react-native-divkit 1.6.5 → 1.8.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 +18 -15
  2. package/dist/DivKit.d.ts.map +1 -1
  3. package/dist/DivKit.js +115 -4
  4. package/dist/DivKit.js.map +1 -1
  5. package/dist/components/DivComponent.d.ts.map +1 -1
  6. package/dist/components/DivComponent.js +6 -2
  7. package/dist/components/DivComponent.js.map +1 -1
  8. package/dist/components/index.d.ts +4 -0
  9. package/dist/components/index.d.ts.map +1 -1
  10. package/dist/components/index.js +2 -0
  11. package/dist/components/index.js.map +1 -1
  12. package/dist/components/indicator/DivIndicator.d.ts +19 -0
  13. package/dist/components/indicator/DivIndicator.d.ts.map +1 -0
  14. package/dist/components/indicator/DivIndicator.js +112 -0
  15. package/dist/components/indicator/DivIndicator.js.map +1 -0
  16. package/dist/components/indicator/index.d.ts +3 -0
  17. package/dist/components/indicator/index.d.ts.map +1 -0
  18. package/dist/components/indicator/index.js +2 -0
  19. package/dist/components/indicator/index.js.map +1 -0
  20. package/dist/components/indicator/utils.d.ts +61 -0
  21. package/dist/components/indicator/utils.d.ts.map +1 -0
  22. package/dist/components/indicator/utils.js +104 -0
  23. package/dist/components/indicator/utils.js.map +1 -0
  24. package/dist/components/pager/DivPager.d.ts +22 -0
  25. package/dist/components/pager/DivPager.d.ts.map +1 -0
  26. package/dist/components/pager/DivPager.js +269 -0
  27. package/dist/components/pager/DivPager.js.map +1 -0
  28. package/dist/components/pager/index.d.ts +3 -0
  29. package/dist/components/pager/index.d.ts.map +1 -0
  30. package/dist/components/pager/index.js +2 -0
  31. package/dist/components/pager/index.js.map +1 -0
  32. package/dist/components/pager/utils.d.ts +96 -0
  33. package/dist/components/pager/utils.d.ts.map +1 -0
  34. package/dist/components/pager/utils.js +142 -0
  35. package/dist/components/pager/utils.js.map +1 -0
  36. package/dist/components/state/DivState.d.ts +11 -12
  37. package/dist/components/state/DivState.d.ts.map +1 -1
  38. package/dist/components/state/DivState.js +263 -35
  39. package/dist/components/state/DivState.js.map +1 -1
  40. package/dist/components/utilities/Background.d.ts.map +1 -1
  41. package/dist/components/utilities/Background.js +4 -3
  42. package/dist/components/utilities/Background.js.map +1 -1
  43. package/dist/components/utilities/Outer.d.ts.map +1 -1
  44. package/dist/components/utilities/Outer.js +175 -78
  45. package/dist/components/utilities/Outer.js.map +1 -1
  46. package/dist/context/DivStateScopeContext.d.ts +18 -0
  47. package/dist/context/DivStateScopeContext.d.ts.map +1 -0
  48. package/dist/context/DivStateScopeContext.js +7 -0
  49. package/dist/context/DivStateScopeContext.js.map +1 -0
  50. package/dist/context/PagerContext.d.ts +30 -0
  51. package/dist/context/PagerContext.d.ts.map +1 -0
  52. package/dist/context/PagerContext.js +76 -0
  53. package/dist/context/PagerContext.js.map +1 -0
  54. package/dist/context/index.d.ts +1 -0
  55. package/dist/context/index.d.ts.map +1 -1
  56. package/dist/context/index.js +1 -0
  57. package/dist/context/index.js.map +1 -1
  58. package/dist/hooks/useAppearanceTransition.d.ts +86 -0
  59. package/dist/hooks/useAppearanceTransition.d.ts.map +1 -0
  60. package/dist/hooks/useAppearanceTransition.js +490 -0
  61. package/dist/hooks/useAppearanceTransition.js.map +1 -0
  62. package/dist/hooks/useChangeBoundsTransition.d.ts +46 -0
  63. package/dist/hooks/useChangeBoundsTransition.d.ts.map +1 -0
  64. package/dist/hooks/useChangeBoundsTransition.js +151 -0
  65. package/dist/hooks/useChangeBoundsTransition.js.map +1 -0
  66. package/dist/utils/configureChangeBoundsLayout.d.ts +11 -0
  67. package/dist/utils/configureChangeBoundsLayout.d.ts.map +1 -0
  68. package/dist/utils/configureChangeBoundsLayout.js +65 -0
  69. package/dist/utils/configureChangeBoundsLayout.js.map +1 -0
  70. package/dist/utils/flattenTransition.d.ts +5 -0
  71. package/dist/utils/flattenTransition.d.ts.map +1 -0
  72. package/dist/utils/flattenTransition.js +27 -0
  73. package/dist/utils/flattenTransition.js.map +1 -0
  74. package/package.json +3 -1
  75. package/src/DivKit.tsx +131 -5
  76. package/src/components/DivComponent.tsx +8 -2
  77. package/src/components/README.md +59 -5
  78. package/src/components/index.ts +4 -0
  79. package/src/components/indicator/DivIndicator.tsx +175 -0
  80. package/src/components/indicator/index.ts +2 -0
  81. package/src/components/indicator/utils.ts +149 -0
  82. package/src/components/pager/DivPager.tsx +393 -0
  83. package/src/components/pager/index.ts +2 -0
  84. package/src/components/pager/utils.ts +214 -0
  85. package/src/components/state/DivState.tsx +308 -39
  86. package/src/components/utilities/Background.tsx +4 -3
  87. package/src/components/utilities/Outer.tsx +192 -75
  88. package/src/context/DivStateScopeContext.tsx +23 -0
  89. package/src/context/PagerContext.tsx +108 -0
  90. package/src/context/index.ts +8 -0
  91. package/src/hooks/useAppearanceTransition.ts +621 -0
  92. package/src/hooks/useChangeBoundsTransition.ts +193 -0
  93. package/src/types/indicator.d.ts +32 -0
  94. package/src/types/pager.d.ts +36 -0
  95. package/src/types/shape.d.ts +26 -0
  96. package/src/utils/configureChangeBoundsLayout.ts +74 -0
  97. package/src/utils/flattenTransition.ts +36 -0
