@datagrok/hit-triage 1.10.8 → 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 (129) hide show
  1. package/.grokignore +2 -0
  2. package/.turbo/turbo-build.log +24 -6
  3. package/.vscode/settings.json +16 -0
  4. package/CHANGELOG.md +80 -1
  5. package/CLAUDE.md +87 -10
  6. package/README_HD.md +14 -14
  7. package/README_HT.md +6 -6
  8. package/README_PH.md +110 -0
  9. package/bdd/bdd.config.json +3 -0
  10. package/bdd/bindings/campaign.ts +626 -0
  11. package/bdd/bindings/hit-design.ts +93 -0
  12. package/bdd/bindings/landing.ts +839 -0
  13. package/bdd/bindings/pepti-hit.ts +35 -0
  14. package/bdd/features/campaign/crumbs.feature +22 -0
  15. package/bdd/features/campaign/grid.feature +56 -0
  16. package/bdd/features/campaign/merge.feature +105 -0
  17. package/bdd/features/campaign/molecule-vid.feature +40 -0
  18. package/bdd/features/campaign/permissions.feature +46 -0
  19. package/bdd/features/campaign/progress-tracker.feature +89 -0
  20. package/bdd/features/campaign/refresh-hint.feature +33 -0
  21. package/bdd/features/campaign/ribbon.feature +49 -0
  22. package/bdd/features/campaign/stage-choices.feature +39 -0
  23. package/bdd/features/campaign/submit.feature +135 -0
  24. package/bdd/features/campaign/tracker-cards.feature +46 -0
  25. package/bdd/features/campaign/view-only.feature +37 -0
  26. package/bdd/features/hit-design/campaign-column-metadata.feature +61 -0
  27. package/bdd/features/landing/campaign-deep-links.feature +61 -0
  28. package/bdd/features/landing/hit-design-campaigns-fixes.feature +116 -0
  29. package/bdd/features/landing/hit-design-campaigns.feature +153 -0
  30. package/bdd/features/landing/hit-triage-campaigns.feature +99 -0
  31. package/bdd/features/landing/new-campaign.feature +69 -0
  32. package/bdd/features/landing/pep-triage-campaigns.feature +41 -0
  33. package/bdd/features/landing/pepti-hit-landing.feature +132 -0
  34. package/bdd/features/pepti-hit/helm-edit.feature +47 -0
  35. package/bdd/features/templates/template-editor.feature +130 -0
  36. package/bdd/features/templates/template-picker.feature +112 -0
  37. package/bdd/features/templates/triage-forms.feature +59 -0
  38. package/bdd/fixtures/bar-chart.layout +1 -0
  39. package/bdd/fixtures/merge-local.csv +2 -0
  40. package/bdd/generated/campaign/crumbs.test.ts +33 -0
  41. package/bdd/generated/campaign/grid.test.ts +79 -0
  42. package/bdd/generated/campaign/merge.test.ts +134 -0
  43. package/bdd/generated/campaign/molecule-vid.test.ts +52 -0
  44. package/bdd/generated/campaign/permissions.test.ts +58 -0
  45. package/bdd/generated/campaign/progress-tracker.test.ts +129 -0
  46. package/bdd/generated/campaign/refresh-hint.test.ts +44 -0
  47. package/bdd/generated/campaign/ribbon.test.ts +65 -0
  48. package/bdd/generated/campaign/stage-choices.test.ts +55 -0
  49. package/bdd/generated/campaign/submit.test.ts +167 -0
  50. package/bdd/generated/campaign/tracker-cards.test.ts +49 -0
  51. package/bdd/generated/campaign/view-only.test.ts +51 -0
  52. package/bdd/generated/hit-design/campaign-column-metadata.test.ts +76 -0
  53. package/bdd/generated/landing/campaign-deep-links.test.ts +68 -0
  54. package/bdd/generated/landing/hit-design-campaigns-fixes.test.ts +99 -0
  55. package/bdd/generated/landing/hit-design-campaigns.test.ts +160 -0
  56. package/bdd/generated/landing/hit-triage-campaigns.test.ts +107 -0
  57. package/bdd/generated/landing/new-campaign.test.ts +78 -0
  58. package/bdd/generated/landing/pep-triage-campaigns.test.ts +52 -0
  59. package/bdd/generated/landing/pepti-hit-landing.test.ts +130 -0
  60. package/bdd/generated/pepti-hit/helm-edit.test.ts +64 -0
  61. package/bdd/generated/templates/template-editor.test.ts +137 -0
  62. package/bdd/generated/templates/template-picker.test.ts +119 -0
  63. package/bdd/generated/templates/triage-forms.test.ts +68 -0
  64. package/bdd/package.json +1 -0
  65. package/bdd/tsconfig.json +13 -0
  66. package/css/hit-triage.css +27 -23
  67. package/dist/package-test.js +690 -4
  68. package/dist/package-test.js.map +1 -1
  69. package/dist/package.js +318 -73
  70. package/dist/package.js.map +1 -1
  71. package/package.json +15 -8
  72. package/queries/locks.sql +37 -0
  73. package/src/app/accordeons/layout-input.ts +52 -44
  74. package/src/app/accordeons/new-campaign-accordeon.ts +91 -54
  75. package/src/app/accordeons/new-hit-design-campaign-accordeon.ts +3 -67
  76. package/src/app/accordeons/new-pep-triage-template-accordeon.ts +39 -41
  77. package/src/app/accordeons/new-template-accordeon.ts +41 -24
  78. package/src/app/ai/view-functions.ts +22 -19
  79. package/src/app/base-view.ts +99 -8
  80. package/src/app/consts.ts +8 -5
  81. package/src/app/dialogs/functions-dialog.ts +14 -9
  82. package/src/app/dialogs/merge-table-dialog.ts +181 -325
  83. package/src/app/hit-app-base.ts +61 -90
  84. package/src/app/hit-design-app.ts +492 -882
  85. package/src/app/hit-design-views/info-view.ts +57 -407
  86. package/src/app/hit-design-views/submit-view.ts +216 -111
  87. package/src/app/hit-design-views/tiles-view.ts +168 -123
  88. package/src/app/hit-design-views/utils.css +0 -8
  89. package/src/app/hit-triage-app.ts +69 -38
  90. package/src/app/hit-triage-views/info-view.ts +70 -371
  91. package/src/app/pep-triage-app.ts +2 -2
  92. package/src/app/pep-triage-views/info-view.ts +42 -83
  93. package/src/app/pepti-hit-app.ts +32 -183
  94. package/src/app/pepti-hits-views/info-view.ts +15 -37
  95. package/src/app/shared/campaign-catalog.ts +408 -0
  96. package/src/app/shared/campaign-session.ts +557 -0
  97. package/src/app/shared/compute-editor.ts +274 -0
  98. package/src/app/shared/hit-home.ts +45 -0
  99. package/src/app/shared/new-campaign-form.ts +90 -0
  100. package/src/app/shared/permissions-editor.ts +93 -0
  101. package/src/app/shared/template-editor.ts +331 -0
  102. package/src/app/shared/template-picker.ts +154 -0
  103. package/src/app/types.ts +2 -0
  104. package/src/app/utils/merge-table.ts +183 -78
  105. package/src/app/utils.ts +34 -325
  106. package/src/package-api.ts +29 -8
  107. package/src/package-test.ts +17 -2
  108. package/src/package.g.ts +12 -8
  109. package/src/package.ts +19 -7
  110. package/src/tests/ai.ts +244 -0
  111. package/src/tests/campaign-layout.ts +82 -0
  112. package/src/tests/campaign-session.ts +168 -0
  113. package/src/tests/campaigns.ts +23 -0
  114. package/src/tests/catalog.ts +156 -0
  115. package/src/tests/compat.ts +482 -0
  116. package/src/tests/compute.ts +165 -0
  117. package/src/tests/fixtures.ts +359 -0
  118. package/src/tests/merge.ts +149 -0
  119. package/src/tests/owners.ts +11 -0
  120. package/src/tests/save-lock.ts +932 -0
  121. package/src/tests/storage.ts +106 -0
  122. package/src/tests/template-editor.ts +538 -0
  123. package/src/tests/templates.ts +143 -0
  124. package/src/tests/triage-start.ts +81 -0
  125. package/src/tests/u2-guards.ts +384 -0
  126. package/src/tests/vid.ts +77 -0
  127. package/tsconfig.json +3 -0
  128. package/src/app/accordeons/new-hit-design-template-accordeon.ts +0 -238
  129. 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,305 +168,219 @@ 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;
