Bin
2025-12-16 9e0b2ba2c317b1a86212f24cbae3195ad1f3dbfa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
import TriggerOptions = Cypress.TriggerOptions;
import ObjectLike = Cypress.ObjectLike;
import ClickOptions = Cypress.ClickOptions;
import { withMedia } from "@humansignal/frontend-test/helpers/utils/media/MediaMixin";
import { LabelStudio } from "@humansignal/frontend-test/helpers/LSF/LabelStudio";
import type { ViewWithMedia } from "@humansignal/frontend-test/helpers/utils/media/types";
 
type MouseInteractionOptions = Partial<TriggerOptions & ObjectLike & MouseEvent>;
 
class AudioViewHelper extends withMedia(
  class implements ViewWithMedia {
    get _baseRootSelector() {
      return ".lsf-audio-tag";
    }
 
    _rootSelector: string;
 
    constructor(rootSelector: string) {
      this._rootSelector = rootSelector.replace(/^\&/, this._baseRootSelector);
    }
 
    get root() {
      return cy.get(this._rootSelector);
    }
 
    get errorContainer() {
      return this.root.find('[data-testid^="error:"]', { timeout: 30000 });
    }
 
    get drawingArea() {
      return this.root.find("canvas");
    }
 
    get visualizer() {
      return this.drawingArea.parent();
    }
 
    get container() {
      return this.visualizer.parent();
    }
 
    get timelineControls() {
      return this.root.find(".lsf-timeline-controls");
    }
 
    get currentTimebox() {
      return this.timelineControls.find('[data-testid="timebox-current-time"] > .lsf-time-box__input-time');
    }
 
    get endTimebox() {
      return this.timelineControls.find('[data-testid="timebox-end-time"] > .lsf-time-box__input-time');
    }
 
    get configButton() {
      return this.timelineControls.find(".lsf-audio-config > [aria-label='Audio settings']");
    }
    get volumeButton() {
      return this.timelineControls.find(".lsf-audio-control > .lsf-button");
    }
 
    get loadingBar() {
      return this.root.get("loading-progress-bar", { timeout: 10000 });
    }
 
    get audioElement() {
      return this.root.get('[data-testid="waveform-audio"]');
    }
 
    get mediaElement() {
      return this.audioElement.should("exist");
    }
 
    get volumeSlider() {
      return this.root.find(".lsf-audio-slider__range");
    }
 
    get volumeInput() {
      return this.root.find(".lsf-audio-slider__input");
    }
 
    get muteButton() {
      return this.root.find(".lsf-audio-control__mute-button");
    }
 
    get playbackSpeedSlider() {
      return cy.get(
        ".lsf-audio-config__modal > .lsf-audio-config__scroll-content > .lsf-audio-slider:nth-child(2) .lsf-audio-slider__range",
      );
    }
 
    get playbackSpeedInput() {
      return cy.get(
        ".lsf-audio-config__modal > .lsf-audio-config__scroll-content > .lsf-audio-slider:nth-child(2) .lsf-audio-slider__input",
      );
    }
 
    get amplitudeSlider() {
      return cy.get(
        ".lsf-audio-config__modal > .lsf-audio-config__scroll-content > .lsf-audio-slider:nth-child(3) .lsf-audio-slider__range",
      );
    }
 
    get amplitudeInput() {
      return cy.get(
        ".lsf-audio-config__modal > .lsf-audio-config__scroll-content > .lsf-audio-slider:nth-child(3) .lsf-audio-slider__input",
      );
    }
 
    get hideTimelineButton() {
      return this.root.get(".lsf-audio-config__buttons > .lsf-audio-config__menu-button:nth-child(1)");
    }
 
    get hideWaveformButton() {
      return this.root.get(".lsf-audio-config__buttons > .lsf-audio-config__menu-button:nth-child(2)");
    }
 
    isReady() {
      LabelStudio.waitForObjectsReady();
      this.loadingBar.should("not.exist");
      /**
       * Enhanced audio ready state checking with canvas stabilization
       * Replaces the previous fixed 32ms wait with actual canvas rendering verification
       * This ensures the canvas is fully rendered before proceeding with tests
       */
      this.waitForCanvasStable();
    }
 
    _playButtonSelector = '[data-testid="playback-button:play"]';
    get playButton() {
      return this.root.find(this._playButtonSelector);
    }
 
    _pauseButtonSelector = '[data-testid="playback-button:pause"]';
    get pauseButton() {
      return this.root.find(this._pauseButtonSelector);
    }
 
    seekCurrentTimebox(to: number) {
      let timeString = "";
      timeString = `${to.toString().padStart(6, "0")}000`;
 
      this.currentTimebox.click({ force: true }).clear().type(timeString, { force: true }).blur();
    }
 
    pause() {
      this.pauseButton.click();
    }
 
    play(from?: number, to?: number) {
      if (from) {
        this.seekCurrentTimebox(from);
      }
      this.playButton.click();
      if (to) {
        cy.wait((to - (from || 0)) * 1000);
        this.pause();
      }
    }
 
    toggleControlsMenu() {
      this.volumeButton.click();
      cy.wait(100);
    }
 
    toggleSettingsMenu() {
      this.configButton.click();
      cy.wait(100);
    }
 
    setVolumeInput(value: number) {
      this.toggleControlsMenu();
      this.volumeInput.clear().type(value.toString());
      this.volumeInput.should("have.value", value.toString());
      this.toggleControlsMenu();
    }
 
    setPlaybackSpeedInput(value: number, checkVideo = true) {
      cy.log(`🎵 Setting playback speed to ${value}x`);
      this.toggleSettingsMenu();
      this.playbackSpeedInput.dblclick().clear().type(value.toString());
      this.playbackSpeedInput.should("have.value", value.toString());
      this.toggleSettingsMenu();
 
      // Wait for the speed change to propagate to audio/video elements
      this.waitForPlaybackRate(value, 8000, checkVideo);
      cy.log(`✅ Playback speed set to ${value}x`);
    }
 
    setAmplitudeInput(value: number) {
      this.toggleSettingsMenu();
      this.amplitudeInput.clear().type(value.toString());
      this.amplitudeInput.should("have.value", value.toString());
      this.toggleSettingsMenu();
    }
 
    clickMuteButton() {
      this.toggleControlsMenu();
      this.muteButton.click();
      this.toggleControlsMenu();
    }
 
    /**
     * Clicks at the coordinates on the drawing area
     * @param {number} x
     * @param {number} y
     */
    clickAt(x: number, y: number, options?: Partial<ClickOptions>) {
      cy.log(`Click at the AudioView at (${x}, ${y})`);
      this.drawingArea.scrollIntoView().click(x, y, options);
    }
 
    /**
     * Clicks at the relative coordinates on the drawing area
     * @param {number} x
     * @param {number} y
     */
    clickAtRelative(x: number, y = 0.5, options?: Partial<ClickOptions>) {
      this.drawingArea.then((el) => {
        const bbox: DOMRect = el[0].getBoundingClientRect();
        const realX = x * bbox.width;
        const realY = y * bbox.height;
 
        this.clickAt(realX, realY, options);
      });
    }
 
    hoverAt(x: number, y: number, options: MouseInteractionOptions = {}) {
      cy.log(`Hover at the AudioView at (${x}, ${y})`);
      this.drawingArea.scrollIntoView().trigger("mousemove", x, y, options);
    }
 
    hoverAtRelative(x: number, y: number, options: MouseInteractionOptions = {}) {
      this.drawingArea.then((el) => {
        const bbox: DOMRect = el[0].getBoundingClientRect();
        const realX = x * bbox.width;
        const realY = y * bbox.height;
 
        this.hoverAt(realX, realY, options);
      });
    }
 
    /**
     * Draws a rectangle on the drawing area.
     * It also could be used for some drag and drop interactions for example selecting area or moving existing regions.
     * @param {number} x
     * @param {number} y
     * @param {number} width
     * @param {number} height
     */
    drawRect(x: number, y: number, width: number, height: number, options: MouseInteractionOptions = {}) {
      cy.log(`Draw rectangle at (${x}, ${y}) of size ${width}x${height}`);
      this.drawingArea
        .scrollIntoView()
        .trigger("mousemove", x, y, {
          eventConstructor: "MouseEvent",
          buttons: 1,
          ...options,
        })
        .trigger("mousedown", x, y, {
          eventConstructor: "MouseEvent",
          buttons: 1,
          ...options,
        })
        .trigger("mousemove", x + width, y + height, {
          eventConstructor: "MouseEvent",
          buttons: 1,
          ...options,
        })
        .trigger("mouseup", x + width, y + height, {
          eventConstructor: "MouseEvent",
          buttons: 1,
          ...options,
        })
        .wait(0);
    }
 
    /**
     * Draws the rectangle on the drawing area with coordinates and size relative to the drawing area.
     * It also could be used for some drag and drop interactions for example selecting area or moving existing regions.
     * @param {number} x
     * @param {number} y
     * @param {number} width
     * @param {number} height
     */
    drawRectRelative(x: number, y: number, width: number, height: number, options: MouseInteractionOptions = {}) {
      this.drawingArea.then((el) => {
        const bbox: DOMRect = el[0].getBoundingClientRect();
        const realX = x * bbox.width;
        const realY = y * bbox.height;
        const realWidth = width * bbox.width;
        const realHeight = height * bbox.height;
 
        this.drawRect(realX, realY, realWidth, realHeight, options);
      });
    }
 
    /**
     * Matches the visual appearance of the entire AudioView component
     */
    toMatchImageSnapshot(el?: Cypress.Chainable<JQuery<HTMLElement>>, options?: { name?: string; threshold?: number }) {
      el = el || this.root;
      let name;
      if (options && options.name) {
        name = options.name;
        delete options.name;
      }
      if (name) {
        el.wait(0).matchImageSnapshot(name);
      } else {
        el.wait(0).matchImageSnapshot();
      }
    }
 
    getPixelColor(x: number, y: number) {
      this.drawingArea.trigger("getPixelColor", x, y);
      return this.drawingArea.then(async (canvas) => {
        const ctx = canvas[0].getContext("2d");
        const pixelRatio = window.devicePixelRatio;
 
        // Ensure coordinates are within canvas bounds
        const canvasEl = canvas[0] as HTMLCanvasElement;
        const adjustedX = Math.max(0, Math.min(Math.round(x) * pixelRatio, canvasEl.width - 1));
        const adjustedY = Math.max(0, Math.min(Math.round(y) * pixelRatio, canvasEl.height - 1));
 
        const pixel = ctx.getImageData(adjustedX, adjustedY, 1, 1);
 
        const displayColor = `rgba(${pixel.data[0]}, ${pixel.data[1]}, ${pixel.data[2]}, ${pixel.data[3]})`;
        cy.log(
          `🎨 Pixel at (${x}, ${y}) -> canvas(${adjustedX}, ${adjustedY}): ${displayColor} | Canvas: ${canvasEl.width}x${canvasEl.height} | Ratio: ${pixelRatio}`,
        );
 
        // Log warning if we get transparent pixels
        if (pixel.data[0] === 0 && pixel.data[1] === 0 && pixel.data[2] === 0 && pixel.data[3] === 0) {
          cy.log(`⚠️ WARNING: Transparent pixel detected at (${x}, ${y}) - canvas may not be ready`);
        }
 
        return await pixel.data;
      });
    }
 
    getPixelColorRelative(x: number, y: number) {
      return this.drawingArea.then((el) => {
        const bbox: DOMRect = el[0].getBoundingClientRect();
        const realX = x * bbox.width;
        const realY = y * bbox.height;
 
        return this.getPixelColor(realX, realY);
      });
    }
 
    /**
     * Gets pixel color with retry logic for more stable color sampling
     * @param x relative x coordinate (0-1)
     * @param y relative y coordinate (0-1)
     * @param retries number of retries if colors are inconsistent
     */
    getStablePixelColorRelative(x: number, y: number, retries = 3) {
      let attempts = 0;
      let lastColor: Uint8ClampedArray | null = null;
 
      const sampleColor = () => {
        return this.getPixelColorRelative(x, y).then((color) => {
          attempts++;
 
          // If we have a previous color, check if they match
          if (lastColor && this.colorsEqual(lastColor, color)) {
            return color;
          }
 
          lastColor = color;
 
          // If we haven't reached max retries, wait and try again
          if (attempts < retries) {
            cy.wait(16); // Wait one frame
            return sampleColor();
          }
 
          // Return the last sampled color
          return color;
        });
      };
 
      return sampleColor();
    }
 
    /**
     * Compares two color arrays for equality
     * @param color1 first color array
     * @param color2 second color array
     */
    colorsEqual(color1: Uint8ClampedArray, color2: Uint8ClampedArray): boolean {
      if (color1.length !== color2.length) return false;
      for (let i = 0; i < color1.length; i++) {
        if (color1[i] !== color2[i]) return false;
      }
      return true;
    }
 
    /**
     * Wait a couple of animation frames based on the requestAnimationFrame pattern
     */
    waitForStableState() {
      // This ensures React has completed its render cycle
      cy.waitForFrames(2);
    }
 
    /**
     * Waits for canvas rendering to stabilize by checking that pixel colors remain consistent
     * @param x relative x coordinate to monitor
     * @param y relative y coordinate to monitor
     * @param stabilityChecks number of consecutive stable checks required
     * @param timeout maximum time to wait in milliseconds
     */
    waitForCanvasStable(x = 0.36, y = 0.9, stabilityChecks = 3, timeout = 10000) {
      let stableCount = 0;
      let lastColor: Uint8ClampedArray | null = null;
      const startTime = Date.now();
 
      const checkStability = (): Cypress.Chainable => {
        if (Date.now() - startTime > timeout) {
          cy.log(`⏰ Canvas stabilization timeout after ${timeout}ms`);
          return cy.wrap(null);
        }
 
        return this.getPixelColorRelative(x, y).then((currentColor) => {
          // Check if we're getting transparent pixels (indicates canvas not ready)
          const isTransparent =
            currentColor[0] === 0 && currentColor[1] === 0 && currentColor[2] === 0 && currentColor[3] === 0;
 
          if (isTransparent) {
            cy.log("🔍 Canvas not ready - transparent pixel detected, continuing to wait...");
            stableCount = 0;
            lastColor = null;
            cy.wait(100); // Wait longer for CI environments
            return checkStability();
          }
 
          if (lastColor && this.colorsEqual(lastColor, currentColor)) {
            stableCount++;
            cy.log(`✅ Canvas stable check ${stableCount}/${stabilityChecks}`);
            if (stableCount >= stabilityChecks) {
              cy.log(`🎯 Canvas stabilized after ${stableCount} consecutive checks`);
              return cy.wrap(null);
            }
          } else {
            stableCount = 0;
            cy.log("🔄 Canvas changed, resetting stability counter");
          }
 
          lastColor = currentColor;
          cy.wait(16); // Wait one frame
          return checkStability();
        });
      };
 
      cy.log(`🏁 Starting canvas stabilization check at (${x}, ${y})`);
      return checkStability();
    }
 
    /**
     * Waits for canvas to have actual content (non-transparent pixels)
     * @param timeout maximum time to wait in milliseconds
     */
    waitForCanvasContent(timeout = 15000) {
      const startTime = Date.now();
 
      const checkForContent = (): Cypress.Chainable => {
        if (Date.now() - startTime > timeout) {
          cy.log(`⏰ Canvas content timeout after ${timeout}ms`);
          return cy.wrap(null);
        }
 
        return this.drawingArea.then((canvas) => {
          const ctx = (canvas[0] as HTMLCanvasElement).getContext("2d");
          const canvasEl = canvas[0] as HTMLCanvasElement;
 
          // Sample multiple points to check for content
          const samplePoints = [
            { x: canvasEl.width * 0.25, y: canvasEl.height * 0.5 },
            { x: canvasEl.width * 0.5, y: canvasEl.height * 0.5 },
            { x: canvasEl.width * 0.75, y: canvasEl.height * 0.5 },
          ];
 
          let hasContent = false;
          for (const point of samplePoints) {
            const pixel = ctx.getImageData(Math.floor(point.x), Math.floor(point.y), 1, 1);
            // Check if pixel has any non-transparent content
            if (pixel.data[3] > 0 || pixel.data[0] > 0 || pixel.data[1] > 0 || pixel.data[2] > 0) {
              hasContent = true;
              break;
            }
          }
 
          if (hasContent) {
            cy.log("🎨 Canvas has content!");
            return cy.wrap(null);
          }
          cy.log("🔍 Canvas empty, waiting for content...");
          cy.wait(200); // Increased wait for CI environments
          return checkForContent();
        });
      };
 
      cy.log("🏁 Waiting for canvas content...");
      return checkForContent();
    }
 
    /**
     * Waits for audio and video elements to be synchronized
     * @param tolerance tolerance for time/rate differences
     * @param timeout maximum time to wait
     * @param checkVideo whether to check video sync (default: true)
     */
    waitForMediaSync(tolerance = 0.01, timeout = 5000, checkVideo = true) {
      const startTime = Date.now();
 
      const checkSync = (): Cypress.Chainable => {
        if (Date.now() - startTime > timeout) {
          cy.log(`⏰ Media sync timeout after ${timeout}ms`);
          return cy.wrap(null);
        }
 
        if (checkVideo) {
          // Audio+Video mode: Must sync both elements
          return cy.get("audio").then(([audio]) => {
            return cy.get("video").then(([video]) => {
              const timeDiff = Math.abs(audio.currentTime - video.currentTime);
              const rateDiff = Math.abs(audio.playbackRate - video.playbackRate);
 
              if (timeDiff <= tolerance && rateDiff <= tolerance) {
                cy.log(`🎯 Media sync achieved! Time diff: ${timeDiff.toFixed(3)}s, Rate diff: ${rateDiff.toFixed(3)}`);
                return cy.wrap(null);
              }
              cy.log(`🔄 Media syncing... Time diff: ${timeDiff.toFixed(3)}s, Rate diff: ${rateDiff.toFixed(3)}`);
              cy.wait(50);
              return checkSync();
            });
          });
        }
        // Audio-only mode - no sync needed
        cy.log("🎯 Audio-only mode - sync achieved!");
        return cy.wrap(null);
      };
 
      cy.log(`🏁 Waiting for ${checkVideo ? "audio/video" : "audio-only"} synchronization...`);
      return checkSync();
    }
 
    /**
     * Waits for audio/video to be in a specific play state
     * @param shouldBePlaying expected play state
     * @param timeout maximum time to wait
     * @param checkVideo whether to check video state (default: true)
     */
    waitForPlayState(shouldBePlaying: boolean, timeout = 8000, checkVideo = true) {
      cy.log(
        `🎵 Waiting for ${checkVideo ? "audio/video" : "audio"} to ${shouldBePlaying ? "start playing" : "be paused"}...`,
      );
 
      return cy
        .get("audio", { timeout })
        .should(([audio]) => {
          expect(audio.paused).to.equal(!shouldBePlaying);
        })
        .then(() => {
          if (checkVideo) {
            return cy.get("video").should(([video]) => {
              expect(video.paused).to.equal(!shouldBePlaying);
            });
          }
          return cy.wrap(null);
        });
    }
 
    /**
     * Waits for audio/video playback rate to reach expected value
     * @param expectedRate expected playback rate
     * @param timeout maximum time to wait
     * @param checkVideo whether to check video rate (default: true)
     */
    waitForPlaybackRate(expectedRate: number, timeout = 8000, checkVideo = true) {
      cy.log(`🎵 Waiting for ${checkVideo ? "audio/video" : "audio"} playback rate to be ${expectedRate}x...`);
 
      return cy
        .get("audio", { timeout })
        .should(([audio]) => {
          expect(audio.playbackRate).to.equal(expectedRate);
        })
        .then(() => {
          if (checkVideo) {
            return cy.get("video").should(([video]) => {
              expect(video.playbackRate).to.equal(expectedRate);
            });
          }
          return cy.wrap(null);
        });
    }
 
    /**
     * Waits for audio/video current time to stabilize (not changing)
     * @param tolerance tolerance for time changes
     * @param stabilityDuration how long to be stable (ms)
     * @param timeout maximum time to wait
     */
    waitForTimeStabilization(tolerance = 0.01, stabilityDuration = 200, timeout = 8000) {
      let lastAudioTime: number | null = null;
      let lastVideoTime: number | null = null;
      let stableStartTime: number | null = null;
 
      const checkStability = (): Cypress.Chainable => {
        return cy.get("audio").then(([audio]) => {
          return cy.get("body").then(($body) => {
            const currentTime = Date.now();
            const audioTimeDiff =
              lastAudioTime !== null ? Math.abs(audio.currentTime - lastAudioTime) : Number.POSITIVE_INFINITY;
 
            if ($body.find("video").length > 0) {
              return cy.get("video").then(([video]) => {
                const videoTimeDiff =
                  lastVideoTime !== null ? Math.abs(video.currentTime - lastVideoTime) : Number.POSITIVE_INFINITY;
 
                if (audioTimeDiff <= tolerance && videoTimeDiff <= tolerance) {
                  if (!stableStartTime) {
                    stableStartTime = currentTime;
                    cy.log("🔄 Media time starting to stabilize...");
                  } else if (currentTime - stableStartTime >= stabilityDuration) {
                    cy.log("✅ Media time stabilized!");
                    return cy.wrap(null);
                  }
                } else {
                  stableStartTime = null;
                }
 
                lastAudioTime = audio.currentTime;
                lastVideoTime = video.currentTime;
 
                if (currentTime - (stableStartTime || currentTime) > timeout) {
                  cy.log("⏰ Time stabilization timeout");
                  return cy.wrap(null);
                }
 
                cy.wait(16); // One frame
                return checkStability();
              });
            }
            // Audio-only mode
            if (audioTimeDiff <= tolerance) {
              if (!stableStartTime) {
                stableStartTime = currentTime;
                cy.log("🔄 Audio time starting to stabilize...");
              } else if (currentTime - stableStartTime >= stabilityDuration) {
                cy.log("✅ Audio time stabilized!");
                return cy.wrap(null);
              }
            } else {
              stableStartTime = null;
            }
 
            lastAudioTime = audio.currentTime;
 
            if (currentTime - (stableStartTime || currentTime) > timeout) {
              cy.log("⏰ Time stabilization timeout");
              return cy.wrap(null);
            }
 
            cy.wait(16); // One frame
            return checkStability();
          });
        });
      };
 
      cy.log("🏁 Waiting for media time to stabilize...");
      return checkStability();
    }
 
    zoomIn({ times = 1, speed = 4 }) {
      cy.log(`Zoom in by ${times} times)`);
      for (let i = 0; i < times; i++) {
        this.visualizer.trigger("wheel", "center", "center", {
          deltaY: -speed,
          ctrlKey: true,
          metaKey: true,
        });
      }
    }
 
    scroll({ times = 1, speed = 4, backward = false }) {
      cy.log(`Scroll by ${times} times)`);
      for (let i = 0; i < times; i++) {
        this.visualizer.trigger("wheel", "center", "center", {
          deltaX: 0,
          deltaY: backward ? -speed : speed,
        });
      }
    }
 
    /**
     * Checks if an error message is displayed in the audio view
     * @param {string} errorText - The error text to check for
     */
    hasError(errorText: string) {
      cy.log(`Checking for error message: "${errorText}"`);
      this.errorContainer.should("exist");
      this.errorContainer.contains(errorText).should("exist");
    }
  },
) {}
 
const AudioView = new AudioViewHelper("&:eq(0)");
const useAudioView = (rootSelector: string) => {
  return new AudioViewHelper(rootSelector);
};
 
export { AudioView, useAudioView };