import { shadowHost } from "../core/dom/shadow-host"; import { keepingFocus, type Keeping } from "./keep"; type ReadState = (root: ShadowRoot) => string | null; type CaptureState = (root: ShadowRoot) => ReadState | null; type NativeKind = "checkbox" | "radio"; const controls = (root: ShadowRoot, kind: NativeKind): HTMLInputElement[] => Array.from(root.querySelectorAll(`input[part~=input][type=${kind}]`)); const canEdit = (element: Element): boolean => !element.matches("[disabled],[readonly],:disabled"); /** A restore goes through the quiet form path, including its one form sync. */ export const keepingChecked = (capture: CaptureState, kind: NativeKind = "checkbox"): Keeping => keepingFocus({ capture(root, expire) { const sourceHost = shadowHost(root); if (!sourceHost || !canEdit(sourceHost)) return null; const read = capture(root); if (!read) return null; queueMicrotask(expire); return target => { const host = shadowHost(target); if (!host || !canEdit(host)) return false; const state = read(target); if (state === null) return false; (host as HTMLElement & { formStateRestoreCallback(state: string): void }).formStateRestoreCallback(state); return true; }; }, }, node => node.matches(`input[part~=input][type=${kind}]`) ? kind === "radio" ? node.getAttribute("value") : "checked-control" : null); export const checkboxEdit = (root: ShadowRoot): ReadState | null => { const [input, extra] = controls(root, "checkbox"); if (!input || extra || !canEdit(input) || input.checked === input.defaultChecked) return null; const state = input.checked ? "checked" : "unchecked"; return target => { const [control, extra] = controls(target, "checkbox"); return control && !extra && canEdit(control) ? state : null; }; }; const byKey = (inputs: readonly HTMLInputElement[], key: string): HTMLInputElement[] => inputs.filter(input => input.getAttribute("value") === key); export const radioEdit = ( root: ShadowRoot, optionKeys: readonly string[], ): ReadState | null => { const inputs = controls(root, "radio"); if (!inputs.some(input => canEdit(input) && input.checked !== input.defaultChecked)) return null; const [selected, extra] = inputs.filter(input => input.checked); if (extra || (selected && !canEdit(selected))) return null; if (!selected) return target => { const current = controls(target, "radio"); return current.some(canEdit) && !current.some(input => input.checked && !canEdit(input)) ? "" : null; }; // Match the selected input to a declared option. Only the option key crosses // the upgrade, so there is never a read of a native input's live value. const key = optionKeys.find(value => value && byKey(inputs, value).length === 1 && selected.getAttribute("value") === value); if (key === undefined || optionKeys.filter(value => value === key).length !== 1) return null; return target => { const [control, extra] = byKey(controls(target, "radio"), key); return control && !extra && canEdit(control) ? key : null; }; };