@ahrowe/ui 0.51.0 → 0.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +1 -0
  3. package/dist/cjs-types/common/actionIcon/actionIcon.types.d.ts +10 -6
  4. package/dist/cjs-types/common/ahroweProvider/ahroweProvider.d.ts +1 -1
  5. package/dist/cjs-types/common/button/button.types.d.ts +25 -8
  6. package/dist/cjs-types/common/configProvider/configProvider.d.ts +2 -1
  7. package/dist/cjs-types/common/configProvider/configProvider.types.d.ts +8 -0
  8. package/dist/cjs-types/common/copyButton/copyButton.types.d.ts +4 -1
  9. package/dist/cjs-types/common/listItem/index.d.ts +2 -0
  10. package/dist/cjs-types/common/listItem/listItem.d.ts +4 -0
  11. package/dist/cjs-types/common/listItem/listItem.types.d.ts +33 -0
  12. package/dist/cjs-types/common/menu/menu.types.d.ts +2 -2
  13. package/dist/cjs-types/common/menu/menuItem.d.ts +5 -2
  14. package/dist/cjs-types/common/otpInput/otpInput.types.d.ts +1 -1
  15. package/dist/cjs-types/common/themeProvider/theme.types.d.ts +4 -0
  16. package/dist/cjs-types/common/utils/navigation.d.ts +12 -0
  17. package/dist/cjs-types/index.d.ts +3 -1
  18. package/dist/cjs-types/services/formValidation/index.d.ts +1 -1
  19. package/dist/cjs-types/services/formValidation/useFormValidatorGroup.d.ts +1 -1
  20. package/dist/esm/common/ahroweProvider/ahroweProvider.mjs +1 -1
  21. package/dist/esm/common/ahroweProvider/ahroweProvider.mjs.map +1 -1
  22. package/dist/esm/common/breadcrumb/breadcrumb.mjs +1 -1
  23. package/dist/esm/common/breadcrumb/breadcrumb.mjs.map +1 -1
  24. package/dist/esm/common/button/button.mjs +1 -1
  25. package/dist/esm/common/button/button.mjs.map +1 -1
  26. package/dist/esm/common/button/button.module.mjs +1 -1
  27. package/dist/esm/common/button/button.module.mjs.map +1 -1
  28. package/dist/esm/common/button/button.types.mjs.map +1 -1
  29. package/dist/esm/common/commandPalette/commandPalette.mjs +1 -1
  30. package/dist/esm/common/commandPalette/commandPalette.mjs.map +1 -1
  31. package/dist/esm/common/configProvider/configProvider.mjs +1 -1
  32. package/dist/esm/common/configProvider/configProvider.mjs.map +1 -1
  33. package/dist/esm/common/datePicker/datePicker.mjs +1 -1
  34. package/dist/esm/common/datePicker/datePicker.mjs.map +1 -1
  35. package/dist/esm/common/dropdown/dropdown.mjs +1 -1
  36. package/dist/esm/common/dropdown/dropdown.mjs.map +1 -1
  37. package/dist/esm/common/iconPicker/iconPicker.mjs +1 -1
  38. package/dist/esm/common/iconPicker/iconPicker.mjs.map +1 -1
  39. package/dist/esm/common/input/input.mjs +1 -1
  40. package/dist/esm/common/input/input.mjs.map +1 -1
  41. package/dist/esm/common/inputDropdown/inputDropdown.mjs +1 -1
  42. package/dist/esm/common/inputDropdown/inputDropdown.mjs.map +1 -1
  43. package/dist/esm/common/listItem/listItem.mjs +2 -0
  44. package/dist/esm/common/listItem/listItem.mjs.map +1 -0
  45. package/dist/esm/common/listItem/listItem.module.mjs +2 -0
  46. package/dist/esm/common/listItem/listItem.module.mjs.map +1 -0
  47. package/dist/esm/common/menu/menu.mjs +1 -1
  48. package/dist/esm/common/menu/menu.mjs.map +1 -1
  49. package/dist/esm/common/menu/menu.types.mjs.map +1 -1
  50. package/dist/esm/common/menu/menuItem.mjs +1 -1
  51. package/dist/esm/common/menu/menuItem.mjs.map +1 -1
  52. package/dist/esm/common/multiSelect/multiSelect.mjs +1 -1
  53. package/dist/esm/common/multiSelect/multiSelect.mjs.map +1 -1
  54. package/dist/esm/common/numberInput/numberInput.mjs +1 -1
  55. package/dist/esm/common/numberInput/numberInput.mjs.map +1 -1
  56. package/dist/esm/common/otpInput/otpInput.mjs +1 -1
  57. package/dist/esm/common/otpInput/otpInput.mjs.map +1 -1
  58. package/dist/esm/common/otpInput/otpInput.types.mjs.map +1 -1
  59. package/dist/esm/common/radioGroup/radioGroup.mjs +1 -1
  60. package/dist/esm/common/radioGroup/radioGroup.mjs.map +1 -1
  61. package/dist/esm/common/timeInput/timeInput.mjs +1 -1
  62. package/dist/esm/common/timeInput/timeInput.mjs.map +1 -1
  63. package/dist/esm/common/utils/navigation.mjs +2 -0
  64. package/dist/esm/common/utils/navigation.mjs.map +1 -0
  65. package/dist/esm/index.mjs +1 -1
  66. package/dist/esm/services/formValidation/useFormValidatorGroup.mjs +1 -1
  67. package/dist/esm/services/formValidation/useFormValidatorGroup.mjs.map +1 -1
  68. package/dist/esm/services/formValidation/validatableComponent.mjs +1 -1
  69. package/dist/esm/services/formValidation/validatableComponent.mjs.map +1 -1
  70. package/dist/index.cjs +5 -5
  71. package/dist/index.cjs.map +1 -1
  72. package/dist/style.css +1 -1
  73. package/dist/types/common/actionIcon/actionIcon.types.d.ts +10 -6
  74. package/dist/types/common/ahroweProvider/ahroweProvider.d.ts +1 -1
  75. package/dist/types/common/button/button.types.d.ts +25 -8
  76. package/dist/types/common/configProvider/configProvider.d.ts +2 -1
  77. package/dist/types/common/configProvider/configProvider.types.d.ts +8 -0
  78. package/dist/types/common/copyButton/copyButton.types.d.ts +4 -1
  79. package/dist/types/common/listItem/index.d.ts +2 -0
  80. package/dist/types/common/listItem/listItem.d.ts +4 -0
  81. package/dist/types/common/listItem/listItem.types.d.ts +33 -0
  82. package/dist/types/common/menu/menu.types.d.ts +2 -2
  83. package/dist/types/common/menu/menuItem.d.ts +5 -2
  84. package/dist/types/common/otpInput/otpInput.types.d.ts +1 -1
  85. package/dist/types/common/themeProvider/theme.types.d.ts +4 -0
  86. package/dist/types/common/utils/navigation.d.ts +12 -0
  87. package/dist/types/index.d.ts +3 -1
  88. package/dist/types/services/formValidation/index.d.ts +1 -1
  89. package/dist/types/services/formValidation/useFormValidatorGroup.d.ts +1 -1
  90. package/docs/ActionIcon.md +7 -3
  91. package/docs/AhroweProvider.md +2 -1
  92. package/docs/Breadcrumb.md +4 -24
  93. package/docs/Button.md +44 -9
  94. package/docs/CLAUDE.md +4 -0
  95. package/docs/CommandPalette.md +1 -1
  96. package/docs/ConfigProvider.md +34 -1
  97. package/docs/FormValidator.md +23 -1
  98. package/docs/FormValidatorGroup.md +5 -2
  99. package/docs/InputDropdown.md +1 -1
  100. package/docs/ListItem.md +97 -0
  101. package/docs/Menu.md +2 -2
  102. package/docs/MultiSelect.md +1 -1
  103. package/docs/OtpInput.md +1 -1
  104. package/docs/RadioGroup.md +1 -1
  105. package/docs/ScrollbarProvider.md +1 -1
  106. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"input.mjs","names":[],"sources":["../../../../package/common/input/input.tsx"],"sourcesContent":["import React, { useState, useEffect, useRef, useId } from 'react';\nimport cx from 'classnames';\nimport { FontAwesomeIcon } from '@fortawesome/react-fontawesome';\nimport {\n faPhone,\n faPen,\n faEnvelope,\n faSearch,\n faXmark,\n faEye as passwordHiddenIcon,\n faEyeSlash as passwordShownIcon,\n} from '@fortawesome/free-solid-svg-icons';\nimport type { IconDefinition } from '@fortawesome/fontawesome-svg-core';\nimport Tooltip from 'components/common/tooltip';\nimport AnimatedIcon from 'components/common/animatedIcon';\nimport { useComponentDefaults, useLabels } from 'components/common/configProvider';\nimport styles from './input.module.pcss';\nimport { mergeRefs } from '../utils/mergeRefs';\nimport { useAutoGrow } from '../hooks/useAutoGrow';\nimport type { InputLabels, InputProps } from './input.types';\nimport { InputType, InputIconPosition } from './input.types';\n\nconst DEFAULT_LABELS: Required<InputLabels> = {\n clear: 'Clear',\n showPassword: 'Show password',\n hidePassword: 'Hide password',\n clearSearch: 'Clear search',\n};\n\nconst TYPE_ICONS: Partial<Record<InputType, IconDefinition>> = {\n [InputType.Phone]: faPhone,\n [InputType.Email]: faEnvelope,\n [InputType.Edit]: faPen,\n};\n\nfunction clickableIconProps(onActivate?: ((event: React.SyntheticEvent) => void) | null) {\n if (!onActivate) return undefined;\n return {\n role: 'button' as const,\n tabIndex: 0,\n // The icon sits inside the <label>, whose click focuses the field anyway. Letting mousedown\n // focus the icon first would hand the consumer a blur and a focus for a single click.\n onMouseDown: (event: React.MouseEvent) => event.preventDefault(),\n onKeyDown: (event: React.KeyboardEvent) => {\n if (event.key !== 'Enter' && event.key !== ' ') return;\n event.preventDefault();\n onActivate(event);\n },\n };\n}\n\nfunction Input(props: InputProps) {\n const {\n name = '',\n id,\n label = '',\n errorMessage = '',\n isValid = true,\n className = '',\n style,\n value = '',\n icon = null,\n iconPosition,\n onChange = () => {},\n onFocus: onFocusProp = null,\n onBlur: onBlurProp = null,\n onMouseEnter: onMouseEnterProp = null,\n onMouseLeave: onMouseLeaveProp = null,\n isUppercase = false,\n isRequired = false,\n tabIndex = 0,\n type = undefined,\n isRow = false,\n onIconClick = null,\n parse = null,\n formValidator = null,\n autoFocus = false,\n suffix = null,\n upperRightLabel = null,\n labelInBorder = false,\n clearable = false,\n onClear,\n min = null,\n max = null,\n placeholder = '',\n useMatLabelStyle = true,\n alwaysFloatLabel = false,\n autoComplete = null,\n onClick = () => null,\n readOnly = false,\n customInput,\n multiline = false,\n rows,\n autoResize = false,\n classNames,\n styles: slotStyles,\n disabled = false,\n labels,\n ref,\n ...rest\n } = useComponentDefaults('Input', props);\n const text = useLabels('Input', labels, DEFAULT_LABELS);\n const [isFocused, setIsFocused] = useState(false);\n // Chrome fills a field on page load without firing anything React sees. The animation the\n // stylesheet binds to :-webkit-autofill is the only notification it gives.\n const [isAutofilled, setIsAutofilled] = useState(false);\n const [isHovered, setIsHovered] = useState(false);\n const [isPasswordShown, setIsPasswordShown] = useState(false);\n const [, forceUpdate] = useState(0);\n\n const inputRef = useRef<HTMLInputElement | HTMLTextAreaElement>(null);\n const fvRef = useRef(formValidator);\n\n const generatedId = useId();\n const inputId = id || name || generatedId;\n\n const currVal = formValidator ? formValidator.value : value;\n\n useAutoGrow(inputRef, currVal, { enabled: autoResize });\n\n useEffect(() => {\n if (autoFocus && inputRef.current) {\n setTimeout(() => {\n inputRef.current?.focus();\n }, 1);\n }\n }, [autoFocus]);\n\n useEffect(() => {\n fvRef.current = formValidator;\n const fv = fvRef.current;\n if (!fv) return;\n fv.label = label ?? '';\n fv.validate();\n const listener = () => forceUpdate((n) => n + 1);\n fv.registerOnUpdateListener(listener);\n return () => {\n fv.removeOnUpdateListener(listener);\n };\n }, [formValidator, label]);\n\n const hasError = (): boolean => {\n return formValidator ? formValidator.touched && formValidator.hasError() : !isValid || !!errorMessage;\n };\n\n const computedIsRequired = (): boolean => {\n return !!(\n isRequired ||\n (formValidator &&\n formValidator.validators.find((v) => (v as { validatorId?: string }).validatorId === 'required'))\n );\n };\n\n const onMouseEnterHandler = (event: React.MouseEvent) => {\n setIsHovered(true);\n if (onMouseEnterProp) onMouseEnterProp(event);\n };\n\n const onMouseLeaveHandler = (event: React.MouseEvent) => {\n setIsHovered(false);\n if (onMouseLeaveProp) onMouseLeaveProp(event);\n };\n\n const onFocusHandler = (event: React.FocusEvent) => {\n setIsFocused(true);\n if (onFocusProp) onFocusProp(event);\n };\n\n const onBlurHandler = (event: React.FocusEvent) => {\n if (fvRef.current) fvRef.current.touched = true;\n setIsFocused(false);\n if (onBlurProp) onBlurProp(event);\n };\n\n const onChangeHandler = (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement> | string): void => {\n let parsedEvent: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement> | undefined;\n let val: string;\n\n if (typeof event !== 'string') {\n parsedEvent = event;\n val = event.target.value;\n } else {\n val = event;\n }\n\n if (parse) val = parse(val);\n if (formValidator) formValidator.set(val);\n if (onChange) onChange(val, parsedEvent);\n };\n\n const getInputType = (): string | undefined => {\n if (type === InputType.Email) return undefined;\n if (type === InputType.Phone) return 'tel';\n if (type === InputType.Search) return 'search';\n if (type === 'password' && isPasswordShown) return 'text';\n return type;\n };\n\n const getInputMode = (): React.HTMLAttributes<HTMLInputElement>['inputMode'] => {\n if (type === InputType.Email) return 'email';\n if (type === InputType.Phone) return 'tel';\n if (type === InputType.Search) return 'search';\n return undefined;\n };\n\n const isFunctionalIconType = type === InputType.Search || type === InputType.Password;\n const hasCustomIcon = !!icon;\n const customIconApplies = hasCustomIcon && !isFunctionalIconType;\n\n const defaultsLeftWithoutMatLabel = type === InputType.Email || type === InputType.Phone || type === InputType.Search;\n const resolvedIconPosition =\n iconPosition ??\n (!useMatLabelStyle && defaultsLeftWithoutMatLabel ? InputIconPosition.Left : InputIconPosition.Right);\n const iconIsLeft = resolvedIconPosition === InputIconPosition.Left;\n\n const iconProps = {\n className: cx(styles.inputFieldIcon, {\n [styles.inputFieldIconNotClickable]: !onIconClick,\n [styles.inputFieldIconLeft]: iconIsLeft,\n }),\n onClick: onIconClick ?? undefined,\n ...clickableIconProps(onIconClick),\n };\n const typeIcon = type && !hasCustomIcon ? TYPE_ICONS[type] : undefined;\n\n const customIcon = icon as React.ReactElement<{ className?: string; onClick?: React.MouseEventHandler }> | null;\n const resolvedCustomIconClick = onIconClick ?? customIcon?.props.onClick;\n const renderedIcon =\n customIconApplies && customIcon\n ? React.cloneElement(customIcon, {\n className: cx(\n styles.inputFieldIcon,\n {\n [styles.inputFieldIconNotClickable]: !resolvedCustomIconClick,\n [styles.inputFieldIconLeft]: iconIsLeft,\n },\n customIcon.props.className,\n ),\n onClick: resolvedCustomIconClick,\n ...clickableIconProps(resolvedCustomIconClick as ((event: React.SyntheticEvent) => void) | undefined),\n })\n : null;\n\n const hasErr = hasError();\n\n let editedLabel = label;\n if (editedLabel && computedIsRequired()) editedLabel = `${editedLabel} *`;\n const requiredMark = computedIsRequired() ? <span className={styles.requiredMark}>*</span> : null;\n\n const showFocus = isFocused && !readOnly;\n const shouldFloatLabel =\n useMatLabelStyle && (alwaysFloatLabel || showFocus || currVal || isAutofilled || type === InputType.Date);\n\n const handleAutofillAnimation = (event: React.AnimationEvent) => {\n const { animationName } = event;\n if (animationName === styles.inputAutofillStart) {\n setIsAutofilled(true);\n // The field is controlled, so the commit this triggers would write `value` back over\n // what the browser just put there and blank it. Replay it as an ordinary change first.\n const filled = (event.currentTarget as HTMLInputElement).value;\n if (filled && filled !== String(currVal ?? '')) onChangeHandler(filled);\n return;\n }\n if (animationName === styles.inputAutofillEnd) {\n setIsAutofilled(false);\n return;\n }\n // Not ours. `onAnimationStart` arrives through `rest`, and the consumer must not receive\n // the two above: the `:not()` rule fires one of them on every mount.\n rest.onAnimationStart?.(event as React.AnimationEvent<HTMLInputElement>);\n };\n\n const canClear = !!currVal && !disabled && !readOnly;\n const isSearchCleared = type === InputType.Search && canClear;\n\n function togglePassword() {\n setIsPasswordShown(!isPasswordShown);\n }\n\n let fieldIcon: React.ReactNode = renderedIcon;\n if (type === InputType.Search) {\n fieldIcon = (\n <AnimatedIcon\n icon={isSearchCleared ? faXmark : faSearch}\n className={cx(styles.inputFieldIcon, {\n [styles.inputFieldIconNotClickable]: !isSearchCleared,\n [styles.inputFieldIconLeft]: iconIsLeft,\n })}\n onClick={isSearchCleared ? handleClear : undefined}\n {...clickableIconProps(isSearchCleared ? handleClear : undefined)}\n aria-label={isSearchCleared ? text.clearSearch : undefined}\n />\n );\n } else if (type === InputType.Password) {\n fieldIcon = (\n <FontAwesomeIcon\n icon={isPasswordShown ? passwordShownIcon : passwordHiddenIcon}\n className={cx(styles.inputFieldIcon, { [styles.inputFieldIconLeft]: iconIsLeft })}\n onClick={togglePassword}\n {...clickableIconProps(togglePassword)}\n aria-label={isPasswordShown ? text.hidePassword : text.showPassword}\n />\n );\n } else if (typeIcon) {\n fieldIcon = <FontAwesomeIcon icon={typeIcon} {...iconProps} />;\n }\n const hasLeftIcon = !!fieldIcon && iconIsLeft;\n\n const customInputProps = customInput?.props as { className?: string; style?: React.CSSProperties } | undefined;\n\n function handleClear() {\n if (formValidator) formValidator.set('');\n onChange?.('');\n onClear?.();\n // A key press would otherwise leave focus on a button that is about to vanish.\n inputRef.current?.focus();\n }\n\n return (\n <div\n className={cx(\n styles.input,\n { [styles.inputIconLeft]: hasLeftIcon, [styles.inputWithLabel]: useMatLabelStyle && !!label },\n className,\n )}\n style={style}\n >\n <label\n htmlFor={inputId}\n className={cx(styles.inputLabel, classNames?.label, {\n [styles.inputLabelColumn]: !isRow,\n [styles.inputLabelInBorder]: labelInBorder,\n })}\n style={slotStyles?.label}\n >\n {label && !useMatLabelStyle ? (\n <span className={styles.inputLabelText}>\n {label}\n {requiredMark}\n </span>\n ) : null}\n {upperRightLabel && (\n <div\n className={cx(styles.inputUpperRightLabel, classNames?.upperRightLabel)}\n style={slotStyles?.upperRightLabel}\n >\n {upperRightLabel}\n </div>\n )}\n <div\n className={cx(\n styles.inputContainer,\n {\n [styles.inputContainerMultiline]: multiline,\n [styles.inputContainerResizable]: multiline && !autoResize,\n [styles.inputContainerDisabled]: disabled,\n },\n classNames?.container,\n )}\n style={slotStyles?.container}\n onMouseEnter={onMouseEnterHandler}\n onMouseLeave={onMouseLeaveHandler}\n >\n {iconIsLeft && fieldIcon}\n {React.cloneElement(customInput || (multiline ? <textarea /> : <input />), {\n ...rest,\n className: cx(\n styles.inputField,\n {\n [styles.inputFieldUppercase]: isUppercase,\n [styles.inputFieldDate]: type === InputType.Date,\n [styles.inputFieldDefault]: type !== InputType.Date,\n [styles.inputFieldWithIconLeft]: hasLeftIcon,\n [styles.inputFieldMultiline]: multiline,\n [styles.inputFieldMultilineAutoResize]: multiline && autoResize,\n [styles.inputFieldReadOnly]: readOnly && !disabled,\n },\n classNames?.input,\n customInputProps?.className,\n ),\n style:\n customInputProps?.style || slotStyles?.input\n ? { ...customInputProps?.style, ...slotStyles?.input }\n : undefined,\n name,\n id: inputId,\n value: currVal,\n tabIndex,\n ref: customInput ? undefined : mergeRefs(inputRef, ref),\n onChange: onChangeHandler,\n onAnimationStart: handleAutofillAnimation,\n onFocus: onFocusHandler,\n onBlur: onBlurHandler,\n placeholder: !useMatLabelStyle ? placeholder : '',\n autoComplete,\n onClick,\n readOnly,\n disabled,\n ...(!multiline && { type: getInputType(), inputMode: rest.inputMode ?? getInputMode(), min, max }),\n ...(multiline && rows !== undefined && { rows }),\n })}\n {suffix && (\n <div className={cx(styles.inputFieldSuffix, classNames?.suffix)} style={slotStyles?.suffix}>\n {suffix}\n </div>\n )}\n {/* Mounted while empty too, so the first character grows it in rather than popping it in. */}\n {clearable && type !== InputType.Search && (\n <FontAwesomeIcon\n icon={faXmark}\n className={cx(styles.inputFieldIcon, styles.inputFieldIconClear, {\n [styles.inputFieldIconClearHidden]: !canClear,\n })}\n onClick={canClear ? handleClear : undefined}\n {...clickableIconProps(canClear ? handleClear : undefined)}\n aria-label={text.clear}\n />\n )}\n {!iconIsLeft && fieldIcon}\n </div>\n <fieldset\n className={cx(styles.inputFieldset, classNames?.fieldset, {\n [styles.inputContainerBorderFocused]: showFocus,\n [styles.inputContainerBorderSearchFocused]: type === InputType.Search && (showFocus || !!currVal),\n [styles.inputContainerBorderInvalid]: hasErr,\n [styles.inputContainerBorderError]: hasErr,\n })}\n style={slotStyles?.fieldset}\n >\n <legend\n className={cx(styles.inputFieldsetLegend, {\n [styles.inputFieldsetLegendActive]: shouldFloatLabel,\n })}\n >\n <span>{editedLabel}</span>\n </legend>\n </fieldset>\n {useMatLabelStyle && label && (\n <div\n className={cx(styles.inputMatLabel, {\n [styles.inputMatLabelFloating]: shouldFloatLabel,\n [styles.inputMatLabelMultiline]: multiline && !shouldFloatLabel,\n })}\n >\n {label}\n {requiredMark}\n </div>\n )}\n {useMatLabelStyle && placeholder && (\n <div\n className={cx(\n styles.inputPlaceholder,\n showFocus && !currVal && !isAutofilled && styles.inputPlaceholderShown,\n multiline && styles.inputPlaceholderMultiline,\n )}\n >\n {placeholder}\n </div>\n )}\n <Tooltip\n variant='error'\n message={formValidator ? formValidator.getCurrentErrorMessage() : errorMessage || ''}\n isVisible={hasErr && (isFocused || isHovered)}\n />\n </label>\n </div>\n );\n}\n\nexport default Input;\n"],"mappings":"kzBAsBA,IAAM,GAAwC,CAC5C,MAAO,QACP,aAAc,gBACd,aAAc,gBACd,YAAa,cACf,EAEM,GAAyD,EAC5D,EAAU,OAAQ,IAClB,E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W,EAAG,EAAO,iBAAkB,GAAY,MAAM,EAAG,MAAO,GAAY,OACjF,SAAA,CACE,CAAA,EAGN,IAAa,IAAS,EAAU,QAC/B,EAAC,EAAD,CACE,KAAM,GACN,UAAW,EAAG,EAAO,eAAgB,EAAO,oBAAqB,EAC9D,EAAO,2BAA4B,CAAC,CACvC,CAAC,EACD,QAAS,EAAW,EAAc,IAAA,GAClC,GAAI,EAAmB,EAAW,EAAc,IAAA,EAAS,EACzD,aAAY,EAAK,KAClB,CAAA,EAEF,CAAC,GAAc,CACb,IACL,EAAC,WAAD,CACE,UAAW,EAAG,EAAO,cAAe,GAAY,SAAU,EACvD,EAAO,6BAA8B,GACrC,EAAO,mCAAoC,IAAS,EAAU,SAAW,GAAa,CAAC,CAAC,IACxF,EAAO,6BAA8B,GACrC,EAAO,2BAA4B,CACtC,CAAC,EACD,MAAO,GAAY,SAEnB,SAAA,EAAC,SAAD,CACE,UAAW,EAAG,EAAO,oBAAqB,EACvC,EAAO,2BAA4B,CACtC,CAAC,EAED,SAAA,EAAC,OAAD,CAAA,SAAO,CAAkB,CAAA,CACnB,CAAA,CACA,CAAA,EACT,GAAoB,GACnB,EAAC,MAAD,CACE,UAAW,EAAG,EAAO,cAAe,EACjC,EAAO,uBAAwB,GAC/B,EAAO,wBAAyB,GAAa,CAAC,CACjD,CAAC,EAJH,SAAA,CAMG,EACA,EACE,IAEN,GAAoB,GACnB,EAAC,MAAD,CACE,UAAW,EACT,EAAO,iBACP,GAAa,CAAC,GAAW,CAAC,IAAgB,EAAO,sBACjD,GAAa,EAAO,yBACtB,EAEC,SAAA,CACE,CAAA,EAEP,EAAC,GAAD,CACE,QAAQ,QACR,QAAS,EAAgB,EAAc,uBAAuB,EAAI,IAAgB,GAClF,UAAW,IAAW,IAAa,GACpC,CAAA,CACI,GACJ,CAAA,CAET"}
