@twick/canvas 0.15.1 → 0.15.3

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.
package/dist/index.mjs CHANGED
@@ -126,7 +126,6 @@ const reorderElementsByZIndex = (canvas) => {
126
126
  if (!canvas) return;
127
127
  const backgroundColor = canvas.backgroundColor;
128
128
  const objects = canvas.getObjects();
129
- console.log("objects", objects);
130
129
  objects.sort((a, b) => (a.zIndex || 0) - (b.zIndex || 0));
131
130
  canvas.clear();
132
131
  canvas.backgroundColor = backgroundColor;
@@ -211,15 +210,133 @@ const rotateControl = new Control({
211
210
  /** Whether to show connection line */
212
211
  withConnection: true
213
212
  });
214
- const getThumbnail = async (videoUrl, seekTime = 0.1, playbackRate = 1) => {
215
- return new Promise((resolve, reject) => {
213
+ class LRUCache {
214
+ constructor(maxSize = 100) {
215
+ if (maxSize <= 0) {
216
+ throw new Error("maxSize must be greater than 0");
217
+ }
218
+ this.maxSize = maxSize;
219
+ this.cache = /* @__PURE__ */ new Map();
220
+ }
221
+ /**
222
+ * Get a value from the cache.
223
+ * Moves the item to the end (most recently used).
224
+ */
225
+ get(key) {
226
+ const value = this.cache.get(key);
227
+ if (value === void 0) {
228
+ return void 0;
229
+ }
230
+ this.cache.delete(key);
231
+ this.cache.set(key, value);
232
+ return value;
233
+ }
234
+ /**
235
+ * Set a value in the cache.
236
+ * If cache is full, removes the least recently used item.
237
+ */
238
+ set(key, value) {
239
+ if (this.cache.has(key)) {
240
+ this.cache.delete(key);
241
+ } else if (this.cache.size >= this.maxSize) {
242
+ const firstKey = this.cache.keys().next().value;
243
+ if (firstKey !== void 0) {
244
+ this.cache.delete(firstKey);
245
+ }
246
+ }
247
+ this.cache.set(key, value);
248
+ }
249
+ /**
250
+ * Check if a key exists in the cache.
251
+ */
252
+ has(key) {
253
+ return this.cache.has(key);
254
+ }
255
+ /**
256
+ * Delete a key from the cache.
257
+ */
258
+ delete(key) {
259
+ return this.cache.delete(key);
260
+ }
261
+ /**
262
+ * Clear all entries from the cache.
263
+ */
264
+ clear() {
265
+ this.cache.clear();
266
+ }
267
+ /**
268
+ * Get the current size of the cache.
269
+ */
270
+ get size() {
271
+ return this.cache.size;
272
+ }
273
+ }
274
+ class VideoFrameExtractor {
275
+ constructor(options = {}) {
276
+ this.frameCache = new LRUCache(
277
+ options.maxCacheSize ?? 50
278
+ );
279
+ this.videoElements = /* @__PURE__ */ new Map();
280
+ this.maxVideoElements = options.maxVideoElements ?? 5;
281
+ this.loadTimeout = options.loadTimeout ?? 15e3;
282
+ this.jpegQuality = options.jpegQuality ?? 0.8;
283
+ this.playbackRate = options.playbackRate ?? 1;
284
+ }
285
+ /**
286
+ * Get a frame thumbnail from a video at a specific time.
287
+ * Uses caching and reuses video elements for optimal performance.
288
+ *
289
+ * @param videoUrl - The URL of the video
290
+ * @param seekTime - The time in seconds to extract the frame
291
+ * @returns Promise resolving to a thumbnail image URL (data URL or blob URL)
292
+ */
293
+ async getFrame(videoUrl, seekTime = 0.1) {
294
+ const cacheKey = this.getCacheKey(videoUrl, seekTime);
295
+ const cached = this.frameCache.get(cacheKey);
296
+ if (cached) {
297
+ return cached;
298
+ }
299
+ const videoState = await this.getVideoElement(videoUrl);
300
+ const thumbnail = await this.extractFrame(videoState.video, seekTime);
301
+ this.frameCache.set(cacheKey, thumbnail);
302
+ return thumbnail;
303
+ }
304
+ /**
305
+ * Get or create a video element for the given URL.
306
+ * Reuses existing elements and manages cleanup.
307
+ */
308
+ async getVideoElement(videoUrl) {
309
+ let videoState = this.videoElements.get(videoUrl);
310
+ if (videoState && videoState.isReady) {
311
+ videoState.lastUsed = Date.now();
312
+ return videoState;
313
+ }
314
+ if (videoState && videoState.isLoading && videoState.loadPromise) {
315
+ await videoState.loadPromise;
316
+ if (videoState.isReady) {
317
+ videoState.lastUsed = Date.now();
318
+ return videoState;
319
+ }
320
+ }
321
+ if (this.videoElements.size >= this.maxVideoElements) {
322
+ this.cleanupOldVideoElements();
323
+ }
324
+ videoState = await this.createVideoElement(videoUrl);
325
+ this.videoElements.set(videoUrl, videoState);
326
+ videoState.lastUsed = Date.now();
327
+ return videoState;
328
+ }
329
+ /**
330
+ * Create and initialize a new video element.
331
+ */
332
+ async createVideoElement(videoUrl) {
216
333
  const video = document.createElement("video");
217
334
  video.crossOrigin = "anonymous";
218
335
  video.muted = true;
219
336
  video.playsInline = true;
220
337
  video.autoplay = false;
221
338
  video.preload = "auto";
222
- video.playbackRate = playbackRate;
339
+ video.playbackRate = this.playbackRate;
223
340
  video.style.position = "absolute";
224
341
  video.style.left = "-9999px";
225
342
  video.style.top = "-9999px";
@@ -228,55 +345,128 @@ const getThumbnail = async (videoUrl, seekTime = 0.1, playbackRate = 1) => {
228
345
  video.style.opacity = "0";
229
346
  video.style.pointerEvents = "none";
230
347
  video.style.zIndex = "-1";
231
- let timeoutId;
232
- const cleanup = () => {
233
- if (video.parentNode) video.remove();
234
- if (timeoutId) clearTimeout(timeoutId);
235
- };
236
- const handleError = () => {
237
- var _a;
238
- cleanup();
239
- reject(new Error(`Failed to load video: ${((_a = video.error) == null ? void 0 : _a.message) || "Unknown error"}`));
348
+ const state = {
349
+ video,
350
+ isReady: false,
351
+ isLoading: true,
352
+ loadPromise: null,
353
+ lastUsed: Date.now()
240
354
  };
241
- const handleSeeked = () => {
242
- try {
243
- video.pause();
244
- const canvas = document.createElement("canvas");
245
- const width = video.videoWidth || 640;
246
- const height = video.videoHeight || 360;
247
- canvas.width = width;
248
- canvas.height = height;
249
- const ctx = canvas.getContext("2d");
250
- if (!ctx) {
251
- cleanup();
252
- reject(new Error("Failed to get canvas context"));
355
+ state.loadPromise = new Promise((resolve, reject) => {
356
+ let timeoutId;
357
+ const cleanup = () => {
358
+ if (timeoutId) clearTimeout(timeoutId);
359
+ };
360
+ const handleError = () => {
361
+ var _a;
362
+ cleanup();
363
+ state.isLoading = false;
364
+ reject(new Error(`Failed to load video: ${((_a = video.error) == null ? void 0 : _a.message) || "Unknown error"}`));
365
+ };
366
+ const handleLoadedMetadata = () => {
367
+ cleanup();
368
+ state.isReady = true;
369
+ state.isLoading = false;
370
+ resolve();
371
+ };
372
+ video.addEventListener("error", handleError, { once: true });
373
+ video.addEventListener("loadedmetadata", handleLoadedMetadata, { once: true });
374
+ timeoutId = window.setTimeout(() => {
375
+ cleanup();
376
+ state.isLoading = false;
377
+ reject(new Error("Video loading timed out"));
378
+ }, this.loadTimeout);
379
+ video.src = videoUrl;
380
+ document.body.appendChild(video);
381
+ });
382
+ try {
383
+ await state.loadPromise;
384
+ } catch (error) {
385
+ if (video.parentNode) {
386
+ video.remove();
387
+ }
388
+ throw error;
389
+ }
390
+ return state;
391
+ }
392
+ /**
393
+ * Extract a frame from a video at the specified time.
394
+ */
395
+ async extractFrame(video, seekTime) {
396
+ return new Promise((resolve, reject) => {
397
+ video.pause();
398
+ const timeThreshold = 0.1;
399
+ if (Math.abs(video.currentTime - seekTime) < timeThreshold) {
400
+ try {
401
+ const canvas = document.createElement("canvas");
402
+ const width = video.videoWidth || 640;
403
+ const height = video.videoHeight || 360;
404
+ canvas.width = width;
405
+ canvas.height = height;
406
+ const ctx = canvas.getContext("2d");
407
+ if (!ctx) {
408
+ reject(new Error("Failed to get canvas context"));
409
+ return;
410
+ }
411
+ ctx.drawImage(video, 0, 0, width, height);
412
+ try {
413
+ const dataUrl = canvas.toDataURL("image/jpeg", this.jpegQuality);
414
+ resolve(dataUrl);
415
+ } catch {
416
+ canvas.toBlob(
417
+ (blob) => {
418
+ if (!blob) {
419
+ reject(new Error("Failed to create Blob"));
420
+ return;
421
+ }
422
+ const blobUrl = URL.createObjectURL(blob);
423
+ resolve(blobUrl);
424
+ },
425
+ "image/jpeg",
426
+ this.jpegQuality
427
+ );
428
+ }
429
+ return;
430
+ } catch (err) {
431
+ reject(new Error(`Error creating thumbnail: ${err}`));
253
432
  return;
254
433
  }
255
- ctx.drawImage(video, 0, 0, width, height);
434
+ }
435
+ const handleSeeked = () => {
256
436
  try {
257
- const dataUrl = canvas.toDataURL("image/jpeg", 0.8);
258
- cleanup();
259
- resolve(dataUrl);
260
- } catch {
261
- canvas.toBlob((blob) => {
262
- if (!blob) {
263
- cleanup();
264
- reject(new Error("Failed to create Blob"));
265
- return;
266
- }
267
- const blobUrl = URL.createObjectURL(blob);
268
- cleanup();
269
- resolve(blobUrl);
270
- }, "image/jpeg", 0.8);
437
+ const canvas = document.createElement("canvas");
438
+ const width = video.videoWidth || 640;
439
+ const height = video.videoHeight || 360;
440
+ canvas.width = width;
441
+ canvas.height = height;
442
+ const ctx = canvas.getContext("2d");
443
+ if (!ctx) {
444
+ reject(new Error("Failed to get canvas context"));
445
+ return;
446
+ }
447
+ ctx.drawImage(video, 0, 0, width, height);
448
+ try {
449
+ const dataUrl = canvas.toDataURL("image/jpeg", this.jpegQuality);
450
+ resolve(dataUrl);
451
+ } catch {
452
+ canvas.toBlob(
453
+ (blob) => {
454
+ if (!blob) {
455
+ reject(new Error("Failed to create Blob"));
456
+ return;
457
+ }
458
+ const blobUrl = URL.createObjectURL(blob);
459
+ resolve(blobUrl);
460
+ },
461
+ "image/jpeg",
462
+ this.jpegQuality
463
+ );
464
+ }
465
+ } catch (err) {
466
+ reject(new Error(`Error creating thumbnail: ${err}`));
271
467
  }
272
- } catch (err) {
273
- cleanup();
274
- reject(new Error(`Error creating thumbnail: ${err}`));
275
- }
276
- };
277
- video.addEventListener("error", handleError, { once: true });
278
- video.addEventListener("seeked", handleSeeked, { once: true });
279
- video.addEventListener("loadedmetadata", () => {
468
+ };
469
+ video.addEventListener("seeked", handleSeeked, { once: true });
280
470
  const playPromise = video.play();
281
471
  if (playPromise !== void 0) {
282
472
  playPromise.then(() => {
@@ -287,15 +477,80 @@ const getThumbnail = async (videoUrl, seekTime = 0.1, playbackRate = 1) => {
287
477
  } else {
288
478
  video.currentTime = seekTime;
289
479
  }
290
- }, { once: true });
291
- timeoutId = window.setTimeout(() => {
292
- cleanup();
293
- reject(new Error("Video loading timed out"));
294
- }, 15e3);
295
- video.src = videoUrl;
296
- document.body.appendChild(video);
297
- });
298
- };
480
+ });
481
+ }
482
+ /**
483
+ * Generate cache key for a video URL and seek time.
484
+ */
485
+ getCacheKey(videoUrl, seekTime) {
486
+ const roundedTime = Math.round(seekTime * 100) / 100;
487
+ return `${videoUrl}:${roundedTime}`;
488
+ }
489
+ /**
490
+ * Cleanup least recently used video elements.
491
+ */
492
+ cleanupOldVideoElements() {
493
+ if (this.videoElements.size < this.maxVideoElements) {
494
+ return;
495
+ }
496
+ const entries = Array.from(this.videoElements.entries());
497
+ entries.sort((a, b) => a[1].lastUsed - b[1].lastUsed);
498
+ const toRemove = entries.slice(0, entries.length - this.maxVideoElements + 1);
499
+ for (const [url, state] of toRemove) {
500
+ if (state.video.parentNode) {
501
+ state.video.remove();
502
+ }
503
+ this.videoElements.delete(url);
504
+ }
505
+ }
506
+ /**
507
+ * Clear the frame cache.
508
+ */
509
+ clearCache() {
510
+ this.frameCache.clear();
511
+ }
512
+ /**
513
+ * Remove a specific video element and clear its cached frames.
514
+ */
515
+ removeVideo(videoUrl) {
516
+ const state = this.videoElements.get(videoUrl);
517
+ if (state) {
518
+ if (state.video.parentNode) {
519
+ state.video.remove();
520
+ }
521
+ this.videoElements.delete(videoUrl);
522
+ }
523
+ this.frameCache.clear();
524
+ }
525
+ /**
526
+ * Dispose of all video elements and clear caches.
527
+ * Removes all video elements from the DOM and clears both the frame cache
528
+ * and video element cache. Call this when the extractor is no longer needed
529
+ * to prevent memory leaks.
530
+ */
531
+ dispose() {
532
+ for (const state of this.videoElements.values()) {
533
+ if (state.video.parentNode) {
534
+ state.video.remove();
535
+ }
536
+ }
537
+ this.videoElements.clear();
538
+ this.frameCache.clear();
539
+ }
540
+ }
541
+ let defaultExtractor = null;
542
+ function getDefaultVideoFrameExtractor(options) {
543
+ if (!defaultExtractor) {
544
+ defaultExtractor = new VideoFrameExtractor(options);
545
+ }
546
+ return defaultExtractor;
547
+ }
548
+ async function getThumbnailCached(videoUrl, seekTime = 0.1, playbackRate) {
549
+ const extractor = getDefaultVideoFrameExtractor(
550
+ void 0
551
+ );
552
+ return extractor.getFrame(videoUrl, seekTime);
553
+ }
299
554
  const getObjectFitSize = (objectFit, elementSize, containerSize) => {
300
555
  const elementAspectRatio = elementSize.width / elementSize.height;
301
556
  const containerAspectRatio = containerSize.width / containerSize.height;
@@ -477,7 +732,7 @@ const addVideoElement = async ({
477
732
  }) => {
478
733
  var _a;
479
734
  try {
480
- const thumbnailUrl = await getThumbnail(
735
+ const thumbnailUrl = await getThumbnailCached(
481
736
  ((_a = element == null ? void 0 : element.props) == null ? void 0 : _a.src) || "",
482
737
  snapTime
483
738
  );