All files / src/desktop Capture.ts

100% Statements 19/19
100% Branches 17/17
100% Functions 3/3
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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          1x       6x   6x   6x 6x   6x         3x 4x 4x 4x 4x 3x 4x    
import { invoke } from '@tauri-apps/api/core';
import { getCurrentWindow } from '@tauri-apps/api/window';
import { addShot } from '../lib/Db';
import { copyPng, type Action } from '../platform/Desktop';
 
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
 
/** Captures, saves to History, then opens the editor (or copies). Resolves false if cancelled. */
export async function runCapture(action: Action, delay = 0) {
  const wasVisible = await getCurrentWindow().isVisible();
  // Through Rust, so macOS also drops the Dock icon (otherwise it quits the windowless app).
  if (wasVisible) await invoke('hide_main');
  // Give the window time to fade out so it isn't in the shot.
  if (wasVisible || delay) await sleep(Math.max(delay * 1000, 250));
  const mode = action === 'copy-selection' ? 'selection' : action;
  const info =
    mode === 'screen'
      ? await invoke<{ title: string } | null>('capture_screen')
      : await invoke<{ title: string } | null>('select', {
          kind: mode === 'window' ? 'window' : 'region',
        });
  if (!info) return false;
  const png = await invoke<ArrayBuffer>('take_capture');
  const blob = new Blob([png], { type: 'image/png' });
  const id = await addShot(blob, { title: info.title, url: '', mode });
  if (action === 'copy-selection') await copyPng(blob);
  else await invoke('open_editor', { id });
  return true;
}