@genesislcap/foundation-workspace 15.78.1 → 15.79.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.
@@ -1,20 +1,140 @@
1
1
  import { __awaiter } from "tslib";
2
2
  import { DI } from '@genesislcap/web-core';
3
+ /** Defaults for {@link DefaultGridRegistry}'s filter guard. */
4
+ const FILTER_SETTLE_MS = 1500;
5
+ const FILTER_GUARD_MAX_MS = 10000;
6
+ const MAX_FILTER_REAPPLIES = 3;
3
7
  /**
8
+ * Default grid registry implementation.
9
+ *
10
+ * @remarks
11
+ * Keeps a store of every grid's last known column state and filter model by key, so a workspace
12
+ * covers grids that aren't currently mounted (e.g. on another route):
13
+ * - `unregisterGrid` stores the grid's last state; `registerGrid` applies any stored state.
14
+ * - `applyAllGridsSettings` (workspace load) replaces the store with the loaded settings and
15
+ * applies them to mounted grids; unmounted ones pick theirs up when they register.
16
+ * - `getAllGridsSettings` (workspace save) returns the store with mounted grids' live state on
17
+ * top, so a grid the user never visited keeps its loaded state rather than being dropped.
18
+ *
19
+ * Filters race with the grid's own start-up. grid-pro restores its persisted filter model
20
+ * (`persist-filter-model-key`) asynchronously, up to three times — at grid ready, once
21
+ * datasource-driven columns exist, and on the datasource's `filtersRestored` — and a restore with
22
+ * nothing stored applies `{}`, clearing every filter. A filter for a column that doesn't exist yet
23
+ * is dropped. So when the registry applies a filter model it:
24
+ * 1. writes it into the grid's own filter persistence first (`filterPersistence`), so grid-pro's
25
+ * later restores, including a datasource re-init long after start-up, return the workspace's
26
+ * model rather than an older one;
27
+ * 2. arms a guard that re-applies it if a programmatic filter change (e.g. a restore that read
28
+ * storage before step 1 landed, as KV storage can) replaces it, and when the grid's columns
29
+ * change (so filters on columns that arrive late apply). The guard ends as soon as the user
30
+ * changes a filter, once the grid has been quiet for `filterSettleMs` after its last start-up
31
+ * event, and in any case after `filterGuardMaxMs`, so it never fights app code for long. It
32
+ * re-applies at most `maxFilterReapplies` times per arming, so it cannot loop.
33
+ *
34
+ * The guard can't tell grid-pro's restores from the app's own programmatic filter changes (both
35
+ * are `source: 'api'`), so an app that calls `setFilterModel` or clears filters while the guard
36
+ * runs has that change reverted. Since `{}` is saved for unfiltered grids, every grid with a
37
+ * stored entry is guarded when it registers.
38
+ *
39
+ * A saved entry without `filterModel` (a workspace saved before filters were captured) leaves the
40
+ * grid's filters alone.
4
41
  * @alpha
5
42
  */
