@tldraw/utils 5.5.0-next.4d6473b0bda1 → 5.5.0-next.68ff40bd4640

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.
@@ -931,6 +931,7 @@ export declare class LruCache<K, V> {
931
931
  get(key: K): undefined | V;
932
932
  set(key: K, value: V): void;
933
933
  has(key: K): boolean;
934
+ delete(key: K): boolean;
934
935
  get size(): number;
935
936
  }
936
937
 
@@ -1875,6 +1876,47 @@ export declare class Timers {
1875
1876
  * @public
1876
1877
  */
1877
1878
  requestAnimationFrame(contextId: string, callback: FrameRequestCallback): number;
1879
+ /**
1880
+ * Clears a timeout created with {@link Timers.setTimeout} and stops tracking it.
1881
+ * Prefer this over the global `clearTimeout` for ids that came from this instance,
1882
+ * otherwise the id stays tracked until its context is disposed.
1883
+ * @param contextId - The context identifier the timeout was created under.
1884
+ * @param id - The timer ID returned by `setTimeout`. Ignored when undefined.
1885
+ * @example
1886
+ * ```ts
1887
+ * const timers = new Timers()
1888
+ * const id = timers.setTimeout('autosave', () => save(), 5000)
1889
+ * timers.clearTimeout('autosave', id)
1890
+ * ```
1891
+ * @public
1892
+ */
1893
+ clearTimeout(contextId: string, id: number | undefined): void;
1894
+ /**
1895
+ * Clears an interval created with {@link Timers.setInterval} and stops tracking it.
1896
+ * @param contextId - The context identifier the interval was created under.
1897
+ * @param id - The interval ID returned by `setInterval`. Ignored when undefined.
1898
+ * @example
1899
+ * ```ts
1900
+ * const timers = new Timers()
1901
+ * const id = timers.setInterval('refresh', () => updateData(), 1000)
1902
+ * timers.clearInterval('refresh', id)
1903
+ * ```
1904
+ * @public
1905
+ */
1906
+ clearInterval(contextId: string, id: number | undefined): void;
1907
+ /**
1908
+ * Cancels an animation frame requested with {@link Timers.requestAnimationFrame} and stops tracking it.
1909
+ * @param contextId - The context identifier the animation frame was requested under.
1910
+ * @param id - The request ID returned by `requestAnimationFrame`. Ignored when undefined.
1911
+ * @example
1912
+ * ```ts
1913
+ * const timers = new Timers()
1914
+ * const id = timers.requestAnimationFrame('render', () => draw())
1915
+ * timers.cancelAnimationFrame('render', id)
1916
+ * ```
1917
+ * @public
1918
+ */
1919
+ cancelAnimationFrame(contextId: string, id: number | undefined): void;
1878
1920
  /**
1879
1921
  * Disposes of all timers associated with the specified context.
1880
1922
  * Clears all timeouts, intervals, and animation frames for the given context ID.
@@ -1912,23 +1954,29 @@ export declare class Timers {
1912
1954
  * Returns an object with timer methods bound to a specific context.
1913
1955
  * Convenient for getting context-specific timer functions without repeatedly passing the contextId.
1914
1956
  * @param contextId - The context identifier to bind the returned methods to.
1915
- * @returns An object with setTimeout, setInterval, requestAnimationFrame, and dispose methods bound to the context.
1957
+ * @returns An object with setTimeout, setInterval, requestAnimationFrame, the matching clear methods, and dispose bound to the context.
1916
1958
  * @example
1917
1959
  * ```ts
1918
1960
  * const timers = new Timers()
1919
1961
  * const uiTimers = timers.forContext('ui')
1920
1962
  *
1921
1963
  * // These are equivalent to calling timers.setTimeout('ui', ...)
1922
- * uiTimers.setTimeout(() => console.log('timeout'), 1000)
1964
+ * const id = uiTimers.setTimeout(() => console.log('timeout'), 1000)
1923
1965
  * uiTimers.setInterval(() => console.log('interval'), 500)
1924
1966
  * uiTimers.requestAnimationFrame(() => console.log('frame'))
1925
1967
  *
1968
+ * // Clear a single timer
1969
+ * uiTimers.clearTimeout(id)
1970
+ *
1926
1971
  * // Dispose only this context
1927
1972
  * uiTimers.dispose()
1928
1973
  * ```
1929
1974
  * @public
1930
1975
  */
1931
1976
  forContext(contextId: string): {
1977
+ cancelAnimationFrame: (id: number | undefined) => void;
1978
+ clearInterval: (id: number | undefined) => void;
1979
+ clearTimeout: (id: number | undefined) => void;
1932
1980
  dispose: () => void;
1933
1981
  requestAnimationFrame: (callback: FrameRequestCallback) => number;
1934
1982
  setInterval: (handler: TimerHandler, timeout?: number, ...args: any[]) => number;
package/dist-cjs/index.js CHANGED
@@ -174,7 +174,7 @@ var import_version2 = require("./lib/version");
174
174
  var import_warn = require("./lib/warn");
175
175
  (0, import_version.registerTldrawLibraryVersion)(
176
176
  "@tldraw/utils",
177
- "5.5.0-next.4d6473b0bda1",
177
+ "5.5.0-next.68ff40bd4640",
178
178
  "cjs"
179
179
  );
180
180
  //# sourceMappingURL=index.js.map
@@ -44,6 +44,9 @@ class LruCache {
44
44
  has(key) {
45
45
  return this.map.has(key);
46
46
  }
47
+ delete(key) {
48
+ return this.map.delete(key);
49
+ }
47
50
  // eslint-disable-next-line tldraw/no-setter-getter
48
51
  get size() {
49
52
  return this.map.size;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/lib/LruCache.ts"],
4
- "sourcesContent": ["/** Simple LRU cache backed by a Map's insertion-order iteration. @public */\nexport class LruCache<K, V> {\n\tprivate map = new Map<K, V>()\n\tconstructor(private maxSize: number) {}\n\n\tget(key: K): V | undefined {\n\t\tif (!this.map.has(key)) return undefined\n\t\tconst value = this.map.get(key)!\n\t\t// Move to most-recent position\n\t\tthis.map.delete(key)\n\t\tthis.map.set(key, value)\n\t\treturn value\n\t}\n\n\tset(key: K, value: V): void {\n\t\tif (this.map.has(key)) this.map.delete(key)\n\t\tthis.map.set(key, value)\n\t\tif (this.map.size > this.maxSize) {\n\t\t\t// Evict oldest entry\n\t\t\tthis.map.delete(this.map.keys().next().value!)\n\t\t}\n\t}\n\n\thas(key: K): boolean {\n\t\treturn this.map.has(key)\n\t}\n\n\t// eslint-disable-next-line tldraw/no-setter-getter\n\tget size(): number {\n\t\treturn this.map.size\n\t}\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACO,MAAM,SAAe;AAAA,EAE3B,YAAoB,SAAiB;AAAjB;AAAA,EAAkB;AAAA,EAAlB;AAAA,EADZ,MAAM,oBAAI,IAAU;AAAA,EAG5B,IAAI,KAAuB;AAC1B,QAAI,CAAC,KAAK,IAAI,IAAI,GAAG,EAAG,QAAO;AAC/B,UAAM,QAAQ,KAAK,IAAI,IAAI,GAAG;AAE9B,SAAK,IAAI,OAAO,GAAG;AACnB,SAAK,IAAI,IAAI,KAAK,KAAK;AACvB,WAAO;AAAA,EACR;AAAA,EAEA,IAAI,KAAQ,OAAgB;AAC3B,QAAI,KAAK,IAAI,IAAI,GAAG,EAAG,MAAK,IAAI,OAAO,GAAG;AAC1C,SAAK,IAAI,IAAI,KAAK,KAAK;AACvB,QAAI,KAAK,IAAI,OAAO,KAAK,SAAS;AAEjC,WAAK,IAAI,OAAO,KAAK,IAAI,KAAK,EAAE,KAAK,EAAE,KAAM;AAAA,IAC9C;AAAA,EACD;AAAA,EAEA,IAAI,KAAiB;AACpB,WAAO,KAAK,IAAI,IAAI,GAAG;AAAA,EACxB;AAAA;AAAA,EAGA,IAAI,OAAe;AAClB,WAAO,KAAK,IAAI;AAAA,EACjB;AACD;",
4
+ "sourcesContent": ["/** Simple LRU cache backed by a Map's insertion-order iteration. @public */\nexport class LruCache<K, V> {\n\tprivate map = new Map<K, V>()\n\tconstructor(private maxSize: number) {}\n\n\tget(key: K): V | undefined {\n\t\tif (!this.map.has(key)) return undefined\n\t\tconst value = this.map.get(key)!\n\t\t// Move to most-recent position\n\t\tthis.map.delete(key)\n\t\tthis.map.set(key, value)\n\t\treturn value\n\t}\n\n\tset(key: K, value: V): void {\n\t\tif (this.map.has(key)) this.map.delete(key)\n\t\tthis.map.set(key, value)\n\t\tif (this.map.size > this.maxSize) {\n\t\t\t// Evict oldest entry\n\t\t\tthis.map.delete(this.map.keys().next().value!)\n\t\t}\n\t}\n\n\thas(key: K): boolean {\n\t\treturn this.map.has(key)\n\t}\n\n\tdelete(key: K): boolean {\n\t\treturn this.map.delete(key)\n\t}\n\n\t// eslint-disable-next-line tldraw/no-setter-getter\n\tget size(): number {\n\t\treturn this.map.size\n\t}\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACO,MAAM,SAAe;AAAA,EAE3B,YAAoB,SAAiB;AAAjB;AAAA,EAAkB;AAAA,EAAlB;AAAA,EADZ,MAAM,oBAAI,IAAU;AAAA,EAG5B,IAAI,KAAuB;AAC1B,QAAI,CAAC,KAAK,IAAI,IAAI,GAAG,EAAG,QAAO;AAC/B,UAAM,QAAQ,KAAK,IAAI,IAAI,GAAG;AAE9B,SAAK,IAAI,OAAO,GAAG;AACnB,SAAK,IAAI,IAAI,KAAK,KAAK;AACvB,WAAO;AAAA,EACR;AAAA,EAEA,IAAI,KAAQ,OAAgB;AAC3B,QAAI,KAAK,IAAI,IAAI,GAAG,EAAG,MAAK,IAAI,OAAO,GAAG;AAC1C,SAAK,IAAI,IAAI,KAAK,KAAK;AACvB,QAAI,KAAK,IAAI,OAAO,KAAK,SAAS;AAEjC,WAAK,IAAI,OAAO,KAAK,IAAI,KAAK,EAAE,KAAK,EAAE,KAAM;AAAA,IAC9C;AAAA,EACD;AAAA,EAEA,IAAI,KAAiB;AACpB,WAAO,KAAK,IAAI,IAAI,GAAG;AAAA,EACxB;AAAA,EAEA,OAAO,KAAiB;AACvB,WAAO,KAAK,IAAI,OAAO,GAAG;AAAA,EAC3B;AAAA;AAAA,EAGA,IAAI,OAAe;AAClB,WAAO,KAAK,IAAI;AAAA,EACjB;AACD;",
6
6
  "names": []
7
7
  }
@@ -22,6 +22,9 @@ __export(timers_exports, {
22
22
  });
23
23
  module.exports = __toCommonJS(timers_exports);
24
24
  class Timers {
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.
25
28
  timeouts = /* @__PURE__ */ new Map();
26
29
  intervals = /* @__PURE__ */ new Map();
27
30
  rafs = /* @__PURE__ */ new Map();
@@ -38,6 +41,9 @@ class Timers {
38
41
  this.setTimeout = this.setTimeout.bind(this);
39
42
  this.setInterval = this.setInterval.bind(this);
40
43
  this.requestAnimationFrame = this.requestAnimationFrame.bind(this);
44
+ this.clearTimeout = this.clearTimeout.bind(this);
45
+ this.clearInterval = this.clearInterval.bind(this);
46
+ this.cancelAnimationFrame = this.cancelAnimationFrame.bind(this);
41
47
  this.dispose = this.dispose.bind(this);
42
48
  }
43
49
  /**
@@ -56,9 +62,16 @@ class Timers {
56
62
  * @public
57
63
  */
58
64
  setTimeout(contextId, handler, timeout, ...args) {
59
- const id = window.setTimeout(handler, timeout, args);
60
- const current = this.timeouts.get(contextId) ?? [];
61
- this.timeouts.set(contextId, [...current, id]);
65
+ const ids = getOrCreateSet(this.timeouts, contextId);
66
+ let fired = false;
67
+ let id = -1;
68
+ const wrapped = typeof handler === "function" ? (...handlerArgs) => {
69
+ fired = true;
70
+ ids.delete(id);
71
+ handler(...handlerArgs);
72
+ } : handler;
73
+ id = window.setTimeout(wrapped, timeout, args);
74
+ if (!fired) ids.add(id);
62
75
  return id;
63
76
  }
64
77
  /**
@@ -78,8 +91,7 @@ class Timers {
78
91
  */
79
92
  setInterval(contextId, handler, timeout, ...args) {
80
93
  const id = window.setInterval(handler, timeout, args);
81
- const current = this.intervals.get(contextId) ?? [];
82
- this.intervals.set(contextId, [...current, id]);
94
+ getOrCreateSet(this.intervals, contextId).add(id);
83
95
  return id;
84
96
  }
85
97
  /**
@@ -96,11 +108,70 @@ class Timers {
96
108
  * @public
97
109
  */
98
110
  requestAnimationFrame(contextId, callback) {
99
- const id = window.requestAnimationFrame(callback);
100
- const current = this.rafs.get(contextId) ?? [];
101
- this.rafs.set(contextId, [...current, id]);
111
+ const ids = getOrCreateSet(this.rafs, contextId);
112
+ let fired = false;
113
+ let id = -1;
114
+ id = window.requestAnimationFrame((time) => {
115
+ fired = true;
116
+ ids.delete(id);
117
+ callback(time);
118
+ });
119
+ if (!fired) ids.add(id);
102
120
  return id;
103
121
  }
122
+ /**
123
+ * Clears a timeout created with {@link Timers.setTimeout} and stops tracking it.
124
+ * Prefer this over the global `clearTimeout` for ids that came from this instance,
125
+ * otherwise the id stays tracked until its context is disposed.
126
+ * @param contextId - The context identifier the timeout was created under.
127
+ * @param id - The timer ID returned by `setTimeout`. Ignored when undefined.
128
+ * @example
129
+ * ```ts
130
+ * const timers = new Timers()
131
+ * const id = timers.setTimeout('autosave', () => save(), 5000)
132
+ * timers.clearTimeout('autosave', id)
133
+ * ```
134
+ * @public
135
+ */
136
+ clearTimeout(contextId, id) {
137
+ if (id === void 0) return;
138
+ clearTimeout(id);
139
+ this.timeouts.get(contextId)?.delete(id);
140
+ }
141
+ /**
142
+ * Clears an interval created with {@link Timers.setInterval} and stops tracking it.
143
+ * @param contextId - The context identifier the interval was created under.
144
+ * @param id - The interval ID returned by `setInterval`. Ignored when undefined.
145
+ * @example
146
+ * ```ts
147
+ * const timers = new Timers()
148
+ * const id = timers.setInterval('refresh', () => updateData(), 1000)
149
+ * timers.clearInterval('refresh', id)
150
+ * ```
151
+ * @public
152
+ */
153
+ clearInterval(contextId, id) {
154
+ if (id === void 0) return;
155
+ clearInterval(id);
156
+ this.intervals.get(contextId)?.delete(id);
157
+ }
158
+ /**
159
+ * Cancels an animation frame requested with {@link Timers.requestAnimationFrame} and stops tracking it.
160
+ * @param contextId - The context identifier the animation frame was requested under.
161
+ * @param id - The request ID returned by `requestAnimationFrame`. Ignored when undefined.
162
+ * @example
163
+ * ```ts
164
+ * const timers = new Timers()
165
+ * const id = timers.requestAnimationFrame('render', () => draw())
166
+ * timers.cancelAnimationFrame('render', id)
167
+ * ```
168
+ * @public
169
+ */
170
+ cancelAnimationFrame(contextId, id) {
171
+ if (id === void 0) return;
172
+ cancelAnimationFrame(id);
173
+ this.rafs.get(contextId)?.delete(id);
174
+ }
104
175
  /**
105
176
  * Disposes of all timers associated with the specified context.
106
177
  * Clears all timeouts, intervals, and animation frames for the given context ID.
@@ -141,7 +212,12 @@ class Timers {
141
212
  * @public
142
213
  */
143
214
  disposeAll() {
144
- for (const contextId of this.timeouts.keys()) {
215
+ const contextIds = /* @__PURE__ */ new Set([
216
+ ...this.timeouts.keys(),
217
+ ...this.intervals.keys(),
218
+ ...this.rafs.keys()
219
+ ]);
220
+ for (const contextId of contextIds) {
145
221
  this.dispose(contextId);
146
222
  }
147
223
  }
@@ -149,17 +225,20 @@ class Timers {
149
225
  * Returns an object with timer methods bound to a specific context.
150
226
  * Convenient for getting context-specific timer functions without repeatedly passing the contextId.
151
227
  * @param contextId - The context identifier to bind the returned methods to.
152
- * @returns An object with setTimeout, setInterval, requestAnimationFrame, and dispose methods bound to the context.
228
+ * @returns An object with setTimeout, setInterval, requestAnimationFrame, the matching clear methods, and dispose bound to the context.
153
229
  * @example
154
230
  * ```ts
155
231
  * const timers = new Timers()
156
232
  * const uiTimers = timers.forContext('ui')
157
233
  *
158
234
  * // These are equivalent to calling timers.setTimeout('ui', ...)
159
- * uiTimers.setTimeout(() => console.log('timeout'), 1000)
235
+ * const id = uiTimers.setTimeout(() => console.log('timeout'), 1000)
160
236
  * uiTimers.setInterval(() => console.log('interval'), 500)
161
237
  * uiTimers.requestAnimationFrame(() => console.log('frame'))
162
238
  *
239
+ * // Clear a single timer
240
+ * uiTimers.clearTimeout(id)
241
+ *
163
242
  * // Dispose only this context
164
243
  * uiTimers.dispose()
165
244
  * ```
@@ -170,8 +249,19 @@ class Timers {
170
249
  setTimeout: (handler, timeout, ...args) => this.setTimeout(contextId, handler, timeout, args),
171
250
  setInterval: (handler, timeout, ...args) => this.setInterval(contextId, handler, timeout, args),
172
251
  requestAnimationFrame: (callback) => this.requestAnimationFrame(contextId, callback),
252
+ clearTimeout: (id) => this.clearTimeout(contextId, id),
253
+ clearInterval: (id) => this.clearInterval(contextId, id),
254
+ cancelAnimationFrame: (id) => this.cancelAnimationFrame(contextId, id),
173
255
  dispose: () => this.dispose(contextId)
174
256
  };
175
257
  }
176
258
  }
259
+ function getOrCreateSet(map, contextId) {
260
+ let set = map.get(contextId);
261
+ if (!set) {
262
+ set = /* @__PURE__ */ new Set();
263
+ map.set(contextId, set);
264
+ }
265
+ return set;
266
+ }
177
267
  //# sourceMappingURL=timers.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/lib/timers.ts"],
4
- "sourcesContent": ["/* eslint-disable tldraw/no-restricted-properties */\n\n/**\n * A utility class for managing timeouts, intervals, and animation frames with context-based organization and automatic cleanup.\n * Helps prevent memory leaks by organizing timers into named contexts that can be cleared together.\n * @example\n * ```ts\n * const timers = new Timers()\n *\n * // Set timers with context organization\n * timers.setTimeout('ui', () => console.log('Auto save'), 5000)\n * timers.setInterval('ui', () => console.log('Refresh'), 1000)\n * timers.requestAnimationFrame('ui', () => console.log('Render'))\n *\n * // Clear all timers for a context\n * timers.dispose('ui')\n *\n * // Or get context-bound functions\n * const uiTimers = timers.forContext('ui')\n * uiTimers.setTimeout(() => console.log('Contextual timeout'), 1000)\n * ```\n * @public\n */\nexport class Timers {\n\tprivate timeouts = new Map<string, number[]>()\n\tprivate intervals = new Map<string, number[]>()\n\tprivate rafs = new Map<string, number[]>()\n\n\t/**\n\t * Creates a new Timers instance with bound methods for safe callback usage.\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * // Methods are pre-bound, safe to use as callbacks\n\t * element.addEventListener('click', timers.dispose)\n\t * ```\n\t */\n\tconstructor() {\n\t\tthis.setTimeout = this.setTimeout.bind(this)\n\t\tthis.setInterval = this.setInterval.bind(this)\n\t\tthis.requestAnimationFrame = this.requestAnimationFrame.bind(this)\n\t\tthis.dispose = this.dispose.bind(this)\n\t}\n\n\t/**\n\t * Creates a timeout that will be tracked under the specified context.\n\t * @param contextId - The context identifier to group this timer under.\n\t * @param handler - The function to execute when the timeout expires.\n\t * @param timeout - The delay in milliseconds (default: 0).\n\t * @param args - Additional arguments to pass to the handler.\n\t * @returns The timer ID that can be used with clearTimeout.\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * const id = timers.setTimeout('autosave', () => save(), 5000)\n\t * // Timer will be automatically cleared when 'autosave' context is disposed\n\t * ```\n\t * @public\n\t */\n\tsetTimeout(contextId: string, handler: TimerHandler, timeout?: number, ...args: any[]): number {\n\t\tconst id = window.setTimeout(handler, timeout, args)\n\t\tconst current = this.timeouts.get(contextId) ?? []\n\t\tthis.timeouts.set(contextId, [...current, id])\n\t\treturn id\n\t}\n\n\t/**\n\t * Creates an interval that will be tracked under the specified context.\n\t * @param contextId - The context identifier to group this timer under.\n\t * @param handler - The function to execute repeatedly.\n\t * @param timeout - The delay in milliseconds between executions (default: 0).\n\t * @param args - Additional arguments to pass to the handler.\n\t * @returns The interval ID that can be used with clearInterval.\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * const id = timers.setInterval('refresh', () => updateData(), 1000)\n\t * // Interval will be automatically cleared when 'refresh' context is disposed\n\t * ```\n\t * @public\n\t */\n\tsetInterval(contextId: string, handler: TimerHandler, timeout?: number, ...args: any[]): number {\n\t\tconst id = window.setInterval(handler, timeout, args)\n\t\tconst current = this.intervals.get(contextId) ?? []\n\t\tthis.intervals.set(contextId, [...current, id])\n\t\treturn id\n\t}\n\n\t/**\n\t * Requests an animation frame that will be tracked under the specified context.\n\t * @param contextId - The context identifier to group this animation frame under.\n\t * @param callback - The function to execute on the next animation frame.\n\t * @returns The request ID that can be used with cancelAnimationFrame.\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * const id = timers.requestAnimationFrame('render', () => draw())\n\t * // Animation frame will be automatically cancelled when 'render' context is disposed\n\t * ```\n\t * @public\n\t */\n\trequestAnimationFrame(contextId: string, callback: FrameRequestCallback): number {\n\t\tconst id = window.requestAnimationFrame(callback)\n\t\tconst current = this.rafs.get(contextId) ?? []\n\t\tthis.rafs.set(contextId, [...current, id])\n\t\treturn id\n\t}\n\n\t/**\n\t * Disposes of all timers associated with the specified context.\n\t * Clears all timeouts, intervals, and animation frames for the given context ID.\n\t * @param contextId - The context identifier whose timers should be cleared.\n\t * @returns void\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * timers.setTimeout('ui', () => console.log('timeout'), 1000)\n\t * timers.setInterval('ui', () => console.log('interval'), 500)\n\t *\n\t * // Clear all 'ui' context timers\n\t * timers.dispose('ui')\n\t * ```\n\t * @public\n\t */\n\tdispose(contextId: string) {\n\t\tthis.timeouts.get(contextId)?.forEach((id) => clearTimeout(id))\n\t\tthis.intervals.get(contextId)?.forEach((id) => clearInterval(id))\n\t\tthis.rafs.get(contextId)?.forEach((id) => cancelAnimationFrame(id))\n\n\t\tthis.timeouts.delete(contextId)\n\t\tthis.intervals.delete(contextId)\n\t\tthis.rafs.delete(contextId)\n\t}\n\n\t/**\n\t * Disposes of all timers across all contexts.\n\t * Clears every timeout, interval, and animation frame managed by this instance.\n\t * @returns void\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * timers.setTimeout('ui', () => console.log('ui'), 1000)\n\t * timers.setTimeout('background', () => console.log('bg'), 2000)\n\t *\n\t * // Clear everything\n\t * timers.disposeAll()\n\t * ```\n\t * @public\n\t */\n\tdisposeAll() {\n\t\tfor (const contextId of this.timeouts.keys()) {\n\t\t\tthis.dispose(contextId)\n\t\t}\n\t}\n\n\t/**\n\t * Returns an object with timer methods bound to a specific context.\n\t * Convenient for getting context-specific timer functions without repeatedly passing the contextId.\n\t * @param contextId - The context identifier to bind the returned methods to.\n\t * @returns An object with setTimeout, setInterval, requestAnimationFrame, and dispose methods bound to the context.\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * const uiTimers = timers.forContext('ui')\n\t *\n\t * // These are equivalent to calling timers.setTimeout('ui', ...)\n\t * uiTimers.setTimeout(() => console.log('timeout'), 1000)\n\t * uiTimers.setInterval(() => console.log('interval'), 500)\n\t * uiTimers.requestAnimationFrame(() => console.log('frame'))\n\t *\n\t * // Dispose only this context\n\t * uiTimers.dispose()\n\t * ```\n\t * @public\n\t */\n\tforContext(contextId: string) {\n\t\treturn {\n\t\t\tsetTimeout: (handler: TimerHandler, timeout?: number, ...args: any[]) =>\n\t\t\t\tthis.setTimeout(contextId, handler, timeout, args),\n\t\t\tsetInterval: (handler: TimerHandler, timeout?: number, ...args: any[]) =>\n\t\t\t\tthis.setInterval(contextId, handler, timeout, args),\n\t\t\trequestAnimationFrame: (callback: FrameRequestCallback) =>\n\t\t\t\tthis.requestAnimationFrame(contextId, callback),\n\t\t\tdispose: () => this.dispose(contextId),\n\t\t}\n\t}\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAuBO,MAAM,OAAO;AAAA,EACX,WAAW,oBAAI,IAAsB;AAAA,EACrC,YAAY,oBAAI,IAAsB;AAAA,EACtC,OAAO,oBAAI,IAAsB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWzC,cAAc;AACb,SAAK,aAAa,KAAK,WAAW,KAAK,IAAI;AAC3C,SAAK,cAAc,KAAK,YAAY,KAAK,IAAI;AAC7C,SAAK,wBAAwB,KAAK,sBAAsB,KAAK,IAAI;AACjE,SAAK,UAAU,KAAK,QAAQ,KAAK,IAAI;AAAA,EACtC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBA,WAAW,WAAmB,SAAuB,YAAqB,MAAqB;AAC9F,UAAM,KAAK,OAAO,WAAW,SAAS,SAAS,IAAI;AACnD,UAAM,UAAU,KAAK,SAAS,IAAI,SAAS,KAAK,CAAC;AACjD,SAAK,SAAS,IAAI,WAAW,CAAC,GAAG,SAAS,EAAE,CAAC;AAC7C,WAAO;AAAA,EACR;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBA,YAAY,WAAmB,SAAuB,YAAqB,MAAqB;AAC/F,UAAM,KAAK,OAAO,YAAY,SAAS,SAAS,IAAI;AACpD,UAAM,UAAU,KAAK,UAAU,IAAI,SAAS,KAAK,CAAC;AAClD,S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,WAAW,WAAW,SAAS,SAAS,IAAI;AAAA,MAClD,aAAa,CAAC,SAAuB,YAAqB,SACzD,KAAK,YAAY,WAAW,SAAS,SAAS,IAAI;AAAA,MACnD,uBAAuB,CAAC,aACvB,KAAK,sBAAsB,WAAW,QAAQ;AAAA,MAC/C,SAAS,MAAM,KAAK,QAAQ,SAAS;AAAA,IACtC;AAAA,EACD;AACD;",
4
+ "sourcesContent": ["/* eslint-disable tldraw/no-restricted-properties */\n\n/**\n * A utility class for managing timeouts, intervals, and animation frames with context-based organization and automatic cleanup.\n * Helps prevent memory leaks by organizing timers into named contexts that can be cleared together.\n * @example\n * ```ts\n * const timers = new Timers()\n *\n * // Set timers with context organization\n * timers.setTimeout('ui', () => console.log('Auto save'), 5000)\n * timers.setInterval('ui', () => console.log('Refresh'), 1000)\n * timers.requestAnimationFrame('ui', () => console.log('Render'))\n *\n * // Clear all timers for a context\n * timers.dispose('ui')\n *\n * // Or get context-bound functions\n * const uiTimers = timers.forContext('ui')\n * uiTimers.setTimeout(() => console.log('Contextual timeout'), 1000)\n * ```\n * @public\n */\nexport class Timers {\n\t// Ids are dropped as soon as a timer fires or is cleared through this class, so a\n\t// long-lived context (the editor creates two timeouts per pointer down) does not\n\t// accumulate stale ids that `dispose` would otherwise have to clear one by one.\n\tprivate timeouts = new Map<string, Set<number>>()\n\tprivate intervals = new Map<string, Set<number>>()\n\tprivate rafs = new Map<string, Set<number>>()\n\n\t/**\n\t * Creates a new Timers instance with bound methods for safe callback usage.\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * // Methods are pre-bound, safe to use as callbacks\n\t * element.addEventListener('click', timers.dispose)\n\t * ```\n\t */\n\tconstructor() {\n\t\tthis.setTimeout = this.setTimeout.bind(this)\n\t\tthis.setInterval = this.setInterval.bind(this)\n\t\tthis.requestAnimationFrame = this.requestAnimationFrame.bind(this)\n\t\tthis.clearTimeout = this.clearTimeout.bind(this)\n\t\tthis.clearInterval = this.clearInterval.bind(this)\n\t\tthis.cancelAnimationFrame = this.cancelAnimationFrame.bind(this)\n\t\tthis.dispose = this.dispose.bind(this)\n\t}\n\n\t/**\n\t * Creates a timeout that will be tracked under the specified context.\n\t * @param contextId - The context identifier to group this timer under.\n\t * @param handler - The function to execute when the timeout expires.\n\t * @param timeout - The delay in milliseconds (default: 0).\n\t * @param args - Additional arguments to pass to the handler.\n\t * @returns The timer ID that can be used with clearTimeout.\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * const id = timers.setTimeout('autosave', () => save(), 5000)\n\t * // Timer will be automatically cleared when 'autosave' context is disposed\n\t * ```\n\t * @public\n\t */\n\tsetTimeout(contextId: string, handler: TimerHandler, timeout?: number, ...args: any[]): number {\n\t\tconst ids = getOrCreateSet(this.timeouts, contextId)\n\t\t// A test stub can run the handler synchronously, before `id` is assigned, so the wrapper\n\t\t// records that it fired instead of relying on the id being set when it runs.\n\t\tlet fired = false\n\t\tlet id = -1\n\t\t// A string handler is evaluated by the browser, so it cannot be wrapped and stays\n\t\t// tracked until it is cleared or the context is disposed.\n\t\tconst wrapped =\n\t\t\ttypeof handler === 'function'\n\t\t\t\t? (...handlerArgs: any[]) => {\n\t\t\t\t\t\tfired = true\n\t\t\t\t\t\tids.delete(id)\n\t\t\t\t\t\thandler(...handlerArgs)\n\t\t\t\t\t}\n\t\t\t\t: handler\n\t\tid = window.setTimeout(wrapped, timeout, args)\n\t\tif (!fired) ids.add(id)\n\t\treturn id\n\t}\n\n\t/**\n\t * Creates an interval that will be tracked under the specified context.\n\t * @param contextId - The context identifier to group this timer under.\n\t * @param handler - The function to execute repeatedly.\n\t * @param timeout - The delay in milliseconds between executions (default: 0).\n\t * @param args - Additional arguments to pass to the handler.\n\t * @returns The interval ID that can be used with clearInterval.\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * const id = timers.setInterval('refresh', () => updateData(), 1000)\n\t * // Interval will be automatically cleared when 'refresh' context is disposed\n\t * ```\n\t * @public\n\t */\n\tsetInterval(contextId: string, handler: TimerHandler, timeout?: number, ...args: any[]): number {\n\t\tconst id = window.setInterval(handler, timeout, args)\n\t\tgetOrCreateSet(this.intervals, contextId).add(id)\n\t\treturn id\n\t}\n\n\t/**\n\t * Requests an animation frame that will be tracked under the specified context.\n\t * @param contextId - The context identifier to group this animation frame under.\n\t * @param callback - The function to execute on the next animation frame.\n\t * @returns The request ID that can be used with cancelAnimationFrame.\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * const id = timers.requestAnimationFrame('render', () => draw())\n\t * // Animation frame will be automatically cancelled when 'render' context is disposed\n\t * ```\n\t * @public\n\t */\n\trequestAnimationFrame(contextId: string, callback: FrameRequestCallback): number {\n\t\tconst ids = getOrCreateSet(this.rafs, contextId)\n\t\t// Test stubs (the sync fuzz suite, for one) run the frame synchronously, before `id` is\n\t\t// assigned, so the callback records that it fired rather than touching `id` first.\n\t\tlet fired = false\n\t\tlet id = -1\n\t\tid = window.requestAnimationFrame((time) => {\n\t\t\tfired = true\n\t\t\tids.delete(id)\n\t\t\tcallback(time)\n\t\t})\n\t\tif (!fired) ids.add(id)\n\t\treturn id\n\t}\n\n\t/**\n\t * Clears a timeout created with {@link Timers.setTimeout} and stops tracking it.\n\t * Prefer this over the global `clearTimeout` for ids that came from this instance,\n\t * otherwise the id stays tracked until its context is disposed.\n\t * @param contextId - The context identifier the timeout was created under.\n\t * @param id - The timer ID returned by `setTimeout`. Ignored when undefined.\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * const id = timers.setTimeout('autosave', () => save(), 5000)\n\t * timers.clearTimeout('autosave', id)\n\t * ```\n\t * @public\n\t */\n\tclearTimeout(contextId: string, id: number | undefined): void {\n\t\tif (id === undefined) return\n\t\tclearTimeout(id)\n\t\tthis.timeouts.get(contextId)?.delete(id)\n\t}\n\n\t/**\n\t * Clears an interval created with {@link Timers.setInterval} and stops tracking it.\n\t * @param contextId - The context identifier the interval was created under.\n\t * @param id - The interval ID returned by `setInterval`. Ignored when undefined.\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * const id = timers.setInterval('refresh', () => updateData(), 1000)\n\t * timers.clearInterval('refresh', id)\n\t * ```\n\t * @public\n\t */\n\tclearInterval(contextId: string, id: number | undefined): void {\n\t\tif (id === undefined) return\n\t\tclearInterval(id)\n\t\tthis.intervals.get(contextId)?.delete(id)\n\t}\n\n\t/**\n\t * Cancels an animation frame requested with {@link Timers.requestAnimationFrame} and stops tracking it.\n\t * @param contextId - The context identifier the animation frame was requested under.\n\t * @param id - The request ID returned by `requestAnimationFrame`. Ignored when undefined.\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * const id = timers.requestAnimationFrame('render', () => draw())\n\t * timers.cancelAnimationFrame('render', id)\n\t * ```\n\t * @public\n\t */\n\tcancelAnimationFrame(contextId: string, id: number | undefined): void {\n\t\tif (id === undefined) return\n\t\tcancelAnimationFrame(id)\n\t\tthis.rafs.get(contextId)?.delete(id)\n\t}\n\n\t/**\n\t * Disposes of all timers associated with the specified context.\n\t * Clears all timeouts, intervals, and animation frames for the given context ID.\n\t * @param contextId - The context identifier whose timers should be cleared.\n\t * @returns void\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * timers.setTimeout('ui', () => console.log('timeout'), 1000)\n\t * timers.setInterval('ui', () => console.log('interval'), 500)\n\t *\n\t * // Clear all 'ui' context timers\n\t * timers.dispose('ui')\n\t * ```\n\t * @public\n\t */\n\tdispose(contextId: string) {\n\t\tthis.timeouts.get(contextId)?.forEach((id) => clearTimeout(id))\n\t\tthis.intervals.get(contextId)?.forEach((id) => clearInterval(id))\n\t\tthis.rafs.get(contextId)?.forEach((id) => cancelAnimationFrame(id))\n\n\t\tthis.timeouts.delete(contextId)\n\t\tthis.intervals.delete(contextId)\n\t\tthis.rafs.delete(contextId)\n\t}\n\n\t/**\n\t * Disposes of all timers across all contexts.\n\t * Clears every timeout, interval, and animation frame managed by this instance.\n\t * @returns void\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * timers.setTimeout('ui', () => console.log('ui'), 1000)\n\t * timers.setTimeout('background', () => console.log('bg'), 2000)\n\t *\n\t * // Clear everything\n\t * timers.disposeAll()\n\t * ```\n\t * @public\n\t */\n\tdisposeAll() {\n\t\tconst contextIds = new Set([\n\t\t\t...this.timeouts.keys(),\n\t\t\t...this.intervals.keys(),\n\t\t\t...this.rafs.keys(),\n\t\t])\n\t\tfor (const contextId of contextIds) {\n\t\t\tthis.dispose(contextId)\n\t\t}\n\t}\n\n\t/**\n\t * Returns an object with timer methods bound to a specific context.\n\t * Convenient for getting context-specific timer functions without repeatedly passing the contextId.\n\t * @param contextId - The context identifier to bind the returned methods to.\n\t * @returns An object with setTimeout, setInterval, requestAnimationFrame, the matching clear methods, and dispose bound to the context.\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * const uiTimers = timers.forContext('ui')\n\t *\n\t * // These are equivalent to calling timers.setTimeout('ui', ...)\n\t * const id = uiTimers.setTimeout(() => console.log('timeout'), 1000)\n\t * uiTimers.setInterval(() => console.log('interval'), 500)\n\t * uiTimers.requestAnimationFrame(() => console.log('frame'))\n\t *\n\t * // Clear a single timer\n\t * uiTimers.clearTimeout(id)\n\t *\n\t * // Dispose only this context\n\t * uiTimers.dispose()\n\t * ```\n\t * @public\n\t */\n\tforContext(contextId: string) {\n\t\treturn {\n\t\t\tsetTimeout: (handler: TimerHandler, timeout?: number, ...args: any[]) =>\n\t\t\t\tthis.setTimeout(contextId, handler, timeout, args),\n\t\t\tsetInterval: (handler: TimerHandler, timeout?: number, ...args: any[]) =>\n\t\t\t\tthis.setInterval(contextId, handler, timeout, args),\n\t\t\trequestAnimationFrame: (callback: FrameRequestCallback) =>\n\t\t\t\tthis.requestAnimationFrame(contextId, callback),\n\t\t\tclearTimeout: (id: number | undefined) => this.clearTimeout(contextId, id),\n\t\t\tclearInterval: (id: number | undefined) => this.clearInterval(contextId, id),\n\t\t\tcancelAnimationFrame: (id: number | undefined) => this.cancelAnimationFrame(contextId, id),\n\t\t\tdispose: () => this.dispose(contextId),\n\t\t}\n\t}\n}\n\nfunction getOrCreateSet(map: Map<string, Set<number>>, contextId: string): Set<number> {\n\tlet set = map.get(contextId)\n\tif (!set) {\n\t\tset = new Set()\n\t\tmap.set(contextId, set)\n\t}\n\treturn set\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAuBO,MAAM,OAAO;AAAA;AAAA;AAAA;AAAA,EAIX,WAAW,oBAAI,IAAyB;AAAA,EACxC,YAAY,oBAAI,IAAyB;AAAA,EACzC,OAAO,oBAAI,IAAyB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAW5C,cAAc;AACb,SAAK,aAAa,KAAK,WAAW,KAAK,IAAI;AAC3C,SAAK,cAAc,KAAK,YAAY,KAAK,IAAI;AAC7C,SAAK,wBAAwB,KAAK,sBAAsB,KAAK,IAAI;AACjE,SAAK,eAAe,KAAK,aAAa,KAAK,IAAI;AAC/C,SAAK,gBAAgB,KAAK,cAAc,KAAK,IAAI;AACjD,SAAK,uBAAuB,KAAK,qBAAqB,KAAK,IAAI;AAC/D,SAAK,UAAU,KAAK,QAAQ,KAAK,IAAI;AAAA,EACtC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBA,WAAW,WAAmB,SAAuB,YAAqB,MAAqB;AAC9F,UAAM,MAAM,eAAe,KAAK,UAAU,SAAS;AAGnD,QAAI,QAAQ;AACZ,QAAI,KAAK;AAGT,UAAM,UACL,OAAO,YAAY,aAChB,IAAI,gBAAuB;AAC3B,cAAQ;AACR,UAAI,OAAO,EAAE;AACb,cAAQ,GAAG,WAAW;AAAA,IACvB,IACC;AACJ,SAAK,OAAO,WAAW,SAAS,SAAS,IAAI;AAC7C,QAAI,CAAC,MAAO,KAAI,IAAI,EAAE;AACtB,WA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AW,QAAQ;AAAA,MAC/C,cAAc,CAAC,OAA2B,KAAK,aAAa,WAAW,EAAE;AAAA,MACzE,eAAe,CAAC,OAA2B,KAAK,cAAc,WAAW,EAAE;AAAA,MAC3E,sBAAsB,CAAC,OAA2B,KAAK,qBAAqB,WAAW,EAAE;AAAA,MACzF,SAAS,MAAM,KAAK,QAAQ,SAAS;AAAA,IACtC;AAAA,EACD;AACD;AAEA,SAAS,eAAe,KAA+B,WAAgC;AACtF,MAAI,MAAM,IAAI,IAAI,SAAS;AAC3B,MAAI,CAAC,KAAK;AACT,UAAM,oBAAI,IAAI;AACd,QAAI,IAAI,WAAW,GAAG;AAAA,EACvB;AACA,SAAO;AACR;",
6
6
  "names": []
7
7
  }
@@ -931,6 +931,7 @@ export declare class LruCache<K, V> {
931
931
  get(key: K): undefined | V;
932
932
  set(key: K, value: V): void;
933
933
  has(key: K): boolean;
934
+ delete(key: K): boolean;
934
935
  get size(): number;
935
936
  }
936
937
 
@@ -1875,6 +1876,47 @@ export declare class Timers {
1875
1876
  * @public
1876
1877
  */
1877
1878
  requestAnimationFrame(contextId: string, callback: FrameRequestCallback): number;
1879
+ /**
1880
+ * Clears a timeout created with {@link Timers.setTimeout} and stops tracking it.
1881
+ * Prefer this over the global `clearTimeout` for ids that came from this instance,
1882
+ * otherwise the id stays tracked until its context is disposed.
1883
+ * @param contextId - The context identifier the timeout was created under.
1884
+ * @param id - The timer ID returned by `setTimeout`. Ignored when undefined.
1885
+ * @example
1886
+ * ```ts
1887
+ * const timers = new Timers()
1888
+ * const id = timers.setTimeout('autosave', () => save(), 5000)
1889
+ * timers.clearTimeout('autosave', id)
1890
+ * ```
1891
+ * @public
1892
+ */
1893
+ clearTimeout(contextId: string, id: number | undefined): void;
1894
+ /**
1895
+ * Clears an interval created with {@link Timers.setInterval} and stops tracking it.
1896
+ * @param contextId - The context identifier the interval was created under.
1897
+ * @param id - The interval ID returned by `setInterval`. Ignored when undefined.
1898
+ * @example
1899
+ * ```ts
1900
+ * const timers = new Timers()
1901
+ * const id = timers.setInterval('refresh', () => updateData(), 1000)
1902
+ * timers.clearInterval('refresh', id)
1903
+ * ```
1904
+ * @public
1905
+ */
1906
+ clearInterval(contextId: string, id: number | undefined): void;
1907
+ /**
1908
+ * Cancels an animation frame requested with {@link Timers.requestAnimationFrame} and stops tracking it.
1909
+ * @param contextId - The context identifier the animation frame was requested under.
1910
+ * @param id - The request ID returned by `requestAnimationFrame`. Ignored when undefined.
1911
+ * @example
1912
+ * ```ts
1913
+ * const timers = new Timers()
1914
+ * const id = timers.requestAnimationFrame('render', () => draw())
1915
+ * timers.cancelAnimationFrame('render', id)
1916
+ * ```
1917
+ * @public
1918
+ */
1919
+ cancelAnimationFrame(contextId: string, id: number | undefined): void;
1878
1920
  /**
1879
1921
  * Disposes of all timers associated with the specified context.
1880
1922
  * Clears all timeouts, intervals, and animation frames for the given context ID.
@@ -1912,23 +1954,29 @@ export declare class Timers {
1912
1954
  * Returns an object with timer methods bound to a specific context.
1913
1955
  * Convenient for getting context-specific timer functions without repeatedly passing the contextId.
1914
1956
  * @param contextId - The context identifier to bind the returned methods to.
1915
- * @returns An object with setTimeout, setInterval, requestAnimationFrame, and dispose methods bound to the context.
1957
+ * @returns An object with setTimeout, setInterval, requestAnimationFrame, the matching clear methods, and dispose bound to the context.
1916
1958
  * @example
1917
1959
  * ```ts
1918
1960
  * const timers = new Timers()
1919
1961
  * const uiTimers = timers.forContext('ui')
1920
1962
  *
1921
1963
  * // These are equivalent to calling timers.setTimeout('ui', ...)
1922
- * uiTimers.setTimeout(() => console.log('timeout'), 1000)
1964
+ * const id = uiTimers.setTimeout(() => console.log('timeout'), 1000)
1923
1965
  * uiTimers.setInterval(() => console.log('interval'), 500)
1924
1966
  * uiTimers.requestAnimationFrame(() => console.log('frame'))
1925
1967
  *
1968
+ * // Clear a single timer
1969
+ * uiTimers.clearTimeout(id)
1970
+ *
1926
1971
  * // Dispose only this context
1927
1972
  * uiTimers.dispose()
1928
1973
  * ```
1929
1974
  * @public
1930
1975
  */
1931
1976
  forContext(contextId: string): {
1977
+ cancelAnimationFrame: (id: number | undefined) => void;
1978
+ clearInterval: (id: number | undefined) => void;
1979
+ clearTimeout: (id: number | undefined) => void;
1932
1980
  dispose: () => void;
1933
1981
  requestAnimationFrame: (callback: FrameRequestCallback) => number;
1934
1982
  setInterval: (handler: TimerHandler, timeout?: number, ...args: any[]) => number;
@@ -103,7 +103,7 @@ import { registerTldrawLibraryVersion as registerTldrawLibraryVersion2 } from ".
103
103
  import { warnDeprecatedGetter, warnOnce } from "./lib/warn.mjs";
104
104
  registerTldrawLibraryVersion(
105
105
  "@tldraw/utils",
106
- "5.5.0-next.4d6473b0bda1",
106
+ "5.5.0-next.68ff40bd4640",
107
107
  "esm"
108
108
  );
109
109
  export {
@@ -21,6 +21,9 @@ class LruCache {
21
21
  has(key) {
22
22
  return this.map.has(key);
23
23
  }
24
+ delete(key) {
25
+ return this.map.delete(key);
26
+ }
24
27
  // eslint-disable-next-line tldraw/no-setter-getter
25
28
  get size() {
26
29
  return this.map.size;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/lib/LruCache.ts"],
4
- "sourcesContent": ["/** Simple LRU cache backed by a Map's insertion-order iteration. @public */\nexport class LruCache<K, V> {\n\tprivate map = new Map<K, V>()\n\tconstructor(private maxSize: number) {}\n\n\tget(key: K): V | undefined {\n\t\tif (!this.map.has(key)) return undefined\n\t\tconst value = this.map.get(key)!\n\t\t// Move to most-recent position\n\t\tthis.map.delete(key)\n\t\tthis.map.set(key, value)\n\t\treturn value\n\t}\n\n\tset(key: K, value: V): void {\n\t\tif (this.map.has(key)) this.map.delete(key)\n\t\tthis.map.set(key, value)\n\t\tif (this.map.size > this.maxSize) {\n\t\t\t// Evict oldest entry\n\t\t\tthis.map.delete(this.map.keys().next().value!)\n\t\t}\n\t}\n\n\thas(key: K): boolean {\n\t\treturn this.map.has(key)\n\t}\n\n\t// eslint-disable-next-line tldraw/no-setter-getter\n\tget size(): number {\n\t\treturn this.map.size\n\t}\n}\n"],
5
- "mappings": "AACO,MAAM,SAAe;AAAA,EAE3B,YAAoB,SAAiB;AAAjB;AAAA,EAAkB;AAAA,EAAlB;AAAA,EADZ,MAAM,oBAAI,IAAU;AAAA,EAG5B,IAAI,KAAuB;AAC1B,QAAI,CAAC,KAAK,IAAI,IAAI,GAAG,EAAG,QAAO;AAC/B,UAAM,QAAQ,KAAK,IAAI,IAAI,GAAG;AAE9B,SAAK,IAAI,OAAO,GAAG;AACnB,SAAK,IAAI,IAAI,KAAK,KAAK;AACvB,WAAO;AAAA,EACR;AAAA,EAEA,IAAI,KAAQ,OAAgB;AAC3B,QAAI,KAAK,IAAI,IAAI,GAAG,EAAG,MAAK,IAAI,OAAO,GAAG;AAC1C,SAAK,IAAI,IAAI,KAAK,KAAK;AACvB,QAAI,KAAK,IAAI,OAAO,KAAK,SAAS;AAEjC,WAAK,IAAI,OAAO,KAAK,IAAI,KAAK,EAAE,KAAK,EAAE,KAAM;AAAA,IAC9C;AAAA,EACD;AAAA,EAEA,IAAI,KAAiB;AACpB,WAAO,KAAK,IAAI,IAAI,GAAG;AAAA,EACxB;AAAA;AAAA,EAGA,IAAI,OAAe;AAClB,WAAO,KAAK,IAAI;AAAA,EACjB;AACD;",
4
+ "sourcesContent": ["/** Simple LRU cache backed by a Map's insertion-order iteration. @public */\nexport class LruCache<K, V> {\n\tprivate map = new Map<K, V>()\n\tconstructor(private maxSize: number) {}\n\n\tget(key: K): V | undefined {\n\t\tif (!this.map.has(key)) return undefined\n\t\tconst value = this.map.get(key)!\n\t\t// Move to most-recent position\n\t\tthis.map.delete(key)\n\t\tthis.map.set(key, value)\n\t\treturn value\n\t}\n\n\tset(key: K, value: V): void {\n\t\tif (this.map.has(key)) this.map.delete(key)\n\t\tthis.map.set(key, value)\n\t\tif (this.map.size > this.maxSize) {\n\t\t\t// Evict oldest entry\n\t\t\tthis.map.delete(this.map.keys().next().value!)\n\t\t}\n\t}\n\n\thas(key: K): boolean {\n\t\treturn this.map.has(key)\n\t}\n\n\tdelete(key: K): boolean {\n\t\treturn this.map.delete(key)\n\t}\n\n\t// eslint-disable-next-line tldraw/no-setter-getter\n\tget size(): number {\n\t\treturn this.map.size\n\t}\n}\n"],
5
+ "mappings": "AACO,MAAM,SAAe;AAAA,EAE3B,YAAoB,SAAiB;AAAjB;AAAA,EAAkB;AAAA,EAAlB;AAAA,EADZ,MAAM,oBAAI,IAAU;AAAA,EAG5B,IAAI,KAAuB;AAC1B,QAAI,CAAC,KAAK,IAAI,IAAI,GAAG,EAAG,QAAO;AAC/B,UAAM,QAAQ,KAAK,IAAI,IAAI,GAAG;AAE9B,SAAK,IAAI,OAAO,GAAG;AACnB,SAAK,IAAI,IAAI,KAAK,KAAK;AACvB,WAAO;AAAA,EACR;AAAA,EAEA,IAAI,KAAQ,OAAgB;AAC3B,QAAI,KAAK,IAAI,IAAI,GAAG,EAAG,MAAK,IAAI,OAAO,GAAG;AAC1C,SAAK,IAAI,IAAI,KAAK,KAAK;AACvB,QAAI,KAAK,IAAI,OAAO,KAAK,SAAS;AAEjC,WAAK,IAAI,OAAO,KAAK,IAAI,KAAK,EAAE,KAAK,EAAE,KAAM;AAAA,IAC9C;AAAA,EACD;AAAA,EAEA,IAAI,KAAiB;AACpB,WAAO,KAAK,IAAI,IAAI,GAAG;AAAA,EACxB;AAAA,EAEA,OAAO,KAAiB;AACvB,WAAO,KAAK,IAAI,OAAO,GAAG;AAAA,EAC3B;AAAA;AAAA,EAGA,IAAI,OAAe;AAClB,WAAO,KAAK,IAAI;AAAA,EACjB;AACD;",
6
6
  "names": []
7
7
  }
@@ -1,4 +1,7 @@
1
1
  class Timers {
2
+ // Ids are dropped as soon as a timer fires or is cleared through this class, so a
3
+ // long-lived context (the editor creates two timeouts per pointer down) does not
4
+ // accumulate stale ids that `dispose` would otherwise have to clear one by one.
2
5
  timeouts = /* @__PURE__ */ new Map();
3
6
  intervals = /* @__PURE__ */ new Map();
4
7
  rafs = /* @__PURE__ */ new Map();
@@ -15,6 +18,9 @@ class Timers {
15
18
  this.setTimeout = this.setTimeout.bind(this);
16
19
  this.setInterval = this.setInterval.bind(this);
17
20
  this.requestAnimationFrame = this.requestAnimationFrame.bind(this);
21
+ this.clearTimeout = this.clearTimeout.bind(this);
22
+ this.clearInterval = this.clearInterval.bind(this);
23
+ this.cancelAnimationFrame = this.cancelAnimationFrame.bind(this);
18
24
  this.dispose = this.dispose.bind(this);
19
25
  }
20
26
  /**
@@ -33,9 +39,16 @@ class Timers {
33
39
  * @public
34
40
  */
35
41
  setTimeout(contextId, handler, timeout, ...args) {
36
- const id = window.setTimeout(handler, timeout, args);
37
- const current = this.timeouts.get(contextId) ?? [];
38
- this.timeouts.set(contextId, [...current, id]);
42
+ const ids = getOrCreateSet(this.timeouts, contextId);
43
+ let fired = false;
44
+ let id = -1;
45
+ const wrapped = typeof handler === "function" ? (...handlerArgs) => {
46
+ fired = true;
47
+ ids.delete(id);
48
+ handler(...handlerArgs);
49
+ } : handler;
50
+ id = window.setTimeout(wrapped, timeout, args);
51
+ if (!fired) ids.add(id);
39
52
  return id;
40
53
  }
41
54
  /**
@@ -55,8 +68,7 @@ class Timers {
55
68
  */
56
69
  setInterval(contextId, handler, timeout, ...args) {
57
70
  const id = window.setInterval(handler, timeout, args);
58
- const current = this.intervals.get(contextId) ?? [];
59
- this.intervals.set(contextId, [...current, id]);
71
+ getOrCreateSet(this.intervals, contextId).add(id);
60
72
  return id;
61
73
  }
62
74
  /**
@@ -73,11 +85,70 @@ class Timers {
73
85
  * @public
74
86
  */
75
87
  requestAnimationFrame(contextId, callback) {
76
- const id = window.requestAnimationFrame(callback);
77
- const current = this.rafs.get(contextId) ?? [];
78
- this.rafs.set(contextId, [...current, id]);
88
+ const ids = getOrCreateSet(this.rafs, contextId);
89
+ let fired = false;
90
+ let id = -1;
91
+ id = window.requestAnimationFrame((time) => {
92
+ fired = true;
93
+ ids.delete(id);
94
+ callback(time);
95
+ });
96
+ if (!fired) ids.add(id);
79
97
  return id;
80
98
  }
99
+ /**
100
+ * Clears a timeout created with {@link Timers.setTimeout} and stops tracking it.
101
+ * Prefer this over the global `clearTimeout` for ids that came from this instance,
102
+ * otherwise the id stays tracked until its context is disposed.
103
+ * @param contextId - The context identifier the timeout was created under.
104
+ * @param id - The timer ID returned by `setTimeout`. Ignored when undefined.
105
+ * @example
106
+ * ```ts
107
+ * const timers = new Timers()
108
+ * const id = timers.setTimeout('autosave', () => save(), 5000)
109
+ * timers.clearTimeout('autosave', id)
110
+ * ```
111
+ * @public
112
+ */
113
+ clearTimeout(contextId, id) {
114
+ if (id === void 0) return;
115
+ clearTimeout(id);
116
+ this.timeouts.get(contextId)?.delete(id);
117
+ }
118
+ /**
119
+ * Clears an interval created with {@link Timers.setInterval} and stops tracking it.
120
+ * @param contextId - The context identifier the interval was created under.
121
+ * @param id - The interval ID returned by `setInterval`. Ignored when undefined.
122
+ * @example
123
+ * ```ts
124
+ * const timers = new Timers()
125
+ * const id = timers.setInterval('refresh', () => updateData(), 1000)
126
+ * timers.clearInterval('refresh', id)
127
+ * ```
128
+ * @public
129
+ */
130
+ clearInterval(contextId, id) {
131
+ if (id === void 0) return;
132
+ clearInterval(id);
133
+ this.intervals.get(contextId)?.delete(id);
134
+ }
135
+ /**
136
+ * Cancels an animation frame requested with {@link Timers.requestAnimationFrame} and stops tracking it.
137
+ * @param contextId - The context identifier the animation frame was requested under.
138
+ * @param id - The request ID returned by `requestAnimationFrame`. Ignored when undefined.
139
+ * @example
140
+ * ```ts
141
+ * const timers = new Timers()
142
+ * const id = timers.requestAnimationFrame('render', () => draw())
143
+ * timers.cancelAnimationFrame('render', id)
144
+ * ```
145
+ * @public
146
+ */
147
+ cancelAnimationFrame(contextId, id) {
148
+ if (id === void 0) return;
149
+ cancelAnimationFrame(id);
150
+ this.rafs.get(contextId)?.delete(id);
151
+ }
81
152
  /**
82
153
  * Disposes of all timers associated with the specified context.
83
154
  * Clears all timeouts, intervals, and animation frames for the given context ID.
@@ -118,7 +189,12 @@ class Timers {
118
189
  * @public
119
190
  */
120
191
  disposeAll() {
121
- for (const contextId of this.timeouts.keys()) {
192
+ const contextIds = /* @__PURE__ */ new Set([
193
+ ...this.timeouts.keys(),
194
+ ...this.intervals.keys(),
195
+ ...this.rafs.keys()
196
+ ]);
197
+ for (const contextId of contextIds) {
122
198
  this.dispose(contextId);
123
199
  }
124
200
  }
@@ -126,17 +202,20 @@ class Timers {
126
202
  * Returns an object with timer methods bound to a specific context.
127
203
  * Convenient for getting context-specific timer functions without repeatedly passing the contextId.
128
204
  * @param contextId - The context identifier to bind the returned methods to.
129
- * @returns An object with setTimeout, setInterval, requestAnimationFrame, and dispose methods bound to the context.
205
+ * @returns An object with setTimeout, setInterval, requestAnimationFrame, the matching clear methods, and dispose bound to the context.
130
206
  * @example
131
207
  * ```ts
132
208
  * const timers = new Timers()
133
209
  * const uiTimers = timers.forContext('ui')
134
210
  *
135
211
  * // These are equivalent to calling timers.setTimeout('ui', ...)
136
- * uiTimers.setTimeout(() => console.log('timeout'), 1000)
212
+ * const id = uiTimers.setTimeout(() => console.log('timeout'), 1000)
137
213
  * uiTimers.setInterval(() => console.log('interval'), 500)
138
214
  * uiTimers.requestAnimationFrame(() => console.log('frame'))
139
215
  *
216
+ * // Clear a single timer
217
+ * uiTimers.clearTimeout(id)
218
+ *
140
219
  * // Dispose only this context
141
220
  * uiTimers.dispose()
142
221
  * ```
@@ -147,10 +226,21 @@ class Timers {
147
226
  setTimeout: (handler, timeout, ...args) => this.setTimeout(contextId, handler, timeout, args),
148
227
  setInterval: (handler, timeout, ...args) => this.setInterval(contextId, handler, timeout, args),
149
228
  requestAnimationFrame: (callback) => this.requestAnimationFrame(contextId, callback),
229
+ clearTimeout: (id) => this.clearTimeout(contextId, id),
230
+ clearInterval: (id) => this.clearInterval(contextId, id),
231
+ cancelAnimationFrame: (id) => this.cancelAnimationFrame(contextId, id),
150
232
  dispose: () => this.dispose(contextId)
151
233
  };
152
234
  }
153
235
  }
236
+ function getOrCreateSet(map, contextId) {
237
+ let set = map.get(contextId);
238
+ if (!set) {
239
+ set = /* @__PURE__ */ new Set();
240
+ map.set(contextId, set);
241
+ }
242
+ return set;
243
+ }
154
244
  export {
155
245
  Timers
156
246
  };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/lib/timers.ts"],
4
- "sourcesContent": ["/* eslint-disable tldraw/no-restricted-properties */\n\n/**\n * A utility class for managing timeouts, intervals, and animation frames with context-based organization and automatic cleanup.\n * Helps prevent memory leaks by organizing timers into named contexts that can be cleared together.\n * @example\n * ```ts\n * const timers = new Timers()\n *\n * // Set timers with context organization\n * timers.setTimeout('ui', () => console.log('Auto save'), 5000)\n * timers.setInterval('ui', () => console.log('Refresh'), 1000)\n * timers.requestAnimationFrame('ui', () => console.log('Render'))\n *\n * // Clear all timers for a context\n * timers.dispose('ui')\n *\n * // Or get context-bound functions\n * const uiTimers = timers.forContext('ui')\n * uiTimers.setTimeout(() => console.log('Contextual timeout'), 1000)\n * ```\n * @public\n */\nexport class Timers {\n\tprivate timeouts = new Map<string, number[]>()\n\tprivate intervals = new Map<string, number[]>()\n\tprivate rafs = new Map<string, number[]>()\n\n\t/**\n\t * Creates a new Timers instance with bound methods for safe callback usage.\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * // Methods are pre-bound, safe to use as callbacks\n\t * element.addEventListener('click', timers.dispose)\n\t * ```\n\t */\n\tconstructor() {\n\t\tthis.setTimeout = this.setTimeout.bind(this)\n\t\tthis.setInterval = this.setInterval.bind(this)\n\t\tthis.requestAnimationFrame = this.requestAnimationFrame.bind(this)\n\t\tthis.dispose = this.dispose.bind(this)\n\t}\n\n\t/**\n\t * Creates a timeout that will be tracked under the specified context.\n\t * @param contextId - The context identifier to group this timer under.\n\t * @param handler - The function to execute when the timeout expires.\n\t * @param timeout - The delay in milliseconds (default: 0).\n\t * @param args - Additional arguments to pass to the handler.\n\t * @returns The timer ID that can be used with clearTimeout.\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * const id = timers.setTimeout('autosave', () => save(), 5000)\n\t * // Timer will be automatically cleared when 'autosave' context is disposed\n\t * ```\n\t * @public\n\t */\n\tsetTimeout(contextId: string, handler: TimerHandler, timeout?: number, ...args: any[]): number {\n\t\tconst id = window.setTimeout(handler, timeout, args)\n\t\tconst current = this.timeouts.get(contextId) ?? []\n\t\tthis.timeouts.set(contextId, [...current, id])\n\t\treturn id\n\t}\n\n\t/**\n\t * Creates an interval that will be tracked under the specified context.\n\t * @param contextId - The context identifier to group this timer under.\n\t * @param handler - The function to execute repeatedly.\n\t * @param timeout - The delay in milliseconds between executions (default: 0).\n\t * @param args - Additional arguments to pass to the handler.\n\t * @returns The interval ID that can be used with clearInterval.\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * const id = timers.setInterval('refresh', () => updateData(), 1000)\n\t * // Interval will be automatically cleared when 'refresh' context is disposed\n\t * ```\n\t * @public\n\t */\n\tsetInterval(contextId: string, handler: TimerHandler, timeout?: number, ...args: any[]): number {\n\t\tconst id = window.setInterval(handler, timeout, args)\n\t\tconst current = this.intervals.get(contextId) ?? []\n\t\tthis.intervals.set(contextId, [...current, id])\n\t\treturn id\n\t}\n\n\t/**\n\t * Requests an animation frame that will be tracked under the specified context.\n\t * @param contextId - The context identifier to group this animation frame under.\n\t * @param callback - The function to execute on the next animation frame.\n\t * @returns The request ID that can be used with cancelAnimationFrame.\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * const id = timers.requestAnimationFrame('render', () => draw())\n\t * // Animation frame will be automatically cancelled when 'render' context is disposed\n\t * ```\n\t * @public\n\t */\n\trequestAnimationFrame(contextId: string, callback: FrameRequestCallback): number {\n\t\tconst id = window.requestAnimationFrame(callback)\n\t\tconst current = this.rafs.get(contextId) ?? []\n\t\tthis.rafs.set(contextId, [...current, id])\n\t\treturn id\n\t}\n\n\t/**\n\t * Disposes of all timers associated with the specified context.\n\t * Clears all timeouts, intervals, and animation frames for the given context ID.\n\t * @param contextId - The context identifier whose timers should be cleared.\n\t * @returns void\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * timers.setTimeout('ui', () => console.log('timeout'), 1000)\n\t * timers.setInterval('ui', () => console.log('interval'), 500)\n\t *\n\t * // Clear all 'ui' context timers\n\t * timers.dispose('ui')\n\t * ```\n\t * @public\n\t */\n\tdispose(contextId: string) {\n\t\tthis.timeouts.get(contextId)?.forEach((id) => clearTimeout(id))\n\t\tthis.intervals.get(contextId)?.forEach((id) => clearInterval(id))\n\t\tthis.rafs.get(contextId)?.forEach((id) => cancelAnimationFrame(id))\n\n\t\tthis.timeouts.delete(contextId)\n\t\tthis.intervals.delete(contextId)\n\t\tthis.rafs.delete(contextId)\n\t}\n\n\t/**\n\t * Disposes of all timers across all contexts.\n\t * Clears every timeout, interval, and animation frame managed by this instance.\n\t * @returns void\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * timers.setTimeout('ui', () => console.log('ui'), 1000)\n\t * timers.setTimeout('background', () => console.log('bg'), 2000)\n\t *\n\t * // Clear everything\n\t * timers.disposeAll()\n\t * ```\n\t * @public\n\t */\n\tdisposeAll() {\n\t\tfor (const contextId of this.timeouts.keys()) {\n\t\t\tthis.dispose(contextId)\n\t\t}\n\t}\n\n\t/**\n\t * Returns an object with timer methods bound to a specific context.\n\t * Convenient for getting context-specific timer functions without repeatedly passing the contextId.\n\t * @param contextId - The context identifier to bind the returned methods to.\n\t * @returns An object with setTimeout, setInterval, requestAnimationFrame, and dispose methods bound to the context.\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * const uiTimers = timers.forContext('ui')\n\t *\n\t * // These are equivalent to calling timers.setTimeout('ui', ...)\n\t * uiTimers.setTimeout(() => console.log('timeout'), 1000)\n\t * uiTimers.setInterval(() => console.log('interval'), 500)\n\t * uiTimers.requestAnimationFrame(() => console.log('frame'))\n\t *\n\t * // Dispose only this context\n\t * uiTimers.dispose()\n\t * ```\n\t * @public\n\t */\n\tforContext(contextId: string) {\n\t\treturn {\n\t\t\tsetTimeout: (handler: TimerHandler, timeout?: number, ...args: any[]) =>\n\t\t\t\tthis.setTimeout(contextId, handler, timeout, args),\n\t\t\tsetInterval: (handler: TimerHandler, timeout?: number, ...args: any[]) =>\n\t\t\t\tthis.setInterval(contextId, handler, timeout, args),\n\t\t\trequestAnimationFrame: (callback: FrameRequestCallback) =>\n\t\t\t\tthis.requestAnimationFrame(contextId, callback),\n\t\t\tdispose: () => this.dispose(contextId),\n\t\t}\n\t}\n}\n"],
5
- "mappings": "AAuBO,MAAM,OAAO;AAAA,EACX,WAAW,oBAAI,IAAsB;AAAA,EACrC,YAAY,oBAAI,IAAsB;AAAA,EACtC,OAAO,oBAAI,IAAsB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWzC,cAAc;AACb,SAAK,aAAa,KAAK,WAAW,KAAK,IAAI;AAC3C,SAAK,cAAc,KAAK,YAAY,KAAK,IAAI;AAC7C,SAAK,wBAAwB,KAAK,sBAAsB,KAAK,IAAI;AACjE,SAAK,UAAU,KAAK,QAAQ,KAAK,IAAI;AAAA,EACtC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBA,WAAW,WAAmB,SAAuB,YAAqB,MAAqB;AAC9F,UAAM,KAAK,OAAO,WAAW,SAAS,SAAS,IAAI;AACnD,UAAM,UAAU,KAAK,SAAS,IAAI,SAAS,KAAK,CAAC;AACjD,SAAK,SAAS,IAAI,WAAW,CAAC,GAAG,SAAS,EAAE,CAAC;AAC7C,WAAO;AAAA,EACR;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBA,YAAY,WAAmB,SAAuB,YAAqB,MAAqB;AAC/F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AAA;AAAA;AAAA;AAAA,EAsBA,WAAW,WAAmB;AAC7B,WAAO;AAAA,MACN,YAAY,CAAC,SAAuB,YAAqB,SACxD,KAAK,WAAW,WAAW,SAAS,SAAS,IAAI;AAAA,MAClD,aAAa,CAAC,SAAuB,YAAqB,SACzD,KAAK,YAAY,WAAW,SAAS,SAAS,IAAI;AAAA,MACnD,uBAAuB,CAAC,aACvB,KAAK,sBAAsB,WAAW,QAAQ;AAAA,MAC/C,SAAS,MAAM,KAAK,QAAQ,SAAS;AAAA,IACtC;AAAA,EACD;AACD;",
4
+ "sourcesContent": ["/* eslint-disable tldraw/no-restricted-properties */\n\n/**\n * A utility class for managing timeouts, intervals, and animation frames with context-based organization and automatic cleanup.\n * Helps prevent memory leaks by organizing timers into named contexts that can be cleared together.\n * @example\n * ```ts\n * const timers = new Timers()\n *\n * // Set timers with context organization\n * timers.setTimeout('ui', () => console.log('Auto save'), 5000)\n * timers.setInterval('ui', () => console.log('Refresh'), 1000)\n * timers.requestAnimationFrame('ui', () => console.log('Render'))\n *\n * // Clear all timers for a context\n * timers.dispose('ui')\n *\n * // Or get context-bound functions\n * const uiTimers = timers.forContext('ui')\n * uiTimers.setTimeout(() => console.log('Contextual timeout'), 1000)\n * ```\n * @public\n */\nexport class Timers {\n\t// Ids are dropped as soon as a timer fires or is cleared through this class, so a\n\t// long-lived context (the editor creates two timeouts per pointer down) does not\n\t// accumulate stale ids that `dispose` would otherwise have to clear one by one.\n\tprivate timeouts = new Map<string, Set<number>>()\n\tprivate intervals = new Map<string, Set<number>>()\n\tprivate rafs = new Map<string, Set<number>>()\n\n\t/**\n\t * Creates a new Timers instance with bound methods for safe callback usage.\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * // Methods are pre-bound, safe to use as callbacks\n\t * element.addEventListener('click', timers.dispose)\n\t * ```\n\t */\n\tconstructor() {\n\t\tthis.setTimeout = this.setTimeout.bind(this)\n\t\tthis.setInterval = this.setInterval.bind(this)\n\t\tthis.requestAnimationFrame = this.requestAnimationFrame.bind(this)\n\t\tthis.clearTimeout = this.clearTimeout.bind(this)\n\t\tthis.clearInterval = this.clearInterval.bind(this)\n\t\tthis.cancelAnimationFrame = this.cancelAnimationFrame.bind(this)\n\t\tthis.dispose = this.dispose.bind(this)\n\t}\n\n\t/**\n\t * Creates a timeout that will be tracked under the specified context.\n\t * @param contextId - The context identifier to group this timer under.\n\t * @param handler - The function to execute when the timeout expires.\n\t * @param timeout - The delay in milliseconds (default: 0).\n\t * @param args - Additional arguments to pass to the handler.\n\t * @returns The timer ID that can be used with clearTimeout.\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * const id = timers.setTimeout('autosave', () => save(), 5000)\n\t * // Timer will be automatically cleared when 'autosave' context is disposed\n\t * ```\n\t * @public\n\t */\n\tsetTimeout(contextId: string, handler: TimerHandler, timeout?: number, ...args: any[]): number {\n\t\tconst ids = getOrCreateSet(this.timeouts, contextId)\n\t\t// A test stub can run the handler synchronously, before `id` is assigned, so the wrapper\n\t\t// records that it fired instead of relying on the id being set when it runs.\n\t\tlet fired = false\n\t\tlet id = -1\n\t\t// A string handler is evaluated by the browser, so it cannot be wrapped and stays\n\t\t// tracked until it is cleared or the context is disposed.\n\t\tconst wrapped =\n\t\t\ttypeof handler === 'function'\n\t\t\t\t? (...handlerArgs: any[]) => {\n\t\t\t\t\t\tfired = true\n\t\t\t\t\t\tids.delete(id)\n\t\t\t\t\t\thandler(...handlerArgs)\n\t\t\t\t\t}\n\t\t\t\t: handler\n\t\tid = window.setTimeout(wrapped, timeout, args)\n\t\tif (!fired) ids.add(id)\n\t\treturn id\n\t}\n\n\t/**\n\t * Creates an interval that will be tracked under the specified context.\n\t * @param contextId - The context identifier to group this timer under.\n\t * @param handler - The function to execute repeatedly.\n\t * @param timeout - The delay in milliseconds between executions (default: 0).\n\t * @param args - Additional arguments to pass to the handler.\n\t * @returns The interval ID that can be used with clearInterval.\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * const id = timers.setInterval('refresh', () => updateData(), 1000)\n\t * // Interval will be automatically cleared when 'refresh' context is disposed\n\t * ```\n\t * @public\n\t */\n\tsetInterval(contextId: string, handler: TimerHandler, timeout?: number, ...args: any[]): number {\n\t\tconst id = window.setInterval(handler, timeout, args)\n\t\tgetOrCreateSet(this.intervals, contextId).add(id)\n\t\treturn id\n\t}\n\n\t/**\n\t * Requests an animation frame that will be tracked under the specified context.\n\t * @param contextId - The context identifier to group this animation frame under.\n\t * @param callback - The function to execute on the next animation frame.\n\t * @returns The request ID that can be used with cancelAnimationFrame.\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * const id = timers.requestAnimationFrame('render', () => draw())\n\t * // Animation frame will be automatically cancelled when 'render' context is disposed\n\t * ```\n\t * @public\n\t */\n\trequestAnimationFrame(contextId: string, callback: FrameRequestCallback): number {\n\t\tconst ids = getOrCreateSet(this.rafs, contextId)\n\t\t// Test stubs (the sync fuzz suite, for one) run the frame synchronously, before `id` is\n\t\t// assigned, so the callback records that it fired rather than touching `id` first.\n\t\tlet fired = false\n\t\tlet id = -1\n\t\tid = window.requestAnimationFrame((time) => {\n\t\t\tfired = true\n\t\t\tids.delete(id)\n\t\t\tcallback(time)\n\t\t})\n\t\tif (!fired) ids.add(id)\n\t\treturn id\n\t}\n\n\t/**\n\t * Clears a timeout created with {@link Timers.setTimeout} and stops tracking it.\n\t * Prefer this over the global `clearTimeout` for ids that came from this instance,\n\t * otherwise the id stays tracked until its context is disposed.\n\t * @param contextId - The context identifier the timeout was created under.\n\t * @param id - The timer ID returned by `setTimeout`. Ignored when undefined.\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * const id = timers.setTimeout('autosave', () => save(), 5000)\n\t * timers.clearTimeout('autosave', id)\n\t * ```\n\t * @public\n\t */\n\tclearTimeout(contextId: string, id: number | undefined): void {\n\t\tif (id === undefined) return\n\t\tclearTimeout(id)\n\t\tthis.timeouts.get(contextId)?.delete(id)\n\t}\n\n\t/**\n\t * Clears an interval created with {@link Timers.setInterval} and stops tracking it.\n\t * @param contextId - The context identifier the interval was created under.\n\t * @param id - The interval ID returned by `setInterval`. Ignored when undefined.\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * const id = timers.setInterval('refresh', () => updateData(), 1000)\n\t * timers.clearInterval('refresh', id)\n\t * ```\n\t * @public\n\t */\n\tclearInterval(contextId: string, id: number | undefined): void {\n\t\tif (id === undefined) return\n\t\tclearInterval(id)\n\t\tthis.intervals.get(contextId)?.delete(id)\n\t}\n\n\t/**\n\t * Cancels an animation frame requested with {@link Timers.requestAnimationFrame} and stops tracking it.\n\t * @param contextId - The context identifier the animation frame was requested under.\n\t * @param id - The request ID returned by `requestAnimationFrame`. Ignored when undefined.\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * const id = timers.requestAnimationFrame('render', () => draw())\n\t * timers.cancelAnimationFrame('render', id)\n\t * ```\n\t * @public\n\t */\n\tcancelAnimationFrame(contextId: string, id: number | undefined): void {\n\t\tif (id === undefined) return\n\t\tcancelAnimationFrame(id)\n\t\tthis.rafs.get(contextId)?.delete(id)\n\t}\n\n\t/**\n\t * Disposes of all timers associated with the specified context.\n\t * Clears all timeouts, intervals, and animation frames for the given context ID.\n\t * @param contextId - The context identifier whose timers should be cleared.\n\t * @returns void\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * timers.setTimeout('ui', () => console.log('timeout'), 1000)\n\t * timers.setInterval('ui', () => console.log('interval'), 500)\n\t *\n\t * // Clear all 'ui' context timers\n\t * timers.dispose('ui')\n\t * ```\n\t * @public\n\t */\n\tdispose(contextId: string) {\n\t\tthis.timeouts.get(contextId)?.forEach((id) => clearTimeout(id))\n\t\tthis.intervals.get(contextId)?.forEach((id) => clearInterval(id))\n\t\tthis.rafs.get(contextId)?.forEach((id) => cancelAnimationFrame(id))\n\n\t\tthis.timeouts.delete(contextId)\n\t\tthis.intervals.delete(contextId)\n\t\tthis.rafs.delete(contextId)\n\t}\n\n\t/**\n\t * Disposes of all timers across all contexts.\n\t * Clears every timeout, interval, and animation frame managed by this instance.\n\t * @returns void\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * timers.setTimeout('ui', () => console.log('ui'), 1000)\n\t * timers.setTimeout('background', () => console.log('bg'), 2000)\n\t *\n\t * // Clear everything\n\t * timers.disposeAll()\n\t * ```\n\t * @public\n\t */\n\tdisposeAll() {\n\t\tconst contextIds = new Set([\n\t\t\t...this.timeouts.keys(),\n\t\t\t...this.intervals.keys(),\n\t\t\t...this.rafs.keys(),\n\t\t])\n\t\tfor (const contextId of contextIds) {\n\t\t\tthis.dispose(contextId)\n\t\t}\n\t}\n\n\t/**\n\t * Returns an object with timer methods bound to a specific context.\n\t * Convenient for getting context-specific timer functions without repeatedly passing the contextId.\n\t * @param contextId - The context identifier to bind the returned methods to.\n\t * @returns An object with setTimeout, setInterval, requestAnimationFrame, the matching clear methods, and dispose bound to the context.\n\t * @example\n\t * ```ts\n\t * const timers = new Timers()\n\t * const uiTimers = timers.forContext('ui')\n\t *\n\t * // These are equivalent to calling timers.setTimeout('ui', ...)\n\t * const id = uiTimers.setTimeout(() => console.log('timeout'), 1000)\n\t * uiTimers.setInterval(() => console.log('interval'), 500)\n\t * uiTimers.requestAnimationFrame(() => console.log('frame'))\n\t *\n\t * // Clear a single timer\n\t * uiTimers.clearTimeout(id)\n\t *\n\t * // Dispose only this context\n\t * uiTimers.dispose()\n\t * ```\n\t * @public\n\t */\n\tforContext(contextId: string) {\n\t\treturn {\n\t\t\tsetTimeout: (handler: TimerHandler, timeout?: number, ...args: any[]) =>\n\t\t\t\tthis.setTimeout(contextId, handler, timeout, args),\n\t\t\tsetInterval: (handler: TimerHandler, timeout?: number, ...args: any[]) =>\n\t\t\t\tthis.setInterval(contextId, handler, timeout, args),\n\t\t\trequestAnimationFrame: (callback: FrameRequestCallback) =>\n\t\t\t\tthis.requestAnimationFrame(contextId, callback),\n\t\t\tclearTimeout: (id: number | undefined) => this.clearTimeout(contextId, id),\n\t\t\tclearInterval: (id: number | undefined) => this.clearInterval(contextId, id),\n\t\t\tcancelAnimationFrame: (id: number | undefined) => this.cancelAnimationFrame(contextId, id),\n\t\t\tdispose: () => this.dispose(contextId),\n\t\t}\n\t}\n}\n\nfunction getOrCreateSet(map: Map<string, Set<number>>, contextId: string): Set<number> {\n\tlet set = map.get(contextId)\n\tif (!set) {\n\t\tset = new Set()\n\t\tmap.set(contextId, set)\n\t}\n\treturn set\n}\n"],
5
+ "mappings": "AAuBO,MAAM,OAAO;AAAA;AAAA;AAAA;AAAA,EAIX,WAAW,oBAAI,IAAyB;AAAA,EACxC,YAAY,oBAAI,IAAyB;AAAA,EACzC,OAAO,oBAAI,IAAyB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAW5C,cAAc;AACb,SAAK,aAAa,KAAK,WAAW,KAAK,IAAI;AAC3C,SAAK,cAAc,KAAK,YAAY,KAAK,IAAI;AAC7C,SAAK,wBAAwB,KAAK,sBAAsB,KAAK,IAAI;AACjE,SAAK,eAAe,KAAK,aAAa,KAAK,IAAI;AAC/C,SAAK,gBAAgB,KAAK,cAAc,KAAK,IAAI;AACjD,SAAK,uBAAuB,KAAK,qBAAqB,KAAK,IAAI;AAC/D,SAAK,UAAU,KAAK,QAAQ,KAAK,IAAI;AAAA,EACtC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBA,WAAW,WAAmB,SAAuB,YAAqB,MAAqB;AAC9F,UAAM,MAAM,eAAe,KAAK,UAAU,SAAS;AAGnD,QAAI,QAAQ;AACZ,QAAI,KAAK;AAGT,UAAM,UACL,OAAO,YAAY,aAChB,IAAI,gBAAuB;AAC3B,cAAQ;AACR,UAAI,OAAO,EAAE;AACb,cAAQ,GAAG,WAAW;AAAA,IACvB,IACC;AACJ,SAAK,OAAO,WAAW,SAAS,SAAS,IAAI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AI;AAAA,MACnD,uBAAuB,CAAC,aACvB,KAAK,sBAAsB,WAAW,QAAQ;AAAA,MAC/C,cAAc,CAAC,OAA2B,KAAK,aAAa,WAAW,EAAE;AAAA,MACzE,eAAe,CAAC,OAA2B,KAAK,cAAc,WAAW,EAAE;AAAA,MAC3E,sBAAsB,CAAC,OAA2B,KAAK,qBAAqB,WAAW,EAAE;AAAA,MACzF,SAAS,MAAM,KAAK,QAAQ,SAAS;AAAA,IACtC;AAAA,EACD;AACD;AAEA,SAAS,eAAe,KAA+B,WAAgC;AACtF,MAAI,MAAM,IAAI,IAAI,SAAS;AAC3B,MAAI,CAAC,KAAK;AACT,UAAM,oBAAI,IAAI;AACd,QAAI,IAAI,WAAW,GAAG;AAAA,EACvB;AACA,SAAO;AACR;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@tldraw/utils",
3
3
  "description": "tldraw infinite canvas SDK (private utilities).",
4
- "version": "5.5.0-next.4d6473b0bda1",
4
+ "version": "5.5.0-next.68ff40bd4640",
5
5
  "author": {
6
6
  "name": "tldraw Inc.",
7
7
  "email": "hello@tldraw.com"
8
8
  },
9
9
  "homepage": "https://tldraw.dev",
10
- "license": "SEE LICENSE IN LICENSE.md",
10
+ "license": "MIT",
11
11
  "tldraw_product": {
12
12
  "stableId": "tldraw:sdk-core",
13
13
  "name": "SDK",
@@ -61,7 +61,7 @@
61
61
  "@types/lodash.throttle": "^4.1.9",
62
62
  "@types/lodash.uniq": "^4.5.9",
63
63
  "lazyrepo": "0.0.0-alpha.27",
64
- "vitest": "^4.1.7"
64
+ "vitest": "^5.0.0"
65
65
  },
66
66
  "engines": {
67
67
  "node": ">=22.12.0"
@@ -19,6 +19,18 @@ describe('LruCache', () => {
19
19
  expect(cache.size).toBe(2)
20
20
  })
21
21
 
22
+ it('delete() removes an entry and frees its slot', () => {
23
+ const cache = new LruCache<string, number>(2)
24
+ cache.set('a', 1)
25
+ cache.set('b', 2)
26
+ expect(cache.delete('a')).toBe(true)
27
+ expect(cache.delete('a')).toBe(false)
28
+ expect(cache.has('a')).toBe(false)
29
+ cache.set('c', 3)
30
+ expect(cache.get('b')).toBe(2)
31
+ expect(cache.size).toBe(2)
32
+ })
33
+
22
34
  it('has() checks existence without promoting', () => {
23
35
  const cache = new LruCache<string, number>(2)
24
36
  cache.set('a', 1)
@@ -25,6 +25,10 @@ export class LruCache<K, V> {
25
25
  return this.map.has(key)
26
26
  }
27
27
 
28
+ delete(key: K): boolean {
29
+ return this.map.delete(key)
30
+ }
31
+
28
32
  // eslint-disable-next-line tldraw/no-setter-getter
29
33
  get size(): number {
30
34
  return this.map.size
@@ -13,35 +13,26 @@ import {
13
13
  } from './storage'
14
14
 
15
15
  describe('storage', () => {
16
- // Store original implementations
17
- const originalLocalStorage = global.localStorage
18
- const originalSessionStorage = global.sessionStorage
19
-
20
- beforeEach(() => {
21
- // Mock localStorage
22
- const localStorageMock = {
16
+ // Stub the Window accessors rather than assigning to `global.localStorage`: jsdom defines
17
+ // these as getters that assignment can't overwrite, and each read returns a fresh wrapper,
18
+ // so a spy on one instance wouldn't be seen by the next read.
19
+ function stubStorage(name: 'localStorage' | 'sessionStorage') {
20
+ const mock = {
23
21
  getItem: vi.fn(),
24
22
  setItem: vi.fn(),
25
23
  removeItem: vi.fn(),
26
24
  clear: vi.fn(),
27
25
  }
28
- global.localStorage = localStorageMock as any
26
+ vi.spyOn(window, name, 'get').mockReturnValue(mock as any)
27
+ }
29
28
 
30
- // Mock sessionStorage
31
- const sessionStorageMock = {
32
- getItem: vi.fn(),
33
- setItem: vi.fn(),
34
- removeItem: vi.fn(),
35
- clear: vi.fn(),
36
- }
37
- global.sessionStorage = sessionStorageMock as any
29
+ beforeEach(() => {
30
+ stubStorage('localStorage')
31
+ stubStorage('sessionStorage')
38
32
  })
39
33
 
40
34
  afterEach(() => {
41
- // Restore original implementations
42
- global.localStorage = originalLocalStorage
43
- global.sessionStorage = originalSessionStorage
44
- vi.clearAllMocks()
35
+ vi.restoreAllMocks()
45
36
  })
46
37
 
47
38
  describe('getFromLocalStorage', () => {
@@ -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
+ }