@lifesg/react-design-system 3.5.0-canary.2 → 3.5.0-canary.3
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/cjs/data-table/data-table.js +1 -1
- package/cjs/data-table/data-table.js.map +1 -1
- package/cjs/data-table/data-table.styles.js +61 -52
- package/cjs/data-table/data-table.styles.js.map +1 -1
- package/cjs/external/dompurify/dist/purify.es.js +2 -2
- package/cjs/external/dompurify/dist/purify.es.js.map +1 -1
- package/cjs/predictive-text-input/predictive-text-input.js +1 -1
- package/cjs/predictive-text-input/predictive-text-input.js.map +1 -1
- package/cjs/shared/dropdown-wrapper/element-with-dropdown.js +1 -1
- package/cjs/shared/dropdown-wrapper/element-with-dropdown.js.map +1 -1
- package/cjs/table/table.styles.js +4 -6
- package/cjs/table/table.styles.js.map +1 -1
- package/cjs/util/use-throttle.js +2 -0
- package/cjs/util/use-throttle.js.map +1 -0
- package/data-table/data-table.js +1 -1
- package/data-table/data-table.js.map +1 -1
- package/data-table/data-table.styles.d.ts +11 -11
- package/data-table/data-table.styles.js +73 -64
- package/data-table/data-table.styles.js.map +1 -1
- package/external/dompurify/dist/purify.es.js +2 -2
- package/external/dompurify/dist/purify.es.js.map +1 -1
- package/package.json +1 -1
- package/predictive-text-input/predictive-text-input.js +1 -1
- package/predictive-text-input/predictive-text-input.js.map +1 -1
- package/shared/dropdown-wrapper/element-with-dropdown.d.ts +5 -4
- package/shared/dropdown-wrapper/element-with-dropdown.js +1 -1
- package/shared/dropdown-wrapper/element-with-dropdown.js.map +1 -1
- package/table/table.styles.js +10 -12
- package/table/table.styles.js.map +1 -1
- package/util/index.d.ts +1 -0
- package/util/use-throttle.d.ts +1 -0
- package/util/use-throttle.js +2 -0
- package/util/use-throttle.js.map +1 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var e=require("../_virtual/_tslib.js"),r=require("react/jsx-runtime"),t=require("../external/lodash/debounce.js"),s=require("react"),
|
|
1
|
+
"use strict";var e=require("../_virtual/_tslib.js"),r=require("react/jsx-runtime"),t=require("../external/lodash/debounce.js"),s=require("react"),i=require("../shared/accessibility/index.js"),a=require("../input/input.js");require("styled-components"),require("../theme/index.js"),require("../util/string-helper.js"),require("../shared/dropdown-list/dropdown-label.styles.js");var o=require("../shared/dropdown-list/dropdown-list.js"),l=require("../shared/dropdown-list/dropdown-list-state.js");require("../shared/dropdown-list/expandable-element.js"),require("@lifesg/react-icons/caret-right"),require("react-virtuoso"),require("../button/button.style.js"),require("../util/calendar-helper.js"),require("../util/date-helper.js"),require("../util/date-input-helper.js");var n=require("../util/simple-id-generator.js");require("@react-aria/live-announcer");var d=require("../shared/dropdown-wrapper/element-with-dropdown.js");require("../shared/dropdown-list/dropdown-list.styles.js"),require("../shared/dropdown-list/dropdown-search.js"),require("immer"),require("../external/lodash/_getTag.js"),require("../external/lodash/isArguments.js"),require("../external/lodash/_baseGetTag.js"),require("../external/lodash/isBuffer.js"),require("../external/lodash/isTypedArray.js"),require("../external/lodash/_Stack.js"),require("../external/lodash/_SetCache.js"),require("../external/lodash/_equalByTag.js"),require("../shared/dropdown-list/nested-dropdown-list.styles.js"),require("../shared/dropdown-list/virtuoso-components.js");var u=require("../shared/input-wrapper/input-wrapper.js");exports.PredictiveTextInput=c=>{var{className:p,"data-testid":h,selectedOption:x,minimumCharacters:j=3,fetchOptions:m,placeholder:f="Enter here...",readOnly:q=!1,disabled:g=!1,error:w,valueExtractor:v,listExtractor:b,displayValueExtractor:y,onSelectOption:S,alignment:E,dropdownZIndex:T,dropdownRootNode:I,dropdownWidth:O,"aria-describedby":_}=c,C=e.__rest(c,["className","data-testid","selectedOption","minimumCharacters","fetchOptions","placeholder","readOnly","disabled","error","valueExtractor","listExtractor","displayValueExtractor","onSelectOption","alignment","dropdownZIndex","dropdownRootNode","dropdownWidth","aria-describedby"]);const D=e=>e?y?y(e):e.toString():"",[N,$]=s.useState((()=>x?D(x):"")),[R,L]=s.useState((()=>x?D(x):"")),[W,k]=s.useState([]),[B,H]=s.useState(!0),[V,A]=s.useState(!1),[Z,F]=s.useState(!!x),[P,G]=s.useState(x),[M,z]=s.useState(!1),[J,K]=s.useState(!1),Q=n.useId(),[U,X]=s.useState(null),Y=`${Q}-instruction`,ee=s.useRef(null),re=s.useRef(null),te=s.useRef(m),se=s.useCallback((r=>e.__awaiter(void 0,void 0,void 0,(function*(){if(te.current){A(!1),H(!0);try{const e=yield te.current(r);L(r),k(null!=e?e:[]),H(!1)}catch(e){A(!0),H(!1)}}}))),[]),ie=s.useCallback(t.default((e=>{se(e)}),500),[se]);s.useEffect((()=>{te.current=m}),[m]),s.useEffect((()=>{N&&N.length>=j?Z?N!==R&&ie(N):(z(!0),ie(N)):ie.cancel(),""===N&&P&&(null==S||S(void 0,void 0),pe(),G(void 0)),x&&N!==D(x)&&F(!1)}),[N,x]),s.useEffect((()=>{$(x?D(x):""),L(x?D(x):""),G(x),F(!!x)}),[x]),s.useEffect((()=>{var e;const r=he(),t=null!==(e=null==W?void 0:W.length)&&void 0!==e?e:0;"loading"===r&&N.length>=j?X("Loading suggested results"):"fail"!==r?!M||B||V||X(0===t?N?"No results found.":null:`${t} result${t>1?"s":""} found. Press down arrow to scroll through the list.`):X("Suggestions failed to load. Try again.")}),[W,N,V,B]),s.useEffect((()=>()=>{ie.cancel()}),[ie]);const ae=(e,r)=>{var t;null===(t=re.current)||void 0===t||t.focus(),$(D(e)),L(e?D(e):""),F(!0),G(e),z(!1),null==S||S(e,r)},oe=()=>{K(!0)},le=e=>{M||!ee.current||ee.current.contains(e.relatedTarget)||(K(!1),ue())},ne=()=>{z(!1),K(!1)},de=()=>{$(""),F(!1),z(!1),null==S||S(void 0,void 0)},ue=()=>{if(!Z)if(P){const e=D(P);$(e),z(!1)}else de()},ce=e=>{$(e.target.value),F(!1)},pe=e=>{L(""),F(!1),H(!0)},he=()=>V?"fail":B?"loading":"success";return r.jsx(l.DropdownListState,{children:r.jsx(d.ElementWithDropdown,{enabled:!q&&!g,isOpen:M,renderElement:()=>r.jsxs(u.InputWrapper,{className:p,"data-testid":h,ref:ee,tabIndex:-1,onFocus:oe,onBlur:le,$focused:J,$disabled:g,$readOnly:q,$error:w,children:[r.jsxs(i.VisuallyHidden,{id:Y,"aria-hidden":!0,children:["Type in ",j," or more characters for suggested results."]}),U&&r.jsx(i.VisuallyHidden,{"aria-live":"polite",children:U}),r.jsx(a.Input,Object.assign({role:"combobox",ref:re,id:Q,type:"text",value:N,onChange:ce,placeholder:f,readOnly:q,disabled:g,allowClear:!0,onClear:de,"aria-expanded":M,"aria-controls":Q,"aria-autocomplete":"list","aria-haspopup":"listbox",onBlur:N.length<j?ue:void 0,styleType:"no-border","aria-describedby":i.concatIds(_,Y)},C))]}),renderDropdown:()=>r.jsx(o.DropdownList,{listboxId:Q,listItems:W,onSelectItem:ae,onDismiss:ne,valueExtractor:v,listExtractor:b,itemsLoadState:he(),itemTruncationType:"end",itemMaxLines:1,labelDisplayType:"next-line",disableItemFocus:!0,onRetry:()=>se(N),width:O,matchElementWidth:!0}),onOpen:()=>{!Z&&N.length>=j&&K(!0)},onClose:()=>{z(!1),K(!1),ue()},onDismiss:()=>{var e;z(!1),K(!1),ue(),null===(e=re.current)||void 0===e||e.focus()},onHide:()=>{k([]),H(!0),A(!1)},clickToToggle:!1,offset:8,alignment:E,fitAvailableHeight:!0,customZIndex:T,rootNode:I})})};
|
|
2
2
|
//# sourceMappingURL=predictive-text-input.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"predictive-text-input.js","sources":["../../../src/predictive-text-input/predictive-text-input.tsx"],"sourcesContent":["import debounce from \"lodash/debounce\";\nimport React, { useCallback, useEffect, useRef, useState } from \"react\";\nimport { VisuallyHidden, concatIds } from \"src/shared/accessibility\";\nimport { Input } from \"../input\";\nimport { DropdownList, DropdownListState } from \"../shared/dropdown-list\";\nimport { ItemsLoadStateType } from \"../shared/dropdown-list/types\";\nimport { ElementWithDropdown } from \"../shared/dropdown-wrapper\";\nimport { InputWrapper } from \"../shared/input-wrapper/input-wrapper\";\nimport { useId } from \"../util\";\nimport { PredictiveTextInputProps } from \"./types\";\n\nexport const PredictiveTextInput = <T, V>({\n className,\n \"data-testid\": testId,\n selectedOption,\n minimumCharacters = 3,\n fetchOptions,\n placeholder = \"Enter here...\",\n readOnly = false,\n disabled = false,\n error,\n valueExtractor,\n listExtractor,\n displayValueExtractor,\n onSelectOption,\n alignment,\n dropdownZIndex,\n dropdownRootNode,\n dropdownWidth,\n \"aria-describedby\": ariaDescribedBy,\n ...otherProps\n}: PredictiveTextInputProps<T, V>): JSX.Element => {\n const getDisplayValue = (item: T | undefined): string => {\n if (!item) return \"\";\n return displayValueExtractor\n ? displayValueExtractor(item)\n : item.toString();\n };\n\n // =============================================================================\n // CONST, STATE\n // =============================================================================\n const [input, setInput] = useState<string>(() =>\n selectedOption ? getDisplayValue(selectedOption) : \"\"\n );\n const [searchedInput, setSearchedInput] = useState<string>(() =>\n selectedOption ? getDisplayValue(selectedOption) : \"\"\n );\n const [options, setOptions] = useState<T[]>([]);\n const [isLoading, setIsLoading] = useState<boolean>(true);\n const [isError, setIsError] = useState<boolean>(false);\n const [isOptionSelected, setIsOptionSelected] = useState<boolean>(\n !!selectedOption\n );\n const [prevOptionSelected, setPrevOptionSelected] = useState<T | undefined>(\n selectedOption\n );\n const [isOpen, setIsOpen] = useState(false);\n const [isFocused, setIsFocused] = useState(false);\n\n const internalId = useId();\n const [resultAnnouncement, setResultAnnouncement] = useState<string | null>(\n null\n );\n const instructionId = `${internalId}-instruction`;\n\n const nodeRef = useRef<HTMLDivElement | null>(null);\n const selectorRef = useRef<HTMLInputElement | null>(null);\n\n const fetchOptionsRef = useRef(fetchOptions);\n\n // =============================================================================\n // DEBOUNCE FUNCTIONS\n // =============================================================================\n const handleFetchOptions = useCallback(async (input: string) => {\n if (!fetchOptionsRef.current) return;\n setIsError(false);\n setIsLoading(true);\n try {\n const fetchedOptions = await fetchOptionsRef.current(input);\n setSearchedInput(input);\n setOptions(fetchedOptions ?? []);\n setIsLoading(false);\n } catch {\n setIsError(true);\n setIsLoading(false);\n }\n }, []);\n\n const fetchOptionsDebounced = useCallback(\n debounce((input: string) => {\n handleFetchOptions(input);\n }, 500),\n [handleFetchOptions]\n );\n\n // =============================================================================\n // EFFECTS\n // =============================================================================\n\n useEffect(() => {\n fetchOptionsRef.current = fetchOptions;\n }, [fetchOptions]);\n\n useEffect(() => {\n /***\n * Should not fetch options for the following the scenario :\n * 1. When input < minimumCharacters\n * 2. When user selected option from dropdown becomes input\n * 3. Initial selectedOption passed in as input\n */\n if (input && input.length >= minimumCharacters) {\n if (!isOptionSelected) {\n setIsOpen(true);\n fetchOptionsDebounced(input);\n } else if (input !== searchedInput) {\n fetchOptionsDebounced(input);\n }\n } else {\n fetchOptionsDebounced.cancel();\n }\n\n if (input === \"\" && prevOptionSelected) {\n onSelectOption?.(undefined, undefined);\n handleDropdownDismiss();\n setPrevOptionSelected(undefined);\n }\n\n if (selectedOption && input !== getDisplayValue(selectedOption)) {\n setIsOptionSelected(false);\n }\n }, [input, selectedOption]);\n\n useEffect(() => {\n setInput(selectedOption ? getDisplayValue(selectedOption) : \"\");\n setSearchedInput(selectedOption ? getDisplayValue(selectedOption) : \"\");\n setPrevOptionSelected(selectedOption);\n setOptions([]);\n setIsOptionSelected(!!selectedOption);\n }, [selectedOption]);\n\n useEffect(() => {\n const state = getItemsLoadState();\n const count = options?.length ?? 0;\n\n if (state === \"loading\" && input.length >= minimumCharacters) {\n setResultAnnouncement(\"Loading suggested results\");\n return;\n }\n\n if (state === \"fail\") {\n setResultAnnouncement(\"Suggestions failed to load. Try again.\");\n return;\n }\n\n if (isOpen && !isLoading && !isError) {\n if (count === 0) {\n setResultAnnouncement(input ? \"No results found.\" : null);\n } else {\n setResultAnnouncement(\n `${count} result${\n count > 1 ? \"s\" : \"\"\n } found. Press down arrow to scroll through the list.`\n );\n }\n }\n }, [options, input, isError, isLoading]);\n\n // =============================================================================\n // Cleanup: cancel debounce on unmount\n // =============================================================================\n useEffect(() => {\n return () => {\n fetchOptionsDebounced.cancel();\n };\n }, [fetchOptionsDebounced]);\n\n // =============================================================================\n // EVENT HANDLERS\n // =============================================================================\n const handleListItemClick = (item: T, extractedValue: V) => {\n selectorRef.current?.focus();\n setInput(getDisplayValue(item));\n setSearchedInput(item ? getDisplayValue(item) : \"\");\n setIsOptionSelected(true);\n setPrevOptionSelected(item);\n setIsOpen(false);\n onSelectOption?.(item, extractedValue);\n };\n\n const handleOpen = () => {\n if (!isOptionSelected && input.length >= minimumCharacters) {\n setIsFocused(true);\n }\n };\n\n const handleClose = () => {\n setIsOpen(false);\n setIsFocused(false);\n handleOnBlur();\n };\n\n const handleNodeFocus = () => {\n setIsFocused(true);\n };\n\n const handleNodeBlur = (e: React.FocusEvent) => {\n if (\n !isOpen &&\n nodeRef.current &&\n !nodeRef.current.contains(e.relatedTarget as Node)\n ) {\n setIsFocused(false);\n handleOnBlur();\n }\n };\n\n const handleListDismiss = () => {\n setIsOpen(false);\n setIsFocused(false);\n };\n\n const handleDismiss = () => {\n setIsOpen(false);\n setIsFocused(false);\n handleOnBlur();\n selectorRef.current?.focus();\n };\n\n const handleOnClear = () => {\n setInput(\"\");\n setOptions([]);\n setIsOptionSelected(false);\n setIsOpen(false);\n onSelectOption?.(undefined, undefined);\n };\n\n const handleOnBlur = () => {\n if (!isOptionSelected) {\n if (prevOptionSelected) {\n const prevValue = getDisplayValue(prevOptionSelected);\n setInput(prevValue);\n setIsOpen(false);\n } else {\n handleOnClear();\n }\n }\n };\n\n const handleTyping = (e: React.ChangeEvent<HTMLInputElement>) => {\n setInput(e.target.value);\n setIsOptionSelected(false);\n };\n\n const handleDropdownDismiss = (item?: T) => {\n setSearchedInput(item ? getDisplayValue(item) : \"\");\n setIsOptionSelected(!!item);\n setOptions([]);\n setIsLoading(true);\n };\n\n // =============================================================================\n // HELPER FUNCTION\n // =============================================================================\n const getItemsLoadState = (): ItemsLoadStateType => {\n if (isError) return \"fail\";\n return isLoading ? \"loading\" : \"success\";\n };\n\n // =============================================================================\n // RENDER FUNCTION\n // =============================================================================\n const renderInputElement = () => {\n return (\n <InputWrapper\n className={className}\n data-testid={testId}\n ref={nodeRef}\n tabIndex={-1}\n onFocus={handleNodeFocus}\n onBlur={handleNodeBlur}\n $focused={isFocused}\n $disabled={disabled}\n $readOnly={readOnly}\n $error={error}\n >\n <VisuallyHidden id={instructionId} aria-hidden>\n Type in {minimumCharacters} or more characters for suggested\n results.\n </VisuallyHidden>\n {resultAnnouncement && (\n <VisuallyHidden aria-live=\"polite\">\n {resultAnnouncement}\n </VisuallyHidden>\n )}\n <Input\n role=\"combobox\"\n ref={selectorRef}\n id={internalId}\n type=\"text\"\n value={input}\n onChange={handleTyping}\n placeholder={placeholder}\n readOnly={readOnly}\n disabled={disabled}\n allowClear\n onClear={handleOnClear}\n aria-expanded={isOpen}\n aria-controls={internalId}\n aria-autocomplete=\"list\"\n aria-haspopup=\"listbox\"\n onBlur={\n input.length < minimumCharacters\n ? handleOnBlur\n : undefined\n }\n styleType=\"no-border\"\n aria-describedby={concatIds(ariaDescribedBy, instructionId)}\n {...otherProps}\n />\n </InputWrapper>\n );\n };\n\n const renderDropdown = () => {\n return (\n <>\n <DropdownList\n listboxId={internalId}\n listItems={options}\n onSelectItem={handleListItemClick}\n onDismiss={handleListDismiss}\n valueExtractor={valueExtractor}\n listExtractor={listExtractor}\n itemsLoadState={getItemsLoadState()}\n itemTruncationType={\"end\"}\n itemMaxLines={1}\n labelDisplayType={\"next-line\"}\n disableItemFocus\n onRetry={() => handleFetchOptions(input)}\n width={dropdownWidth}\n matchElementWidth\n />\n </>\n );\n };\n\n return (\n <DropdownListState>\n <ElementWithDropdown\n enabled={!readOnly && !disabled}\n isOpen={isOpen}\n renderElement={renderInputElement}\n renderDropdown={renderDropdown}\n onOpen={handleOpen}\n onClose={handleClose}\n onDismiss={handleDismiss}\n clickToToggle={false}\n offset={8}\n alignment={alignment}\n fitAvailableHeight\n customZIndex={dropdownZIndex}\n rootNode={dropdownRootNode}\n />\n </DropdownListState>\n );\n};\n"],"names":["_a","className","testId","selectedOption","minimumCharacters","fetchOptions","placeholder","readOnly","disabled","error","valueExtractor","listExtractor","displayValueExtractor","onSelectOption","alignment","dropdownZIndex","dropdownRootNode","dropdownWidth","ariaDescribedBy","otherProps","__rest","getDisplayValue","item","toString","input","setInput","useState","searchedInput","setSearchedInput","options","setOptions","isLoading","setIsLoading","isError","setIsError","isOptionSelected","setIsOptionSelected","prevOptionSelected","setPrevOptionSelected","isOpen","setIsOpen","isFocused","setIsFocused","internalId","useId","resultAnnouncement","setResultAnnouncement","instructionId","nodeRef","useRef","selectorRef","fetchOptionsRef","handleFetchOptions","useCallback","__awaiter","current","fetchedOptions","fetchOptionsDebounced","debounce","useEffect","length","cancel","undefined","handleDropdownDismiss","state","getItemsLoadState","count","handleListItemClick","extractedValue","focus","handleNodeFocus","handleNodeBlur","e","contains","relatedTarget","handleOnBlur","handleListDismiss","handleOnClear","prevValue","handleTyping","target","value","_jsx","DropdownListState","children","ElementWithDropdown","enabled","renderElement","_jsxs","InputWrapper","ref","tabIndex","onFocus","onBlur","$focused","$readOnly","$error","VisuallyHidden","id","Input","Object","assign","role","type","onChange","allowClear","onClear","styleType","concatIds","renderDropdown","_Fragment","DropdownList","listboxId","listItems","onSelectItem","onDismiss","itemsLoadState","itemTruncationType","itemMaxLines","labelDisplayType","disableItemFocus","onRetry","width","matchElementWidth","onOpen","onClose","clickToToggle","offset","fitAvailableHeight","customZIndex","rootNode"],"mappings":"4kDAW0CA,QAAAC,UACtCA,EACA,cAAeC,EAAMC,eACrBA,EAAcC,kBACdA,EAAoB,EAACC,aACrBA,EAAYC,YACZA,EAAc,gBAAeC,SAC7BA,GAAW,EAAKC,SAChBA,GAAW,EAAKC,MAChBA,EAAKC,eACLA,EAAcC,cACdA,EAAaC,sBACbA,EAAqBC,eACrBA,EAAcC,UACdA,EAASC,eACTA,EAAcC,iBACdA,E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AUzB,GACVzE,YAAaA,EACbC,SAAUA,EACVC,SAAUA,EACViG,YAAU,EACVC,QAAS7B,GAAa,gBACPtC,kBACAI,EAAU,oBACP,OAAM,gBACV,UACdkD,OACIrE,EAAMoC,OAASxD,EACTuE,QACAb,EAEV6C,UAAU,+BACQC,EAAAA,UAAU1F,EAAiB6B,IACzC5B,OAmCR0F,eA7BW,IAEf3B,EAAAA,IAAA4B,EAAAA,SAAA,CAAA1B,SACIF,EAAAA,IAAC6B,eAAY,CACTC,UAAWrE,EACXsE,UAAWpF,EACXqF,aAAc/C,GACdgD,UAAWvC,GACXlE,eAAgBA,EAChBC,cAAeA,EACfyG,eAAgBnD,KAChBoD,mBAAoB,MACpBC,aAAc,EACdC,iBAAkB,YAClBC,oBACAC,QAAS,IAAMrE,GAAmB5B,GAClCkG,MAAOzG,EACP0G,mBAAiB,MAarBC,OApKO,MACVzF,GAAoBX,EAAMoC,QAAUxD,GACrCsC,GAAa,EACjB,EAkKQmF,QA/JQ,KAChBrF,GAAU,GACVE,GAAa,GACbiC,IAAc,EA6JNwC,UAtIU,WAClB3E,GAAU,GACVE,GAAa,GACbiC,KACmB,QAAnB3E,EAAAkD,GAAYK,eAAO,IAAAvD,GAAAA,EAAEqE,OAAO,EAmIpByD,eAAe,EACfC,OAAQ,EACRjH,UAAWA,EACXkH,oBAAkB,EAClBC,aAAclH,EACdmH,SAAUlH,KAEE"}
|
|
1
|
+
{"version":3,"file":"predictive-text-input.js","sources":["../../../src/predictive-text-input/predictive-text-input.tsx"],"sourcesContent":["import debounce from \"lodash/debounce\";\nimport React, { useCallback, useEffect, useRef, useState } from \"react\";\nimport { VisuallyHidden, concatIds } from \"src/shared/accessibility\";\nimport { Input } from \"../input\";\nimport { DropdownList, DropdownListState } from \"../shared/dropdown-list\";\nimport { ItemsLoadStateType } from \"../shared/dropdown-list/types\";\nimport { ElementWithDropdown } from \"../shared/dropdown-wrapper\";\nimport { InputWrapper } from \"../shared/input-wrapper/input-wrapper\";\nimport { useId } from \"../util\";\nimport { PredictiveTextInputProps } from \"./types\";\n\nexport const PredictiveTextInput = <T, V>({\n className,\n \"data-testid\": testId,\n selectedOption,\n minimumCharacters = 3,\n fetchOptions,\n placeholder = \"Enter here...\",\n readOnly = false,\n disabled = false,\n error,\n valueExtractor,\n listExtractor,\n displayValueExtractor,\n onSelectOption,\n alignment,\n dropdownZIndex,\n dropdownRootNode,\n dropdownWidth,\n \"aria-describedby\": ariaDescribedBy,\n ...otherProps\n}: PredictiveTextInputProps<T, V>): JSX.Element => {\n const getDisplayValue = (item: T | undefined): string => {\n if (!item) return \"\";\n return displayValueExtractor\n ? displayValueExtractor(item)\n : item.toString();\n };\n\n // =============================================================================\n // CONST, STATE\n // =============================================================================\n const [input, setInput] = useState<string>(() =>\n selectedOption ? getDisplayValue(selectedOption) : \"\"\n );\n const [searchedInput, setSearchedInput] = useState<string>(() =>\n selectedOption ? getDisplayValue(selectedOption) : \"\"\n );\n const [options, setOptions] = useState<T[]>([]);\n const [isLoading, setIsLoading] = useState<boolean>(true);\n const [isError, setIsError] = useState<boolean>(false);\n const [isOptionSelected, setIsOptionSelected] = useState<boolean>(\n !!selectedOption\n );\n const [prevOptionSelected, setPrevOptionSelected] = useState<T | undefined>(\n selectedOption\n );\n const [isOpen, setIsOpen] = useState(false);\n const [isFocused, setIsFocused] = useState(false);\n\n const internalId = useId();\n const [resultAnnouncement, setResultAnnouncement] = useState<string | null>(\n null\n );\n const instructionId = `${internalId}-instruction`;\n\n const nodeRef = useRef<HTMLDivElement | null>(null);\n const selectorRef = useRef<HTMLInputElement | null>(null);\n\n const fetchOptionsRef = useRef(fetchOptions);\n\n // =============================================================================\n // DEBOUNCE FUNCTIONS\n // =============================================================================\n const handleFetchOptions = useCallback(async (input: string) => {\n if (!fetchOptionsRef.current) return;\n setIsError(false);\n setIsLoading(true);\n try {\n const fetchedOptions = await fetchOptionsRef.current(input);\n setSearchedInput(input);\n setOptions(fetchedOptions ?? []);\n setIsLoading(false);\n } catch {\n setIsError(true);\n setIsLoading(false);\n }\n }, []);\n\n const fetchOptionsDebounced = useCallback(\n debounce((input: string) => {\n handleFetchOptions(input);\n }, 500),\n [handleFetchOptions]\n );\n\n // =============================================================================\n // EFFECTS\n // =============================================================================\n\n useEffect(() => {\n fetchOptionsRef.current = fetchOptions;\n }, [fetchOptions]);\n\n useEffect(() => {\n /***\n * Should not fetch options for the following the scenario :\n * 1. When input < minimumCharacters\n * 2. When user selected option from dropdown becomes input\n * 3. Initial selectedOption passed in as input\n */\n if (input && input.length >= minimumCharacters) {\n if (!isOptionSelected) {\n setIsOpen(true);\n fetchOptionsDebounced(input);\n } else if (input !== searchedInput) {\n fetchOptionsDebounced(input);\n }\n } else {\n fetchOptionsDebounced.cancel();\n }\n\n if (input === \"\" && prevOptionSelected) {\n onSelectOption?.(undefined, undefined);\n handleDropdownDismiss();\n setPrevOptionSelected(undefined);\n }\n\n if (selectedOption && input !== getDisplayValue(selectedOption)) {\n setIsOptionSelected(false);\n }\n }, [input, selectedOption]);\n\n useEffect(() => {\n setInput(selectedOption ? getDisplayValue(selectedOption) : \"\");\n setSearchedInput(selectedOption ? getDisplayValue(selectedOption) : \"\");\n setPrevOptionSelected(selectedOption);\n setIsOptionSelected(!!selectedOption);\n }, [selectedOption]);\n\n useEffect(() => {\n const state = getItemsLoadState();\n const count = options?.length ?? 0;\n\n if (state === \"loading\" && input.length >= minimumCharacters) {\n setResultAnnouncement(\"Loading suggested results\");\n return;\n }\n\n if (state === \"fail\") {\n setResultAnnouncement(\"Suggestions failed to load. Try again.\");\n return;\n }\n\n if (isOpen && !isLoading && !isError) {\n if (count === 0) {\n setResultAnnouncement(input ? \"No results found.\" : null);\n } else {\n setResultAnnouncement(\n `${count} result${\n count > 1 ? \"s\" : \"\"\n } found. Press down arrow to scroll through the list.`\n );\n }\n }\n }, [options, input, isError, isLoading]);\n\n // =============================================================================\n // Cleanup: cancel debounce on unmount\n // =============================================================================\n useEffect(() => {\n return () => {\n fetchOptionsDebounced.cancel();\n };\n }, [fetchOptionsDebounced]);\n\n // =============================================================================\n // EVENT HANDLERS\n // =============================================================================\n const handleListItemClick = (item: T, extractedValue: V) => {\n selectorRef.current?.focus();\n setInput(getDisplayValue(item));\n setSearchedInput(item ? getDisplayValue(item) : \"\");\n setIsOptionSelected(true);\n setPrevOptionSelected(item);\n setIsOpen(false);\n onSelectOption?.(item, extractedValue);\n };\n\n const handleOpen = () => {\n if (!isOptionSelected && input.length >= minimumCharacters) {\n setIsFocused(true);\n }\n };\n\n const handleClose = () => {\n setIsOpen(false);\n setIsFocused(false);\n handleOnBlur();\n };\n\n const handleNodeFocus = () => {\n setIsFocused(true);\n };\n\n const handleNodeBlur = (e: React.FocusEvent) => {\n if (\n !isOpen &&\n nodeRef.current &&\n !nodeRef.current.contains(e.relatedTarget as Node)\n ) {\n setIsFocused(false);\n handleOnBlur();\n }\n };\n\n const handleListDismiss = () => {\n setIsOpen(false);\n setIsFocused(false);\n };\n\n const handleDismiss = () => {\n setIsOpen(false);\n setIsFocused(false);\n handleOnBlur();\n selectorRef.current?.focus();\n };\n\n const handleHide = () => {\n // reset dropdown state once it fully closes\n setOptions([]);\n setIsLoading(true);\n setIsError(false);\n };\n\n const handleOnClear = () => {\n setInput(\"\");\n setIsOptionSelected(false);\n setIsOpen(false);\n onSelectOption?.(undefined, undefined);\n };\n\n const handleOnBlur = () => {\n if (!isOptionSelected) {\n if (prevOptionSelected) {\n const prevValue = getDisplayValue(prevOptionSelected);\n setInput(prevValue);\n setIsOpen(false);\n } else {\n handleOnClear();\n }\n }\n };\n\n const handleTyping = (e: React.ChangeEvent<HTMLInputElement>) => {\n setInput(e.target.value);\n setIsOptionSelected(false);\n };\n\n const handleDropdownDismiss = (item?: T) => {\n setSearchedInput(item ? getDisplayValue(item) : \"\");\n setIsOptionSelected(!!item);\n setIsLoading(true);\n };\n\n // =============================================================================\n // HELPER FUNCTION\n // =============================================================================\n const getItemsLoadState = (): ItemsLoadStateType => {\n if (isError) return \"fail\";\n return isLoading ? \"loading\" : \"success\";\n };\n\n // =============================================================================\n // RENDER FUNCTION\n // =============================================================================\n const renderInputElement = () => {\n return (\n <InputWrapper\n className={className}\n data-testid={testId}\n ref={nodeRef}\n tabIndex={-1}\n onFocus={handleNodeFocus}\n onBlur={handleNodeBlur}\n $focused={isFocused}\n $disabled={disabled}\n $readOnly={readOnly}\n $error={error}\n >\n <VisuallyHidden id={instructionId} aria-hidden>\n Type in {minimumCharacters} or more characters for suggested\n results.\n </VisuallyHidden>\n {resultAnnouncement && (\n <VisuallyHidden aria-live=\"polite\">\n {resultAnnouncement}\n </VisuallyHidden>\n )}\n <Input\n role=\"combobox\"\n ref={selectorRef}\n id={internalId}\n type=\"text\"\n value={input}\n onChange={handleTyping}\n placeholder={placeholder}\n readOnly={readOnly}\n disabled={disabled}\n allowClear\n onClear={handleOnClear}\n aria-expanded={isOpen}\n aria-controls={internalId}\n aria-autocomplete=\"list\"\n aria-haspopup=\"listbox\"\n onBlur={\n input.length < minimumCharacters\n ? handleOnBlur\n : undefined\n }\n styleType=\"no-border\"\n aria-describedby={concatIds(ariaDescribedBy, instructionId)}\n {...otherProps}\n />\n </InputWrapper>\n );\n };\n\n const renderDropdown = () => {\n return (\n <DropdownList\n listboxId={internalId}\n listItems={options}\n onSelectItem={handleListItemClick}\n onDismiss={handleListDismiss}\n valueExtractor={valueExtractor}\n listExtractor={listExtractor}\n itemsLoadState={getItemsLoadState()}\n itemTruncationType={\"end\"}\n itemMaxLines={1}\n labelDisplayType={\"next-line\"}\n disableItemFocus\n onRetry={() => handleFetchOptions(input)}\n width={dropdownWidth}\n matchElementWidth\n />\n );\n };\n\n return (\n <DropdownListState>\n <ElementWithDropdown\n enabled={!readOnly && !disabled}\n isOpen={isOpen}\n renderElement={renderInputElement}\n renderDropdown={renderDropdown}\n onOpen={handleOpen}\n onClose={handleClose}\n onDismiss={handleDismiss}\n onHide={handleHide}\n clickToToggle={false}\n offset={8}\n alignment={alignment}\n fitAvailableHeight\n customZIndex={dropdownZIndex}\n rootNode={dropdownRootNode}\n />\n </DropdownListState>\n );\n};\n"],"names":["_a","className","testId","selectedOption","minimumCharacters","fetchOptions","placeholder","readOnly","disabled","error","valueExtractor","listExtractor","displayValueExtractor","onSelectOption","alignment","dropdownZIndex","dropdownRootNode","dropdownWidth","ariaDescribedBy","otherProps","__rest","getDisplayValue","item","toString","input","setInput","useState","searchedInput","setSearchedInput","options","setOptions","isLoading","setIsLoading","isError","setIsError","isOptionSelected","setIsOptionSelected","prevOptionSelected","setPrevOptionSelected","isOpen","setIsOpen","isFocused","setIsFocused","internalId","useId","resultAnnouncement","setResultAnnouncement","instructionId","nodeRef","useRef","selectorRef","fetchOptionsRef","handleFetchOptions","useCallback","__awaiter","current","fetchedOptions","fetchOptionsDebounced","debounce","useEffect","length","cancel","undefined","handleDropdownDismiss","state","getItemsLoadState","count","handleListItemClick","extractedValue","focus","handleNodeFocus","handleNodeBlur","e","contains","relatedTarget","handleOnBlur","handleListDismiss","handleOnClear","prevValue","handleTyping","target","value","_jsx","DropdownListState","children","ElementWithDropdown","enabled","renderElement","_jsxs","InputWrapper","ref","tabIndex","onFocus","onBlur","$focused","$readOnly","$error","VisuallyHidden","id","Input","Object","assign","role","type","onChange","allowClear","onClear","styleType","concatIds","renderDropdown","DropdownList","listboxId","listItems","onSelectItem","onDismiss","itemsLoadState","itemTruncationType","itemMaxLines","labelDisplayType","disableItemFocus","onRetry","width","matchElementWidth","onOpen","onClose","onHide","clickToToggle","offset","fitAvailableHeight","customZIndex","rootNode"],"mappings":"4kDAW0CA,QAAAC,UACtCA,EACA,cAAeC,EAAMC,eACrBA,EAAcC,kBACdA,EAAoB,EAACC,aACrBA,EAAYC,YACZA,EAAc,gBAAeC,SAC7BA,GAAW,EAAKC,SAChBA,GAAW,EAAKC,MAChBA,EAAKC,eACLA,EAAcC,cACdA,EAAaC,sBACbA,EAAqBC,eACrBA,EAAcC,UACdA,EAASC,eACTA,EAAcC,iBACdA,EAAgBC,cAChB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A,EACViG,YAAU,EACVC,QAAS7B,GAAa,gBACPtC,kBACAI,EAAU,oBACP,OAAM,gBACV,UACdkD,OACIrE,EAAMoC,OAASxD,EACTuE,QACAb,EAEV6C,UAAU,+BACQC,EAAAA,UAAU1F,EAAiB6B,IACzC5B,OAiCR0F,eA3BW,IAEf3B,EAAAA,IAAC4B,EAAAA,aAAY,CACTC,UAAWpE,EACXqE,UAAWnF,EACXoF,aAAc9C,GACd+C,UAAWtC,GACXlE,eAAgBA,EAChBC,cAAeA,EACfwG,eAAgBlD,KAChBmD,mBAAoB,MACpBC,aAAc,EACdC,iBAAkB,YAClBC,oBACAC,QAAS,IAAMpE,GAAmB5B,GAClCiG,MAAOxG,EACPyG,mBAAiB,IAYjBC,OAvKO,MACVxF,GAAoBX,EAAMoC,QAAUxD,GACrCsC,GAAa,EACjB,EAqKQkF,QAlKQ,KAChBpF,GAAU,GACVE,GAAa,GACbiC,IAAc,EAgKNuC,UAzIU,WAClB1E,GAAU,GACVE,GAAa,GACbiC,KACmB,QAAnB3E,EAAAkD,GAAYK,eAAO,IAAAvD,GAAAA,EAAEqE,OAAO,EAsIpBwD,OAnIO,KAEf/F,EAAW,IACXE,GAAa,GACbE,GAAW,EAAM,EAgIT4F,eAAe,EACfC,OAAQ,EACRjH,UAAWA,EACXkH,oBAAkB,EAClBC,aAAclH,EACdmH,SAAUlH,KAEE"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var e=require("react/jsx-runtime"),t=require("@floating-ui/react"),
|
|
1
|
+
"use strict";var e=require("react/jsx-runtime"),t=require("@floating-ui/react"),i=require("react"),n=require("../../external/react-resize-detector/build/index.esm.js"),r=require("styled-components"),s=require("../../overlay/use-floating-context.js"),l=require("../../theme/index.js");require("../../util/calendar-helper.js"),require("../../util/date-helper.js"),require("../../util/date-input-helper.js"),require("../../util/simple-id-generator.js"),require("../../util/string-helper.js"),require("@react-aria/live-announcer");var o=require("../../util/use-event.js"),a=require("../../util/use-previous.js");const u=e=>"right"===e?"bottom-end":"bottom-start",d=i.createContext({elementWidth:0,styles:{},setFloatingRef:()=>{},getFloatingProps:()=>({})});exports.DropdownRenderContext=d,exports.ElementWithDropdown=({enabled:c,isOpen:g,onOpen:h,onClose:p,onDismiss:f,onHide:m,renderElement:x,renderDropdown:j,customZIndex:v,clickToToggle:y=!1,offset:b=0,alignment:q="left",fitAvailableHeight:w,rootNode:F,positionRef:R})=>{var C;const P=i.useContext(r.ThemeContext),D=l.Breakpoint["sm-max"]({theme:P}),O=i.useRef(null),{width:H=0}=n.useResizeDetector({targetRef:null!=R?R:O,handleHeight:!1}),W={name:"center",fn:({x:e,rects:t})=>{const i=0===e||e+t.floating.width===window.innerWidth,n=window.innerWidth<D;return{x:i&&n?(window.innerWidth-t.floating.width)/2:e}}},{refs:k,floatingStyles:E,context:z}=t.useFloating({open:g,onOpenChange:(e,t,i)=>{"escape-key"===i?null==f||f():e&&!g?null==h||h():!e&&g&&(null==p||p(i))},whileElementsMounted:t.autoUpdate,placement:u(q),middleware:[t.offset(b),t.flip(),t.shift({limiter:t.limitShift()}),t.size({apply({availableHeight:e,elements:t}){!w||e>=t.floating.scrollHeight?t.floating.style.setProperty("--available-height",""):t.floating.style.setProperty("--available-height",`${Math.max(0,e)}px`)}}),W]}),M=s.useFloatingChild(),{isMounted:T,styles:I}=t.useTransitionStyles(z,{initial:{opacity:0},open:{opacity:1},duration:300}),S=t.useClick(z,{enabled:c,toggle:y,keyboardHandlers:y}),A=t.useDismiss(z,{enabled:c}),{getReferenceProps:B,getFloatingProps:N}=t.useInteractions([S,A]),U=a.usePrevious(T),Z=o.useEvent((()=>null==m?void 0:m()));i.useEffect((()=>{U&&!T&&Z()}),[U,T,Z]);const $={elementWidth:H,styles:Object.assign(Object.assign(Object.assign({},I),E),{zIndex:null!==(C=null!=v?v:M)&&void 0!==C?C:50}),setFloatingRef:k.setFloating,getFloatingProps:N};return e.jsxs(e.Fragment,{children:[e.jsx("div",Object.assign({ref:e=>{O.current=e,k.setReference(e)}},B(),{children:x()})),T&&e.jsx(t.FloatingPortal,{root:F,children:e.jsx(t.FloatingFocusManager,{context:z,modal:!1,initialFocus:-1,returnFocus:!1,children:e.jsx(d.Provider,{value:$,children:j($)})})})]})},exports.useDropdownRender=()=>i.useContext(d);
|
|
2
2
|
//# sourceMappingURL=element-with-dropdown.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"element-with-dropdown.js","sources":["../../../../src/shared/dropdown-wrapper/element-with-dropdown.tsx"],"sourcesContent":["import {\n FloatingFocusManager,\n FloatingPortal,\n Middleware,\n OpenChangeReason,\n Placement,\n autoUpdate,\n flip,\n limitShift,\n offset,\n shift,\n size,\n useClick,\n useDismiss,\n useFloating,\n useInteractions,\n useTransitionStyles,\n} from \"@floating-ui/react\";\nimport {\n CSSProperties,\n RefObject,\n createContext,\n useContext,\n useRef,\n} from \"react\";\nimport { useResizeDetector } from \"react-resize-detector\";\nimport { ThemeContext } from \"styled-components\";\nimport { useFloatingChild } from \"../../overlay/use-floating-context\";\nimport { Breakpoint } from \"../../theme\";\nimport { DropdownAlignmentType } from \"./types\";\n\nexport interface DropdownRenderProps {\n elementWidth: number;\n styles: CSSProperties;\n setFloatingRef: (node: HTMLElement | null) => void;\n getFloatingProps: (\n userProps?: React.HTMLProps<HTMLElement>\n ) => Record<string, unknown>;\n}\n\ninterface ElementWithDropdownProps {\n enabled: boolean;\n isOpen: boolean;\n onOpen?: () => void | undefined;\n onClose?: (reason: OpenChangeReason | undefined) => void | undefined;\n onDismiss?: () => void | undefined;\n renderElement: () => React.ReactNode;\n renderDropdown: (props: DropdownRenderProps) => React.ReactNode;\n customZIndex?: number | undefined;\n clickToToggle?: boolean | undefined;\n /* the distance between the reference element and the dropdown */\n offset?: number | undefined;\n /* the alignment of the dropdown to the left or right of the reference element */\n alignment?: DropdownAlignmentType | undefined;\n fitAvailableHeight?: boolean | undefined;\n /**\n * The root element that contains the popover element. Defaults to the document body.\n *\n * If the parent that contains the trigger element has a higher z-index than the popover,\n * the popover may not be visible. Specify the parent element here instead\n */\n rootNode?: RefObject<HTMLElement> | undefined;\n /** If set, the `elementWidth` refers to this instead of the reference element */\n positionRef?: RefObject<HTMLElement> | undefined;\n}\n\nconst getFloatingPlacement = (alignment: DropdownAlignmentType): Placement => {\n switch (alignment) {\n case \"right\":\n return \"bottom-end\";\n case \"left\":\n default:\n return \"bottom-start\";\n }\n};\n\nconst DEFAULT_Z_INDEX = 50;\n\nexport const DropdownRenderContext = createContext<DropdownRenderProps>({\n elementWidth: 0,\n styles: {},\n setFloatingRef: () => {\n // noop\n },\n getFloatingProps: () => ({}),\n});\n\nexport const useDropdownRender = () => {\n return useContext(DropdownRenderContext);\n};\n\n/**\n * A wrapper to handle the common pattern of a field with a card-based dropdown\n * using Floating UI\n *\n * Usage:\n * - Specify `renderElement` for the main field\n * - Specify `renderDropdown` for the dropdown\n * - Use `isOpen` to control the visibility of the dropdown\n * - Handle changes in visibility with `onOpen`, `onClose` and `onDismiss`\n * - If your dropdown can resize, set the css like so: `max-height: var(--available-height);`\n * - If your dropdown has a preferred max-height, set the css like so:\n * `max-height: min(100px, var(--available-height, infinity * 1px))`\n *\n * Pass the floating props to the dropdown:\n * ```\n * <DropdownContainer\n * ref={setFloatingRef}\n * style={styles}\n * {...getFloatingProps()}\n * >\n * </DropdownContainer>\n * ```\n *\n * If you need event listeners, pass them to `getFloatingProps()`:\n * ```\n * getFloatingProps({\n * onClick: handleOnClick\n * })\n * ```\n */\nexport const ElementWithDropdown = ({\n enabled,\n isOpen,\n onOpen,\n onClose,\n onDismiss,\n renderElement,\n renderDropdown,\n customZIndex,\n clickToToggle = false,\n offset: dropdownOffset = 0,\n alignment = \"left\",\n fitAvailableHeight,\n rootNode,\n positionRef,\n}: ElementWithDropdownProps) => {\n // =============================================================================\n // CONST, STATE, REF\n // =============================================================================\n const theme = useContext(ThemeContext);\n const mobileBreakpoint = Breakpoint[\"sm-max\"]({ theme });\n const elementRef = useRef<HTMLDivElement | null>(null);\n const { width: referenceWidth = 0 } = useResizeDetector({\n targetRef: positionRef ?? elementRef,\n handleHeight: false,\n });\n const center: Middleware = {\n name: \"center\",\n fn: ({ x, rects }) => {\n const noGapInBetween =\n x === 0 || x + rects.floating.width === window.innerWidth;\n const isMobileScreen = window.innerWidth < mobileBreakpoint;\n return {\n x:\n noGapInBetween && isMobileScreen\n ? (window.innerWidth - rects.floating.width) / 2\n : x,\n };\n },\n };\n const { refs, floatingStyles, context } = useFloating({\n open: isOpen,\n onOpenChange: (open, _event, reason) => {\n if (reason === \"escape-key\") {\n onDismiss?.();\n } else if (open && !isOpen) {\n onOpen?.();\n } else if (!open && isOpen) {\n onClose?.(reason);\n }\n },\n whileElementsMounted: autoUpdate,\n placement: getFloatingPlacement(alignment),\n middleware: [\n offset(dropdownOffset),\n flip(),\n shift({\n limiter: limitShift(),\n }),\n size({\n // shrink to fit available vertical space\n apply({ availableHeight, elements }) {\n if (\n !fitAvailableHeight ||\n availableHeight >= elements.floating.scrollHeight\n ) {\n // reset this so that dropdown can expand as needed\n elements.floating.style.setProperty(\n \"--available-height\",\n \"\"\n );\n return;\n }\n\n elements.floating.style.setProperty(\n \"--available-height\",\n `${Math.max(0, availableHeight)}px`\n );\n },\n }),\n center,\n ],\n });\n const parentZIndex = useFloatingChild();\n\n const { isMounted, styles } = useTransitionStyles(context, {\n initial: { opacity: 0 },\n open: { opacity: 1 },\n duration: 300,\n });\n\n const click = useClick(context, {\n enabled,\n toggle: clickToToggle,\n keyboardHandlers: clickToToggle,\n });\n const dismiss = useDismiss(context, { enabled });\n\n const { getReferenceProps, getFloatingProps } = useInteractions([\n click,\n dismiss,\n ]);\n\n // =============================================================================\n // RENDER FUNCTIONS\n // =============================================================================\n const dropdownRenderProps = {\n elementWidth: referenceWidth,\n styles: {\n ...styles,\n ...floatingStyles,\n zIndex: customZIndex ?? parentZIndex ?? DEFAULT_Z_INDEX,\n },\n setFloatingRef: refs.setFloating,\n getFloatingProps,\n };\n\n return (\n <>\n <div\n ref={(node) => {\n elementRef.current = node;\n refs.setReference(node);\n }}\n {...getReferenceProps()}\n >\n {renderElement()}\n </div>\n {isMounted && (\n <FloatingPortal root={rootNode}>\n <FloatingFocusManager\n context={context}\n modal={false}\n initialFocus={-1}\n returnFocus={false} // leads to focus trap. parent to handle the final focus state\n >\n <DropdownRenderContext.Provider\n value={dropdownRenderProps}\n >\n {renderDropdown(dropdownRenderProps)}\n </DropdownRenderContext.Provider>\n </FloatingFocusManager>\n </FloatingPortal>\n )}\n </>\n );\n};\n"],"names":["getFloatingPlacement","alignment","DropdownRenderContext","createContext","elementWidth","styles","setFloatingRef","getFloatingProps","enabled","isOpen","onOpen","onClose","onDismiss","renderElement","renderDropdown","customZIndex","clickToToggle","offset","dropdownOffset","fitAvailableHeight","rootNode","positionRef","theme","useContext","ThemeContext","mobileBreakpoint","Breakpoint","elementRef","useRef","width","referenceWidth","useResizeDetector","targetRef","handleHeight","center","name","fn","x","rects","noGapInBetween","floating","window","innerWidth","isMobileScreen","refs","floatingStyles","context","useFloating","open","onOpenChange","_event","reason","whileElementsMounted","autoUpdate","placement","middleware","flip","shift","limiter","limitShift","size","apply","availableHeight","elements","scrollHeight","style","setProperty","Math","max","parentZIndex","useFloatingChild","isMounted","useTransitionStyles","initial","opacity","duration","click","useClick","toggle","keyboardHandlers","dismiss","useDismiss","getReferenceProps","useInteractions","dropdownRenderProps","zIndex","_a","setFloating","_jsxs","_jsx","Object","assign","ref","node","current","setReference","children","FloatingPortal","root","FloatingFocusManager","modal","initialFocus","returnFocus","Provider","value"],"mappings":"4RAkEA,MAAMA,EAAwBC,GAEjB,UADDA,EAEO,aAGA,eAMNC,EAAwBC,EAAAA,cAAmC,CACpEC,aAAc,EACdC,OAAQ,CAAA,EACRC,eAAgB,OAGhBC,iBAAkB,KAAA,CAAS,iEAqCI,EAC/BC,UACAC,SACAC,SACAC,UACAC,YACAC,gBACAC,iBACAC,eACAC,iBAAgB,EAChBC,OAAQC,EAAi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AsE,OAAQ9D,EACR+D,iBAAkB/D,IAEhBgE,EAAUC,EAAAA,WAAWnC,EAAS,CAAEtC,aAEhC0E,kBAAEA,EAAiB3E,iBAAEA,GAAqB4E,kBAAgB,CAC5DP,EACAI,IAMEI,EAAsB,CACxBhF,aAAc0B,EACdzB,oDACOA,GACAwC,GAAc,CACjBwC,OAAoC,QAA5BC,EAAAvE,QAAAA,EAAgBsD,SAAY,IAAAiB,EAAAA,EA5JxB,KA8JhBhF,eAAgBsC,EAAK2C,YACrBhF,oBAGJ,OACIiF,6BACIC,EAAAA,IAAA,MAAAC,OAAAC,OAAA,CACIC,IAAMC,IACFlE,EAAWmE,QAAUD,EACrBjD,EAAKmD,aAAaF,EAAK,GAEvBX,IAAmB,CAAAc,SAEtBnF,OAEJ0D,GACGkB,EAAAA,IAACQ,EAAAA,gBAAeC,KAAM9E,EAAQ4E,SAC1BP,EAAAA,IAACU,uBAAoB,CACjBrD,QAASA,EACTsD,OAAO,EACPC,cAAc,EACdC,aAAa,EAAKN,SAElBP,EAAAA,IAACvF,EAAsBqG,SAAQ,CAC3BC,MAAOpB,EAAmBY,SAEzBlF,EAAesE,WAKjC,4BAlLsB,IACtB7D,EAAAA,WAAWrB"}
|
|
1
|
+
{"version":3,"file":"element-with-dropdown.js","sources":["../../../../src/shared/dropdown-wrapper/element-with-dropdown.tsx"],"sourcesContent":["import {\n FloatingFocusManager,\n FloatingPortal,\n Middleware,\n OpenChangeReason,\n Placement,\n autoUpdate,\n flip,\n limitShift,\n offset,\n shift,\n size,\n useClick,\n useDismiss,\n useFloating,\n useInteractions,\n useTransitionStyles,\n} from \"@floating-ui/react\";\nimport {\n CSSProperties,\n RefObject,\n createContext,\n useContext,\n useEffect,\n useRef,\n} from \"react\";\nimport { useResizeDetector } from \"react-resize-detector\";\nimport { ThemeContext } from \"styled-components\";\nimport { useFloatingChild } from \"../../overlay/use-floating-context\";\nimport { Breakpoint } from \"../../theme\";\nimport { useEvent, usePrevious } from \"../../util\";\nimport { DropdownAlignmentType } from \"./types\";\n\nexport interface DropdownRenderProps {\n elementWidth: number;\n styles: CSSProperties;\n setFloatingRef: (node: HTMLElement | null) => void;\n getFloatingProps: (\n userProps?: React.HTMLProps<HTMLElement>\n ) => Record<string, unknown>;\n}\n\ninterface ElementWithDropdownProps {\n enabled: boolean;\n isOpen: boolean;\n onOpen?: (() => void) | undefined;\n onClose?: ((reason: OpenChangeReason | undefined) => void) | undefined;\n onDismiss?: (() => void) | undefined;\n onHide?: (() => void) | undefined;\n renderElement: () => React.ReactNode;\n renderDropdown: (props: DropdownRenderProps) => React.ReactNode;\n customZIndex?: number | undefined;\n clickToToggle?: boolean | undefined;\n /* the distance between the reference element and the dropdown */\n offset?: number | undefined;\n /* the alignment of the dropdown to the left or right of the reference element */\n alignment?: DropdownAlignmentType | undefined;\n fitAvailableHeight?: boolean | undefined;\n /**\n * The root element that contains the popover element. Defaults to the document body.\n *\n * If the parent that contains the trigger element has a higher z-index than the popover,\n * the popover may not be visible. Specify the parent element here instead\n */\n rootNode?: RefObject<HTMLElement> | undefined;\n /** If set, the `elementWidth` refers to this instead of the reference element */\n positionRef?: RefObject<HTMLElement> | undefined;\n}\n\nconst getFloatingPlacement = (alignment: DropdownAlignmentType): Placement => {\n switch (alignment) {\n case \"right\":\n return \"bottom-end\";\n case \"left\":\n default:\n return \"bottom-start\";\n }\n};\n\nconst DEFAULT_Z_INDEX = 50;\n\nexport const DropdownRenderContext = createContext<DropdownRenderProps>({\n elementWidth: 0,\n styles: {},\n setFloatingRef: () => {\n // noop\n },\n getFloatingProps: () => ({}),\n});\n\nexport const useDropdownRender = () => {\n return useContext(DropdownRenderContext);\n};\n\n/**\n * A wrapper to handle the common pattern of a field with a card-based dropdown\n * using Floating UI\n *\n * Usage:\n * - Specify `renderElement` for the main field\n * - Specify `renderDropdown` for the dropdown\n * - Use `isOpen` to control the visibility of the dropdown\n * - Handle changes in visibility with `onOpen`, `onClose` and `onDismiss`\n * - If your dropdown can resize, set the css like so: `max-height: var(--available-height);`\n * - If your dropdown has a preferred max-height, set the css like so:\n * `max-height: min(100px, var(--available-height, infinity * 1px))`\n *\n * Pass the floating props to the dropdown:\n * ```\n * <DropdownContainer\n * ref={setFloatingRef}\n * style={styles}\n * {...getFloatingProps()}\n * >\n * </DropdownContainer>\n * ```\n *\n * If you need event listeners, pass them to `getFloatingProps()`:\n * ```\n * getFloatingProps({\n * onClick: handleOnClick\n * })\n * ```\n */\nexport const ElementWithDropdown = ({\n enabled,\n isOpen,\n onOpen,\n onClose,\n onDismiss,\n onHide,\n renderElement,\n renderDropdown,\n customZIndex,\n clickToToggle = false,\n offset: dropdownOffset = 0,\n alignment = \"left\",\n fitAvailableHeight,\n rootNode,\n positionRef,\n}: ElementWithDropdownProps) => {\n // =============================================================================\n // CONST, STATE, REF\n // =============================================================================\n const theme = useContext(ThemeContext);\n const mobileBreakpoint = Breakpoint[\"sm-max\"]({ theme });\n const elementRef = useRef<HTMLDivElement | null>(null);\n const { width: referenceWidth = 0 } = useResizeDetector({\n targetRef: positionRef ?? elementRef,\n handleHeight: false,\n });\n const center: Middleware = {\n name: \"center\",\n fn: ({ x, rects }) => {\n const noGapInBetween =\n x === 0 || x + rects.floating.width === window.innerWidth;\n const isMobileScreen = window.innerWidth < mobileBreakpoint;\n return {\n x:\n noGapInBetween && isMobileScreen\n ? (window.innerWidth - rects.floating.width) / 2\n : x,\n };\n },\n };\n const { refs, floatingStyles, context } = useFloating({\n open: isOpen,\n onOpenChange: (open, _event, reason) => {\n if (reason === \"escape-key\") {\n onDismiss?.();\n } else if (open && !isOpen) {\n onOpen?.();\n } else if (!open && isOpen) {\n onClose?.(reason);\n }\n },\n whileElementsMounted: autoUpdate,\n placement: getFloatingPlacement(alignment),\n middleware: [\n offset(dropdownOffset),\n flip(),\n shift({\n limiter: limitShift(),\n }),\n size({\n // shrink to fit available vertical space\n apply({ availableHeight, elements }) {\n if (\n !fitAvailableHeight ||\n availableHeight >= elements.floating.scrollHeight\n ) {\n // reset this so that dropdown can expand as needed\n elements.floating.style.setProperty(\n \"--available-height\",\n \"\"\n );\n return;\n }\n\n elements.floating.style.setProperty(\n \"--available-height\",\n `${Math.max(0, availableHeight)}px`\n );\n },\n }),\n center,\n ],\n });\n const parentZIndex = useFloatingChild();\n\n const { isMounted, styles } = useTransitionStyles(context, {\n initial: { opacity: 0 },\n open: { opacity: 1 },\n duration: 300,\n });\n\n const click = useClick(context, {\n enabled,\n toggle: clickToToggle,\n keyboardHandlers: clickToToggle,\n });\n const dismiss = useDismiss(context, { enabled });\n\n const { getReferenceProps, getFloatingProps } = useInteractions([\n click,\n dismiss,\n ]);\n\n // =========================================================================\n // ON HIDE EFFECT\n // =========================================================================\n const prevIsMounted = usePrevious(isMounted);\n const onHideEvent = useEvent(() => onHide?.());\n\n useEffect(() => {\n if (prevIsMounted && !isMounted) {\n onHideEvent();\n }\n }, [prevIsMounted, isMounted, onHideEvent]);\n\n // =========================================================================\n // RENDER FUNCTIONS\n // =========================================================================\n const dropdownRenderProps = {\n elementWidth: referenceWidth,\n styles: {\n ...styles,\n ...floatingStyles,\n zIndex: customZIndex ?? parentZIndex ?? DEFAULT_Z_INDEX,\n },\n setFloatingRef: refs.setFloating,\n getFloatingProps,\n };\n\n return (\n <>\n <div\n ref={(node) => {\n elementRef.current = node;\n refs.setReference(node);\n }}\n {...getReferenceProps()}\n >\n {renderElement()}\n </div>\n {isMounted && (\n <FloatingPortal root={rootNode}>\n <FloatingFocusManager\n context={context}\n modal={false}\n initialFocus={-1}\n returnFocus={false} // leads to focus trap. parent to handle the final focus state\n >\n <DropdownRenderContext.Provider\n value={dropdownRenderProps}\n >\n {renderDropdown(dropdownRenderProps)}\n </DropdownRenderContext.Provider>\n </FloatingFocusManager>\n </FloatingPortal>\n )}\n </>\n );\n};\n"],"names":["getFloatingPlacement","alignment","DropdownRenderContext","createContext","elementWidth","styles","setFloatingRef","getFloatingProps","enabled","isOpen","onOpen","onClose","onDismiss","onHide","renderElement","renderDropdown","customZIndex","clickToToggle","offset","dropdownOffset","fitAvailableHeight","rootNode","positionRef","theme","useContext","ThemeContext","mobileBreakpoint","Breakpoint","elementRef","useRef","width","referenceWidth","useResizeDetector","targetRef","handleHeight","center","name","fn","x","rects","noGapInBetween","floating","window","innerWidth","isMobileScreen","refs","floatingStyles","context","useFloating","open","onOpenChange","_event","reason","whileElementsMounted","autoUpdate","placement","middleware","flip","shift","limiter","limitShift","size","apply","availableHeight","elements","scrollHeight","style","setProperty","Math","max","parentZIndex","useFloatingChild","isMounted","useTransitionStyles","initial","opacity","duration","click","useClick","toggle","keyboardHandlers","dismiss","useDismiss","getReferenceProps","useInteractions","prevIsMounted","usePrevious","onHideEvent","useEvent","useEffect","dropdownRenderProps","zIndex","_a","setFloating","_jsxs","_jsx","Object","assign","ref","node","current","setReference","children","FloatingPortal","root","FloatingFocusManager","modal","initialFocus","returnFocus","Provider","value"],"mappings":"gmBAqEA,MAAMA,EAAwBC,GAEjB,UADDA,EAEO,aAGA,eAMNC,EAAwBC,EAAAA,cAAmC,CACpEC,aAAc,EACdC,OAAQ,CAAA,EACRC,eAAgB,OAGhBC,iBAAkB,KAAA,CAAS,iEAqCI,EAC/BC,UACAC,SACAC,SACAC,UACAC,YACAC,SACAC,gBACAC,iBACAC,eACAC,iBAAgB,EAChBC,OAAQC,EAAiB,EACzBlB,YAAY,OACZmB,qBACAC,WACAC,wBAKA,MAAMC,EAAQC,EAAAA,WAAWC,gBACnBC,EAAmBC,EAAAA,WAAW,UAAU,CAAEJ,UAC1CK,EAAaC,EAAAA,OAA8B,OACzCC,MAAOC,EAAiB,GAAMC,EAAAA,kBAAkB,CACpDC,UAAWX,QAAAA,EAAeM,EAC1BM,cAAc,IAEZC,EAAqB,CACvBC,KAAM,SACNC,GAAI,EAAGC,IAAGC,YACN,MAAMC,EACI,IAANF,GAAWA,EAAIC,EAAME,SAASX,QAAUY,OAAOC,WAC7CC,EAAiBF,OAAOC,WAAajB,EAC3C,MAAO,CACHY,EACIE,GAAkB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Y,IAAAsB,EAAAA,EAzKxB,KA2KhBtF,eAAgBuC,EAAKgD,YACrBtF,oBAGJ,OACIuF,6BACIC,EAAAA,IAAA,MAAAC,OAAAC,OAAA,CACIC,IAAMC,IACFvE,EAAWwE,QAAUD,EACrBtD,EAAKwD,aAAaF,EAAK,GAEvBhB,IAAmB,CAAAmB,SAEtBxF,OAEJ0D,GACGuB,EAAAA,IAACQ,EAAAA,gBAAeC,KAAMnF,EAAQiF,SAC1BP,EAAAA,IAACU,uBAAoB,CACjB1D,QAASA,EACT2D,OAAO,EACPC,cAAc,EACdC,aAAa,EAAKN,SAElBP,EAAAA,IAAC7F,EAAsB2G,SAAQ,CAC3BC,MAAOpB,EAAmBY,SAEzBvF,EAAe2E,WAKjC,4BA/LsB,IACtBlE,EAAAA,WAAWtB"}
|
|
@@ -3,13 +3,11 @@
|
|
|
3
3
|
border: ${r.Border["width-010"]} ${r.Border.solid} ${t};
|
|
4
4
|
border-radius: ${r.Radius.md};
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
/* Hide scrollbar */
|
|
7
|
+
scrollbar-width: none; /* Firefox */
|
|
8
|
+
-ms-overflow-style: none; /* IE 10+ */
|
|
7
9
|
&::-webkit-scrollbar {
|
|
8
|
-
display: none;
|
|
9
|
-
}
|
|
10
|
-
* {
|
|
11
|
-
-ms-overflow-style: none; /* IE and Edge */
|
|
12
|
-
scrollbar-width: none; /* Firefox */
|
|
10
|
+
display: none; /* Chrome/Safari/Webkit */
|
|
13
11
|
}
|
|
14
12
|
`;i.displayName="Table.Container";const l=d.default.table`
|
|
15
13
|
text-align: left;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"table.styles.js","sources":["../../../src/table/table.styles.tsx"],"sourcesContent":["import styled from \"styled-components\";\nimport { Border, Colour, Radius, Spacing } from \"../theme\";\n\n// =============================================================================\n// STYLES CONSTANTS\n// =============================================================================\nconst borderColor = Colour[\"border\"];\nconst fontColor = Colour[\"text\"];\n\n// =============================================================================\n// STYLES\n// =============================================================================\nexport const TableWrapper = styled.div`\n overflow: auto;\n border: ${Border[\"width-010\"]} ${Border[\"solid\"]} ${borderColor};\n border-radius: ${Radius[\"md\"]};\n\n
|
|
1
|
+
{"version":3,"file":"table.styles.js","sources":["../../../src/table/table.styles.tsx"],"sourcesContent":["import styled from \"styled-components\";\nimport { Border, Colour, Radius, Spacing } from \"../theme\";\n\n// =============================================================================\n// STYLES CONSTANTS\n// =============================================================================\nconst borderColor = Colour[\"border\"];\nconst fontColor = Colour[\"text\"];\n\n// =============================================================================\n// STYLES\n// =============================================================================\nexport const TableWrapper = styled.div`\n overflow: auto;\n border: ${Border[\"width-010\"]} ${Border[\"solid\"]} ${borderColor};\n border-radius: ${Radius[\"md\"]};\n\n /* Hide scrollbar */\n scrollbar-width: none; /* Firefox */\n -ms-overflow-style: none; /* IE 10+ */\n &::-webkit-scrollbar {\n display: none; /* Chrome/Safari/Webkit */\n }\n`;\n\nTableWrapper.displayName = \"Table.Container\";\n\nexport const TableComponent = styled.table`\n text-align: left;\n border-collapse: separate;\n border-spacing: 0;\n width: 100%;\n`;\n\nTableComponent.displayName = \"Table.Table\";\n\nexport const TableBody = styled.tbody`\n :where(tr:last-child) {\n td {\n border-bottom: none;\n }\n }\n`;\n\nexport const HeaderCell = styled.th`\n padding: ${Spacing[\"spacing-20\"]} ${Spacing[\"spacing-16\"]};\n text-align: left;\n cursor: default;\n vertical-align: middle;\n color: ${fontColor};\n background-color: ${Colour[\"bg-stronger\"]};\n height: 6rem;\n border-bottom: ${Border[\"width-010\"]} ${Border[\"solid\"]} ${borderColor};\n\n &:where(&:first-child) {\n padding-left: ${Spacing[\"spacing-24\"]};\n }\n &:where(&:last-child) {\n padding-right: ${Spacing[\"spacing-24\"]};\n }\n`;\n\nexport const BodyRow = styled.tr`\n background-color: ${Colour[\"bg\"]};\n border-top: ${Border[\"width-010\"]} ${Border[\"solid\"]} ${borderColor};\n`;\n\nexport const BodyCell = styled.td`\n padding: ${Spacing[\"spacing-20\"]} ${Spacing[\"spacing-16\"]};\n vertical-align: middle;\n color: ${fontColor};\n border-bottom: ${Border[\"width-010\"]} ${Border[\"solid\"]} ${borderColor};\n\n &:where(&:first-child) {\n padding-left: ${Spacing[\"spacing-24\"]};\n }\n &:where(&:last-child) {\n padding-right: ${Spacing[\"spacing-24\"]};\n }\n`;\n"],"names":["borderColor","Colour","fontColor","TableWrapper","styled","div","Border","Radius","displayName","TableComponent","table","TableBody","tbody","HeaderCell","th","Spacing","BodyRow","tr","BodyCell","td"],"mappings":"kKAMA,MAAMA,EAAcC,EAAAA,OAAe,OAC7BC,EAAYD,EAAAA,OAAa,KAKlBE,EAAeC,EAAAA,QAAOC,GAAG;;cAExBC,EAAAA,OAAO,gBAAgBA,EAAAA,OAAc,SAAKN;qBACnCO,EAAAA,OAAW;;;;;;;;EAUhCJ,EAAaK,YAAc,kBAEpB,MAAMC,EAAiBL,EAAAA,QAAOM,KAAK;;;;;EAO1CD,EAAeD,YAAc,cAEtB,MAAMG,EAAYP,EAAAA,QAAOQ,KAAK;;;;;;EAQxBC,EAAaT,EAAAA,QAAOU,EAAE;eACpBC,EAAAA,QAAQ,iBAAiBA,EAAAA,QAAQ;;;;aAInCb;wBACWD,EAAAA,OAAO;;qBAEVK,EAAAA,OAAO,gBAAgBA,EAAAA,OAAc,SAAKN;;;wBAGvCe,EAAAA,QAAQ;;;yBAGPA,EAAAA,QAAQ;;EAIpBC,EAAUZ,EAAAA,QAAOa,EAAE;wBACRhB,EAAAA,OAAW;kBACjBK,EAAAA,OAAO,gBAAgBA,EAAAA,OAAc,SAAKN;EAG/CkB,EAAWd,EAAAA,QAAOe,EAAE;eAClBJ,EAAAA,QAAQ,iBAAiBA,EAAAA,QAAQ;;aAEnCb;qBACQI,EAAAA,OAAO,gBAAgBA,EAAAA,OAAc,SAAKN;;;wBAGvCe,EAAAA,QAAQ;;;yBAGPA,EAAAA,QAAQ;;"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var e=require("react");exports.useThrottle=function(r,u){const t=e.useRef(r),n=e.useRef(0),c=e.useRef(null);return e.useEffect((()=>{t.current=r}),[r]),e.useEffect((()=>()=>{null!==c.current&&clearTimeout(c.current)}),[]),e.useCallback(((...e)=>{const r=Date.now(),l=r-n.current;null!==c.current&&(clearTimeout(c.current),c.current=null),l>=u?(n.current=r,t.current(...e)):c.current=setTimeout((()=>{n.current=Date.now(),c.current=null,t.current(...e)}),u-l)}),[u])};
|
|
2
|
+
//# sourceMappingURL=use-throttle.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-throttle.js","sources":["../../../src/util/use-throttle.ts"],"sourcesContent":["import { useCallback, useEffect, useRef } from \"react\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function useThrottle<T extends (...args: any[]) => any>(\n callback: T,\n wait: number\n): T {\n const callbackRef = useRef<T>(callback);\n const lastCalledRef = useRef<number>(0);\n const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n useEffect(() => {\n callbackRef.current = callback;\n }, [callback]);\n\n useEffect(() => {\n return () => {\n if (timeoutRef.current !== null) {\n clearTimeout(timeoutRef.current);\n }\n };\n }, []);\n\n return useCallback(\n (...args: Parameters<T>) => {\n const now = Date.now();\n const elapsed = now - lastCalledRef.current;\n\n if (timeoutRef.current !== null) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = null;\n }\n\n if (elapsed >= wait) {\n lastCalledRef.current = now;\n callbackRef.current(...args);\n } else {\n timeoutRef.current = setTimeout(() => {\n lastCalledRef.current = Date.now();\n timeoutRef.current = null;\n callbackRef.current(...args);\n }, wait - elapsed);\n }\n },\n [wait]\n ) as T;\n}\n"],"names":["callback","wait","callbackRef","useRef","lastCalledRef","timeoutRef","useEffect","current","clearTimeout","useCallback","args","now","Date","elapsed","setTimeout"],"mappings":"wDAGM,SACFA,EACAC,GAEA,MAAMC,EAAcC,EAAAA,OAAUH,GACxBI,EAAgBD,EAAAA,OAAe,GAC/BE,EAAaF,EAAAA,OAA6C,MAchE,OAZAG,EAAAA,WAAU,KACNJ,EAAYK,QAAUP,CAAQ,GAC/B,CAACA,IAEJM,EAAAA,WAAU,IACC,KACwB,OAAvBD,EAAWE,SACXC,aAAaH,EAAWE,QAC5B,GAEL,IAEIE,EAAAA,aACH,IAAIC,KACA,MAAMC,EAAMC,KAAKD,MACXE,EAAUF,EAAMP,EAAcG,QAET,OAAvBF,EAAWE,UACXC,aAAaH,EAAWE,SACxBF,EAAWE,QAAU,MAGrBM,GAAWZ,GACXG,EAAcG,QAAUI,EACxBT,EAAYK,WAAWG,IAEvBL,EAAWE,QAAUO,YAAW,KAC5BV,EAAcG,QAAUK,KAAKD,MAC7BN,EAAWE,QAAU,KACrBL,EAAYK,WAAWG,EAAK,GAC7BT,EAAOY,EACd,GAEJ,CAACZ,GAET"}
|
package/data-table/data-table.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{__rest as e}from"../_virtual/_tslib.js";import{jsxs as t,jsx as i,Fragment as
|
|
1
|
+
import{__rest as e}from"../_virtual/_tslib.js";import{jsxs as t,jsx as i,Fragment as n}from"react/jsx-runtime";import{ArrowUpIcon as l,ArrowDownIcon as r}from"@lifesg/react-icons";import{useRef as o,useState as d,useEffect as a}from"react";import{useResizeDetector as s}from"../external/react-resize-detector/build/index.esm.js";import"../animations/loading-spinner/loading-spinner.js";import"../animations/loading-dots/loading-dots.js";import{LoadingDotsSpinner as c}from"../animations/loading-dots-spinner/loading-dots-spinner.js";import"styled-components";import{Checkbox as h}from"../checkbox/checkbox.js";import{ErrorDisplay as p}from"../error-display/error-display.js";import"../error-display/helper.js";import{VisuallyHidden as u,concatIds as m}from"../shared/accessibility/index.js";import{Typography as g}from"../typography/typography.js";import"../util/calendar-helper.js";import"../util/date-helper.js";import"../util/date-input-helper.js";import{useId as b}from"../util/simple-id-generator.js";import"../util/string-helper.js";import"@react-aria/live-announcer";import{useEvent as f}from"../util/use-event.js";import{useEventListener as y}from"../util/use-event-listener.js";import{useThrottle as w}from"../util/use-throttle.js";import{TableWrapper as $,TableContainer as k,Table as v,TableBody as S,TableHead as C,HeaderRow as j,BodyRow as H,EmptyViewCell as x,LoaderWrapper as B,ActionBarWrapper as R,ActionBar as I,TextButton as A,ActionBarSpacer as N,HeaderCell as K,CheckBoxWrapper as M,HeaderCellWrapper as V,ErrorDisplayTitle as L,BodyCell as z,BodyCellContent as D}from"./data-table.styles.js";const E=E=>{var{id:W,headers:_,rows:O,className:P,sortIndicators:T,alternatingRows:q,loadState:F="success",enableMultiSelect:G,selectedIds:J,disabledIds:Q,enableActionBar:U,enableSelectAll:X,enableStickyHeader:Y,emptyView:Z,actionBarContent:ee,renderCustomEmptyView:te,onHeaderClick:ie,onSelect:ne,onSelectAll:le,onClearSelectionClick:re}=E,oe=e(E,["id","headers","rows","className","sortIndicators","alternatingRows","loadState","enableMultiSelect","selectedIds","disabledIds","enableActionBar","enableSelectAll","enableStickyHeader","emptyView","actionBarContent","renderCustomEmptyView","onHeaderClick","onSelect","onSelectAll","onClearSelectionClick"]);const de=o(null),ae=o(null),se=o(null),ce=o(null),he=b(),pe=_.filter((e=>"string"!=typeof e&&!!e.keyColumn)),[ue,me]=d("inline"),[ge,be]=d(!1),[fe,ye]=d(!1),we=f((()=>{Ne()}));a((()=>{we()}),[we]);const $e=w((()=>Ne()),100);s({targetRef:ce,onResize:()=>$e()}),y("scroll",$e),y("scroll",$e,ce.current);const ke=()=>!!(O&&O.length&&J)&&J.length===O.length,ve=e=>!!(null==J?void 0:J.includes(e)),Se=e=>!!q&&e%2==1,Ce=e=>!!(null==Q?void 0:Q.includes(e)),je=e=>{if(oe["data-testid"])return`${oe["data-testid"]}-${e}`},He=()=>_.length+(G?1:0),xe=e=>null==T?void 0:T[e],Be=e=>{const t=xe(e);if(t)return"asc"===t?"ascending":"descending"},Re=e=>` by ${"asc"===xe(e)?"descending":"ascending"} order`,Ie=(e,t)=>`${he}-row-${e}-${t}-key-column`,Ae=e=>{const t=pe.map((t=>Ie(e,t.fieldKey)));return m(...t)},Ne=()=>{if(!ce.current||!ae.current||!se.current)return;const e=ce.current.getBoundingClientRect(),t=ae.current.getBoundingClientRect();let i="inline";const n=ce.current.scrollHeight>ce.current.clientHeight;if(e.top>window.innerHeight||e.bottom<0?i="inline":n?e.top>0&&e.top<window.innerHeight&&e.bottom>0&&e.bottom<window.innerHeight||e.top<0&&e.bottom>0&&e.bottom<window.innerHeight?i="sticky":e.bottom>window.innerHeight&&Math.max(e.top,t.bottom)+t.height<window.innerHeight&&(i="fixed"):e.bottom>window.innerHeight&&t.bottom+t.height<window.innerHeight&&(i="fixed"),be(n),me(i),"fixed"===i)ye(!0);else if("sticky"===i){const e=ce.current.scrollTop+ce.current.clientHeight<ce.current.scrollHeight;ye(e)}else ye(!1)},Ke=e=>{const{fieldKey:n,label:l,clickable:r=!1,style:o}="string"==typeof e?{fieldKey:e,label:e,style:void 0}:e,d=!!xe(n),a=(e=>`${he}-header-${e}`)(n);return t(K,{"data-testid":je(`header-${n}`),$clickable:r,scope:"col","aria-sort":Be(n),style:o,$isCheckbox:!1,onClick:()=>(e=>{null==ie||ie(e)})(n),children:[t(V,{id:a,children:["string"==typeof l?i(g.BodyBL,{weight:"bold",children:l}):l,Me(n)]}),(r||d)&&i(u,{children:t("button",{onClick:e=>((e,t)=>{e.stopPropagation(),null==ie||ie(t)})(e,n),children:[d&&"Sort ",i("span",{"aria-labelledby":a}),d&&Re(n)]})})]},n)},Me=e=>{const t=null==T?void 0:T[e];return t?"asc"===t?i(l,{"aria-hidden":!0,"data-testid":je(`header-${e}-arrowup`)}):i(r,{"aria-hidden":!0,"data-testid":je(`header-${e}-arrowdown`)}):i(n,{})},Ve=()=>i(K,{"data-testid":je("header-selection"),$clickable:!1,$isCheckbox:!0,scope:"col",children:t(M,{children:[i(u,{children:"Row selection"}),X&&i(h,{checked:ke(),indeterminate:!!J&&0!==J.length&&!ke(),disabled:!O||!O.length||!J,"aria-label":"Select all rows",onClick:()=>{le&&le(ke())}})]})}),Le=(e,t)=>{const n="string"!=typeof e?e.style:void 0,l="string"==typeof e?e:e.fieldKey,r=t.id.toString(),o=t[l],d=`${r}-${l}`;return i(z,{"data-testid":je(`row-${d}`),id:Ie(r,l),style:n,$isCheckbox:!1,children:"string"==typeof o||"number"==typeof o?i(D,{children:o}):"function"==typeof o?o(t,{isSelected:ve(r)}):o},d)},ze=e=>{const t=e.id.toString();return i(z,{"data-testid":je(`row-${t}-selection`),$isCheckbox:!0,children:i(M,{children:i(h,{checked:ve(t),"aria-labelledby":Ae(t),onClick:()=>{ne&&ne(t,!ve(t))},disabled:Ce(t),focusableWhenDisabled:Ce(t)})})})},De=()=>i(p,Object.assign({type:"no-item-found"},Z,{title:(null==Z?void 0:Z.title)?"string"==typeof Z.title?i(L,{weight:"bold",children:Z.title}):Z.title:i(L,{weight:"bold",children:"No <items> found"}),description:(null==Z?void 0:Z.description)?Z.description:"No matching rows"}));return t($,{id:W||"table-wrapper","data-testid":oe["data-testid"]||"table",className:P,ref:ce,tabIndex:0,$scrollable:ge,children:[i(k,{children:t(v,{ref:de,children:[i(C,{ref:ae,$stickyHeader:Y,children:t(j,{children:[G&&Ve(),_.map(Ke)]})}),i(S,{children:"success"===F?!O||O.length<1?i(H,{$alternating:!1,children:i(x,{colSpan:He(),children:te?te():De()})}):i(n,{children:null==O?void 0:O.map(((e,i)=>t(H,{"data-testid":je(`row-${e.id.toString()}`),$showLastRowBottomBorder:fe,$alternating:Se(i),$isSelectable:G,$isSelected:ve(e.id.toString()),children:[G&&ze(e),_.map((t=>Le(t,e)))]},e.id.toString())))}):i(H,{$alternating:!1,children:i("td",{colSpan:He(),children:i(B,{role:"status","aria-live":"polite","aria-label":"Loading table",children:"loading"===F&&i(c,{})})})})})]})}),U&&J&&J.length>0&&(()=>{var e,l,r,o;const d=null!==(e=null==J?void 0:J.length)&&void 0!==e?e:0,a="item"+(d>1?"s":"");return t(n,{children:[i(R,{ref:se,$strategy:ue,$left:fe?null===(r=null===(l=null==de?void 0:de.current)||void 0===l?void 0:l.getBoundingClientRect())||void 0===r?void 0:r.left:0,$width:null===(o=null==de?void 0:de.current)||void 0===o?void 0:o.clientWidth,children:t(I,{$float:fe,children:[i(g.BodyMD,{weight:"semibold",children:`${d} ${a} selected`}),i(A,{type:"button","aria-label":`Clear selection of ${d} ${a}`,onClick:re,children:"Clear selection"}),ee]})}),"sticky"!==ue&&i(N,{})]})})()]})};export{E as DataTable};
|
|
2
2
|
//# sourceMappingURL=data-table.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"data-table.js","sources":["../../src/data-table/data-table.tsx"],"sourcesContent":["import { ArrowDownIcon, ArrowUpIcon } from \"@lifesg/react-icons\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { useInView } from \"react-intersection-observer\";\nimport { useResizeDetector } from \"react-resize-detector\";\nimport { LoadingDotsSpinner } from \"../animations\";\nimport { Checkbox } from \"../checkbox\";\nimport { ErrorDisplay } from \"../error-display\";\nimport { VisuallyHidden, concatIds } from \"../shared/accessibility\";\nimport { Typography } from \"../typography\";\nimport { useId } from \"../util\";\nimport { useEventListener } from \"../util/use-event-listener\";\nimport {\n ActionBar,\n ActionBarWrapper,\n BodyCell,\n BodyCellContent,\n BodyRow,\n CheckBoxWrapper,\n EmptyViewCell,\n ErrorDisplayTitle,\n HeaderCell,\n HeaderCellWrapper,\n HeaderRow,\n LoaderWrapper,\n Table,\n TableBody,\n TableContainer,\n TableWrapper,\n TextButton,\n} from \"./data-table.styles\";\nimport { DataTableProps, HeaderProps, RowProps } from \"./types\";\n\nexport const DataTable = ({\n id,\n headers,\n rows,\n className,\n sortIndicators,\n alternatingRows,\n loadState = \"success\",\n enableMultiSelect,\n selectedIds,\n disabledIds,\n enableActionBar,\n enableSelectAll,\n enableStickyHeader,\n emptyView,\n actionBarContent,\n renderCustomEmptyView,\n onHeaderClick,\n onSelect,\n onSelectAll,\n onClearSelectionClick,\n ...otherProps\n}: DataTableProps) => {\n // =============================================================================\n // CONST, STATE, REF\n // =============================================================================\n const tableRef = useRef<HTMLTableElement>(null);\n const tableEndRef = useRef<HTMLDivElement | null>(null);\n const headerRef = useRef<HTMLTableSectionElement>(null);\n const actionBarRef = useRef<HTMLDivElement>(null);\n const wrapperRef = useRef<HTMLDivElement>(null);\n const internalId = useId();\n const keyColumns = headers.filter(\n (header): header is Exclude<HeaderProps, string> => {\n return typeof header !== \"string\" && !!header.keyColumn;\n }\n );\n\n const [scrollable, setScrollable] = useState(false);\n const [scrollEnd, setScrollEnd] = useState(false);\n const [tableEnd, setTableEnd] = useState(false);\n const [isFloatingActionBar, setIsFloatingActionBar] = useState(false);\n const [showLastBorder, setShowLastBorder] = useState(false);\n\n const { ref: endRef, inView: end } = useInView();\n\n // =============================================================================\n // EFFECTS, EVENT LISTENERS\n // ============================================================================\n const onResize = useCallback(() => {\n if (!wrapperRef.current || !actionBarRef.current) {\n return;\n }\n const scrollable =\n wrapperRef.current.scrollHeight > wrapperRef.current.clientHeight;\n setScrollable(scrollable);\n\n if (scrollable) {\n actionBarRef.current.style.transform = `translateY(0)`;\n } else {\n calculateStickyInViewport();\n }\n }, []);\n\n useEffect(() => {\n onResize();\n }, []);\n\n useResizeDetector({ onResize });\n\n const scrollHandler = () => {\n requestAnimationFrame(() => {\n if (scrollable) {\n calculateFixedInViewport();\n } else {\n calculateStickyInViewport();\n }\n });\n\n if (wrapperRef.current) {\n setTableEnd(\n wrapperRef.current.getBoundingClientRect().bottom <=\n window.innerHeight\n );\n }\n };\n\n useEventListener(\"scroll\", scrollHandler, \"window\");\n\n useEffect(() => {\n checkLastBorder();\n }, [rows]);\n\n // ===========================================================================\n // HELPER FUNCTIONS\n // ===========================================================================\n const isAllCheckboxSelected = (): boolean => {\n if (!rows || !rows.length || !selectedIds) {\n return false;\n }\n\n return selectedIds.length === rows.length;\n };\n\n const isIndeterminateCheckbox = (): boolean => {\n return (\n !!selectedIds &&\n selectedIds.length !== 0 &&\n !isAllCheckboxSelected()\n );\n };\n\n const isHeaderCheckboxDisabled = (): boolean => {\n return !rows || !rows.length || !selectedIds;\n };\n\n const isRowSelected = (rowId: string): boolean => {\n return !!selectedIds?.includes(rowId);\n };\n\n const isAlternatingRow = (index: number): boolean => {\n return !!alternatingRows && index % 2 === 1;\n };\n\n const isDisabledRow = (rowId: string): boolean => {\n return !!disabledIds?.includes(rowId);\n };\n\n const getDataTestId = (subStr: string) => {\n if (!otherProps[\"data-testid\"]) return undefined;\n return `${otherProps[\"data-testid\"]}-${subStr}`;\n };\n\n const getTotalColumns = (): number => {\n return headers.length + (enableMultiSelect ? 1 : 0);\n };\n\n const getSortDirection = (fieldKey: string) => {\n return sortIndicators?.[fieldKey];\n };\n\n const getHeaderAriaSort = (fieldKey: string) => {\n const sortDirection = getSortDirection(fieldKey);\n\n if (!sortDirection) {\n return undefined;\n }\n\n return sortDirection === \"asc\" ? \"ascending\" : \"descending\";\n };\n\n const getSortButtonAriaLabel = (fieldKey: string) => {\n const nextSortDirection =\n getSortDirection(fieldKey) === \"asc\" ? \"descending\" : \"ascending\";\n\n return ` by ${nextSortDirection} order`;\n };\n\n const getHeaderWrapperId = (fieldKey: string) => {\n return `${internalId}-header-${fieldKey}`;\n };\n const getCellId = (rowId: string, fieldKey: string) => {\n return `${internalId}-row-${rowId}-${fieldKey}-key-column`;\n };\n\n const getRowCheckboxAriaLabelledBy = (rowId: string) => {\n const keyColumnIds = keyColumns.map((header) =>\n getCellId(rowId, header.fieldKey)\n );\n\n return concatIds(...keyColumnIds);\n };\n\n const calculateFixedInViewport = () => {\n if (!wrapperRef.current) {\n return;\n }\n const wrapperBounds = wrapperRef.current.getBoundingClientRect();\n setIsFloatingActionBar(\n wrapperBounds.bottom > window.innerHeight + 30 &&\n wrapperBounds.top < window.innerHeight - 200\n );\n };\n\n const calculateStickyInViewport = () => {\n if (\n !tableRef.current ||\n !tableEndRef.current ||\n !wrapperRef.current ||\n !actionBarRef.current ||\n !headerRef.current\n ) {\n return;\n }\n\n const endBounds = tableEndRef.current.getBoundingClientRect();\n\n if (endBounds.top > window.innerHeight) {\n const bottomOffset = endBounds.bottom - window.innerHeight;\n const bottomToHeaderOffset =\n tableRef.current.getBoundingClientRect().height -\n headerRef.current.clientHeight -\n 32;\n const maxBottomOffset = Math.min(\n bottomOffset,\n bottomToHeaderOffset\n );\n\n actionBarRef.current.style.transform = `translateY(-${maxBottomOffset}px)`;\n } else {\n actionBarRef.current.style.transform = `translateY(0)`;\n }\n };\n\n const checkLastBorder = () => {\n if (!tableRef.current || !wrapperRef.current) {\n return;\n }\n // 56 pixels added due to the behavior of action bar\n setShowLastBorder(\n tableRef.current.clientHeight + (enableActionBar ? 56 : 0) <\n wrapperRef.current.clientHeight\n );\n };\n\n // =============================================================================\n // EVENT HANDLERS\n // =============================================================================\n const handleHeaderClick = (fieldKey: string) => {\n onHeaderClick?.(fieldKey);\n };\n\n const handleHeaderButtonClick = (\n event: React.MouseEvent<HTMLButtonElement>,\n fieldKey: string\n ) => {\n event.stopPropagation();\n onHeaderClick?.(fieldKey);\n };\n\n // =============================================================================\n // RENDER FUNCTIONS\n // =============================================================================\n const renderHeaders = () => (\n <thead ref={headerRef}>\n <HeaderRow>\n {enableMultiSelect && renderHeaderCheckBox()}\n {headers.map(renderHeaderCell)}\n </HeaderRow>\n </thead>\n );\n\n const renderHeaderCell = (header: HeaderProps) => {\n const {\n fieldKey,\n label,\n clickable = false,\n style,\n } = typeof header === \"string\"\n ? {\n fieldKey: header,\n label: header,\n style: undefined,\n }\n : header;\n\n const isSortable = !!getSortDirection(fieldKey);\n const headerCellWrapperId = getHeaderWrapperId(fieldKey);\n\n return (\n <HeaderCell\n data-testid={getDataTestId(`header-${fieldKey}`)}\n key={fieldKey}\n $clickable={clickable}\n scope=\"col\"\n aria-sort={getHeaderAriaSort(fieldKey)}\n style={style}\n $isCheckbox={false}\n onClick={() => handleHeaderClick(fieldKey)}\n >\n <HeaderCellWrapper id={headerCellWrapperId}>\n {typeof label === \"string\" ? (\n <Typography.BodyBL weight=\"bold\">\n {label}\n </Typography.BodyBL>\n ) : (\n label\n )}\n {renderSortedArrow(fieldKey)}\n </HeaderCellWrapper>\n {(clickable || isSortable) && (\n <VisuallyHidden>\n <button\n onClick={(event) =>\n handleHeaderButtonClick(event, fieldKey)\n }\n >\n {isSortable && \"Sort \"}\n <span aria-labelledby={headerCellWrapperId} />\n {isSortable && getSortButtonAriaLabel(fieldKey)}\n </button>\n </VisuallyHidden>\n )}\n </HeaderCell>\n );\n };\n\n const renderSortedArrow = (fieldKey: string) => {\n const isSorted = sortIndicators?.[fieldKey];\n\n if (!isSorted) {\n return <></>;\n }\n if (isSorted === \"asc\") {\n return (\n <ArrowUpIcon\n aria-hidden\n data-testid={getDataTestId(`header-${fieldKey}-arrowup`)}\n />\n );\n }\n return (\n <ArrowDownIcon\n aria-hidden\n data-testid={getDataTestId(`header-${fieldKey}-arrowdown`)}\n />\n );\n };\n\n const renderHeaderCheckBox = () => {\n return (\n <HeaderCell\n data-testid={getDataTestId(\"header-selection\")}\n $clickable={false}\n $isCheckbox={true}\n scope=\"col\"\n >\n <CheckBoxWrapper>\n <VisuallyHidden>Row selection</VisuallyHidden>\n {enableSelectAll && (\n <Checkbox\n checked={isAllCheckboxSelected()}\n indeterminate={isIndeterminateCheckbox()}\n disabled={isHeaderCheckboxDisabled()}\n aria-label=\"Select all rows\"\n onClick={() => {\n if (onSelectAll) {\n onSelectAll(isAllCheckboxSelected());\n }\n }}\n />\n )}\n </CheckBoxWrapper>\n </HeaderCell>\n );\n };\n\n const renderRows = () => {\n return !rows || rows.length < 1 ? (\n <BodyRow $alternating={false}>\n <EmptyViewCell colSpan={getTotalColumns()}>\n {renderCustomEmptyView\n ? renderCustomEmptyView()\n : renderBasicEmptyView()}\n </EmptyViewCell>\n </BodyRow>\n ) : (\n <>\n {rows?.map((row: RowProps, index: number) => (\n <BodyRow\n data-testid={getDataTestId(`row-${row.id.toString()}`)}\n key={row.id.toString()}\n $alternating={isAlternatingRow(index)}\n $isSelectable={enableMultiSelect}\n $isSelected={isRowSelected(row.id.toString())}\n >\n {enableMultiSelect && renderRowCheckBox(row)}\n\n {headers.map((header) => renderRowCell(header, row))}\n </BodyRow>\n ))}\n </>\n );\n };\n\n const renderRowCell = (header: HeaderProps, row: RowProps) => {\n const style = typeof header !== \"string\" ? header.style : undefined;\n const fieldKey = typeof header === \"string\" ? header : header.fieldKey;\n const rowId = row.id.toString();\n const cellData = row[fieldKey];\n const cellId = `${rowId}-${fieldKey}`;\n\n return (\n <BodyCell\n data-testid={getDataTestId(`row-${cellId}`)}\n key={cellId}\n id={getCellId(rowId, fieldKey)}\n style={style}\n $isCheckbox={false}\n >\n {typeof cellData === \"string\" ||\n typeof cellData === \"number\" ? (\n <BodyCellContent>{cellData}</BodyCellContent>\n ) : typeof cellData === \"function\" ? (\n cellData(row, { isSelected: isRowSelected(rowId) })\n ) : (\n cellData\n )}\n </BodyCell>\n );\n };\n\n const renderRowCheckBox = (row: RowProps) => {\n const rowId = row.id.toString();\n\n return (\n <BodyCell\n data-testid={getDataTestId(`row-${rowId}-selection`)}\n $isCheckbox={true}\n >\n <CheckBoxWrapper>\n <Checkbox\n checked={isRowSelected(rowId)}\n aria-labelledby={getRowCheckboxAriaLabelledBy(rowId)}\n onClick={() => {\n if (onSelect) {\n onSelect(rowId, !isRowSelected(rowId));\n }\n }}\n disabled={isDisabledRow(rowId)}\n focusableWhenDisabled={isDisabledRow(rowId)}\n />\n </CheckBoxWrapper>\n </BodyCell>\n );\n };\n\n const renderBasicEmptyView = () => {\n return (\n <ErrorDisplay\n type={\"no-item-found\"}\n {...emptyView}\n title={\n emptyView?.title ? (\n typeof emptyView.title === \"string\" ? (\n <ErrorDisplayTitle weight=\"bold\">\n {emptyView.title}\n </ErrorDisplayTitle>\n ) : (\n emptyView.title\n )\n ) : (\n <ErrorDisplayTitle weight=\"bold\">\n {\"No <items> found\"}\n </ErrorDisplayTitle>\n )\n }\n description={\n emptyView?.description\n ? emptyView.description\n : \"No matching rows\"\n }\n />\n );\n };\n\n const renderLoader = () => {\n return (\n <BodyRow $alternating={false}>\n <td colSpan={getTotalColumns()}>\n <LoaderWrapper\n role=\"status\"\n aria-live=\"polite\"\n aria-label=\"Loading table\"\n >\n {loadState === \"loading\" && <LoadingDotsSpinner />}\n </LoaderWrapper>\n </td>\n </BodyRow>\n );\n };\n\n const renderSelectionBar = () => {\n const count = selectedIds?.length ?? 0;\n\n return (\n <ActionBarWrapper\n ref={actionBarRef}\n $fixed={isFloatingActionBar}\n $left={tableRef?.current?.getBoundingClientRect()?.left}\n $width={tableRef?.current?.clientWidth}\n >\n <ActionBar\n $float={\n (scrollable ? !scrollEnd : !end) || isFloatingActionBar\n }\n $scrollable={scrollable}\n >\n <Typography.BodyMD weight=\"semibold\">{`${count} item${\n count > 1 ? \"s\" : \"\"\n } selected`}</Typography.BodyMD>\n <TextButton\n type=\"button\"\n aria-label={`Clear selection of ${count} item${\n count === 1 ? \"\" : \"s\"\n }`}\n onClick={onClearSelectionClick}\n >\n Clear selection\n </TextButton>\n {actionBarContent}\n </ActionBar>\n </ActionBarWrapper>\n );\n };\n\n return (\n <TableWrapper\n id={id || \"table-wrapper\"}\n data-testid={otherProps[\"data-testid\"] || \"table\"}\n className={className}\n ref={wrapperRef}\n onScroll={() => {\n if (scrollable && wrapperRef.current) {\n setScrollEnd(\n wrapperRef.current.scrollTop +\n wrapperRef.current.clientHeight >=\n wrapperRef.current.scrollHeight\n );\n }\n }}\n tabIndex={0} // scrollable container must be focusable to support keyboard users\n >\n <TableContainer>\n <Table\n $end={tableEnd}\n $scrollable={scrollable}\n ref={tableRef}\n $stickyHeader={enableStickyHeader}\n >\n {renderHeaders()}\n <TableBody $showLastRowBottomBorder={showLastBorder}>\n {loadState === \"success\"\n ? renderRows()\n : renderLoader()}\n </TableBody>\n </Table>\n </TableContainer>\n {enableActionBar &&\n selectedIds &&\n selectedIds.length > 0 &&\n renderSelectionBar()}\n <div\n ref={(r) => {\n tableEndRef.current = r;\n endRef(r);\n }}\n />\n </TableWrapper>\n );\n};\n"],"names":["DataTable","_a","id","headers","rows","className","sortIndicators","alternatingRows","loadState","enableMultiSelect","selectedIds","disabledIds","enableActionBar","enableSelectAll","enableStickyHeader","emptyView","actionBarContent","renderCustomEmptyView","onHeaderClick","onSelect","onSelectAll","onClearSelectionClick","otherProps","__rest","tableRef","useRef","tableEndRef","headerRef","actionBarRef","wrapperRef","internalId","useId","keyColumns","filter","header","keyColumn","scrollable","setScrollable","useState","scrollEnd","setScrollEnd","tableEnd","setTableEnd","isFloatingActionBar","setIsFloatingActionBar","showLastBorder","setShowLastBorder","ref","endRef","inView","end","useInView","onResize","useCallback","current","scrollHeight","clientHeight","style","transform","calculateStickyInViewport","useEffect","useResizeDetector","useEventListener","requestAnimationFrame","calculateFixedInViewport","getBoundingClientRect","bottom","window","innerHeight","checkLastBorder","isAllCheckboxSelected","length","isRowSelected","rowId","includes","isAlternatingRow","index","isDisabledRow","getDataTestId","subStr","getTotalColumns","getSortDirection","fieldKey","getHeaderAriaSort","sortDirection","getSortButtonAriaLabel","getCellId","getRowCheckboxAriaLabelledBy","keyColumnIds","map","concatIds","wrapperBounds","top","endBounds","bottomOffset","bottomToHeaderOffset","height","maxBottomOffset","Math","min","renderHeaderCell","label","clickable","undefined","isSortable","headerCellWrapperId","getHeaderWrapperId","_jsxs","HeaderCell","$clickable","scope","$isCheckbox","onClick","handleHeaderClick","children","HeaderCellWrapper","_jsx","Typography","BodyBL","weight","renderSortedArrow","VisuallyHidden","event","stopPropagation","handleHeaderButtonClick","isSorted","ArrowUpIcon","ArrowDownIcon","renderHeaderCheckBox","CheckBoxWrapper","Checkbox","checked","indeterminate","disabled","renderRowCell","row","toString","cellData","cellId","BodyCell","BodyCellContent","isSelected","renderRowCheckBox","focusableWhenDisabled","renderBasicEmptyView","ErrorDisplay","Object","assign","type","title","ErrorDisplayTitle","description","TableWrapper","onScroll","scrollTop","tabIndex","TableContainer","Table","$end","$stickyHeader","HeaderRow","TableBody","$showLastRowBottomBorder","BodyRow","$alternating","EmptyViewCell","colSpan","$isSelectable","$isSelected","LoaderWrapper","role","LoadingDotsSpinner","count","ActionBarWrapper","$fixed","$left","_c","_b","left","$width","_d","clientWidth","ActionBar","$float","$scrollable","BodyMD","TextButton","renderSelectionBar","r"],"mappings":"kiDAgCO,MAAMA,EAAaC,QAAAC,GACtBA,EAAEC,QACFA,EAAOC,KACPA,EAAIC,UACJA,EAASC,eACTA,EAAcC,gBACdA,EAAeC,UACfA,EAAY,UAASC,kBACrBA,EAAiBC,YACjBA,EAAWC,YACXA,EAAWC,gBACXA,EAAeC,gBACfA,EAAeC,mBACfA,EAAkBC,UAClBA,EAASC,iBACTA,EAAgBC,sBAChBA,EAAqBC,cACrBA,GAAaC,SACbA,GAAQC,YACRA,GAAWC,sBACXA,MACGC,GAAUC,EAAAtB,EArBS,CAAA,KAAA,UAAA,OAAA,YAAA,iBAAA,kBAAA,YAAA,oBAAA,cAAA,cAAA,kBAAA,kBAAA,qBAAA,YAAA,mBAAA,wBAAA,gBAAA,WAAA,cAAA,0BA0BtB,MAAMuB,GAAWC,EAAyB,MACpCC,GAAcD,EAA8B,MAC5CE,GAAYF,EAAgC,MAC5CG,GAAeH,EAAuB,MACtCI,GAAaJ,EAAuB,MACpCK,GAAaC,IACbC,GAAa7B,EAAQ8B,QACtBC,GAC4B,iBAAXA,KAAyBA,EAAOC,aAI/CC,GAAYC,IAAiBC,GAAS,IACtCC,GAAWC,IAAgBF,GAAS,IACpCG,GAAUC,IAAeJ,GAAS,IAClCK,GAAqBC,IAA0BN,GAAS,IACxDO,GAAgBC,IAAqBR,GAAS,IAE7CS,IAAKC,GAAQC,OAAQC,IAAQC,IAK/BC,GAAWC,GAAY,KACzB,IAAKxB,GAAWyB,UAAY1B,GAAa0B,QACrC,OAEJ,MAAMlB,EACFP,GAAWyB,QAAQC,aAAe1B,GAAWyB,QAAQE,aACzDnB,GAAcD,GAEVA,EAC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E9CpJ,GAAU8E,SAAA,CAEvBE,EAACC,EAAWoE,OAAM,CAAClE,OAAO,WAAUL,SAAE,GAAG0D,SACrCA,EAAQ,EAAI,IAAM,gBAEtBxD,EAACsE,EAAU,CACPtC,KAAK,SAAQ,aACD,sBAAsBwB,SACpB,IAAVA,EAAc,GAAK,MAEvB5D,QAAS3F,GAAqB6F,SAAA,oBAIjClG,MAEU,EAuCf2K,GACJvE,EAAA,MAAA,CACIrE,IAAM6I,IACFlK,GAAY4B,QAAUsI,EACtB5I,GAAO4I,EAAE,MAGN"}
|
|
1
|
+
{"version":3,"file":"data-table.js","sources":["../../src/data-table/data-table.tsx"],"sourcesContent":["import { ArrowDownIcon, ArrowUpIcon } from \"@lifesg/react-icons\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { useResizeDetector } from \"react-resize-detector\";\nimport { LoadingDotsSpinner } from \"../animations\";\nimport { Checkbox } from \"../checkbox\";\nimport { ErrorDisplay } from \"../error-display\";\nimport { VisuallyHidden, concatIds } from \"../shared/accessibility\";\nimport { Typography } from \"../typography\";\nimport { useEvent, useEventListener, useId, useThrottle } from \"../util\";\nimport {\n ActionBar,\n ActionBarSpacer,\n ActionBarWrapper,\n BodyCell,\n BodyCellContent,\n BodyRow,\n CheckBoxWrapper,\n EmptyViewCell,\n ErrorDisplayTitle,\n HeaderCell,\n HeaderCellWrapper,\n HeaderRow,\n LoaderWrapper,\n Table,\n TableBody,\n TableContainer,\n TableHead,\n TableWrapper,\n TextButton,\n} from \"./data-table.styles\";\nimport { DataTableProps, HeaderProps, RowProps } from \"./types\";\n\nexport const DataTable = ({\n id,\n headers,\n rows,\n className,\n sortIndicators,\n alternatingRows,\n loadState = \"success\",\n enableMultiSelect,\n selectedIds,\n disabledIds,\n enableActionBar,\n enableSelectAll,\n enableStickyHeader,\n emptyView,\n actionBarContent,\n renderCustomEmptyView,\n onHeaderClick,\n onSelect,\n onSelectAll,\n onClearSelectionClick,\n ...otherProps\n}: DataTableProps) => {\n // =============================================================================\n // CONST, STATE, REF\n // =============================================================================\n const tableRef = useRef<HTMLTableElement>(null);\n const headerRef = useRef<HTMLTableSectionElement>(null);\n const actionBarWrapperRef = useRef<HTMLDivElement>(null);\n const wrapperRef = useRef<HTMLDivElement>(null);\n const internalId = useId();\n const keyColumns = headers.filter(\n (header): header is Exclude<HeaderProps, string> => {\n return typeof header !== \"string\" && !!header.keyColumn;\n }\n );\n\n const [actionBarStrategy, setActionBarStrategy] = useState<\n \"sticky\" | \"fixed\" | \"inline\"\n >(\"inline\");\n const [scrollable, setScrollable] = useState(false);\n const [isFloatingActionBar, setIsFloatingActionBar] = useState(false);\n\n // =============================================================================\n // EFFECTS, EVENT LISTENERS\n // ============================================================================\n const useUpdateActionBarBehaviour = useEvent(() => {\n updateActionBarBehaviour();\n });\n\n useEffect(() => {\n useUpdateActionBarBehaviour();\n }, [useUpdateActionBarBehaviour]);\n\n const updateActionBarBehaviourThrottled = useThrottle(\n () => updateActionBarBehaviour(),\n 100\n );\n\n useResizeDetector({\n targetRef: wrapperRef,\n onResize: () => updateActionBarBehaviourThrottled(),\n });\n\n useEventListener(\"scroll\", updateActionBarBehaviourThrottled);\n useEventListener(\n \"scroll\",\n updateActionBarBehaviourThrottled,\n wrapperRef.current\n );\n\n // ===========================================================================\n // HELPER FUNCTIONS\n // ===========================================================================\n const isAllCheckboxSelected = (): boolean => {\n if (!rows || !rows.length || !selectedIds) {\n return false;\n }\n\n return selectedIds.length === rows.length;\n };\n\n const isIndeterminateCheckbox = (): boolean => {\n return (\n !!selectedIds &&\n selectedIds.length !== 0 &&\n !isAllCheckboxSelected()\n );\n };\n\n const isHeaderCheckboxDisabled = (): boolean => {\n return !rows || !rows.length || !selectedIds;\n };\n\n const isRowSelected = (rowId: string): boolean => {\n return !!selectedIds?.includes(rowId);\n };\n\n const isAlternatingRow = (index: number): boolean => {\n return !!alternatingRows && index % 2 === 1;\n };\n\n const isDisabledRow = (rowId: string): boolean => {\n return !!disabledIds?.includes(rowId);\n };\n\n const getDataTestId = (subStr: string) => {\n if (!otherProps[\"data-testid\"]) return undefined;\n return `${otherProps[\"data-testid\"]}-${subStr}`;\n };\n\n const getTotalColumns = (): number => {\n return headers.length + (enableMultiSelect ? 1 : 0);\n };\n\n const getSortDirection = (fieldKey: string) => {\n return sortIndicators?.[fieldKey];\n };\n\n const getHeaderAriaSort = (fieldKey: string) => {\n const sortDirection = getSortDirection(fieldKey);\n\n if (!sortDirection) {\n return undefined;\n }\n\n return sortDirection === \"asc\" ? \"ascending\" : \"descending\";\n };\n\n const getSortButtonAriaLabel = (fieldKey: string) => {\n const nextSortDirection =\n getSortDirection(fieldKey) === \"asc\" ? \"descending\" : \"ascending\";\n\n return ` by ${nextSortDirection} order`;\n };\n\n const getHeaderWrapperId = (fieldKey: string) => {\n return `${internalId}-header-${fieldKey}`;\n };\n const getCellId = (rowId: string, fieldKey: string) => {\n return `${internalId}-row-${rowId}-${fieldKey}-key-column`;\n };\n\n const getRowCheckboxAriaLabelledBy = (rowId: string) => {\n const keyColumnIds = keyColumns.map((header) =>\n getCellId(rowId, header.fieldKey)\n );\n\n return concatIds(...keyColumnIds);\n };\n\n const updateActionBarBehaviour = () => {\n if (\n !wrapperRef.current ||\n !headerRef.current ||\n !actionBarWrapperRef.current\n ) {\n return;\n }\n\n const wrapperBounds = wrapperRef.current.getBoundingClientRect();\n const headerBounds = headerRef.current.getBoundingClientRect();\n\n let strategy: typeof actionBarStrategy = \"inline\";\n\n const scrollable =\n wrapperRef.current.scrollHeight > wrapperRef.current.clientHeight;\n\n if (\n wrapperBounds.top > window.innerHeight ||\n wrapperBounds.bottom < 0\n ) {\n // if fully out of the viewport, disable floating\n strategy = \"inline\";\n } else if (scrollable) {\n if (\n wrapperBounds.top > 0 &&\n wrapperBounds.top < window.innerHeight &&\n wrapperBounds.bottom > 0 &&\n wrapperBounds.bottom < window.innerHeight\n ) {\n // if fully in the viewport, use the native sticky behaviour\n strategy = \"sticky\";\n } else if (\n wrapperBounds.top < 0 &&\n wrapperBounds.bottom > 0 &&\n wrapperBounds.bottom < window.innerHeight\n ) {\n // if partially offscreen at the top, use the native sticky behaviour\n strategy = \"sticky\";\n } else if (\n wrapperBounds.bottom > window.innerHeight &&\n Math.max(wrapperBounds.top, headerBounds.bottom) +\n headerBounds.height <\n window.innerHeight\n ) {\n // if offscreen at the bottom, pin to the viewport, up until the table/header\n strategy = \"fixed\";\n }\n } else if (\n wrapperBounds.bottom > window.innerHeight &&\n headerBounds.bottom + headerBounds.height < window.innerHeight\n ) {\n // if offscreen at the bottom, pin to the viewport, up until the header\n strategy = \"fixed\";\n }\n\n setScrollable(scrollable);\n setActionBarStrategy(strategy);\n\n if (strategy === \"fixed\") {\n setIsFloatingActionBar(true);\n } else if (strategy === \"sticky\") {\n const beforeScrollEnd =\n wrapperRef.current.scrollTop + wrapperRef.current.clientHeight <\n wrapperRef.current.scrollHeight;\n setIsFloatingActionBar(beforeScrollEnd);\n } else {\n setIsFloatingActionBar(false);\n }\n };\n\n // =============================================================================\n // EVENT HANDLERS\n // =============================================================================\n const handleHeaderClick = (fieldKey: string) => {\n onHeaderClick?.(fieldKey);\n };\n\n const handleHeaderButtonClick = (\n event: React.MouseEvent<HTMLButtonElement>,\n fieldKey: string\n ) => {\n event.stopPropagation();\n onHeaderClick?.(fieldKey);\n };\n\n // =============================================================================\n // RENDER FUNCTIONS\n // =============================================================================\n const renderHeaders = () => (\n <TableHead ref={headerRef} $stickyHeader={enableStickyHeader}>\n <HeaderRow>\n {enableMultiSelect && renderHeaderCheckBox()}\n {headers.map(renderHeaderCell)}\n </HeaderRow>\n </TableHead>\n );\n\n const renderHeaderCell = (header: HeaderProps) => {\n const {\n fieldKey,\n label,\n clickable = false,\n style,\n } = typeof header === \"string\"\n ? {\n fieldKey: header,\n label: header,\n style: undefined,\n }\n : header;\n\n const isSortable = !!getSortDirection(fieldKey);\n const headerCellWrapperId = getHeaderWrapperId(fieldKey);\n\n return (\n <HeaderCell\n data-testid={getDataTestId(`header-${fieldKey}`)}\n key={fieldKey}\n $clickable={clickable}\n scope=\"col\"\n aria-sort={getHeaderAriaSort(fieldKey)}\n style={style}\n $isCheckbox={false}\n onClick={() => handleHeaderClick(fieldKey)}\n >\n <HeaderCellWrapper id={headerCellWrapperId}>\n {typeof label === \"string\" ? (\n <Typography.BodyBL weight=\"bold\">\n {label}\n </Typography.BodyBL>\n ) : (\n label\n )}\n {renderSortedArrow(fieldKey)}\n </HeaderCellWrapper>\n {(clickable || isSortable) && (\n <VisuallyHidden>\n <button\n onClick={(event) =>\n handleHeaderButtonClick(event, fieldKey)\n }\n >\n {isSortable && \"Sort \"}\n <span aria-labelledby={headerCellWrapperId} />\n {isSortable && getSortButtonAriaLabel(fieldKey)}\n </button>\n </VisuallyHidden>\n )}\n </HeaderCell>\n );\n };\n\n const renderSortedArrow = (fieldKey: string) => {\n const isSorted = sortIndicators?.[fieldKey];\n\n if (!isSorted) {\n return <></>;\n }\n if (isSorted === \"asc\") {\n return (\n <ArrowUpIcon\n aria-hidden\n data-testid={getDataTestId(`header-${fieldKey}-arrowup`)}\n />\n );\n }\n return (\n <ArrowDownIcon\n aria-hidden\n data-testid={getDataTestId(`header-${fieldKey}-arrowdown`)}\n />\n );\n };\n\n const renderHeaderCheckBox = () => {\n return (\n <HeaderCell\n data-testid={getDataTestId(\"header-selection\")}\n $clickable={false}\n $isCheckbox={true}\n scope=\"col\"\n >\n <CheckBoxWrapper>\n <VisuallyHidden>Row selection</VisuallyHidden>\n {enableSelectAll && (\n <Checkbox\n checked={isAllCheckboxSelected()}\n indeterminate={isIndeterminateCheckbox()}\n disabled={isHeaderCheckboxDisabled()}\n aria-label=\"Select all rows\"\n onClick={() => {\n if (onSelectAll) {\n onSelectAll(isAllCheckboxSelected());\n }\n }}\n />\n )}\n </CheckBoxWrapper>\n </HeaderCell>\n );\n };\n\n const renderRows = () => {\n return !rows || rows.length < 1 ? (\n <BodyRow $alternating={false}>\n <EmptyViewCell colSpan={getTotalColumns()}>\n {renderCustomEmptyView\n ? renderCustomEmptyView()\n : renderBasicEmptyView()}\n </EmptyViewCell>\n </BodyRow>\n ) : (\n <>\n {rows?.map((row: RowProps, index: number) => (\n <BodyRow\n data-testid={getDataTestId(`row-${row.id.toString()}`)}\n key={row.id.toString()}\n $showLastRowBottomBorder={isFloatingActionBar}\n $alternating={isAlternatingRow(index)}\n $isSelectable={enableMultiSelect}\n $isSelected={isRowSelected(row.id.toString())}\n >\n {enableMultiSelect && renderRowCheckBox(row)}\n\n {headers.map((header) => renderRowCell(header, row))}\n </BodyRow>\n ))}\n </>\n );\n };\n\n const renderRowCell = (header: HeaderProps, row: RowProps) => {\n const style = typeof header !== \"string\" ? header.style : undefined;\n const fieldKey = typeof header === \"string\" ? header : header.fieldKey;\n const rowId = row.id.toString();\n const cellData = row[fieldKey];\n const cellId = `${rowId}-${fieldKey}`;\n\n return (\n <BodyCell\n data-testid={getDataTestId(`row-${cellId}`)}\n key={cellId}\n id={getCellId(rowId, fieldKey)}\n style={style}\n $isCheckbox={false}\n >\n {typeof cellData === \"string\" ||\n typeof cellData === \"number\" ? (\n <BodyCellContent>{cellData}</BodyCellContent>\n ) : typeof cellData === \"function\" ? (\n cellData(row, { isSelected: isRowSelected(rowId) })\n ) : (\n cellData\n )}\n </BodyCell>\n );\n };\n\n const renderRowCheckBox = (row: RowProps) => {\n const rowId = row.id.toString();\n\n return (\n <BodyCell\n data-testid={getDataTestId(`row-${rowId}-selection`)}\n $isCheckbox={true}\n >\n <CheckBoxWrapper>\n <Checkbox\n checked={isRowSelected(rowId)}\n aria-labelledby={getRowCheckboxAriaLabelledBy(rowId)}\n onClick={() => {\n if (onSelect) {\n onSelect(rowId, !isRowSelected(rowId));\n }\n }}\n disabled={isDisabledRow(rowId)}\n focusableWhenDisabled={isDisabledRow(rowId)}\n />\n </CheckBoxWrapper>\n </BodyCell>\n );\n };\n\n const renderBasicEmptyView = () => {\n return (\n <ErrorDisplay\n type={\"no-item-found\"}\n {...emptyView}\n title={\n emptyView?.title ? (\n typeof emptyView.title === \"string\" ? (\n <ErrorDisplayTitle weight=\"bold\">\n {emptyView.title}\n </ErrorDisplayTitle>\n ) : (\n emptyView.title\n )\n ) : (\n <ErrorDisplayTitle weight=\"bold\">\n {\"No <items> found\"}\n </ErrorDisplayTitle>\n )\n }\n description={\n emptyView?.description\n ? emptyView.description\n : \"No matching rows\"\n }\n />\n );\n };\n\n const renderLoader = () => {\n return (\n <BodyRow $alternating={false}>\n <td colSpan={getTotalColumns()}>\n <LoaderWrapper\n role=\"status\"\n aria-live=\"polite\"\n aria-label=\"Loading table\"\n >\n {loadState === \"loading\" && <LoadingDotsSpinner />}\n </LoaderWrapper>\n </td>\n </BodyRow>\n );\n };\n\n const renderSelectionBar = () => {\n const count = selectedIds?.length ?? 0;\n const counter = `item${count > 1 ? \"s\" : \"\"}`;\n\n return (\n <>\n <ActionBarWrapper\n ref={actionBarWrapperRef}\n $strategy={actionBarStrategy}\n $left={\n isFloatingActionBar\n ? tableRef?.current?.getBoundingClientRect()?.left\n : 0\n }\n $width={tableRef?.current?.clientWidth}\n >\n <ActionBar $float={isFloatingActionBar}>\n <Typography.BodyMD weight=\"semibold\">{`${count} ${counter} selected`}</Typography.BodyMD>\n <TextButton\n type=\"button\"\n aria-label={`Clear selection of ${count} ${counter}`}\n onClick={onClearSelectionClick}\n >\n Clear selection\n </TextButton>\n {actionBarContent}\n </ActionBar>\n </ActionBarWrapper>\n {/* leave a fixed space when action bar floats to avoid layout shift */}\n {actionBarStrategy !== \"sticky\" && <ActionBarSpacer />}\n </>\n );\n };\n\n return (\n <TableWrapper\n id={id || \"table-wrapper\"}\n data-testid={otherProps[\"data-testid\"] || \"table\"}\n className={className}\n ref={wrapperRef}\n tabIndex={0} // scrollable container must be focusable to support keyboard users\n $scrollable={scrollable}\n >\n <TableContainer>\n <Table ref={tableRef}>\n {renderHeaders()}\n <TableBody>\n {loadState === \"success\"\n ? renderRows()\n : renderLoader()}\n </TableBody>\n </Table>\n </TableContainer>\n {enableActionBar &&\n selectedIds &&\n selectedIds.length > 0 &&\n renderSelectionBar()}\n </TableWrapper>\n );\n};\n"],"names":["DataTable","_a","id","headers","rows","className","sortIndicators","alternatingRows","loadState","enableMultiSelect","selectedIds","disabledIds","enableActionBar","enableSelectAll","enableStickyHeader","emptyView","actionBarContent","renderCustomEmptyView","onHeaderClick","onSelect","onSelectAll","onClearSelectionClick","otherProps","__rest","tableRef","useRef","headerRef","actionBarWrapperRef","wrapperRef","internalId","useId","keyColumns","filter","header","keyColumn","actionBarStrategy","setActionBarStrategy","useState","scrollable","setScrollable","isFloatingActionBar","setIsFloatingActionBar","useUpdateActionBarBehaviour","useEvent","updateActionBarBehaviour","useEffect","updateActionBarBehaviourThrottled","useThrottle","useResizeDetector","targetRef","onResize","useEventListener","current","isAllCheckboxSelected","length","isRowSelected","rowId","includes","isAlternatingRow","index","isDisabledRow","getDataTestId","subStr","getTotalColumns","getSortDirection","fieldKey","getHeaderAriaSort","sortDirection","getSortButtonAriaLabel","getCellId","getRowCheckboxAriaLabelledBy","keyColumnIds","map","concatIds","wrapperBounds","getBoundingClientRect","headerBounds","strategy","scrollHeight","clientHeight","top","window","innerHeight","bottom","Math","max","height","beforeScrollEnd","scrollTop","renderHeaderCell","label","clickable","style","undefined","isSortable","headerCellWrapperId","getHeaderWrapperId","_jsxs","HeaderCell","$clickable","scope","$isCheckbox","onClick","handleHeaderClick","children","HeaderCellWrapper","_jsx","Typography","BodyBL","weight","renderSortedArrow","VisuallyHidden","event","stopPropagation","handleHeaderButtonClick","isSorted","ArrowUpIcon","ArrowDownIcon","renderHeaderCheckBox","CheckBoxWrapper","Checkbox","checked","indeterminate","disabled","renderRowCell","row","toString","cellData","cellId","BodyCell","BodyCellContent","isSelected","renderRowCheckBox","focusableWhenDisabled","renderBasicEmptyView","ErrorDisplay","Object","assign","type","title","ErrorDisplayTitle","description","TableWrapper","ref","tabIndex","$scrollable","TableContainer","Table","TableHead","$stickyHeader","HeaderRow","TableBody","BodyRow","$alternating","EmptyViewCell","colSpan","$isSelected","LoaderWrapper","role","LoadingDotsSpinner","count","counter","_Fragment","ActionBarWrapper","$strategy","$left","_c","_b","left","$width","_d","clientWidth","ActionBar","$float","BodyMD","TextButton","ActionBarSpacer","renderSelectionBar"],"mappings":"8kDAgCO,MAAMA,EAAaC,QAAAC,GACtBA,EAAEC,QACFA,EAAOC,KACPA,EAAIC,UACJA,EAASC,eACTA,EAAcC,gBACdA,EAAeC,UACfA,EAAY,UAASC,kBACrBA,EAAiBC,YACjBA,EAAWC,YACXA,EAAWC,gBACXA,EAAeC,gBACfA,EAAeC,mBACfA,EAAkBC,UAClBA,EAASC,iBACTA,GAAgBC,sBAChBA,GAAqBC,cACrBA,GAAaC,SACbA,GAAQC,YACRA,GAAWC,sBACXA,MACGC,GAAUC,EAAAtB,EArBS,CAAA,KAAA,UAAA,OAAA,YAAA,iBAAA,kBAAA,YAAA,oBAAA,cAAA,cAAA,kBAAA,kBAAA,qBAAA,YAAA,mBAAA,wBAAA,gBAAA,WAAA,cAAA,0BA0BtB,MAAMuB,GAAWC,EAAyB,MACpCC,GAAYD,EAAgC,MAC5CE,GAAsBF,EAAuB,MAC7CG,GAAaH,EAAuB,MACpCI,GAAaC,IACbC,GAAa5B,EAAQ6B,QACtBC,GAC4B,iBAAXA,KAAyBA,EAAOC,aAI/CC,GAAmBC,IAAwBC,EAEhD,WACKC,GAAYC,IAAiBF,GAAS,IACtCG,GAAqBC,IAA0BJ,GAAS,GAKzDK,GAA8BC,GAAS,KACzCC,IAA0B,IAG9BC,GAAU,KACNH,IAA6B,GAC9B,CAACA,KAEJ,MAAMI,GAAoCC,GACtC,IAAMH,MACN,KAGJI,EAAkB,CACdC,UAAWrB,GACXsB,SAAU,IAAMJ,OAGpBK,EAAiB,SAAUL,IAC3BK,EACI,SACAL,GACAlB,GAAWwB,SAMf,MAAMC,GAAwB,OACrBjD,GAASA,EAAKkD,QAAW5C,IAIvBA,EAAY4C,SAAWlD,EAAKkD,OAejCC,G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
4
|
-
$stickyHeader: boolean | undefined;
|
|
5
3
|
}
|
|
6
|
-
interface
|
|
7
|
-
$
|
|
4
|
+
interface TableHeadProps {
|
|
5
|
+
$stickyHeader: boolean | undefined;
|
|
8
6
|
}
|
|
9
7
|
interface HeaderCellProps {
|
|
10
8
|
$clickable: boolean;
|
|
@@ -14,23 +12,24 @@ interface BodyRowProps {
|
|
|
14
12
|
$alternating: boolean;
|
|
15
13
|
$isSelected?: boolean;
|
|
16
14
|
$isSelectable?: boolean;
|
|
15
|
+
$showLastRowBottomBorder?: boolean;
|
|
17
16
|
}
|
|
18
17
|
interface BodyCellProps {
|
|
19
18
|
$isCheckbox: boolean;
|
|
20
19
|
}
|
|
21
20
|
interface ActionBarWrapperProps {
|
|
22
|
-
$
|
|
21
|
+
$strategy: "fixed" | "sticky" | "inline";
|
|
23
22
|
$left?: number | undefined;
|
|
24
23
|
$width?: number | undefined;
|
|
25
24
|
}
|
|
26
25
|
interface ActionBarProps {
|
|
27
26
|
$float: boolean;
|
|
28
|
-
$scrollable: boolean;
|
|
29
27
|
}
|
|
30
|
-
export declare const TableWrapper: import("styled-components/dist/types").IStyledComponentBase<"web", import("styled-components").FastOmit<import("react").DetailedHTMLProps<import("react").HTMLAttributes<HTMLDivElement>, HTMLDivElement>, never> & Partial<Pick<import("react").DetailedHTMLProps<import("react").HTMLAttributes<HTMLDivElement>, HTMLDivElement>, never>>> & string;
|
|
28
|
+
export declare const TableWrapper: import("styled-components/dist/types").IStyledComponentBase<"web", import("styled-components").FastOmit<import("styled-components").FastOmit<import("react").DetailedHTMLProps<import("react").HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "$scrollable"> & TableWrapperProps, never> & Partial<Pick<import("styled-components").FastOmit<import("react").DetailedHTMLProps<import("react").HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "$scrollable"> & TableWrapperProps, never>>> & string;
|
|
31
29
|
export declare const TableContainer: import("styled-components/dist/types").IStyledComponentBase<"web", import("styled-components").FastOmit<import("react").DetailedHTMLProps<import("react").HTMLAttributes<HTMLDivElement>, HTMLDivElement>, never> & Partial<Pick<import("react").DetailedHTMLProps<import("react").HTMLAttributes<HTMLDivElement>, HTMLDivElement>, never>>> & string;
|
|
32
|
-
export declare const Table: import("styled-components/dist/types").IStyledComponentBase<"web", import("styled-components").FastOmit<import("
|
|
33
|
-
export declare const
|
|
30
|
+
export declare const Table: import("styled-components/dist/types").IStyledComponentBase<"web", import("styled-components").FastOmit<import("react").DetailedHTMLProps<import("react").TableHTMLAttributes<HTMLTableElement>, HTMLTableElement>, never> & Partial<Pick<import("react").DetailedHTMLProps<import("react").TableHTMLAttributes<HTMLTableElement>, HTMLTableElement>, never>>> & string;
|
|
31
|
+
export declare const TableHead: import("styled-components/dist/types").IStyledComponentBase<"web", import("styled-components").FastOmit<import("styled-components").FastOmit<import("react").DetailedHTMLProps<import("react").HTMLAttributes<HTMLTableSectionElement>, HTMLTableSectionElement>, "$stickyHeader"> & TableHeadProps, never> & Partial<Pick<import("styled-components").FastOmit<import("react").DetailedHTMLProps<import("react").HTMLAttributes<HTMLTableSectionElement>, HTMLTableSectionElement>, "$stickyHeader"> & TableHeadProps, never>>> & string;
|
|
32
|
+
export declare const TableBody: import("styled-components/dist/types").IStyledComponentBase<"web", import("styled-components").FastOmit<import("react").DetailedHTMLProps<import("react").HTMLAttributes<HTMLTableSectionElement>, HTMLTableSectionElement>, never> & Partial<Pick<import("react").DetailedHTMLProps<import("react").HTMLAttributes<HTMLTableSectionElement>, HTMLTableSectionElement>, never>>> & string;
|
|
34
33
|
export declare const ActionBarWrapper: import("styled-components/dist/types").IStyledComponentBase<"web", import("styled-components").FastOmit<import("styled-components").FastOmit<import("react").DetailedHTMLProps<import("react").HTMLAttributes<HTMLDivElement>, HTMLDivElement>, keyof ActionBarWrapperProps> & ActionBarWrapperProps, never> & Partial<Pick<import("styled-components").FastOmit<import("react").DetailedHTMLProps<import("react").HTMLAttributes<HTMLDivElement>, HTMLDivElement>, keyof ActionBarWrapperProps> & ActionBarWrapperProps, never>>> & string;
|
|
35
34
|
export declare const TextButton: import("styled-components/dist/types").IStyledComponentBase<"web", import("styled-components").FastOmit<Omit<import("styled-components").FastOmit<import("styled-components").FastOmit<import("react").DetailedHTMLProps<import("react").ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "$variant"> & import("../shared/input-wrapper").InputStyleProps, never> & Partial<Pick<import("styled-components").FastOmit<import("react").DetailedHTMLProps<import("react").ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "$variant"> & import("../shared/input-wrapper").InputStyleProps, never>> & {
|
|
36
35
|
as?: import("styled-components").WebTarget | undefined;
|
|
@@ -43,7 +42,8 @@ export declare const TextButton: import("styled-components/dist/types").IStyledC
|
|
|
43
42
|
}, "ref"> & {
|
|
44
43
|
ref?: ((instance: HTMLButtonElement | null) => void) | import("react").RefObject<HTMLButtonElement> | null | undefined;
|
|
45
44
|
}, never>>> & string;
|
|
46
|
-
export declare const ActionBar: import("styled-components/dist/types").IStyledComponentBase<"web", import("styled-components").FastOmit<import("styled-components").FastOmit<import("react").DetailedHTMLProps<import("react").HTMLAttributes<HTMLDivElement>, HTMLDivElement>,
|
|
45
|
+
export declare const ActionBar: import("styled-components/dist/types").IStyledComponentBase<"web", import("styled-components").FastOmit<import("styled-components").FastOmit<import("react").DetailedHTMLProps<import("react").HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "$float"> & ActionBarProps, never> & Partial<Pick<import("styled-components").FastOmit<import("react").DetailedHTMLProps<import("react").HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "$float"> & ActionBarProps, never>>> & string;
|
|
46
|
+
export declare const ActionBarSpacer: import("styled-components/dist/types").IStyledComponentBase<"web", import("styled-components").FastOmit<import("react").DetailedHTMLProps<import("react").HTMLAttributes<HTMLDivElement>, HTMLDivElement>, never> & Partial<Pick<import("react").DetailedHTMLProps<import("react").HTMLAttributes<HTMLDivElement>, HTMLDivElement>, never>>> & string;
|
|
47
47
|
export declare const HeaderRow: import("styled-components/dist/types").IStyledComponentBase<"web", import("styled-components").FastOmit<import("react").DetailedHTMLProps<import("react").HTMLAttributes<HTMLTableRowElement>, HTMLTableRowElement>, never> & Partial<Pick<import("react").DetailedHTMLProps<import("react").HTMLAttributes<HTMLTableRowElement>, HTMLTableRowElement>, never>>> & string;
|
|
48
48
|
export declare const HeaderCell: import("styled-components/dist/types").IStyledComponentBase<"web", import("styled-components").FastOmit<import("styled-components").FastOmit<import("react").DetailedHTMLProps<import("react").ThHTMLAttributes<HTMLTableHeaderCellElement>, HTMLTableHeaderCellElement>, keyof HeaderCellProps> & HeaderCellProps, never> & Partial<Pick<import("styled-components").FastOmit<import("react").DetailedHTMLProps<import("react").ThHTMLAttributes<HTMLTableHeaderCellElement>, HTMLTableHeaderCellElement>, keyof HeaderCellProps> & HeaderCellProps, never>>> & string;
|
|
49
49
|
export declare const HeaderCellWrapper: import("styled-components/dist/types").IStyledComponentBase<"web", import("styled-components").FastOmit<import("react").DetailedHTMLProps<import("react").HTMLAttributes<HTMLDivElement>, HTMLDivElement>, never> & Partial<Pick<import("react").DetailedHTMLProps<import("react").HTMLAttributes<HTMLDivElement>, HTMLDivElement>, never>>> & string;
|