Skip to content

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

9.2 KB
Raw Blame
import { useEffect, useMemo, useState } from "react";
import { Plus, UserPlus } from "../../icons";
import { useTranslation } from "react-i18next";
import InviteTeammateDialog from "../../InviteTeammateDialog";
import { useWorkspaceStore } from "../../../stores/workspaceStore";
import { canManageSpace } from "../../../lib/spacePermissions";
import {
  useNotes,
  useNotesByContainer,
  useFolders,
  useFolderCounts,
  useSpaceRootCounts,
  folderContainerKey,
  ensureContainerLoaded,
} from "../../../stores/noteStore";
import { useContainerChat } from "../../../hooks/useContainerChat";
import { cn } from "../../lib/utils";
import { PAGE_CONTENT_WIDTH_CLASS } from "../../ui/pageWidth";
import { PAGE_HERO_ICON_TILE_CLASS } from "../../ui/surfaces";
import { ContainerIcon } from "./ContainerIcon";
import { OverviewExplainerBanner } from "./OverviewExplainerBanner";
import { OverviewAskSection } from "./OverviewAskSection";
import { OverviewNoteList } from "./OverviewNoteList";
import { defaultFolderDisplayName } from "../shared";
import type { NoteItem, SpaceItem, FolderItem } from "../../../types/electron";

const SPACE_NOTES_LIMIT = 50;

interface ContainerOverviewProps {
  space: SpaceItem;
  folder: FolderItem | null;
  onOpenNote: (noteId: number) => void;
  onNewNote: () => void;
  onAddExisting?: () => void;
}