248
+ }
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
+ }
297
259
  }
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
- });
260
+ // restored before the view binds the table, which subscribes formula columns to recalculation only if it has any
261
+ for (const [colName, tags] of Object.entries(campaign?.columnTags ?? {})) {
262
+ const col = df.columns.byName(colName);
263
+ if (!col)
264
+ continue;
265
+ for (const [tag, value] of Object.entries(tags))
266
+ !!tag && !!value && col.setTag(tag, value);
267
+ // the tag alone does not reorder the categories
268
+ if (tags['.category-order'] && col.type === DG.COLUMN_TYPE.STRING)
269
+ col.setCategoryOrder(col.getCategoryOrder());
270
+ }
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
+ }
304
279
  }
305
- //await this.dataFrame.meta.detectSemanticTypes();
306
280
  }
307
281
 
308
- if (!this.dataFrame) {
282
+ if (!df) {
309
283
  grok.shell.error('DataFrame is empty');
310
- clearInterval(this._updateCheckIntervalId);
311
- this._updateCheckIntervalId = null;
312
- return;
284
+ return false;
313
285
  }
314
- await this.dataFrame.meta.detectSemanticTypes();
315
- this._molColName = this.dataFrame.columns.bySemType(DG.SEMTYPE.MOLECULE)?.name ?? HitDesignMolColName;
316
- this._campaignId = campaignId;
317
- this.template = template;
318
-
319
- this._submitView ??= new HitDesignSubmitView(this);
320
- grok.shell.windows.showHelp = false;
321
- if (this.campaign)
322
- await this.setCanEdit(this.campaign);
323
- else
324
- 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);
325
290
 
326
291
  // Implicit merge pass before the view is shown: only runs when the campaign carries a
327
292
  // mergeConfig with autoMergeOnOpen and a remembered fileshare path. Compute is forced off
328
293
  // and we deliberately do not save — the user can save manually after the merge.
329
- if (campaignId && this.campaign?.mergeConfig?.autoMergeOnOpen && this.campaign.mergeConfig.filePath)
330
- await autoMergeOnCampaignOpen(this);
294
+ if (campaign) {
295
+ await autoMergeOnCampaignOpen(this, campaign.mergeConfig, {df, molColName, campaignId,
296
+ stages: campaign.template?.stages ?? template.stages ?? []});
297
+ }
331
298
 
332
299
  // Recompute any compute functions flagged "re-run when campaign opens" over the whole molecule
333
300
  // column. Like the auto-merge pass, this runs only for existing campaigns and is not auto-saved.
334
- if (campaignId && this.campaign)
335
- await this.reComputeOnCampaignOpen();
336
-
337
- const designV = this.designView;
338
- 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();
339
321
  this.setBaseUrl();
340
- modifyUrl(CampaignIdKey, this._campaignId ?? this._campaign?.name ?? '');
341
- if (this.campaign)
342
- this.campaign.template = template;
343
-
344
- // get the last saved time
345
- api.queries.getLastModified(this.appName, this._campaignId!).then((timeDf) => {
346
- const timeStr = timeDf?.col('updated_at')?.getString(0);
347
- this._lastExpiresTimeString = timeStr ?? null;
348
- this._needsRefresh = false;
349
- // add the interval to check for updates
350
- clearInterval(this._updateCheckIntervalId);
351
- let isChecking = false;
352
- this._updateCheckIntervalId = setInterval(async () => {
353
- if (isChecking || this._needsRefresh)
354
- return;
355
- isChecking = true;
356
- // first, check if this view is still active
357
- if (this._designView && !Array.from(grok.shell.tableViews).some((tv) => tv === this._designView)) {
358
- clearInterval(this._updateCheckIntervalId);
359
- console.log('Clearing campaign update check interval');
360
- this._updateCheckIntervalId = null;
361
- isChecking = false;
362
- return;
363
- }
364
- if (!this._campaignId || !this.template || this._isSaving || this.isJoining || !this._designView || grok.shell.v !== this._designView) {
365
- isChecking = false;
366
- return;
367
- }
368
- try {
369
- const timeDf = await api.queries.getLastModified(this.appName, this._campaignId);
370
- const timeStr = timeDf?.col('updated_at')?.getString(0);
371
- if (!timeStr) {
372
- isChecking = false;
373
- return;
374
- }
375
- if (this._lastExpiresTimeString !== timeStr && this._refreshCampaignIcon) {
376
- this._lastExpiresTimeString = timeStr;
377
- ui.hints.addHintIndicator(this._refreshCampaignIcon, true, 10000);
378
- this._refreshIconTooltip = 'New changes available. Click to refresh campaign.';
379
- this._lastExpiresTimeString = timeStr;
380
- this._needsRefresh = true;
381
- }
382
- } catch (e) {
383
- console.error(e);
384
- }
385
- isChecking = false;
386
- }, 3000);
387
- }).catch((e) => console.error(e));
322
+ modifyUrl(CampaignIdKey, campaignId);
323
+ return true;
388
324
  }
