@masterteam/dashboard-builder 0.0.118 → 0.0.120

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.
@@ -0,0 +1,588 @@
1
+ import * as i0 from '@angular/core';
2
+ import { input, inject, signal, ChangeDetectionStrategy, Component, Injector, computed, Injectable, DestroyRef, effect, untracked, Directive } from '@angular/core';
3
+ import { toSignal } from '@angular/core/rxjs-interop';
4
+ import { TranslocoDirective, TranslocoService } from '@jsverse/transloco';
5
+ import { Router } from '@angular/router';
6
+ import { ConfirmationService } from '@masterteam/components/confirmation';
7
+ import { ConfirmEventType } from 'primeng/api';
8
+ import { WIDGET_PALETTE_TILE_HOST, DashboardBuilder, cloneDeep, DASHBOARD_BUILDER_ASSIST, DashboardList, DashboardBuilderService, dashboardLevelOptions } from '@masterteam/dashboard-builder';
9
+ import { FarisMark, FarisPageActions, FarisDraftTargets, FarisContextRegistry, FarisSessionStore, FARIS_CONFIG, controlPanelContextPath, localizedActionText } from '@masterteam/faris';
10
+ import { Icon } from '@masterteam/icons';
11
+ import { map, catchError, of } from 'rxjs';
12
+
13
+ class FarisWidgetPaletteTile {
14
+ widget = input.required(...(ngDevMode ? [{ debugName: "widget" }] : /* istanbul ignore next */ []));
15
+ label = input.required(...(ngDevMode ? [{ debugName: "label" }] : /* istanbul ignore next */ []));
16
+ host = inject(WIDGET_PALETTE_TILE_HOST);
17
+ split = signal(false, ...(ngDevMode ? [{ debugName: "split" }] : /* istanbul ignore next */ []));
18
+ pointerType = '';
19
+ onPointerDown(event) {
20
+ this.pointerType = event.pointerType;
21
+ }
22
+ choose(choice) {
23
+ if (this.pointerType === 'touch' && !this.split()) {
24
+ this.split.set(true);
25
+ return;
26
+ }
27
+ this.host[choice](this.widget());
28
+ }
29
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: FarisWidgetPaletteTile, deps: [], target: i0.ɵɵFactoryTarget.Component });
30
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.1.0", version: "21.2.8", type: FarisWidgetPaletteTile, isStandalone: true, selector: "mt-faris-widget-palette-tile", inputs: { widget: { classPropertyName: "widget", publicName: "widget", isSignal: true, isRequired: true, transformFunction: null }, label: { classPropertyName: "label", publicName: "label", isSignal: true, isRequired: true, transformFunction: null } }, ngImport: i0, template: "<ng-container *transloco=\"let t\">\r\n <div\r\n class=\"faris-palette-tile group relative flex min-h-24 overflow-hidden rounded-lg border border-surface-200 bg-surface-0 select-none transition-all hover:border-faris-accent-border hover:shadow-md\"\r\n draggable=\"true\"\r\n (dragstart)=\"host.dragStart($event, widget())\"\r\n (pointerdown)=\"onPointerDown($event)\"\r\n [attr.data-split]=\"split() || null\"\r\n >\r\n <div\r\n aria-hidden=\"true\"\r\n class=\"absolute inset-0 flex flex-col items-center justify-center gap-2 p-4 transition-opacity duration-faris motion-reduce:transition-none group-hover:opacity-0 group-focus-within:opacity-0\"\r\n [class.opacity-0]=\"split()\"\r\n >\r\n <!-- The same face as the palette's plain tiles; Faris shows only as the spark. -->\r\n <div class=\"flex h-10 w-10 items-center justify-center text-primary-500\">\r\n <mt-icon [icon]=\"widget().icon\" class=\"text-2xl\" />\r\n </div>\r\n <span class=\"text-center text-xs font-medium leading-tight text-color\">{{\r\n label()\r\n }}</span>\r\n <mt-faris-mark\r\n size=\"0.75rem\"\r\n tone=\"spark\"\r\n class=\"absolute end-1.5 top-1.5\"\r\n />\r\n </div>\r\n <button\r\n type=\"button\"\r\n class=\"absolute start-0 inset-y-0 flex w-1/2 flex-col items-center justify-center gap-2 p-2 bg-faris-accent-soft text-faris-accent-soft-ink transition-opacity duration-faris motion-reduce:transition-none group-hover:opacity-100 group-focus-within:opacity-100 active:bg-faris-hover\"\r\n [class.opacity-0]=\"!split()\"\r\n [class.opacity-100]=\"split()\"\r\n [attr.aria-label]=\"\r\n t('faris.assist.createTypeWithFaris', { type: label() })\r\n \"\r\n (click)=\"choose('assist')\"\r\n >\r\n <span\r\n class=\"absolute inset-x-0 top-0 h-0.5 bg-linear-to-r from-faris-brand-from to-faris-brand-to rtl:bg-linear-to-l\"\r\n aria-hidden=\"true\"\r\n ></span>\r\n <mt-faris-mark size=\"0.875rem\" tone=\"spark\" />\r\n <span class=\"text-center text-xs font-semibold leading-tight\">{{\r\n t(\"faris.assist.withFaris\")\r\n }}</span>\r\n </button>\r\n <button\r\n type=\"button\"\r\n class=\"absolute end-0 inset-y-0 flex w-1/2 flex-col items-center justify-center gap-2 border-s border-surface-200 bg-surface-0 p-2 text-surface-700 transition-opacity duration-faris motion-reduce:transition-none group-hover:opacity-100 group-focus-within:opacity-100 active:bg-surface-100\"\r\n [class.opacity-0]=\"!split()\"\r\n [class.opacity-100]=\"split()\"\r\n [attr.aria-label]=\"t('faris.assist.addTypeManually', { type: label() })\"\r\n (click)=\"choose('select')\"\r\n >\r\n <mt-icon icon=\"general.plus\" />\r\n <span class=\"text-center text-xs leading-tight\">{{\r\n t(\"faris.assist.manual\")\r\n }}</span>\r\n </button>\r\n </div>\r\n</ng-container>\r\n", dependencies: [{ kind: "component", type: FarisMark, selector: "mt-faris-mark", inputs: ["size", "label", "tone", "alive"] }, { kind: "component", type: Icon, selector: "mt-icon", inputs: ["icon"] }, { kind: "directive", type: TranslocoDirective, selector: "[transloco]", inputs: ["transloco", "translocoParams", "translocoScope", "translocoRead", "translocoPrefix", "translocoLang", "translocoLoadingTpl"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
31
+ }
32
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: FarisWidgetPaletteTile, decorators: [{
33
+ type: Component,
34
+ args: [{ selector: 'mt-faris-widget-palette-tile', imports: [FarisMark, Icon, TranslocoDirective], changeDetection: ChangeDetectionStrategy.OnPush, template: "<ng-container *transloco=\"let t\">\r\n <div\r\n class=\"faris-palette-tile group relative flex min-h-24 overflow-hidden rounded-lg border border-surface-200 bg-surface-0 select-none transition-all hover:border-faris-accent-border hover:shadow-md\"\r\n draggable=\"true\"\r\n (dragstart)=\"host.dragStart($event, widget())\"\r\n (pointerdown)=\"onPointerDown($event)\"\r\n [attr.data-split]=\"split() || null\"\r\n >\r\n <div\r\n aria-hidden=\"true\"\r\n class=\"absolute inset-0 flex flex-col items-center justify-center gap-2 p-4 transition-opacity duration-faris motion-reduce:transition-none group-hover:opacity-0 group-focus-within:opacity-0\"\r\n [class.opacity-0]=\"split()\"\r\n >\r\n <!-- The same face as the palette's plain tiles; Faris shows only as the spark. -->\r\n <div class=\"flex h-10 w-10 items-center justify-center text-primary-500\">\r\n <mt-icon [icon]=\"widget().icon\" class=\"text-2xl\" />\r\n </div>\r\n <span class=\"text-center text-xs font-medium leading-tight text-color\">{{\r\n label()\r\n }}</span>\r\n <mt-faris-mark\r\n size=\"0.75rem\"\r\n tone=\"spark\"\r\n class=\"absolute end-1.5 top-1.5\"\r\n />\r\n </div>\r\n <button\r\n type=\"button\"\r\n class=\"absolute start-0 inset-y-0 flex w-1/2 flex-col items-center justify-center gap-2 p-2 bg-faris-accent-soft text-faris-accent-soft-ink transition-opacity duration-faris motion-reduce:transition-none group-hover:opacity-100 group-focus-within:opacity-100 active:bg-faris-hover\"\r\n [class.opacity-0]=\"!split()\"\r\n [class.opacity-100]=\"split()\"\r\n [attr.aria-label]=\"\r\n t('faris.assist.createTypeWithFaris', { type: label() })\r\n \"\r\n (click)=\"choose('assist')\"\r\n >\r\n <span\r\n class=\"absolute inset-x-0 top-0 h-0.5 bg-linear-to-r from-faris-brand-from to-faris-brand-to rtl:bg-linear-to-l\"\r\n aria-hidden=\"true\"\r\n ></span>\r\n <mt-faris-mark size=\"0.875rem\" tone=\"spark\" />\r\n <span class=\"text-center text-xs font-semibold leading-tight\">{{\r\n t(\"faris.assist.withFaris\")\r\n }}</span>\r\n </button>\r\n <button\r\n type=\"button\"\r\n class=\"absolute end-0 inset-y-0 flex w-1/2 flex-col items-center justify-center gap-2 border-s border-surface-200 bg-surface-0 p-2 text-surface-700 transition-opacity duration-faris motion-reduce:transition-none group-hover:opacity-100 group-focus-within:opacity-100 active:bg-surface-100\"\r\n [class.opacity-0]=\"!split()\"\r\n [class.opacity-100]=\"split()\"\r\n [attr.aria-label]=\"t('faris.assist.addTypeManually', { type: label() })\"\r\n (click)=\"choose('select')\"\r\n >\r\n <mt-icon icon=\"general.plus\" />\r\n <span class=\"text-center text-xs leading-tight\">{{\r\n t(\"faris.assist.manual\")\r\n }}</span>\r\n </button>\r\n </div>\r\n</ng-container>\r\n" }]
35
+ }], propDecorators: { widget: [{ type: i0.Input, args: [{ isSignal: true, alias: "widget", required: true }] }], label: [{ type: i0.Input, args: [{ isSignal: true, alias: "label", required: true }] }] } });
36
+
37
+ class FarisDashboardAssist {
38
+ actions = inject(FarisPageActions);
39
+ // The builder requests this provider while it is being constructed. Resolve
40
+ // its instance only when the menu asks, avoiding a circular element injection.
41
+ injector = inject(Injector);
42
+ transloco = inject(TranslocoService);
43
+ typeIds = computed(() => {
44
+ const capability = this.actions
45
+ .actions()
46
+ .find((action) => action.capabilityId === 'widget.draft' &&
47
+ this.actions.isStartable(action));
48
+ const input = capability?.inputs?.find((entry) => entry.name === 'widgetType');
49
+ return new Set((input?.options ?? [])
50
+ .map((option) => option.value)
51
+ .filter((value) => typeof value === 'string'));
52
+ }, ...(ngDevMode ? [{ debugName: "typeIds" }] : /* istanbul ignore next */ []));
53
+ paletteTile = FarisWidgetPaletteTile;
54
+ itemLabel = toSignal(this.transloco.selectTranslate('faris.assist.changeWithFaris'), { initialValue: '' });
55
+ itemIcon = 'weather.stars-02';
56
+ canAssistItem(item) {
57
+ const builder = this.injector.get(DashboardBuilder);
58
+ const level = builder.chartLevel(item);
59
+ return (this.typeIds().has(item.chartTypeId ?? '') &&
60
+ builder.levelOptions().some((option) => option.levelId === level));
61
+ }
62
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: FarisDashboardAssist, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
63
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: FarisDashboardAssist });
64
+ }
65
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: FarisDashboardAssist, decorators: [{
66
+ type: Injectable
67
+ }] });
68
+
69
+ /** One in-memory handoff to a new, unsaved dashboard. */
70
+ class FarisDashboardIntent {
71
+ pending = null;
72
+ set(document, draftId, levelId = null) {
73
+ this.pending = { document: cloneDeep(document), draftId, levelId };
74
+ }
75
+ take() {
76
+ const pending = this.pending;
77
+ this.pending = null;
78
+ return pending;
79
+ }
80
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: FarisDashboardIntent, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
81
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: FarisDashboardIntent, providedIn: 'root' });
82
+ }
83
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: FarisDashboardIntent, decorators: [{
84
+ type: Injectable,
85
+ args: [{ providedIn: 'root' }]
86
+ }] });
87
+
88
+ class FarisDashboardDrafts {
89
+ mtFarisNewDashboardLink = input(null, ...(ngDevMode ? [{ debugName: "mtFarisNewDashboardLink" }] : /* istanbul ignore next */ []));
90
+ builder = inject(DashboardBuilder, { self: true });
91
+ pageActions = inject(FarisPageActions);
92
+ targets = inject(FarisDraftTargets);
93
+ registry = inject(FarisContextRegistry);
94
+ session = inject(FarisSessionStore);
95
+ config = inject(FARIS_CONFIG);
96
+ transloco = inject(TranslocoService);
97
+ destroyRef = inject(DestroyRef);
98
+ router = inject(Router);
99
+ confirmation = inject(ConfirmationService);
100
+ intent = inject(FarisDashboardIntent);
101
+ levelId = signal(null, ...(ngDevMode ? [{ debugName: "levelId" }] : /* istanbul ignore next */ []));
102
+ records = new Map();
103
+ documents = new Map();
104
+ filled = signal(new Set(), ...(ngDevMode ? [{ debugName: "filled" }] : /* istanbul ignore next */ []));
105
+ arriving = signal(new Set(), ...(ngDevMode ? [{ debugName: "arriving" }] : /* istanbul ignore next */ []));
106
+ timers = new Map();
107
+ arrivalTimers = new Map();
108
+ pendingConfirmations = new Set();
109
+ filledLabel = toSignal(this.transloco.selectTranslate('faris.pageDraft.filledByFaris'), { initialValue: '' });
110
+ target = {
111
+ kinds: ['widget', 'dashboard'],
112
+ scope: () => ({ levelId: this.levelId(), moduleId: null }),
113
+ load: (draft, context) => this.load(draft, context),
114
+ undo: (draftId) => {
115
+ const document = this.documents.get(draftId);
116
+ if (document) {
117
+ const current = this.builder.snapshot();
118
+ const kept = (current.charts ?? []).filter((item) => {
119
+ const loaded = document.signatures.get(item.config.serviceConfig.dashboardId);
120
+ return (!loaded ||
121
+ configSignature(item) !== configSignature(loaded) ||
122
+ geometrySignature(item) !== geometrySignature(loaded));
123
+ });
124
+ const keepFilters = changed(current.filters, document.loaded.filters);
125
+ const keepDialogs = changed(current.dialogs, document.loaded.dialogs);
126
+ const keepPage = changed(current.page, document.loaded.page);
127
+ this.builder.restore({
128
+ page: keepPage ? current.page : document.snapshot.page,
129
+ charts: [...(document.snapshot.charts ?? []), ...kept],
130
+ filters: keepFilters ? current.filters : document.snapshot.filters,
131
+ dialogs: keepDialogs ? current.dialogs : document.snapshot.dialogs,
132
+ });
133
+ for (const id of document.signatures.keys())
134
+ this.dropMark(id);
135
+ this.documents.delete(draftId);
136
+ return {
137
+ kept: kept.length +
138
+ Number(keepFilters) +
139
+ Number(keepDialogs) +
140
+ Number(keepPage),
141
+ };
142
+ }
143
+ const record = this.records.get(draftId);
144
+ if (!record)
145
+ return null;
146
+ const item = this.builder.chartById(record.dashboardId);
147
+ const configEdited = !!item && configSignature(item) !== record.signature;
148
+ const moved = !!item && geometrySignature(item) !== record.geometry;
149
+ if (item && !configEdited) {
150
+ if (record.previous)
151
+ this.builder.replaceChart(record.dashboardId, record.previous);
152
+ else if (!moved)
153
+ this.builder.removeChart(record.dashboardId);
154
+ }
155
+ this.dropMark(record.dashboardId);
156
+ this.records.delete(draftId);
157
+ return { kept: !item || configEdited || moved ? 1 : 0 };
158
+ },
159
+ levelOptions: () => this.builder.levelOptions().map((option) => ({
160
+ levelId: option.levelId,
161
+ label: (option.templateName
162
+ ? this.localized(option.templateName) + ' · '
163
+ : '') + this.localized(option.name),
164
+ })),
165
+ selectLevel: (id) => this.levelId.set(id),
166
+ refineNotice: (draft) => {
167
+ if (draft.kind !== 'dashboard')
168
+ return null;
169
+ const record = this.documents.get(draft.draftId);
170
+ if (!record)
171
+ return null;
172
+ const count = this.builder.charts().filter((item) => {
173
+ const signature = record.signatures.get(item.config.serviceConfig.dashboardId);
174
+ return (signature !== undefined &&
175
+ (configSignature(signature) !== configSignature(item) ||
176
+ geometrySignature(signature) !== geometrySignature(item)));
177
+ }).length;
178
+ return count
179
+ ? this.transloco.translate('faris.dashboard.rebuildNotice', { count })
180
+ : null;
181
+ },
182
+ subjectLevel: (subject) => this.builder.chartLevel(subject),
183
+ actionInputs: (capabilityId, subject) => {
184
+ if (capabilityId !== 'widget.draft')
185
+ return {};
186
+ const filters = this.builder.pageFilters();
187
+ const id = dashboardIdOf(subject);
188
+ const item = id ? this.builder.chartById(id) : null;
189
+ return {
190
+ ...(filters.length ? { pageFilters: cloneDeep(filters) } : {}),
191
+ ...(item ? { current: wire(item) } : {}),
192
+ };
193
+ },
194
+ };
195
+ marks = computed(() => {
196
+ const marks = {};
197
+ for (const id of this.filled())
198
+ marks[id] = {
199
+ cssClass: 'faris-filled-widget',
200
+ label: this.filledLabel(),
201
+ };
202
+ const addClass = (id, cssClass) => {
203
+ marks[id] = {
204
+ ...marks[id],
205
+ cssClass: [marks[id]?.cssClass, cssClass].filter(Boolean).join(' '),
206
+ };
207
+ };
208
+ for (const id of this.arriving())
209
+ addClass(id, 'faris-arrived');
210
+ const workingId = this.session.isRunning()
211
+ ? dashboardIdOf(this.pageActions.active()?.subject)
212
+ : null;
213
+ if (workingId && this.builder.chartById(workingId))
214
+ addClass(workingId, 'faris-working');
215
+ return marks;
216
+ }, ...(ngDevMode ? [{ debugName: "marks" }] : /* istanbul ignore next */ []));
217
+ constructor() {
218
+ const release = this.pageActions.watch();
219
+ const unregisterContext = this.registry.register('faris-dashboard-builder', () => {
220
+ const id = this.levelId();
221
+ return id ? { context: controlPanelContextPath(id) } : null;
222
+ });
223
+ const unregisterTarget = this.targets.register(this.target);
224
+ const pending = this.intent.take();
225
+ if (pending?.levelId != null)
226
+ this.levelId.set(pending.levelId);
227
+ let consumed = false;
228
+ if (pending)
229
+ effect(() => {
230
+ if (consumed ||
231
+ !this.builder.newPage() ||
232
+ this.builder.effectivePageId() != null)
233
+ return;
234
+ consumed = true;
235
+ untracked(() => {
236
+ this.loadDashboard(pending.document, pending.draftId, 'new');
237
+ this.targets.adoptLoaded(pending.draftId, this.target, pending.document.charts.length);
238
+ });
239
+ });
240
+ effect(() => this.builder.itemMarks.set(this.marks()));
241
+ effect(() => {
242
+ this.builder.charts();
243
+ const filled = this.filled();
244
+ untracked(() => this.dropChangedMarks(filled));
245
+ });
246
+ const saved = this.builder.onSave.subscribe(() => {
247
+ this.targets.markSaved(this.target);
248
+ this.filled.set(new Set());
249
+ this.arriving.set(new Set());
250
+ this.records.clear();
251
+ this.documents.clear();
252
+ this.clearTimers();
253
+ for (const cancel of this.pendingConfirmations)
254
+ cancel();
255
+ });
256
+ const widgetAssist = this.builder.widgetAssist.subscribe((widget) => this.pageActions.start('widget.draft', {
257
+ inputs: { widgetType: widget.id },
258
+ returnFocusTo: document.activeElement,
259
+ }));
260
+ const itemAssist = this.builder.itemAssist.subscribe((item) => this.pageActions.start('widget.draft', {
261
+ subject: item,
262
+ inputs: { widgetType: item.chartTypeId },
263
+ }));
264
+ this.destroyRef.onDestroy(() => {
265
+ release();
266
+ unregisterContext();
267
+ unregisterTarget();
268
+ saved.unsubscribe();
269
+ widgetAssist.unsubscribe();
270
+ itemAssist.unsubscribe();
271
+ this.clearTimers();
272
+ for (const cancel of this.pendingConfirmations)
273
+ cancel();
274
+ });
275
+ }
276
+ localized(name) {
277
+ if (typeof name === 'string')
278
+ return name;
279
+ return this.config.locale() === 'ar'
280
+ ? name.ar || name.en || ''
281
+ : name.en || name.ar || '';
282
+ }
283
+ load(draft, context) {
284
+ if (draft.kind === 'dashboard') {
285
+ // A refinement rebuilds the dashboard its draft filled on this page; the
286
+ // user chose that (the chip says it), so it does not ask again.
287
+ const replaced = context.replaces
288
+ ? this.documents.get(context.replaces.draftId)
289
+ : undefined;
290
+ if (replaced && replaced.pageId === this.builder.effectivePageId())
291
+ return this.loadDashboard(draft.document, draft.draftId, replaced.pageId == null ? 'new' : 'replace');
292
+ return this.openDashboard(draft.document, draft.draftId, draft.scope.levelId);
293
+ }
294
+ if (draft.kind !== 'widget')
295
+ return { status: 'failed', message: null };
296
+ // A refinement replaces the widget its draft became; after a save the
297
+ // record is gone, and the subject (that widget) still names it.
298
+ const targetId = (context.replaces
299
+ ? this.records.get(context.replaces.draftId)?.dashboardId
300
+ : null) ?? dashboardIdOf(context.subject);
301
+ const existing = targetId ? this.builder.chartById(targetId) : null;
302
+ const previous = existing
303
+ ? cloneDeep({
304
+ chartTypeId: existing.chartTypeId ?? '',
305
+ config: existing.config,
306
+ })
307
+ : null;
308
+ const item = existing && targetId
309
+ ? this.builder.replaceChart(targetId, draft.widget)
310
+ : this.builder.addChart(draft.widget, { placement: 'first-free' });
311
+ if (!item)
312
+ return { status: 'failed', message: null };
313
+ const dashboardId = item.config.serviceConfig.dashboardId;
314
+ this.records.set(draft.draftId, {
315
+ dashboardId,
316
+ previous,
317
+ signature: configSignature(item),
318
+ geometry: geometrySignature(item),
319
+ });
320
+ this.filled.update((ids) => new Set([...ids, dashboardId]));
321
+ this.arrive(dashboardId);
322
+ this.builder.revealItem(dashboardId);
323
+ return {
324
+ status: 'loaded',
325
+ changed: 1,
326
+ subject: this.builder.chartById(dashboardId),
327
+ };
328
+ }
329
+ async openDashboard(document, draftId, levelId) {
330
+ const pageId = this.builder.effectivePageId();
331
+ const count = this.builder.charts().length;
332
+ if (count === 0) {
333
+ return this.loadDashboard(document, draftId, pageId == null ? 'new' : 'replace');
334
+ }
335
+ const t = (key) => this.transloco.translate('faris.dashboard.' + key, { count });
336
+ const link = this.builder.newPage() ? null : this.mtFarisNewDashboardLink();
337
+ if (link) {
338
+ const choice = await this.confirm({
339
+ header: t('openTitle'),
340
+ message: t('openMessage'),
341
+ acceptLabel: t('openAsNew'),
342
+ rejectLabel: t('replace'),
343
+ acceptButton: { severity: 'primary' },
344
+ defaultFocus: 'accept',
345
+ });
346
+ if (choice === 'cancel')
347
+ return { status: 'declined' };
348
+ if (choice === 'accept') {
349
+ this.intent.set(document, draftId, levelId);
350
+ const navigated = typeof link === 'string'
351
+ ? await this.router.navigateByUrl(link)
352
+ : await this.router.navigate([...link]);
353
+ if (!navigated) {
354
+ this.intent.take();
355
+ return { status: 'declined' };
356
+ }
357
+ return { status: 'loaded', changed: document.charts.length };
358
+ }
359
+ }
360
+ const choice = await this.confirm({
361
+ header: t('replaceTitle'),
362
+ message: t('replaceMessage'),
363
+ acceptLabel: t('replaceConfirm'),
364
+ rejectLabel: this.transloco.translate('faris.common.cancel'),
365
+ acceptButton: { severity: 'danger' },
366
+ defaultFocus: 'reject',
367
+ });
368
+ return choice === 'accept'
369
+ ? this.loadDashboard(document, draftId, 'replace')
370
+ : { status: 'declined' };
371
+ }
372
+ confirm(config) {
373
+ return new Promise((resolve) => {
374
+ const finish = (choice) => {
375
+ this.pendingConfirmations.delete(cancel);
376
+ resolve(choice);
377
+ };
378
+ const cancel = () => finish('cancel');
379
+ this.pendingConfirmations.add(cancel);
380
+ this.confirmation.confirm({
381
+ ...config,
382
+ type: 'dialog',
383
+ accept: () => finish('accept'),
384
+ reject: (type) => finish(type === ConfirmEventType.CANCEL ? 'cancel' : 'reject'),
385
+ });
386
+ });
387
+ }
388
+ loadDashboard(document, draftId, mode) {
389
+ const snapshot = this.builder.snapshot();
390
+ this.builder.loadDocument(document, {
391
+ mode,
392
+ });
393
+ const charts = this.builder.charts();
394
+ const loaded = this.builder.snapshot();
395
+ this.documents.set(draftId, {
396
+ pageId: this.builder.effectivePageId(),
397
+ snapshot,
398
+ loaded,
399
+ signatures: new Map((loaded.charts ?? []).map((item) => [
400
+ item.config.serviceConfig.dashboardId,
401
+ item,
402
+ ])),
403
+ });
404
+ charts.forEach((item, i) => {
405
+ const id = item.config.serviceConfig.dashboardId;
406
+ this.filled.update((ids) => new Set([...ids, id]));
407
+ this.arrivalTimers.set(id, setTimeout(() => {
408
+ this.arrivalTimers.delete(id);
409
+ this.arrive(id);
410
+ }, i * 60));
411
+ });
412
+ const first = charts[0]?.config.serviceConfig.dashboardId;
413
+ if (first)
414
+ this.builder.revealItem(first);
415
+ return { status: 'loaded', changed: charts.length };
416
+ }
417
+ arrive(id) {
418
+ this.arriving.update((ids) => new Set([...ids, id]));
419
+ clearTimeout(this.timers.get(id));
420
+ this.timers.set(id, setTimeout(() => {
421
+ this.arriving.update((ids) => without(ids, id));
422
+ this.timers.delete(id);
423
+ }, matchMedia('(prefers-reduced-motion: reduce)').matches ? 2000 : 900));
424
+ }
425
+ /** A mark leaves when the user changed the widget (its geometry does not count). */
426
+ dropChangedMarks(filled) {
427
+ for (const id of filled) {
428
+ const item = this.builder.chartById(id);
429
+ const record = [...this.records.values()]
430
+ .reverse()
431
+ .find((entry) => entry.dashboardId === id);
432
+ const loaded = [...this.documents.values()]
433
+ .reverse()
434
+ .map((entry) => entry.signatures.get(id))
435
+ .find((value) => value !== undefined);
436
+ const signature = record?.signature ?? (loaded ? configSignature(loaded) : undefined);
437
+ if (!item ||
438
+ signature === undefined ||
439
+ configSignature(item) !== signature) {
440
+ this.dropMark(id);
441
+ }
442
+ }
443
+ }
444
+ dropMark(id) {
445
+ this.filled.update((ids) => without(ids, id));
446
+ this.arriving.update((ids) => without(ids, id));
447
+ clearTimeout(this.timers.get(id));
448
+ this.timers.delete(id);
449
+ clearTimeout(this.arrivalTimers.get(id));
450
+ this.arrivalTimers.delete(id);
451
+ }
452
+ clearTimers() {
453
+ for (const timer of this.timers.values())
454
+ clearTimeout(timer);
455
+ this.timers.clear();
456
+ for (const timer of this.arrivalTimers.values())
457
+ clearTimeout(timer);
458
+ this.arrivalTimers.clear();
459
+ }
460
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: FarisDashboardDrafts, deps: [], target: i0.ɵɵFactoryTarget.Directive });
461
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.8", type: FarisDashboardDrafts, isStandalone: true, selector: "mt-dashboard-builder[mtFarisDrafts]", inputs: { mtFarisNewDashboardLink: { classPropertyName: "mtFarisNewDashboardLink", publicName: "mtFarisNewDashboardLink", isSignal: true, isRequired: false, transformFunction: null } }, providers: [
462
+ FarisDashboardAssist,
463
+ { provide: DASHBOARD_BUILDER_ASSIST, useExisting: FarisDashboardAssist },
464
+ ], ngImport: i0 });
465
+ }
466
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: FarisDashboardDrafts, decorators: [{
467
+ type: Directive,
468
+ args: [{
469
+ selector: 'mt-dashboard-builder[mtFarisDrafts]',
470
+ standalone: true,
471
+ providers: [
472
+ FarisDashboardAssist,
473
+ { provide: DASHBOARD_BUILDER_ASSIST, useExisting: FarisDashboardAssist },
474
+ ],
475
+ }]
476
+ }], ctorParameters: () => [], propDecorators: { mtFarisNewDashboardLink: [{ type: i0.Input, args: [{ isSignal: true, alias: "mtFarisNewDashboardLink", required: false }] }] } });
477
+ function without(ids, id) {
478
+ const next = new Set(ids);
479
+ next.delete(id);
480
+ return next;
481
+ }
482
+ function dashboardIdOf(subject) {
483
+ return (subject?.config?.serviceConfig
484
+ ?.dashboardId ?? null);
485
+ }
486
+ function wire(item) {
487
+ const { x, y, cols, rows, chartTypeId, config } = item;
488
+ return cloneDeep({
489
+ x,
490
+ y,
491
+ cols,
492
+ rows,
493
+ chartTypeId,
494
+ config: {
495
+ serviceConfig: config.serviceConfig,
496
+ clientConfig: config.clientConfig,
497
+ },
498
+ });
499
+ }
500
+ function configSignature(item) {
501
+ const serviceConfig = {
502
+ ...item.config.serviceConfig,
503
+ };
504
+ delete serviceConfig['dashboardId'];
505
+ return JSON.stringify({
506
+ type: item.chartTypeId,
507
+ ...item.config,
508
+ serviceConfig,
509
+ });
510
+ }
511
+ function geometrySignature(item) {
512
+ const { x, y, cols, rows, group, orderInGroup } = item;
513
+ return JSON.stringify({ x, y, cols, rows, group, orderInGroup });
514
+ }
515
+ function changed(current, loaded) {
516
+ return JSON.stringify(current) !== JSON.stringify(loaded);
517
+ }
518
+
519
+ /** The list supplies a level and opens whole drafts in the unsaved builder. */
520
+ class FarisDashboardListDrafts {
521
+ list = inject(DashboardList, { self: true });
522
+ config = inject(FARIS_CONFIG);
523
+ router = inject(Router);
524
+ intent = inject(FarisDashboardIntent);
525
+ levelId = signal(null, ...(ngDevMode ? [{ debugName: "levelId" }] : /* istanbul ignore next */ []));
526
+ levels = toSignal(inject(DashboardBuilderService)
527
+ .getModulesTree({ services: [] })
528
+ .pipe(map((response) => dashboardLevelOptions(response.data?.services ?? [])), catchError(() => of([]))), { initialValue: [] });
529
+ levelOptions = computed(() => {
530
+ const locale = this.config.locale();
531
+ const labelOf = (name) => (typeof name === 'string' ? name : localizedActionText(name, locale));
532
+ return this.levels().map((level) => ({
533
+ levelId: level.levelId,
534
+ label: [labelOf(level.templateName), labelOf(level.name)]
535
+ .filter(Boolean)
536
+ .join(' · '),
537
+ }));
538
+ }, ...(ngDevMode ? [{ debugName: "levelOptions" }] : /* istanbul ignore next */ []));
539
+ constructor() {
540
+ const target = {
541
+ kinds: ['dashboard'],
542
+ scope: () => ({ levelId: this.levelId(), moduleId: null }),
543
+ levelOptions: this.levelOptions,
544
+ selectLevel: (id) => this.levelId.set(id),
545
+ inviteActions: () => [],
546
+ load: async (draft) => {
547
+ const path = this.list.createPath();
548
+ if (draft.kind !== 'dashboard' || !path)
549
+ return { status: 'declined' };
550
+ this.intent.set(draft.document, draft.draftId, draft.scope.levelId);
551
+ let navigated = false;
552
+ try {
553
+ navigated = await this.router.navigateByUrl(path);
554
+ return navigated
555
+ ? { status: 'loaded', changed: draft.document.charts.length }
556
+ : { status: 'declined' };
557
+ }
558
+ finally {
559
+ if (!navigated)
560
+ this.intent.take();
561
+ }
562
+ },
563
+ };
564
+ const unregisterContext = inject(FarisContextRegistry).register('faris-dashboard-list', () => ({ context: controlPanelContextPath(this.levelId()) }));
565
+ const unregisterTarget = inject(FarisDraftTargets).register(target);
566
+ const release = inject(FarisPageActions).watch();
567
+ inject(DestroyRef).onDestroy(() => {
568
+ unregisterContext();
569
+ unregisterTarget();
570
+ release();
571
+ });
572
+ }
573
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: FarisDashboardListDrafts, deps: [], target: i0.ɵɵFactoryTarget.Directive });
574
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.2.8", type: FarisDashboardListDrafts, isStandalone: true, selector: "mt-dashboard-list[mtFarisDrafts]", ngImport: i0 });
575
+ }
576
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: FarisDashboardListDrafts, decorators: [{
577
+ type: Directive,
578
+ args: [{
579
+ selector: 'mt-dashboard-list[mtFarisDrafts]',
580
+ }]
581
+ }], ctorParameters: () => [] });
582
+
583
+ /**
584
+ * Generated bundle index. Do not edit.
585
+ */
586
+
587
+ export { FarisDashboardAssist, FarisDashboardDrafts, FarisDashboardIntent, FarisDashboardListDrafts, FarisWidgetPaletteTile };
588
+ //# sourceMappingURL=masterteam-dashboard-builder-faris.mjs.map