smarthr-ui 99.3.1 → 99.3.2
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/_virtual/index.cjs +2 -2
- package/lib/_virtual/index.js +2 -2
- package/lib/_virtual/index2.cjs +2 -2
- package/lib/_virtual/index2.js +2 -2
- package/lib/components/Combobox/ItemButton.cjs +11 -2
- package/lib/components/Combobox/ItemButton.cjs.map +1 -1
- package/lib/components/Combobox/ItemButton.js +11 -2
- package/lib/components/Combobox/ItemButton.js.map +1 -1
- package/lib/components/Combobox/MultiCombobox/MultiCombobox.cjs +1 -1
- package/lib/components/Combobox/MultiCombobox/MultiCombobox.cjs.map +1 -1
- package/lib/components/Combobox/MultiCombobox/MultiCombobox.js +1 -1
- package/lib/components/Combobox/MultiCombobox/MultiCombobox.js.map +1 -1
- package/lib/components/Combobox/SingleCombobox/SingleCombobox.cjs +1 -1
- package/lib/components/Combobox/SingleCombobox/SingleCombobox.cjs.map +1 -1
- package/lib/components/Combobox/SingleCombobox/SingleCombobox.js +1 -1
- package/lib/components/Combobox/SingleCombobox/SingleCombobox.js.map +1 -1
- package/lib/components/DatePicker/DatePicker.cjs +1 -1
- package/lib/components/DatePicker/DatePicker.cjs.map +1 -1
- package/lib/components/DatePicker/DatePicker.js +1 -1
- package/lib/components/DatePicker/DatePicker.js.map +1 -1
- package/lib/components/Dialog/FocusTrap.cjs +8 -8
- package/lib/components/Dialog/FocusTrap.cjs.map +1 -1
- package/lib/components/Dialog/FocusTrap.js +9 -9
- package/lib/components/Dialog/FocusTrap.js.map +1 -1
- package/lib/components/Dialog/ModelessDialog/ModelessDialog.cjs +2 -1
- package/lib/components/Dialog/ModelessDialog/ModelessDialog.cjs.map +1 -1
- package/lib/components/Dialog/ModelessDialog/ModelessDialog.js +2 -1
- package/lib/components/Dialog/ModelessDialog/ModelessDialog.js.map +1 -1
- package/lib/components/Input/CurrencyInput/CurrencyInput.cjs +2 -2
- package/lib/components/Input/CurrencyInput/CurrencyInput.cjs.map +1 -1
- package/lib/components/Input/CurrencyInput/CurrencyInput.js +2 -2
- package/lib/components/Input/CurrencyInput/CurrencyInput.js.map +1 -1
- package/lib/components/Input/Input.cjs +14 -16
- package/lib/components/Input/Input.cjs.map +1 -1
- package/lib/components/Input/Input.js +14 -16
- package/lib/components/Input/Input.js.map +1 -1
- package/lib/components/InputFile/InputFileMultiplyAppendable.cjs +8 -7
- package/lib/components/InputFile/InputFileMultiplyAppendable.cjs.map +1 -1
- package/lib/components/InputFile/InputFileMultiplyAppendable.js +8 -7
- package/lib/components/InputFile/InputFileMultiplyAppendable.js.map +1 -1
- package/lib/components/InputFile/InputFileNative.cjs +6 -5
- package/lib/components/InputFile/InputFileNative.cjs.map +1 -1
- package/lib/components/InputFile/InputFileNative.js +6 -5
- package/lib/components/InputFile/InputFileNative.js.map +1 -1
- package/lib/components/Layout/Container/Container.cjs.map +1 -1
- package/lib/components/Layout/Container/Container.js.map +1 -1
- package/lib/components/Pagination/Pagination.cjs +3 -2
- package/lib/components/Pagination/Pagination.cjs.map +1 -1
- package/lib/components/Pagination/Pagination.js +2 -1
- package/lib/components/Pagination/Pagination.js.map +1 -1
- package/lib/components/Panel/Groupbox/Groupbox.cjs +1 -0
- package/lib/components/Panel/Groupbox/Groupbox.cjs.map +1 -1
- package/lib/components/Panel/Groupbox/Groupbox.js +1 -0
- package/lib/components/Panel/Groupbox/Groupbox.js.map +1 -1
- package/lib/components/Select/Select.cjs +12 -14
- package/lib/components/Select/Select.cjs.map +1 -1
- package/lib/components/Select/Select.js +12 -14
- package/lib/components/Select/Select.js.map +1 -1
- package/lib/components/Table/TableScroller.cjs +13 -15
- package/lib/components/Table/TableScroller.cjs.map +1 -1
- package/lib/components/Table/TableScroller.js +14 -16
- package/lib/components/Table/TableScroller.js.map +1 -1
- package/lib/components/Textarea/Textarea.cjs +18 -12
- package/lib/components/Textarea/Textarea.cjs.map +1 -1
- package/lib/components/Textarea/Textarea.js +19 -13
- package/lib/components/Textarea/Textarea.js.map +1 -1
- package/lib/components/Tooltip/TooltipPortal.cjs +1 -0
- package/lib/components/Tooltip/TooltipPortal.cjs.map +1 -1
- package/lib/components/Tooltip/TooltipPortal.js +1 -0
- package/lib/components/Tooltip/TooltipPortal.js.map +1 -1
- package/lib/hooks/useClick.cjs +7 -4
- package/lib/hooks/useClick.cjs.map +1 -1
- package/lib/hooks/useClick.js +7 -4
- package/lib/hooks/useClick.js.map +1 -1
- package/lib/hooks/useOuterClick.cjs +5 -6
- package/lib/hooks/useOuterClick.cjs.map +1 -1
- package/lib/hooks/useOuterClick.js +6 -7
- package/lib/hooks/useOuterClick.js.map +1 -1
- package/lib/hooks/usePortal.cjs +24 -17
- package/lib/hooks/usePortal.cjs.map +1 -1
- package/lib/hooks/usePortal.d.ts +1 -1
- package/lib/hooks/usePortal.js +25 -18
- package/lib/hooks/usePortal.js.map +1 -1
- package/lib/hooks/useResponseStatus.cjs +20 -23
- package/lib/hooks/useResponseStatus.cjs.map +1 -1
- package/lib/hooks/useResponseStatus.js +20 -23
- package/lib/hooks/useResponseStatus.js.map +1 -1
- package/lib/intl/locales/en_us.json.cjs +1 -0
- package/lib/intl/locales/en_us.json.cjs.map +1 -1
- package/lib/intl/locales/en_us.json.js +1 -0
- package/lib/intl/locales/en_us.json.js.map +1 -1
- package/lib/intl/locales/id_id.json.cjs +0 -8
- package/lib/intl/locales/id_id.json.cjs.map +1 -1
- package/lib/intl/locales/id_id.json.js +0 -8
- package/lib/intl/locales/id_id.json.js.map +1 -1
- package/lib/intl/locales/index.d.ts +6 -16
- package/lib/intl/locales/ja_easy.json.cjs +1 -0
- package/lib/intl/locales/ja_easy.json.cjs.map +1 -1
- package/lib/intl/locales/ja_easy.json.js +1 -0
- package/lib/intl/locales/ja_easy.json.js.map +1 -1
- package/lib/intl/locales/ko_kr.json.cjs +1 -0
- package/lib/intl/locales/ko_kr.json.cjs.map +1 -1
- package/lib/intl/locales/ko_kr.json.js +1 -0
- package/lib/intl/locales/ko_kr.json.js.map +1 -1
- package/lib/intl/locales/pt_br.json.cjs +0 -8
- package/lib/intl/locales/pt_br.json.cjs.map +1 -1
- package/lib/intl/locales/pt_br.json.js +0 -8
- package/lib/intl/locales/pt_br.json.js.map +1 -1
- package/lib/intl/locales/vi_vn.json.cjs +1 -0
- package/lib/intl/locales/vi_vn.json.cjs.map +1 -1
- package/lib/intl/locales/vi_vn.json.js +1 -0
- package/lib/intl/locales/vi_vn.json.js.map +1 -1
- package/lib/intl/locales/zh_hans_cn.json.cjs +1 -0
- package/lib/intl/locales/zh_hans_cn.json.cjs.map +1 -1
- package/lib/intl/locales/zh_hans_cn.json.js +1 -0
- package/lib/intl/locales/zh_hans_cn.json.js.map +1 -1
- package/lib/intl/locales/zh_hant_tw.json.cjs +1 -0
- package/lib/intl/locales/zh_hant_tw.json.cjs.map +1 -1
- package/lib/intl/locales/zh_hant_tw.json.js +1 -0
- package/lib/intl/locales/zh_hant_tw.json.js.map +1 -1
- package/lib/intl/useDateFormat.cjs +1 -2
- package/lib/intl/useDateFormat.cjs.map +1 -1
- package/lib/intl/useDateFormat.js +1 -2
- package/lib/intl/useDateFormat.js.map +1 -1
- package/lib/intl/useIntl.cjs +2 -4
- package/lib/intl/useIntl.cjs.map +1 -1
- package/lib/intl/useIntl.js +2 -4
- package/lib/intl/useIntl.js.map +1 -1
- package/lib/libs/debounce.cjs +10 -2
- package/lib/libs/debounce.cjs.map +1 -1
- package/lib/libs/debounce.d.ts +4 -2
- package/lib/libs/debounce.js +10 -2
- package/lib/libs/debounce.js.map +1 -1
- package/lib/libs/lodash.cjs +3 -4
- package/lib/libs/lodash.cjs.map +1 -1
- package/lib/libs/lodash.d.ts +2 -11
- package/lib/libs/lodash.js +2 -7
- package/lib/libs/lodash.js.map +1 -1
- package/lib/libs/map.cjs +1 -5
- package/lib/libs/map.cjs.map +1 -1
- package/lib/libs/map.js +1 -5
- package/lib/libs/map.js.map +1 -1
- package/lib/themes/createBackgroundColor.cjs +3 -2
- package/lib/themes/createBackgroundColor.cjs.map +1 -1
- package/lib/themes/createBackgroundColor.js +2 -1
- package/lib/themes/createBackgroundColor.js.map +1 -1
- package/lib/themes/createBorder.cjs +3 -2
- package/lib/themes/createBorder.cjs.map +1 -1
- package/lib/themes/createBorder.js +2 -1
- package/lib/themes/createBorder.js.map +1 -1
- package/lib/themes/createBreakpoint.cjs +3 -2
- package/lib/themes/createBreakpoint.cjs.map +1 -1
- package/lib/themes/createBreakpoint.js +2 -1
- package/lib/themes/createBreakpoint.js.map +1 -1
- package/lib/themes/createColor.cjs +3 -2
- package/lib/themes/createColor.cjs.map +1 -1
- package/lib/themes/createColor.js +2 -1
- package/lib/themes/createColor.js.map +1 -1
- package/lib/themes/createFontSize.cjs +3 -2
- package/lib/themes/createFontSize.cjs.map +1 -1
- package/lib/themes/createFontSize.js +2 -1
- package/lib/themes/createFontSize.js.map +1 -1
- package/lib/themes/createInteraction.cjs +3 -2
- package/lib/themes/createInteraction.cjs.map +1 -1
- package/lib/themes/createInteraction.js +2 -1
- package/lib/themes/createInteraction.js.map +1 -1
- package/lib/themes/createLeading.cjs +3 -2
- package/lib/themes/createLeading.cjs.map +1 -1
- package/lib/themes/createLeading.js +2 -1
- package/lib/themes/createLeading.js.map +1 -1
- package/lib/themes/createRadius.cjs +3 -2
- package/lib/themes/createRadius.cjs.map +1 -1
- package/lib/themes/createRadius.js +2 -1
- package/lib/themes/createRadius.js.map +1 -1
- package/lib/themes/createShadow/createShadow.cjs +3 -2
- package/lib/themes/createShadow/createShadow.cjs.map +1 -1
- package/lib/themes/createShadow/createShadow.js +2 -1
- package/lib/themes/createShadow/createShadow.js.map +1 -1
- package/lib/themes/createTextColor.cjs +3 -2
- package/lib/themes/createTextColor.cjs.map +1 -1
- package/lib/themes/createTextColor.js +2 -1
- package/lib/themes/createTextColor.js.map +1 -1
- package/lib/themes/createZIndex.cjs +3 -2
- package/lib/themes/createZIndex.cjs.map +1 -1
- package/lib/themes/createZIndex.js +2 -1
- package/lib/themes/createZIndex.js.map +1 -1
- package/metadata.json +1 -1
- package/package.json +1 -1
- package/smarthr-ui.css +27 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DatePicker.cjs","sources":["../../../src/components/DatePicker/DatePicker.tsx"],"sourcesContent":["'use client'\n\nimport dayjs from 'dayjs'\nimport {\n type ChangeEvent,\n type ComponentProps,\n type ComponentPropsWithRef,\n type MouseEvent,\n type ReactNode,\n forwardRef,\n memo,\n useEffect,\n useId,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n} from 'react'\nimport { tv } from 'tailwind-variants'\n\nimport { useLatest } from '../../hooks/useLatest'\nimport { useOuterClick } from '../../hooks/useOuterClick'\nimport { useTheme } from '../../hooks/useTheme'\nimport { Calendar } from '../Calendar'\nimport { FaCalendarDaysIcon } from '../Icon'\nimport { Input } from '../Input'\n\nimport { Portal } from './Portal'\nimport { parseJpnDateString } from './datePickerHelper'\n\ntype ChangeLikeEvent = ChangeEvent | React.KeyboardEvent | MouseEvent\ntype BaseProps = {\n /** input 要素の `value` 属性の値 */\n value?: string | null\n /** input 要素の `name` 属性の値 */\n name?: string\n /** 選択可能な期間の開始日 */\n from?: Date\n /** 選択可能な期間の終了日 */\n to?: Date\n /** フォームを無効にするかどうか */\n disabled?: boolean\n /**\n * placeholder属性は非推奨です。別途ヒント用要素を設置するか、それらの領域を確保出来ない場合はTooltipコンポーネントの利用を検討してください。\n */\n placeholder?: string\n /** フォームにエラーがあるかどうか */\n error?: boolean\n /** コンポーネントの幅 */\n width?: number | string\n /** 入力を独自にパースする場合に、パース処理を記述する関数 */\n parseInput?: (input: string) => Date | null\n /** 表示する日付を独自にフォーマットする場合に、フォーマット処理を記述する関数 */\n formatDate?: (date: Date | null) => string\n /** 入出力用文字列と併記する別フォーマット処理を記述する関数 */\n showAlternative?: (date: Date | null) => ReactNode\n /** @deprecated onChangeDate は非推奨です。onChange を使ってください。 */\n onChangeDate?: (date: Date | null, value: string, other: { errors: string[] }) => void\n /** 選択された日付が変わった時に発火するコールバック関数 */\n onChange?: (\n e: ChangeEvent<HTMLInputElement>,\n other: { date: Date | null; formatValue: string; errors: string[] },\n ) => void\n}\ntype Props = BaseProps &\n Omit<\n ComponentPropsWithRef<'input'>,\n | keyof BaseProps\n | 'type'\n | 'onChange'\n | 'onKeyPress'\n | 'onFocus'\n | 'aria-expanded'\n | 'aria-controls'\n | 'aria-haspopup'\n >\n\nexport const DEFAULT_FROM = new Date(1900, 0, 1)\n\nconst classNameGenerator = tv({\n slots: {\n container: 'smarthr-ui-DatePicker shr-inline-block',\n inputSuffixLayout: 'shr-box-border shr-h-full shr-py-0.5',\n inputSuffixWrapper:\n 'shr-border-l-shorthand shr-box-border shr-flex shr-h-full shr-items-center shr-justify-center shr-ps-0.5 shr-text-base',\n inputSuffixText: 'shr-text-gray shr-me-0.5 shr-text-sm',\n },\n})\n\nconst DEFAULT_DATE_TO_STRING_FORMAT = 'YYYY/MM/DD'\nconst DEFAULT_DATE_TO_STRING = (d: Date | null) =>\n d ? dayjs(d).format(DEFAULT_DATE_TO_STRING_FORMAT) : ''\nconst ESCAPE_KEY_REGEX = /^Esc(ape)?$/\n\nconst parseStringDate = (\n str: string | null | undefined,\n parseInputFn: ((input: string) => Date | null) | undefined,\n) => {\n if (!str) return null\n return parseInputFn ? parseInputFn(str) : parseJpnDateString(str)\n}\n\n/** @deprecated DatePicker は非推奨です。Input[type=date] を使ってください。 */\nexport const DatePicker = forwardRef<HTMLInputElement, Props>(\n (\n {\n value,\n name,\n from = DEFAULT_FROM,\n to,\n disabled,\n width,\n error,\n className,\n parseInput,\n formatDate,\n showAlternative,\n onChangeDate,\n onChange,\n onBlur,\n ...rest\n },\n ref,\n ) => {\n const theme = useTheme()\n const classNames = useMemo(() => {\n const { container, inputSuffixLayout, inputSuffixWrapper, inputSuffixText } =\n classNameGenerator()\n\n return {\n container: container({ className }),\n inputSuffixLayout: inputSuffixLayout(),\n inputSuffixWrapper: inputSuffixWrapper(),\n inputSuffixText: inputSuffixText(),\n }\n }, [className])\n\n const [isInputFocused, setIsInputFocused] = useState(false)\n const inputRef = useRef<HTMLInputElement>(null)\n const inputWrapperRef = useRef<HTMLDivElement>(null)\n const calendarPortalRef = useRef<HTMLDivElement>(null)\n const [inputRect, setInputRect] = useState<DOMRect | null>(null)\n const [isCalendarShown, setIsCalendarShown] = useState(false)\n const [alternativeFormat, setAlternativeFormat] = useState<null | ReactNode>(null)\n const calenderId = useId()\n\n const [selectedDate, setSelectedDate] = useState<Date | null>(() =>\n parseStringDate(value, parseInput),\n )\n\n const latest = useLatest({\n onChange,\n onChangeDate,\n parseInput,\n formatDate,\n showAlternative,\n onBlur,\n isInputFocused,\n selectedDate,\n })\n\n const functions = useMemo(() => {\n const dateToString = (date: Date | null) =>\n latest.formatDate ? latest.formatDate(date) : DEFAULT_DATE_TO_STRING(date)\n\n const dateToAlternativeFormat = (d: Date | null) => {\n if (!latest.showAlternative) return null\n return d ? latest.showAlternative(d) : null\n }\n\n const stringToDate = (str: string | null | undefined) =>\n parseStringDate(str, latest.parseInput)\n\n const updateDate = (e: ChangeLikeEvent, newDate: Date | null) => {\n if (\n !inputRef.current ||\n newDate === latest.selectedDate ||\n (newDate && latest.selectedDate && newDate.getTime() === latest.selectedDate.getTime())\n ) {\n // Do not update date if the new date is same with the old one.\n return\n }\n\n const isValid = !newDate || dayjs(newDate).isValid()\n const errors: string[] = []\n\n if (!isValid) {\n errors.push('INVALID_DATE')\n }\n\n const nextDate = isValid ? newDate : null\n const formatValue = dateToString(nextDate)\n\n inputRef.current.value = formatValue\n setAlternativeFormat(dateToAlternativeFormat(nextDate))\n setSelectedDate(nextDate)\n\n if (latest.onChange) {\n e.preventDefault()\n e.stopPropagation()\n\n const event = new Event('change', { bubbles: true })\n const input = inputRef.current\n\n input.dispatchEvent(event)\n latest.onChange(\n // HINT: 型問題のため別途オブジェクトをイベントに見立てる\n {\n stopPropagation: () => {\n event.stopPropagation()\n },\n preventDefault: () => {\n event.preventDefault()\n },\n target: input,\n currentTarget: input,\n } as ChangeEvent<HTMLInputElement>,\n { date: nextDate, formatValue, errors },\n )\n } else if (latest.onChangeDate) {\n latest.onChangeDate(nextDate, formatValue, { errors })\n }\n }\n\n const closeCalendar = () => setIsCalendarShown(false)\n\n const openCalendar = () => {\n if (inputWrapperRef.current) {\n setIsCalendarShown(true)\n setInputRect(inputWrapperRef.current.getBoundingClientRect())\n }\n }\n\n return {\n stringToDate,\n dateToString,\n dateToAlternativeFormat,\n closeCalendar,\n openCalendar,\n handleBlur: (e: React.FocusEvent<HTMLInputElement>) => {\n setIsInputFocused(false)\n updateDate(e, e.target.value ? stringToDate(e.target.value) : null)\n latest.onBlur?.(e)\n },\n handleDelegateKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => {\n if (ESCAPE_KEY_REGEX.test(e.key)) {\n e.stopPropagation()\n // delay hiding calendar because calendar will be displayed when input is focused\n requestAnimationFrame(closeCalendar)\n\n if (inputRef.current) inputRef.current.focus()\n }\n },\n handleKeyPressInput: (e: React.KeyboardEvent<HTMLInputElement>) => {\n if (e.key === 'Enter') {\n const isExpanded = e.currentTarget.getAttribute('aria-expanded') === 'true'\n ;(isExpanded ? closeCalendar : openCalendar)()\n updateDate(e, stringToDate(e.currentTarget.value))\n }\n },\n handleFocusInput: () => {\n setIsInputFocused(true)\n openCalendar()\n },\n handleSelectDateCalendar: (e: ChangeLikeEvent, selected: Date | null) => {\n updateDate(e, selected)\n // delay hiding calendar because calendar will be displayed when input is focused\n requestAnimationFrame(closeCalendar)\n\n if (inputRef.current) inputRef.current.focus()\n },\n }\n }, [latest])\n\n useImperativeHandle<HTMLInputElement | null, HTMLInputElement | null>(\n ref,\n () => inputRef.current,\n [],\n )\n\n useEffect(() => {\n if (value === undefined || !inputRef.current) {\n return\n }\n\n /**\n * Do not format the given value in the following cases\n * - while input element is focused.\n * - if the given value is not date formattable.\n */\n if (!isInputFocused) {\n const newDate = functions.stringToDate(value)\n\n if (newDate && dayjs(newDate).isValid()) {\n inputRef.current.value = functions.dateToString(newDate)\n setAlternativeFormat(functions.dateToAlternativeFormat(newDate))\n setSelectedDate(newDate)\n\n return\n }\n\n setSelectedDate(null)\n }\n\n inputRef.current.value = value || ''\n }, [value, isInputFocused, functions])\n\n useOuterClick(\n useMemo(() => [inputWrapperRef, calendarPortalRef], [inputWrapperRef, calendarPortalRef]),\n functions.closeCalendar,\n )\n\n useEffect(() => {\n const handleKeyDown = (e: KeyboardEvent) => {\n if (!inputRef.current || !calendarPortalRef.current || e.key !== 'Tab') {\n return\n }\n\n const calendarButtons = calendarPortalRef.current.querySelectorAll('button')\n\n if (calendarButtons.length === 0) {\n return\n }\n\n const firstCalendarButton = calendarButtons[0]\n\n if (latest.isInputFocused) {\n if (e.shiftKey) {\n // move focus from Input to previous elements of DatePicker\n functions.closeCalendar()\n\n return\n }\n\n // move focus from Input to Calendar\n e.preventDefault()\n firstCalendarButton.focus()\n\n return\n }\n\n const calendarButtonAry = Array.from(calendarButtons)\n const currentFocused = calendarButtonAry.find((button) => button === e.target)\n\n if (e.shiftKey) {\n if (currentFocused === firstCalendarButton) {\n // move focus from Calendar to Input\n inputRef.current.focus()\n e.preventDefault()\n }\n } else if (currentFocused === calendarButtonAry.at(-1)) {\n // move focus from Calendar to next elements of DatePicker\n inputRef.current.focus()\n functions.closeCalendar()\n }\n }\n\n window.addEventListener('keydown', handleKeyDown)\n\n return () => {\n window.removeEventListener('keydown', handleKeyDown)\n }\n }, [functions, latest])\n\n const caretIconColor =\n isInputFocused || isCalendarShown\n ? theme.textColor.black\n : disabled\n ? theme.textColor.disabled\n : theme.textColor.grey\n\n return (\n // eslint-disable-next-line smarthr/best-practice-for-interactive-element\n <div\n onClick={!isCalendarShown && !disabled ? functions.openCalendar : undefined}\n onKeyDown={isCalendarShown ? functions.handleDelegateKeyDown : undefined}\n role=\"presentation\"\n className={classNames.container}\n style={{\n width: typeof width === 'number' ? `${width}px` : width,\n }}\n >\n <div ref={inputWrapperRef}>\n <Input\n {...rest}\n data-smarthr-ui-input=\"true\"\n width=\"100%\"\n name={name}\n onChange={isCalendarShown ? functions.closeCalendar : undefined}\n onKeyPress={functions.handleKeyPressInput}\n onFocus={functions.handleFocusInput}\n onBlur={functions.handleBlur}\n suffix={\n <InputSuffixIcon\n alternativeFormat={showAlternative ? alternativeFormat : null}\n caretIconColor={caretIconColor}\n classNames={classNames}\n />\n }\n disabled={disabled}\n error={error}\n ref={inputRef}\n className=\"smarthr-ui-DatePicker-inputContainer\"\n aria-expanded={isCalendarShown}\n aria-controls={calenderId}\n aria-haspopup={true}\n />\n </div>\n {isCalendarShown && inputRect && (\n <Portal inputRect={inputRect} ref={calendarPortalRef}>\n <Calendar\n id={calenderId}\n value={selectedDate || undefined}\n from={from}\n to={to}\n onSelectDate={functions.handleSelectDateCalendar}\n />\n </Portal>\n )}\n </div>\n )\n },\n)\n\nconst InputSuffixIcon = memo<{\n classNames: { inputSuffixLayout: string; inputSuffixWrapper: string; inputSuffixText: string }\n alternativeFormat: null | ReactNode\n caretIconColor: ComponentProps<typeof FaCalendarDaysIcon>['color']\n}>(({ classNames, alternativeFormat, caretIconColor }) => (\n <span className={classNames.inputSuffixLayout}>\n <span className={classNames.inputSuffixWrapper}>\n {alternativeFormat && <span className={classNames.inputSuffixText}>{alternativeFormat}</span>}\n <FaCalendarDaysIcon color={caretIconColor} />\n </span>\n </span>\n))\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AA6EO;AAEP;AACE;AACE;AACA;AACA;AAEA;AACD;AACF;AAED;AACA;AAEA;AAEA;AAIE;AAAU;AACV;AACF;AAEA;;AAsBI;AACA;AACE;;AAIE;;;;;AAKJ;;AAGA;AACA;AACA;;;;AAIA;AAEA;;;;;;;;;;AAaC;AAED;;AAIE;;AAC+B;AAC7B;AACF;AAEA;AAGA;;;AAII;;;;AAMF;;;AAIE;;;AAIF;AAEA;AACA;;AAGA;;;AAIE;AACA;AAEA;AACA;;AAEE;;;;;;;AAOE;AACA;;;AAIC;;;AAGT;;;AAKE;;;;AAIF;;;;;;;AAQE;;;AAGE;;AAEF;;;;;;AAM0B;;;AAG1B;AACE;AACE;;AAEA;;;;;AAKF;;AAEF;AACE;;;;AAIsB;;;AAG5B;AAEA;;;;;AAWE;;;;AAIG;;;;;;;;;;;;;;;AAwBH;AACE;;;;AAMA;;;AAIA;AAEA;AACE;;;;;;;;;;;AAeF;AAEA;AACE;;AAEE;;;;;;AAKF;;;AAGJ;AAEA;AAEA;AACE;AACF;AACF;AAEA;AAEI;AACA;AACE;AACA;;;AAIJ;AAMI;AACD;AAyCP;AAGF;;;"}
|
|
1
|
+
{"version":3,"file":"DatePicker.cjs","sources":["../../../src/components/DatePicker/DatePicker.tsx"],"sourcesContent":["'use client'\n\nimport dayjs from 'dayjs'\nimport {\n type ChangeEvent,\n type ComponentProps,\n type ComponentPropsWithRef,\n type MouseEvent,\n type ReactNode,\n forwardRef,\n memo,\n useEffect,\n useId,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n} from 'react'\nimport { tv } from 'tailwind-variants'\n\nimport { useLatest } from '../../hooks/useLatest'\nimport { useOuterClick } from '../../hooks/useOuterClick'\nimport { useTheme } from '../../hooks/useTheme'\nimport { Calendar } from '../Calendar'\nimport { FaCalendarDaysIcon } from '../Icon'\nimport { Input } from '../Input'\n\nimport { Portal } from './Portal'\nimport { parseJpnDateString } from './datePickerHelper'\n\ntype ChangeLikeEvent = ChangeEvent | React.KeyboardEvent | MouseEvent\ntype BaseProps = {\n /** input 要素の `value` 属性の値 */\n value?: string | null\n /** input 要素の `name` 属性の値 */\n name?: string\n /** 選択可能な期間の開始日 */\n from?: Date\n /** 選択可能な期間の終了日 */\n to?: Date\n /** フォームを無効にするかどうか */\n disabled?: boolean\n /**\n * placeholder属性は非推奨です。別途ヒント用要素を設置するか、それらの領域を確保出来ない場合はTooltipコンポーネントの利用を検討してください。\n */\n placeholder?: string\n /** フォームにエラーがあるかどうか */\n error?: boolean\n /** コンポーネントの幅 */\n width?: number | string\n /** 入力を独自にパースする場合に、パース処理を記述する関数 */\n parseInput?: (input: string) => Date | null\n /** 表示する日付を独自にフォーマットする場合に、フォーマット処理を記述する関数 */\n formatDate?: (date: Date | null) => string\n /** 入出力用文字列と併記する別フォーマット処理を記述する関数 */\n showAlternative?: (date: Date | null) => ReactNode\n /** @deprecated onChangeDate は非推奨です。onChange を使ってください。 */\n onChangeDate?: (date: Date | null, value: string, other: { errors: string[] }) => void\n /** 選択された日付が変わった時に発火するコールバック関数 */\n onChange?: (\n e: ChangeEvent<HTMLInputElement>,\n other: { date: Date | null; formatValue: string; errors: string[] },\n ) => void\n}\ntype Props = BaseProps &\n Omit<\n ComponentPropsWithRef<'input'>,\n | keyof BaseProps\n | 'type'\n | 'onChange'\n | 'onKeyPress'\n | 'onFocus'\n | 'aria-expanded'\n | 'aria-controls'\n | 'aria-haspopup'\n >\n\nexport const DEFAULT_FROM = new Date(1900, 0, 1)\n\nconst classNameGenerator = tv({\n slots: {\n container: 'smarthr-ui-DatePicker shr-inline-block',\n inputSuffixLayout: 'shr-box-border shr-h-full shr-py-0.5',\n inputSuffixWrapper:\n 'shr-border-l-shorthand shr-box-border shr-flex shr-h-full shr-items-center shr-justify-center shr-ps-0.5 shr-text-base',\n inputSuffixText: 'shr-text-gray shr-me-0.5 shr-text-sm',\n },\n})\n\nconst DEFAULT_DATE_TO_STRING_FORMAT = 'YYYY/MM/DD'\nconst DEFAULT_DATE_TO_STRING = (d: Date | null) =>\n d ? dayjs(d).format(DEFAULT_DATE_TO_STRING_FORMAT) : ''\nconst ESCAPE_KEY_REGEX = /^Esc(ape)?$/\n\nconst parseStringDate = (\n str: string | null | undefined,\n parseInputFn: ((input: string) => Date | null) | undefined,\n) => {\n if (!str) return null\n return parseInputFn ? parseInputFn(str) : parseJpnDateString(str)\n}\n\n/** @deprecated DatePicker は非推奨です。Input[type=date] を使ってください。 */\nexport const DatePicker = forwardRef<HTMLInputElement, Props>(\n (\n {\n value,\n name,\n from = DEFAULT_FROM,\n to,\n disabled,\n width,\n error,\n className,\n parseInput,\n formatDate,\n showAlternative,\n onChangeDate,\n onChange,\n onBlur,\n ...rest\n },\n ref,\n ) => {\n const theme = useTheme()\n const classNames = useMemo(() => {\n const { container, inputSuffixLayout, inputSuffixWrapper, inputSuffixText } =\n classNameGenerator()\n\n return {\n container: container({ className }),\n inputSuffixLayout: inputSuffixLayout(),\n inputSuffixWrapper: inputSuffixWrapper(),\n inputSuffixText: inputSuffixText(),\n }\n }, [className])\n\n const [isInputFocused, setIsInputFocused] = useState(false)\n const inputRef = useRef<HTMLInputElement>(null)\n const inputWrapperRef = useRef<HTMLDivElement>(null)\n const calendarPortalRef = useRef<HTMLDivElement>(null)\n const [inputRect, setInputRect] = useState<DOMRect | null>(null)\n const [isCalendarShown, setIsCalendarShown] = useState(false)\n const [alternativeFormat, setAlternativeFormat] = useState<null | ReactNode>(null)\n const calenderId = useId()\n\n const [selectedDate, setSelectedDate] = useState<Date | null>(() =>\n parseStringDate(value, parseInput),\n )\n\n const latest = useLatest({\n onChange,\n onChangeDate,\n parseInput,\n formatDate,\n showAlternative,\n onBlur,\n isInputFocused,\n selectedDate,\n })\n\n const functions = useMemo(() => {\n const dateToString = (date: Date | null) =>\n latest.formatDate ? latest.formatDate(date) : DEFAULT_DATE_TO_STRING(date)\n\n const dateToAlternativeFormat = (d: Date | null) => {\n if (!latest.showAlternative) return null\n return d ? latest.showAlternative(d) : null\n }\n\n const stringToDate = (str: string | null | undefined) =>\n parseStringDate(str, latest.parseInput)\n\n const updateDate = (e: ChangeLikeEvent, newDate: Date | null) => {\n if (\n !inputRef.current ||\n newDate === latest.selectedDate ||\n (newDate && latest.selectedDate && newDate.getTime() === latest.selectedDate.getTime())\n ) {\n // Do not update date if the new date is same with the old one.\n return\n }\n\n const isValid = !newDate || dayjs(newDate).isValid()\n const errors: string[] = []\n\n if (!isValid) {\n errors.push('INVALID_DATE')\n }\n\n const nextDate = isValid ? newDate : null\n const formatValue = dateToString(nextDate)\n\n inputRef.current.value = formatValue\n setAlternativeFormat(dateToAlternativeFormat(nextDate))\n setSelectedDate(nextDate)\n\n if (latest.onChange) {\n e.preventDefault()\n e.stopPropagation()\n\n const event = new Event('change', { bubbles: true })\n const input = inputRef.current\n\n input.dispatchEvent(event)\n latest.onChange(\n // HINT: 型問題のため別途オブジェクトをイベントに見立てる\n {\n stopPropagation: () => {\n event.stopPropagation()\n },\n preventDefault: () => {\n event.preventDefault()\n },\n target: input,\n currentTarget: input,\n } as ChangeEvent<HTMLInputElement>,\n { date: nextDate, formatValue, errors },\n )\n } else if (latest.onChangeDate) {\n latest.onChangeDate(nextDate, formatValue, { errors })\n }\n }\n\n const closeCalendar = () => setIsCalendarShown(false)\n\n const openCalendar = () => {\n if (inputWrapperRef.current) {\n setIsCalendarShown(true)\n setInputRect(inputWrapperRef.current.getBoundingClientRect())\n }\n }\n\n return {\n stringToDate,\n dateToString,\n dateToAlternativeFormat,\n closeCalendar,\n openCalendar,\n handleBlur: (e: React.FocusEvent<HTMLInputElement>) => {\n setIsInputFocused(false)\n updateDate(e, e.target.value ? stringToDate(e.target.value) : null)\n latest.onBlur?.(e)\n },\n handleDelegateKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => {\n if (ESCAPE_KEY_REGEX.test(e.key)) {\n e.stopPropagation()\n // delay hiding calendar because calendar will be displayed when input is focused\n requestAnimationFrame(closeCalendar)\n\n if (inputRef.current) inputRef.current.focus()\n }\n },\n handleKeyPressInput: (e: React.KeyboardEvent<HTMLInputElement>) => {\n if (e.key === 'Enter') {\n const isExpanded = e.currentTarget.getAttribute('aria-expanded') === 'true'\n ;(isExpanded ? closeCalendar : openCalendar)()\n updateDate(e, stringToDate(e.currentTarget.value))\n }\n },\n handleFocusInput: () => {\n setIsInputFocused(true)\n openCalendar()\n },\n handleSelectDateCalendar: (e: ChangeLikeEvent, selected: Date | null) => {\n updateDate(e, selected)\n // delay hiding calendar because calendar will be displayed when input is focused\n requestAnimationFrame(closeCalendar)\n\n if (inputRef.current) inputRef.current.focus()\n },\n }\n }, [latest])\n\n useImperativeHandle<HTMLInputElement | null, HTMLInputElement | null>(\n ref,\n () => inputRef.current,\n [],\n )\n\n useEffect(() => {\n if (value === undefined || !inputRef.current) {\n return\n }\n\n /**\n * Do not format the given value in the following cases\n * - while input element is focused.\n * - if the given value is not date formattable.\n */\n if (!isInputFocused) {\n const newDate = functions.stringToDate(value)\n\n if (newDate && dayjs(newDate).isValid()) {\n inputRef.current.value = functions.dateToString(newDate)\n setAlternativeFormat(functions.dateToAlternativeFormat(newDate))\n setSelectedDate(newDate)\n\n return\n }\n\n setSelectedDate(null)\n }\n\n inputRef.current.value = value || ''\n }, [value, isInputFocused, functions])\n\n useOuterClick([inputWrapperRef, calendarPortalRef], functions.closeCalendar)\n\n useEffect(() => {\n const handleKeyDown = (e: KeyboardEvent) => {\n if (!inputRef.current || !calendarPortalRef.current || e.key !== 'Tab') {\n return\n }\n\n const calendarButtons = calendarPortalRef.current.querySelectorAll('button')\n\n if (calendarButtons.length === 0) {\n return\n }\n\n const firstCalendarButton = calendarButtons[0]\n\n if (latest.isInputFocused) {\n if (e.shiftKey) {\n // move focus from Input to previous elements of DatePicker\n functions.closeCalendar()\n\n return\n }\n\n // move focus from Input to Calendar\n e.preventDefault()\n firstCalendarButton.focus()\n\n return\n }\n\n const calendarButtonAry = Array.from(calendarButtons)\n const currentFocused = calendarButtonAry.find((button) => button === e.target)\n\n if (e.shiftKey) {\n if (currentFocused === firstCalendarButton) {\n // move focus from Calendar to Input\n inputRef.current.focus()\n e.preventDefault()\n }\n } else if (currentFocused === calendarButtonAry.at(-1)) {\n // move focus from Calendar to next elements of DatePicker\n inputRef.current.focus()\n functions.closeCalendar()\n }\n }\n\n window.addEventListener('keydown', handleKeyDown)\n\n return () => {\n window.removeEventListener('keydown', handleKeyDown)\n }\n }, [functions, latest])\n\n const caretIconColor =\n isInputFocused || isCalendarShown\n ? theme.textColor.black\n : disabled\n ? theme.textColor.disabled\n : theme.textColor.grey\n\n return (\n // eslint-disable-next-line smarthr/best-practice-for-interactive-element\n <div\n onClick={!isCalendarShown && !disabled ? functions.openCalendar : undefined}\n onKeyDown={isCalendarShown ? functions.handleDelegateKeyDown : undefined}\n role=\"presentation\"\n className={classNames.container}\n style={{\n width: typeof width === 'number' ? `${width}px` : width,\n }}\n >\n <div ref={inputWrapperRef}>\n <Input\n {...rest}\n data-smarthr-ui-input=\"true\"\n width=\"100%\"\n name={name}\n onChange={isCalendarShown ? functions.closeCalendar : undefined}\n onKeyPress={functions.handleKeyPressInput}\n onFocus={functions.handleFocusInput}\n onBlur={functions.handleBlur}\n suffix={\n <InputSuffixIcon\n alternativeFormat={showAlternative ? alternativeFormat : null}\n caretIconColor={caretIconColor}\n classNames={classNames}\n />\n }\n disabled={disabled}\n error={error}\n ref={inputRef}\n className=\"smarthr-ui-DatePicker-inputContainer\"\n aria-expanded={isCalendarShown}\n aria-controls={calenderId}\n aria-haspopup={true}\n />\n </div>\n {isCalendarShown && inputRect && (\n <Portal inputRect={inputRect} ref={calendarPortalRef}>\n <Calendar\n id={calenderId}\n value={selectedDate || undefined}\n from={from}\n to={to}\n onSelectDate={functions.handleSelectDateCalendar}\n />\n </Portal>\n )}\n </div>\n )\n },\n)\n\nconst InputSuffixIcon = memo<{\n classNames: { inputSuffixLayout: string; inputSuffixWrapper: string; inputSuffixText: string }\n alternativeFormat: null | ReactNode\n caretIconColor: ComponentProps<typeof FaCalendarDaysIcon>['color']\n}>(({ classNames, alternativeFormat, caretIconColor }) => (\n <span className={classNames.inputSuffixLayout}>\n <span className={classNames.inputSuffixWrapper}>\n {alternativeFormat && <span className={classNames.inputSuffixText}>{alternativeFormat}</span>}\n <FaCalendarDaysIcon color={caretIconColor} />\n </span>\n </span>\n))\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AA6EO;AAEP;AACE;AACE;AACA;AACA;AAEA;AACD;AACF;AAED;AACA;AAEA;AAEA;AAIE;AAAU;AACV;AACF;AAEA;;AAsBI;AACA;AACE;;AAIE;;;;;AAKJ;;AAGA;AACA;AACA;;;;AAIA;AAEA;;;;;;;;;;AAaC;AAED;;AAIE;;AAC+B;AAC7B;AACF;AAEA;AAGA;;;AAII;;;;AAMF;;;AAIE;;;AAIF;AAEA;AACA;;AAGA;;;AAIE;AACA;AAEA;AACA;;AAEE;;;;;;;AAOE;AACA;;;AAIC;;;AAGT;;;AAKE;;;;AAIF;;;;;;;AAQE;;;AAGE;;AAEF;;;;;;AAM0B;;;AAG1B;AACE;AACE;;AAEA;;;;;AAKF;;AAEF;AACE;;;;AAIsB;;;AAG5B;AAEA;;;;;AAWE;;;;AAIG;;;;;;;;;;;;;;;AAqBH;AACE;;;;AAMA;;;AAIA;AAEA;AACE;;;;;;;;;;;AAeF;AAEA;AACE;;AAEE;;;;;;AAKF;;;AAGJ;AAEA;AAEA;AACE;AACF;AACF;AAEA;AAEI;AACA;AACE;AACA;;;AAIJ;AAMI;AACD;AAyCP;AAGF;;;"}
|
|
@@ -181,7 +181,7 @@ const DatePicker = forwardRef(({ value, name, from = DEFAULT_FROM, to, disabled,
|
|
|
181
181
|
}
|
|
182
182
|
inputRef.current.value = value || '';
|
|
183
183
|
}, [value, isInputFocused, functions]);
|
|
184
|
-
useOuterClick(
|
|
184
|
+
useOuterClick([inputWrapperRef, calendarPortalRef], functions.closeCalendar);
|
|
185
185
|
useEffect(() => {
|
|
186
186
|
const handleKeyDown = (e) => {
|
|
187
187
|
if (!inputRef.current || !calendarPortalRef.current || e.key !== 'Tab') {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DatePicker.js","sources":["../../../src/components/DatePicker/DatePicker.tsx"],"sourcesContent":["'use client'\n\nimport dayjs from 'dayjs'\nimport {\n type ChangeEvent,\n type ComponentProps,\n type ComponentPropsWithRef,\n type MouseEvent,\n type ReactNode,\n forwardRef,\n memo,\n useEffect,\n useId,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n} from 'react'\nimport { tv } from 'tailwind-variants'\n\nimport { useLatest } from '../../hooks/useLatest'\nimport { useOuterClick } from '../../hooks/useOuterClick'\nimport { useTheme } from '../../hooks/useTheme'\nimport { Calendar } from '../Calendar'\nimport { FaCalendarDaysIcon } from '../Icon'\nimport { Input } from '../Input'\n\nimport { Portal } from './Portal'\nimport { parseJpnDateString } from './datePickerHelper'\n\ntype ChangeLikeEvent = ChangeEvent | React.KeyboardEvent | MouseEvent\ntype BaseProps = {\n /** input 要素の `value` 属性の値 */\n value?: string | null\n /** input 要素の `name` 属性の値 */\n name?: string\n /** 選択可能な期間の開始日 */\n from?: Date\n /** 選択可能な期間の終了日 */\n to?: Date\n /** フォームを無効にするかどうか */\n disabled?: boolean\n /**\n * placeholder属性は非推奨です。別途ヒント用要素を設置するか、それらの領域を確保出来ない場合はTooltipコンポーネントの利用を検討してください。\n */\n placeholder?: string\n /** フォームにエラーがあるかどうか */\n error?: boolean\n /** コンポーネントの幅 */\n width?: number | string\n /** 入力を独自にパースする場合に、パース処理を記述する関数 */\n parseInput?: (input: string) => Date | null\n /** 表示する日付を独自にフォーマットする場合に、フォーマット処理を記述する関数 */\n formatDate?: (date: Date | null) => string\n /** 入出力用文字列と併記する別フォーマット処理を記述する関数 */\n showAlternative?: (date: Date | null) => ReactNode\n /** @deprecated onChangeDate は非推奨です。onChange を使ってください。 */\n onChangeDate?: (date: Date | null, value: string, other: { errors: string[] }) => void\n /** 選択された日付が変わった時に発火するコールバック関数 */\n onChange?: (\n e: ChangeEvent<HTMLInputElement>,\n other: { date: Date | null; formatValue: string; errors: string[] },\n ) => void\n}\ntype Props = BaseProps &\n Omit<\n ComponentPropsWithRef<'input'>,\n | keyof BaseProps\n | 'type'\n | 'onChange'\n | 'onKeyPress'\n | 'onFocus'\n | 'aria-expanded'\n | 'aria-controls'\n | 'aria-haspopup'\n >\n\nexport const DEFAULT_FROM = new Date(1900, 0, 1)\n\nconst classNameGenerator = tv({\n slots: {\n container: 'smarthr-ui-DatePicker shr-inline-block',\n inputSuffixLayout: 'shr-box-border shr-h-full shr-py-0.5',\n inputSuffixWrapper:\n 'shr-border-l-shorthand shr-box-border shr-flex shr-h-full shr-items-center shr-justify-center shr-ps-0.5 shr-text-base',\n inputSuffixText: 'shr-text-gray shr-me-0.5 shr-text-sm',\n },\n})\n\nconst DEFAULT_DATE_TO_STRING_FORMAT = 'YYYY/MM/DD'\nconst DEFAULT_DATE_TO_STRING = (d: Date | null) =>\n d ? dayjs(d).format(DEFAULT_DATE_TO_STRING_FORMAT) : ''\nconst ESCAPE_KEY_REGEX = /^Esc(ape)?$/\n\nconst parseStringDate = (\n str: string | null | undefined,\n parseInputFn: ((input: string) => Date | null) | undefined,\n) => {\n if (!str) return null\n return parseInputFn ? parseInputFn(str) : parseJpnDateString(str)\n}\n\n/** @deprecated DatePicker は非推奨です。Input[type=date] を使ってください。 */\nexport const DatePicker = forwardRef<HTMLInputElement, Props>(\n (\n {\n value,\n name,\n from = DEFAULT_FROM,\n to,\n disabled,\n width,\n error,\n className,\n parseInput,\n formatDate,\n showAlternative,\n onChangeDate,\n onChange,\n onBlur,\n ...rest\n },\n ref,\n ) => {\n const theme = useTheme()\n const classNames = useMemo(() => {\n const { container, inputSuffixLayout, inputSuffixWrapper, inputSuffixText } =\n classNameGenerator()\n\n return {\n container: container({ className }),\n inputSuffixLayout: inputSuffixLayout(),\n inputSuffixWrapper: inputSuffixWrapper(),\n inputSuffixText: inputSuffixText(),\n }\n }, [className])\n\n const [isInputFocused, setIsInputFocused] = useState(false)\n const inputRef = useRef<HTMLInputElement>(null)\n const inputWrapperRef = useRef<HTMLDivElement>(null)\n const calendarPortalRef = useRef<HTMLDivElement>(null)\n const [inputRect, setInputRect] = useState<DOMRect | null>(null)\n const [isCalendarShown, setIsCalendarShown] = useState(false)\n const [alternativeFormat, setAlternativeFormat] = useState<null | ReactNode>(null)\n const calenderId = useId()\n\n const [selectedDate, setSelectedDate] = useState<Date | null>(() =>\n parseStringDate(value, parseInput),\n )\n\n const latest = useLatest({\n onChange,\n onChangeDate,\n parseInput,\n formatDate,\n showAlternative,\n onBlur,\n isInputFocused,\n selectedDate,\n })\n\n const functions = useMemo(() => {\n const dateToString = (date: Date | null) =>\n latest.formatDate ? latest.formatDate(date) : DEFAULT_DATE_TO_STRING(date)\n\n const dateToAlternativeFormat = (d: Date | null) => {\n if (!latest.showAlternative) return null\n return d ? latest.showAlternative(d) : null\n }\n\n const stringToDate = (str: string | null | undefined) =>\n parseStringDate(str, latest.parseInput)\n\n const updateDate = (e: ChangeLikeEvent, newDate: Date | null) => {\n if (\n !inputRef.current ||\n newDate === latest.selectedDate ||\n (newDate && latest.selectedDate && newDate.getTime() === latest.selectedDate.getTime())\n ) {\n // Do not update date if the new date is same with the old one.\n return\n }\n\n const isValid = !newDate || dayjs(newDate).isValid()\n const errors: string[] = []\n\n if (!isValid) {\n errors.push('INVALID_DATE')\n }\n\n const nextDate = isValid ? newDate : null\n const formatValue = dateToString(nextDate)\n\n inputRef.current.value = formatValue\n setAlternativeFormat(dateToAlternativeFormat(nextDate))\n setSelectedDate(nextDate)\n\n if (latest.onChange) {\n e.preventDefault()\n e.stopPropagation()\n\n const event = new Event('change', { bubbles: true })\n const input = inputRef.current\n\n input.dispatchEvent(event)\n latest.onChange(\n // HINT: 型問題のため別途オブジェクトをイベントに見立てる\n {\n stopPropagation: () => {\n event.stopPropagation()\n },\n preventDefault: () => {\n event.preventDefault()\n },\n target: input,\n currentTarget: input,\n } as ChangeEvent<HTMLInputElement>,\n { date: nextDate, formatValue, errors },\n )\n } else if (latest.onChangeDate) {\n latest.onChangeDate(nextDate, formatValue, { errors })\n }\n }\n\n const closeCalendar = () => setIsCalendarShown(false)\n\n const openCalendar = () => {\n if (inputWrapperRef.current) {\n setIsCalendarShown(true)\n setInputRect(inputWrapperRef.current.getBoundingClientRect())\n }\n }\n\n return {\n stringToDate,\n dateToString,\n dateToAlternativeFormat,\n closeCalendar,\n openCalendar,\n handleBlur: (e: React.FocusEvent<HTMLInputElement>) => {\n setIsInputFocused(false)\n updateDate(e, e.target.value ? stringToDate(e.target.value) : null)\n latest.onBlur?.(e)\n },\n handleDelegateKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => {\n if (ESCAPE_KEY_REGEX.test(e.key)) {\n e.stopPropagation()\n // delay hiding calendar because calendar will be displayed when input is focused\n requestAnimationFrame(closeCalendar)\n\n if (inputRef.current) inputRef.current.focus()\n }\n },\n handleKeyPressInput: (e: React.KeyboardEvent<HTMLInputElement>) => {\n if (e.key === 'Enter') {\n const isExpanded = e.currentTarget.getAttribute('aria-expanded') === 'true'\n ;(isExpanded ? closeCalendar : openCalendar)()\n updateDate(e, stringToDate(e.currentTarget.value))\n }\n },\n handleFocusInput: () => {\n setIsInputFocused(true)\n openCalendar()\n },\n handleSelectDateCalendar: (e: ChangeLikeEvent, selected: Date | null) => {\n updateDate(e, selected)\n // delay hiding calendar because calendar will be displayed when input is focused\n requestAnimationFrame(closeCalendar)\n\n if (inputRef.current) inputRef.current.focus()\n },\n }\n }, [latest])\n\n useImperativeHandle<HTMLInputElement | null, HTMLInputElement | null>(\n ref,\n () => inputRef.current,\n [],\n )\n\n useEffect(() => {\n if (value === undefined || !inputRef.current) {\n return\n }\n\n /**\n * Do not format the given value in the following cases\n * - while input element is focused.\n * - if the given value is not date formattable.\n */\n if (!isInputFocused) {\n const newDate = functions.stringToDate(value)\n\n if (newDate && dayjs(newDate).isValid()) {\n inputRef.current.value = functions.dateToString(newDate)\n setAlternativeFormat(functions.dateToAlternativeFormat(newDate))\n setSelectedDate(newDate)\n\n return\n }\n\n setSelectedDate(null)\n }\n\n inputRef.current.value = value || ''\n }, [value, isInputFocused, functions])\n\n useOuterClick(\n useMemo(() => [inputWrapperRef, calendarPortalRef], [inputWrapperRef, calendarPortalRef]),\n functions.closeCalendar,\n )\n\n useEffect(() => {\n const handleKeyDown = (e: KeyboardEvent) => {\n if (!inputRef.current || !calendarPortalRef.current || e.key !== 'Tab') {\n return\n }\n\n const calendarButtons = calendarPortalRef.current.querySelectorAll('button')\n\n if (calendarButtons.length === 0) {\n return\n }\n\n const firstCalendarButton = calendarButtons[0]\n\n if (latest.isInputFocused) {\n if (e.shiftKey) {\n // move focus from Input to previous elements of DatePicker\n functions.closeCalendar()\n\n return\n }\n\n // move focus from Input to Calendar\n e.preventDefault()\n firstCalendarButton.focus()\n\n return\n }\n\n const calendarButtonAry = Array.from(calendarButtons)\n const currentFocused = calendarButtonAry.find((button) => button === e.target)\n\n if (e.shiftKey) {\n if (currentFocused === firstCalendarButton) {\n // move focus from Calendar to Input\n inputRef.current.focus()\n e.preventDefault()\n }\n } else if (currentFocused === calendarButtonAry.at(-1)) {\n // move focus from Calendar to next elements of DatePicker\n inputRef.current.focus()\n functions.closeCalendar()\n }\n }\n\n window.addEventListener('keydown', handleKeyDown)\n\n return () => {\n window.removeEventListener('keydown', handleKeyDown)\n }\n }, [functions, latest])\n\n const caretIconColor =\n isInputFocused || isCalendarShown\n ? theme.textColor.black\n : disabled\n ? theme.textColor.disabled\n : theme.textColor.grey\n\n return (\n // eslint-disable-next-line smarthr/best-practice-for-interactive-element\n <div\n onClick={!isCalendarShown && !disabled ? functions.openCalendar : undefined}\n onKeyDown={isCalendarShown ? functions.handleDelegateKeyDown : undefined}\n role=\"presentation\"\n className={classNames.container}\n style={{\n width: typeof width === 'number' ? `${width}px` : width,\n }}\n >\n <div ref={inputWrapperRef}>\n <Input\n {...rest}\n data-smarthr-ui-input=\"true\"\n width=\"100%\"\n name={name}\n onChange={isCalendarShown ? functions.closeCalendar : undefined}\n onKeyPress={functions.handleKeyPressInput}\n onFocus={functions.handleFocusInput}\n onBlur={functions.handleBlur}\n suffix={\n <InputSuffixIcon\n alternativeFormat={showAlternative ? alternativeFormat : null}\n caretIconColor={caretIconColor}\n classNames={classNames}\n />\n }\n disabled={disabled}\n error={error}\n ref={inputRef}\n className=\"smarthr-ui-DatePicker-inputContainer\"\n aria-expanded={isCalendarShown}\n aria-controls={calenderId}\n aria-haspopup={true}\n />\n </div>\n {isCalendarShown && inputRect && (\n <Portal inputRect={inputRect} ref={calendarPortalRef}>\n <Calendar\n id={calenderId}\n value={selectedDate || undefined}\n from={from}\n to={to}\n onSelectDate={functions.handleSelectDateCalendar}\n />\n </Portal>\n )}\n </div>\n )\n },\n)\n\nconst InputSuffixIcon = memo<{\n classNames: { inputSuffixLayout: string; inputSuffixWrapper: string; inputSuffixText: string }\n alternativeFormat: null | ReactNode\n caretIconColor: ComponentProps<typeof FaCalendarDaysIcon>['color']\n}>(({ classNames, alternativeFormat, caretIconColor }) => (\n <span className={classNames.inputSuffixLayout}>\n <span className={classNames.inputSuffixWrapper}>\n {alternativeFormat && <span className={classNames.inputSuffixText}>{alternativeFormat}</span>}\n <FaCalendarDaysIcon color={caretIconColor} />\n </span>\n </span>\n))\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AA6EO;AAEP;AACE;AACE;AACA;AACA;AAEA;AACD;AACF;AAED;AACA;AAEA;AAEA;AAIE;AAAU;AACV;AACF;AAEA;;AAsBI;AACA;AACE;;AAIE;;;;;AAKJ;;AAGA;AACA;AACA;;;;AAIA;AAEA;;;;;;;;;;AAaC;AAED;;AAIE;;AAC+B;AAC7B;AACF;AAEA;AAGA;;;AAII;;;;AAMF;;;AAIE;;;AAIF;AAEA;AACA;;AAGA;;;AAIE;AACA;AAEA;AACA;;AAEE;;;;;;;AAOE;AACA;;;AAIC;;;AAGT;;;AAKE;;;;AAIF;;;;;;;AAQE;;;AAGE;;AAEF;;;;;;AAM0B;;;AAG1B;AACE;AACE;;AAEA;;;;;AAKF;;AAEF;AACE;;;;AAIsB;;;AAG5B;AAEA;;;;;AAWE;;;;AAIG;;;;;;;;;;;;;;;AAwBH;AACE;;;;AAMA;;;AAIA;AAEA;AACE;;;;;;;;;;;AAeF;AAEA;AACE;;AAEE;;;;;;AAKF;;;AAGJ;AAEA;AAEA;AACE;AACF;AACF;AAEA;AAEI;AACA;AACE;AACA;;;AAIJ;AAMI;AACD;AAyCP;AAGF;;"}
|
|
1
|
+
{"version":3,"file":"DatePicker.js","sources":["../../../src/components/DatePicker/DatePicker.tsx"],"sourcesContent":["'use client'\n\nimport dayjs from 'dayjs'\nimport {\n type ChangeEvent,\n type ComponentProps,\n type ComponentPropsWithRef,\n type MouseEvent,\n type ReactNode,\n forwardRef,\n memo,\n useEffect,\n useId,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n} from 'react'\nimport { tv } from 'tailwind-variants'\n\nimport { useLatest } from '../../hooks/useLatest'\nimport { useOuterClick } from '../../hooks/useOuterClick'\nimport { useTheme } from '../../hooks/useTheme'\nimport { Calendar } from '../Calendar'\nimport { FaCalendarDaysIcon } from '../Icon'\nimport { Input } from '../Input'\n\nimport { Portal } from './Portal'\nimport { parseJpnDateString } from './datePickerHelper'\n\ntype ChangeLikeEvent = ChangeEvent | React.KeyboardEvent | MouseEvent\ntype BaseProps = {\n /** input 要素の `value` 属性の値 */\n value?: string | null\n /** input 要素の `name` 属性の値 */\n name?: string\n /** 選択可能な期間の開始日 */\n from?: Date\n /** 選択可能な期間の終了日 */\n to?: Date\n /** フォームを無効にするかどうか */\n disabled?: boolean\n /**\n * placeholder属性は非推奨です。別途ヒント用要素を設置するか、それらの領域を確保出来ない場合はTooltipコンポーネントの利用を検討してください。\n */\n placeholder?: string\n /** フォームにエラーがあるかどうか */\n error?: boolean\n /** コンポーネントの幅 */\n width?: number | string\n /** 入力を独自にパースする場合に、パース処理を記述する関数 */\n parseInput?: (input: string) => Date | null\n /** 表示する日付を独自にフォーマットする場合に、フォーマット処理を記述する関数 */\n formatDate?: (date: Date | null) => string\n /** 入出力用文字列と併記する別フォーマット処理を記述する関数 */\n showAlternative?: (date: Date | null) => ReactNode\n /** @deprecated onChangeDate は非推奨です。onChange を使ってください。 */\n onChangeDate?: (date: Date | null, value: string, other: { errors: string[] }) => void\n /** 選択された日付が変わった時に発火するコールバック関数 */\n onChange?: (\n e: ChangeEvent<HTMLInputElement>,\n other: { date: Date | null; formatValue: string; errors: string[] },\n ) => void\n}\ntype Props = BaseProps &\n Omit<\n ComponentPropsWithRef<'input'>,\n | keyof BaseProps\n | 'type'\n | 'onChange'\n | 'onKeyPress'\n | 'onFocus'\n | 'aria-expanded'\n | 'aria-controls'\n | 'aria-haspopup'\n >\n\nexport const DEFAULT_FROM = new Date(1900, 0, 1)\n\nconst classNameGenerator = tv({\n slots: {\n container: 'smarthr-ui-DatePicker shr-inline-block',\n inputSuffixLayout: 'shr-box-border shr-h-full shr-py-0.5',\n inputSuffixWrapper:\n 'shr-border-l-shorthand shr-box-border shr-flex shr-h-full shr-items-center shr-justify-center shr-ps-0.5 shr-text-base',\n inputSuffixText: 'shr-text-gray shr-me-0.5 shr-text-sm',\n },\n})\n\nconst DEFAULT_DATE_TO_STRING_FORMAT = 'YYYY/MM/DD'\nconst DEFAULT_DATE_TO_STRING = (d: Date | null) =>\n d ? dayjs(d).format(DEFAULT_DATE_TO_STRING_FORMAT) : ''\nconst ESCAPE_KEY_REGEX = /^Esc(ape)?$/\n\nconst parseStringDate = (\n str: string | null | undefined,\n parseInputFn: ((input: string) => Date | null) | undefined,\n) => {\n if (!str) return null\n return parseInputFn ? parseInputFn(str) : parseJpnDateString(str)\n}\n\n/** @deprecated DatePicker は非推奨です。Input[type=date] を使ってください。 */\nexport const DatePicker = forwardRef<HTMLInputElement, Props>(\n (\n {\n value,\n name,\n from = DEFAULT_FROM,\n to,\n disabled,\n width,\n error,\n className,\n parseInput,\n formatDate,\n showAlternative,\n onChangeDate,\n onChange,\n onBlur,\n ...rest\n },\n ref,\n ) => {\n const theme = useTheme()\n const classNames = useMemo(() => {\n const { container, inputSuffixLayout, inputSuffixWrapper, inputSuffixText } =\n classNameGenerator()\n\n return {\n container: container({ className }),\n inputSuffixLayout: inputSuffixLayout(),\n inputSuffixWrapper: inputSuffixWrapper(),\n inputSuffixText: inputSuffixText(),\n }\n }, [className])\n\n const [isInputFocused, setIsInputFocused] = useState(false)\n const inputRef = useRef<HTMLInputElement>(null)\n const inputWrapperRef = useRef<HTMLDivElement>(null)\n const calendarPortalRef = useRef<HTMLDivElement>(null)\n const [inputRect, setInputRect] = useState<DOMRect | null>(null)\n const [isCalendarShown, setIsCalendarShown] = useState(false)\n const [alternativeFormat, setAlternativeFormat] = useState<null | ReactNode>(null)\n const calenderId = useId()\n\n const [selectedDate, setSelectedDate] = useState<Date | null>(() =>\n parseStringDate(value, parseInput),\n )\n\n const latest = useLatest({\n onChange,\n onChangeDate,\n parseInput,\n formatDate,\n showAlternative,\n onBlur,\n isInputFocused,\n selectedDate,\n })\n\n const functions = useMemo(() => {\n const dateToString = (date: Date | null) =>\n latest.formatDate ? latest.formatDate(date) : DEFAULT_DATE_TO_STRING(date)\n\n const dateToAlternativeFormat = (d: Date | null) => {\n if (!latest.showAlternative) return null\n return d ? latest.showAlternative(d) : null\n }\n\n const stringToDate = (str: string | null | undefined) =>\n parseStringDate(str, latest.parseInput)\n\n const updateDate = (e: ChangeLikeEvent, newDate: Date | null) => {\n if (\n !inputRef.current ||\n newDate === latest.selectedDate ||\n (newDate && latest.selectedDate && newDate.getTime() === latest.selectedDate.getTime())\n ) {\n // Do not update date if the new date is same with the old one.\n return\n }\n\n const isValid = !newDate || dayjs(newDate).isValid()\n const errors: string[] = []\n\n if (!isValid) {\n errors.push('INVALID_DATE')\n }\n\n const nextDate = isValid ? newDate : null\n const formatValue = dateToString(nextDate)\n\n inputRef.current.value = formatValue\n setAlternativeFormat(dateToAlternativeFormat(nextDate))\n setSelectedDate(nextDate)\n\n if (latest.onChange) {\n e.preventDefault()\n e.stopPropagation()\n\n const event = new Event('change', { bubbles: true })\n const input = inputRef.current\n\n input.dispatchEvent(event)\n latest.onChange(\n // HINT: 型問題のため別途オブジェクトをイベントに見立てる\n {\n stopPropagation: () => {\n event.stopPropagation()\n },\n preventDefault: () => {\n event.preventDefault()\n },\n target: input,\n currentTarget: input,\n } as ChangeEvent<HTMLInputElement>,\n { date: nextDate, formatValue, errors },\n )\n } else if (latest.onChangeDate) {\n latest.onChangeDate(nextDate, formatValue, { errors })\n }\n }\n\n const closeCalendar = () => setIsCalendarShown(false)\n\n const openCalendar = () => {\n if (inputWrapperRef.current) {\n setIsCalendarShown(true)\n setInputRect(inputWrapperRef.current.getBoundingClientRect())\n }\n }\n\n return {\n stringToDate,\n dateToString,\n dateToAlternativeFormat,\n closeCalendar,\n openCalendar,\n handleBlur: (e: React.FocusEvent<HTMLInputElement>) => {\n setIsInputFocused(false)\n updateDate(e, e.target.value ? stringToDate(e.target.value) : null)\n latest.onBlur?.(e)\n },\n handleDelegateKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => {\n if (ESCAPE_KEY_REGEX.test(e.key)) {\n e.stopPropagation()\n // delay hiding calendar because calendar will be displayed when input is focused\n requestAnimationFrame(closeCalendar)\n\n if (inputRef.current) inputRef.current.focus()\n }\n },\n handleKeyPressInput: (e: React.KeyboardEvent<HTMLInputElement>) => {\n if (e.key === 'Enter') {\n const isExpanded = e.currentTarget.getAttribute('aria-expanded') === 'true'\n ;(isExpanded ? closeCalendar : openCalendar)()\n updateDate(e, stringToDate(e.currentTarget.value))\n }\n },\n handleFocusInput: () => {\n setIsInputFocused(true)\n openCalendar()\n },\n handleSelectDateCalendar: (e: ChangeLikeEvent, selected: Date | null) => {\n updateDate(e, selected)\n // delay hiding calendar because calendar will be displayed when input is focused\n requestAnimationFrame(closeCalendar)\n\n if (inputRef.current) inputRef.current.focus()\n },\n }\n }, [latest])\n\n useImperativeHandle<HTMLInputElement | null, HTMLInputElement | null>(\n ref,\n () => inputRef.current,\n [],\n )\n\n useEffect(() => {\n if (value === undefined || !inputRef.current) {\n return\n }\n\n /**\n * Do not format the given value in the following cases\n * - while input element is focused.\n * - if the given value is not date formattable.\n */\n if (!isInputFocused) {\n const newDate = functions.stringToDate(value)\n\n if (newDate && dayjs(newDate).isValid()) {\n inputRef.current.value = functions.dateToString(newDate)\n setAlternativeFormat(functions.dateToAlternativeFormat(newDate))\n setSelectedDate(newDate)\n\n return\n }\n\n setSelectedDate(null)\n }\n\n inputRef.current.value = value || ''\n }, [value, isInputFocused, functions])\n\n useOuterClick([inputWrapperRef, calendarPortalRef], functions.closeCalendar)\n\n useEffect(() => {\n const handleKeyDown = (e: KeyboardEvent) => {\n if (!inputRef.current || !calendarPortalRef.current || e.key !== 'Tab') {\n return\n }\n\n const calendarButtons = calendarPortalRef.current.querySelectorAll('button')\n\n if (calendarButtons.length === 0) {\n return\n }\n\n const firstCalendarButton = calendarButtons[0]\n\n if (latest.isInputFocused) {\n if (e.shiftKey) {\n // move focus from Input to previous elements of DatePicker\n functions.closeCalendar()\n\n return\n }\n\n // move focus from Input to Calendar\n e.preventDefault()\n firstCalendarButton.focus()\n\n return\n }\n\n const calendarButtonAry = Array.from(calendarButtons)\n const currentFocused = calendarButtonAry.find((button) => button === e.target)\n\n if (e.shiftKey) {\n if (currentFocused === firstCalendarButton) {\n // move focus from Calendar to Input\n inputRef.current.focus()\n e.preventDefault()\n }\n } else if (currentFocused === calendarButtonAry.at(-1)) {\n // move focus from Calendar to next elements of DatePicker\n inputRef.current.focus()\n functions.closeCalendar()\n }\n }\n\n window.addEventListener('keydown', handleKeyDown)\n\n return () => {\n window.removeEventListener('keydown', handleKeyDown)\n }\n }, [functions, latest])\n\n const caretIconColor =\n isInputFocused || isCalendarShown\n ? theme.textColor.black\n : disabled\n ? theme.textColor.disabled\n : theme.textColor.grey\n\n return (\n // eslint-disable-next-line smarthr/best-practice-for-interactive-element\n <div\n onClick={!isCalendarShown && !disabled ? functions.openCalendar : undefined}\n onKeyDown={isCalendarShown ? functions.handleDelegateKeyDown : undefined}\n role=\"presentation\"\n className={classNames.container}\n style={{\n width: typeof width === 'number' ? `${width}px` : width,\n }}\n >\n <div ref={inputWrapperRef}>\n <Input\n {...rest}\n data-smarthr-ui-input=\"true\"\n width=\"100%\"\n name={name}\n onChange={isCalendarShown ? functions.closeCalendar : undefined}\n onKeyPress={functions.handleKeyPressInput}\n onFocus={functions.handleFocusInput}\n onBlur={functions.handleBlur}\n suffix={\n <InputSuffixIcon\n alternativeFormat={showAlternative ? alternativeFormat : null}\n caretIconColor={caretIconColor}\n classNames={classNames}\n />\n }\n disabled={disabled}\n error={error}\n ref={inputRef}\n className=\"smarthr-ui-DatePicker-inputContainer\"\n aria-expanded={isCalendarShown}\n aria-controls={calenderId}\n aria-haspopup={true}\n />\n </div>\n {isCalendarShown && inputRect && (\n <Portal inputRect={inputRect} ref={calendarPortalRef}>\n <Calendar\n id={calenderId}\n value={selectedDate || undefined}\n from={from}\n to={to}\n onSelectDate={functions.handleSelectDateCalendar}\n />\n </Portal>\n )}\n </div>\n )\n },\n)\n\nconst InputSuffixIcon = memo<{\n classNames: { inputSuffixLayout: string; inputSuffixWrapper: string; inputSuffixText: string }\n alternativeFormat: null | ReactNode\n caretIconColor: ComponentProps<typeof FaCalendarDaysIcon>['color']\n}>(({ classNames, alternativeFormat, caretIconColor }) => (\n <span className={classNames.inputSuffixLayout}>\n <span className={classNames.inputSuffixWrapper}>\n {alternativeFormat && <span className={classNames.inputSuffixText}>{alternativeFormat}</span>}\n <FaCalendarDaysIcon color={caretIconColor} />\n </span>\n </span>\n))\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AA6EO;AAEP;AACE;AACE;AACA;AACA;AAEA;AACD;AACF;AAED;AACA;AAEA;AAEA;AAIE;AAAU;AACV;AACF;AAEA;;AAsBI;AACA;AACE;;AAIE;;;;;AAKJ;;AAGA;AACA;AACA;;;;AAIA;AAEA;;;;;;;;;;AAaC;AAED;;AAIE;;AAC+B;AAC7B;AACF;AAEA;AAGA;;;AAII;;;;AAMF;;;AAIE;;;AAIF;AAEA;AACA;;AAGA;;;AAIE;AACA;AAEA;AACA;;AAEE;;;;;;;AAOE;AACA;;;AAIC;;;AAGT;;;AAKE;;;;AAIF;;;;;;;AAQE;;;AAGE;;AAEF;;;;;;AAM0B;;;AAG1B;AACE;AACE;;AAEA;;;;;AAKF;;AAEF;AACE;;;;AAIsB;;;AAG5B;AAEA;;;;;AAWE;;;;AAIG;;;;;;;;;;;;;;;AAqBH;AACE;;;;AAMA;;;AAIA;AAEA;AACE;;;;;;;;;;;AAeF;AAEA;AACE;;AAEE;;;;;;AAKF;;;AAGJ;AAEA;AAEA;AACE;AACF;AACF;AAEA;AAEI;AACA;AACE;AACA;;;AAIJ;AAMI;AACD;AAyCP;AAGF;;"}
|
|
@@ -7,16 +7,16 @@ var libs_tabbable = require('../../libs/tabbable.cjs');
|
|
|
7
7
|
const FocusTrap = React.forwardRef(({ firstFocusTarget, children }, ref) => {
|
|
8
8
|
const innerRef = React.useRef(null);
|
|
9
9
|
const dummyFocusRef = React.useRef(null);
|
|
10
|
-
const
|
|
11
|
-
(
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
10
|
+
const functions = React.useMemo(() => ({
|
|
11
|
+
focus: () => {
|
|
12
|
+
(firstFocusTarget?.current || dummyFocusRef.current)?.focus();
|
|
13
|
+
},
|
|
14
|
+
}), [firstFocusTarget]);
|
|
15
|
+
React.useImperativeHandle(ref, () => functions, [functions]);
|
|
16
16
|
React.useEffect(() => {
|
|
17
17
|
// FocusTrap がマウントされた時点のフォーカス要素を保存
|
|
18
18
|
const triggerElement = document.activeElement;
|
|
19
|
-
focus();
|
|
19
|
+
functions.focus();
|
|
20
20
|
const handleKeyDown = (e) => {
|
|
21
21
|
// IME 変換中の Tab は変換候補の選択に使われるため、フォーカストラップの対象外にする。
|
|
22
22
|
// ここで preventDefault してしまうと、Dialog 内で日本語入力中に Tab を押しても
|
|
@@ -50,7 +50,7 @@ const FocusTrap = React.forwardRef(({ firstFocusTarget, children }, ref) => {
|
|
|
50
50
|
triggerElement.focus();
|
|
51
51
|
}
|
|
52
52
|
};
|
|
53
|
-
}, [
|
|
53
|
+
}, [functions]);
|
|
54
54
|
return (jsxRuntime.jsxs("div", { ref: innerRef, children: [jsxRuntime.jsx("div", { ref: dummyFocusRef, tabIndex: -1 }), children] }));
|
|
55
55
|
});
|
|
56
56
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"FocusTrap.cjs","sources":["../../../src/components/Dialog/FocusTrap.tsx"],"sourcesContent":["import {\n type PropsWithChildren,\n type RefObject,\n forwardRef,\n
|
|
1
|
+
{"version":3,"file":"FocusTrap.cjs","sources":["../../../src/components/Dialog/FocusTrap.tsx"],"sourcesContent":["import {\n type PropsWithChildren,\n type RefObject,\n forwardRef,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n} from 'react'\n\nimport { tabbable } from '../../libs/tabbable'\n\ntype Props = PropsWithChildren<{\n firstFocusTarget?: RefObject<HTMLElement>\n}>\n\nexport type FocusTrapRef = {\n focus: () => void\n}\n\nexport const FocusTrap = forwardRef<FocusTrapRef, Props>(({ firstFocusTarget, children }, ref) => {\n const innerRef = useRef<HTMLDivElement | null>(null)\n const dummyFocusRef = useRef<HTMLDivElement>(null)\n\n const functions = useMemo(\n () => ({\n focus: () => {\n ;(firstFocusTarget?.current || dummyFocusRef.current)?.focus()\n },\n }),\n [firstFocusTarget],\n )\n\n useImperativeHandle(ref, () => functions, [functions])\n\n useEffect(() => {\n // FocusTrap がマウントされた時点のフォーカス要素を保存\n const triggerElement = document.activeElement\n\n functions.focus()\n\n const handleKeyDown = (e: KeyboardEvent) => {\n // IME 変換中の Tab は変換候補の選択に使われるため、フォーカストラップの対象外にする。\n // ここで preventDefault してしまうと、Dialog 内で日本語入力中に Tab を押しても\n // 変換候補が確定されず、未確定文字列がそのまま入力されてしまう。\n if (e.key !== 'Tab' || e.isComposing || innerRef.current === null) {\n return\n }\n\n const tabbables = tabbable(innerRef.current).filter((elm) => elm.tabIndex >= 0)\n\n if (tabbables.length === 0) {\n return\n }\n\n const firstTabbable = tabbables[0]\n const lastTabbable = tabbables[tabbables.length - 1]\n const currentFocused = tabbables.find((elm) => elm === e.target)\n\n if (e.shiftKey) {\n if (currentFocused === firstTabbable || document.activeElement === dummyFocusRef.current) {\n e.preventDefault()\n lastTabbable.focus()\n }\n } else if (currentFocused === lastTabbable) {\n e.preventDefault()\n firstTabbable.focus()\n }\n }\n\n window.addEventListener('keydown', handleKeyDown)\n\n return () => {\n window.removeEventListener('keydown', handleKeyDown)\n // フォーカストラップ終了時にトリガにフォーカスを戻す\n if (triggerElement instanceof HTMLElement) {\n triggerElement.focus()\n }\n }\n }, [functions])\n\n return (\n <div ref={innerRef}>\n {/* eslint-disable-next-line smarthr/a11y-scroller-has-tabindex -- dummy element for focus management. */}\n <div ref={dummyFocusRef} tabIndex={-1} />\n {children}\n </div>\n )\n})\n"],"names":["forwardRef","useRef","useMemo","useImperativeHandle","useEffect","tabbable","_jsxs","_jsx"],"mappings":";;;;;;AAoBO,MAAM,SAAS,GAAGA,gBAAU,CAAsB,CAAC,EAAE,gBAAgB,EAAE,QAAQ,EAAE,EAAE,GAAG,KAAI;AAC/F,IAAA,MAAM,QAAQ,GAAGC,YAAM,CAAwB,IAAI,CAAC;AACpD,IAAA,MAAM,aAAa,GAAGA,YAAM,CAAiB,IAAI,CAAC;AAElD,IAAA,MAAM,SAAS,GAAGC,aAAO,CACvB,OAAO;QACL,KAAK,EAAE,MAAK;YACT,CAAC,gBAAgB,EAAE,OAAO,IAAI,aAAa,CAAC,OAAO,GAAG,KAAK,EAAE;QAChE,CAAC;AACF,KAAA,CAAC,EACF,CAAC,gBAAgB,CAAC,CACnB;AAED,IAAAC,yBAAmB,CAAC,GAAG,EAAE,MAAM,SAAS,EAAE,CAAC,SAAS,CAAC,CAAC;IAEtDC,eAAS,CAAC,MAAK;;AAEb,QAAA,MAAM,cAAc,GAAG,QAAQ,CAAC,aAAa;QAE7C,SAAS,CAAC,KAAK,EAAE;AAEjB,QAAA,MAAM,aAAa,GAAG,CAAC,CAAgB,KAAI;;;;AAIzC,YAAA,IAAI,CAAC,CAAC,GAAG,KAAK,KAAK,IAAI,CAAC,CAAC,WAAW,IAAI,QAAQ,CAAC,OAAO,KAAK,IAAI,EAAE;gBACjE;YACF;YAEA,MAAM,SAAS,GAAGC,sBAAQ,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,GAAG,KAAK,GAAG,CAAC,QAAQ,IAAI,CAAC,CAAC;AAE/E,YAAA,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE;gBAC1B;YACF;AAEA,YAAA,MAAM,aAAa,GAAG,SAAS,CAAC,CAAC,CAAC;YAClC,MAAM,YAAY,GAAG,SAAS,CAAC,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC;AACpD,YAAA,MAAM,cAAc,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC,GAAG,KAAK,GAAG,KAAK,CAAC,CAAC,MAAM,CAAC;AAEhE,YAAA,IAAI,CAAC,CAAC,QAAQ,EAAE;AACd,gBAAA,IAAI,cAAc,KAAK,aAAa,IAAI,QAAQ,CAAC,aAAa,KAAK,aAAa,CAAC,OAAO,EAAE;oBACxF,CAAC,CAAC,cAAc,EAAE;oBAClB,YAAY,CAAC,KAAK,EAAE;gBACtB;YACF;AAAO,iBAAA,IAAI,cAAc,KAAK,YAAY,EAAE;gBAC1C,CAAC,CAAC,cAAc,EAAE;gBAClB,aAAa,CAAC,KAAK,EAAE;YACvB;AACF,QAAA,CAAC;AAED,QAAA,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,aAAa,CAAC;AAEjD,QAAA,OAAO,MAAK;AACV,YAAA,MAAM,CAAC,mBAAmB,CAAC,SAAS,EAAE,aAAa,CAAC;;AAEpD,YAAA,IAAI,cAAc,YAAY,WAAW,EAAE;gBACzC,cAAc,CAAC,KAAK,EAAE;YACxB;AACF,QAAA,CAAC;AACH,IAAA,CAAC,EAAE,CAAC,SAAS,CAAC,CAAC;IAEf,QACEC,yBAAK,GAAG,EAAE,QAAQ,EAAA,QAAA,EAAA,CAEhBC,cAAA,CAAA,KAAA,EAAA,EAAK,GAAG,EAAE,aAAa,EAAE,QAAQ,EAAE,EAAE,EAAA,CAAI,EACxC,QAAQ,CAAA,EAAA,CACL;AAEV,CAAC;;;;"}
|
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
import { jsxs, jsx } from 'react/jsx-runtime';
|
|
2
|
-
import { forwardRef, useRef,
|
|
2
|
+
import { forwardRef, useRef, useMemo, useImperativeHandle, useEffect } from 'react';
|
|
3
3
|
import { tabbable } from '../../libs/tabbable.js';
|
|
4
4
|
|
|
5
5
|
const FocusTrap = forwardRef(({ firstFocusTarget, children }, ref) => {
|
|
6
6
|
const innerRef = useRef(null);
|
|
7
7
|
const dummyFocusRef = useRef(null);
|
|
8
|
-
const
|
|
9
|
-
(
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
8
|
+
const functions = useMemo(() => ({
|
|
9
|
+
focus: () => {
|
|
10
|
+
(firstFocusTarget?.current || dummyFocusRef.current)?.focus();
|
|
11
|
+
},
|
|
12
|
+
}), [firstFocusTarget]);
|
|
13
|
+
useImperativeHandle(ref, () => functions, [functions]);
|
|
14
14
|
useEffect(() => {
|
|
15
15
|
// FocusTrap がマウントされた時点のフォーカス要素を保存
|
|
16
16
|
const triggerElement = document.activeElement;
|
|
17
|
-
focus();
|
|
17
|
+
functions.focus();
|
|
18
18
|
const handleKeyDown = (e) => {
|
|
19
19
|
// IME 変換中の Tab は変換候補の選択に使われるため、フォーカストラップの対象外にする。
|
|
20
20
|
// ここで preventDefault してしまうと、Dialog 内で日本語入力中に Tab を押しても
|
|
@@ -48,7 +48,7 @@ const FocusTrap = forwardRef(({ firstFocusTarget, children }, ref) => {
|
|
|
48
48
|
triggerElement.focus();
|
|
49
49
|
}
|
|
50
50
|
};
|
|
51
|
-
}, [
|
|
51
|
+
}, [functions]);
|
|
52
52
|
return (jsxs("div", { ref: innerRef, children: [jsx("div", { ref: dummyFocusRef, tabIndex: -1 }), children] }));
|
|
53
53
|
});
|
|
54
54
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"FocusTrap.js","sources":["../../../src/components/Dialog/FocusTrap.tsx"],"sourcesContent":["import {\n type PropsWithChildren,\n type RefObject,\n forwardRef,\n
|
|
1
|
+
{"version":3,"file":"FocusTrap.js","sources":["../../../src/components/Dialog/FocusTrap.tsx"],"sourcesContent":["import {\n type PropsWithChildren,\n type RefObject,\n forwardRef,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n} from 'react'\n\nimport { tabbable } from '../../libs/tabbable'\n\ntype Props = PropsWithChildren<{\n firstFocusTarget?: RefObject<HTMLElement>\n}>\n\nexport type FocusTrapRef = {\n focus: () => void\n}\n\nexport const FocusTrap = forwardRef<FocusTrapRef, Props>(({ firstFocusTarget, children }, ref) => {\n const innerRef = useRef<HTMLDivElement | null>(null)\n const dummyFocusRef = useRef<HTMLDivElement>(null)\n\n const functions = useMemo(\n () => ({\n focus: () => {\n ;(firstFocusTarget?.current || dummyFocusRef.current)?.focus()\n },\n }),\n [firstFocusTarget],\n )\n\n useImperativeHandle(ref, () => functions, [functions])\n\n useEffect(() => {\n // FocusTrap がマウントされた時点のフォーカス要素を保存\n const triggerElement = document.activeElement\n\n functions.focus()\n\n const handleKeyDown = (e: KeyboardEvent) => {\n // IME 変換中の Tab は変換候補の選択に使われるため、フォーカストラップの対象外にする。\n // ここで preventDefault してしまうと、Dialog 内で日本語入力中に Tab を押しても\n // 変換候補が確定されず、未確定文字列がそのまま入力されてしまう。\n if (e.key !== 'Tab' || e.isComposing || innerRef.current === null) {\n return\n }\n\n const tabbables = tabbable(innerRef.current).filter((elm) => elm.tabIndex >= 0)\n\n if (tabbables.length === 0) {\n return\n }\n\n const firstTabbable = tabbables[0]\n const lastTabbable = tabbables[tabbables.length - 1]\n const currentFocused = tabbables.find((elm) => elm === e.target)\n\n if (e.shiftKey) {\n if (currentFocused === firstTabbable || document.activeElement === dummyFocusRef.current) {\n e.preventDefault()\n lastTabbable.focus()\n }\n } else if (currentFocused === lastTabbable) {\n e.preventDefault()\n firstTabbable.focus()\n }\n }\n\n window.addEventListener('keydown', handleKeyDown)\n\n return () => {\n window.removeEventListener('keydown', handleKeyDown)\n // フォーカストラップ終了時にトリガにフォーカスを戻す\n if (triggerElement instanceof HTMLElement) {\n triggerElement.focus()\n }\n }\n }, [functions])\n\n return (\n <div ref={innerRef}>\n {/* eslint-disable-next-line smarthr/a11y-scroller-has-tabindex -- dummy element for focus management. */}\n <div ref={dummyFocusRef} tabIndex={-1} />\n {children}\n </div>\n )\n})\n"],"names":["_jsxs","_jsx"],"mappings":";;;;AAoBO,MAAM,SAAS,GAAG,UAAU,CAAsB,CAAC,EAAE,gBAAgB,EAAE,QAAQ,EAAE,EAAE,GAAG,KAAI;AAC/F,IAAA,MAAM,QAAQ,GAAG,MAAM,CAAwB,IAAI,CAAC;AACpD,IAAA,MAAM,aAAa,GAAG,MAAM,CAAiB,IAAI,CAAC;AAElD,IAAA,MAAM,SAAS,GAAG,OAAO,CACvB,OAAO;QACL,KAAK,EAAE,MAAK;YACT,CAAC,gBAAgB,EAAE,OAAO,IAAI,aAAa,CAAC,OAAO,GAAG,KAAK,EAAE;QAChE,CAAC;AACF,KAAA,CAAC,EACF,CAAC,gBAAgB,CAAC,CACnB;AAED,IAAA,mBAAmB,CAAC,GAAG,EAAE,MAAM,SAAS,EAAE,CAAC,SAAS,CAAC,CAAC;IAEtD,SAAS,CAAC,MAAK;;AAEb,QAAA,MAAM,cAAc,GAAG,QAAQ,CAAC,aAAa;QAE7C,SAAS,CAAC,KAAK,EAAE;AAEjB,QAAA,MAAM,aAAa,GAAG,CAAC,CAAgB,KAAI;;;;AAIzC,YAAA,IAAI,CAAC,CAAC,GAAG,KAAK,KAAK,IAAI,CAAC,CAAC,WAAW,IAAI,QAAQ,CAAC,OAAO,KAAK,IAAI,EAAE;gBACjE;YACF;YAEA,MAAM,SAAS,GAAG,QAAQ,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,GAAG,KAAK,GAAG,CAAC,QAAQ,IAAI,CAAC,CAAC;AAE/E,YAAA,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE;gBAC1B;YACF;AAEA,YAAA,MAAM,aAAa,GAAG,SAAS,CAAC,CAAC,CAAC;YAClC,MAAM,YAAY,GAAG,SAAS,CAAC,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC;AACpD,YAAA,MAAM,cAAc,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC,GAAG,KAAK,GAAG,KAAK,CAAC,CAAC,MAAM,CAAC;AAEhE,YAAA,IAAI,CAAC,CAAC,QAAQ,EAAE;AACd,gBAAA,IAAI,cAAc,KAAK,aAAa,IAAI,QAAQ,CAAC,aAAa,KAAK,aAAa,CAAC,OAAO,EAAE;oBACxF,CAAC,CAAC,cAAc,EAAE;oBAClB,YAAY,CAAC,KAAK,EAAE;gBACtB;YACF;AAAO,iBAAA,IAAI,cAAc,KAAK,YAAY,EAAE;gBAC1C,CAAC,CAAC,cAAc,EAAE;gBAClB,aAAa,CAAC,KAAK,EAAE;YACvB;AACF,QAAA,CAAC;AAED,QAAA,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,aAAa,CAAC;AAEjD,QAAA,OAAO,MAAK;AACV,YAAA,MAAM,CAAC,mBAAmB,CAAC,SAAS,EAAE,aAAa,CAAC;;AAEpD,YAAA,IAAI,cAAc,YAAY,WAAW,EAAE;gBACzC,cAAc,CAAC,KAAK,EAAE;YACxB;AACF,QAAA,CAAC;AACH,IAAA,CAAC,EAAE,CAAC,SAAS,CAAC,CAAC;IAEf,QACEA,cAAK,GAAG,EAAE,QAAQ,EAAA,QAAA,EAAA,CAEhBC,GAAA,CAAA,KAAA,EAAA,EAAK,GAAG,EAAE,aAAa,EAAE,QAAQ,EAAE,EAAE,EAAA,CAAI,EACxC,QAAQ,CAAA,EAAA,CACL;AAEV,CAAC;;;;"}
|
|
@@ -171,7 +171,7 @@ const ModelessDialog = ({ heading, children, contentBgColor, contentPadding, foo
|
|
|
171
171
|
React.useEffect(() => {
|
|
172
172
|
if (!wrapperPosition) {
|
|
173
173
|
setDebouncedLiveRegionText('');
|
|
174
|
-
return;
|
|
174
|
+
return functions.debounceLiveRegionText.cancel;
|
|
175
175
|
}
|
|
176
176
|
const txt = localize({
|
|
177
177
|
id: 'smarthr-ui/ModelessDialog/dialogHandlerLiveRegionText',
|
|
@@ -181,6 +181,7 @@ const ModelessDialog = ({ heading, children, contentBgColor, contentPadding, foo
|
|
|
181
181
|
left: Math.trunc(wrapperPosition.left).toString(),
|
|
182
182
|
});
|
|
183
183
|
functions.debounceLiveRegionText(txt);
|
|
184
|
+
return functions.debounceLiveRegionText.cancel;
|
|
184
185
|
}, [localize, wrapperPosition, functions]);
|
|
185
186
|
React.useEffect(() => {
|
|
186
187
|
if (wrapperRef.current instanceof Element) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ModelessDialog.cjs","sources":["../../../../src/components/Dialog/ModelessDialog/ModelessDialog.tsx"],"sourcesContent":["'use client'\n\nimport {\n type FC,\n type KeyboardEvent,\n type MouseEvent,\n type PropsWithChildren,\n type ReactNode,\n type RefObject,\n memo,\n useEffect,\n useId,\n useMemo,\n useRef,\n useState,\n} from 'react'\nimport Draggable from 'react-draggable'\nimport { type VariantProps, tv } from 'tailwind-variants'\n\nimport { useHandleEscape } from '../../../hooks/useHandleEscape'\nimport { useLatest } from '../../../hooks/useLatest'\nimport { Localizer, useIntl } from '../../../intl'\nimport { debounce } from '../../../libs/debounce'\nimport { dialogSize } from '../../../tailwind'\nimport { Button } from '../../Button'\nimport { Heading } from '../../Heading'\nimport { FaGripIcon, FaXmarkIcon } from '../../Icon'\nimport { Panel, type PanelElementProps } from '../../Panel'\nimport { DialogBody, type Props as DialogBodyProps } from '../DialogBody'\nimport { DialogOverlap } from '../DialogOverlap'\nimport { useDialogPortal } from '../useDialogPortal'\n\nimport type { DialogSize } from '../types'\n\ntype BaseProps = PropsWithChildren<{\n /**\n * ダイアログのタイトルの内容\n */\n heading: ReactNode\n /**\n * ダイアログのフッタ部分の内容\n */\n footer?: ReactNode\n /**\n * ダイアログが開かれているかどうかの真偽値\n */\n isOpen: boolean\n /**\n * 閉じるボタンを押下したときのハンドラ\n */\n onClickClose?: (e: MouseEvent<HTMLButtonElement>) => void\n /**\n * ダイアログが開いている状態で Escape キーを押下したときのハンドラ\n */\n onPressEscape?: () => void\n /**\n * @deprecated ダイアログの幅を指定する場合は、`width` ではなく `size` を使用してください。\n * ダイアログの幅\n */\n width?: string | number\n /**\n * ダイアログの大きさ\n */\n size?: DialogSize\n /**\n * ダイアログの高さ\n */\n height?: string | number\n /**\n * ダイアログを開いたときの初期 top 位置\n */\n top?: string | number\n /**\n * ダイアログを開いたときの初期 left 位置\n */\n left?: string | number\n /**\n * ダイアログを開いたときの初期 right 位置\n */\n right?: string | number\n /**\n * ダイアログを開いたときの初期 bottom 位置\n */\n bottom?: string | number\n /**\n * ポータルの container となる DOM 要素を追加する親要素\n */\n portalParent?: HTMLElement | RefObject<HTMLElement>\n}>\ntype Props = BaseProps &\n Omit<DialogBodyProps, keyof BaseProps> &\n Omit<PanelElementProps, keyof BaseProps> &\n Omit<VariantProps<typeof classNameGenerator>, keyof BaseProps>\n\nconst classNameGenerator = tv({\n slots: {\n overlap: 'shr-inset-[unset]',\n wrapper:\n 'smarthr-ui-ModelessDialog shr-fixed shr-flex shr-max-h-[calc(100svh-theme(spacing[0.5]))] shr-max-w-[calc(100vw-theme(spacing[0.5]))] shr-flex-col',\n headerEl: [\n 'smarthr-ui-ModelessDialog-header shr-border-b-shorthand shr-relative shr-flex shr-cursor-move shr-items-center shr-rounded-tl-l shr-rounded-tr-l shr-pe-1 shr-ps-1.5',\n 'hover:shr-bg-white-darken',\n /* DialogHandlerにフォーカスが当たっているときは、headerもフォーカス状態のスタイルにする。 */\n 'has-[.smarthr-ui-ModelessDialog-handle:focus-visible]:shr-focus-indicator has-[.smarthr-ui-ModelessDialog-handle:focus-visible]:shr-bg-white-darken has-[.smarthr-ui-ModelessDialog-handle:focus-visible]:shr-transition-colors has-[.smarthr-ui-ModelessDialog-handle:focus-visible]:shr-duration-100 has-[.smarthr-ui-ModelessDialog-handle:focus-visible]:shr-ease-in-out',\n ],\n dialogHandler: [\n 'smarthr-ui-ModelessDialog-handle shr-absolute shr-inset-x-0 shr-bottom-0 shr-top-[2px] shr-m-auto shr-flex shr-justify-center shr-rounded-tl-s shr-rounded-tr-s shr-border-none shr-text-grey shr-transition-colors shr-duration-100 shr-ease-in-out',\n 'focus-visible:shr-focus-indicator--none shr-cursor-[inherit] shr-bg-[unset]',\n ],\n headingEl: ['shr-my-1 shr-me-1'],\n closeButtonLayout: [\n 'shr-relative' /* DialogHandlerの上に出すためにスタッキングコンテキストを生成 */,\n 'shr-ml-auto shr-shrink-0',\n ],\n footerEl: 'smarthr-ui-ModelessDialog-footer shr-border-t-shorthand',\n },\n variants: {\n size: {\n XS: { wrapper: dialogSize.XS },\n S: { wrapper: dialogSize.S },\n M: { wrapper: dialogSize.M },\n L: { wrapper: dialogSize.L },\n XL: { wrapper: dialogSize.XL },\n XXL: { wrapper: dialogSize.XXL },\n FULL: { wrapper: dialogSize.FULL },\n },\n resizable: {\n true: {\n wrapper: 'shr-resize shr-overflow-auto',\n },\n false: {},\n },\n },\n})\n\nexport const ModelessDialog: FC<Props> = ({\n heading,\n children,\n contentBgColor,\n contentPadding,\n footer,\n isOpen,\n onPressEscape,\n resizable = false,\n width,\n size,\n height,\n top,\n left,\n right,\n bottom,\n portalParent,\n className,\n id,\n onClickClose,\n ...rest\n}) => {\n const labelId = useId()\n const lastFocusElementRef = useRef<HTMLElement | null>(null)\n const { createPortal } = useDialogPortal(portalParent, id)\n const { localize } = useIntl()\n\n const classNames = useMemo(() => {\n const { overlap, wrapper, headerEl, headingEl, dialogHandler, closeButtonLayout, footerEl } =\n classNameGenerator()\n\n return {\n overlap: overlap({ className }),\n wrapper: wrapper({ size, resizable }),\n header: headerEl(),\n heading: headingEl(),\n dialogHandler: dialogHandler(),\n closeButtonLayout: closeButtonLayout(),\n footer: footerEl(),\n }\n }, [className, size, resizable])\n\n const wrapperRef = useRef<HTMLDivElement>(null)\n const focusTargetRef = useRef<HTMLDivElement>(null)\n\n const [wrapperPosition, setWrapperPosition] = useState<DOMRect | undefined>(undefined)\n const [debouncedLiveRegionText, setDebouncedLiveRegionText] = useState<string>('')\n const [centering, setCentering] = useState<{\n top?: number\n left?: number\n }>({})\n const [position, setPosition] = useState<{ x: number; y: number }>({\n x: 0,\n y: 0,\n })\n const [draggableBounds, setDraggableBounds] = useState(Draggable.defaultProps.bounds)\n\n const positionStyle = useMemo(\n () => ({\n top: centering.top ?? top,\n left: centering.left ?? left,\n right,\n bottom,\n width: size ? undefined : width,\n height,\n }),\n [centering, top, left, right, bottom, width, height, size],\n )\n\n const latest = useLatest({ isOpen, onClickClose, onPressEscape })\n\n const functions = useMemo(\n () => ({\n debounceLiveRegionText: debounce(setDebouncedLiveRegionText, 600),\n handleArrowKeyDown: (e: KeyboardEvent) => {\n if (!latest.isOpen || document.activeElement !== e.currentTarget) {\n return\n }\n\n const movingDistance = 20\n\n switch (e.key) {\n case 'ArrowUp':\n setPosition((prev) => ({\n x: prev.x,\n y: prev.y - movingDistance,\n }))\n e.preventDefault()\n break\n case 'ArrowDown':\n setPosition((prev) => ({\n x: prev.x,\n y: prev.y + movingDistance,\n }))\n e.preventDefault()\n break\n case 'ArrowLeft':\n setPosition((prev) => ({\n x: prev.x - movingDistance,\n y: prev.y,\n }))\n e.preventDefault()\n break\n case 'ArrowRight':\n setPosition((prev) => ({\n x: prev.x + movingDistance,\n y: prev.y,\n }))\n e.preventDefault()\n break\n }\n },\n handleClickClose: (e: MouseEvent<HTMLButtonElement>) => {\n lastFocusElementRef.current?.focus()\n latest.onClickClose?.(e)\n },\n handlePressEscape: () => {\n lastFocusElementRef.current?.focus()\n latest.onPressEscape?.()\n },\n handleDragStart: (_: any, data: { x: number; y: number }) => setPosition(data),\n handleDrag: (_: any, data: { deltaX: number; deltaY: number }) => {\n setPosition((prev) => ({\n x: prev.x + data.deltaX,\n y: prev.y + data.deltaY,\n }))\n },\n }),\n [latest],\n )\n\n useEffect(() => {\n if (!wrapperPosition) {\n setDebouncedLiveRegionText('')\n return\n }\n\n const txt = localize(\n {\n id: 'smarthr-ui/ModelessDialog/dialogHandlerLiveRegionText',\n defaultText: '上から{top}px、左から{left}px',\n },\n {\n top: Math.trunc(wrapperPosition.top).toString(),\n left: Math.trunc(wrapperPosition.left).toString(),\n },\n )\n\n functions.debounceLiveRegionText(txt)\n }, [localize, wrapperPosition, functions])\n\n useEffect(() => {\n if (wrapperRef.current instanceof Element) {\n setWrapperPosition(wrapperRef.current.getBoundingClientRect())\n }\n }, [position])\n\n useEffect(() => {\n // 中央寄せの座標計算を行う\n if (!wrapperRef.current || !isOpen) {\n return\n }\n\n const isXCenter = left === undefined && right === undefined\n const isYCenter = top === undefined && bottom === undefined\n\n if (isXCenter || isYCenter) {\n const rect = wrapperRef.current.getBoundingClientRect()\n\n setCentering({\n top: isYCenter ? Math.max(0, window.innerHeight / 2 - rect.height / 2) : undefined,\n left: isXCenter ? Math.max(0, window.innerWidth / 2 - rect.width / 2) : undefined,\n })\n }\n }, [bottom, isOpen, left, right, top])\n\n useEffect(() => {\n if (!isOpen) return\n\n if (centering.top) {\n setDraggableBounds({ top: centering.top * -1 })\n\n return\n }\n\n if (wrapperRef.current) {\n const rect = wrapperRef.current.getBoundingClientRect()\n\n setDraggableBounds({ top: rect.top * -1 })\n }\n }, [isOpen, centering.top])\n\n useEffect(() => {\n if (isOpen) {\n setPosition({ x: 0, y: 0 })\n focusTargetRef.current?.focus()\n }\n }, [isOpen])\n\n useHandleEscape(isOpen ? functions.handlePressEscape : undefined)\n\n useEffect(() => {\n const focusHandler = (e: FocusEvent) => {\n // e.target(現在フォーカスがあたっている要素)がModeless dialog外の要素であれば、lastFocusElementRefに代入する\n if (e.target instanceof HTMLElement && !wrapperRef?.current?.contains(e.target)) {\n lastFocusElementRef.current = e.target\n }\n }\n\n document.addEventListener('focus', focusHandler, true)\n\n return () => document.removeEventListener('focus', focusHandler, true)\n }, [])\n\n return createPortal(\n <DialogOverlap isOpen={isOpen} className={classNames.overlap} as=\"section\">\n <Draggable\n {...Draggable.defaultProps}\n handle=\".smarthr-ui-ModelessDialog-handle\"\n onStart={functions.handleDragStart}\n onDrag={functions.handleDrag}\n position={position}\n bounds={draggableBounds ?? false}\n nodeRef={wrapperRef}\n >\n <Panel\n {...rest}\n ref={wrapperRef}\n role=\"dialog\"\n aria-labelledby={labelId}\n radius=\"m\"\n layer={3}\n overflow=\"auto\"\n className={classNames.wrapper}\n style={positionStyle}\n >\n {/* eslint-disable-next-line smarthr/a11y-scroller-has-tabindex -- dummy element for focus management. */}\n <div tabIndex={-1} ref={focusTargetRef} />\n <div className={classNames.header}>\n <Handler\n handleArrowKeyDown={functions.handleArrowKeyDown}\n className={classNames.dialogHandler}\n />\n <div id={labelId} className={classNames.heading}>\n {/* eslint-disable-next-line smarthr/a11y-heading-in-sectioning-content */}\n <Heading>{heading}</Heading>\n </div>\n <CloseButton\n handleClick={functions.handleClickClose}\n className={classNames.closeButtonLayout}\n />\n </div>\n <DialogBody\n contentBgColor={contentBgColor}\n contentPadding={contentPadding}\n className=\"smarthr-ui-ModelessDialog-content shr-overscroll-contain\"\n >\n {children}\n </DialogBody>\n {footer && <div className={classNames.footer}>{footer}</div>}\n <LiveRegion regionText={debouncedLiveRegionText} />\n </Panel>\n </Draggable>\n </DialogOverlap>,\n )\n}\n\nconst Handler = memo<{\n className: string\n handleArrowKeyDown: (e: KeyboardEvent) => void\n}>(({ handleArrowKeyDown, ...rest }) => {\n const { localize } = useIntl()\n\n return (\n <>\n <button\n {...rest}\n type=\"button\"\n aria-label={localize({\n id: 'smarthr-ui/ModelessDialog/dialogHandlerAriaLabel',\n defaultText: 'ダイアログの位置',\n })}\n aria-roledescription={localize({\n id: 'smarthr-ui/ModelessDialog/dialogHandlerAriaRoleDescription',\n defaultText: 'ドラッグ可能',\n })}\n aria-describedby=\"handler-description\"\n onKeyDown={handleArrowKeyDown}\n >\n <FaGripIcon />\n </button>\n <div className=\"shr-hidden\" id=\"handler-description\">\n {localize({\n id: 'smarthr-ui/ModelessDialog/dialogHandlerDescription',\n defaultText: '矢印キーを押して上下左右に移動できます',\n })}\n </div>\n </>\n )\n})\n\nconst LiveRegion = ({ regionText }: { regionText: string | undefined }) => (\n <div\n role=\"status\"\n className=\"shr-fixed -shr-m-px shr-h-px shr-w-px shr-overflow-hidden shr-whitespace-nowrap\"\n >\n {regionText}\n </div>\n)\n\nconst CloseButton = memo<{\n className: string\n handleClick: (e: MouseEvent<HTMLButtonElement>) => void\n}>(({ handleClick, className }) => (\n <div className={className}>\n <Button\n type=\"button\"\n size=\"S\"\n onClick={handleClick}\n className=\"smarthr-ui-ModelessDialog-closeButton\"\n >\n <FaXmarkIcon\n alt={<Localizer id=\"smarthr-ui/ModelessDialog/closeButtonIconAlt\" defaultText=\"閉じる\" />}\n />\n </Button>\n </div>\n))\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FA;AACE;AACE;AACA;AAEA;;;;;AAKC;AACD;;;AAGC;;AAED;AACE;;AAED;AACD;AACD;AACD;AACE;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACD;AACD;AACE;AACE;AACD;AACD;AACD;AACF;AACF;;AAwBC;AACA;;AAEA;AAEA;AACE;;AAIE;;;;;;;;;AAUJ;AACA;;;;AAQA;AACE;AACA;AACD;AACD;AAEA;AAEI;AACA;;;;;AAKD;AAIH;AAEA;AAEI;AACA;AACE;;;;AAMA;AACE;AACE;;AAEE;AACD;;;AAGH;AACE;;AAEE;AACD;;;AAGH;AACE;AACE;;AAED;;;AAGH;AACE;AACE;;AAED;;;;;AAKP;AACE;AACA;;;AAGA;AACA;;;AAGF;AACE;AACE;AACA;AACD;;AAEJ;;;;;;;AAYG;AACA;;;;AAKD;AAGH;;;AAIA;;;AAGF;;;;;;;;AAWE;;AAGE;;;AAGC;;AAEL;;AAGE;;AAEA;AACE;;;AAKF;;AAGE;;;;;;AAOA;;AAEJ;AAEA;;AAGE;;AAEE;AACE;;AAEJ;;AAIA;;;AAsDJ;AAEA;AAIE;;AAQQ;AACA;;AAGA;AACA;;AASA;AACA;;AAKV;AAEA;AASA;;"}
|
|
1
|
+
{"version":3,"file":"ModelessDialog.cjs","sources":["../../../../src/components/Dialog/ModelessDialog/ModelessDialog.tsx"],"sourcesContent":["'use client'\n\nimport {\n type FC,\n type KeyboardEvent,\n type MouseEvent,\n type PropsWithChildren,\n type ReactNode,\n type RefObject,\n memo,\n useEffect,\n useId,\n useMemo,\n useRef,\n useState,\n} from 'react'\nimport Draggable from 'react-draggable'\nimport { type VariantProps, tv } from 'tailwind-variants'\n\nimport { useHandleEscape } from '../../../hooks/useHandleEscape'\nimport { useLatest } from '../../../hooks/useLatest'\nimport { Localizer, useIntl } from '../../../intl'\nimport { debounce } from '../../../libs/debounce'\nimport { dialogSize } from '../../../tailwind'\nimport { Button } from '../../Button'\nimport { Heading } from '../../Heading'\nimport { FaGripIcon, FaXmarkIcon } from '../../Icon'\nimport { Panel, type PanelElementProps } from '../../Panel'\nimport { DialogBody, type Props as DialogBodyProps } from '../DialogBody'\nimport { DialogOverlap } from '../DialogOverlap'\nimport { useDialogPortal } from '../useDialogPortal'\n\nimport type { DialogSize } from '../types'\n\ntype BaseProps = PropsWithChildren<{\n /**\n * ダイアログのタイトルの内容\n */\n heading: ReactNode\n /**\n * ダイアログのフッタ部分の内容\n */\n footer?: ReactNode\n /**\n * ダイアログが開かれているかどうかの真偽値\n */\n isOpen: boolean\n /**\n * 閉じるボタンを押下したときのハンドラ\n */\n onClickClose?: (e: MouseEvent<HTMLButtonElement>) => void\n /**\n * ダイアログが開いている状態で Escape キーを押下したときのハンドラ\n */\n onPressEscape?: () => void\n /**\n * @deprecated ダイアログの幅を指定する場合は、`width` ではなく `size` を使用してください。\n * ダイアログの幅\n */\n width?: string | number\n /**\n * ダイアログの大きさ\n */\n size?: DialogSize\n /**\n * ダイアログの高さ\n */\n height?: string | number\n /**\n * ダイアログを開いたときの初期 top 位置\n */\n top?: string | number\n /**\n * ダイアログを開いたときの初期 left 位置\n */\n left?: string | number\n /**\n * ダイアログを開いたときの初期 right 位置\n */\n right?: string | number\n /**\n * ダイアログを開いたときの初期 bottom 位置\n */\n bottom?: string | number\n /**\n * ポータルの container となる DOM 要素を追加する親要素\n */\n portalParent?: HTMLElement | RefObject<HTMLElement>\n}>\ntype Props = BaseProps &\n Omit<DialogBodyProps, keyof BaseProps> &\n Omit<PanelElementProps, keyof BaseProps> &\n Omit<VariantProps<typeof classNameGenerator>, keyof BaseProps>\n\nconst classNameGenerator = tv({\n slots: {\n overlap: 'shr-inset-[unset]',\n wrapper:\n 'smarthr-ui-ModelessDialog shr-fixed shr-flex shr-max-h-[calc(100svh-theme(spacing[0.5]))] shr-max-w-[calc(100vw-theme(spacing[0.5]))] shr-flex-col',\n headerEl: [\n 'smarthr-ui-ModelessDialog-header shr-border-b-shorthand shr-relative shr-flex shr-cursor-move shr-items-center shr-rounded-tl-l shr-rounded-tr-l shr-pe-1 shr-ps-1.5',\n 'hover:shr-bg-white-darken',\n /* DialogHandlerにフォーカスが当たっているときは、headerもフォーカス状態のスタイルにする。 */\n 'has-[.smarthr-ui-ModelessDialog-handle:focus-visible]:shr-focus-indicator has-[.smarthr-ui-ModelessDialog-handle:focus-visible]:shr-bg-white-darken has-[.smarthr-ui-ModelessDialog-handle:focus-visible]:shr-transition-colors has-[.smarthr-ui-ModelessDialog-handle:focus-visible]:shr-duration-100 has-[.smarthr-ui-ModelessDialog-handle:focus-visible]:shr-ease-in-out',\n ],\n dialogHandler: [\n 'smarthr-ui-ModelessDialog-handle shr-absolute shr-inset-x-0 shr-bottom-0 shr-top-[2px] shr-m-auto shr-flex shr-justify-center shr-rounded-tl-s shr-rounded-tr-s shr-border-none shr-text-grey shr-transition-colors shr-duration-100 shr-ease-in-out',\n 'focus-visible:shr-focus-indicator--none shr-cursor-[inherit] shr-bg-[unset]',\n ],\n headingEl: ['shr-my-1 shr-me-1'],\n closeButtonLayout: [\n 'shr-relative' /* DialogHandlerの上に出すためにスタッキングコンテキストを生成 */,\n 'shr-ml-auto shr-shrink-0',\n ],\n footerEl: 'smarthr-ui-ModelessDialog-footer shr-border-t-shorthand',\n },\n variants: {\n size: {\n XS: { wrapper: dialogSize.XS },\n S: { wrapper: dialogSize.S },\n M: { wrapper: dialogSize.M },\n L: { wrapper: dialogSize.L },\n XL: { wrapper: dialogSize.XL },\n XXL: { wrapper: dialogSize.XXL },\n FULL: { wrapper: dialogSize.FULL },\n },\n resizable: {\n true: {\n wrapper: 'shr-resize shr-overflow-auto',\n },\n false: {},\n },\n },\n})\n\nexport const ModelessDialog: FC<Props> = ({\n heading,\n children,\n contentBgColor,\n contentPadding,\n footer,\n isOpen,\n onPressEscape,\n resizable = false,\n width,\n size,\n height,\n top,\n left,\n right,\n bottom,\n portalParent,\n className,\n id,\n onClickClose,\n ...rest\n}) => {\n const labelId = useId()\n const lastFocusElementRef = useRef<HTMLElement | null>(null)\n const { createPortal } = useDialogPortal(portalParent, id)\n const { localize } = useIntl()\n\n const classNames = useMemo(() => {\n const { overlap, wrapper, headerEl, headingEl, dialogHandler, closeButtonLayout, footerEl } =\n classNameGenerator()\n\n return {\n overlap: overlap({ className }),\n wrapper: wrapper({ size, resizable }),\n header: headerEl(),\n heading: headingEl(),\n dialogHandler: dialogHandler(),\n closeButtonLayout: closeButtonLayout(),\n footer: footerEl(),\n }\n }, [className, size, resizable])\n\n const wrapperRef = useRef<HTMLDivElement>(null)\n const focusTargetRef = useRef<HTMLDivElement>(null)\n\n const [wrapperPosition, setWrapperPosition] = useState<DOMRect | undefined>(undefined)\n const [debouncedLiveRegionText, setDebouncedLiveRegionText] = useState<string>('')\n const [centering, setCentering] = useState<{\n top?: number\n left?: number\n }>({})\n const [position, setPosition] = useState<{ x: number; y: number }>({\n x: 0,\n y: 0,\n })\n const [draggableBounds, setDraggableBounds] = useState(Draggable.defaultProps.bounds)\n\n const positionStyle = useMemo(\n () => ({\n top: centering.top ?? top,\n left: centering.left ?? left,\n right,\n bottom,\n width: size ? undefined : width,\n height,\n }),\n [centering, top, left, right, bottom, width, height, size],\n )\n\n const latest = useLatest({ isOpen, onClickClose, onPressEscape })\n\n const functions = useMemo(\n () => ({\n debounceLiveRegionText: debounce(setDebouncedLiveRegionText, 600),\n handleArrowKeyDown: (e: KeyboardEvent) => {\n if (!latest.isOpen || document.activeElement !== e.currentTarget) {\n return\n }\n\n const movingDistance = 20\n\n switch (e.key) {\n case 'ArrowUp':\n setPosition((prev) => ({\n x: prev.x,\n y: prev.y - movingDistance,\n }))\n e.preventDefault()\n break\n case 'ArrowDown':\n setPosition((prev) => ({\n x: prev.x,\n y: prev.y + movingDistance,\n }))\n e.preventDefault()\n break\n case 'ArrowLeft':\n setPosition((prev) => ({\n x: prev.x - movingDistance,\n y: prev.y,\n }))\n e.preventDefault()\n break\n case 'ArrowRight':\n setPosition((prev) => ({\n x: prev.x + movingDistance,\n y: prev.y,\n }))\n e.preventDefault()\n break\n }\n },\n handleClickClose: (e: MouseEvent<HTMLButtonElement>) => {\n lastFocusElementRef.current?.focus()\n latest.onClickClose?.(e)\n },\n handlePressEscape: () => {\n lastFocusElementRef.current?.focus()\n latest.onPressEscape?.()\n },\n handleDragStart: (_: any, data: { x: number; y: number }) => setPosition(data),\n handleDrag: (_: any, data: { deltaX: number; deltaY: number }) => {\n setPosition((prev) => ({\n x: prev.x + data.deltaX,\n y: prev.y + data.deltaY,\n }))\n },\n }),\n [latest],\n )\n\n useEffect(() => {\n if (!wrapperPosition) {\n setDebouncedLiveRegionText('')\n return functions.debounceLiveRegionText.cancel\n }\n\n const txt = localize(\n {\n id: 'smarthr-ui/ModelessDialog/dialogHandlerLiveRegionText',\n defaultText: '上から{top}px、左から{left}px',\n },\n {\n top: Math.trunc(wrapperPosition.top).toString(),\n left: Math.trunc(wrapperPosition.left).toString(),\n },\n )\n\n functions.debounceLiveRegionText(txt)\n\n return functions.debounceLiveRegionText.cancel\n }, [localize, wrapperPosition, functions])\n\n useEffect(() => {\n if (wrapperRef.current instanceof Element) {\n setWrapperPosition(wrapperRef.current.getBoundingClientRect())\n }\n }, [position])\n\n useEffect(() => {\n // 中央寄せの座標計算を行う\n if (!wrapperRef.current || !isOpen) {\n return\n }\n\n const isXCenter = left === undefined && right === undefined\n const isYCenter = top === undefined && bottom === undefined\n\n if (isXCenter || isYCenter) {\n const rect = wrapperRef.current.getBoundingClientRect()\n\n setCentering({\n top: isYCenter ? Math.max(0, window.innerHeight / 2 - rect.height / 2) : undefined,\n left: isXCenter ? Math.max(0, window.innerWidth / 2 - rect.width / 2) : undefined,\n })\n }\n }, [bottom, isOpen, left, right, top])\n\n useEffect(() => {\n if (!isOpen) return\n\n if (centering.top) {\n setDraggableBounds({ top: centering.top * -1 })\n\n return\n }\n\n if (wrapperRef.current) {\n const rect = wrapperRef.current.getBoundingClientRect()\n\n setDraggableBounds({ top: rect.top * -1 })\n }\n }, [isOpen, centering.top])\n\n useEffect(() => {\n if (isOpen) {\n setPosition({ x: 0, y: 0 })\n focusTargetRef.current?.focus()\n }\n }, [isOpen])\n\n useHandleEscape(isOpen ? functions.handlePressEscape : undefined)\n\n useEffect(() => {\n const focusHandler = (e: FocusEvent) => {\n // e.target(現在フォーカスがあたっている要素)がModeless dialog外の要素であれば、lastFocusElementRefに代入する\n if (e.target instanceof HTMLElement && !wrapperRef?.current?.contains(e.target)) {\n lastFocusElementRef.current = e.target\n }\n }\n\n document.addEventListener('focus', focusHandler, true)\n\n return () => document.removeEventListener('focus', focusHandler, true)\n }, [])\n\n return createPortal(\n <DialogOverlap isOpen={isOpen} className={classNames.overlap} as=\"section\">\n <Draggable\n {...Draggable.defaultProps}\n handle=\".smarthr-ui-ModelessDialog-handle\"\n onStart={functions.handleDragStart}\n onDrag={functions.handleDrag}\n position={position}\n bounds={draggableBounds ?? false}\n nodeRef={wrapperRef}\n >\n <Panel\n {...rest}\n ref={wrapperRef}\n role=\"dialog\"\n aria-labelledby={labelId}\n radius=\"m\"\n layer={3}\n overflow=\"auto\"\n className={classNames.wrapper}\n style={positionStyle}\n >\n {/* eslint-disable-next-line smarthr/a11y-scroller-has-tabindex -- dummy element for focus management. */}\n <div tabIndex={-1} ref={focusTargetRef} />\n <div className={classNames.header}>\n <Handler\n handleArrowKeyDown={functions.handleArrowKeyDown}\n className={classNames.dialogHandler}\n />\n <div id={labelId} className={classNames.heading}>\n {/* eslint-disable-next-line smarthr/a11y-heading-in-sectioning-content */}\n <Heading>{heading}</Heading>\n </div>\n <CloseButton\n handleClick={functions.handleClickClose}\n className={classNames.closeButtonLayout}\n />\n </div>\n <DialogBody\n contentBgColor={contentBgColor}\n contentPadding={contentPadding}\n className=\"smarthr-ui-ModelessDialog-content shr-overscroll-contain\"\n >\n {children}\n </DialogBody>\n {footer && <div className={classNames.footer}>{footer}</div>}\n <LiveRegion regionText={debouncedLiveRegionText} />\n </Panel>\n </Draggable>\n </DialogOverlap>,\n )\n}\n\nconst Handler = memo<{\n className: string\n handleArrowKeyDown: (e: KeyboardEvent) => void\n}>(({ handleArrowKeyDown, ...rest }) => {\n const { localize } = useIntl()\n\n return (\n <>\n <button\n {...rest}\n type=\"button\"\n aria-label={localize({\n id: 'smarthr-ui/ModelessDialog/dialogHandlerAriaLabel',\n defaultText: 'ダイアログの位置',\n })}\n aria-roledescription={localize({\n id: 'smarthr-ui/ModelessDialog/dialogHandlerAriaRoleDescription',\n defaultText: 'ドラッグ可能',\n })}\n aria-describedby=\"handler-description\"\n onKeyDown={handleArrowKeyDown}\n >\n <FaGripIcon />\n </button>\n <div className=\"shr-hidden\" id=\"handler-description\">\n {localize({\n id: 'smarthr-ui/ModelessDialog/dialogHandlerDescription',\n defaultText: '矢印キーを押して上下左右に移動できます',\n })}\n </div>\n </>\n )\n})\n\nconst LiveRegion = ({ regionText }: { regionText: string | undefined }) => (\n <div\n role=\"status\"\n className=\"shr-fixed -shr-m-px shr-h-px shr-w-px shr-overflow-hidden shr-whitespace-nowrap\"\n >\n {regionText}\n </div>\n)\n\nconst CloseButton = memo<{\n className: string\n handleClick: (e: MouseEvent<HTMLButtonElement>) => void\n}>(({ handleClick, className }) => (\n <div className={className}>\n <Button\n type=\"button\"\n size=\"S\"\n onClick={handleClick}\n className=\"smarthr-ui-ModelessDialog-closeButton\"\n >\n <FaXmarkIcon\n alt={<Localizer id=\"smarthr-ui/ModelessDialog/closeButtonIconAlt\" defaultText=\"閉じる\" />}\n />\n </Button>\n </div>\n))\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FA;AACE;AACE;AACA;AAEA;;;;;AAKC;AACD;;;AAGC;;AAED;AACE;;AAED;AACD;AACD;AACD;AACE;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACD;AACD;AACE;AACE;AACD;AACD;AACD;AACF;AACF;;AAwBC;AACA;;AAEA;AAEA;AACE;;AAIE;;;;;;;;;AAUJ;AACA;;;;AAQA;AACE;AACA;AACD;AACD;AAEA;AAEI;AACA;;;;;AAKD;AAIH;AAEA;AAEI;AACA;AACE;;;;AAMA;AACE;AACE;;AAEE;AACD;;;AAGH;AACE;;AAEE;AACD;;;AAGH;AACE;AACE;;AAED;;;AAGH;AACE;AACE;;AAED;;;;;AAKP;AACE;AACA;;;AAGA;AACA;;;AAGF;AACE;AACE;AACA;AACD;;AAEJ;;;;AAOC;;;AAKE;AACA;;;;AAKD;AAGH;AAEA;;;AAIA;;;AAGF;;;;;;;;AAWE;;AAGE;;;AAGC;;AAEL;;AAGE;;AAEA;AACE;;;AAKF;;AAGE;;;;;;AAOA;;AAEJ;AAEA;;AAGE;;AAEE;AACE;;AAEJ;;AAIA;;;AAsDJ;AAEA;AAIE;;AAQQ;AACA;;AAGA;AACA;;AASA;AACA;;AAKV;AAEA;AASA;;"}
|
|
@@ -169,7 +169,7 @@ const ModelessDialog = ({ heading, children, contentBgColor, contentPadding, foo
|
|
|
169
169
|
useEffect(() => {
|
|
170
170
|
if (!wrapperPosition) {
|
|
171
171
|
setDebouncedLiveRegionText('');
|
|
172
|
-
return;
|
|
172
|
+
return functions.debounceLiveRegionText.cancel;
|
|
173
173
|
}
|
|
174
174
|
const txt = localize({
|
|
175
175
|
id: 'smarthr-ui/ModelessDialog/dialogHandlerLiveRegionText',
|
|
@@ -179,6 +179,7 @@ const ModelessDialog = ({ heading, children, contentBgColor, contentPadding, foo
|
|
|
179
179
|
left: Math.trunc(wrapperPosition.left).toString(),
|
|
180
180
|
});
|
|
181
181
|
functions.debounceLiveRegionText(txt);
|
|
182
|
+
return functions.debounceLiveRegionText.cancel;
|
|
182
183
|
}, [localize, wrapperPosition, functions]);
|
|
183
184
|
useEffect(() => {
|
|
184
185
|
if (wrapperRef.current instanceof Element) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ModelessDialog.js","sources":["../../../../src/components/Dialog/ModelessDialog/ModelessDialog.tsx"],"sourcesContent":["'use client'\n\nimport {\n type FC,\n type KeyboardEvent,\n type MouseEvent,\n type PropsWithChildren,\n type ReactNode,\n type RefObject,\n memo,\n useEffect,\n useId,\n useMemo,\n useRef,\n useState,\n} from 'react'\nimport Draggable from 'react-draggable'\nimport { type VariantProps, tv } from 'tailwind-variants'\n\nimport { useHandleEscape } from '../../../hooks/useHandleEscape'\nimport { useLatest } from '../../../hooks/useLatest'\nimport { Localizer, useIntl } from '../../../intl'\nimport { debounce } from '../../../libs/debounce'\nimport { dialogSize } from '../../../tailwind'\nimport { Button } from '../../Button'\nimport { Heading } from '../../Heading'\nimport { FaGripIcon, FaXmarkIcon } from '../../Icon'\nimport { Panel, type PanelElementProps } from '../../Panel'\nimport { DialogBody, type Props as DialogBodyProps } from '../DialogBody'\nimport { DialogOverlap } from '../DialogOverlap'\nimport { useDialogPortal } from '../useDialogPortal'\n\nimport type { DialogSize } from '../types'\n\ntype BaseProps = PropsWithChildren<{\n /**\n * ダイアログのタイトルの内容\n */\n heading: ReactNode\n /**\n * ダイアログのフッタ部分の内容\n */\n footer?: ReactNode\n /**\n * ダイアログが開かれているかどうかの真偽値\n */\n isOpen: boolean\n /**\n * 閉じるボタンを押下したときのハンドラ\n */\n onClickClose?: (e: MouseEvent<HTMLButtonElement>) => void\n /**\n * ダイアログが開いている状態で Escape キーを押下したときのハンドラ\n */\n onPressEscape?: () => void\n /**\n * @deprecated ダイアログの幅を指定する場合は、`width` ではなく `size` を使用してください。\n * ダイアログの幅\n */\n width?: string | number\n /**\n * ダイアログの大きさ\n */\n size?: DialogSize\n /**\n * ダイアログの高さ\n */\n height?: string | number\n /**\n * ダイアログを開いたときの初期 top 位置\n */\n top?: string | number\n /**\n * ダイアログを開いたときの初期 left 位置\n */\n left?: string | number\n /**\n * ダイアログを開いたときの初期 right 位置\n */\n right?: string | number\n /**\n * ダイアログを開いたときの初期 bottom 位置\n */\n bottom?: string | number\n /**\n * ポータルの container となる DOM 要素を追加する親要素\n */\n portalParent?: HTMLElement | RefObject<HTMLElement>\n}>\ntype Props = BaseProps &\n Omit<DialogBodyProps, keyof BaseProps> &\n Omit<PanelElementProps, keyof BaseProps> &\n Omit<VariantProps<typeof classNameGenerator>, keyof BaseProps>\n\nconst classNameGenerator = tv({\n slots: {\n overlap: 'shr-inset-[unset]',\n wrapper:\n 'smarthr-ui-ModelessDialog shr-fixed shr-flex shr-max-h-[calc(100svh-theme(spacing[0.5]))] shr-max-w-[calc(100vw-theme(spacing[0.5]))] shr-flex-col',\n headerEl: [\n 'smarthr-ui-ModelessDialog-header shr-border-b-shorthand shr-relative shr-flex shr-cursor-move shr-items-center shr-rounded-tl-l shr-rounded-tr-l shr-pe-1 shr-ps-1.5',\n 'hover:shr-bg-white-darken',\n /* DialogHandlerにフォーカスが当たっているときは、headerもフォーカス状態のスタイルにする。 */\n 'has-[.smarthr-ui-ModelessDialog-handle:focus-visible]:shr-focus-indicator has-[.smarthr-ui-ModelessDialog-handle:focus-visible]:shr-bg-white-darken has-[.smarthr-ui-ModelessDialog-handle:focus-visible]:shr-transition-colors has-[.smarthr-ui-ModelessDialog-handle:focus-visible]:shr-duration-100 has-[.smarthr-ui-ModelessDialog-handle:focus-visible]:shr-ease-in-out',\n ],\n dialogHandler: [\n 'smarthr-ui-ModelessDialog-handle shr-absolute shr-inset-x-0 shr-bottom-0 shr-top-[2px] shr-m-auto shr-flex shr-justify-center shr-rounded-tl-s shr-rounded-tr-s shr-border-none shr-text-grey shr-transition-colors shr-duration-100 shr-ease-in-out',\n 'focus-visible:shr-focus-indicator--none shr-cursor-[inherit] shr-bg-[unset]',\n ],\n headingEl: ['shr-my-1 shr-me-1'],\n closeButtonLayout: [\n 'shr-relative' /* DialogHandlerの上に出すためにスタッキングコンテキストを生成 */,\n 'shr-ml-auto shr-shrink-0',\n ],\n footerEl: 'smarthr-ui-ModelessDialog-footer shr-border-t-shorthand',\n },\n variants: {\n size: {\n XS: { wrapper: dialogSize.XS },\n S: { wrapper: dialogSize.S },\n M: { wrapper: dialogSize.M },\n L: { wrapper: dialogSize.L },\n XL: { wrapper: dialogSize.XL },\n XXL: { wrapper: dialogSize.XXL },\n FULL: { wrapper: dialogSize.FULL },\n },\n resizable: {\n true: {\n wrapper: 'shr-resize shr-overflow-auto',\n },\n false: {},\n },\n },\n})\n\nexport const ModelessDialog: FC<Props> = ({\n heading,\n children,\n contentBgColor,\n contentPadding,\n footer,\n isOpen,\n onPressEscape,\n resizable = false,\n width,\n size,\n height,\n top,\n left,\n right,\n bottom,\n portalParent,\n className,\n id,\n onClickClose,\n ...rest\n}) => {\n const labelId = useId()\n const lastFocusElementRef = useRef<HTMLElement | null>(null)\n const { createPortal } = useDialogPortal(portalParent, id)\n const { localize } = useIntl()\n\n const classNames = useMemo(() => {\n const { overlap, wrapper, headerEl, headingEl, dialogHandler, closeButtonLayout, footerEl } =\n classNameGenerator()\n\n return {\n overlap: overlap({ className }),\n wrapper: wrapper({ size, resizable }),\n header: headerEl(),\n heading: headingEl(),\n dialogHandler: dialogHandler(),\n closeButtonLayout: closeButtonLayout(),\n footer: footerEl(),\n }\n }, [className, size, resizable])\n\n const wrapperRef = useRef<HTMLDivElement>(null)\n const focusTargetRef = useRef<HTMLDivElement>(null)\n\n const [wrapperPosition, setWrapperPosition] = useState<DOMRect | undefined>(undefined)\n const [debouncedLiveRegionText, setDebouncedLiveRegionText] = useState<string>('')\n const [centering, setCentering] = useState<{\n top?: number\n left?: number\n }>({})\n const [position, setPosition] = useState<{ x: number; y: number }>({\n x: 0,\n y: 0,\n })\n const [draggableBounds, setDraggableBounds] = useState(Draggable.defaultProps.bounds)\n\n const positionStyle = useMemo(\n () => ({\n top: centering.top ?? top,\n left: centering.left ?? left,\n right,\n bottom,\n width: size ? undefined : width,\n height,\n }),\n [centering, top, left, right, bottom, width, height, size],\n )\n\n const latest = useLatest({ isOpen, onClickClose, onPressEscape })\n\n const functions = useMemo(\n () => ({\n debounceLiveRegionText: debounce(setDebouncedLiveRegionText, 600),\n handleArrowKeyDown: (e: KeyboardEvent) => {\n if (!latest.isOpen || document.activeElement !== e.currentTarget) {\n return\n }\n\n const movingDistance = 20\n\n switch (e.key) {\n case 'ArrowUp':\n setPosition((prev) => ({\n x: prev.x,\n y: prev.y - movingDistance,\n }))\n e.preventDefault()\n break\n case 'ArrowDown':\n setPosition((prev) => ({\n x: prev.x,\n y: prev.y + movingDistance,\n }))\n e.preventDefault()\n break\n case 'ArrowLeft':\n setPosition((prev) => ({\n x: prev.x - movingDistance,\n y: prev.y,\n }))\n e.preventDefault()\n break\n case 'ArrowRight':\n setPosition((prev) => ({\n x: prev.x + movingDistance,\n y: prev.y,\n }))\n e.preventDefault()\n break\n }\n },\n handleClickClose: (e: MouseEvent<HTMLButtonElement>) => {\n lastFocusElementRef.current?.focus()\n latest.onClickClose?.(e)\n },\n handlePressEscape: () => {\n lastFocusElementRef.current?.focus()\n latest.onPressEscape?.()\n },\n handleDragStart: (_: any, data: { x: number; y: number }) => setPosition(data),\n handleDrag: (_: any, data: { deltaX: number; deltaY: number }) => {\n setPosition((prev) => ({\n x: prev.x + data.deltaX,\n y: prev.y + data.deltaY,\n }))\n },\n }),\n [latest],\n )\n\n useEffect(() => {\n if (!wrapperPosition) {\n setDebouncedLiveRegionText('')\n return\n }\n\n const txt = localize(\n {\n id: 'smarthr-ui/ModelessDialog/dialogHandlerLiveRegionText',\n defaultText: '上から{top}px、左から{left}px',\n },\n {\n top: Math.trunc(wrapperPosition.top).toString(),\n left: Math.trunc(wrapperPosition.left).toString(),\n },\n )\n\n functions.debounceLiveRegionText(txt)\n }, [localize, wrapperPosition, functions])\n\n useEffect(() => {\n if (wrapperRef.current instanceof Element) {\n setWrapperPosition(wrapperRef.current.getBoundingClientRect())\n }\n }, [position])\n\n useEffect(() => {\n // 中央寄せの座標計算を行う\n if (!wrapperRef.current || !isOpen) {\n return\n }\n\n const isXCenter = left === undefined && right === undefined\n const isYCenter = top === undefined && bottom === undefined\n\n if (isXCenter || isYCenter) {\n const rect = wrapperRef.current.getBoundingClientRect()\n\n setCentering({\n top: isYCenter ? Math.max(0, window.innerHeight / 2 - rect.height / 2) : undefined,\n left: isXCenter ? Math.max(0, window.innerWidth / 2 - rect.width / 2) : undefined,\n })\n }\n }, [bottom, isOpen, left, right, top])\n\n useEffect(() => {\n if (!isOpen) return\n\n if (centering.top) {\n setDraggableBounds({ top: centering.top * -1 })\n\n return\n }\n\n if (wrapperRef.current) {\n const rect = wrapperRef.current.getBoundingClientRect()\n\n setDraggableBounds({ top: rect.top * -1 })\n }\n }, [isOpen, centering.top])\n\n useEffect(() => {\n if (isOpen) {\n setPosition({ x: 0, y: 0 })\n focusTargetRef.current?.focus()\n }\n }, [isOpen])\n\n useHandleEscape(isOpen ? functions.handlePressEscape : undefined)\n\n useEffect(() => {\n const focusHandler = (e: FocusEvent) => {\n // e.target(現在フォーカスがあたっている要素)がModeless dialog外の要素であれば、lastFocusElementRefに代入する\n if (e.target instanceof HTMLElement && !wrapperRef?.current?.contains(e.target)) {\n lastFocusElementRef.current = e.target\n }\n }\n\n document.addEventListener('focus', focusHandler, true)\n\n return () => document.removeEventListener('focus', focusHandler, true)\n }, [])\n\n return createPortal(\n <DialogOverlap isOpen={isOpen} className={classNames.overlap} as=\"section\">\n <Draggable\n {...Draggable.defaultProps}\n handle=\".smarthr-ui-ModelessDialog-handle\"\n onStart={functions.handleDragStart}\n onDrag={functions.handleDrag}\n position={position}\n bounds={draggableBounds ?? false}\n nodeRef={wrapperRef}\n >\n <Panel\n {...rest}\n ref={wrapperRef}\n role=\"dialog\"\n aria-labelledby={labelId}\n radius=\"m\"\n layer={3}\n overflow=\"auto\"\n className={classNames.wrapper}\n style={positionStyle}\n >\n {/* eslint-disable-next-line smarthr/a11y-scroller-has-tabindex -- dummy element for focus management. */}\n <div tabIndex={-1} ref={focusTargetRef} />\n <div className={classNames.header}>\n <Handler\n handleArrowKeyDown={functions.handleArrowKeyDown}\n className={classNames.dialogHandler}\n />\n <div id={labelId} className={classNames.heading}>\n {/* eslint-disable-next-line smarthr/a11y-heading-in-sectioning-content */}\n <Heading>{heading}</Heading>\n </div>\n <CloseButton\n handleClick={functions.handleClickClose}\n className={classNames.closeButtonLayout}\n />\n </div>\n <DialogBody\n contentBgColor={contentBgColor}\n contentPadding={contentPadding}\n className=\"smarthr-ui-ModelessDialog-content shr-overscroll-contain\"\n >\n {children}\n </DialogBody>\n {footer && <div className={classNames.footer}>{footer}</div>}\n <LiveRegion regionText={debouncedLiveRegionText} />\n </Panel>\n </Draggable>\n </DialogOverlap>,\n )\n}\n\nconst Handler = memo<{\n className: string\n handleArrowKeyDown: (e: KeyboardEvent) => void\n}>(({ handleArrowKeyDown, ...rest }) => {\n const { localize } = useIntl()\n\n return (\n <>\n <button\n {...rest}\n type=\"button\"\n aria-label={localize({\n id: 'smarthr-ui/ModelessDialog/dialogHandlerAriaLabel',\n defaultText: 'ダイアログの位置',\n })}\n aria-roledescription={localize({\n id: 'smarthr-ui/ModelessDialog/dialogHandlerAriaRoleDescription',\n defaultText: 'ドラッグ可能',\n })}\n aria-describedby=\"handler-description\"\n onKeyDown={handleArrowKeyDown}\n >\n <FaGripIcon />\n </button>\n <div className=\"shr-hidden\" id=\"handler-description\">\n {localize({\n id: 'smarthr-ui/ModelessDialog/dialogHandlerDescription',\n defaultText: '矢印キーを押して上下左右に移動できます',\n })}\n </div>\n </>\n )\n})\n\nconst LiveRegion = ({ regionText }: { regionText: string | undefined }) => (\n <div\n role=\"status\"\n className=\"shr-fixed -shr-m-px shr-h-px shr-w-px shr-overflow-hidden shr-whitespace-nowrap\"\n >\n {regionText}\n </div>\n)\n\nconst CloseButton = memo<{\n className: string\n handleClick: (e: MouseEvent<HTMLButtonElement>) => void\n}>(({ handleClick, className }) => (\n <div className={className}>\n <Button\n type=\"button\"\n size=\"S\"\n onClick={handleClick}\n className=\"smarthr-ui-ModelessDialog-closeButton\"\n >\n <FaXmarkIcon\n alt={<Localizer id=\"smarthr-ui/ModelessDialog/closeButtonIconAlt\" defaultText=\"閉じる\" />}\n />\n </Button>\n </div>\n))\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FA;AACE;AACE;AACA;AAEA;;;;;AAKC;AACD;;;AAGC;;AAED;AACE;;AAED;AACD;AACD;AACD;AACE;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACD;AACD;AACE;AACE;AACD;AACD;AACD;AACF;AACF;;AAwBC;AACA;;AAEA;AAEA;AACE;;AAIE;;;;;;;;;AAUJ;AACA;;;;AAQA;AACE;AACA;AACD;AACD;AAEA;AAEI;AACA;;;;;AAKD;AAIH;AAEA;AAEI;AACA;AACE;;;;AAMA;AACE;AACE;;AAEE;AACD;;;AAGH;AACE;;AAEE;AACD;;;AAGH;AACE;AACE;;AAED;;;AAGH;AACE;AACE;;AAED;;;;;AAKP;AACE;AACA;;;AAGA;AACA;;;AAGF;AACE;AACE;AACA;AACD;;AAEJ;;;;;;;AAYG;AACA;;;;AAKD;AAGH;;;AAIA;;;AAGF;;;;;;;;AAWE;;AAGE;;;AAGC;;AAEL;;AAGE;;AAEA;AACE;;;AAKF;;AAGE;;;;;;AAOA;;AAEJ;AAEA;;AAGE;;AAEE;AACE;;AAEJ;;AAIA;;;AAsDJ;AAEA;AAIE;;AAQQ;AACA;;AAGA;AACA;;AASA;AACA;;AAKV;AAEA;AASA;;"}
|
|
1
|
+
{"version":3,"file":"ModelessDialog.js","sources":["../../../../src/components/Dialog/ModelessDialog/ModelessDialog.tsx"],"sourcesContent":["'use client'\n\nimport {\n type FC,\n type KeyboardEvent,\n type MouseEvent,\n type PropsWithChildren,\n type ReactNode,\n type RefObject,\n memo,\n useEffect,\n useId,\n useMemo,\n useRef,\n useState,\n} from 'react'\nimport Draggable from 'react-draggable'\nimport { type VariantProps, tv } from 'tailwind-variants'\n\nimport { useHandleEscape } from '../../../hooks/useHandleEscape'\nimport { useLatest } from '../../../hooks/useLatest'\nimport { Localizer, useIntl } from '../../../intl'\nimport { debounce } from '../../../libs/debounce'\nimport { dialogSize } from '../../../tailwind'\nimport { Button } from '../../Button'\nimport { Heading } from '../../Heading'\nimport { FaGripIcon, FaXmarkIcon } from '../../Icon'\nimport { Panel, type PanelElementProps } from '../../Panel'\nimport { DialogBody, type Props as DialogBodyProps } from '../DialogBody'\nimport { DialogOverlap } from '../DialogOverlap'\nimport { useDialogPortal } from '../useDialogPortal'\n\nimport type { DialogSize } from '../types'\n\ntype BaseProps = PropsWithChildren<{\n /**\n * ダイアログのタイトルの内容\n */\n heading: ReactNode\n /**\n * ダイアログのフッタ部分の内容\n */\n footer?: ReactNode\n /**\n * ダイアログが開かれているかどうかの真偽値\n */\n isOpen: boolean\n /**\n * 閉じるボタンを押下したときのハンドラ\n */\n onClickClose?: (e: MouseEvent<HTMLButtonElement>) => void\n /**\n * ダイアログが開いている状態で Escape キーを押下したときのハンドラ\n */\n onPressEscape?: () => void\n /**\n * @deprecated ダイアログの幅を指定する場合は、`width` ではなく `size` を使用してください。\n * ダイアログの幅\n */\n width?: string | number\n /**\n * ダイアログの大きさ\n */\n size?: DialogSize\n /**\n * ダイアログの高さ\n */\n height?: string | number\n /**\n * ダイアログを開いたときの初期 top 位置\n */\n top?: string | number\n /**\n * ダイアログを開いたときの初期 left 位置\n */\n left?: string | number\n /**\n * ダイアログを開いたときの初期 right 位置\n */\n right?: string | number\n /**\n * ダイアログを開いたときの初期 bottom 位置\n */\n bottom?: string | number\n /**\n * ポータルの container となる DOM 要素を追加する親要素\n */\n portalParent?: HTMLElement | RefObject<HTMLElement>\n}>\ntype Props = BaseProps &\n Omit<DialogBodyProps, keyof BaseProps> &\n Omit<PanelElementProps, keyof BaseProps> &\n Omit<VariantProps<typeof classNameGenerator>, keyof BaseProps>\n\nconst classNameGenerator = tv({\n slots: {\n overlap: 'shr-inset-[unset]',\n wrapper:\n 'smarthr-ui-ModelessDialog shr-fixed shr-flex shr-max-h-[calc(100svh-theme(spacing[0.5]))] shr-max-w-[calc(100vw-theme(spacing[0.5]))] shr-flex-col',\n headerEl: [\n 'smarthr-ui-ModelessDialog-header shr-border-b-shorthand shr-relative shr-flex shr-cursor-move shr-items-center shr-rounded-tl-l shr-rounded-tr-l shr-pe-1 shr-ps-1.5',\n 'hover:shr-bg-white-darken',\n /* DialogHandlerにフォーカスが当たっているときは、headerもフォーカス状態のスタイルにする。 */\n 'has-[.smarthr-ui-ModelessDialog-handle:focus-visible]:shr-focus-indicator has-[.smarthr-ui-ModelessDialog-handle:focus-visible]:shr-bg-white-darken has-[.smarthr-ui-ModelessDialog-handle:focus-visible]:shr-transition-colors has-[.smarthr-ui-ModelessDialog-handle:focus-visible]:shr-duration-100 has-[.smarthr-ui-ModelessDialog-handle:focus-visible]:shr-ease-in-out',\n ],\n dialogHandler: [\n 'smarthr-ui-ModelessDialog-handle shr-absolute shr-inset-x-0 shr-bottom-0 shr-top-[2px] shr-m-auto shr-flex shr-justify-center shr-rounded-tl-s shr-rounded-tr-s shr-border-none shr-text-grey shr-transition-colors shr-duration-100 shr-ease-in-out',\n 'focus-visible:shr-focus-indicator--none shr-cursor-[inherit] shr-bg-[unset]',\n ],\n headingEl: ['shr-my-1 shr-me-1'],\n closeButtonLayout: [\n 'shr-relative' /* DialogHandlerの上に出すためにスタッキングコンテキストを生成 */,\n 'shr-ml-auto shr-shrink-0',\n ],\n footerEl: 'smarthr-ui-ModelessDialog-footer shr-border-t-shorthand',\n },\n variants: {\n size: {\n XS: { wrapper: dialogSize.XS },\n S: { wrapper: dialogSize.S },\n M: { wrapper: dialogSize.M },\n L: { wrapper: dialogSize.L },\n XL: { wrapper: dialogSize.XL },\n XXL: { wrapper: dialogSize.XXL },\n FULL: { wrapper: dialogSize.FULL },\n },\n resizable: {\n true: {\n wrapper: 'shr-resize shr-overflow-auto',\n },\n false: {},\n },\n },\n})\n\nexport const ModelessDialog: FC<Props> = ({\n heading,\n children,\n contentBgColor,\n contentPadding,\n footer,\n isOpen,\n onPressEscape,\n resizable = false,\n width,\n size,\n height,\n top,\n left,\n right,\n bottom,\n portalParent,\n className,\n id,\n onClickClose,\n ...rest\n}) => {\n const labelId = useId()\n const lastFocusElementRef = useRef<HTMLElement | null>(null)\n const { createPortal } = useDialogPortal(portalParent, id)\n const { localize } = useIntl()\n\n const classNames = useMemo(() => {\n const { overlap, wrapper, headerEl, headingEl, dialogHandler, closeButtonLayout, footerEl } =\n classNameGenerator()\n\n return {\n overlap: overlap({ className }),\n wrapper: wrapper({ size, resizable }),\n header: headerEl(),\n heading: headingEl(),\n dialogHandler: dialogHandler(),\n closeButtonLayout: closeButtonLayout(),\n footer: footerEl(),\n }\n }, [className, size, resizable])\n\n const wrapperRef = useRef<HTMLDivElement>(null)\n const focusTargetRef = useRef<HTMLDivElement>(null)\n\n const [wrapperPosition, setWrapperPosition] = useState<DOMRect | undefined>(undefined)\n const [debouncedLiveRegionText, setDebouncedLiveRegionText] = useState<string>('')\n const [centering, setCentering] = useState<{\n top?: number\n left?: number\n }>({})\n const [position, setPosition] = useState<{ x: number; y: number }>({\n x: 0,\n y: 0,\n })\n const [draggableBounds, setDraggableBounds] = useState(Draggable.defaultProps.bounds)\n\n const positionStyle = useMemo(\n () => ({\n top: centering.top ?? top,\n left: centering.left ?? left,\n right,\n bottom,\n width: size ? undefined : width,\n height,\n }),\n [centering, top, left, right, bottom, width, height, size],\n )\n\n const latest = useLatest({ isOpen, onClickClose, onPressEscape })\n\n const functions = useMemo(\n () => ({\n debounceLiveRegionText: debounce(setDebouncedLiveRegionText, 600),\n handleArrowKeyDown: (e: KeyboardEvent) => {\n if (!latest.isOpen || document.activeElement !== e.currentTarget) {\n return\n }\n\n const movingDistance = 20\n\n switch (e.key) {\n case 'ArrowUp':\n setPosition((prev) => ({\n x: prev.x,\n y: prev.y - movingDistance,\n }))\n e.preventDefault()\n break\n case 'ArrowDown':\n setPosition((prev) => ({\n x: prev.x,\n y: prev.y + movingDistance,\n }))\n e.preventDefault()\n break\n case 'ArrowLeft':\n setPosition((prev) => ({\n x: prev.x - movingDistance,\n y: prev.y,\n }))\n e.preventDefault()\n break\n case 'ArrowRight':\n setPosition((prev) => ({\n x: prev.x + movingDistance,\n y: prev.y,\n }))\n e.preventDefault()\n break\n }\n },\n handleClickClose: (e: MouseEvent<HTMLButtonElement>) => {\n lastFocusElementRef.current?.focus()\n latest.onClickClose?.(e)\n },\n handlePressEscape: () => {\n lastFocusElementRef.current?.focus()\n latest.onPressEscape?.()\n },\n handleDragStart: (_: any, data: { x: number; y: number }) => setPosition(data),\n handleDrag: (_: any, data: { deltaX: number; deltaY: number }) => {\n setPosition((prev) => ({\n x: prev.x + data.deltaX,\n y: prev.y + data.deltaY,\n }))\n },\n }),\n [latest],\n )\n\n useEffect(() => {\n if (!wrapperPosition) {\n setDebouncedLiveRegionText('')\n return functions.debounceLiveRegionText.cancel\n }\n\n const txt = localize(\n {\n id: 'smarthr-ui/ModelessDialog/dialogHandlerLiveRegionText',\n defaultText: '上から{top}px、左から{left}px',\n },\n {\n top: Math.trunc(wrapperPosition.top).toString(),\n left: Math.trunc(wrapperPosition.left).toString(),\n },\n )\n\n functions.debounceLiveRegionText(txt)\n\n return functions.debounceLiveRegionText.cancel\n }, [localize, wrapperPosition, functions])\n\n useEffect(() => {\n if (wrapperRef.current instanceof Element) {\n setWrapperPosition(wrapperRef.current.getBoundingClientRect())\n }\n }, [position])\n\n useEffect(() => {\n // 中央寄せの座標計算を行う\n if (!wrapperRef.current || !isOpen) {\n return\n }\n\n const isXCenter = left === undefined && right === undefined\n const isYCenter = top === undefined && bottom === undefined\n\n if (isXCenter || isYCenter) {\n const rect = wrapperRef.current.getBoundingClientRect()\n\n setCentering({\n top: isYCenter ? Math.max(0, window.innerHeight / 2 - rect.height / 2) : undefined,\n left: isXCenter ? Math.max(0, window.innerWidth / 2 - rect.width / 2) : undefined,\n })\n }\n }, [bottom, isOpen, left, right, top])\n\n useEffect(() => {\n if (!isOpen) return\n\n if (centering.top) {\n setDraggableBounds({ top: centering.top * -1 })\n\n return\n }\n\n if (wrapperRef.current) {\n const rect = wrapperRef.current.getBoundingClientRect()\n\n setDraggableBounds({ top: rect.top * -1 })\n }\n }, [isOpen, centering.top])\n\n useEffect(() => {\n if (isOpen) {\n setPosition({ x: 0, y: 0 })\n focusTargetRef.current?.focus()\n }\n }, [isOpen])\n\n useHandleEscape(isOpen ? functions.handlePressEscape : undefined)\n\n useEffect(() => {\n const focusHandler = (e: FocusEvent) => {\n // e.target(現在フォーカスがあたっている要素)がModeless dialog外の要素であれば、lastFocusElementRefに代入する\n if (e.target instanceof HTMLElement && !wrapperRef?.current?.contains(e.target)) {\n lastFocusElementRef.current = e.target\n }\n }\n\n document.addEventListener('focus', focusHandler, true)\n\n return () => document.removeEventListener('focus', focusHandler, true)\n }, [])\n\n return createPortal(\n <DialogOverlap isOpen={isOpen} className={classNames.overlap} as=\"section\">\n <Draggable\n {...Draggable.defaultProps}\n handle=\".smarthr-ui-ModelessDialog-handle\"\n onStart={functions.handleDragStart}\n onDrag={functions.handleDrag}\n position={position}\n bounds={draggableBounds ?? false}\n nodeRef={wrapperRef}\n >\n <Panel\n {...rest}\n ref={wrapperRef}\n role=\"dialog\"\n aria-labelledby={labelId}\n radius=\"m\"\n layer={3}\n overflow=\"auto\"\n className={classNames.wrapper}\n style={positionStyle}\n >\n {/* eslint-disable-next-line smarthr/a11y-scroller-has-tabindex -- dummy element for focus management. */}\n <div tabIndex={-1} ref={focusTargetRef} />\n <div className={classNames.header}>\n <Handler\n handleArrowKeyDown={functions.handleArrowKeyDown}\n className={classNames.dialogHandler}\n />\n <div id={labelId} className={classNames.heading}>\n {/* eslint-disable-next-line smarthr/a11y-heading-in-sectioning-content */}\n <Heading>{heading}</Heading>\n </div>\n <CloseButton\n handleClick={functions.handleClickClose}\n className={classNames.closeButtonLayout}\n />\n </div>\n <DialogBody\n contentBgColor={contentBgColor}\n contentPadding={contentPadding}\n className=\"smarthr-ui-ModelessDialog-content shr-overscroll-contain\"\n >\n {children}\n </DialogBody>\n {footer && <div className={classNames.footer}>{footer}</div>}\n <LiveRegion regionText={debouncedLiveRegionText} />\n </Panel>\n </Draggable>\n </DialogOverlap>,\n )\n}\n\nconst Handler = memo<{\n className: string\n handleArrowKeyDown: (e: KeyboardEvent) => void\n}>(({ handleArrowKeyDown, ...rest }) => {\n const { localize } = useIntl()\n\n return (\n <>\n <button\n {...rest}\n type=\"button\"\n aria-label={localize({\n id: 'smarthr-ui/ModelessDialog/dialogHandlerAriaLabel',\n defaultText: 'ダイアログの位置',\n })}\n aria-roledescription={localize({\n id: 'smarthr-ui/ModelessDialog/dialogHandlerAriaRoleDescription',\n defaultText: 'ドラッグ可能',\n })}\n aria-describedby=\"handler-description\"\n onKeyDown={handleArrowKeyDown}\n >\n <FaGripIcon />\n </button>\n <div className=\"shr-hidden\" id=\"handler-description\">\n {localize({\n id: 'smarthr-ui/ModelessDialog/dialogHandlerDescription',\n defaultText: '矢印キーを押して上下左右に移動できます',\n })}\n </div>\n </>\n )\n})\n\nconst LiveRegion = ({ regionText }: { regionText: string | undefined }) => (\n <div\n role=\"status\"\n className=\"shr-fixed -shr-m-px shr-h-px shr-w-px shr-overflow-hidden shr-whitespace-nowrap\"\n >\n {regionText}\n </div>\n)\n\nconst CloseButton = memo<{\n className: string\n handleClick: (e: MouseEvent<HTMLButtonElement>) => void\n}>(({ handleClick, className }) => (\n <div className={className}>\n <Button\n type=\"button\"\n size=\"S\"\n onClick={handleClick}\n className=\"smarthr-ui-ModelessDialog-closeButton\"\n >\n <FaXmarkIcon\n alt={<Localizer id=\"smarthr-ui/ModelessDialog/closeButtonIconAlt\" defaultText=\"閉じる\" />}\n />\n </Button>\n </div>\n))\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FA;AACE;AACE;AACA;AAEA;;;;;AAKC;AACD;;;AAGC;;AAED;AACE;;AAED;AACD;AACD;AACD;AACE;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACD;AACD;AACE;AACE;AACD;AACD;AACD;AACF;AACF;;AAwBC;AACA;;AAEA;AAEA;AACE;;AAIE;;;;;;;;;AAUJ;AACA;;;;AAQA;AACE;AACA;AACD;AACD;AAEA;AAEI;AACA;;;;;AAKD;AAIH;AAEA;AAEI;AACA;AACE;;;;AAMA;AACE;AACE;;AAEE;AACD;;;AAGH;AACE;;AAEE;AACD;;;AAGH;AACE;AACE;;AAED;;;AAGH;AACE;AACE;;AAED;;;;;AAKP;AACE;AACA;;;AAGA;AACA;;;AAGF;AACE;AACE;AACA;AACD;;AAEJ;;;;AAOC;;;AAKE;AACA;;;;AAKD;AAGH;AAEA;;;AAIA;;;AAGF;;;;;;;;AAWE;;AAGE;;;AAGC;;AAEL;;AAGE;;AAEA;AACE;;;AAKF;;AAGE;;;;;;AAOA;;AAEJ;AAEA;;AAGE;;AAEE;AACE;;AAEJ;;AAIA;;;AAsDJ;AAEA;AAIE;;AAQQ;AACA;;AAGA;AACA;;AASA;AACA;;AAKV;AAEA;AASA;;"}
|
|
@@ -7,7 +7,7 @@ var hooks_useLatest = require('../../../hooks/useLatest.cjs');
|
|
|
7
7
|
var components_Input_Input = require('../Input.cjs');
|
|
8
8
|
var components_Input_CurrencyInput_currencyInputHelper = require('./currencyInputHelper.cjs');
|
|
9
9
|
|
|
10
|
-
const CurrencyInput = React.forwardRef(({ onFormatValue, onFocus, onBlur, value, defaultValue, className
|
|
10
|
+
const CurrencyInput = React.forwardRef(({ onFormatValue, onFocus, onBlur, value, defaultValue, className, ...rest }, ref) => {
|
|
11
11
|
const innerRef = React.useRef(null);
|
|
12
12
|
const [isFocused, setIsFocused] = React.useState(false);
|
|
13
13
|
const latest = hooks_useLatest.useLatest({
|
|
@@ -60,7 +60,7 @@ const CurrencyInput = React.forwardRef(({ onFormatValue, onFocus, onBlur, value,
|
|
|
60
60
|
}
|
|
61
61
|
}
|
|
62
62
|
}, [isFocused, value, functions]);
|
|
63
|
-
return (jsxRuntime.jsx(components_Input_Input.Input, { ...rest, type: "text", value: value, defaultValue: defaultValue, onFocus: functions.handleFocus, onBlur: functions.handleBlur,
|
|
63
|
+
return (jsxRuntime.jsx(components_Input_Input.Input, { ...rest, ref: innerRef, type: "text", value: value, defaultValue: defaultValue, onFocus: functions.handleFocus, onBlur: functions.handleBlur, className: `smarthr-ui-CurrencyInput${className ? ` ${className}` : ''}` }));
|
|
64
64
|
});
|
|
65
65
|
|
|
66
66
|
exports.CurrencyInput = CurrencyInput;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CurrencyInput.cjs","sources":["../../../../src/components/Input/CurrencyInput/CurrencyInput.tsx"],"sourcesContent":["'use client'\n\nimport {\n type ComponentProps,\n type FocusEvent,\n forwardRef,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n} from 'react'\n\nimport { useLatest } from '../../../hooks/useLatest'\nimport { Input } from '../Input'\n\nimport { formatCurrency } from './currencyInputHelper'\n\ntype Props = Omit<ComponentProps<typeof Input>, 'type' | 'value' | 'defaultValue'> & {\n /** 通貨の値 */\n value?: string\n /** デフォルトで表示する通貨の値 */\n defaultValue?: string\n /** 入力値がフォーマットされたときに発火するコールバック関数 */\n onFormatValue?: (value: string) => void\n}\n\nexport const CurrencyInput = forwardRef<HTMLInputElement, Props>(\n ({ onFormatValue, onFocus, onBlur, value, defaultValue, className
|
|
1
|
+
{"version":3,"file":"CurrencyInput.cjs","sources":["../../../../src/components/Input/CurrencyInput/CurrencyInput.tsx"],"sourcesContent":["'use client'\n\nimport {\n type ComponentProps,\n type FocusEvent,\n forwardRef,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n} from 'react'\n\nimport { useLatest } from '../../../hooks/useLatest'\nimport { Input } from '../Input'\n\nimport { formatCurrency } from './currencyInputHelper'\n\ntype Props = Omit<ComponentProps<typeof Input>, 'type' | 'value' | 'defaultValue'> & {\n /** 通貨の値 */\n value?: string\n /** デフォルトで表示する通貨の値 */\n defaultValue?: string\n /** 入力値がフォーマットされたときに発火するコールバック関数 */\n onFormatValue?: (value: string) => void\n}\n\nexport const CurrencyInput = forwardRef<HTMLInputElement, Props>(\n ({ onFormatValue, onFocus, onBlur, value, defaultValue, className, ...rest }, ref) => {\n const innerRef = useRef<HTMLInputElement>(null)\n const [isFocused, setIsFocused] = useState(false)\n\n const latest = useLatest({\n onFocus,\n onBlur,\n onFormatValue,\n })\n\n const functions = useMemo(() => {\n const formatValue = (formatted = '') => {\n if (innerRef.current && formatted !== innerRef.current.value) {\n innerRef.current.value = formatted\n latest.onFormatValue?.(formatted)\n }\n }\n\n return {\n formatCurrencyValue: (raw = '') => {\n formatValue(formatCurrency(raw))\n },\n handleFocus: (e: FocusEvent<HTMLInputElement>) => {\n setIsFocused(true)\n\n if (innerRef.current) {\n const commaExcluded = innerRef.current.value.replace(/,/g, '')\n formatValue(commaExcluded)\n }\n\n latest.onFocus?.(e)\n },\n handleBlur: (e: FocusEvent<HTMLInputElement>) => {\n setIsFocused(false)\n\n latest.onBlur?.(e)\n },\n }\n }, [latest])\n\n useImperativeHandle<HTMLInputElement | null, HTMLInputElement | null>(\n ref,\n () => innerRef.current,\n [],\n )\n\n useEffect(() => {\n if (value === undefined && defaultValue !== undefined) {\n functions.formatCurrencyValue(defaultValue)\n }\n // when component did mount\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n useEffect(() => {\n if (!isFocused) {\n if (value !== undefined) {\n // for controlled component\n functions.formatCurrencyValue(value)\n } else if (innerRef.current) {\n // for uncontrolled component\n functions.formatCurrencyValue(innerRef.current.value)\n }\n }\n }, [isFocused, value, functions])\n\n return (\n <Input\n {...rest}\n ref={innerRef}\n type=\"text\"\n value={value}\n defaultValue={defaultValue}\n onFocus={functions.handleFocus}\n onBlur={functions.handleBlur}\n className={`smarthr-ui-CurrencyInput${className ? ` ${className}` : ''}`}\n />\n )\n },\n)\n"],"names":[],"mappings":";;;;;;;;;AA2BO;AAEH;;;;;;AAOC;AAED;AACE;AACE;AACE;AACA;;AAEJ;;AAGE;AACE;;AAEF;;AAGE;AACE;;;AAIF;;AAEF;;AAGE;;;AAGN;AAEA;;;AAQI;;;;;;;AAQA;;AAEE;;AACK;;;;;;;AAmBb;;"}
|
|
@@ -5,7 +5,7 @@ import { useLatest } from '../../../hooks/useLatest.js';
|
|
|
5
5
|
import { Input } from '../Input.js';
|
|
6
6
|
import { formatCurrency } from './currencyInputHelper.js';
|
|
7
7
|
|
|
8
|
-
const CurrencyInput = forwardRef(({ onFormatValue, onFocus, onBlur, value, defaultValue, className
|
|
8
|
+
const CurrencyInput = forwardRef(({ onFormatValue, onFocus, onBlur, value, defaultValue, className, ...rest }, ref) => {
|
|
9
9
|
const innerRef = useRef(null);
|
|
10
10
|
const [isFocused, setIsFocused] = useState(false);
|
|
11
11
|
const latest = useLatest({
|
|
@@ -58,7 +58,7 @@ const CurrencyInput = forwardRef(({ onFormatValue, onFocus, onBlur, value, defau
|
|
|
58
58
|
}
|
|
59
59
|
}
|
|
60
60
|
}, [isFocused, value, functions]);
|
|
61
|
-
return (jsx(Input, { ...rest, type: "text", value: value, defaultValue: defaultValue, onFocus: functions.handleFocus, onBlur: functions.handleBlur,
|
|
61
|
+
return (jsx(Input, { ...rest, ref: innerRef, type: "text", value: value, defaultValue: defaultValue, onFocus: functions.handleFocus, onBlur: functions.handleBlur, className: `smarthr-ui-CurrencyInput${className ? ` ${className}` : ''}` }));
|
|
62
62
|
});
|
|
63
63
|
|
|
64
64
|
export { CurrencyInput };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CurrencyInput.js","sources":["../../../../src/components/Input/CurrencyInput/CurrencyInput.tsx"],"sourcesContent":["'use client'\n\nimport {\n type ComponentProps,\n type FocusEvent,\n forwardRef,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n} from 'react'\n\nimport { useLatest } from '../../../hooks/useLatest'\nimport { Input } from '../Input'\n\nimport { formatCurrency } from './currencyInputHelper'\n\ntype Props = Omit<ComponentProps<typeof Input>, 'type' | 'value' | 'defaultValue'> & {\n /** 通貨の値 */\n value?: string\n /** デフォルトで表示する通貨の値 */\n defaultValue?: string\n /** 入力値がフォーマットされたときに発火するコールバック関数 */\n onFormatValue?: (value: string) => void\n}\n\nexport const CurrencyInput = forwardRef<HTMLInputElement, Props>(\n ({ onFormatValue, onFocus, onBlur, value, defaultValue, className
|
|
1
|
+
{"version":3,"file":"CurrencyInput.js","sources":["../../../../src/components/Input/CurrencyInput/CurrencyInput.tsx"],"sourcesContent":["'use client'\n\nimport {\n type ComponentProps,\n type FocusEvent,\n forwardRef,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n} from 'react'\n\nimport { useLatest } from '../../../hooks/useLatest'\nimport { Input } from '../Input'\n\nimport { formatCurrency } from './currencyInputHelper'\n\ntype Props = Omit<ComponentProps<typeof Input>, 'type' | 'value' | 'defaultValue'> & {\n /** 通貨の値 */\n value?: string\n /** デフォルトで表示する通貨の値 */\n defaultValue?: string\n /** 入力値がフォーマットされたときに発火するコールバック関数 */\n onFormatValue?: (value: string) => void\n}\n\nexport const CurrencyInput = forwardRef<HTMLInputElement, Props>(\n ({ onFormatValue, onFocus, onBlur, value, defaultValue, className, ...rest }, ref) => {\n const innerRef = useRef<HTMLInputElement>(null)\n const [isFocused, setIsFocused] = useState(false)\n\n const latest = useLatest({\n onFocus,\n onBlur,\n onFormatValue,\n })\n\n const functions = useMemo(() => {\n const formatValue = (formatted = '') => {\n if (innerRef.current && formatted !== innerRef.current.value) {\n innerRef.current.value = formatted\n latest.onFormatValue?.(formatted)\n }\n }\n\n return {\n formatCurrencyValue: (raw = '') => {\n formatValue(formatCurrency(raw))\n },\n handleFocus: (e: FocusEvent<HTMLInputElement>) => {\n setIsFocused(true)\n\n if (innerRef.current) {\n const commaExcluded = innerRef.current.value.replace(/,/g, '')\n formatValue(commaExcluded)\n }\n\n latest.onFocus?.(e)\n },\n handleBlur: (e: FocusEvent<HTMLInputElement>) => {\n setIsFocused(false)\n\n latest.onBlur?.(e)\n },\n }\n }, [latest])\n\n useImperativeHandle<HTMLInputElement | null, HTMLInputElement | null>(\n ref,\n () => innerRef.current,\n [],\n )\n\n useEffect(() => {\n if (value === undefined && defaultValue !== undefined) {\n functions.formatCurrencyValue(defaultValue)\n }\n // when component did mount\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n useEffect(() => {\n if (!isFocused) {\n if (value !== undefined) {\n // for controlled component\n functions.formatCurrencyValue(value)\n } else if (innerRef.current) {\n // for uncontrolled component\n functions.formatCurrencyValue(innerRef.current.value)\n }\n }\n }, [isFocused, value, functions])\n\n return (\n <Input\n {...rest}\n ref={innerRef}\n type=\"text\"\n value={value}\n defaultValue={defaultValue}\n onFocus={functions.handleFocus}\n onBlur={functions.handleBlur}\n className={`smarthr-ui-CurrencyInput${className ? ` ${className}` : ''}`}\n />\n )\n },\n)\n"],"names":[],"mappings":";;;;;;;AA2BO;AAEH;;;;;;AAOC;AAED;AACE;AACE;AACE;AACA;;AAEJ;;AAGE;AACE;;AAEF;;AAGE;AACE;;;AAIF;;AAEF;;AAGE;;;AAGN;AAEA;;;AAQI;;;;;;;AAQA;;AAEE;;AACK;;;;;;;AAmBb;;"}
|