@tarojs/components-advanced 4.1.12-beta.9 → 4.2.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 (59) hide show
  1. package/dist/components/index.js +0 -2
  2. package/dist/components/index.js.map +1 -1
  3. package/dist/components/list/index.d.ts +3 -60
  4. package/dist/components/list/index.js +110 -983
  5. package/dist/components/list/index.js.map +1 -1
  6. package/dist/components/virtual-list/vue/list.d.ts +2 -2
  7. package/dist/components/virtual-waterfall/vue/waterfall.d.ts +1 -1
  8. package/dist/components/water-flow/interface.d.ts +2 -14
  9. package/dist/components/water-flow/root.d.ts +1 -11
  10. package/dist/components/water-flow/root.js +25 -42
  11. package/dist/components/water-flow/root.js.map +1 -1
  12. package/dist/components/water-flow/section.d.ts +1 -1
  13. package/dist/components/water-flow/section.js +2 -2
  14. package/dist/components/water-flow/section.js.map +1 -1
  15. package/dist/components/water-flow/utils.d.ts +0 -2
  16. package/dist/components/water-flow/utils.js +1 -3
  17. package/dist/components/water-flow/utils.js.map +1 -1
  18. package/dist/components/water-flow/water-flow.d.ts +1 -2
  19. package/dist/components/water-flow/water-flow.js +25 -188
  20. package/dist/components/water-flow/water-flow.js.map +1 -1
  21. package/dist/index.js +0 -3
  22. package/dist/index.js.map +1 -1
  23. package/dist/utils/index.d.ts +0 -1
  24. package/dist/utils/index.js +0 -1
  25. package/dist/utils/index.js.map +1 -1
  26. package/package.json +8 -9
  27. package/dist/components/list/NoMore.d.ts +0 -30
  28. package/dist/components/list/NoMore.js +0 -10
  29. package/dist/components/list/NoMore.js.map +0 -1
  30. package/dist/components/list/hooks/useItemSizeCache.d.ts +0 -13
  31. package/dist/components/list/hooks/useItemSizeCache.js +0 -40
  32. package/dist/components/list/hooks/useItemSizeCache.js.map +0 -1
  33. package/dist/components/list/hooks/useListNestedScroll.d.ts +0 -13
  34. package/dist/components/list/hooks/useListNestedScroll.js +0 -46
  35. package/dist/components/list/hooks/useListNestedScroll.js.map +0 -1
  36. package/dist/components/list/hooks/useListScrollElementAttach.d.ts +0 -21
  37. package/dist/components/list/hooks/useListScrollElementAttach.js +0 -86
  38. package/dist/components/list/hooks/useListScrollElementAttach.js.map +0 -1
  39. package/dist/components/list/hooks/useMeasureStartOffset.d.ts +0 -12
  40. package/dist/components/list/hooks/useMeasureStartOffset.js +0 -84
  41. package/dist/components/list/hooks/useMeasureStartOffset.js.map +0 -1
  42. package/dist/components/list/hooks/useRefresher.d.ts +0 -74
  43. package/dist/components/list/hooks/useRefresher.js +0 -503
  44. package/dist/components/list/hooks/useRefresher.js.map +0 -1
  45. package/dist/components/list/hooks/useResizeObserver.d.ts +0 -26
  46. package/dist/components/list/hooks/useResizeObserver.js +0 -152
  47. package/dist/components/list/hooks/useResizeObserver.js.map +0 -1
  48. package/dist/components/list/hooks/useScrollCorrection.d.ts +0 -19
  49. package/dist/components/list/hooks/useScrollCorrection.js +0 -73
  50. package/dist/components/list/hooks/useScrollCorrection.js.map +0 -1
  51. package/dist/components/list/hooks/useScrollParentAutoFind.d.ts +0 -17
  52. package/dist/components/list/hooks/useScrollParentAutoFind.js +0 -54
  53. package/dist/components/list/hooks/useScrollParentAutoFind.js.map +0 -1
  54. package/dist/components/list/utils.d.ts +0 -16
  55. package/dist/components/list/utils.js +0 -19
  56. package/dist/components/list/utils.js.map +0 -1
  57. package/dist/utils/scrollParent.d.ts +0 -22
  58. package/dist/utils/scrollParent.js +0 -55
  59. package/dist/utils/scrollParent.js.map +0 -1
@@ -1,20 +1,9 @@
1
- import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
1
+ import { jsx, jsxs } from 'react/jsx-runtime';
2
2
  import { View, ScrollView } from '@tarojs/components';
3
- import { ScrollElementContext } from '@tarojs/components-react';
4
- export { ScrollElementContext as ListScrollElementContext } from '@tarojs/components-react';
5
- import Taro from '@tarojs/taro';
6
3
  import React from 'react';
7
- import { useItemSizeCache } from './hooks/useItemSizeCache.js';
8
- import { useListNestedScroll } from './hooks/useListNestedScroll.js';
9
- import { useListScrollElementAttach } from './hooks/useListScrollElementAttach.js';
10
- import { useRefresher, DEFAULT_REFRESHER_HEIGHT } from './hooks/useRefresher.js';
11
- import { useResizeObserver } from './hooks/useResizeObserver.js';
12
- import { useScrollCorrection } from './hooks/useScrollCorrection.js';
13
4
  import { ListItem } from './ListItem.js';
14
- import { NoMore } from './NoMore.js';
15
5
  import { StickyHeader } from './StickyHeader.js';
16
6
  import { StickySection } from './StickySection.js';
17
- import { isWeapp, isH5, supportsNativeRefresher } from './utils.js';
18
7
 
19
8
  // 工具:累加数组
