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
import TriggerOptions = Cypress.TriggerOptions;
import ObjectLike = Cypress.ObjectLike;
import ClickOptions = Cypress.ClickOptions;
import { SINGLE_FRAME_TIMEOUT } from "../../../../editor/tests/integration/e2e/utils/constants";
import { withMedia } from "@humansignal/frontend-test/helpers/utils/media/MediaMixin";
import type { ViewWithMedia } from "@humansignal/frontend-test/helpers/utils/media/types";
 
type MouseInteractionOptions = Partial<TriggerOptions & ObjectLike & MouseEvent>;
 
// The width of the frame item on the timeline
const FRAME_WIDTH = 16;
// The height of the area on the timeline reserved to interactions
const FRAME_RESERVED_HEIGHT = 24;
 
class VideoViewHelper extends withMedia(
  class implements ViewWithMedia {
    get _baseRootSelector() {
      return ".lsf-video-segmentation";
    }
 
    _rootSelector: string;
 
    constructor(rootSelector: string) {
      this._rootSelector = rootSelector.replace(/^\&/, this._baseRootSelector);
    }
    get root() {
      cy.log("Get VideoView's root");
      return cy.get(this._rootSelector);
    }
 
    get mediaElement() {
      return this.root.get("video").should("exist");
    }
 
    get drawingArea() {
      cy.log("Get VideoView's drawing area");
      return this.root.get(".konvajs-content");
    }
 
    get videoCanvas() {
      return this.root.get(".lsf-video-canvas");
    }
 
    get framesControl() {
      return this.root.find(".lsf-frames-control");
    }
 
    get timelineContainer() {
      return this.root.get(".lsf-video-segmentation__timeline");
    }
 
    get timelineToolbar() {
      return this.root.get(".lsf-timeline__topbar");
    }
 
    get timeLine() {
      return this.timelineToolbar.find(".lsf-seeker");
    }
    get frameCounter() {
      return this.timelineToolbar.get(".lsf-frames-control");
    }
 
    get frameCounterInput() {
      return this.frameCounter.get("input[type='text']");
    }
 
    get timeLineLabels() {
      return this.root.get(".lsf-timeline-frames__labels-bg");
    }
 
    get timeframesArea() {
      return this.root.get(".lsf-timeline-frames__scroll");
    }
 
    get configButton() {
      return this.timelineToolbar.get('[aria-label="Video settings"]');
    }
 
    get configModal() {
      return this.timelineToolbar.get('[class*="modal--"]');
    }
 
    get loopTimelineRegionToggle() {
      return this.configModal.find('[class*="toggle--"]').find("label");
    }
 
    get loopTimelineRegionCheckbox() {
      return this.configModal.find('[class*="toggle--"] input[type="checkbox"]');
    }
 
    get playButton() {
      return this.timelineToolbar.find('[data-testid="playback-button:play"]');
    }
 
    get pauseButton() {
      return this.timelineToolbar.find('[data-testid="playback-button:pause"]');
    }
 
    clickAtTimeline(x: number, y: number, options?: Partial<ClickOptions>) {
      this.timeLine.scrollIntoView().click(x, y, options);
    }
    clickAtTimelineRelative(x: number, y = 0.5, options?: Partial<ClickOptions>) {
      this.timeLine.then((el) => {
        const bbox: DOMRect = el[0].getBoundingClientRect();
        const realX = x * bbox.width;
        const realY = y * bbox.height;
 
        this.clickAtTimeline(realX, realY, options);
      });
    }
    /**
     * 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 image view 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: number, 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);
      });
    }
 
    /**
     * 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("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 })
        // We need this while the Video tag creates new regions in useEffect hook (it means not immediately)
        // This problem could be solved in VideoRegions component of lsf
        // Without this wait we get absence of a region on screenshots
        .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);
      });
    }
 
    /**
     * Click at visible frame on the timeline
     */
    clickAtFrame(idx, options?: Partial<ClickOptions>) {
      cy.log(`Click at ${idx} on the timeline`);
 
      this.timeLineLabels.then((el) => {
        const bbox: DOMRect = el[0].getBoundingClientRect();
        const pointX = bbox.width + (idx - 0.5) * FRAME_WIDTH;
        const pointY = FRAME_RESERVED_HEIGHT / 2;
 
        this.timeframesArea.scrollIntoView().trigger("mouseover", pointX, pointY).click(pointX, pointY, options);
      });
    }
 
    /**
     * Captures a screenshot of an element to compare later
     * @param {string} name name of the screenshot
     */
    captureCanvas(name: string) {
      return this.drawingArea.captureScreenshot(name, { withHidden: [".lsf-video-canvas"] });
    }
 
    /**
     * Captures a new screenshot and compares it to already taken one
     * Fails if screenshots are identical
     * @param name name of the screenshot
     * @param threshold to compare image. It's a relation between original number of pixels vs changed number of pixels
     */
    canvasShouldChange(name: string, threshold = 0.1) {
      return this.drawingArea.compareScreenshot(name, "shouldChange", { withHidden: [".lsf-video-canvas"], threshold });
    }
 
    /**
     * Captures a new screenshot and compares it to already taken one
     * Fails if screenshots are different
     * @param name name of the screenshot
     * @param threshold to compare image. It's a relation between original number of pixels vs changed number of pixels
     */
    canvasShouldNotChange(name: string, threshold = 0.1) {
      return this.drawingArea.compareScreenshot(name, "shouldNotChange", {
        withHidden: [".lsf-video-canvas"],
        threshold,
      });
    }
 
    /**
     * Captures a screenshot of the video canvas to compare later
     * @param {string} name name of the screenshot
     */
    captureVideoCanvas(name: string) {
      return this.videoCanvas.captureScreenshot(name, { withHidden: [".konvajs-content"] });
    }
 
    /**
     * Captures a new screenshot of the video canvas and compares it to already taken one
     * Fails if screenshots are identical
     * @param name name of the screenshot
     * @param threshold to compare image. It's a relation between original number of pixels vs changed number of pixels
     */
    videoCanvasShouldChange(name: string, threshold = 0.1) {
      return this.videoCanvas.compareScreenshot(name, "shouldChange", { withHidden: [".konvajs-content"], threshold });
    }
 
    /**
     * Captures a new screenshot of the video canvas and compares it to already taken one
     * Fails if screenshots are different
     * @param name name of the screenshot
     * @param threshold to compare image. It's a relation between original number of pixels vs changed number of pixels
     */
    videoCanvasShouldNotChange(name: string, threshold = 0.1) {
      return this.videoCanvas.compareScreenshot(name, "shouldNotChange", {
        withHidden: [".konvajs-content"],
        threshold,
      });
    }
 
    hasCurrentFrame(frameNumber: number) {
      this.framesControl.should("have.string", `${frameNumber.toString()} of `);
    }
 
    toggleConfigModal() {
      cy.log("Toggle video config modal");
      this.configButton.click();
      // Wait for modal animation
      cy.wait(100);
    }
 
    enableLoopTimelineRegion() {
      cy.log("Enable Loop Timeline Region");
      this.loopTimelineRegionCheckbox.then(($checkbox) => {
        if (!$checkbox.prop("checked")) {
          this.loopTimelineRegionToggle.click();
        }
      });
    }
 
    disableLoopTimelineRegion() {
      cy.log("Disable Loop Timeline Region");
      this.loopTimelineRegionCheckbox.then(($checkbox) => {
        if ($checkbox.prop("checked")) {
          this.loopTimelineRegionToggle.click();
        }
      });
    }
 
    setLoopTimelineRegion(enabled: boolean) {
      cy.log(`Set Loop Timeline Region to: ${enabled}`);
      if (enabled) {
        this.enableLoopTimelineRegion();
      } else {
        this.disableLoopTimelineRegion();
      }
    }
 
    // State verification
    isLoopTimelineRegionEnabled() {
      return this.loopTimelineRegionCheckbox.should("be.checked");
    }
 
    isLoopTimelineRegionDisabled() {
      return this.loopTimelineRegionCheckbox.should("not.be.checked");
    }
 
    // Playback controls
    play() {
      cy.log("Start video playback");
      this.playButton.click();
    }
 
    pause() {
      cy.log("Pause video playback");
      this.pauseButton.click();
    }
 
    // Wait for video to be at specific frame
    waitForFrame(frameNumber: number) {
      cy.log(`Wait for video to be at frame ${frameNumber}`);
      // Wait for frame counter to show the expected frame
      this.frameCounter.should("contain.text", `${frameNumber.toString()} of`);
    }
 
    // Get current frame number from timeline controls
    getCurrentFrame() {
      return this.frameCounter.invoke("text").then((text) => Number.parseInt(text.split(" ")[0]));
    }
 
    /**
     * Wait a couple of animation frames based on the requestAnimationFrame pattern
     */
    waitForStableState() {
      // This ensures React has completed its render cycle
      cy.waitForFrames(2);
    }
 
    // Wait for region by index to be passed to Konva Stage
    // Gets region ID from store and checks if it exists in Konva
    waitForRegionInKonvaByIndex(regionIndex: number) {
      cy.log(`Wait for region at index ${regionIndex} to be available in Konva Stage`);
 
      // First get the region ID from store
      cy.window().then((win) => {
        const store = (win as any).Htx || (win as any).store;
        if (!store?.annotationStore?.selected?.regionStore?.regions) {
          cy.log("No regions found in store");
          return;
        }
 
        const regions = store.annotationStore.selected.regionStore.regions;
        if (regionIndex >= regions.length) {
          cy.log(`Region index ${regionIndex} out of bounds (${regions.length} regions)`);
          return;
        }
 
        const region = regions[regionIndex];
        const regionId = region.id;
 
        cy.log(`Found region ID: ${regionId} for index ${regionIndex}`);
 
        // Now wait for this region in Konva
        this.waitForRegionInKonva(regionId);
      });
    }
 
    // Find specific Konva stage by DOM element and check for region
    waitForRegionInKonva(regionId: string) {
      cy.log(`Wait for region ${regionId} to be available in Konva Stage`);
 
      cy.window().then((win) => {
        this.drawingArea.should(($drawingArea) => {
          // Get the specific Konva stage from this DOM element
          const drawingArea = $drawingArea[0];
          const stage = (win as any).Konva?.stages?.find((stage) => stage.content === drawingArea);
 
          if (!stage) {
            throw new Error("Konva stage not found for this canvas");
          }
 
          // Find region in this specific stage
          const elements = stage.find(`#${regionId}`);
          if (!elements || elements.length === 0) {
            throw new Error(`Region ${regionId} not found in Konva Stage`);
          }
        });
      });
    }
 
    // Check that specific region is NOT in Konva Stage
    waitForRegionNotInKonva(regionId: string) {
      cy.log(`Wait for region ${regionId} to be NOT available in Konva Stage`);
 
      cy.window().then((win) => {
        this.drawingArea.should(($drawingArea) => {
          // Get the specific Konva stage from this DOM element
          const drawingArea = $drawingArea[0];
          const stage = (win as any).Konva?.stages?.find((stage) => stage.content === drawingArea);
 
          if (!stage) {
            // No stage means no regions - that's what we want
            return;
          }
 
          // Find region in this specific stage
          const elements = stage.find(`#${regionId}`);
          if (elements && elements.length > 0) {
            throw new Error(`Region ${regionId} should NOT be in Konva Stage but it was found`);
          }
        });
      });
    }
 
    // Check region by index is NOT in Konva Stage
    waitForRegionNotInKonvaByIndex(regionIndex: number) {
      cy.log(`Wait for region at index ${regionIndex} to be NOT available in Konva Stage`);
 
      // First get the region ID from store
      cy.window().then((win) => {
        const store = (win as any).Htx || (win as any).store;
        if (!store?.annotationStore?.selected?.regionStore?.regions) {
          cy.log("No regions found in store - that's expected");
          return;
        }
 
        const regions = store.annotationStore.selected.regionStore.regions;
        if (regionIndex >= regions.length) {
          cy.log(`Region index ${regionIndex} out of bounds (${regions.length} regions) - that's expected`);
          return;
        }
 
        const region = regions[regionIndex];
        const regionId = region.id;
 
        cy.log(`Checking that region ID: ${regionId} for index ${regionIndex} is NOT in Konva`);
 
        // Now check this region is NOT in Konva
        this.waitForRegionNotInKonva(regionId);
      });
    }
 
    setCurrentFrame(frameNumber: number) {
      cy.log(`Set current frame to ${frameNumber}`);
      this.frameCounter.click();
      // select all to replace the current frame number
      this.frameCounterInput.clear();
      this.frameCounterInput.type(`${frameNumber}{enter}`);
    }
 
    verifyPlayingRange(startPositionMax: number, endPosition: number, withoutStopping = false) {
      const checkFrame = (lastFrame, rewind = false, waitTimes = 10) => {
        VideoView.getCurrentFrame().then((frame) => {
          if (withoutStopping ? frame > endPosition : frame === endPosition) {
            // Sequence of frames is the same as expected
            return;
          }
          if (rewind) {
            // If rewinding, we expect to see frames going back
            expect(frame).to.be.lessThan(lastFrame);
          } else {
            if (frame === lastFrame && waitTimes--) {
              // If we hit the same frame, wait a bit and check again
              cy.wait(SINGLE_FRAME_TIMEOUT);
              checkFrame(lastFrame, rewind, waitTimes);
              return;
            }
            expect(frame).to.be.greaterThan(lastFrame);
          }
          cy.wait(SINGLE_FRAME_TIMEOUT);
          checkFrame(frame);
        });
      };
      checkFrame(startPositionMax, true);
    }
  },
) {}
 
const VideoView = new VideoViewHelper("&:eq(0)");
const useVideoView = (rootSelector: string) => {
  return new VideoViewHelper(rootSelector);
};
 
export { VideoView, useVideoView };