Skip to content

Commit

Permalink
refactor(subject previews): allow for single series JSON data subjects
Browse files Browse the repository at this point in the history
Refactor previews for JSON data subjects to include subjects with a single `x,y` data series. `getDatasets(data)` reflects on the type of data, then calls an appropriate helper function to convert `data` into an array of `chart.js` datasets.
  • Loading branch information
eatyourgreens committed Jun 6, 2024
1 parent 1ca8532 commit db27228
Showing 1 changed file with 34 additions and 18 deletions.
52 changes: 34 additions & 18 deletions app/features/modelling/line-plot/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,37 @@
import { Chart } from 'chart.js/auto';

function getXYData(data) {
return {
data: data.x.map((x, index) => ({ x, y: data.y[index] })),
pointStyle: 'circle',
backgroundColor: '#ffffff',
borderColor: '#000000'
}
}

function getSeriesData(series, index) {
const { seriesData, seriesOptions } = series;
return {
data: seriesData,
label: seriesOptions.label || `Series ${index + 1}`,
pointStyle: seriesOptions.glyph,
backgroundColor: seriesOptions.color,
borderColor: '#000000'
};
}

function getDatasets(data) {
if (data?.datasets) {
return data.datasets;
}
if (data?.map) {
return data.map(getSeriesData);
}
if (data.x && data.y) {
return [getXYData(data)];
}
}

// Help at http://www.chartjs.org/docs/latest
class LinePlotModel {
constructor(canvas, { frame, src }, { onLoad, modelDidError }) {
Expand All @@ -8,24 +40,8 @@ class LinePlotModel {
this.frame = frame;
fetch(`${src}?=`)
.then(response => response.json())
.then((data) => {
let datasets;
const { chartOptions, data: FEMdata, ...rest } = data;
if (FEMdata) {
datasets = FEMdata.map( (data, index) => {
const { seriesData, seriesOptions } = data
return {
data: seriesData,
label: seriesOptions.label || `Series ${index + 1}`,
pointStyle: seriesOptions.glyph,
backgroundColor: seriesOptions.color,
borderColor: '#000000'
}
});
}
if (data.datasets) {
datasets = data.datasets
}
.then(({ data, chartOptions, ...rest }) => {
const datasets = getDatasets(data);
console.log({
type: 'scatter',
data: {
Expand Down

0 comments on commit db27228

Please sign in to comment.