smarthr-ui 99.7.0 → 99.7.1

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.
Files changed (55) hide show
  1. package/lib/components/Checkbox/client/ActualCheckbox.cjs +2 -1
  2. package/lib/components/Checkbox/client/ActualCheckbox.cjs.map +1 -1
  3. package/lib/components/Checkbox/client/ActualCheckbox.js +2 -1
  4. package/lib/components/Checkbox/client/ActualCheckbox.js.map +1 -1
  5. package/lib/components/Combobox/MultiCombobox/MultiCombobox.cjs +2 -1
  6. package/lib/components/Combobox/MultiCombobox/MultiCombobox.cjs.map +1 -1
  7. package/lib/components/Combobox/MultiCombobox/MultiCombobox.js +2 -1
  8. package/lib/components/Combobox/MultiCombobox/MultiCombobox.js.map +1 -1
  9. package/lib/components/DropZone/client/DropZone.cjs +2 -1
  10. package/lib/components/DropZone/client/DropZone.cjs.map +1 -1
  11. package/lib/components/DropZone/client/DropZone.js +2 -1
  12. package/lib/components/DropZone/client/DropZone.js.map +1 -1
  13. package/lib/components/FormGroup/client/FormGroup.cjs +6 -1
  14. package/lib/components/FormGroup/client/FormGroup.cjs.map +1 -1
  15. package/lib/components/FormGroup/client/FormGroup.js +7 -2
  16. package/lib/components/FormGroup/client/FormGroup.js.map +1 -1
  17. package/lib/components/FormGroup/client/constants.cjs +2 -0
  18. package/lib/components/FormGroup/client/constants.cjs.map +1 -1
  19. package/lib/components/FormGroup/client/constants.d.ts +1 -0
  20. package/lib/components/FormGroup/client/constants.js +2 -1
  21. package/lib/components/FormGroup/client/constants.js.map +1 -1
  22. package/lib/components/Input/client/Input.cjs +2 -1
  23. package/lib/components/Input/client/Input.cjs.map +1 -1
  24. package/lib/components/Input/client/Input.js +2 -1
  25. package/lib/components/Input/client/Input.js.map +1 -1
  26. package/lib/components/InputFile/client/InputFileMultiplyAppendable.cjs +2 -1
  27. package/lib/components/InputFile/client/InputFileMultiplyAppendable.cjs.map +1 -1
  28. package/lib/components/InputFile/client/InputFileMultiplyAppendable.js +2 -1
  29. package/lib/components/InputFile/client/InputFileMultiplyAppendable.js.map +1 -1
  30. package/lib/components/InputFile/client/InputFileNative.cjs +2 -1
  31. package/lib/components/InputFile/client/InputFileNative.cjs.map +1 -1
  32. package/lib/components/InputFile/client/InputFileNative.js +2 -1
  33. package/lib/components/InputFile/client/InputFileNative.js.map +1 -1
  34. package/lib/components/Picker/DatetimeLocalPicker.cjs +2 -1
  35. package/lib/components/Picker/DatetimeLocalPicker.cjs.map +1 -1
  36. package/lib/components/Picker/DatetimeLocalPicker.js +2 -1
  37. package/lib/components/Picker/DatetimeLocalPicker.js.map +1 -1
  38. package/lib/components/Picker/MonthPicker.cjs +2 -1
  39. package/lib/components/Picker/MonthPicker.cjs.map +1 -1
  40. package/lib/components/Picker/MonthPicker.js +2 -1
  41. package/lib/components/Picker/MonthPicker.js.map +1 -1
  42. package/lib/components/Picker/TimePicker.cjs +2 -1
  43. package/lib/components/Picker/TimePicker.cjs.map +1 -1
  44. package/lib/components/Picker/TimePicker.js +2 -1
  45. package/lib/components/Picker/TimePicker.js.map +1 -1
  46. package/lib/components/Select/client/ActualSelect.cjs +20 -17
  47. package/lib/components/Select/client/ActualSelect.cjs.map +1 -1
  48. package/lib/components/Select/client/ActualSelect.js +20 -17
  49. package/lib/components/Select/client/ActualSelect.js.map +1 -1
  50. package/lib/components/Textarea/client/Textarea.cjs +2 -1
  51. package/lib/components/Textarea/client/Textarea.cjs.map +1 -1
  52. package/lib/components/Textarea/client/Textarea.js +2 -1
  53. package/lib/components/Textarea/client/Textarea.js.map +1 -1
  54. package/metadata.json +1 -1
  55. package/package.json +1 -1
@@ -28,7 +28,8 @@ const ActualCheckbox = ({ checkboxRef, checked, mixed, error, ...rest }) => {
28
28
  // HINT: useMergeRefsはv18でもcallbackRefのcleanup関数に対応している
29
29
  // もしuseMergeRefsをなくす場合、react v18対応が不要になっているかどうか確認する
30
30
  const mergedRef = hooks_client_useMergeRefs_useMergeRefs.useMergeRefs(callbackRef, checkboxRef);
31
- return (jsxRuntime.jsx("input", { ...rest, ref: mergedRef, type: "checkbox", checked: checked, "aria-invalid": error || undefined, "data-smarthr-ui-input": "true", "data-checked": checked || undefined, "data-mixed": mixed || undefined }));
31
+ const errorAttr = error || undefined;
32
+ return (jsxRuntime.jsx("input", { ...rest, ref: mergedRef, type: "checkbox", checked: checked, "aria-invalid": errorAttr, "data-smarthr-ui-input-error": errorAttr, "data-smarthr-ui-input": "true", "data-checked": checked || undefined, "data-mixed": mixed || undefined }));
32
33
  };
33
34
 
34
35
  exports.ActualCheckbox = ActualCheckbox;
@@ -1 +1 @@
1
- {"version":3,"file":"ActualCheckbox.cjs","sources":["../../../../src/components/Checkbox/client/ActualCheckbox.tsx"],"sourcesContent":["'use client'\n\nimport { useMergeRefs } from '../../../hooks/client/useMergeRefs'\n\nimport type { ComponentPropsWithoutRef, FC, Ref } from 'react'\n\nexport type Props = ComponentPropsWithoutRef<'input'> & {\n checkboxRef?: Ref<HTMLInputElement>\n /** `true` のとき、チェック状態を `mixed` にする */\n mixed?: boolean\n /** チェックボックスにエラーがあるかどうか */\n error?: boolean\n}\n\nconst callbackRef = (node: HTMLInputElement | null) => {\n if (!node) {\n return\n }\n\n // checkedはcontrolled propとしてinput.checkedプロパティにのみ反映され、\n // HTML属性としては反映されないため、data-checked属性で代替判定する\n const action = () => {\n node.indeterminate =\n node.getAttribute('data-checked') === 'true' && node.getAttribute('data-mixed') === 'true'\n }\n\n action()\n\n const observer = new MutationObserver(action)\n\n observer.observe(node, {\n attributes: true,\n attributeFilter: ['data-checked', 'data-mixed'],\n })\n\n return () => {\n observer.disconnect()\n }\n}\n\nexport const ActualCheckbox: FC<Props> = ({ checkboxRef, checked, mixed, error, ...rest }) => {\n // HINT: useMergeRefsはv18でもcallbackRefのcleanup関数に対応している\n // もしuseMergeRefsをなくす場合、react v18対応が不要になっているかどうか確認する\n const mergedRef = useMergeRefs(callbackRef, checkboxRef)\n\n return (\n <input\n {...rest}\n ref={mergedRef}\n type=\"checkbox\"\n checked={checked}\n aria-invalid={error || undefined}\n data-smarthr-ui-input=\"true\"\n // checkedはDOM属性ではなくプロパティとしてのみ反映されるため、data-checkedをMutationObserverで監視\n data-checked={checked || undefined}\n data-mixed={mixed || undefined}\n />\n )\n}\n"],"names":[],"mappings":";;;;;;AAcA;;;;;;;AAQI;AACE;AACJ;AAEA;AAEA;AAEA;AACE;AACA;AACD;AAED;;AAEA;AACF;AAEO;;;;AAKL;AAaF;;"}
1
+ {"version":3,"file":"ActualCheckbox.cjs","sources":["../../../../src/components/Checkbox/client/ActualCheckbox.tsx"],"sourcesContent":["'use client'\n\nimport { useMergeRefs } from '../../../hooks/client/useMergeRefs'\n\nimport type { ComponentPropsWithoutRef, FC, Ref } from 'react'\n\nexport type Props = ComponentPropsWithoutRef<'input'> & {\n checkboxRef?: Ref<HTMLInputElement>\n /** `true` のとき、チェック状態を `mixed` にする */\n mixed?: boolean\n /** チェックボックスにエラーがあるかどうか */\n error?: boolean\n}\n\nconst callbackRef = (node: HTMLInputElement | null) => {\n if (!node) {\n return\n }\n\n // checkedはcontrolled propとしてinput.checkedプロパティにのみ反映され、\n // HTML属性としては反映されないため、data-checked属性で代替判定する\n const action = () => {\n node.indeterminate =\n node.getAttribute('data-checked') === 'true' && node.getAttribute('data-mixed') === 'true'\n }\n\n action()\n\n const observer = new MutationObserver(action)\n\n observer.observe(node, {\n attributes: true,\n attributeFilter: ['data-checked', 'data-mixed'],\n })\n\n return () => {\n observer.disconnect()\n }\n}\n\nexport const ActualCheckbox: FC<Props> = ({ checkboxRef, checked, mixed, error, ...rest }) => {\n // HINT: useMergeRefsはv18でもcallbackRefのcleanup関数に対応している\n // もしuseMergeRefsをなくす場合、react v18対応が不要になっているかどうか確認する\n const mergedRef = useMergeRefs(callbackRef, checkboxRef)\n const errorAttr = error || undefined\n\n return (\n <input\n {...rest}\n ref={mergedRef}\n type=\"checkbox\"\n checked={checked}\n aria-invalid={errorAttr}\n data-smarthr-ui-input-error={errorAttr}\n data-smarthr-ui-input=\"true\"\n // checkedはDOM属性ではなくプロパティとしてのみ反映されるため、data-checkedをMutationObserverで監視\n data-checked={checked || undefined}\n data-mixed={mixed || undefined}\n />\n )\n}\n"],"names":[],"mappings":";;;;;;AAcA;;;;;;;AAQI;AACE;AACJ;AAEA;AAEA;AAEA;AACE;AACA;AACD;AAED;;AAEA;AACF;AAEO;;;;AAIL;AAEA;AAcF;;"}
@@ -26,7 +26,8 @@ const ActualCheckbox = ({ checkboxRef, checked, mixed, error, ...rest }) => {
26
26
  // HINT: useMergeRefsはv18でもcallbackRefのcleanup関数に対応している
27
27
  // もしuseMergeRefsをなくす場合、react v18対応が不要になっているかどうか確認する
28
28
  const mergedRef = useMergeRefs(callbackRef, checkboxRef);
29
- return (jsx("input", { ...rest, ref: mergedRef, type: "checkbox", checked: checked, "aria-invalid": error || undefined, "data-smarthr-ui-input": "true", "data-checked": checked || undefined, "data-mixed": mixed || undefined }));
29
+ const errorAttr = error || undefined;
30
+ return (jsx("input", { ...rest, ref: mergedRef, type: "checkbox", checked: checked, "aria-invalid": errorAttr, "data-smarthr-ui-input-error": errorAttr, "data-smarthr-ui-input": "true", "data-checked": checked || undefined, "data-mixed": mixed || undefined }));
30
31
  };
31
32
 
32
33
  export { ActualCheckbox };
@@ -1 +1 @@
1
- {"version":3,"file":"ActualCheckbox.js","sources":["../../../../src/components/Checkbox/client/ActualCheckbox.tsx"],"sourcesContent":["'use client'\n\nimport { useMergeRefs } from '../../../hooks/client/useMergeRefs'\n\nimport type { ComponentPropsWithoutRef, FC, Ref } from 'react'\n\nexport type Props = ComponentPropsWithoutRef<'input'> & {\n checkboxRef?: Ref<HTMLInputElement>\n /** `true` のとき、チェック状態を `mixed` にする */\n mixed?: boolean\n /** チェックボックスにエラーがあるかどうか */\n error?: boolean\n}\n\nconst callbackRef = (node: HTMLInputElement | null) => {\n if (!node) {\n return\n }\n\n // checkedはcontrolled propとしてinput.checkedプロパティにのみ反映され、\n // HTML属性としては反映されないため、data-checked属性で代替判定する\n const action = () => {\n node.indeterminate =\n node.getAttribute('data-checked') === 'true' && node.getAttribute('data-mixed') === 'true'\n }\n\n action()\n\n const observer = new MutationObserver(action)\n\n observer.observe(node, {\n attributes: true,\n attributeFilter: ['data-checked', 'data-mixed'],\n })\n\n return () => {\n observer.disconnect()\n }\n}\n\nexport const ActualCheckbox: FC<Props> = ({ checkboxRef, checked, mixed, error, ...rest }) => {\n // HINT: useMergeRefsはv18でもcallbackRefのcleanup関数に対応している\n // もしuseMergeRefsをなくす場合、react v18対応が不要になっているかどうか確認する\n const mergedRef = useMergeRefs(callbackRef, checkboxRef)\n\n return (\n <input\n {...rest}\n ref={mergedRef}\n type=\"checkbox\"\n checked={checked}\n aria-invalid={error || undefined}\n data-smarthr-ui-input=\"true\"\n // checkedはDOM属性ではなくプロパティとしてのみ反映されるため、data-checkedをMutationObserverで監視\n data-checked={checked || undefined}\n data-mixed={mixed || undefined}\n />\n )\n}\n"],"names":[],"mappings":";;;;AAcA;;;;;;;AAQI;AACE;AACJ;AAEA;AAEA;AAEA;AACE;AACA;AACD;AAED;;AAEA;AACF;AAEO;;;;AAKL;AAaF;;"}
1
+ {"version":3,"file":"ActualCheckbox.js","sources":["../../../../src/components/Checkbox/client/ActualCheckbox.tsx"],"sourcesContent":["'use client'\n\nimport { useMergeRefs } from '../../../hooks/client/useMergeRefs'\n\nimport type { ComponentPropsWithoutRef, FC, Ref } from 'react'\n\nexport type Props = ComponentPropsWithoutRef<'input'> & {\n checkboxRef?: Ref<HTMLInputElement>\n /** `true` のとき、チェック状態を `mixed` にする */\n mixed?: boolean\n /** チェックボックスにエラーがあるかどうか */\n error?: boolean\n}\n\nconst callbackRef = (node: HTMLInputElement | null) => {\n if (!node) {\n return\n }\n\n // checkedはcontrolled propとしてinput.checkedプロパティにのみ反映され、\n // HTML属性としては反映されないため、data-checked属性で代替判定する\n const action = () => {\n node.indeterminate =\n node.getAttribute('data-checked') === 'true' && node.getAttribute('data-mixed') === 'true'\n }\n\n action()\n\n const observer = new MutationObserver(action)\n\n observer.observe(node, {\n attributes: true,\n attributeFilter: ['data-checked', 'data-mixed'],\n })\n\n return () => {\n observer.disconnect()\n }\n}\n\nexport const ActualCheckbox: FC<Props> = ({ checkboxRef, checked, mixed, error, ...rest }) => {\n // HINT: useMergeRefsはv18でもcallbackRefのcleanup関数に対応している\n // もしuseMergeRefsをなくす場合、react v18対応が不要になっているかどうか確認する\n const mergedRef = useMergeRefs(callbackRef, checkboxRef)\n const errorAttr = error || undefined\n\n return (\n <input\n {...rest}\n ref={mergedRef}\n type=\"checkbox\"\n checked={checked}\n aria-invalid={errorAttr}\n data-smarthr-ui-input-error={errorAttr}\n data-smarthr-ui-input=\"true\"\n // checkedはDOM属性ではなくプロパティとしてのみ反映されるため、data-checkedをMutationObserverで監視\n data-checked={checked || undefined}\n data-mixed={mixed || undefined}\n />\n )\n}\n"],"names":[],"mappings":";;;;AAcA;;;;;;;AAQI;AACE;AACJ;AAEA;AAEA;AAEA;AACE;AACA;AACD;AAED;;AAEA;AACF;AAEO;;;;AAIL;AAEA;AAcF;;"}
@@ -348,12 +348,13 @@ const ActualMultiCombobox = ({ items, selectedItems, name, disabled = false, req
348
348
  defaultText: '選択済みアイテム',
349
349
  },
350
350
  });
351
+ const errorAttr = error || undefined;
351
352
  return (
352
353
  // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions
353
354
  jsxRuntime.jsxs("div", { ref: mergedTriggerRef, role: "group", className: classNames.wrapper, style: {
354
355
  ...style,
355
356
  width: typeof width === 'number' ? `${width}px` : width,
356
- }, onClick: functions.handleDelegateClick, onKeyDown: functions.handleDelegateKeyDown, onKeyPress: functions.handleDelegateKeyPress, children: [jsxRuntime.jsxs(components_Scroller_client_Scroller.Scroller, { className: classNames.inputArea, children: [jsxRuntime.jsx("ul", { id: selectedListId, className: classNames.selectedList, "aria-label": localized.selectedListAriaLabel, children: selectedItems.map((selectedItem) => (jsxRuntime.jsx("li", { children: jsxRuntime.jsx(components_Combobox_MultiCombobox_MultiSelectedItem.MultiSelectedItem, { disabled: disabled, item: selectedItem, enableEllipsis: selectedItemEllipsis, handleDelete: functions.handleDelete }) }, `${selectedItem.label}-${index$1(selectedItem.value)}`))) }), jsxRuntime.jsx("div", { className: classNames.inputWrapper, children: jsxRuntime.jsx("input", { ...rest, ref: mergedInputRef, role: "combobox", type: "text", name: name, required: required && selectedItems.length === 0, disabled: disabled, value: inputValue, autoComplete: autoComplete ?? 'off', tabIndex: 0, className: classNames.input, "aria-activedescendant": activeOption?.id, "aria-controls": `${listBoxId} ${selectedListId}`, "aria-haspopup": "listbox", "aria-expanded": isExpanded, "aria-invalid": error || undefined, "aria-disabled": disabled, "aria-autocomplete": "list", "data-smarthr-ui-input": "true", onChange: functions.handleChangeInput, onFocus: functions.handleFocusInput, onCompositionStart: functions.handleCompositionStart, onCompositionEnd: functions.handleCompositionEnd, onKeyDown: functions.handleKeyDownInput }) }), selectedItems.length === 0 && placeholder && !isExpanded && (jsxRuntime.jsx("p", { className: classNames.placeholder, children: placeholder }))] }), jsxRuntime.jsx(MemoizedCaretDown, { disabled: disabled, isExpanded: isExpanded, classNames: classNames }), jsxRuntime.jsx(components_Combobox_useListbox.ListBox, { ...listBoxProps, callbackRef: listBoxCallbackRef })] }));
357
+ }, onClick: functions.handleDelegateClick, onKeyDown: functions.handleDelegateKeyDown, onKeyPress: functions.handleDelegateKeyPress, children: [jsxRuntime.jsxs(components_Scroller_client_Scroller.Scroller, { className: classNames.inputArea, children: [jsxRuntime.jsx("ul", { id: selectedListId, className: classNames.selectedList, "aria-label": localized.selectedListAriaLabel, children: selectedItems.map((selectedItem) => (jsxRuntime.jsx("li", { children: jsxRuntime.jsx(components_Combobox_MultiCombobox_MultiSelectedItem.MultiSelectedItem, { disabled: disabled, item: selectedItem, enableEllipsis: selectedItemEllipsis, handleDelete: functions.handleDelete }) }, `${selectedItem.label}-${index$1(selectedItem.value)}`))) }), jsxRuntime.jsx("div", { className: classNames.inputWrapper, children: jsxRuntime.jsx("input", { ...rest, ref: mergedInputRef, role: "combobox", type: "text", name: name, required: required && selectedItems.length === 0, disabled: disabled, value: inputValue, autoComplete: autoComplete ?? 'off', tabIndex: 0, className: classNames.input, "aria-activedescendant": activeOption?.id, "aria-controls": `${listBoxId} ${selectedListId}`, "aria-haspopup": "listbox", "aria-expanded": isExpanded, "aria-invalid": errorAttr, "aria-disabled": disabled, "aria-autocomplete": "list", "data-smarthr-ui-input-error": errorAttr, "data-smarthr-ui-input": "true", onChange: functions.handleChangeInput, onFocus: functions.handleFocusInput, onCompositionStart: functions.handleCompositionStart, onCompositionEnd: functions.handleCompositionEnd, onKeyDown: functions.handleKeyDownInput }) }), selectedItems.length === 0 && placeholder && !isExpanded && (jsxRuntime.jsx("p", { className: classNames.placeholder, children: placeholder }))] }), jsxRuntime.jsx(MemoizedCaretDown, { disabled: disabled, isExpanded: isExpanded, classNames: classNames }), jsxRuntime.jsx(components_Combobox_useListbox.ListBox, { ...listBoxProps, callbackRef: listBoxCallbackRef })] }));
357
358
  };
358
359
  const MultiCombobox = libs_util.genericsForwardRef(ActualMultiCombobox);
