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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
fix(docs-ui): use paragraph identities for document outlines (#7919)
Univer1e585787f94f
diff --git a/packages/docs-ui/src/views/DocSideMenu.tsx b/packages/docs-ui/src/views/DocSideMenu.tsxindex 9739f7520a..30a9f4a302 100644--- a/packages/docs-ui/src/views/DocSideMenu.tsx+++ b/packages/docs-ui/src/views/DocSideMenu.tsx@@ -70,21 +70,30 @@ function findActiveHeading(boundMap: Map<number, IMutiPageParagraphBound> | unde}const paragraphBounds = Array.from(boundMap.values());const paragraphIndex = paragraphBounds.findIndex((p) => p.paragraphStart !== p.paragraphEnd && p.rect.top < bottom && p.rect.bottom > scrollTop);- if (paragraphIndex === -1) return undefined;- const lastParagraphIndex = paragraphBounds?.findLastIndex((p) => p.paragraphStart !== p.paragraphEnd && p.rect.top < bottom && p.rect.bottom > scrollTop);+ if (paragraphIndex === -1) {+ return undefined;+ }+ let lastParagraphIndex = paragraphBounds.length - 1;+ while (lastParagraphIndex > paragraphIndex) {+ const bound = paragraphBounds[lastParagraphIndex];+ if (bound.paragraphStart !== bound.paragraphEnd && bound.rect.top < bottom && bound.rect.bottom > scrollTop) {+ break;+ }+ lastParagraphIndex--;+ }for (let i = paragraphIndex; i <= lastParagraphIndex; i++) {const bound = paragraphBounds[i];const paragraph = paragraphMap.get(bound.startIndex);- if (paragraph?.paragraphStyle?.headingId) {- return paragraph.paragraphStyle.headingId;+ if (paragraph) {+ return paragraph.paragraphId;}}for (let i = paragraphIndex; i >= 0; i--) {const bound = paragraphBounds[i];const paragraph = paragraphMap.get(bound.startIndex);- if (paragraph?.paragraphStyle?.headingId) {- return paragraph.paragraphStyle.headingId;+ if (paragraph) {+ return paragraph.paragraphId;}}@@ -184,24 +193,30 @@ function DocSideMenuContent({ toc }: { toc?: boolean }) {const paragraphs = useMemo(() => documentData?.body?.paragraphs ?? [], [documentData?.body?.paragraphs]);const paragraphStarts = useMemo(() => getParagraphContentStartOffsets({ dataStream: fullDataStream, paragraphs }), [fullDataStream, paragraphs]);+ const headingParagraphs = useMemo(() => paragraphs.filter((p) =>+ p.paragraphStyle?.namedStyleType !== undefined &&+ p.paragraphStyle.namedStyleType !== NamedStyleType.SUBTITLE &&+ p.paragraphStyle.namedStyleType !== NamedStyleType.NORMAL_TEXT+ ).map((p) => p.paragraphId+ ? p+ : {+ ...p,+ // Legacy snapshots can omit paragraph IDs; keep their fallback local to the outline.+ paragraphId: `__paragraph_${p.startIndex}`,+ }), [paragraphs]);const paragraphMap = useMemo(() => {const map = new Map<number, IParagraph>();- paragraphs.forEach((p) => {+ headingParagraphs.forEach((p) => {map.set(p.startIndex, p);});return map;- }, [paragraphs]);+ }, [headingParagraphs]);const mode = left < 288 || layout.overlapsTable ? 'float' : 'side-bar';- const paragraphMenus = paragraphs- ?.filter((p) =>- p.paragraphStyle?.namedStyleType !== undefined &&- p.paragraphStyle!.namedStyleType !== NamedStyleType.SUBTITLE &&- p.paragraphStyle.namedStyleType !== NamedStyleType.NORMAL_TEXT- )+ const paragraphMenus = headingParagraphs.map((p) => {const level = transformNamedStyleTypeToLevel(p.paragraphStyle!.namedStyleType!);return {- id: p.paragraphStyle!.headingId!,+ id: p.paragraphId,text: getPlainText(fullDataStream.slice(paragraphStarts.get(p.startIndex)!, p.startIndex)),level,isTitle: p.paragraphStyle?.namedStyleType === NamedStyleType.TITLE,@@ -280,7 +295,7 @@ function DocSideMenuContent({ toc }: { toc?: boolean }) {setActiveId(menu.id);return;}- const paragraph = paragraphs.find((p) => p.paragraphStyle?.headingId === menu.id);+ const paragraph = headingParagraphs.find((p) => p.paragraphId === menu.id);if (!paragraph) {return;}diff --git a/packages/docs-ui/src/views/__tests__/DocSideMenu.spec.tsx b/packages/docs-ui/src/views/__tests__/DocSideMenu.spec.tsxindex 55d530fbf6..4a01e627d9 100644--- a/packages/docs-ui/src/views/__tests__/DocSideMenu.spec.tsx+++ b/packages/docs-ui/src/views/__tests__/DocSideMenu.spec.tsx@@ -23,6 +23,7 @@ import {IUniverInstanceService,LocaleService,LocaleType,+ NamedStyleType,Univer,UniverInstanceType,} from '@univerjs/core';@@ -33,6 +34,7 @@ import {ICanvasColorService,IRenderManagerService,RenderManagerService,+ ScrollBar,setDocsTableRenderViewportProvider,Viewport,} from '@univerjs/engine-render';@@ -216,4 +218,76 @@ describe('DocSideMenu', () => {expect(container.querySelector('button[aria-expanded="true"]')).not.toBeNull();expect(container.querySelector('nav')?.textContent).toContain('Short outline');});++ it.each([+ [undefined, true],+ ['shared-heading-id', true],+ ['legacy-heading-id', false],+ ] as const)('navigates and highlights headings with headingId %s and paragraph IDs %s', (headingId, hasParagraphIds) => {+ const injector = univer.__getInjector();+ injector.get(IConfigService).setConfig(DOCS_UI_PLUGIN_CONFIG_KEY, { toc: true });+ const lines = ['First heading', ...Array.from({ length: 60 }, () => 'Body text'), 'Second heading', 'Final body'];+ let offset = 0;+ const data: IDocumentData = {+ id: 'headings',+ title: 'Document title',+ body: {+ dataStream: `${lines.join('\r')}\r\n`,+ paragraphs: lines.map((text, index) => {+ offset += text.length + 1;+ return {+ startIndex: offset - 1,+ paragraphId: `paragraph-${index}`,+ paragraphStyle: {+ namedStyleType: index === 0 || index === 61 ? NamedStyleType.HEADING_1 : NamedStyleType.NORMAL_TEXT,+ headingId: hasParagraphIds ? headingId : `${headingId}-${index}`,+ },+ };+ }),+ sectionBreaks: [{ startIndex: lines.join('\r').length + 1, sectionId: 'section' }],+ },+ documentStyle: { pageSize: { width: 1400, height: 2400 } },+ };+ if (!hasParagraphIds) {+ data.body!.paragraphs!.forEach((paragraph) => Reflect.deleteProperty(paragraph, 'paragraphId'));+ }+ const originalHeadingIds = data.body!.paragraphs!.map((paragraph) => paragraph.paragraphStyle?.headingId);+ const originalParagraphIds = data.body!.paragraphs!.map((paragraph) => paragraph.paragraphId);+ const model = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, data);+ const render = injector.get(IRenderManagerService).createRender(data.id) as RenderUnit;+ render.deactivate();+ render.engine.resizeBySize(1400, 400);+ render.addRenderDependencies([[DocSkeletonManagerService]]);+ const documents = new Documents(data.id, render.with(DocSkeletonManagerService).getSkeleton());+ documents.translate(400, 0);+ render.mainComponent = documents;+ render.scene.addObject(documents);+ render.components.set(data.id, documents);+ const viewport = new Viewport(VIEWPORT_KEY.VIEW_MAIN, render.scene);+ render.disposeWithMe(viewport);+ render.disposeWithMe(new ScrollBar(viewport, { mainScene: render.scene }));+ render.scene.transformByState({ width: 1400, height: 3000 });+ render.addRenderDependencies([[DocEventManagerService]]);+ const bounds = render.with(DocEventManagerService).paragraphBounds;+ const secondHeadingTop = bounds.get(data.body!.paragraphs![61].startIndex)!.rect.top;+ expect(secondHeadingTop).toBeGreaterThan(400);++ act(() => root.render(<RediContext.Provider value={{ injector }}><DocSideMenu /></RediContext.Provider>));+ act(() => vi.advanceTimersByTime(150));+ const headingButtons = Array.from(container.querySelectorAll<HTMLButtonElement>('nav button'));+ expect(headingButtons.map((button) => button.textContent)).toEqual(['Document title', 'First heading', 'Second heading']);+ expect(container.querySelectorAll('[aria-current="location"]')).toHaveLength(0);++ act(() => headingButtons[2].click());+ expect(viewport.viewportScrollY).toBeCloseTo(secondHeadingTop);+ expect(container.querySelectorAll('[aria-current="location"]')).toHaveLength(1);+ expect(headingButtons[2].getAttribute('aria-current')).toBe('location');++ act(() => vi.advanceTimersByTime(100));+ act(() => viewport.scrollToViewportPos({ viewportScrollY: bounds.get(data.body!.paragraphs![10].startIndex)!.rect.top }));+ expect(container.querySelectorAll('[aria-current="location"]')).toHaveLength(1);+ expect(headingButtons[1].getAttribute('aria-current')).toBe('location');+ expect(model.getBody()?.paragraphs?.map((paragraph) => paragraph.paragraphStyle?.headingId)).toEqual(originalHeadingIds);+ expect(model.getBody()?.paragraphs?.map((paragraph) => paragraph.paragraphId)).toEqual(originalParagraphIds);+ });});