@hozo/primitives 0.1.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 (218) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +54 -0
  3. package/dist/flat-list.native.d.ts +17 -0
  4. package/dist/flat-list.native.d.ts.map +1 -0
  5. package/dist/flat-list.native.js +89 -0
  6. package/dist/flat-list.native.js.map +1 -0
  7. package/dist/foundation.d.ts +104 -0
  8. package/dist/foundation.d.ts.map +1 -0
  9. package/dist/foundation.js +115 -0
  10. package/dist/foundation.js.map +1 -0
  11. package/dist/foundation.native.d.ts +59 -0
  12. package/dist/foundation.native.d.ts.map +1 -0
  13. package/dist/foundation.native.js +40 -0
  14. package/dist/foundation.native.js.map +1 -0
  15. package/dist/generated/animated.d.ts +2 -0
  16. package/dist/generated/animated.d.ts.map +1 -0
  17. package/dist/generated/animated.js +3 -0
  18. package/dist/generated/animated.js.map +1 -0
  19. package/dist/generated/backdrop-filter.d.ts +2 -0
  20. package/dist/generated/backdrop-filter.d.ts.map +1 -0
  21. package/dist/generated/backdrop-filter.js +3 -0
  22. package/dist/generated/backdrop-filter.js.map +1 -0
  23. package/dist/generated/container.d.ts +2 -0
  24. package/dist/generated/container.d.ts.map +1 -0
  25. package/dist/generated/container.js +3 -0
  26. package/dist/generated/container.js.map +1 -0
  27. package/dist/generated/flat-list.d.ts +2 -0
  28. package/dist/generated/flat-list.d.ts.map +1 -0
  29. package/dist/generated/flat-list.js +2 -0
  30. package/dist/generated/flat-list.js.map +1 -0
  31. package/dist/generated/flat-list.native.d.ts +3 -0
  32. package/dist/generated/flat-list.native.d.ts.map +1 -0
  33. package/dist/generated/flat-list.native.js +2 -0
  34. package/dist/generated/flat-list.native.js.map +1 -0
  35. package/dist/generated/grid.d.ts +3 -0
  36. package/dist/generated/grid.d.ts.map +1 -0
  37. package/dist/generated/grid.js +4 -0
  38. package/dist/generated/grid.js.map +1 -0
  39. package/dist/generated/link.d.ts +2 -0
  40. package/dist/generated/link.d.ts.map +1 -0
  41. package/dist/generated/link.js +2 -0
  42. package/dist/generated/link.js.map +1 -0
  43. package/dist/generated/link.native.d.ts +2 -0
  44. package/dist/generated/link.native.d.ts.map +1 -0
  45. package/dist/generated/link.native.js +2 -0
  46. package/dist/generated/link.native.js.map +1 -0
  47. package/dist/generated/pressable.d.ts +2 -0
  48. package/dist/generated/pressable.d.ts.map +1 -0
  49. package/dist/generated/pressable.js +2 -0
  50. package/dist/generated/pressable.js.map +1 -0
  51. package/dist/generated/pressable.native.d.ts +2 -0
  52. package/dist/generated/pressable.native.d.ts.map +1 -0
  53. package/dist/generated/pressable.native.js +2 -0
  54. package/dist/generated/pressable.native.js.map +1 -0
  55. package/dist/generated/refresh-control.d.ts +2 -0
  56. package/dist/generated/refresh-control.d.ts.map +1 -0
  57. package/dist/generated/refresh-control.js +2 -0
  58. package/dist/generated/refresh-control.js.map +1 -0
  59. package/dist/generated/refresh-control.native.d.ts +2 -0
  60. package/dist/generated/refresh-control.native.d.ts.map +1 -0
  61. package/dist/generated/refresh-control.native.js +2 -0
  62. package/dist/generated/refresh-control.native.js.map +1 -0
  63. package/dist/generated/scroll-view.d.ts +2 -0
  64. package/dist/generated/scroll-view.d.ts.map +1 -0
  65. package/dist/generated/scroll-view.js +2 -0
  66. package/dist/generated/scroll-view.js.map +1 -0
  67. package/dist/generated/scroll-view.native.d.ts +2 -0
  68. package/dist/generated/scroll-view.native.d.ts.map +1 -0
  69. package/dist/generated/scroll-view.native.js +2 -0
  70. package/dist/generated/scroll-view.native.js.map +1 -0
  71. package/dist/generated/spaced.d.ts +2 -0
  72. package/dist/generated/spaced.d.ts.map +1 -0
  73. package/dist/generated/spaced.js +3 -0
  74. package/dist/generated/spaced.js.map +1 -0
  75. package/dist/generated/text-input.d.ts +2 -0
  76. package/dist/generated/text-input.d.ts.map +1 -0
  77. package/dist/generated/text-input.js +2 -0
  78. package/dist/generated/text-input.js.map +1 -0
  79. package/dist/generated/text-input.native.d.ts +2 -0
  80. package/dist/generated/text-input.native.d.ts.map +1 -0
  81. package/dist/generated/text-input.native.js +2 -0
  82. package/dist/generated/text-input.native.js.map +1 -0
  83. package/dist/generated/text-size.d.ts +2 -0
  84. package/dist/generated/text-size.d.ts.map +1 -0
  85. package/dist/generated/text-size.js +3 -0
  86. package/dist/generated/text-size.js.map +1 -0
  87. package/dist/generated/text.d.ts +2 -0
  88. package/dist/generated/text.d.ts.map +1 -0
  89. package/dist/generated/text.js +5 -0
  90. package/dist/generated/text.js.map +1 -0
  91. package/dist/generated/view.d.ts +2 -0
  92. package/dist/generated/view.d.ts.map +1 -0
  93. package/dist/generated/view.js +2 -0
  94. package/dist/generated/view.js.map +1 -0
  95. package/dist/generated/view.native.d.ts +2 -0
  96. package/dist/generated/view.native.d.ts.map +1 -0
  97. package/dist/generated/view.native.js +2 -0
  98. package/dist/generated/view.native.js.map +1 -0
  99. package/dist/index.d.ts +188 -0
  100. package/dist/index.d.ts.map +1 -0
  101. package/dist/index.js +718 -0
  102. package/dist/index.js.map +1 -0
  103. package/dist/index.native.d.ts +22 -0
  104. package/dist/index.native.d.ts.map +1 -0
  105. package/dist/index.native.js +8 -0
  106. package/dist/index.native.js.map +1 -0
  107. package/dist/link.d.ts +320 -0
  108. package/dist/link.d.ts.map +1 -0
  109. package/dist/link.js +69 -0
  110. package/dist/link.js.map +1 -0
  111. package/dist/link.native.d.ts +33 -0
  112. package/dist/link.native.d.ts.map +1 -0
  113. package/dist/link.native.js +44 -0
  114. package/dist/link.native.js.map +1 -0
  115. package/dist/pressable.d.ts +65 -0
  116. package/dist/pressable.d.ts.map +1 -0
  117. package/dist/pressable.js +202 -0
  118. package/dist/pressable.js.map +1 -0
  119. package/dist/pressable.native.d.ts +55 -0
  120. package/dist/pressable.native.d.ts.map +1 -0
  121. package/dist/pressable.native.js +405 -0
  122. package/dist/pressable.native.js.map +1 -0
  123. package/dist/runtime-backdrop.native.d.ts +8 -0
  124. package/dist/runtime-backdrop.native.d.ts.map +1 -0
  125. package/dist/runtime-backdrop.native.js +12 -0
  126. package/dist/runtime-backdrop.native.js.map +1 -0
  127. package/dist/runtime-container.native.d.ts +41 -0
  128. package/dist/runtime-container.native.d.ts.map +1 -0
  129. package/dist/runtime-container.native.js +61 -0
  130. package/dist/runtime-container.native.js.map +1 -0
  131. package/dist/runtime-grid.d.ts +37 -0
  132. package/dist/runtime-grid.d.ts.map +1 -0
  133. package/dist/runtime-grid.js +139 -0
  134. package/dist/runtime-grid.js.map +1 -0
  135. package/dist/runtime-grid.native.d.ts +26 -0
  136. package/dist/runtime-grid.native.d.ts.map +1 -0
  137. package/dist/runtime-grid.native.js +76 -0
  138. package/dist/runtime-grid.native.js.map +1 -0
  139. package/dist/runtime-measured.d.ts +20 -0
  140. package/dist/runtime-measured.d.ts.map +1 -0
  141. package/dist/runtime-measured.js +42 -0
  142. package/dist/runtime-measured.js.map +1 -0
  143. package/dist/runtime-spacing.d.ts +9 -0
  144. package/dist/runtime-spacing.d.ts.map +1 -0
  145. package/dist/runtime-spacing.js +35 -0
  146. package/dist/runtime-spacing.js.map +1 -0
  147. package/dist/runtime-spacing.native.d.ts +12 -0
  148. package/dist/runtime-spacing.native.d.ts.map +1 -0
  149. package/dist/runtime-spacing.native.js +64 -0
  150. package/dist/runtime-spacing.native.js.map +1 -0
  151. package/dist/runtime-text-size.native.d.ts +29 -0
  152. package/dist/runtime-text-size.native.d.ts.map +1 -0
  153. package/dist/runtime-text-size.native.js +51 -0
  154. package/dist/runtime-text-size.native.js.map +1 -0
  155. package/dist/runtime-transition.native.d.ts +15 -0
  156. package/dist/runtime-transition.native.d.ts.map +1 -0
  157. package/dist/runtime-transition.native.js +156 -0
  158. package/dist/runtime-transition.native.js.map +1 -0
  159. package/dist/text-input.d.ts +40 -0
  160. package/dist/text-input.d.ts.map +1 -0
  161. package/dist/text-input.js +54 -0
  162. package/dist/text-input.js.map +1 -0
  163. package/dist/view.d.ts +42 -0
  164. package/dist/view.d.ts.map +1 -0
  165. package/dist/view.js +84 -0
  166. package/dist/view.js.map +1 -0
  167. package/dist/view.native.d.ts +8 -0
  168. package/dist/view.native.d.ts.map +1 -0
  169. package/dist/view.native.js +5 -0
  170. package/dist/view.native.js.map +1 -0
  171. package/dist/windowing.d.ts +149 -0
  172. package/dist/windowing.d.ts.map +1 -0
  173. package/dist/windowing.js +336 -0
  174. package/dist/windowing.js.map +1 -0
  175. package/package.json +160 -0
  176. package/src/flat-list.native.tsx +158 -0
  177. package/src/foundation.native.tsx +179 -0
  178. package/src/foundation.tsx +323 -0
  179. package/src/generated/animated.ts +6 -0
  180. package/src/generated/backdrop-filter.ts +5 -0
  181. package/src/generated/container.ts +7 -0
  182. package/src/generated/flat-list.native.ts +6 -0
  183. package/src/generated/flat-list.ts +7 -0
  184. package/src/generated/grid.ts +4 -0
  185. package/src/generated/link.native.ts +1 -0
  186. package/src/generated/link.ts +1 -0
  187. package/src/generated/pressable.native.ts +5 -0
  188. package/src/generated/pressable.ts +5 -0
  189. package/src/generated/refresh-control.native.ts +4 -0
  190. package/src/generated/refresh-control.ts +1 -0
  191. package/src/generated/scroll-view.native.ts +4 -0
  192. package/src/generated/scroll-view.ts +1 -0
  193. package/src/generated/spaced.ts +2 -0
  194. package/src/generated/text-input.native.ts +4 -0
  195. package/src/generated/text-input.ts +1 -0
  196. package/src/generated/text-size.ts +7 -0
  197. package/src/generated/text.ts +8 -0
  198. package/src/generated/view.native.ts +1 -0
  199. package/src/generated/view.ts +1 -0
  200. package/src/index.native.ts +24 -0
  201. package/src/index.ts +1111 -0
  202. package/src/link.native.tsx +77 -0
  203. package/src/link.ts +125 -0
  204. package/src/pressable.native.tsx +538 -0
  205. package/src/pressable.ts +358 -0
  206. package/src/runtime-backdrop.native.tsx +22 -0
  207. package/src/runtime-container.native.tsx +105 -0
  208. package/src/runtime-grid.native.tsx +143 -0
  209. package/src/runtime-grid.ts +198 -0
  210. package/src/runtime-measured.ts +42 -0
  211. package/src/runtime-spacing.native.tsx +75 -0
  212. package/src/runtime-spacing.ts +37 -0
  213. package/src/runtime-text-size.native.tsx +79 -0
  214. package/src/runtime-transition.native.tsx +183 -0
  215. package/src/text-input.ts +129 -0
  216. package/src/view.native.ts +7 -0
  217. package/src/view.ts +165 -0
  218. package/src/windowing.ts +415 -0