359
360
  const MemoizedCaretDown = React.memo(({ disabled, isExpanded, classNames }) => {
@@ -1 +1 @@
1
- {"version":3,"file":"MultiCombobox.cjs","sources":["../../../../src/components/Combobox/MultiCombobox/MultiCombobox.tsx"],"sourcesContent":["'use client'\n\nimport {\n type ChangeEvent,\n type ComponentPropsWithoutRef,\n type KeyboardEvent,\n type MouseEvent,\n type ReactNode,\n type Ref,\n memo,\n useEffect,\n useId,\n useMemo,\n useRef,\n useState,\n} from 'react'\nimport innerText from 'react-innertext'\nimport { tv } from 'tailwind-variants'\n\nimport { useAnimationFrame } from '../../../hooks/client/useAnimationFrame'\nimport { useAreaClickCallbackRef } from '../../../hooks/client/useAreaClickCallbackRef'\nimport { useMergeRefs } from '../../../hooks/client/useMergeRefs'\nimport { useTheme } from '../../../hooks/client/useTheme'\nimport { useLatest } from '../../../hooks/useLatest'\nimport { useLocalize } from '../../../intl'\nimport { findDelegateTarget } from '../../../libs/delegate'\nimport { genericsForwardRef } from '../../../libs/util'\nimport { FaCaretDownIcon } from '../../Icon'\nimport { Scroller } from '../../Scroller'\nimport { areItemsEqual } from '../helper'\nimport { ListBox, useListbox } from '../useListbox'\nimport { useMultiOptions } from '../useOptions'\n\nimport { DELETE_BUTTON_SELECTOR, MultiSelectedItem } from './MultiSelectedItem'\n\nimport type { ComboboxItem, BaseProps as ComboboxProps } from '../types'\n\ntype BaseProps<T> = ComboboxProps<T> & {\n /**\n * 選択されているアイテムのリスト\n */\n selectedItems: Array<ComboboxItem<T> & { deletable?: boolean }>\n /**\n * 選択されているアイテムのラベルを省略表示するかどうか\n */\n selectedItemEllipsis?: boolean\n /**\n * テキストボックスの `value` 属性の値。\n * `onChangeInput` と併せて設定することで、テキストボックスの挙動が制御可能になる。\n */\n inputValue?: string\n /**\n * 選択されているアイテムの削除ボタンがクリックされた時に発火するコールバック関数\n */\n onDelete?: (item: ComboboxItem<T>) => void\n /**\n * 選択されているアイテムのリストが変わった時に発火するコールバック関数\n */\n onChangeSelected?: (selectedItems: Array<ComboboxItem<T>>) => void\n /**\n * コンポーネントがフォーカスされたときに発火するコールバック関数\n */\n onFocus?: () => void\n /**\n * コンポーネントからフォーカスが外れた時に発火するコールバック関数\n */\n onBlur?: () => void\n /**\n * アイテムが選択されたときに選択済みかどうかを判定するコールバック関数/\n */\n isItemSelected?: (targetItem: ComboboxItem<T>, selectedItems: Array<ComboboxItem<T>>) => boolean\n /**\n * 検索結果が0件の時に表示するコンテンツ\n */\n noResultText?: ReactNode\n}\ntype Props<T> = BaseProps<T> & Omit<ComponentPropsWithoutRef<'input'>, keyof BaseProps<unknown>>\n\nconst NOOP = () => undefined\n\nconst preventDefaultWithPressEnter = (e: KeyboardEvent<HTMLInputElement>) => {\n if (e.key === 'Enter') {\n e.preventDefault()\n }\n}\n\nconst ESCAPE_KEY_REGEX = /^Esc(ape)?$/\nconst ARROW_LEFT_KEY_REGEX = /^(Arrow)?Left$/\nconst ARROW_RIGHT_KEY_REGEX = /^(Arrow)?Right/\nconst ARROW_UP_AND_DOWN_KEY_REGEX = /^(Arrow)?(Up|Down)$/\n\nconst EMPTY_INPUT_CHANGE_EVENT = {\n currentTarget: { value: '' },\n target: { value: '' },\n} as ChangeEvent<HTMLInputElement>\n\nconst DELETE_BUTTON_CLASSNAME = `.${DELETE_BUTTON_SELECTOR}`\n\nconst classNameGenerator = tv({\n slots: {\n wrapper: [\n 'smarthr-ui-MultiCombobox',\n 'shr-box-border shr-inline-flex shr-min-w-[15em] shr-rounded-m shr-border shr-border-solid shr-px-0.5 shr-py-0.25 shr-align-bottom',\n 'contrast-more:shr-border-high-contrast',\n 'has-[[role=combobox][aria-expanded=true]]:shr-focus-indicator',\n 'shr-cursor-text shr-border-default shr-bg-white',\n 'has-[[role=combobox]:disabled]:shr-cursor-not-allowed',\n 'has-[[role=combobox]:disabled]:shr-border-default/50',\n 'has-[[role=combobox]:disabled]:shr-bg-white-darken',\n 'has-[[role=combobox]:disabled]:shr-text-disabled',\n // HINT: disabled と詳細度が同じ [0,2,0] のため、CSS ソース順でこちらを後に置くことで error 時の border 色を優先させる\n 'has-[[role=combobox][aria-invalid]]:shr-border-danger',\n ],\n inputArea: 'shr-flex shr-flex-1 shr-flex-wrap shr-gap-0.5',\n selectedList:\n 'smarthr-ui-MultiCombobox-selectedList shr-contents shr-list-none [&_li]:shr-min-w-0',\n inputWrapper: [\n 'shr-flex shr-flex-1 shr-items-center',\n 'has-[[role=combobox][aria-expanded=false]]:shr-pointer-events-none',\n 'has-[[role=combobox][aria-expanded=false]]:shr-absolute',\n 'has-[[role=combobox][aria-expanded=false]]:shr-opacity-0',\n ],\n input: [\n 'smarthr-ui-MultiCombobox-input',\n 'shr-w-full shr-min-w-[5em] shr-border-none shr-text-base shr-text-black shr-outline-none shr-outline-0',\n 'disabled:shr-hidden',\n ],\n placeholderEl: 'smarthr-ui-MultiCombobox-placeholder shr-my-0 shr-self-center',\n suffixWrapper: [\n 'shr-relative -shr-me-0.5 shr-ms-0.5 shr-p-0.5',\n 'before:shr-absolute before:shr-inset-x-0 before:shr-inset-y-0.25 before:shr-w-0 before:shr-border-0 before:shr-border-l before:shr-border-solid before:shr-border-default before:shr-content-[\"\"]',\n ],\n suffixIcon: 'shr-block',\n },\n})\n\nconst ActualMultiCombobox = <T,>(\n {\n items,\n selectedItems,\n name,\n disabled = false,\n required = false,\n error = false,\n creatable = false,\n placeholder = '',\n autoComplete,\n dropdownHelpMessage,\n isLoading,\n selectedItemEllipsis,\n width,\n dropdownWidth = 'auto',\n inputValue: controlledInputValue,\n className,\n onChange,\n onChangeInput,\n onAdd,\n onDelete,\n onSelect,\n onChangeSelected,\n onFocus,\n onBlur,\n onKeyPress,\n isItemSelected,\n noResultText,\n style,\n ...rest\n }: Props<T>,\n ref: Ref<HTMLInputElement>,\n) => {\n const triggerRef = useRef<HTMLDivElement>(null)\n const [isExpanded, setIsExpanded] = useState(false)\n const [highlighted, setHighlighted] = useState(false)\n const [uncontrolledInputValue, setUncontrolledInputValue] = useState('')\n const [isComposing, setIsComposing] = useState(false)\n\n const baseId = useId()\n const selectedListId = `${baseId}-selected`\n\n const isInputControlled = controlledInputValue !== undefined\n const inputValue = isInputControlled ? controlledInputValue : uncontrolledInputValue\n const setInputValueIfUncontrolled = isInputControlled ? NOOP : setUncontrolledInputValue\n const isInputEmpty = !inputValue\n\n const { options } = useMultiOptions({\n items,\n selected: selectedItems,\n creatable,\n inputValue,\n isItemSelected,\n })\n const inputRef = useRef<HTMLInputElement>(null)\n const deleteFrame = useAnimationFrame()\n const selectFrame = useAnimationFrame()\n\n // eslint-disable-next-line local-rules/best-practice-for-use-latest\n const latestForListBox = useLatest({\n onDelete,\n onChangeSelected,\n onSelect,\n onChangeInput,\n selectedItems,\n deleteFrame,\n selectFrame,\n })\n\n const listBoxFunctions = useMemo(() => {\n const handleDelete = (item: ComboboxItem<T>) => {\n const handlers: Array<(deletingItem: ComboboxItem<T>) => void> = []\n\n if (latestForListBox.onDelete) {\n handlers.push((deletingItem: ComboboxItem<T>) => latestForListBox.onDelete!(deletingItem))\n }\n if (latestForListBox.onChangeSelected) {\n handlers.push((deletingItem: ComboboxItem<T>) =>\n latestForListBox.onChangeSelected!(\n latestForListBox.selectedItems.filter(\n (selected) => !areItemsEqual(selected, deletingItem),\n ),\n ),\n )\n }\n\n if (handlers.length > 0) {\n // HINT: Dropdown系コンポーネント内でComboboxを使うと、選択肢がportalで表現されている関係上Dropdownが閉じてしまう\n // 処理を遅延させることで正常に閉じる/閉じないの判定を行えるようにする\n latestForListBox.deleteFrame.request(() => {\n handlers.forEach((h) => h(item))\n })\n }\n }\n\n return {\n cleanupListBoxCallbackRef: () => () => {\n latestForListBox.deleteFrame.cancel()\n latestForListBox.selectFrame.cancel()\n },\n handleDelete,\n handleSelect: (selected: ComboboxItem<T>) => {\n // HINT: Dropdown系コンポーネント内でComboboxを使うと、選択肢がportalで表現されている関係上Dropdownが閉じてしまう\n // 処理を遅延させることで正常に閉じる/閉じないの判定を行えるようにする\n latestForListBox.selectFrame.request(() => {\n const matchedSelectedItem = latestForListBox.selectedItems.find((item) =>\n areItemsEqual(item, selected),\n )\n\n if (matchedSelectedItem === undefined) {\n latestForListBox.onSelect?.(selected)\n latestForListBox.onChangeSelected?.(latestForListBox.selectedItems.concat(selected))\n\n // 制御コンポーネントの場合に親側でinputValueを更新できるように、選択時にonChangeInputを空文字で発火する\n latestForListBox.onChangeInput?.(EMPTY_INPUT_CHANGE_EVENT)\n } else if (matchedSelectedItem.deletable !== false) {\n handleDelete(selected)\n }\n })\n },\n }\n }, [latestForListBox])\n\n const { listBoxProps, activeOption, cleanupAddFrame, handleKeyDownListBox, listBoxId } =\n useListbox({\n options,\n dropdownHelpMessage,\n dropdownWidth,\n onAdd,\n onSelect: listBoxFunctions.handleSelect,\n isExpanded,\n isLoading,\n triggerRef,\n noResultText,\n })\n\n const latest = useLatest({\n onChange,\n onChangeInput,\n onFocus,\n onBlur,\n onKeyPress,\n disabled,\n isExpanded,\n highlighted,\n isComposing,\n isInputEmpty,\n selectedItems,\n setInputValueIfUncontrolled,\n handleKeyDownListBox,\n cleanupAddFrame,\n })\n\n const functions = useMemo(() => {\n const handleDelete = listBoxFunctions.handleDelete\n\n const getDeletionButtons = () => {\n if (triggerRef.current) {\n const buttons =\n triggerRef.current.querySelectorAll<HTMLButtonElement>(DELETE_BUTTON_CLASSNAME)\n\n if (buttons.length > 0) {\n const actualButtons = Array.from(buttons)\n\n return {\n buttons: actualButtons,\n currentIndex: actualButtons.indexOf(document.activeElement as HTMLButtonElement),\n }\n }\n }\n\n return null\n }\n\n const focusPrevDeletionButton = () => {\n const result = getDeletionButtons()\n\n if (!result) return\n\n const { buttons, currentIndex } = result\n\n if (currentIndex !== -1) {\n buttons[Math.max(currentIndex - 1, 0)].focus()\n } else if (inputRef.current?.selectionStart === 0) {\n buttons[buttons.length - 1].focus()\n }\n }\n\n const focusNextDeletionButton = () => {\n const result = getDeletionButtons()\n\n if (!result) return\n\n const { buttons, currentIndex } = result\n\n if (currentIndex === -1) return\n\n const nextIndex = currentIndex + 1\n\n if (nextIndex < buttons.length) {\n buttons[nextIndex].focus()\n } else {\n // キー入力が input に影響しないようにフォーカスタイミングを遅らせる\n setTimeout(() => {\n inputRef.current?.focus()\n })\n }\n }\n\n const focus = () => {\n latest.onFocus?.()\n setIsExpanded(true)\n }\n\n const blur = () => {\n if (latest.isExpanded) {\n latest.onBlur?.()\n setIsExpanded(false)\n }\n }\n\n return {\n handleDelete,\n blur,\n cleanupCallbackRef: () => latest.cleanupAddFrame,\n handleDelegateKeyDown: (e: KeyboardEvent<HTMLDivElement>) => {\n if (latest.isComposing) return\n\n if (ESCAPE_KEY_REGEX.test(e.key)) {\n if (latest.isExpanded) {\n e.stopPropagation()\n }\n\n blur()\n } else if (e.key === 'Tab') {\n if (latest.isExpanded) {\n // フォーカスがコンポーネントを抜けるように先に input をフォーカスしておく\n inputRef.current?.focus()\n }\n\n blur()\n } else if (ARROW_LEFT_KEY_REGEX.test(e.key)) {\n e.stopPropagation()\n focusPrevDeletionButton()\n } else if (ARROW_RIGHT_KEY_REGEX.test(e.key)) {\n e.stopPropagation()\n focusNextDeletionButton()\n } else if (\n e.key === 'Backspace' &&\n latest.isInputEmpty &&\n latest.selectedItems.length > 0 &&\n latest.selectedItems[latest.selectedItems.length - 1].deletable !== false\n ) {\n e.preventDefault()\n e.stopPropagation()\n\n const lastItem = latest.selectedItems[latest.selectedItems.length - 1]\n\n handleDelete(lastItem)\n setHighlighted(true)\n latest.setInputValueIfUncontrolled(innerText(lastItem.label))\n } else {\n e.stopPropagation()\n inputRef.current?.focus()\n }\n\n latest.handleKeyDownListBox(e)\n },\n handleDelegateClick: (e: MouseEvent<HTMLElement>) => {\n if (\n !latest.disabled &&\n !latest.isExpanded &&\n !findDelegateTarget(e, DELETE_BUTTON_CLASSNAME)\n ) {\n focus()\n }\n },\n handleChangeInput: (e: ChangeEvent<HTMLInputElement>) => {\n const handlers = [latest.onChange, latest.onChangeInput].filter((h) => !!h)\n\n handlers.forEach((h) => h(e))\n latest.setInputValueIfUncontrolled(e.currentTarget.value)\n },\n handleFocusInput: () => {\n if (!latest.isExpanded) {\n focus()\n }\n },\n handleCompositionStart: () => setIsComposing(true),\n handleCompositionEnd: () => setIsComposing(false),\n handleKeyDownInput: (e: KeyboardEvent<HTMLInputElement>) => {\n if (ARROW_UP_AND_DOWN_KEY_REGEX.test(e.key)) {\n // 上下キー入力はリストボックスの activeDescendant の移動に用いるため、input 内では作用させない\n e.preventDefault()\n }\n },\n // HINT: form内にcomboboxを設置 & 検索inputにfocusした状態で\n // アイテムをキーボードで選択し、Enterを押すとinput上でEnterを押したことになるため、\n // submitイベントが発生し、formが送信される場合がある\n handleDelegateKeyPress: (e: KeyboardEvent<HTMLInputElement>) => {\n preventDefaultWithPressEnter(e)\n latest.onKeyPress?.(e)\n },\n }\n }, [listBoxFunctions, latest])\n\n const listBoxCallbackRef = useAreaClickCallbackRef(\n isExpanded ? [triggerRef] : null,\n functions.blur,\n )\n\n const mergedInputRef = useMergeRefs(inputRef, listBoxFunctions.cleanupListBoxCallbackRef, ref)\n const mergedTriggerRef = useMergeRefs(triggerRef, functions.cleanupCallbackRef)\n\n useEffect(() => {\n if (latest.highlighted) {\n setHighlighted(false)\n inputRef.current?.select()\n } else {\n setInputValueIfUncontrolled('')\n }\n }, [selectedItems, setInputValueIfUncontrolled, latest])\n\n useEffect(() => {\n if (isExpanded) {\n inputRef.current?.focus()\n }\n }, [isExpanded, selectedItems, isInputControlled])\n\n const classNames = useMemo(() => {\n const {\n wrapper,\n inputArea,\n selectedList,\n inputWrapper,\n input,\n placeholderEl,\n suffixWrapper,\n suffixIcon,\n } = classNameGenerator()\n\n return {\n wrapper: wrapper({ className }),\n inputArea: inputArea(),\n selectedList: selectedList(),\n inputWrapper: inputWrapper(),\n input: input(),\n placeholder: placeholderEl(),\n suffixWrapper: suffixWrapper(),\n suffixIcon: suffixIcon(),\n }\n }, [className])\n\n const localized = useLocalize({\n selectedListAriaLabel: {\n id: 'smarthr-ui/MultiCombobox/selectedListAriaLabel',\n defaultText: '選択済みアイテム',\n },\n })\n\n return (\n // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions\n <div\n ref={mergedTriggerRef}\n role=\"group\"\n className={classNames.wrapper}\n style={{\n ...style,\n width: typeof width === 'number' ? `${width}px` : width,\n }}\n onClick={functions.handleDelegateClick}\n onKeyDown={functions.handleDelegateKeyDown}\n onKeyPress={functions.handleDelegateKeyPress}\n >\n <Scroller className={classNames.inputArea}>\n <ul\n id={selectedListId}\n className={classNames.selectedList}\n aria-label={localized.selectedListAriaLabel}\n >\n {selectedItems.map((selectedItem) => (\n <li key={`${selectedItem.label}-${innerText(selectedItem.value)}`}>\n <MultiSelectedItem\n disabled={disabled}\n item={selectedItem}\n enableEllipsis={selectedItemEllipsis}\n handleDelete={functions.handleDelete}\n />\n </li>\n ))}\n </ul>\n\n <div className={classNames.inputWrapper}>\n <input\n {...rest}\n ref={mergedInputRef}\n role=\"combobox\"\n type=\"text\"\n name={name}\n required={required && selectedItems.length === 0}\n disabled={disabled}\n value={inputValue}\n autoComplete={autoComplete ?? 'off'}\n tabIndex={0}\n className={classNames.input}\n aria-activedescendant={activeOption?.id}\n aria-controls={`${listBoxId} ${selectedListId}`}\n aria-haspopup=\"listbox\"\n aria-expanded={isExpanded}\n aria-invalid={error || undefined}\n aria-disabled={disabled}\n aria-autocomplete=\"list\"\n data-smarthr-ui-input=\"true\"\n onChange={functions.handleChangeInput}\n onFocus={functions.handleFocusInput}\n onCompositionStart={functions.handleCompositionStart}\n onCompositionEnd={functions.handleCompositionEnd}\n onKeyDown={functions.handleKeyDownInput}\n />\n </div>\n\n {selectedItems.length === 0 && placeholder && !isExpanded && (\n <p className={classNames.placeholder}>{placeholder}</p>\n )}\n </Scroller>\n\n <MemoizedCaretDown disabled={disabled} isExpanded={isExpanded} classNames={classNames} />\n\n <ListBox {...listBoxProps} callbackRef={listBoxCallbackRef} />\n </div>\n )\n}\n\nexport const MultiCombobox = genericsForwardRef(ActualMultiCombobox)\n\nconst MemoizedCaretDown = memo<{\n disabled: boolean\n isExpanded: boolean\n classNames: {\n suffixWrapper: string\n suffixIcon: string\n }\n}>(({ disabled, isExpanded, classNames }) => {\n const theme = useTheme()\n const caretIconColor = isExpanded\n ? theme.textColor.black\n : disabled\n ? theme.textColor.disabled\n : theme.textColor.grey\n\n return (\n <div className={classNames.suffixWrapper}>\n <FaCaretDownIcon color={caretIconColor} className={classNames.suffixIcon} />\n </div>\n )\n})\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8EA;AAEA;AACE;;;AAGF;AAEA;AACA;AACA;AACA;AAEA;AACE;AACA;;AAGF;AAEA;AACE;AACE;;;;;;;;;;;;AAYC;AACD;AACA;AAEA;;;;;AAKC;AACD;;;;AAIC;AACD;AACA;;;AAGC;AACD;AACD;AACF;AAED;AAkCE;;;;;AAMA;AACA;AAEA;;;AAGA;AAEA;;AAEE;;;;AAID;AACD;AACA;AACA;;;;;;;;;;AAWC;AAED;AACE;;AAGE;AACE;;AAEF;AACE;;AASF;;;AAGE;AACE;AACF;;AAEJ;;AAGE;AACE;AACA;;;AAGF;;;AAGE;;AAKE;AACE;AACA;;AAGA;;AACK;;;AAGT;;;AAGN;AAEA;;;;;;;;;;AAWG;;;;;;;;;;;;;;;;AAiBF;AAED;AACE;;AAGE;;AAIE;;;AAII;;;;;AAMN;AACF;;AAGE;AAEA;;AAEA;AAEA;AACE;;;;;AAIJ;;AAGE;AAEA;;AAEA;;;AAIA;AAEA;AACE;;;;;AAIE;AACF;;AAEJ;;AAGE;;AAEF;;AAGE;AACE;;;AAGJ;;;;AAKE;AACA;;;;AAII;;;AAIA;;AACK;AACL;;AAEE;;AAGF;;;;AAGA;;;;AAGA;;AACK;AAEL;AACA;AACA;;;AAKA;;;;;;;AAOA;;AAGF;;AAEF;;;AAII;AAEA;;;AAGJ;;AAGE;;;;AAIA;AACE;;;AAGJ;AACA;AACA;;;;;;;;;AASA;;AAEE;;;AAGN;;AAOA;;;AAIE;;AAEE;;;;;;;;AAQA;;;AAIJ;;;AAaI;;;;;;;;;AASJ;;AAGE;AACE;AACA;AACD;AACF;;;AAIC;AAKI;AACA;AACD;AA8DP;;AAIA;AAQE;;AAEE;AACA;AACE;AACA;;AAON;;"}
1
+ {"version":3,"file":"MultiCombobox.cjs","sources":["../../../../src/components/Combobox/MultiCombobox/MultiCombobox.tsx"],"sourcesContent":["'use client'\n\nimport {\n type ChangeEvent,\n type ComponentPropsWithoutRef,\n type KeyboardEvent,\n type MouseEvent,\n type ReactNode,\n type Ref,\n memo,\n useEffect,\n useId,\n useMemo,\n useRef,\n useState,\n} from 'react'\nimport innerText from 'react-innertext'\nimport { tv } from 'tailwind-variants'\n\nimport { useAnimationFrame } from '../../../hooks/client/useAnimationFrame'\nimport { useAreaClickCallbackRef } from '../../../hooks/client/useAreaClickCallbackRef'\nimport { useMergeRefs } from '../../../hooks/client/useMergeRefs'\nimport { useTheme } from '../../../hooks/client/useTheme'\nimport { useLatest } from '../../../hooks/useLatest'\nimport { useLocalize } from '../../../intl'\nimport { findDelegateTarget } from '../../../libs/delegate'\nimport { genericsForwardRef } from '../../../libs/util'\nimport { FaCaretDownIcon } from '../../Icon'\nimport { Scroller } from '../../Scroller'\nimport { areItemsEqual } from '../helper'\nimport { ListBox, useListbox } from '../useListbox'\nimport { useMultiOptions } from '../useOptions'\n\nimport { DELETE_BUTTON_SELECTOR, MultiSelectedItem } from './MultiSelectedItem'\n\nimport type { ComboboxItem, BaseProps as ComboboxProps } from '../types'\n\ntype BaseProps<T> = ComboboxProps<T> & {\n /**\n * 選択されているアイテムのリスト\n */\n selectedItems: Array<ComboboxItem<T> & { deletable?: boolean }>\n /**\n * 選択されているアイテムのラベルを省略表示するかどうか\n */\n selectedItemEllipsis?: boolean\n /**\n * テキストボックスの `value` 属性の値。\n * `onChangeInput` と併せて設定することで、テキストボックスの挙動が制御可能になる。\n */\n inputValue?: string\n /**\n * 選択されているアイテムの削除ボタンがクリックされた時に発火するコールバック関数\n */\n onDelete?: (item: ComboboxItem<T>) => void\n /**\n * 選択されているアイテムのリストが変わった時に発火するコールバック関数\n */\n onChangeSelected?: (selectedItems: Array<ComboboxItem<T>>) => void\n /**\n * コンポーネントがフォーカスされたときに発火するコールバック関数\n */\n onFocus?: () => void\n /**\n * コンポーネントからフォーカスが外れた時に発火するコールバック関数\n */\n onBlur?: () => void\n /**\n * アイテムが選択されたときに選択済みかどうかを判定するコールバック関数/\n */\n isItemSelected?: (targetItem: ComboboxItem<T>, selectedItems: Array<ComboboxItem<T>>) => boolean\n /**\n * 検索結果が0件の時に表示するコンテンツ\n */\n noResultText?: ReactNode\n}\ntype Props<T> = BaseProps<T> & Omit<ComponentPropsWithoutRef<'input'>, keyof BaseProps<unknown>>\n\nconst NOOP = () => undefined\n\nconst preventDefaultWithPressEnter = (e: KeyboardEvent<HTMLInputElement>) => {\n if (e.key === 'Enter') {\n e.preventDefault()\n }\n}\n\nconst ESCAPE_KEY_REGEX = /^Esc(ape)?$/\nconst ARROW_LEFT_KEY_REGEX = /^(Arrow)?Left$/\nconst ARROW_RIGHT_KEY_REGEX = /^(Arrow)?Right/\nconst ARROW_UP_AND_DOWN_KEY_REGEX = /^(Arrow)?(Up|Down)$/\n\nconst EMPTY_INPUT_CHANGE_EVENT = {\n currentTarget: { value: '' },\n target: { value: '' },\n} as ChangeEvent<HTMLInputElement>\n\nconst DELETE_BUTTON_CLASSNAME = `.${DELETE_BUTTON_SELECTOR}`\n\nconst classNameGenerator = tv({\n slots: {\n wrapper: [\n 'smarthr-ui-MultiCombobox',\n 'shr-box-border shr-inline-flex shr-min-w-[15em] shr-rounded-m shr-border shr-border-solid shr-px-0.5 shr-py-0.25 shr-align-bottom',\n 'contrast-more:shr-border-high-contrast',\n 'has-[[role=combobox][aria-expanded=true]]:shr-focus-indicator',\n 'shr-cursor-text shr-border-default shr-bg-white',\n 'has-[[role=combobox]:disabled]:shr-cursor-not-allowed',\n 'has-[[role=combobox]:disabled]:shr-border-default/50',\n 'has-[[role=combobox]:disabled]:shr-bg-white-darken',\n 'has-[[role=combobox]:disabled]:shr-text-disabled',\n // HINT: disabled と詳細度が同じ [0,2,0] のため、CSS ソース順でこちらを後に置くことで error 時の border 色を優先させる\n 'has-[[role=combobox][aria-invalid]]:shr-border-danger',\n ],\n inputArea: 'shr-flex shr-flex-1 shr-flex-wrap shr-gap-0.5',\n selectedList:\n 'smarthr-ui-MultiCombobox-selectedList shr-contents shr-list-none [&_li]:shr-min-w-0',\n inputWrapper: [\n 'shr-flex shr-flex-1 shr-items-center',\n 'has-[[role=combobox][aria-expanded=false]]:shr-pointer-events-none',\n 'has-[[role=combobox][aria-expanded=false]]:shr-absolute',\n 'has-[[role=combobox][aria-expanded=false]]:shr-opacity-0',\n ],\n input: [\n 'smarthr-ui-MultiCombobox-input',\n 'shr-w-full shr-min-w-[5em] shr-border-none shr-text-base shr-text-black shr-outline-none shr-outline-0',\n 'disabled:shr-hidden',\n ],\n placeholderEl: 'smarthr-ui-MultiCombobox-placeholder shr-my-0 shr-self-center',\n suffixWrapper: [\n 'shr-relative -shr-me-0.5 shr-ms-0.5 shr-p-0.5',\n 'before:shr-absolute before:shr-inset-x-0 before:shr-inset-y-0.25 before:shr-w-0 before:shr-border-0 before:shr-border-l before:shr-border-solid before:shr-border-default before:shr-content-[\"\"]',\n ],\n suffixIcon: 'shr-block',\n },\n})\n\nconst ActualMultiCombobox = <T,>(\n {\n items,\n selectedItems,\n name,\n disabled = false,\n required = false,\n error = false,\n creatable = false,\n placeholder = '',\n autoComplete,\n dropdownHelpMessage,\n isLoading,\n selectedItemEllipsis,\n width,\n dropdownWidth = 'auto',\n inputValue: controlledInputValue,\n className,\n onChange,\n onChangeInput,\n onAdd,\n onDelete,\n onSelect,\n onChangeSelected,\n onFocus,\n onBlur,\n onKeyPress,\n isItemSelected,\n noResultText,\n style,\n ...rest\n }: Props<T>,\n ref: Ref<HTMLInputElement>,\n) => {\n const triggerRef = useRef<HTMLDivElement>(null)\n const [isExpanded, setIsExpanded] = useState(false)\n const [highlighted, setHighlighted] = useState(false)\n const [uncontrolledInputValue, setUncontrolledInputValue] = useState('')\n const [isComposing, setIsComposing] = useState(false)\n\n const baseId = useId()\n const selectedListId = `${baseId}-selected`\n\n const isInputControlled = controlledInputValue !== undefined\n const inputValue = isInputControlled ? controlledInputValue : uncontrolledInputValue\n const setInputValueIfUncontrolled = isInputControlled ? NOOP : setUncontrolledInputValue\n const isInputEmpty = !inputValue\n\n const { options } = useMultiOptions({\n items,\n selected: selectedItems,\n creatable,\n inputValue,\n isItemSelected,\n })\n const inputRef = useRef<HTMLInputElement>(null)\n const deleteFrame = useAnimationFrame()\n const selectFrame = useAnimationFrame()\n\n // eslint-disable-next-line local-rules/best-practice-for-use-latest\n const latestForListBox = useLatest({\n onDelete,\n onChangeSelected,\n onSelect,\n onChangeInput,\n selectedItems,\n deleteFrame,\n selectFrame,\n })\n\n const listBoxFunctions = useMemo(() => {\n const handleDelete = (item: ComboboxItem<T>) => {\n const handlers: Array<(deletingItem: ComboboxItem<T>) => void> = []\n\n if (latestForListBox.onDelete) {\n handlers.push((deletingItem: ComboboxItem<T>) => latestForListBox.onDelete!(deletingItem))\n }\n if (latestForListBox.onChangeSelected) {\n handlers.push((deletingItem: ComboboxItem<T>) =>\n latestForListBox.onChangeSelected!(\n latestForListBox.selectedItems.filter(\n (selected) => !areItemsEqual(selected, deletingItem),\n ),\n ),\n )\n }\n\n if (handlers.length > 0) {\n // HINT: Dropdown系コンポーネント内でComboboxを使うと、選択肢がportalで表現されている関係上Dropdownが閉じてしまう\n // 処理を遅延させることで正常に閉じる/閉じないの判定を行えるようにする\n latestForListBox.deleteFrame.request(() => {\n handlers.forEach((h) => h(item))\n })\n }\n }\n\n return {\n cleanupListBoxCallbackRef: () => () => {\n latestForListBox.deleteFrame.cancel()\n latestForListBox.selectFrame.cancel()\n },\n handleDelete,\n handleSelect: (selected: ComboboxItem<T>) => {\n // HINT: Dropdown系コンポーネント内でComboboxを使うと、選択肢がportalで表現されている関係上Dropdownが閉じてしまう\n // 処理を遅延させることで正常に閉じる/閉じないの判定を行えるようにする\n latestForListBox.selectFrame.request(() => {\n const matchedSelectedItem = latestForListBox.selectedItems.find((item) =>\n areItemsEqual(item, selected),\n )\n\n if (matchedSelectedItem === undefined) {\n latestForListBox.onSelect?.(selected)\n latestForListBox.onChangeSelected?.(latestForListBox.selectedItems.concat(selected))\n\n // 制御コンポーネントの場合に親側でinputValueを更新できるように、選択時にonChangeInputを空文字で発火する\n latestForListBox.onChangeInput?.(EMPTY_INPUT_CHANGE_EVENT)\n } else if (matchedSelectedItem.deletable !== false) {\n handleDelete(selected)\n }\n })\n },\n }\n }, [latestForListBox])\n\n const { listBoxProps, activeOption, cleanupAddFrame, handleKeyDownListBox, listBoxId } =\n useListbox({\n options,\n dropdownHelpMessage,\n dropdownWidth,\n onAdd,\n onSelect: listBoxFunctions.handleSelect,\n isExpanded,\n isLoading,\n triggerRef,\n noResultText,\n })\n\n const latest = useLatest({\n onChange,\n onChangeInput,\n onFocus,\n onBlur,\n onKeyPress,\n disabled,\n isExpanded,\n highlighted,\n isComposing,\n isInputEmpty,\n selectedItems,\n setInputValueIfUncontrolled,\n handleKeyDownListBox,\n cleanupAddFrame,\n })\n\n const functions = useMemo(() => {\n const handleDelete = listBoxFunctions.handleDelete\n\n const getDeletionButtons = () => {\n if (triggerRef.current) {\n const buttons =\n triggerRef.current.querySelectorAll<HTMLButtonElement>(DELETE_BUTTON_CLASSNAME)\n\n if (buttons.length > 0) {\n const actualButtons = Array.from(buttons)\n\n return {\n buttons: actualButtons,\n currentIndex: actualButtons.indexOf(document.activeElement as HTMLButtonElement),\n }\n }\n }\n\n return null\n }\n\n const focusPrevDeletionButton = () => {\n const result = getDeletionButtons()\n\n if (!result) return\n\n const { buttons, currentIndex } = result\n\n if (currentIndex !== -1) {\n buttons[Math.max(currentIndex - 1, 0)].focus()\n } else if (inputRef.current?.selectionStart === 0) {\n buttons[buttons.length - 1].focus()\n }\n }\n\n const focusNextDeletionButton = () => {\n const result = getDeletionButtons()\n\n if (!result) return\n\n const { buttons, currentIndex } = result\n\n if (currentIndex === -1) return\n\n const nextIndex = currentIndex + 1\n\n if (nextIndex < buttons.length) {\n buttons[nextIndex].focus()\n } else {\n // キー入力が input に影響しないようにフォーカスタイミングを遅らせる\n setTimeout(() => {\n inputRef.current?.focus()\n })\n }\n }\n\n const focus = () => {\n latest.onFocus?.()\n setIsExpanded(true)\n }\n\n const blur = () => {\n if (latest.isExpanded) {\n latest.onBlur?.()\n setIsExpanded(false)\n }\n }\n\n return {\n handleDelete,\n blur,\n cleanupCallbackRef: () => latest.cleanupAddFrame,\n handleDelegateKeyDown: (e: KeyboardEvent<HTMLDivElement>) => {\n if (latest.isComposing) return\n\n if (ESCAPE_KEY_REGEX.test(e.key)) {\n if (latest.isExpanded) {\n e.stopPropagation()\n }\n\n blur()\n } else if (e.key === 'Tab') {\n if (latest.isExpanded) {\n // フォーカスがコンポーネントを抜けるように先に input をフォーカスしておく\n inputRef.current?.focus()\n }\n\n blur()\n } else if (ARROW_LEFT_KEY_REGEX.test(e.key)) {\n e.stopPropagation()\n focusPrevDeletionButton()\n } else if (ARROW_RIGHT_KEY_REGEX.test(e.key)) {\n e.stopPropagation()\n focusNextDeletionButton()\n } else if (\n e.key === 'Backspace' &&\n latest.isInputEmpty &&\n latest.selectedItems.length > 0 &&\n latest.selectedItems[latest.selectedItems.length - 1].deletable !== false\n ) {\n e.preventDefault()\n e.stopPropagation()\n\n const lastItem = latest.selectedItems[latest.selectedItems.length - 1]\n\n handleDelete(lastItem)\n setHighlighted(true)\n latest.setInputValueIfUncontrolled(innerText(lastItem.label))\n } else {\n e.stopPropagation()\n inputRef.current?.focus()\n }\n\n latest.handleKeyDownListBox(e)\n },\n handleDelegateClick: (e: MouseEvent<HTMLElement>) => {\n if (\n !latest.disabled &&\n !latest.isExpanded &&\n !findDelegateTarget(e, DELETE_BUTTON_CLASSNAME)\n ) {\n focus()\n }\n },\n handleChangeInput: (e: ChangeEvent<HTMLInputElement>) => {\n const handlers = [latest.onChange, latest.onChangeInput].filter((h) => !!h)\n\n handlers.forEach((h) => h(e))\n latest.setInputValueIfUncontrolled(e.currentTarget.value)\n },\n handleFocusInput: () => {\n if (!latest.isExpanded) {\n focus()\n }\n },\n handleCompositionStart: () => setIsComposing(true),\n handleCompositionEnd: () => setIsComposing(false),\n handleKeyDownInput: (e: KeyboardEvent<HTMLInputElement>) => {\n if (ARROW_UP_AND_DOWN_KEY_REGEX.test(e.key)) {\n // 上下キー入力はリストボックスの activeDescendant の移動に用いるため、input 内では作用させない\n e.preventDefault()\n }\n },\n // HINT: form内にcomboboxを設置 & 検索inputにfocusした状態で\n // アイテムをキーボードで選択し、Enterを押すとinput上でEnterを押したことになるため、\n // submitイベントが発生し、formが送信される場合がある\n handleDelegateKeyPress: (e: KeyboardEvent<HTMLInputElement>) => {\n preventDefaultWithPressEnter(e)\n latest.onKeyPress?.(e)\n },\n }\n }, [listBoxFunctions, latest])\n\n const listBoxCallbackRef = useAreaClickCallbackRef(\n isExpanded ? [triggerRef] : null,\n functions.blur,\n )\n\n const mergedInputRef = useMergeRefs(inputRef, listBoxFunctions.cleanupListBoxCallbackRef, ref)\n const mergedTriggerRef = useMergeRefs(triggerRef, functions.cleanupCallbackRef)\n\n useEffect(() => {\n if (latest.highlighted) {\n setHighlighted(false)\n inputRef.current?.select()\n } else {\n setInputValueIfUncontrolled('')\n }\n }, [selectedItems, setInputValueIfUncontrolled, latest])\n\n useEffect(() => {\n if (isExpanded) {\n inputRef.current?.focus()\n }\n }, [isExpanded, selectedItems, isInputControlled])\n\n const classNames = useMemo(() => {\n const {\n wrapper,\n inputArea,\n selectedList,\n inputWrapper,\n input,\n placeholderEl,\n suffixWrapper,\n suffixIcon,\n } = classNameGenerator()\n\n return {\n wrapper: wrapper({ className }),\n inputArea: inputArea(),\n selectedList: selectedList(),\n inputWrapper: inputWrapper(),\n input: input(),\n placeholder: placeholderEl(),\n suffixWrapper: suffixWrapper(),\n suffixIcon: suffixIcon(),\n }\n }, [className])\n\n const localized = useLocalize({\n selectedListAriaLabel: {\n id: 'smarthr-ui/MultiCombobox/selectedListAriaLabel',\n defaultText: '選択済みアイテム',\n },\n })\n\n const errorAttr = error || undefined\n\n return (\n // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions\n <div\n ref={mergedTriggerRef}\n role=\"group\"\n className={classNames.wrapper}\n style={{\n ...style,\n width: typeof width === 'number' ? `${width}px` : width,\n }}\n onClick={functions.handleDelegateClick}\n onKeyDown={functions.handleDelegateKeyDown}\n onKeyPress={functions.handleDelegateKeyPress}\n >\n <Scroller className={classNames.inputArea}>\n <ul\n id={selectedListId}\n className={classNames.selectedList}\n aria-label={localized.selectedListAriaLabel}\n >\n {selectedItems.map((selectedItem) => (\n <li key={`${selectedItem.label}-${innerText(selectedItem.value)}`}>\n <MultiSelectedItem\n disabled={disabled}\n item={selectedItem}\n enableEllipsis={selectedItemEllipsis}\n handleDelete={functions.handleDelete}\n />\n </li>\n ))}\n </ul>\n\n <div className={classNames.inputWrapper}>\n <input\n {...rest}\n ref={mergedInputRef}\n role=\"combobox\"\n type=\"text\"\n name={name}\n required={required && selectedItems.length === 0}\n disabled={disabled}\n value={inputValue}\n autoComplete={autoComplete ?? 'off'}\n tabIndex={0}\n className={classNames.input}\n aria-activedescendant={activeOption?.id}\n aria-controls={`${listBoxId} ${selectedListId}`}\n aria-haspopup=\"listbox\"\n aria-expanded={isExpanded}\n aria-invalid={errorAttr}\n aria-disabled={disabled}\n aria-autocomplete=\"list\"\n data-smarthr-ui-input-error={errorAttr}\n data-smarthr-ui-input=\"true\"\n onChange={functions.handleChangeInput}\n onFocus={functions.handleFocusInput}\n onCompositionStart={functions.handleCompositionStart}\n onCompositionEnd={functions.handleCompositionEnd}\n onKeyDown={functions.handleKeyDownInput}\n />\n </div>\n\n {selectedItems.length === 0 && placeholder && !isExpanded && (\n <p className={classNames.placeholder}>{placeholder}</p>\n )}\n </Scroller>\n\n <MemoizedCaretDown disabled={disabled} isExpanded={isExpanded} classNames={classNames} />\n\n <ListBox {...listBoxProps} callbackRef={listBoxCallbackRef} />\n </div>\n )\n}\n\nexport const MultiCombobox = genericsForwardRef(ActualMultiCombobox)\n\nconst MemoizedCaretDown = memo<{\n disabled: boolean\n isExpanded: boolean\n classNames: {\n suffixWrapper: string\n suffixIcon: string\n }\n}>(({ disabled, isExpanded, classNames }) => {\n const theme = useTheme()\n const caretIconColor = isExpanded\n ? theme.textColor.black\n : disabled\n ? theme.textColor.disabled\n : theme.textColor.grey\n\n return (\n <div className={classNames.suffixWrapper}>\n <FaCaretDownIcon color={caretIconColor} className={classNames.suffixIcon} />\n </div>\n )\n})\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8EA;AAEA;AACE;;;AAGF;AAEA;AACA;AACA;AACA;AAEA;AACE;AACA;;AAGF;AAEA;AACE;AACE;;;;;;;;;;;;AAYC;AACD;AACA;AAEA;;;;;AAKC;AACD;;;;AAIC;AACD;AACA;;;AAGC;AACD;AACD;AACF;AAED;AAkCE;;;;;AAMA;AACA;AAEA;;;AAGA;AAEA;;AAEE;;;;AAID;AACD;AACA;AACA;;;;;;;;;;AAWC;AAED;AACE;;AAGE;AACE;;AAEF;AACE;;AASF;;;AAGE;AACE;AACF;;AAEJ;;AAGE;AACE;AACA;;;AAGF;;;AAGE;;AAKE;AACE;AACA;;AAGA;;AACK;;;AAGT;;;AAGN;AAEA;;;;;;;;;;AAWG;;;;;;;;;;;;;;;;AAiBF;AAED;AACE;;AAGE;;AAIE;;;AAII;;;;;AAMN;AACF;;AAGE;AAEA;;AAEA;AAEA;AACE;;;;;AAIJ;;AAGE;AAEA;;AAEA;;;AAIA;AAEA;AACE;;;;;AAIE;AACF;;AAEJ;;AAGE;;AAEF;;AAGE;AACE;;;AAGJ;;;;AAKE;AACA;;;;AAII;;;AAIA;;AACK;AACL;;AAEE;;AAGF;;;;AAGA;;;;AAGA;;AACK;AAEL;AACA;AACA;;;AAKA;;;;;;;AAOA;;AAGF;;AAEF;;;AAII;AAEA;;;AAGJ;;AAGE;;;;AAIA;AACE;;;AAGJ;AACA;AACA;;;;;;;;;AASA;;AAEE;;;AAGN;;AAOA;;;AAIE;;AAEE;;;;;;;;AAQA;;;AAIJ;;;AAaI;;;;;;;;;AASJ;;AAGE;AACE;AACA;AACD;AACF;AAED;;;AAIE;AAKI;AACA;AACD;AA+DP;;AAIA;AAQE;;AAEE;AACA;AACE;AACA;;AAON;;"}
@@ -346,12 +346,13 @@ const ActualMultiCombobox = ({ items, selectedItems, name, disabled = false, req
346
346
  defaultText: '選択済みアイテム',
347
347
  },
348
348
  });
349
+ const errorAttr = error || undefined;
349
350
  return (
350
351
  // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions
351
352
  jsxs("div", { ref: mergedTriggerRef, role: "group", className: classNames.wrapper, style: {
352
353
  ...style,
353
354
  width: typeof width === 'number' ? `${width}px` : width,
354
- }, onClick: functions.handleDelegateClick, onKeyDown: functions.handleDelegateKeyDown, onKeyPress: functions.handleDelegateKeyPress, children: [jsxs(Scroller, { className: classNames.inputArea, children: [jsx("ul", { id: selectedListId, className: classNames.selectedList, "aria-label": localized.selectedListAriaLabel, children: selectedItems.map((selectedItem) => (jsx("li", { children: jsx(MultiSelectedItem, { disabled: disabled, item: selectedItem, enableEllipsis: selectedItemEllipsis, handleDelete: functions.handleDelete }) }, `${selectedItem.label}-${innerText(selectedItem.value)}`))) }), jsx("div", { className: classNames.inputWrapper, children: jsx("input", { ...rest, ref: mergedInputRef, role: "combobox", type: "text", name: name, required: required && selectedItems.length === 0, disabled: disabled, value: inputValue, autoComplete: autoComplete ?? 'off', tabIndex: 0, className: classNames.input, "aria-activedescendant": activeOption?.id, "aria-controls": `${listBoxId} ${selectedListId}`, "aria-haspopup": "listbox", "aria-expanded": isExpanded, "aria-invalid": error || undefined, "aria-disabled": disabled, "aria-autocomplete": "list", "data-smarthr-ui-input": "true", onChange: functions.handleChangeInput, onFocus: functions.handleFocusInput, onCompositionStart: functions.handleCompositionStart, onCompositionEnd: functions.handleCompositionEnd, onKeyDown: functions.handleKeyDownInput }) }), selectedItems.length === 0 && placeholder && !isExpanded && (jsx("p", { className: classNames.placeholder, children: placeholder }))] }), jsx(MemoizedCaretDown, { disabled: disabled, isExpanded: isExpanded, classNames: classNames }), jsx(ListBox, { ...listBoxProps, callbackRef: listBoxCallbackRef })] }));
355
+ }, onClick: functions.handleDelegateClick, onKeyDown: functions.handleDelegateKeyDown, onKeyPress: functions.handleDelegateKeyPress, children: [jsxs(Scroller, { className: classNames.inputArea, children: [jsx("ul", { id: selectedListId, className: classNames.selectedList, "aria-label": localized.selectedListAriaLabel, children: selectedItems.map((selectedItem) => (jsx("li", { children: jsx(MultiSelectedItem, { disabled: disabled, item: selectedItem, enableEllipsis: selectedItemEllipsis, handleDelete: functions.handleDelete }) }, `${selectedItem.label}-${innerText(selectedItem.value)}`))) }), jsx("div", { className: classNames.inputWrapper, children: jsx("input", { ...rest, ref: mergedInputRef, role: "combobox", type: "text", name: name, required: required && selectedItems.length === 0, disabled: disabled, value: inputValue, autoComplete: autoComplete ?? 'off', tabIndex: 0, className: classNames.input, "aria-activedescendant": activeOption?.id, "aria-controls": `${listBoxId} ${selectedListId}`, "aria-haspopup": "listbox", "aria-expanded": isExpanded, "aria-invalid": errorAttr, "aria-disabled": disabled, "aria-autocomplete": "list", "data-smarthr-ui-input-error": errorAttr, "data-smarthr-ui-input": "true", onChange: functions.handleChangeInput, onFocus: functions.handleFocusInput, onCompositionStart: functions.handleCompositionStart, onCompositionEnd: functions.handleCompositionEnd, onKeyDown: functions.handleKeyDownInput }) }), selectedItems.length === 0 && placeholder && !isExpanded && (jsx("p", { className: classNames.placeholder, children: placeholder }))] }), jsx(MemoizedCaretDown, { disabled: disabled, isExpanded: isExpanded, classNames: classNames }), jsx(ListBox, { ...listBoxProps, callbackRef: listBoxCallbackRef })] }));
355
356
  };