389
325
 
390
- private _lastExpiresTimeString: string | null = null;
391
-
392
- get campaignId(): string | undefined {return this._campaignId;}
393
-
394
- get designView(): DG.TableView {
395
- 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;
396
335
  attachHitCampaignAi(view, this, 'design');
397
- 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
+ });
398
341
  }
399
342
 
343
+ get campaignId(): string | undefined {return this._campaignId;}
344
+
400
345
  get designViewName(): string {return this._designViewName;}
401
346
 
402
347
  set designViewName(name: string) {
403
348
  this._designViewName = name;
404
- this._designView && (this._designView.name = name);
349
+ if (this.designView)
350
+ this.designView.name = name;
405
351
  }
406
352
 
407
353
  get molColName() {
408
- 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);
409
365
  }
410
366
 
411
367
  get campaign(): HitDesignCampaign | undefined {return this._campaign;}
412
368
 
413
369
  set campaign(campaign: HitDesignCampaign | undefined) {this._campaign = campaign;}
414
370
 
415
- 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
+ }
416
384
 
417
385
  private _duplicateVidCache?: {
418
386
  colVersion: number,
@@ -442,36 +410,70 @@ export class HitDesignApp<T extends HitDesignTemplate = HitDesignTemplate> exten
442
410
  return this._duplicateVidCache;
443
411
  }
444
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. */
445
426
  async performSingleCellCalculations(newValueIdx: number, newValue?: string) {
446
427
  const computeObj = this.template!.compute;
447
- 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))
448
430
  return;
449
-
431
+ const df = this.dataFrame!;
432
+ const run = this.nextRun(newValueIdx);
450
433
  const calcDf =
451
434
  await calculateCellValues(
452
435
  [newValue], computeObj.descriptors.args, computeObj.functions, computeObj.scripts, computeObj.queries);
453
-
436
+ if (!this.isLatestRun(newValueIdx, run) || this.dataFrame !== df)
437
+ return;
454
438
  for (const col of calcDf.columns.toList()) {
455
439
  if (col.name === HitDesignMolColName) continue;
456
- if (!this.dataFrame!.columns.contains(col.name)) {
457
- 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);
458
443
  newCol.semType = col.semType;
459
444
  }
460
- 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);
461
450
  }
462
- this.dataFrame!.fireValuesChanged();
463
- 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);
464
466
  }
465
467
 
466
468
  /**
467
469
  * Recomputes the compute functions/scripts/queries flagged with `rerunOnOpen` over the whole
468
- * 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
469
471
  * shown. Mirrors the auto-merge-on-open pass: values are updated in memory but the campaign is
470
472
  * not auto-saved, and failures never bubble up so the campaign still opens.
471
473
  */
472
- private async reComputeOnCampaignOpen(): Promise<void> {
473
- const compute = this.template?.compute;
474
- 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)
475
477
  return;
476
478
 
477
479
  // Descriptors are deterministic from structure, so they are intentionally never re-run on open.
@@ -481,7 +483,7 @@ export class HitDesignApp<T extends HitDesignTemplate = HitDesignTemplate> exten
481
483
  if (!functions.length && !scripts.length && !queries.length)
482
484
  return;
483
485
 
484
- const molCol = this.dataFrame.col(this.molColName);
486
+ const molCol = df.col(molColName);
485
487
  if (!molCol)
486
488
  return;
487
489
 
@@ -492,585 +494,227 @@ export class HitDesignApp<T extends HitDesignTemplate = HitDesignTemplate> exten
492
494
  const values = molCol.toList();
493
495
  const calcDf = await calculateCellValues(values, [], functions, scripts, queries);
494
496
  for (const resCol of calcDf.columns.toList()) {
495
- if (resCol.name === this.molColName || resCol.name === HitDesignMolColName)
497
+ if (resCol.name === molColName || resCol.name === HitDesignMolColName)
496
498
  continue;
497
- let targetCol = this.dataFrame.col(resCol.name);
499
+ let targetCol = df.col(resCol.name);
498
500
  if (!targetCol || targetCol.type !== resCol.type) {
499
501
  if (targetCol) // existing column of a different type: replace it wholesale
500
- this.dataFrame.columns.remove(resCol.name);
501
- targetCol = this.dataFrame.columns.addNew(resCol.name, resCol.type);
502
+ df.columns.remove(resCol.name);
503
+ targetCol = df.columns.addNew(resCol.name, resCol.type);
502
504
  }
503
505
  targetCol.semType = resCol.semType;
504
506
  const rows = Math.min(resCol.length, targetCol.length);
505
507
  for (let i = 0; i < rows; i++)
506
508
  targetCol.set(i, resCol.isNone(i) ? null : resCol.get(i), false);
507
509
  }
508
- this.dataFrame.fireValuesChanged();
510
+ df.fireValuesChanged();
509
511
  } catch (e) {
510
512
  _package.logger.error(e);
511
513
  grok.shell.warning('Re-run on open failed for some functions; opening the campaign anyway.');
512
514
  }
513
515
  }
514
516
 
