Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

23.3 KB
Raw Blame
import { act } from 'react';
import { createRoot, Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { LayerItem } from '../../types/editor';
import {
  captureResolutionToMaxDim,
  computeMediaRecorderBitrate,
  computeTimelapseDimensions,
  globalTimelapseManager,
  resolveTimelapseTargetSeconds,
  sampleTimelapseFrameIndices,
  TimelapseRecorderManager,
} from '../timelapseEngine';
import {
  computeWatermarkPosition,
  DEFAULT_TIMELAPSE_WATERMARK,
  drawWatermarkOnContext,
  TimelapseWatermarkConfig,
} from '../timelapseWatermark';
import { computeCanvasViewDimensions } from '../timelapseCanvasView';
import { TimelapseExportModal } from '../../components/TimelapseExportModal';

const mockTauriInvoke = vi.fn();
vi.mock('@tauri-apps/api/core', () => ({
  invoke: (...args: unknown[]) => mockTauriInvoke(...args),
}));

const mockNativeStudioTl = vi.hoisted(() => ({
  captureNativeTimelapseFrame: vi.fn(),
  flattenNativeDocument: vi.fn(),
}));

vi.mock('../nativeEngineBridge', async (importOriginal) => {
  const actual = await importOriginal<typeof import('../nativeEngineBridge')>();
  return {
    ...actual,
    isNativeCanvasActive: () => true,
    captureNativeTimelapseFrame: (...args: unknown[]) =>
      mockNativeStudioTl.captureNativeTimelapseFrame(...args),
    flattenNativeDocument: (...args: unknown[]) =>
      mockNativeStudioTl.flattenNativeDocument(...args),
  };
});

function makeBaseLayer(): LayerItem {
  return {
    id: 'layer-1',
    name: 'Lineart',
    type: 'raster',
    visible: true,
    opacity: 1,
    blendMode: 'normal',
    locked: false,
    parentId: null,
  };
}

function makeFakeWebpBytes(tag: number, len = 36): Uint8Array {
  const bytes = new Uint8Array(len);
  bytes[0] = 0x52;
  bytes[1] = 0x49;
  bytes[2] = 0x46;
  bytes[3] = 0x46;
  bytes[8] = 0x57;
  bytes[9] = 0x45;
  bytes[10] = 0x42;
  bytes[11] = 0x50;
  for (let i = 12; i < len; i++) bytes[i] = (tag * 17 + i) & 0xff;
  return bytes;
}

describe('Time-lapse Studio Math: Intervals, FPS, Quality, 4K & Watermark', () => {
  it('computes even dimensions across 720p, 1080p, 2k, 4k and all aspect ratios including 4:5', () => {
    expect(captureResolutionToMaxDim('720p')).toBe(1280);
    expect(captureResolutionToMaxDim('1080p')).toBe(1920);
    expect(captureResolutionToMaxDim('2k')).toBe(2560);
    expect(captureResolutionToMaxDim('4k')).toBe(3840);

    expect(computeTimelapseDimensions(3000, 3000, '16:9', '4k')).toEqual({
      width: 3840,
      height: 2160,
    });
    expect(computeTimelapseDimensions(3000, 3000, '9:16', '2k')).toEqual({
      width: 1440,
      height: 2560,
    });
    expect(computeTimelapseDimensions(2000, 2000, '4:5', '1080p')).toEqual({
      width: 1080,
      height: 1350,
    });
    expect(computeCanvasViewDimensions(1920, 1080, 1280)).toEqual({
      width: 1280,
      height: 720,
    });
  });

  it('samples timeline accurately for 15s, 30s, 60s, 120s, custom, and full at 24/30/60 FPS', () => {
    expect(sampleTimelapseFrameIndices(100, '15s', 24)).toHaveLength(360);
    expect(sampleTimelapseFrameIndices(100, '30s', 30)).toHaveLength(900);
    expect(sampleTimelapseFrameIndices(100, '60s', 60)).toHaveLength(3600);
    expect(sampleTimelapseFrameIndices(100, '120s', 30)).toHaveLength(3600);
    expect(sampleTimelapseFrameIndices(100, 'custom', 30, 42)).toHaveLength(1260);
    expect(resolveTimelapseTargetSeconds(100, 'custom', 30, 42)).toBe(42);
    expect(resolveTimelapseTargetSeconds(100, '120s', 30)).toBe(120);

    // Higher quality and FPS produce strictly higher MediaRecorder bitrates
    const std30 = computeMediaRecorderBitrate('1080p', 30, 'standard');
    const high30 = computeMediaRecorderBitrate('1080p', 30, 'high');
    const ultra60 = computeMediaRecorderBitrate('1080p', 60, 'ultra');
    const max4k = computeMediaRecorderBitrate('4k', 60, 'lossless');
    expect(std30).toBeLessThan(high30);
    expect(high30).toBeLessThan(ultra60);
    expect(ultra60).toBeLessThan(max4k);
  });

  it('computes watermark placement across all anchors and renders text watermark onto Canvas 2D', () => {
    const tl = computeWatermarkPosition(1920, 1080, 200, 50, 'top-left', 3);
    const br = computeWatermarkPosition(1920, 1080, 200, 50, 'bottom-right', 3);
    const center = computeWatermarkPosition(1920, 1080, 200, 50, 'center', 3);

    expect(tl).toEqual({ x: 32, y: 32 });
    expect(br).toEqual({ x: 1920 - 200 - 32, y: 1080 - 50 - 32 });
    expect(center).toEqual({ x: 860, y: 515 });

    const fillText = vi.fn();
    const fill = vi.fn();
    const fakeCtx = {
      save: vi.fn(),
      restore: vi.fn(),
      beginPath: vi.fn(),
      moveTo: vi.fn(),
      lineTo: vi.fn(),
      quadraticCurveTo: vi.fn(),
      closePath: vi.fn(),
      fill,
      fillText,
      measureText: () => ({ width: 120 }),
      font: '',
      textBaseline: '',
      textAlign: '',
      globalAlpha: 1,
      fillStyle: '',
      shadowColor: '',
      shadowBlur: 0,
      shadowOffsetX: 0,
      shadowOffsetY: 0,
    } as unknown as CanvasRenderingContext2D;

    const cfg: TimelapseWatermarkConfig = {
      ...DEFAULT_TIMELAPSE_WATERMARK,
      enabled: true,
      mode: 'text',
      text: '@ArtistName',
      position: 'bottom-right',
    };
    const rect = drawWatermarkOnContext(fakeCtx, 1920, 1080, cfg);
    expect(rect).toBeTruthy();
    expect(fillText).toHaveBeenCalledWith('@ArtistName', expect.any(Number), expect.any(Number), expect.any(Number));
    expect(fill).toHaveBeenCalled();

    // Disabled watermark draws nothing
    expect(drawWatermarkOnContext(fakeCtx, 1920, 1080, { ...cfg, enabled: false })).toBeNull();
  });
});

describe('Time-lapse Capture Area Modes, Deduplication & FFmpeg Export Options', () => {
  afterEach(() => {
    vi.restoreAllMocks();
    vi.unstubAllGlobals();
    mockTauriInvoke.mockReset();
    if (typeof window !== 'undefined') {
      delete (window as unknown as Record<string, unknown>).__TAURI_INTERNALS__;
    }
  });

  it('captures artwork, canvas-view, and native app-window frames and defers during active strokes', async () => {
    mockNativeStudioTl.captureNativeTimelapseFrame.mockReset();
    mockNativeStudioTl.captureNativeTimelapseFrame.mockResolvedValue({
      width: 800,
      height: 600,
      bytes: 4096,
    });
    mockNativeStudioTl.flattenNativeDocument.mockReset();
    mockNativeStudioTl.flattenNativeDocument.mockResolvedValue({
      width: 4,
      height: 4,
      rgba: new Uint8ClampedArray(4 * 4 * 4).fill(255),
    });

    vi.stubGlobal('ImageData', class FakeImageData {
      constructor(
        public data: Uint8ClampedArray,
        public width: number,
        public height: number
      ) {}
    });

    const putImageDataSpy = vi.fn();
    vi.stubGlobal('document', {
      createElement: (tag: string) => {
        if (tag !== 'canvas') return {};
        return {
          width: 0,
          height: 0,
          getContext: () => ({
            save: () => {},
            restore: () => {},
            setTransform: () => {},
            scale: () => {},
            translate: () => {},
            rotate: () => {},
            beginPath: () => {},
            moveTo: () => {},
            lineTo: () => {},
            quadraticCurveTo: () => {},
            closePath: () => {},
            fill: () => {},
            fillText: () => {},
            measureText: () => ({ width: 120 }),
            rect: () => {},
            clip: () => {},
            fillRect: () => {},
            clearRect: () => {},
            drawImage: () => {},
            createImageData: (w: number, h: number) => ({
              width: w,
              height: h,
              data: new Uint8ClampedArray(w * h * 4),
            }),
            putImageData: putImageDataSpy,
            globalAlpha: 1,
            globalCompositeOperation: 'source-over',
          }),
          toBlob: (cb: (b: Blob | null) => void, mime?: string) => {
            cb(new Blob([makeFakeWebpBytes(7) as BlobPart], { type: mime || 'image/webp' }));
          },
        };
      },
    });

    (globalThis as unknown as Record<string, unknown>).window = {
      __TAURI_INTERNALS__: {
        invoke: (...args: unknown[]) => mockTauriInvoke(...args),
      },
    };

    mockTauriInvoke.mockImplementation(async (cmd: string) => {
      if (cmd === 'timelapse_capture_app_window') {
        // Return valid 4x4 packed RGBA frame: [w:u32 LE][h:u32 LE][rgba...]
        const out = new Uint8Array(8 + 4 * 4 * 4);
        const dv = new DataView(out.buffer);
        dv.setUint32(0, 4, true);
        dv.setUint32(4, 4, true);
        out.fill(200, 8);
        return out.buffer;
      }
      if (cmd === 'timelapse_check_ffmpeg') return true;
      if (cmd === 'timelapse_export_ffmpeg') return new Uint8Array([0, 0, 0, 24]).buffer;
      return undefined;
    });

    const layers = [makeBaseLayer()];
    const dims = { width: 800, height: 600, dpi: 300 };

    const mgr = new TimelapseRecorderManager({ minIntervalMs: 0 });
    mgr.setRecording('doc-cap', true, 'Scene');

    // 1. Active stroke deferral: capture skipped immediately while stylus is down
    const deferred = await mgr.captureKeyframe('doc-cap', layers, dims, false, {
      isDrawingActive: () => true,
    });
    expect(deferred).toBe(false);
    expect(mgr.getStats('doc-cap').frameCount).toBe(0);

    // 2. Artwork only capture delegates directly to Rust ink-engine
    expect(await mgr.captureKeyframe('doc-cap', layers, dims, true)).toBe(true);
    expect(mockNativeStudioTl.captureNativeTimelapseFrame).toHaveBeenCalledTimes(1);
    expect(mgr.getFrames('doc-cap')[0].captureArea).toBe('artwork');

    // 3. Canvas view capture with live camera transform
    mgr.setCaptureArea('doc-cap', 'canvas-view');
    const fakeViewport = { clientWidth: 1280, clientHeight: 720 } as HTMLElement;
    expect(
      await mgr.captureKeyframe('doc-cap', layers, dims, true, {
        viewportElement: fakeViewport,
        camera: { pan: { x: 640, y: 360 }, zoom: 1.25, rotation: 15, flipX: false, flipY: false },
      })
    ).toBe(true);
    expect(mgr.getFrames('doc-cap')[1].captureArea).toBe('canvas-view');
    expect(mgr.getFrames('doc-cap')[1].width).toBe(1280);
    expect(mgr.getFrames('doc-cap')[1].height).toBe(720);

    // 4. Native App Window capture calls Rust `timelapse_capture_app_window`
    mgr.setCaptureArea('doc-cap', 'app-window');
    mgr.setCaptureResolution('doc-cap', '4k');
    expect(await mgr.captureKeyframe('doc-cap', layers, dims, true)).toBe(true);
    expect(mockTauriInvoke).toHaveBeenCalledWith('timelapse_capture_app_window', { maxDim: 3840 });
    expect(putImageDataSpy).toHaveBeenCalled();
    expect(mgr.getFrames('doc-cap')[2].captureArea).toBe('app-window');
    expect(mgr.getFrames('doc-cap')[2].width).toBe(4);
    expect(mgr.getFrames('doc-cap')[2].height).toBe(4);

    // 6. Export via FFmpeg passes FPS, quality, blur backdrop, and watermark PNG headers
    const exportRes = await mgr.exportVideo('doc-cap', {
      duration: '15s',
      fps: 60,
      quality: 'ultra',
      resolution: '1080p',
      aspectRatio: '9:16',
      backgroundMode: 'blur',
      backgroundColor: '#141414',
      preferFfmpeg: true,
      watermark: {
        ...DEFAULT_TIMELAPSE_WATERMARK,
        enabled: true,
        mode: 'text',
        text: 'Made in InkStudio',
      },
    });
    expect(exportRes.extension).toBe('.mp4');
    expect(exportRes.frameCount).toBe(900); // 15s @ 60 FPS

    const ffmpegCall = mockTauriInvoke.mock.calls.find((c) => c[0] === 'timelapse_export_ffmpeg');
    expect(ffmpegCall).toBeDefined();
    const ffmpegHeaders = (ffmpegCall![2] as { headers: Record<string, string> }).headers;
    expect(ffmpegHeaders['x-fps']).toBe('60');
    expect(ffmpegHeaders['x-quality']).toBe('ultra');
    expect(ffmpegHeaders['x-bg-blur']).toBe('1');
    expect(ffmpegHeaders['x-width']).toBe('1080');
    expect(ffmpegHeaders['x-height']).toBe('1920');
    expect(Number(ffmpegHeaders['x-watermark-bytes'])).toBeGreaterThan(0);

    await mgr.clearSession('doc-cap');
  });
});

// Minimal DOM harness for rendering TimelapseExportModal UI interactions
interface MiniNode {
  nodeType: number;
  nodeName: string;
  parentNode: MiniElement | null;
  ownerDocument: MiniDocument;
}

class MiniTextNode implements MiniNode {
  public nodeType = 3;
  public nodeName = '#text';
  public parentNode: MiniElement | null = null;
  constructor(public nodeValue: string, public ownerDocument: MiniDocument) {}
}

class MiniCommentNode implements MiniNode {
  public nodeType = 8;
  public nodeName = '#comment';
  public parentNode: MiniElement | null = null;
  constructor(public nodeValue: string, public ownerDocument: MiniDocument) {}
}

class MiniElement extends EventTarget implements MiniNode {
  public nodeType = 1;
  public nodeName: string;
  public tagName: string;
  public namespaceURI = 'http://www.w3.org/1999/xhtml';
  public parentNode: MiniElement | null = null;
  public childNodes: MiniNode[] = [];
  public style: Record<string, string> = {};
  public disabled = false;
  public className = '';
  public isContentEditable = false;
  public value = '';
  public width = 0;
  public height = 0;
  private attrs = new Map<string, string>();

  constructor(tag: string, public ownerDocument: MiniDocument) {
    super();
    this.nodeName = tag.toUpperCase();
    this.tagName = tag.toUpperCase();
  }
  get firstChild(): MiniNode | null {
    return this.childNodes[0] ?? null;
  }
  get textContent(): string {
    return this.childNodes
      .map((n) => (n instanceof MiniTextNode ? n.nodeValue : n instanceof MiniElement ? n.textContent : ''))
      .join('');
  }
  set textContent(val: string) {
    this.childNodes = val ? [new MiniTextNode(val, this.ownerDocument)] : [];
  }
  appendChild<T extends MiniNode>(child: T): T {
    if (child.parentNode) child.parentNode.removeChild(child);
    child.parentNode = this;
    this.childNodes.push(child);
    return child;
  }
  removeChild<T extends MiniNode>(child: T): T {
    const idx = this.childNodes.indexOf(child);
    if (idx >= 0) {
      this.childNodes.splice(idx, 1);
      child.parentNode = null;
    }
    return child;
  }
  insertBefore<T extends MiniNode>(newNode: T, refNode: MiniNode | null): T {
    if (newNode.parentNode) newNode.parentNode.removeChild(newNode);
    newNode.parentNode = this;
    if (!refNode) {
      this.childNodes.push(newNode);
      return newNode;
    }
    const idx = this.childNodes.indexOf(refNode);
    if (idx < 0) this.childNodes.push(newNode);
    else this.childNodes.splice(idx, 0, newNode);
    return newNode;
  }
  setAttribute(k: string, v: string) {
    this.attrs.set(k, String(v));
  }
  getAttribute(k: string): string | null {
    return this.attrs.get(k) ?? null;
  }
  removeAttribute(k: string) {
    this.attrs.delete(k);
  }
  hasAttribute(k: string): boolean {
    return this.attrs.has(k);
  }
  contains(node: unknown): boolean {
    if (node === this) return true;
    for (const c of this.childNodes) {
      if (c === node) return true;
      if (c instanceof MiniElement && c.contains(node)) return true;
    }
    return false;
  }
  getContext() {
    return {
      save: () => {},
      restore: () => {},
      setTransform: () => {},
      fillRect: () => {},
      drawImage: () => {},
      beginPath: () => {},
      moveTo: () => {},
      lineTo: () => {},
      quadraticCurveTo: () => {},
      closePath: () => {},
      fill: () => {},
      fillText: () => {},
      measureText: () => ({ width: 80 }),
      filter: 'none',
      fillStyle: '',
      globalAlpha: 1,
      globalCompositeOperation: 'source-over',
    };
  }
  toBlob(cb: (b: Blob | null) => void, mime?: string) {
    cb(new Blob([makeFakeWebpBytes(99) as BlobPart], { type: mime || 'image/webp' }));
  }
  focus() {}
  blur() {}
}

class MiniDocument extends EventTarget {
  public nodeType = 9;
  public nodeName = '#document';
  public body: MiniElement;
  public documentElement: MiniElement;
  public activeElement: MiniElement | null = null;
  public fullscreenElement: MiniElement | null = null;
  constructor(public defaultView: unknown) {
    super();
    this.documentElement = new MiniElement('html', this);
    this.body = new MiniElement('body', this);
    this.documentElement.appendChild(this.body);
  }
  createElement(tag: string) {
    return new MiniElement(tag, this);
  }
  createElementNS(_ns: string, tag: string) {
    return new MiniElement(tag, this);
  }
  createTextNode(text: string) {
    return new MiniTextNode(text, this);
  }
  createComment(text: string) {
    return new MiniCommentNode(text, this);
  }
}

function findElements(root: MiniElement, pred: (el: MiniElement) => boolean): MiniElement[] {
  const out: MiniElement[] = [];
  const walk = (node: MiniNode) => {
    if (node instanceof MiniElement) {
      if (pred(node)) out.push(node);
      for (const c of node.childNodes) walk(c);
    }
  };
  walk(root);
  return out;
}

function dispatchClick(el: MiniElement) {
  const ev = new Event('click', { bubbles: true, cancelable: true });
  Object.defineProperty(ev, 'target', { value: el, enumerable: true });
  let cur: MiniElement | null = el;
  while (cur) {
    cur.dispatchEvent(ev);
    cur = cur.parentNode;
  }
}

describe('TimelapseExportModal UI: Capture Dropdown, Interval Preview, Full-Screen & Watermark', () => {
  let prevWindow: unknown;
  let prevDocument: unknown;
  let prevAct: unknown;
  let miniWin: EventTarget & Record<string, unknown>;
  let miniDoc: MiniDocument;
  let container: MiniElement;
  let root: Root | null = null;

  beforeEach(() => {
    prevWindow = (globalThis as Record<string, unknown>).window;
    prevDocument = (globalThis as Record<string, unknown>).document;
    prevAct = (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT;

    const baseWinTarget = new EventTarget();
    miniWin = Object.assign(baseWinTarget, {
      addEventListener(
        type: string,
        listener: EventListenerOrEventListenerObject | null,
        options?: boolean | AddEventListenerOptions
      ) {
        const norm = typeof options === 'boolean' ? { capture: options } : options;
        return EventTarget.prototype.addEventListener.call(baseWinTarget, type, listener, norm);
      },
      removeEventListener(
        type: string,
        listener: EventListenerOrEventListenerObject | null,
        options?: boolean | EventListenerOptions
      ) {
        const norm = typeof options === 'boolean' ? { capture: options } : options;
        return EventTarget.prototype.removeEventListener.call(baseWinTarget, type, listener, norm);
      },
      HTMLElement: MiniElement,
      HTMLIFrameElement: class HTMLIFrameElement {},
      Element: MiniElement,
      Node: MiniElement,
      setTimeout: globalThis.setTimeout.bind(globalThis),
      clearTimeout: globalThis.clearTimeout.bind(globalThis),
      setInterval: globalThis.setInterval.bind(globalThis),
      clearInterval: globalThis.clearInterval.bind(globalThis),
    }) as unknown as EventTarget & Record<string, unknown>;
    miniDoc = new MiniDocument(miniWin);
    miniWin.document = miniDoc;

    (globalThis as Record<string, unknown>).window = miniWin;
    (globalThis as Record<string, unknown>).document = miniDoc;
    (globalThis as Record<string, unknown>).HTMLElement = MiniElement;
    (globalThis as Record<string, unknown>).HTMLIFrameElement = miniWin.HTMLIFrameElement;
    (globalThis as Record<string, unknown>).Element = MiniElement;
    (globalThis as Record<string, unknown>).Node = MiniElement;
    (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;

    container = miniDoc.createElement('div');
    miniDoc.body.appendChild(container);
  });

  afterEach(async () => {
    if (root) {
      await act(async () => {
        root!.unmount();
      });
      root = null;
    }
    await globalTimelapseManager.removeSession('ui-doc-1');
    vi.restoreAllMocks();
    (globalThis as Record<string, unknown>).window = prevWindow;
    (globalThis as Record<string, unknown>).document = prevDocument;
    (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = prevAct;
  });

  it('supports switching Capture Area, previewing at 15s/30s/60s, entering/exiting Full-Screen, and enabling Watermark', async () => {
    mockNativeStudioTl.captureNativeTimelapseFrame.mockReset();
    mockNativeStudioTl.captureNativeTimelapseFrame.mockResolvedValue({
      width: 600,
      height: 400,
      bytes: 2048,
    });
    const layers = [makeBaseLayer()];
    const dims = { width: 600, height: 400, dpi: 300 };

    globalTimelapseManager.setRecording('ui-doc-1', true, 'Brainy 10');
    await globalTimelapseManager.captureKeyframe('ui-doc-1', layers, dims, true);
    await globalTimelapseManager.captureKeyframe('ui-doc-1', layers, dims, true);

    const onClose = vi.fn();
    await act(async () => {
      root = createRoot(container as unknown as Element);
      root.render(
        <TimelapseExportModal
          isOpen={true}
          onClose={onClose}
          documentId="ui-doc-1"
          documentName="Brainy 10"
        />
      );
      await Promise.resolve();
      await Promise.resolve();
    });

    // 1. Capture Area dropdown shows Artwork only / Canvas view / App window and updates manager
    const captureTrigger = findElements(
      container,
      (el) => el.tagName === 'BUTTON' && el.textContent.trim() === 'Artwork only'
    )[0];
    expect(captureTrigger).toBeDefined();
    await act(async () => {
      dispatchClick(captureTrigger);
    });
    expect(container.textContent).toContain('Canvas view');
    expect(container.textContent).toContain('App window');

    const canvasViewOption = findElements(
      container,
      (el) => el.getAttribute('role') === 'option' && el.textContent.includes('Canvas view')
    )[0];
    await act(async () => {
      dispatchClick(canvasViewOption);
    });
    expect(globalTimelapseManager.getStats('ui-doc-1').captureArea).toBe('canvas-view');

    // 2. Direct in-app preview interval switching updates total duration readout immediately
    expect(container.textContent).toContain('00:30.0');
    const btn15s = findElements(
      container,
      (el) => el.tagName === 'BUTTON' && el.textContent.trim() === '15s'
    )[0];
    await act(async () => {
      dispatchClick(btn15s);
    });
    expect(container.textContent).toContain('00:15.0');

    // 3. Full-Screen mode opens overlay and Esc exits full-screen WITHOUT closing the modal
    const fsBtn = findElements(
      container,
      (el) => el.getAttribute('aria-label') === 'View in full-screen'
    )[0];
    expect(fsBtn).toBeDefined();
    await act(async () => {
      dispatchClick(fsBtn);
    });
    expect(
      findElements(container, (el) => el.getAttribute('aria-label') === 'Time-lapse Full-screen Preview')
    ).toHaveLength(1);

    await act(async () => {
      const escEv = new Event('keydown', { bubbles: true, cancelable: true }) as KeyboardEvent;
      Object.defineProperty(escEv, 'key', { value: 'Escape' });
      miniWin.dispatchEvent(escEv);
    });
    expect(
      findElements(container, (el) => el.getAttribute('aria-label') === 'Time-lapse Full-screen Preview')
    ).toHaveLength(0);
    expect(onClose).not.toHaveBeenCalled();

    // 4. Watermark tab exposes toggle & text/image modes
    const wmTab = findElements(
      container,
      (el) => el.tagName === 'BUTTON' && el.textContent.trim() === 'Watermark'
    )[0];
    await act(async () => {
      dispatchClick(wmTab);
    });
    expect(container.textContent).toContain('Enable Watermark');
    expect(container.textContent).toContain('Logo / Signature');
  });
});