1
+ {"version":3,"file":"input.mjs","names":[],"sources":["../../../../package/common/input/input.tsx"],"sourcesContent":["import React, { useState, useEffect, useRef, useId } from 'react';\nimport cx from 'classnames';\nimport { FontAwesomeIcon } from '@fortawesome/react-fontawesome';\nimport {\n faPhone,\n faPen,\n faEnvelope,\n faSearch,\n faXmark,\n faEye as passwordHiddenIcon,\n faEyeSlash as passwordShownIcon,\n} from '@fortawesome/free-solid-svg-icons';\nimport type { IconDefinition } from '@fortawesome/fontawesome-svg-core';\nimport Tooltip from 'components/common/tooltip';\nimport AnimatedIcon from 'components/common/animatedIcon';\nimport { useComponentDefaults, useLabels } from 'components/common/configProvider';\nimport styles from './input.module.pcss';\nimport { mergeRefs } from '../utils/mergeRefs';\nimport { useAutoGrow } from '../hooks/useAutoGrow';\nimport type { InputLabels, InputProps } from './input.types';\nimport { InputType, InputIconPosition } from './input.types';\n\nconst DEFAULT_LABELS: Required<InputLabels> = {\n clear: 'Clear',\n showPassword: 'Show password',\n hidePassword: 'Hide password',\n clearSearch: 'Clear search',\n};\n\nconst TYPE_ICONS: Partial<Record<InputType, IconDefinition>> = {\n [InputType.Phone]: faPhone,\n [InputType.Email]: faEnvelope,\n [InputType.Edit]: faPen,\n};\n\nfunction clickableIconProps(onActivate?: ((event: React.SyntheticEvent) => void) | null) {\n if (!onActivate) return undefined;\n return {\n role: 'button' as const,\n tabIndex: 0,\n // The icon sits inside the <label>, whose click focuses the field anyway. Letting mousedown\n // focus the icon first would hand the consumer a blur and a focus for a single click.\n onMouseDown: (event: React.MouseEvent) => event.preventDefault(),\n onKeyDown: (event: React.KeyboardEvent) => {\n if (event.key !== 'Enter' && event.key !== ' ') return;\n event.preventDefault();\n onActivate(event);\n },\n };\n}\n\nfunction Input(props: InputProps) {\n const {\n name = '',\n id,\n label = '',\n errorMessage = '',\n isValid = true,\n className = '',\n style,\n value = '',\n icon = null,\n iconPosition,\n onChange = () => {},\n onFocus: onFocusProp = null,\n onBlur: onBlurProp = null,\n onMouseEnter: onMouseEnterProp = null,\n onMouseLeave: onMouseLeaveProp = null,\n isUppercase = false,\n isRequired = false,\n tabIndex = 0,\n type = undefined,\n isRow = false,\n onIconClick = null,\n parse = null,\n formValidator = null,\n autoFocus = false,\n suffix = null,\n upperRightLabel = null,\n labelInBorder = false,\n clearable = false,\n onClear,\n min = null,\n max = null,\n placeholder = '',\n useMatLabelStyle = true,\n alwaysFloatLabel = false,\n autoComplete = null,\n onClick = () => null,\n readOnly = false,\n customInput,\n multiline = false,\n rows,\n autoResize = false,\n classNames,\n styles: slotStyles,\n disabled = false,\n labels,\n ref,\n ...rest\n } = useComponentDefaults('Input', props);\n const text = useLabels('Input', labels, DEFAULT_LABELS);\n const [isFocused, setIsFocused] = useState(false);\n // Chrome fills a field on page load without firing anything React sees. The animation the\n // stylesheet binds to :-webkit-autofill is the only notification it gives.\n const [isAutofilled, setIsAutofilled] = useState(false);\n const [isHovered, setIsHovered] = useState(false);\n const [isPasswordShown, setIsPasswordShown] = useState(false);\n const [, forceUpdate] = useState(0);\n\n const inputRef = useRef<HTMLInputElement | HTMLTextAreaElement>(null);\n const fvRef = useRef(formValidator);\n\n const generatedId = useId();\n const inputId = id || name || generatedId;\n\n const currVal = formValidator ? formValidator.value : value;\n\n useAutoGrow(inputRef, currVal, { enabled: autoResize });\n\n useEffect(() => {\n if (autoFocus && inputRef.current) {\n setTimeout(() => {\n inputRef.current?.focus();\n }, 1);\n }\n }, [autoFocus]);\n\n useEffect(() => {\n fvRef.current = formValidator;\n const fv = fvRef.current;\n if (!fv) return;\n fv.label = label ?? '';\n fv.validate();\n const listener = () => forceUpdate((n) => n + 1);\n fv.registerOnUpdateListener(listener);\n return () => {\n fv.removeOnUpdateListener(listener);\n };\n }, [formValidator, label]);\n\n const hasError = (): boolean => {\n return formValidator ? formValidator.shouldShowError : !isValid || !!errorMessage;\n };\n\n const computedIsRequired = (): boolean => {\n return !!(\n isRequired ||\n (formValidator &&\n formValidator.validators.find((v) => (v as { validatorId?: string }).validatorId === 'required'))\n );\n };\n\n const onMouseEnterHandler = (event: React.MouseEvent) => {\n setIsHovered(true);\n if (onMouseEnterProp) onMouseEnterProp(event);\n };\n\n const onMouseLeaveHandler = (event: React.MouseEvent) => {\n setIsHovered(false);\n if (onMouseLeaveProp) onMouseLeaveProp(event);\n };\n\n const onFocusHandler = (event: React.FocusEvent) => {\n setIsFocused(true);\n if (onFocusProp) onFocusProp(event);\n };\n\n const onBlurHandler = (event: React.FocusEvent) => {\n if (fvRef.current) fvRef.current.touched = true;\n setIsFocused(false);\n if (onBlurProp) onBlurProp(event);\n };\n\n const onChangeHandler = (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement> | string): void => {\n let parsedEvent: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement> | undefined;\n let val: string;\n\n if (typeof event !== 'string') {\n parsedEvent = event;\n val = event.target.value;\n } else {\n val = event;\n }\n\n if (parse) val = parse(val);\n if (formValidator) formValidator.set(val);\n if (onChange) onChange(val, parsedEvent);\n };\n\n const getInputType = (): string | undefined => {\n if (type === InputType.Email) return undefined;\n if (type === InputType.Phone) return 'tel';\n if (type === InputType.Search) return 'search';\n if (type === 'password' && isPasswordShown) return 'text';\n return type;\n };\n\n const getInputMode = (): React.HTMLAttributes<HTMLInputElement>['inputMode'] => {\n if (type === InputType.Email) return 'email';\n if (type === InputType.Phone) return 'tel';\n if (type === InputType.Search) return 'search';\n return undefined;\n };\n\n const isFunctionalIconType = type === InputType.Search || type === InputType.Password;\n const hasCustomIcon = !!icon;\n const customIconApplies = hasCustomIcon && !isFunctionalIconType;\n\n const defaultsLeftWithoutMatLabel = type === InputType.Email || type === InputType.Phone || type === InputType.Search;\n const resolvedIconPosition =\n iconPosition ??\n (!useMatLabelStyle && defaultsLeftWithoutMatLabel ? InputIconPosition.Left : InputIconPosition.Right);\n const iconIsLeft = resolvedIconPosition === InputIconPosition.Left;\n\n const iconProps = {\n className: cx(styles.inputFieldIcon, {\n [styles.inputFieldIconNotClickable]: !onIconClick,\n [styles.inputFieldIconLeft]: iconIsLeft,\n }),\n onClick: onIconClick ?? undefined,\n ...clickableIconProps(onIconClick),\n };\n const typeIcon = type && !hasCustomIcon ? TYPE_ICONS[type] : undefined;\n\n const customIcon = icon as React.ReactElement<{ className?: string; onClick?: React.MouseEventHandler }> | null;\n const resolvedCustomIconClick = onIconClick ?? customIcon?.props.onClick;\n const renderedIcon =\n customIconApplies && customIcon\n ? React.cloneElement(customIcon, {\n className: cx(\n styles.inputFieldIcon,\n {\n [styles.inputFieldIconNotClickable]: !resolvedCustomIconClick,\n [styles.inputFieldIconLeft]: iconIsLeft,\n },\n customIcon.props.className,\n ),\n onClick: resolvedCustomIconClick,\n ...clickableIconProps(resolvedCustomIconClick as ((event: React.SyntheticEvent) => void) | undefined),\n })\n : null;\n\n const hasErr = hasError();\n\n let editedLabel = label;\n if (editedLabel && computedIsRequired()) editedLabel = `${editedLabel} *`;\n const requiredMark = computedIsRequired() ? <span className={styles.requiredMark}>*</span> : null;\n\n const showFocus = isFocused && !readOnly;\n const shouldFloatLabel =\n useMatLabelStyle && (alwaysFloatLabel || showFocus || currVal || isAutofilled || type === InputType.Date);\n\n const handleAutofillAnimation = (event: React.AnimationEvent) => {\n const { animationName } = event;\n if (animationName === styles.inputAutofillStart) {\n setIsAutofilled(true);\n // The field is controlled, so the commit this triggers would write `value` back over\n // what the browser just put there and blank it. Replay it as an ordinary change first.\n const filled = (event.currentTarget as HTMLInputElement).value;\n if (filled && filled !== String(currVal ?? '')) onChangeHandler(filled);\n return;\n }\n if (animationName === styles.inputAutofillEnd) {\n setIsAutofilled(false);\n return;\n }\n // Not ours. `onAnimationStart` arrives through `rest`, and the consumer must not receive\n // the two above: the `:not()` rule fires one of them on every mount.\n rest.onAnimationStart?.(event as React.AnimationEvent<HTMLInputElement>);\n };\n\n const canClear = !!currVal && !disabled && !readOnly;\n const isSearchCleared = type === InputType.Search && canClear;\n\n function togglePassword() {\n setIsPasswordShown(!isPasswordShown);\n }\n\n let fieldIcon: React.ReactNode = renderedIcon;\n if (type === InputType.Search) {\n fieldIcon = (\n <AnimatedIcon\n icon={isSearchCleared ? faXmark : faSearch}\n className={cx(styles.inputFieldIcon, {\n [styles.inputFieldIconNotClickable]: !isSearchCleared,\n [styles.inputFieldIconLeft]: iconIsLeft,\n })}\n onClick={isSearchCleared ? handleClear : undefined}\n {...clickableIconProps(isSearchCleared ? handleClear : undefined)}\n aria-label={isSearchCleared ? text.clearSearch : undefined}\n />\n );\n } else if (type === InputType.Password) {\n fieldIcon = (\n <FontAwesomeIcon\n icon={isPasswordShown ? passwordShownIcon : passwordHiddenIcon}\n className={cx(styles.inputFieldIcon, { [styles.inputFieldIconLeft]: iconIsLeft })}\n onClick={togglePassword}\n {...clickableIconProps(togglePassword)}\n aria-label={isPasswordShown ? text.hidePassword : text.showPassword}\n />\n );\n } else if (typeIcon) {\n fieldIcon = <FontAwesomeIcon icon={typeIcon} {...iconProps} />;\n }\n const hasLeftIcon = !!fieldIcon && iconIsLeft;\n\n const customInputProps = customInput?.props as { className?: string; style?: React.CSSProperties } | undefined;\n\n function handleClear() {\n if (formValidator) formValidator.set('');\n onChange?.('');\n onClear?.();\n // A key press would otherwise leave focus on a button that is about to vanish.\n inputRef.current?.focus();\n }\n\n return (\n <div\n className={cx(\n styles.input,\n { [styles.inputIconLeft]: hasLeftIcon, [styles.inputWithLabel]: useMatLabelStyle && !!label },\n className,\n )}\n style={style}\n >\n <label\n htmlFor={inputId}\n className={cx(styles.inputLabel, classNames?.label, {\n [styles.inputLabelColumn]: !isRow,\n [styles.inputLabelInBorder]: labelInBorder,\n })}\n style={slotStyles?.label}\n >\n {label && !useMatLabelStyle ? (\n <span className={styles.inputLabelText}>\n {label}\n {requiredMark}\n </span>\n ) : null}\n {upperRightLabel && (\n <div\n className={cx(styles.inputUpperRightLabel, classNames?.upperRightLabel)}\n style={slotStyles?.upperRightLabel}\n >\n {upperRightLabel}\n </div>\n )}\n <div\n className={cx(\n styles.inputContainer,\n {\n [styles.inputContainerMultiline]: multiline,\n [styles.inputContainerResizable]: multiline && !autoResize,\n [styles.inputContainerDisabled]: disabled,\n },\n classNames?.container,\n )}\n style={slotStyles?.container}\n onMouseEnter={onMouseEnterHandler}\n onMouseLeave={onMouseLeaveHandler}\n >\n {iconIsLeft && fieldIcon}\n {React.cloneElement(customInput || (multiline ? <textarea /> : <input />), {\n ...rest,\n className: cx(\n styles.inputField,\n {\n [styles.inputFieldUppercase]: isUppercase,\n [styles.inputFieldDate]: type === InputType.Date,\n [styles.inputFieldDefault]: type !== InputType.Date,\n [styles.inputFieldWithIconLeft]: hasLeftIcon,\n [styles.inputFieldMultiline]: multiline,\n [styles.inputFieldMultilineAutoResize]: multiline && autoResize,\n [styles.inputFieldReadOnly]: readOnly && !disabled,\n },\n classNames?.input,\n customInputProps?.className,\n ),\n style:\n customInputProps?.style || slotStyles?.input\n ? { ...customInputProps?.style, ...slotStyles?.input }\n : undefined,\n name,\n id: inputId,\n value: currVal,\n tabIndex,\n ref: customInput ? undefined : mergeRefs(inputRef, ref),\n onChange: onChangeHandler,\n onAnimationStart: handleAutofillAnimation,\n onFocus: onFocusHandler,\n onBlur: onBlurHandler,\n placeholder: !useMatLabelStyle ? placeholder : '',\n autoComplete,\n onClick,\n readOnly,\n disabled,\n ...(!multiline && { type: getInputType(), inputMode: rest.inputMode ?? getInputMode(), min, max }),\n ...(multiline && rows !== undefined && { rows }),\n })}\n {suffix && (\n <div className={cx(styles.inputFieldSuffix, classNames?.suffix)} style={slotStyles?.suffix}>\n {suffix}\n </div>\n )}\n {/* Mounted while empty too, so the first character grows it in rather than popping it in. */}\n {clearable && type !== InputType.Search && (\n <FontAwesomeIcon\n icon={faXmark}\n className={cx(styles.inputFieldIcon, styles.inputFieldIconClear, {\n [styles.inputFieldIconClearHidden]: !canClear,\n })}\n onClick={canClear ? handleClear : undefined}\n {...clickableIconProps(canClear ? handleClear : undefined)}\n aria-label={text.clear}\n />\n )}\n {!iconIsLeft && fieldIcon}\n </div>\n <fieldset\n className={cx(styles.inputFieldset, classNames?.fieldset, {\n [styles.inputContainerBorderFocused]: showFocus,\n [styles.inputContainerBorderSearchFocused]: type === InputType.Search && (showFocus || !!currVal),\n [styles.inputContainerBorderInvalid]: hasErr,\n [styles.inputContainerBorderError]: hasErr,\n })}\n style={slotStyles?.fieldset}\n >\n <legend\n className={cx(styles.inputFieldsetLegend, {\n [styles.inputFieldsetLegendActive]: shouldFloatLabel,\n })}\n >\n <span>{editedLabel}</span>\n </legend>\n </fieldset>\n {useMatLabelStyle && label && (\n <div\n className={cx(styles.inputMatLabel, {\n [styles.inputMatLabelFloating]: shouldFloatLabel,\n [styles.inputMatLabelMultiline]: multiline && !shouldFloatLabel,\n })}\n >\n {label}\n {requiredMark}\n </div>\n )}\n {useMatLabelStyle && placeholder && (\n <div\n className={cx(\n styles.inputPlaceholder,\n showFocus && !currVal && !isAutofilled && styles.inputPlaceholderShown,\n multiline && styles.inputPlaceholderMultiline,\n )}\n >\n {placeholder}\n </div>\n )}\n <Tooltip\n variant='error'\n message={formValidator ? formValidator.getCurrentErrorMessage() : errorMessage || ''}\n isVisible={hasErr && (isFocused || isHovered)}\n />\n </label>\n </div>\n );\n}\n\nexport default Input;\n"],"mappings":"kzBAsBA,IAAM,GAAwC,CAC5C,MAAO,QACP,aAAc,gBACd,aAAc,gBACd,YAAa,cACf,EAEM,GAAyD,EAC5D,EAAU,OAAQ,IAClB,EAAU,OAAQ,GAClB,EAAU,MAAO,CACpB,EAEA,SAAS,EAAmB,EAA6D,CAClF,KACL,MAAO,CACL,KAAM,SACN,SAAU,EAGV,YAAc,GAA4B,EAAM,eAAe,EAC/D,UAAY,GAA+B,EACrC,EAAM,MAAQ,SAAW,EAAM,MAAQ,OAC3C,EAAM,eAAe,EACrB,EAAW,CAAK,EAClB,CACF,CACF,CAEA,SAAS,EAAM,EAAmB,CAChC,GAAM,CACJ,OAAO,GACP,MACA,QAAQ,GACR,gBAAe,GACf,WAAU,GACV,aAAY,GACZ,SACA,SAAQ,GACR,OAAO,KACP,gBACA,eAAiB,CAAC,EAClB,QAAS,EAAc,KACvB,OAAQ,EAAa,KACrB,aA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Aa,CAAC,CAAC,IACxF,EAAO,6BAA8B,GACrC,EAAO,2BAA4B,CACtC,CAAC,EACD,MAAO,GAAY,SAEnB,SAAA,EAAC,SAAD,CACE,UAAW,EAAG,EAAO,oBAAqB,EACvC,EAAO,2BAA4B,CACtC,CAAC,EAED,SAAA,EAAC,OAAD,CAAA,SAAO,CAAkB,CAAA,CACnB,CAAA,CACA,CAAA,EACT,GAAoB,GACnB,EAAC,MAAD,CACE,UAAW,EAAG,EAAO,cAAe,EACjC,EAAO,uBAAwB,GAC/B,EAAO,wBAAyB,GAAa,CAAC,CACjD,CAAC,EAJH,SAAA,CAMG,EACA,EACE,IAEN,GAAoB,GACnB,EAAC,MAAD,CACE,UAAW,EACT,EAAO,iBACP,GAAa,CAAC,GAAW,CAAC,IAAgB,EAAO,sBACjD,GAAa,EAAO,yBACtB,EAEC,SAAA,CACE,CAAA,EAEP,EAAC,GAAD,CACE,QAAQ,QACR,QAAS,EAAgB,EAAc,uBAAuB,EAAI,IAAgB,GAClF,UAAW,IAAW,IAAa,GACpC,CAAA,CACI,GACJ,CAAA,CAET"}
@@ -1,2 +1,2 @@
1
- "use client";import{useComponentDefaults as e}from"../configProvider/useComponentDefaults.mjs";import{useLabels as t}from"../configProvider/useLabels.mjs";import{Presentation as n}from"../configProvider/presentation.types.mjs";import{PopoverAlign as r,PopoverPlacement as i}from"../popover/popover.types.mjs";import ee from"../popover/popover.mjs";import a from"../input/input.mjs";import{nextIndex as o,scrollOptionIntoView as s}from"../utils/listNavigation.mjs";import c from"./inputDropdown.module.mjs";import{useCallback as l,useEffect as u,useMemo as te,useRef as d,useState as f}from"react";import p from"classnames";import{jsx as m,jsxs as h}from"react/jsx-runtime";function ne(e,t){return t?t.value??``:e??``}function g(e,t){let n=t.find(t=>t.value===e);return n?n.label??n.value:e}var re={wrap:!1},ie={empty:`No matches`};function _(_){let{label:ae=``,value:v=``,formValidator:y=null,error:b,isRequired:x=!1,items:S=[],allowCustomValue:C=!1,maxItems:w=100,className:T,style:E,classNames:D,styles:O,onSelect:k=()=>null,onChange:A,placeholder:oe=``,readOnly:j=!1,labels:M,...se}=e(`InputDropdown`,_),N=t(`InputDropdown`,M,ie),P=ne(v,y),[,F]=f(0),I=d(y);u(()=>{if(I.current=y,!y)return;let e=()=>F(e=>e+1);return y.registerOnUpdateListener(e),()=>{y.removeOnUpdateListener(e)}},[y]);let L=x||!!y?.validators.find(e=>e.validatorId===`required`),[R,z]=f(()=>g(P,S)),[B,V]=f(P),[H,U]=f(!1),[W,G]=f(null),K=d(null),q=d(null),J=d(null);if(P!==B){V(P);let e=S.find(e=>e.value===P);e?z(e.label??e.value):C&&z(P)}if(!H&&!C&&R===P){let e=g(P,S);e!==R&&z(e)}let Y=te(()=>{let e=R.toLowerCase(),t=[];for(let n of S)if((n.label??n.value).toLowerCase().includes(e)&&(t.push(n),w>0&&t.length>=w))break;return t},[S,R,w]),ce=!C&&R!==``&&R!==g(P,S),X=Y.length===0&&ce,Z=H&&!j&&(Y.length>0||X),Q=O?.dropdown?.fontSize,le=l(e=>{let t=q.current;e&&t&&Q==null&&(e.style.fontSize=window.getComputedStyle(t).fontSize)},[Q]),ue=()=>{j||(K.current&&=(clearTimeout(K.current),null),U(!0))},de=()=>{I.current&&(I.current.touched=!0),K.current=setTimeout(()=>{U(!1),G(null),K.current=null,C||z(g(P,S))},100)};u(()=>{Z&&W!==null&&s(J.current,J.current?.children[W])},[Z,W]);let $=l(e=>{z(e.label??e.value),U(!1),G(null),y&&y.set(e.value),A&&A(e.value),k(e.value)},[y,A,k]),fe=l(e=>{if(j)return;let t=e.key===`ArrowUp`||e.key===`ArrowDown`;if(!Z){t&&(e.preventDefault(),U(!0));return}if(t){e.preventDefault();let t=e.key===`ArrowDown`?1:-1;G(e=>e!==null&&e===(t===1?Y.length-1:0)?null:o(e,t,Y.length,re))}else e.key===`Enter`&&(W!==null&&Y[W]?(e.preventDefault(),$(Y[W])):C&&(U(!1),G(null)))},[Y,W,$,C,j,Z]),pe=h(`div`,{ref:le,className:p(c.dropdown,D?.dropdown),style:O?.dropdown,children:[X&&m(`div`,{className:p(c.dropdownEmpty,D?.empty),style:O?.empty,onMouseDown:e=>e.preventDefault(),children:N.empty}),m(`div`,{ref:J,className:c.dropdownScroll,children:Y.map((e,t)=>m(`div`,{className:p(c.dropdownItem,W===t&&c.dropdownItemHighlighted,D?.item),style:O?.item,onMouseDown:e=>e.preventDefault(),onClick:()=>$(e),children:e.label??e.value},`${t}_${e.label}_${e.value}`))})]});return h(`div`,{...se,ref:q,className:p(c.inputDropdown,D?.root,T),style:{...O?.root,...E},onFocus:ue,onBlur:de,onKeyDown:fe,children:[m(ee,{isOpen:Z,onOpenChange:e=>{e||(U(!1),G(null))},presentation:n.Default,placement:i.Bottom,align:r.Start,offset:0,withArrow:!1,constrainWidth:!1,closeOnTriggerClick:!1,focusOnOpen:!1,classNames:{panel:c.inputDropdownPanel},content:pe,children:m(a,{autoComplete:`off`,label:ae,value:R,readOnly:j,formValidator:null,isRequired:L,isValid:y?!y.touched||!y.hasError():!b,errorMessage:y?y.touched?y.getCurrentErrorMessage()??``:``:b??``,onChange:e=>{if(z(e),G(null),U(!0),C)y&&y.set(e),A&&A(e);else if(e===``)y&&y.set(``),A&&A(``),k(``);else{let t=S.find(t=>(t.label??t.value).toLowerCase()===e.toLowerCase());t&&(y&&y.set(t.value),A&&A(t.value),k(t.value))}},placeholder:oe})}),m(`span`,{className:c.inputDropdownStatus,role:`status`,"aria-live":`polite`,children:Z&&X?N.empty:``})]})}export{_ as default};
1
+ "use client";import{useComponentDefaults as e}from"../configProvider/useComponentDefaults.mjs";import{useLabels as t}from"../configProvider/useLabels.mjs";import{Presentation as n}from"../configProvider/presentation.types.mjs";import{PopoverAlign as r,PopoverPlacement as i}from"../popover/popover.types.mjs";import ee from"../popover/popover.mjs";import a from"../input/input.mjs";import{nextIndex as o,scrollOptionIntoView as s}from"../utils/listNavigation.mjs";import c from"./inputDropdown.module.mjs";import{useCallback as l,useEffect as u,useMemo as te,useRef as d,useState as f}from"react";import p from"classnames";import{jsx as m,jsxs as h}from"react/jsx-runtime";function ne(e,t){return t?t.value??``:e??``}function g(e,t){let n=t.find(t=>t.value===e);return n?n.label??n.value:e}var re={wrap:!1},ie={empty:`No matches`};function _(_){let{label:ae=``,value:v=``,formValidator:y=null,error:b,isRequired:x=!1,items:S=[],allowCustomValue:C=!1,maxItems:w=100,className:T,style:E,classNames:D,styles:O,onSelect:k=()=>null,onChange:A,placeholder:oe=``,readOnly:j=!1,labels:M,...se}=e(`InputDropdown`,_),N=t(`InputDropdown`,M,ie),P=ne(v,y),[,F]=f(0),I=d(y);u(()=>{if(I.current=y,!y)return;let e=()=>F(e=>e+1);return y.registerOnUpdateListener(e),()=>{y.removeOnUpdateListener(e)}},[y]);let L=x||!!y?.validators.find(e=>e.validatorId===`required`),[R,z]=f(()=>g(P,S)),[B,V]=f(P),[H,U]=f(!1),[W,G]=f(null),K=d(null),q=d(null),J=d(null);if(P!==B){V(P);let e=S.find(e=>e.value===P);e?z(e.label??e.value):C&&z(P)}if(!H&&!C&&R===P){let e=g(P,S);e!==R&&z(e)}let Y=te(()=>{let e=R.toLowerCase(),t=[];for(let n of S)if((n.label??n.value).toLowerCase().includes(e)&&(t.push(n),w>0&&t.length>=w))break;return t},[S,R,w]),ce=!C&&R!==``&&R!==g(P,S),X=Y.length===0&&ce,Z=H&&!j&&(Y.length>0||X),Q=O?.dropdown?.fontSize,le=l(e=>{let t=q.current;e&&t&&Q==null&&(e.style.fontSize=window.getComputedStyle(t).fontSize)},[Q]),ue=()=>{j||(K.current&&=(clearTimeout(K.current),null),U(!0))},de=()=>{I.current&&(I.current.touched=!0),K.current=setTimeout(()=>{U(!1),G(null),K.current=null,C||z(g(P,S))},100)};u(()=>{Z&&W!==null&&s(J.current,J.current?.children[W])},[Z,W]);let $=l(e=>{z(e.label??e.value),U(!1),G(null),y&&y.set(e.value),A&&A(e.value),k(e.value)},[y,A,k]),fe=l(e=>{if(j)return;let t=e.key===`ArrowUp`||e.key===`ArrowDown`;if(!Z){t&&(e.preventDefault(),U(!0));return}if(t){e.preventDefault();let t=e.key===`ArrowDown`?1:-1;G(e=>e!==null&&e===(t===1?Y.length-1:0)?null:o(e,t,Y.length,re))}else e.key===`Enter`&&(W!==null&&Y[W]?(e.preventDefault(),$(Y[W])):C&&(U(!1),G(null)))},[Y,W,$,C,j,Z]),pe=h(`div`,{ref:le,className:p(c.dropdown,D?.dropdown),style:O?.dropdown,children:[X&&m(`div`,{className:p(c.dropdownEmpty,D?.empty),style:O?.empty,onMouseDown:e=>e.preventDefault(),children:N.empty}),m(`div`,{ref:J,className:c.dropdownScroll,children:Y.map((e,t)=>m(`div`,{className:p(c.dropdownItem,W===t&&c.dropdownItemHighlighted,D?.item),style:O?.item,onMouseDown:e=>e.preventDefault(),onClick:()=>$(e),children:e.label??e.value},`${t}_${e.label}_${e.value}`))})]});return h(`div`,{...se,ref:q,className:p(c.inputDropdown,D?.root,T),style:{...O?.root,...E},onFocus:ue,onBlur:de,onKeyDown:fe,children:[m(ee,{isOpen:Z,onOpenChange:e=>{e||(U(!1),G(null))},presentation:n.Default,placement:i.Bottom,align:r.Start,offset:0,withArrow:!1,constrainWidth:!1,closeOnTriggerClick:!1,focusOnOpen:!1,classNames:{panel:c.inputDropdownPanel},content:pe,children:m(a,{autoComplete:`off`,label:ae,value:R,readOnly:j,formValidator:null,isRequired:L,isValid:y?!y.shouldShowError:!b,errorMessage:y?y.shouldShowError?y.getCurrentErrorMessage()??``:``:b??``,onChange:e=>{if(z(e),G(null),U(!0),C)y&&y.set(e),A&&A(e);else if(e===``)y&&y.set(``),A&&A(``),k(``);else{let t=S.find(t=>(t.label??t.value).toLowerCase()===e.toLowerCase());t&&(y&&y.set(t.value),A&&A(t.value),k(t.value))}},placeholder:oe})}),m(`span`,{className:c.inputDropdownStatus,role:`status`,"aria-live":`polite`,children:Z&&X?N.empty:``})]})}export{_ as default};
2
2
  //# sourceMappingURL=inputDropdown.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"inputDropdown.mjs","names":[],"sources":["../../../../package/common/inputDropdown/inputDropdown.tsx"],"sourcesContent":["import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport cx from 'classnames';\nimport styles from './inputDropdown.module.pcss';\nimport Input from '../input';\nimport Popover from '../popover';\nimport { PopoverAlign, PopoverPlacement } from '../popover/popover.types';\nimport { useComponentDefaults, useLabels } from '../configProvider';\nimport { Presentation } from '../configProvider/presentation.types';\nimport type { InputDropdownItem, InputDropdownLabels, InputDropdownProps } from './inputDropdown.types';\nimport { nextIndex, scrollOptionIntoView } from '../utils/listNavigation';\n\nfunction getKeyFromProps(value: string | undefined, formValidator: InputDropdownProps['formValidator']): string {\n return formValidator ? ((formValidator.value as string) ?? '') : (value ?? '');\n}\n\nfunction labelForKey(key: string, items: InputDropdownItem[]): string {\n const match = items.find((item) => item.value === key);\n return match ? (match.label ?? match.value) : key;\n}\n\n/**\n * The suggestions do not wrap: the list is filtered by what is being typed, so running off one\n * end and reappearing at the other reads as the list having changed under the caret.\n */\nconst NO_WRAP = { wrap: false };\n\nconst DEFAULT_LABELS: Required<InputDropdownLabels> = { empty: 'No matches' };\n\nexport default function InputDropdown(props: InputDropdownProps) {\n const {\n label = '',\n value = '',\n formValidator = null,\n error,\n isRequired = false,\n items = [],\n allowCustomValue = false,\n maxItems = 100,\n className,\n style,\n classNames,\n styles: slotStyles,\n onSelect = () => null,\n onChange,\n placeholder = '',\n readOnly = false,\n labels,\n ...rest\n } = useComponentDefaults('InputDropdown', props);\n const text = useLabels('InputDropdown', labels, DEFAULT_LABELS);\n const currentKey = getKeyFromProps(value, formValidator);\n const [, forceUpdate] = useState(0);\n const fvRef = useRef(formValidator);\n\n useEffect(() => {\n fvRef.current = formValidator;\n if (!formValidator) return;\n const listener = () => forceUpdate((n) => n + 1);\n formValidator.registerOnUpdateListener(listener);\n return () => {\n formValidator.removeOnUpdateListener(listener);\n };\n }, [formValidator]);\n\n const computedIsRequired =\n isRequired || !!formValidator?.validators.find((v) => (v as { validatorId?: string }).validatorId === 'required');\n\n const [inputText, setInputText] = useState(() => labelForKey(currentKey, items));\n const [prevKey, setPrevKey] = useState(currentKey);\n const [isMenuShown, setIsMenuShown] = useState(false);\n const [highlightedIndex, setHighlightedIndex] = useState<number | null>(null);\n const hideTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const triggerRef = useRef<HTMLDivElement>(null);\n const scrollRef = useRef<HTMLDivElement>(null);\n\n // Sync display text when the controlled key changes externally (e.g. parent reset).\n if (currentKey !== prevKey) {\n setPrevKey(currentKey);\n const match = items.find((item) => item.value === currentKey);\n if (match) setInputText(match.label ?? match.value);\n else if (allowCustomValue) setInputText(currentKey);\n }\n\n // `items` often arrives after the value, leaving the raw key on display. Not while open, or a key\n // being typed would turn into its label under the caret.\n if (!isMenuShown && !allowCustomValue && inputText === currentKey) {\n const selectedLabel = labelForKey(currentKey, items);\n if (selectedLabel !== inputText) setInputText(selectedLabel);\n }\n\n const currItems = useMemo(() => {\n const needle = inputText.toLowerCase();\n const matches: InputDropdownItem[] = [];\n for (const item of items) {\n if (!(item.label ?? item.value).toLowerCase().includes(needle)) continue;\n matches.push(item);\n if (maxItems > 0 && matches.length >= maxItems) break;\n }\n return matches;\n }, [items, inputText, maxItems]);\n\n // Only text that blur swaps for the selection's label needs a warning. Comparing with the label\n // rather than '' keeps a preset value missing from `items` from showing \"No matches\" unprompted.\n const isDiscardedOnBlur = !allowCustomValue && inputText !== '' && inputText !== labelForKey(currentKey, items);\n const showEmpty = currItems.length === 0 && isDiscardedOnBlur;\n // Closed rather than hidden when empty: a mounted panel stays on the overlay stack, so inside a\n // Modal an invisible list would take the Escape meant for the modal.\n const isOpen = isMenuShown && !readOnly && (currItems.length > 0 || showEmpty);\n\n // A ref callback rather than a layout effect: the list is portaled out of the field's font size,\n // and Popover positions it in its own layout effect, which runs before this component's would.\n const menuFontSizeOverride = slotStyles?.dropdown?.fontSize;\n const menuRef = useCallback(\n (menu: HTMLDivElement | null) => {\n const trigger = triggerRef.current;\n if (!menu || !trigger || menuFontSizeOverride != null) return;\n menu.style.fontSize = window.getComputedStyle(trigger).fontSize;\n },\n [menuFontSizeOverride],\n );\n\n const handleFocus = () => {\n if (readOnly) return;\n if (hideTimeoutRef.current) {\n clearTimeout(hideTimeoutRef.current);\n hideTimeoutRef.current = null;\n }\n setIsMenuShown(true);\n };\n\n const handleBlur = () => {\n if (fvRef.current) fvRef.current.touched = true;\n hideTimeoutRef.current = setTimeout(() => {\n setIsMenuShown(false);\n setHighlightedIndex(null);\n hideTimeoutRef.current = null;\n // Without custom values, uncommitted typed text is invalid — snap the\n // display back to the currently selected item's label.\n if (!allowCustomValue) setInputText(labelForKey(currentKey, items));\n }, 100);\n };\n\n useEffect(() => {\n if (!isOpen || highlightedIndex === null) return;\n scrollOptionIntoView(scrollRef.current, scrollRef.current?.children[highlightedIndex]);\n }, [isOpen, highlightedIndex]);\n\n const handleSelect = useCallback(\n (item: InputDropdownItem) => {\n setInputText(item.label ?? item.value);\n setIsMenuShown(false);\n setHighlightedIndex(null);\n if (formValidator) formValidator.set(item.value);\n if (onChange) onChange(item.value);\n onSelect(item.value);\n },\n [formValidator, onChange, onSelect],\n );\n\n const onKeyDown = useCallback(\n (event: React.KeyboardEvent) => {\n if (readOnly) return;\n const isArrow = event.key === 'ArrowUp' || event.key === 'ArrowDown';\n // Enter belongs to the form while closed, or it would pick a suggestion the user never saw.\n if (!isOpen) {\n if (isArrow) {\n event.preventDefault();\n setIsMenuShown(true);\n }\n return;\n }\n if (isArrow) {\n event.preventDefault();\n const step = event.key === 'ArrowDown' ? 1 : -1;\n setHighlightedIndex((idx) => {\n // The text being typed is part of the cycle, so both ends lead back to it and on round\n // to the far end: last → text → first, first → text → last. That is how a browser's own\n // address bar behaves, and it is why this list does not wrap straight around the way\n // Dropdown and MultiSelect do — they have no typed text to pass through.\n const atFarEnd = idx !== null && idx === (step === 1 ? currItems.length - 1 : 0);\n return atFarEnd ? null : nextIndex(idx, step, currItems.length, NO_WRAP);\n });\n } else if (event.key === 'Enter') {\n if (highlightedIndex !== null && currItems[highlightedIndex]) {\n // This Enter picked a suggestion, so it must not also reach the form around the field.\n // Without this the browser's implicit submission runs as well, and choosing from the\n // list submitted the form underneath the user. The blank state deliberately does not\n // do this: Enter there means the text as typed, and submitting is a fair reading of it.\n event.preventDefault();\n handleSelect(currItems[highlightedIndex]);\n } else if (allowCustomValue) {\n setIsMenuShown(false);\n setHighlightedIndex(null);\n }\n }\n },\n [currItems, highlightedIndex, handleSelect, allowCustomValue, readOnly, isOpen],\n );\n\n const menu = (\n <div ref={menuRef} className={cx(styles.dropdown, classNames?.dropdown)} style={slotStyles?.dropdown}>\n {showEmpty && (\n <div\n className={cx(styles.dropdownEmpty, classNames?.empty)}\n style={slotStyles?.empty}\n // A blur would throw the typed text away.\n onMouseDown={(e) => e.preventDefault()}\n >\n {text.empty}\n </div>\n )}\n <div ref={scrollRef} className={styles.dropdownScroll}>\n {currItems.map((item, key) => (\n <div\n key={`${key}_${item.label}_${item.value}`}\n className={cx(\n styles.dropdownItem,\n highlightedIndex === key && styles.dropdownItemHighlighted,\n classNames?.item,\n )}\n style={slotStyles?.item}\n // Prevent the input from blurring before the click resolves.\n onMouseDown={(e) => e.preventDefault()}\n onClick={() => handleSelect(item)}\n >\n {item.label ?? item.value}\n </div>\n ))}\n </div>\n </div>\n );\n\n return (\n <div\n {...rest}\n ref={triggerRef}\n className={cx(styles.inputDropdown, classNames?.root, className)}\n style={{ ...slotStyles?.root, ...style }}\n onFocus={handleFocus}\n onBlur={handleBlur}\n onKeyDown={onKeyDown}\n >\n <Popover\n // The field owns the open state: it opens on typing and closes on blur, on\n // a pick, or on Escape. Only a close is taken from Popover, which is the\n // outside click its portaled panel would otherwise not see.\n isOpen={isOpen}\n onOpenChange={(next) => {\n if (next) return;\n setIsMenuShown(false);\n setHighlightedIndex(null);\n }}\n // Never a sheet, whatever the app-wide `presentation`: its backdrop would cover the field\n // being typed into.\n presentation={Presentation.Default}\n placement={PopoverPlacement.Bottom}\n align={PopoverAlign.Start}\n offset={0}\n withArrow={false}\n constrainWidth={false}\n closeOnTriggerClick={false}\n focusOnOpen={false}\n classNames={{ panel: styles.inputDropdownPanel }}\n content={menu}\n >\n <Input\n // A combobox renders its own suggestion list; the browser's autofill dropdown\n // opens on top of it, so two lists compete for the same space.\n autoComplete='off'\n label={label}\n value={inputText}\n readOnly={readOnly}\n formValidator={null}\n isRequired={computedIsRequired}\n isValid={formValidator ? (formValidator.touched ? !formValidator.hasError() : true) : !error}\n errorMessage={\n formValidator\n ? formValidator.touched\n ? (formValidator.getCurrentErrorMessage() ?? '')\n : ''\n : (error ?? '')\n }\n onChange={(typed) => {\n setInputText(typed);\n setHighlightedIndex(null);\n setIsMenuShown(true);\n if (allowCustomValue) {\n if (formValidator) formValidator.set(typed);\n if (onChange) onChange(typed);\n } else if (typed === '') {\n if (formValidator) formValidator.set('');\n if (onChange) onChange('');\n onSelect('');\n } else {\n // Emit when the typed text exactly matches an item's label/value.\n const match = items.find((item) => (item.label ?? item.value).toLowerCase() === typed.toLowerCase());\n if (match) {\n if (formValidator) formValidator.set(match.value);\n if (onChange) onChange(match.value);\n onSelect(match.value);\n }\n }\n }}\n placeholder={placeholder}\n />\n </Popover>\n {/* Outside the portal and always mounted: a live region that mounts already filled is not\n reliably announced. */}\n <span className={styles.inputDropdownStatus} role='status' aria-live='polite'>\n {isOpen && showEmpty ? text.empty : ''}\n </span>\n </div>\n );\n}\n"],"mappings":"iqBAWA,SAAS,GAAgB,EAA2B,EAA4D,CAC9G,OAAO,EAAkB,EAAc,OAAoB,GAAO,GAAS,EAC7E,CAEA,SAAS,EAAY,EAAa,EAAoC,CACpE,IAAM,EAAQ,EAAM,KAAM,GAAS,EAAK,QAAU,CAAG,EACrD,OAAO,EAAS,EAAM,OAAS,EAAM,MAAS,CAChD,CAMA,IAAM,GAAU,CAAE,KAAM,EAAM,EAExB,GAAgD,CAAE,MAA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],"sources":["../../../../package/common/inputDropdown/inputDropdown.tsx"],"sourcesContent":["import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport cx from 'classnames';\nimport styles from './inputDropdown.module.pcss';\nimport Input from '../input';\nimport Popover from '../popover';\nimport { PopoverAlign, PopoverPlacement } from '../popover/popover.types';\nimport { useComponentDefaults, useLabels } from '../configProvider';\nimport { Presentation } from '../configProvider/presentation.types';\nimport type { InputDropdownItem, InputDropdownLabels, InputDropdownProps } from './inputDropdown.types';\nimport { nextIndex, scrollOptionIntoView } from '../utils/listNavigation';\n\nfunction getKeyFromProps(value: string | undefined, formValidator: InputDropdownProps['formValidator']): string {\n return formValidator ? ((formValidator.value as string) ?? '') : (value ?? '');\n}\n\nfunction labelForKey(key: string, items: InputDropdownItem[]): string {\n const match = items.find((item) => item.value === key);\n return match ? (match.label ?? match.value) : key;\n}\n\n/**\n * The suggestions do not wrap: the list is filtered by what is being typed, so running off one\n * end and reappearing at the other reads as the list having changed under the caret.\n */\nconst NO_WRAP = { wrap: false };\n\nconst DEFAULT_LABELS: Required<InputDropdownLabels> = { empty: 'No matches' };\n\nexport default function InputDropdown(props: InputDropdownProps) {\n const {\n label = '',\n value = '',\n formValidator = null,\n error,\n isRequired = false,\n items = [],\n allowCustomValue = false,\n maxItems = 100,\n className,\n style,\n classNames,\n styles: slotStyles,\n onSelect = () => null,\n onChange,\n placeholder = '',\n readOnly = false,\n labels,\n ...rest\n } = useComponentDefaults('InputDropdown', props);\n const text = useLabels('InputDropdown', labels, DEFAULT_LABELS);\n const currentKey = getKeyFromProps(value, formValidator);\n const [, forceUpdate] = useState(0);\n const fvRef = useRef(formValidator);\n\n useEffect(() => {\n fvRef.current = formValidator;\n if (!formValidator) return;\n const listener = () => forceUpdate((n) => n + 1);\n formValidator.registerOnUpdateListener(listener);\n return () => {\n formValidator.removeOnUpdateListener(listener);\n };\n }, [formValidator]);\n\n const computedIsRequired =\n isRequired || !!formValidator?.validators.find((v) => (v as { validatorId?: string }).validatorId === 'required');\n\n const [inputText, setInputText] = useState(() => labelForKey(currentKey, items));\n const [prevKey, setPrevKey] = useState(currentKey);\n const [isMenuShown, setIsMenuShown] = useState(false);\n const [highlightedIndex, setHighlightedIndex] = useState<number | null>(null);\n const hideTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const triggerRef = useRef<HTMLDivElement>(null);\n const scrollRef = useRef<HTMLDivElement>(null);\n\n // Sync display text when the controlled key changes externally (e.g. parent reset).\n if (currentKey !== prevKey) {\n setPrevKey(currentKey);\n const match = items.find((item) => item.value === currentKey);\n if (match) setInputText(match.label ?? match.value);\n else if (allowCustomValue) setInputText(currentKey);\n }\n\n // `items` often arrives after the value, leaving the raw key on display. Not while open, or a key\n // being typed would turn into its label under the caret.\n if (!isMenuShown && !allowCustomValue && inputText === currentKey) {\n const selectedLabel = labelForKey(currentKey, items);\n if (selectedLabel !== inputText) setInputText(selectedLabel);\n }\n\n const currItems = useMemo(() => {\n const needle = inputText.toLowerCase();\n const matches: InputDropdownItem[] = [];\n for (const item of items) {\n if (!(item.label ?? item.value).toLowerCase().includes(needle)) continue;\n matches.push(item);\n if (maxItems > 0 && matches.length >= maxItems) break;\n }\n return matches;\n }, [items, inputText, maxItems]);\n\n // Only text that blur swaps for the selection's label needs a warning. Comparing with the label\n // rather than '' keeps a preset value missing from `items` from showing \"No matches\" unprompted.\n const isDiscardedOnBlur = !allowCustomValue && inputText !== '' && inputText !== labelForKey(currentKey, items);\n const showEmpty = currItems.length === 0 && isDiscardedOnBlur;\n // Closed rather than hidden when empty: a mounted panel stays on the overlay stack, so inside a\n // Modal an invisible list would take the Escape meant for the modal.\n const isOpen = isMenuShown && !readOnly && (currItems.length > 0 || showEmpty);\n\n // A ref callback rather than a layout effect: the list is portaled out of the field's font size,\n // and Popover positions it in its own layout effect, which runs before this component's would.\n const menuFontSizeOverride = slotStyles?.dropdown?.fontSize;\n const menuRef = useCallback(\n (menu: HTMLDivElement | null) => {\n const trigger = triggerRef.current;\n if (!menu || !trigger || menuFontSizeOverride != null) return;\n menu.style.fontSize = window.getComputedStyle(trigger).fontSize;\n },\n [menuFontSizeOverride],\n );\n\n const handleFocus = () => {\n if (readOnly) return;\n if (hideTimeoutRef.current) {\n clearTimeout(hideTimeoutRef.current);\n hideTimeoutRef.current = null;\n }\n setIsMenuShown(true);\n };\n\n const handleBlur = () => {\n if (fvRef.current) fvRef.current.touched = true;\n hideTimeoutRef.current = setTimeout(() => {\n setIsMenuShown(false);\n setHighlightedIndex(null);\n hideTimeoutRef.current = null;\n // Without custom values, uncommitted typed text is invalid — snap the\n // display back to the currently selected item's label.\n if (!allowCustomValue) setInputText(labelForKey(currentKey, items));\n }, 100);\n };\n\n useEffect(() => {\n if (!isOpen || highlightedIndex === null) return;\n scrollOptionIntoView(scrollRef.current, scrollRef.current?.children[highlightedIndex]);\n }, [isOpen, highlightedIndex]);\n\n const handleSelect = useCallback(\n (item: InputDropdownItem) => {\n setInputText(item.label ?? item.value);\n setIsMenuShown(false);\n setHighlightedIndex(null);\n if (formValidator) formValidator.set(item.value);\n if (onChange) onChange(item.value);\n onSelect(item.value);\n },\n [formValidator, onChange, onSelect],\n );\n\n const onKeyDown = useCallback(\n (event: React.KeyboardEvent) => {\n if (readOnly) return;\n const isArrow = event.key === 'ArrowUp' || event.key === 'ArrowDown';\n // Enter belongs to the form while closed, or it would pick a suggestion the user never saw.\n if (!isOpen) {\n if (isArrow) {\n event.preventDefault();\n setIsMenuShown(true);\n }\n return;\n }\n if (isArrow) {\n event.preventDefault();\n const step = event.key === 'ArrowDown' ? 1 : -1;\n setHighlightedIndex((idx) => {\n // The text being typed is part of the cycle, so both ends lead back to it and on round\n // to the far end: last → text → first, first → text → last. That is how a browser's own\n // address bar behaves, and it is why this list does not wrap straight around the way\n // Dropdown and MultiSelect do — they have no typed text to pass through.\n const atFarEnd = idx !== null && idx === (step === 1 ? currItems.length - 1 : 0);\n return atFarEnd ? null : nextIndex(idx, step, currItems.length, NO_WRAP);\n });\n } else if (event.key === 'Enter') {\n if (highlightedIndex !== null && currItems[highlightedIndex]) {\n // This Enter picked a suggestion, so it must not also reach the form around the field.\n // Without this the browser's implicit submission runs as well, and choosing from the\n // list submitted the form underneath the user. The blank state deliberately does not\n // do this: Enter there means the text as typed, and submitting is a fair reading of it.\n event.preventDefault();\n handleSelect(currItems[highlightedIndex]);\n } else if (allowCustomValue) {\n setIsMenuShown(false);\n setHighlightedIndex(null);\n }\n }\n },\n [currItems, highlightedIndex, handleSelect, allowCustomValue, readOnly, isOpen],\n );\n\n const menu = (\n <div ref={menuRef} className={cx(styles.dropdown, classNames?.dropdown)} style={slotStyles?.dropdown}>\n {showEmpty && (\n <div\n className={cx(styles.dropdownEmpty, classNames?.empty)}\n style={slotStyles?.empty}\n // A blur would throw the typed text away.\n onMouseDown={(e) => e.preventDefault()}\n >\n {text.empty}\n </div>\n )}\n <div ref={scrollRef} className={styles.dropdownScroll}>\n {currItems.map((item, key) => (\n <div\n key={`${key}_${item.label}_${item.value}`}\n className={cx(\n styles.dropdownItem,\n highlightedIndex === key && styles.dropdownItemHighlighted,\n classNames?.item,\n )}\n style={slotStyles?.item}\n // Prevent the input from blurring before the click resolves.\n onMouseDown={(e) => e.preventDefault()}\n onClick={() => handleSelect(item)}\n >\n {item.label ?? item.value}\n </div>\n ))}\n </div>\n </div>\n );\n\n return (\n <div\n {...rest}\n ref={triggerRef}\n className={cx(styles.inputDropdown, classNames?.root, className)}\n style={{ ...slotStyles?.root, ...style }}\n onFocus={handleFocus}\n onBlur={handleBlur}\n onKeyDown={onKeyDown}\n >\n <Popover\n // The field owns the open state: it opens on typing and closes on blur, on\n // a pick, or on Escape. Only a close is taken from Popover, which is the\n // outside click its portaled panel would otherwise not see.\n isOpen={isOpen}\n onOpenChange={(next) => {\n if (next) return;\n setIsMenuShown(false);\n setHighlightedIndex(null);\n }}\n // Never a sheet, whatever the app-wide `presentation`: its backdrop would cover the field\n // being typed into.\n presentation={Presentation.Default}\n placement={PopoverPlacement.Bottom}\n align={PopoverAlign.Start}\n offset={0}\n withArrow={false}\n constrainWidth={false}\n closeOnTriggerClick={false}\n focusOnOpen={false}\n classNames={{ panel: styles.inputDropdownPanel }}\n content={menu}\n >\n <Input\n // A combobox renders its own suggestion list; the browser's autofill dropdown\n // opens on top of it, so two lists compete for the same space.\n autoComplete='off'\n label={label}\n value={inputText}\n readOnly={readOnly}\n formValidator={null}\n isRequired={computedIsRequired}\n isValid={formValidator ? !formValidator.shouldShowError : !error}\n errorMessage={\n formValidator\n ? formValidator.shouldShowError\n ? (formValidator.getCurrentErrorMessage() ?? '')\n : ''\n : (error ?? '')\n }\n onChange={(typed) => {\n setInputText(typed);\n setHighlightedIndex(null);\n setIsMenuShown(true);\n if (allowCustomValue) {\n if (formValidator) formValidator.set(typed);\n if (onChange) onChange(typed);\n } else if (typed === '') {\n if (formValidator) formValidator.set('');\n if (onChange) onChange('');\n onSelect('');\n } else {\n // Emit when the typed text exactly matches an item's label/value.\n const match = items.find((item) => (item.label ?? item.value).toLowerCase() === typed.toLowerCase());\n if (match) {\n if (formValidator) formValidator.set(match.value);\n if (onChange) onChange(match.value);\n onSelect(match.value);\n }\n }\n }}\n placeholder={placeholder}\n />\n </Popover>\n {/* Outside the portal and always mounted: a live region that mounts already filled is not\n reliably announced. */}\n <span className={styles.inputDropdownStatus} role='status' aria-live='polite'>\n {isOpen && showEmpty ? text.empty : ''}\n </span>\n </div>\n );\n}\n"],"mappings":"iqBAWA,SAAS,GAAgB,EAA2B,EAA4D,CAC9G,OAAO,EAAkB,EAAc,OAAoB,GAAO,GAAS,EAC7E,CAEA,SAAS,EAAY,EAAa,EAAoC,CACpE,IAAM,EAAQ,EAAM,KAAM,GAAS,EAAK,QAAU,CAAG,EACrD,OAAO,EAAS,EAAM,OAAS,EAAM,MAAS,CAChD,CAMA,IAAM,GAAU,CAAE,KAAM,EAAM,EAExB,GAAgD,CAAE,MAAO,YAAa,EAE5E,SAAwB,EAAc,EAA2B,CAC/D,GAAM,C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AAS,EAC/D,MAAO,CAAE,GAAG,GAAY,KAAM,GAAG,CAAM,EACvC,QAAS,GACT,OAAQ,GACG,aAPb,SAAA,CASE,EAAC,GAAD,CAIU,SACR,aAAe,GAAS,CAClB,IACJ,EAAe,EAAK,EACpB,EAAoB,IAAI,EAC1B,EAGA,aAAc,EAAa,QAC3B,UAAW,EAAiB,OAC5B,MAAO,EAAa,MACpB,OAAQ,EACR,UAAW,GACX,eAAgB,GAChB,oBAAqB,GACrB,YAAa,GACb,WAAY,CAAE,MAAO,EAAO,kBAAmB,EAC/C,QAAS,GAET,SAAA,EAAC,EAAD,CAGE,aAAa,MACN,SACP,MAAO,EACG,WACV,cAAe,KACf,WAAY,EACZ,QAAS,EAAgB,CAAC,EAAc,gBAAkB,CAAC,EAC3D,aACE,EACI,EAAc,gBACX,EAAc,uBAAuB,GAAK,GAC3C,GACD,GAAS,GAEhB,SAAW,GAAU,CAInB,GAHA,EAAa,CAAK,EAClB,EAAoB,IAAI,EACxB,EAAe,EAAI,EACf,EACE,GAAe,EAAc,IAAI,CAAK,EACtC,GAAU,EAAS,CAAK,OACvB,GAAI,IAAU,GACf,GAAe,EAAc,IAAI,EAAE,EACnC,GAAU,EAAS,EAAE,EACzB,EAAS,EAAE,MACN,CAEL,IAAM,EAAQ,EAAM,KAAM,IAAU,EAAK,OAAS,EAAK,MAAA,CAAO,YAAY,IAAM,EAAM,YAAY,CAAC,EAC/F,IACE,GAAe,EAAc,IAAI,EAAM,KAAK,EAC5C,GAAU,EAAS,EAAM,KAAK,EAClC,EAAS,EAAM,KAAK,EAExB,CACF,EACa,cACd,CAAA,CACM,CAAA,EAGT,EAAC,OAAD,CAAM,UAAW,EAAO,oBAAqB,KAAK,SAAS,YAAU,SAClE,SAAA,GAAU,EAAY,EAAK,MAAQ,EAChC,CAAA,CACH,GAET"}
