@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
@@ -0,0 +1,331 @@
1
+ /* The New Template view of Hit Design and PeptiHit: one page, in this order — Details (Name, Key, Layout),
2
+ Additional fields, Stages, Compute, Submit — over a footer that stays in view, with a line saying what CREATE makes
3
+ or why it cannot yet, CANCEL and CREATE. A clone starts from a template under a name and a key no template has, and
4
+ keeps its fields, stages, compute, submit function and layout. */
5
+ import * as grok from 'datagrok-api/grok';
6
+ import * as ui from 'datagrok-api/ui';
7
+ import * as DG from 'datagrok-api/dg';
8
+ import {BoolInput, ChoiceInput, Control, Form, Page, RecordsInput, Section, TextInput, batch, button, component,
9
+ computed, confirmDialog, div, on, signal, statusLine, untracked} from '@datagrok-libraries/u2';
10
+ import {ViewHost, fromDartInput} from '@datagrok-libraries/u2/dg';
11
+ import {_package} from '../../package';
12
+ import {AppName, CampaignFieldTypes, ComputeFunctions, HitDesignTemplate, HitTriageCampaignField,
13
+ TemplateCompute} from '../types';
14
+ import {HitTriageSubmitTag, HTFunctionOrderingLSKey, i18n} from '../consts';
15
+ import {getFuncPackageNameSafe} from '../utils';
16
+ import {descriptorsTree, rerunOnOpenOption} from '../dialogs/functions-dialog';
17
+ import {TemplateLayout, layoutFile, layoutFileInput, readLayout} from '../accordeons/layout-input';
18
+ import {computeEditor} from './compute-editor';
19
+ import type {HitAppBase} from '../hit-app-base';
20
+
21
+ export interface TemplateEditorRequest<T extends HitDesignTemplate> {
22
+ app: HitAppBase<unknown>;
23
+ /** Clone: the template the new one starts from. */
24
+ preset?: T;
25
+ /** Runs once the template file is written, before the editor closes. */
26
+ onCreated: (template: T) => unknown;
27
+ }
28
+
29
+ /** Opens the New Template view over the current one, the app's landing. Its crumb leads back there and closes the
30
+ * editor, as it always did — after asking, once something was typed into it. */
31
+ export async function openTemplateEditor<T extends HitDesignTemplate>(request: TemplateEditorRequest<T>):
32
+ Promise<void> {
33
+ const {app, preset} = request;
34
+ const parent = grok.shell.v;
35
+ ui.setUpdateIndicator(parent.root, true);
36
+ try {
37
+ const existing = await existingTemplates(app.appName);
38
+ let closing = false;
39
+ const close = () => {
40
+ closing = true;
41
+ view.close();
42
+ };
43
+ let editor!: Control & TemplateEditor;
44
+ const view = ViewHost.create({name: i18n.createNewTemplate, content: () => {
45
+ editor = templateEditor<T>({app: app.appName, preset, existing,
46
+ functions: app.computeFunctions, cancel: close,
47
+ created: async (template) => {
48
+ try {
49
+ await request.onCreated(template);
50
+ }
51
+ catch (e) {
52
+ grok.shell.error(`Template ${template.name} was created, but the app could not show it: ` +
53
+ `${e instanceof Error ? e.message : e}`);
54
+ }
55
+ close();
56
+ }});
57
+ return {root: editor, path: `${new URL(app.baseUrl).pathname}/new-template`};
58
+ }}).view;
59
+ view.parentView = parent;
60
+ view.parentCall = app.parentCall;
61
+ view.helpUrl = `${_package.webRoot}${app.appName === 'PeptiHit' ? 'README_PH.md' : 'README_HD.md'}#templates`;
62
+ grok.shell.addView(view);
63
+ const leave = async () => {
64
+ if (!editor.dirty || await confirmDialog({title: 'Discard the new template?', name: 'discard-template',
65
+ message: 'What you filled in for the new template is not saved.', confirmText: 'Discard', destructive: true}))
66
+ close();
67
+ else
68
+ grok.shell.v = view;
69
+ };
70
+ // the crumb (or any way back) to the landing leaves the editor; another view leaves it open behind
71
+ let current = true;
72
+ editor.subscribe(grok.events.onCurrentViewChanged, () => {
73
+ const now = grok.shell.v;
74
+ const left = current && !closing && now?.dart === parent.dart &&
75
+ Array.from(grok.shell.views).some((v) => v.dart === view.dart);
76
+ current = now?.dart === view.dart;
77
+ if (left)
78
+ void leave();
79
+ });
80
+ }
81
+ catch (e) {
82
+ grok.shell.error(`Could not open the template editor: ${e instanceof Error ? e.message : e}`);
83
+ } finally {
84
+ ui.setUpdateIndicator(parent.root, false);
85
+ }
86
+ }
87
+
88
+ interface TemplateId {
89
+ name: string;
90
+ key: string;
91
+ }
92
+
93
+ export interface TemplateEditorOptions<T extends HitDesignTemplate> {
94
+ app: AppName;
95
+ preset?: T;
96
+ /** The app's templates: a new one takes a name and a key none of them has. */
97
+ existing: TemplateId[];
98
+ functions: ComputeFunctions;
99
+ cancel: () => void;
100
+ created: (template: T) => Promise<unknown>;
101
+ }
102
+
103
+ const NO_COMPUTE: TemplateCompute = {descriptors: {enabled: false, args: []}, functions: [], scripts: [], queries: []};
104
+ const FIELD_TYPES = Object.keys(CampaignFieldTypes);
105
+
106
+ export interface TemplateEditor {
107
+ /** Something was typed or picked: an input edited, a row added, removed or moved, a descriptor picked. */
108
+ readonly dirty: boolean;
109
+ }
110
+
111
+ export function templateEditor<T extends HitDesignTemplate>(options: TemplateEditorOptions<T>):
112
+ Control & TemplateEditor {
113
+ return component((self) => {
114
+ // the names and keys taken, trimmed and in lower case; a key by the template that has it
115
+ const names = new Set<string>();
116
+ const keys = new Map<string, string>();
117
+ const submitFuncs = submitFunctions();
118
+ const reading = signal(false);
119
+ const busy = signal(false);
120
+ const edited = signal(false);
121
+ let reads = 0;
122
+ remember(options.existing);
123
+ const preset = options.preset;
124
+ const layout = signal<TemplateLayout | null>(preset?.layoutViewState ?
125
+ {viewState: preset.layoutViewState, localPath: preset.localLayoutPath ?? null} : null);
126
+
127
+ const form = new Form();
128
+ const nameInput = new TextInput({label: 'Name', name: 'name', required: true, tooltipText: 'Template name',
129
+ value: preset ? freeName(preset.name, names) : ''});
130
+ nameInput.addValidator((v) => names.has(v.trim().toLowerCase()) ?
131
+ 'A template with this name already exists' : null);
132
+ const keyInput = new TextInput({label: 'Key', name: 'key', required: true,
133
+ tooltipText: 'Template key used for campaign prefix',
134
+ value: preset ? freeKey(preset.key, new Set(keys.keys())) : ''});
135
+ keyInput.addValidator((v) => {
136
+ const owner = keys.get(v.trim().toLowerCase());
137
+ return owner === undefined ? null : `${v.trim()} is used by ${owner}`;
138
+ });
139
+
140
+ const picker = layoutFileInput();
141
+ picker.setTooltip('Select a layout file');
142
+ const carried = layout.peek();
143
+ if (carried !== null)
144
+ picker.value = layoutFile(carried, preset!.name);
145
+ const layoutInput = fromDartInput(picker, 'layout', {fill: true});
146
+ layoutInput.addValidator((file) => file !== null && !reading.value && layout.value === null ?
147
+ 'Not a layout file' : null);
148
+ layoutInput.effect(() => {
149
+ const file = layoutInput.value;
150
+ untracked(() => void readLayoutFile(file));
151
+ });
152
+
153
+ const fields = new RecordsInput<HitTriageCampaignField>({label: '', name: 'fields', addText: 'Add field',
154
+ value: preset?.campaignFields ?? [], newItem: () => ({name: '', type: 'String', required: false}),
155
+ rowName: (f, i) => f.name || `Field ${i + 1}`,
156
+ columns: [
157
+ {name: 'name', header: 'Name', input: (v) => new TextInput({inline: true, value: v ?? ''})},
158
+ {name: 'type', header: 'Type', width: '120px',
159
+ input: (v) => new ChoiceInput({inline: true, nullable: false, items: FIELD_TYPES, value: v ?? 'String'})},
160
+ {name: 'required', header: 'Required', width: '64px',
161
+ input: (v) => new BoolInput({inline: true, value: v === true})},
162
+ ]});
163
+ const stages = new RecordsInput<{name: string}>({label: '', name: 'stages', addText: 'Add stage',
164
+ orderable: true, value: (preset?.stages ?? []).map((name) => ({name})), newItem: () => ({name: ''}),
165
+ rowName: (_, i) => `Stage ${i + 1}`,
166
+ columns: [{name: 'name', header: 'Name', input: (v) => new TextInput({inline: true, value: v ?? ''})}]});
167
+
168
+ const submit = preset?.submit;
169
+ const presetSubmit = submit === undefined ? undefined : submitFuncs.find((f) => f.name === submit.fName &&
170
+ (!submit.package || getFuncPackageNameSafe(f) === submit.package));
171
+ const submitInput = new ChoiceInput({label: 'Submit function', name: 'submit-function', nullable: true,
172
+ tooltipText: 'Select function to be called upon submitting', value: presetSubmit?.nqName ?? null,
173
+ items: submitFuncs.map((f) => ({value: f.nqName, label: f.friendlyName ?? f.name}))});
174
+
175
+ const compute = computeEditor({functions: options.functions, value: preset?.compute ?? NO_COMPUTE,
176
+ descriptors: descriptorsTree, orderKey: HTFunctionOrderingLSKey, rerunOnOpen: rerunOnOpenOption});
177
+
178
+ const section = (title: string, hint?: string): HTMLElement => {
179
+ const s = new Section({title, hint, collapsible: false});
180
+ form.addElement(s.root);
181
+ return s.body;
182
+ };
183
+ const details = section('Details');
184
+ form.add(nameInput, details).add(keyInput, details).add(layoutInput, details);
185
+ form.add(fields, section('Additional fields', 'filled in by people when they start a campaign'));
186
+ form.add(stages, section('Stages', 'new molecules start in the first stage'));
187
+ section('Compute', 'calculated for every molecule').append(compute.root);
188
+ form.add(submitInput, section('Submit'));
189
+
190
+ const missing = computed(() => [nameInput, keyInput].filter((i) => i.value.trim() === '')
191
+ .map((i) => i.label));
192
+ const quiet = computed(() => {
193
+ const key = keyInput.value.trim();
194
+ return missing.value.length > 0 ? `Fill in ${missing.value.join(' and ')} to create the template` :
195
+ `Creates template "${nameInput.value.trim()}"; campaigns get codes ${key}-1, ${key}-2, …`;
196
+ });
197
+ const create = button(i18n.createTemplate, () => void createTemplate(), {primary: true,
198
+ disabled: computed(() => busy.value ? 'Creating the template…' :
199
+ reading.value ? 'Reading the layout…' : form.problem.value)});
200
+ const page = new Page({content: form, maxWidth: 820, labelColumn: false});
201
+ form.addButtons((row) => row.append(statusLine(form.shownProblem, quiet),
202
+ button(i18n.cancel, () => options.cancel()), create), {host: page.footer});
203
+ const root = div([page], 'hit-triage-template-editor');
204
+
205
+ // typing and picking reach the root as input and change events; rows added, removed or moved do not
206
+ for (const type of ['input', 'change'])
207
+ on(root, type, () => edited.value = true);
208
+ let first = true;
209
+ self.effect(() => {
210
+ fields.value;
211
+ stages.value;
212
+ if (!first)
213
+ untracked(() => edited.value = true);
214
+ first = false;
215
+ });
216
+ return {root, get dirty() {
217
+ return edited.peek() || compute.edited.peek();
218
+ }};
219
+
220
+ /** The template the editor holds, its keys in the order the editor has always written them. */
221
+ function currentTemplate(): T {
222
+ const chosen = layout.peek();
223
+ const submitFunc = submitFuncs.find((f) => f.nqName === submitInput.peek());
224
+ return {
225
+ name: nameInput.peek().trim(),
226
+ key: keyInput.peek().trim(),
227
+ campaignFields: fields.peek().filter((f) => f.name).map((f) => ({...f, required: !!f.required})),
228
+ stages: stages.peek().map((s) => s.name).filter((s) => s),
229
+ ...chosen === null ? {} :
230
+ {layoutViewState: chosen.viewState, ...chosen.localPath === null ? {} : {localLayoutPath: chosen.localPath}},
231
+ compute: compute.read(),
232
+ ...submitFunc === undefined ? {} :
233
+ {submit: {fName: submitFunc.name, package: getFuncPackageNameSafe(submitFunc)}},
234
+ } as unknown as T;
235
+ }
236
+
237
+ async function readLayoutFile(file: DG.FileInfo | null): Promise<void> {
238
+ const read = ++reads;
239
+ reading.value = true;
240
+ const loaded = file === null ? null : await readLayout(file);
241
+ if (read !== reads || self.isDisposed)
242
+ return;
243
+ batch(() => {
244
+ layout.value = loaded;
245
+ reading.value = false;
246
+ });
247
+ layoutInput.revalidate();
248
+ }
249
+
250
+ function remember(existing: TemplateId[]): void {
251
+ for (const t of existing) {
252
+ if (t.name.trim() !== '')
253
+ names.add(t.name.trim().toLowerCase());
254
+ if (t.key.trim() !== '')
255
+ keys.set(t.key.trim().toLowerCase(), t.name);
256
+ }
257
+ }
258
+
259
+ /** Writes the template after reading the app's templates again: a name or a key another session took since the
260
+ * editor opened, or a failed write, keeps the editor open. CREATE stays busy after a write: the editor closes. */
261
+ async function createTemplate(): Promise<void> {
262
+ const template = currentTemplate();
263
+ busy.value = true;
264
+ try {
265
+ remember(await existingTemplates(options.app));
266
+ const taken = [nameInput, keyInput].filter((input) => {
267
+ input.revalidate();
268
+ return input.validity.peek() !== null;
269
+ });
270
+ if (taken.length > 0) {
271
+ busy.value = false;
272
+ for (const input of taken)
273
+ input.touch();
274
+ return;
275
+ }
276
+ await _package.files.writeAsText(`${options.app}/templates/${template.name}.json`, JSON.stringify(template));
277
+ }
278
+ catch (e) {
279
+ busy.value = false;
280
+ grok.shell.error(`Could not save template ${template.name}: ${e instanceof Error ? e.message : e}`);
281
+ return;
282
+ }
283
+ grok.shell.info('Template created successfully');
284
+ await options.created(template);
285
+ }
286
+ }, {name: 'template-editor'});
287
+ }
288
+
289
+ /** The app's templates by name and key; one that cannot be read, by name alone. */
290
+ async function existingTemplates(app: AppName): Promise<TemplateId[]> {
291
+ const folder = `${app}/templates`;
292
+ if (!await _package.files.exists(folder))
293
+ return [];
294
+ const files = (await _package.files.list(folder)).filter((f) => f.name.endsWith('.json'));
295
+ return Promise.all(files.map(async (f) => {
296
+ const name = f.name.slice(0, -5);
297
+ try {
298
+ return {name, key: String(JSON.parse(await _package.files.readAsText(f)).key ?? '')};
299
+ }
300
+ catch {
301
+ return {name, key: ''};
302
+ }
303
+ }));
304
+ }
305
+
306
+ /** The functions a campaign can be submitted to, each once. */
307
+ function submitFunctions(): DG.Func[] {
308
+ const found = DG.Func.find({meta: {role: HitTriageSubmitTag}}).concat(DG.Func.find({tags: [HitTriageSubmitTag]}));
309
+ return Array.from(new Map(found.map((f) => [f.nqName, f])).values());
310
+ }
311
+
312
+ /** "<name> (copy)", or "(copy 2)" and on when that is taken too; `taken` in lower case. */
313
+ export function freeName(name: string, taken: Set<string>): string {
314
+ for (let n = 1; ; n++) {
315
+ const candidate = n === 1 ? `${name} (copy)` : `${name} (copy ${n})`;
316
+ if (!taken.has(candidate.toLowerCase()))
317
+ return candidate;
318
+ }
319
+ }
320
+
321
+ /** The key with the next free number, as wide as its own: KHL → KHL2, KHL2 → KHL3, KHL09 → KHL10; none for none. */
322
+ export function freeKey(key: string, taken: Set<string>): string {
323
+ if (key === '')
324
+ return '';
325
+ const [, base, digits] = /^(.*?)(\d*)$/.exec(key)!;
326
+ const next = (n: number) => `${base}${String(n).padStart(digits.length, '0')}`;
327
+ let n = digits === '' ? 2 : Number(digits) + 1;
328
+ while (taken.has(next(n).toLowerCase()))
329
+ n++;
330
+ return next(n);
331
+ }
@@ -0,0 +1,154 @@
1
+ /* The New Campaign section's Template picker: the app's templates by file name, with New, Clone and Delete beside it,
2
+ and under it the new-campaign form of the template picked — built for that template alone, so a late answer for
3
+ an earlier pick never lands. An app with no template at all offers to create the first one. */
4
+ import * as grok from 'datagrok-api/grok';
5
+ import {AsyncValue, ChoiceInput, Control, Form, LabelColumn, Scope, batch, button, component, computed, confirmDialog,
6
+ div, each, emptyState, iconButton, signal, skeleton} from '@datagrok-libraries/u2';
7
+ import type {AsyncValueState, ReadonlySignal} from '@datagrok-libraries/u2';
8
+ import type {TemplateCompute} from '@datagrok-libraries/statistics/src/compute-functions/types';
9
+ import {_package} from '../../package';
10
+ import {AppName} from '../types';
11
+ import {i18n} from '../consts';
12
+ import {loadTemplate} from '../utils';
13
+
14
+ export interface CampaignTemplate {
15
+ name: string;
16
+ key: string;
17
+ compute: TemplateCompute;
18
+ }
19
+
20
+ /** The widest the picker and a template's form get, in px. */
21
+ export const PICKER_PX = 720;
22
+
23
+ /** What a template's form is built with: the label column it shares with the picker, and the scope it lives in (a
24
+ * form built after an await creates its controls there). */
25
+ export interface TemplateFormContext {
26
+ column: LabelColumn;
27
+ owner: Scope;
28
+ }
29
+
30
+ export interface TemplatePickerOptions<T extends CampaignTemplate> {
31
+ app: AppName;
32
+ /** A template saved a moment ago: picked first, and offered before the share lists its file. */
33
+ preset?: T;
34
+ /** "+" and Clone: the template editor, empty or filled from a template. */
35
+ edit: (preset?: T) => void;
36
+ form: (template: T, context: TemplateFormContext) => HTMLElement | Control | Promise<HTMLElement | Control>;
37
+ }
38
+
39
+ export interface TemplatePicker {
40
+ /** The templates offered, in the share's order; null until listed. */
41
+ readonly names: ReadonlySignal<string[] | null>;
42
+ }
43
+
44
+ export function templatePicker<T extends CampaignTemplate>(options: TemplatePickerOptions<T>):
45
+ Control & TemplatePicker {
46
+ return component((self) => {
47
+ const names = signal<string[] | null>(null);
48
+ const listing = new AsyncValue(() => list(), {debounceMs: 0});
49
+ self.effect(() => {
50
+ const s = listing.state.value;
51
+ if (s.kind === 'ready')
52
+ names.value = s.value;
53
+ });
54
+ const mode = computed(() => {
55
+ const s = listing.state.value;
56
+ const listed = names.value;
57
+ return s.kind === 'error' ? `error:${s.message}` : listed === null ? 'loading' :
58
+ listed.length === 0 ? 'empty' : 'ready';
59
+ });
60
+ const root = div();
61
+ each(root, () => [mode.value], (m) => m, (m) => section(m));
62
+ return {root, names};
63
+
64
+ function section(mode: string): HTMLElement {
65
+ if (mode === 'loading')
66
+ return skeleton(3);
67
+ if (mode.startsWith('error:'))
68
+ return emptyState(`Could not list the templates: ${mode.slice(6)}`, {error: true});
69
+ if (mode === 'empty') {
70
+ return emptyState('No templates yet. A template sets the fields, stages and calculations of every campaign ' +
71
+ 'made from it.', {icon: 'file-plus',
72
+ actions: [button('Create template', () => options.edit(), {primary: true})]});
73
+ }
74
+ return picker();
75
+ }
76
+
77
+ function picker(): HTMLElement {
78
+ const column = new LabelColumn();
79
+ const form = new Form({labelColumn: column, maxWidth: PICKER_PX});
80
+ // never empty, so no required asterisk
81
+ const input = new ChoiceInput({label: i18n.selectTemplate, name: 'template', nullable: false, required: false,
82
+ items: computed(() => names.value ?? []), value: options.preset?.name ?? names.peek()![0]});
83
+ const picked = new AsyncValue<T>(() => read(input.peek()!),
84
+ {deps: () => input.value, debounceMs: 0});
85
+ input.addOptions(iconButton('plus', () => options.edit(), {tooltip: i18n.createNewTemplate}));
86
+ input.addOptions(iconButton('copy', () => {
87
+ const template = picked.peek();
88
+ if (template !== undefined)
89
+ options.edit(template);
90
+ }, {tooltip: 'Clone template'}));
91
+ input.addOptions(iconButton('trash-alt', () => void remove(input), {tooltip: 'Delete template',
92
+ disabled: computed(() => (names.value?.length ?? 0) < 2 ? 'The last template cannot be deleted' : null)}));
93
+ form.add(input);
94
+ const host = div([]);
95
+ each(host, () => [picked.state.value], (s) => s.kind === 'ready' ? `ready:${s.value.name}` : s.kind,
96
+ (s) => templateForm(s, column));
97
+ return div([form.root, host]);
98
+ }
99
+
100
+ function templateForm(state: AsyncValueState<T>, column: LabelColumn): HTMLElement {
101
+ if (state.kind === 'error')
102
+ return emptyState(`Could not read the template: ${state.message}`, {error: true});
103
+ if (state.kind !== 'ready')
104
+ return skeleton(3);
105
+ const owner = Scope.ambient!;
106
+ const built = options.form(state.value, {column, owner});
107
+ if (!(built instanceof Promise))
108
+ return Control.is(built) ? built.root : built;
109
+ const slot = div([skeleton(3)]);
110
+ built.then((el) => {
111
+ if (!owner.isDisposed)
112
+ slot.replaceChildren(Control.is(el) ? el.root : el);
113
+ }, (e) => {
114
+ if (!owner.isDisposed) {
115
+ slot.replaceChildren(emptyState(`Could not build the form: ${e instanceof Error ? e.message : e}`,
116
+ {error: true}));
117
+ }
118
+ });
119
+ return slot;
120
+ }
121
+
122
+ async function list(): Promise<string[]> {
123
+ const folder = `${options.app}/templates`;
124
+ const listed = !await _package.files.exists(folder) ? [] : (await _package.files.list(folder))
125
+ .filter((file) => file.name.endsWith('.json'))
126
+ .map((file) => file.name.slice(0, -5));
127
+ const preset = options.preset?.name;
128
+ return preset !== undefined && !listed.includes(preset) ? [...listed, preset] : listed;
129
+ }
130
+
131
+ async function read(name: string): Promise<T> {
132
+ const preset = options.preset;
133
+ return preset?.name === name ? preset : await loadTemplate<T>(`${options.app}/templates/${name}.json`);
134
+ }
135
+
136
+ async function remove(input: ChoiceInput): Promise<void> {
137
+ const name = input.peek();
138
+ if (name === null)
139
+ return;
140
+ const deleted = await confirmDialog({title: 'Delete template', name: 'delete-template', confirmText: 'Delete',
141
+ destructive: true, message: `Are you sure you want to delete template ${name}?`,
142
+ detail: 'Campaigns made from it keep working.',
143
+ onConfirm: () => _package.files.delete(`${options.app}/templates/${name}.json`)});
144
+ if (!deleted)
145
+ return;
146
+ const rest = (names.peek() ?? []).filter((n) => n !== name);
147
+ batch(() => {
148
+ names.value = rest;
149
+ input.value = rest[0] ?? null;
150
+ });
151
+ grok.shell.info(`Template ${name} was deleted successfully`);
152
+ }
153
+ }, {name: 'template-picker'});
154
+ }
package/src/app/types.ts CHANGED
@@ -125,6 +125,8 @@ export type HitDesignMergeConfig = {
125
125
  export type HitDesignCampaign = Omit<HitTriageCampaign, 'filters' | 'ingest'> & {
126
126
  tilesViewerFormSketch?: string,
127
127
  mergeConfig?: HitDesignMergeConfig,
128
+ // the CSV table carries no column metadata
129
+ columnTags?: {[colName: string]: {[tag: string]: string}},
128
130
  };
129
131
 
130
132
  // todo: probably add some more stuff