Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

16.2 KB
Raw Blame
import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Calendar, ExternalLink, Loader2, Mic, Monitor, Video } from "./icons";
import { Button } from "./ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
import PersonAvatar from "./ui/PersonAvatar";
import EmptyStateCard from "./ui/EmptyStateCard";
import ThemedEmptyIllustration from "./ui/ThemedEmptyIllustration";
import calendarEmptyLight from "../assets/empty-states/home-calendar-light.svg";
import calendarEmptyDark from "../assets/empty-states/home-calendar-dark.svg";
import { cn } from "./lib/utils";
import { CARD_SURFACE_CLASS } from "./ui/surfaces";
import type { CalendarAttendee, CalendarEvent } from "../types/calendar";
import { parseAttendees } from "../utils/calendarAttendees";
import { useSystemAudioPermission } from "../hooks/useSystemAudioPermission";
import { canManageSystemAudioInApp } from "../utils/systemAudioAccess";
import { getMeetingJoinUrl } from "../helpers/meetingJoinUrl";
import TouchGrass from "./TouchGrass";
import { createGrassRustle, type GrassRustle } from "../utils/grassRustle";
import { formatTimeRange, parseEventDate } from "../utils/dateFormatting";

interface UpcomingMeetingsProps {
  events: CalendarEvent[];
  isLoading: boolean;
  isConnected: boolean;
  onConnectCalendar: () => void;
}

const openJoinUrl = (url: string) => {
  if (window.electronAPI?.openExternal) {
    window.electronAPI.openExternal(url);
  } else {
    window.open(url, "_blank");
  }
};

// Today plus the next days that have events, capped at a working week.
const MAX_DAY_CARDS = 5;
// Avatars shown before the "+N" overflow pill.
const MAX_STACKED_AVATARS = 2;

interface DayGroup {
  key: string;
  date: Date;
  isToday: boolean;
  items: CalendarEvent[];
}

function groupEventsByDay(events: CalendarEvent[], now: Date): DayGroup[] {
  const groups: DayGroup[] = [];
  const byKey = new Map<string, DayGroup>();
  for (const event of events) {
    const date = parseEventDate(event.start_time);
    if (!date) continue;
    const key = date.toDateString();
    let group = byKey.get(key);
    if (!group) {
      group = { key, date, isToday: key === now.toDateString(), items: [] };
      byKey.set(key, group);
      groups.push(group);
    }
    group.items.push(event);
  }
  // Surface "today" even when it has nothing scheduled, so the list always
  // answers "what's next today?" at a glance.
  if (groups.length > 0 && !groups.some((g) => g.isToday)) {
    groups.unshift({ key: now.toDateString(), date: now, isToday: true, items: [] });
  }
  return groups.slice(0, MAX_DAY_CARDS);
}

// The quiet grey buttons inside a day card: join a meeting, touch grass.
const DAY_CARD_BUTTON_CLASS =
  "h-7 bg-surface-3 hover:bg-surface-raised dark:bg-surface-2 dark:hover:bg-surface-3";

const ATTENDEE_COUNT_PILL_CLASS =
  "flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-surface-3 px-0.5 text-[9px] font-medium tabular-nums text-muted-foreground ring-1 ring-background";

const RSVP_DOT: Record<string, string> = {
  accepted: "bg-green-500",
  declined: "bg-red-400",
  tentative: "bg-amber-400",
};