@@ -0,0 +1,2 @@
1
+ "use client";import{renderIcon as e}from"../utils/renderIcon.mjs";import{useLinkClick as t}from"../utils/navigation.mjs";import n from"./listItem.module.mjs";import{useId as r}from"react";import i from"classnames";import{faChevronRight as a}from"@fortawesome/free-solid-svg-icons";import{jsx as o,jsxs as s}from"react/jsx-runtime";var c=e=>e!=null&&typeof e!=`boolean`&&e!==``;function l({icon:l,title:u,subtitle:d,endContent:f,href:p,target:m,rel:h,download:g,onClick:_,selected:v=!1,chevron:y=p!==void 0,className:b,style:x,classNames:S,styles:C,...w}){let T=t(),E=r(),D=c(d),O=c(f),k=p!==void 0||_!==void 0,A=[D&&`${E}-subtitle`,typeof f==`string`&&`${E}-end`].filter(Boolean).join(` `),j=o(`span`,{className:i(n.listItemTitle,S?.title),style:C?.title,children:u}),M={className:i(n.listItemTrigger,S?.trigger),style:C?.trigger,"aria-describedby":A||void 0},N=p===void 0?_?o(`button`,{...M,type:`button`,"aria-pressed":v||void 0,onClick:_,children:j}):j:o(`a`,{...M,href:p,target:m,rel:h,download:g,"aria-current":v?`page`:void 0,onClick:e=>{_?.(e),T(e)},children:j});return s(`div`,{...w,className:i(n.listItem,{[n.listItemInteractive]:k,[n.listItemSelected]:v},b,S?.root),style:{...x,...C?.root},children:[l!=null&&e(l,{className:i(n.listItemIcon,S?.icon),style:C?.icon}),s(`div`,{className:i(n.listItemLabels,S?.labels),style:C?.labels,children:[N,D&&o(`div`,{id:`${E}-subtitle`,className:i(n.listItemSubtitle,S?.subtitle),style:C?.subtitle,children:d})]}),O&&o(`div`,{id:`${E}-end`,className:i(n.listItemEndContent,S?.endContent),style:C?.endContent,children:f}),y&&e(a,{className:i(n.listItemChevron,S?.chevron),style:C?.chevron})]})}export{l as default};
2
+ //# sourceMappingURL=listItem.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"listItem.mjs","names":[],"sources":["../../../../package/common/listItem/listItem.tsx"],"sourcesContent":["import { useId, type ReactElement, type ReactNode } from 'react';\nimport cx from 'classnames';\nimport { faChevronRight } from '@fortawesome/free-solid-svg-icons';\n\nimport type { ListItemProps } from './listItem.types';\nimport styles from './listItem.module.pcss';\nimport { renderIcon } from '../utils/renderIcon';\nimport { useLinkClick } from '../utils/navigation';\n\n// `subtitle={isOverdue && 'Overdue'}` passes false, which renders nothing and needs no box.\nconst isShown = (node: ReactNode) => node != null && typeof node !== 'boolean' && node !== '';\n\nfunction ListItem({\n icon,\n title,\n subtitle,\n endContent,\n href,\n target,\n rel,\n download,\n onClick,\n selected = false,\n chevron = href !== undefined,\n className,\n style,\n classNames,\n styles: slotStyles,\n ...rest\n}: ListItemProps): ReactElement {\n const followLink = useLinkClick();\n const id = useId();\n const hasSubtitle = isShown(subtitle);\n const hasEndContent = isShown(endContent);\n const isInteractive = href !== undefined || onClick !== undefined;\n // A status in endContent (\"Open\") is part of what the row says, so the link is described by it\n // too, where it is text: a control there would only read its own name a second time.\n const describedBy = [hasSubtitle && `${id}-subtitle`, typeof endContent === 'string' && `${id}-end`]\n .filter(Boolean)\n .join(' ');\n\n const titleElement = (\n <span className={cx(styles.listItemTitle, classNames?.title)} style={slotStyles?.title}>\n {title}\n </span>\n );\n // Only the title is the link or button: the rest of the row can then hold controls of its own,\n // which an <a> or <button> may not contain. Its ::after stretches over the whole row instead.\n const triggerProps = {\n className: cx(styles.listItemTrigger, classNames?.trigger),\n style: slotStyles?.trigger,\n 'aria-describedby': describedBy || undefined,\n };\n const trigger =\n href !== undefined ? (\n <a\n {...triggerProps}\n href={href}\n target={target}\n rel={rel}\n download={download}\n aria-current={selected ? 'page' : undefined}\n onClick={(event) => {\n onClick?.(event);\n followLink(event);\n }}\n >\n {titleElement}\n </a>\n ) : onClick ? (\n <button {...triggerProps} type='button' aria-pressed={selected || undefined} onClick={onClick}>\n {titleElement}\n </button>\n ) : (\n titleElement\n );\n\n return (\n <div\n {...rest}\n className={cx(\n styles.listItem,\n { [styles.listItemInteractive]: isInteractive, [styles.listItemSelected]: selected },\n className,\n classNames?.root,\n )}\n style={{ ...style, ...slotStyles?.root }}\n >\n {icon != null &&\n renderIcon(icon, { className: cx(styles.listItemIcon, classNames?.icon), style: slotStyles?.icon })}\n <div className={cx(styles.listItemLabels, classNames?.labels)} style={slotStyles?.labels}>\n {trigger}\n {hasSubtitle && (\n <div\n id={`${id}-subtitle`}\n className={cx(styles.listItemSubtitle, classNames?.subtitle)}\n style={slotStyles?.subtitle}\n >\n {subtitle}\n </div>\n )}\n </div>\n {hasEndContent && (\n <div\n id={`${id}-end`}\n className={cx(styles.listItemEndContent, classNames?.endContent)}\n style={slotStyles?.endContent}\n >\n {endContent}\n </div>\n )}\n {chevron &&\n renderIcon(faChevronRight, {\n className: cx(styles.listItemChevron, classNames?.chevron),\n style: slotStyles?.chevron,\n })}\n </div>\n );\n}\n\nexport default ListItem;\n"],"mappings":"2UAUA,IAAM,EAAW,GAAoB,GAAQ,MAAQ,OAAO,GAAS,WAAa,IAAS,GAE3F,SAAS,EAAS,CAChB,OACA,QACA,WACA,aACA,OACA,SACA,MACA,WACA,UACA,WAAW,GACX,UAAU,IAAS,IAAA,GACnB,YACA,QACA,aACA,OAAQ,EACR,GAAG,GAC2B,CAC9B,IAAM,EAAa,EAAa,EAC1B,EAAK,EAAM,EACX,EAAc,EAAQ,CAAQ,EAC9B,EAAgB,EAAQ,CAAU,EAClC,EAAgB,IAAS,IAAA,IAAa,IAAY,IAAA,GAGlD,EAAc,CAAC,GAAe,GAAG,EAAG,WAAY,OAAO,GAAe,UAAY,GAAG,EAAG,KAAK,CAAC,CACjG,OAAO,OAAO,CAAC,CACf,KAAK,GAAG,EAEL,EACJ,EAAC,OAAD,CAAM,UAAW,EAAG,EAAO,cAAe,GAAY,KAAK,EAAG,MAAO,GAAY,MAC9E,SAAA,CACG,CAAA,EAIF,EAAe,CACnB,UAAW,EAAG,EAAO,gBAAiB,GAAY,OAAO,EACzD,MAAO,GAAY,QACnB,mBAAoB,GAAe,IAAA,EACrC,EACM,EACJ,IAAS,IAAA,GAeL,EACF,EAAC,SAAD,CAAQ,GAAI,EAAc,KAAK,SAAS,eAAc,GAAY,IAAA,GAAoB,UACnF,SAAA,CACK,CAAA,EAER,EAnBA,EAAC,IAAD,CACE,GAAI,EACE,OACE,SACH,MACK,WACV,eAAc,EAAW,OAAS,IAAA,GAClC,QAAU,GAAU,CAClB,IAAU,CAAK,EACf,EAAW,CAAK,CAClB,EAEC,SAAA,CACA,CAAA,EASP,OACE,EAAC,MAAD,CACE,GAAI,EACJ,UAAW,EACT,EAAO,SACP,EAAG,EAAO,qBAAsB,GAAgB,EAAO,kBAAmB,CAAS,EACnF,EACA,GAAY,IACd,EACA,MAAO,CAAE,GAAG,EAAO,GAAG,GAAY,IAAK,EARzC,SAAA,CAUG,GAAQ,MACP,EAAW,EAAM,CAAE,UAAW,EAAG,EAAO,aAAc,GAAY,IAAI,EAAG,MAAO,GAAY,IAAK,CAAC,EACpG,EAAC,MAAD,CAAK,UAAW,EAAG,EAAO,eAAgB,GAAY,MAAM,EAAG,MAAO,GAAY,OAAlF,SAAA,CACG,EACA,GACC,EAAC,MAAD,CACE,GAAI,GAAG,EAAG,WACV,UAAW,EAAG,EAAO,iBAAkB,GAAY,QAAQ,EAC3D,MAAO,GAAY,SAElB,SAAA,CACE,CAAA,CAEJ,IACJ,GACC,EAAC,MAAD,CACE,GAAI,GAAG,EAAG,MACV,UAAW,EAAG,EAAO,mBAAoB,GAAY,UAAU,EAC/D,MAAO,GAAY,WAElB,SAAA,CACE,CAAA,EAEN,GACC,EAAW,EAAgB,CACzB,UAAW,EAAG,EAAO,gBAAiB,GAAY,OAAO,EACzD,MAAO,GAAY,OACrB,CAAC,CACA,GAET"}
@@ -0,0 +1,2 @@
1
+ "use client";var e=`listItem_i7EoH`,t=`listItem-icon_HEdQy`,n=`listItem-labels_dZXiH`,r=`listItem-title_zmlAW`,i=`listItem-trigger_07n1-`,a=`listItem-selected_zY4Ni`,o=`listItem-subtitle_-XwvP`,s=`listItem-endContent_cQoge`,c=`listItem-chevron_19GEH`,l=`listItem-interactive_GFbY-`,u={listItem:e,"listItem-icon":`listItem-icon_HEdQy`,listItemIcon:t,"listItem-labels":`listItem-labels_dZXiH`,listItemLabels:n,"listItem-title":`listItem-title_zmlAW`,listItemTitle:r,"listItem-trigger":`listItem-trigger_07n1-`,listItemTrigger:i,"listItem-selected":`listItem-selected_zY4Ni`,listItemSelected:a,"listItem-subtitle":`listItem-subtitle_-XwvP`,listItemSubtitle:o,"listItem-endContent":`listItem-endContent_cQoge`,listItemEndContent:s,"listItem-chevron":`listItem-chevron_19GEH`,listItemChevron:c,"listItem-interactive":`listItem-interactive_GFbY-`,listItemInteractive:l};export{u as default,e as listItem,c as listItemChevron,s as listItemEndContent,t as listItemIcon,l as listItemInteractive,n as listItemLabels,a as listItemSelected,o as listItemSubtitle,r as listItemTitle,i as listItemTrigger};
2
+ //# sourceMappingURL=listItem.module.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"listItem.module.mjs","names":[],"sources":["../../../../package/common/listItem/listItem.module.pcss"],"sourcesContent":["/* position: relative so the trigger's ::after can stretch over the whole row, and isolation so\n its z-index stays inside the row instead of rising over a sticky header of the page. */\n.listItem {\n position: relative;\n isolation: isolate;\n display: flex;\n align-items: center;\n gap: var(--spacing-m, 8px);\n box-sizing: border-box;\n width: 100%;\n min-height: var(--list-item-min-height, 48px);\n padding: var(--spacing-m, 8px);\n\n &-icon {\n /* FontAwesome's own rule is unlayered and outranks `width` from inside the library's layer. */\n --fa-width: 1.25em;\n\n flex-shrink: 0;\n }\n\n /* min-width: 0 lets the labels shrink, so a long title ellipses instead of pushing\n endContent and the chevron out of the row. */\n &-labels {\n display: flex;\n flex: 1 1 auto;\n flex-direction: column;\n gap: 2px;\n min-width: 0;\n }\n\n &-title {\n display: block;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n\n /* The <a> or <button> around the title. */\n &-trigger {\n display: block;\n margin: 0;\n padding: 0;\n border: none;\n background: none;\n color: inherit;\n font: inherit;\n text-align: start;\n text-decoration: none;\n cursor: pointer;\n -webkit-tap-highlight-color: transparent;\n\n /* Over the whole row. It belongs to the link, so a middle click and a long press anywhere on\n the row act on the link too. */\n\n /* z-index above content that positions itself, a Chip among many, which would otherwise\n paint over it in tree order and swallow the click. */\n &::after {\n content: '';\n position: absolute;\n inset: 0;\n z-index: 1;\n transition: background-color 0.15s;\n }\n\n /* A tint of the text colour, so it shows on any surface the row sits on. (hover: hover)\n because on touch a tap latches :hover until the next tap elsewhere. */\n @media (hover: hover) {\n &:hover::after {\n background-color: color-mix(in srgb, currentcolor 6%, transparent);\n }\n }\n\n &:active::after {\n background-color: color-mix(in srgb, currentcolor 12%, transparent);\n }\n\n /* On the stretched area, to ring the row rather than the title. Inside the edge: a row\n usually fills a card that clips its overflow. */\n &:focus-visible {\n outline: none;\n }\n\n &:focus-visible::after {\n outline: 2px solid var(--focus-border-color, var(--primary-color));\n outline-offset: -2px;\n }\n }\n\n /* Under the trigger's hover tint, which still shows on top of it. */\n &-selected {\n background-color: var(--list-item-selected-background, color-mix(in srgb, var(--primary-color) 12%, transparent));\n }\n\n &-subtitle {\n display: -webkit-box;\n overflow: hidden;\n color: var(--text-dark);\n font-size: 0.85em;\n -webkit-box-orient: vertical;\n -webkit-line-clamp: 2;\n line-clamp: 2;\n }\n\n &-endContent {\n display: flex;\n flex-shrink: 0;\n align-items: center;\n gap: var(--spacing-s, 4px);\n }\n\n &-chevron {\n flex-shrink: 0;\n color: var(--text-dark);\n font-size: 0.85em;\n }\n}\n\n/* Controls elsewhere in the row sit above the stretched area, so they stay clickable while the\n text around them still opens the row. Any `a`, not `a[href]`: a disabled link Button drops its\n href, and a click on it must not open the row. All in :where(), for no specificity at all: a\n control's own position wins, so an input it positions absolutely stays absolute. */\n:where(.listItem-interactive)\n :where(a, button, input, select, textarea, label, [tabindex]):where(:not(.listItem-trigger)) {\n position: relative;\n z-index: 2;\n}\n"],"mappings":""}
@@ -1,2 +1,2 @@
1
- "use client";import{isSelfActivation as e}from"../utils/activationKey.mjs";import{ariaKeyshortcuts as t,formatHotkey as n}from"../hooks/useHotkeys.mjs";import{PopoverAlign as r,PopoverPlacement as i}from"../popover/popover.types.mjs";import{useFocusBoundary as a}from"../hooks/useFocusBoundary.mjs";import o from"../popover/popover.mjs";import{isMenuAction as s,isMenuHeading as c,isMenuSeparator as l}from"./menu.types.mjs";import{hasAnyIcon as u,renderItemIcon as d}from"./menuItem.mjs";import f from"./menu.module.mjs";import{cloneElement as ee,isValidElement as p,useEffect as m,useId as h,useRef as g,useState as _}from"react";import v from"classnames";import{Fragment as te,jsx as y,jsxs as b}from"react/jsx-runtime";var x=600;function S(e,t,n){for(let r=1;r<=e.length;r++){let i=(t+n*r+e.length*r)%e.length,a=e[i];if(s(a)&&!a.disabled)return i}return-1}function C(e){return e.findIndex(e=>s(e)&&!e.disabled)}function w(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(s(n)&&!n.disabled)return t}return-1}function T({items:T,children:E,onAction:D,isOpen:O,onOpenChange:k,placement:A=i.Bottom,align:ne=r.Start,presentation:re,className:ie,style:ae,classNames:j,styles:M,...N}){let P=O!==void 0,[F,I]=_(!1),L=P?O:F,[R,z]=_(-1),B=g([]),V=g(null),H=g(null),{restoreFocusToTrigger:U,focusAfterTrigger:W}=a({triggerRef:V,contentRef:H}),G=h(),K=g(`first`),q=g({query:``,timer:void 0}),J=g(!1);function Y(e,t=!1){e&&(J.current=t),P||I(e),k?.(e)}let X=g(T);m(()=>{X.current=T}),m(()=>{if(!L)return;if(!J.current){z(-1);return}let e=X.current,t=K.current===`last`?w(e):C(e);z(t);let n=requestAnimationFrame(()=>{B.current[t]?.focus()});return()=>{cancelAnimationFrame(n),K.current=`first`}},[L]),m(()=>()=>clearTimeout(q.current.timer),[]);function Z(e){e<0||(z(e),B.current[e]?.focus())}function Q(e){Y(!1),e&&U()}function oe(e){if(e.length!==1||!e.trim())return!1;clearTimeout(q.current.timer),q.current.query+=e.toLowerCase(),q.current.timer=setTimeout(()=>{q.current.query=``},x);let t=q.current.query,n=t.length>1&&[...t].every(e=>e===t[0]),r=n?t[0]:t,i=n||t.length===1?R:R-1;for(let e=1;e<=T.length;e++){let t=(i+e+T.length)%T.length,n=T[t];if(s(n)&&!n.disabled&&(B.current[t]?.textContent?.trim().toLowerCase()??``).startsWith(r))return Z(t),!0}return!1}function se(e){if(e.key===`ArrowDown`||e.key===`ArrowUp`){if(e.preventDefault(),e.stopPropagation(),L){Z(e.key===`ArrowUp`?w(T):C(T));return}K.current=e.key===`ArrowUp`?`last`:`first`,Y(!0,!0)}}function ce(e){switch(e.key){case`ArrowDown`:Z(S(T,R,1));break;case`ArrowUp`:Z(R<0?w(T):S(T,R,-1));break;case`Home`:Z(C(T));break;case`End`:Z(w(T));break;case`Escape`:Q(!0);break;case`Tab`:Q(!1),e.shiftKey?U():W();break;default:if(!oe(e.key))return}e.preventDefault(),e.stopPropagation()}function le(e){let t=T[e];s(t)&&!t.disabled&&(t.onClick?.(),D?.(t.id),Q(!0))}let $=p(E)?ee(E,{"aria-haspopup":E.props[`aria-haspopup`]??`menu`,"aria-expanded":E.props[`aria-expanded`]??L,"aria-controls":L?E.props[`aria-controls`]??G:E.props[`aria-controls`]}):E,ue=u(T),de=y(`div`,{ref:H,id:G,role:`menu`,className:v(f.menu,j?.menu),style:M?.menu,onKeyDown:ce,children:T.map((r,i)=>{if(l(r))return y(`div`,{role:`separator`,className:v(f.menuSeparator,j?.separator),style:M?.separator},`separator-${i}`);if(c(r))return y(`div`,{role:`presentation`,className:v(f.menuHeading,j?.heading),style:M?.heading,children:r.heading},`heading-${i}`);let a={ref:e=>{B.current[i]=e},role:`menuitem`,"aria-keyshortcuts":t(r.shortcut),tabIndex:i===R?0:-1,className:v(f.menuItem,r.danger&&f.menuItemDanger,j?.item),style:M?.item,onClick:()=>le(i),onMouseEnter:()=>z(i)},o=b(te,{children:[d(r.icon,ue,{className:v(f.menuItemIcon,j?.itemIcon),style:M?.itemIcon}),y(`span`,{className:v(f.menuItemLabel,j?.itemLabel),style:M?.itemLabel,children:r.label}),r.shortcut!=null&&y(`span`,{"aria-hidden":!0,className:v(f.menuItemShortcut,j?.itemShortcut),style:M?.itemShortcut,children:n(r.shortcut)})]});return r.href&&!r.disabled?y(`a`,{href:r.href,...a,onKeyDown:t=>{t.key===` `&&e(t)&&(t.preventDefault(),t.currentTarget.click())},children:o},r.id):y(`button`,{type:`button`,disabled:r.disabled,...a,children:o},r.id)})});return y(o,{...N,isOpen:L,onOpenChange:(e,{fromKeyboard:t})=>Y(e,t),placement:A,align:ne,presentation:re,content:de,focusOnOpen:!1,constrainWidth:!1,classNames:{panel:f.menuPanel},className:v(ie,j?.root),style:{...ae,...M?.root},children:y(`span`,{ref:V,className:v(f.menuTrigger,j?.trigger),style:M?.trigger,onKeyDown:se,children:$})})}export{T as default};
1
+ "use client";import{isSelfActivation as e}from"../utils/activationKey.mjs";import{ariaKeyshortcuts as t,formatHotkey as n}from"../hooks/useHotkeys.mjs";import{useLinkClick as r}from"../utils/navigation.mjs";import{PopoverAlign as i,PopoverPlacement as a}from"../popover/popover.types.mjs";import{useFocusBoundary as o}from"../hooks/useFocusBoundary.mjs";import ee from"../popover/popover.mjs";import{isMenuAction as s,isMenuHeading as c,isMenuSeparator as te}from"./menu.types.mjs";import{hasAnyIcon as l,renderItemIcon as u}from"./menuItem.mjs";import d from"./menu.module.mjs";import{cloneElement as ne,isValidElement as re,useEffect as f,useId as ie,useRef as p,useState as m}from"react";import h from"classnames";import{Fragment as g,jsx as _,jsxs as ae}from"react/jsx-runtime";var oe=600;function v(e,t,n){for(let r=1;r<=e.length;r++){let i=(t+n*r+e.length*r)%e.length,a=e[i];if(s(a)&&!a.disabled)return i}return-1}function y(e){return e.findIndex(e=>s(e)&&!e.disabled)}function b(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(s(n)&&!n.disabled)return t}return-1}function x({items:x,children:S,onAction:C,isOpen:w,onOpenChange:T,placement:E=a.Bottom,align:D=i.Start,presentation:O,className:k,style:A,classNames:j,styles:M,...se}){let N=w!==void 0,[P,F]=m(!1),I=N?w:P,[L,R]=m(-1),z=p([]),B=p(null),V=p(null),{restoreFocusToTrigger:H,focusAfterTrigger:U}=o({triggerRef:B,contentRef:V}),W=ie(),G=r(),K=p(`first`),q=p({query:``,timer:void 0}),J=p(!1);function Y(e,t=!1){e&&(J.current=t),N||F(e),T?.(e)}let X=p(x);f(()=>{X.current=x}),f(()=>{if(!I)return;if(!J.current){R(-1);return}let e=X.current,t=K.current===`last`?b(e):y(e);R(t);let n=requestAnimationFrame(()=>{z.current[t]?.focus()});return()=>{cancelAnimationFrame(n),K.current=`first`}},[I]),f(()=>()=>clearTimeout(q.current.timer),[]);function Z(e){e<0||(R(e),z.current[e]?.focus())}function Q(e){Y(!1),e&&H()}function ce(e){if(e.length!==1||!e.trim())return!1;clearTimeout(q.current.timer),q.current.query+=e.toLowerCase(),q.current.timer=setTimeout(()=>{q.current.query=``},oe);let t=q.current.query,n=t.length>1&&[...t].every(e=>e===t[0]),r=n?t[0]:t,i=n||t.length===1?L:L-1;for(let e=1;e<=x.length;e++){let t=(i+e+x.length)%x.length,n=x[t];if(s(n)&&!n.disabled&&(z.current[t]?.textContent?.trim().toLowerCase()??``).startsWith(r))return Z(t),!0}return!1}function le(e){if(e.key===`ArrowDown`||e.key===`ArrowUp`){if(e.preventDefault(),e.stopPropagation(),I){Z(e.key===`ArrowUp`?b(x):y(x));return}K.current=e.key===`ArrowUp`?`last`:`first`,Y(!0,!0)}}function ue(e){switch(e.key){case`ArrowDown`:Z(v(x,L,1));break;case`ArrowUp`:Z(L<0?b(x):v(x,L,-1));break;case`Home`:Z(y(x));break;case`End`:Z(b(x));break;case`Escape`:Q(!0);break;case`Tab`:Q(!1),e.shiftKey?H():U();break;default:if(!ce(e.key))return}e.preventDefault(),e.stopPropagation()}function $(e){let t=x[e];s(t)&&!t.disabled&&(t.onClick?.(),C?.(t.id),Q(!0))}let de=re(S)?ne(S,{"aria-haspopup":S.props[`aria-haspopup`]??`menu`,"aria-expanded":S.props[`aria-expanded`]??I,"aria-controls":I?S.props[`aria-controls`]??W:S.props[`aria-controls`]}):S,fe=l(x),pe=_(`div`,{ref:V,id:W,role:`menu`,className:h(d.menu,j?.menu),style:M?.menu,onKeyDown:ue,children:x.map((r,i)=>{if(te(r))return _(`div`,{role:`separator`,className:h(d.menuSeparator,j?.separator),style:M?.separator},`separator-${i}`);if(c(r))return _(`div`,{role:`presentation`,className:h(d.menuHeading,j?.heading),style:M?.heading,children:r.heading},`heading-${i}`);let a={ref:e=>{z.current[i]=e},role:`menuitem`,"aria-keyshortcuts":t(r.shortcut),tabIndex:i===L?0:-1,className:h(d.menuItem,r.danger&&d.menuItemDanger,j?.item),style:M?.item,onClick:()=>$(i),onMouseEnter:()=>R(i)},o=ae(g,{children:[u(r.icon,fe,{className:h(d.menuItemIcon,j?.itemIcon),style:M?.itemIcon}),_(`span`,{className:h(d.menuItemLabel,j?.itemLabel),style:M?.itemLabel,children:r.label}),r.shortcut!=null&&_(`span`,{"aria-hidden":!0,className:h(d.menuItemShortcut,j?.itemShortcut),style:M?.itemShortcut,children:n(r.shortcut)})]});return r.href&&!r.disabled?_(`a`,{href:r.href,...a,onClick:e=>{$(i),G(e)},onKeyDown:t=>{t.key===` `&&e(t)&&(t.preventDefault(),t.currentTarget.click())},children:o},r.id):_(`button`,{type:`button`,disabled:r.disabled,...a,children:o},r.id)})});return _(ee,{...se,isOpen:I,onOpenChange:(e,{fromKeyboard:t})=>Y(e,t),placement:E,align:D,presentation:O,content:pe,focusOnOpen:!1,constrainWidth:!1,classNames:{panel:d.menuPanel},className:h(k,j?.root),style:{...A,...M?.root},children:_(`span`,{ref:B,className:h(d.menuTrigger,j?.trigger),style:M?.trigger,onKeyDown:le,children:de})})}export{x as default};
2
2
  //# sourceMappingURL=menu.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"menu.mjs","names":[],"sources":["../../../../package/common/menu/menu.tsx"],"sourcesContent":["import { cloneElement, isValidElement, useEffect, useId, useRef, useState, type ReactElement } from 'react';\nimport cx from 'classnames';\n\nimport styles from './menu.module.pcss';\nimport Popover from '../popover';\nimport { PopoverAlign, PopoverPlacement } from '../popover/popover.types';\nimport { isSelfActivation } from '../utils/activationKey';\nimport { useFocusBoundary } from '../hooks/useFocusBoundary';\nimport { ariaKeyshortcuts, formatHotkey } from '../hooks/useHotkeys';\nimport { isMenuAction, isMenuHeading, isMenuSeparator, type MenuEntry, type MenuProps } from './menu.types';\nimport { hasAnyIcon, renderItemIcon } from './menuItem';\n\n/** How long a typed run stays one search before it starts over. */\nconst TYPEAHEAD_RESET_MS = 600;\n\n/** Index of the next action that can be focused, wrapping, or -1 if there is none. */\nfunction nextEnabled(items: MenuEntry[], from: number, step: 1 | -1): number {\n for (let i = 1; i <= items.length; i++) {\n // The `items.length * i` term only keeps the value positive for a backwards\n // step; JavaScript's `%` would otherwise return a negative index.\n const index = (from + step * i + items.length * i) % items.length;\n const entry = items[index];\n if (isMenuAction(entry) && !entry.disabled) return index;\n }\n return -1;\n}\n\nfunction firstEnabled(items: MenuEntry[]): number {\n return items.findIndex((entry) => isMenuAction(entry) && !entry.disabled);\n}\n\nfunction lastEnabled(items: MenuEntry[]): number {\n for (let i = items.length - 1; i >= 0; i--) {\n const entry = items[i];\n if (isMenuAction(entry) && !entry.disabled) return i;\n }\n return -1;\n}\n\n/**\n * A menu of actions on a trigger of your choosing.\n *\n * `Popover` does the anchoring, portalling and outside-click work but takes\n * arbitrary `content`, which leaves every consumer to write their own `ul`/`li`\n * and, in practice, to leave out the roles and the arrow keys. This is that list,\n * done once: `role=\"menu\"`, a roving focus that skips disabled entries, Escape\n * back to the trigger, and separators and headings that stay out of the keyboard\n * order.\n */\nfunction Menu({\n items,\n children,\n onAction,\n isOpen: controlledOpen,\n onOpenChange,\n placement = PopoverPlacement.Bottom,\n align = PopoverAlign.Start,\n presentation,\n className,\n style,\n classNames,\n styles: slotStyles,\n ...rest\n}: MenuProps): ReactElement {\n const isControlled = controlledOpen !== undefined;\n const [internalOpen, setInternalOpen] = useState(false);\n const isOpen = isControlled ? controlledOpen : internalOpen;\n\n const [activeIndex, setActiveIndex] = useState(-1);\n const itemRefs = useRef<(HTMLElement | null)[]>([]);\n const triggerRef = useRef<HTMLSpanElement>(null);\n const menuRef = useRef<HTMLDivElement>(null);\n // Tab leaves the panel in both directions, so the menu needs the same boundary\n // Popover uses: back to the trigger, or on to whatever follows it.\n const { restoreFocusToTrigger, focusAfterTrigger } = useFocusBoundary({ triggerRef, contentRef: menuRef });\n const menuId = useId();\n // Which end to land on when the menu opens: `ArrowUp` on the trigger opens at\n // the bottom, everything else at the top.\n const openAtRef = useRef<'first' | 'last'>('first');\n const typeahead = useRef<{ query: string; timer: ReturnType<typeof setTimeout> | undefined }>({\n query: '',\n timer: undefined,\n });\n\n // Whether a key opened the menu, which decides between landing the focus on an\n // entry and leaving it on the trigger. Set from Popover, which is what sees the\n // trigger's events, or here when an arrow key did the opening.\n const openedByKeyboardRef = useRef(false);\n\n function setOpen(next: boolean, fromKeyboard = false) {\n if (next) openedByKeyboardRef.current = fromKeyboard;\n if (!isControlled) setInternalOpen(next);\n onOpenChange?.(next);\n }\n\n // The effect below needs the entries, but must not re-run when the array is rebuilt. A consumer\n // writes `items={[…]}` inline, so it is a new identity on every render of *their* component:\n // keyed off it, any parent re-render while the menu was open threw the focus back to the first\n // entry, mid-navigation. Declared above the effect that reads it, so it has already run.\n const itemsRef = useRef(items);\n useEffect(() => {\n itemsRef.current = items;\n });\n\n // Focus follows the active entry rather than the menu keeping focus and\n // pointing at it: the items are real buttons, so Enter and Space are theirs.\n // Popover's own `focusOnOpen` would take the first focusable and stop there;\n // the active index has to move with it, so the menu does it itself.\n useEffect(() => {\n if (!isOpen) return;\n // A pointer open leaves the focus where the pointer put it. A highlight on an\n // entry nobody pointed at reads as a selection, and the mouse is about to land\n // somewhere else anyway; the first arrow key moves in, see the trigger's keys.\n if (!openedByKeyboardRef.current) {\n setActiveIndex(-1);\n return;\n }\n const entries = itemsRef.current;\n const target = openAtRef.current === 'last' ? lastEnabled(entries) : firstEnabled(entries);\n setActiveIndex(target);\n // The panel is portalled and animated in, so its buttons exist a frame later.\n const frame = requestAnimationFrame(() => {\n itemRefs.current[target]?.focus();\n });\n return () => {\n cancelAnimationFrame(frame);\n openAtRef.current = 'first';\n };\n }, [isOpen]);\n\n useEffect(() => () => clearTimeout(typeahead.current.timer), []);\n\n function moveTo(index: number) {\n if (index < 0) return;\n setActiveIndex(index);\n itemRefs.current[index]?.focus();\n }\n\n function close(returnFocus: boolean) {\n setOpen(false);\n if (returnFocus) restoreFocusToTrigger();\n }\n\n /**\n * Jumps to the next entry whose label starts with what has been typed. The\n * text comes off the rendered button rather than the `label` prop, which is a\n * `ReactNode` and may be an icon, a badge or anything else.\n */\n function handleTypeahead(key: string): boolean {\n if (key.length !== 1 || !key.trim()) return false;\n clearTimeout(typeahead.current.timer);\n typeahead.current.query += key.toLowerCase();\n typeahead.current.timer = setTimeout(() => {\n typeahead.current.query = '';\n }, TYPEAHEAD_RESET_MS);\n\n const query = typeahead.current.query;\n // A repeated single character walks through the entries starting with it,\n // rather than sticking to the first one.\n const repeated = query.length > 1 && [...query].every((c) => c === query[0]);\n const needle = repeated ? query[0] : query;\n const from = repeated || query.length === 1 ? activeIndex : activeIndex - 1;\n\n for (let i = 1; i <= items.length; i++) {\n const index = (from + i + items.length) % items.length;\n const entry = items[index];\n if (!isMenuAction(entry) || entry.disabled) continue;\n const text = itemRefs.current[index]?.textContent?.trim().toLowerCase() ?? '';\n if (text.startsWith(needle)) {\n moveTo(index);\n return true;\n }\n }\n return false;\n }\n\n /** The trigger's own keys, which decide where the menu opens. */\n function handleTriggerKeyDown(event: React.KeyboardEvent) {\n if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return;\n // Popover opens on these keys too; letting both act would be harmless but\n // this keeps the decision about where to land in one place.\n event.preventDefault();\n event.stopPropagation();\n // Already open means a pointer opened it and the focus never left the trigger,\n // since an entry's own keys never reach here. This is the key that moves in.\n if (isOpen) {\n moveTo(event.key === 'ArrowUp' ? lastEnabled(items) : firstEnabled(items));\n return;\n }\n openAtRef.current = event.key === 'ArrowUp' ? 'last' : 'first';\n setOpen(true, true);\n }\n\n function handleKeyDown(event: React.KeyboardEvent) {\n switch (event.key) {\n case 'ArrowDown':\n moveTo(nextEnabled(items, activeIndex, 1));\n break;\n case 'ArrowUp':\n // Stepping back from \"nothing active\" lands two short of the end, so the end is named.\n moveTo(activeIndex < 0 ? lastEnabled(items) : nextEnabled(items, activeIndex, -1));\n break;\n case 'Home':\n moveTo(firstEnabled(items));\n break;\n case 'End':\n moveTo(lastEnabled(items));\n break;\n // Popover handles both of these too, but only once the focus has actually\n // reached the panel: its Escape restores focus on that condition, and its\n // Tab handling acts at the first and last focusable. A menu focuses its\n // first entry a frame after opening, so a key pressed in between would\n // fall through. Here they are unconditional, which is also what a menu\n // wants from Tab: leave, whatever is focused.\n case 'Escape':\n close(true);\n break;\n case 'Tab':\n // Carry on from the trigger, as if the panel had never been in the tab\n // order. Closing and letting the browser take it from here would move on\n // from an entry that is about to be removed, which lands at the top of\n // the document.\n close(false);\n if (event.shiftKey) restoreFocusToTrigger();\n else focusAfterTrigger();\n break;\n default:\n if (!handleTypeahead(event.key)) return;\n }\n event.preventDefault();\n event.stopPropagation();\n }\n\n function handleAction(index: number) {\n const entry = items[index];\n if (!isMenuAction(entry) || entry.disabled) return;\n // Not runMenuAction: a link entry is an <a>, which the browser follows by itself.\n entry.onClick?.();\n onAction?.(entry.id);\n close(true);\n }\n\n // A screen reader has no way to tell that this button opens a menu unless the\n // button itself says so. Only filled in where the consumer has not, so a\n // trigger that describes itself keeps doing that.\n const triggerWithMenuSemantics = isValidElement<Record<string, unknown>>(children)\n ? cloneElement(children, {\n 'aria-haspopup': children.props['aria-haspopup'] ?? 'menu',\n 'aria-expanded': children.props['aria-expanded'] ?? isOpen,\n 'aria-controls': isOpen ? (children.props['aria-controls'] ?? menuId) : children.props['aria-controls'],\n })\n : children;\n\n const hasIcons = hasAnyIcon(items);\n\n const content = (\n <div\n ref={menuRef}\n id={menuId}\n role='menu'\n className={cx(styles.menu, classNames?.menu)}\n style={slotStyles?.menu}\n onKeyDown={handleKeyDown}\n >\n {items.map((entry, index) => {\n if (isMenuSeparator(entry))\n return (\n <div\n // Separators and headings carry no id of their own, and reordering\n // the list re-renders it wholesale anyway.\n key={`separator-${index}`}\n role='separator'\n className={cx(styles.menuSeparator, classNames?.separator)}\n style={slotStyles?.separator}\n />\n );\n\n if (isMenuHeading(entry))\n return (\n <div\n key={`heading-${index}`}\n role='presentation'\n className={cx(styles.menuHeading, classNames?.heading)}\n style={slotStyles?.heading}\n >\n {entry.heading}\n </div>\n );\n\n const itemProps = {\n ref: (el: HTMLElement | null) => {\n itemRefs.current[index] = el;\n },\n role: 'menuitem',\n 'aria-keyshortcuts': ariaKeyshortcuts(entry.shortcut),\n // One tab stop for the whole menu: the arrow keys move between items.\n tabIndex: index === activeIndex ? 0 : -1,\n className: cx(styles.menuItem, entry.danger && styles.menuItemDanger, classNames?.item),\n style: slotStyles?.item,\n onClick: () => handleAction(index),\n onMouseEnter: () => setActiveIndex(index),\n };\n const itemContent = (\n <>\n {renderItemIcon(entry.icon, hasIcons, {\n className: cx(styles.menuItemIcon, classNames?.itemIcon),\n style: slotStyles?.itemIcon,\n })}\n <span className={cx(styles.menuItemLabel, classNames?.itemLabel)} style={slotStyles?.itemLabel}>\n {entry.label}\n </span>\n {entry.shortcut != null && (\n <span\n aria-hidden\n className={cx(styles.menuItemShortcut, classNames?.itemShortcut)}\n style={slotStyles?.itemShortcut}\n >\n {formatHotkey(entry.shortcut)}\n </span>\n )}\n </>\n );\n\n // An <a> cannot be disabled, so a disabled link is a disabled button.\n return entry.href && !entry.disabled ? (\n <a\n key={entry.id}\n href={entry.href}\n {...itemProps}\n // A link takes Enter but not Space, which every other entry answers to.\n onKeyDown={(event) => {\n if (event.key !== ' ' || !isSelfActivation(event)) return;\n event.preventDefault();\n event.currentTarget.click();\n }}\n >\n {itemContent}\n </a>\n ) : (\n <button key={entry.id} type='button' disabled={entry.disabled} {...itemProps}>\n {itemContent}\n </button>\n );\n })}\n </div>\n );\n\n return (\n <Popover\n {...rest}\n isOpen={isOpen}\n onOpenChange={(next, { fromKeyboard }) => setOpen(next, fromKeyboard)}\n placement={placement}\n align={align}\n presentation={presentation}\n content={content}\n // The list pads its own rows, so a hover highlight reaches the panel edge,\n // and it sizes itself. Focus is the menu's own business, see above.\n focusOnOpen={false}\n constrainWidth={false}\n classNames={{ panel: styles.menuPanel }}\n className={cx(className, classNames?.root)}\n style={{ ...style, ...slotStyles?.root }}\n >\n <span\n ref={triggerRef}\n className={cx(styles.menuTrigger, classNames?.trigger)}\n style={slotStyles?.trigger}\n onKeyDown={handleTriggerKeyDown}\n >\n {triggerWithMenuSemantics}\n </span>\n </Popover>\n );\n}\n\nexport default Menu;\n"],"mappings":"mtBAaA,IAAM,EAAqB,IAG3B,SAAS,EAAY,EAAoB,EAAc,EAAsB,CAC3E,IAAK,IAAI,EAAI,EAAG,GAAK,EAAM,OAAQ,IAAK,CAGtC,IAAM,GAAS,EAAO,EAAO,EAAI,EAAM,OAAS,GAAK,EAAM,OACrD,EAAQ,EAAM,GACpB,GAAI,EAAa,CAAK,GAAK,CAAC,EAAM,SAAU,OAAO,CACrD,CACA,MAAO,EACT,CAEA,SAAS,EAAa,EAA4B,CAChD,OAAO,EAAM,UAAW,GAAU,EAAa,CAAK,GAAK,CAAC,EAAM,QAAQ,CAC1E,CAEA,SAAS,EAAY,EAA4B,CAC/C,IAAK,IAAI,EAAI,EAAM,OAAS,EAAG,GAAK,EAAG,IAAK,CAC1C,IAAM,EAAQ,EAAM,GACpB,GAAI,EAAa,CAAK,GAAK,CAAC,EAAM,SAAU,OAAO,CACrD,CACA,MAAO,EACT,CAYA,SAAS,EAAK,CACZ,QACA,WACA,WACA,OAAQ,EACR,eACA,YAAY,EAAiB,OAC7B,SAAQ,EAAa,MACrB,gBACA,aACA,SACA,aACA,OAAQ,EACR,GAAG,GACuB,CAC1B,IAAM,EAAe,IAAmB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,UAAW,GAEV,SAAA,CACG,CAAA,CACC,CAAA,CAEb"}
