@contentful/f36-autocomplete 4.48.0 → 4.48.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/index.js CHANGED
@@ -14,4 +14,5 @@ import p from '@contentful/f36-tokens';
14
14
  var Pe=Object.defineProperty,Me=Object.defineProperties;var Se=Object.getOwnPropertyDescriptors;var M=Object.getOwnPropertySymbols;var q=Object.prototype.hasOwnProperty,z=Object.prototype.propertyIsEnumerable;var W=(e,o,i)=>o in e?Pe(e,o,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[o]=i,d=(e,o)=>{for(var i in o||(o={}))q.call(o,i)&&W(e,i,o[i]);if(M)for(var i of M(o))z.call(o,i)&&W(e,i,o[i]);return e},g=(e,o)=>Me(e,Se(o));var j=(e,o)=>{var i={};for(var r in e)q.call(e,r)&&o.indexOf(r)<0&&(i[r]=e[r]);if(e!=null&&M)for(var r of M(e))o.indexOf(r)<0&&z.call(e,r)&&(i[r]=e[r]);return i};var S=e=>({autocomplete:css({position:"relative",width:"100%"}),combobox:css({position:"relative"}),inputField:css({paddingRight:p.spacingXl,textOverflow:"ellipsis",whiteSpace:"nowrap"}),toggleButton:css({position:"absolute",top:"1px",right:"1px",zIndex:1,padding:p.spacing2Xs,height:"38px"}),content:css({overflow:"auto",maxHeight:`${e}px`}),list:css({listStyle:"none",padding:`${p.spacingXs} 0`,margin:0}),groupTitle:css({padding:`${p.spacingXs} ${p.spacingM}`,lineHeight:p.lineHeightM}),noMatchesTitle:css({color:p.gray500,margin:`${p.spacingM} 0 ${p.spacingM} 0`}),item:css({display:"block",padding:`${p.spacingXs} ${p.spacingM}`,wordBreak:"break-word",whiteSpace:"break-spaces",cursor:"pointer",hyphens:"auto","&:focus, &:hover":{backgroundColor:p.gray100},"&:active":{backgroundColor:p.gray200}}),disabled:css({opacity:.5,pointerEvents:"none"}),highlighted:css({backgroundColor:p.gray100}),hidden:css({display:"none"})});var C=e=>{let{items:o,elementStartIndex:i,highlightedIndex:r,getItemProps:I,renderItem:T,inputValue:b,listMaxHeight:H=180}=e,s=S(H);return n.createElement("ul",{className:s.list,"data-test-id":"cf-autocomplete-list"},o.map((u,E)=>{let c=i+E,L=I({item:u,index:c});return n.createElement(Text,g(d({},L),{as:"li",key:c,className:cx([s.item,r===c&&s.highlighted]),"data-test-id":`cf-autocomplete-list-item-${c}`}),T?T(u,b):typeof u=="string"?n.createElement(K,{item:u,inputValue:b}):u)}))};C.displayName="AutocompleteItems";function K({item:e,inputValue:o}){let{before:i,match:r,after:I}=getStringMatch(e,o);return n.createElement(n.Fragment,null,i,n.createElement("b",null,r),I)}K.displayName="HighlightedItem";function Re(e,o){let {id:i,className:r,clearAfterSelect:I=!1,closeAfterSelect:T=!0,defaultValue:b="",selectedItem:H,items:s,onInputValueChange:u,onSelectItem:E,onFocus:c,onBlur:L,renderItem:O,icon:Y=n.createElement(ChevronDownIcon,{variant:"muted"}),itemToString:Z=t=>t,isInvalid:ee,isDisabled:_,isRequired:te,isReadOnly:oe,showEmptyList:ne,noMatchesMessage:ie="No matches found",placeholder:se="Search",inputRef:re,toggleRef:pe,listRef:le,listWidth:ae="auto",listMaxHeight:me=180,isGrouped:x=!1,isLoading:v=!1,usePortal:ue=!1,testId:ce="cf-autocomplete"}=e,m=S(me),[h,de]=useState(b),y=useCallback(t=>{de(t),u==null||u(t);},[u]),ge=useCallback(t=>{let l=t.target.value;y(l);},[y]),he=A(x)?s.reduce((t,l)=>[...t,...l.options],[]):s,fe=A(x)?s.every(t=>t.options.length===0):s.length===0,{getComboboxProps:Ie,getInputProps:ye,getItemProps:$,getMenuProps:Te,getToggleButtonProps:be,highlightedIndex:D,isOpen:F,toggleMenu:k}=useCombobox({items:he,selectedItem:H,inputValue:h,itemToString:Z,onInputValueChange:({type:t,inputValue:l})=>{t!=="__input_change__"&&y(l);},onStateChange:({type:t,selectedItem:l})=>{switch(t){case useCombobox.stateChangeTypes.InputKeyDownEnter:case useCombobox.stateChangeTypes.ItemClick:l&&E(l),I&&y(""),T||k();break;}}}),U=ye(),w=j(U,["aria-labelledby","id"]),xe=Ie(),X=be(),P=Te(),N=0;return n.createElement("div",{"data-test-id":ce,className:cx(m.autocomplete,r),ref:o},n.createElement(Popover,{usePortal:ue,isOpen:F,isFullWidth:ae==="full",renderOnlyWhenOpen:!1,autoFocus:!1,id:P.id},n.createElement(Popover.Trigger,null,n.createElement("div",g(d({},xe),{className:m.combobox}),n.createElement(TextInput,g(d({className:m.inputField},w),{onFocus:t=>{c==null||c(t),F||k();},onBlur:L,id:i,isInvalid:ee,isDisabled:_,isRequired:te,isReadOnly:oe,ref:mergeRefs(w.ref,re),testId:"cf-autocomplete-input",placeholder:se,onChange:t=>{w.onChange(t),ge(t);}})),n.createElement(IconButton,g(d({},X),{ref:mergeRefs(X.ref,pe),"aria-label":h?"Clear":"Show list",className:m.toggleButton,variant:"transparent",icon:h?n.createElement(CloseIcon,{variant:"muted"}):Y,onClick:()=>{h?y(""):k();},isDisabled:_,size:"small"})))),s.length>0||h.length>0||ne?n.createElement(Popover.Content,g(d({},P),{ref:mergeRefs(P.ref,le),className:m.content,testId:"cf-autocomplete-container"}),v&&[...Array(3)].map((t,l)=>n.createElement("div",{key:l,className:cx(m.item,m.disabled)},n.createElement(Be,null))),!v&&fe&&n.createElement("div",{className:m.item},n.createElement(Subheading,{className:m.noMatchesTitle},ie)),!v&&A(x)&&s.map((t,l)=>{if(t.options.length<1)return;let ve=n.createElement("div",{key:l},n.createElement(SectionHeading,{key:l,"data-test-id":"cf-autocomplete-grouptitle",marginBottom:"none",className:m.groupTitle},t.groupTitle),n.createElement(C,{items:t.options,highlightedIndex:D,getItemProps:$,renderItem:O,inputValue:h,elementStartIndex:N}));return N+=t.options.length,ve}),!v&&!A(x)&&s.length>0&&n.createElement(C,{items:s,elementStartIndex:N,highlightedIndex:D,getItemProps:$,renderItem:O,inputValue:h})):n.createElement("div",g(d({},P),{className:cx(m.hidden)}))))}var Be=()=>n.createElement(Skeleton.Container,{svgHeight:16},n.createElement(Skeleton.BodyText,{numberOfLines:1}));function A(e,o){return e}var Oe=n.forwardRef(Re);
15
15
 
16
16
  export { Oe as Autocomplete };
17
+ //# sourceMappingURL=out.js.map
17
18
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/Autocomplete.tsx","../../src/AutocompleteItems.tsx","../../src/Autocomplete.styles.ts"],"names":["React","useCallback","useState","cx","useCombobox","mergeRefs","IconButton","TextInput","CloseIcon","ChevronDownIcon","Skeleton","Popover","Subheading","SectionHeading","getStringMatch","Text","css","tokens","getAutocompleteStyles","listMaxHeight","AutocompleteItems","props","items","elementStartIndex","highlightedIndex","getItemProps","renderItem","inputValue","styles","item","index","itemIndex","itemProps","__spreadProps","__spreadValues","HighlightedItem","before","match","after","_Autocomplete","ref","id","className","clearAfterSelect","closeAfterSelect","defaultValue","selectedItem","onInputValueChange","onSelectItem","onFocus","onBlur","icon","itemToString","isInvalid","isDisabled","isRequired","isReadOnly","showEmptyList","noMatchesMessage","placeholder","inputRef","toggleRef","listRef","listWidth","isGrouped","isLoading","usePortal","testId","setInputValue","handleInputValueChange","value","handleNativeChangeEvent","event","flattenItems","isUsingGroups","acc","group","isShowingNoMatches","getComboboxProps","getInputProps","getMenuProps","getToggleButtonProps","isOpen","toggleMenu","type","_a","_labelledby","_inputId","inputProps","__objRest","comboboxProps","toggleProps","menuProps","e","_","ListItemLoadingState","render","Autocomplete"],"mappings":"qlBAAA,OAAOA,GAAS,eAAAC,EAAa,YAAAC,OAAgB,QAC7C,OAAS,MAAAC,MAAU,UACnB,OAAS,eAAAC,MAAmB,YAE5B,OACE,aAAAC,MAGK,uBACP,OAAS,cAAAC,OAAkB,yBAC3B,OAAS,aAAAC,OAAsC,wBAC/C,OAAS,aAAAC,GAAW,mBAAAC,OAAuB,wBAC3C,OAAS,YAAAC,MAAgB,2BACzB,OAAS,WAAAC,MAAe,0BACxB,OAAS,cAAAC,GAAY,kBAAAC,O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ACd,CAEN,EAIA3B,EAAA,cAAC,MAAAiC,EAAAC,EAAA,GAAQ0D,GAAR,CAAmB,UAAWzF,EAAGyB,EAAO,MAAM,GAAG,CAEtD,CACF,CAEJ,CAEA,IAAMmE,GAAuB,IAEzB/F,EAAA,cAACU,EAAS,UAAT,CAAmB,UAAW,IAC7BV,EAAA,cAACU,EAAS,SAAT,CAAkB,cAAe,EAAG,CACvC,EAKJ,SAASgE,EACPV,EACA1C,EACuC,CACvC,OAAO0C,CACT,CAOO,IAAMiC,GAAejG,EAAM,WAAWuC,EAAa","sourcesContent":["import React, { useCallback, useState } from 'react';\nimport { cx } from 'emotion';\nimport { useCombobox } from 'downshift';\n\nimport {\n mergeRefs,\n type CommonProps,\n type ExpandProps,\n} from '@contentful/f36-core';\nimport { IconButton } from '@contentful/f36-button';\nimport { TextInput, type TextInputProps } from '@contentful/f36-forms';\nimport { CloseIcon, ChevronDownIcon } from '@contentful/f36-icons';\nimport { Skeleton } from '@contentful/f36-skeleton';\nimport { Popover } from '@contentful/f36-popover';\nimport { Subheading, SectionHeading } from '@contentful/f36-typography';\n\nimport { AutocompleteItems } from './AutocompleteItems';\nimport { getAutocompleteStyles } from './Autocomplete.styles';\n\nexport interface GenericGroupType<ItemType> {\n groupTitle: string;\n options: ItemType[];\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface AutocompleteProps<ItemType>\n extends CommonProps,\n Pick<\n TextInputProps,\n | 'isDisabled'\n | 'isInvalid'\n | 'isReadOnly'\n | 'isRequired'\n | 'id'\n | 'defaultValue'\n > {\n /**\n * It’s an array of data to be used as \"options\" by the autocomplete component.\n * This can either be a plain list of items or a list of groups of items.\n */\n items: ItemType[] | GenericGroupType<ItemType>[];\n\n /**\n * Set a custom icon for the text input\n */\n icon?: React.ReactElement;\n\n /**\n * Tells if the item is a object with groups\n */\n isGrouped?: boolean;\n\n /**\n * Function called whenever the input value changes\n */\n onInputValueChange?: (value: string) => void;\n /**\n * This is the function that will be called when the user selects one of the \"options\" in the list.\n * The component will pass the selected \"item\" as an argument to the function..\n */\n onSelectItem: (item: ItemType) => void;\n\n /**\n * Applying the selectedItem property turns autocomplete into a controlled component.\n * Can be used to display e.g. previously selected element. If it is an object the itemToString function will apply to it.\n */\n selectedItem?: ItemType;\n\n /**\n * This is the function that will be called for each \"item\" passed in the `items` prop.\n * It receives the \"item\" and \"inputValue\" as arguments and returns a ReactNode.\n * The inputValue is passed in case you want to highlight the match on the render.\n */\n renderItem?: (item: ItemType, inputValue: string) => React.ReactNode;\n /**\n * When using objects as `items`, we recommend passing a function that tells Downshift how to extract a string\n * from those objetcs to be used as inputValue\n */\n itemToString?: (item: ItemType) => string;\n /**\n * If this is set to `true` the text input will be cleared after an item is selected\n * @default false\n */\n clearAfterSelect?: boolean;\n /**\n * If this is set to `false` the dropdown menu will stay open after selecting an item\n * @default true\n */\n closeAfterSelect?: boolean;\n /**\n * This is the value will be passed to the `placeholder` prop of the input.\n * @default \"Search\"\n */\n placeholder?: string;\n /**\n * Defines if the list should be shown even if empty, when input is focused\n * @default false\n */\n showEmptyList?: boolean;\n /**\n * A message that will be shown when it is not possible to find any option that matches the input value\n * @default \"No matches\"\n */\n noMatchesMessage?: string;\n /**\n * Use this prop to get a ref to the input element of the component\n */\n inputRef?: React.Ref<HTMLInputElement>;\n /**\n * Use this prop to get a ref to the toggle button of the component\n */\n toggleRef?: React.Ref<HTMLButtonElement>;\n /**\n * Use this prop to get a ref to the list of items of the component\n */\n listRef?: React.Ref<HTMLUListElement>;\n /**\n * It sets the width of the list\n * @default \"auto\"\n */\n listWidth?: 'auto' | 'full';\n /**\n * It sets the max-height, in pixels, of the list\n * The default value is the height of 5 single line items\n * @default 180\n */\n listMaxHeight?: number;\n /**\n * Sets the list to show its loading state\n * @default false\n */\n isLoading?: boolean;\n /**\n * Boolean to control whether or not to render the suggestions box in a React Portal.\n * Rendering content inside a Portal allows the suggestions box to escape the bounds\n * of its parent while still being positioned correctly.\n * Defaults to `false`\n */\n usePortal?: boolean;\n\n /**\n * Function called when the input is focused\n *\n * @param event\n */\n onFocus?: (event: React.FocusEvent<HTMLInputElement>) => void;\n /**\n * Function called when the input is blurred\n * @param event\n */\n onBlur?: (event: React.FocusEvent<HTMLInputElement>) => void;\n}\n\nfunction _Autocomplete<ItemType>(\n props: AutocompleteProps<ItemType>,\n ref: React.Ref<HTMLDivElement>,\n) {\n const {\n id,\n className,\n clearAfterSelect = false,\n closeAfterSelect = true,\n defaultValue = '',\n selectedItem,\n items,\n onInputValueChange,\n onSelectItem,\n onFocus,\n onBlur,\n renderItem,\n icon = <ChevronDownIcon variant=\"muted\" />,\n itemToString = (item: ItemType) => item as unknown as string,\n isInvalid,\n isDisabled,\n isRequired,\n isReadOnly,\n showEmptyList,\n noMatchesMessage = 'No matches found',\n placeholder = 'Search',\n inputRef,\n toggleRef,\n listRef,\n listWidth = 'auto',\n listMaxHeight = 180,\n isGrouped = false,\n isLoading = false,\n usePortal = false,\n testId = 'cf-autocomplete',\n } = props;\n\n type GroupType = GenericGroupType<ItemType>;\n\n const styles = getAutocompleteStyles(listMaxHeight);\n\n const [inputValue, setInputValue] = useState(defaultValue);\n\n const handleInputValueChange = useCallback(\n (value: string) => {\n setInputValue(value);\n\n onInputValueChange?.(value);\n },\n [onInputValueChange],\n );\n\n // Handle manually to avoid a jumping cursor, see https://github.com/downshift-js/downshift/issues/1108#issuecomment-842407759\n const handleNativeChangeEvent = useCallback(\n (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {\n const value = event.target.value;\n handleInputValueChange(value);\n },\n [handleInputValueChange],\n );\n\n const flattenItems = isUsingGroups(isGrouped, items)\n ? items.reduce(\n (acc: ItemType[], group: GroupType) => [...acc, ...group.options],\n [],\n )\n : items;\n\n const isShowingNoMatches = isUsingGroups(isGrouped, items)\n ? items.every((group: GroupType) => group.options.length === 0)\n : items.length === 0;\n\n const {\n getComboboxProps,\n getInputProps,\n getItemProps,\n getMenuProps,\n getToggleButtonProps,\n highlightedIndex,\n isOpen,\n toggleMenu,\n } = useCombobox({\n items: flattenItems,\n selectedItem,\n inputValue,\n itemToString,\n onInputValueChange: ({ type, inputValue }) => {\n if (type !== '__input_change__') {\n handleInputValueChange(inputValue);\n }\n },\n onStateChange: ({ type, selectedItem }) => {\n switch (type) {\n case useCombobox.stateChangeTypes.InputKeyDownEnter:\n case useCombobox.stateChangeTypes.ItemClick:\n if (selectedItem) {\n onSelectItem(selectedItem);\n }\n if (clearAfterSelect) {\n handleInputValueChange('');\n }\n if (!closeAfterSelect) {\n toggleMenu();\n }\n break;\n default:\n break;\n }\n },\n });\n\n const {\n 'aria-labelledby': _labelledby,\n id: _inputId,\n ...inputProps\n } = getInputProps();\n const comboboxProps = getComboboxProps();\n const toggleProps = getToggleButtonProps();\n const menuProps = getMenuProps();\n let elementStartIndex = 0;\n\n return (\n <div\n data-test-id={testId}\n className={cx(styles.autocomplete, className)}\n ref={ref}\n >\n <Popover\n usePortal={usePortal}\n isOpen={isOpen}\n isFullWidth={listWidth === 'full'}\n renderOnlyWhenOpen={false}\n // This is necessary, otherwise the focus will change from the input to the Popover\n // and the user won't be able to type in the input\n // eslint-disable-next-line jsx-a11y/no-autofocus\n autoFocus={false}\n id={menuProps.id}\n >\n <Popover.Trigger>\n <div {...comboboxProps} className={styles.combobox}>\n <TextInput\n className={styles.inputField}\n {...inputProps}\n onFocus={(e) => {\n onFocus?.(e as React.FocusEvent<HTMLInputElement>);\n if (!isOpen) {\n toggleMenu();\n }\n }}\n onBlur={onBlur}\n id={id}\n isInvalid={isInvalid}\n isDisabled={isDisabled}\n isRequired={isRequired}\n isReadOnly={isReadOnly}\n ref={mergeRefs(inputProps.ref, inputRef)}\n testId=\"cf-autocomplete-input\"\n placeholder={placeholder}\n onChange={(event) => {\n inputProps.onChange(event);\n handleNativeChangeEvent(event);\n }}\n />\n <IconButton\n {...toggleProps}\n ref={mergeRefs(toggleProps.ref, toggleRef)}\n aria-label={inputValue ? 'Clear' : 'Show list'}\n className={styles.toggleButton}\n variant=\"transparent\"\n icon={inputValue ? <CloseIcon variant=\"muted\" /> : icon}\n onClick={() => {\n if (inputValue) {\n handleInputValueChange('');\n } else {\n toggleMenu();\n }\n }}\n isDisabled={isDisabled}\n size=\"small\"\n />\n </div>\n </Popover.Trigger>\n\n {items.length > 0 || inputValue.length > 0 || showEmptyList ? (\n <Popover.Content\n {...menuProps}\n ref={mergeRefs(menuProps.ref, listRef)}\n className={styles.content}\n testId=\"cf-autocomplete-container\"\n >\n {isLoading &&\n [...Array(3)].map((_, index) => (\n <div key={index} className={cx(styles.item, styles.disabled)}>\n <ListItemLoadingState />\n </div>\n ))}\n\n {!isLoading && isShowingNoMatches && (\n <div className={styles.item}>\n <Subheading className={styles.noMatchesTitle}>\n {noMatchesMessage}\n </Subheading>\n </div>\n )}\n\n {!isLoading &&\n isUsingGroups(isGrouped, items) &&\n items.map((group: GroupType, index: number) => {\n if (group.options.length < 1) {\n return;\n }\n const render = (\n <div key={index}>\n <SectionHeading\n key={index}\n data-test-id=\"cf-autocomplete-grouptitle\"\n marginBottom=\"none\"\n className={styles.groupTitle}\n >\n {group.groupTitle}\n </SectionHeading>\n <AutocompleteItems<ItemType>\n items={group.options}\n highlightedIndex={highlightedIndex}\n getItemProps={getItemProps}\n renderItem={renderItem}\n inputValue={inputValue}\n elementStartIndex={elementStartIndex}\n />\n </div>\n );\n elementStartIndex += group.options.length;\n return render;\n })}\n\n {!isLoading &&\n !isUsingGroups(isGrouped, items) &&\n items.length > 0 && (\n <AutocompleteItems<ItemType>\n items={items}\n elementStartIndex={elementStartIndex}\n highlightedIndex={highlightedIndex}\n getItemProps={getItemProps}\n renderItem={renderItem}\n inputValue={inputValue}\n />\n )}\n </Popover.Content>\n ) : (\n // We need to render an empty hidden div, so we can pass the menuProps or downshift will show a warning about it\n // https://github.com/downshift-js/downshift/issues/1167#issuecomment-1088022842\n <div {...menuProps} className={cx(styles.hidden)} />\n )}\n </Popover>\n </div>\n );\n}\n\nconst ListItemLoadingState = () => {\n return (\n <Skeleton.Container svgHeight={16}>\n <Skeleton.BodyText numberOfLines={1} />\n </Skeleton.Container>\n );\n};\n\n// This is required to infer correct typings when differentiating groups and items\nfunction isUsingGroups<ItemType>(\n isGrouped: boolean,\n items: ItemType[] | GenericGroupType<ItemType>[],\n): items is GenericGroupType<ItemType>[] {\n return isGrouped;\n}\n\n/**\n * The Autocomplete is a component that will show a `TextInput` where a user can type any word which will be used\n * to filter a list of items. That list of filtered items will be shown to the user as possible options for the input.\n * Once one of the options is selected, that option becomes the value of the `TextInput`.\n */\nexport const Autocomplete = React.forwardRef(_Autocomplete) as <T>(\n props: ExpandProps<AutocompleteProps<T>> & {\n ref?: React.Ref<HTMLDivElement>;\n },\n) => ReturnType<typeof _Autocomplete>;\n","import React, { HTMLAttributes } from 'react';\nimport { cx } from 'emotion';\nimport { getStringMatch } from '@contentful/f36-utils';\nimport type { UseComboboxGetItemPropsOptions } from 'downshift';\nimport { Text } from '@contentful/f36-typography';\n\nimport { getAutocompleteStyles } from './Autocomplete.styles';\n\ninterface AutocompleteItemsProps<ItemType> {\n items: ItemType[];\n elementStartIndex: number;\n highlightedIndex: number;\n getItemProps: (\n options: UseComboboxGetItemPropsOptions<ItemType>,\n ) => HTMLAttributes<HTMLLIElement>;\n renderItem: (item: ItemType, inputValue: string) => React.ReactNode;\n inputValue: string;\n listMaxHeight?: number;\n}\n\nexport const AutocompleteItems = <ItemType,>(\n props: AutocompleteItemsProps<ItemType>,\n) => {\n const {\n items,\n elementStartIndex,\n highlightedIndex,\n getItemProps,\n renderItem,\n inputValue,\n listMaxHeight = 180,\n } = props;\n\n const styles = getAutocompleteStyles(listMaxHeight);\n\n return (\n <ul className={styles.list} data-test-id=\"cf-autocomplete-list\">\n {items.map((item: ItemType, index: number) => {\n const itemIndex = elementStartIndex + index;\n const itemProps = getItemProps({ item, index: itemIndex });\n return (\n <Text\n {...itemProps}\n as=\"li\"\n key={itemIndex}\n className={cx([\n styles.item,\n highlightedIndex === itemIndex && styles.highlighted,\n ])}\n data-test-id={`cf-autocomplete-list-item-${itemIndex}`}\n >\n {renderItem ? (\n renderItem(item, inputValue)\n ) : typeof item === 'string' ? (\n <HighlightedItem item={item} inputValue={inputValue} />\n ) : (\n item\n )}\n </Text>\n );\n })}\n </ul>\n );\n};\n\nAutocompleteItems.displayName = 'AutocompleteItems';\n\nfunction HighlightedItem({\n item,\n inputValue,\n}: {\n item: string;\n inputValue: string;\n}) {\n const { before, match, after } = getStringMatch(item, inputValue);\n\n return (\n <>\n {before}\n <b>{match}</b>\n {after}\n </>\n );\n}\n\nHighlightedItem.displayName = 'HighlightedItem';\n","import { css } from 'emotion';\nimport tokens from '@contentful/f36-tokens';\n\nexport const getAutocompleteStyles = (listMaxHeight: number) => ({\n autocomplete: css({\n position: 'relative',\n width: '100%',\n }),\n combobox: css({\n position: 'relative',\n }),\n inputField: css({\n paddingRight: tokens.spacingXl,\n textOverflow: 'ellipsis',\n whiteSpace: 'nowrap',\n }),\n toggleButton: css({\n position: 'absolute',\n top: '1px',\n right: '1px',\n zIndex: 1,\n padding: tokens.spacing2Xs,\n height: '38px',\n }),\n content: css({\n overflow: 'auto',\n maxHeight: `${listMaxHeight}px`,\n }),\n list: css({\n listStyle: 'none',\n padding: `${tokens.spacingXs} 0`,\n margin: 0,\n }),\n groupTitle: css({\n padding: `${tokens.spacingXs} ${tokens.spacingM}`,\n lineHeight: tokens.lineHeightM,\n }),\n noMatchesTitle: css({\n color: tokens.gray500,\n margin: `${tokens.spacingM} 0 ${tokens.spacingM} 0`,\n }),\n item: css({\n display: 'block',\n padding: `${tokens.spacingXs} ${tokens.spacingM}`,\n wordBreak: 'break-word',\n whiteSpace: 'break-spaces',\n cursor: 'pointer',\n hyphens: 'auto',\n\n '&:focus, &:hover': {\n backgroundColor: tokens.gray100,\n },\n '&:active': {\n backgroundColor: tokens.gray200,\n },\n }),\n disabled: css({\n opacity: 0.5,\n pointerEvents: 'none',\n }),\n highlighted: css({\n backgroundColor: tokens.gray100,\n }),\n hidden: css({\n display: 'none',\n }),\n});\n"]}
1
+ {"version":3,"sources":["../../src/Autocomplete.tsx","../../src/AutocompleteItems.tsx","../../src/Autocomplete.styles.ts"],"names":["React","useCallback","useState","cx","useCombobox","mergeRefs","IconButton","TextInput","CloseIcon","ChevronDownIcon","Skeleton","Popover","Subheading","SectionHeading","getStringMatch","Text","css","tokens","getAutocompleteStyles","listMaxHeight","AutocompleteItems","props","items","elementStartIndex","highlightedIndex","getItemProps","renderItem","inputValue","styles","item","index","itemIndex","itemProps","__spreadProps","__spreadValues","HighlightedItem","before","match","after","_Autocomplete","ref","id","className","clearAfterSelect","closeAfterSelect","defaultValue","selectedItem","onInputValueChange","onSelectItem","onFocus","onBlur","icon","itemToString","isInvalid","isDisabled","isRequired","isReadOnly","showEmptyList","noMatchesMessage","placeholder","inputRef","toggleRef","listRef","listWidth","isGrouped","isLoading","usePortal","testId","setInputValue","handleInputValueChange","value","handleNativeChangeEvent","event","flattenItems","isUsingGroups","acc","group","isShowingNoMatches","getComboboxProps","getInputProps","getMenuProps","getToggleButtonProps","isOpen","toggleMenu","type","_a","_labelledby","_inputId","inputProps","__objRest","comboboxProps","toggleProps","menuProps","e","_","ListItemLoadingState","render","Autocomplete"],"mappings":"qlBAAA,OAAOA,GAAS,eAAAC,EAAa,YAAAC,OAAgB,QAC7C,OAAS,MAAAC,MAAU,UACnB,OAAS,eAAAC,MAAmB,YAE5B,OACE,aAAAC,MAGK,uBACP,OAAS,cAAAC,OAAkB,yBAC3B,OAAS,aAAAC,OAAsC,wBAC/C,OAAS,aAAAC,GAAW,mBAAAC,OAAuB,wBAC3C,OAAS,YAAAC,MAAgB,2BACzB,OAAS,WAAAC,MAAe,0BACxB,OAAS,cAAAC,GAAY,kBAAAC,OAAsB,6BCd3C,OAAOb,MAA+B,QACtC,OAAS,MAAAG,OAAU,UACnB,OAAS,kBAAAW,OAAsB,wBAE/B,OAAS,QAAAC,OAAY,6BCJrB,OAAS,OAAAC,MA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AmB,UAAWzF,EAAGyB,EAAO,MAAM,GAAG,CAEtD,CACF,CAEJ,CAEA,IAAMmE,GAAuB,IAEzB/F,EAAA,cAACU,EAAS,UAAT,CAAmB,UAAW,IAC7BV,EAAA,cAACU,EAAS,SAAT,CAAkB,cAAe,EAAG,CACvC,EAKJ,SAASgE,EACPV,EACA1C,EACuC,CACvC,OAAO0C,CACT,CAOO,IAAMiC,GAAejG,EAAM,WAAWuC,EAAa","sourcesContent":["import React, { useCallback, useState } from 'react';\nimport { cx } from 'emotion';\nimport { useCombobox } from 'downshift';\n\nimport {\n mergeRefs,\n type CommonProps,\n type ExpandProps,\n} from '@contentful/f36-core';\nimport { IconButton } from '@contentful/f36-button';\nimport { TextInput, type TextInputProps } from '@contentful/f36-forms';\nimport { CloseIcon, ChevronDownIcon } from '@contentful/f36-icons';\nimport { Skeleton } from '@contentful/f36-skeleton';\nimport { Popover } from '@contentful/f36-popover';\nimport { Subheading, SectionHeading } from '@contentful/f36-typography';\n\nimport { AutocompleteItems } from './AutocompleteItems';\nimport { getAutocompleteStyles } from './Autocomplete.styles';\n\nexport interface GenericGroupType<ItemType> {\n groupTitle: string;\n options: ItemType[];\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface AutocompleteProps<ItemType>\n extends CommonProps,\n Pick<\n TextInputProps,\n | 'isDisabled'\n | 'isInvalid'\n | 'isReadOnly'\n | 'isRequired'\n | 'id'\n | 'defaultValue'\n > {\n /**\n * It’s an array of data to be used as \"options\" by the autocomplete component.\n * This can either be a plain list of items or a list of groups of items.\n */\n items: ItemType[] | GenericGroupType<ItemType>[];\n\n /**\n * Set a custom icon for the text input\n */\n icon?: React.ReactElement;\n\n /**\n * Tells if the item is a object with groups\n */\n isGrouped?: boolean;\n\n /**\n * Function called whenever the input value changes\n */\n onInputValueChange?: (value: string) => void;\n /**\n * This is the function that will be called when the user selects one of the \"options\" in the list.\n * The component will pass the selected \"item\" as an argument to the function..\n */\n onSelectItem: (item: ItemType) => void;\n\n /**\n * Applying the selectedItem property turns autocomplete into a controlled component.\n * Can be used to display e.g. previously selected element. If it is an object the itemToString function will apply to it.\n */\n selectedItem?: ItemType;\n\n /**\n * This is the function that will be called for each \"item\" passed in the `items` prop.\n * It receives the \"item\" and \"inputValue\" as arguments and returns a ReactNode.\n * The inputValue is passed in case you want to highlight the match on the render.\n */\n renderItem?: (item: ItemType, inputValue: string) => React.ReactNode;\n /**\n * When using objects as `items`, we recommend passing a function that tells Downshift how to extract a string\n * from those objetcs to be used as inputValue\n */\n itemToString?: (item: ItemType) => string;\n /**\n * If this is set to `true` the text input will be cleared after an item is selected\n * @default false\n */\n clearAfterSelect?: boolean;\n /**\n * If this is set to `false` the dropdown menu will stay open after selecting an item\n * @default true\n */\n closeAfterSelect?: boolean;\n /**\n * This is the value will be passed to the `placeholder` prop of the input.\n * @default \"Search\"\n */\n placeholder?: string;\n /**\n * Defines if the list should be shown even if empty, when input is focused\n * @default false\n */\n showEmptyList?: boolean;\n /**\n * A message that will be shown when it is not possible to find any option that matches the input value\n * @default \"No matches\"\n */\n noMatchesMessage?: string;\n /**\n * Use this prop to get a ref to the input element of the component\n */\n inputRef?: React.Ref<HTMLInputElement>;\n /**\n * Use this prop to get a ref to the toggle button of the component\n */\n toggleRef?: React.Ref<HTMLButtonElement>;\n /**\n * Use this prop to get a ref to the list of items of the component\n */\n listRef?: React.Ref<HTMLUListElement>;\n /**\n * It sets the width of the list\n * @default \"auto\"\n */\n listWidth?: 'auto' | 'full';\n /**\n * It sets the max-height, in pixels, of the list\n * The default value is the height of 5 single line items\n * @default 180\n */\n listMaxHeight?: number;\n /**\n * Sets the list to show its loading state\n * @default false\n */\n isLoading?: boolean;\n /**\n * Boolean to control whether or not to render the suggestions box in a React Portal.\n * Rendering content inside a Portal allows the suggestions box to escape the bounds\n * of its parent while still being positioned correctly.\n * Defaults to `false`\n */\n usePortal?: boolean;\n\n /**\n * Function called when the input is focused\n *\n * @param event\n */\n onFocus?: (event: React.FocusEvent<HTMLInputElement>) => void;\n /**\n * Function called when the input is blurred\n * @param event\n */\n onBlur?: (event: React.FocusEvent<HTMLInputElement>) => void;\n}\n\nfunction _Autocomplete<ItemType>(\n props: AutocompleteProps<ItemType>,\n ref: React.Ref<HTMLDivElement>,\n) {\n const {\n id,\n className,\n clearAfterSelect = false,\n closeAfterSelect = true,\n defaultValue = '',\n selectedItem,\n items,\n onInputValueChange,\n onSelectItem,\n onFocus,\n onBlur,\n renderItem,\n icon = <ChevronDownIcon variant=\"muted\" />,\n itemToString = (item: ItemType) => item as unknown as string,\n isInvalid,\n isDisabled,\n isRequired,\n isReadOnly,\n showEmptyList,\n noMatchesMessage = 'No matches found',\n placeholder = 'Search',\n inputRef,\n toggleRef,\n listRef,\n listWidth = 'auto',\n listMaxHeight = 180,\n isGrouped = false,\n isLoading = false,\n usePortal = false,\n testId = 'cf-autocomplete',\n } = props;\n\n type GroupType = GenericGroupType<ItemType>;\n\n const styles = getAutocompleteStyles(listMaxHeight);\n\n const [inputValue, setInputValue] = useState(defaultValue);\n\n const handleInputValueChange = useCallback(\n (value: string) => {\n setInputValue(value);\n\n onInputValueChange?.(value);\n },\n [onInputValueChange],\n );\n\n // Handle manually to avoid a jumping cursor, see https://github.com/downshift-js/downshift/issues/1108#issuecomment-842407759\n const handleNativeChangeEvent = useCallback(\n (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {\n const value = event.target.value;\n handleInputValueChange(value);\n },\n [handleInputValueChange],\n );\n\n const flattenItems = isUsingGroups(isGrouped, items)\n ? items.reduce(\n (acc: ItemType[], group: GroupType) => [...acc, ...group.options],\n [],\n )\n : items;\n\n const isShowingNoMatches = isUsingGroups(isGrouped, items)\n ? items.every((group: GroupType) => group.options.length === 0)\n : items.length === 0;\n\n const {\n getComboboxProps,\n getInputProps,\n getItemProps,\n getMenuProps,\n getToggleButtonProps,\n highlightedIndex,\n isOpen,\n toggleMenu,\n } = useCombobox({\n items: flattenItems,\n selectedItem,\n inputValue,\n itemToString,\n onInputValueChange: ({ type, inputValue }) => {\n if (type !== '__input_change__') {\n handleInputValueChange(inputValue);\n }\n },\n onStateChange: ({ type, selectedItem }) => {\n switch (type) {\n case useCombobox.stateChangeTypes.InputKeyDownEnter:\n case useCombobox.stateChangeTypes.ItemClick:\n if (selectedItem) {\n onSelectItem(selectedItem);\n }\n if (clearAfterSelect) {\n handleInputValueChange('');\n }\n if (!closeAfterSelect) {\n toggleMenu();\n }\n break;\n default:\n break;\n }\n },\n });\n\n const {\n 'aria-labelledby': _labelledby,\n id: _inputId,\n ...inputProps\n } = getInputProps();\n const comboboxProps = getComboboxProps();\n const toggleProps = getToggleButtonProps();\n const menuProps = getMenuProps();\n let elementStartIndex = 0;\n\n return (\n <div\n data-test-id={testId}\n className={cx(styles.autocomplete, className)}\n ref={ref}\n >\n <Popover\n usePortal={usePortal}\n isOpen={isOpen}\n isFullWidth={listWidth === 'full'}\n renderOnlyWhenOpen={false}\n // This is necessary, otherwise the focus will change from the input to the Popover\n // and the user won't be able to type in the input\n // eslint-disable-next-line jsx-a11y/no-autofocus\n autoFocus={false}\n id={menuProps.id}\n >\n <Popover.Trigger>\n <div {...comboboxProps} className={styles.combobox}>\n <TextInput\n className={styles.inputField}\n {...inputProps}\n onFocus={(e) => {\n onFocus?.(e as React.FocusEvent<HTMLInputElement>);\n if (!isOpen) {\n toggleMenu();\n }\n }}\n onBlur={onBlur}\n id={id}\n isInvalid={isInvalid}\n isDisabled={isDisabled}\n isRequired={isRequired}\n isReadOnly={isReadOnly}\n ref={mergeRefs(inputProps.ref, inputRef)}\n testId=\"cf-autocomplete-input\"\n placeholder={placeholder}\n onChange={(event) => {\n inputProps.onChange(event);\n handleNativeChangeEvent(event);\n }}\n />\n <IconButton\n {...toggleProps}\n ref={mergeRefs(toggleProps.ref, toggleRef)}\n aria-label={inputValue ? 'Clear' : 'Show list'}\n className={styles.toggleButton}\n variant=\"transparent\"\n icon={inputValue ? <CloseIcon variant=\"muted\" /> : icon}\n onClick={() => {\n if (inputValue) {\n handleInputValueChange('');\n } else {\n toggleMenu();\n }\n }}\n isDisabled={isDisabled}\n size=\"small\"\n />\n </div>\n </Popover.Trigger>\n\n {items.length > 0 || inputValue.length > 0 || showEmptyList ? (\n <Popover.Content\n {...menuProps}\n ref={mergeRefs(menuProps.ref, listRef)}\n className={styles.content}\n testId=\"cf-autocomplete-container\"\n >\n {isLoading &&\n [...Array(3)].map((_, index) => (\n <div key={index} className={cx(styles.item, styles.disabled)}>\n <ListItemLoadingState />\n </div>\n ))}\n\n {!isLoading && isShowingNoMatches && (\n <div className={styles.item}>\n <Subheading className={styles.noMatchesTitle}>\n {noMatchesMessage}\n </Subheading>\n </div>\n )}\n\n {!isLoading &&\n isUsingGroups(isGrouped, items) &&\n items.map((group: GroupType, index: number) => {\n if (group.options.length < 1) {\n return;\n }\n const render = (\n <div key={index}>\n <SectionHeading\n key={index}\n data-test-id=\"cf-autocomplete-grouptitle\"\n marginBottom=\"none\"\n className={styles.groupTitle}\n >\n {group.groupTitle}\n </SectionHeading>\n <AutocompleteItems<ItemType>\n items={group.options}\n highlightedIndex={highlightedIndex}\n getItemProps={getItemProps}\n renderItem={renderItem}\n inputValue={inputValue}\n elementStartIndex={elementStartIndex}\n />\n </div>\n );\n elementStartIndex += group.options.length;\n return render;\n })}\n\n {!isLoading &&\n !isUsingGroups(isGrouped, items) &&\n items.length > 0 && (\n <AutocompleteItems<ItemType>\n items={items}\n elementStartIndex={elementStartIndex}\n highlightedIndex={highlightedIndex}\n getItemProps={getItemProps}\n renderItem={renderItem}\n inputValue={inputValue}\n />\n )}\n </Popover.Content>\n ) : (\n // We need to render an empty hidden div, so we can pass the menuProps or downshift will show a warning about it\n // https://github.com/downshift-js/downshift/issues/1167#issuecomment-1088022842\n <div {...menuProps} className={cx(styles.hidden)} />\n )}\n </Popover>\n </div>\n );\n}\n\nconst ListItemLoadingState = () => {\n return (\n <Skeleton.Container svgHeight={16}>\n <Skeleton.BodyText numberOfLines={1} />\n </Skeleton.Container>\n );\n};\n\n// This is required to infer correct typings when differentiating groups and items\nfunction isUsingGroups<ItemType>(\n isGrouped: boolean,\n items: ItemType[] | GenericGroupType<ItemType>[],\n): items is GenericGroupType<ItemType>[] {\n return isGrouped;\n}\n\n/**\n * The Autocomplete is a component that will show a `TextInput` where a user can type any word which will be used\n * to filter a list of items. That list of filtered items will be shown to the user as possible options for the input.\n * Once one of the options is selected, that option becomes the value of the `TextInput`.\n */\nexport const Autocomplete = React.forwardRef(_Autocomplete) as <T>(\n props: ExpandProps<AutocompleteProps<T>> & {\n ref?: React.Ref<HTMLDivElement>;\n },\n) => ReturnType<typeof _Autocomplete>;\n","import React, { HTMLAttributes } from 'react';\nimport { cx } from 'emotion';\nimport { getStringMatch } from '@contentful/f36-utils';\nimport type { UseComboboxGetItemPropsOptions } from 'downshift';\nimport { Text } from '@contentful/f36-typography';\n\nimport { getAutocompleteStyles } from './Autocomplete.styles';\n\ninterface AutocompleteItemsProps<ItemType> {\n items: ItemType[];\n elementStartIndex: number;\n highlightedIndex: number;\n getItemProps: (\n options: UseComboboxGetItemPropsOptions<ItemType>,\n ) => HTMLAttributes<HTMLLIElement>;\n renderItem: (item: ItemType, inputValue: string) => React.ReactNode;\n inputValue: string;\n listMaxHeight?: number;\n}\n\nexport const AutocompleteItems = <ItemType,>(\n props: AutocompleteItemsProps<ItemType>,\n) => {\n const {\n items,\n elementStartIndex,\n highlightedIndex,\n getItemProps,\n renderItem,\n inputValue,\n listMaxHeight = 180,\n } = props;\n\n const styles = getAutocompleteStyles(listMaxHeight);\n\n return (\n <ul className={styles.list} data-test-id=\"cf-autocomplete-list\">\n {items.map((item: ItemType, index: number) => {\n const itemIndex = elementStartIndex + index;\n const itemProps = getItemProps({ item, index: itemIndex });\n return (\n <Text\n {...itemProps}\n as=\"li\"\n key={itemIndex}\n className={cx([\n styles.item,\n highlightedIndex === itemIndex && styles.highlighted,\n ])}\n data-test-id={`cf-autocomplete-list-item-${itemIndex}`}\n >\n {renderItem ? (\n renderItem(item, inputValue)\n ) : typeof item === 'string' ? (\n <HighlightedItem item={item} inputValue={inputValue} />\n ) : (\n item\n )}\n </Text>\n );\n })}\n </ul>\n );\n};\n\nAutocompleteItems.displayName = 'AutocompleteItems';\n\nfunction HighlightedItem({\n item,\n inputValue,\n}: {\n item: string;\n inputValue: string;\n}) {\n const { before, match, after } = getStringMatch(item, inputValue);\n\n return (\n <>\n {before}\n <b>{match}</b>\n {after}\n </>\n );\n}\n\nHighlightedItem.displayName = 'HighlightedItem';\n","import { css } from 'emotion';\nimport tokens from '@contentful/f36-tokens';\n\nexport const getAutocompleteStyles = (listMaxHeight: number) => ({\n autocomplete: css({\n position: 'relative',\n width: '100%',\n }),\n combobox: css({\n position: 'relative',\n }),\n inputField: css({\n paddingRight: tokens.spacingXl,\n textOverflow: 'ellipsis',\n whiteSpace: 'nowrap',\n }),\n toggleButton: css({\n position: 'absolute',\n top: '1px',\n right: '1px',\n zIndex: 1,\n padding: tokens.spacing2Xs,\n height: '38px',\n }),\n content: css({\n overflow: 'auto',\n maxHeight: `${listMaxHeight}px`,\n }),\n list: css({\n listStyle: 'none',\n padding: `${tokens.spacingXs} 0`,\n margin: 0,\n }),\n groupTitle: css({\n padding: `${tokens.spacingXs} ${tokens.spacingM}`,\n lineHeight: tokens.lineHeightM,\n }),\n noMatchesTitle: css({\n color: tokens.gray500,\n margin: `${tokens.spacingM} 0 ${tokens.spacingM} 0`,\n }),\n item: css({\n display: 'block',\n padding: `${tokens.spacingXs} ${tokens.spacingM}`,\n wordBreak: 'break-word',\n whiteSpace: 'break-spaces',\n cursor: 'pointer',\n hyphens: 'auto',\n\n '&:focus, &:hover': {\n backgroundColor: tokens.gray100,\n },\n '&:active': {\n backgroundColor: tokens.gray200,\n },\n }),\n disabled: css({\n opacity: 0.5,\n pointerEvents: 'none',\n }),\n highlighted: css({\n backgroundColor: tokens.gray100,\n }),\n hidden: css({\n display: 'none',\n }),\n});\n"]}
@@ -0,0 +1,130 @@
1
+ import React from 'react';
2
+ import { CommonProps } from '@contentful/f36-core';
3
+ import { TextInputProps } from '@contentful/f36-forms';
4
+
5
+ interface GenericGroupType<ItemType> {
6
+ groupTitle: string;
7
+ options: ItemType[];
8
+ }
9
+ interface AutocompleteProps<ItemType> extends CommonProps, Pick<TextInputProps, 'isDisabled' | 'isInvalid' | 'isReadOnly' | 'isRequired' | 'id' | 'defaultValue'> {
10
+ /**
11
+ * It’s an array of data to be used as "options" by the autocomplete component.
12
+ * This can either be a plain list of items or a list of groups of items.
13
+ */
14
+ items: ItemType[] | GenericGroupType<ItemType>[];
15
+ /**
16
+ * Set a custom icon for the text input
17
+ */
18
+ icon?: React.ReactElement;
19
+ /**
20
+ * Tells if the item is a object with groups
21
+ */
22
+ isGrouped?: boolean;
23
+ /**
24
+ * Function called whenever the input value changes
25
+ */
26
+ onInputValueChange?: (value: string) => void;
27
+ /**
28
+ * This is the function that will be called when the user selects one of the "options" in the list.
29
+ * The component will pass the selected "item" as an argument to the function..
30
+ */
31
+ onSelectItem: (item: ItemType) => void;
32
+ /**
33
+ * Applying the selectedItem property turns autocomplete into a controlled component.
34
+ * Can be used to display e.g. previously selected element. If it is an object the itemToString function will apply to it.
35
+ */
36
+ selectedItem?: ItemType;
37
+ /**
38
+ * This is the function that will be called for each "item" passed in the `items` prop.
39
+ * It receives the "item" and "inputValue" as arguments and returns a ReactNode.
40
+ * The inputValue is passed in case you want to highlight the match on the render.
41
+ */
42
+ renderItem?: (item: ItemType, inputValue: string) => React.ReactNode;
43
+ /**
44
+ * When using objects as `items`, we recommend passing a function that tells Downshift how to extract a string
45
+ * from those objetcs to be used as inputValue
46
+ */
47
+ itemToString?: (item: ItemType) => string;
48
+ /**
49
+ * If this is set to `true` the text input will be cleared after an item is selected
50
+ * @default false
51
+ */
52
+ clearAfterSelect?: boolean;
53
+ /**
54
+ * If this is set to `false` the dropdown menu will stay open after selecting an item
55
+ * @default true
56
+ */
57
+ closeAfterSelect?: boolean;
58
+ /**
59
+ * This is the value will be passed to the `placeholder` prop of the input.
60
+ * @default "Search"
61
+ */
62
+ placeholder?: string;
63
+ /**
64
+ * Defines if the list should be shown even if empty, when input is focused
65
+ * @default false
66
+ */
67
+ showEmptyList?: boolean;
68
+ /**
69
+ * A message that will be shown when it is not possible to find any option that matches the input value
70
+ * @default "No matches"
71
+ */
72
+ noMatchesMessage?: string;
73
+ /**
74
+ * Use this prop to get a ref to the input element of the component
75
+ */
76
+ inputRef?: React.Ref<HTMLInputElement>;
77
+ /**
78
+ * Use this prop to get a ref to the toggle button of the component
79
+ */
80
+ toggleRef?: React.Ref<HTMLButtonElement>;
81
+ /**
82
+ * Use this prop to get a ref to the list of items of the component
83
+ */
84
+ listRef?: React.Ref<HTMLUListElement>;
85
+ /**
86
+ * It sets the width of the list
87
+ * @default "auto"
88
+ */
89
+ listWidth?: 'auto' | 'full';
90
+ /**
91
+ * It sets the max-height, in pixels, of the list
92
+ * The default value is the height of 5 single line items
93
+ * @default 180
94
+ */
95
+ listMaxHeight?: number;
96
+ /**
97
+ * Sets the list to show its loading state
98
+ * @default false
99
+ */
100
+ isLoading?: boolean;
101
+ /**
102
+ * Boolean to control whether or not to render the suggestions box in a React Portal.
103
+ * Rendering content inside a Portal allows the suggestions box to escape the bounds
104
+ * of its parent while still being positioned correctly.
105
+ * Defaults to `false`
106
+ */
107
+ usePortal?: boolean;
108
+ /**
109
+ * Function called when the input is focused
110
+ *
111
+ * @param event
112
+ */
113
+ onFocus?: (event: React.FocusEvent<HTMLInputElement>) => void;
114
+ /**
115
+ * Function called when the input is blurred
116
+ * @param event
117
+ */
118
+ onBlur?: (event: React.FocusEvent<HTMLInputElement>) => void;
119
+ }
120
+ declare function _Autocomplete<ItemType>(props: AutocompleteProps<ItemType>, ref: React.Ref<HTMLDivElement>): JSX.Element;
121
+ /**
122
+ * The Autocomplete is a component that will show a `TextInput` where a user can type any word which will be used
123
+ * to filter a list of items. That list of filtered items will be shown to the user as possible options for the input.
124
+ * Once one of the options is selected, that option becomes the value of the `TextInput`.
125
+ */
126
+ declare const Autocomplete: <T>(props: AutocompleteProps<T> & {
127
+ ref?: React.Ref<HTMLDivElement>;
128
+ }) => ReturnType<typeof _Autocomplete>;
129
+
130
+ export { Autocomplete, AutocompleteProps };
package/dist/index.js CHANGED
@@ -1,7 +1,5 @@
1
1
  'use strict';
2
2
 
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
3
  var n = require('react');
6
4
  var emotion = require('emotion');
7
5
  var downshift = require('downshift');
@@ -15,12 +13,13 @@ var f36Typography = require('@contentful/f36-typography');
15
13
  var f36Utils = require('@contentful/f36-utils');
16
14
  var p = require('@contentful/f36-tokens');
17
15
 
18
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
16
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
19
17
 
20
- var n__default = /*#__PURE__*/_interopDefaultLegacy(n);
21
- var p__default = /*#__PURE__*/_interopDefaultLegacy(p);
18
+ var n__default = /*#__PURE__*/_interopDefault(n);
19
+ var p__default = /*#__PURE__*/_interopDefault(p);
22
20
 
23
- var Pe=Object.defineProperty,Me=Object.defineProperties;var Se=Object.getOwnPropertyDescriptors;var M=Object.getOwnPropertySymbols;var q=Object.prototype.hasOwnProperty,z=Object.prototype.propertyIsEnumerable;var W=(e,o,i)=>o in e?Pe(e,o,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[o]=i,d=(e,o)=>{for(var i in o||(o={}))q.call(o,i)&&W(e,i,o[i]);if(M)for(var i of M(o))z.call(o,i)&&W(e,i,o[i]);return e},g=(e,o)=>Me(e,Se(o));var j=(e,o)=>{var i={};for(var r in e)q.call(e,r)&&o.indexOf(r)<0&&(i[r]=e[r]);if(e!=null&&M)for(var r of M(e))o.indexOf(r)<0&&z.call(e,r)&&(i[r]=e[r]);return i};var S=e=>({autocomplete:emotion.css({position:"relative",width:"100%"}),combobox:emotion.css({position:"relative"}),inputField:emotion.css({paddingRight:p__default["default"].spacingXl,textOverflow:"ellipsis",whiteSpace:"nowrap"}),toggleButton:emotion.css({position:"absolute",top:"1px",right:"1px",zIndex:1,padding:p__default["default"].spacing2Xs,height:"38px"}),content:emotion.css({overflow:"auto",maxHeight:`${e}px`}),list:emotion.css({listStyle:"none",padding:`${p__default["default"].spacingXs} 0`,margin:0}),groupTitle:emotion.css({padding:`${p__default["default"].spacingXs} ${p__default["default"].spacingM}`,lineHeight:p__default["default"].lineHeightM}),noMatchesTitle:emotion.css({color:p__default["default"].gray500,margin:`${p__default["default"].spacingM} 0 ${p__default["default"].spacingM} 0`}),item:emotion.css({display:"block",padding:`${p__default["default"].spacingXs} ${p__default["default"].spacingM}`,wordBreak:"break-word",whiteSpace:"break-spaces",cursor:"pointer",hyphens:"auto","&:focus, &:hover":{backgroundColor:p__default["default"].gray100},"&:active":{backgroundColor:p__default["default"].gray200}}),disabled:emotion.css({opacity:.5,pointerEvents:"none"}),highlighted:emotion.css({backgroundColor:p__default["default"].gray100}),hidden:emotion.css({display:"none"})});var C=e=>{let{items:o,elementStartIndex:i,highlightedIndex:r,getItemProps:I,renderItem:T,inputValue:b,listMaxHeight:H=180}=e,s=S(H);return n__default["default"].createElement("ul",{className:s.list,"data-test-id":"cf-autocomplete-list"},o.map((u,E)=>{let c=i+E,L=I({item:u,index:c});return n__default["default"].createElement(f36Typography.Text,g(d({},L),{as:"li",key:c,className:emotion.cx([s.item,r===c&&s.highlighted]),"data-test-id":`cf-autocomplete-list-item-${c}`}),T?T(u,b):typeof u=="string"?n__default["default"].createElement(K,{item:u,inputValue:b}):u)}))};C.displayName="AutocompleteItems";function K({item:e,inputValue:o}){let{before:i,match:r,after:I}=f36Utils.getStringMatch(e,o);return n__default["default"].createElement(n__default["default"].Fragment,null,i,n__default["default"].createElement("b",null,r),I)}K.displayName="HighlightedItem";function Re(e,o){let {id:i,className:r,clearAfterSelect:I=!1,closeAfterSelect:T=!0,defaultValue:b="",selectedItem:H,items:s,onInputValueChange:u,onSelectItem:E,onFocus:c,onBlur:L,renderItem:O,icon:Y=n__default["default"].createElement(f36Icons.ChevronDownIcon,{variant:"muted"}),itemToString:Z=t=>t,isInvalid:ee,isDisabled:_,isRequired:te,isReadOnly:oe,showEmptyList:ne,noMatchesMessage:ie="No matches found",placeholder:se="Search",inputRef:re,toggleRef:pe,listRef:le,listWidth:ae="auto",listMaxHeight:me=180,isGrouped:x=!1,isLoading:v=!1,usePortal:ue=!1,testId:ce="cf-autocomplete"}=e,m=S(me),[h,de]=n.useState(b),y=n.useCallback(t=>{de(t),u==null||u(t);},[u]),ge=n.useCallback(t=>{let l=t.target.value;y(l);},[y]),he=A(x)?s.reduce((t,l)=>[...t,...l.options],[]):s,fe=A(x)?s.every(t=>t.options.length===0):s.length===0,{getComboboxProps:Ie,getInputProps:ye,getItemProps:$,getMenuProps:Te,getToggleButtonProps:be,highlightedIndex:D,isOpen:F,toggleMenu:k}=downshift.useCombobox({items:he,selectedItem:H,inputValue:h,itemToString:Z,onInputValueChange:({type:t,inputValue:l})=>{t!=="__input_change__"&&y(l);},onStateChange:({type:t,selectedItem:l})=>{switch(t){case downshift.useCombobox.stateChangeTypes.InputKeyDownEnter:case downshift.useCombobox.stateChangeTypes.ItemClick:l&&E(l),I&&y(""),T||k();break;}}}),U=ye(),w=j(U,["aria-labelledby","id"]),xe=Ie(),X=be(),P=Te(),N=0;return n__default["default"].createElement("div",{"data-test-id":ce,className:emotion.cx(m.autocomplete,r),ref:o},n__default["default"].createElement(f36Popover.Popover,{usePortal:ue,isOpen:F,isFullWidth:ae==="full",renderOnlyWhenOpen:!1,autoFocus:!1,id:P.id},n__default["default"].createElement(f36Popover.Popover.Trigger,null,n__default["default"].createElement("div",g(d({},xe),{className:m.combobox}),n__default["default"].createElement(f36Forms.TextInput,g(d({className:m.inputField},w),{onFocus:t=>{c==null||c(t),F||k();},onBlur:L,id:i,isInvalid:ee,isDisabled:_,isRequired:te,isReadOnly:oe,ref:f36Core.mergeRefs(w.ref,re),testId:"cf-autocomplete-input",placeholder:se,onChange:t=>{w.onChange(t),ge(t);}})),n__default["default"].createElement(f36Button.IconButton,g(d({},X),{ref:f36Core.mergeRefs(X.ref,pe),"aria-label":h?"Clear":"Show list",className:m.toggleButton,variant:"transparent",icon:h?n__default["default"].createElement(f36Icons.CloseIcon,{variant:"muted"}):Y,onClick:()=>{h?y(""):k();},isDisabled:_,size:"small"})))),s.length>0||h.length>0||ne?n__default["default"].createElement(f36Popover.Popover.Content,g(d({},P),{ref:f36Core.mergeRefs(P.ref,le),className:m.content,testId:"cf-autocomplete-container"}),v&&[...Array(3)].map((t,l)=>n__default["default"].createElement("div",{key:l,className:emotion.cx(m.item,m.disabled)},n__default["default"].createElement(Be,null))),!v&&fe&&n__default["default"].createElement("div",{className:m.item},n__default["default"].createElement(f36Typography.Subheading,{className:m.noMatchesTitle},ie)),!v&&A(x)&&s.map((t,l)=>{if(t.options.length<1)return;let ve=n__default["default"].createElement("div",{key:l},n__default["default"].createElement(f36Typography.SectionHeading,{key:l,"data-test-id":"cf-autocomplete-grouptitle",marginBottom:"none",className:m.groupTitle},t.groupTitle),n__default["default"].createElement(C,{items:t.options,highlightedIndex:D,getItemProps:$,renderItem:O,inputValue:h,elementStartIndex:N}));return N+=t.options.length,ve}),!v&&!A(x)&&s.length>0&&n__default["default"].createElement(C,{items:s,elementStartIndex:N,highlightedIndex:D,getItemProps:$,renderItem:O,inputValue:h})):n__default["default"].createElement("div",g(d({},P),{className:emotion.cx(m.hidden)}))))}var Be=()=>n__default["default"].createElement(f36Skeleton.Skeleton.Container,{svgHeight:16},n__default["default"].createElement(f36Skeleton.Skeleton.BodyText,{numberOfLines:1}));function A(e,o){return e}var Oe=n__default["default"].forwardRef(Re);
21
+ var Pe=Object.defineProperty,Me=Object.defineProperties;var Se=Object.getOwnPropertyDescriptors;var M=Object.getOwnPropertySymbols;var q=Object.prototype.hasOwnProperty,z=Object.prototype.propertyIsEnumerable;var W=(e,o,i)=>o in e?Pe(e,o,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[o]=i,d=(e,o)=>{for(var i in o||(o={}))q.call(o,i)&&W(e,i,o[i]);if(M)for(var i of M(o))z.call(o,i)&&W(e,i,o[i]);return e},g=(e,o)=>Me(e,Se(o));var j=(e,o)=>{var i={};for(var r in e)q.call(e,r)&&o.indexOf(r)<0&&(i[r]=e[r]);if(e!=null&&M)for(var r of M(e))o.indexOf(r)<0&&z.call(e,r)&&(i[r]=e[r]);return i};var S=e=>({autocomplete:emotion.css({position:"relative",width:"100%"}),combobox:emotion.css({position:"relative"}),inputField:emotion.css({paddingRight:p__default.default.spacingXl,textOverflow:"ellipsis",whiteSpace:"nowrap"}),toggleButton:emotion.css({position:"absolute",top:"1px",right:"1px",zIndex:1,padding:p__default.default.spacing2Xs,height:"38px"}),content:emotion.css({overflow:"auto",maxHeight:`${e}px`}),list:emotion.css({listStyle:"none",padding:`${p__default.default.spacingXs} 0`,margin:0}),groupTitle:emotion.css({padding:`${p__default.default.spacingXs} ${p__default.default.spacingM}`,lineHeight:p__default.default.lineHeightM}),noMatchesTitle:emotion.css({color:p__default.default.gray500,margin:`${p__default.default.spacingM} 0 ${p__default.default.spacingM} 0`}),item:emotion.css({display:"block",padding:`${p__default.default.spacingXs} ${p__default.default.spacingM}`,wordBreak:"break-word",whiteSpace:"break-spaces",cursor:"pointer",hyphens:"auto","&:focus, &:hover":{backgroundColor:p__default.default.gray100},"&:active":{backgroundColor:p__default.default.gray200}}),disabled:emotion.css({opacity:.5,pointerEvents:"none"}),highlighted:emotion.css({backgroundColor:p__default.default.gray100}),hidden:emotion.css({display:"none"})});var C=e=>{let{items:o,elementStartIndex:i,highlightedIndex:r,getItemProps:I,renderItem:T,inputValue:b,listMaxHeight:H=180}=e,s=S(H);return n__default.default.createElement("ul",{className:s.list,"data-test-id":"cf-autocomplete-list"},o.map((u,E)=>{let c=i+E,L=I({item:u,index:c});return n__default.default.createElement(f36Typography.Text,g(d({},L),{as:"li",key:c,className:emotion.cx([s.item,r===c&&s.highlighted]),"data-test-id":`cf-autocomplete-list-item-${c}`}),T?T(u,b):typeof u=="string"?n__default.default.createElement(K,{item:u,inputValue:b}):u)}))};C.displayName="AutocompleteItems";function K({item:e,inputValue:o}){let{before:i,match:r,after:I}=f36Utils.getStringMatch(e,o);return n__default.default.createElement(n__default.default.Fragment,null,i,n__default.default.createElement("b",null,r),I)}K.displayName="HighlightedItem";function Re(e,o){let {id:i,className:r,clearAfterSelect:I=!1,closeAfterSelect:T=!0,defaultValue:b="",selectedItem:H,items:s,onInputValueChange:u,onSelectItem:E,onFocus:c,onBlur:L,renderItem:O,icon:Y=n__default.default.createElement(f36Icons.ChevronDownIcon,{variant:"muted"}),itemToString:Z=t=>t,isInvalid:ee,isDisabled:_,isRequired:te,isReadOnly:oe,showEmptyList:ne,noMatchesMessage:ie="No matches found",placeholder:se="Search",inputRef:re,toggleRef:pe,listRef:le,listWidth:ae="auto",listMaxHeight:me=180,isGrouped:x=!1,isLoading:v=!1,usePortal:ue=!1,testId:ce="cf-autocomplete"}=e,m=S(me),[h,de]=n.useState(b),y=n.useCallback(t=>{de(t),u==null||u(t);},[u]),ge=n.useCallback(t=>{let l=t.target.value;y(l);},[y]),he=A(x)?s.reduce((t,l)=>[...t,...l.options],[]):s,fe=A(x)?s.every(t=>t.options.length===0):s.length===0,{getComboboxProps:Ie,getInputProps:ye,getItemProps:$,getMenuProps:Te,getToggleButtonProps:be,highlightedIndex:D,isOpen:F,toggleMenu:k}=downshift.useCombobox({items:he,selectedItem:H,inputValue:h,itemToString:Z,onInputValueChange:({type:t,inputValue:l})=>{t!=="__input_change__"&&y(l);},onStateChange:({type:t,selectedItem:l})=>{switch(t){case downshift.useCombobox.stateChangeTypes.InputKeyDownEnter:case downshift.useCombobox.stateChangeTypes.ItemClick:l&&E(l),I&&y(""),T||k();break;}}}),U=ye(),w=j(U,["aria-labelledby","id"]),xe=Ie(),X=be(),P=Te(),N=0;return n__default.default.createElement("div",{"data-test-id":ce,className:emotion.cx(m.autocomplete,r),ref:o},n__default.default.createElement(f36Popover.Popover,{usePortal:ue,isOpen:F,isFullWidth:ae==="full",renderOnlyWhenOpen:!1,autoFocus:!1,id:P.id},n__default.default.createElement(f36Popover.Popover.Trigger,null,n__default.default.createElement("div",g(d({},xe),{className:m.combobox}),n__default.default.createElement(f36Forms.TextInput,g(d({className:m.inputField},w),{onFocus:t=>{c==null||c(t),F||k();},onBlur:L,id:i,isInvalid:ee,isDisabled:_,isRequired:te,isReadOnly:oe,ref:f36Core.mergeRefs(w.ref,re),testId:"cf-autocomplete-input",placeholder:se,onChange:t=>{w.onChange(t),ge(t);}})),n__default.default.createElement(f36Button.IconButton,g(d({},X),{ref:f36Core.mergeRefs(X.ref,pe),"aria-label":h?"Clear":"Show list",className:m.toggleButton,variant:"transparent",icon:h?n__default.default.createElement(f36Icons.CloseIcon,{variant:"muted"}):Y,onClick:()=>{h?y(""):k();},isDisabled:_,size:"small"})))),s.length>0||h.length>0||ne?n__default.default.createElement(f36Popover.Popover.Content,g(d({},P),{ref:f36Core.mergeRefs(P.ref,le),className:m.content,testId:"cf-autocomplete-container"}),v&&[...Array(3)].map((t,l)=>n__default.default.createElement("div",{key:l,className:emotion.cx(m.item,m.disabled)},n__default.default.createElement(Be,null))),!v&&fe&&n__default.default.createElement("div",{className:m.item},n__default.default.createElement(f36Typography.Subheading,{className:m.noMatchesTitle},ie)),!v&&A(x)&&s.map((t,l)=>{if(t.options.length<1)return;let ve=n__default.default.createElement("div",{key:l},n__default.default.createElement(f36Typography.SectionHeading,{key:l,"data-test-id":"cf-autocomplete-grouptitle",marginBottom:"none",className:m.groupTitle},t.groupTitle),n__default.default.createElement(C,{items:t.options,highlightedIndex:D,getItemProps:$,renderItem:O,inputValue:h,elementStartIndex:N}));return N+=t.options.length,ve}),!v&&!A(x)&&s.length>0&&n__default.default.createElement(C,{items:s,elementStartIndex:N,highlightedIndex:D,getItemProps:$,renderItem:O,inputValue:h})):n__default.default.createElement("div",g(d({},P),{className:emotion.cx(m.hidden)}))))}var Be=()=>n__default.default.createElement(f36Skeleton.Skeleton.Container,{svgHeight:16},n__default.default.createElement(f36Skeleton.Skeleton.BodyText,{numberOfLines:1}));function A(e,o){return e}var Oe=n__default.default.forwardRef(Re);
24
22
 
25
23
  exports.Autocomplete = Oe;
24
+ //# sourceMappingURL=out.js.map
26
25
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/Autocomplete.tsx","../src/AutocompleteItems.tsx","../src/Autocomplete.styles.ts"],"names":["React","useCallback","useState","cx","useCombobox","mergeRefs","IconButton","TextInput","CloseIcon","ChevronDownIcon","Skeleton","Popover","Subheading","SectionHeading","getStringMatch","Text","css","tokens","getAutocompleteStyles","listMaxHeight","AutocompleteItems","props","items","elementStartIndex","highlightedIndex","getItemProps","renderItem","inputValue","styles","item","index","itemIndex","itemProps","__spreadProps","__spreadValues","HighlightedItem","before","match","after","_Autocomplete","ref","id","className","clearAfterSelect","closeAfterSelect","defaultValue","selectedItem","onInputValueChange","onSelectItem","onFocus","onBlur","icon","itemToString","isInvalid","isDisabled","isRequired","isReadOnly","showEmptyList","noMatchesMessage","placeholder","inputRef","toggleRef","listRef","listWidth","isGrouped","isLoading","usePortal","testId","setInputValue","handleInputValueChange","value","handleNativeChangeEvent","event","flattenItems","isUsingGroups","acc","group","isShowingNoMatches","getComboboxProps","getInputProps","getMenuProps","getToggleButtonProps","isOpen","toggleMenu","type","_a","_labelledby","_inputId","inputProps","__objRest","comboboxProps","toggleProps","menuProps","e","_","ListItemLoadingState","render","Autocomplete"],"mappings":"qlBAAA,OAAOA,GAAS,eAAAC,EAAa,YAAAC,OAAgB,QAC7C,OAAS,MAAAC,MAAU,UACnB,OAAS,eAAAC,MAAmB,YAE5B,OACE,aAAAC,MAGK,uBACP,OAAS,cAAAC,OAAkB,yBAC3B,OAAS,aAAAC,OAAsC,wBAC/C,OAAS,aAAAC,GAAW,mBAAAC,OAAuB,wBAC3C,OAAS,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MAAOE,EACP,kBAAmBC,EACnB,iBAAkBC,EAClB,aAAcC,EACd,WAAYC,EACZ,WAAYC,EACd,CAEN,EAIA3B,EAAA,cAAC,MAAAiC,EAAAC,EAAA,GAAQ0D,GAAR,CAAmB,UAAWzF,EAAGyB,EAAO,MAAM,GAAG,CAEtD,CACF,CAEJ,CAEA,IAAMmE,GAAuB,IAEzB/F,EAAA,cAACU,EAAS,UAAT,CAAmB,UAAW,IAC7BV,EAAA,cAACU,EAAS,SAAT,CAAkB,cAAe,EAAG,CACvC,EAKJ,SAASgE,EACPV,EACA1C,EACuC,CACvC,OAAO0C,CACT,CAOO,IAAMiC,GAAejG,EAAM,WAAWuC,EAAa","sourcesContent":["import React, { useCallback, useState } from 'react';\nimport { cx } from 'emotion';\nimport { useCombobox } from 'downshift';\n\nimport {\n mergeRefs,\n type CommonProps,\n type ExpandProps,\n} from '@contentful/f36-core';\nimport { IconButton } from '@contentful/f36-button';\nimport { TextInput, type TextInputProps } from '@contentful/f36-forms';\nimport { CloseIcon, ChevronDownIcon } from '@contentful/f36-icons';\nimport { Skeleton } from '@contentful/f36-skeleton';\nimport { Popover } from '@contentful/f36-popover';\nimport { Subheading, SectionHeading } from '@contentful/f36-typography';\n\nimport { AutocompleteItems } from './AutocompleteItems';\nimport { getAutocompleteStyles } from './Autocomplete.styles';\n\nexport interface GenericGroupType<ItemType> {\n groupTitle: string;\n options: ItemType[];\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface AutocompleteProps<ItemType>\n extends CommonProps,\n Pick<\n TextInputProps,\n | 'isDisabled'\n | 'isInvalid'\n | 'isReadOnly'\n | 'isRequired'\n | 'id'\n | 'defaultValue'\n > {\n /**\n * It’s an array of data to be used as \"options\" by the autocomplete component.\n * This can either be a plain list of items or a list of groups of items.\n */\n items: ItemType[] | GenericGroupType<ItemType>[];\n\n /**\n * Set a custom icon for the text input\n */\n icon?: React.ReactElement;\n\n /**\n * Tells if the item is a object with groups\n */\n isGrouped?: boolean;\n\n /**\n * Function called whenever the input value changes\n */\n onInputValueChange?: (value: string) => void;\n /**\n * This is the function that will be called when the user selects one of the \"options\" in the list.\n * The component will pass the selected \"item\" as an argument to the function..\n */\n onSelectItem: (item: ItemType) => void;\n\n /**\n * Applying the selectedItem property turns autocomplete into a controlled component.\n * Can be used to display e.g. previously selected element. If it is an object the itemToString function will apply to it.\n */\n selectedItem?: ItemType;\n\n /**\n * This is the function that will be called for each \"item\" passed in the `items` prop.\n * It receives the \"item\" and \"inputValue\" as arguments and returns a ReactNode.\n * The inputValue is passed in case you want to highlight the match on the render.\n */\n renderItem?: (item: ItemType, inputValue: string) => React.ReactNode;\n /**\n * When using objects as `items`, we recommend passing a function that tells Downshift how to extract a string\n * from those objetcs to be used as inputValue\n */\n itemToString?: (item: ItemType) => string;\n /**\n * If this is set to `true` the text input will be cleared after an item is selected\n * @default false\n */\n clearAfterSelect?: boolean;\n /**\n * If this is set to `false` the dropdown menu will stay open after selecting an item\n * @default true\n */\n closeAfterSelect?: boolean;\n /**\n * This is the value will be passed to the `placeholder` prop of the input.\n * @default \"Search\"\n */\n placeholder?: string;\n /**\n * Defines if the list should be shown even if empty, when input is focused\n * @default false\n */\n showEmptyList?: boolean;\n /**\n * A message that will be shown when it is not possible to find any option that matches the input value\n * @default \"No matches\"\n */\n noMatchesMessage?: string;\n /**\n * Use this prop to get a ref to the input element of the component\n */\n inputRef?: React.Ref<HTMLInputElement>;\n /**\n * Use this prop to get a ref to the toggle button of the component\n */\n toggleRef?: React.Ref<HTMLButtonElement>;\n /**\n * Use this prop to get a ref to the list of items of the component\n */\n listRef?: React.Ref<HTMLUListElement>;\n /**\n * It sets the width of the list\n * @default \"auto\"\n */\n listWidth?: 'auto' | 'full';\n /**\n * It sets the max-height, in pixels, of the list\n * The default value is the height of 5 single line items\n * @default 180\n */\n listMaxHeight?: number;\n /**\n * Sets the list to show its loading state\n * @default false\n */\n isLoading?: boolean;\n /**\n * Boolean to control whether or not to render the suggestions box in a React Portal.\n * Rendering content inside a Portal allows the suggestions box to escape the bounds\n * of its parent while still being positioned correctly.\n * Defaults to `false`\n */\n usePortal?: boolean;\n\n /**\n * Function called when the input is focused\n *\n * @param event\n */\n onFocus?: (event: React.FocusEvent<HTMLInputElement>) => void;\n /**\n * Function called when the input is blurred\n * @param event\n */\n onBlur?: (event: React.FocusEvent<HTMLInputElement>) => void;\n}\n\nfunction _Autocomplete<ItemType>(\n props: AutocompleteProps<ItemType>,\n ref: React.Ref<HTMLDivElement>,\n) {\n const {\n id,\n className,\n clearAfterSelect = false,\n closeAfterSelect = true,\n defaultValue = '',\n selectedItem,\n items,\n onInputValueChange,\n onSelectItem,\n onFocus,\n onBlur,\n renderItem,\n icon = <ChevronDownIcon variant=\"muted\" />,\n itemToString = (item: ItemType) => item as unknown as string,\n isInvalid,\n isDisabled,\n isRequired,\n isReadOnly,\n showEmptyList,\n noMatchesMessage = 'No matches found',\n placeholder = 'Search',\n inputRef,\n toggleRef,\n listRef,\n listWidth = 'auto',\n listMaxHeight = 180,\n isGrouped = false,\n isLoading = false,\n usePortal = false,\n testId = 'cf-autocomplete',\n } = props;\n\n type GroupType = GenericGroupType<ItemType>;\n\n const styles = getAutocompleteStyles(listMaxHeight);\n\n const [inputValue, setInputValue] = useState(defaultValue);\n\n const handleInputValueChange = useCallback(\n (value: string) => {\n setInputValue(value);\n\n onInputValueChange?.(value);\n },\n [onInputValueChange],\n );\n\n // Handle manually to avoid a jumping cursor, see https://github.com/downshift-js/downshift/issues/1108#issuecomment-842407759\n const handleNativeChangeEvent = useCallback(\n (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {\n const value = event.target.value;\n handleInputValueChange(value);\n },\n [handleInputValueChange],\n );\n\n const flattenItems = isUsingGroups(isGrouped, items)\n ? items.reduce(\n (acc: ItemType[], group: GroupType) => [...acc, ...group.options],\n [],\n )\n : items;\n\n const isShowingNoMatches = isUsingGroups(isGrouped, items)\n ? items.every((group: GroupType) => group.options.length === 0)\n : items.length === 0;\n\n const {\n getComboboxProps,\n getInputProps,\n getItemProps,\n getMenuProps,\n getToggleButtonProps,\n highlightedIndex,\n isOpen,\n toggleMenu,\n } = useCombobox({\n items: flattenItems,\n selectedItem,\n inputValue,\n itemToString,\n onInputValueChange: ({ type, inputValue }) => {\n if (type !== '__input_change__') {\n handleInputValueChange(inputValue);\n }\n },\n onStateChange: ({ type, selectedItem }) => {\n switch (type) {\n case useCombobox.stateChangeTypes.InputKeyDownEnter:\n case useCombobox.stateChangeTypes.ItemClick:\n if (selectedItem) {\n onSelectItem(selectedItem);\n }\n if (clearAfterSelect) {\n handleInputValueChange('');\n }\n if (!closeAfterSelect) {\n toggleMenu();\n }\n break;\n default:\n break;\n }\n },\n });\n\n const {\n 'aria-labelledby': _labelledby,\n id: _inputId,\n ...inputProps\n } = getInputProps();\n const comboboxProps = getComboboxProps();\n const toggleProps = getToggleButtonProps();\n const menuProps = getMenuProps();\n let elementStartIndex = 0;\n\n return (\n <div\n data-test-id={testId}\n className={cx(styles.autocomplete, className)}\n ref={ref}\n >\n <Popover\n usePortal={usePortal}\n isOpen={isOpen}\n isFullWidth={listWidth === 'full'}\n renderOnlyWhenOpen={false}\n // This is necessary, otherwise the focus will change from the input to the Popover\n // and the user won't be able to type in the input\n // eslint-disable-next-line jsx-a11y/no-autofocus\n autoFocus={false}\n id={menuProps.id}\n >\n <Popover.Trigger>\n <div {...comboboxProps} className={styles.combobox}>\n <TextInput\n className={styles.inputField}\n {...inputProps}\n onFocus={(e) => {\n onFocus?.(e as React.FocusEvent<HTMLInputElement>);\n if (!isOpen) {\n toggleMenu();\n }\n }}\n onBlur={onBlur}\n id={id}\n isInvalid={isInvalid}\n isDisabled={isDisabled}\n isRequired={isRequired}\n isReadOnly={isReadOnly}\n ref={mergeRefs(inputProps.ref, inputRef)}\n testId=\"cf-autocomplete-input\"\n placeholder={placeholder}\n onChange={(event) => {\n inputProps.onChange(event);\n handleNativeChangeEvent(event);\n }}\n />\n <IconButton\n {...toggleProps}\n ref={mergeRefs(toggleProps.ref, toggleRef)}\n aria-label={inputValue ? 'Clear' : 'Show list'}\n className={styles.toggleButton}\n variant=\"transparent\"\n icon={inputValue ? <CloseIcon variant=\"muted\" /> : icon}\n onClick={() => {\n if (inputValue) {\n handleInputValueChange('');\n } else {\n toggleMenu();\n }\n }}\n isDisabled={isDisabled}\n size=\"small\"\n />\n </div>\n </Popover.Trigger>\n\n {items.length > 0 || inputValue.length > 0 || showEmptyList ? (\n <Popover.Content\n {...menuProps}\n ref={mergeRefs(menuProps.ref, listRef)}\n className={styles.content}\n testId=\"cf-autocomplete-container\"\n >\n {isLoading &&\n [...Array(3)].map((_, index) => (\n <div key={index} className={cx(styles.item, styles.disabled)}>\n <ListItemLoadingState />\n </div>\n ))}\n\n {!isLoading && isShowingNoMatches && (\n <div className={styles.item}>\n <Subheading className={styles.noMatchesTitle}>\n {noMatchesMessage}\n </Subheading>\n </div>\n )}\n\n {!isLoading &&\n isUsingGroups(isGrouped, items) &&\n items.map((group: GroupType, index: number) => {\n if (group.options.length < 1) {\n return;\n }\n const render = (\n <div key={index}>\n <SectionHeading\n key={index}\n data-test-id=\"cf-autocomplete-grouptitle\"\n marginBottom=\"none\"\n className={styles.groupTitle}\n >\n {group.groupTitle}\n </SectionHeading>\n <AutocompleteItems<ItemType>\n items={group.options}\n highlightedIndex={highlightedIndex}\n getItemProps={getItemProps}\n renderItem={renderItem}\n inputValue={inputValue}\n elementStartIndex={elementStartIndex}\n />\n </div>\n );\n elementStartIndex += group.options.length;\n return render;\n })}\n\n {!isLoading &&\n !isUsingGroups(isGrouped, items) &&\n items.length > 0 && (\n <AutocompleteItems<ItemType>\n items={items}\n elementStartIndex={elementStartIndex}\n highlightedIndex={highlightedIndex}\n getItemProps={getItemProps}\n renderItem={renderItem}\n inputValue={inputValue}\n />\n )}\n </Popover.Content>\n ) : (\n // We need to render an empty hidden div, so we can pass the menuProps or downshift will show a warning about it\n // https://github.com/downshift-js/downshift/issues/1167#issuecomment-1088022842\n <div {...menuProps} className={cx(styles.hidden)} />\n )}\n </Popover>\n </div>\n );\n}\n\nconst ListItemLoadingState = () => {\n return (\n <Skeleton.Container svgHeight={16}>\n <Skeleton.BodyText numberOfLines={1} />\n </Skeleton.Container>\n );\n};\n\n// This is required to infer correct typings when differentiating groups and items\nfunction isUsingGroups<ItemType>(\n isGrouped: boolean,\n items: ItemType[] | GenericGroupType<ItemType>[],\n): items is GenericGroupType<ItemType>[] {\n return isGrouped;\n}\n\n/**\n * The Autocomplete is a component that will show a `TextInput` where a user can type any word which will be used\n * to filter a list of items. That list of filtered items will be shown to the user as possible options for the input.\n * Once one of the options is selected, that option becomes the value of the `TextInput`.\n */\nexport const Autocomplete = React.forwardRef(_Autocomplete) as <T>(\n props: ExpandProps<AutocompleteProps<T>> & {\n ref?: React.Ref<HTMLDivElement>;\n },\n) => ReturnType<typeof _Autocomplete>;\n","import React, { HTMLAttributes } from 'react';\nimport { cx } from 'emotion';\nimport { getStringMatch } from '@contentful/f36-utils';\nimport type { UseComboboxGetItemPropsOptions } from 'downshift';\nimport { Text } from '@contentful/f36-typography';\n\nimport { getAutocompleteStyles } from './Autocomplete.styles';\n\ninterface AutocompleteItemsProps<ItemType> {\n items: ItemType[];\n elementStartIndex: number;\n highlightedIndex: number;\n getItemProps: (\n options: UseComboboxGetItemPropsOptions<ItemType>,\n ) => HTMLAttributes<HTMLLIElement>;\n renderItem: (item: ItemType, inputValue: string) => React.ReactNode;\n inputValue: string;\n listMaxHeight?: number;\n}\n\nexport const AutocompleteItems = <ItemType,>(\n props: AutocompleteItemsProps<ItemType>,\n) => {\n const {\n items,\n elementStartIndex,\n highlightedIndex,\n getItemProps,\n renderItem,\n inputValue,\n listMaxHeight = 180,\n } = props;\n\n const styles = getAutocompleteStyles(listMaxHeight);\n\n return (\n <ul className={styles.list} data-test-id=\"cf-autocomplete-list\">\n {items.map((item: ItemType, index: number) => {\n const itemIndex = elementStartIndex + index;\n const itemProps = getItemProps({ item, index: itemIndex });\n return (\n <Text\n {...itemProps}\n as=\"li\"\n key={itemIndex}\n className={cx([\n styles.item,\n highlightedIndex === itemIndex && styles.highlighted,\n ])}\n data-test-id={`cf-autocomplete-list-item-${itemIndex}`}\n >\n {renderItem ? (\n renderItem(item, inputValue)\n ) : typeof item === 'string' ? (\n <HighlightedItem item={item} inputValue={inputValue} />\n ) : (\n item\n )}\n </Text>\n );\n })}\n </ul>\n );\n};\n\nAutocompleteItems.displayName = 'AutocompleteItems';\n\nfunction HighlightedItem({\n item,\n inputValue,\n}: {\n item: string;\n inputValue: string;\n}) {\n const { before, match, after } = getStringMatch(item, inputValue);\n\n return (\n <>\n {before}\n <b>{match}</b>\n {after}\n </>\n );\n}\n\nHighlightedItem.displayName = 'HighlightedItem';\n","import { css } from 'emotion';\nimport tokens from '@contentful/f36-tokens';\n\nexport const getAutocompleteStyles = (listMaxHeight: number) => ({\n autocomplete: css({\n position: 'relative',\n width: '100%',\n }),\n combobox: css({\n position: 'relative',\n }),\n inputField: css({\n paddingRight: tokens.spacingXl,\n textOverflow: 'ellipsis',\n whiteSpace: 'nowrap',\n }),\n toggleButton: css({\n position: 'absolute',\n top: '1px',\n right: '1px',\n zIndex: 1,\n padding: tokens.spacing2Xs,\n height: '38px',\n }),\n content: css({\n overflow: 'auto',\n maxHeight: `${listMaxHeight}px`,\n }),\n list: css({\n listStyle: 'none',\n padding: `${tokens.spacingXs} 0`,\n margin: 0,\n }),\n groupTitle: css({\n padding: `${tokens.spacingXs} ${tokens.spacingM}`,\n lineHeight: tokens.lineHeightM,\n }),\n noMatchesTitle: css({\n color: tokens.gray500,\n margin: `${tokens.spacingM} 0 ${tokens.spacingM} 0`,\n }),\n item: css({\n display: 'block',\n padding: `${tokens.spacingXs} ${tokens.spacingM}`,\n wordBreak: 'break-word',\n whiteSpace: 'break-spaces',\n cursor: 'pointer',\n hyphens: 'auto',\n\n '&:focus, &:hover': {\n backgroundColor: tokens.gray100,\n },\n '&:active': {\n backgroundColor: tokens.gray200,\n },\n }),\n disabled: css({\n opacity: 0.5,\n pointerEvents: 'none',\n }),\n highlighted: css({\n backgroundColor: tokens.gray100,\n }),\n hidden: css({\n display: 'none',\n }),\n});\n"]}
1
+ {"version":3,"sources":["../src/Autocomplete.tsx","../src/AutocompleteItems.tsx","../src/Autocomplete.styles.ts"],"names":["React","useCallback","useState","cx","useCombobox","mergeRefs","IconButton","TextInput","CloseIcon","ChevronDownIcon","Skeleton","Popover","Subheading","SectionHeading","getStringMatch","Text","css","tokens","getAutocompleteStyles","listMaxHeight","AutocompleteItems","props","items","elementStartIndex","highlightedIndex","getItemProps","renderItem","inputValue","styles","item","index","itemIndex","itemProps","__spreadProps","__spreadValues","HighlightedItem","before","match","after","_Autocomplete","ref","id","className","clearAfterSelect","closeAfterSelect","defaultValue","selectedItem","onInputValueChange","onSelectItem","onFocus","onBlur","icon","itemToString","isInvalid","isDisabled","isRequired","isReadOnly","showEmptyList","noMatchesMessage","placeholder","inputRef","toggleRef","listRef","listWidth","isGrouped","isLoading","usePortal","testId","setInputValue","handleInputValueChange","value","handleNativeChangeEvent","event","flattenItems","isUsingGroups","acc","group","isShowingNoMatches","getComboboxProps","getInputProps","getMenuProps","getToggleButtonProps","isOpen","toggleMenu","type","_a","_labelledby","_inputId","inputProps","__objRest","comboboxProps","toggleProps","menuProps","e","_","ListItemLoadingState","render","Autocomplete"],"mappings":"qlBAAA,OAAOA,GAAS,eAAAC,EAAa,YAAAC,OAAgB,QAC7C,OAAS,MAAAC,MAAU,UACnB,OAAS,eAAAC,MAAmB,YAE5B,OACE,aAAAC,MAGK,uBACP,OAAS,cAAAC,OAAkB,yBAC3B,OAAS,aAAAC,OAAsC,wBAC/C,OAAS,aAAAC,GAAW,mBAAAC,OAAuB,wBAC3C,OAAS,YAAAC,MAAgB,2BACzB,OAAS,WAAAC,MAAe,0BACxB,OAAS,cAAAC,GAAY,kBAAAC,OAAsB,6BCd3C,OAAOb,MAA+B,QACtC,OAAS,MAAAG,OAAU,UACnB,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C,EACd,CAEN,EAIA3B,EAAA,cAAC,MAAAiC,EAAAC,EAAA,GAAQ0D,GAAR,CAAmB,UAAWzF,EAAGyB,EAAO,MAAM,GAAG,CAEtD,CACF,CAEJ,CAEA,IAAMmE,GAAuB,IAEzB/F,EAAA,cAACU,EAAS,UAAT,CAAmB,UAAW,IAC7BV,EAAA,cAACU,EAAS,SAAT,CAAkB,cAAe,EAAG,CACvC,EAKJ,SAASgE,EACPV,EACA1C,EACuC,CACvC,OAAO0C,CACT,CAOO,IAAMiC,GAAejG,EAAM,WAAWuC,EAAa","sourcesContent":["import React, { useCallback, useState } from 'react';\nimport { cx } from 'emotion';\nimport { useCombobox } from 'downshift';\n\nimport {\n mergeRefs,\n type CommonProps,\n type ExpandProps,\n} from '@contentful/f36-core';\nimport { IconButton } from '@contentful/f36-button';\nimport { TextInput, type TextInputProps } from '@contentful/f36-forms';\nimport { CloseIcon, ChevronDownIcon } from '@contentful/f36-icons';\nimport { Skeleton } from '@contentful/f36-skeleton';\nimport { Popover } from '@contentful/f36-popover';\nimport { Subheading, SectionHeading } from '@contentful/f36-typography';\n\nimport { AutocompleteItems } from './AutocompleteItems';\nimport { getAutocompleteStyles } from './Autocomplete.styles';\n\nexport interface GenericGroupType<ItemType> {\n groupTitle: string;\n options: ItemType[];\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface AutocompleteProps<ItemType>\n extends CommonProps,\n Pick<\n TextInputProps,\n | 'isDisabled'\n | 'isInvalid'\n | 'isReadOnly'\n | 'isRequired'\n | 'id'\n | 'defaultValue'\n > {\n /**\n * It’s an array of data to be used as \"options\" by the autocomplete component.\n * This can either be a plain list of items or a list of groups of items.\n */\n items: ItemType[] | GenericGroupType<ItemType>[];\n\n /**\n * Set a custom icon for the text input\n */\n icon?: React.ReactElement;\n\n /**\n * Tells if the item is a object with groups\n */\n isGrouped?: boolean;\n\n /**\n * Function called whenever the input value changes\n */\n onInputValueChange?: (value: string) => void;\n /**\n * This is the function that will be called when the user selects one of the \"options\" in the list.\n * The component will pass the selected \"item\" as an argument to the function..\n */\n onSelectItem: (item: ItemType) => void;\n\n /**\n * Applying the selectedItem property turns autocomplete into a controlled component.\n * Can be used to display e.g. previously selected element. If it is an object the itemToString function will apply to it.\n */\n selectedItem?: ItemType;\n\n /**\n * This is the function that will be called for each \"item\" passed in the `items` prop.\n * It receives the \"item\" and \"inputValue\" as arguments and returns a ReactNode.\n * The inputValue is passed in case you want to highlight the match on the render.\n */\n renderItem?: (item: ItemType, inputValue: string) => React.ReactNode;\n /**\n * When using objects as `items`, we recommend passing a function that tells Downshift how to extract a string\n * from those objetcs to be used as inputValue\n */\n itemToString?: (item: ItemType) => string;\n /**\n * If this is set to `true` the text input will be cleared after an item is selected\n * @default false\n */\n clearAfterSelect?: boolean;\n /**\n * If this is set to `false` the dropdown menu will stay open after selecting an item\n * @default true\n */\n closeAfterSelect?: boolean;\n /**\n * This is the value will be passed to the `placeholder` prop of the input.\n * @default \"Search\"\n */\n placeholder?: string;\n /**\n * Defines if the list should be shown even if empty, when input is focused\n * @default false\n */\n showEmptyList?: boolean;\n /**\n * A message that will be shown when it is not possible to find any option that matches the input value\n * @default \"No matches\"\n */\n noMatchesMessage?: string;\n /**\n * Use this prop to get a ref to the input element of the component\n */\n inputRef?: React.Ref<HTMLInputElement>;\n /**\n * Use this prop to get a ref to the toggle button of the component\n */\n toggleRef?: React.Ref<HTMLButtonElement>;\n /**\n * Use this prop to get a ref to the list of items of the component\n */\n listRef?: React.Ref<HTMLUListElement>;\n /**\n * It sets the width of the list\n * @default \"auto\"\n */\n listWidth?: 'auto' | 'full';\n /**\n * It sets the max-height, in pixels, of the list\n * The default value is the height of 5 single line items\n * @default 180\n */\n listMaxHeight?: number;\n /**\n * Sets the list to show its loading state\n * @default false\n */\n isLoading?: boolean;\n /**\n * Boolean to control whether or not to render the suggestions box in a React Portal.\n * Rendering content inside a Portal allows the suggestions box to escape the bounds\n * of its parent while still being positioned correctly.\n * Defaults to `false`\n */\n usePortal?: boolean;\n\n /**\n * Function called when the input is focused\n *\n * @param event\n */\n onFocus?: (event: React.FocusEvent<HTMLInputElement>) => void;\n /**\n * Function called when the input is blurred\n * @param event\n */\n onBlur?: (event: React.FocusEvent<HTMLInputElement>) => void;\n}\n\nfunction _Autocomplete<ItemType>(\n props: AutocompleteProps<ItemType>,\n ref: React.Ref<HTMLDivElement>,\n) {\n const {\n id,\n className,\n clearAfterSelect = false,\n closeAfterSelect = true,\n defaultValue = '',\n selectedItem,\n items,\n onInputValueChange,\n onSelectItem,\n onFocus,\n onBlur,\n renderItem,\n icon = <ChevronDownIcon variant=\"muted\" />,\n itemToString = (item: ItemType) => item as unknown as string,\n isInvalid,\n isDisabled,\n isRequired,\n isReadOnly,\n showEmptyList,\n noMatchesMessage = 'No matches found',\n placeholder = 'Search',\n inputRef,\n toggleRef,\n listRef,\n listWidth = 'auto',\n listMaxHeight = 180,\n isGrouped = false,\n isLoading = false,\n usePortal = false,\n testId = 'cf-autocomplete',\n } = props;\n\n type GroupType = GenericGroupType<ItemType>;\n\n const styles = getAutocompleteStyles(listMaxHeight);\n\n const [inputValue, setInputValue] = useState(defaultValue);\n\n const handleInputValueChange = useCallback(\n (value: string) => {\n setInputValue(value);\n\n onInputValueChange?.(value);\n },\n [onInputValueChange],\n );\n\n // Handle manually to avoid a jumping cursor, see https://github.com/downshift-js/downshift/issues/1108#issuecomment-842407759\n const handleNativeChangeEvent = useCallback(\n (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {\n const value = event.target.value;\n handleInputValueChange(value);\n },\n [handleInputValueChange],\n );\n\n const flattenItems = isUsingGroups(isGrouped, items)\n ? items.reduce(\n (acc: ItemType[], group: GroupType) => [...acc, ...group.options],\n [],\n )\n : items;\n\n const isShowingNoMatches = isUsingGroups(isGrouped, items)\n ? items.every((group: GroupType) => group.options.length === 0)\n : items.length === 0;\n\n const {\n getComboboxProps,\n getInputProps,\n getItemProps,\n getMenuProps,\n getToggleButtonProps,\n highlightedIndex,\n isOpen,\n toggleMenu,\n } = useCombobox({\n items: flattenItems,\n selectedItem,\n inputValue,\n itemToString,\n onInputValueChange: ({ type, inputValue }) => {\n if (type !== '__input_change__') {\n handleInputValueChange(inputValue);\n }\n },\n onStateChange: ({ type, selectedItem }) => {\n switch (type) {\n case useCombobox.stateChangeTypes.InputKeyDownEnter:\n case useCombobox.stateChangeTypes.ItemClick:\n if (selectedItem) {\n onSelectItem(selectedItem);\n }\n if (clearAfterSelect) {\n handleInputValueChange('');\n }\n if (!closeAfterSelect) {\n toggleMenu();\n }\n break;\n default:\n break;\n }\n },\n });\n\n const {\n 'aria-labelledby': _labelledby,\n id: _inputId,\n ...inputProps\n } = getInputProps();\n const comboboxProps = getComboboxProps();\n const toggleProps = getToggleButtonProps();\n const menuProps = getMenuProps();\n let elementStartIndex = 0;\n\n return (\n <div\n data-test-id={testId}\n className={cx(styles.autocomplete, className)}\n ref={ref}\n >\n <Popover\n usePortal={usePortal}\n isOpen={isOpen}\n isFullWidth={listWidth === 'full'}\n renderOnlyWhenOpen={false}\n // This is necessary, otherwise the focus will change from the input to the Popover\n // and the user won't be able to type in the input\n // eslint-disable-next-line jsx-a11y/no-autofocus\n autoFocus={false}\n id={menuProps.id}\n >\n <Popover.Trigger>\n <div {...comboboxProps} className={styles.combobox}>\n <TextInput\n className={styles.inputField}\n {...inputProps}\n onFocus={(e) => {\n onFocus?.(e as React.FocusEvent<HTMLInputElement>);\n if (!isOpen) {\n toggleMenu();\n }\n }}\n onBlur={onBlur}\n id={id}\n isInvalid={isInvalid}\n isDisabled={isDisabled}\n isRequired={isRequired}\n isReadOnly={isReadOnly}\n ref={mergeRefs(inputProps.ref, inputRef)}\n testId=\"cf-autocomplete-input\"\n placeholder={placeholder}\n onChange={(event) => {\n inputProps.onChange(event);\n handleNativeChangeEvent(event);\n }}\n />\n <IconButton\n {...toggleProps}\n ref={mergeRefs(toggleProps.ref, toggleRef)}\n aria-label={inputValue ? 'Clear' : 'Show list'}\n className={styles.toggleButton}\n variant=\"transparent\"\n icon={inputValue ? <CloseIcon variant=\"muted\" /> : icon}\n onClick={() => {\n if (inputValue) {\n handleInputValueChange('');\n } else {\n toggleMenu();\n }\n }}\n isDisabled={isDisabled}\n size=\"small\"\n />\n </div>\n </Popover.Trigger>\n\n {items.length > 0 || inputValue.length > 0 || showEmptyList ? (\n <Popover.Content\n {...menuProps}\n ref={mergeRefs(menuProps.ref, listRef)}\n className={styles.content}\n testId=\"cf-autocomplete-container\"\n >\n {isLoading &&\n [...Array(3)].map((_, index) => (\n <div key={index} className={cx(styles.item, styles.disabled)}>\n <ListItemLoadingState />\n </div>\n ))}\n\n {!isLoading && isShowingNoMatches && (\n <div className={styles.item}>\n <Subheading className={styles.noMatchesTitle}>\n {noMatchesMessage}\n </Subheading>\n </div>\n )}\n\n {!isLoading &&\n isUsingGroups(isGrouped, items) &&\n items.map((group: GroupType, index: number) => {\n if (group.options.length < 1) {\n return;\n }\n const render = (\n <div key={index}>\n <SectionHeading\n key={index}\n data-test-id=\"cf-autocomplete-grouptitle\"\n marginBottom=\"none\"\n className={styles.groupTitle}\n >\n {group.groupTitle}\n </SectionHeading>\n <AutocompleteItems<ItemType>\n items={group.options}\n highlightedIndex={highlightedIndex}\n getItemProps={getItemProps}\n renderItem={renderItem}\n inputValue={inputValue}\n elementStartIndex={elementStartIndex}\n />\n </div>\n );\n elementStartIndex += group.options.length;\n return render;\n })}\n\n {!isLoading &&\n !isUsingGroups(isGrouped, items) &&\n items.length > 0 && (\n <AutocompleteItems<ItemType>\n items={items}\n elementStartIndex={elementStartIndex}\n highlightedIndex={highlightedIndex}\n getItemProps={getItemProps}\n renderItem={renderItem}\n inputValue={inputValue}\n />\n )}\n </Popover.Content>\n ) : (\n // We need to render an empty hidden div, so we can pass the menuProps or downshift will show a warning about it\n // https://github.com/downshift-js/downshift/issues/1167#issuecomment-1088022842\n <div {...menuProps} className={cx(styles.hidden)} />\n )}\n </Popover>\n </div>\n );\n}\n\nconst ListItemLoadingState = () => {\n return (\n <Skeleton.Container svgHeight={16}>\n <Skeleton.BodyText numberOfLines={1} />\n </Skeleton.Container>\n );\n};\n\n// This is required to infer correct typings when differentiating groups and items\nfunction isUsingGroups<ItemType>(\n isGrouped: boolean,\n items: ItemType[] | GenericGroupType<ItemType>[],\n): items is GenericGroupType<ItemType>[] {\n return isGrouped;\n}\n\n/**\n * The Autocomplete is a component that will show a `TextInput` where a user can type any word which will be used\n * to filter a list of items. That list of filtered items will be shown to the user as possible options for the input.\n * Once one of the options is selected, that option becomes the value of the `TextInput`.\n */\nexport const Autocomplete = React.forwardRef(_Autocomplete) as <T>(\n props: ExpandProps<AutocompleteProps<T>> & {\n ref?: React.Ref<HTMLDivElement>;\n },\n) => ReturnType<typeof _Autocomplete>;\n","import React, { HTMLAttributes } from 'react';\nimport { cx } from 'emotion';\nimport { getStringMatch } from '@contentful/f36-utils';\nimport type { UseComboboxGetItemPropsOptions } from 'downshift';\nimport { Text } from '@contentful/f36-typography';\n\nimport { getAutocompleteStyles } from './Autocomplete.styles';\n\ninterface AutocompleteItemsProps<ItemType> {\n items: ItemType[];\n elementStartIndex: number;\n highlightedIndex: number;\n getItemProps: (\n options: UseComboboxGetItemPropsOptions<ItemType>,\n ) => HTMLAttributes<HTMLLIElement>;\n renderItem: (item: ItemType, inputValue: string) => React.ReactNode;\n inputValue: string;\n listMaxHeight?: number;\n}\n\nexport const AutocompleteItems = <ItemType,>(\n props: AutocompleteItemsProps<ItemType>,\n) => {\n const {\n items,\n elementStartIndex,\n highlightedIndex,\n getItemProps,\n renderItem,\n inputValue,\n listMaxHeight = 180,\n } = props;\n\n const styles = getAutocompleteStyles(listMaxHeight);\n\n return (\n <ul className={styles.list} data-test-id=\"cf-autocomplete-list\">\n {items.map((item: ItemType, index: number) => {\n const itemIndex = elementStartIndex + index;\n const itemProps = getItemProps({ item, index: itemIndex });\n return (\n <Text\n {...itemProps}\n as=\"li\"\n key={itemIndex}\n className={cx([\n styles.item,\n highlightedIndex === itemIndex && styles.highlighted,\n ])}\n data-test-id={`cf-autocomplete-list-item-${itemIndex}`}\n >\n {renderItem ? (\n renderItem(item, inputValue)\n ) : typeof item === 'string' ? (\n <HighlightedItem item={item} inputValue={inputValue} />\n ) : (\n item\n )}\n </Text>\n );\n })}\n </ul>\n );\n};\n\nAutocompleteItems.displayName = 'AutocompleteItems';\n\nfunction HighlightedItem({\n item,\n inputValue,\n}: {\n item: string;\n inputValue: string;\n}) {\n const { before, match, after } = getStringMatch(item, inputValue);\n\n return (\n <>\n {before}\n <b>{match}</b>\n {after}\n </>\n );\n}\n\nHighlightedItem.displayName = 'HighlightedItem';\n","import { css } from 'emotion';\nimport tokens from '@contentful/f36-tokens';\n\nexport const getAutocompleteStyles = (listMaxHeight: number) => ({\n autocomplete: css({\n position: 'relative',\n width: '100%',\n }),\n combobox: css({\n position: 'relative',\n }),\n inputField: css({\n paddingRight: tokens.spacingXl,\n textOverflow: 'ellipsis',\n whiteSpace: 'nowrap',\n }),\n toggleButton: css({\n position: 'absolute',\n top: '1px',\n right: '1px',\n zIndex: 1,\n padding: tokens.spacing2Xs,\n height: '38px',\n }),\n content: css({\n overflow: 'auto',\n maxHeight: `${listMaxHeight}px`,\n }),\n list: css({\n listStyle: 'none',\n padding: `${tokens.spacingXs} 0`,\n margin: 0,\n }),\n groupTitle: css({\n padding: `${tokens.spacingXs} ${tokens.spacingM}`,\n lineHeight: tokens.lineHeightM,\n }),\n noMatchesTitle: css({\n color: tokens.gray500,\n margin: `${tokens.spacingM} 0 ${tokens.spacingM} 0`,\n }),\n item: css({\n display: 'block',\n padding: `${tokens.spacingXs} ${tokens.spacingM}`,\n wordBreak: 'break-word',\n whiteSpace: 'break-spaces',\n cursor: 'pointer',\n hyphens: 'auto',\n\n '&:focus, &:hover': {\n backgroundColor: tokens.gray100,\n },\n '&:active': {\n backgroundColor: tokens.gray200,\n },\n }),\n disabled: css({\n opacity: 0.5,\n pointerEvents: 'none',\n }),\n highlighted: css({\n backgroundColor: tokens.gray100,\n }),\n hidden: css({\n display: 'none',\n }),\n});\n"]}
package/package.json CHANGED
@@ -1,19 +1,19 @@
1
1
  {
2
2
  "name": "@contentful/f36-autocomplete",
3
- "version": "4.48.0",
3
+ "version": "4.48.1",
4
4
  "description": "Forma 36: Autocomplete component",
5
5
  "scripts": {
6
6
  "build": "tsup"
7
7
  },
8
8
  "dependencies": {
9
- "@contentful/f36-button": "^4.48.0",
10
- "@contentful/f36-core": "^4.48.0",
11
- "@contentful/f36-forms": "^4.48.0",
9
+ "@contentful/f36-button": "^4.48.1",
10
+ "@contentful/f36-core": "^4.48.1",
11
+ "@contentful/f36-forms": "^4.48.1",
12
12
  "@contentful/f36-icons": "^4.27.0",
13
- "@contentful/f36-popover": "^4.48.0",
14
- "@contentful/f36-skeleton": "^4.48.0",
13
+ "@contentful/f36-popover": "^4.48.1",
14
+ "@contentful/f36-skeleton": "^4.48.1",
15
15
  "@contentful/f36-tokens": "^4.0.2",
16
- "@contentful/f36-typography": "^4.48.0",
16
+ "@contentful/f36-typography": "^4.48.1",
17
17
  "@contentful/f36-utils": "^4.23.2",
18
18
  "downshift": "^6.1.12",
19
19
  "emotion": "^10.0.17"