@pega/cosmos-react-core 4.0.1 → 4.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/components/AIButton/AIButton.d.ts +1 -1
- package/lib/components/ComboBox/MultiSelectInput/MultiSelectInput.d.ts.map +1 -1
- package/lib/components/ComboBox/MultiSelectInput/MultiSelectInput.js +1 -0
- package/lib/components/ComboBox/MultiSelectInput/MultiSelectInput.js.map +1 -1
- package/lib/components/Configuration/Configuration.d.ts +17 -9
- package/lib/components/Configuration/Configuration.d.ts.map +1 -1
- package/lib/components/Configuration/Configuration.js +46 -26
- package/lib/components/Configuration/Configuration.js.map +1 -1
- package/lib/components/DangerButton/DangerButton.d.ts +1 -1
- package/lib/components/DangerButton/DangerButton.d.ts.map +1 -1
- package/lib/components/DateTime/utils.d.ts +2 -1
- package/lib/components/DateTime/utils.d.ts.map +1 -1
- package/lib/components/DateTime/utils.js +5 -4
- package/lib/components/DateTime/utils.js.map +1 -1
- package/lib/components/Drawer/Drawer.js +1 -1
- package/lib/components/Drawer/Drawer.js.map +1 -1
- package/lib/components/File/FileInput.d.ts.map +1 -1
- package/lib/components/File/FileInput.js +3 -2
- package/lib/components/File/FileInput.js.map +1 -1
- package/lib/components/ListToolbar/ListToolbar.styles.d.ts +1 -1
- package/lib/components/ListToolbar/ListToolbar.styles.d.ts.map +1 -1
- package/lib/hooks/useActiveDescendant.d.ts +1 -1
- package/lib/hooks/useActiveDescendant.js.map +1 -1
- package/package.json +3 -3
|
@@ -4,6 +4,6 @@ export interface AIButtonProps extends NoChildrenProp, OmitStrict<Attributes<'bu
|
|
|
4
4
|
label: string;
|
|
5
5
|
}
|
|
6
6
|
export declare const StyledAIButton: import("styled-components").StyledComponent<import("react").FunctionComponent<import("../Button").ButtonProps & import("../../types").ForwardProps>, import("styled-components").DefaultTheme, {}, never>;
|
|
7
|
-
declare const _default: import("react").ForwardRefExoticComponent<
|
|
7
|
+
declare const _default: import("react").ForwardRefExoticComponent<Omit<AIButtonProps, "ref"> & import("react").RefAttributes<HTMLButtonElement>>;
|
|
8
8
|
export default _default;
|
|
9
9
|
//# sourceMappingURL=AIButton.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MultiSelectInput.d.ts","sourceRoot":"","sources":["../../../../src/components/ComboBox/MultiSelectInput/MultiSelectInput.tsx"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EAWlB,MAAM,OAAO,CAAC;AAIf,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAiB9C,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AAEjE,eAAO,MAAM,sBAAsB,yGA4BjC,CAAC;AAIH,QAAA,MAAM,gBAAgB,EAAE,iBAAiB,CAAC,qBAAqB,GAAG,YAAY,
|
|
1
|
+
{"version":3,"file":"MultiSelectInput.d.ts","sourceRoot":"","sources":["../../../../src/components/ComboBox/MultiSelectInput/MultiSelectInput.tsx"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EAWlB,MAAM,OAAO,CAAC;AAIf,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAiB9C,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AAEjE,eAAO,MAAM,sBAAsB,yGA4BjC,CAAC;AAIH,QAAA,MAAM,gBAAgB,EAAE,iBAAiB,CAAC,qBAAqB,GAAG,YAAY,CAmO7E,CAAC;AAEF,eAAe,gBAAgB,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MultiSelectInput.js","sourceRoot":"","sources":["../../../../src/components/ComboBox/MultiSelectInput/MultiSelectInput.tsx"],"names":[],"mappings":";AAAA,OAAO,EAEL,UAAU,EAIV,MAAM,EACN,WAAW,EACX,OAAO,EACP,QAAQ,EACR,SAAS,EAEV,MAAM,OAAO,CAAC;AACf,OAAO,MAAM,EAAE,EAAE,GAAG,EAAE,M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AS,EAAE,cAAc,EACzB,QAAQ,EAAE,QAAQ,IAAI,CAAC,QAAQ,EAC/B,QAAQ,EAAE,QAAQ,EAClB,WAAW,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW,EACvD,YAAY,EAAC,KAAK,EAClB,SAAS,EAAE,SAAS,mBACL,CAAC,yBAAyB,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,YAAY,KACzD,SAAS,EACb,QAAQ,EAAE,SAAS,GACnB,IACG,EACN,OAAO,EAER,KAAC,kBAAkB,IAAC,EAAE,EAAE,GAAG,EAAE,mBAAmB,YAC7C,GAAG,CAAC,CAAC,qBAAqB,CAAC,GAAG,GACZ,EACrB,KAAC,kBAAkB,IAAC,EAAE,EAAE,GAAG,EAAE,oBAAoB,YAC9C,CAAC,CAAC,8BAA8B,CAAC,GACf,IAChB,CACR,CAAC;AACJ,CAAC,CACF,CAAC;AAEF,eAAe,gBAAgB,CAAC","sourcesContent":["import {\n FunctionComponent,\n forwardRef,\n Ref,\n PropsWithoutRef,\n KeyboardEvent,\n useRef,\n useCallback,\n useMemo,\n useState,\n useEffect,\n MouseEvent\n} from 'react';\nimport styled, { css } from 'styled-components';\nimport { transparentize } from 'polished';\n\nimport { ForwardProps } from '../../../types';\nimport { defaultThemeProp } from '../../../theme';\nimport Selectable, { StyledSelectable } from '../../Badges/Selection';\nimport { StyledFormControl } from '../../FormControl';\nimport Flex from '../../Flex';\nimport {\n useConsolidatedRef,\n useActiveDescendant,\n useDirection,\n useI18n,\n useUID\n} from '../../../hooks';\nimport { cap, tryCatch } from '../../../utils';\nimport { StyledBareButton } from '../../Button/BareButton';\nimport VisuallyHiddenText from '../../VisuallyHiddenText';\nimport { StyledSelectInput } from '../ComboBox.styles';\n\nimport { MultiSelectInputProps } from './MultiSelectInput.types';\n\nexport const StyledMultiSelectInput = styled(StyledSelectInput)(({ theme }) => {\n const { background } = theme.components.badges.selectable.base;\n const { 'foreground-color': foreground } = theme.base.palette;\n const boxShadowColor = tryCatch(() => transparentize(0.45, foreground));\n\n return css`\n cursor: text;\n\n ul {\n list-style: none;\n display: contents;\n\n &[data-active-scope='true'] ${StyledSelectable}[data-current='true'] {\n color: ${theme.base.palette.interactive};\n box-shadow: 0 0 0.5rem -0.125rem ${boxShadowColor}, inset 0 0 0 0.125rem ${background};\n outline: none;\n\n ${StyledBareButton} {\n color: ${theme.base.palette.interactive};\n }\n }\n }\n\n input {\n width: 8ch;\n height: 1.125rem;\n }\n `;\n});\n\nStyledMultiSelectInput.defaultProps = defaultThemeProp;\n\nconst MultiSelectInput: FunctionComponent<MultiSelectInputProps & ForwardProps> = forwardRef(\n function MultiSelectInput(\n props: PropsWithoutRef<MultiSelectInputProps>,\n ref: Ref<HTMLInputElement>\n ) {\n const {\n selected = [],\n value,\n onRemove,\n onChange,\n onKeyDown,\n onResolveSuggestion,\n actions,\n readOnly,\n disabled,\n status,\n placeholder,\n autoFocus,\n pauseDescendantEvaluation,\n onSelectedFocus,\n onSelectedBlur,\n 'aria-controls': ariaControls,\n ...restProps\n } = props;\n const t = useI18n();\n const id = useUID();\n\n const inputRef = useConsolidatedRef<HTMLInputElement>(ref);\n const listRef = useRef<HTMLUListElement>(null);\n const [focusDescendant, setFocusDescendant] = useState<HTMLElement | null>(null);\n const [activeItemId, setActiveItemId] = useState<string | null>(null);\n const { start, end } = useDirection();\n\n const uadConfig = useMemo(\n () => ({\n focusEl: inputRef.current,\n scope: listRef.current,\n selector: 'li[role=\"option\"]',\n orientation: 'horizontal' as const,\n focusReturnEl: focusDescendant,\n clearFocusReturn: () => {\n setFocusDescendant(null);\n },\n pauseDescendantEvaluation,\n onClick: (el: HTMLElement) => {\n el.click();\n }\n }),\n [pauseDescendantEvaluation, selected, focusDescendant]\n );\n\n const { activeDescendant } = useActiveDescendant(uadConfig, [selected]);\n\n const handleSelectedRemoval = useCallback(\n (selectionId, idx) => {\n if (!pauseDescendantEvaluation) {\n if (idx === selected.length - 1) {\n // If removing last selected item\n if (selected.length > 1) {\n // If other selected items, focus previous\n setFocusDescendant(\n (listRef.current?.querySelectorAll(uadConfig.selector)[idx - 1] as HTMLElement) ||\n null\n );\n } else {\n // Blur selected if final only item removed\n onSelectedBlur?.();\n }\n } else if (selected.length > 1) {\n // If not last item removed and other selected items, focus next\n setFocusDescendant(\n (listRef.current?.querySelectorAll(uadConfig.selector)[idx + 1] as HTMLElement) ||\n null\n );\n }\n }\n onRemove?.(selectionId, idx);\n inputRef.current?.focus();\n },\n [selected, onRemove, onSelectedBlur, uadConfig]\n );\n\n useEffect(() => {\n // Maintain active item & prev. val only as it changes.\n if (activeDescendant?.id && activeDescendant.id !== activeItemId) {\n setActiveItemId(activeDescendant.id);\n }\n }, [activeDescendant]);\n\n const onInputKeyDown = useCallback(\n (e: KeyboardEvent<HTMLInputElement>) => {\n if (selected.length && inputRef.current?.selectionStart === 0) {\n const lastIndex = selected.length - 1;\n if (pauseDescendantEvaluation && e.key === `Arrow${cap(start)}`) {\n setFocusDescendant(\n (listRef.current?.querySelectorAll(uadConfig.selector)[lastIndex] as HTMLElement) ||\n null\n );\n onSelectedFocus?.();\n }\n\n const lastSelectableId = listRef.current?.querySelectorAll(uadConfig.selector)[lastIndex]\n ?.id;\n const onLastItem = activeItemId === lastSelectableId;\n\n if (\n !pauseDescendantEvaluation &&\n ((onLastItem && e.key === `Arrow${cap(end)}`) || e.key === 'ArrowDown')\n ) {\n onSelectedBlur?.();\n }\n\n if (['Backspace', 'Delete'].includes(e.key) && !(readOnly || disabled)) {\n handleSelectedRemoval(selected[lastIndex].id, lastIndex);\n }\n }\n onKeyDown?.(e);\n },\n [\n pauseDescendantEvaluation,\n activeItemId,\n onKeyDown,\n handleSelectedRemoval,\n selected,\n readOnly,\n disabled\n ]\n );\n\n const ariaDescribedBy = useMemo(() => {\n return onChange\n ? `${id}-inputDescription ${id}-searchDescription`\n : `${id}-inputDescription`;\n }, [id]);\n\n return (\n <Flex\n as={StyledMultiSelectInput}\n forwardedAs={StyledFormControl}\n hasSuggestion={status === 'pending' && !!onResolveSuggestion}\n container={{ alignItems: 'center', justify: 'between' }}\n {...{\n readOnly,\n disabled,\n status\n }}\n >\n <Flex\n container={{ alignContent: 'center', wrap: 'wrap', rowGap: 0.5, colGap: 0.25, pad: 0.25 }}\n item={{ grow: 1 }}\n onClick={(e: MouseEvent<HTMLDivElement>) => {\n if (\n e.target instanceof HTMLElement &&\n !e.currentTarget.contains(e.target.closest('li'))\n ) {\n inputRef.current?.focus();\n inputRef.current?.click();\n }\n }}\n >\n {selected.length > 0 && (\n <ul ref={listRef} id={id} role='listbox' aria-label={t('selected_items')}>\n {selected.map((element, idx) => {\n return (\n <Selectable\n as='li'\n key={element.id}\n role='option'\n id={element.id.toString()}\n status={status}\n onClick={e => {\n const mouseClick = e.detail !== 0;\n\n if (!readOnly && !disabled && !mouseClick) {\n handleSelectedRemoval(element.id, idx);\n }\n }}\n onRemove={() => {\n if (!readOnly && !disabled) {\n handleSelectedRemoval(element.id, idx);\n }\n }}\n onKeyDown={(e: KeyboardEvent<Element>) => {\n // prevent browser's Back on FF\n if (e.key === 'Backspace') e.preventDefault();\n }}\n tabIndex='-1'\n aria-label={`${t('remove')} ${element.text}`}\n aria-describedby={ariaDescribedBy}\n >\n {element.text}\n </Selectable>\n );\n })}\n </ul>\n )}\n <Flex\n item={{ grow: 1 }}\n as='input'\n size={1}\n ref={inputRef}\n value={value}\n // no-op avoids react uncontrolled warning\n onChange={onChange || (() => {})}\n onKeyDown={onInputKeyDown}\n readOnly={readOnly || !onChange}\n disabled={disabled}\n placeholder={selected?.length ? undefined : placeholder}\n autoComplete='off'\n autoFocus={autoFocus}\n aria-controls={!pauseDescendantEvaluation ? id : ariaControls}\n {...restProps}\n required={undefined}\n />\n </Flex>\n {actions}\n\n <VisuallyHiddenText id={`${id}-inputDescription`}>\n {`${t('combobox_open_close')} `}\n </VisuallyHiddenText>\n <VisuallyHiddenText id={`${id}-searchDescription`}>\n {t('combobox_search_instructions')}\n </VisuallyHiddenText>\n </Flex>\n );\n }\n);\n\nexport default MultiSelectInput;\n"]}
|
|
1
|
+
{"version":3,"file":"MultiSelectInput.js","sourceRoot":"","sources":["../../../../src/components/ComboBox/MultiSelectInput/MultiSelectInput.tsx"],"names":[],"mappings":";AAAA,OAAO,EAEL,UAAU,EAIV,MAAM,EACN,WAAW,EACX,OAAO,EACP,QAAQ,EACR,SAAS,EAEV,MAAM,OAAO,CAAC;AACf,OAAO,MAAM,EAAE,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAG1C,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,UAAU,EAAE,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AACtE,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,IAAI,MAAM,YAAY,CAAC;AAC9B,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,YAAY,EACZ,OAAO,EACP,MAAM,EACP,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC/C,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,kBAAkB,MAAM,0BAA0B,CAAC;AAC1D,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAIvD,MAAM,CAAC,MAAM,sBAAsB,GAAG,MAAM,CAAC,iBAAiB,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE;IAC5E,MAAM,EAAE,UAAU,EAAE,GAAG,KAAK,CAAC,UAAU,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC;IAC/D,MAAM,EAAE,kBAAkB,EAAE,UAAU,EAAE,GAAG,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC;IAC9D,MAAM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AC1B,eAAe,YAEhC,OAAO,CAAC,IAAI,IAxBR,OAAO,CAAC,EAAE,CAyBJ,CACd,CAAC;wBACJ,CAAC,CAAC,GACC,CACN,EACD,KAAC,IAAI,IACH,IAAI,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,EACjB,EAAE,EAAC,OAAO,EACV,IAAI,EAAE,CAAC,EACP,GAAG,EAAE,QAAQ,EACb,KAAK,EAAE,KAAK;wBACZ,0CAA0C;wBAC1C,QAAQ,EAAE,QAAQ,IAAI,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,EAChC,SAAS,EAAE,cAAc,EACzB,QAAQ,EAAE,QAAQ,IAAI,CAAC,QAAQ,EAC/B,QAAQ,EAAE,QAAQ,EAClB,WAAW,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW,EACvD,YAAY,EAAC,KAAK,EAClB,SAAS,EAAE,SAAS,mBACL,CAAC,yBAAyB,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,YAAY,KACzD,SAAS,EACb,QAAQ,EAAE,SAAS,GACnB,IACG,EACN,OAAO,EAER,KAAC,kBAAkB,IAAC,EAAE,EAAE,GAAG,EAAE,mBAAmB,YAC7C,GAAG,CAAC,CAAC,qBAAqB,CAAC,GAAG,GACZ,EACrB,KAAC,kBAAkB,IAAC,EAAE,EAAE,GAAG,EAAE,oBAAoB,YAC9C,CAAC,CAAC,8BAA8B,CAAC,GACf,IAChB,CACR,CAAC;AACJ,CAAC,CACF,CAAC;AAEF,eAAe,gBAAgB,CAAC","sourcesContent":["import {\n FunctionComponent,\n forwardRef,\n Ref,\n PropsWithoutRef,\n KeyboardEvent,\n useRef,\n useCallback,\n useMemo,\n useState,\n useEffect,\n MouseEvent\n} from 'react';\nimport styled, { css } from 'styled-components';\nimport { transparentize } from 'polished';\n\nimport { ForwardProps } from '../../../types';\nimport { defaultThemeProp } from '../../../theme';\nimport Selectable, { StyledSelectable } from '../../Badges/Selection';\nimport { StyledFormControl } from '../../FormControl';\nimport Flex from '../../Flex';\nimport {\n useConsolidatedRef,\n useActiveDescendant,\n useDirection,\n useI18n,\n useUID\n} from '../../../hooks';\nimport { cap, tryCatch } from '../../../utils';\nimport { StyledBareButton } from '../../Button/BareButton';\nimport VisuallyHiddenText from '../../VisuallyHiddenText';\nimport { StyledSelectInput } from '../ComboBox.styles';\n\nimport { MultiSelectInputProps } from './MultiSelectInput.types';\n\nexport const StyledMultiSelectInput = styled(StyledSelectInput)(({ theme }) => {\n const { background } = theme.components.badges.selectable.base;\n const { 'foreground-color': foreground } = theme.base.palette;\n const boxShadowColor = tryCatch(() => transparentize(0.45, foreground));\n\n return css`\n cursor: text;\n\n ul {\n list-style: none;\n display: contents;\n\n &[data-active-scope='true'] ${StyledSelectable}[data-current='true'] {\n color: ${theme.base.palette.interactive};\n box-shadow: 0 0 0.5rem -0.125rem ${boxShadowColor}, inset 0 0 0 0.125rem ${background};\n outline: none;\n\n ${StyledBareButton} {\n color: ${theme.base.palette.interactive};\n }\n }\n }\n\n input {\n width: 8ch;\n height: 1.125rem;\n }\n `;\n});\n\nStyledMultiSelectInput.defaultProps = defaultThemeProp;\n\nconst MultiSelectInput: FunctionComponent<MultiSelectInputProps & ForwardProps> = forwardRef(\n function MultiSelectInput(\n props: PropsWithoutRef<MultiSelectInputProps>,\n ref: Ref<HTMLInputElement>\n ) {\n const {\n selected = [],\n value,\n onRemove,\n onChange,\n onKeyDown,\n onResolveSuggestion,\n actions,\n readOnly,\n disabled,\n status,\n placeholder,\n autoFocus,\n pauseDescendantEvaluation,\n onSelectedFocus,\n onSelectedBlur,\n 'aria-controls': ariaControls,\n ...restProps\n } = props;\n const t = useI18n();\n const id = useUID();\n\n const inputRef = useConsolidatedRef<HTMLInputElement>(ref);\n const listRef = useRef<HTMLUListElement>(null);\n const [focusDescendant, setFocusDescendant] = useState<HTMLElement | null>(null);\n const [activeItemId, setActiveItemId] = useState<string | null>(null);\n const { start, end } = useDirection();\n\n const uadConfig = useMemo(\n () => ({\n focusEl: inputRef.current,\n scope: listRef.current,\n selector: 'li[role=\"option\"]',\n orientation: 'horizontal' as const,\n focusReturnEl: focusDescendant,\n clearFocusReturn: () => {\n setFocusDescendant(null);\n },\n pauseDescendantEvaluation,\n preventInitialScroll: true,\n onClick: (el: HTMLElement) => {\n el.click();\n }\n }),\n [pauseDescendantEvaluation, selected, focusDescendant]\n );\n\n const { activeDescendant } = useActiveDescendant(uadConfig, [selected]);\n\n const handleSelectedRemoval = useCallback(\n (selectionId, idx) => {\n if (!pauseDescendantEvaluation) {\n if (idx === selected.length - 1) {\n // If removing last selected item\n if (selected.length > 1) {\n // If other selected items, focus previous\n setFocusDescendant(\n (listRef.current?.querySelectorAll(uadConfig.selector)[idx - 1] as HTMLElement) ||\n null\n );\n } else {\n // Blur selected if final only item removed\n onSelectedBlur?.();\n }\n } else if (selected.length > 1) {\n // If not last item removed and other selected items, focus next\n setFocusDescendant(\n (listRef.current?.querySelectorAll(uadConfig.selector)[idx + 1] as HTMLElement) ||\n null\n );\n }\n }\n onRemove?.(selectionId, idx);\n inputRef.current?.focus();\n },\n [selected, onRemove, onSelectedBlur, uadConfig]\n );\n\n useEffect(() => {\n // Maintain active item & prev. val only as it changes.\n if (activeDescendant?.id && activeDescendant.id !== activeItemId) {\n setActiveItemId(activeDescendant.id);\n }\n }, [activeDescendant]);\n\n const onInputKeyDown = useCallback(\n (e: KeyboardEvent<HTMLInputElement>) => {\n if (selected.length && inputRef.current?.selectionStart === 0) {\n const lastIndex = selected.length - 1;\n if (pauseDescendantEvaluation && e.key === `Arrow${cap(start)}`) {\n setFocusDescendant(\n (listRef.current?.querySelectorAll(uadConfig.selector)[lastIndex] as HTMLElement) ||\n null\n );\n onSelectedFocus?.();\n }\n\n const lastSelectableId = listRef.current?.querySelectorAll(uadConfig.selector)[lastIndex]\n ?.id;\n const onLastItem = activeItemId === lastSelectableId;\n\n if (\n !pauseDescendantEvaluation &&\n ((onLastItem && e.key === `Arrow${cap(end)}`) || e.key === 'ArrowDown')\n ) {\n onSelectedBlur?.();\n }\n\n if (['Backspace', 'Delete'].includes(e.key) && !(readOnly || disabled)) {\n handleSelectedRemoval(selected[lastIndex].id, lastIndex);\n }\n }\n onKeyDown?.(e);\n },\n [\n pauseDescendantEvaluation,\n activeItemId,\n onKeyDown,\n handleSelectedRemoval,\n selected,\n readOnly,\n disabled\n ]\n );\n\n const ariaDescribedBy = useMemo(() => {\n return onChange\n ? `${id}-inputDescription ${id}-searchDescription`\n : `${id}-inputDescription`;\n }, [id]);\n\n return (\n <Flex\n as={StyledMultiSelectInput}\n forwardedAs={StyledFormControl}\n hasSuggestion={status === 'pending' && !!onResolveSuggestion}\n container={{ alignItems: 'center', justify: 'between' }}\n {...{\n readOnly,\n disabled,\n status\n }}\n >\n <Flex\n container={{ alignContent: 'center', wrap: 'wrap', rowGap: 0.5, colGap: 0.25, pad: 0.25 }}\n item={{ grow: 1 }}\n onClick={(e: MouseEvent<HTMLDivElement>) => {\n if (\n e.target instanceof HTMLElement &&\n !e.currentTarget.contains(e.target.closest('li'))\n ) {\n inputRef.current?.focus();\n inputRef.current?.click();\n }\n }}\n >\n {selected.length > 0 && (\n <ul ref={listRef} id={id} role='listbox' aria-label={t('selected_items')}>\n {selected.map((element, idx) => {\n return (\n <Selectable\n as='li'\n key={element.id}\n role='option'\n id={element.id.toString()}\n status={status}\n onClick={e => {\n const mouseClick = e.detail !== 0;\n\n if (!readOnly && !disabled && !mouseClick) {\n handleSelectedRemoval(element.id, idx);\n }\n }}\n onRemove={() => {\n if (!readOnly && !disabled) {\n handleSelectedRemoval(element.id, idx);\n }\n }}\n onKeyDown={(e: KeyboardEvent<Element>) => {\n // prevent browser's Back on FF\n if (e.key === 'Backspace') e.preventDefault();\n }}\n tabIndex='-1'\n aria-label={`${t('remove')} ${element.text}`}\n aria-describedby={ariaDescribedBy}\n >\n {element.text}\n </Selectable>\n );\n })}\n </ul>\n )}\n <Flex\n item={{ grow: 1 }}\n as='input'\n size={1}\n ref={inputRef}\n value={value}\n // no-op avoids react uncontrolled warning\n onChange={onChange || (() => {})}\n onKeyDown={onInputKeyDown}\n readOnly={readOnly || !onChange}\n disabled={disabled}\n placeholder={selected?.length ? undefined : placeholder}\n autoComplete='off'\n autoFocus={autoFocus}\n aria-controls={!pauseDescendantEvaluation ? id : ariaControls}\n {...restProps}\n required={undefined}\n />\n </Flex>\n {actions}\n\n <VisuallyHiddenText id={`${id}-inputDescription`}>\n {`${t('combobox_open_close')} `}\n </VisuallyHiddenText>\n <VisuallyHiddenText id={`${id}-searchDescription`}>\n {t('combobox_search_instructions')}\n </VisuallyHiddenText>\n </Flex>\n );\n }\n);\n\nexport default MultiSelectInput;\n"]}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { FunctionComponent, ReactNode, Context, MutableRefObject } from 'react';
|
|
2
|
+
import { createPortal } from 'react-dom';
|
|
3
|
+
import type { StyleSheetManagerProps } from 'styled-components';
|
|
4
|
+
import '../../init';
|
|
2
5
|
import { ThemeMachineLike, DefaultSettableTheme, DefaultThemeDefinition } from '../../theme';
|
|
3
6
|
import { Translation, TranslationPack } from '../../i18n';
|
|
4
|
-
import '../../init';
|
|
5
7
|
export interface ConfigurationProps {
|
|
6
8
|
/** Any components or nodes that should be impacted by the settings applied by this Configuration component. */
|
|
7
9
|
children: ReactNode;
|
|
@@ -15,10 +17,16 @@ export interface ConfigurationProps {
|
|
|
15
17
|
theme?: DefaultSettableTheme;
|
|
16
18
|
/** Disables loading Open Sans or Inter from Google Fonts. Only takes effect on the root configuration. */
|
|
17
19
|
disableDefaultFontLoading?: boolean;
|
|
18
|
-
/**
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
20
|
+
/**
|
|
21
|
+
* Target element for loading styles related to `styled-components`.
|
|
22
|
+
* @deprecated
|
|
23
|
+
*/
|
|
24
|
+
styleSheetTarget?: StyleSheetManagerProps['target'];
|
|
25
|
+
/**
|
|
26
|
+
* Target element for rendering a `ReactDOM` portal.
|
|
27
|
+
* @deprecated
|
|
28
|
+
*/
|
|
29
|
+
portalTarget?: Parameters<typeof createPortal>[1];
|
|
22
30
|
/**
|
|
23
31
|
* Use native HTML5 controls for inputs instead of rich ones.
|
|
24
32
|
* @default false
|
|
@@ -34,14 +42,14 @@ export interface ConfigurationProps {
|
|
|
34
42
|
}
|
|
35
43
|
export interface ConfigurationContextValue {
|
|
36
44
|
locale: string;
|
|
37
|
-
direction: ConfigurationProps['direction']
|
|
45
|
+
direction: NonNullable<ConfigurationProps['direction']>;
|
|
38
46
|
translations: TranslationPack;
|
|
39
47
|
themeMachine: ThemeMachineLike<DefaultThemeDefinition>;
|
|
40
|
-
styleSheetTarget
|
|
41
|
-
portalTarget
|
|
48
|
+
styleSheetTarget: ConfigurationProps['styleSheetTarget'];
|
|
49
|
+
portalTarget: ConfigurationProps['portalTarget'];
|
|
42
50
|
loadedRef: MutableRefObject<boolean>;
|
|
43
51
|
renderNativeControls: boolean;
|
|
44
|
-
testIds
|
|
52
|
+
testIds: NonNullable<ConfigurationProps['testIds']>;
|
|
45
53
|
/** @internal */
|
|
46
54
|
initialized: boolean;
|
|
47
55
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Configuration.d.ts","sourceRoot":"","sources":["../../../src/components/Configuration/Configuration.tsx"],"names":[],"mappings":"AAAA,OAAO,EAGL,iBAAiB,EACjB,SAAS,
|
|
1
|
+
{"version":3,"file":"Configuration.d.ts","sourceRoot":"","sources":["../../../src/components/Configuration/Configuration.tsx"],"names":[],"mappings":"AAAA,OAAO,EAGL,iBAAiB,EACjB,SAAS,EAGT,OAAO,EACP,gBAAgB,EACjB,MAAM,OAAO,CAAC;AACf,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEzC,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAEhE,OAAO,YAAY,CAAC;AAEpB,OAAO,EAEL,gBAAgB,EAEhB,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AAC,CAAC,CAAC;IACpD,gBAAgB;IAChB,WAAW,EAAE,OAAO,CAAC;CACtB;AAID,eAAO,MAAM,oBAAoB,oCAW/B,CAAC;AAEH,QAAA,MAAM,aAAa,eAAiD,CAAC;AAErE,UAAU,mBAAmB;IAC3B,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,OAAO,CAAC,MAAM,CAAC;IACb,UAAU,MAAM;QACd,CAAC,aAAa,CAAC,CAAC,EAAE;YAChB,IAAI,EAAE,CAAC,QAAQ,EAAE,mBAAmB,KAAK,IAAI,CAAC;SAC/C,CAAC;KACH;CACF;AAID,UAAU,cAAe,SAAQ,mBAAmB;IAClD,cAAc,EAAE,MAAM,EAAE,CAAC;IACzB,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACpC;AA4BD,OAAO,QAAQ,YAAY,CAAC;IAC1B,UAAiB,aAAa;QAC5B,SAAS,CAAC,EAAE,CAAC,cAAc,GAAG,mBAAmB,CAAC,EAAE,CAAC;QACrD,oBAAoB,CAAC,EAAE,OAAO,CAAC,yBAAyB,CAAC,CAAC;KAC3D;CACF;AA2BD,QAAA,MAAM,aAAa,EAAE,iBAAiB,CAAC,kBAAkB,CAuGxD,CAAC;AAEF,eAAe,aAAa,CAAC"}
|
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
-
import { createContext, useContext, useMemo,
|
|
2
|
+
import { createContext, useContext, useMemo, useEffect } from 'react';
|
|
3
3
|
import { createPortal } from 'react-dom';
|
|
4
|
-
import { ThemeProvider, StyleSheetManager } from 'styled-components';
|
|
4
|
+
import styled, { ThemeProvider, StyleSheetManager } from 'styled-components';
|
|
5
|
+
import '../../init';
|
|
5
6
|
import { GlobalStyle } from '../../styles';
|
|
6
7
|
import { ThemeMachine, BaseThemeMachine } from '../../theme';
|
|
7
8
|
import { createTranslationPack, DefaultTranslation, direction as directionOfLocale } from '../../i18n';
|
|
8
9
|
import { windowIsAvailable, navigatorIsAvailable, documentIsAvailable } from '../../utils';
|
|
9
10
|
import pkg from '../../../package.json';
|
|
10
|
-
import '../../
|
|
11
|
+
import useElement from '../../hooks/useElement';
|
|
11
12
|
const defaultLocale = navigatorIsAvailable ? navigator.language : 'en';
|
|
12
13
|
export const ConfigurationContext = createContext({
|
|
13
14
|
locale: defaultLocale,
|
|
@@ -60,6 +61,9 @@ if (windowIsAvailable) {
|
|
|
60
61
|
};
|
|
61
62
|
}
|
|
62
63
|
}
|
|
64
|
+
const StyledConfigurationWrapper = styled.div `
|
|
65
|
+
display: contents;
|
|
66
|
+
`;
|
|
63
67
|
const Configuration = ({ children, locale, direction, translations: customTranslations, theme, disableDefaultFontLoading, styleSheetTarget, portalTarget, renderNativeControls, testIds, id }) => {
|
|
64
68
|
const context = windowIsAvailable
|
|
65
69
|
? window.cosmos.configurationContext ?? ConfigurationContext
|
|
@@ -69,10 +73,27 @@ const Configuration = ({ children, locale, direction, translations: customTransl
|
|
|
69
73
|
? new ThemeMachine({ theme, parent: ctx.themeMachine })
|
|
70
74
|
: ctx.themeMachine;
|
|
71
75
|
const translations = useMemo(() => createTranslationPack({ ...ctx.translations, ...customTranslations }), [ctx.translations, customTranslations]);
|
|
72
|
-
const [
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
+
const [wrapperEl, setWrapperEl] = useElement();
|
|
77
|
+
// Determine valid style sheet and portal target with ShadowDOM handling.
|
|
78
|
+
const [resolvedStyleSheetTarget, resolvedPortalTarget] = useMemo(() => {
|
|
79
|
+
// When rendering on the server, or before the wrapper is in the DOM, just bail.
|
|
80
|
+
if (!documentIsAvailable || !wrapperEl)
|
|
81
|
+
return [undefined, undefined];
|
|
82
|
+
const rootNode = wrapperEl.getRootNode();
|
|
83
|
+
// When within the ShadowDOM, the default target is the ShadowRoot, otherwise default to head/body element.
|
|
84
|
+
const defaultStyleSheetTarget = rootNode instanceof ShadowRoot ? rootNode : document.head;
|
|
85
|
+
const defaultPortalTarget = rootNode instanceof ShadowRoot ? rootNode : document.body;
|
|
86
|
+
// Currently passed prop or previous context value
|
|
87
|
+
const requestedStyleSheetTarget = styleSheetTarget ?? ctx.styleSheetTarget;
|
|
88
|
+
const requestedPortalTarget = portalTarget ?? ctx.portalTarget;
|
|
89
|
+
// If the "requested" target is within the root node, it is valid, so use that, otherwise fallback to the default.
|
|
90
|
+
return [
|
|
91
|
+
rootNode.contains(requestedStyleSheetTarget ?? null)
|
|
92
|
+
? requestedStyleSheetTarget
|
|
93
|
+
: defaultStyleSheetTarget,
|
|
94
|
+
rootNode.contains(requestedPortalTarget ?? null) ? requestedPortalTarget : defaultPortalTarget
|
|
95
|
+
];
|
|
96
|
+
}, [wrapperEl, styleSheetTarget, portalTarget, ctx.styleSheetTarget, ctx.portalTarget]);
|
|
76
97
|
useEffect(() => {
|
|
77
98
|
const sym = Symbol(id);
|
|
78
99
|
mountConfig(sym);
|
|
@@ -80,26 +101,25 @@ const Configuration = ({ children, locale, direction, translations: customTransl
|
|
|
80
101
|
unmountConfig(sym);
|
|
81
102
|
};
|
|
82
103
|
}, [id]);
|
|
83
|
-
const wrappedChildren = ctx.initialized ? (children) : (_jsx(StyleSheetManager, { disableVendorPrefixes: true, target:
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
return (_jsx(context.Provider
|
|
88
|
-
// eslint-disable-next-line react/jsx-no-constructed-context-values
|
|
89
|
-
, {
|
|
104
|
+
const wrappedChildren = ctx.initialized ? (children) : (_jsx(StyleSheetManager, { disableVendorPrefixes: true, target: resolvedStyleSheetTarget, children: _jsxs(_Fragment, { children: [!disableDefaultFontLoading &&
|
|
105
|
+
resolvedStyleSheetTarget &&
|
|
106
|
+
createPortal(_jsx("link", { rel: 'stylesheet', href: 'https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,400..700;1,400..700&family=Inter:wght@400..700&display=swap', "data-cosmos-global-style": true }), resolvedStyleSheetTarget), _jsx(GlobalStyle, {}), children] }) }));
|
|
107
|
+
return (_jsx(StyledConfigurationWrapper, { ref: setWrapperEl, children: _jsx(context.Provider
|
|
90
108
|
// eslint-disable-next-line react/jsx-no-constructed-context-values
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
109
|
+
, {
|
|
110
|
+
// eslint-disable-next-line react/jsx-no-constructed-context-values
|
|
111
|
+
value: {
|
|
112
|
+
locale: locale ?? ctx.locale,
|
|
113
|
+
direction: direction ?? (locale !== undefined ? directionOfLocale(locale) : ctx.direction),
|
|
114
|
+
translations,
|
|
115
|
+
themeMachine,
|
|
116
|
+
styleSheetTarget: resolvedStyleSheetTarget,
|
|
117
|
+
portalTarget: resolvedPortalTarget,
|
|
118
|
+
loadedRef: ctx.loadedRef,
|
|
119
|
+
renderNativeControls: renderNativeControls ?? ctx.renderNativeControls,
|
|
120
|
+
testIds: testIds ?? ctx.testIds,
|
|
121
|
+
initialized: true
|
|
122
|
+
}, children: _jsx(ThemeProvider, { theme: themeMachine.theme, children: wrappedChildren }) }) }));
|
|
103
123
|
};
|
|
104
124
|
export default Configuration;
|
|
105
125
|
//# sourceMappingURL=Configuration.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Configuration.js","sourceRoot":"","sources":["../../../src/components/Configuration/Configuration.tsx"],"names":[],"mappings":";AAAA,OAAO,EACL,aAAa,EACb,UAAU,EAGV,OAAO,EACP,QAAQ,EACR,SAAS,EAGV,MAAM,OAAO,CAAC;AACf,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAErE,OAAO,EAAE,WAAW,EAAE,MAAM,cAA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GAAiB,GAC1D,CACpB,CAAC;AACJ,CAAC,CAAC;AAEF,eAAe,aAAa,CAAC","sourcesContent":["import {\n createContext,\n useContext,\n FunctionComponent,\n ReactNode,\n useMemo,\n useState,\n useEffect,\n Context,\n MutableRefObject\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport { ThemeProvider, StyleSheetManager } from 'styled-components';\n\nimport { GlobalStyle } from '../../styles';\nimport {\n ThemeMachine,\n ThemeMachineLike,\n BaseThemeMachine,\n DefaultSettableTheme,\n DefaultThemeDefinition\n} from '../../theme';\nimport {\n createTranslationPack,\n Translation,\n TranslationPack,\n DefaultTranslation,\n direction as directionOfLocale\n} from '../../i18n';\nimport { windowIsAvailable, navigatorIsAvailable, documentIsAvailable } from '../../utils';\nimport pkg from '../../../package.json';\nimport '../../init';\n\nexport interface ConfigurationProps {\n /** Any components or nodes that should be impacted by the settings applied by this Configuration component. */\n children: ReactNode;\n /** User locale as defined in [BCP-47](https://www.techonthenet.com/js/language_tags.php). */\n locale?: string;\n /** Override rendering direction of the document. Direction will be based on the locale if now provided. */\n direction?: 'ltr' | 'rtl';\n /** Object with (partial) translations. */\n translations?: Translation;\n /** Theme object used to override any or all Cosmos theme properties. */\n theme?: DefaultSettableTheme;\n /** Disables loading Open Sans or Inter from Google Fonts. Only takes effect on the root configuration. */\n disableDefaultFontLoading?: boolean;\n /** Target element for loading styles related to `styled-components`. */\n styleSheetTarget?: HTMLElement;\n /** Target element for rendering a `ReactDOM` portal. */\n portalTarget?: Element;\n /**\n * Use native HTML5 controls for inputs instead of rich ones.\n * @default false\n */\n renderNativeControls?: boolean;\n /** String to identify this configuration instance. */\n id?: string;\n /**\n * Enable/disable testId attribute rendering for all components.\n * @default true\n */\n testIds?: boolean;\n}\n\nexport interface ConfigurationContextValue {\n locale: string;\n direction: ConfigurationProps['direction'];\n translations: TranslationPack;\n themeMachine: ThemeMachineLike<DefaultThemeDefinition>;\n styleSheetTarget?: HTMLElement;\n portalTarget?: Element;\n loadedRef: MutableRefObject<boolean>;\n renderNativeControls: boolean;\n testIds?: ConfigurationProps['testIds'];\n /** @internal */\n initialized: boolean;\n}\n\nconst defaultLocale = navigatorIsAvailable ? navigator.language : 'en';\n\nexport const ConfigurationContext = createContext<ConfigurationContextValue>({\n locale: defaultLocale,\n direction: directionOfLocale(defaultLocale),\n translations: DefaultTranslation,\n themeMachine: BaseThemeMachine,\n styleSheetTarget: documentIsAvailable ? document.head : undefined,\n portalTarget: documentIsAvailable ? document.body : undefined,\n loadedRef: { current: false },\n renderNativeControls: false,\n testIds: true,\n initialized: false\n});\n\nconst legacyMetaKey = Symbol.for('@pega/cosmos-react-core.metadata');\n\ninterface LegacyCosmosInstace {\n version: string;\n}\n\ndeclare global {\n interface Window {\n [legacyMetaKey]?: {\n push: (instance: LegacyCosmosInstace) => void;\n };\n }\n}\n\nconst mountedConfigs = new Set<symbol>();\n\ninterface CosmosInstance extends LegacyCosmosInstace {\n mountedConfigs: string[];\n mountOrder: string[];\n mountCount: Record<string, number>;\n}\n\nconst instance: CosmosInstance = {\n version: pkg.version,\n mountedConfigs: [],\n mountOrder: [],\n mountCount: {}\n};\n\nconst mountConfig = (sym: symbol) => {\n mountedConfigs.add(sym);\n instance.mountedConfigs = [...mountedConfigs].map(i => i.description ?? 'Unknown');\n\n const description = sym.description ?? 'Unknown';\n\n instance.mountOrder.push(description);\n\n if (!(description in instance.mountCount)) {\n instance.mountCount[description] = 0;\n }\n instance.mountCount[description] += 1;\n};\n\nconst unmountConfig = (sym: symbol) => {\n mountedConfigs.delete(sym);\n instance.mountedConfigs = [...mountedConfigs].map(i => i.description ?? 'Unknown');\n};\n\ndeclare module '../../init' {\n export interface CosmosGlobals {\n instances?: (CosmosInstance | LegacyCosmosInstace)[];\n configurationContext?: Context<ConfigurationContextValue>;\n }\n}\n\nif (windowIsAvailable) {\n if (!window.cosmos.instances) {\n window.cosmos.instances = [];\n }\n\n window.cosmos.instances.push(instance);\n\n if (Array.isArray(window[legacyMetaKey])) {\n window.cosmos.instances.push(...window[legacyMetaKey]);\n delete window[legacyMetaKey];\n }\n\n if (!window[legacyMetaKey]) {\n window[legacyMetaKey] = {\n push: inst => {\n window.cosmos.instances?.push(inst);\n }\n };\n }\n}\n\nconst Configuration: FunctionComponent<ConfigurationProps> = ({\n children,\n locale,\n direction,\n translations: customTranslations,\n theme,\n disableDefaultFontLoading,\n styleSheetTarget,\n portalTarget,\n renderNativeControls,\n testIds,\n id\n}: ConfigurationProps) => {\n const context = windowIsAvailable\n ? window.cosmos.configurationContext ?? ConfigurationContext\n : ConfigurationContext;\n const ctx = useContext(context);\n const themeMachine = theme\n ? new ThemeMachine<DefaultThemeDefinition>({ theme, parent: ctx.themeMachine })\n : ctx.themeMachine;\n const translations = useMemo(\n () => createTranslationPack({ ...ctx.translations, ...customTranslations }),\n [ctx.translations, customTranslations]\n );\n\n const [mounted, setMounted] = useState(false);\n\n useEffect(() => {\n setMounted(true);\n }, []);\n\n useEffect(() => {\n const sym = Symbol(id);\n mountConfig(sym);\n\n return () => {\n unmountConfig(sym);\n };\n }, [id]);\n\n const wrappedChildren = ctx.initialized ? (\n children\n ) : (\n <StyleSheetManager disableVendorPrefixes target={styleSheetTarget ?? ctx.styleSheetTarget}>\n <>\n {!disableDefaultFontLoading &&\n mounted &&\n documentIsAvailable &&\n createPortal(\n <link\n rel='stylesheet'\n href='https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,400..700;1,400..700&family=Inter:wght@400..700&display=swap'\n data-cosmos-global-style\n />,\n styleSheetTarget ?? ctx.styleSheetTarget ?? document.head\n )}\n <GlobalStyle />\n {children}\n </>\n </StyleSheetManager>\n );\n\n return (\n <context.Provider\n // eslint-disable-next-line react/jsx-no-constructed-context-values\n value={{\n locale: locale ?? ctx.locale,\n direction: direction ?? (locale !== undefined ? directionOfLocale(locale) : ctx.direction),\n translations,\n themeMachine,\n styleSheetTarget: styleSheetTarget ?? ctx.styleSheetTarget,\n portalTarget: portalTarget ?? ctx.portalTarget,\n loadedRef: ctx.loadedRef,\n renderNativeControls: renderNativeControls ?? ctx.renderNativeControls,\n testIds: testIds ?? ctx.testIds,\n initialized: true\n }}\n >\n <ThemeProvider theme={themeMachine.theme}>{wrappedChildren}</ThemeProvider>\n </context.Provider>\n );\n};\n\nexport default Configuration;\n"]}
|
|
1
|
+
{"version":3,"file":"Configuration.js","sourceRoot":"","sources":["../../../src/components/Configuration/Configuration.tsx"],"names":[],"mappings":";AAAA,OAAO,EACL,aAAa,EACb,UAAU,EAGV,OAAO,EACP,SAAS,EAGV,MAAM,OAAO,CAAC;AACf,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,MAAM,EAAE,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAG7E,OAAO,YAAY,CAAC;AACpB,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EACL,YAAY,EAEZ,gBAAgB,EAGjB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,qBAAqB,EAGrB,kBAAkB,EAClB,SAAS,IAAI,iBAAiB,EAC/B,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAC3F,OAAO,GAAG,MAAM,uBAAuB,CAAC;AACxC,OAAO,UAAU,MAAM,wBAAwB,CAAC;AAqDhD,MAAM,aAAa,GAAG,oBAAoB,CAAC,CAAC,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC;AAEvE,MAAM,CAAC,MAAM,oBAAoB,GAAG,aAAa,CAA4B;IAC3E,MAAM,EAAE,aAAa;IACrB,SAAS,EAAE,iBAAiB,CAAC,aAAa,CAAC;IAC3C,YAAY,EAAE,kBAAkB;IAChC,YAAY,EAAE,gBAAgB;IAC9B,gBAAgB,EAAE,mBAAmB,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,S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SAAS,EAAE,GAAG,CAAC,SAAS;gBACxB,oBAAoB,EAAE,oBAAoB,IAAI,GAAG,CAAC,oBAAoB;gBACtE,OAAO,EAAE,OAAO,IAAI,GAAG,CAAC,OAAO;gBAC/B,WAAW,EAAE,IAAI;aAClB,YAED,KAAC,aAAa,IAAC,KAAK,EAAE,YAAY,CAAC,KAAK,YAAG,eAAe,GAAiB,GAC1D,GACQ,CAC9B,CAAC;AACJ,CAAC,CAAC;AAEF,eAAe,aAAa,CAAC","sourcesContent":["import {\n createContext,\n useContext,\n FunctionComponent,\n ReactNode,\n useMemo,\n useEffect,\n Context,\n MutableRefObject\n} from 'react';\nimport { createPortal } from 'react-dom';\nimport styled, { ThemeProvider, StyleSheetManager } from 'styled-components';\nimport type { StyleSheetManagerProps } from 'styled-components';\n\nimport '../../init';\nimport { GlobalStyle } from '../../styles';\nimport {\n ThemeMachine,\n ThemeMachineLike,\n BaseThemeMachine,\n DefaultSettableTheme,\n DefaultThemeDefinition\n} from '../../theme';\nimport {\n createTranslationPack,\n Translation,\n TranslationPack,\n DefaultTranslation,\n direction as directionOfLocale\n} from '../../i18n';\nimport { windowIsAvailable, navigatorIsAvailable, documentIsAvailable } from '../../utils';\nimport pkg from '../../../package.json';\nimport useElement from '../../hooks/useElement';\n\nexport interface ConfigurationProps {\n /** Any components or nodes that should be impacted by the settings applied by this Configuration component. */\n children: ReactNode;\n /** User locale as defined in [BCP-47](https://www.techonthenet.com/js/language_tags.php). */\n locale?: string;\n /** Override rendering direction of the document. Direction will be based on the locale if now provided. */\n direction?: 'ltr' | 'rtl';\n /** Object with (partial) translations. */\n translations?: Translation;\n /** Theme object used to override any or all Cosmos theme properties. */\n theme?: DefaultSettableTheme;\n /** Disables loading Open Sans or Inter from Google Fonts. Only takes effect on the root configuration. */\n disableDefaultFontLoading?: boolean;\n /**\n * Target element for loading styles related to `styled-components`.\n * @deprecated\n */\n styleSheetTarget?: StyleSheetManagerProps['target'];\n /**\n * Target element for rendering a `ReactDOM` portal.\n * @deprecated\n */\n portalTarget?: Parameters<typeof createPortal>[1];\n /**\n * Use native HTML5 controls for inputs instead of rich ones.\n * @default false\n */\n renderNativeControls?: boolean;\n /** String to identify this configuration instance. */\n id?: string;\n /**\n * Enable/disable testId attribute rendering for all components.\n * @default true\n */\n testIds?: boolean;\n}\n\nexport interface ConfigurationContextValue {\n locale: string;\n direction: NonNullable<ConfigurationProps['direction']>;\n translations: TranslationPack;\n themeMachine: ThemeMachineLike<DefaultThemeDefinition>;\n styleSheetTarget: ConfigurationProps['styleSheetTarget'];\n portalTarget: ConfigurationProps['portalTarget'];\n loadedRef: MutableRefObject<boolean>;\n renderNativeControls: boolean;\n testIds: NonNullable<ConfigurationProps['testIds']>;\n /** @internal */\n initialized: boolean;\n}\n\nconst defaultLocale = navigatorIsAvailable ? navigator.language : 'en';\n\nexport const ConfigurationContext = createContext<ConfigurationContextValue>({\n locale: defaultLocale,\n direction: directionOfLocale(defaultLocale),\n translations: DefaultTranslation,\n themeMachine: BaseThemeMachine,\n styleSheetTarget: documentIsAvailable ? document.head : undefined,\n portalTarget: documentIsAvailable ? document.body : undefined,\n loadedRef: { current: false },\n renderNativeControls: false,\n testIds: true,\n initialized: false\n});\n\nconst legacyMetaKey = Symbol.for('@pega/cosmos-react-core.metadata');\n\ninterface LegacyCosmosInstace {\n version: string;\n}\n\ndeclare global {\n interface Window {\n [legacyMetaKey]?: {\n push: (instance: LegacyCosmosInstace) => void;\n };\n }\n}\n\nconst mountedConfigs = new Set<symbol>();\n\ninterface CosmosInstance extends LegacyCosmosInstace {\n mountedConfigs: string[];\n mountOrder: string[];\n mountCount: Record<string, number>;\n}\n\nconst instance: CosmosInstance = {\n version: pkg.version,\n mountedConfigs: [],\n mountOrder: [],\n mountCount: {}\n};\n\nconst mountConfig = (sym: symbol) => {\n mountedConfigs.add(sym);\n instance.mountedConfigs = [...mountedConfigs].map(i => i.description ?? 'Unknown');\n\n const description = sym.description ?? 'Unknown';\n\n instance.mountOrder.push(description);\n\n if (!(description in instance.mountCount)) {\n instance.mountCount[description] = 0;\n }\n instance.mountCount[description] += 1;\n};\n\nconst unmountConfig = (sym: symbol) => {\n mountedConfigs.delete(sym);\n instance.mountedConfigs = [...mountedConfigs].map(i => i.description ?? 'Unknown');\n};\n\ndeclare module '../../init' {\n export interface CosmosGlobals {\n instances?: (CosmosInstance | LegacyCosmosInstace)[];\n configurationContext?: Context<ConfigurationContextValue>;\n }\n}\n\nif (windowIsAvailable) {\n if (!window.cosmos.instances) {\n window.cosmos.instances = [];\n }\n\n window.cosmos.instances.push(instance);\n\n if (Array.isArray(window[legacyMetaKey])) {\n window.cosmos.instances.push(...window[legacyMetaKey]);\n delete window[legacyMetaKey];\n }\n\n if (!window[legacyMetaKey]) {\n window[legacyMetaKey] = {\n push: inst => {\n window.cosmos.instances?.push(inst);\n }\n };\n }\n}\n\nconst StyledConfigurationWrapper = styled.div`\n display: contents;\n`;\n\nconst Configuration: FunctionComponent<ConfigurationProps> = ({\n children,\n locale,\n direction,\n translations: customTranslations,\n theme,\n disableDefaultFontLoading,\n styleSheetTarget,\n portalTarget,\n renderNativeControls,\n testIds,\n id\n}: ConfigurationProps) => {\n const context = windowIsAvailable\n ? window.cosmos.configurationContext ?? ConfigurationContext\n : ConfigurationContext;\n const ctx = useContext(context);\n const themeMachine = theme\n ? new ThemeMachine<DefaultThemeDefinition>({ theme, parent: ctx.themeMachine })\n : ctx.themeMachine;\n const translations = useMemo(\n () => createTranslationPack({ ...ctx.translations, ...customTranslations }),\n [ctx.translations, customTranslations]\n );\n\n const [wrapperEl, setWrapperEl] = useElement<HTMLDivElement>();\n\n // Determine valid style sheet and portal target with ShadowDOM handling.\n const [resolvedStyleSheetTarget, resolvedPortalTarget] = useMemo(() => {\n // When rendering on the server, or before the wrapper is in the DOM, just bail.\n if (!documentIsAvailable || !wrapperEl) return [undefined, undefined];\n\n const rootNode = wrapperEl.getRootNode();\n\n // When within the ShadowDOM, the default target is the ShadowRoot, otherwise default to head/body element.\n const defaultStyleSheetTarget = rootNode instanceof ShadowRoot ? rootNode : document.head;\n const defaultPortalTarget = rootNode instanceof ShadowRoot ? rootNode : document.body;\n\n // Currently passed prop or previous context value\n const requestedStyleSheetTarget = styleSheetTarget ?? ctx.styleSheetTarget;\n const requestedPortalTarget = portalTarget ?? ctx.portalTarget;\n\n // If the \"requested\" target is within the root node, it is valid, so use that, otherwise fallback to the default.\n return [\n rootNode.contains(requestedStyleSheetTarget ?? null)\n ? requestedStyleSheetTarget\n : defaultStyleSheetTarget,\n rootNode.contains(requestedPortalTarget ?? null) ? requestedPortalTarget : defaultPortalTarget\n ];\n }, [wrapperEl, styleSheetTarget, portalTarget, ctx.styleSheetTarget, ctx.portalTarget]);\n\n useEffect(() => {\n const sym = Symbol(id);\n mountConfig(sym);\n\n return () => {\n unmountConfig(sym);\n };\n }, [id]);\n\n const wrappedChildren = ctx.initialized ? (\n children\n ) : (\n <StyleSheetManager disableVendorPrefixes target={resolvedStyleSheetTarget}>\n <>\n {!disableDefaultFontLoading &&\n resolvedStyleSheetTarget &&\n createPortal(\n <link\n rel='stylesheet'\n href='https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,400..700;1,400..700&family=Inter:wght@400..700&display=swap'\n data-cosmos-global-style\n />,\n resolvedStyleSheetTarget\n )}\n <GlobalStyle />\n {children}\n </>\n </StyleSheetManager>\n );\n\n return (\n <StyledConfigurationWrapper ref={setWrapperEl}>\n <context.Provider\n // eslint-disable-next-line react/jsx-no-constructed-context-values\n value={{\n locale: locale ?? ctx.locale,\n direction:\n direction ?? (locale !== undefined ? directionOfLocale(locale) : ctx.direction),\n translations,\n themeMachine,\n styleSheetTarget: resolvedStyleSheetTarget,\n portalTarget: resolvedPortalTarget,\n loadedRef: ctx.loadedRef,\n renderNativeControls: renderNativeControls ?? ctx.renderNativeControls,\n testIds: testIds ?? ctx.testIds,\n initialized: true\n }}\n >\n <ThemeProvider theme={themeMachine.theme}>{wrappedChildren}</ThemeProvider>\n </context.Provider>\n </StyledConfigurationWrapper>\n );\n};\n\nexport default Configuration;\n"]}
|
|
@@ -9,6 +9,6 @@ export interface DangerButtonProps extends NoChildrenProp, OmitStrict<Attributes
|
|
|
9
9
|
primary?: boolean;
|
|
10
10
|
}
|
|
11
11
|
export declare const StyledDangerButton: import("styled-components").StyledComponent<import("react").FunctionComponent<import("../Button").ButtonProps & import("../../types").ForwardProps>, import("styled-components").DefaultTheme, {}, never>;
|
|
12
|
-
declare const DangerButton: import("react").ForwardRefExoticComponent<
|
|
12
|
+
declare const DangerButton: import("react").ForwardRefExoticComponent<Omit<DangerButtonProps, "ref"> & import("react").RefAttributes<HTMLButtonElement>>;
|
|
13
13
|
export default DangerButton;
|
|
14
14
|
//# sourceMappingURL=DangerButton.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DangerButton.d.ts","sourceRoot":"","sources":["../../../src/components/DangerButton/DangerButton.tsx"],"names":[],"mappings":"AAIA,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,UAAU,EAAc,MAAM,aAAa,CAAC;AAKjF,MAAM,WAAW,iBACf,SAAQ,cAAc,EACpB,UAAU,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,UAAU,CAAC;IAC9C,mCAAmC;IACnC,KAAK,EAAE,WAAW,CAAC,iBAAiB,CAAC,aAAa,CAAC,CAAC,CAAC;IACrD;;;OAGG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED,eAAO,MAAM,kBAAkB,2MAAmB,CAAC;AAInD,QAAA,MAAM,YAAY,
|
|
1
|
+
{"version":3,"file":"DangerButton.d.ts","sourceRoot":"","sources":["../../../src/components/DangerButton/DangerButton.tsx"],"names":[],"mappings":"AAIA,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,UAAU,EAAc,MAAM,aAAa,CAAC;AAKjF,MAAM,WAAW,iBACf,SAAQ,cAAc,EACpB,UAAU,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,UAAU,CAAC;IAC9C,mCAAmC;IACnC,KAAK,EAAE,WAAW,CAAC,iBAAiB,CAAC,aAAa,CAAC,CAAC,CAAC;IACrD;;;OAGG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED,eAAO,MAAM,kBAAkB,2MAAmB,CAAC;AAInD,QAAA,MAAM,YAAY,8HAoBjB,CAAC;AAEF,eAAe,YAAY,CAAC"}
|
|
@@ -7,6 +7,7 @@ type DateTimeFormatOptions = {
|
|
|
7
7
|
format: DateTimeFormat;
|
|
8
8
|
timeZone?: string;
|
|
9
9
|
clockFormat?: ClockFormat;
|
|
10
|
+
calendarType?: string;
|
|
10
11
|
} & ({
|
|
11
12
|
variant: ExcludeStrict<DateTimeVariant, 'quarteryear'>;
|
|
12
13
|
t?: TranslationFunction<TranslationPack>;
|
|
@@ -14,7 +15,7 @@ type DateTimeFormatOptions = {
|
|
|
14
15
|
variant: 'quarteryear';
|
|
15
16
|
t: TranslationFunction<TranslationPack>;
|
|
16
17
|
});
|
|
17
|
-
export declare function formatDateTime(value: Date, { t, locale, format, variant, clockFormat, timeZone }: DateTimeFormatOptions): string;
|
|
18
|
+
export declare function formatDateTime(value: Date, { t, locale, format, variant, clockFormat, calendarType, timeZone }: DateTimeFormatOptions): string;
|
|
18
19
|
interface DurationFormatOptions {
|
|
19
20
|
locale: string;
|
|
20
21
|
significantUnits: 4 | 3 | 2 | 1;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/components/DateTime/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAClE,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAG5C,OAAO,EAAmB,cAAc,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;
|
|
1
|
+
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/components/DateTime/utils.ts"],"names":[],"m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Input/local';
|
|
2
3
|
import { getEndOfWeek, getQuarter, getStartOfWeek, getWeek, getWeekYear } from './Input/utils';
|
|
3
4
|
const unitsInMs = {
|
|
4
5
|
year: 24 * 60 * 60 * 1000 * 365,
|
|
@@ -97,7 +98,7 @@ const formatMapping = {
|
|
|
97
98
|
const dateTimeFormatCache = {};
|
|
98
99
|
const relativeTimeFormatCache = {};
|
|
99
100
|
const displayNamesCache = {};
|
|
100
|
-
export function formatDateTime(value, { t, locale, format, variant, clockFormat, timeZone }) {
|
|
101
|
+
export function formatDateTime(value, { t, locale, format, variant, clockFormat, calendarType = CALENDAR_TYPES.ISO_8601, timeZone }) {
|
|
101
102
|
const getFormattedDate = (date, dateVariant, overrideTimeZone) => {
|
|
102
103
|
const resolvedVariant = dateVariant === 'time' || dateVariant === 'datetime'
|
|
103
104
|
? `${dateVariant}${clockFormat ?? ''}`
|
|
@@ -200,9 +201,9 @@ export function formatDateTime(value, { t, locale, format, variant, clockFormat,
|
|
|
200
201
|
});
|
|
201
202
|
const displayNames = displayNamesCache[locale];
|
|
202
203
|
const adjustedUTCDate = new Date(date.getTime() - date.getTimezoneOffset() * 60000);
|
|
203
|
-
const startDate = getFormattedDate(getStartOfWeek(adjustedUTCDate), 'week', 'UTC');
|
|
204
|
-
const endDate = getFormattedDate(getEndOfWeek(adjustedUTCDate), 'week', 'UTC');
|
|
205
|
-
return `${cap(displayNames.of('weekOfYear'))} ${getWeek(adjustedUTCDate)}, ${getWeekYear(adjustedUTCDate)} (${startDate} - ${endDate})`;
|
|
204
|
+
const startDate = getFormattedDate(getStartOfWeek(adjustedUTCDate, calendarType), 'week', 'UTC');
|
|
205
|
+
const endDate = getFormattedDate(getEndOfWeek(adjustedUTCDate, calendarType), 'week', 'UTC');
|
|
206
|
+
return `${cap(displayNames.of('weekOfYear'))} ${getWeek(adjustedUTCDate, calendarType)}, ${getWeekYear(adjustedUTCDate)} (${startDate} - ${endDate})`;
|
|
206
207
|
};
|
|
207
208
|
const getFormattedQuarterYear = (date) => {
|
|
208
209
|
const formattedYear = getFormattedDate(date, 'year');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/components/DateTime/utils.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAGlC,OAAO,EAEL,YAAY,EACZ,UAAU,EACV,cAAc,EACd,OAAO,EACP,WAAW,EACZ,MAAM,eAAe,CAAC;AAEvB,MAAM,SAAS,GAAG;IAChB,IAAI,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,GAAG,GAAG;IAC/B,KAAK,EAAE,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,GAAG,GAAG,CAAC,GAAG,EAAE;IACvC,GAAG,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI;IACxB,IAAI,EAAE,EAAE,GAAG,EAAE,GAAG,IAAI;IACpB,MAAM,EAAE,EAAE,GAAG,IAAI;IACjB,MAAM,EAAE,IAAI;CACkD,CAAC;AAmBjE,MAAM,SAAS,GAAG;IAChB,IAAI,EAAE,SAAS;IACf,MAAM,EAAE,SAAS;CACI,CAAC;AAExB,MAAM,WAAW,GAAG;IAClB,GAAG,SAAS;IACZ,MAAM,EAAE,IAAI;CACS,CAAC;AAExB,MAAM,WAAW,GAAG;IAClB,GAAG,SAAS;IACZ,MAAM,EAAE,KAAK;CACQ,CAAC;AAExB,MAAM,QAAQ,GAAG;IACf,GAAG,SAAS;IACZ,MAAM,EAAE,SAAS;CACI,CAAC;AAExB,MAAM,UAAU,GAAG;IACjB,GAAG,WAAW;IACd,MAAM,EAAE,SAAS;CACI,CAAC;AAExB,MAAM,UAAU,GAAG;IACjB,GAAG,WAAW;IACd,MAAM,EAAE,SAAS;CACI,CAAC;AAMxB,MAAM,aAAa,GAAG;IACpB,IAAI,EAAE;QACJ,KAAK,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,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AE;gBAC7E,KAAK,EAAE,MAAM;gBACb,IAAI;gBACJ,WAAW;aACZ,CAAC,CAAC;YAEH,MAAM,CAAC,IAAI,CAAC,iBAAiB,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,WAAW,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;SACzE;KACF;IACD,OAAO,GAAG,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;AACtC,CAAC","sourcesContent":["import { TranslationFunction, TranslationPack } from '../../i18n';\nimport { ExcludeStrict } from '../../types';\nimport { cap } from '../../utils';\n\nimport { AbsoluteVariant, DateTimeFormat, DateTimeVariant } from './DateTime.types';\nimport {\n ClockFormat,\n getEndOfWeek,\n getQuarter,\n getStartOfWeek,\n getWeek,\n getWeekYear\n} from './Input/utils';\n\nconst unitsInMs = {\n year: 24 * 60 * 60 * 1000 * 365,\n month: (24 * 60 * 60 * 1000 * 365) / 12,\n day: 24 * 60 * 60 * 1000,\n hour: 60 * 60 * 1000,\n minute: 60 * 1000,\n second: 1000\n} satisfies Partial<Record<Intl.RelativeTimeFormatUnit, number>>;\n\ntype TimeUnit = keyof typeof unitsInMs;\n\ntype DateTimeFormatOptions = {\n locale: string;\n format: DateTimeFormat;\n timeZone?: string;\n clockFormat?: ClockFormat;\n} & (\n | {\n variant: ExcludeStrict<DateTimeVariant, 'quarteryear'>;\n t?: TranslationFunction<TranslationPack>;\n }\n | { variant: 'quarteryear'; t: TranslationFunction<TranslationPack> }\n);\n\ntype TimeOptions = Pick<Intl.DateTimeFormatOptions, 'hour' | 'minute' | 'second' | 'hour12'>;\n\nconst timeShort = {\n hour: 'numeric',\n minute: 'numeric'\n} satisfies TimeOptions;\n\nconst timeShort12 = {\n ...timeShort,\n hour12: true\n} satisfies TimeOptions;\n\nconst timeShort24 = {\n ...timeShort,\n hour12: false\n} satisfies TimeOptions;\n\nconst timeLong = {\n ...timeShort,\n second: 'numeric'\n} satisfies TimeOptions;\n\nconst timeLong12 = {\n ...timeShort12,\n second: 'numeric'\n} satisfies TimeOptions;\n\nconst timeLong24 = {\n ...timeShort24,\n second: 'numeric'\n} satisfies TimeOptions;\n\ntype AddClockFormatToTimeKeys<Key extends DateTimeVariant> = Key extends `${string}time`\n ? `${Key}${'' | 12 | 24}`\n : Key;\n\nconst formatMapping = {\n date: {\n short: { year: 'numeric', month: 'short', day: 'numeric' },\n long: { year: 'numeric', month: 'long', day: 'numeric' },\n numeric: { year: 'numeric', month: 'numeric', day: 'numeric' }\n },\n datetime: {\n short: { year: 'numeric', month: 'short', day: 'numeric', ...timeShort },\n long: { year: 'numeric', month: 'long', day: 'numeric', ...timeLong },\n numeric: { year: 'numeric', month: 'numeric', day: 'numeric', ...timeShort }\n },\n datetime12: {\n short: { year: 'numeric', month: 'short', day: 'numeric', ...timeShort12 },\n long: { year: 'numeric', month: 'long', day: 'numeric', ...timeLong12 },\n numeric: { year: 'numeric', month: 'numeric', day: 'numeric', ...timeShort12 }\n },\n datetime24: {\n short: { year: 'numeric', month: 'short', day: 'numeric', ...timeShort24 },\n long: { year: 'numeric', month: 'long', day: 'numeric', ...timeLong24 },\n numeric: { year: 'numeric', month: 'numeric', day: 'numeric', ...timeShort24 }\n },\n time: {\n short: timeShort,\n long: timeLong,\n numeric: timeShort\n },\n time12: {\n short: timeShort12,\n long: timeLong12,\n numeric: timeShort12\n },\n time24: {\n short: timeShort24,\n long: timeLong24,\n numeric: timeShort24\n },\n month: {\n short: { month: 'short' },\n long: { month: 'long' },\n numeric: { month: 'numeric' }\n },\n monthyear: {\n short: { year: 'numeric', month: 'short' },\n long: { year: 'numeric', month: 'long' },\n numeric: { year: 'numeric', month: 'numeric' }\n },\n week: {\n short: { month: 'short', day: 'numeric' },\n long: { month: 'long', day: 'numeric' },\n numeric: { month: 'numeric', day: 'numeric' }\n },\n year: {\n short: { year: 'numeric' },\n long: { year: 'numeric' },\n numeric: { year: '2-digit' }\n },\n relative: {\n short: { style: 'long', numeric: 'auto' },\n long: { style: 'long', numeric: 'auto' },\n numeric: { style: 'short', numeric: 'auto' }\n }\n} satisfies Record<\n AddClockFormatToTimeKeys<ExcludeStrict<AbsoluteVariant, 'quarteryear'>>,\n Record<DateTimeFormat, Intl.DateTimeFormatOptions>\n> &\n Record<'relative', Record<DateTimeFormat, Intl.RelativeTimeFormatOptions>>;\n\nconst dateTimeFormatCache: Record<\n // locale\n string,\n Record<\n // timeZone\n string,\n Map<Intl.DateTimeFormatOptions, Intl.DateTimeFormat>\n >\n> = {};\n\nconst relativeTimeFormatCache: Record<\n // locale\n string,\n Map<Intl.RelativeTimeFormatOptions, Intl.RelativeTimeFormat>\n> = {};\n\nconst displayNamesCache: Record<\n // locale\n string,\n Intl.DateTimeDisplayNames\n> = {};\n\nexport function formatDateTime(\n value: Date,\n { t, locale, format, variant, clockFormat, timeZone }: DateTimeFormatOptions\n) {\n const getFormattedDate = (\n date: Date,\n dateVariant: ExcludeStrict<AbsoluteVariant, 'quarteryear'>,\n overrideTimeZone?: string\n ) => {\n const resolvedVariant: AddClockFormatToTimeKeys<typeof dateVariant> =\n dateVariant === 'time' || dateVariant === 'datetime'\n ? `${dateVariant}${clockFormat ?? ''}`\n : dateVariant;\n const resolvedTimeZone = overrideTimeZone ?? timeZone;\n const resolvedOptions = formatMapping[resolvedVariant][format];\n\n dateTimeFormatCache[locale] ??= {};\n dateTimeFormatCache[locale][`${resolvedTimeZone}`] ??= new Map();\n\n const map = dateTimeFormatCache[locale][`${resolvedTimeZone}`];\n\n if (!map.has(resolvedOptions)) {\n map.set(\n resolvedOptions,\n new Intl.DateTimeFormat(locale, {\n ...resolvedOptions,\n timeZone: resolvedTimeZone\n })\n );\n }\n\n return map.get(resolvedOptions)!.format(date);\n };\n\n const relativeTimeFormatter = (relativeValue: number, unit: TimeUnit) => {\n const resolvedOptions = formatMapping.relative[format];\n\n relativeTimeFormatCache[locale] ??= new Map();\n const map = relativeTimeFormatCache[locale];\n\n if (!map.has(resolvedOptions)) {\n map.set(resolvedOptions, new Intl.RelativeTimeFormat(locale, resolvedOptions));\n }\n\n return map.get(resolvedOptions)!.format(relativeValue, unit);\n };\n\n const getUnitsElapsed = (date: Date, unit: TimeUnit): number => {\n let amount: number;\n const now = new Date();\n\n switch (unit) {\n case 'year':\n amount = date.getUTCFullYear() - now.getUTCFullYear();\n break;\n case 'month':\n if (date.getUTCFullYear() === now.getUTCFullYear()) {\n amount = date.getUTCMonth() - now.getUTCMonth();\n } else if (date < now) {\n amount = (11 - date.getUTCMonth() + now.getUTCMonth() + 1) * -1;\n } else {\n amount = 11 - now.getUTCMonth() + date.getUTCMonth() + 1;\n }\n break;\n case 'day':\n if (date.getUTCMonth() === now.getUTCMonth()) {\n amount = date.getUTCDate() - now.getUTCDate();\n } else if (date < now) {\n const maximalDayOfMonth = new Date(\n Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 0)\n ).getUTCDate();\n amount = (maximalDayOfMonth - date.getUTCDate() + now.getUTCDate()) * -1;\n } else {\n const maximalDayOfMonth = new Date(\n Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 0)\n ).getUTCDate();\n amount = maximalDayOfMonth - now.getUTCDate() + date.getUTCDate() + 1;\n }\n break;\n case 'hour':\n if (date.getUTCDate() === now.getUTCDate()) {\n amount = date.getUTCHours() - now.getUTCHours();\n } else if (date < now) {\n amount = (23 - date.getUTCHours() + now.getUTCHours() + 1) * -1;\n } else {\n amount = 23 - now.getUTCHours() + date.getUTCHours() + 1;\n }\n break;\n case 'minute':\n if (date.getUTCHours() === now.getUTCHours()) {\n amount = date.getUTCMinutes() - now.getUTCMinutes();\n } else if (date < now) {\n amount = (59 - date.getUTCMinutes() + now.getUTCMinutes() + 1) * -1;\n } else {\n amount = 59 - now.getUTCMinutes() + date.getUTCMinutes() + 1;\n }\n break;\n default:\n amount = 0;\n break;\n }\n return amount;\n };\n\n const getRelativeTime = (date: Date) => {\n let elapsed = date.getTime() - Date.now();\n // Deliberately reduce precision to 1 minute\n if (Math.abs(elapsed) < 60000) elapsed = 0;\n const unit = (Object.keys(unitsInMs).find(u => Math.abs(elapsed) >= unitsInMs[u as TimeUnit]) ||\n 'second') as TimeUnit;\n const amount = getUnitsElapsed(date, unit);\n\n return relativeTimeFormatter(amount, unit);\n };\n\n const getFormattedWeek = (date: Date) => {\n displayNamesCache[locale] ??= new Intl.DisplayNames(locale, {\n style: 'long',\n type: 'dateTimeField'\n }) as Intl.DateTimeDisplayNames;\n\n const displayNames = displayNamesCache[locale];\n const adjustedUTCDate = new Date(date.getTime() - date.getTimezoneOffset() * 60000);\n const startDate = getFormattedDate(getStartOfWeek(adjustedUTCDate), 'week', 'UTC');\n const endDate = getFormattedDate(getEndOfWeek(adjustedUTCDate), 'week', 'UTC');\n return `${cap(displayNames.of('weekOfYear'))} ${getWeek(adjustedUTCDate)}, ${getWeekYear(\n adjustedUTCDate\n )} (${startDate} - ${endDate})`;\n };\n\n const getFormattedQuarterYear = (date: Date) => {\n const formattedYear = getFormattedDate(date, 'year');\n const adjustedUTCDate = new Date(date.getTime() - date.getTimezoneOffset() * 60000);\n const quarterNumber = getQuarter(adjustedUTCDate);\n return `${t!(`date_quarter_q${quarterNumber}`, [formattedYear])}`;\n };\n\n switch (variant) {\n case 'relative':\n return getRelativeTime(value);\n case 'week':\n return getFormattedWeek(value);\n case 'quarteryear':\n return getFormattedQuarterYear(value);\n default:\n return getFormattedDate(value, variant);\n }\n}\n\nconst dayInMs = 24 * 60 * 60 * 1000;\nconst hourInMs = 60 * 60 * 1000;\nconst minuteInMs = 60 * 1000;\nconst secondInMs = 1000;\n\ninterface DurationFormatOptions {\n locale: string;\n significantUnits: 4 | 3 | 2 | 1;\n unitDisplay?: Intl.NumberFormatOptions['unitDisplay'];\n}\n\nconst numberFormatCache: Record<\n // locale\n string,\n Record<\n // unit\n string,\n Record<\n // unitDisplay\n string,\n Intl.NumberFormat\n >\n >\n> = {};\n\nexport function formatDuration(\n valueInMs: number,\n { locale, significantUnits, unitDisplay = 'narrow' }: DurationFormatOptions\n) {\n numberFormatCache[locale] ??= {};\n\n const sign = valueInMs < 0 ? '-' : '';\n const absMs = Math.abs(valueInMs);\n if (absMs < secondInMs) {\n numberFormatCache[locale].seconds ??= {};\n\n numberFormatCache[locale].seconds.narrow ??= new Intl.NumberFormat(locale, {\n style: 'unit',\n unit: 'second',\n unitDisplay: 'narrow'\n });\n\n return numberFormatCache[locale].seconds.narrow.format(0);\n }\n\n const durationParts = [\n { unit: 'day', value: Math.floor(absMs / dayInMs) },\n { unit: 'hour', value: Math.floor((absMs % dayInMs) / hourInMs) },\n { unit: 'minute', value: Math.floor((absMs % hourInMs) / minuteInMs) },\n { unit: 'second', value: Math.floor((absMs % minuteInMs) / secondInMs) }\n ];\n\n const result = [];\n for (let i = 0; result.length < significantUnits && i < durationParts.length; i += 1) {\n const { value, unit } = durationParts[i];\n\n if (value > 0) {\n numberFormatCache[locale][unit] ??= {};\n numberFormatCache[locale][unit][unitDisplay] ??= new Intl.NumberFormat(locale, {\n style: 'unit',\n unit,\n unitDisplay\n });\n\n result.push(numberFormatCache[locale][unit][unitDisplay].format(value));\n }\n }\n return `${sign}${result.join(' ')}`;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/components/DateTime/utils.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAGlC,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAEL,YAAY,EACZ,UAAU,EACV,cAAc,EACd,OAAO,EACP,WAAW,EACZ,MAAM,eAAe,CAAC;AAEvB,MAAM,SAAS,GAAG;IAChB,IAAI,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,GAAG,GAAG;IAC/B,KAAK,EAAE,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,GAAG,GAAG,CAAC,GAAG,EAAE;IACvC,GAAG,EAAE,EAAE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O,CAAC,GAAG,QAAQ,CAAC,EAAE;QACjE,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,KAAK,GAAG,QAAQ,CAAC,GAAG,UAAU,CAAC,EAAE;QACtE,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,KAAK,GAAG,UAAU,CAAC,GAAG,UAAU,CAAC,EAAE;KACzE,CAAC;IAEF,MAAM,MAAM,GAAG,EAAE,CAAC;IAClB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,GAAG,gBAAgB,IAAI,CAAC,GAAG,aAAa,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE;QACpF,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,aAAa,CAAC,CAAC,CAAC,CAAC;QAEzC,IAAI,KAAK,GAAG,CAAC,EAAE;YACb,iBAAiB,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC;YACvC,iBAAiB,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,WAAW,CAAC,KAAK,IAAI,IAAI,CAAC,YAAY,CAAC,MAAM,EAAE;gBAC7E,KAAK,EAAE,MAAM;gBACb,IAAI;gBACJ,WAAW;aACZ,CAAC,CAAC;YAEH,MAAM,CAAC,IAAI,CAAC,iBAAiB,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,WAAW,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;SACzE;KACF;IACD,OAAO,GAAG,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;AACtC,CAAC","sourcesContent":["import { TranslationFunction, TranslationPack } from '../../i18n';\nimport { ExcludeStrict } from '../../types';\nimport { cap } from '../../utils';\n\nimport { AbsoluteVariant, DateTimeFormat, DateTimeVariant } from './DateTime.types';\nimport { CALENDAR_TYPES } from './Input/local';\nimport {\n ClockFormat,\n getEndOfWeek,\n getQuarter,\n getStartOfWeek,\n getWeek,\n getWeekYear\n} from './Input/utils';\n\nconst unitsInMs = {\n year: 24 * 60 * 60 * 1000 * 365,\n month: (24 * 60 * 60 * 1000 * 365) / 12,\n day: 24 * 60 * 60 * 1000,\n hour: 60 * 60 * 1000,\n minute: 60 * 1000,\n second: 1000\n} satisfies Partial<Record<Intl.RelativeTimeFormatUnit, number>>;\n\ntype TimeUnit = keyof typeof unitsInMs;\n\ntype DateTimeFormatOptions = {\n locale: string;\n format: DateTimeFormat;\n timeZone?: string;\n clockFormat?: ClockFormat;\n calendarType?: string;\n} & (\n | {\n variant: ExcludeStrict<DateTimeVariant, 'quarteryear'>;\n t?: TranslationFunction<TranslationPack>;\n }\n | { variant: 'quarteryear'; t: TranslationFunction<TranslationPack> }\n);\n\ntype TimeOptions = Pick<Intl.DateTimeFormatOptions, 'hour' | 'minute' | 'second' | 'hour12'>;\n\nconst timeShort = {\n hour: 'numeric',\n minute: 'numeric'\n} satisfies TimeOptions;\n\nconst timeShort12 = {\n ...timeShort,\n hour12: true\n} satisfies TimeOptions;\n\nconst timeShort24 = {\n ...timeShort,\n hour12: false\n} satisfies TimeOptions;\n\nconst timeLong = {\n ...timeShort,\n second: 'numeric'\n} satisfies TimeOptions;\n\nconst timeLong12 = {\n ...timeShort12,\n second: 'numeric'\n} satisfies TimeOptions;\n\nconst timeLong24 = {\n ...timeShort24,\n second: 'numeric'\n} satisfies TimeOptions;\n\ntype AddClockFormatToTimeKeys<Key extends DateTimeVariant> = Key extends `${string}time`\n ? `${Key}${'' | 12 | 24}`\n : Key;\n\nconst formatMapping = {\n date: {\n short: { year: 'numeric', month: 'short', day: 'numeric' },\n long: { year: 'numeric', month: 'long', day: 'numeric' },\n numeric: { year: 'numeric', month: 'numeric', day: 'numeric' }\n },\n datetime: {\n short: { year: 'numeric', month: 'short', day: 'numeric', ...timeShort },\n long: { year: 'numeric', month: 'long', day: 'numeric', ...timeLong },\n numeric: { year: 'numeric', month: 'numeric', day: 'numeric', ...timeShort }\n },\n datetime12: {\n short: { year: 'numeric', month: 'short', day: 'numeric', ...timeShort12 },\n long: { year: 'numeric', month: 'long', day: 'numeric', ...timeLong12 },\n numeric: { year: 'numeric', month: 'numeric', day: 'numeric', ...timeShort12 }\n },\n datetime24: {\n short: { year: 'numeric', month: 'short', day: 'numeric', ...timeShort24 },\n long: { year: 'numeric', month: 'long', day: 'numeric', ...timeLong24 },\n numeric: { year: 'numeric', month: 'numeric', day: 'numeric', ...timeShort24 }\n },\n time: {\n short: timeShort,\n long: timeLong,\n numeric: timeShort\n },\n time12: {\n short: timeShort12,\n long: timeLong12,\n numeric: timeShort12\n },\n time24: {\n short: timeShort24,\n long: timeLong24,\n numeric: timeShort24\n },\n month: {\n short: { month: 'short' },\n long: { month: 'long' },\n numeric: { month: 'numeric' }\n },\n monthyear: {\n short: { year: 'numeric', month: 'short' },\n long: { year: 'numeric', month: 'long' },\n numeric: { year: 'numeric', month: 'numeric' }\n },\n week: {\n short: { month: 'short', day: 'numeric' },\n long: { month: 'long', day: 'numeric' },\n numeric: { month: 'numeric', day: 'numeric' }\n },\n year: {\n short: { year: 'numeric' },\n long: { year: 'numeric' },\n numeric: { year: '2-digit' }\n },\n relative: {\n short: { style: 'long', numeric: 'auto' },\n long: { style: 'long', numeric: 'auto' },\n numeric: { style: 'short', numeric: 'auto' }\n }\n} satisfies Record<\n AddClockFormatToTimeKeys<ExcludeStrict<AbsoluteVariant, 'quarteryear'>>,\n Record<DateTimeFormat, Intl.DateTimeFormatOptions>\n> &\n Record<'relative', Record<DateTimeFormat, Intl.RelativeTimeFormatOptions>>;\n\nconst dateTimeFormatCache: Record<\n // locale\n string,\n Record<\n // timeZone\n string,\n Map<Intl.DateTimeFormatOptions, Intl.DateTimeFormat>\n >\n> = {};\n\nconst relativeTimeFormatCache: Record<\n // locale\n string,\n Map<Intl.RelativeTimeFormatOptions, Intl.RelativeTimeFormat>\n> = {};\n\nconst displayNamesCache: Record<\n // locale\n string,\n Intl.DateTimeDisplayNames\n> = {};\n\nexport function formatDateTime(\n value: Date,\n {\n t,\n locale,\n format,\n variant,\n clockFormat,\n calendarType = CALENDAR_TYPES.ISO_8601,\n timeZone\n }: DateTimeFormatOptions\n) {\n const getFormattedDate = (\n date: Date,\n dateVariant: ExcludeStrict<AbsoluteVariant, 'quarteryear'>,\n overrideTimeZone?: string\n ) => {\n const resolvedVariant: AddClockFormatToTimeKeys<typeof dateVariant> =\n dateVariant === 'time' || dateVariant === 'datetime'\n ? `${dateVariant}${clockFormat ?? ''}`\n : dateVariant;\n const resolvedTimeZone = overrideTimeZone ?? timeZone;\n const resolvedOptions = formatMapping[resolvedVariant][format];\n\n dateTimeFormatCache[locale] ??= {};\n dateTimeFormatCache[locale][`${resolvedTimeZone}`] ??= new Map();\n\n const map = dateTimeFormatCache[locale][`${resolvedTimeZone}`];\n\n if (!map.has(resolvedOptions)) {\n map.set(\n resolvedOptions,\n new Intl.DateTimeFormat(locale, {\n ...resolvedOptions,\n timeZone: resolvedTimeZone\n })\n );\n }\n\n return map.get(resolvedOptions)!.format(date);\n };\n\n const relativeTimeFormatter = (relativeValue: number, unit: TimeUnit) => {\n const resolvedOptions = formatMapping.relative[format];\n\n relativeTimeFormatCache[locale] ??= new Map();\n const map = relativeTimeFormatCache[locale];\n\n if (!map.has(resolvedOptions)) {\n map.set(resolvedOptions, new Intl.RelativeTimeFormat(locale, resolvedOptions));\n }\n\n return map.get(resolvedOptions)!.format(relativeValue, unit);\n };\n\n const getUnitsElapsed = (date: Date, unit: TimeUnit): number => {\n let amount: number;\n const now = new Date();\n\n switch (unit) {\n case 'year':\n amount = date.getUTCFullYear() - now.getUTCFullYear();\n break;\n case 'month':\n if (date.getUTCFullYear() === now.getUTCFullYear()) {\n amount = date.getUTCMonth() - now.getUTCMonth();\n } else if (date < now) {\n amount = (11 - date.getUTCMonth() + now.getUTCMonth() + 1) * -1;\n } else {\n amount = 11 - now.getUTCMonth() + date.getUTCMonth() + 1;\n }\n break;\n case 'day':\n if (date.getUTCMonth() === now.getUTCMonth()) {\n amount = date.getUTCDate() - now.getUTCDate();\n } else if (date < now) {\n const maximalDayOfMonth = new Date(\n Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 0)\n ).getUTCDate();\n amount = (maximalDayOfMonth - date.getUTCDate() + now.getUTCDate()) * -1;\n } else {\n const maximalDayOfMonth = new Date(\n Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 0)\n ).getUTCDate();\n amount = maximalDayOfMonth - now.getUTCDate() + date.getUTCDate() + 1;\n }\n break;\n case 'hour':\n if (date.getUTCDate() === now.getUTCDate()) {\n amount = date.getUTCHours() - now.getUTCHours();\n } else if (date < now) {\n amount = (23 - date.getUTCHours() + now.getUTCHours() + 1) * -1;\n } else {\n amount = 23 - now.getUTCHours() + date.getUTCHours() + 1;\n }\n break;\n case 'minute':\n if (date.getUTCHours() === now.getUTCHours()) {\n amount = date.getUTCMinutes() - now.getUTCMinutes();\n } else if (date < now) {\n amount = (59 - date.getUTCMinutes() + now.getUTCMinutes() + 1) * -1;\n } else {\n amount = 59 - now.getUTCMinutes() + date.getUTCMinutes() + 1;\n }\n break;\n default:\n amount = 0;\n break;\n }\n return amount;\n };\n\n const getRelativeTime = (date: Date) => {\n let elapsed = date.getTime() - Date.now();\n // Deliberately reduce precision to 1 minute\n if (Math.abs(elapsed) < 60000) elapsed = 0;\n const unit = (Object.keys(unitsInMs).find(u => Math.abs(elapsed) >= unitsInMs[u as TimeUnit]) ||\n 'second') as TimeUnit;\n const amount = getUnitsElapsed(date, unit);\n\n return relativeTimeFormatter(amount, unit);\n };\n\n const getFormattedWeek = (date: Date) => {\n displayNamesCache[locale] ??= new Intl.DisplayNames(locale, {\n style: 'long',\n type: 'dateTimeField'\n }) as Intl.DateTimeDisplayNames;\n\n const displayNames = displayNamesCache[locale];\n const adjustedUTCDate = new Date(date.getTime() - date.getTimezoneOffset() * 60000);\n const startDate = getFormattedDate(\n getStartOfWeek(adjustedUTCDate, calendarType),\n 'week',\n 'UTC'\n );\n const endDate = getFormattedDate(getEndOfWeek(adjustedUTCDate, calendarType), 'week', 'UTC');\n return `${cap(displayNames.of('weekOfYear'))} ${getWeek(\n adjustedUTCDate,\n calendarType\n )}, ${getWeekYear(adjustedUTCDate)} (${startDate} - ${endDate})`;\n };\n\n const getFormattedQuarterYear = (date: Date) => {\n const formattedYear = getFormattedDate(date, 'year');\n const adjustedUTCDate = new Date(date.getTime() - date.getTimezoneOffset() * 60000);\n const quarterNumber = getQuarter(adjustedUTCDate);\n return `${t!(`date_quarter_q${quarterNumber}`, [formattedYear])}`;\n };\n\n switch (variant) {\n case 'relative':\n return getRelativeTime(value);\n case 'week':\n return getFormattedWeek(value);\n case 'quarteryear':\n return getFormattedQuarterYear(value);\n default:\n return getFormattedDate(value, variant);\n }\n}\n\nconst dayInMs = 24 * 60 * 60 * 1000;\nconst hourInMs = 60 * 60 * 1000;\nconst minuteInMs = 60 * 1000;\nconst secondInMs = 1000;\n\ninterface DurationFormatOptions {\n locale: string;\n significantUnits: 4 | 3 | 2 | 1;\n unitDisplay?: Intl.NumberFormatOptions['unitDisplay'];\n}\n\nconst numberFormatCache: Record<\n // locale\n string,\n Record<\n // unit\n string,\n Record<\n // unitDisplay\n string,\n Intl.NumberFormat\n >\n >\n> = {};\n\nexport function formatDuration(\n valueInMs: number,\n { locale, significantUnits, unitDisplay = 'narrow' }: DurationFormatOptions\n) {\n numberFormatCache[locale] ??= {};\n\n const sign = valueInMs < 0 ? '-' : '';\n const absMs = Math.abs(valueInMs);\n if (absMs < secondInMs) {\n numberFormatCache[locale].seconds ??= {};\n\n numberFormatCache[locale].seconds.narrow ??= new Intl.NumberFormat(locale, {\n style: 'unit',\n unit: 'second',\n unitDisplay: 'narrow'\n });\n\n return numberFormatCache[locale].seconds.narrow.format(0);\n }\n\n const durationParts = [\n { unit: 'day', value: Math.floor(absMs / dayInMs) },\n { unit: 'hour', value: Math.floor((absMs % dayInMs) / hourInMs) },\n { unit: 'minute', value: Math.floor((absMs % hourInMs) / minuteInMs) },\n { unit: 'second', value: Math.floor((absMs % minuteInMs) / secondInMs) }\n ];\n\n const result = [];\n for (let i = 0; result.length < significantUnits && i < durationParts.length; i += 1) {\n const { value, unit } = durationParts[i];\n\n if (value > 0) {\n numberFormatCache[locale][unit] ??= {};\n numberFormatCache[locale][unit][unitDisplay] ??= new Intl.NumberFormat(locale, {\n style: 'unit',\n unit,\n unitDisplay\n });\n\n result.push(numberFormatCache[locale][unit][unitDisplay].format(value));\n }\n }\n return `${sign}${result.join(' ')}`;\n}\n"]}
|
|
@@ -44,7 +44,7 @@ const Drawer = forwardRef(function Drawer(props, ref) {
|
|
|
44
44
|
let prevState = usePrevious(state);
|
|
45
45
|
if (!prevState)
|
|
46
46
|
prevState = state;
|
|
47
|
-
useOuterEvent('mousedown', [drawerRef
|
|
47
|
+
useOuterEvent('mousedown', [drawerRef], useCallback(() => {
|
|
48
48
|
if (open)
|
|
49
49
|
onOuterClick?.();
|
|
50
50
|
}, [open, onOuterClick]));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Drawer.js","sourceRoot":"","sources":["../../../src/components/Drawer/Drawer.tsx"],"names":[],"mappings":";AAAA,OAAO,EACL,SAAS,EAET,WAAW,EAEX,UAAU,EAGV,QAAQ,EACT,MAAM,OAAO,CAAC;AACf,OAAO,MAAM,EAAE,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AAEhD,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE7E,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAsD/C,MAAM,CAAC,MAAM,YAAY,GAAG,MAAM,CAAC,GAAG,CAA0C,KAAK,CAAC,EAAE;IACtF,MAAM,EAAE,KAAK,EAAE,MAAM,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Q,CAAC,SAAS,CAAC,CAAC;SACrB;aAAM,IAAI,IAAI,IAAI,KAAK,KAAK,MAAM,IAAI,SAAS,KAAK,MAAM,EAAE;YAC3D,WAAW,EAAE,EAAE,CAAC;SACjB;aAAM,IAAI,CAAC,IAAI,IAAI,KAAK,KAAK,QAAQ,IAAI,SAAS,KAAK,QAAQ,EAAE;YAChE,YAAY,EAAE,EAAE,CAAC;SAClB;IACH,CAAC,EAAE,CAAC,IAAI,EAAE,KAAK,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,WAAW,EAAE,YAAY,CAAC,CAAC,CAAC;IAErF,MAAM,eAAe,GAAG,WAAW,CACjC,CAAC,CAAkB,EAAQ,EAAE;QAC3B,IAAI,CAAC,CAAC,MAAM,KAAK,SAAS,CAAC,OAAO,IAAI,CAAC,CAAC,YAAY,KAAK,WAAW;YAAE,OAAO;QAC7E,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC;IACrC,CAAC,EACD,CAAC,IAAI,CAAC,CACP,CAAC;IAEF,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,IAAI,IAAI,cAAc,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAC5D,KAAC,YAAY,IACX,GAAG,EAAE,SAAS,EACd,QAAQ,EAAE,QAAQ,EAClB,MAAM,EAAE,MAAM,IAAI,IAAI,EACtB,eAAe,EAAE,eAAe,EAChC,SAAS,EAAE,SAAS,EACpB,IAAI,EAAE,IAAI,EACV,IAAI,EAAE,IAAI,EACV,KAAK,EAAE,KAAK,EACZ,eAAe,EAAE,eAAe,KAC5B,SAAS,YAEZ,QAAQ,GACI,CAChB,CAAC;AACJ,CAAC,CAAC,CAAC;AAEH,eAAe,MAAM,CAAC","sourcesContent":["import {\n useEffect,\n Ref,\n useCallback,\n FunctionComponent,\n forwardRef,\n ReactNode,\n TransitionEvent,\n useState\n} from 'react';\nimport styled, { css } from 'styled-components';\n\nimport { useOuterEvent, useConsolidatedRef, usePrevious } from '../../hooks';\nimport { AsProp, BaseProps, ForwardProps } from '../../types';\nimport { reflow } from '../../utils';\nimport { defaultThemeProp } from '../../theme';\n\nexport interface DrawerProps extends AsProp, BaseProps {\n /**\n * If true, the Drawer will be visible.\n * @default false\n */\n open: boolean;\n /** Content of the Drawer. */\n children?: ReactNode;\n /**\n * Determines whether a drop shadow should be visible along the edge of the Drawer for contrast purposes.\n * @default false\n */\n shadow?: boolean;\n /**\n * Used to determine which side of the viewport the Drawer should open from.\n * @default 'right'\n */\n placement?: 'top' | 'right' | 'bottom' | 'left';\n /**\n * The position of the Drawer.\n * @default 'absolute'\n */\n position?: 'absolute' | 'fixed';\n /**\n * Determines the speed of the transition. This value comes from `theme.base.animation.speed`.\n * @default '0.25s'\n */\n transitionSpeed?: string;\n /**\n * The width or height that the Drawer will open to, depending on its placement.\n * @default '100%'\n */\n size?: string;\n /** Callback fired after Drawer opens. */\n onAfterOpen?: () => void;\n /** Callback fired after Drawer closes. */\n onAfterClose?: () => void;\n /** Callback fired before Drawer opens. */\n onBeforeOpen?: () => void;\n /** Callback fired before Drawer closes. */\n onBeforeClose?: () => void;\n /** Callback fired when a click action occurs outside of the Drawer. */\n onOuterClick?: () => void;\n /**\n * If true, removes the component from the real DOM when closed. For full virtual DOM unmount(if necessary), perform at a parent level.\n * @default false\n */\n nullWhenClosed?: boolean;\n}\n\ntype State = 'open' | 'closed' | 'opening' | 'closing';\n\nexport const StyledDrawer = styled.div<Partial<DrawerProps & { state: State }>>(props => {\n const { state, shadow, position, placement, transitionSpeed, size, theme } = props;\n let dimension = 'horizontal';\n let axis = 'X';\n let anchor = 'top';\n\n if (placement === 'top' || placement === 'bottom') {\n dimension = 'vertical';\n axis = 'Y';\n anchor = 'left';\n }\n\n const translate = state === 'open' || state === 'opening' ? 0 : '100%';\n const speed = transitionSpeed || theme.base.animation.speed;\n\n return css`\n z-index: ${theme.base['z-index'].drawer};\n position: ${position};\n ${placement}: 0;\n ${anchor}: 0;\n height: ${dimension === 'vertical' ? size : '100%'};\n width: ${dimension === 'horizontal' ? size : '100%'};\n transition-property: transform, box-shadow, opacity;\n transition-duration: max(${speed}, 0.0001s);\n transition-timing-function: ${theme.base.animation.timing.ease};\n transform: ${state === 'open'\n ? 'none'\n : `translate${axis}(${placement === 'top' || placement === 'left' ? '-' : ''}${translate})`};\n\n ${shadow &&\n css`\n box-shadow: ${theme.base.shadow.high};\n `}\n `;\n});\n\nStyledDrawer.defaultProps = defaultThemeProp;\n\nconst Drawer: FunctionComponent<DrawerProps & ForwardProps> = forwardRef(function Drawer(\n props: DrawerProps,\n ref: Ref<HTMLElement>\n) {\n const {\n open = false,\n shadow = false,\n position = 'absolute',\n children,\n placement = 'right',\n transitionSpeed,\n size = '100%',\n onAfterOpen,\n onAfterClose,\n onBeforeOpen,\n onBeforeClose,\n onOuterClick,\n nullWhenClosed = false,\n ...restProps\n } = props;\n\n const drawerRef = useConsolidatedRef(ref);\n\n const [state, setState] = useState<State>(open ? 'open' : 'closed');\n\n let prevState = usePrevious(state);\n if (!prevState) prevState = state;\n\n useOuterEvent(\n 'mousedown',\n [drawerRef],\n useCallback(() => {\n if (open) onOuterClick?.();\n }, [open, onOuterClick])\n );\n\n useEffect(() => {\n if (open && (state === 'closed' || state === 'closing')) {\n onBeforeOpen?.();\n reflow(drawerRef.current);\n setState('opening');\n } else if (!open && (state === 'open' || state === 'opening')) {\n onBeforeClose?.();\n setState('closing');\n } else if (open && state === 'open' && prevState !== 'open') {\n onAfterOpen?.();\n } else if (!open && state === 'closed' && prevState !== 'closed') {\n onAfterClose?.();\n }\n }, [open, state, prevState, onBeforeOpen, onBeforeClose, onAfterOpen, onAfterClose]);\n\n const onTransitionEnd = useCallback(\n (e: TransitionEvent): void => {\n if (e.target !== drawerRef.current || e.propertyName !== 'transform') return;\n setState(open ? 'open' : 'closed');\n },\n [open]\n );\n\n return state === 'closed' && !open && nullWhenClosed ? null : (\n <StyledDrawer\n ref={drawerRef}\n position={position}\n shadow={shadow && open}\n transitionSpeed={transitionSpeed}\n placement={placement}\n size={size}\n open={open}\n state={state}\n onTransitionEnd={onTransitionEnd}\n {...restProps}\n >\n {children}\n </StyledDrawer>\n );\n});\n\nexport default Drawer;\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"FileInput.d.ts","sourceRoot":"","sources":["../../../src/components/File/FileInput.tsx"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EACjB,GAAG,EAOJ,MAAM,OAAO,CAAC;AAIf,OAAO,EACL,SAAS,EACT,YAAY,EACZ,cAAc,EAEd,UAAU,EACX,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"FileInput.d.ts","sourceRoot":"","sources":["../../../src/components/File/FileInput.tsx"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EACjB,GAAG,EAOJ,MAAM,OAAO,CAAC;AAIf,OAAO,EACL,SAAS,EACT,YAAY,EACZ,cAAc,EAEd,UAAU,EACX,MAAM,aAAa,CAAC;AASrB,OAAoB,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAU/D,OAAuB,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAOvE,MAAM,WAAW,cAAe,SAAQ,SAAS,EAAE,cAAc,EAAE,UAAU;IAC3E,qEAAqE;IACrE,YAAY,CAAC,EAAE,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,IAAI,CAAC;IACvC;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,iDAAiD;IACjD,KAAK,CAAC,EAAE,mBAAmB,EAAE,CAAC;IAC9B;;;OAGG;IACH,EAAE,CAAC,EAAE,gBAAgB,CAAC,IAAI,CAAC,CAAC;IAC5B,oDAAoD;IACpD,MAAM,CAAC,EAAE,gBAAgB,CAAC,QAAQ,CAAC,CAAC;IACpC,2DAA2D;IAC3D,KAAK,CAAC,EAAE,gBAAgB,CAAC,OAAO,CAAC,CAAC;IAClC,uCAAuC;IACvC,WAAW,CAAC,EAAE,gBAAgB,CAAC,aAAa,CAAC,CAAC;IAC9C,6GAA6G;IAC7G,IAAI,CAAC,EAAE,gBAAgB,CAAC,MAAM,CAAC,CAAC;IAChC,wEAAwE;IACxE,QAAQ,CAAC,EAAE,gBAAgB,CAAC,UAAU,CAAC,CAAC;IACxC,0DAA0D;IAC1D,QAAQ,CAAC,EAAE,gBAAgB,CAAC,UAAU,CAAC,CAAC;IACxC,+FAA+F;IAC/F,IAAI,CAAC,EAAE,gBAAgB,CAAC,MAAM,CAAC,CAAC;IAChC,sEAAsE;IACtE,GAAG,CAAC,EAAE,GAAG,CAAC,gBAAgB,CAAC,CAAC;CAC7B;AAED,eAAO,MAAM,cAAc;cAAmC,OAAO;SAYnE,CAAC;AAEH,eAAO,MAAM,eAAe,wMAkB3B,CAAC;;;;AA0JF,wBAA2D"}
|
|
@@ -2,7 +2,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
|
2
2
|
import { forwardRef, useCallback, useState } from 'react';
|
|
3
3
|
import styled, { css } from 'styled-components';
|
|
4
4
|
import { hideVisually } from 'polished';
|
|
5
|
-
import { useConsolidatedRef, useI18n, useUID, useDirection, useTestIds } from '../../hooks';
|
|
5
|
+
import { useConsolidatedRef, useI18n, useUID, useDirection, useTestIds, useTheme } from '../../hooks';
|
|
6
6
|
import FormControl from '../FormControl';
|
|
7
7
|
import { defaultThemeProp } from '../../theme';
|
|
8
8
|
import Flex from '../Flex';
|
|
@@ -55,6 +55,7 @@ StyledInteractiveText.defaultProps = defaultThemeProp;
|
|
|
55
55
|
const FileInput = forwardRef(function FileInput(props, ref) {
|
|
56
56
|
const uid = useUID();
|
|
57
57
|
const { testId, id = uid, label, labelHidden, info, required = false, disabled = false, files, onFilesAdded, multiple = false, status, ...restProps } = props;
|
|
58
|
+
const { base: { 'content-width': { md } } } = useTheme();
|
|
58
59
|
const testIds = useTestIds(testId, getFileInputTestIds);
|
|
59
60
|
const icon = _jsx(Icon, { name: 'paper-clip' });
|
|
60
61
|
const inputRef = useConsolidatedRef(ref);
|
|
@@ -99,7 +100,7 @@ const FileInput = forwardRef(function FileInput(props, ref) {
|
|
|
99
100
|
status
|
|
100
101
|
}, children: fileInput })) : (fileInput), !!files?.length && (_jsx(Grid, { "data-testid": testIds.files, container: {
|
|
101
102
|
gap: 1,
|
|
102
|
-
cols:
|
|
103
|
+
cols: `repeat(auto-fill, minmax(min(${md}, 100%), 1fr));`
|
|
103
104
|
}, as: 'ul', children: files.map((file, index) => {
|
|
104
105
|
const key = file.id ?? (file.File ? `${file.File.name}_${file.File.lastModified}` : index);
|
|
105
106
|
// When files is an array of native File objects, all properties (including name) are on the prototype, so spreading will not set any props.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"FileInput.js","sourceRoot":"","sources":["../../../src/components/File/FileInput.tsx"],"names":[],"mappings":";AAAA,OAAO,EAGL,UAAU,EAEV,WAAW,EAGX,QAAQ,EACT,MAAM,OAAO,CAAC;AACf,OAAO,MAAM,EAAE,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AASxC,OAAO,EAAE,kBAAkB,EAAE,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC5F,OAAO,WAAiC,MAAM,gBAAgB,CAAC;AAC/D,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,IAAI,MAAM,SAAS,CAAC;AAC3B,OAAO,IAAI,MAAM,SAAS,CAAC;AAC3B,OAAO,IAAI,EAAE,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAC7C,OAAO,KAAK,aAAa,MAAM,+BAA+B,CAAC;AAC/D,OAAO,SAAS,MAAM,cAAc,CAAC;AACrC,OAAO,IAAI,MAAM,SAAS,CAAC;AAC3B,OAAO,EAAE,WA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,EACA,CAAC,CAAC,KAAK,EAAE,MAAM,IAAI,CAClB,KAAC,IAAI,mBACU,OAAO,CAAC,KAAK,EAC1B,SAAS,EAAE;oBACT,GAAG,EAAE,CAAC;oBACN,IAAI,EAAE,2BAA2B;iBAClC,EACD,EAAE,EAAC,IAAI,YAEN,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE;oBACzB,MAAM,GAAG,GACP,IAAI,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;oBAEjF,4IAA4I;oBAC5I,OAAO,KAAC,cAAc,OAAe,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,IAA9B,GAAG,CAA+B,CAAC;gBACjE,CAAC,CAAC,GACG,CACR,IACI,CACR,CAAC;AACJ,CAAC,CAAC,CAAC;AAEH,eAAe,WAAW,CAAC,SAAS,EAAE,mBAAmB,CAAC,CAAC","sourcesContent":["import {\n FunctionComponent,\n Ref,\n forwardRef,\n ChangeEvent,\n useCallback,\n PropsWithoutRef,\n DragEvent,\n useState\n} from 'react';\nimport styled, { css } from 'styled-components';\nimport { hideVisually } from 'polished';\n\nimport {\n BaseProps,\n ForwardProps,\n NoChildrenProp,\n PropsWithDefaults,\n TestIdProp\n} from '../../types';\nimport { useConsolidatedRef, useI18n, useUID, useDirection, useTestIds } from '../../hooks';\nimport FormControl, { FormControlProps } from '../FormControl';\nimport { defaultThemeProp } from '../../theme';\nimport Flex from '../Flex';\nimport Text from '../Text';\nimport Icon, { registerIcon } from '../Icon';\nimport * as paperClipIcon from '../Icon/icons/paper-clip.icon';\nimport FormField from '../FormField';\nimport Grid from '../Grid';\nimport { withTestIds } from '../../utils';\n\nimport FileUploadItem, { FileUploadItemProps } from './FileUploadItem';\nimport { getFileInputTestIds } from './File.test-ids';\n\nregisterIcon(paperClipIcon);\n\ntype FileInputPropsWithDefaults = PropsWithDefaults<FileInputProps>;\n\nexport interface FileInputProps extends BaseProps, NoChildrenProp, TestIdProp {\n /** Called when files are added either via the input or drop zone. */\n onFilesAdded?: (files: File[]) => void;\n /**\n * Allow multiple files to be selected from the OS specific file browser.\n * NOTE: This does not restrict multiple files from being added via drag and drop.\n * Restrict multi file drag and drop via onFilesAdded and custom info message.\n * @default false\n */\n multiple?: boolean;\n /** An array of files that have been uploaded. */\n files?: FileUploadItemProps[];\n /**\n * Sets DOM id for the control and associates label element via 'for' attribute.\n * If an id is not pass, a random id will be generated for any render.\n */\n id?: FormControlProps['id'];\n /** Set visual state based on a validation state. */\n status?: FormControlProps['status'];\n /** Pass a string or a fragment with an Icon and string. */\n label?: FormControlProps['label'];\n /** Visually hides the label region. */\n labelHidden?: FormControlProps['labelHidden'];\n /** It is recommended to pass a simple string to offer guidance. Text will be styled based on status prop. */\n info?: FormControlProps['info'];\n /** Indicate if the field is required. The browser defaults to false. */\n required?: FormControlProps['required'];\n /** Disable the control. The browser defaults to false. */\n disabled?: FormControlProps['disabled'];\n /** Sets html name attribute for the underlying control. Useful for mapping to a data field. */\n name?: FormControlProps['name'];\n /** Ref for the input element within the component's dom structure. */\n ref?: Ref<HTMLInputElement>;\n}\n\nexport const StyledDropZone = styled(FormControl)<{ dragOver: boolean }>(({ dragOver, theme }) => {\n return css`\n padding: calc(2 * ${theme.base.spacing});\n min-height: 4rem;\n border-style: dashed;\n cursor: pointer;\n\n ${dragOver &&\n css`\n border-style: solid;\n `}\n `;\n});\n\nexport const StyledFileInput = styled.div<FileInputPropsWithDefaults & ForwardProps>(\n ({ theme }) => {\n return css`\n position: relative;\n\n input {\n ${hideVisually}\n }\n\n input:enabled:focus + ${StyledDropZone} {\n box-shadow: ${theme.components['form-control'][':focus']['box-shadow']};\n }\n\n input[hidden] + ${StyledDropZone} {\n display: none;\n }\n `;\n }\n);\n\nStyledFileInput.defaultProps = defaultThemeProp;\n\nconst StyledInteractiveText = styled.span(({ theme }) => {\n return css`\n color: ${theme.base.palette.interactive};\n `;\n});\n\nStyledInteractiveText.defaultProps = defaultThemeProp;\n\nconst FileInput: FunctionComponent<FileInputProps & ForwardProps> = forwardRef(function FileInput(\n props: PropsWithoutRef<FileInputProps>,\n ref: FileInputProps['ref']\n) {\n const uid = useUID();\n const {\n testId,\n id = uid,\n label,\n labelHidden,\n info,\n required = false,\n disabled = false,\n files,\n onFilesAdded,\n multiple = false,\n status,\n ...restProps\n } = props;\n\n const testIds = useTestIds(testId, getFileInputTestIds);\n\n const icon = <Icon name='paper-clip' />;\n const inputRef = useConsolidatedRef(ref);\n\n const onChange = useCallback(\n (e: ChangeEvent<HTMLInputElement>) => {\n if (e.target.files) {\n onFilesAdded?.(Array.from(e.target.files));\n }\n /**\n * WHY are we doing this?\n * We are not working with the \"value\" prop of the input but rather the File instances that are created.\n * The consumer of this component should manage an array or File(s) and allow for a user to remove a selected file.\n * Since we can not modify the input value of files for browser security reasons,\n * and since setting the files property is less than ideal, we reset/toggle the input to a fresh state after a render.\n * This enables onChange to fire even if the user had just previously selected a file, removed it, and selected it again.\n */\n if (inputRef.current) inputRef.current.value = '';\n },\n [onFilesAdded]\n );\n\n const t = useI18n();\n const [dragOver, setDragOver] = useState(false);\n const { ltr, rtl } = useDirection();\n\n const fileInput = (\n <StyledFileInput>\n <input\n data-testid={testIds.control}\n {...restProps}\n ref={inputRef}\n type='file'\n id={id}\n disabled={disabled}\n onChange={onChange}\n multiple={multiple}\n />\n <Flex\n container={{ alignItems: 'center', justify: 'center' }}\n item={{ grow: 1 }}\n as={StyledDropZone}\n dragOver={dragOver}\n onClick={() => {\n inputRef.current?.focus();\n inputRef.current?.click();\n }}\n onDragOver={(e: DragEvent<HTMLDivElement>) => {\n e.preventDefault();\n }}\n onDragEnter={() => setDragOver(true)}\n onDragLeave={() => setDragOver(false)}\n onDrop={(e: DragEvent<HTMLDivElement>) => {\n e.preventDefault();\n setDragOver(false);\n onFilesAdded?.(Array.from(e.dataTransfer.files));\n }}\n >\n {ltr && icon}\n <Text variant='primary'>\n \n {t('file_upload_text_main', [\n <StyledInteractiveText>\n {t(multiple ? 'file_upload_text_multiple' : 'file_upload_text_one')}\n </StyledInteractiveText>\n ])}\n \n </Text>\n {rtl && icon}\n </Flex>\n </StyledFileInput>\n );\n\n return (\n <Grid container={{ rowGap: 1 }}>\n {label ? (\n <FormField\n {...{\n testId: testIds,\n label,\n labelHidden,\n id,\n info,\n required,\n disabled,\n status\n }}\n >\n {fileInput}\n </FormField>\n ) : (\n fileInput\n )}\n {!!files?.length && (\n <Grid\n data-testid={testIds.files}\n container={{\n gap: 1,\n cols: 'repeat(2, minmax(0, 1fr))'\n }}\n as='ul'\n >\n {files.map((file, index) => {\n const key =\n file.id ?? (file.File ? `${file.File.name}_${file.File.lastModified}` : index);\n\n // When files is an array of native File objects, all properties (including name) are on the prototype, so spreading will not set any props.\n return <FileUploadItem key={key} {...file} name={file.name} />;\n })}\n </Grid>\n )}\n </Grid>\n );\n});\n\nexport default withTestIds(FileInput, getFileInputTestIds);\n"]}
|
|
1
|
+
{"version":3,"file":"FileInput.js","sourceRoot":"","sources":["../../../src/components/File/FileInput.tsx"],"names":[],"mappings":";AAAA,OAAO,EAGL,UAAU,EAEV,WAAW,EAGX,QAAQ,EACT,MAAM,OAAO,CAAC;AACf,OAAO,MAAM,EAAE,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AASxC,OAAO,EACL,kBAAkB,EAClB,OAAO,EACP,MAAM,EACN,YAAY,EACZ,UAAU,EACV,QAAQ,EACT,MAAM,aAAa,CAAC;AACrB,OAAO,WAAiC,MAAM,gBAAgB,CAAC;AAC/D,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,IAAI,MAAM,SAAS,CAAC;AAC3B,OAAO,IAAI,MAAM,S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CACnB,CAAC;IAEF,OAAO,CACL,MAAC,IAAI,IAAC,SAAS,EAAE,EAAE,MAAM,EAAE,CAAC,EAAE,aAC3B,KAAK,CAAC,CAAC,CAAC,CACP,KAAC,SAAS,OACJ;oBACF,MAAM,EAAE,OAAO;oBACf,KAAK;oBACL,WAAW;oBACX,EAAE;oBACF,IAAI;oBACJ,QAAQ;oBACR,QAAQ;oBACR,MAAM;iBACP,YAEA,SAAS,GACA,CACb,CAAC,CAAC,CAAC,CACF,SAAS,CACV,EACA,CAAC,CAAC,KAAK,EAAE,MAAM,IAAI,CAClB,KAAC,IAAI,mBACU,OAAO,CAAC,KAAK,EAC1B,SAAS,EAAE;oBACT,GAAG,EAAE,CAAC;oBACN,IAAI,EAAE,gCAAgC,EAAE,iBAAiB;iBAC1D,EACD,EAAE,EAAC,IAAI,YAEN,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE;oBACzB,MAAM,GAAG,GACP,IAAI,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;oBAEjF,4IAA4I;oBAC5I,OAAO,KAAC,cAAc,OAAe,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,IAA9B,GAAG,CAA+B,CAAC;gBACjE,CAAC,CAAC,GACG,CACR,IACI,CACR,CAAC;AACJ,CAAC,CAAC,CAAC;AAEH,eAAe,WAAW,CAAC,SAAS,EAAE,mBAAmB,CAAC,CAAC","sourcesContent":["import {\n FunctionComponent,\n Ref,\n forwardRef,\n ChangeEvent,\n useCallback,\n PropsWithoutRef,\n DragEvent,\n useState\n} from 'react';\nimport styled, { css } from 'styled-components';\nimport { hideVisually } from 'polished';\n\nimport {\n BaseProps,\n ForwardProps,\n NoChildrenProp,\n PropsWithDefaults,\n TestIdProp\n} from '../../types';\nimport {\n useConsolidatedRef,\n useI18n,\n useUID,\n useDirection,\n useTestIds,\n useTheme\n} from '../../hooks';\nimport FormControl, { FormControlProps } from '../FormControl';\nimport { defaultThemeProp } from '../../theme';\nimport Flex from '../Flex';\nimport Text from '../Text';\nimport Icon, { registerIcon } from '../Icon';\nimport * as paperClipIcon from '../Icon/icons/paper-clip.icon';\nimport FormField from '../FormField';\nimport Grid from '../Grid';\nimport { withTestIds } from '../../utils';\n\nimport FileUploadItem, { FileUploadItemProps } from './FileUploadItem';\nimport { getFileInputTestIds } from './File.test-ids';\n\nregisterIcon(paperClipIcon);\n\ntype FileInputPropsWithDefaults = PropsWithDefaults<FileInputProps>;\n\nexport interface FileInputProps extends BaseProps, NoChildrenProp, TestIdProp {\n /** Called when files are added either via the input or drop zone. */\n onFilesAdded?: (files: File[]) => void;\n /**\n * Allow multiple files to be selected from the OS specific file browser.\n * NOTE: This does not restrict multiple files from being added via drag and drop.\n * Restrict multi file drag and drop via onFilesAdded and custom info message.\n * @default false\n */\n multiple?: boolean;\n /** An array of files that have been uploaded. */\n files?: FileUploadItemProps[];\n /**\n * Sets DOM id for the control and associates label element via 'for' attribute.\n * If an id is not pass, a random id will be generated for any render.\n */\n id?: FormControlProps['id'];\n /** Set visual state based on a validation state. */\n status?: FormControlProps['status'];\n /** Pass a string or a fragment with an Icon and string. */\n label?: FormControlProps['label'];\n /** Visually hides the label region. */\n labelHidden?: FormControlProps['labelHidden'];\n /** It is recommended to pass a simple string to offer guidance. Text will be styled based on status prop. */\n info?: FormControlProps['info'];\n /** Indicate if the field is required. The browser defaults to false. */\n required?: FormControlProps['required'];\n /** Disable the control. The browser defaults to false. */\n disabled?: FormControlProps['disabled'];\n /** Sets html name attribute for the underlying control. Useful for mapping to a data field. */\n name?: FormControlProps['name'];\n /** Ref for the input element within the component's dom structure. */\n ref?: Ref<HTMLInputElement>;\n}\n\nexport const StyledDropZone = styled(FormControl)<{ dragOver: boolean }>(({ dragOver, theme }) => {\n return css`\n padding: calc(2 * ${theme.base.spacing});\n min-height: 4rem;\n border-style: dashed;\n cursor: pointer;\n\n ${dragOver &&\n css`\n border-style: solid;\n `}\n `;\n});\n\nexport const StyledFileInput = styled.div<FileInputPropsWithDefaults & ForwardProps>(\n ({ theme }) => {\n return css`\n position: relative;\n\n input {\n ${hideVisually}\n }\n\n input:enabled:focus + ${StyledDropZone} {\n box-shadow: ${theme.components['form-control'][':focus']['box-shadow']};\n }\n\n input[hidden] + ${StyledDropZone} {\n display: none;\n }\n `;\n }\n);\n\nStyledFileInput.defaultProps = defaultThemeProp;\n\nconst StyledInteractiveText = styled.span(({ theme }) => {\n return css`\n color: ${theme.base.palette.interactive};\n `;\n});\n\nStyledInteractiveText.defaultProps = defaultThemeProp;\n\nconst FileInput: FunctionComponent<FileInputProps & ForwardProps> = forwardRef(function FileInput(\n props: PropsWithoutRef<FileInputProps>,\n ref: FileInputProps['ref']\n) {\n const uid = useUID();\n const {\n testId,\n id = uid,\n label,\n labelHidden,\n info,\n required = false,\n disabled = false,\n files,\n onFilesAdded,\n multiple = false,\n status,\n ...restProps\n } = props;\n\n const {\n base: {\n 'content-width': { md }\n }\n } = useTheme();\n\n const testIds = useTestIds(testId, getFileInputTestIds);\n\n const icon = <Icon name='paper-clip' />;\n const inputRef = useConsolidatedRef(ref);\n\n const onChange = useCallback(\n (e: ChangeEvent<HTMLInputElement>) => {\n if (e.target.files) {\n onFilesAdded?.(Array.from(e.target.files));\n }\n /**\n * WHY are we doing this?\n * We are not working with the \"value\" prop of the input but rather the File instances that are created.\n * The consumer of this component should manage an array or File(s) and allow for a user to remove a selected file.\n * Since we can not modify the input value of files for browser security reasons,\n * and since setting the files property is less than ideal, we reset/toggle the input to a fresh state after a render.\n * This enables onChange to fire even if the user had just previously selected a file, removed it, and selected it again.\n */\n if (inputRef.current) inputRef.current.value = '';\n },\n [onFilesAdded]\n );\n\n const t = useI18n();\n const [dragOver, setDragOver] = useState(false);\n const { ltr, rtl } = useDirection();\n\n const fileInput = (\n <StyledFileInput>\n <input\n data-testid={testIds.control}\n {...restProps}\n ref={inputRef}\n type='file'\n id={id}\n disabled={disabled}\n onChange={onChange}\n multiple={multiple}\n />\n <Flex\n container={{ alignItems: 'center', justify: 'center' }}\n item={{ grow: 1 }}\n as={StyledDropZone}\n dragOver={dragOver}\n onClick={() => {\n inputRef.current?.focus();\n inputRef.current?.click();\n }}\n onDragOver={(e: DragEvent<HTMLDivElement>) => {\n e.preventDefault();\n }}\n onDragEnter={() => setDragOver(true)}\n onDragLeave={() => setDragOver(false)}\n onDrop={(e: DragEvent<HTMLDivElement>) => {\n e.preventDefault();\n setDragOver(false);\n onFilesAdded?.(Array.from(e.dataTransfer.files));\n }}\n >\n {ltr && icon}\n <Text variant='primary'>\n \n {t('file_upload_text_main', [\n <StyledInteractiveText>\n {t(multiple ? 'file_upload_text_multiple' : 'file_upload_text_one')}\n </StyledInteractiveText>\n ])}\n \n </Text>\n {rtl && icon}\n </Flex>\n </StyledFileInput>\n );\n\n return (\n <Grid container={{ rowGap: 1 }}>\n {label ? (\n <FormField\n {...{\n testId: testIds,\n label,\n labelHidden,\n id,\n info,\n required,\n disabled,\n status\n }}\n >\n {fileInput}\n </FormField>\n ) : (\n fileInput\n )}\n {!!files?.length && (\n <Grid\n data-testid={testIds.files}\n container={{\n gap: 1,\n cols: `repeat(auto-fill, minmax(min(${md}, 100%), 1fr));`\n }}\n as='ul'\n >\n {files.map((file, index) => {\n const key =\n file.id ?? (file.File ? `${file.File.name}_${file.File.lastModified}` : index);\n\n // When files is an array of native File objects, all properties (including name) are on the prototype, so spreading will not set any props.\n return <FileUploadItem key={key} {...file} name={file.name} />;\n })}\n </Grid>\n )}\n </Grid>\n );\n});\n\nexport default withTestIds(FileInput, getFileInputTestIds);\n"]}
|
|
@@ -3,7 +3,7 @@ export declare const StyledViewSelector: import("styled-components").StyledCompo
|
|
|
3
3
|
required: boolean;
|
|
4
4
|
}, never>;
|
|
5
5
|
export declare const StyledListToolbar: import("styled-components").StyledComponent<"div", import("styled-components").DefaultTheme, {}, never>;
|
|
6
|
-
export declare const StyledListToolbarDialog: import("styled-components").StyledComponent<import("react").FC<import("../Dialog").FormDialogProps & Pick<import("react").HTMLAttributes<HTMLDivElement>, "hidden" | "color" | "style" | "translate" | "prefix" | "slot" | "title" | "children" | "defaultChecked" | "defaultValue" | "suppressContentEditableWarning" | "suppressHydrationWarning" | "accessKey" | "className" | "contentEditable" | "contextMenu" | "dir" | "draggable" | "id" | "lang" | "placeholder" | "spellCheck" | "tabIndex" | "radioGroup" | "role" | "about" | "datatype" | "inlist" | "property" | "resource" | "typeof" | "vocab" | "autoCapitalize" | "autoCorrect" | "autoSave" | "itemProp" | "itemScope" | "itemType" | "itemID" | "itemRef" | "results" | "security" | "unselectable" | "inputMode" | "is" | "aria-activedescendant" | "aria-atomic" | "aria-autocomplete" | "aria-busy" | "aria-checked" | "aria-colcount" | "aria-colindex" | "aria-colspan" | "aria-controls" | "aria-current" | "aria-describedby" | "aria-details" | "aria-disabled" | "aria-dropeffect" | "aria-errormessage" | "aria-expanded" | "aria-flowto" | "aria-grabbed" | "aria-haspopup" | "aria-hidden" | "aria-invalid" | "aria-keyshortcuts" | "aria-label" | "aria-labelledby" | "aria-level" | "aria-live" | "aria-modal" | "aria-multiline" | "aria-multiselectable" | "aria-orientation" | "aria-owns" | "aria-placeholder" | "aria-posinset" | "aria-pressed" | "aria-readonly" | "aria-relevant" | "aria-required" | "aria-roledescription" | "aria-rowcount" | "aria-rowindex" | "aria-rowspan" | "aria-selected" | "aria-setsize" | "aria-sort" | "aria-valuemax" | "aria-valuemin" | "aria-valuenow" | "aria-valuetext" | "dangerouslySetInnerHTML" | "onCopy" | "onCopyCapture" | "onCut" | "onCutCapture" | "onPaste" | "onPasteCapture" | "onCompositionEnd" | "onCompositionEndCapture" | "onCompositionStart" | "onCompositionStartCapture" | "onCompositionUpdate" | "onCompositionUpdateCapture" | "onFocus" | "onFocusCapture" | "onBlur" | "onBlurCapture" | "onChange" | "onChangeCapture" | "onBeforeInput" | "onBeforeInputCapture" | "onInput" | "onInputCapture" | "onReset" | "onResetCapture" | "onSubmitCapture" | "onInvalid" | "onInvalidCapture" | "onLoad" | "onLoadCapture" | "onError" | "onErrorCapture" | "onKeyDown" | "onKeyDownCapture" | "onKeyPress" | "onKeyPressCapture" | "onKeyUp" | "onKeyUpCapture" | "onAbort" | "onAbortCapture" | "onCanPlay" | "onCanPlayCapture" | "onCanPlayThrough" | "onCanPlayThroughCapture" | "onDurationChange" | "onDurationChangeCapture" | "onEmptied" | "onEmptiedCapture" | "onEncrypted" | "onEncryptedCapture" | "onEnded" | "onEndedCapture" | "onLoadedData" | "onLoadedDataCapture" | "onLoadedMetadata" | "onLoadedMetadataCapture" | "onLoadStart" | "onLoadStartCapture" | "onPause" | "onPauseCapture" | "onPlay" | "onPlayCapture" | "onPlaying" | "onPlayingCapture" | "onProgress" | "onProgressCapture" | "onRateChange" | "onRateChangeCapture" | "onSeeked" | "onSeekedCapture" | "onSeeking" | "onSeekingCapture" | "onStalled" | "onStalledCapture" | "onSuspend" | "onSuspendCapture" | "onTimeUpdate" | "onTimeUpdateCapture" | "onVolumeChange" | "onVolumeChangeCapture" | "onWaiting" | "onWaitingCapture" | "onAuxClick" | "onAuxClickCapture" | "onClick" | "onClickCapture" | "onContextMenu" | "onContextMenuCapture" | "onDoubleClick" | "onDoubleClickCapture" | "onDrag" | "onDragCapture" | "onDragEnd" | "onDragEndCapture" | "onDragEnter" | "onDragEnterCapture" | "onDragExit" | "onDragExitCapture" | "onDragLeave" | "onDragLeaveCapture" | "onDragOver" | "onDragOverCapture" | "onDragStart" | "onDragStartCapture" | "onDrop" | "onDropCapture" | "onMouseDown" | "onMouseDownCapture" | "onMouseEnter" | "onMouseLeave" | "onMouseMove" | "onMouseMoveCapture" | "onMouseOut" | "onMouseOutCapture" | "onMouseOver" | "onMouseOverCapture" | "onMouseUp" | "onMouseUpCapture" | "onSelect" | "onSelectCapture" | "onTouchCancel" | "onTouchCancelCapture" | "onTouchEnd" | "onTouchEndCapture" | "onTouchMove" | "onTouchMoveCapture" | "onTouchStart" | "onTouchStartCapture" | "onPointerDown" | "onPointerDownCapture" | "onPointerMove" | "onPointerMoveCapture" | "onPointerUp" | "onPointerUpCapture" | "onPointerCancel" | "onPointerCancelCapture" | "onPointerEnter" | "onPointerEnterCapture" | "onPointerLeave" | "onPointerLeaveCapture" | "onPointerOver" | "onPointerOverCapture" | "onPointerOut" | "onPointerOutCapture" | "onGotPointerCapture" | "onGotPointerCaptureCapture" | "onLostPointerCapture" | "onLostPointerCaptureCapture" | "onScroll" | "onScrollCapture" | "onWheel" | "onWheelCapture" | "onAnimationStart" | "onAnimationStartCapture" | "onAnimationEnd" | "onAnimationEndCapture" | "onAnimationIteration" | "onAnimationIterationCapture" | "onTransitionEnd" | "onTransitionEndCapture">>, import("styled-components").DefaultTheme, {}, never>;
|
|
6
|
+
export declare const StyledListToolbarDialog: import("styled-components").StyledComponent<import("react").FC<import("../Dialog").FormDialogProps & Pick<import("react").HTMLAttributes<HTMLDivElement>, "hidden" | "color" | "content" | "style" | "translate" | "prefix" | "slot" | "title" | "children" | "defaultChecked" | "defaultValue" | "suppressContentEditableWarning" | "suppressHydrationWarning" | "accessKey" | "autoFocus" | "className" | "contentEditable" | "contextMenu" | "dir" | "draggable" | "id" | "lang" | "nonce" | "placeholder" | "spellCheck" | "tabIndex" | "radioGroup" | "role" | "about" | "datatype" | "inlist" | "property" | "rel" | "resource" | "rev" | "typeof" | "vocab" | "autoCapitalize" | "autoCorrect" | "autoSave" | "itemProp" | "itemScope" | "itemType" | "itemID" | "itemRef" | "results" | "security" | "unselectable" | "inputMode" | "is" | "aria-activedescendant" | "aria-atomic" | "aria-autocomplete" | "aria-busy" | "aria-checked" | "aria-colcount" | "aria-colindex" | "aria-colspan" | "aria-controls" | "aria-current" | "aria-describedby" | "aria-details" | "aria-disabled" | "aria-dropeffect" | "aria-errormessage" | "aria-expanded" | "aria-flowto" | "aria-grabbed" | "aria-haspopup" | "aria-hidden" | "aria-invalid" | "aria-keyshortcuts" | "aria-label" | "aria-labelledby" | "aria-level" | "aria-live" | "aria-modal" | "aria-multiline" | "aria-multiselectable" | "aria-orientation" | "aria-owns" | "aria-placeholder" | "aria-posinset" | "aria-pressed" | "aria-readonly" | "aria-relevant" | "aria-required" | "aria-roledescription" | "aria-rowcount" | "aria-rowindex" | "aria-rowspan" | "aria-selected" | "aria-setsize" | "aria-sort" | "aria-valuemax" | "aria-valuemin" | "aria-valuenow" | "aria-valuetext" | "dangerouslySetInnerHTML" | "onCopy" | "onCopyCapture" | "onCut" | "onCutCapture" | "onPaste" | "onPasteCapture" | "onCompositionEnd" | "onCompositionEndCapture" | "onCompositionStart" | "onCompositionStartCapture" | "onCompositionUpdate" | "onCompositionUpdateCapture" | "onFocus" | "onFocusCapture" | "onBlur" | "onBlurCapture" | "onChange" | "onChangeCapture" | "onBeforeInput" | "onBeforeInputCapture" | "onInput" | "onInputCapture" | "onReset" | "onResetCapture" | "onSubmitCapture" | "onInvalid" | "onInvalidCapture" | "onLoad" | "onLoadCapture" | "onError" | "onErrorCapture" | "onKeyDown" | "onKeyDownCapture" | "onKeyPress" | "onKeyPressCapture" | "onKeyUp" | "onKeyUpCapture" | "onAbort" | "onAbortCapture" | "onCanPlay" | "onCanPlayCapture" | "onCanPlayThrough" | "onCanPlayThroughCapture" | "onDurationChange" | "onDurationChangeCapture" | "onEmptied" | "onEmptiedCapture" | "onEncrypted" | "onEncryptedCapture" | "onEnded" | "onEndedCapture" | "onLoadedData" | "onLoadedDataCapture" | "onLoadedMetadata" | "onLoadedMetadataCapture" | "onLoadStart" | "onLoadStartCapture" | "onPause" | "onPauseCapture" | "onPlay" | "onPlayCapture" | "onPlaying" | "onPlayingCapture" | "onProgress" | "onProgressCapture" | "onRateChange" | "onRateChangeCapture" | "onSeeked" | "onSeekedCapture" | "onSeeking" | "onSeekingCapture" | "onStalled" | "onStalledCapture" | "onSuspend" | "onSuspendCapture" | "onTimeUpdate" | "onTimeUpdateCapture" | "onVolumeChange" | "onVolumeChangeCapture" | "onWaiting" | "onWaitingCapture" | "onAuxClick" | "onAuxClickCapture" | "onClick" | "onClickCapture" | "onContextMenu" | "onContextMenuCapture" | "onDoubleClick" | "onDoubleClickCapture" | "onDrag" | "onDragCapture" | "onDragEnd" | "onDragEndCapture" | "onDragEnter" | "onDragEnterCapture" | "onDragExit" | "onDragExitCapture" | "onDragLeave" | "onDragLeaveCapture" | "onDragOver" | "onDragOverCapture" | "onDragStart" | "onDragStartCapture" | "onDrop" | "onDropCapture" | "onMouseDown" | "onMouseDownCapture" | "onMouseEnter" | "onMouseLeave" | "onMouseMove" | "onMouseMoveCapture" | "onMouseOut" | "onMouseOutCapture" | "onMouseOver" | "onMouseOverCapture" | "onMouseUp" | "onMouseUpCapture" | "onSelect" | "onSelectCapture" | "onTouchCancel" | "onTouchCancelCapture" | "onTouchEnd" | "onTouchEndCapture" | "onTouchMove" | "onTouchMoveCapture" | "onTouchStart" | "onTouchStartCapture" | "onPointerDown" | "onPointerDownCapture" | "onPointerMove" | "onPointerMoveCapture" | "onPointerUp" | "onPointerUpCapture" | "onPointerCancel" | "onPointerCancelCapture" | "onPointerEnter" | "onPointerEnterCapture" | "onPointerLeave" | "onPointerLeaveCapture" | "onPointerOver" | "onPointerOverCapture" | "onPointerOut" | "onPointerOutCapture" | "onGotPointerCapture" | "onGotPointerCaptureCapture" | "onLostPointerCapture" | "onLostPointerCaptureCapture" | "onScroll" | "onScrollCapture" | "onWheel" | "onWheelCapture" | "onAnimationStart" | "onAnimationStartCapture" | "onAnimationEnd" | "onAnimationEndCapture" | "onAnimationIteration" | "onAnimationIterationCapture" | "onTransitionEnd" | "onTransitionEndCapture">>, import("styled-components").DefaultTheme, {}, never>;
|
|
7
7
|
export declare const StyledListToolbarContent: import("styled-components").StyledComponent<import("react").FunctionComponent<import("../Flex").FlexProps & import("../..").ForwardProps>, import("styled-components").DefaultTheme, {}, never>;
|
|
8
8
|
export declare const StyledHeadingText: import("styled-components").StyledComponent<import("react").FunctionComponent<import("../Text").TextProps & import("../..").ForwardProps>, import("styled-components").DefaultTheme, {
|
|
9
9
|
required?: boolean | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ListToolbar.styles.d.ts","sourceRoot":"","sources":["../../../src/components/ListToolbar/ListToolbar.styles.ts"],"names":[],"mappings":"AAUA,eAAO,MAAM,gBAAgB,yGAK5B,CAAC;AAEF,eAAO,MAAM,kBAAkB;cAA6B,OAAO;SA0BjE,CAAC;AAIH,eAAO,MAAM,iBAAiB,yGAAe,CAAC;AAI9C,eAAO,MAAM,uBAAuB,
|
|
1
|
+
{"version":3,"file":"ListToolbar.styles.d.ts","sourceRoot":"","sources":["../../../src/components/ListToolbar/ListToolbar.styles.ts"],"names":[],"mappings":"AAUA,eAAO,MAAM,gBAAgB,yGAK5B,CAAC;AAEF,eAAO,MAAM,kBAAkB;cAA6B,OAAO;SA0BjE,CAAC;AAIH,eAAO,MAAM,iBAAiB,yGAAe,CAAC;AAI9C,eAAO,MAAM,uBAAuB,uuJAKlC,CAAC;AAIH,eAAO,MAAM,wBAAwB,iMAOnC,CAAC;AAIH,eAAO,MAAM,iBAAiB;;SA0B5B,CAAC;AAIH,eAAO,MAAM,eAAe,iMAW1B,CAAC;AAIH,eAAO,MAAM,eAAe,iMAU3B,CAAC"}
|
|
@@ -35,7 +35,7 @@ export interface UseActiveDescendantConfig {
|
|
|
35
35
|
/** Explicit onClick handler called on keydown 'enter' event */
|
|
36
36
|
onClick?: (currentDescendantEl: HTMLElement) => void;
|
|
37
37
|
/** Prevent scrolling to the active descendant on the initial render.
|
|
38
|
-
* Include `
|
|
38
|
+
* Include `clearPreventScroll` to scroll on subsequent interactions if applicable.
|
|
39
39
|
*/
|
|
40
40
|
preventInitialScroll?: boolean;
|
|
41
41
|
/** Callback to clear preventInitialScroll after use. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":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B,CAAC,EAAE,EAAE;gBAClC,IAAI,QAAQ,EAAE;oBACZ,QAAQ,CAAC,SAAS,GAAG,QAAQ,CAAC,YAAY,GAAG,QAAQ,CAAC,YAAY,CAAC;iBACpE;gBAED,IAAI,aAAa,EAAE,EAAE,KAAK,gBAAgB,CAAC,EAAE,EAAE;oBAC7C,uEAAuE;oBACvE,SAAS,GAAG,UAAU,CAAC,GAAG,EAAE;wBAC1B,gBAAgB,CAAC,QAAQ,CAAC,CAAC;oBAC7B,CAAC,EAAE,CAAC,CAAC,CAAC;iBACP;aACF;YACD,mBAAmB;iBACd,IAAI,aAAa,EAAE,EAAE,KAAK,gBAAgB,CAAC,EAAE,EAAE;gBAClD,sEAAsE;gBACtE,2EAA2E;gBAC3E,SAAS,GAAG,UAAU,CAAC,GAAG,EAAE;oBAC1B,gBAAgB,CAAC,gBAAgB,CAAC,CAAC;gBACrC,CAAC,EAAE,CAAC,CAAC,CAAC;aACP;YAED,OAAO,GAAG,EAAE,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;SACtC;IACH,CAAC,EAAE,CAAC,OAAO,EAAE,WAAW,EAAE,wBAAwB,EAAE,gBAAgB,EAAE,QAAQ,EAAE,aAAa,CAAC,CAAC,CAAC;AAClG,CAAC,CAAC;AAEF,eAAe,mBAAmB,CAAC","sourcesContent":["import { useEffect, useState, DependencyList, useCallback, useRef } from 'react';\n\nimport { createUID, getActiveElement } from '../utils';\n\nimport useDirection from './useDirection';\n\nexport interface UseActiveDescendantConfig {\n /** DOM element which controls and has active descendants */\n focusEl: HTMLElement | null;\n /** Root scope for descendant options */\n scope: HTMLElement | null;\n /** Custom selector for specific descendant scope in root descendant scope */\n scopeSelector?: string;\n /** Custom selector for descendant options */\n selector?: string;\n /** Orientation of descendant navigation\n * @default 'vertical'\n */\n orientation?: 'horizontal' | 'vertical';\n /** One-time override for the focused descendant, triggers re-evaluation.\n * Include `clearFocusDescendantEl` for cleanup.\n */\n focusDescendantEl?: HTMLElement | null;\n /** Callback to clear focusDescendantEl after use. */\n clearFocusDescendant?: () => void;\n /** One-time override for focused element on NEXT re-evaluation of active descendants.\n * Include `clearFocusReturn` for cleanup.\n */\n focusReturnEl?: HTMLElement | null;\n /** Callback to clear focusReturnEl after use. */\n clearFocusReturn?: () => void;\n /**\n * Descendant ID used for continuous override of current active descendant,\n * used for external focus control / keyDown bindings (see RTE).\n * NOTE: setting currentDescendantId once effectively disables the keybindings of this hook.\n * If you only need to set the current element once, use focusReturnEl & clearFocusReturn.\n * @deprecated\n */\n currentDescendantId?: string;\n /** Explicit onClick handler called on keydown 'enter' event */\n onClick?: (currentDescendantEl: HTMLElement) => void;\n /** Prevent scrolling to the active descendant on the initial render.\n * Include `preventInitialScroll` for cleanup.\n */\n preventInitialScroll?: boolean;\n /** Callback to clear preventInitialScroll after use. */\n clearPreventScroll?: () => void;\n /** Boolean to prevent descendant evaluation.\n * @default false\n */\n pauseDescendantEvaluation?: boolean;\n}\n\ntype CurrentDescendant = HTMLElement | undefined;\ntype Descendants = HTMLElement[] | null;\ntype InteractiveElementTypes =\n | HTMLButtonElement\n | HTMLAnchorElement\n | HTMLInputElement\n | HTMLLIElement\n | HTMLLegendElement;\n\nconst interactiveNodeNames = ['button', 'a', 'input', 'li', 'legend'];\n\nconst useActiveDescendant = (\n {\n focusEl,\n scope,\n scopeSelector,\n selector,\n orientation = 'vertical',\n focusDescendantEl,\n clearFocusDescendant,\n focusReturnEl,\n clearFocusReturn,\n currentDescendantId,\n onClick,\n preventInitialScroll,\n pauseDescendantEvaluation = false,\n clearPreventScroll\n }: UseActiveDescendantConfig,\n dependencyArray: DependencyList = []\n): {\n activeDescendant: CurrentDescendant;\n descendants: Descendants;\n} => {\n const [resetId, setResetId] = useState(0);\n const previousActiveId = useRef('');\n const paused = useRef(pauseDescendantEvaluation);\n const [focusDescendantElIndex, setFocusDescendantElIndex] = useState<number | null>(null);\n const [currentIndex, setCurrentIndex] = useState<number | null>(null);\n const [descendants, setDescendants] = useState<Descendants>();\n const { rtl } = useDirection();\n\n const clearDescendants = useCallback(() => {\n descendants?.forEach(node => {\n node.setAttribute('data-current', 'false');\n });\n }, [descendants]);\n\n const clearThenSetDescendants = useCallback(\n (setVal: NodeListOf<Element> | null) => {\n clearDescendants();\n setDescendants(\n setVal\n ? Array.from(setVal).filter((item): item is HTMLElement => item instanceof HTMLElement)\n : null\n );\n },\n [descendants]\n );\n\n const setIdsAndOwns = useCallback(\n ({ clear }: { clear: boolean } = { clear: false }) => {\n const ownedIds: string[] = [];\n\n if (descendants && descendants.length) {\n descendants.forEach(node => {\n node.id = node.id || createUID();\n ownedIds.push(node.id);\n });\n }\n\n if (clear) {\n const currentOwnedIds = focusEl?.getAttribute('aria-owns')?.split(' ');\n const clearedIds = currentOwnedIds?.filter(id => !ownedIds.includes(id));\n focusEl?.setAttribute('aria-owns', clearedIds?.join(' ') || '');\n } else {\n focusEl?.setAttribute('aria-owns', ownedIds.join(' '));\n }\n },\n [focusEl, descendants]\n );\n\n const updateDescendants = useCallback(() => {\n if (pauseDescendantEvaluation) return;\n\n let hasScope = scope;\n\n if (hasScope && hasScope instanceof HTMLElement) {\n if (scopeSelector) {\n hasScope = hasScope.querySelector(scopeSelector);\n }\n\n if (!hasScope) {\n clearThenSetDescendants(null);\n return;\n }\n\n if (selector) {\n const setVal = hasScope.querySelectorAll(selector);\n clearThenSetDescendants(setVal);\n } else {\n const setVal = hasScope.querySelectorAll(\n 'a, button, input, textarea, select, details, [tabindex]:not([tabindex=\"-1\"])'\n );\n clearThenSetDescendants(setVal);\n }\n } else {\n clearThenSetDescendants(null);\n }\n }, [scope, scopeSelector, selector, pauseDescendantEvaluation]);\n\n // Update paused ref\n useEffect(() => {\n paused.current = pauseDescendantEvaluation;\n }, [pauseDescendantEvaluation]);\n\n // Toggle active scope data attr.\n useEffect(() => {\n if (!scope || !focusEl) return;\n\n scope.setAttribute('data-active-scope', getActiveElement() === focusEl ? 'true' : 'false');\n\n const onFocus = () => {\n scope.setAttribute('data-active-scope', 'true');\n };\n const onBlur = () => {\n scope.setAttribute('data-active-scope', 'false');\n };\n\n focusEl.addEventListener('focus', onFocus);\n focusEl.addEventListener('blur', onBlur);\n\n return () => {\n focusEl.removeEventListener('focus', onFocus);\n focusEl.removeEventListener('blur', onBlur);\n };\n }, [scope, focusEl]);\n\n // Update descendants when un-paused\n useEffect(() => {\n if (!pauseDescendantEvaluation) {\n updateDescendants();\n }\n }, [pauseDescendantEvaluation]);\n\n // Update descendants & reset current index when dependencies change\n useEffect(() => {\n /**\n * 0 second timeout added because descendantScope needs to be\n * up to date before running query after dependencyArray change\n */\n const timeoutId = setTimeout(() => {\n updateDescendants();\n if (!paused.current) {\n setCurrentIndex(0);\n }\n }, 0);\n\n return () => clearTimeout(timeoutId);\n }, [...dependencyArray]);\n\n // Set IDs and aria-owns\n useEffect(() => {\n if (!pauseDescendantEvaluation) {\n setIdsAndOwns();\n setResetId(Math.random());\n } else {\n clearDescendants();\n setIdsAndOwns({ clear: true });\n }\n }, [pauseDescendantEvaluation, focusEl, descendants]);\n\n // Bind focus el keyDown\n useEffect(() => {\n const nextIndex = () => {\n // Focus next or first\n clearFocusReturn?.();\n clearPreventScroll?.();\n if (currentIndex !== null && currentIndex + 1 < descendants!.length) {\n setCurrentIndex(currentIndex + 1);\n } else {\n setCurrentIndex(0);\n }\n };\n const prevIndex = () => {\n // Focus previous or last\n clearFocusReturn?.();\n clearPreventScroll?.();\n if (currentIndex !== null && currentIndex - 1 > -1) {\n setCurrentIndex(currentIndex - 1);\n } else {\n setCurrentIndex(descendants!.length - 1);\n }\n };\n\n const onKeyDown = (e: KeyboardEvent) => {\n if (descendants?.length) {\n if (['ArrowDown', 'ArrowUp'].includes(e.key) && orientation === 'vertical') {\n e.preventDefault();\n }\n\n if (['ArrowLeft', 'ArrowRight'].includes(e.key) && orientation === 'horizontal') {\n e.preventDefault();\n }\n\n // 0 second timeout to execute after explicitly defined onKeyDown event handlers.\n setTimeout(() => {\n switch (e.key) {\n case 'ArrowDown':\n if (orientation === 'vertical') {\n nextIndex();\n }\n break;\n case 'ArrowUp':\n if (orientation === 'vertical') {\n prevIndex();\n }\n break;\n case 'ArrowRight':\n if (orientation === 'horizontal') {\n if (rtl) {\n prevIndex();\n } else {\n nextIndex();\n }\n }\n break;\n case 'ArrowLeft':\n if (orientation === 'horizontal') {\n if (rtl) {\n nextIndex();\n } else {\n prevIndex();\n }\n }\n break;\n case 'Enter':\n // Click focused item\n if (currentIndex !== null) {\n if (onClick) {\n onClick(descendants[currentIndex]);\n break;\n }\n\n const nodeName = descendants[currentIndex].nodeName.toLowerCase();\n if (interactiveNodeNames.includes(nodeName)) {\n descendants[currentIndex].click();\n } else {\n descendants[currentIndex]\n .querySelector<InteractiveElementTypes>(`${interactiveNodeNames.join(',')}`)\n ?.click();\n }\n }\n break;\n default:\n break;\n }\n }, 0);\n }\n };\n\n // Do not rebind once / if `currentDescendantId` (deprecated) control is defined\n if (!pauseDescendantEvaluation && focusEl && descendants?.length && !currentDescendantId) {\n focusEl.addEventListener('keydown', onKeyDown);\n }\n\n return () => {\n focusEl?.removeEventListener('keydown', onKeyDown);\n };\n }, [focusEl, currentIndex, descendants, pauseDescendantEvaluation]);\n\n // Handle independent control update (deprecated)\n useEffect(() => {\n if (!pauseDescendantEvaluation && descendants && currentDescendantId) {\n descendants.forEach((node, index) => {\n if (node.id === currentDescendantId) {\n setCurrentIndex(index);\n }\n });\n }\n }, [currentDescendantId, descendants, pauseDescendantEvaluation]);\n\n // Set and scroll to current descendant\n useEffect(() => {\n if (paused.current) {\n return;\n }\n const nextIndex = focusDescendantElIndex || currentIndex;\n const focusReturnId = focusReturnEl?.id;\n let focusReturnIndex;\n const focusDescendantElId = focusDescendantEl?.id;\n let focusDescendantIndex;\n let foundFocusDescendantEl = false;\n\n if (descendants && descendants.length) {\n // clear previous & catch focusReturn / focusDescendantEl index\n descendants.forEach((node, index) => {\n if (focusDescendantElIndex === null && node.id === focusDescendantElId) {\n focusDescendantIndex = index;\n foundFocusDescendantEl = true;\n setFocusDescendantElIndex(index);\n }\n if (node.id === focusReturnId) {\n focusReturnIndex = index;\n }\n node.setAttribute('data-current', 'false');\n });\n\n // early return for focusReturn / focusDescendantEl\n if (focusReturnIndex && focusReturnIndex !== currentIndex) {\n setCurrentIndex(focusReturnIndex);\n clearFocusReturn?.();\n return;\n }\n if (foundFocusDescendantEl && focusDescendantIndex !== undefined) {\n // hard reset to continue focusDescendantEl process even if it is the active descendant\n setResetId(Math.random());\n setCurrentIndex(focusDescendantIndex);\n return;\n }\n\n // set new\n if (nextIndex !== null && descendants[nextIndex]) {\n const itemEl = descendants[nextIndex!];\n itemEl.setAttribute('data-current', 'true');\n focusEl?.setAttribute('aria-activedescendant', itemEl.id);\n\n // scroll to element\n if (itemEl.id !== previousActiveId.current && !preventInitialScroll) {\n const scrollTo: (this: Element, arg: boolean) => void =\n Element.prototype.scrollIntoViewIfNeeded ?? Element.prototype.scrollIntoView;\n\n scrollTo?.call(itemEl, false);\n }\n\n // focusDescendantEl cleanup\n if (focusDescendantElIndex !== null) {\n setFocusDescendantElIndex(null);\n clearFocusDescendant?.();\n }\n\n previousActiveId.current = itemEl.id;\n }\n }\n\n return () => {\n focusEl?.removeAttribute('aria-activedescendant');\n };\n }, [descendants, currentIndex, focusDescendantEl, focusEl, resetId]);\n\n return {\n activeDescendant: currentIndex !== null && descendants ? descendants[currentIndex] : undefined,\n descendants: descendants || null\n };\n};\n\nexport const useLazyDescendant = ({\n loading,\n descendants,\n previousActiveDescendant,\n activeDescendant,\n focusReturnEl,\n setFocusReturnEl,\n scrollEl\n}: {\n loading: boolean;\n descendants: Descendants;\n previousActiveDescendant: CurrentDescendant;\n activeDescendant: CurrentDescendant;\n focusReturnEl: UseActiveDescendantConfig['focusReturnEl'];\n setFocusReturnEl: (el: HTMLElement | null | undefined) => void;\n scrollEl?: HTMLElement | null;\n}) => {\n // Bump scroll & set return element when descendant focused in loading state.\n useEffect(() => {\n if (loading && descendants && descendants.length && activeDescendant) {\n const descendantList = [...descendants];\n const lastItem = descendantList.pop();\n const lastId = lastItem?.id || undefined;\n let timeoutId: ReturnType<typeof setTimeout>;\n\n if (lastId === activeDescendant.id) {\n if (scrollEl) {\n scrollEl.scrollTop = scrollEl.scrollHeight - scrollEl.offsetHeight;\n }\n\n if (focusReturnEl?.id !== activeDescendant.id) {\n // Set focus return to AD on 'nextTick', to avoid reset of AD on update\n timeoutId = setTimeout(() => {\n setFocusReturnEl(lastItem);\n }, 0);\n }\n }\n // If not last item\n else if (focusReturnEl?.id !== activeDescendant.id) {\n // Set focus return to AD on 'nextTick' to avoid reset of AD on update\n // Do not D.R.Y to avoid conflicting calls with immediately prior elements.\n timeoutId = setTimeout(() => {\n setFocusReturnEl(activeDescendant);\n }, 0);\n }\n\n return () => clearTimeout(timeoutId);\n }\n }, [loading, descendants, previousActiveDescendant, activeDescendant, scrollEl, focusReturnEl]);\n};\n\nexport default useActiveDescendant;\n"]}
|
|
1
|
+
{"version":3,"file":"useActiveDescendant.js","sourceRoot":"","sources":["../../src/hooks/useActiveDescendant.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAkB,WAAW,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AAEjF,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAEvD,OAAO,YAAY,MAAM,gBAAgB,CAAC;AA0D1C,MAAM,oBAAoB,GAAG,CAAC,QAAQ,EAAE,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC;AAEtE,MAAM,mBAAmB,GAAG,CAC1B,EACE,OAAO,EACP,KAAK,EACL,aAAa,EACb,QAAQ,EACR,WAAW,GAAG,UAAU,EACxB,iBAAiB,EACjB,oBAAoB,EACpB,aAAa,EACb,gBAAgB,EAChB,mBAAmB,EACnB,OAAO,EACP,oBAAoB,EACpB,yBAAyB,GAAG,KAAK,EACjC,kBAAkB,EACQ,EAC5B,kBAAkC,EAAE,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S,CAAC,CAAC;SACtC;IACH,CAAC,EAAE,CAAC,OAAO,EAAE,WAAW,EAAE,wBAAwB,EAAE,gBAAgB,EAAE,QAAQ,EAAE,aAAa,CAAC,CAAC,CAAC;AAClG,CAAC,CAAC;AAEF,eAAe,mBAAmB,CAAC","sourcesContent":["import { useEffect, useState, DependencyList, useCallback, useRef } from 'react';\n\nimport { createUID, getActiveElement } from '../utils';\n\nimport useDirection from './useDirection';\n\nexport interface UseActiveDescendantConfig {\n /** DOM element which controls and has active descendants */\n focusEl: HTMLElement | null;\n /** Root scope for descendant options */\n scope: HTMLElement | null;\n /** Custom selector for specific descendant scope in root descendant scope */\n scopeSelector?: string;\n /** Custom selector for descendant options */\n selector?: string;\n /** Orientation of descendant navigation\n * @default 'vertical'\n */\n orientation?: 'horizontal' | 'vertical';\n /** One-time override for the focused descendant, triggers re-evaluation.\n * Include `clearFocusDescendantEl` for cleanup.\n */\n focusDescendantEl?: HTMLElement | null;\n /** Callback to clear focusDescendantEl after use. */\n clearFocusDescendant?: () => void;\n /** One-time override for focused element on NEXT re-evaluation of active descendants.\n * Include `clearFocusReturn` for cleanup.\n */\n focusReturnEl?: HTMLElement | null;\n /** Callback to clear focusReturnEl after use. */\n clearFocusReturn?: () => void;\n /**\n * Descendant ID used for continuous override of current active descendant,\n * used for external focus control / keyDown bindings (see RTE).\n * NOTE: setting currentDescendantId once effectively disables the keybindings of this hook.\n * If you only need to set the current element once, use focusReturnEl & clearFocusReturn.\n * @deprecated\n */\n currentDescendantId?: string;\n /** Explicit onClick handler called on keydown 'enter' event */\n onClick?: (currentDescendantEl: HTMLElement) => void;\n /** Prevent scrolling to the active descendant on the initial render.\n * Include `clearPreventScroll` to scroll on subsequent interactions if applicable.\n */\n preventInitialScroll?: boolean;\n /** Callback to clear preventInitialScroll after use. */\n clearPreventScroll?: () => void;\n /** Boolean to prevent descendant evaluation.\n * @default false\n */\n pauseDescendantEvaluation?: boolean;\n}\n\ntype CurrentDescendant = HTMLElement | undefined;\ntype Descendants = HTMLElement[] | null;\ntype InteractiveElementTypes =\n | HTMLButtonElement\n | HTMLAnchorElement\n | HTMLInputElement\n | HTMLLIElement\n | HTMLLegendElement;\n\nconst interactiveNodeNames = ['button', 'a', 'input', 'li', 'legend'];\n\nconst useActiveDescendant = (\n {\n focusEl,\n scope,\n scopeSelector,\n selector,\n orientation = 'vertical',\n focusDescendantEl,\n clearFocusDescendant,\n focusReturnEl,\n clearFocusReturn,\n currentDescendantId,\n onClick,\n preventInitialScroll,\n pauseDescendantEvaluation = false,\n clearPreventScroll\n }: UseActiveDescendantConfig,\n dependencyArray: DependencyList = []\n): {\n activeDescendant: CurrentDescendant;\n descendants: Descendants;\n} => {\n const [resetId, setResetId] = useState(0);\n const previousActiveId = useRef('');\n const paused = useRef(pauseDescendantEvaluation);\n const [focusDescendantElIndex, setFocusDescendantElIndex] = useState<number | null>(null);\n const [currentIndex, setCurrentIndex] = useState<number | null>(null);\n const [descendants, setDescendants] = useState<Descendants>();\n const { rtl } = useDirection();\n\n const clearDescendants = useCallback(() => {\n descendants?.forEach(node => {\n node.setAttribute('data-current', 'false');\n });\n }, [descendants]);\n\n const clearThenSetDescendants = useCallback(\n (setVal: NodeListOf<Element> | null) => {\n clearDescendants();\n setDescendants(\n setVal\n ? Array.from(setVal).filter((item): item is HTMLElement => item instanceof HTMLElement)\n : null\n );\n },\n [descendants]\n );\n\n const setIdsAndOwns = useCallback(\n ({ clear }: { clear: boolean } = { clear: false }) => {\n const ownedIds: string[] = [];\n\n if (descendants && descendants.length) {\n descendants.forEach(node => {\n node.id = node.id || createUID();\n ownedIds.push(node.id);\n });\n }\n\n if (clear) {\n const currentOwnedIds = focusEl?.getAttribute('aria-owns')?.split(' ');\n const clearedIds = currentOwnedIds?.filter(id => !ownedIds.includes(id));\n focusEl?.setAttribute('aria-owns', clearedIds?.join(' ') || '');\n } else {\n focusEl?.setAttribute('aria-owns', ownedIds.join(' '));\n }\n },\n [focusEl, descendants]\n );\n\n const updateDescendants = useCallback(() => {\n if (pauseDescendantEvaluation) return;\n\n let hasScope = scope;\n\n if (hasScope && hasScope instanceof HTMLElement) {\n if (scopeSelector) {\n hasScope = hasScope.querySelector(scopeSelector);\n }\n\n if (!hasScope) {\n clearThenSetDescendants(null);\n return;\n }\n\n if (selector) {\n const setVal = hasScope.querySelectorAll(selector);\n clearThenSetDescendants(setVal);\n } else {\n const setVal = hasScope.querySelectorAll(\n 'a, button, input, textarea, select, details, [tabindex]:not([tabindex=\"-1\"])'\n );\n clearThenSetDescendants(setVal);\n }\n } else {\n clearThenSetDescendants(null);\n }\n }, [scope, scopeSelector, selector, pauseDescendantEvaluation]);\n\n // Update paused ref\n useEffect(() => {\n paused.current = pauseDescendantEvaluation;\n }, [pauseDescendantEvaluation]);\n\n // Toggle active scope data attr.\n useEffect(() => {\n if (!scope || !focusEl) return;\n\n scope.setAttribute('data-active-scope', getActiveElement() === focusEl ? 'true' : 'false');\n\n const onFocus = () => {\n scope.setAttribute('data-active-scope', 'true');\n };\n const onBlur = () => {\n scope.setAttribute('data-active-scope', 'false');\n };\n\n focusEl.addEventListener('focus', onFocus);\n focusEl.addEventListener('blur', onBlur);\n\n return () => {\n focusEl.removeEventListener('focus', onFocus);\n focusEl.removeEventListener('blur', onBlur);\n };\n }, [scope, focusEl]);\n\n // Update descendants when un-paused\n useEffect(() => {\n if (!pauseDescendantEvaluation) {\n updateDescendants();\n }\n }, [pauseDescendantEvaluation]);\n\n // Update descendants & reset current index when dependencies change\n useEffect(() => {\n /**\n * 0 second timeout added because descendantScope needs to be\n * up to date before running query after dependencyArray change\n */\n const timeoutId = setTimeout(() => {\n updateDescendants();\n if (!paused.current) {\n setCurrentIndex(0);\n }\n }, 0);\n\n return () => clearTimeout(timeoutId);\n }, [...dependencyArray]);\n\n // Set IDs and aria-owns\n useEffect(() => {\n if (!pauseDescendantEvaluation) {\n setIdsAndOwns();\n setResetId(Math.random());\n } else {\n clearDescendants();\n setIdsAndOwns({ clear: true });\n }\n }, [pauseDescendantEvaluation, focusEl, descendants]);\n\n // Bind focus el keyDown\n useEffect(() => {\n const nextIndex = () => {\n // Focus next or first\n clearFocusReturn?.();\n clearPreventScroll?.();\n if (currentIndex !== null && currentIndex + 1 < descendants!.length) {\n setCurrentIndex(currentIndex + 1);\n } else {\n setCurrentIndex(0);\n }\n };\n const prevIndex = () => {\n // Focus previous or last\n clearFocusReturn?.();\n clearPreventScroll?.();\n if (currentIndex !== null && currentIndex - 1 > -1) {\n setCurrentIndex(currentIndex - 1);\n } else {\n setCurrentIndex(descendants!.length - 1);\n }\n };\n\n const onKeyDown = (e: KeyboardEvent) => {\n if (descendants?.length) {\n if (['ArrowDown', 'ArrowUp'].includes(e.key) && orientation === 'vertical') {\n e.preventDefault();\n }\n\n if (['ArrowLeft', 'ArrowRight'].includes(e.key) && orientation === 'horizontal') {\n e.preventDefault();\n }\n\n // 0 second timeout to execute after explicitly defined onKeyDown event handlers.\n setTimeout(() => {\n switch (e.key) {\n case 'ArrowDown':\n if (orientation === 'vertical') {\n nextIndex();\n }\n break;\n case 'ArrowUp':\n if (orientation === 'vertical') {\n prevIndex();\n }\n break;\n case 'ArrowRight':\n if (orientation === 'horizontal') {\n if (rtl) {\n prevIndex();\n } else {\n nextIndex();\n }\n }\n break;\n case 'ArrowLeft':\n if (orientation === 'horizontal') {\n if (rtl) {\n nextIndex();\n } else {\n prevIndex();\n }\n }\n break;\n case 'Enter':\n // Click focused item\n if (currentIndex !== null) {\n if (onClick) {\n onClick(descendants[currentIndex]);\n break;\n }\n\n const nodeName = descendants[currentIndex].nodeName.toLowerCase();\n if (interactiveNodeNames.includes(nodeName)) {\n descendants[currentIndex].click();\n } else {\n descendants[currentIndex]\n .querySelector<InteractiveElementTypes>(`${interactiveNodeNames.join(',')}`)\n ?.click();\n }\n }\n break;\n default:\n break;\n }\n }, 0);\n }\n };\n\n // Do not rebind once / if `currentDescendantId` (deprecated) control is defined\n if (!pauseDescendantEvaluation && focusEl && descendants?.length && !currentDescendantId) {\n focusEl.addEventListener('keydown', onKeyDown);\n }\n\n return () => {\n focusEl?.removeEventListener('keydown', onKeyDown);\n };\n }, [focusEl, currentIndex, descendants, pauseDescendantEvaluation]);\n\n // Handle independent control update (deprecated)\n useEffect(() => {\n if (!pauseDescendantEvaluation && descendants && currentDescendantId) {\n descendants.forEach((node, index) => {\n if (node.id === currentDescendantId) {\n setCurrentIndex(index);\n }\n });\n }\n }, [currentDescendantId, descendants, pauseDescendantEvaluation]);\n\n // Set and scroll to current descendant\n useEffect(() => {\n if (paused.current) {\n return;\n }\n const nextIndex = focusDescendantElIndex || currentIndex;\n const focusReturnId = focusReturnEl?.id;\n let focusReturnIndex;\n const focusDescendantElId = focusDescendantEl?.id;\n let focusDescendantIndex;\n let foundFocusDescendantEl = false;\n\n if (descendants && descendants.length) {\n // clear previous & catch focusReturn / focusDescendantEl index\n descendants.forEach((node, index) => {\n if (focusDescendantElIndex === null && node.id === focusDescendantElId) {\n focusDescendantIndex = index;\n foundFocusDescendantEl = true;\n setFocusDescendantElIndex(index);\n }\n if (node.id === focusReturnId) {\n focusReturnIndex = index;\n }\n node.setAttribute('data-current', 'false');\n });\n\n // early return for focusReturn / focusDescendantEl\n if (focusReturnIndex && focusReturnIndex !== currentIndex) {\n setCurrentIndex(focusReturnIndex);\n clearFocusReturn?.();\n return;\n }\n if (foundFocusDescendantEl && focusDescendantIndex !== undefined) {\n // hard reset to continue focusDescendantEl process even if it is the active descendant\n setResetId(Math.random());\n setCurrentIndex(focusDescendantIndex);\n return;\n }\n\n // set new\n if (nextIndex !== null && descendants[nextIndex]) {\n const itemEl = descendants[nextIndex!];\n itemEl.setAttribute('data-current', 'true');\n focusEl?.setAttribute('aria-activedescendant', itemEl.id);\n\n // scroll to element\n if (itemEl.id !== previousActiveId.current && !preventInitialScroll) {\n const scrollTo: (this: Element, arg: boolean) => void =\n Element.prototype.scrollIntoViewIfNeeded ?? Element.prototype.scrollIntoView;\n\n scrollTo?.call(itemEl, false);\n }\n\n // focusDescendantEl cleanup\n if (focusDescendantElIndex !== null) {\n setFocusDescendantElIndex(null);\n clearFocusDescendant?.();\n }\n\n previousActiveId.current = itemEl.id;\n }\n }\n\n return () => {\n focusEl?.removeAttribute('aria-activedescendant');\n };\n }, [descendants, currentIndex, focusDescendantEl, focusEl, resetId]);\n\n return {\n activeDescendant: currentIndex !== null && descendants ? descendants[currentIndex] : undefined,\n descendants: descendants || null\n };\n};\n\nexport const useLazyDescendant = ({\n loading,\n descendants,\n previousActiveDescendant,\n activeDescendant,\n focusReturnEl,\n setFocusReturnEl,\n scrollEl\n}: {\n loading: boolean;\n descendants: Descendants;\n previousActiveDescendant: CurrentDescendant;\n activeDescendant: CurrentDescendant;\n focusReturnEl: UseActiveDescendantConfig['focusReturnEl'];\n setFocusReturnEl: (el: HTMLElement | null | undefined) => void;\n scrollEl?: HTMLElement | null;\n}) => {\n // Bump scroll & set return element when descendant focused in loading state.\n useEffect(() => {\n if (loading && descendants && descendants.length && activeDescendant) {\n const descendantList = [...descendants];\n const lastItem = descendantList.pop();\n const lastId = lastItem?.id || undefined;\n let timeoutId: ReturnType<typeof setTimeout>;\n\n if (lastId === activeDescendant.id) {\n if (scrollEl) {\n scrollEl.scrollTop = scrollEl.scrollHeight - scrollEl.offsetHeight;\n }\n\n if (focusReturnEl?.id !== activeDescendant.id) {\n // Set focus return to AD on 'nextTick', to avoid reset of AD on update\n timeoutId = setTimeout(() => {\n setFocusReturnEl(lastItem);\n }, 0);\n }\n }\n // If not last item\n else if (focusReturnEl?.id !== activeDescendant.id) {\n // Set focus return to AD on 'nextTick' to avoid reset of AD on update\n // Do not D.R.Y to avoid conflicting calls with immediately prior elements.\n timeoutId = setTimeout(() => {\n setFocusReturnEl(activeDescendant);\n }, 0);\n }\n\n return () => clearTimeout(timeoutId);\n }\n }, [loading, descendants, previousActiveDescendant, activeDescendant, scrollEl, focusReturnEl]);\n};\n\nexport default useActiveDescendant;\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pega/cosmos-react-core",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.1.1",
|
|
4
4
|
"description": "Cosmos is a visual design system and UI component collection. Its goal is to empower application developers in their pursuit to create engaging and rewarding user experiences.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -31,8 +31,8 @@
|
|
|
31
31
|
"@types/emoji-regex": "^8.0.0",
|
|
32
32
|
"@types/google.maps": "^3.49.2",
|
|
33
33
|
"@types/qrcode": "^1.5.0",
|
|
34
|
-
"@types/react": "^16.14.
|
|
35
|
-
"@types/react-dom": "^16.9.
|
|
34
|
+
"@types/react": "^16.14.43 || ^17.0.62",
|
|
35
|
+
"@types/react-dom": "^16.9.19 || ^17.0.20",
|
|
36
36
|
"@types/styled-components": "^5.1.26",
|
|
37
37
|
"bignumber.js": "^9.0.1",
|
|
38
38
|
"credit-card-type": "^9.1.0",
|