515
- private _refreshCampaignIcon: HTMLElement | null = null;
516
- protected initDesignViewRibbons(view: DG.TableView, subs: Subscription[], addDesignerButton = false) {
517
- const onRemoveSub = grok.events.onViewRemoved.subscribe((v) => {
518
- if (v.id === view?.id) {
519
- subs.forEach((s) => s.unsubscribe());
520
- onRemoveSub.unsubscribe();
521
- }
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()));
522
531
  });
523
- let ribbons = view?.getRibbonPanels();
524
- if (ribbons) {
525
- const hasSubmit = checkRibbonsHaveSubmit(ribbons);
526
- if (!hasSubmit) {
527
- setTimeout(() => {
528
- const {sub} = addBreadCrumbsToRibbons(view, this.appName, view.name, () => {
529
- grok.shell.v = this.mainView;
530
- view?.close();
531
- this._infoView.init();
532
- sub.unsubscribe();
533
- });
534
- }, 1000);
535
- const getComputeDialog = async () => {
536
- chemFunctionsDialog(this, async (resultMap) => {
537
- const oldDescriptors = this.template!.compute.descriptors.args;
538
- const oldFunctions = this.template!.compute.functions;
539
- const oldScripts = this.template!.compute.scripts ?? [];
540
- const oldQueries = this.template!.compute.queries ?? [];
541
- const newDescriptors = resultMap.descriptors;
542
- const newComputeObj = {
543
- descriptors: {
544
- enabled: !!resultMap?.descriptors?.length,
545
- args: resultMap?.descriptors ?? [],
546
- },
547
- functions: Object.entries(resultMap?.externals ?? {}).map(([funcName, args]) => {
548
- const splitFunc = funcName.split(':');
549
- return ({
550
- name: splitFunc[1],
551
- package: splitFunc[0],
552
- args: args,
553
- rerunOnOpen: !!resultMap?.rerunOnOpen?.[funcName],
554
- });
555
- }),
556
- scripts: Object.entries(resultMap?.scripts ?? {})
557
- .filter(([name, _]) => name.startsWith(HTScriptPrefix) && name.split(':').length === 3)
558
- .map(([scriptId, args]) => {
559
- const scriptNameParts = scriptId.split(':');
560
- return ({
561
- name: scriptNameParts[1] ?? '',
562
- id: scriptNameParts[2] ?? '',
563
- args: args,
564
- rerunOnOpen: !!resultMap?.rerunOnOpen?.[scriptId],
565
- });
566
- }),
567
- queries: Object.entries(resultMap?.queries ?? {})
568
- .filter(([name, _]) => name.startsWith(HTQueryPrefix) && name.split(':').length === 3)
569
- .map(([queryName, args]) => {
570
- const queryNameParts = queryName.split(':');
571
- return ({
572
- name: queryNameParts[1] ?? '',
573
- id: queryNameParts[2] ?? '',
574
- args: args,
575
- rerunOnOpen: !!resultMap?.rerunOnOpen?.[queryName],
576
- });
577
- }),
578
- };
579
- this.template!.compute = newComputeObj;
580
- this.campaign!.template = this.template;
581
- const uncalculatedDescriptors = newDescriptors.filter((d) => !oldDescriptors.includes(d));
582
-
583
- const newFunctions: {[_: string]: IFunctionArgs} = {};
584
- Object.entries(resultMap?.externals ?? {})
585
- .filter(([funcName, args]) => {
586
- const oldFunc = oldFunctions.find((f) => `${f.package}:${f.name}` === funcName);
587
- if (!oldFunc)
588
- return true;
589
- return !Object.entries(args).every(([key, value]) => oldFunc.args[key] === value);
590
- }).forEach(([funcName, args]) => {newFunctions[funcName] = args;});
591
-
592
- const newScripts: {[_: string]: IFunctionArgs} = {};
593
- Object.entries(resultMap?.scripts ?? {})
594
- .filter(([scriptName, args]) => {
595
- const oldScript = oldScripts.find((f) => `${HTScriptPrefix}:${f.name}:${f.id}` === scriptName);
596
- if (!oldScript)
597
- return true;
598
- return !Object.entries(args).every(([key, value]) => oldScript.args[key] === value);
599
- }).forEach(([scriptName, args]) => {newScripts[scriptName] = args;});
600
-
601
- const newQueries: {[_: string]: IFunctionArgs} = {};
602
- Object.entries(resultMap?.queries ?? {})
603
- .filter(([queryName, args]) => {
604
- const oldQuery = oldQueries.find((f) => `${HTQueryPrefix}:${f.name}:${f.id}` === queryName);
605
- if (!oldQuery)
606
- return true;
607
- return !Object.entries(args).every(([key, value]) => oldQuery.args[key] === value);
608
- }).forEach(([queryName, args]) => {newQueries[queryName] = args;});
609
- ui.setUpdateIndicator(view.grid.root, true);
610
- try {
611
- await calculateColumns({descriptors: uncalculatedDescriptors, externals: newFunctions,
612
- scripts: newScripts, queries: newQueries}, this.dataFrame!, this.molColName!);
613
- this.dataFrame!.fireValuesChanged();
614
- } finally {
615
- ui.setUpdateIndicator(view.grid.root, false);
616
- this.saveCampaign(false);
617
- }
618
- }, () => null, this.campaign?.template!, true, true);
619
- };
620
-
621
- const calculateRibbon = ui.iconFA('wrench', getComputeDialog, 'Calculate additional properties');
622
- const mergeTableButton = ui.iconFA('code-merge', () => {openMergeTableDialog(this);},
623
- 'Merge another table into the campaign');
624
- const addNewRowButton = ui.icons.add(() => {this.dataFrame?.rows.addNew(null, true);}, 'Add new row');
625
- const applyLayoutButton = ui.iconSvg('view-layout', () => {this.applyTemplateLayout(view);}, `Apply template layout ${this.template?.localLayoutPath ? '(Loaded from mounted file storage)' : '(Static)'}`);
626
- this._refreshCampaignIcon = ui.icons.sync(async () => {this.refreshCampaign();}, 'Refresh');
627
- ui.tooltip.bind(this._refreshCampaignIcon, () => this._refreshIconTooltip);
628
- const permissionsButton = ui.iconFA('share', async () => {
629
- await (new PermissionsDialog(this.campaign?.permissions)).show((res) => {
630
- this.campaign!.permissions = res;
631
- this.saveCampaign(true);
632
- });
633
- }, 'Edit campaign permissions');
634
- const tilesButton = ui.bigButton('Progress tracker', () => {
635
- getTilesViewDialog(this, () => this._designView ?? null);
636
- });
637
-
638
- const submitButton = ui.bigButton('Submit...', () => {
639
- this._submitView?.render();
640
- });
641
-
642
- const designerFuncs = DG.Func.find({meta: {role: HitDesignerFunctionTag}}).filter((f) => f.outputs.length === 1 && f.outputs[0].propertyType === DG.TYPE.DATA_FRAME);
643
- submitButton.classList.add('hit-design-submit-button');
644
- const ribbonButtons: HTMLElement[] = [submitButton];
645
- if (this.stages.length > 0)
646
- ribbonButtons.unshift(tilesButton);
647
- // only initialize campaign template if its not exsitent yet
648
- if (this.campaign && this.template && !this.campaign.template)
649
- this.campaign.template = this.template;
650
-
651
- if (this.template?.layoutViewState || this.template?.localLayoutPath)
652
- ribbonButtons.unshift(applyLayoutButton);
653
- if (this.hasEditPermission)
654
- ribbonButtons.unshift(permissionsButton);
655
-
656
- if (designerFuncs.length > 0 && addDesignerButton) {
657
- // TODO: Support multiple functions
658
- const designerFunc = designerFuncs[0];
659
- const designerButton = ui.iconFA('pen-nib', async () => {
660
- const prepareObj: any = {};
661
- if (designerFunc.inputs.length > 0 && this.dataFrame && this.dataFrame.currentRowIdx >=0 && designerFunc.inputs[0].semType === DG.SEMTYPE.MOLECULE) {
662
- const mol = _package.convertToSmiles(this.dataFrame.col(this.molColName)?.get(this.dataFrame.currentRowIdx));
663
- if (mol)
664
- prepareObj[designerFunc.inputs[0].name] = mol;
665
- }
666
- const fc = designerFunc.prepare(prepareObj);
667
- // the editor we get here will be editing the funccall, so then we can just call it.
668
- const dialogContent = await fc.getEditor();
669
- ui.dialog(designerFunc.friendlyName)
670
- .add(dialogContent)
671
- .onOK(async () => {
672
- const pg = DG.TaskBarProgressIndicator.create(`Running ${designerFunc.friendlyName}`);
673
- try {
674
- await fc.call();
675
- const res: DG.DataFrame = fc.getOutputParamValue();
676
- if (!res || !res.rowCount) {
677
- grok.shell.warning(`${designerFunc.friendlyName} returned an empty result`);
678
- pg.close();
679
- return;
680
- }
681
- await res.meta.detectSemanticTypes();
682
- await grok.data.detectSemanticTypes(res);
683
- await this.handleJoiningDataframe(res);
684
- } catch (e) {
685
- grok.shell.error(`Failed to run ${designerFunc.friendlyName}`);
686
- _package.logger.error(e);
687
- } finally {
688
- pg.close();
689
- }
690
- })
691
- .show();
692
- }, designerFunc.description ? designerFunc.description : designerFunc.friendlyName);
693
- ribbonButtons.unshift(designerButton);
694
- }
695
- ribbonButtons.unshift(calculateRibbon);
696
- ribbonButtons.unshift(mergeTableButton);
697
- ribbonButtons.unshift(addNewRowButton);
698
- ribbonButtons.unshift(this._refreshCampaignIcon);
699
-
700
- ribbons.push(ribbonButtons);
701
- // remove project save button from the ribbon
702
- ribbons.some((rg) => {
703
- const saveBtnIdx = rg?.findIndex((r) => r?.textContent?.toLowerCase() === 'save') ?? -1;
704
- if (saveBtnIdx !== -1) {
705
- rg.splice(saveBtnIdx, 1);
706
- return true;
707
- }
708
- return false;
709
- });
710
- // remove empty ribbon arrays
711
- ribbons = ribbons.filter((r) => (r?.length ?? 0) > 0);
712
- view.setRibbonPanels(ribbons);
713
- }
714
- }
715
- return view;
532
+ this._session!.host.show(dialog, {width: 800, resizable: true});
716
533
  }
