Files
o2o-castad-frontend/src/utils/playreelPrefs.ts
T

73 lines
2.8 KiB
TypeScript

import { useSyncExternalStore } from 'react';
import { GateKey } from './playreelApi';
/**
* 롱컷 게이트 자동 승인 설정 — playreel 원본(`lib/prefs.ts`)과 같은 방식이다.
*
* 대상은 되돌릴 수 있는 게이트(① 수집 확인, ③ 나레이션 확인)뿐이다.
* ②·④·⑤ 는 크레딧을 쓰거나 결과를 고정하는 비가역 단계라 항상 사람이 확인한다.
*
* 브라우저 localStorage 에만 저장하고 서버에는 보내지 않는다. `storageKeys.K` 에 넣지 않은 것도
* 의도적이다 — 그쪽 키는 새 프로젝트·로그아웃 때 지워지는데, 이건 사용자의 취향이라
* 생성할 때마다 다시 켜게 만들면 안 된다.
*/
export const AUTO_APPROVABLE = ['fetch_confirm', 'narration_confirm'] as const satisfies readonly GateKey[];
export type AutoApprovable = (typeof AUTO_APPROVABLE)[number];
export type AutoApprovePrefs = Partial<Record<AutoApprovable, boolean>>;
export const isAutoApprovable = (gate: GateKey | null | undefined): gate is AutoApprovable =>
!!gate && (AUTO_APPROVABLE as readonly string[]).includes(gate);
const STORAGE_KEY = 'castad_playreel_auto_approve';
const CHANGE_EVENT = 'castad:playreel-prefs';
const EMPTY: AutoApprovePrefs = {};
// useSyncExternalStore 는 같은 값이면 같은 참조를 돌려줘야 한다
let cache: { raw: string | null; value: AutoApprovePrefs } = { raw: null, value: EMPTY };
export function readAutoApprove(): AutoApprovePrefs {
let raw: string | null = null;
try {
raw = localStorage.getItem(STORAGE_KEY);
} catch {
return EMPTY; // 저장소를 못 쓰면 항상 사람이 확인한다
}
if (raw === cache.raw) return cache.value;
let value: AutoApprovePrefs = EMPTY;
try {
const parsed = raw ? JSON.parse(raw) : {};
value = Object.fromEntries(
AUTO_APPROVABLE.filter((gate) => parsed?.[gate] === true).map((gate) => [gate, true]),
);
} catch {
/* 깨진 값은 꺼진 것으로 본다 */
}
cache = { raw, value };
return value;
}
export function setAutoApprove(gate: AutoApprovable, on: boolean): void {
const next = { ...readAutoApprove() };
if (on) next[gate] = true;
else delete next[gate];
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
} catch {
/* 프라이빗 모드 등 — 이 세션에서만 유지되지 않는다 */
}
window.dispatchEvent(new Event(CHANGE_EVENT));
}
function subscribe(onChange: () => void): () => void {
window.addEventListener(CHANGE_EVENT, onChange);
window.addEventListener('storage', onChange); // 다른 탭에서 바꾼 경우
return () => {
window.removeEventListener(CHANGE_EVENT, onChange);
window.removeEventListener('storage', onChange);
};
}
export function useAutoApprove(): AutoApprovePrefs {
return useSyncExternalStore(subscribe, readAutoApprove, () => EMPTY);
}