Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
144 changes: 144 additions & 0 deletions e2e-tests/persistence.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import { expect, test, type Page } from "@playwright/test";

const storageKey = "eslint-explorer";

async function getPersistedJavaScriptCode(page: Page): Promise<string> {
return page.evaluate(key => {
const storedValue = window.localStorage.getItem(key);

if (!storedValue) {
return "";
}

return JSON.parse(storedValue).state.code.javascript;
}, storageKey);
}

async function getPersistedExplorerState(page: Page): Promise<string> {
const persistedValue = await page.evaluate(
key => window.localStorage.getItem(key),
storageKey,
);

if (!persistedValue) {
throw new Error("Expected explorer state to be persisted");
}

return persistedValue;
}

async function getStoredHashValue(page: Page): Promise<string> {
return page.evaluate(key => {
return (
new URLSearchParams(window.location.hash.slice(1)).get(key) ?? ""
);
}, storageKey);
}

async function replaceEditorValue(page: Page, value: string) {
const codeEditor = page
.getByRole("region", { name: "Code Editor Panel" })
.getByRole("textbox")
.nth(1);

await codeEditor.click();
await codeEditor.press("ControlOrMeta+KeyA");
await codeEditor.press("Backspace");
await codeEditor.pressSequentially(value);
}

test("should persist unicode code safely in the URL hash", async ({ page }) => {
await page.addInitScript(key => {
window.localStorage.removeItem(key);
}, storageKey);
await page.goto("/");

const unicodeCode = 'const \u03C0 = "\u{1F600}";';

await replaceEditorValue(page, unicodeCode);

await expect.poll(() => getPersistedJavaScriptCode(page)).toBe(unicodeCode);
await expect.poll(() => getStoredHashValue(page)).toContain("v2:");

const persistedHash = await page.evaluate(() => window.location.hash);

await page.evaluate(key => {
window.localStorage.removeItem(key);
}, storageKey);
await page.goto(`/${persistedHash}`);

await expect(page.locator(".cm-content")).toContainText(unicodeCode);
});

test("should still load state from legacy hash links", async ({ page }) => {
await page.addInitScript(key => {
window.localStorage.removeItem(key);
}, storageKey);
await page.goto("/");

const legacyCode = "console.log('legacy hash');";

await replaceEditorValue(page, legacyCode);

await expect.poll(() => getPersistedJavaScriptCode(page)).toBe(legacyCode);

const persistedValue = await getPersistedExplorerState(page);

const legacyHash = await page.evaluate(
([key, value]) => {
const searchParams = new URLSearchParams();
searchParams.set(key, btoa(JSON.stringify(value)));
return searchParams.toString();
},
[storageKey, persistedValue],
);

await page.evaluate(key => {
window.localStorage.removeItem(key);
}, storageKey);
await page.goto(`/#${legacyHash}`);

await expect(page.locator(".cm-content")).toContainText(legacyCode);
});

test("should fall back to localStorage when a v2 hash is malformed", async ({
page,
}) => {
await page.addInitScript(key => {
window.localStorage.removeItem(key);
}, storageKey);
await page.goto("/");

const fallbackCode = "console.log('localStorage fallback');";

await replaceEditorValue(page, fallbackCode);

await expect
.poll(() => getPersistedJavaScriptCode(page))
.toBe(fallbackCode);

const persistedValue = await getPersistedExplorerState(page);

const malformedHash = await page.evaluate(key => {
const bytes = new TextEncoder().encode("not valid persisted state");
let binary = "";

for (const byte of bytes) {
binary += String.fromCharCode(byte);
}

const searchParams = new URLSearchParams();
searchParams.set(key, `v2:${btoa(binary)}`);
return searchParams.toString();
}, storageKey);

await page.evaluate(
([key, value]) => {
window.localStorage.setItem(key, value);
},
[storageKey, persistedValue],
);
await page.goto(`/#${malformedHash}`);

await expect(page.locator(".cm-content")).toContainText(fallbackCode);
});
66 changes: 64 additions & 2 deletions src/hooks/use-explorer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,20 +117,82 @@ const getHashParams = (): URLSearchParams => {
return new URLSearchParams(location.hash.slice(1));
};

const versionedHashPrefix = "v2:";

function isPersistedStorageValue(
value: unknown,
): value is { state: unknown; version: number } {
return (
typeof value === "object" &&
value !== null &&
"state" in value &&
"version" in value &&
typeof value.version === "number"
);
}

function isSerializedPersistedStorageValue(value: string) {
try {
const parsedValue = JSON.parse(value);
return isPersistedStorageValue(parsedValue);
} catch {
return false;
}
}

function encodeHashStorageValue(value: string) {
const bytes = new TextEncoder().encode(value);
let binary = "";

for (const byte of bytes) {
binary += String.fromCharCode(byte);
}

return `${versionedHashPrefix}${btoa(binary)}`;
}

function decodeHashStorageValue(value: string) {
try {
if (value.startsWith(versionedHashPrefix)) {
const binary = atob(value.slice(versionedHashPrefix.length));
const bytes = Uint8Array.from(binary, character =>
character.charCodeAt(0),
);
const decodedValue = new TextDecoder().decode(bytes);

return isSerializedPersistedStorageValue(decodedValue)
? decodedValue
: null;
}

const legacyValue = JSON.parse(atob(value));
return typeof legacyValue === "string" &&
isSerializedPersistedStorageValue(legacyValue)
? legacyValue
: null;
} catch {
return null;
}
}

const hybridStorage: StateStorage = {
getItem: (key): string => {
// Priority: URL hash first, then localStorage fallback
const hashValue = getHashParams().get(key);
if (hashValue) {
return JSON.parse(atob(hashValue));
const decodedHashValue = decodeHashStorageValue(hashValue);

if (decodedHashValue !== null) {
return decodedHashValue;
}
}

const localValue = localStorage.getItem(key);
return localValue || "";
},
setItem: (key, newValue): void => {
const searchParams = getHashParams();
const encodedValue = btoa(JSON.stringify(newValue));
const encodedValue = encodeHashStorageValue(newValue);
searchParams.set(key, encodedValue);
location.hash = searchParams.toString();

Expand Down
Loading