package/src/index.ts ADDED
@@ -0,0 +1,1111 @@
1
+ import {
2
+ type HozoDomStyle,
3
+ hozoDomStyle,
4
+ type ResponderProps,
5
+ useResponderDomProps,
6
+ } from '@hozo/engine'
7
+ import {
8
+ createElement,
9
+ forwardRef,
10
+ type HTMLAttributes,
11
+ isValidElement,
12
+ type ReactElement,
13
+ type ReactNode,
14
+ type Ref,
15
+ useCallback,
16
+ useEffect,
17
+ useLayoutEffect,
18
+ useMemo,
19
+ useRef,
20
+ useState,
21
+ } from 'react'
22
+ import type { HozoLayoutEvent } from './foundation.tsx'
23
+ import {
24
+ type Anchor,
25
+ anchorRow,
26
+ initialRange,
27
+ ListMetrics,
28
+ type MaintainVisibleContentPosition,
29
+ windowRange,
30
+ withFocus,
31
+ } from './windowing.ts'
32
+
33
+ export * from './foundation.tsx'
34
+
35
+ export interface HozoScrollEvent {
36
+ nativeEvent: {
37
+ contentOffset: { x: number; y: number }
38
+ contentSize: { width: number; height: number }
39
+ layoutMeasurement: { width: number; height: number }
40
+ }
41
+ }
42
+
43
+ export interface HozoRefreshControlProps {
44
+ refreshing: boolean
45
+ onRefresh?: () => void
46
+ tintColor?: string
47
+ titleColor?: string
48
+ progressViewOffset?: number
49
+ }
50
+
51
+ /** A portable refresh intent. Hozo lists consume it; standalone use stays operable. */
52
+ export function HozoRefreshControl({ refreshing, onRefresh }: HozoRefreshControlProps) {
53
+ return createElement(
54
+ 'button',
55
+ {
56
+ type: 'button',
57
+ disabled: refreshing || !onRefresh,
58
+ onClick: onRefresh,
59
+ 'aria-busy': refreshing || undefined,
60
+ 'data-hozo-refresh-control': '',
61
+ },
62
+ refreshing ? 'Refreshing…' : 'Refresh',
63
+ )
64
+ }
65
+
66
+ function assignRef<T>(ref: Ref<T> | undefined, value: T | null) {
67
+ if (typeof ref === 'function') ref(value)
68
+ else if (ref) ref.current = value
69
+ }
70
+
71
+ function nativeScrollEvent(element: HTMLElement): HozoScrollEvent {
72
+ return {
73
+ nativeEvent: {
74
+ contentOffset: { x: element.scrollLeft, y: element.scrollTop },
75
+ contentSize: { width: element.scrollWidth, height: element.scrollHeight },
76
+ layoutMeasurement: { width: element.clientWidth, height: element.clientHeight },
77
+ },
78
+ }
79
+ }
80
+
81
+ function refreshProps(control: ReactNode): HozoRefreshControlProps | undefined {
82
+ return isValidElement(control) && control.type === HozoRefreshControl
83
+ ? (control.props as HozoRefreshControlProps)
84
+ : undefined
85
+ }
86
+
87
+ function renderSlot(slot: ReactNode | (() => ReactNode)) {
88
+ if (typeof slot === 'function') return createElement(slot)
89
+ return slot
90
+ }
91
+
92
+ interface SharedScrollableProps
93
+ extends Omit<HTMLAttributes<HTMLDivElement>, 'children' | 'onScroll' | 'style'>,
94
+ ResponderProps {
95
+ children?: ReactNode
96
+ style?: HozoDomStyle
97
+ contentContainerStyle?: HozoDomStyle
98
+ horizontal?: boolean
99
+ refreshing?: boolean
100
+ onRefresh?: () => void
101
+ refreshControl?: ReactElement<HozoRefreshControlProps>
102
+ showsVerticalScrollIndicator?: boolean
103
+ showsHorizontalScrollIndicator?: boolean
104
+ onScroll?: (event: HozoScrollEvent) => void
105
+ scrollEventThrottle?: number
106
+ onScrollBeginDrag?: (event: HozoScrollEvent) => void
107
+ onScrollEndDrag?: (event: HozoScrollEvent) => void
108
+ onMomentumScrollEnd?: (event: HozoScrollEvent) => void
109
+ onContentSizeChange?: (width: number, height: number) => void
110
+ onLayout?: (event: HozoLayoutEvent) => void
111
+ testID?: string
112
+ nativeID?: string
113
+ pointerEvents?: 'auto' | 'none' | 'box-none' | 'box-only'
114
+ accessibilityLabel?: string
115
+ accessibilityHint?: string
116
+ accessibilityRole?: string
117
+ accessibilityState?: {
118
+ disabled?: boolean
119
+ selected?: boolean
120
+ checked?: boolean | 'mixed'
121
+ busy?: boolean
122
+ expanded?: boolean
123
+ }
124
+ accessibilityValue?: { min?: number; max?: number; now?: number; text?: string }
125
+ accessibilityLiveRegion?: 'none' | 'polite' | 'assertive'
126
+ keyboardShouldPersistTaps?: 'always' | 'never' | 'handled'
127
+ stickyHeaderIndices?: readonly number[]
128
+ contentInsetAdjustmentBehavior?: string
129
+ automaticallyAdjustKeyboardInsets?: boolean
130
+ bounces?: boolean
131
+ pagingEnabled?: boolean
132
+ directionalLockEnabled?: boolean
133
+ nestedScrollEnabled?: boolean
134
+ alwaysBounceVertical?: boolean
135
+ overScrollMode?: string
136
+ snapToOffsets?: readonly number[]
137
+ snapToEnd?: boolean
138
+ }
139
+
140
+ function useMeasurements(
141
+ rootRef: React.RefObject<HTMLDivElement | null>,
142
+ contentRef: React.RefObject<HTMLDivElement | null>,
143
+ onLayout: SharedScrollableProps['onLayout'],
144
+ onContentSizeChange: SharedScrollableProps['onContentSizeChange'],
145
+ ) {
146
+ const layoutRef = useRef(onLayout)
147
+ const contentSizeRef = useRef(onContentSizeChange)
148
+ layoutRef.current = onLayout
149
+ contentSizeRef.current = onContentSizeChange
150
+
151
+ useEffect(() => {
152
+ const root = rootRef.current
153
+ const content = contentRef.current
154
+ if (!root || !content) return
155
+ let lastLayout = ''
156
+ let lastContent = ''
157
+ const emit = () => {
158
+ const rect = root.getBoundingClientRect()
159
+ const layout = {
160
+ x: root.offsetLeft,
161
+ y: root.offsetTop,
162
+ width: rect.width,
163
+ height: rect.height,
164
+ }
165
+ const layoutKey = `${layout.x}:${layout.y}:${layout.width}:${layout.height}`
166
+ if (layoutKey !== lastLayout) {
167
+ lastLayout = layoutKey
168
+ layoutRef.current?.({ nativeEvent: { layout } })
169
+ }
170
+ const contentRect = content.getBoundingClientRect()
171
+ const contentKey = `${contentRect.width}:${contentRect.height}`
172
+ if (contentKey !== lastContent) {
173
+ lastContent = contentKey
174
+ contentSizeRef.current?.(contentRect.width, contentRect.height)
175
+ }
176
+ }
177
+ emit()
178
+ if (typeof ResizeObserver === 'undefined') return
179
+ const observer = new ResizeObserver(emit)
180
+ observer.observe(root)
181
+ observer.observe(content)
182
+ return () => observer.disconnect()
183
+ }, [rootRef, contentRef])
184
+ }
185
+
186
+ export interface HozoScrollViewProps extends SharedScrollableProps {}
187
+
188
+ export const HozoScrollView = forwardRef<HTMLDivElement, HozoScrollViewProps>(
189
+ function HozoScrollView(
190
+ {
191
+ children,
192
+ className,
193
+ style,
194
+ contentContainerStyle,
195
+ horizontal,
196
+ refreshing,
197
+ onRefresh,
198
+ refreshControl,
199
+ showsVerticalScrollIndicator = true,
200
+ showsHorizontalScrollIndicator = true,
201
+ onScroll,
202
+ scrollEventThrottle = 0,
203
+ onScrollBeginDrag,
204
+ onScrollEndDrag,
205
+ onMomentumScrollEnd,
206
+ onContentSizeChange,
207
+ onLayout,
208
+ testID,
209
+ nativeID,
210
+ pointerEvents,
211
+ accessibilityLabel,
212
+ accessibilityHint,
213
+ accessibilityRole,
214
+ accessibilityState,
215
+ accessibilityValue,
216
+ accessibilityLiveRegion,
217
+ keyboardShouldPersistTaps: _keyboardShouldPersistTaps,
218
+ stickyHeaderIndices: _stickyHeaderIndices,
219
+ contentInsetAdjustmentBehavior: _contentInsetAdjustmentBehavior,
220
+ automaticallyAdjustKeyboardInsets: _automaticallyAdjustKeyboardInsets,
221
+ bounces: _bounces,
222
+ pagingEnabled: _pagingEnabled,
223
+ directionalLockEnabled: _directionalLockEnabled,
224
+ nestedScrollEnabled: _nestedScrollEnabled,
225
+ alwaysBounceVertical: _alwaysBounceVertical,
226
+ overScrollMode: _overScrollMode,
227
+ snapToOffsets: _snapToOffsets,
228
+ snapToEnd: _snapToEnd,
229
+ onPointerDown,
230
+ onPointerDownCapture,
231
+ onPointerMove,
232
+ onPointerMoveCapture,
233
+ onPointerUp,
234
+ onPointerCancel,
235
+ onLostPointerCapture,
236
+ onStartShouldSetResponder,
237
+ onStartShouldSetResponderCapture,
238
+ onMoveShouldSetResponder,
239
+ onMoveShouldSetResponderCapture,
240
+ onResponderGrant,
241
+ onResponderStart,
242
+ onResponderMove,
243
+ onResponderEnd,
244
+ onResponderRelease,
245
+ onResponderReject,
246
+ onResponderTerminate,
247
+ onResponderTerminationRequest,
248
+ ...domProps
249
+ },
250
+ forwardedRef,
251
+ ) {
252
+ const rootRef = useRef<HTMLDivElement>(null)
253
+ const contentRef = useRef<HTMLDivElement>(null)
254
+ const lastScroll = useRef(0)
255
+ const setRoot = useCallback(
256
+ (element: HTMLDivElement | null) => {
257
+ rootRef.current = element
258
+ assignRef(forwardedRef, element)
259
+ },
260
+ [forwardedRef],
261
+ )
262
+ useMeasurements(rootRef, contentRef, onLayout, onContentSizeChange)
263
+ const responderProps = {
264
+ onStartShouldSetResponder,
265
+ onStartShouldSetResponderCapture,
266
+ onMoveShouldSetResponder,
267
+ onMoveShouldSetResponderCapture,
268
+ onResponderGrant,
269
+ onResponderStart,
270
+ onResponderMove,
271
+ onResponderEnd,
272
+ onResponderRelease,
273
+ onResponderReject,
274
+ onResponderTerminate,
275
+ onResponderTerminationRequest,
276
+ }
277
+ const hasResponderContract = Object.values(responderProps).some(Boolean)
278
+ const responder = useResponderDomProps(
279
+ rootRef,
280
+ responderProps,
281
+ hasResponderContract && accessibilityState?.disabled !== true,
282
+ )
283
+ const nestedRefresh = refreshProps(refreshControl)
284
+ const activeRefreshing = refreshing ?? nestedRefresh?.refreshing ?? false
285
+ const activeRefresh = onRefresh ?? nestedRefresh?.onRefresh
286
+ const hideScrollbar = horizontal
287
+ ? !showsHorizontalScrollIndicator
288
+ : !showsVerticalScrollIndicator
289
+ const viewport = horizontal
290
+ ? { overflowX: 'auto' as const, overflowY: 'hidden' as const }
291
+ : { overflowX: 'hidden' as const, overflowY: 'auto' as const }
292
+ const emitScroll = () => (rootRef.current ? nativeScrollEvent(rootRef.current) : undefined)
293
+ const emitTo = (callback: ((event: HozoScrollEvent) => void) | undefined) => {
294
+ const event = emitScroll()
295
+ if (event) callback?.(event)
296
+ }
297
+
298
+ return createElement(
299
+ 'div',
300
+ {
301
+ ...domProps,
302
+ ref: setRoot,
303
+ className,
304
+ id: nativeID,
305
+ 'data-testid': testID,
306
+ role: accessibilityRole ?? domProps.role,
307
+ 'data-hozo-pointer-events': pointerEvents,
308
+ 'data-hozo-disabled': accessibilityState?.disabled ? '' : undefined,
309
+ 'data-hozo-horizontal': horizontal ? '' : undefined,
310
+ 'data-hozo-hide-scrollbar': hideScrollbar ? '' : undefined,
311
+ 'aria-label': accessibilityLabel,
312
+ 'aria-description': accessibilityHint,
313
+ 'aria-disabled': accessibilityState?.disabled,
314
+ 'aria-selected': accessibilityState?.selected,
315
+ 'aria-checked': accessibilityState?.checked,
316
+ 'aria-busy': accessibilityState?.busy || activeRefreshing || undefined,
317
+ 'aria-expanded': accessibilityState?.expanded,
318
+ 'aria-valuemin': accessibilityValue?.min,
319
+ 'aria-valuemax': accessibilityValue?.max,
320
+ 'aria-valuenow': accessibilityValue?.now,
321
+ 'aria-valuetext': accessibilityValue?.text,
322
+ 'aria-live': accessibilityLiveRegion === 'none' ? undefined : accessibilityLiveRegion,
323
+ style: { ...viewport, ...hozoDomStyle(style) },
324
+ onPointerDown:
325
+ onScrollBeginDrag || responder.onPointerDown || onPointerDown
326
+ ? (event) => {
327
+ emitTo(onScrollBeginDrag)
328
+ responder.onPointerDown?.(event)
329
+ onPointerDown?.(event)
330
+ }
331
+ : undefined,
332
+ onPointerDownCapture:
333
+ responder.onPointerDownCapture || onPointerDownCapture
334
+ ? (event) => {
335
+ responder.onPointerDownCapture?.(event)
336
+ onPointerDownCapture?.(event)
337
+ }
338
+ : undefined,
339
+ onPointerMove:
340
+ responder.onPointerMove || onPointerMove
341
+ ? (event) => {
342
+ responder.onPointerMove?.(event)
343
+ onPointerMove?.(event)
344
+ }
345
+ : undefined,
346
+ onPointerMoveCapture:
347
+ responder.onPointerMoveCapture || onPointerMoveCapture
348
+ ? (event) => {
349
+ responder.onPointerMoveCapture?.(event)
350
+ onPointerMoveCapture?.(event)
351
+ }
352
+ : undefined,
353
+ onPointerUp:
354
+ onScrollEndDrag || responder.onPointerUp || onPointerUp
355
+ ? (event) => {
356
+ emitTo(onScrollEndDrag)
357
+ responder.onPointerUp?.(event)
358
+ onPointerUp?.(event)
359
+ }
360
+ : undefined,
361
+ onPointerCancel:
362
+ responder.onPointerCancel || onPointerCancel
363
+ ? (event) => {
364
+ responder.onPointerCancel?.(event)
365
+ onPointerCancel?.(event)
366
+ }
367
+ : undefined,
368
+ onLostPointerCapture:
369
+ responder.onLostPointerCapture || onLostPointerCapture
370
+ ? (event) => {
371
+ responder.onLostPointerCapture?.(event)
372
+ onLostPointerCapture?.(event)
373
+ }
374
+ : undefined,
375
+ onScroll: () => {
376
+ const now = Date.now()
377
+ const event = emitScroll()
378
+ if (!event) return
379
+ if (
380
+ onScroll &&
381
+ (scrollEventThrottle <= 0 || now - lastScroll.current >= scrollEventThrottle)
382
+ ) {
383
+ lastScroll.current = now
384
+ onScroll(event)
385
+ }
386
+ },
387
+ onScrollEnd: onMomentumScrollEnd ? () => emitTo(onMomentumScrollEnd) : undefined,
388
+ },
389
+ activeRefresh
390
+ ? createElement(HozoRefreshControl, {
391
+ refreshing: activeRefreshing,
392
+ onRefresh: activeRefresh,
393
+ })
394
+ : null,
395
+ createElement(
396
+ 'div',
397
+ { ref: contentRef, style: hozoDomStyle(contentContainerStyle) },
398
+ children,
399
+ ),
400
+ )
401
+ },
402
+ )
403
+
404
+ export interface HozoFlatListRenderInfo<T> {
405
+ item: T
406
+ index: number
407
+ separators: { highlight(): void; unhighlight(): void; updateProps(): void }
408
+ }
409
+
410
+ /** React Native's `getItemLayout` result: a row's size and position, already known. */
411
+ export interface HozoFlatListLayout {
412
+ length: number
413
+ offset: number
414
+ index: number
415
+ }
416
+
417
+ export interface HozoFlatListProps<T>
418
+ extends Omit<SharedScrollableProps, 'children' | 'onContentSizeChange'> {
419
+ data: readonly T[] | null | undefined
420
+ renderItem: (info: HozoFlatListRenderInfo<T>) => ReactNode
421
+ keyExtractor?: (item: T, index: number) => string
422
+ ListHeaderComponent?: ReactNode | (() => ReactNode)
423
+ ListFooterComponent?: ReactNode | (() => ReactNode)
424
+ ListEmptyComponent?: ReactNode | (() => ReactNode)
425
+ ItemSeparatorComponent?: ReactNode | (() => ReactNode)
426
+ numColumns?: number
427
+ onEndReached?: (info: { distanceFromEnd: number }) => void
428
+ /** In viewport lengths, as React Native measures it. Its default is 2. */
429
+ onEndReachedThreshold?: number
430
+ /** Rows to mount before the viewport has been measured. */
431
+ initialNumToRender?: number
432
+ /** `(windowSize - 1)` viewports of overscan, split half each way. */
433
+ windowSize?: number
434
+ /** A cap on how many *new* rows one pass may mount. */
435
+ maxToRenderPerBatch?: number
436
+ /**
437
+ * Exact geometry, when the caller already has it.
438
+ *
439
+ * Believed rather than measured, which is the whole reason React Native
440
+ * offers it: `scrollToIndex` to an unmeasured row is otherwise a guess
441
+ * followed by a correction. With `numColumns > 1` it describes *items*
442
+ * and the list windows *rows*, so only its `length` is used there and the
443
+ * row offsets are still summed here.
444
+ */
445
+ getItemLayout?: (data: readonly T[] | null | undefined, index: number) => HozoFlatListLayout
446
+ /**
447
+ * What a row is assumed to be until one has been measured.
448
+ *
449
+ * Only the first paint depends on it: the mean of the measured rows takes
450
+ * over as soon as there are any. A number in the right order of magnitude
451
+ * is worth more than an exact one.
452
+ */
453
+ estimatedItemSize?: number
454
+ /**
455
+ * Row 0 at the bottom, and `scrollToOffset(0)` with it.
456
+ *
457
+ * A mirror transform on the scroller and on each row, which is how
458
+ * `react-native-web` does it: layout, scroll offsets and measurement all
459
+ * stay in list space, so nothing else in this file has to know.
460
+ */
461
+ inverted?: boolean
462
+ /** Holds the reader's place when rows are inserted above them. */
463
+ maintainVisibleContentPosition?: MaintainVisibleContentPosition
464
+ /**
465
+ * Accepted and unused, because it no longer describes a choice: rows
466
+ * outside the window are not mounted at all.
467
+ */
468
+ removeClippedSubviews?: boolean
469
+ /**
470
+ * Accepted for source compatibility and needed by nothing here.
471
+ *
472
+ * React Native carries it because `VirtualizedList` memoises cells and
473
+ * has to be told when a closure went stale. Nothing memoises here, so any
474
+ * prop change already re-renders the rows -- including this one.
475
+ */
476
+ extraData?: unknown
477
+ }
478
+
479
+ export interface HozoFlatListHandle extends HTMLDivElement {
480
+ scrollToOffset(options: { offset: number; animated?: boolean }): void
481
+ scrollToEnd(options?: { animated?: boolean }): void
482
+ scrollToIndex(options: { index: number; animated?: boolean; viewOffset?: number }): void
483
+ }
484
+
485
+ const separators = { highlight() {}, unhighlight() {}, updateProps() {} }
486
+
487
+ /** The mirror `inverted` applies, in React Native's own spelling. */
488
+ function invertedTransform(horizontal: boolean | undefined) {
489
+ return horizontal ? [{ scaleX: -1 }] : [{ scaleY: -1 }]
490
+ }
491
+
492
+ function HozoFlatListInner<T>(props: HozoFlatListProps<T>, forwardedRef: Ref<HozoFlatListHandle>) {
493
+ const {
494
+ data = [],
495
+ renderItem,
496
+ keyExtractor,
497
+ ListHeaderComponent,
498
+ ListFooterComponent,
499
+ ListEmptyComponent,
500
+ ItemSeparatorComponent,
501
+ numColumns = 1,
502
+ horizontal,
503
+ inverted,
504
+ contentContainerStyle,
505
+ style,
506
+ onEndReached,
507
+ // React Native's default, read from `VirtualizedListProps`. This file
508
+ // used to default it to 0, which asks for the callback only once the
509
+ // very last pixel is on screen.
510
+ onEndReachedThreshold = 2,
511
+ initialNumToRender = 10,
512
+ windowSize = 21,
513
+ maxToRenderPerBatch = 10,
514
+ getItemLayout,
515
+ estimatedItemSize = 100,
516
+ maintainVisibleContentPosition,
517
+ removeClippedSubviews: _removeClippedSubviews,
518
+ extraData: _extraData,
519
+ ...scrollProps
520
+ } = props
521
+
522
+ const items = data ?? []
523
+ const columns = Math.max(1, Math.floor(numColumns))
524
+
525
+ // Rows, not items, are what gets windowed. A two-column grid scrolls by
526
+ // rows, so a window measured in items would mount half a row at each
527
+ // edge and measure heights that no row has.
528
+ const rows = useMemo(() => {
529
+ const grouped: { key: string; start: number; items: T[] }[] = []
530
+ for (let start = 0; start < items.length; start += columns) {
531
+ const slice = items.slice(start, start + columns)
532
+ const first = slice[0] as T
533
+ grouped.push({ key: keyExtractor?.(first, start) ?? String(start), start, items: slice })
534
+ }
535
+ return grouped
536
+ // `items` by identity: a caller handing a fresh array of the same data
537
+ // every render is ordinary React, and regrouping is cheap next to
538
+ // rendering.
539
+ }, [items, columns, keyExtractor])
540
+
541
+ const rowKeys = useMemo(() => rows.map((row) => row.key), [rows])
542
+
543
+ const metricsRef = useRef<ListMetrics>(undefined as unknown as ListMetrics)
544
+ if (metricsRef.current === undefined) metricsRef.current = new ListMetrics(estimatedItemSize)
545
+ const metrics = metricsRef.current
546
+ metrics.setEstimate(estimatedItemSize)
547
+ metrics.setKeys(rowKeys)
548
+
549
+ // Exact geometry replaces measurement entirely when the caller has it and
550
+ // there is one item per row -- the case `getItemLayout` was written for.
551
+ const exact = getItemLayout && columns === 1 ? getItemLayout : undefined
552
+ const geometry = useMemo(
553
+ () =>
554
+ exact
555
+ ? {
556
+ offsetAt: (index: number) =>
557
+ index <= 0
558
+ ? 0
559
+ : index >= rows.length
560
+ ? exact(data, rows.length - 1).offset + exact(data, rows.length - 1).length
561
+ : exact(data, index).offset,
562
+ lengthAt: (index: number) => exact(data, Math.min(index, rows.length - 1)).length,
563
+ }
564
+ : metrics,
565
+ [exact, data, rows.length, metrics],
566
+ )
567
+
568
+ const rootRef = useRef<HozoFlatListHandle | null>(null)
569
+ const endRef = useRef<HTMLDivElement>(null)
570
+ const [range, setRange] = useState(() => initialRange(rows.length, initialNumToRender))
571
+ const rangeRef = useRef(range)
572
+ rangeRef.current = range
573
+ const scrollRef = useRef({ offset: 0, velocity: 0, time: 0 })
574
+ const emitRef = useRef(0)
575
+
576
+ /**
577
+ * Rows kept mounted around wherever focus is, on top of the scroll window.
578
+ *
579
+ * Two things break without it. Focus lands on a row, the reader scrolls,
580
+ * that row leaves the window, React unmounts it -- and focus falls back to
581
+ * `<body>`, which loses their place entirely. And tabbing forward through
582
+ * a long list walks to the last mounted row and finds nothing after it,
583
+ * because there is nothing after it in the document.
584
+ *
585
+ * `FOCUS_MARGIN` rows either side, so stepping past the edge has somewhere
586
+ * to go before the next recompute catches up.
587
+ */
588
+ const focusRowRef = useRef<number | null>(null)
589
+
590
+ /** Recomputes the window from wherever the scroller and focus currently are. */
591
+ const recompute = useCallback(() => {
592
+ const root = rootRef.current
593
+ if (!root) return
594
+ const visibleLength = horizontal ? root.clientWidth : root.clientHeight
595
+ // Before the first layout the viewport is zero and every window is
596
+ // empty, which would unmount the rows the first render put there.
597
+ if (visibleLength === 0) return
598
+ const scrolled = windowRange({
599
+ count: rows.length,
600
+ offset: horizontal ? root.scrollLeft : root.scrollTop,
601
+ visibleLength,
602
+ windowSize,
603
+ maxToRenderPerBatch,
604
+ velocity: scrollRef.current.velocity,
605
+ previous: rangeRef.current,
606
+ metrics: geometry,
607
+ })
608
+ const next = withFocus(scrolled, focusRowRef.current, rows.length)
609
+ if (next.first === rangeRef.current.first && next.last === rangeRef.current.last) return
610
+ rangeRef.current = next
611
+ setRange(next)
612
+ }, [geometry, horizontal, maxToRenderPerBatch, rows.length, windowSize])
613
+
614
+ /**
615
+ * Recomputes now, rather than on the next frame.
616
+ *
617
+ * This went through `requestAnimationFrame` first, which is the usual
618
+ * advice and was wrong here twice over. It is unnecessary -- the work is
619
+ * two binary searches and a prefix sum that only rebuilds when something
620
+ * was measured -- and it is unreliable: a frame callback is tied to the
621
+ * compositor producing frames, and in headless Chrome under a virtual
622
+ * time budget it simply never ran. The window stayed on row 0 through a
623
+ * 200,000px scroll, and `scripts/check-list.mjs` is what said so.
624
+ */
625
+ const scheduleRecompute = recompute
626
+ // A row that mounted is a row that can be measured, and one pass of that
627
+ // usually changes the window -- so the window is recomputed after every
628
+ // commit rather than only on scroll.
629
+ useEffect(() => {
630
+ recompute()
631
+ })
632
+
633
+ useEffect(() => {
634
+ const root = rootRef.current
635
+ if (!root || typeof ResizeObserver === 'undefined') return
636
+ const observer = new ResizeObserver(() => recompute())
637
+ observer.observe(root)
638
+ return () => observer.disconnect()
639
+ }, [recompute])
640
+
641
+ // Where focus is, as a row index. `focusin` and `focusout` bubble, so one
642
+ // pair of listeners on the scroller covers every row in it -- including
643
+ // the ones mounted after this ran.
644
+ useEffect(() => {
645
+ const root = rootRef.current
646
+ if (!root) return
647
+ const rowOf = (target: EventTarget | null) => {
648
+ if (!(target instanceof Element)) return null
649
+ const row = target.closest<HTMLElement>('[data-hozo-list-row]')
650
+ if (!row || !root.contains(row)) return null
651
+ const index = Number(row.dataset.hozoListRow)
652
+ return Number.isFinite(index) ? index : null
653
+ }
654
+ const onFocusIn = (event: FocusEvent) => {
655
+ const row = rowOf(event.target)
656
+ if (row === focusRowRef.current) return
657
+ focusRowRef.current = row
658
+ recompute()
659
+ }
660
+ const onFocusOut = (event: FocusEvent) => {
661
+ // Only when focus left the list entirely. Moving between two rows
662
+ // fires this for the one being left, and forgetting the row there
663
+ // would unmount the row focus is arriving at.
664
+ if (rowOf(event.relatedTarget) !== null) return
665
+ if (focusRowRef.current === null) return
666
+ focusRowRef.current = null
667
+ recompute()
668
+ }
669
+ root.addEventListener('focusin', onFocusIn)
670
+ root.addEventListener('focusout', onFocusOut)
671
+ return () => {
672
+ root.removeEventListener('focusin', onFocusIn)
673
+ root.removeEventListener('focusout', onFocusOut)
674
+ }
675
+ }, [recompute])
676
+
677
+ /**
678
+ * Records what a mounted row measured.
679
+ *
680
+ * A `ref` callback plus one shared `ResizeObserver` rather than an
681
+ * observer per row: a window is up to twenty viewports of rows, and an
682
+ * observer each is twenty viewports of observers.
683
+ *
684
+ * The row leaving the window has to stop being observed, and that is not
685
+ * a tidiness point. A `ResizeObserver` keeps reporting an element after
686
+ * React removes it from the document, and a removed element measures
687
+ * zero by zero -- so every row that scrolled out of the window wrote a
688
+ * height of 0 into the store, the mean of the measured rows fell towards
689
+ * nothing, and ten thousand rows came to a scrollable length of 7,138px.
690
+ * The list then had eleven rows in it and the scroll position was
691
+ * meaningless. `scripts/check-list.mjs` is what found that; nothing
692
+ * without layout could have.
693
+ */
694
+ // The observer is created once and outlives the render that made it, so
695
+ // what its callback calls has to be read at call time rather than closed
696
+ // over. Captured directly, it would still be holding the first render's
697
+ // `rowKeys` and `geometry` after a data change -- and then correcting a
698
+ // scroll position against a list that no longer exists.
699
+ const latestRef = useRef({ recompute: () => {}, applyPin: () => {} })
700
+ const observerRef = useRef<ResizeObserver | null>(null)
701
+ const observedRef = useRef(new Map<Element, string>())
702
+ const elementsRef = useRef(new Map<string, Element>())
703
+ const measure = useCallback(
704
+ (element: HTMLDivElement | null, key: string) => {
705
+ if (typeof ResizeObserver === 'undefined') return
706
+ const observed = observedRef.current
707
+ const elements = elementsRef.current
708
+ const previous = elements.get(key)
709
+ if (previous && previous !== element) {
710
+ observerRef.current?.unobserve(previous)
711
+ observed.delete(previous)
712
+ elements.delete(key)
713
+ }
714
+ if (!element) return
715
+ if (!observerRef.current) {
716
+ observerRef.current = new ResizeObserver((entries) => {
717
+ let changed = false
718
+ for (const entry of entries) {
719
+ const entryKey = observedRef.current.get(entry.target)
720
+ if (entryKey === undefined) continue
721
+ // The second half of the same defence: an entry can be queued
722
+ // for an element that has since left the document, and its box
723
+ // is zero.
724
+ if (!entry.target.isConnected) continue
725
+ const box = entry.target.getBoundingClientRect()
726
+ if (metrics.measure(entryKey, horizontal ? box.width : box.height)) changed = true
727
+ }
728
+ if (!changed) return
729
+ latestRef.current.recompute()
730
+ latestRef.current.applyPin()
731
+ })
732
+ }
733
+ observed.set(element, key)
734
+ elements.set(key, element)
735
+ observerRef.current.observe(element)
736
+ },
737
+ [horizontal, metrics],
738
+ )
739
+
740
+ useEffect(
741
+ () => () => {
742
+ observerRef.current?.disconnect()
743
+ observerRef.current = null
744
+ observedRef.current.clear()
745
+ elementsRef.current.clear()
746
+ },
747
+ [],
748
+ )
749
+
750
+ // Keeping one row where it is meant to be, for as long as that keeps
751
+ // moving.
752
+ //
753
+ // Two features need the same thing. `maintainVisibleContentPosition` has
754
+ // to hold the reader's row still while rows are inserted above it, and
755
+ // `scrollToIndex` has to put a named row at the top of the viewport. Both
756
+ // start from a scroll offset computed out of *estimated* row heights,
757
+ // because the rows in question have not been near the viewport and
758
+ // nothing has measured them -- so both are right to within an estimate
759
+ // and wrong by the difference. Measured on device-sized data: a jump to
760
+ // row 5,000 landed 1,603px off, and ten prepended rows moved the reader
761
+ // by 12px.
762
+ //
763
+ // So neither of them is a single correction. A pin says which row belongs
764
+ // at which offset from the top of the viewport, and it is re-applied on
765
+ // every commit -- which is every time the window moves or a row reports
766
+ // its size -- until the answer stops changing or the budget runs out.
767
+ //
768
+ // It yields to the reader: if the scroll position is not where the pin
769
+ // last put it, somebody scrolled, and a list that scrolled itself back
770
+ // would be worse than one that landed 1,603px out.
771
+ interface Pin {
772
+ key: string
773
+ /** Where the row should sit, measured from the start of the viewport. */
774
+ screenOffset: number
775
+ /** What this last set the scroll offset to, so a reader's scroll is visible. */
776
+ applied: number
777
+ /** Corrections left to spend. */
778
+ left: number
779
+ /** When to give up, whatever has or has not settled. */
780
+ until: number
781
+ }
782
+ const pinRef = useRef<Pin | null>(null)
783
+ const anchorRef = useRef<Anchor | undefined>(undefined)
784
+ const previousKeysRef = useRef<readonly string[]>(rowKeys)
785
+
786
+ const pinTo = useCallback((key: string, screenOffset: number) => {
787
+ pinRef.current = {
788
+ key,
789
+ screenOffset,
790
+ applied: Number.NaN,
791
+ left: 20,
792
+ // A wall clock as well as a budget. A pin that waits for a
793
+ // measurement that never comes -- a row removed while off screen, a
794
+ // list nobody is looking at -- would otherwise sit there and move the
795
+ // page much later, on a change it has nothing to do with.
796
+ until: Date.now() + 2000,
797
+ }
798
+ }, [])
799
+
800
+ /**
801
+ * Puts the pinned row back where it belongs, if it has moved.
802
+ *
803
+ * Called after every commit *and* from the measurement callback, and the
804
+ * second is the one that matters. A pin's first target is computed from
805
+ * estimated row heights, so it is right to within an estimate; the real
806
+ * answer only arrives when the rows near it report their sizes, and that
807
+ * does not always change the window, so it does not always cause a
808
+ * commit. Waiting for one left `scrollToIndex(5000)` sitting 1,204px
809
+ * short.
810
+ *
811
+ * Silent when it is already right, rather than releasing: being in the
812
+ * right place according to an estimate is exactly the state this exists
813
+ * to correct.
814
+ */
815
+ const applyPin = useCallback(() => {
816
+ const root = rootRef.current
817
+ const pin = pinRef.current
818
+ if (!root || !pin) return
819
+ const offset = horizontal ? root.scrollLeft : root.scrollTop
820
+ if (!Number.isNaN(pin.applied) && Math.abs(offset - pin.applied) > 1) {
821
+ // The reader moved. The pin is theirs to override, and a list that
822
+ // scrolled itself back would be worse than one that landed short.
823
+ pinRef.current = null
824
+ return
825
+ }
826
+ const index = rowKeys.indexOf(pin.key)
827
+ if (index === -1 || pin.left <= 0 || Date.now() > pin.until) {
828
+ pinRef.current = null
829
+ return
830
+ }
831
+ const target = Math.max(0, geometry.offsetAt(index) - pin.screenOffset)
832
+ if (Math.abs(target - offset) < 1) return
833
+ pin.left -= 1
834
+ root.scrollTo({ [horizontal ? 'left' : 'top']: target })
835
+ pin.applied = horizontal ? root.scrollLeft : root.scrollTop
836
+ }, [geometry, horizontal, rowKeys])
837
+
838
+ latestRef.current = { recompute, applyPin }
839
+
840
+ // `maintainVisibleContentPosition`: the row the reader is looking at
841
+ // stays where it is when rows arrive above it. Anchored by key rather
842
+ // than by index, because a feed that prepends renumbers every index and
843
+ // no arithmetic on indices survives that.
844
+ //
845
+ // Ordered before the effect that applies a pin, and that is not a
846
+ // preference. A pin left over from a `scrollToIndex` would otherwise
847
+ // correct first, against the new list -- moving the scroll by the height
848
+ // of what was inserted -- and this effect would then read the corrected
849
+ // offset as though it were where the reader had been, and pin the anchor
850
+ // that far out. Measured: the reader's row moved 996px, which is what ten
851
+ // inserted rows are worth.
852
+ useLayoutEffect(() => {
853
+ const root = rootRef.current
854
+ const previousKeys = previousKeysRef.current
855
+ previousKeysRef.current = rowKeys
856
+ if (!root || previousKeys === rowKeys) return
857
+
858
+ // Whatever was being held in place was being held in a list that no
859
+ // longer exists.
860
+ pinRef.current = null
861
+
862
+ if (!maintainVisibleContentPosition || previousKeys.length === 0) return
863
+ const anchor = anchorRef.current
864
+ if (!anchor) return
865
+ const offset = horizontal ? root.scrollLeft : root.scrollTop
866
+ const threshold = maintainVisibleContentPosition.autoscrollToTopThreshold
867
+ if (threshold !== undefined && offset <= threshold) {
868
+ root.scrollTo({ [horizontal ? 'left' : 'top']: 0 })
869
+ return
870
+ }
871
+ if (rowKeys.indexOf(anchor.key) === -1) return
872
+ pinTo(anchor.key, anchor.offset - offset)
873
+ }, [rowKeys, maintainVisibleContentPosition, horizontal, pinTo])
874
+
875
+ useLayoutEffect(applyPin)
876
+
877
+ /**
878
+ * Where the reader is, as a row and its offset.
879
+ *
880
+ * Recorded after every commit *and* on every scroll. A commit alone is
881
+ * not enough: a list can be scrolled a long way with nothing re-rendering
882
+ * once the window covers where it went, and an anchor left over from
883
+ * before that describes somebody who has moved on. Measured -- gating
884
+ * this on "no pin is active" left a stale anchor from before a
885
+ * `scrollToIndex`, and the next prepend moved the reader 1,329px.
886
+ */
887
+ const recordAnchor = useCallback(() => {
888
+ const root = rootRef.current
889
+ if (!root || !maintainVisibleContentPosition) return
890
+ anchorRef.current = anchorRow(
891
+ rowKeys,
892
+ geometry,
893
+ horizontal ? root.scrollLeft : root.scrollTop,
894
+ maintainVisibleContentPosition.minIndexForVisible,
895
+ )
896
+ }, [geometry, horizontal, maintainVisibleContentPosition, rowKeys])
897
+ useEffect(recordAnchor)
898
+
899
+ const setRoot = useCallback(
900
+ (element: HTMLDivElement | null) => {
901
+ if (!element) {
902
+ rootRef.current = null
903
+ assignRef(forwardedRef, null)
904
+ return
905
+ }
906
+ const handle = element as HozoFlatListHandle
907
+ const axis = horizontal ? ('left' as const) : ('top' as const)
908
+ handle.scrollToOffset = ({ offset, animated }) =>
909
+ handle.scrollTo({ [axis]: offset, behavior: animated ? 'smooth' : 'auto' })
910
+ handle.scrollToEnd = ({ animated } = {}) =>
911
+ handle.scrollTo({
912
+ [axis]: horizontal ? handle.scrollWidth : handle.scrollHeight,
913
+ behavior: animated ? 'smooth' : 'auto',
914
+ })
915
+ handle.scrollToIndex = ({ index, animated, viewOffset = 0 }) => {
916
+ // React Native throws here when the target has not been measured
917
+ // and there is no `getItemLayout`. This scrolls to the estimate
918
+ // instead and pins the row until the rows that land there report
919
+ // their real sizes -- the reader sees one settle rather than an
920
+ // exception. Measured: the first version of this stopped after
921
+ // five timeouts, all of which ran before any measurement did, and
922
+ // left row 5,000 sitting 1,603px below the top of the viewport.
923
+ const row = Math.floor(Math.max(0, Math.min(index, items.length - 1)) / columns)
924
+ handle.scrollTo({
925
+ [axis]: Math.max(0, geometry.offsetAt(row) - viewOffset),
926
+ behavior: animated ? 'smooth' : 'auto',
927
+ })
928
+ const key = rowKeys[row]
929
+ if (key !== undefined) pinTo(key, viewOffset)
930
+ }
931
+ rootRef.current = handle
932
+ assignRef(forwardedRef, handle)
933
+ },
934
+ [columns, forwardedRef, geometry, horizontal, items.length, pinTo, rowKeys],
935
+ )
936
+
937
+ // `range.last` is in the dependencies and not read in the body, on
938
+ // purpose. The sentinel sits after the *rendered* window rather than after
939
+ // the data, so it is a different element every time the window moves, and
940
+ // an observer left on the old one is watching a node that is gone.
941
+ // biome-ignore lint/correctness/useExhaustiveDependencies: see above
942
+ useEffect(() => {
943
+ const root = rootRef.current
944
+ const target = endRef.current
945
+ if (!root || !target || !onEndReached || rows.length === 0) return
946
+ if (typeof IntersectionObserver === 'undefined') return
947
+ let fired = false
948
+ const margin = `${Math.max(0, onEndReachedThreshold) * 100}%`
949
+ const observer = new IntersectionObserver(
950
+ ([entry]) => {
951
+ if (!entry?.isIntersecting || fired) return
952
+ fired = true
953
+ observer.disconnect()
954
+ onEndReached({ distanceFromEnd: 0 })
955
+ },
956
+ { root, rootMargin: horizontal ? `0px ${margin} 0px 0px` : `0px 0px ${margin} 0px` },
957
+ )
958
+ observer.observe(target)
959
+ return () => observer.disconnect()
960
+ // The sentinel sits after the *rendered* window rather than after the
961
+ // data, so it moves as the window does. Re-observed on every window
962
+ // change for that reason, and re-armed on a data change so a feed that
963
+ // paginates can reach the end more than once.
964
+ }, [rows.length, range.last, horizontal, onEndReached, onEndReachedThreshold])
965
+
966
+ const first = Math.max(0, range.first)
967
+ const last = Math.min(rows.length - 1, range.last)
968
+ const leading = rows.length === 0 ? 0 : geometry.offsetAt(first)
969
+ const total = rows.length === 0 ? 0 : geometry.offsetAt(rows.length)
970
+ const trailing = rows.length === 0 ? 0 : Math.max(0, total - geometry.offsetAt(last + 1))
971
+
972
+ const mounted: ReactNode[] = []
973
+ for (let index = first; index <= last; index++) {
974
+ const row = rows[index]
975
+ if (!row) continue
976
+ const cells = row.items.map((item, column) =>
977
+ createElement(
978
+ 'div',
979
+ {
980
+ key: keyExtractor?.(item, row.start + column) ?? row.start + column,
981
+ role: 'listitem',
982
+ // How long the list is, and where this row is in it.
983
+ //
984
+ // Without these a screen reader announces what is *mounted*: a
985
+ // ten-thousand-row feed reads as "list, 67 items", and the reader
986
+ // has no way to know otherwise, because the other 9,933 rows are
987
+ // not in the accessibility tree to be counted. They are the one
988
+ // thing about virtualisation the Web can answer completely, and
989
+ // `@hozo/core`'s `Tree` already does the same for its rows.
990
+ 'aria-setsize': items.length,
991
+ 'aria-posinset': row.start + column + 1,
992
+ 'data-hozo-list-index': row.start + column,
993
+ },
994
+ renderItem({ item, index: row.start + column, separators }),
995
+ ),
996
+ )
997
+ mounted.push(
998
+ createElement(
999
+ 'div',
1000
+ {
1001
+ key: row.key,
1002
+ ref: (element: HTMLDivElement | null) => measure(element, row.key),
1003
+ // Out of the accessibility tree, so the `listitem`s inside it are
1004
+ // owned by the `list` above it. ARIA requires that relationship,
1005
+ // and this wrapper -- which exists to be measured, and to be the
1006
+ // grid row when there is more than one column -- broke it the
1007
+ // moment windowing introduced it.
1008
+ role: 'presentation',
1009
+ 'data-hozo-list-row': index,
1010
+ style: {
1011
+ ...(columns > 1
1012
+ ? {
1013
+ display: 'grid',
1014
+ gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))`,
1015
+ }
1016
+ : undefined),
1017
+ ...(inverted ? hozoDomStyle({ transform: invertedTransform(horizontal) }) : undefined),
1018
+ },
1019
+ },
1020
+ cells,
1021
+ // Inside the row rather than beside it, so a row's measured size is
1022
+ // the space it actually occupies and the window arithmetic has one
1023
+ // kind of thing to reason about.
1024
+ index < rows.length - 1 && ItemSeparatorComponent
1025
+ ? createElement(
1026
+ 'div',
1027
+ { key: 'separator', role: 'presentation' },
1028
+ renderSlot(ItemSeparatorComponent),
1029
+ )
1030
+ : null,
1031
+ ),
1032
+ )
1033
+ }
1034
+
1035
+ // The rows that are not mounted, as space rather than as elements. Padding
1036
+ // on the container rather than spacer siblings: the container may be a
1037
+ // grid or a flex row, and a spacer would take a cell in one and a column
1038
+ // in the other.
1039
+ const padStart = horizontal ? 'paddingLeft' : 'paddingTop'
1040
+ const padEnd = horizontal ? 'paddingRight' : 'paddingBottom'
1041
+
1042
+ const slotStyle = inverted
1043
+ ? hozoDomStyle({ transform: invertedTransform(horizontal) })
1044
+ : undefined
1045
+ const slot = (node: ReactNode) =>
1046
+ node == null || !inverted ? node : createElement('div', { style: slotStyle }, node)
1047
+
1048
+ return createElement(
1049
+ HozoScrollView,
1050
+ {
1051
+ ...scrollProps,
1052
+ horizontal,
1053
+ contentContainerStyle,
1054
+ style: inverted ? [style, { transform: invertedTransform(horizontal) }] : style,
1055
+ ref: setRoot,
1056
+ onScroll: (event: HozoScrollEvent) => {
1057
+ const now = Date.now()
1058
+ const offset = horizontal
1059
+ ? event.nativeEvent.contentOffset.x
1060
+ : event.nativeEvent.contentOffset.y
1061
+ const previous = scrollRef.current
1062
+ const dt = now - previous.time
1063
+ scrollRef.current = {
1064
+ offset,
1065
+ velocity: dt > 0 ? (offset - previous.offset) / dt : 0,
1066
+ time: now,
1067
+ }
1068
+ scheduleRecompute()
1069
+ recordAnchor()
1070
+ // The caller's throttle applied here rather than upstream. The
1071
+ // window has to keep up with the scroller whatever the caller
1072
+ // asked to hear about, so this listens to every event and rations
1073
+ // only what it passes on.
1074
+ const throttle = props.scrollEventThrottle ?? 0
1075
+ if (throttle <= 0 || now - emitRef.current >= throttle) {
1076
+ emitRef.current = now
1077
+ props.onScroll?.(event)
1078
+ }
1079
+ },
1080
+ scrollEventThrottle: 0,
1081
+ },
1082
+ slot(renderSlot(ListHeaderComponent)),
1083
+ rows.length === 0 ? slot(renderSlot(ListEmptyComponent)) : null,
1084
+ rows.length > 0
1085
+ ? createElement(
1086
+ 'div',
1087
+ {
1088
+ role: 'list',
1089
+ 'data-hozo-list-count': items.length,
1090
+ style: {
1091
+ [padStart]: leading,
1092
+ [padEnd]: trailing,
1093
+ ...(horizontal ? { display: 'flex', flexDirection: 'row' as const } : undefined),
1094
+ },
1095
+ },
1096
+ mounted,
1097
+ )
1098
+ : null,
1099
+ slot(renderSlot(ListFooterComponent)),
1100
+ createElement('div', { ref: endRef, 'aria-hidden': true }),
1101
+ )
1102
+ }
1103
+
1104
+ export const HozoFlatList = forwardRef(HozoFlatListInner) as <T>(
1105
+ props: HozoFlatListProps<T> & { ref?: Ref<HozoFlatListHandle> },
1106
+ ) => ReactElement
1107
+
1108
+ export { HozoFlatList as FlatList, HozoScrollView as ScrollView }
1109
+ export type FlatListRenderInfo<T> = HozoFlatListRenderInfo<T>
1110
+ export type FlatListProps<T> = HozoFlatListProps<T>
1111
+ export type ScrollViewProps = HozoScrollViewProps