export function ContainerOverview({
  space,
  folder,
  onOpenNote,
  onNewNote,
  onAddExisting,
}: ContainerOverviewProps) {
  const { t } = useTranslation();
  const workspaces = useWorkspaceStore((s) => s.workspaces);
  const folders = useFolders();
  const containerNotes = useNotes();
  const notesByContainer = useNotesByContainer();
  const folderCounts = useFolderCounts();
  const spaceRootCounts = useSpaceRootCounts();
  const [spaceNotes, setSpaceNotes] = useState<NoteItem[] | null>(null);
  const [spaceNotesError, setSpaceNotesError] = useState(false);
  const [folderNotesError, setFolderNotesError] = useState(false);
  const [reloadKey, setReloadKey] = useState(0);
  const [showInviteDialog, setShowInviteDialog] = useState(false);

  // Folder overviews mirror the store's active container; space overviews list
  // the whole space (foldered + root), which the store doesn't hold — fetched
  // here and refreshed whenever any container's notes change.
  useEffect(() => {
    if (folder) return;
    let stale = false;
    window.electronAPI
      .getSpaceNotes(space.id, SPACE_NOTES_LIMIT)
      .then((rows) => {
        if (!stale) {
          setSpaceNotes(rows ?? []);
          setSpaceNotesError(false);
        }
      })
      .catch(() => {
        if (!stale) setSpaceNotesError(true);
      });
    return () => {
      stale = true;
    };
  }, [folder, space.id, notesByContainer, reloadKey]);

  useEffect(() => {
    if (!folder) return;
    const key = folderContainerKey(folder.id);
    if (notesByContainer[key] !== undefined) return;
    let stale = false;
    void ensureContainerLoaded(key)
      .then(() => {
        if (!stale) setFolderNotesError(false);
      })
      .catch(() => {
        if (!stale) setFolderNotesError(true);
      });
    return () => {
      stale = true;
    };
  }, [folder, notesByContainer]);

  const notes = folder ? containerNotes : (spaceNotes ?? []);
  const folderKey = folder ? folderContainerKey(folder.id) : null;
  const folderNotesLoaded = folderKey !== null && notesByContainer[folderKey] !== undefined;
  const isLoaded = folder ? folderNotesLoaded : spaceNotes !== null;
  const loadFailed = folder
    ? folderNotesError && !folderNotesLoaded
    : spaceNotesError && spaceNotes === null;

  const chat = useContainerChat({ space, folder, notes });

  const workspace = space.workspace_id
    ? workspaces.find((w) => w.id === space.workspace_id)
    : undefined;
  const canInvite =
    space.kind === "team" &&
    !!space.cloud_space_id &&
    !!workspace &&
    canManageSpace(space, workspace.role ?? null);

  const spaceFolders = useMemo(
    () => folders.filter((f) => f.space_id === space.id),
    [folders, space.id]
  );
  // DB-backed counts, as in SpacesTree: the visible list is capped at the
  // container page size, so notes.length undercounts large containers.
  const noteCount = folder
    ? (folderCounts[folder.id] ?? notes.length)
    : spaceFolders.reduce((sum, f) => sum + (folderCounts[f.id] ?? 0), 0) +
      (spaceRootCounts[space.id] ?? 0);

  const metaParts: string[] = [];
  if (space.kind === "team" && workspace) metaParts.push(workspace.name);
  if (!folder && spaceFolders.length > 0) {
    metaParts.push(t("notes.overview.meta.folders", { count: spaceFolders.length }));
  }
  metaParts.push(t("notes.spaces.noteCount", { count: noteCount }));
  if (space.kind === "team" && space.member_count != null) {
    metaParts.push(t("notes.overview.meta.members", { count: space.member_count }));
  }

  if (loadFailed || !isLoaded) {
    return (
      <div className="flex flex-1 flex-col items-center justify-center gap-3 px-6 text-sm text-muted-foreground">
        <p>{t(loadFailed ? "common.error" : "common.loading")}</p>
        {loadFailed && (
          <button
            onClick={() => {
              if (folderKey) {
                setFolderNotesError(false);
                void ensureContainerLoaded(folderKey).catch(() => setFolderNotesError(true));
              } else {
                setSpaceNotes(null);
                setSpaceNotesError(false);
                setReloadKey((value) => value + 1);
              }
            }}
            className="text-primary hover:underline focus-visible:underline"
          >
            {t("common.retry")}
          </button>
        )}
      </div>
    );
  }

  // Keyed, and a direct child of the same parent in both of its slots, so crossing
  // zero notes moves the composer instead of remounting it and losing its draft.
  const askSection = (
    <OverviewAskSection
      key="ask"
      messages={chat.messages}
      agentState={chat.agentState}
      onTextSubmit={chat.sendMessage}
      onCancel={chat.cancelStream}
      conversations={chat.conversations}
      activeConversationId={chat.activeConversationId}
      onSwitchConversation={chat.switchConversation}
      onNewChat={chat.startNewChat}
      onOpenNote={onOpenNote}
    />
  );

  return (
    <div className="flex-1 overflow-y-auto min-h-0">
      <div className={cn(PAGE_CONTENT_WIDTH_CLASS, "px-6 py-8 flex flex-col gap-5")}>
        <div className="flex flex-col items-center text-center gap-2 pt-4">
          <div className={cn(PAGE_HERO_ICON_TILE_CLASS, "mb-1")}>
            <ContainerIcon space={space} folder={folder} size={20} />
          </div>
          <h1 className="text-xl font-semibold text-foreground tracking-tight">
            {folder ? defaultFolderDisplayName(folder, t) : space.name}
          </h1>
          <p className="text-[13px] text-foreground/50 dark:text-foreground/45">
            {t(`notes.overview.subtitle.${space.kind === "team" ? "team" : "private"}`)}
          </p>
          <p className="text-xs text-foreground/45 dark:text-foreground/45">
            {metaParts.join(" · ")}
          </p>
          <div className="mt-1 flex items-center gap-2">
            {/* The empty state keeps its own focal create CTA in the list. */}
            {notes.length > 0 && (
              <button
                onClick={onNewNote}
                className="inline-flex items-center gap-1.5 px-3 h-7 rounded-md border border-border/70 dark:border-white/10 text-xs font-medium text-foreground/60 hover:text-foreground/85 hover:border-border/70 hover:bg-foreground/3 dark:hover:bg-white/3 transition-colors duration-150 focus:outline-none focus-visible:ring-1 focus-visible:ring-ring/30"
              >
                <Plus size={12} />
                {t("notes.list.newNote")}
              </button>
            )}
            {canInvite && (
              <button
                onClick={() => setShowInviteDialog(true)}
                className="inline-flex items-center gap-1.5 px-3 h-7 rounded-md border border-border/70 dark:border-white/10 text-xs font-medium text-foreground/60 hover:text-foreground/85 hover:border-border/70 hover:bg-foreground/3 dark:hover:bg-white/3 transition-colors duration-150 focus:outline-none focus-visible:ring-1 focus-visible:ring-ring/30"
              >
                <UserPlus size={12} />
                {t("notes.overview.invite")}
              </button>
            )}
          </div>
        </div>

        {notes.length > 0 && (
          <OverviewExplainerBanner kind={space.kind === "team" ? "team" : "private"} />
        )}
        {notes.length > 0 && askSection}
        <div className={notes.length > 0 ? "border-t border-border/70 dark:border-white/10" : ""}>
          <OverviewNoteList
            notes={notes}
            space={space}
            onOpenNote={onOpenNote}
            onNewNote={onNewNote}
            onAddExisting={onAddExisting}
          />
        </div>
        {notes.length === 0 && askSection}
      </div>

      {canInvite && workspace && space.cloud_space_id && (
        <InviteTeammateDialog
          open={showInviteDialog}
          onOpenChange={setShowInviteDialog}
          workspaceId={workspace.id}
          workspaceName={workspace.name}
          spaceIds={[space.cloud_space_id]}
        />
      )}
    </div>
  );
}