@memberjunction/ng-base-application 6.2.0-edge.4 → 6.2.0-edge.6
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.
- package/dist/lib/__tests__/permission-constrained-boot.test.d.ts +2 -0
- package/dist/lib/__tests__/permission-constrained-boot.test.d.ts.map +1 -0
- package/dist/lib/__tests__/permission-constrained-boot.test.js +114 -0
- package/dist/lib/__tests__/permission-constrained-boot.test.js.map +1 -0
- package/dist/lib/__tests__/tab-service-url-replacement.test.d.ts +2 -0
- package/dist/lib/__tests__/tab-service-url-replacement.test.d.ts.map +1 -0
- package/dist/lib/__tests__/tab-service-url-replacement.test.js +33 -0
- package/dist/lib/__tests__/tab-service-url-replacement.test.js.map +1 -0
- package/dist/lib/__tests__/workspace-journal.test.d.ts +2 -0
- package/dist/lib/__tests__/workspace-journal.test.d.ts.map +1 -0
- package/dist/lib/__tests__/workspace-journal.test.js +317 -0
- package/dist/lib/__tests__/workspace-journal.test.js.map +1 -0
- package/dist/lib/application-manager.d.ts +21 -0
- package/dist/lib/application-manager.d.ts.map +1 -1
- package/dist/lib/application-manager.js +59 -5
- package/dist/lib/application-manager.js.map +1 -1
- package/dist/lib/tab.service.d.ts +21 -0
- package/dist/lib/tab.service.d.ts.map +1 -1
- package/dist/lib/tab.service.js +34 -0
- package/dist/lib/tab.service.js.map +1 -1
- package/dist/lib/workspace-journal.d.ts +87 -0
- package/dist/lib/workspace-journal.d.ts.map +1 -0
- package/dist/lib/workspace-journal.js +123 -0
- package/dist/lib/workspace-journal.js.map +1 -0
- package/dist/lib/workspace-state-manager.d.ts +57 -1
- package/dist/lib/workspace-state-manager.d.ts.map +1 -1
- package/dist/lib/workspace-state-manager.js +159 -11
- package/dist/lib/workspace-state-manager.js.map +1 -1
- package/dist/public-api.d.ts +1 -0
- package/dist/public-api.d.ts.map +1 -1
- package/dist/public-api.js +1 -0
- package/dist/public-api.js.map +1 -1
- package/package.json +4 -4
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/** Reads a server timestamp that may arrive as a Date or an ISO string; null when absent or unparseable. */
|
|
2
|
+
export function WorkspaceStampToEpoch(value) {
|
|
3
|
+
if (value == null) {
|
|
4
|
+
return null;
|
|
5
|
+
}
|
|
6
|
+
const ms = value instanceof Date ? value.getTime() : Date.parse(value);
|
|
7
|
+
return Number.isFinite(ms) ? ms : null;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Decides whether a journal snapshot is newer than the configuration the server returned.
|
|
11
|
+
*
|
|
12
|
+
* The journal wins only when it belongs to the same workspace row AND the server row has not
|
|
13
|
+
* been saved since the snapshot's base stamp. A server row stamped LATER than the base was
|
|
14
|
+
* saved by something this browser never saw (another device or browser tab), so the server
|
|
15
|
+
* wins. A server row stamped at or before the base is what this browser already built on —
|
|
16
|
+
* including a stale locally-cached copy of the row — so the journal, which holds every change
|
|
17
|
+
* made since, wins.
|
|
18
|
+
*
|
|
19
|
+
* One exception to "later row wins": the row is this browser's OWN save that landed after the
|
|
20
|
+
* page unloaded (its stamp moved past the base, but the browser never saw the response). The row's
|
|
21
|
+
* configuration then equals the snapshot's {@link WorkspaceJournalEntry.InFlightConfiguration},
|
|
22
|
+
* and the snapshot, which holds every change made after that save started, still wins.
|
|
23
|
+
*
|
|
24
|
+
* @param entry the journal snapshot, if any.
|
|
25
|
+
* @param workspaceId the loaded workspace row's ID, or null when the user has none.
|
|
26
|
+
* @param serverUpdatedAt the loaded row's `__mj_UpdatedAt`, or null when there is no row.
|
|
27
|
+
* @param serverConfiguration the loaded row's raw `Configuration` text, when there is a row.
|
|
28
|
+
*/
|
|
29
|
+
export function ShouldUseWorkspaceJournal(entry, workspaceId, serverUpdatedAt, serverConfiguration) {
|
|
30
|
+
if (!entry) {
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
const entryRow = entry.WorkspaceID ?? null;
|
|
34
|
+
const sameRow = entryRow === null || workspaceId === null
|
|
35
|
+
? entryRow === workspaceId
|
|
36
|
+
: entryRow.toLowerCase() === workspaceId.toLowerCase();
|
|
37
|
+
if (!sameRow) {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
if (workspaceId === null) {
|
|
41
|
+
return true; // no server row to be newer than
|
|
42
|
+
}
|
|
43
|
+
const server = WorkspaceStampToEpoch(serverUpdatedAt);
|
|
44
|
+
const base = WorkspaceStampToEpoch(entry.BaseUpdatedAt);
|
|
45
|
+
if (server === null) {
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
if (base !== null && server <= base) {
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
// The row is newer than the base (or there is no base): the snapshot still wins when that row
|
|
52
|
+
// is exactly the save this browser had in flight — its own write, already superseded.
|
|
53
|
+
const inFlight = entry.InFlightConfiguration;
|
|
54
|
+
return inFlight != null && serverConfiguration != null && inFlight === serverConfiguration;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Synchronous, per-user workspace snapshot in browser storage. Every operation is
|
|
58
|
+
* exception-safe: storage can be absent, full, or blocked (private mode), and the journal
|
|
59
|
+
* is only ever a recovery aid — the database stays the system of record.
|
|
60
|
+
*/
|
|
61
|
+
export class WorkspaceJournal {
|
|
62
|
+
getStorage;
|
|
63
|
+
static keyPrefix = 'mj.workspace.journal.';
|
|
64
|
+
/**
|
|
65
|
+
* @param getStorage resolves the storage lazily on each call, so a missing or throwing
|
|
66
|
+
* `localStorage` is handled per call rather than at construction.
|
|
67
|
+
*/
|
|
68
|
+
constructor(getStorage) {
|
|
69
|
+
this.getStorage = getStorage;
|
|
70
|
+
}
|
|
71
|
+
/** The storage key for a user's snapshot. */
|
|
72
|
+
static KeyFor(userId) {
|
|
73
|
+
return `${WorkspaceJournal.keyPrefix}${userId.toLowerCase()}`;
|
|
74
|
+
}
|
|
75
|
+
/** Writes (replaces) the user's snapshot. Silently does nothing when storage is unavailable. */
|
|
76
|
+
Write(entry) {
|
|
77
|
+
try {
|
|
78
|
+
this.getStorage()?.setItem(WorkspaceJournal.KeyFor(entry.UserID), JSON.stringify(entry));
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
// Quota exceeded / storage blocked: the debounced database save still runs.
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/** Reads the user's snapshot, or null when absent, unreadable, or of another format version. */
|
|
85
|
+
Read(userId) {
|
|
86
|
+
try {
|
|
87
|
+
const raw = this.getStorage()?.getItem(WorkspaceJournal.KeyFor(userId));
|
|
88
|
+
if (!raw) {
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
const parsed = JSON.parse(raw);
|
|
92
|
+
if (parsed?.Version !== 1 || !parsed.Configuration || !Array.isArray(parsed.Configuration.tabs)) {
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
if (typeof parsed.UserID !== 'string' || parsed.UserID.toLowerCase() !== userId.toLowerCase()) {
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
return parsed;
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
/** Removes the user's snapshot. */
|
|
105
|
+
Clear(userId) {
|
|
106
|
+
try {
|
|
107
|
+
this.getStorage()?.removeItem(WorkspaceJournal.KeyFor(userId));
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
// ignore — see Write
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/** `window.localStorage` when it exists and can be touched, else null. */
|
|
115
|
+
export function BrowserWorkspaceJournalStorage() {
|
|
116
|
+
try {
|
|
117
|
+
return typeof localStorage !== 'undefined' ? localStorage : null;
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
return null; // accessing localStorage throws when site data is blocked
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
//# sourceMappingURL=workspace-journal.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"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E,OAAO,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,aAAa,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,CAAC;gBAC9F,OAAO,IAAI,CAAC;YAChB,CAAC;YACD,IAAI,OAAO,MAAM,CAAC,MAAM,KAAK,QAAQ,IAAI,MAAM,CAAC,MAAM,CAAC,WAAW,EAAE,KAAK,MAAM,CAAC,WAAW,EAAE,EAAE,CAAC;gBAC5F,OAAO,IAAI,CAAC;YAChB,CAAC;YACD,OAAO,MAA+B,CAAC;QAC3C,CAAC;QAAC,MAAM,CAAC;YACL,OAAO,IAAI,CAAC;QAChB,CAAC;IACL,CAAC;IAED,mCAAmC;IAC5B,KAAK,CAAC,MAAc;QACvB,IAAI,CAAC;YACD,IAAI,CAAC,UAAU,EAAE,EAAE,UAAU,CAAC,gBAAgB,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;QACnE,CAAC;QAAC,MAAM,CAAC;YACL,qBAAqB;QACzB,CAAC;IACL,CAAC;;AAGL,0EAA0E;AAC1E,MAAM,UAAU,8BAA8B;IAC1C,IAAI,CAAC;QACD,OAAO,OAAO,YAAY,KAAK,WAAW,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,IAAI,CAAC;IACrE,CAAC;IAAC,MAAM,CAAC;QACL,OAAO,IAAI,CAAC,CAAC,0DAA0D;IAC3E,CAAC;AACL,CAAC","sourcesContent":["import { WorkspaceConfiguration } from './interfaces/workspace-configuration.interface';\n\n/**\n * One browser-local snapshot of the user's workspace configuration.\n *\n * The workspace is persisted to `MJ: Workspaces` through a debounced, asynchronous entity\n * save. A refresh that lands inside that window (debounce + network round trip) used to\n * come back one step behind: the newest tab/selection change existed only in memory. The\n * journal is written SYNCHRONOUSLY on every change, so the newest state survives any unload.\n */\nexport interface WorkspaceJournalEntry {\n /** Format version of this entry; entries with another version are ignored. */\n Version: 1;\n /** The user the snapshot belongs to. */\n UserID: string;\n /** The `MJ: Workspaces` row the snapshot was built on, or null when the user has none (permission-constrained sessions). */\n WorkspaceID: string | null;\n /**\n * The row's server `__mj_UpdatedAt` (ISO) that this snapshot is built on top of: the stamp of\n * the last save this browser saw complete, or of the row as loaded. Compared only with another\n * SERVER stamp, never with this browser's clock, so client clock skew cannot pick the wrong side.\n */\n BaseUpdatedAt: string | null;\n /**\n * The serialized configuration of a save this browser started but has not yet seen complete,\n * or null/absent when no save is in flight. A save that lands on the server while the page is\n * unloading advances the row's stamp past {@link BaseUpdatedAt} without this browser ever\n * re-basing; matching the row against this value is how the next load recognises that newer\n * row as its OWN write (which the snapshot already supersedes) rather than another device's.\n */\n InFlightConfiguration?: string | null;\n /** The configuration itself. */\n Configuration: WorkspaceConfiguration;\n}\n\n/** The storage surface the journal needs — `window.localStorage` in a browser. */\nexport interface WorkspaceJournalStorage {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n}\n\n/** Reads a server timestamp that may arrive as a Date or an ISO string; null when absent or unparseable. */\nexport function WorkspaceStampToEpoch(value: Date | string | null | undefined): number | null {\n if (value == null) {\n return null;\n }\n const ms = value instanceof Date ? value.getTime() : Date.parse(value);\n return Number.isFinite(ms) ? ms : null;\n}\n\n/**\n * Decides whether a journal snapshot is newer than the configuration the server returned.\n *\n * The journal wins only when it belongs to the same workspace row AND the server row has not\n * been saved since the snapshot's base stamp. A server row stamped LATER than the base was\n * saved by something this browser never saw (another device or browser tab), so the server\n * wins. A server row stamped at or before the base is what this browser already built on —\n * including a stale locally-cached copy of the row — so the journal, which holds every change\n * made since, wins.\n *\n * One exception to \"later row wins\": the row is this browser's OWN save that landed after the\n * page unloaded (its stamp moved past the base, but the browser never saw the response). The row's\n * configuration then equals the snapshot's {@link WorkspaceJournalEntry.InFlightConfiguration},\n * and the snapshot, which holds every change made after that save started, still wins.\n *\n * @param entry the journal snapshot, if any.\n * @param workspaceId the loaded workspace row's ID, or null when the user has none.\n * @param serverUpdatedAt the loaded row's `__mj_UpdatedAt`, or null when there is no row.\n * @param serverConfiguration the loaded row's raw `Configuration` text, when there is a row.\n */\nexport function ShouldUseWorkspaceJournal(\n entry: WorkspaceJournalEntry | null,\n workspaceId: string | null,\n serverUpdatedAt: Date | string | null | undefined,\n serverConfiguration?: string | null\n): boolean {\n if (!entry) {\n return false;\n }\n const entryRow = entry.WorkspaceID ?? null;\n const sameRow = entryRow === null || workspaceId === null\n ? entryRow === workspaceId\n : entryRow.toLowerCase() === workspaceId.toLowerCase();\n if (!sameRow) {\n return false;\n }\n if (workspaceId === null) {\n return true; // no server row to be newer than\n }\n const server = WorkspaceStampToEpoch(serverUpdatedAt);\n const base = WorkspaceStampToEpoch(entry.BaseUpdatedAt);\n if (server === null) {\n return true;\n }\n if (base !== null && server <= base) {\n return true;\n }\n // The row is newer than the base (or there is no base): the snapshot still wins when that row\n // is exactly the save this browser had in flight — its own write, already superseded.\n const inFlight = entry.InFlightConfiguration;\n return inFlight != null && serverConfiguration != null && inFlight === serverConfiguration;\n}\n\n/**\n * Synchronous, per-user workspace snapshot in browser storage. Every operation is\n * exception-safe: storage can be absent, full, or blocked (private mode), and the journal\n * is only ever a recovery aid — the database stays the system of record.\n */\nexport class WorkspaceJournal {\n private static readonly keyPrefix = 'mj.workspace.journal.';\n\n /**\n * @param getStorage resolves the storage lazily on each call, so a missing or throwing\n * `localStorage` is handled per call rather than at construction.\n */\n constructor(private readonly getStorage: () => WorkspaceJournalStorage | null) {}\n\n /** The storage key for a user's snapshot. */\n public static KeyFor(userId: string): string {\n return `${WorkspaceJournal.keyPrefix}${userId.toLowerCase()}`;\n }\n\n /** Writes (replaces) the user's snapshot. Silently does nothing when storage is unavailable. */\n public Write(entry: WorkspaceJournalEntry): void {\n try {\n this.getStorage()?.setItem(WorkspaceJournal.KeyFor(entry.UserID), JSON.stringify(entry));\n } catch {\n // Quota exceeded / storage blocked: the debounced database save still runs.\n }\n }\n\n /** Reads the user's snapshot, or null when absent, unreadable, or of another format version. */\n public Read(userId: string): WorkspaceJournalEntry | null {\n try {\n const raw = this.getStorage()?.getItem(WorkspaceJournal.KeyFor(userId));\n if (!raw) {\n return null;\n }\n const parsed = JSON.parse(raw) as Partial<WorkspaceJournalEntry>;\n if (parsed?.Version !== 1 || !parsed.Configuration || !Array.isArray(parsed.Configuration.tabs)) {\n return null;\n }\n if (typeof parsed.UserID !== 'string' || parsed.UserID.toLowerCase() !== userId.toLowerCase()) {\n return null;\n }\n return parsed as WorkspaceJournalEntry;\n } catch {\n return null;\n }\n }\n\n /** Removes the user's snapshot. */\n public Clear(userId: string): void {\n try {\n this.getStorage()?.removeItem(WorkspaceJournal.KeyFor(userId));\n } catch {\n // ignore — see Write\n }\n }\n}\n\n/** `window.localStorage` when it exists and can be touched, else null. */\nexport function BrowserWorkspaceJournalStorage(): WorkspaceJournalStorage | null {\n try {\n return typeof localStorage !== 'undefined' ? localStorage : null;\n } catch {\n return null; // accessing localStorage throws when site data is blocked\n }\n}\n"]}
|
|
@@ -2,7 +2,25 @@ import { Observable } from 'rxjs';
|
|
|
2
2
|
import { IMetadataProvider } from '@memberjunction/core';
|
|
3
3
|
import { WorkspaceConfiguration, WorkspaceTab } from './interfaces/workspace-configuration.interface';
|
|
4
4
|
import { TabRequest } from './interfaces/tab-request.interface';
|
|
5
|
+
import { WorkspaceJournal } from './workspace-journal';
|
|
5
6
|
import * as i0 from "@angular/core";
|
|
7
|
+
/**
|
|
8
|
+
* Options for {@link WorkspaceStateManager.Initialize}.
|
|
9
|
+
*/
|
|
10
|
+
export interface WorkspaceInitializeOptions {
|
|
11
|
+
/**
|
|
12
|
+
* Adjusts the loaded configuration BEFORE it is published to any subscriber.
|
|
13
|
+
*
|
|
14
|
+
* The shell uses this to make a deep link win on a full page load: the URL's query params
|
|
15
|
+
* are written into the matching restored tab before the tab container mounts that tab's
|
|
16
|
+
* component. Applying them afterwards (when the resolver's queued tab request replays) is
|
|
17
|
+
* too late — the component has already initialised from the saved params, and an async
|
|
18
|
+
* init that writes its selection back can clobber the URL's params entirely.
|
|
19
|
+
*
|
|
20
|
+
* Return the same object for "no change"; a different object is published and persisted.
|
|
21
|
+
*/
|
|
22
|
+
PrepareConfiguration?: (config: WorkspaceConfiguration) => WorkspaceConfiguration | Promise<WorkspaceConfiguration>;
|
|
23
|
+
}
|
|
6
24
|
/**
|
|
7
25
|
* Manages workspace state including tabs, layout, and persistence.
|
|
8
26
|
*
|
|
@@ -16,6 +34,23 @@ export declare class WorkspaceStateManager {
|
|
|
16
34
|
private loading$;
|
|
17
35
|
private tabBarVisible$;
|
|
18
36
|
private initialized;
|
|
37
|
+
/** The user this manager was initialized for (journal key). */
|
|
38
|
+
private userId;
|
|
39
|
+
/** A configuration change has been requested but not yet handed to the database. */
|
|
40
|
+
private savePending;
|
|
41
|
+
/**
|
|
42
|
+
* The database save currently running, if any. Saves run one at a time: they share one
|
|
43
|
+
* `MJ: Workspaces` entity instance, and a flush on page hide must not start a second
|
|
44
|
+
* `Save()` on it while the debounced one is still in flight.
|
|
45
|
+
*/
|
|
46
|
+
private saveInFlight;
|
|
47
|
+
/** The serialized configuration the in-flight save is writing (journaled — see WorkspaceJournalEntry.InFlightConfiguration). */
|
|
48
|
+
private inFlightConfiguration;
|
|
49
|
+
/**
|
|
50
|
+
* Synchronous browser-local snapshot of the newest configuration — see {@link WorkspaceJournal}.
|
|
51
|
+
* Replaceable for tests.
|
|
52
|
+
*/
|
|
53
|
+
Journal: WorkspaceJournal;
|
|
19
54
|
/**
|
|
20
55
|
* Optional predicate identifying tabs that belong to the MAIN layout.
|
|
21
56
|
* Tabs failing the predicate (e.g. record tabs under the records-style
|
|
@@ -99,7 +134,7 @@ export declare class WorkspaceStateManager {
|
|
|
99
134
|
/**
|
|
100
135
|
* Initialize the workspace state for a user
|
|
101
136
|
*/
|
|
102
|
-
Initialize(userId: string): Promise<void>;
|
|
137
|
+
Initialize(userId: string, options?: WorkspaceInitializeOptions): Promise<void>;
|
|
103
138
|
/**
|
|
104
139
|
* Ephemeral mode: when `window.__MJ_EPHEMERAL_WORKSPACE__ === true` is set
|
|
105
140
|
* (only baked into the regression test Explorer build via Dockerfile.explorer),
|
|
@@ -113,14 +148,35 @@ export declare class WorkspaceStateManager {
|
|
|
113
148
|
* Load workspace from database using UserInfoEngine for centralized, cached access
|
|
114
149
|
*/
|
|
115
150
|
private loadWorkspace;
|
|
151
|
+
/**
|
|
152
|
+
* Runs the caller's {@link WorkspaceInitializeOptions.PrepareConfiguration} hook, then
|
|
153
|
+
* publishes the result as the first configuration. Persists when the hook (or the journal)
|
|
154
|
+
* changed what the server holds.
|
|
155
|
+
*/
|
|
156
|
+
private publishInitialConfiguration;
|
|
116
157
|
/**
|
|
117
158
|
* Persist configuration to database (debounced)
|
|
118
159
|
*/
|
|
119
160
|
private persistConfiguration;
|
|
161
|
+
/**
|
|
162
|
+
* Runs the debounced save if one is still pending (a flush may already have run it). Saves are
|
|
163
|
+
* serialised: a call while one is in flight waits for it, then saves whatever is still pending.
|
|
164
|
+
*/
|
|
165
|
+
private runPendingSave;
|
|
166
|
+
/**
|
|
167
|
+
* Persist any change still waiting in the save debounce NOW. Called automatically on
|
|
168
|
+
* `pagehide` and when the page becomes hidden; hosts may also call it before a deliberate
|
|
169
|
+
* reload or sign-out. A no-op when nothing is pending.
|
|
170
|
+
*/
|
|
171
|
+
FlushPendingSave(): Promise<void>;
|
|
172
|
+
/** True while a configuration change is waiting for the debounced database save. */
|
|
173
|
+
get HasPendingSave(): boolean;
|
|
120
174
|
/**
|
|
121
175
|
* Request a save (will be debounced)
|
|
122
176
|
*/
|
|
123
177
|
private requestSave;
|
|
178
|
+
/** Synchronously snapshot the current configuration to the browser journal. */
|
|
179
|
+
private writeJournal;
|
|
124
180
|
/**
|
|
125
181
|
* Update configuration and request save
|
|
126
182
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workspace-state-manager.d.ts","sourceRoot":"","sources":["../../src/lib/workspace-state-manager.ts"],"names":[],"mappings":"AACA,OAAO,EAAmB,UAAU,EAAW,MAAM,MAAM,CAAC;AAE5D,OAAO,EAAY,iBAAiB,EAAyC,MAAM,sBAAsB,CAAC;AAE1G,OAAO,EACL,sBAAsB,EACtB,YAAY,EAEb,MAAM,gDAAgD,CAAC;AACxD,OAAO,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;;
|
|
1
|
+
{"version":3,"file":"workspace-state-manager.d.ts","sourceRoot":"","sources":["../../src/lib/workspace-state-manager.ts"],"names":[],"mappings":"AACA,OAAO,EAAmB,UAAU,EAAW,MAAM,MAAM,CAAC;AAE5D,OAAO,EAAY,iBAAiB,EAAyC,MAAM,sBAAsB,CAAC;AAE1G,OAAO,EACL,sBAAsB,EACtB,YAAY,EAEb,MAAM,gDAAgD,CAAC;AACxD,OAAO,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAChE,OAAO,EAGL,gBAAgB,EACjB,MAAM,qBAAqB,CAAC;;AAE7B;;GAEG;AACH,MAAM,WAAW,0BAA0B;IACzC;;;;;;;;;;OAUG;IACH,oBAAoB,CAAC,EAAE,CAAC,MAAM,EAAE,sBAAsB,KAAK,sBAAsB,GAAG,OAAO,CAAC,sBAAsB,CAAC,CAAC;CACrH;AAED;;;;;GAKG;AACH,qBAGa,qBAAqB;IAChC,OAAO,CAAC,UAAU,CAAuD;IACzE,OAAO,CAAC,cAAc,CAA4D;IAClF,OAAO,CAAC,YAAY,CAAuB;IAC3C,OAAO,CAAC,QAAQ,CAAuC;IACvD,OAAO,CAAC,cAAc,CAAsC;IAC5D,OAAO,CAAC,WAAW,CAAS;IAE5B,+DAA+D;IAC/D,OAAO,CAAC,MAAM,CAAuB;IAErC,oFAAoF;IACpF,OAAO,CAAC,WAAW,CAAS;IAE5B;;;;OAIG;IACH,OAAO,CAAC,YAAY,CAA8B;IAElD,gIAAgI;IAChI,OAAO,CAAC,qBAAqB,CAAuB;IAEpD;;;OAGG;IACI,OAAO,EAAE,gBAAgB,CAAwD;IAExF;;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,MAAM,GAAG,YAAY,EAAE;IAIzC;;OAEG;IACH,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI;IAgBrD;;;;;OAKG;IACH,sBAAsB,CAAC,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,OAAO,CAAC,YAAY,CAAC,eAAe,CAAC,CAAC,GAAG,IAAI;IAyBjG;;;;;;;;;OASG;IACH,yBAAyB,CAAC,KAAK,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,IAAI;IA2BnE;;OAEG;IACH,cAAc,IAAI,MAAM,GAAG,IAAI;IAI/B;;OAEG;IACH,OAAO,CAAC,YAAY;yCAr/BT,qBAAqB;6CAArB,qBAAqB;CA4/BjC"}
|
|
@@ -4,6 +4,7 @@ import { debounceTime } from 'rxjs/operators';
|
|
|
4
4
|
import { Metadata, LogStatus } from '@memberjunction/core';
|
|
5
5
|
import { UserInfoEngine } from '@memberjunction/core-entities';
|
|
6
6
|
import { CreateDefaultWorkspaceConfiguration } from './interfaces/workspace-configuration.interface';
|
|
7
|
+
import { BrowserWorkspaceJournalStorage, ShouldUseWorkspaceJournal, WorkspaceJournal } from './workspace-journal';
|
|
7
8
|
import * as i0 from "@angular/core";
|
|
8
9
|
/**
|
|
9
10
|
* Manages workspace state including tabs, layout, and persistence.
|
|
@@ -18,6 +19,23 @@ export class WorkspaceStateManager {
|
|
|
18
19
|
loading$ = new BehaviorSubject(false);
|
|
19
20
|
tabBarVisible$ = new BehaviorSubject(true);
|
|
20
21
|
initialized = false;
|
|
22
|
+
/** The user this manager was initialized for (journal key). */
|
|
23
|
+
userId = null;
|
|
24
|
+
/** A configuration change has been requested but not yet handed to the database. */
|
|
25
|
+
savePending = false;
|
|
26
|
+
/**
|
|
27
|
+
* The database save currently running, if any. Saves run one at a time: they share one
|
|
28
|
+
* `MJ: Workspaces` entity instance, and a flush on page hide must not start a second
|
|
29
|
+
* `Save()` on it while the debounced one is still in flight.
|
|
30
|
+
*/
|
|
31
|
+
saveInFlight = null;
|
|
32
|
+
/** The serialized configuration the in-flight save is writing (journaled — see WorkspaceJournalEntry.InFlightConfiguration). */
|
|
33
|
+
inFlightConfiguration = null;
|
|
34
|
+
/**
|
|
35
|
+
* Synchronous browser-local snapshot of the newest configuration — see {@link WorkspaceJournal}.
|
|
36
|
+
* Replaceable for tests.
|
|
37
|
+
*/
|
|
38
|
+
Journal = new WorkspaceJournal(BrowserWorkspaceJournalStorage);
|
|
21
39
|
/**
|
|
22
40
|
* Optional predicate identifying tabs that belong to the MAIN layout.
|
|
23
41
|
* Tabs failing the predicate (e.g. record tabs under the records-style
|
|
@@ -87,8 +105,22 @@ export class WorkspaceStateManager {
|
|
|
87
105
|
// Set up debounced saves
|
|
88
106
|
this.saveRequest$.pipe(debounceTime(500) // Wait 500ms after last change
|
|
89
107
|
).subscribe(() => {
|
|
90
|
-
this.
|
|
108
|
+
this.runPendingSave();
|
|
91
109
|
});
|
|
110
|
+
// Flush the debounced save when the page is going away or being backgrounded, so a
|
|
111
|
+
// refresh/close inside the debounce window doesn't drop the newest change. (The journal
|
|
112
|
+
// already holds it locally; this gets it to the database too.) beforeunload is avoided
|
|
113
|
+
// deliberately: registering it makes the page ineligible for the back/forward cache.
|
|
114
|
+
if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {
|
|
115
|
+
window.addEventListener('pagehide', () => { void this.FlushPendingSave(); });
|
|
116
|
+
if (typeof document !== 'undefined') {
|
|
117
|
+
document.addEventListener('visibilitychange', () => {
|
|
118
|
+
if (document.visibilityState === 'hidden') {
|
|
119
|
+
void this.FlushPendingSave();
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
}
|
|
92
124
|
// Update tab bar visibility whenever configuration changes
|
|
93
125
|
this.configuration$.subscribe(config => {
|
|
94
126
|
if (config) {
|
|
@@ -146,13 +178,14 @@ export class WorkspaceStateManager {
|
|
|
146
178
|
/**
|
|
147
179
|
* Initialize the workspace state for a user
|
|
148
180
|
*/
|
|
149
|
-
async Initialize(userId) {
|
|
181
|
+
async Initialize(userId, options) {
|
|
150
182
|
if (this.initialized) {
|
|
151
183
|
return;
|
|
152
184
|
}
|
|
153
185
|
this.loading$.next(true);
|
|
186
|
+
this.userId = userId;
|
|
154
187
|
try {
|
|
155
|
-
await this.loadWorkspace(userId);
|
|
188
|
+
await this.loadWorkspace(userId, options);
|
|
156
189
|
this.initialized = true;
|
|
157
190
|
}
|
|
158
191
|
finally {
|
|
@@ -174,7 +207,7 @@ export class WorkspaceStateManager {
|
|
|
174
207
|
/**
|
|
175
208
|
* Load workspace from database using UserInfoEngine for centralized, cached access
|
|
176
209
|
*/
|
|
177
|
-
async loadWorkspace(userId) {
|
|
210
|
+
async loadWorkspace(userId, options) {
|
|
178
211
|
if (this.isEphemeral()) {
|
|
179
212
|
// Test mode — skip server load entirely. Just emit a default config so the
|
|
180
213
|
// workspace starts clean for this BrowserContext. No MJWorkspaceEntity is
|
|
@@ -187,7 +220,13 @@ export class WorkspaceStateManager {
|
|
|
187
220
|
// Permission-denied ≠ empty — don't auto-create a workspace for denied users.
|
|
188
221
|
if (engine.IsPermissionConstrained) {
|
|
189
222
|
LogStatus('[WorkspaceStateManager] UserInfoEngine is permission-constrained, using default workspace configuration');
|
|
190
|
-
this
|
|
223
|
+
// No server row to persist to, but the browser journal still carries this session's
|
|
224
|
+
// tabs across a refresh.
|
|
225
|
+
const journal = this.Journal.Read(userId);
|
|
226
|
+
const base = ShouldUseWorkspaceJournal(journal, null, null) && journal
|
|
227
|
+
? journal.Configuration
|
|
228
|
+
: CreateDefaultWorkspaceConfiguration();
|
|
229
|
+
await this.publishInitialConfiguration(base, options, false);
|
|
191
230
|
return;
|
|
192
231
|
}
|
|
193
232
|
const workspaces = engine.Workspaces;
|
|
@@ -196,10 +235,19 @@ export class WorkspaceStateManager {
|
|
|
196
235
|
this.workspace$.next(workspace);
|
|
197
236
|
// Parse configuration or create default
|
|
198
237
|
const configJson = workspace.Configuration;
|
|
199
|
-
const
|
|
238
|
+
const serverConfig = configJson
|
|
200
239
|
? JSON.parse(configJson)
|
|
201
240
|
: CreateDefaultWorkspaceConfiguration();
|
|
202
|
-
|
|
241
|
+
// A refresh inside the debounce/save window left a newer snapshot in the journal than
|
|
242
|
+
// the row we just read (or the row came from a stale local cache): the journal wins,
|
|
243
|
+
// and is pushed to the database.
|
|
244
|
+
const journal = this.Journal.Read(userId);
|
|
245
|
+
const useJournal = ShouldUseWorkspaceJournal(journal, workspace.ID, workspace.__mj_UpdatedAt, configJson) && journal != null
|
|
246
|
+
&& JSON.stringify(journal.Configuration) !== JSON.stringify(serverConfig);
|
|
247
|
+
if (useJournal) {
|
|
248
|
+
LogStatus('[WorkspaceStateManager] Restoring workspace from the local journal (newer than the saved row)');
|
|
249
|
+
}
|
|
250
|
+
await this.publishInitialConfiguration(useJournal && journal ? journal.Configuration : serverConfig, options, useJournal);
|
|
203
251
|
}
|
|
204
252
|
else {
|
|
205
253
|
// Create new workspace for user
|
|
@@ -211,7 +259,9 @@ export class WorkspaceStateManager {
|
|
|
211
259
|
const saveResult = await workspace.Save();
|
|
212
260
|
if (saveResult) {
|
|
213
261
|
this.workspace$.next(workspace);
|
|
214
|
-
|
|
262
|
+
// Through the same path as a loaded row, so a brand-new user's first boot also gets the
|
|
263
|
+
// PrepareConfiguration hook (deep-link precedence) and a journal seeded on the new row.
|
|
264
|
+
await this.publishInitialConfiguration(CreateDefaultWorkspaceConfiguration(), options, false);
|
|
215
265
|
}
|
|
216
266
|
else {
|
|
217
267
|
console.error('[WorkspaceStateManager.loadWorkspace] Failed to save workspace');
|
|
@@ -219,6 +269,31 @@ export class WorkspaceStateManager {
|
|
|
219
269
|
}
|
|
220
270
|
}
|
|
221
271
|
}
|
|
272
|
+
/**
|
|
273
|
+
* Runs the caller's {@link WorkspaceInitializeOptions.PrepareConfiguration} hook, then
|
|
274
|
+
* publishes the result as the first configuration. Persists when the hook (or the journal)
|
|
275
|
+
* changed what the server holds.
|
|
276
|
+
*/
|
|
277
|
+
async publishInitialConfiguration(config, options, alreadyDiffersFromServer) {
|
|
278
|
+
let prepared = config;
|
|
279
|
+
if (options?.PrepareConfiguration) {
|
|
280
|
+
try {
|
|
281
|
+
prepared = await options.PrepareConfiguration(config);
|
|
282
|
+
}
|
|
283
|
+
catch (e) {
|
|
284
|
+
// The hook is an enhancement (deep-link precedence); never let it block startup.
|
|
285
|
+
console.error('[WorkspaceStateManager] PrepareConfiguration failed; using the loaded configuration', e);
|
|
286
|
+
prepared = config;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
this.configuration$.next(prepared);
|
|
290
|
+
if (alreadyDiffersFromServer || prepared !== config) {
|
|
291
|
+
this.requestSave();
|
|
292
|
+
}
|
|
293
|
+
else {
|
|
294
|
+
this.writeJournal(); // seed / re-base the snapshot on the row as loaded
|
|
295
|
+
}
|
|
296
|
+
}
|
|
222
297
|
/**
|
|
223
298
|
* Persist configuration to database (debounced)
|
|
224
299
|
*/
|
|
@@ -231,16 +306,87 @@ export class WorkspaceStateManager {
|
|
|
231
306
|
const workspace = this.workspace$.value;
|
|
232
307
|
const config = this.configuration$.value;
|
|
233
308
|
if (workspace && config) {
|
|
234
|
-
|
|
235
|
-
|
|
309
|
+
const json = JSON.stringify(config);
|
|
310
|
+
workspace.Configuration = json;
|
|
311
|
+
// Journal what this save writes BEFORE it is sent: if the page unloads while it is in flight
|
|
312
|
+
// and the write still lands, the next load recognises the newer row as this browser's own.
|
|
313
|
+
this.inFlightConfiguration = json;
|
|
314
|
+
this.writeJournal();
|
|
315
|
+
try {
|
|
316
|
+
await workspace.Save();
|
|
317
|
+
}
|
|
318
|
+
finally {
|
|
319
|
+
this.inFlightConfiguration = null;
|
|
320
|
+
// Re-base the journal on the stamp this save produced (a failed save leaves the stamp, and
|
|
321
|
+
// so the base, unchanged). The CURRENT configuration is written, not the one just saved:
|
|
322
|
+
// any change made while the save was in flight is newer still, and must keep winning.
|
|
323
|
+
this.writeJournal();
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Runs the debounced save if one is still pending (a flush may already have run it). Saves are
|
|
329
|
+
* serialised: a call while one is in flight waits for it, then saves whatever is still pending.
|
|
330
|
+
*/
|
|
331
|
+
runPendingSave() {
|
|
332
|
+
if (this.saveInFlight) {
|
|
333
|
+
return this.saveInFlight.then(() => this.runPendingSave());
|
|
334
|
+
}
|
|
335
|
+
if (!this.savePending) {
|
|
336
|
+
return Promise.resolve();
|
|
236
337
|
}
|
|
338
|
+
this.savePending = false;
|
|
339
|
+
const run = this.persistConfiguration()
|
|
340
|
+
.catch((e) => {
|
|
341
|
+
// A failed save leaves the change in the journal; the next change (or load) retries it.
|
|
342
|
+
console.error('[WorkspaceStateManager] Workspace save failed', e);
|
|
343
|
+
})
|
|
344
|
+
.finally(() => {
|
|
345
|
+
if (this.saveInFlight === run) {
|
|
346
|
+
this.saveInFlight = null;
|
|
347
|
+
}
|
|
348
|
+
});
|
|
349
|
+
this.saveInFlight = run;
|
|
350
|
+
return run;
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Persist any change still waiting in the save debounce NOW. Called automatically on
|
|
354
|
+
* `pagehide` and when the page becomes hidden; hosts may also call it before a deliberate
|
|
355
|
+
* reload or sign-out. A no-op when nothing is pending.
|
|
356
|
+
*/
|
|
357
|
+
FlushPendingSave() {
|
|
358
|
+
return this.runPendingSave();
|
|
359
|
+
}
|
|
360
|
+
/** True while a configuration change is waiting for the debounced database save. */
|
|
361
|
+
get HasPendingSave() {
|
|
362
|
+
return this.savePending;
|
|
237
363
|
}
|
|
238
364
|
/**
|
|
239
365
|
* Request a save (will be debounced)
|
|
240
366
|
*/
|
|
241
367
|
requestSave() {
|
|
368
|
+
this.savePending = true;
|
|
369
|
+
this.writeJournal();
|
|
242
370
|
this.saveRequest$.next();
|
|
243
371
|
}
|
|
372
|
+
/** Synchronously snapshot the current configuration to the browser journal. */
|
|
373
|
+
writeJournal() {
|
|
374
|
+
const config = this.configuration$.value;
|
|
375
|
+
if (!config || !this.userId || this.isEphemeral()) {
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
const workspace = this.workspace$.value;
|
|
379
|
+
// Typed Date, but a value that crossed the wire can still be an ISO string at runtime.
|
|
380
|
+
const base = workspace?.__mj_UpdatedAt;
|
|
381
|
+
this.Journal.Write({
|
|
382
|
+
Version: 1,
|
|
383
|
+
UserID: this.userId,
|
|
384
|
+
WorkspaceID: workspace?.ID ?? null,
|
|
385
|
+
BaseUpdatedAt: base instanceof Date ? base.toISOString() : (base ?? null),
|
|
386
|
+
InFlightConfiguration: this.inFlightConfiguration,
|
|
387
|
+
Configuration: config
|
|
388
|
+
});
|
|
389
|
+
}
|
|
244
390
|
/**
|
|
245
391
|
* Update configuration and request save
|
|
246
392
|
*/
|
|
@@ -255,7 +401,9 @@ export class WorkspaceStateManager {
|
|
|
255
401
|
async ResetConfiguration() {
|
|
256
402
|
const defaultConfig = CreateDefaultWorkspaceConfiguration();
|
|
257
403
|
this.configuration$.next(defaultConfig);
|
|
258
|
-
|
|
404
|
+
this.savePending = true;
|
|
405
|
+
this.writeJournal(); // the reset must also replace a (possibly corrupt) local snapshot
|
|
406
|
+
await this.runPendingSave(); // serialised with any save already in flight
|
|
259
407
|
}
|
|
260
408
|
/**
|
|
261
409
|
* Force creation of a new tab, never replacing temporary tabs
|