@knitui/components 0.3.0 → 0.5.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 (97) hide show
  1. package/README.md +2 -2
  2. package/lib/commonjs/ActionIcon/ActionIcon.js.map +1 -1
  3. package/lib/commonjs/Alert/Alert.js.map +1 -1
  4. package/lib/commonjs/Avatar/Avatar.js.map +1 -1
  5. package/lib/commonjs/Badge/Badge.js.map +1 -1
  6. package/lib/commonjs/Button/Button.js.map +1 -1
  7. package/lib/commonjs/ColorPicker/ColorPicker.js.map +1 -1
  8. package/lib/commonjs/Image/createImage.js +48 -2
  9. package/lib/commonjs/Image/createImage.js.map +1 -1
  10. package/lib/commonjs/PinInput/PinInput.js.map +1 -1
  11. package/lib/commonjs/ScrollArea/ScrollArea.native.js +18 -0
  12. package/lib/commonjs/ScrollArea/ScrollArea.native.js.map +1 -1
  13. package/lib/commonjs/ScrollArea/ScrollArea.shared.js.map +1 -1
  14. package/lib/commonjs/ThemeIcon/ThemeIcon.js.map +1 -1
  15. package/lib/commonjs/Title/Title.js.map +1 -1
  16. package/lib/commonjs/Transition/use-transition.js.map +1 -1
  17. package/lib/commonjs/UnstyledButton/UnstyledButton.js +12 -0
  18. package/lib/commonjs/UnstyledButton/UnstyledButton.js.map +1 -1
  19. package/lib/commonjs/VirtualList/VirtualList.js +311 -0
  20. package/lib/commonjs/VirtualList/VirtualList.js.map +1 -0
  21. package/lib/commonjs/VirtualList/VirtualList.shared.js +233 -0
  22. package/lib/commonjs/VirtualList/VirtualList.shared.js.map +1 -0
  23. package/lib/commonjs/VirtualList/index.js +17 -0
  24. package/lib/commonjs/VirtualList/index.js.map +1 -0
  25. package/lib/commonjs/index.js +7 -0
  26. package/lib/commonjs/index.js.map +1 -1
  27. package/lib/module/ActionIcon/ActionIcon.js.map +1 -1
  28. package/lib/module/Alert/Alert.js.map +1 -1
  29. package/lib/module/Avatar/Avatar.js.map +1 -1
  30. package/lib/module/Badge/Badge.js.map +1 -1
  31. package/lib/module/Button/Button.js.map +1 -1
  32. package/lib/module/ColorPicker/ColorPicker.js.map +1 -1
  33. package/lib/module/Image/createImage.js +48 -2
  34. package/lib/module/Image/createImage.js.map +1 -1
  35. package/lib/module/PinInput/PinInput.js.map +1 -1
  36. package/lib/module/ScrollArea/ScrollArea.native.js +18 -0
  37. package/lib/module/ScrollArea/ScrollArea.native.js.map +1 -1
  38. package/lib/module/ScrollArea/ScrollArea.shared.js.map +1 -1
  39. package/lib/module/ThemeIcon/ThemeIcon.js.map +1 -1
  40. package/lib/module/Title/Title.js.map +1 -1
  41. package/lib/module/Transition/use-transition.js.map +1 -1
  42. package/lib/module/UnstyledButton/UnstyledButton.js +13 -1
  43. package/lib/module/UnstyledButton/UnstyledButton.js.map +1 -1
  44. package/lib/module/VirtualList/VirtualList.js +306 -0
  45. package/lib/module/VirtualList/VirtualList.js.map +1 -0
  46. package/lib/module/VirtualList/VirtualList.shared.js +222 -0
  47. package/lib/module/VirtualList/VirtualList.shared.js.map +1 -0
  48. package/lib/module/VirtualList/index.js +4 -0
  49. package/lib/module/VirtualList/index.js.map +1 -0
  50. package/lib/module/index.js +1 -0
  51. package/lib/module/index.js.map +1 -1
  52. package/lib/typescript/ActionIcon/ActionIcon.d.ts.map +1 -1
  53. package/lib/typescript/Alert/Alert.d.ts.map +1 -1
  54. package/lib/typescript/Avatar/Avatar.d.ts.map +1 -1
  55. package/lib/typescript/Badge/Badge.d.ts.map +1 -1
  56. package/lib/typescript/Button/Button.d.ts.map +1 -1
  57. package/lib/typescript/ColorPicker/ColorPicker.d.ts.map +1 -1
  58. package/lib/typescript/FileButton/FileButton.types.d.ts.map +1 -1
  59. package/lib/typescript/Image/createImage.d.ts.map +1 -1
  60. package/lib/typescript/PinInput/PinInput.d.ts.map +1 -1
  61. package/lib/typescript/ScrollArea/ScrollArea.native.d.ts.map +1 -1
  62. package/lib/typescript/ScrollArea/ScrollArea.shared.d.ts +14 -0
  63. package/lib/typescript/ScrollArea/ScrollArea.shared.d.ts.map +1 -1
  64. package/lib/typescript/ThemeIcon/ThemeIcon.d.ts.map +1 -1
  65. package/lib/typescript/Title/Title.d.ts.map +1 -1
  66. package/lib/typescript/Transition/use-transition.d.ts.map +1 -1
  67. package/lib/typescript/Tree/Tree.d.ts +1 -1
  68. package/lib/typescript/Tree/Tree.d.ts.map +1 -1
  69. package/lib/typescript/UnstyledButton/UnstyledButton.d.ts.map +1 -1
  70. package/lib/typescript/VirtualList/VirtualList.d.ts +15 -0
  71. package/lib/typescript/VirtualList/VirtualList.d.ts.map +1 -0
  72. package/lib/typescript/VirtualList/VirtualList.shared.d.ts +188 -0
  73. package/lib/typescript/VirtualList/VirtualList.shared.d.ts.map +1 -0
  74. package/lib/typescript/VirtualList/index.d.ts +3 -0
  75. package/lib/typescript/VirtualList/index.d.ts.map +1 -0
  76. package/lib/typescript/index.d.ts +1 -0
  77. package/lib/typescript/index.d.ts.map +1 -1
  78. package/package.json +13 -13
  79. package/src/ActionIcon/ActionIcon.tsx +1 -8
  80. package/src/Alert/Alert.tsx +1 -7
  81. package/src/Avatar/Avatar.tsx +1 -7
  82. package/src/Badge/Badge.tsx +1 -8
  83. package/src/Button/Button.tsx +1 -8
  84. package/src/ColorPicker/ColorPicker.tsx +1 -2
  85. package/src/FileButton/FileButton.types.ts +2 -11
  86. package/src/Image/createImage.tsx +45 -2
  87. package/src/PinInput/PinInput.tsx +1 -8
  88. package/src/ScrollArea/ScrollArea.native.tsx +17 -0
  89. package/src/ScrollArea/ScrollArea.shared.ts +16 -0
  90. package/src/ThemeIcon/ThemeIcon.tsx +1 -8
  91. package/src/Title/Title.tsx +1 -13
  92. package/src/Transition/use-transition.ts +1 -6
  93. package/src/UnstyledButton/UnstyledButton.tsx +19 -1
  94. package/src/VirtualList/VirtualList.shared.ts +359 -0
  95. package/src/VirtualList/VirtualList.tsx +379 -0
  96. package/src/VirtualList/index.ts +7 -0
  97. package/src/index.ts +8 -0
