smarthr-ui 103.0.0 → 103.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/components/AppHeader/AppHeader.cjs +2 -2
- package/lib/components/AppHeader/AppHeader.cjs.map +1 -1
- package/lib/components/AppHeader/AppHeader.js +2 -2
- package/lib/components/AppHeader/AppHeader.js.map +1 -1
- package/lib/components/AppHeader/components/common/CommonButton.cjs +1 -1
- package/lib/components/AppHeader/components/common/CommonButton.cjs.map +1 -1
- package/lib/components/AppHeader/components/common/CommonButton.js +1 -1
- package/lib/components/AppHeader/components/common/CommonButton.js.map +1 -1
- package/lib/components/AppHeader/components/desktop/Navigation.cjs +1 -1
- package/lib/components/AppHeader/components/desktop/Navigation.cjs.map +1 -1
- package/lib/components/AppHeader/components/desktop/Navigation.js +1 -1
- package/lib/components/AppHeader/components/desktop/Navigation.js.map +1 -1
- package/lib/components/AppHeader/components/mobile/AppLauncher.cjs +4 -1
- package/lib/components/AppHeader/components/mobile/AppLauncher.cjs.map +1 -1
- package/lib/components/AppHeader/components/mobile/AppLauncher.js +4 -1
- package/lib/components/AppHeader/components/mobile/AppLauncher.js.map +1 -1
- package/lib/components/AppHeader/components/mobile/MenuDialog.cjs +4 -2
- package/lib/components/AppHeader/components/mobile/MenuDialog.cjs.map +1 -1
- package/lib/components/AppHeader/components/mobile/MenuDialog.js +4 -2
- package/lib/components/AppHeader/components/mobile/MenuDialog.js.map +1 -1
- package/lib/components/Badge/Badge.cjs +1 -1
- package/lib/components/Badge/Badge.cjs.map +1 -1
- package/lib/components/Badge/Badge.js +1 -1
- package/lib/components/Badge/Badge.js.map +1 -1
- package/lib/components/Browser/Browser.cjs +1 -1
- package/lib/components/Browser/Browser.cjs.map +1 -1
- package/lib/components/Browser/Browser.js +1 -1
- package/lib/components/Browser/Browser.js.map +1 -1
- package/lib/components/Combobox/client/useListbox.cjs +24 -7
- package/lib/components/Combobox/client/useListbox.cjs.map +1 -1
- package/lib/components/Combobox/client/useListbox.js +24 -7
- package/lib/components/Combobox/client/useListbox.js.map +1 -1
- package/lib/components/Dialog/ControlledStepFormDialog/client/ControlledStepFormDialog.cjs +1 -1
- package/lib/components/Dialog/ControlledStepFormDialog/client/ControlledStepFormDialog.cjs.map +1 -1
- package/lib/components/Dialog/ControlledStepFormDialog/client/ControlledStepFormDialog.js +1 -1
- package/lib/components/Dialog/ControlledStepFormDialog/client/ControlledStepFormDialog.js.map +1 -1
- package/lib/components/Dialog/ModelessDialog/client/ModelessDialog.cjs +33 -11
- package/lib/components/Dialog/ModelessDialog/client/ModelessDialog.cjs.map +1 -1
- package/lib/components/Dialog/ModelessDialog/client/ModelessDialog.js +33 -11
- package/lib/components/Dialog/ModelessDialog/client/ModelessDialog.js.map +1 -1
- package/lib/components/Dialog/client/DialogContent.cjs +15 -4
- package/lib/components/Dialog/client/DialogContent.cjs.map +1 -1
- package/lib/components/Dialog/client/DialogContent.js +15 -4
- package/lib/components/Dialog/client/DialogContent.js.map +1 -1
- package/lib/components/Dialog/dialogContentClassNameGenerator.cjs +4 -1
- package/lib/components/Dialog/dialogContentClassNameGenerator.cjs.map +1 -1
- package/lib/components/Dialog/dialogContentClassNameGenerator.d.ts +3 -3
- package/lib/components/Dialog/dialogContentClassNameGenerator.js +4 -1
- package/lib/components/Dialog/dialogContentClassNameGenerator.js.map +1 -1
- package/lib/components/Dropdown/client/Dropdown.cjs +4 -1
- package/lib/components/Dropdown/client/Dropdown.cjs.map +1 -1
- package/lib/components/Dropdown/client/Dropdown.js +4 -1
- package/lib/components/Dropdown/client/Dropdown.js.map +1 -1
- package/lib/components/Dropdown/client/DropdownMenuButton/DropdownMenuButton.cjs +1 -1
- package/lib/components/Dropdown/client/DropdownMenuButton/DropdownMenuButton.cjs.map +1 -1
- package/lib/components/Dropdown/client/DropdownMenuButton/DropdownMenuButton.js +1 -1
- package/lib/components/Dropdown/client/DropdownMenuButton/DropdownMenuButton.js.map +1 -1
- package/lib/components/Dropdown/client/SortDropdown/SortDropdown.cjs +1 -1
- package/lib/components/Dropdown/client/SortDropdown/SortDropdown.cjs.map +1 -1
- package/lib/components/Dropdown/client/SortDropdown/SortDropdown.js +1 -1
- package/lib/components/Dropdown/client/SortDropdown/SortDropdown.js.map +1 -1
- package/lib/components/Dropdown/client/getContentBoxStyle.cjs +24 -14
- package/lib/components/Dropdown/client/getContentBoxStyle.cjs.map +1 -1
- package/lib/components/Dropdown/client/getContentBoxStyle.d.ts +3 -2
- package/lib/components/Dropdown/client/getContentBoxStyle.js +24 -14
- package/lib/components/Dropdown/client/getContentBoxStyle.js.map +1 -1
- package/lib/components/ErrorScreen/ErrorScreen.cjs +5 -1
- package/lib/components/ErrorScreen/ErrorScreen.cjs.map +1 -1
- package/lib/components/ErrorScreen/ErrorScreen.js +5 -1
- package/lib/components/ErrorScreen/ErrorScreen.js.map +1 -1
- package/lib/components/FileViewer/client/FileViewer.cjs +2 -2
- package/lib/components/FileViewer/client/FileViewer.cjs.map +1 -1
- package/lib/components/FileViewer/client/FileViewer.js +2 -2
- package/lib/components/FileViewer/client/FileViewer.js.map +1 -1
- package/lib/components/FloatArea/FloatArea.cjs +32 -27
- package/lib/components/FloatArea/FloatArea.cjs.map +1 -1
- package/lib/components/FloatArea/FloatArea.js +32 -27
- package/lib/components/FloatArea/FloatArea.js.map +1 -1
- package/lib/components/FloatArea/client/FloatAreaPanel.cjs +42 -0
- package/lib/components/FloatArea/client/FloatAreaPanel.cjs.map +1 -0
- package/lib/components/FloatArea/client/FloatAreaPanel.d.ts +5 -0
- package/lib/components/FloatArea/client/FloatAreaPanel.js +40 -0
- package/lib/components/FloatArea/client/FloatAreaPanel.js.map +1 -0
- package/lib/components/FloatArea/client/index.cjs +8 -0
- package/lib/components/FloatArea/client/index.cjs.map +1 -0
- package/lib/components/FloatArea/client/index.d.ts +1 -0
- package/lib/components/FloatArea/client/index.js +2 -0
- package/lib/components/FloatArea/client/index.js.map +1 -0
- package/lib/components/Header/Header.cjs +1 -1
- package/lib/components/Header/Header.cjs.map +1 -1
- package/lib/components/Header/Header.js +1 -1
- package/lib/components/Header/Header.js.map +1 -1
- package/lib/components/Header/LanguageSwitcher/client/LanguageSwitcher.cjs +1 -1
- package/lib/components/Header/LanguageSwitcher/client/LanguageSwitcher.cjs.map +1 -1
- package/lib/components/Header/LanguageSwitcher/client/LanguageSwitcher.js +1 -1
- package/lib/components/Header/LanguageSwitcher/client/LanguageSwitcher.js.map +1 -1
- package/lib/components/Heading/client/PageHeading/PageHeading.cjs.map +1 -1
- package/lib/components/Heading/client/PageHeading/PageHeading.js.map +1 -1
- package/lib/components/Icon/FilterIcon.cjs +1 -1
- package/lib/components/Icon/FilterIcon.cjs.map +1 -1
- package/lib/components/Icon/FilterIcon.js +1 -1
- package/lib/components/Icon/FilterIcon.js.map +1 -1
- package/lib/components/Input/SearchInput/SearchInput.cjs +1 -1
- package/lib/components/Input/SearchInput/SearchInput.cjs.map +1 -1
- package/lib/components/Input/SearchInput/SearchInput.js +1 -1
- package/lib/components/Input/SearchInput/SearchInput.js.map +1 -1
- package/lib/components/Input/WarekiPicker/client/Portal.cjs +9 -5
- package/lib/components/Input/WarekiPicker/client/Portal.cjs.map +1 -1
- package/lib/components/Input/WarekiPicker/client/Portal.js +9 -5
- package/lib/components/Input/WarekiPicker/client/Portal.js.map +1 -1
- package/lib/components/Input/WarekiPicker/client/WarekiPicker.cjs +1 -1
- package/lib/components/Input/WarekiPicker/client/WarekiPicker.cjs.map +1 -1
- package/lib/components/Input/WarekiPicker/client/WarekiPicker.js +1 -1
- package/lib/components/Input/WarekiPicker/client/WarekiPicker.js.map +1 -1
- package/lib/components/Input/client/Input.cjs +2 -2
- package/lib/components/Input/client/Input.cjs.map +1 -1
- package/lib/components/Input/client/Input.js +2 -2
- package/lib/components/Input/client/Input.js.map +1 -1
- package/lib/components/InputFile/client/FilePreviewDialog.cjs +2 -2
- package/lib/components/InputFile/client/FilePreviewDialog.cjs.map +1 -1
- package/lib/components/InputFile/client/FilePreviewDialog.js +2 -2
- package/lib/components/InputFile/client/FilePreviewDialog.js.map +1 -1
- package/lib/components/InputFile/client/InputFileMultiplyAppendable.cjs +4 -4
- package/lib/components/InputFile/client/InputFileMultiplyAppendable.cjs.map +1 -1
- package/lib/components/InputFile/client/InputFileMultiplyAppendable.js +4 -4
- package/lib/components/InputFile/client/InputFileMultiplyAppendable.js.map +1 -1
- package/lib/components/InputFile/client/InputFileNative.cjs +4 -4
- package/lib/components/InputFile/client/InputFileNative.cjs.map +1 -1
- package/lib/components/InputFile/client/InputFileNative.js +4 -4
- package/lib/components/InputFile/client/InputFileNative.js.map +1 -1
- package/lib/components/InputFile/client/parts.cjs +1 -1
- package/lib/components/InputFile/client/parts.cjs.map +1 -1
- package/lib/components/InputFile/client/parts.js +1 -1
- package/lib/components/InputFile/client/parts.js.map +1 -1
- package/lib/components/InputFile/client/style.cjs +39 -4
- package/lib/components/InputFile/client/style.cjs.map +1 -1
- package/lib/components/InputFile/client/style.d.ts +98 -0
- package/lib/components/InputFile/client/style.js +39 -4
- package/lib/components/InputFile/client/style.js.map +1 -1
- package/lib/components/InputFile/types.d.ts +3 -0
- package/lib/components/NotificationBar/NotificationBar.cjs +1 -1
- package/lib/components/NotificationBar/NotificationBar.cjs.map +1 -1
- package/lib/components/NotificationBar/NotificationBar.js +1 -1
- package/lib/components/NotificationBar/NotificationBar.js.map +1 -1
- package/lib/components/Panel/Panel.d.ts +56 -56
- package/lib/components/RadioButtonPanel/RadioButtonPanel.cjs +1 -1
- package/lib/components/RadioButtonPanel/RadioButtonPanel.cjs.map +1 -1
- package/lib/components/RadioButtonPanel/RadioButtonPanel.js +1 -1
- package/lib/components/RadioButtonPanel/RadioButtonPanel.js.map +1 -1
- package/lib/components/SideNav/SideNavItemButton.cjs +2 -2
- package/lib/components/SideNav/SideNavItemButton.cjs.map +1 -1
- package/lib/components/SideNav/SideNavItemButton.js +2 -2
- package/lib/components/SideNav/SideNavItemButton.js.map +1 -1
- package/lib/components/SmartHRAILogo/SmartHRAILogo.cjs +1 -1
- package/lib/components/SmartHRAILogo/SmartHRAILogo.cjs.map +1 -1
- package/lib/components/SmartHRAILogo/SmartHRAILogo.js +1 -1
- package/lib/components/SmartHRAILogo/SmartHRAILogo.js.map +1 -1
- package/lib/components/Table/Th/Th.cjs +1 -1
- package/lib/components/Table/Th/Th.cjs.map +1 -1
- package/lib/components/Table/Th/Th.js +1 -1
- package/lib/components/Table/Th/Th.js.map +1 -1
- package/lib/components/Text/Text.cjs +1 -1
- package/lib/components/Text/Text.cjs.map +1 -1
- package/lib/components/Text/Text.js +1 -1
- package/lib/components/Text/Text.js.map +1 -1
- package/lib/components/Textarea/client/Textarea.cjs +19 -2
- package/lib/components/Textarea/client/Textarea.cjs.map +1 -1
- package/lib/components/Textarea/client/Textarea.js +19 -2
- package/lib/components/Textarea/client/Textarea.js.map +1 -1
- package/lib/components/Tooltip/client/Tooltip.cjs +2 -2
- package/lib/components/Tooltip/client/Tooltip.cjs.map +1 -1
- package/lib/components/Tooltip/client/Tooltip.js +2 -2
- package/lib/components/Tooltip/client/Tooltip.js.map +1 -1
- package/lib/components/Tooltip/client/TooltipPortal.cjs +29 -18
- package/lib/components/Tooltip/client/TooltipPortal.cjs.map +1 -1
- package/lib/components/Tooltip/client/TooltipPortal.js +29 -18
- package/lib/components/Tooltip/client/TooltipPortal.js.map +1 -1
- package/lib/hooks/client/useAreaClickCallbackRef.cjs +1 -1
- package/lib/hooks/client/useAreaClickCallbackRef.cjs.map +1 -1
- package/lib/hooks/client/useAreaClickCallbackRef.js +1 -1
- package/lib/hooks/client/useAreaClickCallbackRef.js.map +1 -1
- package/lib/hooks/client/useSafeAreaInsets/index.cjs +8 -0
- package/lib/hooks/client/useSafeAreaInsets/index.cjs.map +1 -0
- package/lib/hooks/client/useSafeAreaInsets/index.d.ts +1 -0
- package/lib/hooks/client/useSafeAreaInsets/index.js +2 -0
- package/lib/hooks/client/useSafeAreaInsets/index.js.map +1 -0
- package/lib/hooks/client/useSafeAreaInsets/useSafeAreaInsets.cjs +72 -0
- package/lib/hooks/client/useSafeAreaInsets/useSafeAreaInsets.cjs.map +1 -0
- package/lib/hooks/client/useSafeAreaInsets/useSafeAreaInsets.d.ts +20 -0
- package/lib/hooks/client/useSafeAreaInsets/useSafeAreaInsets.js +70 -0
- package/lib/hooks/client/useSafeAreaInsets/useSafeAreaInsets.js.map +1 -0
- package/lib/libs/map.cjs +1 -1
- package/lib/libs/map.cjs.map +1 -1
- package/lib/libs/map.js +1 -1
- package/lib/libs/map.js.map +1 -1
- package/lib/themes/createFontSize.cjs.map +1 -1
- package/lib/themes/createFontSize.d.ts +0 -2
- package/lib/themes/createFontSize.js.map +1 -1
- package/lib/themes/index.d.ts +0 -2
- package/metadata.json +1 -1
- package/package.json +1 -1
- package/smarthr-ui.css +140 -104
|
@@ -46,7 +46,7 @@ const Browser = ({ value, items, onSelectItem, className, ...rest }) => {
|
|
|
46
46
|
return [...node.getAncestors().map((n) => n.value), node.value];
|
|
47
47
|
}, [rootNode, value]);
|
|
48
48
|
const latest = hooks_useLatest.useLatest({ onSelectItem, value, rootNode });
|
|
49
|
-
const hasOnSelectItem =
|
|
49
|
+
const hasOnSelectItem = Boolean(onSelectItem);
|
|
50
50
|
const functions = React.useMemo(() => {
|
|
51
51
|
// FIXME: focusメソッドのfocusVisibleが主要ブラウザでサポートされたら使うようにしたい(現状ではマウスクリックでもfocusのoutlineが出てしまう)
|
|
52
52
|
// https://developer.mozilla.org/ja/docs/Web/API/HTMLElement/focus
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Browser.cjs","sources":["../../../src/components/Browser/Browser.tsx"],"sourcesContent":["import { type ChangeEvent, type FC, type KeyboardEventHandler, useMemo } from 'react'\nimport { tv } from 'tailwind-variants'\n\nimport { useLatest } from '../../hooks/useLatest'\n\nimport { BrowserColumn } from './BrowserColumn'\nimport { ItemNode, type ItemNodeLike, RootNode } from './models'\nimport { getElementIdFromNode } from './utils'\n\nimport type { ExtendElementPropsWithRef } from '../../types'\n\nconst classNameGenerator = tv({\n slots: {\n wrapper: ['smarthr-ui-Browser', 'shr-flex'],\n column: ['shr-min-w-[13em] shr-list-none', '[&_+_&]:shr-border-l-shorthand'],\n },\n variants: {\n isSingleColumn: {\n true: {\n column: 'shr-max-w-[theme(width.1/3)]',\n },\n false: {\n column: 'last:shr-grow',\n },\n },\n },\n})\n\ntype Props = ExtendElementPropsWithRef<\n 'div',\n {\n /** 表示する item の配列 */\n items: ItemNodeLike[]\n /** 選択中の item の値 */\n value?: string\n /** 選択された際に呼び出されるコールバック。第一引数に item の value を取る。 */\n onSelectItem?: (value: string) => void\n }\n>\n\nexport const Browser: FC<Props> = ({ value, items, onSelectItem, className, ...rest }) => {\n // eslint-disable-next-line smarthr/best-practice-for-unstable-dependencies\n const rootNode = useMemo(() => RootNode.from({ children: items }), [items])\n const columns = useMemo(() => rootNode.toViewData(value), [rootNode, value])\n\n const isSingleColumn = columns.length === 1\n const classNames = useMemo(() => {\n const { wrapper, column } = classNameGenerator()\n\n return {\n wrapper: wrapper({ className }),\n column: column({ isSingleColumn }),\n }\n }, [isSingleColumn, className])\n\n const selectedPath = useMemo(() => {\n if (!value) return []\n const node = rootNode.findByValue(value)\n if (!node) return []\n return [...node.getAncestors().map((n) => n.value), node.value]\n }, [rootNode, value])\n\n const latest = useLatest({ onSelectItem, value, rootNode })\n const hasOnSelectItem =
|
|
1
|
+
{"version":3,"file":"Browser.cjs","sources":["../../../src/components/Browser/Browser.tsx"],"sourcesContent":["import { type ChangeEvent, type FC, type KeyboardEventHandler, useMemo } from 'react'\nimport { tv } from 'tailwind-variants'\n\nimport { useLatest } from '../../hooks/useLatest'\n\nimport { BrowserColumn } from './BrowserColumn'\nimport { ItemNode, type ItemNodeLike, RootNode } from './models'\nimport { getElementIdFromNode } from './utils'\n\nimport type { ExtendElementPropsWithRef } from '../../types'\n\nconst classNameGenerator = tv({\n slots: {\n wrapper: ['smarthr-ui-Browser', 'shr-flex'],\n column: ['shr-min-w-[13em] shr-list-none', '[&_+_&]:shr-border-l-shorthand'],\n },\n variants: {\n isSingleColumn: {\n true: {\n column: 'shr-max-w-[theme(width.1/3)]',\n },\n false: {\n column: 'last:shr-grow',\n },\n },\n },\n})\n\ntype Props = ExtendElementPropsWithRef<\n 'div',\n {\n /** 表示する item の配列 */\n items: ItemNodeLike[]\n /** 選択中の item の値 */\n value?: string\n /** 選択された際に呼び出されるコールバック。第一引数に item の value を取る。 */\n onSelectItem?: (value: string) => void\n }\n>\n\nexport const Browser: FC<Props> = ({ value, items, onSelectItem, className, ...rest }) => {\n // eslint-disable-next-line smarthr/best-practice-for-unstable-dependencies\n const rootNode = useMemo(() => RootNode.from({ children: items }), [items])\n const columns = useMemo(() => rootNode.toViewData(value), [rootNode, value])\n\n const isSingleColumn = columns.length === 1\n const classNames = useMemo(() => {\n const { wrapper, column } = classNameGenerator()\n\n return {\n wrapper: wrapper({ className }),\n column: column({ isSingleColumn }),\n }\n }, [isSingleColumn, className])\n\n const selectedPath = useMemo(() => {\n if (!value) return []\n const node = rootNode.findByValue(value)\n if (!node) return []\n return [...node.getAncestors().map((n) => n.value), node.value]\n }, [rootNode, value])\n\n const latest = useLatest({ onSelectItem, value, rootNode })\n const hasOnSelectItem = Boolean(onSelectItem)\n\n const functions = useMemo(() => {\n // FIXME: focusメソッドのfocusVisibleが主要ブラウザでサポートされたら使うようにしたい(現状ではマウスクリックでもfocusのoutlineが出てしまう)\n // https://developer.mozilla.org/ja/docs/Web/API/HTMLElement/focus\n const handleDelegateKeyDown: KeyboardEventHandler = (e) => {\n const selectedNode = latest.value ? latest.rootNode.findByValue(latest.value) : undefined\n\n if (!selectedNode) {\n return\n }\n\n let target: ItemNode | undefined = undefined\n\n switch (e.key) {\n case 'ArrowUp': {\n target = selectedNode.getPrev() ?? selectedNode.parent?.getLastChild()\n\n break\n }\n case 'ArrowDown': {\n target = selectedNode.getNext() ?? selectedNode.parent?.getFirstChild()\n\n break\n }\n case 'ArrowLeft': {\n const node = selectedNode.parent\n\n if (node instanceof ItemNode) {\n target = node\n }\n\n break\n }\n case 'ArrowRight':\n case 'Enter':\n case ' ': {\n target = selectedNode.getFirstChild()\n\n break\n }\n }\n\n if (target) {\n e.preventDefault()\n latest.onSelectItem?.(target.value)\n document.getElementById(getElementIdFromNode(target.value))?.focus()\n }\n }\n\n return {\n handleDelegateKeyDown,\n handleChangeInput: hasOnSelectItem\n ? (e: ChangeEvent<HTMLInputElement>) => {\n latest.onSelectItem?.(e.currentTarget.value)\n }\n : undefined,\n }\n }, [hasOnSelectItem, latest])\n\n return (\n // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions\n <div\n {...rest}\n role=\"application\"\n className={classNames.wrapper}\n onKeyDown={functions.handleDelegateKeyDown}\n >\n {columns.map((colItems, index) => (\n <BrowserColumn\n key={index}\n value={selectedPath[index]}\n index={index}\n className={classNames.column}\n handleChangeInput={functions.handleChangeInput}\n items={colItems}\n />\n ))}\n </div>\n )\n}\n"],"names":["tv","useMemo","RootNode","useLatest","ItemNode","getElementIdFromNode","_jsx","BrowserColumn"],"mappings":"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"}
|
|
@@ -44,7 +44,7 @@ const Browser = ({ value, items, onSelectItem, className, ...rest }) => {
|
|
|
44
44
|
return [...node.getAncestors().map((n) => n.value), node.value];
|
|
45
45
|
}, [rootNode, value]);
|
|
46
46
|
const latest = useLatest({ onSelectItem, value, rootNode });
|
|
47
|
-
const hasOnSelectItem =
|
|
47
|
+
const hasOnSelectItem = Boolean(onSelectItem);
|
|
48
48
|
const functions = useMemo(() => {
|
|
49
49
|
// FIXME: focusメソッドのfocusVisibleが主要ブラウザでサポートされたら使うようにしたい(現状ではマウスクリックでもfocusのoutlineが出てしまう)
|
|
50
50
|
// https://developer.mozilla.org/ja/docs/Web/API/HTMLElement/focus
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Browser.js","sources":["../../../src/components/Browser/Browser.tsx"],"sourcesContent":["import { type ChangeEvent, type FC, type KeyboardEventHandler, useMemo } from 'react'\nimport { tv } from 'tailwind-variants'\n\nimport { useLatest } from '../../hooks/useLatest'\n\nimport { BrowserColumn } from './BrowserColumn'\nimport { ItemNode, type ItemNodeLike, RootNode } from './models'\nimport { getElementIdFromNode } from './utils'\n\nimport type { ExtendElementPropsWithRef } from '../../types'\n\nconst classNameGenerator = tv({\n slots: {\n wrapper: ['smarthr-ui-Browser', 'shr-flex'],\n column: ['shr-min-w-[13em] shr-list-none', '[&_+_&]:shr-border-l-shorthand'],\n },\n variants: {\n isSingleColumn: {\n true: {\n column: 'shr-max-w-[theme(width.1/3)]',\n },\n false: {\n column: 'last:shr-grow',\n },\n },\n },\n})\n\ntype Props = ExtendElementPropsWithRef<\n 'div',\n {\n /** 表示する item の配列 */\n items: ItemNodeLike[]\n /** 選択中の item の値 */\n value?: string\n /** 選択された際に呼び出されるコールバック。第一引数に item の value を取る。 */\n onSelectItem?: (value: string) => void\n }\n>\n\nexport const Browser: FC<Props> = ({ value, items, onSelectItem, className, ...rest }) => {\n // eslint-disable-next-line smarthr/best-practice-for-unstable-dependencies\n const rootNode = useMemo(() => RootNode.from({ children: items }), [items])\n const columns = useMemo(() => rootNode.toViewData(value), [rootNode, value])\n\n const isSingleColumn = columns.length === 1\n const classNames = useMemo(() => {\n const { wrapper, column } = classNameGenerator()\n\n return {\n wrapper: wrapper({ className }),\n column: column({ isSingleColumn }),\n }\n }, [isSingleColumn, className])\n\n const selectedPath = useMemo(() => {\n if (!value) return []\n const node = rootNode.findByValue(value)\n if (!node) return []\n return [...node.getAncestors().map((n) => n.value), node.value]\n }, [rootNode, value])\n\n const latest = useLatest({ onSelectItem, value, rootNode })\n const hasOnSelectItem =
|
|
1
|
+
{"version":3,"file":"Browser.js","sources":["../../../src/components/Browser/Browser.tsx"],"sourcesContent":["import { type ChangeEvent, type FC, type KeyboardEventHandler, useMemo } from 'react'\nimport { tv } from 'tailwind-variants'\n\nimport { useLatest } from '../../hooks/useLatest'\n\nimport { BrowserColumn } from './BrowserColumn'\nimport { ItemNode, type ItemNodeLike, RootNode } from './models'\nimport { getElementIdFromNode } from './utils'\n\nimport type { ExtendElementPropsWithRef } from '../../types'\n\nconst classNameGenerator = tv({\n slots: {\n wrapper: ['smarthr-ui-Browser', 'shr-flex'],\n column: ['shr-min-w-[13em] shr-list-none', '[&_+_&]:shr-border-l-shorthand'],\n },\n variants: {\n isSingleColumn: {\n true: {\n column: 'shr-max-w-[theme(width.1/3)]',\n },\n false: {\n column: 'last:shr-grow',\n },\n },\n },\n})\n\ntype Props = ExtendElementPropsWithRef<\n 'div',\n {\n /** 表示する item の配列 */\n items: ItemNodeLike[]\n /** 選択中の item の値 */\n value?: string\n /** 選択された際に呼び出されるコールバック。第一引数に item の value を取る。 */\n onSelectItem?: (value: string) => void\n }\n>\n\nexport const Browser: FC<Props> = ({ value, items, onSelectItem, className, ...rest }) => {\n // eslint-disable-next-line smarthr/best-practice-for-unstable-dependencies\n const rootNode = useMemo(() => RootNode.from({ children: items }), [items])\n const columns = useMemo(() => rootNode.toViewData(value), [rootNode, value])\n\n const isSingleColumn = columns.length === 1\n const classNames = useMemo(() => {\n const { wrapper, column } = classNameGenerator()\n\n return {\n wrapper: wrapper({ className }),\n column: column({ isSingleColumn }),\n }\n }, [isSingleColumn, className])\n\n const selectedPath = useMemo(() => {\n if (!value) return []\n const node = rootNode.findByValue(value)\n if (!node) return []\n return [...node.getAncestors().map((n) => n.value), node.value]\n }, [rootNode, value])\n\n const latest = useLatest({ onSelectItem, value, rootNode })\n const hasOnSelectItem = Boolean(onSelectItem)\n\n const functions = useMemo(() => {\n // FIXME: focusメソッドのfocusVisibleが主要ブラウザでサポートされたら使うようにしたい(現状ではマウスクリックでもfocusのoutlineが出てしまう)\n // https://developer.mozilla.org/ja/docs/Web/API/HTMLElement/focus\n const handleDelegateKeyDown: KeyboardEventHandler = (e) => {\n const selectedNode = latest.value ? latest.rootNode.findByValue(latest.value) : undefined\n\n if (!selectedNode) {\n return\n }\n\n let target: ItemNode | undefined = undefined\n\n switch (e.key) {\n case 'ArrowUp': {\n target = selectedNode.getPrev() ?? selectedNode.parent?.getLastChild()\n\n break\n }\n case 'ArrowDown': {\n target = selectedNode.getNext() ?? selectedNode.parent?.getFirstChild()\n\n break\n }\n case 'ArrowLeft': {\n const node = selectedNode.parent\n\n if (node instanceof ItemNode) {\n target = node\n }\n\n break\n }\n case 'ArrowRight':\n case 'Enter':\n case ' ': {\n target = selectedNode.getFirstChild()\n\n break\n }\n }\n\n if (target) {\n e.preventDefault()\n latest.onSelectItem?.(target.value)\n document.getElementById(getElementIdFromNode(target.value))?.focus()\n }\n }\n\n return {\n handleDelegateKeyDown,\n handleChangeInput: hasOnSelectItem\n ? (e: ChangeEvent<HTMLInputElement>) => {\n latest.onSelectItem?.(e.currentTarget.value)\n }\n : undefined,\n }\n }, [hasOnSelectItem, latest])\n\n return (\n // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions\n <div\n {...rest}\n role=\"application\"\n className={classNames.wrapper}\n onKeyDown={functions.handleDelegateKeyDown}\n >\n {columns.map((colItems, index) => (\n <BrowserColumn\n key={index}\n value={selectedPath[index]}\n index={index}\n className={classNames.column}\n handleChangeInput={functions.handleChangeInput}\n items={colItems}\n />\n ))}\n </div>\n )\n}\n"],"names":["tv","_jsx"],"mappings":"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"}
|
|
@@ -7,6 +7,7 @@ var index = require('./../../../vendor/.pnpm/tailwind-variants@0.3.1_tailwindcss
|
|
|
7
7
|
var hooks_client_useAnimationFrame_useAnimationFrame = require('../../../hooks/client/useAnimationFrame/useAnimationFrame.cjs');
|
|
8
8
|
var hooks_client_useLayoutEffectRef = require('../../../hooks/client/useLayoutEffectRef.cjs');
|
|
9
9
|
var hooks_client_useMergeRefs_useMergeRefs = require('../../../hooks/client/useMergeRefs/useMergeRefs.cjs');
|
|
10
|
+
var hooks_client_useSafeAreaInsets_useSafeAreaInsets = require('../../../hooks/client/useSafeAreaInsets/useSafeAreaInsets.cjs');
|
|
10
11
|
var hooks_client_useTheme = require('../../../hooks/client/useTheme.cjs');
|
|
11
12
|
var hooks_useLatest = require('../../../hooks/useLatest.cjs');
|
|
12
13
|
require('../../../_virtual/dayjs.min.cjs');
|
|
@@ -80,8 +81,18 @@ const useListbox = ({ options, dropdownHelpMessage, dropdownWidth, onAdd, onSele
|
|
|
80
81
|
}
|
|
81
82
|
const theme = hooks_client_useTheme.useTheme();
|
|
82
83
|
const addFrame = hooks_client_useAnimationFrame_useAnimationFrame.useAnimationFrame();
|
|
83
|
-
const
|
|
84
|
-
const
|
|
84
|
+
const getSafeAreaInsets = hooks_client_useSafeAreaInsets_useSafeAreaInsets.useSafeAreaInsets();
|
|
85
|
+
const latest = hooks_useLatest.useLatest({
|
|
86
|
+
onAdd,
|
|
87
|
+
onSelect,
|
|
88
|
+
activeOption,
|
|
89
|
+
options,
|
|
90
|
+
triggerRef,
|
|
91
|
+
theme,
|
|
92
|
+
getSafeAreaInsets,
|
|
93
|
+
addFrame,
|
|
94
|
+
});
|
|
95
|
+
const hasOnAdd = Boolean(onAdd);
|
|
85
96
|
const functions = React.useMemo(() => {
|
|
86
97
|
let listBox = null;
|
|
87
98
|
const moveActiveOptionIndex = (currentActive, delta) => {
|
|
@@ -117,8 +128,10 @@ const useListbox = ({ options, dropdownHelpMessage, dropdownWidth, onAdd, onSele
|
|
|
117
128
|
return;
|
|
118
129
|
}
|
|
119
130
|
const rect = latest.triggerRef.current.getBoundingClientRect();
|
|
120
|
-
|
|
121
|
-
const
|
|
131
|
+
// HINT: safe areaに重ならない領域を、リストボックスを表示できる範囲とする
|
|
132
|
+
const safeAreaInsets = latest.getSafeAreaInsets();
|
|
133
|
+
const bottomSpace = window.innerHeight - safeAreaInsets.bottom - rect.bottom;
|
|
134
|
+
const topSpace = rect.top - safeAreaInsets.top;
|
|
122
135
|
const listBoxHeight = Math.min(listBox.scrollHeight, parseInt(getComputedStyle(listBox).maxHeight, 10));
|
|
123
136
|
const offset = 2;
|
|
124
137
|
let top = 0;
|
|
@@ -146,9 +159,9 @@ const useListbox = ({ options, dropdownHelpMessage, dropdownWidth, onAdd, onSele
|
|
|
146
159
|
// ドロップダウンの幅は maxWidth でビューポート右端から余白分を残すよう制限しているため、位置の判定にも同じ余白を使う
|
|
147
160
|
const viewportMargin = parseInt(latest.theme.spacingByChar(0.5), 10);
|
|
148
161
|
// 入力欄の左端を起点に右方向へ表示する場合に使える幅
|
|
149
|
-
const rightSpace = window.innerWidth - rect.left - viewportMargin;
|
|
162
|
+
const rightSpace = window.innerWidth - safeAreaInsets.right - rect.left - viewportMargin;
|
|
150
163
|
// 入力欄の右端を起点に左方向へ表示する場合に使える幅
|
|
151
|
-
const leftSpace = rect.right;
|
|
164
|
+
const leftSpace = rect.right - safeAreaInsets.left;
|
|
152
165
|
// ビューポートの左端を基準に計算
|
|
153
166
|
let left = window.pageXOffset;
|
|
154
167
|
if (listBoxWidth <= rightSpace) {
|
|
@@ -159,6 +172,10 @@ const useListbox = ({ options, dropdownHelpMessage, dropdownWidth, onAdd, onSele
|
|
|
159
172
|
// 左側に収まる場合は入力欄の右端に揃えて表示
|
|
160
173
|
left += rect.right - listBoxWidth;
|
|
161
174
|
}
|
|
175
|
+
else {
|
|
176
|
+
// どちらにも収まらない場合はsafe areaの左端に揃えて表示
|
|
177
|
+
left += safeAreaInsets.left;
|
|
178
|
+
}
|
|
162
179
|
setListBoxRect({
|
|
163
180
|
top,
|
|
164
181
|
left,
|
|
@@ -300,7 +317,7 @@ const ListBox = React.memo(({ activeOptionId, options, isExpanded, isLoading, no
|
|
|
300
317
|
width: typeof dropdownListWidth === 'string' ? dropdownListWidth : `${dropdownListWidth}px`,
|
|
301
318
|
/* HINT: left に依存させると、算出した幅がさらに maxWidth を縮めて再計算の度に幅が縮んでいくため、
|
|
302
319
|
ビューポート幅のみから算出する */
|
|
303
|
-
maxWidth: `calc(100vw - ${theme.spacingByChar(0.5)})`,
|
|
320
|
+
maxWidth: `calc(100vw - ${theme.spacingByChar(0.5)} - env(safe-area-inset-left) - env(safe-area-inset-right))`,
|
|
304
321
|
height: height ? `${height}px` : undefined,
|
|
305
322
|
},
|
|
306
323
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useListbox.cjs","sources":["../../../../src/components/Combobox/client/useListbox.tsx"],"sourcesContent":["'use client'\n\nimport {\n type KeyboardEvent,\n type MouseEvent,\n type ReactNode,\n type RefCallback,\n type RefObject,\n memo,\n useId,\n useLayoutEffect,\n useMemo,\n useState,\n} from 'react'\nimport { tv } from 'tailwind-variants'\n\nimport { useAnimationFrame } from '../../../hooks/client/useAnimationFrame'\nimport { useLayoutEffectRef } from '../../../hooks/client/useLayoutEffectRef'\nimport { useMergeRefs } from '../../../hooks/client/useMergeRefs'\nimport { useTheme } from '../../../hooks/client/useTheme'\nimport { useLatest } from '../../../hooks/useLatest'\nimport { Localizer } from '../../../intl'\nimport { findDelegateTarget } from '../../../libs/delegate'\nimport { FaCircleInfoIcon } from '../../Icon'\nimport { LiveRegion } from '../../LiveRegion'\nimport { Loader } from '../../Loader'\nimport { Portal } from '../../Portal'\nimport { Scroller } from '../../Scroller'\nimport { Text } from '../../Text'\n\nimport { ItemButton } from './ItemButton'\n\nimport type { ComboboxItem, ComboboxOption } from './types'\n\ntype Props<T> = {\n options: Array<ComboboxOption<T>>\n dropdownHelpMessage?: ReactNode\n dropdownWidth?: string | number\n onAdd?: (label: string) => void\n onSelect: (item: ComboboxItem<T>) => void\n isExpanded: boolean\n isLoading?: boolean\n triggerRef: RefObject<HTMLElement | null>\n /** 検索結果が0件の時に表示するコンテンツ */\n noResultText?: ReactNode\n}\n\ntype Rect = {\n top: number\n left: number\n height?: number\n}\n\nconst KEY_DOWN_REGEX = /^(Arrow)?Down$/\nconst KEY_UP_REGEX = /^(Arrow)?Up/\n\nconst OPTION_INCREMENT_AMOUNT = 100\n\nconst classNameGenerator = tv({\n slots: {\n wrapper: 'shr-absolute',\n dropdownList: [\n 'smarthr-ui-Combobox-dropdownList',\n 'shr-absolute shr-z-overlap shr-box-border shr-min-w-full shr-rounded-m shr-bg-white shr-py-0.5 shr-shadow-layer-3 forced-colors:shr-outline forced-colors:shr-outline-1',\n /* 縦スクロールに気づきやすくするために8個目のアイテムが半分見切れるように max-height を算出\n = (アイテムのフォントサイズ + アイテムの上下padding) * 7.5 + コンテナの上padding */\n 'shr-max-h-[calc((theme(fontSize.base)_+_theme(spacing[0.5])_*_2)_*_7.5_+_theme(spacing[0.5]))]',\n 'aria-hidden:shr-hidden',\n ],\n helpMessage:\n 'shr-whitespace-[initial] shr-border-b-shorthand shr-mx-0.5 shr-mb-0.5 shr-mt-0 shr-px-0.5 shr-pb-0.5 shr-pt-0 shr-text-sm',\n loaderWrapper: 'shr-flex shr-items-center shr-justify-center shr-p-1',\n noItems:\n 'smarthr-ui-Combobox-noItems shr-my-0 shr-block shr-bg-white shr-px-1 shr-py-0.5 shr-text-base',\n },\n})\n\nconst CLASS_NAMES = (() => {\n const { wrapper, dropdownList, helpMessage, loaderWrapper, noItems } = classNameGenerator()\n\n return {\n wrapper: wrapper(),\n dropdownList: dropdownList(),\n helpMessage: helpMessage(),\n loaderWrapper: loaderWrapper(),\n noItems: noItems(),\n }\n})()\n\nexport const useListbox = <T,>({\n options,\n dropdownHelpMessage,\n dropdownWidth,\n onAdd,\n onSelect,\n isExpanded,\n isLoading,\n triggerRef,\n noResultText,\n}: Props<T>) => {\n const listBoxId = useId()\n\n const [navigationType, setNavigationType] = useState<'pointer' | 'key'>('pointer')\n const [listBoxRect, setListBoxRect] = useState<Rect>({\n top: 0,\n left: 0,\n })\n // HINT: calculateRectで同時に計算するとwidthの幅が変更されるタイミングの問題でlistBoxHeightが変化する場合がある\n const [triggerWidth, setTriggerWidth] = useState(0)\n\n const [activeOption, setActiveOption] = useState<ComboboxOption<T> | null>(null)\n const [prevOptions, setPrevOptions] = useState(options)\n\n if (options !== prevOptions) {\n setPrevOptions(options)\n // props の変更によって activeOption の状態が変わりうるので、実態を反映する\n setActiveOption((current) => {\n if (current === null) {\n return null\n }\n\n return options.find((option) => current.id === option.id) ?? null\n })\n }\n\n const theme = useTheme()\n\n const addFrame = useAnimationFrame()\n\n const latest = useLatest({ onAdd, onSelect, activeOption, options, triggerRef, theme, addFrame })\n const hasOnAdd = !!onAdd\n\n const functions = useMemo(() => {\n let listBox: HTMLElement | null = null\n\n const moveActiveOptionIndex = (currentActive: ComboboxOption<T> | null, delta: -1 | 1) => {\n if (latest.options.every((option) => option.item.disabled)) {\n return\n }\n\n const currentActiveIndex =\n currentActive === null\n ? -1\n : latest.options.findIndex((option) => option.id === currentActive.id)\n let nextIndex = 0\n\n if (currentActiveIndex !== -1) {\n nextIndex = (currentActiveIndex + delta + latest.options.length) % latest.options.length\n } else if (delta !== 1) {\n nextIndex = latest.options.length - 1\n }\n\n const nextActive = latest.options[nextIndex]\n\n if (nextActive) {\n if (nextActive.item.disabled) {\n moveActiveOptionIndex(nextActive, delta)\n } else {\n setActiveOption(nextActive)\n }\n }\n }\n\n return {\n baseCallbackRef: (node: HTMLElement | null) => {\n listBox = node\n },\n calculateRect: () => {\n if (!listBox || !latest.triggerRef.current) {\n return\n }\n\n const rect = latest.triggerRef.current.getBoundingClientRect()\n const bottomSpace = window.innerHeight - rect.bottom\n const topSpace = rect.top\n const listBoxHeight = Math.min(\n listBox.scrollHeight,\n parseInt(getComputedStyle(listBox).maxHeight, 10),\n )\n const offset = 2\n\n let top = 0\n let height: number | undefined = undefined\n\n if (bottomSpace >= listBoxHeight) {\n // 下側に十分なスペースがある場合は下側に通常表示\n top = rect.top + rect.height - offset + window.pageYOffset\n } else if (topSpace >= listBoxHeight) {\n // 上側に十分なスペースがある場合は上側に通常表示\n top = rect.top - listBoxHeight + offset + window.pageYOffset\n } else if (topSpace > bottomSpace) {\n // 上下に十分なスペースがなく、上側の方がスペースが大きい場合は上側に縮めて表示\n top = rect.top - topSpace + offset + window.pageYOffset\n height = topSpace\n } else {\n // 下側に縮めて表示\n top = rect.top + rect.height - offset + window.pageYOffset\n height = bottomSpace\n }\n\n // HINT: dropdownWidth は 'auto' や '%' などの CSS 値を取りうるため、算出済みの幅を実測して判定する\n const listBoxWidth = listBox.getBoundingClientRect().width\n // ドロップダウンの幅は maxWidth でビューポート右端から余白分を残すよう制限しているため、位置の判定にも同じ余白を使う\n const viewportMargin = parseInt(latest.theme.spacingByChar(0.5), 10)\n // 入力欄の左端を起点に右方向へ表示する場合に使える幅\n const rightSpace = window.innerWidth - rect.left - viewportMargin\n // 入力欄の右端を起点に左方向へ表示する場合に使える幅\n const leftSpace = rect.right\n\n // ビューポートの左端を基準に計算\n let left = window.pageXOffset\n\n if (listBoxWidth <= rightSpace) {\n // 右側に十分なスペースがある場合は入力欄の左端に揃えて通常表示\n left += rect.left\n } else if (listBoxWidth <= leftSpace) {\n // 左側に収まる場合は入力欄の右端に揃えて表示\n left += rect.right - listBoxWidth\n }\n\n setListBoxRect({\n top,\n left,\n height,\n })\n setTriggerWidth(rect.width)\n },\n handleKeyDownListBox: (e: KeyboardEvent<HTMLElement>) => {\n setNavigationType('key')\n\n if (KEY_DOWN_REGEX.test(e.key)) {\n // HINT: MultiComboboxの削除ボタンにフォーカスがある状態など、input以外からこのハンドラへ\n // 到達する経路ではpreventDefaultされないため、ブラウザ側のデフォルトキー操作(iOS Safariでの\n // ページスクロール等)が発生してしまう。ここで明示的に止める\n e.preventDefault()\n e.stopPropagation()\n moveActiveOptionIndex(latest.activeOption, 1)\n } else if (KEY_UP_REGEX.test(e.key)) {\n e.preventDefault()\n e.stopPropagation()\n moveActiveOptionIndex(latest.activeOption, -1)\n } else if (e.key === 'Enter') {\n if (latest.activeOption === null) {\n return\n }\n\n e.stopPropagation()\n\n if (!latest.activeOption.isNew) {\n latest.onSelect(latest.activeOption.item)\n } else if (latest.onAdd) {\n latest.onAdd(latest.activeOption.item.value)\n }\n } else {\n setActiveOption(null)\n }\n },\n cleanupAddFrame: () => latest.addFrame.cancel(),\n handleAdd: hasOnAdd\n ? (option: ComboboxOption<T>) => {\n // HINT: Dropdown系コンポーネント内でComboboxを使うと、選択肢がportalで表現されている関係上Dropdownが閉じてしまう\n // 処理を遅延させることで正常に閉じる/閉じないの判定を行えるようにする\n latest.addFrame.request(() => {\n latest.onAdd!(option.item.value)\n })\n }\n : undefined,\n handleSelect: (option: ComboboxOption<T>) => {\n latest.onSelect(option.item)\n },\n handleHoverOption: (option: ComboboxOption<T>) => {\n setNavigationType('pointer')\n setActiveOption(option)\n },\n }\n }, [hasOnAdd, latest])\n\n const listBoxLayoutEffectRef = useLayoutEffectRef(\n (node: HTMLElement | null) => {\n // actionOption の要素が表示される位置までリストボックス内をスクロールさせる\n if (!node || activeOption === null || navigationType !== 'key') {\n return\n }\n\n const activeElement = node.querySelector<HTMLElement>('button[data-active=\"true\"]')\n\n if (!activeElement) {\n return\n }\n\n const activeRect = activeElement.getBoundingClientRect()\n const containerRect = node.getBoundingClientRect()\n\n if (activeRect.top < containerRect.top) {\n node.scrollTop -= containerRect.top - activeRect.top\n } else if (activeRect.bottom > containerRect.bottom) {\n node.scrollTop += activeRect.bottom - containerRect.bottom\n }\n },\n [activeOption, navigationType],\n )\n const mergedListBoxRef = useMergeRefs(listBoxLayoutEffectRef, functions.baseCallbackRef)\n\n useLayoutEffect(() => {\n // 閉じたときに activeOption を初期化\n if (!isExpanded) {\n return setActiveOption(null)\n }\n\n functions.calculateRect()\n\n const scrollOption = { capture: true, passive: true }\n window.addEventListener('scroll', functions.calculateRect, scrollOption)\n window.addEventListener('resize', functions.calculateRect, { passive: true })\n\n return () => {\n window.removeEventListener('scroll', functions.calculateRect, scrollOption)\n window.removeEventListener('resize', functions.calculateRect)\n }\n // HINT: optionsが変わる場合メニューのサイズが変わる可能性がある\n // eslint-disable-next-line smarthr/best-practice-for-unstable-dependencies\n }, [isExpanded, options, functions])\n\n return {\n listBoxProps: {\n activeOptionId: activeOption?.id,\n options,\n isExpanded,\n isLoading,\n dropdownHelpMessage,\n noResultText,\n listBoxId,\n listBoxRef: mergedListBoxRef,\n handleAdd: functions.handleAdd,\n handleHoverOption: functions.handleHoverOption,\n handleSelect: functions.handleSelect,\n listBoxRect,\n triggerWidth,\n dropdownWidth,\n },\n activeOption,\n cleanupAddFrame: functions.cleanupAddFrame,\n handleKeyDownListBox: functions.handleKeyDownListBox,\n listBoxId,\n }\n}\n\ntype ListBoxProps<T> = {\n activeOptionId: string | undefined\n options: Array<ComboboxOption<T>>\n isExpanded: boolean\n isLoading?: boolean\n noResultText?: ReactNode\n dropdownHelpMessage?: ReactNode\n listBoxId: string\n listBoxRef: RefCallback<HTMLDivElement>\n handleAdd: ((option: ComboboxOption<T>) => void) | undefined\n handleHoverOption: (option: ComboboxOption<T>) => void\n handleSelect: (option: ComboboxOption<T>) => void\n listBoxRect: { top: number; left: number; height?: number }\n triggerWidth: number\n dropdownWidth?: string | number\n callbackRef?: (node: HTMLElement | null) => void\n}\n\nexport const ListBox = memo(\n <T,>({\n activeOptionId,\n options,\n isExpanded,\n isLoading,\n noResultText,\n dropdownHelpMessage,\n listBoxId,\n listBoxRef,\n handleAdd,\n handleHoverOption,\n handleSelect,\n listBoxRect,\n triggerWidth,\n dropdownWidth,\n callbackRef,\n }: ListBoxProps<T>) => {\n const theme = useTheme()\n\n const minLength = useMemo(\n () =>\n (activeOptionId === undefined ? 0 : options.findIndex((o) => o.id === activeOptionId)) + 1,\n // eslint-disable-next-line smarthr/best-practice-for-unstable-dependencies\n [activeOptionId, options],\n )\n const [prevMinLength, setPrevMinLength] = useState(minLength)\n const [currentItemLength, setCurrentItemLength] = useState(() =>\n Math.max(OPTION_INCREMENT_AMOUNT, minLength),\n )\n\n if (minLength !== prevMinLength) {\n setPrevMinLength(minLength)\n setCurrentItemLength((current) => Math.max(current, minLength))\n }\n\n // eslint-disable-next-line smarthr/best-practice-for-unstable-dependencies\n const items = useMemo(() => options.slice(0, currentItemLength), [currentItemLength, options])\n\n const styles = useMemo(() => {\n const { top, left, height } = listBoxRect\n const dropdownListWidth = dropdownWidth || triggerWidth\n\n return {\n wrapper: {\n top: `${top}px`,\n left: `${left}px`,\n width: `${triggerWidth}px`,\n },\n dropdownList: {\n width:\n typeof dropdownListWidth === 'string' ? dropdownListWidth : `${dropdownListWidth}px`,\n /* HINT: left に依存させると、算出した幅がさらに maxWidth を縮めて再計算の度に幅が縮んでいくため、\n ビューポート幅のみから算出する */\n maxWidth: `calc(100vw - ${theme.spacingByChar(0.5)})`,\n height: height ? `${height}px` : undefined,\n },\n }\n }, [listBoxRect, triggerWidth, dropdownWidth, theme])\n\n const latest = useLatest({ handleAdd, handleHoverOption, handleSelect, options, minLength })\n\n const functions = useMemo(() => {\n const resolveOption = (e: MouseEvent) => {\n const el = findDelegateTarget<HTMLButtonElement>(e, 'button[role=\"option\"]')\n if (!el || el.disabled) return null\n return latest.options.find((o) => o.id === el.id) ?? null\n }\n\n return {\n intersectCallbackRef: (node: HTMLElement | null) => {\n if (node === null) {\n return\n }\n\n const observer = new IntersectionObserver(([entry]) => {\n if (entry.isIntersecting) {\n setCurrentItemLength((current) =>\n Math.max(current + OPTION_INCREMENT_AMOUNT, latest.minLength),\n )\n }\n })\n\n observer.observe(node)\n\n return () => observer.disconnect()\n },\n handleDelegateClick: (e: MouseEvent) => {\n const option = resolveOption(e)\n if (option) {\n if (option.isNew) {\n latest.handleAdd?.(option)\n } else {\n latest.handleSelect(option)\n }\n }\n },\n handleDelegateMouseOver: (e: MouseEvent) => {\n const option = resolveOption(e)\n if (option) {\n latest.handleHoverOption(option)\n }\n },\n }\n }, [latest])\n\n return (\n <Portal ref={callbackRef} className={CLASS_NAMES.wrapper} style={styles.wrapper}>\n <Scroller\n ref={listBoxRef}\n role=\"listbox\"\n id={listBoxId}\n className={CLASS_NAMES.dropdownList}\n style={styles.dropdownList}\n aria-hidden={!isExpanded}\n onMouseOver={functions.handleDelegateMouseOver}\n onClick={functions.handleDelegateClick}\n >\n {dropdownHelpMessage && (\n <Text\n as=\"p\"\n className={CLASS_NAMES.helpMessage}\n icon={<FaCircleInfoIcon color=\"TEXT_GREY\" />}\n >\n {dropdownHelpMessage}\n </Text>\n )}\n {isExpanded ? (\n isLoading ? (\n <div className={CLASS_NAMES.loaderWrapper}>\n <Loader />\n </div>\n ) : options.length === 0 ? (\n <LiveRegion className={CLASS_NAMES.noItems}>\n {noResultText ?? (\n <Localizer\n id=\"smarthr-ui/Combobox/noResultsText\"\n defaultText=\"一致する選択肢がありません。\"\n />\n )}\n </LiveRegion>\n ) : (\n items.map(({ item: { label, disabled }, id, ...optionRest }) => (\n <ItemButton\n {...optionRest}\n key={id}\n id={id}\n disabled={disabled}\n active={id === activeOptionId}\n label={label}\n />\n ))\n )\n ) : null}\n {currentItemLength < options.length && (\n <Intersection callbackRef={functions.intersectCallbackRef} />\n )}\n </Scroller>\n </Portal>\n )\n },\n) as <T>(props: ListBoxProps<T>) => ReactNode\n\nconst Intersection = memo<{\n callbackRef: (node: HTMLElement | null) => (() => void) | undefined\n}>(({ callbackRef }) => <div ref={callbackRef} />)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDA;AACA;AAEA;AAEA;AACE;AACE;AACA;;;AAGE;AAC0D;;;AAG3D;AACD;AAEA;AACA;AAED;AACF;AAED;AACE;;;;;;;;AASF;AAEO;AAWL;;AAGA;AACE;AACA;AACD;;;;;AAOD;;;AAGE;AACE;AACE;;AAGF;AACF;;AAGF;AAEA;;AAGA;AAEA;;AAGE;AACE;;;AAIA;;;;AAMA;AACE;;AACK;;;;;AAOL;AACE;;;;;;AAKN;;AAGE;;;;;;;;;AAUE;;;;;AAUA;;AAEE;;AACK;;AAEL;;AACK;;AAEL;;;;;AAIA;;;;;;AAOF;;;;AAIA;;AAGA;AAEA;;AAEE;;AACK;;AAEL;;AAGF;;;;AAIC;AACD;;AAEF;;;;;;;;AASI;;;;;;;AAKK;AACL;;;;AAMA;;;AAEO;;;;;;;;;AAQX;AACE;;;AAGI;;AAEA;;AAEJ;AACF;AACE;;AAEF;;;;;AAKJ;AAEA;;;;;;;;;AAaI;AACA;;;;;;;AAOF;;;;;AAQE;;;;;AAOF;AAEA;;;AAGA;;;;;AAMA;;;;;;;;AAQE;;;;;;;AAOD;;;;;;AAML;AAoBO;AAkBH;AAEA;;AAIE;;;AAOF;;AAEE;;;;AAMF;;AAEE;;AAGE;;;;AAIC;AACD;AACE;AAEA;AACkB;;;AAGnB;;;AAIL;AAEA;AACE;;AAEE;AAAwB;;AAE1B;;AAGE;AACE;;;;AAKE;AACE;;AAIJ;AAEA;AAEA;;AAEF;AACE;;AAEE;AACE;;;AAEA;;;;AAIN;AACE;;AAEE;;;;AAIR;;AAwDF;AAGF;;;"}
|
|
1
|
+
{"version":3,"file":"useListbox.cjs","sources":["../../../../src/components/Combobox/client/useListbox.tsx"],"sourcesContent":["'use client'\n\nimport {\n type KeyboardEvent,\n type MouseEvent,\n type ReactNode,\n type RefCallback,\n type RefObject,\n memo,\n useId,\n useLayoutEffect,\n useMemo,\n useState,\n} from 'react'\nimport { tv } from 'tailwind-variants'\n\nimport { useAnimationFrame } from '../../../hooks/client/useAnimationFrame'\nimport { useLayoutEffectRef } from '../../../hooks/client/useLayoutEffectRef'\nimport { useMergeRefs } from '../../../hooks/client/useMergeRefs'\nimport { useSafeAreaInsets } from '../../../hooks/client/useSafeAreaInsets'\nimport { useTheme } from '../../../hooks/client/useTheme'\nimport { useLatest } from '../../../hooks/useLatest'\nimport { Localizer } from '../../../intl'\nimport { findDelegateTarget } from '../../../libs/delegate'\nimport { FaCircleInfoIcon } from '../../Icon'\nimport { LiveRegion } from '../../LiveRegion'\nimport { Loader } from '../../Loader'\nimport { Portal } from '../../Portal'\nimport { Scroller } from '../../Scroller'\nimport { Text } from '../../Text'\n\nimport { ItemButton } from './ItemButton'\n\nimport type { ComboboxItem, ComboboxOption } from './types'\n\ntype Props<T> = {\n options: Array<ComboboxOption<T>>\n dropdownHelpMessage?: ReactNode\n dropdownWidth?: string | number\n onAdd?: (label: string) => void\n onSelect: (item: ComboboxItem<T>) => void\n isExpanded: boolean\n isLoading?: boolean\n triggerRef: RefObject<HTMLElement | null>\n /** 検索結果が0件の時に表示するコンテンツ */\n noResultText?: ReactNode\n}\n\ntype Rect = {\n top: number\n left: number\n height?: number\n}\n\nconst KEY_DOWN_REGEX = /^(Arrow)?Down$/\nconst KEY_UP_REGEX = /^(Arrow)?Up/\n\nconst OPTION_INCREMENT_AMOUNT = 100\n\nconst classNameGenerator = tv({\n slots: {\n wrapper: 'shr-absolute',\n dropdownList: [\n 'smarthr-ui-Combobox-dropdownList',\n 'shr-absolute shr-z-overlap shr-box-border shr-min-w-full shr-rounded-m shr-bg-white shr-py-0.5 shr-shadow-layer-3 forced-colors:shr-outline forced-colors:shr-outline-1',\n /* 縦スクロールに気づきやすくするために8個目のアイテムが半分見切れるように max-height を算出\n = (アイテムのフォントサイズ + アイテムの上下padding) * 7.5 + コンテナの上padding */\n 'shr-max-h-[calc((theme(fontSize.base)_+_theme(spacing[0.5])_*_2)_*_7.5_+_theme(spacing[0.5]))]',\n 'aria-hidden:shr-hidden',\n ],\n helpMessage:\n 'shr-whitespace-[initial] shr-border-b-shorthand shr-mx-0.5 shr-mb-0.5 shr-mt-0 shr-px-0.5 shr-pb-0.5 shr-pt-0 shr-text-sm',\n loaderWrapper: 'shr-flex shr-items-center shr-justify-center shr-p-1',\n noItems:\n 'smarthr-ui-Combobox-noItems shr-my-0 shr-block shr-bg-white shr-px-1 shr-py-0.5 shr-text-base',\n },\n})\n\nconst CLASS_NAMES = (() => {\n const { wrapper, dropdownList, helpMessage, loaderWrapper, noItems } = classNameGenerator()\n\n return {\n wrapper: wrapper(),\n dropdownList: dropdownList(),\n helpMessage: helpMessage(),\n loaderWrapper: loaderWrapper(),\n noItems: noItems(),\n }\n})()\n\nexport const useListbox = <T,>({\n options,\n dropdownHelpMessage,\n dropdownWidth,\n onAdd,\n onSelect,\n isExpanded,\n isLoading,\n triggerRef,\n noResultText,\n}: Props<T>) => {\n const listBoxId = useId()\n\n const [navigationType, setNavigationType] = useState<'pointer' | 'key'>('pointer')\n const [listBoxRect, setListBoxRect] = useState<Rect>({\n top: 0,\n left: 0,\n })\n // HINT: calculateRectで同時に計算するとwidthの幅が変更されるタイミングの問題でlistBoxHeightが変化する場合がある\n const [triggerWidth, setTriggerWidth] = useState(0)\n\n const [activeOption, setActiveOption] = useState<ComboboxOption<T> | null>(null)\n const [prevOptions, setPrevOptions] = useState(options)\n\n if (options !== prevOptions) {\n setPrevOptions(options)\n // props の変更によって activeOption の状態が変わりうるので、実態を反映する\n setActiveOption((current) => {\n if (current === null) {\n return null\n }\n\n return options.find((option) => current.id === option.id) ?? null\n })\n }\n\n const theme = useTheme()\n\n const addFrame = useAnimationFrame()\n\n const getSafeAreaInsets = useSafeAreaInsets()\n const latest = useLatest({\n onAdd,\n onSelect,\n activeOption,\n options,\n triggerRef,\n theme,\n getSafeAreaInsets,\n addFrame,\n })\n const hasOnAdd = Boolean(onAdd)\n\n const functions = useMemo(() => {\n let listBox: HTMLElement | null = null\n\n const moveActiveOptionIndex = (currentActive: ComboboxOption<T> | null, delta: -1 | 1) => {\n if (latest.options.every((option) => option.item.disabled)) {\n return\n }\n\n const currentActiveIndex =\n currentActive === null\n ? -1\n : latest.options.findIndex((option) => option.id === currentActive.id)\n let nextIndex = 0\n\n if (currentActiveIndex !== -1) {\n nextIndex = (currentActiveIndex + delta + latest.options.length) % latest.options.length\n } else if (delta !== 1) {\n nextIndex = latest.options.length - 1\n }\n\n const nextActive = latest.options[nextIndex]\n\n if (nextActive) {\n if (nextActive.item.disabled) {\n moveActiveOptionIndex(nextActive, delta)\n } else {\n setActiveOption(nextActive)\n }\n }\n }\n\n return {\n baseCallbackRef: (node: HTMLElement | null) => {\n listBox = node\n },\n calculateRect: () => {\n if (!listBox || !latest.triggerRef.current) {\n return\n }\n\n const rect = latest.triggerRef.current.getBoundingClientRect()\n // HINT: safe areaに重ならない領域を、リストボックスを表示できる範囲とする\n const safeAreaInsets = latest.getSafeAreaInsets()\n const bottomSpace = window.innerHeight - safeAreaInsets.bottom - rect.bottom\n const topSpace = rect.top - safeAreaInsets.top\n const listBoxHeight = Math.min(\n listBox.scrollHeight,\n parseInt(getComputedStyle(listBox).maxHeight, 10),\n )\n const offset = 2\n\n let top = 0\n let height: number | undefined = undefined\n\n if (bottomSpace >= listBoxHeight) {\n // 下側に十分なスペースがある場合は下側に通常表示\n top = rect.top + rect.height - offset + window.pageYOffset\n } else if (topSpace >= listBoxHeight) {\n // 上側に十分なスペースがある場合は上側に通常表示\n top = rect.top - listBoxHeight + offset + window.pageYOffset\n } else if (topSpace > bottomSpace) {\n // 上下に十分なスペースがなく、上側の方がスペースが大きい場合は上側に縮めて表示\n top = rect.top - topSpace + offset + window.pageYOffset\n height = topSpace\n } else {\n // 下側に縮めて表示\n top = rect.top + rect.height - offset + window.pageYOffset\n height = bottomSpace\n }\n\n // HINT: dropdownWidth は 'auto' や '%' などの CSS 値を取りうるため、算出済みの幅を実測して判定する\n const listBoxWidth = listBox.getBoundingClientRect().width\n // ドロップダウンの幅は maxWidth でビューポート右端から余白分を残すよう制限しているため、位置の判定にも同じ余白を使う\n const viewportMargin = parseInt(latest.theme.spacingByChar(0.5), 10)\n // 入力欄の左端を起点に右方向へ表示する場合に使える幅\n const rightSpace = window.innerWidth - safeAreaInsets.right - rect.left - viewportMargin\n // 入力欄の右端を起点に左方向へ表示する場合に使える幅\n const leftSpace = rect.right - safeAreaInsets.left\n\n // ビューポートの左端を基準に計算\n let left = window.pageXOffset\n\n if (listBoxWidth <= rightSpace) {\n // 右側に十分なスペースがある場合は入力欄の左端に揃えて通常表示\n left += rect.left\n } else if (listBoxWidth <= leftSpace) {\n // 左側に収まる場合は入力欄の右端に揃えて表示\n left += rect.right - listBoxWidth\n } else {\n // どちらにも収まらない場合はsafe areaの左端に揃えて表示\n left += safeAreaInsets.left\n }\n\n setListBoxRect({\n top,\n left,\n height,\n })\n setTriggerWidth(rect.width)\n },\n handleKeyDownListBox: (e: KeyboardEvent<HTMLElement>) => {\n setNavigationType('key')\n\n if (KEY_DOWN_REGEX.test(e.key)) {\n // HINT: MultiComboboxの削除ボタンにフォーカスがある状態など、input以外からこのハンドラへ\n // 到達する経路ではpreventDefaultされないため、ブラウザ側のデフォルトキー操作(iOS Safariでの\n // ページスクロール等)が発生してしまう。ここで明示的に止める\n e.preventDefault()\n e.stopPropagation()\n moveActiveOptionIndex(latest.activeOption, 1)\n } else if (KEY_UP_REGEX.test(e.key)) {\n e.preventDefault()\n e.stopPropagation()\n moveActiveOptionIndex(latest.activeOption, -1)\n } else if (e.key === 'Enter') {\n if (latest.activeOption === null) {\n return\n }\n\n e.stopPropagation()\n\n if (!latest.activeOption.isNew) {\n latest.onSelect(latest.activeOption.item)\n } else if (latest.onAdd) {\n latest.onAdd(latest.activeOption.item.value)\n }\n } else {\n setActiveOption(null)\n }\n },\n cleanupAddFrame: () => latest.addFrame.cancel(),\n handleAdd: hasOnAdd\n ? (option: ComboboxOption<T>) => {\n // HINT: Dropdown系コンポーネント内でComboboxを使うと、選択肢がportalで表現されている関係上Dropdownが閉じてしまう\n // 処理を遅延させることで正常に閉じる/閉じないの判定を行えるようにする\n latest.addFrame.request(() => {\n latest.onAdd!(option.item.value)\n })\n }\n : undefined,\n handleSelect: (option: ComboboxOption<T>) => {\n latest.onSelect(option.item)\n },\n handleHoverOption: (option: ComboboxOption<T>) => {\n setNavigationType('pointer')\n setActiveOption(option)\n },\n }\n }, [hasOnAdd, latest])\n\n const listBoxLayoutEffectRef = useLayoutEffectRef(\n (node: HTMLElement | null) => {\n // actionOption の要素が表示される位置までリストボックス内をスクロールさせる\n if (!node || activeOption === null || navigationType !== 'key') {\n return\n }\n\n const activeElement = node.querySelector<HTMLElement>('button[data-active=\"true\"]')\n\n if (!activeElement) {\n return\n }\n\n const activeRect = activeElement.getBoundingClientRect()\n const containerRect = node.getBoundingClientRect()\n\n if (activeRect.top < containerRect.top) {\n node.scrollTop -= containerRect.top - activeRect.top\n } else if (activeRect.bottom > containerRect.bottom) {\n node.scrollTop += activeRect.bottom - containerRect.bottom\n }\n },\n [activeOption, navigationType],\n )\n const mergedListBoxRef = useMergeRefs(listBoxLayoutEffectRef, functions.baseCallbackRef)\n\n useLayoutEffect(() => {\n // 閉じたときに activeOption を初期化\n if (!isExpanded) {\n return setActiveOption(null)\n }\n\n functions.calculateRect()\n\n const scrollOption = { capture: true, passive: true }\n window.addEventListener('scroll', functions.calculateRect, scrollOption)\n window.addEventListener('resize', functions.calculateRect, { passive: true })\n\n return () => {\n window.removeEventListener('scroll', functions.calculateRect, scrollOption)\n window.removeEventListener('resize', functions.calculateRect)\n }\n // HINT: optionsが変わる場合メニューのサイズが変わる可能性がある\n // eslint-disable-next-line smarthr/best-practice-for-unstable-dependencies\n }, [isExpanded, options, functions])\n\n return {\n listBoxProps: {\n activeOptionId: activeOption?.id,\n options,\n isExpanded,\n isLoading,\n dropdownHelpMessage,\n noResultText,\n listBoxId,\n listBoxRef: mergedListBoxRef,\n handleAdd: functions.handleAdd,\n handleHoverOption: functions.handleHoverOption,\n handleSelect: functions.handleSelect,\n listBoxRect,\n triggerWidth,\n dropdownWidth,\n },\n activeOption,\n cleanupAddFrame: functions.cleanupAddFrame,\n handleKeyDownListBox: functions.handleKeyDownListBox,\n listBoxId,\n }\n}\n\ntype ListBoxProps<T> = {\n activeOptionId: string | undefined\n options: Array<ComboboxOption<T>>\n isExpanded: boolean\n isLoading?: boolean\n noResultText?: ReactNode\n dropdownHelpMessage?: ReactNode\n listBoxId: string\n listBoxRef: RefCallback<HTMLDivElement>\n handleAdd: ((option: ComboboxOption<T>) => void) | undefined\n handleHoverOption: (option: ComboboxOption<T>) => void\n handleSelect: (option: ComboboxOption<T>) => void\n listBoxRect: { top: number; left: number; height?: number }\n triggerWidth: number\n dropdownWidth?: string | number\n callbackRef?: (node: HTMLElement | null) => void\n}\n\nexport const ListBox = memo(\n <T,>({\n activeOptionId,\n options,\n isExpanded,\n isLoading,\n noResultText,\n dropdownHelpMessage,\n listBoxId,\n listBoxRef,\n handleAdd,\n handleHoverOption,\n handleSelect,\n listBoxRect,\n triggerWidth,\n dropdownWidth,\n callbackRef,\n }: ListBoxProps<T>) => {\n const theme = useTheme()\n\n const minLength = useMemo(\n () =>\n (activeOptionId === undefined ? 0 : options.findIndex((o) => o.id === activeOptionId)) + 1,\n // eslint-disable-next-line smarthr/best-practice-for-unstable-dependencies\n [activeOptionId, options],\n )\n const [prevMinLength, setPrevMinLength] = useState(minLength)\n const [currentItemLength, setCurrentItemLength] = useState(() =>\n Math.max(OPTION_INCREMENT_AMOUNT, minLength),\n )\n\n if (minLength !== prevMinLength) {\n setPrevMinLength(minLength)\n setCurrentItemLength((current) => Math.max(current, minLength))\n }\n\n // eslint-disable-next-line smarthr/best-practice-for-unstable-dependencies\n const items = useMemo(() => options.slice(0, currentItemLength), [currentItemLength, options])\n\n const styles = useMemo(() => {\n const { top, left, height } = listBoxRect\n const dropdownListWidth = dropdownWidth || triggerWidth\n\n return {\n wrapper: {\n top: `${top}px`,\n left: `${left}px`,\n width: `${triggerWidth}px`,\n },\n dropdownList: {\n width:\n typeof dropdownListWidth === 'string' ? dropdownListWidth : `${dropdownListWidth}px`,\n /* HINT: left に依存させると、算出した幅がさらに maxWidth を縮めて再計算の度に幅が縮んでいくため、\n ビューポート幅のみから算出する */\n maxWidth: `calc(100vw - ${theme.spacingByChar(0.5)} - env(safe-area-inset-left) - env(safe-area-inset-right))`,\n height: height ? `${height}px` : undefined,\n },\n }\n }, [listBoxRect, triggerWidth, dropdownWidth, theme])\n\n const latest = useLatest({ handleAdd, handleHoverOption, handleSelect, options, minLength })\n\n const functions = useMemo(() => {\n const resolveOption = (e: MouseEvent) => {\n const el = findDelegateTarget<HTMLButtonElement>(e, 'button[role=\"option\"]')\n if (!el || el.disabled) return null\n return latest.options.find((o) => o.id === el.id) ?? null\n }\n\n return {\n intersectCallbackRef: (node: HTMLElement | null) => {\n if (node === null) {\n return\n }\n\n const observer = new IntersectionObserver(([entry]) => {\n if (entry.isIntersecting) {\n setCurrentItemLength((current) =>\n Math.max(current + OPTION_INCREMENT_AMOUNT, latest.minLength),\n )\n }\n })\n\n observer.observe(node)\n\n return () => observer.disconnect()\n },\n handleDelegateClick: (e: MouseEvent) => {\n const option = resolveOption(e)\n if (option) {\n if (option.isNew) {\n latest.handleAdd?.(option)\n } else {\n latest.handleSelect(option)\n }\n }\n },\n handleDelegateMouseOver: (e: MouseEvent) => {\n const option = resolveOption(e)\n if (option) {\n latest.handleHoverOption(option)\n }\n },\n }\n }, [latest])\n\n return (\n <Portal ref={callbackRef} className={CLASS_NAMES.wrapper} style={styles.wrapper}>\n <Scroller\n ref={listBoxRef}\n role=\"listbox\"\n id={listBoxId}\n className={CLASS_NAMES.dropdownList}\n style={styles.dropdownList}\n aria-hidden={!isExpanded}\n onMouseOver={functions.handleDelegateMouseOver}\n onClick={functions.handleDelegateClick}\n >\n {dropdownHelpMessage && (\n <Text\n as=\"p\"\n className={CLASS_NAMES.helpMessage}\n icon={<FaCircleInfoIcon color=\"TEXT_GREY\" />}\n >\n {dropdownHelpMessage}\n </Text>\n )}\n {isExpanded ? (\n isLoading ? (\n <div className={CLASS_NAMES.loaderWrapper}>\n <Loader />\n </div>\n ) : options.length === 0 ? (\n <LiveRegion className={CLASS_NAMES.noItems}>\n {noResultText ?? (\n <Localizer\n id=\"smarthr-ui/Combobox/noResultsText\"\n defaultText=\"一致する選択肢がありません。\"\n />\n )}\n </LiveRegion>\n ) : (\n items.map(({ item: { label, disabled }, id, ...optionRest }) => (\n <ItemButton\n {...optionRest}\n key={id}\n id={id}\n disabled={disabled}\n active={id === activeOptionId}\n label={label}\n />\n ))\n )\n ) : null}\n {currentItemLength < options.length && (\n <Intersection callbackRef={functions.intersectCallbackRef} />\n )}\n </Scroller>\n </Portal>\n )\n },\n) as <T>(props: ListBoxProps<T>) => ReactNode\n\nconst Intersection = memo<{\n callbackRef: (node: HTMLElement | null) => (() => void) | undefined\n}>(({ callbackRef }) => <div ref={callbackRef} />)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA;AACA;AAEA;AAEA;AACE;AACE;AACA;;;AAGE;AAC0D;;;AAG3D;AACD;AAEA;AACA;AAED;AACF;AAED;AACE;;;;;;;;AASF;AAEO;AAWL;;AAGA;AACE;AACA;AACD;;;;;AAOD;;;AAGE;AACE;AACE;;AAGF;AACF;;AAGF;AAEA;AAEA;;;;;;;;;;AAUC;AACD;AAEA;;AAGE;AACE;;;AAIA;;;;AAMA;AACE;;AACK;;;;;AAOL;AACE;;;;;;AAKN;;AAGE;;;;;;;;;AAUE;AACA;;;;;;AAWA;;AAEE;;AACK;;AAEL;;AACK;;AAEL;;;;;AAIA;;;;;;AAOF;;AAEA;;;;AAKA;AAEA;;AAEE;;AACK;;AAEL;;;;AAGA;;AAGF;;;;AAIC;AACD;;AAEF;;;;;;;;AASI;;;;;;;AAKK;AACL;;;;AAMA;;;AAEO;;;;;;;;;AAQX;AACE;;;AAGI;;AAEA;;AAEJ;AACF;AACE;;AAEF;;;;;AAKJ;AAEA;;;;;;;;;AAaI;AACA;;;;;;;AAOF;;;;;AAQE;;;;;AAOF;AAEA;;;AAGA;;;;;AAMA;;;;;;;;AAQE;;;;;;;AAOD;;;;;;AAML;AAoBO;AAkBH;AAEA;;AAIE;;;AAOF;;AAEE;;;;AAMF;;AAEE;;AAGE;;;;AAIC;AACD;AACE;AAEA;AACkB;;;AAGnB;;;AAIL;AAEA;AACE;;AAEE;AAAwB;;AAE1B;;AAGE;AACE;;;;AAKE;AACE;;AAIJ;AAEA;AAEA;;AAEF;AACE;;AAEE;AACE;;;AAEA;;;;AAIN;AACE;;AAEE;;;;AAIR;;AAwDF;AAGF;;;"}
|
|
@@ -5,6 +5,7 @@ import { tv as ce } from './../../../vendor/.pnpm/tailwind-variants@0.3.1_tailwi
|
|
|
5
5
|
import { useAnimationFrame } from '../../../hooks/client/useAnimationFrame/useAnimationFrame.js';
|
|
6
6
|
import { useLayoutEffectRef } from '../../../hooks/client/useLayoutEffectRef.js';
|
|
7
7
|
import { useMergeRefs } from '../../../hooks/client/useMergeRefs/useMergeRefs.js';
|
|
8
|
+
import { useSafeAreaInsets } from '../../../hooks/client/useSafeAreaInsets/useSafeAreaInsets.js';
|
|
8
9
|
import { useTheme } from '../../../hooks/client/useTheme.js';
|
|
9
10
|
import { useLatest } from '../../../hooks/useLatest.js';
|
|
10
11
|
import '../../../_virtual/dayjs.min.js';
|
|
@@ -78,8 +79,18 @@ const useListbox = ({ options, dropdownHelpMessage, dropdownWidth, onAdd, onSele
|
|
|
78
79
|
}
|
|
79
80
|
const theme = useTheme();
|
|
80
81
|
const addFrame = useAnimationFrame();
|
|
81
|
-
const
|
|
82
|
-
const
|
|
82
|
+
const getSafeAreaInsets = useSafeAreaInsets();
|
|
83
|
+
const latest = useLatest({
|
|
84
|
+
onAdd,
|
|
85
|
+
onSelect,
|
|
86
|
+
activeOption,
|
|
87
|
+
options,
|
|
88
|
+
triggerRef,
|
|
89
|
+
theme,
|
|
90
|
+
getSafeAreaInsets,
|
|
91
|
+
addFrame,
|
|
92
|
+
});
|
|
93
|
+
const hasOnAdd = Boolean(onAdd);
|
|
83
94
|
const functions = useMemo(() => {
|
|
84
95
|
let listBox = null;
|
|
85
96
|
const moveActiveOptionIndex = (currentActive, delta) => {
|
|
@@ -115,8 +126,10 @@ const useListbox = ({ options, dropdownHelpMessage, dropdownWidth, onAdd, onSele
|
|
|
115
126
|
return;
|
|
116
127
|
}
|
|
117
128
|
const rect = latest.triggerRef.current.getBoundingClientRect();
|
|
118
|
-
|
|
119
|
-
const
|
|
129
|
+
// HINT: safe areaに重ならない領域を、リストボックスを表示できる範囲とする
|
|
130
|
+
const safeAreaInsets = latest.getSafeAreaInsets();
|
|
131
|
+
const bottomSpace = window.innerHeight - safeAreaInsets.bottom - rect.bottom;
|
|
132
|
+
const topSpace = rect.top - safeAreaInsets.top;
|
|
120
133
|
const listBoxHeight = Math.min(listBox.scrollHeight, parseInt(getComputedStyle(listBox).maxHeight, 10));
|
|
121
134
|
const offset = 2;
|
|
122
135
|
let top = 0;
|
|
@@ -144,9 +157,9 @@ const useListbox = ({ options, dropdownHelpMessage, dropdownWidth, onAdd, onSele
|
|
|
144
157
|
// ドロップダウンの幅は maxWidth でビューポート右端から余白分を残すよう制限しているため、位置の判定にも同じ余白を使う
|
|
145
158
|
const viewportMargin = parseInt(latest.theme.spacingByChar(0.5), 10);
|
|
146
159
|
// 入力欄の左端を起点に右方向へ表示する場合に使える幅
|
|
147
|
-
const rightSpace = window.innerWidth - rect.left - viewportMargin;
|
|
160
|
+
const rightSpace = window.innerWidth - safeAreaInsets.right - rect.left - viewportMargin;
|
|
148
161
|
// 入力欄の右端を起点に左方向へ表示する場合に使える幅
|
|
149
|
-
const leftSpace = rect.right;
|
|
162
|
+
const leftSpace = rect.right - safeAreaInsets.left;
|
|
150
163
|
// ビューポートの左端を基準に計算
|
|
151
164
|
let left = window.pageXOffset;
|
|
152
165
|
if (listBoxWidth <= rightSpace) {
|
|
@@ -157,6 +170,10 @@ const useListbox = ({ options, dropdownHelpMessage, dropdownWidth, onAdd, onSele
|
|
|
157
170
|
// 左側に収まる場合は入力欄の右端に揃えて表示
|
|
158
171
|
left += rect.right - listBoxWidth;
|
|
159
172
|
}
|
|
173
|
+
else {
|
|
174
|
+
// どちらにも収まらない場合はsafe areaの左端に揃えて表示
|
|
175
|
+
left += safeAreaInsets.left;
|
|
176
|
+
}
|
|
160
177
|
setListBoxRect({
|
|
161
178
|
top,
|
|
162
179
|
left,
|
|
@@ -298,7 +315,7 @@ const ListBox = memo(({ activeOptionId, options, isExpanded, isLoading, noResult
|
|
|
298
315
|
width: typeof dropdownListWidth === 'string' ? dropdownListWidth : `${dropdownListWidth}px`,
|
|
299
316
|
/* HINT: left に依存させると、算出した幅がさらに maxWidth を縮めて再計算の度に幅が縮んでいくため、
|
|
300
317
|
ビューポート幅のみから算出する */
|
|
301
|
-
maxWidth: `calc(100vw - ${theme.spacingByChar(0.5)})`,
|
|
318
|
+
maxWidth: `calc(100vw - ${theme.spacingByChar(0.5)} - env(safe-area-inset-left) - env(safe-area-inset-right))`,
|
|
302
319
|
height: height ? `${height}px` : undefined,
|
|
303
320
|
},
|
|
304
321
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useListbox.js","sources":["../../../../src/components/Combobox/client/useListbox.tsx"],"sourcesContent":["'use client'\n\nimport {\n type KeyboardEvent,\n type MouseEvent,\n type ReactNode,\n type RefCallback,\n type RefObject,\n memo,\n useId,\n useLayoutEffect,\n useMemo,\n useState,\n} from 'react'\nimport { tv } from 'tailwind-variants'\n\nimport { useAnimationFrame } from '../../../hooks/client/useAnimationFrame'\nimport { useLayoutEffectRef } from '../../../hooks/client/useLayoutEffectRef'\nimport { useMergeRefs } from '../../../hooks/client/useMergeRefs'\nimport { useTheme } from '../../../hooks/client/useTheme'\nimport { useLatest } from '../../../hooks/useLatest'\nimport { Localizer } from '../../../intl'\nimport { findDelegateTarget } from '../../../libs/delegate'\nimport { FaCircleInfoIcon } from '../../Icon'\nimport { LiveRegion } from '../../LiveRegion'\nimport { Loader } from '../../Loader'\nimport { Portal } from '../../Portal'\nimport { Scroller } from '../../Scroller'\nimport { Text } from '../../Text'\n\nimport { ItemButton } from './ItemButton'\n\nimport type { ComboboxItem, ComboboxOption } from './types'\n\ntype Props<T> = {\n options: Array<ComboboxOption<T>>\n dropdownHelpMessage?: ReactNode\n dropdownWidth?: string | number\n onAdd?: (label: string) => void\n onSelect: (item: ComboboxItem<T>) => void\n isExpanded: boolean\n isLoading?: boolean\n triggerRef: RefObject<HTMLElement | null>\n /** 検索結果が0件の時に表示するコンテンツ */\n noResultText?: ReactNode\n}\n\ntype Rect = {\n top: number\n left: number\n height?: number\n}\n\nconst KEY_DOWN_REGEX = /^(Arrow)?Down$/\nconst KEY_UP_REGEX = /^(Arrow)?Up/\n\nconst OPTION_INCREMENT_AMOUNT = 100\n\nconst classNameGenerator = tv({\n slots: {\n wrapper: 'shr-absolute',\n dropdownList: [\n 'smarthr-ui-Combobox-dropdownList',\n 'shr-absolute shr-z-overlap shr-box-border shr-min-w-full shr-rounded-m shr-bg-white shr-py-0.5 shr-shadow-layer-3 forced-colors:shr-outline forced-colors:shr-outline-1',\n /* 縦スクロールに気づきやすくするために8個目のアイテムが半分見切れるように max-height を算出\n = (アイテムのフォントサイズ + アイテムの上下padding) * 7.5 + コンテナの上padding */\n 'shr-max-h-[calc((theme(fontSize.base)_+_theme(spacing[0.5])_*_2)_*_7.5_+_theme(spacing[0.5]))]',\n 'aria-hidden:shr-hidden',\n ],\n helpMessage:\n 'shr-whitespace-[initial] shr-border-b-shorthand shr-mx-0.5 shr-mb-0.5 shr-mt-0 shr-px-0.5 shr-pb-0.5 shr-pt-0 shr-text-sm',\n loaderWrapper: 'shr-flex shr-items-center shr-justify-center shr-p-1',\n noItems:\n 'smarthr-ui-Combobox-noItems shr-my-0 shr-block shr-bg-white shr-px-1 shr-py-0.5 shr-text-base',\n },\n})\n\nconst CLASS_NAMES = (() => {\n const { wrapper, dropdownList, helpMessage, loaderWrapper, noItems } = classNameGenerator()\n\n return {\n wrapper: wrapper(),\n dropdownList: dropdownList(),\n helpMessage: helpMessage(),\n loaderWrapper: loaderWrapper(),\n noItems: noItems(),\n }\n})()\n\nexport const useListbox = <T,>({\n options,\n dropdownHelpMessage,\n dropdownWidth,\n onAdd,\n onSelect,\n isExpanded,\n isLoading,\n triggerRef,\n noResultText,\n}: Props<T>) => {\n const listBoxId = useId()\n\n const [navigationType, setNavigationType] = useState<'pointer' | 'key'>('pointer')\n const [listBoxRect, setListBoxRect] = useState<Rect>({\n top: 0,\n left: 0,\n })\n // HINT: calculateRectで同時に計算するとwidthの幅が変更されるタイミングの問題でlistBoxHeightが変化する場合がある\n const [triggerWidth, setTriggerWidth] = useState(0)\n\n const [activeOption, setActiveOption] = useState<ComboboxOption<T> | null>(null)\n const [prevOptions, setPrevOptions] = useState(options)\n\n if (options !== prevOptions) {\n setPrevOptions(options)\n // props の変更によって activeOption の状態が変わりうるので、実態を反映する\n setActiveOption((current) => {\n if (current === null) {\n return null\n }\n\n return options.find((option) => current.id === option.id) ?? null\n })\n }\n\n const theme = useTheme()\n\n const addFrame = useAnimationFrame()\n\n const latest = useLatest({ onAdd, onSelect, activeOption, options, triggerRef, theme, addFrame })\n const hasOnAdd = !!onAdd\n\n const functions = useMemo(() => {\n let listBox: HTMLElement | null = null\n\n const moveActiveOptionIndex = (currentActive: ComboboxOption<T> | null, delta: -1 | 1) => {\n if (latest.options.every((option) => option.item.disabled)) {\n return\n }\n\n const currentActiveIndex =\n currentActive === null\n ? -1\n : latest.options.findIndex((option) => option.id === currentActive.id)\n let nextIndex = 0\n\n if (currentActiveIndex !== -1) {\n nextIndex = (currentActiveIndex + delta + latest.options.length) % latest.options.length\n } else if (delta !== 1) {\n nextIndex = latest.options.length - 1\n }\n\n const nextActive = latest.options[nextIndex]\n\n if (nextActive) {\n if (nextActive.item.disabled) {\n moveActiveOptionIndex(nextActive, delta)\n } else {\n setActiveOption(nextActive)\n }\n }\n }\n\n return {\n baseCallbackRef: (node: HTMLElement | null) => {\n listBox = node\n },\n calculateRect: () => {\n if (!listBox || !latest.triggerRef.current) {\n return\n }\n\n const rect = latest.triggerRef.current.getBoundingClientRect()\n const bottomSpace = window.innerHeight - rect.bottom\n const topSpace = rect.top\n const listBoxHeight = Math.min(\n listBox.scrollHeight,\n parseInt(getComputedStyle(listBox).maxHeight, 10),\n )\n const offset = 2\n\n let top = 0\n let height: number | undefined = undefined\n\n if (bottomSpace >= listBoxHeight) {\n // 下側に十分なスペースがある場合は下側に通常表示\n top = rect.top + rect.height - offset + window.pageYOffset\n } else if (topSpace >= listBoxHeight) {\n // 上側に十分なスペースがある場合は上側に通常表示\n top = rect.top - listBoxHeight + offset + window.pageYOffset\n } else if (topSpace > bottomSpace) {\n // 上下に十分なスペースがなく、上側の方がスペースが大きい場合は上側に縮めて表示\n top = rect.top - topSpace + offset + window.pageYOffset\n height = topSpace\n } else {\n // 下側に縮めて表示\n top = rect.top + rect.height - offset + window.pageYOffset\n height = bottomSpace\n }\n\n // HINT: dropdownWidth は 'auto' や '%' などの CSS 値を取りうるため、算出済みの幅を実測して判定する\n const listBoxWidth = listBox.getBoundingClientRect().width\n // ドロップダウンの幅は maxWidth でビューポート右端から余白分を残すよう制限しているため、位置の判定にも同じ余白を使う\n const viewportMargin = parseInt(latest.theme.spacingByChar(0.5), 10)\n // 入力欄の左端を起点に右方向へ表示する場合に使える幅\n const rightSpace = window.innerWidth - rect.left - viewportMargin\n // 入力欄の右端を起点に左方向へ表示する場合に使える幅\n const leftSpace = rect.right\n\n // ビューポートの左端を基準に計算\n let left = window.pageXOffset\n\n if (listBoxWidth <= rightSpace) {\n // 右側に十分なスペースがある場合は入力欄の左端に揃えて通常表示\n left += rect.left\n } else if (listBoxWidth <= leftSpace) {\n // 左側に収まる場合は入力欄の右端に揃えて表示\n left += rect.right - listBoxWidth\n }\n\n setListBoxRect({\n top,\n left,\n height,\n })\n setTriggerWidth(rect.width)\n },\n handleKeyDownListBox: (e: KeyboardEvent<HTMLElement>) => {\n setNavigationType('key')\n\n if (KEY_DOWN_REGEX.test(e.key)) {\n // HINT: MultiComboboxの削除ボタンにフォーカスがある状態など、input以外からこのハンドラへ\n // 到達する経路ではpreventDefaultされないため、ブラウザ側のデフォルトキー操作(iOS Safariでの\n // ページスクロール等)が発生してしまう。ここで明示的に止める\n e.preventDefault()\n e.stopPropagation()\n moveActiveOptionIndex(latest.activeOption, 1)\n } else if (KEY_UP_REGEX.test(e.key)) {\n e.preventDefault()\n e.stopPropagation()\n moveActiveOptionIndex(latest.activeOption, -1)\n } else if (e.key === 'Enter') {\n if (latest.activeOption === null) {\n return\n }\n\n e.stopPropagation()\n\n if (!latest.activeOption.isNew) {\n latest.onSelect(latest.activeOption.item)\n } else if (latest.onAdd) {\n latest.onAdd(latest.activeOption.item.value)\n }\n } else {\n setActiveOption(null)\n }\n },\n cleanupAddFrame: () => latest.addFrame.cancel(),\n handleAdd: hasOnAdd\n ? (option: ComboboxOption<T>) => {\n // HINT: Dropdown系コンポーネント内でComboboxを使うと、選択肢がportalで表現されている関係上Dropdownが閉じてしまう\n // 処理を遅延させることで正常に閉じる/閉じないの判定を行えるようにする\n latest.addFrame.request(() => {\n latest.onAdd!(option.item.value)\n })\n }\n : undefined,\n handleSelect: (option: ComboboxOption<T>) => {\n latest.onSelect(option.item)\n },\n handleHoverOption: (option: ComboboxOption<T>) => {\n setNavigationType('pointer')\n setActiveOption(option)\n },\n }\n }, [hasOnAdd, latest])\n\n const listBoxLayoutEffectRef = useLayoutEffectRef(\n (node: HTMLElement | null) => {\n // actionOption の要素が表示される位置までリストボックス内をスクロールさせる\n if (!node || activeOption === null || navigationType !== 'key') {\n return\n }\n\n const activeElement = node.querySelector<HTMLElement>('button[data-active=\"true\"]')\n\n if (!activeElement) {\n return\n }\n\n const activeRect = activeElement.getBoundingClientRect()\n const containerRect = node.getBoundingClientRect()\n\n if (activeRect.top < containerRect.top) {\n node.scrollTop -= containerRect.top - activeRect.top\n } else if (activeRect.bottom > containerRect.bottom) {\n node.scrollTop += activeRect.bottom - containerRect.bottom\n }\n },\n [activeOption, navigationType],\n )\n const mergedListBoxRef = useMergeRefs(listBoxLayoutEffectRef, functions.baseCallbackRef)\n\n useLayoutEffect(() => {\n // 閉じたときに activeOption を初期化\n if (!isExpanded) {\n return setActiveOption(null)\n }\n\n functions.calculateRect()\n\n const scrollOption = { capture: true, passive: true }\n window.addEventListener('scroll', functions.calculateRect, scrollOption)\n window.addEventListener('resize', functions.calculateRect, { passive: true })\n\n return () => {\n window.removeEventListener('scroll', functions.calculateRect, scrollOption)\n window.removeEventListener('resize', functions.calculateRect)\n }\n // HINT: optionsが変わる場合メニューのサイズが変わる可能性がある\n // eslint-disable-next-line smarthr/best-practice-for-unstable-dependencies\n }, [isExpanded, options, functions])\n\n return {\n listBoxProps: {\n activeOptionId: activeOption?.id,\n options,\n isExpanded,\n isLoading,\n dropdownHelpMessage,\n noResultText,\n listBoxId,\n listBoxRef: mergedListBoxRef,\n handleAdd: functions.handleAdd,\n handleHoverOption: functions.handleHoverOption,\n handleSelect: functions.handleSelect,\n listBoxRect,\n triggerWidth,\n dropdownWidth,\n },\n activeOption,\n cleanupAddFrame: functions.cleanupAddFrame,\n handleKeyDownListBox: functions.handleKeyDownListBox,\n listBoxId,\n }\n}\n\ntype ListBoxProps<T> = {\n activeOptionId: string | undefined\n options: Array<ComboboxOption<T>>\n isExpanded: boolean\n isLoading?: boolean\n noResultText?: ReactNode\n dropdownHelpMessage?: ReactNode\n listBoxId: string\n listBoxRef: RefCallback<HTMLDivElement>\n handleAdd: ((option: ComboboxOption<T>) => void) | undefined\n handleHoverOption: (option: ComboboxOption<T>) => void\n handleSelect: (option: ComboboxOption<T>) => void\n listBoxRect: { top: number; left: number; height?: number }\n triggerWidth: number\n dropdownWidth?: string | number\n callbackRef?: (node: HTMLElement | null) => void\n}\n\nexport const ListBox = memo(\n <T,>({\n activeOptionId,\n options,\n isExpanded,\n isLoading,\n noResultText,\n dropdownHelpMessage,\n listBoxId,\n listBoxRef,\n handleAdd,\n handleHoverOption,\n handleSelect,\n listBoxRect,\n triggerWidth,\n dropdownWidth,\n callbackRef,\n }: ListBoxProps<T>) => {\n const theme = useTheme()\n\n const minLength = useMemo(\n () =>\n (activeOptionId === undefined ? 0 : options.findIndex((o) => o.id === activeOptionId)) + 1,\n // eslint-disable-next-line smarthr/best-practice-for-unstable-dependencies\n [activeOptionId, options],\n )\n const [prevMinLength, setPrevMinLength] = useState(minLength)\n const [currentItemLength, setCurrentItemLength] = useState(() =>\n Math.max(OPTION_INCREMENT_AMOUNT, minLength),\n )\n\n if (minLength !== prevMinLength) {\n setPrevMinLength(minLength)\n setCurrentItemLength((current) => Math.max(current, minLength))\n }\n\n // eslint-disable-next-line smarthr/best-practice-for-unstable-dependencies\n const items = useMemo(() => options.slice(0, currentItemLength), [currentItemLength, options])\n\n const styles = useMemo(() => {\n const { top, left, height } = listBoxRect\n const dropdownListWidth = dropdownWidth || triggerWidth\n\n return {\n wrapper: {\n top: `${top}px`,\n left: `${left}px`,\n width: `${triggerWidth}px`,\n },\n dropdownList: {\n width:\n typeof dropdownListWidth === 'string' ? dropdownListWidth : `${dropdownListWidth}px`,\n /* HINT: left に依存させると、算出した幅がさらに maxWidth を縮めて再計算の度に幅が縮んでいくため、\n ビューポート幅のみから算出する */\n maxWidth: `calc(100vw - ${theme.spacingByChar(0.5)})`,\n height: height ? `${height}px` : undefined,\n },\n }\n }, [listBoxRect, triggerWidth, dropdownWidth, theme])\n\n const latest = useLatest({ handleAdd, handleHoverOption, handleSelect, options, minLength })\n\n const functions = useMemo(() => {\n const resolveOption = (e: MouseEvent) => {\n const el = findDelegateTarget<HTMLButtonElement>(e, 'button[role=\"option\"]')\n if (!el || el.disabled) return null\n return latest.options.find((o) => o.id === el.id) ?? null\n }\n\n return {\n intersectCallbackRef: (node: HTMLElement | null) => {\n if (node === null) {\n return\n }\n\n const observer = new IntersectionObserver(([entry]) => {\n if (entry.isIntersecting) {\n setCurrentItemLength((current) =>\n Math.max(current + OPTION_INCREMENT_AMOUNT, latest.minLength),\n )\n }\n })\n\n observer.observe(node)\n\n return () => observer.disconnect()\n },\n handleDelegateClick: (e: MouseEvent) => {\n const option = resolveOption(e)\n if (option) {\n if (option.isNew) {\n latest.handleAdd?.(option)\n } else {\n latest.handleSelect(option)\n }\n }\n },\n handleDelegateMouseOver: (e: MouseEvent) => {\n const option = resolveOption(e)\n if (option) {\n latest.handleHoverOption(option)\n }\n },\n }\n }, [latest])\n\n return (\n <Portal ref={callbackRef} className={CLASS_NAMES.wrapper} style={styles.wrapper}>\n <Scroller\n ref={listBoxRef}\n role=\"listbox\"\n id={listBoxId}\n className={CLASS_NAMES.dropdownList}\n style={styles.dropdownList}\n aria-hidden={!isExpanded}\n onMouseOver={functions.handleDelegateMouseOver}\n onClick={functions.handleDelegateClick}\n >\n {dropdownHelpMessage && (\n <Text\n as=\"p\"\n className={CLASS_NAMES.helpMessage}\n icon={<FaCircleInfoIcon color=\"TEXT_GREY\" />}\n >\n {dropdownHelpMessage}\n </Text>\n )}\n {isExpanded ? (\n isLoading ? (\n <div className={CLASS_NAMES.loaderWrapper}>\n <Loader />\n </div>\n ) : options.length === 0 ? (\n <LiveRegion className={CLASS_NAMES.noItems}>\n {noResultText ?? (\n <Localizer\n id=\"smarthr-ui/Combobox/noResultsText\"\n defaultText=\"一致する選択肢がありません。\"\n />\n )}\n </LiveRegion>\n ) : (\n items.map(({ item: { label, disabled }, id, ...optionRest }) => (\n <ItemButton\n {...optionRest}\n key={id}\n id={id}\n disabled={disabled}\n active={id === activeOptionId}\n label={label}\n />\n ))\n )\n ) : null}\n {currentItemLength < options.length && (\n <Intersection callbackRef={functions.intersectCallbackRef} />\n )}\n </Scroller>\n </Portal>\n )\n },\n) as <T>(props: ListBoxProps<T>) => ReactNode\n\nconst Intersection = memo<{\n callbackRef: (node: HTMLElement | null) => (() => void) | undefined\n}>(({ callbackRef }) => <div ref={callbackRef} />)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDA;AACA;AAEA;AAEA;AACE;AACE;AACA;;;AAGE;AAC0D;;;AAG3D;AACD;AAEA;AACA;AAED;AACF;AAED;AACE;;;;;;;;AASF;AAEO;AAWL;;AAGA;AACE;AACA;AACD;;;;;AAOD;;;AAGE;AACE;AACE;;AAGF;AACF;;AAGF;AAEA;;AAGA;AAEA;;AAGE;AACE;;;AAIA;;;;AAMA;AACE;;AACK;;;;;AAOL;AACE;;;;;;AAKN;;AAGE;;;;;;;;;AAUE;;;;;AAUA;;AAEE;;AACK;;AAEL;;AACK;;AAEL;;;;;AAIA;;;;;;AAOF;;;;AAIA;;AAGA;AAEA;;AAEE;;AACK;;AAEL;;AAGF;;;;AAIC;AACD;;AAEF;;;;;;;;AASI;;;;;;;AAKK;AACL;;;;AAMA;;;AAEO;;;;;;;;;AAQX;AACE;;;AAGI;;AAEA;;AAEJ;AACF;AACE;;AAEF;;;;;AAKJ;AAEA;;;;;;;;;AAaI;AACA;;;;;;;AAOF;;;;;AAQE;;;;;AAOF;AAEA;;;AAGA;;;;;AAMA;;;;;;;;AAQE;;;;;;;AAOD;;;;;;AAML;AAoBO;AAkBH;AAEA;;AAIE;;;AAOF;;AAEE;;;;AAMF;;AAEE;;AAGE;;;;AAIC;AACD;AACE;AAEA;AACkB;;;AAGnB;;;AAIL;AAEA;AACE;;AAEE;AAAwB;;AAE1B;;AAGE;AACE;;;;AAKE;AACE;;AAIJ;AAEA;AAEA;;AAEF;AACE;;AAEE;AACE;;;AAEA;;;;AAIN;AACE;;AAEE;;;;AAIR;;AAwDF;AAGF;;"}
|
|
1
|
+
{"version":3,"file":"useListbox.js","sources":["../../../../src/components/Combobox/client/useListbox.tsx"],"sourcesContent":["'use client'\n\nimport {\n type KeyboardEvent,\n type MouseEvent,\n type ReactNode,\n type RefCallback,\n type RefObject,\n memo,\n useId,\n useLayoutEffect,\n useMemo,\n useState,\n} from 'react'\nimport { tv } from 'tailwind-variants'\n\nimport { useAnimationFrame } from '../../../hooks/client/useAnimationFrame'\nimport { useLayoutEffectRef } from '../../../hooks/client/useLayoutEffectRef'\nimport { useMergeRefs } from '../../../hooks/client/useMergeRefs'\nimport { useSafeAreaInsets } from '../../../hooks/client/useSafeAreaInsets'\nimport { useTheme } from '../../../hooks/client/useTheme'\nimport { useLatest } from '../../../hooks/useLatest'\nimport { Localizer } from '../../../intl'\nimport { findDelegateTarget } from '../../../libs/delegate'\nimport { FaCircleInfoIcon } from '../../Icon'\nimport { LiveRegion } from '../../LiveRegion'\nimport { Loader } from '../../Loader'\nimport { Portal } from '../../Portal'\nimport { Scroller } from '../../Scroller'\nimport { Text } from '../../Text'\n\nimport { ItemButton } from './ItemButton'\n\nimport type { ComboboxItem, ComboboxOption } from './types'\n\ntype Props<T> = {\n options: Array<ComboboxOption<T>>\n dropdownHelpMessage?: ReactNode\n dropdownWidth?: string | number\n onAdd?: (label: string) => void\n onSelect: (item: ComboboxItem<T>) => void\n isExpanded: boolean\n isLoading?: boolean\n triggerRef: RefObject<HTMLElement | null>\n /** 検索結果が0件の時に表示するコンテンツ */\n noResultText?: ReactNode\n}\n\ntype Rect = {\n top: number\n left: number\n height?: number\n}\n\nconst KEY_DOWN_REGEX = /^(Arrow)?Down$/\nconst KEY_UP_REGEX = /^(Arrow)?Up/\n\nconst OPTION_INCREMENT_AMOUNT = 100\n\nconst classNameGenerator = tv({\n slots: {\n wrapper: 'shr-absolute',\n dropdownList: [\n 'smarthr-ui-Combobox-dropdownList',\n 'shr-absolute shr-z-overlap shr-box-border shr-min-w-full shr-rounded-m shr-bg-white shr-py-0.5 shr-shadow-layer-3 forced-colors:shr-outline forced-colors:shr-outline-1',\n /* 縦スクロールに気づきやすくするために8個目のアイテムが半分見切れるように max-height を算出\n = (アイテムのフォントサイズ + アイテムの上下padding) * 7.5 + コンテナの上padding */\n 'shr-max-h-[calc((theme(fontSize.base)_+_theme(spacing[0.5])_*_2)_*_7.5_+_theme(spacing[0.5]))]',\n 'aria-hidden:shr-hidden',\n ],\n helpMessage:\n 'shr-whitespace-[initial] shr-border-b-shorthand shr-mx-0.5 shr-mb-0.5 shr-mt-0 shr-px-0.5 shr-pb-0.5 shr-pt-0 shr-text-sm',\n loaderWrapper: 'shr-flex shr-items-center shr-justify-center shr-p-1',\n noItems:\n 'smarthr-ui-Combobox-noItems shr-my-0 shr-block shr-bg-white shr-px-1 shr-py-0.5 shr-text-base',\n },\n})\n\nconst CLASS_NAMES = (() => {\n const { wrapper, dropdownList, helpMessage, loaderWrapper, noItems } = classNameGenerator()\n\n return {\n wrapper: wrapper(),\n dropdownList: dropdownList(),\n helpMessage: helpMessage(),\n loaderWrapper: loaderWrapper(),\n noItems: noItems(),\n }\n})()\n\nexport const useListbox = <T,>({\n options,\n dropdownHelpMessage,\n dropdownWidth,\n onAdd,\n onSelect,\n isExpanded,\n isLoading,\n triggerRef,\n noResultText,\n}: Props<T>) => {\n const listBoxId = useId()\n\n const [navigationType, setNavigationType] = useState<'pointer' | 'key'>('pointer')\n const [listBoxRect, setListBoxRect] = useState<Rect>({\n top: 0,\n left: 0,\n })\n // HINT: calculateRectで同時に計算するとwidthの幅が変更されるタイミングの問題でlistBoxHeightが変化する場合がある\n const [triggerWidth, setTriggerWidth] = useState(0)\n\n const [activeOption, setActiveOption] = useState<ComboboxOption<T> | null>(null)\n const [prevOptions, setPrevOptions] = useState(options)\n\n if (options !== prevOptions) {\n setPrevOptions(options)\n // props の変更によって activeOption の状態が変わりうるので、実態を反映する\n setActiveOption((current) => {\n if (current === null) {\n return null\n }\n\n return options.find((option) => current.id === option.id) ?? null\n })\n }\n\n const theme = useTheme()\n\n const addFrame = useAnimationFrame()\n\n const getSafeAreaInsets = useSafeAreaInsets()\n const latest = useLatest({\n onAdd,\n onSelect,\n activeOption,\n options,\n triggerRef,\n theme,\n getSafeAreaInsets,\n addFrame,\n })\n const hasOnAdd = Boolean(onAdd)\n\n const functions = useMemo(() => {\n let listBox: HTMLElement | null = null\n\n const moveActiveOptionIndex = (currentActive: ComboboxOption<T> | null, delta: -1 | 1) => {\n if (latest.options.every((option) => option.item.disabled)) {\n return\n }\n\n const currentActiveIndex =\n currentActive === null\n ? -1\n : latest.options.findIndex((option) => option.id === currentActive.id)\n let nextIndex = 0\n\n if (currentActiveIndex !== -1) {\n nextIndex = (currentActiveIndex + delta + latest.options.length) % latest.options.length\n } else if (delta !== 1) {\n nextIndex = latest.options.length - 1\n }\n\n const nextActive = latest.options[nextIndex]\n\n if (nextActive) {\n if (nextActive.item.disabled) {\n moveActiveOptionIndex(nextActive, delta)\n } else {\n setActiveOption(nextActive)\n }\n }\n }\n\n return {\n baseCallbackRef: (node: HTMLElement | null) => {\n listBox = node\n },\n calculateRect: () => {\n if (!listBox || !latest.triggerRef.current) {\n return\n }\n\n const rect = latest.triggerRef.current.getBoundingClientRect()\n // HINT: safe areaに重ならない領域を、リストボックスを表示できる範囲とする\n const safeAreaInsets = latest.getSafeAreaInsets()\n const bottomSpace = window.innerHeight - safeAreaInsets.bottom - rect.bottom\n const topSpace = rect.top - safeAreaInsets.top\n const listBoxHeight = Math.min(\n listBox.scrollHeight,\n parseInt(getComputedStyle(listBox).maxHeight, 10),\n )\n const offset = 2\n\n let top = 0\n let height: number | undefined = undefined\n\n if (bottomSpace >= listBoxHeight) {\n // 下側に十分なスペースがある場合は下側に通常表示\n top = rect.top + rect.height - offset + window.pageYOffset\n } else if (topSpace >= listBoxHeight) {\n // 上側に十分なスペースがある場合は上側に通常表示\n top = rect.top - listBoxHeight + offset + window.pageYOffset\n } else if (topSpace > bottomSpace) {\n // 上下に十分なスペースがなく、上側の方がスペースが大きい場合は上側に縮めて表示\n top = rect.top - topSpace + offset + window.pageYOffset\n height = topSpace\n } else {\n // 下側に縮めて表示\n top = rect.top + rect.height - offset + window.pageYOffset\n height = bottomSpace\n }\n\n // HINT: dropdownWidth は 'auto' や '%' などの CSS 値を取りうるため、算出済みの幅を実測して判定する\n const listBoxWidth = listBox.getBoundingClientRect().width\n // ドロップダウンの幅は maxWidth でビューポート右端から余白分を残すよう制限しているため、位置の判定にも同じ余白を使う\n const viewportMargin = parseInt(latest.theme.spacingByChar(0.5), 10)\n // 入力欄の左端を起点に右方向へ表示する場合に使える幅\n const rightSpace = window.innerWidth - safeAreaInsets.right - rect.left - viewportMargin\n // 入力欄の右端を起点に左方向へ表示する場合に使える幅\n const leftSpace = rect.right - safeAreaInsets.left\n\n // ビューポートの左端を基準に計算\n let left = window.pageXOffset\n\n if (listBoxWidth <= rightSpace) {\n // 右側に十分なスペースがある場合は入力欄の左端に揃えて通常表示\n left += rect.left\n } else if (listBoxWidth <= leftSpace) {\n // 左側に収まる場合は入力欄の右端に揃えて表示\n left += rect.right - listBoxWidth\n } else {\n // どちらにも収まらない場合はsafe areaの左端に揃えて表示\n left += safeAreaInsets.left\n }\n\n setListBoxRect({\n top,\n left,\n height,\n })\n setTriggerWidth(rect.width)\n },\n handleKeyDownListBox: (e: KeyboardEvent<HTMLElement>) => {\n setNavigationType('key')\n\n if (KEY_DOWN_REGEX.test(e.key)) {\n // HINT: MultiComboboxの削除ボタンにフォーカスがある状態など、input以外からこのハンドラへ\n // 到達する経路ではpreventDefaultされないため、ブラウザ側のデフォルトキー操作(iOS Safariでの\n // ページスクロール等)が発生してしまう。ここで明示的に止める\n e.preventDefault()\n e.stopPropagation()\n moveActiveOptionIndex(latest.activeOption, 1)\n } else if (KEY_UP_REGEX.test(e.key)) {\n e.preventDefault()\n e.stopPropagation()\n moveActiveOptionIndex(latest.activeOption, -1)\n } else if (e.key === 'Enter') {\n if (latest.activeOption === null) {\n return\n }\n\n e.stopPropagation()\n\n if (!latest.activeOption.isNew) {\n latest.onSelect(latest.activeOption.item)\n } else if (latest.onAdd) {\n latest.onAdd(latest.activeOption.item.value)\n }\n } else {\n setActiveOption(null)\n }\n },\n cleanupAddFrame: () => latest.addFrame.cancel(),\n handleAdd: hasOnAdd\n ? (option: ComboboxOption<T>) => {\n // HINT: Dropdown系コンポーネント内でComboboxを使うと、選択肢がportalで表現されている関係上Dropdownが閉じてしまう\n // 処理を遅延させることで正常に閉じる/閉じないの判定を行えるようにする\n latest.addFrame.request(() => {\n latest.onAdd!(option.item.value)\n })\n }\n : undefined,\n handleSelect: (option: ComboboxOption<T>) => {\n latest.onSelect(option.item)\n },\n handleHoverOption: (option: ComboboxOption<T>) => {\n setNavigationType('pointer')\n setActiveOption(option)\n },\n }\n }, [hasOnAdd, latest])\n\n const listBoxLayoutEffectRef = useLayoutEffectRef(\n (node: HTMLElement | null) => {\n // actionOption の要素が表示される位置までリストボックス内をスクロールさせる\n if (!node || activeOption === null || navigationType !== 'key') {\n return\n }\n\n const activeElement = node.querySelector<HTMLElement>('button[data-active=\"true\"]')\n\n if (!activeElement) {\n return\n }\n\n const activeRect = activeElement.getBoundingClientRect()\n const containerRect = node.getBoundingClientRect()\n\n if (activeRect.top < containerRect.top) {\n node.scrollTop -= containerRect.top - activeRect.top\n } else if (activeRect.bottom > containerRect.bottom) {\n node.scrollTop += activeRect.bottom - containerRect.bottom\n }\n },\n [activeOption, navigationType],\n )\n const mergedListBoxRef = useMergeRefs(listBoxLayoutEffectRef, functions.baseCallbackRef)\n\n useLayoutEffect(() => {\n // 閉じたときに activeOption を初期化\n if (!isExpanded) {\n return setActiveOption(null)\n }\n\n functions.calculateRect()\n\n const scrollOption = { capture: true, passive: true }\n window.addEventListener('scroll', functions.calculateRect, scrollOption)\n window.addEventListener('resize', functions.calculateRect, { passive: true })\n\n return () => {\n window.removeEventListener('scroll', functions.calculateRect, scrollOption)\n window.removeEventListener('resize', functions.calculateRect)\n }\n // HINT: optionsが変わる場合メニューのサイズが変わる可能性がある\n // eslint-disable-next-line smarthr/best-practice-for-unstable-dependencies\n }, [isExpanded, options, functions])\n\n return {\n listBoxProps: {\n activeOptionId: activeOption?.id,\n options,\n isExpanded,\n isLoading,\n dropdownHelpMessage,\n noResultText,\n listBoxId,\n listBoxRef: mergedListBoxRef,\n handleAdd: functions.handleAdd,\n handleHoverOption: functions.handleHoverOption,\n handleSelect: functions.handleSelect,\n listBoxRect,\n triggerWidth,\n dropdownWidth,\n },\n activeOption,\n cleanupAddFrame: functions.cleanupAddFrame,\n handleKeyDownListBox: functions.handleKeyDownListBox,\n listBoxId,\n }\n}\n\ntype ListBoxProps<T> = {\n activeOptionId: string | undefined\n options: Array<ComboboxOption<T>>\n isExpanded: boolean\n isLoading?: boolean\n noResultText?: ReactNode\n dropdownHelpMessage?: ReactNode\n listBoxId: string\n listBoxRef: RefCallback<HTMLDivElement>\n handleAdd: ((option: ComboboxOption<T>) => void) | undefined\n handleHoverOption: (option: ComboboxOption<T>) => void\n handleSelect: (option: ComboboxOption<T>) => void\n listBoxRect: { top: number; left: number; height?: number }\n triggerWidth: number\n dropdownWidth?: string | number\n callbackRef?: (node: HTMLElement | null) => void\n}\n\nexport const ListBox = memo(\n <T,>({\n activeOptionId,\n options,\n isExpanded,\n isLoading,\n noResultText,\n dropdownHelpMessage,\n listBoxId,\n listBoxRef,\n handleAdd,\n handleHoverOption,\n handleSelect,\n listBoxRect,\n triggerWidth,\n dropdownWidth,\n callbackRef,\n }: ListBoxProps<T>) => {\n const theme = useTheme()\n\n const minLength = useMemo(\n () =>\n (activeOptionId === undefined ? 0 : options.findIndex((o) => o.id === activeOptionId)) + 1,\n // eslint-disable-next-line smarthr/best-practice-for-unstable-dependencies\n [activeOptionId, options],\n )\n const [prevMinLength, setPrevMinLength] = useState(minLength)\n const [currentItemLength, setCurrentItemLength] = useState(() =>\n Math.max(OPTION_INCREMENT_AMOUNT, minLength),\n )\n\n if (minLength !== prevMinLength) {\n setPrevMinLength(minLength)\n setCurrentItemLength((current) => Math.max(current, minLength))\n }\n\n // eslint-disable-next-line smarthr/best-practice-for-unstable-dependencies\n const items = useMemo(() => options.slice(0, currentItemLength), [currentItemLength, options])\n\n const styles = useMemo(() => {\n const { top, left, height } = listBoxRect\n const dropdownListWidth = dropdownWidth || triggerWidth\n\n return {\n wrapper: {\n top: `${top}px`,\n left: `${left}px`,\n width: `${triggerWidth}px`,\n },\n dropdownList: {\n width:\n typeof dropdownListWidth === 'string' ? dropdownListWidth : `${dropdownListWidth}px`,\n /* HINT: left に依存させると、算出した幅がさらに maxWidth を縮めて再計算の度に幅が縮んでいくため、\n ビューポート幅のみから算出する */\n maxWidth: `calc(100vw - ${theme.spacingByChar(0.5)} - env(safe-area-inset-left) - env(safe-area-inset-right))`,\n height: height ? `${height}px` : undefined,\n },\n }\n }, [listBoxRect, triggerWidth, dropdownWidth, theme])\n\n const latest = useLatest({ handleAdd, handleHoverOption, handleSelect, options, minLength })\n\n const functions = useMemo(() => {\n const resolveOption = (e: MouseEvent) => {\n const el = findDelegateTarget<HTMLButtonElement>(e, 'button[role=\"option\"]')\n if (!el || el.disabled) return null\n return latest.options.find((o) => o.id === el.id) ?? null\n }\n\n return {\n intersectCallbackRef: (node: HTMLElement | null) => {\n if (node === null) {\n return\n }\n\n const observer = new IntersectionObserver(([entry]) => {\n if (entry.isIntersecting) {\n setCurrentItemLength((current) =>\n Math.max(current + OPTION_INCREMENT_AMOUNT, latest.minLength),\n )\n }\n })\n\n observer.observe(node)\n\n return () => observer.disconnect()\n },\n handleDelegateClick: (e: MouseEvent) => {\n const option = resolveOption(e)\n if (option) {\n if (option.isNew) {\n latest.handleAdd?.(option)\n } else {\n latest.handleSelect(option)\n }\n }\n },\n handleDelegateMouseOver: (e: MouseEvent) => {\n const option = resolveOption(e)\n if (option) {\n latest.handleHoverOption(option)\n }\n },\n }\n }, [latest])\n\n return (\n <Portal ref={callbackRef} className={CLASS_NAMES.wrapper} style={styles.wrapper}>\n <Scroller\n ref={listBoxRef}\n role=\"listbox\"\n id={listBoxId}\n className={CLASS_NAMES.dropdownList}\n style={styles.dropdownList}\n aria-hidden={!isExpanded}\n onMouseOver={functions.handleDelegateMouseOver}\n onClick={functions.handleDelegateClick}\n >\n {dropdownHelpMessage && (\n <Text\n as=\"p\"\n className={CLASS_NAMES.helpMessage}\n icon={<FaCircleInfoIcon color=\"TEXT_GREY\" />}\n >\n {dropdownHelpMessage}\n </Text>\n )}\n {isExpanded ? (\n isLoading ? (\n <div className={CLASS_NAMES.loaderWrapper}>\n <Loader />\n </div>\n ) : options.length === 0 ? (\n <LiveRegion className={CLASS_NAMES.noItems}>\n {noResultText ?? (\n <Localizer\n id=\"smarthr-ui/Combobox/noResultsText\"\n defaultText=\"一致する選択肢がありません。\"\n />\n )}\n </LiveRegion>\n ) : (\n items.map(({ item: { label, disabled }, id, ...optionRest }) => (\n <ItemButton\n {...optionRest}\n key={id}\n id={id}\n disabled={disabled}\n active={id === activeOptionId}\n label={label}\n />\n ))\n )\n ) : null}\n {currentItemLength < options.length && (\n <Intersection callbackRef={functions.intersectCallbackRef} />\n )}\n </Scroller>\n </Portal>\n )\n },\n) as <T>(props: ListBoxProps<T>) => ReactNode\n\nconst Intersection = memo<{\n callbackRef: (node: HTMLElement | null) => (() => void) | undefined\n}>(({ callbackRef }) => <div ref={callbackRef} />)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA;AACA;AAEA;AAEA;AACE;AACE;AACA;;;AAGE;AAC0D;;;AAG3D;AACD;AAEA;AACA;AAED;AACF;AAED;AACE;;;;;;;;AASF;AAEO;AAWL;;AAGA;AACE;AACA;AACD;;;;;AAOD;;;AAGE;AACE;AACE;;AAGF;AACF;;AAGF;AAEA;AAEA;;;;;;;;;;AAUC;AACD;AAEA;;AAGE;AACE;;;AAIA;;;;AAMA;AACE;;AACK;;;;;AAOL;AACE;;;;;;AAKN;;AAGE;;;;;;;;;AAUE;AACA;;;;;;AAWA;;AAEE;;AACK;;AAEL;;AACK;;AAEL;;;;;AAIA;;;;;;AAOF;;AAEA;;;;AAKA;AAEA;;AAEE;;AACK;;AAEL;;;;AAGA;;AAGF;;;;AAIC;AACD;;AAEF;;;;;;;;AASI;;;;;;;AAKK;AACL;;;;AAMA;;;AAEO;;;;;;;;;AAQX;AACE;;;AAGI;;AAEA;;AAEJ;AACF;AACE;;AAEF;;;;;AAKJ;AAEA;;;;;;;;;AAaI;AACA;;;;;;;AAOF;;;;;AAQE;;;;;AAOF;AAEA;;;AAGA;;;;;AAMA;;;;;;;;AAQE;;;;;;;AAOD;;;;;;AAML;AAoBO;AAkBH;AAEA;;AAIE;;;AAOF;;AAEE;;;;AAMF;;AAEE;;AAGE;;;;AAIC;AACD;AACE;AAEA;AACkB;;;AAGnB;;;AAIL;AAEA;AACE;;AAEE;AAAwB;;AAE1B;;AAGE;AACE;;;;AAKE;AACE;;AAIJ;AAEA;AAEA;;AAEF;AACE;;AAEE;AACE;;;AAEA;;;;AAIN;AACE;;AAEE;;;;AAIR;;AAwDF;AAGF;;"}
|
|
@@ -20,7 +20,7 @@ var components_Dialog_ControlledStepFormDialog_client_StepFormDialogProvider = r
|
|
|
20
20
|
|
|
21
21
|
// HINT: ButtonArgTypeの関数部分とButtonResolverTypeはどちらも`(currentStep, defaultText) => ...`という
|
|
22
22
|
// 同じ引数形だが、戻り値がReactNodeかButtonResolverResultかで実行時に判別する
|
|
23
|
-
const isButtonResolverResult = (value) =>
|
|
23
|
+
const isButtonResolverResult = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value) && !React.isValidElement(value);
|
|
24
24
|
const headingObjectConverter = (text) => ({ text });
|
|
25
25
|
const buttonObjectConverter = (text) => ({
|
|
26
26
|
text,
|
package/lib/components/Dialog/ControlledStepFormDialog/client/ControlledStepFormDialog.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ControlledStepFormDialog.cjs","sources":["../../../../../src/components/Dialog/ControlledStepFormDialog/client/ControlledStepFormDialog.tsx"],"sourcesContent":["'use client'\n\nimport {\n type ComponentPropsWithRef,\n type FC,\n type FormEvent,\n type MouseEvent,\n type ReactNode,\n isValidElement,\n useContext,\n useMemo,\n useRef,\n} from 'react'\n\nimport { useLatest } from '../../../../hooks/useLatest'\nimport { useObjectAttributes } from '../../../../hooks/useObjectAttributes'\nimport { useLocalize } from '../../../../intl'\nimport { DialogContent, DialogPortal } from '../../client'\nimport { useObjectHeading } from '../../useObjectHeading'\n\nimport { StepFormDialogContent } from './StepFormDialogContent'\nimport { StepFormDialogContext, StepFormDialogProvider } from './StepFormDialogProvider'\n\nimport type { ExtendElementPropsWithRef, ExtendProps } from '../../../../types'\nimport type { DialogProps /** コンテンツなにもないDialogの基本props */ } from '../../types'\nimport type { ButtonThemeType, CommonButtonType, StepItem } from '../type'\n\ntype ButtonArgType = ReactNode | ((currentStep: StepItem, defaultText: ReactNode) => ReactNode)\n\ntype VariableFunctionType<T> = (currentStep: StepItem) => T\ntype ObjectButtonType = {\n text?: ButtonArgType\n /** ボタンを非表示にするかどうか */\n hidden?: boolean | VariableFunctionType<boolean>\n /** ボタンを無効にするかどうか */\n disabled?: boolean | VariableFunctionType<boolean>\n /** ボタンのスタイル */\n theme?: ButtonThemeType | VariableFunctionType<ButtonThemeType>\n}\n\n/** text/theme/disabled/hiddenをまとめて1つの関数で解決する場合の戻り値。関数のネストは許容しない */\ntype ButtonResolverResult = {\n text?: ReactNode\n theme?: ButtonThemeType\n disabled?: boolean\n hidden?: boolean\n}\n/** currentStepに応じてtext/theme/disabled/hiddenをまとめて返す関数形式 */\ntype ButtonResolverType = (currentStep: StepItem, defaultText: ReactNode) => ButtonResolverResult\n\ntype ButtonType = ButtonArgType | ObjectButtonType | ButtonResolverType\n\n// HINT: ButtonArgTypeの関数部分とButtonResolverTypeはどちらも`(currentStep, defaultText) => ...`という\n// 同じ引数形だが、戻り値がReactNodeかButtonResolverResultかで実行時に判別する\nconst isButtonResolverResult = (value: unknown): value is ButtonResolverResult =>\n
|
|
1
|
+
{"version":3,"file":"ControlledStepFormDialog.cjs","sources":["../../../../../src/components/Dialog/ControlledStepFormDialog/client/ControlledStepFormDialog.tsx"],"sourcesContent":["'use client'\n\nimport {\n type ComponentPropsWithRef,\n type FC,\n type FormEvent,\n type MouseEvent,\n type ReactNode,\n isValidElement,\n useContext,\n useMemo,\n useRef,\n} from 'react'\n\nimport { useLatest } from '../../../../hooks/useLatest'\nimport { useObjectAttributes } from '../../../../hooks/useObjectAttributes'\nimport { useLocalize } from '../../../../intl'\nimport { DialogContent, DialogPortal } from '../../client'\nimport { useObjectHeading } from '../../useObjectHeading'\n\nimport { StepFormDialogContent } from './StepFormDialogContent'\nimport { StepFormDialogContext, StepFormDialogProvider } from './StepFormDialogProvider'\n\nimport type { ExtendElementPropsWithRef, ExtendProps } from '../../../../types'\nimport type { DialogProps /** コンテンツなにもないDialogの基本props */ } from '../../types'\nimport type { ButtonThemeType, CommonButtonType, StepItem } from '../type'\n\ntype ButtonArgType = ReactNode | ((currentStep: StepItem, defaultText: ReactNode) => ReactNode)\n\ntype VariableFunctionType<T> = (currentStep: StepItem) => T\ntype ObjectButtonType = {\n text?: ButtonArgType\n /** ボタンを非表示にするかどうか */\n hidden?: boolean | VariableFunctionType<boolean>\n /** ボタンを無効にするかどうか */\n disabled?: boolean | VariableFunctionType<boolean>\n /** ボタンのスタイル */\n theme?: ButtonThemeType | VariableFunctionType<ButtonThemeType>\n}\n\n/** text/theme/disabled/hiddenをまとめて1つの関数で解決する場合の戻り値。関数のネストは許容しない */\ntype ButtonResolverResult = {\n text?: ReactNode\n theme?: ButtonThemeType\n disabled?: boolean\n hidden?: boolean\n}\n/** currentStepに応じてtext/theme/disabled/hiddenをまとめて返す関数形式 */\ntype ButtonResolverType = (currentStep: StepItem, defaultText: ReactNode) => ButtonResolverResult\n\ntype ButtonType = ButtonArgType | ObjectButtonType | ButtonResolverType\n\n// HINT: ButtonArgTypeの関数部分とButtonResolverTypeはどちらも`(currentStep, defaultText) => ...`という\n// 同じ引数形だが、戻り値がReactNodeかButtonResolverResultかで実行時に判別する\nconst isButtonResolverResult = (value: unknown): value is ButtonResolverResult =>\n Boolean(value) && typeof value === 'object' && !Array.isArray(value) && !isValidElement(value)\n\ntype StepFormDialogContentProps = ComponentPropsWithRef<typeof StepFormDialogContent>\n\ntype ObjectHeadingType = Omit<StepFormDialogContentProps['heading'], 'id'>\ntype HeadingType = ReactNode | ObjectHeadingType\n\ntype Props = ExtendElementPropsWithRef<\n typeof DialogContent,\n ExtendProps<\n StepFormDialogContentProps,\n DialogProps & {\n heading: HeadingType\n submitButton: ButtonType\n closeButton?: ButtonType\n backButton?: ButtonType\n onSubmit: StepFormDialogContentProps['handleSubmit']\n onClickClose: (e?: MouseEvent<HTMLButtonElement> | KeyboardEvent) => void\n onClickBack?: () => void\n },\n { omit: 'activeStep' | 'handleClickClose' | 'handleClickBack' | 'handleSubmit' }\n >,\n { omit: 'focusTrapRef' }\n>\n\nconst headingObjectConverter = (text: ReactNode) => ({ text })\n\n// HINT: ButtonResolverType(関数)もtextとして保持し、呼び出し後にisButtonResolverResultで判別する\ntype InternalObjectButtonType = Omit<ObjectButtonType, 'text'> & {\n text?: ButtonArgType | ButtonResolverType\n}\n\nconst buttonObjectConverter = (\n text: ButtonArgType | ButtonResolverType,\n): InternalObjectButtonType => ({\n text,\n})\n\ntype UseStepFormDialogButtonProps = {\n button: ButtonType\n currentStep: StepItem\n defaultValues: {\n text: ReactNode\n theme?: ButtonThemeType\n }\n}\n\nconst useStepFormDialogButton = ({\n button,\n currentStep,\n defaultValues: { text: defaultText, theme: defaultTheme },\n}: UseStepFormDialogButtonProps): CommonButtonType => {\n const {\n text: tempText,\n theme: tempTheme,\n disabled: tempDisabled,\n hidden: tempHidden,\n } = useObjectAttributes<ButtonType, InternalObjectButtonType>(button, buttonObjectConverter)\n\n const actualButton = useMemo((): CommonButtonType => {\n let text = tempText ?? defaultText\n let textFunc = false\n let actualTempTheme = tempTheme\n let actualTempDisabled = tempDisabled\n let actualTempHidden = tempHidden\n\n if (typeof text === 'function') {\n textFunc = true\n\n const result = text(currentStep, defaultText)\n\n if (isButtonResolverResult(result)) {\n text = result.text ?? defaultText\n actualTempTheme = result.theme ?? actualTempTheme\n actualTempDisabled = result.disabled ?? actualTempDisabled\n actualTempHidden = result.hidden ?? actualTempHidden\n } else {\n text = result\n }\n }\n\n const actualTheme = actualTempTheme || defaultTheme\n const theme = typeof actualTheme === 'function' ? actualTheme(currentStep) : actualTheme\n const disabled =\n typeof actualTempDisabled === 'function'\n ? actualTempDisabled(currentStep)\n : actualTempDisabled\n const hidden =\n typeof actualTempHidden === 'function' ? actualTempHidden(currentStep) : actualTempHidden\n\n return {\n text,\n theme,\n disabled,\n hidden,\n functionCall: {\n text: textFunc,\n },\n }\n }, [currentStep, tempText, tempTheme, tempDisabled, tempHidden, defaultText, defaultTheme])\n\n return actualButton\n}\n\nexport const ControlledStepFormDialog: FC<Props> = ({ portalParent, id, firstStep, ...rest }) => (\n <DialogPortal id={id} parent={portalParent}>\n <StepFormDialogProvider firstStep={firstStep}>\n <ActualControlledStepFormDialog {...rest} firstStep={firstStep} />\n </StepFormDialogProvider>\n </DialogPortal>\n)\n\nconst ActualControlledStepFormDialog: FC<Omit<Props, 'portalParent'>> = ({\n children,\n heading: orgHeading,\n stepLength,\n contentBgColor,\n contentPadding,\n submitButton: originalSubmitButton,\n closeButton: originalCloseButton,\n backButton: originalBackButton,\n firstStep,\n onSubmit,\n onClickClose,\n onClickBack,\n onPressEscape = onClickClose,\n responseStatus,\n className,\n isOpen,\n ...rest\n}) => {\n const defaultTexts = useLocalize({\n closeButtonLabel: {\n id: 'smarthr-ui/StepFormDialog/closeButtonLabel',\n defaultText: 'キャンセル',\n },\n nextButtonLabel: {\n id: 'smarthr-ui/StepFormDialog/nextButtonLabel',\n defaultText: '次へ',\n },\n backButtonLabel: {\n id: 'smarthr-ui/StepFormDialog/backButtonLabel',\n defaultText: '戻る',\n },\n })\n const { currentStep } = useContext(StepFormDialogContext)\n const activeStep = currentStep?.stepNumber ?? 1\n\n const heading = useObjectHeading<HeadingType, ObjectHeadingType>(\n orgHeading,\n headingObjectConverter,\n )\n\n const tempSubmitButton = useStepFormDialogButton({\n button: originalSubmitButton,\n currentStep,\n defaultValues: {\n text: defaultTexts.nextButtonLabel,\n theme: 'primary' as const,\n },\n })\n const submitButton = useMemo(\n () => ({\n ...tempSubmitButton,\n text:\n tempSubmitButton.functionCall.text || activeStep === stepLength\n ? tempSubmitButton.text\n : defaultTexts.nextButtonLabel,\n }),\n [tempSubmitButton, activeStep, stepLength, defaultTexts.nextButtonLabel],\n )\n const closeButton = useStepFormDialogButton({\n button: originalCloseButton,\n currentStep,\n defaultValues: {\n text: defaultTexts.closeButtonLabel,\n },\n })\n const backButton = useStepFormDialogButton({\n button: originalBackButton,\n currentStep,\n defaultValues: {\n text: defaultTexts.backButtonLabel,\n },\n })\n\n const focusTrapRef = useRef<{ focus: () => void } | null>(null)\n\n const latest = useLatest({ onClickClose, onSubmit, onClickBack, isOpen })\n\n const functions = useMemo(\n () => ({\n handleClickClose: (e?: MouseEvent<HTMLButtonElement>) => {\n if (latest.isOpen) {\n focusTrapRef.current?.focus()\n latest.onClickClose(e)\n }\n },\n handleSubmit: (e: FormEvent<HTMLFormElement>, helpers: Parameters<typeof onSubmit>[1]) => {\n if (latest.isOpen) {\n focusTrapRef.current?.focus()\n latest.onSubmit(e, helpers)\n }\n },\n handleClickBack: () => {\n if (latest.isOpen) {\n focusTrapRef.current?.focus()\n latest.onClickBack?.()\n }\n },\n }),\n [latest],\n )\n\n return (\n <DialogContent\n {...rest}\n focusTrapRef={focusTrapRef}\n isOpen={isOpen}\n className={className}\n ariaLabelledby={heading.id}\n onPressEscape={closeButton.disabled ? undefined : onPressEscape}\n >\n <StepFormDialogContent\n activeStep={activeStep}\n contentBgColor={contentBgColor}\n contentPadding={contentPadding}\n firstStep={firstStep}\n stepLength={stepLength}\n responseStatus={responseStatus}\n handleClickClose={functions.handleClickClose}\n handleSubmit={functions.handleSubmit}\n handleClickBack={functions.handleClickBack}\n heading={heading}\n submitButton={submitButton}\n closeButton={closeButton}\n backButton={backButton}\n >\n {children}\n </StepFormDialogContent>\n </DialogContent>\n )\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAoDA;AACA;AACA;AA0BA;AAOA;;AAIC;AAWD;;AAYE;AACE;;;;;AAMA;;;AAKE;AACE;AACA;AACA;AACA;;;;;;AAMJ;AACA;AACA;AAEI;;AAEJ;;;;;;AAQE;AACE;AACD;;AAEL;AAEA;AACF;;AAUA;;AAoBI;AACE;AACA;AACD;AACD;AACE;AACA;AACD;AACD;AACE;AACA;AACD;AACF;;AAED;;;AAQE;;AAEA;;AAEE;AACD;AACF;AACD;AAEI;;;;AAKD;;AAID;;AAEA;;AAEC;AACF;;AAEC;;AAEA;;AAEC;AACF;AAED;AAEA;AAEA;AAEI;AACE;AACE;AACA;;;AAGJ;AACE;AACE;AACA;;;;AAIF;AACE;AACA;;;AAGL;;AAgCL;;"}
|
|
@@ -18,7 +18,7 @@ import { StepFormDialogProvider, StepFormDialogContext } from './StepFormDialogP
|
|
|
18
18
|
|
|
19
19
|
// HINT: ButtonArgTypeの関数部分とButtonResolverTypeはどちらも`(currentStep, defaultText) => ...`という
|
|
20
20
|
// 同じ引数形だが、戻り値がReactNodeかButtonResolverResultかで実行時に判別する
|
|
21
|
-
const isButtonResolverResult = (value) =>
|
|
21
|
+
const isButtonResolverResult = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value) && !isValidElement(value);
|
|
22
22
|
const headingObjectConverter = (text) => ({ text });
|
|
23
23
|
const buttonObjectConverter = (text) => ({
|
|
24
24
|
text,
|
package/lib/components/Dialog/ControlledStepFormDialog/client/ControlledStepFormDialog.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ControlledStepFormDialog.js","sources":["../../../../../src/components/Dialog/ControlledStepFormDialog/client/ControlledStepFormDialog.tsx"],"sourcesContent":["'use client'\n\nimport {\n type ComponentPropsWithRef,\n type FC,\n type FormEvent,\n type MouseEvent,\n type ReactNode,\n isValidElement,\n useContext,\n useMemo,\n useRef,\n} from 'react'\n\nimport { useLatest } from '../../../../hooks/useLatest'\nimport { useObjectAttributes } from '../../../../hooks/useObjectAttributes'\nimport { useLocalize } from '../../../../intl'\nimport { DialogContent, DialogPortal } from '../../client'\nimport { useObjectHeading } from '../../useObjectHeading'\n\nimport { StepFormDialogContent } from './StepFormDialogContent'\nimport { StepFormDialogContext, StepFormDialogProvider } from './StepFormDialogProvider'\n\nimport type { ExtendElementPropsWithRef, ExtendProps } from '../../../../types'\nimport type { DialogProps /** コンテンツなにもないDialogの基本props */ } from '../../types'\nimport type { ButtonThemeType, CommonButtonType, StepItem } from '../type'\n\ntype ButtonArgType = ReactNode | ((currentStep: StepItem, defaultText: ReactNode) => ReactNode)\n\ntype VariableFunctionType<T> = (currentStep: StepItem) => T\ntype ObjectButtonType = {\n text?: ButtonArgType\n /** ボタンを非表示にするかどうか */\n hidden?: boolean | VariableFunctionType<boolean>\n /** ボタンを無効にするかどうか */\n disabled?: boolean | VariableFunctionType<boolean>\n /** ボタンのスタイル */\n theme?: ButtonThemeType | VariableFunctionType<ButtonThemeType>\n}\n\n/** text/theme/disabled/hiddenをまとめて1つの関数で解決する場合の戻り値。関数のネストは許容しない */\ntype ButtonResolverResult = {\n text?: ReactNode\n theme?: ButtonThemeType\n disabled?: boolean\n hidden?: boolean\n}\n/** currentStepに応じてtext/theme/disabled/hiddenをまとめて返す関数形式 */\ntype ButtonResolverType = (currentStep: StepItem, defaultText: ReactNode) => ButtonResolverResult\n\ntype ButtonType = ButtonArgType | ObjectButtonType | ButtonResolverType\n\n// HINT: ButtonArgTypeの関数部分とButtonResolverTypeはどちらも`(currentStep, defaultText) => ...`という\n// 同じ引数形だが、戻り値がReactNodeかButtonResolverResultかで実行時に判別する\nconst isButtonResolverResult = (value: unknown): value is ButtonResolverResult =>\n
|
|
1
|
+
{"version":3,"file":"ControlledStepFormDialog.js","sources":["../../../../../src/components/Dialog/ControlledStepFormDialog/client/ControlledStepFormDialog.tsx"],"sourcesContent":["'use client'\n\nimport {\n type ComponentPropsWithRef,\n type FC,\n type FormEvent,\n type MouseEvent,\n type ReactNode,\n isValidElement,\n useContext,\n useMemo,\n useRef,\n} from 'react'\n\nimport { useLatest } from '../../../../hooks/useLatest'\nimport { useObjectAttributes } from '../../../../hooks/useObjectAttributes'\nimport { useLocalize } from '../../../../intl'\nimport { DialogContent, DialogPortal } from '../../client'\nimport { useObjectHeading } from '../../useObjectHeading'\n\nimport { StepFormDialogContent } from './StepFormDialogContent'\nimport { StepFormDialogContext, StepFormDialogProvider } from './StepFormDialogProvider'\n\nimport type { ExtendElementPropsWithRef, ExtendProps } from '../../../../types'\nimport type { DialogProps /** コンテンツなにもないDialogの基本props */ } from '../../types'\nimport type { ButtonThemeType, CommonButtonType, StepItem } from '../type'\n\ntype ButtonArgType = ReactNode | ((currentStep: StepItem, defaultText: ReactNode) => ReactNode)\n\ntype VariableFunctionType<T> = (currentStep: StepItem) => T\ntype ObjectButtonType = {\n text?: ButtonArgType\n /** ボタンを非表示にするかどうか */\n hidden?: boolean | VariableFunctionType<boolean>\n /** ボタンを無効にするかどうか */\n disabled?: boolean | VariableFunctionType<boolean>\n /** ボタンのスタイル */\n theme?: ButtonThemeType | VariableFunctionType<ButtonThemeType>\n}\n\n/** text/theme/disabled/hiddenをまとめて1つの関数で解決する場合の戻り値。関数のネストは許容しない */\ntype ButtonResolverResult = {\n text?: ReactNode\n theme?: ButtonThemeType\n disabled?: boolean\n hidden?: boolean\n}\n/** currentStepに応じてtext/theme/disabled/hiddenをまとめて返す関数形式 */\ntype ButtonResolverType = (currentStep: StepItem, defaultText: ReactNode) => ButtonResolverResult\n\ntype ButtonType = ButtonArgType | ObjectButtonType | ButtonResolverType\n\n// HINT: ButtonArgTypeの関数部分とButtonResolverTypeはどちらも`(currentStep, defaultText) => ...`という\n// 同じ引数形だが、戻り値がReactNodeかButtonResolverResultかで実行時に判別する\nconst isButtonResolverResult = (value: unknown): value is ButtonResolverResult =>\n Boolean(value) && typeof value === 'object' && !Array.isArray(value) && !isValidElement(value)\n\ntype StepFormDialogContentProps = ComponentPropsWithRef<typeof StepFormDialogContent>\n\ntype ObjectHeadingType = Omit<StepFormDialogContentProps['heading'], 'id'>\ntype HeadingType = ReactNode | ObjectHeadingType\n\ntype Props = ExtendElementPropsWithRef<\n typeof DialogContent,\n ExtendProps<\n StepFormDialogContentProps,\n DialogProps & {\n heading: HeadingType\n submitButton: ButtonType\n closeButton?: ButtonType\n backButton?: ButtonType\n onSubmit: StepFormDialogContentProps['handleSubmit']\n onClickClose: (e?: MouseEvent<HTMLButtonElement> | KeyboardEvent) => void\n onClickBack?: () => void\n },\n { omit: 'activeStep' | 'handleClickClose' | 'handleClickBack' | 'handleSubmit' }\n >,\n { omit: 'focusTrapRef' }\n>\n\nconst headingObjectConverter = (text: ReactNode) => ({ text })\n\n// HINT: ButtonResolverType(関数)もtextとして保持し、呼び出し後にisButtonResolverResultで判別する\ntype InternalObjectButtonType = Omit<ObjectButtonType, 'text'> & {\n text?: ButtonArgType | ButtonResolverType\n}\n\nconst buttonObjectConverter = (\n text: ButtonArgType | ButtonResolverType,\n): InternalObjectButtonType => ({\n text,\n})\n\ntype UseStepFormDialogButtonProps = {\n button: ButtonType\n currentStep: StepItem\n defaultValues: {\n text: ReactNode\n theme?: ButtonThemeType\n }\n}\n\nconst useStepFormDialogButton = ({\n button,\n currentStep,\n defaultValues: { text: defaultText, theme: defaultTheme },\n}: UseStepFormDialogButtonProps): CommonButtonType => {\n const {\n text: tempText,\n theme: tempTheme,\n disabled: tempDisabled,\n hidden: tempHidden,\n } = useObjectAttributes<ButtonType, InternalObjectButtonType>(button, buttonObjectConverter)\n\n const actualButton = useMemo((): CommonButtonType => {\n let text = tempText ?? defaultText\n let textFunc = false\n let actualTempTheme = tempTheme\n let actualTempDisabled = tempDisabled\n let actualTempHidden = tempHidden\n\n if (typeof text === 'function') {\n textFunc = true\n\n const result = text(currentStep, defaultText)\n\n if (isButtonResolverResult(result)) {\n text = result.text ?? defaultText\n actualTempTheme = result.theme ?? actualTempTheme\n actualTempDisabled = result.disabled ?? actualTempDisabled\n actualTempHidden = result.hidden ?? actualTempHidden\n } else {\n text = result\n }\n }\n\n const actualTheme = actualTempTheme || defaultTheme\n const theme = typeof actualTheme === 'function' ? actualTheme(currentStep) : actualTheme\n const disabled =\n typeof actualTempDisabled === 'function'\n ? actualTempDisabled(currentStep)\n : actualTempDisabled\n const hidden =\n typeof actualTempHidden === 'function' ? actualTempHidden(currentStep) : actualTempHidden\n\n return {\n text,\n theme,\n disabled,\n hidden,\n functionCall: {\n text: textFunc,\n },\n }\n }, [currentStep, tempText, tempTheme, tempDisabled, tempHidden, defaultText, defaultTheme])\n\n return actualButton\n}\n\nexport const ControlledStepFormDialog: FC<Props> = ({ portalParent, id, firstStep, ...rest }) => (\n <DialogPortal id={id} parent={portalParent}>\n <StepFormDialogProvider firstStep={firstStep}>\n <ActualControlledStepFormDialog {...rest} firstStep={firstStep} />\n </StepFormDialogProvider>\n </DialogPortal>\n)\n\nconst ActualControlledStepFormDialog: FC<Omit<Props, 'portalParent'>> = ({\n children,\n heading: orgHeading,\n stepLength,\n contentBgColor,\n contentPadding,\n submitButton: originalSubmitButton,\n closeButton: originalCloseButton,\n backButton: originalBackButton,\n firstStep,\n onSubmit,\n onClickClose,\n onClickBack,\n onPressEscape = onClickClose,\n responseStatus,\n className,\n isOpen,\n ...rest\n}) => {\n const defaultTexts = useLocalize({\n closeButtonLabel: {\n id: 'smarthr-ui/StepFormDialog/closeButtonLabel',\n defaultText: 'キャンセル',\n },\n nextButtonLabel: {\n id: 'smarthr-ui/StepFormDialog/nextButtonLabel',\n defaultText: '次へ',\n },\n backButtonLabel: {\n id: 'smarthr-ui/StepFormDialog/backButtonLabel',\n defaultText: '戻る',\n },\n })\n const { currentStep } = useContext(StepFormDialogContext)\n const activeStep = currentStep?.stepNumber ?? 1\n\n const heading = useObjectHeading<HeadingType, ObjectHeadingType>(\n orgHeading,\n headingObjectConverter,\n )\n\n const tempSubmitButton = useStepFormDialogButton({\n button: originalSubmitButton,\n currentStep,\n defaultValues: {\n text: defaultTexts.nextButtonLabel,\n theme: 'primary' as const,\n },\n })\n const submitButton = useMemo(\n () => ({\n ...tempSubmitButton,\n text:\n tempSubmitButton.functionCall.text || activeStep === stepLength\n ? tempSubmitButton.text\n : defaultTexts.nextButtonLabel,\n }),\n [tempSubmitButton, activeStep, stepLength, defaultTexts.nextButtonLabel],\n )\n const closeButton = useStepFormDialogButton({\n button: originalCloseButton,\n currentStep,\n defaultValues: {\n text: defaultTexts.closeButtonLabel,\n },\n })\n const backButton = useStepFormDialogButton({\n button: originalBackButton,\n currentStep,\n defaultValues: {\n text: defaultTexts.backButtonLabel,\n },\n })\n\n const focusTrapRef = useRef<{ focus: () => void } | null>(null)\n\n const latest = useLatest({ onClickClose, onSubmit, onClickBack, isOpen })\n\n const functions = useMemo(\n () => ({\n handleClickClose: (e?: MouseEvent<HTMLButtonElement>) => {\n if (latest.isOpen) {\n focusTrapRef.current?.focus()\n latest.onClickClose(e)\n }\n },\n handleSubmit: (e: FormEvent<HTMLFormElement>, helpers: Parameters<typeof onSubmit>[1]) => {\n if (latest.isOpen) {\n focusTrapRef.current?.focus()\n latest.onSubmit(e, helpers)\n }\n },\n handleClickBack: () => {\n if (latest.isOpen) {\n focusTrapRef.current?.focus()\n latest.onClickBack?.()\n }\n },\n }),\n [latest],\n )\n\n return (\n <DialogContent\n {...rest}\n focusTrapRef={focusTrapRef}\n isOpen={isOpen}\n className={className}\n ariaLabelledby={heading.id}\n onPressEscape={closeButton.disabled ? undefined : onPressEscape}\n >\n <StepFormDialogContent\n activeStep={activeStep}\n contentBgColor={contentBgColor}\n contentPadding={contentPadding}\n firstStep={firstStep}\n stepLength={stepLength}\n responseStatus={responseStatus}\n handleClickClose={functions.handleClickClose}\n handleSubmit={functions.handleSubmit}\n handleClickBack={functions.handleClickBack}\n heading={heading}\n submitButton={submitButton}\n closeButton={closeButton}\n backButton={backButton}\n >\n {children}\n </StepFormDialogContent>\n </DialogContent>\n )\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAoDA;AACA;AACA;AA0BA;AAOA;;AAIC;AAWD;;AAYE;AACE;;;;;AAMA;;;AAKE;AACE;AACA;AACA;AACA;;;;;;AAMJ;AACA;AACA;AAEI;;AAEJ;;;;;;AAQE;AACE;AACD;;AAEL;AAEA;AACF;;AAUA;;AAoBI;AACE;AACA;AACD;AACD;AACE;AACA;AACD;AACD;AACE;AACA;AACD;AACF;;AAED;;;AAQE;;AAEA;;AAEE;AACD;AACF;AACD;AAEI;;;;AAKD;;AAID;;AAEA;;AAEC;AACF;;AAEC;;AAEA;;AAEC;AACF;AAED;AAEA;AAEA;AAEI;AACE;AACE;AACA;;;AAGJ;AACE;AACE;AACA;;;;AAIF;AACE;AACA;;;AAGL;;AAgCL;;"}
|