@datagrok/hit-triage 1.10.9 → 1.11.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.
Files changed (123) hide show
  1. package/.grokignore +2 -0
  2. package/.turbo/turbo-build.log +25 -3
  3. package/CHANGELOG.md +78 -0
  4. package/CLAUDE.md +87 -10
  5. package/README_HD.md +14 -14
  6. package/README_HT.md +6 -6
  7. package/README_PH.md +110 -0
  8. package/bdd/bdd.config.json +3 -1
  9. package/bdd/bindings/campaign.ts +626 -0
  10. package/bdd/bindings/hit-design.ts +36 -42
  11. package/bdd/bindings/landing.ts +839 -0
  12. package/bdd/bindings/pepti-hit.ts +35 -0
  13. package/bdd/features/campaign/crumbs.feature +22 -0
  14. package/bdd/features/campaign/grid.feature +56 -0
  15. package/bdd/features/campaign/merge.feature +105 -0
  16. package/bdd/features/campaign/molecule-vid.feature +40 -0
  17. package/bdd/features/campaign/permissions.feature +46 -0
  18. package/bdd/features/campaign/progress-tracker.feature +89 -0
  19. package/bdd/features/campaign/refresh-hint.feature +33 -0
  20. package/bdd/features/campaign/ribbon.feature +49 -0
  21. package/bdd/features/campaign/stage-choices.feature +39 -0
  22. package/bdd/features/campaign/submit.feature +135 -0
  23. package/bdd/features/campaign/tracker-cards.feature +46 -0
  24. package/bdd/features/campaign/view-only.feature +37 -0
  25. package/bdd/features/landing/campaign-deep-links.feature +61 -0
  26. package/bdd/features/landing/hit-design-campaigns-fixes.feature +116 -0
  27. package/bdd/features/landing/hit-design-campaigns.feature +153 -0
  28. package/bdd/features/landing/hit-triage-campaigns.feature +99 -0
  29. package/bdd/features/landing/new-campaign.feature +69 -0
  30. package/bdd/features/landing/pep-triage-campaigns.feature +41 -0
  31. package/bdd/features/landing/pepti-hit-landing.feature +132 -0
  32. package/bdd/features/pepti-hit/helm-edit.feature +47 -0
  33. package/bdd/features/templates/template-editor.feature +130 -0
  34. package/bdd/features/templates/template-picker.feature +112 -0
  35. package/bdd/features/templates/triage-forms.feature +59 -0
  36. package/bdd/fixtures/bar-chart.layout +1 -0
  37. package/bdd/fixtures/merge-local.csv +2 -0
  38. package/bdd/generated/campaign/crumbs.test.ts +33 -0
  39. package/bdd/generated/campaign/grid.test.ts +79 -0
  40. package/bdd/generated/campaign/merge.test.ts +134 -0
  41. package/bdd/generated/campaign/molecule-vid.test.ts +52 -0
  42. package/bdd/generated/campaign/permissions.test.ts +58 -0
  43. package/bdd/generated/campaign/progress-tracker.test.ts +129 -0
  44. package/bdd/generated/campaign/refresh-hint.test.ts +44 -0
  45. package/bdd/generated/campaign/ribbon.test.ts +65 -0
  46. package/bdd/generated/campaign/stage-choices.test.ts +55 -0
  47. package/bdd/generated/campaign/submit.test.ts +167 -0
  48. package/bdd/generated/campaign/tracker-cards.test.ts +49 -0
  49. package/bdd/generated/campaign/view-only.test.ts +51 -0
  50. package/bdd/generated/hit-design/campaign-column-metadata.test.ts +1 -0
  51. package/bdd/generated/landing/campaign-deep-links.test.ts +68 -0
  52. package/bdd/generated/landing/hit-design-campaigns-fixes.test.ts +99 -0
  53. package/bdd/generated/landing/hit-design-campaigns.test.ts +160 -0
  54. package/bdd/generated/landing/hit-triage-campaigns.test.ts +107 -0
  55. package/bdd/generated/landing/new-campaign.test.ts +78 -0
  56. package/bdd/generated/landing/pep-triage-campaigns.test.ts +52 -0
  57. package/bdd/generated/landing/pepti-hit-landing.test.ts +130 -0
  58. package/bdd/generated/pepti-hit/helm-edit.test.ts +64 -0
  59. package/bdd/generated/templates/template-editor.test.ts +137 -0
  60. package/bdd/generated/templates/template-picker.test.ts +119 -0
  61. package/bdd/generated/templates/triage-forms.test.ts +68 -0
  62. package/css/hit-triage.css +27 -23
  63. package/dist/package-test.js +690 -4
  64. package/dist/package-test.js.map +1 -1
  65. package/dist/package.js +318 -73
  66. package/dist/package.js.map +1 -1
  67. package/package.json +11 -7
  68. package/queries/locks.sql +37 -0
  69. package/src/app/accordeons/layout-input.ts +52 -44
  70. package/src/app/accordeons/new-campaign-accordeon.ts +91 -54
  71. package/src/app/accordeons/new-hit-design-campaign-accordeon.ts +3 -67
  72. package/src/app/accordeons/new-pep-triage-template-accordeon.ts +39 -41
  73. package/src/app/accordeons/new-template-accordeon.ts +41 -24
  74. package/src/app/ai/view-functions.ts +22 -19
  75. package/src/app/base-view.ts +99 -8
  76. package/src/app/consts.ts +8 -5
  77. package/src/app/dialogs/functions-dialog.ts +14 -9
  78. package/src/app/dialogs/merge-table-dialog.ts +181 -325
  79. package/src/app/hit-app-base.ts +61 -90
  80. package/src/app/hit-design-app.ts +481 -886
  81. package/src/app/hit-design-views/info-view.ts +57 -407
  82. package/src/app/hit-design-views/submit-view.ts +216 -111
  83. package/src/app/hit-design-views/tiles-view.ts +168 -123
  84. package/src/app/hit-design-views/utils.css +0 -8
  85. package/src/app/hit-triage-app.ts +69 -38
  86. package/src/app/hit-triage-views/info-view.ts +70 -371
  87. package/src/app/pep-triage-app.ts +2 -2
  88. package/src/app/pep-triage-views/info-view.ts +42 -83
  89. package/src/app/pepti-hit-app.ts +32 -183
  90. package/src/app/pepti-hits-views/info-view.ts +15 -37
  91. package/src/app/shared/campaign-catalog.ts +408 -0
  92. package/src/app/shared/campaign-session.ts +557 -0
  93. package/src/app/shared/compute-editor.ts +274 -0
  94. package/src/app/shared/hit-home.ts +45 -0
  95. package/src/app/shared/new-campaign-form.ts +90 -0
  96. package/src/app/shared/permissions-editor.ts +93 -0
  97. package/src/app/shared/template-editor.ts +331 -0
  98. package/src/app/shared/template-picker.ts +154 -0
  99. package/src/app/utils/merge-table.ts +183 -78
  100. package/src/app/utils.ts +34 -325
  101. package/src/package-api.ts +29 -8
  102. package/src/package-test.ts +17 -2
  103. package/src/package.g.ts +12 -8
  104. package/src/package.ts +19 -7
  105. package/src/tests/ai.ts +244 -0
  106. package/src/tests/campaign-layout.ts +82 -0
  107. package/src/tests/campaign-session.ts +168 -0
  108. package/src/tests/campaigns.ts +23 -0
  109. package/src/tests/catalog.ts +156 -0
  110. package/src/tests/compat.ts +482 -0
  111. package/src/tests/compute.ts +165 -0
  112. package/src/tests/fixtures.ts +359 -0
  113. package/src/tests/merge.ts +149 -0
  114. package/src/tests/owners.ts +11 -0
  115. package/src/tests/save-lock.ts +932 -0
  116. package/src/tests/storage.ts +106 -0
  117. package/src/tests/template-editor.ts +538 -0
  118. package/src/tests/templates.ts +143 -0
  119. package/src/tests/triage-start.ts +81 -0
  120. package/src/tests/u2-guards.ts +384 -0
  121. package/src/tests/vid.ts +77 -0
  122. package/src/app/accordeons/new-hit-design-template-accordeon.ts +0 -238
  123. package/src/app/dialogs/permissions-dialog.ts +0 -66
@@ -2,36 +2,62 @@
2
2
  import * as grok from 'datagrok-api/grok';
3
3
  import * as ui from 'datagrok-api/ui';
4
4
  import * as DG from 'datagrok-api/dg';
5
- import {AppName, HitDesignCampaign, HitDesignTemplate, IFunctionArgs, TriagePermissions} from './types';
5
+ import {Dialog, computed, signal} from '@datagrok-libraries/u2';
6
+ import {AppName, HitDesignCampaign, HitDesignTemplate, IFunctionArgs, TemplateCompute, TriagePermissions} from './types';
6
7
  import {HitDesignInfoView} from './hit-design-views/info-view';
7
- import {CampaignIdKey, CampaignJsonName, CampaignTableName,
8
- HTQueryPrefix, HTScriptPrefix, HitDesignCampaignIdKey,
9
- HitDesignMolColName, HitDesignerFunctionTag, TileCategoriesColName, ViDColName, ViDSemType, i18n} from './consts';
8
+ import {CampaignIdKey, CampaignJsonName, CampaignTableName, HTFunctionOrderingLSKey,
9
+ HTQueryPrefix, HTScriptPrefix, HitDesignMolColName, TileCategoriesColName, ViDColName} from './consts';
10
10
  import {calculateColumns, calculateCellValues} from './utils/calculate-single-cell';
11
11
  // @ts-ignore
12
12
  import '../../css/hit-triage.css';
13
+ // @ts-ignore
14
+ import './hit-design-views/utils.css';
13
15
  import {_package} from '../package';
14
- import {addBreadCrumbsToRibbons, checkFileExists, checkRibbonsHaveSubmit, editableTableField, modifyUrl, toFormatedDateString} from './utils';
16
+ import {modifyUrl, toFormatedDateString} from './utils';
15
17
  import {HitDesignSubmitView} from './hit-design-views/submit-view';
16
- import {getTilesViewDialog} from './hit-design-views/tiles-view';
17
- import {HitAppBase} from './hit-app-base';
18
+ import {CampaignLockHeldError, HitAppBase} from './hit-app-base';
18
19
  import {HitBaseView} from './base-view';
19
- import {chemFunctionsDialog} from './dialogs/functions-dialog';
20
- import {Observable, Subscription} from 'rxjs';
21
- import {filter} from 'rxjs/operators';
22
- import {defaultPermissions, PermissionsDialog} from './dialogs/permissions-dialog';
20
+ import {descriptorsTree, rerunOnOpenOption} from './dialogs/functions-dialog';
21
+ import {defaultPermissions} from './shared/permissions-editor';
22
+ import {computeEditor} from './shared/compute-editor';
23
+ import {CampaignSession, CampaignSessionOptions, openCampaignSession, pickMoleculeColumn}
24
+ from './shared/campaign-session';
25
+ import {createNewHitDesignDataFrame} from './accordeons/new-hit-design-campaign-accordeon';
23
26
  import {getDefaultCampaignStorageSettings, getDefaultSharingSettings} from '../packageSettingsEditor';
24
- import * as api from '../package-api';
25
27
  import {registerMol} from './utils/molreg';
