All files / src Popup.tsx

98.9% Statements 90/91
96.92% Branches 63/65
100% Functions 28/28
100% Lines 81/81

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 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                                                1x                                                         1x     5x 5x       51x 51x 51x 51x 51x 51x 51x 51x 30x       51x 17x 2x 2x 2x 2x   17x   17x 17x 17x 17x   17x       14x 12x 1x 1x   12x 4x 14x   14x   17x 17x       3x         1x   17x 17x     17x 49x     17x 17x 17x 17x         8x   2x 2x     2x 2x 1x     1x     7x       7x 6x 6x 6x           6x 8x 3x 3x     51x 11x 11x                                                                                 1x                   1x 1x     40x                   1x                               160x     7x                                                         160x       1x                         1x                                 1x                             1x           3x     1x                                 1x                 1x 1x  
import { useEffect, useMemo, useRef, useState } from 'react';
import { createRoot } from 'react-dom/client';
import {
  listShots,
  type CaptureMode,
  type Progress,
  type Shot,
} from './lib/Db';
import './Styles.css';
import {
  Icon,
  Logo,
  SUPPORT_LABEL,
  SUPPORT_TEXT,
  SUPPORT_URL,
  type IconName,
} from './Ui';
 
const ACTIONS: {
  mode: CaptureMode;
  label: string;
  hint: string;
  icon: IconName;
  command?: string;
}[] = [
  {
    mode: 'visible',
    label: 'Visible area',
    hint: 'What you see now',
    icon: 'visible',
    command: 'capture-visible',
  },
  {
    mode: 'full',
    label: 'Entire page',
    hint: 'Scrolls and stitches',
    icon: 'full',
    command: 'capture-full',
  },
  {
    mode: 'selection',
    label: 'Select area',
    hint: 'Drag a region',
    icon: 'selection',
    command: 'capture-selection',
  },
  {
    mode: 'tabs',
    label: 'All tabs',
    hint: 'Asks for access once',
    icon: 'tabs',
  },
];
const DELAYS = [0, 3, 5, 10];
 
function openPage(url: string) {
  void chrome.tabs.create({ url });
  window.close();
}
 