1
+ {"version":3,"file":"menu.mjs","names":[],"sources":["../../../../package/common/menu/menu.tsx"],"sourcesContent":["import { cloneElement, isValidElement, useEffect, useId, useRef, useState, type ReactElement } from 'react';\nimport cx from 'classnames';\n\nimport styles from './menu.module.pcss';\nimport Popover from '../popover';\nimport { PopoverAlign, PopoverPlacement } from '../popover/popover.types';\nimport { isSelfActivation } from '../utils/activationKey';\nimport { useLinkClick } from '../utils/navigation';\nimport { useFocusBoundary } from '../hooks/useFocusBoundary';\nimport { ariaKeyshortcuts, formatHotkey } from '../hooks/useHotkeys';\nimport { isMenuAction, isMenuHeading, isMenuSeparator, type MenuEntry, type MenuProps } from './menu.types';\nimport { hasAnyIcon, renderItemIcon } from './menuItem';\n\n/** How long a typed run stays one search before it starts over. */\nconst TYPEAHEAD_RESET_MS = 600;\n\n/** Index of the next action that can be focused, wrapping, or -1 if there is none. */\nfunction nextEnabled(items: MenuEntry[], from: number, step: 1 | -1): number {\n for (let i = 1; i <= items.length; i++) {\n // The `items.length * i` term only keeps the value positive for a backwards\n // step; JavaScript's `%` would otherwise return a negative index.\n const index = (from + step * i + items.length * i) % items.length;\n const entry = items[index];\n if (isMenuAction(entry) && !entry.disabled) return index;\n }\n return -1;\n}\n\nfunction firstEnabled(items: MenuEntry[]): number {\n return items.findIndex((entry) => isMenuAction(entry) && !entry.disabled);\n}\n\nfunction lastEnabled(items: MenuEntry[]): number {\n for (let i = items.length - 1; i >= 0; i--) {\n const entry = items[i];\n if (isMenuAction(entry) && !entry.disabled) return i;\n }\n return -1;\n}\n\n/**\n * A menu of actions on a trigger of your choosing.\n *\n * `Popover` does the anchoring, portalling and outside-click work but takes\n * arbitrary `content`, which leaves every consumer to write their own `ul`/`li`\n * and, in practice, to leave out the roles and the arrow keys. This is that list,\n * done once: `role=\"menu\"`, a roving focus that skips disabled entries, Escape\n * back to the trigger, and separators and headings that stay out of the keyboard\n * order.\n */\nfunction Menu({\n items,\n children,\n onAction,\n isOpen: controlledOpen,\n onOpenChange,\n placement = PopoverPlacement.Bottom,\n align = PopoverAlign.Start,\n presentation,\n className,\n style,\n classNames,\n styles: slotStyles,\n ...rest\n}: MenuProps): ReactElement {\n const isControlled = controlledOpen !== undefined;\n const [internalOpen, setInternalOpen] = useState(false);\n const isOpen = isControlled ? controlledOpen : internalOpen;\n\n const [activeIndex, setActiveIndex] = useState(-1);\n const itemRefs = useRef<(HTMLElement | null)[]>([]);\n const triggerRef = useRef<HTMLSpanElement>(null);\n const menuRef = useRef<HTMLDivElement>(null);\n // Tab leaves the panel in both directions, so the menu needs the same boundary\n // Popover uses: back to the trigger, or on to whatever follows it.\n const { restoreFocusToTrigger, focusAfterTrigger } = useFocusBoundary({ triggerRef, contentRef: menuRef });\n const menuId = useId();\n const followLink = useLinkClick();\n // Which end to land on when the menu opens: `ArrowUp` on the trigger opens at\n // the bottom, everything else at the top.\n const openAtRef = useRef<'first' | 'last'>('first');\n const typeahead = useRef<{ query: string; timer: ReturnType<typeof setTimeout> | undefined }>({\n query: '',\n timer: undefined,\n });\n\n // Whether a key opened the menu, which decides between landing the focus on an\n // entry and leaving it on the trigger. Set from Popover, which is what sees the\n // trigger's events, or here when an arrow key did the opening.\n const openedByKeyboardRef = useRef(false);\n\n function setOpen(next: boolean, fromKeyboard = false) {\n if (next) openedByKeyboardRef.current = fromKeyboard;\n if (!isControlled) setInternalOpen(next);\n onOpenChange?.(next);\n }\n\n // The effect below needs the entries, but must not re-run when the array is rebuilt. A consumer\n // writes `items={[…]}` inline, so it is a new identity on every render of *their* component:\n // keyed off it, any parent re-render while the menu was open threw the focus back to the first\n // entry, mid-navigation. Declared above the effect that reads it, so it has already run.\n const itemsRef = useRef(items);\n useEffect(() => {\n itemsRef.current = items;\n });\n\n // Focus follows the active entry rather than the menu keeping focus and\n // pointing at it: the items are real buttons, so Enter and Space are theirs.\n // Popover's own `focusOnOpen` would take the first focusable and stop there;\n // the active index has to move with it, so the menu does it itself.\n useEffect(() => {\n if (!isOpen) return;\n // A pointer open leaves the focus where the pointer put it. A highlight on an\n // entry nobody pointed at reads as a selection, and the mouse is about to land\n // somewhere else anyway; the first arrow key moves in, see the trigger's keys.\n if (!openedByKeyboardRef.current) {\n setActiveIndex(-1);\n return;\n }\n const entries = itemsRef.current;\n const target = openAtRef.current === 'last' ? lastEnabled(entries) : firstEnabled(entries);\n setActiveIndex(target);\n // The panel is portalled and animated in, so its buttons exist a frame later.\n const frame = requestAnimationFrame(() => {\n itemRefs.current[target]?.focus();\n });\n return () => {\n cancelAnimationFrame(frame);\n openAtRef.current = 'first';\n };\n }, [isOpen]);\n\n useEffect(() => () => clearTimeout(typeahead.current.timer), []);\n\n function moveTo(index: number) {\n if (index < 0) return;\n setActiveIndex(index);\n itemRefs.current[index]?.focus();\n }\n\n function close(returnFocus: boolean) {\n setOpen(false);\n if (returnFocus) restoreFocusToTrigger();\n }\n\n /**\n * Jumps to the next entry whose label starts with what has been typed. The\n * text comes off the rendered button rather than the `label` prop, which is a\n * `ReactNode` and may be an icon, a badge or anything else.\n */\n function handleTypeahead(key: string): boolean {\n if (key.length !== 1 || !key.trim()) return false;\n clearTimeout(typeahead.current.timer);\n typeahead.current.query += key.toLowerCase();\n typeahead.current.timer = setTimeout(() => {\n typeahead.current.query = '';\n }, TYPEAHEAD_RESET_MS);\n\n const query = typeahead.current.query;\n // A repeated single character walks through the entries starting with it,\n // rather than sticking to the first one.\n const repeated = query.length > 1 && [...query].every((c) => c === query[0]);\n const needle = repeated ? query[0] : query;\n const from = repeated || query.length === 1 ? activeIndex : activeIndex - 1;\n\n for (let i = 1; i <= items.length; i++) {\n const index = (from + i + items.length) % items.length;\n const entry = items[index];\n if (!isMenuAction(entry) || entry.disabled) continue;\n const text = itemRefs.current[index]?.textContent?.trim().toLowerCase() ?? '';\n if (text.startsWith(needle)) {\n moveTo(index);\n return true;\n }\n }\n return false;\n }\n\n /** The trigger's own keys, which decide where the menu opens. */\n function handleTriggerKeyDown(event: React.KeyboardEvent) {\n if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return;\n // Popover opens on these keys too; letting both act would be harmless but\n // this keeps the decision about where to land in one place.\n event.preventDefault();\n event.stopPropagation();\n // Already open means a pointer opened it and the focus never left the trigger,\n // since an entry's own keys never reach here. This is the key that moves in.\n if (isOpen) {\n moveTo(event.key === 'ArrowUp' ? lastEnabled(items) : firstEnabled(items));\n return;\n }\n openAtRef.current = event.key === 'ArrowUp' ? 'last' : 'first';\n setOpen(true, true);\n }\n\n function handleKeyDown(event: React.KeyboardEvent) {\n switch (event.key) {\n case 'ArrowDown':\n moveTo(nextEnabled(items, activeIndex, 1));\n break;\n case 'ArrowUp':\n // Stepping back from \"nothing active\" lands two short of the end, so the end is named.\n moveTo(activeIndex < 0 ? lastEnabled(items) : nextEnabled(items, activeIndex, -1));\n break;\n case 'Home':\n moveTo(firstEnabled(items));\n break;\n case 'End':\n moveTo(lastEnabled(items));\n break;\n // Popover handles both of these too, but only once the focus has actually\n // reached the panel: its Escape restores focus on that condition, and its\n // Tab handling acts at the first and last focusable. A menu focuses its\n // first entry a frame after opening, so a key pressed in between would\n // fall through. Here they are unconditional, which is also what a menu\n // wants from Tab: leave, whatever is focused.\n case 'Escape':\n close(true);\n break;\n case 'Tab':\n // Carry on from the trigger, as if the panel had never been in the tab\n // order. Closing and letting the browser take it from here would move on\n // from an entry that is about to be removed, which lands at the top of\n // the document.\n close(false);\n if (event.shiftKey) restoreFocusToTrigger();\n else focusAfterTrigger();\n break;\n default:\n if (!handleTypeahead(event.key)) return;\n }\n event.preventDefault();\n event.stopPropagation();\n }\n\n function handleAction(index: number) {\n const entry = items[index];\n if (!isMenuAction(entry) || entry.disabled) return;\n // Not runMenuAction: a link entry is an <a>, which the browser follows by itself.\n entry.onClick?.();\n onAction?.(entry.id);\n close(true);\n }\n\n // A screen reader has no way to tell that this button opens a menu unless the\n // button itself says so. Only filled in where the consumer has not, so a\n // trigger that describes itself keeps doing that.\n const triggerWithMenuSemantics = isValidElement<Record<string, unknown>>(children)\n ? cloneElement(children, {\n 'aria-haspopup': children.props['aria-haspopup'] ?? 'menu',\n 'aria-expanded': children.props['aria-expanded'] ?? isOpen,\n 'aria-controls': isOpen ? (children.props['aria-controls'] ?? menuId) : children.props['aria-controls'],\n })\n : children;\n\n const hasIcons = hasAnyIcon(items);\n\n const content = (\n <div\n ref={menuRef}\n id={menuId}\n role='menu'\n className={cx(styles.menu, classNames?.menu)}\n style={slotStyles?.menu}\n onKeyDown={handleKeyDown}\n >\n {items.map((entry, index) => {\n if (isMenuSeparator(entry))\n return (\n <div\n // Separators and headings carry no id of their own, and reordering\n // the list re-renders it wholesale anyway.\n key={`separator-${index}`}\n role='separator'\n className={cx(styles.menuSeparator, classNames?.separator)}\n style={slotStyles?.separator}\n />\n );\n\n if (isMenuHeading(entry))\n return (\n <div\n key={`heading-${index}`}\n role='presentation'\n className={cx(styles.menuHeading, classNames?.heading)}\n style={slotStyles?.heading}\n >\n {entry.heading}\n </div>\n );\n\n const itemProps = {\n ref: (el: HTMLElement | null) => {\n itemRefs.current[index] = el;\n },\n role: 'menuitem',\n 'aria-keyshortcuts': ariaKeyshortcuts(entry.shortcut),\n // One tab stop for the whole menu: the arrow keys move between items.\n tabIndex: index === activeIndex ? 0 : -1,\n className: cx(styles.menuItem, entry.danger && styles.menuItemDanger, classNames?.item),\n style: slotStyles?.item,\n onClick: () => handleAction(index),\n onMouseEnter: () => setActiveIndex(index),\n };\n const itemContent = (\n <>\n {renderItemIcon(entry.icon, hasIcons, {\n className: cx(styles.menuItemIcon, classNames?.itemIcon),\n style: slotStyles?.itemIcon,\n })}\n <span className={cx(styles.menuItemLabel, classNames?.itemLabel)} style={slotStyles?.itemLabel}>\n {entry.label}\n </span>\n {entry.shortcut != null && (\n <span\n aria-hidden\n className={cx(styles.menuItemShortcut, classNames?.itemShortcut)}\n style={slotStyles?.itemShortcut}\n >\n {formatHotkey(entry.shortcut)}\n </span>\n )}\n </>\n );\n\n // An <a> cannot be disabled, so a disabled link is a disabled button.\n return entry.href && !entry.disabled ? (\n <a\n key={entry.id}\n href={entry.href}\n {...itemProps}\n onClick={(event) => {\n handleAction(index);\n followLink(event);\n }}\n // A link takes Enter but not Space, which every other entry answers to.\n onKeyDown={(event) => {\n if (event.key !== ' ' || !isSelfActivation(event)) return;\n event.preventDefault();\n event.currentTarget.click();\n }}\n >\n {itemContent}\n </a>\n ) : (\n <button key={entry.id} type='button' disabled={entry.disabled} {...itemProps}>\n {itemContent}\n </button>\n );\n })}\n </div>\n );\n\n return (\n <Popover\n {...rest}\n isOpen={isOpen}\n onOpenChange={(next, { fromKeyboard }) => setOpen(next, fromKeyboard)}\n placement={placement}\n align={align}\n presentation={presentation}\n content={content}\n // The list pads its own rows, so a hover highlight reaches the panel edge,\n // and it sizes itself. Focus is the menu's own business, see above.\n focusOnOpen={false}\n constrainWidth={false}\n classNames={{ panel: styles.menuPanel }}\n className={cx(className, classNames?.root)}\n style={{ ...style, ...slotStyles?.root }}\n >\n <span\n ref={triggerRef}\n className={cx(styles.menuTrigger, classNames?.trigger)}\n style={slotStyles?.trigger}\n onKeyDown={handleTriggerKeyDown}\n >\n {triggerWithMenuSemantics}\n </span>\n </Popover>\n );\n}\n\nexport default Menu;\n"],"mappings":"8wBAcA,IAAM,GAAqB,IAG3B,SAAS,EAAY,EAAoB,EAAc,EAAsB,CAC3E,IAAK,IAAI,EAAI,EAAG,GAAK,EAAM,OAAQ,IAAK,CAGtC,IAAM,GAAS,EAAO,EAAO,EAAI,EAAM,OAAS,GAAK,EAAM,OACrD,EAAQ,EAAM,GACpB,GAAI,EAAa,CAAK,GAAK,CAAC,EAAM,SAAU,OAAO,CACrD,CACA,MAAO,EACT,CAEA,SAAS,EAAa,EAA4B,CAChD,OAAO,EAAM,UAAW,GAAU,EAAa,CAAK,GAAK,CAAC,EAAM,QAAQ,CAC1E,CAEA,SAAS,EAAY,EAA4B,CAC/C,IAAK,IAAI,EAAI,EAAM,OAAS,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CACE,CAAA,EAGP,OACE,EAAC,GAAD,CACE,GAAI,GACI,SACR,cAAe,EAAM,CAAE,kBAAmB,EAAQ,EAAM,CAAY,EACzD,YACJ,QACO,eACL,WAGT,YAAa,GACb,eAAgB,GAChB,WAAY,CAAE,MAAO,EAAO,SAAU,EACtC,UAAW,EAAG,EAAW,GAAY,IAAI,EACzC,MAAO,CAAE,GAAG,EAAO,GAAG,GAAY,IAAK,EAEvC,SAAA,EAAC,OAAD,CACE,IAAK,EACL,UAAW,EAAG,EAAO,YAAa,GAAY,OAAO,EACrD,MAAO,GAAY,QACnB,UAAW,GAEV,SAAA,EACG,CAAA,CACC,CAAA,CAEb"}
@@ -1 +1 @@
1
- {"version":3,"file":"menu.types.mjs","names":[],"sources":["../../../../package/common/menu/menu.types.ts"],"sourcesContent":["import type { CSSProperties, ReactNode } from 'react';\nimport type { SlotClassNames, SlotStyles, HtmlProps } from '../types/slots.types';\nimport type { IconContent } from '../types/icon.types';\nimport type { PopoverAlign, PopoverPlacement } from '../popover/popover.types';\nimport type { Presentation } from '../configProvider/presentation.types';\n\n/** One thing the menu can do. */\nexport interface MenuAction {\n /** Stable id, also what `onAction` reports. */\n id: string;\n label: ReactNode;\n icon?: IconContent;\n /**\n * A keyboard shortcut for this action, in `useHotkeys` spelling: `'mod+k'`,\n * `'shift+f2'`, `'delete'`. Shown on the trailing edge written for the\n * platform: `⌘K` on an Apple one, `Ctrl+K` elsewhere.\n *\n * The menu draws it and nothing more. Binding is yours, because only the app\n * knows what else is listening and whether the shortcut should work at all\n * times or only while the menu is open. `menuHotkeys` turns these entries\n * into a `useHotkeys` map, so the one spelling covers both ends.\n */\n shortcut?: string;\n /** Extra search terms for `CommandPalette`, which also matches a string `label`. `Menu` ignores them. */\n keywords?: string[];\n disabled?: boolean;\n /** Renders in the destructive colour. For deleting, discarding, revoking. */\n danger?: boolean;\n /**\n * Followed after `onClick` and `onAction`. In `Menu` a real `<a>`, so Ctrl/⌘-click opens a new tab.\n * Loads the whole page: with a client-side router, navigate in `onClick` instead.\n */\n href?: string;\n onClick?: () => void;\n}\n\n/** A line between groups of actions. */\nexport interface MenuSeparator {\n separator: true;\n}\n\n/** A label over the actions that follow it. */\nexport interface MenuHeading {\n heading: ReactNode;\n}\n\nexport type MenuEntry = MenuAction | MenuSeparator | MenuHeading;\n\nexport function isMenuSeparator(entry: MenuEntry): entry is MenuSeparator {\n return 'separator' in entry;\n}\n\nexport function isMenuHeading(entry: MenuEntry): entry is MenuHeading {\n return 'heading' in entry;\n}\n\nexport function isMenuAction(entry: MenuEntry): entry is MenuAction {\n return !isMenuSeparator(entry) && !isMenuHeading(entry);\n}\n\nexport type MenuSlots =\n | 'root'\n | 'trigger'\n | 'menu'\n | 'item'\n | 'itemIcon'\n | 'itemLabel'\n | 'itemShortcut'\n | 'separator'\n | 'heading';\n\nexport interface MenuProps extends Omit<HtmlProps, 'onSelect'> {\n /** What the menu offers, in the order it is read. */\n items: MenuEntry[];\n /** The element that opens the menu. */\n children?: ReactNode;\n /** Called with the id of the action that was picked, after its own `onClick`. */\n onAction?: (id: string) => void;\n /** Controlled open state. Leave it out to let the menu manage its own. */\n isOpen?: boolean;\n onOpenChange?: (isOpen: boolean) => void;\n /** Which side of the trigger the menu opens on (default `Bottom`). */\n placement?: PopoverPlacement;\n /** Which edge it lines up with on the cross axis (default `Start`). */\n align?: PopoverAlign;\n /** Anchored to the trigger, pinned to the bottom of the screen, or the latter only on touch. */\n presentation?: Presentation;\n className?: string;\n style?: CSSProperties;\n classNames?: SlotClassNames<MenuSlots>;\n styles?: SlotStyles<MenuSlots>;\n}\n"],"mappings":"aAgDA,SAAgB,EAAgB,EAA0C,CACxE,MAAO,cAAe,CACxB,CAEA,SAAgB,EAAc,EAAwC,CACpE,MAAO,YAAa,CACtB,CAEA,SAAgB,EAAa,EAAuC,CAClE,MAAO,CAAC,EAAgB,CAAK,GAAK,CAAC,EAAc,CAAK,CACxD"}
1
+ {"version":3,"file":"menu.types.mjs","names":[],"sources":["../../../../package/common/menu/menu.types.ts"],"sourcesContent":["import type { CSSProperties, ReactNode } from 'react';\nimport type { SlotClassNames, SlotStyles, HtmlProps } from '../types/slots.types';\nimport type { IconContent } from '../types/icon.types';\nimport type { PopoverAlign, PopoverPlacement } from '../popover/popover.types';\nimport type { Presentation } from '../configProvider/presentation.types';\n\n/** One thing the menu can do. */\nexport interface MenuAction {\n /** Stable id, also what `onAction` reports. */\n id: string;\n label: ReactNode;\n icon?: IconContent;\n /**\n * A keyboard shortcut for this action, in `useHotkeys` spelling: `'mod+k'`,\n * `'shift+f2'`, `'delete'`. Shown on the trailing edge written for the\n * platform: `⌘K` on an Apple one, `Ctrl+K` elsewhere.\n *\n * The menu draws it and nothing more. Binding is yours, because only the app\n * knows what else is listening and whether the shortcut should work at all\n * times or only while the menu is open. `menuHotkeys` turns these entries\n * into a `useHotkeys` map, so the one spelling covers both ends.\n */\n shortcut?: string;\n /** Extra search terms for `CommandPalette`, which also matches a string `label`. `Menu` ignores them. */\n keywords?: string[];\n disabled?: boolean;\n /** Renders in the destructive colour. For deleting, discarding, revoking. */\n danger?: boolean;\n /**\n * Followed after `onClick` and `onAction`, through `ConfigProvider`'s `navigate` when it is set.\n * In `Menu` a real `<a>`, so Ctrl/⌘-click opens a new tab.\n */\n href?: string;\n onClick?: () => void;\n}\n\n/** A line between groups of actions. */\nexport interface MenuSeparator {\n separator: true;\n}\n\n/** A label over the actions that follow it. */\nexport interface MenuHeading {\n heading: ReactNode;\n}\n\nexport type MenuEntry = MenuAction | MenuSeparator | MenuHeading;\n\nexport function isMenuSeparator(entry: MenuEntry): entry is MenuSeparator {\n return 'separator' in entry;\n}\n\nexport function isMenuHeading(entry: MenuEntry): entry is MenuHeading {\n return 'heading' in entry;\n}\n\nexport function isMenuAction(entry: MenuEntry): entry is MenuAction {\n return !isMenuSeparator(entry) && !isMenuHeading(entry);\n}\n\nexport type MenuSlots =\n | 'root'\n | 'trigger'\n | 'menu'\n | 'item'\n | 'itemIcon'\n | 'itemLabel'\n | 'itemShortcut'\n | 'separator'\n | 'heading';\n\nexport interface MenuProps extends Omit<HtmlProps, 'onSelect'> {\n /** What the menu offers, in the order it is read. */\n items: MenuEntry[];\n /** The element that opens the menu. */\n children?: ReactNode;\n /** Called with the id of the action that was picked, after its own `onClick`. */\n onAction?: (id: string) => void;\n /** Controlled open state. Leave it out to let the menu manage its own. */\n isOpen?: boolean;\n onOpenChange?: (isOpen: boolean) => void;\n /** Which side of the trigger the menu opens on (default `Bottom`). */\n placement?: PopoverPlacement;\n /** Which edge it lines up with on the cross axis (default `Start`). */\n align?: PopoverAlign;\n /** Anchored to the trigger, pinned to the bottom of the screen, or the latter only on touch. */\n presentation?: Presentation;\n className?: string;\n style?: CSSProperties;\n classNames?: SlotClassNames<MenuSlots>;\n styles?: SlotStyles<MenuSlots>;\n}\n"],"mappings":"aAgDA,SAAgB,EAAgB,EAA0C,CACxE,MAAO,cAAe,CACxB,CAEA,SAAgB,EAAc,EAAwC,CACpE,MAAO,YAAa,CACtB,CAEA,SAAgB,EAAa,EAAuC,CAClE,MAAO,CAAC,EAAgB,CAAK,GAAK,CAAC,EAAc,CAAK,CACxD"}
@@ -1,2 +1,2 @@
1
- "use client";import{renderIcon as e}from"../utils/renderIcon.mjs";import{isMenuAction as t}from"./menu.types.mjs";import{jsx as n}from"react/jsx-runtime";function r(e){return e.some(e=>t(e)&&e.icon!=null)}function i(t,r,i){return t==null?r?n(`span`,{"aria-hidden":!0,...i}):null:e(t,i)}function a(e,t){e.onClick?.(),t?.(e.id),e.href&&o(e.href)}function o(e){let t;try{t=new URL(e,document.baseURI)}catch{return}t.protocol!==`javascript:`&&window.location.assign(t)}export{r as hasAnyIcon,i as renderItemIcon,a as runMenuAction};
1
+ "use client";import{renderIcon as e}from"../utils/renderIcon.mjs";import{followHref as t}from"../utils/navigation.mjs";import{isMenuAction as n}from"./menu.types.mjs";import{jsx as r}from"react/jsx-runtime";function i(e){return e.some(e=>n(e)&&e.icon!=null)}function a(t,n,i){return t==null?n?r(`span`,{"aria-hidden":!0,...i}):null:e(t,i)}function o(e,n,r=t){e.onClick?.(),n?.(e.id),e.href&&r(e.href)}export{i as hasAnyIcon,a as renderItemIcon,o as runMenuAction};
2
2
  //# sourceMappingURL=menuItem.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"menuItem.mjs","names":[],"sources":["../../../../package/common/menu/menuItem.tsx"],"sourcesContent":["import type { CSSProperties, ReactNode } from 'react';\n\nimport { renderIcon } from '../utils/renderIcon';\nimport { isMenuAction, type MenuAction, type MenuEntry } from './menu.types';\n\nexport function hasAnyIcon(items: MenuEntry[]): boolean {\n return items.some((entry) => isMenuAction(entry) && entry.icon != null);\n}\n\n/** The action's icon, or an empty cell as wide when another action has one, so the labels line up. */\nexport function renderItemIcon(\n icon: MenuAction['icon'],\n reserveCell: boolean,\n props: { className: string; style?: CSSProperties },\n): ReactNode {\n if (icon != null) return renderIcon(icon, props);\n return reserveCell ? <span aria-hidden {...props} /> : null;\n}\n\n/** Runs an action the way clicking it does: its own `onClick`, then `onAction`, then its `href`. */\nexport function runMenuAction(action: MenuAction, onAction?: (id: string) => void): void {\n action.onClick?.();\n onAction?.(action.id);\n if (action.href) followHref(action.href);\n}\n\nfunction followHref(href: string) {\n let url: URL;\n try {\n url = new URL(href, document.baseURI);\n } catch {\n return;\n }\n // React refuses a javascript: URL on Menu's <a>, so the same entry must not run one here. Parsed,\n // not matched, because the parser strips the spaces and control characters that can hide one.\n if (url.protocol === 'javascript:') return;\n window.location.assign(url);\n}\n"],"mappings":"0JAKA,SAAgB,EAAW,EAA6B,CACtD,OAAO,EAAM,KAAM,GAAU,EAAa,CAAK,GAAK,EAAM,MAAQ,IAAI,CACxE,CAGA,SAAgB,EACd,EACA,EACA,EACW,CAEX,OADI,GAAQ,KACL,EAAc,EAAC,OAAD,CAAM,cAAA,GAAY,GAAI,CAAQ,CAAA,EAAI,KAD9B,EAAW,EAAM,CAAK,CAEjD,CAGA,SAAgB,EAAc,EAAoB,EAAuC,CACvF,EAAO,UAAU,EACjB,IAAW,EAAO,EAAE,EAChB,EAAO,MAAM,EAAW,EAAO,IAAI,CACzC,CAEA,SAAS,EAAW,EAAc,CAChC,IAAI,EACJ,GAAI,CACF,EAAM,IAAI,IAAI,EAAM,SAAS,OAAO,CACtC,MAAQ,CACN,MACF,CAGI,EAAI,WAAa,eACrB,OAAO,SAAS,OAAO,CAAG,CAC5B"}
