From ce782dc70b47880b4174f40c9b0a072d858ce90f Mon Sep 17 00:00:00 2001 From: alex Date: Mon, 4 Mar 2024 16:15:20 +0000 Subject: [PATCH] Wrap local/session storage calls in try/catch (take 2) (#3066) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Steve tried this in #3043, but we reverted it in #3063. Steve's version added `JSON.parse`/`JSON.stringify` to the helpers without checking for where we were already `JSON.parse`ing (or not). In some places we just store strings directly rather than wanting them jsonified, so in this version we leave the jsonification to the callers - the helpers just do the reading/writing and return the string values. ### Change Type - [x] `patch` — Bug fix --- .eslintrc.js | 9 ++ .../src/utils/scratch-persistence-key.ts | 8 +- apps/dotcom/src/utils/userPreferences.ts | 14 +-- .../src/lib/config/TLSessionStateSnapshot.ts | 17 +-- .../src/lib/config/TLUserPreferences.ts | 21 ++-- packages/editor/src/lib/utils/debug-flags.ts | 15 +-- .../editor/src/lib/utils/sync/hardReset.ts | 5 +- .../src/lib/utils/sync/indexedDb.test.ts | 3 +- .../editor/src/lib/utils/sync/indexedDb.ts | 5 +- .../src/lib/ui/hooks/useLocalStorageState.ts | 5 +- packages/utils/api-report.md | 24 ++++ packages/utils/src/index.ts | 10 ++ packages/utils/src/lib/storage.tsx | 119 ++++++++++++++++++ 13 files changed, 204 insertions(+), 51 deletions(-) create mode 100644 packages/utils/src/lib/storage.tsx diff --git a/.eslintrc.js b/.eslintrc.js index b30c4aff9..ca67e5fb3 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -57,6 +57,14 @@ module.exports = { 'error', { selector: "MethodDefinition[kind='set']", message: 'Property setters are not allowed' }, { selector: "MethodDefinition[kind='get']", message: 'Property getters are not allowed' }, + { + selector: 'Identifier[name=localStorage]', + message: 'Use the getFromLocalStorage/setInLocalStorage helpers instead', + }, + { + selector: 'Identifier[name=sessionStorage]', + message: 'Use the getFromSessionStorage/setInSessionStorage helpers instead', + }, ], }, parser: '@typescript-eslint/parser', @@ -88,6 +96,7 @@ module.exports = { files: ['apps/examples/**/*'], rules: { 'import/no-internal-modules': 'off', + 'no-restricted-syntax': 'off', }, }, { diff --git a/apps/dotcom/src/utils/scratch-persistence-key.ts b/apps/dotcom/src/utils/scratch-persistence-key.ts index 9f2ec1b83..60da19b48 100644 --- a/apps/dotcom/src/utils/scratch-persistence-key.ts +++ b/apps/dotcom/src/utils/scratch-persistence-key.ts @@ -8,10 +8,12 @@ * Many users still have that random string in their localStorage so we need to load it. But for new * users it does not need to be unique and we can just use a constant. */ + +import { getFromLocalStorage, setInLocalStorage } from 'tldraw' + // DO NOT CHANGE THESE WITHOUT ADDING MIGRATION LOGIC. DOING SO WOULD WIPE ALL EXISTING LOCAL DATA. const defaultDocumentKey = 'TLDRAW_DEFAULT_DOCUMENT_NAME_v2' -const w = typeof window === 'undefined' ? undefined : window export const SCRATCH_PERSISTENCE_KEY = - (w?.localStorage.getItem(defaultDocumentKey) as any) ?? 'tldraw_document_v3' -w?.localStorage.setItem(defaultDocumentKey, SCRATCH_PERSISTENCE_KEY) + getFromLocalStorage(defaultDocumentKey) ?? 'tldraw_document_v3' +setInLocalStorage(defaultDocumentKey, SCRATCH_PERSISTENCE_KEY) diff --git a/apps/dotcom/src/utils/userPreferences.ts b/apps/dotcom/src/utils/userPreferences.ts index a2a938cbc..67aea40ed 100644 --- a/apps/dotcom/src/utils/userPreferences.ts +++ b/apps/dotcom/src/utils/userPreferences.ts @@ -1,4 +1,4 @@ -import { T, atom } from 'tldraw' +import { T, atom, getFromLocalStorage, setInLocalStorage } from 'tldraw' const channel = typeof BroadcastChannel !== 'undefined' ? new BroadcastChannel('tldrawUserPreferences') : null @@ -37,9 +37,7 @@ function createPreference(key: string, validator: T.Validator, defau } function loadItemFromStorage(key: string, validator: T.Validator): Type | null { - if (typeof localStorage === 'undefined' || !localStorage) return null - - const item = localStorage.getItem(`tldrawUserPreferences.${key}`) + const item = getFromLocalStorage(`tldrawUserPreferences.${key}`) if (item == null) return null try { return validator.validate(JSON.parse(item)) @@ -49,11 +47,5 @@ function loadItemFromStorage(key: string, validator: T.Validator): T } function saveItemToStorage(key: string, value: unknown): void { - if (typeof localStorage === 'undefined' || !localStorage) return - - try { - localStorage.setItem(`tldrawUserPreferences.${key}`, JSON.stringify(value)) - } catch (e) { - // not a big deal - } + setInLocalStorage(`tldrawUserPreferences.${key}`, JSON.stringify(value)) } diff --git a/packages/editor/src/lib/config/TLSessionStateSnapshot.ts b/packages/editor/src/lib/config/TLSessionStateSnapshot.ts index a3315feda..d98d87668 100644 --- a/packages/editor/src/lib/config/TLSessionStateSnapshot.ts +++ b/packages/editor/src/lib/config/TLSessionStateSnapshot.ts @@ -17,7 +17,12 @@ import { pageIdValidator, shapeIdValidator, } from '@tldraw/tlschema' -import { objectMapFromEntries } from '@tldraw/utils' +import { + deleteFromSessionStorage, + getFromSessionStorage, + objectMapFromEntries, + setInSessionStorage, +} from '@tldraw/utils' import { T } from '@tldraw/validate' import { uniqueId } from '../utils/uniqueId' @@ -26,8 +31,6 @@ const tabIdKey = 'TLDRAW_TAB_ID_v2' as const const window = globalThis.window as | { navigator: Window['navigator'] - localStorage: Window['localStorage'] - sessionStorage: Window['sessionStorage'] addEventListener: Window['addEventListener'] TLDRAW_TAB_ID_v2?: string } @@ -51,7 +54,7 @@ function iOS() { * @public */ export const TAB_ID: string = window - ? window[tabIdKey] ?? window.sessionStorage[tabIdKey] ?? `TLDRAW_INSTANCE_STATE_V1_` + uniqueId() + ? window[tabIdKey] ?? getFromSessionStorage(tabIdKey) ?? `TLDRAW_INSTANCE_STATE_V1_` + uniqueId() : '' if (window) { window[tabIdKey] = TAB_ID @@ -62,14 +65,14 @@ if (window) { // in which case they'll have two tabs with the same UI state. // It's not a big deal, but it's not ideal. // And anyway I can't see a way to duplicate a tab in iOS Safari. - window.sessionStorage[tabIdKey] = TAB_ID + setInSessionStorage(tabIdKey, TAB_ID) } else { - delete window.sessionStorage[tabIdKey] + deleteFromSessionStorage(tabIdKey) } } window?.addEventListener('beforeunload', () => { - window.sessionStorage[tabIdKey] = TAB_ID + setInSessionStorage(tabIdKey, TAB_ID) }) const Versions = { diff --git a/packages/editor/src/lib/config/TLUserPreferences.ts b/packages/editor/src/lib/config/TLUserPreferences.ts index 8c6cf55ad..76bef8f49 100644 --- a/packages/editor/src/lib/config/TLUserPreferences.ts +++ b/packages/editor/src/lib/config/TLUserPreferences.ts @@ -1,6 +1,7 @@ import { atom } from '@tldraw/state' import { defineMigrations, migrate } from '@tldraw/store' import { getDefaultTranslationLocale } from '@tldraw/tlschema' +import { getFromLocalStorage, setInLocalStorage } from '@tldraw/utils' import { T } from '@tldraw/validate' import { uniqueId } from '../utils/uniqueId' @@ -200,11 +201,8 @@ function migrateUserPreferences(userData: unknown) { } function loadUserPreferences(): TLUserPreferences { - const userData = - typeof window === 'undefined' - ? null - : ((JSON.parse(window?.localStorage?.getItem(USER_DATA_KEY) || 'null') ?? - null) as null | UserDataSnapshot) + const userData = (JSON.parse(getFromLocalStorage(USER_DATA_KEY) || 'null') ?? + null) as null | UserDataSnapshot return migrateUserPreferences(userData) } @@ -212,15 +210,10 @@ function loadUserPreferences(): TLUserPreferences { const globalUserPreferences = atom('globalUserData', null) function storeUserPreferences() { - if (typeof window !== 'undefined' && window.localStorage) { - window.localStorage.setItem( - USER_DATA_KEY, - JSON.stringify({ - version: userMigrations.currentVersion, - user: globalUserPreferences.get(), - }) - ) - } + setInLocalStorage( + USER_DATA_KEY, + JSON.stringify({ version: userMigrations.currentVersion, user: globalUserPreferences.get() }) + ) } /** @public */ diff --git a/packages/editor/src/lib/utils/debug-flags.ts b/packages/editor/src/lib/utils/debug-flags.ts index 2e11d3143..51fbecb74 100644 --- a/packages/editor/src/lib/utils/debug-flags.ts +++ b/packages/editor/src/lib/utils/debug-flags.ts @@ -1,4 +1,5 @@ import { Atom, atom, react } from '@tldraw/state' +import { deleteFromSessionStorage, getFromSessionStorage, setInSessionStorage } from '@tldraw/utils' // --- 1. DEFINE --- // @@ -126,14 +127,10 @@ function createDebugValueBase(def: DebugFlagDef): DebugFlag { if (def.shouldStoreForSession) { react(`debug:${def.name}`, () => { const currentValue = valueAtom.get() - try { - if (currentValue === defaultValue) { - window.sessionStorage.removeItem(`tldraw_debug:${def.name}`) - } else { - window.sessionStorage.setItem(`tldraw_debug:${def.name}`, JSON.stringify(currentValue)) - } - } catch { - // not a big deal + if (currentValue === defaultValue) { + deleteFromSessionStorage(`tldraw_debug:${def.name}`) + } else { + setInSessionStorage(`tldraw_debug:${def.name}`, JSON.stringify(currentValue)) } }) } @@ -154,7 +151,7 @@ function createDebugValueBase(def: DebugFlagDef): DebugFlag { function getStoredInitialValue(name: string) { try { - return JSON.parse(window?.sessionStorage.getItem(`tldraw_debug:${name}`) ?? 'null') + return JSON.parse(getFromSessionStorage(`tldraw_debug:${name}`) ?? 'null') } catch (err) { return null } diff --git a/packages/editor/src/lib/utils/sync/hardReset.ts b/packages/editor/src/lib/utils/sync/hardReset.ts index 956cec159..fa611b456 100644 --- a/packages/editor/src/lib/utils/sync/hardReset.ts +++ b/packages/editor/src/lib/utils/sync/hardReset.ts @@ -1,3 +1,4 @@ +import { clearLocalStorage, clearSessionStorage } from '@tldraw/utils' import { deleteDB } from 'idb' import { getAllIndexDbNames } from './indexedDb' @@ -6,11 +7,11 @@ import { getAllIndexDbNames } from './indexedDb' * * @public */ export async function hardReset({ shouldReload = true } = {}) { - sessionStorage.clear() + clearSessionStorage() await Promise.all(getAllIndexDbNames().map((db) => deleteDB(db))) - localStorage.clear() + clearLocalStorage() if (shouldReload) { window.location.reload() } diff --git a/packages/editor/src/lib/utils/sync/indexedDb.test.ts b/packages/editor/src/lib/utils/sync/indexedDb.test.ts index 78c66a458..2d5ce852e 100644 --- a/packages/editor/src/lib/utils/sync/indexedDb.test.ts +++ b/packages/editor/src/lib/utils/sync/indexedDb.test.ts @@ -1,4 +1,5 @@ import { createTLSchema } from '@tldraw/tlschema' +import { clearLocalStorage } from '@tldraw/utils' import { getAllIndexDbNames, loadDataFromStore, @@ -9,7 +10,7 @@ import { const clearAll = async () => { const dbs = (indexedDB as any)._databases as Map dbs.clear() - localStorage.clear() + clearLocalStorage() } beforeEach(async () => { diff --git a/packages/editor/src/lib/utils/sync/indexedDb.ts b/packages/editor/src/lib/utils/sync/indexedDb.ts index 39c215d54..b042a5f19 100644 --- a/packages/editor/src/lib/utils/sync/indexedDb.ts +++ b/packages/editor/src/lib/utils/sync/indexedDb.ts @@ -1,5 +1,6 @@ import { RecordsDiff, SerializedSchema, SerializedStore } from '@tldraw/store' import { TLRecord, TLStoreSchema } from '@tldraw/tlschema' +import { getFromLocalStorage, setInLocalStorage } from '@tldraw/utils' import { IDBPDatabase, openDB } from 'idb' import { TLSessionStateSnapshot } from '../../config/TLSessionStateSnapshot' @@ -221,7 +222,7 @@ async function pruneSessionState({ /** @internal */ export function getAllIndexDbNames(): string[] { - const result = JSON.parse(window?.localStorage.getItem(dbNameIndexKey) || '[]') ?? [] + const result = JSON.parse(getFromLocalStorage(dbNameIndexKey) || '[]') ?? [] if (!Array.isArray(result)) { return [] } @@ -231,5 +232,5 @@ export function getAllIndexDbNames(): string[] { function addDbName(name: string) { const all = new Set(getAllIndexDbNames()) all.add(name) - window?.localStorage.setItem(dbNameIndexKey, JSON.stringify([...all])) + setInLocalStorage(dbNameIndexKey, JSON.stringify([...all])) } diff --git a/packages/tldraw/src/lib/ui/hooks/useLocalStorageState.ts b/packages/tldraw/src/lib/ui/hooks/useLocalStorageState.ts index d7e6d8796..fd84aa122 100644 --- a/packages/tldraw/src/lib/ui/hooks/useLocalStorageState.ts +++ b/packages/tldraw/src/lib/ui/hooks/useLocalStorageState.ts @@ -1,3 +1,4 @@ +import { getFromLocalStorage, setInLocalStorage } from '@tldraw/editor' import React from 'react' /** @public */ @@ -5,7 +6,7 @@ export function useLocalStorageState(key: string, defaultValue: T) { const [state, setState] = React.useState(defaultValue) React.useLayoutEffect(() => { - const value = localStorage.getItem(key) + const value = getFromLocalStorage(key) if (value) { try { setState(JSON.parse(value)) @@ -19,7 +20,7 @@ export function useLocalStorageState(key: string, defaultValue: T) { (setter: T | ((value: T) => T)) => { setState((s) => { const value = typeof setter === 'function' ? (setter as any)(s) : setter - localStorage.setItem(key, JSON.stringify(value)) + setInLocalStorage(key, JSON.stringify(value)) return value }) }, diff --git a/packages/utils/api-report.md b/packages/utils/api-report.md index 63b0f9f19..911cc0e5f 100644 --- a/packages/utils/api-report.md +++ b/packages/utils/api-report.md @@ -19,6 +19,12 @@ export const assert: (value: unknown, message?: string) => asserts value; // @internal (undocumented) export const assertExists: (value: T, message?: string | undefined) => NonNullable; +// @internal +export function clearLocalStorage(): void; + +// @internal +export function clearSessionStorage(): void; + // @internal (undocumented) export function compact(arr: T[]): NonNullable[]; @@ -34,6 +40,12 @@ export function dedupe(input: T[], equals?: (a: any, b: any) => boolean): T[] // @public export function deepCopy(obj: T): T; +// @internal +export function deleteFromLocalStorage(key: string): void; + +// @internal +export function deleteFromSessionStorage(key: string): void; + // @public (undocumented) export type ErrorResult = { readonly ok: false; @@ -68,6 +80,12 @@ export function getErrorAnnotations(error: Error): ErrorAnnotations; // @public export function getFirstFromIterable(set: Map | Set): T; +// @internal +export function getFromLocalStorage(key: string): null | string; + +// @internal +export function getFromSessionStorage(key: string): null | string; + // @public export function getHashForBuffer(buffer: ArrayBuffer): string; @@ -273,6 +291,12 @@ export function rng(seed?: string): () => number; // @public export function rotateArray(arr: T[], offset: number): T[]; +// @internal +export function setInLocalStorage(key: string, value: string): void; + +// @internal +export function setInSessionStorage(key: string, value: string): void; + // @public (undocumented) export function sortById