@datagrok/curves 1.13.2 → 1.13.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/.turbo/turbo-build.log +5 -7
  2. package/CHANGELOG.md +13 -1
  3. package/README.md +2 -2
  4. package/bdd/bdd.config.json +1 -0
  5. package/bdd/bindings/curves.ts +34 -0
  6. package/bdd/features/MISSING.md +18 -0
  7. package/bdd/features/data/curve-json-columns.feature +66 -0
  8. package/bdd/features/data/pzfx-files.feature +25 -0
  9. package/bdd/features/grid/curve-cells.feature +55 -0
  10. package/bdd/features/grid/curve-options.feature +52 -0
  11. package/bdd/features/grid/statistic-columns.feature +47 -0
  12. package/bdd/features/guides/INDEX.md +8 -0
  13. package/bdd/features/guides/curves-legend-cells.feature +37 -0
  14. package/bdd/features/guides/curves-legend.feature +42 -0
  15. package/bdd/features/viewers/curves-in-trellis.feature +90 -0
  16. package/bdd/features/viewers/multi-curve-viewer.feature +92 -0
  17. package/bdd/generated/data/curve-json-columns.test.ts +75 -0
  18. package/bdd/generated/data/pzfx-files.test.ts +50 -0
  19. package/bdd/generated/grid/curve-cells.test.ts +67 -0
  20. package/bdd/generated/grid/curve-options.test.ts +66 -0
  21. package/bdd/generated/grid/statistic-columns.test.ts +64 -0
  22. package/bdd/generated/guides/curves-legend-cells.test.ts +47 -0
  23. package/bdd/generated/guides/curves-legend.test.ts +48 -0
  24. package/bdd/generated/viewers/curves-in-trellis.test.ts +98 -0
  25. package/bdd/generated/viewers/multi-curve-viewer.test.ts +103 -0
  26. package/bdd/package.json +1 -0
  27. package/bdd/tsconfig.json +13 -0
  28. package/dist/package-test.js +16 -16
  29. package/dist/package-test.js.map +1 -1
  30. package/dist/package.js +1 -1
  31. package/dist/package.js.map +1 -1
  32. package/package.json +10 -3
  33. package/src/fit/fit-grid-cell-handler.ts +29 -4
  34. package/src/fit/fit-interaction.ts +15 -9
  35. package/src/fit/fit-legend.ts +35 -9
  36. package/src/fit/fit-renderer.ts +24 -9
  37. package/src/fit/multi-curve-viewer.ts +82 -19
  38. package/src/package.g.ts +1 -0
  39. package/src/package.ts +1 -1
  40. package/src/tests/calculated-columns-tests.ts +3 -3
  41. package/src/tests/curve-data.ts +5 -1
  42. package/src/tests/curves-cell-renderer-tests.ts +10 -10
  43. package/src/tests/detector-tests.ts +26 -0
  44. package/src/tests/legend-tests.ts +24 -1
  45. package/src/tests/multi-curve-viewer-tests.ts +90 -17
  46. package/src/tests/panel-renderer-tests.ts +75 -30
  47. package/src/tests/project-tests.ts +30 -12
  48. package/test-console-output-1.log +193 -169
  49. package/test-record-1.mp4 +0 -0
  50. package/webpack.config.js +3 -0
