Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

23.8 KB
Raw Blame
/**
 * The organization handbook — `handbook/` in the organization directory, the company's
 * knowledge base — as two panes. Left, the app's shared file tree over the directory
 * (handbook-explorer.tsx, the same tree the Workspace panel and the plugin browser draw): the
 * index (`README.md`, the page every trigger makes the employee read first) leading the rows,
 * then folders and documents nested as they are on disk, with one button that collapses them
 * all. Right, the selected document rendered as Markdown (anything else preformatted),
 * edited in place through a monospace textarea with save and cancel — a save the server refuses
 * keeps its reason above the draft, where the button that retries it is — and, for every document
 * but the index, deleted behind the shared confirmation, which closes only once its own delete
 * landed: a refusal keeps the card standing with the server's words inside it, where the button
 * that retries them is. The new-document dialog refuses a path the server would, starts from
 * the selected document's own folder so a document lands beside its siblings, then creates the
 * file with a one-line title and selects it. A relative link inside a document opens the
 * document it names in the same pane, so the index works as the handbook's own navigation.
 *
 * Loading discipline: the skeleton stands only until the first listing or its failure; a
 * failed refresh keeps the list on screen under one error line with its retry; a document
 * that fails to load says so inside its pane with the list still usable. The selection is
 * component state — the URL stays at the page.
 */
import { useCallback, useEffect, useMemo, useState } from "react";
import type { KeyboardEvent as ReactKeyboardEvent, MouseEvent as ReactMouseEvent } from "react";
import type { OrgHandbookFile, OrgHandbookFileResponse } from "@adelie/server/api";
import {
  Badge,
  Button,
  ConfirmModal,
  EmptyState,
  GlyphIcon,
  ICON_GAP,
  ICON_SIZE,
  Input,
  Md,
  Modal,
  RuledSection,
  Skeleton,
  Textarea,
  toastSuccess,
} from "@adelie/ui";
import type { TreeToggle } from "@adelie/ui";
import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
import { toneInk } from "../../lib/tone";
import { formatBytes, formatDateTime, formatRelativeShort } from "../../lib/format";
import { isShortcut } from "../../lib/shortcuts/match";
import { currentPlatform } from "../../lib/shortcuts/platform";
import { keymap } from "../../lib/shortcuts/store";
import { useShortcutLabel } from "../../lib/shortcuts/use-keymap";
import { useDocumentTitle } from "../../lib/use-document-title";
import { useLocale } from "../../state/locale";
import { OrgEmptyLine, OrgPage, useOrg } from "./org-layout";
import { ErrorLine } from "./shared";
import { COLLAPSE_ALL_ICON, HandbookExplorer } from "./handbook-explorer";
import { handbookSaveRefusal } from "./handbook-save-refusal";
import {
  HANDBOOK_INDEX,
  ancestorFolders,
  buildHandbookTree,
  completeHandbookPath,
  handbookTreeRows,
  isHandbookPath,
  isMarkdownPath,
  newDocumentBody,
  resolveHandbookLink,
} from "./handbook-tree";

/** The two panes: a fixed list column beside the document, stacked on a narrow screen. */
const PANES_CLASS = "grid grid-cols-1 gap-x-10 gap-y-6 lg:grid-cols-[17rem_minmax(0,1fr)]";

/** The size a listing row would report for content just written, before the listing is re-read. */
const byteLength = (text: string) => new TextEncoder().encode(text).length;

