@solid2-aria/core 0.0.1 → 0.1.0
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/README.md +14 -0
- package/dist/NOTICE.txt +33 -11
- package/dist/browser/actiongroup/create-action-group.js +2 -1
- package/dist/browser/actiongroup/create-action-group.js.map +1 -1
- package/dist/browser/combobox/create-combo-box.js +2 -2
- package/dist/browser/combobox/create-combo-box.js.map +1 -1
- package/dist/browser/dnd/drag-preview.js +7 -8
- package/dist/browser/dnd/drag-preview.js.map +1 -1
- package/dist/browser/focus/focus-scope.js +2 -2
- package/dist/browser/focus/focus-scope.js.map +1 -1
- package/dist/browser/focus/virtual-focus.d.ts +1 -0
- package/dist/browser/focus/virtual-focus.js +20 -5
- package/dist/browser/focus/virtual-focus.js.map +1 -1
- package/dist/browser/grid/create-grid-cell.js +4 -4
- package/dist/browser/grid/create-grid-cell.js.map +1 -1
- package/dist/browser/gridlist/create-grid-list-item.js +3 -3
- package/dist/browser/gridlist/create-grid-list-item.js.map +1 -1
- package/dist/browser/interactions/create-hover.js +6 -3
- package/dist/browser/interactions/create-hover.js.map +1 -1
- package/dist/browser/interactions/create-press.js +5 -4
- package/dist/browser/interactions/create-press.js.map +1 -1
- package/dist/browser/interactions/utils.js +4 -3
- package/dist/browser/interactions/utils.js.map +1 -1
- package/dist/browser/landmark/create-landmark.js +2 -2
- package/dist/browser/landmark/create-landmark.js.map +1 -1
- package/dist/browser/overlays/aria-hide-outside.js +5 -3
- package/dist/browser/overlays/aria-hide-outside.js.map +1 -1
- package/dist/browser/overlays/calculate-position.js +3 -3
- package/dist/browser/overlays/calculate-position.js.map +1 -1
- package/dist/browser/overlays/create-modal.js +15 -18
- package/dist/browser/overlays/create-modal.js.map +1 -1
- package/dist/browser/overlays/create-prevent-scroll.js +3 -3
- package/dist/browser/overlays/create-prevent-scroll.js.map +1 -1
- package/dist/browser/overlays/overlay.js +7 -8
- package/dist/browser/overlays/overlay.js.map +1 -1
- package/dist/browser/select/create-select.js +1 -1
- package/dist/browser/select/create-select.js.map +1 -1
- package/dist/browser/select/hidden-select.js +61 -64
- package/dist/browser/select/hidden-select.js.map +1 -1
- package/dist/browser/selection/create-selectable-item.js +2 -2
- package/dist/browser/selection/create-selectable-item.js.map +1 -1
- package/dist/browser/selection/create-type-select.js +11 -3
- package/dist/browser/selection/create-type-select.js.map +1 -1
- package/dist/browser/selection/list-keyboard-delegate.js +1 -1
- package/dist/browser/selection/list-keyboard-delegate.js.map +1 -1
- package/dist/browser/tokenfield/create-token-field.js +3 -3
- package/dist/browser/tokenfield/create-token-field.js.map +1 -1
- package/dist/browser/tokenfield/create-token.js +2 -1
- package/dist/browser/tokenfield/create-token.js.map +1 -1
- package/dist/browser/toolbar/create-toolbar.js +2 -2
- package/dist/browser/toolbar/create-toolbar.js.map +1 -1
- package/dist/browser/utils/dom-helpers.d.ts +2 -15
- package/dist/browser/utils/dom-helpers.js +1 -28
- package/dist/browser/utils/dom-helpers.js.map +1 -1
- package/dist/browser/utils/dom-value.js +2 -1
- package/dist/browser/utils/dom-value.js.map +1 -1
- package/dist/browser/utils/get-scroll-parent.js +3 -2
- package/dist/browser/utils/get-scroll-parent.js.map +1 -1
- package/dist/browser/utils/get-scroll-parents.js +2 -1
- package/dist/browser/utils/get-scroll-parents.js.map +1 -1
- package/dist/browser/utils/is-element-visible.js +3 -1
- package/dist/browser/utils/is-element-visible.js.map +1 -1
- package/dist/browser/utils/is-focusable.js +2 -1
- package/dist/browser/utils/is-focusable.js.map +1 -1
- package/dist/browser/utils/shadowdom/dom-functions.d.ts +8 -0
- package/dist/browser/utils/shadowdom/dom-functions.js +26 -7
- package/dist/browser/utils/shadowdom/dom-functions.js.map +1 -1
- package/dist/browser/utils/shadowdom/shadow-tree-walker.js +1 -1
- package/dist/browser/utils/shadowdom/shadow-tree-walker.js.map +1 -1
- package/dist/browser/utils/type-helpers.d.ts +42 -0
- package/dist/browser/utils/type-helpers.js +55 -0
- package/dist/browser/utils/type-helpers.js.map +1 -0
- package/dist/server/actiongroup/create-action-group.js +2 -1
- package/dist/server/actiongroup/create-action-group.js.map +1 -1
- package/dist/server/combobox/create-combo-box.js +2 -2
- package/dist/server/combobox/create-combo-box.js.map +1 -1
- package/dist/server/dnd/drag-preview.js +9 -12
- package/dist/server/dnd/drag-preview.js.map +1 -1
- package/dist/server/focus/focus-scope.js +2 -2
- package/dist/server/focus/focus-scope.js.map +1 -1
- package/dist/server/focus/virtual-focus.js +20 -5
- package/dist/server/focus/virtual-focus.js.map +1 -1
- package/dist/server/grid/create-grid-cell.js +4 -4
- package/dist/server/grid/create-grid-cell.js.map +1 -1
- package/dist/server/gridlist/create-grid-list-item.js +3 -3
- package/dist/server/gridlist/create-grid-list-item.js.map +1 -1
- package/dist/server/interactions/create-hover.js +6 -3
- package/dist/server/interactions/create-hover.js.map +1 -1
- package/dist/server/interactions/create-press.js +5 -4
- package/dist/server/interactions/create-press.js.map +1 -1
- package/dist/server/interactions/utils.js +4 -3
- package/dist/server/interactions/utils.js.map +1 -1
- package/dist/server/landmark/create-landmark.js +2 -2
- package/dist/server/landmark/create-landmark.js.map +1 -1
- package/dist/server/overlays/aria-hide-outside.js +5 -3
- package/dist/server/overlays/aria-hide-outside.js.map +1 -1
- package/dist/server/overlays/calculate-position.js +3 -3
- package/dist/server/overlays/calculate-position.js.map +1 -1
- package/dist/server/overlays/create-modal.js +7 -27
- package/dist/server/overlays/create-modal.js.map +1 -1
- package/dist/server/overlays/create-prevent-scroll.js +3 -3
- package/dist/server/overlays/create-prevent-scroll.js.map +1 -1
- package/dist/server/overlays/overlay.js +8 -18
- package/dist/server/overlays/overlay.js.map +1 -1
- package/dist/server/select/create-select.js +1 -1
- package/dist/server/select/create-select.js.map +1 -1
- package/dist/server/select/hidden-select.js +85 -138
- package/dist/server/select/hidden-select.js.map +1 -1
- package/dist/server/selection/create-selectable-item.js +2 -2
- package/dist/server/selection/create-selectable-item.js.map +1 -1
- package/dist/server/selection/create-type-select.js +11 -3
- package/dist/server/selection/create-type-select.js.map +1 -1
- package/dist/server/selection/list-keyboard-delegate.js +1 -1
- package/dist/server/selection/list-keyboard-delegate.js.map +1 -1
- package/dist/server/tokenfield/create-token-field.js +3 -3
- package/dist/server/tokenfield/create-token-field.js.map +1 -1
- package/dist/server/tokenfield/create-token.js +2 -1
- package/dist/server/tokenfield/create-token.js.map +1 -1
- package/dist/server/toolbar/create-toolbar.js +2 -2
- package/dist/server/toolbar/create-toolbar.js.map +1 -1
- package/dist/server/utils/dom-helpers.js +1 -28
- package/dist/server/utils/dom-helpers.js.map +1 -1
- package/dist/server/utils/dom-value.js +2 -1
- package/dist/server/utils/dom-value.js.map +1 -1
- package/dist/server/utils/get-scroll-parent.js +3 -2
- package/dist/server/utils/get-scroll-parent.js.map +1 -1
- package/dist/server/utils/get-scroll-parents.js +2 -1
- package/dist/server/utils/get-scroll-parents.js.map +1 -1
- package/dist/server/utils/is-element-visible.js +3 -1
- package/dist/server/utils/is-element-visible.js.map +1 -1
- package/dist/server/utils/is-focusable.js +2 -1
- package/dist/server/utils/is-focusable.js.map +1 -1
- package/dist/server/utils/shadowdom/dom-functions.js +26 -7
- package/dist/server/utils/shadowdom/dom-functions.js.map +1 -1
- package/dist/server/utils/shadowdom/shadow-tree-walker.js +1 -1
- package/dist/server/utils/shadowdom/shadow-tree-walker.js.map +1 -1
- package/dist/server/utils/type-helpers.js +55 -0
- package/dist/server/utils/type-helpers.js.map +1 -0
- package/dist/server/virtualizer/scroll-view.js +3 -1
- package/dist/server/virtualizer/scroll-view.js.map +1 -1
- package/package.json +16 -10
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-token-field.js","names":[],"sources":["../../../src/tokenfield/create-token-field.ts"],"sourcesContent":["/*\n * Copyright 2026 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing\n */\n/*\n * Derived from Adobe React Spectrum: packages/react-aria/src/tokenfield/useTokenField.ts.\n * Modified for Solid Aria: adapted hooks, reactive getters, DOM types, and imports for Solid 2.\n * Licensed under Apache-2.0. See LICENSES/Apache-2.0.txt and NOTICE.txt at the repository root.\n */\n\nimport type {\n TokenFieldProps,\n TokenFieldState,\n} from \"@solid2-aria/stately/tokenfield/create-token-field-state\";\nimport { TokenFieldValue } from \"@solid2-aria/stately/tokenfield/token-field-value\";\nimport type {\n Position,\n SelectedRange,\n TokenFieldSegment,\n} from \"@solid2-aria/stately/tokenfield/token-field-value\";\nimport type {\n AriaLabelingProps,\n FocusableProps,\n} from \"@solid2-aria/types-shared\";\nimport type { DOMAttributes } from \"@solid2-aria/types-shared-web\";\nimport { merge, createMemo, createEffect, onSettled } from \"solid-js\";\nimport type { Accessor } from \"solid-js\";\n\nimport { createLocale } from \"../i18n/i18n-provider\";\nimport {\n getInteractionModality,\n setInteractionModality,\n} from \"../interactions/create-focus-visible\";\nimport { createFocusable } from \"../interactions/create-focusable\";\nimport { createKeyboard } from \"../interactions/create-keyboard\";\nimport type { KeyboardShortcutBindings } from \"../interactions/create-keyboard-shortcut-handler\";\nimport { createField } from \"../label/create-field\";\nimport { announce } from \"../live-announcer/live-announcer\";\nimport type {\n ClipboardEventHandler,\n HTMLAttributes,\n KeyboardEvent,\n} from \"../types\";\nimport { ariaValue } from \"../utils/aria-value\";\nimport { createEvent } from \"../utils/create-event\";\nimport { getOwnerDocument } from \"../utils/dom-helpers\";\nimport { requireHTMLElement } from \"../utils/dom-value\";\nimport { getScrollParents } from \"../utils/get-scroll-parents\";\nimport { isPresent } from \"../utils/is-present\";\nimport { mergeProps } from \"../utils/merge-props\";\nimport { isMac } from \"../utils/platform\";\nimport { requireValue } from \"../utils/require-value\";\nimport { scrollRectIntoView } from \"../utils/scroll-into-view\";\nimport {\n getActiveElement,\n nodeContains,\n} from \"../utils/shadowdom/dom-functions\";\nimport { isTruthy } from \"../utils/truthy\";\n\nexport type AriaTokenFieldProps<T extends TokenFieldValue = TokenFieldValue> =\n TokenFieldProps<T> &\n Omit<FocusableProps, \"onKeyDown\" | \"onKeyUp\"> &\n AriaLabelingProps & {\n /**\n * The accessibility role of the token field.\n *\n * @default 'textbox'\n */\n role?: \"textbox\" | \"searchbox\" | \"combobox\";\n /** Whether the token field allows newlines. */\n allowsNewlines?: boolean;\n /** Whether the token field is read only. */\n isReadOnly?: boolean;\n /** Whether the token field is disabled. */\n isDisabled?: boolean;\n /** A function that is called when the user presses the Enter key. */\n onSubmit?: () => void;\n /** Handler that is called when a key is pressed. */\n onKeyDown?: (e: KeyboardEvent<HTMLDivElement>) => void;\n /** Handler that is called when a key is released. */\n onKeyUp?: (e: KeyboardEvent<HTMLDivElement>) => void;\n /**\n * Handler that is called when the user copies text. See\n * [MDN](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/oncopy).\n */\n onCopy?: ClipboardEventHandler<HTMLDivElement>;\n /**\n * Handler that is called when the user cuts text. See\n * [MDN](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/oncut).\n */\n onCut?: ClipboardEventHandler<HTMLDivElement>;\n /**\n * Handler that is called when the user pastes text. See\n * [MDN](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/onpaste).\n */\n onPaste?: ClipboardEventHandler<HTMLDivElement>;\n };\n\nexport interface TokenFieldAria {\n /** Props for the token field's input element. */\n tokenFieldProps: HTMLAttributes<HTMLDivElement>;\n /** Props for the text field's visible label element, if any. */\n labelProps: DOMAttributes;\n /** Props for the text field's description element, if any. */\n descriptionProps: DOMAttributes;\n}\n\nconst CLIPBOARD_MIME_TYPE = \"application/vnd.react-aria.tokens+json\";\n\n/**\n * Provides the behavior and accessibility implementation for a token field.\n * A token field allows users to enter text with inline tokens.\n *\n * @param props - Props for the token field.\n * @param state - State for the token field, as returned by `useTokenFieldState`.\n */\nexport function createTokenField<T extends TokenFieldValue = TokenFieldValue>(\n props: AriaTokenFieldProps<T>,\n state: TokenFieldState,\n ref: Accessor<HTMLDivElement | null>\n): TokenFieldAria {\n const _result1 = props;\n const _result2 = state;\n const _result3 = createLocale();\n\n const graphemeSegmenter = createMemo(\n () => new Intl.Segmenter(_result3.locale, { granularity: \"grapheme\" })\n );\n\n const wordSegmenter = createMemo(\n () => new Intl.Segmenter(_result3.locale, { granularity: \"word\" })\n );\n\n let dropPosition: Position | null = null;\n let transferredData: TokenFieldSegment[] | null = null;\n let nextValue: TokenFieldValue | null = null;\n\n const apply = (fn: (value: TokenFieldValue) => TokenFieldValue) => {\n state.setValue((value) => {\n const newValue = fn(value);\n nextValue = newValue;\n\n return newValue;\n });\n };\n\n // Composition events are not cancelable. Pause controlled DOM updates while the IME owns it,\n // track the browser's mutations, then restore the controlled value when composition ends.\n // Mutating the DOM in any way during composition breaks the IME, causing composition to end unexpectedly.\n // During composition, we still emit updates via onChange to ensure that things like autocomplete work,\n // but we don't actually re-render to the DOM unless the value changes from what we expect (e.g. inserting a completion).\n const mutationTracker = createMutationTracker(ref);\n\n const startComposition = () => {\n mutationTracker.start();\n state.setComposing(true);\n };\n\n const stopComposition = () => {\n mutationTracker.stop();\n state.setComposing(false);\n };\n\n createEvent(ref, \"compositionstart\", () => {\n startComposition();\n const range = window.getSelection()?.getRangeAt(0);\n\n if (range) {\n const [start, end] = rangeToPositions(\n requireValue(ref(), \"Expected ref.current\"),\n range\n );\n\n // Normalize the range to ensure it is not inside a token, otherwise the browser\n // will attempt to insert the composed text into the token instead of replacing it.\n const r = createDOMRange(\n requireValue(ref(), \"Expected ref.current\"),\n start,\n end\n );\n\n if (\n r.startContainer !== range.startContainer ||\n r.startOffset !== range.startOffset\n ) {\n range.setStart(r.startContainer, r.startOffset);\n }\n\n if (\n r.endContainer !== range.endContainer ||\n r.endOffset !== range.endOffset\n ) {\n range.setEnd(r.endContainer, r.endOffset);\n }\n }\n });\n createEvent(ref, \"compositionend\", stopComposition);\n // If a prop update occurs during composition that doesn't match the expected value,\n // end composition and re-render the controlled value.\n createEffect(\n () => ({ isComposing: state.isComposing, value: _result2.value }),\n ({ value, isComposing }) => {\n if (isComposing && value !== nextValue) {\n stopComposition();\n }\n\n nextValue = value;\n },\n { ssrSource: \"client\" }\n );\n let selectedRange: SelectedRange | null = null;\n createEffect(\n () => ({\n element: ref(),\n isComposing: state.isComposing,\n observedSelectedRange: _result2.value.selectedRange,\n value: _result2.value,\n }),\n ({ observedSelectedRange, value, isComposing, element }) => {\n const refElement = element;\n\n if (\n refElement &&\n !isComposing &&\n observedSelectedRange !== selectedRange\n ) {\n // Only move the caret when the field is already focused.\n if (refElement === getActiveElement(getOwnerDocument(refElement))) {\n setTokenFieldSelection(refElement, observedSelectedRange);\n announceToken(value);\n // We call preventDefault in the beforeinput handler below, which also prevents the\n // browser's default behavior of scrolling the caret into view. Do it ourselves instead.\n scrollCaretIntoView(refElement);\n }\n\n selectedRange = observedSelectedRange;\n }\n },\n { ssrSource: \"client\" }\n );\n // Handle text editing commands and prevent browser default behavior.\n createEvent(ref, \"beforeinput\", (e) => {\n // Android sometimes doesn't fire a compositionend event before a regular input event.\n if (state.isComposing && !e.isComposing) {\n stopComposition();\n }\n\n let [range] = e.getTargetRanges();\n\n if (!range) {\n const selection = window.getSelection();\n\n if (!selection || selection.rangeCount === 0) {\n return;\n }\n\n range = selection.getRangeAt(0);\n }\n\n let [start, end] = rangeToPositions(\n requireValue(ref(), \"Expected ref.current\"),\n range\n );\n\n // insertFromComposition is no longer in the spec but is still fired by Safari.\n // https://www.w3.org/TR/input-events-2/#interface-InputEvent-Attributes\n switch (e.inputType) {\n case \"insertText\":\n case \"insertReplacementText\":\n case \"insertCompositionText\":\n case \"insertFromComposition\":\n case \"insertFromPaste\":\n case \"insertFromYank\":\n case \"insertFromDrop\": {\n const data = getInsertionData(e, transferredData);\n transferredData = null;\n\n if (e.inputType === \"insertFromDrop\" && dropPosition) {\n end = dropPosition;\n start = end;\n dropPosition = null;\n }\n\n if (!(_result1.allowsNewlines ?? false)) {\n for (const segment of data) {\n segment.text = segment.text.replaceAll(/[\\r\\n]+/gu, \" \");\n }\n }\n\n apply((tokens) =>\n tokens.replaceRangeWithSegments(\n start,\n end,\n data,\n // Don't coalesce paste/drop events with other edits.\n e.inputType === \"insertText\" ||\n e.inputType === \"insertCompositionText\" ||\n e.inputType === \"insertFromComposition\"\n )\n );\n break;\n }\n\n case \"insertParagraph\": {\n if (props.onSubmit) {\n props.onSubmit();\n break;\n }\n\n if (_result1.allowsNewlines ?? false) {\n apply((tokens) => tokens.replaceRange(start, end, \"\\n\"));\n }\n\n break;\n }\n\n case \"insertLineBreak\": {\n if (_result1.allowsNewlines ?? false) {\n apply((tokens) => tokens.replaceRange(start, end, \"\\n\"));\n }\n\n break;\n }\n\n case \"deleteContentBackward\":\n case \"deleteContentForward\":\n case \"deleteWordBackward\":\n case \"deleteWordForward\":\n case \"deleteHardLineForward\":\n case \"deleteHardLineBackward\":\n case \"deleteSoftLineForward\":\n case \"deleteSoftLineBackward\":\n case \"deleteContent\":\n case \"deleteByCut\":\n case \"deleteCompositionText\": {\n if (!range.collapsed && !isSamePosition(start, end)) {\n apply((tokens) => tokens.replaceRange(start, end, \"\"));\n break;\n }\n\n switch (e.inputType) {\n case \"deleteContentBackward\": {\n apply((tokens) =>\n tokens.delete(\n start,\n graphemeSegmenter(),\n TokenFieldValue.Direction.Backward\n )\n );\n break;\n }\n\n case \"deleteContentForward\": {\n apply((tokens) =>\n tokens.delete(\n start,\n graphemeSegmenter(),\n TokenFieldValue.Direction.Forward\n )\n );\n break;\n }\n\n case \"deleteWordBackward\": {\n apply((tokens) =>\n tokens.delete(\n start,\n wordSegmenter(),\n TokenFieldValue.Direction.Backward\n )\n );\n break;\n }\n\n case \"deleteWordForward\": {\n apply((tokens) =>\n tokens.delete(\n start,\n wordSegmenter(),\n TokenFieldValue.Direction.Forward\n )\n );\n break;\n }\n\n case \"deleteHardLineForward\":\n case \"deleteSoftLineForward\": {\n // Follow-up: this usually deletes to the nearest *visual* line break rather than a hard break\n apply((tokens) =>\n tokens.deleteLine(start, TokenFieldValue.Direction.Forward)\n );\n break;\n }\n\n case \"deleteHardLineBackward\":\n case \"deleteSoftLineBackward\": {\n apply((tokens) =>\n tokens.deleteLine(start, TokenFieldValue.Direction.Backward)\n );\n break;\n }\n\n case \"deleteByCut\": {\n throw new Error('Not implemented yet: \"deleteByCut\" case');\n }\n\n case \"deleteCompositionText\": {\n throw new Error(\n 'Not implemented yet: \"deleteCompositionText\" case'\n );\n }\n\n case \"deleteContent\": {\n throw new Error('Not implemented yet: \"deleteContent\" case');\n }\n\n default: {\n break;\n }\n }\n\n break;\n }\n\n case \"deleteByDrag\": {\n apply((tokens) => {\n const endOffset =\n start.index === end.index\n ? end.offset\n : (tokens.segments[start.index]?.text.length ?? 0);\n\n const change = tokens.replaceRange(start, end, \"\");\n\n if (\n dropPosition &&\n dropPosition.index === start.index &&\n dropPosition.offset >= start.offset\n ) {\n dropPosition.offset -= endOffset - start.offset;\n }\n\n return change;\n });\n break;\n }\n\n default: {\n break;\n }\n }\n\n e.preventDefault();\n });\n\n const writeClipboardData = (e: ClipboardEvent | DragEvent) => {\n if (\"clipboardData\" in e) {\n e.preventDefault();\n }\n\n const selection = getSelection(requireValue(ref(), \"Expected ref.current\"));\n\n if (!selection) {\n return;\n }\n\n const [start, end] = selection;\n const slice = _result2.value.slice(start, end);\n\n const dataTransfer =\n \"clipboardData\" in e ? e.clipboardData : e.dataTransfer;\n\n dataTransfer?.setData(CLIPBOARD_MIME_TYPE, JSON.stringify(slice.segments));\n dataTransfer?.setData(\"text/plain\", slice.toString());\n\n if (e.type === \"cut\") {\n apply((tokens) => tokens.replaceRange(start, end, \"\", false));\n }\n };\n\n createEvent(ref, \"copy\", writeClipboardData);\n createEvent(ref, \"cut\", writeClipboardData);\n createEvent(ref, \"dragstart\", writeClipboardData);\n createEvent(ref, \"paste\", (e) => {\n // Safari doesn't pass the custom clipboard data type to beforeinput dataTransfer so we handle it here.\n if (\n e.clipboardData &&\n e.clipboardData.types.includes(CLIPBOARD_MIME_TYPE)\n ) {\n transferredData = parseSegments(\n e.clipboardData.getData(CLIPBOARD_MIME_TYPE)\n );\n }\n });\n // Store the cursor position on drop so we know where to insert when the insertFromDrop event occurs.\n createEvent(ref, \"drop\", (e) => {\n if (typeof document.caretPositionFromPoint === \"function\") {\n const pos = document.caretPositionFromPoint(e.clientX, e.clientY);\n\n if (pos) {\n dropPosition = getPosition(\n requireValue(ref(), \"Expected ref.current\"),\n pos.offsetNode,\n pos.offset\n );\n }\n } else {\n // oxlint-disable-next-line typescript/no-deprecated, typescript/unbound-method -- Retain the Safari caret fallback and call it with its document receiver.\n const legacyCaretRange = document.caretRangeFromPoint;\n\n const range =\n typeof legacyCaretRange === \"function\"\n ? legacyCaretRange.call(document, e.clientX, e.clientY)\n : null;\n\n if (range) {\n dropPosition = getPosition(\n requireValue(ref(), \"Expected ref.current\"),\n range.startContainer,\n range.startOffset\n );\n }\n }\n\n if (e.dataTransfer && e.dataTransfer.types.includes(CLIPBOARD_MIME_TYPE)) {\n transferredData = parseSegments(\n e.dataTransfer.getData(CLIPBOARD_MIME_TYPE)\n );\n }\n });\n createSelectionChange(ref, () => {\n if (state.isComposing) {\n return;\n }\n\n _result2.value.endCoalescing();\n\n // When the cursor moves next to a token, announce it.\n // Otherwise the screen reader will only announce the first/last character.\n const range = getSelectedRange(requireValue(ref(), \"Expected ref.current\"));\n\n if (!range) {\n return;\n }\n\n announceToken(_result2.value, range);\n // Update the selected range in the value.\n state.setValue((value) => value.withSelectedRange(range));\n });\n // Clear selection on blur.\n createEvent(ref, \"blur\", (e) => {\n const refElement = ref();\n\n if (!e.isTrusted) {\n return;\n }\n\n const selection = window.getSelection();\n\n if (\n refElement &&\n selection &&\n selection.containsNode(refElement, true) &&\n !selection.isCollapsed\n ) {\n selection.removeAllRanges();\n state.setValue((value) =>\n value.withSelectedRange(\n new TokenFieldValue.SelectedRange(value.caretPosition)\n )\n );\n }\n });\n // Override the default triple click behavior to ensure that tokens get selected.\n // Some browsers only select the text between tokens instead of the entire line.\n createEvent(ref, \"mousedown\", (e) => {\n if (e.detail === 3) {\n const selection = getSelection(\n requireValue(ref(), \"Expected ref.current\")\n );\n\n if (!selection) {\n return;\n }\n\n const start = _result2.value.findLineBoundary(\n selection[0],\n TokenFieldValue.Direction.Backward\n );\n\n const end = _result2.value.findLineBoundary(\n selection[1],\n TokenFieldValue.Direction.Forward\n );\n\n if (start && end) {\n e.preventDefault();\n setTokenFieldSelection(\n requireValue(ref(), \"Expected ref.current\"),\n new TokenFieldValue.SelectedRange(start, end),\n true\n );\n }\n }\n });\n\n const moveSelection = (\n direction: \"left\" | \"right\",\n granularity: \"character\" | \"word\",\n extend = false\n ) => {\n const selection = window.getSelection();\n\n if (\n !selection ||\n selection.rangeCount === 0 ||\n !selection.focusNode ||\n !selection.anchorNode\n ) {\n return false;\n }\n\n // Pressing an arrow with a non-empty selection collapses it to the corresponding edge.\n // The browser handles this natively.\n if (!extend && !selection.isCollapsed) {\n return false;\n }\n\n // Move the caret using the browser's native caret movement (Selection.modify) so that\n // bidirectional text is handled correctly. Repeat until the position actually changes\n // to account for the zero width spaces around tokens.\n const pos = getPosition(\n requireValue(ref(), \"Expected ref.current\"),\n selection.focusNode,\n selection.focusOffset\n );\n\n while (true) {\n const focusNode: globalThis.Node | null = selection.focusNode;\n const focusOffset: number = selection.focusOffset;\n selection.modify(extend ? \"extend\" : \"move\", direction, granularity);\n\n if (\n selection.focusNode === focusNode &&\n selection.focusOffset === focusOffset\n ) {\n return false;\n }\n\n if (!isTruthy(selection.focusNode)) {\n return false;\n }\n\n const newPos = getPosition(\n requireValue(ref(), \"Expected ref.current\"),\n selection.focusNode,\n selection.focusOffset\n );\n\n if (!isSamePosition(pos, newPos)) {\n return true;\n }\n }\n };\n\n // macOS supports additional keyboard shortcuts for text editing.\n // We need to handle these manually so they behave consistently with tokens.\n // https://support.apple.com/en-us/102650#text\n\n const mod = isMac() ? \"Meta\" : \"Control\";\n const wordModKey = isMac() ? \"Alt\" : \"Control\";\n\n const shortcuts: KeyboardShortcutBindings = {\n [`${mod}+z`]: (): undefined | false => {\n // If composing, the browser handles undo natively.\n if (state.isComposing) {\n return false;\n }\n\n apply((currentState) => currentState.undo());\n\n return undefined;\n },\n [isMac() ? \"Shift+Meta+z\" : \"Control+y\"]: (): undefined | false => {\n if (state.isComposing) {\n return false;\n }\n\n apply((currentState2) => currentState2.redo());\n\n return undefined;\n },\n ArrowLeft: () => moveSelection(\"left\", \"character\"),\n [`${wordModKey}+ArrowLeft`]: () => moveSelection(\"left\", \"word\"),\n ArrowRight: () => moveSelection(\"right\", \"character\"),\n [`Shift+${wordModKey}+ArrowLeft`]: () =>\n moveSelection(\"left\", \"word\", true),\n End: () => {\n const selection = getSelection(\n requireValue(ref(), \"Expected ref.current\")\n );\n\n if (!selection) {\n return false;\n }\n\n const boundary = _result2.value.findLineBoundary(\n selection[1],\n TokenFieldValue.Direction.Forward\n );\n\n if (boundary) {\n setCursor(requireValue(ref(), \"Expected ref.current\"), boundary, true);\n\n return true;\n }\n\n return false;\n },\n [`${wordModKey}+ArrowRight`]: () => moveSelection(\"right\", \"word\"),\n Home: () => {\n // Browsers do not behave consistently when there are tokens.\n const selection = getSelection(\n requireValue(ref(), \"Expected ref.current\")\n );\n\n if (!selection) {\n return false;\n }\n\n const boundary = _result2.value.findLineBoundary(\n selection[0],\n TokenFieldValue.Direction.Backward\n );\n\n if (boundary) {\n setCursor(requireValue(ref(), \"Expected ref.current\"), boundary, true);\n\n return true;\n }\n\n return false;\n },\n [`Shift+${wordModKey}+ArrowRight`]: () =>\n moveSelection(\"right\", \"word\", true),\n \"Shift+ArrowLeft\": () => moveSelection(\"left\", \"character\", true),\n \"Shift+ArrowRight\": () => moveSelection(\"right\", \"character\", true),\n };\n\n const macShortcuts: KeyboardShortcutBindings = isMac()\n ? {\n \"Control+a\": (event) => shortcuts.Home?.(event),\n \"Control+b\": (event) => shortcuts.ArrowLeft?.(event),\n \"Control+e\": (event) => shortcuts.End?.(event),\n \"Control+f\": (event) => shortcuts.ArrowRight?.(event),\n }\n : {};\n\n Object.assign(shortcuts, macShortcuts);\n\n // Follow-up: user provided onKeyDown currently relies on user provided preventDefault to stop submit\n // maybe can have them specify a format like shortcuts and merge into above?\n const _result4 = createKeyboard({\n get allowRepeats(): true {\n return true;\n },\n get isDisabled() {\n return (_result1.isDisabled ?? false) || (_result1.isReadOnly ?? false);\n },\n get onKeyDown() {\n return props.onKeyDown;\n },\n get onKeyUp() {\n return props.onKeyUp;\n },\n get shortcuts() {\n return shortcuts;\n },\n });\n\n const _result5 = createFocusable(props, ref);\n\n const _result6 = createField(\n merge(props, {\n get labelElementType(): \"span\" {\n return \"span\";\n },\n })\n );\n\n return {\n get descriptionProps() {\n return _result6.descriptionProps;\n },\n get labelProps() {\n return merge(_result6.labelProps, {\n onClick: () => {\n if (!isTruthy(props.isDisabled)) {\n ref()?.focus();\n // Show the focus ring so the user knows where focus went\n setInteractionModality(\"keyboard\");\n }\n },\n });\n },\n get tokenFieldProps() {\n return mergeProps(\n _result5.focusableProps,\n _result4.keyboardProps,\n _result6.fieldProps,\n {\n \"aria-details\": ariaValue(_result1[\"aria-details\"]),\n \"aria-disabled\": ariaValue(_result1.isDisabled ?? false),\n \"aria-multiline\": ariaValue(_result1.allowsNewlines ?? false),\n \"aria-readonly\": ariaValue(_result1.isReadOnly ?? false),\n contenteditable:\n !(_result1.isDisabled ?? false) && !(_result1.isReadOnly ?? false),\n onCopy: props.onCopy,\n onCut: props.onCut,\n onPaste: props.onPaste,\n role: _result1.role ?? \"textbox\",\n style: { whiteSpace: \"pre-wrap\" },\n suppressContentEditableWarning: true,\n }\n );\n },\n };\n}\n\nfunction indexOfNode(node: Node) {\n let index = 0;\n let n: Node | null = node;\n\n while ((n = n.previousSibling)) {\n index += 1;\n }\n\n return index;\n}\n\nexport function getSelection(container: Element): [Position, Position] | null {\n const selection = window.getSelection();\n\n if (!selection || selection.rangeCount === 0) {\n return null;\n }\n\n const range = selection.getRangeAt(0);\n\n return rangeToPositions(container, range);\n}\n\nexport function getSelectedRange(container: Element) {\n const selection = window.getSelection();\n\n if (\n !selection ||\n !selection.anchorNode ||\n !selection.focusNode ||\n !nodeContains(container, selection.anchorNode) ||\n !nodeContains(container, selection.focusNode)\n ) {\n return null;\n }\n\n const anchor = getPosition(\n container,\n selection.anchorNode,\n selection.anchorOffset,\n false\n );\n\n const current = getPosition(\n container,\n selection.focusNode,\n selection.focusOffset,\n !selection.isCollapsed\n );\n\n return new TokenFieldValue.SelectedRange(anchor, current);\n}\n\nfunction rangeToPositions(\n container: Element,\n range: Range | StaticRange\n): [Position, Position] {\n const start = getPosition(\n container,\n range.startContainer,\n range.startOffset,\n false\n );\n\n const end = getPosition(\n container,\n range.endContainer,\n range.endOffset,\n !range.collapsed\n );\n\n return [start, end];\n}\n\nfunction getPosition(\n container: Element,\n node: Node,\n offset: number,\n isRangeEnd = false\n): Position {\n let currentNode = node;\n const currentOffset = offset;\n\n if (currentNode === container) {\n return { index: currentOffset, offset: 0 };\n }\n\n const originalNode = currentNode;\n\n while (currentNode.parentNode !== container) {\n currentNode = requireValue(\n currentNode.parentNode,\n \"Expected node.parentNode\"\n );\n }\n\n const index = indexOfNode(currentNode);\n\n if (currentNode.nodeType === Node.ELEMENT_NODE) {\n return getTokenPosition(\n currentNode,\n originalNode,\n currentOffset,\n isRangeEnd,\n index\n );\n }\n\n return { index, offset: currentOffset };\n}\n\nconst programmaticSelectionChanges = new WeakSet<Element>();\n\nfunction setCursor(root: Element, pos: Position, fireEvent = false) {\n setTokenFieldSelection(\n root,\n new TokenFieldValue.SelectedRange(pos),\n fireEvent\n );\n}\n\nexport function setTokenFieldSelection(\n root: Element,\n selectedRange: SelectedRange,\n fireEvent = false\n) {\n const selection = window.getSelection();\n\n if (selection) {\n // Use setBaseAndExtent to preserve the selection direction. A plain Range +\n // addRange always produces a forward selection and collapses when the\n // anchor comes after the current position (backward selections).\n const [anchorNode, anchorOffset] = getDOMPosition(\n root,\n selectedRange.anchor\n );\n\n const [focusNode, focusOffset] = getDOMPosition(\n root,\n selectedRange.current\n );\n\n // Only set selection if it has changed, because this can clobber the browser's selection direction.\n if (\n selection.anchorNode !== anchorNode ||\n selection.anchorOffset !== anchorOffset ||\n selection.focusNode !== focusNode ||\n selection.focusOffset !== focusOffset\n ) {\n // Only flag the change when the selection actually moves. Otherwise no selectionchange\n // event fires to consume the flag, and the next user selection change would be ignored.\n if (fireEvent) {\n programmaticSelectionChanges.delete(root);\n } else {\n programmaticSelectionChanges.add(root);\n }\n\n selection.setBaseAndExtent(\n anchorNode,\n anchorOffset,\n focusNode,\n focusOffset\n );\n }\n }\n}\n\n// Calling preventDefault in the beforeinput handler stops the browser from performing its\n// default edit action, which also suppresses its normal behavior of scrolling the caret into\n// view. Recreate that behavior by measuring the caret's position with a Range and\n// scrolling each scrollable ancestor of the field so it is visible.\nfunction scrollCaretIntoView(root: HTMLElement): void {\n const selection = window.getSelection();\n\n if (\n getInteractionModality() !== \"keyboard\" ||\n !selection ||\n selection.rangeCount === 0 ||\n !nodeContains(root, selection.focusNode)\n ) {\n return;\n }\n\n let range = selection.getRangeAt(0);\n\n if (range.collapsed && range.endContainer === root) {\n // Root-level positions around tokens have no rect. Measure the adjacent\n // zero width space without moving the actual selection into the token.\n range = tokenFieldPositionToDOMRange(root, {\n index: range.endOffset,\n offset: 0,\n });\n }\n\n let rect = getCaretRect(root, range);\n\n for (const element of getScrollParents(root, true)) {\n // scrollRectIntoView only scrolls a single scroll parent based on `rect`, which is a\n // snapshot of the caret's position before any scrolling occurs. Scrolling an inner ancestor\n // moves the caret within the viewport, so translate `rect` by however much we just scrolled\n // before moving on to the next (outer) ancestor.\n const scrollParent = requireHTMLElement(element);\n const beforeTop = scrollParent.scrollTop;\n const beforeLeft = scrollParent.scrollLeft;\n scrollRectIntoView(scrollParent, root, rect, {\n block: \"nearest\",\n inline: \"nearest\",\n });\n const dy = scrollParent.scrollTop - beforeTop;\n const dx = scrollParent.scrollLeft - beforeLeft;\n\n if (dy !== 0 || dx !== 0) {\n rect = new DOMRect(rect.x - dx, rect.y - dy, rect.width, rect.height);\n }\n }\n}\n\nexport function tokenFieldPositionToDOMRange(\n root: Element,\n pos: Position\n): Range {\n // Unlike createDOMRange (used for caret/selection placement), this range is only\n // measured via getBoundingClientRect to position things like an autocomplete popover.\n // Place the endpoints inside the token's zero width space wrappers so the range has a\n // valid rect at the token, rather than a collapsed root-level position.\n const range = document.createRange();\n const [startContainer, startOffset] = getDOMRectPosition(root, pos);\n range.setStart(startContainer, startOffset);\n range.setEnd(startContainer, startOffset);\n\n return range;\n}\n\nfunction getDOMRectPosition(root: Element, pos: Position): [Node, number] {\n const child = root.childNodes[pos.index];\n\n if (\n pos.index >= root.childNodes.length &&\n root.lastChild?.lastChild?.nodeType === Node.TEXT_NODE\n ) {\n // A position after the last token belongs to its trailing zero width space.\n const text = root.lastChild.lastChild;\n\n return [\n text,\n requireValue(text.textContent, \"Expected text.textContent\").length,\n ];\n }\n\n if (child && child.nodeType === Node.ELEMENT_NODE) {\n // Place the position inside the zero width space wrappers around the token.\n if (pos.offset > 0) {\n return [requireValue(child.lastChild, \"Expected child.lastChild\"), 1];\n }\n\n return [requireValue(child.firstChild, \"Expected child.firstChild\"), 0];\n }\n\n return getDOMPosition(root, pos);\n}\n\nfunction createDOMRange(root: Element, start: Position, end: Position): Range {\n const range = document.createRange();\n const [startContainer, startOffset] = getDOMPosition(root, start);\n const [endContainer, endOffset] = getDOMPosition(root, end);\n range.setStart(startContainer, startOffset);\n range.setEnd(endContainer, endOffset);\n\n return range;\n}\n\nfunction getDOMPosition(root: Element, pos: Position): [Node, number] {\n const index = Math.max(0, Math.min(root.childNodes.length, pos.index));\n const child = root.childNodes[index];\n\n if (!child) {\n return [root, index];\n } else if (child.nodeType === Node.ELEMENT_NODE) {\n // Place the cursor outside the token wrapper element.\n // This is necessary for composition events.\n if (pos.offset > 0) {\n return [root, index + 1];\n }\n\n return [root, index];\n }\n\n const offset = Math.max(\n 0,\n Math.min(child.textContent?.length ?? 0, pos.offset)\n );\n\n return [child, offset];\n}\n\nfunction isSamePosition(a: Position, b: Position): boolean {\n return a.index === b.index && a.offset === b.offset;\n}\n\n// Parse and validate segments from clipboard/drag data. Returns null if the data is not valid\n// JSON or does not match the expected shape, so malformed or untrusted data is ignored rather\n// than throwing or being inserted into the field.\nfunction parseSegments(json: string): TokenFieldSegment[] | null {\n try {\n const data: unknown = JSON.parse(json);\n\n if (Array.isArray(data) && data.length > 0 && data.every(isValidSegment)) {\n return data;\n }\n } catch {\n // Ignore invalid clipboard data.\n }\n\n return null;\n}\n\nfunction isValidSegment(segment: unknown): segment is TokenFieldSegment {\n return (\n typeof segment === \"object\" &&\n segment !== null &&\n segment !== undefined &&\n \"type\" in segment &&\n (segment.type === \"text\" || segment.type === \"token\") &&\n \"text\" in segment &&\n typeof segment.text === \"string\"\n );\n}\n\nfunction createSelectionChange(\n ref: Accessor<Element | null>,\n handler: () => void\n) {\n createEvent(\n () => (typeof document === \"undefined\" ? null : document),\n \"selectionchange\",\n () => {\n const refElement = ref();\n\n if (refElement && programmaticSelectionChanges.has(refElement)) {\n programmaticSelectionChanges.delete(refElement);\n\n return;\n }\n\n const selection = window.getSelection();\n\n if (!selection || selection.rangeCount === 0 || !refElement) {\n return;\n }\n\n const range = selection.getRangeAt(0);\n\n if (range.intersectsNode(refElement)) {\n handler();\n }\n }\n );\n}\n\nfunction createMutationTracker(ref: Accessor<Element | null>) {\n let mutationTracker: (() => void) | null = null;\n // Disconnect the mutation observer if the field unmounts mid-composition.\n onSettled(() => () => {\n mutationTracker?.();\n mutationTracker = null;\n });\n\n const _memo0 = {\n start() {\n // Android sometimes fires two compositionstart events in a row, without a compositionend.\n // In that case, reuse the existing tracker.\n mutationTracker ??= trackMutations(\n requireValue(ref(), \"Expected ref.current\")\n );\n },\n stop() {\n mutationTracker?.();\n mutationTracker = null;\n },\n };\n\n return _memo0;\n}\n\n// Tracks mutations to the DOM until the returned function is called,\n// at which point the mutations are reverted.\nfunction trackMutations(element: Element) {\n const mutations: MutationRecord[] = [];\n\n const observer = new MutationObserver((records) => {\n mutations.push(...records);\n });\n\n observer.observe(element, {\n characterData: true,\n characterDataOldValue: true,\n childList: true,\n subtree: true,\n });\n\n return () => {\n mutations.push(...observer.takeRecords());\n observer.disconnect();\n\n for (const record of mutations.toReversed()) {\n switch (record.type) {\n case \"childList\": {\n for (const node of record.removedNodes) {\n record.target.insertBefore(node, record.nextSibling);\n }\n\n for (const node of record.addedNodes) {\n // oxlint-disable-next-line unicorn/prefer-dom-node-remove -- MutationRecord exposes Node, which does not declare ChildNode.remove.\n record.target.removeChild(node);\n }\n\n break;\n }\n\n case \"characterData\": {\n record.target.nodeValue = record.oldValue;\n break;\n }\n\n case \"attributes\": {\n throw new Error('Not implemented yet: \"attributes\" case');\n }\n\n default: {\n break;\n }\n }\n }\n };\n}\n\nfunction announceToken(value: TokenFieldValue, range = value.selectedRange) {\n if (range.isCollapsed) {\n // Announce adjacent tokens.\n let segment = value.segments[range.current.index];\n\n if (segment && segment.type !== \"token\") {\n if (range.current.offset === 0) {\n segment = value.segments[range.current.index - 1];\n } else if (range.current.offset === segment.text.length) {\n segment = value.segments[range.current.index + 1];\n }\n }\n\n if (segment?.type === \"token\") {\n announce(segment.text, \"assertive\");\n }\n } else {\n // Announce token if it is the only thing selected.\n const selected = value.slice(range.start, range.end).segments;\n const [only] = selected;\n\n if (selected.length === 1 && only?.type === \"token\") {\n announce(only.text, \"assertive\");\n }\n }\n}\n\nfunction getTokenPosition(\n wrapper: Node,\n originalNode: Node,\n offset: number,\n isRangeEnd: boolean,\n wrapperIndex: number\n): Position {\n let index = wrapperIndex;\n let currentOffset = offset;\n\n const [, tokenNode] = wrapper.childNodes;\n\n if (!tokenNode) {\n return { index, offset: 0 };\n }\n\n let atEnd: boolean;\n let endOffset = 0;\n\n if (originalNode === tokenNode) {\n // Cursor is inside the token.\n atEnd = isRangeEnd || currentOffset > 0;\n } else if (originalNode === wrapper) {\n // Cursor is inside the wrapper element.\n atEnd = currentOffset > 1;\n } else {\n // Cursor is on one of the zero width spaces.\n atEnd = originalNode !== tokenNode.previousSibling;\n // If the offset is greater than 1, the browser is trying to insert text into\n // the zero width space node. This will actually end up in the next text node.\n endOffset = atEnd && currentOffset > 1 ? currentOffset - 1 : 0;\n }\n\n currentOffset = atEnd ? (tokenNode?.textContent?.length ?? 0) : 0;\n\n // Several positions are equivalent due to the zero width spaces around tokens.\n // Normalize offset to the end of the preceding text node, or the beginning of the following node.\n if (\n currentOffset === 0 &&\n wrapper.previousSibling?.nodeType === Node.TEXT_NODE\n ) {\n index -= 1;\n currentOffset = wrapper.previousSibling?.textContent?.length ?? 0;\n } else if (atEnd) {\n index += 1;\n currentOffset = endOffset;\n }\n\n return { index, offset: currentOffset };\n}\n\nfunction getCaretRect(root: HTMLElement, range: Range): DOMRect {\n let measurement = range;\n let rect = measurement.getBoundingClientRect();\n\n // A collapsed measurement doesn't always produce a client rect. This happens for empty lines.\n if (\n rect.top === 0 &&\n rect.bottom === 0 &&\n rect.left === 0 &&\n rect.right === 0\n ) {\n let node: Node | null = measurement.endContainer;\n\n if (\n node.nodeType === Node.TEXT_NODE &&\n measurement.endOffset <\n requireValue(node.nodeValue, \"Expected node.nodeValue\").length\n ) {\n // If we are not at the end of the text node, extend the measurement to include the next character.\n measurement = measurement.cloneRange();\n measurement.setEnd(node, measurement.endOffset + 1);\n rect = measurement.getBoundingClientRect();\n } else if (isPresent(root.firstChild)) {\n // Otherwise find the next sibling element (e.g. trailing <br>) and use its rect in this case.\n let nextSibling = node === root ? null : node.nextSibling;\n\n while (node && node !== root && !nextSibling) {\n node = node.parentNode;\n nextSibling = node && node !== root ? node.nextSibling : null;\n }\n\n if (nextSibling?.nodeType === Node.ELEMENT_NODE) {\n rect = requireHTMLElement(nextSibling).getBoundingClientRect();\n }\n } else {\n // If the root has no children, use its rect.\n rect = root.getBoundingClientRect();\n }\n }\n\n return rect;\n}\n\nfunction getInsertionData(\n e: InputEvent,\n transferred: TokenFieldSegment[] | null\n): TokenFieldSegment[] {\n let data: TokenFieldSegment[] = [{ text: e.data ?? \"\", type: \"text\" }];\n\n if (transferred) {\n data = transferred;\n } else if (e.dataTransfer) {\n const parsed = e.dataTransfer.types.includes(CLIPBOARD_MIME_TYPE)\n ? parseSegments(e.dataTransfer.getData(CLIPBOARD_MIME_TYPE))\n : null;\n\n if (parsed) {\n data = parsed;\n } else if (e.dataTransfer.types.includes(\"text/plain\")) {\n data = [{ text: e.dataTransfer.getData(\"text/plain\"), type: \"text\" }];\n }\n }\n\n return data;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkHA,MAAM,sBAAsB;;;;;;;;AAS5B,SAAgB,iBACd,OACA,OACA,KACgB;CAChB,MAAM,WAAW;CACjB,MAAM,WAAW;CACjB,MAAM,WAAW,aAAa;CAE9B,MAAM,oBAAoB,iBAClB,IAAI,KAAK,UAAU,SAAS,QAAQ,EAAE,aAAa,WAAW,CAAC,CACvE;CAEA,MAAM,gBAAgB,iBACd,IAAI,KAAK,UAAU,SAAS,QAAQ,EAAE,aAAa,OAAO,CAAC,CACnE;CAEA,IAAI,eAAgC;CACpC,IAAI,kBAA8C;CAClD,IAAI,YAAoC;CAExC,MAAM,SAAS,OAAoD;EACjE,MAAM,UAAU,UAAU;GACxB,MAAM,WAAW,GAAG,KAAK;GACzB,YAAY;GAEZ,OAAO;EACT,CAAC;CACH;CAOA,MAAM,kBAAkB,sBAAsB,GAAG;CAEjD,MAAM,yBAAyB;EAC7B,gBAAgB,MAAM;EACtB,MAAM,aAAa,IAAI;CACzB;CAEA,MAAM,wBAAwB;EAC5B,gBAAgB,KAAK;EACrB,MAAM,aAAa,KAAK;CAC1B;CAEA,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EA,IAAI,aAAa,aAAa,KAAK,cACjC,OAAO,mBAAmB,WAAW,CAAC,CAAC,sBAAsB;EAEjE,OAEE,OAAO,KAAK,sBAAsB;CAEtC;CAEA,OAAO;AACT;AAEA,SAAS,iBACP,GACA,aACqB;CACrB,IAAI,OAA4B,CAAC;EAAE,MAAM,EAAE,QAAQ;EAAI,MAAM;CAAO,CAAC;CAErE,IAAI,aACF,OAAO;MACF,IAAI,EAAE,cAAc;EACzB,MAAM,SAAS,EAAE,aAAa,MAAM,SAAS,mBAAmB,IAC5D,cAAc,EAAE,aAAa,QAAQ,mBAAmB,CAAC,IACzD;EAEJ,IAAI,QACF,OAAO;OACF,IAAI,EAAE,aAAa,MAAM,SAAS,YAAY,GACnD,OAAO,CAAC;GAAE,MAAM,EAAE,aAAa,QAAQ,YAAY;GAAG,MAAM;EAAO,CAAC;CAExE;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"create-token-field.js","names":[],"sources":["../../../src/tokenfield/create-token-field.ts"],"sourcesContent":["/*\n * Copyright 2026 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing\n */\n/*\n * Derived from Adobe React Spectrum: packages/react-aria/src/tokenfield/useTokenField.ts.\n * Modified for Solid Aria: adapted hooks, reactive getters, DOM types, and imports for Solid 2.\n * Licensed under Apache-2.0. See LICENSES/Apache-2.0.txt and NOTICE.txt at the repository root.\n */\n\nimport type {\n TokenFieldProps,\n TokenFieldState,\n} from \"@solid2-aria/stately/tokenfield/create-token-field-state\";\nimport { TokenFieldValue } from \"@solid2-aria/stately/tokenfield/token-field-value\";\nimport type {\n Position,\n SelectedRange,\n TokenFieldSegment,\n} from \"@solid2-aria/stately/tokenfield/token-field-value\";\nimport type {\n AriaLabelingProps,\n FocusableProps,\n} from \"@solid2-aria/types-shared\";\nimport type { DOMAttributes } from \"@solid2-aria/types-shared-web\";\nimport { merge, createMemo, createEffect, onSettled } from \"solid-js\";\nimport type { Accessor } from \"solid-js\";\n\nimport { createLocale } from \"../i18n/i18n-provider\";\nimport {\n getInteractionModality,\n setInteractionModality,\n} from \"../interactions/create-focus-visible\";\nimport { createFocusable } from \"../interactions/create-focusable\";\nimport { createKeyboard } from \"../interactions/create-keyboard\";\nimport type { KeyboardShortcutBindings } from \"../interactions/create-keyboard-shortcut-handler\";\nimport { createField } from \"../label/create-field\";\nimport { announce } from \"../live-announcer/live-announcer\";\nimport type {\n ClipboardEventHandler,\n HTMLAttributes,\n KeyboardEvent,\n} from \"../types\";\nimport { ariaValue } from \"../utils/aria-value\";\nimport { createEvent } from \"../utils/create-event\";\nimport { getOwnerDocument } from \"../utils/dom-helpers\";\nimport { requireHTMLElement } from \"../utils/dom-value\";\nimport { getScrollParents } from \"../utils/get-scroll-parents\";\nimport { isPresent } from \"../utils/is-present\";\nimport { mergeProps } from \"../utils/merge-props\";\nimport { isMac } from \"../utils/platform\";\nimport { requireValue } from \"../utils/require-value\";\nimport { scrollRectIntoView } from \"../utils/scroll-into-view\";\nimport {\n getActiveElement,\n getParentNode,\n nodeContains,\n} from \"../utils/shadowdom/dom-functions\";\nimport { isTruthy } from \"../utils/truthy\";\n\nexport type AriaTokenFieldProps<T extends TokenFieldValue = TokenFieldValue> =\n TokenFieldProps<T> &\n Omit<FocusableProps, \"onKeyDown\" | \"onKeyUp\"> &\n AriaLabelingProps & {\n /**\n * The accessibility role of the token field.\n *\n * @default 'textbox'\n */\n role?: \"textbox\" | \"searchbox\" | \"combobox\";\n /** Whether the token field allows newlines. */\n allowsNewlines?: boolean;\n /** Whether the token field is read only. */\n isReadOnly?: boolean;\n /** Whether the token field is disabled. */\n isDisabled?: boolean;\n /** A function that is called when the user presses the Enter key. */\n onSubmit?: () => void;\n /** Handler that is called when a key is pressed. */\n onKeyDown?: (e: KeyboardEvent<HTMLDivElement>) => void;\n /** Handler that is called when a key is released. */\n onKeyUp?: (e: KeyboardEvent<HTMLDivElement>) => void;\n /**\n * Handler that is called when the user copies text. See\n * [MDN](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/oncopy).\n */\n onCopy?: ClipboardEventHandler<HTMLDivElement>;\n /**\n * Handler that is called when the user cuts text. See\n * [MDN](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/oncut).\n */\n onCut?: ClipboardEventHandler<HTMLDivElement>;\n /**\n * Handler that is called when the user pastes text. See\n * [MDN](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/onpaste).\n */\n onPaste?: ClipboardEventHandler<HTMLDivElement>;\n };\n\nexport interface TokenFieldAria {\n /** Props for the token field's input element. */\n tokenFieldProps: HTMLAttributes<HTMLDivElement>;\n /** Props for the text field's visible label element, if any. */\n labelProps: DOMAttributes;\n /** Props for the text field's description element, if any. */\n descriptionProps: DOMAttributes;\n}\n\nconst CLIPBOARD_MIME_TYPE = \"application/vnd.react-aria.tokens+json\";\n\n/**\n * Provides the behavior and accessibility implementation for a token field.\n * A token field allows users to enter text with inline tokens.\n *\n * @param props - Props for the token field.\n * @param state - State for the token field, as returned by `useTokenFieldState`.\n */\nexport function createTokenField<T extends TokenFieldValue = TokenFieldValue>(\n props: AriaTokenFieldProps<T>,\n state: TokenFieldState,\n ref: Accessor<HTMLDivElement | null>\n): TokenFieldAria {\n const _result1 = props;\n const _result2 = state;\n const _result3 = createLocale();\n\n const graphemeSegmenter = createMemo(\n () => new Intl.Segmenter(_result3.locale, { granularity: \"grapheme\" })\n );\n\n const wordSegmenter = createMemo(\n () => new Intl.Segmenter(_result3.locale, { granularity: \"word\" })\n );\n\n let dropPosition: Position | null = null;\n let transferredData: TokenFieldSegment[] | null = null;\n let nextValue: TokenFieldValue | null = null;\n\n const apply = (fn: (value: TokenFieldValue) => TokenFieldValue) => {\n state.setValue((value) => {\n const newValue = fn(value);\n nextValue = newValue;\n\n return newValue;\n });\n };\n\n // Composition events are not cancelable. Pause controlled DOM updates while the IME owns it,\n // track the browser's mutations, then restore the controlled value when composition ends.\n // Mutating the DOM in any way during composition breaks the IME, causing composition to end unexpectedly.\n // During composition, we still emit updates via onChange to ensure that things like autocomplete work,\n // but we don't actually re-render to the DOM unless the value changes from what we expect (e.g. inserting a completion).\n const mutationTracker = createMutationTracker(ref);\n\n const startComposition = () => {\n mutationTracker.start();\n state.setComposing(true);\n };\n\n const stopComposition = () => {\n mutationTracker.stop();\n state.setComposing(false);\n };\n\n createEvent(ref, \"compositionstart\", () => {\n startComposition();\n const range = window.getSelection()?.getRangeAt(0);\n\n if (range) {\n const [start, end] = rangeToPositions(\n requireValue(ref(), \"Expected ref.current\"),\n range\n );\n\n // Normalize the range to ensure it is not inside a token, otherwise the browser\n // will attempt to insert the composed text into the token instead of replacing it.\n const r = createDOMRange(\n requireValue(ref(), \"Expected ref.current\"),\n start,\n end\n );\n\n if (\n r.startContainer !== range.startContainer ||\n r.startOffset !== range.startOffset\n ) {\n range.setStart(r.startContainer, r.startOffset);\n }\n\n if (\n r.endContainer !== range.endContainer ||\n r.endOffset !== range.endOffset\n ) {\n range.setEnd(r.endContainer, r.endOffset);\n }\n }\n });\n createEvent(ref, \"compositionend\", stopComposition);\n // If a prop update occurs during composition that doesn't match the expected value,\n // end composition and re-render the controlled value.\n createEffect(\n () => ({ isComposing: state.isComposing, value: _result2.value }),\n ({ value, isComposing }) => {\n if (isComposing && value !== nextValue) {\n stopComposition();\n }\n\n nextValue = value;\n },\n { ssrSource: \"client\" }\n );\n let selectedRange: SelectedRange | null = null;\n createEffect(\n () => ({\n element: ref(),\n isComposing: state.isComposing,\n observedSelectedRange: _result2.value.selectedRange,\n value: _result2.value,\n }),\n ({ observedSelectedRange, value, isComposing, element }) => {\n const refElement = element;\n\n if (\n refElement &&\n !isComposing &&\n observedSelectedRange !== selectedRange\n ) {\n // Only move the caret when the field is already focused.\n if (refElement === getActiveElement(getOwnerDocument(refElement))) {\n setTokenFieldSelection(refElement, observedSelectedRange);\n announceToken(value);\n // We call preventDefault in the beforeinput handler below, which also prevents the\n // browser's default behavior of scrolling the caret into view. Do it ourselves instead.\n scrollCaretIntoView(refElement);\n }\n\n selectedRange = observedSelectedRange;\n }\n },\n { ssrSource: \"client\" }\n );\n // Handle text editing commands and prevent browser default behavior.\n createEvent(ref, \"beforeinput\", (e) => {\n // Android sometimes doesn't fire a compositionend event before a regular input event.\n if (state.isComposing && !e.isComposing) {\n stopComposition();\n }\n\n let [range] = e.getTargetRanges();\n\n if (!range) {\n const selection = window.getSelection();\n\n if (!selection || selection.rangeCount === 0) {\n return;\n }\n\n range = selection.getRangeAt(0);\n }\n\n let [start, end] = rangeToPositions(\n requireValue(ref(), \"Expected ref.current\"),\n range\n );\n\n // insertFromComposition is no longer in the spec but is still fired by Safari.\n // https://www.w3.org/TR/input-events-2/#interface-InputEvent-Attributes\n switch (e.inputType) {\n case \"insertText\":\n case \"insertReplacementText\":\n case \"insertCompositionText\":\n case \"insertFromComposition\":\n case \"insertFromPaste\":\n case \"insertFromYank\":\n case \"insertFromDrop\": {\n const data = getInsertionData(e, transferredData);\n transferredData = null;\n\n if (e.inputType === \"insertFromDrop\" && dropPosition) {\n end = dropPosition;\n start = end;\n dropPosition = null;\n }\n\n if (!(_result1.allowsNewlines ?? false)) {\n for (const segment of data) {\n segment.text = segment.text.replaceAll(/[\\r\\n]+/gu, \" \");\n }\n }\n\n apply((tokens) =>\n tokens.replaceRangeWithSegments(\n start,\n end,\n data,\n // Don't coalesce paste/drop events with other edits.\n e.inputType === \"insertText\" ||\n e.inputType === \"insertCompositionText\" ||\n e.inputType === \"insertFromComposition\"\n )\n );\n break;\n }\n\n case \"insertParagraph\": {\n if (props.onSubmit) {\n props.onSubmit();\n break;\n }\n\n if (_result1.allowsNewlines ?? false) {\n apply((tokens) => tokens.replaceRange(start, end, \"\\n\"));\n }\n\n break;\n }\n\n case \"insertLineBreak\": {\n if (_result1.allowsNewlines ?? false) {\n apply((tokens) => tokens.replaceRange(start, end, \"\\n\"));\n }\n\n break;\n }\n\n case \"deleteContentBackward\":\n case \"deleteContentForward\":\n case \"deleteWordBackward\":\n case \"deleteWordForward\":\n case \"deleteHardLineForward\":\n case \"deleteHardLineBackward\":\n case \"deleteSoftLineForward\":\n case \"deleteSoftLineBackward\":\n case \"deleteContent\":\n case \"deleteByCut\":\n case \"deleteCompositionText\": {\n if (!range.collapsed && !isSamePosition(start, end)) {\n apply((tokens) => tokens.replaceRange(start, end, \"\"));\n break;\n }\n\n switch (e.inputType) {\n case \"deleteContentBackward\": {\n apply((tokens) =>\n tokens.delete(\n start,\n graphemeSegmenter(),\n TokenFieldValue.Direction.Backward\n )\n );\n break;\n }\n\n case \"deleteContentForward\": {\n apply((tokens) =>\n tokens.delete(\n start,\n graphemeSegmenter(),\n TokenFieldValue.Direction.Forward\n )\n );\n break;\n }\n\n case \"deleteWordBackward\": {\n apply((tokens) =>\n tokens.delete(\n start,\n wordSegmenter(),\n TokenFieldValue.Direction.Backward\n )\n );\n break;\n }\n\n case \"deleteWordForward\": {\n apply((tokens) =>\n tokens.delete(\n start,\n wordSegmenter(),\n TokenFieldValue.Direction.Forward\n )\n );\n break;\n }\n\n case \"deleteHardLineForward\":\n case \"deleteSoftLineForward\": {\n // Follow-up: this usually deletes to the nearest *visual* line break rather than a hard break\n apply((tokens) =>\n tokens.deleteLine(start, TokenFieldValue.Direction.Forward)\n );\n break;\n }\n\n case \"deleteHardLineBackward\":\n case \"deleteSoftLineBackward\": {\n apply((tokens) =>\n tokens.deleteLine(start, TokenFieldValue.Direction.Backward)\n );\n break;\n }\n\n case \"deleteByCut\": {\n throw new Error('Not implemented yet: \"deleteByCut\" case');\n }\n\n case \"deleteCompositionText\": {\n throw new Error(\n 'Not implemented yet: \"deleteCompositionText\" case'\n );\n }\n\n case \"deleteContent\": {\n throw new Error('Not implemented yet: \"deleteContent\" case');\n }\n\n default: {\n break;\n }\n }\n\n break;\n }\n\n case \"deleteByDrag\": {\n apply((tokens) => {\n const endOffset =\n start.index === end.index\n ? end.offset\n : (tokens.segments[start.index]?.text.length ?? 0);\n\n const change = tokens.replaceRange(start, end, \"\");\n\n if (\n dropPosition &&\n dropPosition.index === start.index &&\n dropPosition.offset >= start.offset\n ) {\n dropPosition.offset -= endOffset - start.offset;\n }\n\n return change;\n });\n break;\n }\n\n default: {\n break;\n }\n }\n\n e.preventDefault();\n });\n\n const writeClipboardData = (e: ClipboardEvent | DragEvent) => {\n if (\"clipboardData\" in e) {\n e.preventDefault();\n }\n\n const selection = getSelection(requireValue(ref(), \"Expected ref.current\"));\n\n if (!selection) {\n return;\n }\n\n const [start, end] = selection;\n const slice = _result2.value.slice(start, end);\n\n const dataTransfer =\n \"clipboardData\" in e ? e.clipboardData : e.dataTransfer;\n\n dataTransfer?.setData(CLIPBOARD_MIME_TYPE, JSON.stringify(slice.segments));\n dataTransfer?.setData(\"text/plain\", slice.toString());\n\n if (e.type === \"cut\") {\n apply((tokens) => tokens.replaceRange(start, end, \"\", false));\n }\n };\n\n createEvent(ref, \"copy\", writeClipboardData);\n createEvent(ref, \"cut\", writeClipboardData);\n createEvent(ref, \"dragstart\", writeClipboardData);\n createEvent(ref, \"paste\", (e) => {\n // Safari doesn't pass the custom clipboard data type to beforeinput dataTransfer so we handle it here.\n if (\n e.clipboardData &&\n e.clipboardData.types.includes(CLIPBOARD_MIME_TYPE)\n ) {\n transferredData = parseSegments(\n e.clipboardData.getData(CLIPBOARD_MIME_TYPE)\n );\n }\n });\n // Store the cursor position on drop so we know where to insert when the insertFromDrop event occurs.\n createEvent(ref, \"drop\", (e) => {\n if (typeof document.caretPositionFromPoint === \"function\") {\n const pos = document.caretPositionFromPoint(e.clientX, e.clientY);\n\n if (pos) {\n dropPosition = getPosition(\n requireValue(ref(), \"Expected ref.current\"),\n pos.offsetNode,\n pos.offset\n );\n }\n } else {\n // oxlint-disable-next-line typescript/no-deprecated, typescript/unbound-method -- Retain the Safari caret fallback and call it with its document receiver.\n const legacyCaretRange = document.caretRangeFromPoint;\n\n const range =\n typeof legacyCaretRange === \"function\"\n ? legacyCaretRange.call(document, e.clientX, e.clientY)\n : null;\n\n if (range) {\n dropPosition = getPosition(\n requireValue(ref(), \"Expected ref.current\"),\n range.startContainer,\n range.startOffset\n );\n }\n }\n\n if (e.dataTransfer && e.dataTransfer.types.includes(CLIPBOARD_MIME_TYPE)) {\n transferredData = parseSegments(\n e.dataTransfer.getData(CLIPBOARD_MIME_TYPE)\n );\n }\n });\n createSelectionChange(ref, () => {\n if (state.isComposing) {\n return;\n }\n\n _result2.value.endCoalescing();\n\n // When the cursor moves next to a token, announce it.\n // Otherwise the screen reader will only announce the first/last character.\n const range = getSelectedRange(requireValue(ref(), \"Expected ref.current\"));\n\n if (!range) {\n return;\n }\n\n announceToken(_result2.value, range);\n // Update the selected range in the value.\n state.setValue((value) => value.withSelectedRange(range));\n });\n // Clear selection on blur.\n createEvent(ref, \"blur\", (e) => {\n const refElement = ref();\n\n if (!e.isTrusted) {\n return;\n }\n\n const selection = window.getSelection();\n\n if (\n refElement &&\n selection &&\n selection.containsNode(refElement, true) &&\n !selection.isCollapsed\n ) {\n selection.removeAllRanges();\n state.setValue((value) =>\n value.withSelectedRange(\n new TokenFieldValue.SelectedRange(value.caretPosition)\n )\n );\n }\n });\n // Override the default triple click behavior to ensure that tokens get selected.\n // Some browsers only select the text between tokens instead of the entire line.\n createEvent(ref, \"mousedown\", (e) => {\n if (e.detail === 3) {\n const selection = getSelection(\n requireValue(ref(), \"Expected ref.current\")\n );\n\n if (!selection) {\n return;\n }\n\n const start = _result2.value.findLineBoundary(\n selection[0],\n TokenFieldValue.Direction.Backward\n );\n\n const end = _result2.value.findLineBoundary(\n selection[1],\n TokenFieldValue.Direction.Forward\n );\n\n if (start && end) {\n e.preventDefault();\n setTokenFieldSelection(\n requireValue(ref(), \"Expected ref.current\"),\n new TokenFieldValue.SelectedRange(start, end),\n true\n );\n }\n }\n });\n\n const moveSelection = (\n direction: \"left\" | \"right\",\n granularity: \"character\" | \"word\",\n extend = false\n ) => {\n const selection = window.getSelection();\n\n if (\n !selection ||\n selection.rangeCount === 0 ||\n !selection.focusNode ||\n !selection.anchorNode\n ) {\n return false;\n }\n\n // Pressing an arrow with a non-empty selection collapses it to the corresponding edge.\n // The browser handles this natively.\n if (!extend && !selection.isCollapsed) {\n return false;\n }\n\n // Move the caret using the browser's native caret movement (Selection.modify) so that\n // bidirectional text is handled correctly. Repeat until the position actually changes\n // to account for the zero width spaces around tokens.\n const pos = getPosition(\n requireValue(ref(), \"Expected ref.current\"),\n selection.focusNode,\n selection.focusOffset\n );\n\n while (true) {\n const focusNode: globalThis.Node | null = selection.focusNode;\n const focusOffset: number = selection.focusOffset;\n selection.modify(extend ? \"extend\" : \"move\", direction, granularity);\n\n if (\n selection.focusNode === focusNode &&\n selection.focusOffset === focusOffset\n ) {\n return false;\n }\n\n if (!isTruthy(selection.focusNode)) {\n return false;\n }\n\n const newPos = getPosition(\n requireValue(ref(), \"Expected ref.current\"),\n selection.focusNode,\n selection.focusOffset\n );\n\n if (!isSamePosition(pos, newPos)) {\n return true;\n }\n }\n };\n\n // macOS supports additional keyboard shortcuts for text editing.\n // We need to handle these manually so they behave consistently with tokens.\n // https://support.apple.com/en-us/102650#text\n\n const mod = isMac() ? \"Meta\" : \"Control\";\n const wordModKey = isMac() ? \"Alt\" : \"Control\";\n\n const shortcuts: KeyboardShortcutBindings = {\n [`${mod}+z`]: (): undefined | false => {\n // If composing, the browser handles undo natively.\n if (state.isComposing) {\n return false;\n }\n\n apply((currentState) => currentState.undo());\n\n return undefined;\n },\n [isMac() ? \"Shift+Meta+z\" : \"Control+y\"]: (): undefined | false => {\n if (state.isComposing) {\n return false;\n }\n\n apply((currentState2) => currentState2.redo());\n\n return undefined;\n },\n ArrowLeft: () => moveSelection(\"left\", \"character\"),\n [`${wordModKey}+ArrowLeft`]: () => moveSelection(\"left\", \"word\"),\n ArrowRight: () => moveSelection(\"right\", \"character\"),\n [`Shift+${wordModKey}+ArrowLeft`]: () =>\n moveSelection(\"left\", \"word\", true),\n End: () => {\n const selection = getSelection(\n requireValue(ref(), \"Expected ref.current\")\n );\n\n if (!selection) {\n return false;\n }\n\n const boundary = _result2.value.findLineBoundary(\n selection[1],\n TokenFieldValue.Direction.Forward\n );\n\n if (boundary) {\n setCursor(requireValue(ref(), \"Expected ref.current\"), boundary, true);\n\n return true;\n }\n\n return false;\n },\n [`${wordModKey}+ArrowRight`]: () => moveSelection(\"right\", \"word\"),\n Home: () => {\n // Browsers do not behave consistently when there are tokens.\n const selection = getSelection(\n requireValue(ref(), \"Expected ref.current\")\n );\n\n if (!selection) {\n return false;\n }\n\n const boundary = _result2.value.findLineBoundary(\n selection[0],\n TokenFieldValue.Direction.Backward\n );\n\n if (boundary) {\n setCursor(requireValue(ref(), \"Expected ref.current\"), boundary, true);\n\n return true;\n }\n\n return false;\n },\n [`Shift+${wordModKey}+ArrowRight`]: () =>\n moveSelection(\"right\", \"word\", true),\n \"Shift+ArrowLeft\": () => moveSelection(\"left\", \"character\", true),\n \"Shift+ArrowRight\": () => moveSelection(\"right\", \"character\", true),\n };\n\n const macShortcuts: KeyboardShortcutBindings = isMac()\n ? {\n \"Control+a\": (event) => shortcuts.Home?.(event),\n \"Control+b\": (event) => shortcuts.ArrowLeft?.(event),\n \"Control+e\": (event) => shortcuts.End?.(event),\n \"Control+f\": (event) => shortcuts.ArrowRight?.(event),\n }\n : {};\n\n Object.assign(shortcuts, macShortcuts);\n\n // Follow-up: user provided onKeyDown currently relies on user provided preventDefault to stop submit\n // maybe can have them specify a format like shortcuts and merge into above?\n const _result4 = createKeyboard({\n get allowRepeats(): true {\n return true;\n },\n get isDisabled() {\n return (_result1.isDisabled ?? false) || (_result1.isReadOnly ?? false);\n },\n get onKeyDown() {\n return props.onKeyDown;\n },\n get onKeyUp() {\n return props.onKeyUp;\n },\n get shortcuts() {\n return shortcuts;\n },\n });\n\n const _result5 = createFocusable(props, ref);\n\n const _result6 = createField(\n merge(props, {\n get labelElementType(): \"span\" {\n return \"span\";\n },\n })\n );\n\n return {\n get descriptionProps() {\n return _result6.descriptionProps;\n },\n get labelProps() {\n return merge(_result6.labelProps, {\n onClick: () => {\n if (!isTruthy(props.isDisabled)) {\n ref()?.focus();\n // Show the focus ring so the user knows where focus went\n setInteractionModality(\"keyboard\");\n }\n },\n });\n },\n get tokenFieldProps() {\n return mergeProps(\n _result5.focusableProps,\n _result4.keyboardProps,\n _result6.fieldProps,\n {\n \"aria-details\": ariaValue(_result1[\"aria-details\"]),\n \"aria-disabled\": ariaValue(_result1.isDisabled ?? false),\n \"aria-multiline\": ariaValue(_result1.allowsNewlines ?? false),\n \"aria-readonly\": ariaValue(_result1.isReadOnly ?? false),\n contenteditable:\n !(_result1.isDisabled ?? false) && !(_result1.isReadOnly ?? false),\n onCopy: props.onCopy,\n onCut: props.onCut,\n onPaste: props.onPaste,\n role: _result1.role ?? \"textbox\",\n style: { whiteSpace: \"pre-wrap\" },\n suppressContentEditableWarning: true,\n }\n );\n },\n };\n}\n\nfunction indexOfNode(node: Node) {\n let index = 0;\n let n: Node | null = node;\n\n while ((n = n.previousSibling)) {\n index += 1;\n }\n\n return index;\n}\n\nexport function getSelection(container: Element): [Position, Position] | null {\n const selection = window.getSelection();\n\n if (!selection || selection.rangeCount === 0) {\n return null;\n }\n\n const range = selection.getRangeAt(0);\n\n return rangeToPositions(container, range);\n}\n\nexport function getSelectedRange(container: Element) {\n const selection = window.getSelection();\n\n if (\n !selection ||\n !selection.anchorNode ||\n !selection.focusNode ||\n !nodeContains(container, selection.anchorNode) ||\n !nodeContains(container, selection.focusNode)\n ) {\n return null;\n }\n\n const anchor = getPosition(\n container,\n selection.anchorNode,\n selection.anchorOffset,\n false\n );\n\n const current = getPosition(\n container,\n selection.focusNode,\n selection.focusOffset,\n !selection.isCollapsed\n );\n\n return new TokenFieldValue.SelectedRange(anchor, current);\n}\n\nfunction rangeToPositions(\n container: Element,\n range: Range | StaticRange\n): [Position, Position] {\n const start = getPosition(\n container,\n range.startContainer,\n range.startOffset,\n false\n );\n\n const end = getPosition(\n container,\n range.endContainer,\n range.endOffset,\n !range.collapsed\n );\n\n return [start, end];\n}\n\nfunction getPosition(\n container: Element,\n node: Node,\n offset: number,\n isRangeEnd = false\n): Position {\n let currentNode = node;\n const currentOffset = offset;\n\n if (currentNode === container) {\n return { index: currentOffset, offset: 0 };\n }\n\n const originalNode = currentNode;\n\n while (getParentNode(currentNode) !== container) {\n currentNode = requireValue(\n getParentNode(currentNode),\n \"Expected node.parentNode\"\n );\n }\n\n const index = indexOfNode(currentNode);\n\n if (currentNode.nodeType === Node.ELEMENT_NODE) {\n return getTokenPosition(\n currentNode,\n originalNode,\n currentOffset,\n isRangeEnd,\n index\n );\n }\n\n return { index, offset: currentOffset };\n}\n\nconst programmaticSelectionChanges = new WeakSet<Element>();\n\nfunction setCursor(root: Element, pos: Position, fireEvent = false) {\n setTokenFieldSelection(\n root,\n new TokenFieldValue.SelectedRange(pos),\n fireEvent\n );\n}\n\nexport function setTokenFieldSelection(\n root: Element,\n selectedRange: SelectedRange,\n fireEvent = false\n) {\n const selection = window.getSelection();\n\n if (selection) {\n // Use setBaseAndExtent to preserve the selection direction. A plain Range +\n // addRange always produces a forward selection and collapses when the\n // anchor comes after the current position (backward selections).\n const [anchorNode, anchorOffset] = getDOMPosition(\n root,\n selectedRange.anchor\n );\n\n const [focusNode, focusOffset] = getDOMPosition(\n root,\n selectedRange.current\n );\n\n // Only set selection if it has changed, because this can clobber the browser's selection direction.\n if (\n selection.anchorNode !== anchorNode ||\n selection.anchorOffset !== anchorOffset ||\n selection.focusNode !== focusNode ||\n selection.focusOffset !== focusOffset\n ) {\n // Only flag the change when the selection actually moves. Otherwise no selectionchange\n // event fires to consume the flag, and the next user selection change would be ignored.\n if (fireEvent) {\n programmaticSelectionChanges.delete(root);\n } else {\n programmaticSelectionChanges.add(root);\n }\n\n selection.setBaseAndExtent(\n anchorNode,\n anchorOffset,\n focusNode,\n focusOffset\n );\n }\n }\n}\n\n// Calling preventDefault in the beforeinput handler stops the browser from performing its\n// default edit action, which also suppresses its normal behavior of scrolling the caret into\n// view. Recreate that behavior by measuring the caret's position with a Range and\n// scrolling each scrollable ancestor of the field so it is visible.\nfunction scrollCaretIntoView(root: HTMLElement): void {\n const selection = window.getSelection();\n\n if (\n getInteractionModality() !== \"keyboard\" ||\n !selection ||\n selection.rangeCount === 0 ||\n !nodeContains(root, selection.focusNode)\n ) {\n return;\n }\n\n let range = selection.getRangeAt(0);\n\n if (range.collapsed && range.endContainer === root) {\n // Root-level positions around tokens have no rect. Measure the adjacent\n // zero width space without moving the actual selection into the token.\n range = tokenFieldPositionToDOMRange(root, {\n index: range.endOffset,\n offset: 0,\n });\n }\n\n let rect = getCaretRect(root, range);\n\n for (const element of getScrollParents(root, true)) {\n // scrollRectIntoView only scrolls a single scroll parent based on `rect`, which is a\n // snapshot of the caret's position before any scrolling occurs. Scrolling an inner ancestor\n // moves the caret within the viewport, so translate `rect` by however much we just scrolled\n // before moving on to the next (outer) ancestor.\n const scrollParent = requireHTMLElement(element);\n const beforeTop = scrollParent.scrollTop;\n const beforeLeft = scrollParent.scrollLeft;\n scrollRectIntoView(scrollParent, root, rect, {\n block: \"nearest\",\n inline: \"nearest\",\n });\n const dy = scrollParent.scrollTop - beforeTop;\n const dx = scrollParent.scrollLeft - beforeLeft;\n\n if (dy !== 0 || dx !== 0) {\n rect = new DOMRect(rect.x - dx, rect.y - dy, rect.width, rect.height);\n }\n }\n}\n\nexport function tokenFieldPositionToDOMRange(\n root: Element,\n pos: Position\n): Range {\n // Unlike createDOMRange (used for caret/selection placement), this range is only\n // measured via getBoundingClientRect to position things like an autocomplete popover.\n // Place the endpoints inside the token's zero width space wrappers so the range has a\n // valid rect at the token, rather than a collapsed root-level position.\n const range = document.createRange();\n const [startContainer, startOffset] = getDOMRectPosition(root, pos);\n range.setStart(startContainer, startOffset);\n range.setEnd(startContainer, startOffset);\n\n return range;\n}\n\nfunction getDOMRectPosition(root: Element, pos: Position): [Node, number] {\n const child = root.childNodes[pos.index];\n\n if (\n pos.index >= root.childNodes.length &&\n root.lastChild?.lastChild?.nodeType === Node.TEXT_NODE\n ) {\n // A position after the last token belongs to its trailing zero width space.\n const text = root.lastChild.lastChild;\n\n return [\n text,\n requireValue(text.textContent, \"Expected text.textContent\").length,\n ];\n }\n\n if (child && child.nodeType === Node.ELEMENT_NODE) {\n // Place the position inside the zero width space wrappers around the token.\n if (pos.offset > 0) {\n return [requireValue(child.lastChild, \"Expected child.lastChild\"), 1];\n }\n\n return [requireValue(child.firstChild, \"Expected child.firstChild\"), 0];\n }\n\n return getDOMPosition(root, pos);\n}\n\nfunction createDOMRange(root: Element, start: Position, end: Position): Range {\n const range = document.createRange();\n const [startContainer, startOffset] = getDOMPosition(root, start);\n const [endContainer, endOffset] = getDOMPosition(root, end);\n range.setStart(startContainer, startOffset);\n range.setEnd(endContainer, endOffset);\n\n return range;\n}\n\nfunction getDOMPosition(root: Element, pos: Position): [Node, number] {\n const index = Math.max(0, Math.min(root.childNodes.length, pos.index));\n const child = root.childNodes[index];\n\n if (!child) {\n return [root, index];\n } else if (child.nodeType === Node.ELEMENT_NODE) {\n // Place the cursor outside the token wrapper element.\n // This is necessary for composition events.\n if (pos.offset > 0) {\n return [root, index + 1];\n }\n\n return [root, index];\n }\n\n const offset = Math.max(\n 0,\n Math.min(child.textContent?.length ?? 0, pos.offset)\n );\n\n return [child, offset];\n}\n\nfunction isSamePosition(a: Position, b: Position): boolean {\n return a.index === b.index && a.offset === b.offset;\n}\n\n// Parse and validate segments from clipboard/drag data. Returns null if the data is not valid\n// JSON or does not match the expected shape, so malformed or untrusted data is ignored rather\n// than throwing or being inserted into the field.\nfunction parseSegments(json: string): TokenFieldSegment[] | null {\n try {\n const data: unknown = JSON.parse(json);\n\n if (Array.isArray(data) && data.length > 0 && data.every(isValidSegment)) {\n return data;\n }\n } catch {\n // Ignore invalid clipboard data.\n }\n\n return null;\n}\n\nfunction isValidSegment(segment: unknown): segment is TokenFieldSegment {\n return (\n typeof segment === \"object\" &&\n segment !== null &&\n segment !== undefined &&\n \"type\" in segment &&\n (segment.type === \"text\" || segment.type === \"token\") &&\n \"text\" in segment &&\n typeof segment.text === \"string\"\n );\n}\n\nfunction createSelectionChange(\n ref: Accessor<Element | null>,\n handler: () => void\n) {\n createEvent(\n () => (typeof document === \"undefined\" ? null : document),\n \"selectionchange\",\n () => {\n const refElement = ref();\n\n if (refElement && programmaticSelectionChanges.has(refElement)) {\n programmaticSelectionChanges.delete(refElement);\n\n return;\n }\n\n const selection = window.getSelection();\n\n if (!selection || selection.rangeCount === 0 || !refElement) {\n return;\n }\n\n const range = selection.getRangeAt(0);\n\n if (range.intersectsNode(refElement)) {\n handler();\n }\n }\n );\n}\n\nfunction createMutationTracker(ref: Accessor<Element | null>) {\n let mutationTracker: (() => void) | null = null;\n // Disconnect the mutation observer if the field unmounts mid-composition.\n onSettled(() => () => {\n mutationTracker?.();\n mutationTracker = null;\n });\n\n const _memo0 = {\n start() {\n // Android sometimes fires two compositionstart events in a row, without a compositionend.\n // In that case, reuse the existing tracker.\n mutationTracker ??= trackMutations(\n requireValue(ref(), \"Expected ref.current\")\n );\n },\n stop() {\n mutationTracker?.();\n mutationTracker = null;\n },\n };\n\n return _memo0;\n}\n\n// Tracks mutations to the DOM until the returned function is called,\n// at which point the mutations are reverted.\nfunction trackMutations(element: Element) {\n const mutations: MutationRecord[] = [];\n\n const observer = new MutationObserver((records) => {\n mutations.push(...records);\n });\n\n observer.observe(element, {\n characterData: true,\n characterDataOldValue: true,\n childList: true,\n subtree: true,\n });\n\n return () => {\n mutations.push(...observer.takeRecords());\n observer.disconnect();\n\n for (const record of mutations.toReversed()) {\n switch (record.type) {\n case \"childList\": {\n for (const node of record.removedNodes) {\n record.target.insertBefore(node, record.nextSibling);\n }\n\n for (const node of record.addedNodes) {\n // oxlint-disable-next-line unicorn/prefer-dom-node-remove -- MutationRecord exposes Node, which does not declare ChildNode.remove.\n record.target.removeChild(node);\n }\n\n break;\n }\n\n case \"characterData\": {\n record.target.nodeValue = record.oldValue;\n break;\n }\n\n case \"attributes\": {\n throw new Error('Not implemented yet: \"attributes\" case');\n }\n\n default: {\n break;\n }\n }\n }\n };\n}\n\nfunction announceToken(value: TokenFieldValue, range = value.selectedRange) {\n if (range.isCollapsed) {\n // Announce adjacent tokens.\n let segment = value.segments[range.current.index];\n\n if (segment && segment.type !== \"token\") {\n if (range.current.offset === 0) {\n segment = value.segments[range.current.index - 1];\n } else if (range.current.offset === segment.text.length) {\n segment = value.segments[range.current.index + 1];\n }\n }\n\n if (segment?.type === \"token\") {\n announce(segment.text, \"assertive\");\n }\n } else {\n // Announce token if it is the only thing selected.\n const selected = value.slice(range.start, range.end).segments;\n const [only] = selected;\n\n if (selected.length === 1 && only?.type === \"token\") {\n announce(only.text, \"assertive\");\n }\n }\n}\n\nfunction getTokenPosition(\n wrapper: Node,\n originalNode: Node,\n offset: number,\n isRangeEnd: boolean,\n wrapperIndex: number\n): Position {\n let index = wrapperIndex;\n let currentOffset = offset;\n\n const [, tokenNode] = wrapper.childNodes;\n\n if (!tokenNode) {\n return { index, offset: 0 };\n }\n\n let atEnd: boolean;\n let endOffset = 0;\n\n if (originalNode === tokenNode) {\n // Cursor is inside the token.\n atEnd = isRangeEnd || currentOffset > 0;\n } else if (originalNode === wrapper) {\n // Cursor is inside the wrapper element.\n atEnd = currentOffset > 1;\n } else {\n // Cursor is on one of the zero width spaces.\n atEnd = originalNode !== tokenNode.previousSibling;\n // If the offset is greater than 1, the browser is trying to insert text into\n // the zero width space node. This will actually end up in the next text node.\n endOffset = atEnd && currentOffset > 1 ? currentOffset - 1 : 0;\n }\n\n currentOffset = atEnd ? (tokenNode?.textContent?.length ?? 0) : 0;\n\n // Several positions are equivalent due to the zero width spaces around tokens.\n // Normalize offset to the end of the preceding text node, or the beginning of the following node.\n if (\n currentOffset === 0 &&\n wrapper.previousSibling?.nodeType === Node.TEXT_NODE\n ) {\n index -= 1;\n currentOffset = wrapper.previousSibling?.textContent?.length ?? 0;\n } else if (atEnd) {\n index += 1;\n currentOffset = endOffset;\n }\n\n return { index, offset: currentOffset };\n}\n\nfunction getCaretRect(root: HTMLElement, range: Range): DOMRect {\n let measurement = range;\n let rect = measurement.getBoundingClientRect();\n\n // A collapsed measurement doesn't always produce a client rect. This happens for empty lines.\n if (\n rect.top === 0 &&\n rect.bottom === 0 &&\n rect.left === 0 &&\n rect.right === 0\n ) {\n let node: Node | null = measurement.endContainer;\n\n if (\n node.nodeType === Node.TEXT_NODE &&\n measurement.endOffset <\n requireValue(node.nodeValue, \"Expected node.nodeValue\").length\n ) {\n // If we are not at the end of the text node, extend the measurement to include the next character.\n measurement = measurement.cloneRange();\n measurement.setEnd(node, measurement.endOffset + 1);\n rect = measurement.getBoundingClientRect();\n } else if (isPresent(root.firstChild)) {\n // Otherwise find the next sibling element (e.g. trailing <br>) and use its rect in this case.\n let nextSibling = node === root ? null : node.nextSibling;\n\n while (node && node !== root && !nextSibling) {\n node = getParentNode(node);\n nextSibling = node && node !== root ? node.nextSibling : null;\n }\n\n if (nextSibling?.nodeType === Node.ELEMENT_NODE) {\n rect = requireHTMLElement(nextSibling).getBoundingClientRect();\n }\n } else {\n // If the root has no children, use its rect.\n rect = root.getBoundingClientRect();\n }\n }\n\n return rect;\n}\n\nfunction getInsertionData(\n e: InputEvent,\n transferred: TokenFieldSegment[] | null\n): TokenFieldSegment[] {\n let data: TokenFieldSegment[] = [{ text: e.data ?? \"\", type: \"text\" }];\n\n if (transferred) {\n data = transferred;\n } else if (e.dataTransfer) {\n const parsed = e.dataTransfer.types.includes(CLIPBOARD_MIME_TYPE)\n ? parseSegments(e.dataTransfer.getData(CLIPBOARD_MIME_TYPE))\n : null;\n\n if (parsed) {\n data = parsed;\n } else if (e.dataTransfer.types.includes(\"text/plain\")) {\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AE,aAAa,MAAM,SAAS,YAAY,GACnD,OAAO,CAAC;GAAE,MAAM,EAAE,aAAa,QAAQ,YAAY;GAAG,MAAM;EAAO,CAAC;CAExE;CAEA,OAAO;AACT"}
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
* Licensed under Apache-2.0. See LICENSES/Apache-2.0.txt and NOTICE.txt at the repository root.
|
|
16
16
|
*/
|
|
17
17
|
import { isTruthy } from "../utils/truthy.js";
|
|
18
|
+
import { getParentElement } from "../utils/shadowdom/dom-functions.js";
|
|
18
19
|
import { isVirtualClick } from "../utils/is-virtual-event.js";
|
|
19
20
|
import { createEvent } from "../utils/create-event.js";
|
|
20
21
|
import { createSignal } from "solid-js";
|
|
@@ -45,7 +46,7 @@ function createToken(_props, _state, ref) {
|
|
|
45
46
|
onClick(e) {
|
|
46
47
|
if (isSelected() || !isVirtualClick(e)) return;
|
|
47
48
|
const selection = window.getSelection();
|
|
48
|
-
const wrapper = ref()
|
|
49
|
+
const wrapper = getParentElement(ref());
|
|
49
50
|
if (!selection || !wrapper) return;
|
|
50
51
|
const range = document.createRange();
|
|
51
52
|
range.setStartBefore(wrapper);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-token.js","names":[],"sources":["../../../src/tokenfield/create-token.ts"],"sourcesContent":["/*\n * Copyright 2026 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing\n */\n/*\n * Derived from Adobe React Spectrum: packages/react-aria/src/tokenfield/useToken.ts.\n * Modified for Solid Aria: adapted hooks, reactive getters, DOM types, and imports for Solid 2.\n * Licensed under Apache-2.0. See LICENSES/Apache-2.0.txt and NOTICE.txt at the repository root.\n */\n\nimport type { TokenFieldState } from \"@solid2-aria/stately/tokenfield/create-token-field-state\";\nimport { createSignal } from \"solid-js\";\nimport type { Accessor } from \"solid-js\";\n\nimport type { HTMLAttributes } from \"../types\";\nimport { createEvent } from \"../utils/create-event\";\nimport { isVirtualClick } from \"../utils/is-virtual-event\";\nimport { isTruthy } from \"../utils/truthy\";\n\nexport type TokenProps = Record<string, never>;\n\nexport interface TokenAria {\n /** Props for the token element. */\n tokenProps: HTMLAttributes<HTMLSpanElement>;\n /** Whether the token is currently selected. */\n isSelected: boolean;\n}\n\n/**\n * Provides the behavior and accessibility implementation for a token within a token field.\n * A token field allows users to enter text with inline tokens.\n */\nexport function createToken(\n // Unused but matches the normal signature.\n _props: TokenProps,\n _state: TokenFieldState,\n ref: Accessor<HTMLSpanElement | null>\n): TokenAria {\n const [isSelected, setSelected] = createSignal(false, { ownedWrite: true });\n createEvent(\n () => (typeof document === \"undefined\" ? null : document),\n \"selectionchange\",\n () => {\n const refElement = ref();\n const selection = window.getSelection();\n\n if (!selection || !refElement) {\n return;\n }\n\n const range = selection.rangeCount === 0 ? null : selection.getRangeAt(0);\n\n if (\n !isTruthy(range?.collapsed) &&\n isTruthy(range?.intersectsNode(refElement))\n ) {\n setSelected(true);\n } else {\n setSelected(false);\n }\n }\n );\n\n return {\n get isSelected() {\n return isSelected();\n },\n get tokenProps() {\n return {\n get contenteditable(): false {\n return false;\n },\n onClick(e: globalThis.MouseEvent) {\n // Select the token when a screen reader clicks on it.\n if (isSelected() || !isVirtualClick(e)) {\n return;\n }\n\n const selection = window.getSelection();\n const wrapper = ref()
|
|
1
|
+
{"version":3,"file":"create-token.js","names":[],"sources":["../../../src/tokenfield/create-token.ts"],"sourcesContent":["/*\n * Copyright 2026 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing\n */\n/*\n * Derived from Adobe React Spectrum: packages/react-aria/src/tokenfield/useToken.ts.\n * Modified for Solid Aria: adapted hooks, reactive getters, DOM types, and imports for Solid 2.\n * Licensed under Apache-2.0. See LICENSES/Apache-2.0.txt and NOTICE.txt at the repository root.\n */\n\nimport type { TokenFieldState } from \"@solid2-aria/stately/tokenfield/create-token-field-state\";\nimport { createSignal } from \"solid-js\";\nimport type { Accessor } from \"solid-js\";\n\nimport type { HTMLAttributes } from \"../types\";\nimport { createEvent } from \"../utils/create-event\";\nimport { isVirtualClick } from \"../utils/is-virtual-event\";\nimport { getParentElement } from \"../utils/shadowdom/dom-functions\";\nimport { isTruthy } from \"../utils/truthy\";\n\nexport type TokenProps = Record<string, never>;\n\nexport interface TokenAria {\n /** Props for the token element. */\n tokenProps: HTMLAttributes<HTMLSpanElement>;\n /** Whether the token is currently selected. */\n isSelected: boolean;\n}\n\n/**\n * Provides the behavior and accessibility implementation for a token within a token field.\n * A token field allows users to enter text with inline tokens.\n */\nexport function createToken(\n // Unused but matches the normal signature.\n _props: TokenProps,\n _state: TokenFieldState,\n ref: Accessor<HTMLSpanElement | null>\n): TokenAria {\n const [isSelected, setSelected] = createSignal(false, { ownedWrite: true });\n createEvent(\n () => (typeof document === \"undefined\" ? null : document),\n \"selectionchange\",\n () => {\n const refElement = ref();\n const selection = window.getSelection();\n\n if (!selection || !refElement) {\n return;\n }\n\n const range = selection.rangeCount === 0 ? null : selection.getRangeAt(0);\n\n if (\n !isTruthy(range?.collapsed) &&\n isTruthy(range?.intersectsNode(refElement))\n ) {\n setSelected(true);\n } else {\n setSelected(false);\n }\n }\n );\n\n return {\n get isSelected() {\n return isSelected();\n },\n get tokenProps() {\n return {\n get contenteditable(): false {\n return false;\n },\n onClick(e: globalThis.MouseEvent) {\n // Select the token when a screen reader clicks on it.\n if (isSelected() || !isVirtualClick(e)) {\n return;\n }\n\n const selection = window.getSelection();\n const wrapper = getParentElement(ref());\n\n if (!selection || !wrapper) {\n return;\n }\n\n const range = document.createRange();\n range.setStartBefore(wrapper);\n range.setEndAfter(wrapper);\n selection.removeAllRanges();\n selection.addRange(range);\n },\n get style() {\n return {\n get WebkitTapHighlightColor(): \"transparent\" {\n return \"transparent\";\n },\n get WebkitUserSelect(): \"all\" {\n return \"all\";\n },\n get userSelect(): \"all\" {\n return \"all\";\n },\n };\n },\n get suppressContentEditableWarning(): true {\n return true;\n },\n };\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAgB,YAEd,QACA,QACA,KACW;CACX,MAAM,CAAC,YAAY,eAAe,aAAa,OAAO,EAAE,YAAY,KAAK,CAAC;CAC1E,kBACS,OAAO,aAAa,cAAc,OAAO,UAChD,yBACM;EACJ,MAAM,aAAa,IAAI;EACvB,MAAM,YAAY,OAAO,aAAa;EAEtC,IAAI,CAAC,aAAa,CAAC,YACjB;EAGF,MAAM,QAAQ,UAAU,eAAe,IAAI,OAAO,UAAU,WAAW,CAAC;EAExE,IACE,CAAC,SAAS,OAAO,SAAS,KAC1B,SAAS,OAAO,eAAe,UAAU,CAAC,GAE1C,YAAY,IAAI;OAEhB,YAAY,KAAK;CAErB,CACF;CAEA,OAAO;EACL,IAAI,aAAa;GACf,OAAO,WAAW;EACpB;EACA,IAAI,aAAa;GACf,OAAO;IACL,IAAI,kBAAyB;KAC3B,OAAO;IACT;IACA,QAAQ,GAA0B;KAEhC,IAAI,WAAW,KAAK,CAAC,eAAe,CAAC,GACnC;KAGF,MAAM,YAAY,OAAO,aAAa;KACtC,MAAM,UAAU,iBAAiB,IAAI,CAAC;KAEtC,IAAI,CAAC,aAAa,CAAC,SACjB;KAGF,MAAM,QAAQ,SAAS,YAAY;KACnC,MAAM,eAAe,OAAO;KAC5B,MAAM,YAAY,OAAO;KACzB,UAAU,gBAAgB;KAC1B,UAAU,SAAS,KAAK;IAC1B;IACA,IAAI,QAAQ;KACV,OAAO;MACL,IAAI,0BAAyC;OAC3C,OAAO;MACT;MACA,IAAI,mBAA0B;OAC5B,OAAO;MACT;MACA,IAAI,aAAoB;OACtB,OAAO;MACT;KACF;IACF;IACA,IAAI,iCAAuC;KACzC,OAAO;IACT;GACF;EACF;CACF;AACF"}
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
* Licensed under Apache-2.0. See LICENSES/Apache-2.0.txt and NOTICE.txt at the repository root.
|
|
16
16
|
*/
|
|
17
17
|
import { isPresent } from "../utils/is-present.js";
|
|
18
|
-
import { getActiveElement, getEventTarget, nodeContains } from "../utils/shadowdom/dom-functions.js";
|
|
18
|
+
import { getActiveElement, getEventTarget, getParentElement, nodeContains } from "../utils/shadowdom/dom-functions.js";
|
|
19
19
|
import { htmlElementOrNull } from "../utils/dom-value.js";
|
|
20
20
|
import { createLocale } from "../i18n/i18n-provider.js";
|
|
21
21
|
import { ariaValue } from "../utils/aria-value.js";
|
|
@@ -37,7 +37,7 @@ function createToolbar(props, ref) {
|
|
|
37
37
|
const [isInToolbar, setInToolbar] = createSignal(false, { ownedWrite: true });
|
|
38
38
|
createEffect(() => ({ element: ref() }), ({ element }) => {
|
|
39
39
|
const refElement = element;
|
|
40
|
-
setInToolbar(!!(refElement && refElement
|
|
40
|
+
setInToolbar(!!(refElement && getParentElement(refElement)?.closest("[role=\"toolbar\"]")));
|
|
41
41
|
}, { ssrSource: "client" });
|
|
42
42
|
const _result1 = createLocale();
|
|
43
43
|
const shouldReverse = createMemo(() => _result1.direction === "rtl" && (_result0.orientation ?? "horizontal") === "horizontal");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-toolbar.js","names":[],"sources":["../../../src/toolbar/create-toolbar.ts"],"sourcesContent":["/*\n * Copyright 2023 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n/*\n * Derived from Adobe React Spectrum: packages/react-aria/src/toolbar/useToolbar.ts.\n * Modified for Solid Aria: adapted hooks, reactive getters, DOM types, and imports for Solid 2.\n * Licensed under Apache-2.0. See LICENSES/Apache-2.0.txt and NOTICE.txt at the repository root.\n */\n\nimport type {\n AriaLabelingProps,\n FocusableElement,\n Orientation,\n} from \"@solid2-aria/types-shared\";\nimport { merge, createMemo, createSignal, createEffect } from \"solid-js\";\nimport type { Accessor } from \"solid-js\";\n\nimport { createFocusManager } from \"../focus/focus-scope\";\nimport { createLocale } from \"../i18n/i18n-provider\";\nimport type {\n FocusEventHandler,\n HTMLAttributes,\n KeyboardEventHandler,\n} from \"../types\";\nimport { ariaValue } from \"../utils/aria-value\";\nimport { createEvent } from \"../utils/create-event\";\nimport { htmlElementOrNull } from \"../utils/dom-value\";\nimport { filterDOMProps } from \"../utils/filter-dom-props\";\nimport { isPresent } from \"../utils/is-present\";\nimport { scrollIntoViewport } from \"../utils/scroll-into-view\";\nimport {\n getActiveElement,\n getEventTarget,\n nodeContains,\n} from \"../utils/shadowdom/dom-functions\";\n\nexport interface AriaToolbarProps extends AriaLabelingProps {\n /**\n * The orientation of the entire toolbar.\n *\n * @default 'horizontal'\n */\n orientation?: Orientation;\n}\n\nexport interface ToolbarAria {\n /**\n * Props for the toolbar container.\n */\n toolbarProps: HTMLAttributes;\n}\n\n/**\n * Provides the behavior and accessibility implementation for a toolbar.\n * A toolbar is a container for a set of interactive controls with arrow key navigation.\n *\n * @param props - Props to be applied to the toolbar.\n * @param ref - A ref to a DOM element for the toolbar.\n */\nexport function createToolbar(\n props: AriaToolbarProps,\n ref: Accessor<HTMLElement | null>\n): ToolbarAria {\n const _result0 = props;\n const [isInToolbar, setInToolbar] = createSignal(false, { ownedWrite: true });\n // should be safe because re-calling set state with the same value it already has is a no-op\n // this will allow us to react should a parent re-render and change its role though\n\n createEffect(\n () => ({ element: ref() }),\n ({ element }) => {\n const refElement = element;\n setInToolbar(\n !!(refElement
|
|
1
|
+
{"version":3,"file":"create-toolbar.js","names":[],"sources":["../../../src/toolbar/create-toolbar.ts"],"sourcesContent":["/*\n * Copyright 2023 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n/*\n * Derived from Adobe React Spectrum: packages/react-aria/src/toolbar/useToolbar.ts.\n * Modified for Solid Aria: adapted hooks, reactive getters, DOM types, and imports for Solid 2.\n * Licensed under Apache-2.0. See LICENSES/Apache-2.0.txt and NOTICE.txt at the repository root.\n */\n\nimport type {\n AriaLabelingProps,\n FocusableElement,\n Orientation,\n} from \"@solid2-aria/types-shared\";\nimport { merge, createMemo, createSignal, createEffect } from \"solid-js\";\nimport type { Accessor } from \"solid-js\";\n\nimport { createFocusManager } from \"../focus/focus-scope\";\nimport { createLocale } from \"../i18n/i18n-provider\";\nimport type {\n FocusEventHandler,\n HTMLAttributes,\n KeyboardEventHandler,\n} from \"../types\";\nimport { ariaValue } from \"../utils/aria-value\";\nimport { createEvent } from \"../utils/create-event\";\nimport { htmlElementOrNull } from \"../utils/dom-value\";\nimport { filterDOMProps } from \"../utils/filter-dom-props\";\nimport { isPresent } from \"../utils/is-present\";\nimport { scrollIntoViewport } from \"../utils/scroll-into-view\";\nimport {\n getActiveElement,\n getEventTarget,\n nodeContains,\n getParentElement,\n} from \"../utils/shadowdom/dom-functions\";\n\nexport interface AriaToolbarProps extends AriaLabelingProps {\n /**\n * The orientation of the entire toolbar.\n *\n * @default 'horizontal'\n */\n orientation?: Orientation;\n}\n\nexport interface ToolbarAria {\n /**\n * Props for the toolbar container.\n */\n toolbarProps: HTMLAttributes;\n}\n\n/**\n * Provides the behavior and accessibility implementation for a toolbar.\n * A toolbar is a container for a set of interactive controls with arrow key navigation.\n *\n * @param props - Props to be applied to the toolbar.\n * @param ref - A ref to a DOM element for the toolbar.\n */\nexport function createToolbar(\n props: AriaToolbarProps,\n ref: Accessor<HTMLElement | null>\n): ToolbarAria {\n const _result0 = props;\n const [isInToolbar, setInToolbar] = createSignal(false, { ownedWrite: true });\n // should be safe because re-calling set state with the same value it already has is a no-op\n // this will allow us to react should a parent re-render and change its role though\n\n createEffect(\n () => ({ element: ref() }),\n ({ element }) => {\n const refElement = element;\n setInToolbar(\n !!(\n refElement &&\n getParentElement(refElement)?.closest('[role=\"toolbar\"]')\n )\n );\n },\n { ssrSource: \"client\" }\n );\n const _result1 = createLocale();\n\n const shouldReverse = createMemo(\n () =>\n _result1.direction === \"rtl\" &&\n (_result0.orientation ?? \"horizontal\") === \"horizontal\"\n );\n\n const focusManager = createFocusManager(ref);\n\n let lastFocused: HTMLElement | null = null;\n\n const onKeyDown: KeyboardEventHandler = (e) => {\n // don't handle portalled events\n if (!nodeContains(e.currentTarget, getEventTarget(e))) {\n return;\n }\n\n let nextFocused: FocusableElement | null = null;\n\n if (\n ((_result0.orientation ?? \"horizontal\") === \"horizontal\" &&\n e.key === \"ArrowRight\") ||\n ((_result0.orientation ?? \"horizontal\") === \"vertical\" &&\n e.key === \"ArrowDown\")\n ) {\n nextFocused = shouldReverse()\n ? focusManager.focusPrevious()\n : focusManager.focusNext();\n } else if (\n ((_result0.orientation ?? \"horizontal\") === \"horizontal\" &&\n e.key === \"ArrowLeft\") ||\n ((_result0.orientation ?? \"horizontal\") === \"vertical\" &&\n e.key === \"ArrowUp\")\n ) {\n nextFocused = shouldReverse()\n ? focusManager.focusNext()\n : focusManager.focusPrevious();\n } else if (e.key === \"Tab\") {\n // When the tab key is pressed, we want to move focus\n // out of the entire toolbar. To do this, move focus\n // to the first or last focusable child, and let the\n // browser handle the Tab key as usual from there.\n lastFocused = htmlElementOrNull(getActiveElement());\n\n if (e.shiftKey) {\n focusManager.focusFirst();\n } else {\n focusManager.focusLast();\n }\n\n return;\n } else {\n // if we didn't handle anything, return early so we don't preventDefault\n return;\n }\n\n // Focusing an item that is only partially visible doesn't scroll it fully into view,\n // so scroll it manually (e.g. the last button in an overflowing toolbar).\n if (nextFocused) {\n scrollIntoViewport(nextFocused, { containingElement: ref() });\n }\n\n // Prevent arrow keys from being handled by nested action groups.\n e.stopPropagation();\n e.preventDefault();\n };\n\n // Record the last focused child when focus moves out of the toolbar.\n\n const onBlur: FocusEventHandler<HTMLElement> = (e) => {\n if (\n !nodeContains(\n e.currentTarget,\n e.relatedTarget instanceof Node ? e.relatedTarget : null\n ) &&\n !lastFocused\n ) {\n lastFocused = getEventTarget(e);\n }\n };\n\n // Restore focus to the last focused child when focus returns into the toolbar.\n // If the element was removed, do nothing, either the first item in the first group,\n // or the last item in the last group will be focused, depending on direction.\n const onFocus: FocusEventHandler<HTMLElement> = (e) => {\n if (\n lastFocused &&\n !nodeContains(\n e.currentTarget,\n e.relatedTarget instanceof Node ? e.relatedTarget : null\n ) &&\n nodeContains(ref(), getEventTarget(e))\n ) {\n lastFocused?.focus();\n lastFocused = null;\n }\n };\n\n createEvent(\n ref,\n \"blur\",\n (event) => {\n if (!isInToolbar()) {\n onBlur(event);\n }\n },\n { capture: true }\n );\n createEvent(\n ref,\n \"focus\",\n (event) => {\n if (!isInToolbar()) {\n onFocus(event);\n }\n },\n { capture: true }\n );\n createEvent(\n ref,\n \"keydown\",\n (event) => {\n if (!isInToolbar()) {\n onKeyDown(event);\n }\n },\n { capture: true }\n );\n\n return {\n get toolbarProps() {\n return merge(filterDOMProps(props, { labelable: true }), {\n get \"aria-label\"() {\n return ariaValue(ariaValue(_result0[\"aria-label\"]));\n },\n get \"aria-labelledby\"() {\n return ariaValue(\n ariaValue(\n isPresent(_result0[\"aria-label\"])\n ? undefined\n : _result0[\"aria-labelledby\"]\n )\n );\n },\n get \"aria-orientation\"() {\n return ariaValue(ariaValue(_result0.orientation ?? \"horizontal\"));\n },\n get role() {\n return isInToolbar() ? \"group\" : \"toolbar\";\n },\n });\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEA,SAAgB,cACd,OACA,KACa;CACb,MAAM,WAAW;CACjB,MAAM,CAAC,aAAa,gBAAgB,aAAa,OAAO,EAAE,YAAY,KAAK,CAAC;CAI5E,oBACS,EAAE,SAAS,IAAI,EAAE,KACvB,EAAE,cAAc;EACf,MAAM,aAAa;EACnB,aACE,CAAC,EACC,cACA,iBAAiB,UAAU,CAAC,EAAE,QAAQ,oBAAkB,EAE5D;CACF,GACA,EAAE,WAAW,SAAS,CACxB;CACA,MAAM,WAAW,aAAa;CAE9B,MAAM,gBAAgB,iBAElB,SAAS,cAAc,UACtB,SAAS,eAAe,kBAAkB,YAC/C;CAEA,MAAM,eAAe,mBAAmB,GAAG;CAE3C,IAAI,cAAkC;CAEtC,MAAM,aAAmC,MAAM;EAE7C,IAAI,CAAC,aAAa,EAAE,eAAe,eAAe,CAAC,CAAC,GAClD;EAGF,IAAI,cAAuC;EAE3C,KACI,SAAS,eAAe,kBAAkB,gBAC1C,EAAE,QAAQ,iBACV,SAAS,eAAe,kBAAkB,cAC1C,EAAE,QAAQ,aAEZ,cAAc,cAAc,IACxB,aAAa,cAAc,IAC3B,aAAa,UAAU;OACtB,KACH,SAAS,eAAe,kBAAkB,gBAC1C,EAAE,QAAQ,gBACV,SAAS,eAAe,kBAAkB,cAC1C,EAAE,QAAQ,WAEZ,cAAc,cAAc,IACxB,aAAa,UAAU,IACvB,aAAa,cAAc;OAC1B,IAAI,EAAE,QAAQ,OAAO;GAK1B,cAAc,kBAAkB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ACF"}
|
|
@@ -14,24 +14,10 @@
|
|
|
14
14
|
* Modified for Solid Aria: adapted hooks, reactive getters, DOM types, and imports for Solid 2.
|
|
15
15
|
* Licensed under Apache-2.0. See LICENSES/Apache-2.0.txt and NOTICE.txt at the repository root.
|
|
16
16
|
*/
|
|
17
|
+
import { isDocument, isNode, isShadowRoot } from "./type-helpers.js";
|
|
17
18
|
import { EventMapType } from "@solid2-aria/types-shared";
|
|
18
19
|
export declare const getOwnerDocument: (target?: EventTarget | null) => Document;
|
|
19
20
|
export declare const getOwnerWindow: (target?: EventTarget | null) => Window & typeof globalThis;
|
|
20
|
-
/**
|
|
21
|
-
* Type guard that checks if a value is a Node. Verifies the presence and type of the nodeType
|
|
22
|
-
* property.
|
|
23
|
-
*/
|
|
24
|
-
export declare function isNode<T>(value: T): value is T & Node;
|
|
25
|
-
/**
|
|
26
|
-
* Type guard that checks if a value is a Document. Uses nodeType and host property checks to
|
|
27
|
-
* distinguish Document from other values.
|
|
28
|
-
*/
|
|
29
|
-
export declare function isDocument<T>(value: T): value is T & Document;
|
|
30
|
-
/**
|
|
31
|
-
* Type guard that checks if a value is a ShadowRoot. Uses nodeType and host property checks to
|
|
32
|
-
* distinguish ShadowRoot from other values.
|
|
33
|
-
*/
|
|
34
|
-
export declare function isShadowRoot<T>(value: T): value is T & ShadowRoot;
|
|
35
21
|
/**
|
|
36
22
|
* Attaches an event listener on target(s) and returns a cleanup function.
|
|
37
23
|
*/
|
|
@@ -42,4 +28,5 @@ export declare function addEvent<T extends EventTarget, K extends keyof EventMap
|
|
|
42
28
|
* Sets a CSS property on an element and returns a cleanup function.
|
|
43
29
|
*/
|
|
44
30
|
export declare function setStyle(target: HTMLElement | HTMLElement[] | null, property: string, value: string, priority?: string): () => void;
|
|
31
|
+
export { isDocument, isNode, isShadowRoot };
|
|
45
32
|
//# sourceMappingURL=dom-helpers.d.ts.map
|
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
*/
|
|
17
17
|
import { isPresent } from "./is-present.js";
|
|
18
18
|
import { noop } from "./noop.js";
|
|
19
|
+
import { isDocument, isNode, isShadowRoot, isWindow } from "./type-helpers.js";
|
|
19
20
|
// src/utils/dom-helpers.ts
|
|
20
21
|
const getOwnerDocument = (target) => {
|
|
21
22
|
if (isWindow(target)) return target.document;
|
|
@@ -26,34 +27,6 @@ const getOwnerWindow = (target) => {
|
|
|
26
27
|
return getOwnerDocument(target)?.defaultView ?? (typeof window === "undefined" ? void 0 : window);
|
|
27
28
|
};
|
|
28
29
|
/**
|
|
29
|
-
* Type guard that checks if a value is a Node. Verifies the presence and type of the nodeType
|
|
30
|
-
* property.
|
|
31
|
-
*/
|
|
32
|
-
function isNode(value) {
|
|
33
|
-
return value !== null && typeof value === "object" && "nodeType" in value && typeof value.nodeType === "number";
|
|
34
|
-
}
|
|
35
|
-
/**
|
|
36
|
-
* Type guard that checks if a value is a Window. Uses window self reference checks to
|
|
37
|
-
* distinguish Window from other values.
|
|
38
|
-
*/
|
|
39
|
-
function isWindow(value) {
|
|
40
|
-
return typeof value === "object" && value !== null && value !== void 0 && "window" in value && value.window === value;
|
|
41
|
-
}
|
|
42
|
-
/**
|
|
43
|
-
* Type guard that checks if a value is a Document. Uses nodeType and host property checks to
|
|
44
|
-
* distinguish Document from other values.
|
|
45
|
-
*/
|
|
46
|
-
function isDocument(value) {
|
|
47
|
-
return isNode(value) && value.nodeType === 9;
|
|
48
|
-
}
|
|
49
|
-
/**
|
|
50
|
-
* Type guard that checks if a value is a ShadowRoot. Uses nodeType and host property checks to
|
|
51
|
-
* distinguish ShadowRoot from other values.
|
|
52
|
-
*/
|
|
53
|
-
function isShadowRoot(value) {
|
|
54
|
-
return isNode(value) && value.nodeType === 11 && "host" in value;
|
|
55
|
-
}
|
|
56
|
-
/**
|
|
57
30
|
* Attaches an event listener on target(s) and returns a cleanup function.
|
|
58
31
|
*/
|
|
59
32
|
function addEvent(target, event, listener, options) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dom-helpers.js","names":[],"sources":["../../../src/utils/dom-helpers.ts"],"sourcesContent":["/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n/*\n * Derived from Adobe React Spectrum: packages/react-aria/src/utils/domHelpers.ts.\n * Modified for Solid Aria: adapted hooks, reactive getters, DOM types, and imports for Solid 2.\n * Licensed under Apache-2.0. See LICENSES/Apache-2.0.txt and NOTICE.txt at the repository root.\n */\n\nimport type { EventMapType } from \"@solid2-aria/types-shared\";\n\nimport { isPresent } from \"./is-present\";\nimport { noop } from \"./noop\";\n\nexport const getOwnerDocument = (target?: EventTarget | null): Document => {\n if (isWindow(target)) {\n return target.document;\n }\n\n if (isDocument(target)) {\n return target;\n }\n\n // @ts-expect-error Ensure safe access in SSR environments.\n return (\n (isNode(target) ? target.ownerDocument : undefined) ??\n (typeof document === \"undefined\" ? undefined : document)\n );\n};\n\nexport const getOwnerWindow = (\n target?: EventTarget | null\n): Window & typeof globalThis => {\n const ownerDocument = getOwnerDocument(target);\n\n // @ts-expect-error Ensure safe access in SSR environments.\n return (\n ownerDocument?.defaultView ??\n (typeof window === \"undefined\" ? undefined : window)\n );\n};\n\n/**\n *
|
|
1
|
+
{"version":3,"file":"dom-helpers.js","names":[],"sources":["../../../src/utils/dom-helpers.ts"],"sourcesContent":["/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n/*\n * Derived from Adobe React Spectrum: packages/react-aria/src/utils/domHelpers.ts.\n * Modified for Solid Aria: adapted hooks, reactive getters, DOM types, and imports for Solid 2.\n * Licensed under Apache-2.0. See LICENSES/Apache-2.0.txt and NOTICE.txt at the repository root.\n */\n\nimport type { EventMapType } from \"@solid2-aria/types-shared\";\n\nimport { isPresent } from \"./is-present\";\nimport { noop } from \"./noop\";\nimport { isDocument, isNode, isWindow } from \"./type-helpers\";\n\nexport { isDocument, isNode, isShadowRoot } from \"./type-helpers\";\n\nexport const getOwnerDocument = (target?: EventTarget | null): Document => {\n if (isWindow(target)) {\n return target.document;\n }\n\n if (isDocument(target)) {\n return target;\n }\n\n // @ts-expect-error Ensure safe access in SSR environments.\n return (\n (isNode(target) ? target.ownerDocument : undefined) ??\n (typeof document === \"undefined\" ? undefined : document)\n );\n};\n\nexport const getOwnerWindow = (\n target?: EventTarget | null\n): Window & typeof globalThis => {\n const ownerDocument = getOwnerDocument(target);\n\n // @ts-expect-error Ensure safe access in SSR environments.\n return (\n ownerDocument?.defaultView ??\n (typeof window === \"undefined\" ? undefined : window)\n );\n};\n\n/**\n * Attaches an event listener on target(s) and returns a cleanup function.\n */\nexport function addEvent<\n T extends EventTarget,\n K extends keyof EventMapType<Exclude<T, null>>,\n>(\n target: T | EventTarget[] | null,\n event: Extract<K, string> | (string & Record<never, never>),\n listener?: (\n this: T,\n ev: EventMapType<Exclude<T, null>>[K] & { readonly currentTarget: T }\n ) => void,\n options?: boolean | AddEventListenerOptions\n): () => void {\n if (!isPresent(listener) || target === null || target === undefined) {\n return noop;\n }\n\n // SAFETY: The event-map overload relates the event name and callback before the native listener API erases them.\n // oxlint-disable-next-line anti-slop/no-chained-type-assertions, typescript/no-unsafe-type-assertion -- Native listeners receive the declared event type with the bound target as currentTarget.\n const nativeListener = listener as unknown as EventListener;\n const eventTargets = Array.isArray(target) ? target : [target];\n\n for (const eventTarget of eventTargets) {\n eventTarget.addEventListener(event, nativeListener, options);\n }\n\n return () => {\n for (const eventTarget of eventTargets) {\n eventTarget.removeEventListener(event, nativeListener, options);\n }\n };\n}\n\n/**\n * Sets a CSS property on an element and returns a cleanup function.\n */\nexport function setStyle(\n target: HTMLElement | HTMLElement[] | null,\n property: string,\n value: string,\n priority?: string\n): () => void {\n if (!isPresent(target)) {\n return noop;\n }\n\n const restore = new Array<() => void>();\n const styleTargets = Array.isArray(target) ? target : [target];\n\n for (const styleTarget of styleTargets) {\n const initialValue = styleTarget.style.getPropertyValue(property);\n const initialPriority = styleTarget.style.getPropertyPriority(property);\n styleTarget.style.setProperty(property, value, priority);\n restore.unshift(() => {\n if (initialValue) {\n styleTarget.style.setProperty(property, initialValue, initialPriority);\n } else {\n styleTarget.style.removeProperty(property);\n }\n });\n }\n\n return () => {\n for (const cleanup of restore) {\n cleanup();\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,oBAAoB,WAA0C;CACzE,IAAI,SAAS,MAAM,GACjB,OAAO,OAAO;CAGhB,IAAI,WAAW,MAAM,GACnB,OAAO;CAIT,QACG,OAAO,MAAM,IAAI,OAAO,gBAAgB,KAAA,OACxC,OAAO,aAAa,cAAc,KAAA,IAAY;AAEnD;AAEA,MAAa,kBACX,WAC+B;CAI/B,OAHsB,iBAAiB,MAIzB,CAAC,EAAE,gBACd,OAAO,WAAW,cAAc,KAAA,IAAY;AAEjD;;;;AAKA,SAAgB,SAId,QACA,OACA,UAIA,SACY;CACZ,IAAI,CAAC,UAAU,QAAQ,KAAK,WAAW,QAAQ,WAAW,KAAA,GACxD,OAAO;CAKT,MAAM,iBAAiB;CACvB,MAAM,eAAe,MAAM,QAAQ,MAAM,IAAI,SAAS,CAAC,MAAM;CAE7D,KAAK,MAAM,eAAe,cACxB,YAAY,iBAAiB,OAAO,gBAAgB,OAAO;CAG7D,aAAa;EACX,KAAK,MAAM,eAAe,cACxB,YAAY,oBAAoB,OAAO,gBAAgB,OAAO;CAElE;AACF;;;;AAKA,SAAgB,SACd,QACA,UACA,OACA,UACY;CACZ,IAAI,CAAC,UAAU,MAAM,GACnB,OAAO;CAGT,MAAM,UAAU,IAAI,MAAkB;CACtC,MAAM,eAAe,MAAM,QAAQ,MAAM,IAAI,SAAS,CAAC,MAAM;CAE7D,KAAK,MAAM,eAAe,cAAc;EACtC,MAAM,eAAe,YAAY,MAAM,iBAAiB,QAAQ;EAChE,MAAM,kBAAkB,YAAY,MAAM,oBAAoB,QAAQ;EACtE,YAAY,MAAM,YAAY,UAAU,OAAO,QAAQ;EACvD,QAAQ,cAAc;GACpB,IAAI,cACF,YAAY,MAAM,YAAY,UAAU,cAAc,eAAe;QAErE,YAAY,MAAM,eAAe,QAAQ;EAE7C,CAAC;CACH;CAEA,aAAa;EACX,KAAK,MAAM,WAAW,SACpB,QAAQ;CAEZ;AACF"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
|
|
2
2
|
import { isPresent } from "./is-present.js";
|
|
3
|
-
import {
|
|
3
|
+
import { isNode } from "./type-helpers.js";
|
|
4
|
+
import { getOwnerWindow } from "./dom-helpers.js";
|
|
4
5
|
// src/utils/dom-value.ts
|
|
5
6
|
function requireElement(value) {
|
|
6
7
|
if (!(value instanceof getOwnerWindow(isNode(value) ? value : null).Element)) throw new TypeError("Expected a DOM element");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dom-value.js","names":[],"sources":["../../../src/utils/dom-value.ts"],"sourcesContent":["import type { FocusableElement } from \"@solid2-aria/types-shared\";\n\nimport { getOwnerWindow
|
|
1
|
+
{"version":3,"file":"dom-value.js","names":[],"sources":["../../../src/utils/dom-value.ts"],"sourcesContent":["import type { FocusableElement } from \"@solid2-aria/types-shared\";\n\nimport { getOwnerWindow } from \"./dom-helpers\";\nimport { isPresent } from \"./is-present\";\nimport { isNode } from \"./type-helpers\";\n\nexport function requireElement(\n // oxlint-disable-next-line anti-slop/no-unknown-parameters -- Native and framework event targets are validated against their own DOM realm here.\n value: unknown\n): Element {\n if (\n !(value instanceof getOwnerWindow(isNode(value) ? value : null).Element)\n ) {\n throw new TypeError(\"Expected a DOM element\");\n }\n\n return value;\n}\n\nexport function requireHTMLElement(\n // oxlint-disable-next-line anti-slop/no-unknown-parameters -- Native and framework event targets are validated against their own DOM realm here.\n value: unknown\n): HTMLElement {\n if (\n !(value instanceof getOwnerWindow(isNode(value) ? value : null).HTMLElement)\n ) {\n throw new TypeError(\"Expected an HTML element\");\n }\n\n return value;\n}\n\nexport function requireFocusableElement(\n // oxlint-disable-next-line anti-slop/no-unknown-parameters -- Native and framework event targets are validated against their own DOM realm here.\n value: unknown\n): FocusableElement {\n const owner = getOwnerWindow(isNode(value) ? value : null);\n\n if (\n !(value instanceof owner.HTMLElement) &&\n !(value instanceof owner.SVGElement)\n ) {\n throw new TypeError(\"Expected an HTML or SVG element\");\n }\n\n return value;\n}\n\nexport function requireHTMLInputElement(\n // oxlint-disable-next-line anti-slop/no-unknown-parameters -- Native and framework event targets are validated against their own DOM realm here.\n value: unknown\n): HTMLInputElement {\n if (\n !(\n value instanceof\n getOwnerWindow(isNode(value) ? value : null).HTMLInputElement\n )\n ) {\n throw new TypeError(\"Expected an input element\");\n }\n\n return value;\n}\n\nexport function elementOrNull(\n value: EventTarget | null | undefined\n): Element | null {\n return isPresent(value) ? requireElement(value) : null;\n}\n\nexport function htmlElementOrNull(\n value: EventTarget | null | undefined\n): HTMLElement | null {\n return isPresent(value) ? requireHTMLElement(value) : null;\n}\n\nexport function focusableElementOrNull(\n value: EventTarget | null | undefined\n): FocusableElement | null {\n return isPresent(value) ? requireFocusableElement(value) : null;\n}\n"],"mappings":";;;;;AAMA,SAAgB,eAEd,OACS;CACT,IACE,EAAE,iBAAiB,eAAe,OAAO,KAAK,IAAI,QAAQ,IAAI,CAAC,CAAC,UAEhE,MAAM,IAAI,UAAU,wBAAwB;CAG9C,OAAO;AACT;AAEA,SAAgB,mBAEd,OACa;CACb,IACE,EAAE,iBAAiB,eAAe,OAAO,KAAK,IAAI,QAAQ,IAAI,CAAC,CAAC,cAEhE,MAAM,IAAI,UAAU,0BAA0B;CAGhD,OAAO;AACT;AAEA,SAAgB,wBAEd,OACkB;CAClB,MAAM,QAAQ,eAAe,OAAO,KAAK,IAAI,QAAQ,IAAI;CAEzD,IACE,EAAE,iBAAiB,MAAM,gBACzB,EAAE,iBAAiB,MAAM,aAEzB,MAAM,IAAI,UAAU,iCAAiC;CAGvD,OAAO;AACT;AAEA,SAAgB,wBAEd,OACkB;CAClB,IACE,EACE,iBACA,eAAe,OAAO,KAAK,IAAI,QAAQ,IAAI,CAAC,CAAC,mBAG/C,MAAM,IAAI,UAAU,2BAA2B;CAGjD,OAAO;AACT;AAEA,SAAgB,cACd,OACgB;CAChB,OAAO,UAAU,KAAK,IAAI,eAAe,KAAK,IAAI;AACpD;AAEA,SAAgB,kBACd,OACoB;CACpB,OAAO,UAAU,KAAK,IAAI,mBAAmB,KAAK,IAAI;AACxD;AAEA,SAAgB,uBACd,OACyB;CACzB,OAAO,UAAU,KAAK,IAAI,wBAAwB,KAAK,IAAI;AAC7D"}
|
|
@@ -15,12 +15,13 @@
|
|
|
15
15
|
* Licensed under Apache-2.0. See LICENSES/Apache-2.0.txt and NOTICE.txt at the repository root.
|
|
16
16
|
*/
|
|
17
17
|
import { getTruthyValue } from "./truthy.js";
|
|
18
|
+
import { getParentElement } from "./shadowdom/dom-functions.js";
|
|
18
19
|
import { isScrollable } from "./is-scrollable.js";
|
|
19
20
|
// src/utils/get-scroll-parent.ts
|
|
20
21
|
function getScrollParent(node, checkForOverflow) {
|
|
21
22
|
let scrollableNode = node;
|
|
22
|
-
if (isScrollable(scrollableNode, checkForOverflow)) scrollableNode = scrollableNode
|
|
23
|
-
while (scrollableNode && !isScrollable(scrollableNode, checkForOverflow)) scrollableNode = scrollableNode
|
|
23
|
+
if (isScrollable(scrollableNode, checkForOverflow)) scrollableNode = getParentElement(scrollableNode);
|
|
24
|
+
while (scrollableNode && !isScrollable(scrollableNode, checkForOverflow)) scrollableNode = getParentElement(scrollableNode);
|
|
24
25
|
return getTruthyValue(scrollableNode ?? document.scrollingElement) ?? document.documentElement;
|
|
25
26
|
}
|
|
26
27
|
export { getScrollParent };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"get-scroll-parent.js","names":[],"sources":["../../../src/utils/get-scroll-parent.ts"],"sourcesContent":["/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n/*\n * Derived from Adobe React Spectrum: packages/react-aria/src/utils/getScrollParent.ts.\n * Modified for Solid Aria: adapted hooks, reactive getters, DOM types, and imports for Solid 2.\n * Licensed under Apache-2.0. See LICENSES/Apache-2.0.txt and NOTICE.txt at the repository root.\n */\n\nimport { isScrollable } from \"./is-scrollable\";\nimport { getTruthyValue } from \"./truthy\";\n\nexport function getScrollParent(\n node: Element,\n checkForOverflow?: boolean\n): Element {\n let scrollableNode: Element | null = node;\n\n if (isScrollable(scrollableNode, checkForOverflow)) {\n scrollableNode = scrollableNode
|
|
1
|
+
{"version":3,"file":"get-scroll-parent.js","names":[],"sources":["../../../src/utils/get-scroll-parent.ts"],"sourcesContent":["/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n/*\n * Derived from Adobe React Spectrum: packages/react-aria/src/utils/getScrollParent.ts.\n * Modified for Solid Aria: adapted hooks, reactive getters, DOM types, and imports for Solid 2.\n * Licensed under Apache-2.0. See LICENSES/Apache-2.0.txt and NOTICE.txt at the repository root.\n */\n\nimport { isScrollable } from \"./is-scrollable\";\nimport { getParentElement } from \"./shadowdom/dom-functions\";\nimport { getTruthyValue } from \"./truthy\";\n\nexport function getScrollParent(\n node: Element,\n checkForOverflow?: boolean\n): Element {\n let scrollableNode: Element | null = node;\n\n if (isScrollable(scrollableNode, checkForOverflow)) {\n scrollableNode = getParentElement(scrollableNode);\n }\n\n while (scrollableNode && !isScrollable(scrollableNode, checkForOverflow)) {\n scrollableNode = getParentElement(scrollableNode);\n }\n\n return (\n getTruthyValue(scrollableNode ?? document.scrollingElement) ??\n document.documentElement\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,gBACd,MACA,kBACS;CACT,IAAI,iBAAiC;CAErC,IAAI,aAAa,gBAAgB,gBAAgB,GAC/C,iBAAiB,iBAAiB,cAAc;CAGlD,OAAO,kBAAkB,CAAC,aAAa,gBAAgB,gBAAgB,GACrE,iBAAiB,iBAAiB,cAAc;CAGlD,OACE,eAAe,kBAAkB,SAAS,gBAAgB,KAC1D,SAAS;AAEb"}
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
* Licensed under Apache-2.0. See LICENSES/Apache-2.0.txt and NOTICE.txt at the repository root.
|
|
16
16
|
*/
|
|
17
17
|
import { getTruthyValue, isTruthy } from "./truthy.js";
|
|
18
|
+
import { getParentElement } from "./shadowdom/dom-functions.js";
|
|
18
19
|
import { isScrollable } from "./is-scrollable.js";
|
|
19
20
|
// src/utils/get-scroll-parents.ts
|
|
20
21
|
function getScrollParents(node, checkForOverflow) {
|
|
@@ -24,7 +25,7 @@ function getScrollParents(node, checkForOverflow) {
|
|
|
24
25
|
while (isTruthy(currentNode)) {
|
|
25
26
|
if (isScrollable(currentNode, checkForOverflow)) parentElements.push(currentNode);
|
|
26
27
|
if (currentNode === root) break;
|
|
27
|
-
currentNode = currentNode
|
|
28
|
+
currentNode = getParentElement(currentNode);
|
|
28
29
|
}
|
|
29
30
|
return parentElements;
|
|
30
31
|
}
|