Skip to content

armgit / clipy

Public Imported from GitHub
0

The AI-native screen recorder. Record your screen and talk; the people you share it with and your AI agents both get it.

16.2 KB
Raw Blame
import { useCallback, useEffect, useRef, useState } from "react";
import { writeText } from "@tauri-apps/plugin-clipboard-manager";
import { invoke } from "@tauri-apps/api/core";
import { useFormatter, useTranslations } from "use-intl";
import { deviceName, isWindows } from "../lib/platform";
import { LOCAL_EDITION } from "../lib/edition";
import { onLocalRecordingRenamed, renameLocalRecording } from "../lib/bridge";

type LocalRecording = {
  id: string;
  stage: string;
  message: string;
  directory: string;
  arec_path: string | null;
  /** When it was made; a retry does not change it. */
  recorded_at_ms?: number;
  bytes: number;
  kept: boolean;
  expires_at_ms: number | null;
  title?: string | null;
  /** Ready, but its transcript can be made again now: offer Retry. */
  transcript_retry?: boolean;
};

/** `list_local_recordings`: `retention_days` is 0 when nothing expires. */
type LocalListing = { retention_days: number; recordings: LocalRecording[] };

type Filter = "all" | "kept" | "attention";
type Sort = "newest" | "oldest" | "largest";

const DAY_MS = 24 * 60 * 60 * 1000;

type LocalT = ReturnType<typeof useTranslations<"desktop.local">>;

export function formatBytes(t: LocalT, bytes: number): string {
  if (bytes >= 1e9) return t("size.gb", { size: (bytes / 1e9).toFixed(1) });
  if (bytes >= 1e6) return t("size.mb", { size: Math.round(bytes / 1e6) });
  return t("size.kb", { size: Math.max(1, Math.round(bytes / 1e3)) });
}

// Days rather than a date: the question a viewer has is "how long have I got",
// and a recording made minutes ago should not read as clearing "on the 28th".
const formatExpiry = (t: LocalT, row: LocalRecording) => {
  if (row.kept) return t("expiry.kept");
  if (!row.expires_at_ms) return null;
  const days = Math.ceil((row.expires_at_ms - Date.now()) / DAY_MS);
  if (days <= 0) return t("expiry.soon");
  return t("expiry.days", { days });
};

/**
 * `listAll` is the recorder strip's Local library sheet: every recording at
 * once, and an empty state instead of nothing. `onRetentionDays` reports the
 * retention period each listing came with.
 */