export function HandbookPage() {
  const { projectId, orgId, org } = useOrg();
  const { locale } = useLocale();
  useDocumentTitle(org ? `${org.name} · ${S.nav.org.handbook}` : S.nav.org.handbook);
  const [files, setFiles] = useState<OrgHandbookFile[] | null>(null);
  const [listError, setListError] = useState<string | null>(null);
  const [selected, setSelected] = useState(HANDBOOK_INDEX);
  /** The open folders of the tree, by path: a folder starts closed and is opened by hand. */
  const [expanded, setExpanded] = useState<ReadonlySet<string>>(() => new Set<string>());
  /** The folder last opened or closed, so the tree animates that subtree and no other. */
  const [toggled, setToggled] = useState<TreeToggle | null>(null);
  const [doc, setDoc] = useState<OrgHandbookFileResponse | null>(null);
  const [docError, setDocError] = useState<string | null>(null);
  /** Bumped to re-read the selected document (its retry) without changing the selection. */
  const [docAttempt, setDocAttempt] = useState(0);
  const [editing, setEditing] = useState(false);
  const [draft, setDraft] = useState("");
  const [saving, setSaving] = useState(false);
  /** The words of a save the server refused, kept above the draft whose save button retries it. */
  const [saveRefusal, setSaveRefusal] = useState<string | null>(null);
  const [createOpen, setCreateOpen] = useState(false);
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [deleting, setDeleting] = useState(false);
  /** The words of a delete the server refused, kept in the card that asked for it. */
  const [deleteRefusal, setDeleteRefusal] = useState<string | null>(null);

  // Another organization's handbook must not linger while this one loads.
  useEffect(() => {
    setFiles(null);
    setListError(null);
    setSelected(HANDBOOK_INDEX);
    setExpanded(new Set<string>());
    setToggled(null);
    setEditing(false);
  }, [projectId, orgId]);

  const loadList = useCallback(async () => {
    try {
      const res = await api.listOrgHandbookFiles(projectId, orgId);
      setFiles(res.files);
      setListError(null);
    } catch (e) {
      setListError(apiErrorText(e));
    }
  }, [projectId, orgId]);
  useEffect(() => {
    void loadList();
  }, [loadList]);

  // The pane follows the selection. A response for a document the user has already left
  // must not land in it, hence the cancellation.
  useEffect(() => {
    let cancelled = false;
    setDoc(null);
    setDocError(null);
    setEditing(false);
    // Another document is another draft: the last one's refusal is not about this text.
    setSaveRefusal(null);
    api
      .getOrgHandbookFile(projectId, orgId, selected)
      .then((res) => {
        if (cancelled) return;
        setDoc(res);
        setDocError(null);
      })
      .catch((e: unknown) => {
        if (!cancelled) setDocError(apiErrorText(e));
      });
    return () => {
      cancelled = true;
    };
  }, [projectId, orgId, selected, docAttempt]);

  // A document that vanished from the listing (deleted elsewhere) gives way to the index.
  useEffect(() => {
    if (files !== null && selected !== HANDBOOK_INDEX && !files.some((f) => f.path === selected)) {
      setSelected(HANDBOOK_INDEX);
    }
  }, [files, selected]);

  // The selected document is always in view: whatever selects it — the first load, a link
  // followed inside another document, a document just created — opens the folders above it.
  // Collapsing them all afterwards is the reader's to do, and stays done.
  useEffect(() => {
    const parents = ancestorFolders(selected);
    if (parents.length === 0) return;
    setExpanded((prev) => {
      if (parents.every((p) => prev.has(p))) return prev;
      const next = new Set(prev);
      for (const p of parents) next.add(p);
      return next;
    });
  }, [selected]);

  const toggleFolder = (path: string) => {
    // The serial makes toggling the same folder again a new event for the tree to animate.
    setToggled((last) => ({
      dir: path,
      open: !expanded.has(path),
      serial: (last?.serial ?? 0) + 1,
    }));
    setExpanded((prev) => {
      const next = new Set(prev);
      if (!next.delete(path)) next.add(path);
      return next;
    });
  };

  /** A write's effect on the listing, ahead of the re-read that confirms it. */
  const upsertFile = (file: OrgHandbookFile) =>
    setFiles((prev) =>
      prev === null ? [file] : [...prev.filter((f) => f.path !== file.path), file],
    );

  const startEdit = () => {
    if (doc === null) return;
    setDraft(doc.content);
    setEditing(true);
    setSaveRefusal(null);
  };

  /** Leaving the editor drops the draft, and with it the answer about the draft's save. */
  const cancelEdit = () => {
    setEditing(false);
    setSaveRefusal(null);
  };

  const save = async () => {
    if (doc === null || saving) return;
    setSaving(true);
    // The last answer is not this attempt's: the line goes when Save is pressed again.
    setSaveRefusal(null);
    try {
      const res = await api.putOrgHandbookFile(projectId, orgId, doc.path, draft);
      setDoc(res);
      setEditing(false);
      upsertFile({
        path: res.path,
        size: byteLength(res.content),
        updatedAt: new Date().toISOString(),
      });
      toastSuccess(S.common.saved);
      void loadList();
    } catch (e) {
      // The editor stays open with the draft in it, so the reason stays where the draft and the
      // button that retries it are (7.19's rule) rather than in a toast that outlives nothing.
      setSaveRefusal(handbookSaveRefusal(e, draft, doc.content));
    } finally {
      setSaving(false);
    }
  };

  const create = async (path: string) => {
    const res = await api.putOrgHandbookFile(projectId, orgId, path, newDocumentBody(path));
    upsertFile({
      path: res.path,
      size: byteLength(res.content),
      updatedAt: new Date().toISOString(),
    });
    setCreateOpen(false);
    setSelected(res.path);
    toastSuccess(S.company.handbook.documentCreated);
    void loadList();
  };

  const remove = async () => {
    if (doc === null || deleting) return;
    const path = doc.path;
    setDeleting(true);
    try {
      await api.deleteOrgHandbookFile(projectId, orgId, path);
      // The card goes with its own delete landing, never before: a refusal has to stay readable
      // next to the button that retries it.
      setDeleteOpen(false);
      setDeleteRefusal(null);
      setFiles((prev) => (prev === null ? prev : prev.filter((f) => f.path !== path)));
      setSelected(HANDBOOK_INDEX);
      toastSuccess(S.company.handbook.documentDeleted);
      void loadList();
    } catch (e) {
      setDeleteRefusal(apiErrorText(e));
    } finally {
      setDeleting(false);
    }
  };

  // A relative link inside the rendered document is another document of the handbook: it
  // opens in this pane rather than in the new tab the Markdown renderer's links default to.
  const onBodyClick = (e: ReactMouseEvent<HTMLDivElement>) => {
    if (doc === null) return;
    const anchor = (e.target as HTMLElement).closest("a");
    if (anchor === null) return;
    const target = resolveHandbookLink(doc.path, anchor.getAttribute("href") ?? "");
    if (target === null) return;
    e.preventDefault();
    setSelected(target);
  };

  const onEditorKey = (e: ReactKeyboardEvent<HTMLTextAreaElement>) => {
    if (isShortcut(e.nativeEvent, keymap(), "editor.save", currentPlatform())) {
      // A held chord repeats: every repeat is kept from the browser (Save Page), one save runs.
      e.preventDefault();
      if (!e.repeat) void save();
    }
  };
  const saveShortcut = useShortcutLabel("editor.save");

  const tree = useMemo(() => (files === null ? null : buildHandbookTree(files)), [files]);
  const rows = useMemo(
    () => (tree === null ? [] : handbookTreeRows(tree, expanded)),
    [tree, expanded],
  );
  const existing = useMemo(() => new Set((files ?? []).map((f) => f.path)), [files]);
  const selectedFile = files?.find((f) => f.path === selected) ?? null;
  const isIndex = selected === HANDBOOK_INDEX;
  // A new document starts in the selected one's folder: that is where its siblings are.
  const selectedFolders = ancestorFolders(selected);
  const newDocumentFolder =
    selectedFolders.length === 0 ? "" : `${selectedFolders[selectedFolders.length - 1]!}/`;

  const title = S.nav.org.handbook;
  const info = S.company.handbook.info;

  if (tree === null) {
    return (
      <OrgPage title={title} info={info}>
        {listError !== null ? (
          <EmptyState
            title={S.company.handbook.loadFailed}
            description={listError}
            action={<Button onClick={() => void loadList()}>{S.common.retry}</Button>}
          />
        ) : (
          <HandbookSkeleton />
        )}
      </OrgPage>
    );
  }

  return (
    <OrgPage title={title} info={info}>
      {listError !== null && (
        <ErrorLine
          message={S.company.handbook.loadFailed}
          detail={listError}
          onRetry={() => void loadList()}
          className="mb-4"
        />
      )}
      <div className={PANES_CLASS}>
        {/* The create button sits in the section's action slot rather than the page's: it
            is the list's own action, and a button in both headers keeps their rules level. */}
        <RuledSection
          title={S.company.handbook.documents}
          count={files?.length ?? 0}
          actions={
            <>
              <button
                type="button"
                data-tooltip={S.company.handbook.collapseAll}
                aria-label={S.company.handbook.collapseAll}
                disabled={expanded.size === 0}
                onClick={() => {
                  // Every folder at once is not one subtree shrinking: nothing to animate.
                  setToggled(null);
                  setExpanded(new Set<string>());
                }}
                className="inline-flex items-center justify-center rounded p-1 text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-700 disabled:opacity-40 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200"
              >
                <GlyphIcon d={COLLAPSE_ALL_ICON} size={ICON_SIZE.groupHeaderAction} />
              </button>
              <Button size="sm" onClick={() => setCreateOpen(true)}>
                {S.company.handbook.newDocument}
              </Button>
            </>
          }
        >
          <HandbookExplorer
            rows={rows}
            selected={selected}
            locale={locale}
            toggled={toggled}
            onSelect={setSelected}
            onToggle={toggleFolder}
          />
          {tree.nodes.length === 0 && (
            <OrgEmptyLine>{S.company.handbook.noOtherDocuments}</OrgEmptyLine>
          )}
        </RuledSection>

        <section className="min-w-0" aria-label={selected}>
          {/* The document's own header: its path (a file name, not a heading, so no
              uppercase), the index mark, when it was written, and the pane's controls. */}
          <div className="mb-3 flex flex-wrap items-center justify-between gap-x-3 gap-y-2 border-b border-gray-200 pb-2 dark:border-gray-800">
            <div className={`flex min-w-0 items-center ${ICON_GAP.row}`}>
              <span className="truncate font-mono text-xs font-semibold text-gray-700 dark:text-gray-200">
                {selected}
              </span>
              {/* The one place the index's reason for being pinned is on screen — it says what
                  the document open in this pane is, so it belongs to the document, not to a row
                  in a list of them. The explorer row carries the same sentence in its tooltip
                  and its accessible name. */}
              {isIndex && (
                <span className="shrink-0">
                  <Badge size="sm">{S.company.handbook.indexLabel}</Badge>
                </span>
              )}
              {selectedFile !== null && (
                <span
                  className="hidden shrink-0 text-xs text-gray-400 sm:inline dark:text-gray-500"
                  data-tooltip={S.company.handbook.updatedAt(
                    formatDateTime(selectedFile.updatedAt),
                    formatBytes(selectedFile.size),
                  )}
                  data-tooltip-extra
                >
                  {formatRelativeShort(selectedFile.updatedAt, locale)}
                </span>
              )}
            </div>
            <div className="flex shrink-0 items-center gap-1.5">
              {editing ? (
                <>
                  <span className="hidden text-xs text-gray-400 sm:inline dark:text-gray-500">
                    {S.company.handbook.editorHint(saveShortcut)}
                  </span>
                  <Button size="sm" disabled={saving} onClick={cancelEdit}>
                    {S.common.cancel}
                  </Button>
                  <Button size="sm" variant="primary" disabled={saving} onClick={() => void save()}>
                    {saving ? S.common.saving : S.common.save}
                  </Button>
                </>
              ) : (
                <>
                  <Button size="sm" disabled={doc === null} onClick={startEdit}>
                    {S.common.edit}
                  </Button>
                  {!isIndex && (
                    <Button
                      size="sm"
                      variant="danger"
                      disabled={doc === null}
                      onClick={() => {
                        // A new question, not the last one: the previous refusal is not its answer.
                        setDeleteRefusal(null);
                        setDeleteOpen(true);
                      }}
                    >
                      {S.common.delete}
                    </Button>
                  )}
                </>
              )}
            </div>
          </div>
          {editing && saveRefusal !== null && (
            <p
              role="alert"
              data-tooltip={saveRefusal}
              data-tooltip-content="text"
              className={`mb-2 line-clamp-2 break-words text-xs ${toneInk.danger}`}
            >
              {saveRefusal}
            </p>
          )}
          {docError !== null ? (
            <EmptyState
              title={S.company.handbook.documentLoadFailed}
              description={docError}
              action={<Button onClick={() => setDocAttempt((n) => n + 1)}>{S.common.retry}</Button>}
            />
          ) : doc === null ? (
            <DocumentSkeleton />
          ) : editing ? (
            <Textarea
              mono
              size="sm"
              aria-label={selected}
              value={draft}
              rows={24}
              spellCheck={false}
              autoFocus
              disabled={saving}
              className="min-h-[50vh]"
              onChange={(e) => {
                setDraft(e.target.value);
                // A new draft has not been refused yet: the line described the text as it was.
                setSaveRefusal(null);
              }}
              onKeyDown={onEditorKey}
            />
          ) : doc.content.trim() === "" ? (
            <OrgEmptyLine>{S.company.handbook.emptyDocument}</OrgEmptyLine>
          ) : isMarkdownPath(doc.path) ? (
            <div
              className="md-body text-sm leading-relaxed text-gray-800 dark:text-gray-100"
              onClick={onBodyClick}
            >
              <Md text={doc.content} />
            </div>
          ) : (
            <pre className="overflow-x-auto whitespace-pre-wrap rounded-md border border-gray-200 bg-gray-50 p-3 font-mono text-xs leading-relaxed text-gray-800 dark:border-gray-800 dark:bg-gray-900 dark:text-gray-200">
              {doc.content}
            </pre>
          )}
        </section>
      </div>

      <NewDocumentDialog
        open={createOpen}
        folder={newDocumentFolder}
        existing={existing}
        onClose={() => setCreateOpen(false)}
        onCreate={create}
      />
      <ConfirmModal
        open={deleteOpen}
        title={S.company.handbook.deleteDocument}
        confirmLabel={S.common.delete}
        cancelLabel={S.common.cancel}
        busy={deleting}
        onClose={() => (deleting ? undefined : setDeleteOpen(false))}
        onConfirm={() => void remove()}
        refusal={deleteRefusal === null ? undefined : S.common.refused(deleteRefusal)}
      >
        <p className="text-sm text-gray-600 dark:text-gray-300">
          {S.company.handbook.deleteConfirm(selected)}
        </p>
      </ConfirmModal>
    </OrgPage>
  );
}

