@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/dist/index.js ADDED
@@ -0,0 +1,718 @@
1
+ import { hozoDomStyle, useResponderDomProps, } from '@hozo/engine';
2
+ import { createElement, forwardRef, isValidElement, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, } from 'react';
3
+ import { anchorRow, initialRange, ListMetrics, windowRange, withFocus, } from './windowing.js';
4
+ export * from './foundation.js';
5
+ /** A portable refresh intent. Hozo lists consume it; standalone use stays operable. */
6
+ export function HozoRefreshControl({ refreshing, onRefresh }) {
7
+ return createElement('button', {
8
+ type: 'button',
9
+ disabled: refreshing || !onRefresh,
10
+ onClick: onRefresh,
11
+ 'aria-busy': refreshing || undefined,
12
+ 'data-hozo-refresh-control': '',
13
+ }, refreshing ? 'Refreshing…' : 'Refresh');
14
+ }
15
+ function assignRef(ref, value) {
16
+ if (typeof ref === 'function')
17
+ ref(value);
18
+ else if (ref)
19
+ ref.current = value;
20
+ }
21
+ function nativeScrollEvent(element) {
22
+ return {
23
+ nativeEvent: {
24
+ contentOffset: { x: element.scrollLeft, y: element.scrollTop },
25
+ contentSize: { width: element.scrollWidth, height: element.scrollHeight },
26
+ layoutMeasurement: { width: element.clientWidth, height: element.clientHeight },
27
+ },
28
+ };
29
+ }
30
+ function refreshProps(control) {
31
+ return isValidElement(control) && control.type === HozoRefreshControl
32
+ ? control.props
33
+ : undefined;
34
+ }
35
+ function renderSlot(slot) {
36
+ if (typeof slot === 'function')
37
+ return createElement(slot);
38
+ return slot;
39
+ }
40
+ function useMeasurements(rootRef, contentRef, onLayout, onContentSizeChange) {
41
+ const layoutRef = useRef(onLayout);
42
+ const contentSizeRef = useRef(onContentSizeChange);
43
+ layoutRef.current = onLayout;
44
+ contentSizeRef.current = onContentSizeChange;
45
+ useEffect(() => {
46
+ const root = rootRef.current;
47
+ const content = contentRef.current;
48
+ if (!root || !content)
49
+ return;
50
+ let lastLayout = '';
51
+ let lastContent = '';
52
+ const emit = () => {
53
+ const rect = root.getBoundingClientRect();
54
+ const layout = {
55
+ x: root.offsetLeft,
56
+ y: root.offsetTop,
57
+ width: rect.width,
58
+ height: rect.height,
59
+ };
60
+ const layoutKey = `${layout.x}:${layout.y}:${layout.width}:${layout.height}`;
61
+ if (layoutKey !== lastLayout) {
62
+ lastLayout = layoutKey;
63
+ layoutRef.current?.({ nativeEvent: { layout } });
64
+ }
65
+ const contentRect = content.getBoundingClientRect();
66
+ const contentKey = `${contentRect.width}:${contentRect.height}`;
67
+ if (contentKey !== lastContent) {
68
+ lastContent = contentKey;
69
+ contentSizeRef.current?.(contentRect.width, contentRect.height);
70
+ }
71
+ };
72
+ emit();
73
+ if (typeof ResizeObserver === 'undefined')
74
+ return;
75
+ const observer = new ResizeObserver(emit);
76
+ observer.observe(root);
77
+ observer.observe(content);
78
+ return () => observer.disconnect();
79
+ }, [rootRef, contentRef]);
80
+ }
81
+ export const HozoScrollView = forwardRef(function HozoScrollView({ children, className, style, contentContainerStyle, horizontal, refreshing, onRefresh, refreshControl, showsVerticalScrollIndicator = true, showsHorizontalScrollIndicator = true, onScroll, scrollEventThrottle = 0, onScrollBeginDrag, onScrollEndDrag, onMomentumScrollEnd, onContentSizeChange, onLayout, testID, nativeID, pointerEvents, accessibilityLabel, accessibilityHint, accessibilityRole, accessibilityState, accessibilityValue, accessibilityLiveRegion, keyboardShouldPersistTaps: _keyboardShouldPersistTaps, stickyHeaderIndices: _stickyHeaderIndices, contentInsetAdjustmentBehavior: _contentInsetAdjustmentBehavior, automaticallyAdjustKeyboardInsets: _automaticallyAdjustKeyboardInsets, bounces: _bounces, pagingEnabled: _pagingEnabled, directionalLockEnabled: _directionalLockEnabled, nestedScrollEnabled: _nestedScrollEnabled, alwaysBounceVertical: _alwaysBounceVertical, overScrollMode: _overScrollMode, snapToOffsets: _snapToOffsets, snapToEnd: _snapToEnd, onPointerDown, onPointerDownCapture, onPointerMove, onPointerMoveCapture, onPointerUp, onPointerCancel, onLostPointerCapture, onStartShouldSetResponder, onStartShouldSetResponderCapture, onMoveShouldSetResponder, onMoveShouldSetResponderCapture, onResponderGrant, onResponderStart, onResponderMove, onResponderEnd, onResponderRelease, onResponderReject, onResponderTerminate, onResponderTerminationRequest, ...domProps }, forwardedRef) {
82
+ const rootRef = useRef(null);
83
+ const contentRef = useRef(null);
84
+ const lastScroll = useRef(0);
85
+ const setRoot = useCallback((element) => {
86
+ rootRef.current = element;
87
+ assignRef(forwardedRef, element);
88
+ }, [forwardedRef]);
89
+ useMeasurements(rootRef, contentRef, onLayout, onContentSizeChange);
90
+ const responderProps = {
91
+ onStartShouldSetResponder,
92
+ onStartShouldSetResponderCapture,
93
+ onMoveShouldSetResponder,
94
+ onMoveShouldSetResponderCapture,
95
+ onResponderGrant,
96
+ onResponderStart,
97
+ onResponderMove,
98
+ onResponderEnd,
99
+ onResponderRelease,
100
+ onResponderReject,
101
+ onResponderTerminate,
102
+ onResponderTerminationRequest,
103
+ };
104
+ const hasResponderContract = Object.values(responderProps).some(Boolean);
105
+ const responder = useResponderDomProps(rootRef, responderProps, hasResponderContract && accessibilityState?.disabled !== true);
106
+ const nestedRefresh = refreshProps(refreshControl);
107
+ const activeRefreshing = refreshing ?? nestedRefresh?.refreshing ?? false;
108
+ const activeRefresh = onRefresh ?? nestedRefresh?.onRefresh;
109
+ const hideScrollbar = horizontal
110
+ ? !showsHorizontalScrollIndicator
111
+ : !showsVerticalScrollIndicator;
112
+ const viewport = horizontal
113
+ ? { overflowX: 'auto', overflowY: 'hidden' }
114
+ : { overflowX: 'hidden', overflowY: 'auto' };
115
+ const emitScroll = () => (rootRef.current ? nativeScrollEvent(rootRef.current) : undefined);
116
+ const emitTo = (callback) => {
117
+ const event = emitScroll();
118
+ if (event)
119
+ callback?.(event);
120
+ };
121
+ return createElement('div', {
122
+ ...domProps,
123
+ ref: setRoot,
124
+ className,
125
+ id: nativeID,
126
+ 'data-testid': testID,
127
+ role: accessibilityRole ?? domProps.role,
128
+ 'data-hozo-pointer-events': pointerEvents,
129
+ 'data-hozo-disabled': accessibilityState?.disabled ? '' : undefined,
130
+ 'data-hozo-horizontal': horizontal ? '' : undefined,
131
+ 'data-hozo-hide-scrollbar': hideScrollbar ? '' : undefined,
132
+ 'aria-label': accessibilityLabel,
133
+ 'aria-description': accessibilityHint,
134
+ 'aria-disabled': accessibilityState?.disabled,
135
+ 'aria-selected': accessibilityState?.selected,
136
+ 'aria-checked': accessibilityState?.checked,
137
+ 'aria-busy': accessibilityState?.busy || activeRefreshing || undefined,
138
+ 'aria-expanded': accessibilityState?.expanded,
139
+ 'aria-valuemin': accessibilityValue?.min,
140
+ 'aria-valuemax': accessibilityValue?.max,
141
+ 'aria-valuenow': accessibilityValue?.now,
142
+ 'aria-valuetext': accessibilityValue?.text,
143
+ 'aria-live': accessibilityLiveRegion === 'none' ? undefined : accessibilityLiveRegion,
144
+ style: { ...viewport, ...hozoDomStyle(style) },
145
+ onPointerDown: onScrollBeginDrag || responder.onPointerDown || onPointerDown
146
+ ? (event) => {
147
+ emitTo(onScrollBeginDrag);
148
+ responder.onPointerDown?.(event);
149
+ onPointerDown?.(event);
150
+ }
151
+ : undefined,
152
+ onPointerDownCapture: responder.onPointerDownCapture || onPointerDownCapture
153
+ ? (event) => {
154
+ responder.onPointerDownCapture?.(event);
155
+ onPointerDownCapture?.(event);
156
+ }
157
+ : undefined,
158
+ onPointerMove: responder.onPointerMove || onPointerMove
159
+ ? (event) => {
160
+ responder.onPointerMove?.(event);
161
+ onPointerMove?.(event);
162
+ }
163
+ : undefined,
164
+ onPointerMoveCapture: responder.onPointerMoveCapture || onPointerMoveCapture
165
+ ? (event) => {
166
+ responder.onPointerMoveCapture?.(event);
167
+ onPointerMoveCapture?.(event);
168
+ }
169
+ : undefined,
170
+ onPointerUp: onScrollEndDrag || responder.onPointerUp || onPointerUp
171
+ ? (event) => {
172
+ emitTo(onScrollEndDrag);
173
+ responder.onPointerUp?.(event);
174
+ onPointerUp?.(event);
175
+ }
176
+ : undefined,
177
+ onPointerCancel: responder.onPointerCancel || onPointerCancel
178
+ ? (event) => {
179
+ responder.onPointerCancel?.(event);
180
+ onPointerCancel?.(event);
181
+ }
182
+ : undefined,
183
+ onLostPointerCapture: responder.onLostPointerCapture || onLostPointerCapture
184
+ ? (event) => {
185
+ responder.onLostPointerCapture?.(event);
186
+ onLostPointerCapture?.(event);
187
+ }
188
+ : undefined,
189
+ onScroll: () => {
190
+ const now = Date.now();
191
+ const event = emitScroll();
192
+ if (!event)
193
+ return;
194
+ if (onScroll &&
195
+ (scrollEventThrottle <= 0 || now - lastScroll.current >= scrollEventThrottle)) {
196
+ lastScroll.current = now;
197
+ onScroll(event);
198
+ }
199
+ },
200
+ onScrollEnd: onMomentumScrollEnd ? () => emitTo(onMomentumScrollEnd) : undefined,
201
+ }, activeRefresh
202
+ ? createElement(HozoRefreshControl, {
203
+ refreshing: activeRefreshing,
204
+ onRefresh: activeRefresh,
205
+ })
206
+ : null, createElement('div', { ref: contentRef, style: hozoDomStyle(contentContainerStyle) }, children));
207
+ });
208
+ const separators = { highlight() { }, unhighlight() { }, updateProps() { } };
209
+ /** The mirror `inverted` applies, in React Native's own spelling. */
210
+ function invertedTransform(horizontal) {
211
+ return horizontal ? [{ scaleX: -1 }] : [{ scaleY: -1 }];
212
+ }
213
+ function HozoFlatListInner(props, forwardedRef) {
214
+ const { data = [], renderItem, keyExtractor, ListHeaderComponent, ListFooterComponent, ListEmptyComponent, ItemSeparatorComponent, numColumns = 1, horizontal, inverted, contentContainerStyle, style, onEndReached,
215
+ // React Native's default, read from `VirtualizedListProps`. This file
216
+ // used to default it to 0, which asks for the callback only once the
217
+ // very last pixel is on screen.
218
+ onEndReachedThreshold = 2, initialNumToRender = 10, windowSize = 21, maxToRenderPerBatch = 10, getItemLayout, estimatedItemSize = 100, maintainVisibleContentPosition, removeClippedSubviews: _removeClippedSubviews, extraData: _extraData, ...scrollProps } = props;
219
+ const items = data ?? [];
220
+ const columns = Math.max(1, Math.floor(numColumns));
221
+ // Rows, not items, are what gets windowed. A two-column grid scrolls by
222
+ // rows, so a window measured in items would mount half a row at each
223
+ // edge and measure heights that no row has.
224
+ const rows = useMemo(() => {
225
+ const grouped = [];
226
+ for (let start = 0; start < items.length; start += columns) {
227
+ const slice = items.slice(start, start + columns);
228
+ const first = slice[0];
229
+ grouped.push({ key: keyExtractor?.(first, start) ?? String(start), start, items: slice });
230
+ }
231
+ return grouped;
232
+ // `items` by identity: a caller handing a fresh array of the same data
233
+ // every render is ordinary React, and regrouping is cheap next to
234
+ // rendering.
235
+ }, [items, columns, keyExtractor]);
236
+ const rowKeys = useMemo(() => rows.map((row) => row.key), [rows]);
237
+ const metricsRef = useRef(undefined);
238
+ if (metricsRef.current === undefined)
239
+ metricsRef.current = new ListMetrics(estimatedItemSize);
240
+ const metrics = metricsRef.current;
241
+ metrics.setEstimate(estimatedItemSize);
242
+ metrics.setKeys(rowKeys);
243
+ // Exact geometry replaces measurement entirely when the caller has it and
244
+ // there is one item per row -- the case `getItemLayout` was written for.
245
+ const exact = getItemLayout && columns === 1 ? getItemLayout : undefined;
246
+ const geometry = useMemo(() => exact
247
+ ? {
248
+ offsetAt: (index) => index <= 0
249
+ ? 0
250
+ : index >= rows.length
251
+ ? exact(data, rows.length - 1).offset + exact(data, rows.length - 1).length
252
+ : exact(data, index).offset,
253
+ lengthAt: (index) => exact(data, Math.min(index, rows.length - 1)).length,
254
+ }
255
+ : metrics, [exact, data, rows.length, metrics]);
256
+ const rootRef = useRef(null);
257
+ const endRef = useRef(null);
258
+ const [range, setRange] = useState(() => initialRange(rows.length, initialNumToRender));
259
+ const rangeRef = useRef(range);
260
+ rangeRef.current = range;
261
+ const scrollRef = useRef({ offset: 0, velocity: 0, time: 0 });
262
+ const emitRef = useRef(0);
263
+ /**
264
+ * Rows kept mounted around wherever focus is, on top of the scroll window.
265
+ *
266
+ * Two things break without it. Focus lands on a row, the reader scrolls,
267
+ * that row leaves the window, React unmounts it -- and focus falls back to
268
+ * `<body>`, which loses their place entirely. And tabbing forward through
269
+ * a long list walks to the last mounted row and finds nothing after it,
270
+ * because there is nothing after it in the document.
271
+ *
272
+ * `FOCUS_MARGIN` rows either side, so stepping past the edge has somewhere
273
+ * to go before the next recompute catches up.
274
+ */
275
+ const focusRowRef = useRef(null);
276
+ /** Recomputes the window from wherever the scroller and focus currently are. */
277
+ const recompute = useCallback(() => {
278
+ const root = rootRef.current;
279
+ if (!root)
280
+ return;
281
+ const visibleLength = horizontal ? root.clientWidth : root.clientHeight;
282
+ // Before the first layout the viewport is zero and every window is
283
+ // empty, which would unmount the rows the first render put there.
284
+ if (visibleLength === 0)
285
+ return;
286
+ const scrolled = windowRange({
287
+ count: rows.length,
288
+ offset: horizontal ? root.scrollLeft : root.scrollTop,
289
+ visibleLength,
290
+ windowSize,
291
+ maxToRenderPerBatch,
292
+ velocity: scrollRef.current.velocity,
293
+ previous: rangeRef.current,
294
+ metrics: geometry,
295
+ });
296
+ const next = withFocus(scrolled, focusRowRef.current, rows.length);
297
+ if (next.first === rangeRef.current.first && next.last === rangeRef.current.last)
298
+ return;
299
+ rangeRef.current = next;
300
+ setRange(next);
301
+ }, [geometry, horizontal, maxToRenderPerBatch, rows.length, windowSize]);
302
+ /**
303
+ * Recomputes now, rather than on the next frame.
304
+ *
305
+ * This went through `requestAnimationFrame` first, which is the usual
306
+ * advice and was wrong here twice over. It is unnecessary -- the work is
307
+ * two binary searches and a prefix sum that only rebuilds when something
308
+ * was measured -- and it is unreliable: a frame callback is tied to the
309
+ * compositor producing frames, and in headless Chrome under a virtual
310
+ * time budget it simply never ran. The window stayed on row 0 through a
311
+ * 200,000px scroll, and `scripts/check-list.mjs` is what said so.
312
+ */
313
+ const scheduleRecompute = recompute;
314
+ // A row that mounted is a row that can be measured, and one pass of that
315
+ // usually changes the window -- so the window is recomputed after every
316
+ // commit rather than only on scroll.
317
+ useEffect(() => {
318
+ recompute();
319
+ });
320
+ useEffect(() => {
321
+ const root = rootRef.current;
322
+ if (!root || typeof ResizeObserver === 'undefined')
323
+ return;
324
+ const observer = new ResizeObserver(() => recompute());
325
+ observer.observe(root);
326
+ return () => observer.disconnect();
327
+ }, [recompute]);
328
+ // Where focus is, as a row index. `focusin` and `focusout` bubble, so one
329
+ // pair of listeners on the scroller covers every row in it -- including
330
+ // the ones mounted after this ran.
331
+ useEffect(() => {
332
+ const root = rootRef.current;
333
+ if (!root)
334
+ return;
335
+ const rowOf = (target) => {
336
+ if (!(target instanceof Element))
337
+ return null;
338
+ const row = target.closest('[data-hozo-list-row]');
339
+ if (!row || !root.contains(row))
340
+ return null;
341
+ const index = Number(row.dataset.hozoListRow);
342
+ return Number.isFinite(index) ? index : null;
343
+ };
344
+ const onFocusIn = (event) => {
345
+ const row = rowOf(event.target);
346
+ if (row === focusRowRef.current)
347
+ return;
348
+ focusRowRef.current = row;
349
+ recompute();
350
+ };
351
+ const onFocusOut = (event) => {
352
+ // Only when focus left the list entirely. Moving between two rows
353
+ // fires this for the one being left, and forgetting the row there
354
+ // would unmount the row focus is arriving at.
355
+ if (rowOf(event.relatedTarget) !== null)
356
+ return;
357
+ if (focusRowRef.current === null)
358
+ return;
359
+ focusRowRef.current = null;
360
+ recompute();
361
+ };
362
+ root.addEventListener('focusin', onFocusIn);
363
+ root.addEventListener('focusout', onFocusOut);
364
+ return () => {
365
+ root.removeEventListener('focusin', onFocusIn);
366
+ root.removeEventListener('focusout', onFocusOut);
367
+ };
368
+ }, [recompute]);
369
+ /**
370
+ * Records what a mounted row measured.
371
+ *
372
+ * A `ref` callback plus one shared `ResizeObserver` rather than an
373
+ * observer per row: a window is up to twenty viewports of rows, and an
374
+ * observer each is twenty viewports of observers.
375
+ *
376
+ * The row leaving the window has to stop being observed, and that is not
377
+ * a tidiness point. A `ResizeObserver` keeps reporting an element after
378
+ * React removes it from the document, and a removed element measures
379
+ * zero by zero -- so every row that scrolled out of the window wrote a
380
+ * height of 0 into the store, the mean of the measured rows fell towards
381
+ * nothing, and ten thousand rows came to a scrollable length of 7,138px.
382
+ * The list then had eleven rows in it and the scroll position was
383
+ * meaningless. `scripts/check-list.mjs` is what found that; nothing
384
+ * without layout could have.
385
+ */
386
+ // The observer is created once and outlives the render that made it, so
387
+ // what its callback calls has to be read at call time rather than closed
388
+ // over. Captured directly, it would still be holding the first render's
389
+ // `rowKeys` and `geometry` after a data change -- and then correcting a
390
+ // scroll position against a list that no longer exists.
391
+ const latestRef = useRef({ recompute: () => { }, applyPin: () => { } });
392
+ const observerRef = useRef(null);
393
+ const observedRef = useRef(new Map());
394
+ const elementsRef = useRef(new Map());
395
+ const measure = useCallback((element, key) => {
396
+ if (typeof ResizeObserver === 'undefined')
397
+ return;
398
+ const observed = observedRef.current;
399
+ const elements = elementsRef.current;
400
+ const previous = elements.get(key);
401
+ if (previous && previous !== element) {
402
+ observerRef.current?.unobserve(previous);
403
+ observed.delete(previous);
404
+ elements.delete(key);
405
+ }
406
+ if (!element)
407
+ return;
408
+ if (!observerRef.current) {
409
+ observerRef.current = new ResizeObserver((entries) => {
410
+ let changed = false;
411
+ for (const entry of entries) {
412
+ const entryKey = observedRef.current.get(entry.target);
413
+ if (entryKey === undefined)
414
+ continue;
415
+ // The second half of the same defence: an entry can be queued
416
+ // for an element that has since left the document, and its box
417
+ // is zero.
418
+ if (!entry.target.isConnected)
419
+ continue;
420
+ const box = entry.target.getBoundingClientRect();
421
+ if (metrics.measure(entryKey, horizontal ? box.width : box.height))
422
+ changed = true;
423
+ }
424
+ if (!changed)
425
+ return;
426
+ latestRef.current.recompute();
427
+ latestRef.current.applyPin();
428
+ });
429
+ }
430
+ observed.set(element, key);
431
+ elements.set(key, element);
432
+ observerRef.current.observe(element);
433
+ }, [horizontal, metrics]);
434
+ useEffect(() => () => {
435
+ observerRef.current?.disconnect();
436
+ observerRef.current = null;
437
+ observedRef.current.clear();
438
+ elementsRef.current.clear();
439
+ }, []);
440
+ const pinRef = useRef(null);
441
+ const anchorRef = useRef(undefined);
442
+ const previousKeysRef = useRef(rowKeys);
443
+ const pinTo = useCallback((key, screenOffset) => {
444
+ pinRef.current = {
445
+ key,
446
+ screenOffset,
447
+ applied: Number.NaN,
448
+ left: 20,
449
+ // A wall clock as well as a budget. A pin that waits for a
450
+ // measurement that never comes -- a row removed while off screen, a
451
+ // list nobody is looking at -- would otherwise sit there and move the
452
+ // page much later, on a change it has nothing to do with.
453
+ until: Date.now() + 2000,
454
+ };
455
+ }, []);
456
+ /**
457
+ * Puts the pinned row back where it belongs, if it has moved.
458
+ *
459
+ * Called after every commit *and* from the measurement callback, and the
460
+ * second is the one that matters. A pin's first target is computed from
461
+ * estimated row heights, so it is right to within an estimate; the real
462
+ * answer only arrives when the rows near it report their sizes, and that
463
+ * does not always change the window, so it does not always cause a
464
+ * commit. Waiting for one left `scrollToIndex(5000)` sitting 1,204px
465
+ * short.
466
+ *
467
+ * Silent when it is already right, rather than releasing: being in the
468
+ * right place according to an estimate is exactly the state this exists
469
+ * to correct.
470
+ */
471
+ const applyPin = useCallback(() => {
472
+ const root = rootRef.current;
473
+ const pin = pinRef.current;
474
+ if (!root || !pin)
475
+ return;
476
+ const offset = horizontal ? root.scrollLeft : root.scrollTop;
477
+ if (!Number.isNaN(pin.applied) && Math.abs(offset - pin.applied) > 1) {
478
+ // The reader moved. The pin is theirs to override, and a list that
479
+ // scrolled itself back would be worse than one that landed short.
480
+ pinRef.current = null;
481
+ return;
482
+ }
483
+ const index = rowKeys.indexOf(pin.key);
484
+ if (index === -1 || pin.left <= 0 || Date.now() > pin.until) {
485
+ pinRef.current = null;
486
+ return;
487
+ }
488
+ const target = Math.max(0, geometry.offsetAt(index) - pin.screenOffset);
489
+ if (Math.abs(target - offset) < 1)
490
+ return;
491
+ pin.left -= 1;
492
+ root.scrollTo({ [horizontal ? 'left' : 'top']: target });
493
+ pin.applied = horizontal ? root.scrollLeft : root.scrollTop;
494
+ }, [geometry, horizontal, rowKeys]);
495
+ latestRef.current = { recompute, applyPin };
496
+ // `maintainVisibleContentPosition`: the row the reader is looking at
497
+ // stays where it is when rows arrive above it. Anchored by key rather
498
+ // than by index, because a feed that prepends renumbers every index and
499
+ // no arithmetic on indices survives that.
500
+ //
501
+ // Ordered before the effect that applies a pin, and that is not a
502
+ // preference. A pin left over from a `scrollToIndex` would otherwise
503
+ // correct first, against the new list -- moving the scroll by the height
504
+ // of what was inserted -- and this effect would then read the corrected
505
+ // offset as though it were where the reader had been, and pin the anchor
506
+ // that far out. Measured: the reader's row moved 996px, which is what ten
507
+ // inserted rows are worth.
508
+ useLayoutEffect(() => {
509
+ const root = rootRef.current;
510
+ const previousKeys = previousKeysRef.current;
511
+ previousKeysRef.current = rowKeys;
512
+ if (!root || previousKeys === rowKeys)
513
+ return;
514
+ // Whatever was being held in place was being held in a list that no
515
+ // longer exists.
516
+ pinRef.current = null;
517
+ if (!maintainVisibleContentPosition || previousKeys.length === 0)
518
+ return;
519
+ const anchor = anchorRef.current;
520
+ if (!anchor)
521
+ return;
522
+ const offset = horizontal ? root.scrollLeft : root.scrollTop;
523
+ const threshold = maintainVisibleContentPosition.autoscrollToTopThreshold;
524
+ if (threshold !== undefined && offset <= threshold) {
525
+ root.scrollTo({ [horizontal ? 'left' : 'top']: 0 });
526
+ return;
527
+ }
528
+ if (rowKeys.indexOf(anchor.key) === -1)
529
+ return;
530
+ pinTo(anchor.key, anchor.offset - offset);
531
+ }, [rowKeys, maintainVisibleContentPosition, horizontal, pinTo]);
532
+ useLayoutEffect(applyPin);
533
+ /**
534
+ * Where the reader is, as a row and its offset.
535
+ *
536
+ * Recorded after every commit *and* on every scroll. A commit alone is
537
+ * not enough: a list can be scrolled a long way with nothing re-rendering
538
+ * once the window covers where it went, and an anchor left over from
539
+ * before that describes somebody who has moved on. Measured -- gating
540
+ * this on "no pin is active" left a stale anchor from before a
541
+ * `scrollToIndex`, and the next prepend moved the reader 1,329px.
542
+ */
543
+ const recordAnchor = useCallback(() => {
544
+ const root = rootRef.current;
545
+ if (!root || !maintainVisibleContentPosition)
546
+ return;
547
+ anchorRef.current = anchorRow(rowKeys, geometry, horizontal ? root.scrollLeft : root.scrollTop, maintainVisibleContentPosition.minIndexForVisible);
548
+ }, [geometry, horizontal, maintainVisibleContentPosition, rowKeys]);
549
+ useEffect(recordAnchor);
550
+ const setRoot = useCallback((element) => {
551
+ if (!element) {
552
+ rootRef.current = null;
553
+ assignRef(forwardedRef, null);
554
+ return;
555
+ }
556
+ const handle = element;
557
+ const axis = horizontal ? 'left' : 'top';
558
+ handle.scrollToOffset = ({ offset, animated }) => handle.scrollTo({ [axis]: offset, behavior: animated ? 'smooth' : 'auto' });
559
+ handle.scrollToEnd = ({ animated } = {}) => handle.scrollTo({
560
+ [axis]: horizontal ? handle.scrollWidth : handle.scrollHeight,
561
+ behavior: animated ? 'smooth' : 'auto',
562
+ });
563
+ handle.scrollToIndex = ({ index, animated, viewOffset = 0 }) => {
564
+ // React Native throws here when the target has not been measured
565
+ // and there is no `getItemLayout`. This scrolls to the estimate
566
+ // instead and pins the row until the rows that land there report
567
+ // their real sizes -- the reader sees one settle rather than an
568
+ // exception. Measured: the first version of this stopped after
569
+ // five timeouts, all of which ran before any measurement did, and
570
+ // left row 5,000 sitting 1,603px below the top of the viewport.
571
+ const row = Math.floor(Math.max(0, Math.min(index, items.length - 1)) / columns);
572
+ handle.scrollTo({
573
+ [axis]: Math.max(0, geometry.offsetAt(row) - viewOffset),
574
+ behavior: animated ? 'smooth' : 'auto',
575
+ });
576
+ const key = rowKeys[row];
577
+ if (key !== undefined)
578
+ pinTo(key, viewOffset);
579
+ };
580
+ rootRef.current = handle;
581
+ assignRef(forwardedRef, handle);
582
+ }, [columns, forwardedRef, geometry, horizontal, items.length, pinTo, rowKeys]);
583
+ // `range.last` is in the dependencies and not read in the body, on
584
+ // purpose. The sentinel sits after the *rendered* window rather than after
585
+ // the data, so it is a different element every time the window moves, and
586
+ // an observer left on the old one is watching a node that is gone.
587
+ // biome-ignore lint/correctness/useExhaustiveDependencies: see above
588
+ useEffect(() => {
589
+ const root = rootRef.current;
590
+ const target = endRef.current;
591
+ if (!root || !target || !onEndReached || rows.length === 0)
592
+ return;
593
+ if (typeof IntersectionObserver === 'undefined')
594
+ return;
595
+ let fired = false;
596
+ const margin = `${Math.max(0, onEndReachedThreshold) * 100}%`;
597
+ const observer = new IntersectionObserver(([entry]) => {
598
+ if (!entry?.isIntersecting || fired)
599
+ return;
600
+ fired = true;
601
+ observer.disconnect();
602
+ onEndReached({ distanceFromEnd: 0 });
603
+ }, { root, rootMargin: horizontal ? `0px ${margin} 0px 0px` : `0px 0px ${margin} 0px` });
604
+ observer.observe(target);
605
+ return () => observer.disconnect();
606
+ // The sentinel sits after the *rendered* window rather than after the
607
+ // data, so it moves as the window does. Re-observed on every window
608
+ // change for that reason, and re-armed on a data change so a feed that
609
+ // paginates can reach the end more than once.
610
+ }, [rows.length, range.last, horizontal, onEndReached, onEndReachedThreshold]);
611
+ const first = Math.max(0, range.first);
612
+ const last = Math.min(rows.length - 1, range.last);
613
+ const leading = rows.length === 0 ? 0 : geometry.offsetAt(first);
614
+ const total = rows.length === 0 ? 0 : geometry.offsetAt(rows.length);
615
+ const trailing = rows.length === 0 ? 0 : Math.max(0, total - geometry.offsetAt(last + 1));
616
+ const mounted = [];
617
+ for (let index = first; index <= last; index++) {
618
+ const row = rows[index];
619
+ if (!row)
620
+ continue;
621
+ const cells = row.items.map((item, column) => createElement('div', {
622
+ key: keyExtractor?.(item, row.start + column) ?? row.start + column,
623
+ role: 'listitem',
624
+ // How long the list is, and where this row is in it.
625
+ //
626
+ // Without these a screen reader announces what is *mounted*: a
627
+ // ten-thousand-row feed reads as "list, 67 items", and the reader
628
+ // has no way to know otherwise, because the other 9,933 rows are
629
+ // not in the accessibility tree to be counted. They are the one
630
+ // thing about virtualisation the Web can answer completely, and
631
+ // `@hozo/core`'s `Tree` already does the same for its rows.
632
+ 'aria-setsize': items.length,
633
+ 'aria-posinset': row.start + column + 1,
634
+ 'data-hozo-list-index': row.start + column,
635
+ }, renderItem({ item, index: row.start + column, separators })));
636
+ mounted.push(createElement('div', {
637
+ key: row.key,
638
+ ref: (element) => measure(element, row.key),
639
+ // Out of the accessibility tree, so the `listitem`s inside it are
640
+ // owned by the `list` above it. ARIA requires that relationship,
641
+ // and this wrapper -- which exists to be measured, and to be the
642
+ // grid row when there is more than one column -- broke it the
643
+ // moment windowing introduced it.
644
+ role: 'presentation',
645
+ 'data-hozo-list-row': index,
646
+ style: {
647
+ ...(columns > 1
648
+ ? {
649
+ display: 'grid',
650
+ gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))`,
651
+ }
652
+ : undefined),
653
+ ...(inverted ? hozoDomStyle({ transform: invertedTransform(horizontal) }) : undefined),
654
+ },
655
+ }, cells,
656
+ // Inside the row rather than beside it, so a row's measured size is
657
+ // the space it actually occupies and the window arithmetic has one
658
+ // kind of thing to reason about.
659
+ index < rows.length - 1 && ItemSeparatorComponent
660
+ ? createElement('div', { key: 'separator', role: 'presentation' }, renderSlot(ItemSeparatorComponent))
661
+ : null));
662
+ }
663
+ // The rows that are not mounted, as space rather than as elements. Padding
664
+ // on the container rather than spacer siblings: the container may be a
665
+ // grid or a flex row, and a spacer would take a cell in one and a column
666
+ // in the other.
667
+ const padStart = horizontal ? 'paddingLeft' : 'paddingTop';
668
+ const padEnd = horizontal ? 'paddingRight' : 'paddingBottom';
669
+ const slotStyle = inverted
670
+ ? hozoDomStyle({ transform: invertedTransform(horizontal) })
671
+ : undefined;
672
+ const slot = (node) => node == null || !inverted ? node : createElement('div', { style: slotStyle }, node);
673
+ return createElement(HozoScrollView, {
674
+ ...scrollProps,
675
+ horizontal,
676
+ contentContainerStyle,
677
+ style: inverted ? [style, { transform: invertedTransform(horizontal) }] : style,
678
+ ref: setRoot,
679
+ onScroll: (event) => {
680
+ const now = Date.now();
681
+ const offset = horizontal
682
+ ? event.nativeEvent.contentOffset.x
683
+ : event.nativeEvent.contentOffset.y;
684
+ const previous = scrollRef.current;
685
+ const dt = now - previous.time;
686
+ scrollRef.current = {
687
+ offset,
688
+ velocity: dt > 0 ? (offset - previous.offset) / dt : 0,
689
+ time: now,
690
+ };
691
+ scheduleRecompute();
692
+ recordAnchor();
693
+ // The caller's throttle applied here rather than upstream. The
694
+ // window has to keep up with the scroller whatever the caller
695
+ // asked to hear about, so this listens to every event and rations
696
+ // only what it passes on.
697
+ const throttle = props.scrollEventThrottle ?? 0;
698
+ if (throttle <= 0 || now - emitRef.current >= throttle) {
699
+ emitRef.current = now;
700
+ props.onScroll?.(event);
701
+ }
702
+ },
703
+ scrollEventThrottle: 0,
704
+ }, slot(renderSlot(ListHeaderComponent)), rows.length === 0 ? slot(renderSlot(ListEmptyComponent)) : null, rows.length > 0
705
+ ? createElement('div', {
706
+ role: 'list',
707
+ 'data-hozo-list-count': items.length,
708
+ style: {
709
+ [padStart]: leading,
710
+ [padEnd]: trailing,
711
+ ...(horizontal ? { display: 'flex', flexDirection: 'row' } : undefined),
712
+ },
713
+ }, mounted)
714
+ : null, slot(renderSlot(ListFooterComponent)), createElement('div', { ref: endRef, 'aria-hidden': true }));
715
+ }
716
+ export const HozoFlatList = forwardRef(HozoFlatListInner);
717
+ export { HozoFlatList as FlatList, HozoScrollView as ScrollView };
718
+ //# sourceMappingURL=index.js.map