| 46 | } |
| 47 | |
| 48 | export function createImperativeHandle(ctx: StateContext, scheduleImperativeScrollCommit?: () => void): LegendListRef { |
| 49 | const state = ctx.state; |
| 50 | const IMPERATIVE_SCROLL_SETTLE_MAX_WAIT_MS = 800; |
| 51 | const IMPERATIVE_SCROLL_SETTLE_STABLE_FRAMES = 2; |
| 52 | let imperativeScrollToken = 0; |
| 53 | |
| 54 | const isSettlingAfterDataChange = () => |
| 55 | !!state.didDataChange || |
| 56 | !!state.didColumnsChange || |
| 57 | state.queuedMVCPRecalculate !== undefined || |
| 58 | state.ignoreScrollFromMVCP !== undefined; |
| 59 | |
| 60 | const isScrollToIndexReady = (targetIndex: number, allowEmpty = false) => { |
| 61 | const props = state.props; |
| 62 | const dataLength = props.data.length; |
| 63 | const anchorIndex = props.anchoredEndSpace?.anchorIndex; |
| 64 | |
| 65 | if (targetIndex < 0) { |
| 66 | return allowEmpty; |
| 67 | } |
| 68 | if (targetIndex >= dataLength) { |
| 69 | return false; |
| 70 | } |
| 71 | if (anchorIndex === undefined || anchorIndex < 0 || anchorIndex >= dataLength || targetIndex < anchorIndex) { |
| 72 | return true; |
| 73 | } |
| 74 | |
| 75 | return areKnownOrFixedItemSizesAvailable(ctx, anchorIndex, dataLength - 1); |
| 76 | }; |
| 77 | |
| 78 | const runWhenReady = (token: number, run: () => void, isReady: () => boolean) => { |
| 79 | const startedAt = Date.now(); |
| 80 | let stableFrames = 0; |
| 81 | |
| 82 | const check = () => { |
| 83 | if (token !== imperativeScrollToken) { |
| 84 | return; |
| 85 | } |
| 86 | |
| 87 | if (isSettlingAfterDataChange() || !isReady()) { |
| 88 | stableFrames = 0; |
| 89 | } else { |
| 90 | stableFrames += 1; |
| 91 | } |
| 92 | |
| 93 | const timedOut = Date.now() - startedAt >= IMPERATIVE_SCROLL_SETTLE_MAX_WAIT_MS; |
| 94 | if (stableFrames >= IMPERATIVE_SCROLL_SETTLE_STABLE_FRAMES || timedOut) { |
| 95 | run(); |
| 96 | return; |
| 97 | } |
| 98 | |
| 99 | requestAnimationFrame(check); |
| 100 | }; |
| 101 | |
| 102 | requestAnimationFrame(check); |
| 103 | }; |
| 104 | |
| 105 | const runScrollRequest = (token: number, resolve: () => void, run: () => boolean, isReady = () => true) => { |