@tldraw/utils 5.5.0-canary.fdb2d37fcb2a → 5.5.0-canary.fdd9b4dee0d9

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.
@@ -1,3 +1,5 @@
1
+ import _throttle from 'lodash.throttle'
2
+
1
3
  const isTest = () =>
2
4
  typeof process !== 'undefined' &&
3
5
  process.env.NODE_ENV === 'test' &&
@@ -225,3 +227,47 @@ export function fpsThrottle(fn: { (): void; cancel?(): void }): {
225
227
  export function throttleToNextFrame(fn: () => void): () => void {
226
228
  return defaultScheduler.throttleToNextFrame(fn)
227
229
  }
230
+
231
+ /**
232
+ * The function returned by `throttle`. Call it like the original function; it returns the
233
+ * result of the last invocation, or `undefined` if the original hasn't run yet.
234
+ *
235
+ * Declared here rather than re-exported from `@types/lodash`, so code can name a throttled
236
+ * function's type without depending on lodash's type packages.
237
+ *
238
+ * @example
239
+ * ```ts
240
+ * class Saver {
241
+ * save: ThrottledFunction<() => void> = throttle(() => this.persist(), 1000)
242
+ * }
243
+ * ```
244
+ *
245
+ * @public
246
+ */
247
+ export interface ThrottledFunction<T extends (...args: any[]) => any> {
248
+ (...args: Parameters<T>): ReturnType<T> | undefined
249
+ /** Cancels any pending invocation. */
250
+ cancel(): void
251
+ /** Immediately runs any pending invocation and returns its result. */
252
+ flush(): ReturnType<T> | undefined
253
+ }
254
+
255
+ /**
256
+ * Creates a throttled function that invokes `fn` at most once per `wait` milliseconds. Wraps
257
+ * lodash's `throttle`, typed with {@link ThrottledFunction} so the published types don't depend
258
+ * on lodash's type packages.
259
+ *
260
+ * @example
261
+ * ```ts
262
+ * const save = throttle(() => persist(), 1000, { leading: false })
263
+ * save()
264
+ * save.flush()
265
+ * ```
266
+ *
267
+ * @public
268
+ */
269
+ export const throttle: <T extends (...args: any[]) => any>(
270
+ fn: T,
271
+ wait?: number,
272
+ options?: { leading?: boolean; trailing?: boolean }
273
+ ) => ThrottledFunction<T> = _throttle
@@ -1,4 +1,4 @@
1
- import { describe, expect, it, vi } from 'vitest'
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2
2
  import { Timers } from './timers'
3
3
 
4
4
  describe('Timers', () => {
@@ -38,21 +38,27 @@ describe('Timers', () => {
38
38
  const timers = new Timers()
39
39
  const mockClearTimeout = vi.fn()
40
40
  const mockClearInterval = vi.fn()
41
+ const mockCancelAnimationFrame = vi.fn()
41
42
 
42
43
  vi.stubGlobal('setTimeout', vi.fn().mockReturnValueOnce(1).mockReturnValueOnce(2))
43
44
  vi.stubGlobal('setInterval', vi.fn().mockReturnValue(3))
45
+ vi.stubGlobal('requestAnimationFrame', vi.fn().mockReturnValue(4))
44
46
  vi.stubGlobal('clearTimeout', mockClearTimeout)
45
47
  vi.stubGlobal('clearInterval', mockClearInterval)
48
+ vi.stubGlobal('cancelAnimationFrame', mockCancelAnimationFrame)
46
49
 
47
50
  timers.setTimeout('context1', () => {}, 1000)
48
51
  timers.setTimeout('context2', () => {}, 2000)
49
52
  timers.setInterval('context1', () => {}, 500)
53
+ // A context that only holds an animation frame must be disposed too
54
+ timers.requestAnimationFrame('context3', () => {})
50
55
 
51
56
  timers.disposeAll()
52
57
 
53
58
  expect(mockClearTimeout).toHaveBeenCalledWith(1)
54
59
  expect(mockClearTimeout).toHaveBeenCalledWith(2)
55
60
  expect(mockClearInterval).toHaveBeenCalledWith(3)
61
+ expect(mockCancelAnimationFrame).toHaveBeenCalledWith(4)
56
62
 
57
63
  vi.unstubAllGlobals()
58
64
  })
@@ -72,4 +78,153 @@ describe('Timers', () => {
72
78
 
73
79
  vi.unstubAllGlobals()
74
80
  })
81
+
82
+ describe('pruning tracked ids', () => {
83
+ beforeEach(() => {
84
+ vi.useFakeTimers()
85
+ })
86
+
87
+ afterEach(() => {
88
+ vi.useRealTimers()
89
+ vi.restoreAllMocks()
90
+ })
91
+
92
+ it('stops tracking a timeout once it has fired', () => {
93
+ const timers = new Timers()
94
+ const handler = vi.fn()
95
+
96
+ const fired = timers.setTimeout('ctx', handler, 100)
97
+ const pending = timers.setTimeout('ctx', () => {}, 1000)
98
+ vi.advanceTimersByTime(100)
99
+ expect(handler).toHaveBeenCalledTimes(1)
100
+
101
+ const clearTimeoutSpy = vi.spyOn(window, 'clearTimeout')
102
+ timers.dispose('ctx')
103
+
104
+ expect(clearTimeoutSpy.mock.calls).toEqual([[pending]])
105
+ expect(clearTimeoutSpy).not.toHaveBeenCalledWith(fired)
106
+ })
107
+
108
+ it('stops tracking an animation frame once it has run', () => {
109
+ const timers = new Timers()
110
+ const callback = vi.fn()
111
+
112
+ const ran = timers.requestAnimationFrame('ctx', callback)
113
+ vi.advanceTimersToNextFrame()
114
+ expect(callback).toHaveBeenCalledTimes(1)
115
+ expect(callback.mock.calls[0][0]).toEqual(expect.any(Number))
116
+
117
+ const pending = timers.requestAnimationFrame('ctx', () => {})
118
+ const cancelSpy = vi.spyOn(window, 'cancelAnimationFrame')
119
+ timers.dispose('ctx')
120
+
121
+ expect(cancelSpy.mock.calls).toEqual([[pending]])
122
+ expect(cancelSpy).not.toHaveBeenCalledWith(ran)
123
+ })
124
+
125
+ // The sync fuzz suite stubs requestAnimationFrame to run its callback synchronously, so the
126
+ // wrapper runs before the id it would prune has been assigned.
127
+ it('survives a timer that fires before its id is returned', () => {
128
+ const timers = new Timers()
129
+ vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => {
130
+ cb(0)
131
+ return 7
132
+ })
133
+ vi.stubGlobal('setTimeout', (handler: () => void) => {
134
+ handler()
135
+ return 8
136
+ })
137
+ const frameCallback = vi.fn()
138
+ const timeoutHandler = vi.fn()
139
+
140
+ expect(timers.requestAnimationFrame('ctx', frameCallback)).toBe(7)
141
+ expect(timers.setTimeout('ctx', timeoutHandler, 0)).toBe(8)
142
+ expect(frameCallback).toHaveBeenCalledTimes(1)
143
+ expect(timeoutHandler).toHaveBeenCalledTimes(1)
144
+
145
+ const cancelSpy = vi.fn()
146
+ const clearSpy = vi.fn()
147
+ vi.stubGlobal('cancelAnimationFrame', cancelSpy)
148
+ vi.stubGlobal('clearTimeout', clearSpy)
149
+ timers.dispose('ctx')
150
+ expect(cancelSpy).not.toHaveBeenCalled()
151
+ expect(clearSpy).not.toHaveBeenCalled()
152
+ vi.unstubAllGlobals()
153
+ })
154
+
155
+ it('stops tracking timers cleared through the instance', () => {
156
+ const timers = new Timers()
157
+ const timeoutHandler = vi.fn()
158
+ const intervalHandler = vi.fn()
159
+ const frameCallback = vi.fn()
160
+
161
+ const timeout = timers.setTimeout('ctx', timeoutHandler, 100)
162
+ const interval = timers.setInterval('ctx', intervalHandler, 100)
163
+ const frame = timers.requestAnimationFrame('ctx', frameCallback)
164
+
165
+ timers.clearTimeout('ctx', timeout)
166
+ timers.clearInterval('ctx', interval)
167
+ timers.cancelAnimationFrame('ctx', frame)
168
+
169
+ vi.advanceTimersByTime(1000)
170
+ expect(timeoutHandler).not.toHaveBeenCalled()
171
+ expect(intervalHandler).not.toHaveBeenCalled()
172
+ expect(frameCallback).not.toHaveBeenCalled()
173
+
174
+ const clearTimeoutSpy = vi.spyOn(window, 'clearTimeout')
175
+ const clearIntervalSpy = vi.spyOn(window, 'clearInterval')
176
+ const cancelSpy = vi.spyOn(window, 'cancelAnimationFrame')
177
+ timers.dispose('ctx')
178
+
179
+ expect(clearTimeoutSpy).not.toHaveBeenCalled()
180
+ expect(clearIntervalSpy).not.toHaveBeenCalled()
181
+ expect(cancelSpy).not.toHaveBeenCalled()
182
+ })
183
+
184
+ it('ignores undefined ids when clearing', () => {
185
+ const timers = new Timers()
186
+ const clearTimeoutSpy = vi.spyOn(window, 'clearTimeout')
187
+
188
+ timers.clearTimeout('ctx', undefined)
189
+ timers.clearInterval('ctx', undefined)
190
+ timers.cancelAnimationFrame('ctx', undefined)
191
+
192
+ expect(clearTimeoutSpy).not.toHaveBeenCalled()
193
+ })
194
+
195
+ it('keeps tracking an interval until it is cleared or disposed', () => {
196
+ const timers = new Timers()
197
+ const handler = vi.fn()
198
+
199
+ const interval = timers.setInterval('ctx', handler, 100)
200
+ vi.advanceTimersByTime(350)
201
+ expect(handler).toHaveBeenCalledTimes(3)
202
+
203
+ const clearIntervalSpy = vi.spyOn(window, 'clearInterval')
204
+ timers.dispose('ctx')
205
+
206
+ expect(clearIntervalSpy.mock.calls).toEqual([[interval]])
207
+ vi.advanceTimersByTime(1000)
208
+ expect(handler).toHaveBeenCalledTimes(3)
209
+ })
210
+
211
+ it('does not grow the tracked set as timeouts fire and are cleared', () => {
212
+ const timers = new Timers()
213
+ const context = timers.forContext('ctx')
214
+
215
+ for (let i = 0; i < 100; i++) {
216
+ // Mirrors a pointer down and up: a long-press timeout that is cleared before it fires,
217
+ // and a click timeout that is left to fire on its own.
218
+ const longPress = context.setTimeout(() => {}, 500)
219
+ context.setTimeout(() => {}, 200)
220
+ context.clearTimeout(longPress)
221
+ vi.advanceTimersByTime(300)
222
+ }
223
+
224
+ const clearTimeoutSpy = vi.spyOn(window, 'clearTimeout')
225
+ context.dispose()
226
+
227
+ expect(clearTimeoutSpy).not.toHaveBeenCalled()
228
+ })
229
+ })
75
230
  })