26
- import {autoMergeOnCampaignOpen, mergeIntoCampaign} from './utils/merge-table';
27
- import {openMergeTableDialog} from './dialogs/merge-table-dialog';
28
+ import {PlaceholderTag, autoMergeOnCampaignOpen, isEmptyPlaceholder, mergeIntoCampaign, mergeServerTable}
29
+ from './utils/merge-table';
28
30
  import {attachHitInfoAi, attachHitCampaignAi} from './ai/view-functions';
29
31
 
32
+ interface SaveRequest {
33
+ /** The table of the campaign the save was asked for. */
34
+ df: DG.DataFrame;
35
+ notify: boolean;
36
+ isCreating: boolean;
37
+ customProps?: Partial<HitDesignCampaign>;
38
+ }
39
+
40
+ /** A campaign besides its table, as a save writes it: the app's own while the campaign is open, else what the app
41
+ * kept of it when another one opened. */
42
+ interface CampaignState {
43
+ campaign?: HitDesignCampaign;
44
+ template: HitDesignTemplate;
45
+ campaignId: string;
46
+ filePath: string;
47
+ molColName: string;
48
+ /** The table as the app last read it from the server or wrote it there: what a save over another session's save
49
+ * tells the other session's edits by. */
50
+ base?: DG.DataFrame;
51
+ canEdit: boolean;
52
+ /** A new campaign's fields. */
53
+ fields: {[key: string]: any};
54
+ session?: CampaignSession;
55
+ }
56
+
30
57
  export class HitDesignApp<T extends HitDesignTemplate = HitDesignTemplate> extends HitAppBase<T> {
31
58
  multiView: DG.MultiView;
32
59
  protected _infoView: HitDesignInfoView;
33
60
  get infoView(): HitDesignInfoView {return this._infoView;}
34
- protected _designView?: DG.TableView;
35
61
  public _submitView?: HitDesignSubmitView;
36
62
  get submitView(): HitDesignSubmitView | undefined {return this._submitView;}
37
63
  protected _designViewName = 'Design';
@@ -40,60 +66,88 @@ export class HitDesignApp<T extends HitDesignTemplate = HitDesignTemplate> exten
40
66
  protected _molColName: string = HitDesignMolColName;
41
67
  protected _campaign?: HitDesignCampaign;
42
68
  public campaignProps: {[key: string]: any} = {};
43
-
44
- protected currentDesignViewId?: string;
45
69
  public mainView: DG.ViewBase;
46
70
  protected get version() {return this._campaign?.version ?? 0;};
47
71
  public existingStatuses: string[] = [];
72
+ /** Merges running: the rows they add are not the user's. */
73
+ public joining = 0;
74
+ private _session?: CampaignSession;
75
+ private _base?: DG.DataFrame;
76
+ /** Saves asked for and not finished. */
77
+ private _saves = 0;
78
+ /** The last save asked for: the next one starts after it. */
79
+ private _queue: Promise<unknown> = Promise.resolve();
80
+ /** The save waiting for the running one: a save of its campaign asked for meanwhile is folded into it. */
81
+ private _nextSave?: {request: SaveRequest, done: Promise<HitDesignCampaign | undefined>};
82
+ /** What the app kept of each campaign it switched away from, for a save of it still to run. */
83
+ private readonly _closed = new WeakMap<DG.DataFrame, CampaignState>();
84
+ private _opens = 0;
85
+ /** The latest single-cell calculation per row: an earlier one still running drops its results. */
86
+ private readonly _rowRuns = new Map<number, number>();
87
+
48
88
  constructor(c: DG.FuncCall, an: AppName = 'Hit Design',
49
89
  infoViewConstructor: (app: HitDesignApp) => HitDesignInfoView = (app) => new HitDesignInfoView(app)) {
50
90
  super(c, an);
51
91
  this._infoView = infoViewConstructor(this);
52
92
  this.multiView = new DG.MultiView({viewFactories: {[this._infoView.name]: () => this._infoView}});
93
+ this.multiView.helpUrl = this._infoView.helpUrl;
53
94
  this.multiView.subs.push(this.multiView.tabs.onTabChanged.subscribe((_) => {
54
95
  if (this.multiView.currentView instanceof HitBaseView)
55
96
  (this.multiView.currentView as HitBaseView<T, typeof this>).onActivated();
56
97
  }));
98
+ this.multiView.subs.push(grok.events.onCurrentViewChanged.subscribe(() => {
99
+ if (grok.shell.v === this.mainView)
100
+ this.setBaseUrl();
101
+ }));
57
102
 
58
103
  this.multiView.parentCall = c;
59
104
  attachHitInfoAi(this.multiView, this);
60
105
 
61
106
  this.mainView = this.multiView;
62
- this._initViewSubs();
63
107
  }
64
108
 
109
+ /** The open campaign's view. */
110
+ get designView(): DG.TableView | undefined {return this._session?.view;}
111
+
112
+ /** A save is running or waiting for the one that runs. */
113
+ get isSaving(): boolean {return this._saves > 0;}
114
+
115
+ /** How the campaign view of this app works: Hit Design's. */
116
+ protected sessionOptions(): CampaignSessionOptions {
117
+ const layout = this.campaign?.layout ?? (this.campaign ? undefined : this.template?.layoutViewState);
118
+ return {entryColumn: this.molColName, editor: 'Chem:editMoleculeCell', duplicateLabel: 'Duplicate molecule',
119
+ registerFirst: true, designer: true, layout};
120
+ }
121
+
122
+ /** Gets the campaign's table ready before its view shows it. */
123
+ protected prepareTable(_df: DG.DataFrame): void {}
124
+
65
125
  /**
66
126
  * Correctly joins the incoming dataframe with the existing campaign dataframe.
67
127
  * Drag-n-drop entry point — uses SMILES-based join with the historical defaults.
68
128
  * @param df Dataframe to be joined into existing campaign dataframe
69
129
  */
70
130
  async handleJoiningDataframe(df: DG.DataFrame) {
71
- const molCols = df.columns.bySemTypeAll(DG.SEMTYPE.MOLECULE);
72
- if (!molCols || molCols.length === 0) {
131
+ const molCols = HitAppBase.moleculeColumns(df);
132
+ if (molCols.length === 0) {
73
133
  grok.shell.error('No molecule column found');
74
134
  return;
75
135
  }
76
136
 
77
- let chosenMolColName: string | null = null;
137
+ let chosenMolColName: string | null = molCols[0]!.name;
78
138
  if (molCols.length > 1) {
79
- const molColNames = molCols.map((c) => c.name);
80
- const likelyMolCol = molCols.find((c) => c?.name?.toLowerCase() === 'smiles' || c?.name?.toLowerCase() === 'molecule') ?? molCols[0];
81
- const molColInput = ui.input.choice('Primary Molecule Column', {items: molColNames, value: likelyMolCol.name, nullable: false});
82
- const promise = new Promise<string | null>((resolve) => {
83
- ui.dialog('Select Primary Molecule Column')
84
- .add(ui.divText('Multiple molecule columns found. Please select the primary molecule column to be used for calculations.'))
85
- .add(molColInput)
86
- .onOK(() => resolve(molColInput.value!))
87
- .onCancel(() => resolve(null))
88
- .show();
89
- });
90
- chosenMolColName = await promise;
139
+ const likely = molCols.find((c) => c?.name?.toLowerCase() === 'smiles' || c?.name?.toLowerCase() === 'molecule') ?? molCols[0];
140
+ const session = this._session;
141
+ const table = this.dataFrame;
142
+ chosenMolColName = await pickMoleculeColumn(molCols.map((c) => c.name), likely.name, session?.host);
143
+ // the table goes into the campaign it was dropped on, or nowhere
144
+ if (session?.host.scope.isDisposed || this.dataFrame !== table)
145
+ return;
91
146
  if (!chosenMolColName) {
92
147
  grok.shell.info('Operation cancelled by user');
93
148
  return;
94
149
  }
95
- } else
96
- chosenMolColName = molCols[0]!.name!;
150
+ }
97
151
 
98
152
  if (!df.col(chosenMolColName)) {
99
153
  grok.shell.error('No molecule column found');
@@ -114,197 +168,98 @@ export class HitDesignApp<T extends HitDesignTemplate = HitDesignTemplate> exten
114
168
  return this.campaign?.template?.submit ?? this.template?.submit;
115
169
  }
116
170
 
117
- _initViewSubs() {
118
- this.multiView.subs.push(grok.events.onCurrentViewChanged.subscribe(async () => {
119
- try {
120
- if (grok.shell.v === this._designView) {
121
- grok.shell.windows.showHelp = false;
122
-
123
- this.setBaseUrl();
124
- modifyUrl(CampaignIdKey, this._campaignId ?? this._campaign?.name ?? '');
125
-
126
- const {sub} = addBreadCrumbsToRibbons(grok.shell.v, this.appName, grok.shell.v?.name, () => {
127
- grok.shell.v = this.mainView;
128
- this._designView?.close();
129
- this._infoView.init();
130
- sub.unsubscribe();
131
- });
132
- } else if (grok.shell.v === this.mainView)
133
- this.setBaseUrl();
134
- } catch (e) {
135
- console.error(e);
136
- }
137
- }));
138
-
139
- this.multiView.subs.push((grok.events.onFileImportRequest as unknown as Observable<DG.EventData<DG.FileImportArgs>>).subscribe((args) => {
140
- if (!grok.shell.tv || !this._designView || grok.shell.tv !== this._designView)
141
- return;
142
- if (!args?.args?.file)
143
- return;
144
- const file = args.args.file;
145
-
146
- if (!file.name?.endsWith('.csv') && !HitAppBase.molFileExtReaders.some((ext) => file.name?.endsWith(ext.ext)))
147
- return;
148
- // at this point, we can start checking the file, and prevent default behavior
149
- args.preventDefault();
150
- this.handleUploadingDataframe(file);
151
- }));
152
- }
153
-
154
- private async handleUploadingDataframe(file: File) {
155
- // TODO: Expose api for file readers
156
- try {
157
- let df: DG.DataFrame | null = null;
158
-
159
- if (file.name.endsWith('.csv'))
160
- df = DG.DataFrame.fromCsv(await file.text());
161
- else {
162
- const fileBytes: Uint8Array | null = await new Promise(async (resolve) => {
163
- const reader = new FileReader();
164
- let timeout: any = null;
165
- let result: Uint8Array | null = null;
166
- reader.onload = () => {
167
- result = reader.result ? new Uint8Array(reader.result as ArrayBuffer) : null;
168
- timeout && clearTimeout(timeout);
169
- resolve(result);
170
- };
171
- reader.readAsArrayBuffer(file);
172
- timeout = setTimeout(() => {
173
- reader.abort();
174
- resolve(null);
175
- }, 10000);
176
- });
177
- if (!fileBytes) {
178
- grok.shell.error('Failed to read file');
179
- return;
180
- }
181
- // since we are here, we can assume that the file extention reader exists
182
- const readerFunc = HitAppBase.molFileExtReaders.find((ext) => file.name.endsWith(ext.ext))!.handlerFunc!;
183
- const bytesArg = readerFunc.inputs[0].name;
184
- df = (await readerFunc.apply({[bytesArg]: fileBytes}))[0];
185
- }
186
-
187
- if (!df)
188
- throw new Error('Failed to read file');
189
- df.name = file.name.slice(0, file.name.lastIndexOf('.'));
190
- await df.meta.detectSemanticTypes();
191
- await grok.data.detectSemanticTypes(df);
192
- // TODO: Support choosing molecule column if there are multiple
193
- const molCol = df.columns.bySemType(DG.SEMTYPE.MOLECULE);
194
- if (!molCol) {
195
- // default behavior: add dataframe
196
- grok.shell.addTableView(df);
197
- return;
198
- }
199
-
200
- const dialog = ui.dialog('Uploading table with molecules')
201
- .add(ui.divText('Add new table to workspace or join with existing Hit Design campaign'))
202
- .addButton('Add to workspace', () => {
203
- dialog.close();
204
- grok.shell.addTableView(df);
205
- })
206
- .addButton('Add to existing campaign', () => {
207
- dialog.close();
208
- this.handleJoiningDataframe(df);
209
- });
210
- dialog.getButton('CANCEL')?.remove();
211
- dialog.show();
212
- } catch (e) {
213
- grok.shell.error('Hit Design Failed to read file');
214
- console.error(e);
215
- }
216
- }
217
-
218
171
  public get stages() {
219
172
  return this.campaign?.template?.stages ?? this.template?.stages ?? [];
220
173
  }
221
174
 
222
- public async setStages(st: string[]) {
175
+ /** The campaign's stages from now on, duplicates merged; rows in a stage that goes move to the first one. Saved;
176
+ * answers whether the save happened (a balloon says why not). */
177
+ public async setStages(st: string[]): Promise<boolean> {
223
178
  if (!this.campaign || !this.campaign.template || !this.template) {
224
179
  grok.shell.error('Campaign or template is not set');
225
- return;
180
+ return false;
226
181
  }
227
182
  if (!st?.length) {
228
183
  grok.shell.error('Removing all stages is not allowed');
229
- return;
184
+ return false;
230
185
  }
231
186
  const stageCol = this.dataFrame?.col(TileCategoriesColName);
232
187
  if (!stageCol) {
233
188
  grok.shell.error('No stage column found');
234
- return;
189
+ return false;
235
190
  }
236
- const removedStages: string[] = [];
237
- //make sure there is no duplication
238
191
  const stageSet = new Set(st);
239
192
  const uniqueStages = [...stageSet];
240
- const dfLen = this.dataFrame!.rowCount;
241
- const stageCats = stageCol.categories;
242
- const stageIndexes = stageCol.getRawData() as Int32Array;
243
- for (let i = 0; i < dfLen; i++) {
244
- const stage = stageCats[stageIndexes[i]];
245
- if (!stageSet.has(stage)) {
193
+ for (let i = 0; i < this.dataFrame!.rowCount; i++) {
194
+ if (!stageSet.has(stageCol.get(i)))
246
195
  stageCol.set(i, st[0], false);
247
- removedStages.push(stage);
248
- }
249
196
  }
250
-
251
- if (removedStages.length > 0)
252
- grok.shell.warning(`Some stages were removed: (${removedStages.join(', ')}). Corresponding rows were set to stage "${st[0]}"`);
253
-
254
-
255
197
  this.campaign.template.stages = uniqueStages;
256
198
  this.template.stages = uniqueStages;
257
- await this.saveCampaign(true);
199
+ stageCol.setTag(DG.TAGS.CHOICES, JSON.stringify(uniqueStages));
200
+ return await this.saveCampaign(true) !== undefined;
258
201
  }
259
202
 
260
- private _refreshIconTooltip = 'Refresh Campaign';
261
- protected async refreshCampaign() {
203
+ /** Reads the campaign's table from the server again into a new view; the rest of the campaign stays as it is. */
204
+ public async refreshCampaign() {
262
205
  if (!this._campaignId || !this.template) {
263
206
  grok.shell.warning('No campaign to refresh');
264
207
  return; // should not happen
265
208
  }
266
- if (this._isSaving) {
209
+ if (this.isSaving) {
267
210
  grok.shell.info('Campaign is being saved. Please wait a moment and try again.');
268
211
  return;
269
212
  }
270
- clearInterval(this._updateCheckIntervalId);
271
- this._refreshIconTooltip = 'Refresh Campaign';
272
213
  await this.setTemplate(this.template, this._campaignId);
273
214
  }
274
215
 
275
- private _updateCheckIntervalId: any = null;
276
- private _needsRefresh: boolean = false;
277
- public async setTemplate(template: T, campaignId?: string) {
216
+ /** The ticket of an open asked for now: of the opens asked for, only the latest one takes its campaign. */
217
+ openTicket(): number {
218
+ return ++this._opens;
219
+ }
220
+
221
+ /** Opens the campaign of `campaignId` (`campaign` is its campaign.json, by default the open one: a refresh) with
222
+ * `template`, or a new campaign of the template without one. Everything is read first; then the app takes the
223
+ * campaign and its view at once, so no save sees half of one campaign and half of another. An open asked for later
224
+ * wins: `ticket` ({@link openTicket}) is taken when the open is asked for, before what the caller reads first.
225
+ * Answers whether this one took the campaign. */
226
+ public async setTemplate(template: T, campaignId?: string,
227
+ campaign: HitDesignCampaign | undefined = campaignId ? this._campaign : undefined,
228
+ ticket = this.openTicket()): Promise<boolean> {
229
+ let df: DG.DataFrame;
230
+ let filePath: string;
278
231
  if (!campaignId) {
279
- this._designView?.dataFrame && grok.shell.closeTable(this._designView.dataFrame);
280
- this._designView = undefined;
281
232
  campaignId = await this.getNewCampaignName(`${this.appName}/campaigns`, template.key);
282
- modifyUrl(HitDesignCampaignIdKey, campaignId);
283
233
  let defaultFolderPath = await getDefaultCampaignStorageSettings();
284
234
  if (!defaultFolderPath.endsWith('/'))
285
235
  defaultFolderPath += '/';
286
- this._filePath = `${defaultFolderPath}${this.appName}/campaigns/${campaignId}/${CampaignTableName}`;
236
+ filePath = `${defaultFolderPath}${this.appName}/campaigns/${campaignId}/${CampaignTableName}`;
237
+ df = this.newCampaignFrame(template);
287
238
  } else {
288
239
  const fileLoc = `System.AppData/HitTriage/${this.appName}/campaigns`;
289
- this._filePath = this.campaign?.savePath ?? `${fileLoc}/${campaignId}/${CampaignTableName}`;
290
- this.dataFrame = await grok.dapi.files.readCsv(this._filePath);
291
- if (this._campaign?.columnSemTypes) {
292
- Object.entries(this._campaign.columnSemTypes).forEach(([colName, semtype]) => {
293
- const col = this.dataFrame!.columns.byName(colName);
294
- if (col && semtype)
295
- col.semType = semtype;
296
- });
240
+ filePath = campaign?.savePath ?? `${fileLoc}/${campaignId}/${CampaignTableName}`;
241
+ df = await grok.dapi.files.readCsv(filePath);
242
+ for (const name of df.columns.names().filter((name) => name.startsWith('~')))
243
+ df.columns.remove(name);
244
+ for (const [colName, semtype] of Object.entries(campaign?.columnSemTypes ?? {})) {
245
+ const col = df.columns.byName(colName);
246
+ if (col && semtype)
247
+ col.semType = semtype;
297
248
  }
298
- if (this._campaign?.columnTypes) {
299
- Object.entries(this._campaign.columnTypes).forEach(([colName, type]) => {
300
- const col = this.dataFrame!.columns.byName(colName);
301
- if (col && col.type !== type)
302
- try {this.dataFrame!.changeColumnType(colName, type as DG.COLUMN_TYPE);} catch (e) {console.error(e);}
303
- });
249
+ for (const [colName, type] of Object.entries(campaign?.columnTypes ?? {})) {
250
+ const col = df.columns.byName(colName);
251
+ if (!col || col.type === type)
252
+ continue;
253
+ try {
254
+ df.changeColumnType(colName, type as DG.COLUMN_TYPE);
255
+ }
256
+ catch (e) {
257
+ console.error(e);
258
+ }
304
259
  }
305
260
  // restored before the view binds the table, which subscribes formula columns to recalculation only if it has any
306
- for (const [colName, tags] of Object.entries(this._campaign?.columnTags ?? {})) {
307
- const col = this.dataFrame.columns.byName(colName);
261
+ for (const [colName, tags] of Object.entries(campaign?.columnTags ?? {})) {
262
+ const col = df.columns.byName(colName);
308
263
  if (!col)
309
264
  continue;
310
265
  for (const [tag, value] of Object.entries(tags))
@@ -313,117 +268,119 @@ export class HitDesignApp<T extends HitDesignTemplate = HitDesignTemplate> exten
313
268
  if (tags['.category-order'] && col.type === DG.COLUMN_TYPE.STRING)
314
269
  col.setCategoryOrder(col.getCategoryOrder());
315
270
  }
316
- //await this.dataFrame.meta.detectSemanticTypes();
271
+ // the CSV reader formats a number column to every digit it read ('0.0000000000000' for a calculated MW): unless
272
+ // the campaign chose another format, the column shows as the grid shows numbers, as it did before the reload
273
+ for (const col of df.columns.toList()) {
274
+ const digits = col.getTag(DG.TAGS.SOURCE_PRECISION);
275
+ if (digits !== null && col.getTag(DG.TAGS.FORMAT) === `0.${'0'.repeat(parseInt(digits, 10))}`) {
276
+ col.tags.delete(DG.TAGS.FORMAT);
277
+ col.tags.delete(DG.TAGS.SOURCE_PRECISION);
278
+ }
279
+ }
317
280
  }
318
281
 
319
- if (!this.dataFrame) {
282
+ if (!df) {
320
283
  grok.shell.error('DataFrame is empty');
321
- clearInterval(this._updateCheckIntervalId);
322
- this._updateCheckIntervalId = null;
323
- return;
284
+ return false;
324
285
  }
325
- await this.dataFrame.meta.detectSemanticTypes();
326
- this._molColName = this.dataFrame.columns.bySemType(DG.SEMTYPE.MOLECULE)?.name ?? HitDesignMolColName;
327
- this._campaignId = campaignId;
328
- this.template = template;
329
-
330
- this._submitView ??= new HitDesignSubmitView(this);
331
- grok.shell.windows.showHelp = false;
332
- if (this.campaign)
333
- await this.setCanEdit(this.campaign);
334
- else
335
- this.hasEditPermission = true; // if the campaign is new, obviously the user can edit it
286
+ const base = df.clone();
287
+ await df.meta.detectSemanticTypes();
288
+ const molColName = HitAppBase.moleculeColumn(df)?.name ?? HitDesignMolColName;
289
+ const canEdit = await this.canEditCampaign(campaign);
336
290
 
337
291
  // Implicit merge pass before the view is shown: only runs when the campaign carries a
338
292
  // mergeConfig with autoMergeOnOpen and a remembered fileshare path. Compute is forced off
339
293
  // and we deliberately do not save — the user can save manually after the merge.
340
- if (campaignId && this.campaign?.mergeConfig?.autoMergeOnOpen && this.campaign.mergeConfig.filePath)
341
- await autoMergeOnCampaignOpen(this);
294
+ if (campaign) {
295
+ await autoMergeOnCampaignOpen(this, campaign.mergeConfig, {df, molColName, campaignId,
296
+ stages: campaign.template?.stages ?? template.stages ?? []});
297
+ }
342
298
 
343
299
  // Recompute any compute functions flagged "re-run when campaign opens" over the whole molecule
344
300
  // column. Like the auto-merge pass, this runs only for existing campaigns and is not auto-saved.
345
- if (campaignId && this.campaign)
346
- await this.reComputeOnCampaignOpen();
347
-
348
- const designV = this.designView;
349
- this.currentDesignViewId = designV.name;
301
+ if (campaign)
302
+ await this.reComputeOnCampaignOpen(df, template, molColName);
303
+ if (ticket !== this._opens)
304
+ return false;
305
+
306
+ if (this.dataFrame && this.dataFrame !== df)
307
+ this._closed.set(this.dataFrame, {...this.state(), session: undefined});
308
+ this._campaign = campaign;
309
+ if (campaign)
310
+ campaign.template = template;
311
+ this.template = template;
312
+ this._campaignId = campaignId;
313
+ this._filePath = filePath;
314
+ this.dataFrame = df;
315
+ this._base = base;
316
+ this._molColName = molColName;
317
+ this.hasEditPermission = canEdit;
318
+ this._submitView ??= new HitDesignSubmitView(this);
319
+ grok.shell.windows.showHelp = false;
320
+ this.openView();
350
321
  this.setBaseUrl();
351
- modifyUrl(CampaignIdKey, this._campaignId ?? this._campaign?.name ?? '');
352
- if (this.campaign)
353
- this.campaign.template = template;
354
-
355
- // get the last saved time
356
- api.queries.getLastModified(this.appName, this._campaignId!).then((timeDf) => {
357
- const timeStr = timeDf?.col('updated_at')?.getString(0);
358
- this._lastExpiresTimeString = timeStr ?? null;
359
- this._needsRefresh = false;
360
- // add the interval to check for updates
361
- clearInterval(this._updateCheckIntervalId);
362
- let isChecking = false;
363
- this._updateCheckIntervalId = setInterval(async () => {
364
- if (isChecking || this._needsRefresh)
365
- return;
366
- isChecking = true;
367
- // first, check if this view is still active
368
- if (this._designView && !Array.from(grok.shell.tableViews).some((tv) => tv === this._designView)) {
369
- clearInterval(this._updateCheckIntervalId);
370
- console.log('Clearing campaign update check interval');
371
- this._updateCheckIntervalId = null;
372
- isChecking = false;
373
- return;
374
- }
375
- if (!this._campaignId || !this.template || this._isSaving || this.isJoining || !this._designView || grok.shell.v !== this._designView) {
376
- isChecking = false;
377
- return;
378
- }
379
- try {
380
- const timeDf = await api.queries.getLastModified(this.appName, this._campaignId);
381
- const timeStr = timeDf?.col('updated_at')?.getString(0);
382
- if (!timeStr) {
383
- isChecking = false;
384
- return;
385
- }
386
- if (this._lastExpiresTimeString !== timeStr && this._refreshCampaignIcon) {
387
- this._lastExpiresTimeString = timeStr;
388
- ui.hints.addHintIndicator(this._refreshCampaignIcon, true, 10000);
389
- this._refreshIconTooltip = 'New changes available. Click to refresh campaign.';
390
- this._lastExpiresTimeString = timeStr;
391
- this._needsRefresh = true;
392
- }
393
- } catch (e) {
394
- console.error(e);
395
- }
396
- isChecking = false;
397
- }, 3000);
398
- }).catch((e) => console.error(e));
322
+ modifyUrl(CampaignIdKey, campaignId);
323
+ return true;
399
324
  }
400
325
 
401
- private _lastExpiresTimeString: string | null = null;
402
-
403
- get campaignId(): string | undefined {return this._campaignId;}
404
-
405
- get designView(): DG.TableView {
406
- const view = this.getDesignView();
326
+ /** The campaign's view, the one open before closed first. */
327
+ private openView(): void {
328
+ this._session?.view.close();
329
+ const df = this.dataFrame!;
330
+ this.prepareTable(df);
331
+ this._designViewName = this.campaign?.friendlyName ?? this.campaign?.name ?? this._designViewName;
332
+ const view = grok.shell.addTableView(df);
333
+ view.name = this._designViewName;
334
+ view.parentCall = this.parentCall;
407
335
  attachHitCampaignAi(view, this, 'design');
408
- return this._designView = view;
336
+ const session = this._session = openCampaignSession(this, view, this.sessionOptions());
337
+ session.host.own(() => {
338
+ if (this._session === session)
339
+ this._session = undefined;
340
+ });
409
341
  }
410
342
 
343
+ get campaignId(): string | undefined {return this._campaignId;}
344
+
411
345
  get designViewName(): string {return this._designViewName;}
412
346
 
413
347
  set designViewName(name: string) {
414
348
  this._designViewName = name;
415
- this._designView && (this._designView.name = name);
349
+ if (this.designView)
350
+ this.designView.name = name;
416
351
  }
417
352
 
418
353
  get molColName() {
419
- return this._molColName ??= this.dataFrame?.columns.bySemType(DG.SEMTYPE.MOLECULE)?.name ?? HitDesignMolColName;
354
+ return this._molColName ??= (this.dataFrame && HitAppBase.moleculeColumn(this.dataFrame)?.name) ?? HitDesignMolColName;
355
+ }
356
+
357
+ /** Where the campaign's table is kept. */
358
+ get filePath(): string {return this._filePath;}
359
+ set filePath(path: string) {this._filePath = path;}
360
+
361
+ /** The folder the campaign's own folder is in. */
362
+ get campaignFolder(): string {
363
+ const at = this._filePath.indexOf((this.campaignId ?? this._campaign?.name)!);
364
+ return at === -1 ? this._filePath : this._filePath.substring(0, at - 1);
420
365
  }
421
366
 
422
367
  get campaign(): HitDesignCampaign | undefined {return this._campaign;}
423
368
 
424
369
  set campaign(campaign: HitDesignCampaign | undefined) {this._campaign = campaign;}
425
370
 
426
- clearCampaign() {this._campaign = undefined;}
371
+ /** A new campaign from `template`, opened and saved at once: nothing of the campaign open before carries over, the
372
+ * name typed names it, and its first save takes the code that is free then. */
373
+ async startNewCampaign(template: T, fields: {[key: string]: unknown}, name?: string): Promise<void> {
374
+ if (!await this.setTemplate(template))
375
+ return;
376
+ this.campaignProps = fields;
377
+ await this.saveCampaign(false, true, {friendlyName: name});
378
+ }
379
+
380
+ /** The one-row table a new campaign starts from. */
381
+ protected newCampaignFrame(template: T): DG.DataFrame {
382
+ return createNewHitDesignDataFrame(template);
383
+ }
427
384
 
428
385
  private _duplicateVidCache?: {
429
386
  colVersion: number,
@@ -453,36 +410,70 @@ export class HitDesignApp<T extends HitDesignTemplate = HitDesignTemplate> exten
453
410
  return this._duplicateVidCache;
454
411
  }
455
412
 
413
+ /** Starts the row's calculation; answers its number, which {@link isLatestRun} checks after each await. */
414
+ protected nextRun(row: number): number {
415
+ const run = (this._rowRuns.get(row) ?? 0) + 1;
416
+ this._rowRuns.set(row, run);
417
+ return run;
418
+ }
419
+
420
+ protected isLatestRun(row: number, run: number): boolean {
421
+ return this._rowRuns.get(row) === run;
422
+ }
423
+
424
+ /** The template's compute on the row's molecule, the results into the row (new columns added); saved. A later
425
+ * calculation of the row started meanwhile wins. */
456
426
  async performSingleCellCalculations(newValueIdx: number, newValue?: string) {
457
427
  const computeObj = this.template!.compute;
458
- if (!newValue || newValue === '')
428
+ // OK on an empty sketcher writes an empty molfile into a molblock cell: no molecule to calculate
429
+ if (!newValue || !_package.convertToSmiles(newValue))
459
430
  return;
460
-
431
+ const df = this.dataFrame!;
432
+ const run = this.nextRun(newValueIdx);
461
433
  const calcDf =
462
434
  await calculateCellValues(
463
435
  [newValue], computeObj.descriptors.args, computeObj.functions, computeObj.scripts, computeObj.queries);
464
-
436
+ if (!this.isLatestRun(newValueIdx, run) || this.dataFrame !== df)
437
+ return;
465
438
  for (const col of calcDf.columns.toList()) {
466
439
  if (col.name === HitDesignMolColName) continue;
467
- if (!this.dataFrame!.columns.contains(col.name)) {
468
- const newCol = this.dataFrame!.columns.addNew(col.name, col.type);
440
+ const target = df.col(col.name);
441
+ if (!target) {
442
+ const newCol = df.columns.addNew(col.name, col.type);
469
443
  newCol.semType = col.semType;
470
444
  }
471
- this.dataFrame!.col(col.name)!.set(newValueIdx, col.get(0), false);
445
+ else if (target.type !== col.type && isEmptyPlaceholder(target) &&
446
+ // a number placeholder keeps counts as they come: a retype would take the layout's filter on it away
447
+ !(target.type === DG.COLUMN_TYPE.FLOAT && col.type === DG.COLUMN_TYPE.INT))
448
+ df.changeColumnType(col.name, col.type as DG.COLUMN_TYPE);
449
+ df.col(col.name)!.set(newValueIdx, col.get(0), false);
472
450
  }
473
- this.dataFrame!.fireValuesChanged();
474
- this.saveCampaign(false);
451
+ df.fireValuesChanged();
452
+ void this.saveCampaign(false);
453
+ }
454
+
455
+ /** The V-iD of the row's molecule, registered with the campaign; written only while the row still holds that
456
+ * molecule, so the registration of a later edit wins. */
457
+ async registerRow(row: number): Promise<void> {
458
+ const df = this.dataFrame;
459
+ const molecules = df?.col(this.molColName);
460
+ const molecule = molecules?.get(row);
461
+ if (!df || !molecule)
462
+ return;
463
+ const vid = await registerMol(molecule, this._campaignId!, this.appName);
464
+ if (vid && molecules!.get(row) === molecule)
465
+ df.col(ViDColName)?.set(row, vid, true);
475
466
  }
476
467
 
477
468
  /**
478
469
  * Recomputes the compute functions/scripts/queries flagged with `rerunOnOpen` over the whole
479
- * molecule column. Called once when an existing campaign is opened, before the design view is
470
+ * molecule column of `df`, the table of a campaign being opened, before the design view is
480
471
  * shown. Mirrors the auto-merge-on-open pass: values are updated in memory but the campaign is
481
472
  * not auto-saved, and failures never bubble up so the campaign still opens.
482
473
  */
483
- private async reComputeOnCampaignOpen(): Promise<void> {
484
- const compute = this.template?.compute;
485
- if (!compute || !this.dataFrame || !this.molColName)
474
+ private async reComputeOnCampaignOpen(df: DG.DataFrame, template: T, molColName: string): Promise<void> {
475
+ const compute = template.compute;
476
+ if (!compute)
486
477
  return;
487
478
 
488
479
  // Descriptors are deterministic from structure, so they are intentionally never re-run on open.
@@ -492,7 +483,7 @@ export class HitDesignApp<T extends HitDesignTemplate = HitDesignTemplate> exten
492
483
  if (!functions.length && !scripts.length && !queries.length)
493
484
  return;
494
485
 
495
- const molCol = this.dataFrame.col(this.molColName);
486
+ const molCol = df.col(molColName);
496
487
  if (!molCol)
497
488
  return;
498
489
 
@@ -503,588 +494,227 @@ export class HitDesignApp<T extends HitDesignTemplate = HitDesignTemplate> exten
503
494
  const values = molCol.toList();
504
495
  const calcDf = await calculateCellValues(values, [], functions, scripts, queries);
505
496
  for (const resCol of calcDf.columns.toList()) {
506
- if (resCol.name === this.molColName || resCol.name === HitDesignMolColName)
497
+ if (resCol.name === molColName || resCol.name === HitDesignMolColName)
507
498
  continue;
508
- let targetCol = this.dataFrame.col(resCol.name);
499
+ let targetCol = df.col(resCol.name);
509
500
  if (!targetCol || targetCol.type !== resCol.type) {
510
501
  if (targetCol) // existing column of a different type: replace it wholesale
511
- this.dataFrame.columns.remove(resCol.name);
512
- targetCol = this.dataFrame.columns.addNew(resCol.name, resCol.type);
502
+ df.columns.remove(resCol.name);
503
+ targetCol = df.columns.addNew(resCol.name, resCol.type);
513
504
  }
514
505
  targetCol.semType = resCol.semType;
515
506
  const rows = Math.min(resCol.length, targetCol.length);
516
507
  for (let i = 0; i < rows; i++)
517
508
  targetCol.set(i, resCol.isNone(i) ? null : resCol.get(i), false);
518
509
  }
519
- this.dataFrame.fireValuesChanged();
510
+ df.fireValuesChanged();
520
511
  } catch (e) {
521
512
  _package.logger.error(e);
522
513
  grok.shell.warning('Re-run on open failed for some functions; opening the campaign anyway.');
523
514
  }
524
515
  }
525
516
 
526
- private _refreshCampaignIcon: HTMLElement | null = null;
527
- protected initDesignViewRibbons(view: DG.TableView, subs: Subscription[], addDesignerButton = false) {
528
- const onRemoveSub = grok.events.onViewRemoved.subscribe((v) => {
529
- if (v.id === view?.id) {
530
- subs.forEach((s) => s.unsubscribe());
531
- onRemoveSub.unsubscribe();
532
- }
517
+ /** "Calculate additional properties": the campaign's compute in the compute editor; on OK what is new or changed
518
+ * is calculated over the whole table, and the campaign saved. */
519
+ editCompute(): void {
520
+ const dialog = new Dialog('Compute', {name: 'compute'});
521
+ dialog.build(() => {
522
+ const editor = computeEditor({functions: this.computeFunctions,
523
+ value: this.campaign?.template?.compute ?? this.template!.compute, descriptors: descriptorsTree,
524
+ orderKey: HTFunctionOrderingLSKey, rerunOnOpen: rerunOnOpenOption});
525
+ // the descriptors picked are written in the tree's order, as the compute dialog wrote them
526
+ const listed = signal(false);
527
+ void editor.ready.then(() => listed.value = true);
528
+ dialog.add(editor);
529
+ dialog.okDisabled(computed(() => listed.value ? null : 'Listing the descriptors…'), {footer: true});
530
+ dialog.onOK(() => void this.applyCompute(editor.read()));
533
531
  });
534
- let ribbons = view?.getRibbonPanels();
535
- if (ribbons) {
536
- const hasSubmit = checkRibbonsHaveSubmit(ribbons);
537
- if (!hasSubmit) {
538
- setTimeout(() => {
539
- const {sub} = addBreadCrumbsToRibbons(view, this.appName, view.name, () => {
540
- grok.shell.v = this.mainView;
541
- view?.close();
542
- this._infoView.init();
543
- sub.unsubscribe();
544
- });
545
- }, 1000);
546
- const getComputeDialog = async () => {
547
- chemFunctionsDialog(this, async (resultMap) => {
548
- const oldDescriptors = this.template!.compute.descriptors.args;
549
- const oldFunctions = this.template!.compute.functions;
550
- const oldScripts = this.template!.compute.scripts ?? [];
551
- const oldQueries = this.template!.compute.queries ?? [];
552
- const newDescriptors = resultMap.descriptors;
553
- const newComputeObj = {
554
- descriptors: {
555
- enabled: !!resultMap?.descriptors?.length,
556
- args: resultMap?.descriptors ?? [],
557
- },
558
- functions: Object.entries(resultMap?.externals ?? {}).map(([funcName, args]) => {
559
- const splitFunc = funcName.split(':');
560
- return ({
561
- name: splitFunc[1],
562
- package: splitFunc[0],
563
- args: args,
564
- rerunOnOpen: !!resultMap?.rerunOnOpen?.[funcName],
565
- });
566
- }),
567
- scripts: Object.entries(resultMap?.scripts ?? {})
568
- .filter(([name, _]) => name.startsWith(HTScriptPrefix) && name.split(':').length === 3)
569
- .map(([scriptId, args]) => {
570
- const scriptNameParts = scriptId.split(':');
571
- return ({
572
- name: scriptNameParts[1] ?? '',
573
- id: scriptNameParts[2] ?? '',
574
- args: args,
575
- rerunOnOpen: !!resultMap?.rerunOnOpen?.[scriptId],
576
- });
577
- }),
578
- queries: Object.entries(resultMap?.queries ?? {})
579
- .filter(([name, _]) => name.startsWith(HTQueryPrefix) && name.split(':').length === 3)
580
- .map(([queryName, args]) => {
581
- const queryNameParts = queryName.split(':');
582
- return ({
583
- name: queryNameParts[1] ?? '',
584
- id: queryNameParts[2] ?? '',
585
- args: args,
586
- rerunOnOpen: !!resultMap?.rerunOnOpen?.[queryName],
587
- });
588
- }),
589
- };
590
- this.template!.compute = newComputeObj;
591
- this.campaign!.template = this.template;
592
- const uncalculatedDescriptors = newDescriptors.filter((d) => !oldDescriptors.includes(d));
593
-
594
- const newFunctions: {[_: string]: IFunctionArgs} = {};
595
- Object.entries(resultMap?.externals ?? {})
596
- .filter(([funcName, args]) => {
597
- const oldFunc = oldFunctions.find((f) => `${f.package}:${f.name}` === funcName);
598
- if (!oldFunc)
599
- return true;
600
- return !Object.entries(args).every(([key, value]) => oldFunc.args[key] === value);
601
- }).forEach(([funcName, args]) => {newFunctions[funcName] = args;});
602
-
603
- const newScripts: {[_: string]: IFunctionArgs} = {};
604
- Object.entries(resultMap?.scripts ?? {})
605
- .filter(([scriptName, args]) => {
606
- const oldScript = oldScripts.find((f) => `${HTScriptPrefix}:${f.name}:${f.id}` === scriptName);
607
- if (!oldScript)
608
- return true;
609
- return !Object.entries(args).every(([key, value]) => oldScript.args[key] === value);
610
- }).forEach(([scriptName, args]) => {newScripts[scriptName] = args;});
611
-
612
- const newQueries: {[_: string]: IFunctionArgs} = {};
613
- Object.entries(resultMap?.queries ?? {})
614
- .filter(([queryName, args]) => {
615
- const oldQuery = oldQueries.find((f) => `${HTQueryPrefix}:${f.name}:${f.id}` === queryName);
616
- if (!oldQuery)
617
- return true;
618
- return !Object.entries(args).every(([key, value]) => oldQuery.args[key] === value);
619
- }).forEach(([queryName, args]) => {newQueries[queryName] = args;});
620
- ui.setUpdateIndicator(view.grid.root, true);
621
- try {
622
- await calculateColumns({descriptors: uncalculatedDescriptors, externals: newFunctions,
623
- scripts: newScripts, queries: newQueries}, this.dataFrame!, this.molColName!);
624
- this.dataFrame!.fireValuesChanged();
625
- } finally {
626
- ui.setUpdateIndicator(view.grid.root, false);
627
- this.saveCampaign(false);
628
- }
629
- }, () => null, this.campaign?.template!, true, true);
630
- };
631
-
632
- const calculateRibbon = ui.iconFA('wrench', getComputeDialog, 'Calculate additional properties');
633
- const mergeTableButton = ui.iconFA('code-merge', () => {openMergeTableDialog(this);},
634
- 'Merge another table into the campaign');
635
- const addNewRowButton = ui.icons.add(() => {this.dataFrame?.rows.addNew(null, true);}, 'Add new row');
636
- const applyLayoutButton = ui.iconSvg('view-layout', () => {this.applyTemplateLayout(view);}, `Apply template layout ${this.template?.localLayoutPath ? '(Loaded from mounted file storage)' : '(Static)'}`);
637
- this._refreshCampaignIcon = ui.icons.sync(async () => {this.refreshCampaign();}, 'Refresh');
638
- ui.tooltip.bind(this._refreshCampaignIcon, () => this._refreshIconTooltip);
639
- const permissionsButton = ui.iconFA('share', async () => {
640
- await (new PermissionsDialog(this.campaign?.permissions)).show((res) => {
641
- this.campaign!.permissions = res;
642
- this.saveCampaign(true);
643
- });
644
- }, 'Edit campaign permissions');
645
- const tilesButton = ui.bigButton('Progress tracker', () => {
646
- getTilesViewDialog(this, () => this._designView ?? null);
647
- });
648
-
649
- const submitButton = ui.bigButton('Submit...', () => {
650
- this._submitView?.render();
651
- });
652
-
653
- const designerFuncs = DG.Func.find({meta: {role: HitDesignerFunctionTag}}).filter((f) => f.outputs.length === 1 && f.outputs[0].propertyType === DG.TYPE.DATA_FRAME);
654
- submitButton.classList.add('hit-design-submit-button');
655
- const ribbonButtons: HTMLElement[] = [submitButton];
656
- if (this.stages.length > 0)
657
- ribbonButtons.unshift(tilesButton);
658
- // only initialize campaign template if its not exsitent yet
659
- if (this.campaign && this.template && !this.campaign.template)
660
- this.campaign.template = this.template;
661
-
662
- if (this.template?.layoutViewState || this.template?.localLayoutPath)
663
- ribbonButtons.unshift(applyLayoutButton);
664
- if (this.hasEditPermission)
665
- ribbonButtons.unshift(permissionsButton);
666
-
667
- if (designerFuncs.length > 0 && addDesignerButton) {
668
- // TODO: Support multiple functions
669
- const designerFunc = designerFuncs[0];
670
- const designerButton = ui.iconFA('pen-nib', async () => {
671
- const prepareObj: any = {};
672
- if (designerFunc.inputs.length > 0 && this.dataFrame && this.dataFrame.currentRowIdx >=0 && designerFunc.inputs[0].semType === DG.SEMTYPE.MOLECULE) {
673
- const mol = _package.convertToSmiles(this.dataFrame.col(this.molColName)?.get(this.dataFrame.currentRowIdx));
674
- if (mol)
675
- prepareObj[designerFunc.inputs[0].name] = mol;
676
- }
677
- const fc = designerFunc.prepare(prepareObj);
678
- // the editor we get here will be editing the funccall, so then we can just call it.
679
- const dialogContent = await fc.getEditor();
680
- ui.dialog(designerFunc.friendlyName)
681
- .add(dialogContent)
682
- .onOK(async () => {
683
- const pg = DG.TaskBarProgressIndicator.create(`Running ${designerFunc.friendlyName}`);
684
- try {
685
- await fc.call();
686
- const res: DG.DataFrame = fc.getOutputParamValue();
687
- if (!res || !res.rowCount) {
688
- grok.shell.warning(`${designerFunc.friendlyName} returned an empty result`);
689
- pg.close();
690
- return;
691
- }
692
- await res.meta.detectSemanticTypes();
693
- await grok.data.detectSemanticTypes(res);
694
- await this.handleJoiningDataframe(res);
695
- } catch (e) {
696
- grok.shell.error(`Failed to run ${designerFunc.friendlyName}`);
697
- _package.logger.error(e);
698
- } finally {
699
- pg.close();
700
- }
701
- })
702
- .show();
703
- }, designerFunc.description ? designerFunc.description : designerFunc.friendlyName);
704
- ribbonButtons.unshift(designerButton);
705
- }
706
- ribbonButtons.unshift(calculateRibbon);
707
- ribbonButtons.unshift(mergeTableButton);
708
- ribbonButtons.unshift(addNewRowButton);
709
- ribbonButtons.unshift(this._refreshCampaignIcon);
710
-
711
- ribbons.push(ribbonButtons);
712
- // remove project save button from the ribbon
713
- ribbons.some((rg) => {
714
- const saveBtnIdx = rg?.findIndex((r) => r?.textContent?.toLowerCase() === 'save') ?? -1;
715
- if (saveBtnIdx !== -1) {
716
- rg.splice(saveBtnIdx, 1);
717
- return true;
718
- }
719
- return false;
720
- });
721
- // remove empty ribbon arrays
722
- ribbons = ribbons.filter((r) => (r?.length ?? 0) > 0);
723
- view.setRibbonPanels(ribbons);
724
- }
725
- }
726
- return view;
532
+ this._session!.host.show(dialog, {width: 800, resizable: true});
727
533
  }
728
534
 
729
- protected async applyTemplateLayout(view: DG.TableView) {
730
- if (!view) {
731
- grok.shell.error('No view found');
732
- return;
733
- }
734
- if (this.template?.localLayoutPath) {
735
- try {
736
- const file = await grok.dapi.files.readAsText(this.template.localLayoutPath);
737
- const layout = DG.ViewLayout.fromJson(file);
738
- view.loadLayout(layout);
739
- return;
740
- } catch (e) {
741
- grok.shell.error('Failed to apply layout from mounted file storage. Falling back to static layout');
742
- _package.logger.error(e);
743
- }
744
- }
745
- if (!this.template?.layoutViewState) {
746
- grok.shell.error('No layout found');
747
- return;
748
- }
535
+ /** The campaign's compute from now on: what it calculates anew or with other settings is calculated over the
536
+ * whole table, and the campaign saved. */
537
+ private async applyCompute(compute: TemplateCompute): Promise<void> {
538
+ const old = this.template!.compute;
539
+ const df = this.dataFrame!;
540
+ this.template!.compute = compute;
541
+ if (this.campaign)
542
+ this.campaign.template = this.template;
543
+ const changed = <F extends {args: IFunctionArgs}>(items: F[], before: F[], key: (f: F) => string) =>
544
+ Object.fromEntries(items.filter((f) => {
545
+ const was = before.find((b) => key(b) === key(f));
546
+ return !was || !Object.entries(f.args).every(([name, value]) => was.args[name] === value);
547
+ }).map((f) => [key(f), f.args]));
548
+ const grid = this.designView?.grid;
549
+ grid && ui.setUpdateIndicator(grid.root, true);
749
550
  try {
750
- const layout = DG.ViewLayout.fromViewState(this.template.layoutViewState);
751
- view.loadLayout(layout);
752
- } catch (e) {
753
- grok.shell.error('Failed to apply template layout. Check console for more details.');
754
- _package.logger.error(e);
551
+ await calculateColumns({
552
+ descriptors: compute.descriptors.args.filter((d) => !old.descriptors.args.includes(d)),
553
+ externals: changed(compute.functions, old.functions, (f) => `${f.package}:${f.name}`),
554
+ scripts: changed(compute.scripts ?? [], old.scripts ?? [], (s) => `${HTScriptPrefix}:${s.name}:${s.id}`),
555
+ queries: changed(compute.queries ?? [], old.queries ?? [], (q) => `${HTQueryPrefix}:${q.name}:${q.id}`),
556
+ }, df, this.molColName!);
557
+ } finally {
558
+ grid && ui.setUpdateIndicator(grid.root, false);
559
+ if (this.dataFrame === df)
560
+ void this.saveCampaign(false);
755
561
  }
756
562
  }
757
563
 
758
- protected getDesignView(): DG.TableView {
759
- this._designView && this._designView.close();
760
- const subs: Subscription[] = [];
761
- const isNew = this.dataFrame!.col(this.molColName)?.toList().every((m) => !m && m === '');
762
- const view = grok.shell.addTableView(this.dataFrame!);
763
- this._designViewName = this.campaign?.friendlyName ?? this.campaign?.name ?? this._designViewName;
764
- view.name = this._designViewName;
765
-
766
- view._onAdded();
767
- const layoutViewState = this._campaign?.layout;
768
- if (layoutViewState) {
769
- try {
770
- const layout = DG.ViewLayout.fromViewState(layoutViewState);
771
- view.loadLayout(layout);
772
- } catch (e) {
773
- grok.shell.error('Failed to apply layout. Falling back to default layout.');
774
- console.error(e);
775
- }
776
- }
777
- this.checkGrid(view);
778
- if (isNew)
779
- grok.functions.call('Chem:editMoleculeCell', {cell: view.grid.cell(this._molColName, 0)});
780
-
781
- this.initGridSubs(view, subs);
782
- // make VID column non-editable
783
- const vidGridCol = view.grid?.col(ViDColName);
784
- if (vidGridCol)
785
- vidGridCol.editable = false;
786
- // set the semType of vidCol
787
- const vidCol = this.dataFrame!.col(ViDColName);
788
- if (vidCol) {
789
- vidCol.semType = ViDSemType;
790
- vidCol.valueComparer = (a: string | null, b: string | null) => {
791
- if (a === b) return 0;
792
- if (a === null) return -1;
793
- if (b === null) return 1;
794
- // column is in string format of V######, but at some point it might go beyond 1 million, so remove the 'V' and compare as numbers
795
- const aNum = parseInt(a.substring(1));
796
- const bNum = parseInt(b.substring(1));
797
- return aNum - bNum;
798
- };
564
+ /** Saves the open campaign: one save at a time; a save of a campaign asked for while one runs is folded into the
565
+ * next one of that campaign. Answers the saved campaign, or nothing when it was not saved (a balloon says why). */
566
+ saveCampaign(notify = true, isCreating = false, customProps?: Partial<HitDesignCampaign>): Promise<HitDesignCampaign | undefined> {
567
+ const df = this.dataFrame;
568
+ if (!df)
569
+ return Promise.resolve(undefined);
570
+ const next = this._nextSave;
571
+ if (next?.request.df === df) {
572
+ next.request.notify ||= notify;
573
+ next.request.isCreating ||= isCreating;
574
+ next.request.customProps ??= customProps;
575
+ return next.done;
799
576
  }
800
-
801
- subs.push(this.dataFrame!.onRowsAdded.pipe(filter(() => !this.isJoining))
802
- .subscribe(() => { // TODO, insertion of rows in the middle
803
- try {
804
- if (this.stages.length > 0) {
805
- for (let i = 0; i < this.dataFrame!.rowCount; i++) {
806
- const colVal = this.dataFrame!.col(TileCategoriesColName)!.get(i);
807
- if (!colVal || colVal === '' || this.dataFrame!.col(TileCategoriesColName)?.isNone(i))
808
- this.dataFrame!.set(TileCategoriesColName, i, this.stages[0]);
809
- }
810
- }
811
- let lastAddedCell: DG.GridCell | null = null;
812
- for (let i = 0; i < this.dataFrame!.rowCount; i++) {
813
- const cell = view.grid.cell(this.molColName, i);
814
- if (!cell)
815
- continue;
816
- if (cell.cell.value === '' || cell.cell.value === null)
817
- lastAddedCell = cell;
818
- }
819
- if (lastAddedCell)
820
- grok.functions.call('Chem:editMoleculeCell', {cell: lastAddedCell});
821
- } catch (e) {
822
- console.error(e);
823
- }
824
- }));
825
- subs.push(grok.events.onContextMenu.subscribe((args) => {
826
- try {
827
- const viewer: DG.Viewer = args?.args?.context;
828
- if (!viewer)
829
- return;
830
- if (viewer?.type !== DG.VIEWER.GRID)
831
- return;
832
- if (!viewer.tableView || viewer.tableView.id !== view.id)
833
- return;
834
- if (args?.args?.item?.tableColumn?.name !== this.molColName || !args?.args?.item?.isTableCell)
835
- return;
836
- const menu: DG.Menu = args?.args?.menu;
837
- if (!menu)
838
- return;
839
- menu.item('Add new row', () => {
840
- this.dataFrame!.rows.addNew(null, true);
841
- });
842
- menu.item('Duplicate molecule', () => {
843
- try {
844
- const row = this.dataFrame!.rows.addNew(null, true);
845
- const cell = row.get(this.molColName);
846
- if (cell != null && row.idx > -1)
847
- this.dataFrame!.cell(row.idx, this.molColName).value = args?.args?.item?.cell?.value ?? '';
848
- } catch (e) {
849
- console.error(e);
850
- }
851
- });
852
-
853
- const cellIndex = args?.args?.item?.tableRowIndex;
854
- const cellValue = args?.args?.item?.cell?.value;
855
- if (cellValue && (cellIndex ?? -1) > -1) {
856
- menu.item('Re-Run Calculations', async () => {
857
- try {
858
- await this.performSingleCellCalculations(cellIndex, cellValue);
859
- } catch (e) {
860
- console.error(e);
861
- }
862
- });
863
- }
864
- } catch (e: any) {
865
- grok.log.error(e);
866
- }
867
- }));
868
-
869
- subs.push(grok.events.onViewLayoutApplied.subscribe((vI) => {
870
- if (!vI || vI.view !== view)
871
- return;
872
- this.initGridSubs(view, subs);
873
- }));
874
-
875
- this.initDesignViewRibbons(view, subs, true);
876
- view.parentCall = this.parentCall;
877
- return view;
577
+ const request: SaveRequest = {df, notify, isCreating, customProps};
578
+ const queued = this._saves > 0;
579
+ this._saves++;
580
+ const start = () => {
581
+ if (this._nextSave?.request === request)
582
+ this._nextSave = undefined;
583
+ return this._write(request);
584
+ };
585
+ const done = (queued ? this._queue.then(start, start) : start()).finally(() => this._saves--);
586
+ this._queue = done;
587
+ if (queued)
588
+ this._nextSave = {request, done};
589
+ return done;
878
590
  }
879
591
 
880
- checkGrid(view: DG.TableView) {
881
- if (!view.grid) {
882
- grok.shell.error('Applied layout created view without grid. Resetting layout.');
883
- view.resetLayout();
884
- }
592
+ /** The open campaign besides its table. */
593
+ private state(): CampaignState {
594
+ return {campaign: this._campaign, template: this.template!, campaignId: this._campaignId!, filePath: this._filePath,
595
+ molColName: this.molColName, base: this._base, canEdit: this.hasEditPermission, fields: this.campaignProps,
596
+ session: this._session};
885
597
  }
886
598
 
887
- // some of the subs are on grid, layout application will detach the grid, thus we need to re-init those subs
888
- protected _gridSubs: {grid: DG.Grid, subs: Subscription[]} | null = null;
889
-
890
- protected initGridSubs(view: DG.TableView, subs: Subscription[]) {
891
- if (this._gridSubs && this._gridSubs.grid === view.grid)
892
- return;
893
- if (this._gridSubs)
894
- this._gridSubs.subs.forEach((s) => s.unsubscribe());
895
- this.checkGrid(view);
896
- if (!view.grid) {
897
- grok.shell.error('No grid found, cannot initialize grid subscriptions');
599
+ /** What a save changed of the campaign of `df`: the app's own if it still has it open, else what it kept of it. */
600
+ private recordSave(df: DG.DataFrame, changes: Partial<CampaignState>): void {
601
+ if (this.dataFrame !== df) {
602
+ const kept = this._closed.get(df);
603
+ if (kept)
604
+ Object.assign(kept, changes);
898
605
  return;
899
606
  }
900
- this._gridSubs = {grid: view.grid, subs: []};
901
- view?.grid && this._gridSubs.subs.push(view.grid.onCellValueEdited.subscribe(async (gc) => {
902
- try {
903
- if (gc.tableColumn?.name === TileCategoriesColName) {
904
- await this.saveCampaign(false);
905
- return;
906
- }
907
- if (gc.tableColumn?.name !== this.molColName)
908
- return;
909
- const newValue = gc.cell.value;
910
- const newValueIdx = gc.tableRowIndex!;
911
-
912
- if (newValue) {
913
- try {
914
- const newVid = await registerMol(newValue, this._campaignId!, this.appName);
915
- this.dataFrame!.col(ViDColName)!.set(newValueIdx, newVid, true);
916
- } catch (e) {
917
- console.error('Failed to register molecule');
918
- }
919
- }
920
-
921
-
922
- await this.performSingleCellCalculations(newValueIdx, newValue);
923
- } catch (e) {
924
- grok.shell.error('Failed to process molecule edit, check console for details');
925
- console.error(e);
926
- }
927
- }));
928
-
929
- view?.grid && this._gridSubs.subs.push(view.grid.onCellRender.subscribe((args) => {
930
- try {
931
- // color duplicate vid values
932
- const cell = args.cell;
933
- const vdCache = this.duplicateVidCache;
934
- if (!cell || !cell.isTableCell || !cell.tableColumn || !vdCache ||
935
- cell.tableColumn.name !== ViDColName || (cell.tableRowIndex ?? -1) < 0)
936
- return;
937
-
938
- if (vdCache.valueCounts[vdCache.indexes[cell.tableRowIndex!]] > 1) {
939
- args.cell.style.backColor =
940
- DG.Color.setAlpha(DG.Color.getCategoricalColor(vdCache.indexes[cell.tableRowIndex!])
941
- , 150);
942
- }
943
- } catch (e) {}
944
- }));
945
- this._gridSubs.subs.forEach((s) => subs.push(s));
607
+ if (changes.campaign)
608
+ this._campaign = changes.campaign;
609
+ if (changes.base)
610
+ this._base = changes.base;
611
+ if (changes.filePath !== undefined)
612
+ this._filePath = changes.filePath;
613
+ if (changes.campaignId !== undefined) {
614
+ this._campaignId = changes.campaignId;
615
+ modifyUrl(CampaignIdKey, changes.campaignId);
616
+ }
946
617
  }
947
618
 
948
- getSummary(): {[_: string]: any} {
949
- const getFolderPath = () => {
950
- const campaignIndex = this._filePath.indexOf((this.campaignId ?? this._campaign?.name)!);
951
- const folderPath = campaignIndex === -1 ? this._filePath : this._filePath.substring(0, campaignIndex - 1);
952
- return folderPath;
953
- };
954
- const campaignProps = {...(this.campaign?.campaignFields ?? this.campaignProps)};
955
- if (this.template && this.template.campaignFields) {
956
- Object.entries(campaignProps).forEach(([key, value]) => {
957
- const field = this.template!.campaignFields!.find((f) => f.name === key);
958
- if (field && field.type === 'Date' && value) {
959
- const dateString = (new Date(value)).toString();
960
- if (dateString !== 'Invalid Date')
961
- campaignProps[key] = (new Date(value)).toLocaleDateString();
962
- else {
963
- if (value.date)
964
- campaignProps[key] = new Date(value.date).toLocaleDateString();
965
- else
966
- campaignProps[key] = value;
967
- }
968
- } else {
969
- if (field && field.type === DG.SEMTYPE.MOLECULE && value)
970
- campaignProps[key] = grok.chem.drawMolecule(value);
619
+ /** One save of the campaign of `df` under the campaign's lock: refused before the lock when the user may not edit
620
+ * the campaign. The app shows the saved campaign only if it still has that one open. */
621
+ private async _write({df, notify, isCreating, customProps}: SaveRequest): Promise<HitDesignCampaign | undefined> {
622
+ const open = () => this.dataFrame === df;
623
+ const state = open() ? this.state() : this._closed.get(df);
624
+ if (!state)
625
+ return undefined;
626
+ if (!state.canEdit) {
627
+ grok.shell.error('You do not have permission to modify this campaign');
628
+ return undefined;
629
+ }
630
+ // a closed view's session shows no feedback: its timers would start on a disposed host
631
+ const session = state.session?.host.scope.isDisposed ? undefined : state.session;
632
+ let {campaignId, filePath} = state;
633
+ session?.waitingForLock(true);
634
+ try {
635
+ if (state.campaign) {
636
+ const lock = await this.aquireAndWaitCampaignLock(campaignId);
637
+ if (!lock?.aquired)
638
+ throw new CampaignLockHeldError('Could not acquire lock for campaign during 30 seconds');
639
+ } else {
640
+ const locked = await this.lockNewCampaignCode(campaignId, state.template.key);
641
+ if (locked !== campaignId) {
642
+ filePath = filePath.replace(`/${campaignId}/${CampaignTableName}`, `/${locked}/${CampaignTableName}`);
643
+ campaignId = locked;
644
+ this.recordSave(df, {campaignId, filePath});
971
645
  }
972
- });
646
+ }
973
647
  }
974
-
975
- const getPathEditor = () => {
976
- const editIcon = ui.icons.edit(() => {
977
- const folderPath = getFolderPath();
978
- const newPathInput = ui.input.string('Path', {value: folderPath});
979
- const labelElement = newPathInput.root.getElementsByTagName('label').item(0);
980
- if (labelElement)
981
- labelElement.remove();
982
- newPathInput.root.style.width = '100%';
983
-
984
- const saveButton = ui.button('Save', async () => {
985
- const exists = await checkFileExists(newPathInput.value);
986
- if (!exists)
987
- return;
988
- const newPath = newPathInput.value;
989
- if (newPath.endsWith('/'))
990
- this._filePath = `${newPath}${this.campaignId}/${CampaignTableName}`;
991
- else
992
- this._filePath = `${newPath}/${this.campaignId}/${CampaignTableName}`;
993
-
994
- if (this._campaign)
995
- this._campaign!.savePath = this._filePath;
996
- await this.saveCampaign(true);
997
- ui.empty(pathDiv);
998
- const folderPath = getFolderPath();
999
- link = ui.link(folderPath,
1000
- () => this.download(this.dataFrame!, this.campaignId ?? this._campaign?.name ?? 'Molecules'),
1001
- i18n.download);
1002
- pathDiv.appendChild(link);
1003
- pathDiv.appendChild(editIcon);
1004
- });
1005
- const cancelButton = ui.button('Cancel', () => {
1006
- ui.empty(pathDiv);
1007
- pathDiv.appendChild(link);
1008
- pathDiv.appendChild(editIcon);
1009
- });
1010
- ui.empty(pathDiv);
1011
- newPathInput.addOptions(cancelButton);
1012
- newPathInput.addOptions(saveButton);
1013
- pathDiv.appendChild(newPathInput.root);
1014
- newPathInput.input.focus();
1015
- }, 'Edit file path');
1016
- editIcon.style.marginLeft = '5px';
1017
- const folderPath = getFolderPath();
1018
- let link = ui.link(folderPath,
1019
- () => this.download(this.dataFrame!, this.campaignId ?? this._campaign?.name ?? 'Molecules'), i18n.download);
1020
- const pathDiv = ui.divH([link, editIcon], {style: {alignItems: 'center'}});
1021
- return pathDiv;
1022
- };
1023
-
1024
- const campaignName = this.campaign?.friendlyName ?? this.campaign?.name ?? this.campaignId!;
1025
- const campaignNameField = editableTableField(ui.divText(campaignName), {
1026
- tooltip: 'Edit Campaign Name',
1027
- nullable: false,
1028
- onOk: async (a) => {
1029
- this.campaign!.friendlyName = a!;
1030
- await this.saveCampaign(true);
1031
- },
1032
- validator: async (a) => !!a?.trim() ? null : 'Campaign name can not be empty',
1033
- });
1034
-
1035
-
1036
- return {
1037
- 'Name': campaignNameField,
1038
- 'Code': this.campaignId ?? this._campaign?.name,
1039
- 'Template': this.template?.name ?? 'Molecules',
1040
- 'File Path': getPathEditor(),
1041
- ...(this.campaign?.authorUserFriendlyName ? {'Author': this.campaign.authorUserFriendlyName} : {}),
1042
- ...(this.campaign?.lastModifiedUserName ? {'Last Modified By': this.campaign.lastModifiedUserName} : {}),
1043
- ...(this.campaign?.createDate ? {'Create Date': this.campaign.createDate} : {}),
1044
- ...campaignProps,
1045
- 'Number of Molecules': (this.dataFrame!.rowCount).toString(),
1046
- 'Enrichment Methods': [this.template!.compute.descriptors.enabled ? 'descriptors' : '',
1047
- ...this.template!.compute.functions.map((func) => func.name)].filter((f) => f && f.trim() !== '').join(', '),
1048
- };
1049
- }
1050
-
1051
- private _isSaving: boolean = false;
1052
-
1053
- async saveCampaign(notify = true, isCreating = false, customProps?: Partial<HitDesignCampaign>): Promise<HitDesignCampaign> {
1054
- this._isSaving = true;
1055
- const campaignId = this.campaignId!;
1056
- const someoneElseEditingLoaderTimeout = setTimeout(() => {
1057
- if (this._designView?.grid)
1058
- ui.setUpdateIndicator(this._designView.grid.root, true, 'Someone else is saving the campaign. Please wait...');
1059
- }, 500);
648
+ catch (e) {
649
+ _package.logger.error(e);
650
+ // only a lock another session kept is "someone else"; a query that failed says why
651
+ grok.shell.error(e instanceof CampaignLockHeldError ?
652
+ 'Failed to acquire campaign lock. Someone else might be editing the campaign. Please try again later.' :
653
+ `Failed to save the campaign: ${e instanceof Error ? e.message : e}`);
654
+ return undefined;
655
+ } finally {
656
+ session?.waitingForLock(false);
657
+ }
658
+ session?.saving(true);
659
+ const save: CampaignState = {...state, campaignId, filePath};
660
+ const version = state.campaign?.version ?? 0;
661
+ let written = false;
1060
662
  try {
1061
- const lock = await this.aquireAndWaitCampaignLock(campaignId);
1062
- if (!lock?.aquired) // could not acquire lock
1063
- throw new Error('Could not acquire lock for campaign during 30 seconds');
663
+ const serverVersion = await this.mergeStaleSave(df, save);
664
+ const campaign = await this.campaignToSave(df, save, customProps);
665
+ if (serverVersion !== undefined)
666
+ campaign.version = Math.max(version, serverVersion) + 1;
667
+ const saved = df.columns.toList().filter((col) => !col.name.startsWith('~') && !isEmptyPlaceholder(col));
668
+ const csvDf = DG.DataFrame.fromColumns(saved).toCsv();
669
+ const base = df.clone();
670
+ await grok.dapi.files.writeAsText(filePath, csvDf);
671
+ written = true;
672
+ // a view closed meanwhile keeps the layout saved before
673
+ const view = session && !session.host.scope.isDisposed ? session.view : undefined;
674
+ const newLayout = view?.saveLayout();
675
+ if (view && !newLayout)
676
+ grok.shell.warning('Layout cound not be saved');
677
+ else if (newLayout)
678
+ campaign.layout = newLayout.viewState;
679
+ campaign.template = save.template;
680
+
681
+ await _package.saveCampaignJson(this.appName, campaign);
682
+ notify && grok.shell.info('Campaign saved successfully.');
683
+ !notify && isCreating && grok.shell.info('Campaign created successfully.');
684
+ const updatedAt = await this.releaseCampaignLock(campaignId);
685
+ this.recordSave(df, {campaign, base});
686
+ if (open()) {
687
+ this.designViewName = campaign.friendlyName ?? campaign.name;
688
+ session?.saved(updatedAt);
689
+ }
690
+ return campaign;
1064
691
  } catch (e) {
1065
- clearTimeout(someoneElseEditingLoaderTimeout);
1066
- if (this._designView?.grid)
1067
- ui.setUpdateIndicator(this._designView.grid.root, false);
1068
- grok.shell.error('Failed to acquire campaign lock. Someone else might be editing the campaign. Please try again later.');
1069
- this._isSaving = false;
1070
- return this.campaign!;
692
+ _package.logger.error(e);
693
+ // nothing written yet: the lock goes without logging a save other sessions would be told of
694
+ await (written ? this.releaseCampaignLock(campaignId) : this.dropCampaignLock(campaignId))
695
+ .catch((err) => _package.logger.error(err));
696
+ grok.shell.error(`Failed to save the campaign: ${e instanceof Error ? e.message : e}`);
697
+ return undefined;
698
+ } finally {
699
+ session?.saving(false);
1071
700
  }
1072
- clearTimeout(someoneElseEditingLoaderTimeout);
1073
- if (this._designView?.grid)
1074
- ui.setUpdateIndicator(this._designView.grid.root, true, 'Saving Campaign...');
1075
- // await DG.delay(3000); // artificial delay to simulate long save
701
+ }
1076
702
 
1077
- const templateName = this.template!.name;
1078
- const enrichedDf = this.dataFrame!;
1079
- const campaignName = campaignId;
703
+ /** campaign.json as the save writes it: the keys this app knows, and every key of the stored one it does not. A
704
+ * layout's column nothing filled yet is left out. */
705
+ private async campaignToSave(df: DG.DataFrame, save: CampaignState,
706
+ customProps?: Partial<HitDesignCampaign>): Promise<HitDesignCampaign> {
707
+ const columns = df.columns.toList().filter((col) => !col.name.startsWith('~') && !isEmptyPlaceholder(col));
1080
708
  const columnSemTypes: {[_: string]: string} = {};
1081
- enrichedDf.columns.toList().forEach((col) => columnSemTypes[col.name] = col.semType);
1082
709
  const colTypeMap: {[_: string]: string} = {};
1083
- enrichedDf.columns.toList().forEach((col) => colTypeMap[col.name] = col.type);
1084
710
  const columnTags: {[_: string]: {[_: string]: string}} = {};
1085
- for (const col of enrichedDf.columns.toList().filter((col) => !col.name.startsWith('~')))
1086
- columnTags[col.name] = Object.fromEntries(col.tags);
1087
- const sketchStateString = this.campaign?.tilesViewerFormSketch ?? undefined;
711
+ for (const col of columns) {
712
+ columnSemTypes[col.name] = col.semType;
713
+ colTypeMap[col.name] = col.type;
714
+ // the Stage choices are the template's stages, set on every open: a stored copy would go stale
715
+ columnTags[col.name] = Object.fromEntries(Array.from(col.tags).filter(([tag]) => tag !== PlaceholderTag &&
716
+ !(col.name === TileCategoriesColName && tag === DG.TAGS.CHOICES)));
717
+ }
1088
718
 
1089
719
  const getDefaultPerms = async () => {
1090
720
  try {
@@ -1101,81 +731,46 @@ export class HitDesignApp<T extends HitDesignTemplate = HitDesignTemplate> exten
1101
731
  }
1102
732
  return defaultPermissions;
1103
733
  };
734
+ const previous = save.campaign;
1104
735
  // if its first time save author as current user, else keep the same
1105
- const authorUserId = this.campaign?.authorUserId ?? grok.shell.user.id;
1106
- const permissions = this.campaign?.permissions ?? await getDefaultPerms();
1107
- const authorName = authorUserId ? this.campaign?.authorUserFriendlyName ?? (await grok.dapi.users.find(authorUserId))?.friendlyName : undefined;
1108
- const campaign: HitDesignCampaign = {
1109
- name: campaignName,
1110
- friendlyName: this.campaign?.friendlyName ?? customProps?.friendlyName ?? campaignName,
1111
- templateName,
1112
- status: this.campaign?.status ?? 'In Progress',
1113
- createDate: this.campaign?.createDate ?? toFormatedDateString(new Date()),
1114
- campaignFields: this.campaign?.campaignFields ?? this.campaignProps,
736
+ const authorUserId = previous?.authorUserId ?? grok.shell.user.id;
737
+ const permissions = previous?.permissions ?? await getDefaultPerms();
738
+ const authorName = authorUserId ? previous?.authorUserFriendlyName ?? (await grok.dapi.users.find(authorUserId))?.friendlyName : undefined;
739
+ return {
740
+ ...previous,
741
+ name: save.campaignId,
742
+ friendlyName: previous?.friendlyName ?? customProps?.friendlyName ?? save.campaignId,
743
+ templateName: save.template.name,
744
+ status: previous?.status ?? 'In Progress',
745
+ createDate: previous?.createDate ?? toFormatedDateString(new Date()),
746
+ campaignFields: previous?.campaignFields ?? save.fields,
1115
747
  columnSemTypes,
1116
- rowCount: enrichedDf.rowCount,
1117
- filteredRowCount: enrichedDf.filter.trueCount,
1118
- savePath: this._filePath,
748
+ rowCount: df.rowCount,
749
+ filteredRowCount: df.filter.trueCount,
750
+ savePath: save.filePath,
1119
751
  columnTypes: colTypeMap,
1120
752
  columnTags,
1121
- tilesViewerFormSketch: sketchStateString,
1122
- version: this.version + 1,
753
+ version: (previous?.version ?? 0) + 1,
1123
754
  authorUserId,
1124
755
  authorUserFriendlyName: authorName,
1125
756
  lastModifiedUserName: grok.shell.user.friendlyName,
1126
757
  permissions,
1127
- mergeConfig: this.campaign?.mergeConfig,
1128
758
  };
1129
- if (!this.hasEditPermission) {
1130
- grok.shell.error('You do not have permission to modify this campaign');
1131
- if (this._designView?.grid)
1132
- ui.setUpdateIndicator(this._designView.grid.root, false);
1133
- await this.releaseCampaignLock(campaignId);
1134
- this._isSaving = false;
1135
- return campaign;
1136
- }
1137
- const campaignPath = `${this.appName}/campaigns/${campaignId}/${CampaignJsonName}`;
1138
- // check if someone already saved the campaign
1139
- let resDf = enrichedDf;
1140
-
1141
-
1142
- if (await _package.files.exists(campaignPath)) {
1143
- const prevCamp: HitDesignCampaign = JSON.parse(await _package.files.readAsText(campaignPath));
1144
- if ((prevCamp.version ?? 0) > this.version) {
1145
- campaign.version = Math.max(this.version, (prevCamp.version ?? 0)) + 1;
1146
- if (await grok.dapi.files.exists(this._filePath)) {
1147
- try {
1148
- const prevCampDf = await grok.dapi.files.readCsv(this._filePath);
1149
- const joined = this.unionDataframes(prevCampDf, enrichedDf, this.molColName, this.molColName);
1150
- resDf = joined;
1151
- } catch (e) {
1152
- console.error(e);
1153
- }
1154
- }
1155
- }
1156
- }
1157
- const csvDf = DG.DataFrame.fromColumns(
1158
- resDf.columns.toList().filter((col) => !col.name.startsWith('~')),
1159
- ).toCsv();
1160
- await grok.dapi.files.writeAsText(this._filePath, csvDf);
1161
- const newLayout = this._designView!.saveLayout();
1162
- if (!newLayout)
1163
- grok.shell.warning('Layout cound not be saved');
1164
- else
1165
- campaign.layout = newLayout.viewState;
1166
- campaign.template = this.template;
759
+ }
1167
760
 
1168
- await _package.saveCampaignJson(this.appName, campaign);
1169
- notify && grok.shell.info('Campaign saved successfully.');
1170
- !notify && isCreating && grok.shell.info('Campaign created successfully.');
1171
- this.campaign = campaign;
1172
- this.designViewName = campaign.friendlyName ?? campaign.name;
1173
- const updatedAt = await this.releaseCampaignLock(campaignId);
1174
- this._lastExpiresTimeString = updatedAt;
1175
- if (this._designView?.grid)
1176
- ui.setUpdateIndicator(this._designView.grid.root, false);
1177
- this._isSaving = false;
1178
- this._refreshIconTooltip = 'Refresh Campaign';
1179
- return campaign;
761
+ /** Another session saved the campaign since this one read it: its table, where its campaign.json says, is merged
762
+ * into `df`. Answers the version it saved, nothing when there was no such save. */
763
+ private async mergeStaleSave(df: DG.DataFrame, save: CampaignState): Promise<number | undefined> {
764
+ const campaignPath = `${this.appName}/campaigns/${save.campaignId}/${CampaignJsonName}`;
765
+ if (!await _package.files.exists(campaignPath))
766
+ return undefined;
767
+ const server: HitDesignCampaign = JSON.parse(await _package.files.readAsText(campaignPath));
768
+ const serverVersion = server.version ?? 0;
769
+ if (serverVersion <= (save.campaign?.version ?? 0))
770
+ return undefined;
771
+ const table = server.savePath ?? save.filePath;
772
+ if (await grok.dapi.files.exists(table))
773
+ mergeServerTable(this, df, save.molColName, await grok.dapi.files.readCsv(table), save.base);
774
+ return serverVersion;
1180
775
  }
1181
776
  }