import { memo, useCallback, useEffect, useRef, useState } from "react"; import type { BlockParam } from "@hyperframes/core/registry"; import { useFileManagerContextOptional } from "../../contexts/FileManagerContext"; import { useStudioPlaybackContext } from "../../contexts/StudioContext"; import { trackBlockParamCommit } from "../../telemetry/events"; import { serializeStudioFileMutation } from "../../utils/studioFileMutationCoordinator"; interface BlockParamsPanelProps { blockName: string; blockTitle: string; params: BlockParam[]; compositionPath: string; onClose: () => void; } type CommitState = { tone: "idle" | "saving" | "saved" | "error"; message?: string }; export const BlockParamsPanel = memo(function BlockParamsPanel({ blockName, blockTitle, params, compositionPath, onClose, }: BlockParamsPanelProps) { const fileManager = useFileManagerContextOptional(); const { setRefreshKey } = useStudioPlaybackContext(); const [values, setValues] = useState>(() => { const initial: Record = {}; for (const p of params) { initial[p.key] = p.default; } return initial; }); // Last value actually written to the block file per param — the literal we // substitute when the next commit rewrites the file. const appliedRef = useRef>( Object.fromEntries(params.map((p) => [p.key, p.default])), ); const [commitState, setCommitState] = useState({ tone: "idle" }); // Per-param debounce timers: a single shared timer would let a second // param's edit silently cancel the first param's pending commit. const commitTimersRef = useRef>>(new Map()); const commitParamNow = useCallback( async (key: string, nextValue: string) => { if (!fileManager) return; const previous = appliedRef.current[key]; if (previous === undefined || previous === nextValue || !nextValue.trim()) return; setCommitState({ tone: "saving" }); try { const content = await fileManager.readProjectFile(compositionPath); // Token-boundary match so "#0c0c0c" never rewrites part of "#0c0c0cff". const matcher = new RegExp( `(? 1) { setCommitState({ tone: "error", message: `"${previous}" appears ${matches}× in ${compositionPath}. The panel can't tell which one belongs to this parameter, so it won't risk changing unrelated content. Edit the file directly to disambiguate.`, }); trackBlockParamCommit({ tone: "error", blockName, key }); return; } await fileManager.writeProjectFile( compositionPath, content.replace(matcher, nextValue), content, ); appliedRef.current[key] = nextValue; setCommitState({ tone: "saved" }); trackBlockParamCommit({ tone: "saved", blockName, key }); setRefreshKey((k) => k + 1); } catch { setCommitState({ tone: "error", message: "Couldn't save the block file. Retry?" }); trackBlockParamCommit({ tone: "error", blockName, key }); } }, [fileManager, compositionPath, setRefreshKey, blockName], ); // Commits join the file's queue: two read-modify-writes of one file must not interleave. const commitParam = useCallback( (key: string, nextValue: string) => fileManager ? serializeStudioFileMutation(fileManager.writeProjectFile, compositionPath, () => commitParamNow(key, nextValue), ) : Promise.resolve(), [commitParamNow, compositionPath, fileManager], ); const handleChange = useCallback( (key: string, value: string) => { setValues((prev) => ({ ...prev, [key]: value })); const timers = commitTimersRef.current; const existing = timers.get(key); if (existing) clearTimeout(existing); timers.set( key, setTimeout(() => { timers.delete(key); void commitParam(key, value); }, 300), ); }, [commitParam], ); // Flush (not discard) pending commits on unmount so closing the panel // within the debounce window doesn't silently drop the last edit. const flushRef = useRef<() => void>(() => {}); flushRef.current = () => { for (const [key, timer] of commitTimersRef.current) { clearTimeout(timer); const value = values[key]; if (value !== undefined) void commitParam(key, value); } commitTimersRef.current.clear(); }; useEffect(() => () => flushRef.current(), []); return (
{blockTitle}
Parameters
{params.length === 0 && (
This block has no editable parameters.
)} {!fileManager && params.length > 0 && (
Block params can't be edited here: no project file access.
)} {params.map((param) => ( handleChange(param.key, v)} /> ))} {commitState.tone === "saving" && (
Saving…
)} {commitState.tone === "saved" && (
Saved to {compositionPath}
)} {commitState.tone === "error" && (
{commitState.message}
)}
); }); function ParamControl({ param, value, disabled, onChange, }: { param: BlockParam; value: string; disabled?: boolean; onChange: (value: string) => void; }) { return (
{param.type === "color" && (
onChange(e.target.value)} className="w-7 h-7 rounded-sm border border-neutral-700 bg-transparent cursor-pointer disabled:cursor-not-allowed disabled:opacity-50" /> onChange(e.target.value)} className="flex-1 bg-neutral-900 border border-neutral-800 rounded-sm px-2 py-1 text-[10px] text-neutral-200 font-mono focus:outline-hidden focus:border-neutral-700 disabled:cursor-not-allowed disabled:opacity-50" />
)} {param.type === "number" && (
onChange(e.target.value)} className="flex-1 disabled:cursor-not-allowed disabled:opacity-50" /> {value}
)} {param.type === "text" && ( onChange(e.target.value)} className="w-full bg-neutral-900 border border-neutral-800 rounded-sm px-2 py-1 text-[10px] text-neutral-200 focus:outline-hidden focus:border-neutral-700 disabled:cursor-not-allowed disabled:opacity-50" /> )} {param.type === "select" && param.options && ( )}
); }