@ahrowe/ui 0.30.0 → 0.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/common/tree/tree.mjs +1 -1
- package/dist/esm/common/tree/tree.mjs.map +1 -1
- package/dist/esm/common/virtualList/useColumnResize.mjs +2 -0
- package/dist/esm/common/virtualList/useColumnResize.mjs.map +1 -0
- package/dist/esm/common/virtualList/useColumns.mjs +1 -1
- package/dist/esm/common/virtualList/useColumns.mjs.map +1 -1
- package/dist/esm/common/virtualList/useHeaderNavigation.mjs +2 -0
- package/dist/esm/common/virtualList/useHeaderNavigation.mjs.map +1 -0
- package/dist/esm/common/virtualList/useRowNavigation.mjs +2 -0
- package/dist/esm/common/virtualList/useRowNavigation.mjs.map +1 -0
- package/dist/esm/common/virtualList/useSorting.mjs +2 -0
- package/dist/esm/common/virtualList/useSorting.mjs.map +1 -0
- package/dist/esm/common/virtualList/useVirtualWindow.mjs +1 -1
- package/dist/esm/common/virtualList/useVirtualWindow.mjs.map +1 -1
- package/dist/esm/common/virtualList/virtualList.mjs +1 -1
- package/dist/esm/common/virtualList/virtualList.mjs.map +1 -1
- package/dist/esm/common/virtualList/virtualList.module.mjs +1 -1
- package/dist/esm/common/virtualList/virtualList.module.mjs.map +1 -1
- package/dist/esm/common/virtualList/virtualList.utils.mjs +1 -1
- package/dist/esm/common/virtualList/virtualList.utils.mjs.map +1 -1
- package/dist/esm/common/virtualList/virtualListHeader.mjs +2 -0
- package/dist/esm/common/virtualList/virtualListHeader.mjs.map +1 -0
- package/dist/esm/common/virtualList/virtualRow.mjs +1 -1
- package/dist/esm/common/virtualList/virtualRow.mjs.map +1 -1
- package/dist/index.cjs +3 -3
- package/dist/index.cjs.map +1 -1
- package/dist/style.css +1 -1
- package/dist/types/common/virtualList/useColumnResize.d.ts +59 -0
- package/dist/types/common/virtualList/useColumns.d.ts +12 -2
- package/dist/types/common/virtualList/useHeaderNavigation.d.ts +22 -0
- package/dist/types/common/virtualList/useRowNavigation.d.ts +50 -0
- package/dist/types/common/virtualList/useSorting.d.ts +26 -0
- package/dist/types/common/virtualList/useVirtualWindow.d.ts +1 -8
- package/dist/types/common/virtualList/virtualList.d.ts +1 -1
- package/dist/types/common/virtualList/virtualList.types.d.ts +82 -1
- package/dist/types/common/virtualList/virtualList.utils.d.ts +83 -1
- package/dist/types/common/virtualList/virtualListHeader.d.ts +35 -0
- package/dist/types/common/virtualList/virtualRow.d.ts +14 -1
- package/docs/VirtualList.md +125 -7
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{useComponentDefaults as e}from"../configProvider/useComponentDefaults.mjs";import{renderIcon as t}from"../utils/renderIcon.mjs";import n from"../virtualList/virtualList.mjs";import{flattenTree as r}from"./flattenTree.mjs";import i from"./tree.module.mjs";import{useEffect as a,useRef as o,useState as s}from"react";import c from"classnames";import{faChevronRight as l}from"@fortawesome/free-solid-svg-icons";import{jsx as u,jsxs as d}from"react/jsx-runtime";var f=[];function p(p){let{nodes:m,expandedKeys:h,defaultExpandedKeys:g=f,onExpandedChange:_=()=>{},selectedKey:v,defaultSelectedKey:y,onSelect:b=()=>{},expandOnSelect:x=!0,indent:S=20,toggleIcon:C=l,height:w,estimatedRowHeight:T=32,emptyLabel:ee=`Nothing here`,disabled:E=!1,"aria-label":D=`Tree`,className:O,style:k,classNames:A,styles:j,...M}=e(`Tree`,p),N=o(new Map),P=o(null),F=o(null),I=w!==void 0,L=h!==void 0,[R,z]=s(g),B=L?h:R,V=v!==void 0,[H,U]=s(y??null),W=V?v:H,G=r(m,B),K=Math.max(0,G.findIndex(e=>e.node.key===W)),q=G[K]?.node.key;function J(e){L||z(e),_(e)}function Y(e){J(B.includes(e)?B.filter(t=>t!==e):[...B,e])}function X(e){E||e.node.disabled||(V||U(e.node.key),b(e.node.key,e.node),x&&e.isBranch&&Y(e.node.key))}function Z(e){let t=G[e]?.node.key;if(t===void 0)return;let n=N.current.get(t);if(n){n.focus();return}F.current=t,P.current?.scrollToIndex(e,{align:`center`})}a(()=>{let e=F.current;if(e===null)return;let t=N.current.get(e);t&&(t.focus(),F.current=null)});function Q(e,t,n){if(!E)switch(e.key){case`ArrowDown`:e.preventDefault(),Z(Math.min(n+1,G.length-1));break;case`ArrowUp`:e.preventDefault(),Z(Math.max(n-1,0));break;case`ArrowRight`:if(e.preventDefault(),!t.isBranch)break;t.isExpanded?Z(n+1):Y(t.node.key);break;case`ArrowLeft`:{if(e.preventDefault(),t.isBranch&&t.isExpanded){Y(t.node.key);break}let n=G.findIndex(e=>e.node.key===t.parentKey);n>=0&&Z(n);break}case`Home`:e.preventDefault(),Z(0);break;case`End`:e.preventDefault(),Z(G.length-1);break;case`Enter`:case` `:e.preventDefault(),X(t)}}function $(e,n){let{node:r,level:a,isBranch:o,isExpanded:s}=e,l=r.key===W,f=E||r.disabled;return d(`div`,{ref:e=>{e?N.current.set(r.key,e):N.current.delete(r.key)},role:`treeitem`,"aria-level":a+1,"aria-setsize":e.setSize,"aria-posinset":e.posInSet,"aria-expanded":o?s:void 0,"aria-selected":l,"aria-disabled":f||void 0,tabIndex:r.key===q&&!f?0:-1,className:c(i.treeNode,l&&i.treeNodeSelected,f&&i.treeNodeDisabled,A?.node),style:{paddingLeft:a*S,...j?.node},onClick:()=>X(e),onKeyDown:t=>Q(t,e,n),children:[u(`span`,{className:c(i.treeToggle,s&&i.treeToggleOpen,!o&&i.treeToggleHidden,A?.toggle),style:j?.toggle,"aria-hidden":`true`,onClick:e=>{e.stopPropagation(),!f&&o&&Y(r.key)},children:o&&t(C)}),r.icon&&t(r.icon,{className:c(i.treeIcon,A?.icon),style:j?.icon}),u(`span`,{className:c(i.treeLabel,A?.label),style:j?.label,children:r.label})]},r.key)}return u(`div`,{...M,role:`tree`,"aria-label":D,"aria-disabled":E||void 0,tabIndex:I&&!E?0:void 0,onFocus:e=>{e.target===e.currentTarget&&Z(K)},className:c(i.tree,E&&i.treeDisabled,A?.root,O),style:{...k,...j?.root},children:G.length===0?u(`div`,{className:c(i.treeEmpty,A?.empty),style:j?.empty,children:ee}):I?u(n,{ref:P,items:G,height:w,estimatedRowHeight:T,getItemKey:e=>e.node.key,getItemDepth:e=>e.level,ariaRoles:{container:`none`,row:`none`},renderRow:$}):G.map($)})}export{p as default};
|
|
1
|
+
import{useComponentDefaults as e}from"../configProvider/useComponentDefaults.mjs";import{renderIcon as t}from"../utils/renderIcon.mjs";import n from"../virtualList/virtualList.mjs";import{flattenTree as r}from"./flattenTree.mjs";import i from"./tree.module.mjs";import{useEffect as a,useRef as o,useState as s}from"react";import c from"classnames";import{faChevronRight as l}from"@fortawesome/free-solid-svg-icons";import{jsx as u,jsxs as d}from"react/jsx-runtime";var f=[];function p(p){let{nodes:m,expandedKeys:h,defaultExpandedKeys:g=f,onExpandedChange:_=()=>{},selectedKey:v,defaultSelectedKey:y,onSelect:b=()=>{},expandOnSelect:x=!0,indent:S=20,toggleIcon:C=l,height:w,estimatedRowHeight:T=32,emptyLabel:ee=`Nothing here`,disabled:E=!1,"aria-label":D=`Tree`,className:O,style:k,classNames:A,styles:j,...M}=e(`Tree`,p),N=o(new Map),P=o(null),F=o(null),I=w!==void 0,L=h!==void 0,[R,z]=s(g),B=L?h:R,V=v!==void 0,[H,U]=s(y??null),W=V?v:H,G=r(m,B),K=Math.max(0,G.findIndex(e=>e.node.key===W)),q=G[K]?.node.key;function J(e){L||z(e),_(e)}function Y(e){J(B.includes(e)?B.filter(t=>t!==e):[...B,e])}function X(e){E||e.node.disabled||(V||U(e.node.key),b(e.node.key,e.node),x&&e.isBranch&&Y(e.node.key))}function Z(e){let t=G[e]?.node.key;if(t===void 0)return;let n=N.current.get(t);if(n){n.focus();return}F.current=t,P.current?.scrollToIndex(e,{align:`center`})}a(()=>{let e=F.current;if(e===null)return;let t=N.current.get(e);t&&(t.focus(),F.current=null)});function Q(e,t,n){if(!E)switch(e.key){case`ArrowDown`:e.preventDefault(),Z(Math.min(n+1,G.length-1));break;case`ArrowUp`:e.preventDefault(),Z(Math.max(n-1,0));break;case`ArrowRight`:if(e.preventDefault(),!t.isBranch)break;t.isExpanded?Z(n+1):Y(t.node.key);break;case`ArrowLeft`:{if(e.preventDefault(),t.isBranch&&t.isExpanded){Y(t.node.key);break}let n=G.findIndex(e=>e.node.key===t.parentKey);n>=0&&Z(n);break}case`Home`:e.preventDefault(),Z(0);break;case`End`:e.preventDefault(),Z(G.length-1);break;case`Enter`:case` `:e.preventDefault(),X(t)}}function $(e,n){let{node:r,level:a,isBranch:o,isExpanded:s}=e,l=r.key===W,f=E||r.disabled;return d(`div`,{ref:e=>{e?N.current.set(r.key,e):N.current.delete(r.key)},role:`treeitem`,"aria-level":a+1,"aria-setsize":e.setSize,"aria-posinset":e.posInSet,"aria-expanded":o?s:void 0,"aria-selected":l,"aria-disabled":f||void 0,tabIndex:r.key===q&&!f?0:-1,className:c(i.treeNode,l&&i.treeNodeSelected,f&&i.treeNodeDisabled,A?.node),style:{paddingLeft:a*S,...j?.node},onClick:()=>X(e),onKeyDown:t=>Q(t,e,n),children:[u(`span`,{className:c(i.treeToggle,s&&i.treeToggleOpen,!o&&i.treeToggleHidden,A?.toggle),style:j?.toggle,"aria-hidden":`true`,onClick:e=>{e.stopPropagation(),!f&&o&&Y(r.key)},children:o&&t(C)}),r.icon&&t(r.icon,{className:c(i.treeIcon,A?.icon),style:j?.icon}),u(`span`,{className:c(i.treeLabel,A?.label),style:j?.label,children:r.label})]},r.key)}return u(`div`,{...M,role:`tree`,"aria-label":D,"aria-disabled":E||void 0,tabIndex:I&&!E?0:void 0,onFocus:e=>{e.target===e.currentTarget&&Z(K)},className:c(i.tree,E&&i.treeDisabled,A?.root,O),style:{...k,...j?.root},children:G.length===0?u(`div`,{className:c(i.treeEmpty,A?.empty),style:j?.empty,children:ee}):I?u(n,{ref:P,items:G,height:w,estimatedRowHeight:T,getItemKey:e=>e.node.key,getItemDepth:e=>e.level,ariaRoles:{container:`none`,row:`none`},keyboardNavigation:!1,renderRow:$}):G.map($)})}export{p as default};
|
|
2
2
|
//# sourceMappingURL=tree.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tree.mjs","names":[],"sources":["../../../../package/common/tree/tree.tsx"],"sourcesContent":["import { useEffect, useRef, useState } from 'react';\nimport type { ReactElement } from 'react';\nimport cx from 'classnames';\nimport { faChevronRight } from '@fortawesome/free-solid-svg-icons';\n\nimport VirtualList from 'components/common/virtualList';\nimport type { VirtualListHandle } from 'components/common/virtualList';\nimport { useComponentDefaults } from '../configProvider';\nimport { renderIcon } from '../utils/renderIcon';\nimport { flattenTree } from './flattenTree';\nimport type { FlatTreeNode, TreeProps, TreeValue } from './tree.types';\n\nimport styles from './tree.module.pcss';\n\nconst EMPTY_KEYS: TreeValue[] = [];\n\nfunction Tree(props: TreeProps): ReactElement {\n const {\n nodes,\n expandedKeys: controlledExpanded,\n defaultExpandedKeys = EMPTY_KEYS,\n onExpandedChange = () => {},\n selectedKey: controlledSelected,\n defaultSelectedKey,\n onSelect = () => {},\n expandOnSelect = true,\n indent = 20,\n toggleIcon = faChevronRight,\n height,\n estimatedRowHeight = 32,\n emptyLabel = 'Nothing here',\n disabled = false,\n 'aria-label': ariaLabel = 'Tree',\n className,\n style,\n classNames,\n styles: slotStyles,\n ...rest\n } = useComponentDefaults('Tree', props);\n\n const nodeRefs = useRef(new Map<TreeValue, HTMLDivElement>());\n const listRef = useRef<VirtualListHandle>(null);\n const pendingFocusRef = useRef<TreeValue | null>(null);\n const isWindowed = height !== undefined;\n\n const isExpandedControlled = controlledExpanded !== undefined;\n const [internalExpanded, setInternalExpanded] = useState<TreeValue[]>(defaultExpandedKeys);\n const expandedKeys = isExpandedControlled ? controlledExpanded : internalExpanded;\n\n const isSelectedControlled = controlledSelected !== undefined;\n const [internalSelected, setInternalSelected] = useState<TreeValue | null>(defaultSelectedKey ?? null);\n const selectedKey = isSelectedControlled ? controlledSelected : internalSelected;\n\n const visible = flattenTree(nodes, expandedKeys);\n\n // Windowed, the tab stop sits on the container instead of this row: a roving tabindex on a row\n // scrolled out of the window would leave the tree with no tab stop at all.\n const activeIndex = Math.max(\n 0,\n visible.findIndex((entry) => entry.node.key === selectedKey),\n );\n const activeKey = visible[activeIndex]?.node.key;\n\n function setExpanded(next: TreeValue[]) {\n if (!isExpandedControlled) setInternalExpanded(next);\n onExpandedChange(next);\n }\n\n function toggle(key: TreeValue) {\n setExpanded(expandedKeys.includes(key) ? expandedKeys.filter((k) => k !== key) : [...expandedKeys, key]);\n }\n\n function select(entry: FlatTreeNode) {\n if (disabled || entry.node.disabled) return;\n if (!isSelectedControlled) setInternalSelected(entry.node.key);\n onSelect(entry.node.key, entry.node);\n if (expandOnSelect && entry.isBranch) toggle(entry.node.key);\n }\n\n function focusAt(index: number) {\n const key = visible[index]?.node.key;\n if (key === undefined) return;\n\n const element = nodeRefs.current.get(key);\n if (element) {\n element.focus();\n return;\n }\n\n // Outside the window, so it has to be scrolled in before it exists to receive focus.\n pendingFocusRef.current = key;\n listRef.current?.scrollToIndex(index, { align: 'center' });\n }\n\n useEffect(() => {\n const key = pendingFocusRef.current;\n if (key === null) return;\n const element = nodeRefs.current.get(key);\n if (element) {\n element.focus();\n pendingFocusRef.current = null;\n }\n });\n\n function handleKeyDown(event: React.KeyboardEvent<HTMLDivElement>, entry: FlatTreeNode, index: number) {\n if (disabled) return;\n\n switch (event.key) {\n case 'ArrowDown':\n event.preventDefault();\n focusAt(Math.min(index + 1, visible.length - 1));\n break;\n case 'ArrowUp':\n event.preventDefault();\n focusAt(Math.max(index - 1, 0));\n break;\n case 'ArrowRight':\n event.preventDefault();\n if (!entry.isBranch) break;\n if (entry.isExpanded) focusAt(index + 1);\n else toggle(entry.node.key);\n break;\n case 'ArrowLeft': {\n event.preventDefault();\n if (entry.isBranch && entry.isExpanded) {\n toggle(entry.node.key);\n break;\n }\n const parentIndex = visible.findIndex((e) => e.node.key === entry.parentKey);\n if (parentIndex >= 0) focusAt(parentIndex);\n break;\n }\n case 'Home':\n event.preventDefault();\n focusAt(0);\n break;\n case 'End':\n event.preventDefault();\n focusAt(visible.length - 1);\n break;\n case 'Enter':\n case ' ':\n event.preventDefault();\n select(entry);\n break;\n default:\n break;\n }\n }\n\n function renderNode(entry: FlatTreeNode, index: number) {\n const { node, level, isBranch, isExpanded } = entry;\n const isSelected = node.key === selectedKey;\n const isDisabled = disabled || node.disabled;\n\n return (\n <div\n key={node.key}\n ref={(el) => {\n if (el) nodeRefs.current.set(node.key, el);\n else nodeRefs.current.delete(node.key);\n }}\n role='treeitem'\n aria-level={level + 1}\n aria-setsize={entry.setSize}\n aria-posinset={entry.posInSet}\n aria-expanded={isBranch ? isExpanded : undefined}\n aria-selected={isSelected}\n aria-disabled={isDisabled || undefined}\n tabIndex={node.key === activeKey && !isDisabled ? 0 : -1}\n className={cx(\n styles.treeNode,\n isSelected && styles.treeNodeSelected,\n isDisabled && styles.treeNodeDisabled,\n classNames?.node,\n )}\n style={{ paddingLeft: level * indent, ...slotStyles?.node }}\n onClick={() => select(entry)}\n onKeyDown={(event) => handleKeyDown(event, entry, index)}\n >\n <span\n className={cx(\n styles.treeToggle,\n isExpanded && styles.treeToggleOpen,\n !isBranch && styles.treeToggleHidden,\n classNames?.toggle,\n )}\n style={slotStyles?.toggle}\n aria-hidden='true'\n onClick={(event) => {\n event.stopPropagation();\n if (!isDisabled && isBranch) toggle(node.key);\n }}\n >\n {isBranch && renderIcon(toggleIcon)}\n </span>\n\n {node.icon &&\n renderIcon(node.icon, {\n className: cx(styles.treeIcon, classNames?.icon),\n style: slotStyles?.icon,\n })}\n\n <span className={cx(styles.treeLabel, classNames?.label)} style={slotStyles?.label}>\n {node.label}\n </span>\n </div>\n );\n }\n\n return (\n <div\n {...rest}\n role='tree'\n aria-label={ariaLabel}\n aria-disabled={disabled || undefined}\n tabIndex={isWindowed && !disabled ? 0 : undefined}\n onFocus={(event) => {\n if (event.target === event.currentTarget) focusAt(activeIndex);\n }}\n className={cx(styles.tree, disabled && styles.treeDisabled, classNames?.root, className)}\n style={{ ...style, ...slotStyles?.root }}\n >\n {visible.length === 0 ? (\n <div className={cx(styles.treeEmpty, classNames?.empty)} style={slotStyles?.empty}>\n {emptyLabel}\n </div>\n ) : isWindowed ? (\n <VirtualList\n ref={listRef}\n items={visible}\n height={height}\n estimatedRowHeight={estimatedRowHeight}\n getItemKey={(entry) => entry.node.key}\n getItemDepth={(entry) => entry.level}\n ariaRoles={{ container: 'none', row: 'none' }}\n renderRow={renderNode}\n />\n ) : (\n visible.map(renderNode)\n )}\n </div>\n );\n}\n\nexport default Tree;\n"],"mappings":"idAcA,IAAM,EAA0B,CAAC,EAEjC,SAAS,EAAK,EAAgC,CAC5C,GAAM,CACJ,QACA,aAAc,EACd,sBAAsB,EACtB,uBAAyB,CAAC,EAC1B,YAAa,EACb,qBACA,eAAiB,CAAC,EAClB,iBAAiB,GACjB,SAAS,GACT,aAAa,EACb,SACA,qBAAqB,GACrB,cAAa,eACb,WAAW,GACX,aAAc,EAAY,OAC1B,YACA,QACA,aACA,OAAQ,EACR,GAAG,GACD,EAAqB,OAAQ,CAAK,EAEhC,EAAW,EAAO,IAAI,GAAgC,EACtD,EAAU,EAA0B,IAAI,EACxC,EAAkB,EAAyB,IAAI,EAC/C,EAAa,IAAW,IAAA,GAExB,EAAuB,IAAuB,IAAA,GAC9C,CAAC,EAAkB,GAAuB,EAAsB,CAAmB,EACnF,EAAe,EAAuB,EAAqB,EAE3D,EAAuB,IAAuB,IAAA,GAC9C,CAAC,EAAkB,GAAuB,EAA2B,GAAsB,IAAI,EAC/F,EAAc,EAAuB,EAAqB,EAE1D,EAAU,EAAY,EAAO,CAAY,EAIzC,EAAc,KAAK,IACvB,EACA,EAAQ,UAAW,GAAU,EAAM,KAAK,MAAQ,CAAW,CAC7D,EACM,EAAY,EAAQ,EAAY,EAAE,KAAK,IAE7C,SAAS,EAAY,EAAmB,CACjC,GAAsB,EAAoB,CAAI,EACnD,EAAiB,CAAI,CACvB,CAEA,SAAS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A,EAEL,EAAK,MACJ,EAAW,EAAK,KAAM,CACpB,UAAW,EAAG,EAAO,SAAU,GAAY,IAAI,EAC/C,MAAO,GAAY,IACrB,CAAC,EAEH,EAAC,OAAD,CAAM,UAAW,EAAG,EAAO,UAAW,GAAY,KAAK,EAAG,MAAO,GAAY,MAC1E,SAAA,EAAK,KACF,CAAA,CACH,CAjDE,EAAA,EAAK,GAiDP,CAET,CAEA,OACE,EAAC,MAAD,CACE,GAAI,EACJ,KAAK,OACL,aAAY,EACZ,gBAAe,GAAY,IAAA,GAC3B,SAAU,GAAc,CAAC,EAAW,EAAI,IAAA,GACxC,QAAU,GAAU,CACd,EAAM,SAAW,EAAM,eAAe,EAAQ,CAAW,CAC/D,EACA,UAAW,EAAG,EAAO,KAAM,GAAY,EAAO,aAAc,GAAY,KAAM,CAAS,EACvF,MAAO,CAAE,GAAG,EAAO,GAAG,GAAY,IAAK,EAEtC,SAAA,EAAQ,SAAW,EAClB,EAAC,MAAD,CAAK,UAAW,EAAG,EAAO,UAAW,GAAY,KAAK,EAAG,MAAO,GAAY,MACzE,SAAA,EACE,CAAA,EACH,EACF,EAAC,EAAD,CACE,IAAK,EACL,MAAO,EACC,SACY,qBACpB,WAAa,GAAU,EAAM,KAAK,IAClC,aAAe,GAAU,EAAM,MAC/B,UAAW,CAAE,UAAW,OAAQ,IAAK,MAAO,EAC5C,UAAW,CACZ,CAAA,EAED,EAAQ,IAAI,CAAU,CAErB,CAAA,CAET"}
|
|
1
|
+
{"version":3,"file":"tree.mjs","names":[],"sources":["../../../../package/common/tree/tree.tsx"],"sourcesContent":["import { useEffect, useRef, useState } from 'react';\nimport type { ReactElement } from 'react';\nimport cx from 'classnames';\nimport { faChevronRight } from '@fortawesome/free-solid-svg-icons';\n\nimport VirtualList from 'components/common/virtualList';\nimport type { VirtualListHandle } from 'components/common/virtualList';\nimport { useComponentDefaults } from '../configProvider';\nimport { renderIcon } from '../utils/renderIcon';\nimport { flattenTree } from './flattenTree';\nimport type { FlatTreeNode, TreeProps, TreeValue } from './tree.types';\n\nimport styles from './tree.module.pcss';\n\nconst EMPTY_KEYS: TreeValue[] = [];\n\nfunction Tree(props: TreeProps): ReactElement {\n const {\n nodes,\n expandedKeys: controlledExpanded,\n defaultExpandedKeys = EMPTY_KEYS,\n onExpandedChange = () => {},\n selectedKey: controlledSelected,\n defaultSelectedKey,\n onSelect = () => {},\n expandOnSelect = true,\n indent = 20,\n toggleIcon = faChevronRight,\n height,\n estimatedRowHeight = 32,\n emptyLabel = 'Nothing here',\n disabled = false,\n 'aria-label': ariaLabel = 'Tree',\n className,\n style,\n classNames,\n styles: slotStyles,\n ...rest\n } = useComponentDefaults('Tree', props);\n\n const nodeRefs = useRef(new Map<TreeValue, HTMLDivElement>());\n const listRef = useRef<VirtualListHandle>(null);\n const pendingFocusRef = useRef<TreeValue | null>(null);\n const isWindowed = height !== undefined;\n\n const isExpandedControlled = controlledExpanded !== undefined;\n const [internalExpanded, setInternalExpanded] = useState<TreeValue[]>(defaultExpandedKeys);\n const expandedKeys = isExpandedControlled ? controlledExpanded : internalExpanded;\n\n const isSelectedControlled = controlledSelected !== undefined;\n const [internalSelected, setInternalSelected] = useState<TreeValue | null>(defaultSelectedKey ?? null);\n const selectedKey = isSelectedControlled ? controlledSelected : internalSelected;\n\n const visible = flattenTree(nodes, expandedKeys);\n\n // Windowed, the tab stop sits on the container instead of this row: a roving tabindex on a row\n // scrolled out of the window would leave the tree with no tab stop at all.\n const activeIndex = Math.max(\n 0,\n visible.findIndex((entry) => entry.node.key === selectedKey),\n );\n const activeKey = visible[activeIndex]?.node.key;\n\n function setExpanded(next: TreeValue[]) {\n if (!isExpandedControlled) setInternalExpanded(next);\n onExpandedChange(next);\n }\n\n function toggle(key: TreeValue) {\n setExpanded(expandedKeys.includes(key) ? expandedKeys.filter((k) => k !== key) : [...expandedKeys, key]);\n }\n\n function select(entry: FlatTreeNode) {\n if (disabled || entry.node.disabled) return;\n if (!isSelectedControlled) setInternalSelected(entry.node.key);\n onSelect(entry.node.key, entry.node);\n if (expandOnSelect && entry.isBranch) toggle(entry.node.key);\n }\n\n function focusAt(index: number) {\n const key = visible[index]?.node.key;\n if (key === undefined) return;\n\n const element = nodeRefs.current.get(key);\n if (element) {\n element.focus();\n return;\n }\n\n // Outside the window, so it has to be scrolled in before it exists to receive focus.\n pendingFocusRef.current = key;\n listRef.current?.scrollToIndex(index, { align: 'center' });\n }\n\n useEffect(() => {\n const key = pendingFocusRef.current;\n if (key === null) return;\n const element = nodeRefs.current.get(key);\n if (element) {\n element.focus();\n pendingFocusRef.current = null;\n }\n });\n\n function handleKeyDown(event: React.KeyboardEvent<HTMLDivElement>, entry: FlatTreeNode, index: number) {\n if (disabled) return;\n\n switch (event.key) {\n case 'ArrowDown':\n event.preventDefault();\n focusAt(Math.min(index + 1, visible.length - 1));\n break;\n case 'ArrowUp':\n event.preventDefault();\n focusAt(Math.max(index - 1, 0));\n break;\n case 'ArrowRight':\n event.preventDefault();\n if (!entry.isBranch) break;\n if (entry.isExpanded) focusAt(index + 1);\n else toggle(entry.node.key);\n break;\n case 'ArrowLeft': {\n event.preventDefault();\n if (entry.isBranch && entry.isExpanded) {\n toggle(entry.node.key);\n break;\n }\n const parentIndex = visible.findIndex((e) => e.node.key === entry.parentKey);\n if (parentIndex >= 0) focusAt(parentIndex);\n break;\n }\n case 'Home':\n event.preventDefault();\n focusAt(0);\n break;\n case 'End':\n event.preventDefault();\n focusAt(visible.length - 1);\n break;\n case 'Enter':\n case ' ':\n event.preventDefault();\n select(entry);\n break;\n default:\n break;\n }\n }\n\n function renderNode(entry: FlatTreeNode, index: number) {\n const { node, level, isBranch, isExpanded } = entry;\n const isSelected = node.key === selectedKey;\n const isDisabled = disabled || node.disabled;\n\n return (\n <div\n key={node.key}\n ref={(el) => {\n if (el) nodeRefs.current.set(node.key, el);\n else nodeRefs.current.delete(node.key);\n }}\n role='treeitem'\n aria-level={level + 1}\n aria-setsize={entry.setSize}\n aria-posinset={entry.posInSet}\n aria-expanded={isBranch ? isExpanded : undefined}\n aria-selected={isSelected}\n aria-disabled={isDisabled || undefined}\n tabIndex={node.key === activeKey && !isDisabled ? 0 : -1}\n className={cx(\n styles.treeNode,\n isSelected && styles.treeNodeSelected,\n isDisabled && styles.treeNodeDisabled,\n classNames?.node,\n )}\n style={{ paddingLeft: level * indent, ...slotStyles?.node }}\n onClick={() => select(entry)}\n onKeyDown={(event) => handleKeyDown(event, entry, index)}\n >\n <span\n className={cx(\n styles.treeToggle,\n isExpanded && styles.treeToggleOpen,\n !isBranch && styles.treeToggleHidden,\n classNames?.toggle,\n )}\n style={slotStyles?.toggle}\n aria-hidden='true'\n onClick={(event) => {\n event.stopPropagation();\n if (!isDisabled && isBranch) toggle(node.key);\n }}\n >\n {isBranch && renderIcon(toggleIcon)}\n </span>\n\n {node.icon &&\n renderIcon(node.icon, {\n className: cx(styles.treeIcon, classNames?.icon),\n style: slotStyles?.icon,\n })}\n\n <span className={cx(styles.treeLabel, classNames?.label)} style={slotStyles?.label}>\n {node.label}\n </span>\n </div>\n );\n }\n\n return (\n <div\n {...rest}\n role='tree'\n aria-label={ariaLabel}\n aria-disabled={disabled || undefined}\n tabIndex={isWindowed && !disabled ? 0 : undefined}\n onFocus={(event) => {\n if (event.target === event.currentTarget) focusAt(activeIndex);\n }}\n className={cx(styles.tree, disabled && styles.treeDisabled, classNames?.root, className)}\n style={{ ...style, ...slotStyles?.root }}\n >\n {visible.length === 0 ? (\n <div className={cx(styles.treeEmpty, classNames?.empty)} style={slotStyles?.empty}>\n {emptyLabel}\n </div>\n ) : isWindowed ? (\n <VirtualList\n ref={listRef}\n items={visible}\n height={height}\n estimatedRowHeight={estimatedRowHeight}\n getItemKey={(entry) => entry.node.key}\n getItemDepth={(entry) => entry.level}\n ariaRoles={{ container: 'none', row: 'none' }}\n // Tree owns the keyboard: its rows carry the roving tabindex and their\n // own key handling, and a second tab stop here would sit inside it.\n keyboardNavigation={false}\n renderRow={renderNode}\n />\n ) : (\n visible.map(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e,GAAY,IAAA,GAC3B,SAAU,GAAc,CAAC,EAAW,EAAI,IAAA,GACxC,QAAU,GAAU,CACd,EAAM,SAAW,EAAM,eAAe,EAAQ,CAAW,CAC/D,EACA,UAAW,EAAG,EAAO,KAAM,GAAY,EAAO,aAAc,GAAY,KAAM,CAAS,EACvF,MAAO,CAAE,GAAG,EAAO,GAAG,GAAY,IAAK,EAEtC,SAAA,EAAQ,SAAW,EAClB,EAAC,MAAD,CAAK,UAAW,EAAG,EAAO,UAAW,GAAY,KAAK,EAAG,MAAO,GAAY,MACzE,SAAA,EACE,CAAA,EACH,EACF,EAAC,EAAD,CACE,IAAK,EACL,MAAO,EACC,SACY,qBACpB,WAAa,GAAU,EAAM,KAAK,IAClC,aAAe,GAAU,EAAM,MAC/B,UAAW,CAAE,UAAW,OAAQ,IAAK,MAAO,EAG5C,mBAAoB,GACpB,UAAW,CACZ,CAAA,EAED,EAAQ,IAAI,CAAU,CAErB,CAAA,CAET"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{columnCellSelector as e,columnWidthVar as t,loadPersistedColumns as n,resolveFrozenWidth as r}from"./virtualList.utils.mjs";import{useCallback as i,useLayoutEffect as a,useRef as o,useState as s}from"react";function c(e){return Math.max(1,e?.minWidth??48)}function l({columns:l,visibleColumnsRef:u,resizableColumns:d,columnWidths:f,onColumnWidthsChange:p,persistColumnsKey:m,rootRef:h}){let g=f!==void 0,[_,v]=s(()=>n(m)?.widths??{}),[y,b]=s(!1),x=g?f:_,S=o(x);S.current=x;let C=i(e=>{g||v(e),p?.(e)},[g,p]),w=i(()=>{let t=h.current,n={...S.current};for(let i of u.current){if(n[i.key]!=null)continue;let a=t?.querySelector(`[aria-rowindex="1"] ${e(i.key)}`),o=a?Math.round(a.getBoundingClientRect().width):0;n[i.key]=o>0?o:r(i)}return n},[h,u]);a(()=>{let e=h.current;if(e)for(let[n,r]of Object.entries(x))e.style.setProperty(t(n),`${r}px`)},[x,h]);let T=i((e,n)=>{h.current?.style.setProperty(t(e),`${n}px`)},[h]),E=i(()=>{g&&requestAnimationFrame(()=>{for(let[e,t]of Object.entries(S.current))T(e,t)})},[T,g]),D=i((e,t)=>{let n=w(),r=c(l?.find(t=>t.key===e)),i={...n,[e]:Math.max(r,Math.round(t(n[e])))};T(e,i[e]),C(i),E()},[T,l,C,w,E]),O=i((e,t)=>{if(e.button!==0)return;e.preventDefault(),e.stopPropagation();let n=e.currentTarget,r=w(),i=r[t],a=e.clientX,o=c(l?.find(e=>e.key===t)),s=i,u=0,d=()=>{u=0,T(t,s)};function f(a){if(u&&cancelAnimationFrame(u),n.releasePointerCapture?.(e.pointerId),n.removeEventListener(`pointermove`,p),n.removeEventListener(`pointerup`,m),n.removeEventListener(`pointercancel`,h),n.removeEventListener(`lostpointercapture`,h),window.removeEventListener(`keydown`,g,!0),document.body.style.cursor=``,document.body.style.userSelect=``,b(!1),a==null){T(t,i);return}a!==i&&C({...r,[t]:a}),E()}function p(e){s=Math.max(o,Math.round(i+e.clientX-a)),u||=requestAnimationFrame(d)}function m(){f(s)}function h(){f(null)}function g(e){e.key===`Escape`&&(e.preventDefault(),f(null))}n.setPointerCapture?.(e.pointerId),n.addEventListener(`pointermove`,p),n.addEventListener(`pointerup`,m),n.addEventListener(`pointercancel`,h),n.addEventListener(`lostpointercapture`,h),window.addEventListener(`keydown`,g,!0),document.body.style.cursor=`col-resize`,document.body.style.userSelect=`none`,b(!0),Object.keys(S.current).length===0&&C(r)},[T,l,C,w,E]),k=i(n=>{let r=h.current;if(!r)return 0;let i=t(n),a=r.style.getPropertyValue(i),o=r.style.getPropertyValue(`--vl-total`);r.style.setProperty(i,`max-content`),r.style.removeProperty(`--vl-total`);let s=0;return r.querySelectorAll(e(n)).forEach(e=>{let t=Math.ceil(e.getBoundingClientRect().width);t>s&&(s=t)}),r.style.setProperty(i,a),o&&r.style.setProperty(`--vl-total`,o),Math.min(s,r.clientWidth)},[h]),A=i(e=>{let t=()=>{let t=k(e);t>0&&D(e,()=>t)};Object.keys(S.current).length>0?t():(C(w()),requestAnimationFrame(t))},[C,w,k,D]),j=i(()=>{let e=h.current;if(e)for(let n of Object.keys(S.current))e.style.removeProperty(t(n));C({})},[C,h]),M=i(e=>d&&e.resizable!==!1,[d]),N=i((e,t)=>D(e,e=>e+t),[D]),P=i(e=>D(e,()=>c(l?.find(t=>t.key===e))),[l,D]),F=i(e=>M(e)?{"aria-hidden":!0,onPointerDown:t=>O(t,e.key),onDoubleClick:t=>{t.stopPropagation(),A(e.key)},onClick:e=>e.stopPropagation()}:null,[A,O,M]);return{widths:x,isFrozen:Object.keys(x).length>0,isResizing:y,reset:j,isResizable:M,resizeBy:N,resizeToMin:P,autoFit:A,getHandleProps:F}}export{l as useColumnResize};
|
|
2
|
+
//# sourceMappingURL=useColumnResize.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useColumnResize.mjs","names":[],"sources":["../../../../package/common/virtualList/useColumnResize.ts"],"sourcesContent":["import React, { useCallback, useLayoutEffect, useRef, useState } from 'react';\n\nimport {\n columnCellSelector,\n columnWidthVar,\n loadPersistedColumns,\n resolveFrozenWidth,\n MIN_COLUMN_WIDTH,\n} from './virtualList.utils';\nimport type { VirtualListColumn } from './virtualList.types';\n\ninterface UseColumnResizeArgs<T> {\n columns?: VirtualListColumn<T>[];\n /**\n * The columns currently rendered, in order. A ref rather than a value because\n * the visible set is derived one hook later, and only the freeze reads it, at\n * event time.\n */\n visibleColumnsRef: React.RefObject<VirtualListColumn<T>[]>;\n resizableColumns: boolean;\n /** Controlled widths. When provided, internal state is ignored. */\n columnWidths?: Record<string, number>;\n onColumnWidthsChange?: (widths: Record<string, number>) => void;\n /** Restores widths saved under this key. Uncontrolled mode only. */\n persistColumnsKey?: string;\n rootRef: React.RefObject<HTMLDivElement | null>;\n}\n\nexport interface UseColumnResizeResult<T> {\n widths: Record<string, number>;\n /**\n * True once every visible column has an exact px width. Nothing moves at that\n * moment, but from then on the layout is pixels rather than `fr`/`fit`.\n */\n isFrozen: boolean;\n isResizing: boolean;\n /** Drops every user width and hands the layout back to the column definitions. */\n reset: () => void;\n /** Whether this column takes a resize at all, by handle or by keyboard. */\n isResizable: (col: VirtualListColumn<T>) => boolean;\n /** Widens (or, negative, narrows) one column. The keyboard entry point. */\n resizeBy: (key: string, delta: number) => void;\n /** Takes one column down to its minimum. */\n resizeToMin: (key: string) => void;\n /** Sizes one column to its widest rendered cell. */\n autoFit: (key: string) => void;\n /** Pointer props for one column's handle, or null when that column can't be resized. */\n getHandleProps: (col: VirtualListColumn<T>) => React.HTMLAttributes<HTMLDivElement> | null;\n}\n\nfunction minWidthFor<T>(col: VirtualListColumn<T> | undefined): number {\n return Math.max(1, col?.minWidth ?? MIN_COLUMN_WIDTH);\n}\n\n/**\n * User column resizing: the width state, and a drag that doesn't go through\n * React.\n *\n * A pointer move writes the dragged column's custom property straight onto the\n * list element. The header and every row read that same property, so one DOM\n * write resizes all of them in a single layout pass. Going through state\n * instead would re-render the header plus every visible row on every frame, and\n * the handle would trail the cursor by one frame, which is the whole difference\n * between this feeling attached to the pointer and feeling cheap. React is told\n * once, on release.\n *\n * The first resize **freezes** every visible column to its measured width. A\n * `fr` track can't express \"this one column is now 240px\" without the others\n * silently absorbing the difference, and once they hit their minimum the dragged\n * edge stops following the cursor, which is the worst moment for it to happen.\n * Frozen, the table is exact pixels and simply scrolls horizontally instead.\n */\nexport function useColumnResize<T>({\n columns,\n visibleColumnsRef,\n resizableColumns,\n columnWidths,\n onColumnWidthsChange,\n persistColumnsKey,\n rootRef,\n}: UseColumnResizeArgs<T>): UseColumnResizeResult<T> {\n const isControlled = columnWidths !== undefined;\n const [internalWidths, setInternalWidths] = useState<Record<string, number>>(\n () => loadPersistedColumns(persistColumnsKey)?.widths ?? {},\n );\n const [isResizing, setIsResizing] = useState(false);\n const effectiveWidths = isControlled ? columnWidths! : internalWidths;\n\n // Read by the pointer handlers, which are installed once per drag and must not\n // capture a stale snapshot of either.\n const widthsRef = useRef(effectiveWidths);\n widthsRef.current = effectiveWidths;\n\n const commit = useCallback(\n (next: Record<string, number>) => {\n if (!isControlled) setInternalWidths(next);\n onColumnWidthsChange?.(next);\n },\n [isControlled, onColumnWidthsChange],\n );\n\n /**\n * Current width of every visible column, measured from the rendered header so\n * the freeze is invisible: the px values are the ones already on screen.\n * Columns that already have a width keep it, and a header cell that can't be\n * measured (jsdom, a display:none list) falls back to its declared width.\n */\n const freeze = useCallback((): Record<string, number> => {\n const root = rootRef.current;\n const next: Record<string, number> = { ...widthsRef.current };\n for (const col of visibleColumnsRef.current) {\n if (next[col.key] != null) continue;\n const cell = root?.querySelector(`[aria-rowindex=\"1\"] ${columnCellSelector(col.key)}`);\n const measured = cell ? Math.round(cell.getBoundingClientRect().width) : 0;\n next[col.key] = measured > 0 ? measured : resolveFrozenWidth(col);\n }\n return next;\n }, [rootRef, visibleColumnsRef]);\n\n // The widths live on the element as custom properties, written from here and\n // from the drag, never through React's `style`. One owner means a drag's\n // imperative writes can't be clobbered by a render that happens to land\n // mid-gesture, and the steady state still follows the committed widths.\n useLayoutEffect(() => {\n const root = rootRef.current;\n if (!root) return;\n for (const [key, width] of Object.entries(effectiveWidths))\n root.style.setProperty(columnWidthVar(key), `${width}px`);\n }, [effectiveWidths, rootRef]);\n\n const applyWidth = useCallback(\n (key: string, width: number) => {\n rootRef.current?.style.setProperty(columnWidthVar(key), `${width}px`);\n },\n [rootRef],\n );\n\n /**\n * In controlled mode the drag has already written widths the prop may not\n * agree with. A frame later either the consumer has accepted them (the ref\n * holds the new values and this writes them again, a no-op) or it hasn't, and\n * the columns snap back to what the prop says. Without it a rejected width\n * would stay on screen, since nothing re-rendered to correct it.\n */\n const syncControlled = useCallback(() => {\n if (!isControlled) return;\n requestAnimationFrame(() => {\n for (const [key, width] of Object.entries(widthsRef.current)) applyWidth(key, width);\n });\n }, [applyWidth, isControlled]);\n\n const resize = useCallback(\n (key: string, toWidth: (from: number) => number) => {\n const base = freeze();\n const min = minWidthFor(columns?.find((c) => c.key === key));\n const next = { ...base, [key]: Math.max(min, Math.round(toWidth(base[key]))) };\n applyWidth(key, next[key]);\n commit(next);\n syncControlled();\n },\n [applyWidth, columns, commit, freeze, syncControlled],\n );\n\n const beginDrag = useCallback(\n (event: React.PointerEvent<HTMLDivElement>, key: string) => {\n if (event.button !== 0) return;\n // The handle sits on top of the header's sort button; without this the\n // drag would also count as a click on it.\n event.preventDefault();\n event.stopPropagation();\n\n const handle = event.currentTarget;\n const base = freeze();\n const startWidth = base[key];\n const startX = event.clientX;\n const min = minWidthFor(columns?.find((c) => c.key === key));\n\n let width = startWidth;\n let frame = 0;\n const paint = () => {\n frame = 0;\n applyWidth(key, width);\n };\n\n function finish(commitWidth: number | null) {\n if (frame) cancelAnimationFrame(frame);\n handle.releasePointerCapture?.(event.pointerId);\n handle.removeEventListener('pointermove', onMove);\n handle.removeEventListener('pointerup', onUp);\n handle.removeEventListener('pointercancel', onCancel);\n handle.removeEventListener('lostpointercapture', onCancel);\n window.removeEventListener('keydown', onKeyDown, true);\n document.body.style.cursor = '';\n document.body.style.userSelect = '';\n setIsResizing(false);\n if (commitWidth == null) {\n // The freeze was committed at pointerdown and stays: on its own it\n // changes nothing the user can see. Only the drag is undone.\n applyWidth(key, startWidth);\n return;\n }\n if (commitWidth !== startWidth) commit({ ...base, [key]: commitWidth });\n syncControlled();\n }\n\n function onMove(moveEvent: PointerEvent) {\n // Always from the values captured at pointerdown, never from the\n // element's current geometry: re-measuring mid-drag lets rounding\n // accumulate and the handle slides away from the cursor.\n width = Math.max(min, Math.round(startWidth + moveEvent.clientX - startX));\n if (!frame) frame = requestAnimationFrame(paint);\n }\n function onUp() {\n finish(width);\n }\n function onCancel() {\n finish(null);\n }\n function onKeyDown(keyEvent: KeyboardEvent) {\n if (keyEvent.key !== 'Escape') return;\n keyEvent.preventDefault();\n finish(null);\n }\n\n handle.setPointerCapture?.(event.pointerId);\n handle.addEventListener('pointermove', onMove);\n handle.addEventListener('pointerup', onUp);\n handle.addEventListener('pointercancel', onCancel);\n handle.addEventListener('lostpointercapture', onCancel);\n window.addEventListener('keydown', onKeyDown, true);\n // On the body, not on the handle: the pointer leaves the handle as soon as\n // the drag starts, and the cursor must not flicker back to the default.\n document.body.style.cursor = 'col-resize';\n document.body.style.userSelect = 'none';\n setIsResizing(true);\n // Committing the freeze up front, rather than on release: until React has\n // rendered the frozen template, the tracks are still `fr`/`fit` and read\n // no custom property, so the drag would move nothing at all.\n if (Object.keys(widthsRef.current).length === 0) commit(base);\n },\n [applyWidth, columns, commit, freeze, syncControlled],\n );\n\n /**\n * Width the column would need for its widest cell, measured by sizing its\n * track to `max-content` for one synchronous layout.\n *\n * Reading `scrollWidth` off the cells instead reports the *min*-content width:\n * a body cell is free to wrap, so long text never overflows it, it only makes\n * the row taller, and the widest thing that can't wrap is a single word.\n * `max-content` is the width with no wrapping at all, which is what fitting a\n * column means. The header and every row are separate grids, so each sizes its\n * own track independently and all of them have to be read: the widest is the\n * one width that fits the whole column.\n */\n const measureAutoFit = useCallback(\n (key: string): number => {\n const root = rootRef.current;\n if (!root) return 0;\n const widthProperty = columnWidthVar(key);\n const previousWidth = root.style.getPropertyValue(widthProperty);\n // `--vl-total` is a calc() over these same properties, so it turns invalid\n // while one of them holds a keyword, and the header and body would be left\n // with an unresolvable width mid-measurement.\n const previousTotal = root.style.getPropertyValue('--vl-total');\n\n root.style.setProperty(widthProperty, 'max-content');\n root.style.removeProperty('--vl-total');\n let measured = 0;\n root.querySelectorAll(columnCellSelector(key)).forEach((cell) => {\n const width = Math.ceil(cell.getBoundingClientRect().width);\n if (width > measured) measured = width;\n });\n root.style.setProperty(widthProperty, previousWidth);\n if (previousTotal) root.style.setProperty('--vl-total', previousTotal);\n\n // Only the rendered rows are measurable, so this fits what is on screen.\n return Math.min(measured, root.clientWidth);\n },\n [rootRef],\n );\n\n const autoFit = useCallback(\n (key: string) => {\n const run = () => {\n const measured = measureAutoFit(key);\n if (measured > 0) resize(key, () => measured);\n };\n // Until the frozen template has rendered, the tracks read no custom\n // property and sizing one to `max-content` measures nothing. A drag has\n // already frozen by the time its double-click lands; a keyboard `End` on\n // an untouched list has not, so it waits for the render it just asked for.\n if (Object.keys(widthsRef.current).length > 0) run();\n else {\n commit(freeze());\n requestAnimationFrame(run);\n }\n },\n [commit, freeze, measureAutoFit, resize],\n );\n\n const reset = useCallback(() => {\n const root = rootRef.current;\n // The layout effect only ever writes the widths it has, so the properties of\n // the ones being dropped have to be cleared here or they would linger and\n // reappear with the next freeze.\n if (root) for (const key of Object.keys(widthsRef.current)) root.style.removeProperty(columnWidthVar(key));\n commit({});\n }, [commit, rootRef]);\n\n const isResizable = useCallback(\n (col: VirtualListColumn<T>) => resizableColumns && col.resizable !== false,\n [resizableColumns],\n );\n\n const resizeBy = useCallback((key: string, delta: number) => resize(key, (w) => w + delta), [resize]);\n\n const resizeToMin = useCallback(\n (key: string) => resize(key, () => minWidthFor(columns?.find((c) => c.key === key))),\n [columns, resize],\n );\n\n const getHandleProps = useCallback(\n (col: VirtualListColumn<T>): React.HTMLAttributes<HTMLDivElement> | null => {\n if (!isResizable(col)) return null;\n return {\n // Deliberately not focusable, and hidden from assistive technology: the\n // keyboard path is Alt plus the arrow keys on the header cell itself, so\n // a second tab stop per column would buy nothing and cost a lot.\n 'aria-hidden': true,\n onPointerDown: (event: React.PointerEvent<HTMLDivElement>) => beginDrag(event, col.key),\n onDoubleClick: (event: React.MouseEvent) => {\n event.stopPropagation();\n autoFit(col.key);\n },\n onClick: (event: React.MouseEvent) => event.stopPropagation(),\n };\n },\n [autoFit, beginDrag, isResizable],\n );\n\n return {\n widths: effectiveWidths,\n isFrozen: Object.keys(effectiveWidths).length > 0,\n isResizing,\n reset,\n isResizable,\n resizeBy,\n resizeToMin,\n autoFit,\n getHandleProps,\n };\n}\n"],"mappings":"sNAkDA,SAAS,EAAe,EAA+C,CACrE,OAAO,KAAK,IAAI,EAAG,GAAK,UAAA,EAA4B,CACtD,CAoBA,SAAgB,EAAmB,CAC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ildColumnTemplate as t,
|
|
1
|
+
import{COLUMN_STORAGE_PREFIX as e,buildColumnTemplate as t,buildFrozenTemplate as n,columnWidthVar as r,isColumnInitiallyVisible as i,loadPersistedColumns as a,measureCellWidth as o}from"./virtualList.utils.mjs";import{useCallback as s,useEffect as c,useLayoutEffect as l,useRef as u,useState as d}from"react";function f({columns:f,items:p,multiSelect:m,visibleColumnKeys:h,onVisibleColumnsChange:g,persistColumnsKey:_,showColumnToggle:v,userWidths:y,isFrozen:b,rootRef:x,startIndex:S,endIndex:C,containerHeight:w,containerWidth:T}){let E=h!==void 0,[D,O]=d(!1),[k,A]=d({}),[j,M]=d(()=>{let e=a(_);return new Set((f??[]).filter(t=>i(t,e)).map(e=>e.key))}),N=u(new Set((f??[]).map(e=>e.key)));c(()=>{if(E)return;let e=f??[],t=new Set(e.map(e=>e.key)),n=N.current,r=t.size===n.size;if(r){for(let e of t)if(!n.has(e)){r=!1;break}}if(r)return;N.current=t;let o=a(_);M(t=>{let r=new Set;for(let a of e)n.has(a.key)?t.has(a.key)&&r.add(a.key):i(a,o)&&r.add(a.key);return r})},[f,E,_]),c(()=>{if(E||!_||typeof window>`u`)return;let t=f??[];if(t.length!==0&&j.size!==0)try{window.localStorage.setItem(e+_,JSON.stringify({visible:[...j],known:t.map(e=>e.key),widths:y}))}catch{}},[j,f,E,_,y]);let P=E?new Set(h):j,F=(f??[]).filter(e=>e.lockVisible).map(e=>e.key),I=F.some(e=>!P.has(e))?new Set([...P,...F]):P,L=!!f?.length,R=L?f.filter(e=>I.has(e.key)):[],z=L?f.filter(e=>!e.defaultHidden&&!I.has(e.key)).length:0,B=L?`${m&&L?`40px `:``}${b?n(R):t(R,k)}`:void 0,V=v!==!1&&L&&f.some(e=>!e.hideFromToggle),H={};if(b&&L){let e=R.map(e=>`var(${r(e.key)}, 160px)`);m&&e.unshift(`40px`),V&&e.push(`32px`),H[`--vl-total`]=`calc(${e.join(` + `)})`}let U=R.filter(e=>e.width.type===`fit`),W=!b&&U.length>0,G=U.map(e=>e.key).join(`|`),[K,q]=d({key:G,items:p});(K.key!==G||K.items!==p)&&(q({key:G,items:p}),Object.keys(k).length>0&&A({}));let J=s(()=>{let e=x.current;if(!e)return;let t=new Map;e.querySelectorAll(`[data-fit-key]`).forEach(e=>{let n=e,r=n.getAttribute(`data-fit-key`);if(!r)return;let i=o(n);i>(t.get(r)??0)&&t.set(r,i)}),t.size!==0&&A(n=>{let r=!1,i={...n};for(let[a,o]of t){if(o<=0)continue;let t=Math.min(Math.ceil(o),e.clientWidth);t>(n[a]??0)&&(i[a]=t,r=!0)}return r?i:n})},[x]),[Y]=d(()=>typeof ResizeObserver>`u`?null:new ResizeObserver(()=>J())),X=u(new Set);c(()=>()=>{Y?.disconnect(),X.current.clear()},[Y]),l(()=>{if(!W)return;let e=x.current;if(!e||(J(),!Y))return;let t=new Set(e.querySelectorAll(`[data-fit-key]`)),n=X.current;for(let e of n)t.has(e)||(Y.unobserve(e),n.delete(e));for(let e of t)n.has(e)||(Y.observe(e),n.add(e))},[x,W,G,k,S,C,w,T,p,J,Y]),c(()=>{if(!W)return;let e=0,t=requestAnimationFrame(()=>{J(),e=requestAnimationFrame(()=>J())});return()=>{cancelAnimationFrame(t),cancelAnimationFrame(e)}},[W,G,p,J]);let Z=s(()=>A({}),[]);function Q(e){if(f?.find(t=>t.key===e)?.lockVisible)return;let t=new Set(I);if(t.has(e)){if(t.size<=1)return;t.delete(e)}else t.add(e);let n=[...t];E||M(t),g?.(n)}return{hasColumns:L,visibleColumns:R,columnTemplate:B,widthVars:H,shouldShowToggle:V,effectiveVisible:I,manuallyHiddenCount:z,toggleOpen:D,setToggleOpen:O,handleToggleColumn:Q,recalculateColumns:Z}}export{f as useColumns};
|
|
2
2
|
//# sourceMappingURL=useColumns.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useColumns.mjs","names":[],"sources":["../../../../package/common/virtualList/useColumns.ts"],"sourcesContent":["import React, { useState, useRef, useEffect, useLayoutEffect, useCallback } from 'react';\n\nimport {\n buildColumnTemplate,\n loadPersistedColumns,\n isColumnInitiallyVisible,\n COLUMN_STORAGE_PREFIX,\n type PersistedColumns,\n} from './virtualList.utils';\nimport type { VirtualListColumn } from './virtualList.types';\n\ninterface UseColumnsArgs<T> {\n columns?: VirtualListColumn<T>[];\n items: T[];\n multiSelect: boolean;\n visibleColumnKeys?: string[];\n onVisibleColumnsChange?: (keys: string[]) => void;\n persistColumnsKey?: string;\n showColumnToggle?: boolean;\n rootRef: React.RefObject<HTMLDivElement | null>;\n /** Visible-window bounds — re-measure `fit` columns as new cells scroll in. */\n startIndex: number;\n endIndex: number;\n containerHeight: number;\n /** Re-measure `fit` columns when the container width settles (e.g. after a route transition). */\n containerWidth: number;\n}\n\ninterface UseColumnsResult<T> {\n hasColumns: boolean;\n visibleColumns: VirtualListColumn<T>[];\n columnTemplate: string | undefined;\n shouldShowToggle: boolean;\n effectiveVisible: Set<string>;\n /** How many default-visible columns the user has hidden (excludes defaultHidden). */\n manuallyHiddenCount: number;\n toggleOpen: boolean;\n setToggleOpen: React.Dispatch<React.SetStateAction<boolean>>;\n handleToggleColumn: (key: string) => void;\n /** Imperative escape hatch: drop fit-column pins so they re-measure on the\n * next layout. For out-of-band content changes that don't flow through a new\n * `items` array or `columns` set (which reset automatically). */\n recalculateColumns: () => void;\n}\n\n/**\n * Table-mode column logic: visibility (controlled or uncontrolled, with\n * localStorage persistence and runtime reconciliation), the toggle popover, and\n * `fit`-column width measurement that pins one shared px track across the header\n * and every row grid so they stay aligned.\n */\nexport function useColumns<T>({\n columns,\n items,\n multiSelect,\n visibleColumnKeys,\n onVisibleColumnsChange,\n persistColumnsKey,\n showColumnToggle,\n rootRef,\n startIndex,\n endIndex,\n containerHeight,\n containerWidth,\n}: UseColumnsArgs<T>): UseColumnsResult<T> {\n const isControlled = visibleColumnKeys !== undefined;\n const [toggleOpen, setToggleOpen] = useState(false);\n // Measured px widths for `fit` columns, keyed by column key. Pinning these\n // into the shared column template keeps the header and rows aligned (a raw\n // `fit-content` track resolves per-grid and drifts). See the effects below.\n const [fitWidths, setFitWidths] = useState<Record<string, number>>({});\n\n const [internalVisibleKeys, setInternalVisibleKeys] = useState<Set<string>>(() => {\n const persisted = loadPersistedColumns(persistColumnsKey);\n return new Set((columns ?? []).filter((c) => isColumnInitiallyVisible(c, persisted)).map((c) => c.key));\n });\n // The set of column keys the internal visibility state was last reconciled\n // against. The lazy initializer above only runs at mount, so without this a\n // list that mounts in list mode (no columns) and later switches to table mode\n // would keep an empty visible set and render no columns.\n const knownColumnKeysRef = useRef<Set<string>>(new Set((columns ?? []).map((c) => c.key)));\n\n // Re-derive internal visibility when the column set changes at runtime: new\n // columns get their saved/default visibility, removed columns drop out, and\n // existing columns keep whatever the user toggled them to. This is also what\n // applies persisted settings when a list switches from list mode to table\n // mode (columns absent at mount, supplied later).\n useEffect(() => {\n if (isControlled) return;\n const cols = columns ?? [];\n const currentKeys = new Set(cols.map((c) => c.key));\n const known = knownColumnKeysRef.current;\n let identical = currentKeys.size === known.size;\n if (identical)\n for (const k of currentKeys)\n if (!known.has(k)) {\n identical = false;\n break;\n }\n if (identical) return;\n knownColumnKeysRef.current = currentKeys;\n const persisted = loadPersistedColumns(persistColumnsKey);\n setInternalVisibleKeys((prev) => {\n const next = new Set<string>();\n for (const c of cols) {\n if (known.has(c.key)) {\n if (prev.has(c.key)) next.add(c.key); // preserve the current-session choice\n } else if (isColumnInitiallyVisible(c, persisted)) {\n next.add(c.key); // newly-added column: saved setting, else defaultHidden\n }\n }\n return next;\n });\n }, [columns, isControlled, persistColumnsKey]);\n\n // Persist visibility whenever it changes (uncontrolled mode only). Skip while\n // there are no columns, or the transient empty state during a list→table\n // switch before the reconcile effect above has filled in the visible set —\n // writing then would clobber the saved config with an empty set.\n useEffect(() => {\n if (isControlled || !persistColumnsKey || typeof window === 'undefined') return;\n const cols = columns ?? [];\n if (cols.length === 0 || internalVisibleKeys.size === 0) return;\n try {\n window.localStorage.setItem(\n COLUMN_STORAGE_PREFIX + persistColumnsKey,\n JSON.stringify({ visible: [...internalVisibleKeys], known: cols.map((c) => c.key) } satisfies PersistedColumns),\n );\n } catch {\n // Storage full or unavailable — non-fatal, just don't persist.\n }\n }, [internalVisibleKeys, columns, isControlled, persistColumnsKey]);\n\n // Locked columns can never be hidden — force them into the visible set even if\n // a controlled `visibleColumnKeys` or persisted state omits them. Only clone\n // (rather than mutate the state Set) when a locked key is actually missing;\n // in uncontrolled mode they're already present via isColumnInitiallyVisible.\n const baseVisible: Set<string> = isControlled ? new Set(visibleColumnKeys) : internalVisibleKeys;\n const lockedKeys = (columns ?? []).filter((c) => c.lockVisible).map((c) => c.key);\n const effectiveVisible: Set<string> = lockedKeys.some((k) => !baseVisible.has(k))\n ? new Set([...baseVisible, ...lockedKeys])\n : baseVisible;\n\n const hasColumns = !!columns?.length;\n const visibleColumns = hasColumns ? columns!.filter((c) => effectiveVisible.has(c.key)) : [];\n // A column counts as \"manually hidden\" only if it's default-visible yet\n // currently hidden — a defaultHidden column being hidden is its default\n // state, not a user choice, so it never contributes to the chip.\n const manuallyHiddenCount = hasColumns\n ? columns!.filter((c) => !c.defaultHidden && !effectiveVisible.has(c.key)).length\n : 0;\n const selectPrefix = multiSelect && hasColumns ? '40px ' : '';\n const columnTemplate = hasColumns ? `${selectPrefix}${buildColumnTemplate(visibleColumns, fitWidths)}` : undefined;\n // Hide the gear entirely when nothing is left to toggle (every column opts out).\n const shouldShowToggle = showColumnToggle !== false && hasColumns && columns!.some((c) => !c.hideFromToggle);\n\n // ── `fit` column width measurement ──────────────────────────────────────────\n const fitColumns = visibleColumns.filter((c) => c.width.type === 'fit');\n const hasFit = fitColumns.length > 0;\n const fitColKey = fitColumns.map((c) => c.key).join('|');\n\n // Drop the measured pins when the data or the fit-column set changes, so the\n // measure effect below re-reads the true intrinsic width on the next pass —\n // this is what lets a column shrink (during scroll the effect only grows it,\n // to avoid jitter). Resetting state during render is React's recommended\n // pattern for \"reset on prop change\" and avoids a cascading effect render.\n const [fitReset, setFitReset] = useState<{ key: string; items: T[] }>({ key: fitColKey, items });\n if (fitReset.key !== fitColKey || fitReset.items !== items) {\n setFitReset({ key: fitColKey, items });\n if (Object.keys(fitWidths).length > 0) setFitWidths({});\n }\n\n // Measure every fit cell currently in the DOM (header + visible rows), keyed\n // by its `data-fit-key`, and grow each column's pin to the widest. Reading the\n // key off the DOM (rather than closing over `fitColumns`) keeps this a stable\n // callback the ResizeObserver below can reuse. `scrollWidth` reports the true\n // content width even when the cell is pinned narrower than its content, so a\n // later pass always recovers a column first measured while it was still empty\n // (e.g. an actions cell whose buttons mount a tick after the row commits — its\n // empty width is just the padding, ~24px, which \"only grow\" can't undo).\n const measureFitWidths = useCallback(() => {\n const root = rootRef.current;\n if (!root) return;\n const maxByKey = new Map<string, number>();\n root.querySelectorAll('[data-fit-key]').forEach((node) => {\n const el = node as HTMLElement;\n const key = el.getAttribute('data-fit-key');\n if (!key) return;\n const overflowing = el.scrollWidth > el.clientWidth;\n let w = el.scrollWidth;\n // Only resolve computed padding when we actually need it — the overflow\n // fix-up, or the collapse check below — so the hot scroll path stays cheap\n // for plain in-flow cells.\n if (overflowing || el.firstElementChild) {\n const cs = getComputedStyle(el);\n const padLeft = parseFloat(cs.paddingLeft) || 0;\n const padRight = parseFloat(cs.paddingRight) || 0;\n // scrollWidth includes the left padding but drops the right padding when\n // the content overflows — add it back.\n if (overflowing) w += padRight;\n // Collapsed-content case (FontAwesome icons etc.): element children are\n // present, yet scrollWidth is only the cell's padding because their boxes\n // overflow via `overflow: visible` and carry no intrinsic width, so they\n // don't count toward scrollWidth (and, when right-aligned, overflow to the\n // *left* into negative offsets). ONLY then walk the descendants for their\n // true span — once a real width pins, the cell is no longer collapsed, so\n // this stops running on every scroll frame.\n if (el.firstElementChild && !overflowing && el.scrollWidth <= padLeft + padRight + 1) {\n let minLeft = Infinity;\n let maxRight = -Infinity;\n el.querySelectorAll('*').forEach((d) => {\n const r = d.getBoundingClientRect();\n if (r.left < minLeft) minLeft = r.left;\n if (r.right > maxRight) maxRight = r.right;\n });\n if (maxRight > minLeft) {\n const span = Math.ceil(maxRight - minLeft) + padLeft + padRight;\n if (span > w) w = span;\n }\n }\n }\n if (w > (maxByKey.get(key) ?? 0)) maxByKey.set(key, w);\n });\n if (maxByKey.size === 0) return;\n setFitWidths((prev) => {\n let changed = false;\n const next = { ...prev };\n for (const [key, max] of maxByKey) {\n if (max <= 0) continue;\n // Cap at the viewport width so one oversized cell can't blow out layout.\n const pinned = Math.min(Math.ceil(max), root.clientWidth);\n if (pinned > (prev[key] ?? 0)) {\n next[key] = pinned;\n changed = true;\n }\n }\n return changed ? next : prev;\n });\n }, [rootRef]);\n\n // One ResizeObserver shared across all fit cells. It re-measures whenever a\n // cell's box changes — crucially when content first appears after mount (which\n // changes the cell's height even while its width is pinned), so a too-early or\n // empty-cell measure self-corrects instead of sticking. Its initial callback\n // also fires once after layout settles, covering route transitions and other\n // post-mount layout shifts without depending on font/rAF timing.\n const [fitObserver] = useState<ResizeObserver | null>(() =>\n typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(() => measureFitWidths()),\n );\n const observedRef = useRef<Set<Element>>(new Set());\n useEffect(\n () => () => {\n fitObserver?.disconnect();\n observedRef.current.clear();\n },\n [fitObserver],\n );\n\n // Measure synchronously (before paint, so a wider row scrolling in never shows\n // a clipped frame), then *diff* the observed set rather than re-observing every\n // cell. Re-observing fires a redundant ResizeObserver callback per node, and\n // `startIndex`/`endIndex` change every scroll frame — so observing only the\n // cells that entered (and dropping the ones that left) keeps stable, already\n // pinned cells from generating any observer traffic while scrolling. A newly\n // entered cell still fires exactly once, which is when we want to measure it.\n useLayoutEffect(() => {\n if (!hasFit) return;\n const root = rootRef.current;\n if (!root) return;\n measureFitWidths();\n if (!fitObserver) return;\n const current = new Set<Element>(root.querySelectorAll('[data-fit-key]'));\n const observed = observedRef.current;\n for (const el of observed)\n if (!current.has(el)) {\n fitObserver.unobserve(el);\n observed.delete(el);\n }\n for (const el of current)\n if (!observed.has(el)) {\n fitObserver.observe(el);\n observed.add(el);\n }\n }, [\n rootRef,\n hasFit,\n fitColKey,\n fitWidths,\n startIndex,\n endIndex,\n containerHeight,\n containerWidth,\n items,\n measureFitWidths,\n fitObserver,\n ]);\n\n // Cheap insurance: re-measure on the next two frames after mount / data /\n // fit-column changes, in case the icons (or the injected FontAwesome sizing\n // CSS) resolve a frame after the first synchronous pass. Safe and scoped —\n // measureFitWidths only ever grows a pin, and this runs on mount / data change\n // (not every scroll frame), so it keeps the diff-observe perf win.\n useEffect(() => {\n if (!hasFit) return;\n let raf2 = 0;\n const raf1 = requestAnimationFrame(() => {\n measureFitWidths();\n raf2 = requestAnimationFrame(() => measureFitWidths());\n });\n return () => {\n cancelAnimationFrame(raf1);\n cancelAnimationFrame(raf2);\n };\n }, [hasFit, fitColKey, items, measureFitWidths]);\n\n // Force a fresh fit-column measure regardless of current pins. Always installs\n // a new empty object so the measure layout effect re-runs even when nothing\n // was pinned (e.g. content changed while the column was still fit-content).\n const recalculateColumns = useCallback(() => setFitWidths({}), []);\n\n function handleToggleColumn(key: string) {\n // Locked columns can't be toggled off.\n if (columns?.find((c) => c.key === key)?.lockVisible) return;\n const next = new Set(effectiveVisible);\n if (next.has(key)) {\n if (next.size <= 1) return;\n next.delete(key);\n } else {\n next.add(key);\n }\n const nextArray = [...next];\n if (!isControlled) setInternalVisibleKeys(next);\n onVisibleColumnsChange?.(nextArray);\n }\n\n return {\n hasColumns,\n visibleColumns,\n columnTemplate,\n shouldShowToggle,\n effectiveVisible,\n manuallyHiddenCount,\n toggleOpen,\n setToggleOpen,\n handleToggleColumn,\n recalculateColumns,\n };\n}\n"],"mappings":"mPAmDA,SAAgB,EAAc,CAC5B,UACA,QACA,cACA,oBACA,yBACA,oBACA,mBACA,UACA,aACA,WACA,kBACA,kBACyC,CACzC,IAAM,EAAe,IAAsB,IAAA,GACrC,CAAC,EAAY,GAAiB,EAAS,EAAK,EAI5C,CAAC,EA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
|
1
|
+
{"version":3,"file":"useColumns.mjs","names":[],"sources":["../../../../package/common/virtualList/useColumns.ts"],"sourcesContent":["import React, { useState, useRef, useEffect, useLayoutEffect, useCallback } from 'react';\n\nimport {\n buildColumnTemplate,\n buildFrozenTemplate,\n columnWidthVar,\n DEFAULT_FROZEN_WIDTH,\n measureCellWidth,\n loadPersistedColumns,\n isColumnInitiallyVisible,\n COLUMN_STORAGE_PREFIX,\n type PersistedColumns,\n} from './virtualList.utils';\nimport type { VirtualListColumn } from './virtualList.types';\n\ninterface UseColumnsArgs<T> {\n columns?: VirtualListColumn<T>[];\n items: T[];\n multiSelect: boolean;\n visibleColumnKeys?: string[];\n onVisibleColumnsChange?: (keys: string[]) => void;\n persistColumnsKey?: string;\n showColumnToggle?: boolean;\n /** User-set column widths, from `useColumnResize`. */\n userWidths: Record<string, number>;\n /** Whether those widths have taken over the layout. */\n isFrozen: boolean;\n rootRef: React.RefObject<HTMLDivElement | null>;\n /** Visible-window bounds — re-measure `fit` columns as new cells scroll in. */\n startIndex: number;\n endIndex: number;\n containerHeight: number;\n /** Re-measure `fit` columns when the container width settles (e.g. after a route transition). */\n containerWidth: number;\n}\n\nexport interface UseColumnsResult<T> {\n hasColumns: boolean;\n visibleColumns: VirtualListColumn<T>[];\n columnTemplate: string | undefined;\n /**\n * Custom properties for the list element: the total width of a frozen layout,\n * as a `calc()` over the per-column properties so that rewriting one width\n * during a drag updates the total without any bookkeeping.\n */\n widthVars: React.CSSProperties;\n shouldShowToggle: boolean;\n effectiveVisible: Set<string>;\n /** How many default-visible columns the user has hidden (excludes defaultHidden). */\n manuallyHiddenCount: number;\n toggleOpen: boolean;\n setToggleOpen: React.Dispatch<React.SetStateAction<boolean>>;\n handleToggleColumn: (key: string) => void;\n /** Imperative escape hatch: drop fit-column pins so they re-measure on the\n * next layout. For out-of-band content changes that don't flow through a new\n * `items` array or `columns` set (which reset automatically). */\n recalculateColumns: () => void;\n}\n\n/**\n * Table-mode column logic: visibility (controlled or uncontrolled, with\n * localStorage persistence and runtime reconciliation), the toggle popover, and\n * `fit`-column width measurement that pins one shared px track across the header\n * and every row grid so they stay aligned.\n */\nexport function useColumns<T>({\n columns,\n items,\n multiSelect,\n visibleColumnKeys,\n onVisibleColumnsChange,\n persistColumnsKey,\n showColumnToggle,\n userWidths,\n isFrozen,\n rootRef,\n startIndex,\n endIndex,\n containerHeight,\n containerWidth,\n}: UseColumnsArgs<T>): UseColumnsResult<T> {\n const isControlled = visibleColumnKeys !== undefined;\n const [toggleOpen, setToggleOpen] = useState(false);\n // Measured px widths for `fit` columns, keyed by column key. Pinning these\n // into the shared column template keeps the header and rows aligned (a raw\n // `fit-content` track resolves per-grid and drifts). See the effects below.\n const [fitWidths, setFitWidths] = useState<Record<string, number>>({});\n\n const [internalVisibleKeys, setInternalVisibleKeys] = useState<Set<string>>(() => {\n const persisted = loadPersistedColumns(persistColumnsKey);\n return new Set((columns ?? []).filter((c) => isColumnInitiallyVisible(c, persisted)).map((c) => c.key));\n });\n // The set of column keys the internal visibility state was last reconciled\n // against. The lazy initializer above only runs at mount, so without this a\n // list that mounts in list mode (no columns) and later switches to table mode\n // would keep an empty visible set and render no columns.\n const knownColumnKeysRef = useRef<Set<string>>(new Set((columns ?? []).map((c) => c.key)));\n\n // Re-derive internal visibility when the column set changes at runtime: new\n // columns get their saved/default visibility, removed columns drop out, and\n // existing columns keep whatever the user toggled them to. This is also what\n // applies persisted settings when a list switches from list mode to table\n // mode (columns absent at mount, supplied later).\n useEffect(() => {\n if (isControlled) return;\n const cols = columns ?? [];\n const currentKeys = new Set(cols.map((c) => c.key));\n const known = knownColumnKeysRef.current;\n let identical = currentKeys.size === known.size;\n if (identical)\n for (const k of currentKeys)\n if (!known.has(k)) {\n identical = false;\n break;\n }\n if (identical) return;\n knownColumnKeysRef.current = currentKeys;\n const persisted = loadPersistedColumns(persistColumnsKey);\n setInternalVisibleKeys((prev) => {\n const next = new Set<string>();\n for (const c of cols) {\n if (known.has(c.key)) {\n if (prev.has(c.key)) next.add(c.key); // preserve the current-session choice\n } else if (isColumnInitiallyVisible(c, persisted)) {\n next.add(c.key); // newly-added column: saved setting, else defaultHidden\n }\n }\n return next;\n });\n }, [columns, isControlled, persistColumnsKey]);\n\n // Persist visibility whenever it changes (uncontrolled mode only). Skip while\n // there are no columns, or the transient empty state during a list→table\n // switch before the reconcile effect above has filled in the visible set —\n // writing then would clobber the saved config with an empty set.\n useEffect(() => {\n if (isControlled || !persistColumnsKey || typeof window === 'undefined') return;\n const cols = columns ?? [];\n if (cols.length === 0 || internalVisibleKeys.size === 0) return;\n try {\n window.localStorage.setItem(\n COLUMN_STORAGE_PREFIX + persistColumnsKey,\n JSON.stringify({\n visible: [...internalVisibleKeys],\n known: cols.map((c) => c.key),\n widths: userWidths,\n } satisfies PersistedColumns),\n );\n } catch {\n // Storage full or unavailable — non-fatal, just don't persist.\n }\n }, [internalVisibleKeys, columns, isControlled, persistColumnsKey, userWidths]);\n\n // Locked columns can never be hidden — force them into the visible set even if\n // a controlled `visibleColumnKeys` or persisted state omits them. Only clone\n // (rather than mutate the state Set) when a locked key is actually missing;\n // in uncontrolled mode they're already present via isColumnInitiallyVisible.\n const baseVisible: Set<string> = isControlled ? new Set(visibleColumnKeys) : internalVisibleKeys;\n const lockedKeys = (columns ?? []).filter((c) => c.lockVisible).map((c) => c.key);\n const effectiveVisible: Set<string> = lockedKeys.some((k) => !baseVisible.has(k))\n ? new Set([...baseVisible, ...lockedKeys])\n : baseVisible;\n\n const hasColumns = !!columns?.length;\n const visibleColumns = hasColumns ? columns!.filter((c) => effectiveVisible.has(c.key)) : [];\n // A column counts as \"manually hidden\" only if it's default-visible yet\n // currently hidden — a defaultHidden column being hidden is its default\n // state, not a user choice, so it never contributes to the chip.\n const manuallyHiddenCount = hasColumns\n ? columns!.filter((c) => !c.defaultHidden && !effectiveVisible.has(c.key)).length\n : 0;\n const selectPrefix = multiSelect && hasColumns ? '40px ' : '';\n const columnTemplate = hasColumns\n ? `${selectPrefix}${isFrozen ? buildFrozenTemplate(visibleColumns) : buildColumnTemplate(visibleColumns, fitWidths)}`\n : undefined;\n // Hide the gear entirely when nothing is left to toggle (every column opts out).\n const shouldShowToggle = showColumnToggle !== false && hasColumns && columns!.some((c) => !c.hideFromToggle);\n\n // Sum of the tracks, so the header and body can stretch past the viewport and\n // the list scrolls horizontally instead of clipping. Kept as a `calc()` over\n // the same custom properties the tracks read, so a drag rewriting one of them\n // resizes the row canvas in the same layout pass.\n const widthVars: React.CSSProperties = {};\n if (isFrozen && hasColumns) {\n const parts = visibleColumns.map((c) => `var(${columnWidthVar(c.key)}, ${DEFAULT_FROZEN_WIDTH}px)`);\n if (multiSelect) parts.unshift('40px');\n if (shouldShowToggle) parts.push('32px');\n (widthVars as Record<string, string>)['--vl-total'] = `calc(${parts.join(' + ')})`;\n }\n\n // ── `fit` column width measurement ──────────────────────────────────────────\n const fitColumns = visibleColumns.filter((c) => c.width.type === 'fit');\n // A frozen layout is exact px and ignores the pins, so measuring would only\n // fight the user: `measureFitWidths` never shrinks a column, and every drag\n // narrower than the content would be undone on the next scroll frame.\n const hasFit = !isFrozen && fitColumns.length > 0;\n const fitColKey = fitColumns.map((c) => c.key).join('|');\n\n // Drop the measured pins when the data or the fit-column set changes, so the\n // measure effect below re-reads the true intrinsic width on the next pass —\n // this is what lets a column shrink (during scroll the effect only grows it,\n // to avoid jitter). Resetting state during render is React's recommended\n // pattern for \"reset on prop change\" and avoids a cascading effect render.\n const [fitReset, setFitReset] = useState<{ key: string; items: T[] }>({ key: fitColKey, items });\n if (fitReset.key !== fitColKey || fitReset.items !== items) {\n setFitReset({ key: fitColKey, items });\n if (Object.keys(fitWidths).length > 0) setFitWidths({});\n }\n\n // Measure every fit cell currently in the DOM (header + visible rows), keyed\n // by its `data-fit-key`, and grow each column's pin to the widest. Reading the\n // key off the DOM (rather than closing over `fitColumns`) keeps this a stable\n // callback the ResizeObserver below can reuse. `measureCellWidth` reports the\n // true content width even when the cell is pinned narrower, so a later pass\n // always recovers a column first measured while it was still empty.\n const measureFitWidths = useCallback(() => {\n const root = rootRef.current;\n if (!root) return;\n const maxByKey = new Map<string, number>();\n root.querySelectorAll('[data-fit-key]').forEach((node) => {\n const el = node as HTMLElement;\n const key = el.getAttribute('data-fit-key');\n if (!key) return;\n const w = measureCellWidth(el);\n if (w > (maxByKey.get(key) ?? 0)) maxByKey.set(key, w);\n });\n if (maxByKey.size === 0) return;\n setFitWidths((prev) => {\n let changed = false;\n const next = { ...prev };\n for (const [key, max] of maxByKey) {\n if (max <= 0) continue;\n // Cap at the viewport width so one oversized cell can't blow out layout.\n const pinned = Math.min(Math.ceil(max), root.clientWidth);\n if (pinned > (prev[key] ?? 0)) {\n next[key] = pinned;\n changed = true;\n }\n }\n return changed ? next : prev;\n });\n }, [rootRef]);\n\n // One ResizeObserver shared across all fit cells. It re-measures whenever a\n // cell's box changes — crucially when content first appears after mount (which\n // changes the cell's height even while its width is pinned), so a too-early or\n // empty-cell measure self-corrects instead of sticking. Its initial callback\n // also fires once after layout settles, covering route transitions and other\n // post-mount layout shifts without depending on font/rAF timing.\n const [fitObserver] = useState<ResizeObserver | null>(() =>\n typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(() => measureFitWidths()),\n );\n const observedRef = useRef<Set<Element>>(new Set());\n useEffect(\n () => () => {\n fitObserver?.disconnect();\n observedRef.current.clear();\n },\n [fitObserver],\n );\n\n // Measure synchronously (before paint, so a wider row scrolling in never shows\n // a clipped frame), then *diff* the observed set rather than re-observing every\n // cell. Re-observing fires a redundant ResizeObserver callback per node, and\n // `startIndex`/`endIndex` change every scroll frame — so observing only the\n // cells that entered (and dropping the ones that left) keeps stable, already\n // pinned cells from generating any observer traffic while scrolling. A newly\n // entered cell still fires exactly once, which is when we want to measure it.\n useLayoutEffect(() => {\n if (!hasFit) return;\n const root = rootRef.current;\n if (!root) return;\n measureFitWidths();\n if (!fitObserver) return;\n const current = new Set<Element>(root.querySelectorAll('[data-fit-key]'));\n const observed = observedRef.current;\n for (const el of observed)\n if (!current.has(el)) {\n fitObserver.unobserve(el);\n observed.delete(el);\n }\n for (const el of current)\n if (!observed.has(el)) {\n fitObserver.observe(el);\n observed.add(el);\n }\n }, [\n rootRef,\n hasFit,\n fitColKey,\n fitWidths,\n startIndex,\n endIndex,\n containerHeight,\n containerWidth,\n items,\n measureFitWidths,\n fitObserver,\n ]);\n\n // Cheap insurance: re-measure on the next two frames after mount / data /\n // fit-column changes, in case the icons (or the injected FontAwesome sizing\n // CSS) resolve a frame after the first synchronous pass. Safe and scoped —\n // measureFitWidths only ever grows a pin, and this runs on mount / data change\n // (not every scroll frame), so it keeps the diff-observe perf win.\n useEffect(() => {\n if (!hasFit) return;\n let raf2 = 0;\n const raf1 = requestAnimationFrame(() => {\n measureFitWidths();\n raf2 = requestAnimationFrame(() => measureFitWidths());\n });\n return () => {\n cancelAnimationFrame(raf1);\n cancelAnimationFrame(raf2);\n };\n }, [hasFit, fitColKey, items, measureFitWidths]);\n\n // Force a fresh fit-column measure regardless of current pins. Always installs\n // a new empty object so the measure layout effect re-runs even when nothing\n // was pinned (e.g. content changed while the column was still fit-content).\n const recalculateColumns = useCallback(() => setFitWidths({}), []);\n\n function handleToggleColumn(key: string) {\n // Locked columns can't be toggled off.\n if (columns?.find((c) => c.key === key)?.lockVisible) return;\n const next = new Set(effectiveVisible);\n if (next.has(key)) {\n if (next.size <= 1) return;\n next.delete(key);\n } else {\n next.add(key);\n }\n const nextArray = [...next];\n if (!isControlled) setInternalVisibleKeys(next);\n onVisibleColumnsChange?.(nextArray);\n }\n\n return {\n hasColumns,\n visibleColumns,\n columnTemplate,\n widthVars,\n shouldShowToggle,\n effectiveVisible,\n manuallyHiddenCount,\n toggleOpen,\n setToggleOpen,\n handleToggleColumn,\n recalculateColumns,\n };\n}\n"],"mappings":"sTAiEA,SAAgB,EAAc,CAC5B,UACA,QACA,cACA,oBACA,yBACA,oBACA,mBACA,aACA,WACA,UACA,aACA,WACA,kBACA,kBACyC,CACzC,I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I,IAAa,EAAK,iBAAiB,gBAAgB,CAAC,EAClE,EAAW,EAAY,QAC7B,IAAK,IAAM,KAAM,EACV,EAAQ,IAAI,CAAE,IACjB,EAAY,UAAU,CAAE,EACxB,EAAS,OAAO,CAAE,GAEtB,IAAK,IAAM,KAAM,EACV,EAAS,IAAI,CAAE,IAClB,EAAY,QAAQ,CAAE,EACtB,EAAS,IAAI,CAAE,EAErB,EAAG,CACD,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,CACF,CAAC,EAOD,MAAgB,CACd,GAAI,CAAC,EAAQ,OACb,IAAI,EAAO,EACL,EAAO,0BAA4B,CACvC,EAAiB,EACjB,EAAO,0BAA4B,EAAiB,CAAC,CACvD,CAAC,EACD,UAAa,CACX,qBAAqB,CAAI,EACzB,qBAAqB,CAAI,CAC3B,CACF,EAAG,CAAC,EAAQ,EAAW,EAAO,CAAgB,CAAC,EAK/C,IAAM,EAAqB,MAAkB,EAAa,CAAC,CAAC,EAAG,CAAC,CAAC,EAEjE,SAAS,EAAmB,EAAa,CAEvC,GAAI,GAAS,KAAM,GAAM,EAAE,MAAQ,CAAG,CAAC,EAAE,YAAa,OACtD,IAAM,EAAO,IAAI,IAAI,CAAgB,EACrC,GAAI,EAAK,IAAI,CAAG,EAAG,CACjB,GAAI,EAAK,MAAQ,EAAG,OACpB,EAAK,OAAO,CAAG,CACjB,MACE,EAAK,IAAI,CAAG,EAEd,IAAM,EAAY,CAAC,GAAG,CAAI,EACrB,GAAc,EAAuB,CAAI,EAC9C,IAAyB,CAAS,CACpC,CAEA,MAAO,CACL,aACA,iBACA,iBACA,YACA,mBACA,mBACA,sBACA,aACA,gBACA,qBACA,oBACF,CACF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{useRef as e,useState as t}from"react";function n(n){let[r,i]=t(0),a=e([]),o=Math.min(r,Math.max(0,n-1));o!==r&&i(o);function s(e){let t=Math.max(0,Math.min(e,n-1));i(t),a.current[t]?.focus()}function c(e){return{tabIndex:e===o?0:-1,ref:t=>{a.current[e]=t},onFocus:()=>i(e)}}function l(e,t){if(e.altKey||e.ctrlKey||e.metaKey)return!1;switch(e.key){case`ArrowRight`:s(t+1);break;case`ArrowLeft`:s(t-1);break;case`Home`:s(0);break;case`End`:s(n-1);break;default:return!1}return e.preventDefault(),e.stopPropagation(),!0}return{getStationProps:c,handleNavigationKey:l}}export{n as useHeaderNavigation};
|
|
2
|
+
//# sourceMappingURL=useHeaderNavigation.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useHeaderNavigation.mjs","names":[],"sources":["../../../../package/common/virtualList/useHeaderNavigation.ts"],"sourcesContent":["import React, { useRef, useState } from 'react';\n\ninterface StationProps {\n tabIndex: number;\n ref: (el: HTMLElement | null) => void;\n onFocus: () => void;\n}\n\ninterface UseHeaderNavigationResult {\n getStationProps: (index: number) => StationProps;\n /** True when the key moved the focus, so the caller stops handling it. */\n handleNavigationKey: (event: React.KeyboardEvent, index: number) => boolean;\n}\n\n/**\n * Roving tab stop across the header: the select-all cell, every column header,\n * and the column menu are stations, and arrow keys move between them.\n *\n * Without it each of those is its own tab stop, so a table with eight sortable,\n * resizable columns takes seventeen presses of Tab before the data. The stops\n * also belong together: they all act on the same header, which is exactly the\n * case the roving pattern exists for.\n */\nexport function useHeaderNavigation(stationCount: number): UseHeaderNavigationResult {\n const [activeIndex, setActiveIndex] = useState(0);\n const stationsRef = useRef<(HTMLElement | null)[]>([]);\n\n // Hiding a column can shrink the header past the active station. Clamping\n // during render rather than in an effect keeps the header from painting a\n // single frame with no tab stop at all.\n const active = Math.min(activeIndex, Math.max(0, stationCount - 1));\n if (active !== activeIndex) setActiveIndex(active);\n\n function focusStation(index: number) {\n const next = Math.max(0, Math.min(index, stationCount - 1));\n setActiveIndex(next);\n stationsRef.current[next]?.focus();\n }\n\n function getStationProps(index: number): StationProps {\n return {\n tabIndex: index === active ? 0 : -1,\n ref: (el: HTMLElement | null) => {\n stationsRef.current[index] = el;\n },\n // Also fires for a click, which keeps the tab stop where the user last\n // was rather than snapping back to the first column.\n onFocus: () => setActiveIndex(index),\n };\n }\n\n function handleNavigationKey(event: React.KeyboardEvent, index: number): boolean {\n // Alt is the resize modifier, so those combinations belong to the station.\n if (event.altKey || event.ctrlKey || event.metaKey) return false;\n switch (event.key) {\n case 'ArrowRight':\n focusStation(index + 1);\n break;\n case 'ArrowLeft':\n focusStation(index - 1);\n break;\n case 'Home':\n focusStation(0);\n break;\n case 'End':\n focusStation(stationCount - 1);\n break;\n default:\n return false;\n }\n event.preventDefault();\n event.stopPropagation();\n return true;\n }\n\n return { getStationProps, handleNavigationKey };\n}\n"],"mappings":"6CAuBA,SAAgB,EAAoB,EAAiD,CACnF,GAAM,CAAC,EAAa,GAAkB,EAAS,CAAC,EAC1C,EAAc,EAA+B,CAAC,CAAC,EAK/C,EAAS,KAAK,IAAI,EAAa,KAAK,IAAI,EAAG,EAAe,CAAC,CAAC,EAC9D,IAAW,GAAa,EAAe,CAAM,EAEjD,SAAS,EAAa,EAAe,CACnC,IAAM,EAAO,KAAK,IAAI,EAAG,KAAK,IAAI,EAAO,EAAe,CAAC,CAAC,EAC1D,EAAe,CAAI,EACnB,EAAY,QAAQ,EAAK,EAAE,MAAM,CACnC,CAEA,SAAS,EAAgB,EAA6B,CACpD,MAAO,CACL,SAAU,IAAU,EAAS,EAAI,GACjC,IAAM,GAA2B,CAC/B,EAAY,QAAQ,GAAS,CAC/B,EAGA,YAAe,EAAe,CAAK,CACrC,CACF,CAEA,SAAS,EAAoB,EAA4B,EAAwB,CAE/E,GAAI,EAAM,QAAU,EAAM,SAAW,EAAM,QAAS,MAAO,GAC3D,OAAQ,EAAM,IAAd,CACE,IAAK,aACH,EAAa,EAAQ,CAAC,EACtB,MACF,IAAK,YACH,EAAa,EAAQ,CAAC,EACtB,MACF,IAAK,OACH,EAAa,CAAC,EACd,MACF,IAAK,MACH,EAAa,EAAe,CAAC,EAC7B,MACF,QACE,MAAO,EACX,CAGA,OAFA,EAAM,eAAe,EACrB,EAAM,gBAAgB,EACf,EACT,CAEA,MAAO,CAAE,kBAAiB,qBAAoB,CAChD"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{ROW_ENTER_SELECTOR as e,findStartIndex as t}from"./virtualList.utils.mjs";import{useRef as n,useState as r}from"react";function i({enabled:i,rowCount:a,offsets:o,rootRef:s,headerRef:c,scrollToIndex:l,initialIndex:u,multiSelect:d,onActivate:f,onToggleSelect:p}){let[m,h]=r(u),[g,_]=r(-1),v=n(o);v.current=o;let y=i&&a>0?Math.min(Math.max(m,0),a-1):-1;y>=0&&y!==m&&h(y);function b(e){let t=s.current;if(!t)return;let n=c.current?.offsetHeight??0,r=v.current[e]??0,i=v.current[e+1]??r;r<t.scrollTop+n?l(e,{align:`start`}):i>t.scrollTop+t.clientHeight&&l(e,{align:`end`})}function x(e){let t=Math.max(0,Math.min(e,a-1));h(t),b(t)}function S(e){let n=s.current;if(!n)return 1;let r=Math.max(0,n.clientHeight-(c.current?.offsetHeight??0)),i=t(v.current,(v.current[e]??0)+r,a);return Math.max(1,i-e)}function C(t){let n=(s.current?.querySelector(`[data-index="${t}"]`))?.querySelector(e);return n?(_(t),n.focus(),!0):!1}function w(e){let t=e?.closest?.(`[data-index]`),n=Number(t?.dataset.index);return Number.isFinite(n)?n:-1}function T(e){if(e.target===e.currentTarget)return;let t=w(e.target);t<0||(_(t),h(t))}function E(e){w(e.relatedTarget)!==g&&_(-1)}function D(e){if(e.key!==`Escape`||e.defaultPrevented)return;let t=w(e.target);t>=0&&h(t),_(-1),s.current?.focus(),e.preventDefault()}function O(e){if(e.target!==e.currentTarget){D(e);return}switch(e.key){case`ArrowDown`:x(y+1);break;case`ArrowUp`:x(y-1);break;case`Home`:x(0);break;case`End`:x(a-1);break;case`PageDown`:x(y+S(y));break;case`PageUp`:x(y-S(Math.max(0,y-1)));break;case`Enter`:if(f)f(y);else if(!C(y))return;break;case`F2`:if(!C(y))return;break;case` `:if(!d)return;p(y);break;default:return}e.preventDefault()}return y<0?{activeIndex:y,enteredIndex:-1,setActiveIndex:h,containerProps:{}}:{activeIndex:y,enteredIndex:g,setActiveIndex:h,containerProps:{tabIndex:0,onKeyDown:O,onFocus:T,onBlur:E}}}export{i as useRowNavigation};
|
|
2
|
+
//# sourceMappingURL=useRowNavigation.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useRowNavigation.mjs","names":[],"sources":["../../../../package/common/virtualList/useRowNavigation.ts"],"sourcesContent":["import React, { useRef, useState } from 'react';\n\nimport { findStartIndex, ROW_ENTER_SELECTOR } from './virtualList.utils';\nimport type { VirtualListScrollOptions } from './virtualList.types';\n\ninterface UseRowNavigationArgs {\n enabled: boolean;\n rowCount: number;\n /** Row tops, from the windowing engine, used for paging and visibility. */\n offsets: number[];\n rootRef: React.RefObject<HTMLDivElement | null>;\n headerRef: React.RefObject<HTMLDivElement | null>;\n scrollToIndex: (index: number, options?: VirtualListScrollOptions) => void;\n /** Row index the active row starts on, normally the selected one. */\n initialIndex: number;\n multiSelect: boolean;\n /** Undefined when the consumer gave the rows no activation of their own. */\n onActivate?: (index: number) => void;\n onToggleSelect: (index: number) => void;\n}\n\ninterface UseRowNavigationResult {\n /** Index of the row the arrow keys are on, or -1 when navigation is off. */\n activeIndex: number;\n /** Keeps the arrow keys where the pointer last was. */\n setActiveIndex: (index: number) => void;\n /**\n * The row currently being used, or -1. Its controls are in the tab order and\n * it stays mounted even when it scrolls out of the window.\n */\n enteredIndex: number;\n containerProps: {\n tabIndex?: number;\n onKeyDown?: (event: React.KeyboardEvent) => void;\n onFocus?: (event: React.FocusEvent) => void;\n onBlur?: (event: React.FocusEvent) => void;\n };\n}\n\n/**\n * Arrow-key navigation over the rows, with the tab stop on the list itself.\n *\n * The stop cannot sit on the active row, the way a roving tabindex normally\n * would: a virtualized row unmounts when it scrolls out of the window, and the\n * list would be left with no tab stop at all (the same reason `Tree` puts its\n * stop on its container). Instead the list keeps the focus and points at the\n * active row with `aria-activedescendant`.\n *\n * Keys are only handled when the list element itself has the focus. A cell may\n * hold an input, a dropdown or a button, and every one of them wants the arrows,\n * Enter and Space for itself. `F2` steps into such a row and `Escape` steps back\n * out, which is the one pair of keys that does work from inside a cell.\n */\nexport function useRowNavigation({\n enabled,\n rowCount,\n offsets,\n rootRef,\n headerRef,\n scrollToIndex,\n initialIndex,\n multiSelect,\n onActivate,\n onToggleSelect,\n}: UseRowNavigationArgs): UseRowNavigationResult {\n const [index, setIndex] = useState(initialIndex);\n const [enteredIndex, setEnteredIndex] = useState(-1);\n const offsetsRef = useRef(offsets);\n offsetsRef.current = offsets;\n\n // Rows come and go (a filter, a page, a reset), so the active index is clamped\n // during render rather than corrected in an effect.\n const activeIndex = enabled && rowCount > 0 ? Math.min(Math.max(index, 0), rowCount - 1) : -1;\n if (activeIndex >= 0 && activeIndex !== index) setIndex(activeIndex);\n\n /** Scrolls only when the row isn't already fully in view, so paging doesn't jump. */\n function revealRow(target: number) {\n const el = rootRef.current;\n if (!el) return;\n const headerHeight = headerRef.current?.offsetHeight ?? 0;\n const rowTop = offsetsRef.current[target] ?? 0;\n const rowBottom = offsetsRef.current[target + 1] ?? rowTop;\n if (rowTop < el.scrollTop + headerHeight) scrollToIndex(target, { align: 'start' });\n else if (rowBottom > el.scrollTop + el.clientHeight) scrollToIndex(target, { align: 'end' });\n }\n\n function moveTo(target: number) {\n const next = Math.max(0, Math.min(target, rowCount - 1));\n setIndex(next);\n revealRow(next);\n }\n\n /** How many rows fit in the viewport below the sticky header, at least one. */\n function pageSize(from: number): number {\n const el = rootRef.current;\n if (!el) return 1;\n const usable = Math.max(0, el.clientHeight - (headerRef.current?.offsetHeight ?? 0));\n const edge = findStartIndex(offsetsRef.current, (offsetsRef.current[from] ?? 0) + usable, rowCount);\n return Math.max(1, edge - from);\n }\n\n /** Moves the focus into the row's first control. False when it has none. */\n function enterRow(target: number): boolean {\n const row = rootRef.current?.querySelector(`[data-index=\"${target}\"]`);\n const focusable = row?.querySelector<HTMLElement>(ROW_ENTER_SELECTOR);\n if (!focusable) return false;\n // The row's controls are still out of the tab order at this point, which is\n // no obstacle to focusing one directly; the render that follows puts them\n // back in, so Tab then moves along that row.\n setEnteredIndex(target);\n focusable.focus();\n return true;\n }\n\n function rowIndexOf(node: EventTarget | null): number {\n const row = (node as HTMLElement | null)?.closest?.<HTMLElement>('[data-index]');\n const parsed = Number(row?.dataset.index);\n return Number.isFinite(parsed) ? parsed : -1;\n }\n\n /** A click or a Tab landing in a row counts as entering it, same as F2. */\n function handleFocus(event: React.FocusEvent) {\n if (event.target === event.currentTarget) return;\n const rowIndex = rowIndexOf(event.target);\n if (rowIndex < 0) return;\n setEnteredIndex(rowIndex);\n setIndex(rowIndex);\n }\n\n /** Leaving the entered row puts its controls back out of the tab order. */\n function handleBlur(event: React.FocusEvent) {\n if (rowIndexOf(event.relatedTarget) === enteredIndex) return;\n setEnteredIndex(-1);\n }\n\n /** Escape from inside a cell: hands the focus back to the list. */\n function handleExitKey(event: React.KeyboardEvent): void {\n // Something inside the row may own Escape, a dropdown closing for instance.\n if (event.key !== 'Escape' || event.defaultPrevented) return;\n const rowIndex = rowIndexOf(event.target);\n if (rowIndex >= 0) setIndex(rowIndex);\n setEnteredIndex(-1);\n rootRef.current?.focus();\n event.preventDefault();\n }\n\n function handleKeyDown(event: React.KeyboardEvent) {\n // Focus inside a cell means the row's own content is being used.\n if (event.target !== event.currentTarget) {\n handleExitKey(event);\n return;\n }\n switch (event.key) {\n case 'ArrowDown':\n moveTo(activeIndex + 1);\n break;\n case 'ArrowUp':\n moveTo(activeIndex - 1);\n break;\n case 'Home':\n moveTo(0);\n break;\n case 'End':\n moveTo(rowCount - 1);\n break;\n case 'PageDown':\n moveTo(activeIndex + pageSize(activeIndex));\n break;\n case 'PageUp':\n moveTo(activeIndex - pageSize(Math.max(0, activeIndex - 1)));\n break;\n case 'Enter':\n // With no activation of its own, a row's content is the only thing\n // Enter could mean, so it steps in rather than doing nothing.\n if (onActivate) onActivate(activeIndex);\n else if (!enterRow(activeIndex)) return;\n break;\n case 'F2':\n if (!enterRow(activeIndex)) return;\n break;\n case ' ':\n if (!multiSelect) return;\n onToggleSelect(activeIndex);\n break;\n default:\n return;\n }\n // Reached only by a handled key, so the page never scrolls under the list.\n event.preventDefault();\n }\n\n if (activeIndex < 0) return { activeIndex, enteredIndex: -1, setActiveIndex: setIndex, containerProps: {} };\n return {\n activeIndex,\n enteredIndex,\n setActiveIndex: setIndex,\n containerProps: { tabIndex: 0, onKeyDown: handleKeyDown, onFocus: handleFocus, onBlur: handleBlur },\n };\n}\n"],"mappings":"8HAqDA,SAAgB,EAAiB,CAC/B,UACA,WACA,UACA,UACA,YACA,gBACA,eACA,cACA,aACA,kBAC+C,CAC/C,GAAM,CAAC,EAAO,GAAY,EAAS,CAAY,EACzC,CAAC,EAAc,GAAmB,EAAS,EAAE,EAC7C,EAAa,EAAO,CAAO,EACjC,EAAW,QAAU,EAIrB,IAAM,EAAc,GAAW,EAAW,EAAI,KAAK,IAAI,KAAK,IAAI,EAAO,CAAC,EAAG,EAAW,CAAC,EAAI,GACvF,GAAe,GAAK,IAAgB,GAAO,EAAS,CAAW,EAGnE,SAAS,EAAU,EAAgB,CACjC,IAAM,EAAK,EAAQ,QACnB,GAAI,CAAC,EAAI,OACT,IAAM,EAAe,EAAU,SAAS,cAAgB,EAClD,EAAS,EAAW,QAAQ,IAAW,EACvC,EAAY,EAAW,QAAQ,EAAS,IAAM,EAChD,EAAS,EAAG,UAAY,EAAc,EAAc,EAAQ,CAAE,MAAO,OAAQ,CAAC,EACzE,EAAY,EAAG,UAAY,EAAG,cAAc,EAAc,EAAQ,CAAE,MAAO,KAAM,CAAC,CAC7F,CAEA,SAAS,EAAO,EAAgB,CAC9B,IAAM,EAAO,KAAK,IAAI,EAAG,KAAK,IAAI,EAAQ,EAAW,CAAC,CAAC,EACvD,EAAS,CAAI,EACb,EAAU,CAAI,CAChB,CAGA,SAAS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MACF,IAAK,OACH,EAAO,CAAC,EACR,MACF,IAAK,MACH,EAAO,EAAW,CAAC,EACnB,MACF,IAAK,WACH,EAAO,EAAc,EAAS,CAAW,CAAC,EAC1C,MACF,IAAK,SACH,EAAO,EAAc,EAAS,KAAK,IAAI,EAAG,EAAc,CAAC,CAAC,CAAC,EAC3D,MACF,IAAK,QAGH,GAAI,EAAY,EAAW,CAAW,OACjC,GAAI,CAAC,EAAS,CAAW,EAAG,OACjC,MACF,IAAK,KACH,GAAI,CAAC,EAAS,CAAW,EAAG,OAC5B,MACF,IAAK,IACH,GAAI,CAAC,EAAa,OAClB,EAAe,CAAW,EAC1B,MACF,QACE,MACJ,CAEA,EAAM,eAAe,CACvB,CAGA,OADI,EAAc,EAAU,CAAE,cAAa,aAAc,GAAI,eAAgB,EAAU,eAAgB,CAAC,CAAE,EACnG,CACL,cACA,eACA,eAAgB,EAChB,eAAgB,CAAE,SAAU,EAAG,UAAW,EAAe,QAAS,EAAa,OAAQ,CAAW,CACpG,CACF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{nextSort as e,sortItems as t}from"./virtualList.utils.mjs";import{useMemo as n,useState as r}from"react";function i({items:i,columns:a,sort:o,defaultSort:s=null,onSortChange:c}){let l=o!==void 0,[u,d]=r(s),f=l?o:u,p=n(()=>t(i,f,a),[i,f,a]);function m(t){let n=e(f,t);l||d(n),c?.(n)}return{rows:p,effectiveSort:f,isSorted:p!==i,handleHeaderSort:m}}export{i as useSorting};
|
|
2
|
+
//# sourceMappingURL=useSorting.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useSorting.mjs","names":[],"sources":["../../../../package/common/virtualList/useSorting.ts"],"sourcesContent":["import { useMemo, useState } from 'react';\n\nimport { nextSort, sortItems } from './virtualList.utils';\nimport type { VirtualListColumn, VirtualListSort } from './virtualList.types';\n\ninterface UseSortingArgs<T> {\n items: T[];\n columns?: VirtualListColumn<T>[];\n /** Controlled sort. When provided, internal state is ignored. */\n sort?: VirtualListSort | null;\n defaultSort?: VirtualListSort | null;\n onSortChange?: (sort: VirtualListSort | null) => void;\n}\n\ninterface UseSortingResult<T> {\n /** `items`, reordered when the sorted column carries a comparator. */\n rows: T[];\n effectiveSort: VirtualListSort | null;\n /** True only when this hook reordered the rows, not when it merely reported. */\n isSorted: boolean;\n handleHeaderSort: (key: string) => void;\n}\n\n/**\n * Header sorting, controlled or uncontrolled. Whether the list reorders the data\n * or only reports the click is the column's decision, not a prop: a column with\n * `sortValue`/`compare` is sorted here, a bare `sortable` one is left alone so a\n * server-side sort can own it. Sorting a paginated list here would silently\n * order only the rows loaded so far.\n */\nexport function useSorting<T>({\n items,\n columns,\n sort,\n defaultSort = null,\n onSortChange,\n}: UseSortingArgs<T>): UseSortingResult<T> {\n const isControlled = sort !== undefined;\n const [internalSort, setInternalSort] = useState<VirtualListSort | null>(defaultSort);\n const effectiveSort = isControlled ? sort! : internalSort;\n\n // Returns `items` itself when nothing applies, which is what `isSorted` reads.\n const rows = useMemo(() => sortItems(items, effectiveSort, columns), [items, effectiveSort, columns]);\n\n function handleHeaderSort(key: string) {\n const next = nextSort(effectiveSort, key);\n if (!isControlled) setInternalSort(next);\n onSortChange?.(next);\n }\n\n return { rows, effectiveSort, isSorted: rows !== items, handleHeaderSort };\n}\n"],"mappings":"gHA8BA,SAAgB,EAAc,CAC5B,QACA,UACA,OACA,cAAc,KACd,gBACyC,CACzC,IAAM,EAAe,IAAS,IAAA,GACxB,CAAC,EAAc,GAAmB,EAAiC,CAAW,EAC9E,EAAgB,EAAe,EAAQ,EAGvC,EAAO,MAAc,EAAU,EAAO,EAAe,CAAO,EAAG,CAAC,EAAO,EAAe,CAAO,CAAC,EAEpG,SAAS,EAAiB,EAAa,CACrC,IAAM,EAAO,EAAS,EAAe,CAAG,EACnC,GAAc,EAAgB,CAAI,EACvC,IAAe,CAAI,CACrB,CAEA,MAAO,CAAE,OAAM,gBAAe,SAAU,IAAS,EAAO,kBAAiB,CAC3E"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{buildOffsets as e,findStartIndex as t,getVisibleRange as n}from"./virtualList.utils.mjs";import{useCallback as r,useEffect as i,useLayoutEffect as a,useMemo as o,useRef as s,useState as c}from"react";function l(e,t){if(typeof e==`number`)return e;let n=e.trim();if(n===``)return 0;let r=Number(n);if(!Number.isNaN(r))return r;let i=/^(-?\d*\.?\d+)px$/.exec(n);if(i)return parseFloat(i[1]);if(typeof document>`u`||!t)return 0;let a=document.createElement(`div`);a.style.cssText=`position:absolute;visibility:hidden;height:${n};`,t.appendChild(a);let o=a.getBoundingClientRect().height;return t.removeChild(a),Number.isFinite(o)?o:0}function
|
|
1
|
+
import{buildOffsets as e,findStartIndex as t,getVisibleRange as n}from"./virtualList.utils.mjs";import{useCallback as r,useEffect as i,useLayoutEffect as a,useMemo as o,useRef as s,useState as c}from"react";function l(e,t){if(typeof e==`number`)return e;let n=e.trim();if(n===``)return 0;let r=Number(n);if(!Number.isNaN(r))return r;let i=/^(-?\d*\.?\d+)px$/.exec(n);if(i)return parseFloat(i[1]);if(typeof document>`u`||!t)return 0;let a=document.createElement(`div`);a.style.cssText=`position:absolute;visibility:hidden;height:${n};`,t.appendChild(a);let o=a.getBoundingClientRect().height;return t.removeChild(a),Number.isFinite(o)?o:0}var u=20;function d({items:d,keys:f,getItemKey:p,estimatedRowHeight:m,rowGap:h,overscan:g,onLoadMore:_,loadMoreThreshold:v,isLoading:y}){let[b,x]=c(0),[S,C]=c(0),[w,T]=c(0),[E,D]=c(()=>l(h,null)),[O,k]=c(new Map),[A,j]=c(!1),M=s(!1),N=s(null),P=s(null),F=s([]),I=s(null),L=s(0),R=s([]),[z]=c(()=>typeof ResizeObserver>`u`?null:new ResizeObserver(e=>{k(t=>{let n=null;for(let r of e){let e=r.target,i=Number(e.dataset.index);if(Number.isNaN(i))continue;let a=R.current[i];if(a===void 0)continue;let o=r.borderBoxSize?.[0],s=o?Math.round(o.blockSize):e.offsetHeight;t.get(a)!==s&&(n||=new Map(t),n.set(a,s))}return n??t})}));i(()=>()=>z?.disconnect(),[z]),a(()=>{let e=N.current;if(!e)return;C(e.clientHeight),T(e.clientWidth);let t=new ResizeObserver(()=>{C(e.clientHeight),T(e.clientWidth)});return t.observe(e),()=>t.disconnect()},[]);let B=s(_);a(()=>{B.current=_});let V=r(()=>{let e=B.current;e&&!M.current&&(M.current=!0,j(!0),e().finally(()=>{M.current=!1,j(!1)}))},[]),H=r(e=>{let t=e.currentTarget;L.current=t.scrollTop,I.current??=requestAnimationFrame(()=>{I.current=null,x(L.current)}),t.scrollTop+t.clientHeight>=t.scrollHeight-v&&V()},[v,V]);i(()=>()=>{I.current!=null&&cancelAnimationFrame(I.current)},[]),a(()=>{R.current=f}),a(()=>{let e=l(h,N.current);D(t=>t===e?t:e)},[h,w,S]);let U=o(()=>{if(O.size===0)return m;let e=0;for(let t of O.values())e+=t;return e/O.size},[O,m]),{offsets:W,totalHeight:G}=o(()=>e(f,O,U,E),[f,O,U,E]),K=s(``);i(()=>{if(!_||y||A||S===0)return;let e=P.current?.offsetHeight??0;if(G>=S-e)return;let t=`${d.length}:${S}`;K.current!==t&&(K.current=t,V())},[_,y,A,d.length,G,S,V]),a(()=>{let e=N.current,n=F.current;if(F.current=W,!e||n.length===0||Y.current)return;let r=e.scrollTop;if(r<=0)return;let i=n.length-1,a=t(n,r,i);if(a>=d.length)return;let o=r-n[a],s=W[a]+o;Math.abs(s-r)>.5&&(e.scrollTop=s,L.current=s,x(s))},[W,d.length]);let q=r((e,t)=>{let n=N.current;if(!n)return;let r=Math.max(0,e);typeof n.scrollTo==`function`?n.scrollTo({top:r,behavior:t??`auto`}):n.scrollTop=r},[]),J=r((e,t)=>{let n=N.current;if(!n||d.length===0)return null;let r=Math.max(0,Math.min(e,d.length-1)),i=W[r]??0,a=(W[r+1]??i)-i,o=P.current?.offsetHeight??0,s=Math.max(0,n.clientHeight-o),c=t?.align??`start`,l=i;return c===`center`?l-=(s-a)/2:c===`end`&&(l-=s-a),l},[d.length,W]),Y=s(null);a(()=>{let e=Y.current,t=N.current;if(!e)return;let n=e.items===d&&t?J(e.index,e.options):null;if(n==null){Y.current=null;return}let r=Math.abs(n-e.lastTarget)<=1;if(r&&Math.abs(t.scrollTop-n)<=1||e.attempts>=u){Y.current=null;return}r||(e.lastTarget=n,e.attempts+=1,q(n,e.options?.behavior))}),i(()=>{let e=N.current;if(!e)return;let t=()=>{Y.current=null};return e.addEventListener(`wheel`,t,{passive:!0}),e.addEventListener(`touchstart`,t,{passive:!0}),e.addEventListener(`keydown`,t),()=>{e.removeEventListener(`wheel`,t),e.removeEventListener(`touchstart`,t),e.removeEventListener(`keydown`,t)}},[]);let X=o(()=>{function e(e,t){let n=J(e,t);n!=null&&(Y.current={index:e,options:t,lastTarget:n,attempts:0,items:d},q(n,t?.behavior))}return{scrollToIndex:e,scrollToKey(t,n){let r=d.findIndex((e,n)=>(p?p(e,n):n)===t);r>=0&&e(r,n)},scrollToTop(e){Y.current=null,q(0,e?.behavior)},getScrollElement:()=>N.current}},[d,p,J,q]),{startIndex:Z,endIndex:Q}=o(()=>n(W,b,S,g,d.length),[W,b,S,g,d.length]);return{rootRef:N,headerRef:P,rowObserver:z,keysRef:R,offsets:W,totalHeight:G,containerHeight:S,containerWidth:w,startIndex:Z,endIndex:Q,handleScroll:H,showLoadMoreSpinner:A,scrollApi:X}}export{d as useVirtualWindow};
|
|
2
2
|
//# sourceMappingURL=useVirtualWindow.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useVirtualWindow.mjs","names":[],"sources":["../../../../package/common/virtualList/useVirtualWindow.ts"],"sourcesContent":["import React, { useState, useRef, useEffect, useLayoutEffect, useMemo, useCallback } from 'react';\n\nimport { buildOffsets, findStartIndex, getVisibleRange } from './virtualList.utils';\nimport type { VirtualListHandle, VirtualListScrollOptions } from './virtualList.types';\n\n/**\n * Resolve a `rowGap` value to pixels for the offset math. Numbers and plain\n * `px`/numeric strings parse directly (no DOM, SSR/test-safe); any other CSS\n * length (`em`, `rem`, `%`, `var(...)`) is resolved via a hidden probe appended\n * to `contextEl` so it inherits the list's font-size and custom properties.\n */\nfunction resolveCssLength(value: number | string, contextEl: HTMLElement | null): number {\n if (typeof value === 'number') return value;\n const trimmed = value.trim();\n if (trimmed === '') return 0;\n const asNumber = Number(trimmed);\n if (!Number.isNaN(asNumber)) return asNumber; // \"8\" → 8\n const pxMatch = /^(-?\\d*\\.?\\d+)px$/.exec(trimmed);\n if (pxMatch) return parseFloat(pxMatch[1]); // \"8px\" → 8\n if (typeof document === 'undefined' || !contextEl) return 0;\n const probe = document.createElement('div');\n probe.style.cssText = `position:absolute;visibility:hidden;height:${trimmed};`;\n contextEl.appendChild(probe);\n const px = probe.getBoundingClientRect().height;\n contextEl.removeChild(probe);\n return Number.isFinite(px) ? px : 0;\n}\n\ninterface UseVirtualWindowArgs<T> {\n items: T[];\n /** Stable key per row (already derived by the caller). */\n keys: (string | number)[];\n getItemKey?: (item: T, index: number) => string | number;\n estimatedRowHeight: number;\n rowGap: number | string;\n overscan: number;\n onLoadMore?: () => Promise<void>;\n loadMoreThreshold: number;\n /** Initial/filter load in progress — the body is replaced by a spinner. */\n isLoading: boolean;\n}\n\ninterface UseVirtualWindowResult {\n rootRef: React.RefObject<HTMLDivElement | null>;\n headerRef: React.RefObject<HTMLDivElement | null>;\n /** Shared by every row to measure its height (read back via `data-index`). */\n rowObserver: ResizeObserver | null;\n /** Latest index → key mapping, for async consumers (e.g. the drag hook). */\n keysRef: React.RefObject<(string | number)[]>;\n offsets: number[];\n totalHeight: number;\n containerHeight: number;\n containerWidth: number;\n startIndex: number;\n endIndex: number;\n handleScroll: (e: React.UIEvent<HTMLDivElement>) => void;\n showLoadMoreSpinner: boolean;\n /** The scroll-related imperative methods, for the component to compose into\n * the forwarded handle alongside column controls. */\n scrollApi: Omit<VirtualListHandle, 'recalculateColumns'>;\n}\n\n/**\n * The generic virtualization engine: viewport measurement, per-row height\n * caching, offset/visible-range computation, scroll coalescing, scroll\n * anchoring on height changes, infinite-load triggering, and the imperative\n * scroll handle. Mode-agnostic — knows nothing about columns, selection or\n * dragging.\n */\nexport function useVirtualWindow<T>({\n items,\n keys,\n getItemKey,\n estimatedRowHeight,\n rowGap,\n overscan,\n onLoadMore,\n loadMoreThreshold,\n isLoading,\n}: UseVirtualWindowArgs<T>): UseVirtualWindowResult {\n const [scrollTop, setScrollTop] = useState(0);\n const [containerHeight, setContainerHeight] = useState(0);\n const [containerWidth, setContainerWidth] = useState(0);\n // rowGap may be any CSS length; resolve it to px for the offset math. Seed with\n // the synchronous fast path (number / px), then refine before paint for units\n // that need the DOM (em/rem/%/var).\n const [resolvedRowGap, setResolvedRowGap] = useState<number>(() => resolveCssLength(rowGap, null));\n const [heightsMap, setHeightsMap] = useState<Map<string | number, number>>(new Map());\n const [showLoadMoreSpinner, setShowLoadMoreSpinner] = useState(false);\n const isLoadingMoreRef = useRef(false);\n\n const rootRef = useRef<HTMLDivElement>(null);\n const headerRef = useRef<HTMLDivElement>(null);\n const prevOffsetsRef = useRef<number[]>([]);\n const scrollRafRef = useRef<number | null>(null);\n const pendingScrollTopRef = useRef(0);\n const keysRef = useRef<(string | number)[]>([]);\n\n // One ResizeObserver shared by every row, created once via a lazy state\n // initializer so rows mounting in the same commit can register in their\n // layout effect. Batching all entries into a single setState avoids a\n // re-render per row when many rows enter the viewport at once (the main\n // source of scroll jank). The row index is read back from `data-index`.\n const [rowObserver] = useState<ResizeObserver | null>(() => {\n if (typeof ResizeObserver === 'undefined') return null;\n return new ResizeObserver((entries) => {\n setHeightsMap((prev) => {\n let next: Map<string | number, number> | null = null;\n for (const entry of entries) {\n const el = entry.target as HTMLElement;\n const idx = Number(el.dataset.index);\n if (Number.isNaN(idx)) continue;\n // Resolve the row's stable key so the cache survives reorders/filters.\n const key = keysRef.current[idx];\n if (key === undefined) continue;\n // Prefer the size the observer already computed — reading offsetHeight\n // here would force a synchronous reflow on every measurement batch.\n const box = entry.borderBoxSize?.[0];\n const h = box ? Math.round(box.blockSize) : el.offsetHeight;\n if (prev.get(key) === h) continue;\n if (!next) next = new Map(prev);\n next.set(key, h);\n }\n return next ?? prev;\n });\n });\n });\n useEffect(() => () => rowObserver?.disconnect(), [rowObserver]);\n\n useLayoutEffect(() => {\n const el = rootRef.current;\n if (!el) return;\n // Measure synchronously before the first paint so the initial render fills\n // the viewport, instead of painting a few overscan rows and re-rendering.\n setContainerHeight(el.clientHeight);\n setContainerWidth(el.clientWidth);\n // Track width too: `fit` columns are measured against this box and capped at\n // its width, so when the container settles to its real width after a route\n // transition / async layout, that change has to re-trigger the measure —\n // otherwise an early measure against a 0/tiny width gets pinned and sticks.\n const observer = new ResizeObserver(() => {\n setContainerHeight(el.clientHeight);\n setContainerWidth(el.clientWidth);\n });\n observer.observe(el);\n return () => observer.disconnect();\n }, []);\n\n // Read through a ref so the trigger below stays stable even when the consumer\n // passes a fresh `onLoadMore` closure on every render.\n const onLoadMoreRef = useRef(onLoadMore);\n useLayoutEffect(() => {\n onLoadMoreRef.current = onLoadMore;\n });\n\n /** Start a load unless one is already in flight (and drive the bottom spinner). */\n const triggerLoadMore = useCallback(() => {\n const load = onLoadMoreRef.current;\n if (!load || isLoadingMoreRef.current) return;\n isLoadingMoreRef.current = true;\n setShowLoadMoreSpinner(true);\n load().finally(() => {\n isLoadingMoreRef.current = false;\n setShowLoadMoreSpinner(false);\n });\n }, []);\n\n const handleScroll = useCallback(\n (e: React.UIEvent<HTMLDivElement>) => {\n const el = e.currentTarget;\n // Coalesce scroll-driven re-renders to at most one per animation frame.\n // Scroll events can fire several times per frame (especially while dragging\n // the scrollbar thumb); rendering the visible window once per frame keeps\n // the content in step with the cursor instead of lagging behind.\n pendingScrollTopRef.current = el.scrollTop;\n if (scrollRafRef.current == null) {\n scrollRafRef.current = requestAnimationFrame(() => {\n scrollRafRef.current = null;\n setScrollTop(pendingScrollTopRef.current);\n });\n }\n\n if (el.scrollTop + el.clientHeight >= el.scrollHeight - loadMoreThreshold) triggerLoadMore();\n },\n [loadMoreThreshold, triggerLoadMore],\n );\n\n useEffect(\n () => () => {\n if (scrollRafRef.current != null) cancelAnimationFrame(scrollRafRef.current);\n },\n [],\n );\n\n useLayoutEffect(() => {\n keysRef.current = keys;\n });\n\n // Resolve the gap to px before paint, re-running when the value or the\n // container's layout changes (a theme/font change that alters em/var is caught\n // by the container ResizeObserver feeding containerWidth/Height).\n useLayoutEffect(() => {\n const px = resolveCssLength(rowGap, rootRef.current);\n setResolvedRowGap((prev) => (prev === px ? prev : px));\n }, [rowGap, containerWidth, containerHeight]);\n\n const { offsets, totalHeight } = useMemo(\n () => buildOffsets(keys, heightsMap, estimatedRowHeight, resolvedRowGap),\n [keys, heightsMap, estimatedRowHeight, resolvedRowGap],\n );\n\n // The scroll trigger above can only fire on a list that actually scrolls. When\n // a batch is smaller than the viewport there is no overflow, so no scroll event\n // ever happens and lazy loading dead-ends after the first batch. Keep asking\n // for more until the content overflows; the consumer ends the loop by appending\n // nothing (or by dropping `onLoadMore` once its source is exhausted).\n //\n // Each (row count, viewport height) pair is probed at most once, so rows\n // settling to their measured heights can't re-ask a source that already ran\n // dry, and progress depends entirely on the consumer appending rows.\n const fillProbeRef = useRef('');\n useEffect(() => {\n if (!onLoadMore || isLoading || showLoadMoreSpinner) return;\n // 0 while the list is unmeasured or `display: none` — nothing to fill yet.\n if (containerHeight === 0) return;\n // The sticky header eats into the scroll area, so it isn't usable space.\n const headerH = headerRef.current?.offsetHeight ?? 0;\n if (totalHeight >= containerHeight - headerH) return; // already scrollable\n const probe = `${items.length}:${containerHeight}`;\n if (fillProbeRef.current === probe) return;\n fillProbeRef.current = probe;\n triggerLoadMore();\n }, [onLoadMore, isLoading, showLoadMoreSpinner, items.length, totalHeight, containerHeight, triggerLoadMore]);\n\n useLayoutEffect(() => {\n const el = rootRef.current;\n const prevOffsets = prevOffsetsRef.current;\n prevOffsetsRef.current = offsets;\n\n // Nothing to anchor against on the first pass or when pinned at the top.\n if (!el || prevOffsets.length === 0) return;\n const curScrollTop = el.scrollTop;\n if (curScrollTop <= 0) return;\n\n // Scroll anchoring: pin the row at the top of the viewport. Find it under\n // the *previous* offsets, then re-derive scrollTop from its *new* offset so\n // it stays visually fixed when rows above it are measured or resized. This\n // is more robust than summing per-row height deltas — it can't drift, and\n // one correction covers any number of simultaneous changes above the fold.\n const prevCount = prevOffsets.length - 1;\n const anchor = findStartIndex(prevOffsets, curScrollTop, prevCount);\n if (anchor >= items.length) return;\n const within = curScrollTop - prevOffsets[anchor];\n const target = offsets[anchor] + within;\n if (Math.abs(target - curScrollTop) > 0.5) {\n el.scrollTop = target;\n pendingScrollTopRef.current = target;\n setScrollTop(target);\n }\n }, [offsets, items.length]);\n\n const scrollApi = useMemo<Omit<VirtualListHandle, 'recalculateColumns'>>(() => {\n function scrollToOffset(top: number, behavior?: ScrollBehavior) {\n const el = rootRef.current;\n if (!el) return;\n const clamped = Math.max(0, top);\n if (typeof el.scrollTo === 'function') el.scrollTo({ top: clamped, behavior: behavior ?? 'auto' });\n else el.scrollTop = clamped;\n }\n function scrollToIndex(index: number, options?: VirtualListScrollOptions) {\n const el = rootRef.current;\n if (!el || items.length === 0) return;\n const i = Math.max(0, Math.min(index, items.length - 1));\n const rowTop = offsets[i] ?? 0;\n const rowHeight = (offsets[i + 1] ?? rowTop) - rowTop;\n // The sticky header overlaps the top of the scroll area, so the usable\n // viewport starts below it — account for that when aligning.\n const headerH = headerRef.current?.offsetHeight ?? 0;\n const usable = Math.max(0, el.clientHeight - headerH);\n const align = options?.align ?? 'start';\n let top = rowTop - headerH;\n if (align === 'center') top -= (usable - rowHeight) / 2;\n else if (align === 'end') top -= usable - rowHeight;\n scrollToOffset(top, options?.behavior);\n }\n return {\n scrollToIndex,\n scrollToKey(key, options) {\n const i = items.findIndex((item, idx) => (getItemKey ? getItemKey(item, idx) : idx) === key);\n if (i >= 0) scrollToIndex(i, options);\n },\n scrollToTop(options) {\n scrollToOffset(0, options?.behavior);\n },\n getScrollElement: () => rootRef.current,\n };\n }, [items, offsets, getItemKey]);\n\n const { startIndex, endIndex } = useMemo(\n () => getVisibleRange(offsets, scrollTop, containerHeight, overscan, items.length),\n [offsets, scrollTop, containerHeight, overscan, items.length],\n );\n\n return {\n rootRef,\n headerRef,\n rowObserver,\n keysRef,\n offsets,\n totalHeight,\n containerHeight,\n containerWidth,\n startIndex,\n endIndex,\n handleScroll,\n showLoadMoreSpinner,\n scrollApi,\n };\n}\n"],"mappings":"+MAWA,SAAS,EAAiB,EAAwB,EAAuC,CACvF,GAAI,OAAO,GAAU,SAAU,OAAO,EACtC,IAAM,EAAU,EAAM,KAAK,EAC3B,GAAI,IAAY,GAAI,MAAO,GAC3B,IAAM,EAAW,OAAO,CAAO,EAC/B,GAAI,CAAC,OAAO,MAAM,CAAQ,EAAG,OAAO,EACpC,IAAM,EAAU,oBAAoB,KAAK,CAAO,EAChD,GAAI,EAAS,OAAO,WAAW,EAAQ,EAAE,EACzC,GAAI,OAAO,SAAa,KAAe,CAAC,EAAW,MAAO,GAC1D,IAAM,EAAQ,SAAS,cAAc,KAAK,EAC1C,EAAM,MAAM,QAAU,8CAA8C,EAAQ,GAC5E,EAAU,YAAY,CAAK,EAC3B,IAAM,EAAK,EAAM,sBAAsB,CAAC,CAAC,OAEzC,OADA,EAAU,YAAY,CAAK,EACpB,OAAO,SAAS,CAAE,EAAI,EAAK,CACpC,CA2CA,SAAgB,EAAoB,CAClC,QACA,OACA,aACA,qBACA,SACA,WACA,aACA,oBACA,aACkD,CAClD,GAAM,CAAC,EAAW,GAAgB,EAAS,CAAC,EACtC,CAAC,EAAiB,GAAsB,EAAS,CAAC,EAClD,CAAC,EAAgB,GAAqB,EAAS,CAAC,EAIhD,CAAC,EAAgB,GAAqB,MAAuB,EAAiB,EAAQ,IAAI,CAAC,EAC3F,CAAC,EAAY,GAAiB,EAAuC,IAAI,GAAK,EAC9E,CAAC,EAAqB,GAA0B,EAAS,EAAK,EAC9D,EAAmB,EA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Ae,EAAG,GAAS,QAAQ,CACrC,EACA,qBAAwB,EAAQ,OAClC,CACF,EAAG,CAAC,EAAO,EAAS,CAAU,CAAC,EAEzB,CAAE,aAAY,YAAa,MACzB,EAAgB,EAAS,EAAW,EAAiB,EAAU,EAAM,MAAM,EACjF,CAAC,EAAS,EAAW,EAAiB,EAAU,EAAM,MAAM,CAC9D,EAEA,MAAO,CACL,UACA,YACA,cACA,UACA,UACA,cACA,kBACA,iBACA,aACA,WACA,eACA,sBACA,WACF,CACF"}
|
|
1
|
+
{"version":3,"file":"useVirtualWindow.mjs","names":[],"sources":["../../../../package/common/virtualList/useVirtualWindow.ts"],"sourcesContent":["import React, { useState, useRef, useEffect, useLayoutEffect, useMemo, useCallback } from 'react';\n\nimport { buildOffsets, findStartIndex, getVisibleRange } from './virtualList.utils';\nimport type { VirtualListHandle, VirtualListScrollOptions } from './virtualList.types';\n\n/**\n * Resolve a `rowGap` value to pixels for the offset math. Numbers and plain\n * `px`/numeric strings parse directly (no DOM, SSR/test-safe); any other CSS\n * length (`em`, `rem`, `%`, `var(...)`) is resolved via a hidden probe appended\n * to `contextEl` so it inherits the list's font-size and custom properties.\n */\nfunction resolveCssLength(value: number | string, contextEl: HTMLElement | null): number {\n if (typeof value === 'number') return value;\n const trimmed = value.trim();\n if (trimmed === '') return 0;\n const asNumber = Number(trimmed);\n if (!Number.isNaN(asNumber)) return asNumber; // \"8\" → 8\n const pxMatch = /^(-?\\d*\\.?\\d+)px$/.exec(trimmed);\n if (pxMatch) return parseFloat(pxMatch[1]); // \"8px\" → 8\n if (typeof document === 'undefined' || !contextEl) return 0;\n const probe = document.createElement('div');\n probe.style.cssText = `position:absolute;visibility:hidden;height:${trimmed};`;\n contextEl.appendChild(probe);\n const px = probe.getBoundingClientRect().height;\n contextEl.removeChild(probe);\n return Number.isFinite(px) ? px : 0;\n}\n\ninterface UseVirtualWindowArgs<T> {\n items: T[];\n /** Stable key per row (already derived by the caller). */\n keys: (string | number)[];\n getItemKey?: (item: T, index: number) => string | number;\n estimatedRowHeight: number;\n rowGap: number | string;\n overscan: number;\n onLoadMore?: () => Promise<void>;\n loadMoreThreshold: number;\n /** Initial/filter load in progress — the body is replaced by a spinner. */\n isLoading: boolean;\n}\n\ninterface UseVirtualWindowResult {\n rootRef: React.RefObject<HTMLDivElement | null>;\n headerRef: React.RefObject<HTMLDivElement | null>;\n /** Shared by every row to measure its height (read back via `data-index`). */\n rowObserver: ResizeObserver | null;\n /** Latest index → key mapping, for async consumers (e.g. the drag hook). */\n keysRef: React.RefObject<(string | number)[]>;\n offsets: number[];\n totalHeight: number;\n containerHeight: number;\n containerWidth: number;\n startIndex: number;\n endIndex: number;\n handleScroll: (e: React.UIEvent<HTMLDivElement>) => void;\n showLoadMoreSpinner: boolean;\n /** The scroll-related imperative methods, for the component to compose into\n * the forwarded handle alongside column controls. */\n scrollApi: Omit<VirtualListHandle, 'recalculateColumns' | 'resetColumnWidths'>;\n}\n\n/**\n * The generic virtualization engine: viewport measurement, per-row height\n * caching, offset/visible-range computation, scroll coalescing, scroll\n * anchoring on height changes, infinite-load triggering, and the imperative\n * scroll handle. Mode-agnostic — knows nothing about columns, selection or\n * dragging.\n */\n/**\n * Loop guard for a jump re-aiming at its target. It normally ends because the\n * target stops moving, long before this; the cap is only there so a target that\n * can never be reached, the last row asked for with `align: 'start'`, can't\n * re-aim forever.\n */\nconst MAX_JUMP_CORRECTIONS = 20;\n\nexport function useVirtualWindow<T>({\n items,\n keys,\n getItemKey,\n estimatedRowHeight,\n rowGap,\n overscan,\n onLoadMore,\n loadMoreThreshold,\n isLoading,\n}: UseVirtualWindowArgs<T>): UseVirtualWindowResult {\n const [scrollTop, setScrollTop] = useState(0);\n const [containerHeight, setContainerHeight] = useState(0);\n const [containerWidth, setContainerWidth] = useState(0);\n // rowGap may be any CSS length; resolve it to px for the offset math. Seed with\n // the synchronous fast path (number / px), then refine before paint for units\n // that need the DOM (em/rem/%/var).\n const [resolvedRowGap, setResolvedRowGap] = useState<number>(() => resolveCssLength(rowGap, null));\n const [heightsMap, setHeightsMap] = useState<Map<string | number, number>>(new Map());\n const [showLoadMoreSpinner, setShowLoadMoreSpinner] = useState(false);\n const isLoadingMoreRef = useRef(false);\n\n const rootRef = useRef<HTMLDivElement>(null);\n const headerRef = useRef<HTMLDivElement>(null);\n const prevOffsetsRef = useRef<number[]>([]);\n const scrollRafRef = useRef<number | null>(null);\n const pendingScrollTopRef = useRef(0);\n const keysRef = useRef<(string | number)[]>([]);\n\n // One ResizeObserver shared by every row, created once via a lazy state\n // initializer so rows mounting in the same commit can register in their\n // layout effect. Batching all entries into a single setState avoids a\n // re-render per row when many rows enter the viewport at once (the main\n // source of scroll jank). The row index is read back from `data-index`.\n const [rowObserver] = useState<ResizeObserver | null>(() => {\n if (typeof ResizeObserver === 'undefined') return null;\n return new ResizeObserver((entries) => {\n setHeightsMap((prev) => {\n let next: Map<string | number, number> | null = null;\n for (const entry of entries) {\n const el = entry.target as HTMLElement;\n const idx = Number(el.dataset.index);\n if (Number.isNaN(idx)) continue;\n // Resolve the row's stable key so the cache survives reorders/filters.\n const key = keysRef.current[idx];\n if (key === undefined) continue;\n // Prefer the size the observer already computed — reading offsetHeight\n // here would force a synchronous reflow on every measurement batch.\n const box = entry.borderBoxSize?.[0];\n const h = box ? Math.round(box.blockSize) : el.offsetHeight;\n if (prev.get(key) === h) continue;\n if (!next) next = new Map(prev);\n next.set(key, h);\n }\n return next ?? prev;\n });\n });\n });\n useEffect(() => () => rowObserver?.disconnect(), [rowObserver]);\n\n useLayoutEffect(() => {\n const el = rootRef.current;\n if (!el) return;\n // Measure synchronously before the first paint so the initial render fills\n // the viewport, instead of painting a few overscan rows and re-rendering.\n setContainerHeight(el.clientHeight);\n setContainerWidth(el.clientWidth);\n // Track width too: `fit` columns are measured against this box and capped at\n // its width, so when the container settles to its real width after a route\n // transition / async layout, that change has to re-trigger the measure —\n // otherwise an early measure against a 0/tiny width gets pinned and sticks.\n const observer = new ResizeObserver(() => {\n setContainerHeight(el.clientHeight);\n setContainerWidth(el.clientWidth);\n });\n observer.observe(el);\n return () => observer.disconnect();\n }, []);\n\n // Read through a ref so the trigger below stays stable even when the consumer\n // passes a fresh `onLoadMore` closure on every render.\n const onLoadMoreRef = useRef(onLoadMore);\n useLayoutEffect(() => {\n onLoadMoreRef.current = onLoadMore;\n });\n\n /** Start a load unless one is already in flight (and drive the bottom spinner). */\n const triggerLoadMore = useCallback(() => {\n const load = onLoadMoreRef.current;\n if (!load || isLoadingMoreRef.current) return;\n isLoadingMoreRef.current = true;\n setShowLoadMoreSpinner(true);\n load().finally(() => {\n isLoadingMoreRef.current = false;\n setShowLoadMoreSpinner(false);\n });\n }, []);\n\n const handleScroll = useCallback(\n (e: React.UIEvent<HTMLDivElement>) => {\n const el = e.currentTarget;\n // Coalesce scroll-driven re-renders to at most one per animation frame.\n // Scroll events can fire several times per frame (especially while dragging\n // the scrollbar thumb); rendering the visible window once per frame keeps\n // the content in step with the cursor instead of lagging behind.\n pendingScrollTopRef.current = el.scrollTop;\n if (scrollRafRef.current == null) {\n scrollRafRef.current = requestAnimationFrame(() => {\n scrollRafRef.current = null;\n setScrollTop(pendingScrollTopRef.current);\n });\n }\n\n if (el.scrollTop + el.clientHeight >= el.scrollHeight - loadMoreThreshold) triggerLoadMore();\n },\n [loadMoreThreshold, triggerLoadMore],\n );\n\n useEffect(\n () => () => {\n if (scrollRafRef.current != null) cancelAnimationFrame(scrollRafRef.current);\n },\n [],\n );\n\n useLayoutEffect(() => {\n keysRef.current = keys;\n });\n\n // Resolve the gap to px before paint, re-running when the value or the\n // container's layout changes (a theme/font change that alters em/var is caught\n // by the container ResizeObserver feeding containerWidth/Height).\n useLayoutEffect(() => {\n const px = resolveCssLength(rowGap, rootRef.current);\n setResolvedRowGap((prev) => (prev === px ? prev : px));\n }, [rowGap, containerWidth, containerHeight]);\n\n // What an unmeasured row is assumed to be. `estimatedRowHeight` is only the\n // seed: once rows have been measured, their average is a far better guess, and\n // it is the guess every row between here and a distant jump target is made of.\n // With a fixed estimate the error compounds over that distance (40 assumed\n // against 35 real puts row 75 at row 86), and no amount of re-aiming fixes it,\n // because the rows that are wrong are precisely the ones never rendered.\n const assumedRowHeight = useMemo(() => {\n if (heightsMap.size === 0) return estimatedRowHeight;\n let total = 0;\n for (const height of heightsMap.values()) total += height;\n return total / heightsMap.size;\n }, [heightsMap, estimatedRowHeight]);\n\n const { offsets, totalHeight } = useMemo(\n () => buildOffsets(keys, heightsMap, assumedRowHeight, resolvedRowGap),\n [keys, heightsMap, assumedRowHeight, resolvedRowGap],\n );\n\n // The scroll trigger above can only fire on a list that actually scrolls. When\n // a batch is smaller than the viewport there is no overflow, so no scroll event\n // ever happens and lazy loading dead-ends after the first batch. Keep asking\n // for more until the content overflows; the consumer ends the loop by appending\n // nothing (or by dropping `onLoadMore` once its source is exhausted).\n //\n // Each (row count, viewport height) pair is probed at most once, so rows\n // settling to their measured heights can't re-ask a source that already ran\n // dry, and progress depends entirely on the consumer appending rows.\n const fillProbeRef = useRef('');\n useEffect(() => {\n if (!onLoadMore || isLoading || showLoadMoreSpinner) return;\n // 0 while the list is unmeasured or `display: none` — nothing to fill yet.\n if (containerHeight === 0) return;\n // The sticky header eats into the scroll area, so it isn't usable space.\n const headerH = headerRef.current?.offsetHeight ?? 0;\n if (totalHeight >= containerHeight - headerH) return; // already scrollable\n const probe = `${items.length}:${containerHeight}`;\n if (fillProbeRef.current === probe) return;\n fillProbeRef.current = probe;\n triggerLoadMore();\n }, [onLoadMore, isLoading, showLoadMoreSpinner, items.length, totalHeight, containerHeight, triggerLoadMore]);\n\n useLayoutEffect(() => {\n const el = rootRef.current;\n const prevOffsets = prevOffsetsRef.current;\n prevOffsetsRef.current = offsets;\n\n // Nothing to anchor against on the first pass or when pinned at the top.\n if (!el || prevOffsets.length === 0) return;\n // A jump in flight is aiming at a row; anchoring would hold the row it\n // happens to be passing instead, and the two would fight to a standstill.\n if (pendingJumpRef.current) return;\n const curScrollTop = el.scrollTop;\n if (curScrollTop <= 0) return;\n\n // Scroll anchoring: pin the row at the top of the viewport. Find it under\n // the *previous* offsets, then re-derive scrollTop from its *new* offset so\n // it stays visually fixed when rows above it are measured or resized. This\n // is more robust than summing per-row height deltas — it can't drift, and\n // one correction covers any number of simultaneous changes above the fold.\n const prevCount = prevOffsets.length - 1;\n const anchor = findStartIndex(prevOffsets, curScrollTop, prevCount);\n if (anchor >= items.length) return;\n const within = curScrollTop - prevOffsets[anchor];\n const target = offsets[anchor] + within;\n if (Math.abs(target - curScrollTop) > 0.5) {\n el.scrollTop = target;\n pendingScrollTopRef.current = target;\n setScrollTop(target);\n }\n }, [offsets, items.length]);\n\n const scrollToOffset = useCallback((top: number, behavior?: ScrollBehavior) => {\n const el = rootRef.current;\n if (!el) return;\n const clamped = Math.max(0, top);\n if (typeof el.scrollTo === 'function') el.scrollTo({ top: clamped, behavior: behavior ?? 'auto' });\n else el.scrollTop = clamped;\n }, []);\n\n /** Scroll position that puts row `index` where `align` asks for, or null if there is none. */\n const computeScrollTop = useCallback(\n (index: number, options?: VirtualListScrollOptions): number | null => {\n const el = rootRef.current;\n if (!el || items.length === 0) return null;\n const i = Math.max(0, Math.min(index, items.length - 1));\n const rowTop = offsets[i] ?? 0;\n const rowHeight = (offsets[i + 1] ?? rowTop) - rowTop;\n // Row offsets are measured from the top of the body, which itself starts\n // below the sticky header: the header is in flow, so scrolling by exactly\n // `rowTop` already puts the row flush under it. Subtracting the header\n // height on top of that, as this once did, left the row one header lower,\n // which in a table whose rows are about as tall as its header reads as\n // landing a row short.\n const headerHeight = headerRef.current?.offsetHeight ?? 0;\n // What is left of the viewport once the header has taken its share.\n const usable = Math.max(0, el.clientHeight - headerHeight);\n const align = options?.align ?? 'start';\n let top = rowTop;\n if (align === 'center') top -= (usable - rowHeight) / 2;\n else if (align === 'end') top -= usable - rowHeight;\n return top;\n },\n [items.length, offsets],\n );\n\n // A jump lands on the wrong row while the rows between here and there have\n // never been rendered: their offsets are `estimatedRowHeight` guesses, and the\n // error compounds over the distance (40px guessed against 35px real puts row\n // 75 at row 86). Scrolling there renders those rows, measuring corrects the\n // offsets, and the effect below re-aims at the target until it stops moving.\n // This is why the same jump is accurate once the list has been scrolled\n // through: by then every row in between carries a measured height.\n const pendingJumpRef = useRef<{\n index: number;\n options?: VirtualListScrollOptions;\n lastTarget: number;\n attempts: number;\n items: T[];\n } | null>(null);\n\n // Deliberately without a dependency list: every commit is a chance that new\n // measurements have moved the target, including the ones that come from the\n // scroll position itself changing mid-animation.\n useLayoutEffect(() => {\n const pending = pendingJumpRef.current;\n const el = rootRef.current;\n if (!pending) return;\n const target = pending.items === items && el ? computeScrollTop(pending.index, pending.options) : null;\n if (target == null) {\n pendingJumpRef.current = null; // new data supersedes an in-flight jump\n return;\n }\n const isStable = Math.abs(target - pending.lastTarget) <= 1;\n // Only once it has both stopped moving and been reached: with a smooth\n // behaviour the target can sit still for several frames while the animation\n // is still on its way there, and giving up then would leave it short.\n if ((isStable && Math.abs(el!.scrollTop - target) <= 1) || pending.attempts >= MAX_JUMP_CORRECTIONS) {\n pendingJumpRef.current = null;\n return;\n }\n if (isStable) return;\n pending.lastTarget = target;\n pending.attempts += 1;\n scrollToOffset(target, pending.options?.behavior);\n });\n\n // Any input of the user's own outranks a jump still in flight: being pulled\n // back to a row you just scrolled away from is worse than not arriving.\n useEffect(() => {\n const el = rootRef.current;\n if (!el) return;\n const cancel = () => {\n pendingJumpRef.current = null;\n };\n el.addEventListener('wheel', cancel, { passive: true });\n el.addEventListener('touchstart', cancel, { passive: true });\n el.addEventListener('keydown', cancel);\n return () => {\n el.removeEventListener('wheel', cancel);\n el.removeEventListener('touchstart', cancel);\n el.removeEventListener('keydown', cancel);\n };\n }, []);\n\n const scrollApi = useMemo<Omit<VirtualListHandle, 'recalculateColumns' | 'resetColumnWidths'>>(() => {\n function scrollToIndex(index: number, options?: VirtualListScrollOptions) {\n const target = computeScrollTop(index, options);\n if (target == null) return;\n pendingJumpRef.current = { index, options, lastTarget: target, attempts: 0, items };\n scrollToOffset(target, options?.behavior);\n }\n return {\n scrollToIndex,\n scrollToKey(key, options) {\n const i = items.findIndex((item, idx) => (getItemKey ? getItemKey(item, idx) : idx) === key);\n if (i >= 0) scrollToIndex(i, options);\n },\n scrollToTop(options) {\n pendingJumpRef.current = null;\n scrollToOffset(0, options?.behavior);\n },\n getScrollElement: () => rootRef.current,\n };\n }, [items, getItemKey, computeScrollTop, scrollToOffset]);\n\n const { startIndex, endIndex } = useMemo(\n () => getVisibleRange(offsets, scrollTop, containerHeight, overscan, items.length),\n [offsets, scrollTop, containerHeight, overscan, items.length],\n );\n\n return {\n rootRef,\n headerRef,\n rowObserver,\n keysRef,\n offsets,\n totalHeight,\n containerHeight,\n containerWidth,\n startIndex,\n endIndex,\n handleScroll,\n showLoadMoreSpinner,\n scrollApi,\n };\n}\n"],"mappings":"+MAWA,SAAS,EAAiB,EAAwB,EAAuC,CACvF,GAAI,OAAO,GAAU,SAAU,OAAO,EACtC,IAAM,EAAU,EAAM,KAAK,EAC3B,GAAI,IAAY,GAAI,MAAO,GAC3B,IAAM,EAAW,OAAO,CAAO,EAC/B,GAAI,CAAC,OAAO,MAAM,CAAQ,EAAG,OAAO,EACpC,IAAM,EAAU,oBAAoB,KAAK,CAAO,EAChD,GAAI,EAAS,OAAO,WAAW,EAAQ,EAAE,EACzC,GAAI,OAAO,SAAa,KAAe,CAAC,EAAW,MAAO,GAC1D,IAAM,EAAQ,SAAS,cAAc,KAAK,EAC1C,EAAM,MAAM,QAAU,8CAA8C,EAAQ,GAC5E,EAAU,YAAY,CAAK,EAC3B,IAAM,EAAK,EAAM,sBAAsB,CAAC,CAAC,OAEzC,OADA,EAAU,YAAY,CAAK,EACpB,OAAO,SAAS,CAAE,EAAI,EAAK,CACpC,CAiDA,IAAM,EAAuB,GAE7B,SAAgB,EAAoB,CAClC,QACA,OACA,aACA,qBACA,SACA,WACA,aACA,oBACA,aACkD,CAClD,GAAM,CAAC,EAAW,GAAgB,EAAS,CAA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,EAAiB,EAAO,CAAO,EAC1C,GAAU,OACd,EAAe,QAAU,CAAE,QAAO,UAAS,WAAY,EAAQ,SAAU,EAAG,OAAM,EAClF,EAAe,EAAQ,GAAS,QAAQ,EAC1C,CACA,MAAO,CACL,gBACA,YAAY,EAAK,EAAS,CACxB,IAAM,EAAI,EAAM,WAAW,EAAM,KAAS,EAAa,EAAW,EAAM,CAAG,EAAI,KAAS,CAAG,EACvF,GAAK,GAAG,EAAc,EAAG,CAAO,CACtC,EACA,YAAY,EAAS,CACnB,EAAe,QAAU,KACzB,EAAe,EAAG,GAAS,QAAQ,CACrC,EACA,qBAAwB,EAAQ,OAClC,CACF,EAAG,CAAC,EAAO,EAAY,EAAkB,CAAc,CAAC,EAElD,CAAE,aAAY,YAAa,MACzB,EAAgB,EAAS,EAAW,EAAiB,EAAU,EAAM,MAAM,EACjF,CAAC,EAAS,EAAW,EAAiB,EAAU,EAAM,MAAM,CAC9D,EAEA,MAAO,CACL,UACA,YACA,cACA,UACA,UACA,cACA,kBACA,iBACA,aACA,WACA,eACA,sBACA,WACF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"../loading/spinnerLoading/index.mjs";import
|
|
1
|
+
import e from"../loading/spinnerLoading/index.mjs";import t from"../checkbox/checkbox.mjs";import n from"./virtualList.module.mjs";import"./virtualList.utils.mjs";import ee from"./virtualRow.mjs";import r from"./virtualListHeader.mjs";import{useVirtualWindow as i}from"./useVirtualWindow.mjs";import{useSelection as a}from"./useSelection.mjs";import{useColumns as o}from"./useColumns.mjs";import{useRowDrag as te}from"./useRowDrag.mjs";import{useSorting as ne}from"./useSorting.mjs";import{useColumnResize as re}from"./useColumnResize.mjs";import{useRowNavigation as ie}from"./useRowNavigation.mjs";import s,{useCallback as c,useEffect as ae,useId as oe,useImperativeHandle as se,useMemo as l,useRef as ce}from"react";import u from"classnames";import{Fragment as le,jsx as d,jsxs as f}from"react/jsx-runtime";function p({items:s,renderRow:p,ariaRoles:m,columns:h,height:ue=`100%`,estimatedRowHeight:de=40,overscan:fe=3,rowGap:pe=0,rowPadding:g,selectedKey:_,getItemKey:v,onRowClick:y,keyboardNavigation:b=!0,visibleColumnKeys:me,onVisibleColumnsChange:he,persistColumnsKey:ge,resizableColumns:_e=!1,columnWidths:ve,onColumnWidthsChange:ye,resetColumnWidthsLabel:be=`Reset column widths`,sort:xe,defaultSort:Se,onSortChange:Ce,showColumnToggle:we,onLoadMore:Te,loadMoreThreshold:Ee=100,isLoading:x=!1,multiSelect:S=!1,selectedKeys:De,onSelectionChange:Oe,reorderable:C=!1,onReorder:ke,longPressDelay:Ae=400,treeReorder:w=!1,getItemDepth:T,isGroup:E,onTreeDrop:je,treeIndentPx:Me=24,dragHandle:Ne=!1,showDivider:Pe=!0,rowHover:Fe=!0,className:Ie,style:Le,classNames:D,styles:O,...Re},ze){let{rows:k,effectiveSort:Be,isSorted:A,handleHeaderSort:Ve}=ne({items:s,columns:h,sort:xe,defaultSort:Se,onSortChange:Ce}),j=c((e,t)=>v?v(e,t):t,[v]),M=l(()=>k.map((e,t)=>j(e,t)),[k,j]),He=l(()=>T?k.map((e,t)=>T(e,t)):[],[k,T]),Ue=c(e=>E?E(k[e],e):!1,[E,k]),N=i({items:k,keys:M,getItemKey:v,estimatedRowHeight:de,rowGap:pe,overscan:fe,onLoadMore:Te,loadMoreThreshold:Ee,isLoading:x}),{rootRef:P,headerRef:F,rowObserver:We,keysRef:Ge,offsets:I,totalHeight:Ke,startIndex:L,endIndex:R}=N,z=ce([]),B=re({columns:h,visibleColumnsRef:z,resizableColumns:_e,columnWidths:ve,onColumnWidthsChange:ye,persistColumnsKey:ge,rootRef:P}),V=a({items:k,getKey:j,multiSelect:S,selectedKeys:De,onSelectionChange:Oe}),{effectiveSelectedKeys:H}=V,U=o({columns:h,items:k,multiSelect:S,visibleColumnKeys:me,onVisibleColumnsChange:he,persistColumnsKey:ge,showColumnToggle:we,userWidths:B.widths,isFrozen:B.isFrozen,rootRef:P,startIndex:L,endIndex:R,containerHeight:N.containerHeight,containerWidth:N.containerWidth}),{hasColumns:W,visibleColumns:G,columnTemplate:qe,widthVars:Je,shouldShowToggle:Ye,recalculateColumns:K}=U;z.current=G,se(ze,()=>({...N.scrollApi,recalculateColumns:K,resetColumnWidths:B.reset}),[N.scrollApi,K,B.reset]);let q=A&&(C||w);ae(()=>{q&&console.warn(`VirtualList: row reordering is disabled while the list is sorted. Clear the sort to drag rows.`)},[q]);let J=te({reorderable:C&&!A,treeReorder:w&&!A,onReorder:ke,onTreeDrop:je,longPressDelay:Ae,dragHandle:Ne,treeIndentPx:Me,keys:M,depths:He,isGroupAt:Ue,rootRef:P,keysRef:Ge}),Xe=oe(),Y=e=>`${Xe}-row-${e}`,X=ie({enabled:b,rowCount:k.length,offsets:I,rootRef:P,headerRef:F,scrollToIndex:N.scrollApi.scrollToIndex,initialIndex:_==null?0:Math.max(0,M.indexOf(_)),multiSelect:S,onActivate:y&&(e=>y(k[e],e)),onToggleSelect:e=>V.handleRowSelect(M[e])}),Ze=typeof g==`number`?`${g}px`:g,Z=e=>{let r=k[e],i=j(r,e),a=_!=null&&i===_||H.has(i),o=J.getRowDragProps(e,i);return d(ee,{id:Y(e),index:e,top:I[e],padding:Ze,columnTemplate:qe,isSelected:a,isActive:e===X.activeIndex,manageTabStops:b,isEntered:e===X.enteredIndex,activeClassName:D?.activeRow,activeStyle:O?.activeRow,showDivider:Pe,hover:Fe,onClick:()=>{J.consumeSuppressedClick()||(X.setActiveIndex(e),y?.(r,e))},observer:We,ariaRowIndex:W?e+2:void 0,ariaPosInSet:W?void 0:e+1,ariaSetSize:W?void 0:k.length,rowRole:m?.row??(W?`row`:`listitem`),reserveToggleGutter:Ye,...o,dropIndicatorClassName:D?.dropIndicator,dropIndicatorStyle:O?.dropIndicator,rowClassName:D?.row,rowStyle:O?.row,children:W?f(le,{children:[S&&d(`div`,{className:u(n.virtualListSelectCell,D?.selectCell),style:O?.selectCell,role:`gridcell`,onClick:e=>e.stopPropagation(),children:d(t,{selected:H.has(i),onToggle:()=>V.handleRowSelect(i),"aria-label":`Select row`,tabIndex:-1})}),G.map(t=>d(`div`,{className:u(n.virtualListCell,D?.cell),style:O?.cell,role:`gridcell`,"data-col-key":t.key,"data-fit-key":t.width.type===`fit`?t.key:void 0,children:t.renderCell(r,e)},t.key))]}):p?.(r,e)},i)},Q=[];for(let e=L;e<=R;e++)Q.push(Z(e));let $=J.draggingKey==null?-1:M.indexOf(J.draggingKey);return $>=0&&($<L||$>R)&&Q.push(Z($)),X.enteredIndex>=0&&(X.enteredIndex<L||X.enteredIndex>R)&&Q.push(Z(X.enteredIndex)),f(`div`,{...Re,...X.containerProps,ref:P,className:u(n.virtualList,J.draggingKey!=null&&n.virtualListReordering,B.isResizing&&n.virtualListResizing,Ie,D?.root),style:{height:ue,...Je,...Le,...O?.root},onScroll:N.handleScroll,role:m?.container??(W?`grid`:`list`),"aria-rowcount":W?k.length+1:void 0,"aria-activedescendant":X.activeIndex>=0&&(m?.container??(W?`grid`:`list`))!==`list`?Y(X.activeIndex):void 0,children:[W&&d(r,{headerRef:F,columns:h,cols:U,resize:B,sort:Be,onSort:Ve,multiSelect:S,allSelected:V.allSelected,someSelected:V.someSelected,onSelectAll:V.handleSelectAll,resetColumnWidthsLabel:be,classNames:D,styles:O}),x?d(`div`,{className:n.virtualListLoadingFull,children:d(e,{className:n.virtualListSpinner})}):d(`div`,{className:u(n.virtualListBody,D?.body),style:{height:Ke,...O?.body},children:Q}),N.showLoadMoreSpinner&&d(`div`,{className:u(n.virtualListLoadingIndicator,D?.loadingIndicator),style:O?.loadingIndicator,children:d(e,{className:n.virtualListSpinner})})]})}var m=s.forwardRef(p);export{m as default};
|
|
2
2
|
//# sourceMappingURL=virtualList.mjs.map
|