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.

8.7 KB
Raw Blame
import { useCallback, useEffect, useState } from "react";
import {
  clearDictationHistory,
  copyDictation,
  deleteDictation,
  getDictationHistory,
  getTalkSettings,
  onDictationHistoryChanged,
  type DictationDto,
  type TalkKey,
} from "../lib/bridge";
import { useDesktopT, type DesktopT } from "../lib/messages";
import { deviceName, isWindows } from "../lib/platform";
import { Icon } from "./recorder/ui";

/** Taller items fold to this many lines until "Show more". */
const FOLDED_LINES = 4;
const NAMED_KEYS = ["option", "right_option", "control", "right_control", "fn", "right_shift"];
/** Keys Windows names in words (`shortcuts.talk.keysWindows`). */
const WINDOWS_KEYS = ["control", "right_control", "right_shift"];

type Elapsed = { unit: "now" | "m" | "h" | "d"; count: number };

function ago(ms: number, now: number): Elapsed {
  const s = Math.max(0, Math.round((now - ms) / 1000));
  if (s < 60) return { unit: "now", count: 0 };
  if (s < 3600) return { unit: "m", count: Math.floor(s / 60) };
  if (s < 86400) return { unit: "h", count: Math.floor(s / 3600) };
  return { unit: "d", count: Math.floor(s / 86400) };
}

function keyName(key: TalkKey, t: DesktopT): string {
  if (isWindows && WINDOWS_KEYS.includes(key)) return t(`shortcuts.talk.keysWindows.${key}`);
  return NAMED_KEYS.includes(key) ? t(`shortcuts.talk.keys.${key}`) : key.toUpperCase();
}

/**
 * The Transcribe tab: every Talk take's text (Dictate and Show), newest
 * first, from `dictation_history.rs`. Kept on this Mac only.
 */