/**
 * The new-document dialog: one path field, checked here before the request — the server's
 * own rule, a name already taken — so the failure lands under the field; anything the server
 * still refuses lands in a strip above the footer with its retry.
 */
function NewDocumentDialog({
  open,
  folder,
  existing,
  onClose,
  onCreate,
}: {
  open: boolean;
  /** What the field starts with: the selected document's folder as a `<folder>/` prefix, or "". */
  folder: string;
  /** Every path the listing holds, so a duplicate is refused before it overwrites. */
  existing: ReadonlySet<string>;
  onClose: () => void;
  /** Creates the file; a rejection is shown in the dialog. */
  onCreate: (path: string) => Promise<void>;
}) {
  const [path, setPath] = useState("");
  const [pathError, setPathError] = useState<string | undefined>(undefined);
  const [formError, setFormError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  // No draft is kept: the field starts from the selected document's folder every time the
  // dialog opens, so a document lands beside its siblings unless the path is typed over.
  useEffect(() => {
    if (!open) return;
    setPath(folder);
    setPathError(undefined);
    setFormError(null);
  }, [open, folder]);

  const submit = async () => {
    const rel = completeHandbookPath(path);
    // A path that is only a folder names no document: the field starts as one, and completing
    // `decisions/` to `decisions.md` would create a file beside the folder rather than in it.
    if (rel === "" || path.trim().endsWith("/")) {
      setPathError(S.common.requiredField);
      return;
    }
    if (!isHandbookPath(rel)) {
      setPathError(S.company.handbook.pathInvalid);
      return;
    }
    if (existing.has(rel)) {
      setPathError(S.company.handbook.pathExists);
      return;
    }
    setBusy(true);
    setFormError(null);
    try {
      await onCreate(rel);
    } catch (e) {
      setFormError(apiErrorText(e));
    } finally {
      setBusy(false);
    }
  };

  return (
    <Modal
      open={open}
      title={S.company.handbook.newDocument}
      onClose={busy ? () => undefined : onClose}
      footer={
        <>
          <Button size="sm" onClick={onClose} disabled={busy}>
            {S.common.cancel}
          </Button>
          <Button size="sm" variant="primary" disabled={busy} onClick={() => void submit()}>
            {busy ? S.company.handbook.creating : S.common.create}
          </Button>
        </>
      }
    >
      <div className="space-y-3">
        <Input
          label={S.company.handbook.pathField}
          required
          size="sm"
          value={path}
          error={pathError}
          hint={S.company.handbook.pathHint}
          placeholder={S.company.handbook.pathPlaceholder}
          className="font-mono"
          autoFocus
          disabled={busy}
          onChange={(e) => {
            setPath(e.target.value);
            setPathError(undefined);
          }}
          onKeyDown={(e) => {
            if (e.key === "Enter") {
              e.preventDefault();
              void submit();
            }
          }}
        />
        {formError !== null && <ErrorLine message={formError} onRetry={() => void submit()} />}
      </div>
    </Modal>
  );
}

/** The two panes as placeholder bands, until the first listing arrives. */
function HandbookSkeleton() {
  return (
    <div className={PANES_CLASS} aria-busy="true">
      <div className="space-y-2">
        <Skeleton className="h-3 w-16" />
        {[0, 1, 2, 3, 4].map((i) => (
          <Skeleton key={i} className="h-8" />
        ))}
      </div>
      <DocumentSkeleton />
    </div>
  );
}

/** The document pane's placeholder: a title band over three lines. */
function DocumentSkeleton() {
  return (
    <div className="space-y-3" aria-busy="true">
      <Skeleton className="h-6 w-2/3" />
      <Skeleton className="h-4" />
      <Skeleton className="h-4 w-5/6" />
      <Skeleton className="h-4 w-3/4" />
    </div>
  );
}