@datagrok/hit-triage 1.10.9 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/.grokignore +2 -0
  2. package/.turbo/turbo-build.log +25 -3
  3. package/CHANGELOG.md +78 -0
  4. package/CLAUDE.md +87 -10
  5. package/README_HD.md +14 -14
  6. package/README_HT.md +6 -6
  7. package/README_PH.md +110 -0
  8. package/bdd/bdd.config.json +3 -1
  9. package/bdd/bindings/campaign.ts +626 -0
  10. package/bdd/bindings/hit-design.ts +36 -42
  11. package/bdd/bindings/landing.ts +839 -0
  12. package/bdd/bindings/pepti-hit.ts +35 -0
  13. package/bdd/features/campaign/crumbs.feature +22 -0
  14. package/bdd/features/campaign/grid.feature +56 -0
  15. package/bdd/features/campaign/merge.feature +105 -0
  16. package/bdd/features/campaign/molecule-vid.feature +40 -0
  17. package/bdd/features/campaign/permissions.feature +46 -0
  18. package/bdd/features/campaign/progress-tracker.feature +89 -0
  19. package/bdd/features/campaign/refresh-hint.feature +33 -0
  20. package/bdd/features/campaign/ribbon.feature +49 -0
  21. package/bdd/features/campaign/stage-choices.feature +39 -0
  22. package/bdd/features/campaign/submit.feature +135 -0
  23. package/bdd/features/campaign/tracker-cards.feature +46 -0
  24. package/bdd/features/campaign/view-only.feature +37 -0
  25. package/bdd/features/landing/campaign-deep-links.feature +61 -0
  26. package/bdd/features/landing/hit-design-campaigns-fixes.feature +116 -0
  27. package/bdd/features/landing/hit-design-campaigns.feature +153 -0
  28. package/bdd/features/landing/hit-triage-campaigns.feature +99 -0
  29. package/bdd/features/landing/new-campaign.feature +69 -0
  30. package/bdd/features/landing/pep-triage-campaigns.feature +41 -0
  31. package/bdd/features/landing/pepti-hit-landing.feature +132 -0
  32. package/bdd/features/pepti-hit/helm-edit.feature +47 -0
  33. package/bdd/features/templates/template-editor.feature +130 -0
  34. package/bdd/features/templates/template-picker.feature +112 -0
  35. package/bdd/features/templates/triage-forms.feature +59 -0
  36. package/bdd/fixtures/bar-chart.layout +1 -0
  37. package/bdd/fixtures/merge-local.csv +2 -0
  38. package/bdd/generated/campaign/crumbs.test.ts +33 -0
  39. package/bdd/generated/campaign/grid.test.ts +79 -0
  40. package/bdd/generated/campaign/merge.test.ts +134 -0
  41. package/bdd/generated/campaign/molecule-vid.test.ts +52 -0
  42. package/bdd/generated/campaign/permissions.test.ts +58 -0
  43. package/bdd/generated/campaign/progress-tracker.test.ts +129 -0
  44. package/bdd/generated/campaign/refresh-hint.test.ts +44 -0
  45. package/bdd/generated/campaign/ribbon.test.ts +65 -0
  46. package/bdd/generated/campaign/stage-choices.test.ts +55 -0
  47. package/bdd/generated/campaign/submit.test.ts +167 -0
  48. package/bdd/generated/campaign/tracker-cards.test.ts +49 -0
  49. package/bdd/generated/campaign/view-only.test.ts +51 -0
  50. package/bdd/generated/hit-design/campaign-column-metadata.test.ts +1 -0
  51. package/bdd/generated/landing/campaign-deep-links.test.ts +68 -0
  52. package/bdd/generated/landing/hit-design-campaigns-fixes.test.ts +99 -0
  53. package/bdd/generated/landing/hit-design-campaigns.test.ts +160 -0
  54. package/bdd/generated/landing/hit-triage-campaigns.test.ts +107 -0
  55. package/bdd/generated/landing/new-campaign.test.ts +78 -0
  56. package/bdd/generated/landing/pep-triage-campaigns.test.ts +52 -0
  57. package/bdd/generated/landing/pepti-hit-landing.test.ts +130 -0
  58. package/bdd/generated/pepti-hit/helm-edit.test.ts +64 -0
  59. package/bdd/generated/templates/template-editor.test.ts +137 -0
  60. package/bdd/generated/templates/template-picker.test.ts +119 -0
  61. package/bdd/generated/templates/triage-forms.test.ts +68 -0
  62. package/css/hit-triage.css +27 -23
  63. package/dist/package-test.js +690 -4
  64. package/dist/package-test.js.map +1 -1
  65. package/dist/package.js +318 -73
  66. package/dist/package.js.map +1 -1
  67. package/package.json +11 -7
  68. package/queries/locks.sql +37 -0
  69. package/src/app/accordeons/layout-input.ts +52 -44
  70. package/src/app/accordeons/new-campaign-accordeon.ts +91 -54
  71. package/src/app/accordeons/new-hit-design-campaign-accordeon.ts +3 -67
  72. package/src/app/accordeons/new-pep-triage-template-accordeon.ts +39 -41
  73. package/src/app/accordeons/new-template-accordeon.ts +41 -24
  74. package/src/app/ai/view-functions.ts +22 -19
  75. package/src/app/base-view.ts +99 -8
  76. package/src/app/consts.ts +8 -5
  77. package/src/app/dialogs/functions-dialog.ts +14 -9
  78. package/src/app/dialogs/merge-table-dialog.ts +181 -325
  79. package/src/app/hit-app-base.ts +61 -90
  80. package/src/app/hit-design-app.ts +481 -886
  81. package/src/app/hit-design-views/info-view.ts +57 -407
  82. package/src/app/hit-design-views/submit-view.ts +216 -111
  83. package/src/app/hit-design-views/tiles-view.ts +168 -123
  84. package/src/app/hit-design-views/utils.css +0 -8
  85. package/src/app/hit-triage-app.ts +69 -38
  86. package/src/app/hit-triage-views/info-view.ts +70 -371
  87. package/src/app/pep-triage-app.ts +2 -2
  88. package/src/app/pep-triage-views/info-view.ts +42 -83
  89. package/src/app/pepti-hit-app.ts +32 -183
  90. package/src/app/pepti-hits-views/info-view.ts +15 -37
  91. package/src/app/shared/campaign-catalog.ts +408 -0
  92. package/src/app/shared/campaign-session.ts +557 -0
  93. package/src/app/shared/compute-editor.ts +274 -0
  94. package/src/app/shared/hit-home.ts +45 -0
  95. package/src/app/shared/new-campaign-form.ts +90 -0
  96. package/src/app/shared/permissions-editor.ts +93 -0
  97. package/src/app/shared/template-editor.ts +331 -0
  98. package/src/app/shared/template-picker.ts +154 -0
  99. package/src/app/utils/merge-table.ts +183 -78
  100. package/src/app/utils.ts +34 -325
  101. package/src/package-api.ts +29 -8
  102. package/src/package-test.ts +17 -2
  103. package/src/package.g.ts +12 -8
  104. package/src/package.ts +19 -7
  105. package/src/tests/ai.ts +244 -0
  106. package/src/tests/campaign-layout.ts +82 -0
  107. package/src/tests/campaign-session.ts +168 -0
  108. package/src/tests/campaigns.ts +23 -0
  109. package/src/tests/catalog.ts +156 -0
  110. package/src/tests/compat.ts +482 -0
  111. package/src/tests/compute.ts +165 -0
  112. package/src/tests/fixtures.ts +359 -0
  113. package/src/tests/merge.ts +149 -0
  114. package/src/tests/owners.ts +11 -0
  115. package/src/tests/save-lock.ts +932 -0
  116. package/src/tests/storage.ts +106 -0
  117. package/src/tests/template-editor.ts +538 -0
  118. package/src/tests/templates.ts +143 -0
  119. package/src/tests/triage-start.ts +81 -0
  120. package/src/tests/u2-guards.ts +384 -0
  121. package/src/tests/vid.ts +77 -0
  122. package/src/app/accordeons/new-hit-design-template-accordeon.ts +0 -238
  123. package/src/app/dialogs/permissions-dialog.ts +0 -66