717
534
 
718
- protected async applyTemplateLayout(view: DG.TableView) {
719
- if (!view) {
720
- grok.shell.error('No view found');
721
- return;
722
- }
723
- if (this.template?.localLayoutPath) {
724
- try {
725
- const file = await grok.dapi.files.readAsText(this.template.localLayoutPath);
726
- const layout = DG.ViewLayout.fromJson(file);
727
- view.loadLayout(layout);
728
- return;
729
- } catch (e) {
730
- grok.shell.error('Failed to apply layout from mounted file storage. Falling back to static layout');
731
- _package.logger.error(e);
732
- }
733
- }
734
- if (!this.template?.layoutViewState) {
735
- grok.shell.error('No layout found');
736
- return;
737
- }
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);
738
550
  try {
739
- const layout = DG.ViewLayout.fromViewState(this.template.layoutViewState);
740
- view.loadLayout(layout);
741
- } catch (e) {
742
- grok.shell.error('Failed to apply template layout. Check console for more details.');
743
- _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);
744
561
  }
745
562
  }
746
563
 
747
- protected getDesignView(): DG.TableView {
748
- this._designView && this._designView.close();
749
- const subs: Subscription[] = [];
750
- const isNew = this.dataFrame!.col(this.molColName)?.toList().every((m) => !m && m === '');
751
- const view = grok.shell.addTableView(this.dataFrame!);
752
- this._designViewName = this.campaign?.friendlyName ?? this.campaign?.name ?? this._designViewName;
753
- view.name = this._designViewName;
754
-
755
- view._onAdded();
756
- const layoutViewState = this._campaign?.layout;
757
- if (layoutViewState) {
758
- try {
759
- const layout = DG.ViewLayout.fromViewState(layoutViewState);
760
- view.loadLayout(layout);
761
- } catch (e) {
762
- grok.shell.error('Failed to apply layout. Falling back to default layout.');
763
- console.error(e);
764
- }
765
- }
766
- this.checkGrid(view);
767
- if (isNew)
768
- grok.functions.call('Chem:editMoleculeCell', {cell: view.grid.cell(this._molColName, 0)});
769
-
770
- this.initGridSubs(view, subs);
771
- // make VID column non-editable
772
- const vidGridCol = view.grid?.col(ViDColName);
773
- if (vidGridCol)
774
- vidGridCol.editable = false;
775
- // set the semType of vidCol
776
- const vidCol = this.dataFrame!.col(ViDColName);
777
- if (vidCol) {
778
- vidCol.semType = ViDSemType;
779
- vidCol.valueComparer = (a: string | null, b: string | null) => {
780
- if (a === b) return 0;
781
- if (a === null) return -1;
782
- if (b === null) return 1;
783
- // 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
784
- const aNum = parseInt(a.substring(1));
785
- const bNum = parseInt(b.substring(1));
786
- return aNum - bNum;
787
- };
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;
788
576
  }
789
-
790
- subs.push(this.dataFrame!.onRowsAdded.pipe(filter(() => !this.isJoining))
791
- .subscribe(() => { // TODO, insertion of rows in the middle
792
- try {
793
- if (this.stages.length > 0) {
794
- for (let i = 0; i < this.dataFrame!.rowCount; i++) {
795
- const colVal = this.dataFrame!.col(TileCategoriesColName)!.get(i);
796
- if (!colVal || colVal === '' || this.dataFrame!.col(TileCategoriesColName)?.isNone(i))
797
- this.dataFrame!.set(TileCategoriesColName, i, this.stages[0]);
798
- }
799
- }
800
- let lastAddedCell: DG.GridCell | null = null;
801
- for (let i = 0; i < this.dataFrame!.rowCount; i++) {
802
- const cell = view.grid.cell(this.molColName, i);
803
- if (!cell)
804
- continue;
805
- if (cell.cell.value === '' || cell.cell.value === null)
806
- lastAddedCell = cell;
807
- }
808
- if (lastAddedCell)
809
- grok.functions.call('Chem:editMoleculeCell', {cell: lastAddedCell});
810
- } catch (e) {
811
- console.error(e);
812
- }
813
- }));
814
- subs.push(grok.events.onContextMenu.subscribe((args) => {
815
- try {
816
- const viewer: DG.Viewer = args?.args?.context;
817
- if (!viewer)
818
- return;
819
- if (viewer?.type !== DG.VIEWER.GRID)
820
- return;
821
- if (!viewer.tableView || viewer.tableView.id !== view.id)
822
- return;
823
- if (args?.args?.item?.tableColumn?.name !== this.molColName || !args?.args?.item?.isTableCell)
824
- return;
825
- const menu: DG.Menu = args?.args?.menu;
826
- if (!menu)
827
- return;
828
- menu.item('Add new row', () => {
829
- this.dataFrame!.rows.addNew(null, true);
830
- });
831
- menu.item('Duplicate molecule', () => {
832
- try {
833
- const row = this.dataFrame!.rows.addNew(null, true);
834
- const cell = row.get(this.molColName);
835
- if (cell != null && row.idx > -1)
836
- this.dataFrame!.cell(row.idx, this.molColName).value = args?.args?.item?.cell?.value ?? '';
837
- } catch (e) {
838
- console.error(e);
839
- }
840
- });
841
-
842
- const cellIndex = args?.args?.item?.tableRowIndex;
843
- const cellValue = args?.args?.item?.cell?.value;
844
- if (cellValue && (cellIndex ?? -1) > -1) {
845
- menu.item('Re-Run Calculations', async () => {
846
- try {
847
- await this.performSingleCellCalculations(cellIndex, cellValue);
848
- } catch (e) {
849
- console.error(e);
850
- }
851
- });
852
- }
853
- } catch (e: any) {
854
- grok.log.error(e);
855
- }
856
- }));
857
-
858
- subs.push(grok.events.onViewLayoutApplied.subscribe((vI) => {
859
- if (!vI || vI.view !== view)
860
- return;
861
- this.initGridSubs(view, subs);
862
- }));
863
-
864
- this.initDesignViewRibbons(view, subs, true);
865
- view.parentCall = this.parentCall;
866
- 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;
867
590
  }