export function TranscribePanel({ onLayoutChange }: { onLayoutChange?: () => void }) {
  const t = useDesktopT();
  const [items, setItems] = useState<DictationDto[] | null>(null);
  const [dictateKey, setDictateKey] = useState<TalkKey>(isWindows ? "right_control" : "control");
  const [copiedId, setCopiedId] = useState<number | null>(null);
  const [expanded, setExpanded] = useState<Set<number>>(() => new Set());
  const [confirmClear, setConfirmClear] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [now, setNow] = useState(() => Date.now());

  const refresh = useCallback(() => {
    getDictationHistory()
      .then((list) => {
        setItems(list);
        setNow(Date.now());
      })
      .catch((err) => setError(t("transcribe.failed", { error: String(err) })));
  }, [t]);

  useEffect(() => {
    let unlisten: (() => void) | undefined;
    let active = true;
    refresh();
    void onDictationHistoryChanged(refresh).then((fn) => {
      if (active) unlisten = fn;
      else fn();
    });
    getTalkSettings()
      .then((settings) => {
        if (active) setDictateKey(settings.dictateKey);
      })
      .catch(() => {});
    // "2m ago" keeps up while the tab stays open.
    const tick = window.setInterval(() => setNow(Date.now()), 30_000);
    return () => {
      active = false;
      unlisten?.();
      window.clearInterval(tick);
    };
  }, [refresh]);

  useEffect(() => {
    onLayoutChange?.();
  }, [items, expanded, error, onLayoutChange]);

  useEffect(() => {
    if (copiedId === null) return;
    const timer = window.setTimeout(() => setCopiedId(null), 1600);
    return () => window.clearTimeout(timer);
  }, [copiedId]);

  useEffect(() => {
    if (!confirmClear) return;
    const timer = window.setTimeout(() => setConfirmClear(false), 3000);
    return () => window.clearTimeout(timer);
  }, [confirmClear]);

  const copy = (id: number) => {
    copyDictation(id)
      .then(() => setCopiedId(id))
      .catch((err) => setError(t("transcribe.failed", { error: String(err) })));
  };
  const remove = (id: number) => {
    setItems((list) => list?.filter((item) => item.id !== id) ?? null);
    deleteDictation(id).catch((err) => {
      setError(t("transcribe.failed", { error: String(err) }));
      refresh();
    });
  };
  const clearAll = () => {
    if (!confirmClear) {
      setConfirmClear(true);
      return;
    }
    setConfirmClear(false);
    setItems([]);
    clearDictationHistory().catch((err) => {
      setError(t("transcribe.failed", { error: String(err) }));
      refresh();
    });
  };
  const toggle = (id: number) =>
    setExpanded((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });

  return (
    <section className="flex flex-col gap-2 px-4 pb-3 pt-1" aria-label={t("home.transcribe")}>
      <div className="flex items-start gap-2 px-1">
        <p className="min-w-0 flex-1 text-[12px] leading-snug text-ink-secondary">
          {t("transcribe.intro", { device: deviceName })}
        </p>
        {items && items.length > 0 && (
          <button
            type="button"
            onClick={clearAll}
            className={`shrink-0 rounded-lg px-2 py-0.5 text-[12px] font-semibold transition-colors ${
              confirmClear ? "bg-flash-500 text-white" : "text-sheet-link hover:bg-row"
            }`}
          >
            {confirmClear ? t("transcribe.confirmClear") : t("transcribe.clearAll")}
          </button>
        )}
      </div>

      {error && <p className="px-1 text-[11px] text-status-error [overflow-wrap:anywhere]">{error}</p>}

      {items && items.length === 0 && (
        <div className="flex flex-col items-center gap-2 rounded-2xl bg-row px-4 py-6 text-center">
          <span className="flex h-10 w-10 items-center justify-center rounded-full bg-flash-50 text-flash-500">
            <Icon name="mic" size={22} />
          </span>
          <p className="text-[12.5px] leading-snug text-ink-secondary">
            {dictateKey === "off"
              ? t("transcribe.emptyOff")
              : t("transcribe.empty", { key: keyName(dictateKey, t) })}
          </p>
        </div>
      )}

      {items && items.length > 0 && (
        <ul className="clipy-scroll -mx-1 flex max-h-[392px] flex-col gap-1.5 px-1" role="list">
          {items.map((item) => {
            const open = expanded.has(item.id);
            const long = item.text.split("\n").length > FOLDED_LINES || item.text.length > 220;
            const copied = copiedId === item.id;
            return (
              <li key={item.id} className="group rounded-2xl bg-row px-3 py-2.5">
                <p
                  className="whitespace-pre-wrap text-[13px] leading-snug text-ink-text [overflow-wrap:anywhere]"
                  style={
                    open || !long
                      ? undefined
                      : { display: "-webkit-box", WebkitLineClamp: FOLDED_LINES, WebkitBoxOrient: "vertical", overflow: "hidden" }
                  }
                >
                  {item.text}
                </p>
                <div className="mt-1.5 flex items-center gap-1.5">
                  <span
                    className={`rounded-md px-1.5 py-px text-[10.5px] font-semibold ${
                      item.kind === "show" ? "bg-flash-50 text-flash-600" : "bg-surface text-ink-secondary"
                    }`}
                  >
                    {t(`transcribe.kinds.${item.kind}`)}
                  </span>
                  <span className="min-w-0 truncate text-[11px] text-ink-muted" title={new Date(item.at).toLocaleString()}>
                    {t("transcribe.ago", ago(item.at, now))}
                  </span>
                  {long && (
                    <button
                      type="button"
                      onClick={() => toggle(item.id)}
                      className="shrink-0 text-[11px] font-medium text-sheet-link hover:underline"
                    >
                      {open ? t("transcribe.less") : t("transcribe.more")}
                    </button>
                  )}
                  <span className="flex-1" />
                  <button
                    type="button"
                    onClick={() => copy(item.id)}
                    aria-label={t("transcribe.copy")}
                    className={`flex h-7 shrink-0 items-center gap-1 rounded-lg px-2 text-[12px] font-semibold transition-colors ${
                      copied ? "text-status-ok" : "text-ink-text hover:bg-row-hover"
                    }`}
                  >
                    <Icon name={copied ? "check" : "copy"} size={15} />
                    {copied ? t("transcribe.copied") : t("transcribe.copy")}
                  </button>
                  <button
                    type="button"
                    onClick={() => remove(item.id)}
                    aria-label={t("transcribe.delete")}
                    title={t("transcribe.delete")}
                    className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg text-ink-secondary transition-colors hover:bg-row-hover hover:text-flash-600"
                  >
                    <Icon name="trash" size={15} />
                  </button>
                </div>
              </li>
            );
          })}
        </ul>
      )}
    </section>
  );
}