{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "form-changes",
  "title": "Form changes",
  "description": "What a Kino Form has changed since it was last saved, read from the form's own values, and everything a save bar does besides how it looks: Discard and Save, the shortcut, the guard on leaving, the announcements and where focus goes. The Save bar's.",
  "dependencies": [
    "@ui-sdk/core"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/field.json",
    "https://kinoui.com/r/announce.json",
    "https://kinoui.com/r/refuse.json",
    "https://kinoui.com/r/resize.json",
    "https://kinoui.com/r/scroll.json"
  ],
  "files": [
    {
      "path": "registry/lib/form-changes.tsx",
      "content": "'use client'\n\nimport {\n  type FormStatus,\n  formValues,\n  useFormSubmission,\n} from '@/registry/components/kino/field'\nimport { announce } from '@/registry/lib/announce'\nimport { refuse } from '@/registry/lib/refuse'\nimport { transitionsQuiet } from '@/registry/lib/resize'\nimport { revealBehavior } from '@/registry/lib/scroll'\nimport { shortcuts } from '@ui-sdk/core/shortcuts'\nimport {\n  type FocusEvent as ReactFocusEvent,\n  type KeyboardEvent as ReactKeyboardEvent,\n  type RefObject,\n  useCallback,\n  useEffect,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from 'react'\n\n/*\n * What a form has changed since it was last saved, read from what it sends:\n * its FormData, with every named control it holds, so a box that is off\n * still counts. The values the form starts with, and those of each save\n * that works, are the baseline; a control that appears later joins it as it\n * is. The Save bar's.\n */\n\ntype Values = Map<string, unknown>\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    Object.getPrototypeOf(value) === Object.prototype\n  )\n}\n\nfunction isBlank(value: unknown) {\n  return (\n    value === undefined ||\n    value === null ||\n    value === '' ||\n    // What an empty file input sends: a new one each time it is read.\n    (typeof File !== 'undefined' && value instanceof File && !value.name && !value.size)\n  )\n}\n\n/**\n * What a form sends, by name, in the order it holds its controls: a named\n * control that sends nothing, such as a box that is off, is blank.\n */\nexport function formState(form: HTMLFormElement): Values {\n  const values: Values = new Map()\n  for (const control of form.elements) {\n    const name = control.getAttribute('name')\n    if (name && !values.has(name)) values.set(name, '')\n  }\n  for (const [name, value] of Object.entries(formValues(form))) {\n    values.set(name, value)\n  }\n  return values\n}\n\n/** Where a hook outside a Kino Form reads its form from: nowhere. */\nconst noForm: RefObject<HTMLFormElement | null> = { current: null }\n\n/** Whether two field values are the same: equal, both blank, or arrays and plain objects whose items are. */\nexport function sameValue(a: unknown, b: unknown): boolean {\n  if (Object.is(a, b) || (isBlank(a) && isBlank(b))) return true\n  if (Array.isArray(a) && Array.isArray(b)) {\n    return a.length === b.length && a.every((item, index) => sameValue(item, b[index]))\n  }\n  if (isPlainObject(a) && isPlainObject(b)) {\n    const keys = Object.keys(a)\n    return (\n      keys.length === Object.keys(b).length &&\n      keys.every((key) => Object.hasOwn(b, key) && sameValue(a[key], b[key]))\n    )\n  }\n  return false\n}\n\n/**\n * The names whose value differs from the baseline's, in the order the form\n * holds them. A name the baseline doesn't have yet is added to it as it is,\n * so a field that appears later starts unchanged.\n */\nexport function changedNames(baseline: Values, values: Values): string[] {\n  const changed: string[] = []\n  for (const [name, value] of values) {\n    if (!baseline.has(name)) baseline.set(name, value)\n    else if (!sameValue(baseline.get(name), value)) changed.push(name)\n  }\n  return changed\n}\n\nfunction sameNames(a: readonly string[], b: readonly string[]) {\n  return a.length === b.length && a.every((name, index) => name === b[index])\n}\n\n/**\n * Whether a click on `link` leaves the page in this tab: a plain press on a\n * link to another page, not a new tab, a download or a jump within the page.\n */\nexport function leavesPage(\n  click: Pick<\n    MouseEvent,\n    'button' | 'metaKey' | 'ctrlKey' | 'shiftKey' | 'altKey' | 'defaultPrevented'\n  >,\n  link: { href: string; target: string; hasDownload: boolean },\n  here: string,\n): boolean {\n  if (click.defaultPrevented || click.button !== 0) return false\n  if (click.metaKey || click.ctrlKey || click.shiftKey || click.altKey) return false\n  if (link.hasDownload || (link.target !== '' && link.target !== '_self')) return false\n  const to = new URL(link.href, here)\n  const from = new URL(here)\n  if (!/^https?:$/.test(to.protocol)) return false\n  // Only the hash differs: it scrolls this page.\n  return !(\n    to.origin === from.origin &&\n    to.pathname === from.pathname &&\n    to.search === from.search &&\n    to.hash !== ''\n  )\n}\n\n/**\n * The names of the fields whose value differs from the last save, or from\n * where the form started, and whether they have been read since the last save\n * that worked: until then, they are the old ones. Inside a Kino Form, which\n * moves the baseline on each save that works, and reads again after a reset.\n */\nexport function useFormChanges() {\n  const submission = useFormSubmission()\n  const elementRef = submission?.formRef ?? noForm\n  const baseline = useRef<Values>(new Map())\n  const [changed, setChanged] = useState<string[]>([])\n  const read = useRef(() => {})\n  // How many saves the baseline holds, and how many the last read had.\n  const savesTaken = useRef(0)\n  const [savesRead, setSavesRead] = useState(0)\n\n  useEffect(() => {\n    const form = elementRef.current\n    if (!form) return undefined\n    let frame = 0\n    const readNow = () => {\n      frame = 0\n      const next = changedNames(baseline.current, formState(form))\n      setChanged((last) => (sameNames(last, next) ? last : next))\n      setSavesRead(savesTaken.current)\n    }\n    // A frame later, so a change that renders has rendered, and many changes are read once.\n    const schedule = () => {\n      if (!frame) frame = requestAnimationFrame(readNow)\n    }\n    read.current = schedule\n    readNow()\n    // Typing changes no markup; every other control's value shows in its attributes or text.\n    form.addEventListener('input', schedule, true)\n    form.addEventListener('change', schedule, true)\n    const observer = new MutationObserver(schedule)\n    observer.observe(form, {\n      subtree: true,\n      childList: true,\n      attributes: true,\n      characterData: true,\n    })\n    return () => {\n      cancelAnimationFrame(frame)\n      form.removeEventListener('input', schedule, true)\n      form.removeEventListener('change', schedule, true)\n      observer.disconnect()\n    }\n  }, [elementRef])\n\n  // What a save sent is the new baseline, even if the person typed on meanwhile.\n  const saved = submission?.saved\n  useEffect(() => {\n    if (!saved) return\n    // A name the save didn't send, such as a box that is off, was sent blank.\n    for (const name of baseline.current.keys()) {\n      baseline.current.set(name, saved.values[name] ?? '')\n    }\n    for (const [name, value] of Object.entries(saved.values)) {\n      baseline.current.set(name, value)\n    }\n    savesTaken.current = saved.count\n    read.current()\n  }, [saved])\n\n  return { changed, current: savesRead === (saved?.count ?? 0) }\n}\n\n/** Presses on a link a guard has stopped, which the other guards answer too. */\nconst answered = new WeakSet<Event>()\n\n/**\n * While `active`, a try to leave the page calls `onBlocked` instead: a link\n * pressed, or Back and Forward where the browser lets a page stop them.\n * Closing or reloading the tab asks the browser's own question.\n */\nexport function useLeaveGuard(active: boolean, onBlocked: () => void) {\n  const blocked = useRef(onBlocked)\n  useEffect(() => {\n    blocked.current = onBlocked\n  })\n  useEffect(() => {\n    if (!active) return undefined\n    const onBeforeUnload = (event: BeforeUnloadEvent) => {\n      event.preventDefault()\n      // Older browsers ask only when it's set; they show their own words.\n      event.returnValue = ''\n    }\n    // Before the router's own handler, which listens on the root it renders into.\n    const onClick = (event: MouseEvent) => {\n      const link = (event.target as Element | null)?.closest?.('a[href]')\n      if (!(link instanceof HTMLAnchorElement)) return\n      // Another form's guard may have stopped it first: each one with changes says no.\n      const stopped = answered.has(event)\n      const leaves = leavesPage(\n        {\n          button: event.button,\n          metaKey: event.metaKey,\n          ctrlKey: event.ctrlKey,\n          shiftKey: event.shiftKey,\n          altKey: event.altKey,\n          defaultPrevented: event.defaultPrevented && !stopped,\n        },\n        {\n          href: link.href,\n          target: link.target,\n          hasDownload: link.hasAttribute('download'),\n        },\n        window.location.href,\n      )\n      if (!leaves) return\n      answered.add(event)\n      event.preventDefault()\n      event.stopPropagation()\n      blocked.current()\n    }\n    const navigation = (window as { navigation?: EventTarget }).navigation\n    const onNavigate = (event: Event) => {\n      const navigate = event as Event & {\n        navigationType?: string\n        hashChange?: boolean\n      }\n      if (navigate.navigationType !== 'traverse' || navigate.hashChange) return\n      if (!navigate.cancelable) return\n      event.preventDefault()\n      blocked.current()\n    }\n    window.addEventListener('beforeunload', onBeforeUnload)\n    document.addEventListener('click', onClick, true)\n    navigation?.addEventListener('navigate', onNavigate)\n    return () => {\n      window.removeEventListener('beforeunload', onBeforeUnload)\n      document.removeEventListener('click', onClick, true)\n      navigation?.removeEventListener('navigate', onNavigate)\n    }\n  }, [active])\n}\n\n/** Where a save bar is: what it says, and whether it shows. */\ntype SaveBarView = 'changed' | 'saving' | 'saved' | 'failed' | 'blocked'\n\n/**\n * Whether ⌘S pressed at a place is this form's to save: pressed in the form\n * or in its own bar, which sits outside it, or anywhere outside every form\n * and bar.\n */\nexport function ownsSaveShortcut(press: {\n  inForm: boolean\n  inBar: boolean\n  inOtherForm: boolean\n  inOtherBar: boolean\n}) {\n  if (press.inForm || press.inBar) return true\n  return !(press.inOtherForm || press.inOtherBar)\n}\n\n/** What a save bar says in each view, for the screen reader and on the bar. */\nconst SAVE_BAR_TEXT: Record<SaveBarView, string> = {\n  changed: 'Unsaved changes',\n  saving: 'Saving changes',\n  saved: 'Changes saved',\n  failed: \"Couldn't save\",\n  blocked: 'Save or discard first',\n}\n\n/** The controls in `form` that can take focus, outside its save bar. */\nfunction formControls(form: HTMLElement | null, bar: HTMLElement | null) {\n  return [...(form?.querySelectorAll<HTMLElement>(CONTROLS) ?? [])].filter(\n    (control) => !bar?.contains(control),\n  )\n}\n\n/** The bars open now, in the order they opened. */\nconst stacked: { box: HTMLElement; element: HTMLElement }[] = []\n\n/** The space between two stacked bars, in px. */\nconst STACK_GAP = 8\n\n/** Lifts each open bar above the ones that opened before it; a bar placed in the page rather than on the screen takes no part. */\nfunction restack() {\n  let lift = 0\n  for (const { box, element } of stacked) {\n    if (getComputedStyle(box).position !== 'fixed') continue\n    box.style.setProperty('--save-bar-stack', `${lift}px`)\n    lift += element.offsetHeight + STACK_GAP\n  }\n}\n\n/** What can take focus, for handing focus back by its place, and on around a bar that renders away from its form. */\nconst CONTROLS =\n  'a[href], input:not([type=hidden]):not([disabled]), textarea:not([disabled]), select:not([disabled]), button:not([disabled]), [tabindex]:not([tabindex=\"-1\"])'\n\n/**\n * The element Tab reaches before or after `from` in the page's order,\n * outside every element in `skip`: shown, not inert, and not taken out of\n * the Tab order, as a list's unpicked tabs are.\n */\nfunction tabNeighbour(from: Element, after: boolean, skip: (Element | null)[]) {\n  const all = [...from.ownerDocument.querySelectorAll<HTMLElement>(CONTROLS)].filter(\n    (element) =>\n      element !== from &&\n      element.tabIndex >= 0 &&\n      !skip.some((part) => part?.contains(element)) &&\n      element.getClientRects().length > 0 &&\n      !element.closest('[inert]'),\n  )\n  const following = (element: Element) =>\n    Boolean(from.compareDocumentPosition(element) & Node.DOCUMENT_POSITION_FOLLOWING)\n  return after ? all.find(following) : all.findLast((element) => !following(element))\n}\n\ninterface Box {\n  top: number\n  bottom: number\n  left: number\n  right: number\n}\n\n/**\n * How far a control must keep from the screen's edge to clear a fixed bar on\n * that edge, with a little room: the bar's edge and the scroll margin for it,\n * or `null` when the bar doesn't cover the control.\n */\nexport function clearance(\n  control: Box,\n  bar: Box,\n  screenHeight: number,\n  room = 8,\n): { side: 'top' | 'bottom'; size: number } | null {\n  const across = control.left < bar.right && control.right > bar.left\n  const down = control.top < bar.bottom && control.bottom > bar.top\n  if (!across || !down) return null\n  const onBottom = bar.top + bar.bottom > screenHeight\n  return onBottom\n    ? { side: 'bottom', size: screenHeight - bar.top + room }\n    : { side: 'top', size: bar.bottom + room }\n}\n\n/**\n * Everything a save bar does besides how it looks, for the Save bar inside a\n * Kino Form: whether it shows, what it says, Discard and Save, ⌘S, the leave\n * guard with its swell, the announcements, and where focus goes when it\n * leaves with focus inside.\n */\nexport function useSaveBar({\n  frame,\n  onDiscard,\n  container,\n}: {\n  /** The fixed box the bar sits in: it takes the form's `--save-bar-left` and `--save-bar-width`, so the bar lines up with the form. */\n  frame: RefObject<HTMLElement | null>\n  onDiscard?: () => void\n  /** Where the bar renders, in place of the end of the page. */\n  container?: HTMLElement | null\n}) {\n  const submission = useFormSubmission()\n  const elementRef = submission?.formRef ?? noForm\n  // The bar's element, which says no, and which focus leaves as it goes. As\n  // state too: it mounts after its form, outside it, once the page has loaded.\n  const bar = useRef<HTMLElement | null>(null)\n  const [barElement, setBarElement] = useState<HTMLElement | null>(null)\n  const barRef = useCallback((node: HTMLElement | null) => {\n    bar.current = node\n    setBarElement(node)\n  }, [])\n  const status: FormStatus = submission?.status ?? 'idle'\n  const { changed: changes, current } = useFormChanges()\n  const changed = changes.length > 0\n  // A save that worked is still saving until the changes are read against it.\n  const saving = status === 'saving' || (status === 'saved' && !current)\n  // Once a save has worked, the bar stays to say so until its words have\n  // changed, then leaves: never with the old words still on it.\n  const savedCount = submission?.saved?.count ?? 0\n  const [released, setReleased] = useState(0)\n  const holding = status === 'saved' && current && !changed && released !== savedCount\n  const open = changed || saving || holding\n\n  // The warning holds until a new change, a save or a discard answers it.\n  const moment = [\n    status,\n    submission?.revision ?? 0,\n    submission?.saved?.count ?? 0,\n    ...changes,\n  ].join('\\u0000')\n  const [blockedAt, setBlockedAt] = useState<string | null>(null)\n  const blocked = blockedAt === moment\n\n  const view: SaveBarView = saving\n    ? 'saving'\n    : blocked\n      ? 'blocked'\n      : status === 'failed'\n        ? 'failed'\n        : status === 'saved' && !changed\n          ? 'saved'\n          : 'changed'\n\n  useEffect(() => {\n    const element = bar.current\n    if (!holding || !element) return undefined\n    let cancelled = false\n    void transitionsQuiet(element, { subtree: true }).then(() => {\n      if (!cancelled) setReleased(savedCount)\n    })\n    return () => {\n      cancelled = true\n    }\n  }, [holding, savedCount])\n\n  // Said once each time it changes: the bar showing, a save starting, a\n  // failure, and the save done.\n  const said = useRef<{ open: boolean; status: FormStatus; view: SaveBarView }>({\n    open: false,\n    status,\n    view,\n  })\n  useEffect(() => {\n    const last = said.current\n    said.current = { open, status, view }\n    if (status !== last.status && status === 'saving') announce(SAVE_BAR_TEXT.saving)\n    else if (status !== last.status && status === 'failed') announce(SAVE_BAR_TEXT.failed)\n    else if (view === 'saved' && last.view !== 'saved' && open)\n      announce(SAVE_BAR_TEXT.saved)\n    else if (open && !last.open) announce(SAVE_BAR_TEXT.changed)\n  }, [open, status, view])\n\n  // The control the person last used in the form, to hand focus back to, and\n  // its place among the form's controls, which a discard's remount keeps.\n  const lastControl = useRef<{ element: HTMLElement; index: number } | null>(null)\n\n  // A control the fixed bar covers is scrolled clear of it, as the Tabs reveal\n  // a tab, so focus is never hidden under the bar.\n  const clear = (control: Element) => {\n    const box = frame.current?.getBoundingClientRect()\n    if (!box || !(control instanceof HTMLElement)) return\n    const margin = clearance(control.getBoundingClientRect(), box, window.innerHeight)\n    if (!margin) return\n    const property =\n      margin.side === 'bottom' ? 'scroll-margin-bottom' : 'scroll-margin-top'\n    const before = control.style.getPropertyValue(property)\n    control.style.setProperty(property, `${margin.size}px`)\n    control.scrollIntoView({\n      block: 'nearest',\n      behavior: revealBehavior(control),\n    })\n    control.style.setProperty(property, before)\n  }\n  const clearRef = useRef(clear)\n  useEffect(() => {\n    clearRef.current = clear\n  })\n\n  useEffect(() => {\n    const form = elementRef.current\n    if (!form) return undefined\n    const onFocusIn = (event: FocusEvent) => {\n      const target = event.target\n      if (!(target instanceof HTMLElement) || bar.current?.contains(target)) return\n      lastControl.current = {\n        element: target,\n        index: formControls(form, bar.current).indexOf(target),\n      }\n      if (bar.current?.hasAttribute('data-open')) clearRef.current(target)\n    }\n    form.addEventListener('focusin', onFocusIn)\n    return () => form.removeEventListener('focusin', onFocusIn)\n  }, [elementRef])\n\n  // Arriving under the control in use, as it can on the first change, it moves that control clear.\n  useEffect(() => {\n    const active = document.activeElement\n    if (open && active && elementRef.current?.contains(active)) clearRef.current(active)\n  }, [open, elementRef])\n\n  // Leaving with focus inside, it hands focus back to that control, or to its\n  // remounted self after a discard, so focus never falls to the page.\n  useLayoutEffect(() => {\n    if (open) return\n    const element = bar.current\n    if (!element?.contains(document.activeElement)) return\n    const last = lastControl.current\n    const all = formControls(elementRef.current, element)\n    const back =\n      (last?.element.isConnected ? last.element : null) ??\n      (last && last.index >= 0 ? all[last.index] : undefined) ??\n      all[0]\n    back?.focus({ preventScroll: true })\n  }, [open, elementRef])\n\n  // Fixed to the screen, it lines up with the form across.\n  useLayoutEffect(() => {\n    const box = frame.current\n    const form = elementRef.current\n    if (!form || !box || !barElement) return undefined\n    const place = () => {\n      const { left, width } = form.getBoundingClientRect()\n      box.style.setProperty('--save-bar-left', `${left}px`)\n      box.style.setProperty('--save-bar-width', `${width}px`)\n    }\n    place()\n    const observer = new ResizeObserver(place)\n    observer.observe(form)\n    window.addEventListener('resize', place)\n    return () => {\n      observer.disconnect()\n      window.removeEventListener('resize', place)\n    }\n    // Again as it opens, in case the form moved across without changing size.\n  }, [frame, open, elementRef, barElement])\n\n  const block = () => {\n    setBlockedAt(moment)\n    announce(SAVE_BAR_TEXT.blocked)\n    if (!bar.current) return\n    // The swell the Alert dialog answers a press outside with.\n    refuse(bar.current)\n  }\n  useLeaveGuard(changed, block)\n\n  // ⌘S or Ctrl+S saves this form when pressed in it, or outside every form;\n  // pressed in another form, it is that form's. Behind a dialog, it is the dialog's.\n  useEffect(() => {\n    const form = elementRef.current\n    if (!changed || saving || !form) return undefined\n    return shortcuts.register('mod+s', () => form.requestSubmit(), {\n      layer: form,\n      when: () => {\n        const focused = document.activeElement\n        return ownsSaveShortcut({\n          inForm: focused !== null && form.contains(focused),\n          inBar: focused !== null && !!bar.current?.contains(focused),\n          inOtherForm: !!focused?.closest('form'),\n          inOtherBar: !!focused?.closest('[data-slot=save-bar]'),\n        })\n      },\n    })\n  }, [changed, saving, elementRef])\n\n  // Named after its form, so two bars on a page tell themselves apart.\n  useLayoutEffect(() => {\n    const element = barElement\n    const form = elementRef.current\n    if (!form || !element) return\n    const name =\n      form.getAttribute('aria-label') ??\n      document.getElementById(form.getAttribute('aria-labelledby') ?? '')?.textContent ??\n      null\n    element.setAttribute(\n      'aria-label',\n      name ? `${name}: ${SAVE_BAR_TEXT.changed.toLowerCase()}` : SAVE_BAR_TEXT.changed,\n    )\n  }, [barElement, elementRef])\n\n  // Two bars open at once stack, the first on the bottom.\n  useLayoutEffect(() => {\n    const box = frame.current\n    const element = bar.current\n    if (!open || !box || !element) return undefined\n    const entry = { box, element }\n    stacked.push(entry)\n    restack()\n    return () => {\n      stacked.splice(stacked.indexOf(entry), 1)\n      restack()\n    }\n  }, [open, frame, barElement])\n\n  // Where it renders, known once the page has loaded (it starts hidden, so\n  // nothing shows late): in place inside a popup, such as a Dialog, which\n  // ui-sdk opens in the top layer and which keeps focus in; otherwise away from\n  // the form, at the end of the page or in `container`.\n  const anchor = useRef<HTMLSpanElement | null>(null)\n  const guard = useRef<HTMLSpanElement | null>(null)\n  const [target, setTarget] = useState<HTMLElement | 'here' | null>(null)\n  useLayoutEffect(() => {\n    const here = anchor.current\n    if (!here) return\n    setTarget(here.closest('[popover]') ? 'here' : (container ?? here.ownerDocument.body))\n  }, [container])\n  const into = target !== null && target !== 'here' ? target : null\n  const away = into !== null\n\n  // Away from its form, the guard in the form's place sends focus into it:\n  // to Discard from the form or before it, to Save with Shift+Tab from after.\n  const onGuardFocus = (event: ReactFocusEvent<HTMLSpanElement>) => {\n    const buttons = frame.current?.querySelectorAll<HTMLElement>('button')\n    if (!buttons?.length) return\n    const related = event.relatedTarget instanceof Node ? event.relatedTarget : null\n    const fromBefore = Boolean(\n      related &&\n      (elementRef.current?.contains(related) ||\n        event.currentTarget.compareDocumentPosition(related) &\n          Node.DOCUMENT_POSITION_PRECEDING),\n    )\n    ;(fromBefore ? buttons[0] : buttons[buttons.length - 1]).focus()\n  }\n  // Its buttons are then out of the page's own Tab order, which would reach\n  // them again at the end of the page: it moves focus itself, from Discard\n  // to Save, and from either end back to the form's side.\n  const onButtonKeyDown =\n    (edge: 'first' | 'last') => (event: ReactKeyboardEvent<HTMLButtonElement>) => {\n      if (event.key !== 'Tab' || !away) return\n      const buttons = frame.current?.querySelectorAll<HTMLElement>('button')\n      const from = anchor.current\n      if (!buttons?.length || !from || !frame.current) return\n      const inward = event.shiftKey ? edge === 'last' : edge === 'first'\n      // Past the bar's own guard, which would send focus straight back in.\n      const next = inward\n        ? buttons[edge === 'first' ? 1 : 0]\n        : tabNeighbour(from, !event.shiftKey, [frame.current, guard.current])\n      if (!next) return\n      event.preventDefault()\n      next.focus()\n    }\n\n  const discard = () => {\n    submission?.reset()\n    onDiscard?.()\n    announce('Changes discarded')\n  }\n\n  return {\n    /** For the bar's element. */\n    barRef,\n    open,\n    view,\n    text: SAVE_BAR_TEXT[view],\n    /** Every text it can say, so the bar can keep room for the longest and never change width. */\n    texts: SAVE_BAR_TEXT,\n    saving,\n    /** Whether Discard and Save are off: while it saves, and as it leaves once saved. */\n    locked: saving || view === 'saved',\n    discard,\n    /** Where the bar renders, and how focus goes round it when that is away from its form. */\n    placement: {\n      /** Whether it renders in place, inside a top-layer popup; `false` until the page has loaded. */\n      here: target === 'here',\n      /** The element it renders into away from its form, or `null` in place or until the page has loaded. */\n      into,\n      away,\n      /** For a hidden element in the form's place. */\n      anchorRef: anchor,\n      /** For the focus guard in the form's place, while the bar shows away from it. */\n      guardRef: guard,\n      onGuardFocus,\n      onButtonKeyDown,\n      /** The form's id, for Save's `form`. */\n      formId: submission?.formId,\n    },\n  }\n}\n\nexport type { SaveBarView }\n",
      "type": "registry:lib",
      "target": "@lib/form-changes.tsx"
    }
  ],
  "type": "registry:lib"
}