@@ -0,0 +1,379 @@
1
+ import * as React from "react";
2
+
3
+ import { type LayoutChangeEvent, styled } from "@knitui/core";
4
+
5
+ import { Box, type BoxProps } from "../Box";
6
+ import { slotStyles } from "../internal/styles";
7
+ import { ScrollArea, type ScrollAreaHandle } from "../ScrollArea";
8
+ import {
9
+ createLayoutState,
10
+ DEFAULT_DRAW_DISTANCE,
11
+ DEFAULT_END_REACHED_THRESHOLD,
12
+ DEFAULT_ESTIMATED_ITEM_SIZE,
13
+ findVisibleRange,
14
+ getContentSize,
15
+ getItemOffset,
16
+ type LayoutState,
17
+ resizeLayoutState,
18
+ setMeasured,
19
+ VIRTUAL_LIST_SLOTS,
20
+ type VirtualListHandle,
21
+ type VirtualListOwnProps,
22
+ type VirtualListStyles,
23
+ } from "./VirtualList.shared";
24
+
25
+ export type {
26
+ VirtualListHandle,
27
+ VirtualListRenderItemInfo,
28
+ VirtualListStyles,
29
+ } from "./VirtualList.shared";
30
+
31
+ /* -------------------------------------------------------------------------- */
32
+ /* Styled parts */
33
+ /* -------------------------------------------------------------------------- */
34
+
35
+ /**
36
+ * `VirtualList` — a fast, windowed, variable-height list that renders only the
37
+ * rows near the viewport (plus a render-ahead buffer) and recycles the rest by
38
+ * mounting/unmounting at the window edges. One source runs on web and native by
39
+ * riding {@link ScrollArea} (its scroll engine, custom scrollbars, and edge
40
+ * fades come for free) and driving windowing off `onScrollPositionChange`.
41
+ *
42
+ * Rows are absolutely positioned inside a total-height spacer; each row's real
43
+ * height is read back via `onLayout` and fed to a per-type running-average size
44
+ * model, so no exact `estimatedItemSize` is required (a closer seed just means
45
+ * less first-scroll correction). Mirrors the familiar `FlatList` / `FlashList`
46
+ * surface for the v1 subset: vertical, single-column lists.
47
+ */
48
+ const VirtualListFrame = styled(Box, {
49
+ name: "VirtualList",
50
+ position: "relative",
51
+ overflow: "hidden",
52
+ });
53
+
54
+ /** The total-size spacer that holds the absolutely-positioned rows. */
55
+ const VirtualListContent = styled(Box, {
56
+ name: "VirtualListContent",
57
+ position: "relative",
58
+ width: "100%",
59
+ });
60
+
61
+ /** One absolutely-positioned row wrapper (measured via `onLayout`). */
62
+ const VirtualListItem = styled(Box, {
63
+ name: "VirtualListItem",
64
+ position: "absolute",
65
+ left: 0,
66
+ right: 0,
67
+ });
68
+
69
+ /* -------------------------------------------------------------------------- */
70
+ /* Memoized row cell */
71
+ /* -------------------------------------------------------------------------- */
72
+
73
+ interface RowProps<T> {
74
+ item: T;
75
+ index: number;
76
+ top: number;
77
+ isLast: boolean;
78
+ renderItem: VirtualListOwnProps<T>["renderItem"];
79
+ getItemType?: VirtualListOwnProps<T>["getItemType"];
80
+ separator: React.ReactNode;
81
+ onMeasure: (index: number, height: number, type: string | number) => void;
82
+ itemProps: Partial<BoxProps>;
83
+ }
84
+
85
+ /**
86
+ * A single mounted row. Memoized so that pure scrolling — which only changes the
87
+ * *set* of mounted indices, not the props of rows that stay mounted — never
88
+ * re-runs `renderItem` for a surviving row. `top` only changes on relayout, so
89
+ * scroll alone is free.
90
+ */
91
+ const RowInner = <T,>({
92
+ item,
93
+ index,
94
+ top,
95
+ isLast,
96
+ renderItem,
97
+ getItemType,
98
+ separator,
99
+ onMeasure,
100
+ itemProps,
101
+ }: RowProps<T>) => {
102
+ const handleLayout = React.useCallback(
103
+ (e: LayoutChangeEvent) => {
104
+ const type = getItemType ? getItemType(item, index) : 0;
105
+ onMeasure(index, e.nativeEvent.layout.height, type);
106
+ },
107
+ [item, index, getItemType, onMeasure],
108
+ );
109
+ return (
110
+ <VirtualListItem top={top} onLayout={handleLayout} {...itemProps}>
111
+ {renderItem({ item, index })}
112
+ {isLast ? null : separator}
113
+ </VirtualListItem>
114
+ );
115
+ };
116
+ const Row = React.memo(RowInner) as typeof RowInner;
117
+
118
+ /* -------------------------------------------------------------------------- */
119
+ /* Public props */
120
+ /* -------------------------------------------------------------------------- */
121
+
122
+ type VirtualListFrameProps = Omit<BoxProps, "children">;
123
+
124
+ export interface VirtualListProps<T> extends VirtualListFrameProps, VirtualListOwnProps<T> {}
125
+
126
+ /* -------------------------------------------------------------------------- */
127
+ /* Implementation */
128
+ /* -------------------------------------------------------------------------- */
129
+
130
+ function VirtualListInner<T>(
131
+ props: VirtualListProps<T>,
132
+ ref: React.Ref<VirtualListHandle>,
133
+ ): React.ReactElement {
134
+ const {
135
+ data,
136
+ renderItem,
137
+ keyExtractor,
138
+ getItemType,
139
+ estimatedItemSize = DEFAULT_ESTIMATED_ITEM_SIZE,
140
+ drawDistance = DEFAULT_DRAW_DISTANCE,
141
+ extraData,
142
+ onEndReached,
143
+ onEndReachedThreshold = DEFAULT_END_REACHED_THRESHOLD,
144
+ onRenderedRangeChange,
145
+ ListHeaderComponent,
146
+ ListFooterComponent,
147
+ ListEmptyComponent,
148
+ ItemSeparatorComponent,
149
+ handleRef,
150
+ styles,
151
+ ...rest
152
+ } = props;
153
+
154
+ const slots = slotStyles<VirtualListStyles>(styles, VIRTUAL_LIST_SLOTS, "VirtualList");
155
+ const scrollAreaSlot = slots.get("scrollArea");
156
+ const contentSlot = slots.get("content");
157
+ const itemSlot = slots.get("item") ?? {};
158
+
159
+ const count = data.length;
160
+
161
+ // ── layout model (mutable, in a ref — never triggers a render by itself) ──
162
+ const layoutRef = React.useRef<LayoutState>(createLayoutState(count, estimatedItemSize));
163
+ // Keep the store sized to the data. Reset entirely if the seed changed.
164
+ if (layoutRef.current.estimate !== estimatedItemSize) {
165
+ layoutRef.current = createLayoutState(count, estimatedItemSize);
166
+ } else if (layoutRef.current.count !== count) {
167
+ resizeLayoutState(layoutRef.current, count);
168
+ }
169
+
170
+ // Live scroll offset lives in a ref so scrolling never re-renders on its own.
171
+ const scrollTopRef = React.useRef(0);
172
+ const viewportHRef = React.useRef(0);
173
+ const rangeRef = React.useRef<{ start: number; end: number }>({ start: 0, end: -1 });
174
+ const endReachedFiredRef = React.useRef(false);
175
+ const scrollAreaRef = React.useRef<ScrollAreaHandle | null>(null);
176
+
177
+ // The three pieces of state that DO drive re-renders: the mounted index range,
178
+ // the viewport height (needed for the first window), and a layout version bumped
179
+ // whenever a measurement shifts offsets (so rows re-position and the spacer resizes).
180
+ const [range, setRange] = React.useState<{ start: number; end: number }>({
181
+ start: 0,
182
+ end: -1,
183
+ });
184
+ const [viewportH, setViewportH] = React.useState(0);
185
+ const [layoutVersion, bumpLayout] = React.useReducer((v: number) => v + 1, 0);
186
+ const [headerH, setHeaderH] = React.useState(0);
187
+ const [footerH, setFooterH] = React.useState(0);
188
+
189
+ const maybeEndReached = React.useCallback(() => {
190
+ if (!onEndReached) return;
191
+ const vh = viewportHRef.current;
192
+ if (vh <= 0) return;
193
+ const total = getContentSize(layoutRef.current) + headerH + footerH;
194
+ const distanceFromEnd = total - (scrollTopRef.current + vh);
195
+ if (distanceFromEnd <= onEndReachedThreshold * vh) {
196
+ if (!endReachedFiredRef.current) {
197
+ endReachedFiredRef.current = true;
198
+ onEndReached();
199
+ }
200
+ } else {
201
+ endReachedFiredRef.current = false;
202
+ }
203
+ }, [onEndReached, onEndReachedThreshold, headerH, footerH]);
204
+
205
+ // Recompute the mounted range from the live scroll + viewport, and only commit
206
+ // to React state when the range actually changes (one render per row-crossing,
207
+ // not per scroll frame).
208
+ const recomputeRange = React.useCallback(() => {
209
+ const vh = viewportHRef.current;
210
+ const next = findVisibleRange(
211
+ layoutRef.current,
212
+ scrollTopRef.current - headerH,
213
+ vh,
214
+ drawDistance,
215
+ );
216
+ const prev = rangeRef.current;
217
+ if (next.start !== prev.start || next.end !== prev.end) {
218
+ rangeRef.current = next;
219
+ setRange(next);
220
+ onRenderedRangeChange?.(next);
221
+ }
222
+ }, [drawDistance, headerH, onRenderedRangeChange]);
223
+
224
+ const handleScroll = React.useCallback(
225
+ (pos: { x: number; y: number }) => {
226
+ scrollTopRef.current = pos.y;
227
+ recomputeRange();
228
+ maybeEndReached();
229
+ },
230
+ [recomputeRange, maybeEndReached],
231
+ );
232
+
233
+ const handleFrameLayout = React.useCallback((e: LayoutChangeEvent) => {
234
+ const h = e.nativeEvent.layout.height;
235
+ if (h === viewportHRef.current) return;
236
+ viewportHRef.current = h;
237
+ setViewportH(h);
238
+ }, []);
239
+
240
+ const handleMeasure = React.useCallback(
241
+ (index: number, height: number, type: string | number) => {
242
+ if (setMeasured(layoutRef.current, index, type, height)) {
243
+ bumpLayout();
244
+ }
245
+ },
246
+ [],
247
+ );
248
+
249
+ // After any commit that could move offsets (measurement, viewport, data, chrome),
250
+ // re-window and re-check the end. Runs post-layout so measurements are settled.
251
+ React.useEffect(() => {
252
+ recomputeRange();
253
+ maybeEndReached();
254
+ }, [
255
+ layoutVersion,
256
+ viewportH,
257
+ count,
258
+ headerH,
259
+ footerH,
260
+ extraData,
261
+ recomputeRange,
262
+ maybeEndReached,
263
+ ]);
264
+
265
+ /* ---------------- imperative handle ---------------- */
266
+
267
+ const scrollToOffset = React.useCallback((offset: number, animated?: boolean) => {
268
+ scrollAreaRef.current?.scrollTo({ y: offset, animated });
269
+ }, []);
270
+
271
+ const buildHandle = React.useCallback(
272
+ (): VirtualListHandle => ({
273
+ scrollToIndex: ({ index, animated, viewPosition = 0, viewOffset = 0 }) => {
274
+ const clamped = Math.max(0, Math.min(index, count - 1));
275
+ const top = headerH + getItemOffset(layoutRef.current, clamped);
276
+ const slack = viewPosition * viewportHRef.current;
277
+ scrollToOffset(top - slack - viewOffset, animated);
278
+ },
279
+ scrollToOffset: ({ offset, animated }) => scrollToOffset(offset, animated),
280
+ scrollToTop: (animated) => scrollToOffset(0, animated),
281
+ scrollToEnd: (animated) => {
282
+ const total = getContentSize(layoutRef.current) + headerH + footerH;
283
+ scrollToOffset(Math.max(0, total - viewportHRef.current), animated);
284
+ },
285
+ getScrollOffset: () => scrollTopRef.current,
286
+ }),
287
+ [count, headerH, footerH, scrollToOffset],
288
+ );
289
+
290
+ React.useImperativeHandle(ref, buildHandle, [buildHandle]);
291
+ React.useImperativeHandle(handleRef, buildHandle, [buildHandle]);
292
+
293
+ /* ---------------- render ---------------- */
294
+
295
+ const contentTotal = getContentSize(layoutRef.current);
296
+ const spacerHeight = headerH + contentTotal + footerH;
297
+ const isEmpty = count === 0;
298
+
299
+ const rows: React.ReactNode[] = [];
300
+ if (!isEmpty && range.end >= range.start) {
301
+ for (let i = range.start; i <= range.end; i++) {
302
+ const item = data[i];
303
+ const key = keyExtractor ? keyExtractor(item, i) : String(i);
304
+ rows.push(
305
+ <Row<T>
306
+ key={key}
307
+ item={item}
308
+ index={i}
309
+ top={headerH + getItemOffset(layoutRef.current, i)}
310
+ isLast={i === count - 1}
311
+ renderItem={renderItem}
312
+ getItemType={getItemType}
313
+ separator={ItemSeparatorComponent}
314
+ onMeasure={handleMeasure}
315
+ itemProps={itemSlot}
316
+ />,
317
+ );
318
+ }
319
+ }
320
+
321
+ return (
322
+ <VirtualListFrame onLayout={handleFrameLayout} {...(rest as BoxProps)}>
323
+ <ScrollArea
324
+ ref={scrollAreaRef}
325
+ scrollbars="y"
326
+ height="100%"
327
+ width="100%"
328
+ onScrollPositionChange={handleScroll}
329
+ // `scrollArea` slot is a `Partial<BoxProps>`; spread through an index
330
+ // signature so it doesn't collide with ScrollArea's narrowed `shadowColor`.
331
+ {...(scrollAreaSlot as Record<string, unknown>)}
332
+ >
333
+ {isEmpty ? (
334
+ ListEmptyComponent
335
+ ) : (
336
+ <VirtualListContent height={spacerHeight} {...contentSlot}>
337
+ {ListHeaderComponent != null && (
338
+ <Box
339
+ position="absolute"
340
+ top={0}
341
+ left={0}
342
+ right={0}
343
+ onLayout={(e: LayoutChangeEvent) => {
344
+ const h = e.nativeEvent.layout.height;
345
+ setHeaderH((prev) => (Math.abs(prev - h) > 0.5 ? h : prev));
346
+ }}
347
+ >
348
+ {ListHeaderComponent}
349
+ </Box>
350
+ )}
351
+ {rows}
352
+ {ListFooterComponent != null && (
353
+ <Box
354
+ position="absolute"
355
+ top={headerH + contentTotal}
356
+ left={0}
357
+ right={0}
358
+ onLayout={(e: LayoutChangeEvent) => {
359
+ const h = e.nativeEvent.layout.height;
360
+ setFooterH((prev) => (Math.abs(prev - h) > 0.5 ? h : prev));
361
+ }}
362
+ >
363
+ {ListFooterComponent}
364
+ </Box>
365
+ )}
366
+ </VirtualListContent>
367
+ )}
368
+ </ScrollArea>
369
+ </VirtualListFrame>
370
+ );
371
+ }
372
+
373
+ /**
374
+ * `VirtualList<T>` — see {@link VirtualListFrame} for the behaviour overview.
375
+ * Generic in the row data type; forwards a {@link VirtualListHandle} ref.
376
+ */
377
+ export const VirtualList = React.forwardRef(VirtualListInner) as <T>(
378
+ props: VirtualListProps<T> & { ref?: React.Ref<VirtualListHandle> },
379
+ ) => React.ReactElement;
@@ -0,0 +1,7 @@
1
+ export * from "./VirtualList";
2
+ export type {
3
+ VirtualListHandle,
4
+ VirtualListOwnProps,
5
+ VirtualListRenderItemInfo,
6
+ VirtualListStyles,
7
+ } from "./VirtualList.shared";
package/src/index.ts CHANGED
@@ -592,4 +592,12 @@ export { TreeSelect, type TreeSelectProps, type TreeSelectSize } from "./TreeSel
592
592
 
593
593
  export { Typography, type TypographyProps } from "./Typography";
594
594
  export { UnstyledButton, type UnstyledButtonProps } from "./UnstyledButton";
595
+ export {
596
+ VirtualList,
597
+ type VirtualListHandle,
598
+ type VirtualListOwnProps,
599
+ type VirtualListProps,
600
+ type VirtualListRenderItemInfo,
601
+ type VirtualListStyles,
602
+ } from "./VirtualList";
595
603
  export { VisuallyHidden, type VisuallyHiddenProps } from "./VisuallyHidden";