SPB Git

Repository Public

NotesPanel.tsx 13.8 KB 260 lines tsx

1"use client";2// Maintenance notes for a window / occurrence or for a node. Owned by the Maintenance screen; the node detail3// screen embeds it with `scope={{ nodeId }}`. Notes are plain text: bodies are rendered as text nodes and <a>.4import Link from "next/link";5import { useQueryClient } from "@tanstack/react-query";6import { useEffect, useId, useMemo, useRef, useState } from "react";7import { apiDelete, apiPatch, apiPost, type Schemas } from "@/api/client";8import { invalidatePaths, useApiList } from "@/api/query";9import { NodeLink } from "@/features/shared/nodes";10import { useI18n } from "@/i18n";11import { linkify } from "@/lib/linkify";12import { useSession } from "@/shell/session";13import { Badge, Button, Checkbox, ConfirmDialog, DataStamp, EmptyState, ErrorState, ForbiddenState, Icon, IconButton, Kbd, LoadMore, Skeleton, TextAreaField, TextField, useErrorMessage, useToast } from "@/ui";14import { splitHighlight } from "./calendar";1516export interface NotesScope {17  nodeId?: string;18  windowId?: string;19  occurrence?: string;20}21type Note = Schemas["MaintenanceNote"];22const MAX = 20000;2324/** Plain-text body: preserved line breaks, auto-linked http(s) URLs, search matches marked. Never HTML. */25export function NoteBody({ text, query }: { text: string; query?: string }) {26  const segments = useMemo(() => linkify(text), [text]);27  return (28    <span className="pre mt-note-body">29      {segments.map((s, i) =>30        s.kind === "link" ? (31          <a key={i} href={s.href} target="_blank" rel="noopener noreferrer nofollow">{s.value}</a>32        ) : (33          <span key={i}>{splitHighlight(s.value, query ?? "").map((p, j) => (p.match ? <mark key={j}>{p.text}</mark> : p.text))}</span>34        ),35      )}36    </span>37  );38}3940function useDebounced(value: string, ms: number): string {41  const [v, setV] = useState(value);42  useEffect(() => {43    const id = window.setTimeout(() => setV(value), ms);44    return () => window.clearTimeout(id);45  }, [value, ms]);46  return v;47}4849const isTextTarget = (el: EventTarget | null): boolean => {50  if (!(el instanceof HTMLElement)) return false;51  return el.isContentEditable || el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.tagName === "SELECT";52};5354/**55 * Notes panel. With `scope.windowId` (optionally one `occurrence`) or `scope.nodeId` it lists and creates notes56 * for that target; with an empty scope it is a read/search list across every window and node (`showContext`).57 * Keyboard: `n` focuses the note input (when focus is not in a field), ⌘/Ctrl+Enter saves.58 */59export function NotesPanel({ scope, compact, showContext }: { scope: NotesScope; compact?: boolean; showContext?: boolean }) {60  const { t, tn, fmt } = useI18n();61  const qc = useQueryClient();62  const session = useSession();63  const toast = useToast();64  const explain = useErrorMessage();65  const headingId = useId();66  const canWrite = session.can("maintenance.write");67  const canRead = session.can("maintenance.read");68  const canCreate = canWrite && (!!scope.windowId || !!scope.nodeId);6970  const [search, setSearch] = useState("");71  const q = useDebounced(search.trim(), 250);72  const [draft, setDraft] = useState("");73  const [pin, setPin] = useState(false);74  const [saving, setSaving] = useState(false);75  const [editing, setEditing] = useState<{ id: string; body: string } | null>(null);76  const [deleting, setDeleting] = useState<Note | null>(null);77  const [busyId, setBusyId] = useState<string | null>(null);78  const [status, setStatus] = useState("");79  const root = useRef<HTMLElement>(null);8081  const list = useApiList(82    "/maintenance/notes",83    { query: { limit: compact ? 20 : 50, ...(scope.windowId ? { window_id: scope.windowId } : {}), ...(scope.nodeId ? { node_id: scope.nodeId } : {}), ...(scope.occurrence ? { occurrence: scope.occurrence } : {}), ...(q ? { q } : {}) } },84    { enabled: canRead },85  );86  // the server already orders pinned first then newest; keep that contract even after local cache patches87  const notes = useMemo(() => [...list.items].sort((a, b) => Number(b.pinned) - Number(a.pinned) || Date.parse(b.created_at) - Date.parse(a.created_at)), [list.items]);8889  // quick-add shortcut: `n` focuses the input of the first visible panel90  useEffect(() => {91    if (!canCreate) return;92    const onKey = (e: KeyboardEvent) => {93      if (e.key !== "n" || e.metaKey || e.ctrlKey || e.altKey || e.defaultPrevented || isTextTarget(e.target)) return;94      if (document.querySelector("dialog[open]") && !root.current?.closest("dialog[open]")) return;95      const el = root.current?.querySelector<HTMLTextAreaElement>('textarea[data-testid="note-input"]');96      if (!el || el.offsetParent === null) return;97      e.preventDefault();98      el.focus();99      el.scrollIntoView({ block: "nearest" });100    };101    window.addEventListener("keydown", onKey);102    return () => window.removeEventListener("keydown", onKey);103  }, [canCreate]);104105  const refresh = () => invalidatePaths(qc, "/maintenance");106  const fail = (e: unknown) => toast({ tone: "critical", ...explain(e) });107108  const create = async () => {109    const body = draft.trim();110    if (!body || saving || !canCreate) return;111    setSaving(true);112    try {113      await apiPost("/maintenance/notes", { body: { body, pinned: pin, ...(scope.windowId ? { window_id: scope.windowId } : {}), ...(scope.nodeId ? { node_id: scope.nodeId } : {}), ...(scope.occurrence ? { occurrence: scope.occurrence } : {}) } });114      setDraft("");115      setPin(false);116      setStatus(t("maintenance.notes.added"));117      await refresh();118    } catch (e) {119      fail(e);120    } finally {121      setSaving(false);122    }123  };124  const saveEdit = async () => {125    if (!editing) return;126    const body = editing.body.trim();127    if (!body) return;128    setBusyId(editing.id);129    try {130      await apiPatch("/maintenance/notes/{id}", { path: { id: editing.id }, body: { body } });131      setEditing(null);132      setStatus(t("maintenance.notes.updated"));133      await refresh();134    } catch (e) {135      fail(e);136    } finally {137      setBusyId(null);138    }139  };140  const togglePin = async (n: Note) => {141    setBusyId(n.id);142    try {143      await apiPatch("/maintenance/notes/{id}", { path: { id: n.id }, body: { pinned: !n.pinned } });144      setStatus(n.pinned ? t("maintenance.notes.unpinned") : t("maintenance.notes.pinnedDone"));145      await refresh();146    } catch (e) {147      fail(e);148    } finally {149      setBusyId(null);150    }151  };152  const remove = async () => {153    if (!deleting) return;154    setBusyId(deleting.id);155    try {156      await apiDelete("/maintenance/notes/{id}", { path: { id: deleting.id } });157      setDeleting(null);158      setStatus(t("maintenance.notes.deleted"));159      await refresh();160    } catch (e) {161      fail(e);162    } finally {163      setBusyId(null);164    }165  };166167  const myId = session.me?.user.id;168  return (169    <section className="mt-notes" aria-labelledby={headingId} data-testid="notes-panel" ref={root}>170      <div className="section-head">171        <h2 id={headingId}>{scope.occurrence ? t("maintenance.notes.titleOccurrence") : t("maintenance.notes.title")}{list.ready ? <span className="mcc-count mt-notes-count">{notes.length}{list.hasMore ? "+" : ""}</span> : null}</h2>172        <div className="row-wrap">173          {list.ready ? <DataStamp at={list.updatedAt} /> : null}174          <TextField label={t("maintenance.notes.search")} hideLabel placeholder={t("maintenance.notes.search")} icon="search" type="search" value={search} onChange={setSearch} data-testid="note-search" />175        </div>176      </div>177178      {canCreate ? (179        <form className="mt-note-form" onSubmit={(e) => { e.preventDefault(); void create(); }}>180          <TextAreaField181            label={t("maintenance.notes.add")}182            hint={<>{t("maintenance.notes.plainHint")} <Kbd>n</Kbd> {t("maintenance.notes.shortcutFocus")} · <Kbd>⌘/Ctrl</Kbd>+<Kbd>↵</Kbd> {t("maintenance.notes.shortcutSave")}</>}183            value={draft}184            onChange={setDraft}185            maxLength={MAX}186            rows={compact ? 2 : 3}187            placeholder={t("maintenance.notes.placeholder")}188            data-testid="note-input"189            aria-keyshortcuts="n"190            onKeyDown={(e) => { if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); void create(); } }}191          />192          <div className="row-between">193            <Checkbox label={t("maintenance.notes.pinNew")} checked={pin} onChange={setPin} />194            <Button type="submit" variant="primary" size="sm" icon="note" loading={saving} disabled={draft.trim() === ""} data-testid="note-save">{t("maintenance.notes.save")}</Button>195          </div>196        </form>197      ) : canRead && !showContext ? <p className="mcc-hint">{t("maintenance.notes.readOnly")}</p> : null}198199      <span className="sr-only" role="status" aria-live="polite">{status}</span>200201      {!canRead ? <ForbiddenState permission="maintenance.read" /> : null}202      {list.error && !list.ready ? <ErrorState error={list.error} onRetry={list.refetch} compact /> : null}203      {list.isLoading ? <div className="stack" role="status" aria-label={t("common.loading")}><Skeleton width="80" /><Skeleton width="60" /></div> : null}204      {list.ready && notes.length === 0 ? (205        <EmptyState compact icon="note" title={q ? t("maintenance.notes.noMatch", { query: q }) : t("maintenance.notes.empty")}>{q ? undefined : canCreate ? t("maintenance.notes.emptyHintWrite") : t("maintenance.notes.emptyHint")}</EmptyState>206      ) : null}207      {q && list.ready && notes.length > 0 ? <p className="mcc-hint" role="status">{tn("maintenance.notes.matches", notes.length)}</p> : null}208209      <ul className="mt-note-list">210        {notes.map((n) => {211          const mine = !!myId && n.author_id === myId;212          const isEditing = editing?.id === n.id;213          return (214            <li key={n.id} className={n.pinned ? "mt-note pinned" : "mt-note"} data-testid="note-item" data-pinned={n.pinned}>215              <div className="mt-note-head">216                <span className="row-wrap">217                  <strong>{n.author_display_name}</strong>218                  <time className="faint num" dateTime={n.created_at} title={fmt.dateTime(n.created_at, { seconds: true })}>{fmt.relative(n.created_at)} · {fmt.dateTime(n.created_at)}</time>219                  {n.edited_at ? <span className="mt-note-edited" title={fmt.dateTime(n.edited_at, { seconds: true })} data-testid="note-edited"><Icon name="edit" size={12} />{t("maintenance.notes.edited", { time: fmt.relative(n.edited_at) })}</span> : null}220                  {n.pinned ? <Badge tone="info" icon="pin">{t("maintenance.notes.pinned")}</Badge> : null}221                </span>222                {canWrite ? (223                  <span className="row mt-note-actions">224                    <IconButton size="sm" icon="pin" label={n.pinned ? t("maintenance.notes.unpin") : t("maintenance.notes.pin")} aria-pressed={n.pinned} loading={busyId === n.id && !isEditing && deleting?.id !== n.id} onClick={() => void togglePin(n)} data-testid="note-pin" />225                    {mine ? <IconButton size="sm" icon="edit" label={t("maintenance.notes.edit")} onClick={() => setEditing({ id: n.id, body: n.body })} data-testid="note-edit" /> : null}226                    {mine || session.can("alerts.manage") ? <IconButton size="sm" icon="trash" label={t("maintenance.notes.delete")} onClick={() => setDeleting(n)} data-testid="note-delete" /> : null}227                  </span>228                ) : null}229              </div>230              {showContext || (!scope.occurrence && n.occurrence) || (scope.windowId && n.node_id) || (scope.nodeId && n.window_id) ? (231                <div className="mt-note-context row-wrap">232                  {n.window_id && n.window_id !== scope.windowId ? <Link href={`/maintenance/${n.window_id}${n.occurrence ? `?occurrence=${encodeURIComponent(n.occurrence)}` : ""}`} className="row"><Icon name="maintenance" size={13} />{t("maintenance.notes.contextWindow")}</Link> : null}233                  {n.occurrence && !scope.occurrence ? <span className="faint num">{t("maintenance.notes.contextOccurrence", { time: fmt.dateTime(n.occurrence) })}</span> : null}234                  {n.node_id && n.node_id !== scope.nodeId ? <span className="row"><Icon name="nodes" size={13} /><NodeLink id={n.node_id} alias={n.node_alias} /></span> : null}235                </div>236              ) : null}237              {isEditing ? (238                <form className="mt-note-form" onSubmit={(e) => { e.preventDefault(); void saveEdit(); }}>239                  <TextAreaField label={t("maintenance.notes.editLabel")} hideLabel value={editing.body} onChange={(body) => setEditing({ id: n.id, body })} maxLength={MAX} rows={4} autoFocus data-testid="note-edit-input"240                    onKeyDown={(e) => { if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); void saveEdit(); } else if (e.key === "Escape") { e.stopPropagation(); setEditing(null); } }} />241                  <div className="row">242                    <Button type="submit" size="sm" variant="primary" loading={busyId === n.id} disabled={editing.body.trim() === "" || editing.body.trim() === n.body} data-testid="note-edit-save">{t("common.save")}</Button>243                    <Button size="sm" onClick={() => setEditing(null)}>{t("common.cancel")}</Button>244                  </div>245                </form>246              ) : (247                <p><NoteBody text={n.body} query={q} /></p>248              )}249            </li>250          );251        })}252      </ul>253      <LoadMore hasMore={list.hasMore} loading={list.loadingMore} onMore={list.loadMore} />254255      <ConfirmDialog open={deleting !== null} onClose={() => setDeleting(null)} onConfirm={() => void remove()} danger busy={busyId !== null && busyId === deleting?.id} title={t("maintenance.notes.deleteTitle")}256        body={deleting ? t("maintenance.notes.deleteBody", { author: deleting.author_display_name, time: fmt.dateTime(deleting.created_at) }) : undefined} confirmLabel={t("maintenance.notes.delete")} />257    </section>258  );259}260
Files main
Menu

Theme