@ahrowe/ui 0.36.0 → 0.38.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.
Files changed (176) hide show
  1. package/README.md +6 -2
  2. package/dist/cjs-types/common/commandPalette/commandPalette.d.ts +4 -0
  3. package/dist/cjs-types/common/commandPalette/commandPalette.types.d.ts +42 -0
  4. package/dist/cjs-types/common/commandPalette/filterCommands.d.ts +15 -0
  5. package/dist/cjs-types/common/commandPalette/index.d.ts +2 -0
  6. package/dist/cjs-types/common/configProvider/configProvider.types.d.ts +6 -0
  7. package/dist/cjs-types/common/copyButton/copyButton.d.ts +4 -0
  8. package/dist/cjs-types/common/copyButton/copyButton.types.d.ts +36 -0
  9. package/dist/cjs-types/common/copyButton/index.d.ts +2 -0
  10. package/dist/cjs-types/common/errorBoundary/errorBoundary.d.ts +0 -3
  11. package/dist/cjs-types/common/errorBoundary/errorBoundary.types.d.ts +2 -3
  12. package/dist/cjs-types/common/hooks/index.d.ts +15 -0
  13. package/dist/cjs-types/common/hooks/useClipboard.d.ts +16 -0
  14. package/dist/cjs-types/common/hooks/useHotkeys.d.ts +45 -0
  15. package/dist/cjs-types/common/hooks/useSwipeDismiss.d.ts +6 -2
  16. package/dist/cjs-types/common/inputDropdown/inputDropdown.types.d.ts +7 -1
  17. package/dist/cjs-types/common/loading/index.d.ts +0 -1
  18. package/dist/cjs-types/common/menu/index.d.ts +1 -0
  19. package/dist/cjs-types/common/menu/menu.types.d.ts +11 -3
  20. package/dist/cjs-types/common/menu/menuHotkeys.d.ts +20 -0
  21. package/dist/cjs-types/common/popover/usePopoverPosition.d.ts +1 -0
  22. package/dist/cjs-types/common/sticky/sticky.d.ts +1 -1
  23. package/dist/cjs-types/common/sticky/sticky.types.d.ts +15 -0
  24. package/dist/cjs-types/common/sticky/stickyStack.d.ts +5 -0
  25. package/dist/cjs-types/common/themeProvider/themeProvider.d.ts +8 -7
  26. package/dist/cjs-types/common/utils/scrollAncestors.d.ts +10 -0
  27. package/dist/cjs-types/common/virtualList/scroller.d.ts +33 -0
  28. package/dist/cjs-types/common/virtualList/useRowDrag.d.ts +6 -1
  29. package/dist/cjs-types/common/virtualList/useRowNavigation.d.ts +11 -1
  30. package/dist/cjs-types/common/virtualList/useVirtualWindow.d.ts +22 -3
  31. package/dist/cjs-types/common/virtualList/virtualList.d.ts +1 -1
  32. package/dist/cjs-types/common/virtualList/virtualList.types.d.ts +43 -3
  33. package/dist/cjs-types/common/weatherIcon/index.d.ts +3 -0
  34. package/dist/cjs-types/common/weatherIcon/parts.d.ts +26 -0
  35. package/dist/cjs-types/common/weatherIcon/weatherIcon.d.ts +4 -0
  36. package/dist/cjs-types/common/weatherIcon/weatherIcon.types.d.ts +44 -0
  37. package/dist/cjs-types/index.d.ts +7 -0
  38. package/dist/esm/common/buttonGroup/buttonGroup.module.mjs.map +1 -1
  39. package/dist/esm/common/commandPalette/commandPalette.mjs +2 -0
  40. package/dist/esm/common/commandPalette/commandPalette.mjs.map +1 -0
  41. package/dist/esm/common/commandPalette/commandPalette.module.mjs +2 -0
  42. package/dist/esm/common/commandPalette/commandPalette.module.mjs.map +1 -0
  43. package/dist/esm/common/commandPalette/filterCommands.mjs +2 -0
  44. package/dist/esm/common/commandPalette/filterCommands.mjs.map +1 -0
  45. package/dist/esm/common/copyButton/copyButton.mjs +2 -0
  46. package/dist/esm/common/copyButton/copyButton.mjs.map +1 -0
  47. package/dist/esm/common/copyButton/copyButton.module.mjs +2 -0
  48. package/dist/esm/common/copyButton/copyButton.module.mjs.map +1 -0
  49. package/dist/esm/common/dropdown/dropdown.mjs +1 -1
  50. package/dist/esm/common/dropdown/dropdown.module.mjs.map +1 -1
  51. package/dist/esm/common/errorBoundary/errorBoundary.mjs +2 -2
  52. package/dist/esm/common/errorBoundary/errorBoundary.mjs.map +1 -1
  53. package/dist/esm/common/errorBoundary/errorBoundary.module.mjs +1 -1
  54. package/dist/esm/common/errorBoundary/errorBoundary.module.mjs.map +1 -1
  55. package/dist/esm/common/hooks/useClipboard.mjs +2 -0
  56. package/dist/esm/common/hooks/useClipboard.mjs.map +1 -0
  57. package/dist/esm/common/hooks/useHotkeys.mjs +2 -0
  58. package/dist/esm/common/hooks/useHotkeys.mjs.map +1 -0
  59. package/dist/esm/common/hooks/useSwipeDismiss.mjs +1 -1
  60. package/dist/esm/common/hooks/useSwipeDismiss.mjs.map +1 -1
  61. package/dist/esm/common/input/input.mjs +1 -1
  62. package/dist/esm/common/input/input.mjs.map +1 -1
  63. package/dist/esm/common/input/input.module.mjs +1 -1
  64. package/dist/esm/common/input/input.module.mjs.map +1 -1
  65. package/dist/esm/common/inputDropdown/inputDropdown.mjs +1 -1
  66. package/dist/esm/common/inputDropdown/inputDropdown.mjs.map +1 -1
  67. package/dist/esm/common/inputDropdown/inputDropdown.module.mjs +1 -1
  68. package/dist/esm/common/inputDropdown/inputDropdown.module.mjs.map +1 -1
  69. package/dist/esm/common/menu/menu.mjs +1 -1
  70. package/dist/esm/common/menu/menu.mjs.map +1 -1
  71. package/dist/esm/common/menu/menu.types.mjs.map +1 -1
  72. package/dist/esm/common/menu/menuHotkeys.mjs +2 -0
  73. package/dist/esm/common/menu/menuHotkeys.mjs.map +1 -0
  74. package/dist/esm/common/multiSelect/multiSelect.mjs +1 -1
  75. package/dist/esm/common/multiSelect/multiSelect.mjs.map +1 -1
  76. package/dist/esm/common/multiSelect/multiSelect.module.mjs +1 -1
  77. package/dist/esm/common/multiSelect/multiSelect.module.mjs.map +1 -1
  78. package/dist/esm/common/otpInput/otpInput.module.mjs.map +1 -1
  79. package/dist/esm/common/popover/usePopoverPosition.mjs +1 -1
  80. package/dist/esm/common/popover/usePopoverPosition.mjs.map +1 -1
  81. package/dist/esm/common/sticky/sticky.mjs +1 -1
  82. package/dist/esm/common/sticky/sticky.mjs.map +1 -1
  83. package/dist/esm/common/sticky/stickyStack.mjs +1 -1
  84. package/dist/esm/common/sticky/stickyStack.mjs.map +1 -1
  85. package/dist/esm/common/themeProvider/themeProvider.mjs +1 -1
  86. package/dist/esm/common/themeProvider/themeProvider.mjs.map +1 -1
  87. package/dist/esm/common/timer/timer.mjs +1 -1
  88. package/dist/esm/common/timer/timer.mjs.map +1 -1
  89. package/dist/esm/common/utils/scrollAncestors.mjs +1 -1
  90. package/dist/esm/common/utils/scrollAncestors.mjs.map +1 -1
  91. package/dist/esm/common/virtualList/scroller.mjs +2 -0
  92. package/dist/esm/common/virtualList/scroller.mjs.map +1 -0
  93. package/dist/esm/common/virtualList/useRowDrag.mjs +1 -1
  94. package/dist/esm/common/virtualList/useRowDrag.mjs.map +1 -1
  95. package/dist/esm/common/virtualList/useRowNavigation.mjs +1 -1
  96. package/dist/esm/common/virtualList/useRowNavigation.mjs.map +1 -1
  97. package/dist/esm/common/virtualList/useVirtualWindow.mjs +1 -1
  98. package/dist/esm/common/virtualList/useVirtualWindow.mjs.map +1 -1
  99. package/dist/esm/common/virtualList/virtualList.mjs +1 -1
  100. package/dist/esm/common/virtualList/virtualList.mjs.map +1 -1
  101. package/dist/esm/common/virtualList/virtualList.module.mjs +1 -1
  102. package/dist/esm/common/virtualList/virtualList.module.mjs.map +1 -1
  103. package/dist/esm/common/weatherIcon/parts.mjs +2 -0
  104. package/dist/esm/common/weatherIcon/parts.mjs.map +1 -0
  105. package/dist/esm/common/weatherIcon/weatherIcon.mjs +2 -0
  106. package/dist/esm/common/weatherIcon/weatherIcon.mjs.map +1 -0
  107. package/dist/esm/common/weatherIcon/weatherIcon.module.mjs +2 -0
  108. package/dist/esm/common/weatherIcon/weatherIcon.module.mjs.map +1 -0
  109. package/dist/esm/common/weatherIcon/weatherIcon.types.mjs +2 -0
  110. package/dist/esm/common/weatherIcon/weatherIcon.types.mjs.map +1 -0
  111. package/dist/esm/index.mjs +1 -1
  112. package/dist/index.cjs +3 -3
  113. package/dist/index.cjs.map +1 -1
  114. package/dist/style.css +1 -1
  115. package/dist/types/common/commandPalette/commandPalette.d.ts +4 -0
  116. package/dist/types/common/commandPalette/commandPalette.types.d.ts +42 -0
  117. package/dist/types/common/commandPalette/filterCommands.d.ts +15 -0
  118. package/dist/types/common/commandPalette/index.d.ts +2 -0
  119. package/dist/types/common/configProvider/configProvider.types.d.ts +6 -0
  120. package/dist/types/common/copyButton/copyButton.d.ts +4 -0
  121. package/dist/types/common/copyButton/copyButton.types.d.ts +36 -0
  122. package/dist/types/common/copyButton/index.d.ts +2 -0
  123. package/dist/types/common/errorBoundary/errorBoundary.d.ts +0 -3
  124. package/dist/types/common/errorBoundary/errorBoundary.types.d.ts +2 -3
  125. package/dist/types/common/hooks/index.d.ts +15 -0
  126. package/dist/types/common/hooks/useClipboard.d.ts +16 -0
  127. package/dist/types/common/hooks/useHotkeys.d.ts +45 -0
  128. package/dist/types/common/hooks/useSwipeDismiss.d.ts +6 -2
  129. package/dist/types/common/inputDropdown/inputDropdown.types.d.ts +7 -1
  130. package/dist/types/common/loading/index.d.ts +0 -1
  131. package/dist/types/common/menu/index.d.ts +1 -0
  132. package/dist/types/common/menu/menu.types.d.ts +11 -3
  133. package/dist/types/common/menu/menuHotkeys.d.ts +20 -0
  134. package/dist/types/common/popover/usePopoverPosition.d.ts +1 -0
  135. package/dist/types/common/sticky/sticky.d.ts +1 -1
  136. package/dist/types/common/sticky/sticky.types.d.ts +15 -0
  137. package/dist/types/common/sticky/stickyStack.d.ts +5 -0
  138. package/dist/types/common/themeProvider/themeProvider.d.ts +8 -7
  139. package/dist/types/common/utils/scrollAncestors.d.ts +10 -0
  140. package/dist/types/common/virtualList/scroller.d.ts +33 -0
  141. package/dist/types/common/virtualList/useRowDrag.d.ts +6 -1
  142. package/dist/types/common/virtualList/useRowNavigation.d.ts +11 -1
  143. package/dist/types/common/virtualList/useVirtualWindow.d.ts +22 -3
  144. package/dist/types/common/virtualList/virtualList.d.ts +1 -1
  145. package/dist/types/common/virtualList/virtualList.types.d.ts +43 -3
  146. package/dist/types/common/weatherIcon/index.d.ts +3 -0
  147. package/dist/types/common/weatherIcon/parts.d.ts +26 -0
  148. package/dist/types/common/weatherIcon/weatherIcon.d.ts +4 -0
  149. package/dist/types/common/weatherIcon/weatherIcon.types.d.ts +44 -0
  150. package/dist/types/index.d.ts +7 -0
  151. package/docs/ButtonGroup.md +2 -0
  152. package/docs/CLAUDE.md +6 -2
  153. package/docs/CommandPalette.md +84 -0
  154. package/docs/ConfigProvider.md +2 -2
  155. package/docs/CopyButton.md +45 -0
  156. package/docs/ErrorBoundary.md +4 -4
  157. package/docs/Fab.md +1 -2
  158. package/docs/Hooks.md +268 -0
  159. package/docs/InputDropdown.md +9 -4
  160. package/docs/Loading.md +56 -15
  161. package/docs/Menu.md +30 -6
  162. package/docs/Popover.md +2 -0
  163. package/docs/Sticky.md +22 -1
  164. package/docs/VirtualList.md +44 -4
  165. package/docs/WeatherIcon.md +49 -0
  166. package/package.json +1 -2
  167. package/dist/cjs-types/common/loading/iconLoading/iconLoading.d.ts +0 -5
  168. package/dist/cjs-types/common/loading/iconLoading/index.d.ts +0 -2
  169. package/dist/esm/common/loading/iconLoading/iconLoading.mjs +0 -2
  170. package/dist/esm/common/loading/iconLoading/iconLoading.mjs.map +0 -1
  171. package/dist/esm/common/loading/iconLoading/iconLoading.module.mjs +0 -2
  172. package/dist/esm/common/loading/iconLoading/iconLoading.module.mjs.map +0 -1
  173. package/dist/esm/common/loading/iconLoading/index.mjs +0 -2
  174. package/dist/esm/common/loading/iconLoading/index.mjs.map +0 -1
  175. package/dist/types/common/loading/iconLoading/iconLoading.d.ts +0 -5
  176. package/dist/types/common/loading/iconLoading/index.d.ts +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"themeProvider.mjs","names":[],"sources":["../../../../package/common/themeProvider/themeProvider.tsx"],"sourcesContent":["import React, { Component } from 'react';\nimport cx from 'classnames';\n\nimport type { Theme } from './theme.types';\nimport { defaultTheme } from './defaultTheme';\nimport { ThemeVariablesContext } from './themeVariablesContext';\nimport styles from './theme.module.pcss';\n\ninterface Props {\n children: React.ReactNode;\n themes?: Theme[];\n currentThemeId?: string;\n}\n\ninterface State {\n resolvedVariables: Record<string, string>;\n colorFadeActive: boolean;\n currentThemeColor: string | null;\n}\n\nclass ThemeProvider extends Component<Props, State> {\n state: State = {\n resolvedVariables: {},\n colorFadeActive: false,\n currentThemeColor: null,\n };\n\n private colorFadeTimeout: ReturnType<typeof setTimeout> | null = null;\n private wrapperRef = React.createRef<HTMLDivElement>();\n private themeColorMeta: HTMLMetaElement | null = null;\n private createdThemeColorMeta = false;\n\n componentDidMount() {\n this.applyTheme(this.props.currentThemeId);\n this.syncThemeColorMeta(this.state.currentThemeColor ?? '');\n }\n\n componentDidUpdate(prevProps: Props, prevState: State) {\n if (prevState.currentThemeColor !== this.state.currentThemeColor) {\n this.syncThemeColorMeta(this.state.currentThemeColor ?? '');\n }\n if (prevProps.currentThemeId !== this.props.currentThemeId || prevProps.themes !== this.props.themes) {\n this.applyTheme(this.props.currentThemeId);\n }\n }\n\n componentWillUnmount() {\n if (this.colorFadeTimeout) clearTimeout(this.colorFadeTimeout);\n // Only remove the meta tag if we created it; leave a host-app tag intact.\n // Also clear the cached refs — StrictMode's dev-only mount/unmount/remount\n // cycle reuses this instance, and a stale ref would otherwise point at a\n // detached element on remount instead of re-inserting into <head>.\n if (this.createdThemeColorMeta) {\n this.themeColorMeta?.remove();\n this.themeColorMeta = null;\n this.createdThemeColorMeta = false;\n }\n }\n\n /**\n * Replaces the former react-helmet usage: keep a single\n * <meta name=\"theme-color\"> in sync with the active theme's primary colour.\n * Reuses a tag the host app already declares; otherwise creates its own\n * (and removes it again on unmount).\n */\n private syncThemeColorMeta(color: string) {\n if (typeof document === 'undefined') return;\n\n if (!this.themeColorMeta) {\n const existing = document.head.querySelector<HTMLMetaElement>('meta[name=\"theme-color\"]');\n if (existing) {\n this.themeColorMeta = existing;\n } else {\n const meta = document.createElement('meta');\n meta.setAttribute('name', 'theme-color');\n document.head.appendChild(meta);\n this.themeColorMeta = meta;\n this.createdThemeColorMeta = true;\n }\n }\n\n this.themeColorMeta.setAttribute('content', color);\n }\n\n /**\n * Resolves the full variable set for a given theme ID by walking up the\n * baseThemeId chain. Returns variables ordered from deepest ancestor to\n * the requested theme so callers can merge in order (later entries win).\n */\n private resolveChain(id: string): Record<string, string>[] {\n const themes = this.props.themes ?? [defaultTheme];\n const theme = themes.find((t) => t.id === id);\n if (!theme) return [];\n\n const parentVars = theme.baseThemeId ? this.resolveChain(theme.baseThemeId) : [];\n\n return [...parentVars, theme.variables as Record<string, string>];\n }\n\n private applyTheme = (currentThemeId: string | undefined) => {\n const themes = this.props.themes ?? [defaultTheme];\n\n // The root theme is the first theme without a baseThemeId.\n // It is always applied as the variable foundation.\n const rootTheme = themes.find((t) => !t.baseThemeId) ?? themes[0];\n const rootVars: Record<string, string> = rootTheme ? (rootTheme.variables as Record<string, string>) : {};\n\n // Resolve the selected theme's full inheritance chain.\n const selectedTheme = themes.find((t) => t.id === currentThemeId);\n const chainVars = selectedTheme ? this.resolveChain(selectedTheme.id) : [];\n\n // Merge: root foundation → ancestor chain → selected theme (each step overrides)\n const resolvedVariables = Object.assign({}, rootVars, ...chainVars);\n\n this.setState({ resolvedVariables, colorFadeActive: true });\n\n if (this.colorFadeTimeout) clearTimeout(this.colorFadeTimeout);\n this.colorFadeTimeout = setTimeout(() => {\n this.setState({ colorFadeActive: false });\n this.colorFadeTimeout = null;\n }, 500);\n\n // Read --primary-color after the new style is painted for the theme-color meta tag.\n setTimeout(() => {\n if (this.wrapperRef.current) {\n this.setState({\n currentThemeColor: getComputedStyle(this.wrapperRef.current).getPropertyValue('--primary-color').trim(),\n });\n }\n }, 1);\n };\n\n render() {\n const { children } = this.props;\n const { resolvedVariables, colorFadeActive } = this.state;\n\n return (\n <div\n ref={this.wrapperRef}\n id='themeProvider'\n className={cx(styles.themeRoot, colorFadeActive && styles.colorFade)}\n style={resolvedVariables as React.CSSProperties}\n >\n <ThemeVariablesContext.Provider value={resolvedVariables}>{children}</ThemeVariablesContext.Provider>\n </div>\n );\n }\n}\n\n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AAK,WAAW,KAAK,MAAM,cAAc,CAE7C,CAEA,sBAAuB,CACjB,KAAK,kBAAkB,aAAa,KAAK,gBAAgB,EAK7D,AAGE,KAAK,yBAFL,KAAK,gBAAgB,OAAO,EAC5B,KAAK,eAAiB,KACO,GAEjC,CAQA,mBAA2B,EAAe,CACpC,UAAO,SAAa,IAExB,IAAI,CAAC,KAAK,eAAgB,CACxB,IAAM,EAAW,SAAS,KAAK,cAA+B,0BAA0B,EACxF,GAAI,EACF,KAAK,eAAiB,MACjB,CACL,IAAM,EAAO,SAAS,cAAc,MAAM,EAC1C,EAAK,aAAa,OAAQ,aAAa,EACvC,SAAS,KAAK,YAAY,CAAI,EAC9B,KAAK,eAAiB,EACtB,KAAK,sBAAwB,EAC/B,CACF,CAEA,KAAK,eAAe,aAAa,UAAW,CAAK,CAFjD,CAGF,CAOA,aAAqB,EAAsC,CAEzD,IAAM,GADS,KAAK,MAAM,QAAU,CAAC,CAAY,EAAA,CAC5B,KAAM,GAAM,EAAE,KAAO,CAAE,EAK5C,OAJK,EAIE,CAAC,GAFW,EAAM,YAAc,KAAK,aAAa,EAAM,WAAW,EAAI,CAAC,EAExD,EAAM,SAAmC,EAJ7C,CAAC,CAKtB,CAmCA,QAAS,CACP,GAAM,CAAE,YAAa,KAAK,MACpB,CAAE,oBAAmB,mBAAoB,KAAK,MAEpD,OACE,EAAC,MAAD,CACE,IAAK,KAAK,WACV,GAAG,gBACH,UAAW,EAAG,EAAO,UAAW,GAAmB,EAAO,SAAS,EACnE,MAAO,EAEP,SAAA,EAAC,EAAsB,SAAvB,CAAgC,MAAO,EAAoB,UAAyC,CAAA,CACjG,CAAA,CAET,CACF"}