package/package.json CHANGED
@@ -1,14 +1,13 @@
1
1
  {
2
2
  "name": "@datagrok/curves",
3
3
  "friendlyName": "Curves",
4
- "version": "1.13.2",
4
+ "version": "1.13.4",
5
5
  "description": "Curves provides support for fitted curves (such as dose-response curves), including in-grid rendering, storing charts in cells, interactivity, and automatic fitting.",
6
6
  "author": {
7
7
  "name": "Dmytro Kovalyov",
8
8
  "email": "dkovalyov@datagrok.ai"
9
9
  },
10
10
  "dependencies": {
11
- "@datagrok-libraries/test": "1.4.1",
12
11
  "@types/wu": "^2.1.44",
13
12
  "cash-dom": "8.1.5",
14
13
  "datagrok-api": "^1.27.0",
@@ -16,9 +15,17 @@
16
15
  "exceljs": "4.4.0",
17
16
  "jstat": "^1.9.6",
18
17
  "rxjs": "6.6.7",
19
- "@datagrok-libraries/statistics": "^1.12.14",
18
+ "@datagrok-libraries/test": "^1.5.0",
19
+ "@datagrok-libraries/statistics": "^1.12.17",
20
20
  "@datagrok-libraries/utils": "^4.7.9"
21
21
  },
22
+ "overrides": {
23
+ "uuid": "^11.1.1"
24
+ },
25
+ "devDependencies": {
26
+ "@playwright/test": "^1.48.0",
27
+ "@datagrok-libraries/bdd": "^0.1.0"
28
+ },
22
29
  "canEdit": [
23
30
  "Administrators"
24
31
  ],
@@ -20,6 +20,7 @@ import {fitChartDataProperties} from '@datagrok-libraries/statistics/src/fit/fit
20
20
  import {fitSeriesProperties} from '@datagrok-libraries/statistics/src/fit/fit-engine';
21
21
  import {
22
22
  changeCurvesOptions, chartPropertiesFor, normalizeStatisticNames, seriesPropertiesFor, ManipulationLevel,
23
+ MANIPULATION_LEVEL,
23
24
  } from './fit-options';
24
25
 
25
26
  type CurveStatisticParams = {propName: string, seriesNumber: number} | {propName: string, aggrType: string};
@@ -84,6 +85,10 @@ function showWholeList(input: DG.InputBase): DG.InputBase {
84
85
  }
85
86
 
86
87
  export class FitGridCellHandler extends DG.ObjectHandler {
88
+ private levelColumn: WeakRef<any> | null = null;
89
+ private levelRow = -1;
90
+ private manipulationLevel: ManipulationLevel = MANIPULATION_LEVEL.COLUMN;
91
+
87
92
  get type(): string {
88
93
  return 'GridCell';
89
94
  }
@@ -97,15 +102,35 @@ export class FitGridCellHandler extends DG.ObjectHandler {
97
102
  // TODO: add the table for the values on the cell or don't render it at all
98
103
  // TODO: fix the curves demo app
99
104
 
100
- renderProperties(gridCell: DG.GridCell, _context: any = null): HTMLElement {
101
- const acc = ui.accordion('Curves property panel');
105
+ /** The Context Panel rebuilds the panel of a cell it already shows once the current cell settles after a
106
+ * click, and only this input holds the level: starting over would send the next edit to the column. */
107
+ levelInput(gridCell: DG.GridCell): DG.InputBase {
108
+ const cell = gridCell.cell;
109
+ const column = cell.column.dart;
110
+ const row = cell.rowIndex;
111
+ const isLevelCell = () => this.levelColumn?.deref() === column && this.levelRow === row;
112
+ if (!isLevelCell()) {
113
+ this.levelColumn = new WeakRef(column);
114
+ this.levelRow = row;
115
+ this.manipulationLevel = MANIPULATION_LEVEL.COLUMN;
116
+ }
102
117
  // TODO: make just the base ui.input.choice after nullable option is added
103
118
  const switchProperty = DG.Property.js('level', DG.TYPE.STRING, {description: 'Controls the level at which properties will be switched',
104
- defaultValue: 'Column', choices: ['Dataframe', 'Column', 'Cell'], nullable: false});
105
- const switchLevelInput = ui.input.forProperty(switchProperty);
119
+ defaultValue: this.manipulationLevel, choices: ['Dataframe', 'Column', 'Cell'], nullable: false});
120
+ const switchLevelInput = ui.input.forProperty(switchProperty, null,
121
+ {onValueChanged: (v: ManipulationLevel) => {
122
+ if (isLevelCell())
123
+ this.manipulationLevel = v;
124
+ }});
106
125
 
107
126
  // temporarily because input doesn't show the tooltip
108
127
  ui.tooltip.bind(switchLevelInput.captionLabel, 'Controls the level at which properties will be switched');
128
+ return switchLevelInput;
129
+ }
130
+
131
+ renderProperties(gridCell: DG.GridCell, _context: any = null): HTMLElement {
132
+ const acc = ui.accordion('Curves property panel');
133
+ const switchLevelInput = this.levelInput(gridCell);
109
134
 
110
135
  const chartData = getOrCreateParsedChartData(gridCell.cell);
111
136
  const columnChartOptions = getColumnChartOptions(gridCell.cell.column);
@@ -86,20 +86,26 @@ function pointViewport(screenBounds: DG.Rect, data: IFitChartData): Viewport {
86
86
  return new Viewport(getChartBounds(data), dataBox, data.chartOptions?.logX ?? false, data.chartOptions?.logY ?? false);
87
87
  }
88
88
 
89
+ /** What the Context Panel shows for a curve cell: the cell itself, or why its curves cannot be shown. */
90
+ export function contextValue(gridCell: DG.GridCell, data: IFitChartData = getOrCreateParsedChartData(gridCell.cell, false)): any {
91
+ for (const [message, condition] of Object.entries(FitConstants.CONDITION_MAP)) {
92
+ if (condition(data.series))
93
+ return ui.divText(message, {style: {color: 'red'}});
94
+ }
95
+ return gridCell;
96
+ }
97
+
89
98
  export function handleClick(gridCell: DG.GridCell, e: MouseEvent): void {
90
99
  if (!gridCell.cell.value || !gridCell.cell.column)
91
100
  return;
92
101
 
93
102
  const data = getOrCreateParsedChartData(gridCell.cell, false);
94
-
95
- for (const [message, condition] of Object.entries(FitConstants.CONDITION_MAP)) {
96
- if (condition(data.series)) {
97
- grok.shell.o = ui.divText(message, {style: {color: 'red'}});
98
- return;
99
- }
100
- }
101
-
102
- grok.shell.o = gridCell;
103
+ const value = contextValue(gridCell, data);
104
+ // not frozen, as `grok.shell.o =` would: the freeze dropped a click on the next cell within a second,
105
+ // and the Context Panel kept the previous cell's panes
106
+ grok.shell.setCurrentObject(value, false);
107
+ if (value !== gridCell)
108
+ return;
103
109
 
104
110
  const screenBounds = inflateScreenBounds(gridCell.bounds);
105
111
  const viewport = pointViewport(screenBounds, data);
@@ -4,7 +4,7 @@ import * as ui from 'datagrok-api/ui';
4
4
  import {IFitChartData, IFitSeries} from '@datagrok-libraries/statistics/src/fit/fit-curve';
5
5
  import {FitConstants} from '@datagrok-libraries/statistics/src/fit/const';
6
6
  import {ColorType, getSeriesColor} from './render-utils';
7
- import {isLegendShown} from './fit-layout';
7
+ import {isLegendShown, isTitleShown, layoutChart, shownAxesNames} from './fit-layout';
8
8
 
9
9
  /** Whether the curves get named at all: the plot has to have room for it, and it can be turned off. */
10
10
  export function isLegendVisible(data: IFitChartData, screenBounds: DG.Rect): boolean {
@@ -20,13 +20,27 @@ export interface LegendEntry {
20
20
  marker?: DG.MARKER_TYPE;
21
21
  }
22
22
 
23
- interface LegendRow {
23
+ export interface LegendRow {
24
24
  entry: LegendEntry;
25
25
  /** What is drawn, shortened to the width the legend allows itself. */
26
26
  shown: string;
27
27
  box: DG.Rect;
28
28
  }
29
29
 
30
+ /** Where a render put the legend: the plot it was laid out for, its rows, the `+N more` row and the
31
+ * corner, an index into {@link LEGEND_CORNERS}. */
32
+ export interface LegendLayout {
33
+ box: DG.Rect;
34
+ rows: LegendRow[];
35
+ moreBox?: DG.Rect;
36
+ entries: LegendEntry[];
37
+ corner: number;
38
+ whole: boolean;
39
+ }
40
+
41
+ /** The corners in the order {@link chooseLegendCorner} tries them. */
42
+ export const LEGEND_CORNERS = ['top right', 'top left', 'bottom right', 'bottom left'];
43
+
30
44
  const LEGEND_FONT = '11px Roboto, "Roboto Local"';
31
45
  /** The legend annotates the plot, so it may not take more than a corner of it. */
32
46
  const MAX_LEGEND_WIDTH_FRACTION = 0.55;
@@ -53,8 +67,7 @@ export function maxTooltipRows(): number {
53
67
  }
54
68
 
55
69
  let measureCanvas: CanvasRenderingContext2D | undefined;
56
- const lastLayout = new WeakMap<IFitChartData, {box: DG.Rect, rows: LegendRow[], moreBox?: DG.Rect,
57
- entries: LegendEntry[], corner: number, whole: boolean}>();
70
+ const lastLayout = new WeakMap<IFitChartData, LegendLayout>();
58
71
 
59
72
  /** A context of its own, so a row can be measured while hit testing, which has no canvas to draw on. */
60
73
  function measure(text: string): number {
@@ -279,14 +292,27 @@ export function renderLegend(g: CanvasRenderingContext2D, data: IFitChartData, d
279
292
  * when the pointer is on the row counting what did not fit. */
280
293
  export function legendTooltip(data: IFitChartData, dataBox: DG.Rect, x: number,
281
294
  y: number): LegendEntry[] | null {
282
- const last = lastLayout.get(data);
283
- // the same data is drawn in the grid and in the enlarged chart, so the rows only apply to the plot
284
- // they were laid out for
285
- if (!last || Math.round(last.box.x) !== Math.round(dataBox.x) ||
286
- Math.round(last.box.width) !== Math.round(dataBox.width))
295
+ const last = layoutFor(data, dataBox);
296
+ if (!last)
287
297
  return null;
288
298
  if (last.moreBox?.contains(x, y))
289
299
  return last.entries;
290
300
  const row = last.rows.find((r) => r.box.contains(x, y));
291
301
  return row && row.shown !== row.entry.text ? [row.entry] : null;
292
302
  }
303
+
304
+ /** The layout the last render made for the plot in `dataBox`: the same data is drawn in the grid and in
305
+ * the enlarged chart, so the rows only apply to the plot they were laid out for. */
306
+ function layoutFor(data: IFitChartData, dataBox: DG.Rect): LegendLayout | null {
307
+ const last = lastLayout.get(data);
308
+ return last && Math.round(last.box.x) === Math.round(dataBox.x) &&
309
+ Math.round(last.box.width) === Math.round(dataBox.width) ? last : null;
310
+ }
311
+
312
+ /** The legend the last render drew on the chart of `screenBounds`, or null when it drew none there. */
313
+ export function drawnLegend(data: IFitChartData, screenBounds: DG.Rect): LegendLayout | null {
314
+ if (!isLegendVisible(data, screenBounds))
315
+ return null;
316
+ const axesNames = shownAxesNames(screenBounds, data);
317
+ return layoutFor(data, layoutChart(screenBounds, axesNames.x, axesNames.y, isTitleShown(screenBounds, data))[0]);
318
+ }
@@ -31,7 +31,7 @@ import {
31
31
  areAxesLabelsShown, areAxesShown, areDroplineLabelsShown, areDroplinesShown, inflateScreenBounds, isTitleShown,
32
32
  layoutChart, shownAxesNames,
33
33
  } from './fit-layout';
34
- import {handleClick, handleMouseMove, inspectCurve} from './fit-interaction';
34
+ import {contextValue, handleClick, handleMouseMove, inspectCurve} from './fit-interaction';
35
35
 
36
36
  function clamp(value: number, min: number, max: number): number {
37
37
  return Math.min(Math.max(value, min), max);
@@ -133,15 +133,17 @@ export class FitChartCellRenderer extends DG.GridCellRenderer {
133
133
  handleMouseMove(gridCell, e, this);
134
134
  }
135
135
 
136
- /** [fitIdentities] key the fits for a caller with no grid cell; only here are the log options final. */
137
- renderCurves(g: CanvasRenderingContext2D, screenBounds: DG.Rect, data: IFitChartData, gridCell?: DG.GridCell,
138
- fitIdentities?: (string | undefined)[]): void {
139
- g.save();
140
- g.beginPath();
141
- g.rect(screenBounds.x, screenBounds.y, screenBounds.width, screenBounds.height);
142
- g.clip();
136
+ /** Without it the platform replaces the cell with its semantic value once the current cell settles. */
137
+ hasContextValue(gridCell: DG.GridCell): boolean { return !!gridCell.cell.value; }
143
138
 
144
- const isRenderedOnGrid = gridCell?.grid && gridCell?.grid.dart && g.canvas === gridCell?.grid?.canvas; // only use cache for grid, because there is no guarantee that rowIdx will be correct for other places
139
+ async getContextValue(gridCell: DG.GridCell): Promise<any> { return contextValue(gridCell); }
140
+
141
+ /** Where the chart of [data] goes in [screenBounds]: its boxes, the fits, and the data bounds the axes span,
142
+ * which take in the curves as well as the points. [fitIdentities] key the fits for a caller with no grid cell;
143
+ * [canvas] is what the chart is drawn on, the grid's own for the grid's fit cache. */
144
+ layOutChart(screenBounds: DG.Rect, data: IFitChartData, gridCell?: DG.GridCell, fitIdentities?: (string | undefined)[],
145
+ canvas?: HTMLCanvasElement) {
146
+ const isRenderedOnGrid = gridCell?.grid && gridCell?.grid.dart && canvas === gridCell?.grid?.canvas; // only use cache for grid, because there is no guarantee that rowIdx will be correct for other places
145
147
  // a merged series is fitted at index 0, the key real series 0 uses
146
148
  const useFitCache = isRenderedOnGrid && !data.chartOptions?.mergeSeries;
147
149
  const tableCell = gridCell?.cell;
@@ -193,6 +195,19 @@ export class FitChartCellRenderer extends DG.GridCellRenderer {
193
195
  fits.map((fit) => fit?.fitFunc.hasAsymptotes ? fit.curve : null), data.chartOptions);
194
196
 
195
197
  const viewport = new Viewport(dataBounds, dataBox, data.chartOptions?.logX ?? false, data.chartOptions?.logY ?? false);
198
+ return {dataBox, xAxisBox, yAxisBox, dataBounds, fits, chartLogOptions, useFitCache, tableCell, viewport};
199
+ }
200
+
201
+ /** [fitIdentities] key the fits for a caller with no grid cell; only here are the log options final. */
202
+ renderCurves(g: CanvasRenderingContext2D, screenBounds: DG.Rect, data: IFitChartData, gridCell?: DG.GridCell,
203
+ fitIdentities?: (string | undefined)[]): void {
204
+ g.save();
205
+ g.beginPath();
206
+ g.rect(screenBounds.x, screenBounds.y, screenBounds.width, screenBounds.height);
207
+ g.clip();
208
+
209
+ const {dataBox, xAxisBox, yAxisBox, dataBounds, fits, chartLogOptions, useFitCache, tableCell, viewport} =
210
+ this.layOutChart(screenBounds, data, gridCell, fitIdentities, g.canvas);
196
211
  const minSize = Math.min(dataBox.width, dataBox.height);
197
212
  // TODO: make thinner
198
213
  const ratio = minSize > 100 ? 1 : 0.2 + (minSize / 100) * 0.8;
@@ -5,13 +5,16 @@ import * as grok from 'datagrok-api/grok';
5
5
 
6
6
  import {mergeChartOptions, mergeSeries, getOrCreateParsedChartData, mergeProperties, chartDataId} from './fit-chart-data';
7
7
  import {FitChartData, fitChartDataProperties, IFitChartData, IFitChartOptions, IFitSeries} from '@datagrok-libraries/statistics/src/fit/fit-curve';
8
- import {debounce} from 'rxjs/operators';
9
- import {interval, merge} from 'rxjs';
8
+ import {debounce, tap} from 'rxjs/operators';
9
+ import {interval, merge, Observable, Subject} from 'rxjs';
10
10
  import {FitConstants} from '@datagrok-libraries/statistics/src/fit/const';
11
11
  import {FitChartCellRenderer} from './fit-renderer';
12
12
  import {chartTooltip} from './fit-interaction';
13
+ import {drawnLegend, LEGEND_CORNERS} from './fit-legend';
13
14
 
14
15
  const ERROR_CLASS = 'd4-viewer-error';
16
+ /** The properties the viewer tells "set" from "unset" by its field. */
17
+ const FIELD_SET_PROPERTIES = ['logX', 'logY', 'allowXZeroes', 'mergeCellSeries', 'showColumnLabel'];
15
18
 
16
19
  @grok.decorators.viewer({
17
20
  name: 'MultiCurveViewer',
@@ -38,7 +41,14 @@ export class MultiCurveViewer extends DG.JsViewer {
38
41
  allowXZeroes?: boolean;
39
42
  mergeCellSeries?: boolean;
40
43
  showColumnLabel?: boolean;
44
+ private renderPending = false;
45
+ private rendered = new Subject<void>();
41
46
 
47
+ /** Fires after every render - what automation settles on with {@link isRenderPending}. */
48
+ get onRendered(): Observable<void> { return this.rendered; }
49
+
50
+ /** Whether a change of the current, mouse-over or selected rows is waiting for its debounced render. */
51
+ get isRenderPending(): boolean { return this.renderPending; }
42
52
 
43
53
  /** What a trellis plot puts on its control panel. */
44
54
  get trellisProperties(): string[] { return ['mergeColumnSeries', 'logX', 'logY']; }
@@ -69,8 +79,7 @@ export class MultiCurveViewer extends DG.JsViewer {
69
79
  // the grid routes these to the cell renderer; here the viewer owns the canvas and does it itself
70
80
  this.canvas.addEventListener('mousemove', (e: MouseEvent) => {
71
81
  if ((this.data.series?.length ?? 0) > 0 &&
72
- !chartTooltip(this.data, new DG.Rect(0, 0, this.canvas.width, this.canvas.height), e,
73
- {x: e.offsetX, y: e.offsetY}))
82
+ !chartTooltip(this.data, this.chartBounds(), e, {x: e.offsetX, y: e.offsetY}))
74
83
  ui.tooltip.hide();
75
84
  });
76
85
  this.canvas.addEventListener('mouseleave', () => ui.tooltip.hide());
@@ -84,8 +93,14 @@ export class MultiCurveViewer extends DG.JsViewer {
84
93
  this.mergeColumnSeries = this.bool('mergeColumnSeries', false);
85
94
  this.showOutliers = this.bool('showOutliers', true);
86
95
 
87
- for (const p of fitChartDataProperties)
88
- this.addProperty(p.name === 'mergeSeries' ? 'mergeCellSeries' : p.name, p.propertyType, p.defaultValue, {...p.options, showSlider: false});
96
+ for (const p of fitChartDataProperties) {
97
+ const name = p.name === 'mergeSeries' ? 'mergeCellSeries' : p.name;
98
+ const value = this.addProperty(name, p.propertyType, p.defaultValue, {...p.options, showSlider: false});
99
+ // the panel reads the field, so a default the render applies on its own has to be in it: Show Legend
100
+ // read unchecked over a legend that was drawn
101
+ if (value != null && !FIELD_SET_PROPERTIES.includes(name))
102
+ this[name] = value;
103
+ }
89
104
  }
90
105
 
91
106
  static fromChartData(chartData: IFitChartData): MultiCurveViewer {
@@ -107,11 +122,11 @@ export class MultiCurveViewer extends DG.JsViewer {
107
122
 
108
123
  mergeViewerChartOptions(): void {
109
124
  for (const p of fitChartDataProperties) {
110
- const isDefaultValueChanged = ['logX', 'logY', 'allowXZeroes', 'mergeCellSeries', 'showColumnLabel'].includes(p.name === 'mergeSeries' ?
125
+ const isDefaultValueChanged = FIELD_SET_PROPERTIES.includes(p.name === 'mergeSeries' ?
111
126
  'mergeCellSeries' : p.name) ? this[p.name === 'mergeSeries' ? 'mergeCellSeries' : p.name] !== undefined :
112
127
  this.props.get(p.name) !== undefined && this.props.get(p.name) !== p.defaultValue;
113
128
  if (isDefaultValueChanged) {
114
- if (['logX', 'logY', 'allowXZeroes', 'mergeCellSeries', 'showColumnLabel'].includes(p.name === 'mergeSeries' ? 'mergeCellSeries' : p.name))
129
+ if (FIELD_SET_PROPERTIES.includes(p.name === 'mergeSeries' ? 'mergeCellSeries' : p.name))
115
130
  this.data.chartOptions![p.name as keyof IFitChartOptions] = this[p.name];
116
131
  else
117
132
  this.data.chartOptions![p.name as keyof IFitChartOptions] = this.props.get(p.name) as unknown as any;
@@ -210,7 +225,7 @@ export class MultiCurveViewer extends DG.JsViewer {
210
225
  this.props.set('showColumnLabel', this.curvesColumnNames?.length! > 1 as unknown as object);
211
226
  this.showColumnLabel = this.curvesColumnNames?.length! > 1;
212
227
  }
213
- if (['logX', 'logY', 'allowXZeroes', 'mergeCellSeries', 'showColumnLabel'].includes(property?.name === 'mergeSeries' ? 'mergeCellSeries' : property?.name ?? ''))
228
+ if (FIELD_SET_PROPERTIES.includes(property?.name === 'mergeSeries' ? 'mergeCellSeries' : property?.name ?? ''))
214
229
  this[property?.name === 'mergeSeries' ? 'mergeCellSeries' : property?.name ?? ''] = this[property?.name ?? ''];
215
230
  this.applyViewerProperties();
216
231
  this.createChartData();
@@ -224,8 +239,9 @@ export class MultiCurveViewer extends DG.JsViewer {
224
239
  this.curvesColumnNames = [fitCol.name];
225
240
 
226
241
  this.subs.push(merge(...[this.dataFrame.onCurrentCellChanged, ...(grid ? [grid.onCellMouseEnter] : []), this.dataFrame.onSelectionChanged])
227
- .pipe(debounce((_) => interval(50)))
242
+ .pipe(tap(() => this.renderPending = true), debounce((_) => interval(50)))
228
243
  .subscribe((_) => {
244
+ this.renderPending = false;
229
245
  if (this.dataFrame) {
230
246
  this.createChartData();
231
247
  this.render();
@@ -251,17 +267,64 @@ export class MultiCurveViewer extends DG.JsViewer {
251
267
  g.clearRect(0, 0, this.canvas.width, this.canvas.height);
252
268
  this._removeErrorMessage();
253
269
 
254
- if (this.curvesColumnNames?.length === 0) {
270
+ if (this.curvesColumnNames?.length === 0)
255
271
  this._showErrorMessage('The MultiCurveViewer viewer requires a minimum of 1 curves column.');
256
- return;
257
- }
258
- if (this.data?.series?.length === 0) {
272
+ else if (this.data?.series?.length === 0)
259
273
  this._showErrorMessage('No data to show.');
260
- return;
274
+ else {
275
+ // drawn from this very object rather than through a serialized cell, so that hovering can find the
276
+ // legend the render laid out
277
+ new FitChartCellRenderer().renderCurves(g, this.chartBounds(), this.data, undefined, this.fitIdentities);
278
+ }
279
+ this.rendered.next();
280
+ }
281
+
282
+ private chartBounds(): DG.Rect {
283
+ return new DG.Rect(0, 0, this.canvas.width, this.canvas.height);
284
+ }
285
+
286
+ /** What the viewer shows, read off the last render: the curves, and the legend as it was laid out -
287
+ * a hit area per row it drew and one for `+N more`, in CSS pixels of the canvas. */
288
+ getWidgetStatus(): DG.IWidgetStatus {
289
+ const status = super.getWidgetStatus();
290
+ const drawn = this.curvesColumnNames?.length === 0 ? 0 : this.data?.series?.length ?? 0;
291
+ const legend = drawn === 0 ? null : drawnLegend(this.data, this.chartBounds());
292
+ const values: {[name: string]: number | string | boolean} = {...status.values, 'curves': drawn,
293
+ 'legend shown': legend !== null};
294
+ const hitAreas = {...status.hitAreas};
295
+ if (drawn > 0) {
296
+ // the axes as the render lays them out, taking in the curves as well as the points (GROK-20661)
297
+ const bounds = new FitChartCellRenderer().layOutChart(this.chartBounds(), this.data, undefined, this.fitIdentities)
298
+ .dataBounds;
299
+ const num = (x: number) => Number(x.toPrecision(4));
300
+ values['x range'] = `${num(bounds.minX)} .. ${num(bounds.maxX)}`;
301
+ values['y range'] = `${num(bounds.minY)} .. ${num(bounds.maxY)}`;
302
+ // each axis at its own scale: concentrations in molar span 1e-9 .. 1e-5
303
+ const outside = (v: number, min: number, max: number) => {
304
+ const slack = 1e-9 * Math.max(Math.abs(max - min), Math.abs(min), Math.abs(max));
305
+ return v < min - slack || v > max + slack;
306
+ };
307
+ values['points outside the axes'] = (this.data.series ?? []).reduce((n, series) => n + series.points.filter((p) =>
308
+ outside(p.x, bounds.minX, bounds.maxX) || outside(p.y, bounds.minY, bounds.maxY)).length, 0);
309
+ }
310
+ if (legend) {
311
+ const scale = this.canvas.width > 0 ? this.canvas.getBoundingClientRect().width / this.canvas.width : 1;
312
+ const css = (r: DG.Rect) => ({x: r.x * scale, y: r.y * scale, width: r.width * scale, height: r.height * scale});
313
+ const shortened: number[] = [];
314
+ for (const [i, row] of legend.rows.entries()) {
315
+ const whole = row.shown === row.entry.text;
316
+ hitAreas[`${whole ? '' : 'shortened '}legend row ${i + 1}`] = css(row.box);
317
+ values[`legend row ${i + 1}`] = row.shown;
318
+ if (!whole)
319
+ shortened.push(i + 1);
320
+ }
321
+ if (legend.moreBox)
322
+ hitAreas['legend more'] = css(legend.moreBox);
323
+ values['legend corner'] = LEGEND_CORNERS[legend.corner];
324
+ values['legend rows'] = legend.rows.length;
325
+ values['legend shortened rows'] = shortened.join(', ');
326
+ values['legend hidden'] = legend.entries.length - legend.rows.length;
261
327
  }
262
- // drawn from this very object rather than through a serialized cell, so that hovering can find
263
- // the legend the render laid out
264
- const bounds = new DG.Rect(0, 0, this.canvas.width, this.canvas.height);
265
- new FitChartCellRenderer().renderCurves(g, bounds, this.data, undefined, this.fitIdentities);
328
+ return {...status, parts: {...status.parts, canvas: this.canvas}, hitAreas, values};
266
329
  }
267
330
  }
package/src/package.g.ts CHANGED
@@ -70,6 +70,7 @@ export async function dataToCurves(df: DG.DataFrame, concentrationCol: DG.Column
70
70
 
71
71
  //output: dynamic result
72
72
  //top-menu: Data | Curves | Data to Curves
73
+ //meta.requiresTableView: true
73
74
  export async function dataToCurvesTopMenu() {
74
75
  return await PackageFunctions.dataToCurvesTopMenu();
75
76
  }
package/src/package.ts CHANGED
@@ -135,7 +135,7 @@ export class PackageFunctions {
135
135
  );
136
136
  }
137
137
 
138
- @grok.decorators.func({'top-menu': 'Data | Curves | Data to Curves', 'outputs': [{'name': 'result', 'type': 'dynamic'}]})
138
+ @grok.decorators.func({'top-menu': 'Data | Curves | Data to Curves', 'requiresTableView': true, 'outputs': [{'name': 'result', 'type': 'dynamic'}]})
139
139
  static async dataToCurvesTopMenu() {
140
140
  dataToCurvesUI();
141
141
  }
@@ -1,7 +1,7 @@
1
1
  /* eslint-disable max-len */
2
2
  import * as DG from 'datagrok-api/dg';
3
3
 
4
- import {category, test, expect, expectArray, expectFloat, awaitCheck} from '@datagrok-libraries/test/src/test';
4
+ import {category, test, expect, expectArray, expectFloat, waitUntil} from '@datagrok-libraries/test/src/test';
5
5
  import {FitConstants} from '@datagrok-libraries/statistics/src/fit/const';
6
6
  import {IFitChartData} from '@datagrok-libraries/statistics/src/fit/fit-curve';
7
7
  import {getStatistic} from '@datagrok-libraries/statistics/src/fit/fit-engine';
@@ -114,7 +114,7 @@ category('calculated columns', () => {
114
114
 
115
115
  // an unstable result name, or reading through column.dataFrame, leaves this silently stale
116
116
  df.col('curve')!.set(1, curveJson(-5.0), true);
117
- await awaitCheck(() => df.col('curve 1 ic50')!.get(1) !== before,
117
+ await waitUntil(() => df.col('curve 1 ic50')!.get(1) !== before,
118
118
  'statistic column did not recalculate after the source curve changed', 5000);
119
119
 
120
120
  expectFloat(Math.log10(df.col('curve 1 ic50')!.get(1)), -5.0, 0.3);
@@ -194,7 +194,7 @@ category('calculated columns', () => {
194
194
  const before = df.col('curve 1 ic50')!.get(1);
195
195
 
196
196
  df.col('curve')!.set(1, curveJsonNoChartOptions(-5.0), true);
197
- await awaitCheck(() => df.col('curve 1 ic50')!.get(1) !== before,
197
+ await waitUntil(() => df.col('curve 1 ic50')!.get(1) !== before,
198
198
  'statistic column did not recalculate', 5000);
199
199
 
200
200
  // the detached recalculation column has no dataframe, so it must read logX off its own tags
@@ -15,7 +15,12 @@ export function renderedRows(json: string, name: string, width: number = 400, he
15
15
  col.semType = FitConstants.FIT_SEM_TYPE;
16
16
  const df = DG.DataFrame.fromColumns([col]);
17
17
  df.name = name;
18
+ return renderedDataRows(getOrCreateParsedChartData(df.cell(0, 'curve')), width, height);
19
+ }
18
20
 
21
+ /** {@link renderedRows} of chart data already parsed, the options of its levels merged in. */
22
+ export function renderedDataRows(data: IFitChartData, width: number = 400, height: number = 300):
23
+ {rows: {text: string, x: number, y: number}[], data: IFitChartData, dataBox: DG.Rect} {
19
24
  const rows: {text: string, x: number, y: number}[] = [];
20
25
  const g = ui.canvas(width, height).getContext('2d')!;
21
26
  const fillText = g.fillText.bind(g);
@@ -25,7 +30,6 @@ export function renderedRows(json: string, name: string, width: number = 400, he
25
30
  }) as any;
26
31
 
27
32
  const rect = new DG.Rect(0, 0, width, height);
28
- const data = getOrCreateParsedChartData(df.cell(0, 'curve'));
29
33
  new FitChartCellRenderer().renderCurves(g, rect, data);
30
34
  const axesNames = shownAxesNames(rect, data);
31
35
  const dataBox = layoutChart(rect, axesNames.x, axesNames.y, isTitleShown(rect, data))[0];
@@ -5,7 +5,7 @@ import * as ui from 'datagrok-api/ui';
5
5
 
6
6
  import wu from 'wu';
7
7
  import {createSigmoidPoints, createDemoDataFrame} from '../fit/fit-demo';
8
- import {category, test, delay} from '@datagrok-libraries/test/src/test';
8
+ import {category, test, settled} from '@datagrok-libraries/test/src/test';
9
9
  import {FitChartCellRenderer} from '../fit/fit-renderer';
10
10
  import {IFitChartData} from '@datagrok-libraries/statistics/src/fit/fit-curve';
11
11
  import {FitConstants} from '@datagrok-libraries/statistics/src/fit/const';
@@ -36,10 +36,10 @@ chartData.series![0] = {
36
36
  return chartData;
37
37
  }
38
38
 
39
- export async function scrollTable(el: HTMLElement, delta: number, cycles: number, secDelay: number) {
39
+ export async function scrollTable(grid: DG.Grid, el: HTMLElement, delta: number, cycles: number) {
40
40
  for (let i = 0; i < cycles; i++) {
41
41
  el.dispatchEvent(new WheelEvent('wheel', {deltaY: delta}));
42
- await delay(secDelay);
42
+ await settled(grid);
43
43
  }
44
44
  }
45
45
 
@@ -68,7 +68,7 @@ category('rendering', () => {
68
68
  test('rendering same fitChartData on canvas', async () => {
69
69
  const canvasWidth = 160;
70
70
  const canvasHeight = 120;
71
- const renderingTimesAmount = 1000;
71
+ const renderingTimesAmount = DG.Test.isInBenchmark ? 1000 : 100;
72
72
 
73
73
  const canvas = ui.canvas(canvasWidth, canvasHeight);
74
74
  grok.shell.newView('canvas', [canvas]);
@@ -89,7 +89,7 @@ category('rendering', () => {
89
89
  test('rendering different fitChartData on canvas', async () => {
90
90
  const canvasWidth = 160;
91
91
  const canvasHeight = 120;
92
- const renderingTimesAmount = 1000;
92
+ const renderingTimesAmount = DG.Test.isInBenchmark ? 1000 : 100;
93
93
 
94
94
  const canvas = ui.canvas(canvasWidth, canvasHeight);
95
95
  grok.shell.newView('canvas', [canvas]);
@@ -114,14 +114,14 @@ category('rendering', () => {
114
114
  const scrollCycles = 10;
115
115
  const scrollDeltaPlus = 300;
116
116
  const scrollDeltaMinus = -300;
117
- await delay(100);
117
+ await settled(tv.grid);
118
118
  const canvas = tv.grid.root.getElementsByTagName('canvas')[2];
119
119
  const func = async (chartData?: IFitChartData | null) => {
120
- await scrollTable(canvas, scrollDeltaPlus, scrollCycles, 1);
121
- await scrollTable(canvas, scrollDeltaMinus, scrollCycles, 1);
122
- await scrollTable(canvas, scrollDeltaPlus, scrollCycles, 1);
120
+ await scrollTable(tv.grid, canvas, scrollDeltaPlus, scrollCycles);
121
+ await scrollTable(tv.grid, canvas, scrollDeltaMinus, scrollCycles);
122
+ await scrollTable(tv.grid, canvas, scrollDeltaPlus, scrollCycles);
123
123
  };
124
- const time = await getTime(func, null) - 30;
124
+ const time = await getTime(func, null);
125
125
  console.log(`curves rendering took ${time} ms`);
126
126
  return time;
127
127
  }, {benchmark: true});
@@ -70,4 +70,30 @@ category('detectors', () => {
70
70
  expect(col.semType, FitConstants.FIT_SEM_TYPE);
71
71
  expect(col.getTag(FitConstants.TAG_CURVE_FORMAT), 'pzfx');
72
72
  });
73
+
74
+ test('curve JSON needs only series with points', async () => {
75
+ // GROK-18073: no fit function and no colors, the way a formula returning curve JSON gives it
76
+ const json = JSON.stringify({series: [{points: [{x: 0.1, y: 1}, {x: 1, y: 5}, {x: 10, y: 9}]}]});
77
+ const df = DG.DataFrame.fromColumns([DG.Column.fromStrings('curvecol', [json, json])]);
78
+ await grok.data.detectSemanticTypes(df);
79
+ expect(df.col('curvecol')!.semType, FitConstants.FIT_SEM_TYPE);
80
+ });
81
+
82
+ test('curve columns come back whole and detected from an exported CSV', async () => {
83
+ // GROK-17312, public#3215: the curve JSON of an exported CSV came back cropped
84
+ const df = await grok.dapi.files.readCsv('System:AppData/Curves/curves-demo.csv');
85
+ await grok.data.detectSemanticTypes(df);
86
+ const curveColumns = df.columns.bySemTypeAll(FitConstants.FIT_SEM_TYPE).map((c) => c.name);
87
+ expect(curveColumns.length, 5, `the demo has five curve columns, found ${curveColumns}`);
88
+
89
+ const reopened = DG.DataFrame.fromCsv(df.toCsv());
90
+ await grok.data.detectSemanticTypes(reopened);
91
+ expect(reopened.rowCount, df.rowCount);
92
+ expect(reopened.columns.names().join(', '), df.columns.names().join(', '));
93
+ for (const name of curveColumns) {
94
+ expect(reopened.col(name)!.semType, FitConstants.FIT_SEM_TYPE, `${name} is not a curve column again`);
95
+ for (let i = 0; i < df.rowCount; i++)
96
+ expect(reopened.get(name, i), df.get(name, i), `${name} changed in row ${i}`);
97
+ }
98
+ });
73
99
  });
@@ -3,9 +3,12 @@ import * as ui from 'datagrok-api/ui';
3
3
 
4
4
  import {category, test, expect, expectArray} from '@datagrok-libraries/test/src/test';
5
5
  import {IFitChartData} from '@datagrok-libraries/statistics/src/fit/fit-curve';
6
+ import {FitConstants} from '@datagrok-libraries/statistics/src/fit/const';
6
7
  import {chooseLegendCorner, legendEntries, legendTooltip, legendTooltipElement, maxTooltipRows} from '../fit/fit-legend';
8
+ import {getOrCreateParsedChartData} from '../fit/fit-chart-data';
9
+ import {changeCurvesOptions} from '../fit/fit-options';
7
10
 
8
- import {sigmoidPoints, renderedTexts, renderedRows} from './curve-data';
11
+ import {sigmoidPoints, renderedTexts, renderedRows, renderedDataRows} from './curve-data';
9
12
 
10
13
  /** Curves spread over several columns, the way the multi curve viewer hands them over. */
11
14
  function multiColumnJson(columns: {column: string, series: string[]}[], showColumnLabel: boolean = true): string {
@@ -177,6 +180,26 @@ category('legend', () => {
177
180
  expect(off.some((t) => t === 'Conc.' || t === 'Activity' || t.length > 0), true);
178
181
  });
179
182
 
183
+ test('Show Legend set for the column names no curve, set for one cell names that one again', async () => {
184
+ const json = multiColumnJson([{column: 'curve', series: ['Run:2023-08-08']}], false);
185
+ const col = DG.Column.fromStrings('curve', [json, json]);
186
+ col.semType = FitConstants.FIT_SEM_TYPE;
187
+ const df = DG.DataFrame.fromColumns([col]);
188
+ df.name = 'legendLevels';
189
+ const grid = DG.Viewer.grid(df);
190
+ const showLegend = (value: boolean) => ({property: {name: 'showLegend'}, value: value}) as unknown as DG.InputBase;
191
+ const named = (row: number) => renderedDataRows(getOrCreateParsedChartData(df.cell(row, 'curve')), 500, 400)
192
+ .rows.some((r) => r.text === 'Run:2023-08-08');
193
+ expect(named(0) && named(1), true, 'every cell names its curve to begin with');
194
+
195
+ changeCurvesOptions(grid.cell('curve', 0), showLegend(false), 'chartOptions', 'Column');
196
+ expect(named(0) || named(1), false, 'off for the column, no cell names its curve');
197
+
198
+ changeCurvesOptions(grid.cell('curve', 1), showLegend(true), 'chartOptions', 'Cell');
199
+ expect(named(1), true, 'on for one cell, that cell names its curve');
200
+ expect(named(0), false, 'and the rest of the column stays as the column says');
201
+ });
202
+
180
203
  test('hovering what did not fit gives the whole legend', async () => {
181
204
  const names = Array.from({length: 40}, (_, i) => `series ${i}`);
182
205
  const drawn = renderedRows(multiColumnJson([{column: 'curve', series: names}]), 'legendMoreHover', 500, 400);