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
feat(docs-ui): support doc heading menu (#4891)
ZhangWeib17785e640ca
diff --git a/packages/core/src/docs/data-model/preset-list-type.ts b/packages/core/src/docs/data-model/preset-list-type.tsindex 771017efff..832d068c50 100644--- a/packages/core/src/docs/data-model/preset-list-type.ts+++ b/packages/core/src/docs/data-model/preset-list-type.ts@@ -27,6 +27,7 @@ export enum QuickListType {ORDER_LIST_QUICK_5 = 'A.',ORDER_LIST_QUICK_6 = 'I.',ORDER_LIST_QUICK_7 = '01.',+ BULLET_LIST = '*',}export enum PresetListType {@@ -287,4 +288,5 @@ export const QuickListTypeMap = {[QuickListType.ORDER_LIST_QUICK_5]: PresetListType.ORDER_LIST_3,[QuickListType.ORDER_LIST_QUICK_6]: PresetListType.ORDER_LIST_QUICK_6,[QuickListType.ORDER_LIST_QUICK_7]: PresetListType.ORDER_LIST_5,+ [QuickListType.BULLET_LIST]: PresetListType.BULLET_LIST,};diff --git a/packages/core/src/docs/data-model/text-x/build-utils/index.ts b/packages/core/src/docs/data-model/text-x/build-utils/index.tsindex b09c25a6e8..53022ece0a 100644--- a/packages/core/src/docs/data-model/text-x/build-utils/index.ts+++ b/packages/core/src/docs/data-model/text-x/build-utils/index.ts@@ -19,7 +19,7 @@ import { copyCustomRange, getCustomRangesInterestsWithSelection, isIntersectingimport { addDrawing } from './drawings';import { changeParagraphBulletNestLevel, setParagraphBullet, setParagraphStyle, switchParagraphBullet, toggleChecklistParagraph } from './paragraph';import { fromPlainText, getPlainText, isEmptyDocument } from './parse';-import { getParagraphsInRange, getParagraphsInRanges, isSegmentIntersects, makeSelection, normalizeSelection } from './selection';+import { getParagraphsInRange, getParagraphsInRanges, isSegmentIntersects, makeSelection, normalizeSelection, transformParagraphs } from './selection';import { addCustomRangeTextX, deleteCustomRangeTextX, deleteSelectionTextX, replaceSelectionTextRuns, replaceSelectionTextX, retainSelectionTextX } from './text-x-utils';export class BuildTextUtils {@@ -67,6 +67,11 @@ export class BuildTextUtils {style: {set: setParagraphStyle,},+ util: {+ transform: transformParagraphs,+ getParagraphsInRange,+ getParagraphsInRanges,+ },};static drawing = {diff --git a/packages/core/src/docs/data-model/text-x/build-utils/paragraph.ts b/packages/core/src/docs/data-model/text-x/build-utils/paragraph.tsindex 056a3fc27b..59e4e6de00 100644--- a/packages/core/src/docs/data-model/text-x/build-utils/paragraph.ts+++ b/packages/core/src/docs/data-model/text-x/build-utils/paragraph.ts@@ -314,18 +314,33 @@ interface ISetParagraphStyleParams {document: DocumentDataModel;style: IParagraphStyle;paragraphTextRun?: ITextStyle;+ cursor?: number;+ deleteLen?: number;+ textX?: TextX;}export const setParagraphStyle = (params: ISetParagraphStyleParams) => {- const { textRanges, segmentId, document: docDataModel, style, paragraphTextRun } = params;+ const {+ textRanges,+ segmentId,+ document: docDataModel,+ style,+ paragraphTextRun,+ cursor,+ deleteLen,+ textX: _textX,+ } = params;const paragraphs = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody()?.paragraphs ?? [];const currentParagraphs = getParagraphsInRanges(textRanges, paragraphs);const memoryCursor = new MemoryCursor();- const textX = new TextX();+ if (cursor) {+ memoryCursor.moveCursorTo(cursor);+ }+ const textX = _textX ?? new TextX();currentParagraphs.sort((a, b) => a.startIndex - b.startIndex);const start = Math.max(0, currentParagraphs[0].paragraphStart - 1);- if (start > 0) {+ if (start > memoryCursor.cursor) {textX.push({t: TextXActionType.RETAIN,len: start - memoryCursor.cursor,@@ -333,6 +348,13 @@ export const setParagraphStyle = (params: ISetParagraphStyleParams) => {memoryCursor.moveCursorTo(start);}+ if (deleteLen) {+ textX.push({+ t: TextXActionType.DELETE,+ len: deleteLen,+ });+ }+for (const paragraph of currentParagraphs) {const { startIndex, paragraphStyle = {} } = paragraph;const len = startIndex - memoryCursor.cursor;diff --git a/packages/core/src/docs/data-model/text-x/build-utils/selection.ts b/packages/core/src/docs/data-model/text-x/build-utils/selection.tsindex 3341e1c6ce..b3608862ec 100644--- a/packages/core/src/docs/data-model/text-x/build-utils/selection.ts+++ b/packages/core/src/docs/data-model/text-x/build-utils/selection.ts@@ -88,3 +88,25 @@ export function getParagraphsInRanges(ranges: readonly ITextRange[], paragraphs:return results;}++export function transformParagraphs(paragraphs: IParagraph[]) {+ const results: IParagraphRange[] = [];++ let start = -1;++ for (let i = 0; i < paragraphs.length; i++) {+ const paragraph = paragraphs[i];+ const prevParagraph: Nullable<IParagraph> = paragraphs[i - 1];+ const { startIndex } = paragraph;++ results.push({+ ...paragraph,+ paragraphStart: (prevParagraph?.startIndex ?? -1) + 1,+ paragraphEnd: paragraph.startIndex,+ });++ start = startIndex;+ }++ return results;+}diff --git a/packages/design/src/components/side-menu/index.tsx b/packages/design/src/components/side-menu/index.tsxnew file mode 100644index 0000000000..61b5181f0a--- /dev/null+++ b/packages/design/src/components/side-menu/index.tsx@@ -0,0 +1,155 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef } from 'react';+import { clsx } from '../../helper/clsx';++export interface ISideMenuItem {+ text: string;+ level: number;+ id: string;+ isTitle?: boolean;+}++export interface ISideMenuProps {+ menus?: ISideMenuItem[];+ onClick?: (menu: ISideMenuItem) => void;+ className?: string;+ style?: React.CSSProperties;+ mode?: 'float' | 'side-bar';+ maxHeight?: string;+ activeId?: string;+ open?: boolean;+ onOpenChange?: (open: boolean) => void;+ maxWidth?: number;+ wrapperClass?: string;+ wrapperStyle?: React.CSSProperties;+ iconClass?: string;+ iconStyle?: React.CSSProperties;+}++export interface ISideMenuInstance {+ scrollTo: (id: string) => void;+}++const commonClass = 'univer-overflow-hidden univer-truncate univer-h-[24px] univer-mb-2 univer-leading-[24px] univer-ellipsis univer-cursor-pointer';+const titleClass = 'univer-text-base univer-font-semibold';+const h1Class = 'univer-text-sm univer-font-semibold';+const textClass = 'univer-text-sm';+const activeClass = 'univer-text-[#466AF7]';++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 containerRef = useRef<HTMLDivElement>(null);+ const instance: ISideMenuInstance = useMemo(() => ({+ scrollTo: (id: string) => {+ document.getElementById(`univer-side-menu-${id}`)?.scrollIntoView({ behavior: 'smooth' });+ },+ }), []);++ useImperativeHandle(ref, () => instance);++ useEffect(() => {+ if (activeId) {+ instance.scrollTo(activeId);+ }+ }, [activeId, instance]);++ return (+ <div className={clsx('univer-relative', wrapperClass)} style={wrapperStyle}>+ <div+ onClick={() => onOpenChange?.(!open)}+ className={clsx(`+ univer-absolute univer-left-5 univer-top-4 univer-z-[100] univer-flex univer-h-8 univer-w-8+ univer-cursor-pointer univer-items-center univer-justify-center univer-rounded-full univer-bg-white+ univer-shadow-[0px_1px_3px_-1px_rgba(30,40,77,0.10),0px_1px_4px_0px_rgba(30,40,77,0.12)]+ `, iconClass)}+ style={iconStyle}+ >+ {open ? 'x' : 'o'}+ </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-pb-4 univer-pl-5 univer-pr-5 univer-pt-14 univer-transition-all+ univer-duration-300+ `,+ isSideBar+ ? ''+ : [+ 'univer-bg-white',+ 'univer-rounded-r-2xl',+ 'univer-shadow-[0px_1px_6px_-2px_rgba(30,40,77,0.08),0px_2px_6px_-1px_rgba(30,40,77,0.10)]',+ 'univer-backdrop-blur-[10px]',+ ]+ )}+ style={{+ ...style,+ transform: open ? 'translateX(0)' : 'translateX(-100%)',+ maxHeight,+ opacity: open ? 1 : 0,+ maxWidth: maxWidth ?? (mode === 'side-bar' ? 480 : 180),+ paddingRight: mode === 'float' ? undefined : 0,+ }}+ >+ <div+ className={`+ univer-text-xs univer-font-semibold univer-leading-[150%] univer-text-gray-400 univer-font-inter+ univer-mb-2+ `}+ >+ contents+ </div>+ <div+ ref={containerRef}+ className={`+ univer-flex-1 univer-overflow-y-auto univer-overflow-x-hidden univer-scrollbar+ univer-scrollbar-thin univer-scrollbar-track-transparent univer-scrollbar-thumb-[#73737366]+ univer-scrollbar-gutter-stable+ `}+ >+ {menus?.map((menu) => (+ <div+ id={`univer-side-menu-${menu.id}`}+ key={menu.id}+ className={clsx(+ commonClass,+ {+ [titleClass]: menu.isTitle,+ [h1Class]: menu.level === 1,+ [textClass]: menu.level > 1,+ [activeClass]: menu.id === activeId,+ 'univer-text-gray-500': menu.id !== activeId,+ }+ )}+ style={{+ paddingLeft: (menu.level - 1) * 12,+ }}+ onClick={() => {+ onClick?.(menu);+ }}+ >+ {menu.text}+ </div>+ ))}+ </div>+ </div>+ </div>+ );+});diff --git a/packages/design/src/components/side-menu/side-menu.stories.tsx b/packages/design/src/components/side-menu/side-menu.stories.tsxnew file mode 100644index 0000000000..fb3bc3db9c--- /dev/null+++ b/packages/design/src/components/side-menu/side-menu.stories.tsx@@ -0,0 +1,103 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { Meta } from '@storybook/react';+import type { ISideMenuItem } from './index';++import React, { useState } from 'react';+import { SideMenu } from './index';++const meta: Meta<typeof SideMenu> = {+ title: 'Components / SideMenu',+ component: SideMenu,+ parameters: {+ layout: 'centered',+ },+ tags: ['autodocs'],+};++export default meta;++export const SideMenuBasic = {+ render() {+ const [open, setOpen] = useState(false);+ const menus: ISideMenuItem[] = [+ { text: 'Section 1', level: 1, id: 'section1' },+ { text: 'Item 1.1', level: 2, id: 'item1.1' },+ { text: 'Item 1.2', level: 2, id: 'item1.2' },+ { text: 'Section 2', level: 1, id: 'section2' },+ { text: 'Item 2.1', level: 2, id: 'item2.1' },+ { text: 'Item 2.2', level: 2, id: 'item2.2' },+ ];++ const handleClick = (_menu: ISideMenuItem) => {+ };++ return (+ <SideMenu+ maxHeight="150px"+ menus={menus}+ onClick={handleClick}+ open={open}+ onOpenChange={setOpen}+ mode="side-bar"+ />+ );+ },+};++export const EmptySideMenu = {+ render() {+ return <SideMenu />;+ },+};++export const CustomStyledSideMenu = {+ render() {+ const menus: ISideMenuItem[] = [+ { text: 'Section 1', level: 1, id: 'section1' },+ { text: 'Item 1.1', level: 2, id: 'item1.1' },+ { text: 'Item 1.2', level: 2, id: 'item1.2' },+ ];++ const customStyle = {+ backgroundColor: '#f5f5f5',+ padding: '10px',+ borderRadius: '4px',+ };++ return <SideMenu menus={menus} className="custom-side-menu" style={customStyle} />;+ },+};++export const MultiLevelSideMenu = {+ render() {+ const menus: ISideMenuItem[] = [+ { text: 'Section 1', level: 1, id: 'section1' },+ { text: 'Item 1.1', level: 2, id: 'item1.1' },+ { text: 'Subitem 1.1.1', level: 3, id: 'subitem1.1.1' },+ { text: 'Subitem 1.1.2', level: 3, id: 'subitem1.1.2' },+ { text: 'Item 1.2', level: 2, id: 'item1.2' },+ { text: 'Section 2', level: 1, id: 'section2' },+ { text: 'Item 2.1', level: 2, id: 'item2.1' },+ ];++ const handleClick = (_menu: ISideMenuItem) => {+ };++ return <SideMenu menus={menus} onClick={handleClick} />;+ },+};diff --git a/packages/design/src/index.ts b/packages/design/src/index.tsindex be9ab21c49..f611096a09 100644--- a/packages/design/src/index.ts+++ b/packages/design/src/index.ts@@ -54,3 +54,4 @@ export { isBrowser } from './helper/is-browser';export { DropdownMenu, type IDropdownProps } from './components/dropdown-menu';export { Separator } from './components/separator';export { DateRangePicker } from './components/date-range-picker';+export * from './components/side-menu';diff --git a/packages/docs-ui/src/basics/interfaces/component-config/i-doc-ui-plugin-config.ts b/packages/docs-ui/src/basics/interfaces/component-config/i-doc-ui-plugin-config.tsindex 1470c9ee60..40842cf993 100644--- a/packages/docs-ui/src/basics/interfaces/component-config/i-doc-ui-plugin-config.ts+++ b/packages/docs-ui/src/basics/interfaces/component-config/i-doc-ui-plugin-config.ts@@ -28,6 +28,8 @@ export interface DocContainerConfig {footer?: boolean;+ sideMenu?: boolean;+innerLeft?: boolean;innerRight?: boolean;diff --git a/packages/docs-ui/src/commands/commands/break-line.command.ts b/packages/docs-ui/src/commands/commands/break-line.command.tsindex 527868d22e..c96deb723f 100644--- a/packages/docs-ui/src/commands/commands/break-line.command.ts+++ b/packages/docs-ui/src/commands/commands/break-line.command.ts@@ -14,13 +14,13 @@* limitations under the License.*/-import type { DocumentDataModel, ICommand, IDocumentBody, IParagraph, IParagraphBorder } from '@univerjs/core';-import { CommandType, DataStreamTreeTokenType, ICommandService, IUniverInstanceService, PresetListType, Tools, UniverInstanceType } from '@univerjs/core';-import { DocSelectionManagerService } from '@univerjs/docs';+import type { DocumentDataModel, ICommand, IDocumentBody, IMutationInfo, IParagraph, IParagraphBorder } from '@univerjs/core';+import type { IRichTextEditingMutationParams } from '@univerjs/docs';+import { BuildTextUtils, CommandType, DataStreamTreeTokenType, ICommandService, IUniverInstanceService, JSONX, PresetListType, TextX, TextXActionType, Tools, UniverInstanceType, UpdateDocsAttributeType } from '@univerjs/core';+import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';import { getTextRunAtPosition } from '../../basics/paragraph';import { DocMenuStyleService } from '../../services/doc-menu-style.service';-import { InsertCommand } from './core-editing.command';-import { ToggleCheckListCommand } from './list.command';+import { getRichTextEditPath } from '../util';export function generateParagraphs(dataStream: string,@@ -102,9 +102,9 @@ export const BreakLineCommand: ICommand<IBreakLineCommandParams> = {const { horizontalLine } = params ?? {};const { segmentId } = activeTextRange;const docDataModel = univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);- const body = docDataModel?.getSelfOrHeaderFooterModel(segmentId ?? '').getBody();+ const originBody = docDataModel?.getSelfOrHeaderFooterModel(segmentId ?? '').getBody();- if (docDataModel == null || body == null) {+ if (docDataModel == null || originBody == null) {return false;}@@ -112,7 +112,7 @@ export const BreakLineCommand: ICommand<IBreakLineCommandParams> = {const { startOffset, endOffset } = activeTextRange;- const paragraphs = body.paragraphs ?? [];+ const paragraphs = originBody.paragraphs ?? [];const prevParagraph = paragraphs.find((p) => p.startIndex >= startOffset);if (!prevParagraph) {@@ -120,10 +120,9 @@ export const BreakLineCommand: ICommand<IBreakLineCommandParams> = {}const prevParagraphIndex = prevParagraph.startIndex;-const defaultTextStyle = docMenuStyleService.getDefaultStyle();const styleCache = docMenuStyleService.getStyleCache();- const curTextRun = getTextRunAtPosition(body, endOffset, defaultTextStyle, styleCache);+ const curTextRun = getTextRunAtPosition(originBody, endOffset, defaultTextStyle, styleCache);const insertBody: IDocumentBody = {dataStream: DataStreamTreeTokenType.PARAGRAPH,@@ -141,33 +140,106 @@ export const BreakLineCommand: ICommand<IBreakLineCommandParams> = {}],};- const deleteRange = {- startOffset,- endOffset,- collapsed: startOffset === endOffset,+ if (docDataModel == null) {+ return false;+ }++ const activeRange = docSelectionManagerService.getActiveTextRange();++ if (originBody == null) {+ return false;+ }+ const { collapsed } = activeTextRange;+ const cursorMove = insertBody.dataStream.length;+ const textRanges = [+ {+ startOffset: startOffset + cursorMove,+ endOffset: startOffset + cursorMove,+ style: activeRange?.style,+ collapsed,+ },+ ];++ const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {+ id: RichTextEditingMutation.id,+ params: {+ unitId,+ actions: [],+ textRanges,+ debounce: true,+ },};- const result = await commandService.executeCommand(InsertCommand.id, {- unitId,- body: insertBody,- range: deleteRange,- segmentId,- });+ const textX = new TextX();+ const jsonX = JSONX.getInstance();++ if (collapsed) {+ if (startOffset > 0) {+ textX.push({+ t: TextXActionType.RETAIN,+ len: startOffset,+ });+ }- if (prevParagraph.bullet?.listType === PresetListType.CHECK_LIST_CHECKED) {- const params = {- index: prevParagraphIndex + 1 - (endOffset - startOffset),- segmentId,- textRanges: [{- startOffset: startOffset + 1,- endOffset: startOffset + 1,- }],- };- const toggleCheckListResult = await commandService.executeCommand(ToggleCheckListCommand.id, params);-- return Boolean(toggleCheckListResult) && result;+ textX.push({+ t: TextXActionType.INSERT,+ body: insertBody,+ len: insertBody.dataStream.length,+ });+ } else {+ const dos = BuildTextUtils.selection.delete([activeTextRange], originBody, 0, insertBody);+ textX.push(...dos);}- return result;+ if (prevParagraph.bullet?.listType === PresetListType.CHECK_LIST_CHECKED || prevParagraph.paragraphStyle?.headingId) {+ if (activeTextRange.endOffset < prevParagraphIndex) {+ textX.push({+ t: TextXActionType.RETAIN,+ len: prevParagraphIndex - activeTextRange.endOffset,+ });+ }++ textX.push({+ t: TextXActionType.RETAIN,+ len: 1,+ body: {+ dataStream: '',+ paragraphs: [+ {+ ...prevParagraph,+ paragraphStyle: {+ ...prevParagraph.paragraphStyle,+ headingId: undefined,+ namedStyleType: undefined,+ },+ startIndex: 0,+ bullet: prevParagraph.paragraphStyle?.headingId+ ? undefined+ : {+ ...prevParagraph.bullet!,+ listType: PresetListType.CHECK_LIST,+ },+ },+ ],+ },+ coverType: UpdateDocsAttributeType.REPLACE,+ });+ }++ doMutation.params.textRanges = [{+ startOffset: startOffset + cursorMove,+ endOffset: startOffset + cursorMove,+ collapsed,+ }];++ const path = getRichTextEditPath(docDataModel, segmentId);+ doMutation.params.actions = jsonX.editOp(textX.serialize(), path);++ const result = commandService.syncExecuteCommand<+ IRichTextEditingMutationParams,+ IRichTextEditingMutationParams+ >(doMutation.id, doMutation.params);++ return Boolean(result);},};diff --git a/packages/docs-ui/src/commands/commands/list.command.ts b/packages/docs-ui/src/commands/commands/list.command.tsindex c10393d7bb..a1b0b2726d 100644--- a/packages/docs-ui/src/commands/commands/list.command.ts+++ b/packages/docs-ui/src/commands/commands/list.command.ts@@ -377,7 +377,7 @@ export const QuickListCommand: ICommand<IQuickListCommandParams> = {return false;}- const { segmentId } = activeRange;+ const { segmentId, startOffset } = activeRange;const { listType, paragraph } = params;const { paragraphStart, paragraphEnd } = paragraph;// const selection =@@ -428,9 +428,16 @@ export const QuickListCommand: ICommand<IQuickListCommandParams> = {textX.push({t: TextXActionType.DELETE,- len: paragraphEnd - paragraphStart,+ len: startOffset - paragraphStart,});+ if (paragraphEnd > startOffset) {+ textX.push({+ t: TextXActionType.RETAIN,+ len: paragraphEnd - startOffset,+ });+ }+textX.push({t: TextXActionType.RETAIN,len: 1,diff --git a/packages/docs-ui/src/commands/commands/set-heading.command.ts b/packages/docs-ui/src/commands/commands/set-heading.command.tsindex 1b0629d2d1..2befaf57de 100644--- a/packages/docs-ui/src/commands/commands/set-heading.command.ts+++ b/packages/docs-ui/src/commands/commands/set-heading.command.ts@@ -16,7 +16,7 @@import type { DocumentDataModel, ICommand, IMutationInfo } from '@univerjs/core';import type { IRichTextEditingMutationParams } from '@univerjs/docs';-import { BuildTextUtils, CommandType, generateRandomId, ICommandService, IUniverInstanceService, JSONX, NamedStyleType, UniverInstanceType } from '@univerjs/core';+import { BuildTextUtils, CommandType, generateRandomId, ICommandService, IUniverInstanceService, JSONX, NamedStyleType, TextX, TextXActionType, UniverInstanceType } from '@univerjs/core';import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';import { getRichTextEditPath } from '../util';@@ -72,3 +72,80 @@ export const SetParagraphNamedStyleCommand: ICommand<ISetParagraphNamedStyleCommreturn Boolean(result);},};++export const QuickHeadingCommand: ICommand<ISetParagraphNamedStyleCommandParams> = {+ id: 'doc.command.quick-heading',+ type: CommandType.COMMAND,++ handler(accessor, params) {+ if (!params) {+ return false;+ }+ const { value } = params;+ const docSelectionManagerService = accessor.get(DocSelectionManagerService);+ const univerInstanceService = accessor.get(IUniverInstanceService);+ const commandService = accessor.get(ICommandService);+ const docDataModel = univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);+ const activeRange = docSelectionManagerService.getActiveTextRange();+ if (docDataModel == null || activeRange == null || !activeRange.collapsed) {+ return false;+ }++ const { segmentId, startOffset } = activeRange;+ const paragraph = BuildTextUtils.paragraph.util.getParagraphsInRange(activeRange, docDataModel.getBody()?.paragraphs ?? [])[0];+ if (!paragraph) {+ return false;+ }+ const { paragraphStart } = paragraph;+ // const selection =+ const textX = new TextX();+ const jsonX = JSONX.getInstance();+ const { paragraphStyle = {} } = paragraph;++ const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {+ id: RichTextEditingMutation.id,+ params: {+ unitId: docDataModel.getUnitId(),+ actions: [],+ textRanges: [{+ startOffset: paragraphStart,+ endOffset: paragraphStart,+ collapsed: true,+ }],+ isEditing: false,+ },+ };+ textX.push({+ t: TextXActionType.RETAIN,+ len: paragraphStart,+ });++ BuildTextUtils.paragraph.style.set({+ textRanges: [activeRange],+ document: docDataModel,+ style: {+ ...paragraphStyle,+ headingId: generateRandomId(6),+ namedStyleType: value,+ },+ cursor: startOffset,+ deleteLen: startOffset - paragraphStart,+ textX,+ paragraphTextRun: {},+ });+ const path = getRichTextEditPath(docDataModel, segmentId);+ doMutation.params.actions = jsonX.editOp(textX.serialize(), path);++ const result = commandService.syncExecuteCommand(doMutation.id, doMutation.params);+ return Boolean(result);+ },+};++export const QUICK_HEADING_MAP = {+ '#': NamedStyleType.HEADING_1,+ '##': NamedStyleType.HEADING_2,+ '###': NamedStyleType.HEADING_3,+ '####': NamedStyleType.HEADING_4,+ '#####': NamedStyleType.HEADING_5,+ '######': NamedStyleType.HEADING_6,+};diff --git a/packages/docs-ui/src/controllers/doc-auto-format.controller.ts b/packages/docs-ui/src/controllers/doc-auto-format.controller.tsindex 128cca89e9..16334248b9 100644--- a/packages/docs-ui/src/controllers/doc-auto-format.controller.ts+++ b/packages/docs-ui/src/controllers/doc-auto-format.controller.ts@@ -22,6 +22,7 @@ import { IRenderManagerService } from '@univerjs/engine-render';import { AfterSpaceCommand, EnterCommand, TabCommand } from '../commands/commands/auto-format.command';import { BreakLineCommand } from '../commands/commands/break-line.command';import { ChangeListNestingLevelCommand, ChangeListNestingLevelType, ListOperationCommand, QuickListCommand } from '../commands/commands/list.command';+import { QUICK_HEADING_MAP, QuickHeadingCommand } from '../commands/commands/set-heading.command';import { DocTableTabCommand } from '../commands/commands/table/doc-table-tab.command';import { DocAutoFormatService } from '../services/doc-auto-format.service';import { isInSameTableCellData } from '../services/selection/convert-rect-range';@@ -34,7 +35,7 @@ export class DocAutoFormatController extends Disposable {super();this._initListTabAutoFormat();- this._initListSpaceAutoFormat();+ this._initSpaceAutoFormat();this._initDefaultEnterFormat();this._initExitListAutoFormat();}@@ -115,7 +116,7 @@ export class DocAutoFormatController extends Disposable {);}- private _initListSpaceAutoFormat() {+ private _initSpaceAutoFormat() {this.disposeWithMe(this._docAutoFormatService.registerAutoFormat({id: AfterSpaceCommand.id,@@ -127,15 +128,18 @@ export class DocAutoFormatController extends Disposable {if (paragraphs.length !== 1) {return false;}- const text = unit.getBody()?.dataStream.slice(paragraphs[0].paragraphStart, paragraphs[0].paragraphEnd - 1);- if (text && Object.keys(QuickListTypeMap).includes(text)) {+ if (!selection.collapsed) {+ return false;+ }+ const text = unit.getBody()?.dataStream.slice(paragraphs[0].paragraphStart, selection.startOffset - 1);+ if (text && (Object.keys(QuickListTypeMap).includes(text) || Object.keys(QUICK_HEADING_MAP).includes(text))) {return true;}return false;},getMutations(context) {- const { paragraphs, unit } = context;- const text = unit.getBody()?.dataStream.slice(paragraphs[0].paragraphStart, paragraphs[0].paragraphEnd - 1);+ const { paragraphs, unit, selection } = context;+ const text = unit.getBody()?.dataStream.slice(paragraphs[0].paragraphStart, selection.startOffset - 1);if (text && Object.keys(QuickListTypeMap).includes(text)) {const type = QuickListTypeMap[text as keyof typeof QuickListTypeMap];return [{@@ -146,6 +150,16 @@ export class DocAutoFormatController extends Disposable {},}];}++ if (text && Object.keys(QUICK_HEADING_MAP).includes(text)) {+ const type = QUICK_HEADING_MAP[text as keyof typeof QUICK_HEADING_MAP];+ return [{+ id: QuickHeadingCommand.id,+ params: {+ value: type,+ },+ }];+ }return [];},})diff --git a/packages/docs-ui/src/controllers/doc-ui.controller.ts b/packages/docs-ui/src/controllers/doc-ui.controller.tsindex a491fd6b93..f1c9da5c4e 100644--- a/packages/docs-ui/src/controllers/doc-ui.controller.ts+++ b/packages/docs-ui/src/controllers/doc-ui.controller.ts@@ -56,6 +56,7 @@ import {UnderlineShortCut,} from '../shortcuts/toolbar.shortcut';import { DocFooter } from '../views/doc-footer';+import { DocSideMenu } from '../views/side-menu';import { DOCS_UI_PLUGIN_CONFIG_KEY } from './config.schema';import { menuSchema } from './menu.schema';@@ -93,6 +94,10 @@ export class DocUIController extends Disposable {if (config?.layout?.docContainerConfig?.footer) {this.disposeWithMe(this._uiPartsService.registerComponent(BuiltInUIPart.FOOTER, () => connectInjector(DocFooter, this._injector)));}++ if (config?.layout?.docContainerConfig?.sideMenu ?? true) {+ this.disposeWithMe(this._uiPartsService.registerComponent(BuiltInUIPart.CONTENT, () => connectInjector(DocSideMenu, this._injector)));+ }}private _initMenus(): void {diff --git a/packages/docs-ui/src/docs-ui-plugin.ts b/packages/docs-ui/src/docs-ui-plugin.tsindex 95a8c5634f..ed4b47cabb 100644--- a/packages/docs-ui/src/docs-ui-plugin.ts+++ b/packages/docs-ui/src/docs-ui-plugin.ts@@ -73,7 +73,7 @@ import {import { AlignCenterCommand, AlignJustifyCommand, AlignLeftCommand, AlignOperationCommand, AlignRightCommand } from './commands/commands/paragraph-align.command';import { CoverContentCommand, ReplaceContentCommand, ReplaceSelectionCommand, ReplaceSnapshotCommand, ReplaceTextRunsCommand } from './commands/commands/replace-content.command';import { SetDocZoomRatioCommand } from './commands/commands/set-doc-zoom-ratio.command';-import { SetParagraphNamedStyleCommand } from './commands/commands/set-heading.command';+import { QuickHeadingCommand, SetParagraphNamedStyleCommand } from './commands/commands/set-heading.command';import { SwitchDocModeCommand } from './commands/commands/switch-doc-mode.command';import { CreateDocTableCommand } from './commands/commands/table/doc-table-create.command';import { DocTableDeleteColumnsCommand, DocTableDeleteRowsCommand, DocTableDeleteTableCommand } from './commands/commands/table/doc-table-delete.command';@@ -264,6 +264,7 @@ export class UniverDocsUIPlugin extends Plugin {ReplaceSelectionCommand,InsertCustomRangeCommand,SetParagraphNamedStyleCommand,+ QuickHeadingCommand,].forEach((e) => {this.disposeWithMe(this._commandService.registerCommand(e));});diff --git a/packages/docs-ui/src/services/doc-event-manager.service.ts b/packages/docs-ui/src/services/doc-event-manager.service.tsindex 2cc5135882..0326a9006c 100644--- a/packages/docs-ui/src/services/doc-event-manager.service.ts+++ b/packages/docs-ui/src/services/doc-event-manager.service.ts@@ -14,9 +14,9 @@* limitations under the License.*/-import type { DocumentDataModel, ICustomRange, IParagraph, ITextRangeParam, Nullable } from '@univerjs/core';+import type { DocumentDataModel, ICustomRange, IParagraph, IParagraphRange, ITextRangeParam, Nullable } from '@univerjs/core';import type { Documents, DocumentSkeleton, IBoundRectNoAngle, IDocumentSkeletonGlyph, IDocumentSkeletonPage, IMouseEvent, IPointerEvent, IRenderContext, IRenderModule } from '@univerjs/engine-render';-import { Disposable, fromEventSubject, Inject } from '@univerjs/core';+import { BuildTextUtils, Disposable, fromEventSubject, Inject } from '@univerjs/core';import { DocSkeletonManagerService } from '@univerjs/docs';import { CURSOR_TYPE, TRANSFORM_CHANGE_OBSERVABLE_TYPE } from '@univerjs/engine-render';import { BehaviorSubject, distinctUntilChanged, filter, map, Subject, switchMap, take, throttleTime } from 'rxjs';@@ -25,24 +25,29 @@ import { transformOffset2Bound } from './doc-popup-manager.service';import { NodePositionConvertToCursor } from './selection/convert-text-range';import { getLineBounding } from './selection/text-range';-interface ICustomRangeBound {+export interface ICustomRangeBound {customRange: ICustomRange;rects: IBoundRectNoAngle[];segmentId?: string;segmentPageIndex: number;}-interface IBulletBound {+export interface IBulletBound {rect: IBoundRectNoAngle;segmentId?: string;segmentPageIndex: number;paragraph: IParagraph;}+export interface IParagraphBound {+ rect: IBoundRectNoAngle;+ paragraph: IParagraphRange;+}+const calcDocRangePositions = (range: ITextRangeParam, documents: Documents, skeleton: DocumentSkeleton, pageIndex: number): IBoundRectNoAngle[] | undefined => {const startPosition = skeleton.findNodePositionByCharIndex(range.startOffset, true, range.segmentId, pageIndex);const skeletonData = skeleton.getSkeletonData();- let end = range.endOffset;+ let end = range.collapsed ? range.startOffset : range.endOffset - 1;if (range.segmentId) {const root = Array.from(skeletonData?.skeFooters.get(range.segmentId)?.values() ?? [])[0] ?? Array.from(skeletonData?.skeHeaders.get(range.segmentId)?.values() ?? [])[0];if (root) {@@ -67,6 +72,50 @@ const calcDocRangePositions = (range: ITextRangeParam, documents: Documents, ske}));};+const calcDocParagraphPositions = (startIndex: number, endIndex: number, documents: Documents, skeleton: DocumentSkeleton): Nullable<IBoundRectNoAngle> => {+ const startPosition = skeleton.findNodePositionByCharIndex(startIndex, true, undefined, -1);+ const endPosition = skeleton.findNodePositionByCharIndex(endIndex, true, undefined, -1);+ if (!endPosition || !startPosition) {+ return null;+ }++ const documentOffsetConfig = documents.getOffsetConfig();+ const convertor = new NodePositionConvertToCursor(documentOffsetConfig, skeleton);+ const { borderBoxPointGroup } = convertor.getRangePointData(startPosition, endPosition);+ const bounds = getLineBounding(borderBoxPointGroup);+ if (!bounds.length) {+ return null;+ }+ const rects = bounds.map((rect) => ({+ top: rect.top + documentOffsetConfig.docsTop - DOC_VERTICAL_PADDING,+ bottom: rect.bottom + documentOffsetConfig.docsTop + DOC_VERTICAL_PADDING,+ left: rect.left + documentOffsetConfig.docsLeft,+ right: rect.right + documentOffsetConfig.docsLeft,+ }));++ let left;+ let right;+ let top;+ let bottom;++ for (const rect of rects) {+ if (left === undefined || rect.left < left) {+ left = rect.left;+ }+ if (right === undefined || rect.right > right) {+ right = rect.right;+ }+ if (top === undefined || rect.top < top) {+ top = rect.top;+ }+ if (bottom === undefined || rect.bottom > bottom) {+ bottom = rect.bottom;+ }+ }++ return { left: left!, right: right!, top: top!, bottom: bottom! };+};+export const calcDocGlyphPosition = (glyph: IDocumentSkeletonGlyph, documents: Documents, skeleton: DocumentSkeleton, pageIndex = -1): IBoundRectNoAngle | undefined => {const start = skeleton.findPositionByGlyph(glyph, pageIndex);if (!start) {@@ -117,6 +166,7 @@ export class DocEventManagerService extends Disposable implements IRenderModuleprivate _customRangeDirty = true;private _bulletDirty = true;+ private _paragraphDirty = true;/*** cache the bounding of custom ranges,@@ -128,6 +178,11 @@ export class DocEventManagerService extends Disposable implements IRenderModule* it will be updated when the doc-skeleton is recalculated*/private _bulletBounds: IBulletBound[] = [];+ /**+ * cache the bounding of paragraphs,+ * it will be updated when the doc-skeleton is recalculated+ */+ private _paragraphBounds: IParagraphBound[] = [];private get _skeleton() {return this._docSkeletonManagerService.getSkeleton();@@ -170,6 +225,7 @@ export class DocEventManagerService extends Disposable implements IRenderModulethis.disposeWithMe(this._skeleton.dirty$.subscribe(() => {this._customRangeDirty = true;this._bulletDirty = true;+ this._paragraphDirty = true;}));this.disposeWithMe(@@ -178,6 +234,7 @@ export class DocEventManagerService extends Disposable implements IRenderModule).subscribe(() => {this._customRangeDirty = true;this._bulletDirty = true;+ this._paragraphDirty = true;}));}@@ -221,7 +278,6 @@ export class DocEventManagerService extends Disposable implements IRenderModuleprivate _buildCustomRangeBoundsBySegment(segmentId?: string, segmentPage = -1) {const customRanges = this._context.unit.getSelfOrHeaderFooterModel(segmentId)?.getBody()?.customRanges ?? [];const layouts: ICustomRangeBound[] = [];-customRanges.forEach((range) => {const textRange: ITextRangeParam = {startOffset: range.startIndex,@@ -387,4 +443,41 @@ export class DocEventManagerService extends Disposable implements IRenderModule});return bullet;}++ private _buildParagraphBoundsBySegment(segmentId?: string, pageIndex = -1) {+ const paragraphs = BuildTextUtils.paragraph.util.transform(this._context.unit.getBody()?.paragraphs ?? []);+ return paragraphs.map((paragraph) => {+ return {+ paragraph,+ segmentId,+ pageIndex,+ rect: calcDocParagraphPositions(paragraph.paragraphStart, paragraph.paragraphEnd, this._documents, this._skeleton),+ } as IParagraphBound;+ });+ }++ private _buildParagraphBounds() {+ if (!this._paragraphDirty) {+ return;+ }+ this._paragraphDirty = false;++ this._paragraphBounds = [];+ this._paragraphBounds.push(...this._buildParagraphBoundsBySegment());++ this._skeleton.getSkeletonData()?.pages.forEach((page, pageIndex) => {+ if (page.headerId) {+ this._paragraphBounds.push(...this._buildParagraphBoundsBySegment(page.headerId, pageIndex));+ }++ if (page.footerId) {+ this._paragraphBounds.push(...this._buildParagraphBoundsBySegment(page.footerId, pageIndex));+ }+ });+ }++ get paragraphBounds() {+ this._buildParagraphBounds();+ return this._paragraphBounds;+ }}diff --git a/packages/docs-ui/src/views/side-menu/index.tsx b/packages/docs-ui/src/views/side-menu/index.tsxnew file mode 100644index 0000000000..51b0d2abe2--- /dev/null+++ b/packages/docs-ui/src/views/side-menu/index.tsx@@ -0,0 +1,158 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { DocumentDataModel } from '@univerjs/core';+import type { ISideMenuItem } from '@univerjs/design';+import type { IRichTextEditingMutationParams } from '@univerjs/docs';+import type { IParagraphBound } from '../../services/doc-event-manager.service';+import { debounce, fromEventSubject, getPlainText, ICommandService, isInternalEditorID, IUniverInstanceService, NamedStyleType, UniverInstanceType } from '@univerjs/core';+import { SideMenu } from '@univerjs/design';+import { RichTextEditingMutation } from '@univerjs/docs';+import { IRenderManagerService } from '@univerjs/engine-render';+import { useDependency, useObservable } from '@univerjs/ui';+import { useEffect, useMemo, useState } from 'react';+import { of, throttleTime } from 'rxjs';+import { VIEWPORT_KEY } from '../../basics/docs-view-key';+import { DocEventManagerService } from '../../services/doc-event-manager.service';++const transformNamedStyleTypeToLevel = (type: NamedStyleType) => {+ switch (type) {+ case NamedStyleType.HEADING_1:+ return 1;+ case NamedStyleType.HEADING_2:+ return 2;+ case NamedStyleType.HEADING_3:+ return 3;+ case NamedStyleType.HEADING_4:+ return 4;+ case NamedStyleType.HEADING_5:+ return 5;+ case NamedStyleType.HEADING_6:+ return 6;+ case NamedStyleType.TITLE:+ return 1;+ default:+ return 1;+ }+};++function findActiveHeading(paragraphBounds: IParagraphBound[], scrollTop: number, bottom: number) {+ const paragraphIndex = paragraphBounds?.findIndex((p) => p.paragraph.paragraphStart !== p.paragraph.paragraphEnd && p.rect.top < bottom && p.rect.bottom > scrollTop);+ if (paragraphIndex === -1) return undefined;+ for (let i = paragraphIndex; i >= 0; i--) {+ const paragraph = paragraphBounds?.[i];+ if (paragraph.paragraph.paragraphStyle?.headingId) {+ return paragraph.paragraph.paragraphStyle.headingId;+ }+ }++ return undefined;+}++export function DocSideMenu() {+ const commandService = useDependency(ICommandService);+ const instanceService = useDependency(IUniverInstanceService);+ const currentDoc = useObservable(useMemo(() => instanceService.getCurrentTypeOfUnit$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC), []));+ const renderManagerService = useDependency(IRenderManagerService);+ const fullDataStream = currentDoc?.getBody()?.dataStream ?? '';+ const [_updateKey, setUpdateKey] = useState(0);+ const unitId = currentDoc?.getUnitId() ?? '';+ const renderer = renderManagerService.getRenderById(unitId);+ const docEventManagerService = renderer?.with(DocEventManagerService);+ const paragraphBounds = docEventManagerService?.paragraphBounds;+ const left = renderer?.mainComponent?.left ?? 0;+ const [scrollTop, setScrollTop] = useState(0);+ const canvasHeight = renderer?.engine.height ?? 0;+ const scaleY = renderer?.scene.scaleY ?? 1;+ const bottom = scrollTop + (canvasHeight / scaleY);+ useObservable(useMemo(() => (renderer?.engine.onTransformChange$ ? fromEventSubject(renderer?.engine.onTransformChange$).pipe(throttleTime(33)) : of(null)), [renderer?.engine.onTransformChange$]));+ const mode = left < 180 ? 'float' : 'side-bar';+ let minLevel = Infinity;+ const menus = paragraphBounds?.filter(({ paragraph: p }) => p.paragraphStyle?.namedStyleType !== undefined && p.paragraphStyle!.namedStyleType !== NamedStyleType.SUBTITLE).map(({ paragraph: p }) => {+ const level = transformNamedStyleTypeToLevel(p.paragraphStyle!.namedStyleType!);+ minLevel = Math.min(minLevel, level);++ return {+ id: p.paragraphStyle!.headingId!,+ text: getPlainText(fullDataStream.slice(p.paragraphStart, p.paragraphEnd)),+ level,+ isTitle: p.paragraphStyle?.namedStyleType === NamedStyleType.TITLE,+ };+ });++ const [open, setOpen] = useState(false);+ const activeId = findActiveHeading(paragraphBounds ?? [], scrollTop, bottom);++ useEffect(() => {+ const debounceUpdater = debounce(setUpdateKey, 100);++ const sub = commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id === RichTextEditingMutation.id) {+ const params = commandInfo.params as IRichTextEditingMutationParams;+ if (params.unitId === currentDoc?.getUnitId()) {+ debounceUpdater((prev) => prev + 1);+ }+ }+ });+ return () => {+ sub.dispose();+ };+ }, [commandService, currentDoc]);+ useEffect(() => {+ const viewport = renderer?.scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);+ if (!viewport) {+ return;+ }++ const sub = fromEventSubject(viewport.onScrollAfter$).pipe(throttleTime(33)).subscribe((params) => {+ setScrollTop(params.viewportScrollY);+ });+ return () => {+ sub.unsubscribe();+ };+ }, [renderer]);++ const handleClick = (menu: ISideMenuItem) => {+ const bound = paragraphBounds?.find((p) => p.paragraph.paragraphStyle?.headingId === menu.id);+ if (!bound) {+ return;+ }+ const viewport = renderer?.scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);+ if (!viewport) {+ return;+ }+ viewport.scrollToViewportPos({ viewportScrollY: bound.rect.top });+ };++ if (!currentDoc || isInternalEditorID(unitId) || !menus?.length) {+ return null;+ }++ return (+ <div className="univer-absolute univer-bottom-0 univer-left-0 univer-top-0 univer-z-[100] univer-w-[0px]">+ <SideMenu+ menus={menus}+ open={open}+ onOpenChange={setOpen}+ mode={mode}+ maxWidth={mode === 'float' ? undefined : Math.floor(left)}+ wrapperClass="univer-mt-12"+ activeId={activeId}+ onClick={handleClick}+ />+ </div>+ );+}