@coolms/core-angular 2.0.0-alpha.2
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/LICENSE +21 -0
- package/README.md +74 -0
- package/fesm2022/coolms-core-angular.mjs +2085 -0
- package/fesm2022/coolms-core-angular.mjs.map +1 -0
- package/package.json +51 -0
- package/types/coolms-core-angular.d.ts +1415 -0
|
@@ -0,0 +1,2085 @@
|
|
|
1
|
+
import * as i0 from '@angular/core';
|
|
2
|
+
import { Injectable, inject, DestroyRef, Component, signal, computed, effect, input, ChangeDetectionStrategy, InjectionToken } from '@angular/core';
|
|
3
|
+
import { HttpClient, HttpErrorResponse, HttpContextToken, HttpContext, HttpParams } from '@angular/common/http';
|
|
4
|
+
import { Action, Selector, State, Store } from '@ngxs/store';
|
|
5
|
+
import { __decorate } from 'tslib';
|
|
6
|
+
import { Subject, debounceTime, catchError, of, defer, throwError, shareReplay, finalize, from, firstValueFrom, take, switchMap as switchMap$1, ReplaySubject, tap as tap$1, map } from 'rxjs';
|
|
7
|
+
import { tap, switchMap, map as map$1, catchError as catchError$1, shareReplay as shareReplay$1 } from 'rxjs/operators';
|
|
8
|
+
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
|
9
|
+
import { Router } from '@angular/router';
|
|
10
|
+
import { Location, NgIf } from '@angular/common';
|
|
11
|
+
import * as i1 from '@angular/forms';
|
|
12
|
+
import { FormsModule } from '@angular/forms';
|
|
13
|
+
|
|
14
|
+
// Typed contract — must mirror ApiManifest PHP VOs exactly.
|
|
15
|
+
// No `any` anywhere.
|
|
16
|
+
/**
|
|
17
|
+
* Replaces {param} tokens in a URL pattern with encoded values.
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* resolvePattern(manifest.sections!.item, { id: '123' })
|
|
21
|
+
* // -> '/api/v1/sections/123'
|
|
22
|
+
*/
|
|
23
|
+
function resolvePattern(pattern, params) {
|
|
24
|
+
return Object.entries(params).reduce((url, [key, value]) => url.replace(`{${key}}`, encodeURIComponent(value)), pattern);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Typed contract — mirrors FormRenderDefinition PHP VOs exactly.
|
|
28
|
+
// No `any` anywhere.
|
|
29
|
+
|
|
30
|
+
// --- Action ------------------------------------------------------------------
|
|
31
|
+
class SetAppConfig {
|
|
32
|
+
config;
|
|
33
|
+
static type = '[AppConfig] Set';
|
|
34
|
+
constructor(config) {
|
|
35
|
+
this.config = config;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
let AppConfigState = class AppConfigState {
|
|
39
|
+
set(ctx, { config }) {
|
|
40
|
+
ctx.setState({ config, loaded: true });
|
|
41
|
+
}
|
|
42
|
+
static manifest(state) {
|
|
43
|
+
return state.config?.manifest ?? null;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* F.7 viewer manifest. Null when the backend didn't ship a viewers
|
|
47
|
+
* section (no tagged providers); consumers should fall back to a
|
|
48
|
+
* "no preview" surface.
|
|
49
|
+
*/
|
|
50
|
+
static viewers(state) {
|
|
51
|
+
return state.config?.manifest.viewers ?? null;
|
|
52
|
+
}
|
|
53
|
+
static loaded(state) {
|
|
54
|
+
return state.loaded;
|
|
55
|
+
}
|
|
56
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: AppConfigState, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
57
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: AppConfigState });
|
|
58
|
+
};
|
|
59
|
+
__decorate([
|
|
60
|
+
Action(SetAppConfig)
|
|
61
|
+
], AppConfigState.prototype, "set", null);
|
|
62
|
+
__decorate([
|
|
63
|
+
Selector()
|
|
64
|
+
], AppConfigState, "manifest", null);
|
|
65
|
+
__decorate([
|
|
66
|
+
Selector()
|
|
67
|
+
], AppConfigState, "viewers", null);
|
|
68
|
+
__decorate([
|
|
69
|
+
Selector()
|
|
70
|
+
], AppConfigState, "loaded", null);
|
|
71
|
+
AppConfigState = __decorate([
|
|
72
|
+
State({
|
|
73
|
+
name: 'appConfig',
|
|
74
|
+
defaults: { config: null, loaded: false },
|
|
75
|
+
})
|
|
76
|
+
], AppConfigState);
|
|
77
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: AppConfigState, decorators: [{
|
|
78
|
+
type: Injectable
|
|
79
|
+
}], propDecorators: { set: [] } });
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The identity endpoints core owns: the session lifecycle, plus the settings
|
|
83
|
+
* read at boot.
|
|
84
|
+
*
|
|
85
|
+
* Carved out of the admin's `ApiService` -- 2410 lines, 118 methods and 89 DTOs
|
|
86
|
+
* spanning calendars, documents, calls, VFS and the rest. Core cannot depend on
|
|
87
|
+
* that and still ship beneath the UI kit: it would drag every module's wire
|
|
88
|
+
* types down with it. Core called exactly FOUR of those methods.
|
|
89
|
+
*
|
|
90
|
+
* `logout` is the one addition, and not for symmetry: the auth lifecycle lives
|
|
91
|
+
* here (state, refresh coordinator, cross-tab sync), so a core package that
|
|
92
|
+
* could sign in but not out would be incomplete.
|
|
93
|
+
*
|
|
94
|
+
* `ApiService` keeps its own identical signatures and delegates here, so none
|
|
95
|
+
* of the 94 feature files calling it changed.
|
|
96
|
+
*/
|
|
97
|
+
class IdentityApiClient {
|
|
98
|
+
http = inject(HttpClient);
|
|
99
|
+
store = inject(Store);
|
|
100
|
+
/** URLs come from the boot manifest, which core already owns. */
|
|
101
|
+
get manifest() {
|
|
102
|
+
const m = this.store.selectSnapshot(AppConfigState.manifest);
|
|
103
|
+
if (!m)
|
|
104
|
+
throw new Error('ApiManifest not loaded — call AppInitService.load() first');
|
|
105
|
+
return m;
|
|
106
|
+
}
|
|
107
|
+
login(identifier, password) {
|
|
108
|
+
return this.http.post(this.manifest.auth.login, { identifier, password });
|
|
109
|
+
}
|
|
110
|
+
refresh(refreshToken) {
|
|
111
|
+
return this.http.post(this.manifest.auth.refresh, { refreshToken });
|
|
112
|
+
}
|
|
113
|
+
logout() {
|
|
114
|
+
return this.http.post(this.manifest.auth.logout, {});
|
|
115
|
+
}
|
|
116
|
+
me() {
|
|
117
|
+
return this.http.get(this.manifest.auth.me);
|
|
118
|
+
}
|
|
119
|
+
getSettings() {
|
|
120
|
+
// Force plain JSON. Angular's default Accept carries a wildcard, which
|
|
121
|
+
// makes the backend prefer application/ld+json -- and the section keys
|
|
122
|
+
// are then lost inside the Hydra member array.
|
|
123
|
+
return this.http.get(this.manifest.identity.settingsUrl, { headers: { Accept: 'application/json' } });
|
|
124
|
+
}
|
|
125
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: IdentityApiClient, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
126
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: IdentityApiClient, providedIn: 'root' });
|
|
127
|
+
}
|
|
128
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: IdentityApiClient, decorators: [{
|
|
129
|
+
type: Injectable,
|
|
130
|
+
args: [{ providedIn: 'root' }]
|
|
131
|
+
}] });
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* The two realtime endpoints, carved out for the same reason the identity ones
|
|
135
|
+
* were: the UI kit's realtime client needed exactly these two of `ApiService`'s
|
|
136
|
+
* 117 methods, and depending on the whole thing would have pulled the entire
|
|
137
|
+
* application's wire vocabulary underneath the kit.
|
|
138
|
+
*
|
|
139
|
+
* They belong in core rather than in the kit because both answers are derived
|
|
140
|
+
* from things core already owns -- the boot manifest for the URL, and the auth
|
|
141
|
+
* interceptor for the bearer token that authorises the request. A token is
|
|
142
|
+
* session state, not a widget.
|
|
143
|
+
*
|
|
144
|
+
* `ApiService` keeps its identical signatures and delegates here, so nothing
|
|
145
|
+
* calling it had to change.
|
|
146
|
+
*/
|
|
147
|
+
class RealtimeTokenClient {
|
|
148
|
+
http = inject(HttpClient);
|
|
149
|
+
store = inject(Store);
|
|
150
|
+
get manifest() {
|
|
151
|
+
const m = this.store.selectSnapshot(AppConfigState.manifest);
|
|
152
|
+
if (!m)
|
|
153
|
+
throw new Error('ApiManifest not loaded — call AppInitService.load() first');
|
|
154
|
+
return m;
|
|
155
|
+
}
|
|
156
|
+
connectionToken() {
|
|
157
|
+
return this.http.post(this.manifest.apiBase + '/centrifugo/connection-token', {});
|
|
158
|
+
}
|
|
159
|
+
subscriptionToken(channel) {
|
|
160
|
+
return this.http.post(this.manifest.apiBase + '/centrifugo/subscription-token', { channel });
|
|
161
|
+
}
|
|
162
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: RealtimeTokenClient, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
163
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: RealtimeTokenClient, providedIn: 'root' });
|
|
164
|
+
}
|
|
165
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: RealtimeTokenClient, decorators: [{
|
|
166
|
+
type: Injectable,
|
|
167
|
+
args: [{ providedIn: 'root' }]
|
|
168
|
+
}] });
|
|
169
|
+
|
|
170
|
+
class Login {
|
|
171
|
+
identifier;
|
|
172
|
+
password;
|
|
173
|
+
static type = '[Auth] Login';
|
|
174
|
+
constructor(identifier, password) {
|
|
175
|
+
this.identifier = identifier;
|
|
176
|
+
this.password = password;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
class Logout {
|
|
180
|
+
static type = '[Auth] Logout';
|
|
181
|
+
}
|
|
182
|
+
class RestoreSession {
|
|
183
|
+
static type = '[Auth] Restore Session';
|
|
184
|
+
}
|
|
185
|
+
class SetTokens {
|
|
186
|
+
response;
|
|
187
|
+
static type = '[Auth] Set Tokens';
|
|
188
|
+
constructor(response) {
|
|
189
|
+
this.response = response;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
/** Merge a partial update into the currently-stored user (e.g. after avatar change). */
|
|
193
|
+
class PatchCurrentUser {
|
|
194
|
+
patch;
|
|
195
|
+
static type = '[Auth] Patch Current User';
|
|
196
|
+
constructor(patch) {
|
|
197
|
+
this.patch = patch;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Unified user preferences service — all preference types share one
|
|
203
|
+
* localStorage key (`coolms_ui_prefs`) and one debounced server-sync pipeline.
|
|
204
|
+
*
|
|
205
|
+
* Key naming convention (stored as nested objects, referenced via dot-notation):
|
|
206
|
+
*
|
|
207
|
+
* // Grids
|
|
208
|
+
* grids.{gridId}.columns
|
|
209
|
+
* grids.{gridId}.columnWidths
|
|
210
|
+
*
|
|
211
|
+
* // Panels (ExplorerLayout persistKey values from YAML)
|
|
212
|
+
* panel.{persistKey}.width
|
|
213
|
+
* panel.{persistKey}.collapsed
|
|
214
|
+
*
|
|
215
|
+
* // Page navigation state
|
|
216
|
+
* page.vfs.lastPath
|
|
217
|
+
* page.vfs.viewMode
|
|
218
|
+
* page.media.lastDir
|
|
219
|
+
* page.media.viewMode
|
|
220
|
+
*
|
|
221
|
+
* // Global
|
|
222
|
+
* nav.lastRoute
|
|
223
|
+
* terminal.height
|
|
224
|
+
* terminal.open
|
|
225
|
+
*/
|
|
226
|
+
class UserPreferencesService {
|
|
227
|
+
http = inject(HttpClient);
|
|
228
|
+
store = inject(Store);
|
|
229
|
+
destroyRef = inject(DestroyRef);
|
|
230
|
+
STORAGE_KEY = 'coolms_ui_prefs';
|
|
231
|
+
SYNC_DELAY = 2000; // ms
|
|
232
|
+
syncSubject = new Subject();
|
|
233
|
+
constructor() {
|
|
234
|
+
// Debounced sync to server — batches rapid changes (e.g. live resize)
|
|
235
|
+
this.syncSubject.pipe(debounceTime(this.SYNC_DELAY), takeUntilDestroyed(this.destroyRef)).subscribe(prefs => this.syncToServer(prefs));
|
|
236
|
+
}
|
|
237
|
+
// -- Core helpers ---------------------------------------------------------
|
|
238
|
+
/**
|
|
239
|
+
* Write all prefs to localStorage and schedule a debounced server sync.
|
|
240
|
+
*/
|
|
241
|
+
save(all) {
|
|
242
|
+
localStorage.setItem(this.STORAGE_KEY, JSON.stringify(all));
|
|
243
|
+
this.syncSubject.next(all);
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Read the entire prefs object from localStorage, applying legacy key
|
|
247
|
+
* migration on the first read after an upgrade.
|
|
248
|
+
*/
|
|
249
|
+
load() {
|
|
250
|
+
try {
|
|
251
|
+
const raw = localStorage.getItem(this.STORAGE_KEY);
|
|
252
|
+
const all = raw ? JSON.parse(raw) : {};
|
|
253
|
+
return this.migrate(all);
|
|
254
|
+
}
|
|
255
|
+
catch {
|
|
256
|
+
return {};
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* One-time migration of legacy flat keys to the new nested naming convention.
|
|
261
|
+
* Mutates `all` in place and re-persists only when something changed.
|
|
262
|
+
*/
|
|
263
|
+
migrate(all) {
|
|
264
|
+
let dirty = false;
|
|
265
|
+
// terminal_height -> terminal.height
|
|
266
|
+
if (typeof all['terminal_height'] === 'number') {
|
|
267
|
+
const terminal = (all['terminal'] ?? {});
|
|
268
|
+
terminal['height'] = all['terminal_height'];
|
|
269
|
+
all['terminal'] = terminal;
|
|
270
|
+
delete all['terminal_height'];
|
|
271
|
+
dirty = true;
|
|
272
|
+
}
|
|
273
|
+
// media_view_mode -> page.media.viewMode
|
|
274
|
+
if (typeof all['media_view_mode'] === 'string') {
|
|
275
|
+
const page = (all['page'] ?? {});
|
|
276
|
+
const media = (page['media'] ?? {});
|
|
277
|
+
media['viewMode'] = all['media_view_mode'];
|
|
278
|
+
page['media'] = media;
|
|
279
|
+
all['page'] = page;
|
|
280
|
+
delete all['media_view_mode'];
|
|
281
|
+
dirty = true;
|
|
282
|
+
}
|
|
283
|
+
// media_collections_panel -> panel.media_panel_left (matches persistKey in media-library.yaml)
|
|
284
|
+
if (all['media_collections_panel'] && typeof all['media_collections_panel'] === 'object') {
|
|
285
|
+
const panel = (all['panel'] ?? {});
|
|
286
|
+
panel['media_panel_left'] = all['media_collections_panel'];
|
|
287
|
+
all['panel'] = panel;
|
|
288
|
+
delete all['media_collections_panel'];
|
|
289
|
+
dirty = true;
|
|
290
|
+
}
|
|
291
|
+
// Normalize namespace arrays to empty objects.
|
|
292
|
+
// The server serialises empty namespaces as [] (JSON array) rather than {}
|
|
293
|
+
// because PHP converts empty associative arrays to JSON arrays. Arrays silently
|
|
294
|
+
// swallow named-property writes and produce "[]" on serialisation, so column/
|
|
295
|
+
// panel preferences would be lost. Convert once and re-persist.
|
|
296
|
+
const NAMESPACES = new Set(['grids', 'panel', 'page', 'terminal', 'nav']);
|
|
297
|
+
for (const ns of NAMESPACES) {
|
|
298
|
+
if (Array.isArray(all[ns])) {
|
|
299
|
+
all[ns] = {};
|
|
300
|
+
dirty = true;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
// Grid keys: any top-level object with `columns` or `columnWidths` -> grids.{key}
|
|
304
|
+
for (const key of Object.keys(all)) {
|
|
305
|
+
if (NAMESPACES.has(key))
|
|
306
|
+
continue;
|
|
307
|
+
const val = all[key];
|
|
308
|
+
if (val && typeof val === 'object' && !Array.isArray(val)) {
|
|
309
|
+
const obj = val;
|
|
310
|
+
if ('columns' in obj || 'columnWidths' in obj) {
|
|
311
|
+
const grids = (all['grids'] ?? {});
|
|
312
|
+
grids[key] = obj;
|
|
313
|
+
all['grids'] = grids;
|
|
314
|
+
delete all[key];
|
|
315
|
+
dirty = true;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
if (dirty) {
|
|
320
|
+
localStorage.setItem(this.STORAGE_KEY, JSON.stringify(all));
|
|
321
|
+
}
|
|
322
|
+
return all;
|
|
323
|
+
}
|
|
324
|
+
// -- Server sync ----------------------------------------------------------
|
|
325
|
+
/**
|
|
326
|
+
* Seed localStorage from server preferences.
|
|
327
|
+
* Called after login and on every session restore (page reload).
|
|
328
|
+
*
|
|
329
|
+
* Strategy:
|
|
330
|
+
* - No local prefs yet (new device / clean install) -> use server prefs as-is.
|
|
331
|
+
* - Local prefs already exist -> merge with local taking priority at each
|
|
332
|
+
* top-level namespace. This ensures that locally-persisted state
|
|
333
|
+
* (panel widths, last path, etc.) is never overwritten by the stale copy
|
|
334
|
+
* that was saved in the auth token at login time.
|
|
335
|
+
*/
|
|
336
|
+
loadFromServer(uiPrefs) {
|
|
337
|
+
if (Object.keys(uiPrefs).length === 0)
|
|
338
|
+
return;
|
|
339
|
+
try {
|
|
340
|
+
const raw = localStorage.getItem(this.STORAGE_KEY);
|
|
341
|
+
if (!raw) {
|
|
342
|
+
// Fresh device — trust the server entirely
|
|
343
|
+
localStorage.setItem(this.STORAGE_KEY, JSON.stringify(uiPrefs));
|
|
344
|
+
}
|
|
345
|
+
else {
|
|
346
|
+
// Local prefs exist — server is the base, local namespaces win
|
|
347
|
+
const local = JSON.parse(raw);
|
|
348
|
+
const merged = { ...uiPrefs, ...local };
|
|
349
|
+
localStorage.setItem(this.STORAGE_KEY, JSON.stringify(merged));
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
catch {
|
|
353
|
+
localStorage.setItem(this.STORAGE_KEY, JSON.stringify(uiPrefs));
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
syncToServer(prefs) {
|
|
357
|
+
const manifest = this.store.selectSnapshot(AppConfigState.manifest);
|
|
358
|
+
const url = manifest?.auth?.preferencesUrl;
|
|
359
|
+
if (!url)
|
|
360
|
+
return;
|
|
361
|
+
this.http.patch(url, { uiPrefs: prefs }, {
|
|
362
|
+
headers: { 'Content-Type': 'application/merge-patch+json' },
|
|
363
|
+
}).subscribe({
|
|
364
|
+
error: err => console.warn('Preferences sync failed:', err),
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
// -- Grids ----------------------------------------------------------------
|
|
368
|
+
/**
|
|
369
|
+
* Get stored preferences for a specific grid.
|
|
370
|
+
*/
|
|
371
|
+
getGridPref(gridId) {
|
|
372
|
+
try {
|
|
373
|
+
const all = this.load();
|
|
374
|
+
const grids = all['grids'];
|
|
375
|
+
if (!grids)
|
|
376
|
+
return null;
|
|
377
|
+
return grids[gridId] ?? null;
|
|
378
|
+
}
|
|
379
|
+
catch {
|
|
380
|
+
return null;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* Set visible column order for a grid.
|
|
385
|
+
* Applies to localStorage instantly; server sync is debounced.
|
|
386
|
+
*/
|
|
387
|
+
setColumns(gridId, columns) {
|
|
388
|
+
this.updateGrid(gridId, existing => ({ ...existing, columns }));
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Record a column width for a grid column.
|
|
392
|
+
* Applies to localStorage instantly; server sync is debounced.
|
|
393
|
+
*/
|
|
394
|
+
setColumnWidth(gridId, field, width) {
|
|
395
|
+
this.updateGrid(gridId, existing => ({
|
|
396
|
+
...existing,
|
|
397
|
+
columnWidths: {
|
|
398
|
+
...(existing.columnWidths ?? {}),
|
|
399
|
+
[field]: Math.max(60, width),
|
|
400
|
+
},
|
|
401
|
+
}));
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* Remove all preferences for a specific grid and immediately sync to server.
|
|
405
|
+
*/
|
|
406
|
+
resetGrid(gridId) {
|
|
407
|
+
const all = this.load();
|
|
408
|
+
const grids = (all['grids'] ?? {});
|
|
409
|
+
delete grids[gridId];
|
|
410
|
+
all['grids'] = grids;
|
|
411
|
+
this.save(all);
|
|
412
|
+
this.syncToServer(all); // immediate sync
|
|
413
|
+
}
|
|
414
|
+
updateGrid(gridId, updater) {
|
|
415
|
+
const all = this.load();
|
|
416
|
+
const grids = (all['grids'] ?? {});
|
|
417
|
+
grids[gridId] = updater(grids[gridId] ?? {});
|
|
418
|
+
all['grids'] = grids;
|
|
419
|
+
this.save(all);
|
|
420
|
+
}
|
|
421
|
+
// -- Terminal -------------------------------------------------------------
|
|
422
|
+
/**
|
|
423
|
+
* Get persisted terminal panel height.
|
|
424
|
+
*/
|
|
425
|
+
getTerminalHeight() {
|
|
426
|
+
const all = this.load();
|
|
427
|
+
const terminal = all['terminal'];
|
|
428
|
+
return typeof terminal?.['height'] === 'number' ? terminal['height'] : null;
|
|
429
|
+
}
|
|
430
|
+
/**
|
|
431
|
+
* Persist terminal panel height.
|
|
432
|
+
*/
|
|
433
|
+
setTerminalHeight(height) {
|
|
434
|
+
const all = this.load();
|
|
435
|
+
const terminal = (all['terminal'] ?? {});
|
|
436
|
+
terminal['height'] = Math.round(height);
|
|
437
|
+
all['terminal'] = terminal;
|
|
438
|
+
this.save(all);
|
|
439
|
+
}
|
|
440
|
+
// -- Panel ----------------------------------------------------------------
|
|
441
|
+
/**
|
|
442
|
+
* Get persisted state for a resizable panel identified by key.
|
|
443
|
+
* Used by ExplorerLayoutComponent to persist panel widths across sessions.
|
|
444
|
+
*/
|
|
445
|
+
getPanelState(key) {
|
|
446
|
+
try {
|
|
447
|
+
const all = this.load();
|
|
448
|
+
const panel = all['panel'];
|
|
449
|
+
if (!panel)
|
|
450
|
+
return null;
|
|
451
|
+
const p = panel[key];
|
|
452
|
+
if (!p || typeof p !== 'object')
|
|
453
|
+
return null;
|
|
454
|
+
const { width, collapsed } = p;
|
|
455
|
+
return typeof width === 'number' && typeof collapsed === 'boolean'
|
|
456
|
+
? { width, collapsed }
|
|
457
|
+
: null;
|
|
458
|
+
}
|
|
459
|
+
catch {
|
|
460
|
+
return null;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
/**
|
|
464
|
+
* Persist generic panel state by key.
|
|
465
|
+
* Applies to localStorage instantly; server sync is debounced.
|
|
466
|
+
*/
|
|
467
|
+
setPanelState(key, width, collapsed) {
|
|
468
|
+
const all = this.load();
|
|
469
|
+
const panel = (all['panel'] ?? {});
|
|
470
|
+
panel[key] = { width: Math.round(width), collapsed };
|
|
471
|
+
all['panel'] = panel;
|
|
472
|
+
this.save(all);
|
|
473
|
+
}
|
|
474
|
+
// -- Page state -----------------------------------------------------------
|
|
475
|
+
/**
|
|
476
|
+
* Get all persisted state for a page namespace (e.g. 'vfs', 'media', 'nav').
|
|
477
|
+
*/
|
|
478
|
+
getPageState(pageKey) {
|
|
479
|
+
try {
|
|
480
|
+
const all = this.load();
|
|
481
|
+
const page = all['page'];
|
|
482
|
+
if (!page)
|
|
483
|
+
return null;
|
|
484
|
+
return page[pageKey] ?? null;
|
|
485
|
+
}
|
|
486
|
+
catch {
|
|
487
|
+
return null;
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
/**
|
|
491
|
+
* Merge partial state into a page namespace.
|
|
492
|
+
* Existing keys in the namespace are preserved; only provided keys are updated.
|
|
493
|
+
* Applies to localStorage instantly; server sync is debounced.
|
|
494
|
+
*/
|
|
495
|
+
setPageState(pageKey, state) {
|
|
496
|
+
const all = this.load();
|
|
497
|
+
const page = (all['page'] ?? {});
|
|
498
|
+
page[pageKey] = { ...(page[pageKey] ?? {}), ...state };
|
|
499
|
+
all['page'] = page;
|
|
500
|
+
this.save(all);
|
|
501
|
+
}
|
|
502
|
+
// -- Media (legacy pass-through — kept for compatibility) -----------------
|
|
503
|
+
/** @deprecated Use getPageState('media') instead */
|
|
504
|
+
getMediaViewMode() {
|
|
505
|
+
return this.getPageState('media')?.viewMode ?? null;
|
|
506
|
+
}
|
|
507
|
+
/** @deprecated Use setPageState('media', ...) instead */
|
|
508
|
+
setMediaViewMode(mode) {
|
|
509
|
+
this.setPageState('media', { viewMode: mode });
|
|
510
|
+
}
|
|
511
|
+
/** @deprecated Use getPanelState('media_panel_left') instead */
|
|
512
|
+
getMediaCollectionsPanel() {
|
|
513
|
+
return this.getPanelState('media_panel_left');
|
|
514
|
+
}
|
|
515
|
+
/** @deprecated Use setPanelState('media_panel_left', ...) instead */
|
|
516
|
+
setMediaCollectionsPanel(width, collapsed) {
|
|
517
|
+
this.setPanelState('media_panel_left', width, collapsed);
|
|
518
|
+
}
|
|
519
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: UserPreferencesService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
520
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: UserPreferencesService, providedIn: 'root' });
|
|
521
|
+
}
|
|
522
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: UserPreferencesService, decorators: [{
|
|
523
|
+
type: Injectable,
|
|
524
|
+
args: [{ providedIn: 'root' }]
|
|
525
|
+
}], ctorParameters: () => [] });
|
|
526
|
+
|
|
527
|
+
const STORAGE_KEY$1 = 'coolms_token';
|
|
528
|
+
let AuthState = class AuthState {
|
|
529
|
+
// `inject()` rather than constructor parameters, and the imports above are
|
|
530
|
+
// VALUE imports on purpose: an injected type must survive to runtime. As a
|
|
531
|
+
// constructor parameter that is invisible to `tsc`, which type-checks a
|
|
532
|
+
// type-only import happily and leaves the Angular compiler to fail with
|
|
533
|
+
// NG2003. Read as a value here, so the same mistake is a type error.
|
|
534
|
+
api = inject(IdentityApiClient);
|
|
535
|
+
prefs = inject(UserPreferencesService);
|
|
536
|
+
login(ctx, { identifier, password }) {
|
|
537
|
+
return this.api.login(identifier, password).pipe(tap((res) => {
|
|
538
|
+
const state = {
|
|
539
|
+
accessToken: res.accessToken,
|
|
540
|
+
refreshToken: res.refreshToken,
|
|
541
|
+
expiresAt: res.expiresAt,
|
|
542
|
+
user: res.user ?? null,
|
|
543
|
+
};
|
|
544
|
+
ctx.setState(state);
|
|
545
|
+
localStorage.setItem(STORAGE_KEY$1, JSON.stringify(state));
|
|
546
|
+
}),
|
|
547
|
+
// Fetch full user data (includes uiPrefs) to seed preferences
|
|
548
|
+
switchMap(() => this.api.me().pipe(catchError(() => of(null)))), tap(me => {
|
|
549
|
+
if (!me)
|
|
550
|
+
return;
|
|
551
|
+
// Update stored user with full data including uiPrefs
|
|
552
|
+
const updated = { ...ctx.getState(), user: me };
|
|
553
|
+
ctx.setState(updated);
|
|
554
|
+
localStorage.setItem(STORAGE_KEY$1, JSON.stringify(updated));
|
|
555
|
+
if (me.uiPrefs) {
|
|
556
|
+
this.prefs.loadFromServer(me.uiPrefs);
|
|
557
|
+
}
|
|
558
|
+
}));
|
|
559
|
+
}
|
|
560
|
+
logout(ctx) {
|
|
561
|
+
ctx.setState({ accessToken: null, refreshToken: null, expiresAt: null, user: null });
|
|
562
|
+
localStorage.removeItem(STORAGE_KEY$1);
|
|
563
|
+
}
|
|
564
|
+
restore(ctx) {
|
|
565
|
+
const raw = localStorage.getItem(STORAGE_KEY$1);
|
|
566
|
+
if (!raw)
|
|
567
|
+
return;
|
|
568
|
+
try {
|
|
569
|
+
const state = JSON.parse(raw);
|
|
570
|
+
// Restore whenever any token is present.
|
|
571
|
+
// If only the access token has expired but the refresh token is still
|
|
572
|
+
// valid, the HTTP interceptor will transparently refresh on the next
|
|
573
|
+
// request. Discarding state here would throw away the refresh token
|
|
574
|
+
// and force a full re-login unnecessarily.
|
|
575
|
+
if (state.accessToken || state.refreshToken) {
|
|
576
|
+
ctx.setState(state);
|
|
577
|
+
// Seed preferences from previously stored user (covers page-reload case)
|
|
578
|
+
if (state.user?.uiPrefs) {
|
|
579
|
+
this.prefs.loadFromServer(state.user.uiPrefs);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
else {
|
|
583
|
+
localStorage.removeItem(STORAGE_KEY$1);
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
catch {
|
|
587
|
+
localStorage.removeItem(STORAGE_KEY$1);
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
setTokens(ctx, { response }) {
|
|
591
|
+
const state = {
|
|
592
|
+
accessToken: response.accessToken,
|
|
593
|
+
refreshToken: response.refreshToken,
|
|
594
|
+
expiresAt: response.expiresAt,
|
|
595
|
+
user: response.user ?? ctx.getState().user,
|
|
596
|
+
};
|
|
597
|
+
ctx.setState(state);
|
|
598
|
+
localStorage.setItem(STORAGE_KEY$1, JSON.stringify(state));
|
|
599
|
+
}
|
|
600
|
+
patchCurrentUser(ctx, { patch }) {
|
|
601
|
+
const current = ctx.getState();
|
|
602
|
+
if (!current.user)
|
|
603
|
+
return;
|
|
604
|
+
const updated = { ...current, user: { ...current.user, ...patch } };
|
|
605
|
+
ctx.setState(updated);
|
|
606
|
+
localStorage.setItem(STORAGE_KEY$1, JSON.stringify(updated));
|
|
607
|
+
}
|
|
608
|
+
static isAuthenticated(state) {
|
|
609
|
+
return null !== state.accessToken;
|
|
610
|
+
}
|
|
611
|
+
static accessToken(state) {
|
|
612
|
+
return state.accessToken;
|
|
613
|
+
}
|
|
614
|
+
static refreshToken(state) {
|
|
615
|
+
return state.refreshToken;
|
|
616
|
+
}
|
|
617
|
+
/**
|
|
618
|
+
* Sub-phase Y -- expose the access-token expiry timestamp so
|
|
619
|
+
* preemptive-refresh callers (e.g., Centrifuge getToken
|
|
620
|
+
* callbacks) can decide whether to rotate before issuing the
|
|
621
|
+
* next protected request, instead of relying on the
|
|
622
|
+
* interceptor's reactive 401-retry path.
|
|
623
|
+
*/
|
|
624
|
+
static expiresAt(state) {
|
|
625
|
+
return state.expiresAt;
|
|
626
|
+
}
|
|
627
|
+
static currentUser(state) {
|
|
628
|
+
return state.user;
|
|
629
|
+
}
|
|
630
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: AuthState, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
631
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: AuthState });
|
|
632
|
+
};
|
|
633
|
+
__decorate([
|
|
634
|
+
Action(Login)
|
|
635
|
+
], AuthState.prototype, "login", null);
|
|
636
|
+
__decorate([
|
|
637
|
+
Action(Logout)
|
|
638
|
+
], AuthState.prototype, "logout", null);
|
|
639
|
+
__decorate([
|
|
640
|
+
Action(RestoreSession)
|
|
641
|
+
], AuthState.prototype, "restore", null);
|
|
642
|
+
__decorate([
|
|
643
|
+
Action(SetTokens)
|
|
644
|
+
], AuthState.prototype, "setTokens", null);
|
|
645
|
+
__decorate([
|
|
646
|
+
Action(PatchCurrentUser)
|
|
647
|
+
], AuthState.prototype, "patchCurrentUser", null);
|
|
648
|
+
__decorate([
|
|
649
|
+
Selector()
|
|
650
|
+
], AuthState, "isAuthenticated", null);
|
|
651
|
+
__decorate([
|
|
652
|
+
Selector()
|
|
653
|
+
], AuthState, "accessToken", null);
|
|
654
|
+
__decorate([
|
|
655
|
+
Selector()
|
|
656
|
+
], AuthState, "refreshToken", null);
|
|
657
|
+
__decorate([
|
|
658
|
+
Selector()
|
|
659
|
+
], AuthState, "expiresAt", null);
|
|
660
|
+
__decorate([
|
|
661
|
+
Selector()
|
|
662
|
+
], AuthState, "currentUser", null);
|
|
663
|
+
AuthState = __decorate([
|
|
664
|
+
State({
|
|
665
|
+
name: 'auth',
|
|
666
|
+
defaults: { accessToken: null, refreshToken: null, expiresAt: null, user: null },
|
|
667
|
+
})
|
|
668
|
+
], AuthState);
|
|
669
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: AuthState, decorators: [{
|
|
670
|
+
type: Injectable
|
|
671
|
+
}], propDecorators: { login: [], logout: [], restore: [], setTokens: [], patchCurrentUser: [] } });
|
|
672
|
+
|
|
673
|
+
const LOCK_NAME = 'coolms_auth_refresh';
|
|
674
|
+
const FRESH_TOKEN_GRACE_MS = 30_000;
|
|
675
|
+
/**
|
|
676
|
+
* Two-layer refresh coordinator: an intra-tab `shareReplay(1)`
|
|
677
|
+
* mutex dedupes concurrent callers within one tab, and a
|
|
678
|
+
* cross-tab `navigator.locks` wrapper ensures only one tab in
|
|
679
|
+
* the browser issues the actual `POST /auth/refresh` at a time.
|
|
680
|
+
*
|
|
681
|
+
* Without the cross-tab layer, two tabs racing the same expired
|
|
682
|
+
* refresh-token both POST `/auth/refresh`; the backend's
|
|
683
|
+
* `isUsed` replay branch revokes every token for the user on
|
|
684
|
+
* the second arrival and the operator is kicked to /login.
|
|
685
|
+
*
|
|
686
|
+
* The Web Lock body re-reads the current access-token expiry from
|
|
687
|
+
* `AuthState` before issuing the HTTP call. When this tab waited
|
|
688
|
+
* behind another tab's refresh, that tab's `SetTokens` dispatch
|
|
689
|
+
* has already published fresh values into shared `localStorage`,
|
|
690
|
+
* `CrossTabAuthSyncService` has mirrored them into this tab's
|
|
691
|
+
* NGXS state, and the lock body simply returns the cached access
|
|
692
|
+
* token without another network round-trip.
|
|
693
|
+
*
|
|
694
|
+
* `Logout` fires only when the refresh endpoint returns 401
|
|
695
|
+
* (real auth failure). Transient errors (network blips, 5xx,
|
|
696
|
+
* CORS, timeouts) propagate without clearing the session so a
|
|
697
|
+
* momentary refresh failure does not kill a valid login.
|
|
698
|
+
*/
|
|
699
|
+
class AuthRefreshCoordinator {
|
|
700
|
+
api = inject(IdentityApiClient);
|
|
701
|
+
store = inject(Store);
|
|
702
|
+
router = inject(Router);
|
|
703
|
+
inFlight = null;
|
|
704
|
+
/**
|
|
705
|
+
* Return the in-flight refresh Observable, or spawn a new one
|
|
706
|
+
* with the supplied refresh-token value.
|
|
707
|
+
*
|
|
708
|
+
* Callers subscribe via `switchMap` / `firstValueFrom` to retry
|
|
709
|
+
* their original request with the resolved access token.
|
|
710
|
+
*/
|
|
711
|
+
refresh(refreshToken) {
|
|
712
|
+
if (this.inFlight) {
|
|
713
|
+
return this.inFlight;
|
|
714
|
+
}
|
|
715
|
+
this.inFlight = defer(() => this.refreshWithCrossTabLock(refreshToken)).pipe(catchError(refreshErr => {
|
|
716
|
+
const isAuthFailure = refreshErr instanceof HttpErrorResponse && refreshErr.status === 401;
|
|
717
|
+
if (isAuthFailure) {
|
|
718
|
+
this.store.dispatch(new Logout());
|
|
719
|
+
if (this.router.navigated) {
|
|
720
|
+
void this.router.navigate(['/login']);
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
return throwError(() => refreshErr);
|
|
724
|
+
}), shareReplay(1), finalize(() => {
|
|
725
|
+
this.inFlight = null;
|
|
726
|
+
}));
|
|
727
|
+
return this.inFlight;
|
|
728
|
+
}
|
|
729
|
+
/**
|
|
730
|
+
* Run the refresh body inside `navigator.locks` when the API is
|
|
731
|
+
* available; degrade to direct invocation otherwise. The lock
|
|
732
|
+
* body checks for state already updated by a sibling tab before
|
|
733
|
+
* issuing its own HTTP call.
|
|
734
|
+
*/
|
|
735
|
+
refreshWithCrossTabLock(refreshToken) {
|
|
736
|
+
const lockBody = () => this.executeRefresh(refreshToken);
|
|
737
|
+
if (typeof navigator === 'undefined' || !('locks' in navigator)) {
|
|
738
|
+
return from(lockBody());
|
|
739
|
+
}
|
|
740
|
+
return from(navigator.locks.request(LOCK_NAME, lockBody).then(value => {
|
|
741
|
+
if (value === undefined) {
|
|
742
|
+
throw new Error('Refresh lock aborted before completing.');
|
|
743
|
+
}
|
|
744
|
+
return value;
|
|
745
|
+
}));
|
|
746
|
+
}
|
|
747
|
+
/**
|
|
748
|
+
* Lock body. Re-reads `AuthState.expiresAt` first: if another
|
|
749
|
+
* tab published fresh tokens while we were queued, return the
|
|
750
|
+
* cached access token directly. Otherwise read the latest
|
|
751
|
+
* refresh-token value from state (it may have rotated while we
|
|
752
|
+
* waited) and issue the HTTP refresh.
|
|
753
|
+
*/
|
|
754
|
+
async executeRefresh(originalRefreshToken) {
|
|
755
|
+
const cachedAccess = this.tryConsumeFreshState();
|
|
756
|
+
if (cachedAccess !== null) {
|
|
757
|
+
return cachedAccess;
|
|
758
|
+
}
|
|
759
|
+
const currentRefreshToken = this.store.selectSnapshot(AuthState.refreshToken) ?? originalRefreshToken;
|
|
760
|
+
const response = await firstValueFrom(this.api.refresh(currentRefreshToken));
|
|
761
|
+
this.store.dispatch(new SetTokens(response));
|
|
762
|
+
return response.accessToken;
|
|
763
|
+
}
|
|
764
|
+
/**
|
|
765
|
+
* Return the cached access token when `AuthState.expiresAt` has
|
|
766
|
+
* more than `FRESH_TOKEN_GRACE_MS` milliseconds remaining --
|
|
767
|
+
* signalling that some other tab refreshed for us. Null
|
|
768
|
+
* otherwise.
|
|
769
|
+
*/
|
|
770
|
+
tryConsumeFreshState() {
|
|
771
|
+
const accessToken = this.store.selectSnapshot(AuthState.accessToken);
|
|
772
|
+
const expiresAtStr = this.store.selectSnapshot(AuthState.expiresAt);
|
|
773
|
+
if (accessToken === null || expiresAtStr === null) {
|
|
774
|
+
return null;
|
|
775
|
+
}
|
|
776
|
+
const expiresAtMs = new Date(expiresAtStr).getTime();
|
|
777
|
+
if (Number.isNaN(expiresAtMs)) {
|
|
778
|
+
return null;
|
|
779
|
+
}
|
|
780
|
+
if (Date.now() < expiresAtMs - FRESH_TOKEN_GRACE_MS) {
|
|
781
|
+
return accessToken;
|
|
782
|
+
}
|
|
783
|
+
return null;
|
|
784
|
+
}
|
|
785
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: AuthRefreshCoordinator, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
786
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: AuthRefreshCoordinator, providedIn: 'root' });
|
|
787
|
+
}
|
|
788
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: AuthRefreshCoordinator, decorators: [{
|
|
789
|
+
type: Injectable,
|
|
790
|
+
args: [{ providedIn: 'root' }]
|
|
791
|
+
}] });
|
|
792
|
+
|
|
793
|
+
// -- Opt-out context token -----------------------------------------------------
|
|
794
|
+
//
|
|
795
|
+
// Set BYPASS_AUTH to true on any HttpRequest to skip adding the Authorization
|
|
796
|
+
// header entirely. Used by AppInitService for the bootstrap config request so
|
|
797
|
+
// that a stale localStorage token does not cause a 401 on a public endpoint.
|
|
798
|
+
const BYPASS_AUTH = new HttpContextToken(() => false);
|
|
799
|
+
// -----------------------------------------------------------------------------
|
|
800
|
+
const authInterceptor = (req, next) => {
|
|
801
|
+
const store = inject(Store);
|
|
802
|
+
const router = inject(Router);
|
|
803
|
+
const coordinator = inject(AuthRefreshCoordinator);
|
|
804
|
+
const initService = inject(AppInitService);
|
|
805
|
+
// Caller explicitly requested no auth header (e.g. the bootstrap config
|
|
806
|
+
// fetch — the endpoint is public and a stale token would cause 401).
|
|
807
|
+
if (req.context.get(BYPASS_AUTH)) {
|
|
808
|
+
return next(req);
|
|
809
|
+
}
|
|
810
|
+
// Auth endpoints are public by design. The backend's JWT firewall rejects any
|
|
811
|
+
// request that carries an invalid/expired Bearer token — even on endpoints
|
|
812
|
+
// that would otherwise allow anonymous access — so never forward a stored
|
|
813
|
+
// token to login or refresh.
|
|
814
|
+
if (req.url.includes('/auth/login') || req.url.includes('/auth/refresh')) {
|
|
815
|
+
return next(req);
|
|
816
|
+
}
|
|
817
|
+
// Queue behind AppInitService.ready$ so that token restoration from
|
|
818
|
+
// localStorage (RestoreSession) is guaranteed to be in NGXS state before
|
|
819
|
+
// we read it. On F5 the interceptor fires synchronously for every pending
|
|
820
|
+
// request before APP_INITIALIZER has completed; without this guard the
|
|
821
|
+
// token snapshot is null and every request gets a 401 -> refresh cycle even
|
|
822
|
+
// for a perfectly valid session.
|
|
823
|
+
//
|
|
824
|
+
// ready$ is a ReplaySubject(1) that completes after load() finishes, so:
|
|
825
|
+
// - requests fired during init queue here and flush the moment ready$ emits;
|
|
826
|
+
// - requests fired after init pass through take(1) immediately (replayed value).
|
|
827
|
+
return initService.ready$.pipe(take(1), switchMap$1(() => {
|
|
828
|
+
const token = store.selectSnapshot(AuthState.accessToken);
|
|
829
|
+
const authed = token
|
|
830
|
+
? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } })
|
|
831
|
+
: req;
|
|
832
|
+
return next(authed).pipe(catchError((err) => {
|
|
833
|
+
if (!(err instanceof HttpErrorResponse) || err.status !== 401) {
|
|
834
|
+
return throwError(() => err);
|
|
835
|
+
}
|
|
836
|
+
// Avoid infinite loop — skip refresh for auth endpoints themselves.
|
|
837
|
+
if (req.url.includes('/auth/refresh') || req.url.includes('/auth/login')) {
|
|
838
|
+
return throwError(() => err);
|
|
839
|
+
}
|
|
840
|
+
const refreshToken = store.selectSnapshot(AuthState.refreshToken);
|
|
841
|
+
if (!refreshToken) {
|
|
842
|
+
store.dispatch(new Logout());
|
|
843
|
+
// Only navigate programmatically once the router has already
|
|
844
|
+
// completed its initial navigation. During APP_INITIALIZER the
|
|
845
|
+
// router is still blocked; authGuard handles the redirect there.
|
|
846
|
+
if (router.navigated)
|
|
847
|
+
void router.navigate(['/login']);
|
|
848
|
+
return throwError(() => err);
|
|
849
|
+
}
|
|
850
|
+
// Delegate refresh to the shared coordinator so the
|
|
851
|
+
// Centrifuge getToken path and the interceptor share ONE
|
|
852
|
+
// in-flight refresh. Without this, two parallel
|
|
853
|
+
// `api.refresh(refreshToken)` calls (one from each mutex)
|
|
854
|
+
// would send the same refresh-token twice and trigger the
|
|
855
|
+
// backend's `isUsed` replay branch on the second arrival,
|
|
856
|
+
// wiping the whole session.
|
|
857
|
+
return coordinator.refresh(refreshToken).pipe(switchMap$1(newToken => next(req.clone({ setHeaders: { Authorization: `Bearer ${newToken}` } }))));
|
|
858
|
+
}));
|
|
859
|
+
}));
|
|
860
|
+
};
|
|
861
|
+
|
|
862
|
+
const STORAGE_KEY = 'coolms_token';
|
|
863
|
+
/**
|
|
864
|
+
* Bridges shared `localStorage` mutations into the NGXS auth
|
|
865
|
+
* state so a refresh executed in one tab silently propagates to
|
|
866
|
+
* every other open tab.
|
|
867
|
+
*
|
|
868
|
+
* The browser fires `storage` events in tabs OTHER than the one
|
|
869
|
+
* that mutated `localStorage`. So when Tab A's
|
|
870
|
+
* `AuthRefreshCoordinator` rotates the token pair and `SetTokens`
|
|
871
|
+
* persists the new values, every sibling tab receives an event
|
|
872
|
+
* here and dispatches `SetTokens` against its own NGXS state --
|
|
873
|
+
* no extra HTTP roundtrip, no extra refresh contention.
|
|
874
|
+
*
|
|
875
|
+
* Pairs with the `navigator.locks` cross-tab mutex in
|
|
876
|
+
* `AuthRefreshCoordinator`: locks ensure only one tab issues the
|
|
877
|
+
* refresh, this listener propagates the result to the rest.
|
|
878
|
+
*
|
|
879
|
+
* `Logout` from any tab clears `coolms_token` (newValue === null)
|
|
880
|
+
* and this listener mirrors that into the sibling tabs so the
|
|
881
|
+
* shell redirects to `/login` without waiting for the next
|
|
882
|
+
* protected request to 401.
|
|
883
|
+
*
|
|
884
|
+
* Started from `AppInitService.load()` so the listener is in
|
|
885
|
+
* place before any protected HTTP fires.
|
|
886
|
+
*/
|
|
887
|
+
class CrossTabAuthSyncService {
|
|
888
|
+
store = inject(Store);
|
|
889
|
+
listenerAttached = false;
|
|
890
|
+
start() {
|
|
891
|
+
if (this.listenerAttached) {
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
this.listenerAttached = true;
|
|
895
|
+
window.addEventListener('storage', this.handleStorageEvent);
|
|
896
|
+
}
|
|
897
|
+
handleStorageEvent = (event) => {
|
|
898
|
+
if (event.key !== STORAGE_KEY) {
|
|
899
|
+
return;
|
|
900
|
+
}
|
|
901
|
+
// Sibling tab cleared the key (logout dispatch or
|
|
902
|
+
// RestoreSession parse-error cleanup). Mirror the clear so
|
|
903
|
+
// this tab does not keep operating against a revoked
|
|
904
|
+
// server-side session.
|
|
905
|
+
if (event.newValue === null) {
|
|
906
|
+
this.store.dispatch(new Logout());
|
|
907
|
+
return;
|
|
908
|
+
}
|
|
909
|
+
// Parse the new value and dispatch SetTokens so this tab's
|
|
910
|
+
// in-memory NGXS state reflects what the originating tab
|
|
911
|
+
// just wrote. Malformed payloads are ignored.
|
|
912
|
+
let parsed;
|
|
913
|
+
try {
|
|
914
|
+
parsed = JSON.parse(event.newValue);
|
|
915
|
+
}
|
|
916
|
+
catch {
|
|
917
|
+
return;
|
|
918
|
+
}
|
|
919
|
+
if (typeof parsed.accessToken !== 'string' || typeof parsed.refreshToken !== 'string' || typeof parsed.expiresAt !== 'string') {
|
|
920
|
+
return;
|
|
921
|
+
}
|
|
922
|
+
const tokenResponse = {
|
|
923
|
+
accessToken: parsed.accessToken,
|
|
924
|
+
refreshToken: parsed.refreshToken,
|
|
925
|
+
expiresAt: parsed.expiresAt,
|
|
926
|
+
user: parsed.user ?? undefined,
|
|
927
|
+
};
|
|
928
|
+
this.store.dispatch(new SetTokens(tokenResponse));
|
|
929
|
+
};
|
|
930
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: CrossTabAuthSyncService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
931
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: CrossTabAuthSyncService, providedIn: 'root' });
|
|
932
|
+
}
|
|
933
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: CrossTabAuthSyncService, decorators: [{
|
|
934
|
+
type: Injectable,
|
|
935
|
+
args: [{ providedIn: 'root' }]
|
|
936
|
+
}] });
|
|
937
|
+
|
|
938
|
+
class AppInitService {
|
|
939
|
+
// Injected as values, not constructor parameters: an injection token has to
|
|
940
|
+
// exist at runtime, and a type-only import of one type-checks clean while
|
|
941
|
+
// the Angular compiler rejects it with NG2003.
|
|
942
|
+
http = inject(HttpClient);
|
|
943
|
+
store = inject(Store);
|
|
944
|
+
router = inject(Router);
|
|
945
|
+
location = inject(Location);
|
|
946
|
+
prefs = inject(UserPreferencesService);
|
|
947
|
+
crossTabSync = inject(CrossTabAuthSyncService);
|
|
948
|
+
refreshCoordinator = inject(AuthRefreshCoordinator);
|
|
949
|
+
/** The only hardcoded URL — everything else comes from the manifest. */
|
|
950
|
+
configUrl = '/api/v1/theme/config';
|
|
951
|
+
/**
|
|
952
|
+
* Emits (once) when load() has fully completed — tokens settled, manifest
|
|
953
|
+
* set (or swallowed on error). authGuard subscribes to this so it never
|
|
954
|
+
* evaluates isAuthenticated against a partially-restored stale token.
|
|
955
|
+
*/
|
|
956
|
+
initComplete = new ReplaySubject(1);
|
|
957
|
+
ready$ = this.initComplete.asObservable();
|
|
958
|
+
async load() {
|
|
959
|
+
// -- Step 0: cross-tab sync --------------------------------------------
|
|
960
|
+
//
|
|
961
|
+
// Install the storage-event listener before RestoreSession so that
|
|
962
|
+
// any localStorage mutation from a sibling tab during bootstrap
|
|
963
|
+
// (e.g., a parallel tab refreshing tokens just as we load) is mirrored
|
|
964
|
+
// into this tab's NGXS state.
|
|
965
|
+
this.crossTabSync.start();
|
|
966
|
+
// -- Step 1: restore tokens from localStorage --------------------------
|
|
967
|
+
//
|
|
968
|
+
// RestoreSession is synchronous (ctx.setState from localStorage), so
|
|
969
|
+
// this await resolves in the same microtask. Tokens are in NGXS state
|
|
970
|
+
// before ANY subsequent HTTP request fires — the auth interceptor reads
|
|
971
|
+
// the token from state when attaching Authorization headers, so this
|
|
972
|
+
// ordering prevents unauthenticated requests on page reload (F5).
|
|
973
|
+
await firstValueFrom(this.store.dispatch(new RestoreSession()));
|
|
974
|
+
// -- Step 2: fetch the manifest ----------------------------------------
|
|
975
|
+
//
|
|
976
|
+
// BYPASS_AUTH is required here — not optional. The manifest endpoint
|
|
977
|
+
// is public, but two specific failure modes make bypassing necessary:
|
|
978
|
+
//
|
|
979
|
+
// a) The stored access token may be expired. Without BYPASS_AUTH the
|
|
980
|
+
// interceptor attaches the expired token, gets a 401, and tries to
|
|
981
|
+
// refresh. But the refresh endpoint URL comes from the manifest
|
|
982
|
+
// (api.refresh() reads manifest.auth.refresh), which hasn't been
|
|
983
|
+
// loaded yet — triggering a null-dereference crash before the app
|
|
984
|
+
// can recover.
|
|
985
|
+
//
|
|
986
|
+
// b) Even if the token is valid, attaching it to a public endpoint
|
|
987
|
+
// that ignores auth adds unnecessary coupling.
|
|
988
|
+
//
|
|
989
|
+
// Consequence: every page load issues one unauthenticated config
|
|
990
|
+
// request, which is intentional. All subsequent API calls carry the
|
|
991
|
+
// restored (or refreshed) token normally.
|
|
992
|
+
const config = await firstValueFrom(this.http.get(this.configUrl, {
|
|
993
|
+
context: new HttpContext().set(BYPASS_AUTH, true),
|
|
994
|
+
}).pipe(tap$1(cfg => this.store.dispatch(new SetAppConfig(cfg))), catchError(() => {
|
|
995
|
+
console.warn('CoolMS: theme/config unreachable, using safe defaults');
|
|
996
|
+
return of(null);
|
|
997
|
+
})));
|
|
998
|
+
// -- Step 3: validate the restored session -----------------------------
|
|
999
|
+
//
|
|
1000
|
+
// RestoreSession trusts whatever tokens are in localStorage, but they may
|
|
1001
|
+
// have been revoked out-of-band — most notably, signing out on the public
|
|
1002
|
+
// SSR site revokes the user's WHOLE token set. We MUST settle the real
|
|
1003
|
+
// auth state here, BEFORE step 4 signals ready$: both the auth interceptor
|
|
1004
|
+
// AND authGuard gate on ready$, so if we signalled first, the guard would
|
|
1005
|
+
// race ahead and mount the shell against the stale isAuthenticated=true
|
|
1006
|
+
// before this probe finished (-> half-loaded shell + "Session expired"
|
|
1007
|
+
// toasts, the exact bug this fixes). Because the probe itself cannot wait
|
|
1008
|
+
// on ready$ (that would deadlock), validateSession() bypasses the
|
|
1009
|
+
// interceptor and attaches the token / drives the refresh by hand.
|
|
1010
|
+
const meUrl = config?.manifest.identity?.meUrl;
|
|
1011
|
+
if (meUrl && this.store.selectSnapshot(AuthState.isAuthenticated)) {
|
|
1012
|
+
await this.validateSession(meUrl);
|
|
1013
|
+
}
|
|
1014
|
+
// -- Step 4: signal authGuard + unblock the interceptor ----------------
|
|
1015
|
+
//
|
|
1016
|
+
// Auth state is now settled (session confirmed, refreshed, or Logout
|
|
1017
|
+
// dispatched). ReplaySubject(1) replays to guards/requests that subscribe
|
|
1018
|
+
// afterwards, so they evaluate against the final isAuthenticated value.
|
|
1019
|
+
this.initComplete.next();
|
|
1020
|
+
this.initComplete.complete();
|
|
1021
|
+
// -- Step 5: navigate to last-visited route ----------------------------
|
|
1022
|
+
//
|
|
1023
|
+
// Only when the session survived validation. If it did not, isAuthenticated
|
|
1024
|
+
// is now false, we skip the saved-route navigation, and authGuard sends the
|
|
1025
|
+
// initial navigation to /login.
|
|
1026
|
+
//
|
|
1027
|
+
// Only restore when the user opened the bare /admin root. An explicit
|
|
1028
|
+
// deep link (pasted /admin/sync-fleet, a bookmark, a shared URL) must
|
|
1029
|
+
// win over the saved route. The router cannot tell us which one this is:
|
|
1030
|
+
// withEnabledBlockingInitialNavigation holds the initial navigation until
|
|
1031
|
+
// this initializer resolves, so router.url is still '/'. The browser
|
|
1032
|
+
// location is the only record of what was requested — Location.path()
|
|
1033
|
+
// reads it with the /admin base href stripped, so the bare root (with or
|
|
1034
|
+
// without trailing slash) yields ''. Anything else, including a root URL
|
|
1035
|
+
// carrying query params, is treated as an explicit destination.
|
|
1036
|
+
if (this.store.selectSnapshot(AuthState.isAuthenticated)) {
|
|
1037
|
+
const requested = this.location.path();
|
|
1038
|
+
if (requested === '' || requested === '/') {
|
|
1039
|
+
const saved = this.prefs.getPageState('nav');
|
|
1040
|
+
if (saved?.lastRoute && !saved.lastRoute.startsWith('/login')) {
|
|
1041
|
+
void this.router.navigateByUrl(saved.lastRoute);
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
/**
|
|
1047
|
+
* Confirm the restored session is still alive, settling AuthState before the
|
|
1048
|
+
* app unblocks. Runs OUTSIDE the auth interceptor (BYPASS_AUTH) because the
|
|
1049
|
+
* interceptor queues behind ready$, which has not fired yet at this point.
|
|
1050
|
+
*
|
|
1051
|
+
* - access token accepted -> done, session alive;
|
|
1052
|
+
* - access token rejected -> attempt ONE refresh (access tokens are short-lived,
|
|
1053
|
+
* so an expired one with a valid refresh token must
|
|
1054
|
+
* stay logged in). The coordinator dispatches Logout
|
|
1055
|
+
* on a refresh 401 and SetTokens on success; a
|
|
1056
|
+
* transient failure (5xx/network) is swallowed so a
|
|
1057
|
+
* momentary blip never kills a valid session.
|
|
1058
|
+
*/
|
|
1059
|
+
async validateSession(meUrl) {
|
|
1060
|
+
const token = this.store.selectSnapshot(AuthState.accessToken);
|
|
1061
|
+
if (await this.probe(meUrl, token)) {
|
|
1062
|
+
return;
|
|
1063
|
+
}
|
|
1064
|
+
const refreshToken = this.store.selectSnapshot(AuthState.refreshToken);
|
|
1065
|
+
if (!refreshToken) {
|
|
1066
|
+
this.store.dispatch(new Logout());
|
|
1067
|
+
return;
|
|
1068
|
+
}
|
|
1069
|
+
let refreshedToken = null;
|
|
1070
|
+
try {
|
|
1071
|
+
refreshedToken = await firstValueFrom(this.refreshCoordinator.refresh(refreshToken));
|
|
1072
|
+
}
|
|
1073
|
+
catch {
|
|
1074
|
+
// 401 -> coordinator already dispatched Logout; transient -> session kept.
|
|
1075
|
+
return;
|
|
1076
|
+
}
|
|
1077
|
+
// Refresh resolved — but the coordinator's fresh-state optimisation can hand
|
|
1078
|
+
// back the SAME access token (without a network round-trip) when its stored
|
|
1079
|
+
// expiry still looks fresh. For a token that was revoked but not yet expired
|
|
1080
|
+
// (signing out on the SSR site while the access token is still in its TTL),
|
|
1081
|
+
// that token is dead despite looking fresh. Re-probe with whatever we now
|
|
1082
|
+
// hold; a second rejection means the session is genuinely gone.
|
|
1083
|
+
if (!(await this.probe(meUrl, refreshedToken))) {
|
|
1084
|
+
this.store.dispatch(new Logout());
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
/** GET an authed endpoint with an explicit Bearer header, bypassing the interceptor. */
|
|
1088
|
+
probe(url, token) {
|
|
1089
|
+
return firstValueFrom(this.http.get(url, {
|
|
1090
|
+
context: new HttpContext().set(BYPASS_AUTH, true),
|
|
1091
|
+
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
|
1092
|
+
}).pipe(map(() => true), catchError(() => of(false))));
|
|
1093
|
+
}
|
|
1094
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: AppInitService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
1095
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: AppInitService, providedIn: 'root' });
|
|
1096
|
+
}
|
|
1097
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: AppInitService, decorators: [{
|
|
1098
|
+
type: Injectable,
|
|
1099
|
+
args: [{ providedIn: 'root' }]
|
|
1100
|
+
}] });
|
|
1101
|
+
|
|
1102
|
+
/**
|
|
1103
|
+
* Protects routes that require authentication.
|
|
1104
|
+
*
|
|
1105
|
+
* The guard is intentionally ASYNC: it waits for AppInitService.ready$ before
|
|
1106
|
+
* evaluating auth state. Without this, Angular's router can evaluate
|
|
1107
|
+
* isAuthenticated while APP_INITIALIZER is still in-flight — RestoreSession
|
|
1108
|
+
* will have placed a non-null (but expired) token in state, causing the guard
|
|
1109
|
+
* to pass even though the subsequent config/refresh requests will fail and
|
|
1110
|
+
* dispatch Logout. Waiting for ready$ guarantees the auth state is settled.
|
|
1111
|
+
*/
|
|
1112
|
+
const authGuard = () => {
|
|
1113
|
+
const init = inject(AppInitService);
|
|
1114
|
+
const store = inject(Store);
|
|
1115
|
+
const router = inject(Router);
|
|
1116
|
+
return init.ready$.pipe(take(1), map(() => {
|
|
1117
|
+
if (store.selectSnapshot(AuthState.isAuthenticated)) {
|
|
1118
|
+
return true;
|
|
1119
|
+
}
|
|
1120
|
+
return router.createUrlTree(['/login']);
|
|
1121
|
+
}));
|
|
1122
|
+
};
|
|
1123
|
+
|
|
1124
|
+
/**
|
|
1125
|
+
* Guards the `/login` route -- redirects already-authenticated
|
|
1126
|
+
* callers to admin home so a stale tab parked on `/login` cannot
|
|
1127
|
+
* remain mounted while another tab is logged in. When Tab A logs
|
|
1128
|
+
* in fresh, Tab B's `RestoreSession` (driven by APP_INITIALIZER)
|
|
1129
|
+
* reads the new token from shared `localStorage` and populates
|
|
1130
|
+
* `AuthState`; this guard then sees `isAuthenticated === true`
|
|
1131
|
+
* and routes Tab B to `/`.
|
|
1132
|
+
*
|
|
1133
|
+
* Same `ready$` wait as `authGuard` -- ensures `RestoreSession`
|
|
1134
|
+
* has run before the snapshot is read; otherwise a fresh F5 on
|
|
1135
|
+
* `/login` with a valid stored session would briefly evaluate
|
|
1136
|
+
* as anonymous, allow `/login`, and only then have the token
|
|
1137
|
+
* populated.
|
|
1138
|
+
*/
|
|
1139
|
+
const loginPageGuard = () => {
|
|
1140
|
+
const init = inject(AppInitService);
|
|
1141
|
+
const store = inject(Store);
|
|
1142
|
+
const router = inject(Router);
|
|
1143
|
+
return init.ready$.pipe(take(1), map(() => {
|
|
1144
|
+
if (store.selectSnapshot(AuthState.isAuthenticated)) {
|
|
1145
|
+
return router.createUrlTree(['/']);
|
|
1146
|
+
}
|
|
1147
|
+
return true;
|
|
1148
|
+
}));
|
|
1149
|
+
};
|
|
1150
|
+
|
|
1151
|
+
class LoginComponent {
|
|
1152
|
+
identifier = '';
|
|
1153
|
+
password = '';
|
|
1154
|
+
loading = false;
|
|
1155
|
+
error = null;
|
|
1156
|
+
store = inject(Store);
|
|
1157
|
+
router = inject(Router);
|
|
1158
|
+
submit() {
|
|
1159
|
+
if (!this.identifier || !this.password)
|
|
1160
|
+
return;
|
|
1161
|
+
this.loading = true;
|
|
1162
|
+
this.error = null;
|
|
1163
|
+
this.store.dispatch(new Login(this.identifier, this.password)).subscribe({
|
|
1164
|
+
next: () => {
|
|
1165
|
+
// A rejected navigation used to vanish: nothing resets `loading`
|
|
1166
|
+
// on the success path, because the page is expected to go
|
|
1167
|
+
// away. If it does not, the form spins for ever with no reason
|
|
1168
|
+
// given, so say so instead.
|
|
1169
|
+
void this.router.navigate(['/']).catch(() => {
|
|
1170
|
+
this.loading = false;
|
|
1171
|
+
this.error = 'Signed in, but the admin could not be opened. Please reload.';
|
|
1172
|
+
});
|
|
1173
|
+
},
|
|
1174
|
+
error: (err) => {
|
|
1175
|
+
this.loading = false;
|
|
1176
|
+
this.error = err?.error?.detail ?? err?.error?.message ?? err?.message ?? 'Invalid credentials. Please try again.';
|
|
1177
|
+
},
|
|
1178
|
+
});
|
|
1179
|
+
}
|
|
1180
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: LoginComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
|
|
1181
|
+
static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "22.1.3", type: LoginComponent, isStandalone: true, selector: "coolms-admin-login", ngImport: i0, template: "<div class=\"d-flex align-items-center justify-content-center min-vh-100 bg-light\">\n <div class=\"card shadow-sm\" style=\"width: 360px\">\n <div class=\"card-body p-4\">\n <h1 class=\"h5 mb-1\">CoolMS Admin</h1>\n <p class=\"text-muted small mb-4\">Sign in to continue</p>\n\n <div *ngIf=\"error\" class=\"alert alert-danger py-2 small\">{{ error }}</div>\n\n <form (ngSubmit)=\"submit()\" #loginForm=\"ngForm\">\n <div class=\"mb-3\">\n <label class=\"form-label\">Email or username</label>\n <input\n type=\"text\"\n class=\"form-control\"\n [(ngModel)]=\"identifier\"\n name=\"identifier\"\n required\n autocomplete=\"username\"\n />\n </div>\n <div class=\"mb-3\">\n <label class=\"form-label\">Password</label>\n <input\n type=\"password\"\n class=\"form-control\"\n [(ngModel)]=\"password\"\n name=\"password\"\n required\n autocomplete=\"current-password\"\n />\n </div>\n <button\n type=\"submit\"\n class=\"cms-btn cms-btn-primary w-100 justify-content-center\"\n [disabled]=\"loading || loginForm.invalid\"\n >\n {{ loading ? 'Signing in\u2026' : 'Sign in' }}\n </button>\n </form>\n </div>\n </div>\n</div>\n", dependencies: [{ kind: "ngmodule", type: FormsModule }, { kind: "directive", type: i1.ɵNgNoValidate, selector: "form:not([ngNoForm]):not([ngNativeValidate])" }, { kind: "directive", type: i1.DefaultValueAccessor, selector: "input:not([type=checkbox]):not([ngNoCva])[formControlName],textarea:not([ngNoCva])[formControlName],input:not([type=checkbox]):not([ngNoCva])[formControl],textarea:not([ngNoCva])[formControl],input:not([type=checkbox]):not([ngNoCva])[ngModel],textarea:not([ngNoCva])[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i1.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i1.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],[formArray],form:not([ngNoForm]),[ngForm]" }, { kind: "directive", type: i1.RequiredValidator, selector: ":not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]", inputs: ["required"] }, { kind: "directive", type: i1.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { kind: "directive", type: i1.NgForm, selector: "form:not([ngNoForm]):not([formGroup]):not([formArray]),ng-form,[ngForm]", inputs: ["ngFormOptions"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { kind: "directive", type: NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }] });
|
|
1182
|
+
}
|
|
1183
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: LoginComponent, decorators: [{
|
|
1184
|
+
type: Component,
|
|
1185
|
+
args: [{ selector: 'coolms-admin-login', standalone: true, imports: [FormsModule, NgIf], template: "<div class=\"d-flex align-items-center justify-content-center min-vh-100 bg-light\">\n <div class=\"card shadow-sm\" style=\"width: 360px\">\n <div class=\"card-body p-4\">\n <h1 class=\"h5 mb-1\">CoolMS Admin</h1>\n <p class=\"text-muted small mb-4\">Sign in to continue</p>\n\n <div *ngIf=\"error\" class=\"alert alert-danger py-2 small\">{{ error }}</div>\n\n <form (ngSubmit)=\"submit()\" #loginForm=\"ngForm\">\n <div class=\"mb-3\">\n <label class=\"form-label\">Email or username</label>\n <input\n type=\"text\"\n class=\"form-control\"\n [(ngModel)]=\"identifier\"\n name=\"identifier\"\n required\n autocomplete=\"username\"\n />\n </div>\n <div class=\"mb-3\">\n <label class=\"form-label\">Password</label>\n <input\n type=\"password\"\n class=\"form-control\"\n [(ngModel)]=\"password\"\n name=\"password\"\n required\n autocomplete=\"current-password\"\n />\n </div>\n <button\n type=\"submit\"\n class=\"cms-btn cms-btn-primary w-100 justify-content-center\"\n [disabled]=\"loading || loginForm.invalid\"\n >\n {{ loading ? 'Signing in\u2026' : 'Sign in' }}\n </button>\n </form>\n </div>\n </div>\n</div>\n" }]
|
|
1186
|
+
}] });
|
|
1187
|
+
|
|
1188
|
+
/**
|
|
1189
|
+
* Fetches config YAMLs (served as JSON) from GET /api/v1/config/{type}/{id}.
|
|
1190
|
+
*
|
|
1191
|
+
* Responses are cached for the lifetime of the service (Map + shareReplay(1))
|
|
1192
|
+
* so repeated calls never re-fetch the same resource.
|
|
1193
|
+
*
|
|
1194
|
+
* configBase is read from the API manifest (manifest.configBase) and falls
|
|
1195
|
+
* back to '/api/v1/config' when the manifest is not yet loaded.
|
|
1196
|
+
*/
|
|
1197
|
+
class ConfigService {
|
|
1198
|
+
http = inject(HttpClient);
|
|
1199
|
+
store = inject(Store);
|
|
1200
|
+
cache = new Map();
|
|
1201
|
+
layout(id) { return this.fetch('layout', id); }
|
|
1202
|
+
dialog(id) { return this.fetch('dialog', id); }
|
|
1203
|
+
navigraph(slug) { return this.fetch('navigraph', slug); }
|
|
1204
|
+
form(id) { return this.fetch('form', id); }
|
|
1205
|
+
datagrid(id) { return this.fetch('datagrid', id); }
|
|
1206
|
+
fetch(type, id) {
|
|
1207
|
+
const key = `${type}/${id}`;
|
|
1208
|
+
if (!this.cache.has(key)) {
|
|
1209
|
+
const base = this.store.selectSnapshot(AppConfigState.manifest)?.configBase
|
|
1210
|
+
?? '/api/v1/config';
|
|
1211
|
+
// The config endpoint wraps the YAML payload in a `data` field:
|
|
1212
|
+
// { type, id, data: { ...yaml content... } }
|
|
1213
|
+
// Unwrap so callers always receive the config payload directly.
|
|
1214
|
+
const obs = this.http.get(`${base}/${type}/${id}`).pipe(map(r => (r.data ?? r)), shareReplay(1));
|
|
1215
|
+
this.cache.set(key, obs);
|
|
1216
|
+
}
|
|
1217
|
+
return this.cache.get(key);
|
|
1218
|
+
}
|
|
1219
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: ConfigService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
1220
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: ConfigService, providedIn: 'root' });
|
|
1221
|
+
}
|
|
1222
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: ConfigService, decorators: [{
|
|
1223
|
+
type: Injectable,
|
|
1224
|
+
args: [{ providedIn: 'root' }]
|
|
1225
|
+
}] });
|
|
1226
|
+
|
|
1227
|
+
/**
|
|
1228
|
+
* Converts any caught error into a human-readable message.
|
|
1229
|
+
*
|
|
1230
|
+
* Priority order for backend errors:
|
|
1231
|
+
* 1. error.detail (RFC 7807 problem detail)
|
|
1232
|
+
* 2. error['hydra:description'] (Hydra validation errors)
|
|
1233
|
+
* 3. error.message (generic)
|
|
1234
|
+
* 4. error.violations[] (constraint violations)
|
|
1235
|
+
* 5. Status-based fallback
|
|
1236
|
+
*/
|
|
1237
|
+
class ErrorHandlerService {
|
|
1238
|
+
humanize(err) {
|
|
1239
|
+
if (!(err instanceof HttpErrorResponse)) {
|
|
1240
|
+
return err instanceof Error ? err.message : 'An unexpected error occurred.';
|
|
1241
|
+
}
|
|
1242
|
+
const body = err.error;
|
|
1243
|
+
if (body && typeof body === 'object') {
|
|
1244
|
+
const detail = body['detail'] ?? body['hydra:description'] ?? body['message'];
|
|
1245
|
+
if (typeof detail === 'string' && detail.trim()) {
|
|
1246
|
+
return detail.trim();
|
|
1247
|
+
}
|
|
1248
|
+
if (Array.isArray(body['violations'])) {
|
|
1249
|
+
const msgs = body['violations']
|
|
1250
|
+
.map(v => v.message)
|
|
1251
|
+
.filter(Boolean);
|
|
1252
|
+
if (msgs.length)
|
|
1253
|
+
return msgs.join(' ');
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
return this.statusMessage(err.status);
|
|
1257
|
+
}
|
|
1258
|
+
statusMessage(status) {
|
|
1259
|
+
switch (status) {
|
|
1260
|
+
case 0: return 'Network error. Check your connection.';
|
|
1261
|
+
case 400: return 'Invalid request.';
|
|
1262
|
+
case 401: return 'Session expired. Please sign in again.';
|
|
1263
|
+
case 403: return 'Access denied.';
|
|
1264
|
+
case 404: return 'Resource not found.';
|
|
1265
|
+
case 409: return 'Conflict — resource already exists.';
|
|
1266
|
+
case 422: return 'Validation failed.';
|
|
1267
|
+
case 429: return 'Too many requests. Please wait a moment.';
|
|
1268
|
+
case 500: return 'Server error. Please try again later.';
|
|
1269
|
+
case 503: return 'Service unavailable. Please try again later.';
|
|
1270
|
+
default: return `Unexpected error (${status}).`;
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: ErrorHandlerService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
1274
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: ErrorHandlerService, providedIn: 'root' });
|
|
1275
|
+
}
|
|
1276
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: ErrorHandlerService, decorators: [{
|
|
1277
|
+
type: Injectable,
|
|
1278
|
+
args: [{ providedIn: 'root' }]
|
|
1279
|
+
}] });
|
|
1280
|
+
|
|
1281
|
+
const CHOICES = ['light', 'dark', 'system'];
|
|
1282
|
+
/**
|
|
1283
|
+
* A CACHE, never a source of truth.
|
|
1284
|
+
*
|
|
1285
|
+
* The authoritative value is `preferences.theme` in `/auth/me/settings`, which
|
|
1286
|
+
* the Profile -> Preferences tab already writes. This copy exists only so the
|
|
1287
|
+
* first paint of a reload is the right colour: the settings request is async,
|
|
1288
|
+
* so without it every load would start light and flip. It is deliberately NOT
|
|
1289
|
+
* stored via UserPreferencesService, which syncs its own bag to the server —
|
|
1290
|
+
* that would give one setting two server-side homes.
|
|
1291
|
+
*/
|
|
1292
|
+
const CACHE_KEY = 'coolms_theme';
|
|
1293
|
+
const ACCENT_CACHE_KEY = 'coolms_accent';
|
|
1294
|
+
/**
|
|
1295
|
+
* Six-digit hex only, checked again HERE even though the server already vets it
|
|
1296
|
+
* on write. This value is substituted into a `--cms-*` custom property,
|
|
1297
|
+
* and a stored setting is data from the network like any other — the write-side
|
|
1298
|
+
* guard protects what the admin stores, this one protects what it renders.
|
|
1299
|
+
*/
|
|
1300
|
+
const HEX = /^#[0-9a-fA-F]{6}$/;
|
|
1301
|
+
function isChoice(v) {
|
|
1302
|
+
return typeof v === 'string' && CHOICES.includes(v);
|
|
1303
|
+
}
|
|
1304
|
+
function isAccent(v) {
|
|
1305
|
+
return typeof v === 'string' && HEX.test(v);
|
|
1306
|
+
}
|
|
1307
|
+
/**
|
|
1308
|
+
* Applies the user's theme by setting `data-theme` on the document element.
|
|
1309
|
+
*
|
|
1310
|
+
* The stylesheet does the rest: `:root[data-theme='dark']` re-points the
|
|
1311
|
+
* `--cms-*` palette and every colour in the admin arrives through those names.
|
|
1312
|
+
* Nothing here knows a single colour, which is the point — a second
|
|
1313
|
+
* theme is a block of tokens, not a code change.
|
|
1314
|
+
*
|
|
1315
|
+
* Follows the shape of UserCalendarPreferencesService and
|
|
1316
|
+
* CallOverlayPreferencesService: lazy one-shot load of `/auth/me/settings`,
|
|
1317
|
+
* cached for the SPA lifetime, with `update()` called by the Profile page after
|
|
1318
|
+
* a save so the change lands without a refetch.
|
|
1319
|
+
*/
|
|
1320
|
+
class ThemeService {
|
|
1321
|
+
api = inject(IdentityApiClient);
|
|
1322
|
+
store = inject(Store);
|
|
1323
|
+
_choice = signal(ThemeService.readCache(), /* @ts-ignore */
|
|
1324
|
+
...(ngDevMode ? [{ debugName: "_choice" }] : /* istanbul ignore next */ []));
|
|
1325
|
+
_systemDark = signal(false, /* @ts-ignore */
|
|
1326
|
+
...(ngDevMode ? [{ debugName: "_systemDark" }] : /* istanbul ignore next */ []));
|
|
1327
|
+
_userAccent = signal(ThemeService.readAccentCache(), /* @ts-ignore */
|
|
1328
|
+
...(ngDevMode ? [{ debugName: "_userAccent" }] : /* istanbul ignore next */ []));
|
|
1329
|
+
_platformAccent = signal(null, /* @ts-ignore */
|
|
1330
|
+
...(ngDevMode ? [{ debugName: "_platformAccent" }] : /* istanbul ignore next */ []));
|
|
1331
|
+
loadOnce$;
|
|
1332
|
+
/** The user's stored choice, including `system`. */
|
|
1333
|
+
choice = this._choice.asReadonly();
|
|
1334
|
+
/** This user's personal override, independent of the deployment's. */
|
|
1335
|
+
userAccent = this._userAccent.asReadonly();
|
|
1336
|
+
/** The deployment's brand accent from the API manifest, if it set one. */
|
|
1337
|
+
platformAccent = this._platformAccent.asReadonly();
|
|
1338
|
+
/**
|
|
1339
|
+
* The colour actually painted: personal override, else the deployment's,
|
|
1340
|
+
* else null — which leaves the stylesheet's own accent in place.
|
|
1341
|
+
*
|
|
1342
|
+
* Three rungs and each is a real state. A user who has chosen nothing is
|
|
1343
|
+
* NOT the same as one who chose the deployment's colour: clear the
|
|
1344
|
+
* deployment's brand and the first user follows it, the second does not.
|
|
1345
|
+
*/
|
|
1346
|
+
accent = computed(() => this._userAccent() ?? this._platformAccent(), /* @ts-ignore */
|
|
1347
|
+
...(ngDevMode ? [{ debugName: "accent" }] : /* istanbul ignore next */ []));
|
|
1348
|
+
/** The choice with `system` resolved against the OS setting. */
|
|
1349
|
+
resolved = computed(() => {
|
|
1350
|
+
const c = this._choice();
|
|
1351
|
+
return c === 'system' ? (this._systemDark() ? 'dark' : 'light') : c;
|
|
1352
|
+
}, /* @ts-ignore */
|
|
1353
|
+
...(ngDevMode ? [{ debugName: "resolved" }] : /* istanbul ignore next */ []));
|
|
1354
|
+
constructor() {
|
|
1355
|
+
// `matchMedia` is guarded because the unit suite and any SSR-ish
|
|
1356
|
+
// rendering path may not provide it; absent it, `system` means light.
|
|
1357
|
+
const mq = typeof window !== 'undefined' && window.matchMedia
|
|
1358
|
+
? window.matchMedia('(prefers-color-scheme: dark)')
|
|
1359
|
+
: null;
|
|
1360
|
+
if (mq) {
|
|
1361
|
+
this._systemDark.set(mq.matches);
|
|
1362
|
+
// The OS can flip while the SPA is open, and `system` must follow it
|
|
1363
|
+
// live rather than only at load.
|
|
1364
|
+
mq.addEventListener('change', e => this._systemDark.set(e.matches));
|
|
1365
|
+
}
|
|
1366
|
+
effect(() => this.applyToDocument(this.resolved()));
|
|
1367
|
+
effect(() => this.applyAccent(this.accent()));
|
|
1368
|
+
}
|
|
1369
|
+
/**
|
|
1370
|
+
* One-shot load of the stored preference. Safe to call more than once and
|
|
1371
|
+
* safe for anonymous users — a failure leaves the cached/system value in
|
|
1372
|
+
* place rather than forcing light, so the login screen still matches the OS.
|
|
1373
|
+
*/
|
|
1374
|
+
ensureLoaded() {
|
|
1375
|
+
if (this.loadOnce$)
|
|
1376
|
+
return this.loadOnce$;
|
|
1377
|
+
// Read the deployment's colour FIRST and synchronously, so it is in
|
|
1378
|
+
// place whether or not the settings request succeeds — an anonymous
|
|
1379
|
+
// visitor on the login screen still sees the deployment's brand.
|
|
1380
|
+
this.readPlatformAccent();
|
|
1381
|
+
this.loadOnce$ = this.api.getSettings().pipe(map$1(all => {
|
|
1382
|
+
const prefs = all['preferences'];
|
|
1383
|
+
// The accent rides along on the same response — it is a field of
|
|
1384
|
+
// the same section, so it costs no extra request.
|
|
1385
|
+
this.setAccent(isAccent(prefs?.['accentColor']) ? prefs['accentColor'] : null);
|
|
1386
|
+
return isChoice(prefs?.['theme']) ? prefs['theme'] : this._choice();
|
|
1387
|
+
}), tap(choice => this.set(choice)), catchError$1(() => of(this._choice())), shareReplay$1({ bufferSize: 1, refCount: false }));
|
|
1388
|
+
return this.loadOnce$;
|
|
1389
|
+
}
|
|
1390
|
+
/**
|
|
1391
|
+
* Called by the Profile page after the Preferences tab saves, so the admin
|
|
1392
|
+
* re-themes on the spot. Ignores anything that is not a known choice —
|
|
1393
|
+
* the section PATCH returns the whole merged bag, not just this field.
|
|
1394
|
+
*/
|
|
1395
|
+
update(value) {
|
|
1396
|
+
if (isChoice(value))
|
|
1397
|
+
this.set(value);
|
|
1398
|
+
}
|
|
1399
|
+
/**
|
|
1400
|
+
* Companion to {@link update} for the accent field of the same save.
|
|
1401
|
+
* An explicit null clears the override; anything malformed is ignored
|
|
1402
|
+
* rather than applied, so a bad value can never blank the admin's accent.
|
|
1403
|
+
*/
|
|
1404
|
+
updateAccent(value) {
|
|
1405
|
+
if (null === value || '' === value)
|
|
1406
|
+
this.setAccent(null);
|
|
1407
|
+
else if (isAccent(value))
|
|
1408
|
+
this.setAccent(value);
|
|
1409
|
+
}
|
|
1410
|
+
set(choice) {
|
|
1411
|
+
this._choice.set(choice);
|
|
1412
|
+
try {
|
|
1413
|
+
localStorage.setItem(CACHE_KEY, choice);
|
|
1414
|
+
}
|
|
1415
|
+
catch {
|
|
1416
|
+
// A blocked or full localStorage costs the pre-paint hint, nothing
|
|
1417
|
+
// more — the server value still arrives and applies.
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
/**
|
|
1421
|
+
* The manifest is loaded at bootstrap, well before the authenticated shell
|
|
1422
|
+
* calls this, so a snapshot read is enough and no subscription is needed.
|
|
1423
|
+
* A malformed value is ignored rather than applied — the container refuses
|
|
1424
|
+
* to build with one, but the manifest crosses the network all the same.
|
|
1425
|
+
*/
|
|
1426
|
+
readPlatformAccent() {
|
|
1427
|
+
const value = this.store.selectSnapshot(AppConfigState.manifest)?.platformDefaults?.accentColor;
|
|
1428
|
+
this._platformAccent.set(isAccent(value) ? value : null);
|
|
1429
|
+
}
|
|
1430
|
+
setAccent(accent) {
|
|
1431
|
+
this._userAccent.set(accent);
|
|
1432
|
+
try {
|
|
1433
|
+
if (accent)
|
|
1434
|
+
localStorage.setItem(ACCENT_CACHE_KEY, accent);
|
|
1435
|
+
else
|
|
1436
|
+
localStorage.removeItem(ACCENT_CACHE_KEY);
|
|
1437
|
+
}
|
|
1438
|
+
catch {
|
|
1439
|
+
// Same as the theme cache: losing it costs the pre-paint hint only.
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
/**
|
|
1443
|
+
* Writes the override onto the document element, where an inline style
|
|
1444
|
+
* outranks every stylesheet rule — including the dark block — so one
|
|
1445
|
+
* declaration re-points the accent in both themes.
|
|
1446
|
+
*
|
|
1447
|
+
* Only --cms-accent is set, not the -hover/-light/-text members of the
|
|
1448
|
+
* family. Deriving those from an arbitrary user colour needs a colour model
|
|
1449
|
+
* the palette does not have yet, and guessing them would produce hover
|
|
1450
|
+
* states that clash with the very colour the user chose. Until then the
|
|
1451
|
+
* override moves the brand fill and leaves its supporting tones alone.
|
|
1452
|
+
*/
|
|
1453
|
+
applyAccent(accent) {
|
|
1454
|
+
const root = document.documentElement;
|
|
1455
|
+
if (accent && HEX.test(accent))
|
|
1456
|
+
root.style.setProperty('--cms-accent', accent);
|
|
1457
|
+
else
|
|
1458
|
+
root.style.removeProperty('--cms-accent');
|
|
1459
|
+
}
|
|
1460
|
+
applyToDocument(theme) {
|
|
1461
|
+
// Written for BOTH values rather than only removing the attribute for
|
|
1462
|
+
// light, so the attribute is a reliable signal for anything that wants
|
|
1463
|
+
// to read the active theme, and so a future `[data-theme='light']`
|
|
1464
|
+
// block has something to hang on.
|
|
1465
|
+
document.documentElement.setAttribute('data-theme', theme);
|
|
1466
|
+
}
|
|
1467
|
+
static readCache() {
|
|
1468
|
+
try {
|
|
1469
|
+
const raw = localStorage.getItem(CACHE_KEY);
|
|
1470
|
+
return isChoice(raw) ? raw : 'system';
|
|
1471
|
+
}
|
|
1472
|
+
catch {
|
|
1473
|
+
return 'system';
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
static readAccentCache() {
|
|
1477
|
+
try {
|
|
1478
|
+
const raw = localStorage.getItem(ACCENT_CACHE_KEY);
|
|
1479
|
+
return isAccent(raw) ? raw : null;
|
|
1480
|
+
}
|
|
1481
|
+
catch {
|
|
1482
|
+
return null;
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: ThemeService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
1486
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: ThemeService, providedIn: 'root' });
|
|
1487
|
+
}
|
|
1488
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: ThemeService, decorators: [{
|
|
1489
|
+
type: Injectable,
|
|
1490
|
+
args: [{ providedIn: 'root' }]
|
|
1491
|
+
}], ctorParameters: () => [] });
|
|
1492
|
+
|
|
1493
|
+
/**
|
|
1494
|
+
* The platform's loading indicator: the exclamation mark from Cool!MS,
|
|
1495
|
+
* drawing itself.
|
|
1496
|
+
*
|
|
1497
|
+
* ## Why a mark and not a spinner
|
|
1498
|
+
*
|
|
1499
|
+
* A spinner says "something is happening" and nothing else; every product has
|
|
1500
|
+
* one and none of them are yours. The bang is already the one glyph in the
|
|
1501
|
+
* wordmark that carries the brand, so a loader built from it says whose
|
|
1502
|
+
* software is thinking — for free, in the place a user is already looking.
|
|
1503
|
+
*
|
|
1504
|
+
* ## Why one component rather than a snippet per surface
|
|
1505
|
+
*
|
|
1506
|
+
* It is meant for every wait long enough to notice: a dashboard assembling its
|
|
1507
|
+
* cards, an editor paginating a document, an explorer listing a folder. Those
|
|
1508
|
+
* are different teams' files, and a copied SVG in each is how three loaders
|
|
1509
|
+
* that no longer match each other happen.
|
|
1510
|
+
*
|
|
1511
|
+
* ## The animation
|
|
1512
|
+
*
|
|
1513
|
+
* The stem wipes upward and the dot lands after it, on a loop — the shape being
|
|
1514
|
+
* WRITTEN rather than spun. It is deliberately calm: a loader is background
|
|
1515
|
+
* furniture, and anything with a hard beat gets irritating on the third viewing.
|
|
1516
|
+
* Under `prefers-reduced-motion` it holds still and only breathes, because
|
|
1517
|
+
* motion sickness is not a stylistic preference.
|
|
1518
|
+
*/
|
|
1519
|
+
class CmsLoaderComponent {
|
|
1520
|
+
/** Optional caption. Absent renders the mark alone, which suits a small inline wait. */
|
|
1521
|
+
label = input('', /* @ts-ignore */
|
|
1522
|
+
...(ngDevMode ? [{ debugName: "label" }] : /* istanbul ignore next */ []));
|
|
1523
|
+
/** Cover the positioned ancestor rather than sitting in the flow. */
|
|
1524
|
+
overlay = input(false, /* @ts-ignore */
|
|
1525
|
+
...(ngDevMode ? [{ debugName: "overlay" }] : /* istanbul ignore next */ []));
|
|
1526
|
+
/**
|
|
1527
|
+
* Row layout at text scale, for a wait inside a row, a status bar or a
|
|
1528
|
+
* button. Override `--cms-loader-size` to tune the mark.
|
|
1529
|
+
*/
|
|
1530
|
+
inline = input(false, /* @ts-ignore */
|
|
1531
|
+
...(ngDevMode ? [{ debugName: "inline" }] : /* istanbul ignore next */ []));
|
|
1532
|
+
/**
|
|
1533
|
+
* A clip-path needs a document-unique id, and this component is used more
|
|
1534
|
+
* than once per page — two loaders sharing an id makes the second one clip
|
|
1535
|
+
* against the first one's rectangle and stop animating.
|
|
1536
|
+
*/
|
|
1537
|
+
clipId = 'cms-loader-' + Math.random().toString(36).slice(2, 9);
|
|
1538
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: CmsLoaderComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
|
|
1539
|
+
static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "22.1.3", type: CmsLoaderComponent, isStandalone: true, selector: "cms-loader", inputs: { label: { classPropertyName: "label", publicName: "label", isSignal: true, isRequired: false, transformFunction: null }, overlay: { classPropertyName: "overlay", publicName: "overlay", isSignal: true, isRequired: false, transformFunction: null }, inline: { classPropertyName: "inline", publicName: "inline", isSignal: true, isRequired: false, transformFunction: null } }, ngImport: i0, template: `
|
|
1540
|
+
<div class="cms-loader"
|
|
1541
|
+
[class.cms-loader--overlay]="overlay()"
|
|
1542
|
+
[class.cms-loader--inline]="inline()"
|
|
1543
|
+
role="status"
|
|
1544
|
+
[attr.aria-label]="label() || 'Loading'">
|
|
1545
|
+
<svg class="cms-loader__mark" viewBox="0 0 24 48" aria-hidden="true">
|
|
1546
|
+
<defs>
|
|
1547
|
+
<clipPath [attr.id]="clipId">
|
|
1548
|
+
<rect class="cms-loader__wipe" x="0" y="0" width="24" height="34" />
|
|
1549
|
+
</clipPath>
|
|
1550
|
+
</defs>
|
|
1551
|
+
<!-- Ghost beneath: the mark stays legible as a SHAPE while the
|
|
1552
|
+
wipe crosses it, so the loader never looks broken mid-cycle. -->
|
|
1553
|
+
<rect class="cms-loader__ghost" x="8" y="2" width="8" height="30" rx="4" />
|
|
1554
|
+
<circle class="cms-loader__ghost" cx="12" cy="42" r="4" />
|
|
1555
|
+
|
|
1556
|
+
<rect class="cms-loader__stem" x="8" y="2" width="8" height="30" rx="4"
|
|
1557
|
+
[attr.clip-path]="'url(#' + clipId + ')'" />
|
|
1558
|
+
<circle class="cms-loader__dot" cx="12" cy="42" r="4" />
|
|
1559
|
+
</svg>
|
|
1560
|
+
@if (label()) {
|
|
1561
|
+
<span class="cms-loader__label">{{ label() }}</span>
|
|
1562
|
+
}
|
|
1563
|
+
</div>
|
|
1564
|
+
`, isInline: true, styles: [".cms-loader{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;padding:24px;color:var(--cms-text-muted)}.cms-loader--overlay{position:absolute;inset:0;z-index:5;background:var(--cms-surface)}.cms-loader--inline{flex-direction:row;gap:8px;padding:0}.cms-loader--inline .cms-loader__mark{width:var(--cms-loader-size, 14px)}.cms-loader__mark{width:var(--cms-loader-size, 40px);height:auto;overflow:visible}.cms-loader__ghost{fill:var(--cms-border)}.cms-loader__stem,.cms-loader__dot{fill:var(--cms-accent)}.cms-loader__wipe{animation:cms-loader-wipe 1.6s cubic-bezier(.65,0,.35,1) infinite;transform-origin:12px 32px}.cms-loader__dot{animation:cms-loader-dot 1.6s cubic-bezier(.65,0,.35,1) infinite;transform-origin:12px 42px}@keyframes cms-loader-wipe{0%{transform:scaleY(0)}45%,70%{transform:scaleY(1)}to{transform:scaleY(0)}}@keyframes cms-loader-dot{0%,40%{opacity:0;transform:scale(.4)}55%,70%{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(.4)}}.cms-loader__label{font-size:.8125rem}@media(prefers-reduced-motion:reduce){.cms-loader__wipe{animation:none;transform:scaleY(1)}.cms-loader__dot{animation:cms-loader-breathe 2s ease-in-out infinite;opacity:1}}@keyframes cms-loader-breathe{0%,to{opacity:.35}50%{opacity:1}}\n"], changeDetection: i0.ChangeDetectionStrategy.OnPush });
|
|
1565
|
+
}
|
|
1566
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: CmsLoaderComponent, decorators: [{
|
|
1567
|
+
type: Component,
|
|
1568
|
+
args: [{ selector: 'cms-loader', standalone: true, changeDetection: ChangeDetectionStrategy.OnPush, template: `
|
|
1569
|
+
<div class="cms-loader"
|
|
1570
|
+
[class.cms-loader--overlay]="overlay()"
|
|
1571
|
+
[class.cms-loader--inline]="inline()"
|
|
1572
|
+
role="status"
|
|
1573
|
+
[attr.aria-label]="label() || 'Loading'">
|
|
1574
|
+
<svg class="cms-loader__mark" viewBox="0 0 24 48" aria-hidden="true">
|
|
1575
|
+
<defs>
|
|
1576
|
+
<clipPath [attr.id]="clipId">
|
|
1577
|
+
<rect class="cms-loader__wipe" x="0" y="0" width="24" height="34" />
|
|
1578
|
+
</clipPath>
|
|
1579
|
+
</defs>
|
|
1580
|
+
<!-- Ghost beneath: the mark stays legible as a SHAPE while the
|
|
1581
|
+
wipe crosses it, so the loader never looks broken mid-cycle. -->
|
|
1582
|
+
<rect class="cms-loader__ghost" x="8" y="2" width="8" height="30" rx="4" />
|
|
1583
|
+
<circle class="cms-loader__ghost" cx="12" cy="42" r="4" />
|
|
1584
|
+
|
|
1585
|
+
<rect class="cms-loader__stem" x="8" y="2" width="8" height="30" rx="4"
|
|
1586
|
+
[attr.clip-path]="'url(#' + clipId + ')'" />
|
|
1587
|
+
<circle class="cms-loader__dot" cx="12" cy="42" r="4" />
|
|
1588
|
+
</svg>
|
|
1589
|
+
@if (label()) {
|
|
1590
|
+
<span class="cms-loader__label">{{ label() }}</span>
|
|
1591
|
+
}
|
|
1592
|
+
</div>
|
|
1593
|
+
`, styles: [".cms-loader{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;padding:24px;color:var(--cms-text-muted)}.cms-loader--overlay{position:absolute;inset:0;z-index:5;background:var(--cms-surface)}.cms-loader--inline{flex-direction:row;gap:8px;padding:0}.cms-loader--inline .cms-loader__mark{width:var(--cms-loader-size, 14px)}.cms-loader__mark{width:var(--cms-loader-size, 40px);height:auto;overflow:visible}.cms-loader__ghost{fill:var(--cms-border)}.cms-loader__stem,.cms-loader__dot{fill:var(--cms-accent)}.cms-loader__wipe{animation:cms-loader-wipe 1.6s cubic-bezier(.65,0,.35,1) infinite;transform-origin:12px 32px}.cms-loader__dot{animation:cms-loader-dot 1.6s cubic-bezier(.65,0,.35,1) infinite;transform-origin:12px 42px}@keyframes cms-loader-wipe{0%{transform:scaleY(0)}45%,70%{transform:scaleY(1)}to{transform:scaleY(0)}}@keyframes cms-loader-dot{0%,40%{opacity:0;transform:scale(.4)}55%,70%{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(.4)}}.cms-loader__label{font-size:.8125rem}@media(prefers-reduced-motion:reduce){.cms-loader__wipe{animation:none;transform:scaleY(1)}.cms-loader__dot{animation:cms-loader-breathe 2s ease-in-out infinite;opacity:1}}@keyframes cms-loader-breathe{0%,to{opacity:.35}50%{opacity:1}}\n"] }]
|
|
1594
|
+
}], propDecorators: { label: [{ type: i0.Input, args: [{ isSignal: true, alias: "label", required: false }] }], overlay: [{ type: i0.Input, args: [{ isSignal: true, alias: "overlay", required: false }] }], inline: [{ type: i0.Input, args: [{ isSignal: true, alias: "inline", required: false }] }] } });
|
|
1595
|
+
|
|
1596
|
+
/**
|
|
1597
|
+
* Sidebar collapse state -- two independent dimensions:
|
|
1598
|
+
*
|
|
1599
|
+
* - `collapsed`: whole-sidebar icon-only rail toggle (the chevron at
|
|
1600
|
+
* the bottom of the sidebar). Per-device localStorage.
|
|
1601
|
+
* - `collapsedSections`: per-section collapse, keyed by the section
|
|
1602
|
+
* separator's node id. Used to fold a section's items under their
|
|
1603
|
+
* header so the nav doesn't endless-scroll once a tenant has lots
|
|
1604
|
+
* of modules. Per-device localStorage.
|
|
1605
|
+
* - `collapsedItems`: per-item inline-expand collapse, keyed by the
|
|
1606
|
+
* nav node's id. Mirrors `collapsedSections` but for sub-tree items
|
|
1607
|
+
* (a top-level item with children, e.g. Reports -> Process Report).
|
|
1608
|
+
* Absent id = expanded (children visible); present = collapsed.
|
|
1609
|
+
* Per-device localStorage.
|
|
1610
|
+
*
|
|
1611
|
+
* Storage failures (private mode, quota, disabled cookies) fall back
|
|
1612
|
+
* to defaulting un-collapsed -- the toggles still work for the session,
|
|
1613
|
+
* just don't persist.
|
|
1614
|
+
*/
|
|
1615
|
+
class SidebarStateService {
|
|
1616
|
+
static STORAGE_KEY = 'coolms.admin.sidebar.collapsed';
|
|
1617
|
+
static STORAGE_KEY_SECTIONS = 'coolms.admin.sidebar.collapsedSections';
|
|
1618
|
+
static STORAGE_KEY_ITEMS = 'coolms.admin.sidebar.collapsedItems';
|
|
1619
|
+
collapsed = signal(this.readPersisted(), /* @ts-ignore */
|
|
1620
|
+
...(ngDevMode ? [{ debugName: "collapsed" }] : /* istanbul ignore next */ []));
|
|
1621
|
+
collapsedSections = signal(this.readSectionsPersisted(), /* @ts-ignore */
|
|
1622
|
+
...(ngDevMode ? [{ debugName: "collapsedSections" }] : /* istanbul ignore next */ []));
|
|
1623
|
+
collapsedItems = signal(this.readItemsPersisted(), /* @ts-ignore */
|
|
1624
|
+
...(ngDevMode ? [{ debugName: "collapsedItems" }] : /* istanbul ignore next */ []));
|
|
1625
|
+
toggle() {
|
|
1626
|
+
const next = !this.collapsed();
|
|
1627
|
+
this.collapsed.set(next);
|
|
1628
|
+
this.persist(next);
|
|
1629
|
+
}
|
|
1630
|
+
isSectionCollapsed(id) {
|
|
1631
|
+
return this.collapsedSections().has(id);
|
|
1632
|
+
}
|
|
1633
|
+
toggleSection(id) {
|
|
1634
|
+
const next = new Set(this.collapsedSections());
|
|
1635
|
+
if (next.has(id)) {
|
|
1636
|
+
next.delete(id);
|
|
1637
|
+
}
|
|
1638
|
+
else {
|
|
1639
|
+
next.add(id);
|
|
1640
|
+
}
|
|
1641
|
+
this.collapsedSections.set(next);
|
|
1642
|
+
this.persistSections(next);
|
|
1643
|
+
}
|
|
1644
|
+
/**
|
|
1645
|
+
* Force a section to be expanded. Used when navigation lands on
|
|
1646
|
+
* a route inside a manually-collapsed section -- it would be
|
|
1647
|
+
* confusing to leave the active item hidden. The user can
|
|
1648
|
+
* collapse the section again afterwards.
|
|
1649
|
+
*/
|
|
1650
|
+
ensureExpanded(id) {
|
|
1651
|
+
if (!this.collapsedSections().has(id))
|
|
1652
|
+
return;
|
|
1653
|
+
const next = new Set(this.collapsedSections());
|
|
1654
|
+
next.delete(id);
|
|
1655
|
+
this.collapsedSections.set(next);
|
|
1656
|
+
this.persistSections(next);
|
|
1657
|
+
}
|
|
1658
|
+
// --- Per-item inline-expand (sub-tree items, e.g. a section's children) --
|
|
1659
|
+
isItemCollapsed(id) {
|
|
1660
|
+
return this.collapsedItems().has(id);
|
|
1661
|
+
}
|
|
1662
|
+
toggleItem(id) {
|
|
1663
|
+
const next = new Set(this.collapsedItems());
|
|
1664
|
+
if (next.has(id)) {
|
|
1665
|
+
next.delete(id);
|
|
1666
|
+
}
|
|
1667
|
+
else {
|
|
1668
|
+
next.add(id);
|
|
1669
|
+
}
|
|
1670
|
+
this.collapsedItems.set(next);
|
|
1671
|
+
this.persistItems(next);
|
|
1672
|
+
}
|
|
1673
|
+
readPersisted() {
|
|
1674
|
+
try {
|
|
1675
|
+
return localStorage.getItem(SidebarStateService.STORAGE_KEY) === 'true';
|
|
1676
|
+
}
|
|
1677
|
+
catch {
|
|
1678
|
+
return false;
|
|
1679
|
+
}
|
|
1680
|
+
}
|
|
1681
|
+
persist(value) {
|
|
1682
|
+
try {
|
|
1683
|
+
localStorage.setItem(SidebarStateService.STORAGE_KEY, String(value));
|
|
1684
|
+
}
|
|
1685
|
+
catch {
|
|
1686
|
+
// Non-persistence acceptable; toggle still works in-session.
|
|
1687
|
+
}
|
|
1688
|
+
}
|
|
1689
|
+
readSectionsPersisted() {
|
|
1690
|
+
try {
|
|
1691
|
+
const raw = localStorage.getItem(SidebarStateService.STORAGE_KEY_SECTIONS);
|
|
1692
|
+
if (raw === null)
|
|
1693
|
+
return new Set();
|
|
1694
|
+
const parsed = JSON.parse(raw);
|
|
1695
|
+
if (!Array.isArray(parsed))
|
|
1696
|
+
return new Set();
|
|
1697
|
+
return new Set(parsed.filter((v) => typeof v === 'string'));
|
|
1698
|
+
}
|
|
1699
|
+
catch {
|
|
1700
|
+
return new Set();
|
|
1701
|
+
}
|
|
1702
|
+
}
|
|
1703
|
+
persistSections(value) {
|
|
1704
|
+
try {
|
|
1705
|
+
localStorage.setItem(SidebarStateService.STORAGE_KEY_SECTIONS, JSON.stringify(Array.from(value)));
|
|
1706
|
+
}
|
|
1707
|
+
catch {
|
|
1708
|
+
// Non-persistence acceptable; toggle still works in-session.
|
|
1709
|
+
}
|
|
1710
|
+
}
|
|
1711
|
+
readItemsPersisted() {
|
|
1712
|
+
try {
|
|
1713
|
+
const raw = localStorage.getItem(SidebarStateService.STORAGE_KEY_ITEMS);
|
|
1714
|
+
if (raw === null)
|
|
1715
|
+
return new Set();
|
|
1716
|
+
const parsed = JSON.parse(raw);
|
|
1717
|
+
if (!Array.isArray(parsed))
|
|
1718
|
+
return new Set();
|
|
1719
|
+
return new Set(parsed.filter((v) => typeof v === 'string'));
|
|
1720
|
+
}
|
|
1721
|
+
catch {
|
|
1722
|
+
return new Set();
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
persistItems(value) {
|
|
1726
|
+
try {
|
|
1727
|
+
localStorage.setItem(SidebarStateService.STORAGE_KEY_ITEMS, JSON.stringify(Array.from(value)));
|
|
1728
|
+
}
|
|
1729
|
+
catch {
|
|
1730
|
+
// Non-persistence acceptable; toggle still works in-session.
|
|
1731
|
+
}
|
|
1732
|
+
}
|
|
1733
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: SidebarStateService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
1734
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: SidebarStateService, providedIn: 'root' });
|
|
1735
|
+
}
|
|
1736
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: SidebarStateService, decorators: [{
|
|
1737
|
+
type: Injectable,
|
|
1738
|
+
args: [{ providedIn: 'root' }]
|
|
1739
|
+
}] });
|
|
1740
|
+
|
|
1741
|
+
/**
|
|
1742
|
+
* HTTP client for the Phase 2a `/api/entity-search` endpoint.
|
|
1743
|
+
* Returns a stream of search results for the given entity FQCN.
|
|
1744
|
+
* Permission filtering happens at the backend resolver layer —
|
|
1745
|
+
* this service is a thin RPC.
|
|
1746
|
+
*/
|
|
1747
|
+
class EntitySearchService {
|
|
1748
|
+
http = inject(HttpClient);
|
|
1749
|
+
/**
|
|
1750
|
+
* @param entityType Fully-qualified PHP class name of the entity
|
|
1751
|
+
* being searched (e.g. the backend's User entity).
|
|
1752
|
+
* @param query Free-text search input. Empty string is
|
|
1753
|
+
* valid — the backend returns the default
|
|
1754
|
+
* listing for that entity type.
|
|
1755
|
+
* @param limit Max rows to return; clamped server-side to
|
|
1756
|
+
* [1, 100].
|
|
1757
|
+
*/
|
|
1758
|
+
search(entityType, query, limit = 20) {
|
|
1759
|
+
const params = new HttpParams()
|
|
1760
|
+
.set('type', entityType)
|
|
1761
|
+
.set('q', query)
|
|
1762
|
+
.set('limit', String(limit));
|
|
1763
|
+
return this.http.get('/api/entity-search', { params });
|
|
1764
|
+
}
|
|
1765
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: EntitySearchService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
1766
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: EntitySearchService, providedIn: 'root' });
|
|
1767
|
+
}
|
|
1768
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: EntitySearchService, decorators: [{
|
|
1769
|
+
type: Injectable,
|
|
1770
|
+
args: [{ providedIn: 'root' }]
|
|
1771
|
+
}] });
|
|
1772
|
+
|
|
1773
|
+
/**
|
|
1774
|
+
* Loads, caches, and drives admin NaviGraph trees.
|
|
1775
|
+
*
|
|
1776
|
+
* Usage:
|
|
1777
|
+
* naviGraphService.loadAdminNav(url).subscribe();
|
|
1778
|
+
* const items = naviGraphService.adminNav(); // signal<NaviGraphNode[]>
|
|
1779
|
+
* naviGraphService.handleClick(node);
|
|
1780
|
+
*/
|
|
1781
|
+
class NaviGraphService {
|
|
1782
|
+
http = inject(HttpClient);
|
|
1783
|
+
router = inject(Router);
|
|
1784
|
+
store = inject(Store);
|
|
1785
|
+
errors = inject(ErrorHandlerService);
|
|
1786
|
+
/** Resolved root nodes for navi.admin (sidebar). */
|
|
1787
|
+
adminNav = signal([], /* @ts-ignore */
|
|
1788
|
+
...(ngDevMode ? [{ debugName: "adminNav" }] : /* istanbul ignore next */ []));
|
|
1789
|
+
/** Resolved root nodes for navi.admin.topbar. */
|
|
1790
|
+
topbarNav = signal([], /* @ts-ignore */
|
|
1791
|
+
...(ngDevMode ? [{ debugName: "topbarNav" }] : /* istanbul ignore next */ []));
|
|
1792
|
+
cache = new Map();
|
|
1793
|
+
// -------------------------------------------------------------------------
|
|
1794
|
+
loadAdminNav(url) {
|
|
1795
|
+
return this.loadTree(url).pipe(map(tree => { this.adminNav.set(tree); return tree; }));
|
|
1796
|
+
}
|
|
1797
|
+
loadTopbarNav(url) {
|
|
1798
|
+
return this.loadTree(url).pipe(map(tree => { this.topbarNav.set(tree); return tree; }));
|
|
1799
|
+
}
|
|
1800
|
+
// -------------------------------------------------------------------------
|
|
1801
|
+
/**
|
|
1802
|
+
* Handle a nav-node click.
|
|
1803
|
+
*
|
|
1804
|
+
* Routing logic based on meta.target:
|
|
1805
|
+
* 'action.logout' — dispatch Logout
|
|
1806
|
+
* '_blank' — window.open (uses node.path as href)
|
|
1807
|
+
* default — router.navigate with meta.routerLink or node.path
|
|
1808
|
+
*/
|
|
1809
|
+
handleClick(node) {
|
|
1810
|
+
const target = node.meta.target;
|
|
1811
|
+
if (target === 'action.logout') {
|
|
1812
|
+
this.store.dispatch(new Logout()).subscribe(() => {
|
|
1813
|
+
void this.router.navigate(['/login']);
|
|
1814
|
+
});
|
|
1815
|
+
return;
|
|
1816
|
+
}
|
|
1817
|
+
if (target === '_blank') {
|
|
1818
|
+
window.open(node.meta.routerLink ?? node.path, '_blank', 'noopener');
|
|
1819
|
+
return;
|
|
1820
|
+
}
|
|
1821
|
+
const link = node.meta.routerLink ?? node.path;
|
|
1822
|
+
void this.router.navigate([link]);
|
|
1823
|
+
}
|
|
1824
|
+
// -------------------------------------------------------------------------
|
|
1825
|
+
/**
|
|
1826
|
+
* Evaluate `showWhen` meta condition against a record.
|
|
1827
|
+
* Nodes with no `showWhen` are always visible.
|
|
1828
|
+
* Supports nested AND/OR logic: { and: [...] } / { or: [...] }
|
|
1829
|
+
*/
|
|
1830
|
+
isVisible(node, record) {
|
|
1831
|
+
const showWhen = node.meta['showWhen'];
|
|
1832
|
+
if (!showWhen)
|
|
1833
|
+
return true;
|
|
1834
|
+
return this.evalCondition(showWhen, record);
|
|
1835
|
+
}
|
|
1836
|
+
/**
|
|
1837
|
+
* Standalone `showWhen` evaluator for callers that don't have a
|
|
1838
|
+
* full `NaviGraphNode` (e.g. a grid's row context menu — a
|
|
1839
|
+
* `rowAction.showWhen` predicate is evaluated against the row's
|
|
1840
|
+
* own projection). `null`/`undefined` predicates default to
|
|
1841
|
+
* visible, mirroring `isVisible`'s "no rule = always shown"
|
|
1842
|
+
* semantics.
|
|
1843
|
+
*/
|
|
1844
|
+
matchesShowWhen(showWhen, record) {
|
|
1845
|
+
if (!showWhen)
|
|
1846
|
+
return true;
|
|
1847
|
+
return this.evalCondition(showWhen, record);
|
|
1848
|
+
}
|
|
1849
|
+
evalCondition(cond, record) {
|
|
1850
|
+
if ('and' in cond) {
|
|
1851
|
+
return cond['and']
|
|
1852
|
+
.every(c => this.evalCondition(c, record));
|
|
1853
|
+
}
|
|
1854
|
+
if ('or' in cond) {
|
|
1855
|
+
return cond['or']
|
|
1856
|
+
.some(c => this.evalCondition(c, record));
|
|
1857
|
+
}
|
|
1858
|
+
// Strict missing-field semantics. A leaf predicate
|
|
1859
|
+
// referencing a field absent from the record evaluates to
|
|
1860
|
+
// false (fail-loud) instead of the prior op-dependent lax
|
|
1861
|
+
// behavior that returned true for ne/nin/unknown ops. Aligns
|
|
1862
|
+
// with CSS attribute selectors / JSONPath / React conditional
|
|
1863
|
+
// rendering conventions.
|
|
1864
|
+
const field = cond['field'];
|
|
1865
|
+
if (!(field in record))
|
|
1866
|
+
return false;
|
|
1867
|
+
const val = record[field];
|
|
1868
|
+
switch (cond['op']) {
|
|
1869
|
+
case 'eq': return val === cond['value'];
|
|
1870
|
+
case 'ne': return val !== cond['value'];
|
|
1871
|
+
case 'in': return Array.isArray(cond['value']) && cond['value'].includes(val);
|
|
1872
|
+
case 'nin': return Array.isArray(cond['value']) && !cond['value'].includes(val);
|
|
1873
|
+
// Prefix match for strings — primary use case is filtering
|
|
1874
|
+
// actions by MIME-type major (e.g., "image/" matches all
|
|
1875
|
+
// image MIMEs without enumerating each subtype).
|
|
1876
|
+
case 'startsWith':
|
|
1877
|
+
return typeof val === 'string'
|
|
1878
|
+
&& typeof cond['value'] === 'string'
|
|
1879
|
+
&& val.startsWith(cond['value']);
|
|
1880
|
+
// Strict: unknown / typo op (e.g. 'equals' instead of 'eq')
|
|
1881
|
+
// never matches.
|
|
1882
|
+
default: return false;
|
|
1883
|
+
}
|
|
1884
|
+
}
|
|
1885
|
+
/**
|
|
1886
|
+
* Fetch a graph endpoint and return a nested tree.
|
|
1887
|
+
* Handles both compact JSON-LD IRIs (`member`) and
|
|
1888
|
+
* the legacy Hydra key (`hydra:member`).
|
|
1889
|
+
* Results are cached by URL for the lifetime of the service instance.
|
|
1890
|
+
*/
|
|
1891
|
+
loadTree(url) {
|
|
1892
|
+
if (this.cache.has(url)) {
|
|
1893
|
+
return of(this.cache.get(url));
|
|
1894
|
+
}
|
|
1895
|
+
return this.http.get(url, {
|
|
1896
|
+
headers: { Accept: 'application/ld+json' },
|
|
1897
|
+
}).pipe(map(r => {
|
|
1898
|
+
const raw = r['member'] ?? r['hydra:member'] ?? [];
|
|
1899
|
+
const flat = Array.isArray(raw) ? raw : [];
|
|
1900
|
+
const tree = this.buildTree(flat);
|
|
1901
|
+
this.cache.set(url, tree);
|
|
1902
|
+
return tree;
|
|
1903
|
+
}), catchError(err => {
|
|
1904
|
+
console.error('[NaviGraph] loadTree failed for', url, this.errors.humanize(err));
|
|
1905
|
+
return of([]);
|
|
1906
|
+
}));
|
|
1907
|
+
}
|
|
1908
|
+
/**
|
|
1909
|
+
* Build a nested tree from a flat array of nodes.
|
|
1910
|
+
* Nodes are sorted by sortOrder at each level.
|
|
1911
|
+
*/
|
|
1912
|
+
buildTree(flat) {
|
|
1913
|
+
if (!flat.length) {
|
|
1914
|
+
return [];
|
|
1915
|
+
}
|
|
1916
|
+
const map = new Map(flat.map(n => [n.id, { ...n, children: [] }]));
|
|
1917
|
+
const roots = [];
|
|
1918
|
+
for (const node of map.values()) {
|
|
1919
|
+
if (node.parentId && map.has(node.parentId)) {
|
|
1920
|
+
map.get(node.parentId).children.push(node);
|
|
1921
|
+
}
|
|
1922
|
+
else {
|
|
1923
|
+
roots.push(node);
|
|
1924
|
+
}
|
|
1925
|
+
}
|
|
1926
|
+
const sort = (nodes) => {
|
|
1927
|
+
nodes.sort((a, b) => a.sortOrder - b.sortOrder);
|
|
1928
|
+
nodes.forEach(n => n.children?.length && sort(n.children));
|
|
1929
|
+
};
|
|
1930
|
+
sort(roots);
|
|
1931
|
+
return roots;
|
|
1932
|
+
}
|
|
1933
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: NaviGraphService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
1934
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: NaviGraphService, providedIn: 'root' });
|
|
1935
|
+
}
|
|
1936
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: NaviGraphService, decorators: [{
|
|
1937
|
+
type: Injectable,
|
|
1938
|
+
args: [{ providedIn: 'root' }]
|
|
1939
|
+
}] });
|
|
1940
|
+
|
|
1941
|
+
// --- NaviGraph API types ------------------------------------------------------
|
|
1942
|
+
// Mirror the PHP NaviGraphNodeResource DTO exactly. No `any` allowed.
|
|
1943
|
+
|
|
1944
|
+
/**
|
|
1945
|
+
* Registry mapping string keys to Angular component classes.
|
|
1946
|
+
*
|
|
1947
|
+
* Backed by a static Map so components registered at module load time
|
|
1948
|
+
* (e.g. in app.config.ts) are visible to all injected instances.
|
|
1949
|
+
*
|
|
1950
|
+
* Usage — static (app.config.ts / bootstrap time):
|
|
1951
|
+
* ComponentRegistry.register('MediaLibraryPage', MediaLibraryPage);
|
|
1952
|
+
*
|
|
1953
|
+
* Usage — injected (SlotComponent / runtime):
|
|
1954
|
+
* private readonly registry = inject(ComponentRegistry);
|
|
1955
|
+
* const cls = this.registry.get('MediaLibraryPage');
|
|
1956
|
+
*/
|
|
1957
|
+
class ComponentRegistry {
|
|
1958
|
+
static map = new Map();
|
|
1959
|
+
// -- Static API (bootstrap / app.config.ts) -------------------------------
|
|
1960
|
+
static register(key, component) {
|
|
1961
|
+
ComponentRegistry.map.set(key, component);
|
|
1962
|
+
}
|
|
1963
|
+
static get(key) {
|
|
1964
|
+
return ComponentRegistry.map.get(key);
|
|
1965
|
+
}
|
|
1966
|
+
static has(key) {
|
|
1967
|
+
return ComponentRegistry.map.has(key);
|
|
1968
|
+
}
|
|
1969
|
+
static keys() {
|
|
1970
|
+
return Array.from(ComponentRegistry.map.keys());
|
|
1971
|
+
}
|
|
1972
|
+
// -- Instance API (injectable) ---------------------------------------------
|
|
1973
|
+
register(key, component) {
|
|
1974
|
+
ComponentRegistry.register(key, component);
|
|
1975
|
+
}
|
|
1976
|
+
get(key) {
|
|
1977
|
+
return ComponentRegistry.get(key) ?? null;
|
|
1978
|
+
}
|
|
1979
|
+
has(key) {
|
|
1980
|
+
return ComponentRegistry.has(key);
|
|
1981
|
+
}
|
|
1982
|
+
keys() {
|
|
1983
|
+
return ComponentRegistry.keys();
|
|
1984
|
+
}
|
|
1985
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: ComponentRegistry, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
1986
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: ComponentRegistry, providedIn: 'root' });
|
|
1987
|
+
}
|
|
1988
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: ComponentRegistry, decorators: [{
|
|
1989
|
+
type: Injectable,
|
|
1990
|
+
args: [{ providedIn: 'root' }]
|
|
1991
|
+
}] });
|
|
1992
|
+
|
|
1993
|
+
/**
|
|
1994
|
+
* Optional by design: an application assembled without a Sections module binds
|
|
1995
|
+
* nothing and simply sends no `X-CoolMS-Section` header, which is exactly what
|
|
1996
|
+
* a single-site install wants.
|
|
1997
|
+
*/
|
|
1998
|
+
const CURRENT_SECTION = new InjectionToken('coolms.current-section');
|
|
1999
|
+
|
|
2000
|
+
/**
|
|
2001
|
+
* Phase H7 -- admin Site Selector.
|
|
2002
|
+
*
|
|
2003
|
+
* Stamps `X-CoolMS-Section: <slug>` on outgoing `/api/v1/*` requests when
|
|
2004
|
+
* the admin has picked a section from the Site Selector dropdown. The backend
|
|
2005
|
+
* honours it for AUTHENTICATED requests only -- anonymous traffic cannot pivot
|
|
2006
|
+
* the active section.
|
|
2007
|
+
*
|
|
2008
|
+
* What the header actually reaches, counted rather than intended: exactly two
|
|
2009
|
+
* readers act on it, `CreatePageProcessor` and `CreateCollectionProcessor`,
|
|
2010
|
+
* each choosing WHICH SITE a newly created page or collection lands in -- and,
|
|
2011
|
+
* for a page, that section's default locale and slug-naming policy. Nothing
|
|
2012
|
+
* else is scoped by it. Media spaces list every active section regardless, and
|
|
2013
|
+
* every other reader of `_coolms_section` sits on the public SSR surface,
|
|
2014
|
+
* which resolves from host+path and never sees this header.
|
|
2015
|
+
*
|
|
2016
|
+
* This block used to say the backend "scopes site-specific API providers
|
|
2017
|
+
* (pages, media spaces, etc.)". That described where was heading --
|
|
2018
|
+
* H4/H5, multisite Document and Media, never landed -- not what it does. Left
|
|
2019
|
+
* recorded because a docstring naming an intended destination reads exactly
|
|
2020
|
+
* like one naming a shipped feature, and this one misdescribed the control for
|
|
2021
|
+
* three months.
|
|
2022
|
+
*
|
|
2023
|
+
* Skipped:
|
|
2024
|
+
* - non-API URLs (no section context needed for SSR/static)
|
|
2025
|
+
* - `/auth/*` endpoints (login/refresh are pre-session; the header would
|
|
2026
|
+
* be ignored by the backend anyway, but skipping keeps wire traffic clean)
|
|
2027
|
+
* - requests that already carry the header (programmatic overrides win)
|
|
2028
|
+
*/
|
|
2029
|
+
const sectionInterceptor = (req, next) => {
|
|
2030
|
+
if (!shouldStamp(req.url)) {
|
|
2031
|
+
return next(req);
|
|
2032
|
+
}
|
|
2033
|
+
if (req.headers.has('X-CoolMS-Section')) {
|
|
2034
|
+
return next(req);
|
|
2035
|
+
}
|
|
2036
|
+
// Optional: no Sections module installed means no section to stamp.
|
|
2037
|
+
const slug = inject(CURRENT_SECTION, { optional: true })?.currentSlug() ?? null;
|
|
2038
|
+
if (!slug)
|
|
2039
|
+
return next(req);
|
|
2040
|
+
return next(req.clone({ setHeaders: { 'X-CoolMS-Section': slug } }));
|
|
2041
|
+
};
|
|
2042
|
+
function shouldStamp(url) {
|
|
2043
|
+
// Strip protocol/host so absolute and relative URLs are treated alike.
|
|
2044
|
+
const path = url.replace(/^https?:\/\/[^/]+/, '');
|
|
2045
|
+
if (!path.startsWith('/api/v1/'))
|
|
2046
|
+
return false;
|
|
2047
|
+
if (path.startsWith('/api/v1/auth/'))
|
|
2048
|
+
return false;
|
|
2049
|
+
return true;
|
|
2050
|
+
}
|
|
2051
|
+
|
|
2052
|
+
/**
|
|
2053
|
+
* `@coolms/core-angular` -- the CoolMS client runtime for Angular.
|
|
2054
|
+
*
|
|
2055
|
+
* Everything a CoolMS front-end needs before it has any UI: the session and its
|
|
2056
|
+
* refresh/cross-tab machinery, the boot manifest and app config, theme and user
|
|
2057
|
+
* preferences, error handling, the HTTP interceptors, and the wire types the
|
|
2058
|
+
* backend's form-render and navi-graph endpoints emit.
|
|
2059
|
+
*
|
|
2060
|
+
* It is deliberately NOT "the admin's core": nothing here is admin chrome. It is
|
|
2061
|
+
* also not a general Angular library -- every endpoint it speaks is a CoolMS
|
|
2062
|
+
* one, so it is worthless without a CoolMS backend. The layering is
|
|
2063
|
+
*
|
|
2064
|
+
* @coolms/core-angular -> @coolms/admin-ui-angular -> @coolms/x-ui-angular
|
|
2065
|
+
*
|
|
2066
|
+
* and the reason it must be a package rather than app code is federation: the
|
|
2067
|
+
* kit and every remote need this at runtime as ONE `singleton`, and a remote
|
|
2068
|
+
* cannot import from its host.
|
|
2069
|
+
*
|
|
2070
|
+
* This barrel is the whole public surface. Nothing outside `core/` may deep-link
|
|
2071
|
+
* past it -- eslint enforces that, so this file is what "core exports" MEANS. A
|
|
2072
|
+
* symbol not listed here is internal, and adding one is a deliberate act.
|
|
2073
|
+
*
|
|
2074
|
+
* The single component (`LoginComponent`) is here on purpose: core owns the auth
|
|
2075
|
+
* lifecycle, so it ships a working sign-in rather than leaving every consumer to
|
|
2076
|
+
* rebuild one against endpoints only core knows.
|
|
2077
|
+
*/
|
|
2078
|
+
// -- Wire types + the API client core owns ------------------------------------
|
|
2079
|
+
|
|
2080
|
+
/**
|
|
2081
|
+
* Generated bundle index. Do not edit.
|
|
2082
|
+
*/
|
|
2083
|
+
|
|
2084
|
+
export { AppConfigState, AppInitService, AuthRefreshCoordinator, AuthState, BYPASS_AUTH, CURRENT_SECTION, CmsLoaderComponent, ComponentRegistry, ConfigService, CrossTabAuthSyncService, EntitySearchService, ErrorHandlerService, IdentityApiClient, Login, LoginComponent, Logout, NaviGraphService, PatchCurrentUser, RealtimeTokenClient, RestoreSession, SetAppConfig, SetTokens, SidebarStateService, ThemeService, UserPreferencesService, authGuard, authInterceptor, loginPageGuard, resolvePattern, sectionInterceptor };
|
|
2085
|
+
//# sourceMappingURL=coolms-core-angular.mjs.map
|