20
9
  function accumulate(arr) {
@@ -39,252 +28,25 @@ function isShaking(diffList) {
39
28
  // 如果交替次数过多,认为是抖动
40
29
  return alternations >= 2;
41
30
  }
42
- // 小程序端:判断 item 是否应该执行 SelectorQuery 测量(仅检查是否已测量过)
43
- // SelectorQuery 是只读查询,不会触发 setData,滚动期间执行是安全的
44
- function shouldMeasureWeappItem(index, measuredSet) {
45
- return !measuredSet.has(index);
46
- }
47
- // 小程序端暂不外抛 onItemSizeChange,避免父层重渲染导致 List remount 引发回顶或空白
48
- function weappDeferItemSizeChange(_index, _size, _onItemSizeChange) { }
49
- /** 从 scroll 选项解析目标偏移量 */
50
- function resolveScrollTargetOffset(options, isHorizontal) {
51
- const opts = options !== null && options !== void 0 ? options : {};
52
- const top = typeof opts.top === 'number' ? opts.top : undefined;
53
- const left = typeof opts.left === 'number' ? opts.left : undefined;
54
- let result = 0;
55
- if (isHorizontal) {
56
- if (typeof left === 'number')
57
- result = left;
58
- else if (typeof top === 'number')
59
- result = top;
60
- }
61
- else {
62
- if (typeof top === 'number')
63
- result = top;
64
- else if (typeof left === 'number')
65
- result = left;
66
- }
67
- return Number.isFinite(result) ? result : 0;
68
- }
69
- // eslint-disable-next-line complexity -- List 多端/多模式逻辑集中,已抽离 useListNestedScroll、useListScrollElementAttach、resolveScrollTargetOffset 等
70
- const InnerList = (props, ref) => {
71
- var _a, _b, _c;
72
- const { stickyHeader = false, space = 0, height = 400, width = '100%', showScrollbar = true, scrollTop: controlledScrollTop, scrollX = false, scrollY = true, onScroll, onScrollToUpper, onScrollToLower, onScrollStart, onScrollEnd, upperThreshold = 50, lowerThreshold = 50, cacheCount = 2, cacheExtent, enableBackToTop, className, style, children, nestedScroll, scrollElement, scrollRef: scrollRefProp, } = props;
31
+ const List = (props) => {
32
+ const isH5 = process.env.TARO_ENV === 'h5';
33
+ const { stickyHeader = false, space = 0, height = 400, width = '100%', showScrollbar = true, scrollTop: controlledScrollTop, scrollX = false, scrollY = true, onScroll, onScrollToUpper, onScrollToLower, upperThreshold = 0, lowerThreshold = 0, cacheCount = 2, style, children, } = props;
73
34
  const isHorizontal = scrollX === true;
74
- const listType = nestedScroll === true ? 'nested' : 'default';
75
- const { effectiveScrollElement, effectiveStartOffset, useScrollElementMode, needAutoFind, autoFindStatus, contentWrapperRef, } = useListNestedScroll(listType, scrollElement, undefined, isHorizontal);
76
35
  const DEFAULT_ITEM_WIDTH = 120;
77
36
  const DEFAULT_ITEM_HEIGHT = 40;
78
37
  // 滚动状态管理
79
38
  const containerRef = React.useRef(null);
80
- // 生成唯一 List ID(用于小程序 ResizeObserver)
81
- const listId = React.useMemo(() => `list-${Math.random().toString(36).slice(2, 11)}`, []);
82
39
  // 渲染偏移量 - 用于计算应该渲染哪些元素
83
40
  const [renderOffset, setRenderOffset] = React.useState(controlledScrollTop !== null && controlledScrollTop !== void 0 ? controlledScrollTop : 0);
84
- // 程序性滚动用的目标偏移;用户滑动期间不更新,避免与原生滚动冲突
41
+ // 滚动视图偏移量 - 只在滚动结束或明确请求时更新到ScrollView
85
42
  const [scrollViewOffset, setScrollViewOffset] = React.useState(controlledScrollTop !== null && controlledScrollTop !== void 0 ? controlledScrollTop : 0);
86
- // 用户正在滑动时不再向 ScrollView scrollTop,让滚动完全由原生接管
87
- const [isUserScrolling, setIsUserScrolling] = React.useState(false);
88
- // isUserScrolling 的 ref 镜像,供异步上下文读取最新值
89
- const isUserScrollingRef = React.useRef(false);
90
- const initialContainerLength = typeof (isHorizontal ? width : height) === 'number' ? (isHorizontal ? width : height) : 400;
91
- const [containerLength, setContainerLength] = React.useState(initialContainerLength);
92
- // 用容器实际尺寸更新视口长度,避免 props 与 CSS 不一致导致底部空白
93
- React.useEffect(() => {
94
- const el = containerRef.current;
95
- if (!el || typeof ResizeObserver === 'undefined')
96
- return;
97
- const ro = new ResizeObserver((entries) => {
98
- for (const entry of entries) {
99
- const { contentRect } = entry;
100
- const measured = isHorizontal ? contentRect.width : contentRect.height;
101
- if (measured > 0)
102
- setContainerLength(measured);
103
- }
104
- });
105
- ro.observe(el);
106
- return () => ro.disconnect();
107
- }, [isHorizontal]);
43
+ const [containerLength] = React.useState(typeof (isHorizontal ? width : height) === 'number' ? (isHorizontal ? width : height) : 400);
108
44
  // 滚动追踪相关refs
109
45
  const isScrollingRef = React.useRef(false);
110
46
  const lastScrollTopRef = React.useRef(controlledScrollTop !== null && controlledScrollTop !== void 0 ? controlledScrollTop : 0);
111
47
  const scrollDiffListRef = React.useRef([0, 0, 0]);
112
48
  const scrollTimeoutRef = React.useRef(null);
113
- // H5:仅程序性滚动时写回 DOM scrollTop,用户滑动结束后不写回避免卡顿
114
- const programmaticScrollRef = React.useRef(false);
115
- // 小程序端程序性滚动冷却期:handleScroll 只更新 renderOffset,避免 scrollIntoView 后被原生回调拉回
116
- const programmaticCooldownRef = React.useRef(false);
117
- const programmaticCooldownTimerRef = React.useRef(null);
118
- const scrollViewOffsetRef = React.useRef(0);
119
- // 处理渲染偏移量更新。
120
- // syncToScrollView=true:程序性滚动,立即同步 scrollViewOffset。
121
- // syncToScrollView=false:用户滑动,仅更新 renderOffset。weapp 采用 recycle-view 策略:不把用户滑动位置同步到 scrollViewOffset,避免「传滞后值拉回」和「从有到无归顶」。
122
- const updateRenderOffset = React.useCallback((newOffset, syncToScrollView, source) => {
123
- lastScrollTopRef.current = newOffset;
124
- isScrollingRef.current = true;
125
- if (scrollTimeoutRef.current) {
126
- clearTimeout(scrollTimeoutRef.current);
127
- }
128
- setRenderOffset(newOffset); // 始终更新虚拟列表用到的偏移
129
- if (syncToScrollView) {
130
- isUserScrollingRef.current = false;
131
- setIsUserScrolling(false);
132
- // 小程序:target===sv 时 ScrollView 认为无变化不滚动→白屏;imperative/scrollIntoView 时先传中间值再 RAF 传 target 强制触发
133
- // target=0 用 +0.01;target>0 用 -0.01(统一 +0.01 到底部会被 clamp 成同值无效)
134
- const same = isWeapp && Math.abs(scrollViewOffsetRef.current - newOffset) < 1;
135
- const needForce = same && (source === 'imperative' || source === 'scrollIntoView');
136
- if (needForce) {
137
- const intermediate = newOffset > 0 ? newOffset - 0.01 : 0.01;
138
- setScrollViewOffset(intermediate);
139
- requestAnimationFrame(() => {
140
- setScrollViewOffset(newOffset);
141
- });
142
- }
143
- else {
144
- setScrollViewOffset(newOffset);
145
- }
146
- programmaticScrollRef.current = true;
147
- if (isWeapp) {
148
- programmaticCooldownRef.current = true;
149
- if (programmaticCooldownTimerRef.current) {
150
- clearTimeout(programmaticCooldownTimerRef.current);
151
- }
152
- programmaticCooldownTimerRef.current = setTimeout(() => {
153
- programmaticCooldownRef.current = false;
154
- }, 500);
155
- }
156
- }
157
- else {
158
- isUserScrollingRef.current = true;
159
- setIsUserScrolling(true);
160
- }
161
- scrollTimeoutRef.current = setTimeout(() => {
162
- isScrollingRef.current = false;
163
- if (!syncToScrollView) {
164
- isUserScrollingRef.current = false;
165
- setIsUserScrolling(false);
166
- // weapp recycle-view 策略:用户滑动结束后不同步 scrollViewOffset,保持 pass 的值不变,避免 从有到无 归顶
167
- if (!isWeapp) {
168
- setScrollViewOffset(lastScrollTopRef.current);
169
- }
170
- }
171
- }, isWeapp ? 200 : 150);
172
- }, []);
173
- // 暴露给外部的实例方法:通过 ref.scroll({ top / left }) 进行程序性滚动
174
- React.useImperativeHandle(ref, () => ({
175
- scroll(options) {
176
- const targetOffset = resolveScrollTargetOffset(options, isHorizontal);
177
- const el = effectiveScrollElement === null || effectiveScrollElement === void 0 ? void 0 : effectiveScrollElement.current;
178
- if (el && isH5) {
179
- const scrollTarget = targetOffset + effectiveStartOffset;
180
- if (isHorizontal) {
181
- el.scrollTo({ left: scrollTarget });
182
- }
183
- else {
184
- el.scrollTo({ top: scrollTarget });
185
- }
186
- updateRenderOffset(targetOffset, false, 'scrollElement');
187
- }
188
- else {
189
- updateRenderOffset(targetOffset, true, 'imperative');
190
- }
191
- },
192
- }), [scrollX, effectiveScrollElement, effectiveStartOffset, isH5, isHorizontal, updateRenderOffset]);
193
- // 提取 Refresher 配置(List 属性为 base,Refresher 子组件覆盖)
194
- const refresherConfig = React.useMemo(() => {
195
- const listRefresherEnabled = props.refresherEnabled !== false && (props.refresherEnabled === true || props.onRefresherRefresh != null);
196
- const baseFromList = listRefresherEnabled
197
- ? {
198
- refresherEnabled: props.refresherEnabled,
199
- refresherThreshold: props.refresherThreshold,
200
- refresherDefaultStyle: props.refresherDefaultStyle,
201
- refresherBackground: props.refresherBackground,
202
- refresherTriggered: props.refresherTriggered,
203
- onRefresherPulling: props.onRefresherPulling,
204
- onRefresherRefresh: props.onRefresherRefresh,
205
- onRefresherRestore: props.onRefresherRestore,
206
- onRefresherAbort: props.onRefresherAbort,
207
- onRefresherWillRefresh: props.onRefresherWillRefresh,
208
- onRefresherStatusChange: props.onRefresherStatusChange,
209
- }
210
- : null;
211
- const isRefresherComponent = (child) => {
212
- const type = child.type;
213
- return (type === null || type === void 0 ? void 0 : type.displayName) === 'Refresher' || (type === null || type === void 0 ? void 0 : type.name) === 'Refresher';
214
- };
215
- let refresherChildProps = null;
216
- let refresherCount = 0;
217
- React.Children.forEach(children, (child) => {
218
- if (React.isValidElement(child) && isRefresherComponent(child)) {
219
- refresherCount++;
220
- if (refresherCount > 1) {
221
- return;
222
- }
223
- refresherChildProps = child.props;
224
- }
225
- });
226
- if (refresherChildProps != null) {
227
- const base = baseFromList !== null && baseFromList !== void 0 ? baseFromList : {};
228
- // Refresher 子组件的配置覆盖 List 的配置
229
- return Object.assign(Object.assign({}, base), refresherChildProps);
230
- }
231
- return baseFromList;
232
- }, [
233
- children,
234
- props.refresherEnabled,
235
- props.refresherThreshold,
236
- props.refresherDefaultStyle,
237
- props.refresherBackground,
238
- props.refresherTriggered,
239
- props.onRefresherPulling,
240
- props.onRefresherRefresh,
241
- props.onRefresherRestore,
242
- props.onRefresherAbort,
243
- props.onRefresherWillRefresh,
244
- props.onRefresherStatusChange,
245
- ]);
246
- // 提取 NoMore 配置
247
- const noMoreConfig = React.useMemo(() => {
248
- var _a;
249
- let config = null;
250
- let noMoreCount = 0;
251
- // 从子组件中提取 NoMore
252
- React.Children.forEach(children, (child) => {
253
- if (React.isValidElement(child) && child.type === NoMore) {
254
- noMoreCount++;
255
- if (noMoreCount > 1) {
256
- return;
257
- }
258
- const childProps = child.props;
259
- config = Object.assign(Object.assign({}, childProps), { visible: childProps.visible !== false });
260
- }
261
- });
262
- // Props 方式转换为配置(优先级低于子组件)
263
- if (props.showNoMore && !config) {
264
- config = {
265
- visible: true,
266
- text: props.noMoreText,
267
- style: props.noMoreStyle,
268
- children: (_a = props.renderNoMore) === null || _a === void 0 ? void 0 : _a.call(props)
269
- };
270
- }
271
- return config;
272
- }, [children, props.showNoMore, props.noMoreText, props.noMoreStyle, props.renderNoMore]);
273
- // Refresher 平台适配:H5 用 addImperativeTouchListeners
274
- const { scrollViewRefresherProps, scrollViewRefresherHandlers, h5RefresherProps, addImperativeTouchListeners, renderRefresherContent, } = useRefresher(refresherConfig, isH5 && refresherConfig && !supportsNativeRefresher ? 0 : renderOffset, useScrollElementMode
275
- ? (ev) => { var _a, _b; return (_b = (ev.target != null && ((_a = contentWrapperRef.current) === null || _a === void 0 ? void 0 : _a.contains(ev.target)))) !== null && _b !== void 0 ? _b : false; }
276
- : undefined);
277
- const refresherTeardownRef = React.useRef(null);
278
- const addImperativeTouchListenersRef = React.useRef(addImperativeTouchListeners);
279
- addImperativeTouchListenersRef.current = addImperativeTouchListeners;
280
- React.useEffect(() => () => {
281
- if (refresherTeardownRef.current)
282
- refresherTeardownRef.current();
283
- }, []);
284
- // H5 下拉刷新顶栏高度(默认 50px,来自 useRefresher)
285
- const refresherHeightForH5 = (isH5 && refresherConfig && !supportsNativeRefresher && refresherConfig.refresherEnabled !== false) ? DEFAULT_REFRESHER_HEIGHT : 0;
286
49
  // 解析分组结构,只支持 StickySection 和 ListItem 作为直接子组件
287
- // 过滤掉 Refresher 和 NoMore 组件
288
50
  const sections = React.useMemo(() => {
289
51
  const result = [];
290
52
  const defaultItems = [];
@@ -306,109 +68,14 @@ const InnerList = (props, ref) => {
306
68
  // 普通 ListItem
307
69
  defaultItems.push(child);
308
70
  }
309
- // 忽略 Refresher 和 NoMore 组件(已在上面提取配置)
310
71
  });
311
72
  if (defaultItems.length > 0) {
312
73
  result.push({ header: null, items: defaultItems, key: 'default' });
313
74
  }
314
75
  return result;
315
76
  }, [children]);
316
- // 动态尺寸管理
317
- const defaultEstimatedSize = isHorizontal ? DEFAULT_ITEM_WIDTH : DEFAULT_ITEM_HEIGHT;
318
- const estimatedSize = (_a = props.estimatedItemSize) !== null && _a !== void 0 ? _a : defaultEstimatedSize;
319
- // 计算总 item 数量(跨所有 section)
320
- const totalItemCount = React.useMemo(() => {
321
- return sections.reduce((sum, section) => sum + section.items.length, 0);
322
- }, [sections]);
323
- // 存储元素引用(用于 ResizeObserver)
324
- const itemRefsRef = React.useRef(new Map());
325
- // 存储 header 元素引用(用于 ResizeObserver)
326
- const headerRefsRef = React.useRef(new Map());
327
- // 小程序端:已完成 SelectorQuery 测量的 item 索引集,避免 refCallback 重复触发测量导致无限循环
328
- const weappMeasuredItemsRef = React.useRef(new Set());
329
- // 动态尺寸缓存更新版本:setItemSize 后递增,用于驱动 sectionOffsets/totalLength 与 item 定位重算
330
- const [sizeCacheVersion, setSizeCacheVersion] = React.useState(0);
331
- const sizeCacheRafRef = React.useRef(null);
332
- // 小程序端:测量触发 re-render 时,reflow 帧传 eff 并同步 scrollViewOffset,避免下一帧传 0 导致跳变
333
- const measureScrollProtectRef = React.useRef(false);
334
- // 动态尺寸缓存
335
- const sizeCache = useItemSizeCache({
336
- isHorizontal,
337
- estimatedItemSize: estimatedSize,
338
- itemCount: totalItemCount
339
- });
340
- // header 动态尺寸缓存(sectionIndex -> size)
341
- const headerSizeCacheRef = React.useRef(new Map());
342
- // 滚动修正的可见起始索引(后续更新)
343
- const visibleStartIndexRef = React.useRef(0);
344
- // ScrollTop 修正(仅 H5):动高时尺寸变化自动修正 scrollTop
345
- const scrollCorrectionEnabled = !isWeapp && props.useResizeObserver === true;
346
- const scrollCorrection = useScrollCorrection({
347
- enabled: scrollCorrectionEnabled,
348
- visibleStartIndexRef,
349
- setScrollOffset: (offsetOrUpdater) => {
350
- const newOffset = typeof offsetOrUpdater === 'function'
351
- ? offsetOrUpdater(renderOffset)
352
- : offsetOrUpdater;
353
- updateRenderOffset(newOffset, true, 'scrollCorrection'); // 程序性修正需同步到 ScrollView
354
- }
355
- });
356
- const scrollCorrectionRef = React.useRef(scrollCorrection);
357
- scrollCorrectionRef.current = scrollCorrection;
358
- const onScrollRef = React.useRef(onScroll);
359
- onScrollRef.current = onScroll;
360
- const onScrollToUpperRef = React.useRef(onScrollToUpper);
361
- onScrollToUpperRef.current = onScrollToUpper;
362
- const onScrollToLowerRef = React.useRef(onScrollToLower);
363
- onScrollToLowerRef.current = onScrollToLower;
364
- const thresholdRef = React.useRef({ upper: upperThreshold, lower: lowerThreshold });
365
- thresholdRef.current = { upper: upperThreshold, lower: lowerThreshold };
366
- // 小程序 + 动高(virtual-list 风格):测量变化后同帧重排,不做程序性 scrollTop 回拉
367
- const scheduleWeappDynamicReflow = React.useCallback(() => {
368
- if (!isWeapp || props.useResizeObserver !== true)
369
- return;
370
- if (sizeCacheRafRef.current != null)
371
- return;
372
- sizeCacheRafRef.current = requestAnimationFrame(() => {
373
- sizeCacheRafRef.current = null;
374
- measureScrollProtectRef.current = true;
375
- setSizeCacheVersion((v) => v + 1);
376
- });
377
- }, [isWeapp, props.useResizeObserver]);
378
- // ResizeObserver(当启用动态测量时)
379
- const resizeObserver = useResizeObserver({
380
- enabled: props.useResizeObserver === true,
381
- isHorizontal,
382
- listId,
383
- onResize: (index, size) => {
384
- var _a;
385
- const oldSize = sizeCache.getItemSize(index);
386
- sizeCache.setItemSize(index, size);
387
- if (Math.abs(oldSize - size) >= 1) {
388
- if (isWeapp && props.useResizeObserver === true) {
389
- scheduleWeappDynamicReflow();
390
- }
391
- else if (sizeCacheRafRef.current == null) {
392
- sizeCacheRafRef.current = requestAnimationFrame(() => {
393
- sizeCacheRafRef.current = null;
394
- setSizeCacheVersion((v) => v + 1);
395
- });
396
- }
397
- }
398
- // 触发 ScrollTop 修正
399
- scrollCorrection.recordSizeChange(index, oldSize, size);
400
- // 小程序:延迟 onItemSizeChange,避免父组件重渲染导致 List remount
401
- // H5:直接回调
402
- if (isWeapp) {
403
- weappDeferItemSizeChange(index, size, props.onItemSizeChange);
404
- }
405
- else {
406
- (_a = props.onItemSizeChange) === null || _a === void 0 ? void 0 : _a.call(props, index, size);
407
- }
408
- }
409
- });
410
- // 工具:获取 header 默认/估算尺寸
411
- const getDefaultHeaderSize = () => {
77
+ // 工具:获取 header 尺寸,确保所有 header 相关逻辑一致
78
+ const getHeaderSize = () => {
412
79
  if (isHorizontal) {
413
80
  if (typeof props.headerWidth === 'number')
414
81
  return props.headerWidth;
@@ -432,24 +99,8 @@ const InnerList = (props, ref) => {
432
99
  return DEFAULT_ITEM_HEIGHT;
433
100
  }
434
101
  };
435
- // 工具:获取 header 尺寸(支持动态测量)
436
- const getHeaderSize = React.useCallback((sectionIndex) => {
437
- // 如果启用动态测量,优先从缓存读取
438
- if (props.useResizeObserver === true) {
439
- const cached = headerSizeCacheRef.current.get(sectionIndex);
440
- if (cached != null && cached > 0)
441
- return cached;
442
- }
443
- // 否则返回默认尺寸
444
- return getDefaultHeaderSize();
445
- }, [props.useResizeObserver, props.headerHeight, props.headerWidth, props.itemHeight, props.itemWidth, props.itemSize, props.itemData, isHorizontal]);
446
- // 工具:获取 item 尺寸,支持函数/props/默认值/动态测量
447
- const getItemSize = React.useCallback((index) => {
448
- // 优先级1:如果启用动态测量,从缓存读取
449
- if (props.useResizeObserver === true) {
450
- return sizeCache.getItemSize(index);
451
- }
452
- // 优先级2:固定尺寸或函数计算
102
+ // 工具:获取 item 尺寸,支持函数/props/默认值
103
+ const getItemSize = (index) => {
453
104
  if (isHorizontal) {
454
105
  if (typeof props.itemWidth === 'number')
455
106
  return props.itemWidth;
@@ -468,24 +119,20 @@ const InnerList = (props, ref) => {
468
119
  return props.itemSize(index, props.itemData) || DEFAULT_ITEM_HEIGHT;
469
120
  return DEFAULT_ITEM_HEIGHT;
470
121
  }
471
- }, [props.useResizeObserver, props.itemWidth, props.itemHeight, props.itemSize, props.itemData, isHorizontal, sizeCache]);
472
- // 分组累积高度/宽度,sizeCacheVersion 变化时重算
122
+ };
123
+ // 计算分组累积高度/宽度
473
124
  const sectionOffsets = React.useMemo(() => {
474
125
  const offsets = [0];
475
- let globalItemIndex = 0; // 累加全局索引
476
- sections.forEach((section, sectionIdx) => {
477
- const headerSize = getHeaderSize(sectionIdx);
478
- // 使用全局索引计算每个 item 的尺寸
479
- const itemSizes = section.items.map((_, localIdx) => getItemSize(globalItemIndex + localIdx));
126
+ sections.forEach((section) => {
127
+ const headerSize = getHeaderSize();
128
+ const itemSizes = section.items.map((_, i) => getItemSize(i));
480
129
  const groupSize = (section.header ? headerSize : 0) +
481
130
  itemSizes.reduce((a, b) => a + b, 0) +
482
131
  Math.max(0, section.items.length) * space;
483
132
  offsets.push(offsets[offsets.length - 1] + groupSize);
484
- // 累加当前 section 的 item 数量
485
- globalItemIndex += section.items.length;
486
133
  });
487
134
  return offsets;
488
- }, [sections, space, isHorizontal, props.headerHeight, props.headerWidth, props.itemHeight, props.itemWidth, props.itemSize, props.itemData, getItemSize, getHeaderSize, sizeCacheVersion]);
135
+ }, [sections, space, isHorizontal, props.headerHeight, props.headerWidth, props.itemHeight, props.itemWidth, props.itemSize, props.itemData]);
489
136
  // 外层虚拟滚动:可见分组
490
137
  const [startSection, endSection] = React.useMemo(() => {
491
138
  let start = 0;
@@ -504,306 +151,119 @@ const InnerList = (props, ref) => {
504
151
  }
505
152
  return [start, end];
506
153
  }, [renderOffset, containerLength, sectionOffsets, sections.length, cacheCount]);
507
- // 视口内可见 item 的全局索引范围(供 onScrollIndex)
508
- const [visibleStartItem, visibleEndItem] = React.useMemo(() => {
509
- const viewportTop = renderOffset;
510
- const viewportBottom = renderOffset + containerLength;
511
- let firstVisible = -1;
512
- let lastVisible = -1;
513
- let globalIndex = 0;
514
- for (let s = 0; s < sections.length; s++) {
515
- const section = sections[s];
516
- const headerSize = getHeaderSize(s);
517
- const sectionStart = sectionOffsets[s] + (section.header ? headerSize : 0);
518
- let itemTop = sectionStart;
519
- for (let i = 0; i < section.items.length; i++) {
520
- const itemSize = getItemSize(globalIndex);
521
- const itemBottom = itemTop + itemSize;
522
- // 判断 item 本身(不含 space)是否与视口相交
523
- if (itemBottom > viewportTop && itemTop < viewportBottom) {
524
- if (firstVisible < 0)
525
- firstVisible = globalIndex;
526
- lastVisible = globalIndex;
527
- }
528
- // 下一个 item 的起始位置 = 当前 item 结束 + space
529
- itemTop = itemBottom + space;
530
- globalIndex++;
531
- }
532
- }
533
- if (firstVisible < 0 || lastVisible < 0)
534
- return [0, 0];
535
- return [firstVisible, lastVisible];
536
- }, [renderOffset, containerLength, sections, sectionOffsets, getHeaderSize, getItemSize, space]);
537
- // 触发 onScrollIndex 回调(带防重复)
538
- const lastVisibleRangeRef = React.useRef({ start: -1, end: -1 });
154
+ // 触顶/触底事件
539
155
  React.useEffect(() => {
540
- if (props.onScrollIndex) {
541
- // 避免重复触发
542
- if (lastVisibleRangeRef.current.start !== visibleStartItem ||
543
- lastVisibleRangeRef.current.end !== visibleEndItem) {
544
- lastVisibleRangeRef.current = { start: visibleStartItem, end: visibleEndItem };
545
- props.onScrollIndex(visibleStartItem, visibleEndItem);
546
- }
156
+ if (onScrollToUpper && renderOffset <= (upperThreshold > 0 ? sectionOffsets[upperThreshold] : 0)) {
157
+ onScrollToUpper();
158
+ }
159
+ if (onScrollToLower && renderOffset + containerLength >= sectionOffsets[sectionOffsets.length - 1] - (lowerThreshold > 0 ? sectionOffsets[sectionOffsets.length - 1] - sectionOffsets[sections.length - lowerThreshold] : 0)) {
160
+ onScrollToLower();
161
+ }
162
+ }, [renderOffset, containerLength, sectionOffsets, sections.length, upperThreshold, lowerThreshold, onScrollToUpper, onScrollToLower]);
163
+ // 处理渲染偏移量更新
164
+ const updateRenderOffset = React.useCallback((newOffset) => {
165
+ lastScrollTopRef.current = newOffset;
166
+ isScrollingRef.current = true;
167
+ if (scrollTimeoutRef.current) {
168
+ clearTimeout(scrollTimeoutRef.current);
169
+ }
170
+ setRenderOffset(newOffset); // 立即更新渲染偏移量
171
+ // 平台适配:微信小程序使用延时,其他平台立即更新
172
+ const isWeapp = process.env.TARO_ENV === 'weapp';
173
+ if (isWeapp) {
174
+ // 微信小程序:使用延时避免抖动
175
+ scrollTimeoutRef.current = setTimeout(() => {
176
+ isScrollingRef.current = false;
177
+ setScrollViewOffset(newOffset); // 滚动结束后,同步滚动视图偏移量
178
+ }, 200);
547
179
  }
548
- }, [visibleStartItem, visibleEndItem, props.onScrollIndex]);
180
+ else {
181
+ // 其他平台:立即更新以获得更好的响应性
182
+ setScrollViewOffset(newOffset); // 立即更新滚动视图偏移量
183
+ scrollTimeoutRef.current = setTimeout(() => {
184
+ isScrollingRef.current = false;
185
+ }, 200);
186
+ }
187
+ }, []);
188
+ // 智能滚动处理函数
549
189
  const handleScroll = React.useCallback((e) => {
190
+ // 兼容Stencil版本和React版本的事件结构
550
191
  let newOffset;
551
192
  if (e.detail) {
193
+ // React版本的事件结构
552
194
  newOffset = isHorizontal ? e.detail.scrollLeft : e.detail.scrollTop;
553
195
  }
554
196
  else {
197
+ // Stencil版本的事件结构
555
198
  newOffset = isHorizontal ? e.scrollLeft : e.scrollTop;
556
199
  }
557
- const effectiveOffset = newOffset;
558
- const diff = effectiveOffset - lastScrollTopRef.current;
200
+ const diff = newOffset - lastScrollTopRef.current;
559
201
  scrollDiffListRef.current.shift();
560
202
  scrollDiffListRef.current.push(diff);
561
- const shaking = isScrollingRef.current && isShaking(scrollDiffListRef.current);
562
- if (shaking)
563
- return;
564
- if (programmaticCooldownRef.current) {
565
- lastScrollTopRef.current = effectiveOffset;
566
- setRenderOffset(effectiveOffset);
567
- onScroll === null || onScroll === void 0 ? void 0 : onScroll({
568
- scrollTop: isHorizontal ? 0 : newOffset,
569
- scrollLeft: isHorizontal ? newOffset : 0
570
- });
203
+ // 只保留抖动检测,移除方向检测
204
+ if (isScrollingRef.current && isShaking(scrollDiffListRef.current)) {
571
205
  return;
572
206
  }
573
- scrollCorrection.markUserScrolling();
574
- updateRenderOffset(effectiveOffset, false, 'onScroll');
207
+ updateRenderOffset(newOffset); // 直接更新渲染偏移量
575
208
  onScroll === null || onScroll === void 0 ? void 0 : onScroll({
576
209
  scrollTop: isHorizontal ? 0 : newOffset,
577
210
  scrollLeft: isHorizontal ? newOffset : 0
578
211
  });
579
- }, [isHorizontal, onScroll, updateRenderOffset, scrollCorrection, props.useResizeObserver]);
580
- // 小程序:onScrollEnd 优先结束 isUserScrolling,timeout 兜底
581
- const handleNativeScrollEnd = React.useCallback(() => {
582
- if (isWeapp) {
583
- if (scrollTimeoutRef.current) {
584
- clearTimeout(scrollTimeoutRef.current);
585
- scrollTimeoutRef.current = null;
586
- }
587
- if (isUserScrollingRef.current) {
588
- isScrollingRef.current = false;
589
- isUserScrollingRef.current = false;
590
- setIsUserScrolling(false);
591
- // recycle-view 策略:不把用户滑动位置同步到 scrollViewOffset
592
- }
593
- }
594
- onScrollEnd === null || onScrollEnd === void 0 ? void 0 : onScrollEnd();
595
- }, [isWeapp, onScrollEnd]);
596
- // 任务 2.3:暴露 scrollRef 给父组件(供内层 List/WaterFlow 传入 scrollElement)
597
- // 收敛到此处统一赋值,不再在 ResizeObserver 中重复
598
- React.useLayoutEffect(() => {
599
- if (!scrollRefProp)
600
- return;
601
- const el = useScrollElementMode ? effectiveScrollElement === null || effectiveScrollElement === void 0 ? void 0 : effectiveScrollElement.current : containerRef.current;
602
- if (el) {
603
- scrollRefProp.current = el;
604
- }
605
- }, [scrollRefProp, useScrollElementMode, effectiveScrollElement]);
606
- // controlledScrollTop 变化时同步到 ScrollView
212
+ }, [isHorizontal, onScroll, updateRenderOffset, containerLength]);
213
+ // 初始化后的延迟同步 - 确保ScrollView正确设置初始位置
607
214
  React.useEffect(() => {
608
215
  if (typeof controlledScrollTop === 'number') {
609
- const sv = scrollViewOffsetRef.current;
610
- const same = isWeapp && Math.abs(sv - controlledScrollTop) < 1;
611
- if (same) {
612
- const intermediate = controlledScrollTop > 0 ? controlledScrollTop - 0.01 : 0.01;
613
- setRenderOffset(intermediate);
614
- setScrollViewOffset(intermediate);
615
- requestAnimationFrame(() => {
616
- setRenderOffset(controlledScrollTop);
617
- setScrollViewOffset(controlledScrollTop);
618
- });
619
- }
620
- else {
621
- setRenderOffset(controlledScrollTop);
622
- setScrollViewOffset(controlledScrollTop);
623
- }
216
+ setScrollViewOffset(controlledScrollTop);
624
217
  lastScrollTopRef.current = controlledScrollTop;
625
- programmaticScrollRef.current = true;
626
218
  }
627
219
  }, [controlledScrollTop]);
628
- // 清理定时器、ResizeObserver 与尺寸缓存 RAF(仅在卸载时执行)
220
+ // 清理定时器
629
221
  React.useEffect(() => {
630
222
  return () => {
631
223
  if (scrollTimeoutRef.current) {
632
224
  clearTimeout(scrollTimeoutRef.current);
633
225
  }
634
- // 小程序端冷却期定时器清理
635
- if (isWeapp && programmaticCooldownTimerRef.current) {
636
- clearTimeout(programmaticCooldownTimerRef.current);
637
- }
638
- if (sizeCacheRafRef.current != null) {
639
- cancelAnimationFrame(sizeCacheRafRef.current);
640
- sizeCacheRafRef.current = null;
641
- }
642
- resizeObserver.disconnect();
643
- scrollCorrection.clearQueue();
644
226
  };
645
227
  }, []);
646
- // scrollIntoView:仅当 scrollIntoView 变化时执行一次跳动,统一转换为 scrollTop 路径(updateRenderOffset)。
647
- const lastScrollIntoViewRef = React.useRef(null);
648
- React.useEffect(() => {
649
- const targetId = props.scrollIntoView;
650
- if (!targetId) {
651
- lastScrollIntoViewRef.current = null;
652
- return;
653
- }
654
- if (lastScrollIntoViewRef.current === targetId)
655
- return;
656
- lastScrollIntoViewRef.current = targetId;
657
- let targetIndex = -1;
658
- if (targetId.startsWith('list-item-')) {
659
- targetIndex = parseInt(targetId.replace('list-item-', ''), 10);
660
- }
661
- if (targetIndex >= 0 && targetIndex < totalItemCount) {
662
- let targetOffset = 0;
663
- let currentGlobalIndex = 0;
664
- for (let s = 0; s < sections.length; s++) {
665
- const section = sections[s];
666
- const headerSize = section.header ? getHeaderSize(s) : 0;
667
- if (currentGlobalIndex + section.items.length > targetIndex) {
668
- targetOffset += headerSize;
669
- for (let i = 0; i < targetIndex - currentGlobalIndex; i++) {
670
- targetOffset += getItemSize(currentGlobalIndex + i) + space;
671
- }
672
- break;
673
- }
674
- else {
675
- targetOffset += headerSize;
676
- for (let i = 0; i < section.items.length; i++) {
677
- targetOffset += getItemSize(currentGlobalIndex + i) + space;
678
- }
679
- currentGlobalIndex += section.items.length;
680
- }
681
- }
682
- updateRenderOffset(targetOffset, true, 'scrollIntoView');
683
- // scrollElement 模式下需显式滚动外部容器,否则仅 updateRenderOffset 不会滚动 div
684
- if (useScrollElementMode && (effectiveScrollElement === null || effectiveScrollElement === void 0 ? void 0 : effectiveScrollElement.current) && isH5) {
685
- const el = effectiveScrollElement.current;
686
- const scrollTarget = targetOffset + effectiveStartOffset;
687
- if (isHorizontal) {
688
- el.scrollTo({ left: scrollTarget });
689
- }
690
- else {
691
- el.scrollTo({ top: scrollTarget });
692
- }
693
- }
694
- }
695
- }, [props.scrollIntoView, totalItemCount, sections, getHeaderSize, getItemSize, space, updateRenderOffset, useScrollElementMode, effectiveScrollElement, effectiveStartOffset, isH5, isHorizontal]);
696
- // 容器样式;H5 刷新中禁止滚动
697
- const containerStyle = Object.assign(Object.assign({ position: 'relative', boxSizing: 'border-box', height,
698
- width }, style), (isH5 && refresherConfig && !supportsNativeRefresher && h5RefresherProps.isRefreshing
699
- ? { overflow: 'hidden' }
700
- : {}));
228
+ // 容器样式
229
+ const containerStyle = Object.assign({ position: 'relative', boxSizing: 'border-box', height: isHorizontal ? width : height, width: isHorizontal ? height : width }, style);
230
+ // 修改ScrollView组件的props,添加data-testid属性
701
231
  // ScrollView 属性
702
- const scrollViewProps = Object.assign(Object.assign(Object.assign(Object.assign({ scrollY: !scrollX && scrollY, scrollX, style: containerStyle, className, enhanced: true, showScrollbar,
703
- upperThreshold,
704
- lowerThreshold, scrollWithAnimation: false, onScroll: handleScroll, onScrollToUpper,
232
+ const scrollViewProps = {
233
+ scrollY: !scrollX && scrollY,
234
+ scrollX: scrollX,
235
+ style: containerStyle,
236
+ enhanced: true,
237
+ showScrollbar: showScrollbar,
238
+ onScroll: handleScroll,
239
+ onScrollToUpper,
705
240
  onScrollToLower,
706
- onScrollStart, onScrollEnd: handleNativeScrollEnd, enableBackToTop }, (isWeapp ? { scrollAnchoring: true } : {})), (typeof cacheExtent === 'number' ? { cacheExtent } : {})), scrollViewRefresherProps), scrollViewRefresherHandlers);
707
- // H5 对齐小程序:refresherTriggered=true 时顶部立即显示加载指示器,滚到顶部并锁定滚动直至设为 false
708
- React.useEffect(() => {
709
- if (!isH5 || !refresherConfig || supportsNativeRefresher || !h5RefresherProps.isRefreshing)
710
- return;
711
- updateRenderOffset(0, true, 'refresher');
712
- }, [h5RefresherProps.isRefreshing, isH5, refresherConfig, supportsNativeRefresher, updateRenderOffset]);
713
- // H5 下拉刷新:ref 存 addImperativeTouchListeners,避免 config 变化导致 effect 循环
714
- React.useLayoutEffect(() => {
715
- const attach = addImperativeTouchListenersRef.current;
716
- if (!attach)
717
- return;
718
- let teardown = null;
719
- const tryAttach = () => {
720
- const el = useScrollElementMode ? effectiveScrollElement === null || effectiveScrollElement === void 0 ? void 0 : effectiveScrollElement.current : containerRef.current;
721
- if (el && !refresherTeardownRef.current) {
722
- teardown = attach(el);
723
- refresherTeardownRef.current = teardown;
724
- }
725
- };
726
- tryAttach();
727
- const rafId = requestAnimationFrame(tryAttach);
728
- return () => {
729
- cancelAnimationFrame(rafId);
730
- if (teardown) {
731
- teardown();
732
- }
733
- refresherTeardownRef.current = null;
734
- };
735
- }, [useScrollElementMode, effectiveScrollElement]);
736
- scrollViewOffsetRef.current = scrollViewOffset;
737
- // scrollTop:weapp 传 scrollViewOffset(reflow 帧传 eff 防跳变);H5 仅非用户滑动时传
738
- if (isWeapp) {
739
- if (measureScrollProtectRef.current) {
740
- measureScrollProtectRef.current = false;
741
- const eff = lastScrollTopRef.current;
742
- setScrollViewOffset(eff);
743
- if (isHorizontal) {
744
- scrollViewProps.scrollLeft = eff;
745
- }
746
- else {
747
- scrollViewProps.scrollTop = eff;
748
- }
749
- programmaticScrollRef.current = false;
750
- }
751
- else {
752
- const sv = scrollViewOffset;
753
- if (isHorizontal) {
754
- scrollViewProps.scrollLeft = sv;
755
- }
756
- else {
757
- scrollViewProps.scrollTop = sv;
758
- }
759
- programmaticScrollRef.current = false;
760
- }
241
+ 'data-testid': 'taro-list-container'
242
+ };
243
+ // 设置ScrollView的滚动位置 - 同时兼容React版本和Stencil版本
244
+ if (isHorizontal) {
245
+ scrollViewProps.scrollLeft = scrollViewOffset; // React版本
246
+ scrollViewProps.mpScrollLeft = scrollViewOffset; // Stencil版本
761
247
  }
762
248
  else {
763
- // H5:非用户滑动时传
764
- if (!isUserScrolling) {
765
- if (isHorizontal) {
766
- scrollViewProps.scrollLeft = scrollViewOffset;
767
- }
768
- else {
769
- scrollViewProps.scrollTop = scrollViewOffset;
249
+ scrollViewProps.scrollTop = scrollViewOffset; // React版本
250
+ scrollViewProps.mpScrollTop = scrollViewOffset; // Stencil版本
251
+ }
252
+ // H5上额外使用DOM直接操作确保滚动位置正确
253
+ if (isH5) {
254
+ React.useEffect(() => {
255
+ if (containerRef.current && typeof scrollViewOffset === 'number') {
256
+ if (isHorizontal) {
257
+ containerRef.current.scrollLeft = scrollViewOffset;
258
+ }
259
+ else {
260
+ containerRef.current.scrollTop = scrollViewOffset;
261
+ }
770
262
  }
771
- }
263
+ }, [scrollViewOffset, isHorizontal]);
772
264
  }
773
- // H5:程序性滚动时写回 DOM scrollTop
774
- React.useEffect(() => {
775
- if (!isH5)
776
- return;
777
- if (isUserScrolling || !containerRef.current || typeof scrollViewOffset !== 'number')
778
- return;
779
- if (!programmaticScrollRef.current)
780
- return;
781
- const scrollValue = scrollViewOffset;
782
- if (isHorizontal) {
783
- containerRef.current.scrollLeft = scrollValue;
784
- }
785
- else {
786
- containerRef.current.scrollTop = scrollValue;
787
- }
788
- programmaticScrollRef.current = false;
789
- }, [isH5, scrollViewOffset, isHorizontal, isUserScrolling]);
790
- // 总高度/宽度(含 NoMore)
791
- const noMoreHeight = (noMoreConfig === null || noMoreConfig === void 0 ? void 0 : noMoreConfig.visible) ? (noMoreConfig.height || 60) : 0;
792
- const listContentLength = sectionOffsets[sectionOffsets.length - 1] + noMoreHeight;
793
- const totalLength = listContentLength;
794
- // scrollElement 模式下 onScrollToLower 需用内层内容高度判断,供 scroll handler 读取
795
- const listContentLengthRef = React.useRef(0);
796
- listContentLengthRef.current = listContentLength;
797
- const scrollAttachRefsRef = React.useRef(null);
798
- scrollAttachRefsRef.current = {
799
- scrollCorrection: scrollCorrectionRef.current,
800
- onScroll: onScrollRef.current,
801
- onScrollToUpper: onScrollToUpperRef.current,
802
- onScrollToLower: onScrollToLowerRef.current,
803
- threshold: thresholdRef.current,
804
- listContentLength: listContentLengthRef.current,
805
- };
806
- useListScrollElementAttach(useScrollElementMode && isH5, effectiveScrollElement, effectiveStartOffset, isHorizontal, setContainerLength, updateRenderOffset, scrollRefProp, scrollAttachRefsRef);
265
+ // 总高度/宽度
266
+ const totalLength = sectionOffsets[sectionOffsets.length - 1];
807
267
  // 吸顶/吸左 header
808
268
  const stickyHeaderNode = React.useMemo(() => {
809
269
  if (!stickyHeader)
@@ -812,18 +272,9 @@ const InnerList = (props, ref) => {
812
272
  if (sectionOffsets[i] <= renderOffset && renderOffset < sectionOffsets[i + 1]) {
813
273
  const section = sections[i];
814
274
  if (section.header) {
815
- // 吸顶 header 不设固定 height/width,由内容撑开,避免「外部 60px 容器 + 实际内容 40+px」导致 header 内空白
816
- const stickyHeaderStyle = {
817
- position: 'sticky',
818
- top: 0,
819
- left: 0,
820
- zIndex: 100,
821
- background: '#fff',
822
- boxSizing: 'border-box',
823
- minHeight: 20,
824
- overflow: 'hidden',
825
- lineHeight: 1
826
- };
275
+ const headerSize = getHeaderSize();
276
+ // 内联样式替代className
277
+ const stickyHeaderStyle = Object.assign({ position: 'sticky', top: 0, left: 0, zIndex: 100, background: '#fff', boxSizing: 'border-box', minHeight: '20px', overflow: 'hidden', lineHeight: 1 }, (isHorizontal ? { width: headerSize } : { height: headerSize }));
827
278
  return (jsx(View, { style: stickyHeaderStyle, children: section.header }));
828
279
  }
829
280
  }
@@ -834,105 +285,20 @@ const InnerList = (props, ref) => {
834
285
  const renderSections = () => {
835
286
  const nodes = [];
836
287
  let offset = sectionOffsets[startSection];
837
- let globalItemIndex = 0; // 全局 item 索引(跨 section)
838
- // 计算起始 section 之前的所有 item 数量
839
- for (let s = 0; s < startSection; s++) {
840
- globalItemIndex += sections[s].items.length;
841
- }
842
288
  for (let s = startSection; s <= endSection; s++) {
843
289
  const section = sections[s];
844
- const headerSize = getHeaderSize(s);
845
- const itemSizes = section.items.map((_, i) => getItemSize(globalItemIndex + i));
290
+ const headerSize = getHeaderSize();
291
+ const itemSizes = section.items.map((_, i) => getItemSize(i));
846
292
  // header
847
293
  if (section.header) {
848
- const sectionIndex = s;
849
- // 动态测量时外层定位容器不设固定高度,由内层撑开
294
+ // 内联样式替代className
850
295
  const sectionHeaderStyle = Object.assign({ position: 'absolute', zIndex: 2, boxSizing: 'border-box', width: '100%', minHeight: '20px', overflow: 'hidden', lineHeight: 1 }, (isHorizontal
851
- ? { top: 0, height: '100%', left: offset, width: props.useResizeObserver ? undefined : headerSize }
852
- : { top: offset, height: props.useResizeObserver ? undefined : headerSize }));
853
- // header ref 回调(用于 ResizeObserver 测量)
854
- const headerRefCallback = props.useResizeObserver ? (el) => {
855
- if (el) {
856
- headerRefsRef.current.set(sectionIndex, el);
857
- resizeObserver.observe(el, -sectionIndex - 1); // 用负数索引区分 header 和 item
858
- const measureAndUpdateHeader = (measured) => {
859
- var _a;
860
- if (measured > 0) {
861
- const oldSize = (_a = headerSizeCacheRef.current.get(sectionIndex)) !== null && _a !== void 0 ? _a : getDefaultHeaderSize();
862
- if (Math.abs(oldSize - measured) >= 1) {
863
- headerSizeCacheRef.current.set(sectionIndex, measured);
864
- if (isWeapp && props.useResizeObserver === true) {
865
- scheduleWeappDynamicReflow();
866
- }
867
- else if (sizeCacheRafRef.current == null) {
868
- sizeCacheRafRef.current = requestAnimationFrame(() => {
869
- sizeCacheRafRef.current = null;
870
- setSizeCacheVersion((v) => v + 1);
871
- });
872
- }
873
- }
874
- }
875
- };
876
- if (isH5) {
877
- requestAnimationFrame(() => {
878
- if (!headerRefsRef.current.has(sectionIndex))
879
- return;
880
- const rect = el.getBoundingClientRect();
881
- measureAndUpdateHeader(isHorizontal ? rect.width : rect.height);
882
- });
883
- }
884
- else if (isWeapp) {
885
- Taro.nextTick(() => {
886
- if (!headerRefsRef.current.has(sectionIndex))
887
- return;
888
- Taro.createSelectorQuery()
889
- .select(`#${listId}-list-header-inner-${sectionIndex}`)
890
- .boundingClientRect((rect) => {
891
- if (rect) {
892
- measureAndUpdateHeader(isHorizontal ? rect.width : rect.height);
893
- }
894
- })
895
- .exec();
896
- });
897
- }
898
- }
899
- else {
900
- const oldEl = headerRefsRef.current.get(sectionIndex);
901
- if (oldEl) {
902
- resizeObserver.unobserve(oldEl);
903
- headerRefsRef.current.delete(sectionIndex);
904
- }
905
- }
906
- } : undefined;
907
- // 动态尺寸时:外层定位,内层撑开以便测量
908
- const headerContentStyle = props.useResizeObserver
909
- ? (isHorizontal
910
- // weapp 下 max-content 兼容性不稳定,改用 inline-flex 收缩包裹以测得真实宽度
911
- ? (isWeapp
912
- ? { boxSizing: 'border-box', display: 'inline-flex', height: '100%' }
913
- : { boxSizing: 'border-box', width: 'max-content', height: '100%' })
914
- : { boxSizing: 'border-box', width: '100%' })
915
- : {};
916
- if (props.useResizeObserver) {
917
- const headerInnerProps = {
918
- ref: headerRefCallback,
919
- style: headerContentStyle,
920
- 'data-index': String(-sectionIndex - 1), // 用于 unobserve 获取 index;与 observe(el, -sectionIndex-1) 对应
921
- };
922
- if (isWeapp) {
923
- headerInnerProps.id = `${listId}-list-header-inner-${sectionIndex}`;
924
- }
925
- nodes.push(React.createElement(View, {
926
- key: section.key + '-header',
927
- style: sectionHeaderStyle,
928
- }, React.createElement(View, headerInnerProps, section.header)));
929
- }
930
- else {
931
- nodes.push(React.createElement(View, {
932
- key: section.key + '-header',
933
- style: sectionHeaderStyle,
934
- }, section.header));
935
- }
296
+ ? { top: 0, height: '100%', left: offset, width: headerSize }
297
+ : { top: offset, height: headerSize }));
298
+ nodes.push(React.createElement(View, {
299
+ key: section.key + '-header',
300
+ style: sectionHeaderStyle,
301
+ }, section.header));
936
302
  offset += headerSize;
937
303
  }
938
304
  // item offsets
@@ -952,17 +318,9 @@ const InnerList = (props, ref) => {
952
318
  break;
953
319
  }
954
320
  }
955
- // 更新可见起始索引(用于 ScrollCorrection)
956
- if (s === startSection && startItem === 0) {
957
- visibleStartIndexRef.current = globalItemIndex;
958
- }
959
- else if (s === startSection) {
960
- visibleStartIndexRef.current = globalItemIndex + startItem;
961
- }
962
321
  // 渲染可见item
963
322
  for (let i = startItem; i <= endItem; i++) {
964
- const currentGlobalIndex = globalItemIndex + i;
965
- const itemId = `list-item-${currentGlobalIndex}`;
323
+ // 内联样式替代className
966
324
  const sectionItemStyle = Object.assign({ position: 'absolute', zIndex: 1, boxSizing: 'border-box', width: '100%', minHeight: '20px', overflow: 'hidden', lineHeight: 1 }, (isHorizontal
967
325
  ? {
968
326
  top: 0,
@@ -976,248 +334,17 @@ const InnerList = (props, ref) => {
976
334
  height: itemSizes[i],
977
335
  marginBottom: space
978
336
  }));
979
- // ResizeObserver:绑定内层内容容器测量真实尺寸,尺寸变化时才 bump 版本
980
- const refCallback = (el) => {
981
- if (el) {
982
- const capturedIndex = currentGlobalIndex;
983
- itemRefsRef.current.set(capturedIndex, el);
984
- resizeObserver.observe(el, capturedIndex);
985
- // H5:使用 getBoundingClientRect 进行 fallback 测量
986
- // 小程序:使用 SelectorQuery 进行 fallback 测量(小程序没有 getBoundingClientRect)
987
- const measureAndUpdate = (measured) => {
988
- var _a;
989
- if (measured > 0) {
990
- const oldSize = sizeCache.getItemSize(capturedIndex);
991
- if (Math.abs(oldSize - measured) < 1)
992
- return;
993
- sizeCache.setItemSize(capturedIndex, measured);
994
- scrollCorrection.recordSizeChange(capturedIndex, oldSize, measured);
995
- if (isWeapp && props.useResizeObserver === true) {
996
- scheduleWeappDynamicReflow();
997
- }
998
- else if (sizeCacheRafRef.current == null) {
999
- sizeCacheRafRef.current = requestAnimationFrame(() => {
1000
- sizeCacheRafRef.current = null;
1001
- setSizeCacheVersion((v) => v + 1);
1002
- });
1003
- }
1004
- // 小程序:延迟 onItemSizeChange,避免父组件重渲染导致 List remount
1005
- if (isWeapp) {
1006
- weappDeferItemSizeChange(capturedIndex, measured, props.onItemSizeChange);
1007
- }
1008
- else {
1009
- (_a = props.onItemSizeChange) === null || _a === void 0 ? void 0 : _a.call(props, capturedIndex, measured);
1010
- }
1011
- }
1012
- };
1013
- if (isH5) {
1014
- requestAnimationFrame(() => {
1015
- if (!itemRefsRef.current.has(capturedIndex))
1016
- return;
1017
- const rect = el.getBoundingClientRect();
1018
- measureAndUpdate(isHorizontal ? rect.width : rect.height);
1019
- });
1020
- }
1021
- else if (isWeapp) {
1022
- // 小程序端:使用 SelectorQuery 测量内层内容容器的实际尺寸
1023
- // 注意:必须选 inner 容器(无固定高度,由内容撑开),不能选 outer(有虚拟列表设置的固定高度)
1024
- // 已测量过的 item 跳过,避免 refCallback 重复触发导致无限循环
1025
- // 滚动期间跳过 SelectorQuery(不加入 weappMeasuredItemsRef),避免异步查询干扰 scroll-view
1026
- // SelectorQuery 是只读查询,滚动期间执行安全
1027
- if (shouldMeasureWeappItem(capturedIndex, weappMeasuredItemsRef.current)) {
1028
- weappMeasuredItemsRef.current.add(capturedIndex);
1029
- // 使用 Taro.nextTick 代替 setTimeout(50):等待下一帧渲染完成后再测量
1030
- // 比固定延时更快(减少"预估→实测"闪烁)且更可靠(保证 DOM 已更新)
1031
- Taro.nextTick(() => {
1032
- if (!itemRefsRef.current.has(capturedIndex))
1033
- return;
1034
- Taro.createSelectorQuery()
1035
- // 页面上可能同时存在多个 List,inner id 必须带 listId 前缀避免跨列表误命中
1036
- .select(`#${listId}-list-item-inner-${capturedIndex}`)
1037
- .boundingClientRect((rect) => {
1038
- if (rect) {
1039
- measureAndUpdate(isHorizontal ? rect.width : rect.height);
1040
- }
1041
- })
1042
- .exec();
1043
- });
1044
- }
1045
- }
1046
- }
1047
- else {
1048
- const oldEl = itemRefsRef.current.get(currentGlobalIndex);
1049
- if (oldEl) {
1050
- resizeObserver.unobserve(oldEl);
1051
- itemRefsRef.current.delete(currentGlobalIndex);
1052
- }
1053
- }
1054
- };
1055
- // 动态尺寸时:外层负责定位,内层由内容撑开以便测量真实尺寸。
1056
- // 纵向:内层 width:100% 无 height,由内容撑开,测到的是内容高度。
1057
- // 横向:width:max-content + height:100%:
1058
- // - width:max-content 便于测量真实宽度;
1059
- // - height:100% 让测量层与外层 slot 条带高度一致,避免「外层条带 180px、内层 wrapper 只有内容高度」导致的内外高度差。
1060
- const contentWrapperStyle = props.useResizeObserver
1061
- ? (isHorizontal
1062
- // weapp 下 max-content 兼容性不稳定,改用 inline-flex 收缩包裹以测得真实宽度
1063
- ? (isWeapp
1064
- ? { boxSizing: 'border-box', display: 'inline-flex', height: '100%' }
1065
- : { boxSizing: 'border-box', width: 'max-content', height: '100%' })
1066
- : { boxSizing: 'border-box', width: '100%' })
1067
- : {};
1068
- const outerItemProps = {
337
+ nodes.push(React.createElement(View, {
1069
338
  key: section.key + '-item-' + i,
1070
- id: itemId,
1071
339
  style: sectionItemStyle,
1072
- };
1073
- if (props.useResizeObserver) {
1074
- const innerProps = {
1075
- ref: refCallback,
1076
- style: contentWrapperStyle,
1077
- };
1078
- // 小程序端需要 id 用于 SelectorQuery 测量内容真实尺寸;H5 端不需要(用 getBoundingClientRect)
1079
- if (isWeapp) {
1080
- // 页面内多 List 并存时避免 id 冲突(例如 demo 同页含多个 List)
1081
- innerProps.id = `${listId}-list-item-inner-${currentGlobalIndex}`;
1082
- }
1083
- innerProps['data-index'] = String(currentGlobalIndex);
1084
- const itemNode = React.createElement(View, outerItemProps, React.createElement(View, innerProps, section.items[i]));
1085
- // 任务 4.1:当 List 暴露 scrollRef 时,为每个 item 提供 Context,供内层 WaterFlow 使用
1086
- const itemWithContext = scrollRefProp && !useScrollElementMode
1087
- ? React.createElement(ScrollElementContext.Provider, {
1088
- key: outerItemProps.key,
1089
- value: {
1090
- scrollRef: scrollRefProp,
1091
- containerHeight: containerLength,
1092
- startOffset: offset + itemOffsets[i],
1093
- reportNestedHeightChange: props.useResizeObserver
1094
- ? (height) => {
1095
- if (height <= 0)
1096
- return;
1097
- const idx = currentGlobalIndex;
1098
- const estimatedHeader = estimatedSize * 0.5;
1099
- const fullHeight = height + estimatedHeader;
1100
- const oldSize = sizeCache.getItemSize(idx);
1101
- if (Math.abs(oldSize - fullHeight) < 1)
1102
- return;
1103
- sizeCache.setItemSize(idx, fullHeight);
1104
- scrollCorrection.recordSizeChange(idx, oldSize, fullHeight);
1105
- if (isWeapp && props.useResizeObserver === true) {
1106
- scheduleWeappDynamicReflow();
1107
- }
1108
- else if (sizeCacheRafRef.current == null) {
1109
- sizeCacheRafRef.current = requestAnimationFrame(() => {
1110
- sizeCacheRafRef.current = null;
1111
- setSizeCacheVersion((v) => v + 1);
1112
- });
1113
- }
1114
- }
1115
- : undefined,
1116
- },
1117
- }, itemNode)
1118
- : itemNode;
1119
- nodes.push(itemWithContext);
1120
- }
1121
- else {
1122
- const itemNode = React.createElement(View, outerItemProps, section.items[i]);
1123
- const itemWithContext = scrollRefProp && !useScrollElementMode
1124
- ? React.createElement(ScrollElementContext.Provider, {
1125
- key: outerItemProps.key,
1126
- value: {
1127
- scrollRef: scrollRefProp,
1128
- containerHeight: containerLength,
1129
- startOffset: offset + itemOffsets[i],
1130
- reportNestedHeightChange: props.useResizeObserver
1131
- ? (height) => {
1132
- if (height <= 0)
1133
- return;
1134
- const idx = currentGlobalIndex;
1135
- const estimatedHeader = estimatedSize * 0.5;
1136
- const fullHeight = height + estimatedHeader;
1137
- const oldSize = sizeCache.getItemSize(idx);
1138
- if (Math.abs(oldSize - fullHeight) < 1)
1139
- return;
1140
- sizeCache.setItemSize(idx, fullHeight);
1141
- scrollCorrection.recordSizeChange(idx, oldSize, fullHeight);
1142
- if (isWeapp && props.useResizeObserver === true) {
1143
- scheduleWeappDynamicReflow();
1144
- }
1145
- else if (sizeCacheRafRef.current == null) {
1146
- sizeCacheRafRef.current = requestAnimationFrame(() => {
1147
- sizeCacheRafRef.current = null;
1148
- setSizeCacheVersion((v) => v + 1);
1149
- });
1150
- }
1151
- }
1152
- : undefined,
1153
- },
1154
- }, itemNode)
1155
- : itemNode;
1156
- nodes.push(itemWithContext);
1157
- }
340
+ }, section.items[i]));
1158
341
  }
1159
- globalItemIndex += section.items.length;
1160
342
  offset += itemOffsets[itemOffsets.length - 1];
1161
343
  }
1162
344
  return nodes;
1163
345
  };
1164
- // 渲染 NoMore 内容
1165
- const renderNoMoreContent = () => {
1166
- if (!noMoreConfig || !noMoreConfig.visible)
1167
- return null;
1168
- const noMoreHeightValue = noMoreConfig.height || 60;
1169
- const listContentEnd = sectionOffsets[sectionOffsets.length - 1];
1170
- const defaultStyle = Object.assign(Object.assign(Object.assign({ position: 'absolute' }, (isHorizontal
1171
- ? { left: listContentEnd, top: 0, width: noMoreHeightValue, height: '100%' }
1172
- : { top: listContentEnd, left: 0, width: '100%', height: noMoreHeightValue })), { display: 'flex', alignItems: 'center', justifyContent: 'center', textAlign: 'center', color: '#999', fontSize: '14px', boxSizing: 'border-box' }), noMoreConfig.style);
1173
- return (jsx(View, { style: defaultStyle, children: noMoreConfig.children || noMoreConfig.text || '没有更多了' }));
1174
- };
1175
- // 空列表场景:仅显示 NoMore
1176
- if (sections.length === 0 && (noMoreConfig === null || noMoreConfig === void 0 ? void 0 : noMoreConfig.visible)) {
1177
- return (jsx(ScrollView, Object.assign({ ref: containerRef }, scrollViewProps, { children: jsx(View, { style: Object.assign({ minHeight: containerLength, display: 'flex', alignItems: 'center', justifyContent: 'center' }, containerStyle), children: renderNoMoreContent() }) })));
1178
- }
1179
- // 可滚区域总尺寸
1180
- // H5 refresher 用负 translateY 隐藏,有上方混排时可能延伸到 sibling 区域;overflow:hidden 裁剪避免重叠
1181
- const needsRefresherClip = refresherHeightForH5 > 0;
1182
- const contentWrapperStyle = isHorizontal
1183
- ? Object.assign({ width: totalLength, position: 'relative', height: '100%' }, (needsRefresherClip && { overflow: 'hidden' })) : Object.assign({ height: totalLength, position: 'relative', width: '100%' }, (needsRefresherClip && { overflow: 'hidden' }));
1184
- const listWrapperStyle = isHorizontal
1185
- ? { width: listContentLength, position: 'relative', height: '100%' }
1186
- : { height: listContentLength, position: 'relative', width: '100%' };
1187
- const pullTranslate = refresherHeightForH5 > 0 && h5RefresherProps.pullDistance !== 0
1188
- ? { transform: `translateY(${h5RefresherProps.pullDistance}px)` }
1189
- : {};
1190
- const h5RefresherTranslateY = -refresherHeightForH5 + h5RefresherProps.pullDistance;
1191
- // 内容区域渲染
1192
- const renderContentArea = () => {
1193
- var _a, _b;
1194
- return (jsx(View, { style: contentWrapperStyle, children: refresherHeightForH5 > 0 ? (jsxs(Fragment, { children: [jsx(View, { style: {
1195
- position: 'absolute',
1196
- top: 0,
1197
- left: 0,
1198
- right: 0,
1199
- height: refresherHeightForH5,
1200
- zIndex: 0,
1201
- transform: `translateY(${h5RefresherTranslateY}px)`,
1202
- }, children: renderRefresherContent() }), jsxs(View, { style: Object.assign(Object.assign(Object.assign({}, listWrapperStyle), pullTranslate), { zIndex: 1, background: (_b = (_a = style === null || style === void 0 ? void 0 : style.background) !== null && _a !== void 0 ? _a : style === null || style === void 0 ? void 0 : style.backgroundColor) !== null && _b !== void 0 ? _b : '#fff' }), children: [stickyHeaderNode, renderSections(), renderNoMoreContent()] })] })) : (jsxs(Fragment, { children: [!supportsNativeRefresher && renderRefresherContent(), stickyHeaderNode, renderSections(), renderNoMoreContent()] })) }));
1203
- };
1204
- // useScrollElementMode 或 needAutoFind&&pending:渲染 View 以便监听外部滚动或 probe 阶段查找滚动父节点
1205
- const renderView = useScrollElementMode || (!!needAutoFind && autoFindStatus === 'pending');
1206
- if (renderView) {
1207
- // 任务 2.4:恢复 refresher DOM 结构(refresher 层 + listWrapperStyle)
1208
- return (jsx(View, { ref: contentWrapperRef, style: contentWrapperStyle, children: refresherHeightForH5 > 0 ? (jsxs(Fragment, { children: [jsx(View, { style: {
1209
- position: 'absolute',
1210
- top: 0,
1211
- left: 0,
1212
- right: 0,
1213
- height: refresherHeightForH5,
1214
- zIndex: 0,
1215
- transform: `translateY(${h5RefresherTranslateY}px)`,
1216
- }, children: renderRefresherContent() }), jsxs(View, { style: Object.assign(Object.assign(Object.assign({}, listWrapperStyle), pullTranslate), { zIndex: 1, background: (_c = (_b = style === null || style === void 0 ? void 0 : style.background) !== null && _b !== void 0 ? _b : style === null || style === void 0 ? void 0 : style.backgroundColor) !== null && _c !== void 0 ? _c : '#fff' }), children: [stickyHeaderNode, renderSections(), renderNoMoreContent()] })] })) : (jsxs(Fragment, { children: [stickyHeaderNode, renderSections(), renderNoMoreContent()] })) }));
1217
- }
1218
- return (jsxs(ScrollView, Object.assign({ ref: containerRef }, scrollViewProps, { id: listId, children: [supportsNativeRefresher && renderRefresherContent(), renderContentArea()] })));
346
+ return (jsx(ScrollView, Object.assign({ ref: containerRef }, scrollViewProps, { children: jsxs(View, { style: isHorizontal ? { width: totalLength, position: 'relative', height: '100%' } : { height: totalLength, position: 'relative', width: '100%' }, children: [stickyHeaderNode, renderSections()] }) })));
1219
347
  };
1220
- const List = React.forwardRef(InnerList);
1221
348
 
1222
- export { List, ListItem, NoMore, StickyHeader, StickySection, accumulate, List as default, isShaking };
349
+ export { List, ListItem, StickyHeader, StickySection, accumulate, List as default, isShaking };
1223
350
  //# sourceMappingURL=index.js.map