'use client'
import dynamic from 'next/dynamic'
import Link from 'next/link'
import { useCallback, useEffect, useRef, useState } from 'react'
import { useRouter } from 'next/navigation'
import { useTranslation } from 'react-i18next'
import { ChevronLeft, Pin, Download, PanelRight, FolderTree, X, Bookmark } from 'lucide-react'
import {
getNote,
saveNote,
listNotes,
createNote,
getSuggestions,
reviewSuggestion,
noteRequest,
type NoteBlock,
type NotePage,
type NoteSummary,
type NoteSuggestion,
} from '@/lib/notes-api'
import { exportCoWriterDocx } from '@/lib/co-writer-api'
import { notifyCoWriterChanged } from '@/lib/co-writer-events'
import { browserStorage } from '@/shared/storage'
import { useAuthStatus } from '@/hooks/useAuthStatus'
import Tooltip from '@/shared/ui/Tooltip'
import { learningMode, type NoteAIRequest } from '../model/ai-request'
import { researchOutline } from '../model/research'
import type { NoteEditorHandle } from './NoteEditor'
import NotePageTree from './NotePageTree'
import { pageDescendants } from '../model/page-tree'
const Editor = dynamic(() => import('./NoteEditor'), {
ssr: false,
loading: () =>
…
,
})
const Companion = dynamic(() => import('./NoteCompanion'), { ssr: false })
const SourcePicker = dynamic(() => import('./NoteSourcePicker'), { ssr: false })
const FavoritesPicker = dynamic(() => import('./NoteFavoritesPicker'), { ssr: false })
export default function NoteWorkspace({
docId,
embedded = false,
}: {
docId: string
embedded?: boolean
}) {
const { t } = useTranslation()
const router = useRouter()
const auth = useAuthStatus()
const owner =
auth.statusAvailable && !auth.loading ? (auth.enabled ? auth.userId : 'local') : null
const [mutating, setMutating] = useState(false)
const [page, setPage] = useState(null)
const [pages, setPages] = useState([])
const [error, setError] = useState('')
const [reviewErrors, setReviewErrors] = useState>({})
const [status, setStatus] = useState('Saved')
const [companion, setCompanion] = useState(false)
const [tree, setTreeOpen] = useState(false)
const setTree = (open: boolean) => {
setTreeOpen(open)
if (owner) browserStorage.writeRaw('local', `deeptutor.notes.tree:${owner}`, String(open))
}
const [sources, setSources] = useState(false)
const [favorites, setFavorites] = useState(false)
const [suggestions, setSuggestions] = useState([])
const [request, setRequest] = useState(null)
const [backlinks, setBacklinks] = useState([])
const [recovery, setRecovery] = useState<{ title: string; blocks: NoteBlock[] } | null>(null)
const editor = useRef(null)
const latest = useRef(null)
const version = useRef(0)
const savedVersion = useRef(0)
const inflight = useRef | null>(null)
const timer = useRef | null>(null)
const root = useRef(null)
const draftKey = owner ? `deeptutor.notes.draft:${owner}:${docId}` : null
const refreshSuggestions = useCallback(() => {
void getSuggestions(docId)
.then(r => {
const pending = r.suggestions.filter(s => s.status === 'pending')
setSuggestions(previous =>
JSON.stringify(previous) === JSON.stringify(pending) ? previous : pending
)
})
.catch(e => setError(String(e)))
}, [docId])
const refreshPages = useCallback(() => {
void listNotes()
.then(r => setPages(r.documents))
.catch(e => setError(String(e)))
}, [])
const persistDraft = useCallback(() => {
if (draftKey && latest.current)
browserStorage.writeRaw(
'local',
draftKey,
JSON.stringify({
title: latest.current.title,
blocks: latest.current.blocks,
revision: latest.current.revision,
})
)
}, [draftKey])
const flush = useCallback(async () => {
if (inflight.current) await inflight.current
if (savedVersion.current === version.current || !latest.current) return
const save = async () => {
while (savedVersion.current !== version.current && latest.current) {
const snapshot = latest.current
const at = version.current
setStatus('Saving…')
const result = await saveNote(docId, {
title: snapshot.title,
blocks: snapshot.blocks,
expected_revision: snapshot.revision,
})
latest.current = { ...latest.current, revision: result.revision, content: result.content }
savedVersion.current = at
if (version.current === at) {
if (draftKey) browserStorage.removeRaw('local', draftKey)
setStatus('Saved')
} else persistDraft()
setPage(current =>
current ? { ...current, revision: result.revision, content: result.content } : current
)
setPages(current =>
current.map(p =>
p.id === docId ? { ...p, title: snapshot.title, revision: result.revision } : p
)
)
notifyCoWriterChanged()
}
}
inflight.current = save()
try {
await inflight.current
setError('')
} catch (err) {
persistDraft()
setStatus('Save failed')
setError(err instanceof Error ? err.message : String(err))
throw err
} finally {
inflight.current = null
}
}, [docId, draftKey, persistDraft])
const changed = useCallback(
(patch: Partial) => {
if (!latest.current) return
if (patch.blocks && JSON.stringify(patch.blocks) === JSON.stringify(latest.current.blocks))
return
latest.current = { ...latest.current, ...patch }
// Keep the editor's remount snapshot current too. Updating only the ref
// leaves initialContent stale after a lazy component reload/remount.
setPage(current => (current ? { ...current, ...patch } : current))
version.current++
persistDraft()
setStatus('Unsaved changes')
if (timer.current) clearTimeout(timer.current)
timer.current = setTimeout(() => {
void flush().catch(() => {})
}, 900)
},
[flush, persistDraft]
)
useEffect(() => {
if (!draftKey) return
let cancelled = false
void getNote(docId)
.then(doc => {
if (cancelled) return
const raw = browserStorage.readRaw('local', draftKey)
if (raw) {
try {
const draft = JSON.parse(raw)
if (Array.isArray(draft.blocks)) {
if (draft.revision === doc.revision) {
doc = { ...doc, title: draft.title, blocks: draft.blocks }
version.current++
} else setRecovery(draft)
}
} catch {
/* Ignore invalid recovery data, never overwrite the server page. */
}
}
latest.current = doc
setPage(doc)
setTreeOpen(browserStorage.readRaw('local', `deeptutor.notes.tree:${owner}`) === 'true')
if (browserStorage.readRaw('local', `deeptutor.notes.chat:${owner}:${docId}:generation`))
setCompanion(true)
refreshPages()
refreshSuggestions()
void noteRequest<{ pages: NoteSummary[] }>(`/${docId}/backlinks`).then(r => {
if (!cancelled) setBacklinks(r.pages)
})
})
.catch(err => setError(String(err)))
return () => {
cancelled = true
if (timer.current) clearTimeout(timer.current)
}
}, [docId, draftKey, owner, refreshPages, refreshSuggestions])
useEffect(() => {
const onUnload = (e: BeforeUnloadEvent) => {
if (version.current !== savedVersion.current) {
e.preventDefault()
e.returnValue = ''
}
}
window.addEventListener('beforeunload', onUnload)
return () => window.removeEventListener('beforeunload', onUnload)
}, [])
useEffect(() => {
const el = root.current
const showSources = () => setSources(true)
const showFavorites = () => setFavorites(true)
el?.addEventListener('note-sources', showSources)
el?.addEventListener('note-favorites', showFavorites)
const saveBeforeSwitch = (e: Event) => {
;(e as CustomEvent[]>).detail.push(flush())
}
window.addEventListener('deeptutor:before-workspace-switch', saveBeforeSwitch)
return () => {
el?.removeEventListener('note-sources', showSources)
el?.removeEventListener('note-favorites', showFavorites)
window.removeEventListener('deeptutor:before-workspace-switch', saveBeforeSwitch)
}
}, [flush])
const ask = useCallback((prompt: string, blockId?: string) => {
setCompanion(true)
setRequest({
id: Date.now(),
prompt,
instructions: blockId ? `Target block: ${blockId}` : undefined,
})
}, [])
useEffect(() => {
const el = root.current
const generate = (event: Event) => {
const { kind, prompt, blockId, config } = (event as CustomEvent).detail
setCompanion(true)
setRequest({
id: Date.now(),
mode: learningMode(kind),
blockId,
autoSend: true,
config,
prompt: prompt?.trim() || t('Generate this learning block from the page'),
instructions: `Learning block kind: ${kind}. In your visible reply, describe only the learning material; do not mention block IDs, JSON fields, tool names or implementation details.${learningMode(kind) === 'chat' ? ` Use note_read then note_suggest to replace block ${blockId}. Preserve the rest of the page. Keep its id, kind and prompt. Use the interactive learning schema for flashcards, timeline and concept_map.` : ''}`,
})
}
el?.addEventListener('note-generate', generate)
return () => el?.removeEventListener('note-generate', generate)
}, [ask, t, page])
const applySuggestion = async (suggestion: NoteSuggestion, accept: boolean) => {
setMutating(true)
setReviewErrors(previous => ({ ...previous, [suggestion.id]: '' }))
editor.current?.setEditable(false)
try {
await flush()
const replacement =
accept && suggestion.operation !== 'comment' && suggestion.operation !== 'delete'
? suggestion.blocks || editor.current?.parse(suggestion.markdown)
: undefined
const result = await reviewSuggestion(docId, suggestion.id, accept, replacement)
latest.current = result
setPage(result)
if (accept && suggestion.operation !== 'comment' && result.blocks)
editor.current?.replace(result.blocks)
refreshSuggestions()
setError('')
} catch (err) {
const message = String(err instanceof Error ? err.message : err)
setReviewErrors(previous => ({
...previous,
[suggestion.id]: message.includes('The suggested block changed')
? t(
'This block has changed. Your edits are safe. Discuss a new suggestion or dismiss this one.'
)
: message,
}))
} finally {
setMutating(false)
editor.current?.setEditable(true)
}
}
const continueResearch = async (suggestion: NoteSuggestion) => {
const outline = researchOutline(suggestion)
if (!outline) return
try {
await flush()
await reviewSuggestion(docId, suggestion.id, false)
refreshSuggestions()
root.current?.dispatchEvent(
new CustomEvent('note-generate', {
bubbles: true,
detail: {
kind: 'research',
blockId: suggestion.block_id,
prompt: outline.topic,
config: { ...outline.research_config, confirmed_outline: outline.sub_topics },
},
})
)
} catch (err) {
setError(String(err))
}
}
const metadata = async (patch: Partial) => {
setMutating(true)
editor.current?.setEditable(false)
try {
await flush()
const result = await saveNote(docId, {
...patch,
expected_revision: latest.current!.revision,
})
latest.current = result
setPage(result)
refreshPages()
notifyCoWriterChanged()
} catch (err) {
setError(String(err))
} finally {
setMutating(false)
editor.current?.setEditable(true)
}
}
const exportFile = async (format: 'md' | 'docx') => {
try {
await flush()
const doc = latest.current!
const blob =
format === 'docx'
? await exportCoWriterDocx({ title: doc.title, content: doc.content })
: new Blob([doc.content], { type: 'text/markdown' })
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = `${doc.title || 'Note'}.${format}`
link.click()
setTimeout(() => URL.revokeObjectURL(url), 1000)
} catch (err) {
setError(String(err))
}
}
const invalidParents = pageDescendants(pages, docId)
return (
{
const link = (event.target as HTMLElement).closest
('a[data-note-source]')
if (
!link ||
event.button !== 0 ||
event.metaKey ||
event.ctrlKey ||
event.shiftKey ||
event.altKey
)
return
// Editor link handling otherwise consumes the click as a selection.
// Flush pending text/title changes before leaving the page.
event.preventDefault()
event.stopPropagation()
const url = new URL(link.href, window.location.href)
void flush()
.then(() => {
if (url.origin === window.location.origin)
router.push(`${url.pathname}${url.search}${url.hash}`)
else window.location.assign(url.href)
})
.catch(() => {
/* Save error stays visible; keep the current page. */
})
}}
>
{!embedded && (
{t('Learning notebook')}
)}
{t(status)}
{error && (
{error}
)}
{recovery && (
{t('A local draft differs from this page.')}
)}
{tree && (
setTree(false)}
onNavigate={async (event, id) => {
if (id === docId || version.current !== savedVersion.current) {
event.preventDefault()
if (id === docId) return
try {
await flush()
router.push(`/co-writer/${id}`)
} catch {
/* Keep the unsaved page visible. */
}
}
}}
onCreate={async () => {
setMutating(true)
try {
await flush()
const doc = await createNote(t('Untitled page'), docId)
refreshPages()
router.push(`/co-writer/${doc.id}`)
} catch (err) {
setError(String(err))
} finally {
setMutating(false)
}
}}
/>
)}
{page && (
{page.cover && (
)}
void continueResearch(suggestion)}
onReview={(suggestion, accept) => void applySuggestion(suggestion, accept)}
onDiscuss={suggestion =>
ask(
`${t('Discuss this feedback')}: ${suggestion.explanation}`,
suggestion.block_id
)
}
onChange={blocks => changed({ blocks })}
onReady={handle => {
editor.current = handle
if (version.current !== savedVersion.current) void flush().catch(() => {})
}}
onAI={ask}
/>
{!!backlinks.length && (
{t('Linked from')}
{backlinks.map(p => (
↗ {p.title}
))}
)}
)}
{companion && owner && (
setRequest(current =>
current?.id === id ? { ...current, autoSend: false } : current
)
}
onClose={() => setCompanion(false)}
/>
)}
{sources && (
setSources(false)}
onInsert={(title, markdown, url, id) =>
editor.current?.insertClip(title, markdown, url, id)
}
onKnowledge={name => {
setCompanion(true)
setRequest({
id: Date.now(),
prompt: `${t('Find source passages in this knowledge base and suggest cited notes')}: ${name}`,
knowledgeRef: name,
})
}}
/>
)}
{favorites && (
ask(
`${t('Organize these favorites into a coherent note. Cite the source of each section.')}\n\n${sources}`
)
}
onClose={() => setFavorites(false)}
onInsert={clips => {
editor.current?.insertClips(clips)
setFavorites(false)
}}
/>
)}
)
}