export default function LocalModePanel({ signedIn, listAll = false, onRetentionDays }: { signedIn: boolean; listAll?: boolean; onRetentionDays?: (days: number) => void }) {
  const t = useTranslations("desktop.local");
  const format = useFormatter();
  const [busy, setBusy] = useState(false);
  const [readError, setReadError] = useState<string | null>(null);
  const [actionError, setActionError] = useState<string | null>(null);
  const [recordings, setRecordings] = useState<LocalRecording[]>([]);
  const [retentionDays, setRetentionDays] = useState(0);
  const [showAll, setShowAll] = useState(listAll);
  const [loaded, setLoaded] = useState(false);
  const [copiedPath, setCopiedPath] = useState<string | null>(null);
  const [confirmingId, setConfirmingId] = useState<string | null>(null);
  const [renaming, setRenaming] = useState<{ id: string; draft: string } | null>(null);
  const [savingRename, setSavingRename] = useState(false);
  const [filter, setFilter] = useState<Filter>("all");
  const [sort, setSort] = useState<Sort>("newest");
  const refreshSeq = useRef(0);
  const section = useRef<HTMLElement>(null);
  // A button that replaces itself (Delete, Rename, the confirm and the title
  // field) takes keyboard focus with it. After that render, focus goes to the
  // control that takes its place, or to the section when the row is gone.
  const focusNext = useRef<string | null>(null);
  useEffect(() => {
    const key = focusNext.current;
    if (!key || !section.current) return;
    focusNext.current = null;
    const target = section.current.querySelector<HTMLElement>(`[data-focus-key="${CSS.escape(key)}"]`);
    (target ?? section.current).focus();
  });
  // "Path copied" is only true for a moment: the clipboard moves on.
  useEffect(() => {
    if (!copiedPath) return;
    const timer = window.setTimeout(() => setCopiedPath(null), 1500);
    return () => window.clearTimeout(timer);
  }, [copiedPath]);
  const refresh = useCallback(() => {
    const seq = ++refreshSeq.current;
    return invoke<LocalListing>("list_local_recordings")
      .then((listing) => {
        if (seq !== refreshSeq.current) return;
        setRecordings(listing.recordings);
        setRetentionDays(listing.retention_days);
        onRetentionDays?.(listing.retention_days);
        setReadError(null);
      })
      .catch((err) => {
        if (seq !== refreshSeq.current) return;
        setReadError(String(err));
      })
      .finally(() => {
        if (seq === refreshSeq.current) setLoaded(true);
      });
  }, [onRetentionDays]);
  useEffect(() => {
    let active = true;
    const poll = () => { if (active) void refresh(); };
    poll();
    const timer = window.setInterval(poll, 2000);
    let unlisten: (() => void) | undefined;
    void onLocalRecordingRenamed(({ id, title }) => {
      if (!active) return;
      setRecordings((prev) => prev.map((row) => (row.id === id ? { ...row, title } : row)));
    }).then((fn) => {
      if (active) unlisten = fn;
      else fn();
    }).catch(() => {});
    return () => { active = false; window.clearInterval(timer); unlisten?.(); };
  }, [refresh]);

  const signIn = async () => {
    setBusy(true); setActionError(null);
    try {
      await invoke("begin_sign_in");
    } catch (err) { setActionError(String(err)); }
    finally { setBusy(false); }
  };
  const action = async (command: string, row?: LocalRecording) => {
    setActionError(null);
    try { await invoke(command, row ? { id: row.id } : undefined); }
    catch (err) { setActionError(String(err)); }
  };
  // The library window shows it beside every other recording; the
  // single-recording viewer is the fallback if that window cannot open.
  const openInLibrary = async (row: LocalRecording) => {
    setActionError(null);
    try { await invoke("show_local_library", { id: row.id }); }
    catch { await action("show_local_viewer", row); }
  };
  const copyPath = async (path: string) => {
    setActionError(null);
    try { await writeText(path); setCopiedPath(path); }
    catch (err) { setActionError(String(err)); }
  };
  const setKept = async (row: LocalRecording) => {
    setActionError(null);
    try { await invoke("set_local_recording_kept", { id: row.id, kept: !row.kept }); await refresh(); }
    catch (err) { setActionError(String(err)); }
  };
  const remove = async (row: LocalRecording) => {
    setActionError(null);
    setConfirmingId(null);
    if (renaming?.id === row.id) setRenaming(null);
    try {
      await invoke("delete_local_recording", { id: row.id });
      focusNext.current = "section";
      await refresh();
    } catch (err) {
      focusNext.current = `${row.id}:delete`;
      setActionError(String(err));
    }
  };
  const confirmDelete = (row: LocalRecording) => {
    setConfirmingId(row.id);
    focusNext.current = `${row.id}:trash`;
  };
  const cancelDelete = (row: LocalRecording) => {
    setConfirmingId(null);
    focusNext.current = `${row.id}:delete`;
  };
  const endRename = (id: string) => {
    setRenaming(null);
    focusNext.current = `${id}:rename`;
  };
  const startRename = (row: LocalRecording) => {
    setActionError(null);
    setConfirmingId(null);
    setRenaming({ id: row.id, draft: row.title ?? "" });
  };
  const saveRename = async () => {
    if (!renaming || savingRename) return;
    setSavingRename(true);
    setActionError(null);
    try {
      await renameLocalRecording(renaming.id, renaming.draft);
      endRename(renaming.id);
      await refresh();
    } catch (err) {
      setActionError(String(err));
    } finally {
      setSavingRename(false);
    }
  };
  const error = actionError ?? readError;
  const total = recordings.reduce((sum, row) => sum + row.bytes, 0);
  // The filter and sort choices live in state above, so the two-second refresh
  // only replaces `recordings` and never resets them.
  // When it was made, not when it was last processed.
  const madeAt = (row: LocalRecording) => row.recorded_at_ms ?? 0;
  const visible = recordings
    .filter((row) => filter === "all" || (filter === "kept" ? row.kept : row.stage === "failed"))
    .sort((a, b) => sort === "oldest" ? madeAt(a) - madeAt(b) : sort === "largest" ? b.bytes - a.bytes : madeAt(b) - madeAt(a));
  const recordingCard = (row: LocalRecording) => {
    const statusText = row.stage === "ready"
      ? t("status.ready")
      : row.arec_path
        ? t("status.saved", { device: deviceName })
        : row.stage === "failed"
          ? t("status.failed")
          : t("status.recording", { device: deviceName });
    // When it was made, not when it was last processed.
    const formattedDate = row.recorded_at_ms
      ? format.dateTime(new Date(row.recorded_at_ms), { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" })
      : null;
    const titleText = row.title || formattedDate || statusText;
    const hasHeading = Boolean(row.title || formattedDate);
    const expiry = formatExpiry(t, row);
    const canRename = row.stage === "ready" || row.stage === "failed";
    const isRenaming = renaming?.id === row.id;

    return (
      <div key={row.id} role="group" aria-label={titleText} className="border-t border-subtle pt-2 first:border-t-0 first:pt-0">
        {isRenaming ? (
          <form
            onSubmit={(e) => {
              e.preventDefault();
              void saveRename();
            }}
            className="flex items-center gap-1.5"
          >
            <input
              type="text"
              autoFocus
              value={renaming.draft}
              disabled={savingRename}
              aria-label={t("renameLabel")}
              placeholder={t("renamePlaceholder")}
              onChange={(e) => setRenaming({ id: row.id, draft: e.target.value })}
              onKeyDown={(e) => {
                if (e.key === "Escape") {
                  e.preventDefault();
                  endRename(row.id);
                }
              }}
              className="min-w-0 flex-1 rounded-sm border border-strong bg-surface px-2 py-0.5 text-[11px] font-semibold text-ink-text placeholder:text-ink-muted focus:outline-none focus:ring-2 focus:ring-flash-500/50"
            />
            <button type="submit" disabled={savingRename} className="shrink-0 font-semibold text-flash-600 disabled:opacity-50">{t("save")}</button>
            <button type="button" disabled={savingRename} onClick={() => endRename(row.id)} className="shrink-0 text-ink-secondary disabled:opacity-50">{t("cancel")}</button>
          </form>
        ) : (
          <div className="flex items-center justify-between gap-2">
            <p className="min-w-0 truncate font-semibold text-ink-text" role={hasHeading ? undefined : "status"} title={titleText}>{titleText}</p>
            <p className="shrink-0 text-ink-secondary">{formatBytes(t, row.bytes)}</p>
          </div>
        )}
        {(hasHeading || isRenaming || expiry) && (
          <p className="text-ink-secondary">
            {(hasHeading || isRenaming) && <span role="status">{statusText}</span>}
            {row.title && formattedDate && ` · ${formattedDate}`}
            {expiry && `${hasHeading || isRenaming ? " · " : ""}${expiry}`}
          </p>
        )}
        {row.stage !== "ready" && <p className="mt-1 text-ink-secondary">{row.stage === "failed" ? row.message : t("preparing")}</p>}
        <div className="mt-2 flex flex-wrap items-center gap-3">
          {row.arec_path && <button type="button" className="rounded-sm bg-row-hover px-2 py-1 font-semibold text-ink-text" onClick={() => void copyPath(row.arec_path!)}>{copiedPath === row.arec_path ? t("pathCopied") : t("copyArecPath")}</button>}
          <button type="button" className="text-flash-600" onClick={() => void openInLibrary(row)}>{t("open")}</button>
          <button type="button" className="text-flash-600" onClick={() => void action("open_local_recording", row)}>{isWindows ? t("showInExplorer") : t("showInFinder")}</button>
          {canRename && !isRenaming && <button type="button" data-focus-key={`${row.id}:rename`} className="text-flash-600" onClick={() => startRename(row)}>{t("rename")}</button>}
          {(row.stage === "failed" || row.transcript_retry) && (LOCAL_EDITION || signedIn) && <button type="button" className="text-flash-600" onClick={() => void action("retry_local_recording", row)}>{t("retry")}</button>}
          <button type="button" className="text-flash-600" onClick={() => void setKept(row)}>{row.kept ? t("stopKeeping") : t("keep")}</button>
          {confirmingId === row.id
            ? (<><button type="button" data-focus-key={`${row.id}:trash`} className="font-semibold text-flash-600" onClick={() => void remove(row)}>{t("moveToTrash")}</button>
                <button type="button" className="text-ink-secondary" onClick={() => cancelDelete(row)}>{t("cancel")}</button></>)
            : <button type="button" data-focus-key={`${row.id}:delete`} className="text-ink-secondary" onClick={() => confirmDelete(row)}>{t("delete")}</button>}
        </div>
      </div>
    );
  };
  if (!listAll && signedIn && !error && recordings.length === 0) {
    return null;
  }

  return (
    <section ref={section} tabIndex={-1} aria-label={t("sectionLabel")} className="mx-3.5 mt-2 space-y-2 rounded-lg border border-subtle bg-row p-2.5 text-[11px] text-ink-secondary">
      {/* The Copy button's own label changes too, but a focused button's new name is not announced. */}
      <span role="status" className="sr-only">{copiedPath ? t("pathCopied") : ""}</span>
      {listAll && (
        <button
          type="button"
          className="rounded-sm bg-row-hover px-2 py-1 font-semibold text-ink-text"
          onClick={() => void action("open_local_recordings_folder")}
        >
          {t("openRecordingsFolder")}
        </button>
      )}
      {!LOCAL_EDITION && !signedIn && <button type="button" onClick={() => void signIn()} disabled={busy}
        className="text-flash-600 disabled:opacity-40">{busy ? t("openingSignIn") : t("signInToRecord")}</button>}
      {error && <p role="alert" className="text-flash-600">{error}</p>}
      {listAll && signedIn && loaded && !readError && recordings.length === 0 && (
        <p className="px-1 py-6 text-center text-[13px] text-ink-secondary">{t("empty")}</p>
      )}
      {recordings.length > 0 && <p className="text-ink-secondary">{retentionDays === 0
        ? t("totalOnDeviceNever", { size: formatBytes(t, total), device: deviceName })
        : t("totalOnDevice", { size: formatBytes(t, total), device: deviceName, days: retentionDays })}</p>}
      {/* Windows has no on-device speech engine: say where the audio goes. */}
      {!LOCAL_EDITION && isWindows && <p className="text-ink-secondary">{t("windowsAudio")}</p>}
      {listAll && (
        <div className="flex flex-wrap items-center gap-3">
          <label className="flex items-center gap-1">
            {t("filter.label")}
            <select value={filter} onChange={(event) => setFilter(event.target.value as Filter)} className="rounded-sm bg-row-hover px-1 py-0.5 text-ink-text">
              <option value="all">{t("filter.all")}</option>
              <option value="kept">{t("filter.kept")}</option>
              <option value="attention">{t("filter.attention")}</option>
            </select>
          </label>
          <label className="flex items-center gap-1">
            {t("sort.label")}
            <select value={sort} onChange={(event) => setSort(event.target.value as Sort)} className="rounded-sm bg-row-hover px-1 py-0.5 text-ink-text">
              <option value="newest">{t("sort.newest")}</option>
              <option value="oldest">{t("sort.oldest")}</option>
              <option value="largest">{t("sort.largest")}</option>
            </select>
          </label>
        </div>
      )}
      {listAll && visible.length === 0 && <p role="status" className="py-4 text-center text-ink-secondary">{t("filter.empty")}</p>}
      {listAll && visible.map(recordingCard)}
      {!listAll && recordings[0] && recordingCard(recordings[0])}
      {!listAll && recordings.length > 1 && <button type="button" className="text-flash-600" aria-expanded={showAll} onClick={() => setShowAll(!showAll)}>{showAll ? t("hidePrevious") : t("previous", { count: recordings.length - 1 })}</button>}
      {!listAll && showAll && <div className="max-h-40 space-y-2 overflow-y-auto">{recordings.slice(1).map(recordingCard)}</div>}
    </section>
  );
}