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.

13.9 KB
Raw Blame
import { writeText } from "@tauri-apps/plugin-clipboard-manager";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslations } from "use-intl";
import {
  getMeeting,
  meetingMarkdown,
  onMeetingUpdated,
  redoMeeting,
  renameMeetingSpeaker,
  setMeetingActionDone,
  type MeetingDto,
  type MeetingSourceDto,
} from "../lib/bridge";
import { boldSpans, notesBlocks, speakerColour } from "../lib/meetingNotes";

function clock(ms: number): string {
  const total = Math.max(0, Math.round(ms / 1000));
  const h = Math.floor(total / 3600);
  const m = Math.floor((total % 3600) / 60);
  const s = total % 60;
  return h > 0 ? `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}` : `${m}:${String(s).padStart(2, "0")}`;
}

function Bold({ text }: { text: string }) {
  return (
    <>
      {boldSpans(text).map((span, i) =>
        span.bold ? (
          <strong key={i} className="font-semibold">
            {span.text}
          </strong>
        ) : (
          <span key={i}>{span.text}</span>
        ),
      )}
    </>
  );
}

/** Loads the meeting for a local recording and keeps it current. `null`
 * until loaded, then the DTO (whose `meeting` is null while it is made). */
export function useMeeting(id: string): MeetingDto | null | undefined {
  const [meeting, setMeeting] = useState<MeetingDto | null | undefined>(undefined);
  useEffect(() => {
    if (!id) return;
    let active = true;
    const load = () =>
      getMeeting(id)
        .then((dto) => {
          if (active) setMeeting(dto);
        })
        .catch(() => {
          if (active) setMeeting(null);
        });
    void load();
    const unlisten = onMeetingUpdated((changed) => {
      if (changed === id) void load();
    });
    return () => {
      active = false;
      void unlisten.then((fn) => fn());
    };
  }, [id]);
  return meeting;
}

/**
 * The Meeting tab of the AREC viewer: the notes with each line linked to
 * where it was said, the action items to tick, and the transcript of who
 * said what with names to set.
 */