function AttendeePopover({
  event,
  attendees,
  timeRange,
  joinUrl,
}: {
  event: CalendarEvent;
  attendees: CalendarAttendee[];
  timeRange: string;
  joinUrl: string | null;
}) {
  const { t } = useTranslation();

  return (
    <Popover>
      <PopoverTrigger asChild>
        <button
          aria-label={`${attendees.length} ${t("notes.participants.attendees")}`}
          className="flex shrink-0 items-center -space-x-1 rounded-full outline-none transition-opacity hover:opacity-80 focus-visible:ring-1 focus-visible:ring-ring/40"
        >
          {attendees.slice(0, MAX_STACKED_AVATARS).map((a) => (
            <PersonAvatar
              key={a.email}
              email={a.email}
              displayName={a.displayName}
              size={18}
              className="ring-1 ring-background"
            />
          ))}
          {attendees.length > MAX_STACKED_AVATARS && (
            <span className={ATTENDEE_COUNT_PILL_CLASS}>
              +{attendees.length - MAX_STACKED_AVATARS}
            </span>
          )}
        </button>
      </PopoverTrigger>
      <PopoverContent align="end" className="w-72 p-0">
        <div className="border-b border-border/70 px-3 py-2.5">
          <p dir="auto" className="text-xs font-medium leading-snug text-foreground">
            {event.summary || t("upcoming.untitledEvent")}
          </p>
          <p className="mt-0.5 text-[11px] tabular-nums text-muted-foreground">{timeRange}</p>
        </div>
        <div className="max-h-56 overflow-y-auto p-1">
          {attendees.map((a) => (
            <div key={a.email} className="flex items-center gap-2 rounded-md px-2 py-1.5">
              <PersonAvatar email={a.email} displayName={a.displayName} />
              <div className="min-w-0 flex-1">
                <p dir="auto" className="truncate text-xs text-foreground/80">
                  {a.displayName || a.email.split("@")[0]}
                  {a.self && (
                    <span className="ms-1 text-foreground/45">{t("notes.participants.me")}</span>
                  )}
                </p>
                <p dir="ltr" className="truncate text-[11px] text-foreground/45">
                  {a.email}
                </p>
              </div>
              <span
                className={cn(
                  "h-1.5 w-1.5 shrink-0 rounded-full",
                  RSVP_DOT[a.responseStatus ?? ""] ?? "bg-muted-foreground/25"
                )}
              />
            </div>
          ))}
        </div>
        {joinUrl && (
          <div className="border-t border-border/70 p-1">
            <button
              onClick={() => openJoinUrl(joinUrl)}
              className="flex w-full cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-xs text-foreground/70 transition-colors hover:bg-foreground/5"
            >
              <ExternalLink size={12} className="shrink-0" />
              {t("upcoming.openMeetingLink")}
            </button>
          </div>
        )}
      </PopoverContent>
    </Popover>
  );
}

function EventRow({ event, isNow }: { event: CalendarEvent; isNow: boolean }) {
  const { t, i18n } = useTranslation();
  const joinUrl = getMeetingJoinUrl(event);
  const attendees = useMemo(() => parseAttendees(event), [event]);
  const timeRange = formatTimeRange(i18n.language, event.start_time, event.end_time);

  const startNotes = () => {
    if (joinUrl) openJoinUrl(joinUrl);
    window.electronAPI?.joinCalendarMeeting?.(event.id);
  };

  const joinButton = (
    <Button
      size="sm"
      variant="ghost"
      onClick={startNotes}
      className={cn("pointer-events-auto", DAY_CARD_BUTTON_CLASS)}
    >
      {joinUrl ? <Video size={12} /> : <Mic size={12} />}
      {joinUrl ? t("upcoming.joinAndTranscribe") : t("upcoming.takeNotes")}
    </Button>
  );

  return (
    <div className="group/event relative flex items-center gap-3 px-1 py-2">
      {attendees.length > 1 ? (
        <AttendeePopover
          event={event}
          attendees={attendees}
          timeRange={timeRange}
          joinUrl={joinUrl}
        />
      ) : event.attendees_count > 1 ? (
        <span className={ATTENDEE_COUNT_PILL_CLASS}>+{event.attendees_count - 1}</span>
      ) : null}
      <div className="min-w-0 flex-1">
        <p dir="auto" className="truncate text-sm font-medium leading-tight text-foreground">
          {event.summary || t("upcoming.untitledEvent")}
        </p>
        {isNow ? (
          <span className="mt-1 flex items-center gap-1.5">
            <span className="relative flex h-1.5 w-1.5">
              <span className="absolute inline-flex h-full w-full animate-pulse rounded-full bg-green-500 opacity-75" />
              <span className="relative inline-flex h-1.5 w-1.5 rounded-full bg-green-500" />
            </span>
            <span className="text-xs font-medium text-green-600 dark:text-green-400">
              {t("upcoming.now")}
            </span>
          </span>
        ) : (
          <p className="mt-0.5 truncate text-xs tabular-nums text-muted-foreground">{timeRange}</p>
        )}
      </div>
      {/* Always shown once the meeting is live; otherwise revealed on hover so you can join early. */}
      {isNow ? (
        joinButton
      ) : (
        <span
          // Overlaid so the row keeps its full width until hovered; the scrim fades the
          // covered end of a long title out instead of slicing it.
          className="pointer-events-none absolute inset-y-0 end-0 flex items-center bg-linear-to-r from-transparent to-background to-[2rem] ps-8 pe-1 opacity-0 transition-opacity duration-150 group-hover/event:opacity-100 has-[:focus-visible]:opacity-100 dark:to-surface-2"
        >
          {joinButton}
        </span>
      )}
    </div>
  );
}

