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.

77 lines (76 loc) 2.8 kB
var m = Object.defineProperty; var f = (r, e, t) => e in r ? m(r, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : r[e] = t; var a = (r, e, t) => f(r, typeof e != "symbol" ? e + "" : e, t); import n from "vue"; const c = { watchStorage: !1 }; var g; const i = class i { /** * Creates a new VuePersistentStorageManager instance. */ constructor() { /** * Indicates that the StorageManager API is available. */ a(this, "isAvailable", typeof navigator < "u" && ((g = navigator == null ? void 0 : navigator.storage) == null ? void 0 : g.persist) !== void 0); /** * Contains storage quota and usage information. */ a(this, "storageEstimate", {}); a(this, "_isPersistent", !1); var e, t; this.isAvailable && (this._refreshIsPersistent(), this._refreshStorageEstimate(), (t = (e = navigator.permissions) == null ? void 0 : e.query({ name: "persistent-storage" })) == null || t.then((o) => { o.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: t }) => { n.set(this.storageEstimate, "quota", e), n.set(this.storageEstimate, "usage", t); }); } _modifyLocalStorageFunctions() { if (typeof localStorage > "u") return; const e = this; typeof localStorage.originalSetItem > "u" && (localStorage.originalSetItem = localStorage.setItem); const t = localStorage.setItem; localStorage.setItem = function(...s) { t.apply(this, s), e._refreshStorageEstimate(); }, typeof localStorage.originalRemoveItem > "u" && (localStorage.originalRemoveItem = localStorage.removeItem); const o = localStorage.removeItem; localStorage.removeItem = function(...s) { o.apply(this, s), e._refreshStorageEstimate(); }; } }; /** * Installs a VuePersistentStorageManager as a Vue plugin. */ a(i, "install", (e, t) => { const o = { ...c, ...t }, s = n.observable(new i()); o.watchStorage && s._modifyLocalStorageFunctions(), e.prototype.$storageManager = s, e.prototype.$storageEstimate = s.storageEstimate; }); let l = i; export { l as VuePersistentStorageManager };