6
43
  export class DefaultGridRegistry {
7
44
  constructor() {
45
+ /** Quiet period after the last start-up event before the filter guard ends. */
46
+ this.filterSettleMs = FILTER_SETTLE_MS;
47
+ /** Longest the filter guard runs after it is armed, however often it is re-armed. */
48
+ this.filterGuardMaxMs = FILTER_GUARD_MAX_MS;
49
+ /** Most re-applies the filter guard makes per arming. */
50
+ this.maxFilterReapplies = MAX_FILTER_REAPPLIES;
8
51
  this.grids = new Map();
9
- this.cachedSettings = new Map();
52
+ this.stored = new Map();
53
+ this.listeners = new Map();
54
+ this.guards = new Map();
55
+ /** Registrations whose first data has rendered or whose filters the user has changed. */
56
+ this.settled = new Set();
10
57
  }
11
58
  // Note: StatePersistence is not wired here to avoid a hard dependency on grid-pro.
12
- registerGrid(gridKey, gridApi, columnApi) {
13
- this.grids.set(gridKey, {
59
+ registerGrid(gridKey, gridApi, columnApi, filterPersistence) {
60
+ // Re-registering a key (e.g. the grid re-initialised with a new API) keeps what the user did on
61
+ // the outgoing instance, as unregistering would, rather than re-applying older stored state.
62
+ // grid-pro destroys the outgoing grid first, so its snapshot was taken at `gridPreDestroyed`.
63
+ const previous = this.grids.get(gridKey);
64
+ if (previous) {
65
+ this.storeSnapshot(previous);
66
+ this.detach(previous);
67
+ }
68
+ const registration = {
14
69
  gridKey,
15
70
  gridApi: gridApi,
16
71
  columnApi: columnApi,
17
- });
72
+ filterPersistence,
73
+ };
74
+ this.grids.set(gridKey, registration);
75
+ const stored = this.stored.get(gridKey);
76
+ if ((stored === null || stored === void 0 ? void 0 : stored.filterModel) !== undefined) {
77
+ this.armFilterGuard(registration);
78
+ }
79
+ this.applyStoredSettings(registration);
80
+ // A datasource-driven grid creates its columns after grid ready (from the datasource schema),
81
+ // and grid-pro restores its own `persist-column-state-key` state asynchronously then too;
82
+ // either discards state applied now. Apply the stored state again once the first data renders,
83
+ // when both have happened.
84
+ const onFirstDataRendered = () => {
85
+ this.removeListener(registration, 'firstDataRendered', onFirstDataRendered);
86
+ this.settled.add(registration);
87
+ this.touchFilterGuard(registration);
88
+ // Once the user has changed a filter (which ends the guard), keep their filters.
89
+ this.applyStoredSettings(registration, {
90
+ applyFilters: this.guardActive(registration),
91
+ });
92
+ };
93
+ // Columns that arrive late (datasource schema, new column defs) had their filters dropped.
94
+ const onGridColumnsChanged = () => {
95
+ if (this.guardActive(registration)) {
96
+ this.touchFilterGuard(registration);
97
+ this.reapplyStoredFilter(registration);
98
+ }
99
+ };
100
+ const onFilterChanged = (event) => {
101
+ var _a;
102
+ if ((_a = this.guards.get(registration)) === null || _a === void 0 ? void 0 : _a.applying) {
103
+ return;
104
+ }
105
+ if (isUserFilterChange(event)) {
106
+ this.settled.add(registration);
107
+ this.endFilterGuard(registration);
108
+ return;
109
+ }
110
+ if (this.guardActive(registration) && this.filterWasReplaced(registration)) {
111
+ this.reapplyStoredFilter(registration);
112
+ }
113
+ };
114
+ // Only the filter UI fires `filterModified` (v29 and v36 alike): the user is editing a filter.
115
+ const onFilterModified = () => {
116
+ this.settled.add(registration);
117
+ this.endFilterGuard(registration);
118
+ };
119
+ // The API stops reporting state once destroyed, so take the snapshot a re-register (grid-pro
120
+ // rebuilding its grid in place) keeps while it still can.
121
+ const onGridPreDestroyed = () => this.storeSnapshot(registration);
122
+ this.addListener(registration, 'gridPreDestroyed', onGridPreDestroyed);
123
+ this.addListener(registration, 'firstDataRendered', onFirstDataRendered);
124
+ this.addListener(registration, 'gridColumnsChanged', onGridColumnsChanged);
125
+ this.addListener(registration, 'filterChanged', onFilterChanged);
126
+ this.addListener(registration, 'filterModified', onFilterModified);
127
+ }
128
+ /** Applies the stored settings for a grid, unless it already has exactly that state. */
129
+ applyStoredSettings(registration, options) {
130
+ const stored = this.stored.get(registration.gridKey);
131
+ if (!stored) {
132
+ return;
133
+ }
134
+ const settings = (options === null || options === void 0 ? void 0 : options.applyFilters) === false ? Object.assign(Object.assign({}, stored), { filterModel: undefined }) : stored;
135
+ if (!this.hasSettings(registration, settings)) {
136
+ void this.applyGridSettings(settings);
137
+ }
18
138
  }
19
139
  getGrid(gridKey) {
20
140
  return this.grids.get(gridKey) || null;
@@ -22,21 +142,14 @@ export class DefaultGridRegistry {
22
142
  unregisterGrid(gridKey) {
23
143
  const grid = this.grids.get(gridKey);
24
144
  if (grid) {
25
- const settings = this.getGridSettings(gridKey, grid);
26
- if (settings) {
27
- this.cachedSettings.set(gridKey, settings);
28
- }
145
+ this.storeSnapshot(grid);
146
+ this.detach(grid);
29
147
  }
30
148
  this.grids.delete(gridKey);
31
149
  }
32
150
  getAllGridsSettings() {
33
- Array.from(this.grids).forEach(([key, grid]) => {
34
- const settings = this.getGridSettings(key, grid);
35
- if (settings) {
36
- this.cachedSettings.set(key, settings);
37
- }
38
- });
39
- return Array.from(this.cachedSettings.values()).filter((s) => !!s);
151
+ this.grids.forEach((grid) => this.storeSnapshot(grid));
152
+ return Array.from(this.stored.values());
40
153
  }
41
154
  applyGridSettings(gridSetting, options) {
42
155
  return __awaiter(this, void 0, void 0, function* () {
@@ -46,10 +159,10 @@ export class DefaultGridRegistry {
46
159
  return false;
47
160
  }
48
161
  const hasColumnState = gridSetting.columnState && gridSetting.columnState.length > 0;
49
- const applyColumns = !options || options.applyColumns !== false;
50
- const shouldApplyColumns = applyColumns && !!hasColumnState;
51
- if (!shouldApplyColumns) {
52
- // No column state to apply; treat as a no-op.
162
+ const shouldApplyColumns = (options === null || options === void 0 ? void 0 : options.applyColumns) !== false && !!hasColumnState;
163
+ const shouldApplyFilters = (options === null || options === void 0 ? void 0 : options.applyFilters) !== false && gridSetting.filterModel !== undefined;
164
+ if (!shouldApplyColumns && !shouldApplyFilters) {
165
+ // Nothing to apply; treat as a no-op.
53
166
  return false;
54
167
  }
55
168
  try {
@@ -63,11 +176,15 @@ export class DefaultGridRegistry {
63
176
  applyOrder: true,
64
177
  });
65
178
  }
66
- else {
179
+ else if (!shouldApplyFilters) {
67
180
  console.warn(`GridRegistry: applyColumnState not found for ${gridSetting.gridKey} (gridApi/columnApi)`);
68
181
  return false;
69
182
  }
70
183
  }
184
+ // Columns first: a filter on a column the state reveals or reorders still applies.
185
+ if (shouldApplyFilters) {
186
+ this.applyFilterModel(gridRegistration, gridSetting.filterModel);
187
+ }
71
188
  return true;
72
189
  }
73
190
  catch (error) {
@@ -76,43 +193,268 @@ export class DefaultGridRegistry {
76
193
  }
77
194
  });
78
195
  }
79
- applyAllGridsSettings(gridsSettings_1) {
80
- return __awaiter(this, arguments, void 0, function* (gridsSettings, maxRetries = 3) {
81
- for (let attempt = 0; attempt < maxRetries; attempt += 1) {
82
- const remainingSettings = [];
83
- /* oxlint-disable no-await-in-loop -- apply each grid settings snapshot in order */
84
- for (const gridSetting of gridsSettings) {
85
- const applied = yield this.applyGridSettings(gridSetting);
86
- if (!applied) {
87
- remainingSettings.push(gridSetting);
196
+ applyAllGridsSettings(gridsSettings) {
197
+ return __awaiter(this, void 0, void 0, function* () {
198
+ this.stored = new Map(gridsSettings.map((g) => [g.gridKey, g]));
199
+ /* oxlint-disable no-await-in-loop -- apply each grid settings snapshot in order */
200
+ for (const gridSetting of gridsSettings) {
201
+ const registration = this.grids.get(gridSetting.gridKey);
202
+ if (registration) {
203
+ // A grid mid start-up (or whose datasource re-initialises right after) can still restore
204
+ // an older filter over the loaded one, so a load re-arms the guard as a register does.
205
+ if (gridSetting.filterModel !== undefined) {
206
+ this.armFilterGuard(registration);
88
207
  }
208
+ yield this.applyGridSettings(gridSetting);
89
209
  }
90
- /* oxlint-enable no-await-in-loop */
91
- if (remainingSettings.length === 0 || attempt >= maxRetries - 1) {
92
- break;
93
- }
94
- gridsSettings = remainingSettings;
95
210
  }
211
+ /* oxlint-enable no-await-in-loop */
96
212
  });
97
213
  }
214
+ /**
215
+ * Writes a filter model into the grid's own persistence, then onto the grid, and records what
216
+ * the grid reports back so the guard can tell a later replacement from AG Grid's normalisation.
217
+ */
218
+ applyFilterModel(registration, filterModel) {
219
+ var _a;
220
+ try {
221
+ // Fire-and-forget is fine: grid-pro's local-storage persistence writes synchronously, and the
222
+ // guard covers a KV write that a restore's read overtakes.
223
+ void ((_a = registration.filterPersistence) === null || _a === void 0 ? void 0 : _a.setFilterModel(filterModel));
224
+ }
225
+ catch (error) {
226
+ console.warn(`GridRegistry: failed to persist filter model for ${registration.gridKey}`, error);
227
+ }
228
+ const api = registration.gridApi;
229
+ if (!(api === null || api === void 0 ? void 0 : api.setFilterModel)) {
230
+ return;
231
+ }
232
+ const guard = this.guards.get(registration);
233
+ if (guard) {
234
+ guard.applying = true;
235
+ }
236
+ try {
237
+ api.setFilterModel(filterModel);
238
+ }
239
+ finally {
240
+ if (guard) {
241
+ guard.applying = false;
242
+ guard.lastApplied = this.readFilterModel(registration);
243
+ }
244
+ }
245
+ }
246
+ reapplyStoredFilter(registration) {
247
+ var _a;
248
+ const guard = this.guards.get(registration);
249
+ const filterModel = (_a = this.stored.get(registration.gridKey)) === null || _a === void 0 ? void 0 : _a.filterModel;
250
+ if (!guard ||
251
+ filterModel === undefined ||
252
+ this.grids.get(registration.gridKey) !== registration) {
253
+ return;
254
+ }
255
+ if (this.readFilterModel(registration) === stableStringify(filterModel)) {
256
+ return;
257
+ }
258
+ if (guard.reapplies >= this.maxFilterReapplies) {
259
+ this.endFilterGuard(registration);
260
+ return;
261
+ }
262
+ guard.reapplies += 1;
263
+ this.applyFilterModel(registration, filterModel);
264
+ }
265
+ /**
266
+ * Whether the grid's filter model moved away from what the registry last applied — a stale
267
+ * restore or other programmatic change, rather than AG Grid normalising the applied model (which
268
+ * reads back the same each time).
269
+ */
270
+ filterWasReplaced(registration) {
271
+ var _a;
272
+ const guard = this.guards.get(registration);
273
+ const filterModel = (_a = this.stored.get(registration.gridKey)) === null || _a === void 0 ? void 0 : _a.filterModel;
274
+ if (!guard || filterModel === undefined) {
275
+ return false;
276
+ }
277
+ const current = this.readFilterModel(registration);
278
+ return current !== guard.lastApplied && current !== stableStringify(filterModel);
279
+ }
280
+ armFilterGuard(registration) {
281
+ const existing = this.guards.get(registration);
282
+ if (existing === null || existing === void 0 ? void 0 : existing.settleTimer) {
283
+ clearTimeout(existing.settleTimer);
284
+ }
285
+ const guard = {
286
+ hardStop: Date.now() + this.filterGuardMaxMs,
287
+ reapplies: 0,
288
+ active: true,
289
+ };
290
+ this.guards.set(registration, guard);
291
+ this.touchFilterGuard(registration);
292
+ }
293
+ /** Restarts the settle timer: the grid just did something that can precede a stale restore. */
294
+ touchFilterGuard(registration) {
295
+ const guard = this.guards.get(registration);
296
+ if (!(guard === null || guard === void 0 ? void 0 : guard.active)) {
297
+ return;
298
+ }
299
+ if (guard.settleTimer) {
300
+ clearTimeout(guard.settleTimer);
301
+ }
302
+ const remaining = guard.hardStop - Date.now();
303
+ if (remaining <= 0) {
304
+ this.endFilterGuard(registration);
305
+ return;
306
+ }
307
+ guard.settleTimer = setTimeout(() => this.endFilterGuard(registration), Math.min(this.filterSettleMs, remaining));
308
+ }
309
+ guardActive(registration) {
310
+ const guard = this.guards.get(registration);
311
+ if (!(guard === null || guard === void 0 ? void 0 : guard.active)) {
312
+ return false;
313
+ }
314
+ if (Date.now() >= guard.hardStop) {
315
+ this.endFilterGuard(registration);
316
+ return false;
317
+ }
318
+ return true;
319
+ }
320
+ endFilterGuard(registration) {
321
+ const guard = this.guards.get(registration);
322
+ if (!guard) {
323
+ return;
324
+ }
325
+ guard.active = false;
326
+ if (guard.settleTimer) {
327
+ clearTimeout(guard.settleTimer);
328
+ guard.settleTimer = undefined;
329
+ }
330
+ }
331
+ addListener(registration, type, listener) {
332
+ var _a;
333
+ const api = registration.gridApi;
334
+ if (!(api === null || api === void 0 ? void 0 : api.addEventListener)) {
335
+ return;
336
+ }
337
+ api.addEventListener(type, listener);
338
+ const list = (_a = this.listeners.get(registration)) !== null && _a !== void 0 ? _a : [];
339
+ list.push([type, listener]);
340
+ this.listeners.set(registration, list);
341
+ }
342
+ removeListener(registration, type, listener) {
343
+ var _a, _b;
344
+ (_b = (_a = registration.gridApi) === null || _a === void 0 ? void 0 : _a.removeEventListener) === null || _b === void 0 ? void 0 : _b.call(_a, type, listener);
345
+ const list = this.listeners.get(registration);
346
+ if (list) {
347
+ this.listeners.set(registration, list.filter(([t, l]) => t !== type || l !== listener));
348
+ }
349
+ }
350
+ /**
351
+ * Stores a grid's live state over its stored entry, except what the grid can't report yet:
352
+ * - nothing, once its API is destroyed (grid-pro destroys the outgoing grid before the new one
353
+ * re-registers, and a destroyed v36 API returns `undefined` rather than throwing);
354
+ * - the stored column state and filter model while the grid has no columns: before datasource
355
+ * columns exist, and after a datasource restart clears them (AG Grid then drops every filter,
356
+ * before grid-pro rebuilds the grid). With nothing stored, the filter model is left out, so the
357
+ * next registration leaves grid-pro to restore its own persisted filters;
358
+ * - the stored filter model until the first data renders or the user filters, since before that
359
+ * the grid may not have applied it yet (its columns or grid-pro's restore still pending).
360
+ */
361
+ storeSnapshot(registration) {
362
+ var _a;
363
+ if (isDestroyed(registration)) {
364
+ return;
365
+ }
366
+ let live;
367
+ try {
368
+ live = this.getGridSettings(registration.gridKey, registration);
369
+ }
370
+ catch (_b) {
371
+ // A destroyed v29 API can throw; keep what was stored.
372
+ return;
373
+ }
374
+ if (!live) {
375
+ return;
376
+ }
377
+ const stored = this.stored.get(registration.gridKey);
378
+ if (!live.columnState.length) {
379
+ live.columnState = (_a = stored === null || stored === void 0 ? void 0 : stored.columnState) !== null && _a !== void 0 ? _a : [];
380
+ live.filterModel = stored === null || stored === void 0 ? void 0 : stored.filterModel;
381
+ }
382
+ else if (!this.settled.has(registration) && (stored === null || stored === void 0 ? void 0 : stored.filterModel) !== undefined) {
383
+ live.filterModel = stored.filterModel;
384
+ }
385
+ if (live.filterModel === undefined) {
386
+ delete live.filterModel;
387
+ }
388
+ this.stored.set(registration.gridKey, live);
389
+ }
390
+ /** Removes a registration's grid listeners and stops its filter guard. */
391
+ detach(registration) {
392
+ var _a;
393
+ const api = registration.gridApi;
394
+ ((_a = this.listeners.get(registration)) !== null && _a !== void 0 ? _a : []).forEach(([type, listener]) => {
395
+ var _a;
396
+ (_a = api === null || api === void 0 ? void 0 : api.removeEventListener) === null || _a === void 0 ? void 0 : _a.call(api, type, listener);
397
+ });
398
+ this.listeners.delete(registration);
399
+ this.endFilterGuard(registration);
400
+ this.guards.delete(registration);
401
+ this.settled.delete(registration);
402
+ }
403
+ /** Whether the grid already has exactly these settings, so re-applying them is a no-op. */
404
+ hasSettings(grid, settings) {
405
+ var _a, _b, _c, _d, _e;
406
+ const current = (_c = (_b = (_a = grid.gridApi) === null || _a === void 0 ? void 0 : _a.getColumnState) === null || _b === void 0 ? void 0 : _b.call(_a)) !== null && _c !== void 0 ? _c : (_d = grid.columnApi) === null || _d === void 0 ? void 0 : _d.getColumnState();
407
+ const columnsMatch = !((_e = settings.columnState) === null || _e === void 0 ? void 0 : _e.length) ||
408
+ JSON.stringify(current !== null && current !== void 0 ? current : []) === JSON.stringify(settings.columnState);
409
+ const filtersMatch = settings.filterModel === undefined ||
410
+ this.readFilterModel(grid) === stableStringify(settings.filterModel);
411
+ return columnsMatch && filtersMatch;
412
+ }
413
+ readFilterModel(grid) {
414
+ var _a, _b, _c;
415
+ return stableStringify((_c = (_b = (_a = grid.gridApi) === null || _a === void 0 ? void 0 : _a.getFilterModel) === null || _b === void 0 ? void 0 : _b.call(_a)) !== null && _c !== void 0 ? _c : {});
416
+ }
98
417
  getGridSettings(gridKey, grid) {
99
- var _a, _b, _c, _d;
418
+ var _a, _b, _c, _d, _e;
100
419
  if (grid) {
101
420
  // Prefer Grid API if available, otherwise fall back to Column API.
102
421
  // (AG Grid's Column state is typically on ColumnApi; this is defensive.)
103
422
  const columnState = (_c = (_b = (_a = grid.gridApi) === null || _a === void 0 ? void 0 : _a.getColumnState) === null || _b === void 0 ? void 0 : _b.call(_a)) !== null && _c !== void 0 ? _c : (_d = grid.columnApi) === null || _d === void 0 ? void 0 : _d.getColumnState();
104
- const columnCount = (columnState === null || columnState === void 0 ? void 0 : columnState.length) || 0;
105
- console.log(`Saved grid settings for ${gridKey}: ${columnCount} columns`);
106
- return {
107
- gridKey: grid.gridKey,
108
- columnState: columnState || [],
109
- savedAt: new Date().toISOString(),
110
- };
423
+ const api = grid.gridApi;
424
+ // `{}` (no filters) is saved too, so loading the workspace clears filters set since.
425
+ const filterModel = (api === null || api === void 0 ? void 0 : api.getFilterModel) ? ((_e = api.getFilterModel()) !== null && _e !== void 0 ? _e : {}) : undefined;
426
+ return Object.assign(Object.assign({ gridKey: grid.gridKey, columnState: columnState || [] }, (filterModel !== undefined && { filterModel })), { savedAt: new Date().toISOString() });
111
427
  }
112
428
  console.warn(`No grid found for ${gridKey}`);
113
429
  return null;
114
430
  }
115
431
  }
432
+ /**
433
+ * Whether a `filterChanged` event came from the user: v36 tags its `source`; v29 has no `source`,
434
+ * but marks floating-filter changes (column-menu edits are caught by `filterModified`).
435
+ */
436
+ function isUserFilterChange(event) {
437
+ if (!event) {
438
+ return false;
439
+ }
440
+ if (event.afterFloatingFilter) {
441
+ return true;
442
+ }
443
+ return event.source === 'columnFilter' || event.source === 'advancedFilter';
444
+ }
445
+ /** Whether the grid's API has been destroyed (`isDestroyed` exists from AG Grid v31). */
446
+ function isDestroyed(registration) {
447
+ var _a, _b;
448
+ return !!((_b = (_a = registration.gridApi) === null || _a === void 0 ? void 0 : _a.isDestroyed) === null || _b === void 0 ? void 0 : _b.call(_a));
449
+ }
450
+ /** JSON with object keys sorted, so filter models compare equal regardless of key order. */
451
+ function stableStringify(value) {
452
+ return JSON.stringify(value, (_key, v) => v && typeof v === 'object' && !Array.isArray(v)
453
+ ? Object.fromEntries(Object.keys(v)
454
+ .sort()
455
+ .map((k) => [k, v[k]]))
456
+ : v);
457
+ }
116
458
  /**
117
459
  * DI token for grid registry.
118
460
  * @alpha
@@ -1,38 +1,62 @@
1
1
  import { __awaiter } from "tslib";
2
+ import { LayoutEmitEvents } from '@genesislcap/foundation-layout';
2
3
  import { DI } from '@genesislcap/web-core';
3
4
  const LAYOUT_DELAY = 300;
4
5
  /**
5
6
  * Default layout registry implementation.
7
+ *
8
+ * @remarks
9
+ * Keeps a store of every layout's last known config by key, so a workspace covers layouts that
10
+ * aren't currently mounted (e.g. on another route):
11
+ * - `unregisterLayout` stores the layout's last config; `registerLayout` loads any stored config
12
+ * once the layout has finished its first load (so its declared or autosaved layout doesn't
13
+ * overwrite it).
14
+ * - `applySavedLayouts` (workspace load) replaces the store with the loaded configs and loads them
15
+ * into mounted layouts; unmounted ones pick theirs up when they register.
16
+ * - `getLayoutsConfigs` (workspace save) returns the store with mounted layouts' live configs on
17
+ * top, so a layout the user never visited keeps its loaded config rather than being dropped.
6
18
  * @alpha
7
19
  */
8
20
  export class DefaultLayoutRegistry {
9
21
  constructor() {
10
22
  this.layouts = new Map();
23
+ this.stored = new Map();
24
+ /** Layouts with a stored-config load queued for their first load. */
25
+ this.waiting = new WeakSet();
11
26
  }
12
27
  registerLayout(layoutKey, layout) {
13
28
  if (!layoutKey) {
14
29
  return;
15
30
  }
16
31
  this.layouts.set(layoutKey, layout);
32
+ if (this.stored.has(layoutKey)) {
33
+ this.loadStored(layoutKey, layout);
34
+ }
17
35
  }
18
36
  unregisterLayout(layoutKey) {
37
+ const layout = this.layouts.get(layoutKey);
38
+ const config = layout && this.readLayout(layout);
39
+ if (config) {
40
+ this.stored.set(layoutKey, config);
41
+ }
19
42
  this.layouts.delete(layoutKey);
20
43
  }
21
44
  getLayoutsConfigs() {
22
- return Array.from(this.layouts).map(([key, layout]) => ({
23
- layoutKey: key,
24
- layout: layout.getLayout(),
25
- }));
45
+ this.layouts.forEach((layout, key) => {
46
+ const config = this.readLayout(layout);
47
+ if (config) {
48
+ this.stored.set(key, config);
49
+ }
50
+ });
51
+ return Array.from(this.stored).map(([layoutKey, layout]) => ({ layoutKey, layout }));
26
52
  }
27
53
  applySavedLayouts(savedLayouts) {
28
54
  return __awaiter(this, void 0, void 0, function* () {
55
+ this.stored = new Map(savedLayouts.map((s) => [s.layoutKey, s.layout]));
29
56
  savedLayouts.forEach((s) => {
30
57
  const layout = this.layouts.get(s.layoutKey);
31
58
  if (layout) {
32
- layout.loadLayout(s.layout, 'placeholder', true);
33
- }
34
- else {
35
- console.warn(`layout for ${s.layoutKey} not found`);
59
+ this.loadStored(s.layoutKey, layout);
36
60
  }
37
61
  });
38
62
  yield new Promise((resolve) => {
@@ -40,6 +64,43 @@ export class DefaultLayoutRegistry {
40
64
  });
41
65
  });
42
66
  }
67
+ /**
68
+ * A layout's config is only meaningful once it has finished its first load; before that it has
69
+ * no panes yet, and storing that would wipe the saved config.
70
+ */
71
+ readLayout(layout) {
72
+ if (!layout.hasFirstLoaded) {
73
+ return null;
74
+ }
75
+ try {
76
+ return layout.getLayout();
77
+ }
78
+ catch (error) {
79
+ console.warn('LayoutRegistry: failed to read layout config', error);
80
+ return null;
81
+ }
82
+ }
83
+ /**
84
+ * Loads a layout's stored config once it has finished its first load. The config is read at load
85
+ * time, so a workspace loaded while waiting wins, and a layout waiting already isn't queued twice;
86
+ * nothing loads into a layout that has since unregistered or been replaced under its key.
87
+ */
88
+ loadStored(layoutKey, layout) {
89
+ const load = () => {
90
+ this.waiting.delete(layout);
91
+ const stored = this.stored.get(layoutKey);
92
+ if (stored && this.layouts.get(layoutKey) === layout) {
93
+ layout.loadLayout(stored, 'placeholder', true);
94
+ }
95
+ };
96
+ if (layout.hasFirstLoaded) {
97
+ load();
98
+ }
99
+ else if (!this.waiting.has(layout)) {
100
+ this.waiting.add(layout);
101
+ layout.addEventListener(LayoutEmitEvents.firstLoaded, load, { once: true });
102
+ }
103
+ }
43
104
  }
44
105
  /**
45
106
  * DI token for layout registry.
@@ -137,17 +137,18 @@ let WorkspaceManager = class WorkspaceManager extends FoundationElement {
137
137
  }
138
138
  });
139
139
  }
140
+ /**
141
+ * Seeds every registry's store with the workspace's entries (replacing whatever was stored,
142
+ * even when a list is empty) and applies them to what's mounted; unmounted grids, layouts and
143
+ * filters pick theirs up when they register. Grids and filters are seeded before layouts:
144
+ * loading a layout rebuilds its panes, and the grids/filters inside re-register straight away.
145
+ */
140
146
  applyWorkspace(workspace) {
141
147
  return __awaiter(this, void 0, void 0, function* () {
142
- if (workspace.filters && workspace.filters.length > 0) {
143
- this.filterRegistry.applyFiltersValues(workspace.filters);
144
- }
145
- if (workspace.layouts && workspace.layouts.length > 0) {
146
- yield this.layoutRegistry.applySavedLayouts(workspace.layouts);
147
- }
148
- if (workspace.grids && workspace.grids.length > 0) {
149
- yield this.gridRegistry.applyAllGridsSettings(workspace.grids);
150
- }
148
+ var _a, _b, _c;
149
+ this.filterRegistry.applyFiltersValues((_a = workspace.filters) !== null && _a !== void 0 ? _a : []);
150
+ yield this.gridRegistry.applyAllGridsSettings((_b = workspace.grids) !== null && _b !== void 0 ? _b : []);
151
+ yield this.layoutRegistry.applySavedLayouts((_c = workspace.layouts) !== null && _c !== void 0 ? _c : []);
151
152
  });
152
153
  }
153
154
  loadWorkspace(workspaceName) {