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