1
+ {"version":3,"file":"themeProvider.mjs","names":[],"sources":["../../../../package/common/themeProvider/themeProvider.tsx"],"sourcesContent":["import React, { Component } from 'react';\nimport cx from 'classnames';\n\nimport type { Theme } from './theme.types';\nimport { defaultTheme } from './defaultTheme';\nimport { ThemeVariablesContext } from './themeVariablesContext';\nimport styles from './theme.module.pcss';\n\ninterface Props {\n children: React.ReactNode;\n themes?: Theme[];\n currentThemeId?: string;\n}\n\ninterface State {\n resolvedVariables: Record<string, string>;\n colorFadeActive: boolean;\n currentThemeColor: string | null;\n /** What `resolvedVariables` was resolved from, to tell a theme change from any other render. */\n resolvedFrom: { themes: Theme[] | undefined; currentThemeId: string | undefined };\n}\n\n/**\n * Resolves a theme ID's variables by walking up its baseThemeId chain, ordered from deepest\n * ancestor to the requested theme so they merge in order (later entries win).\n */\nfunction resolveChain(themes: Theme[], id: string): Record<string, string>[] {\n const theme = themes.find((t) => t.id === id);\n if (!theme) return [];\n const parentVars = theme.baseThemeId ? resolveChain(themes, theme.baseThemeId) : [];\n return [...parentVars, theme.variables as Record<string, string>];\n}\n\nfunction resolveVariables({ themes = [defaultTheme], currentThemeId }: Props): Record<string, string> {\n // The root theme, the first without a baseThemeId, is always the foundation.\n const rootTheme = themes.find((t) => !t.baseThemeId) ?? themes[0];\n const rootVars = rootTheme ? (rootTheme.variables as Record<string, string>) : {};\n const chainVars = currentThemeId ? resolveChain(themes, currentThemeId) : [];\n return Object.assign({}, rootVars, ...chainVars);\n}\n\nclass ThemeProvider extends Component<Props, State> {\n // Resolved before the first render rather than after mount: resolved in componentDidMount, every\n // component rendered and measured itself unthemed first, and on each page load some 50\n // backgrounds then faded in from nothing.\n state: State = {\n resolvedVariables: resolveVariables(this.props),\n colorFadeActive: false,\n currentThemeColor: null,\n resolvedFrom: { themes: this.props.themes, currentThemeId: this.props.currentThemeId },\n };\n\n private colorFadeTimeout: ReturnType<typeof setTimeout> | null = null;\n private wrapperRef = React.createRef<HTMLDivElement>();\n private themeColorMeta: HTMLMetaElement | null = null;\n private createdThemeColorMeta = false;\n\n // The fade and the new variables have to land in the same render: added a render later, the\n // browser may already have painted the new colours without it.\n static getDerivedStateFromProps(props: Props, state: State): Partial<State> | null {\n const { themes, currentThemeId } = state.resolvedFrom;\n if (props.themes === themes && props.currentThemeId === currentThemeId) return null;\n return {\n resolvedVariables: resolveVariables(props),\n colorFadeActive: true,\n resolvedFrom: { themes: props.themes, currentThemeId: props.currentThemeId },\n };\n }\n\n componentDidMount() {\n this.readThemeColor();\n }\n\n componentDidUpdate(prevProps: Props, prevState: State) {\n if (prevState.resolvedVariables !== this.state.resolvedVariables) {\n this.readThemeColor();\n if (this.colorFadeTimeout) clearTimeout(this.colorFadeTimeout);\n this.colorFadeTimeout = setTimeout(() => {\n this.setState({ colorFadeActive: false });\n this.colorFadeTimeout = null;\n }, 500);\n }\n if (prevState.currentThemeColor !== this.state.currentThemeColor) {\n this.syncThemeColorMeta(this.state.currentThemeColor ?? '');\n }\n }\n\n componentWillUnmount() {\n if (this.colorFadeTimeout) clearTimeout(this.colorFadeTimeout);\n // Only remove the meta tag if we created it; leave a host-app tag intact.\n // Also clear the cached refs — StrictMode's dev-only mount/unmount/remount\n // cycle reuses this instance, and a stale ref would otherwise point at a\n // detached element on remount instead of re-inserting into <head>.\n if (this.createdThemeColorMeta) {\n this.themeColorMeta?.remove();\n this.themeColorMeta = null;\n this.createdThemeColorMeta = false;\n }\n }\n\n /**\n * Replaces the former react-helmet usage: keep a single\n * <meta name=\"theme-color\"> in sync with the active theme's primary colour.\n * Reuses a tag the host app already declares; otherwise creates its own\n * (and removes it again on unmount).\n */\n private syncThemeColorMeta(color: string) {\n if (typeof document === 'undefined') return;\n\n if (!this.themeColorMeta) {\n const existing = document.head.querySelector<HTMLMetaElement>('meta[name=\"theme-color\"]');\n if (existing) {\n this.themeColorMeta = existing;\n } else {\n const meta = document.createElement('meta');\n meta.setAttribute('name', 'theme-color');\n document.head.appendChild(meta);\n this.themeColorMeta = meta;\n this.createdThemeColorMeta = true;\n }\n }\n\n this.themeColorMeta.setAttribute('content', color);\n }\n\n /** `--primary-color` as the browser resolved it, which may be a `var()` of another variable. */\n private readThemeColor() {\n if (!this.wrapperRef.current) return;\n const color = getComputedStyle(this.wrapperRef.current).getPropertyValue('--primary-color').trim();\n if (color !== this.state.currentThemeColor) this.setState({ currentThemeColor: color });\n }\n\n render() {\n const { children } = this.props;\n const { resolvedVariables, colorFadeActive } = this.state;\n\n return (\n <div\n ref={this.wrapperRef}\n id='themeProvider'\n className={cx(styles.themeRoot, colorFadeActive && styles.colorFade)}\n style={resolvedVariables as React.CSSProperties}\n >\n <ThemeVariablesContext.Provider value={resolvedVariables}>{children}</ThemeVariablesContext.Provider>\n </div>\n );\n }\n}\n\nexport default ThemeProvider;\n"],"mappings":"4QA0BA,SAAS,EAAa,EAAiB,EAAsC,CAC3E,IAAM,EAAQ,EAAO,KAAM,GAAM,EAAE,KAAO,CAAE,EAG5C,OAFK,EAEE,CAAC,GADW,EAAM,YAAc,EAAa,EAAQ,EAAM,WAAW,EAAI,CAAC,EAC3D,EAAM,SAAmC,EAF7C,CAAC,CAGtB,CAEA,SAAS,EAAiB,CAAE,SAAS,CAAC,CAAY,EAAG,kBAAiD,CAEpG,IAAM,EAAY,EAAO,KAAM,GAAM,CAAC,EAAE,WAAW,GAAK,EAAO,GACzD,EAAW,EAAa,EAAU,UAAuC,CAAC,EAC1E,EAAY,EAAiB,EAAa,EAAQ,CAAc,EAAI,CAAC,EAC3E,OAAO,OAAO,OAAO,CAAC,EAAG,EAAU,GAAG,CAAS,CACjD,CAEA,IAAM,EAAN,cAA4B,CAAwB,+BAInC,KAAA,MAAA,CACb,kBAAmB,EAAiB,KAAK,KAAK,EAC9C,gBAAiB,GACjB,kBAAmB,KACnB,aAAc,CAAE,OAAQ,KAAK,MAAM,OAAQ,eAAgB,KAAK,MAAM,cAAe,CACvF,EAEiE,KAAA,iBAAA,KAC5C,KAAA,WAAA,EAAM,UAA0B,EACJ,KAAA,eAAA,KACjB,KAAA,sBAAA,GAIhC,OAAO,yBAAyB,EAAc,EAAqC,CACjF,GAAM,CAAE,SAAQ,kBAAmB,EAAM,aAEzC,OADI,EAAM,SAAW,GAAU,EAAM,iBAAmB,EAAuB,KACxE,CACL,kBAAmB,EAAiB,CAAK,EACzC,gBAAiB,G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AC,MAAD,CACE,IAAK,KAAK,WACV,GAAG,gBACH,UAAW,EAAG,EAAO,UAAW,GAAmB,EAAO,SAAS,EACnE,MAAO,EAEP,SAAA,EAAC,EAAsB,SAAvB,CAAgC,MAAO,EAAoB,UAAyC,CAAA,CACjG,CAAA,CAET,CACF"}
@@ -1,2 +1,2 @@
1
- "use client";import{useComponentDefaults as e}from"../configProvider/useComponentDefaults.mjs";import{useLabels as t}from"../configProvider/useLabels.mjs";import{ButtonSize as n}from"../button/button.types.mjs";import r from"../button/button.mjs";import i from"../actionIcon/actionIcon.mjs";import"./timer.chime.mjs";import a from"./timer.module.mjs";import{useEffect as o,useImperativeHandle as ee,useMemo as te,useRef as s,useState as c}from"react";import l from"classnames";import{faMinus as ne,faPause as re,faPlay as ie,faPlus as ae,faXmark as oe}from"@fortawesome/free-solid-svg-icons";import{jsx as u,jsxs as d}from"react/jsx-runtime";var se=200,ce=1e3,le={cancel:`Cancel timer`};function ue(){return typeof window<`u`&&window.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches===!0}function de(e){let t=Math.ceil(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60,a=String(r).padStart(2,`0`),o=String(i).padStart(2,`0`);return n>0?`${n}:${a}:${o}`:`${a}:${o}`}function f(f){let{ref:fe,durationSeconds:p,autoStart:m=!0,resetOnDurationChange:pe=!0,onTick:h,onComplete:me,onStart:he,onPause:ge,onResume:_e,onCancel:ve,onAddTime:ye,onRemoveTime:be,showControls:g=!0,hideAddButton:xe=!1,hideRemoveButton:Se=!1,hidePauseButton:Ce=!1,hideCancelButton:we=!1,adjustSeconds:_=30,maxSeconds:v,label:y,formatTime:Te=de,size:b,strokeWidth:x=10,counterClockwise:Ee=!1,urgentThreshold:De=.1,urgentMinSeconds:Oe=3,pulseOnUrgent:ke=!0,showRunningRipples:S=!1,playSoundOnComplete:C=!1,soundUrl:w,soundVolume:Ae=.5,notifyOnComplete:T=!1,notificationTitle:je,notificationBody:Me,className:Ne,style:Pe,classNames:E,styles:D,labels:Fe,...Ie}=e(`Timer`,f),Le=t(`Timer`,Fe,le),O=p*1e3,[k,Re]=c(m?`running`:`idle`),[A,ze]=c(O),[Be,Ve]=c(0),[j,M]=c([]),N=s(A),P=s(k),F=s(O),I=s(!1),L=s(!1),R=s(!1),z=s(0);function B(e){N.current=e,ze(e)}function V(e){P.current=e,Re(e)}function H(){Ve(e=>e+1)}o(()=>{if(k!==`running`)return;let e=Date.now(),t=N.current,n=setInterval(()=>{let n=Math.max(0,t-(Date.now()-e));B(n),h?.(n),n<=0&&V(`completed`)},se);return()=>clearInterval(n)},[k,Be]),o(()=>{if(k===`completed`&&!I.current){if(I.current=!0,me?.(),C)try{let e=new Audio(w||`data:audio/wav;base64,UklGRkYeAABXQVZFZm10IBAAAAABAAEAESsAACJWAAACABAAZGF0YSIeAAAAAAkAIAA4AEQANwAPANH/jv9b/07/cf/F/zkAsAAJAScB+QCCANv/K/+h/mX+j/4d//P/3QChAQkC8QFZAV0AOP80/pb9i/0g/jj/kgDaAbsC9gJzAkwBwv82/gz9k/zz/Bz+y/+ZARMD1QOoA44CxQC6/u782PvD+778kv7SAO8CYQTGBPwDLALE/1j9hfvD+kz7Bf2J/zwCcgSbBWUF1QNGAVX+vPsk+vj5TPvU/fYA7QP6BZYGkAUjA+D/k/wP+vj4nPna+y3/xQK+BVkHKActBeABC/6h+nz4LPjN+QD9AAHTBIQHYggvBy4EFgDn+6v4NPfm9576uP4zA/YGDAnsCJUGkgLc/Zz54vZh9kL4FfzvAKAF/AgqCtYITQVmAFX7W/d49Sv2Ufkq/ocDFgizCrIKCQhaA8f9sPhY9Zr0rfYW+8QAUwZiCuoLgwp9BtAA3voh9sjzb/T194T9wAMgCUwMdQyJCTgEzv3d9+Dz2fIR9QT6fwDsBrMLoQ00DL4HUgGC+v30JPKy8o32yPzeAxAK1A01DhILKwXu/ST3evIf8W/z4PghAGsH7wxMD+YNDQnrAUH68fOP8PjwGfX2++ED6ApKD+4Powwx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wIhAlUAdf5+/ef9ZP8cASUC/QHNAEb/O/4w/hf/ZwBlAZUB7wDb//X+sP4f//b/uAAEAcEAJQCO/0r/bv/U/zkAaQBXAB8A7v/f/+7/`);e.volume=Ae,e.play()?.catch(()=>{})}catch{}if(T&&typeof Notification<`u`&&Notification.permission===`granted`)try{new Notification(je??`Timer done`,{body:Me??(typeof y==`string`?y:void 0)})}catch{}}k!==`completed`&&(I.current=!1)},[k]),o(()=>{if(!R.current){R.current=!0;return}let e=p*1e3;F.current=e,B(e),I.current=!1,H(),pe&&V(m?`running`:`idle`)},[p]),o(()=>{if(!S||k!==`running`||ue())return;function e(){z.current+=1,M(e=>[...e,z.current])}e();let t=setInterval(e,ce);return()=>clearInterval(t)},[S,k]);function He(e){M(t=>t.filter(t=>t!==e))}function Ue(){T&&!L.current&&typeof Notification<`u`&&Notification.permission==="default"&&(L.current=!0,Notification.requestPermission().catch(()=>{}))}function U(){Ue(),(P.current===`completed`||P.current===`cancelled`)&&(B(F.current),I.current=!1),H(),V(`running`),he?.()}function W(){P.current===`running`&&(V(`paused`),ge?.())}function G(){P.current===`paused`&&(H(),V(`running`),_e?.())}function K(e){let t=v==null?1/0:v*1e3,n=Math.min(N.current+e*1e3,t);B(n),H(),ye?.(e,Math.round(n/1e3)),P.current===`completed`&&n>0&&(I.current=!1,V(`running`))}function q(e){let t=Math.max(0,N.current-e*1e3);B(t),H(),be?.(e,Math.round(t/1e3)),t<=0&&P.current===`running`&&V(`completed`)}function J(){B(F.current),V(`cancelled`),ve?.()}function We(){B(F.current),I.current=!1,V(`idle`)}ee(fe,()=>({start:U,pause:W,resume:G,addTime:K,removeTime:q,cancel:J,reset:We,getStatus:()=>P.current,getRemainingMs:()=>N.current}));let Y=50-x/2,X=te(()=>2*Math.PI*Y,[Y]),Ge=X*(1-(F.current>0?Math.min(1,A/F.current):0)),Z=Math.max(F.current*De,Oe*1e3),Q=k===`running`&&A<=Z,Ke=Q&&A<=Math.min(5e3,Z),$=k===`paused`,qe=g&&!xe,Je=g&&!Se,Ye=g&&!Ce,Xe=k===`running`?re:ie,Ze=k===`running`?`Pause`:$?`Resume`:k===`idle`?`Start`:`Restart`,Qe=k===`running`?W:$?G:U,$e=g&&!we;return d(`div`,{...Ie,className:l(a.timer,ke&&Q&&a.timerPulsing,Ke&&a.timerCritical,Ne,E?.root),style:{...b?{"--timer-size":b}:null,"--timer-stroke-width":`${x}px`,...Pe,...D?.root},children:[d(`div`,{className:l(a.timerRingWrapper,E?.ringWrapper),style:D?.ringWrapper,children:[j.length>0&&u(`div`,{className:l(a.timerRipples,E?.ripples),style:D?.ripples,children:j.map(e=>u(`span`,{className:l(a.timerRipple,E?.ripple),style:D?.ripple,onAnimationEnd:()=>He(e)},e))}),d(`svg`,{className:l(a.timerRingSvg,E?.ringSvg),viewBox:`0 0 100 100`,style:D?.ringSvg,children:[u(`circle`,{className:l(a.timerRingTrack,E?.ringTrack),cx:`50`,cy:`50`,r:Y,style:D?.ringTrack}),u(`circle`,{className:l(a.timerRingProgress,Q&&a.timerRingProgressUrgent,E?.ringProgress),cx:`50`,cy:`50`,r:Y,strokeDasharray:X,strokeDashoffset:Ge,style:{transition:$?`none`:void 0,transform:Ee?`rotate(-90deg)`:void 0,...D?.ringProgress}})]}),d(`div`,{className:l(a.timerDisplay,E?.display),style:D?.display,children:[u(`span`,{className:l(a.timerTime,E?.time),style:D?.time,children:Te(A)}),y&&u(`span`,{className:l(a.timerLabel,E?.label),style:D?.label,children:y})]})]}),g&&d(`div`,{className:l(a.timerControls,E?.controls),style:D?.controls,children:[d(`div`,{className:a.timerControlsRow,children:[Je&&u(i,{icon:ne,title:`Remove ${_}s`,onClick:()=>q(_),className:l(a.timerAdjustButton,E?.removeButton),style:D?.removeButton}),Ye&&u(r,{size:n.Small,icon:Xe,title:Ze,onClick:Qe,className:E?.pauseButton,style:D?.pauseButton}),qe&&u(i,{icon:ae,title:`Add ${_}s`,onClick:()=>K(_),className:l(a.timerAdjustButton,E?.addButton),style:D?.addButton})]}),$e&&u(i,{icon:oe,title:Le.cancel,onClick:J,className:l(a.timerCancelButton,E?.cancelButton),style:D?.cancelButton})]})]})}export{f as default};
1
+ "use client";import{useComponentDefaults as e}from"../configProvider/useComponentDefaults.mjs";import{useLabels as t}from"../configProvider/useLabels.mjs";import{ButtonSize as n}from"../button/button.types.mjs";import r from"../button/button.mjs";import i from"../actionIcon/actionIcon.mjs";import"./timer.chime.mjs";import a from"./timer.module.mjs";import{useEffect as o,useImperativeHandle as ee,useMemo as te,useRef as s,useState as c}from"react";import l from"classnames";import{faMinus as ne,faPause as re,faPlay as ie,faPlus as ae,faXmark as oe}from"@fortawesome/free-solid-svg-icons";import{jsx as u,jsxs as d}from"react/jsx-runtime";var se=200,ce=1e3,le={cancel:`Cancel timer`};function ue(){return typeof window<`u`&&window.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches===!0}function de(e){let t=Math.ceil(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60,a=String(r).padStart(2,`0`),o=String(i).padStart(2,`0`);return n>0?`${n}:${a}:${o}`:`${a}:${o}`}function f(f){let{ref:fe,durationSeconds:p,autoStart:m=!0,resetOnDurationChange:pe=!0,onTick:h,onComplete:me,onStart:he,onPause:ge,onResume:_e,onCancel:ve,onAddTime:g,onRemoveTime:ye,showControls:_=!0,hideAddButton:be=!1,hideRemoveButton:xe=!1,hidePauseButton:Se=!1,hideCancelButton:Ce=!1,adjustSeconds:v=30,maxSeconds:y,label:b,formatTime:we=de,size:x,strokeWidth:S=10,counterClockwise:Te=!1,urgentThreshold:Ee=.1,urgentMinSeconds:De=3,pulseOnUrgent:Oe=!0,showRunningRipples:C=!1,playSoundOnComplete:w=!1,soundUrl:T,soundVolume:ke=.5,notifyOnComplete:E=!1,notificationTitle:Ae,notificationBody:je,className:Me,style:Ne,classNames:D,styles:O,labels:Pe,...Fe}=e(`Timer`,f),Ie=t(`Timer`,Pe,le),k=p*1e3,[A,Le]=c(m?`running`:`idle`),[j,Re]=c(k),[ze,Be]=c(0),[M,N]=c([]),P=s(j),F=s(A),I=s(k),L=s(!1),R=s(!1),z=s(!1),Ve=s(0);function B(e){P.current=e,Re(e)}function V(e){F.current=e,Le(e)}function H(){Be(e=>e+1)}o(()=>{if(A!==`running`)return;let e=Date.now(),t=P.current,n=setInterval(()=>{let n=Math.max(0,t-(Date.now()-e));B(n),h?.(n),n<=0&&V(`completed`)},se);return()=>clearInterval(n)},[A,ze]),o(()=>{if(A===`completed`&&!L.current){if(L.current=!0,me?.(),w)try{let e=new Audio(T||`data:audio/wav;base64,UklGRkYeAABXQVZFZm10IBAAAAABAAEAESsAACJWAAACABAAZGF0YSIeAAAAAAkAIAA4AEQANwAPANH/jv9b/07/cf/F/zkAsAAJAScB+QCCANv/K/+h/mX+j/4d//P/3QChAQkC8QFZAV0AOP80/pb9i/0g/jj/kgDaAbsC9gJzAkwBwv82/gz9k/zz/Bz+y/+ZARMD1QOoA44CxQC6/u782PvD+778kv7SAO8CYQTGBPwDLALE/1j9hfvD+kz7Bf2J/zwCcgSbBWUF1QNGAVX+vPsk+vj5TPvU/fYA7QP6BZYGkAUjA+D/k/wP+vj4nPna+y3/xQK+BVkHKActBeABC/6h+nz4LPjN+QD9AAHTBIQHYggvBy4EFgDn+6v4NPfm9576uP4zA/YGDAnsCJUGkgLc/Zz54vZh9kL4FfzvAKAF/AgqCtYITQVmAFX7W/d49Sv2Ufkq/ocDFgizCrIKCQhaA8f9sPhY9Zr0rfYW+8QAUwZiCuoLgwp9BtAA3voh9sjzb/T194T9wAMgCUwMdQyJCTgEzv3d9+Dz2fIR9QT6fwDsBrMLoQ00DL4HUgGC+v30JPKy8o32yPzeAxAK1A01DhILKwXu/ST3evIf8W/z4PghAGsH7wxMD+YNDQnrAUH68fOP8PjwGfX2++ED6ApKD+4PowwxBin+hfYq8W/vyfGs96r/zgcTDusQmQ9pCpwCGvr+8gvvQu+d8xD7ygOkC60QoBE5DkcHff4C9u/vy+0i8Gr2HP8WCCAPeRJ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8A7v/f/+7/`);e.volume=ke,e.play()?.catch(()=>{})}catch{}if(E&&typeof Notification<`u`&&Notification.permission===`granted`)try{new Notification(Ae??`Timer done`,{body:je??(typeof b==`string`?b:void 0)})}catch{}}A!==`completed`&&(L.current=!1)},[A]),o(()=>{if(!z.current){z.current=!0;return}let e=p*1e3;I.current=e,B(e),L.current=!1,H(),pe&&V(m?`running`:`idle`)},[p]),o(()=>{if(!C||A!==`running`||ue())return;function e(){let e=++Ve.current;N(t=>[...t,e])}e();let t=setInterval(e,ce);return()=>clearInterval(t)},[C,A]);function He(e){N(t=>t.filter(t=>t!==e))}function Ue(){E&&!R.current&&typeof Notification<`u`&&Notification.permission==="default"&&(R.current=!0,Notification.requestPermission().catch(()=>{}))}function U(){Ue(),(F.current===`completed`||F.current===`cancelled`)&&(B(I.current),L.current=!1),H(),V(`running`),he?.()}function W(){F.current===`running`&&(V(`paused`),ge?.())}function G(){F.current===`paused`&&(H(),V(`running`),_e?.())}function K(e){let t=y==null?1/0:y*1e3,n=Math.min(P.current+e*1e3,t);B(n),H(),g?.(e,Math.round(n/1e3)),F.current===`completed`&&n>0&&(L.current=!1,V(`running`))}function q(e){let t=Math.max(0,P.current-e*1e3);B(t),H(),ye?.(e,Math.round(t/1e3)),t<=0&&F.current===`running`&&V(`completed`)}function J(){B(I.current),V(`cancelled`),ve?.()}function We(){B(I.current),L.current=!1,V(`idle`)}ee(fe,()=>({start:U,pause:W,resume:G,addTime:K,removeTime:q,cancel:J,reset:We,getStatus:()=>F.current,getRemainingMs:()=>P.current}));let Y=50-S/2,X=te(()=>2*Math.PI*Y,[Y]),Ge=X*(1-(I.current>0?Math.min(1,j/I.current):0)),Z=Math.max(I.current*Ee,De*1e3),Q=A===`running`&&j<=Z,Ke=Q&&j<=Math.min(5e3,Z),$=A===`paused`,qe=_&&!be,Je=_&&!xe,Ye=_&&!Se,Xe=A===`running`?re:ie,Ze=A===`running`?`Pause`:$?`Resume`:A===`idle`?`Start`:`Restart`,Qe=A===`running`?W:$?G:U,$e=_&&!Ce;return d(`div`,{...Fe,className:l(a.timer,Oe&&Q&&a.timerPulsing,Ke&&a.timerCritical,Me,D?.root),style:{...x?{"--timer-size":x}:null,"--timer-stroke-width":`${S}px`,...Ne,...O?.root},children:[d(`div`,{className:l(a.timerRingWrapper,D?.ringWrapper),style:O?.ringWrapper,children:[M.length>0&&u(`div`,{className:l(a.timerRipples,D?.ripples),style:O?.ripples,children:M.map(e=>u(`span`,{className:l(a.timerRipple,D?.ripple),style:O?.ripple,onAnimationEnd:()=>He(e)},e))}),d(`svg`,{className:l(a.timerRingSvg,D?.ringSvg),viewBox:`0 0 100 100`,style:O?.ringSvg,children:[u(`circle`,{className:l(a.timerRingTrack,D?.ringTrack),cx:`50`,cy:`50`,r:Y,style:O?.ringTrack}),u(`circle`,{className:l(a.timerRingProgress,Q&&a.timerRingProgressUrgent,D?.ringProgress),cx:`50`,cy:`50`,r:Y,strokeDasharray:X,strokeDashoffset:Ge,style:{transition:$?`none`:void 0,transform:Te?`rotate(-90deg)`:void 0,...O?.ringProgress}})]}),d(`div`,{className:l(a.timerDisplay,D?.display),style:O?.display,children:[u(`span`,{className:l(a.timerTime,D?.time),style:O?.time,children:we(j)}),b&&u(`span`,{className:l(a.timerLabel,D?.label),style:O?.label,children:b})]})]}),_&&d(`div`,{className:l(a.timerControls,D?.controls),style:O?.controls,children:[d(`div`,{className:a.timerControlsRow,children:[Je&&u(i,{icon:ne,title:`Remove ${v}s`,onClick:()=>q(v),className:l(a.timerAdjustButton,D?.removeButton),style:O?.removeButton}),Ye&&u(r,{size:n.Small,icon:Xe,title:Ze,onClick:Qe,className:D?.pauseButton,style:O?.pauseButton}),qe&&u(i,{icon:ae,title:`Add ${v}s`,onClick:()=>K(v),className:l(a.timerAdjustButton,D?.addButton),style:O?.addButton})]}),$e&&u(i,{icon:oe,title:Ie.cancel,onClick:J,className:l(a.timerCancelButton,D?.cancelButton),style:O?.cancelButton})]})]})}export{f as default};
2
2
  //# sourceMappingURL=timer.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"timer.mjs","names":[],"sources":["../../../../package/common/timer/timer.tsx"],"sourcesContent":["import { useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';\nimport cx from 'classnames';\nimport { faPlus, faMinus, faPause, faPlay, faXmark } from '@fortawesome/free-solid-svg-icons';\n\nimport ActionIcon from '../actionIcon';\nimport Button from '../button';\nimport { ButtonSize } from '../button/button.types';\nimport { useComponentDefaults, useLabels } from '../configProvider';\nimport { DEFAULT_CHIME_DATA_URI } from './timer.chime';\nimport type { TimerLabels, TimerProps, TimerStatus } from './timer.types';\nimport styles from './timer.module.pcss';\n\nconst TICK_MS = 200;\nconst RIPPLE_SPAWN_INTERVAL_MS = 1000;\n\nconst DEFAULT_LABELS: Required<TimerLabels> = {\n cancel: 'Cancel timer',\n};\n\nfunction prefersReducedMotion(): boolean {\n return typeof window !== 'undefined' && window.matchMedia?.('(prefers-reduced-motion: reduce)').matches === true;\n}\n\nfunction formatTimeDefault(remainingMs: number) {\n const totalSeconds = Math.ceil(remainingMs / 1000);\n const hours = Math.floor(totalSeconds / 3600);\n const minutes = Math.floor((totalSeconds % 3600) / 60);\n const seconds = totalSeconds % 60;\n const mm = String(minutes).padStart(2, '0');\n const ss = String(seconds).padStart(2, '0');\n return hours > 0 ? `${hours}:${mm}:${ss}` : `${mm}:${ss}`;\n}\n\nfunction Timer(props: TimerProps) {\n const {\n ref,\n durationSeconds,\n autoStart = true,\n resetOnDurationChange = true,\n\n onTick,\n onComplete,\n onStart,\n onPause,\n onResume,\n onCancel,\n onAddTime,\n onRemoveTime,\n\n showControls = true,\n hideAddButton = false,\n hideRemoveButton = false,\n hidePauseButton = false,\n hideCancelButton = false,\n adjustSeconds = 30,\n maxSeconds,\n\n label,\n formatTime = formatTimeDefault,\n size,\n strokeWidth = 10,\n counterClockwise = false,\n\n urgentThreshold = 0.1,\n urgentMinSeconds = 3,\n pulseOnUrgent = true,\n showRunningRipples = false,\n\n playSoundOnComplete = false,\n soundUrl,\n soundVolume = 0.5,\n notifyOnComplete = false,\n notificationTitle,\n notificationBody,\n\n className,\n style,\n classNames,\n styles: slotStyles,\n labels,\n ...rest\n } = useComponentDefaults('Timer', props);\n const text = useLabels('Timer', labels, DEFAULT_LABELS);\n\n const initialMs = durationSeconds * 1000;\n const [status, setStatusState] = useState<TimerStatus>(autoStart ? 'running' : 'idle');\n const [remainingMs, setRemainingMsState] = useState(initialMs);\n const [epoch, setEpoch] = useState(0);\n const [ripples, setRipples] = useState<number[]>([]);\n\n const remainingRef = useRef(remainingMs);\n const statusRef = useRef(status);\n const totalMsRef = useRef(initialMs);\n const completedFiredRef = useRef(false);\n const notifyPermissionRequestedRef = useRef(false);\n const mountedRef = useRef(false);\n const rippleIdRef = useRef(0);\n\n function setRemaining(next: number) {\n remainingRef.current = next;\n setRemainingMsState(next);\n }\n\n function setStatus(next: TimerStatus) {\n statusRef.current = next;\n setStatusState(next);\n }\n\n function bumpEpoch() {\n setEpoch((e) => e + 1);\n }\n\n // Ticking effect. Re-derives the remaining time from Date.now() every tick (rather than\n // accumulating setInterval's own drift), so it stays accurate over long countdowns. Any\n // external mutation of remainingRef (addTime/removeTime while already running, or a resume)\n // must bump `epoch` so this effect re-arms and re-captures a fresh start/startRemaining —\n // without that, a stale `startRemaining` captured before the mutation would silently\n // overwrite it on the next tick.\n useEffect(() => {\n if (status !== 'running') return undefined;\n const start = Date.now();\n const startRemaining = remainingRef.current;\n const id = setInterval(() => {\n const next = Math.max(0, startRemaining - (Date.now() - start));\n setRemaining(next);\n onTick?.(next);\n if (next <= 0) setStatus('completed');\n }, TICK_MS);\n return () => clearInterval(id);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [status, epoch]);\n\n // Fires onComplete exactly once per completion, plus the opt-in sound/notification.\n useEffect(() => {\n if (status === 'completed' && !completedFiredRef.current) {\n completedFiredRef.current = true;\n onComplete?.();\n if (playSoundOnComplete) {\n try {\n const audio = new Audio(soundUrl || DEFAULT_CHIME_DATA_URI);\n audio.volume = soundVolume;\n // play() can reject (autoplay policy) or, in some environments, return undefined\n // instead of a Promise — never let a blocked/unsupported playback surface as an error.\n audio.play()?.catch(() => {});\n } catch {\n // Audio unavailable/unsupported — fail silently.\n }\n }\n if (notifyOnComplete && typeof Notification !== 'undefined' && Notification.permission === 'granted') {\n try {\n new Notification(notificationTitle ?? 'Timer done', {\n body: notificationBody ?? (typeof label === 'string' ? label : undefined),\n });\n } catch {\n // Some browsers (e.g. certain mobile Safari versions) throw constructing\n // Notification outside specific contexts — fail silently, as documented.\n }\n }\n }\n if (status !== 'completed') completedFiredRef.current = false;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [status]);\n\n // durationSeconds prop change: reset (and optionally restart) at the new duration. Skips\n // the initial mount, since autoStart/initial state already cover that.\n useEffect(() => {\n if (!mountedRef.current) {\n mountedRef.current = true;\n return;\n }\n const nextMs = durationSeconds * 1000;\n totalMsRef.current = nextMs;\n setRemaining(nextMs);\n completedFiredRef.current = false;\n bumpEpoch();\n if (resetOnDurationChange) {\n setStatus(autoStart ? 'running' : 'idle');\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [durationSeconds]);\n\n // Running-ripple spawner: spawns a new ripple roughly every RIPPLE_SPAWN_INTERVAL_MS while\n // running, each animating once (via CSS, `forwards`) and removing itself on `onAnimationEnd`.\n // Pausing (or otherwise leaving `running`) only stops new spawns here — it doesn't touch\n // `ripples` — so whichever ripples are already mid-flight keep animating to completion\n // instead of vanishing mid-cycle.\n useEffect(() => {\n if (!showRunningRipples || status !== 'running' || prefersReducedMotion()) return undefined;\n function spawnRipple() {\n rippleIdRef.current += 1;\n setRipples((prev) => [...prev, rippleIdRef.current]);\n }\n spawnRipple();\n const id = setInterval(spawnRipple, RIPPLE_SPAWN_INTERVAL_MS);\n return () => clearInterval(id);\n }, [showRunningRipples, status]);\n\n function handleRippleAnimationEnd(id: number) {\n setRipples((prev) => prev.filter((existingId) => existingId !== id));\n }\n\n function requestNotificationPermissionIfNeeded() {\n if (!notifyOnComplete || notifyPermissionRequestedRef.current) return;\n if (typeof Notification === 'undefined' || Notification.permission !== 'default') return;\n notifyPermissionRequestedRef.current = true;\n Notification.requestPermission().catch(() => {});\n }\n\n function start() {\n requestNotificationPermissionIfNeeded();\n if (statusRef.current === 'completed' || statusRef.current === 'cancelled') {\n setRemaining(totalMsRef.current);\n completedFiredRef.current = false;\n }\n bumpEpoch();\n setStatus('running');\n onStart?.();\n }\n\n function pause() {\n if (statusRef.current !== 'running') return;\n setStatus('paused');\n onPause?.();\n }\n\n function resume() {\n if (statusRef.current !== 'paused') return;\n bumpEpoch();\n setStatus('running');\n onResume?.();\n }\n\n function addTime(seconds: number) {\n const capped = maxSeconds != null ? maxSeconds * 1000 : Infinity;\n const next = Math.min(remainingRef.current + seconds * 1000, capped);\n setRemaining(next);\n bumpEpoch();\n onAddTime?.(seconds, Math.round(next / 1000));\n if (statusRef.current === 'completed' && next > 0) {\n completedFiredRef.current = false;\n setStatus('running');\n }\n }\n\n function removeTime(seconds: number) {\n const next = Math.max(0, remainingRef.current - seconds * 1000);\n setRemaining(next);\n bumpEpoch();\n onRemoveTime?.(seconds, Math.round(next / 1000));\n if (next <= 0 && statusRef.current === 'running') setStatus('completed');\n }\n\n function cancel() {\n setRemaining(totalMsRef.current);\n setStatus('cancelled');\n onCancel?.();\n }\n\n function reset() {\n setRemaining(totalMsRef.current);\n completedFiredRef.current = false;\n setStatus('idle');\n }\n\n useImperativeHandle(ref, () => ({\n start,\n pause,\n resume,\n addTime,\n removeTime,\n cancel,\n reset,\n getStatus: () => statusRef.current,\n getRemainingMs: () => remainingRef.current,\n }));\n\n const radius = 50 - strokeWidth / 2;\n const circumference = useMemo(() => 2 * Math.PI * radius, [radius]);\n const clampedFraction = totalMsRef.current > 0 ? Math.min(1, remainingMs / totalMsRef.current) : 0;\n const dashOffset = circumference * (1 - clampedFraction);\n const urgentMs = Math.max(totalMsRef.current * urgentThreshold, urgentMinSeconds * 1000);\n const isUrgent = status === 'running' && remainingMs <= urgentMs;\n const isCritical = isUrgent && remainingMs <= Math.min(5000, urgentMs);\n const isPaused = status === 'paused';\n\n // The pause button doubles as a play/restart button whenever there's nothing to pause —\n // idle (autoStart={false}), completed, or cancelled — rather than hiding itself, so there's\n // always a way to (re)start the countdown from the built-in controls alone.\n const showAddButton = showControls && !hideAddButton;\n const showRemoveButton = showControls && !hideRemoveButton;\n const showPauseButton = showControls && !hidePauseButton;\n const pauseButtonIcon = status === 'running' ? faPause : faPlay;\n const pauseButtonTitle =\n status === 'running' ? 'Pause' : isPaused ? 'Resume' : status === 'idle' ? 'Start' : 'Restart';\n const handlePauseButtonClick = status === 'running' ? pause : isPaused ? resume : start;\n const showCancelButton = showControls && !hideCancelButton;\n\n return (\n <div\n {...rest}\n className={cx(\n styles.timer,\n pulseOnUrgent && isUrgent && styles.timerPulsing,\n isCritical && styles.timerCritical,\n className,\n classNames?.root,\n )}\n style={\n {\n ...(size ? { '--timer-size': size } : null),\n '--timer-stroke-width': `${strokeWidth}px`,\n ...style,\n ...slotStyles?.root,\n } as React.CSSProperties\n }\n >\n <div className={cx(styles.timerRingWrapper, classNames?.ringWrapper)} style={slotStyles?.ringWrapper}>\n {ripples.length > 0 && (\n <div className={cx(styles.timerRipples, classNames?.ripples)} style={slotStyles?.ripples}>\n {ripples.map((id) => (\n <span\n key={id}\n className={cx(styles.timerRipple, classNames?.ripple)}\n style={slotStyles?.ripple}\n onAnimationEnd={() => handleRippleAnimationEnd(id)}\n />\n ))}\n </div>\n )}\n <svg className={cx(styles.timerRingSvg, classNames?.ringSvg)} viewBox='0 0 100 100' style={slotStyles?.ringSvg}>\n <circle\n className={cx(styles.timerRingTrack, classNames?.ringTrack)}\n cx='50'\n cy='50'\n r={radius}\n style={slotStyles?.ringTrack}\n />\n <circle\n className={cx(\n styles.timerRingProgress,\n isUrgent && styles.timerRingProgressUrgent,\n classNames?.ringProgress,\n )}\n cx='50'\n cy='50'\n r={radius}\n strokeDasharray={circumference}\n strokeDashoffset={dashOffset}\n style={{\n transition: isPaused ? 'none' : undefined,\n transform: counterClockwise ? 'rotate(-90deg)' : undefined,\n ...slotStyles?.ringProgress,\n }}\n />\n </svg>\n <div className={cx(styles.timerDisplay, classNames?.display)} style={slotStyles?.display}>\n <span className={cx(styles.timerTime, classNames?.time)} style={slotStyles?.time}>\n {formatTime(remainingMs)}\n </span>\n {label && (\n <span className={cx(styles.timerLabel, classNames?.label)} style={slotStyles?.label}>\n {label}\n </span>\n )}\n </div>\n </div>\n\n {showControls && (\n <div className={cx(styles.timerControls, classNames?.controls)} style={slotStyles?.controls}>\n <div className={styles.timerControlsRow}>\n {showRemoveButton && (\n <ActionIcon\n icon={faMinus}\n title={`Remove ${adjustSeconds}s`}\n onClick={() => removeTime(adjustSeconds)}\n className={cx(styles.timerAdjustButton, classNames?.removeButton)}\n style={slotStyles?.removeButton}\n />\n )}\n {showPauseButton && (\n <Button\n size={ButtonSize.Small}\n icon={pauseButtonIcon}\n title={pauseButtonTitle}\n onClick={handlePauseButtonClick}\n className={classNames?.pauseButton}\n style={slotStyles?.pauseButton}\n />\n )}\n {showAddButton && (\n <ActionIcon\n icon={faPlus}\n title={`Add ${adjustSeconds}s`}\n onClick={() => addTime(adjustSeconds)}\n className={cx(styles.timerAdjustButton, classNames?.addButton)}\n style={slotStyles?.addButton}\n />\n )}\n </div>\n {showCancelButton && (\n <ActionIcon\n icon={faXmark}\n title={text.cancel}\n onClick={cancel}\n className={cx(styles.timerCancelButton, classNames?.cancelButton)}\n style={slotStyles?.cancelButton}\n />\n )}\n </div>\n )}\n </div>\n );\n}\n\nexport default Timer;\n"],"mappings":"koBAYA,IAAM,GAAU,IACV,GAA2B,IAE3B,GAAwC,CAC5C,OAAQ,cACV,EAEA,SAAS,IAAgC,CACvC,OAAO,OAAO,OAAW,KAAe,OAAO,aAAa,kCAAkC,CAAC,CAAC,UAAY,EAC9G,CAEA,SAAS,GAAkB,EAAqB,CAC9C,I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AAC,EAAD,CACE,KAAM,GACN,MAAO,UAAU,EAAc,GAC/B,YAAe,EAAW,CAAa,EACvC,UAAW,EAAG,EAAO,kBAAmB,GAAY,YAAY,EAChE,MAAO,GAAY,YACpB,CAAA,EAEF,IACC,EAAC,EAAD,CACE,KAAM,EAAW,MACjB,KAAM,GACN,MAAO,GACP,QAAS,GACT,UAAW,GAAY,YACvB,MAAO,GAAY,WACpB,CAAA,EAEF,IACC,EAAC,EAAD,CACE,KAAM,GACN,MAAO,OAAO,EAAc,GAC5B,YAAe,EAAQ,CAAa,EACpC,UAAW,EAAG,EAAO,kBAAmB,GAAY,SAAS,EAC7D,MAAO,GAAY,SACpB,CAAA,CAEA,CACJ,CAAA,EAAA,IACC,EAAC,EAAD,CACE,KAAM,GACN,MAAO,GAAK,OACZ,QAAS,EACT,UAAW,EAAG,EAAO,kBAAmB,GAAY,YAAY,EAChE,MAAO,GAAY,YACpB,CAAA,CAEA,CAEJ,CAAA,CAAA,GAET"}
1
+ {"version":3,"file":"timer.mjs","names":[],"sources":["../../../../package/common/timer/timer.tsx"],"sourcesContent":["import { useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';\nimport cx from 'classnames';\nimport { faPlus, faMinus, faPause, faPlay, faXmark } from '@fortawesome/free-solid-svg-icons';\n\nimport ActionIcon from '../actionIcon';\nimport Button from '../button';\nimport { ButtonSize } from '../button/button.types';\nimport { useComponentDefaults, useLabels } from '../configProvider';\nimport { DEFAULT_CHIME_DATA_URI } from './timer.chime';\nimport type { TimerLabels, TimerProps, TimerStatus } from './timer.types';\nimport styles from './timer.module.pcss';\n\nconst TICK_MS = 200;\nconst RIPPLE_SPAWN_INTERVAL_MS = 1000;\n\nconst DEFAULT_LABELS: Required<TimerLabels> = {\n cancel: 'Cancel timer',\n};\n\nfunction prefersReducedMotion(): boolean {\n return typeof window !== 'undefined' && window.matchMedia?.('(prefers-reduced-motion: reduce)').matches === true;\n}\n\nfunction formatTimeDefault(remainingMs: number) {\n const totalSeconds = Math.ceil(remainingMs / 1000);\n const hours = Math.floor(totalSeconds / 3600);\n const minutes = Math.floor((totalSeconds % 3600) / 60);\n const seconds = totalSeconds % 60;\n const mm = String(minutes).padStart(2, '0');\n const ss = String(seconds).padStart(2, '0');\n return hours > 0 ? `${hours}:${mm}:${ss}` : `${mm}:${ss}`;\n}\n\nfunction Timer(props: TimerProps) {\n const {\n ref,\n durationSeconds,\n autoStart = true,\n resetOnDurationChange = true,\n\n onTick,\n onComplete,\n onStart,\n onPause,\n onResume,\n onCancel,\n onAddTime,\n onRemoveTime,\n\n showControls = true,\n hideAddButton = false,\n hideRemoveButton = false,\n hidePauseButton = false,\n hideCancelButton = false,\n adjustSeconds = 30,\n maxSeconds,\n\n label,\n formatTime = formatTimeDefault,\n size,\n strokeWidth = 10,\n counterClockwise = false,\n\n urgentThreshold = 0.1,\n urgentMinSeconds = 3,\n pulseOnUrgent = true,\n showRunningRipples = false,\n\n playSoundOnComplete = false,\n soundUrl,\n soundVolume = 0.5,\n notifyOnComplete = false,\n notificationTitle,\n notificationBody,\n\n className,\n style,\n classNames,\n styles: slotStyles,\n labels,\n ...rest\n } = useComponentDefaults('Timer', props);\n const text = useLabels('Timer', labels, DEFAULT_LABELS);\n\n const initialMs = durationSeconds * 1000;\n const [status, setStatusState] = useState<TimerStatus>(autoStart ? 'running' : 'idle');\n const [remainingMs, setRemainingMsState] = useState(initialMs);\n const [epoch, setEpoch] = useState(0);\n const [ripples, setRipples] = useState<number[]>([]);\n\n const remainingRef = useRef(remainingMs);\n const statusRef = useRef(status);\n const totalMsRef = useRef(initialMs);\n const completedFiredRef = useRef(false);\n const notifyPermissionRequestedRef = useRef(false);\n const mountedRef = useRef(false);\n const rippleIdRef = useRef(0);\n\n function setRemaining(next: number) {\n remainingRef.current = next;\n setRemainingMsState(next);\n }\n\n function setStatus(next: TimerStatus) {\n statusRef.current = next;\n setStatusState(next);\n }\n\n function bumpEpoch() {\n setEpoch((e) => e + 1);\n }\n\n // Ticking effect. Re-derives the remaining time from Date.now() every tick (rather than\n // accumulating setInterval's own drift), so it stays accurate over long countdowns. Any\n // external mutation of remainingRef (addTime/removeTime while already running, or a resume)\n // must bump `epoch` so this effect re-arms and re-captures a fresh start/startRemaining —\n // without that, a stale `startRemaining` captured before the mutation would silently\n // overwrite it on the next tick.\n useEffect(() => {\n if (status !== 'running') return undefined;\n const start = Date.now();\n const startRemaining = remainingRef.current;\n const id = setInterval(() => {\n const next = Math.max(0, startRemaining - (Date.now() - start));\n setRemaining(next);\n onTick?.(next);\n if (next <= 0) setStatus('completed');\n }, TICK_MS);\n return () => clearInterval(id);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [status, epoch]);\n\n // Fires onComplete exactly once per completion, plus the opt-in sound/notification.\n useEffect(() => {\n if (status === 'completed' && !completedFiredRef.current) {\n completedFiredRef.current = true;\n onComplete?.();\n if (playSoundOnComplete) {\n try {\n const audio = new Audio(soundUrl || DEFAULT_CHIME_DATA_URI);\n audio.volume = soundVolume;\n // play() can reject (autoplay policy) or, in some environments, return undefined\n // instead of a Promise — never let a blocked/unsupported playback surface as an error.\n audio.play()?.catch(() => {});\n } catch {\n // Audio unavailable/unsupported — fail silently.\n }\n }\n if (notifyOnComplete && typeof Notification !== 'undefined' && Notification.permission === 'granted') {\n try {\n new Notification(notificationTitle ?? 'Timer done', {\n body: notificationBody ?? (typeof label === 'string' ? label : undefined),\n });\n } catch {\n // Some browsers (e.g. certain mobile Safari versions) throw constructing\n // Notification outside specific contexts — fail silently, as documented.\n }\n }\n }\n if (status !== 'completed') completedFiredRef.current = false;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [status]);\n\n // durationSeconds prop change: reset (and optionally restart) at the new duration. Skips\n // the initial mount, since autoStart/initial state already cover that.\n useEffect(() => {\n if (!mountedRef.current) {\n mountedRef.current = true;\n return;\n }\n const nextMs = durationSeconds * 1000;\n totalMsRef.current = nextMs;\n setRemaining(nextMs);\n completedFiredRef.current = false;\n bumpEpoch();\n if (resetOnDurationChange) {\n setStatus(autoStart ? 'running' : 'idle');\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [durationSeconds]);\n\n // Running-ripple spawner: spawns a new ripple roughly every RIPPLE_SPAWN_INTERVAL_MS while\n // running, each animating once (via CSS, `forwards`) and removing itself on `onAnimationEnd`.\n // Pausing (or otherwise leaving `running`) only stops new spawns here — it doesn't touch\n // `ripples` — so whichever ripples are already mid-flight keep animating to completion\n // instead of vanishing mid-cycle.\n useEffect(() => {\n if (!showRunningRipples || status !== 'running' || prefersReducedMotion()) return undefined;\n function spawnRipple() {\n // Read now, not in the updater: two spawns before a render would both see the later id.\n const rippleId = ++rippleIdRef.current;\n setRipples((prev) => [...prev, rippleId]);\n }\n spawnRipple();\n const id = setInterval(spawnRipple, RIPPLE_SPAWN_INTERVAL_MS);\n return () => clearInterval(id);\n }, [showRunningRipples, status]);\n\n function handleRippleAnimationEnd(id: number) {\n setRipples((prev) => prev.filter((existingId) => existingId !== id));\n }\n\n function requestNotificationPermissionIfNeeded() {\n if (!notifyOnComplete || notifyPermissionRequestedRef.current) return;\n if (typeof Notification === 'undefined' || Notification.permission !== 'default') return;\n notifyPermissionRequestedRef.current = true;\n Notification.requestPermission().catch(() => {});\n }\n\n function start() {\n requestNotificationPermissionIfNeeded();\n if (statusRef.current === 'completed' || statusRef.current === 'cancelled') {\n setRemaining(totalMsRef.current);\n completedFiredRef.current = false;\n }\n bumpEpoch();\n setStatus('running');\n onStart?.();\n }\n\n function pause() {\n if (statusRef.current !== 'running') return;\n setStatus('paused');\n onPause?.();\n }\n\n function resume() {\n if (statusRef.current !== 'paused') return;\n bumpEpoch();\n setStatus('running');\n onResume?.();\n }\n\n function addTime(seconds: number) {\n const capped = maxSeconds != null ? maxSeconds * 1000 : Infinity;\n const next = Math.min(remainingRef.current + seconds * 1000, capped);\n setRemaining(next);\n bumpEpoch();\n onAddTime?.(seconds, Math.round(next / 1000));\n if (statusRef.current === 'completed' && next > 0) {\n completedFiredRef.current = false;\n setStatus('running');\n }\n }\n\n function removeTime(seconds: number) {\n const next = Math.max(0, remainingRef.current - seconds * 1000);\n setRemaining(next);\n bumpEpoch();\n onRemoveTime?.(seconds, Math.round(next / 1000));\n if (next <= 0 && statusRef.current === 'running') setStatus('completed');\n }\n\n function cancel() {\n setRemaining(totalMsRef.current);\n setStatus('cancelled');\n onCancel?.();\n }\n\n function reset() {\n setRemaining(totalMsRef.current);\n completedFiredRef.current = false;\n setStatus('idle');\n }\n\n useImperativeHandle(ref, () => ({\n start,\n pause,\n resume,\n addTime,\n removeTime,\n cancel,\n reset,\n getStatus: () => statusRef.current,\n getRemainingMs: () => remainingRef.current,\n }));\n\n const radius = 50 - strokeWidth / 2;\n const circumference = useMemo(() => 2 * Math.PI * radius, [radius]);\n const clampedFraction = totalMsRef.current > 0 ? Math.min(1, remainingMs / totalMsRef.current) : 0;\n const dashOffset = circumference * (1 - clampedFraction);\n const urgentMs = Math.max(totalMsRef.current * urgentThreshold, urgentMinSeconds * 1000);\n const isUrgent = status === 'running' && remainingMs <= urgentMs;\n const isCritical = isUrgent && remainingMs <= Math.min(5000, urgentMs);\n const isPaused = status === 'paused';\n\n // The pause button doubles as a play/restart button whenever there's nothing to pause —\n // idle (autoStart={false}), completed, or cancelled — rather than hiding itself, so there's\n // always a way to (re)start the countdown from the built-in controls alone.\n const showAddButton = showControls && !hideAddButton;\n const showRemoveButton = showControls && !hideRemoveButton;\n const showPauseButton = showControls && !hidePauseButton;\n const pauseButtonIcon = status === 'running' ? faPause : faPlay;\n const pauseButtonTitle =\n status === 'running' ? 'Pause' : isPaused ? 'Resume' : status === 'idle' ? 'Start' : 'Restart';\n const handlePauseButtonClick = status === 'running' ? pause : isPaused ? resume : start;\n const showCancelButton = showControls && !hideCancelButton;\n\n return (\n <div\n {...rest}\n className={cx(\n styles.timer,\n pulseOnUrgent && isUrgent && styles.timerPulsing,\n isCritical && styles.timerCritical,\n className,\n classNames?.root,\n )}\n style={\n {\n ...(size ? { '--timer-size': size } : null),\n '--timer-stroke-width': `${strokeWidth}px`,\n ...style,\n ...slotStyles?.root,\n } as React.CSSProperties\n }\n >\n <div className={cx(styles.timerRingWrapper, classNames?.ringWrapper)} style={slotStyles?.ringWrapper}>\n {ripples.length > 0 && (\n <div className={cx(styles.timerRipples, classNames?.ripples)} style={slotStyles?.ripples}>\n {ripples.map((id) => (\n <span\n key={id}\n className={cx(styles.timerRipple, classNames?.ripple)}\n style={slotStyles?.ripple}\n onAnimationEnd={() => handleRippleAnimationEnd(id)}\n />\n ))}\n </div>\n )}\n <svg className={cx(styles.timerRingSvg, classNames?.ringSvg)} viewBox='0 0 100 100' style={slotStyles?.ringSvg}>\n <circle\n className={cx(styles.timerRingTrack, classNames?.ringTrack)}\n cx='50'\n cy='50'\n r={radius}\n style={slotStyles?.ringTrack}\n />\n <circle\n className={cx(\n styles.timerRingProgress,\n isUrgent && styles.timerRingProgressUrgent,\n classNames?.ringProgress,\n )}\n cx='50'\n cy='50'\n r={radius}\n strokeDasharray={circumference}\n strokeDashoffset={dashOffset}\n style={{\n transition: isPaused ? 'none' : undefined,\n transform: counterClockwise ? 'rotate(-90deg)' : undefined,\n ...slotStyles?.ringProgress,\n }}\n />\n </svg>\n <div className={cx(styles.timerDisplay, classNames?.display)} style={slotStyles?.display}>\n <span className={cx(styles.timerTime, classNames?.time)} style={slotStyles?.time}>\n {formatTime(remainingMs)}\n </span>\n {label && (\n <span className={cx(styles.timerLabel, classNames?.label)} style={slotStyles?.label}>\n {label}\n </span>\n )}\n </div>\n </div>\n\n {showControls && (\n <div className={cx(styles.timerControls, classNames?.controls)} style={slotStyles?.controls}>\n <div className={styles.timerControlsRow}>\n {showRemoveButton && (\n <ActionIcon\n icon={faMinus}\n title={`Remove ${adjustSeconds}s`}\n onClick={() => removeTime(adjustSeconds)}\n className={cx(styles.timerAdjustButton, classNames?.removeButton)}\n style={slotStyles?.removeButton}\n />\n )}\n {showPauseButton && (\n <Button\n size={ButtonSize.Small}\n icon={pauseButtonIcon}\n title={pauseButtonTitle}\n onClick={handlePauseButtonClick}\n className={classNames?.pauseButton}\n style={slotStyles?.pauseButton}\n />\n )}\n {showAddButton && (\n <ActionIcon\n icon={faPlus}\n title={`Add ${adjustSeconds}s`}\n onClick={() => addTime(adjustSeconds)}\n className={cx(styles.timerAdjustButton, classNames?.addButton)}\n style={slotStyles?.addButton}\n />\n )}\n </div>\n {showCancelButton && (\n <ActionIcon\n icon={faXmark}\n title={text.cancel}\n onClick={cancel}\n className={cx(styles.timerCancelButton, classNames?.cancelButton)}\n style={slotStyles?.cancelButton}\n />\n )}\n </div>\n )}\n </div>\n );\n}\n\nexport default Timer;\n"],"mappings":"koBAYA,IAAM,GAAU,IACV,GAA2B,IAE3B,GAAwC,CAC5C,OAAQ,cACV,EAEA,SAAS,IAAgC,CACvC,OAAO,OAAO,OAAW,KAAe,OAAO,aAAa,kCAAkC,CAAC,CAAC,UAAY,EAC9G,CAEA,SAAS,GAAkB,EAAqB,CAC9C,IAAM,EAAe,KAAK,KAAK,EAAc,GAAI,EAC3C,EAAQ,KAAK,MAAM,EAAe,IAAI,EACtC,EAAU,KAAK,MAAO,EAAe,KAAQ,EAAE,EAC/C,EAAU,EAAe,GACzB,EAAK,OAAO,CAAO,CAAC,CAAC,SAAS,EAAG,GAAG,EACpC,EAAK,OAAO,CAAO,CAAC,CAAC,SAAS,EAAG,GAAG,EAC1C,OAAO,EAAQ,EAAI,GAAG,EAAM,GAAG,EAAG,GAAG,IAAO,GAAG,EAAG,GAAG,GACvD,CAEA,SAAS,EAAM,EAAmB,CAChC,GAAM,CACJ,OACA,kBACA,YAAY,GACZ,yBAAwB,GAExB,SACA,cACA,WACA,WACA,YACA,YACA,YACA,gBAEA,eAAe,GACf,iBAAgB,GAChB,oBAAmB,GACnB,mBAAkB,GAClB,oBAAmB,GACnB,gBAAgB,GAChB,aAEA,QACA,cAAa,GACb,OACA,cAAc,GACd,oBAAmB,GAEnB,mBAAkB,GAClB,oBAAmB,EACnB,iB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@@ -1,2 +1,2 @@
1
- "use client";function e(e){let t=[],n=e.parentElement;for(;n&&n!==document.body&&n!==document.documentElement;){let e=getComputedStyle(n);(e.overflowX!==`visible`||e.overflowY!==`visible`)&&t.push(n),n=n.parentElement}return t}function t(e,t){return t.some(t=>{let n=t.getBoundingClientRect();return e.bottom<=n.top||e.top>=n.bottom||e.right<=n.left||e.left>=n.right})}export{e as getScrollableAncestors,t as isHiddenByAnyAncestor};
1
+ "use client";function e(e){let t=[],n=e.parentElement;for(;n&&n!==document.body&&n!==document.documentElement;){let e=getComputedStyle(n);(e.overflowX!==`visible`||e.overflowY!==`visible`)&&t.push(n),n=n.parentElement}return t}function t(e,t){return t.some(t=>{let n=t.getBoundingClientRect();return e.bottom<=n.top||e.top>=n.bottom||e.right<=n.left||e.left>=n.right})}function n(e){let t=e?.parentElement??null;for(;t&&t!==document.body;){let{overflowY:e}=getComputedStyle(t);if(e===`auto`||e===`scroll`||e===`overlay`)return t;t=t.parentElement}return null}export{n as getScrollParent,e as getScrollableAncestors,t as isHiddenByAnyAncestor};
2
2
  //# sourceMappingURL=scrollAncestors.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"scrollAncestors.mjs","names":[],"sources":["../../../../package/common/utils/scrollAncestors.ts"],"sourcesContent":["// Scrollable ancestors up to (not including) <body>. This is computed once per open rather\n// than on every scroll tick, since walking the tree and reading computed style forces layout,\n// which is too expensive to repeat at scroll frequency (Floating UI's autoUpdate does the same\n// thing, resolving the ancestor list once via getOverflowAncestors). Plain page/viewport scroll\n// is deliberately left out: a trigger that scrolls off the top of the page already renders its\n// fixed-position anchor off-screen for free.\nexport function getScrollableAncestors(el: HTMLElement): HTMLElement[] {\n const ancestors: HTMLElement[] = [];\n let node = el.parentElement;\n while (node && node !== document.body && node !== document.documentElement) {\n const style = getComputedStyle(node);\n if (style.overflowX !== 'visible' || style.overflowY !== 'visible') ancestors.push(node);\n node = node.parentElement;\n }\n return ancestors;\n}\n\nexport function isHiddenByAnyAncestor(rect: DOMRect, ancestors: HTMLElement[]): boolean {\n return ancestors.some((ancestor) => {\n const a = ancestor.getBoundingClientRect();\n return rect.bottom <= a.top || rect.top >= a.bottom || rect.right <= a.left || rect.left >= a.right;\n });\n}\n"],"mappings":"aAMA,SAAgB,EAAuB,EAAgC,CACrE,IAAM,EAA2B,CAAC,EAC9B,EAAO,EAAG,cACd,KAAO,GAAQ,IAAS,SAAS,MAAQ,IAAS,SAAS,iBAAiB,CAC1E,IAAM,EAAQ,iBAAiB,CAAI,GAC/B,EAAM,YAAc,WAAa,EAAM,YAAc,YAAW,EAAU,KAAK,CAAI,EACvF,EAAO,EAAK,aACd,CACA,OAAO,CACT,CAEA,SAAgB,EAAsB,EAAe,EAAmC,CACtF,OAAO,EAAU,KAAM,GAAa,CAClC,IAAM,EAAI,EAAS,sBAAsB,EACzC,OAAO,EAAK,QAAU,EAAE,KAAO,EAAK,KAAO,EAAE,QAAU,EAAK,OAAS,EAAE,MAAQ,EAAK,MAAQ,EAAE,KAChG,CAAC,CACH"}
1
+ {"version":3,"file":"scrollAncestors.mjs","names":[],"sources":["../../../../package/common/utils/scrollAncestors.ts"],"sourcesContent":["// Scrollable ancestors up to (not including) <body>. This is computed once per open rather\n// than on every scroll tick, since walking the tree and reading computed style forces layout,\n// which is too expensive to repeat at scroll frequency (Floating UI's autoUpdate does the same\n// thing, resolving the ancestor list once via getOverflowAncestors). Plain page/viewport scroll\n// is deliberately left out: a trigger that scrolls off the top of the page already renders its\n// fixed-position anchor off-screen for free.\nexport function getScrollableAncestors(el: HTMLElement): HTMLElement[] {\n const ancestors: HTMLElement[] = [];\n let node = el.parentElement;\n while (node && node !== document.body && node !== document.documentElement) {\n const style = getComputedStyle(node);\n if (style.overflowX !== 'visible' || style.overflowY !== 'visible') ancestors.push(node);\n node = node.parentElement;\n }\n return ancestors;\n}\n\nexport function isHiddenByAnyAncestor(rect: DOMRect, ancestors: HTMLElement[]): boolean {\n return ancestors.some((ancestor) => {\n const a = ancestor.getBoundingClientRect();\n return rect.bottom <= a.top || rect.top >= a.bottom || rect.right <= a.left || rect.left >= a.right;\n });\n}\n\n/**\n * The ancestor whose scrollbar carries `el`, or null when that is the page.\n * `Sticky` pins against it and `VirtualList` virtualizes against it, and the two\n * have to agree or a sticky header and the rows under it come apart.\n *\n * Narrower than `getScrollableAncestors` above, which is about who *clips* and so\n * counts `hidden` too: a `hidden` box never scrolls, so pinning to it would pin\n * to something that never moves.\n */\nexport function getScrollParent(el: HTMLElement | null): HTMLElement | null {\n let node = el?.parentElement ?? null;\n while (node && node !== document.body) {\n const { overflowY } = getComputedStyle(node);\n if (overflowY === 'auto' || overflowY === 'scroll' || overflowY === 'overlay') return node;\n node = node.parentElement;\n }\n return null;\n}\n"],"mappings":"aAMA,SAAgB,EAAuB,EAAgC,CACrE,IAAM,EAA2B,CAAC,EAC9B,EAAO,EAAG,cACd,KAAO,GAAQ,IAAS,SAAS,MAAQ,IAAS,SAAS,iBAAiB,CAC1E,IAAM,EAAQ,iBAAiB,CAAI,GAC/B,EAAM,YAAc,WAAa,EAAM,YAAc,YAAW,EAAU,KAAK,CAAI,EACvF,EAAO,EAAK,aACd,CACA,OAAO,CACT,CAEA,SAAgB,EAAsB,EAAe,EAAmC,CACtF,OAAO,EAAU,KAAM,GAAa,CAClC,IAAM,EAAI,EAAS,sBAAsB,EACzC,OAAO,EAAK,QAAU,EAAE,KAAO,EAAK,KAAO,EAAE,QAAU,EAAK,OAAS,EAAE,MAAQ,EAAK,MAAQ,EAAE,KAChG,CAAC,CACH,CAWA,SAAgB,EAAgB,EAA4C,CAC1E,IAAI,EAAO,GAAI,eAAiB,KAChC,KAAO,GAAQ,IAAS,SAAS,MAAM,CACrC,GAAM,CAAE,aAAc,iBAAiB,CAAI,EAC3C,GAAI,IAAc,QAAU,IAAc,UAAY,IAAc,UAAW,OAAO,EACtF,EAAO,EAAK,aACd,CACA,OAAO,IACT"}
@@ -0,0 +1,2 @@
1
+ "use client";function e(e){return!(`nodeType`in e)}function t(e){return e==null||typeof window>`u`?null:e===`window`?window:typeof e==`function`?e()??window:e}function n(t){return e(t)?{top:0,height:t.innerHeight}:{top:t.getBoundingClientRect().top+t.clientTop,height:t.clientHeight}}function r(e,t){let r=e.clientWidth;if(!t){let t=e.clientHeight;return{rel:e.scrollTop,visibleHeight:t,viewportHeight:t,distanceToEnd:e.scrollHeight-e.scrollTop-t,width:r}}let i=e.getBoundingClientRect(),{top:a,height:o}=n(t),s=a+o;return{rel:a-i.top,visibleHeight:Math.max(0,Math.min(s,i.bottom)-Math.max(a,i.top)),viewportHeight:o,distanceToEnd:i.bottom-s,width:r}}export{e as isWindowScroller,r as measureViewport,t as resolveScroller,n as scrollportBounds};
2
+ //# sourceMappingURL=scroller.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scroller.mjs","names":[],"sources":["../../../../package/common/virtualList/scroller.ts"],"sourcesContent":["import type { VirtualListScrollParent } from './virtualList.types';\n\n/**\n * Whatever carries the list's scroll, and how the list is measured against it.\n *\n * Everything here works in *list space*: offset 0 is the top of the first row,\n * which is the root's `scrollTop` when the list scrolls itself and its distance\n * above the scrollport's top edge when it doesn't. One coordinate system, so the\n * windowing, anchoring and jump math never branch.\n */\n\nexport type Scroller = HTMLElement | Window;\n\nexport function isWindowScroller(scroller: Scroller): scroller is Window {\n return !('nodeType' in scroller);\n}\n\n/** `'nearest'` is resolved by the caller, which caches the ancestor walk. */\nexport function resolveScroller(\n scrollParent: Exclude<VirtualListScrollParent, 'nearest'> | undefined,\n): Scroller | null {\n if (scrollParent == null || typeof window === 'undefined') return null;\n if (scrollParent === 'window') return window;\n // Resolved on every commit, so a ref still empty on the first render costs one\n // frame against the page rather than rendering nothing.\n if (typeof scrollParent === 'function') return scrollParent() ?? window;\n return scrollParent;\n}\n\n/** In viewport coordinates, which is what the rects below are compared against. */\nexport function scrollportBounds(scroller: Scroller): { top: number; height: number } {\n if (isWindowScroller(scroller)) return { top: 0, height: scroller.innerHeight };\n // `clientTop` is the border, which `getBoundingClientRect` includes and\n // `clientHeight` doesn't: without it a bordered scroll parent is off by it.\n return { top: scroller.getBoundingClientRect().top + scroller.clientTop, height: scroller.clientHeight };\n}\n\nexport interface Viewport {\n /** List-space scroll position, unclamped: negative while the list starts below\n * the scrollport, which is what makes a target reachable from either side. */\n rel: number;\n /** The slice of the scrollport the list occupies now. */\n visibleHeight: number;\n /** The whole scrollport, which is what a scroll target is aimed within. */\n viewportHeight: number;\n /** From the list's last row to the end of the scrollport. The browser clamps\n * `scrollTop`, so a list that scrolls itself never reports this negative;\n * riding a scrollport, it does, for the whole rest of the page. */\n distanceToEnd: number;\n width: number;\n}\n\nexport function measureViewport(root: HTMLElement, scroller: Scroller | null): Viewport {\n const width = root.clientWidth;\n if (!scroller) {\n const height = root.clientHeight;\n return {\n rel: root.scrollTop,\n visibleHeight: height,\n viewportHeight: height,\n distanceToEnd: root.scrollHeight - root.scrollTop - height,\n width,\n };\n }\n const rect = root.getBoundingClientRect();\n const { top, height } = scrollportBounds(scroller);\n const bottom = top + height;\n return {\n rel: top - rect.top,\n visibleHeight: Math.max(0, Math.min(bottom, rect.bottom) - Math.max(top, rect.top)),\n viewportHeight: height,\n distanceToEnd: rect.bottom - bottom,\n width,\n };\n}\n"],"mappings":"aAaA,SAAgB,EAAiB,EAAwC,CACvE,MAAO,EAAE,aAAc,EACzB,CAGA,SAAgB,EACd,EACiB,CAMjB,OALI,GAAgB,MAAQ,OAAO,OAAW,IAAoB,KAC9D,IAAiB,SAAiB,OAGlC,OAAO,GAAiB,WAAmB,EAAa,GAAK,OAC1D,CACT,CAGA,SAAgB,EAAiB,EAAqD,CAIpF,OAHI,EAAiB,CAAQ,EAAU,CAAE,IAAK,EAAG,OAAQ,EAAS,WAAY,EAGvE,CAAE,IAAK,EAAS,sBAAsB,CAAC,CAAC,IAAM,EAAS,UAAW,OAAQ,EAAS,YAAa,CACzG,CAiBA,SAAgB,EAAgB,EAAmB,EAAqC,CACtF,IAAM,EAAQ,EAAK,YACnB,GAAI,CAAC,EAAU,CACb,IAAM,EAAS,EAAK,aACpB,MAAO,CACL,IAAK,EAAK,UACV,cAAe,EACf,eAAgB,EAChB,cAAe,EAAK,aAAe,EAAK,UAAY,EACpD,OACF,CACF,CACA,IAAM,EAAO,EAAK,sBAAsB,EAClC,CAAE,MAAK,UAAW,EAAiB,CAAQ,EAC3C,EAAS,EAAM,EACrB,MAAO,CACL,IAAK,EAAM,EAAK,IAChB,cAAe,KAAK,IAAI,EAAG,KAAK,IAAI,EAAQ,EAAK,MAAM,EAAI,KAAK,IAAI,EAAK,EAAK,GAAG,CAAC,EAClF,eAAgB,EAChB,cAAe,EAAK,OAAS,EAC7B,OACF,CACF"}
@@ -1,2 +1,2 @@
1
- "use client";import e from"./virtualList.module.mjs";import{lastDescendantIndex as t,resolveReorderTarget as n,resolveTreeDropTarget as r}from"./virtualList.utils.mjs";import{useCallback as i,useEffect as a,useLayoutEffect as o,useRef as s,useState as c}from"react";function l({reorderable:l,treeReorder:u,onReorder:d,onTreeDrop:f,longPressDelay:ee,dragHandle:p,treeIndentPx:m,keys:h,depths:g,isGroupAt:_,rootRef:v,keysRef:y}){let b=s(null),[x,S]=c(null),[C,w]=c(null),T=s(null),E=s(d),D=s(f),O=s(u),k=s(g),A=s(_),j=s(!0),M=s(null),[N,te]=c(null),P=s(null),F=s(!1),I=s(null),L=s(0),R=s(0),z=s(null),B=s(!1),V=s(null),H=s(0),U=s(0),W=s(0),[G]=c(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(pointer: coarse)`).matches);o(()=>{E.current=d,D.current=f,O.current=u,k.current=g,T.current=C,A.current=_});function K(e){G||M.current!==e&&(M.current=e,te(e))}function ne(e,t){t.buttons===0&&K(t.target.closest(`[data-drag-handle]`)?e:null)}function re(e){e.buttons===0&&K(null)}function ie(e,t){if(t.button!==0)return;let n=!!t.target.closest(`[data-drag-handle]`);j.current=n,n&&K(e)}function ae(e,t){if(p&&!j.current){t.preventDefault();return}b.current=e,S(e),u&&w(null)}function oe(e,n,i){let a=b.current;if(a==null)return null;let o=h.indexOf(a);if(o!==-1&&e>=o&&e<=t(o,g))return null;let s=r(n,i.top,i.height,_(e));return{key:h[e],position:s}}function se(e,t){t.preventDefault();let n=t.currentTarget.getBoundingClientRect(),r=oe(e,t.clientY,n);w(e=>e?.key===r?.key&&e?.position===r?.position?e:r)}function ce(){let e=b.current,t=T.current;e!=null&&t&&t.key!==e&&f?.(e,t)}function le(e){e.preventDefault(),ce(),w(null),b.current=null,S(null),K(null)}function ue(){w(null),b.current=null,S(null),K(null)}function de(e,t){t.preventDefault();let r=b.current;if(r==null)return;let i=h.indexOf(r),a=t.currentTarget.getBoundingClientRect(),o=n(i,e,t.clientY,a.top,a.height);o!=null&&d?.(i,o)}function fe(){b.current=null,S(null),K(null)}let q=i(e=>{let i=b.current,a=v.current;if(i==null||!a)return;let o=V.current?R.current-H.current+W.current/2:R.current,s=document.elementFromPoint(e,o),c=s&&a.contains(s)?s.closest(`[data-index]`):null;if(!c)return;let l=Number(c.dataset.index);if(Number.isNaN(l))return;let u=y.current.indexOf(i),d=c.getBoundingClientRect();if(O.current){let e=y.current,n=k.current;if(u!==-1&&l>=u&&l<=t(u,n)){w(null);return}let i=r(o,d.top,d.height,A.current(l)),a={key:e[l],position:i};w(e=>e?.key===a.key&&e?.position===a.position?e:a);return}let f=n(u,l,o,d.top,d.height);f!=null&&E.current?.(u,f)},[v,y]),J=i(()=>{let e=V.current;e&&(e.style.transform=`translate(${U.current}px, ${R.current-H.current}px)`)},[]),Y=i(()=>{let e=v.current;if(!e||!F.current){z.current=null;return}let t=e.getBoundingClientRect(),n=L.current,r=R.current,i=0;n>=t.left&&n<=t.right&&r>=t.top&&r<=t.bottom&&(r<t.top+48?i=-Math.min(18,Math.ceil((t.top+48-r)/3)):r>t.bottom-48&&(i=Math.min(18,Math.ceil((r-(t.bottom-48))/3)))),i!==0&&(e.scrollTop+=i,q(n)),z.current=requestAnimationFrame(Y)},[q,v]),X=i(()=>{if(P.current!=null&&(clearTimeout(P.current),P.current=null),window.removeEventListener(`touchmove`,Z),window.removeEventListener(`touchend`,X),window.removeEventListener(`touchcancel`,X),z.current!=null&&(cancelAnimationFrame(z.current),z.current=null),V.current&&=(V.current.remove(),null),document.body.style.touchAction=``,document.body.style.overscrollBehavior=``,F.current&&(B.current=!0,setTimeout(()=>{B.current=!1},350),O.current)){let e=b.current,t=T.current;e!=null&&t&&t.key!==e&&D.current?.(e,t)}w(null),F.current=!1,I.current=null,b.current=null,S(null)},[]),Z=i(e=>{let t=e.touches[0];if(t){if(L.current=t.clientX,R.current=t.clientY,!F.current){let e=I.current;e!=null&&Math.abs(t.clientY-e)>10&&P.current!=null&&(clearTimeout(P.current),P.current=null);return}e.cancelable&&e.preventDefault(),J(),q(t.clientX)}},[q,J]);function pe(e,t){if(!l&&!u||p&&!t.target.closest(`[data-drag-handle]`)||P.current!=null||F.current)return;let n=t.touches[0];n&&(I.current=n.clientY,L.current=n.clientX,R.current=n.clientY,window.addEventListener(`touchmove`,Z,{passive:!1}),window.addEventListener(`touchend`,X),window.addEventListener(`touchcancel`,X),P.current=window.setTimeout(()=>{P.current=null,F.current=!0,b.current=e,S(e),navigator.vibrate?.(10),document.body.style.touchAction=`none`,document.body.style.overscrollBehavior=`none`,me(e),z.current??=requestAnimationFrame(Y)},ee))}function me(t){let n=v.current;if(!n)return;let r=y.current.indexOf(t),i=n.querySelector(`[data-index="${r}"]`);if(!i)return;let a=i.getBoundingClientRect();H.current=R.current-a.top,U.current=a.left,W.current=a.height;let o=i.cloneNode(!0);o.removeAttribute(`data-index`),o.setAttribute(`data-drag-clone`,`true`),o.setAttribute(`aria-hidden`,`true`),o.classList.add(e.virtualListDragClone),Object.assign(o.style,{position:`fixed`,left:`0`,top:`0`,width:`${a.width}px`,height:`${a.height}px`,margin:`0`,opacity:`1`,pointerEvents:`none`,zIndex:`3`,background:`var(--background)`,boxShadow:`var(--card-shadow)`,borderRadius:`var(--default-border-radius)`}),n.appendChild(o),V.current=o,J()}a(()=>X,[X]);let Q=l||u,$=Q&&!G;function he(e,t){let n=u&&C?.key===t?C.position:void 0;return{reorderable:Q&&!p,mouseDragEnabled:$,draggable:$&&(!p||t===N)||void 0,isDragging:Q&&t===x,onMouseDown:Q&&p?e=>ie(t,e):void 0,onMouseOver:Q&&p?e=>ne(t,e):void 0,onMouseLeave:Q&&p?re:void 0,onDragStart:Q?e=>ae(t,e):void 0,onDragOver:u?t=>se(e,t):l?t=>de(e,t):void 0,onDragEnd:u?ue:l?fe:void 0,onDrop:u?le:void 0,onTouchStart:Q?e=>pe(t,e):void 0,dropPosition:n,dropIndentPx:n?(g[e]??0)*m:void 0}}function ge(){return B.current?(B.current=!1,!0):!1}return{draggingKey:x,dragEnabled:Q,getRowDragProps:he,consumeSuppressedClick:ge}}export{l as useRowDrag};
1
+ "use client";import e from"./virtualList.module.mjs";import{lastDescendantIndex as t,resolveReorderTarget as n,resolveTreeDropTarget as r}from"./virtualList.utils.mjs";import{useCallback as i,useEffect as a,useLayoutEffect as o,useRef as s,useState as c}from"react";function l({reorderable:l,treeReorder:u,onReorder:d,onTreeDrop:f,longPressDelay:ee,dragHandle:p,treeIndentPx:te,keys:m,depths:h,isGroupAt:g,rootRef:_,keysRef:v,getVisibleRect:y,scrollBy:b}){let x=s(null),[S,C]=c(null),[w,T]=c(null),E=s(null),D=s(d),O=s(f),k=s(u),A=s(h),j=s(g),M=s(!0),N=s(null),[ne,re]=c(null),P=s(null),F=s(!1),I=s(null),L=s(0),R=s(0),z=s(null),B=s(!1),V=s(null),H=s(0),U=s(0),W=s(0),[G]=c(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(pointer: coarse)`).matches);o(()=>{D.current=d,O.current=f,k.current=u,A.current=h,E.current=w,j.current=g});function K(e){G||N.current!==e&&(N.current=e,re(e))}function ie(e,t){t.buttons===0&&K(t.target.closest(`[data-drag-handle]`)?e:null)}function ae(e){e.buttons===0&&K(null)}function oe(e,t){if(t.button!==0)return;let n=!!t.target.closest(`[data-drag-handle]`);M.current=n,n&&K(e)}function se(e,t){if(p&&!M.current){t.preventDefault();return}x.current=e,C(e),u&&T(null)}function ce(e,n,i){let a=x.current;if(a==null)return null;let o=m.indexOf(a);if(o!==-1&&e>=o&&e<=t(o,h))return null;let s=r(n,i.top,i.height,g(e));return{key:m[e],position:s}}function le(e,t){t.preventDefault();let n=t.currentTarget.getBoundingClientRect(),r=ce(e,t.clientY,n);T(e=>e?.key===r?.key&&e?.position===r?.position?e:r)}function ue(){let e=x.current,t=E.current;e!=null&&t&&t.key!==e&&f?.(e,t)}function de(e){e.preventDefault(),ue(),T(null),x.current=null,C(null),K(null)}function fe(){T(null),x.current=null,C(null),K(null)}function pe(e,t){t.preventDefault();let r=x.current;if(r==null)return;let i=m.indexOf(r),a=t.currentTarget.getBoundingClientRect(),o=n(i,e,t.clientY,a.top,a.height);o!=null&&d?.(i,o)}function me(){x.current=null,C(null),K(null)}let q=i(e=>{let i=x.current,a=_.current;if(i==null||!a)return;let o=V.current?R.current-H.current+W.current/2:R.current,s=document.elementFromPoint(e,o),c=s&&a.contains(s)?s.closest(`[data-index]`):null;if(!c)return;let l=Number(c.dataset.index);if(Number.isNaN(l))return;let u=v.current.indexOf(i),d=c.getBoundingClientRect();if(k.current){let e=v.current,n=A.current;if(u!==-1&&l>=u&&l<=t(u,n)){T(null);return}let i=r(o,d.top,d.height,j.current(l)),a={key:e[l],position:i};T(e=>e?.key===a.key&&e?.position===a.position?e:a);return}let f=n(u,l,o,d.top,d.height);f!=null&&D.current?.(u,f)},[_,v]),J=i(()=>{let e=V.current;e&&(e.style.transform=`translate(${U.current}px, ${R.current-H.current}px)`)},[]),Y=i(()=>{let e=F.current?y():null;if(!e){z.current=null;return}let t=L.current,n=R.current,r=0;t>=e.left&&t<=e.right&&n>=e.top&&n<=e.bottom&&(n<e.top+48?r=-Math.min(18,Math.ceil((e.top+48-n)/3)):n>e.bottom-48&&(r=Math.min(18,Math.ceil((n-(e.bottom-48))/3)))),r!==0&&(b(r),q(t)),z.current=requestAnimationFrame(Y)},[q,y,b]),X=i(()=>{if(P.current!=null&&(clearTimeout(P.current),P.current=null),window.removeEventListener(`touchmove`,Z),window.removeEventListener(`touchend`,X),window.removeEventListener(`touchcancel`,X),z.current!=null&&(cancelAnimationFrame(z.current),z.current=null),V.current&&=(V.current.remove(),null),document.body.style.touchAction=``,document.body.style.overscrollBehavior=``,F.current&&(B.current=!0,setTimeout(()=>{B.current=!1},350),k.current)){let e=x.current,t=E.current;e!=null&&t&&t.key!==e&&O.current?.(e,t)}T(null),F.current=!1,I.current=null,x.current=null,C(null)},[]),Z=i(e=>{let t=e.touches[0];if(t){if(L.current=t.clientX,R.current=t.clientY,!F.current){let e=I.current;e!=null&&Math.abs(t.clientY-e)>10&&P.current!=null&&(clearTimeout(P.current),P.current=null);return}e.cancelable&&e.preventDefault(),J(),q(t.clientX)}},[q,J]);function he(e,t){if(!l&&!u||p&&!t.target.closest(`[data-drag-handle]`)||P.current!=null||F.current)return;let n=t.touches[0];n&&(I.current=n.clientY,L.current=n.clientX,R.current=n.clientY,window.addEventListener(`touchmove`,Z,{passive:!1}),window.addEventListener(`touchend`,X),window.addEventListener(`touchcancel`,X),P.current=window.setTimeout(()=>{P.current=null,F.current=!0,x.current=e,C(e),navigator.vibrate?.(10),document.body.style.touchAction=`none`,document.body.style.overscrollBehavior=`none`,ge(e),z.current??=requestAnimationFrame(Y)},ee))}function ge(t){let n=_.current;if(!n)return;let r=v.current.indexOf(t),i=n.querySelector(`[data-index="${r}"]`);if(!i)return;let a=i.getBoundingClientRect();H.current=R.current-a.top,U.current=a.left,W.current=a.height;let o=i.cloneNode(!0);o.removeAttribute(`data-index`),o.setAttribute(`data-drag-clone`,`true`),o.setAttribute(`aria-hidden`,`true`),o.classList.add(e.virtualListDragClone),Object.assign(o.style,{position:`fixed`,left:`0`,top:`0`,width:`${a.width}px`,height:`${a.height}px`,margin:`0`,opacity:`1`,pointerEvents:`none`,zIndex:`3`,background:`var(--background)`,boxShadow:`var(--card-shadow)`,borderRadius:`var(--default-border-radius)`}),n.appendChild(o),V.current=o,J()}a(()=>X,[X]);let Q=l||u,$=Q&&!G;function _e(e,t){let n=u&&w?.key===t?w.position:void 0;return{reorderable:Q&&!p,mouseDragEnabled:$,draggable:$&&(!p||t===ne)||void 0,isDragging:Q&&t===S,onMouseDown:Q&&p?e=>oe(t,e):void 0,onMouseOver:Q&&p?e=>ie(t,e):void 0,onMouseLeave:Q&&p?ae:void 0,onDragStart:Q?e=>se(t,e):void 0,onDragOver:u?t=>le(e,t):l?t=>pe(e,t):void 0,onDragEnd:u?fe:l?me:void 0,onDrop:u?de:void 0,onTouchStart:Q?e=>he(t,e):void 0,dropPosition:n,dropIndentPx:n?(h[e]??0)*te:void 0}}function ve(){return B.current?(B.current=!1,!0):!1}return{draggingKey:S,dragEnabled:Q,getRowDragProps:_e,consumeSuppressedClick:ve}}export{l as useRowDrag};
2
2
  //# sourceMappingURL=useRowDrag.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"useRowDrag.mjs","names":[],"sources":["../../../../package/common/virtualList/useRowDrag.ts"],"sourcesContent":["import React, { useState, useRef, useEffect, useLayoutEffect, useCallback } from 'react';\n\nimport styles from './virtualList.module.pcss';\nimport { resolveReorderTarget, resolveTreeDropTarget, lastDescendantIndex } from './virtualList.utils';\nimport type { TreeDropPosition, TreeDropTarget } from './virtualList.types';\n\ninterface UseRowDragArgs {\n reorderable: boolean;\n treeReorder: boolean;\n onReorder?: (fromIndex: number, toIndex: number) => void;\n onTreeDrop?: (dragKey: string | number, target: TreeDropTarget) => void;\n longPressDelay: number;\n dragHandle: boolean;\n treeIndentPx: number;\n /** Current flat ordering and depth tags (mouse handlers read these directly). */\n keys: (string | number)[];\n depths: number[];\n isGroupAt: (index: number) => boolean;\n rootRef: React.RefObject<HTMLDivElement | null>;\n /** Latest keys for async (touch / rAF) consumers — owned by useVirtualWindow. */\n keysRef: React.RefObject<(string | number)[]>;\n}\n\n/** The drag-related props the parent spreads onto a given row. */\nexport interface RowDragProps {\n reorderable: boolean;\n /** Native mouse DnD is active for the list (independent of which row is armed). */\n mouseDragEnabled: boolean;\n draggable: boolean | undefined;\n isDragging: boolean;\n onMouseDown: ((e: React.MouseEvent<HTMLDivElement>) => void) | undefined;\n onMouseOver: ((e: React.MouseEvent<HTMLDivElement>) => void) | undefined;\n onMouseLeave: ((e: React.MouseEvent<HTMLDivElement>) => void) | undefined;\n onDragStart: ((e: React.DragEvent<HTMLDivElement>) => void) | undefined;\n onDragOver: ((e: React.DragEvent<HTMLDivElement>) => void) | undefined;\n onDragEnd: (() => void) | undefined;\n onDrop: ((e: React.DragEvent<HTMLDivElement>) => void) | undefined;\n onTouchStart: ((e: React.TouchEvent<HTMLDivElement>) => void) | undefined;\n dropPosition: TreeDropPosition | undefined;\n dropIndentPx: number | undefined;\n}\n\ninterface UseRowDragResult {\n /** True while a row is being dragged (for the root reordering style). */\n draggingKey: string | number | null;\n /** Whether either drag mode is active. */\n dragEnabled: boolean;\n /** Drag props for the row at `index` / `key`. */\n getRowDragProps: (index: number, key: string | number) => RowDragProps;\n /** Returns true (and resets) if the next click should be swallowed (post-drag). */\n consumeSuppressedClick: () => boolean;\n}\n\n/**\n * Row drag-and-drop for both modes:\n * - `reorderable` (flat): native HTML5 drag on desktop; rows move live via\n * `onReorder` with midpoint hysteresis.\n * - `treeReorder`: a drop indicator (before/after/inside) is shown during the\n * drag and `onTreeDrop` fires once on release; dropping onto the dragged\n * node's own subtree is forbidden.\n * Touch uses a long-press → lifted-clone → pointer-move path with edge\n * auto-scroll. `dragHandle` restricts initiation to `[data-drag-handle]`.\n */\nexport function useRowDrag({\n reorderable,\n treeReorder,\n onReorder,\n onTreeDrop,\n longPressDelay,\n dragHandle,\n treeIndentPx,\n keys,\n depths,\n isGroupAt,\n rootRef,\n keysRef,\n}: UseRowDragArgs): UseRowDragResult {\n // The dragged item is tracked by its stable key (indices shift after each\n // live reorder); the ref drives the logic, the state drives the row's style.\n const dragKeyRef = useRef<string | number | null>(null);\n const [draggingKey, setDraggingKey] = useState<string | number | null>(null);\n // Tree-reorder drop indicator. Unlike flat reorder (which moves rows live),\n // tree mode shows where the drop will land and commits once on release.\n const [dropTarget, setDropTarget] = useState<TreeDropTarget | null>(null);\n const dropTargetRef = useRef<TreeDropTarget | null>(null);\n const onReorderRef = useRef(onReorder);\n const onTreeDropRef = useRef(onTreeDrop);\n const treeModeRef = useRef(treeReorder);\n const depthsRef = useRef<number[]>(depths);\n const isGroupAtRef = useRef<(i: number) => boolean>(isGroupAt);\n // When `dragHandle` is on, a mousedown sets this to whether it landed on a\n // `[data-drag-handle]` element, gating whether the ensuing dragstart is honoured.\n const dragFromHandleRef = useRef(true);\n // In `dragHandle` mode the `draggable` attribute is only on the row whose\n // handle the pointer is currently over (\"armed\"). A permanently `draggable`\n // row breaks mouse text selection (caret placement, double-click word select,\n // drag select) inside any child input in Firefox — see Mozilla bugs 739071 /\n // 800050 / 1189486. Arming on hover rather than on mousedown means the\n // attribute is already in place before the press, so the browser never has to\n // notice it appearing mid-gesture, and any pointer move re-derives it.\n const armedKeyRef = useRef<string | number | null>(null);\n const [armedKey, setArmedKeyState] = useState<string | number | null>(null);\n const longPressRef = useRef<number | null>(null);\n const touchActiveRef = useRef(false);\n const touchStartYRef = useRef<number | null>(null);\n const pointerXRef = useRef(0);\n const pointerYRef = useRef(0);\n const autoScrollRef = useRef<number | null>(null);\n const suppressNextClickRef = useRef(false);\n // Floating clone that follows the finger during a touch drag.\n const dragCloneRef = useRef<HTMLElement | null>(null);\n const grabOffsetYRef = useRef(0);\n const cloneLeftRef = useRef(0);\n const dragHeightRef = useRef(0);\n // The native `draggable` attribute (mouse DnD) makes a long-press start the\n // browser's own drag on touch devices, which hijacks our touch handlers. So\n // expose it only where the primary pointer is fine (mouse/trackpad); touch\n // devices use the touch handlers below instead.\n const [isCoarsePointer] = useState(() =>\n typeof window !== 'undefined' && typeof window.matchMedia === 'function'\n ? window.matchMedia('(pointer: coarse)').matches\n : false,\n );\n\n useLayoutEffect(() => {\n onReorderRef.current = onReorder;\n onTreeDropRef.current = onTreeDrop;\n treeModeRef.current = treeReorder;\n depthsRef.current = depths;\n dropTargetRef.current = dropTarget;\n isGroupAtRef.current = isGroupAt;\n });\n\n // ── Mouse / shared start ──────────────────────────────────────────────────\n\n /** Move the `draggable` attribute to `next` (or off entirely for `null`). */\n function arm(next: string | number | null) {\n // Arming exists purely to place the native `draggable` attribute, which is\n // never set on a coarse pointer (touch uses the handlers below instead). A\n // tap still synthesises mouseover/mousedown, so without this a touch device\n // would re-render the list on every handle tap to no effect whatsoever.\n if (isCoarsePointer) return;\n if (armedKeyRef.current === next) return; // mouseover fires constantly — no-op\n armedKeyRef.current = next;\n setArmedKeyState(next);\n }\n\n // Arm while the pointer rests on this row's handle, disarm as it moves off.\n // `buttons !== 0` means a press is already in progress: the pointer can drift\n // off the handle before the browser reaches its drag threshold, so hover is\n // ignored until release rather than disarming a drag that is about to start.\n function handleRowMouseOver(key: string | number, e: React.MouseEvent<HTMLDivElement>) {\n if (e.buttons !== 0) return;\n arm((e.target as HTMLElement).closest('[data-drag-handle]') ? key : null);\n }\n\n function handleRowMouseLeave(e: React.MouseEvent<HTMLDivElement>) {\n if (e.buttons !== 0) return;\n arm(null);\n }\n\n // With `dragHandle`, remember on mousedown whether the press landed on a\n // handle, so the dragstart that follows can be ignored if it didn't. Arming\n // here too covers a handle that came to sit under an already-stationary cursor\n // (the list scrolled), which produces no mouseover.\n function handleRowMouseDown(key: string | number, e: React.MouseEvent<HTMLDivElement>) {\n if (e.button !== 0) return; // only a primary press can begin a drag\n const fromHandle = !!(e.target as HTMLElement).closest('[data-drag-handle]');\n dragFromHandleRef.current = fromHandle;\n if (fromHandle) arm(key);\n }\n\n function handleReorderStart(key: string | number, e: React.DragEvent<HTMLDivElement>) {\n if (dragHandle && !dragFromHandleRef.current) {\n e.preventDefault(); // not started from a handle — let the row stay put\n return;\n }\n dragKeyRef.current = key;\n setDraggingKey(key);\n if (treeReorder) setDropTarget(null);\n }\n\n // ── Tree mode ─────────────────────────────────────────────────────────────\n\n /** Resolve the tree drop target for the row at `overIndex` under pointer `y`. */\n function computeTreeDrop(overIndex: number, y: number, rect: DOMRect): TreeDropTarget | null {\n const dragKey = dragKeyRef.current;\n if (dragKey == null) return null;\n const fromIndex = keys.indexOf(dragKey);\n // Forbid dropping onto the dragged node or anything in its own subtree.\n if (fromIndex !== -1 && overIndex >= fromIndex && overIndex <= lastDescendantIndex(fromIndex, depths)) {\n return null;\n }\n const position = resolveTreeDropTarget(y, rect.top, rect.height, isGroupAt(overIndex));\n return { key: keys[overIndex], position };\n }\n\n function handleTreeDragOver(overIndex: number, e: React.DragEvent<HTMLDivElement>) {\n e.preventDefault(); // allow the drop\n const rect = e.currentTarget.getBoundingClientRect();\n const next = computeTreeDrop(overIndex, e.clientY, rect);\n setDropTarget((prev) => (prev?.key === next?.key && prev?.position === next?.position ? prev : next));\n }\n\n function commitTreeDrop() {\n const dragKey = dragKeyRef.current;\n const target = dropTargetRef.current;\n if (dragKey != null && target && target.key !== dragKey) onTreeDrop?.(dragKey, target);\n }\n\n function handleTreeDrop(e: React.DragEvent<HTMLDivElement>) {\n e.preventDefault();\n commitTreeDrop();\n setDropTarget(null);\n dragKeyRef.current = null;\n setDraggingKey(null);\n arm(null);\n }\n\n function handleTreeDragEnd() {\n // Fires after `drop` (or on its own when released off a valid target).\n setDropTarget(null);\n dragKeyRef.current = null;\n setDraggingKey(null);\n arm(null);\n }\n\n // ── Flat mode ─────────────────────────────────────────────────────────────\n\n function handleReorderOver(overIndex: number, e: React.DragEvent<HTMLDivElement>) {\n e.preventDefault(); // allow the drop\n const dragKey = dragKeyRef.current;\n if (dragKey == null) return;\n const fromIndex = keys.indexOf(dragKey);\n // Midpoint hysteresis (see resolveReorderTarget): a move only happens once\n // the pointer crosses the centre of the row it's over. After a swap the\n // dragged row sits under the cursor, so moving again needs real pointer\n // travel — this stops the oscillation that made dragging feel jumpy.\n const rect = e.currentTarget.getBoundingClientRect();\n const target = resolveReorderTarget(fromIndex, overIndex, e.clientY, rect.top, rect.height);\n if (target != null) onReorder?.(fromIndex, target);\n }\n\n function handleReorderEnd() {\n dragKeyRef.current = null;\n setDraggingKey(null);\n arm(null);\n }\n\n // ── Touch reordering (long-press to arm, then drag) ──────────────────────────\n // These handlers run from window listeners during a touch drag, so they read\n // mutable state from refs and are stable across renders.\n\n const reorderAtPoint = useCallback(\n (x: number) => {\n const dragKey = dragKeyRef.current;\n const root = rootRef.current;\n if (dragKey == null || !root) return;\n // Reorder against the centre of the lifted clone, not the raw finger — the\n // finger sits below the clone's top by the grab offset, so using it would\n // make the top (and bottom) rows unreachable. The clone is what the user\n // aims with, so match it.\n const y = dragCloneRef.current\n ? pointerYRef.current - grabOffsetYRef.current + dragHeightRef.current / 2\n : pointerYRef.current;\n const el = document.elementFromPoint(x, y) as HTMLElement | null;\n const rowEl = el && root.contains(el) ? el.closest<HTMLElement>('[data-index]') : null;\n if (!rowEl) return;\n const overIndex = Number(rowEl.dataset.index);\n if (Number.isNaN(overIndex)) return;\n const fromIndex = keysRef.current.indexOf(dragKey);\n const rect = rowEl.getBoundingClientRect();\n if (treeModeRef.current) {\n // Tree mode: don't move live — just track where the drop will land.\n const ks = keysRef.current;\n const ds = depthsRef.current;\n if (fromIndex !== -1 && overIndex >= fromIndex && overIndex <= lastDescendantIndex(fromIndex, ds)) {\n setDropTarget(null);\n return;\n }\n const position = resolveTreeDropTarget(y, rect.top, rect.height, isGroupAtRef.current(overIndex));\n const next: TreeDropTarget = { key: ks[overIndex], position };\n setDropTarget((prev) => (prev?.key === next.key && prev?.position === next.position ? prev : next));\n return;\n }\n const target = resolveReorderTarget(fromIndex, overIndex, y, rect.top, rect.height);\n if (target != null) onReorderRef.current?.(fromIndex, target);\n },\n [rootRef, keysRef],\n );\n\n // Keep the floating clone glued under the finger (same grab point).\n const positionDragClone = useCallback(() => {\n const clone = dragCloneRef.current;\n if (!clone) return;\n clone.style.transform = `translate(${cloneLeftRef.current}px, ${pointerYRef.current - grabOffsetYRef.current}px)`;\n }, []);\n\n // While the finger sits near a top/bottom edge (and within the list's width),\n // scroll the list and keep reordering against the rows now passing under it.\n const autoScrollTick = useCallback(() => {\n const root = rootRef.current;\n if (!root || !touchActiveRef.current) {\n autoScrollRef.current = null;\n return;\n }\n const rect = root.getBoundingClientRect();\n const x = pointerXRef.current;\n const y = pointerYRef.current;\n const EDGE = 48;\n let dy = 0;\n // Only auto-scroll while the finger is actually over the list — moving it\n // outside (any direction) stops the scroll instead of running away; pinning\n // the dragged row keeps touch events alive so it resumes when you come back.\n const inside = x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;\n if (inside) {\n if (y < rect.top + EDGE) dy = -Math.min(18, Math.ceil((rect.top + EDGE - y) / 3));\n else if (y > rect.bottom - EDGE) dy = Math.min(18, Math.ceil((y - (rect.bottom - EDGE)) / 3));\n }\n if (dy !== 0) {\n root.scrollTop += dy;\n reorderAtPoint(x);\n }\n autoScrollRef.current = requestAnimationFrame(autoScrollTick);\n }, [reorderAtPoint, rootRef]);\n\n const endTouchDrag = useCallback(() => {\n if (longPressRef.current != null) {\n clearTimeout(longPressRef.current);\n longPressRef.current = null;\n }\n window.removeEventListener('touchmove', handleTouchMove);\n window.removeEventListener('touchend', endTouchDrag);\n window.removeEventListener('touchcancel', endTouchDrag);\n if (autoScrollRef.current != null) {\n cancelAnimationFrame(autoScrollRef.current);\n autoScrollRef.current = null;\n }\n if (dragCloneRef.current) {\n dragCloneRef.current.remove();\n dragCloneRef.current = null;\n }\n // Restore native scrolling that was locked for the duration of the drag.\n document.body.style.touchAction = '';\n document.body.style.overscrollBehavior = '';\n if (touchActiveRef.current) {\n // A real drag happened — swallow the click the browser fires afterwards\n // so it doesn't, e.g., toggle row selection.\n suppressNextClickRef.current = true;\n setTimeout(() => {\n suppressNextClickRef.current = false;\n }, 350);\n // Tree mode commits the pending drop on release (flat mode already moved\n // rows live during the drag, so there's nothing to commit here).\n if (treeModeRef.current) {\n const dk = dragKeyRef.current;\n const target = dropTargetRef.current;\n if (dk != null && target && target.key !== dk) onTreeDropRef.current?.(dk, target);\n }\n }\n setDropTarget(null);\n touchActiveRef.current = false;\n touchStartYRef.current = null;\n dragKeyRef.current = null;\n setDraggingKey(null);\n // handleTouchMove and endTouchDrag remove each other’s listeners, so neither can list\n // the other without a cycle.\n // oxlint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const handleTouchMove = useCallback(\n (e: TouchEvent) => {\n const t = e.touches[0];\n if (!t) return;\n pointerXRef.current = t.clientX;\n pointerYRef.current = t.clientY;\n if (!touchActiveRef.current) {\n // Before the long-press fires: if the finger travels, the user means to\n // scroll, so disarm and let the browser handle it (we don't preventDefault).\n const sy = touchStartYRef.current;\n if (sy != null && Math.abs(t.clientY - sy) > 10 && longPressRef.current != null) {\n clearTimeout(longPressRef.current);\n longPressRef.current = null;\n }\n return;\n }\n // Non-passive listener: preventDefault cancels the native scroll for this\n // gesture — the only reliable way once touch-action has been latched at\n // touchstart. This is what makes the drag actually move on touch devices.\n if (e.cancelable) e.preventDefault();\n positionDragClone();\n reorderAtPoint(t.clientX);\n },\n [reorderAtPoint, positionDragClone],\n );\n\n function handleRowTouchStart(key: string | number, e: React.TouchEvent<HTMLDivElement>) {\n if (!reorderable && !treeReorder) return;\n // With a drag handle, only a press that starts on it arms the drag, so the\n // rest of the row stays free for tapping/typing into inputs.\n if (dragHandle && !(e.target as HTMLElement).closest('[data-drag-handle]')) return;\n if (longPressRef.current != null || touchActiveRef.current) return; // ignore extra fingers\n const t = e.touches[0];\n if (!t) return;\n touchStartYRef.current = t.clientY;\n pointerXRef.current = t.clientX;\n pointerYRef.current = t.clientY;\n window.addEventListener('touchmove', handleTouchMove, { passive: false });\n window.addEventListener('touchend', endTouchDrag);\n window.addEventListener('touchcancel', endTouchDrag);\n longPressRef.current = window.setTimeout(() => {\n longPressRef.current = null;\n touchActiveRef.current = true;\n dragKeyRef.current = key;\n setDraggingKey(key);\n navigator.vibrate?.(10);\n // Lock native scrolling for the whole gesture — relying on per-move\n // preventDefault isn't enough once the finger leaves and re-enters the\n // list (the browser commits to a scroll and ignores it). We do all the\n // scrolling ourselves via autoScrollTick.\n document.body.style.touchAction = 'none';\n document.body.style.overscrollBehavior = 'none';\n createDragClone(key);\n if (autoScrollRef.current == null) autoScrollRef.current = requestAnimationFrame(autoScrollTick);\n }, longPressDelay);\n }\n\n // Build a floating copy of the picked-up row that tracks the finger, so the\n // drag has a visible \"lifted\" element (the original row stays dimmed in place\n // as a drop placeholder).\n function createDragClone(key: string | number) {\n const root = rootRef.current;\n if (!root) return;\n const idx = keysRef.current.indexOf(key);\n const src = root.querySelector<HTMLElement>(`[data-index=\"${idx}\"]`);\n if (!src) return;\n const r = src.getBoundingClientRect();\n grabOffsetYRef.current = pointerYRef.current - r.top;\n cloneLeftRef.current = r.left;\n dragHeightRef.current = r.height;\n const clone = src.cloneNode(true) as HTMLElement;\n clone.removeAttribute('data-index');\n clone.setAttribute('data-drag-clone', 'true');\n clone.setAttribute('aria-hidden', 'true');\n clone.classList.add(styles.virtualListDragClone);\n Object.assign(clone.style, {\n position: 'fixed',\n left: '0',\n top: '0',\n width: `${r.width}px`,\n height: `${r.height}px`,\n margin: '0',\n opacity: '1',\n pointerEvents: 'none',\n // Above the sticky header (z-index 2) and any focused row (z-index 1).\n zIndex: '3',\n background: 'var(--background)',\n boxShadow: 'var(--card-shadow)',\n borderRadius: 'var(--default-border-radius)',\n } as Partial<CSSStyleDeclaration>);\n // Appended inside the list so it inherits the active theme's CSS variables;\n // position:fixed keeps it in viewport coordinates regardless.\n root.appendChild(clone);\n dragCloneRef.current = clone;\n positionDragClone();\n }\n\n // Tear down any in-flight touch drag if the component unmounts mid-gesture.\n useEffect(() => endTouchDrag, [endTouchDrag]);\n\n // Either drag mode arms the same row gestures; the handlers above branch on\n // `treeReorder` for the differing target resolution / commit behaviour.\n const dragEnabled = reorderable || treeReorder;\n // Native mouse DnD is in play for this list. Row-level fallbacks that must\n // cover *every* row — swallowing the browser's own drop and context menu —\n // key off this, not off `draggable`, which in `dragHandle` mode is only ever\n // on the single armed row.\n const mouseDragEnabled = dragEnabled && !isCoarsePointer;\n\n function getRowDragProps(index: number, key: string | number): RowDragProps {\n // The drop indicator only renders on the row currently targeted. `before`/\n // `after` lines indent to the target's depth so they sit under where the\n // dropped content will start; `inside` highlights the whole row instead.\n const rowDrop = treeReorder && dropTarget?.key === key ? dropTarget.position : undefined;\n return {\n // Drives the row-wide grab cursor. With `dragHandle`, only the handle\n // initiates a drag, so the cursor belongs on the handle (styled by the\n // consumer), not across the whole row.\n reorderable: dragEnabled && !dragHandle,\n mouseDragEnabled,\n // In `dragHandle` mode the attribute only goes on the row the pointer has\n // armed, so rows stay text-selectable in Firefox the rest of the time.\n draggable: (mouseDragEnabled && (!dragHandle || key === armedKey)) || undefined,\n isDragging: dragEnabled && key === draggingKey,\n onMouseDown: dragEnabled && dragHandle ? (e) => handleRowMouseDown(key, e) : undefined,\n onMouseOver: dragEnabled && dragHandle ? (e) => handleRowMouseOver(key, e) : undefined,\n onMouseLeave: dragEnabled && dragHandle ? handleRowMouseLeave : undefined,\n onDragStart: dragEnabled ? (e) => handleReorderStart(key, e) : undefined,\n onDragOver: treeReorder\n ? (e) => handleTreeDragOver(index, e)\n : reorderable\n ? (e) => handleReorderOver(index, e)\n : undefined,\n onDragEnd: treeReorder ? handleTreeDragEnd : reorderable ? handleReorderEnd : undefined,\n onDrop: treeReorder ? handleTreeDrop : undefined,\n onTouchStart: dragEnabled ? (e) => handleRowTouchStart(key, e) : undefined,\n dropPosition: rowDrop,\n dropIndentPx: rowDrop ? (depths[index] ?? 0) * treeIndentPx : undefined,\n };\n }\n\n function consumeSuppressedClick(): boolean {\n if (suppressNextClickRef.current) {\n suppressNextClickRef.current = false;\n return true;\n }\n return false;\n }\n\n return { draggingKey, dragEnabled, getRowDragProps, consumeSuppressedClick };\n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,IAAqB,CAAC,GAAc,IAAQ,IAAc,IAAA,GACtE,WAAY,GAAe,IAAQ,EACnC,YAAa,GAAe,EAAc,GAAM,GAAmB,EAAK,CAAC,EAAI,IAAA,GAC7E,YAAa,GAAe,EAAc,GAAM,GAAmB,EAAK,CAAC,EAAI,IAAA,GAC7E,aAAc,GAAe,EAAa,GAAsB,IAAA,GAChE,YAAa,EAAe,GAAM,GAAmB,EAAK,CAAC,EAAI,IAAA,GAC/D,WAAY,EACP,GAAM,GAAmB,EAAO,CAAC,EAClC,EACG,GAAM,GAAkB,EAAO,CAAC,EACjC,IAAA,GACN,UAAW,EAAc,GAAoB,EAAc,GAAmB,IAAA,GAC9E,OAAQ,EAAc,GAAiB,IAAA,GACvC,aAAc,EAAe,GAAM,GAAoB,EAAK,CAAC,EAAI,IAAA,GACjE,aAAc,EACd,aAAc,GAAW,EAAO,IAAU,GAAK,EAAe,IAAA,EAChE,CACF,CAEA,SAAS,IAAkC,CAKzC,OAJI,EAAqB,SACvB,EAAqB,QAAU,GACxB,IAEF,EACT,CAEA,MAAO,CAAE,cAAa,cAAa,mBAAiB,yBAAuB,CAC7E"}
1
+ {"version":3,"file":"useRowDrag.mjs","names":[],"sources":["../../../../package/common/virtualList/useRowDrag.ts"],"sourcesContent":["import React, { useState, useRef, useEffect, useLayoutEffect, useCallback } from 'react';\n\nimport styles from './virtualList.module.pcss';\nimport { resolveReorderTarget, resolveTreeDropTarget, lastDescendantIndex } from './virtualList.utils';\nimport type { TreeDropPosition, TreeDropTarget } from './virtualList.types';\nimport type { ListViewportRect } from './useVirtualWindow';\n\ninterface UseRowDragArgs {\n reorderable: boolean;\n treeReorder: boolean;\n onReorder?: (fromIndex: number, toIndex: number) => void;\n onTreeDrop?: (dragKey: string | number, target: TreeDropTarget) => void;\n longPressDelay: number;\n dragHandle: boolean;\n treeIndentPx: number;\n /** Current flat ordering and depth tags (mouse handlers read these directly). */\n keys: (string | number)[];\n depths: number[];\n isGroupAt: (index: number) => boolean;\n rootRef: React.RefObject<HTMLDivElement | null>;\n /** Latest keys for async (touch / rAF) consumers — owned by useVirtualWindow. */\n keysRef: React.RefObject<(string | number)[]>;\n /** Where the list is on screen, which is not its own box once it rides a\n * scrollport — owned by useVirtualWindow, as is `scrollBy`. */\n getVisibleRect: () => ListViewportRect | null;\n scrollBy: (dy: number) => void;\n}\n\n/** The drag-related props the parent spreads onto a given row. */\nexport interface RowDragProps {\n reorderable: boolean;\n /** Native mouse DnD is active for the list (independent of which row is armed). */\n mouseDragEnabled: boolean;\n draggable: boolean | undefined;\n isDragging: boolean;\n onMouseDown: ((e: React.MouseEvent<HTMLDivElement>) => void) | undefined;\n onMouseOver: ((e: React.MouseEvent<HTMLDivElement>) => void) | undefined;\n onMouseLeave: ((e: React.MouseEvent<HTMLDivElement>) => void) | undefined;\n onDragStart: ((e: React.DragEvent<HTMLDivElement>) => void) | undefined;\n onDragOver: ((e: React.DragEvent<HTMLDivElement>) => void) | undefined;\n onDragEnd: (() => void) | undefined;\n onDrop: ((e: React.DragEvent<HTMLDivElement>) => void) | undefined;\n onTouchStart: ((e: React.TouchEvent<HTMLDivElement>) => void) | undefined;\n dropPosition: TreeDropPosition | undefined;\n dropIndentPx: number | undefined;\n}\n\ninterface UseRowDragResult {\n /** True while a row is being dragged (for the root reordering style). */\n draggingKey: string | number | null;\n /** Whether either drag mode is active. */\n dragEnabled: boolean;\n /** Drag props for the row at `index` / `key`. */\n getRowDragProps: (index: number, key: string | number) => RowDragProps;\n /** Returns true (and resets) if the next click should be swallowed (post-drag). */\n consumeSuppressedClick: () => boolean;\n}\n\n/**\n * Row drag-and-drop for both modes:\n * - `reorderable` (flat): native HTML5 drag on desktop; rows move live via\n * `onReorder` with midpoint hysteresis.\n * - `treeReorder`: a drop indicator (before/after/inside) is shown during the\n * drag and `onTreeDrop` fires once on release; dropping onto the dragged\n * node's own subtree is forbidden.\n * Touch uses a long-press → lifted-clone → pointer-move path with edge\n * auto-scroll. `dragHandle` restricts initiation to `[data-drag-handle]`.\n */\nexport function useRowDrag({\n reorderable,\n treeReorder,\n onReorder,\n onTreeDrop,\n longPressDelay,\n dragHandle,\n treeIndentPx,\n keys,\n depths,\n isGroupAt,\n rootRef,\n keysRef,\n getVisibleRect,\n scrollBy,\n}: UseRowDragArgs): UseRowDragResult {\n // The dragged item is tracked by its stable key (indices shift after each\n // live reorder); the ref drives the logic, the state drives the row's style.\n const dragKeyRef = useRef<string | number | null>(null);\n const [draggingKey, setDraggingKey] = useState<string | number | null>(null);\n // Tree-reorder drop indicator. Unlike flat reorder (which moves rows live),\n // tree mode shows where the drop will land and commits once on release.\n const [dropTarget, setDropTarget] = useState<TreeDropTarget | null>(null);\n const dropTargetRef = useRef<TreeDropTarget | null>(null);\n const onReorderRef = useRef(onReorder);\n const onTreeDropRef = useRef(onTreeDrop);\n const treeModeRef = useRef(treeReorder);\n const depthsRef = useRef<number[]>(depths);\n const isGroupAtRef = useRef<(i: number) => boolean>(isGroupAt);\n // When `dragHandle` is on, a mousedown sets this to whether it landed on a\n // `[data-drag-handle]` element, gating whether the ensuing dragstart is honoured.\n const dragFromHandleRef = useRef(true);\n // In `dragHandle` mode the `draggable` attribute is only on the row whose\n // handle the pointer is currently over (\"armed\"). A permanently `draggable`\n // row breaks mouse text selection (caret placement, double-click word select,\n // drag select) inside any child input in Firefox — see Mozilla bugs 739071 /\n // 800050 / 1189486. Arming on hover rather than on mousedown means the\n // attribute is already in place before the press, so the browser never has to\n // notice it appearing mid-gesture, and any pointer move re-derives it.\n const armedKeyRef = useRef<string | number | null>(null);\n const [armedKey, setArmedKeyState] = useState<string | number | null>(null);\n const longPressRef = useRef<number | null>(null);\n const touchActiveRef = useRef(false);\n const touchStartYRef = useRef<number | null>(null);\n const pointerXRef = useRef(0);\n const pointerYRef = useRef(0);\n const autoScrollRef = useRef<number | null>(null);\n const suppressNextClickRef = useRef(false);\n // Floating clone that follows the finger during a touch drag.\n const dragCloneRef = useRef<HTMLElement | null>(null);\n const grabOffsetYRef = useRef(0);\n const cloneLeftRef = useRef(0);\n const dragHeightRef = useRef(0);\n // The native `draggable` attribute (mouse DnD) makes a long-press start the\n // browser's own drag on touch devices, which hijacks our touch handlers. So\n // expose it only where the primary pointer is fine (mouse/trackpad); touch\n // devices use the touch handlers below instead.\n const [isCoarsePointer] = useState(() =>\n typeof window !== 'undefined' && typeof window.matchMedia === 'function'\n ? window.matchMedia('(pointer: coarse)').matches\n : false,\n );\n\n useLayoutEffect(() => {\n onReorderRef.current = onReorder;\n onTreeDropRef.current = onTreeDrop;\n treeModeRef.current = treeReorder;\n depthsRef.current = depths;\n dropTargetRef.current = dropTarget;\n isGroupAtRef.current = isGroupAt;\n });\n\n // ── Mouse / shared start ──────────────────────────────────────────────────\n\n /** Move the `draggable` attribute to `next` (or off entirely for `null`). */\n function arm(next: string | number | null) {\n // Arming exists purely to place the native `draggable` attribute, which is\n // never set on a coarse pointer (touch uses the handlers below instead). A\n // tap still synthesises mouseover/mousedown, so without this a touch device\n // would re-render the list on every handle tap to no effect whatsoever.\n if (isCoarsePointer) return;\n if (armedKeyRef.current === next) return; // mouseover fires constantly — no-op\n armedKeyRef.current = next;\n setArmedKeyState(next);\n }\n\n // Arm while the pointer rests on this row's handle, disarm as it moves off.\n // `buttons !== 0` means a press is already in progress: the pointer can drift\n // off the handle before the browser reaches its drag threshold, so hover is\n // ignored until release rather than disarming a drag that is about to start.\n function handleRowMouseOver(key: string | number, e: React.MouseEvent<HTMLDivElement>) {\n if (e.buttons !== 0) return;\n arm((e.target as HTMLElement).closest('[data-drag-handle]') ? key : null);\n }\n\n function handleRowMouseLeave(e: React.MouseEvent<HTMLDivElement>) {\n if (e.buttons !== 0) return;\n arm(null);\n }\n\n // With `dragHandle`, remember on mousedown whether the press landed on a\n // handle, so the dragstart that follows can be ignored if it didn't. Arming\n // here too covers a handle that came to sit under an already-stationary cursor\n // (the list scrolled), which produces no mouseover.\n function handleRowMouseDown(key: string | number, e: React.MouseEvent<HTMLDivElement>) {\n if (e.button !== 0) return; // only a primary press can begin a drag\n const fromHandle = !!(e.target as HTMLElement).closest('[data-drag-handle]');\n dragFromHandleRef.current = fromHandle;\n if (fromHandle) arm(key);\n }\n\n function handleReorderStart(key: string | number, e: React.DragEvent<HTMLDivElement>) {\n if (dragHandle && !dragFromHandleRef.current) {\n e.preventDefault(); // not started from a handle — let the row stay put\n return;\n }\n dragKeyRef.current = key;\n setDraggingKey(key);\n if (treeReorder) setDropTarget(null);\n }\n\n // ── Tree mode ─────────────────────────────────────────────────────────────\n\n /** Resolve the tree drop target for the row at `overIndex` under pointer `y`. */\n function computeTreeDrop(overIndex: number, y: number, rect: DOMRect): TreeDropTarget | null {\n const dragKey = dragKeyRef.current;\n if (dragKey == null) return null;\n const fromIndex = keys.indexOf(dragKey);\n // Forbid dropping onto the dragged node or anything in its own subtree.\n if (fromIndex !== -1 && overIndex >= fromIndex && overIndex <= lastDescendantIndex(fromIndex, depths)) {\n return null;\n }\n const position = resolveTreeDropTarget(y, rect.top, rect.height, isGroupAt(overIndex));\n return { key: keys[overIndex], position };\n }\n\n function handleTreeDragOver(overIndex: number, e: React.DragEvent<HTMLDivElement>) {\n e.preventDefault(); // allow the drop\n const rect = e.currentTarget.getBoundingClientRect();\n const next = computeTreeDrop(overIndex, e.clientY, rect);\n setDropTarget((prev) => (prev?.key === next?.key && prev?.position === next?.position ? prev : next));\n }\n\n function commitTreeDrop() {\n const dragKey = dragKeyRef.current;\n const target = dropTargetRef.current;\n if (dragKey != null && target && target.key !== dragKey) onTreeDrop?.(dragKey, target);\n }\n\n function handleTreeDrop(e: React.DragEvent<HTMLDivElement>) {\n e.preventDefault();\n commitTreeDrop();\n setDropTarget(null);\n dragKeyRef.current = null;\n setDraggingKey(null);\n arm(null);\n }\n\n function handleTreeDragEnd() {\n // Fires after `drop` (or on its own when released off a valid target).\n setDropTarget(null);\n dragKeyRef.current = null;\n setDraggingKey(null);\n arm(null);\n }\n\n // ── Flat mode ─────────────────────────────────────────────────────────────\n\n function handleReorderOver(overIndex: number, e: React.DragEvent<HTMLDivElement>) {\n e.preventDefault(); // allow the drop\n const dragKey = dragKeyRef.current;\n if (dragKey == null) return;\n const fromIndex = keys.indexOf(dragKey);\n // Midpoint hysteresis (see resolveReorderTarget): a move only happens once\n // the pointer crosses the centre of the row it's over. After a swap the\n // dragged row sits under the cursor, so moving again needs real pointer\n // travel — this stops the oscillation that made dragging feel jumpy.\n const rect = e.currentTarget.getBoundingClientRect();\n const target = resolveReorderTarget(fromIndex, overIndex, e.clientY, rect.top, rect.height);\n if (target != null) onReorder?.(fromIndex, target);\n }\n\n function handleReorderEnd() {\n dragKeyRef.current = null;\n setDraggingKey(null);\n arm(null);\n }\n\n // ── Touch reordering (long-press to arm, then drag) ──────────────────────────\n // These handlers run from window listeners during a touch drag, so they read\n // mutable state from refs and are stable across renders.\n\n const reorderAtPoint = useCallback(\n (x: number) => {\n const dragKey = dragKeyRef.current;\n const root = rootRef.current;\n if (dragKey == null || !root) return;\n // Reorder against the centre of the lifted clone, not the raw finger — the\n // finger sits below the clone's top by the grab offset, so using it would\n // make the top (and bottom) rows unreachable. The clone is what the user\n // aims with, so match it.\n const y = dragCloneRef.current\n ? pointerYRef.current - grabOffsetYRef.current + dragHeightRef.current / 2\n : pointerYRef.current;\n const el = document.elementFromPoint(x, y) as HTMLElement | null;\n const rowEl = el && root.contains(el) ? el.closest<HTMLElement>('[data-index]') : null;\n if (!rowEl) return;\n const overIndex = Number(rowEl.dataset.index);\n if (Number.isNaN(overIndex)) return;\n const fromIndex = keysRef.current.indexOf(dragKey);\n const rect = rowEl.getBoundingClientRect();\n if (treeModeRef.current) {\n // Tree mode: don't move live — just track where the drop will land.\n const ks = keysRef.current;\n const ds = depthsRef.current;\n if (fromIndex !== -1 && overIndex >= fromIndex && overIndex <= lastDescendantIndex(fromIndex, ds)) {\n setDropTarget(null);\n return;\n }\n const position = resolveTreeDropTarget(y, rect.top, rect.height, isGroupAtRef.current(overIndex));\n const next: TreeDropTarget = { key: ks[overIndex], position };\n setDropTarget((prev) => (prev?.key === next.key && prev?.position === next.position ? prev : next));\n return;\n }\n const target = resolveReorderTarget(fromIndex, overIndex, y, rect.top, rect.height);\n if (target != null) onReorderRef.current?.(fromIndex, target);\n },\n [rootRef, keysRef],\n );\n\n // Keep the floating clone glued under the finger (same grab point).\n const positionDragClone = useCallback(() => {\n const clone = dragCloneRef.current;\n if (!clone) return;\n clone.style.transform = `translate(${cloneLeftRef.current}px, ${pointerYRef.current - grabOffsetYRef.current}px)`;\n }, []);\n\n // While the finger sits near a top/bottom edge (and within the list's width),\n // scroll the list and keep reordering against the rows now passing under it.\n const autoScrollTick = useCallback(() => {\n const rect = touchActiveRef.current ? getVisibleRect() : null;\n if (!rect) {\n autoScrollRef.current = null;\n return;\n }\n const x = pointerXRef.current;\n const y = pointerYRef.current;\n const EDGE = 48;\n let dy = 0;\n // Only auto-scroll while the finger is actually over the list — moving it\n // outside (any direction) stops the scroll instead of running away; pinning\n // the dragged row keeps touch events alive so it resumes when you come back.\n const inside = x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;\n if (inside) {\n if (y < rect.top + EDGE) dy = -Math.min(18, Math.ceil((rect.top + EDGE - y) / 3));\n else if (y > rect.bottom - EDGE) dy = Math.min(18, Math.ceil((y - (rect.bottom - EDGE)) / 3));\n }\n if (dy !== 0) {\n scrollBy(dy);\n reorderAtPoint(x);\n }\n autoScrollRef.current = requestAnimationFrame(autoScrollTick);\n }, [reorderAtPoint, getVisibleRect, scrollBy]);\n\n const endTouchDrag = useCallback(() => {\n if (longPressRef.current != null) {\n clearTimeout(longPressRef.current);\n longPressRef.current = null;\n }\n window.removeEventListener('touchmove', handleTouchMove);\n window.removeEventListener('touchend', endTouchDrag);\n window.removeEventListener('touchcancel', endTouchDrag);\n if (autoScrollRef.current != null) {\n cancelAnimationFrame(autoScrollRef.current);\n autoScrollRef.current = null;\n }\n if (dragCloneRef.current) {\n dragCloneRef.current.remove();\n dragCloneRef.current = null;\n }\n // Restore native scrolling that was locked for the duration of the drag.\n document.body.style.touchAction = '';\n document.body.style.overscrollBehavior = '';\n if (touchActiveRef.current) {\n // A real drag happened — swallow the click the browser fires afterwards\n // so it doesn't, e.g., toggle row selection.\n suppressNextClickRef.current = true;\n setTimeout(() => {\n suppressNextClickRef.current = false;\n }, 350);\n // Tree mode commits the pending drop on release (flat mode already moved\n // rows live during the drag, so there's nothing to commit here).\n if (treeModeRef.current) {\n const dk = dragKeyRef.current;\n const target = dropTargetRef.current;\n if (dk != null && target && target.key !== dk) onTreeDropRef.current?.(dk, target);\n }\n }\n setDropTarget(null);\n touchActiveRef.current = false;\n touchStartYRef.current = null;\n dragKeyRef.current = null;\n setDraggingKey(null);\n // handleTouchMove and endTouchDrag remove each other’s listeners, so neither can list\n // the other without a cycle.\n // oxlint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const handleTouchMove = useCallback(\n (e: TouchEvent) => {\n const t = e.touches[0];\n if (!t) return;\n pointerXRef.current = t.clientX;\n pointerYRef.current = t.clientY;\n if (!touchActiveRef.current) {\n // Before the long-press fires: if the finger travels, the user means to\n // scroll, so disarm and let the browser handle it (we don't preventDefault).\n const sy = touchStartYRef.current;\n if (sy != null && Math.abs(t.clientY - sy) > 10 && longPressRef.current != null) {\n clearTimeout(longPressRef.current);\n longPressRef.current = null;\n }\n return;\n }\n // Non-passive listener: preventDefault cancels the native scroll for this\n // gesture — the only reliable way once touch-action has been latched at\n // touchstart. This is what makes the drag actually move on touch devices.\n if (e.cancelable) e.preventDefault();\n positionDragClone();\n reorderAtPoint(t.clientX);\n },\n [reorderAtPoint, positionDragClone],\n );\n\n function handleRowTouchStart(key: string | number, e: React.TouchEvent<HTMLDivElement>) {\n if (!reorderable && !treeReorder) return;\n // With a drag handle, only a press that starts on it arms the drag, so the\n // rest of the row stays free for tapping/typing into inputs.\n if (dragHandle && !(e.target as HTMLElement).closest('[data-drag-handle]')) return;\n if (longPressRef.current != null || touchActiveRef.current) return; // ignore extra fingers\n const t = e.touches[0];\n if (!t) return;\n touchStartYRef.current = t.clientY;\n pointerXRef.current = t.clientX;\n pointerYRef.current = t.clientY;\n window.addEventListener('touchmove', handleTouchMove, { passive: false });\n window.addEventListener('touchend', endTouchDrag);\n window.addEventListener('touchcancel', endTouchDrag);\n longPressRef.current = window.setTimeout(() => {\n longPressRef.current = null;\n touchActiveRef.current = true;\n dragKeyRef.current = key;\n setDraggingKey(key);\n navigator.vibrate?.(10);\n // Lock native scrolling for the whole gesture — relying on per-move\n // preventDefault isn't enough once the finger leaves and re-enters the\n // list (the browser commits to a scroll and ignores it). We do all the\n // scrolling ourselves via autoScrollTick.\n document.body.style.touchAction = 'none';\n document.body.style.overscrollBehavior = 'none';\n createDragClone(key);\n if (autoScrollRef.current == null) autoScrollRef.current = requestAnimationFrame(autoScrollTick);\n }, longPressDelay);\n }\n\n // Build a floating copy of the picked-up row that tracks the finger, so the\n // drag has a visible \"lifted\" element (the original row stays dimmed in place\n // as a drop placeholder).\n function createDragClone(key: string | number) {\n const root = rootRef.current;\n if (!root) return;\n const idx = keysRef.current.indexOf(key);\n const src = root.querySelector<HTMLElement>(`[data-index=\"${idx}\"]`);\n if (!src) return;\n const r = src.getBoundingClientRect();\n grabOffsetYRef.current = pointerYRef.current - r.top;\n cloneLeftRef.current = r.left;\n dragHeightRef.current = r.height;\n const clone = src.cloneNode(true) as HTMLElement;\n clone.removeAttribute('data-index');\n clone.setAttribute('data-drag-clone', 'true');\n clone.setAttribute('aria-hidden', 'true');\n clone.classList.add(styles.virtualListDragClone);\n Object.assign(clone.style, {\n position: 'fixed',\n left: '0',\n top: '0',\n width: `${r.width}px`,\n height: `${r.height}px`,\n margin: '0',\n opacity: '1',\n pointerEvents: 'none',\n // Above the sticky header (z-index 2) and any focused row (z-index 1).\n zIndex: '3',\n background: 'var(--background)',\n boxShadow: 'var(--card-shadow)',\n borderRadius: 'var(--default-border-radius)',\n } as Partial<CSSStyleDeclaration>);\n // Appended inside the list so it inherits the active theme's CSS variables;\n // position:fixed keeps it in viewport coordinates regardless.\n root.appendChild(clone);\n dragCloneRef.current = clone;\n positionDragClone();\n }\n\n // Tear down any in-flight touch drag if the component unmounts mid-gesture.\n useEffect(() => endTouchDrag, [endTouchDrag]);\n\n // Either drag mode arms the same row gestures; the handlers above branch on\n // `treeReorder` for the differing target resolution / commit behaviour.\n const dragEnabled = reorderable || treeReorder;\n // Native mouse DnD is in play for this list. Row-level fallbacks that must\n // cover *every* row — swallowing the browser's own drop and context menu —\n // key off this, not off `draggable`, which in `dragHandle` mode is only ever\n // on the single armed row.\n const mouseDragEnabled = dragEnabled && !isCoarsePointer;\n\n function getRowDragProps(index: number, key: string | number): RowDragProps {\n // The drop indicator only renders on the row currently targeted. `before`/\n // `after` lines indent to the target's depth so they sit under where the\n // dropped content will start; `inside` highlights the whole row instead.\n const rowDrop = treeReorder && dropTarget?.key === key ? dropTarget.position : undefined;\n return {\n // Drives the row-wide grab cursor. With `dragHandle`, only the handle\n // initiates a drag, so the cursor belongs on the handle (styled by the\n // consumer), not across the whole row.\n reorderable: dragEnabled && !dragHandle,\n mouseDragEnabled,\n // In `dragHandle` mode the attribute only goes on the row the pointer has\n // armed, so rows stay text-selectable in Firefox the rest of the time.\n draggable: (mouseDragEnabled && (!dragHandle || key === armedKey)) || undefined,\n isDragging: dragEnabled && key === draggingKey,\n onMouseDown: dragEnabled && dragHandle ? (e) => handleRowMouseDown(key, e) : undefined,\n onMouseOver: dragEnabled && dragHandle ? (e) => handleRowMouseOver(key, e) : undefined,\n onMouseLeave: dragEnabled && dragHandle ? handleRowMouseLeave : undefined,\n onDragStart: dragEnabled ? (e) => handleReorderStart(key, e) : undefined,\n onDragOver: treeReorder\n ? (e) => handleTreeDragOver(index, e)\n : reorderable\n ? (e) => handleReorderOver(index, e)\n : undefined,\n onDragEnd: treeReorder ? handleTreeDragEnd : reorderable ? handleReorderEnd : undefined,\n onDrop: treeReorder ? handleTreeDrop : undefined,\n onTouchStart: dragEnabled ? (e) => handleRowTouchStart(key, e) : undefined,\n dropPosition: rowDrop,\n dropIndentPx: rowDrop ? (depths[index] ?? 0) * treeIndentPx : undefined,\n };\n }\n\n function consumeSuppressedClick(): boolean {\n if (suppressNextClickRef.current) {\n suppressNextClickRef.current = false;\n return true;\n }\n return false;\n }\n\n return { draggingKey, dragEnabled, getRowDragProps, consumeSuppressedClick };\n}\n"],"mappings":"0QAoEA,SAAgB,EAAW,CACzB,cACA,cACA,YACA,aACA,kBACA,aACA,gBACA,OACA,SACA,YACA,UACA,UACA,iBACA,YACmC,CAGnC,IAAM,EAAa,EAA+B,IAAI,EAChD,CAAC,EAAa,GAAkB,EAAiC,IAAI,EAGrE,CAAC,EAAY,GAAiB,EAAgC,IAAI,EAClE,EAAgB,EAA8B,IAAI,EAClD,EAAe,EAAO,CAAS,EAC/B,EAAgB,EAAO,CAAU,EACjC,EAAc,EAAO,CAAW,EAChC,EAAY,EAAiB,CAAM,EACnC,EAAe,EAA+B,CAAS,EAGvD,EAAoB,EAAO,EAAI,EAQ/B,EAAc,EAA+B,IAAI,EACjD,CAAC,GAAU,IAAoB,EAAiC,IAAI,EACpE,EAAe,EAAsB,IAAI,EACzC,EAAiB,EAAO,EAAK,EAC7B,EAAiB,EAAsB,IAAI,EAC3C,EAAc,EAAO,CAAC,EACtB,EAAc,EAAO,CAAC,EACtB,EAAgB,EAAsB,IAAI,EAC1C,EAAuB,EAAO,EAAK,EAEnC,EAAe,EAA2B,IAAI,EAC9C,EAAiB,EAAO,CAAC,EACzB,EAAe,EAAO,CAAC,EACvB,EAAgB,EAAO,CAAC,EAKxB,CAAC,GAAmB,MACxB,OAAO,OAAW,KAAe,OAAO,OAAO,YAAe,YAC1D,OAAO,WAAW,mBAAmB,CAAC,CAAC,OAE7C,EAEA,MAAsB,CACpB,EAAa,QAAU,EACvB,EAAc,QAAU,EACxB,EAAY,QAAU,EACtB,EAAU,QAAU,EACpB,EAAc,QAAU,EACxB,EAAa,QAAU,CACzB,CAAC,EAKD,SAAS,EAAI,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AAC,EAI5C,IAAM,EAAc,GAAe,EAK7B,EAAmB,GAAe,CAAC,EAEzC,SAAS,GAAgB,EAAe,EAAoC,CAI1E,IAAM,EAAU,GAAe,GAAY,MAAQ,EAAM,EAAW,SAAW,IAAA,GAC/E,MAAO,CAIL,YAAa,GAAe,CAAC,EAC7B,mBAGA,UAAY,IAAqB,CAAC,GAAc,IAAQ,KAAc,IAAA,GACtE,WAAY,GAAe,IAAQ,EACnC,YAAa,GAAe,EAAc,GAAM,GAAmB,EAAK,CAAC,EAAI,IAAA,GAC7E,YAAa,GAAe,EAAc,GAAM,GAAmB,EAAK,CAAC,EAAI,IAAA,GAC7E,aAAc,GAAe,EAAa,GAAsB,IAAA,GAChE,YAAa,EAAe,GAAM,GAAmB,EAAK,CAAC,EAAI,IAAA,GAC/D,WAAY,EACP,GAAM,GAAmB,EAAO,CAAC,EAClC,EACG,GAAM,GAAkB,EAAO,CAAC,EACjC,IAAA,GACN,UAAW,EAAc,GAAoB,EAAc,GAAmB,IAAA,GAC9E,OAAQ,EAAc,GAAiB,IAAA,GACvC,aAAc,EAAe,GAAM,GAAoB,EAAK,CAAC,EAAI,IAAA,GACjE,aAAc,EACd,aAAc,GAAW,EAAO,IAAU,GAAK,GAAe,IAAA,EAChE,CACF,CAEA,SAAS,IAAkC,CAKzC,OAJI,EAAqB,SACvB,EAAqB,QAAU,GACxB,IAEF,EACT,CAEA,MAAO,CAAE,cAAa,cAAa,mBAAiB,yBAAuB,CAC7E"}
@@ -1,2 +1,2 @@
1
- "use client";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};
1
+ "use client";import{ROW_ENTER_SELECTOR as e,ROW_FOCUSABLE_SELECTOR as t,findStartIndex as n}from"./virtualList.utils.mjs";import{useLayoutEffect as r,useRef as i,useState as a}from"react";function o({enabled:o,tabAcrossRows:s,rowCount:c,offsets:l,rootRef:u,headerRef:d,getVisibleSlice:f,viewportHeight:p,scrollToIndex:m,initialIndex:h,multiSelect:g,onActivate:_,onToggleSelect:v}){let[y,b]=a(h),[x,S]=a(-1),C=i(l);C.current=l;let w=o&&c>0?Math.min(Math.max(y,0),c-1):-1;w>=0&&w!==y&&b(w);let T=w>=0;function E(e){let t=d.current?.offsetHeight??0,n=C.current[e]??0,r=C.current[e+1]??n,{top:i,height:a}=f();n<i+t?m(e,{align:`start`}):r>i+a&&m(e,{align:`end`})}function D(e){let t=Math.max(0,Math.min(e,c-1));b(t),E(t)}function O(e){let t=Math.max(0,p-(d.current?.offsetHeight??0)),r=n(C.current,(C.current[e]??0)+t,c);return Math.max(1,r-e)}function k(e){return u.current?.querySelector(`[data-index="${e}"]`)??null}function A(t){let n=k(t)?.querySelector(e);return n?(S(t),n.focus(),!0):!1}let j=i(null),M=i(!1);r(()=>{let t=j.current;if(!t)return;j.current=null;let n=k(t.index)?.querySelectorAll(e);if(n?.length){(t.edge===`first`?n[0]:n[n.length-1]).focus();return}let r=t.index+(t.edge===`first`?1:-1);if(r>=0&&r<c){j.current={index:r,edge:t.edge},S(r),E(r);return}S(-1),M.current=T&&t.edge===`first`,T&&u.current?.focus()});function N(e){let t=e?.closest?.(`[data-index]`),n=Number(t?.dataset.index);return Number.isFinite(n)?n:-1}function P(e){if(e.target===e.currentTarget)return;let t=N(e.target);t<0||(S(t),b(t))}function F(e){e.currentTarget.contains(e.relatedTarget)||(M.current=!1),N(e.relatedTarget)!==x&&S(-1)}function I(e){if(e.key!==`Escape`||e.defaultPrevented||!T)return;let t=N(e.target);t>=0&&b(t),S(-1),u.current?.focus(),e.preventDefault()}function L(e){if(!s||e.key!==`Tab`||e.defaultPrevented||e.altKey||e.ctrlKey||e.metaKey)return;let n=N(e.target);if(n<0)return;let r=k(n)?.querySelectorAll(t);if(!r?.length)return;let i=Array.prototype.indexOf.call(r,e.target);if(i<0)return;let a=e.shiftKey;if(a?i>0:i<r.length-1)return;let o=a?n-1:n+1;o<0||o>=c||(e.preventDefault(),S(o),E(o),j.current={index:o,edge:a?`last`:`first`})}function R(e){if(e.target!==e.currentTarget){L(e),I(e);return}if(!T||e.defaultPrevented)return;let t=M.current;switch(M.current=!1,e.key){case`ArrowDown`:D(w+1);break;case`ArrowUp`:D(w-1);break;case`Home`:D(0);break;case`End`:D(c-1);break;case`PageDown`:D(w+O(w));break;case`PageUp`:D(w-O(Math.max(0,w-1)));break;case`Enter`:if(_)_(w);else if(!A(w))return;break;case`F2`:if(!A(w))return;break;case`Tab`:if(!s||e.shiftKey||t||!A(w))return;break;case` `:if(!g)return;v(w);break;default:return}e.preventDefault()}if(!T&&!s)return{activeIndex:w,enteredIndex:-1,setActiveIndex:b,containerProps:{}};let z={onKeyDown:R,onFocus:P,onBlur:F};return T&&(z.tabIndex=0),{activeIndex:w,enteredIndex:x,setActiveIndex:b,containerProps:z}}export{o as useRowNavigation};
2
2
  //# sourceMappingURL=useRowNavigation.mjs.map
@@ -1 +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":"2IAqDA,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,U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AAG,EAAS,CAAQ,EACpC,EAAgB,EAAE,EAClB,EAAQ,SAAS,MAAM,EACvB,EAAM,eAAe,CACvB,CAEA,SAAS,EAAc,EAA4B,CAEjD,GAAI,EAAM,SAAW,EAAM,cAAe,CACxC,EAAc,CAAK,EACnB,MACF,CACA,OAAQ,EAAM,IAAd,CACE,IAAK,YACH,EAAO,EAAc,CAAC,EACtB,MACF,IAAK,UACH,EAAO,EAAc,CAAC,EACtB,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"}
1
+ {"version":3,"file":"useRowNavigation.mjs","names":[],"sources":["../../../../package/common/virtualList/useRowNavigation.ts"],"sourcesContent":["import React, { useLayoutEffect, useRef, useState } from 'react';\n\nimport { findStartIndex, ROW_ENTER_SELECTOR, ROW_FOCUSABLE_SELECTOR } from './virtualList.utils';\nimport type { VirtualListScrollOptions } from './virtualList.types';\nimport type { VisibleSlice } from './useVirtualWindow';\n\ninterface UseRowNavigationArgs {\n enabled: boolean;\n tabAcrossRows: 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 /** Read live: a held arrow key moves the slice faster than the state commits. */\n getVisibleSlice: () => VisibleSlice;\n /** The whole scrollport, which is what one PageDown covers. */\n viewportHeight: number;\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 *\n * `tabAcrossRows` adds the second pair, Tab and Shift+Tab, which the browser\n * cannot carry across a row boundary itself: the next row may not be in the DOM\n * when it looks for the next stop.\n */\nexport function useRowNavigation({\n enabled,\n tabAcrossRows,\n rowCount,\n offsets,\n rootRef,\n headerRef,\n getVisibleSlice,\n viewportHeight,\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 const navigable = activeIndex >= 0;\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 headerHeight = headerRef.current?.offsetHeight ?? 0;\n const rowTop = offsetsRef.current[target] ?? 0;\n const rowBottom = offsetsRef.current[target + 1] ?? rowTop;\n const { top, height } = getVisibleSlice();\n if (rowTop < top + headerHeight) scrollToIndex(target, { align: 'start' });\n else if (rowBottom > top + height) 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 usable = Math.max(0, viewportHeight - (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 function rowElement(target: number): HTMLElement | null {\n return rootRef.current?.querySelector<HTMLElement>(`[data-index=\"${target}\"]`) ?? null;\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 focusable = rowElement(target)?.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 // A row reached by Tab may not be in the DOM yet: entering it is what pins it\n // there, and that only takes effect on the next commit.\n const pendingFocusRef = useRef<{ index: number; edge: 'first' | 'last' } | null>(null);\n // Set when Tab ran out of rows to land in, so the next one is left to the browser.\n const releaseTabRef = useRef(false);\n // The chain of updates below is bounded: each pass clears the ref and moves one\n // row closer to an end of the list.\n // oxlint-disable-next-line react-hooks/exhaustive-deps\n useLayoutEffect(() => {\n const pending = pendingFocusRef.current;\n if (!pending) return;\n // Cleared whether or not the row was found: the commit that set this renders\n // it, so a second attempt at the same row would be a later commit stealing\n // the focus.\n pendingFocusRef.current = null;\n const focusables = rowElement(pending.index)?.querySelectorAll<HTMLElement>(ROW_ENTER_SELECTOR);\n if (focusables?.length) {\n (pending.edge === 'first' ? focusables[0] : focusables[focusables.length - 1]).focus();\n return;\n }\n // The Tab that got here was already prevented, so a row with nothing to focus\n // must not swallow it.\n const next = pending.index + (pending.edge === 'first' ? 1 : -1);\n if (next >= 0 && next < rowCount) {\n pendingFocusRef.current = { index: next, edge: pending.edge };\n setEnteredIndex(next);\n revealRow(next);\n return;\n }\n setEnteredIndex(-1);\n // Backwards needs no release: Shift+Tab off the list's own stop already leaves.\n releaseTabRef.current = navigable && pending.edge === 'first';\n if (navigable) rootRef.current?.focus();\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 // A release only holds while the list keeps the focus. `contains` counts the\n // list itself, which is where the release puts the focus in the first place.\n if (!event.currentTarget.contains(event.relatedTarget)) releaseTabRef.current = false;\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 || !navigable) 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 /**\n * Only the row's last control (first, going back) is taken over: everywhere\n * else the browser's order is already right, and at the ends of the list Tab\n * is left alone so it can leave.\n */\n function handleTabKey(event: React.KeyboardEvent): void {\n if (!tabAcrossRows || event.key !== 'Tab' || event.defaultPrevented) return;\n if (event.altKey || event.ctrlKey || event.metaKey) return;\n const rowIndex = rowIndexOf(event.target);\n if (rowIndex < 0) return;\n const focusables = rowElement(rowIndex)?.querySelectorAll<HTMLElement>(ROW_FOCUSABLE_SELECTOR);\n if (!focusables?.length) return;\n const at = Array.prototype.indexOf.call(focusables, event.target);\n if (at < 0) return;\n const back = event.shiftKey;\n if (back ? at > 0 : at < focusables.length - 1) return;\n const target = back ? rowIndex - 1 : rowIndex + 1;\n if (target < 0 || target >= rowCount) return;\n event.preventDefault();\n // The active row follows the focus, through `handleFocus`, so that it stays\n // where the user is when the focus never lands.\n setEnteredIndex(target);\n revealRow(target);\n pendingFocusRef.current = { index: target, edge: back ? 'last' : 'first' };\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 handleTabKey(event);\n handleExitKey(event);\n return;\n }\n // The consumer's own handler ran first and may have taken the key, which is\n // what `handleTabKey` and `handleExitKey` already check for.\n if (!navigable || event.defaultPrevented) return;\n const releasing = releaseTabRef.current;\n releaseTabRef.current = false;\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 'Tab':\n // The list's own tab stop is in front of rows whose controls are all\n // parked, so without this Tab would step over every one of them. Which is\n // the point once `releasing` says Tab has run out of rows to land in.\n if (!tabAcrossRows || event.shiftKey || releasing || !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 (!navigable && !tabAcrossRows)\n return { activeIndex, enteredIndex: -1, setActiveIndex: setIndex, containerProps: {} };\n const containerProps: UseRowNavigationResult['containerProps'] = {\n onKeyDown: handleKeyDown,\n onFocus: handleFocus,\n onBlur: handleBlur,\n };\n // Without arrow navigation the list is not a composite widget and must not take\n // a stop of its own. The key is left out rather than set to `undefined`, which\n // would erase a `tabIndex` the consumer passed.\n if (navigable) containerProps.tabIndex = 0;\n return { activeIndex, enteredIndex, setActiveIndex: setIndex, containerProps };\n}\n"],"mappings":"4LA+DA,SAAgB,EAAiB,CAC/B,UACA,gBACA,WACA,UACA,UACA,YACA,kBACA,iBACA,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,EACn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