From 1e35032fd924f5faedc89132653b4a837154aed9 Mon Sep 17 00:00:00 2001 From: Dariusz Szut Date: Fri, 8 Nov 2024 15:45:10 +0100 Subject: [PATCH] IBX-8445: Added storage class --- .../Resources/encore/ibexa.js.config.js | 1 + .../public/js/scripts/core/storage.js | 57 +++++++++++++++++++ 2 files changed, 58 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 0e715c8ce7..076286c1fd 100644 --- a/src/bundle/Resources/encore/ibexa.js.config.js +++ b/src/bundle/Resources/encore/ibexa.js.config.js @@ -22,6 +22,7 @@ const layout = [ path.resolve(__dirname, '../public/js/scripts/core/toggle.button.js'), path.resolve(__dirname, '../public/js/scripts/core/slug.value.input.autogenerator.js'), path.resolve(__dirname, '../public/js/scripts/core/date.time.picker.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..6bab575c0a --- /dev/null +++ b/src/bundle/Resources/public/js/scripts/core/storage.js @@ -0,0 +1,57 @@ +(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; + } + + stringfyData(data) { + try { + return JSON.stringify(data); + } catch (error) { + console.warn('Error stringifying data', error); + } + } + + parseData(data) { + try { + return JSON.parse(data); + } catch (error) { + return null; + } + } + + setItem(data) { + const stringifiedData = this.stringfyData(data); + + window.localStorage.setItem(this.key, stringifiedData); + + this.fireStorageChangeEvent(stringifiedData); + } + + getItem() { + return this.parseData(window.localStorage.getItem(this.key)); + } + + fireStorageChangeEvent(data) { + if (this.eventName) { + const storageChangeEvent = new CustomEvent(this.eventName, { + cancelable: true, + detail: { content: this.parseData(data) }, + }); + + document.body.dispatchEvent(storageChangeEvent); + } + } + + init() { + if (this.eventName) { + window.addEventListener('storage', (event) => this.fireStorageChangeEvent(event.newValue)); + } + } + } + + ibexa.addConfig('core.Storage', IbexaStorage); +})(window, window.document, window.ibexa);