356
357
  const MultiCombobox = genericsForwardRef(ActualMultiCombobox);
357
358
  const MemoizedCaretDown = memo(({ disabled, isExpanded, classNames }) => {
@@ -1 +1 @@
1
- {"version":3,"file":"MultiCombobox.js","sources":["../../../../src/components/Combobox/MultiCombobox/MultiCombobox.tsx"],"sourcesContent":["'use client'\n\nimport {\n type ChangeEvent,\n type ComponentPropsWithoutRef,\n type KeyboardEvent,\n type MouseEvent,\n type ReactNode,\n type Ref,\n memo,\n useEffect,\n useId,\n useMemo,\n useRef,\n useState,\n} from 'react'\nimport innerText from 'react-innertext'\nimport { tv } from 'tailwind-variants'\n\nimport { useAnimationFrame } from '../../../hooks/client/useAnimationFrame'\nimport { useAreaClickCallbackRef } from '../../../hooks/client/useAreaClickCallbackRef'\nimport { useMergeRefs } from '../../../hooks/client/useMergeRefs'\nimport { useTheme } from '../../../hooks/client/useTheme'\nimport { useLatest } from '../../../hooks/useLatest'\nimport { useLocalize } from '../../../intl'\nimport { findDelegateTarget } from '../../../libs/delegate'\nimport { genericsForwardRef } from '../../../libs/util'\nimport { FaCaretDownIcon } from '../../Icon'\nimport { Scroller } from '../../Scroller'\nimport { areItemsEqual } from '../helper'\nimport { ListBox, useListbox } from '../useListbox'\nimport { useMultiOptions } from '../useOptions'\n\nimport { DELETE_BUTTON_SELECTOR, MultiSelectedItem } from './MultiSelectedItem'\n\nimport type { ComboboxItem, BaseProps as ComboboxProps } from '../types'\n\ntype BaseProps<T> = ComboboxProps<T> & {\n /**\n * 選択されているアイテムのリスト\n */\n selectedItems: Array<ComboboxItem<T> & { deletable?: boolean }>\n /**\n * 選択されているアイテムのラベルを省略表示するかどうか\n */\n selectedItemEllipsis?: boolean\n /**\n * テキストボックスの `value` 属性の値。\n * `onChangeInput` と併せて設定することで、テキストボックスの挙動が制御可能になる。\n */\n inputValue?: string\n /**\n * 選択されているアイテムの削除ボタンがクリックされた時に発火するコールバック関数\n */\n onDelete?: (item: ComboboxItem<T>) => void\n /**\n * 選択されているアイテムのリストが変わった時に発火するコールバック関数\n */\n onChangeSelected?: (selectedItems: Array<ComboboxItem<T>>) => void\n /**\n * コンポーネントがフォーカスされたときに発火するコールバック関数\n */\n onFocus?: () => void\n /**\n * コンポーネントからフォーカスが外れた時に発火するコールバック関数\n */\n onBlur?: () => void\n /**\n * アイテムが選択されたときに選択済みかどうかを判定するコールバック関数/\n */\n isItemSelected?: (targetItem: ComboboxItem<T>, selectedItems: Array<ComboboxItem<T>>) => boolean\n /**\n * 検索結果が0件の時に表示するコンテンツ\n */\n noResultText?: ReactNode\n}\ntype Props<T> = BaseProps<T> & Omit<ComponentPropsWithoutRef<'input'>, keyof BaseProps<unknown>>\n\nconst NOOP = () => undefined\n\nconst preventDefaultWithPressEnter = (e: KeyboardEvent<HTMLInputElement>) => {\n if (e.key === 'Enter') {\n e.preventDefault()\n }\n}\n\nconst ESCAPE_KEY_REGEX = /^Esc(ape)?$/\nconst ARROW_LEFT_KEY_REGEX = /^(Arrow)?Left$/\nconst ARROW_RIGHT_KEY_REGEX = /^(Arrow)?Right/\nconst ARROW_UP_AND_DOWN_KEY_REGEX = /^(Arrow)?(Up|Down)$/\n\nconst EMPTY_INPUT_CHANGE_EVENT = {\n currentTarget: { value: '' },\n target: { value: '' },\n} as ChangeEvent<HTMLInputElement>\n\nconst DELETE_BUTTON_CLASSNAME = `.${DELETE_BUTTON_SELECTOR}`\n\nconst classNameGenerator = tv({\n slots: {\n wrapper: [\n 'smarthr-ui-MultiCombobox',\n 'shr-box-border shr-inline-flex shr-min-w-[15em] shr-rounded-m shr-border shr-border-solid shr-px-0.5 shr-py-0.25 shr-align-bottom',\n 'contrast-more:shr-border-high-contrast',\n 'has-[[role=combobox][aria-expanded=true]]:shr-focus-indicator',\n 'shr-cursor-text shr-border-default shr-bg-white',\n 'has-[[role=combobox]:disabled]:shr-cursor-not-allowed',\n 'has-[[role=combobox]:disabled]:shr-border-default/50',\n 'has-[[role=combobox]:disabled]:shr-bg-white-darken',\n 'has-[[role=combobox]:disabled]:shr-text-disabled',\n // HINT: disabled と詳細度が同じ [0,2,0] のため、CSS ソース順でこちらを後に置くことで error 時の border 色を優先させる\n 'has-[[role=combobox][aria-invalid]]:shr-border-danger',\n ],\n inputArea: 'shr-flex shr-flex-1 shr-flex-wrap shr-gap-0.5',\n selectedList:\n 'smarthr-ui-MultiCombobox-selectedList shr-contents shr-list-none [&_li]:shr-min-w-0',\n inputWrapper: [\n 'shr-flex shr-flex-1 shr-items-center',\n 'has-[[role=combobox][aria-expanded=false]]:shr-pointer-events-none',\n 'has-[[role=combobox][aria-expanded=false]]:shr-absolute',\n 'has-[[role=combobox][aria-expanded=false]]:shr-opacity-0',\n ],\n input: [\n 'smarthr-ui-MultiCombobox-input',\n 'shr-w-full shr-min-w-[5em] shr-border-none shr-text-base shr-text-black shr-outline-none shr-outline-0',\n 'disabled:shr-hidden',\n ],\n placeholderEl: 'smarthr-ui-MultiCombobox-placeholder shr-my-0 shr-self-center',\n suffixWrapper: [\n 'shr-relative -shr-me-0.5 shr-ms-0.5 shr-p-0.5',\n 'before:shr-absolute before:shr-inset-x-0 before:shr-inset-y-0.25 before:shr-w-0 before:shr-border-0 before:shr-border-l before:shr-border-solid before:shr-border-default before:shr-content-[\"\"]',\n ],\n suffixIcon: 'shr-block',\n },\n})\n\nconst ActualMultiCombobox = <T,>(\n {\n items,\n selectedItems,\n name,\n disabled = false,\n required = false,\n error = false,\n creatable = false,\n placeholder = '',\n autoComplete,\n dropdownHelpMessage,\n isLoading,\n selectedItemEllipsis,\n width,\n dropdownWidth = 'auto',\n inputValue: controlledInputValue,\n className,\n onChange,\n onChangeInput,\n onAdd,\n onDelete,\n onSelect,\n onChangeSelected,\n onFocus,\n onBlur,\n onKeyPress,\n isItemSelected,\n noResultText,\n style,\n ...rest\n }: Props<T>,\n ref: Ref<HTMLInputElement>,\n) => {\n const triggerRef = useRef<HTMLDivElement>(null)\n const [isExpanded, setIsExpanded] = useState(false)\n const [highlighted, setHighlighted] = useState(false)\n const [uncontrolledInputValue, setUncontrolledInputValue] = useState('')\n const [isComposing, setIsComposing] = useState(false)\n\n const baseId = useId()\n const selectedListId = `${baseId}-selected`\n\n const isInputControlled = controlledInputValue !== undefined\n const inputValue = isInputControlled ? controlledInputValue : uncontrolledInputValue\n const setInputValueIfUncontrolled = isInputControlled ? NOOP : setUncontrolledInputValue\n const isInputEmpty = !inputValue\n\n const { options } = useMultiOptions({\n items,\n selected: selectedItems,\n creatable,\n inputValue,\n isItemSelected,\n })\n const inputRef = useRef<HTMLInputElement>(null)\n const deleteFrame = useAnimationFrame()\n const selectFrame = useAnimationFrame()\n\n // eslint-disable-next-line local-rules/best-practice-for-use-latest\n const latestForListBox = useLatest({\n onDelete,\n onChangeSelected,\n onSelect,\n onChangeInput,\n selectedItems,\n deleteFrame,\n selectFrame,\n })\n\n const listBoxFunctions = useMemo(() => {\n const handleDelete = (item: ComboboxItem<T>) => {\n const handlers: Array<(deletingItem: ComboboxItem<T>) => void> = []\n\n if (latestForListBox.onDelete) {\n handlers.push((deletingItem: ComboboxItem<T>) => latestForListBox.onDelete!(deletingItem))\n }\n if (latestForListBox.onChangeSelected) {\n handlers.push((deletingItem: ComboboxItem<T>) =>\n latestForListBox.onChangeSelected!(\n latestForListBox.selectedItems.filter(\n (selected) => !areItemsEqual(selected, deletingItem),\n ),\n ),\n )\n }\n\n if (handlers.length > 0) {\n // HINT: Dropdown系コンポーネント内でComboboxを使うと、選択肢がportalで表現されている関係上Dropdownが閉じてしまう\n // 処理を遅延させることで正常に閉じる/閉じないの判定を行えるようにする\n latestForListBox.deleteFrame.request(() => {\n handlers.forEach((h) => h(item))\n })\n }\n }\n\n return {\n cleanupListBoxCallbackRef: () => () => {\n latestForListBox.deleteFrame.cancel()\n latestForListBox.selectFrame.cancel()\n },\n handleDelete,\n handleSelect: (selected: ComboboxItem<T>) => {\n // HINT: Dropdown系コンポーネント内でComboboxを使うと、選択肢がportalで表現されている関係上Dropdownが閉じてしまう\n // 処理を遅延させることで正常に閉じる/閉じないの判定を行えるようにする\n latestForListBox.selectFrame.request(() => {\n const matchedSelectedItem = latestForListBox.selectedItems.find((item) =>\n areItemsEqual(item, selected),\n )\n\n if (matchedSelectedItem === undefined) {\n latestForListBox.onSelect?.(selected)\n latestForListBox.onChangeSelected?.(latestForListBox.selectedItems.concat(selected))\n\n // 制御コンポーネントの場合に親側でinputValueを更新できるように、選択時にonChangeInputを空文字で発火する\n latestForListBox.onChangeInput?.(EMPTY_INPUT_CHANGE_EVENT)\n } else if (matchedSelectedItem.deletable !== false) {\n handleDelete(selected)\n }\n })\n },\n }\n }, [latestForListBox])\n\n const { listBoxProps, activeOption, cleanupAddFrame, handleKeyDownListBox, listBoxId } =\n useListbox({\n options,\n dropdownHelpMessage,\n dropdownWidth,\n onAdd,\n onSelect: listBoxFunctions.handleSelect,\n isExpanded,\n isLoading,\n triggerRef,\n noResultText,\n })\n\n const latest = useLatest({\n onChange,\n onChangeInput,\n onFocus,\n onBlur,\n onKeyPress,\n disabled,\n isExpanded,\n highlighted,\n isComposing,\n isInputEmpty,\n selectedItems,\n setInputValueIfUncontrolled,\n handleKeyDownListBox,\n cleanupAddFrame,\n })\n\n const functions = useMemo(() => {\n const handleDelete = listBoxFunctions.handleDelete\n\n const getDeletionButtons = () => {\n if (triggerRef.current) {\n const buttons =\n triggerRef.current.querySelectorAll<HTMLButtonElement>(DELETE_BUTTON_CLASSNAME)\n\n if (buttons.length > 0) {\n const actualButtons = Array.from(buttons)\n\n return {\n buttons: actualButtons,\n currentIndex: actualButtons.indexOf(document.activeElement as HTMLButtonElement),\n }\n }\n }\n\n return null\n }\n\n const focusPrevDeletionButton = () => {\n const result = getDeletionButtons()\n\n if (!result) return\n\n const { buttons, currentIndex } = result\n\n if (currentIndex !== -1) {\n buttons[Math.max(currentIndex - 1, 0)].focus()\n } else if (inputRef.current?.selectionStart === 0) {\n buttons[buttons.length - 1].focus()\n }\n }\n\n const focusNextDeletionButton = () => {\n const result = getDeletionButtons()\n\n if (!result) return\n\n const { buttons, currentIndex } = result\n\n if (currentIndex === -1) return\n\n const nextIndex = currentIndex + 1\n\n if (nextIndex < buttons.length) {\n buttons[nextIndex].focus()\n } else {\n // キー入力が input に影響しないようにフォーカスタイミングを遅らせる\n setTimeout(() => {\n inputRef.current?.focus()\n })\n }\n }\n\n const focus = () => {\n latest.onFocus?.()\n setIsExpanded(true)\n }\n\n const blur = () => {\n if (latest.isExpanded) {\n latest.onBlur?.()\n setIsExpanded(false)\n }\n }\n\n return {\n handleDelete,\n blur,\n cleanupCallbackRef: () => latest.cleanupAddFrame,\n handleDelegateKeyDown: (e: KeyboardEvent<HTMLDivElement>) => {\n if (latest.isComposing) return\n\n if (ESCAPE_KEY_REGEX.test(e.key)) {\n if (latest.isExpanded) {\n e.stopPropagation()\n }\n\n blur()\n } else if (e.key === 'Tab') {\n if (latest.isExpanded) {\n // フォーカスがコンポーネントを抜けるように先に input をフォーカスしておく\n inputRef.current?.focus()\n }\n\n blur()\n } else if (ARROW_LEFT_KEY_REGEX.test(e.key)) {\n e.stopPropagation()\n focusPrevDeletionButton()\n } else if (ARROW_RIGHT_KEY_REGEX.test(e.key)) {\n e.stopPropagation()\n focusNextDeletionButton()\n } else if (\n e.key === 'Backspace' &&\n latest.isInputEmpty &&\n latest.selectedItems.length > 0 &&\n latest.selectedItems[latest.selectedItems.length - 1].deletable !== false\n ) {\n e.preventDefault()\n e.stopPropagation()\n\n const lastItem = latest.selectedItems[latest.selectedItems.length - 1]\n\n handleDelete(lastItem)\n setHighlighted(true)\n latest.setInputValueIfUncontrolled(innerText(lastItem.label))\n } else {\n e.stopPropagation()\n inputRef.current?.focus()\n }\n\n latest.handleKeyDownListBox(e)\n },\n handleDelegateClick: (e: MouseEvent<HTMLElement>) => {\n if (\n !latest.disabled &&\n !latest.isExpanded &&\n !findDelegateTarget(e, DELETE_BUTTON_CLASSNAME)\n ) {\n focus()\n }\n },\n handleChangeInput: (e: ChangeEvent<HTMLInputElement>) => {\n const handlers = [latest.onChange, latest.onChangeInput].filter((h) => !!h)\n\n handlers.forEach((h) => h(e))\n latest.setInputValueIfUncontrolled(e.currentTarget.value)\n },\n handleFocusInput: () => {\n if (!latest.isExpanded) {\n focus()\n }\n },\n handleCompositionStart: () => setIsComposing(true),\n handleCompositionEnd: () => setIsComposing(false),\n handleKeyDownInput: (e: KeyboardEvent<HTMLInputElement>) => {\n if (ARROW_UP_AND_DOWN_KEY_REGEX.test(e.key)) {\n // 上下キー入力はリストボックスの activeDescendant の移動に用いるため、input 内では作用させない\n e.preventDefault()\n }\n },\n // HINT: form内にcomboboxを設置 & 検索inputにfocusした状態で\n // アイテムをキーボードで選択し、Enterを押すとinput上でEnterを押したことになるため、\n // submitイベントが発生し、formが送信される場合がある\n handleDelegateKeyPress: (e: KeyboardEvent<HTMLInputElement>) => {\n preventDefaultWithPressEnter(e)\n latest.onKeyPress?.(e)\n },\n }\n }, [listBoxFunctions, latest])\n\n const listBoxCallbackRef = useAreaClickCallbackRef(\n isExpanded ? [triggerRef] : null,\n functions.blur,\n )\n\n const mergedInputRef = useMergeRefs(inputRef, listBoxFunctions.cleanupListBoxCallbackRef, ref)\n const mergedTriggerRef = useMergeRefs(triggerRef, functions.cleanupCallbackRef)\n\n useEffect(() => {\n if (latest.highlighted) {\n setHighlighted(false)\n inputRef.current?.select()\n } else {\n setInputValueIfUncontrolled('')\n }\n }, [selectedItems, setInputValueIfUncontrolled, latest])\n\n useEffect(() => {\n if (isExpanded) {\n inputRef.current?.focus()\n }\n }, [isExpanded, selectedItems, isInputControlled])\n\n const classNames = useMemo(() => {\n const {\n wrapper,\n inputArea,\n selectedList,\n inputWrapper,\n input,\n placeholderEl,\n suffixWrapper,\n suffixIcon,\n } = classNameGenerator()\n\n return {\n wrapper: wrapper({ className }),\n inputArea: inputArea(),\n selectedList: selectedList(),\n inputWrapper: inputWrapper(),\n input: input(),\n placeholder: placeholderEl(),\n suffixWrapper: suffixWrapper(),\n suffixIcon: suffixIcon(),\n }\n }, [className])\n\n const localized = useLocalize({\n selectedListAriaLabel: {\n id: 'smarthr-ui/MultiCombobox/selectedListAriaLabel',\n defaultText: '選択済みアイテム',\n },\n })\n\n return (\n // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions\n <div\n ref={mergedTriggerRef}\n role=\"group\"\n className={classNames.wrapper}\n style={{\n ...style,\n width: typeof width === 'number' ? `${width}px` : width,\n }}\n onClick={functions.handleDelegateClick}\n onKeyDown={functions.handleDelegateKeyDown}\n onKeyPress={functions.handleDelegateKeyPress}\n >\n <Scroller className={classNames.inputArea}>\n <ul\n id={selectedListId}\n className={classNames.selectedList}\n aria-label={localized.selectedListAriaLabel}\n >\n {selectedItems.map((selectedItem) => (\n <li key={`${selectedItem.label}-${innerText(selectedItem.value)}`}>\n <MultiSelectedItem\n disabled={disabled}\n item={selectedItem}\n enableEllipsis={selectedItemEllipsis}\n handleDelete={functions.handleDelete}\n />\n </li>\n ))}\n </ul>\n\n <div className={classNames.inputWrapper}>\n <input\n {...rest}\n ref={mergedInputRef}\n role=\"combobox\"\n type=\"text\"\n name={name}\n required={required && selectedItems.length === 0}\n disabled={disabled}\n value={inputValue}\n autoComplete={autoComplete ?? 'off'}\n tabIndex={0}\n className={classNames.input}\n aria-activedescendant={activeOption?.id}\n aria-controls={`${listBoxId} ${selectedListId}`}\n aria-haspopup=\"listbox\"\n aria-expanded={isExpanded}\n aria-invalid={error || undefined}\n aria-disabled={disabled}\n aria-autocomplete=\"list\"\n data-smarthr-ui-input=\"true\"\n onChange={functions.handleChangeInput}\n onFocus={functions.handleFocusInput}\n onCompositionStart={functions.handleCompositionStart}\n onCompositionEnd={functions.handleCompositionEnd}\n onKeyDown={functions.handleKeyDownInput}\n />\n </div>\n\n {selectedItems.length === 0 && placeholder && !isExpanded && (\n <p className={classNames.placeholder}>{placeholder}</p>\n )}\n </Scroller>\n\n <MemoizedCaretDown disabled={disabled} isExpanded={isExpanded} classNames={classNames} />\n\n <ListBox {...listBoxProps} callbackRef={listBoxCallbackRef} />\n </div>\n )\n}\n\nexport const MultiCombobox = genericsForwardRef(ActualMultiCombobox)\n\nconst MemoizedCaretDown = memo<{\n disabled: boolean\n isExpanded: boolean\n classNames: {\n suffixWrapper: string\n suffixIcon: string\n }\n}>(({ disabled, isExpanded, classNames }) => {\n const theme = useTheme()\n const caretIconColor = isExpanded\n ? theme.textColor.black\n : disabled\n ? theme.textColor.disabled\n : theme.textColor.grey\n\n return (\n <div className={classNames.suffixWrapper}>\n <FaCaretDownIcon color={caretIconColor} className={classNames.suffixIcon} />\n </div>\n )\n})\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA8EA;AAEA;AACE;;;AAGF;AAEA;AACA;AACA;AACA;AAEA;AACE;AACA;;AAGF;AAEA;AACE;AACE;;;;;;;;;;;;AAYC;AACD;AACA;AAEA;;;;;AAKC;AACD;;;;AAIC;AACD;AACA;;;AAGC;AACD;AACD;AACF;AAED;AAkCE;;;;;AAMA;AACA;AAEA;;;AAGA;AAEA;;AAEE;;;;AAID;AACD;AACA;AACA;;;;;;;;;;AAWC;AAED;AACE;;AAGE;AACE;;AAEF;AACE;;AASF;;;AAGE;AACE;AACF;;AAEJ;;AAGE;AACE;AACA;;;AAGF;;;AAGE;;AAKE;AACE;AACA;;AAGA;;AACK;;;AAGT;;;AAGN;AAEA;;;;;;;;;;AAWG;;;;;;;;;;;;;;;;AAiBF;AAED;AACE;;AAGE;;AAIE;;;AAII;;;;;AAMN;AACF;;AAGE;AAEA;;AAEA;AAEA;AACE;;;;;AAIJ;;AAGE;AAEA;;AAEA;;;AAIA;AAEA;AACE;;;;;AAIE;AACF;;AAEJ;;AAGE;;AAEF;;AAGE;AACE;;;AAGJ;;;;AAKE;AACA;;;;AAII;;;AAIA;;AACK;AACL;;AAEE;;AAGF;;;;AAGA;;;;AAGA;;AACK;AAEL;AACA;AACA;;;AAKA;;;;;;;AAOA;;AAGF;;AAEF;;;AAII;AAEA;;;AAGJ;;AAGE;;;;AAIA;AACE;;;AAGJ;AACA;AACA;;;;;;;;;AASA;;AAEE;;;AAGN;;AAOA;;;AAIE;;AAEE;;;;;;;;AAQA;;;AAIJ;;;AAaI;;;;;;;;;AASJ;;AAGE;AACE;AACA;AACD;AACF;;;AAIC;AAKI;AACA;AACD;AA8DP;;AAIA;AAQE;;AAEE;AACA;AACE;AACA;;AAON;;"}
1
+ {"version":3,"file":"MultiCombobox.js","sources":["../../../../src/components/Combobox/MultiCombobox/MultiCombobox.tsx"],"sourcesContent":["'use client'\n\nimport {\n type ChangeEvent,\n type ComponentPropsWithoutRef,\n type KeyboardEvent,\n type MouseEvent,\n type ReactNode,\n type Ref,\n memo,\n useEffect,\n useId,\n useMemo,\n useRef,\n useState,\n} from 'react'\nimport innerText from 'react-innertext'\nimport { tv } from 'tailwind-variants'\n\nimport { useAnimationFrame } from '../../../hooks/client/useAnimationFrame'\nimport { useAreaClickCallbackRef } from '../../../hooks/client/useAreaClickCallbackRef'\nimport { useMergeRefs } from '../../../hooks/client/useMergeRefs'\nimport { useTheme } from '../../../hooks/client/useTheme'\nimport { useLatest } from '../../../hooks/useLatest'\nimport { useLocalize } from '../../../intl'\nimport { findDelegateTarget } from '../../../libs/delegate'\nimport { genericsForwardRef } from '../../../libs/util'\nimport { FaCaretDownIcon } from '../../Icon'\nimport { Scroller } from '../../Scroller'\nimport { areItemsEqual } from '../helper'\nimport { ListBox, useListbox } from '../useListbox'\nimport { useMultiOptions } from '../useOptions'\n\nimport { DELETE_BUTTON_SELECTOR, MultiSelectedItem } from './MultiSelectedItem'\n\nimport type { ComboboxItem, BaseProps as ComboboxProps } from '../types'\n\ntype BaseProps<T> = ComboboxProps<T> & {\n /**\n * 選択されているアイテムのリスト\n */\n selectedItems: Array<ComboboxItem<T> & { deletable?: boolean }>\n /**\n * 選択されているアイテムのラベルを省略表示するかどうか\n */\n selectedItemEllipsis?: boolean\n /**\n * テキストボックスの `value` 属性の値。\n * `onChangeInput` と併せて設定することで、テキストボックスの挙動が制御可能になる。\n */\n inputValue?: string\n /**\n * 選択されているアイテムの削除ボタンがクリックされた時に発火するコールバック関数\n */\n onDelete?: (item: ComboboxItem<T>) => void\n /**\n * 選択されているアイテムのリストが変わった時に発火するコールバック関数\n */\n onChangeSelected?: (selectedItems: Array<ComboboxItem<T>>) => void\n /**\n * コンポーネントがフォーカスされたときに発火するコールバック関数\n */\n onFocus?: () => void\n /**\n * コンポーネントからフォーカスが外れた時に発火するコールバック関数\n */\n onBlur?: () => void\n /**\n * アイテムが選択されたときに選択済みかどうかを判定するコールバック関数/\n */\n isItemSelected?: (targetItem: ComboboxItem<T>, selectedItems: Array<ComboboxItem<T>>) => boolean\n /**\n * 検索結果が0件の時に表示するコンテンツ\n */\n noResultText?: ReactNode\n}\ntype Props<T> = BaseProps<T> & Omit<ComponentPropsWithoutRef<'input'>, keyof BaseProps<unknown>>\n\nconst NOOP = () => undefined\n\nconst preventDefaultWithPressEnter = (e: KeyboardEvent<HTMLInputElement>) => {\n if (e.key === 'Enter') {\n e.preventDefault()\n }\n}\n\nconst ESCAPE_KEY_REGEX = /^Esc(ape)?$/\nconst ARROW_LEFT_KEY_REGEX = /^(Arrow)?Left$/\nconst ARROW_RIGHT_KEY_REGEX = /^(Arrow)?Right/\nconst ARROW_UP_AND_DOWN_KEY_REGEX = /^(Arrow)?(Up|Down)$/\n\nconst EMPTY_INPUT_CHANGE_EVENT = {\n currentTarget: { value: '' },\n target: { value: '' },\n} as ChangeEvent<HTMLInputElement>\n\nconst DELETE_BUTTON_CLASSNAME = `.${DELETE_BUTTON_SELECTOR}`\n\nconst classNameGenerator = tv({\n slots: {\n wrapper: [\n 'smarthr-ui-MultiCombobox',\n 'shr-box-border shr-inline-flex shr-min-w-[15em] shr-rounded-m shr-border shr-border-solid shr-px-0.5 shr-py-0.25 shr-align-bottom',\n 'contrast-more:shr-border-high-contrast',\n 'has-[[role=combobox][aria-expanded=true]]:shr-focus-indicator',\n 'shr-cursor-text shr-border-default shr-bg-white',\n 'has-[[role=combobox]:disabled]:shr-cursor-not-allowed',\n 'has-[[role=combobox]:disabled]:shr-border-default/50',\n 'has-[[role=combobox]:disabled]:shr-bg-white-darken',\n 'has-[[role=combobox]:disabled]:shr-text-disabled',\n // HINT: disabled と詳細度が同じ [0,2,0] のため、CSS ソース順でこちらを後に置くことで error 時の border 色を優先させる\n 'has-[[role=combobox][aria-invalid]]:shr-border-danger',\n ],\n inputArea: 'shr-flex shr-flex-1 shr-flex-wrap shr-gap-0.5',\n selectedList:\n 'smarthr-ui-MultiCombobox-selectedList shr-contents shr-list-none [&_li]:shr-min-w-0',\n inputWrapper: [\n 'shr-flex shr-flex-1 shr-items-center',\n 'has-[[role=combobox][aria-expanded=false]]:shr-pointer-events-none',\n 'has-[[role=combobox][aria-expanded=false]]:shr-absolute',\n 'has-[[role=combobox][aria-expanded=false]]:shr-opacity-0',\n ],\n input: [\n 'smarthr-ui-MultiCombobox-input',\n 'shr-w-full shr-min-w-[5em] shr-border-none shr-text-base shr-text-black shr-outline-none shr-outline-0',\n 'disabled:shr-hidden',\n ],\n placeholderEl: 'smarthr-ui-MultiCombobox-placeholder shr-my-0 shr-self-center',\n suffixWrapper: [\n 'shr-relative -shr-me-0.5 shr-ms-0.5 shr-p-0.5',\n 'before:shr-absolute before:shr-inset-x-0 before:shr-inset-y-0.25 before:shr-w-0 before:shr-border-0 before:shr-border-l before:shr-border-solid before:shr-border-default before:shr-content-[\"\"]',\n ],\n suffixIcon: 'shr-block',\n },\n})\n\nconst ActualMultiCombobox = <T,>(\n {\n items,\n selectedItems,\n name,\n disabled = false,\n required = false,\n error = false,\n creatable = false,\n placeholder = '',\n autoComplete,\n dropdownHelpMessage,\n isLoading,\n selectedItemEllipsis,\n width,\n dropdownWidth = 'auto',\n inputValue: controlledInputValue,\n className,\n onChange,\n onChangeInput,\n onAdd,\n onDelete,\n onSelect,\n onChangeSelected,\n onFocus,\n onBlur,\n onKeyPress,\n isItemSelected,\n noResultText,\n style,\n ...rest\n }: Props<T>,\n ref: Ref<HTMLInputElement>,\n) => {\n const triggerRef = useRef<HTMLDivElement>(null)\n const [isExpanded, setIsExpanded] = useState(false)\n const [highlighted, setHighlighted] = useState(false)\n const [uncontrolledInputValue, setUncontrolledInputValue] = useState('')\n const [isComposing, setIsComposing] = useState(false)\n\n const baseId = useId()\n const selectedListId = `${baseId}-selected`\n\n const isInputControlled = controlledInputValue !== undefined\n const inputValue = isInputControlled ? controlledInputValue : uncontrolledInputValue\n const setInputValueIfUncontrolled = isInputControlled ? NOOP : setUncontrolledInputValue\n const isInputEmpty = !inputValue\n\n const { options } = useMultiOptions({\n items,\n selected: selectedItems,\n creatable,\n inputValue,\n isItemSelected,\n })\n const inputRef = useRef<HTMLInputElement>(null)\n const deleteFrame = useAnimationFrame()\n const selectFrame = useAnimationFrame()\n\n // eslint-disable-next-line local-rules/best-practice-for-use-latest\n const latestForListBox = useLatest({\n onDelete,\n onChangeSelected,\n onSelect,\n onChangeInput,\n selectedItems,\n deleteFrame,\n selectFrame,\n })\n\n const listBoxFunctions = useMemo(() => {\n const handleDelete = (item: ComboboxItem<T>) => {\n const handlers: Array<(deletingItem: ComboboxItem<T>) => void> = []\n\n if (latestForListBox.onDelete) {\n handlers.push((deletingItem: ComboboxItem<T>) => latestForListBox.onDelete!(deletingItem))\n }\n if (latestForListBox.onChangeSelected) {\n handlers.push((deletingItem: ComboboxItem<T>) =>\n latestForListBox.onChangeSelected!(\n latestForListBox.selectedItems.filter(\n (selected) => !areItemsEqual(selected, deletingItem),\n ),\n ),\n )\n }\n\n if (handlers.length > 0) {\n // HINT: Dropdown系コンポーネント内でComboboxを使うと、選択肢がportalで表現されている関係上Dropdownが閉じてしまう\n // 処理を遅延させることで正常に閉じる/閉じないの判定を行えるようにする\n latestForListBox.deleteFrame.request(() => {\n handlers.forEach((h) => h(item))\n })\n }\n }\n\n return {\n cleanupListBoxCallbackRef: () => () => {\n latestForListBox.deleteFrame.cancel()\n latestForListBox.selectFrame.cancel()\n },\n handleDelete,\n handleSelect: (selected: ComboboxItem<T>) => {\n // HINT: Dropdown系コンポーネント内でComboboxを使うと、選択肢がportalで表現されている関係上Dropdownが閉じてしまう\n // 処理を遅延させることで正常に閉じる/閉じないの判定を行えるようにする\n latestForListBox.selectFrame.request(() => {\n const matchedSelectedItem = latestForListBox.selectedItems.find((item) =>\n areItemsEqual(item, selected),\n )\n\n if (matchedSelectedItem === undefined) {\n latestForListBox.onSelect?.(selected)\n latestForListBox.onChangeSelected?.(latestForListBox.selectedItems.concat(selected))\n\n // 制御コンポーネントの場合に親側でinputValueを更新できるように、選択時にonChangeInputを空文字で発火する\n latestForListBox.onChangeInput?.(EMPTY_INPUT_CHANGE_EVENT)\n } else if (matchedSelectedItem.deletable !== false) {\n handleDelete(selected)\n }\n })\n },\n }\n }, [latestForListBox])\n\n const { listBoxProps, activeOption, cleanupAddFrame, handleKeyDownListBox, listBoxId } =\n useListbox({\n options,\n dropdownHelpMessage,\n dropdownWidth,\n onAdd,\n onSelect: listBoxFunctions.handleSelect,\n isExpanded,\n isLoading,\n triggerRef,\n noResultText,\n })\n\n const latest = useLatest({\n onChange,\n onChangeInput,\n onFocus,\n onBlur,\n onKeyPress,\n disabled,\n isExpanded,\n highlighted,\n isComposing,\n isInputEmpty,\n selectedItems,\n setInputValueIfUncontrolled,\n handleKeyDownListBox,\n cleanupAddFrame,\n })\n\n const functions = useMemo(() => {\n const handleDelete = listBoxFunctions.handleDelete\n\n const getDeletionButtons = () => {\n if (triggerRef.current) {\n const buttons =\n triggerRef.current.querySelectorAll<HTMLButtonElement>(DELETE_BUTTON_CLASSNAME)\n\n if (buttons.length > 0) {\n const actualButtons = Array.from(buttons)\n\n return {\n buttons: actualButtons,\n currentIndex: actualButtons.indexOf(document.activeElement as HTMLButtonElement),\n }\n }\n }\n\n return null\n }\n\n const focusPrevDeletionButton = () => {\n const result = getDeletionButtons()\n\n if (!result) return\n\n const { buttons, currentIndex } = result\n\n if (currentIndex !== -1) {\n buttons[Math.max(currentIndex - 1, 0)].focus()\n } else if (inputRef.current?.selectionStart === 0) {\n buttons[buttons.length - 1].focus()\n }\n }\n\n const focusNextDeletionButton = () => {\n const result = getDeletionButtons()\n\n if (!result) return\n\n const { buttons, currentIndex } = result\n\n if (currentIndex === -1) return\n\n const nextIndex = currentIndex + 1\n\n if (nextIndex < buttons.length) {\n buttons[nextIndex].focus()\n } else {\n // キー入力が input に影響しないようにフォーカスタイミングを遅らせる\n setTimeout(() => {\n inputRef.current?.focus()\n })\n }\n }\n\n const focus = () => {\n latest.onFocus?.()\n setIsExpanded(true)\n }\n\n const blur = () => {\n if (latest.isExpanded) {\n latest.onBlur?.()\n setIsExpanded(false)\n }\n }\n\n return {\n handleDelete,\n blur,\n cleanupCallbackRef: () => latest.cleanupAddFrame,\n handleDelegateKeyDown: (e: KeyboardEvent<HTMLDivElement>) => {\n if (latest.isComposing) return\n\n if (ESCAPE_KEY_REGEX.test(e.key)) {\n if (latest.isExpanded) {\n e.stopPropagation()\n }\n\n blur()\n } else if (e.key === 'Tab') {\n if (latest.isExpanded) {\n // フォーカスがコンポーネントを抜けるように先に input をフォーカスしておく\n inputRef.current?.focus()\n }\n\n blur()\n } else if (ARROW_LEFT_KEY_REGEX.test(e.key)) {\n e.stopPropagation()\n focusPrevDeletionButton()\n } else if (ARROW_RIGHT_KEY_REGEX.test(e.key)) {\n e.stopPropagation()\n focusNextDeletionButton()\n } else if (\n e.key === 'Backspace' &&\n latest.isInputEmpty &&\n latest.selectedItems.length > 0 &&\n latest.selectedItems[latest.selectedItems.length - 1].deletable !== false\n ) {\n e.preventDefault()\n e.stopPropagation()\n\n const lastItem = latest.selectedItems[latest.selectedItems.length - 1]\n\n handleDelete(lastItem)\n setHighlighted(true)\n latest.setInputValueIfUncontrolled(innerText(lastItem.label))\n } else {\n e.stopPropagation()\n inputRef.current?.focus()\n }\n\n latest.handleKeyDownListBox(e)\n },\n handleDelegateClick: (e: MouseEvent<HTMLElement>) => {\n if (\n !latest.disabled &&\n !latest.isExpanded &&\n !findDelegateTarget(e, DELETE_BUTTON_CLASSNAME)\n ) {\n focus()\n }\n },\n handleChangeInput: (e: ChangeEvent<HTMLInputElement>) => {\n const handlers = [latest.onChange, latest.onChangeInput].filter((h) => !!h)\n\n handlers.forEach((h) => h(e))\n latest.setInputValueIfUncontrolled(e.currentTarget.value)\n },\n handleFocusInput: () => {\n if (!latest.isExpanded) {\n focus()\n }\n },\n handleCompositionStart: () => setIsComposing(true),\n handleCompositionEnd: () => setIsComposing(false),\n handleKeyDownInput: (e: KeyboardEvent<HTMLInputElement>) => {\n if (ARROW_UP_AND_DOWN_KEY_REGEX.test(e.key)) {\n // 上下キー入力はリストボックスの activeDescendant の移動に用いるため、input 内では作用させない\n e.preventDefault()\n }\n },\n // HINT: form内にcomboboxを設置 & 検索inputにfocusした状態で\n // アイテムをキーボードで選択し、Enterを押すとinput上でEnterを押したことになるため、\n // submitイベントが発生し、formが送信される場合がある\n handleDelegateKeyPress: (e: KeyboardEvent<HTMLInputElement>) => {\n preventDefaultWithPressEnter(e)\n latest.onKeyPress?.(e)\n },\n }\n }, [listBoxFunctions, latest])\n\n const listBoxCallbackRef = useAreaClickCallbackRef(\n isExpanded ? [triggerRef] : null,\n functions.blur,\n )\n\n const mergedInputRef = useMergeRefs(inputRef, listBoxFunctions.cleanupListBoxCallbackRef, ref)\n const mergedTriggerRef = useMergeRefs(triggerRef, functions.cleanupCallbackRef)\n\n useEffect(() => {\n if (latest.highlighted) {\n setHighlighted(false)\n inputRef.current?.select()\n } else {\n setInputValueIfUncontrolled('')\n }\n }, [selectedItems, setInputValueIfUncontrolled, latest])\n\n useEffect(() => {\n if (isExpanded) {\n inputRef.current?.focus()\n }\n }, [isExpanded, selectedItems, isInputControlled])\n\n const classNames = useMemo(() => {\n const {\n wrapper,\n inputArea,\n selectedList,\n inputWrapper,\n input,\n placeholderEl,\n suffixWrapper,\n suffixIcon,\n } = classNameGenerator()\n\n return {\n wrapper: wrapper({ className }),\n inputArea: inputArea(),\n selectedList: selectedList(),\n inputWrapper: inputWrapper(),\n input: input(),\n placeholder: placeholderEl(),\n suffixWrapper: suffixWrapper(),\n suffixIcon: suffixIcon(),\n }\n }, [className])\n\n const localized = useLocalize({\n selectedListAriaLabel: {\n id: 'smarthr-ui/MultiCombobox/selectedListAriaLabel',\n defaultText: '選択済みアイテム',\n },\n })\n\n const errorAttr = error || undefined\n\n return (\n // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions\n <div\n ref={mergedTriggerRef}\n role=\"group\"\n className={classNames.wrapper}\n style={{\n ...style,\n width: typeof width === 'number' ? `${width}px` : width,\n }}\n onClick={functions.handleDelegateClick}\n onKeyDown={functions.handleDelegateKeyDown}\n onKeyPress={functions.handleDelegateKeyPress}\n >\n <Scroller className={classNames.inputArea}>\n <ul\n id={selectedListId}\n className={classNames.selectedList}\n aria-label={localized.selectedListAriaLabel}\n >\n {selectedItems.map((selectedItem) => (\n <li key={`${selectedItem.label}-${innerText(selectedItem.value)}`}>\n <MultiSelectedItem\n disabled={disabled}\n item={selectedItem}\n enableEllipsis={selectedItemEllipsis}\n handleDelete={functions.handleDelete}\n />\n </li>\n ))}\n </ul>\n\n <div className={classNames.inputWrapper}>\n <input\n {...rest}\n ref={mergedInputRef}\n role=\"combobox\"\n type=\"text\"\n name={name}\n required={required && selectedItems.length === 0}\n disabled={disabled}\n value={inputValue}\n autoComplete={autoComplete ?? 'off'}\n tabIndex={0}\n className={classNames.input}\n aria-activedescendant={activeOption?.id}\n aria-controls={`${listBoxId} ${selectedListId}`}\n aria-haspopup=\"listbox\"\n aria-expanded={isExpanded}\n aria-invalid={errorAttr}\n aria-disabled={disabled}\n aria-autocomplete=\"list\"\n data-smarthr-ui-input-error={errorAttr}\n data-smarthr-ui-input=\"true\"\n onChange={functions.handleChangeInput}\n onFocus={functions.handleFocusInput}\n onCompositionStart={functions.handleCompositionStart}\n onCompositionEnd={functions.handleCompositionEnd}\n onKeyDown={functions.handleKeyDownInput}\n />\n </div>\n\n {selectedItems.length === 0 && placeholder && !isExpanded && (\n <p className={classNames.placeholder}>{placeholder}</p>\n )}\n </Scroller>\n\n <MemoizedCaretDown disabled={disabled} isExpanded={isExpanded} classNames={classNames} />\n\n <ListBox {...listBoxProps} callbackRef={listBoxCallbackRef} />\n </div>\n )\n}\n\nexport const MultiCombobox = genericsForwardRef(ActualMultiCombobox)\n\nconst MemoizedCaretDown = memo<{\n disabled: boolean\n isExpanded: boolean\n classNames: {\n suffixWrapper: string\n suffixIcon: string\n }\n}>(({ disabled, isExpanded, classNames }) => {\n const theme = useTheme()\n const caretIconColor = isExpanded\n ? theme.textColor.black\n : disabled\n ? theme.textColor.disabled\n : theme.textColor.grey\n\n return (\n <div className={classNames.suffixWrapper}>\n <FaCaretDownIcon color={caretIconColor} className={classNames.suffixIcon} />\n </div>\n )\n})\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA8EA;AAEA;AACE;;;AAGF;AAEA;AACA;AACA;AACA;AAEA;AACE;AACA;;AAGF;AAEA;AACE;AACE;;;;;;;;;;;;AAYC;AACD;AACA;AAEA;;;;;AAKC;AACD;;;;AAIC;AACD;AACA;;;AAGC;AACD;AACD;AACF;AAED;AAkCE;;;;;AAMA;AACA;AAEA;;;AAGA;AAEA;;AAEE;;;;AAID;AACD;AACA;AACA;;;;;;;;;;AAWC;AAED;AACE;;AAGE;AACE;;AAEF;AACE;;AASF;;;AAGE;AACE;AACF;;AAEJ;;AAGE;AACE;AACA;;;AAGF;;;AAGE;;AAKE;AACE;AACA;;AAGA;;AACK;;;AAGT;;;AAGN;AAEA;;;;;;;;;;AAWG;;;;;;;;;;;;;;;;AAiBF;AAED;AACE;;AAGE;;AAIE;;;AAII;;;;;AAMN;AACF;;AAGE;AAEA;;AAEA;AAEA;AACE;;;;;AAIJ;;AAGE;AAEA;;AAEA;;;AAIA;AAEA;AACE;;;;;AAIE;AACF;;AAEJ;;AAGE;;AAEF;;AAGE;AACE;;;AAGJ;;;;AAKE;AACA;;;;AAII;;;AAIA;;AACK;AACL;;AAEE;;AAGF;;;;AAGA;;;;AAGA;;AACK;AAEL;AACA;AACA;;;AAKA;;;;;;;AAOA;;AAGF;;AAEF;;;AAII;AAEA;;;AAGJ;;AAGE;;;;AAIA;AACE;;;AAGJ;AACA;AACA;;;;;;;;;AASA;;AAEE;;;AAGN;;AAOA;;;AAIE;;AAEE;;;;;;;;AAQA;;;AAIJ;;;AAaI;;;;;;;;;AASJ;;AAGE;AACE;AACA;AACD;AACF;AAED;;;AAIE;AAKI;AACA;AACD;AA+DP;;AAIA;AAQE;;AAEE;AACA;AACE;AACA;;AAON;;"}
@@ -77,9 +77,10 @@ const DropZone = React.forwardRef(({ children, onSelectFiles, multiple = true, d
77
77
  },
78
78
  };
79
79
  }, [latest]);
80
+ const errorAttr = error || undefined;
80
81
  return (
81
82
  // eslint-disable-next-line jsx-a11y/no-static-element-interactions
82
- jsxRuntime.jsxs("div", { className: classNames.wrapper, "data-files-dragged-over": filesDraggedOver || undefined, onDrop: functions.handleDrop, onDragOver: functions.handleDragOver, onDragLeave: functions.handleDragLeave, children: [children, jsxRuntime.jsx(SelectButton, { disabled: disabled, error: error, className: classNames.button, handleClick: functions.handleClickButton, label: selectButtonLabel }), jsxRuntime.jsx(components_VisuallyHiddenText_VisuallyHiddenText.VisuallyHiddenText, { children: jsxRuntime.jsx("input", { ...rest, ref: ref, type: "file", disabled: disabled, multiple: multiple, tabIndex: -1, "aria-invalid": error || undefined, "data-smarthr-ui-input": "true", onChange: functions.handleChange }) })] }));
83
+ jsxRuntime.jsxs("div", { className: classNames.wrapper, "data-files-dragged-over": filesDraggedOver || undefined, onDrop: functions.handleDrop, onDragOver: functions.handleDragOver, onDragLeave: functions.handleDragLeave, children: [children, jsxRuntime.jsx(SelectButton, { disabled: disabled, error: error, className: classNames.button, handleClick: functions.handleClickButton, label: selectButtonLabel }), jsxRuntime.jsx(components_VisuallyHiddenText_VisuallyHiddenText.VisuallyHiddenText, { children: jsxRuntime.jsx("input", { ...rest, ref: ref, type: "file", disabled: disabled, multiple: multiple, tabIndex: -1, "aria-invalid": errorAttr, "data-smarthr-ui-input-error": errorAttr, "data-smarthr-ui-input": "true", onChange: functions.handleChange }) })] }));
83
84
  });