868
591
 
869
- checkGrid(view: DG.TableView) {
870
- if (!view.grid) {
871
- grok.shell.error('Applied layout created view without grid. Resetting layout.');
872
- view.resetLayout();
873
- }
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};
874
597
  }
875
598
 
876
- // some of the subs are on grid, layout application will detach the grid, thus we need to re-init those subs
877
- protected _gridSubs: {grid: DG.Grid, subs: Subscription[]} | null = null;
878
-
879
- protected initGridSubs(view: DG.TableView, subs: Subscription[]) {
880
- if (this._gridSubs && this._gridSubs.grid === view.grid)
881
- return;
882
- if (this._gridSubs)
883
- this._gridSubs.subs.forEach((s) => s.unsubscribe());
884
- this.checkGrid(view);
885
- if (!view.grid) {
886
- 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);
887
605
  return;
888
606
  }
889
- this._gridSubs = {grid: view.grid, subs: []};
890
- view?.grid && this._gridSubs.subs.push(view.grid.onCellValueEdited.subscribe(async (gc) => {
891
- try {
892
- if (gc.tableColumn?.name === TileCategoriesColName) {
893
- await this.saveCampaign(false);
894
- return;
895
- }
896
- if (gc.tableColumn?.name !== this.molColName)
897
- return;
898
- const newValue = gc.cell.value;
899
- const newValueIdx = gc.tableRowIndex!;
900
-
901
- if (newValue) {
902
- try {
903
- const newVid = await registerMol(newValue, this._campaignId!, this.appName);
904
- this.dataFrame!.col(ViDColName)!.set(newValueIdx, newVid, true);
905
- } catch (e) {
906
- console.error('Failed to register molecule');
907
- }
908
- }
909
-
910
-
911
- await this.performSingleCellCalculations(newValueIdx, newValue);
912
- } catch (e) {
913
- grok.shell.error('Failed to process molecule edit, check console for details');
914
- console.error(e);
915
- }
916
- }));
917
-
918
- view?.grid && this._gridSubs.subs.push(view.grid.onCellRender.subscribe((args) => {
919
- try {
920
- // color duplicate vid values
921
- const cell = args.cell;
922
- const vdCache = this.duplicateVidCache;
923
- if (!cell || !cell.isTableCell || !cell.tableColumn || !vdCache ||
924
- cell.tableColumn.name !== ViDColName || (cell.tableRowIndex ?? -1) < 0)
925
- return;
926
-
927
- if (vdCache.valueCounts[vdCache.indexes[cell.tableRowIndex!]] > 1) {
928
- args.cell.style.backColor =
929
- DG.Color.setAlpha(DG.Color.getCategoricalColor(vdCache.indexes[cell.tableRowIndex!])
930
- , 150);
931
- }
932
- } catch (e) {}
933
- }));
934
- 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
+ }
935
617
  }