@@ -0,0 +1,408 @@
1
+ /* The campaigns table of an app's landing: the u2 CatalogTable over the campaign.json files the user may view, with
2
+ the columns, groupings and row actions of the HitTriage apps. Hit Design and PeptiHit keep their choices under the
3
+ HD* localStorage keys, Hit Triage and PepTriage under the HT* ones, in the formats the landings always used. */
4
+ import * as grok from 'datagrok-api/grok';
5
+ import * as DG from 'datagrok-api/dg';
6
+ import {AsyncValue, CatalogTable, SortOrder, confirmDialog, computed, divH, dot, plural, signal, span}
7
+ from '@datagrok-libraries/u2';
8
+ import type {Action, BadgeVariant, CatalogAccess, CatalogColumn, CatalogGrouping, CatalogPersistence, CatalogState,
9
+ ReadonlySignal} from '@datagrok-libraries/u2';
10
+ import {_package} from '../../package';
11
+ import * as api from '../../package-api';
12
+ import {AppName, HitDesignCampaign, HitTriageCampaign} from '../types';
13
+ import {CampaignGrouping, CampaignJsonName, DefaultCampaignTableInfoGetters, HDCampaignsCollapsedLSKey,
14
+ HDCampaignsGroupingLSKey, HDCampaignsTableSortingLSKey, HDCampaignTableColumnsLSKey, HDDefaultCampaignTableColumns,
15
+ HTCampaignsCollapsedLSKey, HTCampaignsGroupingLSKey, HTCampaignsTableSortingLSKey, HTCampaignTableColumnsLSKey,
16
+ HTDefaultCampaignTableColumns, HTDefaultCampaignTableInfoGetters, i18n, LastModifiedByColumn} from '../consts';
17
+ import {checkEditPermissions, MembershipCache} from '../utils';
18
+ import {defaultPermissions, PermissionsEditor} from './permissions-editor';
19
+
20
+ export type AnyCampaign = HitDesignCampaign | HitTriageCampaign;
21
+
22
+ /** Hit Design and PeptiHit ('HD'), Hit Triage and PepTriage ('HT'): each pair shares its table settings. */
23
+ export type CampaignFamily = 'HD' | 'HT';
24
+
25
+ interface Family {
26
+ keys: {grouping: string, columns: string, sorting: string, collapsed: string};
27
+ getters: {[column: string]: (c: AnyCampaign) => string};
28
+ defaultColumns: string[];
29
+ counts: string[];
30
+ /** The last save of each campaign is in hitdesign.update_logs. */
31
+ saveLog: boolean;
32
+ }
33
+
34
+ const FAMILIES: {[f in CampaignFamily]: Family} = {
35
+ HD: {keys: {grouping: HDCampaignsGroupingLSKey, columns: HDCampaignTableColumnsLSKey,
36
+ sorting: HDCampaignsTableSortingLSKey, collapsed: HDCampaignsCollapsedLSKey},
37
+ getters: DefaultCampaignTableInfoGetters as Family['getters'], defaultColumns: HDDefaultCampaignTableColumns,
38
+ counts: ['Molecules'], saveLog: true},
39
+ HT: {keys: {grouping: HTCampaignsGroupingLSKey, columns: HTCampaignTableColumnsLSKey,
40
+ sorting: HTCampaignsTableSortingLSKey, collapsed: HTCampaignsCollapsedLSKey},
41
+ getters: HTDefaultCampaignTableInfoGetters as unknown as Family['getters'],
42
+ defaultColumns: HTDefaultCampaignTableColumns, counts: ['Total', 'Selected'], saveLog: false},
43
+ };
44
+
45
+ const LEGACY_GROUP_KEY = 'Accordion:Hit-Design-campaigns-group-';
46
+ const LAST_MODIFIED = 'Last Modified';
47
+ const FIELD = 'campaignFields.';
48
+ const CODES = new Intl.Collator(undefined, {numeric: true});
49
+
50
+ export interface CampaignCatalogOptions {
51
+ app: AppName;
52
+ family: CampaignFamily;
53
+ /** Campaigns deleted in this page: a share listing may still show their folders for a while. */
54
+ deleted: string[];
55
+ /** The name link: opens the campaign. */
56
+ open: (code: string) => unknown;
57
+ /** Deletes the campaign's files and drops it from the page's list. */
58
+ remove: (code: string) => Promise<void>;
59
+ /** How the balloons name a campaign: Hit Design by its code, Hit Triage by its name. */
60
+ label: (c: AnyCampaign) => string;
61
+ /** Every list read, the statuses of a Submit dialog's suggestions among what it feeds. */
62
+ onLoaded?: (campaigns: readonly AnyCampaign[]) => void;
63
+ /** The table's host is narrow (under 820px): a name is cut at 200px rather than 320px. */
64
+ narrow?: ReadonlySignal<boolean>;
65
+ }
66
+
67
+ export interface CampaignCatalog {
68
+ readonly table: CatalogTable<AnyCampaign>;
69
+ /** The heading's icons: columns, grouping and refresh, with the landing's tooltips. */
70
+ chrome(): HTMLElement[];
71
+ /** Reads the list again: from the page's copy, or with `fresh` from the server. The rows stay meanwhile. */
72
+ reload(fresh?: boolean): Promise<void>;
73
+ }
74
+
75
+ /** The table and its data: a list read through the page's campaign cache (Refresh reads the server again), the
76
+ * order of the last save, and the user's edit rights, looked up once per group for the whole list. Built where it
77
+ * is owned: its sources go with the builder. */
78
+ export function campaignCatalog(options: CampaignCatalogOptions): CampaignCatalog {
79
+ const family = FAMILIES[options.family];
80
+ // the last list read: the campaign-field columns and groupings are made of it, and stay while a refresh runs
81
+ const known = signal<readonly AnyCampaign[]>([]);
82
+ const rights = signal<ReadonlyMap<string, boolean>>(new Map());
83
+ const access = new WeakMap<AnyCampaign, ReadonlySignal<CatalogAccess>>();
84
+ let modified = new Map<string, number>();
85
+ let freshRead = false;
86
+ let reads = 0;
87
+ const source = new AsyncValue(() => load(), {debounceMs: 0});
88
+ // a list read with the same fields keeps the same column objects, and with them the table's rows
89
+ const fields = computed(() => JSON.stringify(fieldsOf(known.value)));
90
+ const table = new CatalogTable<AnyCampaign>({
91
+ name: 'campaigns',
92
+ label: 'Campaigns',
93
+ items: source,
94
+ keyOf: (c) => c.name,
95
+ columns: computed(() => {
96
+ fields.value;
97
+ return catalogColumns(options.family, known.peek(), (c) => lastModified(c), options.narrow?.value);
98
+ }),
99
+ groupings: computed(() => {
100
+ fields.value;
101
+ return catalogGroupings(known.peek());
102
+ }),
103
+ defaultColumns: family.defaultColumns,
104
+ defaultOrder: (a, b) => lastModified(b) - lastModified(a) || CODES.compare(a.name, b.name),
105
+ emptyGroupLabel: i18n.noInformation,
106
+ actionsVisible: 'always',
107
+ access: (c) => accessOf(c),
108
+ viewOnly: {icon: 'eye', tooltip: 'View only: you can open this campaign but not change it'},
109
+ actions: (c) => actions(c),
110
+ onActivate: (c) => options.open(c.name),
111
+ empty: 'No campaigns yet. Start the first one under New Campaign.',
112
+ footer: (shown) => {
113
+ const viewOnly = shown.filter((c) => accessOf(c).value === 'view').length;
114
+ return plural(shown.length, 'campaign', 'campaigns') + (viewOnly > 0 ? ` · ${viewOnly} view only` : '');
115
+ },
116
+ refresh: () => reload(true),
117
+ persist: catalogPersistence(options.family),
118
+ });
119
+ return {
120
+ table,
121
+ chrome: () => table.chrome({columns: 'Edit visible columns in campaigns table',
122
+ group: (g) => `Group Campaigns. Current: ${g}`, refresh: 'Refresh campaigns table'}),
123
+ reload,
124
+ };
125
+
126
+ function reload(fresh = false): Promise<void> {
127
+ freshRead ||= fresh;
128
+ return source.refresh();
129
+ }
130
+
131
+ async function load(): Promise<readonly AnyCampaign[]> {
132
+ const fresh = freshRead;
133
+ freshRead = false;
134
+ const generation = ++reads;
135
+ const [campaigns, times] = await Promise.all([
136
+ _package.loadCampaigns(options.app, options.deleted, fresh), readModified()]);
137
+ const list = Object.values(campaigns) as AnyCampaign[];
138
+ // a later read is under way: its answer is the one the table takes
139
+ if (generation !== reads)
140
+ return list;
141
+ modified = times;
142
+ known.value = list;
143
+ void readRights(list, generation);
144
+ options.onLoaded?.(list);
145
+ return list;
146
+ }
147
+
148
+ /** When each campaign was saved last: its update_logs time (Hit Design, PeptiHit), else its campaign.json's; a
149
+ * source that cannot be read leaves its campaigns to their Created date. */
150
+ async function readModified(): Promise<Map<string, number>> {
151
+ const app = options.app;
152
+ const unread = (e: unknown) => {
153
+ _package.logger.error(e);
154
+ return null;
155
+ };
156
+ const [files, logs] = await Promise.all([_package.files.list(`${app}/campaigns`, true).catch(unread),
157
+ family.saveLog ? api.queries.getLastModifiedAll(app).catch(unread) : null]);
158
+ const times = new Map<string, number>();
159
+ for (const file of files ?? []) {
160
+ const time = file.updatedOn?.valueOf();
161
+ if (file.name === CampaignJsonName && time !== undefined)
162
+ times.set(file.path.split('/').slice(-2)[0], time);
163
+ }
164
+ if (logs) {
165
+ const ids = logs.col('campaign_id')!;
166
+ const at = logs.col('updated_at')!;
167
+ for (let i = 0; i < logs.rowCount; i++) {
168
+ if (!at.isNone(i))
169
+ times.set(ids.get(i), at.get(i).valueOf());
170
+ }
171
+ }
172
+ return times;
173
+ }
174
+
175
+ function lastModified(c: AnyCampaign): number {
176
+ return modified.get(c.name) ?? (Date.parse(c.createDate) || 0);
177
+ }
178
+
179
+ /** The rights of every row land together, in place of the last answer for the rows it covered. */
180
+ async function readRights(list: readonly AnyCampaign[], generation: number): Promise<void> {
181
+ const me = DG.User.current().id;
182
+ const membership: MembershipCache = new Map();
183
+ const answers = await Promise.all(list.map(async (c) => [c.name,
184
+ await checkEditPermissions(c.authorUserId ?? me, c.permissions ?? defaultPermissions, membership)] as const));
185
+ if (generation === reads)
186
+ rights.value = new Map(answers);
187
+ }
188
+
189
+ function accessOf(c: AnyCampaign): ReadonlySignal<CatalogAccess> {
190
+ let a = access.get(c);
191
+ if (a === undefined) {
192
+ a = computed(() => {
193
+ const edit = rights.value.get(c.name);
194
+ return edit === undefined ? 'pending' : edit ? 'edit' : 'view';
195
+ });
196
+ access.set(c, a);
197
+ }
198
+ return a;
199
+ }
200
+
201
+ function actions(c: AnyCampaign): Action[] {
202
+ return [
203
+ {text: 'Manage campaign permissions', icon: 'users', requires: 'edit', run: () => void share(c)},
204
+ {text: 'Delete campaign', icon: 'trash-alt', requires: 'edit', destructive: true,
205
+ run: () => void remove(c)},
206
+ ];
207
+ }
208
+
209
+ /** The landing's share writes campaign.json alone, under the campaign's lock and over what the server holds now
210
+ * (another session may have saved since the list was read), and gives an authorless campaign its first author. */
211
+ async function share(c: AnyCampaign): Promise<void> {
212
+ await PermissionsEditor.show(c.permissions, {subject: subjectOf(c),
213
+ author: c.authorUserFriendlyName, save: async (permissions) => {
214
+ const app = options.app;
215
+ const me = DG.User.current();
216
+ const lock = await api.queries.acquireCampaignLock(app, c.name, me.friendlyName || me.name);
217
+ if (!lock?.rowCount)
218
+ throw new Error('Another session is saving this campaign. Try again in a moment.');
219
+ try {
220
+ const current = JSON.parse(await _package.files.readAsText(`${app}/campaigns/${c.name}/${CampaignJsonName}`));
221
+ await _package.saveCampaignJson(app, {...current, permissions, authorUserId: current.authorUserId ?? me.id});
222
+ } finally {
223
+ await api.queries.releaseCampaignLock(app, c.name).catch((e) => _package.logger.error(e));
224
+ }
225
+ grok.shell.info('Permissions updated for campaign ' + options.label(c));
226
+ await reload();
227
+ }});
228
+ }
229
+
230
+ async function remove(c: AnyCampaign): Promise<void> {
231
+ const deleted = await confirmDialog({title: 'Delete campaign', name: 'delete-campaign', confirmText: 'Delete',
232
+ destructive: true, message: `Are you sure you want to delete campaign ${subjectOf(c, true)}?`,
233
+ detail: `Its ${plural(c.rowCount ?? 0, 'molecule', 'molecules')} and its layout are removed for everyone. ` +
234
+ 'This cannot be undone.',
235
+ onConfirm: () => options.remove(c.name)});
236
+ if (!deleted)
237
+ return;
238
+ await reload();
239
+ grok.shell.info(`Campaign ${options.label(c)} deleted`);
240
+ }
241
+ }
242
+
243
+ /** The columns: Name first, then the family's getters, the optional Last Modified and every campaign field. */
244
+ export function catalogColumns(family: CampaignFamily, campaigns: readonly AnyCampaign[],
245
+ modified: (c: AnyCampaign) => number, narrow = false): CatalogColumn<AnyCampaign>[] {
246
+ const {getters, counts} = FAMILIES[family];
247
+ const columns: CatalogColumn<AnyCampaign>[] = [{name: 'Name', value: getters['Name'], pinned: true,
248
+ link: 'Continue Campaign', maxWidth: narrow ? '200px' : '320px'}];
249
+ for (const name of Object.keys(getters).filter((g) => g !== 'Name')) {
250
+ columns.push(counts.includes(name) ?
251
+ {name, value: (c) => Number(getters[name](c)), align: 'right',
252
+ description: name === 'Selected' ? 'Rows passing the saved filters' : undefined} :
253
+ name === 'Status' ? {name, value: getters[name], render: (c) => statusCell(c.status)} :
254
+ {name, value: getters[name]});
255
+ if (name === LastModifiedByColumn) {
256
+ const at = (c: AnyCampaign) => modified(c) > 0 ? new Date(modified(c)) : null;
257
+ columns.push({name: LAST_MODIFIED, value: at, type: 'date', render: (c) => dayText(at(c))});
258
+ }
259
+ }
260
+ for (const [field, templates] of fieldsOf(campaigns)) {
261
+ columns.push({name: FIELD + field, header: field,
262
+ value: (c) => fieldValue(c.campaignFields?.[field]),
263
+ render: (c) => fieldText(c.campaignFields?.[field]), menuGroup: 'Campaign Fields',
264
+ menuDetail: templates, maxWidth: '240px'});
265
+ }
266
+ return columns;
267
+ }
268
+
269
+ /** The groupings, named as `CampaignGrouping` and `campaignFields.<field>` (the kept choice), offered under the
270
+ * captions of the columns they group by. A Template group is the template's name, trimmed and in any case: a
271
+ * campaign without a template snapshot (LCNS-3) carries the name alone, where the others carry its key too. */
272
+ export function catalogGroupings(campaigns: readonly AnyCampaign[]): CatalogGrouping<AnyCampaign>[] {
273
+ const template = (c: AnyCampaign) => (c.template?.name ?? c.templateName ?? '').trim();
274
+ const groupings: CatalogGrouping<AnyCampaign>[] = [
275
+ {name: CampaignGrouping.Template, key: (c) => template(c).toLowerCase(),
276
+ groupLabel: (_key, first) => template(first)},
277
+ {name: CampaignGrouping.Status, key: (c) => c.status},
278
+ {name: CampaignGrouping.Author, key: (c) => c.authorUserFriendlyName},
279
+ {name: CampaignGrouping.LastModifiedUser, label: LastModifiedByColumn, key: (c) => c.lastModifiedUserName},
280
+ ];
281
+ for (const [field, templates] of fieldsOf(campaigns)) {
282
+ groupings.push({name: FIELD + field, label: field,
283
+ key: (c) => fieldValue(c.campaignFields?.[field]), menuGroup: 'Campaign Fields',
284
+ menuDetail: templates, groupLabel: (_key, first) => fieldText(first.campaignFields?.[field])});
285
+ }
286
+ return groupings;
287
+ }
288
+
289
+ /** The table's choices under the family's six keys, in their formats: the grouping as text ('None' for none), the
290
+ * columns and the sort as JSON (no key for no sort), and the folded groups per grouping. The folds the platform
291
+ * accordion kept per group (`Accordion:Hit-Design-campaigns-group-<key>`) are read while there are none. A save
292
+ * writes only the keys whose choice changed, so a default nobody chose (the columns) is never frozen. */
293
+ export function catalogPersistence(family: CampaignFamily): CatalogPersistence {
294
+ const {keys, defaultColumns} = FAMILIES[family];
295
+ const json = (key: string): unknown => {
296
+ try {
297
+ return JSON.parse(localStorage.getItem(key) ?? 'null');
298
+ }
299
+ catch {
300
+ return null;
301
+ }
302
+ };
303
+ const texts = (s: CatalogState): [string, string | null][] => {
304
+ const sort = SortOrder.parse(s.sort);
305
+ return [
306
+ [keys.grouping, s.groupBy ?? CampaignGrouping.None],
307
+ [keys.columns, JSON.stringify(s.columns)],
308
+ [keys.sorting, sort ? JSON.stringify({columnName: sort.column, ascending: !sort.descending}) : null],
309
+ [keys.collapsed, JSON.stringify(s.collapsed)],
310
+ ];
311
+ };
312
+ // what each key stands for now, as the table last had it
313
+ const kept = new Map<string, string | null>();
314
+ return {
315
+ load: () => {
316
+ const grouping = localStorage.getItem(keys.grouping);
317
+ const sorting = json(keys.sorting) as {columnName?: unknown, ascending?: unknown} | null;
318
+ const state: Partial<CatalogState> = {groupBy: grouping && grouping !== CampaignGrouping.None ? grouping : null,
319
+ sort: typeof sorting?.columnName === 'string' && typeof sorting.ascending === 'boolean' ?
320
+ SortOrder.of(sorting.columnName, !sorting.ascending) : ''};
321
+ const columns = json(keys.columns);
322
+ if (Array.isArray(columns) && columns.every((c) => typeof c === 'string'))
323
+ state.columns = columns;
324
+ state.collapsed = (json(keys.collapsed) ?? legacyCollapsed(state.groupBy ?? null)) as CatalogState['collapsed'];
325
+ for (const [key, text] of texts({columns: defaultColumns, ...state} as CatalogState))
326
+ kept.set(key, text);
327
+ return state;
328
+ },
329
+ save: (s) => {
330
+ for (const [key, text] of texts(s)) {
331
+ if (kept.has(key) && kept.get(key) === text)
332
+ continue;
333
+ kept.set(key, text);
334
+ if (text === null)
335
+ localStorage.removeItem(key);
336
+ else
337
+ localStorage.setItem(key, text);
338
+ }
339
+ },
340
+ };
341
+ }
342
+
343
+ /** A campaign field as the table sorts and groups it: a Date field, in whichever shape the forms wrote it
344
+ * ({_value, isUtc, date} from the new-campaign form, {a, b, date} in older files), is a Date. An object of no known
345
+ * shape is no value, never "[object Object]". */
346
+ export function fieldValue(value: unknown): unknown {
347
+ if (value instanceof Date || value === null || typeof value !== 'object')
348
+ return value;
349
+ const raw = (value as {date?: unknown}).date ?? (value as {_value?: unknown})._value;
350
+ const date = typeof raw === 'string' || typeof raw === 'number' ? new Date(raw) : null;
351
+ return date !== null && !isNaN(date.getTime()) ? date : undefined;
352
+ }
353
+
354
+ /** A campaign field as its cell shows it: a date as the table's days are written (2026/3/30). */
355
+ export function fieldText(value: unknown): string {
356
+ const v = fieldValue(value);
357
+ return v instanceof Date ? dayText(v) : v === null || v === undefined ? '' : String(v);
358
+ }
359
+
360
+ /** A day as the campaigns write their Created date: 2026/3/30; no date, no text. */
361
+ export function dayText(d: Date | null): string {
362
+ return d === null || isNaN(d.getTime()) ? '' : `${d.getFullYear()}/${d.getMonth() + 1}/${d.getDate()}`;
363
+ }
364
+
365
+ /** A status as a coloured dot and its text. */
366
+ function statusCell(status: string | undefined): HTMLElement | string {
367
+ return status ? divH([dot(statusVariant(status)), span(status)], {gap: 's'}) : '';
368
+ }
369
+
370
+ function statusVariant(status: string): BadgeVariant {
371
+ const s = status.toLowerCase();
372
+ return s.includes('progress') ? 'accent' : s.includes('submitted') || s.includes('completed') ? 'success' :
373
+ s.includes('hold') || s.includes('queued') || s.includes('awaiting') ? 'warning' : 'default';
374
+ }
375
+
376
+ /** Every field of the campaigns, by name, with the templates that define it. */
377
+ function fieldsOf(campaigns: readonly AnyCampaign[]): [string, string][] {
378
+ const owners = new Map<string, Set<string>>();
379
+ for (const c of campaigns) {
380
+ for (const field of Object.keys(c.campaignFields ?? {}))
381
+ owners.set(field, (owners.get(field) ?? new Set()).add(c.template?.name ?? c.templateName));
382
+ }
383
+ return [...owners.keys()].sort().map((field) => [field, [...owners.get(field)!].join(', ')]);
384
+ }
385
+
386
+ /** Groups start open now: of the accordion's folds, only a group closed on purpose stays closed. */
387
+ function legacyCollapsed(groupBy: string | null): CatalogState['collapsed'] {
388
+ if (groupBy === null)
389
+ return {};
390
+ const folded = Object.keys(localStorage).filter((key) => key.startsWith(LEGACY_GROUP_KEY)).filter((key) => {
391
+ try {
392
+ return JSON.parse(localStorage.getItem(key)!)?.[key.slice(LEGACY_GROUP_KEY.length)] === false;
393
+ }
394
+ catch {
395
+ return false;
396
+ }
397
+ });
398
+ return {[groupBy]: folded.map((key) => key.slice(LEGACY_GROUP_KEY.length))};
399
+ }
400
+
401
+ /** "KHL-3 (BTK covalent follow-up)", or with `nameFirst` "BTK covalent follow-up (KHL-3)"; the code alone when it
402
+ * is the name. */
403
+ function subjectOf(c: AnyCampaign, nameFirst = false): string {
404
+ const name = c.friendlyName;
405
+ if (!name || name === c.name)
406
+ return c.name;
407
+ return nameFirst ? `${name} (${c.name})` : `${c.name} (${name})`;
408
+ }