nomadro/src/modules/social/lib/useRosterLikes.ts
Eric e65728601f Ship /social H5 deep polish on test7 and document release line.
Tighten mobile Ways/dock/chat/date sheets, add social loading/error boundaries, and mark test8 as the next branch.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-01 23:19:59 +08:00

40 lines
1.3 KiB
TypeScript

"use client";
import { useMemo, useSyncExternalStore } from "react";
import { loadJson, saveJson } from "./storage";
const KEY = "social-roster-likes";
const CHANGE = "social-roster-likes-changed";
function readLikes(): Record<string, boolean> {
const value = loadJson<unknown>(KEY, {});
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
return Object.fromEntries(Object.entries(value).filter(([, liked]) => liked === true));
}
function subscribe(callback: () => void) {
window.addEventListener("storage", callback);
window.addEventListener(CHANGE, callback);
return () => {
window.removeEventListener("storage", callback);
window.removeEventListener(CHANGE, callback);
};
}
const snapshot = () => JSON.stringify(readLikes());
const serverSnapshot = () => "{}";
export function setRosterLike(id: string, liked: boolean) {
const next = readLikes();
if (liked) next[id] = true;
else delete next[id];
saveJson(KEY, next);
window.dispatchEvent(new Event(CHANGE));
}
/** One local follow list shared by discovery, profiles, homepage and swiping. */
export function useRosterLikes() {
const value = useSyncExternalStore(subscribe, snapshot, serverSnapshot);
return useMemo(() => JSON.parse(value) as Record<string, boolean>, [value]);
}