936
618
 
937
- getSummary(): {[_: string]: any} {
938
- const getFolderPath = () => {
939
- const campaignIndex = this._filePath.indexOf((this.campaignId ?? this._campaign?.name)!);
940
- const folderPath = campaignIndex === -1 ? this._filePath : this._filePath.substring(0, campaignIndex - 1);
941
- return folderPath;
942
- };
943
- const campaignProps = {...(this.campaign?.campaignFields ?? this.campaignProps)};
944
- if (this.template && this.template.campaignFields) {
945
- Object.entries(campaignProps).forEach(([key, value]) => {
946
- const field = this.template!.campaignFields!.find((f) => f.name === key);
947
- if (field && field.type === 'Date' && value) {
948
- const dateString = (new Date(value)).toString();
949
- if (dateString !== 'Invalid Date')
950
- campaignProps[key] = (new Date(value)).toLocaleDateString();
951
- else {
952
- if (value.date)
953
- campaignProps[key] = new Date(value.date).toLocaleDateString();
954
- else
955
- campaignProps[key] = value;
956
- }
957
- } else {
958
- if (field && field.type === DG.SEMTYPE.MOLECULE && value)
959
- 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});
960
645
  }
961
- });
646
+ }
962
647
  }
963
-
964
- const getPathEditor = () => {
965
- const editIcon = ui.icons.edit(() => {
966
- const folderPath = getFolderPath();
967
- const newPathInput = ui.input.string('Path', {value: folderPath});
968
- const labelElement = newPathInput.root.getElementsByTagName('label').item(0);
969
- if (labelElement)
970
- labelElement.remove();
971
- newPathInput.root.style.width = '100%';
972
-
973
- const saveButton = ui.button('Save', async () => {
974
- const exists = await checkFileExists(newPathInput.value);
975
- if (!exists)
976
- return;
977
- const newPath = newPathInput.value;
978
- if (newPath.endsWith('/'))
979
- this._filePath = `${newPath}${this.campaignId}/${CampaignTableName}`;
980
- else
981
- this._filePath = `${newPath}/${this.campaignId}/${CampaignTableName}`;
982
-
983
- if (this._campaign)
984
- this._campaign!.savePath = this._filePath;
985
- await this.saveCampaign(true);
986
- ui.empty(pathDiv);
987
- const folderPath = getFolderPath();
988
- link = ui.link(folderPath,
989
- () => this.download(this.dataFrame!, this.campaignId ?? this._campaign?.name ?? 'Molecules'),
990
- i18n.download);
991
- pathDiv.appendChild(link);
992
- pathDiv.appendChild(editIcon);
993
- });
994
- const cancelButton = ui.button('Cancel', () => {
995
- ui.empty(pathDiv);
996
- pathDiv.appendChild(link);
997
- pathDiv.appendChild(editIcon);
998
- });
999
- ui.empty(pathDiv);
1000
- newPathInput.addOptions(cancelButton);
1001
- newPathInput.addOptions(saveButton);
1002
- pathDiv.appendChild(newPathInput.root);
1003
- newPathInput.input.focus();
1004
- }, 'Edit file path');
1005
- editIcon.style.marginLeft = '5px';
1006
- const folderPath = getFolderPath();
1007
- let link = ui.link(folderPath,
1008
- () => this.download(this.dataFrame!, this.campaignId ?? this._campaign?.name ?? 'Molecules'), i18n.download);
1009
- const pathDiv = ui.divH([link, editIcon], {style: {alignItems: 'center'}});
1010
- return pathDiv;
1011
- };
1012
-
1013
- const campaignName = this.campaign?.friendlyName ?? this.campaign?.name ?? this.campaignId!;
1014
- const campaignNameField = editableTableField(ui.divText(campaignName), {
1015
- tooltip: 'Edit Campaign Name',
1016
- nullable: false,
1017
- onOk: async (a) => {
1018
- this.campaign!.friendlyName = a!;
1019
- await this.saveCampaign(true);
1020
- },
1021
- validator: async (a) => !!a?.trim() ? null : 'Campaign name can not be empty',
1022
- });
1023
-
1024
-
1025
- return {
1026
- 'Name': campaignNameField,
1027
- 'Code': this.campaignId ?? this._campaign?.name,
1028
- 'Template': this.template?.name ?? 'Molecules',
1029
- 'File Path': getPathEditor(),
1030
- ...(this.campaign?.authorUserFriendlyName ? {'Author': this.campaign.authorUserFriendlyName} : {}),
1031
- ...(this.campaign?.lastModifiedUserName ? {'Last Modified By': this.campaign.lastModifiedUserName} : {}),
1032
- ...(this.campaign?.createDate ? {'Create Date': this.campaign.createDate} : {}),
1033
- ...campaignProps,
1034
- 'Number of Molecules': (this.dataFrame!.rowCount).toString(),
1035
- 'Enrichment Methods': [this.template!.compute.descriptors.enabled ? 'descriptors' : '',
1036
- ...this.template!.compute.functions.map((func) => func.name)].filter((f) => f && f.trim() !== '').join(', '),
1037
- };
1038
- }
1039
-
1040
- private _isSaving: boolean = false;
1041
-
1042
- async saveCampaign(notify = true, isCreating = false, customProps?: Partial<HitDesignCampaign>): Promise<HitDesignCampaign> {
1043
- this._isSaving = true;
1044
- const campaignId = this.campaignId!;
1045
- const someoneElseEditingLoaderTimeout = setTimeout(() => {
1046
- if (this._designView?.grid)
1047
- ui.setUpdateIndicator(this._designView.grid.root, true, 'Someone else is saving the campaign. Please wait...');
1048
- }, 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;
1049
662
  try {
1050
- const lock = await this.aquireAndWaitCampaignLock(campaignId);
1051
- if (!lock?.aquired) // could not acquire lock
1052
- 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;
1053
691
  } catch (e) {
1054
- clearTimeout(someoneElseEditingLoaderTimeout);
1055
- if (this._designView?.grid)
1056
- ui.setUpdateIndicator(this._designView.grid.root, false);
1057
- grok.shell.error('Failed to acquire campaign lock. Someone else might be editing the campaign. Please try again later.');
1058
- this._isSaving = false;
1059
- 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);
1060
700
  }
1061
- clearTimeout(someoneElseEditingLoaderTimeout);
1062
- if (this._designView?.grid)
1063
- ui.setUpdateIndicator(this._designView.grid.root, true, 'Saving Campaign...');
1064
- // await DG.delay(3000); // artificial delay to simulate long save
701
+ }
1065
702
 
