🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(page): add Notion-style table of contents for long pages (#21321)
Lobehub Coder3d941976d2d0
diff --git a/apps/share/src/entry.tsx b/apps/share/src/entry.tsxindex 10dee784c8b..91a13c98ddd 100644--- a/apps/share/src/entry.tsx+++ b/apps/share/src/entry.tsx@@ -1,3 +1,5 @@+import '@/styles/stylex.css';+import { RouterProvider } from 'react-router/dom';import BootErrorBoundary from '@/components/BootErrorBoundary';diff --git a/locales/en-US/file.json b/locales/en-US/file.jsonindex 90e5fc892fe..e936025dc14 100644--- a/locales/en-US/file.json+++ b/locales/en-US/file.json@@ -308,6 +308,7 @@"pageEditor.saveFailed": "Failed to save the page, please try again later","pageEditor.saving": "Saving...","pageEditor.titlePlaceholder": "Untitled",+ "pageEditor.toc.title": "Contents","pageEditor.wordCount": "{{wordCount}} words","pageList.actions.openInNewTab": "Open in New Tab","pageList.copyConfirm": "Copy",diff --git a/locales/zh-CN/file.json b/locales/zh-CN/file.jsonindex 9c81b655b11..57980259c2e 100644--- a/locales/zh-CN/file.json+++ b/locales/zh-CN/file.json@@ -308,6 +308,7 @@"pageEditor.saveFailed": "页面保存失败,请稍后重试","pageEditor.saving": "正在保存…","pageEditor.titlePlaceholder": "无标题",+ "pageEditor.toc.title": "目录","pageEditor.wordCount": "{{wordCount}} 字","pageList.actions.openInNewTab": "在新标签页中打开","pageList.copyConfirm": "复制",diff --git a/packages/locales/src/default/file.ts b/packages/locales/src/default/file.tsindex 4f0b481b80c..7e923f32238 100644--- a/packages/locales/src/default/file.ts+++ b/packages/locales/src/default/file.ts@@ -343,6 +343,7 @@ export default {'pageEditor.saveFailed': 'Failed to save the page, please try again later','pageEditor.saving': 'Saving...','pageEditor.titlePlaceholder': 'Untitled',+ 'pageEditor.toc.title': 'Contents','pageEditor.wordCount': '{{wordCount}} words','pageList.actions.openInNewTab': 'Open in New Tab','pageList.copyConfirm': 'Copy',diff --git a/src/features/PageEditor/PageEditor.tsx b/src/features/PageEditor/PageEditor.tsxindex 565ad19a1c0..d358603a6f2 100644--- a/src/features/PageEditor/PageEditor.tsx+++ b/src/features/PageEditor/PageEditor.tsx@@ -33,6 +33,7 @@ import { PageAgentProvider } from './PageAgentProvider';import { PageEditorProvider } from './PageEditorProvider';import RightPanel from './RightPanel';import { usePageEditorStore } from './store';+import TableOfContents from './TableOfContents';import TitleSection from './TitleSection';import { usePageEditable } from './usePageEditable';@@ -414,6 +415,9 @@ const PageEditorCanvas = memo<PageEditorCanvasProps>((props) => {</Flexbox></WideScreenContainer></Flexbox>+ {!isHtmlPage && (+ <TableOfContents contentRef={editorContentRef} scrollRef={contentWrapperRef} />+ )}{documentId && <DiffAllToolbar documentId={documentId} editor={editor} />}</Flexbox>);diff --git a/src/features/PageEditor/TableOfContents/headings.test.ts b/src/features/PageEditor/TableOfContents/headings.test.tsnew file mode 100644index 00000000000..6712702c7b2--- /dev/null+++ b/src/features/PageEditor/TableOfContents/headings.test.ts@@ -0,0 +1,74 @@+import { describe, expect, it } from 'vitest';++import { collectHeadings, findActiveIndex, findBodyRoot, isSameOutline } from './headings';++const render = (html: string) => {+ const container = document.createElement('div');+ container.innerHTML = html;+ return container;+};++describe('findBodyRoot', () => {+ it('returns the first Lexical root so comment editors are ignored', () => {+ const content = render(+ '<textarea></textarea><div data-lexical-editor id="body"></div><div data-lexical-editor id="comment"></div>',+ );++ expect(findBodyRoot(content)?.id).toBe('body');+ });++ it('returns null without an editor', () => {+ expect(findBodyRoot(render('<p></p>'))).toBeNull();+ expect(findBodyRoot(null)).toBeNull();+ });+});++describe('collectHeadings', () => {+ it('collects h1-h3 in document order and skips empty headings', () => {+ const root = render(+ '<h1>Intro</h1><p>text</p><h2> Setup </h2><h4>Deep</h4><h3></h3><h3>Details</h3>',+ );++ expect(collectHeadings(root).map(({ level, text }) => ({ level, text }))).toEqual([+ { level: 1, text: 'Intro' },+ { level: 2, text: 'Setup' },+ { level: 3, text: 'Details' },+ ]);+ });++ it('returns an empty list without a root', () => {+ expect(collectHeadings(null)).toEqual([]);+ });+});++describe('findActiveIndex', () => {+ it('picks the last heading above the threshold', () => {+ expect(findActiveIndex([-300, -20, 40, 600], 80)).toBe(2);+ });++ it('falls back to the first heading before any is reached', () => {+ expect(findActiveIndex([200, 600], 80)).toBe(0);+ });++ it('picks the last heading once the pane reaches the bottom', () => {+ expect(findActiveIndex([-300, 40, 600], 80, true)).toBe(2);+ });++ it('returns -1 without headings', () => {+ expect(findActiveIndex([], 80)).toBe(-1);+ expect(findActiveIndex([], 80, true)).toBe(-1);+ });+});++describe('isSameOutline', () => {+ it('treats an unchanged outline as the same and edits to headings as different', () => {+ const root = render('<h1>A</h1><p>text</p><h2>B</h2>');+ const before = collectHeadings(root);++ root.querySelector('p')!.textContent = 'edited';+ expect(isSameOutline(before, collectHeadings(root))).toBe(true);++ root.querySelector('h2')!.textContent = 'B2';+ expect(isSameOutline(before, collectHeadings(root))).toBe(false);+ });+});diff --git a/src/features/PageEditor/TableOfContents/headings.ts b/src/features/PageEditor/TableOfContents/headings.tsnew file mode 100644index 00000000000..646473d2ffa--- /dev/null+++ b/src/features/PageEditor/TableOfContents/headings.ts@@ -0,0 +1,60 @@+export interface TocHeading {+ element: HTMLElement;+ level: 1 | 2 | 3;+ text: string;+}++const HEADING_SELECTOR = 'h1, h2, h3';++/**+ * The page body is the first Lexical root inside the editor content; later roots+ * belong to the comment composers rendered below it.+ */+export const findBodyRoot = (content: ParentNode | null | undefined): HTMLElement | null =>+ content?.querySelector<HTMLElement>('[data-lexical-editor]') ?? null;++export const collectHeadings = (root: ParentNode | null | undefined): TocHeading[] => {+ if (!root) return [];++ const headings: TocHeading[] = [];++ for (const element of root.querySelectorAll<HTMLElement>(HEADING_SELECTOR)) {+ const text = element.textContent?.trim();+ if (!text) continue;++ headings.push({ element, level: Number(element.tagName[1]) as TocHeading['level'], text });+ }++ return headings;+};++/**+ * Index of the heading whose section is being read: the last heading that has+ * scrolled past `threshold` px below the top of the viewport. Before the first+ * heading is reached, the first one is active. Once the pane is scrolled to the+ * bottom, a short final section may never reach the threshold, so the last+ * heading is active.+ */+export const findActiveIndex = (offsets: number[], threshold: number, atBottom = false): number => {+ if (offsets.length === 0) return -1;+ if (atBottom) return offsets.length - 1;++ let active = 0;++ for (const [index, offset] of offsets.entries()) {+ if (offset > threshold) break;+ active = index;+ }++ return active;+};++/** Same headings in the same order, so the rendered outline would not change. */+export const isSameOutline = (a: TocHeading[], b: TocHeading[]): boolean =>+ a.length === b.length &&+ a.every(+ (heading, index) =>+ heading.element === b[index].element &&+ heading.level === b[index].level &&+ heading.text === b[index].text,+ );diff --git a/src/features/PageEditor/TableOfContents/index.test.tsx b/src/features/PageEditor/TableOfContents/index.test.tsxnew file mode 100644index 00000000000..3fbf1e0c9f0--- /dev/null+++ b/src/features/PageEditor/TableOfContents/index.test.tsx@@ -0,0 +1,152 @@+import { act, fireEvent, render, screen } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import TableOfContents from './index';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++// jsdom has no layout: keep the first heading at the pane top and the rest+// below the active threshold.+const setBody = (content: HTMLElement, html: string) => {+ content.innerHTML = `<div data-lexical-editor>${html}</div>`;+ for (const [index, heading] of [...content.querySelectorAll('h1, h2')].entries()) {+ heading.getBoundingClientRect = () => ({ top: index === 0 ? 0 : 500 }) as DOMRect;+ }+};++const flush = async () => {+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 0));+ });+};++const setup = () => {+ const pane = document.createElement('div');+ const content = document.createElement('div');+ pane.append(content);+ document.body.append(pane);+ pane.scrollTo = vi.fn();+ Object.defineProperty(pane, 'scrollHeight', { configurable: true, value: 2000 });+ setBody(content, '<h1>Intro</h1><h2>Usage</h2><h2>FAQ</h2>');++ render(<TableOfContents contentRef={{ current: content }} scrollRef={{ current: pane }} />);+ return { content, pane };+};++const activeText = () =>+ screen.getAllByRole('link').find((el) => el.getAttribute('aria-current'))?.textContent;++let resizeCallbacks: Array<() => void> = [];++describe('TableOfContents', () => {+ beforeEach(() => {+ resizeCallbacks = [];+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ constructor(callback: () => void) {+ resizeCallbacks.push(callback);+ }+ disconnect() {}+ observe() {}+ },+ );+ vi.spyOn(window, 'requestAnimationFrame').mockImplementation((cb) => {+ cb(0);+ return 0;+ });+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ document.body.innerHTML = '';+ });++ it('expands on keyboard focus and collapses when focus leaves', async () => {+ setup();+ await flush();++ expect(screen.queryAllByRole('link')).toHaveLength(0);++ fireEvent.focus(screen.getByRole('button'));+ expect(screen.getAllByRole('link').map((el) => el.textContent)).toEqual([+ 'Intro',+ 'Usage',+ 'FAQ',+ ]);++ fireEvent.blur(screen.getByRole('button'), { relatedTarget: document.body });+ expect(screen.queryAllByRole('link')).toHaveLength(0);+ });++ it('drops the pinned heading when the document is replaced', async () => {+ const { content } = setup();+ await flush();++ fireEvent.focus(screen.getByRole('button'));+ fireEvent.click(screen.getByRole('link', { name: 'FAQ' }));+ expect(activeText()).toBe('FAQ');++ setBody(content, '<h1>Other</h1><h2>Details</h2><h2>More</h2>');+ await flush();++ expect(activeText()).toBe('Other');+ });++ it('releases the pin on scrollbar pointer input', async () => {+ const { pane } = setup();+ await flush();++ fireEvent.focus(screen.getByRole('button'));+ fireEvent.click(screen.getByRole('link', { name: 'FAQ' }));+ expect(activeText()).toBe('FAQ');++ fireEvent.pointerDown(pane);+ fireEvent.scroll(pane);+ expect(activeText()).toBe('Intro');+ });++ it('jumps without animation when reduced motion is preferred', async () => {+ vi.stubGlobal('matchMedia', (query: string) => ({+ matches: query === '(prefers-reduced-motion: reduce)',+ }));+ const { pane } = setup();+ await flush();++ fireEvent.focus(screen.getByRole('button'));+ fireEvent.click(screen.getByRole('link', { name: 'FAQ' }));++ expect(pane.scrollTo).toHaveBeenCalledWith(expect.objectContaining({ behavior: 'auto' }));+ });++ it('keeps the first heading active when the page fits without scrolling', async () => {+ const { pane } = setup();+ Object.defineProperty(pane, 'scrollHeight', { configurable: true, value: 0 });+ fireEvent.scroll(pane);+ await flush();++ fireEvent.focus(screen.getByRole('button'));+ expect(activeText()).toBe('Intro');+ });++ it('recomputes the active heading when layout changes without scrolling', async () => {+ const { pane } = setup();+ await flush();+ fireEvent.focus(screen.getByRole('button'));+ expect(activeText()).toBe('Intro');++ // A side panel opens and reflows the body: "Usage" moves above the threshold.+ for (const heading of pane.querySelectorAll('h1, h2')) {+ const top = heading.textContent === 'FAQ' ? 500 : 0;+ heading.getBoundingClientRect = () => ({ top }) as DOMRect;+ }+ act(() => {+ for (const callback of resizeCallbacks) callback();+ });++ expect(activeText()).toBe('Usage');+ });+});diff --git a/src/features/PageEditor/TableOfContents/index.tsx b/src/features/PageEditor/TableOfContents/index.tsxnew file mode 100644index 00000000000..65acca5fc33--- /dev/null+++ b/src/features/PageEditor/TableOfContents/index.tsx@@ -0,0 +1,292 @@+'use client';++import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import type { RefObject } from 'react';+import { memo, useCallback, useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import type { TocHeading } from './headings';+import { collectHeadings, findActiveIndex, findBodyRoot, isSameOutline } from './headings';++/** A heading counts as "being read" once it scrolls within this distance of the pane top. */+const ACTIVE_THRESHOLD = 96;+const SCROLL_MARGIN = 24;+const MIN_HEADINGS = 2;++const prefersReducedMotion = () =>+ window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;++const styles = stylex.create({+ container: {+ alignItems: 'flex-end',+ display: { 'default': 'flex', '@media (max-width: 1024px)': 'none' },+ flexDirection: 'column',+ // Vertically centered on the right edge, like Notion's outline rail.+ insetBlockStart: '50%',+ insetInlineEnd: 12,+ position: 'absolute',+ transform: 'translateY(-50%)',+ zIndex: 10,+ },+ item: {+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },+ borderRadius: 6,+ color: { 'default': cssVar.colorTextSecondary, ':hover': cssVar.colorText },+ cursor: 'pointer',+ fontSize: 13,+ lineHeight: 1.4,+ overflow: 'hidden',+ paddingBlock: 4,+ paddingInlineEnd: 8,+ textOverflow: 'ellipsis',+ transition: 'background-color 0.15s',+ whiteSpace: 'nowrap',+ width: '100%',+ },+ itemIndent: (indent: number) => ({ paddingInlineStart: indent }),+ itemActive: {+ color: { 'default': cssVar.colorPrimary, ':hover': cssVar.colorPrimary },+ fontWeight: 500,+ },+ line: {+ backgroundColor: cssVar.colorFill,+ borderRadius: 1,+ height: 2,+ transition: 'background-color 0.15s',+ },+ lineWidth: (width: number) => ({ width }),+ lineActive: {+ backgroundColor: cssVar.colorText,+ },+ lines: {+ alignItems: 'flex-end',+ cursor: 'pointer',+ display: 'flex',+ flexDirection: 'column',+ gap: 10,+ paddingBlock: 8,+ paddingInline: 8,+ },+ panel: {+ backgroundColor: cssVar.colorBgElevated,+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: 10,+ borderStyle: 'solid',+ borderWidth: 1,+ boxShadow: cssVar.boxShadowSecondary,+ insetBlockStart: '50%',+ insetInlineEnd: 0,+ maxHeight: 'min(480px, 60vh)',+ overflowY: 'auto',+ padding: 6,+ position: 'absolute',+ transform: 'translateY(-50%)',+ width: 240,+ },+ title: {+ color: cssVar.colorTextTertiary,+ fontSize: 12,+ paddingBlockStart: '4px',+ paddingBlockEnd: '6px',+ paddingInline: 8,+ },+});++const LINE_WIDTH: Record<TocHeading['level'], number> = { 1: 20, 2: 14, 3: 9 };+const ITEM_INDENT: Record<TocHeading['level'], number> = { 1: 8, 2: 20, 3: 32 };++interface TableOfContentsProps {+ /** Element holding the page body; its first Lexical root is the outline source. */+ contentRef: RefObject<HTMLElement | null>;+ /** Scrollable pane wrapping the body. */+ scrollRef: RefObject<HTMLElement | null>;+}++const TableOfContents = memo<TableOfContentsProps>(({ contentRef, scrollRef }) => {+ const { t } = useTranslation('file');+ const [headings, setHeadings] = useState<TocHeading[]>([]);+ const [activeIndex, setActiveIndex] = useState(-1);+ const [expanded, setExpanded] = useState(false);+ // A clicked heading near the end of the page may never reach the top of the+ // pane, so it stays active until the user scrolls on their own. Pinning the+ // element rather than its index drops the pin once the heading is gone, e.g.+ // after switching to another document.+ const pinnedRef = useRef<HTMLElement | null>(null);++ const updateActive = useCallback(+ (list: TocHeading[]) => {+ const pane = scrollRef.current;+ if (!pane) return;++ if (pinnedRef.current) {+ const pinnedIndex = list.findIndex(({ element }) => element === pinnedRef.current);+ if (pinnedIndex !== -1) {+ setActiveIndex(pinnedIndex);+ return;+ }+ pinnedRef.current = null;+ }++ const paneTop = pane.getBoundingClientRect().top;+ // A page that fits in the pane has nothing to scroll and starts at the top.+ const atBottom =+ pane.scrollHeight > pane.clientHeight &&+ pane.scrollTop + pane.clientHeight >= pane.scrollHeight - 1;+ setActiveIndex(+ findActiveIndex(+ list.map(({ element }) => element.getBoundingClientRect().top - paneTop),+ ACTIVE_THRESHOLD,+ atBottom,+ ),+ );+ },+ [scrollRef],+ );++ // Follow the body as it is edited or loaded; the Lexical root itself can be+ // replaced when switching documents, so observe the whole content subtree.+ useEffect(() => {+ const content = contentRef.current;+ if (!content) return;++ let frame = 0;+ const refresh = () => {+ cancelAnimationFrame(frame);+ frame = requestAnimationFrame(() => {+ const next = collectHeadings(findBodyRoot(content));+ // Ordinary text edits leave the outline unchanged; keep the previous list+ // so the TOC does not rerender or reinstall its scroll listeners.+ setHeadings((prev) => (isSameOutline(prev, next) ? prev : next));+ updateActive(next);+ });+ };++ refresh();+ const observer = new MutationObserver(refresh);+ observer.observe(content, { characterData: true, childList: true, subtree: true });++ return () => {+ cancelAnimationFrame(frame);+ observer.disconnect();+ };+ }, [contentRef, updateActive]);++ useEffect(() => {+ const pane = scrollRef.current;+ if (!pane) return;++ let frame = 0;+ const handleScroll = () => {+ cancelAnimationFrame(frame);+ frame = requestAnimationFrame(() => updateActive(headings));+ };++ const releasePin = () => {+ pinnedRef.current = null;+ };++ pane.addEventListener('scroll', handleScroll, { passive: true });+ // Pointer input covers scrollbar clicks and thumb drags.+ pane.addEventListener('pointerdown', releasePin, { passive: true });+ pane.addEventListener('wheel', releasePin, { passive: true });+ pane.addEventListener('touchstart', releasePin, { passive: true });+ pane.addEventListener('keydown', releasePin);++ // Opening a side panel, resizing the window or late reflow moves headings+ // without a scroll event.+ const resizeObserver = new ResizeObserver(handleScroll);+ resizeObserver.observe(pane);+ if (contentRef.current) resizeObserver.observe(contentRef.current);++ return () => {+ cancelAnimationFrame(frame);+ resizeObserver.disconnect();+ pane.removeEventListener('scroll', handleScroll);+ pane.removeEventListener('pointerdown', releasePin);+ pane.removeEventListener('wheel', releasePin);+ pane.removeEventListener('touchstart', releasePin);+ pane.removeEventListener('keydown', releasePin);+ };+ }, [contentRef, headings, scrollRef, updateActive]);++ const scrollToHeading = useCallback(+ (heading: TocHeading, index: number) => {+ const pane = scrollRef.current;+ if (!pane) return;++ pinnedRef.current = heading.element;+ setActiveIndex(index);++ const offset = heading.element.getBoundingClientRect().top - pane.getBoundingClientRect().top;+ pane.scrollTo({+ behavior: prefersReducedMotion() ? 'auto' : 'smooth',+ top: pane.scrollTop + offset - SCROLL_MARGIN,+ });+ },+ [scrollRef],+ );++ if (headings.length < MIN_HEADINGS) return null;++ return (+ <nav+ aria-label={t('pageEditor.toc.title')}+ {...stylex.props(styles.container)}+ onFocus={() => setExpanded(true)}+ onMouseEnter={() => setExpanded(true)}+ onMouseLeave={() => setExpanded(false)}+ onBlur={(event) => {+ if (!event.currentTarget.contains(event.relatedTarget)) setExpanded(false);+ }}+ >+ {/* Focusable so keyboard users can open the panel the way hover does. */}+ <div+ aria-label={t('pageEditor.toc.title')}+ role="button"+ tabIndex={0}+ {...stylex.props(styles.lines)}+ >+ {headings.map((heading, index) => (+ <div+ key={index}+ {...stylex.props(+ styles.line,+ styles.lineWidth(LINE_WIDTH[heading.level]),+ index === activeIndex && styles.lineActive,+ )}+ />+ ))}+ </div>+ {expanded && (+ <div {...stylex.props(styles.panel)}>+ <div {...stylex.props(styles.title)}>{t('pageEditor.toc.title')}</div>+ {headings.map((heading, index) => (+ <div+ aria-current={index === activeIndex ? 'location' : undefined}+ key={index}+ role="link"+ {...stylex.props(+ styles.item,+ styles.itemIndent(ITEM_INDENT[heading.level]),+ index === activeIndex && styles.itemActive,+ )}+ tabIndex={0}+ title={heading.text}+ onClick={() => scrollToHeading(heading, index)}+ onKeyDown={(event) => {+ if (event.key === 'Enter') scrollToHeading(heading, index);+ }}+ >+ {heading.text}+ </div>+ ))}+ </div>+ )}+ </nav>+ );+});++TableOfContents.displayName = 'PageTableOfContents';++export default TableOfContents;