Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

improvement(web): show the page outline beside the text and subpages in the breadcrumbs (#709)

Croffad87c568d1a8
diff --git a/apps/web/messages/ar/documents.json b/apps/web/messages/ar/documents.json
index 02afcd83..954f7fbe 100644
--- a/apps/web/messages/ar/documents.json
+++ b/apps/web/messages/ar/documents.json
@@ -110,14 +110,13 @@
"restore": "استعادة",
"deletePermanently": "حذف نهائيًا",
"details": "تفاصيل الصفحة",
- "detailsDescription": "مخطط هذه الصفحة ومعلوماتها وملفاتها.",
+ "detailsDescription": "معلومات هذه الصفحة وعناصر العمل المرتبطة بها وملفاتها.",
"openDetails": "فتح تفاصيل الصفحة",
"closeDetails": "إغلاق تفاصيل الصفحة",
"close": "إغلاق",
"outline": "المخطط",
"info": "المعلومات",
"assets": "الملفات",
- "outlineEmpty": "أضف عناوين لإنشاء مخطط.",
"untitledHeading": "عنوان بلا اسم",
"owner": "المالك",
"createdAt": "تاريخ الإنشاء",
diff --git a/apps/web/messages/en/documents.json b/apps/web/messages/en/documents.json
index 93f4c649..2d16d4a2 100644
--- a/apps/web/messages/en/documents.json
+++ b/apps/web/messages/en/documents.json
@@ -95,14 +95,13 @@
"restore": "Restore",
"deletePermanently": "Delete permanently",
"details": "Page details",
- "detailsDescription": "Outline, information, and files for this page.",
+ "detailsDescription": "Information, work items, and files for this page.",
"openDetails": "Open page details",
"closeDetails": "Close page details",
"close": "Close",
"outline": "Outline",
"info": "Info",
"assets": "Assets",
- "outlineEmpty": "Add headings to build an outline.",
"untitledHeading": "Untitled heading",
"owner": "Owner",
"createdAt": "Created",
diff --git a/apps/web/messages/es-ES/documents.json b/apps/web/messages/es-ES/documents.json
index d645bfea..b5a230da 100644
--- a/apps/web/messages/es-ES/documents.json
+++ b/apps/web/messages/es-ES/documents.json
@@ -95,14 +95,13 @@
"restore": "Restaurar",
"deletePermanently": "Eliminar de forma definitiva",
"details": "Detalles de la página",
- "detailsDescription": "Esquema, información y ficheros de esta página.",
+ "detailsDescription": "Información, elementos de trabajo y ficheros de esta página.",
"openDetails": "Abrir los detalles de la página",
"closeDetails": "Cerrar los detalles de la página",
"close": "Cerrar",
"outline": "Esquema",
"info": "Información",
"assets": "Recursos",
- "outlineEmpty": "Añade títulos para construir un esquema.",
"untitledHeading": "Título sin nombre",
"owner": "Propietario",
"createdAt": "Creada",
diff --git a/apps/web/messages/fa/documents.json b/apps/web/messages/fa/documents.json
index 9e55864b..6a279ea8 100644
--- a/apps/web/messages/fa/documents.json
+++ b/apps/web/messages/fa/documents.json
@@ -95,14 +95,13 @@
"restore": "بازیابی",
"deletePermanently": "حذف همیشگی",
"details": "جزئیات صفحه",
- "detailsDescription": "ساختار، اطلاعات و فایل‌های این صفحه.",
+ "detailsDescription": "اطلاعات، تسک‌ها و فایل‌های این صفحه.",
"openDetails": "باز کردن جزئیات صفحه",
"closeDetails": "بستن جزئیات صفحه",
"close": "بستن",
"outline": "ساختار",
"info": "اطلاعات",
"assets": "فایل‌ها",
- "outlineEmpty": "برای ساخت ساختار، سرفصل اضافه کنید.",
"untitledHeading": "سرفصل بدون عنوان",
"owner": "مالک",
"createdAt": "ایجاد",
diff --git a/apps/web/messages/fr/documents.json b/apps/web/messages/fr/documents.json
index d06a9e96..f80aeb07 100644
--- a/apps/web/messages/fr/documents.json
+++ b/apps/web/messages/fr/documents.json
@@ -95,14 +95,13 @@
"restore": "Restaurer",
"deletePermanently": "Supprimer définitivement",
"details": "Détails de la page",
- "detailsDescription": "Plan, informations et fichiers de cette page.",
+ "detailsDescription": "Informations, tâches et fichiers de cette page.",
"openDetails": "Ouvrir les détails de la page",
"closeDetails": "Fermer les détails de la page",
"close": "Fermer",
"outline": "Plan",
"info": "Informations",
"assets": "Fichiers",
- "outlineEmpty": "Ajoutez des titres pour créer un plan.",
"untitledHeading": "Titre sans nom",
"owner": "Propriétaire",
"createdAt": "Créée",
diff --git a/apps/web/messages/id/documents.json b/apps/web/messages/id/documents.json
index 5a46c576..ce3f61ee 100644
--- a/apps/web/messages/id/documents.json
+++ b/apps/web/messages/id/documents.json
@@ -95,14 +95,13 @@
"restore": "Pulihkan",
"deletePermanently": "Hapus secara permanen",
"details": "Detail halaman",
- "detailsDescription": "Kerangka, informasi, dan file untuk halaman ini.",
+ "detailsDescription": "Informasi, item kerja, dan file untuk halaman ini.",
"openDetails": "Buka detail halaman",
"closeDetails": "Tutup detail halaman",
"close": "Tutup",
"outline": "Kerangka",
"info": "Info",
"assets": "Aset",
- "outlineEmpty": "Tambahkan judul untuk membuat kerangka.",
"untitledHeading": "Judul tanpa nama",
"owner": "Pemilik",
"createdAt": "Dibuat",
diff --git a/apps/web/messages/ko/documents.json b/apps/web/messages/ko/documents.json
index 054519cd..515f8d0f 100644
--- a/apps/web/messages/ko/documents.json
+++ b/apps/web/messages/ko/documents.json
@@ -95,14 +95,13 @@
"restore": "복원",
"deletePermanently": "영구 삭제",
"details": "페이지 상세 정보",
- "detailsDescription": "이 페이지의 개요, 정보 및 파일입니다.",
+ "detailsDescription": "이 페이지의 정보, 작업 및 파일입니다.",
"openDetails": "페이지 상세 정보 열기",
"closeDetails": "페이지 상세 정보 닫기",
"close": "닫기",
"outline": "개요",
"info": "정보",
"assets": "파일",
- "outlineEmpty": "제목을 추가하면 개요가 생성됩니다.",
"untitledHeading": "제목 없음",
"owner": "소유자",
"createdAt": "생성일",
diff --git a/apps/web/messages/pt-BR/documents.json b/apps/web/messages/pt-BR/documents.json
index 79b63ccd..f4843aaa 100644
--- a/apps/web/messages/pt-BR/documents.json
+++ b/apps/web/messages/pt-BR/documents.json
@@ -95,14 +95,13 @@
"restore": "Restaurar",
"deletePermanently": "Excluir permanentemente",
"details": "Detalhes da página",
- "detailsDescription": "Sumário, informações e arquivos desta página.",
+ "detailsDescription": "Informações, itens de trabalho e arquivos desta página.",
"openDetails": "Abrir detalhes da página",
"closeDetails": "Fechar detalhes da página",
"close": "Fechar",
"outline": "Sumário",
"info": "Informações",
"assets": "Arquivos",
- "outlineEmpty": "Adicione títulos para construir um sumário.",
"untitledHeading": "Título sem nome",
"owner": "Dono",
"createdAt": "Criado",
diff --git a/apps/web/messages/ru/documents.json b/apps/web/messages/ru/documents.json
index 487d5fd1..e7c1d18a 100644
--- a/apps/web/messages/ru/documents.json
+++ b/apps/web/messages/ru/documents.json
@@ -110,14 +110,13 @@
"restore": "Восстановить",
"deletePermanently": "Удалить навсегда",
"details": "Сведения о странице",
- "detailsDescription": "Структура, сведения и файлы этой страницы.",
+ "detailsDescription": "Сведения, задачи и файлы этой страницы.",
"openDetails": "Открыть сведения о странице",
"closeDetails": "Закрыть сведения о странице",
"close": "Закрыть",
"outline": "Структура",
"info": "Сведения",
"assets": "Файлы",
- "outlineEmpty": "Добавьте заголовки, чтобы появилась структура.",
"untitledHeading": "Заголовок без названия",
"owner": "Владелец",
"createdAt": "Создано",
diff --git a/apps/web/messages/tr/documents.json b/apps/web/messages/tr/documents.json
index ba73f588..057d8bfd 100644
--- a/apps/web/messages/tr/documents.json
+++ b/apps/web/messages/tr/documents.json
@@ -95,14 +95,13 @@
"restore": "Geri yükle",
"deletePermanently": "Kalıcı olarak sil",
"details": "Sayfa detayları",
- "detailsDescription": "Bu sayfanın ana hatları, bilgileri ve dosyaları.",
+ "detailsDescription": "Bu sayfanın bilgileri, iş maddeleri ve dosyaları.",
"openDetails": "Sayfa detaylarını aç",
"closeDetails": "Sayfa detaylarını kapat",
"close": "Kapat",
"outline": "İçindekiler",
"info": "Bilgi",
"assets": "Dosyalar",
- "outlineEmpty": "İçindekiler listesi oluşturmak için başlıklar ekleyin.",
"untitledHeading": "Başlıksız başlık",
"owner": "Sahip",
"createdAt": "Oluşturulma",
diff --git a/apps/web/messages/uk/documents.json b/apps/web/messages/uk/documents.json
index 7fcd5ea8..31624623 100644
--- a/apps/web/messages/uk/documents.json
+++ b/apps/web/messages/uk/documents.json
@@ -110,14 +110,13 @@
"restore": "Відновити",
"deletePermanently": "Видалити назавжди",
"details": "Відомості про сторінку",
- "detailsDescription": "Структура, відомості та файли цієї сторінки.",
+ "detailsDescription": "Відомості, задачі та файли цієї сторінки.",
"openDetails": "Відкрити відомості про сторінку",
"closeDetails": "Закрити відомості про сторінку",
"close": "Закрити",
"outline": "Структура",
"info": "Відомості",
"assets": "Файли",
- "outlineEmpty": "Додайте заголовки, щоб з’явилася структура.",
"untitledHeading": "Заголовок без назви",
"owner": "Власник",
"createdAt": "Створено",
diff --git a/apps/web/messages/zh-CN/documents.json b/apps/web/messages/zh-CN/documents.json
index 8d469ba1..8fc981c9 100644
--- a/apps/web/messages/zh-CN/documents.json
+++ b/apps/web/messages/zh-CN/documents.json
@@ -110,14 +110,13 @@
"restore": "恢复",
"deletePermanently": "永久删除",
"details": "页面详情",
- "detailsDescription": "此页面的大纲、信息和附件。",
+ "detailsDescription": "此页面的信息、工作项和附件。",
"openDetails": "打开页面详情",
"closeDetails": "关闭页面详情",
"close": "关闭",
"outline": "大纲",
"info": "信息",
"assets": "附件",
- "outlineEmpty": "添加标题后即可生成大纲。",
"untitledHeading": "无标题标题",
"owner": "所有者",
"createdAt": "创建时间",
diff --git a/apps/web/messages/zh-TW/documents.json b/apps/web/messages/zh-TW/documents.json
index 539a7604..ed460ce3 100644
--- a/apps/web/messages/zh-TW/documents.json
+++ b/apps/web/messages/zh-TW/documents.json
@@ -110,14 +110,13 @@
"restore": "恢復",
"deletePermanently": "永久刪除",
"details": "頁面詳情",
- "detailsDescription": "此頁面的大綱、資訊和附件。",
+ "detailsDescription": "此頁面的資訊、工作項目和附件。",
"openDetails": "開啟頁面詳情",
"closeDetails": "關閉頁面詳情",
"close": "關閉",
"outline": "大綱",
"info": "資訊",
"assets": "附件",
- "outlineEmpty": "新增標題後即可生成大綱。",
"untitledHeading": "未命名標題",
"owner": "所有者",
"createdAt": "建立時間",
diff --git a/apps/web/src/features/documents/DocumentsPage.tsx b/apps/web/src/features/documents/DocumentsPage.tsx
index b9c8cd7a..eb886941 100644
--- a/apps/web/src/features/documents/DocumentsPage.tsx
+++ b/apps/web/src/features/documents/DocumentsPage.tsx
@@ -251,6 +251,7 @@ export default function DocumentsPage() {
projectName={project.project.name}
document={activeDocument}
ancestors={ancestors}
+ documents={allDocumentsQuery.data ?? []}
authorName={author?.name ?? null}
authorNames={Object.fromEntries(
project.assignees.map((candidate) => [candidate.userId, candidate.name]),
@@ -262,7 +263,7 @@ export default function DocumentsPage() {
canCreate={canCreate}
canDelete={canDelete}
onBack={() => router.push(documentsPath(projectKey))}
- onCreateChild={() => void create(activeDocument.id, activeDocument.isPrivate)}
+ onCreate={(parentId, isPrivate) => void create(parentId, isPrivate)}
onDuplicate={duplicate}
onDelete={remove}
onReload={async () => {
diff --git a/apps/web/src/features/documents/components/DocumentBreadcrumbMenu.tsx b/apps/web/src/features/documents/components/DocumentBreadcrumbMenu.tsx
new file mode 100644
index 00000000..966ea226
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentBreadcrumbMenu.tsx
@@ -0,0 +1,97 @@
+'use client';
+
+import Link from 'next/link';
+import { ArrowUpRight, Check, ChevronDown, FileText, Plus } from 'lucide-react';
+import { useTranslations } from 'next-intl';
+import type { ProjectDocumentSummary } from '@/lib/api/endpoints/documents';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { cn } from '@/lib/utils';
+import { documentPath } from '@/utils/paths';
+
+export default function DocumentBreadcrumbMenu({
+ projectKey,
+ label,
+ href,
+ pages,
+ currentId,
+ createLabel,
+ onCreate,
+ current = false,
+ className,
+}: {
+ projectKey: string;
+ label: string;
+ href?: string;
+ pages: ProjectDocumentSummary[];
+ currentId: number;
+ createLabel: string;
+ onCreate?: () => void;
+ current?: boolean;
+ className?: string;
+}) {
+ const t = useTranslations('documents');
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ className={cn(
+ 'flex min-w-0 items-center gap-1 rounded-sm px-1 py-0.5 transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none data-[state=open]:bg-muted data-[state=open]:text-foreground',
+ current && 'font-medium text-foreground',
+ className,
+ )}
+ aria-current={current ? 'page' : undefined}
+ title={label}
+ >
+ <span className="truncate" dir="auto">
+ {label}
+ </span>
+ <ChevronDown className="size-3 shrink-0" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="w-72">
+ {href && (
+ <DropdownMenuItem asChild>
+ <Link href={href}>
+ <span className="min-w-0 flex-1 truncate" dir="auto">
+ {label}
+ </span>
+ <ArrowUpRight />
+ </Link>
+ </DropdownMenuItem>
+ )}
+ {href && pages.length > 0 && <DropdownMenuSeparator />}
+ {pages.map((page) => (
+ <DropdownMenuItem key={page.id} asChild>
+ <Link
+ href={documentPath(projectKey, page.id)}
+ aria-current={page.id === currentId ? 'page' : undefined}
+ >
+ <span
+ className="grid size-4 shrink-0 place-items-center text-sm leading-none"
+ aria-hidden
+ >
+ {page.icon ? page.icon : <FileText />}
+ </span>
+ <span className="min-w-0 flex-1 truncate" dir="auto">
+ {page.title.trim() || t('untitled')}
+ </span>
+ {page.id === currentId && <Check />}
+ </Link>
+ </DropdownMenuItem>
+ ))}
+ {onCreate && (href || pages.length > 0) && <DropdownMenuSeparator />}
+ {onCreate && (
+ <DropdownMenuItem onSelect={onCreate}>
+ <Plus />
+ {createLabel}
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/apps/web/src/features/documents/components/DocumentBreadcrumbs.tsx b/apps/web/src/features/documents/components/DocumentBreadcrumbs.tsx
index 93317197..0263afe3 100644
--- a/apps/web/src/features/documents/components/DocumentBreadcrumbs.tsx
+++ b/apps/web/src/features/documents/components/DocumentBreadcrumbs.tsx
@@ -1,22 +1,31 @@
import { ChevronRight } from 'lucide-react';
-import Link from 'next/link';
import { useTranslations } from 'next-intl';
import type { ProjectDocumentSummary } from '@/lib/api/endpoints/documents';
import { cn } from '@/lib/utils';
import { documentPath, documentsPath } from '@/utils/paths';
+import { documentChildren } from '../utils/documentTree';
+import DocumentBreadcrumbMenu from './DocumentBreadcrumbMenu';
export default function DocumentBreadcrumbs({
projectKey,
projectName,
ancestors,
document,
+ documents,
+ canCreate,
+ onCreate,
}: {
projectKey: string;
projectName: string;
ancestors: ProjectDocumentSummary[];
document: ProjectDocumentSummary;
+ documents: ProjectDocumentSummary[];
+ canCreate: boolean;
+ onCreate: (parentId: number | null, isPrivate: boolean) => void;
}) {
const t = useTranslations('documents');
+ const title = document.title.trim() || t('untitled');
+ const children = documentChildren(document.id, documents);
return (
<nav
@@ -31,16 +40,19 @@ export default function DocumentBreadcrumbs({
{projectName}
</span>
<ChevronRight className="hidden size-3 shrink-0 lg:block rtl:rotate-180" />
- <Link
+ <DocumentBreadcrumbMenu
+ projectKey={projectKey}
+ label={t('title')}
href={documentsPath(projectKey)}
- className="shrink-0 rounded-sm px-1 py-0.5 font-medium transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
- >
- {t('title')}
- </Link>
+ pages={documentChildren(null, documents)}
+ currentId={document.id}
+ createLabel={t('newDocument')}
+ onCreate={canCreate ? () => onCreate(null, false) : undefined}
+ className="shrink-0 font-medium"
+ />
{ancestors.map((ancestor, index) => {
const nearest = index === ancestors.length - 1;
- const ancestorTitle = ancestor.title.trim() || t('untitled');
return (
<span
key={ancestor.id}
@@ -50,27 +62,50 @@ export default function DocumentBreadcrumbs({
)}
>
<ChevronRight className="size-3 shrink-0 rtl:rotate-180" />
- <Link
+ <DocumentBreadcrumbMenu
+ projectKey={projectKey}
+ label={ancestor.title.trim() || t('untitled')}
href={documentPath(projectKey, ancestor.id)}
- className="max-w-32 truncate rounded-sm px-1 py-0.5 transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
- dir="auto"
- title={ancestorTitle}
- >
- {ancestorTitle}
- </Link>
+ pages={documentChildren(ancestor.id, documents)}
+ currentId={document.id}
+ createLabel={t('addSubpage')}
+ onCreate={
+ canCreate && ancestor.archivedAt === null
+ ? () => onCreate(ancestor.id, ancestor.isPrivate)
+ : undefined
+ }
+ className="max-w-32"
+ />
</span>
);
})}
<ChevronRight className="size-3 shrink-0 rtl:rotate-180" />
- <span
- className="min-w-8 truncate rounded-sm px-1 py-0.5 font-medium text-foreground"
- dir="auto"
- title={document.title.trim() || t('untitled')}
- aria-current="page"
- >
- {document.title.trim() || t('untitled')}
- </span>
+ {children.length > 0 ? (
+ <DocumentBreadcrumbMenu
+ projectKey={projectKey}
+ label={title}
+ pages={children}
+ currentId={document.id}
+ createLabel={t('addSubpage')}
+ onCreate={
+ canCreate && document.archivedAt === null
+ ? () => onCreate(document.id, document.isPrivate)
+ : undefined
+ }
+ current
+ className="min-w-8"
+ />
+ ) : (
+ <span
+ className="min-w-8 truncate rounded-sm px-1 py-0.5 font-medium text-foreground"
+ dir="auto"
+ title={title}
+ aria-current="page"
+ >
+ {title}
+ </span>
+ )}
</nav>
);
}
diff --git a/apps/web/src/features/documents/components/DocumentEditor.tsx b/apps/web/src/features/documents/components/DocumentEditor.tsx
index d539baec..5f5d0ae2 100644
--- a/apps/web/src/features/documents/components/DocumentEditor.tsx
+++ b/apps/web/src/features/documents/components/DocumentEditor.tsx
@@ -36,6 +36,7 @@ export default function DocumentEditor({
projectName,
document,
ancestors,
+ documents,
authorName,
authorNames,
canEdit,
@@ -45,7 +46,7 @@ export default function DocumentEditor({
canCreate,
canDelete,
onBack,
- onCreateChild,
+ onCreate,
onDuplicate,
onDelete,
onReload,
@@ -54,6 +55,7 @@ export default function DocumentEditor({
projectName: string;
document: ProjectDocument;
ancestors: ProjectDocumentSummary[];
+ documents: ProjectDocumentSummary[];
authorName: string | null;
authorNames: Record<string, string>;
canEdit: boolean;
@@ -63,7 +65,7 @@ export default function DocumentEditor({
canCreate: boolean;
canDelete: boolean;
onBack: () => void;
- onCreateChild: () => void;
+ onCreate: (parentId: number | null, isPrivate: boolean) => void;
onDuplicate: (title: string, version: number) => Promise<void>;
onDelete: (version: number) => Promise<void>;
onReload: () => Promise<ProjectDocument | null>;
@@ -205,6 +207,7 @@ export default function DocumentEditor({
projectName={projectName}
document={document}
ancestors={ancestors}
+ documents={documents}
title={title}
content={() => editor?.storage.markdown.getMarkdown() ?? content}
richHtml={() => editor?.getHTML() ?? ''}
@@ -237,7 +240,7 @@ export default function DocumentEditor({
);
}}
onStickyToolbarChange={setStickyToolbar}
- onCreateChild={onCreateChild}
+ onCreate={onCreate}
onDuplicate={() => {
void documentAction.run(async () => {
const baseVersion = await prepareVersion();
diff --git a/apps/web/src/features/documents/components/DocumentEditorCanvas.tsx b/apps/web/src/features/documents/components/DocumentEditorCanvas.tsx
index f6188cdd..a65417ac 100644
--- a/apps/web/src/features/documents/components/DocumentEditorCanvas.tsx
+++ b/apps/web/src/features/documents/components/DocumentEditorCanvas.tsx
@@ -6,6 +6,7 @@ import type { ProjectDocument } from '@/lib/api/endpoints/documents';
import { cn } from '@/lib/utils';
import { useTranslations } from 'next-intl';
import DocumentMarkdownEditor, { insertDocumentImage } from './DocumentMarkdownEditor';
+import DocumentOutline from './DocumentOutline';
import DocumentPageTitle from './DocumentPageTitle';
import { type DocumentSelection } from './DocumentSelectionActions';
import DocumentToolbar from './DocumentToolbar';
@@ -62,6 +63,7 @@ export default function DocumentEditorCanvas({
}) {
const t = useTranslations('documents');
const imageInput = useRef<HTMLInputElement>(null);
+ const scrollRef = useRef<HTMLDivElement>(null);
const editableRef = useRef(editable);
editableRef.current = editable;
@@ -84,68 +86,81 @@ export default function DocumentEditorCanvas({
) : null;
return (
- <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain scroll-smooth">
+ <div
+ ref={scrollRef}
+ className="min-h-0 flex-1 overflow-y-auto overscroll-contain scroll-smooth"
+ >
{stickyToolbar && toolbar}
- <article
- className={cn(
- 'mx-auto flex min-h-full w-full max-w-[860px] animate-in flex-col px-5 pt-10 pb-24 duration-300 fade-in slide-in-from-bottom-1 sm:px-8 md:pt-14 lg:px-14',
- document.fullWidth && 'max-w-[1280px] lg:px-20',
- )}
- >
- {!stickyToolbar && <div className="-mx-3 mb-8 sm:-mx-5">{toolbar}</div>}
- {editable && (
- <input
- ref={imageInput}
- className="sr-only"
- type="file"
- accept="image/*"
- aria-label={t('toolbar.uploadImage')}
- onChange={(event) => {
- const file = event.target.files?.[0];
- event.currentTarget.value = '';
- if (!file) return;
- void onUploadImage(file)
- .then((asset) => {
- insertDocumentImage(editor, editableRef.current, asset.url, asset.filename);
- })
- .catch(() => undefined);
- }}
+ <div className="flex min-h-full">
+ <div className="@container min-w-0 flex-1 pt-10 md:pt-14">
+ <DocumentOutline
+ editor={editor}
+ scrollRef={scrollRef}
+ belowToolbar={stickyToolbar && editable}
/>
- )}
+ </div>
+ <article
+ className={cn(
+ 'flex w-full max-w-[860px] animate-in flex-col px-5 pt-10 pb-24 duration-300 fade-in slide-in-from-bottom-1 sm:px-8 md:pt-14 lg:px-14',
+ document.fullWidth && 'max-w-[1280px] lg:px-20',
+ )}
+ >
+ {!stickyToolbar && <div className="-mx-3 mb-8 sm:-mx-5">{toolbar}</div>}
+ {editable && (
+ <input
+ ref={imageInput}
+ className="sr-only"
+ type="file"
+ accept="image/*"
+ aria-label={t('toolbar.uploadImage')}
+ onChange={(event) => {
+ const file = event.target.files?.[0];
+ event.currentTarget.value = '';
+ if (!file) return;
+ void onUploadImage(file)
+ .then((asset) => {
+ insertDocumentImage(editor, editableRef.current, asset.url, asset.filename);
+ })
+ .catch(() => undefined);
+ }}
+ />
+ )}
- <header className="mb-9 border-b border-border/55 pb-8">
- <DocumentPageTitle
- ref={titleRef}
- title={title}
- icon={document.icon}
+ <header className="mb-9 border-b border-border/55 pb-8">
+ <DocumentPageTitle
+ ref={titleRef}
+ title={title}
+ icon={document.icon}
+ editable={editable}
+ onChange={onTitleChange}
+ onSave={onTitleSave}
+ onIconChange={onIconChange}
+ />
+ <p className="mt-3 text-xs text-muted-foreground/80" dir="auto">
+ {updateLabel}
+ </p>
+ </header>
+
+ <DocumentMarkdownEditor
+ key={`${document.id}:${editorRevision}`}
+ projectKey={projectKey}
+ documentId={document.id}
+ onComment={onComment}
+ defaultValue={content}
+ defaultJson={contentJson}
editable={editable}
- onChange={onTitleChange}
- onSave={onTitleSave}
- onIconChange={onIconChange}
+ collaborative={collaborative}
+ placeholder={t('contentPlaceholder')}
+ className="min-h-[58vh] flex-1 text-[15px] leading-7 md:text-base md:leading-7 [&_:is(h1,h2,h3,h4,h5,h6)]:scroll-mt-20"
+ onReady={onEditorReady}
+ onChange={onContentChange}
+ onBlur={onContentBlur}
+ onPickImage={editable ? () => imageInput.current?.click() : undefined}
+ onUploadImage={editable ? onUploadImage : undefined}
/>
- <p className="mt-3 text-xs text-muted-foreground/80" dir="auto">
- {updateLabel}
- </p>
- </header>
-
- <DocumentMarkdownEditor
- key={`${document.id}:${editorRevision}`}
- projectKey={projectKey}
- documentId={document.id}
- onComment={onComment}
- defaultValue={content}
- defaultJson={contentJson}
- editable={editable}
- collaborative={collaborative}
- placeholder={t('contentPlaceholder')}
- className="min-h-[58vh] flex-1 text-[15px] leading-7 md:text-base md:leading-7"
- onReady={onEditorReady}
- onChange={onContentChange}
- onBlur={onContentBlur}
- onPickImage={editable ? () => imageInput.current?.click() : undefined}
- onUploadImage={editable ? onUploadImage : undefined}
- />
- </article>
+ </article>
+ <div className="min-w-0 flex-1" aria-hidden />
+ </div>
</div>
);
}
diff --git a/apps/web/src/features/documents/components/DocumentEditorHeader.tsx b/apps/web/src/features/documents/components/DocumentEditorHeader.tsx
index e7e9268f..bc6f617c 100644
--- a/apps/web/src/features/documents/components/DocumentEditorHeader.tsx
+++ b/apps/web/src/features/documents/components/DocumentEditorHeader.tsx
@@ -23,6 +23,7 @@ export default function DocumentEditorHeader({
projectName,
document,
ancestors,
+ documents,
title,
content,
richHtml,
@@ -39,7 +40,7 @@ export default function DocumentEditorHeader({
onRetrySave,
onFullWidthChange,
onStickyToolbarChange,
- onCreateChild,
+ onCreate,
onDuplicate,
onFavoriteChange,
onLockChange,
@@ -57,6 +58,7 @@ export default function DocumentEditorHeader({
projectName: string;
document: ProjectDocument;
ancestors: ProjectDocumentSummary[];
+ documents: ProjectDocumentSummary[];
title: string;
content: () => string;
richHtml: () => string;
@@ -73,7 +75,7 @@ export default function DocumentEditorHeader({
onRetrySave: () => void;
onFullWidthChange: (value: boolean) => void;
onStickyToolbarChange: (value: boolean) => void;
- onCreateChild: () => void;
+ onCreate: (parentId: number | null, isPrivate: boolean) => void;
onDuplicate: () => void;
onFavoriteChange: (favorite: boolean) => void;
onLockChange: (locked: boolean) => void;
@@ -128,6 +130,9 @@ export default function DocumentEditorHeader({
projectName={projectName}
ancestors={ancestors}
document={document}
+ documents={documents}
+ canCreate={canCreate}
+ onCreate={onCreate}
/>
<div className="ms-auto flex shrink-0 items-center gap-0.5">
@@ -210,7 +215,7 @@ export default function DocumentEditorHeader({
onFullWidthChange={onFullWidthChange}
onStickyToolbarChange={onStickyToolbarChange}
onPrivacyChange={onPrivacyChange}
- onCreateChild={onCreateChild}
+ onCreateChild={() => onCreate(document.id, document.isPrivate)}
onDuplicate={onDuplicate}
onArchive={onArchive}
onRestore={onRestore}
diff --git a/apps/web/src/features/documents/components/DocumentOutline.tsx b/apps/web/src/features/documents/components/DocumentOutline.tsx
new file mode 100644
index 00000000..516339ae
--- /dev/null
+++ b/apps/web/src/features/documents/components/DocumentOutline.tsx
@@ -0,0 +1,54 @@
+'use client';
+
+import type { RefObject } from 'react';
+import type { Editor } from '@tiptap/react';
+import { useTranslations } from 'next-intl';
+import { cn } from '@/lib/utils';
+import { useDocumentOutline } from '../hooks/useDocumentOutline';
+
+export default function DocumentOutline({
+ editor,
+ scrollRef,
+ belowToolbar,
+}: {
+ editor: Editor | null;
+ scrollRef: RefObject<HTMLElement | null>;
+ belowToolbar: boolean;
+}) {
+ const t = useTranslations('documents');
+ const { outline, activeIndex, jumpTo } = useDocumentOutline(editor, scrollRef);
+
+ if (outline.length === 0) return null;
+ const topLevel = Math.min(...outline.map((item) => item.level));
+
+ return (
+ <nav
+ aria-label={t('outline')}
+ className={cn(
+ 'sticky ms-auto hidden max-h-[calc(100dvh-12rem)] w-full max-w-60 overflow-y-auto ps-4 pe-3 @min-[10rem]:block',
+ belowToolbar ? 'top-22' : 'top-8',
+ )}
+ >
+ <p className="mb-2 text-xs font-medium text-muted-foreground">{t('outline')}</p>
+ <ol className="border-s">
+ {outline.map((item, index) => (
+ <li key={item.position}>
+ <button
+ type="button"
+ className={cn(
+ '-ms-px block w-full truncate border-s border-transparent py-1 pe-1 text-start text-[13px] text-muted-foreground transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none',
+ index === activeIndex && 'border-foreground font-medium text-foreground',
+ )}
+ style={{ paddingInlineStart: `${12 + (item.level - topLevel) * 12}px` }}
+ dir="auto"
+ aria-current={index === activeIndex ? 'location' : undefined}
+ onClick={() => jumpTo(index)}
+ >
+ {item.text || t('untitledHeading')}
+ </button>
+ </li>
+ ))}
+ </ol>
+ </nav>
+ );
+}
diff --git a/apps/web/src/features/documents/components/DocumentSidePanel.tsx b/apps/web/src/features/documents/components/DocumentSidePanel.tsx
index 79a832de..929c19b2 100644
--- a/apps/web/src/features/documents/components/DocumentSidePanel.tsx
+++ b/apps/web/src/features/documents/components/DocumentSidePanel.tsx
@@ -1,7 +1,7 @@
'use client';
import Link from 'next/link';
-import { useEffect, useMemo, useRef, useState } from 'react';
+import { useRef, useState } from 'react';
import type { Editor } from '@tiptap/react';
import {
Clipboard,
@@ -36,8 +36,6 @@ import {
useUploadDocumentAsset,
} from '../services/documents.service';
-type OutlineItem = { level: number; position: number; text: string };
-
export default function DocumentSidePanel({
projectKey,
document,
@@ -61,7 +59,6 @@ export default function DocumentSidePanel({
}) {
const t = useTranslations('documents');
const fileInput = useRef<HTMLInputElement>(null);
- const [outlineRevision, setOutlineRevision] = useState(0);
const [issuePickerOpen, setIssuePickerOpen] = useState(false);
const assets = useDocumentAssetsQuery(projectKey, document.id);
const issueLinks = useDocumentIssueLinksQuery(projectKey, document.id, canReadWorkItems);
@@ -71,43 +68,6 @@ export default function DocumentSidePanel({
const unlinkIssue = useUnlinkDocumentIssue(projectKey);
const linkedIssueIds = new Set((issueLinks.data ?? []).map((link) => link.issueId));
- useEffect(() => {
- if (!editor) return;
- let timer: ReturnType<typeof setTimeout>;
- const refreshOutline = ({ transaction }: { transaction: { docChanged: boolean } }) => {
- if (transaction.docChanged) {
- clearTimeout(timer);
- timer = setTimeout(() => setOutlineRevision((value) => value + 1), 300);
- }
- };
- editor.on('transaction', refreshOutline);
- return () => {
- clearTimeout(timer);
- editor.off('transaction', refreshOutline);
- };
- }, [editor]);
-
- const outline = useMemo(() => {
- void outlineRevision;
- const items: OutlineItem[] = [];
- editor?.state.doc.descendants((node, position) => {
- if (node.type.name !== 'heading') return;
- items.push({
- level: Number(node.attrs.level) || 1,
- position: position + 1,
- text: node.textContent.trim(),
- });
- });
- return items;
- }, [editor, outlineRevision]);
-
- const jumpToHeading = (position: number) => {
- if (!editor || editor.isDestroyed) return;
- const chain = editor.chain().setTextSelection(position).scrollIntoView();
- if (editor.isEditable) chain.focus();
- chain.run();
- };
-
const insertAsset = (asset: { contentType: string; filename: string; url: string }) => {
if (!canUpload || !editor || editor.isDestroyed || !editor.isEditable) return;
if (asset.contentType.startsWith('image/')) {
@@ -131,9 +91,8 @@ export default function DocumentSidePanel({
};
return (
- <Tabs defaultValue="outline" className="min-h-0 flex-1 gap-0">
+ <Tabs defaultValue="info" className="min-h-0 flex-1 gap-0">
<TabsList variant="line" className="h-11 w-full shrink-0 justify-start overflow-x-auto px-3">
- <TabsTrigger value="outline">{t('outline')}</TabsTrigger>
<TabsTrigger value="info">{t('info')}</TabsTrigger>
{canReadWorkItems && (
<TabsTrigger value="workItems">
@@ -146,32 +105,6 @@ export default function DocumentSidePanel({
<TabsTrigger value="assets">{t('assets')}</TabsTrigger>
</TabsList>
- <TabsContent value="outline" className="min-h-0 overflow-y-auto p-3">
- {outline.length === 0 ? (
- <p className="px-4 py-10 text-center text-xs leading-5 text-muted-foreground">
- {t('outlineEmpty')}
- </p>
- ) : (
- <nav aria-label={t('outline')}>
- <ol className="space-y-0.5">
- {outline.map((item) => (
- <li key={item.position}>
- <button
- type="button"
- className="w-full truncate rounded-md py-1.5 pe-2 text-start text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
- style={{ paddingInlineStart: `${8 + (item.level - 1) * 12}px` }}
- dir="auto"
- onClick={() => jumpToHeading(item.position)}
- >
- {item.text || t('untitledHeading')}
- </button>
- </li>
- ))}
- </ol>
- </nav>
- )}
- </TabsContent>
-
<TabsContent value="info" className="min-h-0 overflow-y-auto px-4 py-5">
<dl className="divide-y text-xs">
<div className="flex items-start justify-between gap-4 py-3 first:pt-0">
diff --git a/apps/web/src/features/documents/hooks/useDocumentOutline.ts b/apps/web/src/features/documents/hooks/useDocumentOutline.ts
new file mode 100644
index 00000000..8dc094b5
--- /dev/null
+++ b/apps/web/src/features/documents/hooks/useDocumentOutline.ts
@@ -0,0 +1,98 @@
+'use client';
+
+import { useEffect, useMemo, useState, type RefObject } from 'react';
+import type { Editor } from '@tiptap/react';
+
+export type DocumentOutlineItem = { level: number; position: number; text: string };
+
+// A heading becomes the current section once its top passes this line below the top
+// of the scroll container. The line sits under the headings' scroll margin, so the
+// heading a jump lands on is the current one.
+const ACTIVE_LINE = 96;
+
+export function useDocumentOutline(
+ editor: Editor | null,
+ scrollRef: RefObject<HTMLElement | null>,
+) {
+ const [revision, setRevision] = useState(0);
+ const [activeIndex, setActiveIndex] = useState(-1);
+
+ useEffect(() => {
+ if (!editor) return;
+ let timer: ReturnType<typeof setTimeout>;
+ const refresh = ({ transaction }: { transaction: { docChanged: boolean } }) => {
+ if (transaction.docChanged) {
+ clearTimeout(timer);
+ timer = setTimeout(() => setRevision((value) => value + 1), 300);
+ }
+ };
+ editor.on('transaction', refresh);
+ return () => {
+ clearTimeout(timer);
+ editor.off('transaction', refresh);
+ };
+ }, [editor]);
+
+ const outline = useMemo(() => {
+ void revision;
+ const items: DocumentOutlineItem[] = [];
+ editor?.state.doc.descendants((node, position) => {
+ if (node.type.name !== 'heading') return;
+ items.push({ level: Number(node.attrs.level) || 1, position, text: node.textContent.trim() });
+ });
+ return items;
+ }, [editor, revision]);
+
+ useEffect(() => {
+ const container = scrollRef.current;
+ if (!editor || !container || outline.length === 0) return;
+ let frame = 0;
+ const update = () => {
+ frame = 0;
+ if (editor.isDestroyed) return;
+ // The last headings of a page may never reach the line, so the end of the page
+ // selects the last one.
+ if (
+ container.scrollTop > 0 &&
+ container.scrollTop + container.clientHeight >= container.scrollHeight - 2
+ ) {
+ setActiveIndex(outline.length - 1);
+ return;
+ }
+ const line = container.getBoundingClientRect().top + ACTIVE_LINE;
+ let index = -1;
+ for (const [itemIndex, item] of outline.entries()) {
+ const element = editor.view.nodeDOM(item.position);
+ if (!(element instanceof HTMLElement) || element.getBoundingClientRect().top > line) break;
+ index = itemIndex;
+ }
+ setActiveIndex(index);
+ };
+ const schedule = () => {
+ if (!frame) frame = requestAnimationFrame(update);
+ };
+ update();
+ container.addEventListener('scroll', schedule, { passive: true });
+ return () => {
+ container.removeEventListener('scroll', schedule);
+ cancelAnimationFrame(frame);
+ };
+ }, [editor, outline, scrollRef]);
+
+ const jumpTo = (index: number) => {
+ const item = outline[index];
+ if (!editor || editor.isDestroyed || !item) return;
+ const element = editor.view.nodeDOM(item.position);
+ if (element instanceof HTMLElement) element.scrollIntoView({ block: 'start' });
+ if (editor.isEditable) {
+ editor
+ .chain()
+ .setTextSelection(item.position + 1)
+ .focus(undefined, { scrollIntoView: false })
+ .run();
+ }
+ setActiveIndex(index);
+ };
+
+ return { outline, activeIndex, jumpTo };
+}
diff --git a/apps/web/src/features/documents/utils/documentTree.test.ts b/apps/web/src/features/documents/utils/documentTree.test.ts
index fa5a52ea..81ff1344 100644
--- a/apps/web/src/features/documents/utils/documentTree.test.ts
+++ b/apps/web/src/features/documents/utils/documentTree.test.ts
@@ -1,7 +1,7 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import type { ProjectDocumentSummary } from '@/lib/api/endpoints/documents';
-import { documentAncestors } from './documentTree';
+import { documentAncestors, documentChildren } from './documentTree';
function document(id: number, parentId: number | null, title: string): ProjectDocumentSummary {
return {
@@ -42,3 +42,21 @@ describe('documentAncestors', () => {
assert.deepEqual(documentAncestors(first, [first, second]), [second]);
});
});
+
+describe('documentChildren', () => {
+ it('returns the direct children of a page in manual order', () => {
+ const root = document(1, null, 'Root');
+ const second = { ...document(2, 1, 'Second'), position: 2 };
+ const first = { ...document(3, 1, 'First'), position: 1 };
+ const grandchild = document(4, 3, 'Grandchild');
+
+ assert.deepEqual(documentChildren(1, [root, second, first, grandchild]), [first, second]);
+ });
+
+ it('lists a page whose parent is not visible as a top-level page', () => {
+ const root = document(1, null, 'Root');
+ const orphan = document(2, 99, 'Orphan');
+
+ assert.deepEqual(documentChildren(null, [orphan, root]), [root, orphan]);
+ });
+});
diff --git a/apps/web/src/features/documents/utils/documentTree.ts b/apps/web/src/features/documents/utils/documentTree.ts
index 68889dd4..386cfb98 100644
--- a/apps/web/src/features/documents/utils/documentTree.ts
+++ b/apps/web/src/features/documents/utils/documentTree.ts
@@ -19,3 +19,17 @@ export function documentAncestors(
return ancestors;
}
+
+// A page whose parent is not in the list counts as a top-level page, as in the
+// page tree.
+export function documentChildren(
+ parentId: number | null,
+ documents: ProjectDocumentSummary[],
+): ProjectDocumentSummary[] {
+ const ids = new Set(documents.map((item) => item.id));
+ const visibleParentId = (item: ProjectDocumentSummary) =>
+ item.parentId !== null && ids.has(item.parentId) ? item.parentId : null;
+ return documents
+ .filter((item) => visibleParentId(item) === parentId)
+ .sort((a, b) => a.position - b.position || a.id - b.id);
+}