import { useCallback, useRef } from 'react'; const copy = (value: V): V => JSON.parse(JSON.stringify(value ?? null)) as V; /** * A `formOf` for useEditBaseline on a form whose controls adjust what was filled as they mount (a schedule control * fills in its defaults). Measured against the record's own form values, an untouched form would read as edited, so * a newer save would mark it changed instead of filling it. Once the form has settled on an opening, `settle` records * the form as it stands, and `formOf` answers with that for the same record; any other record is filled as usual. */ export const useSettledFormOf = (fill: (record: T) => D) => { const settled = useRef<{ record?: T; values?: D }>({}); const formOf = useCallback((record: T): D => (settled.current.record === record ? copy(settled.current.values as D) : fill(record)), [fill]); const settle = useCallback((record: T | undefined, values: D) => { settled.current = record ? { record, values: copy(values) } : {}; }, []); return { formOf, settle }; };