@uifabric/utilities
Version:
Fluent UI React utilities for building components.
86 lines • 3.24 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
var getWindow_1 = require("./dom/getWindow");
/**
* Storing global state in local module variables has issues when more than one copy
* if the module gets loaded on the page (due to a bundling error or simply by consuming
* a prebundled script.)
*
* This file contains helpers to deal with the getting and setting local state, and allows
* callers to get called back when it mutates.
*/
var GLOBAL_SETTINGS_PROP_NAME = '__globalSettings__';
var CALLBACK_STATE_PROP_NAME = '__callbacks__';
var _counter = 0;
/**
* Global settings helper, which stores settings in the global (window) namespace.
* If window is not provided, it will store settings in module scope. Provides a
* way to observe changes as well when their values change.
*
* @public
* {@docCategory GlobalSettings}
*/
var GlobalSettings = /** @class */ (function () {
function GlobalSettings() {
}
GlobalSettings.getValue = function (key, defaultValue) {
var globalSettings = _getGlobalSettings();
if (globalSettings[key] === undefined) {
globalSettings[key] = typeof defaultValue === 'function' ? defaultValue() : defaultValue;
}
return globalSettings[key];
};
GlobalSettings.setValue = function (key, value) {
var globalSettings = _getGlobalSettings();
var callbacks = globalSettings[CALLBACK_STATE_PROP_NAME];
var oldValue = globalSettings[key];
if (value !== oldValue) {
globalSettings[key] = value;
var changeDescription = {
oldValue: oldValue,
value: value,
key: key,
};
for (var id in callbacks) {
if (callbacks.hasOwnProperty(id)) {
callbacks[id](changeDescription);
}
}
}
return value;
};
GlobalSettings.addChangeListener = function (cb) {
// Note: we use generated ids on the callbacks to create a map of the callbacks, which optimizes removal.
// (It's faster to delete a key than it is to look up the index of an object and splice an array.)
var id = cb.__id__;
var callbacks = _getCallbacks();
if (!id) {
id = cb.__id__ = String(_counter++);
}
callbacks[id] = cb;
};
GlobalSettings.removeChangeListener = function (cb) {
var callbacks = _getCallbacks();
delete callbacks[cb.__id__];
};
return GlobalSettings;
}());
exports.GlobalSettings = GlobalSettings;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function _getGlobalSettings() {
var _a;
var win = getWindow_1.getWindow();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var globalObj = win || {};
if (!globalObj[GLOBAL_SETTINGS_PROP_NAME]) {
globalObj[GLOBAL_SETTINGS_PROP_NAME] = (_a = {},
_a[CALLBACK_STATE_PROP_NAME] = {},
_a);
}
return globalObj[GLOBAL_SETTINGS_PROP_NAME];
}
function _getCallbacks() {
var globalSettings = _getGlobalSettings();
return globalSettings[CALLBACK_STATE_PROP_NAME];
}
//# sourceMappingURL=GlobalSettings.js.map
;