feat(markdown): add document outline sidebar with click-to-jump (#289)

Co-authored-by: Aniruddha Adak <aniruddhaadak80@users.noreply.github.com>
This commit is contained in:
ANIRUDDHA ADAK
2026-09-11 16:18:19 +08:00
committed by GitHub
co-authored by Aniruddha Adak
parent d35d770948
commit 07af399a43
8 changed files with 286 additions and 1 deletions
+19 -1
View File
@@ -3,6 +3,7 @@ import { useAutoSavePref } from '@genoffice/ui'
import { EditorContent, useEditor } from '@tiptap/react'
import { FindPanel, type FindFocusRequest, type FindPanelStrings } from '@genoffice/ui'
import type { Editor } from '@tiptap/core'
import { TextSelection } from '@tiptap/pm/state'
import { useI18n } from './i18n/locale'
import {
buildFrontmatterRaw,
@@ -14,10 +15,12 @@ import {
} from './markdown/docText'
import { buildExtensions } from './editor/extensions'
import { tiptapFindTarget } from './editor/findTarget'
import { collectOutline, type OutlineItem } from './editor/outline'
import { buildSlashItems } from './editor/slashCommand'
import type { SlashController, SlashMenuState } from './editor/slashCommand'
import { setImageBaseDir } from './editor/localImage'
import { Ribbon } from './components/Ribbon'
import { OutlinePane } from './components/OutlinePane'
import { SlashMenu, type SlashMenuHandle } from './components/SlashMenu'
import { ToastHost } from './components/toast'
import { TableMenu } from './components/TableMenu'
@@ -134,6 +137,8 @@ export default function App() {
const [autoSave, setAutoSave] = useAutoSavePref('mdapp.autoSave', window.markdownApi)
const [showFind, setShowFind] = useState(false)
const [findFocus, setFindFocus] = useState<FindFocusRequest>({ field: 'find', nonce: 0 })
const [outlineOpen, setOutlineOpen] = useState(false)
const [outlineItems, setOutlineItems] = useState<OutlineItem[]>([])
const [zoom, setZoom] = useState(100)
const statusRef = useRef<LoadStatus>('loading')
@@ -190,8 +195,9 @@ export default function App() {
autofocus: true,
editorProps: { attributes: { class: 'doc-editor' } },
// uiOnly transactions (toggle fold state) never reach the file — not dirty
onUpdate: ({ transaction }) => {
onUpdate: ({ editor: updated, transaction }) => {
if (!transaction.getMeta('uiOnly')) markDirty()
setOutlineItems(collectOutline(updated))
},
})
editorRef.current = editor
@@ -546,6 +552,14 @@ export default function App() {
current.view.dispatch(current.state.tr.setSelection(selection).scrollIntoView())
current.view.focus()
}, [])
/** outline click: move the cursor into the heading and scroll it into view */
const jumpToOutline = useCallback((pos: number): void => {
const current = editorRef.current
if (!current) return
const selection = TextSelection.near(current.state.doc.resolve(pos))
current.view.dispatch(current.state.tr.setSelection(selection).scrollIntoView())
current.view.focus()
}, [])
const askSendNow = useCallback((text: string): void => {
setAiOpen(true)
setAiPreset((prev) => ({ text, nonce: (prev?.nonce ?? 0) + 1 }))
@@ -632,6 +646,9 @@ export default function App() {
onInsertImage={insertImage}
frontmatterOpen={fmOpen}
onToggleFrontmatter={() => setFmOpen((v) => !v)}
outlineOpen={outlineOpen}
onToggleOutline={() => setOutlineOpen((v) => !v)}
hasOutline={outlineItems.length > 0}
aiOpen={aiOpen}
onToggleAi={() => setAiOpen((v) => !v)}
onAiPreset={(text) => {
@@ -668,6 +685,7 @@ export default function App() {
/>
)}
</div>
{outlineOpen && <OutlinePane items={outlineItems} onJump={jumpToOutline} />}
<div className="app-content">
{showFind && findTarget && (
<FindPanel
@@ -0,0 +1,41 @@
import type { ReactElement } from 'react'
import { useI18n } from '../i18n/locale'
import type { OutlineItem } from '../editor/outline'
/**
* Document outline sidebar: heading list in document order, indented by level
* (PDF bookmark parity). Clicking an entry jumps the editor cursor there.
*/
export function OutlinePane({
items,
onJump,
}: {
items: OutlineItem[]
onJump: (pos: number) => void
}): ReactElement {
const { t } = useI18n()
return (
<aside className="md-outline" aria-label={t('outline')}>
<div className="md-outline-title">{t('outline')}</div>
{items.length === 0 ? (
<div className="md-outline-empty">{t('outlineEmpty')}</div>
) : (
<nav className="md-outline-list">
{items.map((item, index) => (
<button
key={`${item.pos}-${index}`}
type="button"
className="md-outline-item"
style={{ paddingLeft: 10 + (item.level - 1) * 14 }}
data-tip={item.text}
title={item.text}
onClick={() => onJump(item.pos)}
>
{item.text}
</button>
))}
</nav>
)}
</aside>
)
}
@@ -19,6 +19,7 @@ import {
IconInlineCode,
IconLink,
IconNumbered,
IconOutlineView,
IconPicture,
IconProperties,
IconRedo,
@@ -41,6 +42,9 @@ interface Props {
onInsertImage: () => void
frontmatterOpen: boolean
onToggleFrontmatter: () => void
outlineOpen: boolean
onToggleOutline: () => void
hasOutline: boolean
aiOpen: boolean
onToggleAi: () => void
onAiPreset: (instruction: string) => void
@@ -159,6 +163,9 @@ export function Ribbon({
onInsertImage,
frontmatterOpen,
onToggleFrontmatter,
outlineOpen,
onToggleOutline,
hasOutline,
aiOpen,
onToggleAi,
onAiPreset,
@@ -489,6 +496,14 @@ export function Ribbon({
>
<IconProperties size={ICON} />
</IconBtn>
<IconBtn
title={t('outline')}
active={outlineOpen}
disabled={disabled || !hasOutline}
onClick={onToggleOutline}
>
<IconOutlineView size={ICON} />
</IconBtn>
</div>
</div>
</div>
@@ -11,6 +11,7 @@ export {
IconBullets,
IconCaret,
IconNumbered,
IconOutlineView,
IconIndentDec,
IconIndentInc,
IconTable,
@@ -0,0 +1,31 @@
import type { Editor } from '@tiptap/core'
export interface OutlineItem {
/** heading level, 1-6 */
level: number
/** collapsed single-line heading text */
text: string
/** document position before the heading node (resolves to a cursor inside it) */
pos: number
}
/**
* Headings in document order for the outline sidebar (PDF bookmark parity:
* {@link apps/pdf/src/renderer/OutlinePanel.tsx}). Empty headings are skipped
* so the pane never shows blank rows.
*/
export function collectOutline(editor: Editor): OutlineItem[] {
const items: OutlineItem[] = []
editor.state.doc.descendants((node, pos) => {
if (node.type.name !== 'heading') return
const text = node.textContent.replace(/\s+/g, ' ').trim()
if (!text) return
const level = node.attrs.level
items.push({
level: typeof level === 'number' ? Math.min(Math.max(Math.round(level), 1), 6) : 1,
text,
pos,
})
})
return items
}
@@ -109,6 +109,8 @@ export const strings = {
mathPlaceholder: '输入 LaTeX 公式,如 E = mc^2',
slashNoResults: '无匹配项',
fmProperties: '属性',
outline: '大纲',
outlineEmpty: '暂无标题',
codeCopy: '复制',
codeCopied: '已复制',
tableRowAbove: '上方插入行',
@@ -292,6 +294,8 @@ export const strings = {
mathPlaceholder: 'Enter LaTeX, e.g. E = mc^2',
slashNoResults: 'No results',
fmProperties: 'Properties',
outline: 'Outline',
outlineEmpty: 'No headings yet',
codeCopy: 'Copy',
codeCopied: 'Copied',
tableRowAbove: 'Insert row above',
@@ -475,6 +479,8 @@ export const strings = {
mathPlaceholder: 'LaTeX を入力(例:E = mc^2)',
slashNoResults: '該当なし',
fmProperties: 'プロパティ',
outline: 'アウトライン',
outlineEmpty: '見出しがありません',
codeCopy: 'コピー',
codeCopied: 'コピーしました',
tableRowAbove: '上に行を挿入',
@@ -659,6 +665,8 @@ export const strings = {
mathPlaceholder: 'LaTeX 입력 (예: E = mc^2)',
slashNoResults: '결과 없음',
fmProperties: '속성',
outline: '개요',
outlineEmpty: '제목이 없습니다',
codeCopy: '복사',
codeCopied: '복사됨',
tableRowAbove: '위에 행 삽입',
@@ -846,6 +854,8 @@ export const strings = {
mathPlaceholder: 'Saisir du LaTeX, ex. E = mc^2',
slashNoResults: 'Aucun résultat',
fmProperties: 'Propriétés',
outline: 'Signets',
outlineEmpty: 'Aucun titre pour le moment',
codeCopy: 'Copier',
codeCopied: 'Copié',
tableRowAbove: 'Insérer une ligne au-dessus',
@@ -1035,6 +1045,8 @@ export const strings = {
mathPlaceholder: 'LaTeX eingeben, z. B. E = mc^2',
slashNoResults: 'Keine Treffer',
fmProperties: 'Eigenschaften',
outline: 'Gliederung',
outlineEmpty: 'Noch keine Überschriften',
codeCopy: 'Kopieren',
codeCopied: 'Kopiert',
tableRowAbove: 'Zeile oberhalb einfügen',
@@ -1222,6 +1234,8 @@ export const strings = {
mathPlaceholder: 'Escribe LaTeX, p. ej. E = mc^2',
slashNoResults: 'Sin resultados',
fmProperties: 'Propiedades',
outline: 'Esquema',
outlineEmpty: 'Sin encabezados todavía',
codeCopy: 'Copiar',
codeCopied: 'Copiado',
tableRowAbove: 'Insertar fila arriba',
@@ -1407,6 +1421,8 @@ export const strings = {
mathPlaceholder: 'ป้อน LaTeX เช่น E = mc^2',
slashNoResults: 'ไม่พบรายการ',
fmProperties: 'คุณสมบัติ',
outline: 'สารบัญ',
outlineEmpty: 'ยังไม่มีหัวข้อ',
codeCopy: 'คัดลอก',
codeCopied: 'คัดลอกแล้ว',
tableRowAbove: 'แทรกแถวด้านบน',
@@ -1591,6 +1607,8 @@ export const strings = {
mathPlaceholder: 'Masukkan LaTeX, mis. E = mc^2',
slashNoResults: 'Tidak ada hasil',
fmProperties: 'Properti',
outline: 'Kerangka',
outlineEmpty: 'Belum ada judul',
codeCopy: 'Salin',
codeCopied: 'Disalin',
tableRowAbove: 'Sisipkan baris di atas',
@@ -1776,6 +1794,8 @@ export const strings = {
mathPlaceholder: 'Введите LaTeX, напр. E = mc^2',
slashNoResults: 'Нет результатов',
fmProperties: 'Свойства',
outline: 'Оглавление',
outlineEmpty: 'Заголовков пока нет',
codeCopy: 'Копировать',
codeCopied: 'Скопировано',
tableRowAbove: 'Вставить строку выше',
@@ -1958,6 +1978,8 @@ export const strings = {
mathPlaceholder: 'أدخل LaTeX، مثل E = mc^2',
slashNoResults: 'لا نتائج',
fmProperties: 'خصائص',
outline: 'المخطط',
outlineEmpty: 'لا توجد عناوين بعد',
codeCopy: 'نسخ',
codeCopied: 'تم النسخ',
tableRowAbove: 'إدراج صف أعلى',
@@ -2144,6 +2166,8 @@ export const strings = {
mathPlaceholder: 'Digite LaTeX, ex.: E = mc^2',
slashNoResults: 'Sem resultados',
fmProperties: 'Propriedades',
outline: 'Estrutura',
outlineEmpty: 'Sem títulos ainda',
codeCopy: 'Copiar',
codeCopied: 'Copiado',
tableRowAbove: 'Inserir linha acima',
@@ -2331,6 +2355,8 @@ export const strings = {
mathPlaceholder: 'Inserisci LaTeX, es. E = mc^2',
slashNoResults: 'Nessun risultato',
fmProperties: 'Proprietà',
outline: 'Struttura',
outlineEmpty: 'Nessuna intestazione',
codeCopy: 'Copia',
codeCopied: 'Copiato',
tableRowAbove: 'Inserisci riga sopra',
@@ -2517,6 +2543,8 @@ export const strings = {
mathPlaceholder: 'Wpisz LaTeX, np. E = mc^2',
slashNoResults: 'Brak wyników',
fmProperties: 'Właściwości',
outline: 'Konspekt',
outlineEmpty: 'Brak nagłówków',
codeCopy: 'Kopiuj',
codeCopied: 'Skopiowano',
tableRowAbove: 'Wstaw wiersz powyżej',
@@ -2688,6 +2716,8 @@ export const strings = {
mathPlaceholder: 'Zadejte LaTeX, např. E = mc^2',
slashNoResults: 'Žádné výsledky',
fmProperties: 'Vlastnosti',
outline: 'Osnova',
outlineEmpty: 'Zatím žádné nadpisy',
codeCopy: 'Kopírovat',
codeCopied: 'Zkopírováno',
tableRowAbove: 'Vložit řádek nad',
@@ -2887,6 +2917,8 @@ export const strings = {
mathPlaceholder: 'Voer LaTeX in, bijv. E = mc^2',
slashNoResults: 'Geen resultaten',
fmProperties: 'Eigenschappen',
outline: 'Overzicht',
outlineEmpty: 'Nog geen koppen',
codeCopy: 'Kopiëren',
codeCopied: 'Gekopieerd',
tableRowAbove: 'Rij boven invoegen',
@@ -3071,6 +3103,8 @@ export const strings = {
mathPlaceholder: 'Masukkan LaTeX, cth. E = mc^2',
slashNoResults: 'Tiada hasil',
fmProperties: 'Sifat',
outline: 'Rangka',
outlineEmpty: 'Tiada tajuk lagi',
codeCopy: 'Salin',
codeCopied: 'Disalin',
tableRowAbove: 'Sisip baris di atas',
@@ -3253,6 +3287,8 @@ export const strings = {
mathPlaceholder: 'הזן LaTeX, למשל E = mc^2',
slashNoResults: 'אין תוצאות',
fmProperties: 'מאפיינים',
outline: 'מתאר',
outlineEmpty: 'אין כותרות עדיין',
codeCopy: 'העתק',
codeCopied: 'הועתק',
tableRowAbove: 'הוסף שורה מעל',
@@ -3437,6 +3473,8 @@ export const strings = {
mathPlaceholder: 'LaTeX दर्ज करें, जैसे E = mc^2',
slashNoResults: 'कोई परिणाम नहीं',
fmProperties: 'गुण',
outline: 'रूपरेखा',
outlineEmpty: 'अभी कोई शीर्षक नहीं',
codeCopy: 'कॉपी',
codeCopied: 'कॉपी हो गया',
tableRowAbove: 'ऊपर पंक्ति जोड़ें',
@@ -3619,6 +3657,8 @@ export const strings = {
mathPlaceholder: '輸入 LaTeX 公式,如 E = mc^2',
slashNoResults: '無符合項目',
fmProperties: '屬性',
outline: '大綱',
outlineEmpty: '尚無標題',
codeCopy: '複製',
codeCopied: '已複製',
tableRowAbove: '上方插入列',
+54
View File
@@ -2001,6 +2001,60 @@ html.genoffice-popover-open .ribbon-tabs {
min-width: 0;
}
/* ---- document outline sidebar (PDF bookmark parity) ---- */
.md-outline {
display: flex;
flex-direction: column;
flex-shrink: 0;
width: 232px;
min-height: 0;
border-right: 1px solid var(--border);
padding: 8px 4px;
overflow-y: auto;
}
.md-outline-title {
padding: 2px 10px 8px;
font-size: 12px;
font-weight: 600;
color: var(--text-muted);
}
.md-outline-empty {
padding: 2px 10px;
font-size: 12.5px;
color: var(--text-muted);
}
.md-outline-list {
display: flex;
flex-direction: column;
}
.md-outline-item {
display: block;
width: 100%;
border: none;
background: none;
text-align: left;
padding-top: 5px;
padding-bottom: 5px;
padding-right: 8px;
font-size: 12.5px;
line-height: 1.35;
color: var(--text);
border-radius: 4px;
cursor: pointer;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.md-outline-item:hover {
background: var(--hover);
}
/* ---- transient AI-change highlight ---- */
.doc-editor .ai-changed {
+85
View File
@@ -0,0 +1,85 @@
import { afterAll, describe, expect, it } from 'vitest'
import { Editor } from '@tiptap/core'
import { TextSelection } from '@tiptap/pm/state'
import { buildExtensions } from '../src/renderer/editor/extensions'
import { collectOutline } from '../src/renderer/editor/outline'
// Undestroyed views leave DOMObserver flush timers that fire after jsdom teardown
// ("document is not defined" unhandled error). Editors here are shared per describe,
// so destroy them once at the end of the file.
const editors: Editor[] = []
afterAll(() => {
for (const e of editors) e.destroy()
})
function createEditor(): Editor {
const editor = new Editor({
extensions: buildExtensions({
slashController: {
onOpen: () => {},
onUpdate: () => {},
onKeyDown: () => false,
onClose: () => {},
},
slashItems: () => [],
}),
content: '',
})
editors.push(editor)
return editor
}
function setMarkdown(editor: Editor, md: string): void {
editor.commands.setContent(md, { contentType: 'markdown' })
}
describe('collectOutline', () => {
const editor = createEditor()
it('collects headings in document order with levels and text', () => {
setMarkdown(
editor,
'# Title\n\nSome body text.\n\n## Section one\n\n### Deep dive\n\n## Section two\n',
)
const items = collectOutline(editor)
expect(items.map((i) => [i.level, i.text])).toEqual([
[1, 'Title'],
[2, 'Section one'],
[3, 'Deep dive'],
[2, 'Section two'],
])
})
it('skips empty headings so the pane never shows blank rows', () => {
setMarkdown(editor, '# Kept\n\n#\n\n## Also kept\n')
const items = collectOutline(editor)
expect(items.map((i) => i.text)).toEqual(['Kept', 'Also kept'])
})
it('returns an empty list for a document without headings', () => {
setMarkdown(editor, 'Just a paragraph.\n\n- a list\n- of things\n')
expect(collectOutline(editor)).toEqual([])
})
it('positions resolve to a cursor inside the heading (jump targets are valid)', () => {
setMarkdown(editor, '# First\n\n## Second\n')
const items = collectOutline(editor)
expect(items).toHaveLength(2)
for (const item of items) {
const $pos = editor.state.doc.resolve(item.pos)
// must not throw: the outline click handler builds a selection here
const selection = TextSelection.near($pos)
expect(selection).toBeTruthy()
}
})
it('reflects edits after the content changes', () => {
setMarkdown(editor, '# Before\n')
expect(collectOutline(editor).map((i) => i.text)).toEqual(['Before'])
setMarkdown(editor, '# After\n\n## Added\n')
expect(collectOutline(editor).map((i) => [i.level, i.text])).toEqual([
[1, 'After'],
[2, 'Added'],
])
})
})