feat(reader): persist Try-it activation in localStorage
This commit is contained in:
@@ -0,0 +1,43 @@
|
|||||||
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
|
|
||||||
|
function keyFor(id) {
|
||||||
|
return `aibook-demo-activation:${id}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Demo-only activation state. Completing a Try-it writes
|
||||||
|
* localStorage key `aibook-demo-activation:<RECIPE-ID>`.
|
||||||
|
*/
|
||||||
|
export default function useActivation(ids) {
|
||||||
|
const list = useMemo(() => ids, [ids.join("|")]);
|
||||||
|
const [complete, setComplete] = useState(() =>
|
||||||
|
Object.fromEntries(list.map((id) => [id, false]))
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const next = {};
|
||||||
|
list.forEach((id) => {
|
||||||
|
try {
|
||||||
|
next[id] = window.localStorage.getItem(keyFor(id)) === "1";
|
||||||
|
} catch {
|
||||||
|
next[id] = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
setComplete(next);
|
||||||
|
}, [list]);
|
||||||
|
|
||||||
|
const toggle = useCallback((id) => {
|
||||||
|
setComplete((prev) => {
|
||||||
|
const value = !prev[id];
|
||||||
|
try {
|
||||||
|
window.localStorage.setItem(keyFor(id), value ? "1" : "0");
|
||||||
|
} catch {
|
||||||
|
/* private mode: still toggle in memory */
|
||||||
|
}
|
||||||
|
return { ...prev, [id]: value };
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const count = list.filter((id) => complete[id]).length;
|
||||||
|
return { complete, toggle, count, total: list.length };
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user