UNPKG

3.14 kBJavaScriptView Raw
1import { getWindow } from './dom/getWindow';
2/**
3 * Storing global state in local module variables has issues when more than one copy
4 * if the module gets loaded on the page (due to a bundling error or simply by consuming
5 * a prebundled script.)
6 *
7 * This file contains helpers to deal with the getting and setting local state, and allows
8 * callers to get called back when it mutates.
9 */
10var GLOBAL_SETTINGS_PROP_NAME = '__globalSettings__';
11var CALLBACK_STATE_PROP_NAME = '__callbacks__';
12var _counter = 0;
13/**
14 * Global settings helper, which stores settings in the global (window) namespace.
15 * If window is not provided, it will store settings in module scope. Provides a
16 * way to observe changes as well when their values change.
17 *
18 * @public
19 * {@docCategory GlobalSettings}
20 */
21var GlobalSettings = /** @class */ (function () {
22 function GlobalSettings() {
23 }
24 GlobalSettings.getValue = function (key, defaultValue) {
25 var globalSettings = _getGlobalSettings();
26 if (globalSettings[key] === undefined) {
27 globalSettings[key] = typeof defaultValue === 'function' ? defaultValue() : defaultValue;
28 }
29 return globalSettings[key];
30 };
31 GlobalSettings.setValue = function (key, value) {
32 var globalSettings = _getGlobalSettings();
33 var callbacks = globalSettings[CALLBACK_STATE_PROP_NAME];
34 var oldValue = globalSettings[key];
35 if (value !== oldValue) {
36 globalSettings[key] = value;
37 var changeDescription = {
38 oldValue: oldValue,
39 value: value,
40 key: key,
41 };
42 for (var id in callbacks) {
43 if (callbacks.hasOwnProperty(id)) {
44 callbacks[id](changeDescription);
45 }
46 }
47 }
48 return value;
49 };
50 GlobalSettings.addChangeListener = function (cb) {
51 // Note: we use generated ids on the callbacks to create a map of the callbacks, which optimizes removal.
52 // (It's faster to delete a key than it is to look up the index of an object and splice an array.)
53 var id = cb.__id__;
54 var callbacks = _getCallbacks();
55 if (!id) {
56 id = cb.__id__ = String(_counter++);
57 }
58 callbacks[id] = cb;
59 };
60 GlobalSettings.removeChangeListener = function (cb) {
61 var callbacks = _getCallbacks();
62 delete callbacks[cb.__id__];
63 };
64 return GlobalSettings;
65}());
66export { GlobalSettings };
67// eslint-disable-next-line @typescript-eslint/no-explicit-any
68function _getGlobalSettings() {
69 var _a;
70 var win = getWindow();
71 // eslint-disable-next-line @typescript-eslint/no-explicit-any
72 var globalObj = win || {};
73 if (!globalObj[GLOBAL_SETTINGS_PROP_NAME]) {
74 globalObj[GLOBAL_SETTINGS_PROP_NAME] = (_a = {},
75 _a[CALLBACK_STATE_PROP_NAME] = {},
76 _a);
77 }
78 return globalObj[GLOBAL_SETTINGS_PROP_NAME];
79}
80function _getCallbacks() {
81 var globalSettings = _getGlobalSettings();
82 return globalSettings[CALLBACK_STATE_PROP_NAME];
83}
84//# sourceMappingURL=GlobalSettings.js.map
\No newline at end of file