'use client' import { useMemo, useState } from 'react' import { useTranslation } from 'react-i18next' import { catalogTranslate, useTopicSourceLibrary, sourceRequest, type SourceCandidate, } from '@/hooks/useTopicSourceLibrary' import { scopedUrl } from '@/lib/workspace-scope' import PickerShell from '@/components/common/PickerShell' import type { NotePage } from '@/lib/notes-api' export default function NoteSourcePicker({ onClose, onInsert, onKnowledge, }: { onClose: () => void onInsert: (title: string, markdown: string, url: string, id: string) => void onKnowledge: (name: string, workspace: string) => void }) { const { t, i18n } = useTranslation() const zh = i18n.language.startsWith('zh') const tr = useMemo(() => catalogTranslate(t, zh), [t, zh]) const { library, loading } = useTopicSourceLibrary(tr) const [query, setQuery] = useState('') const [busy, setBusy] = useState(false) const [error, setError] = useState('') const items = [...library.drafts, ...library.chats, ...library.knowledgeBases].filter( row => row.available && row.label.toLowerCase().includes(query.toLowerCase()) ) // Only these three kinds feed this picker, so wait on them rather than the // slow question-bank request the shared hook also fires. const pending = library.loadingKinds ? library.loadingKinds.some(kind => ['drafts', 'chats', 'knowledgeBases'].includes(kind)) : loading const select = async (row: SourceCandidate) => { setBusy(true) try { if (row.kind === 'knowledge_base') { onKnowledge(row.sourceId, row.content_workspace_id ?? '') onClose() return } let text = row.excerpt || row.detail if (row.kind === 'cowriter') { const page = await sourceRequest( `/api/documents/${row.sourceId}`, row.content_workspace_id ) text = page.content } else if (row.kind === 'chat') { const session = await sourceRequest<{ messages: { role: string; content: unknown }[] }>( `/api/sessions/${row.sourceId}`, row.content_workspace_id ) text = (session.messages || []) .filter(m => ['user', 'assistant'].includes(m.role)) .map( m => `${m.role === 'user' ? t('Question') : t('Answer')}\n\n${String(m.content || '')}` ) .join('\n\n') .slice(0, 180000) } const path = row.kind === 'cowriter' ? `/co-writer/${row.sourceId}` : `/chat/${row.sourceId}` onInsert(row.label, text, scopedUrl(path, row.content_workspace_id), row.sourceId) onClose() } catch (err) { setError(String(err)) } finally { setBusy(false) } } return (

{t('Reference a source')}

setQuery(e.target.value)} />
{pending && items.length === 0 ? (

…

) : ( items.map(row => ( )) )}
{error && (

{error}

)}
) }