@datagrok/compute 0.2.6 → 0.4.0

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.
@@ -0,0 +1,442 @@
1
+ import * as grok from 'datagrok-api/grok';
2
+ import * as ui from 'datagrok-api/ui';
3
+ import * as DG from 'datagrok-api/dg';
4
+ import CodeMirror from 'codemirror';
5
+ import {_package} from '../package';
6
+
7
+ const enum FUNC_PROPS_FIELDS {
8
+ NAME = 'name',
9
+ DESCRIPTION = 'description',
10
+ LANGUAGE = 'language',
11
+ HELP_URL = 'helpUrl',
12
+ REFERENCE = 'reference',
13
+ LOGIN = 'author?.login',
14
+ SAMPLE = 'sample',
15
+ ENVIRONMENT = 'environment',
16
+ TAGS = 'tags'
17
+ };
18
+
19
+ const obligatoryFuncProps = ['name', 'description', 'helpUrl', 'language'];
20
+
21
+ const functionPropsLabels = (key: FUNC_PROPS_FIELDS) => {
22
+ switch (key) {
23
+ case FUNC_PROPS_FIELDS.NAME: return 'Name';
24
+ case FUNC_PROPS_FIELDS.DESCRIPTION: return 'Description';
25
+ case FUNC_PROPS_FIELDS.LOGIN: return 'Author';
26
+ case FUNC_PROPS_FIELDS.HELP_URL: return 'Help URL';
27
+ case FUNC_PROPS_FIELDS.LANGUAGE: return 'Language';
28
+ case FUNC_PROPS_FIELDS.REFERENCE: return 'Reference';
29
+ case FUNC_PROPS_FIELDS.SAMPLE: return 'Sample';
30
+ case FUNC_PROPS_FIELDS.ENVIRONMENT: return 'Environment';
31
+ case FUNC_PROPS_FIELDS.TAGS: return 'Tags';
32
+ }
33
+ };
34
+
35
+ const functionPropsCode = (key: FUNC_PROPS_FIELDS) => {
36
+ switch (key) {
37
+ case FUNC_PROPS_FIELDS.NAME: return 'name';
38
+ case FUNC_PROPS_FIELDS.DESCRIPTION: return 'description';
39
+ case FUNC_PROPS_FIELDS.LOGIN: return 'author';
40
+ case FUNC_PROPS_FIELDS.HELP_URL: return 'helpUrl';
41
+ case FUNC_PROPS_FIELDS.LANGUAGE: return 'language';
42
+ case FUNC_PROPS_FIELDS.REFERENCE: return 'reference';
43
+ case FUNC_PROPS_FIELDS.SAMPLE: return 'sample';
44
+ case FUNC_PROPS_FIELDS.ENVIRONMENT: return 'environment';
45
+ case FUNC_PROPS_FIELDS.TAGS: return 'tags';
46
+ }
47
+ };
48
+
49
+ type FuncPropsState = {
50
+ [FUNC_PROPS_FIELDS.NAME]: string | null,
51
+ [FUNC_PROPS_FIELDS.DESCRIPTION]: string | null,
52
+ [FUNC_PROPS_FIELDS.LANGUAGE]: string | null,
53
+ [FUNC_PROPS_FIELDS.HELP_URL]: string | null,
54
+ [FUNC_PROPS_FIELDS.REFERENCE]: string | null,
55
+ [FUNC_PROPS_FIELDS.LOGIN]: string | null,
56
+ [FUNC_PROPS_FIELDS.SAMPLE]: string | null,
57
+ [FUNC_PROPS_FIELDS.ENVIRONMENT]: string | null,
58
+ [FUNC_PROPS_FIELDS.TAGS]: string | null,
59
+ }
60
+
61
+ const funcParamTypes = [
62
+ DG.TYPE.BOOL,
63
+ DG.TYPE.COLUMN_LIST,
64
+ DG.TYPE.COLUMN,
65
+ DG.TYPE.DATA_FRAME,
66
+ DG.TYPE.DATE_TIME,
67
+ DG.TYPE.FLOAT,
68
+ DG.TYPE.GRAPHICS,
69
+ DG.TYPE.INT,
70
+ DG.TYPE.STRING,
71
+ ];
72
+
73
+ const enum FUNC_PARAM_FIELDS {
74
+ DIRECTION = 'direction',
75
+ TYPE = 'propertyType',
76
+ NAME = 'name',
77
+ DEFAULT_VALUE = 'defaultValue',
78
+ DESCRIPTION = 'description',
79
+ CATEGORY = 'category',
80
+ };
81
+
82
+ const enum DIRECTION {
83
+ INPUT= 'input',
84
+ OUTPUT= 'output',
85
+ }
86
+
87
+ const functionParamsLabels = (key: FUNC_PARAM_FIELDS) => {
88
+ switch (key) {
89
+ case FUNC_PARAM_FIELDS.DIRECTION: return 'Direction';
90
+ case FUNC_PARAM_FIELDS.TYPE: return 'Type';
91
+ case FUNC_PARAM_FIELDS.NAME: return 'Name';
92
+ case FUNC_PARAM_FIELDS.DEFAULT_VALUE: return 'Default value';
93
+ case FUNC_PARAM_FIELDS.DESCRIPTION: return 'Description';
94
+ case FUNC_PARAM_FIELDS.CATEGORY: return 'Category';
95
+ }
96
+ };
97
+
98
+ export function _functionEditor(functionCode: string) {
99
+ const inputScript = DG.Script.create(functionCode);
100
+
101
+ const editorView = DG.View.create();
102
+ editorView.name = 'Function Editor';
103
+
104
+ const functionPropsCopy: FuncPropsState = {
105
+ [FUNC_PROPS_FIELDS.NAME]: inputScript.name || null,
106
+ [FUNC_PROPS_FIELDS.DESCRIPTION]: inputScript.description || null,
107
+ [FUNC_PROPS_FIELDS.LANGUAGE]: inputScript.language || null,
108
+ [FUNC_PROPS_FIELDS.HELP_URL]: inputScript.helpUrl || null,
109
+ [FUNC_PROPS_FIELDS.REFERENCE]: inputScript.reference || null,
110
+ [FUNC_PROPS_FIELDS.LOGIN]: inputScript.author?.login || null,
111
+ [FUNC_PROPS_FIELDS.SAMPLE]: inputScript.sample || null,
112
+ [FUNC_PROPS_FIELDS.ENVIRONMENT]: inputScript.environment || null,
113
+ [FUNC_PROPS_FIELDS.TAGS]: inputScript.tags?.join(' ') || null,
114
+ };
115
+
116
+ const getNewProps = () => {
117
+ const newProps = [];
118
+ for (const key of Object.keys(functionPropsCopy)) {
119
+ if (functionPropsCopy[key as keyof FuncPropsState] == null) {
120
+ newProps.push(key);
121
+ }
122
+ }
123
+ return newProps;
124
+ };
125
+
126
+ let addButton = ui.div();
127
+ let propsForm = ui.div();
128
+ let inputs = ui.div();
129
+
130
+ const renderAddPropButton = () => {
131
+ if (!getNewProps().length) return ui.div();
132
+
133
+ const onItemClick = (item: string) => {
134
+ functionPropsCopy[item as keyof FuncPropsState] = '';
135
+ const newInputs = ui.inputs(
136
+ Object.keys(functionPropsCopy)
137
+ .filter((prop) => functionPropsCopy[prop as keyof FuncPropsState] !== null)
138
+ .map((prop) => addFullWidthInput(
139
+ ui.stringInput(
140
+ functionPropsLabels(prop as keyof FuncPropsState),
141
+ functionPropsCopy[prop as keyof FuncPropsState] || ''), prop,
142
+ )),
143
+ );
144
+ inputs.replaceWith(newInputs);
145
+ inputs = newInputs;
146
+ refreshPreview();
147
+ const newAddButton = renderAddPropButton();
148
+ addButton.replaceWith(newAddButton);
149
+ addButton = newAddButton;
150
+ };
151
+ const menu = DG.Menu.popup().items(getNewProps(), onItemClick);
152
+
153
+ const shevron = ui.iconFA('chevron-down');
154
+ const button = ui.button([ui.icons.add(()=>{}), shevron], () => {
155
+ menu.show();
156
+ });
157
+
158
+ const div = ui.div([button]);
159
+ div.style.cssText += 'margin-left: 152px';
160
+ return div;
161
+ };
162
+
163
+ const addFullWidthInput = (input: DG.InputBase, propName: string) => {
164
+ (input.root.lastChild as HTMLElement).style.cssText+='width: 400px; max-width: inherit;';
165
+ input.onInput(() => {
166
+ functionPropsCopy[propName as keyof typeof functionPropsCopy] = input.stringValue;
167
+ refreshPreview();
168
+ });
169
+ (input.root as HTMLInputElement).placeholder = 'Enter your value...';
170
+ input.root.append(ui.button(ui.icons.delete(()=>{}), () => {
171
+ functionPropsCopy[propName as keyof typeof functionPropsCopy] = null;
172
+ refreshPreview();
173
+ input.root.remove();
174
+ const newAddButton = renderAddPropButton();
175
+ addButton.replaceWith(newAddButton);
176
+ addButton = newAddButton;
177
+ }));
178
+ (input.root.lastChild as HTMLElement).style.cssText+='display: inline-flex; justify-content: center; flex-direction: column';
179
+ if (obligatoryFuncProps.includes(propName)) {
180
+ input.root.style.cssText += 'padding-right: 35.375px';
181
+ (input.root.lastChild as HTMLElement).style.cssText+='display: none;';
182
+ }
183
+ return input;
184
+ };
185
+
186
+ const functionPropsForm = () => {
187
+ addButton = renderAddPropButton();
188
+
189
+ inputs = ui.inputs(
190
+ Object.keys(functionPropsCopy)
191
+ .filter((prop) => !!functionPropsCopy[prop as keyof FuncPropsState])
192
+ .map((prop) => addFullWidthInput(
193
+ ui.stringInput(
194
+ functionPropsLabels(prop as keyof FuncPropsState),
195
+ functionPropsCopy[prop as keyof FuncPropsState] || ''), prop,
196
+ )),
197
+ );
198
+ return ui.panel([
199
+ ui.divV([
200
+ inputs,
201
+ addButton,
202
+ ]),
203
+ ]);
204
+ };
205
+
206
+ let functionInputParamsCopy = inputScript.inputs;
207
+ let functionOutputParamsCopy = inputScript.outputs;
208
+
209
+ const iconsByTypes = (type: DG.TYPE) => {
210
+ switch (type) {
211
+ case DG.TYPE.BOOL: return ui.iconImage(DG.TYPE.BOOL, `${_package.webRoot}/icons/Bool.svg`);
212
+ case DG.TYPE.COLUMN_LIST: return ui.iconImage(DG.TYPE.BOOL, `${_package.webRoot}/icons/Column-list.svg`);
213
+ case DG.TYPE.COLUMN: return ui.iconImage(DG.TYPE.COLUMN, `${_package.webRoot}/icons/Column.svg`);
214
+ case DG.TYPE.DATA_FRAME: return ui.iconImage(DG.TYPE.DATA_FRAME, `${_package.webRoot}/icons/Dataframe.svg`);
215
+ case DG.TYPE.DATE_TIME: return ui.iconImage(DG.TYPE.COLUMN, `${_package.webRoot}/icons/Datetime.svg`);
216
+ case DG.TYPE.FLOAT: return ui.iconImage(DG.TYPE.FLOAT, `${_package.webRoot}/icons/Double.svg`);
217
+ case DG.TYPE.GRAPHICS: return ui.iconImage(DG.TYPE.GRAPHICS, `${_package.webRoot}/icons/Graphics.svg`);
218
+ case DG.TYPE.INT: return ui.iconImage(DG.TYPE.FLOAT, `${_package.webRoot}/icons/Int.svg`);
219
+ case DG.TYPE.STRING: return ui.iconImage(DG.TYPE.STRING, `${_package.webRoot}/icons/String.svg`);
220
+ default: return ui.iconImage('Blob', `${_package.webRoot}/icons/Blob.svg`);
221
+ }
222
+ };
223
+
224
+ const onFunctionParamClick = (paramName: string, card: HTMLElement, direction: DIRECTION) => {
225
+ const acc = ui.accordion();
226
+ acc.root.style.cssText += 'min-width: 400px';
227
+
228
+ acc.addPane('General', ()=> {
229
+ let paramIndex: number;
230
+ let param: DG.Property;
231
+
232
+ if (direction === DIRECTION.INPUT) {
233
+ paramIndex = functionInputParamsCopy.findIndex((input) => input.name === paramName);
234
+ param = functionInputParamsCopy[paramIndex];
235
+ } else {
236
+ paramIndex= functionOutputParamsCopy.findIndex((input) => input.name === paramName);
237
+ param = functionOutputParamsCopy[paramIndex];
238
+ }
239
+
240
+ if (!param) return ui.div('');
241
+
242
+ const updateCard = (propName: string, v: any) => {
243
+ (param as any)[propName] = v;
244
+ const newCard = renderCard(param, direction);
245
+ card.replaceWith(newCard);
246
+ card = newCard;
247
+ refreshPreview();
248
+ };
249
+
250
+ const funcParams: DG.Property[] = [
251
+ (() => {
252
+ const temp = DG.Property.create(FUNC_PARAM_FIELDS.DIRECTION, DG.TYPE.STRING, (x: any) => x[FUNC_PARAM_FIELDS.DIRECTION], (x: any, v) => updateCard(FUNC_PARAM_FIELDS.DIRECTION, v), '');
253
+ temp.options({choices: ['input', 'output']});
254
+ return temp;
255
+ })(),
256
+ (() => {
257
+ const temp = DG.Property.create(FUNC_PARAM_FIELDS.TYPE, DG.TYPE.STRING, (x: any) => x[FUNC_PARAM_FIELDS.TYPE], (x: any, v) => updateCard(FUNC_PARAM_FIELDS.TYPE, v), '');
258
+ temp.options({choices: funcParamTypes});
259
+ return temp;
260
+ })(),
261
+ DG.Property.create(FUNC_PARAM_FIELDS.NAME, DG.TYPE.STRING, (x: any) => x[FUNC_PARAM_FIELDS.NAME], (x: any, v) => updateCard(FUNC_PARAM_FIELDS.NAME, v), ''),
262
+ DG.Property.create(FUNC_PARAM_FIELDS.DEFAULT_VALUE, DG.TYPE.STRING, (x: any) => x[FUNC_PARAM_FIELDS.DEFAULT_VALUE], (x: any, v) => updateCard(FUNC_PARAM_FIELDS.DEFAULT_VALUE, v), ''),
263
+ (() => {
264
+ const temp = DG.Property.create(FUNC_PARAM_FIELDS.DESCRIPTION, DG.TYPE.STRING, (x: any) => x[FUNC_PARAM_FIELDS.DESCRIPTION], (x: any, v) => updateCard(FUNC_PARAM_FIELDS.DESCRIPTION, v), '');
265
+ temp.options({editor: 'textarea'});
266
+ return temp;
267
+ })(),
268
+ DG.Property.create(FUNC_PARAM_FIELDS.CATEGORY, DG.TYPE.STRING, (x: any) => x[FUNC_PARAM_FIELDS.CATEGORY], (x: any, v) => updateCard(FUNC_PARAM_FIELDS.CATEGORY, v), ''),
269
+ ];
270
+
271
+ const paramProps = funcParams
272
+ .filter((param) => param.name !== FUNC_PARAM_FIELDS.DIRECTION);
273
+
274
+ const result = ui.input.form(param, paramProps);
275
+
276
+ return ui.div(result);
277
+ });
278
+
279
+ acc.addPane('Connections', ()=> {
280
+ return ui.div();
281
+ });
282
+
283
+ acc.addPane('Viewers', ()=> {
284
+ return ui.div();
285
+ });
286
+
287
+
288
+ grok.shell.o = ui.divV([ui.h1(`Param: ${paramName}`), acc.root]);
289
+ };
290
+
291
+ const funcParams: DG.Property[] = [
292
+ DG.Property.jsString(FUNC_PARAM_FIELDS.DIRECTION),
293
+ DG.Property.jsString(FUNC_PARAM_FIELDS.TYPE),
294
+ DG.Property.jsString(FUNC_PARAM_FIELDS.NAME),
295
+ DG.Property.jsString(FUNC_PARAM_FIELDS.DEFAULT_VALUE),
296
+ DG.Property.jsString(FUNC_PARAM_FIELDS.DESCRIPTION),
297
+ DG.Property.jsString(FUNC_PARAM_FIELDS.CATEGORY),
298
+ ];
299
+
300
+
301
+ const renderCard = (functionParam: DG.Property, direction: DIRECTION) => {
302
+ const iconStyle = {style: {
303
+ 'display': 'flex',
304
+ 'flex-direction': 'column',
305
+ 'justify-content': 'center',
306
+ 'width': '32.5px',
307
+ 'align-items': 'center',
308
+ }};
309
+
310
+ const editButtonDiv = ui.div(ui.button(ui.icons.edit(()=>{}), () =>{
311
+ onFunctionParamClick(functionParam.name, tempCard, direction);
312
+ }), {
313
+ style: {
314
+ ...iconStyle.style,
315
+ 'visibility': 'hidden',
316
+ },
317
+ });
318
+
319
+ const tempCard = ui.divH([
320
+ ui.div(iconsByTypes(functionParam.propertyType), iconStyle),
321
+ ui.divV([
322
+ ui.span([functionParam.name], {style: {'font-weight': 'bold'}}),
323
+ ui.span([funcParams
324
+ .filter((param) => param.name !== FUNC_PARAM_FIELDS.NAME)
325
+ .map((param) => (functionParam as any)[param.name])
326
+ .filter((paramValue) => !!paramValue).join(' | '),
327
+ ]),
328
+ ], {style: {'width': '100%', 'padding': '5px'}}),
329
+ editButtonDiv,
330
+ ui.div(ui.button(ui.icons.delete(()=>{}), () =>{
331
+ if (direction === DIRECTION.INPUT) {
332
+ functionInputParamsCopy = functionInputParamsCopy.filter((param) => param !== functionParam);
333
+ } else {
334
+ functionOutputParamsCopy = functionOutputParamsCopy.filter((param) => param !== functionParam);
335
+ }
336
+ refreshPreview();
337
+ tempCard.remove();
338
+ }), iconStyle),
339
+ ], {style: {'border-bottom': 'thin solid #ECEFF2'}});
340
+ tempCard.addEventListener('click', () => onFunctionParamClick(functionParam.name, tempCard, direction));
341
+ tempCard.addEventListener('mouseover', () => editButtonDiv.style.visibility = 'visible');
342
+ tempCard.addEventListener('mouseout', () => editButtonDiv.style.visibility = 'hidden');
343
+ return tempCard;
344
+ };
345
+
346
+ let inputParamCards = ui.divV(
347
+ functionInputParamsCopy.map((functionParam) => renderCard(functionParam, DIRECTION.INPUT)),
348
+ );
349
+ const outputParamCards = ui.divV(
350
+ functionOutputParamsCopy.map((functionParam) => renderCard(functionParam, DIRECTION.OUTPUT)),
351
+ );
352
+
353
+ const area = ui.textInput('', '');
354
+ const myCM = CodeMirror.fromTextArea((area.input as HTMLTextAreaElement), {});
355
+
356
+ const previewDiv = ui.divV([ui.h1('Code preview'), area]);
357
+ previewDiv.style.flexGrow = '1';
358
+
359
+ propsForm = functionPropsForm();
360
+
361
+ const renderAddParamButton = () => {
362
+ const paramProps = funcParams
363
+ .filter((param) => param.name !== FUNC_PARAM_FIELDS.DIRECTION);
364
+
365
+ const newParam: DG.PropertyOptions = {};
366
+
367
+ const onItemClick = () => {
368
+ ui.dialog('Add parameter')
369
+ .add(ui.input.form(newParam, paramProps))
370
+ .onOK(() => {
371
+ functionInputParamsCopy.push(DG.Property.fromOptions(newParam));
372
+ const newInputParamsCards = ui.divV(
373
+ functionInputParamsCopy.map((functionParam) => renderCard(functionParam, DIRECTION.INPUT)),
374
+ );
375
+ inputParamCards.replaceWith(newInputParamsCards);
376
+ inputParamCards = newInputParamsCards;
377
+ refreshPreview();
378
+ })
379
+ .show();
380
+ };
381
+
382
+ const menu = DG.Menu.popup().items(funcParamTypes, onItemClick);
383
+
384
+ const shevron = ui.iconFA('chevron-down');
385
+ const button = ui.button([ui.icons.add(()=>{}), shevron], () => {
386
+ menu.show();
387
+ });
388
+
389
+ const div = ui.div([button]);
390
+ return div;
391
+ };
392
+ const addInputButton = renderAddParamButton();
393
+ const addOutputButton = renderAddParamButton();
394
+
395
+ const tabs = ui.tabControl({
396
+ 'PROPERTIES': propsForm,
397
+ 'PARAMETERS': ui.divV([
398
+ ui.div(ui.h1('Input: '), {style: {'padding': '12px 12px 0px 12px'}}),
399
+ inputParamCards,
400
+ addInputButton,
401
+ ui.div(ui.h1('Output: '), {style: {'padding': '12px 12px 0px 12px'}}),
402
+ outputParamCards,
403
+ addOutputButton,
404
+ ]),
405
+ });
406
+ tabs.root.style.width = '100%';
407
+ tabs.root.style.flexGrow = '3';
408
+
409
+ editorView.append(
410
+ ui.divV([
411
+ tabs,
412
+ previewDiv,
413
+ ]),
414
+ );
415
+ editorView.box = true;
416
+ editorView.setRibbonPanels([
417
+ [
418
+ ui.iconFA('eye', () => {
419
+ previewDiv.hidden ? previewDiv.hidden = false : previewDiv.hidden = true;
420
+ }),
421
+ ui.bigButton('Save', () => grok.shell.info('plus')),
422
+ ],
423
+ ]);
424
+
425
+ const refreshPreview = () => {
426
+ let result = '';
427
+ Object.keys(functionPropsCopy).map((propField) => {
428
+ const propValue = functionPropsCopy[propField as keyof FuncPropsState];
429
+ if (propValue) result += `#${functionPropsCode(propField as keyof FuncPropsState)}: ${propValue}\n`;
430
+ });
431
+ functionInputParamsCopy.map((param) => {
432
+ result += `#input: ${param.propertyType} ${param.name}\n`;
433
+ });
434
+ functionOutputParamsCopy.map((param) => {
435
+ result += `#output: ${param.propertyType} ${param.name}\n`;
436
+ });
437
+ myCM.setValue(result);
438
+ };
439
+
440
+ grok.shell.addView(editorView);
441
+ refreshPreview();
442
+ }
@@ -0,0 +1,259 @@
1
+ import * as grok from 'datagrok-api/grok';
2
+ import * as ui from 'datagrok-api/ui';
3
+ import * as DG from 'datagrok-api/dg';
4
+
5
+ export class OutliersSelectionViewer extends DG.JsViewer {
6
+ constructor() {
7
+ super();
8
+ }
9
+
10
+ // override to handle property changes
11
+ onPropertyChanged(prop: any) {
12
+ grok.shell.info(`${prop.name}: ${prop.get(this)}`);
13
+ }
14
+
15
+ onTableAttached() {
16
+ if (this.dataFrame) {
17
+ this.initialRender();
18
+ }
19
+ }
20
+
21
+ render() {
22
+
23
+ }
24
+
25
+ initialRender() {
26
+ if (!this.dataFrame) {
27
+ this.root.innerHTML = '';
28
+ return;
29
+ }
30
+
31
+ const inputData = this.dataFrame;
32
+ const IS_OUTLIER_COL_LABEL = 'isOutlier';
33
+ const OUTLIER_RATIONALE_COL_LABEL = 'Rationale';
34
+ const OUTLIER_COUNT_COL_LABEL = 'Count';
35
+ const IS_GROUP_CONFIRMED_LABEL = 'isConfirmed';
36
+ const FLUX = 't/V (hr/L)';
37
+
38
+ if (!inputData.columns.byName(IS_OUTLIER_COL_LABEL)) {
39
+ inputData.columns
40
+ .add(DG.Column.fromBitSet(IS_OUTLIER_COL_LABEL, DG.BitSet.create(inputData.rowCount, () => false)));
41
+ }
42
+
43
+ if (!inputData.columns.byName(OUTLIER_RATIONALE_COL_LABEL)) {
44
+ inputData.columns
45
+ .add(DG.Column.fromStrings(OUTLIER_RATIONALE_COL_LABEL, Array.from({length: inputData.rowCount}, () => '')));
46
+ }
47
+
48
+ if (!inputData.columns.byName(FLUX)) {
49
+ (inputData.columns as DG.ColumnList).addNew(FLUX, 'double').init((index) => (inputData.cell(index, 'filtrate volume (mL)').value/1000.0) / (inputData.cell(index, 'time (min)').value/60.0));
50
+ }
51
+
52
+ const initialData = inputData.clone();
53
+
54
+ const clearTable = () => {
55
+ return DG.DataFrame.fromColumns([
56
+ DG.Column.fromStrings(OUTLIER_RATIONALE_COL_LABEL, []),
57
+ DG.Column.fromInt32Array(OUTLIER_COUNT_COL_LABEL, new Int32Array([])),
58
+ DG.Column.fromStrings('Actions', []),
59
+ DG.Column.fromBitSet(IS_GROUP_CONFIRMED_LABEL, DG.BitSet.create(0, () => false)),
60
+ ]);
61
+ };
62
+
63
+ const groupsListGrid = DG.Viewer.grid(clearTable());
64
+ groupsListGrid.root.style.width = '100%';
65
+ groupsListGrid.columns.setVisible([OUTLIER_RATIONALE_COL_LABEL, OUTLIER_COUNT_COL_LABEL, 'Actions']);
66
+
67
+ groupsListGrid.onCellPrepare((gc) => {
68
+ if (!gc.isTableCell) {
69
+ return;
70
+ }
71
+
72
+ const confirmBtn = () => ui.div(
73
+ ui.iconFA('check', () => {
74
+ if (!groupsListGrid.dataFrame) return;
75
+
76
+ const newRationale =
77
+ groupsListGrid.dataFrame?.cell(groupsListGrid.dataFrame.rowCount-1, OUTLIER_RATIONALE_COL_LABEL).value;
78
+
79
+ inputData.selection.getSelectedIndexes().forEach((selectedIndex: number) => {
80
+ inputData.set(IS_OUTLIER_COL_LABEL, selectedIndex, true);
81
+ inputData.set(
82
+ OUTLIER_RATIONALE_COL_LABEL,
83
+ selectedIndex,
84
+ newRationale,
85
+ );
86
+ });
87
+ inputData.selection.setAll(false);
88
+ }, 'Confirm the outliers'), {style: {'text-align': 'center', 'margin': '6px'}},
89
+ );
90
+
91
+ const cancelBtn = () => ui.div(
92
+ ui.iconFA('times', () => {
93
+ if (!groupsListGrid.dataFrame) return;
94
+
95
+ groupsListGrid.dataFrame.rows.removeAt(groupsListGrid.dataFrame.rowCount-1);
96
+ inputData.selection.setAll(false);
97
+ }, 'Cancel the outliers'), {style: {'text-align': 'center', 'margin': '6px'}},
98
+ );
99
+
100
+ const deleteBtn = (rationale: string) => ui.div(
101
+ ui.icons.delete(() => {
102
+ for (let i = 0; i < inputData.rowCount; i++) {
103
+ if (inputData.columns.byName(OUTLIER_RATIONALE_COL_LABEL).get(i) === rationale) {
104
+ inputData.columns.byName(OUTLIER_RATIONALE_COL_LABEL).set(i, '');
105
+ inputData.columns.byName(IS_OUTLIER_COL_LABEL).set(i, false);
106
+ }
107
+ }
108
+ }, 'Remove the outliers group'), {style: {'text-align': 'center', 'margin': '6px'}},
109
+ );
110
+
111
+ if (gc.gridColumn.name === 'Actions') {
112
+ gc.gridColumn.cellType = 'html';
113
+ gc.style.element =
114
+ ui.divH([
115
+ ...!gc.grid.dataFrame?.get(IS_GROUP_CONFIRMED_LABEL, gc.gridRow) ?
116
+ [confirmBtn(), cancelBtn()] :
117
+ [deleteBtn(gc.grid.dataFrame?.get(OUTLIER_RATIONALE_COL_LABEL, gc.gridRow))],
118
+ ]);
119
+ }
120
+ });
121
+
122
+ groupsListGrid.onCellValueEdited.subscribe((editedCell) => {
123
+ if (!groupsListGrid.dataFrame || editedCell.gridColumn.name !== OUTLIER_RATIONALE_COL_LABEL) return;
124
+
125
+ if (!(groupsListGrid.dataFrame.columns as DG.ColumnList)
126
+ .byName(IS_GROUP_CONFIRMED_LABEL).get(editedCell.gridRow)) return;
127
+
128
+ const uniqueValues= new Set<string>();
129
+ for (let i = 0; i < groupsListGrid.dataFrame?.rowCount; i++) {
130
+ const record = groupsListGrid.dataFrame?.columns.byName(OUTLIER_RATIONALE_COL_LABEL).get(i);
131
+ uniqueValues.add(record);
132
+ }
133
+
134
+ for (let i = 0; i < inputData.rowCount; i++) {
135
+ const currentCellValue = inputData.columns.byName(OUTLIER_RATIONALE_COL_LABEL).get(i);
136
+ if (currentCellValue != '' && !uniqueValues.has(currentCellValue)) {
137
+ inputData.columns.byName(OUTLIER_RATIONALE_COL_LABEL).set(i, editedCell.cell.value);
138
+ }
139
+ }
140
+ });
141
+
142
+ const updateGroupsTable = () => {
143
+ const uniqueValues: {[key:string]: number} = {};
144
+ for (let i = 0; i < inputData.rowCount; i++) {
145
+ const record = inputData.columns.byName(OUTLIER_RATIONALE_COL_LABEL).get(i);
146
+ const count = uniqueValues[record];
147
+ if (record != '') {
148
+ count ?
149
+ uniqueValues[record]++ :
150
+ uniqueValues[record] = 1;
151
+ }
152
+ }
153
+ groupsListGrid.dataFrame = clearTable();
154
+ groupsListGrid.columns.setVisible([OUTLIER_RATIONALE_COL_LABEL, OUTLIER_COUNT_COL_LABEL, 'Actions']);
155
+
156
+ Object.keys(uniqueValues).map((key: string) => {
157
+ groupsListGrid.dataFrame?.rows.addNew([key, uniqueValues[key], '', true]);
158
+ });
159
+ };
160
+
161
+ inputData.onDataChanged.subscribe(updateGroupsTable);
162
+ inputData.onSelectionChanged.subscribe(() => {
163
+ if (!groupsListGrid.dataFrame || !inputData.selection.trueCount) return;
164
+
165
+ const isConfirmedColumn = (groupsListGrid.dataFrame.columns as DG.ColumnList)
166
+ .byName(IS_GROUP_CONFIRMED_LABEL).toList();
167
+
168
+ if (isConfirmedColumn.some((value) => value === false)) {
169
+ groupsListGrid.dataFrame.set(
170
+ OUTLIER_COUNT_COL_LABEL,
171
+ groupsListGrid.dataFrame.rowCount-1,
172
+ inputData.selection.trueCount,
173
+ );
174
+ } else {
175
+ const newRow = groupsListGrid.dataFrame.rows.addNew(['Manual', inputData.selection.trueCount, '', false]);
176
+ groupsListGrid.dataFrame.currentCell = groupsListGrid.dataFrame.cell(newRow.idx, OUTLIER_RATIONALE_COL_LABEL);
177
+ }
178
+ });
179
+
180
+ const resetSelectedBtn = ui.button(
181
+ 'RESET SELECTED',
182
+ () => {
183
+ inputData.selection.getSelectedIndexes().forEach((selectedIndex: number) => {
184
+ inputData.set(IS_OUTLIER_COL_LABEL, selectedIndex, false);
185
+ inputData.set(OUTLIER_RATIONALE_COL_LABEL, selectedIndex, '');
186
+ });
187
+ inputData.selection.setAll(false);
188
+ },
189
+ 'Remove the selected points from oultiers list',
190
+ );
191
+
192
+ const resetAllBtn = ui.button(
193
+ 'RESET ALL',
194
+ () => {
195
+ (inputData.columns as DG.ColumnList).byName(IS_OUTLIER_COL_LABEL).init(
196
+ (index) => initialData.get(IS_OUTLIER_COL_LABEL, index),
197
+ );
198
+ (inputData.columns as DG.ColumnList).byName(OUTLIER_RATIONALE_COL_LABEL).init(
199
+ (index) => initialData.get(OUTLIER_RATIONALE_COL_LABEL, index),
200
+ );
201
+ },
202
+ 'Cancel all changes',
203
+ );
204
+
205
+ const autoOutlierGroupBtn = ui.button(
206
+ 'AUTO DETECT...',
207
+ () => {
208
+ const intInput = ui.intInput('N', 3);
209
+ const columnInput = ui.columnInput('Column', inputData, null);
210
+ ui.dialog('Detect outliers automatically')
211
+ .add(columnInput.root)
212
+ .add(intInput.root)
213
+ .onOK(()=>{
214
+ const meanValue = (columnInput.value as DG.Column).stats.avg;
215
+ const stddev = (columnInput.value as DG.Column).stats.stdev;
216
+ inputData.selection.init((index)=>
217
+ Math.abs(meanValue - (columnInput.value as DG.Column).get(index)) > stddev*intInput.value,
218
+ );
219
+ inputData.selection.getSelectedIndexes().forEach((selectedIndex: number) => {
220
+ inputData.set(IS_OUTLIER_COL_LABEL, selectedIndex, true);
221
+ inputData.set(OUTLIER_RATIONALE_COL_LABEL, selectedIndex, `${intInput.value}x stddev rule`);
222
+ });
223
+ inputData.selection.setAll(false);
224
+ })
225
+ .show();
226
+ },
227
+ 'Detect outliers automatically',
228
+ );
229
+
230
+ inputData.selection.setAll(false);
231
+
232
+ inputData.onSelectionChanged.subscribe(() => {
233
+ if (inputData.selection.trueCount === 0) {
234
+ resetSelectedBtn.classList.add('disabled');
235
+ } else {
236
+ resetSelectedBtn.classList.remove('disabled');
237
+ }
238
+ });
239
+
240
+ updateGroupsTable();
241
+ resetSelectedBtn.classList.add('disabled');
242
+
243
+ this.root.replaceWith(ui.panel([
244
+ ui.divV([
245
+ ui.info(
246
+ ui.div([
247
+ ui.p('Hold the “SHIFT” key and start to draw a freehand selection on the plot area'),
248
+ ], {style: {'white-space': 'pre-wrap'}}),
249
+ ),
250
+ ui.divV([
251
+ ui.divH([
252
+ resetSelectedBtn, resetAllBtn, autoOutlierGroupBtn,
253
+ ], {style: {'text-align': 'center'}}),
254
+ groupsListGrid.root,
255
+ ], {style: {'height': '75%'}}),
256
+ ], {style: {'height': '100%', 'min-width': '230px'}}),
257
+ ], {style: {'height': '100%'}}));
258
+ }
259
+ }