NotesPanel.tsx 22.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
"use client";

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import {
  X, Plus, Trash2, Save, Send, Search, Eye, Pencil, Users, FolderPlus,
  Bold, Italic, Heading, List, Code, Quote, Link2, Loader2, ChevronDown,
} from "lucide-react";

import {
  listNotes, createNote, updateNote, deleteNote, promoteNote,
  myProjectKbs, createProjectKb, listCollaborators, addCollaborator,
  removeCollaborator, searchProjectUsers,
  type NoteItem, type ProjectKb, type ProjectCollaborator,
} from "@/lib/auth";
import { NoteCategoryLabel, NoteCategoryOrder, NoteStatusLabel, NoteStatusOrder } from "@/lib/noteEnums";
import { usePerms } from "@/lib/usePerms";

type Draft = {
  id?: string;
  title: string;
  content: string;
  category: string;
  tags: string[];
  status: string;
  source: string;
  promotedKbId?: string | null;
};

const EMPTY_DRAFT: Draft = {
  title: "", content: "", category: "project", tags: [], status: "draft", source: "", promotedKbId: null,
};

export default function NotesPanel() {
  const { has } = usePerms();
  const canProject = has("kb:project:manage");

  const [notes, setNotes] = useState<NoteItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [fCategory, setFCategory] = useState("");
  const [fStatus, setFStatus] = useState("");
  const [kw, setKw] = useState("");
  const [kwInput, setKwInput] = useState("");

  const [draft, setDraft] = useState<Draft>(EMPTY_DRAFT);
  const [tagInput, setTagInput] = useState("");
  const [preview, setPreview] = useState(false);
  const [saving, setSaving] = useState(false);
  const [msg, setMsg] = useState<string | null>(null);
  const taRef = useRef<HTMLTextAreaElement | null>(null);

  const [projects, setProjects] = useState<ProjectKb[]>([]);
  const [promoteKb, setPromoteKb] = useState("");
  const [showProjectMgr, setShowProjectMgr] = useState(false);

  const writableProjects = useMemo(
    () => projects.filter((p) => p.access === "owner" || p.access === "editor"),
    [projects]
  );

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const d = await listNotes({ category: fCategory, status: fStatus, keyword: kw });
      setNotes(d.items);
    } finally {
      setLoading(false);
    }
  }, [fCategory, fStatus, kw]);

  const loadProjects = useCallback(async () => {
    if (!canProject) return;
    try {
      const d = await myProjectKbs();
      setProjects(d.items);
    } catch { /* 忽略 */ }
  }, [canProject]);

  useEffect(() => { load(); }, [load]);
  useEffect(() => { loadProjects(); }, [loadProjects]);

  const flash = (m: string) => { setMsg(m); setTimeout(() => setMsg(null), 2500); };

  const selectNote = (n: NoteItem) => {
    setDraft({
      id: n.id, title: n.title, content: n.content, category: n.category,
      tags: n.tags, status: n.status, source: n.source, promotedKbId: n.promotedKbId,
    });
    setPreview(false);
    setPromoteKb("");
  };

  const newDraft = () => { setDraft(EMPTY_DRAFT); setPreview(false); setPromoteKb(""); };

  const onSave = async () => {
    if (!draft.title.trim() && !draft.content.trim()) { flash("标题与正文不能都为空"); return; }
    setSaving(true);
    try {
      const body = {
        title: draft.title, content: draft.content, category: draft.category,
        tags: draft.tags, status: draft.status, source: draft.source,
      };
      const r = draft.id ? await updateNote(draft.id, body) : await createNote(body);
      selectNote(r.item);
      await load();
      flash("已保存");
    } catch (e) { flash((e as Error).message); } finally { setSaving(false); }
  };

  const onDelete = async () => {
    if (!draft.id) { newDraft(); return; }
    if (!confirm("删除这条笔记?(已沉淀的 wiki 页不受影响)")) return;
    try {
      await deleteNote(draft.id);
      newDraft();
      await load();
      flash("已删除");
    } catch (e) { flash((e as Error).message); }
  };

  const onPromote = async () => {
    if (!draft.id) { flash("请先保存笔记再沉淀"); return; }
    if (!promoteKb) { flash("请选择目标项目库"); return; }
    if (!confirm("将这条笔记沉淀(原文直写)到所选项目库,生成一个 wiki 页?")) return;
    setSaving(true);
    try {
      await promoteNote(draft.id, promoteKb);
      await load();
      setDraft((d) => ({ ...d, status: "archived", promotedKbId: promoteKb }));
      flash("已沉淀到项目库");
    } catch (e) { flash((e as Error).message); } finally { setSaving(false); }
  };

  // Markdown 工具条:在光标处插入/包裹语法
  const wrap = (before: string, after = "", placeholder = "") => {
    const ta = taRef.current;
    if (!ta) return;
    const s = ta.selectionStart, e = ta.selectionEnd;
    const val = draft.content;
    const sel = val.slice(s, e) || placeholder;
    const next = val.slice(0, s) + before + sel + after + val.slice(e);
    setDraft((d) => ({ ...d, content: next }));
    requestAnimationFrame(() => {
      ta.focus();
      ta.selectionStart = s + before.length;
      ta.selectionEnd = s + before.length + sel.length;
    });
  };

  const addTag = () => {
    const t = tagInput.trim();
    if (t && !draft.tags.includes(t)) setDraft((d) => ({ ...d, tags: [...d.tags, t] }));
    setTagInput("");
  };

  return (
    <div className="flex h-full flex-col bg-white min-h-0">
      {/* 顶栏 */}
      <div className="flex items-center justify-between px-6 py-4 border-b border-slate-100 shrink-0">
        <div className="flex items-center gap-3">
          <Pencil className="w-5 h-5 text-blue-600" />
          <div>
            <h2 className="text-lg font-bold text-slate-800">知识录入</h2>
            <p className="text-xs text-slate-400">随手记录项目知识、经验与想法,可沉淀到项目库</p>
          </div>
          {msg && <span className="text-sm text-emerald-600 font-medium">{msg}</span>}
        </div>
        {canProject && (
          <button
            onClick={() => setShowProjectMgr((v) => !v)}
            className={`flex items-center gap-1.5 px-3 py-2 text-sm font-semibold rounded-lg ${showProjectMgr ? "bg-blue-50 text-blue-600" : "text-slate-600 bg-slate-50 hover:bg-slate-100"}`}
          >
            <Users className="w-4 h-4" /> 项目库管理
          </button>
        )}
      </div>

      {showProjectMgr && canProject ? (
        <ProjectManager onDone={loadProjects} projects={projects} />
      ) : (
        <div className="flex flex-1 min-h-0">
          {/* 左:列表 + 筛选 */}
          <div className="w-80 border-r border-slate-100 flex flex-col shrink-0">
            <div className="p-3 space-y-2 border-b border-slate-100">
              <button
                onClick={newDraft}
                className="w-full flex items-center justify-center gap-2 px-3 py-2 bg-blue-600 text-white rounded-lg text-sm font-bold hover:bg-blue-700"
              >
                <Plus className="w-4 h-4" /> 新建笔记
              </button>
              <div className="relative">
                <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                <input
                  value={kwInput}
                  onChange={(e) => setKwInput(e.target.value)}
                  onKeyDown={(e) => e.key === "Enter" && setKw(kwInput.trim())}
                  placeholder="搜索标题/正文"
                  className="w-full pl-8 pr-2 py-1.5 bg-slate-50 border border-slate-200 rounded-lg text-sm outline-none focus:border-blue-500"
                />
              </div>
              <div className="flex gap-2">
                <select value={fCategory} onChange={(e) => setFCategory(e.target.value)}
                  className="flex-1 min-w-0 px-2 py-1.5 bg-slate-50 border border-slate-200 rounded-lg text-xs outline-none">
                  <option value="">全部类型</option>
                  {NoteCategoryOrder.map((c) => <option key={c} value={c}>{NoteCategoryLabel[c]}</option>)}
                </select>
                <select value={fStatus} onChange={(e) => setFStatus(e.target.value)}
                  className="flex-1 min-w-0 px-2 py-1.5 bg-slate-50 border border-slate-200 rounded-lg text-xs outline-none">
                  <option value="">全部状态</option>
                  {NoteStatusOrder.map((s) => <option key={s} value={s}>{NoteStatusLabel[s]}</option>)}
                </select>
              </div>
            </div>
            <div className="flex-1 overflow-y-auto">
              {loading ? (
                <div className="p-6 text-center text-slate-400"><Loader2 className="w-5 h-5 animate-spin inline" /></div>
              ) : notes.length === 0 ? (
                <div className="p-6 text-center text-sm text-slate-400">暂无笔记,点「新建笔记」开始</div>
              ) : (
                notes.map((n) => (
                  <button
                    key={n.id}
                    onClick={() => selectNote(n)}
                    className={`w-full text-left px-3 py-2.5 border-b border-slate-50 hover:bg-slate-50 ${draft.id === n.id ? "bg-blue-50" : ""}`}
                  >
                    <div className="flex items-center gap-2">
                      <span className="text-[10px] px-1.5 py-0.5 rounded bg-slate-100 text-slate-500 shrink-0">
                        {NoteCategoryLabel[n.category] || "其他"}
                      </span>
                      <span className="text-sm font-semibold text-slate-700 truncate flex-1 min-w-0">
                        {n.title || "(无标题)"}
                      </span>
                      {n.promotedFileId && <Send className="w-3 h-3 text-emerald-500 shrink-0" />}
                    </div>
                    <div className="text-xs text-slate-400 truncate mt-1">{n.content || ""}</div>
                  </button>
                ))
              )}
            </div>
          </div>

          {/* 右:编辑器 */}
          <div className="flex-1 min-w-0 flex flex-col">
            <div className="p-4 space-y-3 overflow-y-auto flex-1">
              <input
                value={draft.title}
                onChange={(e) => setDraft((d) => ({ ...d, title: e.target.value }))}
                placeholder="标题(可选)"
                className="w-full px-3 py-2 text-lg font-bold border-b border-slate-100 outline-none focus:border-blue-500"
              />
              {/* 分类维度 */}
              <div className="flex flex-wrap items-center gap-2">
                <select value={draft.category} onChange={(e) => setDraft((d) => ({ ...d, category: e.target.value }))}
                  className="px-2 py-1.5 bg-slate-50 border border-slate-200 rounded-lg text-sm outline-none">
                  {NoteCategoryOrder.map((c) => <option key={c} value={c}>{NoteCategoryLabel[c]}</option>)}
                </select>
                <select value={draft.status} onChange={(e) => setDraft((d) => ({ ...d, status: e.target.value }))}
                  className="px-2 py-1.5 bg-slate-50 border border-slate-200 rounded-lg text-sm outline-none">
                  {NoteStatusOrder.map((s) => <option key={s} value={s}>{NoteStatusLabel[s]}</option>)}
                </select>
                <input
                  value={draft.source}
                  onChange={(e) => setDraft((d) => ({ ...d, source: e.target.value }))}
                  placeholder="来源(可选)"
                  className="px-2 py-1.5 bg-slate-50 border border-slate-200 rounded-lg text-sm outline-none w-40"
                />
              </div>
              {/* 标签 */}
              <div className="flex flex-wrap items-center gap-1.5">
                {draft.tags.map((t) => (
                  <span key={t} className="flex items-center gap-1 text-xs bg-blue-50 text-blue-600 px-2 py-1 rounded-full">
                    {t}
                    <button onClick={() => setDraft((d) => ({ ...d, tags: d.tags.filter((x) => x !== t) }))}>
                      <X className="w-3 h-3" />
                    </button>
                  </span>
                ))}
                <input
                  value={tagInput}
                  onChange={(e) => setTagInput(e.target.value)}
                  onKeyDown={(e) => e.key === "Enter" && (e.preventDefault(), addTag())}
                  placeholder="+ 标签回车"
                  className="text-xs px-2 py-1 border border-dashed border-slate-300 rounded-full outline-none w-24"
                />
              </div>
              {/* 工具条 */}
              <div className="flex items-center gap-1 border border-slate-200 rounded-lg p-1 bg-slate-50">
                <TB onClick={() => wrap("**", "**", "加粗")}><Bold className="w-4 h-4" /></TB>
                <TB onClick={() => wrap("*", "*", "斜体")}><Italic className="w-4 h-4" /></TB>
                <TB onClick={() => wrap("## ", "", "标题")}><Heading className="w-4 h-4" /></TB>
                <TB onClick={() => wrap("- ", "", "列表项")}><List className="w-4 h-4" /></TB>
                <TB onClick={() => wrap("`", "`", "代码")}><Code className="w-4 h-4" /></TB>
                <TB onClick={() => wrap("> ", "", "引用")}><Quote className="w-4 h-4" /></TB>
                <TB onClick={() => wrap("[", "](url)", "链接文字")}><Link2 className="w-4 h-4" /></TB>
                <div className="flex-1" />
                <TB onClick={() => setPreview((v) => !v)} active={preview}>
                  <Eye className="w-4 h-4" /> <span className="text-xs">{preview ? "编辑" : "预览"}</span>
                </TB>
              </div>
              {/* 正文 */}
              {preview ? (
                <div className="prose prose-sm max-w-none min-h-[240px] p-3 border border-slate-100 rounded-lg overflow-auto">
                  <ReactMarkdown remarkPlugins={[remarkGfm]}>{draft.content || "(空)"}</ReactMarkdown>
                </div>
              ) : (
                <textarea
                  ref={taRef}
                  value={draft.content}
                  onChange={(e) => setDraft((d) => ({ ...d, content: e.target.value }))}
                  placeholder="记录你脑海中的知识、经验、想法…(支持 Markdown)"
                  className="w-full min-h-[240px] p-3 border border-slate-200 rounded-lg text-sm outline-none focus:border-blue-500 font-mono leading-relaxed resize-y"
                />
              )}
            </div>

            {/* 底部动作栏 */}
            <div className="flex items-center gap-2 px-4 py-3 border-t border-slate-100 shrink-0 flex-wrap">
              <button onClick={onSave} disabled={saving}
                className="flex items-center gap-1.5 px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-bold hover:bg-blue-700 disabled:opacity-50">
                <Save className="w-4 h-4" /> 保存
              </button>
              <button onClick={onDelete}
                className="flex items-center gap-1.5 px-3 py-2 text-sm text-slate-500 hover:text-red-500 hover:bg-red-50 rounded-lg">
                <Trash2 className="w-4 h-4" /> 删除
              </button>
              <div className="flex-1" />
              {/* 沉淀到项目库 */}
              {canProject ? (
                <div className="flex items-center gap-2">
                  <select value={promoteKb} onChange={(e) => setPromoteKb(e.target.value)}
                    className="px-2 py-2 bg-slate-50 border border-slate-200 rounded-lg text-sm outline-none max-w-48">
                    <option value="">选择项目库…</option>
                    {writableProjects.map((p) => (
                      <option key={p.id} value={p.id}>{p.kbName}{p.isOwner ? "(我的)" : ""}</option>
                    ))}
                  </select>
                  <button onClick={onPromote} disabled={saving || !draft.id}
                    className="flex items-center gap-1.5 px-4 py-2 bg-emerald-600 text-white rounded-lg text-sm font-bold hover:bg-emerald-700 disabled:opacity-50">
                    <Send className="w-4 h-4" /> 沉淀到 Wiki
                  </button>
                </div>
              ) : (
                <span className="text-xs text-slate-400">(无项目库权限,无法沉淀)</span>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function TB({ children, onClick, active }: { children: React.ReactNode; onClick: () => void; active?: boolean }) {
  return (
    <button
      onClick={onClick}
      className={`flex items-center gap-1 px-2 py-1 rounded hover:bg-white text-slate-600 ${active ? "bg-white text-blue-600" : ""}`}
    >
      {children}
    </button>
  );
}

/* ============ 项目库管理:创建 + 协作者 ============ */
function ProjectManager({ projects, onDone }: { projects: ProjectKb[]; onDone: () => void }) {
  const [name, setName] = useState("");
  const [busy, setBusy] = useState(false);
  const [expandKb, setExpandKb] = useState<string | null>(null);
  const owned = useMemo(() => projects.filter((p) => p.isOwner), [projects]);

  const create = async () => {
    if (!name.trim()) return;
    setBusy(true);
    try { await createProjectKb(name.trim()); setName(""); await onDone(); }
    catch (e) { alert((e as Error).message); } finally { setBusy(false); }
  };

  return (
    <div className="flex-1 overflow-y-auto p-6 space-y-6">
      <div>
        <h3 className="text-sm font-bold text-slate-700 mb-2">新建项目库</h3>
        <div className="flex gap-2 max-w-md">
          <input value={name} onChange={(e) => setName(e.target.value)}
            placeholder="项目库名称,如「谈客话术库」" onKeyDown={(e) => e.key === "Enter" && create()}
            className="flex-1 px-3 py-2 bg-slate-50 border border-slate-200 rounded-lg text-sm outline-none focus:border-blue-500" />
          <button onClick={create} disabled={busy}
            className="flex items-center gap-1.5 px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-bold hover:bg-blue-700 disabled:opacity-50">
            <FolderPlus className="w-4 h-4" /> 创建
          </button>
        </div>
        <p className="text-xs text-slate-400 mt-1">创建者即 owner(读写 + 管协作者);协作者按人授 editor(读写)/ reader(只读),类似 git 协作。</p>
      </div>

      <div>
        <h3 className="text-sm font-bold text-slate-700 mb-2">我创建的项目库({owned.length})</h3>
        {owned.length === 0 ? (
          <div className="text-sm text-slate-400">还没有项目库</div>
        ) : (
          <div className="space-y-2">
            {owned.map((p) => (
              <div key={p.id} className="border border-slate-200 rounded-lg">
                <button onClick={() => setExpandKb(expandKb === p.id ? null : p.id)}
                  className="w-full flex items-center justify-between px-4 py-2.5 hover:bg-slate-50">
                  <span className="font-semibold text-slate-700 text-sm">{p.kbName}</span>
                  <ChevronDown className={`w-4 h-4 text-slate-400 transition-transform ${expandKb === p.id ? "rotate-180" : ""}`} />
                </button>
                {expandKb === p.id && <CollaboratorEditor kbId={p.id} />}
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function CollaboratorEditor({ kbId }: { kbId: string }) {
  const [rows, setRows] = useState<ProjectCollaborator[]>([]);
  const [q, setQ] = useState("");
  const [results, setResults] = useState<{ id: string; name: string; username: string }[]>([]);
  const [access, setAccess] = useState<"editor" | "reader">("editor");

  const load = useCallback(async () => {
    try { const d = await listCollaborators(kbId); setRows(d.items); } catch { /* */ }
  }, [kbId]);
  useEffect(() => { load(); }, [load]);

  useEffect(() => {
    const t = setTimeout(async () => {
      if (!q.trim()) { setResults([]); return; }
      try { const d = await searchProjectUsers(q.trim()); setResults(d.items); } catch { /* */ }
    }, 300);
    return () => clearTimeout(t);
  }, [q]);

  const add = async (userId: string) => {
    try { await addCollaborator(kbId, userId, access); setQ(""); setResults([]); await load(); }
    catch (e) { alert((e as Error).message); }
  };
  const remove = async (userId: string) => {
    try { await removeCollaborator(kbId, userId); await load(); } catch (e) { alert((e as Error).message); }
  };

  return (
    <div className="px-4 pb-4 pt-1 border-t border-slate-100 space-y-3">
      <div className="flex items-center gap-2">
        <div className="relative flex-1">
          <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
          <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="搜索同事姓名/账号添加协作者"
            className="w-full pl-8 pr-2 py-1.5 bg-slate-50 border border-slate-200 rounded-lg text-sm outline-none focus:border-blue-500" />
          {results.length > 0 && (
            <div className="absolute z-10 mt-1 w-full bg-white border border-slate-200 rounded-lg shadow-lg max-h-48 overflow-auto">
              {results.map((u) => (
                <button key={u.id} onClick={() => add(u.id)}
                  className="w-full text-left px-3 py-2 hover:bg-blue-50 text-sm">
                  {u.name} <span className="text-slate-400 text-xs">{u.username}</span>
                </button>
              ))}
            </div>
          )}
        </div>
        <select value={access} onChange={(e) => setAccess(e.target.value as "editor" | "reader")}
          className="px-2 py-1.5 bg-slate-50 border border-slate-200 rounded-lg text-sm outline-none">
          <option value="editor">读写</option>
          <option value="reader">只读</option>
        </select>
      </div>
      {rows.length === 0 ? (
        <div className="text-xs text-slate-400">暂无协作者</div>
      ) : (
        <div className="space-y-1">
          {rows.map((r) => (
            <div key={r.grantId} className="flex items-center justify-between text-sm px-2 py-1.5 bg-slate-50 rounded-lg">
              <span className="text-slate-700">{r.userName}
                <span className="ml-2 text-xs text-slate-400">{r.access === "editor" ? "读写" : "只读"}</span>
              </span>
              <button onClick={() => remove(r.userId)} className="text-slate-400 hover:text-red-500">
                <Trash2 className="w-4 h-4" />
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}