All files / src History.tsx

99.08% Statements 108/109
98.55% Branches 68/69
100% Functions 42/42
100% Lines 96/96

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 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389                                                        2x     52x 52x 52x 52x 33x 18x                                   72x 72x 72x 72x 72x 72x 72x 72x 72x   72x 17x     17x 16x 17x 17x 17x 17x     72x 27x 27x     72x 17x 17x 1x 17x 17x   17x 17x 17x 17x       72x 44x     72x 44x       72x 47x 47x 59x               72x 47x 47x 52x 52x   47x       9x 3x 3x 3x 3x 3x             2x 2x 2x 2x                     3x 3x 3x 3x 3x     72x 224x   3x 3x         2x 2x 1x   1x         4x 4x 4x     72x                                         3x                   360x       2x                       3x           1x           1x                     4x                                         24x                     112x       112x                                   4x             2x                 1x                 2x                                                                                         3x 1x                   2x 2x  
import {
  CAPTURE_HINT,
  CAPTURE_MODES,
  NO_URL_LABEL,
  SAVE_PNG_LABEL,
  SEARCH_PLACEHOLDER,
  SHORTCUT_HINTS,
} from '@platform';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { createRoot } from 'react-dom/client';
import {
  clearShots,
  deleteShots,
  listShots,
  putShots,
  type CaptureMode,
  type Shot,
} from './lib/Db';
import {
  copyPng,
  downloadBlob,
  fileName,
  formatBytes,
  hostOf,
} from './lib/Export';
import './Styles.css';
import { ConfirmDialog, Icon, Logo, MODE_LABEL, Toast, useToast } from './Ui';
 
const FILTERS: (CaptureMode | 'all')[] = ['all', ...CAPTURE_MODES];
 
function dayLabel(ts: number) {
  const d = new Date(ts);
  const today = new Date().setHours(0, 0, 0, 0);
  const diff = Math.round((today - new Date(ts).setHours(0, 0, 0, 0)) / 864e5);
  if (diff === 0) return 'Today';
  if (diff === 1) return 'Yesterday';
  return d.toLocaleDateString(undefined, {
    weekday: 'long',
    month: 'long',
    day: 'numeric',
    year: d.getFullYear() !== new Date().getFullYear() ? 'numeric' : undefined,
  });
}
 