package/src/lib/timers.ts CHANGED
@@ -22,9 +22,12 @@
22
22
  * @public
23
23
  */
24
24
  export class Timers {
25
- private timeouts = new Map<string, number[]>()
26
- private intervals = new Map<string, number[]>()
27
- private rafs = new Map<string, number[]>()
25
+ // Ids are dropped as soon as a timer fires or is cleared through this class, so a
26
+ // long-lived context (the editor creates two timeouts per pointer down) does not
27
+ // accumulate stale ids that `dispose` would otherwise have to clear one by one.
28
+ private timeouts = new Map<string, Set<number>>()
29
+ private intervals = new Map<string, Set<number>>()
30
+ private rafs = new Map<string, Set<number>>()
28
31
 
29
32
  /**
30
33
  * Creates a new Timers instance with bound methods for safe callback usage.
@@ -39,6 +42,9 @@ export class Timers {
39
42
  this.setTimeout = this.setTimeout.bind(this)
40
43
  this.setInterval = this.setInterval.bind(this)
41
44
  this.requestAnimationFrame = this.requestAnimationFrame.bind(this)
45
+ this.clearTimeout = this.clearTimeout.bind(this)
46
+ this.clearInterval = this.clearInterval.bind(this)
47
+ this.cancelAnimationFrame = this.cancelAnimationFrame.bind(this)
42
48
  this.dispose = this.dispose.bind(this)
43
49
  }
44
50
 
@@ -58,9 +64,23 @@ export class Timers {
58
64
  * @public
59
65
  */
60
66
  setTimeout(contextId: string, handler: TimerHandler, timeout?: number, ...args: any[]): number {
61
- const id = window.setTimeout(handler, timeout, args)
62
- const current = this.timeouts.get(contextId) ?? []
63
- this.timeouts.set(contextId, [...current, id])
67
+ const ids = getOrCreateSet(this.timeouts, contextId)
68
+ // A test stub can run the handler synchronously, before `id` is assigned, so the wrapper
69
+ // records that it fired instead of relying on the id being set when it runs.
70
+ let fired = false
71
+ let id = -1
72
+ // A string handler is evaluated by the browser, so it cannot be wrapped and stays
73
+ // tracked until it is cleared or the context is disposed.
74
+ const wrapped =
75
+ typeof handler === 'function'
76
+ ? (...handlerArgs: any[]) => {
77
+ fired = true
78
+ ids.delete(id)
79
+ handler(...handlerArgs)
80
+ }
81
+ : handler
82
+ id = window.setTimeout(wrapped, timeout, args)
83
+ if (!fired) ids.add(id)
64
84
  return id
65
85
  }
66
86
 
@@ -81,8 +101,7 @@ export class Timers {
81
101
  */
82
102
  setInterval(contextId: string, handler: TimerHandler, timeout?: number, ...args: any[]): number {
83
103
  const id = window.setInterval(handler, timeout, args)
84
- const current = this.intervals.get(contextId) ?? []
85
- this.intervals.set(contextId, [...current, id])
104
+ getOrCreateSet(this.intervals, contextId).add(id)
86
105
  return id
87
106
  }
88
107
 
@@ -100,12 +119,76 @@ export class Timers {
100
119
  * @public
101
120
  */
102
121
  requestAnimationFrame(contextId: string, callback: FrameRequestCallback): number {
103
- const id = window.requestAnimationFrame(callback)
104
- const current = this.rafs.get(contextId) ?? []
105
- this.rafs.set(contextId, [...current, id])
122
+ const ids = getOrCreateSet(this.rafs, contextId)
123
+ // Test stubs (the sync fuzz suite, for one) run the frame synchronously, before `id` is
124
+ // assigned, so the callback records that it fired rather than touching `id` first.
125
+ let fired = false
126
+ let id = -1
127
+ id = window.requestAnimationFrame((time) => {
128
+ fired = true
129
+ ids.delete(id)
130
+ callback(time)
131
+ })
132
+ if (!fired) ids.add(id)
106
133
  return id
107
134
  }
108
135
 
136
+ /**
137
+ * Clears a timeout created with {@link Timers.setTimeout} and stops tracking it.
138
+ * Prefer this over the global `clearTimeout` for ids that came from this instance,
139
+ * otherwise the id stays tracked until its context is disposed.
140
+ * @param contextId - The context identifier the timeout was created under.
141
+ * @param id - The timer ID returned by `setTimeout`. Ignored when undefined.
142
+ * @example
143
+ * ```ts
144
+ * const timers = new Timers()
145
+ * const id = timers.setTimeout('autosave', () => save(), 5000)
146
+ * timers.clearTimeout('autosave', id)
147
+ * ```
148
+ * @public
149
+ */
150
+ clearTimeout(contextId: string, id: number | undefined): void {
151
+ if (id === undefined) return
152
+ clearTimeout(id)
153
+ this.timeouts.get(contextId)?.delete(id)
154
+ }
155
+
156
+ /**
157
+ * Clears an interval created with {@link Timers.setInterval} and stops tracking it.
158
+ * @param contextId - The context identifier the interval was created under.
159
+ * @param id - The interval ID returned by `setInterval`. Ignored when undefined.
160
+ * @example
161
+ * ```ts
162
+ * const timers = new Timers()
163
+ * const id = timers.setInterval('refresh', () => updateData(), 1000)
164
+ * timers.clearInterval('refresh', id)
165
+ * ```
166
+ * @public
167
+ */
168
+ clearInterval(contextId: string, id: number | undefined): void {
169
+ if (id === undefined) return
170
+ clearInterval(id)
171
+ this.intervals.get(contextId)?.delete(id)
172
+ }
173
+
174
+ /**
175
+ * Cancels an animation frame requested with {@link Timers.requestAnimationFrame} and stops tracking it.
176
+ * @param contextId - The context identifier the animation frame was requested under.
177
+ * @param id - The request ID returned by `requestAnimationFrame`. Ignored when undefined.
178
+ * @example
179
+ * ```ts
180
+ * const timers = new Timers()
181
+ * const id = timers.requestAnimationFrame('render', () => draw())
182
+ * timers.cancelAnimationFrame('render', id)
183
+ * ```
184
+ * @public
185
+ */
186
+ cancelAnimationFrame(contextId: string, id: number | undefined): void {
187
+ if (id === undefined) return
188
+ cancelAnimationFrame(id)
189
+ this.rafs.get(contextId)?.delete(id)
190
+ }
191
+
109
192
  /**
110
193
  * Disposes of all timers associated with the specified context.
111
194
  * Clears all timeouts, intervals, and animation frames for the given context ID.
@@ -148,7 +231,12 @@ export class Timers {
148
231
  * @public
149
232
  */
150
233
  disposeAll() {
151
- for (const contextId of this.timeouts.keys()) {
234
+ const contextIds = new Set([
235
+ ...this.timeouts.keys(),
236
+ ...this.intervals.keys(),
237
+ ...this.rafs.keys(),
238
+ ])
239
+ for (const contextId of contextIds) {
152
240
  this.dispose(contextId)
153
241
  }
154
242
  }
@@ -157,17 +245,20 @@ export class Timers {
157
245
  * Returns an object with timer methods bound to a specific context.
158
246
  * Convenient for getting context-specific timer functions without repeatedly passing the contextId.
159
247
  * @param contextId - The context identifier to bind the returned methods to.
160
- * @returns An object with setTimeout, setInterval, requestAnimationFrame, and dispose methods bound to the context.
248
+ * @returns An object with setTimeout, setInterval, requestAnimationFrame, the matching clear methods, and dispose bound to the context.
161
249
  * @example
162
250
  * ```ts
163
251
  * const timers = new Timers()
164
252
  * const uiTimers = timers.forContext('ui')
165
253
  *
166
254
  * // These are equivalent to calling timers.setTimeout('ui', ...)
167
- * uiTimers.setTimeout(() => console.log('timeout'), 1000)
255
+ * const id = uiTimers.setTimeout(() => console.log('timeout'), 1000)
168
256
  * uiTimers.setInterval(() => console.log('interval'), 500)
169
257
  * uiTimers.requestAnimationFrame(() => console.log('frame'))
170
258
  *
259
+ * // Clear a single timer
260
+ * uiTimers.clearTimeout(id)
261
+ *
171
262
  * // Dispose only this context
172
263
  * uiTimers.dispose()
173
264
  * ```
@@ -181,7 +272,19 @@ export class Timers {
181
272
  this.setInterval(contextId, handler, timeout, args),
182
273
  requestAnimationFrame: (callback: FrameRequestCallback) =>
183
274
  this.requestAnimationFrame(contextId, callback),
275
+ clearTimeout: (id: number | undefined) => this.clearTimeout(contextId, id),
276
+ clearInterval: (id: number | undefined) => this.clearInterval(contextId, id),
277
+ cancelAnimationFrame: (id: number | undefined) => this.cancelAnimationFrame(contextId, id),
184
278
  dispose: () => this.dispose(contextId),
185
279
  }
186
280
  }
187
281
  }
282
+
283
+ function getOrCreateSet(map: Map<string, Set<number>>, contextId: string): Set<number> {
284
+ let set = map.get(contextId)
285
+ if (!set) {
286
+ set = new Set()
287
+ map.set(contextId, set)
288
+ }
289
+ return set
290
+ }