export function Popup() {
  const [delay, setDelay] = useState(0);
  const [shots, setShots] = useState<Shot[]>([]);
  const [error, setError] = useState<string>();
  const [shortcuts, setShortcuts] = useState<Record<string, string>>({});
  const [progress, setProgress] = useState<Progress | null>(null);
  const errorRef = useRef<string>(undefined);
  const recent = useMemo(() => shots.slice(0, 3), [shots]);
  const thumbs = useMemo(
    () => new Map(recent.map((s) => [s.id, URL.createObjectURL(s.thumb)])),
    [recent],
  );
 
  useEffect(() => {
    const showError = (message: unknown) => {
      errorRef.current = String(message);
      setError(errorRef.current);
      void chrome.storage.session.remove('lastError');
      void chrome.action.setBadgeText({ text: '' });
    };
    void chrome.storage.local
      .get('delay')
      .then((r) => setDelay(Number(r.delay) || 0));
    void chrome.storage.session.get(['lastError', 'progress']).then((r) => {
      if (r.lastError) showError(r.lastError);
      if (r.progress) setProgress(r.progress as Progress);
    });
    const onChanged = (
      changes: Record<string, chrome.storage.StorageChange>,
      area: string,
    ) => {
      if (area !== 'session') return;
      if (changes.lastError?.newValue) {
        showError(changes.lastError.newValue);
        setProgress(null);
      }
      if (!changes.progress) return;
      const next = (changes.progress.newValue as Progress | undefined) ?? null;
      setProgress(next);
      // Finished (or cancelled) without an error: the editor or history tab takes over.
      if (!next && !errorRef.current) window.close();
    };
    chrome.storage.onChanged.addListener(onChanged);
    const onPrepareCopy = (
      message: { type?: string; target?: string },
      sender: chrome.runtime.MessageSender,
    ) => {
      if (
        sender.id === chrome.runtime.id &&
        message?.type === 'prepare-copy' &&
        message.target === 'popup'
      )
        window.close();
    };
    chrome.runtime.onMessage.addListener(onPrepareCopy);
    void chrome.commands
      .getAll()
      .then((cmds) =>
        setShortcuts(
          Object.fromEntries(cmds.map((c) => [c.name ?? '', c.shortcut ?? ''])),
        ),
      );
    void listShots().then(setShots);
    return () => {
      chrome.storage.onChanged.removeListener(onChanged);
      chrome.runtime.onMessage.removeListener(onPrepareCopy);
    };
  }, []);
 
  async function capture(mode: CaptureMode, copySelection = false) {
    if (mode === 'tabs') {
      // Must run synchronously inside the click; Chrome skips the prompt when already granted.
      void chrome.storage.session.set({ pendingAllTabs: true });
      const granted = await chrome.permissions.request({
        origins: ['<all_urls>'],
      });
      void chrome.storage.session.remove('pendingAllTabs');
      if (!granted) {
        setError(
          'Capturing every tab needs access to all sites. Screenshots still never leave your device.',
        );
        return;
      }
    }
    const [tab] = await chrome.tabs.query({
      active: true,
      currentWindow: true,
    });
    if (tab?.id === undefined) return;
    errorRef.current = undefined;
    setError(undefined);
    await chrome.runtime.sendMessage(
      copySelection
        ? { type: 'copy-selection', tabId: tab.id }
        : { type: 'capture', mode, tabId: tab.id, delay },
    );
    // Long captures keep the popup open as a progress dialog; it isn't part of the screenshot.
    const longRunning = mode === 'tabs' || (mode === 'full' && !delay);
    if (!longRunning) window.close();
    else Eif (!errorRef.current)
      setProgress({ mode, value: 0, detail: 'Starting…' });
  }
 
  if (progress) {
    const pct = Math.round(progress.value * 100);
    return (
      <div
        className='popup capture-dialog'
        role='dialog'
        aria-labelledby='capture-title'
        aria-describedby='capture-detail'
      >
        <div className='capture-head'>
          <span className='spinner' aria-hidden='true' />
          <div className='capture-text'>
            <h1 id='capture-title'>
              {progress.mode === 'tabs'
                ? 'Capturing all tabs'
                : progress.mode === 'selection'
                  ? 'Capturing selected area'
                  : 'Capturing entire page'}
            </h1>
            <p id='capture-detail' className='truncate'>
              {progress.detail}
            </p>
          </div>
          <span className='capture-pct'>{pct}%</span>
        </div>
        <div
          className='progress'
          role='progressbar'
          aria-label='Capture progress'
          aria-valuemin={0}
          aria-valuemax={100}
          aria-valuenow={pct}
        >
          <span style={{ width: `${Math.max(pct, 2)}%` }} />
        </div>
        <div className='capture-foot'>
          <span>
            {progress.mode === 'tabs'
              ? 'Chrome switches through your tabs, then returns here.'
              : 'The page scrolls on its own. Keep this tab open.'}
          </span>
          <button
            className='btn ghost'
            onClick={() => void chrome.runtime.sendMessage({ type: 'cancel' })}
          >
            Cancel
          </button>
        </div>
      </div>
    );
  }
 
  function changeDelay(value: number) {
    setDelay(value);
    void chrome.storage.local.set({ delay: value });
  }
 
  return (
    <div className='popup'>
      <header className='popup-head'>
        <Logo size={32} />
        <div className='popup-brand'>
          <h1>Daguerre</h1>
          <p>Capture, annotate, export</p>
        </div>
        <button
          className='icon-btn'
          onClick={() => openPage('history.html')}
          aria-label='Open history'
          title='History'
        >
          <Icon name='history' />
        </button>
      </header>
 
      {error && (
        <p className='alert' role='alert'>
          {error}
        </p>
      )}
 
      <div className='tiles'>
        {ACTIONS.map((a) => (
          <button
            key={a.mode}
            className='tile'
            onClick={() => void capture(a.mode)}
          >
            <span className='tile-icon'>
              <Icon name={a.icon} size={20} />
            </span>
            <span className='tile-label'>{a.label}</span>
            <span className='tile-hint'>
              {a.command && shortcuts[a.command] ? (
                <kbd>{shortcuts[a.command]}</kbd>
              ) : (
                a.hint
              )}
            </span>
          </button>
        ))}
      </div>
 
      <div className='field'>
        <span className='field-label' id='delay-label'>
          <Icon name='timer' size={15} />
          Delay
        </span>
        <div
          className='segmented'
          role='radiogroup'
          aria-labelledby='delay-label'
          aria-describedby='delay-hint'
        >
          {DELAYS.map((d) => (
            <button
              key={d}
              role='radio'
              aria-checked={delay === d}
              onClick={() => changeDelay(d)}
            >
              {d ? `${d}s` : 'Off'}
            </button>
          ))}
        </div>
      </div>
      <p className='field-hint' id='delay-hint'>
        Applies to visible area and entire page, so you can open menus first.
      </p>
 
      <button
        className='btn'
        onClick={() => void capture('selection', true)}
        aria-describedby='copy-selection-hint'
      >
        <Icon name='copy' size={16} />
        Copy selected area
        <span className='spacer' />
        {shortcuts['copy-selection'] && (
          <kbd>{shortcuts['copy-selection']}</kbd>
        )}
      </button>
      <p className='field-hint' id='copy-selection-hint'>
        Copies your selection without opening the editor. Saved in History for
        editing later.
      </p>
 
      <button
        className='btn'
        onClick={() => openPage(SUPPORT_URL)}
        aria-label={SUPPORT_LABEL}
        aria-describedby='support-hint'
      >
        <Icon name='coffee' size={16} />
        Support
      </button>
      <p className='field-hint' id='support-hint'>
        {SUPPORT_TEXT}
      </p>
 
      {recent.length > 0 && (
        <section className='recent' aria-label='Recent screenshots'>
          <div className='recent-head'>
            <span>Recent</span>
            <button className='link' onClick={() => openPage('history.html')}>
              View all {shots.length}
            </button>
          </div>
          <div className='recent-grid'>
            {recent.map((s) => (
              <button
                key={s.id}
                className='recent-item'
                onClick={() => openPage(`editor.html?id=${s.id}`)}
                title={s.title}
              >
                <img src={thumbs.get(s.id)} alt={`Open ${s.title}`} />
              </button>
            ))}
          </div>
        </section>
      )}
 
      <footer className='popup-foot'>
        <span>
          <Icon name='lock' size={13} />
          Stored only on this device
        </span>
        <button
          className='link'
          onClick={() => openPage('chrome://extensions/shortcuts')}
        >
          Shortcuts
        </button>
      </footer>
    </div>
  );
}
 
const root = document.getElementById('root');
Iif (root) createRoot(root).render(<Popup />);