Line data Source code
1 40405 : export function createRafBatch(run: () => void) {
2 40405 : let rafId: number | null = null
3 :
4 40405 : const schedule = () => {
5 697 : if (rafId != null) return
6 589 : rafId = requestAnimationFrame(() => {
7 525 : rafId = null
8 525 : run()
9 : })
10 : }
11 :
12 40405 : const cancel = () => {
13 578 : if (rafId != null) {
14 63 : cancelAnimationFrame(rafId)
15 63 : rafId = null
16 : }
17 : }
18 :
19 40405 : const flush = () => {
20 65 : if (rafId == null) return
21 0 : cancelAnimationFrame(rafId)
22 0 : rafId = null
23 0 : run()
24 : }
25 :
26 40405 : const isScheduled = () => rafId != null
27 :
28 40405 : return { schedule, cancel, flush, isScheduled }
29 : }
30 :
31 : /**
32 : * Last-write-wins RAF coalescer. Buffers the latest value and applies it
33 : * on the next animation frame, coalescing multiple pushes into a single
34 : * reactive update.
35 : *
36 : * Pass a `label` to emit `performance.mark` events in dev mode so the
37 : * batching benefit is visible in the browser profiler under that name.
38 : */
39 4710 : export function createRafCoalescer<T>(
40 : apply: (value: T) => void,
41 : label?: string
42 : ) {
43 4710 : let hasPending = false
44 4710 : let pendingValue: T | undefined
45 4710 : let droppedCount = 0
46 :
47 4710 : const batch = createRafBatch(() => {
48 92 : if (!hasPending) return
49 92 : const value = pendingValue as T
50 : if (import.meta.env.DEV && label) {
51 : performance.mark(`${label}:apply`, {
52 : detail: { dropped: droppedCount }
53 : })
54 : }
55 92 : droppedCount = 0
56 92 : hasPending = false
57 92 : pendingValue = undefined
58 92 : apply(value)
59 : })
60 :
61 4710 : const push = (value: T) => {
62 264 : if (hasPending) droppedCount++
63 264 : pendingValue = value
64 264 : hasPending = true
65 264 : batch.schedule()
66 : }
67 :
68 4710 : const cancel = () => {
69 447 : droppedCount = 0
70 447 : hasPending = false
71 447 : pendingValue = undefined
72 447 : batch.cancel()
73 : }
74 :
75 4710 : return { push, cancel, isScheduled: batch.isScheduled }
76 : }
|