Repository navigation
Expand file tree
/
Copy pathsettings.service.ts
More file actions
478 lines (429 loc) · 16.2 KB
/
Copy pathsettings.service.ts
File metadata and controls
478 lines (429 loc) · 16.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
import {
Injectable,
type Signal,
type WritableSignal,
computed,
inject,
signal,
} from '@angular/core';
import { Title } from '@angular/platform-browser';
import { showMetadata, updateMetadata, updateUser } from '@placeos/ts-client';
import { format, isSameDay } from 'date-fns';
import { AsyncHandler } from './async-handler.class';
import { SETTING_KEYS } from './constants';
import { getItemWithKeys, log, setAppName } from './general';
import { DEFAULT_SETTINGS } from './settings';
import { ApplicationIcon, HashMap } from './types';
import { GoogleAnalyticsService } from './google-analytics.service';
import { currentUser, reloadUserData } from './user-state';
import { VERSION } from './version';
declare global {
interface Window {
debug: boolean;
app: HashMap;
setting: (string) => unknown;
}
}
let _service: SettingsService;
const _setting_signals: Record<string, WritableSignal<any>> = {};
/**
* Debug overrides for all apps on this origin. Each app also has its own key,
* `<key>.<app>`, which takes priority. The debug panel writes the app key.
*/
const DEBUG_OVERRIDES_KEY = 'PLACEOS.setting_overrides';
/** Renamed user setting keys, as old key to new key */
const LEGACY_USER_SETTING_KEYS: Record<string, string> = {
favourite_spaces: SETTING_KEYS.FAVORITE_ROOMS,
favourite_parking_spaces: SETTING_KEYS.FAVORITE_PARKING_SPACES,
};
/** CSS rule that sets each entry of the map as a CSS variable */
function cssVariableRule(selector: string, variables: HashMap = {}) {
let rule = `${selector} { `;
for (const key in variables) {
rule += `--${key}: ${variables[key]}; `;
}
return `${rule}}`;
}
/** Use the value of a renamed user setting until the new key has a value */
function withLegacyUserSettings(details: HashMap): HashMap {
const result = { ...details };
for (const [old_key, key] of Object.entries(LEGACY_USER_SETTING_KEYS)) {
result[key] ??= details[old_key];
}
return result;
}
/**
* Local storage key for this app's debug overrides. Uses the same path based
* name as the app name, as settings are not loaded yet when overrides load.
*/
function appDebugOverridesKey() {
const app = location.pathname.replace(/[\\/]/g, '').trim() || 'PlaceOS';
return `${DEBUG_OVERRIDES_KEY}.${app}`;
}
/** Read a stored override map, keeping only `app.*` keys */
function readDebugOverrides(storage_key: string): HashMap {
try {
const overrides = JSON.parse(localStorage.getItem(storage_key) || '{}');
for (const key in overrides) {
if (!key.startsWith('app.')) delete overrides[key];
}
return overrides;
} catch {
return {};
}
}
/** Write an override map, or remove the key when the map is empty */
function writeDebugOverrides(storage_key: string, overrides: HashMap) {
if (Object.keys(overrides).length) {
localStorage.setItem(storage_key, JSON.stringify(overrides));
} else localStorage.removeItem(storage_key);
}
export function setting<T = any>(key: string): T | undefined {
return _service ? _service.get(key) : undefined;
}
/** Name and version of the running app, as stored on saved bookings and events */
export function appDetails() {
return {
app_name:
setting<string>('app.name') ||
setting<string>('app.short_name') ||
'PlaceOS',
app_version: VERSION.raw || VERSION.version || VERSION.hash,
};
}
export function settingSignal<T = any>(
key: string,
default_value: T = undefined,
root = false,
): WritableSignal<T | undefined> {
const full_key = root ? key : `app.${key}`;
if (!_setting_signals[full_key]) {
_setting_signals[full_key] = signal<T>(
setting(full_key) ?? default_value,
);
}
return _setting_signals[full_key];
}
/** Active theme. `'light'` unless the app allows dark mode. */
const active_theme = computed<string>(() =>
settingSignal('allow_dark_mode', false)()
? settingSignal('theme', 'light', true)()
: 'light',
);
const themed_logo = computed(() => {
const logo = settingSignal<string | ApplicationIcon>(
active_theme() === 'dark' ? 'logo_dark' : 'logo_light',
)();
return typeof logo === 'string' ? logo : logo?.src || '';
});
/**
* Image URL of the app logo (`app.logo_dark` or `app.logo_light`) for the
* active theme. Updates when the theme or the logo settings change.
*/
export function themedLogo(): Signal<string> {
return themed_logo;
}
@Injectable({
providedIn: 'root',
})
export class SettingsService extends AsyncHandler {
private _title = inject(Title);
private _analytics = inject(GoogleAnalyticsService, { optional: true });
/** Name of the application */
private _app_name = 'PlaceOS';
/** List of override settings in order of priority */
private _overrides = signal<HashMap[]>([]);
/** Signal that emits when overrides change (e.g. after a building switch) */
public readonly overrides = this._overrides.asReadonly();
/** User's personal settings */
private _user_settings = signal<HashMap>({});
/** Debug overrides for this app only */
private _app_debug_overrides = readDebugOverrides(appDebugOverridesKey());
/** Local debug overrides, highest priority. Flat dot-notation keys. */
private _debug_overrides = signal<HashMap>({
...readDebugOverrides(DEBUG_OVERRIDES_KEY),
...this._app_debug_overrides,
});
public readonly debug_overrides = this._debug_overrides.asReadonly();
/** Mapping of setting signals */
private _subjects: HashMap<WritableSignal<any>> = {};
/** Mapping of pending settings */
private _pending_settings: HashMap = {};
/**
* @hidden
*/
public setOverrides(value: HashMap[]) {
this._overrides.set(value);
this._refreshSettings();
}
/** Set a local debug override for an `app.*` setting. `undefined` clears the key. */
/**
* Set a local debug override for an `app.*` setting in this app only.
* `undefined` clears the key, also from the overrides for all apps.
*/
public setDebugOverride(key: string, value: unknown) {
if (!key.startsWith('app.')) return;
const app_overrides = { ...this._app_debug_overrides };
const shared = readDebugOverrides(DEBUG_OVERRIDES_KEY);
if (value === undefined) {
delete app_overrides[key];
delete shared[key];
writeDebugOverrides(DEBUG_OVERRIDES_KEY, shared);
} else app_overrides[key] = value;
this._app_debug_overrides = app_overrides;
writeDebugOverrides(appDebugOverridesKey(), app_overrides);
this._debug_overrides.set({ ...shared, ...app_overrides });
this._refreshSettings();
}
/** Remove the debug overrides for this app and for all apps */
public clearDebugOverrides() {
this._app_debug_overrides = {};
this._debug_overrides.set({});
localStorage.removeItem(DEBUG_OVERRIDES_KEY);
localStorage.removeItem(appDebugOverridesKey());
this._refreshSettings();
}
private _refreshSettings() {
this._applyCssVariables();
this._updateSignals();
this._applyTheme();
this._setFontSize();
this._setPrintFontSize();
}
public get theme() {
const allow_dark_mode = this.get('app.allow_dark_mode');
return allow_dark_mode ? this.get('theme') : 'light';
}
/** Active theme. Unset `allow_dark_mode` means light, matching `theme` and `_applyTheme`. */
public readonly theme_signal = active_theme;
public readonly time_format_signal = computed(() =>
this.signal('use_24_hour_time', false)() ? 'HH:mm' : 'h:mm a',
);
/** Get signal for key */
public listen<T = any>(name: string): WritableSignal<T> {
if (!this._subjects[name]) this._subjects[name] = signal<T>(null);
return this._subjects[name];
}
/** Update observable value for key */
public post<T>(name: string, value: T): void {
if (!this._subjects[name]) this._subjects[name] = signal<T>(null);
this._subjects[name].set(value);
}
public value<T = any>(name: string): T {
return !this._subjects[name] ? null : this._subjects[name]();
}
public signal<T = any>(
name: string,
default_value?: T,
root?: boolean,
): WritableSignal<T> {
return settingSignal<T>(name, default_value, root);
}
/** Page title */
public get title() {
return this._title.getTitle();
}
public set title(value: string) {
this._title.setTitle(
`${value} | ${this.get('app.name') || this._app_name}`,
);
const tracking_id = this.get('app.analytics.tracking_id');
if (!tracking_id || this.get('app.analytics.enabled') === false) return;
this._analytics?.send('pagename', { title: value });
}
constructor() {
super();
// Register early so setting signals created before init completes
// read current overrides instead of their default values.
_service = this;
const now = new Date();
const time = new Date(VERSION.time);
const built = isSameDay(now, time)
? `Today at ${format(time, 'h:mma')}`
: format(time, 'do MMM yyyy, h:mma');
log('CORE', `${VERSION.semver}`, null, 'debug', true);
log('APP', `${VERSION.hash} | Built: ${built}`, null, 'debug', true);
this.init();
}
/**
* Initialise the settings
*/
public async init() {
if (this.get('debug')) window.debug = true;
if (this.get('app')?.name) {
this._app_name = this.get('app').name;
}
this._app_name =
location.pathname.replace(/[\\/]/g, '').trim() || this._app_name;
setAppName(this._app_name.split('-').join('_').toUpperCase());
log('Settings', 'Successfully loaded settings');
this._initialised.next(true);
if (window.debug) {
if (!window.app) window.app = {};
window.app.settings = this;
window.setting = (key) => this.get(key);
}
const user = await this._currentUser();
const data = await showMetadata(user.id, 'settings');
this._user_settings.set(withLegacyUserSettings(data.details || {}));
this._updateSignals();
this.timeout(
'init',
() => {
this._initDarkMode();
this._applyTheme();
this._setFontSize();
this._setPrintFontSize();
},
1000,
);
}
/** Whether settings service has initialised */
public get app_name() {
return this._app_name.replace(/ /g, '-');
}
public get time_format(): string {
return this.get('app.use_24_hour_time') ? 'HH:mm' : 'h:mm a';
}
/**
* Get a setting
* @param key Name of the setting. i.e. nested items can be grabbed using `.` to seperate key names
*/
public get<T = any>(key: string): T {
const debug_overrides = this._debug_overrides();
// ponytail: exact-key match only — override `app.a` won't affect get('app.a.b')
if (key in debug_overrides) return debug_overrides[key];
const keys = key.split('.');
if (keys[0] !== 'app') {
return (
getItemWithKeys(keys, this._pending_settings) ??
getItemWithKeys(keys, this._user_settings()) ??
getItemWithKeys(keys, DEFAULT_SETTINGS)
);
}
const override_settings = [...this._overrides()];
for (const override of override_settings) {
const value = getItemWithKeys(keys.slice(1), override);
if (value != null) {
return value;
}
}
return getItemWithKeys(keys, DEFAULT_SETTINGS);
}
public saveUserSetting<T>(name: string, value: T) {
this._pending_settings[name] = value;
this._updateSignals();
if (name === 'dark_mode') this.setTheme(value ? 'dark' : '');
if (name === 'font_size') this._setFontSize();
this.timeout('save_settings', () => this._savePendingChanges(), 2400);
}
public async updateLocatable(locatable: boolean) {
await updateUser(currentUser().id, { locatable }, 'patch');
reloadUserData();
}
public overrideCssVariable(key: string, value: string, important = false) {
let element = document.getElementById(`css-var-overrides+${key}`);
if (!element) {
element = document.createElement('style');
element.id = `css-var-overrides+${key}`;
document.head.appendChild(element);
}
element.innerText = `html, body { --${key}: ${value} ${
important ? '!important' : ''
}}`;
}
public setTheme(theme: string) {
const current_theme = this.theme;
if (current_theme === theme) return;
this.saveUserSetting('theme', theme);
this._applyTheme();
}
/**
* Apply the colour overrides from `app.css_variables` and, for the dark
* theme, from `app.css_variables_dark`. The dark rule has the theme class,
* so it wins over the `.theme-dark` defaults of the stylesheet.
*/
private _applyCssVariables() {
const css_string = [
cssVariableRule('body', this.get('app.css_variables') || {}),
cssVariableRule(
'body.theme-dark',
this.get('app.css_variables_dark') || {},
),
].join(' ');
let element = document.getElementById('css-var-overrides');
if (!element) {
element = document.createElement('style');
element.id = 'css-var-overrides';
document.head.appendChild(element);
}
element.innerText = css_string;
}
private async _savePendingChanges() {
const user = currentUser();
if (!user?.id || !Object.keys(this._pending_settings).length) return;
this._updateSignals();
await updateMetadata(user.id, {
name: 'settings',
description: '',
details: {
...this._user_settings(),
...this._pending_settings,
},
});
this._user_settings.set({
...this._user_settings(),
...this._pending_settings,
});
this._pending_settings = {};
}
private _setFontSize() {
if (!this.get('font_size')) return;
this.overrideCssVariable('font-size', `${this.get('font_size')}px`);
}
private _applyTheme() {
const allow_dark_mode = this.get('app.allow_dark_mode');
this._clearTheme();
if (!allow_dark_mode) return;
document.body.classList.add(`theme-${this.theme}`);
}
private _clearTheme() {
const class_list = document.body.classList.value.split(' ');
for (const item of class_list) {
if (item.startsWith('theme-')) {
document.body.classList.remove(item);
}
}
}
private _setPrintFontSize() {
let print_style_el = document.getElementById('placeos-print-block');
if (!print_style_el) {
print_style_el = document.createElement('style');
print_style_el.id = 'placeos-print-block';
document.head.appendChild(print_style_el);
}
print_style_el.innerText = `@media print { html, body { font-size: ${this.get('app.print_font_size') || '4mm'}; } }`;
}
private _initDarkMode() {
if (this.theme) return;
const os_dark = window?.matchMedia
? window?.matchMedia('(prefers-color-scheme: dark)')?.matches
: false;
this.setTheme(os_dark ? 'dark' : '');
}
private _updateSignals() {
for (const key in _setting_signals) {
_setting_signals[key].update((old) => this.get(key) ?? old);
}
}
private _currentUser() {
return new Promise<ReturnType<typeof currentUser>>((resolve) => {
const check = () => {
const user = currentUser();
if (user?.id) return resolve(user);
this.timeout('current_user', check, 100);
};
check();
});
}
}