import invariant from "invariant";
import {
compressToEncodedURIComponent,
decompressFromEncodedURIComponent,
} from "lz-string";
import { defaultStore } from "../defaultStore";
export interface Store {
source: string;
}
export function encodeStore(store: Store): string {
return compressToEncodedURIComponent(JSON.stringify(store));
}
export function decodeStore(hash: string): Store {
return JSON.parse(decompressFromEncodedURIComponent(hash));
}
export function saveStore(store: Store) {
const hash = encodeStore(store);
localStorage.setItem("playgroundStore", hash);
history.replaceState({}, "", `#${hash}`);
}
function isValidStore(raw: unknown): raw is Store {
return (
raw != null &&
typeof raw == "object" &&
"source" in raw &&
typeof raw["source"] === "string"
);
}
export function initStoreFromUrlOrLocalStorage(): Store {
const encodedSourceFromUrl = location.hash.slice(1);
const encodedSourceFromLocal = localStorage.getItem("playgroundStore");
const encodedSource = encodedSourceFromUrl || encodedSourceFromLocal;
if (!encodedSource) return defaultStore;
const raw = decodeStore(encodedSource);
invariant(isValidStore(raw), "Invalid Store");
return raw;
}