@funstack/ui 0.1.0-alpha.23 → 0.1.0-alpha.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/combobox/combobox-keyboard.mjs +2 -1
- package/dist/combobox/combobox-keyboard.mjs.map +1 -1
- package/dist/dialog/dialog-dismiss.mjs +2 -1
- package/dist/dialog/dialog-dismiss.mjs.map +1 -1
- package/dist/docs/components/field.md +2 -2
- package/dist/field/field-root.d.mts.map +1 -1
- package/dist/field/field-root.mjs +71 -16
- package/dist/field/field-root.mjs.map +1 -1
- package/dist/field/use-server-error-visibility.mjs +21 -6
- package/dist/field/use-server-error-visibility.mjs.map +1 -1
- package/dist/hover-card/use-hover-card-interest.mjs +4 -25
- package/dist/hover-card/use-hover-card-interest.mjs.map +1 -1
- package/dist/internal/escape-key.mjs +20 -0
- package/dist/internal/escape-key.mjs.map +1 -0
- package/dist/internal/overlay/open-layer.mjs +31 -0
- package/dist/internal/overlay/open-layer.mjs.map +1 -0
- package/dist/menubar/menubar.d.mts.map +1 -1
- package/dist/menubar/menubar.mjs +2 -1
- package/dist/menubar/menubar.mjs.map +1 -1
- package/dist/multi-select/multi-select-keyboard.mjs +2 -1
- package/dist/multi-select/multi-select-keyboard.mjs.map +1 -1
- package/dist/number-field/number-field-root.d.mts.map +1 -1
- package/dist/number-field/number-field-root.mjs +2 -1
- package/dist/number-field/number-field-root.mjs.map +1 -1
- package/dist/toast/toast-root.d.mts.map +1 -1
- package/dist/toast/toast-root.mjs +4 -1
- package/dist/toast/toast-root.mjs.map +1 -1
- package/dist/tooltip/use-tooltip-interaction.mjs +3 -2
- package/dist/tooltip/use-tooltip-interaction.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { flushSync } from "react-dom";
|
|
3
|
+
import { isComposingKey } from "../internal/escape-key.mjs";
|
|
3
4
|
import { isPopoverOpen } from "../internal/overlay/popover-open.mjs";
|
|
4
5
|
// src/combobox/combobox-keyboard.ts
|
|
5
6
|
/** The caret is at the start of the input with nothing selected. */
|
|
@@ -41,7 +42,7 @@ function createComboboxKeyDown({ disabled, loop, allowCustomValue, popover, opti
|
|
|
41
42
|
};
|
|
42
43
|
return (event) => {
|
|
43
44
|
if (disabled || event.ctrlKey || event.metaKey) return false;
|
|
44
|
-
if (event
|
|
45
|
+
if (isComposingKey(event)) return false;
|
|
45
46
|
const isOpen = isPopoverOpen(popover.popupRef.current);
|
|
46
47
|
switch (event.key) {
|
|
47
48
|
case "ArrowDown":
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"combobox-keyboard.mjs","names":[],"sources":["../../src/combobox/combobox-keyboard.ts"],"sourcesContent":["\"use client\";\nimport { flushSync } from \"react-dom\";\nimport { isPopoverOpen } from \"../internal/overlay/popover-open.js\";\nimport type { RefObject } from \"react\";\nimport type { PopoverRootValue } from \"../internal/overlay/use-overlay-root.js\";\nimport type { ActiveOption } from \"../internal/use-active-option.js\";\nimport type { OptionRegistry } from \"../internal/use-option-registry.js\";\n\nexport interface ComboboxKeyboardOptions {\n /** The Root's `disabled`, `loop` and `allowCustomValue`. */\n readonly disabled: boolean;\n readonly loop: boolean;\n readonly allowCustomValue: boolean;\n readonly popover: Pick<\n PopoverRootValue,\n \"popupRef\" | \"requestOpen\" | \"requestClose\" | \"intended\" | \"committed\"\n >;\n readonly options: Pick<OptionRegistry, \"registry\" | \"orderedOptions\">;\n readonly active: Pick<ActiveOption, \"activeRef\" | \"setActive\" | \"pendingEdgeRef\">;\n /** Accepts an option (design 5.2). */\n readonly accept: (optionValue: string, event: Event) => void;\n /** Free text as the value (design 5.3). Returns whether it dispatched. */\n readonly commitText: (event: Event, close: boolean) => boolean;\n /** With `multiple` (design 15.6): the keys that differ, and the chips. */\n readonly multiple: ComboboxMultipleKeys | undefined;\n}\n\n/** What the Input's keys need from a `multiple` Root (design 15.6, 15.9). */\nexport interface ComboboxMultipleKeys {\n /** The text (urgent). */\n readonly textRef: RefObject<string>;\n /** At least one value is selected (optimistic): there is a chip. */\n readonly hasChips: () => boolean;\n /** Backspace in the empty input: remove the last chip and announce it. */\n readonly removeLast: (event: Event) => void;\n /** The inline-start arrow at the caret's start: focus the last chip. `false`: none mounted. */\n readonly focusLastChip: () => boolean;\n /** `allowCustomValue`: add the text as a value (or nothing if it is one) and clear it. */\n readonly addText: (event: Event) => void;\n /** Clear unmatched text (`\"dismiss\"`). */\n readonly clearText: (event: Event) => void;\n}\n\n/** The caret is at the start of the input with nothing selected. */\nfunction caretAtStart(target: EventTarget | null): boolean {\n if (!(target instanceof HTMLInputElement)) return false;\n return target.selectionStart === 0 && target.selectionEnd === 0;\n}\n\n/** ArrowLeft, or ArrowRight when the input's computed direction is `rtl` (design 15.6). */\nfunction isInlineStartArrow(event: KeyboardEvent): boolean {\n const target = event.target;\n const rtl =\n target instanceof Element &&\n target.ownerDocument.defaultView?.getComputedStyle(target).direction === \"rtl\";\n return event.key === (rtl ? \"ArrowRight\" : \"ArrowLeft\");\n}\n\n/**\n * The keyboard model of the Combobox Input (design/components/combobox.md 8), the counterpart of\n * `menu/use-menu-keyboard.ts`. A plain factory, not a hook (it calls none): the Root calls it on\n * every render. Returns the Input's `keydown` handler, which tells whether it handled the key.\n */\nexport function createComboboxKeyDown({\n disabled,\n loop,\n allowCustomValue,\n popover,\n options,\n active,\n accept,\n commitText,\n multiple,\n}: ComboboxKeyboardOptions): (event: KeyboardEvent) => boolean {\n const { registry, orderedOptions } = options;\n const { activeRef, setActive, pendingEdgeRef } = active;\n\n const move = (direction: 1 | -1): void => {\n const enabled = orderedOptions().filter((option) => !option.disabled);\n if (enabled.length === 0) return;\n const last = enabled.length - 1;\n const index = enabled.findIndex((option) => option.value === activeRef.current);\n let next: number;\n if (direction === 1) next = index < 0 ? 0 : index >= last ? (loop ? 0 : last) : index + 1;\n else next = index < 0 ? last : index <= 0 ? (loop ? last : 0) : index - 1;\n const target = enabled[next]!;\n setActive(target.value);\n if (typeof target.element.scrollIntoView === \"function\") {\n target.element.scrollIntoView({ block: \"nearest\" });\n }\n };\n\n const activeEnabled = (): string | null => {\n const current = activeRef.current;\n if (current === null) return null;\n const entry = registry.get(current);\n return entry !== undefined && !entry.disabled ? current : null;\n };\n\n return (event: KeyboardEvent): boolean => {\n if (disabled || event.ctrlKey || event.metaKey) return false;\n // IME: the key belongs to the composition (Enter commits it, arrows pick a candidate).\n if (event.isComposing || event.keyCode === 229) return false;\n // What the user sees, not what is intended: right after Escape the platform has hidden the\n // popup but its `toggle` (and the fact it reports) is still queued, and an open that\n // is still committing shows nothing yet. Enter must submit and arrows must open in both.\n const isOpen = isPopoverOpen(popover.popupRef.current);\n switch (event.key) {\n case \"ArrowDown\":\n event.preventDefault();\n if (event.altKey) {\n if (!isOpen) popover.requestOpen(event, \"activate\");\n } else if (!isOpen) {\n pendingEdgeRef.current = \"first\";\n popover.requestOpen(event, \"activate\");\n } else {\n move(1);\n }\n return true;\n case \"ArrowUp\":\n event.preventDefault();\n if (event.altKey) {\n if (isOpen && multiple !== undefined) {\n // A pick toggles and does not close: Alt+ArrowUp only closes (design 15.6).\n popover.requestClose(event, \"activate\");\n } else if (isOpen) {\n const current = activeEnabled();\n if (current !== null) accept(current, event);\n else popover.requestClose(event, \"activate\");\n }\n } else if (!isOpen) {\n pendingEdgeRef.current = \"last\";\n popover.requestOpen(event, \"activate\");\n } else {\n move(-1);\n }\n return true;\n case \"Enter\": {\n if (multiple !== undefined) {\n if (isOpen) {\n event.preventDefault();\n const current = activeEnabled();\n if (current !== null) accept(current, event);\n else if (allowCustomValue && multiple.textRef.current !== \"\") multiple.addText(event);\n return true;\n }\n if (multiple.textRef.current === \"\") return false;\n // An open on its way (requested, not committed yet: a slow `openChangeAction`, or the\n // keystroke's own open still rendering): the user typed a search and is about to\n // pick, so Enter is prevented and the text is kept (design 15.6). Not after Escape:\n // there the committed state is still open until the `toggle` fact runs, and Enter\n // keeps the closed rules below (design 8).\n if (popover.intended() && !popover.committed) {\n event.preventDefault();\n return true;\n }\n if (allowCustomValue) {\n // The user is adding an item, not submitting the form (design 15.9).\n event.preventDefault();\n multiple.addText(event);\n return true;\n }\n // Unmatched text must not reach the submission (`required`, design 15.8): cleared in\n // one flush, then the key's default runs.\n flushSync(() => multiple.clearText(event));\n return false;\n }\n if (isOpen) {\n // An open listbox means the user is choosing: never submit from here.\n event.preventDefault();\n const current = activeEnabled();\n if (current !== null) accept(current, event);\n else if (allowCustomValue && !commitText(event, true)) {\n popover.requestClose(event, \"activate\");\n }\n return true;\n }\n // Closed: not prevented, so a form still submits. The key's default action (implicit\n // submission) must see the optimistic hidden value: Firefox submits before React's\n // scheduled flush of the optimistic render, so it is flushed here (design 5.3).\n if (allowCustomValue) flushSync(() => commitText(event, false));\n return false;\n }\n case \"Backspace\":\n // A held Backspace that emptied the text does not go on to eat chips (design 15.6).\n if (\n multiple !== undefined &&\n !event.repeat &&\n !event.altKey &&\n multiple.textRef.current === \"\" &&\n multiple.hasChips()\n ) {\n multiple.removeLast(event);\n return true;\n }\n return false;\n case \"ArrowLeft\":\n case \"ArrowRight\":\n if (\n multiple !== undefined &&\n !event.altKey &&\n !event.shiftKey &&\n isInlineStartArrow(event) &&\n caretAtStart(event.target) &&\n multiple.hasChips() &&\n multiple.focusLastChip()\n ) {\n event.preventDefault();\n if (activeRef.current !== null) setActive(null);\n return true;\n }\n if (activeRef.current !== null) setActive(null);\n return false;\n case \"Home\":\n case \"End\":\n // APG: the caret keys move visual focus to the input (not prevented: the caret moves).\n if (activeRef.current !== null) setActive(null);\n return false;\n default:\n return false;\n }\n };\n}\n"],"mappings":";;;;;AA4CA,SAAS,aAAa,QAAqC;CACzD,IAAI,EAAE,kBAAkB,mBAAmB,OAAO;CAClD,OAAO,OAAO,mBAAmB,KAAK,OAAO,iBAAiB;AAChE;;AAGA,SAAS,mBAAmB,OAA+B;CACzD,MAAM,SAAS,MAAM;CACrB,MAAM,MACJ,kBAAkB,WAClB,OAA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AAO;GAET,KAAK;IAEH,IACE,aAAa,KAAA,KACb,CAAC,MAAM,UACP,CAAC,MAAM,UACP,SAAS,QAAQ,YAAY,MAC7B,SAAS,SAAS,GAClB;KACA,SAAS,WAAW,KAAK;KACzB,OAAO;IACT;IACA,OAAO;GACT,KAAK;GACL,KAAK;IACH,IACE,aAAa,KAAA,KACb,CAAC,MAAM,UACP,CAAC,MAAM,YACP,mBAAmB,KAAK,KACxB,aAAa,MAAM,MAAM,KACzB,SAAS,SAAS,KAClB,SAAS,cAAc,GACvB;KACA,MAAM,eAAe;KACrB,IAAI,UAAU,YAAY,MAAM,UAAU,IAAI;KAC9C,OAAO;IACT;IACA,IAAI,UAAU,YAAY,MAAM,UAAU,IAAI;IAC9C,OAAO;GACT,KAAK;GACL,KAAK;IAEH,IAAI,UAAU,YAAY,MAAM,UAAU,IAAI;IAC9C,OAAO;GACT,SACE,OAAO;EACX;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"combobox-keyboard.mjs","names":[],"sources":["../../src/combobox/combobox-keyboard.ts"],"sourcesContent":["\"use client\";\nimport { flushSync } from \"react-dom\";\nimport { isComposingKey } from \"../internal/escape-key.js\";\nimport { isPopoverOpen } from \"../internal/overlay/popover-open.js\";\nimport type { RefObject } from \"react\";\nimport type { PopoverRootValue } from \"../internal/overlay/use-overlay-root.js\";\nimport type { ActiveOption } from \"../internal/use-active-option.js\";\nimport type { OptionRegistry } from \"../internal/use-option-registry.js\";\n\nexport interface ComboboxKeyboardOptions {\n /** The Root's `disabled`, `loop` and `allowCustomValue`. */\n readonly disabled: boolean;\n readonly loop: boolean;\n readonly allowCustomValue: boolean;\n readonly popover: Pick<\n PopoverRootValue,\n \"popupRef\" | \"requestOpen\" | \"requestClose\" | \"intended\" | \"committed\"\n >;\n readonly options: Pick<OptionRegistry, \"registry\" | \"orderedOptions\">;\n readonly active: Pick<ActiveOption, \"activeRef\" | \"setActive\" | \"pendingEdgeRef\">;\n /** Accepts an option (design 5.2). */\n readonly accept: (optionValue: string, event: Event) => void;\n /** Free text as the value (design 5.3). Returns whether it dispatched. */\n readonly commitText: (event: Event, close: boolean) => boolean;\n /** With `multiple` (design 15.6): the keys that differ, and the chips. */\n readonly multiple: ComboboxMultipleKeys | undefined;\n}\n\n/** What the Input's keys need from a `multiple` Root (design 15.6, 15.9). */\nexport interface ComboboxMultipleKeys {\n /** The text (urgent). */\n readonly textRef: RefObject<string>;\n /** At least one value is selected (optimistic): there is a chip. */\n readonly hasChips: () => boolean;\n /** Backspace in the empty input: remove the last chip and announce it. */\n readonly removeLast: (event: Event) => void;\n /** The inline-start arrow at the caret's start: focus the last chip. `false`: none mounted. */\n readonly focusLastChip: () => boolean;\n /** `allowCustomValue`: add the text as a value (or nothing if it is one) and clear it. */\n readonly addText: (event: Event) => void;\n /** Clear unmatched text (`\"dismiss\"`). */\n readonly clearText: (event: Event) => void;\n}\n\n/** The caret is at the start of the input with nothing selected. */\nfunction caretAtStart(target: EventTarget | null): boolean {\n if (!(target instanceof HTMLInputElement)) return false;\n return target.selectionStart === 0 && target.selectionEnd === 0;\n}\n\n/** ArrowLeft, or ArrowRight when the input's computed direction is `rtl` (design 15.6). */\nfunction isInlineStartArrow(event: KeyboardEvent): boolean {\n const target = event.target;\n const rtl =\n target instanceof Element &&\n target.ownerDocument.defaultView?.getComputedStyle(target).direction === \"rtl\";\n return event.key === (rtl ? \"ArrowRight\" : \"ArrowLeft\");\n}\n\n/**\n * The keyboard model of the Combobox Input (design/components/combobox.md 8), the counterpart of\n * `menu/use-menu-keyboard.ts`. A plain factory, not a hook (it calls none): the Root calls it on\n * every render. Returns the Input's `keydown` handler, which tells whether it handled the key.\n */\nexport function createComboboxKeyDown({\n disabled,\n loop,\n allowCustomValue,\n popover,\n options,\n active,\n accept,\n commitText,\n multiple,\n}: ComboboxKeyboardOptions): (event: KeyboardEvent) => boolean {\n const { registry, orderedOptions } = options;\n const { activeRef, setActive, pendingEdgeRef } = active;\n\n const move = (direction: 1 | -1): void => {\n const enabled = orderedOptions().filter((option) => !option.disabled);\n if (enabled.length === 0) return;\n const last = enabled.length - 1;\n const index = enabled.findIndex((option) => option.value === activeRef.current);\n let next: number;\n if (direction === 1) next = index < 0 ? 0 : index >= last ? (loop ? 0 : last) : index + 1;\n else next = index < 0 ? last : index <= 0 ? (loop ? last : 0) : index - 1;\n const target = enabled[next]!;\n setActive(target.value);\n if (typeof target.element.scrollIntoView === \"function\") {\n target.element.scrollIntoView({ block: \"nearest\" });\n }\n };\n\n const activeEnabled = (): string | null => {\n const current = activeRef.current;\n if (current === null) return null;\n const entry = registry.get(current);\n return entry !== undefined && !entry.disabled ? current : null;\n };\n\n return (event: KeyboardEvent): boolean => {\n if (disabled || event.ctrlKey || event.metaKey) return false;\n // IME: the key belongs to the composition (Enter commits it, arrows pick a candidate).\n if (isComposingKey(event)) return false;\n // What the user sees, not what is intended: right after Escape the platform has hidden the\n // popup but its `toggle` (and the fact it reports) is still queued, and an open that\n // is still committing shows nothing yet. Enter must submit and arrows must open in both.\n const isOpen = isPopoverOpen(popover.popupRef.current);\n switch (event.key) {\n case \"ArrowDown\":\n event.preventDefault();\n if (event.altKey) {\n if (!isOpen) popover.requestOpen(event, \"activate\");\n } else if (!isOpen) {\n pendingEdgeRef.current = \"first\";\n popover.requestOpen(event, \"activate\");\n } else {\n move(1);\n }\n return true;\n case \"ArrowUp\":\n event.preventDefault();\n if (event.altKey) {\n if (isOpen && multiple !== undefined) {\n // A pick toggles and does not close: Alt+ArrowUp only closes (design 15.6).\n popover.requestClose(event, \"activate\");\n } else if (isOpen) {\n const current = activeEnabled();\n if (current !== null) accept(current, event);\n else popover.requestClose(event, \"activate\");\n }\n } else if (!isOpen) {\n pendingEdgeRef.current = \"last\";\n popover.requestOpen(event, \"activate\");\n } else {\n move(-1);\n }\n return true;\n case \"Enter\": {\n if (multiple !== undefined) {\n if (isOpen) {\n event.preventDefault();\n const current = activeEnabled();\n if (current !== null) accept(current, event);\n else if (allowCustomValue && multiple.textRef.current !== \"\") multiple.addText(event);\n return true;\n }\n if (multiple.textRef.current === \"\") return false;\n // An open on its way (requested, not committed yet: a slow `openChangeAction`, or the\n // keystroke's own open still rendering): the user typed a search and is about to\n // pick, so Enter is prevented and the text is kept (design 15.6). Not after Escape:\n // there the committed state is still open until the `toggle` fact runs, and Enter\n // keeps the closed rules below (design 8).\n if (popover.intended() && !popover.committed) {\n event.preventDefault();\n return true;\n }\n if (allowCustomValue) {\n // The user is adding an item, not submitting the form (design 15.9).\n event.preventDefault();\n multiple.addText(event);\n return true;\n }\n // Unmatched text must not reach the submission (`required`, design 15.8): cleared in\n // one flush, then the key's default runs.\n flushSync(() => multiple.clearText(event));\n return false;\n }\n if (isOpen) {\n // An open listbox means the user is choosing: never submit from here.\n event.preventDefault();\n const current = activeEnabled();\n if (current !== null) accept(current, event);\n else if (allowCustomValue && !commitText(event, true)) {\n popover.requestClose(event, \"activate\");\n }\n return true;\n }\n // Closed: not prevented, so a form still submits. The key's default action (implicit\n // submission) must see the optimistic hidden value: Firefox submits before React's\n // scheduled flush of the optimistic render, so it is flushed here (design 5.3).\n if (allowCustomValue) flushSync(() => commitText(event, false));\n return false;\n }\n case \"Backspace\":\n // A held Backspace that emptied the text does not go on to eat chips (design 15.6).\n if (\n multiple !== undefined &&\n !event.repeat &&\n !event.altKey &&\n multiple.textRef.current === \"\" &&\n multiple.hasChips()\n ) {\n multiple.removeLast(event);\n return true;\n }\n return false;\n case \"ArrowLeft\":\n case \"ArrowRight\":\n if (\n multiple !== undefined &&\n !event.altKey &&\n !event.shiftKey &&\n isInlineStartArrow(event) &&\n caretAtStart(event.target) &&\n multiple.hasChips() &&\n multiple.focusLastChip()\n ) {\n event.preventDefault();\n if (activeRef.current !== null) setActive(null);\n return true;\n }\n if (activeRef.current !== null) setActive(null);\n return false;\n case \"Home\":\n case \"End\":\n // APG: the caret keys move visual focus to the input (not prevented: the caret moves).\n if (activeRef.current !== null) setActive(null);\n return false;\n default:\n return false;\n }\n };\n}\n"],"mappings":";;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AAc;KAC9B,IAAI,YAAY,MAAM,OAAO,SAAS,KAAK;UACtC,IAAI,oBAAoB,CAAC,WAAW,OAAO,IAAI,GAClD,QAAQ,aAAa,OAAO,UAAU;KAExC,OAAO;IACT;IAIA,IAAI,kBAAkB,gBAAgB,WAAW,OAAO,KAAK,CAAC;IAC9D,OAAO;GAET,KAAK;IAEH,IACE,aAAa,KAAA,KACb,CAAC,MAAM,UACP,CAAC,MAAM,UACP,SAAS,QAAQ,YAAY,MAC7B,SAAS,SAAS,GAClB;KACA,SAAS,WAAW,KAAK;KACzB,OAAO;IACT;IACA,OAAO;GACT,KAAK;GACL,KAAK;IACH,IACE,aAAa,KAAA,KACb,CAAC,MAAM,UACP,CAAC,MAAM,YACP,mBAAmB,KAAK,KACxB,aAAa,MAAM,MAAM,KACzB,SAAS,SAAS,KAClB,SAAS,cAAc,GACvB;KACA,MAAM,eAAe;KACrB,IAAI,UAAU,YAAY,MAAM,UAAU,IAAI;KAC9C,OAAO;IACT;IACA,IAAI,UAAU,YAAY,MAAM,UAAU,IAAI;IAC9C,OAAO;GACT,KAAK;GACL,KAAK;IAEH,IAAI,UAAU,YAAY,MAAM,UAAU,IAAI;IAC9C,OAAO;GACT,SACE,OAAO;EACX;CACF;AACF"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { afterDispatch } from "../internal/after-dispatch.mjs";
|
|
2
|
+
import { isEscapeRequest } from "../internal/escape-key.mjs";
|
|
2
3
|
import { isPopoverOpen } from "../internal/overlay/popover-open.mjs";
|
|
3
4
|
// src/dialog/dialog-dismiss.ts
|
|
4
5
|
/**
|
|
@@ -70,7 +71,7 @@ function listenDialogDismiss(dialog, { modal, lightDismiss }) {
|
|
|
70
71
|
}
|
|
71
72
|
const record = (event) => {
|
|
72
73
|
const keyboardEvent = event;
|
|
73
|
-
if (keyboardEvent
|
|
74
|
+
if (!isEscapeRequest(keyboardEvent) || !dialog.open) return;
|
|
74
75
|
if (pending?.event === keyboardEvent) return;
|
|
75
76
|
clearPending();
|
|
76
77
|
pending = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dialog-dismiss.mjs","names":[],"sources":["../../src/dialog/dialog-dismiss.ts"],"sourcesContent":["// Dialog's JS baseline for what the platform gives only behind `closedby`: Escape on a\n// non-modal dialog and light dismiss (design/components/dialog.md 2.6). No \"use client\"\n// directive: DOM listeners only (conventions 7.1).\nimport { afterDispatch } from \"../internal/after-dispatch.js\";\nimport { isPopoverOpen } from \"../internal/overlay/popover-open.js\";\n\n/**\n * An open popover that takes Escape before the dialog: `auto` or `hint` (they have a close\n * watcher). A `manual` popover, or `hint` where the engine maps it to `manual`, does not; one\n * that closes on Escape from JS (HoverCard, Tooltip) prevents the `keydown` instead.\n */\nfunction isOpenLightPopover(element: Element): boolean {\n if (!element.hasAttribute(\"popover\")) return false;\n // The IDL attribute reflects the state the engine applies; jsdom has none.\n const reflected: unknown = (element as HTMLElement).popover;\n const state =\n typeof reflected === \"string\" ? reflected : element.getAttribute(\"popover\")!.toLowerCase();\n if (state === \"manual\") return false;\n return isPopoverOpen(element);\n}\n\n/**\n * Whether an Escape `keydown` at `dialog` belongs to a layer inside it that sits above it\n * (design 2.6 and 9: \"closes the innermost one only\"), read from the event path **at the\n * dialog**, where it is complete in any shadow mode: the target is inside an open nested\n * `<dialog>` (that dialog's Escape) or an open `auto` / `hint` popover, or an open `auto` /\n * `hint` popover inside the dialog would take the close request (close watchers are per\n * document, not per focus).\n */\nfunction escapeBelongsToInnerLayer(dialog: HTMLDialogElement, event: Event): boolean {\n const path = event.composedPath();\n const index = path.indexOf(dialog);\n for (const node of path.slice(0, Math.max(index, 0))) {\n if (node instanceof HTMLDialogElement && node.open) return true;\n if (node instanceof Element && isOpenLightPopover(node)) return true;\n }\n for (const element of dialog.querySelectorAll(\"[popover]\")) {\n if (isOpenLightPopover(element)) return true;\n }\n return false;\n}\n\n/** Whether a pointer event on the dialog itself lies outside its border box (the `::backdrop`). */\nfunction onBackdrop(dialog: HTMLDialogElement, event: Event): boolean {\n if (event.target !== dialog) return false;\n const { clientX, clientY } = event as MouseEvent;\n const rect = dialog.getBoundingClientRect();\n return !(\n rect.top <= clientY &&\n clientY <= rect.bottom &&\n rect.left <= clientX &&\n clientX <= rect.right\n );\n}\n\nexport interface DialogDismissOptions {\n /** The Root's `modal`. A modal dialog has the platform's close watcher Escape. */\n readonly modal: boolean;\n /** The Popup's `lightDismiss`. */\n readonly lightDismiss: boolean;\n}\n\n/**\n * Installs the JS dismissals of `dialog` and returns their cleanup: Escape for a non-modal\n * dialog, and with `lightDismiss` a click outside (on the backdrop for a modal dialog). Each\n * calls `dialog.requestClose()`, so the close is the browser's, a fact (conventions 3.9.2).\n * Not for a dialog where native `closedby` is in use.\n */\nexport function listenDialogDismiss(\n dialog: HTMLDialogElement,\n { modal, lightDismiss }: DialogDismissOptions,\n): () => void {\n const doc = dialog.ownerDocument;\n const listeners: [string, EventListener][] = [];\n\n // Non-modal dialogs get no close watcher Escape from the platform (design 2.6). Record at the\n // dialog, decide last (#177): a capture listener on the dialog records the Escape and the\n // inner-layer snapshot (the path is complete there in any shadow mode, and no close watcher\n // has closed a layer yet). The decision runs in a window bubble listener added for that event\n // only, after every element and document listener, so an inner layer that closed on Escape\n // from JS (a `manual` HoverCard or Tooltip) has prevented it by then: a prevented `keydown` is\n // no close request, as for a modal dialog's close watcher. `stopPropagation()` does not keep\n // the dialog open: when the event never reaches the window, the late path (`afterDispatch`)\n // decides instead, without preventing (the dispatch is over). The first of the two wins.\n const win = doc.defaultView;\n let pending: { readonly event: KeyboardEvent; readonly inner: boolean } | null = null;\n let cancelLate: (() => void) | null = null;\n const clearPending = () => {\n pending = null;\n win?.removeEventListener(\"keydown\", onWindow);\n cancelLate?.();\n cancelLate = null;\n };\n const settle = (canPrevent: boolean) => {\n const record = pending;\n clearPending();\n if (record === null) return;\n const { event, inner } = record;\n if (event.defaultPrevented || inner || !dialog.open || !dialog.isConnected) return;\n if (canPrevent) event.preventDefault();\n dialog.requestClose();\n };\n function onWindow(event: Event): void {\n if (pending === null || event !== pending.event) return;\n settle(true);\n }\n const record = (event: Event) => {\n const keyboardEvent = event as KeyboardEvent;\n if (keyboardEvent.key !== \"Escape\" || !dialog.open) return;\n if (pending?.event === keyboardEvent) return;\n // A new Escape while one is pending: the old event's dispatch is over; replace it.\n clearPending();\n pending = { event: keyboardEvent, inner: escapeBelongsToInnerLayer(dialog, keyboardEvent) };\n win?.addEventListener(\"keydown\", onWindow);\n cancelLate = afterDispatch(keyboardEvent, () => settle(false));\n };\n if (!modal) dialog.addEventListener(\"keydown\", record, true);\n\n // Light dismiss needs both the press and the click outside, like native `closedby=\"any\"`: a\n // drag that starts inside (selecting text in an input) and ends on the backdrop or outside\n // fires `click` on the common ancestor and must not close (it would lose a half-filled form).\n let pressedOutside = false;\n\n const isOutside = (target: EventTarget | null): boolean => {\n // The Trigger counts as outside, as native `closedby=\"any\"` treats it.\n return !(target instanceof Node) || !dialog.contains(target);\n };\n let outsideAttached = false;\n const onOutsidePointerDown = (event: Event) => {\n pressedOutside = dialog.open && isOutside(event.target);\n };\n const onOutsideClick = (event: Event) => {\n const pressed = pressedOutside;\n pressedOutside = false;\n if (!dialog.open || !pressed || !isOutside(event.target)) return;\n dialog.requestClose();\n };\n const syncOutside = () => {\n const want = dialog.open;\n if (want === outsideAttached) return;\n outsideAttached = want;\n pressedOutside = false;\n if (want) {\n doc.addEventListener(\"pointerdown\", onOutsidePointerDown, true);\n doc.addEventListener(\"click\", onOutsideClick, true);\n } else {\n doc.removeEventListener(\"pointerdown\", onOutsidePointerDown, true);\n doc.removeEventListener(\"click\", onOutsideClick, true);\n }\n };\n\n if (lightDismiss) {\n if (modal) {\n // A press or click on the ::backdrop targets the dialog itself, outside its border box.\n listeners.push(\n [\n \"pointerdown\",\n (event) => {\n pressedOutside = dialog.open && onBackdrop(dialog, event);\n },\n ],\n [\n \"click\",\n (event) => {\n const pressed = pressedOutside;\n pressedOutside = false;\n if (!dialog.open || !pressed || !onBackdrop(dialog, event)) return;\n dialog.requestClose();\n },\n ],\n );\n } else {\n // A document listener only while open, following the native `toggle` (the React\n // `onToggle` prop never fires on a hydrated <dialog>); reads `dialog.open`, not\n // `newState` (coalescing).\n listeners.push([\"toggle\", syncOutside]);\n syncOutside();\n }\n }\n\n for (const [type, listener] of listeners) dialog.addEventListener(type, listener);\n return () => {\n for (const [type, listener] of listeners) dialog.removeEventListener(type, listener);\n if (!modal) dialog.removeEventListener(\"keydown\", record, true);\n clearPending();\n if (outsideAttached) {\n doc.removeEventListener(\"pointerdown\", onOutsidePointerDown, true);\n doc.removeEventListener(\"click\", onOutsideClick, true);\n }\n };\n}\n"],"mappings":";;;;;;;;AAWA,SAAS,mBAAmB,SAA2B;CACrD,IAAI,CAAC,QAAQ,aAAa,SAAS,GAAG,OAAO;CAE7C,MAAM,YAAsB,QAAwB;CAGpD,KADE,OAAO,cAAc,WAAW,YAAY,QAAQ,aAAa,SAAS,CAAC,CAAE,YAAY,OAC7E,UAAU,OAAO;CAC/B,OAAO,cAAc,OAAO;AAC9B;;;;;;;;;AAUA,SAAS,0BAA0B,QAA2B,OAAuB;CACnF,MAAM,OAAO,MAAM,aAAa;CAChC,MAAM,QAAQ,KAAK,QAAQ,MAAM;CACjC,KAAK,MAAM,QAAQ,KAAK,MAAM,GAAG,KAAK,IAAI,OAAO,CAAC,CAAC,GAAG;EACpD,IAAI,gBAAgB,qBAAqB,KAAK,MAAM,OAAO;EAC3D,IAAI,gBAAgB,WAAW,mBAAmB,IAAI,GAAG,OAAO;CAClE;CACA,KAAK,MAAM,WAAW,OAAO,iBAAiB,WAAW,GACvD,IAAI,mBAAmB,OAAO,GAAG,OAAO;CAE1C,OAAO;AACT;;AAGA,SAAS,WAAW,QAA2B,OAAuB;CACpE,IAAI,MAAM,WAAW,QAAQ,OAAO;CACpC,MAAM,EAAE,SAAS,YAAY;CAC7B,MAAM,OAAO,OAAO,sBAAsB;CAC1C,OAAO,EACL,KAAK,OAAO,WACZ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AAU;EAChB,iBAAiB;EACjB,IAAI,CAAC,OAAO,QAAQ,CAAC,WAAW,CAAC,UAAU,MAAM,MAAM,GAAG;EAC1D,OAAO,aAAa;CACtB;CACA,MAAM,oBAAoB;EACxB,MAAM,OAAO,OAAO;EACpB,IAAI,SAAS,iBAAiB;EAC9B,kBAAkB;EAClB,iBAAiB;EACjB,IAAI,MAAM;GACR,IAAI,iBAAiB,eAAe,sBAAsB,IAAI;GAC9D,IAAI,iBAAiB,SAAS,gBAAgB,IAAI;EACpD,OAAO;GACL,IAAI,oBAAoB,eAAe,sBAAsB,IAAI;GACjE,IAAI,oBAAoB,SAAS,gBAAgB,IAAI;EACvD;CACF;CAEA,IAAI,cAAc;EAChB,IAAI,OAEF,UAAU,KACR,CACE,gBACC,UAAU;GACT,iBAAiB,OAAO,QAAQ,WAAW,QAAQ,KAAK;EAC1D,CACF,GACA,CACE,UACC,UAAU;GACT,MAAM,UAAU;GAChB,iBAAiB;GACjB,IAAI,CAAC,OAAO,QAAQ,CAAC,WAAW,CAAC,WAAW,QAAQ,KAAK,GAAG;GAC5D,OAAO,aAAa;EACtB,CACF,CACF;OACK;GAIL,UAAU,KAAK,CAAC,UAAU,WAAW,CAAC;GACtC,YAAY;EACd;CACF;CAEA,KAAK,MAAM,CAAC,MAAM,aAAa,WAAW,OAAO,iBAAiB,MAAM,QAAQ;CAChF,aAAa;EACX,KAAK,MAAM,CAAC,MAAM,aAAa,WAAW,OAAO,oBAAoB,MAAM,QAAQ;EACnF,IAAI,CAAC,OAAO,OAAO,oBAAoB,WAAW,QAAQ,IAAI;EAC9D,aAAa;EACb,IAAI,iBAAiB;GACnB,IAAI,oBAAoB,eAAe,sBAAsB,IAAI;GACjE,IAAI,oBAAoB,SAAS,gBAAgB,IAAI;EACvD;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"dialog-dismiss.mjs","names":[],"sources":["../../src/dialog/dialog-dismiss.ts"],"sourcesContent":["// Dialog's JS baseline for what the platform gives only behind `closedby`: Escape on a\n// non-modal dialog and light dismiss (design/components/dialog.md 2.6). No \"use client\"\n// directive: DOM listeners only (conventions 7.1).\nimport { afterDispatch } from \"../internal/after-dispatch.js\";\nimport { isEscapeRequest } from \"../internal/escape-key.js\";\nimport { isPopoverOpen } from \"../internal/overlay/popover-open.js\";\n\n/**\n * An open popover that takes Escape before the dialog: `auto` or `hint` (they have a close\n * watcher). A `manual` popover, or `hint` where the engine maps it to `manual`, does not; one\n * that closes on Escape from JS (HoverCard, Tooltip) prevents the `keydown` instead.\n */\nfunction isOpenLightPopover(element: Element): boolean {\n if (!element.hasAttribute(\"popover\")) return false;\n // The IDL attribute reflects the state the engine applies; jsdom has none.\n const reflected: unknown = (element as HTMLElement).popover;\n const state =\n typeof reflected === \"string\" ? reflected : element.getAttribute(\"popover\")!.toLowerCase();\n if (state === \"manual\") return false;\n return isPopoverOpen(element);\n}\n\n/**\n * Whether an Escape `keydown` at `dialog` belongs to a layer inside it that sits above it\n * (design 2.6 and 9: \"closes the innermost one only\"), read from the event path **at the\n * dialog**, where it is complete in any shadow mode: the target is inside an open nested\n * `<dialog>` (that dialog's Escape) or an open `auto` / `hint` popover, or an open `auto` /\n * `hint` popover inside the dialog would take the close request (close watchers are per\n * document, not per focus).\n */\nfunction escapeBelongsToInnerLayer(dialog: HTMLDialogElement, event: Event): boolean {\n const path = event.composedPath();\n const index = path.indexOf(dialog);\n for (const node of path.slice(0, Math.max(index, 0))) {\n if (node instanceof HTMLDialogElement && node.open) return true;\n if (node instanceof Element && isOpenLightPopover(node)) return true;\n }\n for (const element of dialog.querySelectorAll(\"[popover]\")) {\n if (isOpenLightPopover(element)) return true;\n }\n return false;\n}\n\n/** Whether a pointer event on the dialog itself lies outside its border box (the `::backdrop`). */\nfunction onBackdrop(dialog: HTMLDialogElement, event: Event): boolean {\n if (event.target !== dialog) return false;\n const { clientX, clientY } = event as MouseEvent;\n const rect = dialog.getBoundingClientRect();\n return !(\n rect.top <= clientY &&\n clientY <= rect.bottom &&\n rect.left <= clientX &&\n clientX <= rect.right\n );\n}\n\nexport interface DialogDismissOptions {\n /** The Root's `modal`. A modal dialog has the platform's close watcher Escape. */\n readonly modal: boolean;\n /** The Popup's `lightDismiss`. */\n readonly lightDismiss: boolean;\n}\n\n/**\n * Installs the JS dismissals of `dialog` and returns their cleanup: Escape for a non-modal\n * dialog, and with `lightDismiss` a click outside (on the backdrop for a modal dialog). Each\n * calls `dialog.requestClose()`, so the close is the browser's, a fact (conventions 3.9.2).\n * Not for a dialog where native `closedby` is in use.\n */\nexport function listenDialogDismiss(\n dialog: HTMLDialogElement,\n { modal, lightDismiss }: DialogDismissOptions,\n): () => void {\n const doc = dialog.ownerDocument;\n const listeners: [string, EventListener][] = [];\n\n // Non-modal dialogs get no close watcher Escape from the platform (design 2.6). Record at the\n // dialog, decide last (#177): a capture listener on the dialog records the Escape and the\n // inner-layer snapshot (the path is complete there in any shadow mode, and no close watcher\n // has closed a layer yet). The decision runs in a window bubble listener added for that event\n // only, after every element and document listener, so an inner layer that closed on Escape\n // from JS (a `manual` HoverCard or Tooltip) has prevented it by then: a prevented `keydown` is\n // no close request, as for a modal dialog's close watcher. `stopPropagation()` does not keep\n // the dialog open: when the event never reaches the window, the late path (`afterDispatch`)\n // decides instead, without preventing (the dispatch is over). The first of the two wins.\n const win = doc.defaultView;\n let pending: { readonly event: KeyboardEvent; readonly inner: boolean } | null = null;\n let cancelLate: (() => void) | null = null;\n const clearPending = () => {\n pending = null;\n win?.removeEventListener(\"keydown\", onWindow);\n cancelLate?.();\n cancelLate = null;\n };\n const settle = (canPrevent: boolean) => {\n const record = pending;\n clearPending();\n if (record === null) return;\n const { event, inner } = record;\n if (event.defaultPrevented || inner || !dialog.open || !dialog.isConnected) return;\n if (canPrevent) event.preventDefault();\n dialog.requestClose();\n };\n function onWindow(event: Event): void {\n if (pending === null || event !== pending.event) return;\n settle(true);\n }\n const record = (event: Event) => {\n const keyboardEvent = event as KeyboardEvent;\n // Not an Escape of an IME composition, nor one already consumed (conventions 15).\n if (!isEscapeRequest(keyboardEvent) || !dialog.open) return;\n if (pending?.event === keyboardEvent) return;\n // A new Escape while one is pending: the old event's dispatch is over; replace it.\n clearPending();\n pending = { event: keyboardEvent, inner: escapeBelongsToInnerLayer(dialog, keyboardEvent) };\n win?.addEventListener(\"keydown\", onWindow);\n cancelLate = afterDispatch(keyboardEvent, () => settle(false));\n };\n if (!modal) dialog.addEventListener(\"keydown\", record, true);\n\n // Light dismiss needs both the press and the click outside, like native `closedby=\"any\"`: a\n // drag that starts inside (selecting text in an input) and ends on the backdrop or outside\n // fires `click` on the common ancestor and must not close (it would lose a half-filled form).\n let pressedOutside = false;\n\n const isOutside = (target: EventTarget | null): boolean => {\n // The Trigger counts as outside, as native `closedby=\"any\"` treats it.\n return !(target instanceof Node) || !dialog.contains(target);\n };\n let outsideAttached = false;\n const onOutsidePointerDown = (event: Event) => {\n pressedOutside = dialog.open && isOutside(event.target);\n };\n const onOutsideClick = (event: Event) => {\n const pressed = pressedOutside;\n pressedOutside = false;\n if (!dialog.open || !pressed || !isOutside(event.target)) return;\n dialog.requestClose();\n };\n const syncOutside = () => {\n const want = dialog.open;\n if (want === outsideAttached) return;\n outsideAttached = want;\n pressedOutside = false;\n if (want) {\n doc.addEventListener(\"pointerdown\", onOutsidePointerDown, true);\n doc.addEventListener(\"click\", onOutsideClick, true);\n } else {\n doc.removeEventListener(\"pointerdown\", onOutsidePointerDown, true);\n doc.removeEventListener(\"click\", onOutsideClick, true);\n }\n };\n\n if (lightDismiss) {\n if (modal) {\n // A press or click on the ::backdrop targets the dialog itself, outside its border box.\n listeners.push(\n [\n \"pointerdown\",\n (event) => {\n pressedOutside = dialog.open && onBackdrop(dialog, event);\n },\n ],\n [\n \"click\",\n (event) => {\n const pressed = pressedOutside;\n pressedOutside = false;\n if (!dialog.open || !pressed || !onBackdrop(dialog, event)) return;\n dialog.requestClose();\n },\n ],\n );\n } else {\n // A document listener only while open, following the native `toggle` (the React\n // `onToggle` prop never fires on a hydrated <dialog>); reads `dialog.open`, not\n // `newState` (coalescing).\n listeners.push([\"toggle\", syncOutside]);\n syncOutside();\n }\n }\n\n for (const [type, listener] of listeners) dialog.addEventListener(type, listener);\n return () => {\n for (const [type, listener] of listeners) dialog.removeEventListener(type, listener);\n if (!modal) dialog.removeEventListener(\"keydown\", record, true);\n clearPending();\n if (outsideAttached) {\n doc.removeEventListener(\"pointerdown\", onOutsidePointerDown, true);\n doc.removeEventListener(\"click\", onOutsideClick, true);\n }\n };\n}\n"],"mappings":";;;;;;;;;AAYA,SAAS,mBAAmB,SAA2B;CACrD,IAAI,CAAC,QAAQ,aAAa,SAAS,GAAG,OAAO;CAE7C,MAAM,YAAsB,QAAwB;CAGpD,KADE,OAAO,cAAc,WAAW,YAAY,QAAQ,aAAa,SAAS,CAAC,CAAE,YAAY,OAC7E,UAAU,OAAO;CAC/B,OAAO,cAAc,OAAO;AAC9B;;;;;;;;;AAUA,SAAS,0BAA0B,QAA2B,OAAuB;CACnF,MAAM,OAAO,MAAM,aAAa;CAChC,MAAM,QAAQ,KAAK,QAAQ,MAAM;CACjC,KAAK,MAAM,QAAQ,KAAK,MAAM,GAAG,KAAK,IAAI,OAAO,CAAC,CAAC,GAAG;EACpD,IAAI,gBAAgB,qBAAqB,KAAK,MAAM,OAAO;EAC3D,IAAI,gBAAgB,WAAW,mBAAmB,IAAI,GAAG,OAAO;CAClE;CACA,KAAK,MAAM,WAAW,OAAO,iBAAiB,WAAW,GACvD,IAAI,mBAAmB,OAAO,GAAG,OAAO;CAE1C,OAAO;AACT;;AAGA,SAAS,WAAW,QAA2B,OAAuB;CACpE,IAAI,MAAM,WAAW,QAAQ,OAAO;CACpC,MAAM,EAAE,SAAS,YAAY;CAC7B,MAAM,OAAO,OAAO,sBAAsB;CAC1C,OAAO,EACL,KAAK,OAAO,WACZ,WAAW,KAAK,UAChB,KAAK,QAAQ,WACb,WAAW,KAAK;AAEpB;;;;;;;AAeA,SAAgB,oBACd,QACA,EAAE,OAAO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;EAC1D,OAAO,aAAa;CACtB;CACA,MAAM,oBAAoB;EACxB,MAAM,OAAO,OAAO;EACpB,IAAI,SAAS,iBAAiB;EAC9B,kBAAkB;EAClB,iBAAiB;EACjB,IAAI,MAAM;GACR,IAAI,iBAAiB,eAAe,sBAAsB,IAAI;GAC9D,IAAI,iBAAiB,SAAS,gBAAgB,IAAI;EACpD,OAAO;GACL,IAAI,oBAAoB,eAAe,sBAAsB,IAAI;GACjE,IAAI,oBAAoB,SAAS,gBAAgB,IAAI;EACvD;CACF;CAEA,IAAI,cAAc;EAChB,IAAI,OAEF,UAAU,KACR,CACE,gBACC,UAAU;GACT,iBAAiB,OAAO,QAAQ,WAAW,QAAQ,KAAK;EAC1D,CACF,GACA,CACE,UACC,UAAU;GACT,MAAM,UAAU;GAChB,iBAAiB;GACjB,IAAI,CAAC,OAAO,QAAQ,CAAC,WAAW,CAAC,WAAW,QAAQ,KAAK,GAAG;GAC5D,OAAO,aAAa;EACtB,CACF,CACF;OACK;GAIL,UAAU,KAAK,CAAC,UAAU,WAAW,CAAC;GACtC,YAAY;EACd;CACF;CAEA,KAAK,MAAM,CAAC,MAAM,aAAa,WAAW,OAAO,iBAAiB,MAAM,QAAQ;CAChF,aAAa;EACX,KAAK,MAAM,CAAC,MAAM,aAAa,WAAW,OAAO,oBAAoB,MAAM,QAAQ;EACnF,IAAI,CAAC,OAAO,OAAO,oBAAoB,WAAW,QAAQ,IAAI;EAC9D,aAAa;EACb,IAAI,iBAAiB;GACnB,IAAI,oBAAoB,eAAe,sBAAsB,IAAI;GACjE,IAAI,oBAAoB,SAAS,gBAAgB,IAAI;EACvD;CACF;AACF"}
|
|
@@ -263,7 +263,7 @@ A field shows an error when its control matches `:user-invalid` or the Form has
|
|
|
263
263
|
- **Not while the user is still typing for the first time.** `:user-invalid` starts matching after the user changed the value and left the field, or after a submission attempt; it then updates live on every keystroke and stops after a form reset. There is no `validationMode`: this is the heuristic every native form already uses.
|
|
264
264
|
- **A submission attempt** with an invalid field: the Field cancels the browser's validation bubble (only when a `Field.Error` is mounted), renders the message, and the first invalid control in document order is focused. Its description, error included, is read at focus. When focus is already there (Enter pressed in that field), the message is announced with `ariaNotify()` instead, where the browser has it. A field without `Field.Error` keeps the browser's bubble; so does every field before hydration.
|
|
265
265
|
- `form.checkValidity()` shows nothing and `reportValidity()` shows the browser's bubble, as without the library.
|
|
266
|
-
- The display state is updated
|
|
266
|
+
- The display state is updated urgently from the DOM event, not in a transition: the error must be in the DOM when focus reaches the field. After an edit it is updated once the event has been dispatched, so your own `onChange` on a controlled control runs first; the browser's validity follows the new value at once. So no Field part takes a `transition` prop, `Field.Error` animates its entry with CSS `@starting-style`, and content rendered inside it must not suspend.
|
|
267
267
|
|
|
268
268
|
### Custom rules: validate
|
|
269
269
|
|
|
@@ -436,7 +436,7 @@ None: no part adds transition types or takes a `transition` prop.
|
|
|
436
436
|
|
|
437
437
|
Concept: [Pending & optimistic state](../concepts/pending-and-optimistic.md)
|
|
438
438
|
|
|
439
|
-
A Form with a function `action` runs it in its own transition: `data-pending` is on the form, on `Form.Submit` and on every Field part while the submission is in flight. A Field's display state (whether its error shows) is updated
|
|
439
|
+
A Form with a function `action` runs it in its own transition: `data-pending` is on the form, on `Form.Submit` and on every Field part while the submission is in flight. A Field's display state (whether its error shows) is updated urgently from the DOM event (after an edit, once the event has been dispatched), not in a transition.
|
|
440
440
|
|
|
441
441
|
## Suspense
|
|
442
442
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"field-root.d.mts","names":[],"sources":["../../src/field/field-root.tsx"],"mappings":";;;;;;;;;
|
|
1
|
+
{"version":3,"file":"field-root.d.mts","names":[],"sources":["../../src/field/field-root.tsx"],"mappings":";;;;;;;;;YAuDY,iBAAiB,eAAe,UAAU,aAAa;;;;;;iBAOlD,uBAAuB,KACtC;;EAIA;;;;;;EAMA;;;;;;EAMA;;;;;;;;;;;;;;EAcA,WAAW;;EAEX,YAAY,+BAA+B;;EAE3C,QAAQ,WAAW,2BAA2B;;EAE9C,WAAW,WAAW,WAAW;;EAEjC,SAAS,WAAW,8BAA8B;;;;;;;;;;;;;wBAqDpC,YACd,MACA,UACA,UACA,UACA,WACA,OACA,UACA,WACG,QACF,iCAAc,IAAA;yBAVD"}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { use, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
|
|
3
|
-
import { useFormStatus } from "react-dom";
|
|
3
|
+
import { flushSync, useFormStatus } from "react-dom";
|
|
4
4
|
import { FieldContext, FormContext, fieldDataAttributes } from "../internal/form/field-context.mjs";
|
|
5
|
+
import { afterDispatch } from "../internal/after-dispatch.mjs";
|
|
5
6
|
import { collectInvalid } from "../internal/form/focus-first-invalid.mjs";
|
|
6
7
|
import { useDevWarning } from "../internal/use-dev-warning.mjs";
|
|
7
8
|
import { useFormOwnerEvent } from "../internal/form/use-form-owner-event.mjs";
|
|
@@ -82,7 +83,7 @@ function FieldRoot({ name, disabled = false, required = false, validate, classNa
|
|
|
82
83
|
const errors = form?.errors;
|
|
83
84
|
const serverMessages = useMemo(() => normaliseErrorValue(name === void 0 ? void 0 : errors?.[name]), [errors, name]);
|
|
84
85
|
const serverKey = serverMessages.join("\n");
|
|
85
|
-
const { serverShown, dismiss, setSuppressNext } = useServerErrorVisibility(formPending, serverMessages);
|
|
86
|
+
const { serverShown, dismiss, recordEdit, setSuppressNext } = useServerErrorVisibility(formPending, serverMessages);
|
|
86
87
|
const [mirror, setMirror] = useState(INITIAL_MIRROR);
|
|
87
88
|
/** The last mirror written: `refresh` compares against it, so an unchanged read renders nothing. */
|
|
88
89
|
const mirrorRef = useRef(INITIAL_MIRROR);
|
|
@@ -98,23 +99,42 @@ function FieldRoot({ name, disabled = false, required = false, validate, classNa
|
|
|
98
99
|
formPending,
|
|
99
100
|
form
|
|
100
101
|
});
|
|
101
|
-
/**
|
|
102
|
-
const
|
|
102
|
+
/** An edit of the control whose state write is pending (`refreshAfterEdit`): its dismissal. */
|
|
103
|
+
const pendingEdit = useRef(null);
|
|
104
|
+
/**
|
|
105
|
+
* Recomputes and writes the custom-validity slot (design 2.1). No React state is written, so it
|
|
106
|
+
* is safe in any listener; `null` when there is no control (or no element to validate).
|
|
107
|
+
*/
|
|
108
|
+
const writeSlot = useCallback((options = {}) => {
|
|
103
109
|
const registration = controlRef.current;
|
|
104
|
-
if (registration === null) return
|
|
110
|
+
if (registration === null) return null;
|
|
105
111
|
const surface = validityElementOf(registration.element);
|
|
106
112
|
const el = registration.validityElement?.() ?? surface;
|
|
107
|
-
if (el === null) return
|
|
108
|
-
const { name, validate, serverMessages, serverShown
|
|
113
|
+
if (el === null) return null;
|
|
114
|
+
const { name, validate, serverMessages, serverShown } = latest.current;
|
|
109
115
|
const owner = el.form;
|
|
110
116
|
const formData = owner === null ? new FormData() : new FormData(owner);
|
|
111
117
|
const entry = name === void 0 ? null : formData.get(name);
|
|
112
118
|
const custom = validate === void 0 ? NONE : normaliseErrorValue(validate(typeof entry === "string" ? entry : "", formData));
|
|
113
|
-
const showServer = serverShown && options.dismiss !== true;
|
|
119
|
+
const showServer = serverShown && options.dismiss !== true && pendingEdit.current === null;
|
|
114
120
|
if (slotElement.current !== null && slotElement.current !== el) slotElement.current.setCustomValidity("");
|
|
115
121
|
slotElement.current = el;
|
|
116
122
|
el.setCustomValidity(showServer ? serverMessages.join("\n") : custom.join("\n"));
|
|
117
123
|
if (surface !== null && surface !== el && surface.validationMessage !== el.validationMessage) surface.setCustomValidity(el.validationMessage);
|
|
124
|
+
return {
|
|
125
|
+
el,
|
|
126
|
+
surface,
|
|
127
|
+
formData,
|
|
128
|
+
custom,
|
|
129
|
+
showServer
|
|
130
|
+
};
|
|
131
|
+
}, [latest]);
|
|
132
|
+
/** Re-reads the slot and the mirror; returns the messages the Field shows for the control. */
|
|
133
|
+
const refresh = useCallback((options = {}) => {
|
|
134
|
+
const read = writeSlot(options);
|
|
135
|
+
if (read === null) return NONE;
|
|
136
|
+
const { el, surface, formData, custom, showServer } = read;
|
|
137
|
+
const { name, serverMessages, formPending, form } = latest.current;
|
|
118
138
|
if (options.reset === true) attempted.current = false;
|
|
119
139
|
const userInvalid = supportsUserInvalid() ? (surface ?? el).matches(":user-invalid") : attempted.current && !el.validity.valid;
|
|
120
140
|
const validity = snapshotValidity(el.validity);
|
|
@@ -131,7 +151,45 @@ function FieldRoot({ name, disabled = false, required = false, validate, classNa
|
|
|
131
151
|
const submitted = formPending && name !== void 0 ? form?.submittedData() ?? null : null;
|
|
132
152
|
if (submitted !== null && name !== void 0) setSuppressNext(!arraysEqual(entryStrings(formData.getAll(name)), entryStrings(submitted.getAll(name))));
|
|
133
153
|
return showServer ? serverMessages : messages;
|
|
134
|
-
}, [
|
|
154
|
+
}, [
|
|
155
|
+
latest,
|
|
156
|
+
setSuppressNext,
|
|
157
|
+
writeSlot
|
|
158
|
+
]);
|
|
159
|
+
/** The pending state write of the last edit, cancelled by the next one (it covers both). */
|
|
160
|
+
const cancelEditRefresh = useRef(null);
|
|
161
|
+
/**
|
|
162
|
+
* An `input` / `change` (the control's own, or another field's on the form owner): the slot now,
|
|
163
|
+
* the state after the event's dispatch (design 2.4, `afterDispatch`). A state write in the
|
|
164
|
+
* listener would commit in the microtask checkpoint Chromium runs after it, before React's own
|
|
165
|
+
* listener has seen the event, and that commit writes a controlled input's previous `value`
|
|
166
|
+
* back over the keystroke (#193). After the dispatch the slot is recomputed too, from the value
|
|
167
|
+
* React settled on (a controlled parent that did not adopt the text restores the old one).
|
|
168
|
+
*/
|
|
169
|
+
const refreshAfterEdit = useCallback((event, edit) => {
|
|
170
|
+
const applyEdit = edit ? recordEdit() : pendingEdit.current;
|
|
171
|
+
pendingEdit.current = applyEdit;
|
|
172
|
+
writeSlot({ dismiss: applyEdit !== null });
|
|
173
|
+
cancelEditRefresh.current?.();
|
|
174
|
+
const cancel = afterDispatch(event, () => {
|
|
175
|
+
if (cancelEditRefresh.current !== cancel) return;
|
|
176
|
+
cancelEditRefresh.current = null;
|
|
177
|
+
pendingEdit.current = null;
|
|
178
|
+
flushSync(() => {
|
|
179
|
+
applyEdit?.();
|
|
180
|
+
refresh({ dismiss: applyEdit !== null });
|
|
181
|
+
});
|
|
182
|
+
});
|
|
183
|
+
cancelEditRefresh.current = cancel;
|
|
184
|
+
}, [
|
|
185
|
+
writeSlot,
|
|
186
|
+
refresh,
|
|
187
|
+
recordEdit
|
|
188
|
+
]);
|
|
189
|
+
useLayoutEffect(() => () => {
|
|
190
|
+
cancelEditRefresh.current?.();
|
|
191
|
+
cancelEditRefresh.current = null;
|
|
192
|
+
}, []);
|
|
135
193
|
useLayoutEffect(() => {
|
|
136
194
|
refresh();
|
|
137
195
|
}, [
|
|
@@ -148,10 +206,7 @@ function FieldRoot({ name, disabled = false, required = false, validate, classNa
|
|
|
148
206
|
const element = control?.element ?? null;
|
|
149
207
|
useLayoutEffect(() => {
|
|
150
208
|
if (element === null) return;
|
|
151
|
-
const onEdit = () =>
|
|
152
|
-
dismiss();
|
|
153
|
-
refresh({ dismiss: true });
|
|
154
|
-
};
|
|
209
|
+
const onEdit = (event) => refreshAfterEdit(event, true);
|
|
155
210
|
const onBlur = () => refresh();
|
|
156
211
|
const onInvalid = (event) => {
|
|
157
212
|
const target = event.target;
|
|
@@ -183,7 +238,7 @@ function FieldRoot({ name, disabled = false, required = false, validate, classNa
|
|
|
183
238
|
element,
|
|
184
239
|
control,
|
|
185
240
|
refresh,
|
|
186
|
-
|
|
241
|
+
refreshAfterEdit
|
|
187
242
|
]);
|
|
188
243
|
const ownerRef = useMemo(() => ({
|
|
189
244
|
get current() {
|
|
@@ -194,7 +249,7 @@ function FieldRoot({ name, disabled = false, required = false, validate, classNa
|
|
|
194
249
|
const onOwnerEdit = (event) => {
|
|
195
250
|
const target = event.target;
|
|
196
251
|
if (target instanceof Node && controlRef.current?.element.contains(target) === true) return;
|
|
197
|
-
|
|
252
|
+
refreshAfterEdit(event, false);
|
|
198
253
|
};
|
|
199
254
|
useFormOwnerEvent(ownerRef, "input", onOwnerEdit);
|
|
200
255
|
useFormOwnerEvent(ownerRef, "change", onOwnerEdit);
|
|
@@ -208,7 +263,7 @@ function FieldRoot({ name, disabled = false, required = false, validate, classNa
|
|
|
208
263
|
if (registerField === void 0) return;
|
|
209
264
|
const registration = {
|
|
210
265
|
getFocusTarget: () => focusTargetOf(controlRef.current?.element ?? null),
|
|
211
|
-
showsServerError: () => latest.current.serverShown,
|
|
266
|
+
showsServerError: () => latest.current.serverShown && pendingEdit.current === null,
|
|
212
267
|
serverMessages: () => latest.current.serverMessages,
|
|
213
268
|
refresh: () => {
|
|
214
269
|
refresh();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"field-root.mjs","names":[],"sources":["../../src/field/field-root.tsx"],"sourcesContent":["\"use client\";\nimport {\n use,\n useCallback,\n useEffect,\n useId,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport type { ComponentPropsWithRef, CSSProperties, ReactNode, RefObject } from \"react\";\nimport { useFormStatus } from \"react-dom\";\nimport { FieldContext, fieldDataAttributes, FormContext } from \"../internal/form/field-context.js\";\nimport type {\n FieldContextValue,\n FieldControlRegistration,\n FieldState,\n FormFieldRegistration,\n} from \"../internal/form/field-context.js\";\nimport { collectInvalid } from \"../internal/form/focus-first-invalid.js\";\nimport type { RenderProp, StateValue } from \"../internal/types.js\";\nimport { useDevWarning } from \"../internal/use-dev-warning.js\";\nimport { useFormOwnerEvent } from \"../internal/form/use-form-owner-event.js\";\nimport { useFormReset } from \"../internal/form/use-form-reset.js\";\nimport { useLatest } from \"../internal/use-latest.js\";\nimport { useRender } from \"../internal/use-render.js\";\nimport { useServerErrorVisibility } from \"./use-server-error-visibility.js\";\nimport {\n focusTargetOf,\n normaliseErrorValue,\n snapshotValidity,\n supportsUserInvalid,\n VALID,\n validityElementOf,\n validityEquals,\n} from \"../internal/form/validity.js\";\nimport type {\n FieldErrorValue,\n FieldValidity,\n ValidatableElement,\n} from \"../internal/form/validity.js\";\nimport { arraysEqual } from \"../internal/value-set.js\";\n\nexport type { FieldState } from \"../internal/form/field-context.js\";\nexport type { FieldValidity } from \"../internal/form/validity.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/**\n * A custom constraint: receives the field's submitted value (`formData.get(name)` as a string,\n * `\"\"` when absent) and the whole form's `FormData`. Return a message (or several) for an error,\n * `null` / `undefined` / `\"\"` for none.\n */\nexport type FieldValidate = (value: string, formData: FormData) => FieldErrorValue;\n\n/**\n * Props of `Field.Root`.\n *\n * @see https://ui.funstack.work/components/field\n */\nexport interface FieldRootProps extends Omit<\n ComponentPropsWithRef<\"div\">,\n \"className\" | \"style\" | \"children\"\n> {\n /** Form field name: the control's default `name`, the key in `Form.Root errors`, and the entry `validate` reads. */\n name?: string;\n /**\n * Disables the control (native `disabled`) and marks every part `data-disabled`.\n *\n * @defaultValue `false`\n */\n disabled?: boolean;\n /**\n * Makes the control `required` (native) and marks every part `data-required`.\n *\n * @defaultValue `false`\n */\n required?: boolean;\n /**\n * A custom constraint, written into the control with `setCustomValidity`. Sync. Receives the\n * field's submitted value (`formData.get(name)` as a string, `\"\"` when absent) and the whole\n * form's `FormData`, so a cross-field rule can read the other field. Runs at mount, on every\n * `input` / `change` in the form (and a FUNSTACK control's value change), on blur, after a\n * reset, on a submission attempt, and in every commit in which this prop changed identity, so\n * a rule that reads outside state (a list that loads, a sibling value in React state) updates\n * on render. An inline function therefore re-runs on every render of the Field; wrap it in\n * `useCallback` to re-run only when its inputs change. Return a string\n * or strings for an error, `null` / `undefined` / `\"\"` for none. Shown when the platform's\n * `:user-invalid` heuristic says so, like a native constraint. Not serialisable: a Field with\n * `validate` is rendered from a client component.\n */\n validate?: FieldValidate;\n /** Class name, or a function of the part's state that returns one. */\n className?: StateValue<string | undefined, FieldState>;\n /** Inline style, or a function of the part's state that returns one. */\n style?: StateValue<CSSProperties | undefined, FieldState>;\n /** Content, or a function of the part's state. */\n children?: StateValue<ReactNode, FieldState>;\n /** Replace the default `<div>` (element form) or take over rendering (function form). */\n render?: RenderProp<ComponentPropsWithRef<\"div\">, FieldState>;\n}\n\n/** The urgent mirror of browser-owned validity (design 2.4). */\ninterface Mirror {\n readonly userInvalid: boolean;\n readonly validity: FieldValidity;\n readonly messages: readonly string[];\n}\n\nconst NONE: readonly string[] = Object.freeze([]);\nconst INITIAL_MIRROR: Mirror = { userInvalid: false, validity: VALID, messages: NONE };\n\ninterface RefreshOptions {\n /** The user edited the control: the server message is dropped from the slot at once. */\n readonly dismiss?: boolean;\n /** After a form reset: the user-validity flag is clear again. */\n readonly reset?: boolean;\n}\n\nfunction mirrorEquals(a: Mirror, b: Mirror): boolean {\n return (\n a.userInvalid === b.userInvalid &&\n validityEquals(a.validity, b.validity) &&\n arraysEqual(a.messages, b.messages)\n );\n}\n\n/** `FormData` entries as comparable strings; a `File` counts as unchanged (design 3.2 item 2). */\nfunction entryStrings(entries: readonly FormDataEntryValue[]): string[] {\n return entries.map((entry) => (typeof entry === \"string\" ? entry : \"\\u0000file\"));\n}\n\n/**\n * The field: a `div` that owns the ids, the urgent validity mirror, the custom-validity slot\n * (`validate` and the server error), the control registration and the native listeners\n * (design/components/field-form.md 2, 14). `data-pending` is the enclosing form's submission\n * (`useFormStatus`), the one part that folds the form channel into its own state, because a\n * Field has no action of its own.\n *\n * Owned keys (conventions 1.2): `data-invalid`, `data-disabled`, `data-required`, `data-pending`.\n *\n * @see https://ui.funstack.work/components/field\n */\nexport function FieldRoot({\n name,\n disabled = false,\n required = false,\n validate,\n className,\n style,\n children,\n render,\n ...rest\n}: FieldRootProps) {\n const parent = use(FieldContext);\n const form = use(FormContext);\n useDevWarning(\n parent !== null,\n isDev &&\n \"Field.Root: nested inside another Field.Root. A control registers with the nearest Field \" +\n \"only; give each control its own, sibling Field.\",\n );\n useDevWarning(\n validate !== undefined && name === undefined,\n isDev &&\n \"Field.Root: `validate` without `name`. `validate` receives `formData.get(name)`, which is \" +\n 'always \"\" without a name.',\n );\n\n const id = useId();\n const ids = useMemo(\n () => ({\n control: `${id}-control`,\n label: `${id}-label`,\n description: `${id}-description`,\n error: `${id}-error`,\n }),\n [id],\n );\n\n const { pending: formPending } = useFormStatus();\n\n // --- Registration -------------------------------------------------------------------------\n\n const controlRef = useRef<FieldControlRegistration | null>(null);\n const [control, setControl] = useState<FieldControlRegistration | null>(null);\n const warnedTwoControls = useRef(false);\n const registerControl = useCallback((registration: FieldControlRegistration) => {\n const current = controlRef.current;\n if (current !== null && current.element !== registration.element) {\n if (isDev && !warnedTwoControls.current) {\n warnedTwoControls.current = true;\n console.error(\n \"Field.Root: two form controls registered in one Field. The first one is the \" +\n \"Field's control; give each control its own Field.Root.\",\n );\n }\n return () => {};\n }\n controlRef.current = registration;\n setControl(registration);\n return () => {\n if (controlRef.current !== registration) return;\n controlRef.current = null;\n setControl(null);\n };\n }, []);\n\n const errorCount = useRef(0);\n const registerError = useCallback(() => {\n errorCount.current += 1;\n if (isDev && errorCount.current === 2) {\n console.error(\n \"Field.Error: two Field.Error parts in one Field.Root. Render one; its function \" +\n \"`children` receives `validity` for per-constraint wording.\",\n );\n }\n return () => {\n errorCount.current -= 1;\n };\n }, []);\n\n // --- Server errors: shown, dismissed, re-armed, suppressed (design 3.4) -------------------\n\n const errors = form?.errors;\n const serverMessages = useMemo(\n () => normaliseErrorValue(name === undefined ? undefined : errors?.[name]),\n [errors, name],\n );\n const serverKey = serverMessages.join(\"\\n\");\n const { serverShown, dismiss, setSuppressNext } = useServerErrorVisibility(\n formPending,\n serverMessages,\n );\n\n // --- The mirror -----------------------------------------------------------------------------\n\n const [mirror, setMirror] = useState<Mirror>(INITIAL_MIRROR);\n /** The last mirror written: `refresh` compares against it, so an unchanged read renders nothing. */\n const mirrorRef = useRef<Mirror>(INITIAL_MIRROR);\n /** jsdom fallback for `:user-invalid` (design 2.2): `invalid` fired, cleared by a reset. */\n const attempted = useRef(false);\n /** The element the slot was last written on (a group's first member can change). */\n const slotElement = useRef<ValidatableElement | null>(null);\n\n const latest = useLatest({ name, validate, serverMessages, serverShown, formPending, form });\n\n /** Re-reads the slot and the mirror; returns the messages the Field shows for the control. */\n const refresh = useCallback(\n (options: RefreshOptions = {}): readonly string[] => {\n const registration = controlRef.current;\n if (registration === null) return NONE;\n // The element whose validity is real (field-form.md, `validityElement`) and the\n // element whose `:user-invalid` the user's interaction sets; the same for every control but\n // NumberField.\n const surface = validityElementOf(registration.element);\n const el = registration.validityElement?.() ?? surface;\n if (el === null) return NONE;\n const { name, validate, serverMessages, serverShown, formPending, form } = latest.current;\n\n const owner = el.form;\n const formData = owner === null ? new FormData() : new FormData(owner);\n const entry = name === undefined ? null : formData.get(name);\n const value = typeof entry === \"string\" ? entry : \"\";\n const custom = validate === undefined ? NONE : normaliseErrorValue(validate(value, formData));\n\n // The slot (design 2.1): the server message while shown, else `validate`'s.\n const showServer = serverShown && options.dismiss !== true;\n if (slotElement.current !== null && slotElement.current !== el) {\n slotElement.current.setCustomValidity(\"\");\n }\n slotElement.current = el;\n el.setCustomValidity(showServer ? serverMessages.join(\"\\n\") : custom.join(\"\\n\"));\n // Mirror onto the surface so its `:user-invalid` read below sees the new state (the control\n // writes the same derived value after each of its own writes).\n if (\n surface !== null &&\n surface !== el &&\n surface.validationMessage !== el.validationMessage\n ) {\n surface.setCustomValidity(el.validationMessage);\n }\n\n if (options.reset === true) attempted.current = false;\n const userInvalid = supportsUserInvalid()\n ? (surface ?? el).matches(\":user-invalid\")\n : attempted.current && !el.validity.valid;\n const validity = snapshotValidity(el.validity);\n const messages = validity.valid\n ? NONE\n : validity.customError && !showServer && custom.length > 0\n ? custom\n : el.validationMessage === \"\"\n ? NONE\n : [el.validationMessage];\n const next: Mirror = { userInvalid, validity, messages };\n // Only a change schedules a render (a `focusout` with nothing new causes none).\n if (!mirrorEquals(mirrorRef.current, next)) {\n mirrorRef.current = next;\n setMirror(next);\n }\n\n // Stale-value suppression (design 3.2 item 2): while the Form's own submission is in\n // flight, an error is about the value it sent; compare with what the field holds now.\n const submitted = formPending && name !== undefined ? (form?.submittedData() ?? null) : null;\n if (submitted !== null && name !== undefined) {\n setSuppressNext(\n !arraysEqual(entryStrings(formData.getAll(name)), entryStrings(submitted.getAll(name))),\n );\n }\n return showServer ? serverMessages : messages;\n },\n [latest, setSuppressNext],\n );\n\n // The slot follows the server error and `validate` (and is written once the control is known).\n // Keyed on `validate`'s identity (design 2.1): a rule reading outside state updates in the\n // commit that changed it. An inline function re-runs on every render (documented: `useCallback`\n // avoids it); the form's own values are covered by the listeners below.\n useLayoutEffect(() => {\n refresh();\n }, [refresh, control, serverShown, serverKey, validate]);\n\n // Clear the slot when the control goes away (it may be reused outside the Field).\n useLayoutEffect(\n () => () => {\n slotElement.current?.setCustomValidity(\"\");\n slotElement.current = null;\n },\n [],\n );\n\n // The control's own events (capture, so a group's members are seen on its fieldset).\n const element = control?.element ?? null;\n useLayoutEffect(() => {\n if (element === null) return;\n const onEdit = () => {\n dismiss();\n refresh({ dismiss: true });\n };\n const onBlur = () => refresh();\n const onInvalid = (event: Event) => {\n const target = event.target as ValidatableElement;\n // A submission attempt sets user validity before validating; `checkValidity()` and\n // `reportValidity()` do not (design 2.5). The fallback cannot tell them apart.\n const attempt = supportsUserInvalid() ? target.matches(\":user-invalid\") : true;\n if (!supportsUserInvalid()) attempted.current = true;\n if (attempt && errorCount.current > 0) {\n event.preventDefault();\n const messages = refresh();\n collectInvalid(focusTargetOf(element), messages.join(\" \"), target);\n return;\n }\n refresh();\n };\n element.addEventListener(\"input\", onEdit, true);\n element.addEventListener(\"change\", onEdit, true);\n element.addEventListener(\"focusout\", onBlur, true);\n element.addEventListener(\"invalid\", onInvalid, true);\n // A control that cannot validate itself and keeps its validity on an element outside it\n // (MultiSelect's Trigger and its hidden validity `<select>`, multi-select.md B.10): the\n // `invalid` fires there. NumberField's surface validates itself (its hidden input's `invalid`\n // is cancelled and the visible input reports), so it is not listened to twice.\n const outside =\n validityElementOf(element) === null ? (control?.validityElement?.() ?? null) : null;\n const listenOutside = outside !== null && !element.contains(outside);\n if (listenOutside) outside.addEventListener(\"invalid\", onInvalid, true);\n return () => {\n element.removeEventListener(\"input\", onEdit, true);\n element.removeEventListener(\"change\", onEdit, true);\n element.removeEventListener(\"focusout\", onBlur, true);\n element.removeEventListener(\"invalid\", onInvalid, true);\n if (listenOutside) outside.removeEventListener(\"invalid\", onInvalid, true);\n };\n }, [element, control, refresh, dismiss]);\n\n // The form owner's events: another field's edit re-runs `validate` (cross-field rules); a reset\n // clears the user-validity flag, re-read when the controls hold their reset values.\n const ownerRef = useMemo<RefObject<Element | null>>(\n () => ({\n get current() {\n return controlRef.current?.element ?? null;\n },\n set current(_ignored) {},\n }),\n [],\n );\n const onOwnerEdit = (event: Event) => {\n const target = event.target;\n if (target instanceof Node && controlRef.current?.element.contains(target) === true) return;\n refresh();\n };\n useFormOwnerEvent(ownerRef, \"input\", onOwnerEdit);\n useFormOwnerEvent(ownerRef, \"change\", onOwnerEdit);\n // A new submission sends the current values: nothing differs from it yet (a queued second\n // submit arrives while the status stays pending, so the pending edge alone would miss it).\n useFormOwnerEvent(ownerRef, \"submit\", () => {\n setSuppressNext(false);\n });\n // After every listener and the reset algorithm, unless cancelled (conventions 3.8 rules 5, 7).\n useFormReset(ownerRef, () => refresh({ reset: true }));\n\n // Registration with the Form, for the first-error focus after a settle (design 3.5) and the\n // refresh of the other Fields on a change no DOM event carried.\n const registerField = form?.registerField;\n const formRegistration = useRef<FormFieldRegistration | null>(null);\n useLayoutEffect(() => {\n if (registerField === undefined) return;\n const registration: FormFieldRegistration = {\n getFocusTarget: () => focusTargetOf(controlRef.current?.element ?? null),\n showsServerError: () => latest.current.serverShown,\n serverMessages: () => latest.current.serverMessages,\n refresh: () => {\n refresh();\n },\n };\n formRegistration.current = registration;\n const unregister = registerField(registration);\n return () => {\n unregister();\n if (formRegistration.current === registration) formRegistration.current = null;\n };\n }, [registerField, latest, refresh]);\n\n const notifyChange = useCallback(\n (edit: boolean) => {\n if (edit) dismiss();\n refresh(edit ? { dismiss: true } : {});\n latest.current.form?.refreshFields(formRegistration.current);\n },\n [refresh, latest, dismiss],\n );\n\n // Development: a Field around something that is not a form control (Toggle, Menu, ...).\n useEffect(() => {\n if (!isDev || controlRef.current !== null) return;\n console.error(\n \"Field.Root: no form control registered. Render a Field.Control or a FUNSTACK form \" +\n \"control (Checkbox, Switch, RadioGroup, CheckboxGroup, Select, Combobox, MultiSelect, \" +\n \"Slider, NumberField) inside it.\",\n );\n }, []);\n\n const invalid = mirror.userInvalid || serverShown;\n const messages = serverShown ? serverMessages : mirror.userInvalid ? mirror.messages : NONE;\n const validity = mirror.validity;\n const stateDisabled = disabled || (control?.disabled ?? false);\n const stateRequired = required || (control?.required ?? false);\n // Memoised: the context value (and so every part) changes only with the state.\n const memoState = useMemo<FieldState>(\n () => ({\n invalid,\n messages,\n validity,\n disabled: stateDisabled,\n required: stateRequired,\n pending: formPending,\n }),\n [invalid, messages, validity, stateDisabled, stateRequired, formPending],\n );\n\n const labelable = control?.labelable ?? true;\n const controlElement = useCallback(() => controlRef.current?.element ?? null, []);\n const context = useMemo<FieldContextValue>(\n () => ({\n ids,\n name,\n disabled,\n required,\n state: memoState,\n labelable,\n controlElement,\n registerControl,\n registerError,\n notifyChange,\n }),\n [\n ids,\n name,\n disabled,\n required,\n memoState,\n labelable,\n controlElement,\n registerControl,\n registerError,\n notifyChange,\n ],\n );\n\n const element$ = useRender<ComponentPropsWithRef<\"div\">, FieldState>({\n defaultElement: \"div\",\n render,\n state: memoState,\n className,\n style,\n children,\n props: rest,\n libraryProps: fieldDataAttributes(memoState),\n });\n\n return <FieldContext value={context}>{element$}</FieldContext>;\n}\n\nFieldRoot.displayName = \"FieldRoot\";\n"],"mappings":";;;;;;;;;;;;;;;AA+CA,MAAM,QAAQ,QAAQ,IAAI,aAAa;AA+DvC,MAAM,OAA0B,OAAO,OAAO,CAAC,CAAC;AAChD,MAAM,iBAAyB;CAAE,aAAa;CAAO,UAAU;CA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W,CACzE;CAEA,MAAM,YAAY,SAAS,aAAa;CACxC,MAAM,iBAAiB,kBAAkB,WAAW,SAAS,WAAW,MAAM,CAAC,CAAC;CAChF,MAAM,UAAU,eACP;EACL;EACA;EACA;EACA;EACA,OAAO;EACP;EACA;EACA;EACA;EACA;CACF,IACA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CACF;CAEA,MAAM,WAAW,UAAoD;EACnE,gBAAgB;EAChB;EACA,OAAO;EACP;EACA;EACA;EACA,OAAO;EACP,cAAc,oBAAoB,SAAS;CAC7C,CAAC;CAED,OAAO,oBAAC,cAAD;EAAc,OAAO;EAAU,UAAA;CAAuB,CAAA;AAC/D;AAEA,UAAU,cAAc"}
|
|
1
|
+
{"version":3,"file":"field-root.mjs","names":[],"sources":["../../src/field/field-root.tsx"],"sourcesContent":["\"use client\";\nimport {\n use,\n useCallback,\n useEffect,\n useId,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport type { ComponentPropsWithRef, CSSProperties, ReactNode, RefObject } from \"react\";\nimport { flushSync, useFormStatus } from \"react-dom\";\nimport { FieldContext, fieldDataAttributes, FormContext } from \"../internal/form/field-context.js\";\nimport type {\n FieldContextValue,\n FieldControlRegistration,\n FieldState,\n FormFieldRegistration,\n} from \"../internal/form/field-context.js\";\nimport { afterDispatch } from \"../internal/after-dispatch.js\";\nimport { collectInvalid } from \"../internal/form/focus-first-invalid.js\";\nimport type { RenderProp, StateValue } from \"../internal/types.js\";\nimport { useDevWarning } from \"../internal/use-dev-warning.js\";\nimport { useFormOwnerEvent } from \"../internal/form/use-form-owner-event.js\";\nimport { useFormReset } from \"../internal/form/use-form-reset.js\";\nimport { useLatest } from \"../internal/use-latest.js\";\nimport { useRender } from \"../internal/use-render.js\";\nimport { useServerErrorVisibility } from \"./use-server-error-visibility.js\";\nimport {\n focusTargetOf,\n normaliseErrorValue,\n snapshotValidity,\n supportsUserInvalid,\n VALID,\n validityElementOf,\n validityEquals,\n} from \"../internal/form/validity.js\";\nimport type {\n FieldErrorValue,\n FieldValidity,\n ValidatableElement,\n} from \"../internal/form/validity.js\";\nimport { arraysEqual } from \"../internal/value-set.js\";\n\nexport type { FieldState } from \"../internal/form/field-context.js\";\nexport type { FieldValidity } from \"../internal/form/validity.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/**\n * A custom constraint: receives the field's submitted value (`formData.get(name)` as a string,\n * `\"\"` when absent) and the whole form's `FormData`. Return a message (or several) for an error,\n * `null` / `undefined` / `\"\"` for none.\n */\nexport type FieldValidate = (value: string, formData: FormData) => FieldErrorValue;\n\n/**\n * Props of `Field.Root`.\n *\n * @see https://ui.funstack.work/components/field\n */\nexport interface FieldRootProps extends Omit<\n ComponentPropsWithRef<\"div\">,\n \"className\" | \"style\" | \"children\"\n> {\n /** Form field name: the control's default `name`, the key in `Form.Root errors`, and the entry `validate` reads. */\n name?: string;\n /**\n * Disables the control (native `disabled`) and marks every part `data-disabled`.\n *\n * @defaultValue `false`\n */\n disabled?: boolean;\n /**\n * Makes the control `required` (native) and marks every part `data-required`.\n *\n * @defaultValue `false`\n */\n required?: boolean;\n /**\n * A custom constraint, written into the control with `setCustomValidity`. Sync. Receives the\n * field's submitted value (`formData.get(name)` as a string, `\"\"` when absent) and the whole\n * form's `FormData`, so a cross-field rule can read the other field. Runs at mount, on every\n * `input` / `change` in the form (and a FUNSTACK control's value change), on blur, after a\n * reset, on a submission attempt, and in every commit in which this prop changed identity, so\n * a rule that reads outside state (a list that loads, a sibling value in React state) updates\n * on render. An inline function therefore re-runs on every render of the Field; wrap it in\n * `useCallback` to re-run only when its inputs change. Return a string\n * or strings for an error, `null` / `undefined` / `\"\"` for none. Shown when the platform's\n * `:user-invalid` heuristic says so, like a native constraint. Not serialisable: a Field with\n * `validate` is rendered from a client component.\n */\n validate?: FieldValidate;\n /** Class name, or a function of the part's state that returns one. */\n className?: StateValue<string | undefined, FieldState>;\n /** Inline style, or a function of the part's state that returns one. */\n style?: StateValue<CSSProperties | undefined, FieldState>;\n /** Content, or a function of the part's state. */\n children?: StateValue<ReactNode, FieldState>;\n /** Replace the default `<div>` (element form) or take over rendering (function form). */\n render?: RenderProp<ComponentPropsWithRef<\"div\">, FieldState>;\n}\n\n/** The urgent mirror of browser-owned validity (design 2.4). */\ninterface Mirror {\n readonly userInvalid: boolean;\n readonly validity: FieldValidity;\n readonly messages: readonly string[];\n}\n\nconst NONE: readonly string[] = Object.freeze([]);\nconst INITIAL_MIRROR: Mirror = { userInvalid: false, validity: VALID, messages: NONE };\n\ninterface RefreshOptions {\n /** The user edited the control: the server message is dropped from the slot at once. */\n readonly dismiss?: boolean;\n /** After a form reset: the user-validity flag is clear again. */\n readonly reset?: boolean;\n}\n\n/** What `writeSlot` computed, for the mirror read that follows it. */\ninterface SlotRead {\n readonly el: ValidatableElement;\n readonly surface: ValidatableElement | null;\n readonly formData: FormData;\n readonly custom: readonly string[];\n readonly showServer: boolean;\n}\n\nfunction mirrorEquals(a: Mirror, b: Mirror): boolean {\n return (\n a.userInvalid === b.userInvalid &&\n validityEquals(a.validity, b.validity) &&\n arraysEqual(a.messages, b.messages)\n );\n}\n\n/** `FormData` entries as comparable strings; a `File` counts as unchanged (design 3.2 item 2). */\nfunction entryStrings(entries: readonly FormDataEntryValue[]): string[] {\n return entries.map((entry) => (typeof entry === \"string\" ? entry : \"\\u0000file\"));\n}\n\n/**\n * The field: a `div` that owns the ids, the urgent validity mirror, the custom-validity slot\n * (`validate` and the server error), the control registration and the native listeners\n * (design/components/field-form.md 2, 14). `data-pending` is the enclosing form's submission\n * (`useFormStatus`), the one part that folds the form channel into its own state, because a\n * Field has no action of its own.\n *\n * Owned keys (conventions 1.2): `data-invalid`, `data-disabled`, `data-required`, `data-pending`.\n *\n * @see https://ui.funstack.work/components/field\n */\nexport function FieldRoot({\n name,\n disabled = false,\n required = false,\n validate,\n className,\n style,\n children,\n render,\n ...rest\n}: FieldRootProps) {\n const parent = use(FieldContext);\n const form = use(FormContext);\n useDevWarning(\n parent !== null,\n isDev &&\n \"Field.Root: nested inside another Field.Root. A control registers with the nearest Field \" +\n \"only; give each control its own, sibling Field.\",\n );\n useDevWarning(\n validate !== undefined && name === undefined,\n isDev &&\n \"Field.Root: `validate` without `name`. `validate` receives `formData.get(name)`, which is \" +\n 'always \"\" without a name.',\n );\n\n const id = useId();\n const ids = useMemo(\n () => ({\n control: `${id}-control`,\n label: `${id}-label`,\n description: `${id}-description`,\n error: `${id}-error`,\n }),\n [id],\n );\n\n const { pending: formPending } = useFormStatus();\n\n // --- Registration -------------------------------------------------------------------------\n\n const controlRef = useRef<FieldControlRegistration | null>(null);\n const [control, setControl] = useState<FieldControlRegistration | null>(null);\n const warnedTwoControls = useRef(false);\n const registerControl = useCallback((registration: FieldControlRegistration) => {\n const current = controlRef.current;\n if (current !== null && current.element !== registration.element) {\n if (isDev && !warnedTwoControls.current) {\n warnedTwoControls.current = true;\n console.error(\n \"Field.Root: two form controls registered in one Field. The first one is the \" +\n \"Field's control; give each control its own Field.Root.\",\n );\n }\n return () => {};\n }\n controlRef.current = registration;\n setControl(registration);\n return () => {\n if (controlRef.current !== registration) return;\n controlRef.current = null;\n setControl(null);\n };\n }, []);\n\n const errorCount = useRef(0);\n const registerError = useCallback(() => {\n errorCount.current += 1;\n if (isDev && errorCount.current === 2) {\n console.error(\n \"Field.Error: two Field.Error parts in one Field.Root. Render one; its function \" +\n \"`children` receives `validity` for per-constraint wording.\",\n );\n }\n return () => {\n errorCount.current -= 1;\n };\n }, []);\n\n // --- Server errors: shown, dismissed, re-armed, suppressed (design 3.4) -------------------\n\n const errors = form?.errors;\n const serverMessages = useMemo(\n () => normaliseErrorValue(name === undefined ? undefined : errors?.[name]),\n [errors, name],\n );\n const serverKey = serverMessages.join(\"\\n\");\n const { serverShown, dismiss, recordEdit, setSuppressNext } = useServerErrorVisibility(\n formPending,\n serverMessages,\n );\n\n // --- The mirror -----------------------------------------------------------------------------\n\n const [mirror, setMirror] = useState<Mirror>(INITIAL_MIRROR);\n /** The last mirror written: `refresh` compares against it, so an unchanged read renders nothing. */\n const mirrorRef = useRef<Mirror>(INITIAL_MIRROR);\n /** jsdom fallback for `:user-invalid` (design 2.2): `invalid` fired, cleared by a reset. */\n const attempted = useRef(false);\n /** The element the slot was last written on (a group's first member can change). */\n const slotElement = useRef<ValidatableElement | null>(null);\n\n const latest = useLatest({ name, validate, serverMessages, serverShown, formPending, form });\n /** An edit of the control whose state write is pending (`refreshAfterEdit`): its dismissal. */\n const pendingEdit = useRef<(() => void) | null>(null);\n\n /**\n * Recomputes and writes the custom-validity slot (design 2.1). No React state is written, so it\n * is safe in any listener; `null` when there is no control (or no element to validate).\n */\n const writeSlot = useCallback(\n (options: RefreshOptions = {}): SlotRead | null => {\n const registration = controlRef.current;\n if (registration === null) return null;\n // The element whose validity is real (field-form.md, `validityElement`) and the\n // element whose `:user-invalid` the user's interaction sets; the same for every control but\n // NumberField.\n const surface = validityElementOf(registration.element);\n const el = registration.validityElement?.() ?? surface;\n if (el === null) return null;\n const { name, validate, serverMessages, serverShown } = latest.current;\n\n const owner = el.form;\n const formData = owner === null ? new FormData() : new FormData(owner);\n const entry = name === undefined ? null : formData.get(name);\n const value = typeof entry === \"string\" ? entry : \"\";\n const custom = validate === undefined ? NONE : normaliseErrorValue(validate(value, formData));\n\n // The slot (design 2.1): the server message while shown, else `validate`'s. An edit whose\n // dismissal is not written yet (2.4) already counts: a submission attempt before it\n // (an Enter in the next task) must not be blocked by the message the user edited away.\n const showServer = serverShown && options.dismiss !== true && pendingEdit.current === null;\n if (slotElement.current !== null && slotElement.current !== el) {\n slotElement.current.setCustomValidity(\"\");\n }\n slotElement.current = el;\n el.setCustomValidity(showServer ? serverMessages.join(\"\\n\") : custom.join(\"\\n\"));\n // Mirror onto the surface so its `:user-invalid` read below sees the new state (the control\n // writes the same derived value after each of its own writes).\n if (\n surface !== null &&\n surface !== el &&\n surface.validationMessage !== el.validationMessage\n ) {\n surface.setCustomValidity(el.validationMessage);\n }\n return { el, surface, formData, custom, showServer };\n },\n [latest],\n );\n\n /** Re-reads the slot and the mirror; returns the messages the Field shows for the control. */\n const refresh = useCallback(\n (options: RefreshOptions = {}): readonly string[] => {\n const read = writeSlot(options);\n if (read === null) return NONE;\n const { el, surface, formData, custom, showServer } = read;\n const { name, serverMessages, formPending, form } = latest.current;\n\n if (options.reset === true) attempted.current = false;\n const userInvalid = supportsUserInvalid()\n ? (surface ?? el).matches(\":user-invalid\")\n : attempted.current && !el.validity.valid;\n const validity = snapshotValidity(el.validity);\n const messages = validity.valid\n ? NONE\n : validity.customError && !showServer && custom.length > 0\n ? custom\n : el.validationMessage === \"\"\n ? NONE\n : [el.validationMessage];\n const next: Mirror = { userInvalid, validity, messages };\n // Only a change schedules a render (a `focusout` with nothing new causes none).\n if (!mirrorEquals(mirrorRef.current, next)) {\n mirrorRef.current = next;\n setMirror(next);\n }\n\n // Stale-value suppression (design 3.2 item 2): while the Form's own submission is in\n // flight, an error is about the value it sent; compare with what the field holds now.\n const submitted = formPending && name !== undefined ? (form?.submittedData() ?? null) : null;\n if (submitted !== null && name !== undefined) {\n setSuppressNext(\n !arraysEqual(entryStrings(formData.getAll(name)), entryStrings(submitted.getAll(name))),\n );\n }\n return showServer ? serverMessages : messages;\n },\n [latest, setSuppressNext, writeSlot],\n );\n\n /** The pending state write of the last edit, cancelled by the next one (it covers both). */\n const cancelEditRefresh = useRef<(() => void) | null>(null);\n /**\n * An `input` / `change` (the control's own, or another field's on the form owner): the slot now,\n * the state after the event's dispatch (design 2.4, `afterDispatch`). A state write in the\n * listener would commit in the microtask checkpoint Chromium runs after it, before React's own\n * listener has seen the event, and that commit writes a controlled input's previous `value`\n * back over the keystroke (#193). After the dispatch the slot is recomputed too, from the value\n * React settled on (a controlled parent that did not adopt the text restores the old one).\n */\n const refreshAfterEdit = useCallback(\n (event: Event, edit: boolean): void => {\n // An own edit still pending dismisses when another field's edit replaces its write.\n const applyEdit = edit ? recordEdit() : pendingEdit.current;\n pendingEdit.current = applyEdit;\n writeSlot({ dismiss: applyEdit !== null });\n cancelEditRefresh.current?.();\n const cancel = afterDispatch(event, () => {\n // Defence in depth: the next edit cancels this call, but only the latest write may run.\n if (cancelEditRefresh.current !== cancel) return;\n cancelEditRefresh.current = null;\n pendingEdit.current = null;\n // Committed at once, as the listener's own write used to be: outside any event React\n // would give these writes the default lane and a paint could show the old error state.\n // The dispatch is over, so a synchronous commit can no longer clobber the keystroke.\n flushSync(() => {\n applyEdit?.();\n refresh({ dismiss: applyEdit !== null });\n });\n });\n cancelEditRefresh.current = cancel;\n },\n [writeSlot, refresh, recordEdit],\n );\n // Nothing is written after the Field is gone.\n useLayoutEffect(\n () => () => {\n cancelEditRefresh.current?.();\n cancelEditRefresh.current = null;\n },\n [],\n );\n\n // The slot follows the server error and `validate` (and is written once the control is known).\n // Keyed on `validate`'s identity (design 2.1): a rule reading outside state updates in the\n // commit that changed it. An inline function re-runs on every render (documented: `useCallback`\n // avoids it); the form's own values are covered by the listeners below.\n useLayoutEffect(() => {\n refresh();\n }, [refresh, control, serverShown, serverKey, validate]);\n\n // Clear the slot when the control goes away (it may be reused outside the Field).\n useLayoutEffect(\n () => () => {\n slotElement.current?.setCustomValidity(\"\");\n slotElement.current = null;\n },\n [],\n );\n\n // The control's own events (capture, so a group's members are seen on its fieldset).\n const element = control?.element ?? null;\n useLayoutEffect(() => {\n if (element === null) return;\n const onEdit = (event: Event) => refreshAfterEdit(event, true);\n const onBlur = () => refresh();\n const onInvalid = (event: Event) => {\n const target = event.target as ValidatableElement;\n // A submission attempt sets user validity before validating; `checkValidity()` and\n // `reportValidity()` do not (design 2.5). The fallback cannot tell them apart.\n const attempt = supportsUserInvalid() ? target.matches(\":user-invalid\") : true;\n if (!supportsUserInvalid()) attempted.current = true;\n if (attempt && errorCount.current > 0) {\n event.preventDefault();\n const messages = refresh();\n collectInvalid(focusTargetOf(element), messages.join(\" \"), target);\n return;\n }\n refresh();\n };\n element.addEventListener(\"input\", onEdit, true);\n element.addEventListener(\"change\", onEdit, true);\n element.addEventListener(\"focusout\", onBlur, true);\n element.addEventListener(\"invalid\", onInvalid, true);\n // A control that cannot validate itself and keeps its validity on an element outside it\n // (MultiSelect's Trigger and its hidden validity `<select>`, multi-select.md B.10): the\n // `invalid` fires there. NumberField's surface validates itself (its hidden input's `invalid`\n // is cancelled and the visible input reports), so it is not listened to twice.\n const outside =\n validityElementOf(element) === null ? (control?.validityElement?.() ?? null) : null;\n const listenOutside = outside !== null && !element.contains(outside);\n if (listenOutside) outside.addEventListener(\"invalid\", onInvalid, true);\n return () => {\n element.removeEventListener(\"input\", onEdit, true);\n element.removeEventListener(\"change\", onEdit, true);\n element.removeEventListener(\"focusout\", onBlur, true);\n element.removeEventListener(\"invalid\", onInvalid, true);\n if (listenOutside) outside.removeEventListener(\"invalid\", onInvalid, true);\n };\n }, [element, control, refresh, refreshAfterEdit]);\n\n // The form owner's events: another field's edit re-runs `validate` (cross-field rules); a reset\n // clears the user-validity flag, re-read when the controls hold their reset values.\n const ownerRef = useMemo<RefObject<Element | null>>(\n () => ({\n get current() {\n return controlRef.current?.element ?? null;\n },\n set current(_ignored) {},\n }),\n [],\n );\n const onOwnerEdit = (event: Event) => {\n const target = event.target;\n if (target instanceof Node && controlRef.current?.element.contains(target) === true) return;\n refreshAfterEdit(event, false);\n };\n useFormOwnerEvent(ownerRef, \"input\", onOwnerEdit);\n useFormOwnerEvent(ownerRef, \"change\", onOwnerEdit);\n // A new submission sends the current values: nothing differs from it yet (a queued second\n // submit arrives while the status stays pending, so the pending edge alone would miss it).\n useFormOwnerEvent(ownerRef, \"submit\", () => {\n setSuppressNext(false);\n });\n // After every listener and the reset algorithm, unless cancelled (conventions 3.8 rules 5, 7).\n useFormReset(ownerRef, () => refresh({ reset: true }));\n\n // Registration with the Form, for the first-error focus after a settle (design 3.5) and the\n // refresh of the other Fields on a change no DOM event carried.\n const registerField = form?.registerField;\n const formRegistration = useRef<FormFieldRegistration | null>(null);\n useLayoutEffect(() => {\n if (registerField === undefined) return;\n const registration: FormFieldRegistration = {\n getFocusTarget: () => focusTargetOf(controlRef.current?.element ?? null),\n // An edit whose dismissal is not written yet already counts (design 2.4).\n showsServerError: () => latest.current.serverShown && pendingEdit.current === null,\n serverMessages: () => latest.current.serverMessages,\n refresh: () => {\n refresh();\n },\n };\n formRegistration.current = registration;\n const unregister = registerField(registration);\n return () => {\n unregister();\n if (formRegistration.current === registration) formRegistration.current = null;\n };\n }, [registerField, latest, refresh]);\n\n const notifyChange = useCallback(\n (edit: boolean) => {\n if (edit) dismiss();\n refresh(edit ? { dismiss: true } : {});\n latest.current.form?.refreshFields(formRegistration.current);\n },\n [refresh, latest, dismiss],\n );\n\n // Development: a Field around something that is not a form control (Toggle, Menu, ...).\n useEffect(() => {\n if (!isDev || controlRef.current !== null) return;\n console.error(\n \"Field.Root: no form control registered. Render a Field.Control or a FUNSTACK form \" +\n \"control (Checkbox, Switch, RadioGroup, CheckboxGroup, Select, Combobox, MultiSelect, \" +\n \"Slider, NumberField) inside it.\",\n );\n }, []);\n\n const invalid = mirror.userInvalid || serverShown;\n const messages = serverShown ? serverMessages : mirror.userInvalid ? mirror.messages : NONE;\n const validity = mirror.validity;\n const stateDisabled = disabled || (control?.disabled ?? false);\n const stateRequired = required || (control?.required ?? false);\n // Memoised: the context value (and so every part) changes only with the state.\n const memoState = useMemo<FieldState>(\n () => ({\n invalid,\n messages,\n validity,\n disabled: stateDisabled,\n required: stateRequired,\n pending: formPending,\n }),\n [invalid, messages, validity, stateDisabled, stateRequired, formPending],\n );\n\n const labelable = control?.labelable ?? true;\n const controlElement = useCallback(() => controlRef.current?.element ?? null, []);\n const context = useMemo<FieldContextValue>(\n () => ({\n ids,\n name,\n disabled,\n required,\n state: memoState,\n labelable,\n controlElement,\n registerControl,\n registerError,\n notifyChange,\n }),\n [\n ids,\n name,\n disabled,\n required,\n memoState,\n labelable,\n controlElement,\n registerControl,\n registerError,\n notifyChange,\n ],\n );\n\n const element$ = useRender<ComponentPropsWithRef<\"div\">, FieldState>({\n defaultElement: \"div\",\n render,\n state: memoState,\n className,\n style,\n children,\n props: rest,\n libraryProps: fieldDataAttributes(memoState),\n });\n\n return <FieldContext value={context}>{element$}</FieldContext>;\n}\n\nFieldRoot.displayName = \"FieldRoot\";\n"],"mappings":";;;;;;;;;;;;;;;;AAgDA,MAAM,QAAQ,QAAQ,IAAI,aAAa;AA+DvC,MAAM,OAA0B,OAAO,OAAO,CAAC,CAAC;AAChD,MAAM,iBAAyB;CAAE,aAAa;CAAO,UAAU;CAAO,UAAU;AAAK;AAkBrF,SAAS,aAAa,GAAW,GAAoB;CACnD,OACE,EAAE,gBAAgB,EAAE,eACpB,eAAe,EAAE,UAAU,EAAE,QAAQ,KACrC,YAAY,EAAE,UAAU,EAAE,QAAQ;AAEtC;;AAGA,SAAS,aAAa,SAAkD;CACtE,OAAO,QAAQ,KAAK,UAAW,OAAO,UAAU,WAAW,QAAQ,QAAa;AAClF;;;;;;;;;;;;AAaA,SAAgB,UAAU,EACxB,MACA,WAAW,OACX,WAAW,OACX,UACA,WACA,OACA,UACA,QACA,GAAG,QACc;CACjB,MAAM,SAAS,IAAI,YAAY;CAC/B,MAAM,OAAO,IAAI,WAAW;CAC5B,cACE,WAAW,MACX,SACE,0IAEJ;CACA,cACE,aAAa,KAAA,KAAa,SAAS,KAAA,GACnC,SACE,uHAEJ;CAEA,MAAM,KAAK,MAAM;CACjB,MAAM,MAAM,eACH;EACL,SAAS,GAAG,GAAG;EACf,OAAO,GAAG,GAAG;EACb,aAAa,GAAG,GAAG;EACnB,OAAO,GAAG,GAAG;CACf,IACA,CAAC,EAAE,CACL;CAEA,MAAM,EAAE,SAAS,gBAAgB,cAAc;CAI/C,MAAM,aAAa,OAAwC,IAAI;CAC/D,MAAM,CAAC,SAAS,cAAc,SAA0C,IAAI;CAC5E,MAAM,oBAAoB,OAAO,KAAK;CACtC,MAAM,kBAAkB,aAAa,iBAA2C;EAC9E,MAAM,UAAU,W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U;EAAe;EAAe;CAAW,CACzE;CAEA,MAAM,YAAY,SAAS,aAAa;CACxC,MAAM,iBAAiB,kBAAkB,WAAW,SAAS,WAAW,MAAM,CAAC,CAAC;CAChF,MAAM,UAAU,eACP;EACL;EACA;EACA;EACA;EACA,OAAO;EACP;EACA;EACA;EACA;EACA;CACF,IACA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CACF;CAEA,MAAM,WAAW,UAAoD;EACnE,gBAAgB;EAChB;EACA,OAAO;EACP;EACA;EACA;EACA,OAAO;EACP,cAAc,oBAAoB,SAAS;CAC7C,CAAC;CAED,OAAO,oBAAC,cAAD;EAAc,OAAO;EAAU,UAAA;CAAuB,CAAA;AAC/D;AAEA,UAAU,cAAc"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import { useCallback, useState } from "react";
|
|
2
|
+
import { useCallback, useLayoutEffect, useRef, useState } from "react";
|
|
3
3
|
// src/field/use-server-error-visibility.ts
|
|
4
4
|
/**
|
|
5
5
|
* When `Field.Root` shows the server error for its field (design 3.4): shown, dismissed by an
|
|
@@ -11,8 +11,14 @@ import { useCallback, useState } from "react";
|
|
|
11
11
|
* same commit, before the Form's settle effect focuses them.
|
|
12
12
|
*/
|
|
13
13
|
function useServerErrorVisibility(formPending, serverMessages) {
|
|
14
|
-
/**
|
|
15
|
-
const [
|
|
14
|
+
/** Settles seen so far: an edit dismisses the errors of the settle it was made after. */
|
|
15
|
+
const [settles, setSettles] = useState(0);
|
|
16
|
+
/**
|
|
17
|
+
* The `settles` count at the user's last edit (`-1`: none). Dismissed while it equals `settles`.
|
|
18
|
+
* A count, not a flag: an edit applied late (after its event's dispatch) and React's rebase of
|
|
19
|
+
* that update over a settle's render-phase reset both leave a stale count, never a stale flag.
|
|
20
|
+
*/
|
|
21
|
+
const [editedAt, setEditedAt] = useState(-1);
|
|
16
22
|
/**
|
|
17
23
|
* The errors shown now answer a value the user had already changed during their flight
|
|
18
24
|
* (intercepted path). Fixed from one settle to the next, so a hidden stale error stays hidden
|
|
@@ -26,15 +32,24 @@ function useServerErrorVisibility(formPending, serverMessages) {
|
|
|
26
32
|
setPreviousFormPending(formPending);
|
|
27
33
|
if (formPending) setSuppressNext(false);
|
|
28
34
|
else {
|
|
29
|
-
|
|
35
|
+
setSettles(settles + 1);
|
|
30
36
|
setSuppressed(suppressNext);
|
|
31
37
|
setSuppressNext(false);
|
|
32
38
|
}
|
|
33
39
|
}
|
|
34
|
-
const
|
|
40
|
+
const committedSettles = useRef(settles);
|
|
41
|
+
useLayoutEffect(() => {
|
|
42
|
+
committedSettles.current = settles;
|
|
43
|
+
});
|
|
44
|
+
const recordEdit = useCallback(() => {
|
|
45
|
+
const at = committedSettles.current;
|
|
46
|
+
return () => setEditedAt(at);
|
|
47
|
+
}, []);
|
|
48
|
+
const dismiss = useCallback(() => recordEdit()(), [recordEdit]);
|
|
35
49
|
return {
|
|
36
|
-
serverShown: serverMessages.length > 0 &&
|
|
50
|
+
serverShown: serverMessages.length > 0 && editedAt !== settles && !suppressed,
|
|
37
51
|
dismiss,
|
|
52
|
+
recordEdit,
|
|
38
53
|
setSuppressNext
|
|
39
54
|
};
|
|
40
55
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-server-error-visibility.mjs","names":[],"sources":["../../src/field/use-server-error-visibility.ts"],"sourcesContent":["\"use client\";\nimport { useCallback, useState } from \"react\";\n\nexport interface ServerErrorVisibility {\n /** The server's messages for this field are shown. */\n readonly serverShown: boolean;\n
|
|
1
|
+
{"version":3,"file":"use-server-error-visibility.mjs","names":[],"sources":["../../src/field/use-server-error-visibility.ts"],"sourcesContent":["\"use client\";\nimport { useCallback, useLayoutEffect, useRef, useState } from \"react\";\n\nexport interface ServerErrorVisibility {\n /** The server's messages for this field are shown. */\n readonly serverShown: boolean;\n /**\n * Stable. The user edited the control: hide the server error until the next settle. The\n * synchronous form of `recordEdit()()`, for a caller that is already past the edit's event\n * (a FUNSTACK control's `notifyChange(true)` after its commit).\n */\n readonly dismiss: () => void;\n /**\n * Stable. Records an edit now and returns the state write that applies it, for a caller that\n * must not write state yet (an event still being dispatched, design 2.4). Applied after the next\n * settle, an edit recorded before it dismisses nothing: the settle re-armed the errors.\n */\n readonly recordEdit: () => () => void;\n /**\n * Stable. Whether the value differs from the one the submission in flight sent: if so, that\n * submission's errors stay hidden when it settles (design 3.2 item 2).\n */\n readonly setSuppressNext: (differs: boolean) => void;\n}\n\n/**\n * When `Field.Root` shows the server error for its field (design 3.4): shown, dismissed by an\n * edit, re-armed at the enclosing form's settle, and suppressed when it answers a value the user\n * had already changed during the flight.\n *\n * The settle edge is seen in the render that commits the result (the action's result and\n * `useFormStatus`'s NotPending land together), so the next submission's errors are shown in that\n * same commit, before the Form's settle effect focuses them.\n */\nexport function useServerErrorVisibility(\n formPending: boolean,\n serverMessages: readonly string[],\n): ServerErrorVisibility {\n /** Settles seen so far: an edit dismisses the errors of the settle it was made after. */\n const [settles, setSettles] = useState(0);\n /**\n * The `settles` count at the user's last edit (`-1`: none). Dismissed while it equals `settles`.\n * A count, not a flag: an edit applied late (after its event's dispatch) and React's rebase of\n * that update over a settle's render-phase reset both leave a stale count, never a stale flag.\n */\n const [editedAt, setEditedAt] = useState(-1);\n /**\n * The errors shown now answer a value the user had already changed during their flight\n * (intercepted path). Fixed from one settle to the next, so a hidden stale error stays hidden\n * while the next submission is in flight (the `errors` prop still holds that result).\n */\n const [suppressed, setSuppressed] = useState(false);\n /** The user changed the value during the flight in progress: becomes `suppressed` at its settle. */\n const [suppressNext, setSuppressNext] = useState(false);\n const [previousFormPending, setPreviousFormPending] = useState(formPending);\n if (previousFormPending !== formPending) {\n setPreviousFormPending(formPending);\n if (formPending) {\n setSuppressNext(false);\n } else {\n setSettles(settles + 1);\n setSuppressed(suppressNext);\n setSuppressNext(false);\n }\n }\n // The committed count, read when an edit is recorded.\n const committedSettles = useRef(settles);\n useLayoutEffect(() => {\n committedSettles.current = settles;\n });\n const recordEdit = useCallback(() => {\n const at = committedSettles.current;\n return () => setEditedAt(at);\n }, []);\n const dismiss = useCallback(() => recordEdit()(), [recordEdit]);\n return {\n serverShown: serverMessages.length > 0 && editedAt !== settles && !suppressed,\n dismiss,\n recordEdit,\n setSuppressNext,\n };\n}\n"],"mappings":";;;;;;;;;;;;AAkCA,SAAgB,yBACd,aACA,gBACuB;;CAEvB,MAAM,CAAC,SAAS,cAAc,SAAS,CAAC;;;;;;CAMxC,MAAM,CAAC,UAAU,eAAe,SAAS,EAAE;;;;;;CAM3C,MAAM,CAAC,YAAY,iBAAiB,SAAS,KAAK;;CAElD,MAAM,CAAC,cAAc,mBAAmB,SAAS,KAAK;CACtD,MAAM,CAAC,qBAAqB,0BAA0B,SAAS,WAAW;CAC1E,IAAI,wBAAwB,aAAa;EACvC,uBAAuB,WAAW;EAClC,IAAI,aACF,gBAAgB,KAAK;OAChB;GACL,WAAW,UAAU,CAAC;GACtB,cAAc,YAAY;GAC1B,gBAAgB,KAAK;EACvB;CACF;CAEA,MAAM,mBAAmB,OAAO,OAAO;CACvC,sBAAsB;EACpB,iBAAiB,UAAU;CAC7B,CAAC;CACD,MAAM,aAAa,kBAAkB;EACnC,MAAM,KAAK,iBAAiB;EAC5B,aAAa,YAAY,EAAE;CAC7B,GAAG,CAAC,CAAC;CACL,MAAM,UAAU,kBAAkB,WAAW,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC;CAC9D,OAAO;EACL,aAAa,eAAe,SAAS,KAAK,aAAa,WAAW,CAAC;EACnE;EACA;EACA;CACF;AACF"}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { useCallback, useEffect, useEffectEvent, useRef } from "react";
|
|
3
|
+
import { isEscapeRequest } from "../internal/escape-key.mjs";
|
|
4
|
+
import { containsOpenLayer } from "../internal/overlay/open-layer.mjs";
|
|
3
5
|
import { isPopoverOpen } from "../internal/overlay/popover-open.mjs";
|
|
4
6
|
import { createDelayedPair } from "../internal/use-delayed-pair.mjs";
|
|
5
7
|
// src/hover-card/use-hover-card-interest.ts
|
|
@@ -94,7 +96,7 @@ function attachInterest(trigger, popup, { disabled, interestForRequested, suppre
|
|
|
94
96
|
timers.cancel();
|
|
95
97
|
};
|
|
96
98
|
const onDocumentKeyDown = (event) => {
|
|
97
|
-
if (event
|
|
99
|
+
if (!isEscapeRequest(event)) return;
|
|
98
100
|
const isShown = shown();
|
|
99
101
|
if (!isShown && !env().root.intended()) return;
|
|
100
102
|
if (containsOpenLayer(popup, event)) return;
|
|
@@ -165,7 +167,7 @@ function attachInterest(trigger, popup, { disabled, interestForRequested, suppre
|
|
|
165
167
|
else dismiss(event, false);
|
|
166
168
|
});
|
|
167
169
|
listen(trigger, "keydown", (event) => {
|
|
168
|
-
if (event
|
|
170
|
+
if (!isEscapeRequest(event)) return;
|
|
169
171
|
suppressed.current = true;
|
|
170
172
|
timers.cancel();
|
|
171
173
|
});
|
|
@@ -220,29 +222,6 @@ function attachInterest(trigger, popup, { disabled, interestForRequested, suppre
|
|
|
220
222
|
}
|
|
221
223
|
};
|
|
222
224
|
}
|
|
223
|
-
/**
|
|
224
|
-
* Whether a popover or a modal dialog is open inside the card, or an open non-modal dialog inside
|
|
225
|
-
* it that `event` came from (design 2.6: that dialog decides its Escape after the document
|
|
226
|
-
* listeners, #177). Walks the elements and asks each, rather than one
|
|
227
|
-
* `querySelector(":popover-open")`, which the jsdom shim cannot answer.
|
|
228
|
-
*/
|
|
229
|
-
function containsOpenLayer(popup, event) {
|
|
230
|
-
for (const element of popup.querySelectorAll("[popover]")) if (isPopoverOpen(element)) return true;
|
|
231
|
-
const target = event.target;
|
|
232
|
-
for (const dialog of popup.querySelectorAll("dialog")) {
|
|
233
|
-
if (!dialog.open) continue;
|
|
234
|
-
if (isModal(dialog)) return true;
|
|
235
|
-
if (target instanceof Node && dialog.contains(target)) return true;
|
|
236
|
-
}
|
|
237
|
-
return false;
|
|
238
|
-
}
|
|
239
|
-
function isModal(dialog) {
|
|
240
|
-
try {
|
|
241
|
-
return dialog.matches(":modal");
|
|
242
|
-
} catch {
|
|
243
|
-
return false;
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
225
|
export { blurFocusInside, useHoverCardInterest };
|
|
247
226
|
|
|
248
227
|
//# sourceMappingURL=use-hover-card-interest.mjs.map
|