From f63ea6c8e3cad079f2c417fd36123f56e40185e0 Mon Sep 17 00:00:00 2001 From: Dariusz Szut Date: Fri, 6 Dec 2024 13:42:21 +0100 Subject: [PATCH] IBX-8445: Added storage class (#1391) --- .../Resources/encore/ibexa.js.config.js | 1 + .../public/js/scripts/core/storage.js | 45 +++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 src/bundle/Resources/public/js/scripts/core/storage.js diff --git a/src/bundle/Resources/encore/ibexa.js.config.js b/src/bundle/Resources/encore/ibexa.js.config.js index c63cfcd0d0..25a21db5cf 100644 --- a/src/bundle/Resources/encore/ibexa.js.config.js +++ b/src/bundle/Resources/encore/ibexa.js.config.js @@ -24,6 +24,7 @@ const layout = [ path.resolve(__dirname, '../public/js/scripts/core/date.time.picker.js'), path.resolve(__dirname, '../public/js/scripts/core/taggify.js'), path.resolve(__dirname, '../public/js/scripts/core/suggestion.taggify.js'), + path.resolve(__dirname, '../public/js/scripts/core/storage.js'), path.resolve(__dirname, '../public/js/scripts/adaptive.filters.js'), path.resolve(__dirname, '../public/js/scripts/admin.notifications.js'), path.resolve(__dirname, '../public/js/scripts/button.trigger.js'), diff --git a/src/bundle/Resources/public/js/scripts/core/storage.js b/src/bundle/Resources/public/js/scripts/core/storage.js new file mode 100644 index 0000000000..6709b1f5c2 --- /dev/null +++ b/src/bundle/Resources/public/js/scripts/core/storage.js @@ -0,0 +1,45 @@ +(function (global, doc, ibexa) { + class IbexaStorage { + constructor(config) { + const keySuffix = config.isUserAware ? `:${ibexa.helpers.user.getId()}` : ''; + + this.key = `${config.key}${keySuffix}`; + this.eventName = config.eventName; + } + + setItem(data) { + const stringifiedData = JSON.stringify(data); + + global.localStorage.setItem(this.key, stringifiedData); + + this.fireStorageChangeEvent(stringifiedData); + } + + getItem() { + return JSON.parse(global.localStorage.getItem(this.key)); + } + + fireStorageChangeEvent(data) { + if (this.eventName) { + const storageChangeEvent = new CustomEvent(this.eventName, { + cancelable: true, + detail: { content: JSON.parse(data) }, + }); + + doc.body.dispatchEvent(storageChangeEvent); + } + } + + init() { + if (this.eventName) { + global.addEventListener('storage', (event) => { + if (event.key === this.key) { + this.fireStorageChangeEvent(event.newValue); + } + }); + } + } + } + + ibexa.addConfig('core.Storage', IbexaStorage); +})(window, window.document, window.ibexa);