@razorpay/blade 12.53.0 → 12.54.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/lib/native/components/Box/BaseBox/types/propsTypes.js.map +1 -1
- package/build/lib/native/components/Dropdown/dropdownUtils.js +1 -1
- package/build/lib/native/components/Dropdown/dropdownUtils.js.map +1 -1
- package/build/lib/native/components/Input/BaseInput/BaseInput.js +1 -1
- package/build/lib/native/components/Input/BaseInput/BaseInput.js.map +1 -1
- package/build/lib/native/components/Input/DropdownInputTriggers/AutoComplete.js +1 -1
- package/build/lib/native/components/Input/DropdownInputTriggers/AutoComplete.js.map +1 -1
- package/build/lib/native/components/TimePicker/TimePicker.native.js +7 -0
- package/build/lib/native/components/TimePicker/TimePicker.native.js.map +1 -0
- package/build/lib/native/components/index.js +1 -0
- package/build/lib/native/components/index.js.map +1 -1
- package/build/lib/native/tokens/global/size.js +1 -1
- package/build/lib/native/tokens/global/size.js.map +1 -1
- package/build/lib/native/utils/metaAttribute/metaConstants.js +1 -1
- package/build/lib/native/utils/metaAttribute/metaConstants.js.map +1 -1
- package/build/lib/web/development/components/BottomSheet/BottomSheet.web.js +14 -1
- package/build/lib/web/development/components/BottomSheet/BottomSheet.web.js.map +1 -1
- package/build/lib/web/development/components/Box/BaseBox/types/propsTypes.js.map +1 -1
- package/build/lib/web/development/components/DatePicker/usePopup.js.map +1 -1
- package/build/lib/web/development/components/Dropdown/dropdownUtils.js +1 -1
- package/build/lib/web/development/components/Dropdown/dropdownUtils.js.map +1 -1
- package/build/lib/web/development/components/Input/BaseInput/BaseInput.js +4 -2
- package/build/lib/web/development/components/Input/BaseInput/BaseInput.js.map +1 -1
- package/build/lib/web/development/components/Input/BaseInput/StyledBaseInput.web.js +41 -2
- package/build/lib/web/development/components/Input/BaseInput/StyledBaseInput.web.js.map +1 -1
- package/build/lib/web/development/components/Input/DropdownInputTriggers/AutoComplete.js +1 -1
- package/build/lib/web/development/components/Input/DropdownInputTriggers/AutoComplete.js.map +1 -1
- package/build/lib/web/development/components/TimePicker/BaseTimePicker.web.js +262 -0
- package/build/lib/web/development/components/TimePicker/BaseTimePicker.web.js.map +1 -0
- package/build/lib/web/development/components/TimePicker/SpinWheel.web.js +188 -0
- package/build/lib/web/development/components/TimePicker/SpinWheel.web.js.map +1 -0
- package/build/lib/web/development/components/TimePicker/TimeInput.web.js +256 -0
- package/build/lib/web/development/components/TimePicker/TimeInput.web.js.map +1 -0
- package/build/lib/web/development/components/TimePicker/TimePicker.web.js +13 -0
- package/build/lib/web/development/components/TimePicker/TimePicker.web.js.map +1 -0
- package/build/lib/web/development/components/TimePicker/TimePickerContent.web.js +200 -0
- package/build/lib/web/development/components/TimePicker/TimePickerContent.web.js.map +1 -0
- package/build/lib/web/development/components/TimePicker/TimePickerFooter.web.js +49 -0
- package/build/lib/web/development/components/TimePicker/TimePickerFooter.web.js.map +1 -0
- package/build/lib/web/development/components/TimePicker/index.js +2 -0
- package/build/lib/web/development/components/TimePicker/index.js.map +1 -0
- package/build/lib/web/development/components/TimePicker/useTimePickerState.js +146 -0
- package/build/lib/web/development/components/TimePicker/useTimePickerState.js.map +1 -0
- package/build/lib/web/development/components/TimePicker/utils.js +252 -0
- package/build/lib/web/development/components/TimePicker/utils.js.map +1 -0
- package/build/lib/web/development/components/index.js +2 -0
- package/build/lib/web/development/components/index.js.map +1 -1
- package/build/lib/web/development/tokens/global/size.js +16 -0
- package/build/lib/web/development/tokens/global/size.js.map +1 -1
- package/build/lib/web/development/utils/metaAttribute/metaConstants.js +2 -1
- package/build/lib/web/development/utils/metaAttribute/metaConstants.js.map +1 -1
- package/build/lib/web/production/components/BottomSheet/BottomSheet.web.js +14 -1
- package/build/lib/web/production/components/BottomSheet/BottomSheet.web.js.map +1 -1
- package/build/lib/web/production/components/Box/BaseBox/types/propsTypes.js.map +1 -1
- package/build/lib/web/production/components/DatePicker/usePopup.js.map +1 -1
- package/build/lib/web/production/components/Dropdown/dropdownUtils.js +1 -1
- package/build/lib/web/production/components/Dropdown/dropdownUtils.js.map +1 -1
- package/build/lib/web/production/components/Input/BaseInput/BaseInput.js +4 -2
- package/build/lib/web/production/components/Input/BaseInput/BaseInput.js.map +1 -1
- package/build/lib/web/production/components/Input/BaseInput/StyledBaseInput.web.js +41 -2
- package/build/lib/web/production/components/Input/BaseInput/StyledBaseInput.web.js.map +1 -1
- package/build/lib/web/production/components/Input/DropdownInputTriggers/AutoComplete.js +1 -1
- package/build/lib/web/production/components/Input/DropdownInputTriggers/AutoComplete.js.map +1 -1
- package/build/lib/web/production/components/TimePicker/BaseTimePicker.web.js +262 -0
- package/build/lib/web/production/components/TimePicker/BaseTimePicker.web.js.map +1 -0
- package/build/lib/web/production/components/TimePicker/SpinWheel.web.js +188 -0
- package/build/lib/web/production/components/TimePicker/SpinWheel.web.js.map +1 -0
- package/build/lib/web/production/components/TimePicker/TimeInput.web.js +256 -0
- package/build/lib/web/production/components/TimePicker/TimeInput.web.js.map +1 -0
- package/build/lib/web/production/components/TimePicker/TimePicker.web.js +13 -0
- package/build/lib/web/production/components/TimePicker/TimePicker.web.js.map +1 -0
- package/build/lib/web/production/components/TimePicker/TimePickerContent.web.js +200 -0
- package/build/lib/web/production/components/TimePicker/TimePickerContent.web.js.map +1 -0
- package/build/lib/web/production/components/TimePicker/TimePickerFooter.web.js +49 -0
- package/build/lib/web/production/components/TimePicker/TimePickerFooter.web.js.map +1 -0
- package/build/lib/web/production/components/TimePicker/index.js +2 -0
- package/build/lib/web/production/components/TimePicker/index.js.map +1 -0
- package/build/lib/web/production/components/TimePicker/useTimePickerState.js +146 -0
- package/build/lib/web/production/components/TimePicker/useTimePickerState.js.map +1 -0
- package/build/lib/web/production/components/TimePicker/utils.js +252 -0
- package/build/lib/web/production/components/TimePicker/utils.js.map +1 -0
- package/build/lib/web/production/components/index.js +2 -0
- package/build/lib/web/production/components/index.js.map +1 -1
- package/build/lib/web/production/tokens/global/size.js +16 -0
- package/build/lib/web/production/tokens/global/size.js.map +1 -1
- package/build/lib/web/production/utils/metaAttribute/metaConstants.js +2 -1
- package/build/lib/web/production/utils/metaAttribute/metaConstants.js.map +1 -1
- package/build/types/components/index.d.ts +426 -242
- package/build/types/components/index.native.d.ts +148 -144
- package/build/types/tokens/index.d.ts +16 -0
- package/build/types/tokens/index.native.d.ts +16 -0
- package/package.json +5 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"propsTypes.js","sources":["../../../../../../../src/components/Box/BaseBox/types/propsTypes.ts"],"sourcesContent":["import type { View } from 'react-native';\nimport type { CSSObject } from 'styled-components';\nimport type { MarginProps, PaddingProps, SpacingValueType } from './spacingTypes';\nimport type { MakeObjectResponsive } from './responsiveTypes';\nimport type { Theme } from '~components/BladeProvider';\nimport type { Border, Elevation } from '~tokens/global';\nimport type { DataAnalyticsAttribute, PickCSSByPlatform, TestID } from '~utils/types';\nimport type { Platform } from '~utils';\nimport type { BladeCommonEvents } from '~components/types';\nimport type { DotNotationToken } from '~utils/lodashButBetter/get';\n\ntype LayoutProps = MakeObjectResponsive<\n {\n height: SpacingValueType;\n minHeight: SpacingValueType;\n maxHeight: SpacingValueType;\n width: SpacingValueType;\n minWidth: SpacingValueType;\n maxWidth: SpacingValueType;\n } & PickCSSByPlatform<\n 'display' | 'overflow' | 'overflowX' | 'overflowY' | 'textAlign' | 'whiteSpace'\n >\n>;\n\ntype FlexboxProps = MakeObjectResponsive<\n {\n /**\n * This uses the native gap property which might not work on older browsers.\n * If you want to support older browsers, you might want to use `margin` instead.\n *\n * @see https://caniuse.com/?search=gap\n */\n gap: SpacingValueType;\n /**\n * This uses the native row-gap property which might not work on older browsers.\n * If you want to support older browsers, you might want to use `margin` instead.\n *\n * @see https://caniuse.com/?search=row-gap\n */\n rowGap: SpacingValueType;\n /**\n * This uses the native column-gap property which might not work on older browsers.\n * If you want to support older browsers, you might want to use `margin` instead.\n *\n * @see https://caniuse.com/?search=column-gap\n */\n columnGap: SpacingValueType;\n /**\n * The **`flex`** CSS shorthand property sets how a flex _item_ will grow or shrink to fit the space available in its flex container.\n *\n * @see https://developer.mozilla.org/docs/Web/CSS/flex\n */\n flex: string | number;\n } & PickCSSByPlatform<\n | 'flexWrap'\n | 'flexDirection'\n | 'flexGrow'\n | 'flexShrink'\n | 'flexBasis'\n | 'alignItems'\n | 'alignContent'\n | 'alignSelf'\n | 'justifyItems'\n | 'justifyContent'\n | 'justifySelf'\n | 'placeSelf'\n | 'placeItems'\n | 'order'\n >\n>;\n\ntype PositionProps = MakeObjectResponsive<\n {\n top: SpacingValueType;\n right: SpacingValueType;\n bottom: SpacingValueType;\n left: SpacingValueType;\n } & PickCSSByPlatform<'position' | 'zIndex'>\n>;\n\ntype GridProps = MakeObjectResponsive<\n PickCSSByPlatform<\n | 'grid'\n | 'gridColumn'\n | 'gridRow'\n | 'gridRowStart'\n | 'gridRowEnd'\n | 'gridColumnStart'\n | 'gridColumnEnd'\n | 'gridArea'\n | 'gridAutoFlow'\n | 'gridAutoRows'\n | 'gridAutoColumns'\n | 'gridTemplate'\n | 'gridTemplateAreas'\n | 'gridTemplateColumns'\n | 'gridTemplateRows'\n >\n>;\n\ntype ColorObjects = 'feedback' | 'surface' | 'interactive';\ntype BackgroundOnlyColorObjects = 'popup' | 'overlay';\ntype BackgroundColorString<\n T extends ColorObjects | BackgroundOnlyColorObjects\n> = `${T}.background.${DotNotationToken<Theme['colors'][T]['background']>}`;\ntype BorderColorString<T extends ColorObjects> = `${T}.border.${DotNotationToken<\n Theme['colors'][T]['border']\n>}`;\n\n// Created this as an array so I can reuse it for runtime validation\nconst validBoxAsValues = [\n 'div',\n 'section',\n 'footer',\n 'header',\n 'main',\n 'aside',\n 'nav',\n 'span',\n 'label',\n] as const;\n\ntype BoxAsType = typeof validBoxAsValues[number];\n\n// Visual props that are common for both Box and BaseBox\ntype CommonBoxVisualProps = MakeObjectResponsive<\n {\n borderRadius: keyof Border['radius'];\n borderWidth: keyof Border['width'];\n borderColor: BorderColorString<'surface'>;\n borderTopWidth: keyof Border['width'];\n borderTopColor: BorderColorString<'surface'>;\n borderRightWidth: keyof Border['width'];\n borderRightColor: BorderColorString<'surface'>;\n borderBottomWidth: keyof Border['width'];\n borderBottomColor: BorderColorString<'surface'>;\n borderLeftWidth: keyof Border['width'];\n borderLeftColor: BorderColorString<'surface'>;\n borderTopLeftRadius: keyof Border['radius'];\n borderTopRightRadius: keyof Border['radius'];\n borderBottomRightRadius: keyof Border['radius'];\n borderBottomLeftRadius: keyof Border['radius'];\n } & PickCSSByPlatform<\n | 'backgroundImage'\n | 'backgroundSize'\n | 'backgroundPosition'\n | 'backgroundOrigin'\n | 'backgroundRepeat'\n | 'pointerEvents'\n | 'opacity'\n | 'visibility'\n | 'transform'\n | 'transformOrigin'\n | 'clipPath'\n | 'borderStyle'\n | 'borderTopStyle'\n | 'borderBottomStyle'\n | 'borderLeftStyle'\n | 'borderRightStyle'\n | 'backdropFilter'\n | 'transition'\n > & {\n /**\n * Sets the elevation for Box\n *\n * eg: `theme.elevation.midRaised`\n *\n * @default `theme.elevation.lowRaised`\n *\n * **Links:**\n * - Docs: https://blade.razorpay.com/?path=/docs/tokens-elevation--docs\n */\n elevation?: keyof Elevation;\n }\n>;\n\n// Visual props that are specific BaseBox\n// This is used to ensure some of the more flexible BaseBox props are not passed to Box\ntype BaseBoxVisualProps = MakeObjectResponsive<\n {\n backgroundColor:\n | BackgroundColorString<'feedback'>\n | BackgroundColorString<'surface'>\n | BackgroundColorString<'interactive'>\n | BackgroundColorString<'overlay'>\n | BackgroundColorString<'popup'>\n | 'transparent'\n | (string & Record<never, never>);\n lineHeight: SpacingValueType;\n touchAction: CSSObject['touchAction'];\n userSelect: CSSObject['userSelect'];\n } & PickCSSByPlatform<\n | 'border'\n | 'borderLeft'\n | 'borderRight'\n | 'borderTop'\n | 'borderBottom'\n | 'opacity'\n | 'pointerEvents'\n | 'cursor'\n >\n>;\n\n// Visual props that are specific to Box\ntype BoxVisualProps = MakeObjectResponsive<{\n backgroundColor:\n | BackgroundColorString<'surface'>\n | BackgroundColorString<'overlay'>\n | BackgroundColorString<'feedback'>\n | 'transparent';\n}> & {\n // Intentionally keeping this outside of MakeObjectResponsive since we only want as to be string and not responsive object\n // styled-components do not support passing `as` prop as an object\n as: BoxAsType;\n};\n\ntype StyledPropsBlade = Partial<\n Omit<\n MarginProps &\n Pick<FlexboxProps, 'alignSelf' | 'justifySelf' | 'placeSelf' | 'order' | 'flexWrap'> &\n PositionProps &\n Pick<\n GridProps,\n | 'gridColumn'\n | 'gridRow'\n | 'gridRowStart'\n | 'gridRowEnd'\n | 'gridColumnStart'\n | 'gridColumnEnd'\n | 'gridArea'\n > &\n Pick<LayoutProps, 'display'> &\n Pick<CommonBoxVisualProps, 'visibility'>,\n '__brand__'\n >\n>;\n\ntype BoxCallbackProps = Omit<\n Platform.Select<{\n web: {\n /**\n * **Warning**\n *\n * Make sure to not use Box when you want to create a trigger that performs action on hover.\n * You would probably want to render it as `button` using `styled.button` instead.\n *\n * Use this for hoverable containers in cases like custom menus.\n */\n onMouseOver: React.MouseEventHandler<HTMLElement>;\n /**\n * **Warning**\n *\n * Make sure to not use Box when you want to create a trigger that performs action on hover.\n * You would probably want to render it as `button` using `styled.button` instead.\n *\n * Use this for hoverable containers in cases like custom menus.\n */\n onMouseEnter: React.MouseEventHandler<HTMLElement>;\n /**\n * **Warning**\n *\n * Make sure to not use Box when you want to create a trigger that performs action on hover.\n * You would probably want to render it as `button` using `styled.button` instead.\n *\n * Use this for hoverable containers in cases like custom menus.\n */\n onMouseLeave: React.MouseEventHandler<HTMLElement>;\n onScroll: React.UIEventHandler<HTMLElement>;\n };\n native: Record<'onMouseOver' | 'onMouseEnter' | 'onMouseLeave' | 'onScroll', undefined>;\n }>,\n '__brand__'\n>;\n\ntype BoxDragAndDropProps = Omit<\n Platform.Select<{\n web: {\n draggable: boolean;\n onDragStart: React.DragEventHandler<HTMLElement>;\n onDragEnter: React.DragEventHandler<HTMLElement>;\n onDragLeave: React.DragEventHandler<HTMLElement>;\n onDragOver: React.DragEventHandler<HTMLElement>;\n onDragEnd: React.DragEventHandler<HTMLElement>;\n onDrop: React.DragEventHandler<HTMLElement>;\n };\n native: Record<\n | 'draggable'\n | 'onDragStart'\n | 'onDragEnter'\n | 'onDragLeave'\n | 'onDragOver'\n | 'onDragEnd'\n | 'onDrop',\n undefined\n >;\n }>,\n '__brand__'\n>;\n\ntype BoxProps = Partial<\n PaddingProps &\n MarginProps &\n LayoutProps &\n FlexboxProps &\n PositionProps &\n GridProps &\n BoxCallbackProps &\n BoxDragAndDropProps &\n CommonBoxVisualProps &\n BoxVisualProps & {\n children?: React.ReactNode | React.ReactNode[];\n tabIndex?: number;\n id?: string;\n } & TestID &\n DataAnalyticsAttribute\n>;\n\n// Visual props have different types for BaseBox and Box. BaseBox has more flexible types and more props exposed.\n// So first we Omit Visual props of Box\n// Then we append BaseBoxVisualProps and some other props for styled-components like class and id\ntype BaseBoxProps = Omit<BoxProps, keyof BoxVisualProps> &\n Partial<\n DataAnalyticsAttribute &\n BaseBoxVisualProps & {\n className?: string;\n id?: string;\n tabIndex?: number;\n }\n > &\n BladeCommonEvents;\n\n// ref prop type\ntype BoxRefType = Platform.Select<{\n web: Omit<HTMLElement, 'style'>;\n native: View;\n}>;\n\nexport type { BaseBoxProps, BoxProps, BoxRefType, StyledPropsBlade, FlexboxProps, GridProps };\nexport { validBoxAsValues };\n"],"names":["validBoxAsValues"],"mappings":"AA8GM,IAAAA,gBAAgB,CAAG,CACvB,KAAK,CACL,SAAS,CACT,QAAQ,CACR,QAAQ,CACR,MAAM,CACN,OAAO,CACP,KAAK,CACL,MAAM,CACN,OAAO;;;;"}
|
|
1
|
+
{"version":3,"file":"propsTypes.js","sources":["../../../../../../../src/components/Box/BaseBox/types/propsTypes.ts"],"sourcesContent":["import type { View } from 'react-native';\nimport type { CSSObject } from 'styled-components';\nimport type { MarginProps, PaddingProps, SpacingValueType } from './spacingTypes';\nimport type { MakeObjectResponsive } from './responsiveTypes';\nimport type { Theme } from '~components/BladeProvider';\nimport type { Border, Elevation } from '~tokens/global';\nimport type { DataAnalyticsAttribute, PickCSSByPlatform, TestID } from '~utils/types';\nimport type { Platform } from '~utils';\nimport type { BladeCommonEvents } from '~components/types';\nimport type { DotNotationToken } from '~utils/lodashButBetter/get';\n\ntype LayoutProps = MakeObjectResponsive<\n {\n height: SpacingValueType;\n minHeight: SpacingValueType;\n maxHeight: SpacingValueType;\n width: SpacingValueType;\n minWidth: SpacingValueType;\n maxWidth: SpacingValueType;\n } & PickCSSByPlatform<\n 'display' | 'overflow' | 'overflowX' | 'overflowY' | 'textAlign' | 'whiteSpace'\n >\n>;\n\ntype FlexboxProps = MakeObjectResponsive<\n {\n /**\n * This uses the native gap property which might not work on older browsers.\n * If you want to support older browsers, you might want to use `margin` instead.\n *\n * @see https://caniuse.com/?search=gap\n */\n gap: SpacingValueType;\n /**\n * This uses the native row-gap property which might not work on older browsers.\n * If you want to support older browsers, you might want to use `margin` instead.\n *\n * @see https://caniuse.com/?search=row-gap\n */\n rowGap: SpacingValueType;\n /**\n * This uses the native column-gap property which might not work on older browsers.\n * If you want to support older browsers, you might want to use `margin` instead.\n *\n * @see https://caniuse.com/?search=column-gap\n */\n columnGap: SpacingValueType;\n /**\n * The **`flex`** CSS shorthand property sets how a flex _item_ will grow or shrink to fit the space available in its flex container.\n *\n * @see https://developer.mozilla.org/docs/Web/CSS/flex\n */\n flex: string | number;\n } & PickCSSByPlatform<\n | 'flexWrap'\n | 'flexDirection'\n | 'flexGrow'\n | 'flexShrink'\n | 'flexBasis'\n | 'alignItems'\n | 'alignContent'\n | 'alignSelf'\n | 'justifyItems'\n | 'justifyContent'\n | 'justifySelf'\n | 'placeSelf'\n | 'placeItems'\n | 'order'\n >\n>;\n\ntype PositionProps = MakeObjectResponsive<\n {\n top: SpacingValueType;\n right: SpacingValueType;\n bottom: SpacingValueType;\n left: SpacingValueType;\n } & PickCSSByPlatform<'position' | 'zIndex'>\n>;\n\ntype GridProps = MakeObjectResponsive<\n PickCSSByPlatform<\n | 'grid'\n | 'gridColumn'\n | 'gridRow'\n | 'gridRowStart'\n | 'gridRowEnd'\n | 'gridColumnStart'\n | 'gridColumnEnd'\n | 'gridArea'\n | 'gridAutoFlow'\n | 'gridAutoRows'\n | 'gridAutoColumns'\n | 'gridTemplate'\n | 'gridTemplateAreas'\n | 'gridTemplateColumns'\n | 'gridTemplateRows'\n >\n>;\n\ntype ColorObjects = 'feedback' | 'surface' | 'interactive';\ntype BorderOnlyColorObjects = 'popup';\ntype BackgroundOnlyColorObjects = 'popup' | 'overlay';\ntype BackgroundColorString<\n T extends ColorObjects | BackgroundOnlyColorObjects\n> = `${T}.background.${DotNotationToken<Theme['colors'][T]['background']>}`;\ntype BorderColorString<\n T extends ColorObjects | BorderOnlyColorObjects\n> = `${T}.border.${DotNotationToken<Theme['colors'][T]['border']>}`;\n\n// Created this as an array so I can reuse it for runtime validation\nconst validBoxAsValues = [\n 'div',\n 'section',\n 'footer',\n 'header',\n 'main',\n 'aside',\n 'nav',\n 'span',\n 'label',\n] as const;\n\ntype BoxAsType = typeof validBoxAsValues[number];\n\n// Visual props that are common for both Box and BaseBox\ntype CommonBoxVisualProps = MakeObjectResponsive<\n {\n borderRadius: keyof Border['radius'];\n borderWidth: keyof Border['width'];\n borderColor: BorderColorString<'surface'> | BorderColorString<'popup'>;\n borderTopWidth: keyof Border['width'];\n borderTopColor: BorderColorString<'surface'>;\n borderRightWidth: keyof Border['width'];\n borderRightColor: BorderColorString<'surface'>;\n borderBottomWidth: keyof Border['width'];\n borderBottomColor: BorderColorString<'surface'>;\n borderLeftWidth: keyof Border['width'];\n borderLeftColor: BorderColorString<'surface'>;\n borderTopLeftRadius: keyof Border['radius'];\n borderTopRightRadius: keyof Border['radius'];\n borderBottomRightRadius: keyof Border['radius'];\n borderBottomLeftRadius: keyof Border['radius'];\n } & PickCSSByPlatform<\n | 'backgroundImage'\n | 'backgroundSize'\n | 'backgroundPosition'\n | 'backgroundOrigin'\n | 'backgroundRepeat'\n | 'pointerEvents'\n | 'opacity'\n | 'visibility'\n | 'transform'\n | 'transformOrigin'\n | 'clipPath'\n | 'borderStyle'\n | 'borderTopStyle'\n | 'borderBottomStyle'\n | 'borderLeftStyle'\n | 'borderRightStyle'\n | 'backdropFilter'\n | 'transition'\n > & {\n /**\n * Sets the elevation for Box\n *\n * eg: `theme.elevation.midRaised`\n *\n * @default `theme.elevation.lowRaised`\n *\n * **Links:**\n * - Docs: https://blade.razorpay.com/?path=/docs/tokens-elevation--docs\n */\n elevation?: keyof Elevation;\n }\n>;\n\n// Visual props that are specific BaseBox\n// This is used to ensure some of the more flexible BaseBox props are not passed to Box\ntype BaseBoxVisualProps = MakeObjectResponsive<\n {\n backgroundColor:\n | BackgroundColorString<'feedback'>\n | BackgroundColorString<'surface'>\n | BackgroundColorString<'interactive'>\n | BackgroundColorString<'overlay'>\n | BackgroundColorString<'popup'>\n | 'transparent'\n | (string & Record<never, never>);\n lineHeight: SpacingValueType;\n touchAction: CSSObject['touchAction'];\n userSelect: CSSObject['userSelect'];\n } & PickCSSByPlatform<\n | 'border'\n | 'borderLeft'\n | 'borderRight'\n | 'borderTop'\n | 'borderBottom'\n | 'opacity'\n | 'pointerEvents'\n | 'cursor'\n >\n>;\n\n// Visual props that are specific to Box\ntype BoxVisualProps = MakeObjectResponsive<{\n backgroundColor:\n | BackgroundColorString<'surface'>\n | BackgroundColorString<'overlay'>\n | BackgroundColorString<'feedback'>\n | 'transparent';\n}> & {\n // Intentionally keeping this outside of MakeObjectResponsive since we only want as to be string and not responsive object\n // styled-components do not support passing `as` prop as an object\n as: BoxAsType;\n};\n\ntype StyledPropsBlade = Partial<\n Omit<\n MarginProps &\n Pick<FlexboxProps, 'alignSelf' | 'justifySelf' | 'placeSelf' | 'order' | 'flexWrap'> &\n PositionProps &\n Pick<\n GridProps,\n | 'gridColumn'\n | 'gridRow'\n | 'gridRowStart'\n | 'gridRowEnd'\n | 'gridColumnStart'\n | 'gridColumnEnd'\n | 'gridArea'\n > &\n Pick<LayoutProps, 'display'> &\n Pick<CommonBoxVisualProps, 'visibility'>,\n '__brand__'\n >\n>;\n\ntype BoxCallbackProps = Omit<\n Platform.Select<{\n web: {\n /**\n * **Warning**\n *\n * Make sure to not use Box when you want to create a trigger that performs action on hover.\n * You would probably want to render it as `button` using `styled.button` instead.\n *\n * Use this for hoverable containers in cases like custom menus.\n */\n onMouseOver: React.MouseEventHandler<HTMLElement>;\n /**\n * **Warning**\n *\n * Make sure to not use Box when you want to create a trigger that performs action on hover.\n * You would probably want to render it as `button` using `styled.button` instead.\n *\n * Use this for hoverable containers in cases like custom menus.\n */\n onMouseEnter: React.MouseEventHandler<HTMLElement>;\n /**\n * **Warning**\n *\n * Make sure to not use Box when you want to create a trigger that performs action on hover.\n * You would probably want to render it as `button` using `styled.button` instead.\n *\n * Use this for hoverable containers in cases like custom menus.\n */\n onMouseLeave: React.MouseEventHandler<HTMLElement>;\n onScroll: React.UIEventHandler<HTMLElement>;\n };\n native: Record<'onMouseOver' | 'onMouseEnter' | 'onMouseLeave' | 'onScroll', undefined>;\n }>,\n '__brand__'\n>;\n\ntype BoxDragAndDropProps = Omit<\n Platform.Select<{\n web: {\n draggable: boolean;\n onDragStart: React.DragEventHandler<HTMLElement>;\n onDragEnter: React.DragEventHandler<HTMLElement>;\n onDragLeave: React.DragEventHandler<HTMLElement>;\n onDragOver: React.DragEventHandler<HTMLElement>;\n onDragEnd: React.DragEventHandler<HTMLElement>;\n onDrop: React.DragEventHandler<HTMLElement>;\n };\n native: Record<\n | 'draggable'\n | 'onDragStart'\n | 'onDragEnter'\n | 'onDragLeave'\n | 'onDragOver'\n | 'onDragEnd'\n | 'onDrop',\n undefined\n >;\n }>,\n '__brand__'\n>;\n\ntype BoxProps = Partial<\n PaddingProps &\n MarginProps &\n LayoutProps &\n FlexboxProps &\n PositionProps &\n GridProps &\n BoxCallbackProps &\n BoxDragAndDropProps &\n CommonBoxVisualProps &\n BoxVisualProps & {\n children?: React.ReactNode | React.ReactNode[];\n tabIndex?: number;\n id?: string;\n } & TestID &\n DataAnalyticsAttribute\n>;\n\n// Visual props have different types for BaseBox and Box. BaseBox has more flexible types and more props exposed.\n// So first we Omit Visual props of Box\n// Then we append BaseBoxVisualProps and some other props for styled-components like class and id\ntype BaseBoxProps = Omit<BoxProps, keyof BoxVisualProps> &\n Partial<\n DataAnalyticsAttribute &\n BaseBoxVisualProps & {\n className?: string;\n id?: string;\n tabIndex?: number;\n }\n > &\n BladeCommonEvents;\n\n// ref prop type\ntype BoxRefType = Platform.Select<{\n web: Omit<HTMLElement, 'style'>;\n native: View;\n}>;\n\nexport type { BaseBoxProps, BoxProps, BoxRefType, StyledPropsBlade, FlexboxProps, GridProps };\nexport { validBoxAsValues };\n"],"names":["validBoxAsValues"],"mappings":"AA+GM,IAAAA,gBAAgB,CAAG,CACvB,KAAK,CACL,SAAS,CACT,QAAQ,CACR,QAAQ,CACR,MAAM,CACN,OAAO,CACP,KAAK,CACL,MAAM,CACN,OAAO;;;;"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
|
|
2
2
|
import { dropdownComponentIds } from './dropdownComponentIds.js';
|
|
3
3
|
|
|
4
|
-
var SelectActions={Close:'Close',CloseSelect:'CloseSelect',First:'First',Last:'Last',Next:'Next',Open:'Open',PageDown:'PageDown',PageUp:'PageUp',Previous:'Previous',Select:'Select',Type:'Type'};function filterOptions(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var filter=arguments.length>1?arguments[1]:undefined;var exclude=arguments.length>2&&arguments[2]!==undefined?arguments[2]:[];return options.filter(function(option){var matches=option.toLowerCase().startsWith(filter.toLowerCase());return matches&&!exclude.includes(option);});}function getActionFromKey(e,isOpen,dropdownTriggerer){if(!e){return undefined;}var altKey=e.altKey,ctrlKey=e.ctrlKey,metaKey=e.metaKey;var key='';if('key'in e){key=e.key;}var openKeys=['ArrowDown','ArrowUp','Enter',' '];if(!key)return undefined;if(!isOpen&&key&&openKeys.includes(key)){return SelectActions.Open;}if(key==='Home'){return SelectActions.First;}if(key==='End'){return SelectActions.Last;}if(key==='Backspace'||key==='Clear'||key.length===1&&key!==' '&&!altKey&&!ctrlKey&&!metaKey){return SelectActions.Type;}if(isOpen){if(key==='ArrowUp'&&altKey){return SelectActions.CloseSelect;}else if(key==='ArrowDown'&&!altKey){return SelectActions.Next;}else if(key==='ArrowUp'){return SelectActions.Previous;}else if(key==='PageUp'){return SelectActions.PageUp;}else if(key==='PageDown'){return SelectActions.PageDown;}else if(key==='Escape'){return SelectActions.Close;}else if(key==='Enter'||dropdownTriggerer!==dropdownComponentIds.triggers.AutoComplete&&dropdownTriggerer!==dropdownComponentIds.triggers.SearchInput&&key===' '){return SelectActions.CloseSelect;}}return undefined;}function getIndexByLetter(options,filter){var startIndex=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var orderedOptions=[].concat(_toConsumableArray(options.slice(startIndex)),_toConsumableArray(options.slice(0,startIndex)));var firstMatch=filterOptions(orderedOptions,filter)[0];var allSameLetter=function allSameLetter(array){return array.every(function(letter){return letter===array[0];});};if(firstMatch){return options.indexOf(firstMatch);}else if(allSameLetter(filter.split(''))){var matches=filterOptions(orderedOptions,filter[0]);return options.indexOf(matches[0]);}else {return -1;}}function getUpdatedIndex(_ref){var currentIndex=_ref.currentIndex,maxIndex=_ref.maxIndex,actionType=_ref.actionType;var pageSize=10;switch(actionType){case SelectActions.First:return 0;case SelectActions.Last:return maxIndex;case SelectActions.Previous:return Math.max(0,currentIndex-1);case SelectActions.Next:return Math.min(maxIndex,currentIndex+1);case SelectActions.PageUp:return Math.max(0,currentIndex-pageSize);case SelectActions.PageDown:return Math.min(maxIndex,currentIndex+pageSize);default:return currentIndex;}}function isElementVisibleOnScreen(element){var bounding=element.getBoundingClientRect();return bounding.top>=0&&bounding.left>=0&&bounding.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&bounding.right<=(window.innerWidth||document.documentElement.clientWidth);}function isElementVisible(container,element){var containerRect=container.getBoundingClientRect();var elementRect=element.getBoundingClientRect();var isVerticalVisible=elementRect.top>=containerRect.top&&elementRect.bottom<=containerRect.bottom;return isVerticalVisible;}function isScrollable(element){return element&&element.clientHeight<element.scrollHeight;}var performAction=function performAction(action,payload,actions){var event=payload.event;switch(action){case SelectActions.Last:case SelectActions.First:actions.setIsOpen(true);case SelectActions.Next:case SelectActions.Previous:case SelectActions.PageUp:case SelectActions.PageDown:event.preventDefault();actions.onOptionChange(action);return true;case SelectActions.CloseSelect:event.preventDefault();actions.selectCurrentOption();return true;case SelectActions.Close:event.preventDefault();actions.close();return true;case SelectActions.Type:actions.onComboType(event.key,action);return true;case SelectActions.Open:event.preventDefault();actions.setIsOpen(true);return true;}return false;};var ensureScrollVisiblity=function ensureScrollVisiblity(newActiveIndex,containerElement,options){if(containerElement){if(isScrollable(containerElement)){var optionEl=containerElement.querySelectorAll('[role="option"], [role="menuitem"]');if(newActiveIndex>=0&&optionEl[newActiveIndex].dataset.value===options[newActiveIndex]){var activeElement=optionEl[newActiveIndex];if(!isElementVisible(containerElement,activeElement)){activeElement.scrollIntoView({inline:'nearest'});}if(!isElementVisibleOnScreen(optionEl[newActiveIndex])){activeElement.scrollIntoView({behavior:'smooth'});}}}}};var makeInputValue=function makeInputValue(selectedIndices,options){if(options.length===0){return '';}return selectedIndices.map(function(selectedIndex){var _options$selectedInde;return (_options$selectedInde=options[selectedIndex])==null?void 0:_options$selectedInde.value;}).join(', ');};var makeInputDisplayValue=function makeInputDisplayValue(selectedIndices,options){if(options.length===0||selectedIndices.length===0){return '';}if(selectedIndices.length===1){var _options$selectedIndi;return (_options$selectedIndi=options[selectedIndices[0]])==null?void 0:_options$selectedIndi.title;}return `${selectedIndices.length} items selected`;};
|
|
4
|
+
var SelectActions={Close:'Close',CloseSelect:'CloseSelect',First:'First',Last:'Last',Next:'Next',Open:'Open',PageDown:'PageDown',PageUp:'PageUp',Previous:'Previous',Select:'Select',Type:'Type'};function filterOptions(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var filter=arguments.length>1?arguments[1]:undefined;var exclude=arguments.length>2&&arguments[2]!==undefined?arguments[2]:[];return options.filter(function(option){var matches=String(option).toLowerCase().startsWith(filter.toLowerCase());return matches&&!exclude.includes(option);});}function getActionFromKey(e,isOpen,dropdownTriggerer){if(!e){return undefined;}var altKey=e.altKey,ctrlKey=e.ctrlKey,metaKey=e.metaKey;var key='';if('key'in e){key=e.key;}var openKeys=['ArrowDown','ArrowUp','Enter',' '];if(!key)return undefined;if(!isOpen&&key&&openKeys.includes(key)){return SelectActions.Open;}if(key==='Home'){return SelectActions.First;}if(key==='End'){return SelectActions.Last;}if(key==='Backspace'||key==='Clear'||key.length===1&&key!==' '&&!altKey&&!ctrlKey&&!metaKey){return SelectActions.Type;}if(isOpen){if(key==='ArrowUp'&&altKey){return SelectActions.CloseSelect;}else if(key==='ArrowDown'&&!altKey){return SelectActions.Next;}else if(key==='ArrowUp'){return SelectActions.Previous;}else if(key==='PageUp'){return SelectActions.PageUp;}else if(key==='PageDown'){return SelectActions.PageDown;}else if(key==='Escape'){return SelectActions.Close;}else if(key==='Enter'||dropdownTriggerer!==dropdownComponentIds.triggers.AutoComplete&&dropdownTriggerer!==dropdownComponentIds.triggers.SearchInput&&key===' '){return SelectActions.CloseSelect;}}return undefined;}function getIndexByLetter(options,filter){var startIndex=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var orderedOptions=[].concat(_toConsumableArray(options.slice(startIndex)),_toConsumableArray(options.slice(0,startIndex)));var firstMatch=filterOptions(orderedOptions,filter)[0];var allSameLetter=function allSameLetter(array){return array.every(function(letter){return letter===array[0];});};if(firstMatch){return options.indexOf(firstMatch);}else if(allSameLetter(filter.split(''))){var matches=filterOptions(orderedOptions,filter[0]);return options.indexOf(matches[0]);}else {return -1;}}function getUpdatedIndex(_ref){var currentIndex=_ref.currentIndex,maxIndex=_ref.maxIndex,actionType=_ref.actionType;var pageSize=10;switch(actionType){case SelectActions.First:return 0;case SelectActions.Last:return maxIndex;case SelectActions.Previous:return Math.max(0,currentIndex-1);case SelectActions.Next:return Math.min(maxIndex,currentIndex+1);case SelectActions.PageUp:return Math.max(0,currentIndex-pageSize);case SelectActions.PageDown:return Math.min(maxIndex,currentIndex+pageSize);default:return currentIndex;}}function isElementVisibleOnScreen(element){var bounding=element.getBoundingClientRect();return bounding.top>=0&&bounding.left>=0&&bounding.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&bounding.right<=(window.innerWidth||document.documentElement.clientWidth);}function isElementVisible(container,element){var containerRect=container.getBoundingClientRect();var elementRect=element.getBoundingClientRect();var isVerticalVisible=elementRect.top>=containerRect.top&&elementRect.bottom<=containerRect.bottom;return isVerticalVisible;}function isScrollable(element){return element&&element.clientHeight<element.scrollHeight;}var performAction=function performAction(action,payload,actions){var event=payload.event;switch(action){case SelectActions.Last:case SelectActions.First:actions.setIsOpen(true);case SelectActions.Next:case SelectActions.Previous:case SelectActions.PageUp:case SelectActions.PageDown:event.preventDefault();actions.onOptionChange(action);return true;case SelectActions.CloseSelect:event.preventDefault();actions.selectCurrentOption();return true;case SelectActions.Close:event.preventDefault();actions.close();return true;case SelectActions.Type:actions.onComboType(event.key,action);return true;case SelectActions.Open:event.preventDefault();actions.setIsOpen(true);return true;}return false;};var ensureScrollVisiblity=function ensureScrollVisiblity(newActiveIndex,containerElement,options){if(containerElement){if(isScrollable(containerElement)){var optionEl=containerElement.querySelectorAll('[role="option"], [role="menuitem"]');if(newActiveIndex>=0&&optionEl[newActiveIndex].dataset.value===options[newActiveIndex]){var activeElement=optionEl[newActiveIndex];if(!isElementVisible(containerElement,activeElement)){activeElement.scrollIntoView({inline:'nearest'});}if(!isElementVisibleOnScreen(optionEl[newActiveIndex])){activeElement.scrollIntoView({behavior:'smooth'});}}}}};var makeInputValue=function makeInputValue(selectedIndices,options){if(options.length===0){return '';}return selectedIndices.map(function(selectedIndex){var _options$selectedInde;return (_options$selectedInde=options[selectedIndex])==null?void 0:_options$selectedInde.value;}).join(', ');};var makeInputDisplayValue=function makeInputDisplayValue(selectedIndices,options){if(options.length===0||selectedIndices.length===0){return '';}if(selectedIndices.length===1){var _options$selectedIndi;return (_options$selectedIndi=options[selectedIndices[0]])==null?void 0:_options$selectedIndi.title;}return `${selectedIndices.length} items selected`;};
|
|
5
5
|
|
|
6
6
|
export { ensureScrollVisiblity, filterOptions, getActionFromKey, getIndexByLetter, getUpdatedIndex, isElementVisibleOnScreen, isScrollable, makeInputDisplayValue, makeInputValue, performAction };
|
|
7
7
|
//# sourceMappingURL=dropdownUtils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dropdownUtils.js","sources":["../../../../../src/components/Dropdown/dropdownUtils.ts"],"sourcesContent":["/*\n * This content is licensed according to the W3C Software License at\n * https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document\n *\n * This software or document includes material copied from or derived from\n * https://www.w3.org/WAI/ARIA/apg/example-index/combobox/combobox-select-only.html.\n * Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang)\n */\n\nimport type { DropdownContextType, OptionsType } from './useDropdown';\nimport { dropdownComponentIds } from './dropdownComponentIds';\nimport type { SpacingValueType } from '~components/Box/BaseBox';\n\nexport type SelectActionsType =\n | 'Close'\n | 'CloseSelect'\n | 'First'\n | 'Last'\n | 'Next'\n | 'Open'\n | 'PageDown'\n | 'PageUp'\n | 'Previous'\n | 'Select'\n | 'Type';\n\n// Save a list of named combobox actions, for future readability\nconst SelectActions: Record<SelectActionsType, SelectActionsType> = {\n Close: 'Close',\n CloseSelect: 'CloseSelect',\n First: 'First',\n Last: 'Last',\n Next: 'Next',\n Open: 'Open',\n PageDown: 'PageDown',\n PageUp: 'PageUp',\n Previous: 'Previous',\n Select: 'Select',\n Type: 'Type',\n};\n\n/**\n * Filter an array of options against an input string\n * returns an array of options that begin with the filter string, case-independent\n *\n */\nexport function filterOptions(\n options: string[] = [],\n filter: string,\n exclude: string[] = [],\n): string[] {\n return options.filter((option) => {\n const matches = option.toLowerCase().startsWith(filter.toLowerCase());\n return matches && !exclude.includes(option);\n });\n}\n\n/**\n * Map a keypress to action\n */\nexport function getActionFromKey(\n e: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>,\n isOpen: boolean,\n dropdownTriggerer: DropdownContextType['dropdownTriggerer'],\n): SelectActionsType | undefined {\n if (!e) {\n return undefined;\n }\n\n const { altKey, ctrlKey, metaKey } = e;\n let key = '';\n if ('key' in e) {\n key = e.key;\n }\n const openKeys = ['ArrowDown', 'ArrowUp', 'Enter', ' ']; // all keys that will do the default open action\n if (!key) return undefined;\n // handle opening when closed\n if (!isOpen && key && openKeys.includes(key)) {\n return SelectActions.Open;\n }\n\n // home and end move the selected option when open or closed\n if (key === 'Home') {\n return SelectActions.First;\n }\n if (key === 'End') {\n return SelectActions.Last;\n }\n\n // handle typing characters when open or closed\n if (\n key === 'Backspace' ||\n key === 'Clear' ||\n (key.length === 1 && key !== ' ' && !altKey && !ctrlKey && !metaKey)\n ) {\n return SelectActions.Type;\n }\n\n // handle keys when open\n if (isOpen) {\n if (key === 'ArrowUp' && altKey) {\n return SelectActions.CloseSelect;\n } else if (key === 'ArrowDown' && !altKey) {\n return SelectActions.Next;\n } else if (key === 'ArrowUp') {\n return SelectActions.Previous;\n } else if (key === 'PageUp') {\n return SelectActions.PageUp;\n } else if (key === 'PageDown') {\n return SelectActions.PageDown;\n } else if (key === 'Escape') {\n return SelectActions.Close;\n } else if (\n key === 'Enter' ||\n // we ignore the spacebar select in autocomplete since hitting spacebar might be expected while typing\n (dropdownTriggerer !== dropdownComponentIds.triggers.AutoComplete &&\n dropdownTriggerer !== dropdownComponentIds.triggers.SearchInput &&\n key === ' ')\n ) {\n return SelectActions.CloseSelect;\n }\n }\n\n return undefined;\n}\n\n/**\n * Return the index of an option from an array of options, based on a search string\n *\n * if the filter is multiple iterations of the same letter (e.g \"aaa\"), then cycle through first-letter matches\n **/\nexport function getIndexByLetter(options: string[], filter: string, startIndex = 0): number {\n const orderedOptions = [...options.slice(startIndex), ...options.slice(0, startIndex)];\n const firstMatch = filterOptions(orderedOptions, filter)[0];\n const allSameLetter = (array: string[]): boolean => array.every((letter) => letter === array[0]);\n\n // first check if there is an exact match for the typed string\n if (firstMatch) {\n return options.indexOf(firstMatch);\n }\n\n // if the same letter is being repeated, cycle through first-letter matches\n else if (allSameLetter(filter.split(''))) {\n const matches = filterOptions(orderedOptions, filter[0]);\n return options.indexOf(matches[0]);\n }\n\n // if no matches, return -1\n else {\n return -1;\n }\n}\n\n/**\n * This functions makes sure the optionsIndex is not going out of possible options\n */\nexport function getUpdatedIndex({\n currentIndex,\n maxIndex,\n actionType,\n}: {\n currentIndex: number;\n maxIndex: number;\n actionType: SelectActionsType;\n}): number {\n // On PageUP or PageDown, we jump focus by 10 items or to the first or last element\n // Details: https://www.w3.org/WAI/ARIA/apg/example-index/combobox/combobox-select-only.html#:~:text=PageUp,to%20last%20option).\n const pageSize = 10;\n\n switch (actionType) {\n case SelectActions.First:\n return 0;\n case SelectActions.Last:\n return maxIndex;\n case SelectActions.Previous:\n return Math.max(0, currentIndex - 1);\n case SelectActions.Next:\n return Math.min(maxIndex, currentIndex + 1);\n case SelectActions.PageUp:\n return Math.max(0, currentIndex - pageSize);\n case SelectActions.PageDown:\n return Math.min(maxIndex, currentIndex + pageSize);\n default:\n return currentIndex;\n }\n}\n\n/**\n * Checks if the given HTML element is visible on screen\n */\nexport function isElementVisibleOnScreen(element: HTMLElement): boolean {\n const bounding = element.getBoundingClientRect();\n\n return (\n bounding.top >= 0 &&\n bounding.left >= 0 &&\n bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&\n bounding.right <= (window.innerWidth || document.documentElement.clientWidth)\n );\n}\n\n/**\n * Checks if element is visible inside the given container\n */\nfunction isElementVisible(container: HTMLElement, element: HTMLElement): boolean {\n const containerRect = container.getBoundingClientRect();\n const elementRect = element.getBoundingClientRect();\n\n const isVerticalVisible =\n elementRect.top >= containerRect.top && elementRect.bottom <= containerRect.bottom;\n\n return isVerticalVisible;\n}\n\n/**\n * Checks if the dropdown is scrollable\n */\nexport function isScrollable(element: HTMLElement): boolean {\n return element && element.clientHeight < element.scrollHeight;\n}\n\ntype ActionsType = {\n setIsOpen: DropdownContextType['setIsOpen'];\n close: DropdownContextType['close'];\n selectCurrentOption: () => void;\n onOptionChange: (action: SelectActionsType) => void;\n onComboType: (letter: string, action: SelectActionsType) => void;\n};\n/**\n * Performs the action when actionType is passed\n *\n * This function handles all the keydown actions.\n */\nexport const performAction = (\n action: SelectActionsType,\n payload: {\n event: React.KeyboardEvent<HTMLInputElement | HTMLButtonElement>;\n },\n actions: ActionsType,\n): boolean => {\n const { event } = payload;\n\n switch (action) {\n case SelectActions.Last:\n // @ts-expect-error: intentional fallthrough, ignoring the warning\n case SelectActions.First:\n actions.setIsOpen(true);\n // intentional fallthrough\n case SelectActions.Next:\n case SelectActions.Previous:\n case SelectActions.PageUp:\n case SelectActions.PageDown:\n event.preventDefault();\n actions.onOptionChange(action);\n return true;\n case SelectActions.CloseSelect:\n event.preventDefault();\n actions.selectCurrentOption();\n return true;\n case SelectActions.Close:\n event.preventDefault();\n actions.close();\n return true;\n case SelectActions.Type:\n actions.onComboType(event.key, action);\n return true;\n case SelectActions.Open:\n event.preventDefault();\n actions.setIsOpen(true);\n return true;\n\n default:\n break;\n }\n\n return false;\n};\n\n/**\n * When options list is large, it can have a scrollbar.\n *\n * This function ensures the active option is always in the viewport\n */\nexport const ensureScrollVisiblity = (\n newActiveIndex: number,\n containerElement: HTMLElement | null,\n options: string[],\n): void => {\n // ensure the new option is in view\n if (containerElement) {\n if (isScrollable(containerElement)) {\n const optionEl = containerElement.querySelectorAll<HTMLElement>(\n '[role=\"option\"], [role=\"menuitem\"]',\n );\n // Making sure its the same element as the one from options state\n if (\n newActiveIndex >= 0 &&\n optionEl[newActiveIndex].dataset.value === options[newActiveIndex]\n ) {\n const activeElement = optionEl[newActiveIndex];\n\n if (!isElementVisible(containerElement, activeElement)) {\n activeElement.scrollIntoView({ inline: 'nearest' });\n }\n\n if (!isElementVisibleOnScreen(optionEl[newActiveIndex])) {\n activeElement.scrollIntoView({ behavior: 'smooth' });\n }\n }\n }\n }\n};\n\n/**\n * value that is set in the actual form input\n */\nexport const makeInputValue = (selectedIndices: number[], options: OptionsType): string => {\n if (options.length === 0) {\n return '';\n }\n return selectedIndices.map((selectedIndex) => options[selectedIndex]?.value).join(', ');\n};\n\n/**\n * Value that is displayed inside the select field\n */\nexport const makeInputDisplayValue = (selectedIndices: number[], options: OptionsType): string => {\n // When no item is selected or no item is present\n if (options.length === 0 || selectedIndices.length === 0) {\n return '';\n }\n\n // When one item is selected, we display that item's title in input\n if (selectedIndices.length === 1) {\n return options[selectedIndices[0]]?.title;\n }\n\n // When more than one item is selected, we display the count of items\n return `${selectedIndices.length} items selected`;\n};\n\nexport type DropdownPosition = {\n top?: SpacingValueType;\n bottom?: SpacingValueType;\n left?: SpacingValueType;\n right?: SpacingValueType;\n};\n"],"names":["SelectActions","Close","CloseSelect","First","Last","Next","Open","PageDown","PageUp","Previous","Select","Type","filterOptions","options","arguments","length","undefined","filter","exclude","option","matches","toLowerCase","startsWith","includes","getActionFromKey","e","isOpen","dropdownTriggerer","altKey","ctrlKey","metaKey","key","openKeys","dropdownComponentIds","triggers","AutoComplete","SearchInput","getIndexByLetter","startIndex","orderedOptions","concat","_toConsumableArray","slice","firstMatch","allSameLetter","array","every","letter","indexOf","split","getUpdatedIndex","_ref","currentIndex","maxIndex","actionType","pageSize","Math","max","min","isElementVisibleOnScreen","element","bounding","getBoundingClientRect","top","left","bottom","window","innerHeight","document","documentElement","clientHeight","right","innerWidth","clientWidth","isElementVisible","container","containerRect","elementRect","isVerticalVisible","isScrollable","scrollHeight","performAction","action","payload","actions","event","setIsOpen","preventDefault","onOptionChange","selectCurrentOption","close","onComboType","ensureScrollVisiblity","newActiveIndex","containerElement","optionEl","querySelectorAll","dataset","value","activeElement","scrollIntoView","inline","behavior","makeInputValue","selectedIndices","map","selectedIndex","_options$selectedInde","join","makeInputDisplayValue","_options$selectedIndi","title"],"mappings":";;;AA2BA,IAAMA,aAA2D,CAAG,CAClEC,KAAK,CAAE,OAAO,CACdC,WAAW,CAAE,aAAa,CAC1BC,KAAK,CAAE,OAAO,CACdC,IAAI,CAAE,MAAM,CACZC,IAAI,CAAE,MAAM,CACZC,IAAI,CAAE,MAAM,CACZC,QAAQ,CAAE,UAAU,CACpBC,MAAM,CAAE,QAAQ,CAChBC,QAAQ,CAAE,UAAU,CACpBC,MAAM,CAAE,QAAQ,CAChBC,IAAI,CAAE,MACR,CAAC,CAOe,SAAAC,aAAaA,EAIjB,CAHV,IAAAC,OAAiB,CAAAC,SAAA,CAAAC,MAAA,IAAAD,SAAA,CAAA,CAAA,CAAA,GAAAE,SAAA,CAAAF,SAAA,CAAG,CAAA,CAAA,CAAA,EAAE,CACtB,IAAAG,MAAc,CAAAH,SAAA,CAAAC,MAAA,GAAAD,SAAA,CAAA,CAAA,CAAA,CAAAE,SAAA,CAAA,IACdE,OAAiB,CAAAJ,SAAA,CAAAC,MAAA,CAAAD,CAAAA,EAAAA,SAAA,CAAAE,CAAAA,CAAAA,GAAAA,SAAA,CAAAF,SAAA,CAAA,CAAA,CAAA,CAAG,EAAE,CAEtB,OAAOD,OAAO,CAACI,MAAM,CAAC,SAACE,MAAM,CAAK,CAChC,IAAMC,OAAO,CAAGD,MAAM,CAACE,WAAW,EAAE,CAACC,UAAU,CAACL,MAAM,CAACI,WAAW,EAAE,CAAC,CACrE,OAAOD,OAAO,EAAI,CAACF,OAAO,CAACK,QAAQ,CAACJ,MAAM,CAAC,CAC7C,CAAC,CAAC,CACJ,CAKgB,SAAAK,gBAAgBA,CAC9BC,CAAmE,CACnEC,MAAe,CACfC,iBAA2D,CAC5B,CAC/B,GAAI,CAACF,CAAC,CAAE,CACN,OAAOT,SAAS,CAClB,CAEA,IAAQY,MAAM,CAAuBH,CA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CAAE,CACxB,OAAO,EAAE,CACX,CACA,OAAOyF,eAAe,CAACC,GAAG,CAAC,SAACC,aAAa,CAAAC,CAAAA,IAAAA,qBAAA,SAAAA,qBAAA,CAAK9F,OAAO,CAAC6F,aAAa,CAAC,GAAA,IAAA,CAAA,KAAA,CAAA,CAAtBC,qBAAA,CAAwBT,KAAK,CAAC,CAAA,CAAA,CAACU,IAAI,CAAC,IAAI,CAAC,CACzF,EAKa,IAAAC,qBAAqB,CAAG,SAAxBA,qBAAqBA,CAAIL,eAAyB,CAAE3F,OAAoB,CAAa,CAEhG,GAAIA,OAAO,CAACE,MAAM,GAAK,CAAC,EAAIyF,eAAe,CAACzF,MAAM,GAAK,CAAC,CAAE,CACxD,OAAO,EAAE,CACX,CAGA,GAAIyF,eAAe,CAACzF,MAAM,GAAK,CAAC,CAAE,CAAA+F,IAAAA,qBAAA,CAChC,OAAA,CAAAA,qBAAA,CAAOjG,OAAO,CAAC2F,eAAe,CAAC,CAAC,CAAC,CAAC,GAAA,IAAA,CAAA,KAAA,CAAA,CAA3BM,qBAAA,CAA6BC,KAAK,CAC3C,CAGA,OAAO,CAAGP,EAAAA,eAAe,CAACzF,MAAM,CAAA,eAAA,CAAiB,CACnD;;;;"}
|
|
1
|
+
{"version":3,"file":"dropdownUtils.js","sources":["../../../../../src/components/Dropdown/dropdownUtils.ts"],"sourcesContent":["/*\n * This content is licensed according to the W3C Software License at\n * https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document\n *\n * This software or document includes material copied from or derived from\n * https://www.w3.org/WAI/ARIA/apg/example-index/combobox/combobox-select-only.html.\n * Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang)\n */\n\nimport type { DropdownContextType, OptionsType } from './useDropdown';\nimport { dropdownComponentIds } from './dropdownComponentIds';\nimport type { SpacingValueType } from '~components/Box/BaseBox';\n\nexport type SelectActionsType =\n | 'Close'\n | 'CloseSelect'\n | 'First'\n | 'Last'\n | 'Next'\n | 'Open'\n | 'PageDown'\n | 'PageUp'\n | 'Previous'\n | 'Select'\n | 'Type';\n\n// Save a list of named combobox actions, for future readability\nconst SelectActions: Record<SelectActionsType, SelectActionsType> = {\n Close: 'Close',\n CloseSelect: 'CloseSelect',\n First: 'First',\n Last: 'Last',\n Next: 'Next',\n Open: 'Open',\n PageDown: 'PageDown',\n PageUp: 'PageUp',\n Previous: 'Previous',\n Select: 'Select',\n Type: 'Type',\n};\n\n/**\n * Filter an array of options against an input string\n * returns an array of options that begin with the filter string, case-independent\n *\n */\nexport function filterOptions(\n options: string[] = [],\n filter: string,\n exclude: string[] = [],\n): string[] {\n return options.filter((option) => {\n const matches = String(option).toLowerCase().startsWith(filter.toLowerCase());\n return matches && !exclude.includes(option);\n });\n}\n\n/**\n * Map a keypress to action\n */\nexport function getActionFromKey(\n e: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>,\n isOpen: boolean,\n dropdownTriggerer: DropdownContextType['dropdownTriggerer'],\n): SelectActionsType | undefined {\n if (!e) {\n return undefined;\n }\n\n const { altKey, ctrlKey, metaKey } = e;\n let key = '';\n if ('key' in e) {\n key = e.key;\n }\n const openKeys = ['ArrowDown', 'ArrowUp', 'Enter', ' ']; // all keys that will do the default open action\n if (!key) return undefined;\n // handle opening when closed\n if (!isOpen && key && openKeys.includes(key)) {\n return SelectActions.Open;\n }\n\n // home and end move the selected option when open or closed\n if (key === 'Home') {\n return SelectActions.First;\n }\n if (key === 'End') {\n return SelectActions.Last;\n }\n\n // handle typing characters when open or closed\n if (\n key === 'Backspace' ||\n key === 'Clear' ||\n (key.length === 1 && key !== ' ' && !altKey && !ctrlKey && !metaKey)\n ) {\n return SelectActions.Type;\n }\n\n // handle keys when open\n if (isOpen) {\n if (key === 'ArrowUp' && altKey) {\n return SelectActions.CloseSelect;\n } else if (key === 'ArrowDown' && !altKey) {\n return SelectActions.Next;\n } else if (key === 'ArrowUp') {\n return SelectActions.Previous;\n } else if (key === 'PageUp') {\n return SelectActions.PageUp;\n } else if (key === 'PageDown') {\n return SelectActions.PageDown;\n } else if (key === 'Escape') {\n return SelectActions.Close;\n } else if (\n key === 'Enter' ||\n // we ignore the spacebar select in autocomplete since hitting spacebar might be expected while typing\n (dropdownTriggerer !== dropdownComponentIds.triggers.AutoComplete &&\n dropdownTriggerer !== dropdownComponentIds.triggers.SearchInput &&\n key === ' ')\n ) {\n return SelectActions.CloseSelect;\n }\n }\n\n return undefined;\n}\n\n/**\n * Return the index of an option from an array of options, based on a search string\n *\n * if the filter is multiple iterations of the same letter (e.g \"aaa\"), then cycle through first-letter matches\n **/\nexport function getIndexByLetter(options: string[], filter: string, startIndex = 0): number {\n const orderedOptions = [...options.slice(startIndex), ...options.slice(0, startIndex)];\n const firstMatch = filterOptions(orderedOptions, filter)[0];\n const allSameLetter = (array: string[]): boolean => array.every((letter) => letter === array[0]);\n\n // first check if there is an exact match for the typed string\n if (firstMatch) {\n return options.indexOf(firstMatch);\n }\n\n // if the same letter is being repeated, cycle through first-letter matches\n else if (allSameLetter(filter.split(''))) {\n const matches = filterOptions(orderedOptions, filter[0]);\n return options.indexOf(matches[0]);\n }\n\n // if no matches, return -1\n else {\n return -1;\n }\n}\n\n/**\n * This functions makes sure the optionsIndex is not going out of possible options\n */\nexport function getUpdatedIndex({\n currentIndex,\n maxIndex,\n actionType,\n}: {\n currentIndex: number;\n maxIndex: number;\n actionType: SelectActionsType;\n}): number {\n // On PageUP or PageDown, we jump focus by 10 items or to the first or last element\n // Details: https://www.w3.org/WAI/ARIA/apg/example-index/combobox/combobox-select-only.html#:~:text=PageUp,to%20last%20option).\n const pageSize = 10;\n\n switch (actionType) {\n case SelectActions.First:\n return 0;\n case SelectActions.Last:\n return maxIndex;\n case SelectActions.Previous:\n return Math.max(0, currentIndex - 1);\n case SelectActions.Next:\n return Math.min(maxIndex, currentIndex + 1);\n case SelectActions.PageUp:\n return Math.max(0, currentIndex - pageSize);\n case SelectActions.PageDown:\n return Math.min(maxIndex, currentIndex + pageSize);\n default:\n return currentIndex;\n }\n}\n\n/**\n * Checks if the given HTML element is visible on screen\n */\nexport function isElementVisibleOnScreen(element: HTMLElement): boolean {\n const bounding = element.getBoundingClientRect();\n\n return (\n bounding.top >= 0 &&\n bounding.left >= 0 &&\n bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&\n bounding.right <= (window.innerWidth || document.documentElement.clientWidth)\n );\n}\n\n/**\n * Checks if element is visible inside the given container\n */\nfunction isElementVisible(container: HTMLElement, element: HTMLElement): boolean {\n const containerRect = container.getBoundingClientRect();\n const elementRect = element.getBoundingClientRect();\n\n const isVerticalVisible =\n elementRect.top >= containerRect.top && elementRect.bottom <= containerRect.bottom;\n\n return isVerticalVisible;\n}\n\n/**\n * Checks if the dropdown is scrollable\n */\nexport function isScrollable(element: HTMLElement): boolean {\n return element && element.clientHeight < element.scrollHeight;\n}\n\ntype ActionsType = {\n setIsOpen: DropdownContextType['setIsOpen'];\n close: DropdownContextType['close'];\n selectCurrentOption: () => void;\n onOptionChange: (action: SelectActionsType) => void;\n onComboType: (letter: string, action: SelectActionsType) => void;\n};\n/**\n * Performs the action when actionType is passed\n *\n * This function handles all the keydown actions.\n */\nexport const performAction = (\n action: SelectActionsType,\n payload: {\n event: React.KeyboardEvent<HTMLInputElement | HTMLButtonElement>;\n },\n actions: ActionsType,\n): boolean => {\n const { event } = payload;\n\n switch (action) {\n case SelectActions.Last:\n // @ts-expect-error: intentional fallthrough, ignoring the warning\n case SelectActions.First:\n actions.setIsOpen(true);\n // intentional fallthrough\n case SelectActions.Next:\n case SelectActions.Previous:\n case SelectActions.PageUp:\n case SelectActions.PageDown:\n event.preventDefault();\n actions.onOptionChange(action);\n return true;\n case SelectActions.CloseSelect:\n event.preventDefault();\n actions.selectCurrentOption();\n return true;\n case SelectActions.Close:\n event.preventDefault();\n actions.close();\n return true;\n case SelectActions.Type:\n actions.onComboType(event.key, action);\n return true;\n case SelectActions.Open:\n event.preventDefault();\n actions.setIsOpen(true);\n return true;\n\n default:\n break;\n }\n\n return false;\n};\n\n/**\n * When options list is large, it can have a scrollbar.\n *\n * This function ensures the active option is always in the viewport\n */\nexport const ensureScrollVisiblity = (\n newActiveIndex: number,\n containerElement: HTMLElement | null,\n options: string[],\n): void => {\n // ensure the new option is in view\n if (containerElement) {\n if (isScrollable(containerElement)) {\n const optionEl = containerElement.querySelectorAll<HTMLElement>(\n '[role=\"option\"], [role=\"menuitem\"]',\n );\n // Making sure its the same element as the one from options state\n if (\n newActiveIndex >= 0 &&\n optionEl[newActiveIndex].dataset.value === options[newActiveIndex]\n ) {\n const activeElement = optionEl[newActiveIndex];\n\n if (!isElementVisible(containerElement, activeElement)) {\n activeElement.scrollIntoView({ inline: 'nearest' });\n }\n\n if (!isElementVisibleOnScreen(optionEl[newActiveIndex])) {\n activeElement.scrollIntoView({ behavior: 'smooth' });\n }\n }\n }\n }\n};\n\n/**\n * value that is set in the actual form input\n */\nexport const makeInputValue = (selectedIndices: number[], options: OptionsType): string => {\n if (options.length === 0) {\n return '';\n }\n return selectedIndices.map((selectedIndex) => options[selectedIndex]?.value).join(', ');\n};\n\n/**\n * Value that is displayed inside the select field\n */\nexport const makeInputDisplayValue = (selectedIndices: number[], options: OptionsType): string => {\n // When no item is selected or no item is present\n if (options.length === 0 || selectedIndices.length === 0) {\n return '';\n }\n\n // When one item is selected, we display that item's title in input\n if (selectedIndices.length === 1) {\n return options[selectedIndices[0]]?.title;\n }\n\n // When more than one item is selected, we display the count of items\n return `${selectedIndices.length} items selected`;\n};\n\nexport type DropdownPosition = {\n top?: SpacingValueType;\n bottom?: SpacingValueType;\n left?: SpacingValueType;\n right?: SpacingValueType;\n};\n"],"names":["SelectActions","Close","CloseSelect","First","Last","Next","Open","PageDown","PageUp","Previous","Select","Type","filterOptions","options","arguments","length","undefined","filter","exclude","option","matches","String","toLowerCase","startsWith","includes","getActionFromKey","e","isOpen","dropdownTriggerer","altKey","ctrlKey","metaKey","key","openKeys","dropdownComponentIds","triggers","AutoComplete","SearchInput","getIndexByLetter","startIndex","orderedOptions","concat","_toConsumableArray","slice","firstMatch","allSameLetter","array","every","letter","indexOf","split","getUpdatedIndex","_ref","currentIndex","maxIndex","actionType","pageSize","Math","max","min","isElementVisibleOnScreen","element","bounding","getBoundingClientRect","top","left","bottom","window","innerHeight","document","documentElement","clientHeight","right","innerWidth","clientWidth","isElementVisible","container","containerRect","elementRect","isVerticalVisible","isScrollable","scrollHeight","performAction","action","payload","actions","event","setIsOpen","preventDefault","onOptionChange","selectCurrentOption","close","onComboType","ensureScrollVisiblity","newActiveIndex","containerElement","optionEl","querySelectorAll","dataset","value","activeElement","scrollIntoView","inline","behavior","makeInputValue","selectedIndices","map","selectedIndex","_options$selectedInde","join","makeInputDisplayValue","_options$selectedIndi","title"],"mappings":";;;AA2BA,IAAMA,aAA2D,CAAG,CAClEC,KAAK,CAAE,OAAO,CACdC,WAAW,CAAE,aAAa,CAC1BC,KAAK,CAAE,OAAO,CACdC,IAAI,CAAE,MAAM,CACZC,IAAI,CAAE,MAAM,CACZC,IAAI,CAAE,MAAM,CACZC,QAAQ,CAAE,UAAU,CACpBC,MAAM,CAAE,QAAQ,CAChBC,QAAQ,CAAE,UAAU,CACpBC,MAAM,CAAE,QAAQ,CAChBC,IAAI,CAAE,MACR,CAAC,CAOe,SAAAC,aAAaA,EAIjB,CAHV,IAAAC,OAAiB,CAAAC,SAAA,CAAAC,MAAA,IAAAD,SAAA,CAAA,CAAA,CAAA,GAAAE,SAAA,CAAAF,SAAA,CAAG,CAAA,CAAA,CAAA,EAAE,KACtBG,MAAc,CAAAH,SAAA,CAAAC,MAAA,CAAA,CAAA,CAAAD,SAAA,CAAAE,CAAAA,CAAAA,CAAAA,SAAA,CACd,IAAAE,OAAiB,CAAAJ,SAAA,CAAAC,MAAA,IAAAD,SAAA,CAAA,CAAA,CAAA,GAAAE,SAAA,CAAAF,SAAA,CAAG,CAAA,CAAA,CAAA,EAAE,CAEtB,OAAOD,OAAO,CAACI,MAAM,CAAC,SAACE,MAAM,CAAK,CAChC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cAAc,CAAC,CAAEC,MAAM,CAAE,SAAU,CAAC,CAAC,CACrD,CAEA,GAAI,CAAC1C,wBAAwB,CAACoC,QAAQ,CAACF,cAAc,CAAC,CAAC,CAAE,CACvDM,aAAa,CAACC,cAAc,CAAC,CAAEE,QAAQ,CAAE,QAAS,CAAC,CAAC,CACtD,CACF,CACF,CACF,CACF,EAKa,IAAAC,cAAc,CAAG,SAAjBA,cAAcA,CAAIC,eAAyB,CAAE5F,OAAoB,CAAa,CACzF,GAAIA,OAAO,CAACE,MAAM,GAAK,CAAC,CAAE,CACxB,OAAO,EAAE,CACX,CACA,OAAO0F,eAAe,CAACC,GAAG,CAAC,SAACC,aAAa,CAAA,CAAA,IAAAC,qBAAA,CAAAA,OAAAA,CAAAA,qBAAA,CAAK/F,OAAO,CAAC8F,aAAa,CAAC,eAAtBC,qBAAA,CAAwBT,KAAK,CAAA,CAAA,CAAC,CAACU,IAAI,CAAC,IAAI,CAAC,CACzF,EAKa,IAAAC,qBAAqB,CAAG,SAAxBA,qBAAqBA,CAAIL,eAAyB,CAAE5F,OAAoB,CAAa,CAEhG,GAAIA,OAAO,CAACE,MAAM,GAAK,CAAC,EAAI0F,eAAe,CAAC1F,MAAM,GAAK,CAAC,CAAE,CACxD,OAAO,EAAE,CACX,CAGA,GAAI0F,eAAe,CAAC1F,MAAM,GAAK,CAAC,CAAE,CAAAgG,IAAAA,qBAAA,CAChC,OAAA,CAAAA,qBAAA,CAAOlG,OAAO,CAAC4F,eAAe,CAAC,CAAC,CAAC,CAAC,GAAA,IAAA,CAAA,KAAA,CAAA,CAA3BM,qBAAA,CAA6BC,KAAK,CAC3C,CAGA,OAAO,CAAGP,EAAAA,eAAe,CAAC1F,MAAM,CAAA,eAAA,CAAiB,CACnD;;;;"}
|
|
@@ -41,7 +41,7 @@ import { getOuterMotionRef, getInnerMotionRef } from '../../../utils/getMotionRe
|
|
|
41
41
|
import { makeAnalyticsAttribute } from '../../../utils/makeAnalyticsAttribute/makeAnalyticsAttribute.js';
|
|
42
42
|
import { useInputGroupContext } from '../../InputGroup/InputGroupContext.js';
|
|
43
43
|
|
|
44
|
-
var _excluded=["as","label","labelPosition","placeholder","type","defaultValue","tags","showAllTags","activeTagIndex","setActiveTagIndex","name","value","onFocus","onChange","onInput","onBlur","onSubmit","onClick","onKeyDown","isDisabled","necessityIndicator","validationState","errorText","helpText","successText","isRequired","leadingIcon","prefix","trailingInteractionElement","onTrailingInteractionElementClick","leadingInteractionElement","suffix","trailingIcon","maxCharacters","textAlign","autoFocus","keyboardReturnKeyType","keyboardType","autoCompleteSuggestionType","trailingHeaderSlot","trailingFooterSlot","numberOfLines","id","componentName","accessibilityLabel","labelId","activeDescendant","hideLabelText","hideFormHint","hasPopup","popupId","isPopupExpanded","maxTagRows","shouldIgnoreBlurAnimation","setShouldIgnoreBlurAnimation","autoCapitalize","setInputWrapperRef","testID","isDropdownTrigger","isLabelInsideInput","size","trailingButton","valueComponentType","isTableInputCell","showHintsAsTooltip","_motionMeta","role","tabIndex","leadingDropDown","trailingDropDown","labelSuffix","labelTrailing","valueSuffix"];var autoCompleteSuggestionTypeValues=['none','on','name','email','username','password','newPassword','oneTimeCode','telephone','postalCode','countryName','creditCardNumber','creditCardCSC','creditCardExpiry','creditCardExpiryMonth','creditCardExpiryYear'];var useTags=function useTags(tags,activeTagIndex,setActiveTagIndex){var visibleTagsCountRef=React__default.useRef(0);React__default.useEffect(function(){if(tags&&activeTagIndex>=0&&activeTagIndex<tags.length){var _tags$activeTagIndex,_tags$activeTagIndex$;var tagTitle=(_tags$activeTagIndex=tags[activeTagIndex])==null?void 0:(_tags$activeTagIndex$=_tags$activeTagIndex.props)==null?void 0:_tags$activeTagIndex$.children;if(tagTitle){announce(`Close ${tagTitle} Tag`);}}},[activeTagIndex,tags==null?void 0:tags.length]);var onTagLeft=function onTagLeft(){if(activeTagIndex<0){setActiveTagIndex==null?void 0:setActiveTagIndex(visibleTagsCountRef.current-1);}if(activeTagIndex>0){setActiveTagIndex==null?void 0:setActiveTagIndex(activeTagIndex-1);}};var onTagRight=function onTagRight(){if(activeTagIndex<visibleTagsCountRef.current-1){setActiveTagIndex==null?void 0:setActiveTagIndex(activeTagIndex+1);}};var onTagRemove=function onTagRemove(){if(activeTagIndex>=0&&activeTagIndex<visibleTagsCountRef.current&&tags){tags[activeTagIndex].props.onDismiss({tagIndex:activeTagIndex});}};var onInputKeydownTagHandler=function onInputKeydownTagHandler(key){if(tags&&tags.length>0){if(key==='ArrowRight'){onTagRight();}if(key==='ArrowLeft'){onTagLeft();}if(key==='Backspace'){onTagRemove();}}};return {onInputKeydownTagHandler:onInputKeydownTagHandler,visibleTagsCountRef:visibleTagsCountRef};};var useInput=function useInput(_ref){var value=_ref.value,defaultValue=_ref.defaultValue,onClick=_ref.onClick,onFocus=_ref.onFocus,onChange=_ref.onChange,onBlur=_ref.onBlur,onSubmit=_ref.onSubmit,onInput=_ref.onInput,onKeyDown=_ref.onKeyDown,onInputKeydownTagHandler=_ref.onInputKeydownTagHandler;if(__DEV__){if(value&&defaultValue){throwBladeError({message:`Either 'value' or 'defaultValue' shall be passed. This decides if the input field is controlled or uncontrolled`,moduleName:'Input'});}}var _React$useState=React__default.useState(defaultValue!=null?defaultValue:value),_React$useState2=_slicedToArray(_React$useState,2),inputValue=_React$useState2[0],setInputValue=_React$useState2[1];var handleOnFocus=React__default.useCallback(function(_ref2){var name=_ref2.name,value=_ref2.value;var _value='';if(getPlatformType()==='react-native'&&typeof value==='string'){_value=value;}else if(typeof value!=='string'){var _value$target$value;_value=(_value$target$value=value==null?void 0:value.target.value)!=null?_value$target$value:'';}onFocus==null?void 0:onFocus({name:name,value:_value});},[onFocus]);var handleOnClick=React__default.useCallback(function(_ref3){var name=_ref3.name,value=_ref3.value;var _value='';if(getPlatformType()==='react-native'&&typeof value==='string'){_value=value;}else if(typeof value!=='string'){var _value$currentTarget$;_value=(_value$currentTarget$=value==null?void 0:value.currentTarget.value)!=null?_value$currentTarget$:'';}onClick==null?void 0:onClick({name:name,value:_value});},[onClick]);var handleOnSubmit=React__default.useCallback(function(_ref4){var name=_ref4.name,value=_ref4.value;var _value='';if(getPlatformType()==='react-native'&&typeof value==='string'){_value=value;}else if(typeof value!=='string'){var _value$target$value2;_value=(_value$target$value2=value==null?void 0:value.target.value)!=null?_value$target$value2:'';}if(isReactNative()){onSubmit==null?void 0:onSubmit({name:name,value:_value});}},[onSubmit]);var handleOnBlur=React__default.useCallback(function(_ref5){var name=_ref5.name,value=_ref5.value;var _value='';if(getPlatformType()==='react-native'&&typeof value=='string'){_value=value;}else if(typeof value!=='string'){var _value$target$value3;_value=(_value$target$value3=value==null?void 0:value.target.value)!=null?_value$target$value3:'';}onBlur==null?void 0:onBlur({name:name,value:_value});},[onBlur]);var handleOnChange=React__default.useCallback(function(_ref6){var name=_ref6.name,value=_ref6.value;var _value='';if(getPlatformType()==='react-native'&&typeof value==='string'){_value=value;}else if(typeof value!=='string'){var _value$target$value4;_value=(_value$target$value4=value==null?void 0:value.target.value)!=null?_value$target$value4:'';}onChange==null?void 0:onChange({name:name,value:_value});setInputValue(_value);},[onChange]);var handleOnInput=React__default.useCallback(function(_ref7){var name=_ref7.name,value=_ref7.value;var _value='';if(getPlatformType()==='react-native'&&typeof value=='string'){_value=value;}else if(typeof value!=='string'){var _value$target$value5;_value=(_value$target$value5=value==null?void 0:value.target.value)!=null?_value$target$value5:'';}onInput==null?void 0:onInput({name:name,value:_value});},[onInput]);var handleOnKeyDown=React__default.useCallback(function(_ref8){var name=_ref8.name,key=_ref8.key,code=_ref8.code,event=_ref8.event;onInputKeydownTagHandler(key);onKeyDown==null?void 0:onKeyDown({name:name,key:key,code:code,event:event});},[onKeyDown]);return {handleOnFocus:handleOnFocus,handleOnClick:handleOnClick,handleOnChange:handleOnChange,handleOnBlur:handleOnBlur,handleOnSubmit:handleOnSubmit,handleOnInput:handleOnInput,handleOnKeyDown:handleOnKeyDown,inputValue:inputValue};};var getHintType=function getHintType(_ref9){var validationState=_ref9.validationState,hasHelpText=_ref9.hasHelpText;if(validationState==='error'){return 'error';}if(validationState==='success'){return 'success';}if(hasHelpText){return 'help';}return 'help';};var getDescribedByElementId=function getDescribedByElementId(_ref0){var validationState=_ref0.validationState,hasErrorText=_ref0.hasErrorText,hasSuccessText=_ref0.hasSuccessText,hasHelpText=_ref0.hasHelpText,errorTextId=_ref0.errorTextId,successTextId=_ref0.successTextId,helpTextId=_ref0.helpTextId;if(validationState==='error'&&hasErrorText){return errorTextId;}if(validationState==='success'&&hasSuccessText){return successTextId;}if(hasHelpText){return helpTextId;}return '';};var FocusRingWrapper=styled(BaseBox)(function(_ref1){var theme=_ref1.theme,currentInteraction=_ref1.currentInteraction,isTableInputCell=_ref1.isTableInputCell,shouldAddLimitedFocus=_ref1.shouldAddLimitedFocus;return {borderRadius:makeBorderSize(isTableInputCell?theme.border.radius.none:theme.border.radius.medium),width:'100%','&:focus-within':!isTableInputCell&&(shouldAddLimitedFocus?currentInteraction==='focus':true)?Object.assign({},getFocusRingStyles(),{transitionDuration:castWebType(makeMotionTime(getIn(theme.motion.duration,baseInputBorderBackgroundMotion[currentInteraction==='focus'?'enter':'exit'].duration))),transitionTimingFunction:castWebType(theme.motion.easing[baseInputBorderBackgroundMotion[currentInteraction==='focus'?'enter':'exit'].easing])}):{}};});var _BaseInput=function _BaseInput(_ref10,ref){var _inputGroupProps$isDi,_inputGroupProps$size;var _ref10$as=_ref10.as,as=_ref10$as===void 0?'input':_ref10$as,label=_ref10.label,_ref10$labelPosition=_ref10.labelPosition,labelPosition=_ref10$labelPosition===void 0?'top':_ref10$labelPosition,placeholder=_ref10.placeholder,_ref10$type=_ref10.type,type=_ref10$type===void 0?'text':_ref10$type,defaultValue=_ref10.defaultValue,tags=_ref10.tags,_ref10$showAllTags=_ref10.showAllTags,showAllTags=_ref10$showAllTags===void 0?false:_ref10$showAllTags,_ref10$activeTagIndex=_ref10.activeTagIndex,activeTagIndex=_ref10$activeTagIndex===void 0?-1:_ref10$activeTagIndex,setActiveTagIndex=_ref10.setActiveTagIndex,name=_ref10.name,value=_ref10.value,onFocus=_ref10.onFocus,onChange=_ref10.onChange,onInput=_ref10.onInput,onBlur=_ref10.onBlur,onSubmit=_ref10.onSubmit,onClick=_ref10.onClick,onKeyDown=_ref10.onKeyDown,isDisabled=_ref10.isDisabled,necessityIndicator=_ref10.necessityIndicator,validationState=_ref10.validationState,errorText=_ref10.errorText,helpText=_ref10.helpText,successText=_ref10.successText,isRequired=_ref10.isRequired,leadingIcon=_ref10.leadingIcon,prefix=_ref10.prefix,trailingInteractionElement=_ref10.trailingInteractionElement,onTrailingInteractionElementClick=_ref10.onTrailingInteractionElementClick,leadingInteractionElement=_ref10.leadingInteractionElement,suffix=_ref10.suffix,trailingIcon=_ref10.trailingIcon,maxCharacters=_ref10.maxCharacters,textAlign=_ref10.textAlign,autoFocus=_ref10.autoFocus,keyboardReturnKeyType=_ref10.keyboardReturnKeyType,keyboardType=_ref10.keyboardType,autoCompleteSuggestionType=_ref10.autoCompleteSuggestionType,trailingHeaderSlot=_ref10.trailingHeaderSlot,trailingFooterSlot=_ref10.trailingFooterSlot,numberOfLines=_ref10.numberOfLines,id=_ref10.id,componentName=_ref10.componentName,accessibilityLabel=_ref10.accessibilityLabel,labelId=_ref10.labelId,activeDescendant=_ref10.activeDescendant,hideLabelText=_ref10.hideLabelText,hideFormHint=_ref10.hideFormHint,hasPopup=_ref10.hasPopup,popupId=_ref10.popupId,isPopupExpanded=_ref10.isPopupExpanded,maxTagRows=_ref10.maxTagRows,shouldIgnoreBlurAnimation=_ref10.shouldIgnoreBlurAnimation,setShouldIgnoreBlurAnimation=_ref10.setShouldIgnoreBlurAnimation,autoCapitalize=_ref10.autoCapitalize,setInputWrapperRef=_ref10.setInputWrapperRef,testID=_ref10.testID,isDropdownTrigger=_ref10.isDropdownTrigger,isLabelInsideInput=_ref10.isLabelInsideInput,_ref10$size=_ref10.size,size=_ref10$size===void 0?'medium':_ref10$size,trailingButton=_ref10.trailingButton,_ref10$valueComponent=_ref10.valueComponentType,valueComponentType=_ref10$valueComponent===void 0?'text':_ref10$valueComponent,_ref10$isTableInputCe=_ref10.isTableInputCell,isTableInputCell=_ref10$isTableInputCe===void 0?false:_ref10$isTableInputCe,_ref10$showHintsAsToo=_ref10.showHintsAsTooltip,showHintsAsTooltip=_ref10$showHintsAsToo===void 0?false:_ref10$showHintsAsToo,_motionMeta=_ref10._motionMeta,role=_ref10.role,tabIndex=_ref10.tabIndex,leadingDropDown=_ref10.leadingDropDown,trailingDropDown=_ref10.trailingDropDown,labelSuffix=_ref10.labelSuffix,labelTrailing=_ref10.labelTrailing,valueSuffix=_ref10.valueSuffix,rest=_objectWithoutProperties(_ref10,_excluded);var _useTheme=useTheme(),theme=_useTheme.theme;var inputRef=React__default.useRef(null);var mergedInputRef=useMergeRefs(ref,inputRef);var inputWrapperRef=React__default.useRef(null);var _useTags=useTags(tags,activeTagIndex,setActiveTagIndex),onInputKeydownTagHandler=_useTags.onInputKeydownTagHandler,visibleTagsCountRef=_useTags.visibleTagsCountRef;var _React$useState3=React__default.useState(false),_React$useState4=_slicedToArray(_React$useState3,2),showAllTagsWithAnimation=_React$useState4[0],setShowAllTagsWithAnimation=_React$useState4[1];var isReactNative=getPlatformType()==='react-native';var defaultRole=hasPopup?'combobox':undefined;var inputGroupProps=useInputGroupContext();var isInsideInputGroup=inputGroupProps.isInsideInputGroup;var _isDisabled=(_inputGroupProps$isDi=inputGroupProps.isDisabled)!=null?_inputGroupProps$isDi:isDisabled;var _size=(_inputGroupProps$size=inputGroupProps.size)!=null?_inputGroupProps$size:size;React__default.useEffect(function(){if(showAllTags){setShowAllTagsWithAnimation(true);}else if(maxTagRows!=='expandable'){setShowAllTagsWithAnimation(false);}},[showAllTags,maxTagRows]);var _useInput=useInput({defaultValue:defaultValue,value:value,onFocus:onFocus,onClick:onClick,onChange:onChange,onBlur:onBlur,onSubmit:onSubmit,onInput:onInput,onKeyDown:onKeyDown,onInputKeydownTagHandler:onInputKeydownTagHandler}),handleOnFocus=_useInput.handleOnFocus,handleOnChange=_useInput.handleOnChange,handleOnClick=_useInput.handleOnClick,handleOnBlur=_useInput.handleOnBlur,handleOnSubmit=_useInput.handleOnSubmit,handleOnInput=_useInput.handleOnInput,handleOnKeyDown=_useInput.handleOnKeyDown,inputValue=_useInput.inputValue;var _useFormId=useFormId(id),inputId=_useFormId.inputId,helpTextId=_useFormId.helpTextId,errorTextId=_useFormId.errorTextId,successTextId=_useFormId.successTextId;var _useBreakpoint=useBreakpoint({breakpoints:theme.breakpoints}),matchedDeviceType=_useBreakpoint.matchedDeviceType;var isLabelLeftPositioned=labelPosition==='left'&&matchedDeviceType==='desktop';var _useInteraction=useInteraction(),currentInteraction=_useInteraction.currentInteraction,setCurrentInteraction=_useInteraction.setCurrentInteraction;var _isRequired=isRequired||necessityIndicator==='required';var accessibilityProps=makeAccessible({required:Boolean(_isRequired),disabled:Boolean(_isDisabled),invalid:Boolean(validationState==='error'),describedBy:getDescribedByElementId({validationState:validationState,hasErrorText:Boolean(errorText),hasSuccessText:Boolean(successText),hasHelpText:Boolean(helpText),errorTextId:errorTextId,successTextId:successTextId,helpTextId:helpTextId}),label:accessibilityLabel,hasPopup:hasPopup,expanded:hasPopup?isPopupExpanded:undefined,controls:hasPopup?popupId:undefined,role:role!=null?role:defaultRole,activeDescendant:activeDescendant});var willRenderHintText=Boolean(helpText)||validationState==='success'&&Boolean(successText)||validationState==='error'&&Boolean(errorText);if(__DEV__){if(autoCompleteSuggestionType&&!autoCompleteSuggestionTypeValues.includes(autoCompleteSuggestionType)){throwBladeError({message:`Expected autoCompleteSuggestionType to be one of ${autoCompleteSuggestionTypeValues.join(', ')} but received ${autoCompleteSuggestionType}`,moduleName:'Input'});}}var isTextArea=as==='textarea';var hasLeadingDropdown=Boolean(leadingDropDown);var hasTrailingDropdown=Boolean(trailingDropDown);var shouldAddLimitedFocus=hasLeadingDropdown||hasTrailingDropdown;return jsxs(BaseBox,Object.assign({ref:getOuterMotionRef({_motionMeta:_motionMeta,ref:ref})},metaAttribute({name:componentName,testID:testID}),getStyledProps(rest),{children:[jsxs(BaseBox,{display:"flex",flexDirection:isLabelLeftPositioned?'row':'column',justifyContent:isLabelLeftPositioned?'center':undefined,alignItems:isLabelLeftPositioned?'center':undefined,position:"relative",width:"100%",children:[!hideLabelText&&!isLabelInsideInput&&label&&!isInsideInputGroup&&jsxs(BaseBox,{display:"flex",flexDirection:isLabelLeftPositioned?'column':'row',justifyContent:"space-between",alignSelf:isTextArea&&isLabelLeftPositioned?'flex-start':undefined,marginY:isTextArea&&isLabelLeftPositioned?'spacing.3':'spacing.0',children:[jsx(FormLabel,{as:"label",necessityIndicator:necessityIndicator,position:labelPosition,id:labelId,htmlFor:inputId,size:_size,labelSuffix:labelSuffix,labelTrailing:labelTrailing,children:label}),trailingHeaderSlot==null?void 0:trailingHeaderSlot(value!=null?value:inputValue)]}),jsx(FocusRingWrapper,{currentInteraction:currentInteraction,isTableInputCell:isTableInputCell,className:"focus-ring-wrapper",shouldAddLimitedFocus:shouldAddLimitedFocus,children:jsxs(BaseInputWrapper,{isDropdownTrigger:isDropdownTrigger,isTextArea:isTextArea,isDisabled:_isDisabled,validationState:validationState,currentInteraction:currentInteraction,isLabelLeftPositioned:isLabelLeftPositioned,showAllTags:showAllTags,setShowAllTagsWithAnimation:setShowAllTagsWithAnimation,ref:function ref(refNode){if(refNode){setInputWrapperRef==null?void 0:setInputWrapperRef(refNode);inputWrapperRef.current=refNode;}},maxTagRows:maxTagRows,size:_size,numberOfLines:numberOfLines,onClick:function onClick(){if(!isReactNative){var _inputRef$current;(_inputRef$current=inputRef.current)==null?void 0:_inputRef$current.focus();}},isTableInputCell:isTableInputCell,children:[jsx(BaseInputVisuals,{size:_size,leadingIcon:leadingIcon,prefix:prefix,isDisabled:_isDisabled,leadingInteractionElement:leadingInteractionElement,leadingDropDown:leadingDropDown}),jsx(BaseInputTagSlot,{renderAs:as,tags:tags,isDisabled:_isDisabled,showAllTags:showAllTagsWithAnimation,setFocusOnInput:function setFocusOnInput(){var innerRef=getInnerMotionRef({_motionMeta:_motionMeta,ref:ref});if(innerRef&&!isReactNative&&'current'in innerRef){var _innerRef$current;(_innerRef$current=innerRef.current)==null?void 0:_innerRef$current.focus();}},labelPrefix:isLabelInsideInput?label:undefined,isDropdownTrigger:isDropdownTrigger,visibleTagsCountRef:visibleTagsCountRef,handleOnInputClick:function handleOnInputClick(e){handleOnClick({name:name,value:isReactNative?value:e});},setShouldIgnoreBlurAnimation:setShouldIgnoreBlurAnimation,maxTagRows:maxTagRows,inputWrapperRef:inputWrapperRef,size:_size,numberOfLines:numberOfLines,isTextArea:isTextArea,children:jsx(StyledBaseInput,Object.assign({as:as,id:inputId,ref:getInnerMotionRef({_motionMeta:_motionMeta,ref:mergedInputRef}),name:name,type:type,defaultValue:defaultValue,value:value,placeholder:placeholder,isDisabled:_isDisabled,validationState:validationState,isRequired:_isRequired,handleOnFocus:handleOnFocus,handleOnChange:handleOnChange,handleOnBlur:handleOnBlur,handleOnSubmit:handleOnSubmit,handleOnInput:handleOnInput,handleOnKeyDown:handleOnKeyDown,handleOnClick:handleOnClick,leadingIcon:leadingIcon,prefix:prefix,trailingInteractionElement:trailingInteractionElement,leadingInteractionElement:leadingInteractionElement,suffix:suffix,valueSuffix:valueSuffix,trailingIcon:trailingIcon,maxCharacters:maxCharacters,textAlign:textAlign,autoFocus:autoFocus,keyboardReturnKeyType:keyboardReturnKeyType,keyboardType:keyboardType,autoCompleteSuggestionType:autoCompleteSuggestionType,accessibilityProps:accessibilityProps,currentInteraction:currentInteraction,setCurrentInteraction:setCurrentInteraction,numberOfLines:numberOfLines,isTextArea:isTextArea||maxTagRows==='multiple'||maxTagRows==='expandable',hasPopup:hasPopup,hasTags:!!(tags&&tags.length>0),shouldIgnoreBlurAnimation:shouldIgnoreBlurAnimation,autoCapitalize:autoCapitalize,isDropdownTrigger:isDropdownTrigger,$size:_size,valueComponentType:valueComponentType,isTableInputCell:isTableInputCell,tabIndex:tabIndex,hasLeadingDropdown:Boolean(leadingDropDown)},metaAttribute({name:MetaConstants.StyledBaseInput}),makeAnalyticsAttribute(rest)))}),jsx(BaseInputVisuals,{trailingInteractionElement:trailingInteractionElement,onTrailingInteractionElementClick:onTrailingInteractionElementClick,suffix:suffix,trailingIcon:trailingIcon,isDisabled:_isDisabled,validationState:validationState,trailingButton:trailingButton,size:_size,errorText:errorText,successText:successText,showHintsAsTooltip:showHintsAsTooltip,trailingDropDown:trailingDropDown})]})})]}),hideFormHint||showHintsAsTooltip||isInsideInputGroup?null:jsx(BaseBox,{marginLeft:makeSize(isLabelLeftPositioned&&!hideLabelText?formHintLeftLabelMarginLeft[_size]:0),children:jsxs(BaseBox,{display:"flex",flexDirection:"row",justifyContent:willRenderHintText?'space-between':'flex-end',children:[jsx(FormHint,{type:getHintType({validationState:validationState,hasHelpText:Boolean(helpText)}),helpText:helpText,errorText:errorText,successText:successText,helpTextId:helpTextId,errorTextId:errorTextId,successTextId:successTextId,size:_size}),trailingFooterSlot==null?void 0:trailingFooterSlot(value!=null?value:inputValue)]})})]}));};var BaseInputWithRef=React__default.forwardRef(_BaseInput);var BaseInput=assignWithoutSideEffects(BaseInputWithRef,{displayName:'BaseInput'});
|
|
44
|
+
var _excluded=["as","label","labelPosition","placeholder","type","defaultValue","tags","showAllTags","activeTagIndex","setActiveTagIndex","name","value","onFocus","onChange","onInput","onBlur","onSubmit","onClick","onKeyDown","isDisabled","necessityIndicator","validationState","errorText","helpText","successText","isRequired","leadingIcon","prefix","trailingInteractionElement","onTrailingInteractionElementClick","leadingInteractionElement","suffix","trailingIcon","maxCharacters","textAlign","autoFocus","keyboardReturnKeyType","keyboardType","autoCompleteSuggestionType","trailingHeaderSlot","trailingFooterSlot","numberOfLines","id","componentName","accessibilityLabel","labelId","activeDescendant","hideLabelText","hideFormHint","hasPopup","popupId","isPopupExpanded","maxTagRows","shouldIgnoreBlurAnimation","setShouldIgnoreBlurAnimation","autoCapitalize","setInputWrapperRef","testID","isDropdownTrigger","isLabelInsideInput","size","trailingButton","valueComponentType","isTableInputCell","showHintsAsTooltip","_motionMeta","role","tabIndex","leadingDropDown","trailingDropDown","labelSuffix","labelTrailing","valueSuffix","children"];var autoCompleteSuggestionTypeValues=['none','on','name','email','username','password','newPassword','oneTimeCode','telephone','postalCode','countryName','creditCardNumber','creditCardCSC','creditCardExpiry','creditCardExpiryMonth','creditCardExpiryYear'];var useTags=function useTags(tags,activeTagIndex,setActiveTagIndex){var visibleTagsCountRef=React__default.useRef(0);React__default.useEffect(function(){if(tags&&activeTagIndex>=0&&activeTagIndex<tags.length){var _tags$activeTagIndex,_tags$activeTagIndex$;var tagTitle=(_tags$activeTagIndex=tags[activeTagIndex])==null?void 0:(_tags$activeTagIndex$=_tags$activeTagIndex.props)==null?void 0:_tags$activeTagIndex$.children;if(tagTitle){announce(`Close ${tagTitle} Tag`);}}},[activeTagIndex,tags==null?void 0:tags.length]);var onTagLeft=function onTagLeft(){if(activeTagIndex<0){setActiveTagIndex==null?void 0:setActiveTagIndex(visibleTagsCountRef.current-1);}if(activeTagIndex>0){setActiveTagIndex==null?void 0:setActiveTagIndex(activeTagIndex-1);}};var onTagRight=function onTagRight(){if(activeTagIndex<visibleTagsCountRef.current-1){setActiveTagIndex==null?void 0:setActiveTagIndex(activeTagIndex+1);}};var onTagRemove=function onTagRemove(){if(activeTagIndex>=0&&activeTagIndex<visibleTagsCountRef.current&&tags){tags[activeTagIndex].props.onDismiss({tagIndex:activeTagIndex});}};var onInputKeydownTagHandler=function onInputKeydownTagHandler(key){if(tags&&tags.length>0){if(key==='ArrowRight'){onTagRight();}if(key==='ArrowLeft'){onTagLeft();}if(key==='Backspace'){onTagRemove();}}};return {onInputKeydownTagHandler:onInputKeydownTagHandler,visibleTagsCountRef:visibleTagsCountRef};};var useInput=function useInput(_ref){var value=_ref.value,defaultValue=_ref.defaultValue,onClick=_ref.onClick,onFocus=_ref.onFocus,onChange=_ref.onChange,onBlur=_ref.onBlur,onSubmit=_ref.onSubmit,onInput=_ref.onInput,onKeyDown=_ref.onKeyDown,onInputKeydownTagHandler=_ref.onInputKeydownTagHandler;if(__DEV__){if(value&&defaultValue){throwBladeError({message:`Either 'value' or 'defaultValue' shall be passed. This decides if the input field is controlled or uncontrolled`,moduleName:'Input'});}}var _React$useState=React__default.useState(defaultValue!=null?defaultValue:value),_React$useState2=_slicedToArray(_React$useState,2),inputValue=_React$useState2[0],setInputValue=_React$useState2[1];var handleOnFocus=React__default.useCallback(function(_ref2){var name=_ref2.name,value=_ref2.value;var _value='';if(getPlatformType()==='react-native'&&typeof value==='string'){_value=value;}else if(typeof value!=='string'){var _value$target$value;_value=(_value$target$value=value==null?void 0:value.target.value)!=null?_value$target$value:'';}onFocus==null?void 0:onFocus({name:name,value:_value});},[onFocus]);var handleOnClick=React__default.useCallback(function(_ref3){var name=_ref3.name,value=_ref3.value;var _value='';if(getPlatformType()==='react-native'&&typeof value==='string'){_value=value;}else if(typeof value!=='string'){var _value$currentTarget$;_value=(_value$currentTarget$=value==null?void 0:value.currentTarget.value)!=null?_value$currentTarget$:'';}onClick==null?void 0:onClick({name:name,value:_value});},[onClick]);var handleOnSubmit=React__default.useCallback(function(_ref4){var name=_ref4.name,value=_ref4.value;var _value='';if(getPlatformType()==='react-native'&&typeof value==='string'){_value=value;}else if(typeof value!=='string'){var _value$target$value2;_value=(_value$target$value2=value==null?void 0:value.target.value)!=null?_value$target$value2:'';}if(isReactNative()){onSubmit==null?void 0:onSubmit({name:name,value:_value});}},[onSubmit]);var handleOnBlur=React__default.useCallback(function(_ref5){var name=_ref5.name,value=_ref5.value;var _value='';if(getPlatformType()==='react-native'&&typeof value=='string'){_value=value;}else if(typeof value!=='string'){var _value$target$value3;_value=(_value$target$value3=value==null?void 0:value.target.value)!=null?_value$target$value3:'';}onBlur==null?void 0:onBlur({name:name,value:_value});},[onBlur]);var handleOnChange=React__default.useCallback(function(_ref6){var name=_ref6.name,value=_ref6.value;var _value='';if(getPlatformType()==='react-native'&&typeof value==='string'){_value=value;}else if(typeof value!=='string'){var _value$target$value4;_value=(_value$target$value4=value==null?void 0:value.target.value)!=null?_value$target$value4:'';}onChange==null?void 0:onChange({name:name,value:_value});setInputValue(_value);},[onChange]);var handleOnInput=React__default.useCallback(function(_ref7){var name=_ref7.name,value=_ref7.value;var _value='';if(getPlatformType()==='react-native'&&typeof value=='string'){_value=value;}else if(typeof value!=='string'){var _value$target$value5;_value=(_value$target$value5=value==null?void 0:value.target.value)!=null?_value$target$value5:'';}onInput==null?void 0:onInput({name:name,value:_value});},[onInput]);var handleOnKeyDown=React__default.useCallback(function(_ref8){var name=_ref8.name,key=_ref8.key,code=_ref8.code,event=_ref8.event;onInputKeydownTagHandler(key);onKeyDown==null?void 0:onKeyDown({name:name,key:key,code:code,event:event});},[onKeyDown]);return {handleOnFocus:handleOnFocus,handleOnClick:handleOnClick,handleOnChange:handleOnChange,handleOnBlur:handleOnBlur,handleOnSubmit:handleOnSubmit,handleOnInput:handleOnInput,handleOnKeyDown:handleOnKeyDown,inputValue:inputValue};};var getHintType=function getHintType(_ref9){var validationState=_ref9.validationState,hasHelpText=_ref9.hasHelpText;if(validationState==='error'){return 'error';}if(validationState==='success'){return 'success';}if(hasHelpText){return 'help';}return 'help';};var getDescribedByElementId=function getDescribedByElementId(_ref0){var validationState=_ref0.validationState,hasErrorText=_ref0.hasErrorText,hasSuccessText=_ref0.hasSuccessText,hasHelpText=_ref0.hasHelpText,errorTextId=_ref0.errorTextId,successTextId=_ref0.successTextId,helpTextId=_ref0.helpTextId;if(validationState==='error'&&hasErrorText){return errorTextId;}if(validationState==='success'&&hasSuccessText){return successTextId;}if(hasHelpText){return helpTextId;}return '';};var FocusRingWrapper=styled(BaseBox)(function(_ref1){var theme=_ref1.theme,currentInteraction=_ref1.currentInteraction,isTableInputCell=_ref1.isTableInputCell,shouldAddLimitedFocus=_ref1.shouldAddLimitedFocus;return {borderRadius:makeBorderSize(isTableInputCell?theme.border.radius.none:theme.border.radius.medium),width:'100%','&:focus-within':!isTableInputCell&&(shouldAddLimitedFocus?currentInteraction==='focus':true)?Object.assign({},getFocusRingStyles(),{transitionDuration:castWebType(makeMotionTime(getIn(theme.motion.duration,baseInputBorderBackgroundMotion[currentInteraction==='focus'?'enter':'exit'].duration))),transitionTimingFunction:castWebType(theme.motion.easing[baseInputBorderBackgroundMotion[currentInteraction==='focus'?'enter':'exit'].easing])}):{}};});var _BaseInput=function _BaseInput(_ref10,ref){var _inputGroupProps$isDi,_inputGroupProps$size;var _ref10$as=_ref10.as,as=_ref10$as===void 0?'input':_ref10$as,label=_ref10.label,_ref10$labelPosition=_ref10.labelPosition,labelPosition=_ref10$labelPosition===void 0?'top':_ref10$labelPosition,placeholder=_ref10.placeholder,_ref10$type=_ref10.type,type=_ref10$type===void 0?'text':_ref10$type,defaultValue=_ref10.defaultValue,tags=_ref10.tags,_ref10$showAllTags=_ref10.showAllTags,showAllTags=_ref10$showAllTags===void 0?false:_ref10$showAllTags,_ref10$activeTagIndex=_ref10.activeTagIndex,activeTagIndex=_ref10$activeTagIndex===void 0?-1:_ref10$activeTagIndex,setActiveTagIndex=_ref10.setActiveTagIndex,name=_ref10.name,value=_ref10.value,onFocus=_ref10.onFocus,onChange=_ref10.onChange,onInput=_ref10.onInput,onBlur=_ref10.onBlur,onSubmit=_ref10.onSubmit,onClick=_ref10.onClick,onKeyDown=_ref10.onKeyDown,isDisabled=_ref10.isDisabled,necessityIndicator=_ref10.necessityIndicator,validationState=_ref10.validationState,errorText=_ref10.errorText,helpText=_ref10.helpText,successText=_ref10.successText,isRequired=_ref10.isRequired,leadingIcon=_ref10.leadingIcon,prefix=_ref10.prefix,trailingInteractionElement=_ref10.trailingInteractionElement,onTrailingInteractionElementClick=_ref10.onTrailingInteractionElementClick,leadingInteractionElement=_ref10.leadingInteractionElement,suffix=_ref10.suffix,trailingIcon=_ref10.trailingIcon,maxCharacters=_ref10.maxCharacters,textAlign=_ref10.textAlign,autoFocus=_ref10.autoFocus,keyboardReturnKeyType=_ref10.keyboardReturnKeyType,keyboardType=_ref10.keyboardType,autoCompleteSuggestionType=_ref10.autoCompleteSuggestionType,trailingHeaderSlot=_ref10.trailingHeaderSlot,trailingFooterSlot=_ref10.trailingFooterSlot,numberOfLines=_ref10.numberOfLines,id=_ref10.id,componentName=_ref10.componentName,accessibilityLabel=_ref10.accessibilityLabel,labelId=_ref10.labelId,activeDescendant=_ref10.activeDescendant,hideLabelText=_ref10.hideLabelText,hideFormHint=_ref10.hideFormHint,hasPopup=_ref10.hasPopup,popupId=_ref10.popupId,isPopupExpanded=_ref10.isPopupExpanded,maxTagRows=_ref10.maxTagRows,shouldIgnoreBlurAnimation=_ref10.shouldIgnoreBlurAnimation,setShouldIgnoreBlurAnimation=_ref10.setShouldIgnoreBlurAnimation,autoCapitalize=_ref10.autoCapitalize,setInputWrapperRef=_ref10.setInputWrapperRef,testID=_ref10.testID,isDropdownTrigger=_ref10.isDropdownTrigger,isLabelInsideInput=_ref10.isLabelInsideInput,_ref10$size=_ref10.size,size=_ref10$size===void 0?'medium':_ref10$size,trailingButton=_ref10.trailingButton,_ref10$valueComponent=_ref10.valueComponentType,valueComponentType=_ref10$valueComponent===void 0?'text':_ref10$valueComponent,_ref10$isTableInputCe=_ref10.isTableInputCell,isTableInputCell=_ref10$isTableInputCe===void 0?false:_ref10$isTableInputCe,_ref10$showHintsAsToo=_ref10.showHintsAsTooltip,showHintsAsTooltip=_ref10$showHintsAsToo===void 0?false:_ref10$showHintsAsToo,_motionMeta=_ref10._motionMeta,role=_ref10.role,tabIndex=_ref10.tabIndex,leadingDropDown=_ref10.leadingDropDown,trailingDropDown=_ref10.trailingDropDown,labelSuffix=_ref10.labelSuffix,labelTrailing=_ref10.labelTrailing,valueSuffix=_ref10.valueSuffix,children=_ref10.children,rest=_objectWithoutProperties(_ref10,_excluded);var _useTheme=useTheme(),theme=_useTheme.theme;var inputRef=React__default.useRef(null);var mergedInputRef=useMergeRefs(ref,inputRef);var inputWrapperRef=React__default.useRef(null);var _useTags=useTags(tags,activeTagIndex,setActiveTagIndex),onInputKeydownTagHandler=_useTags.onInputKeydownTagHandler,visibleTagsCountRef=_useTags.visibleTagsCountRef;var _React$useState3=React__default.useState(false),_React$useState4=_slicedToArray(_React$useState3,2),showAllTagsWithAnimation=_React$useState4[0],setShowAllTagsWithAnimation=_React$useState4[1];var isReactNative=getPlatformType()==='react-native';var defaultRole=hasPopup?'combobox':undefined;var inputGroupProps=useInputGroupContext();var isInsideInputGroup=inputGroupProps.isInsideInputGroup;var _isDisabled=(_inputGroupProps$isDi=inputGroupProps.isDisabled)!=null?_inputGroupProps$isDi:isDisabled;var _size=(_inputGroupProps$size=inputGroupProps.size)!=null?_inputGroupProps$size:size;React__default.useEffect(function(){if(showAllTags){setShowAllTagsWithAnimation(true);}else if(maxTagRows!=='expandable'){setShowAllTagsWithAnimation(false);}},[showAllTags,maxTagRows]);var _useInput=useInput({defaultValue:defaultValue,value:value,onFocus:onFocus,onClick:onClick,onChange:onChange,onBlur:onBlur,onSubmit:onSubmit,onInput:onInput,onKeyDown:onKeyDown,onInputKeydownTagHandler:onInputKeydownTagHandler}),handleOnFocus=_useInput.handleOnFocus,handleOnChange=_useInput.handleOnChange,handleOnClick=_useInput.handleOnClick,handleOnBlur=_useInput.handleOnBlur,handleOnSubmit=_useInput.handleOnSubmit,handleOnInput=_useInput.handleOnInput,handleOnKeyDown=_useInput.handleOnKeyDown,inputValue=_useInput.inputValue;var _useFormId=useFormId(id),inputId=_useFormId.inputId,helpTextId=_useFormId.helpTextId,errorTextId=_useFormId.errorTextId,successTextId=_useFormId.successTextId;var _useBreakpoint=useBreakpoint({breakpoints:theme.breakpoints}),matchedDeviceType=_useBreakpoint.matchedDeviceType;var isLabelLeftPositioned=labelPosition==='left'&&matchedDeviceType==='desktop';var _useInteraction=useInteraction(),currentInteraction=_useInteraction.currentInteraction,setCurrentInteraction=_useInteraction.setCurrentInteraction;var _isRequired=isRequired||necessityIndicator==='required';var accessibilityProps=makeAccessible({required:Boolean(_isRequired),disabled:Boolean(_isDisabled),invalid:Boolean(validationState==='error'),describedBy:getDescribedByElementId({validationState:validationState,hasErrorText:Boolean(errorText),hasSuccessText:Boolean(successText),hasHelpText:Boolean(helpText),errorTextId:errorTextId,successTextId:successTextId,helpTextId:helpTextId}),label:accessibilityLabel,hasPopup:hasPopup,expanded:hasPopup?isPopupExpanded:undefined,controls:hasPopup?popupId:undefined,role:role!=null?role:defaultRole,activeDescendant:activeDescendant});var willRenderHintText=Boolean(helpText)||validationState==='success'&&Boolean(successText)||validationState==='error'&&Boolean(errorText);if(__DEV__){if(autoCompleteSuggestionType&&!autoCompleteSuggestionTypeValues.includes(autoCompleteSuggestionType)){throwBladeError({message:`Expected autoCompleteSuggestionType to be one of ${autoCompleteSuggestionTypeValues.join(', ')} but received ${autoCompleteSuggestionType}`,moduleName:'Input'});}}var isTextArea=as==='textarea';var hasLeadingDropdown=Boolean(leadingDropDown);var hasTrailingDropdown=Boolean(trailingDropDown);var shouldAddLimitedFocus=hasLeadingDropdown||hasTrailingDropdown;return jsxs(BaseBox,Object.assign({ref:getOuterMotionRef({_motionMeta:_motionMeta,ref:ref})},metaAttribute({name:componentName,testID:testID}),getStyledProps(rest),{children:[jsxs(BaseBox,{display:"flex",flexDirection:isLabelLeftPositioned?'row':'column',justifyContent:isLabelLeftPositioned?'center':undefined,alignItems:isLabelLeftPositioned?'center':undefined,position:"relative",width:"100%",children:[!hideLabelText&&!isLabelInsideInput&&label&&!isInsideInputGroup&&jsxs(BaseBox,{display:"flex",flexDirection:isLabelLeftPositioned?'column':'row',justifyContent:"space-between",alignSelf:isTextArea&&isLabelLeftPositioned?'flex-start':undefined,marginY:isTextArea&&isLabelLeftPositioned?'spacing.3':'spacing.0',children:[jsx(FormLabel,{as:"label",necessityIndicator:necessityIndicator,position:labelPosition,id:labelId,htmlFor:inputId,size:_size,labelSuffix:labelSuffix,labelTrailing:labelTrailing,children:label}),trailingHeaderSlot==null?void 0:trailingHeaderSlot(value!=null?value:inputValue)]}),jsx(FocusRingWrapper,{currentInteraction:currentInteraction,isTableInputCell:isTableInputCell,className:"focus-ring-wrapper",shouldAddLimitedFocus:shouldAddLimitedFocus,children:jsxs(BaseInputWrapper,{isDropdownTrigger:isDropdownTrigger,isTextArea:isTextArea,isDisabled:_isDisabled,validationState:validationState,currentInteraction:currentInteraction,isLabelLeftPositioned:isLabelLeftPositioned,showAllTags:showAllTags,setShowAllTagsWithAnimation:setShowAllTagsWithAnimation,ref:function ref(refNode){if(refNode){setInputWrapperRef==null?void 0:setInputWrapperRef(refNode);inputWrapperRef.current=refNode;}},maxTagRows:maxTagRows,size:_size,numberOfLines:numberOfLines,onClick:function onClick(){if(!isReactNative){var _inputRef$current;(_inputRef$current=inputRef.current)==null?void 0:_inputRef$current.focus();}},isTableInputCell:isTableInputCell,children:[jsx(BaseInputVisuals,{size:_size,leadingIcon:leadingIcon,prefix:prefix,isDisabled:_isDisabled,leadingInteractionElement:leadingInteractionElement,leadingDropDown:leadingDropDown}),jsx(BaseInputTagSlot,{renderAs:as,tags:tags,isDisabled:_isDisabled,showAllTags:showAllTagsWithAnimation,setFocusOnInput:function setFocusOnInput(){var innerRef=getInnerMotionRef({_motionMeta:_motionMeta,ref:ref});if(innerRef&&!isReactNative&&'current'in innerRef){var _innerRef$current;(_innerRef$current=innerRef.current)==null?void 0:_innerRef$current.focus();}},labelPrefix:isLabelInsideInput?label:undefined,isDropdownTrigger:isDropdownTrigger,visibleTagsCountRef:visibleTagsCountRef,handleOnInputClick:function handleOnInputClick(e){handleOnClick({name:name,value:isReactNative?value:e});},setShouldIgnoreBlurAnimation:setShouldIgnoreBlurAnimation,maxTagRows:maxTagRows,inputWrapperRef:inputWrapperRef,size:_size,numberOfLines:numberOfLines,isTextArea:isTextArea,children:jsx(StyledBaseInput,Object.assign({as:as,id:inputId,ref:getInnerMotionRef({_motionMeta:_motionMeta,ref:mergedInputRef}),name:name,type:type,defaultValue:defaultValue,value:value,placeholder:placeholder,isDisabled:_isDisabled,validationState:validationState,isRequired:_isRequired,handleOnFocus:handleOnFocus,handleOnChange:handleOnChange,handleOnBlur:handleOnBlur,handleOnSubmit:handleOnSubmit,handleOnInput:handleOnInput,handleOnKeyDown:handleOnKeyDown,handleOnClick:handleOnClick,leadingIcon:leadingIcon,prefix:prefix,trailingInteractionElement:trailingInteractionElement,leadingInteractionElement:leadingInteractionElement,suffix:suffix,valueSuffix:valueSuffix,trailingIcon:trailingIcon,maxCharacters:maxCharacters,textAlign:textAlign,autoFocus:autoFocus,keyboardReturnKeyType:keyboardReturnKeyType,keyboardType:keyboardType,autoCompleteSuggestionType:autoCompleteSuggestionType,accessibilityProps:accessibilityProps,currentInteraction:currentInteraction,setCurrentInteraction:setCurrentInteraction,numberOfLines:numberOfLines,isTextArea:isTextArea||maxTagRows==='multiple'||maxTagRows==='expandable',hasPopup:hasPopup,hasTags:!!(tags&&tags.length>0),shouldIgnoreBlurAnimation:shouldIgnoreBlurAnimation,autoCapitalize:autoCapitalize,isDropdownTrigger:isDropdownTrigger,$size:_size,valueComponentType:valueComponentType,isTableInputCell:isTableInputCell,tabIndex:tabIndex,hasLeadingDropdown:Boolean(leadingDropDown),children:children},metaAttribute({name:MetaConstants.StyledBaseInput}),makeAnalyticsAttribute(rest)))}),jsx(BaseInputVisuals,{trailingInteractionElement:trailingInteractionElement,onTrailingInteractionElementClick:onTrailingInteractionElementClick,suffix:suffix,trailingIcon:trailingIcon,isDisabled:_isDisabled,validationState:validationState,trailingButton:trailingButton,size:_size,errorText:errorText,successText:successText,showHintsAsTooltip:showHintsAsTooltip,trailingDropDown:trailingDropDown})]})})]}),hideFormHint||showHintsAsTooltip||isInsideInputGroup?null:jsx(BaseBox,{marginLeft:makeSize(isLabelLeftPositioned&&!hideLabelText?formHintLeftLabelMarginLeft[_size]:0),children:jsxs(BaseBox,{display:"flex",flexDirection:"row",justifyContent:willRenderHintText?'space-between':'flex-end',children:[jsx(FormHint,{type:getHintType({validationState:validationState,hasHelpText:Boolean(helpText)}),helpText:helpText,errorText:errorText,successText:successText,helpTextId:helpTextId,errorTextId:errorTextId,successTextId:successTextId,size:_size}),trailingFooterSlot==null?void 0:trailingFooterSlot(value!=null?value:inputValue)]})})]}));};var BaseInputWithRef=React__default.forwardRef(_BaseInput);var BaseInput=assignWithoutSideEffects(BaseInputWithRef,{displayName:'BaseInput'});
|
|
45
45
|
|
|
46
46
|
export { BaseInput, getHintType };
|
|
47
47
|
//# sourceMappingURL=BaseInput.js.map
|