@@ -0,0 +1,393 @@
1
+ import React, { useEffect, useMemo, useRef, useState, useCallback } from 'react';
2
+ import {
3
+ View,
4
+ ScrollView,
5
+ NativeScrollEvent,
6
+ NativeSyntheticEvent,
7
+ LayoutChangeEvent,
8
+ StyleSheet
9
+ } from 'react-native';
10
+ import type { ComponentContext } from '../../types/componentContext';
11
+ import type { DivPagerData, PagerOrientation } from '../../types/pager';
12
+ import type { PagerData, PagerRegisterData } from '../../types/componentContext';
13
+ import type { EdgeInsets } from '../../types/edgeInserts';
14
+ import { Outer } from '../utilities/Outer';
15
+ import { DivComponent } from '../DivComponent';
16
+ import { useDerivedFromVarsSimple } from '../../hooks/useDerivedFromVars';
17
+ import { useDivKitContext } from '../../context/DivKitContext';
18
+ import { usePagerContextOptional } from '../../context/PagerContext';
19
+ import { wrapError } from '../../utils/wrapError';
20
+ import {
21
+ DUPLICATES_IN_INFINITE,
22
+ buildRenderedItems,
23
+ computeContentPad,
24
+ computePageSize,
25
+ isInDuplicateRegion as isInDuplicateRegionFn,
26
+ isInfiniteEnabled,
27
+ offsetToPosition,
28
+ positionToReal as positionToRealFn,
29
+ realToPosition as realToPositionFn,
30
+ type ScrollAxisAlignment
31
+ } from './utils';
32
+
33
+ export interface DivPagerProps {
34
+ componentContext: ComponentContext<DivPagerData>;
35
+ }
36
+
37
+ const DUPLICATES = DUPLICATES_IN_INFINITE;
38
+
39
+ /**
40
+ * DivPager — horizontal/vertical pager with snap-to-page scrolling.
41
+ *
42
+ * Based on Web Pager.svelte. Adapted for React Native:
43
+ * - Uses ScrollView with snapToInterval for paging behaviour.
44
+ * - Computes per-page size from layout_mode (fixed neighbour, percentage,
45
+ * wrap_content) once container size is known.
46
+ * - infinite_scroll: renders DUPLICATES extra items at each end; when the user
47
+ * lands on a duplicate the scroll position is silently snapped to the
48
+ * matching real item (no animation), giving a seamless loop.
49
+ * - Exposes its current page/size to indicators via PagerContext using the
50
+ * same registerPager/listenPager contract as Web. The "currentItem" reported
51
+ * to indicators is always the real index in [0, items.length).
52
+ */
53
+ export function DivPager({ componentContext }: DivPagerProps) {
54
+ const { genId } = useDivKitContext();
55
+ const pagerCtx = usePagerContextOptional();
56
+ const { json, variables } = componentContext;
57
+
58
+ const orientation = useDerivedFromVarsSimple<PagerOrientation>(
59
+ (json.orientation as PagerOrientation) || 'horizontal',
60
+ variables || new Map()
61
+ );
62
+ const layoutMode = useDerivedFromVarsSimple(
63
+ json.layout_mode,
64
+ variables || new Map()
65
+ );
66
+ const itemSpacingObj = useDerivedFromVarsSimple(json.item_spacing, variables || new Map());
67
+ const paddings = useDerivedFromVarsSimple(json.paddings, variables || new Map());
68
+ const scrollAxisAlignment = useDerivedFromVarsSimple(
69
+ json.scroll_axis_alignment || 'center',
70
+ variables || new Map()
71
+ );
72
+ const defaultItem = useDerivedFromVarsSimple<number>(
73
+ typeof json.default_item === 'number' ? json.default_item : 0,
74
+ variables || new Map()
75
+ );
76
+ const infiniteScroll = useDerivedFromVarsSimple<number | boolean | undefined>(
77
+ json.infinite_scroll,
78
+ variables || new Map()
79
+ );
80
+
81
+ const isHorizontal = orientation !== 'vertical';
82
+ const itemSpacing = (itemSpacingObj as { value?: number } | undefined)?.value ?? 0;
83
+
84
+ const items = useMemo(() => {
85
+ return Array.isArray(json.items) ? json.items : [];
86
+ }, [json.items]);
87
+
88
+ const isInfinite = useMemo(
89
+ () => isInfiniteEnabled(infiniteScroll, items.length),
90
+ [infiniteScroll, items.length]
91
+ );
92
+
93
+ // Pager paddings — applied on the inner ScrollView so we can also use them
94
+ // for snap math. Outer should NOT also apply them, so we strip them from
95
+ // the json passed into Outer below.
96
+ const innerPadStart = useMemo(() => {
97
+ const p = (paddings as EdgeInsets | undefined) || {};
98
+ if (isHorizontal) {
99
+ return Number(p.start ?? p.left ?? 0) || 0;
100
+ }
101
+ return Number(p.top ?? 0) || 0;
102
+ }, [paddings, isHorizontal]);
103
+ const innerPadEnd = useMemo(() => {
104
+ const p = (paddings as EdgeInsets | undefined) || {};
105
+ if (isHorizontal) {
106
+ return Number(p.end ?? p.right ?? 0) || 0;
107
+ }
108
+ return Number(p.bottom ?? 0) || 0;
109
+ }, [paddings, isHorizontal]);
110
+
111
+ const [containerSize, setContainerSize] = useState(0);
112
+ const scrollRef = useRef<ScrollView>(null);
113
+ const currentItemRef = useRef(0); // real index, always in [0, items.length)
114
+ const initialScrollDone = useRef(false);
115
+ const registerDataRef = useRef<PagerRegisterData | null>(null);
116
+ const pagerInstId = useRef<string>(genId('pager'));
117
+ const scrollToItemRef = useRef<((realIndex: number, animated: boolean) => void) | null>(null);
118
+
119
+ const pageSize = useMemo(
120
+ () =>
121
+ computePageSize({
122
+ containerSize,
123
+ layoutMode,
124
+ scrollAxisAlignment: scrollAxisAlignment as ScrollAxisAlignment,
125
+ itemSpacing,
126
+ innerPadStart,
127
+ innerPadEnd
128
+ }),
129
+ [containerSize, innerPadStart, innerPadEnd, layoutMode, scrollAxisAlignment, itemSpacing]
130
+ );
131
+
132
+ const snapInterval = pageSize > 0 ? pageSize + itemSpacing : 0;
133
+
134
+ const contentPad = useMemo(
135
+ () =>
136
+ computeContentPad({
137
+ containerSize,
138
+ pageSize,
139
+ innerPadStart,
140
+ innerPadEnd,
141
+ layoutMode,
142
+ scrollAxisAlignment: scrollAxisAlignment as ScrollAxisAlignment,
143
+ itemSpacing,
144
+ isInfinite
145
+ }),
146
+ [
147
+ containerSize,
148
+ pageSize,
149
+ innerPadStart,
150
+ innerPadEnd,
151
+ layoutMode,
152
+ scrollAxisAlignment,
153
+ itemSpacing,
154
+ isInfinite
155
+ ]
156
+ );
157
+
158
+ const realToPosition = useCallback(
159
+ (realIdx: number) => realToPositionFn(realIdx, isInfinite, DUPLICATES),
160
+ [isInfinite]
161
+ );
162
+
163
+ const positionToReal = useCallback(
164
+ (pos: number) => positionToRealFn(pos, isInfinite, items.length, DUPLICATES),
165
+ [isInfinite, items.length]
166
+ );
167
+
168
+ const isInDuplicateRegion = useCallback(
169
+ (pos: number) => isInDuplicateRegionFn(pos, isInfinite, items.length, DUPLICATES),
170
+ [isInfinite, items.length]
171
+ );
172
+
173
+ const runSelectedActions = useCallback(
174
+ (index: number) => {
175
+ const item = items[index] as any;
176
+ const actions = item?.selected_actions;
177
+ if (Array.isArray(actions) && actions.length > 0) {
178
+ componentContext.execAnyActions(actions);
179
+ }
180
+ },
181
+ [items, componentContext]
182
+ );
183
+
184
+ const pushPagerState = useCallback(
185
+ (item: number) => {
186
+ const reg = registerDataRef.current;
187
+ if (!reg) return;
188
+ const data: PagerData = {
189
+ instId: pagerInstId.current,
190
+ size: items.length,
191
+ currentItem: item,
192
+ scrollToPagerItem: (index: number) => scrollToItemRef.current?.(index, true)
193
+ };
194
+ reg.update(data);
195
+ },
196
+ [items.length]
197
+ );
198
+
199
+ const scrollToItem = useCallback(
200
+ (realIndex: number, animated: boolean) => {
201
+ const node = scrollRef.current;
202
+ if (!node || snapInterval <= 0 || items.length === 0) return;
203
+ const clampedReal = isInfinite
204
+ ? ((realIndex % items.length) + items.length) % items.length
205
+ : Math.max(0, Math.min(items.length - 1, realIndex));
206
+ const pos = realToPosition(clampedReal);
207
+ const offset = pos * snapInterval;
208
+ if (isHorizontal) {
209
+ node.scrollTo({ x: offset, y: 0, animated });
210
+ } else {
211
+ node.scrollTo({ x: 0, y: offset, animated });
212
+ }
213
+ if (clampedReal !== currentItemRef.current) {
214
+ currentItemRef.current = clampedReal;
215
+ pushPagerState(clampedReal);
216
+ runSelectedActions(clampedReal);
217
+ }
218
+ },
219
+ [
220
+ items.length,
221
+ snapInterval,
222
+ isHorizontal,
223
+ isInfinite,
224
+ realToPosition,
225
+ pushPagerState,
226
+ runSelectedActions
227
+ ]
228
+ );
229
+
230
+ useEffect(() => {
231
+ scrollToItemRef.current = scrollToItem;
232
+ }, [scrollToItem]);
233
+
234
+ // Register pager in context (so indicators can find it)
235
+ useEffect(() => {
236
+ if (!pagerCtx) return;
237
+ const pagerId = json.id;
238
+ const reg = pagerCtx.registerPager(pagerId);
239
+ registerDataRef.current = reg;
240
+ pushPagerState(currentItemRef.current);
241
+ return () => {
242
+ reg.destroy();
243
+ registerDataRef.current = null;
244
+ };
245
+ }, [pagerCtx, json.id, pushPagerState]);
246
+
247
+ // Re-broadcast on items length / scrollToItem changes
248
+ useEffect(() => {
249
+ pushPagerState(currentItemRef.current);
250
+ }, [pushPagerState]);
251
+
252
+ // Initial scroll to default_item once we know page size
253
+ useEffect(() => {
254
+ if (initialScrollDone.current) return;
255
+ if (snapInterval <= 0) return;
256
+ const initial = Math.max(0, Math.min(items.length - 1, defaultItem ?? 0));
257
+ currentItemRef.current = initial;
258
+ const id = setTimeout(() => {
259
+ scrollToItem(initial, false);
260
+ initialScrollDone.current = true;
261
+ pushPagerState(initial);
262
+ }, 0);
263
+ return () => clearTimeout(id);
264
+ }, [snapInterval, defaultItem, items.length, scrollToItem, pushPagerState]);
265
+
266
+ const onScrollEnd = useCallback(
267
+ (event: NativeSyntheticEvent<NativeScrollEvent>) => {
268
+ if (snapInterval <= 0) return;
269
+ const { contentOffset } = event.nativeEvent;
270
+ const offset = isHorizontal ? contentOffset.x : contentOffset.y;
271
+ const pos = offsetToPosition(offset, snapInterval);
272
+ const realIdx = positionToReal(pos);
273
+
274
+ // In infinite mode: silently snap from a duplicate back to the
275
+ // matching real item without animation.
276
+ if (isInfinite && isInDuplicateRegion(pos)) {
277
+ const realPos = realToPosition(realIdx);
278
+ const node = scrollRef.current;
279
+ if (node) {
280
+ const realOffset = realPos * snapInterval;
281
+ if (isHorizontal) {
282
+ node.scrollTo({ x: realOffset, y: 0, animated: false });
283
+ } else {
284
+ node.scrollTo({ x: 0, y: realOffset, animated: false });
285
+ }
286
+ }
287
+ }
288
+
289
+ if (realIdx !== currentItemRef.current) {
290
+ currentItemRef.current = realIdx;
291
+ pushPagerState(realIdx);
292
+ runSelectedActions(realIdx);
293
+ }
294
+ },
295
+ [
296
+ snapInterval,
297
+ isHorizontal,
298
+ positionToReal,
299
+ isInDuplicateRegion,
300
+ isInfinite,
301
+ realToPosition,
302
+ pushPagerState,
303
+ runSelectedActions
304
+ ]
305
+ );
306
+
307
+ const onLayout = useCallback(
308
+ (e: LayoutChangeEvent) => {
309
+ const size = isHorizontal ? e.nativeEvent.layout.width : e.nativeEvent.layout.height;
310
+ if (size && Math.abs(size - containerSize) > 0.5) {
311
+ setContainerSize(size);
312
+ }
313
+ },
314
+ [containerSize, isHorizontal]
315
+ );
316
+
317
+ // Strip paddings from Outer — we apply them on the ScrollView ourselves.
318
+ const outerContext = useMemo(() => {
319
+ const restJson = { ...json };
320
+ delete restJson.paddings;
321
+ return { ...componentContext, json: restJson } as ComponentContext<DivPagerData>;
322
+ }, [componentContext, json]);
323
+
324
+ const renderedItems = useMemo(
325
+ () => buildRenderedItems(items, isInfinite, DUPLICATES),
326
+ [items, isInfinite]
327
+ );
328
+
329
+ if (!json.layout_mode) {
330
+ componentContext.logError(
331
+ wrapError(new Error('Empty "layout_mode" prop for div "pager"'))
332
+ );
333
+ return null;
334
+ }
335
+
336
+ const renderItems = () => {
337
+ if (!renderedItems.length || pageSize <= 0) return null;
338
+ return renderedItems.map((entry, posIndex) => {
339
+ const childContext = componentContext.produceChildContext(entry.item, {
340
+ path: posIndex
341
+ });
342
+ const isLast = posIndex === renderedItems.length - 1;
343
+ const itemStyle = isHorizontal
344
+ ? { width: pageSize, marginRight: isLast ? 0 : itemSpacing }
345
+ : { height: pageSize, marginBottom: isLast ? 0 : itemSpacing };
346
+ return (
347
+ <View key={entry.key} style={[styles.itemWrapper, itemStyle]}>
348
+ <DivComponent componentContext={childContext} />
349
+ </View>
350
+ );
351
+ });
352
+ };
353
+
354
+ return (
355
+ <Outer componentContext={outerContext}>
356
+ <View style={styles.fill} onLayout={onLayout}>
357
+ {pageSize > 0 ? (
358
+ <ScrollView
359
+ ref={scrollRef}
360
+ horizontal={isHorizontal}
361
+ showsHorizontalScrollIndicator={false}
362
+ showsVerticalScrollIndicator={false}
363
+ decelerationRate="fast"
364
+ snapToInterval={snapInterval}
365
+ snapToAlignment="start"
366
+ disableIntervalMomentum
367
+ onMomentumScrollEnd={onScrollEnd}
368
+ onScrollEndDrag={onScrollEnd}
369
+ scrollEventThrottle={16}
370
+ contentContainerStyle={
371
+ isHorizontal
372
+ ? { paddingLeft: contentPad.start, paddingRight: contentPad.end }
373
+ : { paddingTop: contentPad.start, paddingBottom: contentPad.end }
374
+ }
375
+ style={styles.fill}
376
+ >
377
+ {renderItems()}
378
+ </ScrollView>
379
+ ) : null}
380
+ </View>
381
+ </Outer>
382
+ );
383
+ }
384
+
385
+ const styles = StyleSheet.create({
386
+ fill: {
387
+ flex: 1,
388
+ alignSelf: 'stretch'
389
+ },
390
+ itemWrapper: {
391
+ overflow: 'hidden'
392
+ }
393
+ });
@@ -0,0 +1,2 @@
1
+ export { DivPager } from './DivPager';
2
+ export type { DivPagerProps } from './DivPager';
@@ -0,0 +1,214 @@
1
+ /**
2
+ * Pure helpers for DivPager. Extracted so they can be unit-tested without
3
+ * having to render the React tree.
4
+ */
5
+
6
+ export type ScrollAxisAlignment = 'start' | 'center' | 'end';
7
+
8
+ export interface LayoutModeFixed {
9
+ type: 'fixed';
10
+ neighbour_page_width?: { value?: number };
11
+ }
12
+ export interface LayoutModePercentage {
13
+ type: 'percentage';
14
+ page_width?: { value?: number };
15
+ }
16
+ export interface LayoutModeWrap {
17
+ type: 'wrap_content';
18
+ }
19
+ export type AnyLayoutMode =
20
+ | LayoutModeFixed
21
+ | LayoutModePercentage
22
+ | LayoutModeWrap
23
+ | { type?: string; [k: string]: unknown }
24
+ | null
25
+ | undefined;
26
+
27
+ export interface ComputePageSizeArgs {
28
+ containerSize: number;
29
+ layoutMode: AnyLayoutMode;
30
+ scrollAxisAlignment: ScrollAxisAlignment;
31
+ itemSpacing: number;
32
+ innerPadStart: number;
33
+ innerPadEnd: number;
34
+ }
35
+
36
+ /**
37
+ * Compute the size of a single page along the main axis. Mirrors the Web
38
+ * Pager.svelte autoSizeVal calculation:
39
+ * - fixed + center: containerSize − 2·neighbour − 2·spacing
40
+ * - fixed + start/end: containerSize − neighbour − spacing
41
+ * - percentage: containerSize · page_width / 100
42
+ * - wrap_content / unknown: usable area (containerSize − paddings)
43
+ */
44
+ export function computePageSize(args: ComputePageSizeArgs): number {
45
+ const { containerSize, layoutMode, scrollAxisAlignment, itemSpacing, innerPadStart, innerPadEnd } =
46
+ args;
47
+ if (containerSize <= 0) return 0;
48
+ const usable = containerSize - innerPadStart - innerPadEnd;
49
+
50
+ const lm = layoutMode as { type?: string; neighbour_page_width?: { value?: number }; page_width?: { value?: number } } | null | undefined;
51
+
52
+ if (lm && lm.type === 'fixed') {
53
+ const neighbourW = lm.neighbour_page_width?.value ?? 0;
54
+ if (scrollAxisAlignment === 'center') {
55
+ return Math.max(0, containerSize - 2 * neighbourW - 2 * itemSpacing);
56
+ }
57
+ return Math.max(0, containerSize - neighbourW - itemSpacing);
58
+ }
59
+ if (lm && lm.type === 'percentage') {
60
+ const pageW = lm.page_width?.value ?? 100;
61
+ return Math.max(0, (containerSize * pageW) / 100);
62
+ }
63
+ return Math.max(0, usable);
64
+ }
65
+
66
+ export interface ComputeContentPadArgs extends ComputePageSizeArgs {
67
+ pageSize: number;
68
+ isInfinite: boolean;
69
+ }
70
+
71
+ /**
72
+ * Compute the contentContainer paddings the inner ScrollView needs so that the
73
+ * first/last items snap to the right visual position (centre/start/end). In
74
+ * infinite mode the duplicates take that role and we use zero padding.
75
+ */
76
+ export function computeContentPad(args: ComputeContentPadArgs): { start: number; end: number } {
77
+ const {
78
+ containerSize,
79
+ pageSize,
80
+ innerPadStart,
81
+ innerPadEnd,
82
+ layoutMode,
83
+ scrollAxisAlignment,
84
+ itemSpacing,
85
+ isInfinite
86
+ } = args;
87
+
88
+ if (containerSize <= 0 || pageSize <= 0) {
89
+ return { start: innerPadStart, end: innerPadEnd };
90
+ }
91
+ if (isInfinite) {
92
+ return { start: 0, end: 0 };
93
+ }
94
+ const lm = layoutMode as { type?: string; neighbour_page_width?: { value?: number } } | null | undefined;
95
+ if (lm && lm.type === 'fixed') {
96
+ const neighbourW = lm.neighbour_page_width?.value ?? 0;
97
+ if (scrollAxisAlignment === 'center') {
98
+ const pad = neighbourW + itemSpacing;
99
+ return { start: pad, end: pad };
100
+ }
101
+ if (scrollAxisAlignment === 'start') {
102
+ return { start: innerPadStart, end: neighbourW + itemSpacing + innerPadEnd };
103
+ }
104
+ if (scrollAxisAlignment === 'end') {
105
+ return { start: neighbourW + itemSpacing + innerPadStart, end: innerPadEnd };
106
+ }
107
+ }
108
+ return { start: innerPadStart, end: innerPadEnd };
109
+ }
110
+
111
+ export const DUPLICATES_IN_INFINITE = 2;
112
+
113
+ /**
114
+ * Map a "real" item index (0..size-1) to its rendered position.
115
+ * In infinite mode the real items live in [DUPLICATES, DUPLICATES + size).
116
+ */
117
+ export function realToPosition(realIdx: number, isInfinite: boolean, duplicates = DUPLICATES_IN_INFINITE): number {
118
+ return isInfinite ? duplicates + realIdx : realIdx;
119
+ }
120
+
121
+ /**
122
+ * Map a rendered position back to the real index. Wraps modulo `size` when
123
+ * the position lands inside the duplicate region.
124
+ */
125
+ export function positionToReal(
126
+ pos: number,
127
+ isInfinite: boolean,
128
+ size: number,
129
+ duplicates = DUPLICATES_IN_INFINITE
130
+ ): number {
131
+ if (size <= 0) return 0;
132
+ if (!isInfinite) {
133
+ return Math.max(0, Math.min(size - 1, pos));
134
+ }
135
+ const inner = pos - duplicates;
136
+ return ((inner % size) + size) % size;
137
+ }
138
+
139
+ /**
140
+ * True when `pos` corresponds to one of the duplicate entries (only meaningful
141
+ * in infinite mode).
142
+ */
143
+ export function isInDuplicateRegion(
144
+ pos: number,
145
+ isInfinite: boolean,
146
+ size: number,
147
+ duplicates = DUPLICATES_IN_INFINITE
148
+ ): boolean {
149
+ if (!isInfinite) return false;
150
+ return pos < duplicates || pos >= duplicates + size;
151
+ }
152
+
153
+ export interface RenderedItemEntry<T> {
154
+ item: T;
155
+ realIndex: number;
156
+ key: string;
157
+ }
158
+
159
+ /**
160
+ * Build the list of items to render. In infinite mode this prefixes the array
161
+ * with `duplicates` copies of the last items and suffixes it with `duplicates`
162
+ * copies of the first items, so the user can swipe past either edge and land
163
+ * on something visually identical to the wrap-around target.
164
+ */
165
+ export function buildRenderedItems<T extends { id?: string }>(
166
+ items: T[],
167
+ isInfinite: boolean,
168
+ duplicates = DUPLICATES_IN_INFINITE
169
+ ): RenderedItemEntry<T>[] {
170
+ if (!items.length) return [];
171
+ if (!isInfinite) {
172
+ return items.map((item, index) => ({ item, realIndex: index, key: `r-${index}` }));
173
+ }
174
+ const size = items.length;
175
+ const head: RenderedItemEntry<T>[] = [];
176
+ const tail: RenderedItemEntry<T>[] = [];
177
+ for (let i = 0; i < duplicates; i++) {
178
+ const realIdx = (size - duplicates + i + size) % size;
179
+ head.push({ item: items[realIdx], realIndex: realIdx, key: `dup-h-${i}` });
180
+ }
181
+ for (let i = 0; i < duplicates; i++) {
182
+ const realIdx = i % size;
183
+ tail.push({ item: items[realIdx], realIndex: realIdx, key: `dup-t-${i}` });
184
+ }
185
+ const real: RenderedItemEntry<T>[] = items.map((item, index) => ({
186
+ item,
187
+ realIndex: index,
188
+ key: `r-${index}`
189
+ }));
190
+ return [...head, ...real, ...tail];
191
+ }
192
+
193
+ /**
194
+ * Decide whether infinite_scroll should actually be active.
195
+ * Mirrors Web's correctBooleanInt + the `items.length >= DUPLICATES_IN_INFINITE`
196
+ * gate.
197
+ */
198
+ export function isInfiniteEnabled(infiniteValue: unknown, itemsLength: number): boolean {
199
+ const truthy =
200
+ infiniteValue === true ||
201
+ infiniteValue === 1 ||
202
+ infiniteValue === '1' ||
203
+ infiniteValue === 'true';
204
+ return truthy && itemsLength >= DUPLICATES_IN_INFINITE;
205
+ }
206
+
207
+ /**
208
+ * Convert a scroll offset (in px) into a snap position (rounded). Returns 0
209
+ * when snapInterval <= 0.
210
+ */
211
+ export function offsetToPosition(offset: number, snapInterval: number): number {
212
+ if (snapInterval <= 0) return 0;
213
+ return Math.round(offset / snapInterval);
214
+ }