function DayCard({ group, isNowFn }: { group: DayGroup; isNowFn: (e: CalendarEvent) => boolean }) {
  const { t, i18n } = useTranslation();
  // Non-null while the empty day shows the grass; it owns that visit's rustle audio.
  const [rustle, setRustle] = useState<GrassRustle | null>(null);
  const [sceneHeight, setSceneHeight] = useState(0);
  const emptyStateRef = useRef<HTMLDivElement>(null);
  const tryButtonRef = useRef<HTMLButtonElement>(null);
  const returnFocusRef = useRef(false);

  // A sync can add a meeting to today while the grass is out; the day is no longer empty.
  if (rustle && group.items.length > 0) setRustle(null);

  useEffect(() => () => rustle?.dispose(), [rustle]);

  useEffect(() => {
    if (rustle || !returnFocusRef.current) return;
    returnFocusRef.current = false;
    tryButtonRef.current?.focus();
  }, [rustle]);

  const touchGrass = () => {
    setSceneHeight(emptyStateRef.current?.offsetHeight ?? 0);
    // Created in the click so the browser lets the audio start.
    setRustle(createGrassRustle());
  };

  const leaveGrass = () => {
    returnFocusRef.current = true;
    setRustle(null);
  };

  return (
    <div
      className={cn(
        "overflow-clip rounded-xl border border-border/70 bg-clip-padding dark:border-white/10",
        // Out on the grass the header goes quiet grey, so the lawn carries the colour.
        group.isToday && !rustle
          ? "bg-[image:var(--gradient-calendar-today)]"
          : "bg-surface-3 dark:bg-surface-2"
      )}
    >
      <div
        className={cn(
          "flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium",
          group.isToday && !rustle ? "calendar-today-header text-white" : "text-foreground"
        )}
      >
        <Calendar size={12} className="shrink-0" />
        <span>
          {group.date.toLocaleDateString(i18n.language, {
            weekday: "short",
            day: "numeric",
            month: "short",
          })}
        </span>
        {rustle && (
          <button
            type="button"
            onClick={leaveGrass}
            className="ms-auto rounded-sm px-1 outline-none hover:underline focus-visible:ring-2 focus-visible:ring-current/40"
          >
            {t("common.back")}
          </button>
        )}
      </div>
      {/* The list sits on the header colour with its own rounded top, so that colour shows
          around its corners. The opaque layer keeps the dark tint from mixing with it. */}
      <div className="rounded-t-xl bg-background">
        <div className="rounded-t-xl px-2 dark:bg-surface-2/60">
          {group.items.length === 0 && rustle ? (
            <TouchGrass
              rustle={rustle}
              height={sceneHeight}
              label={t("upcoming.touchGrassLabel")}
              onExit={leaveGrass}
            />
          ) : group.items.length === 0 ? (
            <div ref={emptyStateRef} className="flex flex-col items-center px-1 py-4 text-center">
              {/* The artwork is drawn in the middle third of its height; the negative margin
                  trims most of the empty space above and below it, so the card stays short. */}
              <ThemedEmptyIllustration
                light={calendarEmptyLight}
                dark={calendarEmptyDark}
                width={316}
                height={120}
                className="-my-8"
              />
              <p className="mt-2 text-[15px] font-medium text-foreground">
                {t("upcoming.noEventsToday")}
              </p>
              <p className="mt-1 text-[13px] text-muted-foreground">
                {t("upcoming.emptyDayDescription")}
              </p>
              <Button
                ref={tryButtonRef}
                variant="ghost"
                onClick={touchGrass}
                className={cn(
                  "mt-3",
                  DAY_CARD_BUTTON_CLASS,
                  "h-9 rounded-full px-5 text-primary hover:text-primary dark:text-primary"
                )}
              >
                {t("upcoming.touchGrass")}
              </Button>
            </div>
          ) : (
            <div className="divide-y divide-border/60">
              {group.items.map((event) => (
                <EventRow key={event.id} event={event} isNow={isNowFn(event)} />
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

export default function UpcomingMeetings({
  events,
  isLoading,
  isConnected,
  onConnectCalendar,
}: UpcomingMeetingsProps) {
  const { t } = useTranslation();
  const systemAudio = useSystemAudioPermission();
  const needsSystemAudioGrant = !systemAudio.granted && canManageSystemAudioInApp(systemAudio);

  const now = useMemo(() => new Date(), []);
  const groupedEvents = useMemo(() => groupEventsByDay(events, now), [events, now]);

  const isNowFn = (event: CalendarEvent) => {
    const start = new Date(event.start_time);
    const end = new Date(event.end_time);
    return start <= now && now <= end;
  };

  return (
    <div>
      {/* Loading state */}
      {isLoading && (
        <div className="flex items-center justify-center gap-2 py-6">
          <Loader2 size={14} className="animate-spin text-primary" />
        </div>
      )}

      {/* Calendar not connected */}
      {!isLoading && !isConnected && (
        <EmptyStateCard
          className="px-4 py-8"
          icon={Calendar}
          title={t("upcoming.connectCalendar")}
          description={t("upcoming.connectCalendarDescription")}
        >
          <Button size="sm" onClick={onConnectCalendar} className="h-[30px] px-3.5">
            {t("upcoming.connectCalendarButton")}
          </Button>
        </EmptyStateCard>
      )}

      {/* Connected, nothing scheduled */}
      {!isLoading &&
        isConnected &&
        events.length === 0 &&
        (needsSystemAudioGrant ? (
          <EmptyStateCard
            className="px-4 py-8"
            icon={Monitor}
            description={t("upcoming.systemAudioRequired")}
          >
            <Button
              size="sm"
              variant="outline"
              onClick={() => systemAudio.request()}
              className="h-[30px] px-3.5"
            >
              {systemAudio.mode === "native"
                ? t("upcoming.openSettings")
                : t("onboarding.permissions.grantAccess")}
            </Button>
          </EmptyStateCard>
        ) : (
          <div
            className={cn(CARD_SURFACE_CLASS, "flex flex-col items-center px-4 py-6 text-center")}
          >
            <ThemedEmptyIllustration
              light={calendarEmptyLight}
              dark={calendarEmptyDark}
              width={316}
              height={120}
            />
            <p className="mt-3 text-sm font-semibold text-foreground">
              {t("upcoming.noUpcomingEvents")}
            </p>
            <p className="mt-1 text-xs text-muted-foreground">{t("upcoming.moreCalendarsHint")}</p>
            <button
              onClick={onConnectCalendar}
              className="mt-3 cursor-pointer text-xs text-primary underline-offset-2 outline-none hover:underline focus-visible:underline"
            >
              {t("upcoming.connectHere")}
            </button>
          </div>
        ))}

      {/* Day cards */}
      {!isLoading && isConnected && groupedEvents.length > 0 && (
        <div className="space-y-2.5">
          {groupedEvents.map((group) => (
            <DayCard key={group.key} group={group} isNowFn={isNowFn} />
          ))}
        </div>
      )}
    </div>
  );
}