Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

improvement: fallback to available storage when localStorage is not available (#6879)

Myles Scolnick1525d7a38542
diff --git a/biome.jsonc b/biome.jsonc
index 1b3ea0c754..d79d753b7d 100644
--- a/biome.jsonc
+++ b/biome.jsonc
@@ -3,7 +3,8 @@
"plugins": [
"frontend/lint/addEventListenerObject.grit",
"frontend/lint/removeEventListenerObject.grit",
- "frontend/lint/preferObjectParams.grit"
+ "frontend/lint/preferObjectParams.grit",
+ "frontend/lint/atomWithStorageArgs.grit"
],
"files": {
"includes": ["frontend/**/*", "packages/**/*", "!*.json", "!*.jsonc"]
diff --git a/frontend/lint/atomWithStorageArgs.grit b/frontend/lint/atomWithStorageArgs.grit
new file mode 100644
index 0000000000..6584f7f2ad
--- /dev/null
+++ b/frontend/lint/atomWithStorageArgs.grit
@@ -0,0 +1,12 @@
+// Enforce atomWithStorage to use at least 3 arguments
+// This ensures the storage parameter is always explicitly provided
+or {
+ `atomWithStorage($arg1, $arg2)`,
+ `atomWithStorage<$_>($arg1, $arg2)`
+} where {
+ register_diagnostic(
+ span=$arg1,
+ message="atomWithStorage requires at least 3 arguments (key, defaultValue, storage). Provide the storage parameter explicitly.",
+ severity="error"
+ )
+}
diff --git a/frontend/src/components/chat/acp/state.ts b/frontend/src/components/chat/acp/state.ts
index 595e363f55..85b04f3aaf 100644
--- a/frontend/src/components/chat/acp/state.ts
+++ b/frontend/src/components/chat/acp/state.ts
@@ -4,6 +4,7 @@ import { atom } from "jotai";
import { atomWithStorage } from "jotai/utils";
import { capitalize } from "lodash-es";
import { isPlatformWindows } from "@/core/hotkeys/shortcuts";
+import { jotaiJsonStorage } from "@/utils/storage/jotai";
import type { TypedString } from "@/utils/typed";
import { generateUUID } from "@/utils/uuid";
import type { ExternalAgentSessionId, SessionSupportType } from "./types";
@@ -41,6 +42,7 @@ export const agentSessionStateAtom = atomWithStorage<AgentSessionState>(
sessions: [],
activeTabId: null,
},
+ jotaiJsonStorage,
);
export const selectedTabAtom = atom(
diff --git a/frontend/src/components/data-table/charts/__tests__/storage.test.ts b/frontend/src/components/data-table/charts/__tests__/storage.test.ts
index 2bb22a2916..be4bb7694f 100644
--- a/frontend/src/components/data-table/charts/__tests__/storage.test.ts
+++ b/frontend/src/components/data-table/charts/__tests__/storage.test.ts
@@ -2,8 +2,18 @@
import { getDefaultStore } from "jotai";
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { asMock, SetupMocks } from "@/__mocks__/common";
+
+// Mock the storage module to use our mock storage
+vi.mock("@/utils/storage/storage", () => ({
+ availableStorage: {
+ getItem: vi.fn(),
+ setItem: vi.fn(),
+ removeItem: vi.fn(),
+ },
+}));
+
import type { CellId } from "@/core/cells/ids";
+import { availableStorage } from "@/utils/storage/storage";
import { ChartSchema } from "../schemas";
import type { TabName } from "../storage";
import { KEY, tabsStorageAtom } from "../storage";
@@ -12,7 +22,6 @@ import { ChartType } from "../types";
describe("Chart Transforms Storage", () => {
beforeEach(() => {
vi.clearAllMocks();
- SetupMocks.localStorage();
// Reset the store before each test
const store = getDefaultStore();
store.set(tabsStorageAtom, new Map());
@@ -87,14 +96,11 @@ describe("Chart Transforms Storage", () => {
describe("LocalStorage integration", () => {
it("should call localStorage.setItem when setting data", () => {
- // Reset the mock to ensure clean state
- asMock(window.localStorage.setItem).mockReset();
-
const store = getDefaultStore();
const newMap = new Map();
store.set(tabsStorageAtom, newMap);
- expect(window.localStorage.setItem).toHaveBeenCalledWith(
+ expect(availableStorage.setItem).toHaveBeenCalledWith(
KEY,
JSON.stringify([]),
);
diff --git a/frontend/src/components/data-table/charts/storage.ts b/frontend/src/components/data-table/charts/storage.ts
index 5fb895c913..9265d42114 100644
--- a/frontend/src/components/data-table/charts/storage.ts
+++ b/frontend/src/components/data-table/charts/storage.ts
@@ -5,7 +5,7 @@ import { capitalize } from "lodash-es";
import { z } from "zod";
import type { CellId } from "@/core/cells/ids";
import { Logger } from "@/utils/Logger";
-import { NotebookScopedLocalStorage } from "@/utils/localStorage";
+import { NotebookScopedLocalStorage } from "@/utils/storage/typed";
import type { TypedString } from "@/utils/typed";
import { ChartSchema, type ChartSchemaType } from "./schemas";
import type { ChartType } from "./types";
diff --git a/frontend/src/components/editor/ai/add-cell-with-ai.tsx b/frontend/src/components/editor/ai/add-cell-with-ai.tsx
index 5337bead48..e8c1c9df8a 100644
--- a/frontend/src/components/editor/ai/add-cell-with-ai.tsx
+++ b/frontend/src/components/editor/ai/add-cell-with-ai.tsx
@@ -53,7 +53,8 @@ import { useRuntimeManager } from "@/core/runtime/config";
import { useTheme } from "@/theme/useTheme";
import { cn } from "@/utils/cn";
import { prettyError } from "@/utils/errors";
-import { ZodLocalStorage } from "@/utils/localStorage";
+import { jotaiJsonStorage } from "@/utils/storage/jotai";
+import { ZodLocalStorage } from "@/utils/storage/typed";
import { PythonIcon } from "../cell/code/icons";
import {
CompletionActions,
@@ -66,6 +67,7 @@ import { StreamingChunkTransport } from "./transport/chat-transport";
const languageAtom = atomWithStorage<"python" | "sql">(
"marimo:ai-language",
"python",
+ jotaiJsonStorage,
);
const KEY = "marimo:ai-prompt-history";
diff --git a/frontend/src/components/editor/chrome/state.ts b/frontend/src/components/editor/chrome/state.ts
index e95f46c1df..c3b444e0fd 100644
--- a/frontend/src/components/editor/chrome/state.ts
+++ b/frontend/src/components/editor/chrome/state.ts
@@ -3,7 +3,7 @@
import { useAtomValue } from "jotai";
import { z } from "zod";
import { createReducerAndAtoms } from "@/utils/createReducer";
-import { ZodLocalStorage } from "@/utils/localStorage";
+import { ZodLocalStorage } from "@/utils/storage/typed";
import type { PanelType } from "./types";
export interface ChromeState {
diff --git a/frontend/src/components/editor/columns/storage.ts b/frontend/src/components/editor/columns/storage.ts
index 430f6d15cb..4fa51c2a4b 100644
--- a/frontend/src/components/editor/columns/storage.ts
+++ b/frontend/src/components/editor/columns/storage.ts
@@ -2,7 +2,7 @@
import { z } from "zod";
import { arrayMove } from "@/utils/arrays";
-import { NotebookScopedLocalStorage } from "@/utils/localStorage";
+import { NotebookScopedLocalStorage } from "@/utils/storage/typed";
const BASE_KEY = "marimo:notebook-col-sizes";
diff --git a/frontend/src/components/editor/errors/fix-mode.ts b/frontend/src/components/editor/errors/fix-mode.ts
index 8adf10d538..02731cb6bb 100644
--- a/frontend/src/components/editor/errors/fix-mode.ts
+++ b/frontend/src/components/editor/errors/fix-mode.ts
@@ -2,12 +2,17 @@
import { useAtom } from "jotai";
import { atomWithStorage } from "jotai/utils";
+import { jotaiJsonStorage } from "@/utils/storage/jotai";
export type FixMode = "prompt" | "autofix";
const BASE_KEY = "marimo:ai-autofix-mode";
-const fixModeAtom = atomWithStorage<FixMode>(BASE_KEY, "autofix");
+const fixModeAtom = atomWithStorage<FixMode>(
+ BASE_KEY,
+ "autofix",
+ jotaiJsonStorage,
+);
export function useFixMode() {
const [fixMode, setFixMode] = useAtom(fixModeAtom);
diff --git a/frontend/src/components/editor/output/useWrapText.ts b/frontend/src/components/editor/output/useWrapText.ts
index aa958452ef..5292539b6a 100644
--- a/frontend/src/components/editor/output/useWrapText.ts
+++ b/frontend/src/components/editor/output/useWrapText.ts
@@ -2,11 +2,16 @@
import { useAtom } from "jotai";
import { atomWithStorage } from "jotai/utils";
+import { jotaiJsonStorage } from "@/utils/storage/jotai";
const WRAP_TEXT_KEY = "marimo:console:wrapText";
// Atom for storing wrap text preference - shared across all console outputs
-const wrapTextAtom = atomWithStorage<boolean>(WRAP_TEXT_KEY, false);
+const wrapTextAtom = atomWithStorage<boolean>(
+ WRAP_TEXT_KEY,
+ false,
+ jotaiJsonStorage,
+);
export function useWrapText() {
const [wrapText, setWrapText] = useAtom(wrapTextAtom);
diff --git a/frontend/src/components/home/state.ts b/frontend/src/components/home/state.ts
index 7cda37cbe2..a94866c9e6 100644
--- a/frontend/src/components/home/state.ts
+++ b/frontend/src/components/home/state.ts
@@ -4,6 +4,7 @@ import { atomWithStorage } from "jotai/utils";
import React from "react";
import type { MarimoFile } from "@/core/network/types";
import { Functions } from "@/utils/functions";
+import { jotaiJsonStorage } from "@/utils/storage/jotai";
export type RunningNotebooksMap = Map<string, MarimoFile>;
@@ -19,12 +20,12 @@ export const WorkspaceRootContext = React.createContext<string>("");
export const includeMarkdownAtom = atomWithStorage<boolean>(
"marimo:home:include-markdown",
false,
- undefined,
+ jotaiJsonStorage,
{ getOnInit: true },
);
export const expandedFoldersAtom = atomWithStorage<Record<string, boolean>>(
"marimo:home:expanded-folders",
{},
- undefined,
+ jotaiJsonStorage,
{ getOnInit: true },
);
diff --git a/frontend/src/components/scratchpad/scratchpad-history.ts b/frontend/src/components/scratchpad/scratchpad-history.ts
index 822260d308..9228ec4c95 100644
--- a/frontend/src/components/scratchpad/scratchpad-history.ts
+++ b/frontend/src/components/scratchpad/scratchpad-history.ts
@@ -1,12 +1,17 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { atom } from "jotai";
import { atomWithStorage } from "jotai/utils";
+import { jotaiJsonStorage } from "@/utils/storage/jotai";
const MAX_HISTORY_ITEMS = 15;
const KEY = "marimo:scratchpadHistory:v1";
// Atom for storing the history
-export const scratchpadHistoryAtom = atomWithStorage<string[]>(KEY, []);
+export const scratchpadHistoryAtom = atomWithStorage<string[]>(
+ KEY,
+ [],
+ jotaiJsonStorage,
+);
// Atom for controlling the visibility of the history list
export const historyVisibleAtom = atom(false);
diff --git a/frontend/src/core/ai/state.ts b/frontend/src/core/ai/state.ts
index a23cf83c88..db4c64fe0f 100644
--- a/frontend/src/core/ai/state.ts
+++ b/frontend/src/core/ai/state.ts
@@ -5,7 +5,7 @@ import type { FileUIPart } from "ai";
import { atom } from "jotai";
import { atomWithStorage } from "jotai/utils";
import { uniqueBy } from "@/utils/arrays";
-import { adaptForLocalStorage } from "@/utils/storage";
+import { adaptForLocalStorage, jotaiJsonStorage } from "@/utils/storage/jotai";
import type { TypedString } from "@/utils/typed";
import type { CellId } from "../cells/ids";
@@ -25,6 +25,7 @@ const INCLUDE_OTHER_CELLS_KEY = "marimo:ai:includeOtherCells";
export const includeOtherCellsAtom = atomWithStorage<boolean>(
INCLUDE_OTHER_CELLS_KEY,
true,
+ jotaiJsonStorage,
);
export interface Message {
diff --git a/frontend/src/core/codemirror/copilot/state.ts b/frontend/src/core/codemirror/copilot/state.ts
index c7a2fca9d5..fc121c43f7 100644
--- a/frontend/src/core/codemirror/copilot/state.ts
+++ b/frontend/src/core/codemirror/copilot/state.ts
@@ -7,13 +7,15 @@ import {
resolvedMarimoConfigAtom,
} from "@/core/config/config";
import { store, waitFor } from "@/core/state/jotai";
+import { jotaiJsonStorage } from "@/utils/storage/jotai";
+import { availableStorage } from "@/utils/storage/storage";
const KEY = "marimo:copilot:signedIn";
export const isGitHubCopilotSignedInState = atomWithStorage<boolean | null>(
KEY,
null,
- undefined,
+ jotaiJsonStorage,
{
getOnInit: true,
},
@@ -49,7 +51,7 @@ export function clearGitHubCopilotLoadingVersion(expectedVersion: number) {
}
function getIsLastSignedIn() {
- const lastSignedIn = localStorage.getItem(KEY);
+ const lastSignedIn = availableStorage.getItem(KEY);
return lastSignedIn === "true";
}
diff --git a/frontend/src/core/codemirror/language/languages/sql/sql-mode.ts b/frontend/src/core/codemirror/language/languages/sql/sql-mode.ts
index 3158762939..a0b99904ed 100644
--- a/frontend/src/core/codemirror/language/languages/sql/sql-mode.ts
+++ b/frontend/src/core/codemirror/language/languages/sql/sql-mode.ts
@@ -3,12 +3,17 @@
import { useAtom } from "jotai";
import { atomWithStorage } from "jotai/utils";
import { store } from "@/core/state/jotai";
+import { jotaiJsonStorage } from "@/utils/storage/jotai";
const BASE_KEY = "marimo:notebook-sql-mode";
export type SQLMode = "validate" | "default";
-const sqlModeAtom = atomWithStorage<SQLMode>(BASE_KEY, "default");
+const sqlModeAtom = atomWithStorage<SQLMode>(
+ BASE_KEY,
+ "default",
+ jotaiJsonStorage,
+);
export function useSQLMode() {
const [sqlMode, setSQLMode] = useAtom(sqlModeAtom);
diff --git a/frontend/src/core/rtc/state.ts b/frontend/src/core/rtc/state.ts
index d0c35d83f7..6e00d11288 100644
--- a/frontend/src/core/rtc/state.ts
+++ b/frontend/src/core/rtc/state.ts
@@ -1,13 +1,18 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { atomWithStorage } from "jotai/utils";
import { once } from "lodash-es";
+import { jotaiJsonStorage } from "@/utils/storage/jotai";
import { getFeatureFlag } from "../config/feature-flag";
/**
* The username for the current user when using real-time collaboration.
* This is stored in localStorage.
*/
-export const usernameAtom = atomWithStorage<string>("marimo:rtc:username", "");
+export const usernameAtom = atomWithStorage<string>(
+ "marimo:rtc:username",
+ "",
+ jotaiJsonStorage,
+);
/**
* Whether RTC is enabled.
diff --git a/frontend/src/core/wasm/store.ts b/frontend/src/core/wasm/store.ts
index a23e271dbe..d036737c0a 100644
--- a/frontend/src/core/wasm/store.ts
+++ b/frontend/src/core/wasm/store.ts
@@ -4,7 +4,7 @@ import {
compressToEncodedURIComponent,
decompressFromEncodedURIComponent,
} from "lz-string";
-import { TypedLocalStorage } from "@/utils/localStorage";
+import { TypedLocalStorage } from "@/utils/storage/typed";
import { PyodideRouter } from "./router";
export interface FileStore {
diff --git a/frontend/src/hooks/useLocalStorage.ts b/frontend/src/hooks/useLocalStorage.ts
index e4ac31665a..b8acc7fe50 100644
--- a/frontend/src/hooks/useLocalStorage.ts
+++ b/frontend/src/hooks/useLocalStorage.ts
@@ -1,7 +1,7 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { useState } from "react";
-import { TypedLocalStorage } from "@/utils/localStorage";
+import { TypedLocalStorage } from "@/utils/storage/typed";
/**
* React hook to use localStorage
diff --git a/frontend/src/utils/__tests__/local-storage.test.ts b/frontend/src/utils/__tests__/local-storage.test.ts
index 1b477783a2..6e35db575d 100644
--- a/frontend/src/utils/__tests__/local-storage.test.ts
+++ b/frontend/src/utils/__tests__/local-storage.test.ts
@@ -5,7 +5,7 @@ import { z } from "zod";
import { TestUtils } from "@/__tests__/test-helpers";
import { filenameAtom } from "@/core/saving/file-state";
import { store } from "@/core/state/jotai";
-import { NotebookScopedLocalStorage } from "../localStorage";
+import { NotebookScopedLocalStorage } from "../storage/typed";
describe("NotebookScopedLocalStorage", () => {
const schema = z.object({
diff --git a/frontend/src/utils/__tests__/storage.test.ts b/frontend/src/utils/__tests__/storage.test.ts
index b86cf9e2cf..4585b40532 100644
--- a/frontend/src/utils/__tests__/storage.test.ts
+++ b/frontend/src/utils/__tests__/storage.test.ts
@@ -1,19 +1,16 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { adaptForLocalStorage } from "../storage";
-
-// Mock localStorage
-const localStorageMock = {
- getItem: vi.fn(),
- setItem: vi.fn(),
- removeItem: vi.fn(),
-};
-
-Object.defineProperty(global, "localStorage", {
- value: localStorageMock,
- writable: true,
-});
+
+// Mock the storage module to return our mock
+// This must be before the import of adaptForLocalStorage
+vi.mock("../storage/storage", () => ({
+ availableStorage: {
+ getItem: vi.fn(),
+ setItem: vi.fn(),
+ removeItem: vi.fn(),
+ },
+}));
// Mock Logger
vi.mock("../Logger", () => ({
@@ -22,6 +19,9 @@ vi.mock("../Logger", () => ({
},
}));
+import { adaptForLocalStorage } from "../storage/jotai";
+import { availableStorage } from "../storage/storage";
+
interface TestValue {
id: string;
data: Map<string, number>;
@@ -70,18 +70,18 @@ describe("adaptForLocalStorage", () => {
["key2", 2],
],
});
- localStorageMock.getItem.mockReturnValue(serialized);
+ vi.mocked(availableStorage.getItem).mockReturnValue(serialized);
const result = storage.getItem("test-key", initialValue);
- expect(localStorageMock.getItem).toHaveBeenCalledWith("test-key");
+ expect(availableStorage.getItem).toHaveBeenCalledWith("test-key");
expect(result.id).toBe("test");
expect(result.data.get("key1")).toBe(1);
expect(result.data.get("key2")).toBe(2);
});
it("should return initial value when localStorage returns null", () => {
- localStorageMock.getItem.mockReturnValue(null);
+ vi.mocked(availableStorage.getItem).mockReturnValue(null);
const result = storage.getItem("test-key", initialValue);
@@ -89,7 +89,7 @@ describe("adaptForLocalStorage", () => {
});
it("should return initial value when localStorage returns empty string", () => {
- localStorageMock.getItem.mockReturnValue("");
+ vi.mocked(availableStorage.getItem).mockReturnValue("");
const result = storage.getItem("test-key", initialValue);
@@ -97,7 +97,7 @@ describe("adaptForLocalStorage", () => {
});
it("should return initial value and log warning when JSON parsing fails", () => {
- localStorageMock.getItem.mockReturnValue("invalid-json");
+ vi.mocked(availableStorage.getItem).mockReturnValue("invalid-json");
const result = storage.getItem("test-key", initialValue);
@@ -107,7 +107,7 @@ describe("adaptForLocalStorage", () => {
it("should return initial value and log warning when deserialization fails", () => {
// This JSON is parseable but will cause the Map constructor to throw
- localStorageMock.getItem.mockReturnValue(
+ vi.mocked(availableStorage.getItem).mockReturnValue(
'{"id": "test", "data": "not-an-array"}',
);
@@ -121,7 +121,7 @@ describe("adaptForLocalStorage", () => {
it("should serialize and store value in localStorage", () => {
storage.setItem("test-key", testValue);
- expect(localStorageMock.setItem).toHaveBeenCalledWith(
+ expect(availableStorage.setItem).toHaveBeenCalledWith(
"test-key",
JSON.stringify({
id: "test",
@@ -138,7 +138,7 @@ describe("adaptForLocalStorage", () => {
it("should call localStorage.removeItem with the correct key", () => {
storage.removeItem("test-key");
- expect(localStorageMock.removeItem).toHaveBeenCalledWith("test-key");
+ expect(availableStorage.removeItem).toHaveBeenCalledWith("test-key");
});
});
});
diff --git a/frontend/src/utils/storage.ts b/frontend/src/utils/storage/jotai.ts
similarity index 64%
rename from frontend/src/utils/storage.ts
rename to frontend/src/utils/storage/jotai.ts
index 84fae3be9b..c82b6cb273 100644
--- a/frontend/src/utils/storage.ts
+++ b/frontend/src/utils/storage/jotai.ts
@@ -1,7 +1,9 @@
/* Copyright 2024 Marimo. All rights reserved. */
+import { createJSONStorage } from "jotai/utils";
import type { SyncStorage } from "jotai/vanilla/utils/atomWithStorage";
-import { Logger } from "./Logger";
+import { Logger } from "../Logger";
+import { availableStorage } from "./storage";
/**
* Converts a value to and from a serializable format for storage.
@@ -10,14 +12,18 @@ import { Logger } from "./Logger";
* @param opts - The options for the storage adapter.
* @returns - The storage adapter.
*/
+
export function adaptForLocalStorage<Value, Serializable>(opts: {
toSerializable: (v: Value) => Serializable;
fromSerializable: (s: Serializable) => Value;
+ storage?: Storage;
}): SyncStorage<Value> {
+ const storage = opts.storage || availableStorage;
+
return {
getItem(key, initialValue) {
try {
- const value = localStorage.getItem(key);
+ const value = storage.getItem(key);
if (!value) {
return initialValue;
}
@@ -29,10 +35,16 @@ export function adaptForLocalStorage<Value, Serializable>(opts: {
}
},
setItem: (key, value): void => {
- localStorage.setItem(key, JSON.stringify(opts.toSerializable(value)));
+ storage.setItem(key, JSON.stringify(opts.toSerializable(value)));
},
removeItem: (key: string): void => {
- localStorage.removeItem(key);
+ storage.removeItem(key);
},
};
}
+
+/**
+ * A JSON storage adapter that uses the best available storage.
+ */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+export const jotaiJsonStorage = createJSONStorage<any>(() => availableStorage);
diff --git a/frontend/src/utils/storage/storage.ts b/frontend/src/utils/storage/storage.ts
new file mode 100644
index 0000000000..2d687d9bf2
--- /dev/null
+++ b/frontend/src/utils/storage/storage.ts
@@ -0,0 +1,85 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { Logger } from "../Logger";
+
+/**
+ * In-memory storage implementation of the Storage interface.
+ */
+class InMemoryStorage implements Storage {
+ private store: Map<string, string> = new Map();
+
+ get length(): number {
+ return this.store.size;
+ }
+
+ clear(): void {
+ this.store.clear();
+ }
+
+ getItem(key: string): string | null {
+ return this.store.get(key) || null;
+ }
+
+ key(index: number): string | null {
+ const keys = Array.from(this.store.keys());
+ return keys[index] || null;
+ }
+
+ removeItem(key: string): void {
+ this.store.delete(key);
+ }
+
+ setItem(key: string, value: string): void {
+ this.store.set(key, value);
+ }
+}
+
+/**
+ * Tests if a specific storage type is available and working
+ */
+function isStorageAvailable(type: "localStorage" | "sessionStorage"): boolean {
+ try {
+ const storage: Storage = window[type];
+ const testKey = "__storage_test__";
+ const testValue = "test";
+
+ // Check if storage exists
+ if (!storage) {
+ return false;
+ }
+
+ // Try to use the storage
+ storage.setItem(testKey, testValue);
+ const retrieved = storage.getItem(testKey);
+ storage.removeItem(testKey);
+
+ return retrieved === testValue;
+ } catch (error) {
+ // Storage might be disabled or full
+ return false;
+ }
+}
+
+/**
+ * Gets the best available storage. Should only be called once.
+ */
+function getAvailableStorage(): Storage {
+ if (isStorageAvailable("localStorage")) {
+ return window.localStorage;
+ }
+
+ Logger.warn("localStorage is not available, using sessionStorage");
+
+ if (isStorageAvailable("sessionStorage")) {
+ return window.sessionStorage;
+ }
+
+ Logger.warn("sessionStorage is not available, using in-memory storage");
+
+ return new InMemoryStorage();
+}
+
+/**
+ * The best available storage. Either localStorage, sessionStorage, or in-memory storage.
+ */
+export const availableStorage: Storage = getAvailableStorage();
diff --git a/frontend/src/utils/localStorage.ts b/frontend/src/utils/storage/typed.ts
similarity index 79%
rename from frontend/src/utils/localStorage.ts
rename to frontend/src/utils/storage/typed.ts
index d0a7a102fb..e8c0c025f5 100644
--- a/frontend/src/utils/localStorage.ts
+++ b/frontend/src/utils/storage/typed.ts
@@ -3,23 +3,27 @@
import type { ZodType } from "zod";
import { filenameAtom } from "@/core/saving/file-state";
import { store } from "@/core/state/jotai";
-import { Logger } from "./Logger";
+import { Logger } from "../Logger";
+import { availableStorage } from "./storage";
-interface Storage<T> {
+interface ITypedStorage<T> {
get(key: string): T;
set(key: string, value: T): void;
remove(key: string): void;
}
-export class TypedLocalStorage<T> implements Storage<T> {
+export class TypedLocalStorage<T> implements ITypedStorage<T> {
private defaultValue: T;
- constructor(defaultValue: T) {
+ private storage: Storage;
+
+ constructor(defaultValue: T, storage = availableStorage) {
this.defaultValue = defaultValue;
+ this.storage = storage;
}
get(key: string): T {
try {
- const item = window.localStorage.getItem(key);
+ const item = this.storage.getItem(key);
return item ? (JSON.parse(item) as T) : this.defaultValue;
} catch {
return this.defaultValue;
@@ -27,26 +31,32 @@ export class TypedLocalStorage<T> implements Storage<T> {
}
set(key: string, value: T) {
- window.localStorage.setItem(key, JSON.stringify(value));
+ this.storage.setItem(key, JSON.stringify(value));
}
remove(key: string) {
- window.localStorage.removeItem(key);
+ this.storage.removeItem(key);
}
}
-export class ZodLocalStorage<T> implements Storage<T> {
+export class ZodLocalStorage<T> implements ITypedStorage<T> {
private schema: ZodType<T>;
private getDefaultValue: () => T;
+ private storage: Storage;
- constructor(schema: ZodType<T>, getDefaultValue: () => T) {
+ constructor(
+ schema: ZodType<T>,
+ getDefaultValue: () => T,
+ storage = availableStorage,
+ ) {
this.schema = schema;
this.getDefaultValue = getDefaultValue;
+ this.storage = storage;
}
get(key: string): T {
try {
- const item = window.localStorage.getItem(key);
+ const item = this.storage.getItem(key);
if (item == null) {
return this.getDefaultValue();
}
@@ -63,11 +73,11 @@ export class ZodLocalStorage<T> implements Storage<T> {
}
set(key: string, value: T) {
- window.localStorage.setItem(key, JSON.stringify(value));
+ this.storage.setItem(key, JSON.stringify(value));
}
remove(key: string) {
- window.localStorage.removeItem(key);
+ this.storage.removeItem(key);
}
}