Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

refactor: remove vue dependency (#20514)

ecmadao07efcf2a60d6
diff --git a/frontend/src/react/app/mount.ts b/frontend/src/react/app/mount.ts
index 42e0533c48..e6729c6ece 100644
--- a/frontend/src/react/app/mount.ts
+++ b/frontend/src/react/app/mount.ts
@@ -1,5 +1,3 @@
-import { watch } from "vue";
-import { locale } from "@/plugins/i18n";
import { buildTree, loadCoreDeps, type ReactComponent } from "@/react/mount";
// import.meta.glob keeps vue-tsc from following into the .tsx file. Vite
@@ -25,20 +23,8 @@ export async function mountReactApp(selector: string) {
const [deps, ReactApp] = await Promise.all([loadCoreDeps(), loadReactApp()]);
- // Sync initial locale before first paint.
- if (deps.i18n.language !== locale.value) {
- await deps.i18n.changeLanguage(locale.value);
- }
-
const root = deps.createRoot(container);
root.render(buildTree(deps, ReactApp));
- // Ongoing Vue→React locale sync for the long-lived React app.
- watch(locale, async (next) => {
- if (deps.i18n.language !== next) {
- await deps.i18n.changeLanguage(next);
- }
- });
-
return root;
}
diff --git a/frontend/src/store/cache.ts b/frontend/src/store/cache.ts
deleted file mode 100644
index c94a124d74..0000000000
--- a/frontend/src/store/cache.ts
+++ /dev/null
@@ -1,191 +0,0 @@
-import { shallowReactive } from "vue";
-
-export type KeyType = string | number | boolean;
-
-type RequestCacheEntry<K extends KeyType[], T> = {
- keys: K;
- promise: Promise<T>;
- abortController: AbortController;
-};
-type EntityCacheEntry<K extends KeyType[], T> = {
- keys: K;
- entity: T;
-};
-const REQUEST_CACHE = new Map<
- string,
- Map<string, RequestCacheEntry<KeyType[], unknown>>
->();
-const ENTITY_CACHE = new Map<
- string,
- Map<string, EntityCacheEntry<KeyType[], unknown>>
->();
-
-type NamespaceSubscription = {
- version: number;
- listeners: Set<() => void>;
-};
-const SUBSCRIPTIONS = new Map<string, NamespaceSubscription>();
-
-const getSubscription = (namespace: string): NamespaceSubscription => {
- let sub = SUBSCRIPTIONS.get(namespace);
- if (!sub) {
- sub = { version: 0, listeners: new Set() };
- SUBSCRIPTIONS.set(namespace, sub);
- }
- return sub;
-};
-
-const notify = (namespace: string) => {
- const sub = getSubscription(namespace);
- sub.version++;
- for (const listener of sub.listeners) {
- listener();
- }
-};
-
-export const useCache = <K extends KeyType[], T>(namespace: string) => {
- const requestCacheMap = getRequestCacheMap<K, T>(namespace);
- const entityCacheMap = getEntityCacheMap<K, T>(namespace);
-
- const trace = (title: string, keys: KeyType[], ...args: unknown[]) => {
- console.debug("cache", namespace, title, JSON.stringify(keys), ...args);
- };
-
- const invalidateRequest = (keys: K) => {
- const key = getKey(keys);
- const request = requestCacheMap.get(key);
- if (!request) return;
- if (!request.abortController.signal.aborted) {
- request.abortController.abort();
- }
- requestCacheMap.delete(key);
- };
-
- const getRequest = (keys: K) => {
- const key = getKey(keys);
- trace("getRequest", keys, requestCacheMap.has(key));
- const request = requestCacheMap.get(key);
- if (!request) {
- return undefined;
- }
- if (request.abortController.signal.aborted) {
- invalidateRequest(keys);
- return undefined;
- }
- return request.promise;
- };
-
- const setRequest = (keys: K, promise: Promise<T>) => {
- invalidateRequest(keys);
-
- const key = getKey(keys);
- const abortController = new AbortController();
- promise
- .then((entity: T) => {
- if (!abortController.signal.aborted) {
- setEntity(keys, entity);
- }
- })
- .catch(() => undefined)
- .finally(() => {
- invalidateRequest(keys);
- });
- requestCacheMap.set(key, {
- keys,
- promise,
- abortController,
- });
- };
-
- const getEntity = (keys: K) => {
- const key = getKey(keys);
- return entityCacheMap.get(key)?.entity;
- };
-
- const setEntity = (keys: K, entity: T) => {
- const key = getKey(keys);
- entityCacheMap.set(key, {
- keys,
- entity,
- });
- notify(namespace);
- };
-
- const invalidateEntity = (keys: K) => {
- invalidateRequest(keys);
- const key = getKey(keys);
- const existed = entityCacheMap.delete(key);
- if (existed) {
- notify(namespace);
- }
- };
-
- const clear = () => {
- for (const request of requestCacheMap.values()) {
- if (!request.abortController.signal.aborted) {
- request.abortController.abort();
- }
- }
- const hadEntities = entityCacheMap.size > 0;
- requestCacheMap.clear();
- entityCacheMap.clear();
- if (hadEntities) {
- notify(namespace);
- }
- };
-
- const subscribe = (listener: () => void) => {
- const sub = getSubscription(namespace);
- sub.listeners.add(listener);
- return () => {
- sub.listeners.delete(listener);
- };
- };
-
- const getVersion = () => getSubscription(namespace).version;
-
- return {
- requestCacheMap,
- entityCacheMap,
- getRequest,
- getEntity,
- setRequest,
- setEntity,
- invalidateRequest,
- invalidateEntity,
- clear,
- subscribe,
- getVersion,
- };
-};
-
-const getRequestCacheMap = <K extends KeyType[], T>(namespace: string) => {
- const existed = REQUEST_CACHE.get(namespace) as Map<
- string,
- RequestCacheEntry<K, T>
- >;
- if (existed) {
- return existed;
- }
- const created = new Map<string, RequestCacheEntry<K, T>>();
- REQUEST_CACHE.set(namespace, created);
- return created;
-};
-
-const getEntityCacheMap = <K extends KeyType[], T>(namespace: string) => {
- const existed = ENTITY_CACHE.get(namespace) as Map<
- string,
- EntityCacheEntry<K, T>
- >;
-
- if (existed) {
- return existed;
- }
- const created = shallowReactive(new Map<string, EntityCacheEntry<K, T>>());
- ENTITY_CACHE.set(namespace, created);
- return created;
-};
-
-const getKey = (keys: KeyType[]) => {
- return JSON.stringify(keys);
-};
diff --git a/frontend/src/store/index.ts b/frontend/src/store/index.ts
index ee7f6fa6a3..49d8f6a0e0 100644
--- a/frontend/src/store/index.ts
+++ b/frontend/src/store/index.ts
@@ -1,2 +1 @@
export * from "./modules";
-export * from "./cache";
diff --git a/frontend/src/store/modules/sqlEditor/legacy/migration.ts b/frontend/src/store/modules/sqlEditor/legacy/migration.ts
index 6b13adc511..7b09f3ece7 100644
--- a/frontend/src/store/modules/sqlEditor/legacy/migration.ts
+++ b/frontend/src/store/modules/sqlEditor/legacy/migration.ts
@@ -1,6 +1,5 @@
import { create } from "@bufbuild/protobuf";
import { isUndefined, omit, omitBy } from "lodash-es";
-import { computed, reactive } from "vue";
import { extractWorksheetConnection } from "@/react/lib/sqlEditorConnection";
import { useAppStore } from "@/react/stores/app";
import type { EditorPanelViewState, SQLEditorTab } from "@/types";
@@ -9,11 +8,7 @@ import {
Worksheet_Visibility,
WorksheetSchema,
} from "@/types/proto-es/v1/worksheet_service_pb";
-import {
- defaultSQLEditorTab,
- useDynamicLocalStorage,
- WebStorageHelper,
-} from "@/utils";
+import { defaultSQLEditorTab, WebStorageHelper } from "@/utils";
import { getCurrentUserV1 } from "../../migration-helpers";
import { extractUserEmail } from "../../v1";
import {
@@ -24,6 +19,40 @@ import {
const LOCAL_STORAGE_KEY_PREFIX = "bb.sql-editor-tab";
+// Plain localStorage access mirroring the serialization the legacy data was
+// written with by `useDynamicLocalStorage` (vueuse `useStorage`): plain JSON
+// for objects/arrays, and entries-array JSON for `Map`. `read` also persists
+// the default when the key is absent — matching vueuse's `writeDefaults`, which
+// `storage-migrate.ts` relies on running first.
+const isMap = (v: unknown): v is Map<unknown, unknown> => v instanceof Map;
+
+const serializeLegacy = (value: unknown): string =>
+ isMap(value) ? JSON.stringify([...value.entries()]) : JSON.stringify(value);
+
+const readLegacyStorage = <T>(key: string, defaults: T): T => {
+ const raw = localStorage.getItem(key);
+ if (raw == null) {
+ if (defaults != null) {
+ localStorage.setItem(key, serializeLegacy(defaults));
+ }
+ return defaults;
+ }
+ try {
+ const parsed = JSON.parse(raw);
+ return isMap(defaults) ? (new Map(parsed) as T) : (parsed as T);
+ } catch {
+ return defaults;
+ }
+};
+
+const writeLegacyStorage = <T>(key: string, value: T): void => {
+ if (value == null) {
+ localStorage.removeItem(key);
+ return;
+ }
+ localStorage.setItem(key, serializeLegacy(value));
+};
+
type PersistentTab = Pick<
SQLEditorTab,
"id" | "title" | "connection" | "mode" | "worksheet" | "status"
@@ -32,18 +61,17 @@ type PersistentTab = Pick<
type LegacyStoredTab = PersistentTab & { statement?: string };
export const migrateLegacyCache = async () => {
- const userUID = computed(() => extractUserEmail(getCurrentUserV1().name));
+ const userUID = extractUserEmail(getCurrentUserV1().name);
- const keyNamespace = computed(
- () => `${LOCAL_STORAGE_KEY_PREFIX}.${userUID.value}`
+ const keyNamespace = `${LOCAL_STORAGE_KEY_PREFIX}.${userUID}`;
+ const tabIdListKey = `${keyNamespace}.tab-id-list`;
+ const tabIdListMapByProject = readLegacyStorage<Record<string, string[]>>(
+ tabIdListKey,
+ {}
);
- const tabIdListKey = computed(() => `${keyNamespace.value}.tab-id-list`);
- const tabIdListMapByProject = useDynamicLocalStorage<
- Record<string, string[]>
- >(tabIdListKey, {});
const getStorage = () => {
- return new WebStorageHelper(keyNamespace.value);
+ return new WebStorageHelper(keyNamespace);
};
const keyForTab = (id: string) => {
@@ -58,13 +86,13 @@ export const migrateLegacyCache = async () => {
if (!stored) {
return undefined;
}
- const tab = reactive<SQLEditorTab>({
+ const tab: SQLEditorTab = {
...defaultSQLEditorTab(),
// Ignore extended fields stored in localStorage since they are migrated
// to extendedTabStore.
...omit(stored, EXTENDED_TAB_FIELDS),
id,
- });
+ };
if (tab.mode !== DEFAULT_SQL_EDITOR_TAB_MODE) {
// Do not enter ADMIN mode initially
tab.mode = DEFAULT_SQL_EDITOR_TAB_MODE;
@@ -86,19 +114,13 @@ export const migrateLegacyCache = async () => {
return tab;
};
- const entries = [...Object.entries(tabIdListMapByProject.value)];
+ const entries = [...Object.entries(tabIdListMapByProject)];
for (const [project, tabIds] of entries) {
- const draftTabList = useDynamicLocalStorage<SQLEditorTab[]>(
- computed(
- () =>
- `${LOCAL_STORAGE_KEY_PREFIX}.${project}.${userUID.value}.draft-tab-list`
- ),
- [],
- localStorage
- );
+ const draftTabListKey = `${LOCAL_STORAGE_KEY_PREFIX}.${project}.${userUID}.draft-tab-list`;
+ const draftTabList = readLegacyStorage<SQLEditorTab[]>(draftTabListKey, []);
for (const tabId of tabIds) {
- const exist = draftTabList.value.find((draft) => draft.id === tabId);
+ const exist = draftTabList.find((draft) => draft.id === tabId);
if (exist) {
continue;
}
@@ -107,43 +129,34 @@ export const migrateLegacyCache = async () => {
if (!tab) {
continue;
}
- draftTabList.value.push(tab);
+ draftTabList.push(tab);
}
+ writeLegacyStorage(draftTabListKey, draftTabList);
- delete tabIdListMapByProject.value[project];
+ delete tabIdListMapByProject[project];
+ writeLegacyStorage(tabIdListKey, tabIdListMapByProject);
}
};
export const migrateDraftsFromCache = async (project: string) => {
- const userUID = computed(() => extractUserEmail(getCurrentUserV1().name));
+ const userUID = extractUserEmail(getCurrentUserV1().name);
- const viewStateByTab = useDynamicLocalStorage<
+ const viewStateByTab = readLegacyStorage<
Map</* tab.id */ string, EditorPanelViewState>
- >(
- computed(() => `bb.sql-editor-tab-state.${userUID.value}`),
- new Map()
- );
+ >(`bb.sql-editor-tab-state.${userUID}`, new Map());
- const keyNamespace = computed(
- () => `${LOCAL_STORAGE_KEY_PREFIX}.${project}.${userUID.value}`
- );
+ const keyNamespace = `${LOCAL_STORAGE_KEY_PREFIX}.${project}.${userUID}`;
- const draftTabList = useDynamicLocalStorage<SQLEditorTab[]>(
- computed(() => `${keyNamespace.value}.draft-tab-list`),
- [],
- localStorage,
- {
- listenToStorageChanges: true,
- }
- );
+ const draftTabListKey = `${keyNamespace}.draft-tab-list`;
+ const draftTabList = readLegacyStorage<SQLEditorTab[]>(draftTabListKey, []);
- const drafts = [...draftTabList.value];
+ const drafts = [...draftTabList];
for (const draft of drafts) {
const tab = {
...defaultSQLEditorTab(),
...omitBy(draft, isUndefined),
};
- const viewState = viewStateByTab.value.get(tab.id);
+ const viewState = viewStateByTab.get(tab.id);
if ((!viewState || viewState.view === "CODE") && tab.statement) {
// only store the draft with content
try {
@@ -161,41 +174,37 @@ export const migrateDraftsFromCache = async (project: string) => {
);
} catch {}
}
- const index = draftTabList.value.findIndex((d) => d.id === draft.id);
+ const index = draftTabList.findIndex((d) => d.id === draft.id);
if (index >= 0) {
- draftTabList.value.splice(index, 1);
+ draftTabList.splice(index, 1);
+ writeLegacyStorage(draftTabListKey, draftTabList);
}
}
};
export const migrateTabViewState = (project: string) => {
- const userUID = computed(() => extractUserEmail(getCurrentUserV1().name));
+ const userUID = extractUserEmail(getCurrentUserV1().name);
- const keyNamespace = computed(
- () => `${LOCAL_STORAGE_KEY_PREFIX}.${project}.${userUID.value}`
- );
+ const keyNamespace = `${LOCAL_STORAGE_KEY_PREFIX}.${project}.${userUID}`;
- const viewStateByTab = useDynamicLocalStorage<
+ const viewStateKey = `bb.sql-editor-tab-state.${userUID}`;
+ const viewStateByTab = readLegacyStorage<
Map</* tab.id */ string, EditorPanelViewState>
- >(
- computed(() => `bb.sql-editor-tab-state.${userUID.value}`),
- new Map()
- );
+ >(viewStateKey, new Map());
- const openTmpTabList = useDynamicLocalStorage<PersistentTab[]>(
- computed(() => `${keyNamespace.value}.opening-tab-list`),
- [],
- localStorage,
- {
- listenToStorageChanges: false,
- }
+ const openTmpTabListKey = `${keyNamespace}.opening-tab-list`;
+ const openTmpTabList = readLegacyStorage<PersistentTab[]>(
+ openTmpTabListKey,
+ []
);
- for (const openedTab of openTmpTabList.value) {
- const viewState = viewStateByTab.value.get(openedTab.id);
+ for (const openedTab of openTmpTabList) {
+ const viewState = viewStateByTab.get(openedTab.id);
if (viewState) {
Object.assign(openedTab, { viewState });
}
- viewStateByTab.value.delete(openedTab.id);
+ viewStateByTab.delete(openedTab.id);
}
+ writeLegacyStorage(openTmpTabListKey, openTmpTabList);
+ writeLegacyStorage(viewStateKey, viewStateByTab);
};
diff --git a/frontend/src/store/modules/v1/cache.ts b/frontend/src/store/modules/v1/cache.ts
deleted file mode 100644
index b14a4454fa..0000000000
--- a/frontend/src/store/modules/v1/cache.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-import { reactive } from "vue";
-
-const ATTR_SEPARATOR = "-";
-
-const LIST_CACHE = new Map<
- // The cache name.
- string,
- Map<string, StoreListCache>
->();
-
-type StoreListCache = {
- // The timestamp when the cache was last updated.
- timestamp: number;
- // The flag indicating whether the cache is currently being fetched.
- isFetching: boolean;
-};
-
-export const useListCache = (namespace: string) => {
- const listCache = (() => {
- const cache = LIST_CACHE.get(namespace);
- if (cache) {
- return cache;
- }
- const newCache = reactive(new Map<string, StoreListCache>());
- LIST_CACHE.set(namespace, newCache);
- return newCache;
- })();
-
- const getCacheKey = (
- // Other attributes to include in the cache key, e.g. "active".
- ...attrs: string[]
- ) => {
- let key = namespace;
- for (const attr of attrs.filter(Boolean)) {
- key += `${ATTR_SEPARATOR}${attr}`;
- }
- return key;
- };
-
- const getCache = (key: string) => {
- const keyParts = key.split(ATTR_SEPARATOR);
- let cacheKey = "";
- for (const part of keyParts) {
- cacheKey += `${part}`;
- if (listCache.has(cacheKey)) {
- return listCache.get(cacheKey);
- }
- cacheKey += ATTR_SEPARATOR;
- }
- return undefined;
- };
-
- const deleteCache = (attr: string) => {
- listCache.delete(getCacheKey(attr));
- };
-
- const clearCache = () => {
- LIST_CACHE.delete(namespace);
- };
-
- return {
- cacheMap: listCache,
- getCacheKey,
- getCache,
- clearCache,
- deleteCache,
- };
-};
diff --git a/frontend/src/utils/dom.ts b/frontend/src/utils/dom.ts
index f4aab6f3e2..ceb6817ef2 100644
--- a/frontend/src/utils/dom.ts
+++ b/frontend/src/utils/dom.ts
@@ -1,5 +1,3 @@
-import { onBeforeUnmount, type Ref, unref, watch } from "vue";
-
export const isDescendantOf = (
node: Element | null | undefined,
selector: string
@@ -43,46 +41,3 @@ export const getScrollParent = (
export const nextAnimationFrame = () => {
return new Promise<number>((resolve) => requestAnimationFrame(resolve));
};
-
-export const usePreventBackAndForward = (
- elemRef: Ref<HTMLElement | null | undefined> | HTMLElement = document.body
-) => {
- const preventBackForward = (elem: HTMLElement) => {
- function handleWheel(e: WheelEvent) {
- const maxX = elem.scrollWidth - elem.clientWidth;
- const scrollTarget = elem.scrollLeft + e.deltaX;
- if (scrollTarget < 0 || scrollTarget > maxX) {
- e.preventDefault();
- }
- }
-
- elem.addEventListener("wheel", handleWheel, {
- passive: false,
- });
-
- return () => {
- elem.removeEventListener("wheel", handleWheel);
- };
- };
-
- let unregister: () => void;
- watch(
- () => unref(elemRef),
- (elem) => {
- if (!elem) return;
- if (unregister) {
- unregister();
- }
- unregister = preventBackForward(elem);
- },
- {
- immediate: true,
- }
- );
-
- onBeforeUnmount(() => {
- if (unregister) {
- unregister();
- }
- });
-};
diff --git a/frontend/src/utils/util.ts b/frontend/src/utils/util.ts
index 3d8d624960..fdc5b18612 100644
--- a/frontend/src/utils/util.ts
+++ b/frontend/src/utils/util.ts
@@ -7,7 +7,6 @@ import utc from "dayjs/plugin/utc";
import DOMPurify from "dompurify";
import { escape as escapeHtml, escapeRegExp, round } from "lodash-es";
import semver from "semver";
-import { type Ref, watchEffect } from "vue";
import {
formatAbsoluteDate,
formatRelativeTime,
@@ -253,22 +252,6 @@ export const sleep = (ms: number) => {
return new Promise((resolve) => setTimeout(resolve, ms));
};
-/**
- * Wrap a Ref as a Promise, will be resolved when the Ref turns to expectedValue
- * first time
- */
-export const wrapRefAsPromise = <T>(r: Ref<T>, expectedValue: T) => {
- return new Promise<void>((resolve) => {
- watchEffect(() => {
- if (r.value === expectedValue) {
- // Need not to care about resolving more than once
- // Since `Promise` will handle this
- resolve();
- }
- });
- });
-};
-
// emitStorageChangedEvent is used to notify the storage changed event
export function emitStorageChangedEvent() {
const iframeEl = document.createElement("iframe");
diff --git a/frontend/src/utils/v1/instance.ts b/frontend/src/utils/v1/instance.ts
index 1b543a5a89..eb544288ae 100644
--- a/frontend/src/utils/v1/instance.ts
+++ b/frontend/src/utils/v1/instance.ts
@@ -1,11 +1,5 @@
-import { computed, unref } from "vue";
import { t } from "@/plugins/i18n";
-import type { MaybeRef } from "@/types";
-import {
- isValidInstanceName,
- languageOfEngineV1,
- unknownInstance,
-} from "@/types";
+import { isValidInstanceName, unknownInstance } from "@/types";
import { Engine } from "@/types/proto-es/v1/common_pb";
// Using proto-es types directly, no conversions needed
import type {
@@ -408,14 +402,6 @@ export const hasIndexSizeProperty = (
return ![Engine.CLICKHOUSE, Engine.SNOWFLAKE].includes(engine);
};
-export const useInstanceV1EditorLanguage = (
- instance: MaybeRef<Instance | InstanceResource | undefined>
-) => {
- return computed(() => {
- return languageOfEngineV1(unref(instance)?.engine);
- });
-};
-
export const isValidSpannerHost = (host: string) => {
const RE =
/^projects\/(?<PROJECT_ID>(?:[a-z]|[-.:]|[0-9])+)\/instances\/(?<INSTANCE_ID>(?:[a-z]|[-]|[0-9])+)$/;
diff --git a/frontend/src/utils/web-storage.ts b/frontend/src/utils/web-storage.ts
index ce3194ebd7..b79d823190 100644
--- a/frontend/src/utils/web-storage.ts
+++ b/frontend/src/utils/web-storage.ts
@@ -1,26 +1,3 @@
-import {
- customStorageEventName,
- defaultWindow,
- getSSRHandler,
- pausableWatch,
- type RemovableRef,
- type StorageEventLike,
- type StorageLike,
- StorageSerializers,
- tryOnMounted,
- type UseStorageOptions,
- useEventListener,
-} from "@vueuse/core";
-import {
- type MaybeRefOrGetter,
- nextTick,
- type Ref,
- ref,
- shallowRef,
- toValue,
- watch,
-} from "vue";
-
export class WebStorageHelper {
storage: Storage;
keyPrefix: string;
@@ -78,186 +55,3 @@ export class WebStorageHelper {
});
}
}
-
-/**
- * see: https://github.com/vueuse/vueuse/blob/main/packages/core/useStorage/index.ts
- */
-export const useDynamicLocalStorage = <
- T extends string | number | boolean | object | null,
->(
- key: Ref<string>,
- defaults: MaybeRefOrGetter<T>,
- storage: StorageLike | undefined = window.localStorage,
- options: UseStorageOptions<T> = {}
-) => {
- const {
- flush = "pre",
- deep = true,
- listenToStorageChanges = true,
- writeDefaults = true,
- mergeDefaults = false,
- shallow,
- window = defaultWindow,
- eventFilter,
- onError = (e) => {
- console.error(e);
- },
- initOnMounted,
- } = options;
-
- const data = (shallow ? shallowRef : ref)(
- typeof defaults === "function" ? defaults() : defaults
- ) as RemovableRef<T>;
-
- if (!storage) {
- try {
- storage = getSSRHandler(
- "getDefaultStorage",
- () => defaultWindow?.localStorage
- )();
- } catch (e) {
- onError(e);
- }
- }
-
- if (!storage) return data;
-
- const rawInit: T = toValue(defaults);
- const type = guessSerializerType<T>(rawInit);
- const serializer = options.serializer ?? StorageSerializers[type];
-
- const { pause: pauseWatch, resume: resumeWatch } = pausableWatch(
- data,
- () => write(data.value),
- { flush, deep, eventFilter }
- );
-
- if (window && listenToStorageChanges) {
- tryOnMounted(() => {
- // this should be fine since we are in a mounted hook
- useEventListener(window, "storage", update);
- useEventListener(window, customStorageEventName, updateFromCustomEvent);
- if (initOnMounted) update();
- });
- }
-
- // avoid reading immediately to avoid hydration mismatch when doing SSR
- if (!initOnMounted) update();
-
- function dispatchWriteEvent(
- oldValue: string | null,
- newValue: string | null
- ) {
- // send custom event to communicate within same page
- // importantly this should _not_ be a StorageEvent since those cannot
- // be constructed with a non-built-in storage area
- if (window) {
- window.dispatchEvent(
- new CustomEvent<StorageEventLike>(customStorageEventName, {
- detail: {
- key: key.value,
- oldValue,
- newValue,
- storageArea: storage,
- },
- })
- );
- }
- }
-
- function write(v: unknown) {
- try {
- const oldValue = storage.getItem(key.value);
-
- if (v == null) {
- dispatchWriteEvent(oldValue, null);
- storage.removeItem(key.value);
- } else {
- // v is known to be T at this point since it comes from data.value
- const serialized = serializer.write(v as T);
- if (oldValue !== serialized) {
- storage.setItem(key.value, serialized);
- dispatchWriteEvent(oldValue, serialized);
- }
- }
- } catch (e) {
- onError(e);
- }
- }
-
- function read(event?: StorageEventLike) {
- const rawValue = event ? event.newValue : storage.getItem(key.value);
-
- if (rawValue == null) {
- if (writeDefaults && rawInit != null)
- storage.setItem(key.value, serializer.write(rawInit));
- return rawInit;
- } else if (!event && mergeDefaults) {
- const value = serializer.read(rawValue);
- if (typeof mergeDefaults === "function") {
- return mergeDefaults(value, rawInit);
- } else if (type === "object" && !Array.isArray(value)) {
- // We know T extends object here since type === "object"
- return { ...(rawInit as Record<string, unknown>), ...value } as T;
- }
- return value;
- } else if (typeof rawValue !== "string") {
- return rawValue;
- } else {
- return serializer.read(rawValue);
- }
- }
-
- function update(event?: StorageEventLike) {
- if (event && event.storageArea !== storage) return;
-
- if (event && event.key == null) {
- data.value = rawInit;
- return;
- }
-
- if (event && event.key !== key.value) return;
-
- pauseWatch();
- try {
- if (event?.newValue !== serializer.write(data.value))
- data.value = read(event);
- } catch (e) {
- onError(e);
- } finally {
- // use nextTick to avoid infinite loop
- if (event) nextTick(resumeWatch);
- else resumeWatch();
- }
- }
-
- function updateFromCustomEvent(event: CustomEvent<StorageEventLike>) {
- update(event.detail);
- }
-
- watch(key, () => update());
-
- return data;
-};
-
-function guessSerializerType<
- T extends string | number | boolean | object | null,
->(rawInit: T) {
- return rawInit == null
- ? "any"
- : rawInit instanceof Set
- ? "set"
- : rawInit instanceof Map
- ? "map"
- : rawInit instanceof Date
- ? "date"
- : typeof rawInit === "boolean"
- ? "boolean"
- : typeof rawInit === "string"
- ? "string"
- : typeof rawInit === "object"
- ? "object"
- : !Number.isNaN(rawInit)
- ? "number"
- : "any";
-}