84
85
  const SelectButton = React.memo(({ label, disabled, error, handleClick, className }) => (jsxRuntime.jsx(components_Button_Button.Button, { disabled: disabled, className: className, "data-error": error || undefined, onClick: handleClick, prefix: jsxRuntime.jsx(components_Icon_FaIcon.FaFolderOpenIcon, {}), children: label || jsxRuntime.jsx(intl_Localizer.Localizer, { id: "smarthr-ui/DropZone/selectButtonLabel", defaultText: "\u30D5\u30A1\u30A4\u30EB\u3092\u9078\u629E" }) })));
85
86
 
@@ -1 +1 @@
1
- {"version":3,"file":"DropZone.cjs","sources":["../../../../src/components/DropZone/client/DropZone.tsx"],"sourcesContent":["'use client'\n\nimport {\n type ChangeEvent,\n type ComponentPropsWithRef,\n type DragEvent,\n type MouseEvent,\n type PropsWithChildren,\n forwardRef,\n memo,\n useMemo,\n useState,\n} from 'react'\nimport { tv } from 'tailwind-variants'\n\nimport { useLatest } from '../../../hooks/useLatest'\nimport { Localizer } from '../../../intl'\nimport { Button } from '../../Button'\nimport { FaFolderOpenIcon } from '../../Icon'\nimport { VisuallyHiddenText } from '../../VisuallyHiddenText'\n\nconst classNameGenerator = tv({\n slots: {\n wrapper: [\n 'smarthr-ui-DropZone',\n 'shr-relative',\n 'shr-border-shorthand shr-flex shr-flex-col shr-items-center shr-justify-center shr-bg-column shr-p-2.5',\n 'has-[.smarthr-ui-DropZone-Button[aria-disabled]]:shr-cursor-not-allowed',\n '[&:not([data-files-dragged-over])]:shr-border-dashed',\n 'data-[files-dragged-over]:shr-border-main',\n ],\n button: ['smarthr-ui-DropZone-Button', 'data-[error]:shr-border-danger'],\n },\n})\n\ntype BaseProps = PropsWithChildren<{\n /**\n * ボタンまたはドラッグ&ドロップでファイルが追加された時に発火するコールバック関数\n */\n onSelectFiles: (\n e: DragEvent<HTMLElement> | ChangeEvent<HTMLInputElement>,\n files: FileList | null,\n ) => void\n /**\n * 許可するファイル型を表す1つ以上の固有ファイル型指定子\n * <b>(ドラッグ&ドロップの挙動には影響しません)</b>\n */\n accept?: string\n /** 複数ファイルを選択できるかどうか */\n multiple?: boolean\n name?: string\n disabled?: boolean\n /** フォームにエラーがあるかどうか */\n error?: boolean\n /** ファイル選択ボタンのラベル */\n selectButtonLabel?: string\n}>\ntype Props = BaseProps & Omit<ComponentPropsWithRef<'div'>, keyof BaseProps>\n\nconst overrideEventDefault = (e: DragEvent<HTMLElement>) => {\n e.preventDefault()\n e.stopPropagation()\n}\n\nexport const DropZone = forwardRef<HTMLInputElement, Props>(\n (\n {\n children,\n onSelectFiles,\n multiple = true,\n disabled,\n error,\n selectButtonLabel,\n className,\n ...rest\n },\n ref,\n ) => {\n const [filesDraggedOver, setFilesDraggedOver] = useState(false)\n\n const classNames = useMemo(() => {\n const { wrapper, button } = classNameGenerator()\n return {\n wrapper: wrapper({ className }),\n button: button(),\n }\n }, [className])\n\n const latest = useLatest({ onSelectFiles })\n\n const functions = useMemo(() => {\n const inputFileSelector = 'input[type=\"file\"][data-smarthr-ui-input=\"true\"]'\n\n return {\n handleDrop: (e: DragEvent<HTMLElement>) => {\n overrideEventDefault(e)\n setFilesDraggedOver(false)\n\n if (e.dataTransfer.types.includes('Files')) {\n const input = e.currentTarget.querySelector<HTMLInputElement>(inputFileSelector)\n\n if (input) {\n input.files = e.dataTransfer.files\n }\n latest.onSelectFiles(e, e.dataTransfer.files)\n }\n },\n handleDragOver: (e: DragEvent<HTMLElement>) => {\n overrideEventDefault(e)\n setFilesDraggedOver(true)\n },\n handleDragLeave: () => {\n setFilesDraggedOver(false)\n },\n handleChange: (e: ChangeEvent<HTMLInputElement>) => {\n latest.onSelectFiles(e, e.target.files)\n },\n handleClickButton: (e: MouseEvent<HTMLButtonElement>) => {\n e.currentTarget\n .closest('.smarthr-ui-DropZone')\n ?.querySelector<HTMLInputElement>(inputFileSelector)\n ?.click()\n },\n }\n }, [latest])\n\n return (\n // eslint-disable-next-line jsx-a11y/no-static-element-interactions\n <div\n className={classNames.wrapper}\n data-files-dragged-over={filesDraggedOver || undefined}\n onDrop={functions.handleDrop}\n onDragOver={functions.handleDragOver}\n onDragLeave={functions.handleDragLeave}\n >\n {children}\n <SelectButton\n disabled={disabled}\n error={error}\n className={classNames.button}\n handleClick={functions.handleClickButton}\n label={selectButtonLabel}\n />\n <VisuallyHiddenText>\n {/* TODO: この input にアクセシブルネームが設定されていない。VisuallyHiddenText で視覚的に隠されているが aria-hidden ではないためアクセシビリティツリーに残る。aria-label 等で適切なラベルを付与する必要がある */}\n {/* eslint-disable-next-line smarthr/a11y-input-in-form-control */}\n <input\n {...rest}\n ref={ref}\n type=\"file\"\n disabled={disabled}\n multiple={multiple}\n tabIndex={-1}\n aria-invalid={error || undefined}\n data-smarthr-ui-input=\"true\"\n onChange={functions.handleChange}\n />\n </VisuallyHiddenText>\n </div>\n )\n },\n)\n\nconst SelectButton = memo<{\n label?: string\n disabled?: boolean\n error?: boolean\n handleClick: (e: MouseEvent<HTMLButtonElement>) => void\n className: string\n}>(({ label, disabled, error, handleClick, className }) => (\n <Button\n disabled={disabled}\n className={className}\n data-error={error || undefined}\n onClick={handleClick}\n prefix={<FaFolderOpenIcon />}\n >\n {label || <Localizer id=\"smarthr-ui/DropZone/selectButtonLabel\" defaultText=\"ファイルを選択\" />}\n </Button>\n))\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAqBA;AACE;AACE;;;;;;;AAOC;AACD;AACD;AACF;AA0BD;;;AAGA;AAEO;;AAgBH;;;AAGI;;;AAGJ;;AAIA;;;AAII;;;;;;;;;;;AAaA;;;;;;;AAOA;;;AAGA;AACE;;;;;;AAMN;;;;AAoCF;AAGF;;"}
1
+ {"version":3,"file":"DropZone.cjs","sources":["../../../../src/components/DropZone/client/DropZone.tsx"],"sourcesContent":["'use client'\n\nimport {\n type ChangeEvent,\n type ComponentPropsWithRef,\n type DragEvent,\n type MouseEvent,\n type PropsWithChildren,\n forwardRef,\n memo,\n useMemo,\n useState,\n} from 'react'\nimport { tv } from 'tailwind-variants'\n\nimport { useLatest } from '../../../hooks/useLatest'\nimport { Localizer } from '../../../intl'\nimport { Button } from '../../Button'\nimport { FaFolderOpenIcon } from '../../Icon'\nimport { VisuallyHiddenText } from '../../VisuallyHiddenText'\n\nconst classNameGenerator = tv({\n slots: {\n wrapper: [\n 'smarthr-ui-DropZone',\n 'shr-relative',\n 'shr-border-shorthand shr-flex shr-flex-col shr-items-center shr-justify-center shr-bg-column shr-p-2.5',\n 'has-[.smarthr-ui-DropZone-Button[aria-disabled]]:shr-cursor-not-allowed',\n '[&:not([data-files-dragged-over])]:shr-border-dashed',\n 'data-[files-dragged-over]:shr-border-main',\n ],\n button: ['smarthr-ui-DropZone-Button', 'data-[error]:shr-border-danger'],\n },\n})\n\ntype BaseProps = PropsWithChildren<{\n /**\n * ボタンまたはドラッグ&ドロップでファイルが追加された時に発火するコールバック関数\n */\n onSelectFiles: (\n e: DragEvent<HTMLElement> | ChangeEvent<HTMLInputElement>,\n files: FileList | null,\n ) => void\n /**\n * 許可するファイル型を表す1つ以上の固有ファイル型指定子\n * <b>(ドラッグ&ドロップの挙動には影響しません)</b>\n */\n accept?: string\n /** 複数ファイルを選択できるかどうか */\n multiple?: boolean\n name?: string\n disabled?: boolean\n /** フォームにエラーがあるかどうか */\n error?: boolean\n /** ファイル選択ボタンのラベル */\n selectButtonLabel?: string\n}>\ntype Props = BaseProps & Omit<ComponentPropsWithRef<'div'>, keyof BaseProps>\n\nconst overrideEventDefault = (e: DragEvent<HTMLElement>) => {\n e.preventDefault()\n e.stopPropagation()\n}\n\nexport const DropZone = forwardRef<HTMLInputElement, Props>(\n (\n {\n children,\n onSelectFiles,\n multiple = true,\n disabled,\n error,\n selectButtonLabel,\n className,\n ...rest\n },\n ref,\n ) => {\n const [filesDraggedOver, setFilesDraggedOver] = useState(false)\n\n const classNames = useMemo(() => {\n const { wrapper, button } = classNameGenerator()\n return {\n wrapper: wrapper({ className }),\n button: button(),\n }\n }, [className])\n\n const latest = useLatest({ onSelectFiles })\n\n const functions = useMemo(() => {\n const inputFileSelector = 'input[type=\"file\"][data-smarthr-ui-input=\"true\"]'\n\n return {\n handleDrop: (e: DragEvent<HTMLElement>) => {\n overrideEventDefault(e)\n setFilesDraggedOver(false)\n\n if (e.dataTransfer.types.includes('Files')) {\n const input = e.currentTarget.querySelector<HTMLInputElement>(inputFileSelector)\n\n if (input) {\n input.files = e.dataTransfer.files\n }\n latest.onSelectFiles(e, e.dataTransfer.files)\n }\n },\n handleDragOver: (e: DragEvent<HTMLElement>) => {\n overrideEventDefault(e)\n setFilesDraggedOver(true)\n },\n handleDragLeave: () => {\n setFilesDraggedOver(false)\n },\n handleChange: (e: ChangeEvent<HTMLInputElement>) => {\n latest.onSelectFiles(e, e.target.files)\n },\n handleClickButton: (e: MouseEvent<HTMLButtonElement>) => {\n e.currentTarget\n .closest('.smarthr-ui-DropZone')\n ?.querySelector<HTMLInputElement>(inputFileSelector)\n ?.click()\n },\n }\n }, [latest])\n\n const errorAttr = error || undefined\n\n return (\n // eslint-disable-next-line jsx-a11y/no-static-element-interactions\n <div\n className={classNames.wrapper}\n data-files-dragged-over={filesDraggedOver || undefined}\n onDrop={functions.handleDrop}\n onDragOver={functions.handleDragOver}\n onDragLeave={functions.handleDragLeave}\n >\n {children}\n <SelectButton\n disabled={disabled}\n error={error}\n className={classNames.button}\n handleClick={functions.handleClickButton}\n label={selectButtonLabel}\n />\n <VisuallyHiddenText>\n {/* TODO: この input にアクセシブルネームが設定されていない。VisuallyHiddenText で視覚的に隠されているが aria-hidden ではないためアクセシビリティツリーに残る。aria-label 等で適切なラベルを付与する必要がある */}\n {/* eslint-disable-next-line smarthr/a11y-input-in-form-control */}\n <input\n {...rest}\n ref={ref}\n type=\"file\"\n disabled={disabled}\n multiple={multiple}\n tabIndex={-1}\n aria-invalid={errorAttr}\n data-smarthr-ui-input-error={errorAttr}\n data-smarthr-ui-input=\"true\"\n onChange={functions.handleChange}\n />\n </VisuallyHiddenText>\n </div>\n )\n },\n)\n\nconst SelectButton = memo<{\n label?: string\n disabled?: boolean\n error?: boolean\n handleClick: (e: MouseEvent<HTMLButtonElement>) => void\n className: string\n}>(({ label, disabled, error, handleClick, className }) => (\n <Button\n disabled={disabled}\n className={className}\n data-error={error || undefined}\n onClick={handleClick}\n prefix={<FaFolderOpenIcon />}\n >\n {label || <Localizer id=\"smarthr-ui/DropZone/selectButtonLabel\" defaultText=\"ファイルを選択\" />}\n </Button>\n))\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAqBA;AACE;AACE;;;;;;;AAOC;AACD;AACD;AACF;AA0BD;;;AAGA;AAEO;;AAgBH;;;AAGI;;;AAGJ;;AAIA;;;AAII;;;;;;;;;;;AAaA;;;;;;;AAOA;;;AAGA;AACE;;;;;;AAMN;AAEA;;;;AAqCF;AAGF;;"}
@@ -75,9 +75,10 @@ const DropZone = forwardRef(({ children, onSelectFiles, multiple = true, disable
75
75
  },
76
76
  };
77
77
  }, [latest]);
78
+ const errorAttr = error || undefined;
78
79
  return (
79
80
  // eslint-disable-next-line jsx-a11y/no-static-element-interactions
80
- jsxs("div", { className: classNames.wrapper, "data-files-dragged-over": filesDraggedOver || undefined, onDrop: functions.handleDrop, onDragOver: functions.handleDragOver, onDragLeave: functions.handleDragLeave, children: [children, jsx(SelectButton, { disabled: disabled, error: error, className: classNames.button, handleClick: functions.handleClickButton, label: selectButtonLabel }), jsx(VisuallyHiddenText, { children: jsx("input", { ...rest, ref: ref, type: "file", disabled: disabled, multiple: multiple, tabIndex: -1, "aria-invalid": error || undefined, "data-smarthr-ui-input": "true", onChange: functions.handleChange }) })] }));
81
+ jsxs("div", { className: classNames.wrapper, "data-files-dragged-over": filesDraggedOver || undefined, onDrop: functions.handleDrop, onDragOver: functions.handleDragOver, onDragLeave: functions.handleDragLeave, children: [children, jsx(SelectButton, { disabled: disabled, error: error, className: classNames.button, handleClick: functions.handleClickButton, label: selectButtonLabel }), jsx(VisuallyHiddenText, { children: jsx("input", { ...rest, ref: ref, type: "file", disabled: disabled, multiple: multiple, tabIndex: -1, "aria-invalid": errorAttr, "data-smarthr-ui-input-error": errorAttr, "data-smarthr-ui-input": "true", onChange: functions.handleChange }) })] }));
81
82
  });
