Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

feat(docs-ui): improve document outline navigation (#7683)

白熱470674754717
diff --git a/examples/src/docs/mount.ts b/examples/src/docs/mount.ts
index c048bfb473..2a85c5c21b 100644
--- a/examples/src/docs/mount.ts
+++ b/examples/src/docs/mount.ts
@@ -50,7 +50,7 @@ export const mount: MountExample = async (host, options) => {
darkMode: options.darkMode,
direction: options.direction,
presets: [
- UniverDocsCorePreset({ container: host, ribbonType: options.ribbonType }),
+ UniverDocsCorePreset({ container: host, ribbonType: options.ribbonType, toc: true }),
UniverDocsDrawingPreset(),
UniverDocsHyperLinkPreset(),
UniverDocsThreadCommentPreset(),
diff --git a/packages/docs-ui/src/locale/ar-SA.ts b/packages/docs-ui/src/locale/ar-SA.ts
index 065ed66dbf..bc473f3182 100644
--- a/packages/docs-ui/src/locale/ar-SA.ts
+++ b/packages/docs-ui/src/locale/ar-SA.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ outline: {
+ title: 'مخطط المستند',
+ },
objectPermission: {
paragraphPermission: 'الأذونات',
title: 'الأذونات',
diff --git a/packages/docs-ui/src/locale/ca-ES.ts b/packages/docs-ui/src/locale/ca-ES.ts
index da6a857a5c..a32f9069a3 100644
--- a/packages/docs-ui/src/locale/ca-ES.ts
+++ b/packages/docs-ui/src/locale/ca-ES.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ outline: {
+ title: 'Esquema del document',
+ },
objectPermission: {
paragraphPermission: 'Permisos',
title: 'Permisos',
diff --git a/packages/docs-ui/src/locale/de-DE.ts b/packages/docs-ui/src/locale/de-DE.ts
index eca35b577d..f5b9ce3e63 100644
--- a/packages/docs-ui/src/locale/de-DE.ts
+++ b/packages/docs-ui/src/locale/de-DE.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ outline: {
+ title: 'Dokumentgliederung',
+ },
objectPermission: {
paragraphPermission: 'Berechtigungen',
title: 'Berechtigungen',
diff --git a/packages/docs-ui/src/locale/en-US.ts b/packages/docs-ui/src/locale/en-US.ts
index 4fa81bc1d5..bc7d77555b 100644
--- a/packages/docs-ui/src/locale/en-US.ts
+++ b/packages/docs-ui/src/locale/en-US.ts
@@ -16,6 +16,9 @@
const locale = {
'docs-ui': {
+ outline: {
+ title: 'Outline',
+ },
objectPermission: {
paragraphPermission: 'Permissions',
title: 'Permissions',
diff --git a/packages/docs-ui/src/locale/es-ES.ts b/packages/docs-ui/src/locale/es-ES.ts
index 41ec82e9e9..3736ad9b45 100644
--- a/packages/docs-ui/src/locale/es-ES.ts
+++ b/packages/docs-ui/src/locale/es-ES.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ outline: {
+ title: 'Esquema del documento',
+ },
objectPermission: {
paragraphPermission: 'Permisos',
title: 'Permisos',
diff --git a/packages/docs-ui/src/locale/fa-IR.ts b/packages/docs-ui/src/locale/fa-IR.ts
index c6b0f43a24..53e7018839 100644
--- a/packages/docs-ui/src/locale/fa-IR.ts
+++ b/packages/docs-ui/src/locale/fa-IR.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ outline: {
+ title: 'طرح کلی سند',
+ },
objectPermission: {
paragraphPermission: 'مجوزها',
title: 'مجوزها',
diff --git a/packages/docs-ui/src/locale/fr-FR.ts b/packages/docs-ui/src/locale/fr-FR.ts
index edad18544f..3abda4d1f8 100644
--- a/packages/docs-ui/src/locale/fr-FR.ts
+++ b/packages/docs-ui/src/locale/fr-FR.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ outline: {
+ title: 'Plan du document',
+ },
objectPermission: {
paragraphPermission: 'Autorisations',
title: 'Autorisations',
diff --git a/packages/docs-ui/src/locale/id-ID.ts b/packages/docs-ui/src/locale/id-ID.ts
index b6a551eda7..a61db2d96e 100644
--- a/packages/docs-ui/src/locale/id-ID.ts
+++ b/packages/docs-ui/src/locale/id-ID.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ outline: {
+ title: 'Kerangka dokumen',
+ },
objectPermission: {
paragraphPermission: 'Izin',
title: 'Izin',
diff --git a/packages/docs-ui/src/locale/it-IT.ts b/packages/docs-ui/src/locale/it-IT.ts
index 8d6a5f5bbc..6296474f3a 100644
--- a/packages/docs-ui/src/locale/it-IT.ts
+++ b/packages/docs-ui/src/locale/it-IT.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ outline: {
+ title: 'Struttura del documento',
+ },
objectPermission: {
paragraphPermission: 'Autorizzazioni',
title: 'Autorizzazioni',
diff --git a/packages/docs-ui/src/locale/ja-JP.ts b/packages/docs-ui/src/locale/ja-JP.ts
index 4b8d70913e..5e678b4dbe 100644
--- a/packages/docs-ui/src/locale/ja-JP.ts
+++ b/packages/docs-ui/src/locale/ja-JP.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ outline: {
+ title: 'ドキュメントのアウトライン',
+ },
objectPermission: {
paragraphPermission: '権限',
title: '権限',
diff --git a/packages/docs-ui/src/locale/ko-KR.ts b/packages/docs-ui/src/locale/ko-KR.ts
index 9d42e273d0..39d1449a72 100644
--- a/packages/docs-ui/src/locale/ko-KR.ts
+++ b/packages/docs-ui/src/locale/ko-KR.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ outline: {
+ title: '문서 개요',
+ },
objectPermission: {
paragraphPermission: '권한',
title: '권한',
diff --git a/packages/docs-ui/src/locale/pl-PL.ts b/packages/docs-ui/src/locale/pl-PL.ts
index 081feb64b8..225ea25d47 100644
--- a/packages/docs-ui/src/locale/pl-PL.ts
+++ b/packages/docs-ui/src/locale/pl-PL.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ outline: {
+ title: 'Konspekt dokumentu',
+ },
objectPermission: {
paragraphPermission: 'Uprawnienia',
title: 'Uprawnienia',
diff --git a/packages/docs-ui/src/locale/pt-BR.ts b/packages/docs-ui/src/locale/pt-BR.ts
index a54c8e53de..856c9911a7 100644
--- a/packages/docs-ui/src/locale/pt-BR.ts
+++ b/packages/docs-ui/src/locale/pt-BR.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ outline: {
+ title: 'Estrutura do documento',
+ },
objectPermission: {
paragraphPermission: 'Permissões',
title: 'Permissões',
diff --git a/packages/docs-ui/src/locale/ru-RU.ts b/packages/docs-ui/src/locale/ru-RU.ts
index 94c6337331..a160a08561 100644
--- a/packages/docs-ui/src/locale/ru-RU.ts
+++ b/packages/docs-ui/src/locale/ru-RU.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ outline: {
+ title: 'Структура документа',
+ },
objectPermission: {
paragraphPermission: 'Права доступа',
title: 'Права доступа',
diff --git a/packages/docs-ui/src/locale/sk-SK.ts b/packages/docs-ui/src/locale/sk-SK.ts
index 0a7b0d12af..4ee1b1945d 100644
--- a/packages/docs-ui/src/locale/sk-SK.ts
+++ b/packages/docs-ui/src/locale/sk-SK.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ outline: {
+ title: 'Osnova dokumentu',
+ },
objectPermission: {
paragraphPermission: 'Oprávnenia',
title: 'Oprávnenia',
diff --git a/packages/docs-ui/src/locale/vi-VN.ts b/packages/docs-ui/src/locale/vi-VN.ts
index 76a6c293a5..7a4b782f44 100644
--- a/packages/docs-ui/src/locale/vi-VN.ts
+++ b/packages/docs-ui/src/locale/vi-VN.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ outline: {
+ title: 'Dàn ý tài liệu',
+ },
objectPermission: {
paragraphPermission: 'Quyền',
title: 'Quyền',
diff --git a/packages/docs-ui/src/locale/zh-CN.ts b/packages/docs-ui/src/locale/zh-CN.ts
index 108a857969..e17ca6b1e2 100644
--- a/packages/docs-ui/src/locale/zh-CN.ts
+++ b/packages/docs-ui/src/locale/zh-CN.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ outline: {
+ title: '文档大纲',
+ },
objectPermission: {
paragraphPermission: '权限',
title: '权限',
diff --git a/packages/docs-ui/src/locale/zh-HK.ts b/packages/docs-ui/src/locale/zh-HK.ts
index ca495a6c9d..3ec179da39 100644
--- a/packages/docs-ui/src/locale/zh-HK.ts
+++ b/packages/docs-ui/src/locale/zh-HK.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ outline: {
+ title: '文件大綱',
+ },
objectPermission: {
paragraphPermission: '權限',
title: '權限',
diff --git a/packages/docs-ui/src/locale/zh-TW.ts b/packages/docs-ui/src/locale/zh-TW.ts
index 68040ba123..e3bee68cc3 100644
--- a/packages/docs-ui/src/locale/zh-TW.ts
+++ b/packages/docs-ui/src/locale/zh-TW.ts
@@ -18,6 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'docs-ui': {
+ outline: {
+ title: '文件大綱',
+ },
objectPermission: {
paragraphPermission: '權限',
title: '權限',
diff --git a/packages/docs-ui/src/views/DocSideMenu.tsx b/packages/docs-ui/src/views/DocSideMenu.tsx
index 770b0fddbd..f0c91ce743 100644
--- a/packages/docs-ui/src/views/DocSideMenu.tsx
+++ b/packages/docs-ui/src/views/DocSideMenu.tsx
@@ -16,20 +16,23 @@
import type { DocumentDataModel, IParagraph } from '@univerjs/core';
import type { IUniverDocsUIConfig } from '../config/config';
+import type { LocaleKey } from '../locale/types';
import type { IMutiPageParagraphBound } from '../services/doc-event-manager.service';
import type { ISideMenuItem } from './SideMenu';
import {
fromEventSubject,
+ getParagraphContentStartOffsets,
getPlainText,
isInternalEditorID,
IUniverInstanceService,
+ LocaleService,
NamedStyleType,
UniverInstanceType,
} from '@univerjs/core';
import { IRenderManagerService } from '@univerjs/engine-render';
import { IWorkbenchService, useConfigValue, useDependency, useEvent, useObservable } from '@univerjs/ui';
import { useEffect, useMemo, useState } from 'react';
-import { debounceTime, map, startWith, throttleTime } from 'rxjs';
+import { auditTime, debounceTime, map, merge, startWith, throttleTime } from 'rxjs';
import { VIEWPORT_KEY } from '../basics/docs-view-key';
import { DOCS_UI_PLUGIN_CONFIG_KEY } from '../config/config';
import { DocEventManagerService } from '../services/doc-event-manager.service';
@@ -97,6 +100,7 @@ export function DocSideMenu() {
function DocSideMenuContent() {
const instanceService = useDependency(IUniverInstanceService);
+ const localeService = useDependency(LocaleService);
const currentDoc = useObservable(
() => instanceService.getCurrentTypeOfUnit$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC),
undefined,
@@ -125,12 +129,16 @@ function DocSideMenuContent() {
const readLayout = () => ({
left: renderer?.mainComponent?.left ?? 0,
canvasHeight: renderer?.engine.height ?? 0,
+ canvasWidth: renderer?.engine.width ?? 0,
scaleY: renderer?.scene.scaleY ?? 1,
});
const layout = useObservable(
renderer?.engine.onTransformChange$
- ? () => fromEventSubject(renderer.engine.onTransformChange$).pipe(
- throttleTime(33),
+ ? () => merge(
+ fromEventSubject(renderer.engine.onTransformChange$),
+ ...(renderer.mainComponent ? [fromEventSubject(renderer.mainComponent.onTransformChange$)] : [])
+ ).pipe(
+ auditTime(33),
map(readLayout),
startWith(readLayout())
)
@@ -139,9 +147,10 @@ function DocSideMenuContent() {
false,
[renderer]
);
- const { left, canvasHeight, scaleY } = layout;
+ const { left, canvasHeight, canvasWidth, scaleY } = layout;
const paragraphs = useMemo(() => documentData?.body?.paragraphs ?? [], [documentData?.body?.paragraphs]);
+ const paragraphStarts = useMemo(() => getParagraphContentStartOffsets({ dataStream: fullDataStream, paragraphs }), [fullDataStream, paragraphs]);
const paragraphMap = useMemo(() => {
const map = new Map<number, IParagraph>();
paragraphs.forEach((p) => {
@@ -149,7 +158,7 @@ function DocSideMenuContent() {
});
return map;
}, [paragraphs]);
- const mode = left < 180 ? 'float' : 'side-bar';
+ const mode = left < 240 ? 'float' : 'side-bar';
const paragraphMenus = paragraphs
?.filter((p) =>
p.paragraphStyle?.namedStyleType !== undefined &&
@@ -158,13 +167,9 @@ function DocSideMenuContent() {
)
.map((p) => {
const level = transformNamedStyleTypeToLevel(p.paragraphStyle!.namedStyleType!);
- const bound = paragraphBounds?.get(p.startIndex);
- if (!bound) return null;
- const { paragraphStart, paragraphEnd } = bound;
-
return {
id: p.paragraphStyle!.headingId!,
- text: getPlainText(fullDataStream.slice(paragraphStart, paragraphEnd)),
+ text: getPlainText(fullDataStream.slice(paragraphStarts.get(p.startIndex)!, p.startIndex)),
level,
isTitle: p.paragraphStyle?.namedStyleType === NamedStyleType.TITLE,
};
@@ -217,6 +222,7 @@ function DocSideMenuContent() {
if (menu.id === TITLE_ID) {
viewport.scrollToViewportPos({ viewportScrollY: 0 });
+ setActiveId(menu.id);
return;
}
const paragraph = paragraphs.find((p) => p.paragraphStyle?.headingId === menu.id);
@@ -241,15 +247,16 @@ function DocSideMenuContent() {
className="univer-absolute univer-bottom-0 univer-left-0 univer-top-0 univer-z-[100] univer-w-[0px]"
>
<SideMenu
+ label={localeService.t<LocaleKey>('docs-ui.outline.title')}
menus={menus}
open={open}
onOpenChange={setOpen}
mode={mode}
- maxWidth={mode === 'float' ? undefined : Math.floor(left) - 10}
- wrapperClass="univer-mt-12"
+ maxWidth={Math.max(0, Math.floor(mode === 'float' ? canvasWidth : left) - 24)}
+ wrapperClass="univer-mt-4"
activeId={activeId}
onClick={handleClick}
- maxHeight={canvasHeight - 48}
+ maxHeight={Math.max(0, canvasHeight - 32)}
/>
</div>
);
diff --git a/packages/docs-ui/src/views/SideMenu.tsx b/packages/docs-ui/src/views/SideMenu.tsx
index 833ab4bed4..010761295a 100644
--- a/packages/docs-ui/src/views/SideMenu.tsx
+++ b/packages/docs-ui/src/views/SideMenu.tsx
@@ -14,10 +14,10 @@
* limitations under the License.
*/
-import type { CSSProperties } from 'react';
+import type { CSSProperties, KeyboardEvent } from 'react';
import { clsx, scrollbarClassName } from '@univerjs/design';
import { CatalogueIcon, MoreLeftIcon } from '@univerjs/icons';
-import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef } from 'react';
+import { forwardRef, useEffect, useId, useImperativeHandle, useMemo, useRef } from 'react';
export interface ISideMenuItem {
text: string;
@@ -27,6 +27,7 @@ export interface ISideMenuItem {
}
export interface ISideMenuProps {
+ label: string;
menus?: ISideMenuItem[];
onClick?: (menu: ISideMenuItem) => void;
className?: string;
@@ -48,113 +49,209 @@ export interface ISideMenuInstance {
}
export const SideMenu = forwardRef<ISideMenuInstance, ISideMenuProps>((props, ref) => {
- const { menus, onClick, className, style, mode, maxHeight, activeId, open, onOpenChange, maxWidth, wrapperClass, wrapperStyle, iconClass, iconStyle } = props;
- const isSideBar = mode === 'side-bar';
+ const { label, menus, onClick, className, style, mode, maxHeight, activeId, open, onOpenChange, maxWidth, wrapperClass, wrapperStyle, iconClass, iconStyle } = props;
+ const panelId = useId();
+ const wrapperRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
- const menusRef = useRef(menus);
- menusRef.current = menus;
+ const toggleRef = useRef<HTMLButtonElement>(null);
+ const itemsRef = useRef(new Map<string, HTMLButtonElement>());
+ const width = Math.min(256, maxWidth ?? 256);
const instance: ISideMenuInstance = useMemo(() => ({
scrollTo: (id: string) => {
- if (!menusRef.current) return;
- const index = menusRef.current.findIndex((menu) => menu.id === id);
- if (index === -1 || !containerRef.current) return;
+ const container = containerRef.current;
+ const target = itemsRef.current.get(id);
+ if (!container || !target) return;
- // Find the actual DOM element by its ID
- const targetElement = document.getElementById(`univer-side-menu-${id}`);
- if (!targetElement) return;
-
- // Get the element's offsetTop relative to its parent
- const targetTop = targetElement.offsetTop;
-
- // Get container's scrollable height
- const containerHeight = containerRef.current.clientHeight;
- const maxScrollTop = containerRef.current.scrollHeight - containerHeight;
-
- // Calculate the scroll position to center the element if possible
- const scrollPosition = Math.max(0, Math.min(targetTop - containerHeight / 2 + targetElement.clientHeight / 2, maxScrollTop));
-
- containerRef.current?.scrollTo({
- behavior: 'smooth',
- top: scrollPosition,
- });
+ const top = target.offsetTop;
+ const bottom = top + target.offsetHeight;
+ if (top < container.scrollTop) {
+ container.scrollTo({ top });
+ } else if (bottom > container.scrollTop + container.clientHeight) {
+ container.scrollTo({ top: bottom - container.clientHeight });
+ }
},
}), []);
useImperativeHandle(ref, () => instance);
useEffect(() => {
- if (activeId) {
+ if (open && activeId) {
instance.scrollTo(activeId);
}
- }, [activeId, instance]);
+ }, [activeId, instance, open]);
+
+ useEffect(() => {
+ if (!open || mode !== 'float') return;
+
+ const handlePointerDown = (event: PointerEvent) => {
+ if (event.target instanceof Node && !wrapperRef.current?.contains(event.target)) {
+ onOpenChange?.(false);
+ }
+ };
+ document.addEventListener('pointerdown', handlePointerDown);
+ return () => document.removeEventListener('pointerdown', handlePointerDown);
+ }, [mode, onOpenChange, open]);
+
+ const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
+ if (event.key === 'Escape' && open) {
+ event.preventDefault();
+ event.stopPropagation();
+ onOpenChange?.(false);
+ toggleRef.current?.focus();
+ return;
+ }
+ const items = Array.from(itemsRef.current.values());
+ const index = items.indexOf(event.target as HTMLButtonElement);
+ if (index === -1) return;
+
+ let next: number;
+ switch (event.key) {
+ case 'ArrowDown':
+ next = Math.min(index + 1, items.length - 1);
+ break;
+ case 'ArrowUp':
+ next = Math.max(index - 1, 0);
+ break;
+ case 'Home':
+ next = 0;
+ break;
+ case 'End':
+ next = items.length - 1;
+ break;
+ default: return;
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ items[next]?.focus();
+ };
return (
- <div className={clsx('univer-relative', wrapperClass)} style={wrapperStyle}>
- <div
+ <div
+ ref={wrapperRef}
+ className={clsx('univer-relative univer-ml-3', wrapperClass)}
+ style={{ width, ...wrapperStyle }}
+ onKeyDown={handleKeyDown}
+ >
+ <button
+ ref={toggleRef}
+ type="button"
+ aria-label={label}
+ aria-expanded={!!open}
+ aria-controls={open ? panelId : undefined}
+ title={label}
onClick={() => onOpenChange?.(!open)}
className={clsx(`
- univer-absolute univer-left-5 univer-top-4 univer-z-[100] univer-flex univer-size-8
- univer-cursor-pointer univer-items-center univer-justify-center univer-rounded-full univer-bg-gray-0
- univer-text-gray-800 univer-shadow-sm
- dark:!univer-bg-gray-600 dark:!univer-text-gray-200
- `, iconClass)}
- style={iconStyle}
- >
- {open ? <MoreLeftIcon /> : <CatalogueIcon />}
- </div>
- <div
- className={clsx(
- className,
- `
- univer-absolute univer-left-0 univer-top-0 univer-box-border univer-flex univer-min-w-[180px]
- univer-flex-col univer-px-4 univer-pb-4 univer-pt-14 univer-transition-all univer-duration-300
- `,
- {
- 'univer-rounded-r-2xl univer-bg-gray-0 univer-shadow univer-backdrop-blur-[10px] dark:!univer-bg-gray-900': isSideBar,
- }
- )}
- style={{
- ...style,
- transform: open ? 'translateX(0)' : 'translateX(-100%)',
- maxHeight,
- opacity: open ? 1 : 0,
- maxWidth: maxWidth ?? (mode === 'side-bar' ? 320 : 180),
- paddingRight: mode === 'float' ? undefined : 0,
- }}
+ univer-absolute univer-top-1.5 univer-z-10 univer-flex univer-size-8 univer-cursor-pointer
+ univer-items-center univer-justify-center univer-rounded-md univer-border-0 univer-bg-gray-0
+ univer-text-gray-500 univer-transition-colors
+ hover:univer-bg-gray-100 hover:univer-text-gray-900
+ focus-visible:univer-outline focus-visible:univer-outline-2 focus-visible:univer-outline-primary-600
+ dark:univer-bg-gray-900 dark:univer-text-gray-400
+ dark:hover:univer-bg-gray-800
+ `, !open && 'univer-shadow-sm', iconClass)}
+ style={{ left: open ? width - 40 : 0, ...iconStyle }}
>
- <div
- ref={containerRef}
- className={clsx('univer-flex-1 univer-overflow-y-auto univer-overflow-x-hidden', scrollbarClassName)}
+ {open ? <MoreLeftIcon aria-hidden="true" /> : <CatalogueIcon aria-hidden="true" />}
+ </button>
+ {open && (
+ <nav
+ id={panelId}
+ aria-label={label}
+ className={clsx(`
+ univer-box-border univer-flex univer-w-full univer-flex-col univer-overflow-hidden
+ univer-rounded-lg univer-border univer-border-solid univer-border-gray-200 univer-bg-gray-0
+ univer-text-gray-700
+ dark:univer-border-gray-700 dark:univer-bg-gray-900 dark:univer-text-gray-200
+ `, mode === 'float' ? 'univer-shadow-md' : 'univer-shadow-sm', className)}
+ style={{ maxHeight, ...style }}
>
- {menus?.map((menu) => (
- <div
- id={`univer-side-menu-${menu.id}`}
- key={menu.id}
- className={clsx(
- `
- univer-mb-2 univer-h-[24px] univer-cursor-pointer univer-truncate univer-pr-1
- univer-font-[500] univer-leading-[24px]
- `,
- {
- 'univer-text-base univer-font-semibold': menu.isTitle,
- 'univer-text-sm univer-font-semibold': menu.level === 1,
- 'univer-text-sm': menu.level > 1,
- 'univer-text-gray-500 dark:!univer-text-gray-400': menu.id !== activeId,
- 'univer-text-gray-800 dark:!univer-text-gray-200': menu.id === activeId,
- }
- )}
- style={{
- paddingLeft: (menu.level - 1) * 12,
- }}
- onClick={() => {
- onClick?.(menu);
- }}
- >
- {menu.text}
- </div>
- ))}
- </div>
- </div>
+ <div
+ className="
+ univer-flex univer-h-11 univer-shrink-0 univer-items-center univer-gap-2 univer-px-3
+ univer-pr-12 univer-text-xs univer-font-medium univer-text-gray-500
+ dark:univer-text-gray-400
+ "
+ >
+ <CatalogueIcon aria-hidden="true" className="univer-shrink-0 univer-text-sm" />
+ <span className="univer-truncate">{label}</span>
+ </div>
+ <div
+ ref={containerRef}
+ className={clsx(`
+ univer-relative univer-min-h-0 univer-overflow-y-auto univer-overscroll-contain univer-px-2
+ univer-pb-2
+ `, scrollbarClassName)}
+ >
+ <ol className="univer-m-0 univer-list-none univer-p-0">
+ {menus?.map((menu) => (
+ <li key={menu.id} className={menu.isTitle ? 'univer-mb-1 univer-pb-1' : undefined}>
+ <button
+ ref={(element) => {
+ if (element) itemsRef.current.set(menu.id, element);
+ else itemsRef.current.delete(menu.id);
+ }}
+ type="button"
+ aria-current={menu.id === activeId ? 'location' : undefined}
+ title={menu.text}
+ className={clsx(`
+ univer-relative univer-box-border univer-flex univer-min-h-8 univer-w-full
+ univer-cursor-pointer univer-items-center univer-rounded univer-border-0
+ univer-bg-transparent univer-py-1.5 univer-pr-2 univer-text-left
+ univer-text-sm univer-leading-5 univer-transition-colors
+ hover:univer-bg-gray-100
+ focus-visible:univer-outline focus-visible:univer-outline-2
+ focus-visible:-univer-outline-offset-2
+ focus-visible:univer-outline-primary-600
+ dark:hover:univer-bg-gray-800
+ `, menu.isTitle ? 'univer-font-semibold' : 'univer-font-normal', {
+ 'univer-bg-primary-50 univer-text-primary-700 hover:univer-bg-primary-50 dark:univer-bg-gray-700 dark:univer-text-primary-200 dark:hover:univer-bg-gray-700': menu.id === activeId,
+ 'univer-text-gray-900 dark:univer-text-gray-100': menu.isTitle && menu.id !== activeId,
+ 'univer-text-gray-600 dark:univer-text-gray-300': !menu.isTitle && menu.id !== activeId,
+ })}
+ style={{ paddingLeft: 10 + Math.max(0, menu.level - 1) * 12 }}
+ onClick={() => {
+ onClick?.(menu);
+ if (mode === 'float') {
+ onOpenChange?.(false);
+ toggleRef.current?.focus();
+ }
+ }}
+ >
+ {menu.level > 1 && (
+ <span
+ aria-hidden="true"
+ className="
+ univer-absolute univer-bottom-0 univer-top-0 univer-w-px
+ univer-bg-gray-200
+ dark:univer-bg-gray-700
+ "
+ style={{ left: 14 + Math.max(0, menu.level - 2) * 12 }}
+ />
+ )}
+ {menu.id === activeId && (
+ <span
+ aria-hidden="true"
+ className="
+ univer-absolute univer-bottom-2 univer-left-0 univer-top-2
+ univer-w-0.5 univer-rounded-full univer-bg-primary-600
+ dark:univer-bg-primary-400
+ "
+ />
+ )}
+ <span
+ className={menu.isTitle
+ ? 'univer-line-clamp-2 univer-break-words'
+ : 'univer-truncate'}
+ >
+ {menu.text}
+ </span>
+ </button>
+ </li>
+ ))}
+ </ol>
+ </div>
+ </nav>
+ )}
</div>
);
});
diff --git a/packages/docs-ui/src/views/__tests__/SideMenu.spec.tsx b/packages/docs-ui/src/views/__tests__/SideMenu.spec.tsx
index 94811fbb6c..be55a4d916 100644
--- a/packages/docs-ui/src/views/__tests__/SideMenu.spec.tsx
+++ b/packages/docs-ui/src/views/__tests__/SideMenu.spec.tsx
@@ -14,97 +14,92 @@
* limitations under the License.
*/
+import type { ComponentProps } from 'react';
import type { Root } from 'react-dom/client';
-import { act } from 'react';
+import { act, useState } from 'react';
import { createRoot } from 'react-dom/client';
-import { afterEach, describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
import { SideMenu } from '../SideMenu';
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
const menus = [
- { id: 'title', level: 1, text: 'Document outline', isTitle: true },
+ { id: 'title', level: 1, text: 'Harbor habitat field report', isTitle: true },
{ id: 'intro', level: 1, text: 'Introduction' },
{ id: 'details', level: 2, text: 'Details' },
];
-function renderSideMenu(props: React.ComponentProps<typeof SideMenu>) {
+function renderSideMenu(props: Partial<ComponentProps<typeof SideMenu>> = {}) {
const container = document.createElement('div');
document.body.appendChild(container);
const root = createRoot(container);
- act(() => {
- root.render(<SideMenu {...props} />);
- });
+ function Example() {
+ const [open, setOpen] = useState(props.open ?? true);
+ return <SideMenu label="Document outline" menus={menus} maxHeight={180} {...props} open={open} onOpenChange={setOpen} />;
+ }
+ act(() => root.render(<Example />));
return { container, root };
}
describe('SideMenu', () => {
let root: Root | undefined;
- let container: HTMLElement | undefined;
+ let container: HTMLElement;
afterEach(() => {
- if (root) {
- act(() => root!.unmount());
- }
+ act(() => root?.unmount());
container?.remove();
root = undefined;
- container = undefined;
});
- it('emits the clicked outline item with its document location metadata', () => {
- const selectedItems: typeof menus = [];
- const rendered = renderSideMenu({
- menus,
- maxHeight: 180,
- open: true,
- onClick: (menu) => {
- selectedItems.push(menu);
- },
- });
- root = rendered.root;
- container = rendered.container;
-
- const detailsItem = Array.from(container.querySelectorAll('div')).find((element) => element.textContent === 'Details');
- if (!detailsItem) {
- throw new Error('Missing Details menu item');
- }
-
- act(() => {
- detailsItem.dispatchEvent(new MouseEvent('click', { bubbles: true }));
- });
-
- expect(selectedItems).toEqual([{ id: 'details', level: 2, text: 'Details' }]);
+ it('selects a heading with its document location metadata and marks the current location', () => {
+ const onClick = vi.fn();
+ ({ root, container } = renderSideMenu({ onClick, activeId: 'intro' }));
+ const details = container.querySelector<HTMLButtonElement>('button[title="Details"]')!;
+ act(() => details.click());
+ expect(onClick).toHaveBeenCalledWith(menus[2]);
+ expect(container.querySelector('[aria-current="location"]')?.textContent).toBe('Introduction');
});
- it('requests an open state change and translates the panel from the controlled state', () => {
- const openStates: boolean[] = [];
- const rendered = renderSideMenu({
- menus,
- maxHeight: 180,
- open: false,
- mode: 'side-bar',
- onOpenChange: (open) => {
- openStates.push(open);
- },
- });
- root = rendered.root;
- container = rendered.container;
+ it('removes closed headings from keyboard navigation and restores them when reopened', () => {
+ ({ root, container } = renderSideMenu({ open: false }));
+ const toggle = container.querySelector<HTMLButtonElement>('button[aria-expanded]')!;
+ expect(container.querySelector('nav')).toBeNull();
+ act(() => toggle.click());
+ expect(toggle.getAttribute('aria-expanded')).toBe('true');
+ expect(container.querySelector('nav')?.getAttribute('id')).toBe(toggle.getAttribute('aria-controls'));
+ expect(container.querySelectorAll('nav button')).toHaveLength(3);
+ act(() => toggle.click());
+ expect(toggle.getAttribute('aria-expanded')).toBe('false');
+ expect(container.querySelector('nav')).toBeNull();
+ });
- const toggle = container.firstElementChild?.firstElementChild;
- const panel = container.firstElementChild?.children.item(1) as HTMLElement | null;
- if (!toggle || !panel) {
- throw new Error('Missing side menu toggle or panel');
+ it('supports arrow, Home and End navigation and returns focus on Escape', () => {
+ ({ root, container } = renderSideMenu());
+ const buttons = container.querySelectorAll<HTMLButtonElement>('nav button');
+ buttons[0].focus();
+ for (const [key, expectedIndex] of [['ArrowDown', 1], ['End', 2], ['ArrowUp', 1], ['Home', 0]] as const) {
+ act(() => document.activeElement?.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true })));
+ expect(document.activeElement).toBe(buttons[expectedIndex]);
}
+ act(() => document.activeElement?.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })));
+ expect(container.querySelector('nav')).toBeNull();
+ expect(document.activeElement).toBe(container.querySelector('button[aria-expanded="false"]'));
+ });
- expect(panel.style.transform).toBe('translateX(-100%)');
-
- act(() => {
- toggle.dispatchEvent(new MouseEvent('click', { bubbles: true }));
- });
+ it.each(['float', 'side-bar'] as const)('dismisses only floating navigation after a heading click (%s)', (mode) => {
+ const onClick = vi.fn();
+ ({ root, container } = renderSideMenu({ mode, onClick }));
+ act(() => container.querySelector<HTMLButtonElement>('button[title="Details"]')!.click());
+ expect(onClick).toHaveBeenCalledWith(menus[2]);
+ expect(container.querySelector('nav') !== null).toBe(mode === 'side-bar');
+ });
- expect(openStates).toEqual([true]);
- expect(panel.style.transform).toBe('translateX(-100%)');
+ it.each(['float', 'side-bar'] as const)('dismisses only floating navigation on an outside pointer interaction (%s)', (mode) => {
+ ({ root, container } = renderSideMenu({ mode }));
+ act(() => document.body.dispatchEvent(new Event('pointerdown', { bubbles: true })));
+ expect(container.querySelector('nav') !== null).toBe(mode === 'side-bar');
});
});
diff --git a/packages/docs-ui/src/views/side-menu/SideMenu.stories.tsx b/packages/docs-ui/src/views/side-menu/SideMenu.stories.tsx
index 9a4a66dbb0..f91d2abd01 100644
--- a/packages/docs-ui/src/views/side-menu/SideMenu.stories.tsx
+++ b/packages/docs-ui/src/views/side-menu/SideMenu.stories.tsx
@@ -47,6 +47,7 @@ export const SideMenuBasic = {
return (
<SideMenu
+ label="Document outline"
maxHeight={150}
menus={menus}
onClick={handleClick}
@@ -60,7 +61,7 @@ export const SideMenuBasic = {
export const EmptySideMenu = {
render() {
- return <SideMenu maxHeight={150} />;
+ return <SideMenu label="Document outline" maxHeight={150} />;
},
};
@@ -78,7 +79,7 @@ export const CustomStyledSideMenu = {
borderRadius: '4px',
};
- return <SideMenu maxHeight={150} menus={menus} className="custom-side-menu" style={customStyle} />;
+ return <SideMenu label="Document outline" maxHeight={150} menus={menus} className="custom-side-menu" style={customStyle} />;
},
};
@@ -97,6 +98,6 @@ export const MultiLevelSideMenu = {
const handleClick = (_menu: ISideMenuItem) => {
};
- return <SideMenu maxHeight={150} menus={menus} onClick={handleClick} />;
+ return <SideMenu label="Document outline" maxHeight={150} menus={menus} onClick={handleClick} />;
},
};
diff --git a/presets/packages/preset-docs-core/src/preset.ts b/presets/packages/preset-docs-core/src/preset.ts
index 52764ee66b..53f740c2d4 100644
--- a/presets/packages/preset-docs-core/src/preset.ts
+++ b/presets/packages/preset-docs-core/src/preset.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { IUniverDocsUIConfig } from '@univerjs/docs-ui';
import type { IPreset } from '@univerjs/presets';
import type { IUniverUIConfig } from '@univerjs/ui';
import { UniverDocsPlugin } from '@univerjs/docs';
@@ -30,7 +31,8 @@ export type * from '@univerjs/docs-ui/facade';
export type * from '@univerjs/network/facade';
export interface IUniverDocsCorePresetConfig extends
- Pick<IUniverUIConfig, 'container' | 'header' | 'footer' | 'toolbar' | 'ribbonType' | 'menu' | 'contextMenu' | 'disableAutoFocus'> {
+ Pick<IUniverUIConfig, 'container' | 'header' | 'footer' | 'toolbar' | 'ribbonType' | 'menu' | 'contextMenu' | 'disableAutoFocus'>,
+ Pick<IUniverDocsUIConfig, 'toc'> {
collaboration?: true;
}
@@ -44,6 +46,7 @@ export function UniverDocsCorePreset(config: Partial<IUniverDocsCorePresetConfig
menu,
contextMenu,
disableAutoFocus,
+ toc,
} = config;
return {
@@ -61,7 +64,7 @@ export function UniverDocsCorePreset(config: Partial<IUniverDocsCorePresetConfig
contextMenu,
disableAutoFocus,
}],
- UniverDocsUIPlugin,
+ [UniverDocsUIPlugin, { toc }],
UniverFormulaEnginePlugin,
],
};