import {useEffect,useState,type FormEvent} from 'react'; import type {ExploreEntry} from '@/lib/explore'; import type {Tag} from '@/lib/model'; import {TagInput} from './TagInput'; import {NoteMarkdown} from './NoteMarkdown'; export function NoteEditor({entry,onSaved,onCancel}:{entry:ExploreEntry;onSaved:(entry:ExploreEntry)=>void;onCancel:()=>void}){ const [title,setTitle]=useState(entry.title),[description,setDescription]=useState(entry.description),[markdown,setMarkdown]=useState(entry.editableMarkdown||''); const [allTags,setAllTags]=useState([]),[selected,setSelected]=useState([]),[revision,setRevision]=useState(''); const [loading,setLoading]=useState(true),[busy,setBusy]=useState(false),[tagBusy,setTagBusy]=useState(false),[error,setError]=useState(''); useEffect(()=>{let live=true;void(async()=>{try{const res=await fetch('/api/notes/'+entry.id);const data=await res.json();if(!res.ok)throw Error(data.error||'无法读取笔记');if(live){setTitle(data.entry.title);setDescription(data.entry.description);setMarkdown(data.entry.editableMarkdown);setRevision(data.entry.revision);setAllTags(data.tags);setSelected(data.tags.filter((t:Tag)=>[...data.entry.categories,...(data.entry.systemTags||[]).map((s:Tag)=>s.name)].some((name:string)=>name.toLocaleLowerCase()===t.name.toLocaleLowerCase())).map((t:Tag)=>t.id));}}catch(e){if(live)setError(e instanceof Error?e.message:'读取失败');}finally{if(live)setLoading(false)}})();return()=>{live=false}},[entry.id]); async function save(e:FormEvent){e.preventDefault();if(busy||loading||tagBusy||!revision)return;setBusy(true);setError('');try{const res=await fetch('/api/notes/'+entry.id,{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({title,description,markdown,tags:selected,revision})});const data=await res.json();if(!res.ok)throw Error(data.error||'保存失败');onSaved(data.entry);}catch(e){setError(e instanceof Error?e.message:'保存失败');}finally{setBusy(false)}} return

编辑笔记

{loading&&

正在读取最新内容…

}
setTitle(e.target.value)}/>