@ahrowe/ui 0.48.0 → 0.50.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -0
- package/README.md +3 -0
- package/dist/cjs-types/common/actionIcon/actionIcon.types.d.ts +1 -1
- package/dist/cjs-types/common/button/button.types.d.ts +6 -1
- package/dist/cjs-types/common/chatComposer/chatComposer.d.ts +4 -0
- package/dist/cjs-types/common/chatComposer/chatComposer.types.d.ts +40 -0
- package/dist/cjs-types/common/chatComposer/index.d.ts +2 -0
- package/dist/cjs-types/common/chatMessage/chatMessage.d.ts +4 -0
- package/dist/cjs-types/common/chatMessage/chatMessage.types.d.ts +60 -0
- package/dist/cjs-types/common/chatMessage/index.d.ts +2 -0
- package/dist/cjs-types/common/chatMessageList/chatMessageList.d.ts +4 -0
- package/dist/cjs-types/common/chatMessageList/chatMessageList.types.d.ts +27 -0
- package/dist/cjs-types/common/chatMessageList/index.d.ts +2 -0
- package/dist/cjs-types/common/configProvider/configProvider.types.d.ts +6 -0
- package/dist/cjs-types/common/hooks/useAutoGrow.d.ts +12 -0
- package/dist/cjs-types/common/hooks/useHotkeys.d.ts +11 -0
- package/dist/cjs-types/common/tabHeader/tabHeader.types.d.ts +5 -3
- package/dist/cjs-types/index.d.ts +6 -0
- package/dist/esm/common/button/button.mjs +1 -1
- package/dist/esm/common/button/button.mjs.map +1 -1
- package/dist/esm/common/button/button.module.mjs +1 -1
- package/dist/esm/common/button/button.module.mjs.map +1 -1
- package/dist/esm/common/button/button.types.mjs.map +1 -1
- package/dist/esm/common/chatComposer/chatComposer.mjs +2 -0
- package/dist/esm/common/chatComposer/chatComposer.mjs.map +1 -0
- package/dist/esm/common/chatComposer/chatComposer.module.mjs +2 -0
- package/dist/esm/common/chatComposer/chatComposer.module.mjs.map +1 -0
- package/dist/esm/common/chatMessage/chatMessage.mjs +2 -0
- package/dist/esm/common/chatMessage/chatMessage.mjs.map +1 -0
- package/dist/esm/common/chatMessage/chatMessage.module.mjs +2 -0
- package/dist/esm/common/chatMessage/chatMessage.module.mjs.map +1 -0
- package/dist/esm/common/chatMessage/chatMessage.types.mjs +2 -0
- package/dist/esm/common/chatMessage/chatMessage.types.mjs.map +1 -0
- package/dist/esm/common/chatMessageList/chatMessageList.mjs +2 -0
- package/dist/esm/common/chatMessageList/chatMessageList.mjs.map +1 -0
- package/dist/esm/common/chatMessageList/chatMessageList.module.mjs +2 -0
- package/dist/esm/common/chatMessageList/chatMessageList.module.mjs.map +1 -0
- package/dist/esm/common/commandPalette/commandPalette.mjs +1 -1
- package/dist/esm/common/commandPalette/commandPalette.mjs.map +1 -1
- package/dist/esm/common/dropdown/dropdown.mjs +1 -1
- package/dist/esm/common/hooks/useAutoGrow.mjs +2 -0
- package/dist/esm/common/hooks/useAutoGrow.mjs.map +1 -0
- package/dist/esm/common/hooks/useHotkeys.mjs +1 -1
- package/dist/esm/common/hooks/useHotkeys.mjs.map +1 -1
- package/dist/esm/common/infiniteBlock/useInfiniteScroll.mjs +1 -1
- package/dist/esm/common/infiniteBlock/useInfiniteScroll.mjs.map +1 -1
- package/dist/esm/common/input/input.mjs +1 -1
- package/dist/esm/common/input/input.mjs.map +1 -1
- package/dist/esm/common/menu/menu.mjs +1 -1
- package/dist/esm/common/menu/menu.mjs.map +1 -1
- package/dist/esm/common/tabHeader/tabHeader.mjs +1 -1
- package/dist/esm/common/tabHeader/tabHeader.mjs.map +1 -1
- package/dist/esm/index.mjs +1 -1
- package/dist/index.cjs +3 -3
- package/dist/index.cjs.map +1 -1
- package/dist/style.css +1 -1
- package/dist/types/common/actionIcon/actionIcon.types.d.ts +1 -1
- package/dist/types/common/button/button.types.d.ts +6 -1
- package/dist/types/common/chatComposer/chatComposer.d.ts +4 -0
- package/dist/types/common/chatComposer/chatComposer.types.d.ts +40 -0
- package/dist/types/common/chatComposer/index.d.ts +2 -0
- package/dist/types/common/chatMessage/chatMessage.d.ts +4 -0
- package/dist/types/common/chatMessage/chatMessage.types.d.ts +60 -0
- package/dist/types/common/chatMessage/index.d.ts +2 -0
- package/dist/types/common/chatMessageList/chatMessageList.d.ts +4 -0
- package/dist/types/common/chatMessageList/chatMessageList.types.d.ts +27 -0
- package/dist/types/common/chatMessageList/index.d.ts +2 -0
- package/dist/types/common/configProvider/configProvider.types.d.ts +6 -0
- package/dist/types/common/hooks/useAutoGrow.d.ts +12 -0
- package/dist/types/common/hooks/useHotkeys.d.ts +11 -0
- package/dist/types/common/tabHeader/tabHeader.types.d.ts +5 -3
- package/dist/types/index.d.ts +6 -0
- package/docs/ActionIcon.md +2 -2
- package/docs/Button.md +18 -2
- package/docs/CLAUDE.md +6 -3
- package/docs/ChatComposer.md +100 -0
- package/docs/ChatMessage.md +88 -0
- package/docs/ChatMessageList.md +113 -0
- package/docs/ConfigProvider.md +1 -0
- package/docs/Hooks.md +23 -4
- package/docs/Menu.md +1 -1
- package/docs/TabHeader.md +19 -8
- package/package.json +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chatMessageList.module.mjs","names":[],"sources":["../../../../package/common/chatMessageList/chatMessageList.module.pcss"],"sourcesContent":[".chatMessageList {\n position: relative;\n display: flex;\n flex-direction: column;\n min-height: 0;\n\n &-viewport {\n display: flex;\n flex: 1 1 auto;\n flex-direction: column;\n min-height: 0;\n overflow-y: auto;\n\n /* The component anchors the scroll position itself; the browser's own would correct it twice. */\n overflow-anchor: none;\n overscroll-behavior: contain;\n\n &:focus-visible {\n outline: 2px solid var(--focus-border-color, var(--primary-color));\n outline-offset: -2px;\n }\n }\n\n /* An auto margin rather than justify-content: flex-end, which would put an overflow above the\n top where it can never be scrolled to. Keeps a short conversation at the bottom, by the composer. */\n &-content {\n display: flex;\n flex-direction: column;\n margin-top: auto;\n padding: 0.75em;\n }\n\n /* A fixed height, so the loader showing up inside it moves nothing. */\n &-loader {\n display: flex;\n flex: none;\n align-items: center;\n justify-content: center;\n height: 2.5em;\n }\n}\n\n/* Two classes: it is an ActionIcon, whose own one-class rules it would otherwise tie with. */\n.chatMessageList .chatMessageList-scrollButton {\n position: absolute;\n inset-inline-end: 0.75em;\n bottom: 0.75em;\n width: 2.5em;\n height: 2.5em;\n border-radius: 50%;\n box-shadow: var(--card-shadow);\n}\n\n/* A Plain button over the messages needs a surface of its own. Once something new has arrived\n below it is Filled, and keeps Button's fill. */\n.chatMessageList .chatMessageList-scrollButton-surface {\n background: var(--background-card-elevated, var(--background));\n}\n"],"mappings":""}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use client";import{useComponentDefaults as e}from"../configProvider/useComponentDefaults.mjs";import{useLabels as t}from"../configProvider/useLabels.mjs";import{renderIcon as n}from"../utils/renderIcon.mjs";import r from"../
|
|
1
|
+
"use client";import{useComponentDefaults as e}from"../configProvider/useComponentDefaults.mjs";import{useLabels as t}from"../configProvider/useLabels.mjs";import{renderIcon as n}from"../utils/renderIcon.mjs";import{ariaKeyshortcuts as r,formatHotkey as i}from"../hooks/useHotkeys.mjs";import a from"../modal/modal.mjs";import{edgeIndex as o,nextIndex as ee,scrollOptionIntoView as s}from"../utils/listNavigation.mjs";import{hasAnyIcon as c,renderItemIcon as te,runMenuAction as l}from"../menu/menuItem.mjs";import{filterCommands as ne,groupCommands as u}from"./filterCommands.mjs";import d from"./commandPalette.module.mjs";import{useEffect as f,useId as p,useRef as m,useState as h}from"react";import g from"classnames";import{faMagnifyingGlass as re}from"@fortawesome/free-solid-svg-icons";import{jsx as _,jsxs as v}from"react/jsx-runtime";var y={label:`Search commands`,placeholder:`Type a command or search…`,empty:`No results`,loading:`Searching…`,results:e=>e===1?`1 result`:`${e} results`};function b(b){let{items:x,isOpen:S,onClose:C,onAction:w,onQueryChange:T,filter:E=!0,isLoading:D=!1,presentation:O,labels:ie,className:ae,style:oe,classNames:k,styles:A,...j}=e(`CommandPalette`,b),M=t(`CommandPalette`,ie,y),N=p(),P=m(null),[F,I]=h(``),[L,R]=h(null),[z,B]=h(S);S!==z&&(B(S),S&&(I(``),R(null)));let V=m(T);f(()=>{V.current=T}),f(()=>{S&&V.current?.(``)},[S]);let H=E?ne(u(x),F):u(x),U=c(x),W=H.flatMap(e=>e.actions),G=e=>!!W[e]?.disabled,K=W.findIndex(e=>e.id===L&&!e.disabled),q=K>=0?K:o(`first`,W.length,{isDisabled:G}),J=e=>`${N}-${encodeURIComponent(e.id)}`,Y=q===null?void 0:J(W[q]);f(()=>{Y&&s(P.current,document.getElementById(Y))},[Y]);function X(e){e&&!e.disabled&&(l(e,w),C())}function se(e){if(!e.nativeEvent.isComposing){if(e.key===`ArrowDown`||e.key===`ArrowUp`){let t=ee(q,e.key===`ArrowDown`?1:-1,W.length,{isDisabled:G});R(t===null?null:W[t].id)}else if(e.key===`Enter`)X(q===null?void 0:W[q]);else return;e.preventDefault()}}let Z=F.trim()!==``,Q=D?M.loading:M.empty,$=-1;return v(a,{...j,"aria-label":M.label,isOpen:S,onClose:C,hideHeader:!0,presentation:O,className:g(d.commandPalette,ae,k?.root),style:{...oe,...A?.root},children:[v(`div`,{className:g(d.commandPaletteSearch,k?.search),style:A?.search,children:[n(re,{className:d.commandPaletteSearchIcon}),_(`input`,{type:`text`,role:`combobox`,"aria-label":M.label,"aria-expanded":`true`,"aria-controls":N,"aria-autocomplete":`list`,"aria-activedescendant":Y,autoComplete:`off`,spellCheck:!1,placeholder:M.placeholder,value:F,onChange:e=>{I(e.target.value),R(null),T?.(e.target.value)},onKeyDown:se,className:g(d.commandPaletteInput,k?.input),style:A?.input})]}),_(`div`,{ref:P,id:N,role:`listbox`,"aria-label":M.label,className:g(d.commandPaletteList,k?.list),style:A?.list,children:H.map((e,t)=>{let n=`${N}-heading-${t}`;return v(`div`,{role:e.heading===void 0?`presentation`:`group`,"aria-labelledby":e.heading===void 0?void 0:n,children:[e.separated&&t>0&&_(`div`,{"aria-hidden":!0,className:g(d.commandPaletteSeparator,k?.separator),style:A?.separator}),e.heading!==void 0&&_(`div`,{id:n,role:`presentation`,className:g(d.commandPaletteHeading,k?.heading),style:A?.heading,children:e.heading}),e.actions.map(e=>{$+=1;let t=$;return v(`div`,{id:J(e),role:`option`,"aria-selected":t===q,"aria-disabled":e.disabled||void 0,"aria-keyshortcuts":r(e.shortcut),className:g(d.commandPaletteItem,t===q&&d.commandPaletteItemActive,e.danger&&d.commandPaletteItemDanger,e.disabled&&d.commandPaletteItemDisabled,k?.item),style:A?.item,onMouseDown:e=>e.preventDefault(),onMouseMove:()=>!e.disabled&&R(e.id),onClick:()=>X(e),children:[te(e.icon,U,{className:g(d.commandPaletteItemIcon,k?.itemIcon),style:A?.itemIcon}),_(`span`,{className:g(d.commandPaletteItemLabel,k?.itemLabel),style:A?.itemLabel,children:e.label}),e.shortcut!=null&&_(`span`,{"aria-hidden":!0,className:g(d.commandPaletteItemShortcut,k?.itemShortcut),style:A?.itemShortcut,children:i(e.shortcut)})]},e.id)})]},t)})}),Z&&W.length===0&&_(`div`,{className:g(d.commandPaletteEmpty,k?.empty),style:A?.empty,children:Q}),_(`span`,{className:d.commandPaletteStatus,role:`status`,"aria-live":`polite`,children:Z?W.length>0?M.results(W.length):Q:``})]})}export{b as default};
|
|
2
2
|
//# sourceMappingURL=commandPalette.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"commandPalette.mjs","names":[],"sources":["../../../../package/common/commandPalette/commandPalette.tsx"],"sourcesContent":["import { useEffect, useId, useRef, useState, type KeyboardEvent, type ReactElement } from 'react';\nimport cx from 'classnames';\nimport { faMagnifyingGlass } from '@fortawesome/free-solid-svg-icons';\n\nimport Modal from '../modal';\nimport { useComponentDefaults, useLabels } from '../configProvider';\nimport { formatHotkey } from '../hooks/useHotkeys';\nimport { edgeIndex, nextIndex, scrollOptionIntoView } from '../utils/listNavigation';\nimport { renderIcon } from '../utils/renderIcon';\nimport type { MenuAction } from '../menu/menu.types';\nimport { hasAnyIcon, renderItemIcon, runMenuAction } from '../menu/menuItem';\nimport { filterCommands, groupCommands } from './filterCommands';\nimport type { CommandPaletteLabels, CommandPaletteProps } from './commandPalette.types';\nimport styles from './commandPalette.module.pcss';\n\nconst DEFAULT_LABELS: Required<CommandPaletteLabels> = {\n label: 'Search commands',\n placeholder: 'Type a command or search…',\n empty: 'No results',\n loading: 'Searching…',\n results: (count) => (count === 1 ? '1 result' : `${count} results`),\n};\n\nfunction CommandPalette(props: CommandPaletteProps): ReactElement {\n const {\n items,\n isOpen,\n onClose,\n onAction,\n onQueryChange,\n filter = true,\n isLoading = false,\n presentation,\n labels,\n className,\n style,\n classNames,\n styles: slotStyles,\n ...rest\n } = useComponentDefaults('CommandPalette', props);\n const text = useLabels('CommandPalette', labels, DEFAULT_LABELS);\n const listId = useId();\n const listRef = useRef<HTMLDivElement>(null);\n\n const [query, setQuery] = useState('');\n // An id rather than an index, so the highlight stays on the same command while server results\n // are replaced around it. Typing clears it instead, so Enter runs the best match.\n const [activeId, setActiveId] = useState<string | null>(null);\n const [wasOpen, setWasOpen] = useState(isOpen);\n if (isOpen !== wasOpen) {\n setWasOpen(isOpen);\n if (isOpen) {\n setQuery('');\n setActiveId(null);\n }\n }\n\n // Read through a ref so an inline handler does not re-fire the effect on every parent render.\n const onQueryChangeRef = useRef(onQueryChange);\n useEffect(() => {\n onQueryChangeRef.current = onQueryChange;\n });\n useEffect(() => {\n if (isOpen) onQueryChangeRef.current?.('');\n }, [isOpen]);\n\n const groups = filter ? filterCommands(groupCommands(items), query) : groupCommands(items);\n // From all items, not the matches, so the labels do not jump sideways while the user types.\n const hasIcons = hasAnyIcon(items);\n const actions = groups.flatMap((group) => group.actions);\n const isDisabled = (index: number) => !!actions[index]?.disabled;\n const found = actions.findIndex((action) => action.id === activeId && !action.disabled);\n const activeIndex = found >= 0 ? found : edgeIndex('first', actions.length, { isDisabled });\n // From the command's id, not its position: an id that stayed the same while the option under it\n // changed would not make a screen reader announce the new highlight.\n const optionId = (action: MenuAction) => `${listId}-${encodeURIComponent(action.id)}`;\n const activeOptionId = activeIndex === null ? undefined : optionId(actions[activeIndex]);\n\n useEffect(() => {\n if (!activeOptionId) return;\n scrollOptionIntoView(listRef.current, document.getElementById(activeOptionId));\n }, [activeOptionId]);\n\n function run(action: MenuAction | undefined) {\n if (!action || action.disabled) return;\n runMenuAction(action, onAction);\n onClose();\n }\n\n function handleKeyDown(event: KeyboardEvent<HTMLInputElement>) {\n // Enter confirms an IME composition before it means anything here.\n if (event.nativeEvent.isComposing) return;\n if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {\n const next = nextIndex(activeIndex, event.key === 'ArrowDown' ? 1 : -1, actions.length, { isDisabled });\n setActiveId(next === null ? null : actions[next].id);\n } else if (event.key === 'Enter') {\n run(activeIndex === null ? undefined : actions[activeIndex]);\n } else {\n return;\n }\n event.preventDefault();\n }\n\n const hasQuery = query.trim() !== '';\n const emptyText = isLoading ? text.loading : text.empty;\n let index = -1;\n\n return (\n <Modal\n {...rest}\n aria-label={text.label}\n isOpen={isOpen}\n onClose={onClose}\n hideHeader\n presentation={presentation}\n className={cx(styles.commandPalette, className, classNames?.root)}\n style={{ ...style, ...slotStyles?.root }}\n >\n <div className={cx(styles.commandPaletteSearch, classNames?.search)} style={slotStyles?.search}>\n {renderIcon(faMagnifyingGlass, { className: styles.commandPaletteSearchIcon })}\n <input\n type='text'\n role='combobox'\n aria-label={text.label}\n aria-expanded='true'\n aria-controls={listId}\n aria-autocomplete='list'\n aria-activedescendant={activeOptionId}\n autoComplete='off'\n spellCheck={false}\n placeholder={text.placeholder}\n value={query}\n onChange={(event) => {\n setQuery(event.target.value);\n setActiveId(null);\n onQueryChange?.(event.target.value);\n }}\n onKeyDown={handleKeyDown}\n className={cx(styles.commandPaletteInput, classNames?.input)}\n style={slotStyles?.input}\n />\n </div>\n\n <div\n ref={listRef}\n id={listId}\n role='listbox'\n aria-label={text.label}\n className={cx(styles.commandPaletteList, classNames?.list)}\n style={slotStyles?.list}\n >\n {groups.map((group, groupIndex) => {\n const headingId = `${listId}-heading-${groupIndex}`;\n return (\n <div\n // Groups carry no id of their own; a new query re-renders the list wholesale anyway.\n key={groupIndex}\n role={group.heading === undefined ? 'presentation' : 'group'}\n aria-labelledby={group.heading === undefined ? undefined : headingId}\n >\n {group.separated && groupIndex > 0 && (\n <div\n aria-hidden\n className={cx(styles.commandPaletteSeparator, classNames?.separator)}\n style={slotStyles?.separator}\n />\n )}\n {group.heading !== undefined && (\n <div\n id={headingId}\n role='presentation'\n className={cx(styles.commandPaletteHeading, classNames?.heading)}\n style={slotStyles?.heading}\n >\n {group.heading}\n </div>\n )}\n {group.actions.map((action) => {\n index += 1;\n const own = index;\n return (\n <div\n key={action.id}\n id={optionId(action)}\n role='option'\n aria-selected={own === activeIndex}\n aria-disabled={action.disabled || undefined}\n className={cx(\n styles.commandPaletteItem,\n own === activeIndex && styles.commandPaletteItemActive,\n action.danger && styles.commandPaletteItemDanger,\n action.disabled && styles.commandPaletteItemDisabled,\n classNames?.item,\n )}\n style={slotStyles?.item}\n // Keeps the focus, and so the caret, in the search field.\n onMouseDown={(event) => event.preventDefault()}\n // Move, not enter: a list scrolling under a resting pointer must not steal the highlight.\n onMouseMove={() => !action.disabled && setActiveId(action.id)}\n onClick={() => run(action)}\n >\n {renderItemIcon(action.icon, hasIcons, {\n className: cx(styles.commandPaletteItemIcon, classNames?.itemIcon),\n style: slotStyles?.itemIcon,\n })}\n <span\n className={cx(styles.commandPaletteItemLabel, classNames?.itemLabel)}\n style={slotStyles?.itemLabel}\n >\n {action.label}\n </span>\n {action.shortcut != null && (\n <span\n className={cx(styles.commandPaletteItemShortcut, classNames?.itemShortcut)}\n style={slotStyles?.itemShortcut}\n >\n {formatHotkey(action.shortcut)}\n </span>\n )}\n </div>\n );\n })}\n </div>\n );\n })}\n </div>\n\n {hasQuery && actions.length === 0 && (\n <div className={cx(styles.commandPaletteEmpty, classNames?.empty)} style={slotStyles?.empty}>\n {emptyText}\n </div>\n )}\n <span className={styles.commandPaletteStatus} role='status' aria-live='polite'>\n {hasQuery ? (actions.length > 0 ? text.results(act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ACrB,CAAC,EACD,EAAC,OAAD,CACE,UAAW,EAAG,EAAO,wBAAyB,GAAY,SAAS,EACnE,MAAO,GAAY,UAElB,SAAA,EAAO,KACJ,CAAA,EACL,EAAO,UAAY,MAClB,EAAC,OAAD,CACE,UAAW,EAAG,EAAO,2BAA4B,GAAY,YAAY,EACzE,MAAO,GAAY,aAElB,SAAA,EAAa,EAAO,QAAQ,CACzB,CAAA,CAEL,CArCE,EAAA,EAAO,EAqCT,CAET,CAAC,CACE,CAlEE,EAAA,CAkEF,CAET,CAAC,CACE,CAAA,EAEJ,GAAY,EAAQ,SAAW,GAC9B,EAAC,MAAD,CAAK,UAAW,EAAG,EAAO,oBAAqB,GAAY,KAAK,EAAG,MAAO,GAAY,MACnF,SAAA,CACE,CAAA,EAEP,EAAC,OAAD,CAAM,UAAW,EAAO,qBAAsB,KAAK,SAAS,YAAU,SACnE,SAAA,EAAY,EAAQ,OAAS,EAAI,EAAK,QAAQ,EAAQ,MAAM,EAAI,EAAa,EAC1E,CAAA,CACD,GAEX"}
|
|
1
|
+
{"version":3,"file":"commandPalette.mjs","names":[],"sources":["../../../../package/common/commandPalette/commandPalette.tsx"],"sourcesContent":["import { useEffect, useId, useRef, useState, type KeyboardEvent, type ReactElement } from 'react';\nimport cx from 'classnames';\nimport { faMagnifyingGlass } from '@fortawesome/free-solid-svg-icons';\n\nimport Modal from '../modal';\nimport { useComponentDefaults, useLabels } from '../configProvider';\nimport { ariaKeyshortcuts, formatHotkey } from '../hooks/useHotkeys';\nimport { edgeIndex, nextIndex, scrollOptionIntoView } from '../utils/listNavigation';\nimport { renderIcon } from '../utils/renderIcon';\nimport type { MenuAction } from '../menu/menu.types';\nimport { hasAnyIcon, renderItemIcon, runMenuAction } from '../menu/menuItem';\nimport { filterCommands, groupCommands } from './filterCommands';\nimport type { CommandPaletteLabels, CommandPaletteProps } from './commandPalette.types';\nimport styles from './commandPalette.module.pcss';\n\nconst DEFAULT_LABELS: Required<CommandPaletteLabels> = {\n label: 'Search commands',\n placeholder: 'Type a command or search…',\n empty: 'No results',\n loading: 'Searching…',\n results: (count) => (count === 1 ? '1 result' : `${count} results`),\n};\n\nfunction CommandPalette(props: CommandPaletteProps): ReactElement {\n const {\n items,\n isOpen,\n onClose,\n onAction,\n onQueryChange,\n filter = true,\n isLoading = false,\n presentation,\n labels,\n className,\n style,\n classNames,\n styles: slotStyles,\n ...rest\n } = useComponentDefaults('CommandPalette', props);\n const text = useLabels('CommandPalette', labels, DEFAULT_LABELS);\n const listId = useId();\n const listRef = useRef<HTMLDivElement>(null);\n\n const [query, setQuery] = useState('');\n // An id rather than an index, so the highlight stays on the same command while server results\n // are replaced around it. Typing clears it instead, so Enter runs the best match.\n const [activeId, setActiveId] = useState<string | null>(null);\n const [wasOpen, setWasOpen] = useState(isOpen);\n if (isOpen !== wasOpen) {\n setWasOpen(isOpen);\n if (isOpen) {\n setQuery('');\n setActiveId(null);\n }\n }\n\n // Read through a ref so an inline handler does not re-fire the effect on every parent render.\n const onQueryChangeRef = useRef(onQueryChange);\n useEffect(() => {\n onQueryChangeRef.current = onQueryChange;\n });\n useEffect(() => {\n if (isOpen) onQueryChangeRef.current?.('');\n }, [isOpen]);\n\n const groups = filter ? filterCommands(groupCommands(items), query) : groupCommands(items);\n // From all items, not the matches, so the labels do not jump sideways while the user types.\n const hasIcons = hasAnyIcon(items);\n const actions = groups.flatMap((group) => group.actions);\n const isDisabled = (index: number) => !!actions[index]?.disabled;\n const found = actions.findIndex((action) => action.id === activeId && !action.disabled);\n const activeIndex = found >= 0 ? found : edgeIndex('first', actions.length, { isDisabled });\n // From the command's id, not its position: an id that stayed the same while the option under it\n // changed would not make a screen reader announce the new highlight.\n const optionId = (action: MenuAction) => `${listId}-${encodeURIComponent(action.id)}`;\n const activeOptionId = activeIndex === null ? undefined : optionId(actions[activeIndex]);\n\n useEffect(() => {\n if (!activeOptionId) return;\n scrollOptionIntoView(listRef.current, document.getElementById(activeOptionId));\n }, [activeOptionId]);\n\n function run(action: MenuAction | undefined) {\n if (!action || action.disabled) return;\n runMenuAction(action, onAction);\n onClose();\n }\n\n function handleKeyDown(event: KeyboardEvent<HTMLInputElement>) {\n // Enter confirms an IME composition before it means anything here.\n if (event.nativeEvent.isComposing) return;\n if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {\n const next = nextIndex(activeIndex, event.key === 'ArrowDown' ? 1 : -1, actions.length, { isDisabled });\n setActiveId(next === null ? null : actions[next].id);\n } else if (event.key === 'Enter') {\n run(activeIndex === null ? undefined : actions[activeIndex]);\n } else {\n return;\n }\n event.preventDefault();\n }\n\n const hasQuery = query.trim() !== '';\n const emptyText = isLoading ? text.loading : text.empty;\n let index = -1;\n\n return (\n <Modal\n {...rest}\n aria-label={text.label}\n isOpen={isOpen}\n onClose={onClose}\n hideHeader\n presentation={presentation}\n className={cx(styles.commandPalette, className, classNames?.root)}\n style={{ ...style, ...slotStyles?.root }}\n >\n <div className={cx(styles.commandPaletteSearch, classNames?.search)} style={slotStyles?.search}>\n {renderIcon(faMagnifyingGlass, { className: styles.commandPaletteSearchIcon })}\n <input\n type='text'\n role='combobox'\n aria-label={text.label}\n aria-expanded='true'\n aria-controls={listId}\n aria-autocomplete='list'\n aria-activedescendant={activeOptionId}\n autoComplete='off'\n spellCheck={false}\n placeholder={text.placeholder}\n value={query}\n onChange={(event) => {\n setQuery(event.target.value);\n setActiveId(null);\n onQueryChange?.(event.target.value);\n }}\n onKeyDown={handleKeyDown}\n className={cx(styles.commandPaletteInput, classNames?.input)}\n style={slotStyles?.input}\n />\n </div>\n\n <div\n ref={listRef}\n id={listId}\n role='listbox'\n aria-label={text.label}\n className={cx(styles.commandPaletteList, classNames?.list)}\n style={slotStyles?.list}\n >\n {groups.map((group, groupIndex) => {\n const headingId = `${listId}-heading-${groupIndex}`;\n return (\n <div\n // Groups carry no id of their own; a new query re-renders the list wholesale anyway.\n key={groupIndex}\n role={group.heading === undefined ? 'presentation' : 'group'}\n aria-labelledby={group.heading === undefined ? undefined : headingId}\n >\n {group.separated && groupIndex > 0 && (\n <div\n aria-hidden\n className={cx(styles.commandPaletteSeparator, classNames?.separator)}\n style={slotStyles?.separator}\n />\n )}\n {group.heading !== undefined && (\n <div\n id={headingId}\n role='presentation'\n className={cx(styles.commandPaletteHeading, classNames?.heading)}\n style={slotStyles?.heading}\n >\n {group.heading}\n </div>\n )}\n {group.actions.map((action) => {\n index += 1;\n const own = index;\n return (\n <div\n key={action.id}\n id={optionId(action)}\n role='option'\n aria-selected={own === activeIndex}\n aria-disabled={action.disabled || undefined}\n aria-keyshortcuts={ariaKeyshortcuts(action.shortcut)}\n className={cx(\n styles.commandPaletteItem,\n own === activeIndex && styles.commandPaletteItemActive,\n action.danger && styles.commandPaletteItemDanger,\n action.disabled && styles.commandPaletteItemDisabled,\n classNames?.item,\n )}\n style={slotStyles?.item}\n // Keeps the focus, and so the caret, in the search field.\n onMouseDown={(event) => event.preventDefault()}\n // Move, not enter: a list scrolling under a resting pointer must not steal the highlight.\n onMouseMove={() => !action.disabled && setActiveId(action.id)}\n onClick={() => run(action)}\n >\n {renderItemIcon(action.icon, hasIcons, {\n className: cx(styles.commandPaletteItemIcon, classNames?.itemIcon),\n style: slotStyles?.itemIcon,\n })}\n <span\n className={cx(styles.commandPaletteItemLabel, classNames?.itemLabel)}\n style={slotStyles?.itemLabel}\n >\n {action.label}\n </span>\n {action.shortcut != null && (\n <span\n aria-hidden\n className={cx(styles.commandPaletteItemShortcut, classNames?.itemShortcut)}\n style={slotStyles?.itemShortcut}\n >\n {formatHotkey(action.shortcut)}\n </span>\n )}\n </div>\n );\n })}\n </div>\n );\n })}\n </div>\n\n {hasQuery && actions.length === 0 && (\n <div className={cx(styles.commandPaletteEmpty, classNames?.empty)} style={slotStyles?.empty}>\n {emptyText}\n </div>\n )}\n <span className={styles.commandPaletteStatus} role='status' aria-live='polite'>\n {hasQuery ? (actions.length > 0 ? text.results(actions.length) : emptyText) : ''}\n </span>\n </Modal>\n );\n}\n\nexport default CommandPalette;\n"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D,CACE,UAAW,EAAG,EAAO,wBAAyB,GAAY,SAAS,EACnE,MAAO,GAAY,UAElB,SAAA,EAAO,KACJ,CAAA,EACL,EAAO,UAAY,MAClB,EAAC,OAAD,CACE,cAAA,GACA,UAAW,EAAG,EAAO,2BAA4B,GAAY,YAAY,EACzE,MAAO,GAAY,aAElB,SAAA,EAAa,EAAO,QAAQ,CACzB,CAAA,CAEL,CAvCE,EAAA,EAAO,EAuCT,CAET,CAAC,CACE,CApEE,EAAA,CAoEF,CAET,CAAC,CACE,CAAA,EAEJ,GAAY,EAAQ,SAAW,GAC9B,EAAC,MAAD,CAAK,UAAW,EAAG,EAAO,oBAAqB,GAAY,KAAK,EAAG,MAAO,GAAY,MACnF,SAAA,CACE,CAAA,EAEP,EAAC,OAAD,CAAM,UAAW,EAAO,qBAAsB,KAAK,SAAS,YAAU,SACnE,SAAA,EAAY,EAAQ,OAAS,EAAI,EAAK,QAAQ,EAAQ,MAAM,EAAI,EAAa,EAC1E,CAAA,CACD,GAEX"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use client";import{useComponentDefaults as e}from"../configProvider/useComponentDefaults.mjs";import{usePresentationDefault as t}from"../configProvider/usePresentationDefault.mjs";import{Presentation as n}from"../configProvider/presentation.types.mjs";import r from"../loader/loader.mjs";import i from"../styles/sheet.module.mjs";import{PopoverAlign as ee,PopoverPlacement as te}from"../popover/popover.types.mjs";import ne from"../hooks/useSheet.mjs";import re from"../popover/popover.mjs";import ie from"../tooltip/tooltip.mjs";import{edgeIndex as
|
|
1
|
+
"use client";import{useComponentDefaults as e}from"../configProvider/useComponentDefaults.mjs";import{usePresentationDefault as t}from"../configProvider/usePresentationDefault.mjs";import{Presentation as n}from"../configProvider/presentation.types.mjs";import r from"../loader/loader.mjs";import i from"../styles/sheet.module.mjs";import{PopoverAlign as ee,PopoverPlacement as te}from"../popover/popover.types.mjs";import ne from"../hooks/useSheet.mjs";import re from"../popover/popover.mjs";import{useInfiniteScroll as ie}from"../infiniteBlock/useInfiniteScroll.mjs";import ae from"../tooltip/tooltip.mjs";import{edgeIndex as oe,nextIndex as se,scrollOptionIntoView as ce}from"../utils/listNavigation.mjs";import a from"./dropdown.module.mjs";import{useEffect as o,useId as le,useLayoutEffect as ue,useRef as s,useState as c}from"react";import l from"classnames";import{FontAwesomeIcon as de}from"@fortawesome/react-fontawesome";import{faChevronDown as fe}from"@fortawesome/free-solid-svg-icons";import{jsx as u,jsxs as d}from"react/jsx-runtime";var pe=500;function f(f){let{errorMessage:p=``,className:me=``,style:he,label:m=``,value:ge=``,isValid:_e=!0,tabIndex:ve=0,isRequired:ye=!1,customProps:h={},isRow:be=!1,disabled:g=!1,readOnly:_=!1,onScroll:xe=()=>Promise.resolve(),onClick:v,onChange:y,onFocus:Se=null,onBlur:Ce=null,onMouseEnter:we=null,onMouseLeave:Te=null,dropdownLabel:Ee,isDropdownListWider:b=!1,formValidator:x=null,classNames:S,styles:C,items:w=[],useMatLabelStyle:T=!0,alwaysFloatLabel:E=!1,placeholder:D=``,plainStyle:O=!1,scrollToSelected:De=!1,presentation:Oe,reactRef:ke,...Ae}=e(`Dropdown`,f),[je,Me]=c(!1),[Ne,Pe]=c(!1),[,Fe]=c(0),k=s(x),A=s(null),j=s(null),M=s(null),[Ie,Le]=c(!1),[N,P]=c(null),F=s({buffer:``,at:0}),I=le(),L=`${I}-listbox`,R=`${I}-label`,z=e=>`${I}-option-${e}`,B=!g&&!_,V=Ie&&B,{isLoading:Re,sentinelRef:ze}=ie(M,xe,!1),Be=t(),H=Oe??Be??n.Default,{isSheet:U}=ne(H);ue(()=>{let e=A.current,t=j.current;V&&!U&&e&&t&&(t.style.fontSize=window.getComputedStyle(e).fontSize)},[V,U]),o(()=>{if(k.current=x,!k.current)return;k.current.label=m??``,k.current.validate();let e=()=>Fe(e=>e+1);return k.current.registerOnUpdateListener(e),()=>k.current?.removeOnUpdateListener(e)},[x,m]);let W=x?x.value:ge,G=w.findIndex(e=>e.key===W);o(()=>{V&&N!==null&&ce(M.current,document.getElementById(z(N)))},[V,N]);let Ve=e=>{Pe(!0),we?.(e)},He=e=>{Pe(!1),Te?.(e)},Ue=e=>{Me(!0),Se?.(e)},We=e=>{k.current&&(k.current.touched=!0),Me(!1),Ce?.(e)},Ge=()=>x?x.touched&&x.hasError():!_e||!!p,K=()=>!!(ye||x?.validators.find(e=>e.validatorId===`required`)),Ke=e=>{x?(x.set(e),y?.(x.value,h)):y?.(e,h)};function q(e){(!e||B)&&(Le(e),e?P(De&&G>=0?G:null):F.current={buffer:``,at:0})}function J(e){e.disabled||(Ke(e.key),q(!1))}let qe={isDisabled:e=>!!w[e].disabled};function Je(e){let t=Date.now(),n=t-F.current.at>pe?e:F.current.buffer+e;F.current={buffer:n,at:t};let r=n.toLowerCase(),i=w.findIndex(e=>!e.disabled&&typeof e.label==`string`&&e.label.toLowerCase().startsWith(r));i!==-1&&(V?P(i):J(w[i]))}function Ye(e){if(B){if(!V){e.key===`ArrowDown`||e.key===`ArrowUp`||e.key===`Enter`||e.key===` `?(e.preventDefault(),q(!0)):e.key.length===1&&Je(e.key);return}if(e.key===`ArrowDown`||e.key===`ArrowUp`)e.preventDefault(),P(se(N,e.key===`ArrowDown`?1:-1,w.length,qe));else if(e.key===`Home`||e.key===`End`)e.preventDefault(),P(oe(e.key===`Home`?`first`:`last`,w.length,qe));else if(e.key===`Enter`||e.key===` `){e.preventDefault();let t=N===null?void 0:w[N];t?J(t):q(!1)}else e.key===`Escape`||e.key===`Tab`?q(!1):e.key.length===1&&Je(e.key)}}let Y=Ee,X=Ge();w.forEach(e=>{e.key===W&&(Y=e.label)});let Z=Y||W,Q=Z==null||typeof Z==`string`&&Z.trim()===``,Xe=K()?u(`span`,{className:a.requiredMark,children:`*`}):null,Ze=m&&K()?`${m} *`:m,$=je&&!_;return d(`div`,{...Ae,className:l(me,S?.root,a.dropdownLabel,a.dropdown,{[a.dropdownLabelColumn]:!be,[a.dropdownWithLabel]:T&&!!m}),style:{...he,...C?.root},onMouseEnter:Ve,onMouseLeave:He,children:[u(`div`,{children:u(re,{isOpen:V,onOpenChange:q,disabled:!B,placement:te.Bottom,align:ee.Start,offset:0,withArrow:!1,constrainWidth:!1,width:`trigger`,focusOnOpen:!1,presentation:H,classNames:{panel:a.dropdownPanel},content:u(`div`,{ref:j,className:l(!U&&a.dropdownInputListAnim,{[a.dropdownInputListAnimWider]:b&&!U}),children:d(`div`,{ref:M,id:L,role:`listbox`,"aria-label":m||D||void 0,className:l(a.dropdownInputList,U&&i.sheetScroll,S?.list),style:C?.list,children:[w.map((e,t)=>u(`div`,{id:z(t),role:`option`,"aria-selected":e.key===W,"aria-disabled":e.disabled||void 0,style:C?.option,className:l(a.dropdownInputListItem,S?.option,{[a.dropdownInputListItemActive]:N===t,[a.dropdownInputListItemSelected]:e.key===W,[a.dropdownInputListItemDisabled]:!!e.disabled}),onMouseDown:e=>e.preventDefault(),onMouseEnter:()=>P(t),onClick:()=>J(e),children:e.label},e.key)),u(`div`,{ref:ze,className:a.dropdownSentinel,"aria-hidden":`true`}),Re&&u(`div`,{className:a.dropdownLoadMore,"aria-hidden":`true`,children:u(r,{size:32})})]})}),children:d(`div`,{ref:A,onFocus:Ue,onBlur:We,className:l(a.dropdownInput,{[a.dropdownInputPlain]:O,[a.dropdownInputReadOnly]:_&&!g},S?.field),style:C?.field,children:[u(`button`,{tabIndex:ve,type:`button`,disabled:g,role:`combobox`,"aria-haspopup":`listbox`,"aria-expanded":V,"aria-controls":L,"aria-activedescendant":V&&N!==null?z(N):void 0,"aria-labelledby":m?R:void 0,"aria-label":m?void 0:D||void 0,"aria-readonly":_||void 0,className:l(a.dropdownInputButton,{[a.dropdownInputButtonDisabled]:g,[a.dropdownInputButtonReadOnly]:_&&!g},S?.control),style:{...b?{padding:`6px`,border:`none`}:{},...C?.control},onKeyDown:Ye,onClick:v,ref:ke,children:Q?`\xA0`:Z}),u(`button`,{type:`button`,tabIndex:-1,disabled:g,"aria-hidden":`true`,className:l(a.dropdownInputButtonIcon,S?.icon),style:C?.icon,onMouseDown:e=>e.preventDefault(),onClick:v,children:!g&&!_&&u(de,{icon:fe,className:l(a.dropdownInputButtonIconArrow,{[a.dropdownInputButtonIconArrowOpen]:V})})}),u(`fieldset`,{className:l(a.dropdownFieldset,{[a.dropdownBorderPlain]:O,[a.dropdownBorderFocused]:$,[a.dropdownBorderInvalid]:X,[a.dropdownBorderError]:X}),children:u(`legend`,{className:l(a.dropdownFieldsetLegend,{[a.dropdownFieldsetLegendActive]:T&&(E||$||!Q)}),children:u(`span`,{children:Ze})})}),T&&m&&d(`div`,{id:R,className:l(a.dropdownMatLabel,{[a.dropdownMatLabelFloating]:E||$||!Q},S?.label),style:C?.label,children:[m,Xe]}),T&&D&&u(`div`,{className:l(a.dropdownPlaceholder,$&&!Y&&a.dropdownPlaceholderShown),children:D})]})})}),m&&!T&&d(`div`,{id:R,className:l(a.dropdownLabelText,S?.label),style:C?.label,children:[m,Xe]}),u(ae,{variant:`error`,message:x?x.getCurrentErrorMessage():p||``,isVisible:X&&(je||Ne)})]})}export{f as default};
|
|
2
2
|
//# sourceMappingURL=dropdown.mjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use client";import{useLayoutEffect as e,useRef as t}from"react";function n(e){let t=e.parentElement,{minHeight:n}=t?.style??{},{alignSelf:r}=e.style;t&&(t.style.minHeight=`${t.offsetHeight}px`),e.style.alignSelf=`flex-start`,e.style.height=`auto`;let i=e.scrollHeight>e.clientHeight+1;return e.style.height=`${e.scrollHeight}px`,e.style.alignSelf=r,t&&(t.style.minHeight=n??``),i}function r(r,i,{enabled:a=!0,onGrow:o}={}){let s=t(o);e(()=>{s.current=o}),e(()=>{let e=r.current;if(!a||!e)return;let t=e.offsetWidth,i=0,o=new ResizeObserver(()=>{e.offsetWidth!==t&&(t=e.offsetWidth,cancelAnimationFrame(i),i=requestAnimationFrame(()=>{let t=n(e);s.current?.(t)}))});return o.observe(e),()=>{o.disconnect(),cancelAnimationFrame(i),e.style.height=``}},[r,a]),e(()=>{if(!a||!r.current)return;let e=n(r.current);s.current?.(e)},[r,i,a])}export{r as useAutoGrow};
|
|
2
|
+
//# sourceMappingURL=useAutoGrow.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useAutoGrow.mjs","names":[],"sources":["../../../../package/common/hooks/useAutoGrow.ts"],"sourcesContent":["import { useLayoutEffect, useRef, type RefObject } from 'react';\n\ninterface AutoGrowOptions {\n enabled?: boolean;\n /** Whether the text needs more than the field's `rows`, after each change of `value` or width. */\n onGrow?: (isGrown: boolean) => void;\n}\n\n/** Sizes the field to its text, and says whether that took it past its `rows`. */\nfunction grow(field: HTMLElement): boolean {\n // Collapsing the field to measure it would shrink its parent for that moment. A scroller that\n // gains the room clamps its position and keeps it when the field grows back: a chat's message\n // list lost its bottom on every keystroke. Holding the parent's height keeps the collapse inside;\n // offsetHeight, as a transform (a modal scaling in) would make the rect too small to hold it.\n const parent = field.parentElement;\n const { minHeight } = parent?.style ?? {};\n const { alignSelf } = field.style;\n if (parent) parent.style.minHeight = `${parent.offsetHeight}px`;\n // A stretched field would grow back to the held height and never measure shorter (Input's is).\n field.style.alignSelf = 'flex-start';\n field.style.height = 'auto';\n // Collapsed, the field is as tall as its `rows`. The 1px absorbs rounding: a line is far more.\n const isGrown = field.scrollHeight > field.clientHeight + 1;\n field.style.height = `${field.scrollHeight}px`;\n field.style.alignSelf = alignSelf;\n if (parent) parent.style.minHeight = minHeight ?? '';\n return isGrown;\n}\n\n/**\n * Keeps a textarea as tall as its text, up to the `max-height` its stylesheet sets. It measures\n * again when `value` changes, so the field must be controlled, and when its width changes.\n */\nexport function useAutoGrow(\n ref: RefObject<HTMLElement | null>,\n value: unknown,\n { enabled = true, onGrow }: AutoGrowOptions = {},\n): void {\n // Kept in a ref so a fresh callback each render does not resubscribe the observer.\n const onGrowRef = useRef(onGrow);\n useLayoutEffect(() => {\n onGrowRef.current = onGrow;\n });\n\n useLayoutEffect(() => {\n const field = ref.current;\n if (!enabled || !field) return undefined;\n let width = field.offsetWidth;\n let frame = 0;\n // A new width rewraps the same text onto more or fewer lines. Growing in the callback itself\n // would resize what is observed, which browsers report as a ResizeObserver loop error, so it\n // waits a frame. The height it then changes is skipped, as the width is the same.\n const observer = new ResizeObserver(() => {\n if (field.offsetWidth === width) return;\n width = field.offsetWidth;\n cancelAnimationFrame(frame);\n frame = requestAnimationFrame(() => {\n const isGrown = grow(field);\n onGrowRef.current?.(isGrown);\n });\n });\n observer.observe(field);\n return () => {\n observer.disconnect();\n cancelAnimationFrame(frame);\n // Only clears a height this set, so an explicit one from a style prop survives while\n // disabled. Here rather than below, where it would collapse the field on every keystroke.\n field.style.height = '';\n };\n }, [ref, enabled]);\n\n useLayoutEffect(() => {\n if (!enabled || !ref.current) return;\n // Measured first: an optional call skips evaluating its argument when there is no callback.\n const isGrown = grow(ref.current);\n onGrowRef.current?.(isGrown);\n }, [ref, value, enabled]);\n}\n"],"mappings":"iEASA,SAAS,EAAK,EAA6B,CAKzC,IAAM,EAAS,EAAM,cACf,CAAE,aAAc,GAAQ,OAAS,CAAC,EAClC,CAAE,aAAc,EAAM,MACxB,IAAQ,EAAO,MAAM,UAAY,GAAG,EAAO,aAAa,KAE5D,EAAM,MAAM,UAAY,aACxB,EAAM,MAAM,OAAS,OAErB,IAAM,EAAU,EAAM,aAAe,EAAM,aAAe,EAI1D,MAHA,GAAM,MAAM,OAAS,GAAG,EAAM,aAAa,IAC3C,EAAM,MAAM,UAAY,EACpB,IAAQ,EAAO,MAAM,UAAY,GAAa,IAC3C,CACT,CAMA,SAAgB,EACd,EACA,EACA,CAAE,UAAU,GAAM,UAA4B,CAAC,EACzC,CAEN,IAAM,EAAY,EAAO,CAAM,EAC/B,MAAsB,CACpB,EAAU,QAAU,CACtB,CAAC,EAED,MAAsB,CACpB,IAAM,EAAQ,EAAI,QAClB,GAAI,CAAC,GAAW,CAAC,EAAO,OACxB,IAAI,EAAQ,EAAM,YACd,EAAQ,EAIN,EAAW,IAAI,mBAAqB,CACpC,EAAM,cAAgB,IAC1B,EAAQ,EAAM,YACd,qBAAqB,CAAK,EAC1B,EAAQ,0BAA4B,CAClC,IAAM,EAAU,EAAK,CAAK,EAC1B,EAAU,UAAU,CAAO,CAC7B,CAAC,EACH,CAAC,EAED,OADA,EAAS,QAAQ,CAAK,MACT,CACX,EAAS,WAAW,EACpB,qBAAqB,CAAK,EAG1B,EAAM,MAAM,OAAS,EACvB,CACF,EAAG,CAAC,EAAK,CAAO,CAAC,EAEjB,MAAsB,CACpB,GAAI,CAAC,GAAW,CAAC,EAAI,QAAS,OAE9B,IAAM,EAAU,EAAK,EAAI,OAAO,EAChC,EAAU,UAAU,CAAO,CAC7B,EAAG,CAAC,EAAK,EAAO,CAAO,CAAC,CAC1B"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use client";import{useEffect as e,useRef as t}from"react";var n=`input, textarea, select, [contenteditable=""], [contenteditable="true"]`,r={esc:`escape`,space:` `,spacebar:` `,plus:`+`,up:`arrowup`,down:`arrowdown`,left:`arrowleft`,right:`arrowright`};function i(){return typeof navigator<`u`&&/Mac|iPhone|iPad|iPod/i.test(navigator.userAgent)}function a(e){let t=e.split(`+`).map(e=>e.trim().toLowerCase()).filter(Boolean);if(t.length===0)return null;let n={key:``,ctrl:!1,meta:!1,alt:!1,shift:!1,shiftNamed:!1},a=i();for(let e of t)switch(e){case`mod`:a?n.meta=!0:n.ctrl=!0;break;case`ctrl`:case`control`:n.ctrl=!0;break;case`meta`:case`cmd`:case`command`:n.meta=!0;break;case`alt`:case`option`:n.alt=!0;break;case`shift`:n.shift=!0,n.shiftNamed=!0;break;default:n.key=r[e]??e}return n.key?n:null}function o(e){let t=[e.key.toLowerCase()],n=/^(?:Key|Digit)(.)$/.exec(e.code);return n&&t.push(n[1].toLowerCase()),t}function s(e,t){return e.ctrl!==t.ctrlKey||e.meta!==t.metaKey||e.alt!==t.altKey||e.shiftNamed&&e.shift!==t.shiftKey?!1:o(t).includes(e.key)}function c(e){return e instanceof Element&&!!e.closest(n)}var l=new Set([`arrowup`,`arrowdown`,`arrowleft`,`arrowright`,`home`,`end`,`pageup`,`pagedown`,`backspace`,`delete`,`enter`,`tab`]);function u(e){return e.ctrl||e.meta||e.alt?!1:e.key.length===1||l.has(e.key)}var d={" ":`Space`,arrowup:`↑`,arrowdown:`↓`,arrowleft:`←`,arrowright:`→`,escape:`Esc`,enter:`↵`,backspace:`⌫`,delete:`Del`,pageup:`PgUp`,pagedown:`PgDn`};function f(e){let t=a(e);if(!t)return e;let n=d[t.key]??(t.key.length===1?t.key.toUpperCase():p(t.key));return i()?[t.ctrl&&`⌃`,t.alt&&`⌥`,t.shift&&`⇧`,t.meta&&`⌘`].filter(Boolean).join(``)+n:[...[t.ctrl&&`Ctrl`,t.meta&&`Win`,t.alt&&`Alt`,t.shift&&`Shift`].filter(Boolean),n].join(`+`)}function p(e){return e[0].toUpperCase()+e.slice(1)}function m(n,r={}){let{enabled:i=!0,target:o,enableInFields:l=!1,preventDefault:d=!0}=r,
|
|
1
|
+
"use client";import{useEffect as e,useRef as t}from"react";var n=`input, textarea, select, [contenteditable=""], [contenteditable="true"]`,r={esc:`escape`,space:` `,spacebar:` `,plus:`+`,up:`arrowup`,down:`arrowdown`,left:`arrowleft`,right:`arrowright`};function i(){return typeof navigator<`u`&&/Mac|iPhone|iPad|iPod/i.test(navigator.userAgent)}function a(e){let t=e.split(`+`).map(e=>e.trim().toLowerCase()).filter(Boolean);if(t.length===0)return null;let n={key:``,ctrl:!1,meta:!1,alt:!1,shift:!1,shiftNamed:!1},a=i();for(let e of t)switch(e){case`mod`:a?n.meta=!0:n.ctrl=!0;break;case`ctrl`:case`control`:n.ctrl=!0;break;case`meta`:case`cmd`:case`command`:n.meta=!0;break;case`alt`:case`option`:n.alt=!0;break;case`shift`:n.shift=!0,n.shiftNamed=!0;break;default:n.key=r[e]??e}return n.key?n:null}function o(e){let t=[e.key.toLowerCase()],n=/^(?:Key|Digit)(.)$/.exec(e.code);return n&&t.push(n[1].toLowerCase()),t}function s(e,t){return e.ctrl!==t.ctrlKey||e.meta!==t.metaKey||e.alt!==t.altKey||e.shiftNamed&&e.shift!==t.shiftKey?!1:o(t).includes(e.key)}function c(e){return e instanceof Element&&!!e.closest(n)}var l=new Set([`arrowup`,`arrowdown`,`arrowleft`,`arrowright`,`home`,`end`,`pageup`,`pagedown`,`backspace`,`delete`,`enter`,`tab`]);function u(e){return e.ctrl||e.meta||e.alt?!1:e.key.length===1||l.has(e.key)}var d={" ":`Space`,arrowup:`↑`,arrowdown:`↓`,arrowleft:`←`,arrowright:`→`,escape:`Esc`,enter:`↵`,backspace:`⌫`,delete:`Del`,pageup:`PgUp`,pagedown:`PgDn`};function f(e){let t=a(e);if(!t)return e;let n=d[t.key]??(t.key.length===1?t.key.toUpperCase():p(t.key));return i()?[t.ctrl&&`⌃`,t.alt&&`⌥`,t.shift&&`⇧`,t.meta&&`⌘`].filter(Boolean).join(``)+n:[...[t.ctrl&&`Ctrl`,t.meta&&`Win`,t.alt&&`Alt`,t.shift&&`Shift`].filter(Boolean),n].join(`+`)}function p(e){return e[0].toUpperCase()+e.slice(1)}var m={" ":`Space`,"+":`Plus`,arrowup:`ArrowUp`,arrowdown:`ArrowDown`,arrowleft:`ArrowLeft`,arrowright:`ArrowRight`,pageup:`PageUp`,pagedown:`PageDown`};function h(e){let t=e?a(e):null;if(!t)return;let n=m[t.key]??p(t.key);return[...[t.ctrl&&`Control`,t.alt&&`Alt`,t.shift&&`Shift`,t.meta&&`Meta`].filter(Boolean),n].join(`+`)}function g(n,r={}){let{enabled:i=!0,target:o,enableInFields:l=!1,preventDefault:d=!0,repeat:f=!1}=r,p=t(n);e(()=>{p.current=n}),e(()=>{if(!i)return;let e=o?o.current:window;if(!e)return;function t(e){let t=e;if(!t.isComposing)for(let[e,n]of Object.entries(p.current)){let r=a(e);if(r&&s(r,t)&&!(u(r)&&!l&&c(t.target))){if(d&&t.preventDefault(),t.repeat&&!f)return;n(t);return}}}return e.addEventListener(`keydown`,t),()=>e.removeEventListener(`keydown`,t)},[i,o,l,d,f])}export{h as ariaKeyshortcuts,g as default,g as useHotkeys,f as formatHotkey};
|
|
2
2
|
//# sourceMappingURL=useHotkeys.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useHotkeys.mjs","names":[],"sources":["../../../../package/common/hooks/useHotkeys.ts"],"sourcesContent":["import { useEffect, useRef, type RefObject } from 'react';\n\nexport type HotkeyHandler = (event: KeyboardEvent) => void;\n\n/** Combo → handler, e.g. `{ 'mod+k': open, Escape: close }`. */\nexport type HotkeyMap = Record<string, HotkeyHandler>;\n\nexport interface UseHotkeysOptions {\n /** Attach the listener at all. Default `true`; pass `false` to suspend every combo at once. */\n enabled?: boolean;\n /** Scope the shortcuts to one element instead of the whole window. */\n target?: RefObject<HTMLElement | null>;\n /**\n * Let plain-key combos fire while a text field or `contenteditable` has focus. Default `false`,\n * so `'n'` does not fire for every `n` typed into an input. Combos carrying Ctrl, Cmd or Alt\n * are never suppressed — they cannot be confused with typing.\n */\n enableInFields?: boolean;\n /**\n * Call `preventDefault()` on a match, so `mod+s` does not also open the browser's save dialog.\n * Default `true`.\n */\n preventDefault?: boolean;\n}\n\ninterface Combo {\n key: string;\n ctrl: boolean;\n meta: boolean;\n alt: boolean;\n shift: boolean;\n /** Set when the combo named Shift itself — see `matches`. */\n shiftNamed: boolean;\n}\n\nconst FIELD_SELECTOR = 'input, textarea, select, [contenteditable=\"\"], [contenteditable=\"true\"]';\n\n/** Spellings accepted for keys whose `event.key` is awkward to write inside a `+`-separated combo. */\nconst KEY_ALIASES: Record<string, string> = {\n esc: 'escape',\n space: ' ',\n spacebar: ' ',\n plus: '+',\n up: 'arrowup',\n down: 'arrowdown',\n left: 'arrowleft',\n right: 'arrowright',\n};\n\n/** `mod` is Cmd where Cmd is the command modifier, and Ctrl everywhere else. */\nfunction isApplePlatform(): boolean {\n return typeof navigator !== 'undefined' && /Mac|iPhone|iPad|iPod/i.test(navigator.userAgent);\n}\n\nfunction parseCombo(combo: string): Combo | null {\n const parts = combo\n .split('+')\n .map((part) => part.trim().toLowerCase())\n .filter(Boolean);\n // A trailing separator (`'mod+'`) loses its key to the filter above, so the whole combo is\n // dropped rather than matching on the modifier alone. `'mod+plus'` is how to mean `+` itself.\n if (parts.length === 0) return null;\n\n const parsed: Combo = { key: '', ctrl: false, meta: false, alt: false, shift: false, shiftNamed: false };\n const apple = isApplePlatform();\n\n for (const part of parts) {\n switch (part) {\n case 'mod':\n if (apple) parsed.meta = true;\n else parsed.ctrl = true;\n break;\n case 'ctrl':\n case 'control':\n parsed.ctrl = true;\n break;\n case 'meta':\n case 'cmd':\n case 'command':\n parsed.meta = true;\n break;\n case 'alt':\n case 'option':\n parsed.alt = true;\n break;\n case 'shift':\n parsed.shift = true;\n parsed.shiftNamed = true;\n break;\n default:\n parsed.key = KEY_ALIASES[part] ?? part;\n }\n }\n\n return parsed.key ? parsed : null;\n}\n\n/**\n * The key the event carries, plus the one its physical position would produce unshifted.\n *\n * Both are needed: Alt+K on a Mac arrives as `key: '˚'` and Shift+1 as `key: '!'`, so a combo\n * written against the letter or digit on the keycap only matches through `code`.\n */\nfunction pressedKeys(event: KeyboardEvent): string[] {\n const keys = [event.key.toLowerCase()];\n const physical = /^(?:Key|Digit)(.)$/.exec(event.code);\n if (physical) keys.push(physical[1].toLowerCase());\n return keys;\n}\n\nfunction matches(combo: Combo, event: KeyboardEvent): boolean {\n if (combo.ctrl !== event.ctrlKey || combo.meta !== event.metaKey || combo.alt !== event.altKey) return false;\n // Shift is only compared when the combo named it. A symbol is typed *with* Shift on most\n // layouts, so requiring `shiftKey === false` would make `'?'` and `'mod+/'` unreachable.\n if (combo.shiftNamed && combo.shift !== event.shiftKey) return false;\n return pressedKeys(event).includes(combo.key);\n}\n\nfunction isInField(target: EventTarget | null): boolean {\n return target instanceof Element && !!target.closest(FIELD_SELECTOR);\n}\n\n/** Keys a text field uses for itself, beyond the characters it inserts. */\nconst FIELD_KEYS = new Set([\n 'arrowup',\n 'arrowdown',\n 'arrowleft',\n 'arrowright',\n 'home',\n 'end',\n 'pageup',\n 'pagedown',\n 'backspace',\n 'delete',\n 'enter',\n 'tab',\n]);\n\n/**\n * Whether a combo would be taken out of a focused field's mouth.\n *\n * Ctrl, Cmd and Alt take a key out of the field's hands whatever it is. Without one, a single\n * character is typing and the listed keys are editing, but `F2` and `Escape` are neither, and\n * suppressing those made a menu's `F2` do nothing the moment the page had a focused input.\n */\nfunction isFieldKey(combo: Combo): boolean {\n if (combo.ctrl || combo.meta || combo.alt) return false;\n return combo.key.length === 1 || FIELD_KEYS.has(combo.key);\n}\n\n/** Keys whose name is not what a keycap says. Anything else is capitalised, so `f2` reads `F2`. */\nconst KEY_LABELS: Record<string, string> = {\n ' ': 'Space',\n arrowup: '↑',\n arrowdown: '↓',\n arrowleft: '←',\n arrowright: '→',\n escape: 'Esc',\n enter: '↵',\n backspace: '⌫',\n delete: 'Del',\n pageup: 'PgUp',\n pagedown: 'PgDn',\n};\n\n/**\n * A combo written for the reader: `'mod+shift+k'` reads `⇧⌘K` on an Apple platform and\n * `Ctrl+Shift+K` everywhere else.\n *\n * So a shortcut is written once, in one spelling, and the hint beside it cannot contradict what\n * the binding actually listens for. Hand-written `'⌘K'` hints are wrong on every other platform,\n * silently, because nothing compares the label to the binding.\n *\n * Resolved from the platform at call time, so a server-rendered page renders the non-Apple form.\n */\nexport function formatHotkey(combo: string): string {\n const parsed = parseCombo(combo);\n if (!parsed) return combo;\n\n const key = KEY_LABELS[parsed.key] ?? (parsed.key.length === 1 ? parsed.key.toUpperCase() : capitalise(parsed.key));\n\n // Apple orders modifier symbols ⌃⌥⇧⌘ and runs them into the key; everywhere else they are\n // words joined by `+`.\n if (isApplePlatform()) {\n const symbols = [parsed.ctrl && '⌃', parsed.alt && '⌥', parsed.shift && '⇧', parsed.meta && '⌘'];\n return symbols.filter(Boolean).join('') + key;\n }\n const words = [parsed.ctrl && 'Ctrl', parsed.meta && 'Win', parsed.alt && 'Alt', parsed.shift && 'Shift'];\n return [...words.filter(Boolean), key].join('+');\n}\n\nfunction capitalise(value: string): string {\n return value[0].toUpperCase() + value.slice(1);\n}\n\n/**\n * Keyboard shortcuts, for a whole app or for one element.\n *\n * ```tsx\n * useHotkeys({ 'mod+k': () => setPaletteOpen(true), '?': () => setHelpOpen(true) });\n * ```\n *\n * The map is read through a ref at event time, so an inline object literal is fine and no handler\n * needs memoising. Shortcuts keep firing while a Modal or Drawer is open — pass `enabled` for the\n * ones that should not.\n */\nexport function useHotkeys(hotkeys: HotkeyMap, options: UseHotkeysOptions = {}): void {\n const { enabled = true, target, enableInFields = false, preventDefault = true } = options;\n\n const hotkeysRef = useRef(hotkeys);\n useEffect(() => {\n hotkeysRef.current = hotkeys;\n });\n\n useEffect(() => {\n if (!enabled) return;\n const node: HTMLElement | Window | null = target ? target.current : window;\n if (!node) return;\n\n function onKeyDown(event: Event) {\n const keyboardEvent = event as KeyboardEvent;\n // A key pressed to compose a character in an IME is not a shortcut.\n if (keyboardEvent.isComposing) return;\n\n for (const [spelling, handler] of Object.entries(hotkeysRef.current)) {\n const combo = parseCombo(spelling);\n if (!combo || !matches(combo, keyboardEvent)) continue;\n if (isFieldKey(combo) && !enableInFields && isInField(keyboardEvent.target)) continue;\n if (preventDefault) keyboardEvent.preventDefault();\n handler(keyboardEvent);\n return;\n }\n }\n\n node.addEventListener('keydown', onKeyDown);\n return () => node.removeEventListener('keydown', onKeyDown);\n }, [enabled, target, enableInFields, preventDefault]);\n}\n\nexport default useHotkeys;\n"],"mappings":"2DAmCA,IAAM,EAAiB,0EAGjB,EAAsC,CAC1C,IAAK,SACL,MAAO,IACP,SAAU,IACV,KAAM,IACN,GAAI,UACJ,KAAM,YACN,KAAM,YACN,MAAO,YACT,EAGA,SAAS,GAA2B,CAClC,OAAO,OAAO,UAAc,KAAe,wBAAwB,KAAK,UAAU,SAAS,CAC7F,CAEA,SAAS,EAAW,EAA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c,YAElB,IAAK,GAAM,CAAC,EAAU,KAAY,OAAO,QAAQ,EAAW,OAAO,EAAG,CACpE,IAAM,EAAQ,EAAW,CAAQ,EAC7B,GAAC,GAAU,EAAQ,EAAO,CAAa,GACvC,IAAW,CAAK,GAAK,CAAC,GAAkB,EAAU,EAAc,MAAM,GAE1E,CADI,GAAgB,EAAc,eAAe,EACjD,EAAQ,CAAa,EACrB,MADqB,CAEvB,CACF,CAGA,OADA,EAAK,iBAAiB,UAAW,CAAS,MAC7B,EAAK,oBAAoB,UAAW,CAAS,CAC5D,EAAG,CAAC,EAAS,EAAQ,EAAgB,CAAc,CAAC,CACtD"}
|
|
1
|
+
{"version":3,"file":"useHotkeys.mjs","names":[],"sources":["../../../../package/common/hooks/useHotkeys.ts"],"sourcesContent":["import { useEffect, useRef, type RefObject } from 'react';\n\nexport type HotkeyHandler = (event: KeyboardEvent) => void;\n\n/** Combo → handler, e.g. `{ 'mod+k': open, Escape: close }`. */\nexport type HotkeyMap = Record<string, HotkeyHandler>;\n\nexport interface UseHotkeysOptions {\n /** Attach the listener at all. Default `true`; pass `false` to suspend every combo at once. */\n enabled?: boolean;\n /** Scope the shortcuts to one element instead of the whole window. */\n target?: RefObject<HTMLElement | null>;\n /**\n * Let plain-key combos fire while a text field or `contenteditable` has focus. Default `false`,\n * so `'n'` does not fire for every `n` typed into an input. Combos carrying Ctrl, Cmd or Alt\n * are never suppressed — they cannot be confused with typing.\n */\n enableInFields?: boolean;\n /**\n * Call `preventDefault()` on a match, so `mod+s` does not also open the browser's save dialog.\n * Default `true`.\n */\n preventDefault?: boolean;\n /**\n * Fire again for each repeat while the combo is held. Default `false`, so holding `mod+s` saves\n * once. Turn it on for keys that step through something, such as arrows or zoom.\n */\n repeat?: boolean;\n}\n\ninterface Combo {\n key: string;\n ctrl: boolean;\n meta: boolean;\n alt: boolean;\n shift: boolean;\n /** Set when the combo named Shift itself — see `matches`. */\n shiftNamed: boolean;\n}\n\nconst FIELD_SELECTOR = 'input, textarea, select, [contenteditable=\"\"], [contenteditable=\"true\"]';\n\n/** Spellings accepted for keys whose `event.key` is awkward to write inside a `+`-separated combo. */\nconst KEY_ALIASES: Record<string, string> = {\n esc: 'escape',\n space: ' ',\n spacebar: ' ',\n plus: '+',\n up: 'arrowup',\n down: 'arrowdown',\n left: 'arrowleft',\n right: 'arrowright',\n};\n\n/** `mod` is Cmd where Cmd is the command modifier, and Ctrl everywhere else. */\nfunction isApplePlatform(): boolean {\n return typeof navigator !== 'undefined' && /Mac|iPhone|iPad|iPod/i.test(navigator.userAgent);\n}\n\nfunction parseCombo(combo: string): Combo | null {\n const parts = combo\n .split('+')\n .map((part) => part.trim().toLowerCase())\n .filter(Boolean);\n // A trailing separator (`'mod+'`) loses its key to the filter above, so the whole combo is\n // dropped rather than matching on the modifier alone. `'mod+plus'` is how to mean `+` itself.\n if (parts.length === 0) return null;\n\n const parsed: Combo = { key: '', ctrl: false, meta: false, alt: false, shift: false, shiftNamed: false };\n const apple = isApplePlatform();\n\n for (const part of parts) {\n switch (part) {\n case 'mod':\n if (apple) parsed.meta = true;\n else parsed.ctrl = true;\n break;\n case 'ctrl':\n case 'control':\n parsed.ctrl = true;\n break;\n case 'meta':\n case 'cmd':\n case 'command':\n parsed.meta = true;\n break;\n case 'alt':\n case 'option':\n parsed.alt = true;\n break;\n case 'shift':\n parsed.shift = true;\n parsed.shiftNamed = true;\n break;\n default:\n parsed.key = KEY_ALIASES[part] ?? part;\n }\n }\n\n return parsed.key ? parsed : null;\n}\n\n/**\n * The key the event carries, plus the one its physical position would produce unshifted.\n *\n * Both are needed: Alt+K on a Mac arrives as `key: '˚'` and Shift+1 as `key: '!'`, so a combo\n * written against the letter or digit on the keycap only matches through `code`.\n */\nfunction pressedKeys(event: KeyboardEvent): string[] {\n const keys = [event.key.toLowerCase()];\n const physical = /^(?:Key|Digit)(.)$/.exec(event.code);\n if (physical) keys.push(physical[1].toLowerCase());\n return keys;\n}\n\nfunction matches(combo: Combo, event: KeyboardEvent): boolean {\n if (combo.ctrl !== event.ctrlKey || combo.meta !== event.metaKey || combo.alt !== event.altKey) return false;\n // Shift is only compared when the combo named it. A symbol is typed *with* Shift on most\n // layouts, so requiring `shiftKey === false` would make `'?'` and `'mod+/'` unreachable.\n if (combo.shiftNamed && combo.shift !== event.shiftKey) return false;\n return pressedKeys(event).includes(combo.key);\n}\n\nfunction isInField(target: EventTarget | null): boolean {\n return target instanceof Element && !!target.closest(FIELD_SELECTOR);\n}\n\n/** Keys a text field uses for itself, beyond the characters it inserts. */\nconst FIELD_KEYS = new Set([\n 'arrowup',\n 'arrowdown',\n 'arrowleft',\n 'arrowright',\n 'home',\n 'end',\n 'pageup',\n 'pagedown',\n 'backspace',\n 'delete',\n 'enter',\n 'tab',\n]);\n\n/**\n * Whether a combo would be taken out of a focused field's mouth.\n *\n * Ctrl, Cmd and Alt take a key out of the field's hands whatever it is. Without one, a single\n * character is typing and the listed keys are editing, but `F2` and `Escape` are neither, and\n * suppressing those made a menu's `F2` do nothing the moment the page had a focused input.\n */\nfunction isFieldKey(combo: Combo): boolean {\n if (combo.ctrl || combo.meta || combo.alt) return false;\n return combo.key.length === 1 || FIELD_KEYS.has(combo.key);\n}\n\n/** Keys whose name is not what a keycap says. Anything else is capitalised, so `f2` reads `F2`. */\nconst KEY_LABELS: Record<string, string> = {\n ' ': 'Space',\n arrowup: '↑',\n arrowdown: '↓',\n arrowleft: '←',\n arrowright: '→',\n escape: 'Esc',\n enter: '↵',\n backspace: '⌫',\n delete: 'Del',\n pageup: 'PgUp',\n pagedown: 'PgDn',\n};\n\n/**\n * A combo written for the reader: `'mod+shift+k'` reads `⇧⌘K` on an Apple platform and\n * `Ctrl+Shift+K` everywhere else.\n *\n * So a shortcut is written once, in one spelling, and the hint beside it cannot contradict what\n * the binding actually listens for. Hand-written `'⌘K'` hints are wrong on every other platform,\n * silently, because nothing compares the label to the binding.\n *\n * Resolved from the platform at call time, so a server-rendered page renders the non-Apple form.\n */\nexport function formatHotkey(combo: string): string {\n const parsed = parseCombo(combo);\n if (!parsed) return combo;\n\n const key = KEY_LABELS[parsed.key] ?? (parsed.key.length === 1 ? parsed.key.toUpperCase() : capitalise(parsed.key));\n\n // Apple orders modifier symbols ⌃⌥⇧⌘ and runs them into the key; everywhere else they are\n // words joined by `+`.\n if (isApplePlatform()) {\n const symbols = [parsed.ctrl && '⌃', parsed.alt && '⌥', parsed.shift && '⇧', parsed.meta && '⌘'];\n return symbols.filter(Boolean).join('') + key;\n }\n const words = [parsed.ctrl && 'Ctrl', parsed.meta && 'Win', parsed.alt && 'Alt', parsed.shift && 'Shift'];\n return [...words.filter(Boolean), key].join('+');\n}\n\nfunction capitalise(value: string): string {\n return value[0].toUpperCase() + value.slice(1);\n}\n\n/** UI Events key names that are not the lowercase spelling capitalised. */\nconst ARIA_KEY_NAMES: Record<string, string> = {\n // The attribute's syntax uses both characters as separators, so ARIA names them instead.\n ' ': 'Space',\n '+': 'Plus',\n arrowup: 'ArrowUp',\n arrowdown: 'ArrowDown',\n arrowleft: 'ArrowLeft',\n arrowright: 'ArrowRight',\n pageup: 'PageUp',\n pagedown: 'PageDown',\n};\n\n/**\n * A combo as `aria-keyshortcuts` spells it: `'mod+shift+k'` is `Control+Shift+K`, or\n * `Meta+Shift+K` on an Apple platform. Resolved from the platform like `formatHotkey`, so the two\n * always name the same keys.\n */\nexport function ariaKeyshortcuts(combo: string | undefined): string | undefined {\n const parsed = combo ? parseCombo(combo) : null;\n if (!parsed) return undefined;\n\n const key = ARIA_KEY_NAMES[parsed.key] ?? capitalise(parsed.key);\n const modifiers = [parsed.ctrl && 'Control', parsed.alt && 'Alt', parsed.shift && 'Shift', parsed.meta && 'Meta'];\n return [...modifiers.filter(Boolean), key].join('+');\n}\n\n/**\n * Keyboard shortcuts, for a whole app or for one element.\n *\n * ```tsx\n * useHotkeys({ 'mod+k': () => setPaletteOpen(true), '?': () => setHelpOpen(true) });\n * ```\n *\n * The map is read through a ref at event time, so an inline object literal is fine and no handler\n * needs memoising. Shortcuts keep firing while a Modal or Drawer is open — pass `enabled` for the\n * ones that should not.\n */\nexport function useHotkeys(hotkeys: HotkeyMap, options: UseHotkeysOptions = {}): void {\n const { enabled = true, target, enableInFields = false, preventDefault = true, repeat = false } = options;\n\n const hotkeysRef = useRef(hotkeys);\n useEffect(() => {\n hotkeysRef.current = hotkeys;\n });\n\n useEffect(() => {\n if (!enabled) return;\n const node: HTMLElement | Window | null = target ? target.current : window;\n if (!node) return;\n\n function onKeyDown(event: Event) {\n const keyboardEvent = event as KeyboardEvent;\n // A key pressed to compose a character in an IME is not a shortcut.\n if (keyboardEvent.isComposing) return;\n\n for (const [spelling, handler] of Object.entries(hotkeysRef.current)) {\n const combo = parseCombo(spelling);\n if (!combo || !matches(combo, keyboardEvent)) continue;\n if (isFieldKey(combo) && !enableInFields && isInField(keyboardEvent.target)) continue;\n // Prevented on a skipped repeat too, or the second keydown of a held mod+s opens the\n // browser's save dialog.\n if (preventDefault) keyboardEvent.preventDefault();\n if (keyboardEvent.repeat && !repeat) return;\n handler(keyboardEvent);\n return;\n }\n }\n\n node.addEventListener('keydown', onKeyDown);\n return () => node.removeEventListener('keydown', onKeyDown);\n }, [enabled, target, enableInFields, preventDefault, repeat]);\n}\n\nexport default useHotkeys;\n"],"mappings":"2DAwCA,IAAM,EAAiB,0EAGjB,EAAsC,CAC1C,IAAK,SACL,MAAO,IACP,SAAU,IACV,KAAM,IACN,GAAI,UACJ,KAAM,YACN,KAAM,YACN,MAAO,YACT,EAGA,SAAS,GAA2B,CAClC,OAAO,OAAO,UAAc,KAAe,wBAAwB,KAAK,UAAU,SAAS,CAC7F,CAEA,SAAS,EAAW,EAA6B,CAC/C,IAAM,EAAQ,EACX,MAAM,GAAG,CAAC,CACV,IAAK,GAAS,EAAK,KAAK,CAAC,CAAC,YAAY,CAAC,CAAC,CACxC,OAAO,OAAO,EAGjB,GAAI,EAAM,SAAW,EAAG,OAAO,KAE/B,IAAM,EAAgB,CAAE,IAAK,GAAI,KAAM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B,GAAO,iBAAiB,GAAM,SAAS,IAAU,EAE5F,EAAa,EAAO,CAAO,EACjC,MAAgB,CACd,EAAW,QAAU,CACvB,CAAC,EAED,MAAgB,CACd,GAAI,CAAC,EAAS,OACd,IAAM,EAAoC,EAAS,EAAO,QAAU,OACpE,GAAI,CAAC,EAAM,OAEX,SAAS,EAAU,EAAc,CAC/B,IAAM,EAAgB,EAElB,MAAc,YAElB,IAAK,GAAM,CAAC,EAAU,KAAY,OAAO,QAAQ,EAAW,OAAO,EAAG,CACpE,IAAM,EAAQ,EAAW,CAAQ,EAC7B,GAAC,GAAU,EAAQ,EAAO,CAAa,GACvC,IAAW,CAAK,GAAK,CAAC,GAAkB,EAAU,EAAc,MAAM,GAI1E,IADI,GAAgB,EAAc,eAAe,EAC7C,EAAc,QAAU,CAAC,EAAQ,OACrC,EAAQ,CAAa,EACrB,MAFqC,CAGvC,CACF,CAGA,OADA,EAAK,iBAAiB,UAAW,CAAS,MAC7B,EAAK,oBAAoB,UAAW,CAAS,CAC5D,EAAG,CAAC,EAAS,EAAQ,EAAgB,EAAgB,CAAM,CAAC,CAC9D"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use client";import{useEffect as e,useRef as t,useState as n}from"react";function
|
|
1
|
+
"use client";import{useEffect as e,useRef as t,useState as n}from"react";var r=3e3;function i(i,a,o){let[s,c]=n(!1),l=t(!1),u=t(null),d=t(a);return e(()=>{d.current=a}),e(()=>{let e=i.current,t=u.current;if(o||!e||!t)return;let n=!1,a=0,s=()=>{p.unobserve(t),p.observe(t)},f=()=>{if(l.current)return;l.current=!0,c(!0);let e=e=>{l.current=!1,c(!1),!n&&(e?s():a=window.setTimeout(s,r))};d.current().then(()=>e(!0),()=>e(!1))},p=new IntersectionObserver(([e])=>{e.isIntersecting&&f()},{root:e});return p.observe(t),()=>{n=!0,window.clearTimeout(a),p.disconnect()}},[i,o]),{isLoading:s,sentinelRef:u}}export{i as useInfiniteScroll};
|
|
2
2
|
//# sourceMappingURL=useInfiniteScroll.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useInfiniteScroll.mjs","names":[],"sources":["../../../../package/common/infiniteBlock/useInfiniteScroll.ts"],"sourcesContent":["import { useEffect, useRef, useState } from 'react';\nimport type React from 'react';\n\n// Loads more items once a sentinel element at the end of the list scrolls into view.\n// IntersectionObserver only fires on a change of intersection state, so if a page of\n// freshly-loaded items still doesn't fill the container, the sentinel stays visible and\n// we have to re-arm the observer ourselves to pick up the next page.\nexport function useInfiniteScroll(\n containerRef: React.RefObject<HTMLDivElement | null>,\n onScroll: () => Promise<void>,\n disabled: boolean,\n) {\n const [isLoading, setIsLoading] = useState(false);\n const isLoadingRef = useRef(false);\n const sentinelRef = useRef<HTMLDivElement>(null);\n\n // Kept in a ref so a caller passing a fresh onScroll function each render doesn't\n // tear down and recreate the observer every time.\n const onScrollRef = useRef(onScroll);\n useEffect(() => {\n onScrollRef.current = onScroll;\n });\n\n useEffect(() => {\n const root = containerRef.current;\n const sentinel = sentinelRef.current;\n if (disabled || !root || !sentinel) return undefined;\n\n let cancelled = false;\n\n const loadMore = () => {\n if (isLoadingRef.current) return;\n isLoadingRef.current = true;\n setIsLoading(true);\n\n
|
|
1
|
+
{"version":3,"file":"useInfiniteScroll.mjs","names":[],"sources":["../../../../package/common/infiniteBlock/useInfiniteScroll.ts"],"sourcesContent":["import { useEffect, useRef, useState } from 'react';\nimport type React from 'react';\n\nconst RETRY_DELAY = 3000;\n\n// Loads more items once a sentinel element at the end of the list scrolls into view.\n// IntersectionObserver only fires on a change of intersection state, so if a page of\n// freshly-loaded items still doesn't fill the container, the sentinel stays visible and\n// we have to re-arm the observer ourselves to pick up the next page.\nexport function useInfiniteScroll(\n containerRef: React.RefObject<HTMLDivElement | null>,\n onScroll: () => Promise<void>,\n disabled: boolean,\n) {\n const [isLoading, setIsLoading] = useState(false);\n const isLoadingRef = useRef(false);\n const sentinelRef = useRef<HTMLDivElement>(null);\n\n // Kept in a ref so a caller passing a fresh onScroll function each render doesn't\n // tear down and recreate the observer every time.\n const onScrollRef = useRef(onScroll);\n useEffect(() => {\n onScrollRef.current = onScroll;\n });\n\n useEffect(() => {\n const root = containerRef.current;\n const sentinel = sentinelRef.current;\n if (disabled || !root || !sentinel) return undefined;\n\n let cancelled = false;\n let retry = 0;\n\n // Observing again reports the sentinel at once, for a page that still left it in view.\n const rearm = () => {\n observer.unobserve(sentinel);\n observer.observe(sentinel);\n };\n\n const loadMore = () => {\n if (isLoadingRef.current) return;\n isLoadingRef.current = true;\n setIsLoading(true);\n\n const settle = (succeeded: boolean) => {\n // Reset even once cancelled: a load can outlive its observer when the caller disables it\n // mid-request, and a flag left set would block every load after it.\n isLoadingRef.current = false;\n setIsLoading(false);\n if (cancelled) return;\n if (succeeded) rearm();\n // A failure waits before trying again, or it would retry without end while the sentinel\n // stays in view. It does try again: a list too short to scroll offers no other way.\n else retry = window.setTimeout(rearm, RETRY_DELAY);\n };\n\n onScrollRef.current().then(\n () => settle(true),\n () => settle(false),\n );\n };\n\n const observer = new IntersectionObserver(\n ([entry]) => {\n if (entry.isIntersecting) loadMore();\n },\n { root },\n );\n\n observer.observe(sentinel);\n\n return () => {\n cancelled = true;\n window.clearTimeout(retry);\n observer.disconnect();\n };\n }, [containerRef, disabled]);\n\n return { isLoading, sentinelRef };\n}\n"],"mappings":"yEAGA,IAAM,EAAc,IAMpB,SAAgB,EACd,EACA,EACA,EACA,CACA,GAAM,CAAC,EAAW,GAAgB,EAAS,EAAK,EAC1C,EAAe,EAAO,EAAK,EAC3B,EAAc,EAAuB,IAAI,EAIzC,EAAc,EAAO,CAAQ,EA0DnC,OAzDA,MAAgB,CACd,EAAY,QAAU,CACxB,CAAC,EAED,MAAgB,CACd,IAAM,EAAO,EAAa,QACpB,EAAW,EAAY,QAC7B,GAAI,GAAY,CAAC,GAAQ,CAAC,EAAU,OAEpC,IAAI,EAAY,GACZ,EAAQ,EAGN,MAAc,CAClB,EAAS,UAAU,CAAQ,EAC3B,EAAS,QAAQ,CAAQ,CAC3B,EAEM,MAAiB,CACrB,GAAI,EAAa,QAAS,OAC1B,EAAa,QAAU,GACvB,EAAa,EAAI,EAEjB,IAAM,EAAU,GAAuB,CAGrC,EAAa,QAAU,GACvB,EAAa,EAAK,EACd,KACA,EAAW,EAAM,EAGhB,EAAQ,OAAO,WAAW,EAAO,CAAW,EACnD,EAEA,EAAY,QAAQ,CAAC,CAAC,SACd,EAAO,EAAI,MACX,EAAO,EAAK,CACpB,CACF,EAEM,EAAW,IAAI,sBAClB,CAAC,KAAW,CACP,EAAM,gBAAgB,EAAS,CACrC,EACA,CAAE,MAAK,CACT,EAIA,OAFA,EAAS,QAAQ,CAAQ,MAEZ,CACX,EAAY,GACZ,OAAO,aAAa,CAAK,EACzB,EAAS,WAAW,CACtB,CACF,EAAG,CAAC,EAAc,CAAQ,CAAC,EAEpB,CAAE,YAAW,aAAY,CAClC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use client";import{useComponentDefaults as e}from"../configProvider/useComponentDefaults.mjs";import{useLabels as t}from"../configProvider/useLabels.mjs";import{mergeRefs as n}from"../utils/mergeRefs.mjs";import ee from"../tooltip/tooltip.mjs";import
|
|
1
|
+
"use client";import{useComponentDefaults as e}from"../configProvider/useComponentDefaults.mjs";import{useLabels as t}from"../configProvider/useLabels.mjs";import{mergeRefs as n}from"../utils/mergeRefs.mjs";import{useAutoGrow as ee}from"../hooks/useAutoGrow.mjs";import te from"../tooltip/tooltip.mjs";import ne from"../animatedIcon/animatedIcon.mjs";import r from"./input.module.mjs";import{InputIconPosition as i,InputType as a}from"./input.types.mjs";import re,{useEffect as ie,useId as ae,useRef as oe,useState as o}from"react";import s from"classnames";import{FontAwesomeIcon as c}from"@fortawesome/react-fontawesome";import{faEnvelope as l,faEye as se,faEyeSlash as ce,faPen as u,faPhone as le,faSearch as ue,faXmark as de}from"@fortawesome/free-solid-svg-icons";import{jsx as d,jsxs as f}from"react/jsx-runtime";var fe={clear:`Clear`,showPassword:`Show password`,hidePassword:`Hide password`,clearSearch:`Clear search`},pe={[a.Phone]:le,[a.Email]:l,[a.Edit]:u};function p(e){if(e)return{role:`button`,tabIndex:0,onMouseDown:e=>e.preventDefault(),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),e(t))}}}function m(l){let{name:u=``,id:le,label:m=``,errorMessage:me=``,isValid:he=!0,className:ge=``,style:_e,value:ve=``,icon:h=null,iconPosition:ye,onChange:g=()=>{},onFocus:_=null,onBlur:v=null,onMouseEnter:y=null,onMouseLeave:be=null,isUppercase:xe=!1,isRequired:Se=!1,tabIndex:Ce=0,type:b=void 0,isRow:we=!1,onIconClick:x=null,parse:S=null,formValidator:C=null,autoFocus:w=!1,suffix:T=null,upperRightLabel:E=null,labelInBorder:Te=!1,clearable:Ee=!1,onClear:De,min:Oe=null,max:ke=null,placeholder:D=``,useMatLabelStyle:O=!0,alwaysFloatLabel:Ae=!1,autoComplete:je=null,onClick:Me=()=>null,readOnly:k=!1,customInput:A,multiline:j=!1,rows:Ne,autoResize:M=!1,classNames:N,styles:P,disabled:F=!1,labels:Pe,ref:Fe,...I}=e(`Input`,l),L=t(`Input`,Pe,fe),[Ie,Le]=o(!1),[Re,ze]=o(!1),[Be,Ve]=o(!1),[R,He]=o(!1),[,Ue]=o(0),z=oe(null),B=oe(C),We=ae(),Ge=le||u||We,V=C?C.value:ve;ee(z,V,{enabled:M}),ie(()=>{w&&z.current&&setTimeout(()=>{z.current?.focus()},1)},[w]),ie(()=>{B.current=C;let e=B.current;if(!e)return;e.label=m??``,e.validate();let t=()=>Ue(e=>e+1);return e.registerOnUpdateListener(t),()=>{e.removeOnUpdateListener(t)}},[C,m]);let Ke=()=>C?C.touched&&C.hasError():!he||!!me,qe=()=>!!(Se||C&&C.validators.find(e=>e.validatorId===`required`)),Je=e=>{Ve(!0),y&&y(e)},Ye=e=>{Ve(!1),be&&be(e)},Xe=e=>{Le(!0),_&&_(e)},Ze=e=>{B.current&&(B.current.touched=!0),Le(!1),v&&v(e)},Qe=e=>{let t,n;typeof e==`string`?n=e:(t=e,n=e.target.value),S&&(n=S(n)),C&&C.set(n),g&&g(n,t)},$e=()=>{if(b!==a.Email)return b===a.Phone?`tel`:b===a.Search?`search`:b===`password`&&R?`text`:b},et=()=>{if(b===a.Email)return`email`;if(b===a.Phone)return`tel`;if(b===a.Search)return`search`},tt=b===a.Search||b===a.Password,nt=!!h,rt=nt&&!tt,it=b===a.Email||b===a.Phone||b===a.Search,H=(ye??(!O&&it?i.Left:i.Right))===i.Left,at={className:s(r.inputFieldIcon,{[r.inputFieldIconNotClickable]:!x,[r.inputFieldIconLeft]:H}),onClick:x??void 0,...p(x)},ot=b&&!nt?pe[b]:void 0,U=h,W=x??U?.props.onClick,st=rt&&U?re.cloneElement(U,{className:s(r.inputFieldIcon,{[r.inputFieldIconNotClickable]:!W,[r.inputFieldIconLeft]:H},U.props.className),onClick:W,...p(W)}):null,G=Ke(),K=m;K&&qe()&&(K=`${K} *`);let ct=qe()?d(`span`,{className:r.requiredMark,children:`*`}):null,q=Ie&&!k,J=O&&(Ae||q||V||Re||b===a.Date),lt=e=>{let{animationName:t}=e;if(t===r.inputAutofillStart){ze(!0);let t=e.currentTarget.value;t&&t!==String(V??``)&&Qe(t);return}if(t===r.inputAutofillEnd){ze(!1);return}I.onAnimationStart?.(e)},Y=!!V&&!F&&!k,X=b===a.Search&&Y;function ut(){He(!R)}let Z=st;b===a.Search?Z=d(ne,{icon:X?de:ue,className:s(r.inputFieldIcon,{[r.inputFieldIconNotClickable]:!X,[r.inputFieldIconLeft]:H}),onClick:X?$:void 0,...p(X?$:void 0),"aria-label":X?L.clearSearch:void 0}):b===a.Password?Z=d(c,{icon:R?ce:se,className:s(r.inputFieldIcon,{[r.inputFieldIconLeft]:H}),onClick:ut,...p(ut),"aria-label":R?L.hidePassword:L.showPassword}):ot&&(Z=d(c,{icon:ot,...at}));let dt=!!Z&&H,Q=A?.props;function $(){C&&C.set(``),g?.(``),De?.(),z.current?.focus()}return d(`div`,{className:s(r.input,{[r.inputIconLeft]:dt,[r.inputWithLabel]:O&&!!m},ge),style:_e,children:f(`label`,{htmlFor:Ge,className:s(r.inputLabel,N?.label,{[r.inputLabelColumn]:!we,[r.inputLabelInBorder]:Te}),style:P?.label,children:[m&&!O?f(`span`,{className:r.inputLabelText,children:[m,ct]}):null,E&&d(`div`,{className:s(r.inputUpperRightLabel,N?.upperRightLabel),style:P?.upperRightLabel,children:E}),f(`div`,{className:s(r.inputContainer,{[r.inputContainerMultiline]:j,[r.inputContainerResizable]:j&&!M,[r.inputContainerDisabled]:F},N?.container),style:P?.container,onMouseEnter:Je,onMouseLeave:Ye,children:[H&&Z,re.cloneElement(A||d(j?`textarea`:`input`,{}),{...I,className:s(r.inputField,{[r.inputFieldUppercase]:xe,[r.inputFieldDate]:b===a.Date,[r.inputFieldDefault]:b!==a.Date,[r.inputFieldWithIconLeft]:dt,[r.inputFieldMultiline]:j,[r.inputFieldMultilineAutoResize]:j&&M,[r.inputFieldReadOnly]:k&&!F},N?.input,Q?.className),style:Q?.style||P?.input?{...Q?.style,...P?.input}:void 0,name:u,id:Ge,value:V,tabIndex:Ce,ref:A?void 0:n(z,Fe),onChange:Qe,onAnimationStart:lt,onFocus:Xe,onBlur:Ze,placeholder:O?``:D,autoComplete:je,onClick:Me,readOnly:k,disabled:F,...!j&&{type:$e(),inputMode:I.inputMode??et(),min:Oe,max:ke},...j&&Ne!==void 0&&{rows:Ne}}),T&&d(`div`,{className:s(r.inputFieldSuffix,N?.suffix),style:P?.suffix,children:T}),Ee&&b!==a.Search&&d(c,{icon:de,className:s(r.inputFieldIcon,r.inputFieldIconClear,{[r.inputFieldIconClearHidden]:!Y}),onClick:Y?$:void 0,...p(Y?$:void 0),"aria-label":L.clear}),!H&&Z]}),d(`fieldset`,{className:s(r.inputFieldset,N?.fieldset,{[r.inputContainerBorderFocused]:q,[r.inputContainerBorderSearchFocused]:b===a.Search&&(q||!!V),[r.inputContainerBorderInvalid]:G,[r.inputContainerBorderError]:G}),style:P?.fieldset,children:d(`legend`,{className:s(r.inputFieldsetLegend,{[r.inputFieldsetLegendActive]:J}),children:d(`span`,{children:K})})}),O&&m&&f(`div`,{className:s(r.inputMatLabel,{[r.inputMatLabelFloating]:J,[r.inputMatLabelMultiline]:j&&!J}),children:[m,ct]}),O&&D&&d(`div`,{className:s(r.inputPlaceholder,q&&!V&&!Re&&r.inputPlaceholderShown,j&&r.inputPlaceholderMultiline),children:D}),d(te,{variant:`error`,message:C?C.getCurrentErrorMessage():me||``,isVisible:G&&(Ie||Be)})]})})}export{m as default};
|
|
2
2
|
//# sourceMappingURL=input.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"input.mjs","names":[],"sources":["../../../../package/common/input/input.tsx"],"sourcesContent":["import React, { useState, useEffect, useRef, useCallback, 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 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 const didSetAutoHeightRef = useRef(false);\n\n const resizeTextarea = useCallback(() => {\n const el = inputRef.current;\n if (!el) return;\n if (!autoResize) {\n // Only undo a height this set, so an explicit one from `styles.input` survives.\n if (didSetAutoHeightRef.current) {\n el.style.height = '';\n didSetAutoHeightRef.current = false;\n }\n return;\n }\n el.style.height = 'auto';\n el.style.height = `${el.scrollHeight}px`;\n didSetAutoHeightRef.current = true;\n }, [autoResize]);\n\n // `currVal` is a dependency because the value can change without passing through\n // `onChangeHandler`: the clear button, a parent resetting it, or `formValidator.set` elsewhere.\n useEffect(() => {\n resizeTextarea();\n }, [resizeTextarea, currVal]);\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 resizeTextarea();\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":"0wBAqBA,IAAM,GAAwC,CAC5C,MAAO,QACP,aAAc,gBACd,aAAc,gBACd,YAAa,cACf,EAEM,GAAyD,EAC5D,EAAU,OAAQ,GAClB,EAAU,OAAQ,IAClB,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,GAAmB,CAChC,GAAM,CACJ,OAAO,GACP,KACA,QAAQ,GACR,eAAe,GACf,WAAU,GACV,aAAY,GACZ,SACA,SAAQ,GACR,QAAO,KACP,gBACA,eAAiB,CAAC,EAClB,QAAS,GAAc,KACvB,OAAQ,GAAa,KACrB,aAAc,GAAmB,KACjC,aAAc,GAAmB,KACjC,eAAc,GACd,cAAa,GACb,YAAW,EACX,OAAO,IAAA,GACP,SAAQ,GACR,cAAc,KACd,SAAQ,KACR,gBAAgB,KAChB,aAAY,GACZ,SAAS,KACT,kBAAkB,KAClB,iBAAgB,GAChB,aAAY,GACZ,WACA,OAAM,KACN,OAAM,KACN,cAAc,GACd,mBAAmB,GACnB,oBAAmB,GACnB,gBAAe,KACf,eAAgB,KAChB,WAAW,GACX,cACA,YAAY,GACZ,OACA,aAAa,GACb,aACA,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F,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,CACE,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,GAAgB,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.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,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,aAAc,EAAmB,KACjC,aAAc,GAAmB,KACjC,eAAc,GACd,cAAa,GACb,YAAW,EACX,OAAO,IAAA,GACP,SAAQ,GACR,cAAc,KACd,QAAQ,KACR,gBAAgB,KAChB,YAAY,GACZ,SAAS,KACT,kBAAkB,KAClB,iBAAgB,GAChB,aAAY,GACZ,WACA,OAAM,KACN,OAAM,KACN,cAAc,GACd,mBAAmB,GACnB,oBAAmB,GACnB,gBAAe,KACf,eAAgB,KAChB,WAAW,GACX,cACA,YAAY,GACZ,QACA,aAAa,GACb,aACA,OAAQ,EACR,WAAW,GACX,UACA,OACA,GAAG,GACD,EAAqB,QAAS,CAAK,EACjC,EAAO,EAAU,QAAS,GAAQ,EAAc,EAChD,CAAC,GAAW,IAAgB,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AO,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{isSelfActivation as e}from"../utils/activationKey.mjs";import{
|
|
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};
|
|
2
2
|
//# sourceMappingURL=menu.mjs.map
|