82
83
  const SelectButton = memo(({ label, disabled, error, handleClick, className }) => (jsx(Button, { disabled: disabled, className: className, "data-error": error || undefined, onClick: handleClick, prefix: jsx(FaFolderOpenIcon, {}), children: label || jsx(Localizer, { id: "smarthr-ui/DropZone/selectButtonLabel", defaultText: "\u30D5\u30A1\u30A4\u30EB\u3092\u9078\u629E" }) })));
83
84
 
@@ -1 +1 @@
1
- {"version":3,"file":"DropZone.js","sources":["../../../../src/components/DropZone/client/DropZone.tsx"],"sourcesContent":["'use client'\n\nimport {\n type ChangeEvent,\n type ComponentPropsWithRef,\n type DragEvent,\n type MouseEvent,\n type PropsWithChildren,\n forwardRef,\n memo,\n useMemo,\n useState,\n} from 'react'\nimport { tv } from 'tailwind-variants'\n\nimport { useLatest } from '../../../hooks/useLatest'\nimport { Localizer } from '../../../intl'\nimport { Button } from '../../Button'\nimport { FaFolderOpenIcon } from '../../Icon'\nimport { VisuallyHiddenText } from '../../VisuallyHiddenText'\n\nconst classNameGenerator = tv({\n slots: {\n wrapper: [\n 'smarthr-ui-DropZone',\n 'shr-relative',\n 'shr-border-shorthand shr-flex shr-flex-col shr-items-center shr-justify-center shr-bg-column shr-p-2.5',\n 'has-[.smarthr-ui-DropZone-Button[aria-disabled]]:shr-cursor-not-allowed',\n '[&:not([data-files-dragged-over])]:shr-border-dashed',\n 'data-[files-dragged-over]:shr-border-main',\n ],\n button: ['smarthr-ui-DropZone-Button', 'data-[error]:shr-border-danger'],\n },\n})\n\ntype BaseProps = PropsWithChildren<{\n /**\n * ボタンまたはドラッグ&ドロップでファイルが追加された時に発火するコールバック関数\n */\n onSelectFiles: (\n e: DragEvent<HTMLElement> | ChangeEvent<HTMLInputElement>,\n files: FileList | null,\n ) => void\n /**\n * 許可するファイル型を表す1つ以上の固有ファイル型指定子\n * <b>(ドラッグ&ドロップの挙動には影響しません)</b>\n */\n accept?: string\n /** 複数ファイルを選択できるかどうか */\n multiple?: boolean\n name?: string\n disabled?: boolean\n /** フォームにエラーがあるかどうか */\n error?: boolean\n /** ファイル選択ボタンのラベル */\n selectButtonLabel?: string\n}>\ntype Props = BaseProps & Omit<ComponentPropsWithRef<'div'>, keyof BaseProps>\n\nconst overrideEventDefault = (e: DragEvent<HTMLElement>) => {\n e.preventDefault()\n e.stopPropagation()\n}\n\nexport const DropZone = forwardRef<HTMLInputElement, Props>(\n (\n {\n children,\n onSelectFiles,\n multiple = true,\n disabled,\n error,\n selectButtonLabel,\n className,\n ...rest\n },\n ref,\n ) => {\n const [filesDraggedOver, setFilesDraggedOver] = useState(false)\n\n const classNames = useMemo(() => {\n const { wrapper, button } = classNameGenerator()\n return {\n wrapper: wrapper({ className }),\n button: button(),\n }\n }, [className])\n\n const latest = useLatest({ onSelectFiles })\n\n const functions = useMemo(() => {\n const inputFileSelector = 'input[type=\"file\"][data-smarthr-ui-input=\"true\"]'\n\n return {\n handleDrop: (e: DragEvent<HTMLElement>) => {\n overrideEventDefault(e)\n setFilesDraggedOver(false)\n\n if (e.dataTransfer.types.includes('Files')) {\n const input = e.currentTarget.querySelector<HTMLInputElement>(inputFileSelector)\n\n if (input) {\n input.files = e.dataTransfer.files\n }\n latest.onSelectFiles(e, e.dataTransfer.files)\n }\n },\n handleDragOver: (e: DragEvent<HTMLElement>) => {\n overrideEventDefault(e)\n setFilesDraggedOver(true)\n },\n handleDragLeave: () => {\n setFilesDraggedOver(false)\n },\n handleChange: (e: ChangeEvent<HTMLInputElement>) => {\n latest.onSelectFiles(e, e.target.files)\n },\n handleClickButton: (e: MouseEvent<HTMLButtonElement>) => {\n e.currentTarget\n .closest('.smarthr-ui-DropZone')\n ?.querySelector<HTMLInputElement>(inputFileSelector)\n ?.click()\n },\n }\n }, [latest])\n\n return (\n // eslint-disable-next-line jsx-a11y/no-static-element-interactions\n <div\n className={classNames.wrapper}\n data-files-dragged-over={filesDraggedOver || undefined}\n onDrop={functions.handleDrop}\n onDragOver={functions.handleDragOver}\n onDragLeave={functions.handleDragLeave}\n >\n {children}\n <SelectButton\n disabled={disabled}\n error={error}\n className={classNames.button}\n handleClick={functions.handleClickButton}\n label={selectButtonLabel}\n />\n <VisuallyHiddenText>\n {/* TODO: この input にアクセシブルネームが設定されていない。VisuallyHiddenText で視覚的に隠されているが aria-hidden ではないためアクセシビリティツリーに残る。aria-label 等で適切なラベルを付与する必要がある */}\n {/* eslint-disable-next-line smarthr/a11y-input-in-form-control */}\n <input\n {...rest}\n ref={ref}\n type=\"file\"\n disabled={disabled}\n multiple={multiple}\n tabIndex={-1}\n aria-invalid={error || undefined}\n data-smarthr-ui-input=\"true\"\n onChange={functions.handleChange}\n />\n </VisuallyHiddenText>\n </div>\n )\n },\n)\n\nconst SelectButton = memo<{\n label?: string\n disabled?: boolean\n error?: boolean\n handleClick: (e: MouseEvent<HTMLButtonElement>) => void\n className: string\n}>(({ label, disabled, error, handleClick, className }) => (\n <Button\n disabled={disabled}\n className={className}\n data-error={error || undefined}\n onClick={handleClick}\n prefix={<FaFolderOpenIcon />}\n >\n {label || <Localizer id=\"smarthr-ui/DropZone/selectButtonLabel\" defaultText=\"ファイルを選択\" />}\n </Button>\n))\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAqBA;AACE;AACE;;;;;;;AAOC;AACD;AACD;AACF;AA0BD;;;AAGA;AAEO;;AAgBH;;;AAGI;;;AAGJ;;AAIA;;;AAII;;;;;;;;;;;AAaA;;;;;;;AAOA;;;AAGA;AACE;;;;;;AAMN;;;;AAoCF;AAGF;;"}
1
+ {"version":3,"file":"DropZone.js","sources":["../../../../src/components/DropZone/client/DropZone.tsx"],"sourcesContent":["'use client'\n\nimport {\n type ChangeEvent,\n type ComponentPropsWithRef,\n type DragEvent,\n type MouseEvent,\n type PropsWithChildren,\n forwardRef,\n memo,\n useMemo,\n useState,\n} from 'react'\nimport { tv } from 'tailwind-variants'\n\nimport { useLatest } from '../../../hooks/useLatest'\nimport { Localizer } from '../../../intl'\nimport { Button } from '../../Button'\nimport { FaFolderOpenIcon } from '../../Icon'\nimport { VisuallyHiddenText } from '../../VisuallyHiddenText'\n\nconst classNameGenerator = tv({\n slots: {\n wrapper: [\n 'smarthr-ui-DropZone',\n 'shr-relative',\n 'shr-border-shorthand shr-flex shr-flex-col shr-items-center shr-justify-center shr-bg-column shr-p-2.5',\n 'has-[.smarthr-ui-DropZone-Button[aria-disabled]]:shr-cursor-not-allowed',\n '[&:not([data-files-dragged-over])]:shr-border-dashed',\n 'data-[files-dragged-over]:shr-border-main',\n ],\n button: ['smarthr-ui-DropZone-Button', 'data-[error]:shr-border-danger'],\n },\n})\n\ntype BaseProps = PropsWithChildren<{\n /**\n * ボタンまたはドラッグ&ドロップでファイルが追加された時に発火するコールバック関数\n */\n onSelectFiles: (\n e: DragEvent<HTMLElement> | ChangeEvent<HTMLInputElement>,\n files: FileList | null,\n ) => void\n /**\n * 許可するファイル型を表す1つ以上の固有ファイル型指定子\n * <b>(ドラッグ&ドロップの挙動には影響しません)</b>\n */\n accept?: string\n /** 複数ファイルを選択できるかどうか */\n multiple?: boolean\n name?: string\n disabled?: boolean\n /** フォームにエラーがあるかどうか */\n error?: boolean\n /** ファイル選択ボタンのラベル */\n selectButtonLabel?: string\n}>\ntype Props = BaseProps & Omit<ComponentPropsWithRef<'div'>, keyof BaseProps>\n\nconst overrideEventDefault = (e: DragEvent<HTMLElement>) => {\n e.preventDefault()\n e.stopPropagation()\n}\n\nexport const DropZone = forwardRef<HTMLInputElement, Props>(\n (\n {\n children,\n onSelectFiles,\n multiple = true,\n disabled,\n error,\n selectButtonLabel,\n className,\n ...rest\n },\n ref,\n ) => {\n const [filesDraggedOver, setFilesDraggedOver] = useState(false)\n\n const classNames = useMemo(() => {\n const { wrapper, button } = classNameGenerator()\n return {\n wrapper: wrapper({ className }),\n button: button(),\n }\n }, [className])\n\n const latest = useLatest({ onSelectFiles })\n\n const functions = useMemo(() => {\n const inputFileSelector = 'input[type=\"file\"][data-smarthr-ui-input=\"true\"]'\n\n return {\n handleDrop: (e: DragEvent<HTMLElement>) => {\n overrideEventDefault(e)\n setFilesDraggedOver(false)\n\n if (e.dataTransfer.types.includes('Files')) {\n const input = e.currentTarget.querySelector<HTMLInputElement>(inputFileSelector)\n\n if (input) {\n input.files = e.dataTransfer.files\n }\n latest.onSelectFiles(e, e.dataTransfer.files)\n }\n },\n handleDragOver: (e: DragEvent<HTMLElement>) => {\n overrideEventDefault(e)\n setFilesDraggedOver(true)\n },\n handleDragLeave: () => {\n setFilesDraggedOver(false)\n },\n handleChange: (e: ChangeEvent<HTMLInputElement>) => {\n latest.onSelectFiles(e, e.target.files)\n },\n handleClickButton: (e: MouseEvent<HTMLButtonElement>) => {\n e.currentTarget\n .closest('.smarthr-ui-DropZone')\n ?.querySelector<HTMLInputElement>(inputFileSelector)\n ?.click()\n },\n }\n }, [latest])\n\n const errorAttr = error || undefined\n\n return (\n // eslint-disable-next-line jsx-a11y/no-static-element-interactions\n <div\n className={classNames.wrapper}\n data-files-dragged-over={filesDraggedOver || undefined}\n onDrop={functions.handleDrop}\n onDragOver={functions.handleDragOver}\n onDragLeave={functions.handleDragLeave}\n >\n {children}\n <SelectButton\n disabled={disabled}\n error={error}\n className={classNames.button}\n handleClick={functions.handleClickButton}\n label={selectButtonLabel}\n />\n <VisuallyHiddenText>\n {/* TODO: この input にアクセシブルネームが設定されていない。VisuallyHiddenText で視覚的に隠されているが aria-hidden ではないためアクセシビリティツリーに残る。aria-label 等で適切なラベルを付与する必要がある */}\n {/* eslint-disable-next-line smarthr/a11y-input-in-form-control */}\n <input\n {...rest}\n ref={ref}\n type=\"file\"\n disabled={disabled}\n multiple={multiple}\n tabIndex={-1}\n aria-invalid={errorAttr}\n data-smarthr-ui-input-error={errorAttr}\n data-smarthr-ui-input=\"true\"\n onChange={functions.handleChange}\n />\n </VisuallyHiddenText>\n </div>\n )\n },\n)\n\nconst SelectButton = memo<{\n label?: string\n disabled?: boolean\n error?: boolean\n handleClick: (e: MouseEvent<HTMLButtonElement>) => void\n className: string\n}>(({ label, disabled, error, handleClick, className }) => (\n <Button\n disabled={disabled}\n className={className}\n data-error={error || undefined}\n onClick={handleClick}\n prefix={<FaFolderOpenIcon />}\n >\n {label || <Localizer id=\"smarthr-ui/DropZone/selectButtonLabel\" defaultText=\"ファイルを選択\" />}\n </Button>\n))\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAqBA;AACE;AACE;;;;;;;AAOC;AACD;AACD;AACF;AA0BD;;;AAGA;AAEO;;AAgBH;;;AAGI;;;AAGJ;;AAIA;;;AAII;;;;;;;;;;;AAaA;;;;;;;AAOA;;;AAGA;AACE;;;;;;AAMN;AAEA;;;;AAqCF;AAGF;;"}
@@ -72,7 +72,12 @@ const FormGroup = ({ outerRef, label, subActionArea, innerMargin, statusLabels,
72
72
  if (errorAttr === 'true') {
73
73
  input.setAttribute('aria-invalid', 'true');
74
74
  }
75
- else {
75
+ else if (
76
+ // HINT: 入力要素自体にerror属性が設定されている場合、そちらを優先する
77
+ input.getAttribute('data-smarthr-ui-input-error') !== 'true' &&
78
+ // HINT: Fieldset > FormControlのようにネストしている場合を考慮して
79
+ // autoBindErrorしているFormGroupが親方向に存在する場合、子の入力要素からaria-invalidを外さないようにする
80
+ !input.closest(`${components_FormGroup_client_constants.WRAPPER_SELECTOR}[data-auto-bind-error-input='true']`)) {
76
81
  input.removeAttribute('aria-invalid');
77
82
  }
78
83
  }
@@ -1 +1 @@
1
- {"version":3,"file":"FormGroup.cjs","sources":["../../../../src/components/FormGroup/client/FormGroup.tsx"],"sourcesContent":["'use client'\n\nimport {\n type ComponentProps,\n type ComponentType,\n type FC,\n type PropsWithChildren,\n type ReactNode,\n type Ref,\n useCallback,\n useMemo,\n useRef,\n} from 'react'\n\nimport { useMergeRefs } from '../../../hooks/client/useMergeRefs'\nimport { FaCircleExclamationIcon } from '../../Icon'\nimport { Cluster, Stack } from '../../Layout'\nimport { LiveRegion } from '../../LiveRegion'\nimport { Text } from '../../Text'\n\nimport { CHILDREN_WRAPPER_INPUT_SELECTOR } from './constants'\n\nimport type { CommonProps, LabelComponentProps, ObjectLabelType } from './type'\n\ntype Props = Omit<CommonProps, 'className'> & {\n outerRef: Ref<HTMLElement>\n /** グループのラベル名 */\n label: Omit<ObjectLabelType, 'id' | 'htmlFor'> & Required<Pick<ObjectLabelType, 'id' | 'htmlFor'>>\n as?: string | ComponentType<any>\n /** `true` のとき、文字色を `TEXT_DISABLED` にする */\n disabled?: boolean\n LabelComponent: FC<LabelComponentProps>\n classNames: {\n wrapper: string\n childrenWrapper: string\n }\n}\n\n// HINT: errorMessagesの利用方法とReactNodeのためuseMemoでは適切にmemo化しにくい\n// undefined、もしくは空配列の場合は定数のEMPTY_ERROR_MESSAGESと差し替えることで安定化する\nconst EMPTY_ERROR_MESSAGES: ReactNode[] = []\n\nexport const FormGroup: FC<Props> = ({\n outerRef,\n label,\n subActionArea,\n innerMargin,\n statusLabels,\n helpMessage,\n exampleMessage,\n errorMessages: orgErrorMessages,\n supplementaryMessage,\n as = 'div',\n children,\n classNames,\n LabelComponent,\n autoBindErrorInput = true,\n ...rest\n}) => {\n // HINT: statusLabelsは設定されない場合が大半、かつ設定されてもRequiredLabelでmemo化されているため\n // memo化がかなりの確率で有用\n const actualStatusLabels = useMemo(\n () => (statusLabels ? (Array.isArray(statusLabels) ? statusLabels : [statusLabels]) : []),\n [statusLabels],\n )\n\n // HINT: errorMessagesの利用方法とReactNodeのためuseMemoでは適切にmemo化しにくい\n // undefined、もしくは空配列の場合は定数のEMPTY_ERROR_MESSAGESと差し替えることで安定化する\n const errorMessages = orgErrorMessages\n ? Array.isArray(orgErrorMessages)\n ? orgErrorMessages.length === 0\n ? EMPTY_ERROR_MESSAGES\n : orgErrorMessages\n : [orgErrorMessages]\n : EMPTY_ERROR_MESSAGES\n\n const helpMessageId = helpMessage ? `${label.htmlFor}_helpMessage` : undefined\n const exampleMessageId = exampleMessage ? `${label.htmlFor}_exampleMessage` : undefined\n const supplementaryMessageId = supplementaryMessage\n ? `${label.htmlFor}_supplementaryMessage`\n : undefined\n const visibleErrorMessages = errorMessages.length > 0\n const errorMessagesId = visibleErrorMessages ? `${label.htmlFor}_errorMessages` : undefined\n\n const describedbyIds = useMemo(() => {\n const temp: string[] = []\n\n if (helpMessageId) {\n temp.push(helpMessageId)\n }\n if (exampleMessageId) {\n temp.push(exampleMessageId)\n }\n if (supplementaryMessageId) {\n temp.push(supplementaryMessageId)\n }\n if (errorMessagesId) {\n temp.push(errorMessagesId)\n }\n\n return temp.join(' ')\n }, [helpMessageId, exampleMessageId, supplementaryMessageId, errorMessagesId])\n\n const managedDescribedbyIdsRef = useRef<string[]>([])\n\n const innerCallbackRef = useCallback((node: HTMLElement | null) => {\n if (!node) {\n return\n }\n\n const action = () => {\n const input = node.querySelector<HTMLInputElement>(CHILDREN_WRAPPER_INPUT_SELECTOR)\n\n if (!input) {\n return\n }\n\n const errorAttr = node.getAttribute('data-auto-bind-error-input')\n\n // HINT: そもそも対象の属性の値が存在しない場合、入力要素にaria-invalid属性を自動的にon/offする処理をしない\n if (errorAttr) {\n if (errorAttr === 'true') {\n input.setAttribute('aria-invalid', 'true')\n } else {\n input.removeAttribute('aria-invalid')\n }\n }\n\n const nextDescribedBy = node.getAttribute('data-auto-bind-aria-describedby-for-input')\n const ariaDescribedBy = input.getAttribute('aria-describedby') || ''\n const currentTokens = ariaDescribedBy ? ariaDescribedBy.split(' ') : []\n // HINT: 自分が過去に付与したid以外(=外部由来のid)だけを残す\n const externalTokens = currentTokens.filter(\n (token) => !managedDescribedbyIdsRef.current.includes(token),\n )\n const describedbyIdTokens = nextDescribedBy ? nextDescribedBy.split(' ') : []\n const nextValue = [...externalTokens, ...describedbyIdTokens].join(' ')\n\n if (nextValue !== ariaDescribedBy) {\n if (nextValue) {\n input.setAttribute('aria-describedby', nextValue)\n } else {\n input.removeAttribute('aria-describedby')\n }\n }\n\n managedDescribedbyIdsRef.current = describedbyIdTokens\n }\n\n action()\n\n const observer = new MutationObserver(action)\n observer.observe(node, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['data-auto-bind-error-input', 'data-auto-bind-aria-describedby-for-input'],\n })\n\n return () => {\n observer.disconnect()\n }\n }, [])\n\n const wrapperCallbackRef = useMergeRefs(innerCallbackRef, outerRef)\n\n return (\n <Stack\n {...rest}\n as={as}\n ref={wrapperCallbackRef}\n gap={innerMargin ?? 0.5}\n className={classNames.wrapper}\n aria-describedby={as === 'fieldset' ? describedbyIds || undefined : undefined}\n data-auto-bind-error-input={autoBindErrorInput ? visibleErrorMessages.toString() : undefined}\n data-auto-bind-aria-describedby-for-input={describedbyIds}\n >\n <LabelComponent\n managedLabelId={label.id}\n managedHtmlFor={label.htmlFor}\n unrecommendedHideLabel={label.unrecommendedHide}\n labelType={label.styleType}\n labelIcon={label.icon}\n statusLabels={actualStatusLabels}\n label={label.text}\n subActionArea={subActionArea}\n />\n {helpMessage && (\n <p id={helpMessageId} className=\"smarthr-ui-FormControl-helpMessage\">\n {helpMessage}\n </p>\n )}\n {exampleMessage && (\n <Text\n as=\"p\"\n id={exampleMessageId}\n italic\n color=\"TEXT_GREY\"\n className=\"smarthr-ui-FormControl-exampleMessage\"\n >\n {exampleMessage}\n </Text>\n )}\n {visibleErrorMessages && (\n <div id={errorMessagesId}>\n {errorMessages.map((message, index) => (\n <Text\n key={index}\n as=\"p\"\n className=\"smarthr-ui-FormControl-errorMessage\"\n icon={\n <FaCircleExclamationIcon className=\"smarthr-ui-FormControl-errorMessage-Icon shr-text-danger\" />\n }\n >\n <LiveRegion role=\"alert\">{message}</LiveRegion>\n </Text>\n ))}\n </div>\n )}\n <div className={classNames.childrenWrapper}>{children}</div>\n {supplementaryMessage && (\n <Text\n as=\"p\"\n id={supplementaryMessageId}\n size=\"S\"\n color=\"TEXT_GREY\"\n className=\"smarthr-ui-FormControl-supplementaryMessage\"\n >\n {supplementaryMessage}\n </Text>\n )}\n </Stack>\n )\n}\n\nexport const LabelBody: FC<\n Pick<ComponentProps<typeof Text>, 'styleType' | 'icon' | 'children'> &\n Pick<LabelComponentProps, 'statusLabels'>\n> = ({ styleType, icon, children, statusLabels }) => (\n <>\n <Text styleType={styleType} icon={icon}>\n <span className=\"smarthr-ui-FormControl-labelText\">{children}</span>\n </Text>\n {statusLabels.length > 0 && (\n <Cluster as=\"span\" gap={0.25}>\n {statusLabels}\n </Cluster>\n )}\n </>\n)\n\nexport const LabelCluster: FC<\n PropsWithChildren<{ as?: 'label'; htmlFor?: string; id?: string; 'aria-hidden'?: 'true' }>\n> = ({ children, ...rest }) => (\n <Cluster {...rest} align=\"center\" className=\"smarthr-ui-FormControl-label\">\n {children}\n </Cluster>\n)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAsCA;AACA;AACA;;;;AAqBE;;;;AAQE;AACE;AACE;AACA;;;AAIN;AACA;;AAEE;;AAEF;AACA;AAEA;;;AAII;;;AAGA;;;AAGA;;;AAGA;;AAGF;;AAGF;AAEA;;;;;;;;;;;;AAgBM;AACE;;;AAEA;;;;;AAMJ;;;AAKA;AACA;AAEA;;AAEI;;;AAEA;;;AAIJ;AACF;AAEA;AAEA;AACA;AACE;AACA;AACA;AACA;AACD;AAED;;AAEA;;;;AAwEJ;AAEO;AAgBA;;;;"}
1
+ {"version":3,"file":"FormGroup.cjs","sources":["../../../../src/components/FormGroup/client/FormGroup.tsx"],"sourcesContent":["'use client'\n\nimport {\n type ComponentProps,\n type ComponentType,\n type FC,\n type PropsWithChildren,\n type ReactNode,\n type Ref,\n useCallback,\n useMemo,\n useRef,\n} from 'react'\n\nimport { useMergeRefs } from '../../../hooks/client/useMergeRefs'\nimport { FaCircleExclamationIcon } from '../../Icon'\nimport { Cluster, Stack } from '../../Layout'\nimport { LiveRegion } from '../../LiveRegion'\nimport { Text } from '../../Text'\n\nimport { CHILDREN_WRAPPER_INPUT_SELECTOR, WRAPPER_SELECTOR } from './constants'\n\nimport type { CommonProps, LabelComponentProps, ObjectLabelType } from './type'\n\ntype Props = Omit<CommonProps, 'className'> & {\n outerRef: Ref<HTMLElement>\n /** グループのラベル名 */\n label: Omit<ObjectLabelType, 'id' | 'htmlFor'> & Required<Pick<ObjectLabelType, 'id' | 'htmlFor'>>\n as?: string | ComponentType<any>\n /** `true` のとき、文字色を `TEXT_DISABLED` にする */\n disabled?: boolean\n LabelComponent: FC<LabelComponentProps>\n classNames: {\n wrapper: string\n childrenWrapper: string\n }\n}\n\n// HINT: errorMessagesの利用方法とReactNodeのためuseMemoでは適切にmemo化しにくい\n// undefined、もしくは空配列の場合は定数のEMPTY_ERROR_MESSAGESと差し替えることで安定化する\nconst EMPTY_ERROR_MESSAGES: ReactNode[] = []\n\nexport const FormGroup: FC<Props> = ({\n outerRef,\n label,\n subActionArea,\n innerMargin,\n statusLabels,\n helpMessage,\n exampleMessage,\n errorMessages: orgErrorMessages,\n supplementaryMessage,\n as = 'div',\n children,\n classNames,\n LabelComponent,\n autoBindErrorInput = true,\n ...rest\n}) => {\n // HINT: statusLabelsは設定されない場合が大半、かつ設定されてもRequiredLabelでmemo化されているため\n // memo化がかなりの確率で有用\n const actualStatusLabels = useMemo(\n () => (statusLabels ? (Array.isArray(statusLabels) ? statusLabels : [statusLabels]) : []),\n [statusLabels],\n )\n\n // HINT: errorMessagesの利用方法とReactNodeのためuseMemoでは適切にmemo化しにくい\n // undefined、もしくは空配列の場合は定数のEMPTY_ERROR_MESSAGESと差し替えることで安定化する\n const errorMessages = orgErrorMessages\n ? Array.isArray(orgErrorMessages)\n ? orgErrorMessages.length === 0\n ? EMPTY_ERROR_MESSAGES\n : orgErrorMessages\n : [orgErrorMessages]\n : EMPTY_ERROR_MESSAGES\n\n const helpMessageId = helpMessage ? `${label.htmlFor}_helpMessage` : undefined\n const exampleMessageId = exampleMessage ? `${label.htmlFor}_exampleMessage` : undefined\n const supplementaryMessageId = supplementaryMessage\n ? `${label.htmlFor}_supplementaryMessage`\n : undefined\n const visibleErrorMessages = errorMessages.length > 0\n const errorMessagesId = visibleErrorMessages ? `${label.htmlFor}_errorMessages` : undefined\n\n const describedbyIds = useMemo(() => {\n const temp: string[] = []\n\n if (helpMessageId) {\n temp.push(helpMessageId)\n }\n if (exampleMessageId) {\n temp.push(exampleMessageId)\n }\n if (supplementaryMessageId) {\n temp.push(supplementaryMessageId)\n }\n if (errorMessagesId) {\n temp.push(errorMessagesId)\n }\n\n return temp.join(' ')\n }, [helpMessageId, exampleMessageId, supplementaryMessageId, errorMessagesId])\n\n const managedDescribedbyIdsRef = useRef<string[]>([])\n\n const innerCallbackRef = useCallback((node: HTMLElement | null) => {\n if (!node) {\n return\n }\n\n const action = () => {\n const input = node.querySelector<HTMLInputElement>(CHILDREN_WRAPPER_INPUT_SELECTOR)\n\n if (!input) {\n return\n }\n\n const errorAttr = node.getAttribute('data-auto-bind-error-input')\n\n // HINT: そもそも対象の属性の値が存在しない場合、入力要素にaria-invalid属性を自動的にon/offする処理をしない\n if (errorAttr) {\n if (errorAttr === 'true') {\n input.setAttribute('aria-invalid', 'true')\n } else if (\n // HINT: 入力要素自体にerror属性が設定されている場合、そちらを優先する\n input.getAttribute('data-smarthr-ui-input-error') !== 'true' &&\n // HINT: Fieldset > FormControlのようにネストしている場合を考慮して\n // autoBindErrorしているFormGroupが親方向に存在する場合、子の入力要素からaria-invalidを外さないようにする\n !input.closest(`${WRAPPER_SELECTOR}[data-auto-bind-error-input='true']`)\n ) {\n input.removeAttribute('aria-invalid')\n }\n }\n\n const nextDescribedBy = node.getAttribute('data-auto-bind-aria-describedby-for-input')\n const ariaDescribedBy = input.getAttribute('aria-describedby') || ''\n const currentTokens = ariaDescribedBy ? ariaDescribedBy.split(' ') : []\n // HINT: 自分が過去に付与したid以外(=外部由来のid)だけを残す\n const externalTokens = currentTokens.filter(\n (token) => !managedDescribedbyIdsRef.current.includes(token),\n )\n const describedbyIdTokens = nextDescribedBy ? nextDescribedBy.split(' ') : []\n const nextValue = [...externalTokens, ...describedbyIdTokens].join(' ')\n\n if (nextValue !== ariaDescribedBy) {\n if (nextValue) {\n input.setAttribute('aria-describedby', nextValue)\n } else {\n input.removeAttribute('aria-describedby')\n }\n }\n\n managedDescribedbyIdsRef.current = describedbyIdTokens\n }\n\n action()\n\n const observer = new MutationObserver(action)\n observer.observe(node, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['data-auto-bind-error-input', 'data-auto-bind-aria-describedby-for-input'],\n })\n\n return () => {\n observer.disconnect()\n }\n }, [])\n\n const wrapperCallbackRef = useMergeRefs(innerCallbackRef, outerRef)\n\n return (\n <Stack\n {...rest}\n as={as}\n ref={wrapperCallbackRef}\n gap={innerMargin ?? 0.5}\n className={classNames.wrapper}\n aria-describedby={as === 'fieldset' ? describedbyIds || undefined : undefined}\n data-auto-bind-error-input={autoBindErrorInput ? visibleErrorMessages.toString() : undefined}\n data-auto-bind-aria-describedby-for-input={describedbyIds}\n >\n <LabelComponent\n managedLabelId={label.id}\n managedHtmlFor={label.htmlFor}\n unrecommendedHideLabel={label.unrecommendedHide}\n labelType={label.styleType}\n labelIcon={label.icon}\n statusLabels={actualStatusLabels}\n label={label.text}\n subActionArea={subActionArea}\n />\n {helpMessage && (\n <p id={helpMessageId} className=\"smarthr-ui-FormControl-helpMessage\">\n {helpMessage}\n </p>\n )}\n {exampleMessage && (\n <Text\n as=\"p\"\n id={exampleMessageId}\n italic\n color=\"TEXT_GREY\"\n className=\"smarthr-ui-FormControl-exampleMessage\"\n >\n {exampleMessage}\n </Text>\n )}\n {visibleErrorMessages && (\n <div id={errorMessagesId}>\n {errorMessages.map((message, index) => (\n <Text\n key={index}\n as=\"p\"\n className=\"smarthr-ui-FormControl-errorMessage\"\n icon={\n <FaCircleExclamationIcon className=\"smarthr-ui-FormControl-errorMessage-Icon shr-text-danger\" />\n }\n >\n <LiveRegion role=\"alert\">{message}</LiveRegion>\n </Text>\n ))}\n </div>\n )}\n <div className={classNames.childrenWrapper}>{children}</div>\n {supplementaryMessage && (\n <Text\n as=\"p\"\n id={supplementaryMessageId}\n size=\"S\"\n color=\"TEXT_GREY\"\n className=\"smarthr-ui-FormControl-supplementaryMessage\"\n >\n {supplementaryMessage}\n </Text>\n )}\n </Stack>\n )\n}\n\nexport const LabelBody: FC<\n Pick<ComponentProps<typeof Text>, 'styleType' | 'icon' | 'children'> &\n Pick<LabelComponentProps, 'statusLabels'>\n> = ({ styleType, icon, children, statusLabels }) => (\n <>\n <Text styleType={styleType} icon={icon}>\n <span className=\"smarthr-ui-FormControl-labelText\">{children}</span>\n </Text>\n {statusLabels.length > 0 && (\n <Cluster as=\"span\" gap={0.25}>\n {statusLabels}\n </Cluster>\n )}\n </>\n)\n\nexport const LabelCluster: FC<\n PropsWithChildren<{ as?: 'label'; htmlFor?: string; id?: string; 'aria-hidden'?: 'true' }>\n> = ({ children, ...rest }) => (\n <Cluster {...rest} align=\"center\" className=\"smarthr-ui-FormControl-label\">\n {children}\n </Cluster>\n)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAsCA;AACA;AACA;;;;AAqBE;;;;AAQE;AACE;AACE;AACA;;;AAIN;AACA;;AAEE;;AAEF;AACA;AAEA;;;AAII;;;AAGA;;;AAGA;;;AAGA;;AAGF;;AAGF;AAEA;;;;;;;;;;;;AAgBM;AACE;;AACK;;AAEL;;;;AAKA;;;;;AAMJ;;;AAKA;AACA;AAEA;;AAEI;;;AAEA;;;AAIJ;AACF;AAEA;AAEA;AACA;AACE;AACA;AACA;AACA;AACD;AAED;;AAEA;;;;AAwEJ;AAEO;AAgBA;;;;"}
@@ -13,7 +13,7 @@ import '../../Layout/Center/Center.js';
13
13
  import '../../Layout/Container/Container.js';
14
14
  import { LiveRegion } from '../../LiveRegion/LiveRegion.js';
15
15
  import { Text } from '../../Text/Text.js';
16
- import { CHILDREN_WRAPPER_INPUT_SELECTOR } from './constants.js';
16
+ import { CHILDREN_WRAPPER_INPUT_SELECTOR, WRAPPER_SELECTOR } from './constants.js';
17
17
 
18
18
  // HINT: errorMessagesの利用方法とReactNodeのためuseMemoでは適切にmemo化しにくい
19
19
  // undefined、もしくは空配列の場合は定数のEMPTY_ERROR_MESSAGESと差し替えることで安定化する
@@ -70,7 +70,12 @@ const FormGroup = ({ outerRef, label, subActionArea, innerMargin, statusLabels,
70
70
  if (errorAttr === 'true') {
71
71
  input.setAttribute('aria-invalid', 'true');
72
72
  }
73
- else {
73
+ else if (
74
+ // HINT: 入力要素自体にerror属性が設定されている場合、そちらを優先する
75
+ input.getAttribute('data-smarthr-ui-input-error') !== 'true' &&
76
+ // HINT: Fieldset > FormControlのようにネストしている場合を考慮して
77
+ // autoBindErrorしているFormGroupが親方向に存在する場合、子の入力要素からaria-invalidを外さないようにする
78
+ !input.closest(`${WRAPPER_SELECTOR}[data-auto-bind-error-input='true']`)) {
74
79
  input.removeAttribute('aria-invalid');
75
80
  }
76
81
  }
@@ -1 +1 @@
1
- {"version":3,"file":"FormGroup.js","sources":["../../../../src/components/FormGroup/client/FormGroup.tsx"],"sourcesContent":["'use client'\n\nimport {\n type ComponentProps,\n type ComponentType,\n type FC,\n type PropsWithChildren,\n type ReactNode,\n type Ref,\n useCallback,\n useMemo,\n useRef,\n} from 'react'\n\nimport { useMergeRefs } from '../../../hooks/client/useMergeRefs'\nimport { FaCircleExclamationIcon } from '../../Icon'\nimport { Cluster, Stack } from '../../Layout'\nimport { LiveRegion } from '../../LiveRegion'\nimport { Text } from '../../Text'\n\nimport { CHILDREN_WRAPPER_INPUT_SELECTOR } from './constants'\n\nimport type { CommonProps, LabelComponentProps, ObjectLabelType } from './type'\n\ntype Props = Omit<CommonProps, 'className'> & {\n outerRef: Ref<HTMLElement>\n /** グループのラベル名 */\n label: Omit<ObjectLabelType, 'id' | 'htmlFor'> & Required<Pick<ObjectLabelType, 'id' | 'htmlFor'>>\n as?: string | ComponentType<any>\n /** `true` のとき、文字色を `TEXT_DISABLED` にする */\n disabled?: boolean\n LabelComponent: FC<LabelComponentProps>\n classNames: {\n wrapper: string\n childrenWrapper: string\n }\n}\n\n// HINT: errorMessagesの利用方法とReactNodeのためuseMemoでは適切にmemo化しにくい\n// undefined、もしくは空配列の場合は定数のEMPTY_ERROR_MESSAGESと差し替えることで安定化する\nconst EMPTY_ERROR_MESSAGES: ReactNode[] = []\n\nexport const FormGroup: FC<Props> = ({\n outerRef,\n label,\n subActionArea,\n innerMargin,\n statusLabels,\n helpMessage,\n exampleMessage,\n errorMessages: orgErrorMessages,\n supplementaryMessage,\n as = 'div',\n children,\n classNames,\n LabelComponent,\n autoBindErrorInput = true,\n ...rest\n}) => {\n // HINT: statusLabelsは設定されない場合が大半、かつ設定されてもRequiredLabelでmemo化されているため\n // memo化がかなりの確率で有用\n const actualStatusLabels = useMemo(\n () => (statusLabels ? (Array.isArray(statusLabels) ? statusLabels : [statusLabels]) : []),\n [statusLabels],\n )\n\n // HINT: errorMessagesの利用方法とReactNodeのためuseMemoでは適切にmemo化しにくい\n // undefined、もしくは空配列の場合は定数のEMPTY_ERROR_MESSAGESと差し替えることで安定化する\n const errorMessages = orgErrorMessages\n ? Array.isArray(orgErrorMessages)\n ? orgErrorMessages.length === 0\n ? EMPTY_ERROR_MESSAGES\n : orgErrorMessages\n : [orgErrorMessages]\n : EMPTY_ERROR_MESSAGES\n\n const helpMessageId = helpMessage ? `${label.htmlFor}_helpMessage` : undefined\n const exampleMessageId = exampleMessage ? `${label.htmlFor}_exampleMessage` : undefined\n const supplementaryMessageId = supplementaryMessage\n ? `${label.htmlFor}_supplementaryMessage`\n : undefined\n const visibleErrorMessages = errorMessages.length > 0\n const errorMessagesId = visibleErrorMessages ? `${label.htmlFor}_errorMessages` : undefined\n\n const describedbyIds = useMemo(() => {\n const temp: string[] = []\n\n if (helpMessageId) {\n temp.push(helpMessageId)\n }\n if (exampleMessageId) {\n temp.push(exampleMessageId)\n }\n if (supplementaryMessageId) {\n temp.push(supplementaryMessageId)\n }\n if (errorMessagesId) {\n temp.push(errorMessagesId)\n }\n\n return temp.join(' ')\n }, [helpMessageId, exampleMessageId, supplementaryMessageId, errorMessagesId])\n\n const managedDescribedbyIdsRef = useRef<string[]>([])\n\n const innerCallbackRef = useCallback((node: HTMLElement | null) => {\n if (!node) {\n return\n }\n\n const action = () => {\n const input = node.querySelector<HTMLInputElement>(CHILDREN_WRAPPER_INPUT_SELECTOR)\n\n if (!input) {\n return\n }\n\n const errorAttr = node.getAttribute('data-auto-bind-error-input')\n\n // HINT: そもそも対象の属性の値が存在しない場合、入力要素にaria-invalid属性を自動的にon/offする処理をしない\n if (errorAttr) {\n if (errorAttr === 'true') {\n input.setAttribute('aria-invalid', 'true')\n } else {\n input.removeAttribute('aria-invalid')\n }\n }\n\n const nextDescribedBy = node.getAttribute('data-auto-bind-aria-describedby-for-input')\n const ariaDescribedBy = input.getAttribute('aria-describedby') || ''\n const currentTokens = ariaDescribedBy ? ariaDescribedBy.split(' ') : []\n // HINT: 自分が過去に付与したid以外(=外部由来のid)だけを残す\n const externalTokens = currentTokens.filter(\n (token) => !managedDescribedbyIdsRef.current.includes(token),\n )\n const describedbyIdTokens = nextDescribedBy ? nextDescribedBy.split(' ') : []\n const nextValue = [...externalTokens, ...describedbyIdTokens].join(' ')\n\n if (nextValue !== ariaDescribedBy) {\n if (nextValue) {\n input.setAttribute('aria-describedby', nextValue)\n } else {\n input.removeAttribute('aria-describedby')\n }\n }\n\n managedDescribedbyIdsRef.current = describedbyIdTokens\n }\n\n action()\n\n const observer = new MutationObserver(action)\n observer.observe(node, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['data-auto-bind-error-input', 'data-auto-bind-aria-describedby-for-input'],\n })\n\n return () => {\n observer.disconnect()\n }\n }, [])\n\n const wrapperCallbackRef = useMergeRefs(innerCallbackRef, outerRef)\n\n return (\n <Stack\n {...rest}\n as={as}\n ref={wrapperCallbackRef}\n gap={innerMargin ?? 0.5}\n className={classNames.wrapper}\n aria-describedby={as === 'fieldset' ? describedbyIds || undefined : undefined}\n data-auto-bind-error-input={autoBindErrorInput ? visibleErrorMessages.toString() : undefined}\n data-auto-bind-aria-describedby-for-input={describedbyIds}\n >\n <LabelComponent\n managedLabelId={label.id}\n managedHtmlFor={label.htmlFor}\n unrecommendedHideLabel={label.unrecommendedHide}\n labelType={label.styleType}\n labelIcon={label.icon}\n statusLabels={actualStatusLabels}\n label={label.text}\n subActionArea={subActionArea}\n />\n {helpMessage && (\n <p id={helpMessageId} className=\"smarthr-ui-FormControl-helpMessage\">\n {helpMessage}\n </p>\n )}\n {exampleMessage && (\n <Text\n as=\"p\"\n id={exampleMessageId}\n italic\n color=\"TEXT_GREY\"\n className=\"smarthr-ui-FormControl-exampleMessage\"\n >\n {exampleMessage}\n </Text>\n )}\n {visibleErrorMessages && (\n <div id={errorMessagesId}>\n {errorMessages.map((message, index) => (\n <Text\n key={index}\n as=\"p\"\n className=\"smarthr-ui-FormControl-errorMessage\"\n icon={\n <FaCircleExclamationIcon className=\"smarthr-ui-FormControl-errorMessage-Icon shr-text-danger\" />\n }\n >\n <LiveRegion role=\"alert\">{message}</LiveRegion>\n </Text>\n ))}\n </div>\n )}\n <div className={classNames.childrenWrapper}>{children}</div>\n {supplementaryMessage && (\n <Text\n as=\"p\"\n id={supplementaryMessageId}\n size=\"S\"\n color=\"TEXT_GREY\"\n className=\"smarthr-ui-FormControl-supplementaryMessage\"\n >\n {supplementaryMessage}\n </Text>\n )}\n </Stack>\n )\n}\n\nexport const LabelBody: FC<\n Pick<ComponentProps<typeof Text>, 'styleType' | 'icon' | 'children'> &\n Pick<LabelComponentProps, 'statusLabels'>\n> = ({ styleType, icon, children, statusLabels }) => (\n <>\n <Text styleType={styleType} icon={icon}>\n <span className=\"smarthr-ui-FormControl-labelText\">{children}</span>\n </Text>\n {statusLabels.length > 0 && (\n <Cluster as=\"span\" gap={0.25}>\n {statusLabels}\n </Cluster>\n )}\n </>\n)\n\nexport const LabelCluster: FC<\n PropsWithChildren<{ as?: 'label'; htmlFor?: string; id?: string; 'aria-hidden'?: 'true' }>\n> = ({ children, ...rest }) => (\n <Cluster {...rest} align=\"center\" className=\"smarthr-ui-FormControl-label\">\n {children}\n </Cluster>\n)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAsCA;AACA;AACA;;;;AAqBE;;;;AAQE;AACE;AACE;AACA;;;AAIN;AACA;;AAEE;;AAEF;AACA;AAEA;;;AAII;;;AAGA;;;AAGA;;;AAGA;;AAGF;;AAGF;AAEA;;;;;;;;;;;;AAgBM;AACE;;;AAEA;;;;;AAMJ;;;AAKA;AACA;AAEA;;AAEI;;;AAEA;;;AAIJ;AACF;AAEA;AAEA;AACA;AACE;AACA;AACA;AACA;AACD;AAED;;AAEA;;;;AAwEJ;AAEO;AAgBA;;"}
1
+ {"version":3,"file":"FormGroup.js","sources":["../../../../src/components/FormGroup/client/FormGroup.tsx"],"sourcesContent":["'use client'\n\nimport {\n type ComponentProps,\n type ComponentType,\n type FC,\n type PropsWithChildren,\n type ReactNode,\n type Ref,\n useCallback,\n useMemo,\n useRef,\n} from 'react'\n\nimport { useMergeRefs } from '../../../hooks/client/useMergeRefs'\nimport { FaCircleExclamationIcon } from '../../Icon'\nimport { Cluster, Stack } from '../../Layout'\nimport { LiveRegion } from '../../LiveRegion'\nimport { Text } from '../../Text'\n\nimport { CHILDREN_WRAPPER_INPUT_SELECTOR, WRAPPER_SELECTOR } from './constants'\n\nimport type { CommonProps, LabelComponentProps, ObjectLabelType } from './type'\n\ntype Props = Omit<CommonProps, 'className'> & {\n outerRef: Ref<HTMLElement>\n /** グループのラベル名 */\n label: Omit<ObjectLabelType, 'id' | 'htmlFor'> & Required<Pick<ObjectLabelType, 'id' | 'htmlFor'>>\n as?: string | ComponentType<any>\n /** `true` のとき、文字色を `TEXT_DISABLED` にする */\n disabled?: boolean\n LabelComponent: FC<LabelComponentProps>\n classNames: {\n wrapper: string\n childrenWrapper: string\n }\n}\n\n// HINT: errorMessagesの利用方法とReactNodeのためuseMemoでは適切にmemo化しにくい\n// undefined、もしくは空配列の場合は定数のEMPTY_ERROR_MESSAGESと差し替えることで安定化する\nconst EMPTY_ERROR_MESSAGES: ReactNode[] = []\n\nexport const FormGroup: FC<Props> = ({\n outerRef,\n label,\n subActionArea,\n innerMargin,\n statusLabels,\n helpMessage,\n exampleMessage,\n errorMessages: orgErrorMessages,\n supplementaryMessage,\n as = 'div',\n children,\n classNames,\n LabelComponent,\n autoBindErrorInput = true,\n ...rest\n}) => {\n // HINT: statusLabelsは設定されない場合が大半、かつ設定されてもRequiredLabelでmemo化されているため\n // memo化がかなりの確率で有用\n const actualStatusLabels = useMemo(\n () => (statusLabels ? (Array.isArray(statusLabels) ? statusLabels : [statusLabels]) : []),\n [statusLabels],\n )\n\n // HINT: errorMessagesの利用方法とReactNodeのためuseMemoでは適切にmemo化しにくい\n // undefined、もしくは空配列の場合は定数のEMPTY_ERROR_MESSAGESと差し替えることで安定化する\n const errorMessages = orgErrorMessages\n ? Array.isArray(orgErrorMessages)\n ? orgErrorMessages.length === 0\n ? EMPTY_ERROR_MESSAGES\n : orgErrorMessages\n : [orgErrorMessages]\n : EMPTY_ERROR_MESSAGES\n\n const helpMessageId = helpMessage ? `${label.htmlFor}_helpMessage` : undefined\n const exampleMessageId = exampleMessage ? `${label.htmlFor}_exampleMessage` : undefined\n const supplementaryMessageId = supplementaryMessage\n ? `${label.htmlFor}_supplementaryMessage`\n : undefined\n const visibleErrorMessages = errorMessages.length > 0\n const errorMessagesId = visibleErrorMessages ? `${label.htmlFor}_errorMessages` : undefined\n\n const describedbyIds = useMemo(() => {\n const temp: string[] = []\n\n if (helpMessageId) {\n temp.push(helpMessageId)\n }\n if (exampleMessageId) {\n temp.push(exampleMessageId)\n }\n if (supplementaryMessageId) {\n temp.push(supplementaryMessageId)\n }\n if (errorMessagesId) {\n temp.push(errorMessagesId)\n }\n\n return temp.join(' ')\n }, [helpMessageId, exampleMessageId, supplementaryMessageId, errorMessagesId])\n\n const managedDescribedbyIdsRef = useRef<string[]>([])\n\n const innerCallbackRef = useCallback((node: HTMLElement | null) => {\n if (!node) {\n return\n }\n\n const action = () => {\n const input = node.querySelector<HTMLInputElement>(CHILDREN_WRAPPER_INPUT_SELECTOR)\n\n if (!input) {\n return\n }\n\n const errorAttr = node.getAttribute('data-auto-bind-error-input')\n\n // HINT: そもそも対象の属性の値が存在しない場合、入力要素にaria-invalid属性を自動的にon/offする処理をしない\n if (errorAttr) {\n if (errorAttr === 'true') {\n input.setAttribute('aria-invalid', 'true')\n } else if (\n // HINT: 入力要素自体にerror属性が設定されている場合、そちらを優先する\n input.getAttribute('data-smarthr-ui-input-error') !== 'true' &&\n // HINT: Fieldset > FormControlのようにネストしている場合を考慮して\n // autoBindErrorしているFormGroupが親方向に存在する場合、子の入力要素からaria-invalidを外さないようにする\n !input.closest(`${WRAPPER_SELECTOR}[data-auto-bind-error-input='true']`)\n ) {\n input.removeAttribute('aria-invalid')\n }\n }\n\n const nextDescribedBy = node.getAttribute('data-auto-bind-aria-describedby-for-input')\n const ariaDescribedBy = input.getAttribute('aria-describedby') || ''\n const currentTokens = ariaDescribedBy ? ariaDescribedBy.split(' ') : []\n // HINT: 自分が過去に付与したid以外(=外部由来のid)だけを残す\n const externalTokens = currentTokens.filter(\n (token) => !managedDescribedbyIdsRef.current.includes(token),\n )\n const describedbyIdTokens = nextDescribedBy ? nextDescribedBy.split(' ') : []\n const nextValue = [...externalTokens, ...describedbyIdTokens].join(' ')\n\n if (nextValue !== ariaDescribedBy) {\n if (nextValue) {\n input.setAttribute('aria-describedby', nextValue)\n } else {\n input.removeAttribute('aria-describedby')\n }\n }\n\n managedDescribedbyIdsRef.current = describedbyIdTokens\n }\n\n action()\n\n const observer = new MutationObserver(action)\n observer.observe(node, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['data-auto-bind-error-input', 'data-auto-bind-aria-describedby-for-input'],\n })\n\n return () => {\n observer.disconnect()\n }\n }, [])\n\n const wrapperCallbackRef = useMergeRefs(innerCallbackRef, outerRef)\n\n return (\n <Stack\n {...rest}\n as={as}\n ref={wrapperCallbackRef}\n gap={innerMargin ?? 0.5}\n className={classNames.wrapper}\n aria-describedby={as === 'fieldset' ? describedbyIds || undefined : undefined}\n data-auto-bind-error-input={autoBindErrorInput ? visibleErrorMessages.toString() : undefined}\n data-auto-bind-aria-describedby-for-input={describedbyIds}\n >\n <LabelComponent\n managedLabelId={label.id}\n managedHtmlFor={label.htmlFor}\n unrecommendedHideLabel={label.unrecommendedHide}\n labelType={label.styleType}\n labelIcon={label.icon}\n statusLabels={actualStatusLabels}\n label={label.text}\n subActionArea={subActionArea}\n />\n {helpMessage && (\n <p id={helpMessageId} className=\"smarthr-ui-FormControl-helpMessage\">\n {helpMessage}\n </p>\n )}\n {exampleMessage && (\n <Text\n as=\"p\"\n id={exampleMessageId}\n italic\n color=\"TEXT_GREY\"\n className=\"smarthr-ui-FormControl-exampleMessage\"\n >\n {exampleMessage}\n </Text>\n )}\n {visibleErrorMessages && (\n <div id={errorMessagesId}>\n {errorMessages.map((message, index) => (\n <Text\n key={index}\n as=\"p\"\n className=\"smarthr-ui-FormControl-errorMessage\"\n icon={\n <FaCircleExclamationIcon className=\"smarthr-ui-FormControl-errorMessage-Icon shr-text-danger\" />\n }\n >\n <LiveRegion role=\"alert\">{message}</LiveRegion>\n </Text>\n ))}\n </div>\n )}\n <div className={classNames.childrenWrapper}>{children}</div>\n {supplementaryMessage && (\n <Text\n as=\"p\"\n id={supplementaryMessageId}\n size=\"S\"\n color=\"TEXT_GREY\"\n className=\"smarthr-ui-FormControl-supplementaryMessage\"\n >\n {supplementaryMessage}\n </Text>\n )}\n </Stack>\n )\n}\n\nexport const LabelBody: FC<\n Pick<ComponentProps<typeof Text>, 'styleType' | 'icon' | 'children'> &\n Pick<LabelComponentProps, 'statusLabels'>\n> = ({ styleType, icon, children, statusLabels }) => (\n <>\n <Text styleType={styleType} icon={icon}>\n <span className=\"smarthr-ui-FormControl-labelText\">{children}</span>\n </Text>\n {statusLabels.length > 0 && (\n <Cluster as=\"span\" gap={0.25}>\n {statusLabels}\n </Cluster>\n )}\n </>\n)\n\nexport const LabelCluster: FC<\n PropsWithChildren<{ as?: 'label'; htmlFor?: string; id?: string; 'aria-hidden'?: 'true' }>\n> = ({ children, ...rest }) => (\n <Cluster {...rest} align=\"center\" className=\"smarthr-ui-FormControl-label\">\n {children}\n </Cluster>\n)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAsCA;AACA;AACA;;;;AAqBE;;;;AAQE;AACE;AACE;AACA;;;AAIN;AACA;;AAEE;;AAEF;AACA;AAEA;;;AAII;;;AAGA;;;AAGA;;;AAGA;;AAGF;;AAGF;AAEA;;;;;;;;;;;;AAgBM;AACE;;AACK;;AAEL;;;;AAKA;;;;;AAMJ;;;AAKA;AACA;AAEA;;AAEI;;;AAEA;;;AAIJ;AACF;AAEA;AAEA;AACA;AACE;AACA;AACA;AACA;AACD;AAED;;AAEA;;;;AAwEJ;AAEO;AAgBA;;"}
@@ -2,7 +2,9 @@
2
2
 
3
3
  const CHILDREN_WRAPPER_INPUT_SELECTOR = `.smarthr-ui-FormControl-childrenWrapper [data-smarthr-ui-input="true"]`;
4
4
  const LABEL_TEXT_SELECTOR = '.smarthr-ui-FormControl-labelText';
5
+ const WRAPPER_SELECTOR = '.smarthr-ui-FormControl';
5
6
 
6
7
  exports.CHILDREN_WRAPPER_INPUT_SELECTOR = CHILDREN_WRAPPER_INPUT_SELECTOR;
7
8
  exports.LABEL_TEXT_SELECTOR = LABEL_TEXT_SELECTOR;
9
+ exports.WRAPPER_SELECTOR = WRAPPER_SELECTOR;
8
10
  //# sourceMappingURL=constants.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.cjs","sources":["../../../../src/components/FormGroup/client/constants.ts"],"sourcesContent":["export const CHILDREN_WRAPPER_INPUT_SELECTOR = `.smarthr-ui-FormControl-childrenWrapper [data-smarthr-ui-input=\"true\"]`\nexport const LABEL_TEXT_SELECTOR = '.smarthr-ui-FormControl-labelText'\n"],"names":[],"mappings":";;AAAO,MAAM,+BAA+B,GAAG;AACxC,MAAM,mBAAmB,GAAG;;;"}
1
+ {"version":3,"file":"constants.cjs","sources":["../../../../src/components/FormGroup/client/constants.ts"],"sourcesContent":["export const CHILDREN_WRAPPER_INPUT_SELECTOR = `.smarthr-ui-FormControl-childrenWrapper [data-smarthr-ui-input=\"true\"]`\nexport const LABEL_TEXT_SELECTOR = '.smarthr-ui-FormControl-labelText'\nexport const WRAPPER_SELECTOR = '.smarthr-ui-FormControl'\n"],"names":[],"mappings":";;AAAO,MAAM,+BAA+B,GAAG;AACxC,MAAM,mBAAmB,GAAG;AAC5B,MAAM,gBAAgB,GAAG;;;;"}
@@ -1,2 +1,3 @@
1
1
  export declare const CHILDREN_WRAPPER_INPUT_SELECTOR = ".smarthr-ui-FormControl-childrenWrapper [data-smarthr-ui-input=\"true\"]";
2
2
  export declare const LABEL_TEXT_SELECTOR = ".smarthr-ui-FormControl-labelText";
3
+ export declare const WRAPPER_SELECTOR = ".smarthr-ui-FormControl";