1066
- const templateName = this.template!.name;
1067
- const enrichedDf = this.dataFrame!;
1068
- 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));
1069
708
  const columnSemTypes: {[_: string]: string} = {};
1070
- enrichedDf.columns.toList().forEach((col) => columnSemTypes[col.name] = col.semType);
1071
709
  const colTypeMap: {[_: string]: string} = {};
1072
- enrichedDf.columns.toList().forEach((col) => colTypeMap[col.name] = col.type);
1073
- const sketchStateString = this.campaign?.tilesViewerFormSketch ?? undefined;
710
+ const columnTags: {[_: string]: {[_: string]: string}} = {};
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
+ }
1074
718
 
1075
719
  const getDefaultPerms = async () => {
1076
720
  try {
@@ -1087,80 +731,46 @@ export class HitDesignApp<T extends HitDesignTemplate = HitDesignTemplate> exten
1087
731
  }
1088
732
  return defaultPermissions;
1089
733
  };
734
+ const previous = save.campaign;
1090
735
  // if its first time save author as current user, else keep the same
1091
- const authorUserId = this.campaign?.authorUserId ?? grok.shell.user.id;
1092
- const permissions = this.campaign?.permissions ?? await getDefaultPerms();
1093
- const authorName = authorUserId ? this.campaign?.authorUserFriendlyName ?? (await grok.dapi.users.find(authorUserId))?.friendlyName : undefined;
1094
- const campaign: HitDesignCampaign = {
1095
- name: campaignName,
1096
- friendlyName: this.campaign?.friendlyName ?? customProps?.friendlyName ?? campaignName,
1097
- templateName,
1098
- status: this.campaign?.status ?? 'In Progress',
1099
- createDate: this.campaign?.createDate ?? toFormatedDateString(new Date()),
1100
- 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,
1101
747
  columnSemTypes,
1102
- rowCount: enrichedDf.rowCount,
1103
- filteredRowCount: enrichedDf.filter.trueCount,
1104
- savePath: this._filePath,
748
+ rowCount: df.rowCount,
749
+ filteredRowCount: df.filter.trueCount,
750
+ savePath: save.filePath,
1105
751
  columnTypes: colTypeMap,
1106
- tilesViewerFormSketch: sketchStateString,
1107
- version: this.version + 1,
752
+ columnTags,
753
+ version: (previous?.version ?? 0) + 1,
1108
754
  authorUserId,
1109
755
  authorUserFriendlyName: authorName,
1110
756
  lastModifiedUserName: grok.shell.user.friendlyName,
1111
757
  permissions,
1112
- mergeConfig: this.campaign?.mergeConfig,
1113
758
  };
1114
- if (!this.hasEditPermission) {
1115
- grok.shell.error('You do not have permission to modify this campaign');
1116
- if (this._designView?.grid)
1117
- ui.setUpdateIndicator(this._designView.grid.root, false);
1118
- await this.releaseCampaignLock(campaignId);
1119
- this._isSaving = false;
1120
- return campaign;
1121
- }
1122
- const campaignPath = `${this.appName}/campaigns/${campaignId}/${CampaignJsonName}`;
1123
- // check if someone already saved the campaign
1124
- let resDf = enrichedDf;
1125
-
1126
-
1127
- if (await _package.files.exists(campaignPath)) {
1128
- const prevCamp: HitDesignCampaign = JSON.parse(await _package.files.readAsText(campaignPath));
1129
- if ((prevCamp.version ?? 0) > this.version) {
1130
- campaign.version = Math.max(this.version, (prevCamp.version ?? 0)) + 1;
1131
- if (await grok.dapi.files.exists(this._filePath)) {
1132
- try {
1133
- const prevCampDf = await grok.dapi.files.readCsv(this._filePath);
1134
- const joined = this.unionDataframes(prevCampDf, enrichedDf, this.molColName, this.molColName);
1135
- resDf = joined;
1136
- } catch (e) {
1137
- console.error(e);
1138
- }
1139
- }
1140
- }
1141
- }
1142
- const csvDf = DG.DataFrame.fromColumns(
1143
- resDf.columns.toList().filter((col) => !col.name.startsWith('~')),
1144
- ).toCsv();
1145
- await grok.dapi.files.writeAsText(this._filePath, csvDf);
1146
- const newLayout = this._designView!.saveLayout();
1147
- if (!newLayout)
1148
- grok.shell.warning('Layout cound not be saved');
1149
- else
1150
- campaign.layout = newLayout.viewState;
1151
- campaign.template = this.template;
759
+ }
1152
760
 
1153
- await _package.saveCampaignJson(this.appName, campaign);
1154
- notify && grok.shell.info('Campaign saved successfully.');
1155
- !notify && isCreating && grok.shell.info('Campaign created successfully.');
1156
- this.campaign = campaign;
1157
- this.designViewName = campaign.friendlyName ?? campaign.name;
1158
- const updatedAt = await this.releaseCampaignLock(campaignId);
1159
- this._lastExpiresTimeString = updatedAt;
1160
- if (this._designView?.grid)
1161
- ui.setUpdateIndicator(this._designView.grid.root, false);
1162
- this._isSaving = false;
1163
- this._refreshIconTooltip = 'Refresh Campaign';
1164
- 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;
1165
775
  }
1166
776
  }