export function MeetingPanel({
  id,
  dto,
  position,
  seek,
  onChange,
}: {
  id: string;
  dto: MeetingDto;
  position: number;
  seek: (ms: number) => void;
  onChange: (dto: MeetingDto | null) => void;
}) {
  const t = useTranslations("desktop.viewer.meeting");
  const [hovered, setHovered] = useState<MeetingSourceDto | null>(null);
  const [renaming, setRenaming] = useState<string | null>(null);
  const [draft, setDraft] = useState("");
  const [copied, setCopied] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const meeting = dto.meeting;
  const stage = dto.status?.stage ?? "transcribing";

  const blocks = useMemo(
    () => (meeting?.notes ? notesBlocks(meeting.notes.markdown, dto.noteLines) : []),
    [meeting?.notes, dto.noteLines],
  );
  const sourceByLine = useMemo(() => {
    const map = new Map<number, MeetingSourceDto>();
    for (const source of meeting?.notes?.sources ?? []) map.set(source.line, source);
    return map;
  }, [meeting?.notes?.sources]);
  const label = useCallback(
    (speakerId: string) => {
      const speaker = meeting?.speakers.find((s) => s.id === speakerId);
      if (speaker?.name?.trim()) return speaker.name.trim();
      if (speakerId === "you") return t("you");
      if (speakerId === "others") return t("others");
      const n = Number.parseInt(speakerId.replace(/^p/, ""), 10);
      return Number.isFinite(n) ? t("person", { n }) : speakerId;
    },
    [meeting?.speakers, t],
  );
  const activeLine = useMemo(
    () => meeting?.utterances.findIndex((u) => position >= u.startMs && position < u.endMs + 400) ?? -1,
    [meeting?.utterances, position],
  );

  const run = async (action: () => Promise<MeetingDto | null | void>) => {
    setError(null);
    try {
      const next = await action();
      if (next !== undefined) onChange(next);
    } catch (e) {
      setError(e instanceof Error ? e.message : String(e));
    }
  };

  const copyNotes = async () => {
    await run(async () => {
      await writeText(await meetingMarkdown(id));
      setCopied(true);
      window.setTimeout(() => setCopied(false), 1500);
    });
  };

  const saveName = async (speakerId: string, name: string) => {
    setRenaming(null);
    await run(() => renameMeetingSpeaker(id, speakerId, name));
  };

  const busy = dto.running && (stage === "transcribing" || stage === "voices" || meeting?.notesState.state === "writing");
  const stageText =
    stage === "transcribing"
      ? t("transcribing")
      : stage === "voices"
        ? t("voices")
        : meeting?.notesState.state === "writing"
          ? t("writing")
          : stage === "failed"
            ? dto.status?.message || t("failed")
            : null;

  return (
    <div className="flex flex-col gap-4 px-5 py-4">
      <div className="flex flex-wrap items-center gap-2">
        {meeting?.app && <span className="text-[12px] text-ink-secondary">{t("callIn", { app: meeting.app })}</span>}
        <span className="flex-1" />
        {meeting && (
          <button
            type="button"
            onClick={() => void copyNotes()}
            className="rounded-full bg-row px-3 py-1 text-[12px] font-semibold hover:bg-row-hover"
          >
            {copied ? t("copied") : t("copy")}
          </button>
        )}
        {meeting && !busy && (
          <button
            type="button"
            onClick={() => void run(() => redoMeeting(id, false))}
            className="rounded-full bg-row px-3 py-1 text-[12px] font-semibold hover:bg-row-hover"
          >
            {meeting.notes ? t("rewrite") : t("write")}
          </button>
        )}
      </div>

      {stageText && (
        <p aria-live="polite" className="flex items-center gap-2 text-[13px] text-ink-secondary">
          {busy && <span className="h-2 w-2 animate-pulse rounded-full bg-sheet-link" />}
          {stageText}
        </p>
      )}
      {error && <p className="text-[13px] text-[#dc2626]">{error}</p>}
      {!busy && (stage === "failed" || meeting) && (
        <button
          type="button"
          onClick={() => void run(() => redoMeeting(id, true))}
          className="self-start rounded-full bg-row px-3 py-1 text-[12px] font-semibold hover:bg-row-hover"
        >
          {t("redoTranscript")}
        </button>
      )}

      {meeting?.notesState.state === "failed" && (
        <p className="rounded-lg bg-row px-3 py-2 text-[13px] leading-snug text-ink-text">{meeting.notesState.message}</p>
      )}

      {blocks.length > 0 && (
        <section className="space-y-1.5" aria-label={t("notes")}>
          {blocks.map((block, i) => {
            if (block.kind === "section") {
              return (
                <h3 key={i} className="pt-2 text-[13px] font-bold uppercase tracking-wide text-ink-secondary">
                  {block.text}
                </h3>
              );
            }
            if (block.kind === "topic") {
              return (
                <h4 key={i} className="pt-1 text-[13px] font-semibold text-ink-text">
                  {block.text}
                </h4>
              );
            }
            const source = block.line !== null ? sourceByLine.get(block.line) : undefined;
            const body = (
              <span className="text-[13px] leading-snug text-ink-text">
                <Bold text={block.text} />
                {source && <span className="ml-1.5 text-[11px] font-semibold tabular-nums text-sheet-link">{clock(source.startMs)}</span>}
              </span>
            );
            return (
              <div key={i} className="flex items-start gap-2">
                {block.action !== null ? (
                  <input
                    type="checkbox"
                    checked={block.done}
                    aria-label={t("done")}
                    onChange={(e) => {
                      const index = block.action as number;
                      void run(() => setMeetingActionDone(id, index, e.target.checked));
                    }}
                    className="mt-0.5 h-3.5 w-3.5 shrink-0 accent-[var(--color-sheet-link,#2563eb)]"
                  />
                ) : block.kind === "item" ? (
                  <span className="mt-[7px] h-1 w-1 shrink-0 rounded-full bg-ink-secondary" />
                ) : null}
                {source ? (
                  <button
                    type="button"
                    data-viewer-seek="true"
                    title={t("playFrom", { time: clock(source.startMs) })}
                    onMouseEnter={() => setHovered(source)}
                    onMouseLeave={() => setHovered(null)}
                    onFocus={() => setHovered(source)}
                    onBlur={() => setHovered(null)}
                    onClick={() => seek(source.startMs)}
                    className={`min-w-0 rounded text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sheet-link ${
                      block.done ? "line-through opacity-60" : ""
                    } hover:bg-row`}
                  >
                    {body}
                  </button>
                ) : (
                  <span className={`min-w-0 ${block.done ? "line-through opacity-60" : ""}`}>{body}</span>
                )}
              </div>
            );
          })}
          {meeting?.notes && (
            <p className="pt-2 text-[11px] text-ink-secondary">{t("writtenBy", { writer: meeting.notes.writtenBy })}</p>
          )}
        </section>
      )}

      {meeting && meeting.speakers.length > 0 && (
        <section aria-label={t("speakers")}>
          <h3 className="pb-2 text-[13px] font-bold uppercase tracking-wide text-ink-secondary">{t("speakers")}</h3>
          <div className="flex flex-wrap gap-1.5">
            {meeting.speakers
              .filter((s) => meeting.utterances.some((u) => u.speaker === s.id))
              .map((speaker) =>
                renaming === speaker.id ? (
                  <form
                    key={speaker.id}
                    onSubmit={(e) => {
                      e.preventDefault();
                      void saveName(speaker.id, draft);
                    }}
                    className="flex items-center gap-1"
                  >
                    <input
                      autoFocus
                      value={draft}
                      onChange={(e) => setDraft(e.target.value)}
                      onKeyDown={(e) => {
                        if (e.key === "Escape") setRenaming(null);
                      }}
                      placeholder={speaker.suggestedName ?? label(speaker.id)}
                      aria-label={t("nameLabel", { speaker: label(speaker.id) })}
                      className="w-32 rounded-md border border-subtle bg-transparent px-2 py-0.5 text-[12px] text-ink-text focus:border-sheet-link focus:outline-none"
                    />
                    <button type="submit" className="rounded-full bg-row px-2 py-0.5 text-[12px] font-semibold hover:bg-row-hover">
                      {t("save")}
                    </button>
                  </form>
                ) : (
                  <button
                    key={speaker.id}
                    type="button"
                    title={t("rename")}
                    onClick={() => {
                      setRenaming(speaker.id);
                      setDraft(speaker.name ?? speaker.suggestedName ?? "");
                    }}
                    className="flex items-center gap-1.5 rounded-full bg-row px-2.5 py-0.5 text-[12px] font-semibold hover:bg-row-hover"
                  >
                    <span className="h-2 w-2 rounded-full" style={{ backgroundColor: speakerColour(speaker.id) }} />
                    {label(speaker.id)}
                    {!speaker.name && speaker.suggestedName && (
                      <span className="font-normal text-ink-secondary">{t("maybe", { name: speaker.suggestedName })}</span>
                    )}
                  </button>
                ),
              )}
          </div>
          {!meeting.voicesSplit && meeting.speakers.some((s) => s.id === "others") && (
            <p className="pt-2 text-[12px] text-ink-secondary">{t("notSplit")}</p>
          )}
        </section>
      )}

      {meeting && (
        <section aria-label={t("transcript")}>
          <h3 className="pb-2 text-[13px] font-bold uppercase tracking-wide text-ink-secondary">{t("transcript")}</h3>
          {meeting.utterances.length === 0 ? (
            <p className="text-[13px] text-ink-secondary">{t("noSpeech")}</p>
          ) : (
            <div className="space-y-1">
              {meeting.utterances.map((u, index) => {
                const lit = hovered !== null && index >= hovered.first && index <= hovered.last;
                return (
                  <button
                    key={`${u.startMs}-${index}`}
                    type="button"
                    data-viewer-seek="true"
                    onClick={() => seek(u.startMs)}
                    className={`flex w-full flex-col gap-0.5 rounded-lg px-2 py-1.5 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sheet-link ${
                      lit ? "bg-[#fde68a]/60" : index === activeLine ? "bg-sheet-link-soft" : "hover:bg-row"
                    }`}
                  >
                    <span className="flex items-center gap-2 text-[12px]">
                      <span className="font-semibold" style={{ color: speakerColour(u.speaker) }}>
                        {label(u.speaker)}
                      </span>
                      <span className="tabular-nums text-ink-secondary">{clock(u.startMs)}</span>
                    </span>
                    <span className="text-[13px] leading-snug text-ink-text">{u.text}</span>
                  </button>
                );
              })}
            </div>
          )}
          {meeting.echoDropped > 0 && (
            <p className="pt-2 text-[12px] text-ink-secondary">{t("echoDropped", { count: meeting.echoDropped })}</p>
          )}
        </section>
      )}
    </div>
  );
}