@twick/video-editor 0.15.0 → 0.15.2

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
@@ -6957,7 +6957,6 @@ const reorderElementsByZIndex = (canvas) => {
6957
6957
  if (!canvas) return;
6958
6958
  const backgroundColor = canvas.backgroundColor;
6959
6959
  const objects = canvas.getObjects();
6960
- console.log("objects", objects);
6961
6960
  objects.sort((a2, b2) => (a2.zIndex || 0) - (b2.zIndex || 0));
6962
6961
  canvas.clear();
6963
6962
  canvas.backgroundColor = backgroundColor;
@@ -7042,15 +7041,133 @@ const rotateControl = new ai({
7042
7041
  /** Whether to show connection line */
7043
7042
  withConnection: true
7044
7043
  });
7045
- const getThumbnail = async (videoUrl, seekTime = 0.1, playbackRate = 1) => {
7046
- return new Promise((resolve, reject) => {
7044
+ class LRUCache {
7045
+ constructor(maxSize = 100) {
7046
+ if (maxSize <= 0) {
7047
+ throw new Error("maxSize must be greater than 0");
7048
+ }
7049
+ this.maxSize = maxSize;
7050
+ this.cache = /* @__PURE__ */ new Map();
7051
+ }
7052
+ /**
7053
+ * Get a value from the cache.
7054
+ * Moves the item to the end (most recently used).
7055
+ */
7056
+ get(key) {
7057
+ const value = this.cache.get(key);
7058
+ if (value === void 0) {
7059
+ return void 0;
7060
+ }
7061
+ this.cache.delete(key);
7062
+ this.cache.set(key, value);
7063
+ return value;
7064
+ }
7065
+ /**
7066
+ * Set a value in the cache.
7067
+ * If cache is full, removes the least recently used item.
7068
+ */
7069
+ set(key, value) {
7070
+ if (this.cache.has(key)) {
7071
+ this.cache.delete(key);
7072
+ } else if (this.cache.size >= this.maxSize) {
7073
+ const firstKey = this.cache.keys().next().value;
7074
+ if (firstKey !== void 0) {
7075
+ this.cache.delete(firstKey);
7076
+ }
7077
+ }
7078
+ this.cache.set(key, value);
7079
+ }
7080
+ /**
7081
+ * Check if a key exists in the cache.
7082
+ */
7083
+ has(key) {
7084
+ return this.cache.has(key);
7085
+ }
7086
+ /**
7087
+ * Delete a key from the cache.
7088
+ */
7089
+ delete(key) {
7090
+ return this.cache.delete(key);
7091
+ }
7092
+ /**
7093
+ * Clear all entries from the cache.
7094
+ */
7095
+ clear() {
7096
+ this.cache.clear();
7097
+ }
7098
+ /**
7099
+ * Get the current size of the cache.
7100
+ */
7101
+ get size() {
7102
+ return this.cache.size;
7103
+ }
7104
+ }
7105
+ class VideoFrameExtractor {
7106
+ constructor(options = {}) {
7107
+ this.frameCache = new LRUCache(
7108
+ options.maxCacheSize ?? 50
7109
+ );
7110
+ this.videoElements = /* @__PURE__ */ new Map();
7111
+ this.maxVideoElements = options.maxVideoElements ?? 5;
7112
+ this.loadTimeout = options.loadTimeout ?? 15e3;
7113
+ this.jpegQuality = options.jpegQuality ?? 0.8;
7114
+ this.playbackRate = options.playbackRate ?? 1;
7115
+ }
7116
+ /**
7117
+ * Get a frame thumbnail from a video at a specific time.
7118
+ * Uses caching and reuses video elements for optimal performance.
7119
+ *
7120
+ * @param videoUrl - The URL of the video
7121
+ * @param seekTime - The time in seconds to extract the frame
7122
+ * @returns Promise resolving to a thumbnail image URL (data URL or blob URL)
7123
+ */
7124
+ async getFrame(videoUrl, seekTime = 0.1) {
7125
+ const cacheKey = this.getCacheKey(videoUrl, seekTime);
7126
+ const cached = this.frameCache.get(cacheKey);
7127
+ if (cached) {
7128
+ return cached;
7129
+ }
7130
+ const videoState = await this.getVideoElement(videoUrl);
7131
+ const thumbnail = await this.extractFrame(videoState.video, seekTime);
7132
+ this.frameCache.set(cacheKey, thumbnail);
7133
+ return thumbnail;
7134
+ }
7135
+ /**
7136
+ * Get or create a video element for the given URL.
7137
+ * Reuses existing elements and manages cleanup.
7138
+ */
7139
+ async getVideoElement(videoUrl) {
7140
+ let videoState = this.videoElements.get(videoUrl);
7141
+ if (videoState && videoState.isReady) {
7142
+ videoState.lastUsed = Date.now();
7143
+ return videoState;
7144
+ }
7145
+ if (videoState && videoState.isLoading && videoState.loadPromise) {
7146
+ await videoState.loadPromise;
7147
+ if (videoState.isReady) {
7148
+ videoState.lastUsed = Date.now();
7149
+ return videoState;
7150
+ }
7151
+ }
7152
+ if (this.videoElements.size >= this.maxVideoElements) {
7153
+ this.cleanupOldVideoElements();
7154
+ }
7155
+ videoState = await this.createVideoElement(videoUrl);
7156
+ this.videoElements.set(videoUrl, videoState);
7157
+ videoState.lastUsed = Date.now();
7158
+ return videoState;
7159
+ }
7160
+ /**
7161
+ * Create and initialize a new video element.
7162
+ */
7163
+ async createVideoElement(videoUrl) {
7047
7164
  const video = document.createElement("video");
7048
7165
  video.crossOrigin = "anonymous";
7049
7166
  video.muted = true;
7050
7167
  video.playsInline = true;
7051
7168
  video.autoplay = false;
7052
7169
  video.preload = "auto";
7053
- video.playbackRate = playbackRate;
7170
+ video.playbackRate = this.playbackRate;
7054
7171
  video.style.position = "absolute";
7055
7172
  video.style.left = "-9999px";
7056
7173
  video.style.top = "-9999px";
@@ -7059,55 +7176,128 @@ const getThumbnail = async (videoUrl, seekTime = 0.1, playbackRate = 1) => {
7059
7176
  video.style.opacity = "0";
7060
7177
  video.style.pointerEvents = "none";
7061
7178
  video.style.zIndex = "-1";
7062
- let timeoutId;
7063
- const cleanup = () => {
7064
- if (video.parentNode) video.remove();
7065
- if (timeoutId) clearTimeout(timeoutId);
7066
- };
7067
- const handleError = () => {
7068
- var _a;
7069
- cleanup();
7070
- reject(new Error(`Failed to load video: ${((_a = video.error) == null ? void 0 : _a.message) || "Unknown error"}`));
7179
+ const state = {
7180
+ video,
7181
+ isReady: false,
7182
+ isLoading: true,
7183
+ loadPromise: null,
7184
+ lastUsed: Date.now()
7071
7185
  };
7072
- const handleSeeked = () => {
7073
- try {
7074
- video.pause();
7075
- const canvas = document.createElement("canvas");
7076
- const width = video.videoWidth || 640;
7077
- const height = video.videoHeight || 360;
7078
- canvas.width = width;
7079
- canvas.height = height;
7080
- const ctx = canvas.getContext("2d");
7081
- if (!ctx) {
7082
- cleanup();
7083
- reject(new Error("Failed to get canvas context"));
7186
+ state.loadPromise = new Promise((resolve, reject) => {
7187
+ let timeoutId;
7188
+ const cleanup = () => {
7189
+ if (timeoutId) clearTimeout(timeoutId);
7190
+ };
7191
+ const handleError = () => {
7192
+ var _a;
7193
+ cleanup();
7194
+ state.isLoading = false;
7195
+ reject(new Error(`Failed to load video: ${((_a = video.error) == null ? void 0 : _a.message) || "Unknown error"}`));
7196
+ };
7197
+ const handleLoadedMetadata = () => {
7198
+ cleanup();
7199
+ state.isReady = true;
7200
+ state.isLoading = false;
7201
+ resolve();
7202
+ };
7203
+ video.addEventListener("error", handleError, { once: true });
7204
+ video.addEventListener("loadedmetadata", handleLoadedMetadata, { once: true });
7205
+ timeoutId = window.setTimeout(() => {
7206
+ cleanup();
7207
+ state.isLoading = false;
7208
+ reject(new Error("Video loading timed out"));
7209
+ }, this.loadTimeout);
7210
+ video.src = videoUrl;
7211
+ document.body.appendChild(video);
7212
+ });
7213
+ try {
7214
+ await state.loadPromise;
7215
+ } catch (error) {
7216
+ if (video.parentNode) {
7217
+ video.remove();
7218
+ }
7219
+ throw error;
7220
+ }
7221
+ return state;
7222
+ }
7223
+ /**
7224
+ * Extract a frame from a video at the specified time.
7225
+ */
7226
+ async extractFrame(video, seekTime) {
7227
+ return new Promise((resolve, reject) => {
7228
+ video.pause();
7229
+ const timeThreshold = 0.1;
7230
+ if (Math.abs(video.currentTime - seekTime) < timeThreshold) {
7231
+ try {
7232
+ const canvas = document.createElement("canvas");
7233
+ const width = video.videoWidth || 640;
7234
+ const height = video.videoHeight || 360;
7235
+ canvas.width = width;
7236
+ canvas.height = height;
7237
+ const ctx = canvas.getContext("2d");
7238
+ if (!ctx) {
7239
+ reject(new Error("Failed to get canvas context"));
7240
+ return;
7241
+ }
7242
+ ctx.drawImage(video, 0, 0, width, height);
7243
+ try {
7244
+ const dataUrl = canvas.toDataURL("image/jpeg", this.jpegQuality);
7245
+ resolve(dataUrl);
7246
+ } catch {
7247
+ canvas.toBlob(
7248
+ (blob) => {
7249
+ if (!blob) {
7250
+ reject(new Error("Failed to create Blob"));
7251
+ return;
7252
+ }
7253
+ const blobUrl = URL.createObjectURL(blob);
7254
+ resolve(blobUrl);
7255
+ },
7256
+ "image/jpeg",
7257
+ this.jpegQuality
7258
+ );
7259
+ }
7260
+ return;
7261
+ } catch (err) {
7262
+ reject(new Error(`Error creating thumbnail: ${err}`));
7084
7263
  return;
7085
7264
  }
7086
- ctx.drawImage(video, 0, 0, width, height);
7265
+ }
7266
+ const handleSeeked = () => {
7087
7267
  try {
7088
- const dataUrl = canvas.toDataURL("image/jpeg", 0.8);
7089
- cleanup();
7090
- resolve(dataUrl);
7091
- } catch {
7092
- canvas.toBlob((blob) => {
7093
- if (!blob) {
7094
- cleanup();
7095
- reject(new Error("Failed to create Blob"));
7096
- return;
7097
- }
7098
- const blobUrl = URL.createObjectURL(blob);
7099
- cleanup();
7100
- resolve(blobUrl);
7101
- }, "image/jpeg", 0.8);
7268
+ const canvas = document.createElement("canvas");
7269
+ const width = video.videoWidth || 640;
7270
+ const height = video.videoHeight || 360;
7271
+ canvas.width = width;
7272
+ canvas.height = height;
7273
+ const ctx = canvas.getContext("2d");
7274
+ if (!ctx) {
7275
+ reject(new Error("Failed to get canvas context"));
7276
+ return;
7277
+ }
7278
+ ctx.drawImage(video, 0, 0, width, height);
7279
+ try {
7280
+ const dataUrl = canvas.toDataURL("image/jpeg", this.jpegQuality);
7281
+ resolve(dataUrl);
7282
+ } catch {
7283
+ canvas.toBlob(
7284
+ (blob) => {
7285
+ if (!blob) {
7286
+ reject(new Error("Failed to create Blob"));
7287
+ return;
7288
+ }
7289
+ const blobUrl = URL.createObjectURL(blob);
7290
+ resolve(blobUrl);
7291
+ },
7292
+ "image/jpeg",
7293
+ this.jpegQuality
7294
+ );
7295
+ }
7296
+ } catch (err) {
7297
+ reject(new Error(`Error creating thumbnail: ${err}`));
7102
7298
  }
7103
- } catch (err) {
7104
- cleanup();
7105
- reject(new Error(`Error creating thumbnail: ${err}`));
7106
- }
7107
- };
7108
- video.addEventListener("error", handleError, { once: true });
7109
- video.addEventListener("seeked", handleSeeked, { once: true });
7110
- video.addEventListener("loadedmetadata", () => {
7299
+ };
7300
+ video.addEventListener("seeked", handleSeeked, { once: true });
7111
7301
  const playPromise = video.play();
7112
7302
  if (playPromise !== void 0) {
7113
7303
  playPromise.then(() => {
@@ -7118,15 +7308,80 @@ const getThumbnail = async (videoUrl, seekTime = 0.1, playbackRate = 1) => {
7118
7308
  } else {
7119
7309
  video.currentTime = seekTime;
7120
7310
  }
7121
- }, { once: true });
7122
- timeoutId = window.setTimeout(() => {
7123
- cleanup();
7124
- reject(new Error("Video loading timed out"));
7125
- }, 15e3);
7126
- video.src = videoUrl;
7127
- document.body.appendChild(video);
7128
- });
7129
- };
7311
+ });
7312
+ }
7313
+ /**
7314
+ * Generate cache key for a video URL and seek time.
7315
+ */
7316
+ getCacheKey(videoUrl, seekTime) {
7317
+ const roundedTime = Math.round(seekTime * 100) / 100;
7318
+ return `${videoUrl}:${roundedTime}`;
7319
+ }
7320
+ /**
7321
+ * Cleanup least recently used video elements.
7322
+ */
7323
+ cleanupOldVideoElements() {
7324
+ if (this.videoElements.size < this.maxVideoElements) {
7325
+ return;
7326
+ }
7327
+ const entries = Array.from(this.videoElements.entries());
7328
+ entries.sort((a2, b2) => a2[1].lastUsed - b2[1].lastUsed);
7329
+ const toRemove = entries.slice(0, entries.length - this.maxVideoElements + 1);
7330
+ for (const [url, state] of toRemove) {
7331
+ if (state.video.parentNode) {
7332
+ state.video.remove();
7333
+ }
7334
+ this.videoElements.delete(url);
7335
+ }
7336
+ }
7337
+ /**
7338
+ * Clear the frame cache.
7339
+ */
7340
+ clearCache() {
7341
+ this.frameCache.clear();
7342
+ }
7343
+ /**
7344
+ * Remove a specific video element and clear its cached frames.
7345
+ */
7346
+ removeVideo(videoUrl) {
7347
+ const state = this.videoElements.get(videoUrl);
7348
+ if (state) {
7349
+ if (state.video.parentNode) {
7350
+ state.video.remove();
7351
+ }
7352
+ this.videoElements.delete(videoUrl);
7353
+ }
7354
+ this.frameCache.clear();
7355
+ }
7356
+ /**
7357
+ * Dispose of all video elements and clear caches.
7358
+ * Removes all video elements from the DOM and clears both the frame cache
7359
+ * and video element cache. Call this when the extractor is no longer needed
7360
+ * to prevent memory leaks.
7361
+ */
7362
+ dispose() {
7363
+ for (const state of this.videoElements.values()) {
7364
+ if (state.video.parentNode) {
7365
+ state.video.remove();
7366
+ }
7367
+ }
7368
+ this.videoElements.clear();
7369
+ this.frameCache.clear();
7370
+ }
7371
+ }
7372
+ let defaultExtractor = null;
7373
+ function getDefaultVideoFrameExtractor(options) {
7374
+ if (!defaultExtractor) {
7375
+ defaultExtractor = new VideoFrameExtractor(options);
7376
+ }
7377
+ return defaultExtractor;
7378
+ }
7379
+ async function getThumbnailCached(videoUrl, seekTime = 0.1, playbackRate) {
7380
+ const extractor = getDefaultVideoFrameExtractor(
7381
+ void 0
7382
+ );
7383
+ return extractor.getFrame(videoUrl, seekTime);
7384
+ }
7130
7385
  const getObjectFitSize = (objectFit, elementSize, containerSize) => {
7131
7386
  const elementAspectRatio = elementSize.width / elementSize.height;
7132
7387
  const containerAspectRatio = containerSize.width / containerSize.height;
@@ -7308,7 +7563,7 @@ const addVideoElement = async ({
7308
7563
  }) => {
7309
7564
  var _a;
7310
7565
  try {
7311
- const thumbnailUrl = await getThumbnail(
7566
+ const thumbnailUrl = await getThumbnailCached(
7312
7567
  ((_a = element == null ? void 0 : element.props) == null ? void 0 : _a.src) || "",
7313
7568
  snapTime
7314
7569
  );
@@ -9509,16 +9764,14 @@ function SeekTrack({
9509
9764
  }) {
9510
9765
  const containerRef = useRef(null);
9511
9766
  const [isDragging2, setIsDragging] = useState(false);
9512
- const [seekPosition, setSeekPosition] = useState(0);
9767
+ const [dragPosition, setDragPosition] = useState(null);
9513
9768
  const pixelsPerSecond = 100 * zoom;
9514
9769
  const totalWidth = duration * pixelsPerSecond;
9515
9770
  const pinHeight = 2 + timelineCount * (2.75 + 0.5);
9516
- useEffect(() => {
9517
- if (!isDragging2) {
9518
- console.log("currentTime", currentTime);
9519
- setSeekPosition(currentTime * pixelsPerSecond);
9520
- }
9521
- }, [currentTime, pixelsPerSecond, isDragging2]);
9771
+ const seekPosition = useMemo(() => {
9772
+ const position = isDragging2 && dragPosition !== null ? dragPosition : currentTime * pixelsPerSecond;
9773
+ return Math.max(0, position);
9774
+ }, [isDragging2, dragPosition, currentTime, pixelsPerSecond]);
9522
9775
  const { majorIntervalSec, minorIntervalSec } = useMemo(() => {
9523
9776
  if (timelineTickConfigs && timelineTickConfigs.length > 0) {
9524
9777
  const sortedConfigs = [...timelineTickConfigs].sort((a2, b2) => a2.durationThreshold - b2.durationThreshold);
@@ -9587,8 +9840,11 @@ function SeekTrack({
9587
9840
  const rect = containerRef.current.getBoundingClientRect();
9588
9841
  const xPos = x2 - rect.left + (containerRef.current.scrollLeft || 0);
9589
9842
  const newTime = Math.max(0, Math.min(duration, xPos / pixelsPerSecond));
9590
- setSeekPosition(xPos);
9843
+ setDragPosition(xPos);
9591
9844
  onSeek(newTime);
9845
+ if (!active) {
9846
+ setDragPosition(null);
9847
+ }
9592
9848
  });
9593
9849
  return /* @__PURE__ */ jsx("div", { className: "twick-seek-track", children: /* @__PURE__ */ jsxs(
9594
9850
  "div",
@@ -9680,10 +9936,12 @@ function SeekTrack({
9680
9936
  className: "twick-seek-track-playhead",
9681
9937
  style: {
9682
9938
  position: "absolute",
9683
- left: seekPosition,
9939
+ left: 0,
9940
+ transform: `translateX(${seekPosition}px)`,
9684
9941
  top: 0,
9685
9942
  touchAction: "none",
9686
- transition: isDragging2 ? "none" : "left 0.1s linear"
9943
+ transition: isDragging2 ? "none" : "transform 0.1s linear",
9944
+ willChange: isDragging2 ? "transform" : "auto"
9687
9945
  },
9688
9946
  children: [
9689
9947
  /* @__PURE__ */ jsx("div", { className: "twick-seek-track-handle" }),