/** `embedded` drops the page logo; `onOpen` opens screenshots instead of following editor links. */
export function History({
  embedded = false,
  onOpen,
  onChange,
}: {
  embedded?: boolean;
  onOpen?: (id: string) => void;
  onChange?: () => void;
} = {}) {
  const root = useRef<HTMLDivElement>(null);
  const [isScrolled, setIsScrolled] = useState(false);
  const [shots, setShots] = useState<Shot[]>();
  const [query, setQuery] = useState('');
  const [filter, setFilter] = useState<CaptureMode | 'all'>('all');
  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [usage, setUsage] = useState<number>();
  const [confirmClear, setConfirmClear] = useState(false);
  const [toast, showToast] = useToast();
 
  useEffect(() => {
    const pane = embedded
      ? root.current?.closest<HTMLElement>('.app-main')
      : (document.scrollingElement ?? document.documentElement);
    if (!pane) return;
    const target = embedded ? pane : window;
    const onScroll = () => setIsScrolled(pane.scrollTop > 12);
    onScroll();
    target.addEventListener('scroll', onScroll, { passive: true });
    return () => target.removeEventListener('scroll', onScroll);
  }, [embedded]);
 
  const load = useCallback(async () => {
    setShots(await listShots());
    setUsage((await navigator.storage.estimate()).usage);
  }, []);
 
  useEffect(() => {
    void load();
    const onVisible = () =>
      document.visibilityState === 'visible' && void load();
    const onFocus = () => void load();
    document.addEventListener('visibilitychange', onVisible);
    // Desktop: the window stays visible while the editor (another window) changes shots.
    addEventListener('focus', onFocus);
    return () => {
      document.removeEventListener('visibilitychange', onVisible);
      removeEventListener('focus', onFocus);
    };
  }, [load]);
 
  const thumbs = useMemo(
    () => new Map(shots?.map((s) => [s.id, URL.createObjectURL(s.thumb)])),
    [shots],
  );
  useEffect(
    () => () => thumbs.forEach((url) => URL.revokeObjectURL(url)),
    [thumbs],
  );
 
  const visible = useMemo(() => {
    const q = query.trim().toLowerCase();
    return (shots ?? []).filter(
      (s) =>
        (filter === 'all' || s.mode === filter) &&
        (!q ||
          s.title.toLowerCase().includes(q) ||
          s.url.toLowerCase().includes(q)),
    );
  }, [shots, query, filter]);
 
  const groups = useMemo(() => {
    const map = new Map<string, Shot[]>();
    for (const s of visible) {
      const label = dayLabel(s.createdAt);
      map.set(label, [...(map.get(label) ?? []), s]);
    }
    return [...map];
  }, [visible]);
 
  async function remove(ids: string[]) {
    const removed = shots!.filter((s) => ids.includes(s.id));
    await deleteShots(ids);
    setSelected(new Set());
    await load();
    onChange?.();
    showToast(
      <>
        Deleted{' '}
        {ids.length === 1 ? '1 screenshot' : `${ids.length} screenshots`}
        <button
          className='link'
          onClick={async () => {
            await putShots(removed);
            await load();
            onChange?.();
            showToast('Restored');
          }}
        >
          Undo
        </button>
      </>,
      6000,
    );
  }
 
  async function clearAll() {
    setConfirmClear(false);
    await clearShots();
    setSelected(new Set());
    await load();
    onChange?.();
  }
 
  const openProps = (id: string) =>
    onOpen && {
      onClick: (e: { preventDefault(): void }) => {
        e.preventDefault();
        onOpen(id);
      },
    };
 
  async function copy(shot: Shot) {
    try {
      await copyPng(shot.blob);
      showToast('Copied to clipboard');
    } catch {
      showToast('Could not copy. Click the page and try again.');
    }
  }
 
  function toggle(id: string) {
    const next = new Set(selected);
    if (!next.delete(id)) next.add(id);
    setSelected(next);
  }
 
  return (
    <div ref={root} className={embedded ? 'history embedded' : 'history'}>
      <header className='history-head' data-scrolled={isScrolled}>
        <div className='history-title'>
          {!embedded && <Logo size={34} />}
          <div>
            <h1>History</h1>
            <p className='meta'>
              {shots
                ? `${shots.length} screenshot${shots.length === 1 ? '' : 's'}`
                : 'Loading…'}
              {usage !== undefined && ` · ${formatBytes(usage)} on this device`}
            </p>
          </div>
        </div>
        <label className='search'>
          <Icon name='search' size={16} />
          <input
            type='search'
            placeholder={SEARCH_PLACEHOLDER}
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            aria-label='Search screenshots'
          />
        </label>
        <div
          className='segmented'
          role='radiogroup'
          aria-label='Filter by capture type'
        >
          {FILTERS.map((f) => (
            <button
              key={f}
              role='radio'
              aria-checked={filter === f}
              onClick={() => setFilter(f)}
            >
              {f === 'all' ? 'All' : f === 'tabs' ? 'Tabs' : MODE_LABEL[f]}
            </button>
          ))}
        </div>
        <div className='history-actions'>
          {selected.size > 0 ? (
            <>
              <span className='meta'>{selected.size} selected</span>
              <button
                className='btn ghost'
                onClick={() => setSelected(new Set(visible.map((s) => s.id)))}
              >
                Select all
              </button>
              <button
                className='btn ghost'
                onClick={() => setSelected(new Set())}
              >
                Clear
              </button>
              <button
                className='btn danger'
                onClick={() => void remove([...selected])}
              >
                <Icon name='trash' size={16} />
                Delete
              </button>
            </>
          ) : (
            shots &&
            shots.length > 0 && (
              <button
                className='btn ghost'
                onClick={() => setConfirmClear(true)}
              >
                <Icon name='trash' size={16} />
                Clear all
              </button>
            )
          )}
        </div>
      </header>
 
      <main className='history-main'>
        {shots && shots.length === 0 && (
          <div className='empty'>
            <Logo size={56} />
            <h2>No screenshots yet</h2>
            <p>
              {CAPTURE_HINT} Everything you capture is kept here, on this device
              only.
            </p>
            <ul className='shortcut-list'>
              {SHORTCUT_HINTS.map(([keys, label]) => (
                <li key={keys}>
                  <kbd>{keys}</kbd> {label}
                </li>
              ))}
            </ul>
          </div>
        )}
        {shots && shots.length > 0 && visible.length === 0 && (
          <p className='empty meta'>No screenshots match your search.</p>
        )}
        {groups.map(([label, items]) => (
          <section key={label} className='day'>
            <h2>{label}</h2>
            <div className='grid'>
              {items.map((s) => (
                <article
                  key={s.id}
                  className='card'
                  data-selected={selected.has(s.id) || undefined}
                  data-selecting={selected.size > 0 || undefined}
                >
                  <a
                    className='card-thumb'
                    href={`editor.html?id=${s.id}`}
                    aria-label={`Edit ${s.title}`}
                    {...openProps(s.id)}
                  >
                    <img src={thumbs.get(s.id)} alt='' loading='lazy' />
                  </a>
                  <label className='card-check'>
                    <input
                      type='checkbox'
                      checked={selected.has(s.id)}
                      onChange={() => toggle(s.id)}
                      aria-label={`Select ${s.title}`}
                    />
                  </label>
                  <div className='card-actions'>
                    <button
                      className='icon-btn sm'
                      onClick={() => void copy(s)}
                      aria-label='Copy image'
                      title='Copy image'
                    >
                      <Icon name='copy' size={16} />
                    </button>
                    <button
                      className='icon-btn sm'
                      onClick={() =>
                        void downloadBlob(s.blob, fileName(s, 'png'))
                      }
                      aria-label={SAVE_PNG_LABEL}
                      title={SAVE_PNG_LABEL}
                    >
                      <Icon name='download' size={16} />
                    </button>
                    <button
                      className='icon-btn sm'
                      onClick={() => void remove([s.id])}
                      aria-label='Delete'
                      title='Delete'
                    >
                      <Icon name='trash' size={16} />
                    </button>
                  </div>
                  <div className='card-body'>
                    <a
                      className='card-title'
                      href={`editor.html?id=${s.id}`}
                      title={s.title}
                      {...openProps(s.id)}
                    >
                      {s.title}
                    </a>
                    <div className='card-meta'>
                      <span className='pill'>{MODE_LABEL[s.mode]}</span>
                      <span className='truncate'>
                        {hostOf(s.url) || NO_URL_LABEL}
                      </span>
                    </div>
                    <div className='card-meta mono'>
                      <span>
                        {s.width}×{s.height}
                      </span>
                      <span>{formatBytes(s.size)}</span>
                      <span>
                        {new Date(s.createdAt).toLocaleTimeString(undefined, {
                          hour: '2-digit',
                          minute: '2-digit',
                        })}
                      </span>
                    </div>
                  </div>
                </article>
              ))}
            </div>
          </section>
        ))}
      </main>
      {confirmClear && (
        <ConfirmDialog
          title={`Delete all ${shots!.length} screenshots?`}
          confirmLabel='Delete all'
          onConfirm={() => void clearAll()}
          onCancel={() => setConfirmClear(false)}
        >
          This can't be undone.
        </ConfirmDialog>
      )}
      <Toast message={toast} />
    </div>
  );
}
 
const root = document.getElementById('root');
Iif (root) createRoot(root).render(<History />);