Files
community-rule/app/(app)/create/utils/anonymousDraftStorage.ts
T
2026-04-18 14:12:49 -06:00

91 lines
2.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { CreateFlowState } from "../types";
import { migrateLegacyCreateFlowState } from "../../../../lib/create/migrateLegacyCreateFlowState";
/** Anonymous in-progress create flow (local only until magic-link transfer). */
export const CREATE_FLOW_ANONYMOUS_KEY = "create-flow-anonymous" as const;
/**
* Set when the user submits magic link from “Save your progress?” so after verify we PUT to server.
* Value is arbitrary truthy string; cleared after successful transfer or abandon.
*/
export const CREATE_FLOW_TRANSFER_PENDING_KEY =
"create-flow-transfer-pending" as const;
/**
* When signed-in + sync, {@link SignedInDraftHydration} resolves server vs this key via `window.confirm`
* if both are non-empty; see `messages/en/create/draftHydration.json`.
*/
const LEGACY_LIVE_KEY = "create-flow-state";
const LEGACY_DRAFT_KEY = "create-flow-draft";
export function readAnonymousCreateFlowState(): CreateFlowState {
if (typeof window === "undefined") return {};
try {
const raw = window.localStorage.getItem(CREATE_FLOW_ANONYMOUS_KEY);
if (!raw) return {};
const parsed = JSON.parse(raw) as Record<string, unknown>;
return typeof parsed === "object" && parsed !== null
? migrateLegacyCreateFlowState(parsed)
: {};
} catch {
return {};
}
}
export function writeAnonymousCreateFlowState(value: CreateFlowState): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(
CREATE_FLOW_ANONYMOUS_KEY,
JSON.stringify(value),
);
} catch {
// quota / private mode
}
}
export function clearAnonymousCreateFlowStorage(): void {
if (typeof window === "undefined") return;
try {
window.localStorage.removeItem(CREATE_FLOW_ANONYMOUS_KEY);
window.localStorage.removeItem(CREATE_FLOW_TRANSFER_PENDING_KEY);
} catch {
// ignore
}
}
export function setTransferPendingFlag(): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(CREATE_FLOW_TRANSFER_PENDING_KEY, "1");
} catch {
// ignore
}
}
export function hasTransferPendingFlag(): boolean {
if (typeof window === "undefined") return false;
try {
return Boolean(
window.localStorage.getItem(CREATE_FLOW_TRANSFER_PENDING_KEY),
);
} catch {
return false;
}
}
/** One-time cleanup of preanonymous-draft keys. */
export function clearLegacyCreateFlowKeysOnce(): void {
if (typeof window === "undefined") return;
try {
const done = window.sessionStorage.getItem("create-flow-legacy-cleared");
if (done) return;
window.localStorage.removeItem(LEGACY_LIVE_KEY);
window.localStorage.removeItem(LEGACY_DRAFT_KEY);
window.sessionStorage.setItem("create-flow-legacy-cleared", "1");
} catch {
// ignore
}
}