1
+ {"version":3,"file":"menuItem.mjs","names":[],"sources":["../../../../package/common/menu/menuItem.tsx"],"sourcesContent":["import type { CSSProperties, ReactNode } from 'react';\n\nimport { followHref } from '../utils/navigation';\nimport { renderIcon } from '../utils/renderIcon';\nimport { isMenuAction, type MenuAction, type MenuEntry } from './menu.types';\n\nexport function hasAnyIcon(items: MenuEntry[]): boolean {\n return items.some((entry) => isMenuAction(entry) && entry.icon != null);\n}\n\n/** The action's icon, or an empty cell as wide when another action has one, so the labels line up. */\nexport function renderItemIcon(\n icon: MenuAction['icon'],\n reserveCell: boolean,\n props: { className: string; style?: CSSProperties },\n): ReactNode {\n if (icon != null) return renderIcon(icon, props);\n return reserveCell ? <span aria-hidden {...props} /> : null;\n}\n\n/**\n * Runs an action the way clicking it does: its own `onClick`, then `onAction`, then its `href`.\n * `follow` is `useFollowHref()` where the caller can reach the router; `menuHotkeys` cannot.\n */\nexport function runMenuAction(\n action: MenuAction,\n onAction?: (id: string) => void,\n follow: (href: string) => void = followHref,\n): void {\n action.onClick?.();\n onAction?.(action.id);\n if (action.href) follow(action.href);\n}\n"],"mappings":"+MAMA,SAAgB,EAAW,EAA6B,CACtD,OAAO,EAAM,KAAM,GAAU,EAAa,CAAK,GAAK,EAAM,MAAQ,IAAI,CACxE,CAGA,SAAgB,EACd,EACA,EACA,EACW,CAEX,OADI,GAAQ,KACL,EAAc,EAAC,OAAD,CAAM,cAAA,GAAY,GAAI,CAAQ,CAAA,EAAI,KAD9B,EAAW,EAAM,CAAK,CAEjD,CAMA,SAAgB,EACd,EACA,EACA,EAAiC,EAC3B,CACN,EAAO,UAAU,EACjB,IAAW,EAAO,EAAE,EAChB,EAAO,MAAM,EAAO,EAAO,IAAI,CACrC"}
@@ -1,2 +1,2 @@
1
- "use client";import{useComponentDefaults as e}from"../configProvider/useComponentDefaults.mjs";import{useLabels as t}from"../configProvider/useLabels.mjs";import{PopoverAlign as n,PopoverPlacement as r,PopoverTrigger as ee}from"../popover/popover.types.mjs";import te from"../popover/popover.mjs";import ne from"../chip/chip.mjs";import re from"../tooltip/tooltip.mjs";import{edgeIndex as ie,nextIndex as ae,scrollOptionIntoView as oe}from"../utils/listNavigation.mjs";import se from"../searchInput/searchInput.mjs";import i from"./multiSelect.module.mjs";import{useEffect as a,useId as ce,useRef as o,useState as s}from"react";import c from"classnames";import{FontAwesomeIcon as l}from"@fortawesome/react-fontawesome";import{faCheck as le,faChevronDown as ue,faXmark as de}from"@fortawesome/free-solid-svg-icons";import{jsx as u,jsxs as d}from"react/jsx-runtime";var fe=[],pe={clearSelection:`Clear selection`,create:e=>`Add "${e}"`,searchPlaceholder:`Search…`,empty:`No matches`};function f(f){let{items:p,value:m,defaultValue:me=[],onChange:he=()=>{},label:h=``,alwaysFloatLabel:ge=!1,placeholder:g=``,searchable:_e=!1,allowCustomValues:_=!1,maxSelected:v,clearable:ve=!0,disabled:y=!1,readOnly:b=!1,presentation:ye,formValidator:x=null,errorMessage:S=``,isValid:be=!0,className:xe,style:Se,classNames:C,styles:w,onMouseEnter:Ce,onMouseLeave:we,onFocus:Te,onBlur:Ee,labels:De,...Oe}=e(`MultiSelect`,f),T=t(`MultiSelect`,De,pe),E=o(null),D=o(null),O=o(null),k=o(null),A=ce(),[ke,Ae]=s(me),[j,je]=s(!1),[M,N]=s(``),[P,F]=s(0),[I,L]=s(!1),[Me,Ne]=s(!1),[Pe,Fe]=s(),R=o(x),[,Ie]=s(0);a(()=>{R.current=x;let e=R.current;if(!e)return;e.label=h,e.validate();let t=()=>Ie(e=>e+1);return e.registerOnUpdateListener(t),()=>{e.removeOnUpdateListener(t)}},[x,h]);let z=m!==void 0&&!x,B=x?x.value:z?m:ke,V=Array.isArray(B)?B:fe,H=x?x.touched&&x.hasError():!be||!!S,Le=x?x.getCurrentErrorMessage():S||``,U=!y&&!b,W=v!==void 0&&V.length>=v,G=ge||j||I||V.length>0,K=_e||_,q=M.trim(),J=K?q.toLowerCase():``,Y=J?p.filter(e=>e.label.toLowerCase().includes(J)):p,X=_&&q.length>0&&!W&&!p.some(e=>e.label.toLowerCase()===J||String(e.key).toLowerCase()===J)&&!V.some(e=>String(e).toLowerCase()===J),Z=X?[...Y,{key:q,label:T.create(q)}]:Y,Re=V.map(e=>p.find(t=>t.key===e)??(_?{key:e,label:String(e)}:void 0)).filter(e=>e!==void 0);function Q(e){x?x.set(e):z||Ae(e),he(e)}function $(e){U&&!e.disabled&&(V.includes(e.key)?Q(V.filter(t=>t!==e.key)):W||Q([...V,e.key]),X&&e.key===q&&N(``))}function ze(){E.current?.contains(document.activeElement)&&D.current?.focus()}function Be(e){(!e||U)&&(je(e),e?(Fe(D.current?.offsetWidth),F(0)):(N(``),R.current&&(R.current.touched=!0)))}a(()=>{j&&K&&O.current?.querySelector(`input`)?.focus()},[j,K]),a(()=>{j&&oe(k.current,document.getElementById(`${A}-${P}`))},[j,P,A]);let Ve={isDisabled:e=>{let t=Z[e];return!!t.disabled||W&&!V.includes(t.key)}};function He(e){if(U){if(!j){e.key===`ArrowDown`||e.key===`Enter`||e.key===` `?(e.preventDefault(),Be(!0)):e.key===`Backspace`&&V.length>0&&Q(V.slice(0,-1));return}if(e.key===`ArrowDown`||e.key===`ArrowUp`)e.preventDefault(),F(ae(P,e.key===`ArrowDown`?1:-1,Z.length,Ve)??0);else if(e.key===`Home`||e.key===`End`)e.preventDefault(),F(ie(e.key===`Home`?`first`:`last`,Z.length,Ve)??0);else if(e.key===`Enter`){e.preventDefault();let t=Z[P];t&&$(t)}else e.key===`Backspace`&&!M&&V.length>0&&Q(V.slice(0,-1))}}let Ue=d(`div`,{className:c(i.multiSelectPanel,C?.panel),style:w?.panel,children:[K&&u(`div`,{ref:O,className:c(i.multiSelectSearch,C?.search),style:w?.search,children:u(se,{value:M,onChange:e=>{N(e),F(0)},placeholder:T.searchPlaceholder,onKeyDown:He})}),u(`div`,{ref:k,id:A,role:`listbox`,"aria-multiselectable":`true`,"aria-label":h||void 0,className:c(i.multiSelectOptions,C?.options),style:w?.options,children:Z.length===0?u(`div`,{className:c(i.multiSelectEmpty,C?.empty),style:w?.empty,children:T.empty}):Z.map((e,t)=>{let n=V.includes(e.key),r=e.disabled||W&&!n;return d(`div`,{id:`${A}-${t}`,role:`option`,"aria-selected":n,"aria-disabled":r||void 0,className:c(i.multiSelectOption,t===P&&i.multiSelectOptionActive,n&&i.multiSelectOptionSelected,r&&i.multiSelectOptionDisabled,C?.option),style:w?.option,onMouseDown:e=>e.preventDefault(),onMouseEnter:()=>F(t),onClick:()=>$(e),children:[u(`span`,{className:c(i.multiSelectOptionCheck,C?.optionCheck),style:w?.optionCheck,children:n&&u(l,{icon:le})}),u(`span`,{className:c(i.multiSelectOptionLabel,C?.optionLabel),style:w?.optionLabel,children:e.label})]},e.key)})})]});return d(`div`,{...Oe,ref:E,className:c(i.multiSelect,y&&i.multiSelectDisabled,!!h&&i.multiSelectWithLabel,C?.root,xe),style:{...Se,...w?.root},onMouseEnter:e=>{Ne(!0),Ce?.(e)},onMouseLeave:e=>{Ne(!1),we?.(e)},onFocus:e=>{L(!0),Te?.(e)},onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(L(!1),Ee?.(e))},children:[u(te,{isOpen:j,onOpenChange:Be,trigger:ee.Click,placement:r.Bottom,align:n.Start,offset:4,withArrow:!1,focusOnOpen:K,constrainWidth:!1,width:`trigger`,disabled:!U,presentation:ye,content:Ue,styles:{panel:Pe?{minWidth:Pe}:void 0},children:d(`div`,{ref:D,role:`combobox`,tabIndex:y?-1:0,"aria-expanded":j,"aria-haspopup":`listbox`,"aria-controls":A,"aria-activedescendant":j&&Z.length>0?`${A}-${P}`:void 0,"aria-disabled":y||void 0,"aria-readonly":b||void 0,className:c(i.multiSelectControl,C?.control),style:w?.control,onKeyDown:He,children:[g&&Re.length===0&&u(`span`,{className:c(i.multiSelectPlaceholder,(!h||G)&&i.multiSelectPlaceholderShown,!h&&i.multiSelectPlaceholderInstant,C?.placeholder),style:w?.placeholder,children:g}),u(`div`,{className:c(i.multiSelectValues,C?.values),style:w?.values,children:Re.map(e=>u(ne,{text:e.label,showRemoveIcon:U,labels:{remove:`Remove ${e.label}`},onMouseDown:e=>e.preventDefault(),onRemove:()=>{$(e),ze()},className:c(i.multiSelectChip,C?.chip),style:w?.chip},e.key))}),ve&&U&&V.length>0&&u(`button`,{type:`button`,tabIndex:-1,"aria-label":T.clearSelection,className:c(i.multiSelectClearButton,C?.clearButton),style:w?.clearButton,onMouseDown:e=>e.preventDefault(),onClick:e=>{e.stopPropagation(),Q([]),ze()},children:u(l,{icon:de})}),u(l,{icon:ue,className:c(i.multiSelectIcon,j&&i.multiSelectIconOpen,C?.icon),style:w?.icon}),h&&u(`div`,{className:c(i.multiSelectLabel,G&&i.multiSelectLabelFloating,C?.label),style:w?.label,children:h}),u(`fieldset`,{className:c(i.multiSelectFieldset,(I||j)&&i.multiSelectFieldsetFocused,H&&i.multiSelectFieldsetError,C?.fieldset),style:w?.fieldset,children:u(`legend`,{className:c(i.multiSelectFieldsetLegend,G&&i.multiSelectFieldsetLegendActive),children:u(`span`,{children:h})})})]})}),u(re,{variant:`error`,message:Le,isVisible:H&&(I||Me)})]})}export{f as default};
1
+ "use client";import{useComponentDefaults as e}from"../configProvider/useComponentDefaults.mjs";import{useLabels as t}from"../configProvider/useLabels.mjs";import{PopoverAlign as n,PopoverPlacement as r,PopoverTrigger as ee}from"../popover/popover.types.mjs";import te from"../popover/popover.mjs";import ne from"../chip/chip.mjs";import re from"../tooltip/tooltip.mjs";import{edgeIndex as ie,nextIndex as ae,scrollOptionIntoView as oe}from"../utils/listNavigation.mjs";import se from"../searchInput/searchInput.mjs";import i from"./multiSelect.module.mjs";import{useEffect as a,useId as ce,useRef as o,useState as s}from"react";import c from"classnames";import{FontAwesomeIcon as l}from"@fortawesome/react-fontawesome";import{faCheck as le,faChevronDown as ue,faXmark as de}from"@fortawesome/free-solid-svg-icons";import{jsx as u,jsxs as d}from"react/jsx-runtime";var fe=[],pe={clearSelection:`Clear selection`,create:e=>`Add "${e}"`,searchPlaceholder:`Search…`,empty:`No matches`};function f(f){let{items:p,value:m,defaultValue:me=[],onChange:he=()=>{},label:h=``,alwaysFloatLabel:ge=!1,placeholder:g=``,searchable:_e=!1,allowCustomValues:_=!1,maxSelected:v,clearable:ve=!0,disabled:y=!1,readOnly:b=!1,presentation:ye,formValidator:x=null,errorMessage:S=``,isValid:be=!0,className:xe,style:Se,classNames:C,styles:w,onMouseEnter:Ce,onMouseLeave:we,onFocus:Te,onBlur:Ee,labels:De,...Oe}=e(`MultiSelect`,f),T=t(`MultiSelect`,De,pe),E=o(null),D=o(null),O=o(null),k=o(null),A=ce(),[ke,Ae]=s(me),[j,je]=s(!1),[M,N]=s(``),[P,F]=s(0),[I,L]=s(!1),[Me,Ne]=s(!1),[Pe,Fe]=s(),R=o(x),[,Ie]=s(0);a(()=>{R.current=x;let e=R.current;if(!e)return;e.label=h,e.validate();let t=()=>Ie(e=>e+1);return e.registerOnUpdateListener(t),()=>{e.removeOnUpdateListener(t)}},[x,h]);let z=m!==void 0&&!x,B=x?x.value:z?m:ke,V=Array.isArray(B)?B:fe,H=x?x.shouldShowError:!be||!!S,Le=x?x.getCurrentErrorMessage():S||``,U=!y&&!b,W=v!==void 0&&V.length>=v,G=ge||j||I||V.length>0,K=_e||_,q=M.trim(),J=K?q.toLowerCase():``,Y=J?p.filter(e=>e.label.toLowerCase().includes(J)):p,X=_&&q.length>0&&!W&&!p.some(e=>e.label.toLowerCase()===J||String(e.key).toLowerCase()===J)&&!V.some(e=>String(e).toLowerCase()===J),Z=X?[...Y,{key:q,label:T.create(q)}]:Y,Re=V.map(e=>p.find(t=>t.key===e)??(_?{key:e,label:String(e)}:void 0)).filter(e=>e!==void 0);function Q(e){x?x.set(e):z||Ae(e),he(e)}function $(e){U&&!e.disabled&&(V.includes(e.key)?Q(V.filter(t=>t!==e.key)):W||Q([...V,e.key]),X&&e.key===q&&N(``))}function ze(){E.current?.contains(document.activeElement)&&D.current?.focus()}function Be(e){(!e||U)&&(je(e),e?(Fe(D.current?.offsetWidth),F(0)):(N(``),R.current&&(R.current.touched=!0)))}a(()=>{j&&K&&O.current?.querySelector(`input`)?.focus()},[j,K]),a(()=>{j&&oe(k.current,document.getElementById(`${A}-${P}`))},[j,P,A]);let Ve={isDisabled:e=>{let t=Z[e];return!!t.disabled||W&&!V.includes(t.key)}};function He(e){if(U){if(!j){e.key===`ArrowDown`||e.key===`Enter`||e.key===` `?(e.preventDefault(),Be(!0)):e.key===`Backspace`&&V.length>0&&Q(V.slice(0,-1));return}if(e.key===`ArrowDown`||e.key===`ArrowUp`)e.preventDefault(),F(ae(P,e.key===`ArrowDown`?1:-1,Z.length,Ve)??0);else if(e.key===`Home`||e.key===`End`)e.preventDefault(),F(ie(e.key===`Home`?`first`:`last`,Z.length,Ve)??0);else if(e.key===`Enter`){e.preventDefault();let t=Z[P];t&&$(t)}else e.key===`Backspace`&&!M&&V.length>0&&Q(V.slice(0,-1))}}let Ue=d(`div`,{className:c(i.multiSelectPanel,C?.panel),style:w?.panel,children:[K&&u(`div`,{ref:O,className:c(i.multiSelectSearch,C?.search),style:w?.search,children:u(se,{value:M,onChange:e=>{N(e),F(0)},placeholder:T.searchPlaceholder,onKeyDown:He})}),u(`div`,{ref:k,id:A,role:`listbox`,"aria-multiselectable":`true`,"aria-label":h||void 0,className:c(i.multiSelectOptions,C?.options),style:w?.options,children:Z.length===0?u(`div`,{className:c(i.multiSelectEmpty,C?.empty),style:w?.empty,children:T.empty}):Z.map((e,t)=>{let n=V.includes(e.key),r=e.disabled||W&&!n;return d(`div`,{id:`${A}-${t}`,role:`option`,"aria-selected":n,"aria-disabled":r||void 0,className:c(i.multiSelectOption,t===P&&i.multiSelectOptionActive,n&&i.multiSelectOptionSelected,r&&i.multiSelectOptionDisabled,C?.option),style:w?.option,onMouseDown:e=>e.preventDefault(),onMouseEnter:()=>F(t),onClick:()=>$(e),children:[u(`span`,{className:c(i.multiSelectOptionCheck,C?.optionCheck),style:w?.optionCheck,children:n&&u(l,{icon:le})}),u(`span`,{className:c(i.multiSelectOptionLabel,C?.optionLabel),style:w?.optionLabel,children:e.label})]},e.key)})})]});return d(`div`,{...Oe,ref:E,className:c(i.multiSelect,y&&i.multiSelectDisabled,!!h&&i.multiSelectWithLabel,C?.root,xe),style:{...Se,...w?.root},onMouseEnter:e=>{Ne(!0),Ce?.(e)},onMouseLeave:e=>{Ne(!1),we?.(e)},onFocus:e=>{L(!0),Te?.(e)},onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(L(!1),Ee?.(e))},children:[u(te,{isOpen:j,onOpenChange:Be,trigger:ee.Click,placement:r.Bottom,align:n.Start,offset:4,withArrow:!1,focusOnOpen:K,constrainWidth:!1,width:`trigger`,disabled:!U,presentation:ye,content:Ue,styles:{panel:Pe?{minWidth:Pe}:void 0},children:d(`div`,{ref:D,role:`combobox`,tabIndex:y?-1:0,"aria-expanded":j,"aria-haspopup":`listbox`,"aria-controls":A,"aria-activedescendant":j&&Z.length>0?`${A}-${P}`:void 0,"aria-disabled":y||void 0,"aria-readonly":b||void 0,className:c(i.multiSelectControl,C?.control),style:w?.control,onKeyDown:He,children:[g&&Re.length===0&&u(`span`,{className:c(i.multiSelectPlaceholder,(!h||G)&&i.multiSelectPlaceholderShown,!h&&i.multiSelectPlaceholderInstant,C?.placeholder),style:w?.placeholder,children:g}),u(`div`,{className:c(i.multiSelectValues,C?.values),style:w?.values,children:Re.map(e=>u(ne,{text:e.label,showRemoveIcon:U,labels:{remove:`Remove ${e.label}`},onMouseDown:e=>e.preventDefault(),onRemove:()=>{$(e),ze()},className:c(i.multiSelectChip,C?.chip),style:w?.chip},e.key))}),ve&&U&&V.length>0&&u(`button`,{type:`button`,tabIndex:-1,"aria-label":T.clearSelection,className:c(i.multiSelectClearButton,C?.clearButton),style:w?.clearButton,onMouseDown:e=>e.preventDefault(),onClick:e=>{e.stopPropagation(),Q([]),ze()},children:u(l,{icon:de})}),u(l,{icon:ue,className:c(i.multiSelectIcon,j&&i.multiSelectIconOpen,C?.icon),style:w?.icon}),h&&u(`div`,{className:c(i.multiSelectLabel,G&&i.multiSelectLabelFloating,C?.label),style:w?.label,children:h}),u(`fieldset`,{className:c(i.multiSelectFieldset,(I||j)&&i.multiSelectFieldsetFocused,H&&i.multiSelectFieldsetError,C?.fieldset),style:w?.fieldset,children:u(`legend`,{className:c(i.multiSelectFieldsetLegend,G&&i.multiSelectFieldsetLegendActive),children:u(`span`,{children:h})})})]})}),u(re,{variant:`error`,message:Le,isVisible:H&&(I||Me)})]})}export{f as default};
2
2
  //# sourceMappingURL=multiSelect.mjs.map