'use client'
import {
useCallback,
useEffect,
useLayoutEffect,
useRef,
useState,
useSyncExternalStore,
} from 'react'
import dynamic from 'next/dynamic'
import type { FavoriteSnapshot } from '@/lib/favorite-content'
import NoteFavoriteBlock from './NoteFavoriteBlock'
import {
createExtension,
BlockNoteSchema,
BlockNoteEditor,
defaultBlockSpecs,
defaultInlineContentSpecs,
type PartialBlock,
} from '@blocknote/core'
import { SideMenuExtension, SuggestionMenu } from '@blocknote/core/extensions'
import { en, zh } from '@blocknote/core/locales'
import {
BlockNoteViewRaw,
useCreateBlockNote,
createReactBlockSpec,
createReactInlineContentSpec,
SuggestionMenuController,
FormattingToolbarController,
SideMenuController,
getDefaultReactSlashMenuItems,
useExtension,
useExtensionState,
useActiveStyles,
} from '@blocknote/react'
import { useTranslation } from 'react-i18next'
import {
Bold,
Italic,
Underline,
Strikethrough,
Code,
Sparkles,
GripVertical,
ArrowUp,
ArrowDown,
Plus,
Trash2,
Copy,
Upload,
Link as LinkIcon,
Info,
ListTree,
Columns2,
Bookmark,
Globe,
FileCode,
CalendarDays,
Table2,
FileText,
ArrowUpRight,
Image as ImageIcon,
Film,
Music,
Heading1,
Heading2,
Heading3,
Sigma,
BookOpen,
CheckSquare,
Network,
Layers,
Play,
ListOrdered,
} from 'lucide-react'
import Tooltip from '@/shared/ui/Tooltip'
import { subscribeToThemeChanges } from '@/lib/theme'
import { parseNoteMarkdown } from '../model/markdown'
import { insertNoteClips, type NoteClipInput } from '../model/clip-editing'
import { listNotes, type NoteBlock, type NotePage, type NoteSuggestion } from '@/lib/notes-api'
import { apiFetch, apiUrl } from '@/lib/api'
import { inputRules, InputRule } from '@tiptap/pm/inputrules'
import { closeHistory } from '@tiptap/pm/history'
import '@blocknote/core/style.css'
import './notes.css'
import NoteMath from './NoteMath'
import NoteInlineReviews from './NoteInlineReviews'
import useNoteBlockDrag from './useNoteBlockDrag'
import { noteFile } from './NoteFile'
import { noteUpload, activeNoteUploads } from './NoteUpload'
import { noteMediaAccept, noteMediaType } from '../model/media'
import {
basicPreviewKinds,
isBasicPreviewKind,
type BlockPreviewKind,
} from '../model/block-previews'
import NoteInsertMenu, { type NoteMenuItem } from './NoteInsertMenu'
import {
callout,
toggleHeading,
noteColumn,
noteColumns,
tableOfContents,
webCard,
htmlEmbed,
taskView,
noteDate,
} from './NoteRichBlocks'
const Markdown = dynamic(() => import('@/components/common/MarkdownRenderer'), { ssr: false })
const LearningContent = dynamic(() => import('./NoteLearningContent'), { ssr: false })
const math = createReactBlockSpec(
{ type: 'math', propSchema: { formula: { default: '' } }, content: 'none' },
{
render: function MathBlock({ block, editor }) {
const { t } = useTranslation()
const [editing, setEditing] = useState(!block.props.formula)
return (
{editing ? (
editor.updateBlock(block, { props: { formula: e.target.value } })}
onBlur={() => {
if (block.props.formula.trim()) setEditing(false)
}}
onKeyDown={e => {
if (e.key === 'Enter' || e.key === 'Escape') {
e.preventDefault()
setEditing(false)
editor.focus()
}
}}
/>
) : (
)}
)
},
}
)
const clip = createReactBlockSpec(
{
type: 'clip',
content: 'none',
propSchema: {
title: { default: '' },
markdown: { default: '' },
sourceUrl: { default: '' },
sourceId: { default: '' },
favoriteType: { default: '' },
summary: { default: '' },
metadata: { default: '{}' },
expanded: { default: false },
},
},
{
render: function ClipBlock({ block, editor }) {
const { t } = useTranslation()
if (block.props.favoriteType || /^\/notebooks?\//.test(block.props.sourceUrl))
return (
{
if (editor.getTextCursorPosition().block.id !== block.id)
editor.setTextCursorPosition(block.id, 'start')
}}
onExpanded={expanded =>
editor.transact(tr => {
// Reading a saved excerpt is view state, not a content edit.
tr.setMeta('addToHistory', false)
editor.updateBlock(block, { props: { expanded } })
})
}
/>
)
return (
)
},
}
)
const learning = createReactBlockSpec(
{
type: 'learning',
content: 'none',
propSchema: {
kind: { default: 'mermaid' },
prompt: { default: '' },
markdown: { default: '' },
data: { default: '{}' },
sourceUrl: { default: '' },
},
},
{
render: ({ block, editor }) => (
editor.updateBlock(block, { props })}
/>
),
}
)
const pageLink = createReactInlineContentSpec(
{
type: 'pageLink',
propSchema: { pageId: { default: '' }, title: { default: '' } },
content: 'none',
},
{
render: ({ inlineContent }) => (
{inlineContent.props.title}
),
}
)
const inlineMath = createReactInlineContentSpec(
{ type: 'inlineMath', propSchema: { formula: { default: '' } }, content: 'none' },
{
render: function InlineMath({ inlineContent, updateInlineContent }) {
const { t } = useTranslation()
const [edit, setEdit] = useState(false)
return (
{edit ? (
updateInlineContent({ type: 'inlineMath', props: { formula: e.target.value } })
}
onBlur={() => setEdit(false)}
onKeyDown={e => {
if (e.key === 'Enter' || e.key === 'Escape') {
e.preventDefault()
setEdit(false)
}
}}
/>
) : (
)}
)
},
}
)
const noteInputRules = createExtension({
key: 'note-input-rules',
inputRules: [{ find: /^\$\$\s$/, replace: () => ({ type: 'math', props: { formula: '' } }) }],
prosemirrorPlugins: [
inputRules({
rules: [
new InputRule(/(?:^|[^$])\$([^$\n]+)\$$/, (state, match, start, end) => {
const node = state.schema.nodes.inlineMath
if (!node) return null
const offset = match[0].startsWith('$') ? 0 : 1
return state.tr.replaceWith(start + offset, end, node.create({ formula: match[1] }))
}),
],
}),
],
})
const schema = BlockNoteSchema.create({
blockSpecs: {
...defaultBlockSpecs,
file: noteFile(),
math: math(),
clip: clip(),
learning: learning(),
noteUpload: noteUpload(),
callout: callout(),
toggleHeading: toggleHeading(),
noteColumn: noteColumn(),
noteColumns: noteColumns(),
tableOfContents: tableOfContents(),
webCard: webCard(),
htmlEmbed: htmlEmbed(),
taskView: taskView(),
},
inlineContentSpecs: { ...defaultInlineContentSpecs, pageLink, inlineMath, noteDate },
})
/** Reuse the notebook's normal migration before clipping into an unopened legacy page. */
export function parseLegacyNoteContent(markdown: string): NoteBlock[] {
const editor = BlockNoteEditor.create({ schema })
try {
return parseNoteMarkdown(markdown, text => editor.tryParseMarkdownToBlocks(text) as NoteBlock[])
} finally {
editor._tiptapEditor.destroy()
}
}
export type NotesEditor = typeof schema.BlockNoteEditor
export interface NoteEditorHandle {
blocks: () => NoteBlock[]
setEditable: (editable: boolean) => void
replace: (blocks: NoteBlock[]) => void
parse: (markdown: string) => NoteBlock[]
insertClip: (
title: string,
markdown: string,
sourceUrl: string,
sourceId?: string,
favorite?: FavoriteSnapshot
) => void
insertClips: (clips: NoteClipInput[]) => void
focusBlock: (id: string) => void
}
function Handles({ editor }: { editor: NotesEditor }) {
const { t } = useTranslation()
const handleRoot = useRef(null)
const menu = useExtension(SideMenuExtension)
const block = useExtensionState(SideMenuExtension, { selector: state => state?.block })
const [open, setOpen] = useState(false)
const drag = useNoteBlockDrag(editor)
if (!block) return null
return (
{drag.indicator}
{open && (
{
setOpen(false)
menu.unfreezeMenu()
}}
>
{(['up', 'down'] as const).map(direction => (
))}
{(['nest', 'unnest'] as const).map(action => (
))}
{block.type === 'table' &&
[
'Add row',
'Add column',
'Remove last row',
'Remove last column',
'Toggle header row',
].map(action => (
))}
{block.type === 'codeBlock' && (
)}
{editor.schema.blockSchema[block.type as keyof typeof schema.blockSchema].content ===
'inline' &&
(['paragraph', 'heading', 'bulletListItem', 'checkListItem'] as const).map(type => (
))}
)}
)
}
export default function NoteEditor({
page,
onChange,
onReady,
onAI,
suggestions,
reviewBusy,
reviewErrors,
onReview,
onDiscuss,
onContinueResearch,
}: {
page: NotePage
suggestions: NoteSuggestion[]
reviewBusy: boolean
reviewErrors?: Record
onContinueResearch: (suggestion: NoteSuggestion) => void
onReview: (suggestion: NoteSuggestion, accept: boolean) => void
onDiscuss: (suggestion: NoteSuggestion) => void
onChange: (blocks: NoteBlock[]) => void
onReady: (handle: NoteEditorHandle) => void
onAI: (prompt: string, blockId?: string) => void
}) {
const { t, i18n } = useTranslation()
const theme = useSyncExternalStore<'light' | 'dark'>(
subscribeToThemeChanges,
() => (document.documentElement.classList.contains('dark') ? 'dark' : 'light'),
() => 'light'
)
const ready = useRef(false)
const container = useRef(null)
const uploadInput = useRef(null)
const uploadAnchor = useRef(null)
const uploadRetry = useRef(null)
const initialized = useRef(false)
const latest = useRef({ onChange, onReady, onAI })
useLayoutEffect(() => {
latest.current = { onChange, onReady, onAI }
}, [onChange, onReady, onAI])
const editor = useCreateBlockNote(
{
schema,
tables: { headers: true },
extensions: [noteInputRules],
dictionary: i18n.language.startsWith('zh') ? zh : en,
initialContent: page.blocks?.length
? (page.blocks as PartialBlock<
typeof schema.blockSchema,
typeof schema.inlineContentSchema,
typeof schema.styleSchema
>[])
: undefined,
uploadFile: async file => {
const body = new FormData()
body.append('file', file)
const res = await apiFetch(apiUrl(`/api/documents/${page.id}/assets`), {
method: 'POST',
body,
})
if (!res.ok) {
const error = await res.json().catch(() => ({}))
throw new Error(t(error.detail || 'Upload failed'))
}
return (await res.json()).url as string
},
},
[page.id]
)
useEffect(() => {
const retry = (event: Event) => {
uploadRetry.current = (event as CustomEvent).detail.blockId
if (uploadInput.current) {
uploadInput.current.accept = noteMediaAccept
uploadInput.current.click()
}
}
const el = container.current
el?.addEventListener('note-upload-retry', retry)
return () => el?.removeEventListener('note-upload-retry', retry)
}, [])
const parseMarkdown = useCallback(
(text: string) =>
parseNoteMarkdown(text, value => editor.tryParseMarkdownToBlocks(value) as NoteBlock[]),
[editor]
)
useEffect(() => {
let cancelled = false
// BlockNote mounts React node views synchronously; initialize after React commits.
queueMicrotask(() => {
if (cancelled || initialized.current) return
initialized.current = true
if (page.blocks === null && page.content)
editor.replaceBlocks(editor.document, parseMarkdown(page.content) as typeof editor.document)
const insertClips = (clips: NoteClipInput[]) => {
insertNoteClips(editor, clips)
// PickerShell restores focus when it closes. Return to the document
// afterwards so immediate undo/redo works without an extra click.
requestAnimationFrame(() => {
if (container.current) editor.focus()
})
}
latest.current.onReady({
blocks: () => editor.document as NoteBlock[],
setEditable: editable => {
editor.isEditable = editable
},
replace: blocks => {
// Each acceptance is one undo step, independent of nearby typing or
// another approval, even when the responses arrive within 500 ms.
editor.transact(tr => closeHistory(tr))
editor.replaceBlocks(
editor.document,
blocks.length ? (blocks as typeof editor.document) : [{ type: 'paragraph' }]
)
editor.transact(tr => closeHistory(tr))
},
parse: parseMarkdown,
insertClip: (title, markdown, sourceUrl, sourceId = '', favorite) =>
insertClips([{ title, markdown, sourceUrl, sourceId, favorite }]),
insertClips,
focusBlock: id => {
if (editor.getBlock(id)) {
editor.setTextCursorPosition(id, 'start')
editor.focus()
container.current
?.querySelector(`[data-id="${CSS.escape(id)}"]`)
?.scrollIntoView({ block: 'center', behavior: 'smooth' })
}
},
})
ready.current = true
const target = window.location.hash.slice(1)
if (target && editor.getBlock(target)) {
editor.setTextCursorPosition(target, 'start')
container.current
?.querySelector(`[data-id="${CSS.escape(target)}"]`)
?.scrollIntoView({ block: 'center' })
}
// Persist the first conversion as a revisioned migration, even before typing.
if (page.blocks === null) latest.current.onChange(editor.document as NoteBlock[])
})
return () => {
cancelled = true
}
}, [editor, page.blocks, page.content, parseMarkdown])
const ai = useCallback(
(instruction: string) => {
const selection = editor.getSelectedText()
const block = editor.getTextCursorPosition().block
latest.current.onAI(
`${instruction}${selection ? `\nSelected text: ${selection}` : ''}`,
block.id
)
},
[editor]
)
const getItems = async (query: string): Promise => {
const insert = (block: Record) => {
const current = editor.getTextCursorPosition().block
const empty =
current.type === 'paragraph' && (!current.content || current.content.length === 0)
const [created] = empty
? editor.replaceBlocks(
[current],
[
block as PartialBlock<
typeof schema.blockSchema,
typeof schema.inlineContentSchema,
typeof schema.styleSchema
>,
]
).insertedBlocks
: editor.insertBlocks(
[
block as PartialBlock<
typeof schema.blockSchema,
typeof schema.inlineContentSchema,
typeof schema.styleSchema
>,
],
current,
'after'
)
if (created) {
// Form blocks own focus. Focusing the editor here immediately blurs an
// auto-focused formula input and closes it before the user can type.
if (['math', 'webCard', 'htmlEmbed', 'learning'].includes(created.type)) {
// SuggestionMenu restores editor focus after the insertion callback.
// Hand it to the new form after that transaction and React commit.
requestAnimationFrame(() => {
container.current
?.querySelector(
`[data-id="${CSS.escape(created.id)}"] input, [data-id="${CSS.escape(created.id)}"] textarea`
)
?.focus()
})
} else {
const target =
created.type === 'noteColumns'
? created.children?.[0]?.children?.[0]?.id || created.id
: created.id
editor.setTextCursorPosition(target, 'start')
editor.focus()
}
}
return created
}
const item = (
title: string,
group: string,
subtext: string,
aliases: string[],
Icon: typeof Info,
action: () => void,
preview: BlockPreviewKind,
shortcut?: string
): NoteMenuItem => ({
title: t(title),
group: t(group),
subtext: t(subtext),
aliases,
icon: ,
onItemClick: action,
preview,
shortcut,
})
const shortcuts: Record = {
heading: '#',
heading_2: '##',
heading_3: '###',
heading_4: '####',
bullet_list: '-',
numbered_list: '1.',
check_list: '[]',
toggle_list: '>',
quote: '"',
code_block: '```',
divider: '---',
}
const defaults = getDefaultReactSlashMenuItems(editor).flatMap(i => {
const key = (i as { key?: string }).key || ''
return isBasicPreviewKind(key)
? [{ ...i, preview: key, group: t('Basic blocks'), shortcut: shortcuts[key] }]
: []
})
defaults.sort(
(a, b) => basicPreviewKinds.indexOf(a.preview) - basicPreviewKinds.indexOf(b.preview)
)
const items: NoteMenuItem[] = [
item(
'Ask Dito',
'Suggested',
'Write, explain or improve this part of your note.',
['ai', '生成', '续写'],
Sparkles,
() => ai(t('Continue writing here')),
'ai'
),
item(
'Reference a source',
'Suggested',
'Bring in a passage from your reading, chats or knowledge bases.',
['source', '引用', '知识'],
BookOpen,
() => container.current?.dispatchEvent(new CustomEvent('note-sources', { bubbles: true })),
'source'
),
item(
'Insert favorite',
'Suggested',
'Keep an original answer with its source.',
['favorite', '收藏'],
Bookmark,
() =>
container.current?.dispatchEvent(new CustomEvent('note-favorites', { bubbles: true })),
'favorite'
),
...defaults,
item(
'Callout',
'Basic blocks',
'Highlight a key idea, tip or warning.',
['callout', '标注', '提示'],
Info,
() => insert({ type: 'callout' }),
'callout'
),
item(
'Page link',
'Basic blocks',
'Link to another notebook page.',
['page', '页面', '链接'],
FileText,
() => editor.getExtension(SuggestionMenu)?.openSuggestionMenu('[['),
'pageLink'
),
...(
[
['image', 'Image', ImageIcon, 'image/png,image/jpeg,image/gif,image/webp', '图片'],
['video', 'Video', Film, 'video/mp4', '视频'],
['audio', 'Audio', Music, 'audio/mpeg,audio/wav', '音频'],
['file', 'File', Upload, noteMediaAccept, '文件'],
] as const
).map(([key, label, Icon, accept, alias]) =>
item(
label,
'Media',
'Upload a file to this page.',
[key, alias],
Icon,
() => {
if (uploadInput.current) {
uploadAnchor.current = editor.getTextCursorPosition().block.id
uploadRetry.current = null
uploadInput.current.accept = accept
uploadInput.current.click()
}
},
key
)
),
item(
'Web bookmark',
'Media',
'Save a link with a title and a short description.',
['bookmark', '书签'],
Bookmark,
() => insert({ type: 'webCard' }),
'bookmark'
),
item(
'Embed',
'Media',
'Display an external page that allows embedding.',
['embed', '嵌入'],
Globe,
() => insert({ type: 'webCard', props: { mode: 'embed' } }),
'embed'
),
item(
'HTML',
'Media',
'Preview HTML inside an isolated frame.',
['html', '网页'],
FileCode,
() => insert({ type: 'htmlEmbed' }),
'htmlEmbed'
),
...(['table', 'board', 'list'] as const).map(view =>
item(
{ table: 'Task table', board: 'Task board', list: 'Task list' }[view],
'Linked views',
'View and update tasks from this workspace.',
['task', view, '任务', { table: '表格', board: '看板', list: '列表' }[view]],
Table2,
() => insert({ type: 'taskView', props: { view } }),
`task_${view}`
)
),
item(
'Table of contents',
'Advanced blocks',
'Jump to headings; updates as your page changes.',
['toc', '目录'],
ListTree,
() => insert({ type: 'tableOfContents' }),
'toc'
),
item(
'Math formula',
'Advanced blocks',
'Write a mathematical expression using LaTeX.',
['math', '公式'],
Sigma,
() => insert({ type: 'math' }),
'math',
'$$'
),
...([1, 2, 3] as const).map(level =>
item(
`Toggle heading ${level}`,
'Advanced blocks',
'Keep supporting notes inside a collapsible heading.',
['toggle', '折叠', `h${level}`],
[Heading1, Heading2, Heading3][level - 1],
() =>
insert({ type: 'toggleHeading', props: { level }, children: [{ type: 'paragraph' }] }),
`toggle_heading_${level}`
)
),
...([2, 3, 4, 5] as const).map(count =>
item(
`${count} columns`,
'Advanced blocks',
'Arrange related ideas side by side. Stacks on small screens.',
['columns', '列', String(count)],
Columns2,
() =>
insert({
type: 'noteColumns',
children: Array.from({ length: count }, () => ({
type: 'noteColumn',
children: [{ type: 'paragraph' }],
})),
}),
`columns_${count}`
)
),
item(
'Date',
'Inline',
'Add an editable date in your text.',
['date', '日期'],
CalendarDays,
() =>
editor.insertInlineContent([
{ type: 'noteDate', props: { date: new Date().toLocaleDateString('en-CA') } },
' ',
]),
'date'
),
item(
'Inline formula',
'Inline',
'Place a formula within a sentence.',
['inline math', '行内公式'],
Sigma,
() => editor.insertInlineContent([{ type: 'inlineMath', props: { formula: 'x^2' } }, ' ']),
'inlineMath',
'$…$'
),
...[
['mermaid', 'Diagram', '图解', Network],
['quiz', 'Quiz me', '测验', CheckSquare],
['flashcards', 'Flash Cards', '闪卡', Layers],
['timeline', 'Timeline', '时间线', ListOrdered],
['research', 'Research', '研究', BookOpen],
['task', 'Task', '任务', CheckSquare],
['animation', 'Animation', '动画', Play],
['concept_map', 'Concept map', '概念图', Network],
['geogebra', 'Geometry', '几何', Sigma],
['image', 'Generate image', '生成图片', ImageIcon],
['audio', 'Podcast', '播客', Music],
].map(([kind, label, alias, Icon]) =>
item(
label as string,
'Learning',
'Create learning material grounded in this page.',
[kind as string, alias as string],
Icon as typeof Info,
() => {
insert({ type: 'learning', props: { kind } })
},
({ image: 'generated_image', audio: 'podcast' }[kind as string] ||
kind) as BlockPreviewKind
)
),
]
const needle = query.toLowerCase().trim()
return items.filter(i =>
[i.title, ...(i.aliases || [])].some(label => label.toLowerCase().includes(needle))
)
}
const pageItems = async (query: string): Promise => {
const { documents } = await listNotes()
return documents
.filter(d => d.id !== page.id && d.title.toLowerCase().includes(query.toLowerCase()))
.slice(0, 15)
.map(d => ({
title: d.title,
preview: 'pageLink' as const,
previewTitle: d.title,
subtext: t('Open linked page'),
icon: ,
onItemClick: () =>
editor.insertInlineContent([
{ type: 'pageLink', props: { pageId: d.id, title: d.title } },
' ',
]),
}))
}
const Toolbar = () => {
const activeStyles = useActiveStyles(editor)
const [linkOpen, setLinkOpen] = useState(false)
const [linkUrl, setLinkUrl] = useState('')
const [linkError, setLinkError] = useState('')
// Atomic source/media blocks cannot receive inline formatting. BlockNote
// also selects these on interaction; only offer tools for selected text.
if (!editor.getSelectedText().trim()) return null
return (
{linkOpen && (
)}
{(
[
['bold', Bold, 'Bold'],
['italic', Italic, 'Italic'],
['underline', Underline, 'Underline'],
['strike', Strikethrough, 'Strikethrough'],
['code', Code, 'Code'],
] as const
).map(([style, Icon, label]) => (
))}
)
}
return (
{
// Read-only card controls stop ProseMirror's key handling. Keep the
// document history accessible while a card button or source has focus.
const target = e.target as HTMLElement
if (
target.closest('.dt-note-favorite') &&
!target.closest('input, textarea, [contenteditable="true"]:not(.bn-editor)') &&
!e.nativeEvent.isComposing &&
!e.altKey &&
(e.metaKey || e.ctrlKey) &&
['z', 'y'].includes(e.key.toLowerCase())
) {
e.preventDefault()
e.stopPropagation()
if (e.shiftKey || e.key.toLowerCase() === 'y') editor.redo()
else editor.undo()
editor.focus()
}
}}
onKeyDown={e => {
if (
!(
e.target instanceof HTMLElement &&
e.target.closest('input, textarea, button, [contenteditable="false"]')
) &&
!e.nativeEvent.isComposing &&
e.key === ' ' &&
editor.getTextCursorPosition().block.type === 'paragraph' &&
editor.getSelectedText() === ''
) {
const content = editor.getTextCursorPosition().block.content
if (Array.isArray(content) && content.length === 0) {
e.preventDefault()
ai(t('Continue writing here'))
}
}
}}
>
{
const file = e.target.files?.[0]
e.target.value = ''
if (!file) return
const retryId = uploadRetry.current
uploadRetry.current = null
const id = retryId || crypto.randomUUID()
activeNoteUploads.add(id)
const existing = retryId ? editor.getBlock(retryId) : undefined
if (existing?.type === 'noteUpload') {
editor.updateBlock(existing, { props: { name: file.name, error: '' } })
} else {
const anchor =
editor.getBlock(uploadAnchor.current || '') || editor.getTextCursorPosition().block
const placeholder = { id, type: 'noteUpload' as const, props: { name: file.name } }
if (anchor.type === 'paragraph' && !anchor.content?.length)
editor.replaceBlocks([anchor], [placeholder])
else editor.insertBlocks([placeholder], anchor, 'after')
}
try {
const type = noteMediaType(file)
const url = await editor.uploadFile!(file)
// The user may move the caret or delete the placeholder while uploading.
const target = editor.getBlock(id)
if (target?.type === 'noteUpload')
editor.replaceBlocks(
[target],
[{ id, type, props: { url: typeof url === 'string' ? url : '', name: file.name } }]
)
} catch (err) {
activeNoteUploads.delete(id)
if (editor.getBlock(id)?.type === 'noteUpload')
editor.updateBlock(id, {
props: { error: t(err instanceof Error ? err.message : 'Upload failed') },
})
} finally {
activeNoteUploads.delete(id)
}
}}
/>
{
if (ready.current) latest.current.onChange(editor.document as NoteBlock[])
}}
>
} />
{['/', '、'].map(trigger => (
{
const parent = tr.selection.$from.parent
return (
!parent.type.spec.code &&
!parent.type.isInGroup('tableContent') &&
(trigger !== '、' || parent.textContent.length === 0)
)
}}
getItems={getItems}
suggestionMenuComponent={NoteInsertMenu}
/>
))}
{['[[', '@'].map(trigger => (
=>
trigger === '[['
? pageItems(query)
: [
{
title: t('Reference a source'),
preview: 'source' as const,
onItemClick: () =>
container.current?.dispatchEvent(
new CustomEvent('note-sources', { bubbles: true })
),
},
{
title: t('Insert favorite'),
preview: 'favorite' as const,
onItemClick: () =>
container.current?.dispatchEvent(
new CustomEvent('note-favorites', { bubbles: true })
),
},
...(await pageItems(query)),
]
}
suggestionMenuComponent={NoteInsertMenu}
/>
))}
)
}