UNPKG

vue-persistent-storage-manager

Version:

Vue plugin that wraps the StorageManager API and provides the state of the persistent-storage permission alongside a storage estimate.

71 lines (70 loc) 2.42 kB
import a from "vue"; const i = { watchStorage: !1 }; class o { /** * Indicates that the StorageManager API is available. */ isAvailable = typeof navigator < "u" && navigator?.storage?.persist !== void 0; /** * Contains storage quota and usage information. */ storageEstimate = {}; _isPersistent = !1; /** * Installs a VuePersistentStorageManager as a Vue plugin. */ static install = (e, s) => { const r = { ...i, ...s }, t = a.observable(new o()); r.watchStorage && t._modifyLocalStorageFunctions(), e.prototype.$storageManager = t, e.prototype.$storageEstimate = t.storageEstimate; }; /** * Creates a new VuePersistentStorageManager instance. */ constructor() { this.isAvailable && (this._refreshIsPersistent(), this._refreshStorageEstimate(), navigator.permissions?.query({ name: "persistent-storage" })?.then((e) => { e.onchange = () => this._refreshIsPersistent(); }), window.addEventListener("storage", () => { this._refreshStorageEstimate(); })); } /** * Indicates that persistence of localStorage has been granted. */ get isPersistent() { return this._isPersistent; } /** * Requests persistence of localStorage. * @returns a Promise that resolves to true if permission has been granted. */ requestPersistentStorage() { return this.isAvailable ? navigator.storage.persist().then((e) => (this._isPersistent = e, e)) : Promise.resolve(!1); } _refreshIsPersistent() { navigator.storage.persisted().then((e) => this._isPersistent = e); } _refreshStorageEstimate() { navigator.storage.estimate().then(({ quota: e, usage: s }) => { a.set(this.storageEstimate, "quota", e), a.set(this.storageEstimate, "usage", s); }); } _modifyLocalStorageFunctions() { if (typeof localStorage > "u") return; const e = this; typeof localStorage.originalSetItem > "u" && (localStorage.originalSetItem = localStorage.setItem); const s = localStorage.setItem; localStorage.setItem = function(...t) { s.apply(this, t), e._refreshStorageEstimate(); }, typeof localStorage.originalRemoveItem > "u" && (localStorage.originalRemoveItem = localStorage.removeItem); const r = localStorage.removeItem; localStorage.removeItem = function(...t) { r.apply(this, t), e._refreshStorageEstimate(); }; } } export { o as VuePersistentStorageManager };