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): polish docs table rendering and menus (#6926)
Univere156edcc6a9e
diff --git a/e2e/visual-comparison/docs/docs-visual-comparison.spec.ts-snapshots/default-doc-ci-chromium-linux.png b/e2e/visual-comparison/docs/docs-visual-comparison.spec.ts-snapshots/default-doc-ci-chromium-linux.pngindex 6026816bc5..63c0c69485 100644Binary files a/e2e/visual-comparison/docs/docs-visual-comparison.spec.ts-snapshots/default-doc-ci-chromium-linux.png and b/e2e/visual-comparison/docs/docs-visual-comparison.spec.ts-snapshots/default-doc-ci-chromium-linux.png differdiff --git a/packages/core/src/docs/data-model/__tests__/empty-snapshot.spec.ts b/packages/core/src/docs/data-model/__tests__/empty-snapshot.spec.tsnew file mode 100644index 0000000000..dbf14f1f58--- /dev/null+++ b/packages/core/src/docs/data-model/__tests__/empty-snapshot.spec.ts@@ -0,0 +1,28 @@+/**+ * 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 { describe, expect, it } from 'vitest';+import { getEmptySnapshot } from '../empty-snapshot';++describe('getEmptySnapshot', () => {+ it('uses comfortable paragraph spacing defaults for new docs', () => {+ expect(getEmptySnapshot().body?.paragraphs?.[0].paragraphStyle).toEqual({+ spaceAbove: { v: 0 },+ lineSpacing: 1.5,+ spaceBelow: { v: 8 },+ });+ });+});diff --git a/packages/core/src/docs/data-model/__tests__/utils.spec.ts b/packages/core/src/docs/data-model/__tests__/utils.spec.tsindex a45399f1a1..043c75c0e4 100644--- a/packages/core/src/docs/data-model/__tests__/utils.spec.ts+++ b/packages/core/src/docs/data-model/__tests__/utils.spec.ts@@ -35,6 +35,10 @@ describe('document data-model utils', () => {it: BooleanNumber.FALSE,bl: BooleanNumber.FALSE,});+ const fontStackStyle = getFontStyleString({+ ff: '"SF Mono", "Cascadia Code", Consolas, monospace',+ fs: 12,+ });expect(defaultStyle).toEqual({fontCache: `${DEFAULT_STYLES.fs}pt ${DEFAULT_STYLES.ff}`,@@ -48,6 +52,8 @@ describe('document data-model utils', () => {expect(superscriptStyle.fontSize).toBeCloseTo(7.8);expect(superscriptStyle.fontString).toContain(DEFAULT_FONTFACE_PLANE);expect(normalStyle.fontCache).toBe('normal normal 14pt "Ping Fang"');+ expect(fontStackStyle.fontFamily).toBe('"SF Mono", "Cascadia Code", Consolas, monospace');+ expect(fontStackStyle.fontString).toContain('"SF Mono", "Cascadia Code", Consolas, monospace');});it('should expose baseline offsets and convert text rotation', () => {diff --git a/packages/core/src/docs/data-model/empty-snapshot.ts b/packages/core/src/docs/data-model/empty-snapshot.tsindex 2e85a75299..0e19d495a5 100644--- a/packages/core/src/docs/data-model/empty-snapshot.ts+++ b/packages/core/src/docs/data-model/empty-snapshot.ts@@ -16,6 +16,7 @@import type { IDocumentData } from '../../types/interfaces';import { generateRandomId } from '../../shared/tools';+import { DEFAULT_DOCUMENT_PARAGRAPH_LINE_SPACING, DEFAULT_DOCUMENT_PARAGRAPH_SPACE_ABOVE, DEFAULT_DOCUMENT_PARAGRAPH_SPACE_BELOW, MODERN_DOCUMENT_WIDTH, ModernDocumentWidthMode } from '../../types/const';import { BooleanNumber } from '../../types/enum';import { LocaleType } from '../../types/enum/locale-type';import { DocumentFlavor } from '../../types/interfaces';@@ -43,9 +44,9 @@ export function getEmptySnapshot({startIndex: 0,paragraphStyle: {- spaceAbove: { v: 5 },- lineSpacing: 1,- spaceBelow: { v: 0 },+ spaceAbove: { v: DEFAULT_DOCUMENT_PARAGRAPH_SPACE_ABOVE },+ lineSpacing: DEFAULT_DOCUMENT_PARAGRAPH_LINE_SPACING,+ spaceBelow: { v: DEFAULT_DOCUMENT_PARAGRAPH_SPACE_BELOW },},},],@@ -57,10 +58,10 @@ export function getEmptySnapshot(},documentStyle: {pageSize: {- width: 595 / 0.75,+ width: MODERN_DOCUMENT_WIDTH[ModernDocumentWidthMode.MEDIUM],height: 842 / 0.75,},- documentFlavor: DocumentFlavor.TRADITIONAL,+ documentFlavor: DocumentFlavor.MODERN,marginTop: 50,marginBottom: 50,marginRight: 50,diff --git a/packages/core/src/docs/data-model/text-x/__tests__/block-ranges.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/block-ranges.spec.tsnew file mode 100644index 0000000000..556e9748e7--- /dev/null+++ b/packages/core/src/docs/data-model/text-x/__tests__/block-ranges.spec.ts@@ -0,0 +1,82 @@+/**+ * 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 { IDocumentBody } from '../../../../types/interfaces';+import { describe, expect, it } from 'vitest';+import { DataStreamTreeTokenType } from '../../types';+import { deleteBlockRanges, insertBlockRanges } from '../apply-utils/common';+import { getPlainText } from '../build-utils/parse';+import { getBodySlice } from '../utils';++describe('document block ranges', () => {+ it('moves following block ranges when text is inserted before them', () => {+ const body: IDocumentBody = {+ dataStream: 'A\rB\r\n',+ blockRanges: [{ blockId: 'callout-1', blockType: 'callout', startIndex: 2, endIndex: 3 }],+ };++ insertBlockRanges(body, { dataStream: 'XX' }, 2, 1);++ expect(body.blockRanges).toEqual([+ { blockId: 'callout-1', blockType: 'callout', startIndex: 4, endIndex: 5 },+ ]);+ });++ it('expands containing block ranges when text is inserted inside them', () => {+ const body: IDocumentBody = {+ dataStream: `${DataStreamTreeTokenType.BLOCK_START}A\r${DataStreamTreeTokenType.BLOCK_END}\n`,+ blockRanges: [{ blockId: 'callout-1', blockType: 'callout', startIndex: 0, endIndex: 3 }],+ };++ insertBlockRanges(body, { dataStream: 'XX' }, 2, 2);++ expect(body.blockRanges).toEqual([+ { blockId: 'callout-1', blockType: 'callout', startIndex: 0, endIndex: 5 },+ ]);+ });++ it('cuts block ranges to the copied body with relative indexes', () => {+ const body: IDocumentBody = {+ dataStream: `A\r${DataStreamTreeTokenType.BLOCK_START}B\r${DataStreamTreeTokenType.BLOCK_END}C\r\n`,+ blockRanges: [{ blockId: 'callout-1', blockType: 'callout', startIndex: 2, endIndex: 5 }],+ };++ const slice = getBodySlice(body, 2, 6);++ expect(slice.dataStream).toBe(`${DataStreamTreeTokenType.BLOCK_START}B\r${DataStreamTreeTokenType.BLOCK_END}`);+ expect(slice.blockRanges).toEqual([+ { blockId: 'callout-1', blockType: 'callout', startIndex: 0, endIndex: 3 },+ ]);+ });++ it('removes fully deleted block ranges', () => {+ const body: IDocumentBody = {+ dataStream: `${DataStreamTreeTokenType.BLOCK_START}A\r${DataStreamTreeTokenType.BLOCK_END}\n`,+ blockRanges: [{ blockId: 'callout-1', blockType: 'callout', startIndex: 0, endIndex: 3 }],+ };++ const removed = deleteBlockRanges(body, 4, 0);++ expect(removed).toEqual([{ blockId: 'callout-1', blockType: 'callout', startIndex: 0, endIndex: 3 }]);+ expect(body.blockRanges).toEqual([]);+ });++ it('removes block tokens from plain text', () => {+ const stream = `${DataStreamTreeTokenType.BLOCK_START}Callout\r${DataStreamTreeTokenType.BLOCK_END}\n`;++ expect(getPlainText(stream)).toBe('Callout');+ });+});diff --git a/packages/core/src/docs/data-model/text-x/apply-utils/common.ts b/packages/core/src/docs/data-model/text-x/apply-utils/common.tsindex 2b9bedf703..fcc19fcc83 100644--- a/packages/core/src/docs/data-model/text-x/apply-utils/common.ts+++ b/packages/core/src/docs/data-model/text-x/apply-utils/common.ts@@ -20,6 +20,7 @@ import type {ICustomDecoration,ICustomRange,ICustomTable,+ IDocumentBlockRange,IDocumentBody,IParagraph,ISectionBreak,@@ -315,6 +316,41 @@ export function insertTables(body: IDocumentBody, insertBody: IDocumentBody, tex}}+export function insertBlockRanges(body: IDocumentBody, insertBody: IDocumentBody, textLength: number, currentIndex: number) {+ if (!body.blockRanges && !insertBody.blockRanges?.length) {+ return;+ }++ if (!body.blockRanges) {+ body.blockRanges = [];+ }++ const { blockRanges } = body;+ for (let i = 0, len = blockRanges.length; i < len; i++) {+ const blockRange = blockRanges[i];+ const { startIndex, endIndex } = blockRange;++ if (startIndex >= currentIndex) {+ blockRange.startIndex += textLength;+ blockRange.endIndex += textLength;+ } else if (endIndex >= currentIndex) {+ blockRange.endIndex += textLength;+ }+ }++ const insertBlockRanges = insertBody.blockRanges;+ if (insertBlockRanges) {+ for (let i = 0, len = insertBlockRanges.length; i < len; i++) {+ const blockRange = insertBlockRanges[i];+ blockRange.startIndex += currentIndex;+ blockRange.endIndex += currentIndex;+ }++ blockRanges.push(...insertBlockRanges);+ blockRanges.sort(sortRulesFactory('startIndex'));+ }+}+export function sliceByParagraph(body: IDocumentBody) {const { dataStream, paragraphs = [] } = body;const ranges = [];@@ -873,6 +909,44 @@ export function deleteCustomRanges(body: IDocumentBody, textLength: number, currreturn removeCustomRanges;}+export function deleteBlockRanges(body: IDocumentBody, textLength: number, currentIndex: number) {+ const { blockRanges } = body;++ const startIndex = currentIndex;+ const endIndex = currentIndex + textLength - 1;+ const removeBlockRanges: IDocumentBlockRange[] = [];++ if (blockRanges) {+ const newBlockRanges = [];+ for (let i = 0, len = blockRanges.length; i < len; i++) {+ const blockRange = blockRanges[i];+ const { startIndex: st, endIndex: ed } = blockRange;+ if (st >= startIndex && ed <= endIndex) {+ removeBlockRanges.push(blockRange);+ continue;+ } else if (Math.max(startIndex, st) <= Math.min(endIndex, ed)) {+ const segments = horizontalLineSegmentsSubtraction(st, ed, startIndex, endIndex);++ if (segments.length === 0) {+ removeBlockRanges.push(blockRange);+ continue;+ }++ blockRange.startIndex = segments[0];+ blockRange.endIndex = segments[1];+ } else if (endIndex < st) {+ blockRange.startIndex -= textLength;+ blockRange.endIndex -= textLength;+ }+ newBlockRanges.push(blockRange);+ }++ body.blockRanges = newBlockRanges;+ }++ return removeBlockRanges;+}+export function deleteCustomDecorations(body: IDocumentBody, textLength: number, currentIndex: number, needOffset = true) {const { customDecorations } = body;diff --git a/packages/core/src/docs/data-model/text-x/apply-utils/delete-apply.ts b/packages/core/src/docs/data-model/text-x/apply-utils/delete-apply.tsindex d2a89b465e..edb18112f2 100644--- a/packages/core/src/docs/data-model/text-x/apply-utils/delete-apply.ts+++ b/packages/core/src/docs/data-model/text-x/apply-utils/delete-apply.ts@@ -17,6 +17,7 @@import type { IDocumentBody } from '../../../../types/interfaces';import { deleteContent } from '../../../../shared';import {+ deleteBlockRanges,deleteCustomBlocks,deleteCustomDecorations,deleteCustomRanges,@@ -42,6 +43,8 @@ export function updateAttributeByDelete(body: IDocumentBody, textLength: number,const removeTables = deleteTables(body, textLength, currentIndex);+ const removeBlockRanges = deleteBlockRanges(body, textLength, currentIndex);+const removeCustomRanges = deleteCustomRanges(body, textLength, currentIndex);const removeCustomDecorations = deleteCustomDecorations(body, textLength, currentIndex);@@ -59,6 +62,7 @@ export function updateAttributeByDelete(body: IDocumentBody, textLength: number,sectionBreaks: removeSectionBreaks,customBlocks: removeCustomBlocks,tables: removeTables,+ blockRanges: removeBlockRanges,customRanges: removeCustomRanges,customDecorations: removeCustomDecorations,};diff --git a/packages/core/src/docs/data-model/text-x/apply-utils/insert-apply.ts b/packages/core/src/docs/data-model/text-x/apply-utils/insert-apply.tsindex 8225463aae..357439963a 100644--- a/packages/core/src/docs/data-model/text-x/apply-utils/insert-apply.ts+++ b/packages/core/src/docs/data-model/text-x/apply-utils/insert-apply.ts@@ -17,6 +17,7 @@import type { IDocumentBody } from '../../../../types/interfaces';import { insertTextToContent } from '../../../../shared';import {+ insertBlockRanges,insertCustomBlocks,insertCustomDecorations,insertCustomRanges,@@ -44,6 +45,8 @@ export function updateAttributeByInsert(insertTables(body, insertBody, textLength, currentIndex);+ insertBlockRanges(body, insertBody, textLength, currentIndex);+insertCustomRanges(body, insertBody, textLength, currentIndex);insertCustomDecorations(body, insertBody, textLength, currentIndex);diff --git a/packages/core/src/docs/data-model/text-x/apply-utils/update-apply.ts b/packages/core/src/docs/data-model/text-x/apply-utils/update-apply.tsindex 4012ba7390..ae9019a86e 100644--- a/packages/core/src/docs/data-model/text-x/apply-utils/update-apply.ts+++ b/packages/core/src/docs/data-model/text-x/apply-utils/update-apply.ts@@ -20,11 +20,13 @@ import { Tools, UpdateDocsAttributeType } from '../../../../shared';import { CustomDecorationType } from '../../../../types/interfaces';import { PresetListType } from '../../preset-list-type';import {+ deleteBlockRanges,deleteCustomBlocks,deleteParagraphs,deleteSectionBreaks,deleteTables,deleteTextRuns,+ insertBlockRanges,insertCustomBlocks,insertParagraphs,insertSectionBreaks,@@ -49,6 +51,7 @@ export function updateAttribute(const removeSectionBreaks = updateSectionBreaks(body, updateBody, textLength, currentIndex, coverType);const removeCustomBlocks = updateCustomBlocks(body, updateBody, textLength, currentIndex, coverType);const removeTables = updateTables(body, updateBody, textLength, currentIndex, coverType);+ const removeBlockRanges = updateBlockRanges(body, updateBody, textLength, currentIndex, coverType);const removeCustomRanges = updateCustomRanges(body, updateBody, textLength, currentIndex, coverType);const removeCustomDecorations = updateCustomDecorations(body, updateBody, textLength, currentIndex, coverType);@@ -59,6 +62,7 @@ export function updateAttribute(sectionBreaks: removeSectionBreaks,customBlocks: removeCustomBlocks,tables: removeTables,+ blockRanges: removeBlockRanges,customRanges: removeCustomRanges,customDecorations: removeCustomDecorations,};@@ -433,6 +437,33 @@ function updateTables(return removeTables;}+function updateBlockRanges(+ body: IDocumentBody,+ updateBody: IDocumentBody,+ textLength: number,+ currentIndex: number,+ coverType: UpdateDocsAttributeType+) {+ const { blockRanges } = body;+ const { blockRanges: updateDataBlockRanges } = updateBody;++ if (blockRanges == null || updateDataBlockRanges == null) {+ return;+ }++ const removeBlockRanges = deleteBlockRanges(body, textLength, currentIndex);+ if (coverType !== UpdateDocsAttributeType.REPLACE) {+ updateBody.blockRanges = updateDataBlockRanges.map((updateBlockRange) => {+ const removeBlockRange = removeBlockRanges.find((blockRange) => blockRange.blockId === updateBlockRange.blockId);+ return removeBlockRange ? { ...removeBlockRange, ...updateBlockRange } : updateBlockRange;+ });+ }++ insertBlockRanges(body, updateBody, textLength, currentIndex);++ return removeBlockRanges;+}+// retainfunction updateCustomRanges(body: IDocumentBody,diff --git a/packages/core/src/docs/data-model/text-x/build-utils/parse.ts b/packages/core/src/docs/data-model/text-x/build-utils/parse.tsindex 043a23ae90..a15973ffc7 100644--- a/packages/core/src/docs/data-model/text-x/build-utils/parse.ts+++ b/packages/core/src/docs/data-model/text-x/build-utils/parse.ts@@ -28,6 +28,8 @@ const tags = [DataStreamTreeTokenType.TABLE_CELL_END, // table startDataStreamTreeTokenType.TABLE_ROW_END, // table startDataStreamTreeTokenType.TABLE_END, // table end+ DataStreamTreeTokenType.BLOCK_START, // block start+ DataStreamTreeTokenType.BLOCK_END, // block end// DataStreamTreeTokenType.COLUMN_BREAK, // column break// DataStreamTreeTokenType.PAGE_BREAK, // page break// DataStreamTreeTokenType.DOCS_END, // document end@@ -36,8 +38,8 @@ const tags = [];export const getPlainText = (dataStream: string) => {- const text = dataStream.endsWith('\r\n') ? dataStream.slice(0, -2) : dataStream;- return tags.reduce((res, curr) => res.replaceAll(curr, ''), text);+ const text = tags.reduce((res, curr) => res.replaceAll(curr, ''), dataStream);+ return text.endsWith('\r\n') ? text.slice(0, -2) : text;};export const isEmptyDocument = (dataStream?: string) => {diff --git a/packages/core/src/docs/data-model/text-x/transform-utils.ts b/packages/core/src/docs/data-model/text-x/transform-utils.tsindex 6cb4be1e06..f2b3f9c36a 100644--- a/packages/core/src/docs/data-model/text-x/transform-utils.ts+++ b/packages/core/src/docs/data-model/text-x/transform-utils.ts@@ -17,7 +17,7 @@/* eslint-disable no-param-reassign */import type { Nullable } from '../../../shared';-import type { ICustomDecoration, ICustomRange, IDocumentBody, IParagraph, IParagraphStyle, ITextRun, ITextStyle } from '../../../types/interfaces';+import type { ICustomDecoration, ICustomRange, IDocumentBlockRange, IDocumentBody, IParagraph, IParagraphStyle, ITextRun, ITextStyle } from '../../../types/interfaces';import type { IRetainAction } from './action-types';import { Tools, UpdateDocsAttributeType } from '../../../shared';import { CustomDecorationType } from '../../../types/interfaces';@@ -422,12 +422,14 @@ export function transformBody(const {textRuns: thisTextRuns,paragraphs: thisParagraphs = [],+ blockRanges: thisBlockRanges = [],customRanges: thisCustomRanges,customDecorations: thisCustomDecorations,} = thisBody;const {textRuns: otherTextRuns,paragraphs: otherParagraphs = [],+ blockRanges: otherBlockRanges = [],customRanges: otherCustomRanges,customDecorations: otherCustomDecorations,} = otherBody;@@ -521,8 +523,28 @@ export function transformBody(retBody.paragraphs = paragraphs;}+ const blockRanges = transformBlockRanges(thisBlockRanges, otherBlockRanges, priority);+ if (blockRanges.length) {+ retBody.blockRanges = blockRanges;+ }+return {coverType,body: retBody,};}++function transformBlockRanges(thisBlockRanges: IDocumentBlockRange[], otherBlockRanges: IDocumentBlockRange[], priority: boolean): IDocumentBlockRange[] {+ if (!thisBlockRanges.length) {+ return otherBlockRanges;+ }++ if (!otherBlockRanges.length) {+ return [];+ }++ return otherBlockRanges.map((otherBlockRange) => {+ const thisBlockRange = thisBlockRanges.find((blockRange) => blockRange.blockId === otherBlockRange.blockId);+ return thisBlockRange && priority ? Tools.deepMerge(otherBlockRange, thisBlockRange) : otherBlockRange;+ });+}diff --git a/packages/core/src/docs/data-model/text-x/utils.ts b/packages/core/src/docs/data-model/text-x/utils.tsindex dfa71ef493..c13417f317 100644--- a/packages/core/src/docs/data-model/text-x/utils.ts+++ b/packages/core/src/docs/data-model/text-x/utils.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { ICustomBlock, ICustomDecoration, ICustomRange, IDocumentBody, IParagraph, ISectionBreak, ITextRun } from '../../../types/interfaces/i-document-data';+import type { ICustomBlock, ICustomDecoration, ICustomRange, IDocumentBlockRange, IDocumentBody, IParagraph, ISectionBreak, ITextRun } from '../../../types/interfaces/i-document-data';import type { IRetainAction } from './action-types';import { UpdateDocsAttributeType } from '../../../shared/command-enum';import { Tools } from '../../../shared/tools';@@ -103,6 +103,30 @@ export function getTableSlice(return newTables;}+export function getBlockRangeSlice(+ body: IDocumentBody,+ startOffset: number,+ endOffset: number+) {+ const { blockRanges = [] } = body;+ const newBlockRanges: IDocumentBlockRange[] = [];++ for (const blockRange of blockRanges) {+ const clonedBlockRange = Tools.deepClone(blockRange);+ const { startIndex, endIndex } = clonedBlockRange;++ if (startIndex >= startOffset && endIndex < endOffset) {+ newBlockRanges.push({+ ...clonedBlockRange,+ startIndex: startIndex - startOffset,+ endIndex: endIndex - startOffset,+ });+ }+ }++ return newBlockRanges;+}+export function getParagraphsSlice(body: IDocumentBody,startOffset: number,@@ -193,6 +217,11 @@ export function getBodySlice(docBody.tables = newTables;}+ const newBlockRanges = getBlockRangeSlice(body, startOffset, endOffset);+ if (newBlockRanges.length) {+ docBody.blockRanges = newBlockRanges;+ }+docBody.paragraphs = getParagraphsSlice(body, startOffset, endOffset);if (type === SliceBodyType.cut) {@@ -216,7 +245,7 @@ export function getBodySlice(}export function normalizeBody(body: IDocumentBody): IDocumentBody {- const { dataStream, textRuns, paragraphs, customRanges, customDecorations, tables } = body;+ const { dataStream, textRuns, paragraphs, customRanges, customDecorations, tables, blockRanges } = body;let leftOffset = 0;let rightOffset = 0;@@ -274,6 +303,7 @@ export function normalizeBody(body: IDocumentBody): IDocumentBody {customRanges,customDecorations,tables,+ blockRanges,};}@@ -409,12 +439,14 @@ export function composeBody(paragraphs: thisParagraphs = [],customRanges: thisCustomRanges,customDecorations: thisCustomDecorations = [],+ blockRanges: thisBlockRanges = [],} = thisBody;const {textRuns: otherTextRuns,paragraphs: otherParagraphs = [],customRanges: otherCustomRanges,customDecorations: otherCustomDecorations = [],+ blockRanges: otherBlockRanges = [],} = otherBody;retBody.textRuns = composeTextRuns(otherTextRuns, thisTextRuns, coverType);@@ -463,9 +495,32 @@ export function composeBody(retBody.paragraphs = paragraphs;}+ const blockRanges = composeDocumentBlockRanges(thisBlockRanges, otherBlockRanges);+ if (blockRanges.length) {+ retBody.blockRanges = blockRanges;+ }+return retBody;}+function composeDocumentBlockRanges(+ thisRanges: IDocumentBlockRange[],+ otherRanges: IDocumentBlockRange[]+): IDocumentBlockRange[] {+ if (!thisRanges.length) {+ return otherRanges;+ }++ if (!otherRanges.length) {+ return thisRanges;+ }++ const byId = new Map(thisRanges.map((range) => [range.blockId, Tools.deepClone(range)]));+ otherRanges.forEach((range) => byId.set(range.blockId, Tools.deepClone(range)));++ return Array.from(byId.values()).sort((left, right) => left.startIndex - right.startIndex);+}+export function isUselessRetainAction(action: IRetainAction): boolean {const { body } = action;@@ -473,9 +528,9 @@ export function isUselessRetainAction(action: IRetainAction): boolean {return true;}- const { textRuns, paragraphs, customRanges, customBlocks, customDecorations, tables } = body;+ const { textRuns, paragraphs, customRanges, customBlocks, customDecorations, tables, blockRanges } = body;- if (textRuns == null && paragraphs == null && customRanges == null && customBlocks == null && customDecorations == null && tables == null) {+ if (textRuns == null && paragraphs == null && customRanges == null && customBlocks == null && customDecorations == null && tables == null && blockRanges == null) {return true;}diff --git a/packages/core/src/docs/data-model/types.ts b/packages/core/src/docs/data-model/types.tsindex 997dfea70f..8836e2b3cd 100644--- a/packages/core/src/docs/data-model/types.ts+++ b/packages/core/src/docs/data-model/types.ts@@ -24,6 +24,7 @@ export enum DataStreamTreeNodeType {TABLE = 'TABLE',TABLE_ROW = 'TABLE_ROW',TABLE_CELL = 'TABLE_CELL',+ BLOCK = 'BLOCK',CUSTOM_BLOCK = 'CUSTOM_BLOCK', // \b images, mentions, etc. that do not participate in document flow}@@ -37,6 +38,9 @@ export enum DataStreamTreeTokenType {TABLE_CELL_END = '\x1D', // table cell endTABLE_ROW_END = '\x0E', // table row endTABLE_END = '\x0F', // table end+ // block.+ BLOCK_START = '\x10', // block start+ BLOCK_END = '\x11', // block end// custom range./*** @deprecateddiff --git a/packages/core/src/docs/data-model/utils.ts b/packages/core/src/docs/data-model/utils.tsindex 6a326f082e..f8a8f3edda 100644--- a/packages/core/src/docs/data-model/utils.ts+++ b/packages/core/src/docs/data-model/utils.ts@@ -31,7 +31,6 @@ export interface IDocumentSkeletonFontStyle {fontCache: string;}-// eslint-disable-next-line max-lines-per-functionexport function getFontStyleString(textStyle?: IStyleBase): IDocumentSkeletonFontStyle {@@ -72,26 +71,7 @@ export function getFontStyleString(originFontSize = Math.ceil(textStyle.fs);}- let fontFamilyResult = defaultFont;- if (textStyle.ff) {- let fontFamily = textStyle.ff;-- fontFamily = fontFamily.replace(/"/g, '').replace(/'/g, '');-- if (fontFamily.indexOf(' ') > -1) {- fontFamily = `"${fontFamily}"`;- }-- // if (fontFamily != null && document.fonts && !document.fonts.check('12px ' + fontFamily)) {- // menuButton.addFontToList(fontFamily);- // }-- if (fontFamily == null) {- fontFamily = defaultFont;- }-- fontFamilyResult = fontFamily;- }+ const fontFamilyResult = normalizeFontFamily(textStyle.ff, defaultFont);const { va: baselineOffset } = textStyle;@@ -119,6 +99,21 @@ export function getFontStyleString(};}+function normalizeFontFamily(fontFamily: string | null | undefined | void, defaultFont: string): string {+ if (!fontFamily?.trim()) {+ return defaultFont;+ }++ return fontFamily+ .split(',')+ .map((item) => {+ const family = item.trim().replace(/^['"]|['"]$/g, '');+ return family.includes(' ') ? `"${family}"` : family;+ })+ .filter(Boolean)+ .join(', ');+}+export function getBaselineOffsetInfo(_fontFamily: string, fontSize: number) {// The origin FontCache.getBaselineOffsetInfo needs _fontDataMap// But now _fontDataMap didn't not set value. So we can use getDefault.diff --git a/packages/core/src/sheets/__tests__/sheet-skeleton.integration.spec.ts b/packages/core/src/sheets/__tests__/sheet-skeleton.integration.spec.tsindex 7f9a586cba..01913ece21 100644--- a/packages/core/src/sheets/__tests__/sheet-skeleton.integration.spec.ts+++ b/packages/core/src/sheets/__tests__/sheet-skeleton.integration.spec.ts@@ -25,6 +25,7 @@ import { ThemeService } from '../../services/theme/theme.service';import { ColorKit } from '../../shared';import { BooleanNumber, HorizontalAlign } from '../../types/enum';import { LocaleType } from '../../types/enum/locale-type';+import { DocumentFlavor } from '../../types/interfaces';import { createSheetGapTestConfig, SheetSkeleton } from '../sheet-skeleton';import { RANGE_TYPE } from '../typedef';import { createCoreTestBed } from './create-core-test-bed';@@ -271,6 +272,8 @@ describe('SheetSkeleton integration', () => {width: Number.POSITIVE_INFINITY,height: Number.POSITIVE_INFINITY,},+ documentFlavor: DocumentFlavor.UNSPECIFIED,+ paragraphLineGapDefault: 0,renderConfig: {horizontalAlign: HorizontalAlign.CENTER,},diff --git a/packages/core/src/sheets/__tests__/util.spec.ts b/packages/core/src/sheets/__tests__/util.spec.tsindex 220ce3db35..e387634c52 100644--- a/packages/core/src/sheets/__tests__/util.spec.ts+++ b/packages/core/src/sheets/__tests__/util.spec.ts@@ -16,7 +16,7 @@import { describe, expect, it } from 'vitest';import { BaselineOffset, BooleanNumber, HorizontalAlign, VerticalAlign, WrapStrategy } from '../../types/enum';-import { CustomRangeType } from '../../types/interfaces';+import { CustomRangeType, DocumentFlavor } from '../../types/interfaces';import {addLinkToDocumentModel,createDocumentModelWithStyle,@@ -48,6 +48,8 @@ describe('sheet util helpers', () => {marginRight: 4,marginBottom: 3,marginLeft: 2,+ documentFlavor: DocumentFlavor.UNSPECIFIED,+ paragraphLineGapDefault: 0,renderConfig: {horizontalAlign: HorizontalAlign.CENTER,verticalAlign: VerticalAlign.MIDDLE,diff --git a/packages/core/src/sheets/sheet-skeleton.ts b/packages/core/src/sheets/sheet-skeleton.tsindex 402724c8a8..43d76255c7 100644--- a/packages/core/src/sheets/sheet-skeleton.ts+++ b/packages/core/src/sheets/sheet-skeleton.ts@@ -46,6 +46,7 @@ import { ImageCacheMap } from '../shared/cache/image-cache';import { getIntersectRange } from '../shared/range';import { Skeleton } from '../skeleton';import { BooleanNumber, HorizontalAlign } from '../types/enum';+import { DocumentFlavor } from '../types/interfaces';/*** Configuration for a single gap (visual separator between rows or columns).@@ -1174,6 +1175,8 @@ export class SheetSkeleton extends Skeleton {width: Number.POSITIVE_INFINITY,height: Number.POSITIVE_INFINITY,};+ documentData.documentStyle.documentFlavor = DocumentFlavor.UNSPECIFIED;+ documentData.documentStyle.paragraphLineGapDefault = 0;documentData.documentStyle.renderConfig = {...documentData.documentStyle.renderConfig,diff --git a/packages/core/src/sheets/util.ts b/packages/core/src/sheets/util.tsindex 4887e9547b..cf9d5b3cbb 100644--- a/packages/core/src/sheets/util.ts+++ b/packages/core/src/sheets/util.ts@@ -24,7 +24,7 @@ import { TextX } from '../docs/data-model/text-x/text-x';import { convertTextRotation } from '../docs/data-model/utils';import { Rectangle } from '../shared';import { HorizontalAlign, VerticalAlign, WrapStrategy } from '../types/enum';-import { CustomRangeType } from '../types/interfaces';+import { CustomRangeType, DocumentFlavor } from '../types/interfaces';export interface IFontLocale {fontList: string[];@@ -109,10 +109,12 @@ export function createDocumentModelWithStyle(content: string, textStyle: ITextStwidth: Number.POSITIVE_INFINITY,height: Number.POSITIVE_INFINITY,},+ documentFlavor: DocumentFlavor.UNSPECIFIED,marginTop,marginBottom,marginRight,marginLeft,+ paragraphLineGapDefault: 0,renderConfig: {horizontalAlign,verticalAlign,diff --git a/packages/core/src/sheets/worksheet.ts b/packages/core/src/sheets/worksheet.tsindex 56ee72a23f..8989f1f445 100644--- a/packages/core/src/sheets/worksheet.ts+++ b/packages/core/src/sheets/worksheet.ts@@ -28,6 +28,7 @@ import { createRowColIter } from '../shared/row-col-iter';import { generateRandomId } from '../shared/tools';import { DEFAULT_STYLES } from '../types/const';import { CellValueType } from '../types/enum';+import { DocumentFlavor } from '../types/interfaces';import { cloneWorksheetData } from './clone';import { ColumnManager } from './column-manager';import { Range } from './range';@@ -1269,6 +1270,8 @@ export class Worksheet {width: Number.POSITIVE_INFINITY,height: Number.POSITIVE_INFINITY,};+ documentData.documentStyle.documentFlavor = DocumentFlavor.UNSPECIFIED;+ documentData.documentStyle.paragraphLineGapDefault = 0;documentData.documentStyle.renderConfig = {...documentData.documentStyle.renderConfig,diff --git a/packages/core/src/types/const/const.ts b/packages/core/src/types/const/const.tsindex aa037ab67d..6925511f53 100644--- a/packages/core/src/types/const/const.ts+++ b/packages/core/src/types/const/const.ts@@ -184,6 +184,10 @@ export const NAMED_STYLE_MAP: Record<NamedStyleType, Nullable<ITextStyle>> = {const BOTTOM_P = 4;+export const DEFAULT_DOCUMENT_PARAGRAPH_LINE_SPACING = 1.5;+export const DEFAULT_DOCUMENT_PARAGRAPH_SPACE_ABOVE = 0;+export const DEFAULT_DOCUMENT_PARAGRAPH_SPACE_BELOW = 8;+export const NAMED_STYLE_SPACE_MAP: Record<NamedStyleType, Nullable<IParagraphStyle>> = {[NamedStyleType.HEADING_1]: {spaceAbove: {@@ -227,10 +231,10 @@ export const NAMED_STYLE_SPACE_MAP: Record<NamedStyleType, Nullable<IParagraphSt},[NamedStyleType.NORMAL_TEXT]: {spaceAbove: {- v: 0,+ v: DEFAULT_DOCUMENT_PARAGRAPH_SPACE_ABOVE,},spaceBelow: {- v: 0,+ v: DEFAULT_DOCUMENT_PARAGRAPH_SPACE_BELOW,},},[NamedStyleType.TITLE]: {diff --git a/packages/core/src/types/const/page-size.ts b/packages/core/src/types/const/page-size.tsindex 5438616bbc..00bb111ea1 100644--- a/packages/core/src/types/const/page-size.ts+++ b/packages/core/src/types/const/page-size.ts@@ -63,3 +63,17 @@ export const PAGE_SIZE: Record<PaperType, Required<ISize>> = {height: 1632,},};++export enum ModernDocumentWidthMode {+ NARROW = 'narrow',+ MEDIUM = 'medium',+ WIDE = 'wide',+}++export const MODERN_DOCUMENT_WIDTH: Record<ModernDocumentWidthMode, number> = {+ [ModernDocumentWidthMode.NARROW]: PAGE_SIZE[PaperType.A4].width,+ [ModernDocumentWidthMode.MEDIUM]: 960,+ [ModernDocumentWidthMode.WIDE]: PAGE_SIZE[PaperType.A3].width,+};++export const MODERN_DOCUMENT_DEFAULT_MARGIN = 50 / 0.75;diff --git a/packages/core/src/types/interfaces/i-document-data.ts b/packages/core/src/types/interfaces/i-document-data.tsindex b595c22c95..c3dfce0298 100644--- a/packages/core/src/types/interfaces/i-document-data.ts+++ b/packages/core/src/types/interfaces/i-document-data.ts@@ -131,6 +131,8 @@ export interface IDocumentBody {tables?: ICustomTable[]; // Table+ blockRanges?: IDocumentBlockRange[]; // Generic structured block range, e.g. callout, quote, code.+// tableOfContents?: { [index: number]: ITableOfContent }; // tableOfContents// links?: { [index: number]: IHyperlink }; // links@@ -363,6 +365,13 @@ export type IHyperLinkCustomRange = ICustomRange<{ url: string }>;export type IMentionCustomRange = ICustomRange<IMention>;+export interface IDocumentBlockRange {+ startIndex: number;+ endIndex: number;+ blockId: string;+ blockType: string;+}+export enum CustomRangeType {HYPERLINK,FIELD, // 17.16 Fields and Hyperlinksdiff --git a/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts b/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.tsindex 371ddb05cd..58e8ced678 100644--- a/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts+++ b/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts@@ -20,15 +20,17 @@ import {Direction,ICommandService,IUniverInstanceService,+ ObjectRelativeFromH,+ ObjectRelativeFromV,PositionedObjectLayoutType,UniverInstanceType,WrapTextType,} from '@univerjs/core';-import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';+import { DocSelectionManagerService, DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';import { DocDrawingController as CoreDocDrawingController, DocDrawingService, IDocDrawingService } from '@univerjs/docs-drawing';-import { DocSelectionRenderService } from '@univerjs/docs-ui';+import { DocContentInsertService, DocSelectionRenderService } from '@univerjs/docs-ui';import { DrawingManagerService, IDrawingManagerService } from '@univerjs/drawing';-import { IRenderManagerService } from '@univerjs/engine-render';+import { DocumentEditArea, IRenderManagerService } from '@univerjs/engine-render';import { afterEach, describe, expect, it, vi } from 'vitest';import { createDocUiTestBed } from '../../../__tests__/create-doc-ui-test-bed';import { DocDrawingAddRemoveController } from '../../../controllers/doc-drawing-notification.controller';@@ -36,7 +38,7 @@ import { DeleteDocDrawingsCommand } from '../delete-doc-drawing.command';import { InsertDocDrawingCommand } from '../insert-doc-drawing.command';import { MoveDocDrawingsCommand } from '../move-drawings.command';import { RemoveDocDrawingCommand } from '../remove-doc-drawing.command';-import { UpdateDocDrawingDistanceCommand, UpdateDocDrawingWrapTextCommand, UpdateDrawingDocTransformCommand } from '../update-doc-drawing.command';+import { TextWrappingStyle, UpdateDocDrawingDistanceCommand, UpdateDocDrawingWrappingStyleCommand, UpdateDocDrawingWrapTextCommand, UpdateDrawingDocTransformCommand } from '../update-doc-drawing.command';function createBaseDocData(): IDocumentData {return {@@ -127,6 +129,7 @@ function setupDrawingTestBed(docData: IDocumentData) {injector.add([DocDrawingService]);injector.add([IDocDrawingService, { useClass: DocDrawingService }]);injector.add([IDrawingManagerService, { useClass: DrawingManagerService }]);+ injector.add([DocContentInsertService]);injector.add([CoreDocDrawingController]);injector.add([DocDrawingAddRemoveController]);@@ -137,6 +140,7 @@ function setupDrawingTestBed(docData: IDocumentData) {DeleteDocDrawingsCommand,MoveDocDrawingsCommand,UpdateDocDrawingDistanceCommand,+ UpdateDocDrawingWrappingStyleCommand,UpdateDocDrawingWrapTextCommand,UpdateDrawingDocTransformCommand,RichTextEditingMutation as unknown as ICommand,@@ -211,6 +215,48 @@ describe('docs drawing commands integration', () => {testBed.univer.dispose();});+ it('uses the explicit content insert range for drawing insertion', async () => {+ const insertOffset = 5;+ const testBed = setupDrawingTestBed(createBaseDocData());++ testBed.selectionManager.__TEST_ONLY_add([{+ startOffset: 0,+ endOffset: 0,+ collapsed: true,+ isActive: true,+ segmentId: '',+ style: null as never,+ }]);+ testBed.get(DocContentInsertService).setInsertRange({+ unitId: 'test-doc',+ startOffset: insertOffset,+ endOffset: insertOffset,+ });++ expect(await testBed.commandService.executeCommand(InsertDocDrawingCommand.id, {+ drawings: [{+ drawingId: 'shape-1',+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ drawingType: 'image',+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,+ docTransform: {+ positionH: { posOffset: 1 },+ positionV: { posOffset: 2 },+ },+ }],+ })).toBe(true);+ await awaitTime(0);++ const doc = testBed.get(IUniverInstanceService)+ .getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)!;++ expect(doc.getBody()?.dataStream).toBe('Hello\b\r\n');+ expect(doc.getBody()?.customBlocks).toEqual([{ startIndex: insertOffset, blockId: 'shape-1' }]);++ testBed.univer.dispose();+ });+it('deletes a focused drawing through the command pipeline and removes it from the document and services', async () => {const testBed = setupDrawingTestBed(createDrawingDocData());@@ -303,6 +349,96 @@ describe('docs drawing commands integration', () => {testBed.univer.dispose();});+ it('keeps table cell drawing position when switching from inline to floating layout', async () => {+ const docData = createDrawingDocData();+ docData.drawings!['shape-1'].layoutType = PositionedObjectLayoutType.INLINE;+ docData.drawings!['shape-1'].docTransform = {+ size: {+ width: 40,+ height: 24,+ },+ positionH: {+ relativeFrom: ObjectRelativeFromH.PAGE,+ posOffset: 999,+ },+ positionV: {+ relativeFrom: ObjectRelativeFromV.PARAGRAPH,+ posOffset: 999,+ },+ angle: 0,+ } as never;+ const testBed = setupDrawingTestBed(docData);+ const skeletonManager = testBed.injector.get(DocSkeletonManagerService);+ vi.spyOn(skeletonManager, 'getViewModel').mockReturnValue({+ getEditArea: () => DocumentEditArea.BODY,+ reset: vi.fn(),+ } as never);+ vi.spyOn(skeletonManager, 'getSkeleton').mockReturnValue({+ getSkeletonData: () => ({+ pages: [{+ marginTop: 72,+ marginLeft: 90,+ marginBottom: 72,+ pageHeight: 800,+ pageWidth: 600,+ headerId: '',+ footerId: '',+ skeDrawings: new Map(),+ skeTables: new Map([+ ['table-1', {+ rows: [{+ cells: [{+ marginTop: 4,+ marginLeft: 5,+ skeDrawings: new Map([+ ['shape-1', {+ drawingId: 'shape-1',+ aLeft: 12,+ aTop: 20,+ columnLeft: 3,+ lineTop: 7,+ blockAnchorTop: 15,+ drawingOrigin: docData.drawings!['shape-1'],+ }],+ ]),+ skeTables: new Map(),+ }],+ }],+ }],+ ]),+ }],+ skeHeaders: new Map(),+ skeFooters: new Map(),+ }),+ } as never);++ expect(await testBed.commandService.executeCommand(UpdateDocDrawingWrappingStyleCommand.id, {+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ drawings: [{+ drawingId: 'shape-1',+ }],+ wrappingStyle: TextWrappingStyle.WRAP_SQUARE,+ })).toBe(true);+ await awaitTime(0);++ const doc = testBed.get(IUniverInstanceService)+ .getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)!;+ const drawing = doc.getSnapshot().drawings?.['shape-1'];++ expect(drawing?.layoutType).toBe(PositionedObjectLayoutType.WRAP_SQUARE);+ expect(drawing?.docTransform.positionH).toEqual({+ relativeFrom: ObjectRelativeFromH.PAGE,+ posOffset: 12,+ });+ expect(drawing?.docTransform.positionV).toEqual({+ relativeFrom: ObjectRelativeFromV.PARAGRAPH,+ posOffset: 5,+ });++ testBed.univer.dispose();+ });+it('updates drawing doc transform through the command pipeline', async () => {const testBed = setupDrawingTestBed(createDrawingDocData());diff --git a/packages/docs-drawing-ui/src/commands/commands/insert-doc-drawing.command.ts b/packages/docs-drawing-ui/src/commands/commands/insert-doc-drawing.command.tsindex 8d38f82c95..600199f327 100644--- a/packages/docs-drawing-ui/src/commands/commands/insert-doc-drawing.command.ts+++ b/packages/docs-drawing-ui/src/commands/commands/insert-doc-drawing.command.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { IAccessor, ICommand, IMutationInfo, JSONXActions } from '@univerjs/core';+import type { IAccessor, ICommand, IMutationInfo, ITextRangeParam, JSONXActions } from '@univerjs/core';import type { IRichTextEditingMutationParams } from '@univerjs/docs';import type { IInsertDrawingCommandParams } from './interfaces';import {@@ -27,7 +27,7 @@ import {TextXActionType,} from '@univerjs/core';import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';-import { getCustomBlockIdsInSelections, getRichTextEditPath } from '@univerjs/docs-ui';+import { DocContentInsertService, getCustomBlockIdsInSelections, getRichTextEditPath } from '@univerjs/docs-ui';/*** The command to insert new drawings@@ -48,13 +48,28 @@ export const InsertDocDrawingCommand: ICommand = {const activeTextRange = docSelectionManagerService.getActiveTextRange();const documentDataModel = univerInstanceService.getCurrentUniverDocInstance();- if (activeTextRange == null || documentDataModel == null) {+ if (documentDataModel == null) {return false;}const unitId = documentDataModel.getUnitId();+ const contentInsertRange = getContentInsertRange(accessor, unitId);+ const targetTextRange = contentInsertRange+ ? {+ ...activeTextRange,+ startOffset: contentInsertRange.startOffset,+ endOffset: contentInsertRange.endOffset,+ collapsed: contentInsertRange.startOffset === contentInsertRange.endOffset,+ segmentId: contentInsertRange.segmentId ?? activeTextRange?.segmentId ?? '',+ }+ : activeTextRange;++ if (targetTextRange == null) {+ return false;+ }+const { drawings } = params;- const { collapsed, startOffset, segmentId } = activeTextRange;+ const { collapsed, startOffset, segmentId = '' } = targetTextRange;const body = documentDataModel.getSelfOrHeaderFooterModel(segmentId).getBody();if (body == null) {@@ -76,10 +91,10 @@ export const InsertDocDrawingCommand: ICommand = {});}} else {- const dos = BuildTextUtils.selection.delete([activeTextRange], body, 0, null, false);+ const dos = BuildTextUtils.selection.delete([targetTextRange], body, 0, null, false);textX.push(...dos);- const removedCustomBlockIds = getCustomBlockIdsInSelections(body, [activeTextRange]);+ const removedCustomBlockIds = getCustomBlockIdsInSelections(body, [targetTextRange]);const drawings = documentDataModel.getDrawings() ?? {};const drawingOrder = documentDataModel.getDrawingsOrder() ?? [];const sortedRemovedCustomBlockIds = removedCustomBlockIds.sort((a, b) => {@@ -159,3 +174,21 @@ export const InsertDocDrawingCommand: ICommand = {return Boolean(result);},};++function getContentInsertRange(accessor: IAccessor, unitId: string): ITextRangeParam | null {+ try {+ const range = accessor.get(DocContentInsertService).consumeInsertRange(unitId);+ if (range == null) {+ return null;+ }++ return {+ startOffset: range.startOffset,+ endOffset: range.endOffset,+ collapsed: range.startOffset === range.endOffset,+ segmentId: range.segmentId,+ };+ } catch {+ return null;+ }+}diff --git a/packages/docs-drawing-ui/src/commands/commands/update-doc-drawing.command.ts b/packages/docs-drawing-ui/src/commands/commands/update-doc-drawing.command.tsindex 414c179a38..43e261c0fb 100644--- a/packages/docs-drawing-ui/src/commands/commands/update-doc-drawing.command.ts+++ b/packages/docs-drawing-ui/src/commands/commands/update-doc-drawing.command.ts@@ -17,6 +17,7 @@import type { DocumentDataModel, IAccessor, ICommand, IDocDrawingBase, IDocDrawingPosition, IMutationInfo, IObjectPositionH, IObjectPositionV, ISize, JSONXActions, WrapTextType } from '@univerjs/core';import type { IRichTextEditingMutationParams } from '@univerjs/docs';import type { IDocDrawing } from '@univerjs/docs-drawing';+import type { IDocumentSkeletonDrawing, IDocumentSkeletonHeaderFooter, IDocumentSkeletonPage } from '@univerjs/engine-render';import {BooleanNumber,CommandType,@@ -51,6 +52,41 @@ const WRAPPING_STYLE_TO_LAYOUT_TYPE = {[TextWrappingStyle.BEHIND_TEXT]: PositionedObjectLayoutType.WRAP_NONE,};+interface IDrawingAnchorInPage {+ skeDrawing: IDocumentSkeletonDrawing;+ pageMarginTop: number;+ pageMarginLeft: number;+}++export function findDrawingAnchorInPage(+ page: IDocumentSkeletonPage | IDocumentSkeletonHeaderFooter,+ drawingId: string,+ pageMarginTop: number,+ pageMarginLeft: number+): IDrawingAnchorInPage | null {+ const skeDrawing = page.skeDrawings.get(drawingId);+ if (skeDrawing) {+ return {+ skeDrawing,+ pageMarginTop,+ pageMarginLeft,+ };+ }++ for (const table of page.skeTables.values()) {+ for (const row of table.rows) {+ for (const cell of row.cells) {+ const cellAnchor = findDrawingAnchorInPage(cell, drawingId, cell.marginTop, cell.marginLeft);+ if (cellAnchor) {+ return cellAnchor;+ }+ }+ }+ }++ return null;+}+// eslint-disable-next-line max-lines-per-functionfunction getDeleteAndInsertCustomBlockActions(segmentId: string,@@ -280,9 +316,7 @@ export const UpdateDocDrawingWrappingStyleCommand: ICommand = {}// Update positionH and positionV if layoutType is not inline.- let skeDrawing = null;- let pageMarginTop = 0;- let pageMarginLeft = 0;+ let drawingAnchor: IDrawingAnchorInPage | null = null;for (const page of pages) {const { headerId, footerId, marginTop, marginLeft, marginBottom, pageWidth, pageHeight } = page;@@ -290,10 +324,8 @@ export const UpdateDocDrawingWrappingStyleCommand: ICommand = {case DocumentEditArea.HEADER: {const headerSke = skeHeaders.get(headerId)?.get(pageWidth);- if (headerSke != null && headerSke.skeDrawings.has(drawingId)) {- skeDrawing = headerSke.skeDrawings.get(drawingId);- pageMarginTop = headerSke.marginTop;- pageMarginLeft = marginLeft;+ if (headerSke != null) {+ drawingAnchor = findDrawingAnchorInPage(headerSke, drawingId, headerSke.marginTop, marginLeft);}break;@@ -301,30 +333,25 @@ export const UpdateDocDrawingWrappingStyleCommand: ICommand = {case DocumentEditArea.FOOTER: {const footerSke = skeFooters.get(footerId)?.get(pageWidth);- if (footerSke != null && footerSke.skeDrawings.has(drawingId)) {- skeDrawing = footerSke.skeDrawings.get(drawingId);- pageMarginTop = pageHeight - marginBottom + footerSke.marginTop;- pageMarginLeft = marginLeft;+ if (footerSke != null) {+ drawingAnchor = findDrawingAnchorInPage(footerSke, drawingId, pageHeight - marginBottom + footerSke.marginTop, marginLeft);}break;}case DocumentEditArea.BODY: {- if (page.skeDrawings.has(drawingId)) {- skeDrawing = page.skeDrawings.get(drawingId);- pageMarginTop = marginTop;- pageMarginLeft = marginLeft;- }+ drawingAnchor = findDrawingAnchorInPage(page, drawingId, marginTop, marginLeft);break;}}- if (skeDrawing != null) {+ if (drawingAnchor != null) {break;}}- if (skeDrawing != null) {+ if (drawingAnchor != null) {+ const { skeDrawing, pageMarginTop, pageMarginLeft } = drawingAnchor;const { aTop, aLeft } = skeDrawing;const oldPositionH = oldDrawings[drawingId].docTransform.positionH;let posOffsetH = aLeft;diff --git a/packages/docs-drawing-ui/src/controllers/doc-drawing-transformer-update.controller.ts b/packages/docs-drawing-ui/src/controllers/doc-drawing-transformer-update.controller.tsindex 03e051a28a..685d99afa4 100644--- a/packages/docs-drawing-ui/src/controllers/doc-drawing-transformer-update.controller.ts+++ b/packages/docs-drawing-ui/src/controllers/doc-drawing-transformer-update.controller.ts@@ -15,7 +15,7 @@*/import type { IDocDrawingBase, IDocDrawingPosition, Nullable } from '@univerjs/core';-import type { BaseObject, Documents, IDocumentSkeletonGlyph, IDocumentSkeletonPage, Image, INodeSearch, IPoint, Viewport } from '@univerjs/engine-render';+import type { BaseObject, Documents, IDocumentSkeletonGlyph, IDocumentSkeletonPage, IDocumentSkeletonRow, IDocumentSkeletonTable, Image, IPoint, Viewport } from '@univerjs/engine-render';import type { IDrawingDocTransform } from '../commands/commands/update-doc-drawing.command';import {BooleanNumber,@@ -36,6 +36,7 @@ import { DocSelectionRenderService, getAnchorBounding, getDocObject, getOneTextSimport { IDrawingManagerService } from '@univerjs/drawing';import { DocumentSkeletonPageType, getColor, IRenderManagerService, Liquid, PageLayoutType, Rect, Vector2 } from '@univerjs/engine-render';import { IMoveInlineDrawingCommand, ITransformNonInlineDrawingCommand, UpdateDrawingDocTransformCommand } from '../commands/commands/update-doc-drawing.command';+import { getDocsTableCellDrawingOffset } from './render-controllers/doc-drawing-transform-update.controller';const INLINE_DRAWING_ANCHOR_KEY_PREFIX = '__InlineDrawingAnchor__';@@ -56,10 +57,33 @@ interface IDrawingAnchor {contentBoxPointGroup?: IPoint[][];}-function isInTableCell(nodePosition: INodeSearch) {- const { path } = nodePosition;+export interface IDocsTableCellAnchorContext {+ cell: IDocumentSkeletonPage;+ hostPage: IDocumentSkeletonPage;+ offset: {+ left: number;+ top: number;+ };+ row: IDocumentSkeletonRow;+ table: IDocumentSkeletonTable;+}++export function getDocsTableCellAnchorContext(unitId: string, cell: IDocumentSkeletonPage): Nullable<IDocsTableCellAnchorContext> {+ const row = cell.parent as IDocumentSkeletonRow | undefined;+ const table = row?.parent as IDocumentSkeletonTable | undefined;+ const hostPage = table?.parent as IDocumentSkeletonPage | undefined;++ if (!row || !table || !hostPage || !row.cells?.includes(cell)) {+ return null;+ }- return path.some((p) => p === 'cells');+ return {+ cell,+ hostPage,+ offset: getDocsTableCellDrawingOffset(unitId, table, row, cell),+ row,+ table,+ };}// Listen doc drawing transformer change, and update drawing data.@@ -434,11 +458,6 @@ export class DocDrawingTransformerController extends Disposable {return;}- // TODO: @JOCS, table cell do not support drawings now. so need to disable it.- if (isInTableCell(nodePosition)) {- return;- }-const positionWithIsBack = {...nodePosition,isBack,@@ -534,7 +553,9 @@ export class DocDrawingTransformerController extends Disposable {this._liquid.reset();- const pageType = page.type;+ const tableCellContext = page.type === DocumentSkeletonPageType.CELL ? getDocsTableCellAnchorContext(drawing.unitId, page) : null;+ const anchorPage = tableCellContext?.hostPage ?? page;+ const pageType = anchorPage.type;for (const p of pages) {const { headerId, footerId, pageHeight, pageWidth, marginLeft, marginBottom } = p;@@ -571,13 +592,18 @@ export class DocDrawingTransformerController extends Disposable {break;}++ default: {+ this._liquid.translatePagePadding(p);+ break;+ }}break;}this._liquid.translatePagePadding(p);- if (p === page) {+ if (p === anchorPage) {break;}@@ -585,6 +611,10 @@ export class DocDrawingTransformerController extends Disposable {this._liquid.translatePage(p, pageLayoutType, pageMarginLeft, pageMarginTop);}+ if (tableCellContext) {+ this._liquid.translate(tableCellContext.offset.left, tableCellContext.offset.top);+ }+if (positionV.relativeFrom === ObjectRelativeFromV.LINE) {glyphAnchor = line.divides[0].glyphGroup[0];} else {@@ -637,11 +667,6 @@ export class DocDrawingTransformerController extends Disposable {return;}- // TODO: @JOCS, table cell do not support drawings now. so need to disable it.- if (isInTableCell(nodePosition)) {- return;- }-const positionWithIsBack = {...nodePosition,isBack,diff --git a/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-transform-update.controller.spec.ts b/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-transform-update.controller.spec.tsnew file mode 100644index 0000000000..be8d7bfa54--- /dev/null+++ b/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-transform-update.controller.spec.ts@@ -0,0 +1,101 @@+/**+ * 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 { setDocsTableRenderViewportProvider } from '@univerjs/engine-render';+import { afterEach, describe, expect, it } from 'vitest';+import { getDocsTableCellAnchorContext } from '../../doc-drawing-transformer-update.controller';+import { getDocsTableCellDrawingOffset } from '../doc-drawing-transform-update.controller';++describe('DocDrawingTransformUpdateController', () => {+ afterEach(() => {+ setDocsTableRenderViewportProvider(null);+ });++ it('projects drawings in table cells through table, row, cell and scroll offsets', () => {+ setDocsTableRenderViewportProvider((unitId, tableId) => {+ if (unitId !== 'unit-1' || tableId !== 'table-1') {+ return null;+ }++ return {+ contentWidth: 480,+ scrollLeft: 30,+ viewportWidth: 160,+ };+ });++ const table = {+ left: 40,+ tableId: 'table-1#-#0',+ top: 80,+ };+ const row = {+ top: 12,+ };+ const cell = {+ left: 120,+ marginLeft: 8,+ marginTop: 6,+ };++ expect(getDocsTableCellDrawingOffset('unit-1', table as never, row as never, cell as never)).toEqual({+ left: 138,+ top: 98,+ });+ });++ it('resolves a table cell drawing anchor to the host page and scrolled cell offset', () => {+ setDocsTableRenderViewportProvider((unitId, tableId) => {+ if (unitId !== 'unit-1' || tableId !== 'table-1') {+ return null;+ }++ return {+ contentWidth: 480,+ scrollLeft: 30,+ viewportWidth: 160,+ };+ });++ const hostPage = { type: 'body' };+ const cell = {+ left: 120,+ marginLeft: 8,+ marginTop: 6,+ };+ const row = {+ cells: [cell],+ top: 12,+ };+ const table = {+ left: 40,+ parent: hostPage,+ rows: [row],+ tableId: 'table-1#-#0',+ top: 80,+ };+ Object.assign(row, { parent: table });+ Object.assign(cell, { parent: row });++ expect(getDocsTableCellAnchorContext('unit-1', cell as never)).toMatchObject({+ hostPage,+ offset: {+ left: 138,+ top: 98,+ },+ });+ });+});diff --git a/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-transform-update.controller.ts b/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-transform-update.controller.tsindex f1e75dbae1..77dfa65cb2 100644--- a/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-transform-update.controller.ts+++ b/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-transform-update.controller.ts@@ -16,7 +16,7 @@import type { DocumentDataModel, ICommandInfo, IDrawingParam, ITransformState } from '@univerjs/core';import type { IRichTextEditingMutationParams } from '@univerjs/docs';-import type { Documents, DocumentSkeleton, IDocumentSkeletonHeaderFooter, IDocumentSkeletonPage, Image, IRenderContext, IRenderModule } from '@univerjs/engine-render';+import type { Documents, DocumentSkeleton, IDocumentSkeletonHeaderFooter, IDocumentSkeletonPage, IDocumentSkeletonRow, IDocumentSkeletonTable, Image, IRenderContext, IRenderModule } from '@univerjs/engine-render';import {BooleanNumber,Disposable,@@ -32,7 +32,7 @@ import {import { DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';import { IEditorService, SetDocZoomRatioOperation } from '@univerjs/docs-ui';import { IDrawingManagerService } from '@univerjs/drawing';-import { Liquid, TRANSFORM_CHANGE_OBSERVABLE_TYPE } from '@univerjs/engine-render';+import { getDocsTableRenderViewport, getTableIdAndSliceIndex, Liquid, TRANSFORM_CHANGE_OBSERVABLE_TYPE } from '@univerjs/engine-render';import { debounceTime, filter } from 'rxjs';import { DocRefreshDrawingsService } from '../../services/doc-refresh-drawings.service';@@ -48,6 +48,23 @@ interface IDrawingParamsWithBehindText {isMultiTransform: BooleanNumber;}+export function getDocsTableCellDrawingOffset(+ unitId: string,+ table: IDocumentSkeletonTable,+ row: IDocumentSkeletonRow,+ cell: IDocumentSkeletonPage+) {+ const sourceTableId = getTableIdAndSliceIndex(table.tableId).tableId;+ const viewport = getDocsTableRenderViewport(unitId, sourceTableId);+ const hasHorizontalViewport = viewport && viewport.contentWidth > viewport.viewportWidth;+ const scrollLeft = hasHorizontalViewport ? viewport.scrollLeft : 0;++ return {+ left: table.left + cell.left - scrollLeft + cell.marginLeft,+ top: table.top + row.top + cell.marginTop,+ };+}+export class DocDrawingTransformUpdateController extends Disposable implements IRenderModule {private _liquid = new Liquid();@@ -178,6 +195,15 @@ export class DocDrawingTransformUpdateController extends Disposable implements IheaderPage.marginTop,page.marginLeft);+ this._calculateTableCellDrawingPositions(+ unitId,+ headerPage,+ docsLeft,+ docsTop,+ updateDrawingMap,+ headerPage.marginTop,+ page.marginLeft+ );}}@@ -185,19 +211,30 @@ export class DocDrawingTransformUpdateController extends Disposable implements Iconst footerPage = skeFooters.get(footerId)?.get(pageWidth);if (footerPage) {+ const footerTop = page.pageHeight - page.marginBottom + footerPage.marginTop;this._calculateDrawingPosition(unitId,footerPage,docsLeft,docsTop,updateDrawingMap,- page.pageHeight - page.marginBottom + footerPage.marginTop,+ footerTop,+ page.marginLeft+ );+ this._calculateTableCellDrawingPositions(+ unitId,+ footerPage,+ docsLeft,+ docsTop,+ updateDrawingMap,+ footerTop,page.marginLeft);}}this._calculateDrawingPosition(unitId, page, docsLeft, docsTop, updateDrawingMap, page.marginTop, page.marginLeft);+ this._calculateTableCellDrawingPositions(unitId, page, docsLeft, docsTop, updateDrawingMap, page.marginTop, page.marginLeft);this._liquid.translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);}@@ -298,6 +335,45 @@ export class DocDrawingTransformUpdateController extends Disposable implements I} as IDocumentSkeletonPage);}+ private _calculateTableCellDrawingPositions(+ unitId: string,+ page: IDocumentSkeletonPage | IDocumentSkeletonHeaderFooter,+ docsLeft: number,+ docsTop: number,+ updateDrawingMap: Record<string, IDrawingParamsWithBehindText>,+ baseMarginTop: number,+ baseMarginLeft: number+ ) {+ page.skeTables?.forEach((table) => {+ table.rows.forEach((row) => {+ row.cells.forEach((cell) => {+ const cellOffset = getDocsTableCellDrawingOffset(unitId, table, row, cell);+ const marginTop = baseMarginTop + cellOffset.top;+ const marginLeft = baseMarginLeft + cellOffset.left;++ this._calculateDrawingPosition(+ unitId,+ cell,+ docsLeft,+ docsTop,+ updateDrawingMap,+ marginTop,+ marginLeft+ );+ this._calculateTableCellDrawingPositions(+ unitId,+ cell,+ docsLeft,+ docsTop,+ updateDrawingMap,+ marginTop,+ marginLeft+ );+ });+ });+ });+ }+private _drawingInitializeListener() {const init = () => {const skeleton = this._docSkeletonManagerService.getSkeleton();diff --git a/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-update.render-controller.ts b/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-update.render-controller.tsindex 5b213b905d..0078651b26 100644--- a/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-update.render-controller.ts+++ b/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-update.render-controller.ts@@ -36,6 +36,11 @@ import { SetDocDrawingArrangeCommand } from '../../commands/commands/set-drawingimport { UngroupDocDrawingCommand } from '../../commands/commands/ungroup-doc-drawing.command';import { DocRefreshDrawingsService } from '../../services/doc-refresh-drawings.service';+interface IImageInsertPosition {+ left: number;+ top: number;+}+export class DocDrawingUpdateRenderController extends Disposable implements IRenderModule {constructor(private readonly _context: IRenderContext<DocumentDataModel>,@@ -68,6 +73,7 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen}async insertDocImage(): Promise<boolean> {+ const insertPosition = this._getCurrentImageInsertPosition();const files = await this._fileOpenerService.openFile({multiple: true,accept: DRAWING_IMAGE_ALLOW_IMAGE_LIST.map((image) => `.${image.replace('image/', '')}`).join(','),@@ -84,12 +90,12 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRenreturn false;}- await this._insertFloatImages(files);+ await this._insertFloatImages(files, insertPosition);return true;}// eslint-disable-next-line max-lines-per-function- private async _insertFloatImages(files: File[]) {+ private async _insertFloatImages(files: File[], insertPosition: Nullable<IImageInsertPosition>) {let imageParams: Nullable<IImageIoServiceParam>[] = [];try {@@ -141,12 +147,18 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRenscale = Math.min(scaleWidth, scaleHeight);}- const docTransform = this._getImagePosition(width * scale, height * scale);+ const imagePosition = insertPosition ?? this._getCurrentImageInsertPosition();+ const docTransform = this._getImagePosition(width * scale, height * scale, imagePosition);if (docTransform == null) {return;}+ const transform = docDrawingPositionToTransform(docTransform);+ if (transform != null && imagePosition != null) {+ transform.top = imagePosition.top;+ }+const docDrawingParam: IDocDrawing = {unitId,subUnitId: unitId,@@ -154,7 +166,7 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRendrawingType: DrawingTypeEnum.DRAWING_IMAGE,imageSourceType,source,- transform: docDrawingPositionToTransform(docTransform),+ transform,docTransform,behindDoc: BooleanNumber.FALSE,title: '',@@ -196,11 +208,11 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRenprivate _getImagePosition(imageWidth: number,- imageHeight: number+ imageHeight: number,+ insertPosition?: Nullable<IImageInsertPosition>): Nullable<IDocDrawingPosition> {- const activeTextRange = this._docSelectionRenderService.getActiveTextRange();// TODO: NO need to get the cursor position, because the insert image is inline.- const position = activeTextRange?.getAbsolutePosition() || {+ const position = insertPosition ?? this._getCurrentImageInsertPosition() ?? {left: 0,top: 0,};@@ -222,6 +234,19 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen};}+ private _getCurrentImageInsertPosition(): Nullable<IImageInsertPosition> {+ const position = this._docSelectionRenderService.getActiveTextRange()?.getAbsolutePosition();++ if (position == null) {+ return null;+ }++ return {+ left: position.left,+ top: position.top,+ };+ }+private _updateOrderListener() {this.disposeWithMe(this._drawingManagerService.featurePluginOrderUpdate$.subscribe((params) => {diff --git a/packages/docs-drawing-ui/src/index.ts b/packages/docs-drawing-ui/src/index.tsindex de509e785c..489e6065b2 100644--- a/packages/docs-drawing-ui/src/index.ts+++ b/packages/docs-drawing-ui/src/index.ts@@ -31,3 +31,5 @@ export { type IUniverDocsDrawingUIConfig } from './config/config';export { DocFloatDomController } from './controllers/doc-float-dom.controller';export { DOCS_IMAGE_MENU_ID } from './menu/image.menu';export { UniverDocsDrawingUIPlugin } from './plugin';+export { DocDrawingPosition } from './views/doc-image-panel/DocDrawingPosition';+export { DocDrawingTextWrap } from './views/doc-image-panel/DocDrawingTextWrap';diff --git a/packages/docs-drawing-ui/src/menu/__tests__/schema.spec.ts b/packages/docs-drawing-ui/src/menu/__tests__/schema.spec.tsnew file mode 100644index 0000000000..906e5bf322--- /dev/null+++ b/packages/docs-drawing-ui/src/menu/__tests__/schema.spec.ts@@ -0,0 +1,38 @@+/**+ * 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 { DOC_CONTENT_INSERT_MENU_ID, EMPTY_PARAGRAPH_MENU_ID, INSERT_BELLOW_MENU_ID } from '@univerjs/docs-ui';+import { ContextMenuGroup, ContextMenuPosition } from '@univerjs/ui';+import { describe, expect, it } from 'vitest';+import { InsertDocImageCommand } from '../../commands/commands/insert-image.command';+import { UploadFloatImageMenuFactory } from '../image.menu';+import { menuSchema } from '../schema';++describe('docs drawing menu schema', () => {+ it('adds image to paragraph insert menus', () => {+ const paragraph = (menuSchema as any)[ContextMenuPosition.PARAGRAPH];++ expect(paragraph[ContextMenuGroup.LAYOUT][INSERT_BELLOW_MENU_ID][InsertDocImageCommand.id].menuItemFactory).toBeDefined();+ expect(paragraph[EMPTY_PARAGRAPH_MENU_ID][ContextMenuGroup.LAYOUT][InsertDocImageCommand.id].menuItemFactory).toBeDefined();+ expect(paragraph[DOC_CONTENT_INSERT_MENU_ID][ContextMenuGroup.LAYOUT][InsertDocImageCommand.id].menuItemFactory).toBeDefined();+ });++ it('uses the same image icon in paragraph insert menus', () => {+ const item = UploadFloatImageMenuFactory({ get: () => undefined } as never);++ expect(item.icon).toBe('AddImageIcon');+ });+});diff --git a/packages/docs-drawing-ui/src/menu/drawing-popup-menu.controller.ts b/packages/docs-drawing-ui/src/menu/drawing-popup-menu.controller.tsindex e2ec189311..18eaa0bebb 100644--- a/packages/docs-drawing-ui/src/menu/drawing-popup-menu.controller.ts+++ b/packages/docs-drawing-ui/src/menu/drawing-popup-menu.controller.ts@@ -16,7 +16,7 @@import type { DocumentDataModel, IDisposable, Nullable } from '@univerjs/core';import type { BaseObject, Scene } from '@univerjs/engine-render';-import { DrawingTypeEnum, FOCUSING_COMMON_DRAWINGS, IContextService, Inject, isInternalEditorID, IUniverInstanceService, RxDisposable, UniverInstanceType } from '@univerjs/core';+import { DrawingTypeEnum, FOCUSING_COMMON_DRAWINGS, ICommandService, IContextService, Inject, isInternalEditorID, IUniverInstanceService, RxDisposable, UniverInstanceType } from '@univerjs/core';import { DocCanvasPopManagerService } from '@univerjs/docs-ui';import { IDrawingManagerService } from '@univerjs/drawing';import { COMPONENT_IMAGE_POPUP_MENU, ImageCropperObject, ImageResetSizeOperation, OpenImageCropOperation } from '@univerjs/drawing-ui';@@ -24,17 +24,20 @@ import { IRenderManagerService } from '@univerjs/engine-render';import { takeUntil } from 'rxjs';import { RemoveDocDrawingCommand } from '../commands/commands/remove-doc-drawing.command';import { EditDocDrawingOperation } from '../commands/operations/edit-doc-drawing.operation';+import { SidebarDocDrawingOperation } from '../commands/operations/open-drawing-panel.operation';export class DocDrawingPopupMenuController extends RxDisposable {private _initImagePopupMenu = new Set<string>();private _disposePopups: IDisposable[] = [];+ private _isDrawingPanelOpen = false;constructor(@IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,@Inject(DocCanvasPopManagerService) private readonly _canvasPopManagerService: DocCanvasPopManagerService,@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,- @IContextService private readonly _contextService: IContextService+ @IContextService private readonly _contextService: IContextService,+ @ICommandService private readonly _commandService: ICommandService) {super();@@ -43,6 +46,29 @@ export class DocDrawingPopupMenuController extends RxDisposable {}private _init(): void {+ this.disposeWithMe(+ this._commandService.onCommandExecuted((command) => {+ if (command.id === EditDocDrawingOperation.id) {+ this._isDrawingPanelOpen = true;+ this._clearPopups();+ }+ if (command.id === SidebarDocDrawingOperation.id) {+ const params = command.params as { value?: string } | undefined;+ this._isDrawingPanelOpen = params?.value === 'open';+ if (this._isDrawingPanelOpen) {+ this._clearPopups();+ }+ }+ })+ );+ this.disposeWithMe(+ this._drawingManagerService.focus$.subscribe((params) => {+ if (params.length === 0) {+ this._isDrawingPanelOpen = false;+ }+ })+ );+this.disposeWithMe(this._univerInstanceService.getCurrentTypeOfUnit$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC).pipe(takeUntil(this.dispose$)).subscribe((documentDataModel) => this._create(documentDataModel)));@@ -56,13 +82,15 @@ export class DocDrawingPopupMenuController extends RxDisposable {private _dispose(documentDataModel: DocumentDataModel) {const unitId = documentDataModel.getUnitId();- if (this._disposePopups.length) {- this._disposePopups.forEach((dispose) => dispose.dispose());- this._disposePopups.length = 0;- }+ this._clearPopups();this._renderManagerService.removeRender(unitId);}+ private _clearPopups() {+ this._disposePopups.forEach((dispose) => dispose.dispose());+ this._disposePopups.length = 0;+ }+private _create(documentDataModel: Nullable<DocumentDataModel>) {if (!documentDataModel) {return;@@ -112,6 +140,9 @@ export class DocDrawingPopupMenuController extends RxDisposable {const selectedObjects = transformer.getSelectedObjectMap();disposePopups.forEach((dispose) => dispose.dispose());disposePopups.length = 0;+ if (this._isDrawingPanelOpen) {+ return;+ }if (selectedObjects.size > 1) {return;}@@ -123,19 +154,28 @@ export class DocDrawingPopupMenuController extends RxDisposable {const oKey = object.oKey;const drawingParam = this._drawingManagerService.getDrawingOKey(oKey);- if (!drawingParam || drawingParam.drawingType === DrawingTypeEnum.DRAWING_DOM) {+ if (+ !drawingParam ||+ drawingParam.drawingType === DrawingTypeEnum.DRAWING_DOM ||+ drawingParam.drawingType === DrawingTypeEnum.DRAWING_SHAPE+ ) {return;}const { unitId, subUnitId, drawingId, drawingType } = drawingParam;+ const isImage = drawingType === DrawingTypeEnum.DRAWING_IMAGE;const popup = this._canvasPopManagerService.attachPopupToObject(object,{componentKey: COMPONENT_IMAGE_POPUP_MENU,- direction: 'horizontal',- offset: [2, 0],+ direction: isImage ? 'top-center' : 'horizontal',+ offset: isImage ? [0, 8] : [2, 0],extraProps: {menuItems: this._getImageMenuItems(unitId, subUnitId, drawingId, drawingType),+ variant: isImage ? 'doc-floating-toolbar' : undefined,+ unitId,+ subUnitId,+ drawingId,},},unitId@@ -191,8 +231,7 @@ export class DocDrawingPopupMenuController extends RxDisposable {index: 0,commandId: EditDocDrawingOperation.id,commandParams: { unitId, subUnitId, drawingId },- // disable: !!SHEET_EDITOR_UNITS.includes(unitId) || drawingType === DrawingTypeEnum.DRAWING_DOM,- disable: true,+ disable: drawingType === DrawingTypeEnum.DRAWING_DOM,},{label: 'docs-drawing-ui.image-popup.delete',@@ -206,7 +245,7 @@ export class DocDrawingPopupMenuController extends RxDisposable {index: 2,commandId: OpenImageCropOperation.id,commandParams: { unitId, subUnitId, drawingId },- disable: true, // TODO: @JOCS, feature is not ready.+ disable: drawingType === DrawingTypeEnum.DRAWING_DOM,},{label: 'docs-drawing-ui.image-popup.reset',diff --git a/packages/docs-drawing-ui/src/menu/image.menu.ts b/packages/docs-drawing-ui/src/menu/image.menu.tsindex 7fb04c4947..f82ed8f8a4 100644--- a/packages/docs-drawing-ui/src/menu/image.menu.ts+++ b/packages/docs-drawing-ui/src/menu/image.menu.ts@@ -77,6 +77,7 @@ export function UploadFloatImageMenuFactory(_accessor: IAccessor): IMenuItem {id: IMAGE_MENU_UPLOAD_FLOAT_ID,title: 'docs-drawing-ui.upload.float',type: MenuItemType.BUTTON,+ icon: 'AddImageIcon',hidden$: getMenuHiddenObservable(_accessor, UniverInstanceType.UNIVER_DOC, undefined, DOCS_ZEN_EDITOR_UNIT_ID_KEY),};}diff --git a/packages/docs-drawing-ui/src/menu/schema.ts b/packages/docs-drawing-ui/src/menu/schema.tsindex 1db0639ac6..9b2a96fee8 100644--- a/packages/docs-drawing-ui/src/menu/schema.ts+++ b/packages/docs-drawing-ui/src/menu/schema.ts@@ -15,7 +15,8 @@*/import type { MenuSchemaType } from '@univerjs/ui';-import { RibbonInsertGroup } from '@univerjs/ui';+import { DOC_CONTENT_INSERT_MENU_ID, EMPTY_PARAGRAPH_MENU_ID, INSERT_BELLOW_MENU_ID } from '@univerjs/docs-ui';+import { ContextMenuGroup, ContextMenuPosition, RibbonInsertGroup } from '@univerjs/ui';import {DOCS_IMAGE_MENU_ID,IMAGE_MENU_UPLOAD_FLOAT_ID,@@ -34,4 +35,30 @@ export const menuSchema: MenuSchemaType = {},},},+ [ContextMenuPosition.PARAGRAPH]: {+ [ContextMenuGroup.LAYOUT]: {+ [INSERT_BELLOW_MENU_ID]: {+ [IMAGE_MENU_UPLOAD_FLOAT_ID]: {+ order: 5,+ menuItemFactory: UploadFloatImageMenuFactory,+ },+ },+ },+ [EMPTY_PARAGRAPH_MENU_ID]: {+ [ContextMenuGroup.LAYOUT]: {+ [IMAGE_MENU_UPLOAD_FLOAT_ID]: {+ order: 5,+ menuItemFactory: UploadFloatImageMenuFactory,+ },+ },+ },+ [DOC_CONTENT_INSERT_MENU_ID]: {+ [ContextMenuGroup.LAYOUT]: {+ [IMAGE_MENU_UPLOAD_FLOAT_ID]: {+ order: 5,+ menuItemFactory: UploadFloatImageMenuFactory,+ },+ },+ },+ },};diff --git a/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingPanel.tsx b/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingPanel.tsxindex 1286126eef..c25126cfd9 100644--- a/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingPanel.tsx+++ b/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingPanel.tsx@@ -40,7 +40,7 @@ export const DocDrawingPanel = () => {return !!drawings?.length && (<div className="univer-text-sm">- <DrawingCommonPanel drawings={drawings} hasAlign={false} hasCropper={false} hasGroup={false} hasTransform={false} />+ <DrawingCommonPanel drawings={drawings} hasAlign={false} hasCropper hasGroup={false} hasTransform={false} /><DocDrawingTextWrap drawings={drawings} /><DocDrawingPosition drawings={drawings} /></div>diff --git a/packages/docs-hyper-link-ui/src/controllers/render-controllers/__tests__/hyper-link-event.render-controller.spec.ts b/packages/docs-hyper-link-ui/src/controllers/render-controllers/__tests__/hyper-link-event.render-controller.spec.tsnew file mode 100644index 0000000000..3391d55876--- /dev/null+++ b/packages/docs-hyper-link-ui/src/controllers/render-controllers/__tests__/hyper-link-event.render-controller.spec.ts@@ -0,0 +1,53 @@+/**+ * 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 { config, Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { DocHyperLinkEventRenderController } from '../hyper-link-event.render-controller';++describe('DocHyperLinkEventRenderController', () => {+ it('ignores hover ranges when the current selection has no text ranges', async () => {+ const hoverCustomRanges$ = new Subject<unknown[]>();+ const clickCustomRanges$ = new Subject<unknown>();+ const onUnhandledError = vi.fn();+ const previousUnhandledError = config.onUnhandledError;+ const commandService = {+ executeCommand: vi.fn(),+ };+ config.onUnhandledError = onUnhandledError;++ try {+ const controller = new DocHyperLinkEventRenderController(+ { unitId: 'doc-unit' } as never,+ { hoverCustomRanges$, clickCustomRanges$ } as never,+ commandService as never,+ { showing: false } as never,+ { getSkeleton: vi.fn() } as never,+ { getTextRanges: () => [] } as never+ );++ hoverCustomRanges$.next([]);+ await new Promise((resolve) => setTimeout(resolve, 0));++ expect(onUnhandledError).not.toHaveBeenCalled();+ expect(commandService.executeCommand).not.toHaveBeenCalled();++ controller.dispose();+ } finally {+ config.onUnhandledError = previousUnhandledError;+ }+ });+});diff --git a/packages/docs-hyper-link-ui/src/controllers/render-controllers/hyper-link-event.render-controller.ts b/packages/docs-hyper-link-ui/src/controllers/render-controllers/hyper-link-event.render-controller.tsindex 03ce4dcea2..1c5730f81a 100644--- a/packages/docs-hyper-link-ui/src/controllers/render-controllers/hyper-link-event.render-controller.ts+++ b/packages/docs-hyper-link-ui/src/controllers/render-controllers/hyper-link-event.render-controller.ts@@ -58,7 +58,7 @@ export class DocHyperLinkEventRenderController extends Disposable implements IRethis._docEventManagerService.hoverCustomRanges$.subscribe((ranges) => {const link = ranges.find((range) => range.range.rangeType === CustomRangeType.HYPERLINK);const activeRanges = this._docSelectionManagerService.getTextRanges();- const currentSegmentId = activeRanges?.[0].segmentId;+ const currentSegmentId = activeRanges?.[0]?.segmentId;if ((link?.segmentId ?? '') !== currentSegmentId) {this._hideInfoPopup();return;diff --git a/packages/docs-hyper-link-ui/src/menu/__tests__/schema.spec.ts b/packages/docs-hyper-link-ui/src/menu/__tests__/schema.spec.tsnew file mode 100644index 0000000000..c24c5b54fd--- /dev/null+++ b/packages/docs-hyper-link-ui/src/menu/__tests__/schema.spec.ts@@ -0,0 +1,30 @@+/**+ * 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 { EMPTY_PARAGRAPH_MENU_ID, INSERT_BELLOW_MENU_ID } from '@univerjs/docs-ui';+import { ContextMenuGroup, ContextMenuPosition } from '@univerjs/ui';+import { describe, expect, it } from 'vitest';+import { ShowDocHyperLinkEditPopupOperation } from '../../commands/operations/popup.operation';+import { menuSchema } from '../schema';++describe('docs hyperlink menu schema', () => {+ it('adds hyperlink to paragraph insert menus', () => {+ const paragraph = (menuSchema as any)[ContextMenuPosition.PARAGRAPH];++ expect(paragraph[ContextMenuGroup.LAYOUT][INSERT_BELLOW_MENU_ID][ShowDocHyperLinkEditPopupOperation.id].menuItemFactory).toBeDefined();+ expect(paragraph[EMPTY_PARAGRAPH_MENU_ID][ContextMenuGroup.LAYOUT][ShowDocHyperLinkEditPopupOperation.id].menuItemFactory).toBeDefined();+ });+});diff --git a/packages/docs-hyper-link-ui/src/menu/schema.ts b/packages/docs-hyper-link-ui/src/menu/schema.tsindex 3091de80ab..dc3656ae3e 100644--- a/packages/docs-hyper-link-ui/src/menu/schema.ts+++ b/packages/docs-hyper-link-ui/src/menu/schema.ts@@ -15,6 +15,7 @@*/import type { MenuSchemaType } from '@univerjs/ui';+import { EMPTY_PARAGRAPH_MENU_ID, INSERT_BELLOW_MENU_ID } from '@univerjs/docs-ui';import { ContextMenuGroup, ContextMenuPosition, RibbonInsertGroup } from '@univerjs/ui';import { ShowDocHyperLinkEditPopupOperation } from '../commands/operations/popup.operation';import { AddHyperLinkMenuItemFactory } from './menu';@@ -34,4 +35,22 @@ export const menuSchema: MenuSchemaType = {},},},+ [ContextMenuPosition.PARAGRAPH]: {+ [ContextMenuGroup.LAYOUT]: {+ [INSERT_BELLOW_MENU_ID]: {+ [ShowDocHyperLinkEditPopupOperation.id]: {+ order: 6,+ menuItemFactory: AddHyperLinkMenuItemFactory,+ },+ },+ },+ [EMPTY_PARAGRAPH_MENU_ID]: {+ [ContextMenuGroup.LAYOUT]: {+ [ShowDocHyperLinkEditPopupOperation.id]: {+ order: 6,+ menuItemFactory: AddHyperLinkMenuItemFactory,+ },+ },+ },+ },};diff --git a/packages/docs-quick-insert-ui/src/services/doc-quick-insert-popup.service.ts b/packages/docs-quick-insert-ui/src/services/doc-quick-insert-popup.service.tsindex d6c4ceaf95..ee5bcbd12d 100644--- a/packages/docs-quick-insert-ui/src/services/doc-quick-insert-popup.service.ts+++ b/packages/docs-quick-insert-ui/src/services/doc-quick-insert-popup.service.ts@@ -54,7 +54,7 @@ const noopDisposable = {dispose: () => {},};-interface IKeywordInputPlaceholderExtraProps {+interface IKeywordInputPlaceholderExtraProps extends Record<string, unknown> {fontSize?: number;fontString?: string;fontFamily?: string;diff --git a/packages/docs-ui/src/commands/commands/__tests__/core-editing.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/core-editing.command.spec.tsindex 4b13236343..56c07dd2c2 100644--- a/packages/docs-ui/src/commands/commands/__tests__/core-editing.command.spec.ts+++ b/packages/docs-ui/src/commands/commands/__tests__/core-editing.command.spec.ts@@ -19,15 +19,18 @@ import {awaitTime,BooleanNumber,CustomRangeType,+ DataStreamTreeTokenType,+ HorizontalAlign,ICommandService,IUniverInstanceService,UniverInstanceType,UpdateDocsAttributeType,} from '@univerjs/core';-import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { DocSelectionManagerService, DocSkeletonManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { DeleteDirection } from '../../../types/delete-direction';import { DeleteCommand, InsertCommand, UpdateCommand } from '../core-editing.command';+import { DeleteLeftCommand, DeleteRightCommand, isDeleteOffsetInsideBlockRange } from '../doc-delete.command';import { createCommandTestBed } from './create-command-test-bed';function getDocumentData(): IDocumentData {@@ -63,6 +66,108 @@ function getDocumentData(): IDocumentData {};}+function getCenteredSingleCharacterDocumentData(): IDocumentData {+ return {+ id: 'test-doc',+ body: {+ dataStream: 'A\r\n',+ textRuns: [{+ st: 0,+ ed: 1,+ ts: {},+ }],+ paragraphs: [{+ startIndex: 1,+ paragraphStyle: {+ horizontalAlign: HorizontalAlign.CENTER,+ },+ }],+ },+ documentStyle: {+ pageSize: {+ width: 594.3,+ height: 840.51,+ },+ marginTop: 72,+ marginBottom: 72,+ marginRight: 90,+ marginLeft: 90,+ },+ };+}++function getCenteredEmptyParagraphDocumentData(): IDocumentData {+ return {+ id: 'test-doc',+ body: {+ dataStream: '\r\n',+ paragraphs: [{+ startIndex: 0,+ paragraphStyle: {+ horizontalAlign: HorizontalAlign.CENTER,+ },+ }],+ },+ documentStyle: {+ pageSize: {+ width: 594.3,+ height: 840.51,+ },+ marginTop: 72,+ marginBottom: 72,+ marginRight: 90,+ marginLeft: 90,+ },+ };+}++function getIndentedBlockRangeDocumentData(): IDocumentData {+ return {+ id: 'test-doc',+ body: {+ dataStream: `${DataStreamTreeTokenType.BLOCK_START}A${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.BLOCK_END}\n`,+ paragraphs: [{+ startIndex: 2,+ paragraphStyle: {+ indentStart: { v: 22 },+ },+ }],+ blockRanges: [{+ blockId: 'quote-1',+ blockType: 'quote',+ startIndex: 0,+ endIndex: 3,+ }],+ },+ documentStyle: {+ pageSize: {+ width: 594.3,+ height: 840.51,+ },+ marginTop: 72,+ marginBottom: 72,+ marginRight: 90,+ marginLeft: 90,+ },+ };+}++function createFirstGlyph(paragraphIndex: number, content: string) {+ const line = { paragraphIndex, divides: [] as any[] };+ const divide = { parent: line, glyphGroup: [] as any[] };+ const glyph = {+ parent: divide,+ content,+ streamType: content,+ count: 1,+ };++ divide.glyphGroup.push(glyph);+ line.divides.push(divide);++ return glyph;+}+describe('core editing commands', () => {let univer: Univer;let get: Injector['get'];@@ -87,6 +192,28 @@ describe('core editing commands', () => {}}+ function setActiveSelection(offset: number) {+ const selectionManager = get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ });+ selectionManager.__TEST_ONLY_add([{ startOffset: offset, endOffset: offset, collapsed: true, isActive: true, segmentId: '', style: null as never }]);+ }++ function mockSkeleton() {+ const skeletonManager = get(DocSkeletonManagerService) as unknown as { getSkeleton: () => unknown };+ skeletonManager.getSkeleton = () => ({});+ }++ function registerDeleteKeyCommands() {+ commandService.registerCommand(DeleteLeftCommand);+ commandService.registerCommand(DeleteRightCommand);+ commandService.registerCommand(UpdateCommand);+ commandService.registerCommand(SetTextSelectionsOperation);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);+ }+beforeEach(() => {const testBed = createCommandTestBed(getDocumentData());univer = testBed.univer;@@ -140,6 +267,156 @@ describe('core editing commands', () => {expect(getBody()?.customRanges).toEqual([]);});+ it('keeps center alignment when deleting the last character from a centered paragraph', async () => {+ univer.dispose();+ const testBed = createCommandTestBed(getCenteredSingleCharacterDocumentData());+ univer = testBed.univer;+ get = testBed.get;+ commandService = get(ICommandService);+ commandService.registerCommand(DeleteCommand);+ commandService.registerCommand(SetTextSelectionsOperation);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);++ await commandService.executeCommand(DeleteCommand.id, {+ unitId: 'test-doc',+ segmentId: '',+ range: { startOffset: 0, endOffset: 0, collapsed: true },+ direction: DeleteDirection.RIGHT,+ });++ await awaitTime(0);++ expect(getDataStream()).toBe('\r\n');+ expect(getBody()?.paragraphs?.[0].paragraphStyle?.horizontalAlign).toBe(HorizontalAlign.CENTER);+ });++ it('keeps center alignment when backspacing the last character from a centered paragraph', async () => {+ univer.dispose();+ const testBed = createCommandTestBed(getCenteredSingleCharacterDocumentData());+ univer = testBed.univer;+ get = testBed.get;+ commandService = get(ICommandService);+ commandService.registerCommand(DeleteCommand);+ commandService.registerCommand(SetTextSelectionsOperation);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);++ await commandService.executeCommand(DeleteCommand.id, {+ unitId: 'test-doc',+ segmentId: '',+ range: { startOffset: 1, endOffset: 1, collapsed: true },+ direction: DeleteDirection.LEFT,+ });++ await awaitTime(0);++ expect(getDataStream()).toBe('\r\n');+ expect(getBody()?.paragraphs?.[0].paragraphStyle?.horizontalAlign).toBe(HorizontalAlign.CENTER);+ });++ it('resets an empty centered paragraph to left alignment on a second delete', async () => {+ univer.dispose();+ const testBed = createCommandTestBed(getCenteredEmptyParagraphDocumentData());+ univer = testBed.univer;+ get = testBed.get;+ commandService = get(ICommandService);+ registerDeleteKeyCommands();+ mockSkeleton();+ setActiveSelection(0);++ await commandService.executeCommand(DeleteRightCommand.id);++ await awaitTime(0);++ expect(getDataStream()).toBe('\r\n');+ expect(getBody()?.paragraphs?.[0].paragraphStyle?.horizontalAlign).toBe(HorizontalAlign.LEFT);+ });++ it('resets an empty centered paragraph to left alignment on a second backspace', async () => {+ univer.dispose();+ const testBed = createCommandTestBed(getCenteredEmptyParagraphDocumentData());+ univer = testBed.univer;+ get = testBed.get;+ commandService = get(ICommandService);+ registerDeleteKeyCommands();+ mockSkeleton();+ setActiveSelection(0);++ await commandService.executeCommand(DeleteLeftCommand.id);++ await awaitTime(0);++ expect(getDataStream()).toBe('\r\n');+ expect(getBody()?.paragraphs?.[0].paragraphStyle?.horizontalAlign).toBe(HorizontalAlign.LEFT);+ });++ it('detects delete offsets inside block ranges so backspace does not clear block paragraph indent', () => {+ const dataStream = `${DataStreamTreeTokenType.BLOCK_START}A${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.BLOCK_END}\n`;+ const body = {+ dataStream,+ blockRanges: [{+ blockId: 'block-1',+ blockType: 'quote',+ startIndex: 0,+ endIndex: 3,+ }],+ };++ expect(isDeleteOffsetInsideBlockRange(body, 1)).toBe(true);+ expect(isDeleteOffsetInsideBlockRange(body, 2)).toBe(true);+ expect(isDeleteOffsetInsideBlockRange(body, 0)).toBe(false);+ expect(isDeleteOffsetInsideBlockRange(body, 3)).toBe(false);+ });++ it('detects block ranges whose endIndex points before the block end token', () => {+ const dataStream = `${DataStreamTreeTokenType.BLOCK_START}A${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.BLOCK_END}\n`;+ const body = {+ dataStream,+ blockRanges: [{+ blockId: 'block-1',+ blockType: 'callout',+ startIndex: 0,+ endIndex: 2,+ }],+ };++ expect(isDeleteOffsetInsideBlockRange(body, 1)).toBe(true);+ expect(isDeleteOffsetInsideBlockRange(body, 2)).toBe(true);+ expect(isDeleteOffsetInsideBlockRange(body, 3)).toBe(false);+ });++ it('does not clear paragraph indent when backspacing at the start of a block range paragraph', async () => {+ univer.dispose();+ const testBed = createCommandTestBed(getIndentedBlockRangeDocumentData());+ univer = testBed.univer;+ get = testBed.get;+ commandService = get(ICommandService);+ registerDeleteKeyCommands();+ setActiveSelection(1);++ const curGlyph = createFirstGlyph(2, 'A');+ const preGlyph = createFirstGlyph(2, DataStreamTreeTokenType.BLOCK_START);+ const skeletonManager = get(DocSkeletonManagerService) as unknown as { getSkeleton: () => unknown };+ skeletonManager.getSkeleton = () => ({+ findNodeByCharIndex: (offset: number) => offset === 1 ? curGlyph : preGlyph,+ });++ const originalExecuteCommand = commandService.executeCommand.bind(commandService);+ const executeSpy = vi.spyOn(commandService, 'executeCommand').mockImplementation(async (id: string, params?: object) => {+ if (id === DeleteLeftCommand.id) {+ return originalExecuteCommand(id, params);+ }++ return true;+ });++ await commandService.executeCommand(DeleteLeftCommand.id);++ expect(executeSpy).not.toHaveBeenCalledWith(UpdateCommand.id, expect.anything());+ expect(executeSpy).toHaveBeenCalledWith(DeleteCommand.id, expect.objectContaining({+ direction: DeleteDirection.LEFT,+ }));+ });+it('updates text styles through the shared rich text mutation flow', async () => {await commandService.executeCommand(UpdateCommand.id, {unitId: 'test-doc',diff --git a/packages/docs-ui/src/commands/commands/__tests__/doc-block-move.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/doc-block-move.command.spec.tsnew file mode 100644index 0000000000..a164d21e03--- /dev/null+++ b/packages/docs-ui/src/commands/commands/__tests__/doc-block-move.command.spec.ts@@ -0,0 +1,117 @@+/**+ * 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 { IDocumentData } from '@univerjs/core';+import { BlockType, CustomRangeType } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { buildMoveDocBlockActions } from '../doc-block-move.command';++describe('buildMoveDocBlockActions', () => {+ it('moves a paragraph and remaps paragraph indexes', () => {+ const documentData = createDocument('A\rB\rC\r\n', {+ paragraphs: [{ startIndex: 1 }, { startIndex: 3 }, { startIndex: 5 }],+ sectionBreaks: [{ startIndex: 6 }],+ });++ const { nextDocumentData, movedRange } = buildMoveDocBlockActions({+ documentData,+ sourceRange: { startOffset: 0, endOffset: 2 },+ targetOffset: 6,+ });++ expect(nextDocumentData.body?.dataStream).toBe('B\rC\rA\r\n');+ expect(nextDocumentData.body?.paragraphs?.map((item) => item.startIndex)).toEqual([1, 3, 5]);+ expect(movedRange).toEqual({ startOffset: 4, endOffset: 6 });+ });++ it('moves a block range as one unit', () => {+ const documentData = createDocument('aa\rBB\rcc\r\n', {+ paragraphs: [{ startIndex: 2 }, { startIndex: 5 }, { startIndex: 8 }],+ sectionBreaks: [{ startIndex: 9 }],+ blockRanges: [{ blockId: 'quote-1', blockType: 'quote', startIndex: 3, endIndex: 5 }],+ });++ const { nextDocumentData, movedRange } = buildMoveDocBlockActions({+ documentData,+ sourceRange: { startOffset: 3, endOffset: 6 },+ targetOffset: 0,+ });++ expect(nextDocumentData.body?.dataStream).toBe('BB\raa\rcc\r\n');+ expect(nextDocumentData.body?.blockRanges?.[0]).toMatchObject({ startIndex: 0, endIndex: 2 });+ expect(nextDocumentData.body?.paragraphs?.map((item) => item.startIndex)).toEqual([2, 5, 8]);+ expect(movedRange).toEqual({ startOffset: 0, endOffset: 3 });+ });++ it('moves a table range and remaps custom ranges and text runs', () => {+ const documentData = createDocument('aa\rTT\rcc\r\n', {+ paragraphs: [{ startIndex: 2 }, { startIndex: 5 }, { startIndex: 8 }],+ sectionBreaks: [{ startIndex: 9 }],+ tables: [{ tableId: 'table-1', startIndex: 3, endIndex: 6 }],+ customRanges: [{ rangeId: 'comment-1', rangeType: CustomRangeType.COMMENT, startIndex: 6, endIndex: 7 }],+ textRuns: [{ st: 6, ed: 8, ts: {} }],+ });++ const { nextDocumentData } = buildMoveDocBlockActions({+ documentData,+ sourceRange: { startOffset: 3, endOffset: 6 },+ targetOffset: 0,+ });++ expect(nextDocumentData.body?.dataStream).toBe('TT\raa\rcc\r\n');+ expect(nextDocumentData.body?.tables?.[0]).toMatchObject({ startIndex: 0, endIndex: 3 });+ expect(nextDocumentData.body?.customRanges?.[0]).toMatchObject({ startIndex: 6, endIndex: 7 });+ expect(nextDocumentData.body?.textRuns?.[0]).toMatchObject({ st: 6, ed: 8 });+ });++ it('moves a custom block paragraph and keeps the custom block attached', () => {+ const documentData = createDocument('\b\raa\r\n', {+ paragraphs: [{ startIndex: 1 }, { startIndex: 4 }],+ sectionBreaks: [{ startIndex: 5 }],+ customBlocks: [{ blockId: 'custom-1', blockType: BlockType.CUSTOM, startIndex: 0 }],+ });++ const { nextDocumentData } = buildMoveDocBlockActions({+ documentData,+ sourceRange: { startOffset: 0, endOffset: 2 },+ targetOffset: 5,+ });++ expect(nextDocumentData.body?.dataStream).toBe('aa\r\b\r\n');+ expect(nextDocumentData.body?.customBlocks?.[0]).toMatchObject({ startIndex: 3 });+ });+});++function createDocument(dataStream: string, body: Partial<NonNullable<IDocumentData['body']>>): IDocumentData {+ return {+ id: 'test-doc',+ body: {+ dataStream,+ customBlocks: [],+ ...body,+ },+ documentStyle: {+ pageSize: {+ width: 594.3,+ height: 840.51,+ },+ marginTop: 72,+ marginBottom: 72,+ marginLeft: 72,+ marginRight: 72,+ },+ };+}diff --git a/packages/docs-ui/src/commands/commands/__tests__/inline-format.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/inline-format.command.spec.tsindex d9db328ee6..b11079d6c9 100644--- a/packages/docs-ui/src/commands/commands/__tests__/inline-format.command.spec.ts+++ b/packages/docs-ui/src/commands/commands/__tests__/inline-format.command.spec.ts@@ -15,7 +15,7 @@*/import type { DocumentDataModel, ICommand, Injector, IStyleBase, Univer } from '@univerjs/core';-import { BooleanNumber, ICommandService, IUniverInstanceService, RedoCommand, UndoCommand, UniverInstanceType } from '@univerjs/core';+import { BooleanNumber, DOC_RANGE_TYPE, ICommandService, IUniverInstanceService, RedoCommand, UndoCommand, UniverInstanceType } from '@univerjs/core';import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import {@@ -116,6 +116,51 @@ describe('Test inline format commands', () => {expect(getFormatValueAt('bl', 21)).toBe(BooleanNumber.TRUE);expect(getFormatValueAt('bl', 25)).toBe(BooleanNumber.TRUE);});++ it('formats text ranges without applying stale table rect ranges', async () => {+ const selectionManager = get(DocSelectionManagerService);+ selectionManager.__replaceTextRangesWithNoRefresh({+ textRanges: [{+ startOffset: 0,+ endOffset: 5,+ collapsed: false,+ isActive: true,+ rangeType: DOC_RANGE_TYPE.TEXT,+ }],+ rectRanges: [{+ startOffset: 20,+ endOffset: 30,+ collapsed: false,+ rangeType: DOC_RANGE_TYPE.RECT,+ tableId: 'table-1',+ startRow: 0,+ endRow: 0,+ startColumn: 0,+ endColumn: 0,+ }],+ segmentId: '',+ segmentPage: -1,+ isEditing: true,+ style: {},+ } as never, {+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ });++ expect(getFormatValueAt('ff', 1)).toBe(undefined);+ expect(getFormatValueAt('ff', 21)).toBe(undefined);++ await commandService.executeCommand(SetInlineFormatCommand.id, {+ segmentId: '',+ preCommandId: SetInlineFormatFontFamilyCommand.id,+ value: 'Arial',+ });++ expect(getFormatValueAt('ff', 1)).toBe('Arial');+ expect(getFormatValueAt('ff', 21)).toBe(undefined);++ await commandService.executeCommand(UndoCommand.id);+ });});describe('Set Italic by SetInlineFormatCommand', () => {diff --git a/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.tsindex d987aac803..c103503482 100644--- a/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts+++ b/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts@@ -163,6 +163,61 @@ function createTableDoc(): IDocumentData {};}+function createTableDocWithParagraphsBeforeTable(): IDocumentData {+ const table = genEmptyTable(2, 2);+ const prefix = 'Title\rBody\r';+ const suffix = 'Tail\r\n';+ const dataStream = `${prefix}${table.dataStream}${suffix}`;++ return {+ id: 'test-doc',+ body: {+ dataStream,+ textRuns: [{+ st: 0,+ ed: dataStream.length - 2,+ ts: {},+ }],+ paragraphs: [+ { startIndex: 5 },+ { startIndex: 10 },+ ...table.paragraphs.map((paragraph) => ({+ ...paragraph,+ startIndex: paragraph.startIndex + prefix.length,+ })),+ {+ startIndex: dataStream.length - 2,+ },+ ],+ sectionBreaks: [+ ...table.sectionBreaks.map((sectionBreak) => ({+ ...sectionBreak,+ startIndex: sectionBreak.startIndex + prefix.length,+ })),+ {+ startIndex: dataStream.length - 1,+ },+ ],+ tables: [{+ startIndex: prefix.length,+ endIndex: prefix.length + table.dataStream.length,+ tableId: 'table-1',+ }],+ customBlocks: [],+ },+ documentStyle: {+ pageSize: {+ width: 594.3,+ height: 840.51,+ },+ marginTop: 72,+ marginBottom: 72,+ marginRight: 90,+ marginLeft: 90,+ },+ };+}+describe('misc document commands', () => {let univer: Univer;let get: Injector['get'];@@ -290,7 +345,7 @@ describe('misc document commands', () => {subscription.unsubscribe();});- it('selects text and table ranges when tables are present', async () => {+ it('selects the current paragraph first when tables are present', async () => {({ univer, get } = createCommandTestBed(createTableDoc()));commandService = get(ICommandService);commandService.registerCommand(DocSelectAllCommand);@@ -317,16 +372,136 @@ describe('misc document commands', () => {startOffset: 0,endOffset: 1,}),+ ],+ }));++ subscription.unsubscribe();+ });++ it('expands to the whole body when the current paragraph selection is split into visual ranges', async () => {+ ({ univer, get } = createCommandTestBed(createTableDoc()));+ commandService = get(ICommandService);+ commandService.registerCommand(DocSelectAllCommand);++ const selectionManager = get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ });+ selectionManager.__TEST_ONLY_add([{+ startOffset: 0,+ endOffset: 0,+ collapsed: false,+ isActive: true,+ segmentId: '',+ style: null as never,+ }, {+ startOffset: 1,+ endOffset: 1,+ collapsed: false,+ isActive: false,+ segmentId: '',+ style: null as never,+ }], false);++ const refreshEvents: Array<unknown> = [];+ const subscription = selectionManager.refreshSelection$.subscribe((event) => {+ if (event) {+ refreshEvents.push(event);+ }+ });++ const result = await commandService.executeCommand(DocSelectAllCommand.id);+ await awaitTime(0);++ expect(result).toBe(true);+ expect(refreshEvents.at(-1)).toEqual(expect.objectContaining({+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ isEditing: false,+ docRanges: [+ expect.objectContaining({ startOffset: 0, endOffset: 1 }),+ expect.objectContaining({ startOffset: 5, endOffset: 19, rangeType: 'RECT' }),+ expect.objectContaining({ startOffset: 24, endOffset: 26 }),+ ],+ }));++ subscription.unsubscribe();+ });++ it('expands to the whole body by keeping text before tables selectable across paragraphs', async () => {+ ({ univer, get } = createCommandTestBed(createTableDocWithParagraphsBeforeTable()));+ commandService = get(ICommandService);+ commandService.registerCommand(DocSelectAllCommand);++ const selectionManager = get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ });+ selectionManager.__TEST_ONLY_add([{+ startOffset: 0,+ endOffset: 5,+ collapsed: false,+ isActive: true,+ segmentId: '',+ style: null as never,+ }], false);++ const refreshEvents: Array<unknown> = [];+ const subscription = selectionManager.refreshSelection$.subscribe((event) => {+ if (event) {+ refreshEvents.push(event);+ }+ });++ const result = await commandService.executeCommand(DocSelectAllCommand.id);+ await awaitTime(0);++ expect(result).toBe(true);+ expect(refreshEvents.at(-1)).toEqual(expect.objectContaining({+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ isEditing: false,+ docRanges: [+ expect.objectContaining({ startOffset: 0, endOffset: 5 }),+ expect.objectContaining({ startOffset: 6, endOffset: 10 }),+ expect.objectContaining({ rangeType: 'RECT' }),+ expect.objectContaining({ startOffset: expect.any(Number), endOffset: expect.any(Number), rangeType: 'TEXT' }),+ ],+ }));++ subscription.unsubscribe();+ });++ it('selects the current table first when the cursor is inside a table', async () => {+ ({ univer, get } = createCommandTestBed(createTableDoc()));+ commandService = get(ICommandService);+ commandService.registerCommand(DocSelectAllCommand);+ setCollapsedSelection(6);++ const selectionManager = get(DocSelectionManagerService);+ const refreshEvents: Array<unknown> = [];+ const subscription = selectionManager.refreshSelection$.subscribe((event) => {+ if (event) {+ refreshEvents.push(event);+ }+ });++ const result = await commandService.executeCommand(DocSelectAllCommand.id);+ await awaitTime(0);++ expect(result).toBe(true);+ expect(refreshEvents.at(-1)).toEqual(expect.objectContaining({+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ isEditing: false,+ docRanges: [expect.objectContaining({startOffset: 5,endOffset: 19,rangeType: 'RECT',}),- expect.objectContaining({- startOffset: 24,- endOffset: 26,- rangeType: 'TEXT',- }),],}));diff --git a/packages/docs-ui/src/commands/commands/doc-block-move.command.ts b/packages/docs-ui/src/commands/commands/doc-block-move.command.tsnew file mode 100644index 0000000000..753a376c62--- /dev/null+++ b/packages/docs-ui/src/commands/commands/doc-block-move.command.ts@@ -0,0 +1,267 @@+/**+ * 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, ICommand, IDocumentBody, IDocumentData, JSONXActions } from '@univerjs/core';+import type { IRichTextEditingMutationParams } from '@univerjs/docs';+import type { ITextRangeWithStyle } from '@univerjs/engine-render';+import { CommandType, ICommandService, IUniverInstanceService, JSONX, Tools, UniverInstanceType } from '@univerjs/core';+import { RichTextEditingMutation } from '@univerjs/docs';++export interface IMoveDocBlockCommandParams {+ unitId?: string;+ sourceRange: {+ startOffset: number;+ endOffset: number;+ };+ targetOffset: number;+}++export interface IMoveDocBlockActionResult {+ nextDocumentData: IDocumentData;+ movedRange: {+ startOffset: number;+ endOffset: number;+ };+}++export const MoveDocBlockCommand: ICommand<IMoveDocBlockCommandParams> = {+ id: 'doc.command.move-block',+ type: CommandType.COMMAND,+ handler: async (accessor, params) => {+ if (!params) {+ return false;+ }++ const univerInstanceService = accessor.get(IUniverInstanceService);+ const commandService = accessor.get(ICommandService);+ const doc = (params.unitId+ ? univerInstanceService.getUnit(params.unitId, UniverInstanceType.UNIVER_DOC)+ : univerInstanceService.getCurrentUniverDocInstance()) as DocumentDataModel | undefined;++ if (!doc) {+ return false;+ }++ const previousDocumentData = doc.getSnapshot();+ const { nextDocumentData, movedRange } = buildMoveDocBlockActions({+ documentData: previousDocumentData,+ sourceRange: params.sourceRange,+ targetOffset: params.targetOffset,+ });+ const actions = buildReplaceDocumentBodyActions(previousDocumentData, nextDocumentData);++ if (!actions) {+ return false;+ }++ const textRanges: ITextRangeWithStyle[] = [{+ startOffset: movedRange.startOffset,+ endOffset: movedRange.endOffset,+ collapsed: false,+ }];++ return Boolean(commandService.syncExecuteCommand<IRichTextEditingMutationParams>(RichTextEditingMutation.id, {+ unitId: doc.getUnitId(),+ actions,+ textRanges,+ }));+ },+};++export function buildMoveDocBlockActions(params: {+ documentData: IDocumentData;+ sourceRange: {+ startOffset: number;+ endOffset: number;+ };+ targetOffset: number;+}): IMoveDocBlockActionResult {+ const nextDocumentData = Tools.deepClone(params.documentData);+ const body = nextDocumentData.body;++ if (!body?.dataStream) {+ return {+ nextDocumentData,+ movedRange: params.sourceRange,+ };+ }++ const dataStreamLength = body.dataStream.length;+ const startOffset = clamp(params.sourceRange.startOffset, 0, dataStreamLength);+ const endOffset = clamp(params.sourceRange.endOffset, startOffset, dataStreamLength);+ const targetOffset = clamp(params.targetOffset, 0, dataStreamLength);++ if (startOffset === endOffset || (targetOffset >= startOffset && targetOffset <= endOffset)) {+ return {+ nextDocumentData,+ movedRange: {+ startOffset,+ endOffset,+ },+ };+ }++ const movingText = body.dataStream.slice(startOffset, endOffset);+ const moveLength = movingText.length;+ const insertOffset = targetOffset > endOffset ? targetOffset - moveLength : targetOffset;+ const withoutMovingText = body.dataStream.slice(0, startOffset) + body.dataStream.slice(endOffset);+ body.dataStream = withoutMovingText.slice(0, insertOffset) + movingText + withoutMovingText.slice(insertOffset);++ remapBodyIndexesAfterMove(body, startOffset, endOffset, targetOffset, insertOffset, moveLength);++ return {+ nextDocumentData,+ movedRange: {+ startOffset: insertOffset,+ endOffset: insertOffset + moveLength,+ },+ };+}++function buildReplaceDocumentBodyActions(previousDocumentData: IDocumentData, nextDocumentData: IDocumentData): JSONXActions | null {+ const jsonX = JSONX.getInstance();+ const previousBody = previousDocumentData.body;+ const nextBody = nextDocumentData.body;++ if (!previousBody || !nextBody) {+ return null;+ }++ const rawActions = [+ jsonX.replaceOp(['body', 'dataStream'], previousBody.dataStream, nextBody.dataStream),+ jsonX.replaceOp(['body', 'paragraphs'], previousBody.paragraphs, nextBody.paragraphs),+ jsonX.replaceOp(['body', 'sectionBreaks'], previousBody.sectionBreaks, nextBody.sectionBreaks),+ jsonX.replaceOp(['body', 'tables'], previousBody.tables, nextBody.tables),+ jsonX.replaceOp(['body', 'customBlocks'], previousBody.customBlocks, nextBody.customBlocks),+ jsonX.replaceOp(['body', 'blockRanges'], previousBody.blockRanges, nextBody.blockRanges),+ jsonX.replaceOp(['body', 'customRanges'], previousBody.customRanges, nextBody.customRanges),+ jsonX.replaceOp(['body', 'customDecorations'], previousBody.customDecorations, nextBody.customDecorations),+ jsonX.replaceOp(['body', 'textRuns'], previousBody.textRuns, nextBody.textRuns),+ ].filter(Boolean) as JSONXActions[];++ return rawActions.reduce((acc, cur) => JSONX.compose(acc, cur), null as JSONXActions);+}++function remapBodyIndexesAfterMove(+ body: IDocumentBody,+ startOffset: number,+ endOffset: number,+ targetOffset: number,+ insertOffset: number,+ moveLength: number+) {+ body.paragraphs = body.paragraphs?.map((paragraph) => ({+ ...paragraph,+ startIndex: remapIndexAfterMove(paragraph.startIndex, startOffset, endOffset, targetOffset, insertOffset, moveLength),+ })).sort((left, right) => left.startIndex - right.startIndex);++ body.sectionBreaks = body.sectionBreaks?.map((sectionBreak) => ({+ ...sectionBreak,+ startIndex: remapIndexAfterMove(sectionBreak.startIndex, startOffset, endOffset, targetOffset, insertOffset, moveLength),+ })).sort((left, right) => left.startIndex - right.startIndex);++ body.customBlocks = body.customBlocks?.map((customBlock) => ({+ ...customBlock,+ startIndex: remapIndexAfterMove(customBlock.startIndex, startOffset, endOffset, targetOffset, insertOffset, moveLength),+ })).sort((left, right) => left.startIndex - right.startIndex);++ body.tables = body.tables?.map((table) => remapExclusiveRange(table, startOffset, endOffset, targetOffset, insertOffset, moveLength))+ .sort((left, right) => left.startIndex - right.startIndex);++ body.blockRanges = body.blockRanges?.map((blockRange) => remapInclusiveRange(blockRange, startOffset, endOffset, targetOffset, insertOffset, moveLength))+ .sort((left, right) => left.startIndex - right.startIndex);++ body.customRanges = body.customRanges?.map((customRange) => remapInclusiveRange(customRange, startOffset, endOffset, targetOffset, insertOffset, moveLength))+ .sort((left, right) => left.startIndex - right.startIndex);++ body.customDecorations = body.customDecorations?.map((customDecoration) => remapInclusiveRange(customDecoration, startOffset, endOffset, targetOffset, insertOffset, moveLength))+ .sort((left, right) => left.startIndex - right.startIndex);++ body.textRuns = body.textRuns?.map((textRun) => {+ const remapped = remapExclusiveRange({ startIndex: textRun.st, endIndex: textRun.ed }, startOffset, endOffset, targetOffset, insertOffset, moveLength);+ return {+ ...textRun,+ st: remapped.startIndex,+ ed: remapped.endIndex,+ };+ }).sort((left, right) => left.st - right.st);+}++function remapExclusiveRange<T extends { startIndex: number; endIndex: number }>(+ range: T,+ startOffset: number,+ endOffset: number,+ targetOffset: number,+ insertOffset: number,+ moveLength: number+): T {+ if (range.startIndex >= startOffset && range.endIndex <= endOffset) {+ return {+ ...range,+ startIndex: insertOffset + range.startIndex - startOffset,+ endIndex: insertOffset + range.endIndex - startOffset,+ };+ }++ return {+ ...range,+ startIndex: remapIndexAfterMove(range.startIndex, startOffset, endOffset, targetOffset, insertOffset, moveLength),+ endIndex: remapIndexAfterMove(range.endIndex, startOffset, endOffset, targetOffset, insertOffset, moveLength),+ };+}++function remapInclusiveRange<T extends { startIndex: number; endIndex: number }>(+ range: T,+ startOffset: number,+ endOffset: number,+ targetOffset: number,+ insertOffset: number,+ moveLength: number+): T {+ if (range.startIndex >= startOffset && range.endIndex < endOffset) {+ return {+ ...range,+ startIndex: insertOffset + range.startIndex - startOffset,+ endIndex: insertOffset + range.endIndex - startOffset,+ };+ }++ return {+ ...range,+ startIndex: remapIndexAfterMove(range.startIndex, startOffset, endOffset, targetOffset, insertOffset, moveLength),+ endIndex: remapIndexAfterMove(range.endIndex, startOffset, endOffset, targetOffset, insertOffset, moveLength),+ };+}++function remapIndexAfterMove(index: number, startOffset: number, endOffset: number, targetOffset: number, insertOffset: number, moveLength: number): number {+ if (index >= startOffset && index < endOffset) {+ return insertOffset + index - startOffset;+ }++ if (targetOffset < startOffset && index >= targetOffset && index < startOffset) {+ return index + moveLength;+ }++ if (targetOffset > endOffset && index >= endOffset && index < targetOffset) {+ return index - moveLength;+ }++ return index;+}++function clamp(value: number, min: number, max: number): number {+ return Math.min(Math.max(value, min), max);+}diff --git a/packages/docs-ui/src/commands/commands/doc-delete.command.ts b/packages/docs-ui/src/commands/commands/doc-delete.command.tsindex 26d6e1fe67..5387e05922 100644--- a/packages/docs-ui/src/commands/commands/doc-delete.command.ts+++ b/packages/docs-ui/src/commands/commands/doc-delete.command.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { DocumentDataModel, ICommand, IMutationInfo, IParagraph, ITextRange, JSONXActions, Nullable } from '@univerjs/core';+import type { DocumentDataModel, ICommand, IDocumentBlockRange, IDocumentBody, IMutationInfo, IParagraph, ITextRange, JSONXActions, Nullable } from '@univerjs/core';import type { IRichTextEditingMutationParams } from '@univerjs/docs';import type { IRectRangeWithStyle, ITextRangeWithStyle } from '@univerjs/engine-render';import {@@ -22,10 +22,12 @@ import {BuildTextUtils,CommandType,DataStreamTreeTokenType,+ HorizontalAlign,ICommandService,IUniverInstanceService,JSONX,PositionedObjectLayoutType,+ sequenceExecuteAsync,TextX,TextXActionType,Tools,@@ -35,6 +37,7 @@ import {import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';import { getParagraphByGlyph, hasListGlyph, isFirstGlyph, isIndentByGlyph } from '@univerjs/engine-render';+import { DocAutoFormatService } from '../../services/doc-auto-format.service';import { DeleteDirection } from '../../types/delete-direction';import { getCommandSkeleton, getRichTextEditPath } from '../util';import { CutContentCommand } from './clipboard.inner.command';@@ -401,6 +404,21 @@ export function getCursorWhenDelete(textRanges: Readonly<Nullable<ITextRangeWithreturn cursor;}+function getBlockRangeEndTokenOffset(body: IDocumentBody, blockRange: Pick<IDocumentBlockRange, 'endIndex'>): number {+ return body.dataStream[blockRange.endIndex] === DataStreamTreeTokenType.BLOCK_END+ ? blockRange.endIndex+ : body.dataStream[blockRange.endIndex + 1] === DataStreamTreeTokenType.BLOCK_END+ ? blockRange.endIndex + 1+ : blockRange.endIndex;+}++export function isDeleteOffsetInsideBlockRange(body: IDocumentBody, offset: number): boolean {+ return body.blockRanges?.some((blockRange) => {+ const endTokenOffset = getBlockRangeEndTokenOffset(body, blockRange);+ return blockRange.startIndex < offset && offset < endTokenOffset;+ }) ?? false;+}+// Handle BACKSPACE key.export const DeleteLeftCommand: ICommand = {id: 'doc.command.delete-left',@@ -449,6 +467,11 @@ export const DeleteLeftCommand: ICommand = {return false;}+ const autoFormatResult = await executeDeleteAutoFormat(accessor, DeleteLeftCommand.id);+ if (autoFormatResult != null) {+ return autoFormatResult;+ }+const { segmentId, style, segmentPage } = activeRange;const body = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody();@@ -459,6 +482,13 @@ export const DeleteLeftCommand: ICommand = {const actualRange = activeRange;const { startOffset, collapsed } = actualRange;+ if (collapsed) {+ const emptyCenteredParagraph = getEmptyCenteredParagraphAtOffset(body, startOffset);+ if (emptyCenteredParagraph != null) {+ return resetEmptyCenteredParagraphAlignment(commandService, docDataModel, segmentId ?? '', emptyCenteredParagraph, style);+ }+ }+const curGlyph = skeleton.findNodeByCharIndex(startOffset, segmentId, segmentPage);// is in bullet list?@@ -470,9 +500,10 @@ export const DeleteLeftCommand: ICommand = {// Get the deleted glyph. It maybe null or undefined when the curGlyph is first glyph in skeleton.const preGlyph = skeleton.findNodeByCharIndex(startOffset - 1, segmentId, segmentPage);+ const isInBlockRange = isDeleteOffsetInsideBlockRange(body, startOffset);const isUpdateParagraph =- isFirstGlyph(curGlyph) && preGlyph !== curGlyph && (isBullet === true || isIndent === true);+ !isInBlockRange && isFirstGlyph(curGlyph) && preGlyph !== curGlyph && (isBullet === true || isIndent === true);if (isUpdateParagraph && collapsed) {const paragraph = getParagraphByGlyph(curGlyph, body);@@ -669,6 +700,11 @@ export const DeleteRightCommand: ICommand = {return false;}+ const autoFormatResult = await executeDeleteAutoFormat(accessor, DeleteRightCommand.id);+ if (autoFormatResult != null) {+ return autoFormatResult;+ }+const { segmentId, style, segmentPage } = activeRange;const body = docDataModel?.getSelfOrHeaderFooterModel(segmentId).getBody();@@ -678,6 +714,13 @@ export const DeleteRightCommand: ICommand = {const actualRange = activeRange;const { startOffset, endOffset, collapsed } = actualRange;+ if (collapsed) {+ const emptyCenteredParagraph = getEmptyCenteredParagraphAtOffset(body, startOffset);+ if (emptyCenteredParagraph != null) {+ return resetEmptyCenteredParagraphAlignment(commandService, docDataModel, segmentId ?? '', emptyCenteredParagraph, style);+ }+ }+// No need to delete when the cursor is at the last position of the last paragraph.if (startOffset === body.dataStream.length - 2 && collapsed) {return true;@@ -775,6 +818,20 @@ export const DeleteRightCommand: ICommand = {},};+async function executeDeleteAutoFormat(accessor: Parameters<ICommand['handler']>[0], commandId: string): Promise<boolean | null> {+ if (!accessor.has(DocAutoFormatService)) {+ return null;+ }++ const commandService = accessor.get(ICommandService);+ const mutations = accessor.get(DocAutoFormatService).onAutoFormat(commandId);+ if (!mutations.length) {+ return null;+ }++ return (await sequenceExecuteAsync(mutations, commandService)).result;+}+// get cursor position when BACKSPACE/DELETE excuse the CutContentCommand.function getTextRangesWhenDelete(activeRange: ITextRangeWithStyle, ranges: readonly ITextRange[]) {let cursor = activeRange.endOffset;@@ -802,6 +859,56 @@ function getTextRangesWhenDelete(activeRange: ITextRangeWithStyle, ranges: readoreturn textRanges;}+function getEmptyCenteredParagraphAtOffset(body: IDocumentBody, offset: number) {+ const paragraphs = body.paragraphs ?? [];+ for (let i = 0; i < paragraphs.length; i++) {+ const paragraph = paragraphs[i];+ const paragraphTextStart = i === 0 ? 0 : paragraphs[i - 1].startIndex + 1;+ if (+ paragraph.startIndex === paragraphTextStart &&+ paragraph.startIndex === offset &&+ paragraph.paragraphStyle?.horizontalAlign === HorizontalAlign.CENTER+ ) {+ return paragraph;+ }+ }+}++function resetEmptyCenteredParagraphAlignment(+ commandService: ICommandService,+ docDataModel: DocumentDataModel,+ segmentId: string,+ paragraph: IParagraph,+ style: ITextRangeWithStyle['style']+) {+ return commandService.executeCommand(UpdateCommand.id, {+ unitId: docDataModel.getUnitId(),+ updateBody: {+ dataStream: '',+ paragraphs: [{+ ...paragraph,+ startIndex: 0,+ paragraphStyle: {+ ...paragraph.paragraphStyle,+ horizontalAlign: HorizontalAlign.LEFT,+ },+ }],+ },+ range: {+ startOffset: paragraph.startIndex,+ endOffset: paragraph.startIndex + 1,+ },+ textRanges: [{+ startOffset: paragraph.startIndex,+ endOffset: paragraph.startIndex,+ collapsed: true,+ style,+ }],+ coverType: UpdateDocsAttributeType.REPLACE,+ segmentId,+ });+}+export const DeleteCurrentParagraphCommand: ICommand = {id: 'doc.command.delete-current-paragraph',type: CommandType.COMMAND,diff --git a/packages/docs-ui/src/commands/commands/doc-horizontal-line.command.ts b/packages/docs-ui/src/commands/commands/doc-horizontal-line.command.tsindex 1b5bf65364..746c3cd449 100644--- a/packages/docs-ui/src/commands/commands/doc-horizontal-line.command.ts+++ b/packages/docs-ui/src/commands/commands/doc-horizontal-line.command.ts@@ -15,7 +15,8 @@*/import type { ICommand, ITextRangeParam } from '@univerjs/core';-import { CommandType, DashStyleType, ICommandService } from '@univerjs/core';+import { CommandType, DashStyleType, ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';+import { DocContentInsertService } from '../../services/doc-content-insert.service';import { BreakLineCommand } from './break-line.command';import { getCurrentParagraph } from './util';@@ -50,6 +51,22 @@ export const InsertHorizontalLineBellowCommand: ICommand<IHorizontalCommandParamtype: CommandType.COMMAND,handler: (accessor) => {const commandService = accessor.get(ICommandService);+ const doc = accessor.get(IUniverInstanceService).getCurrentUnitOfType(UniverInstanceType.UNIVER_DOC);+ let contentInsertRange: ReturnType<DocContentInsertService['consumeInsertRange']> = null;+ try {+ contentInsertRange = accessor.get(DocContentInsertService).consumeInsertRange(doc?.getUnitId());+ } catch {+ contentInsertRange = null;+ }+ if (contentInsertRange) {+ return commandService.syncExecuteCommand(HorizontalLineCommand.id, {+ insertRange: {+ startOffset: contentInsertRange.startOffset,+ endOffset: contentInsertRange.endOffset,+ },+ });+ }+const paragraph = getCurrentParagraph(accessor);if (!paragraph) {return false;diff --git a/packages/docs-ui/src/commands/commands/doc-page-setup.command.ts b/packages/docs-ui/src/commands/commands/doc-page-setup.command.tsindex e4de7f056f..5d5ac76d61 100644--- a/packages/docs-ui/src/commands/commands/doc-page-setup.command.ts+++ b/packages/docs-ui/src/commands/commands/doc-page-setup.command.ts@@ -14,20 +14,84 @@* limitations under the License.*/-import type { DocumentDataModel, ICommand, ICommandInfo, ISize, JSONXActions, PageOrientType } from '@univerjs/core';+import type { DocumentDataModel, ICommand, ICommandInfo, IDocumentStyle, ISize, ITable, ITables, JSONXActions, PageOrientType } from '@univerjs/core';import type { IRichTextEditingMutationParams } from '@univerjs/docs';-import { CommandType, ICommandService, IUniverInstanceService, JSONX, UniverInstanceType } from '@univerjs/core';+import { CommandType, DocumentFlavor, ICommandService, IUniverInstanceService, JSONX, MODERN_DOCUMENT_DEFAULT_MARGIN, UniverInstanceType } from '@univerjs/core';import { RichTextEditingMutation } from '@univerjs/docs';export interface IDocPageSetupCommandParams {pageSize: ISize;pageOrient: PageOrientType;+ documentFlavor?: DocumentFlavor;marginTop: number;marginBottom: number;marginLeft: number;marginRight: number;}+const PAGE_FILL_TABLE_TOLERANCE = 2;++interface IPageContentWidthConfig {+ documentFlavor?: DocumentFlavor;+ pageSize?: ISize;+ marginLeft?: number;+ marginRight?: number;+}++function getPageContentWidth(config: IPageContentWidthConfig) {+ const pageWidth = config.pageSize?.width ?? 0;++ if (!pageWidth) {+ return 0;+ }++ if (config.documentFlavor === DocumentFlavor.MODERN) {+ return Math.max(0, pageWidth - MODERN_DOCUMENT_DEFAULT_MARGIN * 2);+ }++ return Math.max(0, pageWidth - (config.marginLeft ?? 0) - (config.marginRight ?? 0));+}++function getTableColumnTotalWidth(table: ITable) {+ return table.tableColumns.reduce((total, column) => total + (column.size.width.v ?? 0), 0);+}++function isPageFillTable(table: ITable, oldContentWidth: number) {+ if (oldContentWidth <= 0 || table.tableColumns.length === 0) {+ return false;+ }++ const columnTotalWidth = getTableColumnTotalWidth(table);+ const tableWidth = columnTotalWidth || table.size.width.v;+ return Math.abs(tableWidth - oldContentWidth) <= PAGE_FILL_TABLE_TOLERANCE;+}++function resizePageFillTables(jsonX: JSONX, rawActions: NonNullable<JSONXActions>, tableSource: ITables | undefined, oldContentWidth: number, newContentWidth: number) {+ if (!tableSource || oldContentWidth <= 0 || newContentWidth <= 0 || Math.abs(oldContentWidth - newContentWidth) <= PAGE_FILL_TABLE_TOLERANCE) {+ return;+ }++ Object.entries(tableSource).forEach(([tableId, table]) => {+ if (!isPageFillTable(table, oldContentWidth)) {+ return;+ }++ const totalColumnWidth = getTableColumnTotalWidth(table);+ if (totalColumnWidth <= 0) {+ return;+ }++ const tableWidthAction = jsonX.replaceOp(['tableSource', tableId, 'size', 'width', 'v'], table.size.width.v, newContentWidth);+ tableWidthAction && rawActions.push(tableWidthAction);++ table.tableColumns.forEach((column, index) => {+ const nextWidth = (column.size.width.v / totalColumnWidth) * newContentWidth;+ const action = jsonX.replaceOp(['tableSource', tableId, 'tableColumns', index, 'size', 'width', 'v'], column.size.width.v, nextWidth);+ action && rawActions.push(action);+ });+ });+}+export const DocPageSetupCommand: ICommand<IDocPageSetupCommandParams> = {id: 'docs.command.page-setup',type: CommandType.COMMAND,@@ -38,9 +102,20 @@ export const DocPageSetupCommand: ICommand<IDocPageSetupCommandParams> = {const commandService = accessor.get(ICommandService);const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);if (!docDataModel) return false;- const { marginLeft, marginRight, marginBottom, marginTop, pageOrient, pageSize } = params;+ const { documentFlavor, marginLeft, marginRight, marginBottom, marginTop, pageOrient, pageSize } = params;const jsonX = JSONX.getInstance();const documentStyle = docDataModel.getDocumentStyle();+ const snapshot = docDataModel.getSnapshot();+ const newDocumentStyle: IDocumentStyle = {+ ...documentStyle,+ documentFlavor: documentFlavor ?? documentStyle.documentFlavor,+ marginBottom,+ marginLeft,+ marginRight,+ marginTop,+ pageOrient,+ pageSize,+ };const {marginBottom: oldMarginBottom,marginLeft: oldMarginLeft,@@ -48,8 +123,27 @@ export const DocPageSetupCommand: ICommand<IDocPageSetupCommandParams> = {marginTop: oldMarginTop,pageOrient: oldPageOrient,pageSize: oldPageSize,+ documentFlavor: oldDocumentFlavor,} = documentStyle;- const rawActions: JSONXActions = [];+ const rawActions: NonNullable<JSONXActions> = [];++ resizePageFillTables(+ jsonX,+ rawActions,+ snapshot.tableSource,+ getPageContentWidth(documentStyle),+ getPageContentWidth(newDocumentStyle)+ );++ if (documentFlavor !== undefined) {+ if (oldDocumentFlavor === undefined) {+ const action = jsonX.insertOp(['documentStyle', 'documentFlavor'], documentFlavor);+ action && rawActions.push(action);+ } else {+ const action = jsonX.replaceOp(['documentStyle', 'documentFlavor'], oldDocumentFlavor, documentFlavor);+ action && rawActions.push(action);+ }+ }if (oldMarginBottom === undefined) {const action = jsonX.insertOp(['documentStyle', 'marginBottom'], marginBottom);diff --git a/packages/docs-ui/src/commands/commands/doc-select-all.command.ts b/packages/docs-ui/src/commands/commands/doc-select-all.command.tsindex ff7d0a88c3..82e57ce7ab 100644--- a/packages/docs-ui/src/commands/commands/doc-select-all.command.ts+++ b/packages/docs-ui/src/commands/commands/doc-select-all.command.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { DocumentDataModel, ICommand } from '@univerjs/core';+import type { DocumentDataModel, ICommand, ICustomTable, IDocumentBody, IParagraph } from '@univerjs/core';import type { ISuccinctDocRangeParam } from '@univerjs/engine-render';import { CommandType, DOC_RANGE_TYPE, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';import { DocSelectionManagerService } from '@univerjs/docs';@@ -41,40 +41,14 @@ export const DocSelectAllCommand: ICommand<ISelectAllCommandParams> = {return false;}- const { tables = [], dataStream } = body;+ const { dataStream } = body;if (dataStream === '\r\n') {return true;}- const textRanges: ISuccinctDocRangeParam[] = [];- let offset = 0;-- for (const table of tables) {- const { startIndex, endIndex } = table;- if (offset !== startIndex) {- textRanges.push({- startOffset: offset,- endOffset: startIndex - 1,- rangeType: DOC_RANGE_TYPE.TEXT,- });- }-- // Push the rect range.- textRanges.push({- startOffset: startIndex + 3, // 3 is TABLE_START, ROW_START, CELL_START.- endOffset: endIndex - 5, // 4 is CELL_END, ROW_END, TABLE_END AND \n.- rangeType: DOC_RANGE_TYPE.RECT,- });-- offset = endIndex;- }- if (offset !== body.dataStream.length - 2) {- textRanges.push({- startOffset: offset,- endOffset: body.dataStream.length - 2,- rangeType: DOC_RANGE_TYPE.TEXT,- });- }+ const wholeDocRanges = getWholeDocumentRanges(body);+ const scopedRange = getScopedSelectAllRange(body, activeRange);+ const textRanges = scopedRange && !isSameRanges(docRanges, scopedRange) ? scopedRange : wholeDocRanges;docSelectionManagerService.replaceDocRanges(textRanges, {unitId,@@ -84,3 +58,187 @@ export const DocSelectAllCommand: ICommand<ISelectAllCommandParams> = {return true;},};++function getWholeDocumentRanges(body: IDocumentBody): ISuccinctDocRangeParam[] {+ const textRanges: ISuccinctDocRangeParam[] = [];+ let offset = 0;++ for (const table of body.tables ?? []) {+ const { startIndex, endIndex } = table;+ if (offset !== startIndex) {+ textRanges.push(...getTextRangesByParagraphs(body, offset, startIndex - 1));+ }++ textRanges.push(getTableRectRange(table));+ offset = endIndex;+ }++ if (offset !== body.dataStream.length - 2) {+ textRanges.push(...getTextRangesByParagraphs(body, offset, body.dataStream.length - 2));+ }++ return textRanges;+}++function getTextRangesByParagraphs(body: IDocumentBody, startOffset: number, endOffset: number): ISuccinctDocRangeParam[] {+ if (startOffset > endOffset) {+ return [];+ }++ const paragraphs = [...(body.paragraphs ?? [])].sort((left, right) => left.startIndex - right.startIndex);+ const ranges: ISuccinctDocRangeParam[] = [];+ let offset = startOffset;++ for (const paragraph of paragraphs) {+ if (paragraph.startIndex < offset) {+ continue;+ }++ if (paragraph.startIndex > endOffset) {+ break;+ }++ ranges.push({+ startOffset: offset,+ endOffset: paragraph.startIndex,+ rangeType: DOC_RANGE_TYPE.TEXT,+ });+ offset = paragraph.startIndex + 1;+ }++ if (offset <= endOffset) {+ ranges.push({+ startOffset: offset,+ endOffset,+ rangeType: DOC_RANGE_TYPE.TEXT,+ });+ }++ return ranges;+}++function getScopedSelectAllRange(body: IDocumentBody, activeRange: ISuccinctDocRangeParam): ISuccinctDocRangeParam[] | null {+ const startOffset = activeRange.startOffset;+ const endOffset = activeRange.endOffset;+ if (startOffset == null || endOffset == null) {+ return null;+ }++ const table = (body.tables ?? []).find((item) => isRangeInside(startOffset, endOffset, item.startIndex, item.endIndex));+ if (table) {+ return [getTableRectRange(table)];+ }++ const customBlock = (body.customBlocks ?? []).find((item) => item.startIndex >= startOffset && item.startIndex <= endOffset);+ if (customBlock) {+ return [{+ endOffset: customBlock.startIndex,+ rangeType: DOC_RANGE_TYPE.TEXT,+ startOffset: customBlock.startIndex,+ }];+ }++ const blockRange = (body.blockRanges ?? []).find((item) => isRangeInside(startOffset, endOffset, item.startIndex, item.endIndex));+ if (blockRange) {+ return [{+ endOffset: Math.max(blockRange.startIndex + 1, blockRange.endIndex - 1),+ rangeType: DOC_RANGE_TYPE.TEXT,+ startOffset: blockRange.startIndex + 1,+ }];+ }++ const paragraphRange = clampParagraphRangeByTables(getParagraphRangeAtOffset(body.paragraphs ?? [], startOffset), body.tables ?? [], startOffset);+ return paragraphRange+ ? [{+ ...paragraphRange,+ rangeType: DOC_RANGE_TYPE.TEXT,+ }]+ : null;+}++function clampParagraphRangeByTables(+ paragraphRange: Pick<ISuccinctDocRangeParam, 'endOffset' | 'startOffset'> | null,+ tables: ICustomTable[],+ activeOffset: number+): Pick<ISuccinctDocRangeParam, 'endOffset' | 'startOffset'> | null {+ if (!paragraphRange) {+ return null;+ }++ const nextRange = { ...paragraphRange };+ for (const table of tables) {+ if (activeOffset < table.startIndex && nextRange.startOffset! < table.startIndex && table.startIndex <= nextRange.endOffset!) {+ nextRange.endOffset = table.startIndex - 1;+ } else if (activeOffset >= table.endIndex && nextRange.startOffset! <= table.endIndex && table.endIndex < nextRange.endOffset!) {+ nextRange.startOffset = table.endIndex;+ }+ }++ return nextRange.startOffset! <= nextRange.endOffset! ? nextRange : null;+}++function getTableRectRange(table: ICustomTable): ISuccinctDocRangeParam {+ return {+ startOffset: table.startIndex + 3,+ endOffset: table.endIndex - 5,+ rangeType: DOC_RANGE_TYPE.RECT,+ };+}++function getParagraphRangeAtOffset(paragraphs: IParagraph[], offset: number): Pick<ISuccinctDocRangeParam, 'endOffset' | 'startOffset'> | null {+ const sortedParagraphs = [...paragraphs].sort((left, right) => left.startIndex - right.startIndex);+ for (let index = 0; index < sortedParagraphs.length; index++) {+ const paragraph = sortedParagraphs[index];+ const startOffset = index === 0 ? 0 : sortedParagraphs[index - 1].startIndex + 1;+ if (startOffset <= offset && offset <= paragraph.startIndex) {+ return {+ endOffset: paragraph.startIndex,+ startOffset,+ };+ }+ }++ return null;+}++function isRangeInside(startOffset: number, endOffset: number, scopeStart: number, scopeEnd: number): boolean {+ return startOffset >= scopeStart && endOffset <= scopeEnd;+}++function isSameRanges(currentRanges: ISuccinctDocRangeParam[], nextRanges: ISuccinctDocRangeParam[]): boolean {+ if (currentRanges.length !== nextRanges.length) {+ return isSameTextRangeCoverage(currentRanges, nextRanges);+ }++ return currentRanges.every((currentRange, index) => {+ const nextRange = nextRanges[index];+ return currentRange.startOffset === nextRange.startOffset &&+ currentRange.endOffset === nextRange.endOffset &&+ getRangeType(currentRange) === getRangeType(nextRange);+ });+}++function isSameTextRangeCoverage(currentRanges: ISuccinctDocRangeParam[], nextRanges: ISuccinctDocRangeParam[]): boolean {+ if (nextRanges.length !== 1 || getRangeType(nextRanges[0]) !== DOC_RANGE_TYPE.TEXT) {+ return false;+ }++ const targetRange = nextRanges[0];+ if (targetRange.startOffset == null || targetRange.endOffset == null) {+ return false;+ }++ if (currentRanges.some((range) => getRangeType(range) !== DOC_RANGE_TYPE.TEXT || range.startOffset == null || range.endOffset == null)) {+ return false;+ }++ const startOffset = Math.min(...currentRanges.map((range) => range.startOffset!));+ const endOffset = Math.max(...currentRanges.map((range) => range.endOffset!));+ return startOffset === targetRange.startOffset &&+ endOffset === targetRange.endOffset &&+ currentRanges.every((range) => range.startOffset! >= targetRange.startOffset! && range.endOffset! <= targetRange.endOffset!);+}++function getRangeType(range: ISuccinctDocRangeParam): DOC_RANGE_TYPE {+ return range.rangeType ?? DOC_RANGE_TYPE.TEXT;+}diff --git a/packages/docs-ui/src/commands/commands/inline-format.command.ts b/packages/docs-ui/src/commands/commands/inline-format.command.tsindex dd83e4014c..80b263248d 100644--- a/packages/docs-ui/src/commands/commands/inline-format.command.ts+++ b/packages/docs-ui/src/commands/commands/inline-format.command.ts@@ -253,7 +253,10 @@ export const SetInlineFormatCommand: ICommand<ISetInlineFormatCommandParams> = {const univerInstanceService = accessor.get(IUniverInstanceService);const docMenuStyleService = accessor.get(DocMenuStyleService);- const docRanges = docSelectionManagerService.getDocRanges();+ const textRanges = docSelectionManagerService.getTextRanges() ?? [];+ const docRanges = textRanges.length > 0+ ? textRanges.filter((range) => range.startOffset != null && range.endOffset != null)+ : docSelectionManagerService.getDocRanges();const activeRange = docRanges.find((r) => r.isActive) ?? docRanges[0];if (docRanges.length === 0) {diff --git a/packages/docs-ui/src/commands/commands/list.command.ts b/packages/docs-ui/src/commands/commands/list.command.tsindex e0ad91cdbc..14fdf86b5e 100644--- a/packages/docs-ui/src/commands/commands/list.command.ts+++ b/packages/docs-ui/src/commands/commands/list.command.ts@@ -33,6 +33,7 @@ import {UniverInstanceType,} from '@univerjs/core';import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';+import { DocContentInsertService } from '../../services/doc-content-insert.service';import { getRichTextEditPath } from '../util';import { getCurrentParagraph } from './util';@@ -345,6 +346,7 @@ export const ToggleCheckListCommand: ICommand<IToggleCheckListCommandParams> = {interface IOrderListCommandParams {value?: PresetListType;+ docRange?: ITextRangeWithStyle[];}export const OrderListCommand: ICommand<IOrderListCommandParams> = {@@ -357,11 +359,13 @@ export const OrderListCommand: ICommand<IOrderListCommandParams> = {if (params?.value) {return commandService.syncExecuteCommand(ChangeListTypeCommand.id, {listType: params.value,+ docRange: params.docRange,});}return commandService.syncExecuteCommand(ListOperationCommand.id, {listType: PresetListType.ORDER_LIST,+ docRange: params?.docRange,});},};@@ -483,19 +487,28 @@ export const QuickListCommand: ICommand<IQuickListCommandParams> = {function insertList(accessor: IAccessor, listType: PresetListType) {const commandService = accessor.get(ICommandService);- const paragraph = getCurrentParagraph(accessor);- if (!paragraph) {- return false;- }const docDataModel = accessor.get(IUniverInstanceService).getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);if (!docDataModel) {return false;}+ let contentInsertRange: ReturnType<DocContentInsertService['consumeInsertRange']> = null;+ try {+ contentInsertRange = accessor.get(DocContentInsertService).consumeInsertRange(docDataModel.getUnitId());+ } catch {+ contentInsertRange = null;+ }+ const paragraph = contentInsertRange ? null : getCurrentParagraph(accessor);+ if (!contentInsertRange && !paragraph) {+ return false;+ }+ const sourceParagraph = paragraph || undefined;+ const insertOffset = contentInsertRange?.startOffset ?? sourceParagraph!.startIndex + 1;+ const sourceBullet = sourceParagraph?.bullet;const textX = BuildTextUtils.selection.replace({doc: docDataModel,selection: {- startOffset: paragraph.startIndex + 1,- endOffset: paragraph.startIndex + 1,+ startOffset: insertOffset,+ endOffset: contentInsertRange?.endOffset ?? insertOffset,collapsed: true,},body: {@@ -504,12 +517,12 @@ function insertList(accessor: IAccessor, listType: PresetListType) {{startIndex: 0,paragraphStyle: {- ...paragraph.paragraphStyle,+ ...(sourceParagraph?.paragraphStyle ?? {}),},bullet: {listType,- listId: paragraph.bullet?.listType === listType ? paragraph.bullet.listId : generateRandomId(6),- nestingLevel: paragraph.bullet?.listType === listType ? paragraph.bullet.nestingLevel : 0,+ listId: sourceBullet?.listType === listType ? sourceBullet.listId : generateRandomId(6),+ nestingLevel: sourceBullet?.listType === listType ? sourceBullet.nestingLevel : 0,},},],@@ -525,8 +538,8 @@ function insertList(accessor: IAccessor, listType: PresetListType) {unitId: docDataModel.getUnitId(),actions: [],textRanges: [{- startOffset: paragraph.startIndex + 1,- endOffset: paragraph.startIndex + 1,+ startOffset: insertOffset,+ endOffset: insertOffset,collapsed: true,}],isEditing: false,diff --git a/packages/docs-ui/src/commands/commands/set-heading.command.ts b/packages/docs-ui/src/commands/commands/set-heading.command.tsindex e9d4ce849c..5d5beaae2e 100644--- a/packages/docs-ui/src/commands/commands/set-heading.command.ts+++ b/packages/docs-ui/src/commands/commands/set-heading.command.ts@@ -19,6 +19,7 @@ import type { IRichTextEditingMutationParams } from '@univerjs/docs';import type { ITextRangeWithStyle } from '@univerjs/engine-render';import { BuildTextUtils, CommandType, generateRandomId, ICommandService, IUniverInstanceService, JSONX, NamedStyleType, TextX, TextXActionType, UniverInstanceType } from '@univerjs/core';import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';+import { DocContentInsertService } from '../../services/doc-content-insert.service';import { getRichTextEditPath } from '../util';export interface ISetParagraphNamedStyleCommandParams {@@ -41,6 +42,11 @@ export const SetParagraphNamedStyleCommand: ICommand<ISetParagraphNamedStyleComm}const unitId = doc.getUnitId();const selectionService = accessor.get(DocSelectionManagerService);+ const contentInsertRange = params.textRanges ? null : consumeContentInsertRange(accessor, unitId);+ if (contentInsertRange) {+ return insertNamedStyleParagraph(accessor, doc, params.value, contentInsertRange.startOffset, contentInsertRange.endOffset);+ }+const selections = params.textRanges ?? selectionService.getTextRanges({ unitId, subUnitId: unitId });if (!selections?.length) {return false;@@ -79,6 +85,58 @@ export const SetParagraphNamedStyleCommand: ICommand<ISetParagraphNamedStyleComm},};+function consumeContentInsertRange(accessor: Parameters<ICommand['handler']>[0], unitId: string) {+ try {+ return accessor.get(DocContentInsertService).consumeInsertRange(unitId);+ } catch {+ return null;+ }+}++function insertNamedStyleParagraph(+ accessor: Parameters<ICommand['handler']>[0],+ doc: DocumentDataModel,+ namedStyleType: NamedStyleType,+ startOffset: number,+ endOffset: number+): boolean {+ const textX = BuildTextUtils.selection.replace({+ doc,+ selection: {+ startOffset,+ endOffset,+ collapsed: startOffset === endOffset,+ },+ body: {+ dataStream: '\r',+ paragraphs: [{+ startIndex: 0,+ paragraphStyle: {+ namedStyleType,+ headingId: !namedStyleType || namedStyleType === NamedStyleType.NORMAL_TEXT ? undefined : generateRandomId(6),+ },+ }],+ },+ });++ if (!textX) {+ return false;+ }++ const jsonX = JSONX.getInstance();+ const commandService = accessor.get(ICommandService);+ return Boolean(commandService.syncExecuteCommand<IRichTextEditingMutationParams>(RichTextEditingMutation.id, {+ actions: jsonX.editOp(textX.serialize(), getRichTextEditPath(doc)),+ isEditing: false,+ textRanges: [{+ startOffset,+ endOffset: startOffset,+ collapsed: true,+ }],+ unitId: doc.getUnitId(),+ }));+}+export const QuickHeadingCommand: ICommand<ISetParagraphNamedStyleCommandParams> = {id: 'doc.command.quick-heading',type: CommandType.COMMAND,diff --git a/packages/docs-ui/src/commands/commands/table/doc-table-create.command.ts b/packages/docs-ui/src/commands/commands/table/doc-table-create.command.tsindex 153cfe9303..f1e1d7516b 100644--- a/packages/docs-ui/src/commands/commands/table/doc-table-create.command.ts+++ b/packages/docs-ui/src/commands/commands/table/doc-table-create.command.ts@@ -20,6 +20,7 @@ import type { ITextRangeWithStyle } from '@univerjs/engine-render';import { CommandType, DataStreamTreeTokenType, ICommandService, IUniverInstanceService, JSONX, TextX, TextXActionType } from '@univerjs/core';import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';import { getTextRunAtPosition } from '../../../basics/paragraph';+import { DocContentInsertService } from '../../../services/doc-content-insert.service';import { DocMenuStyleService } from '../../../services/doc-menu-style.service';import { getCommandSkeleton, getRichTextEditPath } from '../../util';import { generateParagraphs } from '../break-line.command';@@ -46,14 +47,25 @@ export const CreateDocTableCommand: ICommand<ICreateDocTableCommandParams> = {const commandService = accessor.get(ICommandService);const docMenuStyleService = accessor.get(DocMenuStyleService);+ const docDataModel = univerInstanceService.getCurrentUniverDocInstance();+ if (docDataModel == null) {+ return false;+ }+ let contentInsertRange: ReturnType<DocContentInsertService['consumeInsertRange']> = null;+ try {+ contentInsertRange = accessor.get(DocContentInsertService).consumeInsertRange(docDataModel.getUnitId());+ } catch {+ contentInsertRange = null;+ }+const activeRange = docSelectionManagerService.getActiveTextRange();- if (activeRange == null) {+ if (activeRange == null && contentInsertRange == null) {return false;}- const { segmentId, segmentPage } = activeRange;- const docDataModel = univerInstanceService.getCurrentUniverDocInstance();+ const segmentId = contentInsertRange?.segmentId ?? activeRange?.segmentId ?? '';+ const segmentPage = activeRange?.segmentPage;const body = docDataModel?.getSelfOrHeaderFooterModel(segmentId).getBody();- if (docDataModel == null || body == null) {+ if (body == null) {return false;}@@ -64,7 +76,7 @@ export const CreateDocTableCommand: ICommand<ICreateDocTableCommandParams> = {if (skeleton == null) {return false;}- const { startOffset } = activeRange;+ const startOffset = contentInsertRange?.startOffset ?? activeRange!.startOffset;const paragraphs = body.paragraphs ?? [];const prevParagraph = paragraphs.find((p) => p.startIndex >= startOffset);diff --git a/packages/docs-ui/src/commands/operations/open-page-setting.operation.ts b/packages/docs-ui/src/commands/operations/open-page-setting.operation.tsindex d46b8cf219..276bd8c0e5 100644--- a/packages/docs-ui/src/commands/operations/open-page-setting.operation.ts+++ b/packages/docs-ui/src/commands/operations/open-page-setting.operation.ts@@ -14,10 +14,10 @@* limitations under the License.*/-import type { ICommand, PaperType } from '@univerjs/core';+import type { ICommand, ModernDocumentWidthMode, PaperType } from '@univerjs/core';import type { IConfirmPartMethodOptions } from '@univerjs/ui';import type { IDocPageSetupCommandParams } from '../commands/doc-page-setup.command';-import { CommandType, ICommandService, IConfirmService, LocaleService, PAGE_SIZE } from '@univerjs/core';+import { CommandType, DocumentFlavor, ICommandService, IConfirmService, LocaleService, MODERN_DOCUMENT_WIDTH, PAGE_SIZE } from '@univerjs/core';import { PAGE_SETTING_COMPONENT_ID } from '../../views/page-settings';import { DocPageSetupCommand } from '../commands/doc-page-setup.command';@@ -43,8 +43,16 @@ export const DocOpenPageSettingCommand: ICommand = {onConfirm: (result) => {disposable.dispose();if (!result) return;- const paperSize = PAGE_SIZE[result.paperSize as PaperType];++ const paperSize = result.mode === DocumentFlavor.MODERN+ ? {+ width: MODERN_DOCUMENT_WIDTH[result.modernWidth as ModernDocumentWidthMode],+ height: PAGE_SIZE.A4.height,+ }+ : PAGE_SIZE[result.paperSize as PaperType];+commandService.executeCommand(DocPageSetupCommand.id, {+ documentFlavor: result.mode,pageOrient: result.orientation,marginTop: result.margins.top,marginBottom: result.margins.bottom,diff --git a/packages/docs-ui/src/components/float-toolbar/FloatToolbar.stories.tsx b/packages/docs-ui/src/components/float-toolbar/FloatToolbar.stories.tsxindex 44bd2afac9..983b2053c4 100644--- a/packages/docs-ui/src/components/float-toolbar/FloatToolbar.stories.tsx+++ b/packages/docs-ui/src/components/float-toolbar/FloatToolbar.stories.tsx@@ -36,6 +36,7 @@ import {} from '../../commands/commands/inline-format.command';import enUS from '../../locale/en-US';import zhCN from '../../locale/zh-CN';+import { FLOAT_TEXT_STYLE_MENU_ID } from '../../menu/menu';import { menuSchema } from '../../menu/schema';import { FloatToolbar } from './FloatToolbar';@@ -95,6 +96,7 @@ export const Playground = {<div><FloatToolbaravaliableMenus={[+ FLOAT_TEXT_STYLE_MENU_ID,SetInlineFormatFontFamilyCommand.id,SetInlineFormatFontSizeCommand.id,SetInlineFormatBoldCommand.id,diff --git a/packages/docs-ui/src/components/float-toolbar/FloatToolbar.tsx b/packages/docs-ui/src/components/float-toolbar/FloatToolbar.tsxindex 945183858b..964f153b7f 100644--- a/packages/docs-ui/src/components/float-toolbar/FloatToolbar.tsx+++ b/packages/docs-ui/src/components/float-toolbar/FloatToolbar.tsx@@ -29,12 +29,14 @@ import {SetInlineFormatTextColorCommand,SetInlineFormatUnderlineCommand,} from '../../commands/commands/inline-format.command';+import { FLOAT_TEXT_STYLE_MENU_ID, FLOAT_TOOLBAR_MENU_POSITION } from '../../menu/menu';interface IFloatToolbarProps {avaliableMenus?: string[];}const DEFAULT_AVALIABLE_MENUS: string[] = [+ FLOAT_TEXT_STYLE_MENU_ID,SetInlineFormatFontSizeCommand.id,SetInlineFormatBoldCommand.id,SetInlineFormatItalicCommand.id,@@ -56,7 +58,10 @@ export function FloatToolbar(props: IFloatToolbarProps) {// subscribe to menu changesuseEffect(() => {function getRibbon(): void {- const flatMenus = menuManagerService.getFlatMenuByPositionKey(MenuManagerPosition.RIBBON);+ const flatMenus = [+ ...menuManagerService.getFlatMenuByPositionKey(FLOAT_TOOLBAR_MENU_POSITION),+ ...menuManagerService.getFlatMenuByPositionKey(MenuManagerPosition.RIBBON),+ ];const menus: IMenuSchema[] = [];for (const key of avaliableMenus) {diff --git a/packages/docs-ui/src/components/paragraph-menu/__tests__/paragraph-menu.spec.ts b/packages/docs-ui/src/components/paragraph-menu/__tests__/paragraph-menu.spec.tsnew file mode 100644index 0000000000..41d2930553--- /dev/null+++ b/packages/docs-ui/src/components/paragraph-menu/__tests__/paragraph-menu.spec.ts@@ -0,0 +1,215 @@+/**+ * 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 { NamedStyleType } from '@univerjs/core';++import { describe, expect, it } from 'vitest';+import { getParagraphMenuActiveHeadingCommandId, getParagraphMenuCommand, getParagraphMenuHiddenHeadingCommandIds, getParagraphMenuIconSizeClass, getParagraphMenuPopupDirection, getParagraphMenuTargetRange, isEmptyParagraphMenuTarget, shouldShowParagraphSettingMenu, shouldUseInsertBelowRange } from '..';+import { HorizontalLineCommand } from '../../../commands/commands/doc-horizontal-line.command';+import { BulletListCommand, InsertBulletListBellowCommand, OrderListCommand } from '../../../commands/commands/list.command';+import { H1HeadingCommand, H3HeadingCommand, H5HeadingCommand, NormalTextHeadingCommand, SetParagraphNamedStyleCommand, SubtitleHeadingCommand, TitleHeadingCommand } from '../../../commands/commands/set-heading.command';+import { CreateDocTableCommand } from '../../../commands/commands/table/doc-table-create.command';+import {+ EmptyParagraphBulletListMenuItemFactory,+ EmptyParagraphH1MenuItemFactory,+ EmptyParagraphHorizontalLineMenuItemFactory,+ HEADING_ICON_MAP,+ INSERT_BELLOW_MENU_ID,+ shouldShowParagraphHeadingOption,+ TableBlockCopyMenuItemFactory,+ TableBlockDeleteMenuItemFactory,+ TableBlockPasteMenuItemFactory,+} from '../../../menu/paragraph-menu';++describe('ParagraphMenu', () => {+ it('uses a smaller icon for normal text paragraph triggers', () => {+ expect(getParagraphMenuIconSizeClass('TextTypeIcon')).toBe('univer-size-3');+ expect(getParagraphMenuIconSizeClass('TitleTypeIcon')).toBe('univer-size-4');+ expect(getParagraphMenuIconSizeClass('SubtitleTypeIcon')).toBe('univer-size-4');+ expect(getParagraphMenuIconSizeClass('H1Icon')).toBe('univer-size-4');+ expect(HEADING_ICON_MAP[NamedStyleType.TITLE].key).toBe('TitleTypeIcon');+ expect(HEADING_ICON_MAP[NamedStyleType.SUBTITLE].key).toBe('SubtitleTypeIcon');+ });++ it('uses fully-qualified locale keys for paragraph context menu labels', () => {+ const accessor = {+ get: () => ({+ get: () => undefined,+ register: () => undefined,+ }),+ } as never;++ expect(EmptyParagraphH1MenuItemFactory(accessor).title).toBe('ui.toolbar.heading.1');+ expect(EmptyParagraphBulletListMenuItemFactory(accessor).title).toBe('docs-ui.rightClick.bulletList');+ expect(EmptyParagraphHorizontalLineMenuItemFactory(accessor).title).toBe('docs-ui.toolbar.horizontalLine');+ expect(TableBlockCopyMenuItemFactory(accessor).title).toBe('docs-ui.rightClick.copy');+ expect(TableBlockPasteMenuItemFactory(accessor).title).toBe('docs-ui.rightClick.paste');+ expect(TableBlockDeleteMenuItemFactory(accessor).title).toBe('docs-ui.rightClick.delete');+ });++ it('opens the popup away from the drag handle when there is not enough left space', () => {+ expect(getParagraphMenuPopupDirection(170)).toBe('right');+ expect(getParagraphMenuPopupDirection(260)).toBe('left');+ });++ it('shows title and subtitle heading shortcuts only when they are the current paragraph style', () => {+ expect(shouldShowParagraphHeadingOption(NamedStyleType.HEADING_5, NamedStyleType.NORMAL_TEXT)).toBe(true);+ expect(shouldShowParagraphHeadingOption(NamedStyleType.TITLE, NamedStyleType.NORMAL_TEXT)).toBe(false);+ expect(shouldShowParagraphHeadingOption(NamedStyleType.SUBTITLE, NamedStyleType.NORMAL_TEXT)).toBe(false);++ expect(shouldShowParagraphHeadingOption(NamedStyleType.HEADING_5, NamedStyleType.TITLE)).toBe(false);+ expect(shouldShowParagraphHeadingOption(NamedStyleType.TITLE, NamedStyleType.TITLE)).toBe(true);+ expect(shouldShowParagraphHeadingOption(NamedStyleType.SUBTITLE, NamedStyleType.TITLE)).toBe(false);++ expect(shouldShowParagraphHeadingOption(NamedStyleType.HEADING_5, NamedStyleType.SUBTITLE)).toBe(false);+ expect(shouldShowParagraphHeadingOption(NamedStyleType.TITLE, NamedStyleType.SUBTITLE)).toBe(false);+ expect(shouldShowParagraphHeadingOption(NamedStyleType.SUBTITLE, NamedStyleType.SUBTITLE)).toBe(true);+ });++ it('maps paragraph named styles to the active heading menu item', () => {+ expect(getParagraphMenuActiveHeadingCommandId(NamedStyleType.HEADING_1)).toBe(H1HeadingCommand.id);+ expect(getParagraphMenuActiveHeadingCommandId(NamedStyleType.HEADING_3)).toBe(H3HeadingCommand.id);+ expect(getParagraphMenuActiveHeadingCommandId(NamedStyleType.NORMAL_TEXT)).toBe(NormalTextHeadingCommand.id);+ expect(getParagraphMenuActiveHeadingCommandId(undefined)).toBe(NormalTextHeadingCommand.id);+ expect(getParagraphMenuActiveHeadingCommandId(NamedStyleType.TITLE)).toBe(TitleHeadingCommand.id);+ expect(getParagraphMenuActiveHeadingCommandId(NamedStyleType.SUBTITLE)).toBe(SubtitleHeadingCommand.id);+ });++ it('hides the alternate title shortcuts for the hovered paragraph style', () => {+ expect(getParagraphMenuHiddenHeadingCommandIds(NamedStyleType.TITLE)).toEqual([+ H5HeadingCommand.id,+ SubtitleHeadingCommand.id,+ ]);+ expect(getParagraphMenuHiddenHeadingCommandIds(NamedStyleType.SUBTITLE)).toEqual([+ H5HeadingCommand.id,+ TitleHeadingCommand.id,+ ]);+ expect(getParagraphMenuHiddenHeadingCommandIds(NamedStyleType.NORMAL_TEXT)).toEqual([+ TitleHeadingCommand.id,+ SubtitleHeadingCommand.id,+ ]);+ });++ it('shows paragraph settings only for paragraph and list menu targets', () => {+ expect(shouldShowParagraphSettingMenu(null)).toBe(true);+ expect(shouldShowParagraphSettingMenu({ kind: 'paragraph' } as never)).toBe(true);+ expect(shouldShowParagraphSettingMenu({ kind: 'paragraph', icon: 'OrderIcon' } as never)).toBe(true);+ expect(shouldShowParagraphSettingMenu({ kind: 'blockRange' } as never)).toBe(false);+ expect(shouldShowParagraphSettingMenu({ kind: 'table' } as never)).toBe(false);+ expect(shouldShowParagraphSettingMenu({ kind: 'customBlock' } as never)).toBe(false);+ });++ it('detects empty paragraph menu targets', () => {+ const paragraph = {+ paragraphStart: 2,+ paragraphEnd: 2,+ };+ const nonEmptyParagraph = {+ paragraphStart: 2,+ paragraphEnd: 3,+ };++ expect(isEmptyParagraphMenuTarget('a\r\r', paragraph as never)).toBe(true);+ expect(isEmptyParagraphMenuTarget('a\r\r', { paragraphStart: 1, paragraphEnd: 2 } as never)).toBe(true);+ expect(isEmptyParagraphMenuTarget('a\n\n', { paragraphStart: 1, paragraphEnd: 2 } as never)).toBe(true);+ expect(isEmptyParagraphMenuTarget('a\rb\r', nonEmptyParagraph as never)).toBe(false);+ });++ it('builds a collapsed selection range for the hovered paragraph', () => {+ expect(getParagraphMenuTargetRange({+ paragraphStart: 3,+ paragraphEnd: 8,+ segmentId: 'header-1',+ } as never)).toEqual({+ collapsed: true,+ endOffset: 3,+ segmentId: 'header-1',+ startOffset: 3,+ });+ });++ it('preserves context menu command params for paragraph menu actions', () => {+ expect(getParagraphMenuCommand({+ commandId: CreateDocTableCommand.id,+ id: 'doc.operation.create-table',+ label: 'doc.operation.create-table',+ params: { rowCount: 3, colCount: 5 },+ })).toEqual({+ commandId: CreateDocTableCommand.id,+ params: { rowCount: 3, colCount: 5 },+ });++ expect(getParagraphMenuCommand({+ label: 'doc.command.h1-heading',+ }, { startOffset: 3, endOffset: 3, collapsed: true })).toEqual({+ commandId: SetParagraphNamedStyleCommand.id,+ params: {+ value: NamedStyleType.HEADING_1,+ textRanges: [{ startOffset: 3, endOffset: 3, collapsed: true }],+ },+ });+ });++ it('passes the hovered paragraph range to current-paragraph menu commands', () => {+ const targetRange = { startOffset: 3, endOffset: 3, collapsed: true };++ expect(getParagraphMenuCommand({+ label: BulletListCommand.id,+ }, targetRange)).toEqual({+ commandId: BulletListCommand.id,+ params: { docRange: [targetRange] },+ });+ expect(getParagraphMenuCommand({+ label: OrderListCommand.id,+ }, targetRange)).toEqual({+ commandId: OrderListCommand.id,+ params: { docRange: [targetRange] },+ });+ expect(getParagraphMenuCommand({+ label: HorizontalLineCommand.id,+ }, targetRange)).toEqual({+ commandId: HorizontalLineCommand.id,+ params: { insertRange: targetRange },+ });+ expect(getParagraphMenuCommand({+ label: H1HeadingCommand.id,+ }, null)).toEqual({+ commandId: H1HeadingCommand.id,+ params: undefined,+ });+ });++ it('detects menu commands that should use the hovered block insert-below anchor', () => {+ expect(shouldUseInsertBelowRange(InsertBulletListBellowCommand.id, {+ id: InsertBulletListBellowCommand.id,+ })).toBe(true);+ expect(shouldUseInsertBelowRange('docs-callout.command.insert-below', {+ id: 'docs-callout.command.insert-below',+ })).toBe(true);+ expect(shouldUseInsertBelowRange('doc.command.insert-float-image', {+ id: 'doc.command.insert-float-image',+ })).toBe(true);+ expect(shouldUseInsertBelowRange(CreateDocTableCommand.id, {+ id: 'doc.operation.create-table',+ })).toBe(true);+ expect(shouldUseInsertBelowRange(H1HeadingCommand.id, {+ id: H1HeadingCommand.id,+ })).toBe(false);+ expect(shouldUseInsertBelowRange(H1HeadingCommand.id, {+ id: INSERT_BELLOW_MENU_ID,+ })).toBe(true);+ });+});diff --git a/packages/docs-ui/src/components/paragraph-menu/index.tsx b/packages/docs-ui/src/components/paragraph-menu/index.tsxindex 79801454ca..ff9e6730bb 100644--- a/packages/docs-ui/src/components/paragraph-menu/index.tsx+++ b/packages/docs-ui/src/components/paragraph-menu/index.tsx@@ -15,37 +15,208 @@*/import type { DocumentDataModel } from '@univerjs/core';-import type { IPopup } from '@univerjs/ui';-import { ICommandService, IUniverInstanceService, NamedStyleType, UniverInstanceType } from '@univerjs/core';-import { borderClassName, clsx } from '@univerjs/design';+import type { ITextRangeWithStyle } from '@univerjs/engine-render';+import type { IPopup, IValueOption } from '@univerjs/ui';+import type { IMutiPageParagraphBound } from '../../services/doc-event-manager.service';+import type { IDocBlockMenuTarget } from '../../services/doc-paragraph-menu.service';+import { ICommandService, IUniverInstanceService, NamedStyleType, SliceBodyType, UniverInstanceType } from '@univerjs/core';+import { clsx } from '@univerjs/design';+import { DocSelectionManagerService } from '@univerjs/docs';import { IRenderManagerService } from '@univerjs/engine-render';-import { DownIcon } from '@univerjs/icons';-import { ContextMenuPanel, ContextMenuPosition, ILayoutService, RectPopup, useDependency, useObservable } from '@univerjs/ui';-import { useMemo, useRef, useState } from 'react';+import { ComponentManager, ContextMenuPanel, ContextMenuPosition, IClipboardInterfaceService, ILayoutService, RectPopup, useDependency, useObservable } from '@univerjs/ui';+import { useEffect, useMemo, useRef, useState } from 'react';import { BehaviorSubject } from 'rxjs';-import { HEADING_ICON_MAP } from '../../menu/paragraph-menu';+import { DocCopyCommand, DocPasteCommand } from '../../commands/commands/clipboard.command';+import { MoveDocBlockCommand } from '../../commands/commands/doc-block-move.command';+import { HorizontalLineCommand } from '../../commands/commands/doc-horizontal-line.command';+import { BulletListCommand, CheckListCommand, OrderListCommand } from '../../commands/commands/list.command';+import { H1HeadingCommand, H2HeadingCommand, H3HeadingCommand, H4HeadingCommand, H5HeadingCommand, NormalTextHeadingCommand, SetParagraphNamedStyleCommand, SubtitleHeadingCommand, TitleHeadingCommand } from '../../commands/commands/set-heading.command';+import { DocTableDeleteTableCommand } from '../../commands/commands/table/doc-table-delete.command';+import { DocParagraphSettingPanelOperation } from '../../commands/operations/doc-paragraph-setting-panel.operation';+import { DOC_TABLE_BLOCK_MENU_ID, EMPTY_PARAGRAPH_MENU_ID, HEADING_ICON_MAP, INSERT_BELLOW_MENU_ID } from '../../menu/paragraph-menu';+import { IDocClipboardService } from '../../services/clipboard/clipboard.service';+import { DocContentInsertService } from '../../services/doc-content-insert.service';import { DocEventManagerService } from '../../services/doc-event-manager.service';import { DocParagraphMenuService } from '../../services/doc-paragraph-menu.service';+export function getParagraphMenuIconSizeClass(iconKey: string): string {+ return iconKey === 'TextTypeIcon' ? 'univer-size-3' : 'univer-size-4';+}++export function getParagraphMenuPopupDirection(anchorLeft: number, menuWidth = 212, viewportPadding = 8): 'left' | 'right' {+ return anchorLeft - menuWidth < viewportPadding ? 'right' : 'left';+}++export function isEmptyParagraphMenuTarget(dataStream: string, paragraph?: IMutiPageParagraphBound | null | void): boolean {+ if (!paragraph) {+ return false;+ }++ return dataStream.slice(paragraph.paragraphStart, paragraph.paragraphEnd).replace(/[\r\n]/g, '') === '';+}++export function getParagraphMenuTargetRange(paragraph?: IMutiPageParagraphBound | null | void): ITextRangeWithStyle | null {+ if (!paragraph) {+ return null;+ }++ const blockRange = (paragraph as IMutiPageParagraphBound & { blockRange?: { endIndex: number; startIndex: number } }).blockRange;+ if (blockRange) {+ return {+ startOffset: blockRange.startIndex,+ endOffset: blockRange.endIndex + 1,+ collapsed: false,+ segmentId: paragraph.segmentId,+ };+ }++ return {+ startOffset: paragraph.paragraphStart,+ endOffset: paragraph.paragraphStart,+ collapsed: true,+ segmentId: paragraph.segmentId,+ };+}++const HEADING_COMMAND_VALUES: Record<string, NamedStyleType> = {+ [H1HeadingCommand.id]: NamedStyleType.HEADING_1,+ [H2HeadingCommand.id]: NamedStyleType.HEADING_2,+ [H3HeadingCommand.id]: NamedStyleType.HEADING_3,+ [H4HeadingCommand.id]: NamedStyleType.HEADING_4,+ [H5HeadingCommand.id]: NamedStyleType.HEADING_5,+ [NormalTextHeadingCommand.id]: NamedStyleType.NORMAL_TEXT,+ [TitleHeadingCommand.id]: NamedStyleType.TITLE,+ [SubtitleHeadingCommand.id]: NamedStyleType.SUBTITLE,+};++const NAMED_STYLE_HEADING_COMMAND_IDS: Partial<Record<NamedStyleType, string>> = {+ [NamedStyleType.HEADING_1]: H1HeadingCommand.id,+ [NamedStyleType.HEADING_2]: H2HeadingCommand.id,+ [NamedStyleType.HEADING_3]: H3HeadingCommand.id,+ [NamedStyleType.HEADING_4]: H4HeadingCommand.id,+ [NamedStyleType.HEADING_5]: H5HeadingCommand.id,+ [NamedStyleType.NORMAL_TEXT]: NormalTextHeadingCommand.id,+ [NamedStyleType.TITLE]: TitleHeadingCommand.id,+ [NamedStyleType.SUBTITLE]: SubtitleHeadingCommand.id,+};++export function getParagraphMenuActiveHeadingCommandId(namedStyleType?: NamedStyleType): string {+ return NAMED_STYLE_HEADING_COMMAND_IDS[namedStyleType ?? NamedStyleType.NORMAL_TEXT] ?? NormalTextHeadingCommand.id;+}++export function getParagraphMenuHiddenHeadingCommandIds(namedStyleType?: NamedStyleType): string[] {+ if (namedStyleType === NamedStyleType.TITLE) {+ return [H5HeadingCommand.id, SubtitleHeadingCommand.id];+ }++ if (namedStyleType === NamedStyleType.SUBTITLE) {+ return [H5HeadingCommand.id, TitleHeadingCommand.id];+ }++ return [TitleHeadingCommand.id, SubtitleHeadingCommand.id];+}++export function getParagraphMenuCommand(params: IValueOption, targetRange?: ITextRangeWithStyle | null): { commandId?: string; params?: object } {+ const commandId = params.commandId ?? params.id ?? (typeof params.label === 'string' ? params.label : undefined);+ if (commandId && targetRange && commandId in HEADING_COMMAND_VALUES) {+ return {+ commandId: SetParagraphNamedStyleCommand.id,+ params: {+ value: HEADING_COMMAND_VALUES[commandId],+ textRanges: [targetRange],+ },+ };+ }++ if (commandId && targetRange && (commandId === BulletListCommand.id || commandId === OrderListCommand.id || commandId === CheckListCommand.id)) {+ return {+ commandId,+ params: {+ docRange: [targetRange],+ },+ };+ }++ if (commandId === HorizontalLineCommand.id && targetRange) {+ return {+ commandId,+ params: {+ insertRange: targetRange,+ },+ };+ }++ const fallbackParams = typeof params.params === 'function' ? params.params() : params.params;+ const commandParams = typeof params.value === 'undefined'+ ? fallbackParams+ : { value: params.value };++ return {+ commandId,+ params: commandParams && typeof commandParams === 'object' ? commandParams : undefined,+ };+}++function getParagraphMenuType(target: IDocBlockMenuTarget | null | undefined, emptyMode: boolean): string {+ if (target?.kind === 'table') {+ return DOC_TABLE_BLOCK_MENU_ID;+ }++ return emptyMode ? EMPTY_PARAGRAPH_MENU_ID : ContextMenuPosition.PARAGRAPH;+}++export function shouldShowParagraphSettingMenu(target: IDocBlockMenuTarget | null | undefined): boolean {+ return !target || target.kind === 'paragraph';+}+export const ParagraphMenu = ({ popup }: { popup: IPopup }) => {const [visible, setVisible] = useState(false);+ const [emptyMode, setEmptyMode] = useState(false);+ const [dropRect, setDropRect] = useState<{ left: number; right: number; top: number; bottom: number } | null>(null);+ const [menuDirection, setMenuDirection] = useState<'left' | 'right'>('left');const contentRef = useRef<HTMLDivElement>(null);+ const targetRangeRef = useRef<ITextRangeWithStyle | null>(null);+ const dragTargetOffsetRef = useRef<number | null>(null);+ const dragRangeRef = useRef<{ startOffset: number; endOffset: number } | null>(null);+ const isDraggingRef = useRef(false);const commandService = useDependency(ICommandService);+ const docSelectionManagerService = useDependency(DocSelectionManagerService);+ const docClipboardService = useDependency(IDocClipboardService);+ const docContentInsertService = useDependency(DocContentInsertService);+ const clipboardInterfaceService = useDependency(IClipboardInterfaceService);const layoutService = useDependency(ILayoutService);+ const componentManager = useDependency(ComponentManager);const anchorRef = useRef<HTMLDivElement>(null);const isMouseOver = useRef(false);+ const hideTimerRef = useRef<number | null>(null);const renderManagerService = useDependency(IRenderManagerService);const univerInstanceService = useDependency(IUniverInstanceService);const renderUnit = renderManagerService.getRenderById(popup.unitId);const doc = univerInstanceService.getUnit<DocumentDataModel>(popup.unitId, UniverInstanceType.UNIVER_DOC);const docParagraphMenuService = renderUnit?.with(DocParagraphMenuService);const docEventManagerService = renderUnit?.with(DocEventManagerService);+ const activeTarget = useObservable(docParagraphMenuService?.activeTarget$);const paragraph = useObservable(docEventManagerService?.hoverParagraph$);const paragraphLeft = useObservable(docEventManagerService?.hoverParagraphLeft$);- const startIndex = (paragraph ?? paragraphLeft)?.startIndex;- const paragraphObj = useMemo(() => doc?.getBody()?.paragraphs?.find((p) => p.startIndex === startIndex), [doc, paragraph]);+ const currentActiveTarget = activeTarget ?? docParagraphMenuService?.activeTarget;+ const activeParagraphBound = currentActiveTarget?.paragraph ?? docParagraphMenuService?.activeParagraph ?? paragraph ?? paragraphLeft;+ const startIndex = activeParagraphBound?.startIndex;+ const dataStream = doc?.getBody()?.dataStream ?? '';+ const paragraphObj = useMemo(() => doc?.getBody()?.paragraphs?.find((p) => p.startIndex === startIndex), [doc, startIndex]);+ const isEmptyParagraph = currentActiveTarget?.emptyMode ?? isEmptyParagraphMenuTarget(dataStream, activeParagraphBound);const namedStyleType = paragraphObj?.paragraphStyle?.namedStyleType;+ const activeHeadingCommandId = getParagraphMenuActiveHeadingCommandId(namedStyleType);+ const hiddenHeadingCommandIds = useMemo(() => getParagraphMenuHiddenHeadingCommandIds(namedStyleType), [namedStyleType]);+ const hiddenItemIds = useMemo(() => {+ if (!shouldShowParagraphSettingMenu(currentActiveTarget)) {+ return [...hiddenHeadingCommandIds, DocParagraphSettingPanelOperation.id];+ }++ return hiddenHeadingCommandIds;+ }, [currentActiveTarget, hiddenHeadingCommandIds]);const icon = HEADING_ICON_MAP[namedStyleType ?? NamedStyleType.NORMAL_TEXT];+ const targetIconKey = currentActiveTarget?.icon ?? icon.key;+ const TargetIcon = componentManager.get(targetIconKey) ?? icon.component;const anchorRect$ = useMemo(() => new BehaviorSubject({left: 0,right: 0,@@ -53,84 +224,272 @@ export const ParagraphMenu = ({ popup }: { popup: IPopup }) => {bottom: 0,}), []);+ const updateAnchorRect = () => {+ const boundingRect = anchorRef.current?.getBoundingClientRect();+ const left = (boundingRect?.left ?? 0) - 4;+ setMenuDirection(getParagraphMenuPopupDirection(left));+ anchorRect$.next({+ left,+ right: boundingRect?.right ?? 0,+ top: boundingRect?.top ?? 0,+ bottom: boundingRect?.bottom ?? 0,+ });+ };+const handleHideMenu = () => {setVisible(false);- docParagraphMenuService?.hideParagraphMenu(true);+ targetRangeRef.current = null;+ };++ const clearHideTimer = () => {+ if (hideTimerRef.current != null) {+ window.clearTimeout(hideTimerRef.current);+ hideTimerRef.current = null;+ }};+ const scheduleHideMenu = () => {+ clearHideTimer();+ hideTimerRef.current = window.setTimeout(() => {+ if (!isMouseOver.current && !isDraggingRef.current) {+ handleHideMenu();+ }+ }, 180);+ };++ const handleOpenMenu = () => {+ clearHideTimer();+ const latestTarget = docParagraphMenuService?.activeTarget ?? activeTarget;+ const targetRange = latestTarget+ ? {+ ...latestTarget.menuRange,+ segmentId: activeParagraphBound?.segmentId,+ }+ : getParagraphMenuTargetRange(activeParagraphBound);+ targetRangeRef.current = targetRange;+ updateAnchorRect();+ setEmptyMode(isEmptyParagraph);+ setVisible(true);+ };++ useEffect(() => () => clearHideTimer(), []);+return (<><divdata-u-comp="paragraph-menu"ref={anchorRef}className={clsx(`- univer-mr-1 univer-inline-flex univer-h-7 univer-cursor-pointer univer-items-center univer-gap-1- univer-rounded-full univer-px-2.5 univer-py-0- hover:univer-bg-gray-100- dark:hover:!univer-bg-gray-600- `, borderClassName, {- 'univer-bg-gray-100 dark:!univer-bg-gray-700': visible,- 'univer-bg-white dark:!univer-bg-gray-700': !visible,+ univer-mr-1 univer-inline-flex univer-h-8 univer-cursor-pointer univer-items-center univer-gap-1.5+ univer-rounded-lg univer-border univer-border-gray-200 univer-bg-white univer-px-2.5 univer-py-0+ univer-shadow-sm univer-transition-colors+ hover:univer-bg-gray-50 hover:univer-shadow-md+ dark:!univer-border-gray-700 dark:!univer-bg-gray-900+ dark:hover:!univer-bg-gray-800+ `, {+ 'univer-bg-gray-100 univer-shadow-md dark:!univer-bg-gray-800': visible,})}onMouseEnter={(e) => {popup.onPointerEnter?.(e);isMouseOver.current = true;- const boundingRect = anchorRef.current?.getBoundingClientRect();- anchorRect$.next({- left: (boundingRect?.left ?? 0) - 4,- right: boundingRect?.right ?? 0,- top: boundingRect?.top ?? 0,- bottom: boundingRect?.bottom ?? 0,- });+ handleOpenMenu();}}onMouseLeave={() => {isMouseOver.current = false;+ scheduleHideMenu();}}- onClick={() => {- setVisible(true);- docParagraphMenuService?.setParagraphMenuActive(true);+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ isMouseOver.current = true;+ handleOpenMenu();}}>- <icon.component- className={`- univer-size-4 univer-text-gray-900- dark:!univer-text-white- `}- />- <DownIcon- className={`- univer-size-3 univer-text-gray-600- dark:!univer-text-gray-200- `}+ <TargetIcon+ className={clsx(+ getParagraphMenuIconSizeClass(targetIconKey),+ `+ univer-text-gray-700+ dark:!univer-text-white+ `+ )}/>+ {currentActiveTarget?.draggable && (+ <button+ type="button"+ className={`+ univer-group univer-flex univer-h-4 univer-w-2.5 univer-cursor-grab univer-items-center+ univer-justify-center univer-border-none univer-bg-transparent univer-p-0+ active:univer-cursor-grabbing+ `}+ aria-label="Drag block"+ title="Drag block"+ onPointerDown={(event) => {+ const latestTarget = docParagraphMenuService?.activeTarget ?? activeTarget;+ const moveRange = latestTarget?.moveRange;+ if (!moveRange || !latestTarget?.draggable) {+ return;+ }++ event.preventDefault();+ event.stopPropagation();+ event.currentTarget.setPointerCapture?.(event.pointerId);+ clearHideTimer();+ isMouseOver.current = true;+ isDraggingRef.current = true;+ docParagraphMenuService?.setBlockMenuDragging(true);+ dragRangeRef.current = moveRange;+ dragTargetOffsetRef.current = null;+ setDropRect(null);+ const pointerId = event.pointerId;++ const handlePointerMove = (moveEvent: PointerEvent) => {+ if (moveEvent.pointerId !== pointerId) {+ return;+ }++ moveEvent.preventDefault();+ const range = dragRangeRef.current;+ if (!range) {+ return;+ }++ const target = docParagraphMenuService?.getDropTargetFromClientPoint(moveEvent.clientX, moveEvent.clientY, range);+ dragTargetOffsetRef.current = target?.targetOffset ?? null;+ setDropRect(target?.rect ?? null);+ };+ const finishDrag = (shouldDrop: boolean) => {+ window.removeEventListener('pointermove', handlePointerMove);+ window.removeEventListener('pointerup', handlePointerUp);+ window.removeEventListener('pointercancel', handlePointerCancel);+ window.removeEventListener('blur', handleWindowBlur);+ const range = dragRangeRef.current;+ const targetOffset = dragTargetOffsetRef.current;+ dragRangeRef.current = null;+ dragTargetOffsetRef.current = null;+ isDraggingRef.current = false;+ docParagraphMenuService?.setBlockMenuDragging(false);+ setDropRect(null);++ if (shouldDrop && range && targetOffset != null) {+ commandService.executeCommand(MoveDocBlockCommand.id, {+ unitId: popup.unitId,+ sourceRange: range,+ targetOffset,+ });+ }+ };+ const handlePointerUp = (upEvent: PointerEvent) => {+ if (upEvent.pointerId !== pointerId) {+ return;+ }++ upEvent.preventDefault();+ finishDrag(true);+ };+ const handlePointerCancel = (cancelEvent: PointerEvent) => {+ if (cancelEvent.pointerId !== pointerId) {+ return;+ }++ finishDrag(false);+ };+ const handleWindowBlur = () => {+ finishDrag(false);+ };++ window.addEventListener('pointermove', handlePointerMove);+ window.addEventListener('pointerup', handlePointerUp);+ window.addEventListener('pointercancel', handlePointerCancel);+ window.addEventListener('blur', handleWindowBlur, { once: true });+ }}+ >+ <DragHandleDotsIcon />+ </button>+ )}</div>{visible && (<RectPopupportal- mask- maskZIndex={100}anchorRect$={anchorRect$}- direction="left"- onMaskClick={handleHideMenu}+ direction={menuDirection}><sectionref={contentRef}onMouseEnter={(e) => {popup.onPointerEnter?.(e);isMouseOver.current = true;+ clearHideTimer();}}onMouseLeave={() => {isMouseOver.current = false;+ scheduleHideMenu();}}><ContextMenuPanelclassName="univer-w-[212px]"- menuType={ContextMenuPosition.PARAGRAPH}- onOptionSelect={(params) => {- const { label: id, commandId, value } = params;+ menuType={getParagraphMenuType(currentActiveTarget, emptyMode)}+ activeItemIds={[activeHeadingCommandId]}+ hiddenItemIds={hiddenItemIds}+ onOptionSelect={async (params) => {+ const targetRange = targetRangeRef.current ?? getParagraphMenuTargetRange(activeParagraphBound);+ const { commandId, params: commandParams } = getParagraphMenuCommand(params, targetRange);+ const latestTarget = docParagraphMenuService?.activeTarget ?? activeTarget;++ if (commandId && shouldUseInsertBelowRange(commandId, params) && latestTarget?.moveRange) {+ docContentInsertService.setInsertRange({+ unitId: popup.unitId,+ startOffset: latestTarget.moveRange.endOffset,+ endOffset: latestTarget.moveRange.endOffset,+ segmentId: targetRange?.segmentId ?? '',+ });+ }++ if (latestTarget?.kind === 'table' && commandId && targetRange) {+ const tableRange = {+ ...targetRange,+ segmentId: targetRange.segmentId ?? '',+ collapsed: false,+ };+ const afterTableRange = {+ startOffset: latestTarget.moveRange.endOffset,+ endOffset: latestTarget.moveRange.endOffset,+ collapsed: true,+ segmentId: targetRange.segmentId ?? '',+ };++ if (commandId === DocCopyCommand.id || commandId === DocCopyCommand.name) {+ await docClipboardService.copy(SliceBodyType.copy, [tableRange]);+ layoutService.focus();+ handleHideMenu();+ return;+ }++ if (commandId === DocPasteCommand.id) {+ docSelectionManagerService.replaceTextRanges([afterTableRange], false);+ const clipboardItems = await clipboardInterfaceService.read();+ await docClipboardService.paste(clipboardItems);+ layoutService.focus();+ handleHideMenu();+ return;+ }++ if (commandId === DocTableDeleteTableCommand.id) {+ docSelectionManagerService.replaceTextRanges([tableRange], false);+ } else if (params.id === INSERT_BELLOW_MENU_ID || commandId !== INSERT_BELLOW_MENU_ID) {+ docSelectionManagerService.replaceTextRanges([afterTableRange], false);+ }+ }- if (commandService) {- commandService.executeCommand(commandId ?? id as string, { value });+ if (commandService && commandId) {+ const blockRangeParams = latestTarget?.kind === 'blockRange' && latestTarget.blockRange && commandParams && typeof commandParams === 'object'+ ? {+ ...commandParams,+ unitId: popup.unitId,+ blockId: latestTarget.blockRange.blockId,+ }+ : commandParams;+ commandService.executeCommand(commandId, blockRangeParams);}layoutService.focus();@@ -140,6 +499,62 @@ export const ParagraphMenu = ({ popup }: { popup: IPopup }) => {</section></RectPopup>)}+ {dropRect && (+ <div+ className="+ univer-pointer-events-none univer-fixed univer-z-[10000] univer-h-0.5 univer-rounded-full+ univer-bg-primary-600+ "+ style={{+ left: dropRect.left,+ top: dropRect.top,+ width: Math.max(60, dropRect.right - dropRect.left),+ }}+ />+ )}</>);};++export function shouldUseInsertBelowRange(commandId: string, params: IValueOption): boolean {+ if (params.id === INSERT_BELLOW_MENU_ID) {+ return true;+ }++ const normalized = commandId.toLowerCase();++ if (normalized.includes('insert') && (normalized.includes('below') || normalized.includes('bellow'))) {+ return true;+ }++ if (normalized.includes('insert') && normalized.includes('image')) {+ return true;+ }++ return normalized === 'doc.command.create-table' || normalized === 'doc.operation.create-table';+}++function DragHandleDotsIcon() {+ return (+ <span+ className={`+ univer-grid univer-h-3.5 univer-w-2 univer-grid-cols-2 univer-place-items-center univer-gap-x-0.5+ univer-gap-y-px+ `}+ aria-hidden="true"+ >+ {Array.from({ length: 6 }).map((_, index) => (+ <span+ // eslint-disable-next-line react/no-array-index-key+ key={index}+ className={`+ univer-size-0.5 univer-rounded-full univer-bg-gray-400 univer-transition-colors+ group-hover:univer-bg-gray-500+ dark:!univer-bg-gray-500+ dark:group-hover:!univer-bg-gray-300+ `}+ />+ ))}+ </span>+ );+}diff --git a/packages/docs-ui/src/controllers/__tests__/doc-render-controller.spec.ts b/packages/docs-ui/src/controllers/__tests__/doc-render-controller.spec.tsnew file mode 100644index 0000000000..b3c68d5810--- /dev/null+++ b/packages/docs-ui/src/controllers/__tests__/doc-render-controller.spec.ts@@ -0,0 +1,186 @@+/**+ * 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 { ICommandInfo } from '@univerjs/core';+import { DocumentFlavor } from '@univerjs/core';+import { RichTextEditingMutation } from '@univerjs/docs';+import { Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { DocRenderController } from '../render-controllers/doc.render-controller';++vi.mock('@univerjs/engine-render', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@univerjs/engine-render')>();+ const PageLayoutType = {+ VERTICAL: 0,+ HORIZONTAL: 1,+ };++ class MockDocComponent {+ width = 0;+ height = 0;+ pageMarginLeft: number;+ pageMarginTop: number;+ pageLayoutType = PageLayoutType.VERTICAL;+ zIndex = 0;++ constructor(_key: string, _skeleton?: unknown, config?: { pageMarginLeft?: number; pageMarginTop?: number }) {+ this.pageMarginLeft = config?.pageMarginLeft ?? 0;+ this.pageMarginTop = config?.pageMarginTop ?? 0;+ }++ changeSkeleton() {+ return this;+ }++ resize(width: number, height: number) {+ this.width = width;+ this.height = height;+ return this;+ }++ makeDirty() {+ return this;+ }+ }++ return {+ ...actual,+ DOCS_COMPONENT_BACKGROUND_LAYER_INDEX: 0,+ DocBackground: MockDocComponent,+ Documents: MockDocComponent,+ IRenderManagerService: () => undefined,+ Layer: class MockLayer {+ constructor(..._args: unknown[]) { }+ },+ PageLayoutType,+ ScrollBar: class MockScrollBar {+ constructor(..._args: unknown[]) { }+ },+ Viewport: class MockViewport {+ constructor(..._args: unknown[]) { }+ onMouseWheel() { }+ },+ };+});++function createControllerFixture() {+ const commandCallbacks: Array<(command: ICommandInfo) => void> = [];+ const skeleton = {+ calculate: vi.fn(),+ getSkeletonData: vi.fn(() => ({+ pages: [{+ pageWidth: 640,+ pageHeight: 900,+ }],+ })),+ getViewModel: vi.fn(() => ({+ getDataModel: vi.fn(() => ({+ getSnapshot: vi.fn(() => ({ disabled: false })),+ })),+ })),+ };+ const skeletonManager = {+ currentSkeletonBefore$: new Subject(),+ getSkeleton: vi.fn(() => skeleton),+ };+ const context = {+ unitId: 'doc-unit',+ unit: {+ getUnitId: vi.fn(() => 'doc-unit'),+ getSnapshot: vi.fn(() => ({+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ },+ })),+ },+ scene: {+ attachControl: vi.fn(),+ onMouseWheel$: { subscribeEvent: vi.fn() },+ addLayer: vi.fn(),+ addObjects: vi.fn(),+ enableLayerCache: vi.fn(),+ resize: vi.fn(),+ },+ engine: {+ runRenderLoop: vi.fn(),+ stopRenderLoop: vi.fn(),+ getCanvas: vi.fn(() => ({+ getCanvasEle: vi.fn(() => ({ style: {} })),+ })),+ },+ components: new Map(),+ activated$: new Subject<boolean>(),+ };+ const commandService = {+ onCommandExecuted: vi.fn((callback) => {+ commandCallbacks.push(callback);+ return { dispose: vi.fn() };+ }),+ };+ const pageLayoutService = {+ calculatePagePosition: vi.fn(),+ };+ const selectionManager = {+ refreshSelection: vi.fn(),+ };++ const Controller = DocRenderController as unknown as new (...args: unknown[]) => DocRenderController;+ new Controller(+ context,+ commandService,+ { __attachScrollEvent: vi.fn() },+ skeletonManager,+ {+ isEditor: vi.fn(() => false),+ getEditor: vi.fn(() => null),+ },+ {+ getRenderById: vi.fn(() => ({+ with: vi.fn(() => skeletonManager),+ })),+ },+ {+ getCurrentUnitOfType: vi.fn(() => ({+ getUnitId: vi.fn(() => 'doc-unit'),+ })),+ },+ pageLayoutService,+ selectionManager+ );++ return {+ commandCallbacks,+ pageLayoutService,+ selectionManager,+ };+}++describe('doc render controller', () => {+ it('refreshes page layout and selection after rich text mutations resize the document', () => {+ const { commandCallbacks, pageLayoutService, selectionManager } = createControllerFixture();++ commandCallbacks[0]({+ id: RichTextEditingMutation.id,+ params: {+ unitId: 'doc-unit',+ actions: [],+ },+ } as unknown as ICommandInfo);++ expect(pageLayoutService.calculatePagePosition).toHaveBeenCalledTimes(1);+ expect(selectionManager.refreshSelection).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/docs-ui/src/controllers/doc-ui.controller.ts b/packages/docs-ui/src/controllers/doc-ui.controller.tsindex 41646b9e7d..271eab9c4c 100644--- a/packages/docs-ui/src/controllers/doc-ui.controller.ts+++ b/packages/docs-ui/src/controllers/doc-ui.controller.ts@@ -30,7 +30,7 @@ import { CoreHeaderFooterCommand, OpenHeaderFooterPanelCommand } from '../commanimport { SidebarDocHeaderFooterPanelOperation } from '../commands/operations/doc-header-footer-panel.operation';import { BULLET_LIST_TYPE_COMPONENT, BulletListTypePicker, ORDER_LIST_TYPE_COMPONENT, OrderListTypePicker } from '../components/list-type-picker';import { ParagraphMenu } from '../components/paragraph-menu';-import { menuSchema } from '../menu/schema';+import { floatToolbarMenuSchema, menuSchema } from '../menu/schema';import { DocSelectionRenderService } from '../services/selection/doc-selection-render.service';import { TabShortCut } from '../shortcuts/format.shortcut';import {@@ -90,6 +90,7 @@ export class DocUIController extends Disposable {}private _initMenus(): void {+ this._menuManagerService.appendRootMenu(floatToolbarMenuSchema);this._menuManagerService.mergeMenu(menuSchema);}diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-clipboard.controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc-clipboard.controller.tsindex b60bd970d3..c818f7c6cd 100644--- a/packages/docs-ui/src/controllers/render-controllers/doc-clipboard.controller.ts+++ b/packages/docs-ui/src/controllers/render-controllers/doc-clipboard.controller.ts@@ -31,6 +31,7 @@ import {import { takeUntil } from 'rxjs';import { whenDocOrEditor } from '../../commands/commands/clipboard.command';import { IDocClipboardService } from '../../services/clipboard/clipboard.service';+import { DOC_INTERNAL_FRAGMENT_MIME } from '../../services/clipboard/internal-fragment';import { IEditorService } from '../../services/editor/editor-manager.service';import { DocSelectionRenderService } from '../../services/selection/doc-selection-render.service';@@ -62,6 +63,7 @@ export class DocClipboardController extends RxDisposable implements IRenderModulconfig!.event.preventDefault();const clipboardEvent = config!.event as ClipboardEvent;let htmlContent = clipboardEvent.clipboardData?.getData(HTML_CLIPBOARD_MIME_TYPE);+ const internalJson = clipboardEvent.clipboardData?.getData(DOC_INTERNAL_FRAGMENT_MIME);const textContent = clipboardEvent.clipboardData?.getData(PLAIN_TEXT_CLIPBOARD_MIME_TYPE);const files = [...(clipboardEvent.clipboardData?.items || [])]@@ -78,7 +80,7 @@ export class DocClipboardController extends RxDisposable implements IRenderModulhtmlContent = '';}- this._docClipboardService.legacyPaste({ html: htmlContent, text: textContent, files });+ this._docClipboardService.legacyPaste({ html: htmlContent, internalJson, text: textContent, files });});}}diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-contextmenu.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc-contextmenu.render-controller.tsindex 1b7df2aaa4..9a125e408a 100644--- a/packages/docs-ui/src/controllers/render-controllers/doc-contextmenu.render-controller.ts+++ b/packages/docs-ui/src/controllers/render-controllers/doc-contextmenu.render-controller.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { Workbook } from '@univerjs/core';+import type { DocumentDataModel, ITextRangeParam, Workbook } from '@univerjs/core';import type { Documents, IRenderContext, IRenderModule } from '@univerjs/engine-render';import {DEFAULT_EMPTY_DOCUMENT_VALUE,@@ -23,9 +23,13 @@ import {DOCS_NORMAL_EDITOR_UNIT_ID_KEY,DOCS_ZEN_EDITOR_UNIT_ID_KEY,ICommandService,+ Inject,+ IUniverInstanceService,+ UniverInstanceType,} from '@univerjs/core';-import { RichTextEditingMutation } from '@univerjs/docs';+import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';import { ContextMenuPosition, IContextMenuService } from '@univerjs/ui';+import { DocEventManagerService } from '../../services/doc-event-manager.service';const SKIP_UNIT_IDS = [DEFAULT_EMPTY_DOCUMENT_VALUE,@@ -42,7 +46,10 @@ export class DocContextMenuRenderController extends Disposable implements IRendeconstructor(private readonly _context: IRenderContext<Workbook>,@IContextMenuService private readonly _contextMenuService: IContextMenuService,- @ICommandService private readonly _commandService: ICommandService+ @ICommandService private readonly _commandService: ICommandService,+ @Inject(DocEventManagerService) private readonly _docEventManagerService: DocEventManagerService,+ @Inject(DocSelectionManagerService) private readonly _docSelectionManagerService: DocSelectionManagerService,+ @Inject(IUniverInstanceService) private readonly _univerInstanceService: IUniverInstanceService) {super();@@ -57,6 +64,13 @@ export class DocContextMenuRenderController extends Disposable implements IRende// Content range context menuconst documentsSubscription = documentsPointerDownObserver.subscribeEvent((event) => {if (event.button === 2) {+ if (this._docEventManagerService.isPointerOnBullet(event.offsetX, event.offsetY)) {+ return;+ }+ if (this._isSelectionInCodeBlock()) {+ return;+ }+this._contextMenuService.triggerContextMenu(event, ContextMenuPosition.MAIN_AREA);}});@@ -74,4 +88,19 @@ export class DocContextMenuRenderController extends Disposable implements IRende}));}++ private _isSelectionInCodeBlock(): boolean {+ const documentDataModel = this._univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);+ const blockRanges = documentDataModel?.getBody()?.blockRanges?.filter((range) => range.blockType === 'code') ?? [];+ const textRanges = this._docSelectionManagerService.getTextRanges() ?? [];+ if (!blockRanges.length || !textRanges.length) {+ return false;+ }++ return blockRanges.some((blockRange) => textRanges.some((range) => isRangeIntersectingBlock(range, blockRange.startIndex, blockRange.endIndex)));+ }+}++function isRangeIntersectingBlock(range: ITextRangeParam, startIndex: number, endIndex: number): boolean {+ return Math.max(range.startOffset, startIndex) <= Math.min(range.endOffset, endIndex);}diff --git a/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.tsindex 7c6acdb4f1..bb20141c0e 100644--- a/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts+++ b/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts@@ -18,10 +18,12 @@ import type { DocumentDataModel, EventState, ICommandInfo, Nullable } from '@uniimport type { IRichTextEditingMutationParams } from '@univerjs/docs';import type { DocumentSkeleton, IDocumentSkeletonPage, IRenderContext, IRenderModule, IWheelEvent } from '@univerjs/engine-render';import { DocumentFlavor, ICommandService, Inject, IUniverInstanceService, RxDisposable, UniverInstanceType } from '@univerjs/core';-import { DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';+import { DocSelectionManagerService, DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';import { DocBackground, Documents, IRenderManagerService, Layer, PageLayoutType, ScrollBar, Viewport } from '@univerjs/engine-render';import { takeUntil } from 'rxjs';import { DOCS_COMPONENT_BACKGROUND_LAYER_INDEX, DOCS_COMPONENT_DEFAULT_Z_INDEX, DOCS_COMPONENT_HEADER_LAYER_INDEX, DOCS_COMPONENT_MAIN_LAYER_INDEX, DOCS_VIEW_KEY, VIEWPORT_KEY } from '../../basics/docs-view-key';+import { DocPageLayoutService } from '../../services/doc-page-layout.service';+import { getDocsCanvasBackgroundColor } from '../../services/docs-render.service';import { IEditorService } from '../../services/editor/editor-manager.service';import { DocSelectionRenderService } from '../../services/selection/doc-selection-render.service';@@ -33,7 +35,9 @@ export class DocRenderController extends RxDisposable implements IRenderModule {@Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,@IEditorService private readonly _editorService: IEditorService,@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,+ @Inject(DocPageLayoutService) private readonly _docPageLayoutService: DocPageLayoutService,+ @Inject(DocSelectionManagerService) private readonly _textSelectionManagerService: DocSelectionManagerService) {super();@@ -66,6 +70,7 @@ export class DocRenderController extends RxDisposable implements IRenderModule {}this._recalculateSizeBySkeleton(skeleton);+ this._refreshPagePositionAndSelection();}private _addNewRender() {@@ -147,6 +152,7 @@ export class DocRenderController extends RxDisposable implements IRenderModule {const config = {pageMarginLeft: DEFAULT_PAGE_MARGIN_LEFT,pageMarginTop: DEFAULT_PAGE_MARGIN_TOP,+ ...this._getEditorBackgroundConfig(),};const documents = new Documents(DOCS_VIEW_KEY.MAIN, undefined, config);@@ -184,6 +190,7 @@ export class DocRenderController extends RxDisposable implements IRenderModule {docsComponent.changeSkeleton(skeleton);docBackground.changeSkeleton(skeleton);+ this._syncCanvasBackground();const { unitId } = this._context;@@ -196,6 +203,7 @@ export class DocRenderController extends RxDisposable implements IRenderModule {}this._recalculateSizeBySkeleton(skeleton);+ this._refreshPagePositionAndSelection();}private _initCommandListener() {@@ -212,6 +220,15 @@ export class DocRenderController extends RxDisposable implements IRenderModule {}));}+ private _refreshPagePositionAndSelection() {+ if (this._editorService.isEditor(this._context.unitId)) {+ return;+ }++ this._docPageLayoutService.calculatePagePosition();+ this._textSelectionManagerService.refreshSelection();+ }+private _recalculateSizeBySkeleton(skeleton: DocumentSkeleton) {const { mainComponent, scene, unitId, components } = this._context;@@ -230,6 +247,7 @@ export class DocRenderController extends RxDisposable implements IRenderModule {const docDataModel = this._context.unit;const documentFlavor = docDataModel.getSnapshot().documentStyle.documentFlavor;+ this._syncCanvasBackground(documentFlavor);for (let i = 0, len = pages.length; i < len; i++) {const page = pages[i];@@ -273,6 +291,26 @@ export class DocRenderController extends RxDisposable implements IRenderModule {scene.resize(width, height);}}++ private _syncCanvasBackground(documentFlavor = this._context.unit.getSnapshot().documentStyle.documentFlavor) {+ const editor = this._editorService.getEditor(this._context.unitId);+ const editorBackgroundColor = editor?.params.canvasStyle?.backgroundColor;+ this._context.engine.getCanvas().getCanvasEle().style.backgroundColor = editorBackgroundColor ?? getDocsCanvasBackgroundColor(documentFlavor);+ const docBackground = this._context.components.get(DOCS_VIEW_KEY.BACKGROUND) as DocBackground | undefined;+ docBackground?.setFillColors?.(editorBackgroundColor, editorBackgroundColor, editorBackgroundColor, editorBackgroundColor);+ }++ private _getEditorBackgroundConfig() {+ const editorBackgroundColor = this._editorService.getEditor(this._context.unitId)?.params.canvasStyle?.backgroundColor;+ return editorBackgroundColor == null+ ? {}+ : {+ backgroundFillColor: editorBackgroundColor,+ pageFillColor: editorBackgroundColor,+ pageStrokeColor: editorBackgroundColor,+ marginStrokeColor: editorBackgroundColor,+ };+ }}function getPageSizeInModernMode(page: IDocumentSkeletonPage) {diff --git a/packages/docs-ui/src/controllers/render-controllers/zoom.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/zoom.render-controller.tsindex 2a9450f76d..9c56dcc249 100644--- a/packages/docs-ui/src/controllers/render-controllers/zoom.render-controller.ts+++ b/packages/docs-ui/src/controllers/render-controllers/zoom.render-controller.ts@@ -17,6 +17,7 @@import type { DocumentDataModel, ICommandInfo, Workbook } from '@univerjs/core';import type { IRenderContext, IRenderModule, IWheelEvent } from '@univerjs/engine-render';+import type { IDocPageSetupCommandParams } from '../../commands/commands/doc-page-setup.command';import type { ISetDocZoomRatioOperationParams } from '../../commands/operations/set-doc-zoom-ratio.operation';import {Disposable,@@ -31,8 +32,9 @@ import {UniverInstanceType,} from '@univerjs/core';import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';-import { IRenderManagerService } from '@univerjs/engine-render';+import { getNextWheelZoomRatio, IRenderManagerService } from '@univerjs/engine-render';import { neoGetDocObject } from '../../basics/component-tools';+import { DocPageSetupCommand } from '../../commands/commands/doc-page-setup.command';import { SetDocZoomRatioCommand } from '../../commands/commands/set-doc-zoom-ratio.command';import { SwitchDocModeCommand } from '../../commands/commands/switch-doc-mode.command';import { SetDocZoomRatioOperation } from '../../commands/operations/set-doc-zoom-ratio.operation';@@ -59,7 +61,6 @@ export class DocZoomRenderController extends Disposable implements IRenderModulethis._initSkeletonListener();this._initCommandExecutedListener();- this._initRenderRefresher();this._isSheetEditor = this._context.unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY;const currentSheet = this._univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);const sheetRenderer = currentSheet && this._renderManagerService.getRenderById(currentSheet.getUnitId());@@ -76,56 +77,6 @@ export class DocZoomRenderController extends Disposable implements IRenderModulewindow.clearTimeout(this._updateTimer);}- private _initRenderRefresher() {- this._docSkeletonManagerService.currentSkeleton$.subscribe((param) => {- if (param == null) {- return;- }-- const { unitId, scene } = this._context;- if (this._editorService.isEditor(unitId)) {- return;- }-- this.disposeWithMe(scene.onMouseWheel$.subscribeEvent((e: IWheelEvent) => {- if (!e.ctrlKey || !this._contextService.getContextValue(FOCUSING_DOC)) {- return;- }-- const documentModel = this._univerInstanceService.getCurrentUniverDocInstance();- if (!documentModel) {- return;- }-- const { documentFlavor } = documentModel.getSnapshot().documentStyle;-- // Modern document does not support zooming.- if (documentFlavor === DocumentFlavor.MODERN) {- return;- }-- const deltaFactor = Math.abs(e.deltaX);- let ratioDelta = deltaFactor < 40 ? 0.2 : deltaFactor < 80 ? 0.4 : 0.2;- ratioDelta *= e.deltaY > 0 ? -1 : 1;- if (scene.scaleX < 1) {- ratioDelta /= 2;- }-- const currentRatio = documentModel.zoomRatio;-- let nextRatio = +Number.parseFloat(`${currentRatio + ratioDelta}`).toFixed(1);- nextRatio = nextRatio >= 4 ? 4 : nextRatio <= 0.1 ? 0.1 : nextRatio;-- this._commandService.executeCommand(SetDocZoomRatioCommand.id, {- zoomRatio: nextRatio,- unitId: documentModel.getUnitId(),- });-- e.preventDefault();- }));- });- }-private _initSkeletonListener() {this.disposeWithMe(this._docSkeletonManagerService.currentSkeleton$.subscribe((param) => {if (param == null) {@@ -158,7 +109,10 @@ export class DocZoomRenderController extends Disposable implements IRenderModulethis.disposeWithMe(this._commandService.beforeCommandExecuted((command: ICommandInfo) => {- if (command.id === SwitchDocModeCommand.id) {+ const shouldResetZoom = command.id === SwitchDocModeCommand.id ||+ (command.id === DocPageSetupCommand.id && (command.params as IDocPageSetupCommandParams | undefined)?.documentFlavor === DocumentFlavor.MODERN);++ if (shouldResetZoom) {this._commandService.executeCommand(SetDocZoomRatioCommand.id, {zoomRatio: 1,unitId: this._context.unitId,@@ -192,24 +146,28 @@ export class DocZoomRenderController extends Disposable implements IRenderModulethis.disposeWithMe(// hold ctrl & mousewheel ---> zoomscene.onMouseWheel$.subscribeEvent((e: IWheelEvent) => {- if (!e.ctrlKey) {+ if (!e.ctrlKey || !this._contextService.getContextValue(FOCUSING_DOC)) {return;}- const deltaFactor = Math.abs(e.deltaX);- let ratioDelta = deltaFactor < 40 ? 0.2 : deltaFactor < 80 ? 0.4 : 0.2;- ratioDelta *= e.deltaY > 0 ? -1 : 1;- if (scene.scaleX < 1) {- ratioDelta /= 2;+ const documentModel = this._univerInstanceService.getCurrentUniverDocInstance();+ if (!documentModel) {+ return;}- const currentRatio = this._context.unit.zoomRatio;- let nextRatio = +Number.parseFloat(`${currentRatio + ratioDelta}`).toFixed(1);- nextRatio = nextRatio >= 4 ? 4 : nextRatio <= 0.1 ? 0.1 : nextRatio;+ const { documentFlavor } = documentModel.getSnapshot().documentStyle;++ if (documentFlavor === DocumentFlavor.MODERN) {+ e.preventDefault();+ return;+ }++ const currentRatio = documentModel.zoomRatio || 1;+ const nextRatio = getNextWheelZoomRatio(currentRatio, e);this._commandService.executeCommand(SetDocZoomRatioCommand.id, {- zoomRatio: Math.round(nextRatio * 10) / 10,- documentId: this._context.unitId,+ zoomRatio: nextRatio,+ documentId: documentModel.getUnitId(),});e.preventDefault();diff --git a/packages/docs-ui/src/index.ts b/packages/docs-ui/src/index.tsindex a25ab09eb4..ed64a73c7b 100644--- a/packages/docs-ui/src/index.ts+++ b/packages/docs-ui/src/index.ts@@ -39,6 +39,7 @@ export {type IUpdateCommandParams,UpdateCommand,} from './commands/commands/core-editing.command';+export { buildMoveDocBlockActions, type IMoveDocBlockCommandParams, MoveDocBlockCommand } from './commands/commands/doc-block-move.command';export { DeleteCustomBlockCommand, DeleteLeftCommand, DeleteRightCommand, type IDeleteCustomBlockParams, MergeTwoParagraphCommand } from './commands/commands/doc-delete.command';export { getCursorWhenDelete } from './commands/commands/doc-delete.command';export { HorizontalLineCommand } from './commands/commands/doc-horizontal-line.command';@@ -119,15 +120,19 @@ export type { IUniverDocsUIConfig } from './config/config';export { DocUIController } from './controllers/doc-ui.controller';export { DocBackScrollRenderController } from './controllers/render-controllers/back-scroll.render-controller';export { DocRenderController } from './controllers/render-controllers/doc.render-controller';+export { FLOAT_TEXT_STYLE_MENU_ID, FLOAT_TOOLBAR_MENU_POSITION, hideMenuWhenSelectionInBlockRange, isTextRangeInAnyBlockRange } from './menu/menu';+export { DOC_CONTENT_INSERT_MENU_ID, EMPTY_PARAGRAPH_MENU_ID, getDocBlockRangeMenuId, INSERT_BELLOW_MENU_ID } from './menu/paragraph-menu';export { menuSchema as DocsUIMenuSchema } from './menu/schema';export { UniverDocsUIPlugin } from './plugin';export * from './services';-export { IDocClipboardService } from './services/clipboard/clipboard.service';+export { convertBodyToHtml } from './services/clipboard/udm-to-html/convertor';export { DocAutoFormatService } from './services/doc-auto-format.service';-export { DocEventManagerService } from './services/doc-event-manager.service';+export { DocContentInsertService, type IDocContentInsertRange } from './services/doc-content-insert.service';+export { DocEventManagerService, type IBulletBound } from './services/doc-event-manager.service';export { DocIMEInputManagerService } from './services/doc-ime-input-manager.service';+export { DocParagraphMenuService } from './services/doc-paragraph-menu.service';export { calcDocRangePositions, DocCanvasPopManagerService } from './services/doc-popup-manager.service';export { DocPrintInterceptorService, type IDocPrintComponentContext, type IDocPrintContext } from './services/doc-print-interceptor.service';export { DocStateChangeManagerService } from './services/doc-state-change-manager.service';diff --git a/packages/docs-ui/src/locale/ar-SA.ts b/packages/docs-ui/src/locale/ar-SA.tsindex 4756af087b..095adb79ff 100644--- a/packages/docs-ui/src/locale/ar-SA.ts+++ b/packages/docs-ui/src/locale/ar-SA.ts@@ -110,8 +110,16 @@ const locale: typeof enUS = {},'page-settings': {'document-setting': 'إعداد المستند',+ mode: 'الوضع',+ 'modern-mode': 'حديث',+ 'classic-mode': 'كلاسيكي',+ 'modern-width': 'عرض المحتوى',+ 'modern-width-narrow': 'ضيق',+ 'modern-width-medium': 'متوسط',+ 'modern-width-wide': 'واسع','paper-size': 'حجم الورق','page-size': {+ main: 'حجم الورق',a4: 'A4',a3: 'A3',a5: 'A5',@@ -124,6 +132,9 @@ const locale: typeof enUS = {executive: 'Executive',folio: 'Folio',},+ orientation: 'الاتجاه',+ portrait: 'عمودي',+ landscape: 'أفقي','custom-paper-size': 'حجم ورق مخصص',top: 'أعلى',bottom: 'أسفل',diff --git a/packages/docs-ui/src/locale/ca-ES.ts b/packages/docs-ui/src/locale/ca-ES.tsindex 5071af32ab..dcccc72156 100644--- a/packages/docs-ui/src/locale/ca-ES.ts+++ b/packages/docs-ui/src/locale/ca-ES.ts@@ -110,8 +110,16 @@ const locale: typeof enUS = {},'page-settings': {'document-setting': 'Configuració de document',+ mode: 'Mode',+ 'modern-mode': 'Modern',+ 'classic-mode': 'Clàssic',+ 'modern-width': 'Amplada del contingut',+ 'modern-width-narrow': 'Estreta',+ 'modern-width-medium': 'Mitjana',+ 'modern-width-wide': 'Ampla','paper-size': 'Mida del paper','page-size': {+ main: 'Mida del paper',a4: 'A4',a3: 'A3',a5: 'A5',@@ -124,6 +132,9 @@ const locale: typeof enUS = {executive: 'Executiu',folio: 'Foli',},+ orientation: 'Orientació',+ portrait: 'Vertical',+ landscape: 'Horitzontal','custom-paper-size': 'Mida de paper personalitzada',top: 'Superior',bottom: 'Inferior',diff --git a/packages/docs-ui/src/locale/de-DE.ts b/packages/docs-ui/src/locale/de-DE.tsindex c98cba4c13..375c64d838 100644--- a/packages/docs-ui/src/locale/de-DE.ts+++ b/packages/docs-ui/src/locale/de-DE.ts@@ -110,8 +110,16 @@ const locale: typeof enUS = {},'page-settings': {'document-setting': 'Dokumenteneinstellung',+ mode: 'Modus',+ 'modern-mode': 'Modern',+ 'classic-mode': 'Klassisch',+ 'modern-width': 'Inhaltsbreite',+ 'modern-width-narrow': 'Schmal',+ 'modern-width-medium': 'Mittel',+ 'modern-width-wide': 'Breit','paper-size': 'Papierformat','page-size': {+ main: 'Papierformat',a4: 'A4',a3: 'A3',a5: 'A5',@@ -124,6 +132,9 @@ const locale: typeof enUS = {executive: 'Executive',folio: 'Folio',},+ orientation: 'Ausrichtung',+ portrait: 'Hochformat',+ landscape: 'Querformat','custom-paper-size': 'Benutzerdefiniertes Papierformat',top: 'Oben',bottom: 'Unten',diff --git a/packages/docs-ui/src/locale/en-US.ts b/packages/docs-ui/src/locale/en-US.tsindex ce756eeaf2..69706a0a34 100644--- a/packages/docs-ui/src/locale/en-US.ts+++ b/packages/docs-ui/src/locale/en-US.ts@@ -108,8 +108,16 @@ const locale = {},'page-settings': {'document-setting': 'Document Setting',+ mode: 'Mode',+ 'modern-mode': 'Modern',+ 'classic-mode': 'Classic',+ 'modern-width': 'Content width',+ 'modern-width-narrow': 'Narrow',+ 'modern-width-medium': 'Medium',+ 'modern-width-wide': 'Wide','paper-size': 'Paper size','page-size': {+ main: 'Paper size',a4: 'A4',a3: 'A3',a5: 'A5',@@ -122,6 +130,9 @@ const locale = {executive: 'Executive',folio: 'Folio',},+ orientation: 'Orientation',+ portrait: 'Portrait',+ landscape: 'Landscape','custom-paper-size': 'Custom Paper size',top: 'Top',bottom: 'Bottom',diff --git a/packages/docs-ui/src/locale/es-ES.ts b/packages/docs-ui/src/locale/es-ES.tsindex 2b1f9ac714..2c6a4fc4a2 100644--- a/packages/docs-ui/src/locale/es-ES.ts+++ b/packages/docs-ui/src/locale/es-ES.ts@@ -110,8 +110,16 @@ const locale: typeof enUS = {},'page-settings': {'document-setting': 'Configuración de documento',+ mode: 'Modo',+ 'modern-mode': 'Moderno',+ 'classic-mode': 'Clásico',+ 'modern-width': 'Ancho del contenido',+ 'modern-width-narrow': 'Estrecho',+ 'modern-width-medium': 'Medio',+ 'modern-width-wide': 'Ancho','paper-size': 'Tamaño de papel','page-size': {+ main: 'Tamaño de papel',a4: 'A4',a3: 'A3',a5: 'A5',@@ -124,6 +132,9 @@ const locale: typeof enUS = {executive: 'Ejecutivo',folio: 'Folio',},+ orientation: 'Orientación',+ portrait: 'Vertical',+ landscape: 'Horizontal','custom-paper-size': 'Tamaño de papel personalizado',top: 'Superior',bottom: 'Inferior',diff --git a/packages/docs-ui/src/locale/fa-IR.ts b/packages/docs-ui/src/locale/fa-IR.tsindex e712b22764..29b5938812 100644--- a/packages/docs-ui/src/locale/fa-IR.ts+++ b/packages/docs-ui/src/locale/fa-IR.ts@@ -110,8 +110,15 @@ const locale: typeof enUS = {},'page-settings': {'document-setting': 'تنظیمات سند',- 'paper-size': 'اندازه کاغذ',+ mode: 'حالت',+ 'modern-mode': 'مدرن',+ 'classic-mode': 'کلاسیک',+ 'modern-width': 'عرض محتوا',+ 'modern-width-narrow': 'باریک',+ 'modern-width-medium': 'متوسط',+ 'modern-width-wide': 'عریض','page-size': {+ main: 'اندازه کاغذ',a4: 'A4',a3: 'A3',a5: 'A5',@@ -124,6 +131,10 @@ const locale: typeof enUS = {executive: 'کاغذ اجرایی',folio: 'کاغذ فولیو',},+ 'paper-size': 'اندازه کاغذ',+ orientation: 'جهت',+ portrait: 'عمودی',+ landscape: 'افقی','custom-paper-size': 'اندازه کاغذ سفارشی',top: 'بالا',bottom: 'پایین',diff --git a/packages/docs-ui/src/locale/fr-FR.ts b/packages/docs-ui/src/locale/fr-FR.tsindex 99bd459b7d..d6ce9be3ec 100644--- a/packages/docs-ui/src/locale/fr-FR.ts+++ b/packages/docs-ui/src/locale/fr-FR.ts@@ -110,8 +110,16 @@ const locale: typeof enUS = {},'page-settings': {'document-setting': 'Paramètres du document',+ mode: 'Mode',+ 'modern-mode': 'Moderne',+ 'classic-mode': 'Classique',+ 'modern-width': 'Largeur du contenu',+ 'modern-width-narrow': 'Étroit',+ 'modern-width-medium': 'Moyen',+ 'modern-width-wide': 'Large','paper-size': 'Format du papier','page-size': {+ main: 'Format du papier',a4: 'A4',a3: 'A3',a5: 'A5',@@ -124,6 +132,9 @@ const locale: typeof enUS = {executive: 'Format Exécutif',folio: 'Format Folio',},+ orientation: 'Orientation',+ portrait: 'Portrait',+ landscape: 'Paysage','custom-paper-size': 'Format de papier personnalisé',top: 'Haut',bottom: 'Bas',diff --git a/packages/docs-ui/src/locale/id-ID.ts b/packages/docs-ui/src/locale/id-ID.tsindex 912945230a..cb423efcf5 100644--- a/packages/docs-ui/src/locale/id-ID.ts+++ b/packages/docs-ui/src/locale/id-ID.ts@@ -110,8 +110,16 @@ const locale: typeof enUS = {},'page-settings': {'document-setting': 'Pengaturan Dokumen',+ mode: 'Mode',+ 'modern-mode': 'Modern',+ 'classic-mode': 'Klasik',+ 'modern-width': 'Lebar konten',+ 'modern-width-narrow': 'Sempit',+ 'modern-width-medium': 'Sedang',+ 'modern-width-wide': 'Lebar','paper-size': 'Ukuran kertas','page-size': {+ main: 'Ukuran kertas',a4: 'A4',a3: 'A3',a5: 'A5',@@ -124,6 +132,9 @@ const locale: typeof enUS = {executive: 'Executive',folio: 'Folio',},+ orientation: 'Orientasi',+ portrait: 'Potret',+ landscape: 'Lanskap','custom-paper-size': 'Ukuran kertas kustom',top: 'Atas',bottom: 'Bawah',diff --git a/packages/docs-ui/src/locale/it-IT.ts b/packages/docs-ui/src/locale/it-IT.tsindex 3a99b09a9a..d22d7d1b4d 100644--- a/packages/docs-ui/src/locale/it-IT.ts+++ b/packages/docs-ui/src/locale/it-IT.ts@@ -110,8 +110,16 @@ const locale: typeof enUS = {},'page-settings': {'document-setting': 'Impostazione Documento',+ mode: 'Modalità',+ 'modern-mode': 'Moderna',+ 'classic-mode': 'Classica',+ 'modern-width': 'Larghezza contenuto',+ 'modern-width-narrow': 'Stretta',+ 'modern-width-medium': 'Media',+ 'modern-width-wide': 'Ampia','paper-size': 'Dimensione carta','page-size': {+ main: 'Dimensione carta',a4: 'A4',a3: 'A3',a5: 'A5',@@ -124,6 +132,9 @@ const locale: typeof enUS = {executive: 'Executive',folio: 'Folio',},+ orientation: 'Orientamento',+ portrait: 'Verticale',+ landscape: 'Orizzontale','custom-paper-size': 'Dimensione carta personalizzata',top: 'Superiore',bottom: 'Inferiore',diff --git a/packages/docs-ui/src/locale/ja-JP.ts b/packages/docs-ui/src/locale/ja-JP.tsindex ce732a4095..5addf98157 100644--- a/packages/docs-ui/src/locale/ja-JP.ts+++ b/packages/docs-ui/src/locale/ja-JP.ts@@ -110,8 +110,16 @@ const locale: typeof enUS = {},'page-settings': {'document-setting': '文書設定',+ mode: 'モード',+ 'modern-mode': 'モダン',+ 'classic-mode': 'クラシック',+ 'modern-width': 'コンテンツ幅',+ 'modern-width-narrow': '狭い',+ 'modern-width-medium': '標準',+ 'modern-width-wide': '広い','paper-size': '用紙サイズ','page-size': {+ main: '用紙サイズ',a4: 'A4',a3: 'A3',a5: 'A5',@@ -124,6 +132,9 @@ const locale: typeof enUS = {executive: 'Executive',folio: 'Folio',},+ orientation: '方向',+ portrait: '縦',+ landscape: '横','custom-paper-size': 'カスタム用紙サイズ',top: '上',bottom: '下',diff --git a/packages/docs-ui/src/locale/ko-KR.ts b/packages/docs-ui/src/locale/ko-KR.tsindex d7691585ec..1a7bc149d6 100644--- a/packages/docs-ui/src/locale/ko-KR.ts+++ b/packages/docs-ui/src/locale/ko-KR.ts@@ -110,8 +110,16 @@ const locale: typeof enUS = {},'page-settings': {'document-setting': '문서 설정',+ mode: '모드',+ 'modern-mode': '모던',+ 'classic-mode': '클래식',+ 'modern-width': '콘텐츠 너비',+ 'modern-width-narrow': '좁게',+ 'modern-width-medium': '보통',+ 'modern-width-wide': '넓게','paper-size': '용지 크기','page-size': {+ main: '용지 크기',a4: 'A4',a3: 'A3',a5: 'A5',@@ -124,6 +132,9 @@ const locale: typeof enUS = {executive: 'Executive',folio: 'Folio',},+ orientation: '방향',+ portrait: '세로',+ landscape: '가로','custom-paper-size': '사용자 정의 용지 크기',top: '위',bottom: '아래',diff --git a/packages/docs-ui/src/locale/pl-PL.ts b/packages/docs-ui/src/locale/pl-PL.tsindex 66ede8e044..a2b09e99be 100644--- a/packages/docs-ui/src/locale/pl-PL.ts+++ b/packages/docs-ui/src/locale/pl-PL.ts@@ -110,8 +110,16 @@ const locale: typeof enUS = {},'page-settings': {'document-setting': 'Ustawienia dokumentu',+ mode: 'Tryb',+ 'modern-mode': 'Nowoczesny',+ 'classic-mode': 'Klasyczny',+ 'modern-width': 'Szerokość treści',+ 'modern-width-narrow': 'Wąski',+ 'modern-width-medium': 'Średni',+ 'modern-width-wide': 'Szeroki','paper-size': 'Rozmiar papieru','page-size': {+ main: 'Rozmiar papieru',a4: 'A4',a3: 'A3',a5: 'A5',@@ -124,6 +132,9 @@ const locale: typeof enUS = {executive: 'Executive',folio: 'Folio',},+ orientation: 'Orientacja',+ portrait: 'Pionowa',+ landscape: 'Pozioma','custom-paper-size': 'Niestandardowy rozmiar papieru',top: 'Góra',bottom: 'Dół',diff --git a/packages/docs-ui/src/locale/pt-BR.ts b/packages/docs-ui/src/locale/pt-BR.tsindex 1b03f56403..c50452272d 100644--- a/packages/docs-ui/src/locale/pt-BR.ts+++ b/packages/docs-ui/src/locale/pt-BR.ts@@ -110,8 +110,16 @@ const locale: typeof enUS = {},'page-settings': {'document-setting': 'Configuração do documento',+ mode: 'Modo',+ 'modern-mode': 'Moderno',+ 'classic-mode': 'Clássico',+ 'modern-width': 'Largura do conteúdo',+ 'modern-width-narrow': 'Estreito',+ 'modern-width-medium': 'Médio',+ 'modern-width-wide': 'Amplo','paper-size': 'Tamanho do papel','page-size': {+ main: 'Tamanho do papel',a4: 'A4',a3: 'A3',a5: 'A5',@@ -124,6 +132,9 @@ const locale: typeof enUS = {executive: 'Executive',folio: 'Folio',},+ orientation: 'Orientação',+ portrait: 'Retrato',+ landscape: 'Paisagem','custom-paper-size': 'Tamanho de papel personalizado',top: 'Superior',bottom: 'Inferior',diff --git a/packages/docs-ui/src/locale/ru-RU.ts b/packages/docs-ui/src/locale/ru-RU.tsindex 401ff5f05d..ba0942d35d 100644--- a/packages/docs-ui/src/locale/ru-RU.ts+++ b/packages/docs-ui/src/locale/ru-RU.ts@@ -110,8 +110,15 @@ const locale: typeof enUS = {},'page-settings': {'document-setting': 'Настройки документа',- 'paper-size': 'Размер бумаги',+ mode: 'Режим',+ 'modern-mode': 'Современный',+ 'classic-mode': 'Классический',+ 'modern-width': 'Ширина содержимого',+ 'modern-width-narrow': 'Узкая',+ 'modern-width-medium': 'Средняя',+ 'modern-width-wide': 'Широкая','page-size': {+ main: 'Размер бумаги',a4: 'A4',a3: 'A3',a5: 'A5',@@ -124,6 +131,10 @@ const locale: typeof enUS = {executive: 'Исполнительный формат',folio: 'Формат фолио',},+ 'paper-size': 'Размер бумаги',+ orientation: 'Ориентация',+ portrait: 'Книжная',+ landscape: 'Альбомная','custom-paper-size': 'Пользовательский размер бумаги',top: 'Верх',bottom: 'Низ',diff --git a/packages/docs-ui/src/locale/sk-SK.ts b/packages/docs-ui/src/locale/sk-SK.tsindex d6eacdf736..f83eee99f9 100644--- a/packages/docs-ui/src/locale/sk-SK.ts+++ b/packages/docs-ui/src/locale/sk-SK.ts@@ -110,8 +110,16 @@ const locale: typeof enUS = {},'page-settings': {'document-setting': 'Nastavenia dokumentu',+ mode: 'Režim',+ 'modern-mode': 'Moderný',+ 'classic-mode': 'Klasický',+ 'modern-width': 'Šírka obsahu',+ 'modern-width-narrow': 'Úzka',+ 'modern-width-medium': 'Stredná',+ 'modern-width-wide': 'Široká','paper-size': 'Veľkosť papiera','page-size': {+ main: 'Veľkosť papiera',a4: 'A4',a3: 'A3',a5: 'A5',@@ -124,6 +132,9 @@ const locale: typeof enUS = {executive: 'Executive',folio: 'Folio',},+ orientation: 'Orientácia',+ portrait: 'Na výšku',+ landscape: 'Na šírku','custom-paper-size': 'Vlastná veľkosť papiera',top: 'Hore',bottom: 'Dole',diff --git a/packages/docs-ui/src/locale/vi-VN.ts b/packages/docs-ui/src/locale/vi-VN.tsindex 808f4d8369..febb7eabc3 100644--- a/packages/docs-ui/src/locale/vi-VN.ts+++ b/packages/docs-ui/src/locale/vi-VN.ts@@ -55,15 +55,15 @@ const locale: typeof enUS = {pageSetup: 'Cài đặt trang',},table: {- insert: 'Insert',- insertRowAbove: 'Insert row above',- insertRowBelow: 'Insert row below',- insertColumnLeft: 'Insert column left',- insertColumnRight: 'Insert column right',- delete: 'Table delete',- deleteRows: 'Delete row',- deleteColumns: 'Delete column',- deleteTable: 'Delete table',+ insert: 'Chèn',+ insertRowAbove: 'Chèn hàng phía trên',+ insertRowBelow: 'Chèn hàng phía dưới',+ insertColumnLeft: 'Chèn cột bên trái',+ insertColumnRight: 'Chèn cột bên phải',+ delete: 'Xóa bảng',+ deleteRows: 'Xóa hàng',+ deleteColumns: 'Xóa cột',+ deleteTable: 'Xóa bảng',},headerFooter: {header: 'Đầu trang',@@ -110,8 +110,16 @@ const locale: typeof enUS = {},'page-settings': {'document-setting': 'Cài đặt tài liệu',+ mode: 'Chế độ',+ 'modern-mode': 'Hiện đại',+ 'classic-mode': 'Cổ điển',+ 'modern-width': 'Độ rộng nội dung',+ 'modern-width-narrow': 'Hẹp',+ 'modern-width-medium': 'Vừa',+ 'modern-width-wide': 'Rộng','paper-size': 'Kích thước giấy','page-size': {+ main: 'Kích thước giấy',a4: 'A4',a3: 'A3',a5: 'A5',@@ -124,6 +132,9 @@ const locale: typeof enUS = {executive: 'Giấy hành chính',folio: 'Giấy folio',},+ orientation: 'Hướng',+ portrait: 'Dọc',+ landscape: 'Ngang','custom-paper-size': 'Kích thước giấy tùy chỉnh',top: 'Trên',bottom: 'Dưới',diff --git a/packages/docs-ui/src/locale/zh-CN.ts b/packages/docs-ui/src/locale/zh-CN.tsindex 41efa3c25c..d3f486f5e0 100644--- a/packages/docs-ui/src/locale/zh-CN.ts+++ b/packages/docs-ui/src/locale/zh-CN.ts@@ -110,8 +110,15 @@ const locale: typeof enUS = {},'page-settings': {'document-setting': '文档设置',- 'paper-size': '纸张大小',+ mode: '模式',+ 'modern-mode': '现代模式',+ 'classic-mode': '经典模式',+ 'modern-width': '内容宽度',+ 'modern-width-narrow': '窄',+ 'modern-width-medium': '适中',+ 'modern-width-wide': '宽','page-size': {+ main: '纸张大小',a4: 'A4',a3: 'A3',a5: 'A5',@@ -124,6 +131,10 @@ const locale: typeof enUS = {executive: '行政用纸',folio: '对开纸',},+ 'paper-size': '纸张大小',+ orientation: '方向',+ portrait: '纵向',+ landscape: '横向','custom-paper-size': '自定义纸张大小',top: '上',bottom: '下',diff --git a/packages/docs-ui/src/locale/zh-HK.ts b/packages/docs-ui/src/locale/zh-HK.tsindex 33fe012bce..293b3d11b6 100644--- a/packages/docs-ui/src/locale/zh-HK.ts+++ b/packages/docs-ui/src/locale/zh-HK.ts@@ -110,8 +110,16 @@ const locale: typeof enUS = {},'page-settings': {'document-setting': '文檔設置',+ mode: '模式',+ 'modern-mode': '現代模式',+ 'classic-mode': '經典模式',+ 'modern-width': '內容寬度',+ 'modern-width-narrow': '窄',+ 'modern-width-medium': '適中',+ 'modern-width-wide': '寬','paper-size': '紙張大小','page-size': {+ main: '紙張大小',a4: 'A4',a3: 'A3',a5: 'A5',@@ -124,6 +132,9 @@ const locale: typeof enUS = {executive: '行政用紙',folio: '對開紙',},+ orientation: '方向',+ portrait: '縱向',+ landscape: '橫向','custom-paper-size': '自定義紙張大小',top: '上',bottom: '下',diff --git a/packages/docs-ui/src/locale/zh-TW.ts b/packages/docs-ui/src/locale/zh-TW.tsindex 02ab541973..9a882ff073 100644--- a/packages/docs-ui/src/locale/zh-TW.ts+++ b/packages/docs-ui/src/locale/zh-TW.ts@@ -55,15 +55,15 @@ const locale: typeof enUS = {pageSetup: '頁面設置',},table: {- insert: 'Insert',- insertRowAbove: 'Insert row above',- insertRowBelow: 'Insert row below',- insertColumnLeft: 'Insert column left',- insertColumnRight: 'Insert column right',- delete: 'Table delete',- deleteRows: 'Delete row',- deleteColumns: 'Delete column',- deleteTable: 'Delete table',+ insert: '插入',+ insertRowAbove: '在上方插入行',+ insertRowBelow: '在下方插入行',+ insertColumnLeft: '在左側插入列',+ insertColumnRight: '在右側插入列',+ delete: '刪除表格',+ deleteRows: '刪除行',+ deleteColumns: '刪除列',+ deleteTable: '刪除表格',},headerFooter: {header: '頁眉',@@ -110,8 +110,15 @@ const locale: typeof enUS = {},'page-settings': {'document-setting': '文檔設置',- 'paper-size': '紙張大小',+ mode: '模式',+ 'modern-mode': '現代模式',+ 'classic-mode': '經典模式',+ 'modern-width': '內容寬度',+ 'modern-width-narrow': '窄',+ 'modern-width-medium': '適中',+ 'modern-width-wide': '寬','page-size': {+ main: '紙張大小',a4: 'A4',a3: 'A3',a5: 'A5',@@ -124,6 +131,10 @@ const locale: typeof enUS = {executive: '行政用紙',folio: '對開紙',},+ 'paper-size': '紙張大小',+ orientation: '方向',+ portrait: '縱向',+ landscape: '橫向','custom-paper-size': '自定義紙張大小',top: '上',bottom: '下',diff --git a/packages/docs-ui/src/menu/__tests__/schema.spec.ts b/packages/docs-ui/src/menu/__tests__/schema.spec.tsnew file mode 100644index 0000000000..c181fc8823--- /dev/null+++ b/packages/docs-ui/src/menu/__tests__/schema.spec.ts@@ -0,0 +1,186 @@+/**+ * 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 { NamedStyleType, PresetListType } from '@univerjs/core';+import { ContextMenuGroup, ContextMenuPosition, MenuItemType, RibbonInsertGroup, RibbonStartGroup } from '@univerjs/ui';+import { describe, expect, it } from 'vitest';+import { HorizontalLineCommand, InsertHorizontalLineBellowCommand } from '../../commands/commands/doc-horizontal-line.command';+import { BulletListCommand, CheckListCommand, InsertBulletListBellowCommand, InsertCheckListBellowCommand, InsertOrderListBellowCommand, OrderListCommand } from '../../commands/commands/list.command';+import { AlignCenterCommand, AlignJustifyCommand, AlignLeftCommand, AlignOperationCommand, AlignRightCommand } from '../../commands/commands/paragraph-align.command';+import { H1HeadingCommand, NormalTextHeadingCommand, SetParagraphNamedStyleCommand, SubtitleHeadingCommand, TitleHeadingCommand } 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 { DocTableDeleteTableCommand } from '../../commands/commands/table/doc-table-delete.command';+import { DocCreateTableOperation } from '../../commands/operations/doc-create-table.operation';+import { DocParagraphSettingPanelOperation } from '../../commands/operations/doc-paragraph-setting-panel.operation';+import { AlignMenuItemFactory, DocSwitchModeMenuItemFactory, FLOAT_TEXT_STYLE_MENU_ID, FLOAT_TOOLBAR_MENU_POSITION, FloatTextStyleMenuItemFactory, InsertDefaultTableMenuFactory, InsertTableMenuFactory } from '../menu';+import { DOC_CONTENT_INSERT_MENU_ID, DOC_TABLE_BLOCK_MENU_ID, EMPTY_PARAGRAPH_MENU_ID, INSERT_BELLOW_MENU_ID } from '../paragraph-menu';+import { menuSchema } from '../schema';++describe('docs ui ribbon schema', () => {+ it('uses one align dropdown instead of separate toolbar buttons', () => {+ const layout = (menuSchema as any)[RibbonStartGroup.LAYOUT];++ expect(layout[AlignOperationCommand.id].menuItemFactory).toBe(AlignMenuItemFactory);+ expect(layout[AlignLeftCommand.id]).toBeUndefined();+ expect(layout[AlignCenterCommand.id]).toBeUndefined();+ expect(layout[AlignRightCommand.id]).toBeUndefined();+ expect(layout[AlignJustifyCommand.id]).toBeUndefined();++ const item = AlignMenuItemFactory({ get: () => ({}) } as never);+ expect(item.type).toBe(MenuItemType.SELECTOR);+ expect((item.selections as Array<{ id?: string }>).map((option) => option.id)).toEqual([+ AlignLeftCommand.id,+ AlignCenterCommand.id,+ AlignRightCommand.id,+ AlignJustifyCommand.id,+ ]);+ expect((item.selections as Array<{ label?: string }>).map((option) => option.label)).toEqual([+ 'docs-ui.toolbar.alignLeft',+ 'docs-ui.toolbar.alignCenter',+ 'docs-ui.toolbar.alignRight',+ 'docs-ui.toolbar.alignJustify',+ ]);+ });++ it('moves horizontal line and checklist to the insert tab', () => {+ const layout = (menuSchema as any)[RibbonStartGroup.LAYOUT];+ const media = (menuSchema as any)[RibbonInsertGroup.MEDIA];++ expect(layout[HorizontalLineCommand.id]).toBeUndefined();+ expect(layout[CheckListCommand.id]).toBeUndefined();+ expect(media[HorizontalLineCommand.id].menuItemFactory).toBeDefined();+ expect(media[CheckListCommand.id].menuItemFactory).toBeDefined();+ });++ it('keeps the doc mode switch beside page settings', () => {+ const layout = (menuSchema as any)[RibbonStartGroup.LAYOUT];++ expect(layout[SwitchDocModeCommand.id].order).toBe(11);+ expect(layout[SwitchDocModeCommand.id].menuItemFactory).toBe(DocSwitchModeMenuItemFactory);+ });++ it('adds a text style menu for the floating toolbar', () => {+ const format = (menuSchema as any)[RibbonStartGroup.FORMAT];+ const floatToolbar = (menuSchema as any)[FLOAT_TOOLBAR_MENU_POSITION];++ expect(format[FLOAT_TEXT_STYLE_MENU_ID]).toBeUndefined();+ expect(floatToolbar[FLOAT_TEXT_STYLE_MENU_ID].order).toBe(0);++ const item = FloatTextStyleMenuItemFactory({ get: () => ({ get: () => undefined, register: () => undefined }) } as never);+ expect(item.type).toBe(MenuItemType.SELECTOR);+ expect(item.commandId).toBe(SetParagraphNamedStyleCommand.id);+ expect((item.selections as Array<{ id?: string; value?: string | number }>).map((option) => [option.id, option.value])).toEqual([+ [undefined, NamedStyleType.NORMAL_TEXT],+ [undefined, NamedStyleType.HEADING_1],+ [undefined, NamedStyleType.HEADING_2],+ [undefined, NamedStyleType.HEADING_3],+ [undefined, NamedStyleType.HEADING_4],+ [undefined, NamedStyleType.HEADING_5],+ [OrderListCommand.id, PresetListType.ORDER_LIST],+ [BulletListCommand.id, PresetListType.BULLET_LIST],+ [CheckListCommand.id, PresetListType.CHECK_LIST],+ ]);+ expect((item.selections as Array<{ label?: string }>).map((option) => option.label)).toEqual([+ 'ui.toolbar.heading.normal',+ 'ui.toolbar.heading.1',+ 'ui.toolbar.heading.2',+ 'ui.toolbar.heading.3',+ 'ui.toolbar.heading.4',+ 'ui.toolbar.heading.5',+ 'docs-ui.toolbar.order',+ 'docs-ui.toolbar.unorder',+ 'docs-ui.toolbar.checklist',+ ]);+ });++ it('uses current-paragraph first-level actions for empty paragraph menus', () => {+ const paragraph = (menuSchema as any)[ContextMenuPosition.PARAGRAPH];+ const insertBelow = paragraph[ContextMenuGroup.LAYOUT][INSERT_BELLOW_MENU_ID];+ const contentInsertQuick = paragraph[DOC_CONTENT_INSERT_MENU_ID][ContextMenuGroup.QUICK];+ const contentInsert = paragraph[DOC_CONTENT_INSERT_MENU_ID][ContextMenuGroup.LAYOUT];+ const emptyMenu = paragraph[EMPTY_PARAGRAPH_MENU_ID];+ const quick = emptyMenu[ContextMenuGroup.QUICK];+ const layout = emptyMenu[ContextMenuGroup.LAYOUT];++ expect(quick.order).toBe(-1);+ expect(contentInsertQuick.order).toBe(-2);+ expect(contentInsertQuick.quickLayout).toBe('icon');+ expect(layout.order).toBe(1);+ expect(quick[DocParagraphSettingPanelOperation.id]).toBeUndefined();+ expect(paragraph[ContextMenuGroup.LAYOUT][DocParagraphSettingPanelOperation.id].order).toBeLessThan(insertBelow.order);+ expect(layout[DocParagraphSettingPanelOperation.id].order).toBeLessThan(layout[BulletListCommand.id].order);+ expect(quick[H1HeadingCommand.id].menuItemFactory).toBeDefined();+ expect(paragraph[ContextMenuGroup.QUICK][TitleHeadingCommand.id].menuItemFactory).toBeDefined();+ expect(paragraph[ContextMenuGroup.QUICK][SubtitleHeadingCommand.id].menuItemFactory).toBeDefined();+ expect(paragraph[ContextMenuGroup.QUICK][TitleHeadingCommand.id].order).toBeLessThan(quick[H1HeadingCommand.id].order);+ expect(paragraph[ContextMenuGroup.QUICK][SubtitleHeadingCommand.id].order).toBeLessThan(quick[H1HeadingCommand.id].order);+ expect(quick[NormalTextHeadingCommand.id].menuItemFactory).toBeDefined();+ expect(contentInsertQuick[H1HeadingCommand.id].menuItemFactory).toBeDefined();+ expect(contentInsertQuick[NormalTextHeadingCommand.id].menuItemFactory).toBeDefined();+ expect(paragraph[ContextMenuGroup.QUICK][OrderListCommand.id]).toBeUndefined();+ expect(paragraph[ContextMenuGroup.QUICK][BulletListCommand.id]).toBeUndefined();+ expect(paragraph[ContextMenuGroup.QUICK][CheckListCommand.id]).toBeUndefined();++ expect(insertBelow[InsertOrderListBellowCommand.id].menuItemFactory).toBeDefined();+ expect(insertBelow[InsertBulletListBellowCommand.id].menuItemFactory).toBeDefined();+ expect(insertBelow[InsertCheckListBellowCommand.id].menuItemFactory).toBeDefined();+ expect(insertBelow[InsertHorizontalLineBellowCommand.id].menuItemFactory).toBeDefined();+ expect(insertBelow[DocCreateTableOperation.id].menuItemFactory).toBe(InsertDefaultTableMenuFactory);+ expect(contentInsert[InsertOrderListBellowCommand.id].menuItemFactory).toBeDefined();+ expect(contentInsert[InsertBulletListBellowCommand.id].menuItemFactory).toBeDefined();+ expect(contentInsert[InsertCheckListBellowCommand.id].menuItemFactory).toBeDefined();+ expect(contentInsert[InsertHorizontalLineBellowCommand.id].menuItemFactory).toBeDefined();+ expect(contentInsert[DocCreateTableOperation.id].menuItemFactory).toBe(InsertDefaultTableMenuFactory);++ expect(layout[OrderListCommand.id].menuItemFactory).toBeDefined();+ expect(layout[BulletListCommand.id].menuItemFactory).toBeDefined();+ expect(layout[CheckListCommand.id].menuItemFactory).toBeDefined();+ expect(layout[HorizontalLineCommand.id].menuItemFactory).toBeDefined();+ expect(layout[DocCreateTableOperation.id].menuItemFactory).toBe(InsertDefaultTableMenuFactory);+ expect(emptyMenu[ContextMenuGroup.FORMAT]).toBeUndefined();+ expect(emptyMenu[INSERT_BELLOW_MENU_ID]).toBeUndefined();+ expect(layout[InsertHorizontalLineBellowCommand.id]).toBeUndefined();+ });++ it('uses the same table icon in paragraph insert menus', () => {+ const item = InsertTableMenuFactory({ get: () => undefined } as never);++ expect(item.icon).toBe('GridIcon');+ });++ it('uses a compact table block menu without text style actions', () => {+ const paragraph = (menuSchema as any)[ContextMenuPosition.PARAGRAPH];+ const tableMenu = paragraph[DOC_TABLE_BLOCK_MENU_ID];+ const format = tableMenu[ContextMenuGroup.FORMAT];+ const layout = tableMenu[ContextMenuGroup.LAYOUT];++ expect(tableMenu[ContextMenuGroup.QUICK]).toBeUndefined();+ expect(format[DocTableDeleteTableCommand.id].menuItemFactory).toBeDefined();+ expect(format[H1HeadingCommand.id]).toBeUndefined();+ expect(format[NormalTextHeadingCommand.id]).toBeUndefined();+ expect(layout[INSERT_BELLOW_MENU_ID][DocCreateTableOperation.id].menuItemFactory).toBe(InsertDefaultTableMenuFactory);+ });++ it('uses direct table creation for paragraph insert table actions', () => {+ const item = InsertDefaultTableMenuFactory({ get: () => undefined } as never);++ expect(item.commandId).toBe(CreateDocTableCommand.id);+ expect(item.params).toEqual({ rowCount: 3, colCount: 5 });+ expect(item.icon).toBe('GridIcon');+ expect(item.title).toBe('docs-ui.toolbar.table.insert');+ });+});diff --git a/packages/docs-ui/src/menu/menu.ts b/packages/docs-ui/src/menu/menu.tsindex f8069335dd..418590e23c 100644--- a/packages/docs-ui/src/menu/menu.ts+++ b/packages/docs-ui/src/menu/menu.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { DocumentDataModel, IAccessor, PresetListType } from '@univerjs/core';+import type { DocumentDataModel, IAccessor, ITextRangeParam, Nullable } from '@univerjs/core';import type { IRichTextEditingMutationParams } from '@univerjs/docs';import type { IMenuButtonItem, IMenuItem, IMenuSelectorItem } from '@univerjs/ui';import {@@ -29,6 +29,7 @@ import {IUniverInstanceService,NAMED_STYLE_MAP,NamedStyleType,+ PresetListType,ThemeService,Tools,UniverInstanceType,@@ -40,9 +41,11 @@ import {SetTextSelectionsOperation,} from '@univerjs/docs';import { DocumentEditArea, IRenderManagerService } from '@univerjs/engine-render';+import { H1Icon, H2Icon, H3Icon, H4Icon, H5Icon, TextTypeIcon } from '@univerjs/icons';import {COLOR_PICKER_COMPONENT,COMMON_LABEL_COMPONENT,+ ComponentManager,FONT_FAMILY_COMPONENT,FONT_FAMILY_ITEM_COMPONENT,FONT_SIZE_COMPONENT,@@ -61,6 +64,7 @@ import { BulletListCommand, CheckListCommand, OrderListCommand } from '../commanimport { AlignCenterCommand, AlignJustifyCommand, AlignLeftCommand, AlignOperationCommand, AlignRightCommand } from '../commands/commands/paragraph-align.command';import { 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 { DocCreateTableOperation } from '../commands/operations/doc-create-table.operation';import { DocOpenPageSettingCommand } from '../commands/operations/open-page-setting.operation';import { getCommandSkeleton } from '../commands/util';@@ -216,6 +220,7 @@ function getTableDisabledObservable(accessor: IAccessor): Observable<boolean> {export function disableMenuWhenNoDocRange(accessor: IAccessor): Observable<boolean> {const docSelectionManagerService = accessor.get(DocSelectionManagerService);+ const univerInstanceService = accessor.get(IUniverInstanceService);return new Observable((subscriber) => {const subscription = docSelectionManagerService.textSelection$.subscribe((selection) => {@@ -231,6 +236,15 @@ export function disableMenuWhenNoDocRange(accessor: IAccessor): Observable<boolereturn;}+ const document = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);+ const codeBlockRanges = document?.getBody()?.blockRanges?.filter((range) => range.blockType === 'code') ?? [];+ if (codeBlockRanges.some((blockRange) => textRanges.some((range) => (+ Math.max(range.startOffset, blockRange.startIndex) <= Math.min(range.endOffset, blockRange.endIndex)+ )))) {+ subscriber.next(true);+ return;+ }+subscriber.next(false);});@@ -238,6 +252,38 @@ export function disableMenuWhenNoDocRange(accessor: IAccessor): Observable<boole});}+export function isTextRangeInAnyBlockRange(document: Nullable<DocumentDataModel>, range: ITextRangeParam): boolean {+ const blockRanges = document?.getBody()?.blockRanges ?? [];+ const startOffset = range.startOffset;+ const endOffset = range.collapsed ? range.startOffset : range.endOffset - 1;++ return blockRanges.some((blockRange) => (+ Math.max(startOffset, blockRange.startIndex) <= Math.min(endOffset, blockRange.endIndex)+ ));+}++export function hideMenuWhenSelectionInBlockRange(accessor: IAccessor): Observable<boolean> {+ const docSelectionManagerService = accessor.get(DocSelectionManagerService);+ const univerInstanceService = accessor.get(IUniverInstanceService);++ return new Observable((subscriber) => {+ const calc = (selection?: { textRanges?: ITextRangeParam[]; unitId?: string }) => {+ const currentSelection = (docSelectionManagerService as { __getCurrentSelection?: () => { unitId?: string } | null }).__getCurrentSelection?.();+ const textRanges = selection?.textRanges ?? [...(docSelectionManagerService.getTextRanges() ?? [])];+ const unitId = selection?.unitId ?? currentSelection?.unitId;+ const document = unitId+ ? univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC)+ : univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);+ subscriber.next(textRanges.some((range) => isTextRangeInAnyBlockRange(document, range)));+ };++ calc();+ const subscription = docSelectionManagerService.textSelection$.subscribe((selection) => calc(selection));++ return () => subscription.unsubscribe();+ });+}+export function BoldMenuItemFactory(accessor: IAccessor): IMenuButtonItem {const commandService = accessor.get(ICommandService);@@ -577,7 +623,7 @@ export function HeadingSelectorMenuItemFactory(accessor: IAccessor): IMenuSelectreturn {id: SetParagraphNamedStyleCommand.id,type: MenuItemType.SELECTOR,- tooltip: 'docs-ui.toolbar.heading.tooltip',+ tooltip: 'ui.toolbar.heading.tooltip',label: {name: COMMON_LABEL_COMPONENT,props: {@@ -624,6 +670,133 @@ export function HeadingSelectorMenuItemFactory(accessor: IAccessor): IMenuSelect};}+export const FLOAT_TEXT_STYLE_MENU_ID = 'doc.menu.float-text-style';+export const FLOAT_TOOLBAR_MENU_POSITION = 'doc.menu.float-toolbar';++const FLOAT_TEXT_STYLE_OPTIONS = [+ {+ icon: 'TextTypeIcon',+ label: 'ui.toolbar.heading.normal',+ value: NamedStyleType.NORMAL_TEXT,+ },+ {+ icon: 'H1Icon',+ label: 'ui.toolbar.heading.1',+ value: NamedStyleType.HEADING_1,+ },+ {+ icon: 'H2Icon',+ label: 'ui.toolbar.heading.2',+ value: NamedStyleType.HEADING_2,+ },+ {+ icon: 'H3Icon',+ label: 'ui.toolbar.heading.3',+ value: NamedStyleType.HEADING_3,+ },+ {+ icon: 'H4Icon',+ label: 'ui.toolbar.heading.4',+ value: NamedStyleType.HEADING_4,+ },+ {+ icon: 'H5Icon',+ label: 'ui.toolbar.heading.5',+ value: NamedStyleType.HEADING_5,+ },+ {+ id: OrderListCommand.id,+ icon: 'OrderIcon',+ label: 'docs-ui.toolbar.order',+ value: PresetListType.ORDER_LIST,+ },+ {+ id: BulletListCommand.id,+ icon: 'UnorderIcon',+ label: 'docs-ui.toolbar.unorder',+ value: PresetListType.BULLET_LIST,+ },+ {+ id: CheckListCommand.id,+ icon: 'TodoListDoubleIcon',+ label: 'docs-ui.toolbar.checklist',+ value: PresetListType.CHECK_LIST,+ },+];++function registerFloatingTextStyleIcons(componentManager: ComponentManager): void {+ ([+ ['TextTypeIcon', TextTypeIcon],+ ['H1Icon', H1Icon],+ ['H2Icon', H2Icon],+ ['H3Icon', H3Icon],+ ['H4Icon', H4Icon],+ ['H5Icon', H5Icon],+ ] as const).forEach(([key, component]) => {+ if (!componentManager.get(key)) {+ componentManager.register(key, component);+ }+ });+}++function normalizeFloatingTextStyleValue(paragraph: ReturnType<typeof getParagraphStyleAtCursor>): string | number {+ const listType = paragraph?.bullet?.listType;++ if (listType?.startsWith(PresetListType.ORDER_LIST)) {+ return PresetListType.ORDER_LIST;+ }++ if (listType?.startsWith(PresetListType.BULLET_LIST)) {+ return PresetListType.BULLET_LIST;+ }++ if (listType === PresetListType.CHECK_LIST || listType === PresetListType.CHECK_LIST_CHECKED) {+ return PresetListType.CHECK_LIST;+ }++ return paragraph?.paragraphStyle?.namedStyleType ?? NamedStyleType.NORMAL_TEXT;+}++export function FloatTextStyleMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<string | number> {+ const commandService = accessor.get(ICommandService);+ const componentManager = accessor.get(ComponentManager);++ registerFloatingTextStyleIcons(componentManager);++ return {+ id: FLOAT_TEXT_STYLE_MENU_ID,+ commandId: SetParagraphNamedStyleCommand.id,+ type: MenuItemType.SELECTOR,+ icon: 'TextTypeIcon',+ tooltip: 'ui.toolbar.heading.tooltip',+ selections: FLOAT_TEXT_STYLE_OPTIONS,+ value$: new Observable((subscriber) => {+ const calc = () => {+ subscriber.next(normalizeFloatingTextStyleValue(getParagraphStyleAtCursor(accessor)));+ };++ const disposable = commandService.onCommandExecuted((c) => {+ const id = c.id;++ if (+ id === SetTextSelectionsOperation.id ||+ id === SetParagraphNamedStyleCommand.id ||+ id === OrderListCommand.id ||+ id === BulletListCommand.id ||+ id === CheckListCommand.id+ ) {+ calc();+ }+ });++ calc();+ return disposable.dispose;+ }),+ disabled$: disableMenuWhenNoDocRange(accessor),+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),+ };+}+export function TextColorSelectorMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<string, string | undefined> {const commandService = accessor.get(ICommandService);const themeService = accessor.get(ThemeService);@@ -719,6 +892,22 @@ export function InsertTableMenuFactory(_accessor: IAccessor): IMenuButtonItem {id: DocCreateTableOperation.id,title: 'docs-ui.toolbar.table.insert',type: MenuItemType.BUTTON,+ icon: TableIcon,+ hidden$: getMenuHiddenObservable(_accessor, UniverInstanceType.UNIVER_DOC),+ };+}++export function InsertDefaultTableMenuFactory(_accessor: IAccessor): IMenuButtonItem {+ return {+ id: DocCreateTableOperation.id,+ commandId: CreateDocTableCommand.id,+ params: {+ rowCount: 3,+ colCount: 5,+ },+ title: 'docs-ui.toolbar.table.insert',+ type: MenuItemType.BUTTON,+ icon: TableIcon,hidden$: getMenuHiddenObservable(_accessor, UniverInstanceType.UNIVER_DOC),};}@@ -859,6 +1048,64 @@ export function AlignJustifyMenuItemFactory(accessor: IAccessor): IMenuButtonIte};}+const HORIZONTAL_ALIGN_OPTIONS = [+ {+ id: AlignLeftCommand.id,+ value: HorizontalAlign.LEFT,+ label: 'docs-ui.toolbar.alignLeft',+ icon: 'LeftJustifyingIcon',+ },+ {+ id: AlignCenterCommand.id,+ value: HorizontalAlign.CENTER,+ label: 'docs-ui.toolbar.alignCenter',+ icon: 'HorizontallyIcon',+ },+ {+ id: AlignRightCommand.id,+ value: HorizontalAlign.RIGHT,+ label: 'docs-ui.toolbar.alignRight',+ icon: 'RightJustifyingIcon',+ },+ {+ id: AlignJustifyCommand.id,+ value: HorizontalAlign.JUSTIFIED,+ label: 'docs-ui.toolbar.alignJustify',+ icon: 'AlignTextBothIcon',+ },+];++export function AlignMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<HorizontalAlign, HorizontalAlign> {+ const commandService = accessor.get(ICommandService);++ const value$ = new Observable<HorizontalAlign>((subscriber) => {+ const calc = () => {+ const paragraph = getParagraphStyleAtCursor(accessor);++ subscriber.next(paragraph?.paragraphStyle?.horizontalAlign ?? HorizontalAlign.LEFT);+ };+ const disposable = commandService.onCommandExecuted((c) => {+ if (c.id === SetTextSelectionsOperation.id || c.id === AlignOperationCommand.id) {+ calc();+ }+ });++ calc();+ return disposable.dispose;+ });++ return {+ id: AlignOperationCommand.id,+ type: MenuItemType.SELECTOR,+ icon: value$.pipe(map((alignType) => HORIZONTAL_ALIGN_OPTIONS.find((option) => option.value === alignType)?.icon ?? 'LeftJustifyingIcon')),+ tooltip: 'docs-ui.toolbar.alignLeft',+ selections: HORIZONTAL_ALIGN_OPTIONS,+ value$,+ disabled$: disableMenuWhenNoDocRange(accessor),+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC, undefined, DOCS_ZEN_EDITOR_UNIT_ID_KEY),+ };+}+export function HorizontalLineFactory(accessor: IAccessor): IMenuButtonItem {return {id: HorizontalLineCommand.id,diff --git a/packages/docs-ui/src/menu/paragraph-menu.ts b/packages/docs-ui/src/menu/paragraph-menu.tsindex c2df59e0df..0f2c1a8095 100644--- a/packages/docs-ui/src/menu/paragraph-menu.ts+++ b/packages/docs-ui/src/menu/paragraph-menu.ts@@ -15,18 +15,21 @@*/import type { IAccessor, ICommand } from '@univerjs/core';-import type { IMenuItem, IMenuSelectorItem } from '@univerjs/ui';+import type { IMenuButtonItem, IMenuItem, IMenuSelectorItem } from '@univerjs/ui';+import type { ComponentType } from 'react';import { ICommandService, NamedStyleType, UniverInstanceType } from '@univerjs/core';import { SetTextSelectionsOperation } from '@univerjs/docs';import { H1Icon, H2Icon, H3Icon, H4Icon, H5Icon, TextTypeIcon } from '@univerjs/icons';import { ComponentManager, getMenuHiddenObservable, MenuItemType } from '@univerjs/ui';+import { createElement } from 'react';import { Observable } from 'rxjs';-import { DocCopyCurrentParagraphCommand, DocCutCurrentParagraphCommand } from '../commands/commands/clipboard.command';+import { DocCopyCommand, DocCopyCurrentParagraphCommand, DocCutCurrentParagraphCommand, DocPasteCommand } from '../commands/commands/clipboard.command';import { DeleteCurrentParagraphCommand } from '../commands/commands/doc-delete.command';-import { InsertHorizontalLineBellowCommand } from '../commands/commands/doc-horizontal-line.command';+import { HorizontalLineCommand, InsertHorizontalLineBellowCommand } from '../commands/commands/doc-horizontal-line.command';import { SetInlineFormatFontSizeCommand } from '../commands/commands/inline-format.command';-import { InsertBulletListBellowCommand, InsertCheckListBellowCommand, InsertOrderListBellowCommand } from '../commands/commands/list.command';+import { BulletListCommand, CheckListCommand, InsertBulletListBellowCommand, InsertCheckListBellowCommand, InsertOrderListBellowCommand, OrderListCommand } from '../commands/commands/list.command';import { H1HeadingCommand, H2HeadingCommand, H3HeadingCommand, H4HeadingCommand, H5HeadingCommand, NormalTextHeadingCommand, SubtitleHeadingCommand, TitleHeadingCommand } from '../commands/commands/set-heading.command';+import { DocTableDeleteTableCommand } from '../commands/commands/table/doc-table-delete.command';import { disableMenuWhenNoDocRange, getParagraphStyleAtCursor } from './menu';const HEADING_MAP: Record<NamedStyleType, ICommand> = {@@ -41,18 +44,90 @@ const HEADING_MAP: Record<NamedStyleType, ICommand> = {[NamedStyleType.NAMED_STYLE_TYPE_UNSPECIFIED]: NormalTextHeadingCommand,};-export const HEADING_ICON_MAP: Record<NamedStyleType, { key: string; component: React.ComponentType<{ className: string }> }> = {+const HEADING_TITLE_MAP: Partial<Record<NamedStyleType, string>> = {+ [NamedStyleType.HEADING_1]: 'ui.toolbar.heading.1',+ [NamedStyleType.HEADING_2]: 'ui.toolbar.heading.2',+ [NamedStyleType.HEADING_3]: 'ui.toolbar.heading.3',+ [NamedStyleType.HEADING_4]: 'ui.toolbar.heading.4',+ [NamedStyleType.HEADING_5]: 'ui.toolbar.heading.5',+ [NamedStyleType.NORMAL_TEXT]: 'ui.toolbar.heading.normal',+ [NamedStyleType.TITLE]: 'ui.toolbar.heading.title',+ [NamedStyleType.SUBTITLE]: 'ui.toolbar.heading.subTitle',+};++function TitleTypeIcon({ className }: { className: string }) {+ return createElement(+ 'svg',+ {+ className,+ viewBox: '0 0 24 24',+ fill: 'currentColor',+ 'aria-hidden': true,+ },+ createElement('text', {+ x: 2,+ y: 19,+ fontFamily: 'Arial, sans-serif',+ fontSize: 19,+ fontWeight: 500,+ }, 'T'),+ createElement('text', {+ x: 15,+ y: 19,+ fontFamily: 'Arial, sans-serif',+ fontSize: 13,+ fontWeight: 500,+ }, 't')+ );+}++function SubtitleTypeIcon({ className }: { className: string }) {+ return createElement(+ 'svg',+ {+ className,+ viewBox: '0 0 24 24',+ fill: 'currentColor',+ 'aria-hidden': true,+ },+ createElement('text', {+ x: 5,+ y: 19,+ fontFamily: 'Arial, sans-serif',+ fontSize: 19,+ fontWeight: 500,+ }, 'S')+ );+}++export const HEADING_ICON_MAP: Record<NamedStyleType, { key: string; component: ComponentType<{ className: string }> }> = {[NamedStyleType.HEADING_1]: { key: 'H1Icon', component: H1Icon },[NamedStyleType.HEADING_2]: { key: 'H2Icon', component: H2Icon },[NamedStyleType.HEADING_3]: { key: 'H3Icon', component: H3Icon },[NamedStyleType.HEADING_4]: { key: 'H4Icon', component: H4Icon },[NamedStyleType.HEADING_5]: { key: 'H5Icon', component: H5Icon },[NamedStyleType.NORMAL_TEXT]: { key: 'TextTypeIcon', component: TextTypeIcon },- [NamedStyleType.TITLE]: { key: 'TextTypeIcon', component: TextTypeIcon },- [NamedStyleType.SUBTITLE]: { key: 'TextTypeIcon', component: TextTypeIcon },+ [NamedStyleType.TITLE]: { key: 'TitleTypeIcon', component: TitleTypeIcon },+ [NamedStyleType.SUBTITLE]: { key: 'SubtitleTypeIcon', component: SubtitleTypeIcon },[NamedStyleType.NAMED_STYLE_TYPE_UNSPECIFIED]: { key: 'TextTypeIcon', component: TextTypeIcon },};+export function shouldShowParagraphHeadingOption(headingType: NamedStyleType, currentType = NamedStyleType.NORMAL_TEXT): boolean {+ if (headingType === NamedStyleType.HEADING_5) {+ return currentType !== NamedStyleType.TITLE && currentType !== NamedStyleType.SUBTITLE;+ }++ if (headingType === NamedStyleType.TITLE) {+ return currentType === NamedStyleType.TITLE;+ }++ if (headingType === NamedStyleType.SUBTITLE) {+ return currentType === NamedStyleType.SUBTITLE;+ }++ return true;+}+const createHeadingSelectorMenuItemFactory = (headingType: NamedStyleType) => (accessor: IAccessor): IMenuItem => {const commandService = accessor.get(ICommandService);const componentManager = accessor.get(ComponentManager);@@ -65,7 +140,8 @@ const createHeadingSelectorMenuItemFactory = (headingType: NamedStyleType) => (aid: HEADING_MAP[headingType]!.id,type: MenuItemType.BUTTON,icon: icon.key,- tooltip: 'docs-ui.toolbar.heading.tooltip',+ title: HEADING_TITLE_MAP[headingType],+ tooltip: 'ui.toolbar.heading.tooltip',disabled$: disableMenuWhenNoDocRange(accessor),hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),activated$: new Observable((subscriber) => {@@ -104,6 +180,37 @@ export const NormalTextHeadingMenuItemFactory = createHeadingSelectorMenuItemFacexport const TitleHeadingMenuItemFactory = createHeadingSelectorMenuItemFactory(NamedStyleType.TITLE);export const SubtitleHeadingMenuItemFactory = createHeadingSelectorMenuItemFactory(NamedStyleType.SUBTITLE);+const createEmptyParagraphButtonFactory = (+ command: ICommand,+ icon: string,+ title: string+) => (accessor: IAccessor): IMenuButtonItem => {+ const componentManager = accessor.get(ComponentManager);+ const headingIcon = Object.values(HEADING_ICON_MAP).find((item) => item.key === icon);+ if (headingIcon && !componentManager.get(headingIcon.key)) {+ componentManager.register(headingIcon.key, headingIcon.component);+ }++ return {+ id: command.id,+ type: MenuItemType.BUTTON,+ icon,+ title,+ };+};++export const EMPTY_PARAGRAPH_MENU_ID = 'doc.menu.empty-paragraph';+export const EmptyParagraphH1MenuItemFactory = createEmptyParagraphButtonFactory(H1HeadingCommand, 'H1Icon', 'ui.toolbar.heading.1');+export const EmptyParagraphH2MenuItemFactory = createEmptyParagraphButtonFactory(H2HeadingCommand, 'H2Icon', 'ui.toolbar.heading.2');+export const EmptyParagraphH3MenuItemFactory = createEmptyParagraphButtonFactory(H3HeadingCommand, 'H3Icon', 'ui.toolbar.heading.3');+export const EmptyParagraphH4MenuItemFactory = createEmptyParagraphButtonFactory(H4HeadingCommand, 'H4Icon', 'ui.toolbar.heading.4');+export const EmptyParagraphH5MenuItemFactory = createEmptyParagraphButtonFactory(H5HeadingCommand, 'H5Icon', 'ui.toolbar.heading.5');+export const EmptyParagraphNormalTextMenuItemFactory = createEmptyParagraphButtonFactory(NormalTextHeadingCommand, 'TextTypeIcon', 'ui.toolbar.heading.normal');+export const EmptyParagraphOrderListMenuItemFactory = createEmptyParagraphButtonFactory(OrderListCommand, 'OrderIcon', 'docs-ui.rightClick.orderList');+export const EmptyParagraphBulletListMenuItemFactory = createEmptyParagraphButtonFactory(BulletListCommand, 'UnorderIcon', 'docs-ui.rightClick.bulletList');+export const EmptyParagraphCheckListMenuItemFactory = createEmptyParagraphButtonFactory(CheckListCommand, 'TodoListDoubleIcon', 'docs-ui.rightClick.checkList');+export const EmptyParagraphHorizontalLineMenuItemFactory = createEmptyParagraphButtonFactory(HorizontalLineCommand, 'ReduceIcon', 'docs-ui.toolbar.horizontalLine');+export const CopyCurrentParagraphMenuItemFactory = (accessor: IAccessor): IMenuItem => {return {id: DocCopyCurrentParagraphCommand.id,@@ -168,6 +275,40 @@ export const InsertHorizontalLineBellowMenuItemFactory = (accessor: IAccessor):};export const INSERT_BELLOW_MENU_ID = 'doc.menu.insert-bellow';+export const DOC_CONTENT_INSERT_MENU_ID = 'doc.menu.content-insert';+export const DOC_TABLE_BLOCK_MENU_ID = 'doc.menu.table-block';++export function getDocBlockRangeMenuId(blockType: string): string {+ return `doc.block-range.${blockType}.menu`;+}++export const TableBlockCopyMenuItemFactory = (accessor: IAccessor): IMenuItem => {+ return {+ id: DocCopyCommand.name,+ commandId: DocCopyCommand.id,+ type: MenuItemType.BUTTON,+ icon: 'CopyDoubleIcon',+ title: 'docs-ui.rightClick.copy',+ };+};++export const TableBlockPasteMenuItemFactory = (accessor: IAccessor): IMenuItem => {+ return {+ id: DocPasteCommand.id,+ type: MenuItemType.BUTTON,+ icon: 'PasteSpecialDoubleIcon',+ title: 'docs-ui.rightClick.paste',+ };+};++export const TableBlockDeleteMenuItemFactory = (accessor: IAccessor): IMenuItem => {+ return {+ id: DocTableDeleteTableCommand.id,+ type: MenuItemType.BUTTON,+ icon: 'DeleteIcon',+ title: 'docs-ui.rightClick.delete',+ };+};export function DocInsertBellowMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<string> {return {diff --git a/packages/docs-ui/src/menu/schema.ts b/packages/docs-ui/src/menu/schema.tsindex 5d6e2548c0..0cd5fe79a0 100644--- a/packages/docs-ui/src/menu/schema.ts+++ b/packages/docs-ui/src/menu/schema.ts@@ -23,8 +23,8 @@ import { HorizontalLineCommand, InsertHorizontalLineBellowCommand } from '../comimport { ResetInlineFormatTextBackgroundColorCommand, SetInlineFormatBoldCommand, SetInlineFormatFontFamilyCommand, SetInlineFormatFontSizeCommand, SetInlineFormatItalicCommand, SetInlineFormatStrikethroughCommand, SetInlineFormatSubscriptCommand, SetInlineFormatSuperscriptCommand, SetInlineFormatTextBackgroundColorCommand, SetInlineFormatTextColorCommand, SetInlineFormatUnderlineCommand } from '../commands/commands/inline-format.command';import { BulletListCommand, CheckListCommand, InsertBulletListBellowCommand, InsertCheckListBellowCommand, InsertOrderListBellowCommand, OrderListCommand } from '../commands/commands/list.command';-import { AlignCenterCommand, AlignJustifyCommand, AlignLeftCommand, AlignRightCommand } from '../commands/commands/paragraph-align.command';-import { H1HeadingCommand, H2HeadingCommand, H3HeadingCommand, H4HeadingCommand, H5HeadingCommand, NormalTextHeadingCommand, SetParagraphNamedStyleCommand } from '../commands/commands/set-heading.command';+import { AlignOperationCommand } from '../commands/commands/paragraph-align.command';+import { H1HeadingCommand, H2HeadingCommand, H3HeadingCommand, H4HeadingCommand, H5HeadingCommand, NormalTextHeadingCommand, SetParagraphNamedStyleCommand, SubtitleHeadingCommand, TitleHeadingCommand } from '../commands/commands/set-heading.command';import { SwitchDocModeCommand } from '../commands/commands/switch-doc-mode.command';import { DocTableDeleteColumnsCommand, DocTableDeleteRowsCommand, DocTableDeleteTableCommand } from '../commands/commands/table/doc-table-delete.command';import { DocTableInsertColumnLeftCommand, DocTableInsertColumnRightCommand, DocTableInsertRowAboveCommand, DocTableInsertRowBellowCommand } from '../commands/commands/table/doc-table-insert.command';@@ -50,20 +50,21 @@ import {TableInsertMenuItemFactory,} from './context-menu';import {- AlignCenterMenuItemFactory,- AlignJustifyMenuItemFactory,- AlignLeftMenuItemFactory,- AlignRightMenuItemFactory,+ AlignMenuItemFactory,BackgroundColorSelectorMenuItemFactory,BoldMenuItemFactory,BulletListMenuItemFactory,CheckListMenuItemFactory,DocSwitchModeMenuItemFactory,+ FLOAT_TEXT_STYLE_MENU_ID,+ FLOAT_TOOLBAR_MENU_POSITION,+ FloatTextStyleMenuItemFactory,FontFamilySelectorMenuItemFactory,FontSizeSelectorMenuItemFactory,HeaderFooterMenuItemFactory,HeadingSelectorMenuItemFactory,HorizontalLineFactory,+ InsertDefaultTableMenuFactory,InsertTableMenuFactory,ItalicMenuItemFactory,OrderListMenuItemFactory,@@ -77,9 +78,19 @@ import {TextColorSelectorMenuItemFactory,UnderlineMenuItemFactory,} from './menu';-import { CopyCurrentParagraphMenuItemFactory, CutCurrentParagraphMenuItemFactory, DeleteCurrentParagraphMenuItemFactory, DocInsertBellowMenuItemFactory, H1HeadingMenuItemFactory, H2HeadingMenuItemFactory, H3HeadingMenuItemFactory, H4HeadingMenuItemFactory, H5HeadingMenuItemFactory, INSERT_BELLOW_MENU_ID, InsertBulletListBellowMenuItemFactory, InsertCheckListBellowMenuItemFactory, InsertHorizontalLineBellowMenuItemFactory, InsertOrderListBellowMenuItemFactory, NormalTextHeadingMenuItemFactory } from './paragraph-menu';+import { CopyCurrentParagraphMenuItemFactory, CutCurrentParagraphMenuItemFactory, DeleteCurrentParagraphMenuItemFactory, DOC_CONTENT_INSERT_MENU_ID, DOC_TABLE_BLOCK_MENU_ID, DocInsertBellowMenuItemFactory, EMPTY_PARAGRAPH_MENU_ID, EmptyParagraphBulletListMenuItemFactory, EmptyParagraphCheckListMenuItemFactory, EmptyParagraphH1MenuItemFactory, EmptyParagraphH2MenuItemFactory, EmptyParagraphH3MenuItemFactory, EmptyParagraphH4MenuItemFactory, EmptyParagraphH5MenuItemFactory, EmptyParagraphHorizontalLineMenuItemFactory, EmptyParagraphNormalTextMenuItemFactory, EmptyParagraphOrderListMenuItemFactory, H1HeadingMenuItemFactory, H2HeadingMenuItemFactory, H3HeadingMenuItemFactory, H4HeadingMenuItemFactory, H5HeadingMenuItemFactory, INSERT_BELLOW_MENU_ID, InsertBulletListBellowMenuItemFactory, InsertCheckListBellowMenuItemFactory, InsertHorizontalLineBellowMenuItemFactory, InsertOrderListBellowMenuItemFactory, NormalTextHeadingMenuItemFactory, SubtitleHeadingMenuItemFactory, TableBlockCopyMenuItemFactory, TableBlockDeleteMenuItemFactory, TableBlockPasteMenuItemFactory, TitleHeadingMenuItemFactory } from './paragraph-menu';++export const floatToolbarMenuSchema: MenuSchemaType = {+ [FLOAT_TOOLBAR_MENU_POSITION]: {+ [FLOAT_TEXT_STYLE_MENU_ID]: {+ order: 0,+ menuItemFactory: FloatTextStyleMenuItemFactory,+ },+ },+};export const menuSchema: MenuSchemaType = {+ ...floatToolbarMenuSchema,[RibbonStartGroup.FORMAT]: {[SetInlineFormatBoldCommand.id]: {order: 0,@@ -131,25 +142,9 @@ export const menuSchema: MenuSchemaType = {},},[RibbonStartGroup.LAYOUT]: {- [AlignLeftCommand.id]: {+ [AlignOperationCommand.id]: {order: 2,- menuItemFactory: AlignLeftMenuItemFactory,- },- [AlignCenterCommand.id]: {- order: 3,- menuItemFactory: AlignCenterMenuItemFactory,- },- [AlignRightCommand.id]: {- order: 4,- menuItemFactory: AlignRightMenuItemFactory,- },- [AlignJustifyCommand.id]: {- order: 5,- menuItemFactory: AlignJustifyMenuItemFactory,- },- [HorizontalLineCommand.id]: {- order: 6,- menuItemFactory: HorizontalLineFactory,+ menuItemFactory: AlignMenuItemFactory,},[OrderListCommand.id]: {order: 7,@@ -159,10 +154,6 @@ export const menuSchema: MenuSchemaType = {order: 8,menuItemFactory: BulletListMenuItemFactory,},- [CheckListCommand.id]: {- order: 9,- menuItemFactory: CheckListMenuItemFactory,- },[OpenHeaderFooterPanelCommand.id]: {order: 10,menuItemFactory: HeaderFooterMenuItemFactory,@@ -185,6 +176,14 @@ export const menuSchema: MenuSchemaType = {menuItemFactory: InsertTableMenuFactory,},},+ [HorizontalLineCommand.id]: {+ order: 3,+ menuItemFactory: HorizontalLineFactory,+ },+ [CheckListCommand.id]: {+ order: 4,+ menuItemFactory: CheckListMenuItemFactory,+ },},[ContextMenuPosition.MAIN_AREA]: {[ContextMenuGroup.QUICK]: ({@@ -273,22 +272,18 @@ export const menuSchema: MenuSchemaType = {order: 4,menuItemFactory: H5HeadingMenuItemFactory,},+ [TitleHeadingCommand.id]: {+ order: -1,+ menuItemFactory: TitleHeadingMenuItemFactory,+ },+ [SubtitleHeadingCommand.id]: {+ order: -1,+ menuItemFactory: SubtitleHeadingMenuItemFactory,+ },[NormalTextHeadingCommand.id]: {order: 5,menuItemFactory: NormalTextHeadingMenuItemFactory,},- [OrderListCommand.id]: {- order: 6,- menuItemFactory: OrderListMenuItemFactory,- },- [BulletListCommand.id]: {- order: 7,- menuItemFactory: BulletListMenuItemFactory,- },- [CheckListCommand.id]: {- order: 8,- menuItemFactory: CheckListMenuItemFactory,- },},[ContextMenuGroup.FORMAT]: {[DocCopyCurrentParagraphCommand.id]: {@@ -305,8 +300,12 @@ export const menuSchema: MenuSchemaType = {},},[ContextMenuGroup.LAYOUT]: {- // title: 'docs-ui.rightClick.insertBellow',+ [DocParagraphSettingPanelOperation.id]: {+ order: 0,+ menuItemFactory: ParagraphSettingMenuFactory,+ },[INSERT_BELLOW_MENU_ID]: {+ order: 1,menuItemFactory: DocInsertBellowMenuItemFactory,[InsertBulletListBellowCommand.id]: {order: 0,@@ -324,6 +323,162 @@ export const menuSchema: MenuSchemaType = {order: 3,menuItemFactory: InsertHorizontalLineBellowMenuItemFactory,},+ [DocCreateTableOperation.id]: {+ order: 4,+ menuItemFactory: InsertDefaultTableMenuFactory,+ },+ },+ },+ [DOC_CONTENT_INSERT_MENU_ID]: {+ [ContextMenuGroup.QUICK]: {+ order: -2,+ quickLayout: 'icon',+ [H1HeadingCommand.id]: {+ order: 0,+ menuItemFactory: H1HeadingMenuItemFactory,+ },+ [H2HeadingCommand.id]: {+ order: 1,+ menuItemFactory: H2HeadingMenuItemFactory,+ },+ [H3HeadingCommand.id]: {+ order: 2,+ menuItemFactory: H3HeadingMenuItemFactory,+ },+ [H4HeadingCommand.id]: {+ order: 3,+ menuItemFactory: H4HeadingMenuItemFactory,+ },+ [H5HeadingCommand.id]: {+ order: 4,+ menuItemFactory: H5HeadingMenuItemFactory,+ },+ [NormalTextHeadingCommand.id]: {+ order: 5,+ menuItemFactory: NormalTextHeadingMenuItemFactory,+ },+ },+ [ContextMenuGroup.LAYOUT]: {+ order: 1,+ [InsertBulletListBellowCommand.id]: {+ order: 0,+ menuItemFactory: InsertBulletListBellowMenuItemFactory,+ },+ [InsertOrderListBellowCommand.id]: {+ order: 1,+ menuItemFactory: InsertOrderListBellowMenuItemFactory,+ },+ [InsertCheckListBellowCommand.id]: {+ order: 2,+ menuItemFactory: InsertCheckListBellowMenuItemFactory,+ },+ [InsertHorizontalLineBellowCommand.id]: {+ order: 3,+ menuItemFactory: InsertHorizontalLineBellowMenuItemFactory,+ },+ [DocCreateTableOperation.id]: {+ order: 4,+ menuItemFactory: InsertDefaultTableMenuFactory,+ },+ },+ },+ [EMPTY_PARAGRAPH_MENU_ID]: {+ [ContextMenuGroup.QUICK]: {+ order: -1,+ quickLayout: 'icon',+ [H1HeadingCommand.id]: {+ order: 0,+ menuItemFactory: EmptyParagraphH1MenuItemFactory,+ },+ [H2HeadingCommand.id]: {+ order: 1,+ menuItemFactory: EmptyParagraphH2MenuItemFactory,+ },+ [H3HeadingCommand.id]: {+ order: 2,+ menuItemFactory: EmptyParagraphH3MenuItemFactory,+ },+ [H4HeadingCommand.id]: {+ order: 3,+ menuItemFactory: EmptyParagraphH4MenuItemFactory,+ },+ [H5HeadingCommand.id]: {+ order: 4,+ menuItemFactory: EmptyParagraphH5MenuItemFactory,+ },+ [NormalTextHeadingCommand.id]: {+ order: 5,+ menuItemFactory: EmptyParagraphNormalTextMenuItemFactory,+ },+ },+ [ContextMenuGroup.LAYOUT]: {+ order: 1,+ [DocParagraphSettingPanelOperation.id]: {+ order: 0,+ menuItemFactory: ParagraphSettingMenuFactory,+ },+ [BulletListCommand.id]: {+ order: 1,+ menuItemFactory: EmptyParagraphBulletListMenuItemFactory,+ },+ [OrderListCommand.id]: {+ order: 2,+ menuItemFactory: EmptyParagraphOrderListMenuItemFactory,+ },+ [CheckListCommand.id]: {+ order: 3,+ menuItemFactory: EmptyParagraphCheckListMenuItemFactory,+ },+ [HorizontalLineCommand.id]: {+ order: 4,+ menuItemFactory: EmptyParagraphHorizontalLineMenuItemFactory,+ },+ [DocCreateTableOperation.id]: {+ order: 5,+ menuItemFactory: InsertDefaultTableMenuFactory,+ },+ },+ },+ [DOC_TABLE_BLOCK_MENU_ID]: {+ [ContextMenuGroup.FORMAT]: {+ [DocCopyCommand.name]: {+ order: 0,+ menuItemFactory: TableBlockCopyMenuItemFactory,+ },+ [DocPasteCommand.id]: {+ order: 1,+ menuItemFactory: TableBlockPasteMenuItemFactory,+ },+ [DocTableDeleteTableCommand.id]: {+ order: 2,+ menuItemFactory: TableBlockDeleteMenuItemFactory,+ },+ },+ [ContextMenuGroup.LAYOUT]: {+ [INSERT_BELLOW_MENU_ID]: {+ order: 0,+ menuItemFactory: DocInsertBellowMenuItemFactory,+ [InsertBulletListBellowCommand.id]: {+ order: 0,+ menuItemFactory: InsertBulletListBellowMenuItemFactory,+ },+ [InsertOrderListBellowCommand.id]: {+ order: 1,+ menuItemFactory: InsertOrderListBellowMenuItemFactory,+ },+ [InsertCheckListBellowCommand.id]: {+ order: 2,+ menuItemFactory: InsertCheckListBellowMenuItemFactory,+ },+ [InsertHorizontalLineBellowCommand.id]: {+ order: 3,+ menuItemFactory: InsertHorizontalLineBellowMenuItemFactory,+ },+ [DocCreateTableOperation.id]: {+ order: 4,+ menuItemFactory: InsertDefaultTableMenuFactory,+ },+ },},},},diff --git a/packages/docs-ui/src/plugin.ts b/packages/docs-ui/src/plugin.tsindex 980116d40d..48587c3721 100644--- a/packages/docs-ui/src/plugin.ts+++ b/packages/docs-ui/src/plugin.ts@@ -39,6 +39,7 @@ import { BreakLineCommand } from './commands/commands/break-line.command';import { DocCopyCommand, DocCopyCurrentParagraphCommand, DocCutCommand, DocCutCurrentParagraphCommand, DocPasteCommand } from './commands/commands/clipboard.command';import { CutContentCommand, InnerPasteCommand } from './commands/commands/clipboard.inner.command';import { DeleteCommand, InsertCommand, UpdateCommand } from './commands/commands/core-editing.command';+import { MoveDocBlockCommand } from './commands/commands/doc-block-move.command';import { DeleteCurrentParagraphCommand, DeleteCustomBlockCommand, DeleteLeftCommand, DeleteRightCommand, MergeTwoParagraphCommand, RemoveHorizontalLineCommand } from './commands/commands/doc-delete.command';import { CloseHeaderFooterCommand } from './commands/commands/doc-header-footer.command';import { HorizontalLineCommand, InsertHorizontalLineBellowCommand } from './commands/commands/doc-horizontal-line.command';@@ -114,6 +115,7 @@ import { DocRenderController } from './controllers/render-controllers/doc.renderimport { DocZoomRenderController } from './controllers/render-controllers/zoom.render-controller';import { DocClipboardService, IDocClipboardService } from './services/clipboard/clipboard.service';import { DocAutoFormatService } from './services/doc-auto-format.service';+import { DocContentInsertService } from './services/doc-content-insert.service';import { DocEventManagerService } from './services/doc-event-manager.service';import { DocIMEInputManagerService } from './services/doc-ime-input-manager.service';import { DocMenuStyleService } from './services/doc-menu-style.service';@@ -220,6 +222,7 @@ export class UniverDocsUIPlugin extends Plugin {InsertCommand,DeleteCommand,DeleteCustomBlockCommand,+ MoveDocBlockCommand,UpdateCommand,MergeTwoParagraphCommand,RemoveHorizontalLineCommand,@@ -331,6 +334,7 @@ export class UniverDocsUIPlugin extends Plugin {[DocsRenderService],[DocStateChangeManagerService],[DocAutoFormatService],+ [DocContentInsertService],[DocMenuStyleService],], this._config.override);diff --git a/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.tsnew file mode 100644index 0000000000..beb23b54ac--- /dev/null+++ b/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts@@ -0,0 +1,383 @@+/**+ * 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 { IMutiPageParagraphBound } from '../doc-event-manager.service';+import { DataStreamTreeTokenType, PresetListType } from '@univerjs/core';+import { DocumentEditArea } from '@univerjs/engine-render';+import { BehaviorSubject, Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { getPreferredParagraphBoundsInRange, getTableBlockMenuHoverRect, getTableHorizontalViewportGeometry } from '../doc-event-manager.service';+import { DocParagraphMenuService } from '../doc-paragraph-menu.service';++describe('DocParagraphMenuService', () => {+ it('shows the paragraph menu for empty paragraphs', () => {+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));+ const service = createService({+ attachPopupToRect,+ dataStream: '\r',+ });++ service.showParagraphMenu(createParagraphBound({+ paragraphStart: 0,+ paragraphEnd: 0,+ startIndex: 0,+ }));++ expect(attachPopupToRect).toHaveBeenCalledTimes(1);+ });++ it('keeps hiding the paragraph menu for image-only paragraphs', () => {+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));+ const service = createService({+ attachPopupToRect,+ dataStream: '\b\r',+ });++ service.showParagraphMenu(createParagraphBound({+ paragraphStart: 0,+ paragraphEnd: 1,+ startIndex: 1,+ }));++ expect(attachPopupToRect).not.toHaveBeenCalled();+ });++ it('anchors paragraph menu to the latest paragraph bound after layout changes', () => {+ const latestFirstLine = { bottom: 30, left: 20, right: 120, top: 10 };+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));+ const service = createService({+ attachPopupToRect,+ dataStream: 'Title\r',+ findParagraphBoundByIndex: vi.fn(() => ({+ firstLine: latestFirstLine,+ })),+ });++ service.showParagraphMenu(createParagraphBound({+ paragraphStart: 0,+ paragraphEnd: 5,+ startIndex: 5,+ }));++ const [anchor] = attachPopupToRect.mock.calls[0] as unknown as [() => unknown];+ expect(typeof anchor).toBe('function');+ expect(anchor()).toBe(latestFirstLine);+ });++ it('uses one paragraph menu for paragraphs in the same block range', () => {+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));+ const blockText = `${DataStreamTreeTokenType.BLOCK_START}A\rB\r${DataStreamTreeTokenType.BLOCK_END}`;+ const service = createService({+ attachPopupToRect,+ dataStream: blockText,+ blockRanges: [{ blockId: 'block-1', blockType: 'quote', startIndex: 0, endIndex: blockText.length - 1 }],+ });++ service.showParagraphMenu(createParagraphBound({+ paragraphStart: 1,+ paragraphEnd: 3,+ startIndex: 2,+ }));+ service.showParagraphMenu(createParagraphBound({+ paragraphStart: 3,+ paragraphEnd: 5,+ startIndex: 4,+ }));++ expect(attachPopupToRect).toHaveBeenCalledTimes(1);+ });++ it('anchors a block range menu to the block top-left instead of the visible paragraph', () => {+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));+ const blockText = `${DataStreamTreeTokenType.BLOCK_START}A\rB\r${DataStreamTreeTokenType.BLOCK_END}`;+ const firstBlockParagraph = createParagraphBound({+ paragraphStart: 1,+ paragraphEnd: 3,+ startIndex: 2,+ });+ firstBlockParagraph.firstLine = { bottom: 20, left: 10, right: 100, top: 0 };+ const secondBlockParagraph = createParagraphBound({+ paragraphStart: 3,+ paragraphEnd: 5,+ startIndex: 4,+ });+ secondBlockParagraph.firstLine = { bottom: 90, left: 20, right: 100, top: 70 };+ const service = createService({+ attachPopupToRect,+ dataStream: blockText,+ blockRanges: [{ blockId: 'block-1', blockType: 'quote', startIndex: 0, endIndex: blockText.length - 1 }],+ paragraphBounds: new Map([+ [2, firstBlockParagraph],+ [4, secondBlockParagraph],+ ]),+ viewportScrollY: 60,+ });++ service.showParagraphMenu(secondBlockParagraph);++ const [anchor] = attachPopupToRect.mock.calls[0] as unknown as [() => { bottom: number; left: number; right: number; top: number }];+ expect(anchor()).toMatchObject({+ bottom: 0,+ left: 10,+ right: 10,+ top: 0,+ });+ });++ it('anchors the table menu at the table top-left drag handle position', () => {+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));+ const service = createService({+ attachPopupToRect,+ dataStream: '',+ tables: [{ tableId: 'table-1', startIndex: 10, endIndex: 30 }],+ });++ service.showTableMenu({+ pageIndex: 0,+ rect: {+ bottom: 170,+ left: 100,+ right: 400,+ top: 80,+ },+ tableId: 'table-1',+ });++ const [anchor, options] = attachPopupToRect.mock.calls[0] as unknown as [() => { bottom: number; left: number; right: number; top: number }, { direction: string }];+ expect(options.direction).toBe('top-right');+ expect(anchor()).toEqual({+ bottom: 76,+ left: 96,+ right: 96,+ top: 76,+ });+ });++ it('shows a compact paragraph menu for content inside table cells', () => {+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));+ const service = createService({+ attachPopupToRect,+ dataStream: `${DataStreamTreeTokenType.TABLE_START}${DataStreamTreeTokenType.TABLE_ROW_START}${DataStreamTreeTokenType.TABLE_CELL_START}Cell\r${DataStreamTreeTokenType.TABLE_CELL_END}${DataStreamTreeTokenType.TABLE_ROW_END}${DataStreamTreeTokenType.TABLE_END}`,+ tables: [{ tableId: 'table-1', startIndex: 0, endIndex: 9 }],+ });++ service.showParagraphMenu(createParagraphBound({+ paragraphStart: 3,+ paragraphEnd: 7,+ startIndex: 7,+ }));++ expect(attachPopupToRect).toHaveBeenCalledTimes(1);+ expect(service.activeTarget?.kind).toBe('paragraph');+ expect(service.activeTarget?.draggable).toBe(true);+ expect(service.activeTarget?.cellRange).toEqual({ startOffset: 2, endOffset: 8 });+ });++ it('uses list icons for list paragraph menus', () => {+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));+ const service = createService({+ attachPopupToRect,+ dataStream: 'Item\r',+ paragraphs: [{+ startIndex: 4,+ bullet: {+ listType: PresetListType.ORDER_LIST,+ },+ }],+ });++ service.showParagraphMenu(createParagraphBound({+ paragraphStart: 0,+ paragraphEnd: 4,+ startIndex: 4,+ }));++ expect(service.activeTarget?.icon).toBe('OrderIcon');+ });++ it('keeps cell paragraph move ranges inside the current table cell', () => {+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));+ const dataStream = `${DataStreamTreeTokenType.TABLE_START}${DataStreamTreeTokenType.TABLE_ROW_START}${DataStreamTreeTokenType.TABLE_CELL_START}A\rB\r${DataStreamTreeTokenType.TABLE_CELL_END}${DataStreamTreeTokenType.TABLE_ROW_END}${DataStreamTreeTokenType.TABLE_END}`;+ const service = createService({+ attachPopupToRect,+ dataStream,+ paragraphs: [+ { startIndex: 4 },+ { startIndex: 6 },+ ],+ tables: [{ tableId: 'table-1', startIndex: 0, endIndex: dataStream.length - 1 }],+ });++ service.showParagraphMenu(createParagraphBound({+ paragraphStart: 3,+ paragraphEnd: 4,+ startIndex: 4,+ }));++ expect(service.activeTarget?.moveRange).toEqual({+ startOffset: 3,+ endOffset: 5,+ });+ });++ it('keeps a hover bridge between the table and its top-left block menu', () => {+ expect(getTableBlockMenuHoverRect({+ bottom: 170,+ left: 100,+ right: 400,+ top: 80,+ })).toEqual({+ bottom: 170,+ left: 28,+ right: 400,+ top: 38,+ });+ });++ it('projects table cell block-menu geometry through the horizontal table viewport', () => {+ expect(getTableHorizontalViewportGeometry(100, 600, {+ contentWidth: 600,+ scrollLeft: 160,+ viewportWidth: 240,+ })).toEqual({+ scrollLeft: 160,+ visibleLeft: 100,+ visibleRight: 340,+ });+ });++ it('prefers table paragraph bounds over body bounds for block range anchors', () => {+ const bodyBound = createParagraphBound({+ paragraphStart: 1,+ paragraphEnd: 3,+ startIndex: 2,+ });+ bodyBound.firstLine = { bottom: 20, left: 10, right: 100, top: 0 };+ const tableBound = createParagraphBound({+ paragraphStart: 1,+ paragraphEnd: 3,+ startIndex: 2,+ });+ tableBound.firstLine = { bottom: 20, left: 140, right: 240, top: 0 };++ expect(getPreferredParagraphBoundsInRange([bodyBound], [tableBound], 0, 4)).toEqual([tableBound]);+ });++ it('keeps the current menu mounted while block dragging is locked', () => {+ const dispose = vi.fn();+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose }));+ const service = createService({+ attachPopupToRect,+ dataStream: 'Title\r',+ });++ service.showParagraphMenu(createParagraphBound({+ paragraphStart: 0,+ paragraphEnd: 5,+ startIndex: 5,+ }));++ service.setBlockMenuDragging(true);+ service.hideParagraphMenu(true);++ expect(dispose).not.toHaveBeenCalled();+ expect(service.activeTarget?.kind).toBe('paragraph');++ service.setBlockMenuDragging(false);+ service.hideParagraphMenu(true);++ expect(dispose).toHaveBeenCalledTimes(1);+ expect(service.activeTarget).toBeNull();+ });+});++function createService(options: {+ attachPopupToRect: ReturnType<typeof vi.fn>;+ blockRanges?: Array<{ blockId: string; blockType: string; endIndex: number; startIndex: number }>;+ dataStream: string;+ findParagraphBoundByIndex?: (index: number) => unknown;+ paragraphs?: Array<{ bullet?: { listType?: PresetListType }; startIndex: number }>;+ paragraphBounds?: Map<number, IMutiPageParagraphBound>;+ tables?: Array<{ endIndex: number; startIndex: number; tableId: string }>;+ viewportScrollY?: number;+}) {+ return new DocParagraphMenuService(+ {+ unitId: 'doc-1',+ unit: {+ getBody: () => ({+ blockRanges: options.blockRanges ?? [],+ dataStream: options.dataStream,+ paragraphs: options.paragraphs ?? [],+ tables: options.tables ?? [],+ }),+ getDisabled: () => false,+ },+ engine: {+ getCanvasElement: () => ({+ getBoundingClientRect: () => ({ left: 0, top: 0 }),+ }),+ },+ scene: {+ getViewport: () => ({+ height: 300,+ onScrollAfter$: {+ subscribeEvent: vi.fn(() => ({ dispose: vi.fn() })),+ },+ viewportScrollY: options.viewportScrollY ?? 0,+ }),+ },+ } as never,+ {+ getActiveTextRange: () => null,+ replaceDocRanges: vi.fn(),+ textSelection$: new Subject(),+ } as never,+ {+ hoverParagraphRealTime$: new BehaviorSubject(null),+ hoverParagraphLeft$: new BehaviorSubject(null),+ clickCustomRanges$: new Subject(),+ findParagraphBoundByIndex: options.findParagraphBoundByIndex ?? vi.fn(() => null),+ findParagraphBoundsInRange: vi.fn((startIndex: number, endIndex: number) => [...(options.paragraphBounds ?? new Map()).values()]+ .filter((bound) => Math.max(bound.paragraphStart, startIndex) <= Math.min(bound.paragraphEnd, endIndex))),+ paragraphBounds: options.paragraphBounds ?? new Map(),+ tableBounds: new Map(),+ } as never,+ {+ attachPopupToRect: options.attachPopupToRect,+ } as never,+ {+ getViewModel: () => ({+ getEditArea: () => DocumentEditArea.BODY,+ }),+ } as never,+ {+ floatMenu: null,+ } as never+ );+}++function createParagraphBound(partial: Pick<IMutiPageParagraphBound, 'paragraphEnd' | 'paragraphStart' | 'startIndex'>): IMutiPageParagraphBound {+ const rect = { bottom: 20, left: 10, right: 100, top: 0 };++ return {+ ...partial,+ firstLine: rect,+ pageIndex: 0,+ rect,+ rects: [rect],+ };+}diff --git a/packages/docs-ui/src/services/__tests__/doc-popup-manager.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-popup-manager.service.spec.tsnew file mode 100644index 0000000000..78e3aedfa0--- /dev/null+++ b/packages/docs-ui/src/services/__tests__/doc-popup-manager.service.spec.ts@@ -0,0 +1,73 @@+/**+ * 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 { IPopup } from '@univerjs/ui';+import { EventSubject } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import { DocCanvasPopManagerService } from '../doc-popup-manager.service';++describe('DocCanvasPopManagerService', () => {+ it('refreshes rect popup positions after scene scale changes', () => {+ let scale = 1;+ const onTransformChange$ = new EventSubject();+ const onScrollAfter$ = new EventSubject();+ let popup: IPopup | undefined;+ const removePopup = vi.fn();+ const service = new DocCanvasPopManagerService(+ {+ addPopup: vi.fn((param: IPopup) => {+ popup = param;+ return 'popup-1';+ }),+ removePopup,+ activePopupId: 'other-popup',+ } as never,+ {+ getRenderById: () => ({+ engine: {+ getCanvasElement: () => ({+ getBoundingClientRect: () => ({ left: 10, top: 20, width: 1000 }),+ style: { width: '1000px' },+ }),+ },+ scene: {+ getAncestorScale: () => ({ scaleX: scale, scaleY: scale }),+ getViewport: () => ({+ onScrollAfter$,+ viewportScrollX: 0,+ viewportScrollY: 0,+ }),+ onTransformChange$,+ },+ }),+ } as never,+ {} as never,+ {+ onCommandExecuted: vi.fn(() => ({ dispose: vi.fn() })),+ } as never+ );++ service.attachPopupToRect({ left: 10, right: 110, top: 20, bottom: 40 }, { componentKey: 'test' }, 'doc-1');++ expect(popup?.anchorRect).toEqual({ left: 20, right: 120, top: 40, bottom: 60 });++ scale = 1.5;+ onTransformChange$.emitEvent({} as never);++ const anchorRect$ = popup?.anchorRect$ as { value?: unknown } | undefined;+ expect(anchorRect$?.value).toEqual({ left: 25, right: 175, top: 50, bottom: 80 });+ });+});diff --git a/packages/docs-ui/src/services/__tests__/doc-services.spec.ts b/packages/docs-ui/src/services/__tests__/doc-services.spec.tsindex ffbbafd2fb..1e25f8aabe 100644--- a/packages/docs-ui/src/services/__tests__/doc-services.spec.ts+++ b/packages/docs-ui/src/services/__tests__/doc-services.spec.ts@@ -15,7 +15,7 @@*/import type { IDocumentData, Injector, ITextStyle, Univer } from '@univerjs/core';-import { CustomRangeType, IUniverInstanceService } from '@univerjs/core';+import { CustomRangeType, DocumentFlavor, IUniverInstanceService } from '@univerjs/core';import { DocSelectionManagerService } from '@univerjs/docs';import { DocumentEditArea } from '@univerjs/engine-render';import { Subject } from 'rxjs';@@ -197,10 +197,19 @@ describe('docs ui services', () => {const created$ = new Subject<Record<string, unknown>>();const added$ = new Subject<{ unit: Record<string, unknown> }>();const disposed$ = new Subject<Record<string, unknown>>();- const existingDoc = { getUnitId: () => 'doc-1' };- const addedDoc = { getUnitId: () => 'doc-2' };+ const existingDoc = {+ getUnitId: () => 'doc-1',+ getSnapshot: () => ({ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL } }),+ };+ const addedDoc = {+ getUnitId: () => 'doc-2',+ getSnapshot: () => ({ documentStyle: { documentFlavor: DocumentFlavor.MODERN } }),+ };const removedDoc = { getUnitId: () => 'doc-3' };- const canvas = { setId: vi.fn() };+ const canvasElement = { style: {} as Record<string, string> };+ const canvas = { setId: vi.fn(), getCanvasEle: vi.fn(() => canvasElement) };+ const modernCanvasElement = { style: {} as Record<string, string> };+ const modernCanvas = { setId: vi.fn(), getCanvasEle: vi.fn(() => modernCanvasElement) };const context = { setId: vi.fn() };const renderManagerService = {createRender$,@@ -233,8 +242,22 @@ describe('docs ui services', () => {expect(canvas.setId).toHaveBeenCalledWith('univer-doc-main-canvas');expect(context.setId).toHaveBeenCalledWith('univer-doc-main-canvas');+ expect(canvasElement.style.backgroundColor).toBe('#fafafa');added$.next({ unit: addedDoc });+ created$.next({+ unitId: 'doc-2',+ engine: {+ getCanvas: () => ({+ ...modernCanvas,+ getContext: () => context,+ }),+ },+ });++ expect(modernCanvas.setId).toHaveBeenCalledWith('univer-doc-main-canvas');+ expect(modernCanvasElement.style.backgroundColor).toBe('#fff');+createRender$.next('doc-4');disposed$.next(removedDoc);diff --git a/packages/docs-ui/src/services/clipboard/__test__/html-and-udm-convert.spec.ts b/packages/docs-ui/src/services/clipboard/__test__/html-and-udm-convert.spec.tsindex 5199cea355..ac0bb82b0d 100644--- a/packages/docs-ui/src/services/clipboard/__test__/html-and-udm-convert.spec.ts+++ b/packages/docs-ui/src/services/clipboard/__test__/html-and-udm-convert.spec.ts@@ -21,6 +21,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { HtmlToUDMService } from '../html-to-udm/converter';import PastePluginLark from '../html-to-udm/paste-plugins/plugin-lark';import PastePluginWord from '../html-to-udm/paste-plugins/plugin-word';+import { createInternalClipboardFragment, embedInternalClipboardFragment, extractInternalClipboardFragmentFromHtml, wrapClipboardHtml } from '../internal-fragment';import { UDMToHtmlService } from '../udm-to-html/convertor';HtmlToUDMService.use(PastePluginWord);@@ -118,6 +119,32 @@ describe('test case in html and udm convert', () => {expect(udm.body!.dataStream).toBe('hello\rworld');});++ it('should parse semantic html blocks and lists to udm metadata', () => {+ const convertor = new HtmlToUDMService();+ const udm = convertor.convert(`+ <blockquote><p>Quote text</p></blockquote>+ <pre><code>const a = 1;</code></pre>+ <aside role="note" data-doc-type="callout"><p>💡 Callout text</p></aside>+ <ol><li>First</li><li>Second</li></ol>+ `);++ expect(udm.body?.blockRanges?.map((range) => range.blockType)).toEqual(['quote', 'code', 'callout']);+ expect(udm.body?.paragraphs?.filter((paragraph) => paragraph.bullet).map((paragraph) => paragraph.bullet?.listType)).toEqual(['ORDER_LIST', 'ORDER_LIST']);+ expect(udm.body?.dataStream).toContain('Quote text\r');+ expect(udm.body?.dataStream).toContain('const a = 1;\r');+ });++ it('should normalize word and wps mso lists to real list paragraphs', () => {+ const convertor = new HtmlToUDMService();+ const udm = convertor.convert(`+ <p class="MsoListParagraph" style="mso-list:l0 level1 lfo1">1. Alpha</p>+ <p class="MsoListParagraph" style="mso-list:l0 level2 lfo1">a. Nested</p>+ `);++ expect(udm.body?.dataStream).toBe('Alpha\rNested\r');+ expect(udm.body?.paragraphs?.map((paragraph) => paragraph.bullet?.nestingLevel)).toEqual([0, 1]);+ });});describe('test cases in udm-to-html', () => {@@ -127,5 +154,66 @@ describe('test case in html and udm convert', () => {expect(html).toBe('<p class="UniverNormal" ><strong>hello</strong><strong><i>world</i></strong></p>');});++ it('should serialize structured doc metadata as semantic clipboard html', () => {+ const convertor = new UDMToHtmlService();+ const html = convertor.convert([{+ id: '',+ documentStyle: {},+ body: {+ dataStream: 'Quote\rCode\rCallout\rItem\r',+ blockRanges: [+ { blockId: 'quote-1', blockType: 'quote', startIndex: 0, endIndex: 5 },+ { blockId: 'code-1', blockType: 'code', startIndex: 6, endIndex: 10 },+ { blockId: 'callout-1', blockType: 'callout', startIndex: 11, endIndex: 18 },+ ],+ paragraphs: [+ { startIndex: 5 },+ { startIndex: 10 },+ { startIndex: 18 },+ { startIndex: 23, bullet: { listId: 'list-1', listType: 'ORDER_LIST', nestingLevel: 0 } },+ ],+ },+ }]);++ expect(html).toContain('data-doc-type="quote"');+ expect(html).toContain('data-doc-type="code-block"');+ expect(html).toContain('data-doc-type="callout"');+ expect(html).toContain('data-doc-type="ordered-list"');+ });++ it('should serialize adjacent and nested list paragraphs as one semantic list tree', () => {+ const convertor = new UDMToHtmlService();+ const html = convertor.convert([{+ id: '',+ documentStyle: {},+ body: {+ dataStream: 'One\rNested\rTwo\r',+ paragraphs: [+ { startIndex: 3, bullet: { listId: 'list-1', listType: 'ORDER_LIST', nestingLevel: 0 } },+ { startIndex: 10, bullet: { listId: 'list-1', listType: 'BULLET_LIST', nestingLevel: 1 } },+ { startIndex: 14, bullet: { listId: 'list-1', listType: 'ORDER_LIST', nestingLevel: 0 } },+ ],+ },+ }]);++ expect(html.match(/data-doc-type="ordered-list"/g)?.length).toBe(1);+ expect(html.match(/data-doc-type="bullet-list"/g)?.length).toBe(1);+ expect(html).toContain('<li><p class="UniverNormal" >One</p><ul');+ expect(html).toContain('</ul></li><li><p class="UniverNormal" >Two</p>');+ });++ it('should embed and extract an internal clipboard fragment through html', () => {+ const fragment = createInternalClipboardFragment({+ body: {+ dataStream: 'Internal\r',+ paragraphs: [{ startIndex: 8 }],+ },+ });+ const html = wrapClipboardHtml(embedInternalClipboardFragment('<p>Internal</p>', fragment));++ expect(html).toContain('StartFragment');+ expect(extractInternalClipboardFragmentFromHtml(html)?.body?.dataStream).toBe('Internal\r');+ });});});diff --git a/packages/docs-ui/src/services/clipboard/clipboard.service.ts b/packages/docs-ui/src/services/clipboard/clipboard.service.tsindex 45a83d91d3..8dcd1c8a68 100644--- a/packages/docs-ui/src/services/clipboard/clipboard.service.ts+++ b/packages/docs-ui/src/services/clipboard/clipboard.service.ts@@ -58,6 +58,14 @@ import { HtmlToUDMService } from './html-to-udm/converter';import LarkPastePlugin from './html-to-udm/paste-plugins/plugin-lark';import UniverPastePlugin from './html-to-udm/paste-plugins/plugin-univer';import WordPastePlugin from './html-to-udm/paste-plugins/plugin-word';+import {+ createInternalClipboardFragment,+ DOC_INTERNAL_FRAGMENT_MIME,+ embedInternalClipboardFragment,+ extractInternalClipboardFragmentFromHtml,+ parseInternalClipboardFragment,+ wrapClipboardHtml,+} from './internal-fragment';import { UDMToHtmlService } from './udm-to-html/convertor';HtmlToUDMService.use(LarkPastePlugin);@@ -77,7 +85,7 @@ export interface IDocClipboardService {copy(sliceType?: SliceBodyType, ranges?: ITextRangeWithStyle[]): Promise<boolean>;cut(ranges?: ITextRangeWithStyle[]): Promise<boolean>;paste(items: ClipboardItem[]): Promise<boolean>;- legacyPaste(options: { html?: string; text?: string; files: File[] }): Promise<boolean>;+ legacyPaste(options: { html?: string; text?: string; internalJson?: string; files: File[] }): Promise<boolean>;addClipboardHook(hook: IDocClipboardHook): IDisposable;}@@ -162,10 +170,11 @@ export class DocClipboardService extends Disposable implements IDocClipboardServasync legacyPaste(options: {html?: string;+ internalJson?: string;text?: string;files: File[];}): Promise<boolean> {- let { html, text, files } = options;+ let { html, internalJson, text, files } = options;const currentDocInstance = this._univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_DOC);const docUnitId = currentDocInstance?.getUnitId() || '';if (!html && !text && files.length) {@@ -175,7 +184,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServthis._logService.warn('[DocClipboardController] html and text cannot be both empty!');return false;}- const partDocData = this._genDocDataFromHtmlAndText(html, text, docUnitId);+ const partDocData = this._genDocDataFromHtmlAndText(html, text, docUnitId, internalJson);// Paste in sheet editing mode without paste style, so we give textRuns empty array;if (docUnitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY) {if (text) {@@ -342,6 +351,8 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ.replaceAll('\r\n', ' ');let html = this._umdToHtml.convert(documentList);+ let internalJson = '';+ let internalDocData: Partial<IDocumentData> | null = null;// Only cache copy content when the range is 1.if (documentList.length === 1 && needCache) {@@ -370,9 +381,19 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ}copyContentCache.set(copyId, cache);+ internalDocData = cache;+ } else if (documentList.length === 1) {+ internalDocData = { body: documentList[0].body };+ }++ if (internalDocData) {+ internalJson = createInternalClipboardFragment(internalDocData);+ html = embedInternalClipboardFragment(html, internalJson);}- return this._clipboardInterfaceService.write(text, html);+ html = wrapClipboardHtml(html);++ return this._clipboardInterfaceService.write(text, html, internalJson ? { [DOC_INTERNAL_FRAGMENT_MIME]: internalJson } : undefined);}addClipboardHook(hook: IDocClipboardHook): IDisposable {@@ -453,10 +474,15 @@ export class DocClipboardService extends Disposable implements IDocClipboardServtry {let html = '';let text = '';+ let internalJson = '';const files: File[] = [];for (const clipboardItem of items) {for (const type of clipboardItem.types) {switch (type) {+ case DOC_INTERNAL_FRAGMENT_MIME: {+ internalJson = await clipboardItem.getType(type).then((blob) => blob && blob.text());+ break;+ }case PLAIN_TEXT_CLIPBOARD_MIME_TYPE: {text = await clipboardItem.getType(type).then((blob) => blob && blob.text());break;@@ -481,13 +507,18 @@ export class DocClipboardService extends Disposable implements IDocClipboardServhtml = await this._createImagePasteHtml(files);}- return this._genDocDataFromHtmlAndText(html, text);+ return this._genDocDataFromHtmlAndText(html, text, undefined, internalJson);} catch (e) {return Promise.reject(e);}}- private _genDocDataFromHtmlAndText(html?: string, text?: string, _unitId?: string): Partial<IDocumentData> {+ private _genDocDataFromHtmlAndText(html?: string, text?: string, _unitId?: string, internalJson?: string): Partial<IDocumentData> {+ const internalDocData = parseInternalClipboardFragment(internalJson) ?? extractInternalClipboardFragmentFromHtml(html);+ if (internalDocData?.body) {+ return internalDocData;+ }+if (!html) {if (text) {const body = BuildTextUtils.transform.fromPlainText(text);diff --git a/packages/docs-ui/src/services/clipboard/html-to-udm/converter.ts b/packages/docs-ui/src/services/clipboard/html-to-udm/converter.tsindex 0abdefda19..52a4e0233d 100644--- a/packages/docs-ui/src/services/clipboard/html-to-udm/converter.ts+++ b/packages/docs-ui/src/services/clipboard/html-to-udm/converter.ts@@ -14,16 +14,18 @@* limitations under the License.*/-import type { IDocumentBody, IDocumentData, ITable, ITextStyle, Nullable } from '@univerjs/core';+import type { IDocumentBody, IDocumentData, IParagraph, ITable, ITextStyle, Nullable } from '@univerjs/core';import type { IAfterProcessRule, IPastePlugin, IStyleRule } from './paste-plugins/type';import {CustomRangeType,DataStreamTreeTokenType,DrawingTypeEnum,generateRandomId,+ NamedStyleType,ObjectRelativeFromH,ObjectRelativeFromV,PositionedObjectLayoutType,+ PresetListType,skipParseTagNames,Tools,} from '@univerjs/core';@@ -54,6 +56,12 @@ interface ITableCache {startIndex: number;}+interface IListContext {+ listId: string;+ listType: PresetListType;+ nestingLevel: number;+}+/*** Convert html strings into data structures in univer, IDocumentBody.* Support plug-in, add custom rules,@@ -77,6 +85,10 @@ export class HtmlToUDMService {private _afterProcessRules: IAfterProcessRule[] = [];+ private _listStack: IListContext[] = [];++ private _lastParagraphIndex = -1;+convert(html: string, metaConfig: { unitId?: string } = {}): Partial<IDocumentData> {const pastePlugin = HtmlToUDMService._pluginList.find((plugin) => plugin.checkPasteType(html));const dom = parseToDom(html)!;@@ -102,6 +114,8 @@ export class HtmlToUDMService {}this._tableCache = [];+ this._listStack = [];+ this._lastParagraphIndex = -1;this._styleCache.clear();this._process(null, dom.childNodes, docData);this._styleCache.clear();@@ -183,7 +197,13 @@ export class HtmlToUDMService {continue;} else if (node.nodeType === Node.ELEMENT_NODE) {const element = node as HTMLElement;+ if (this._processCodeBlock(element, doc)) {+ continue;+ }+const linkStart = this._processBeforeLink(element, doc);+ const blockStart = this._processBeforeStructuredBlock(element, doc);+ const listContext = this._processBeforeList(element);const parentStyles = parent ? this._styleCache.get(parent) : {};const styleRule = this._styleRules.find(({ filter }) => matchFilter(node as HTMLElement, filter));@@ -200,19 +220,155 @@ export class HtmlToUDMService {this._process(node, childNodes, doc);this._processAfterTable(node as HTMLElement, doc);+ this._processAfterList(listContext);const afterProcessRule = this._afterProcessRules.find(({ filter }) =>matchFilter(node as HTMLElement, filter));+ const paragraphAddedByPlugin = Boolean(afterProcessRule);if (afterProcessRule) {afterProcessRule.handler(doc, node as HTMLElement);}+ this._processAfterDefaultBlock(element, doc, paragraphAddedByPlugin);+ this._processAfterStructuredBlock(element, doc, blockStart);this._processAfterLink(element, doc, linkStart);}}}+ private _processCodeBlock(node: HTMLElement, doc: Partial<IDocumentData>): boolean {+ if (node.tagName.toUpperCase() !== 'PRE') {+ return false;+ }++ const body = doc.body!;+ const startIndex = body.dataStream.length;+ const text = node.textContent ?? '';+ body.dataStream += text;+ this._appendParagraph(doc, node);+ body.blockRanges ??= [];+ body.blockRanges.push({+ blockId: generateRandomId(6),+ blockType: 'code',+ startIndex,+ endIndex: body.dataStream.length - 1,+ });+ return true;+ }++ private _processBeforeStructuredBlock(node: HTMLElement, doc: Partial<IDocumentData>): number | null {+ const blockType = getStructuredBlockType(node);+ if (!blockType) {+ return null;+ }++ return doc.body!.dataStream.length;+ }++ private _processAfterStructuredBlock(node: HTMLElement, doc: Partial<IDocumentData>, startIndex: number | null): void {+ const blockType = getStructuredBlockType(node);+ const body = doc.body!;+ if (!blockType || startIndex == null || body.dataStream.length <= startIndex) {+ return;+ }++ body.blockRanges ??= [];+ body.blockRanges.push({+ blockId: generateRandomId(6),+ blockType,+ startIndex,+ endIndex: body.dataStream.length - 1,+ });+ }++ private _processBeforeList(node: HTMLElement): IListContext | null {+ const tagName = node.tagName.toUpperCase();+ if (tagName !== 'OL' && tagName !== 'UL') {+ return null;+ }++ const context: IListContext = {+ listId: generateRandomId(6),+ listType: tagName === 'OL' ? PresetListType.ORDER_LIST : PresetListType.BULLET_LIST,+ nestingLevel: this._listStack.length,+ };+ this._listStack.push(context);+ return context;+ }++ private _processAfterList(context: IListContext | null): void {+ if (!context) {+ return;+ }++ this._listStack.pop();+ }++ private _processAfterDefaultBlock(node: HTMLElement, doc: Partial<IDocumentData>, paragraphAddedByPlugin: boolean): void {+ if (paragraphAddedByPlugin) {+ this._applyWordListInfo(node, doc);+ this._lastParagraphIndex = doc.body!.dataStream.length - 1;+ return;+ }++ if (!isDefaultParagraphElement(node)) {+ return;+ }++ this._appendParagraph(doc, node);+ }++ private _appendParagraph(doc: Partial<IDocumentData>, node: HTMLElement): void {+ const body = doc.body!;+ if (body.dataStream[this._lastParagraphIndex] === '\r' && this._lastParagraphIndex === body.dataStream.length - 1) {+ return;+ }++ body.paragraphs ??= [];+ const paragraph: IParagraph = {+ startIndex: body.dataStream.length,+ };++ const heading = getHeadingNamedStyleType(node);+ if (heading != null) {+ paragraph.paragraphStyle = {+ ...paragraph.paragraphStyle,+ headingId: generateRandomId(6),+ namedStyleType: heading,+ };+ }++ const listContext = this._listStack[this._listStack.length - 1] ?? extractWordListInfo(node);+ if (listContext) {+ paragraph.bullet = {+ listId: listContext.listId,+ listType: listContext.listType,+ nestingLevel: listContext.nestingLevel,+ };+ paragraph.startIndex -= stripListMarkerFromCurrentParagraph(body);+ }++ body.paragraphs.push(paragraph);+ body.dataStream += '\r';+ this._lastParagraphIndex = body.dataStream.length - 1;+ }++ private _applyWordListInfo(node: HTMLElement, doc: Partial<IDocumentData>): void {+ const listContext = extractWordListInfo(node);+ const paragraph = doc.body?.paragraphs?.[doc.body.paragraphs.length - 1];+ if (!listContext || !paragraph) {+ return;+ }++ paragraph.bullet = {+ listId: listContext.listId,+ listType: listContext.listType,+ nestingLevel: listContext.nestingLevel,+ };+ paragraph.startIndex -= stripListMarkerFromCurrentParagraph(doc.body!);+ }+private _processBeforeTable(node: HTMLElement, doc: Partial<IDocumentData>): void {const tagName = node.tagName.toUpperCase();const body = doc.body!;@@ -347,14 +503,106 @@ export class HtmlToUDMService {const element = node as HTMLElement;if (element.tagName.toUpperCase() === 'A') {+ const href = (element as HTMLAnchorElement).href;+ if (!isSafeUrl(href)) {+ return;+ }+body.customRanges = body.customRanges ?? [];body.customRanges.push({startIndex: start,endIndex: body.dataStream.length - 1,rangeId: element.dataset.rangeid ?? generateRandomId(),rangeType: CustomRangeType.HYPERLINK,- properties: { url: (element as HTMLAnchorElement).href },+ properties: { url: href },});}}}++function isSafeUrl(url: string): boolean {+ try {+ const parsed = new URL(url, window.location.origin);+ return ['http:', 'https:', 'mailto:'].includes(parsed.protocol);+ } catch {+ return false;+ }+}++function getStructuredBlockType(node: HTMLElement): string | null {+ const docType = node.dataset.docType;+ if (docType === 'quote') {+ return 'quote';+ }++ if (docType === 'callout') {+ return 'callout';+ }++ const tagName = node.tagName.toUpperCase();+ if (tagName === 'BLOCKQUOTE') {+ return docType === 'callout' ? 'callout' : 'quote';+ }++ if (tagName === 'ASIDE' && node.getAttribute('role') === 'note') {+ return 'callout';+ }++ return null;+}++function isDefaultParagraphElement(node: HTMLElement): boolean {+ const tagName = node.tagName.toUpperCase();+ return ['P', 'DIV', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'LI'].includes(tagName);+}++function getHeadingNamedStyleType(node: HTMLElement): NamedStyleType | null {+ switch (node.tagName.toUpperCase()) {+ case 'H1': return NamedStyleType.HEADING_1;+ case 'H2': return NamedStyleType.HEADING_2;+ case 'H3': return NamedStyleType.HEADING_3;+ case 'H4': return NamedStyleType.HEADING_4;+ case 'H5': return NamedStyleType.HEADING_5;+ default: return null;+ }+}++function extractWordListInfo(node: HTMLElement): IListContext | null {+ const style = node.getAttribute('style') ?? '';+ const match = style.match(/mso-list:\s*([^ ;]+)\s+level(\d+)/i);+ if (!match && !/MsoListParagraph/i.test(node.className)) {+ return null;+ }++ const marker = (node.textContent ?? '').trim().match(/^([0-9]+\.|[a-zA-Z]\.|[ivxlcdmIVXLCDM]+\.|[·•●○\-])/);+ const ordered = Boolean(marker && !/[·•●○\-]/.test(marker[1]));++ return {+ listId: match?.[1] ?? 'mso-list',+ listType: ordered ? PresetListType.ORDER_LIST : PresetListType.BULLET_LIST,+ nestingLevel: Math.max(0, Number(match?.[2] ?? 1) - 1),+ };+}++function stripListMarkerFromCurrentParagraph(body: IDocumentBody): number {+ const paragraphEnd = body.dataStream.endsWith('\r') ? body.dataStream.length - 1 : body.dataStream.length;+ const paragraphStart = Math.max(0, body.dataStream.lastIndexOf('\r', paragraphEnd - 1) + 1);+ const text = body.dataStream.slice(paragraphStart, paragraphEnd);+ const marker = text.match(/^(\s*(?:[0-9]+\.|[a-zA-Z]\.|[ivxlcdmIVXLCDM]+\.|[·•●○\-])\s*)/);+ if (!marker) {+ return 0;+ }++ const length = marker[1].length;+ body.dataStream = body.dataStream.slice(0, paragraphStart) + body.dataStream.slice(paragraphStart + length);+ body.textRuns?.forEach((textRun) => {+ if (textRun.st >= paragraphStart + length) {+ textRun.st -= length;+ textRun.ed -= length;+ } else if (textRun.ed > paragraphStart) {+ textRun.ed = Math.max(textRun.st, textRun.ed - length);+ }+ });++ return length;+}diff --git a/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/plugin-word.ts b/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/plugin-word.tsindex d763d84216..a30104fe63 100644--- a/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/plugin-word.ts+++ b/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/plugin-word.ts@@ -23,7 +23,7 @@ import { getParagraphStyle } from '../utils';const WordPastePlugin: IPastePlugin = {name: 'univer-doc-paste-plugin-word',checkPasteType(html: string) {- return /word|mso/i.test(html);+ return /word|mso|wps|kingsoft/i.test(html);},stylesRules: [diff --git a/packages/docs-ui/src/services/clipboard/internal-fragment.ts b/packages/docs-ui/src/services/clipboard/internal-fragment.tsnew file mode 100644index 0000000000..ce89c339c3--- /dev/null+++ b/packages/docs-ui/src/services/clipboard/internal-fragment.ts@@ -0,0 +1,82 @@+/**+ * 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 { IDocumentData } from '@univerjs/core';+import { Tools } from '@univerjs/core';++export const DOC_INTERNAL_FRAGMENT_MIME = 'application/x-doc-fragment+json';+export const DOC_INTERNAL_FRAGMENT_COMMENT_PREFIX = 'univer-doc-fragment:';++export interface IDocInternalClipboardFragment {+ version: 1;+ kind: 'univer-doc-fragment';+ doc: Partial<IDocumentData>;+}++export function createInternalClipboardFragment(doc: Partial<IDocumentData>): string {+ return JSON.stringify({+ version: 1,+ kind: 'univer-doc-fragment',+ doc: Tools.deepClone(doc),+ } satisfies IDocInternalClipboardFragment);+}++export function parseInternalClipboardFragment(value?: string): Partial<IDocumentData> | null {+ if (!value) {+ return null;+ }++ try {+ const parsed = JSON.parse(value) as Partial<IDocInternalClipboardFragment>;+ if (parsed?.version === 1 && parsed.kind === 'univer-doc-fragment' && parsed.doc?.body) {+ return parsed.doc as Partial<IDocumentData>;+ }+ } catch {+ return null;+ }++ return null;+}++export function embedInternalClipboardFragment(html: string, fragmentJson: string): string {+ return `<!--${DOC_INTERNAL_FRAGMENT_COMMENT_PREFIX}${encodeBase64(fragmentJson)}-->${html}`;+}++export function extractInternalClipboardFragmentFromHtml(html?: string): Partial<IDocumentData> | null {+ if (!html) {+ return null;+ }++ const escapedPrefix = DOC_INTERNAL_FRAGMENT_COMMENT_PREFIX.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ const match = html.match(new RegExp(`<!--\\s*${escapedPrefix}([A-Za-z0-9+/=]+)\\s*-->`));+ if (!match) {+ return null;+ }++ return parseInternalClipboardFragment(decodeBase64(match[1]));+}++export function wrapClipboardHtml(fragmentHtml: string): string {+ return `<html><head><meta charset="utf-8"></head><body><!--StartFragment-->${fragmentHtml}<!--EndFragment--></body></html>`;+}++function encodeBase64(value: string): string {+ return btoa(unescape(encodeURIComponent(value)));+}++function decodeBase64(value: string): string {+ return decodeURIComponent(escape(atob(value)));+}diff --git a/packages/docs-ui/src/services/clipboard/udm-to-html/convertor.ts b/packages/docs-ui/src/services/clipboard/udm-to-html/convertor.tsindex c46fd8a16b..632dcb6661 100644--- a/packages/docs-ui/src/services/clipboard/udm-to-html/convertor.ts+++ b/packages/docs-ui/src/services/clipboard/udm-to-html/convertor.ts@@ -17,7 +17,7 @@import type { IDocumentBody, IDocumentData, IParagraph, ITextRun } from '@univerjs/core';import type { IDocImage } from '@univerjs/docs-drawing';import type { DataStreamTreeNode } from '@univerjs/engine-render';-import { BaselineOffset, BooleanNumber, CustomRangeType, DataStreamTreeNodeType, DrawingTypeEnum, Tools } from '@univerjs/core';+import { BaselineOffset, BooleanNumber, CustomRangeType, DataStreamTreeNodeType, DrawingTypeEnum, NamedStyleType, PresetListType, Tools } from '@univerjs/core';import { ImageSourceType } from '@univerjs/drawing';import { parseDataStreamToTree } from '@univerjs/engine-render';@@ -47,7 +47,7 @@ export function covertTextRunToHtml(dataStream: string, textRun: ITextRun): striconst { st: start, ed, ts = {} } = textRun;const { ff, fs, it, bl, ul, st, ol, bg, cl, va } = ts;- let html = dataStream.slice(start, ed);+ let html = escapeHtml(dataStream.slice(start, ed));const style: string[] = [];// italic@@ -117,7 +117,7 @@ function getBodyInlineSlice(body: IDocumentBody, startIndex: number, endIndex: nconst { st, ed } = textRun;if (Tools.hasIntersectionBetweenTwoRanges(startIndex, endIndex, st, ed)) {if (st > cursorIndex) {- spanList.push(dataStream.slice(cursorIndex, st));+ spanList.push(escapeHtml(dataStream.slice(cursorIndex, st)));spanList.push(covertTextRunToHtml(dataStream, {...textRun,@@ -136,7 +136,7 @@ function getBodyInlineSlice(body: IDocumentBody, startIndex: number, endIndex: n}if (cursorIndex !== endIndex) {- spanList.push(dataStream.slice(cursorIndex, endIndex));+ spanList.push(escapeHtml(dataStream.slice(cursorIndex, endIndex)));}return spanList.join('');@@ -207,6 +207,13 @@ export function getBodySliceHtml(doc: IDocumentData, startIndex: number, endIndeinterface IHtmlResult {html: string;+ listStack?: IListHtmlContext[];+}++interface IListHtmlContext {+ tag: 'ol' | 'ul';+ level: number;+ listType: string;}export function convertBodyToHtml(doc: IDocumentData): string {@@ -238,6 +245,8 @@ export function convertBodyToHtml(doc: IDocumentData): string {processNode(node, doc, result);}+ closeListStack(result);+return result.html;}@@ -279,15 +288,18 @@ function processNode(node: DataStreamTreeNode, doc: IDocumentData, result: IHtmlstyle.push(`line-height: ${lineSpacing}`);}- result.html += `<p class="UniverNormal" ${style.length ? `style="${style.join('; ')};"` : ''}>`;+ const innerHtml = (() => {+ const childHtml = children.map((table) => {+ const childResult: IHtmlResult = { html: '' };+ processNode(table, doc, childResult);+ closeListStack(childResult);+ return childResult.html;+ }).join('');- if (children.length) {- for (const table of children) {- processNode(table, doc, result);- }- }+ return `${childHtml}${getBodySliceHtml(doc, startIndex, endIndex)}`;+ })();- result.html += `${getBodySliceHtml(doc, startIndex, endIndex)}</p>`;+ renderParagraphNodeHtml(doc, paragraph, startIndex, endIndex, innerHtml, style, result);break;}@@ -295,6 +307,7 @@ function processNode(node: DataStreamTreeNode, doc: IDocumentData, result: IHtmlcase DataStreamTreeNodeType.TABLE: {const { children } = node;+ closeListStack(result);result.html += '<table class="UniverTable" style="width: 100%; border-collapse: collapse;"><tbody>';for (const row of children) {@@ -325,6 +338,7 @@ function processNode(node: DataStreamTreeNode, doc: IDocumentData, result: IHtmlfor (const n of children) {processNode(n, doc, result);}+ closeListStack(result);result.html += '</td>';break;}@@ -335,6 +349,139 @@ function processNode(node: DataStreamTreeNode, doc: IDocumentData, result: IHtml}}+function renderParagraphNodeHtml(doc: IDocumentData, paragraph: IParagraph, startIndex: number, endIndex: number, innerHtml: string, style: string[], result: IHtmlResult): void {+ const listItemHtml = renderListParagraphItemHtml(doc, paragraph, innerHtml, style);+ if (listItemHtml) {+ appendListParagraphHtml(result, listItemHtml);+ return;+ }++ closeListStack(result);+ result.html += renderBlockParagraphHtml(doc, paragraph, startIndex, endIndex, innerHtml, style);+}++function renderBlockParagraphHtml(doc: IDocumentData, paragraph: IParagraph, startIndex: number, endIndex: number, innerHtml: string, style: string[]): string {+ const blockRange = doc.body?.blockRanges?.find((range) => range.startIndex <= startIndex && endIndex <= range.endIndex + 1);+ const paragraphHtml = renderHeadingParagraphHtml(paragraph, innerHtml, style)+ ?? `<p class="UniverNormal" ${style.length ? `style="${style.join('; ')};"` : ''}>${innerHtml}</p>`;++ switch (blockRange?.blockType) {+ case 'quote':+ return `<blockquote data-doc-type="quote" style="border-left: 4px solid #d0d7de; margin: 8px 0; padding: 4px 0 4px 12px; color: #57606a;">${paragraphHtml}</blockquote>`;+ case 'code':+ return `<pre data-doc-type="code-block" style="font-family: Consolas, 'Courier New', monospace; background: #f6f8fa; padding: 12px; border-radius: 6px; white-space: pre-wrap;"><code>${innerHtml.replace(/<\/?[^>]+>/g, '')}</code></pre>`;+ case 'callout':+ return `<aside data-doc-type="callout" role="note" style="background: #fff8c5; border-left: 4px solid #d4a72c; padding: 8px 12px; margin: 8px 0; border-radius: 4px;"><p><span data-callout-icon="true" style="margin-right: 6px;">💡</span>${innerHtml}</p></aside>`;+ default:+ return paragraphHtml;+ }+}++function renderHeadingParagraphHtml(paragraph: IParagraph, innerHtml: string, style: string[]): string | null {+ const headingLevel = getHeadingLevel(paragraph.paragraphStyle?.namedStyleType);+ if (!headingLevel) {+ return null;+ }++ return `<h${headingLevel} class="UniverHeading" ${style.length ? `style="${style.join('; ')};"` : ''}>${innerHtml}</h${headingLevel}>`;+}++function renderListParagraphItemHtml(doc: IDocumentData, paragraph: IParagraph, innerHtml: string, style: string[]): { tag: 'ol' | 'ul'; level: number; listType: string; listStyle: string | null; html: string } | null {+ const bullet = paragraph.bullet;+ if (!bullet) {+ return null;+ }++ const ordered = isOrderedListType(String(bullet.listType));+ const tag = ordered ? 'ol' : 'ul';+ const level = bullet.nestingLevel ?? 0;+ const listStyle = getListStyleType(doc, String(bullet.listType), level);++ return {+ tag,+ level,+ listType: String(bullet.listType),+ listStyle,+ html: `<p class="UniverNormal" ${style.length ? `style="${style.join('; ')};"` : ''}>${innerHtml}</p>`,+ };+}++function appendListParagraphHtml(result: IHtmlResult, listItem: NonNullable<ReturnType<typeof renderListParagraphItemHtml>>): void {+ result.listStack ??= [];+ const stack = result.listStack;++ while (stack.length > listItem.level + 1) {+ result.html += `</li></${stack.pop()!.tag}>`;+ }++ const current = stack[stack.length - 1];+ if (current && current.level === listItem.level) {+ if (current.tag === listItem.tag && current.listType === listItem.listType) {+ result.html += '</li><li>';+ } else {+ result.html += `</li></${stack.pop()!.tag}>`;+ openList(result, listItem);+ }+ } else {+ while (stack.length < listItem.level) {+ openList(result, {+ ...listItem,+ level: stack.length,+ });+ }+ openList(result, listItem);+ }++ result.html += listItem.html;+}++function openList(result: IHtmlResult, listItem: NonNullable<ReturnType<typeof renderListParagraphItemHtml>>): void {+ const listStyleHtml = listItem.listStyle ? ` list-style-type: ${listItem.listStyle};` : '';+ const marginLeft = listItem.level > 0 ? ` margin-left: ${listItem.level * 24}px;` : '';+ result.html += `<${listItem.tag} data-doc-type="${listItem.tag === 'ol' ? 'ordered-list' : 'bullet-list'}" style="margin-top: 0; margin-bottom: 0;${marginLeft}${listStyleHtml}"><li>`;+ result.listStack!.push({ tag: listItem.tag, level: listItem.level, listType: listItem.listType });+}++function closeListStack(result: IHtmlResult): void {+ while (result.listStack?.length) {+ result.html += `</li></${result.listStack.pop()!.tag}>`;+ }+}++function getHeadingLevel(namedStyleType?: NamedStyleType): number | null {+ switch (namedStyleType) {+ 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;+ default: return null;+ }+}++function isOrderedListType(listType: string): boolean {+ return listType.includes('ORDER') || listType === PresetListType.ORDER_LIST;+}++function getListStyleType(doc: IDocumentData, listType: string, level: number): string | null {+ const glyphType = doc.lists?.[listType]?.nestingLevel?.[level]?.glyphType;+ switch (glyphType) {+ case 3: return 'upper-alpha';+ case 4: return 'lower-alpha';+ case 5: return 'upper-roman';+ case 6: return 'lower-roman';+ default: return isOrderedListType(listType) ? 'decimal' : null;+ }+}++function escapeHtml(value: string): string {+ return value+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+}+export class UDMToHtmlService {convert(docList: IDocumentData[]): string {if (docList.length === 0) {diff --git a/packages/docs-ui/src/services/doc-content-insert.service.ts b/packages/docs-ui/src/services/doc-content-insert.service.tsnew file mode 100644index 0000000000..b68dcdfa1d--- /dev/null+++ b/packages/docs-ui/src/services/doc-content-insert.service.ts@@ -0,0 +1,50 @@+/**+ * 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 { Disposable } from '@univerjs/core';++export interface IDocContentInsertRange {+ unitId: string;+ startOffset: number;+ endOffset: number;+ segmentId?: string;+}++export class DocContentInsertService extends Disposable {+ private _range: IDocContentInsertRange | null = null;++ setInsertRange(range: IDocContentInsertRange): void {+ this._range = range;+ }++ consumeInsertRange(unitId?: string): IDocContentInsertRange | null {+ if (!this._range) {+ return null;+ }++ if (unitId && this._range.unitId !== unitId) {+ return null;+ }++ const range = this._range;+ this._range = null;+ return range;+ }++ clearInsertRange(): void {+ this._range = null;+ }+}diff --git a/packages/docs-ui/src/services/doc-event-manager.service.ts b/packages/docs-ui/src/services/doc-event-manager.service.tsindex 922acec79f..aeacb8ba69 100644--- a/packages/docs-ui/src/services/doc-event-manager.service.ts+++ b/packages/docs-ui/src/services/doc-event-manager.service.ts@@ -19,6 +19,7 @@ import type {Documents,DocumentSkeleton,IBoundRectNoAngle,+ IDocsTableRenderViewport,IDocumentSkeletonGlyph,IDocumentSkeletonPage,IDocumentSkeletonSection,@@ -27,7 +28,7 @@ import type {} from '@univerjs/engine-render';import { Disposable, fromEventSubject, Inject } from '@univerjs/core';import { DocSkeletonManagerService } from '@univerjs/docs';-import { CURSOR_TYPE, TRANSFORM_CHANGE_OBSERVABLE_TYPE } from '@univerjs/engine-render';+import { CURSOR_TYPE, getDocsTableRenderViewport, getTableIdAndSliceIndex, TRANSFORM_CHANGE_OBSERVABLE_TYPE } from '@univerjs/engine-render';import { BehaviorSubject, distinctUntilChanged, filter, map, Subject, switchMap, take, throttleTime } from 'rxjs';import { DOC_VERTICAL_PADDING } from '../types/const/padding';import { transformOffset2Bound } from './doc-popup-manager.service';@@ -145,6 +146,9 @@ export const calcDocGlyphPosition = (glyph: IDocumentSkeletonGlyph, documents: Dconst { borderBoxPointGroup } = convertor.getRangePointData(startPosition, startPosition);const bounds = getLineBounding(borderBoxPointGroup);const rect = bounds[0];+ if (!rect) {+ return;+ }return {top: rect.top + documentOffsetConfig.docsTop,@@ -206,6 +210,9 @@ export interface ITableCellBound {tableId: string;}+const TABLE_BLOCK_MENU_HOVER_GUTTER_LEFT = 72;+const TABLE_BLOCK_MENU_HOVER_GUTTER_TOP = 42;+function isPointInRect(x: number, y: number, rect: IBoundRectNoAngle) {const { left, right, top, bottom } = rect;if (x >= left && x <= right && y >= top && y <= bottom) {@@ -214,6 +221,25 @@ function isPointInRect(x: number, y: number, rect: IBoundRectNoAngle) {return false;}+export function getTableBlockMenuHoverRect(tableRect: IBoundRectNoAngle): IBoundRectNoAngle {+ return {+ bottom: tableRect.bottom,+ left: tableRect.left - TABLE_BLOCK_MENU_HOVER_GUTTER_LEFT,+ right: tableRect.right,+ top: tableRect.top - TABLE_BLOCK_MENU_HOVER_GUTTER_TOP,+ };+}++export function getTableHorizontalViewportGeometry(tableLeft: number, tableWidth: number, viewport: Nullable<IDocsTableRenderViewport>) {+ const hasHorizontalViewport = viewport != null && viewport.contentWidth > viewport.viewportWidth;++ return {+ scrollLeft: hasHorizontalViewport ? viewport.scrollLeft : 0,+ visibleLeft: tableLeft,+ visibleRight: tableLeft + (hasHorizontalViewport ? viewport.viewportWidth : tableWidth),+ };+}+export class DocEventManagerService extends Disposable implements IRenderModule {private readonly _hoverCustomRanges$ = new BehaviorSubject<ICustomRangeActive[]>([]);readonly hoverCustomRanges$ = this._hoverCustomRanges$.pipe(distinctUntilChanged((pre, aft) => pre.length === aft.length && pre.every((item, i) => aft[i].range.rangeId === item.range.rangeId && aft[i].segmentId === item.segmentId && aft[i].segmentPageIndex === item.segmentPageIndex && aft[i].range.startIndex === item.range.startIndex)));@@ -227,6 +253,9 @@ export class DocEventManagerService extends Disposable implements IRenderModuleprivate readonly _clickBullet$ = new Subject<IBulletActive>();readonly clickBullets$ = this._clickBullet$.asObservable();+ private readonly _contextMenuBullet$ = new Subject<IBulletActive & { x: number; y: number }>();+ readonly contextMenuBullets$ = this._contextMenuBullet$.asObservable();+private readonly _hoverParagraph$ = new BehaviorSubject<Nullable<IMutiPageParagraphBound>>(null);readonly hoverParagraph$ = this._hoverParagraph$.pipe(distinctUntilChanged((pre, aft) => pre?.startIndex === aft?.startIndex && pre?.segmentId === aft?.segmentId && pre?.pageIndex === aft?.pageIndex));readonly hoverParagraphRealTime$ = this._hoverParagraph$.asObservable();@@ -273,6 +302,7 @@ export class DocEventManagerService extends Disposable implements IRenderModuleprivate _paragraphLeftBounds: IMutiPageParagraphBound[] = [];private _tableParagraphBounds: Map<string, ITableParagraphBound[]> = new Map();private _segmentParagraphBounds: Map<string, Map<number, IMutiPageParagraphBound[]>> = new Map();+ private _tableViewportSignature = '';private _tableCellBounds: Map<string, ITableCellBound[]> = new Map();private _tableBounds: Map<string, ITableBound> = new Map();@@ -330,6 +360,16 @@ export class DocEventManagerService extends Disposable implements IRenderModulethis._paragraphDirty = true;}));++ this.disposeWithMe(+ fromEventSubject(this._context.scene.onTransformChange$).pipe(+ filter((evt) => evt.type === TRANSFORM_CHANGE_OBSERVABLE_TYPE.scale)+ ).subscribe(() => {+ this._customRangeDirty = true;+ this._bulletDirty = true;+ this._paragraphDirty = true;+ })+ );}private _initEvents() {@@ -370,10 +410,21 @@ export class DocEventManagerService extends Disposable implements IRenderModuleswitchMap((down) => onPointerUp$.pipe(take(1), map((up) => ({ down, up })))),filter(({ down, up }) => down.target === up.target && up.timeStamp - down.timeStamp < 300)).subscribe(({ down }) => {+ const point = transformOffset2Bound(down.offsetX, down.offsetY, this._context.scene);+if (down.button === 2) {+ const bullet = this._calcActiveBullet(point);+ if (bullet) {+ this._contextMenuBullet$.next({+ ...bullet,+ x: down.offsetX,+ y: down.offsetY,+ });+ }+return;}- const point = transformOffset2Bound(down.offsetX, down.offsetY, this._context.scene);+const ranges = this._calcActiveRanges(point);if (ranges.length) {this._clickCustomRanges$.next(ranges.pop()!);@@ -386,6 +437,16 @@ export class DocEventManagerService extends Disposable implements IRenderModule}));}+ isPointerOnBullet(offsetX: number, offsetY: number): boolean {+ return Boolean(this._calcActiveBullet(transformOffset2Bound(offsetX, offsetY, this._context.scene)));+ }++ getBulletBounds(): IBulletBound[] {+ this._buildBulletBounds();++ return [...this._bulletBounds];+ }+private _buildCustomRangeBoundsBySegment(segmentId?: string, segmentPage = -1) {const customRanges = this._context.unit.getSelfOrHeaderFooterModel(segmentId)?.getBody()?.customRanges ?? [];const layouts: ICustomRangeBound[] = [];@@ -453,7 +514,7 @@ export class DocEventManagerService extends Disposable implements IRenderModuleprivate _buildBulletBoundsBySegment(segmentId?: string, segmentPage = -1): IBulletBound[] {const body = this._context.unit.getSelfOrHeaderFooterModel(segmentId)?.getBody();- const paragraphs = (body?.paragraphs ?? []).filter((p) => p.bullet && p.bullet.listType.indexOf('CHECK_LIST') === 0);+ const paragraphs = (body?.paragraphs ?? []).filter((p) => p.bullet);const bounds: IBulletBound[] = [];const skeletonData = this._skeleton.getSkeletonData();if (!skeletonData) {@@ -586,7 +647,13 @@ export class DocEventManagerService extends Disposable implements IRenderModuleArray.from(page.skeTables.values()).forEach((table) => {const tableLeft = table.left + left;const tableTop = table.top + top;- const tableRight = tableLeft + table.width;+ const sourceTableId = getTableIdAndSliceIndex(table.tableId).tableId;+ const tableViewport = getTableHorizontalViewportGeometry(+ tableLeft,+ table.width,+ getDocsTableRenderViewport(this._context.unitId, sourceTableId)+ );+ const tableRight = tableViewport.visibleRight;const tableBottom = tableTop + table.height;const tableId = table.tableId;this._tableBounds.set(tableId, {@@ -603,8 +670,18 @@ export class DocEventManagerService extends Disposable implements IRenderModuletable.rows.forEach((row, rowIndex) => {row.cells.forEach((cell, colIndex) => {const top = (((page.pageHeight === Infinity ? 0 : page.pageHeight) + documentOffsetConfig.pageMarginTop) * i) + table.top + documentOffsetConfig.docsTop + page.marginTop + row.top + cell.marginTop;- const left = table.left + documentOffsetConfig.docsLeft + page.marginLeft + cell.left + cell.marginLeft;- const bounds = calcDocParagraphPositions(cell.sections, top, left, cell.pageWidth - cell.marginLeft - cell.marginRight);+ const cellLeft = tableLeft + cell.left - tableViewport.scrollLeft + cell.marginLeft;+ const cellContentWidth = cell.pageWidth - cell.marginLeft - cell.marginRight;+ const cellRight = cellLeft + cellContentWidth;+ const visibleCellLeft = Math.max(cellLeft, tableViewport.visibleLeft);+ const visibleCellRight = Math.min(cellRight, tableViewport.visibleRight);+ if (visibleCellRight <= visibleCellLeft) {+ return;+ }++ const bounds = calcDocParagraphPositions(cell.sections, top, cellLeft, cellContentWidth)+ .map((bound) => clipParagraphBoundHorizontally(bound, tableViewport.visibleLeft, tableViewport.visibleRight))+ .filter((bound): bound is ICustomRangeBoundBase => bound != null);let arr = this._tableParagraphBounds.get(tableId);if (!arr) {arr = [];@@ -635,8 +712,8 @@ export class DocEventManagerService extends Disposable implements IRenderModulecellBounds.push({rect: {top,- left,- right: left + cell.pageWidth - cell.marginLeft - cell.marginRight,+ left: visibleCellLeft,+ right: visibleCellRight,bottom: top + cell.pageHeight - cell.marginBottom - cell.marginTop,},pageIndex: i,@@ -667,10 +744,12 @@ export class DocEventManagerService extends Disposable implements IRenderModule}private _buildParagraphBounds() {- if (!this._paragraphDirty) {+ const tableViewportSignature = this._getTableViewportSignature();+ if (!this._paragraphDirty && this._tableViewportSignature === tableViewportSignature) {return;}this._paragraphDirty = false;+ this._tableViewportSignature = tableViewportSignature;this._tableParagraphBounds = new Map();this._tableCellBounds = new Map();this._tableBounds = new Map();@@ -704,7 +783,7 @@ export class DocEventManagerService extends Disposable implements IRenderModuleconst { x, y } = evt;- const table = Array.from(this._tableBounds.values()).find((bound) => isPointInRect(x, y, bound.rect));+ const table = Array.from(this._tableBounds.values()).find((bound) => isPointInRect(x, y, getTableBlockMenuHoverRect(bound.rect)));this._hoverTable$.next(table);if (table) {@@ -747,14 +826,104 @@ export class DocEventManagerService extends Disposable implements IRenderModulereturn this._paragraphBounds;}+ get tableBounds() {+ this._buildParagraphBounds();+ return this._tableBounds;+ }+findParagraphBoundByIndex(index: number) {this._buildParagraphBounds();+ const tableParagraph = Array.from(this._tableParagraphBounds.values()).flat().find((bound) => bound.startIndex === index);+ if (tableParagraph) {+ return tableParagraph;+ }+const paragraph = this._paragraphBounds.get(index);if (paragraph) {return paragraph;}+ }- const tableParagraph = Array.from(this._tableParagraphBounds.values()).flat().find((bound) => bound.startIndex === index);- return tableParagraph;+ findParagraphBoundsInRange(startIndex: number, endIndex: number): IMutiPageParagraphBound[] {+ this._buildParagraphBounds();++ const bodyBounds = [...this._paragraphBounds.values()];+ const tableBounds = Array.from(this._tableParagraphBounds.values()).flat().map((bound) => ({+ rect: bound.rect,+ paragraphStart: bound.paragraphStart,+ paragraphEnd: bound.paragraphEnd,+ startIndex: bound.startIndex,+ rects: [bound.rect],+ pageIndex: bound.pageIndex,+ segmentId: bound.segmentId,+ firstLine: bound.firstLine,+ }));++ return getPreferredParagraphBoundsInRange(bodyBounds, tableBounds, startIndex, endIndex);+ }++ private _getTableViewportSignature(): string {+ const pages = this._skeleton.getSkeletonData()?.pages ?? [];+ const signatures: string[] = [];++ pages.forEach((page) => {+ page.skeTables?.forEach((table) => {+ const tableId = getTableIdAndSliceIndex(table.tableId).tableId;+ const viewport = getDocsTableRenderViewport(this._context.unitId, tableId);+ if (!viewport) {+ signatures.push(`${tableId}:none`);+ return;+ }++ signatures.push(`${tableId}:${viewport.contentWidth}:${viewport.viewportWidth}:${viewport.scrollLeft}`);+ });+ });++ return signatures.join('|');}}++export function getPreferredParagraphBoundsInRange(+ bodyBounds: IMutiPageParagraphBound[],+ tableBounds: IMutiPageParagraphBound[],+ startIndex: number,+ endIndex: number+): IMutiPageParagraphBound[] {+ const matchedTableBounds = tableBounds.filter((bound) => isRangeOverlappingParagraph(bound, startIndex, endIndex));+ if (matchedTableBounds.length) {+ return matchedTableBounds;+ }++ return bodyBounds.filter((bound) => isRangeOverlappingParagraph(bound, startIndex, endIndex));+}++function isRangeOverlappingParagraph(bound: Pick<IMutiPageParagraphBound, 'paragraphEnd' | 'paragraphStart'>, startIndex: number, endIndex: number): boolean {+ return Math.max(bound.paragraphStart, startIndex) <= Math.min(bound.paragraphEnd, endIndex);+}++function clipParagraphBoundHorizontally(bound: ICustomRangeBoundBase, visibleLeft: number, visibleRight: number): ICustomRangeBoundBase | null {+ const rect = clipRectHorizontally(bound.rect, visibleLeft, visibleRight);+ if (!rect) {+ return null;+ }++ return {+ ...bound,+ rect,+ fisrtLine: clipRectHorizontally(bound.fisrtLine, visibleLeft, visibleRight) ?? rect,+ };+}++function clipRectHorizontally(rect: IBoundRectNoAngle, visibleLeft: number, visibleRight: number): IBoundRectNoAngle | null {+ const left = Math.max(rect.left, visibleLeft);+ const right = Math.min(rect.right, visibleRight);+ if (right <= left) {+ return null;+ }++ return {+ ...rect,+ left,+ right,+ };+}diff --git a/packages/docs-ui/src/services/doc-paragraph-menu.service.ts b/packages/docs-ui/src/services/doc-paragraph-menu.service.tsindex 145b9e794a..885498bf7c 100644--- a/packages/docs-ui/src/services/doc-paragraph-menu.service.ts+++ b/packages/docs-ui/src/services/doc-paragraph-menu.service.ts@@ -14,29 +14,112 @@* limitations under the License.*/-import type { DocumentDataModel, INeedCheckDisposable, IParagraphRange, Nullable } from '@univerjs/core';-import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';-import type { IMutiPageParagraphBound } from './doc-event-manager.service';-import { Disposable, Inject, isInternalEditorID } from '@univerjs/core';+import type { DocumentDataModel, ICustomBlock, ICustomTable, IDocumentBlockRange, INeedCheckDisposable, Nullable } from '@univerjs/core';+import type { IBoundRectNoAngle, IRenderContext, IRenderModule } from '@univerjs/engine-render';+import type { IMutiPageParagraphBound, ITableBound } from './doc-event-manager.service';+import { BlockType, DataStreamTreeTokenType, Disposable, Inject, isInternalEditorID, PresetListType } from '@univerjs/core';import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';import { DocumentEditArea } from '@univerjs/engine-render';-import { combineLatest, first, throttleTime } from 'rxjs';+import { BehaviorSubject, combineLatest, first, throttleTime } from 'rxjs';import { VIEWPORT_KEY } from '../basics/docs-view-key';import { DocEventManagerService } from './doc-event-manager.service';-import { DocCanvasPopManagerService } from './doc-popup-manager.service';+import { DocCanvasPopManagerService, transformBound2OffsetBound, transformOffset2Bound } from './doc-popup-manager.service';import { DocFloatMenuService } from './float-menu.service';+export type DocBlockMenuTargetKind = 'paragraph' | 'blockRange' | 'table' | 'customBlock';++export interface IDocBlockMenuTarget {+ kind: DocBlockMenuTargetKind;+ key: string;+ paragraph?: IMutiPageParagraphBound;+ blockRange?: IDocumentBlockRange;+ table?: ICustomTable;+ customBlock?: ICustomBlock;+ icon?: string;+ cellRange?: {+ startOffset: number;+ endOffset: number;+ };+ menuRange: {+ startOffset: number;+ endOffset: number;+ collapsed: boolean;+ };+ moveRange: {+ startOffset: number;+ endOffset: number;+ };+ emptyMode: boolean;+ draggable: boolean;+}++export interface IDocBlockDropTarget {+ targetOffset: number;+ rect: {+ left: number;+ right: number;+ top: number;+ bottom: number;+ };+}++const BLOCK_RANGE_ICON_MAP: Record<string, string> = {+ code: 'DocsCodeBlockIcon',+ quote: 'DocsQuoteBlockIcon',+ callout: 'DocsCalloutBlockIcon',+};++const LIST_ICON_MAP: Partial<Record<PresetListType, string>> = {+ [PresetListType.ORDER_LIST]: 'OrderIcon',+ [PresetListType.ORDER_LIST_1]: 'OrderIcon',+ [PresetListType.ORDER_LIST_2]: 'OrderIcon',+ [PresetListType.ORDER_LIST_3]: 'OrderIcon',+ [PresetListType.ORDER_LIST_4]: 'OrderIcon',+ [PresetListType.ORDER_LIST_5]: 'OrderIcon',+ [PresetListType.ORDER_LIST_QUICK_2]: 'OrderIcon',+ [PresetListType.ORDER_LIST_QUICK_3]: 'OrderIcon',+ [PresetListType.ORDER_LIST_QUICK_4]: 'OrderIcon',+ [PresetListType.ORDER_LIST_QUICK_5]: 'OrderIcon',+ [PresetListType.ORDER_LIST_QUICK_6]: 'OrderIcon',+ [PresetListType.BULLET_LIST]: 'UnorderIcon',+ [PresetListType.BULLET_LIST_1]: 'UnorderIcon',+ [PresetListType.BULLET_LIST_2]: 'UnorderIcon',+ [PresetListType.BULLET_LIST_3]: 'UnorderIcon',+ [PresetListType.BULLET_LIST_4]: 'UnorderIcon',+ [PresetListType.BULLET_LIST_5]: 'UnorderIcon',+ [PresetListType.CHECK_LIST]: 'TodoListDoubleIcon',+ [PresetListType.CHECK_LIST_CHECKED]: 'TodoListDoubleIcon',+};+export class DocParagraphMenuService extends Disposable implements IRenderModule {private _paragrahMenu: {- paragraph: IParagraphRange;+ paragraph: IMutiPageParagraphBound;+ target: IDocBlockMenuTarget;+ blockRange?: IDocumentBlockRange;disposable: INeedCheckDisposable;active: boolean;} | null = null;+ private readonly _activeTarget$ = new BehaviorSubject<IDocBlockMenuTarget | null>(null);+ readonly activeTarget$ = this._activeTarget$.asObservable();+ private _isBlockMenuDragging = false;+get activeParagraph() {return this._paragrahMenu?.paragraph;}+ get activeTarget() {+ return this._paragrahMenu?.target ?? null;+ }++ setBlockMenuDragging(isDragging: boolean) {+ this._isBlockMenuDragging = isDragging;+ }++ get isBlockMenuDragging() {+ return this._isBlockMenuDragging;+ }+constructor(private _context: IRenderContext<DocumentDataModel>,@Inject(DocSelectionManagerService) private _docSelectionManagerService: DocSelectionManagerService,@@ -88,7 +171,11 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule}private _init() {- const handleHoverParagraph = (paragraph: Nullable<IMutiPageParagraphBound>) => {+ const handleHoverTarget = (paragraph: Nullable<IMutiPageParagraphBound>, tableBound: Nullable<ITableBound>) => {+ if (this._isBlockMenuDragging) {+ return;+ }+const viewModel = this._docSkeletonManagerService.getViewModel();if (viewModel.getEditArea() === DocumentEditArea.BODY &&@@ -103,17 +190,26 @@ export class DocParagraphMenuService extends Disposable implements IRenderModulethis.showParagraphMenu(paragraph);return;}++ if (tableBound) {+ this.showTableMenu(tableBound);+ return;+ }}this.hideParagraphMenu(true);};this.disposeWithMe(- combineLatest([this._docEventManagerService.hoverParagraphRealTime$, this._docEventManagerService.hoverParagraphLeft$])+ combineLatest([+ this._docEventManagerService.hoverParagraphRealTime$,+ this._docEventManagerService.hoverParagraphLeft$,+ this._docEventManagerService.hoverTableRealTime$ ?? new BehaviorSubject<Nullable<ITableBound>>(null),+ ]).pipe(throttleTime(16))- .subscribe(([p, left]) => {+ .subscribe(([p, left, table]) => {const paragraph = p ?? left;- handleHoverParagraph(paragraph);+ handleHoverTarget(paragraph, table);}));@@ -124,32 +220,44 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule}lastScrollY = e.scrollY;+ if (this._paragrahMenu?.blockRange) {+ return;+ }+ if (this._isBlockMenuDragging) {+ return;+ }this.hideParagraphMenu(true);}));this.disposeWithMe(this._docEventManagerService.clickCustomRanges$.subscribe(() => {+ if (this._isBlockMenuDragging) {+ return;+ }this.hideParagraphMenu(true);}));}showParagraphMenu(paragraph: IMutiPageParagraphBound) {- if (this._paragrahMenu?.paragraph.startIndex === paragraph.startIndex) {+ const target = this._buildParagraphMenuTarget(paragraph);+ if (!target) {+ this.hideParagraphMenu(true);return;}- this.hideParagraphMenu(true);- const dataStream = this._context.unit.getBody()?.dataStream ?? '';- const paragraphDataStream = paragraph ? dataStream.slice(paragraph.paragraphStart, paragraph.paragraphEnd) : '';- const isOnlyImage = paragraphDataStream === '\b';- const isEmptyParagraph = paragraphDataStream === '';- const shouldHidden = isOnlyImage || isEmptyParagraph;-- if (shouldHidden) {+ if (this._paragrahMenu?.target.key === target.key) {return;}+ this.hideParagraphMenu(true);+ const targetParagraph = target.paragraph ?? paragraph;+ const blockRange = target.blockRange;++ const getFirstLine = () => blockRange+ ? getBlockRangeAnchorRect(this._docEventManagerService, blockRange, paragraph)+ : this._docEventManagerService.findParagraphBoundByIndex(paragraph.startIndex)?.firstLine ?? paragraph.firstLine;+const disposable = this._docPopupManagerService.attachPopupToRect(- paragraph.firstLine,+ getFirstLine,{componentKey: 'doc.paragraph.menu',direction: 'left-center',@@ -165,17 +273,450 @@ export class DocParagraphMenuService extends Disposable implements IRenderModulethis._context.unitId);+ this._paragrahMenu = {+ paragraph: targetParagraph,+ target,+ blockRange,+ disposable,+ active: false,+ };+ this._activeTarget$.next(target);+ }++ showTableMenu(tableBound: ITableBound) {+ const body = this._context.unit.getBody();+ const table = body?.tables?.find((item) => item.tableId === tableBound.tableId);+ if (!table) {+ return;+ }++ const target: IDocBlockMenuTarget = {+ kind: 'table',+ key: `table:${table.tableId}`,+ table,+ icon: 'GridIcon',+ menuRange: {+ startOffset: table.startIndex,+ endOffset: table.endIndex,+ collapsed: false,+ },+ moveRange: {+ startOffset: table.startIndex,+ endOffset: table.endIndex,+ },+ emptyMode: false,+ draggable: true,+ };++ if (this._paragrahMenu?.target.key === target.key) {+ return;+ }++ const anchorRect = getTableAnchorRect(tableBound);+ const paragraph: IMutiPageParagraphBound = {+ rect: tableBound.rect,+ rects: [tableBound.rect],+ paragraphStart: table.startIndex,+ paragraphEnd: table.endIndex,+ startIndex: table.startIndex,+ pageIndex: tableBound.pageIndex,+ firstLine: anchorRect,+ };++ this.hideParagraphMenu(true);+ const getFirstLine = () => getTableAnchorRect(this._docEventManagerService.tableBounds.get(table.tableId) ?? tableBound);+ const disposable = this._docPopupManagerService.attachPopupToRect(+ getFirstLine,+ {+ componentKey: 'doc.paragraph.menu',+ direction: 'top-right',+ onClickOutside: () => {+ this.hideParagraphMenu(true);+ },+ zIndex: 101,+ },+ this._context.unitId+ );+this._paragrahMenu = {paragraph,+ target,disposable,active: false,};+ this._activeTarget$.next(target);+ }++ getDropTargetFromClientPoint(clientX: number, clientY: number, sourceRange: { startOffset: number; endOffset: number }): IDocBlockDropTarget | null {+ const canvasRect = this._context.engine.getCanvasElement().getBoundingClientRect();+ const point = transformOffset2Bound(clientX - canvasRect.left, clientY - canvasRect.top, this._context.scene);+ const body = this._context.unit.getBody();+ const sourceCellRange = body?.dataStream ? getContainingTableCellRange(body.dataStream, sourceRange.startOffset) : null;+ const blocks = (sourceCellRange ? this._getCellBlockTargets(sourceCellRange) : this._getBodyBlockTargets())+ .filter((block) => block.moveRange.startOffset !== sourceRange.startOffset || block.moveRange.endOffset !== sourceRange.endOffset)+ .filter((block) => block.moveRange.endOffset <= sourceRange.startOffset || block.moveRange.startOffset >= sourceRange.endOffset)+ .sort((left, right) => left.rect.top - right.rect.top || left.rect.left - right.rect.left);++ if (!blocks.length) {+ return null;+ }++ let nearest = blocks[0];+ let nearestDistance = Number.POSITIVE_INFINITY;+ for (const block of blocks) {+ const middle = (block.rect.top + block.rect.bottom) / 2;+ const distance = Math.abs(point.y - middle);+ if (distance < nearestDistance) {+ nearestDistance = distance;+ nearest = block;+ }+ }++ const before = point.y < (nearest.rect.top + nearest.rect.bottom) / 2;+ const targetOffset = before ? nearest.moveRange.startOffset : nearest.moveRange.endOffset;+ const docRect: IBoundRectNoAngle = {+ left: nearest.rect.left,+ right: nearest.rect.right,+ top: before ? nearest.rect.top : nearest.rect.bottom,+ bottom: before ? nearest.rect.top : nearest.rect.bottom,+ };+ const screenRect = transformBound2OffsetBound(docRect, this._context.scene);++ return {+ targetOffset,+ rect: {+ left: canvasRect.left + screenRect.left,+ right: canvasRect.left + screenRect.right,+ top: canvasRect.top + screenRect.top,+ bottom: canvasRect.top + screenRect.bottom,+ },+ };}hideParagraphMenu(force = false) {+ if (this._isBlockMenuDragging) {+ return;+ }+if (this._paragrahMenu && ((this._paragrahMenu.disposable.canDispose() || force))) {this._paragrahMenu.disposable.dispose();this._paragrahMenu = null;+ this._activeTarget$.next(null);}}++ private _buildParagraphMenuTarget(paragraph: IMutiPageParagraphBound): IDocBlockMenuTarget | null {+ const body = this._context.unit.getBody();+ const dataStream = body?.dataStream ?? '';+ const cellRange = getContainingTableCellRange(dataStream, paragraph.paragraphStart);+ const inTable = cellRange != null || isParagraphInTable(this._context.unit, paragraph.paragraphStart);+ const blockRange = getParagraphBlockRange(this._context.unit, paragraph);+ if (blockRange) {+ const targetParagraph = {+ ...paragraph,+ paragraphStart: blockRange.startIndex,+ paragraphEnd: blockRange.endIndex + 1,+ startIndex: blockRange.startIndex,+ blockRange,+ } as IMutiPageParagraphBound;+ return {+ kind: 'blockRange',+ key: `blockRange:${blockRange.blockId}`,+ paragraph: targetParagraph,+ blockRange,+ icon: BLOCK_RANGE_ICON_MAP[blockRange.blockType],+ cellRange: cellRange ?? undefined,+ menuRange: {+ startOffset: blockRange.startIndex,+ endOffset: blockRange.endIndex + 1,+ collapsed: false,+ },+ moveRange: {+ startOffset: blockRange.startIndex,+ endOffset: blockRange.endIndex + 1,+ },+ emptyMode: false,+ draggable: cellRange != null || !inTable,+ };+ }++ const paragraphDataStream = dataStream.slice(paragraph.paragraphStart, paragraph.paragraphEnd);+ const paragraphModel = body?.paragraphs?.find((item) => item.startIndex === paragraph.startIndex);+ const listIcon = getListIcon(paragraphModel?.bullet?.listType);+ const customBlock = body?.customBlocks?.find((item) => item.startIndex >= paragraph.paragraphStart && item.startIndex <= paragraph.paragraphEnd);+ const isCustomBlockOnly = customBlock?.blockType === BlockType.CUSTOM && paragraphDataStream.replace(/[\b\r\n]/g, '') === '';+ if (customBlock && customBlock.blockType === BlockType.CUSTOM && isCustomBlockOnly) {+ return {+ kind: 'customBlock',+ key: `customBlock:${customBlock.blockId}`,+ paragraph,+ customBlock,+ icon: 'TextTypeIcon',+ cellRange: cellRange ?? undefined,+ menuRange: {+ startOffset: customBlock.startIndex,+ endOffset: customBlock.startIndex,+ collapsed: true,+ },+ moveRange: getParagraphMoveRange(this._context.unit, paragraph, cellRange),+ emptyMode: false,+ draggable: cellRange != null || !inTable,+ };+ }++ if (paragraphDataStream === '\b') {+ return null;+ }++ return {+ kind: 'paragraph',+ key: `paragraph:${paragraph.startIndex}`,+ paragraph,+ icon: listIcon,+ cellRange: cellRange ?? undefined,+ menuRange: {+ startOffset: paragraph.paragraphStart,+ endOffset: paragraph.paragraphStart,+ collapsed: true,+ },+ moveRange: getParagraphMoveRange(this._context.unit, paragraph, cellRange),+ emptyMode: paragraphDataStream.replace(/[\r\n]/g, '') === '',+ draggable: cellRange != null || !inTable,+ };+ }++ private _getBodyBlockTargets(): Array<IDocBlockMenuTarget & { rect: IBoundRectNoAngle }> {+ const body = this._context.unit.getBody();+ if (!body) {+ return [];+ }++ const tableRanges = body.tables ?? [];+ const blockRanges = body.blockRanges ?? [];+ const paragraphBounds = [...this._docEventManagerService.paragraphBounds.values()];+ const targets: Array<IDocBlockMenuTarget & { rect: IBoundRectNoAngle }> = [];++ for (const table of tableRanges) {+ const tableBound = this._docEventManagerService.tableBounds.get(table.tableId);+ if (!tableBound) {+ continue;+ }++ targets.push({+ kind: 'table',+ key: `table:${table.tableId}`,+ table,+ icon: 'GridIcon',+ menuRange: { startOffset: table.startIndex, endOffset: table.endIndex, collapsed: false },+ moveRange: { startOffset: table.startIndex, endOffset: table.endIndex },+ emptyMode: false,+ draggable: true,+ rect: tableBound.rect,+ });+ }++ for (const blockRange of blockRanges) {+ const bounds = paragraphBounds.filter((bound) => Math.max(bound.paragraphStart, blockRange.startIndex) <= Math.min(bound.paragraphEnd, blockRange.endIndex));+ const rect = unionRects(bounds.map((bound) => bound.rect));+ if (!rect) {+ continue;+ }++ targets.push({+ kind: 'blockRange',+ key: `blockRange:${blockRange.blockId}`,+ blockRange,+ icon: BLOCK_RANGE_ICON_MAP[blockRange.blockType],+ menuRange: { startOffset: blockRange.startIndex, endOffset: blockRange.endIndex + 1, collapsed: false },+ moveRange: { startOffset: blockRange.startIndex, endOffset: blockRange.endIndex + 1 },+ emptyMode: false,+ draggable: true,+ rect,+ });+ }++ for (const paragraph of paragraphBounds) {+ if (tableRanges.some((table) => paragraph.paragraphStart > table.startIndex && paragraph.paragraphStart < table.endIndex)) {+ continue;+ }++ if (blockRanges.some((range) => Math.max(paragraph.paragraphStart, range.startIndex) <= Math.min(paragraph.paragraphEnd, range.endIndex))) {+ continue;+ }++ const target = this._buildParagraphMenuTarget(paragraph);+ if (!target) {+ continue;+ }++ targets.push({+ ...target,+ rect: paragraph.rect,+ });+ }++ return targets;+ }++ private _getCellBlockTargets(cellRange: { startOffset: number; endOffset: number }): Array<IDocBlockMenuTarget & { rect: IBoundRectNoAngle }> {+ const body = this._context.unit.getBody();+ if (!body) {+ return [];+ }++ const blockRanges = body.blockRanges ?? [];+ const paragraphBounds = [...this._docEventManagerService.paragraphBounds.values()]+ .filter((paragraph) => paragraph.paragraphStart > cellRange.startOffset && paragraph.paragraphStart < cellRange.endOffset);+ const targets: Array<IDocBlockMenuTarget & { rect: IBoundRectNoAngle }> = [];++ for (const blockRange of blockRanges) {+ if (blockRange.startIndex <= cellRange.startOffset || blockRange.endIndex >= cellRange.endOffset) {+ continue;+ }++ const bounds = paragraphBounds.filter((bound) => Math.max(bound.paragraphStart, blockRange.startIndex) <= Math.min(bound.paragraphEnd, blockRange.endIndex));+ const rect = unionRects(bounds.map((bound) => bound.rect));+ if (!rect) {+ continue;+ }++ targets.push({+ kind: 'blockRange',+ key: `blockRange:${blockRange.blockId}`,+ blockRange,+ icon: BLOCK_RANGE_ICON_MAP[blockRange.blockType],+ cellRange,+ menuRange: { startOffset: blockRange.startIndex, endOffset: blockRange.endIndex + 1, collapsed: false },+ moveRange: { startOffset: blockRange.startIndex, endOffset: blockRange.endIndex + 1 },+ emptyMode: false,+ draggable: true,+ rect,+ });+ }++ for (const paragraph of paragraphBounds) {+ if (blockRanges.some((range) => Math.max(paragraph.paragraphStart, range.startIndex) <= Math.min(paragraph.paragraphEnd, range.endIndex))) {+ continue;+ }++ const target = this._buildParagraphMenuTarget(paragraph);+ if (!target) {+ continue;+ }++ targets.push({+ ...target,+ rect: paragraph.rect,+ });+ }++ return targets;+ }+}++function isParagraphInTable(documentDataModel: DocumentDataModel, paragraphStart: number): boolean {+ const tables = documentDataModel.getBody()?.tables ?? [];++ return tables.some((table) => paragraphStart > table.startIndex && paragraphStart < table.endIndex);+}++function getParagraphMoveRange(documentDataModel: DocumentDataModel, paragraph: IMutiPageParagraphBound, cellRange?: { startOffset: number; endOffset: number } | null) {+ const paragraphs = [...(documentDataModel.getBody()?.paragraphs ?? [])].sort((left, right) => left.startIndex - right.startIndex);+ const index = paragraphs.findIndex((item) => item.startIndex === paragraph.startIndex);+ const previousParagraph = index > 0+ ? paragraphs.slice(0, index).reverse().find((item) => {+ if (!cellRange) {+ return true;+ }++ return item.startIndex > cellRange.startOffset && item.startIndex < cellRange.endOffset;+ })+ : null;++ return {+ startOffset: previousParagraph ? previousParagraph.startIndex + 1 : (cellRange ? cellRange.startOffset + 1 : 0),+ endOffset: paragraph.startIndex + 1,+ };+}++function getListIcon(listType?: PresetListType | string): string | undefined {+ if (!listType) {+ return undefined;+ }++ return LIST_ICON_MAP[listType as PresetListType];+}++function getContainingTableCellRange(dataStream: string, offset: number): { startOffset: number; endOffset: number } | null {+ const startOffset = dataStream.lastIndexOf(DataStreamTreeTokenType.TABLE_CELL_START, Math.max(0, offset));+ if (startOffset < 0) {+ return null;+ }++ const previousCellEnd = dataStream.lastIndexOf(DataStreamTreeTokenType.TABLE_CELL_END, Math.max(0, offset));+ if (previousCellEnd > startOffset) {+ return null;+ }++ const endOffset = dataStream.indexOf(DataStreamTreeTokenType.TABLE_CELL_END, startOffset + 1);+ if (endOffset < 0 || offset > endOffset) {+ return null;+ }++ return { startOffset, endOffset };+}++function getTableAnchorRect(tableBound: ITableBound) {+ const gap = 4;+ const left = tableBound.rect.left - gap;+ const top = tableBound.rect.top - gap;++ return {+ left,+ right: left,+ top,+ bottom: top,+ };+}++function unionRects(rects: IBoundRectNoAngle[]): IBoundRectNoAngle | null {+ if (!rects.length) {+ return null;+ }++ return rects.reduce((acc, rect) => ({+ left: Math.min(acc.left, rect.left),+ right: Math.max(acc.right, rect.right),+ top: Math.min(acc.top, rect.top),+ bottom: Math.max(acc.bottom, rect.bottom),+ }));+}++function getParagraphBlockRange(documentDataModel: DocumentDataModel, paragraph: IMutiPageParagraphBound): IDocumentBlockRange | undefined {+ const blockRanges = documentDataModel.getBody()?.blockRanges ?? [];++ return blockRanges.find((range) => (+ Math.max(paragraph.paragraphStart, range.startIndex) <= Math.min(paragraph.paragraphEnd, range.endIndex)+ ));+}++function getBlockRangeAnchorRect(+ docEventManagerService: DocEventManagerService,+ blockRange: IDocumentBlockRange,+ fallbackParagraph: IMutiPageParagraphBound+) {+ const bounds = docEventManagerService+ .findParagraphBoundsInRange(blockRange.startIndex, blockRange.endIndex)+ .sort((left, right) => left.firstLine.top - right.firstLine.top || left.firstLine.left - right.firstLine.left);+ const anchor = bounds[0]?.firstLine ?? fallbackParagraph.firstLine;+ const left = Math.min(...(bounds.length ? bounds : [fallbackParagraph]).map((bound) => bound.firstLine.left));+ const top = anchor.top;++ return {+ ...anchor,+ left,+ right: left,+ top,+ bottom: top,+ };}diff --git a/packages/docs-ui/src/services/doc-popup-manager.service.ts b/packages/docs-ui/src/services/doc-popup-manager.service.tsindex 348200165b..8718c5fdee 100644--- a/packages/docs-ui/src/services/doc-popup-manager.service.ts+++ b/packages/docs-ui/src/services/doc-popup-manager.service.ts@@ -86,7 +86,7 @@ export function transformOffset2Bound(offsetX: number, offsetY: number, scene: Sexport interface IDocCanvasPopup extends Omit<IPopup, 'anchorRect$' | 'children' | 'unitId' | 'subUnitId' | 'canvasElement'> {mask?: boolean;- extraProps?: Record<string, any>;+ extraProps?: Record<string, unknown>;multipleDirection?: IPopup['direction'];}@@ -175,6 +175,10 @@ export class DocCanvasPopManagerService extends Disposable {}));}+ disposable.add(currentRender.scene.onTransformChange$.subscribeEvent(() => {+ position$.next(calc());+ }));+return {position,position$,@@ -227,6 +231,13 @@ export class DocCanvasPopManagerService extends Disposable {}));}+ disposable.add(currentRender.scene.onTransformChange$.subscribeEvent(() => {+ const position = calcDocRangePositions(range, currentRender);+ if (position) {+ positions$.next(position);+ }+ }));+return {positions,positions$,@@ -234,7 +245,7 @@ export class DocCanvasPopManagerService extends Disposable {};}- attachPopupToRect(rect: IBoundRectNoAngle, popup: IDocCanvasPopup, unitId: string): INeedCheckDisposable {+ attachPopupToRect(rect: IBoundRectNoAngle | (() => IBoundRectNoAngle), popup: IDocCanvasPopup, unitId: string): INeedCheckDisposable {const currentRender = this._renderManagerService.getRenderById(unitId);if (!currentRender) {throw new Error(`Current render not found, unitId: ${unitId}`);diff --git a/packages/docs-ui/src/services/docs-render.service.ts b/packages/docs-ui/src/services/docs-render.service.tsindex b772f32134..90159d37f0 100644--- a/packages/docs-ui/src/services/docs-render.service.ts+++ b/packages/docs-ui/src/services/docs-render.service.ts@@ -14,12 +14,20 @@* limitations under the License.*/-import type { DocumentDataModel, Workbook } from '@univerjs/core';-import { IUniverInstanceService, RxDisposable, UniverInstanceType } from '@univerjs/core';+import type { DocumentDataModel } from '@univerjs/core';+import { DocumentFlavor, IUniverInstanceService, RxDisposable, UniverInstanceType } from '@univerjs/core';import { IRenderManagerService } from '@univerjs/engine-render';import { takeUntil } from 'rxjs';const DOC_MAIN_CANVAS_ID = 'univer-doc-main-canvas';+const DOC_TRADITIONAL_WORKSPACE_BACKGROUND_COLOR = '#fafafa';+const DOC_MODERN_WORKSPACE_BACKGROUND_COLOR = '#fff';++export function getDocsCanvasBackgroundColor(documentFlavor?: DocumentFlavor) {+ return documentFlavor === DocumentFlavor.MODERN+ ? DOC_MODERN_WORKSPACE_BACKGROUND_COLOR+ : DOC_TRADITIONAL_WORKSPACE_BACKGROUND_COLOR;+}export class DocsRenderService extends RxDisposable {constructor(@@ -50,11 +58,13 @@ export class DocsRenderService extends RxDisposable {private _createRenderer(doc: DocumentDataModel) {const unitId = doc.getUnitId();- const workbookId = this._instanceSrv.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_DOC)?.getUnitId();this._renderManagerService.created$.subscribe((renderer) => {- if (renderer.unitId === workbookId) {- renderer.engine.getCanvas().setId(DOC_MAIN_CANVAS_ID);- renderer.engine.getCanvas().getContext().setId(DOC_MAIN_CANVAS_ID);+ if (renderer.unitId === unitId) {+ const documentFlavor = doc.getSnapshot().documentStyle.documentFlavor;+ const canvas = renderer.engine.getCanvas();+ canvas.setId(DOC_MAIN_CANVAS_ID);+ canvas.getContext().setId(DOC_MAIN_CANVAS_ID);+ canvas.getCanvasEle().style.backgroundColor = getDocsCanvasBackgroundColor(documentFlavor);}});diff --git a/packages/docs-ui/src/services/editor/editor-manager.service.ts b/packages/docs-ui/src/services/editor/editor-manager.service.tsindex 98ff31c53f..581d198f73 100644--- a/packages/docs-ui/src/services/editor/editor-manager.service.ts+++ b/packages/docs-ui/src/services/editor/editor-manager.service.ts@@ -15,13 +15,14 @@*/import type { DocumentDataModel, IDisposable, IDocumentBody, IDocumentData, Nullable } from '@univerjs/core';-import type { ISuccinctDocRangeParam, Scene } from '@univerjs/engine-render';+import type { DocBackground, ISuccinctDocRangeParam, Scene } from '@univerjs/engine-render';import type { Observable } from 'rxjs';import type { IEditorConfigParams } from './editor';import { createIdentifier, DEFAULT_EMPTY_DOCUMENT_VALUE, Disposable, EDITOR_ACTIVATED, FOCUSING_COMMENT_EDITOR, FOCUSING_EDITOR_STANDALONE, HorizontalAlign, ICommandService, IContextService, Inject, Injector, isCommentEditorID, isInternalEditorID, IUndoRedoService, IUniverInstanceService, toDisposable, UniverInstanceType, VerticalAlign } from '@univerjs/core';import { DocSelectionManagerService } from '@univerjs/docs';import { IRenderManagerService } from '@univerjs/engine-render';import { fromEvent, Subject } from 'rxjs';+import { DOCS_VIEW_KEY } from '../../basics/docs-view-key';import { Editor } from './editor';/**@@ -234,6 +235,16 @@ export class EditorService extends Disposable implements IEditorService, IDispos);this._editors.set(editorUnitId, editor);+ if (canvasStyle.backgroundColor != null) {+ render.engine.getCanvas().getCanvasEle().style.backgroundColor = canvasStyle.backgroundColor;+ const docBackground = render.components.get(DOCS_VIEW_KEY.BACKGROUND) as DocBackground | undefined;+ docBackground?.setFillColors(+ canvasStyle.backgroundColor,+ canvasStyle.backgroundColor,+ canvasStyle.backgroundColor,+ canvasStyle.backgroundColor+ );+ }// Delete scroll barif (!config.scrollBar) {diff --git a/packages/docs-ui/src/services/editor/editor.ts b/packages/docs-ui/src/services/editor/editor.tsindex b0b354c02e..813e1dda93 100644--- a/packages/docs-ui/src/services/editor/editor.ts+++ b/packages/docs-ui/src/services/editor/editor.ts@@ -84,6 +84,7 @@ export interface IEditorStateParams extends Partial<IPosition> {export interface IEditorCanvasStyle {fontSize?: number;+ backgroundColor?: string;}export interface IEditorConfigParams {diff --git a/packages/docs-ui/src/services/float-menu.service.ts b/packages/docs-ui/src/services/float-menu.service.tsindex fbf963e0cb..291bd8ed39 100644--- a/packages/docs-ui/src/services/float-menu.service.ts+++ b/packages/docs-ui/src/services/float-menu.service.ts@@ -108,6 +108,10 @@ export class DocFloatMenuService extends Disposable implements IRenderModule {return;}+ if (isRangeInCodeBlock(documentDataModel, range)) {+ return;+ }+const token = documentDataModel.getBody()?.dataStream[range.startOffset];if (range.endOffset - range.startOffset === 1 && token && SKIP_SYMBOLS.includes(token)) {return;@@ -134,3 +138,12 @@ export class DocFloatMenuService extends Disposable implements IRenderModule {return toDisposable(() => this._hideFloatMenu());}}++function isRangeInCodeBlock(documentDataModel: DocumentDataModel, range: ITextRangeParam): boolean {+ const blockRanges = documentDataModel.getBody()?.blockRanges ?? [];++ return blockRanges.some((blockRange) => (+ blockRange.blockType === 'code' &&+ Math.max(range.startOffset, blockRange.startIndex) <= Math.min(range.endOffset, blockRange.endIndex)+ ));+}diff --git a/packages/docs-ui/src/services/selection/__tests__/convert-text-range.spec.ts b/packages/docs-ui/src/services/selection/__tests__/convert-text-range.spec.tsindex ecb193f539..a51d7e3572 100644--- a/packages/docs-ui/src/services/selection/__tests__/convert-text-range.spec.ts+++ b/packages/docs-ui/src/services/selection/__tests__/convert-text-range.spec.ts@@ -14,11 +14,17 @@* limitations under the License.*/-import { describe, expect, it } from 'vitest';-import { compareNodePosition, compareNodePositionLogic, getOneTextSelectionRange, pushToPoints } from '../convert-text-range';+import type { INodePosition } from '@univerjs/engine-render';+import { DocumentSkeletonPageType, setDocsTableRenderViewportProvider } from '@univerjs/engine-render';+import { afterEach, describe, expect, it } from 'vitest';+import { compareNodePosition, compareNodePositionLogic, getOneTextSelectionRange, NodePositionConvertToCursor, pushToPoints } from '../convert-text-range';import { getAnchorBounding, getLineBounding } from '../text-range';describe('selection convert text range helpers', () => {+ afterEach(() => {+ setDocsTableRenderViewportProvider(null);+ });+it('compares node positions in document order', () => {const start = { page: 0, section: 0, column: 0, line: 0, divide: 0, glyph: 0 } as never;const end = { page: 0, section: 0, column: 0, line: 1, divide: 0, glyph: 0 } as never;@@ -80,4 +86,182 @@ describe('selection convert text range helpers', () => {{ left: 0, right: 4, top: 0, bottom: 2 },]);});++ it('projects cell cursors through the table horizontal viewport', () => {+ setDocsTableRenderViewportProvider((unitId, tableId) => {+ if (unitId !== 'unit-1' || tableId !== 'table-1') {+ return null;+ }++ return {+ contentWidth: 400,+ scrollLeft: 50,+ viewportWidth: 120,+ };+ });++ const glyph = {+ bBox: { ba: 8, bd: 2 },+ count: 1,+ glyphType: 'LETTER',+ left: 20,+ width: 10,+ };+ const cell = {+ left: 100,+ marginLeft: 0,+ marginTop: 0,+ sections: [{+ columns: [{+ left: 0,+ lines: [{+ asc: 10,+ divides: [{+ glyphGroup: [glyph],+ left: 0,+ paddingLeft: 0,+ }],+ lineHeight: 20,+ marginBottom: 0,+ marginTop: 0,+ paddingTop: 0,+ top: 0,+ }],+ }],+ top: 0,+ }],+ };+ const row = {+ cells: [cell],+ height: 20,+ index: 0,+ top: 0,+ };+ const table = {+ left: 0,+ rows: [row],+ tableId: 'table-1',+ top: 0,+ };+ const page = {+ marginLeft: 0,+ marginTop: 0,+ pageHeight: 500,+ pageWidth: 500,+ skeTables: new Map([['table-1', table]]),+ };++ (cell as { parent?: unknown }).parent = row;+ (row as { parent?: unknown }).parent = table;++ const skeleton = {+ getSkeletonData: () => ({+ pages: [page],+ skeFooters: new Map(),+ skeHeaders: new Map(),+ }),+ getViewModel: () => ({+ getDataModel: () => ({+ getUnitId: () => 'unit-1',+ }),+ }),+ };+ const position: INodePosition = {+ column: 0,+ divide: 0,+ glyph: 0,+ isBack: false,+ line: 0,+ page: 0,+ pageType: DocumentSkeletonPageType.CELL,+ path: ['pages', 0, 'skeTables', 'table-1', 'rows', 0, 'cells', 0],+ section: 0,+ segmentPage: 0,+ };++ const convertor = new NodePositionConvertToCursor({+ docsLeft: 0,+ docsTop: 0,+ pageLayoutType: 0,+ pageMarginLeft: 0,+ pageMarginTop: 0,+ } as never, skeleton as never);++ const result = convertor.getRangePointData(position, position);++ expect(getAnchorBounding(result.contentBoxPointGroup).left).toBe(70);+ });++ it('excludes layout-only paragraph spacing from text selection height', () => {+ const glyph = {+ bBox: { ba: 10, bd: 3 },+ count: 1,+ glyphType: 'LETTER',+ left: 0,+ width: 20,+ };+ const line = {+ asc: 13,+ contentHeight: 16,+ divides: [{+ glyphGroup: [glyph],+ left: 0,+ paddingLeft: 0,+ }],+ lineHeight: 92,+ marginBottom: 34,+ marginTop: 0,+ paddingBottom: 4,+ paddingTop: 4,+ top: 0,+ };+ const page = {+ marginLeft: 0,+ marginTop: 0,+ pageHeight: 500,+ pageWidth: 500,+ sections: [{+ columns: [{+ left: 0,+ lines: [line],+ }],+ top: 0,+ }],+ };+ const skeleton = {+ getSkeletonData: () => ({+ pages: [page],+ skeFooters: new Map(),+ skeHeaders: new Map(),+ }),+ };+ const position: INodePosition = {+ column: 0,+ divide: 0,+ glyph: 0,+ isBack: false,+ line: 0,+ page: 0,+ pageType: DocumentSkeletonPageType.BODY,+ path: ['pages', 0],+ section: 0,+ segmentPage: -1,+ };+ const convertor = new NodePositionConvertToCursor({+ docsLeft: 0,+ docsTop: 0,+ pageLayoutType: 0,+ pageMarginLeft: 0,+ pageMarginTop: 0,+ } as never, skeleton as never);++ const result = convertor.getRangePointData(position, position);++ expect(getLineBounding(result.borderBoxPointGroup)[0]).toEqual({+ bottom: 24,+ left: 0,+ right: 20,+ top: 0,+ });+ });});diff --git a/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts b/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.tsindex 2dad0d3876..b128e2f284 100644--- a/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts+++ b/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts@@ -16,6 +16,7 @@import type { Mock } from 'vitest';import { DataStreamTreeTokenType, DOC_RANGE_TYPE } from '@univerjs/core';+import { GlyphType } from '@univerjs/engine-render';import { beforeEach, describe, expect, it, vi } from 'vitest';import { DocSelectionRenderService } from '../doc-selection-render.service';import { TextRange } from '../text-range';@@ -23,11 +24,13 @@ import { TextRange } from '../text-range';const {getCanvasOffsetByEngineMock,getRangeListFromCharIndexMock,+ getRangeListFromSelectionMock,getRectRangeFromCharIndexMock,getTextRangeFromCharIndexMock,} = vi.hoisted(() => ({getCanvasOffsetByEngineMock: vi.fn(),getRangeListFromCharIndexMock: vi.fn(),+ getRangeListFromSelectionMock: vi.fn(),getRectRangeFromCharIndexMock: vi.fn(),getTextRangeFromCharIndexMock: vi.fn(),}));@@ -39,6 +42,7 @@ vi.mock('../selection-utils', async () => {...actual,getCanvasOffsetByEngine: getCanvasOffsetByEngineMock,getRangeListFromCharIndex: getRangeListFromCharIndexMock,+ getRangeListFromSelection: getRangeListFromSelectionMock,getRectRangeFromCharIndex: getRectRangeFromCharIndexMock,getTextRangeFromCharIndex: getTextRangeFromCharIndexMock,};@@ -72,6 +76,8 @@ interface IFakeRectRange {}interface IServiceHarness {+ _anchorNodePosition?: unknown;+ _focusNodePosition?: unknown;_rangeList: IFakeTextRange[];_rangeListCache: IFakeTextRange[];_rectRangeList: IFakeRectRange[];@@ -95,6 +101,7 @@ interface IServiceHarness {_createTextRangeByAnchorPosition(position: Record<string, unknown>): void;_isEmpty(): boolean;_getCanvasOffset(): { left: number; top: number };+ _moving(moveOffsetX: number, moveOffsetY: number): void;_updateInputPosition(): void;addDocRanges(ranges: Array<Record<string, unknown>>, isEditing?: boolean, options?: Record<string, boolean>): void;setCursorManually(evtOffsetX: number, evtOffsetY: number): void;@@ -125,7 +132,7 @@ function createRectRange(overrides: Partial<IFakeRectRange> = {}): IFakeRectRang}function createService() {- const engine = { name: 'engine' };+ const engine = { name: 'engine', setCapture: vi.fn() };const skeleton = { name: 'skeleton' };const mainComponent = { name: 'doc-component' };const scene = {@@ -146,6 +153,9 @@ function createService() {mainComponent,unitId: 'unit-1',},+ _container: {+ style: {},+ },_docSkeletonManagerService: {getSkeleton: vi.fn(() => skeleton),},@@ -176,6 +186,7 @@ describe('doc selection render service internals', () => {vi.clearAllMocks();getCanvasOffsetByEngineMock.mockReturnValue({ left: 8, top: 16 });getRangeListFromCharIndexMock.mockReturnValue(null);+ getRangeListFromSelectionMock.mockReturnValue(null);getRectRangeFromCharIndexMock.mockReturnValue(null);getTextRangeFromCharIndexMock.mockReturnValue(null);vi.spyOn(TextRange.prototype as unknown as Record<'_anchorBlink', () => void>, '_anchorBlink').mockImplementation(() => {});@@ -273,6 +284,7 @@ describe('doc selection render service internals', () => {expect(collapsedRange.dispose).toHaveBeenCalledTimes(1);expect(expandedRange.dispose).not.toHaveBeenCalled();+ expect(service._rangeList).toEqual([expandedRange]);expect(service.focus).toHaveBeenCalledTimes(1);});@@ -448,6 +460,121 @@ describe('doc selection render service internals', () => {});});+ it('snaps reverse drag focus to the start of the first glyph so the first character remains selectable', () => {+ const { engine, mainComponent, scene, service, skeleton } = createService();+ const firstGlyph: {+ content: string;+ count: number;+ glyphType: GlyphType;+ parent?: unknown;+ } = {+ content: 'D',+ count: 1,+ glyphType: GlyphType.WORD,+ };+ const secondGlyph: {+ content: string;+ count: number;+ glyphType: GlyphType;+ parent?: unknown;+ } = {+ content: 'o',+ count: 1,+ glyphType: GlyphType.WORD,+ };+ const divide = {+ glyphGroup: [firstGlyph, secondGlyph],+ };+ firstGlyph.parent = divide;+ secondGlyph.parent = divide;++ const anchorPosition = {+ page: 0,+ section: 0,+ column: 0,+ line: 1,+ divide: 0,+ glyph: 4,+ isBack: false,+ };+ const focusPosition = {+ page: 0,+ section: 0,+ column: 0,+ line: 0,+ divide: 0,+ glyph: 0,+ isBack: false,+ };+ const textRange = createTextRange({ collapsed: false });++ service._anchorNodePosition = anchorPosition;+ service._findNodeByCoord.mockReturnValue({ node: firstGlyph });+ service._getNodePosition.mockReturnValue(focusPosition);+ getRangeListFromSelectionMock.mockReturnValue({+ textRanges: [textRange],+ rectRanges: [],+ });++ service._moving(120, 80);++ expect(focusPosition.isBack).toBe(true);+ expect(getRangeListFromSelectionMock).toHaveBeenCalledWith(+ anchorPosition,+ expect.objectContaining({+ glyph: 0,+ isBack: true,+ }),+ scene,+ mainComponent,+ skeleton,+ service._selectionStyle,+ 'segment-1',+ 2+ );+ expect(service._rangeListCache).toEqual([textRange]);+ expect(engine.setCapture).toHaveBeenCalledTimes(1);+ });++ it('disposes collapsed transient ranges while moving so they do not leak as extra cursors', () => {+ const { engine, service } = createService();+ const glyph = {+ content: 'D',+ count: 1,+ glyphType: GlyphType.WORD,+ parent: {+ glyphGroup: [] as unknown[],+ },+ };+ glyph.parent.glyphGroup = [glyph];+ const anchorPosition = {+ page: 0,+ section: 0,+ column: 0,+ line: 0,+ divide: 0,+ glyph: 0,+ isBack: true,+ };+ const focusPosition = { ...anchorPosition };+ const collapsedTextRange = createTextRange({ collapsed: true });++ service._anchorNodePosition = anchorPosition;+ service._findNodeByCoord.mockReturnValue({ node: glyph });+ service._getNodePosition.mockReturnValue(focusPosition);+ getRangeListFromSelectionMock.mockReturnValue({+ textRanges: [collapsedTextRange],+ rectRanges: [],+ });++ service._moving(120, 80);++ expect(collapsedTextRange.dispose).toHaveBeenCalledTimes(1);+ expect(service._focusNodePosition).toBeUndefined();+ expect(service._rangeListCache).toEqual([]);+ expect(engine.setCapture).not.toHaveBeenCalled();+ });+it('clears ranges when manual cursor placement cannot resolve a node position', () => {const { service } = createService();const removeAllRangesSpy = vi.fn();diff --git a/packages/docs-ui/src/services/selection/__tests__/selection-utils.spec.ts b/packages/docs-ui/src/services/selection/__tests__/selection-utils.spec.tsindex daca1fb4aa..6c956ded0c 100644--- a/packages/docs-ui/src/services/selection/__tests__/selection-utils.spec.ts+++ b/packages/docs-ui/src/services/selection/__tests__/selection-utils.spec.ts@@ -14,7 +14,8 @@* limitations under the License.*/-import { getOffsetRectForDom } from '@univerjs/engine-render';+import type { INodePosition } from '@univerjs/engine-render';+import { getOffsetRectForDom, setDocsTableRenderViewportProvider } from '@univerjs/engine-render';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { NodePositionConvertToRectRange } from '../convert-rect-range';import { RectRange } from '../rect-range';@@ -29,6 +30,289 @@ import {} from '../selection-utils';import { TextRange } from '../text-range';+interface IMockCellPage {+ segmentId: string;+ left: number;+ top: number;+ pageWidth: number;+ width: number;+ height: number;+ sections: Array<{+ columns: Array<{+ lines: unknown[];+ }>;+ }>;+ parent?: unknown;+}++interface IMockRow {+ index: number;+ top: number;+ height: number;+ cells: IMockCellPage[];+ parent?: unknown;+}++function createCellPage(left: number, width: number, segmentId = 'table-1'): IMockCellPage {+ return {+ segmentId,+ left,+ top: 0,+ pageWidth: width,+ width,+ height: 20,+ sections: [{+ columns: [{+ lines: [{+ divides: [{+ glyphGroup: [{ count: 1, content: 'A' }],+ }],+ }],+ }],+ }],+ };+}++function createEmptyCellPage(left: number, width: number, segmentId = 'table-1'): IMockCellPage {+ return {+ segmentId,+ left,+ top: 0,+ pageWidth: width,+ width,+ height: 20,+ sections: [{+ columns: [{+ lines: [],+ }],+ }],+ };+}++function createRectRangeConvertorHarness() {+ const cell00 = createCellPage(0, 200);+ const cell01 = createCellPage(100, 0);+ const cell10 = createCellPage(0, 100);+ const cell11 = createCellPage(100, 100);+ const row0 = { index: 0, top: 0, height: 20, cells: [cell00, cell01] } as never;+ const row1 = { index: 1, top: 20, height: 20, cells: [cell10, cell11] } as never;+ const table = { tableId: 'table-1', top: 0, left: 0, rows: [row0, row1] } as never;+ const page = { skeTables: new Map([['table-1', table]]), marginTop: 0, marginLeft: 0, width: 300, height: 200 } as never;++ (cell00 as { parent?: unknown }).parent = row0;+ (cell01 as { parent?: unknown }).parent = row0;+ (cell10 as { parent?: unknown }).parent = row1;+ (cell11 as { parent?: unknown }).parent = row1;+ (row0 as { parent?: unknown }).parent = table;+ (row1 as { parent?: unknown }).parent = table;++ const skeleton = {+ getSkeletonData: () => ({+ pages: [page],+ }),+ getViewModel: () => ({+ getSnapshot: () => ({+ tableSource: {+ 'table-1': {+ tableRows: [+ {+ tableCells: [+ { columnSpan: 2 },+ { rowSpan: 0, columnSpan: 0 },+ ],+ },+ {+ tableCells: [+ {},+ {},+ ],+ },+ ],+ },+ },+ }),+ }),+ };++ return {+ anchor: createNodePosition(['pages', 0, 'skeTables', 'table-1', 'rows', 0, 'cells', 1]),+ focus: createNodePosition(['pages', 0, 'skeTables', 'table-1', 'rows', 1, 'cells', 1]),+ skeleton,+ };+}++function createVerticalMergeConvertorHarness() {+ const rows = Array.from({ length: 4 }, (_, rowIndex) => {+ const cells = Array.from({ length: 4 }, (_, columnIndex) => createCellPage(columnIndex * 100, 100));+ const row: IMockRow = { index: rowIndex, top: rowIndex * 20, height: 20, cells };+ cells.forEach((cell) => {+ (cell as { parent?: unknown }).parent = row;+ });++ return row;+ });+ const table = { tableId: 'table-1', top: 0, left: 0, rows } as never;+ const page = { skeTables: new Map([['table-1', table]]), marginTop: 0, marginLeft: 0, width: 500, height: 200 } as never;+ rows.forEach((row) => {+ (row as { parent?: unknown }).parent = table;+ });++ const tableNode = {+ children: rows.map((_row, rowIndex) => ({+ children: Array.from({ length: 4 }, (_cell, columnIndex) => ({+ startIndex: rowIndex * 100 + columnIndex * 10,+ endIndex: rowIndex * 100 + columnIndex * 10 + 8,+ })),+ })),+ };+ const findNodePositionByCharIndex = vi.fn((index: number) => createNodePosition(['char', index]));+ const skeleton = {+ getSkeletonData: () => ({+ pages: [page],+ }),+ findCharIndexByPosition: vi+ .fn()+ .mockReturnValueOnce(0)+ .mockReturnValueOnce(999),+ findNodePositionByCharIndex,+ getViewModel: () => ({+ getSnapshot: () => ({+ tableSource: {+ 'table-1': {+ tableRows: [+ {+ tableCells: [+ { rowSpan: 3, columnSpan: 2 },+ { rowSpan: 0, columnSpan: 0 },+ {},+ {},+ ],+ },+ {+ tableCells: [+ { rowSpan: 0, columnSpan: 0 },+ { rowSpan: 0, columnSpan: 0 },+ {},+ {},+ ],+ },+ {+ tableCells: [+ { rowSpan: 0, columnSpan: 0 },+ { rowSpan: 0, columnSpan: 0 },+ {},+ {},+ ],+ },+ {+ tableCells: [+ {},+ {},+ {},+ {},+ ],+ },+ ],+ },+ },+ }),+ findTableNodeById: () => tableNode,+ }),+ };++ return {+ anchor: createNodePosition(['pages', 0, 'skeTables', 'table-1', 'rows', 0, 'cells', 0]),+ focus: createNodePosition(['pages', 0, 'skeTables', 'table-1', 'rows', 3, 'cells', 1]),+ findNodePositionByCharIndex,+ skeleton,+ };+}++function createRowSpanMergePointHarness() {+ const rows = Array.from({ length: 4 }, (_, rowIndex) => {+ const cells = Array.from({ length: 4 }, (_cell, columnIndex) => createCellPage(columnIndex * 100, 100));+ const row: IMockRow = { index: rowIndex, top: rowIndex * 20, height: 20, cells };+ cells.forEach((cell) => {+ (cell as { parent?: unknown }).parent = row;+ });++ return row;+ });++ rows[0].cells[1] = createCellPage(100, 200);+ rows[0].cells[2] = createEmptyCellPage(200, 0);+ rows[1].cells[1] = createEmptyCellPage(100, 0);+ rows[1].cells[2] = createEmptyCellPage(200, 0);+ rows[2].cells[1] = createEmptyCellPage(100, 0);+ rows[2].cells[2] = createEmptyCellPage(200, 0);++ rows.forEach((row) => {+ row.cells.forEach((cell) => {+ (cell as { parent?: unknown }).parent = row;+ });+ });++ const table = { tableId: 'table-1', top: 0, left: 0, rows } as never;+ const page = { skeTables: new Map([['table-1', table]]), marginTop: 0, marginLeft: 0, width: 500, height: 200 } as never;+ rows.forEach((row) => {+ (row as { parent?: unknown }).parent = table;+ });++ const skeleton = {+ getSkeletonData: () => ({+ pages: [page],+ }),+ getViewModel: () => ({+ getSnapshot: () => ({+ tableSource: {+ 'table-1': {+ tableRows: [+ {+ tableCells: [+ {},+ { rowSpan: 3, columnSpan: 2 },+ { rowSpan: 0, columnSpan: 0 },+ {},+ ],+ },+ {+ tableCells: [+ {},+ { rowSpan: 0, columnSpan: 0 },+ { rowSpan: 0, columnSpan: 0 },+ {},+ ],+ },+ {+ tableCells: [+ {},+ { rowSpan: 0, columnSpan: 0 },+ { rowSpan: 0, columnSpan: 0 },+ {},+ ],+ },+ {+ tableCells: [+ {},+ {},+ {},+ {},+ ],+ },+ ],+ },+ },+ }),+ }),+ };++ return {+ anchor: createNodePosition(['pages', 0, 'skeTables', 'table-1', 'rows', 0, 'cells', 0]),+ focus: createNodePosition(['pages', 0, 'skeTables', 'table-1', 'rows', 2, 'cells', 1]),+ skeleton,+ };+}+vi.mock('@univerjs/engine-render', async (importOriginal) => {const actual = await importOriginal<typeof import('@univerjs/engine-render')>();@@ -38,7 +322,7 @@ vi.mock('@univerjs/engine-render', async (importOriginal) => {};});-function createNodePosition(path: Array<string | number>, glyph = 0) {+function createNodePosition(path: Array<string | number>, glyph = 0): INodePosition {return {path,page: 0,@@ -50,7 +334,7 @@ function createNodePosition(path: Array<string | number>, glyph = 0) {isBack: false,segmentPage: -1,pageType: 0,- } as never;+ } as INodePosition;}function createGlyphInCell(cellPage: object) {@@ -85,6 +369,7 @@ describe('selection utils', () => {});afterEach(() => {+ setDocsTableRenderViewportProvider(null);vi.restoreAllMocks();});@@ -164,6 +449,252 @@ describe('selection utils', () => {expect(rectRange?.rectRanges[0]).toBeInstanceOf(RectRange);});+ it('expands core rect selection records to cover intersecting merged cells', () => {+ const { anchor, focus, skeleton } = createRectRangeConvertorHarness();+ const convertor = new NodePositionConvertToRectRange({+ docsLeft: 0,+ docsTop: 0,+ pageLayoutType: 0,+ pageMarginLeft: 0,+ pageMarginTop: 0,+ } as never, skeleton as never);++ const result = convertor.getRangePointData(anchor, focus);++ expect(result).toMatchObject({+ startRow: 0,+ endRow: 1,+ startColumn: 0,+ endColumn: 1,+ tableId: 'table-1',+ });+ });++ it('keeps merge-expanded rect selection as one range to avoid overlapping highlights', () => {+ const { anchor, focus, findNodePositionByCharIndex, skeleton } = createVerticalMergeConvertorHarness();+ const convertor = new NodePositionConvertToRectRange({+ docsLeft: 0,+ docsTop: 0,+ pageLayoutType: 0,+ pageMarginLeft: 0,+ pageMarginTop: 0,+ } as never, skeleton as never);++ const groups = convertor.getNodePositionGroup(anchor, focus);++ expect(groups).toEqual([{ anchor, focus }]);+ expect(findNodePositionByCharIndex).not.toHaveBeenCalled();+ });++ it('draws row-spanning merged cells as full merged rectangles without row gaps', () => {+ const { anchor, focus, skeleton } = createRowSpanMergePointHarness();+ const convertor = new NodePositionConvertToRectRange({+ docsLeft: 0,+ docsTop: 0,+ pageLayoutType: 0,+ pageMarginLeft: 0,+ pageMarginTop: 0,+ } as never, skeleton as never);++ const result = convertor.getRangePointData(anchor, focus);++ expect(result).toMatchObject({+ startRow: 0,+ endRow: 2,+ startColumn: 0,+ endColumn: 2,+ });+ expect(result?.pointGroup).toHaveLength(1);+ expect(result?.pointGroup[0]).toEqual([+ { x: 0, y: 0 },+ { x: 300, y: 0 },+ { x: 300, y: 60 },+ { x: 0, y: 60 },+ { x: 0, y: 0 },+ ]);+ });++ it('draws a full row-spanning merge when the drag only reaches its first row', () => {+ const { anchor, skeleton } = createRowSpanMergePointHarness();+ const focus = createNodePosition(['pages', 0, 'skeTables', 'table-1', 'rows', 0, 'cells', 1]);+ const convertor = new NodePositionConvertToRectRange({+ docsLeft: 0,+ docsTop: 0,+ pageLayoutType: 0,+ pageMarginLeft: 0,+ pageMarginTop: 0,+ } as never, skeleton as never);++ const result = convertor.getRangePointData(anchor, focus);++ expect(result).toMatchObject({+ startRow: 0,+ endRow: 2,+ startColumn: 0,+ endColumn: 2,+ });+ expect(result?.pointGroup).toHaveLength(1);+ expect(result?.pointGroup[0]).toEqual([+ { x: 0, y: 0 },+ { x: 300, y: 0 },+ { x: 300, y: 60 },+ { x: 0, y: 60 },+ { x: 0, y: 0 },+ ]);+ });++ it('draws merge-expanded rect selection as one solid rectangle', () => {+ const { anchor, focus, skeleton } = createVerticalMergeConvertorHarness();+ const convertor = new NodePositionConvertToRectRange({+ docsLeft: 0,+ docsTop: 0,+ pageLayoutType: 0,+ pageMarginLeft: 0,+ pageMarginTop: 0,+ } as never, skeleton as never);++ const result = convertor.getRangePointData(anchor, focus);++ expect(result?.pointGroup).toHaveLength(1);+ expect(result?.pointGroup[0]).toEqual([+ { x: 0, y: 0 },+ { x: 200, y: 0 },+ { x: 200, y: 80 },+ { x: 0, y: 80 },+ { x: 0, y: 0 },+ ]);+ });++ it('clips table rect selection to the horizontal render viewport', () => {+ const { anchor, focus, skeleton } = createRowSpanMergePointHarness();+ setDocsTableRenderViewportProvider((unitId, tableId) => {+ if (unitId !== 'unit-1' || tableId !== 'table-1') {+ return null;+ }++ return {+ contentWidth: 400,+ scrollLeft: 150,+ viewportWidth: 200,+ };+ });+ (skeleton as unknown as {+ getViewModel: () => {+ getDataModel: () => {+ getUnitId: () => string;+ };+ getSnapshot: () => unknown;+ };+ }).getViewModel = () => ({+ getDataModel: () => ({+ getUnitId: () => 'unit-1',+ }),+ getSnapshot: () => ({+ tableSource: {+ 'table-1': {+ tableRows: [+ {+ tableCells: [+ {},+ { rowSpan: 3, columnSpan: 2 },+ { rowSpan: 0, columnSpan: 0 },+ {},+ ],+ },+ {+ tableCells: [+ {},+ { rowSpan: 0, columnSpan: 0 },+ { rowSpan: 0, columnSpan: 0 },+ {},+ ],+ },+ {+ tableCells: [+ {},+ { rowSpan: 0, columnSpan: 0 },+ { rowSpan: 0, columnSpan: 0 },+ {},+ ],+ },+ {+ tableCells: [+ {},+ {},+ {},+ {},+ ],+ },+ ],+ },+ },+ }),+ });+ const convertor = new NodePositionConvertToRectRange({+ docsLeft: 0,+ docsTop: 0,+ pageLayoutType: 0,+ pageMarginLeft: 0,+ pageMarginTop: 0,+ } as never, skeleton as never);++ const result = convertor.getRangePointData(anchor, focus);++ expect(result?.pointGroup).toHaveLength(1);+ expect(result?.pointGroup[0]).toEqual([+ { x: 0, y: 0 },+ { x: 150, y: 0 },+ { x: 150, y: 60 },+ { x: 0, y: 60 },+ { x: 0, y: 0 },+ ]);+ });++ it('keeps drags inside one merged cell as text selection', () => {+ const { anchor, skeleton } = createRectRangeConvertorHarness();+ const focus = {+ ...anchor,+ glyph: 1,+ };+ const cellPage = createCellPage(0, 200);+ const row = { index: 0, cells: [cellPage] };+ (cellPage as { parent?: unknown }).parent = row;+ (skeleton as { findGlyphByPosition?: unknown }).findGlyphByPosition = vi.fn(() => createGlyphInCell(cellPage));+ (skeleton as { findCharIndexByPosition?: unknown }).findCharIndexByPosition = vi.fn(() => undefined);++ const result = getRangeListFromSelection(anchor, focus, {} as never, createDocument(), skeleton as never, {} as never, '', -1);++ expect(result?.textRanges).toHaveLength(1);+ expect(result?.textRanges[0]).toBeInstanceOf(TextRange);+ expect(result?.rectRanges).toHaveLength(0);+ });++ it('routes drags from another cell through a merged cell into core rect selection', () => {+ const { anchor: mergedFocus, focus: normalAnchor, skeleton } = createRectRangeConvertorHarness();+ const mergedCellPage = createCellPage(0, 200);+ const normalCellPage = createCellPage(100, 100);+ const mergedRow = { index: 0, cells: [mergedCellPage] };+ const normalRow = { index: 1, cells: [normalCellPage] };+ (mergedCellPage as { parent?: unknown }).parent = mergedRow;+ (normalCellPage as { parent?: unknown }).parent = normalRow;+ (skeleton as { findGlyphByPosition?: unknown }).findGlyphByPosition = vi+ .fn()+ .mockReturnValueOnce(createGlyphInCell(normalCellPage))+ .mockReturnValueOnce(createGlyphInCell(mergedCellPage));+ vi.spyOn(NodePositionConvertToRectRange.prototype, 'getNodePositionGroup').mockReturnValue([+ {+ anchor: normalAnchor,+ focus: mergedFocus,+ },+ ] as never);++ const result = getRangeListFromSelection(normalAnchor, mergedFocus, {} as never, createDocument(), skeleton as never, {} as never, '', -1);++ expect(result?.textRanges).toHaveLength(0);+ expect(result?.rectRanges).toHaveLength(1);+ expect(result?.rectRanges[0]).toBeInstanceOf(RectRange);+ });+it('builds normal text ranges outside tables and skips when offsets are missing', () => {const startNode = { glyph: 10 };const endNode = { glyph: 20 };@@ -217,6 +748,48 @@ describe('selection utils', () => {expect(missing).toBeUndefined();});+ it('falls back to original boundary positions when the first character index cannot be resolved back to a node', () => {+ const focusPosition = createNodePosition(['body'], 0);+ focusPosition.isBack = true;+ const anchorPosition = createNodePosition(['body'], 4);+ const endNode = createNodePosition(['char', 468], 4);+ const paragraph = {+ startIndex: 0,+ endIndex: 500,+ children: [],+ };+ const skeleton = {+ findCharIndexByPosition: vi+ .fn()+ .mockReturnValueOnce(468)+ .mockReturnValueOnce(0),+ findNodePositionByCharIndex: vi+ .fn()+ .mockReturnValueOnce(undefined)+ .mockReturnValueOnce(endNode),+ getViewModel: () => ({+ getSelfOrHeaderFooterViewModel: () => ({+ getChildren: () => [{ children: [paragraph] }],+ }),+ }),+ } as never;++ const result = getRangeListFromSelection(+ anchorPosition,+ focusPosition,+ {} as never,+ createDocument(),+ skeleton,+ {} as never,+ '',+ -1+ );++ expect(result?.textRanges).toHaveLength(1);+ expect(result?.textRanges[0].anchorNodePosition).toBe(endNode);+ expect(result?.textRanges[0].focusNodePosition).toBe(focusPosition);+ });+it('reads canvas offsets, paragraph glyph info, and serializes ranges', () => {vi.mocked(getOffsetRectForDom).mockReturnValue({ left: 12, top: 34 } as never);diff --git a/packages/docs-ui/src/services/selection/convert-rect-range.ts b/packages/docs-ui/src/services/selection/convert-rect-range.tsindex 5953362cc5..4f20acfc05 100644--- a/packages/docs-ui/src/services/selection/convert-rect-range.ts+++ b/packages/docs-ui/src/services/selection/convert-rect-range.ts@@ -14,10 +14,10 @@* limitations under the License.*/-import type { Nullable } from '@univerjs/core';-import type { DocumentSkeleton, IDocumentOffsetConfig, IDocumentSkeletonPage, IDocumentSkeletonRow, INodePosition, IPoint } from '@univerjs/engine-render';+import type { ITable, Nullable } from '@univerjs/core';+import type { DocumentSkeleton, IDocsTableRenderViewport, IDocumentOffsetConfig, IDocumentSkeletonPage, IDocumentSkeletonRow, IDocumentSkeletonTable, INodePosition, IPoint } from '@univerjs/engine-render';import { Tools } from '@univerjs/core';-import { DocumentSkeletonPageType, getPageFromPath, getTableIdAndSliceIndex, Liquid } from '@univerjs/engine-render';+import { DocumentSkeletonPageType, getDocsTableRenderViewport, getPageFromPath, getTableIdAndSliceIndex, Liquid } from '@univerjs/engine-render';import { compareNodePositionLogic, pushToPoints } from './convert-text-range';// The anchor and focus need to be in the same table,@@ -166,6 +166,62 @@ function findNonEmptyCellPages(}}+function getColumnBoundary(table: IDocumentSkeletonTable, column: number): Nullable<number> {+ const columns = table.tableSource?.tableColumns;+ if (columns && column >= 0 && column <= columns.length) {+ return columns+ .slice(0, column)+ .reduce((total, tableColumn) => total + (tableColumn.size?.width?.v ?? 0), 0);+ }++ const row = table.rows[0];+ const cell = row?.cells[column];+ if (cell) {+ return cell.left;+ }++ const previousCell = row?.cells[column - 1];+ if (previousCell) {+ return previousCell.left + previousCell.pageWidth;+ }++ return null;+}++function getDocumentUnitId(docSkeleton: DocumentSkeleton): string {+ const viewModel = docSkeleton.getViewModel() as {+ getDataModel?: () => {+ getUnitId?: () => string;+ };+ };++ return viewModel.getDataModel?.().getUnitId?.() ?? '';+}++function pushViewportClippedPoints(+ pointGroup: IPoint[][],+ position: { endX: number; endY: number; startX: number; startY: number },+ viewport: Nullable<IDocsTableRenderViewport>,+ tableLeft: number+): void {+ const scrollLeft = viewport && viewport.contentWidth > viewport.viewportWidth ? viewport.scrollLeft : 0;+ const viewportWidth = viewport && viewport.contentWidth > viewport.viewportWidth ? viewport.viewportWidth : null;+ const startX = position.startX - scrollLeft;+ const endX = position.endX - scrollLeft;+ const clippedStartX = viewportWidth == null ? startX : Math.max(startX, tableLeft);+ const clippedEndX = viewportWidth == null ? endX : Math.min(endX, tableLeft + viewportWidth);++ if (clippedEndX <= clippedStartX) {+ return;+ }++ pointGroup.push(pushToPoints({+ ...position,+ startX: clippedStartX,+ endX: clippedEndX,+ }));+}+interface IRectRangeNodePositions {anchor: INodePosition;focus: INodePosition;@@ -208,11 +264,14 @@ export class NodePositionConvertToRectRange {startColumnIndex: startColumn,endRowIndex: endRow,endColumnIndex: endColumn,+ intersectsMergedCell,} = rectInfo;this._liquid.reset();const { pageLayoutType, pageMarginLeft, pageMarginTop } = this._documentOffsetConfig;+ const unitId = getDocumentUnitId(docSkeleton);+ const sourceTableId = getTableIdAndSliceIndex(tableId).tableId;const skipPageIndex = pageType === DocumentSkeletonPageType.BODY || pageType === DocumentSkeletonPageType.CELL ? startPage : startSegmentPage;@@ -247,6 +306,29 @@ export class NodePositionConvertToRectRange {const { x, y } = this._liquid;const { left: tableLeft } = table;+ const viewport = getDocsTableRenderViewport(unitId, sourceTableId);++ if (intersectsMergedCell) {+ const rows = table.rows.filter((row) => row.index >= startRow && row.index <= endRow);+ const firstRow = rows[0];+ const lastRow = rows[rows.length - 1];+ const startX = getColumnBoundary(table, startColumn);+ const endX = getColumnBoundary(table, endColumn + 1);++ if (firstRow && lastRow && startX != null && endX != null) {+ pushViewportClippedPoints(pointGroup, {+ startX: x + tableLeft + startX,+ startY: y + firstRow.top,+ endX: x + tableLeft + endX,+ endY: y + lastRow.top + lastRow.height,+ }, viewport, x + tableLeft);+ }++ this._liquid.translateRestore();+ this._liquid.restorePagePadding(page);+ this._liquid.translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);+ continue;+ }for (const row of table.rows) {if (row.index >= startRow && row.index <= endRow) {@@ -265,7 +347,7 @@ export class NodePositionConvertToRectRange {endY: y + row.top + row.height,};- pointGroup.push(pushToPoints(position));+ pushViewportClippedPoints(pointGroup, position, viewport, x + tableLeft);}}@@ -305,7 +387,14 @@ export class NodePositionConvertToRectRange {return;}- const { tableId, startRowIndex, startColumnIndex, endRowIndex, endColumnIndex } = rectInfo;+ const { tableId, startRowIndex, startColumnIndex, endRowIndex, endColumnIndex, intersectsMergedCell } = rectInfo;++ if (intersectsMergedCell) {+ return [{+ anchor: anchorNodePosition,+ focus: focusNodePosition,+ }];+ }const tableNode = this._docSkeleton.getViewModel().findTableNodeById(tableId);@@ -381,19 +470,123 @@ export class NodePositionConvertToRectRange {const focusRow = (focusCell?.parent as IDocumentSkeletonRow).index;const focusColumn = (focusCell?.parent as IDocumentSkeletonRow).cells.indexOf(focusCell);- const startRowIndex = Math.min(anchorRow, focusRow);- const endRowIndex = Math.max(anchorRow, focusRow);-- const startColumnIndex = Math.min(anchorColumn, focusColumn);- const endColumnIndex = Math.max(anchorColumn, focusColumn);+ const sourceTableId = getTableIdAndSliceIndex(tableId).tableId;+ const tableSource = docSkeleton.getViewModel().getSnapshot().tableSource?.[sourceTableId];+ const rawRange = {+ startRowIndex: Math.min(anchorRow, focusRow),+ endRowIndex: Math.max(anchorRow, focusRow),+ startColumnIndex: Math.min(anchorColumn, focusColumn),+ endColumnIndex: Math.max(anchorColumn, focusColumn),+ };+ const intersectsMergedCell = rangeIntersectsMergedCell(tableSource, rawRange);+ const range = expandRangeByMergedCells(tableSource, rawRange);return {pages,tableId,- startRowIndex,- startColumnIndex,- endRowIndex,- endColumnIndex,+ intersectsMergedCell,+ ...range,};}}++interface ITableRange {+ startRowIndex: number;+ endRowIndex: number;+ startColumnIndex: number;+ endColumnIndex: number;+}++function expandRangeByMergedCells(table: Nullable<ITable>, range: ITableRange): ITableRange {+ if (!table) {+ return range;+ }++ let expanded = normalizeRange(range);+ let changed = true;++ while (changed) {+ changed = false;++ table.tableRows.forEach((row, rowIndex) => {+ row.tableCells.forEach((cell, columnIndex) => {+ const rowSpan = cell.rowSpan ?? 1;+ const columnSpan = cell.columnSpan ?? 1;+ if (rowSpan <= 0 || columnSpan <= 0 || (rowSpan === 1 && columnSpan === 1)) {+ return;+ }++ const mergedRange = {+ startRowIndex: rowIndex,+ endRowIndex: rowIndex + rowSpan - 1,+ startColumnIndex: columnIndex,+ endColumnIndex: columnIndex + columnSpan - 1,+ };++ if (!rangesIntersect(expanded, mergedRange)) {+ return;+ }++ const next = {+ startRowIndex: Math.min(expanded.startRowIndex, mergedRange.startRowIndex),+ endRowIndex: Math.max(expanded.endRowIndex, mergedRange.endRowIndex),+ startColumnIndex: Math.min(expanded.startColumnIndex, mergedRange.startColumnIndex),+ endColumnIndex: Math.max(expanded.endColumnIndex, mergedRange.endColumnIndex),+ };++ if (!rangesEqual(expanded, next)) {+ expanded = next;+ changed = true;+ }+ });+ });+ }++ return expanded;+}++function rangeIntersectsMergedCell(table: Nullable<ITable>, range: ITableRange): boolean {+ if (!table) {+ return false;+ }++ const normalized = normalizeRange(range);++ return table.tableRows.some((row, rowIndex) => row.tableCells.some((cell, columnIndex) => {+ const rowSpan = cell.rowSpan ?? 1;+ const columnSpan = cell.columnSpan ?? 1;+ if (rowSpan <= 0 || columnSpan <= 0 || (rowSpan === 1 && columnSpan === 1)) {+ return false;+ }++ return rangesIntersect(normalized, {+ startRowIndex: rowIndex,+ endRowIndex: rowIndex + rowSpan - 1,+ startColumnIndex: columnIndex,+ endColumnIndex: columnIndex + columnSpan - 1,+ });+ }));+}++function normalizeRange(range: ITableRange): ITableRange {+ return {+ startRowIndex: Math.min(range.startRowIndex, range.endRowIndex),+ endRowIndex: Math.max(range.startRowIndex, range.endRowIndex),+ startColumnIndex: Math.min(range.startColumnIndex, range.endColumnIndex),+ endColumnIndex: Math.max(range.startColumnIndex, range.endColumnIndex),+ };+}++function rangesIntersect(left: ITableRange, right: ITableRange): boolean {+ return left.startRowIndex <= right.endRowIndex &&+ left.endRowIndex >= right.startRowIndex &&+ left.startColumnIndex <= right.endColumnIndex &&+ left.endColumnIndex >= right.startColumnIndex;+}++function rangesEqual(left: ITableRange, right: ITableRange): boolean {+ return left.startRowIndex === right.startRowIndex &&+ left.endRowIndex === right.endRowIndex &&+ left.startColumnIndex === right.startColumnIndex &&+ left.endColumnIndex === right.endColumnIndex;+}diff --git a/packages/docs-ui/src/services/selection/convert-text-range.ts b/packages/docs-ui/src/services/selection/convert-text-range.tsindex e0a34acc42..514e8d1cd4 100644--- a/packages/docs-ui/src/services/selection/convert-text-range.ts+++ b/packages/docs-ui/src/services/selection/convert-text-range.ts@@ -28,7 +28,7 @@ import type {INodePosition,IPoint,} from '@univerjs/engine-render';-import { DocumentSkeletonPageType, getPageFromPath, GlyphType, Liquid } from '@univerjs/engine-render';+import { DocumentSkeletonPageType, getDocsTableRenderViewport, getPageFromPath, getTableIdAndSliceIndex, GlyphType, Liquid } from '@univerjs/engine-render';export enum NodePositionStateType {NORMAL,@@ -212,6 +212,7 @@ export function pushToPoints(position: IPosition) {export class NodePositionConvertToCursor {private _liquid = new Liquid();+ private _horizontalClip: Nullable<{ left: number; right: number }> = null;private _currentStartState: ICurrentNodePositionState = {page: NodePositionStateType.NORMAL,@@ -265,7 +266,7 @@ export class NodePositionConvertToCursor {// eslint-disable-next-line complexitythis._selectionIterator(start, end, (start_sp, end_sp, isFirst, isLast, divide, line) => {- const { lineHeight, asc, paddingTop, marginTop, marginBottom } = line;+ const { lineHeight, asc, paddingTop, paddingBottom, contentHeight, marginTop, marginBottom } = line;const { glyphGroup, st } = divide;if (glyphGroup.length === 0) {// The divide is empty, and no need to set selection.@@ -297,13 +298,17 @@ export class NodePositionConvertToCursor {const collapsed = start === end;const anchorGlyph = isStartBack ? (preGlyph ?? firstGlyph) : firstGlyph;+ const borderBoxStartY = startY;+ const borderBoxEndY = contentHeight == null+ ? startY + lineHeight - marginTop - marginBottom+ : startY + paddingTop + contentHeight + paddingBottom;if (start_sp === 0 && end_sp === glyphGroup.length - 1) {borderBoxPosition = {startX: startX + firstGlyphLeft + (isCurrentList ? firstGlyphWidth : 0),- startY,+ startY: borderBoxStartY,endX: startX + lastGlyphLeft + (isEndBack ? 0 : lastGlyphWidth),- endY: startY + lineHeight - marginTop - marginBottom,+ endY: borderBoxEndY,};contentBoxPosition = {@@ -317,9 +322,9 @@ export class NodePositionConvertToCursor {borderBoxPosition = {startX: startX + firstGlyphLeft + (isStartBackFin ? 0 : firstGlyphWidth),- startY,+ startY: borderBoxStartY,endX: startX + lastGlyphLeft + (isEndBack ? 0 : lastGlyphWidth),- endY: startY + lineHeight - marginTop - marginBottom,+ endY: borderBoxEndY,};contentBoxPosition = {@@ -330,8 +335,15 @@ export class NodePositionConvertToCursor {};}- borderBoxPointGroup.push(pushToPoints(borderBoxPosition));- contentBoxPointGroup.push(pushToPoints(contentBoxPosition));+ const clippedBorderBoxPosition = clipPositionToHorizontalRange(borderBoxPosition, this._horizontalClip);+ const clippedContentBoxPosition = clipPositionToHorizontalRange(contentBoxPosition, this._horizontalClip);++ if (clippedBorderBoxPosition) {+ borderBoxPointGroup.push(pushToPoints(clippedBorderBoxPosition));+ }+ if (clippedContentBoxPosition) {+ contentBoxPointGroup.push(pushToPoints(clippedContentBoxPosition));+ }cursorList.push({startOffset: isStartBack ? startOffset : startOffset + firstGlyph.count,@@ -549,6 +561,8 @@ export class NodePositionConvertToCursor {pageType === DocumentSkeletonPageType.BODY || pageType === DocumentSkeletonPageType.CELL ? p : 0);this._liquid.translateSave();+ const previousHorizontalClip = this._horizontalClip;+ this._horizontalClip = null;switch (pageType) {case DocumentSkeletonPageType.HEADER:@@ -569,8 +583,20 @@ export class NodePositionConvertToCursor {const { left: cellLeft } = segmentPage;const { top: tableTop, left: tableLeft } = tableSke;const { top: rowTop } = rowSke;+ const sourceTableId = getTableIdAndSliceIndex(tableSke.tableId).tableId;+ const viewport = getDocsTableRenderViewport(getDocumentUnitId(skeleton), sourceTableId);+ const hasHorizontalViewport = viewport && viewport.contentWidth > viewport.viewportWidth;+ const scrollLeft = hasHorizontalViewport ? viewport.scrollLeft : 0;++ if (hasHorizontalViewport) {+ const visibleLeft = this._liquid.x + tableLeft;+ this._horizontalClip = {+ left: visibleLeft,+ right: visibleLeft + viewport.viewportWidth,+ };+ }- this._liquid.translate(tableLeft + cellLeft, tableTop + rowTop);+ this._liquid.translate(tableLeft + cellLeft - scrollLeft, tableTop + rowTop);this._liquid.translatePagePadding(segmentPage);break;}@@ -655,8 +681,43 @@ export class NodePositionConvertToCursor {}}this._liquid.translateRestore();+ this._horizontalClip = previousHorizontalClip;this._liquid.translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);}}}++function clipPositionToHorizontalRange(position: IPosition, clip: Nullable<{ left: number; right: number }>): Nullable<IPosition> {+ if (!clip) {+ return position;+ }++ const startX = Math.max(position.startX, clip.left);+ const endX = Math.min(position.endX, clip.right);+ const collapsed = position.startX === position.endX;++ if (collapsed) {+ return position.startX >= clip.left && position.startX <= clip.right ? position : null;+ }++ if (endX <= startX) {+ return null;+ }++ return {+ ...position,+ startX,+ endX,+ };+}++function getDocumentUnitId(docSkeleton: DocumentSkeleton): string {+ const viewModel = docSkeleton.getViewModel() as {+ getDataModel?: () => {+ getUnitId?: () => string;+ };+ };++ return viewModel.getDataModel?.().getUnitId?.() ?? '';+}diff --git a/packages/docs-ui/src/services/selection/doc-selection-render.service.ts b/packages/docs-ui/src/services/selection/doc-selection-render.service.tsindex defbd17318..ed4604ebec 100644--- a/packages/docs-ui/src/services/selection/doc-selection-render.service.ts+++ b/packages/docs-ui/src/services/selection/doc-selection-render.service.ts@@ -38,6 +38,7 @@ import { DocSkeletonManagerService } from '@univerjs/docs';import { CURSOR_TYPE, getSystemHighlightColor, GlyphType, NORMAL_TEXT_SELECTION_PLUGIN_STYLE, PageLayoutType, ScrollTimer, Vector2 } from '@univerjs/engine-render';import { ILayoutService, KeyCode } from '@univerjs/ui';import { BehaviorSubject, filter, fromEvent, merge, Subject, takeUntil } from 'rxjs';+import { compareNodePositionLogic } from './convert-text-range';import {getCanvasOffsetByEngine,getParagraphInfoByGlyph,@@ -869,11 +870,18 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo}private _removeAllCollapsedTextRanges() {+ const newRanges: TextRange[] = [];+for (const range of this._rangeList) {if (range.collapsed) {range.dispose();+ continue;}++ newRanges.push(range);}++ this._rangeList = newRanges;}private _deactivateAllTextRanges() {@@ -1032,9 +1040,9 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMofocusNodePosition.isBack = true;}- this._focusNodePosition = focusNodePosition;-- this._removeAllCacheRanges();+ if (this._shouldSnapBackwardFocusToGlyphStart(focusNode, focusNodePosition)) {+ focusNodePosition.isBack = true;+ }const { _anchorNodePosition, _selectionStyle } = this;const { scene, mainComponent } = this._context;@@ -1060,6 +1068,15 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo}const { textRanges, rectRanges } = ranges;+ if (!this._hasVisibleSelectionRanges(textRanges, rectRanges)) {+ textRanges.forEach((range) => range.dispose());+ rectRanges.forEach((range) => range.dispose());+ return;+ }++ this._focusNodePosition = focusNodePosition;++ this._removeAllCacheRanges();if (this._rangeList.length > 0 && textRanges.length > 0) {this._interactTextRanges(textRanges);@@ -1077,6 +1094,42 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMothis._context.scene?.getEngine()?.setCapture();}+ private _hasVisibleSelectionRanges(textRanges: TextRange[], rectRanges: RectRange[]): boolean {+ return rectRanges.length > 0 || textRanges.some((range) => !range.collapsed);+ }++ private _shouldSnapBackwardFocusToGlyphStart(focusNode: INodeInfo, focusNodePosition: INodePosition): boolean {+ const anchorNodePosition = this._anchorNodePosition;+ if (!anchorNodePosition || !this._isBeforeNodePosition(focusNodePosition, anchorNodePosition)) {+ return false;+ }++ return this._isFirstSelectableGlyphInDivide(focusNode);+ }++ private _isBeforeNodePosition(left: INodePosition, right: INodePosition): boolean {+ if (!compareNodePositionLogic(left, right)) {+ return false;+ }++ return left.page !== right.page ||+ left.section !== right.section ||+ left.column !== right.column ||+ left.line !== right.line ||+ left.divide !== right.divide ||+ left.glyph !== right.glyph;+ }++ private _isFirstSelectableGlyphInDivide(nodeInfo: INodeInfo): boolean {+ const glyphGroup = nodeInfo.node.parent?.glyphGroup;+ if (!glyphGroup) {+ return false;+ }++ const firstSelectableGlyph = glyphGroup.find((glyph) => glyph.content && glyph.glyphType !== GlyphType.LIST);+ return firstSelectableGlyph === nodeInfo.node;+ }+__attachScrollEvent() {const viewport = this.activeViewPort;if (!viewport) {diff --git a/packages/docs-ui/src/services/selection/selection-utils.ts b/packages/docs-ui/src/services/selection/selection-utils.tsindex 28c8d52c11..72d831e4e7 100644--- a/packages/docs-ui/src/services/selection/selection-utils.ts+++ b/packages/docs-ui/src/services/selection/selection-utils.ts@@ -36,6 +36,7 @@ import type { IDocRange } from './range-interface';import { RANGE_DIRECTION, Tools } from '@univerjs/core';import { getOffsetRectForDom } from '@univerjs/engine-render';import { isInSameTableCell, isInSameTableCellData, isValidRectRange } from './convert-rect-range';+import { compareNodePosition } from './convert-text-range';import { convertPositionsToRectRanges, RectRange } from './rect-range';import { TextRange } from './text-range';@@ -190,6 +191,15 @@ export function getRangeListFromSelection(const startOffset = Math.min(anchorOffset, focusOffset);const endOffset = Math.max(anchorOffset, focusOffset);+ const originRange = compareNodePosition(anchorPosition, focusPosition);++ const findStartNodePositionByCharIndex = (charIndex: number, isBack: boolean = true) =>+ skeleton.findNodePositionByCharIndex(charIndex, isBack, segmentId, segmentPage) ??+ (charIndex === startOffset ? originRange.start : undefined);++ const findEndNodePositionByCharIndex = (charIndex: number, isBack: boolean = true) =>+ skeleton.findNodePositionByCharIndex(charIndex, isBack, segmentId, segmentPage) ??+ (charIndex === endOffset ? originRange.end : undefined);let start = startOffset;let end = endOffset;@@ -227,8 +237,8 @@ export function getRangeListFromSelection(tableEndPosition = skeleton.findNodePositionByCharIndex(tableEnd - 4, true, segmentId, segmentPage);if (start <= tableStart - 1) {- const sp = skeleton.findNodePositionByCharIndex(start, true, segmentId, segmentPage);- const ep = skeleton.findNodePositionByCharIndex(tableStart - 1, false, segmentId, segmentPage);+ const sp = findStartNodePositionByCharIndex(start, true);+ const ep = findEndNodePositionByCharIndex(tableStart - 1, false);const ap = direction === RANGE_DIRECTION.FORWARD ? sp : ep;const fp = direction === RANGE_DIRECTION.FORWARD ? ep : sp;@@ -262,8 +272,8 @@ export function getRangeListFromSelection(}if ((end >= startIndex && end <= endIndex) || endInTable) {- const sp = skeleton.findNodePositionByCharIndex(start, true, segmentId, segmentPage);- const ep = skeleton.findNodePositionByCharIndex(end, !endInTable, segmentId, segmentPage);+ const sp = findStartNodePositionByCharIndex(start, true);+ const ep = findEndNodePositionByCharIndex(end, !endInTable);const ap = direction === RANGE_DIRECTION.FORWARD ? sp : ep;const fp = direction === RANGE_DIRECTION.FORWARD ? ep : sp;diff --git a/packages/docs-ui/src/views/page-settings/index.tsx b/packages/docs-ui/src/views/page-settings/index.tsxindex 521f03fea9..861748fe2b 100644--- a/packages/docs-ui/src/views/page-settings/index.tsx+++ b/packages/docs-ui/src/views/page-settings/index.tsx@@ -16,8 +16,9 @@import type { DocumentDataModel, ISize, PaperType } from '@univerjs/core';import type { IConfirmChildrenProps } from '@univerjs/ui';-import { IUniverInstanceService, LocaleService, PAGE_SIZE, PageOrientType, PAPER_TYPES, UniverInstanceType } from '@univerjs/core';-import { InputNumber, Select } from '@univerjs/design';+import type { ReactNode } from 'react';+import { DocumentFlavor, IUniverInstanceService, LocaleService, MODERN_DOCUMENT_WIDTH, ModernDocumentWidthMode, PAGE_SIZE, PageOrientType, PAPER_TYPES, UniverInstanceType } from '@univerjs/core';+import { clsx, InputNumber, Select } from '@univerjs/design';import { useDependency } from '@univerjs/ui';import { useEffect, useState } from 'react';@@ -27,6 +28,8 @@ export interface IPageSettingsProps {}export interface IPageSettings {+ mode: DocumentFlavor.TRADITIONAL | DocumentFlavor.MODERN;+ modernWidth: ModernDocumentWidthMode;paperSize: string;orientation: PageOrientType;margins: {@@ -35,12 +38,18 @@ export interface IPageSettings {left: number;right: number;};- pageSise: {+ pageSize: {width: number;height: number;};}+const MODERN_WIDTH_OPTIONS = [+ ModernDocumentWidthMode.NARROW,+ ModernDocumentWidthMode.MEDIUM,+ ModernDocumentWidthMode.WIDE,+];+const getPaperSize = (size: ISize) => {const keys = Object.keys(PAGE_SIZE);@@ -56,6 +65,34 @@ const getPaperSize = (size: ISize) => {return result ?? 'A4';};+const getModernWidthMode = (size?: ISize) => {+ const width = size?.width ?? MODERN_DOCUMENT_WIDTH[ModernDocumentWidthMode.MEDIUM];++ return MODERN_WIDTH_OPTIONS.reduce((nearest, option) => {+ const nearestDistance = Math.abs(MODERN_DOCUMENT_WIDTH[nearest] - width);+ const currentDistance = Math.abs(MODERN_DOCUMENT_WIDTH[option] - width);++ return currentDistance < nearestDistance ? option : nearest;+ }, ModernDocumentWidthMode.MEDIUM);+};++function SettingsLabel(props: { children: ReactNode; muted?: boolean }) {+ const { children, muted } = props;++ return (+ <label+ className={clsx('univer-text-sm univer-font-medium', muted+ ? 'univer-text-gray-500'+ : `+ univer-text-gray-900+ dark:!univer-text-white+ `)}+ >+ {children}+ </label>+ );+}+export function PageSettings(props: IConfirmChildrenProps) {const { hooks } = props;const univerInstanceService = useDependency(IUniverInstanceService);@@ -63,8 +100,10 @@ export function PageSettings(props: IConfirmChildrenProps) {const documentStyle = currentDoc.getDocumentStyle();const localeService = useDependency(LocaleService);const [settings, setSettings] = useState<IPageSettings>(() => ({- paperSize: getPaperSize(documentStyle.pageSize!),- pageSise: {+ mode: documentStyle.documentFlavor === DocumentFlavor.TRADITIONAL ? DocumentFlavor.TRADITIONAL : DocumentFlavor.MODERN,+ modernWidth: getModernWidthMode(documentStyle.pageSize),+ paperSize: getPaperSize(documentStyle.pageSize ?? PAGE_SIZE.A4),+ pageSize: {width: documentStyle.pageSize?.width ?? 0,height: documentStyle.pageSize?.height ?? 0,},@@ -78,6 +117,7 @@ export function PageSettings(props: IConfirmChildrenProps) {}));useEffect(() => {+ // eslint-disable-next-line react-hooks/immutabilityhooks.beforeClose = () => {return settings;};@@ -88,15 +128,7 @@ export function PageSettings(props: IConfirmChildrenProps) {}, [settings]);const handlePaperSizeChange = (value: string) => {- setSettings((prev) => ({ ...prev, paperSize: value, pageSise: PAGE_SIZE[value as PaperType] }));- };-- const handleOrientationChange = (value: PageOrientType) => {- setSettings((prev) => ({- ...prev,- orientation: value,- pageSise: { width: settings.pageSise.height, height: settings.pageSise.width },- }));+ setSettings((prev) => ({ ...prev, paperSize: value, pageSize: PAGE_SIZE[value as PaperType] }));};const handleMarginChange = (position: keyof IPageSettings['margins'], value: number | null) => {@@ -109,91 +141,138 @@ export function PageSettings(props: IConfirmChildrenProps) {}));};+ const handleModeChange = (mode: IPageSettings['mode']) => {+ setSettings((prev) => ({ ...prev, mode }));+ };++ const handleModernWidthChange = (modernWidth: ModernDocumentWidthMode) => {+ setSettings((prev) => ({ ...prev, modernWidth }));+ };+return (<div className="univer-flex univer-flex-col univer-gap-4">- <div className="univer-flex univer-flex-col univer-gap-2">- <label- className={`- univer-text-sm univer-font-medium univer-text-gray-900- dark:!univer-text-white- `}- >- {localeService.t('docs-ui.page-settings.paper-size')}- </label>- <Select- value={settings.paperSize}- onChange={handlePaperSizeChange}- options={PAPER_TYPES.map((p) => ({- label: localeService.t(`docs-ui.page-settings.page-size.${p.toLocaleLowerCase()}`),- value: p,- }))}- />+ <div+ className="+ univer-grid univer-grid-cols-2 univer-rounded-lg univer-bg-gray-100 univer-p-1+ dark:!univer-bg-gray-800+ "+ >+ {([DocumentFlavor.MODERN, DocumentFlavor.TRADITIONAL] as const).map((mode) => (+ <button+ key={mode}+ type="button"+ className={clsx(`+ univer-h-8 univer-cursor-pointer univer-rounded-md univer-border-none univer-bg-transparent+ univer-text-sm univer-font-medium univer-text-gray-600 univer-transition-colors+ hover:univer-bg-white hover:univer-text-gray-900+ dark:!univer-text-gray-200+ dark:hover:!univer-bg-gray-700+ `, {+ 'univer-bg-white univer-text-gray-900 univer-shadow-sm dark:!univer-bg-gray-700 dark:!univer-text-white': settings.mode === mode,+ })}+ onClick={() => handleModeChange(mode)}+ >+ {localeService.t(mode === DocumentFlavor.MODERN ? 'page-settings.modern-mode' : 'page-settings.classic-mode')}+ </button>+ ))}</div>- <div className="univer-flex univer-flex-col univer-gap-2">- <label- className={`- univer-text-sm univer-font-medium univer-text-gray-900- dark:!univer-text-white- `}- >- {localeService.t('docs-ui.page-settings.custom-paper-size')}- </label>- <div className="univer-flex univer-flex-col univer-gap-2.5">- <div className="univer-flex univer-gap-2.5">- <div className="univer-flex univer-flex-1 univer-flex-col univer-gap-2">- <label className="univer-text-sm univer-font-medium univer-text-gray-500">- {localeService.t('docs-ui.page-settings.top')}- </label>- <InputNumber- precision={2}- min={0}- max={settings.pageSise.height / 2}- value={settings.margins.top}- onChange={(e) => handleMarginChange('top', e)}- />- </div>- <div className="univer-flex univer-flex-1 univer-flex-col univer-gap-2">- <label className="univer-text-sm univer-font-medium univer-text-gray-500">- {localeService.t('docs-ui.page-settings.bottom')}- </label>- <InputNumber- precision={2}- min={0}- max={settings.pageSise.height / 2}- value={settings.margins.bottom}- onChange={(e) => handleMarginChange('bottom', e)}- />+ {settings.mode === DocumentFlavor.MODERN+ ? (+ <div className="univer-flex univer-flex-col univer-gap-2.5">+ <SettingsLabel>{localeService.t('page-settings.modern-width')}</SettingsLabel>+ <div className="univer-grid univer-grid-cols-3 univer-gap-2">+ {MODERN_WIDTH_OPTIONS.map((option) => (+ <button+ key={option}+ type="button"+ className={clsx(`+ univer-flex univer-h-16 univer-cursor-pointer univer-flex-col univer-items-center+ univer-justify-center univer-gap-1 univer-rounded-lg univer-border+ univer-border-solid univer-border-gray-200 univer-bg-white univer-text-sm+ univer-font-medium univer-text-gray-700 univer-transition-colors+ hover:univer-border-primary-500 hover:univer-text-primary-600+ dark:!univer-border-gray-600 dark:!univer-bg-gray-900 dark:!univer-text-gray-100+ `, {+ '!univer-border-primary-500 !univer-bg-primary-50 !univer-text-primary-600 dark:!univer-bg-primary-900': settings.modernWidth === option,+ })}+ onClick={() => handleModernWidthChange(option)}+ >+ <span>{localeService.t(`page-settings.modern-width-${option}`)}</span>+ <span className="univer-text-xs univer-font-normal univer-text-gray-400">+ {MODERN_DOCUMENT_WIDTH[option]}+ px+ </span>+ </button>+ ))}</div></div>- <div className="univer-flex univer-gap-2.5">- <div className="univer-flex univer-flex-1 univer-flex-col univer-gap-2">- <label className="univer-text-sm univer-font-medium univer-text-gray-500">- {localeService.t('docs-ui.page-settings.left')}- </label>- <InputNumber- precision={2}- min={0}- max={settings.pageSise.width / 2}- value={settings.margins.left}- onChange={(e) => handleMarginChange('left', e)}+ )+ : (+ <>+ <div className="univer-flex univer-flex-col univer-gap-2">+ <SettingsLabel>{localeService.t('page-settings.paper-size')}</SettingsLabel>+ <Select+ value={settings.paperSize}+ onChange={handlePaperSizeChange}+ options={PAPER_TYPES.map((p) => ({+ label: localeService.t(`page-settings.page-size.${p.toLocaleLowerCase()}`),+ value: p,+ }))}/></div>- <div className="univer-flex univer-flex-1 univer-flex-col univer-gap-2">- <label className="univer-text-sm univer-font-medium univer-text-gray-500">- {localeService.t('docs-ui.page-settings.right')}- </label>- <InputNumber- precision={2}- min={0}- max={settings.pageSise.width / 2}- value={settings.margins.right}- onChange={(e) => handleMarginChange('right', e)}- />++ <div className="univer-flex univer-flex-col univer-gap-2">+ <SettingsLabel>{localeService.t('page-settings.custom-paper-size')}</SettingsLabel>+ <div className="univer-flex univer-flex-col univer-gap-2.5">+ <div className="univer-flex univer-gap-2.5">+ <div className="univer-flex univer-flex-1 univer-flex-col univer-gap-2">+ <SettingsLabel muted>{localeService.t('page-settings.top')}</SettingsLabel>+ <InputNumber+ precision={2}+ min={0}+ max={settings.pageSize.height / 2}+ value={settings.margins.top}+ onChange={(e) => handleMarginChange('top', e)}+ />+ </div>+ <div className="univer-flex univer-flex-1 univer-flex-col univer-gap-2">+ <SettingsLabel muted>{localeService.t('page-settings.bottom')}</SettingsLabel>+ <InputNumber+ precision={2}+ min={0}+ max={settings.pageSize.height / 2}+ value={settings.margins.bottom}+ onChange={(e) => handleMarginChange('bottom', e)}+ />+ </div>+ </div>+ <div className="univer-flex univer-gap-2.5">+ <div className="univer-flex univer-flex-1 univer-flex-col univer-gap-2">+ <SettingsLabel muted>{localeService.t('page-settings.left')}</SettingsLabel>+ <InputNumber+ precision={2}+ min={0}+ max={settings.pageSize.width / 2}+ value={settings.margins.left}+ onChange={(e) => handleMarginChange('left', e)}+ />+ </div>+ <div className="univer-flex univer-flex-1 univer-flex-col univer-gap-2">+ <SettingsLabel muted>{localeService.t('page-settings.right')}</SettingsLabel>+ <InputNumber+ precision={2}+ min={0}+ max={settings.pageSize.width / 2}+ value={settings.margins.right}+ onChange={(e) => handleMarginChange('right', e)}+ />+ </div>+ </div>+ </div></div>- </div>- </div>- </div>+ </>+ )}</div>);}diff --git a/packages/docs-ui/src/views/paragraph-setting/Setting.tsx b/packages/docs-ui/src/views/paragraph-setting/Setting.tsxindex 9cf552fc86..2d3de04bcd 100644--- a/packages/docs-ui/src/views/paragraph-setting/Setting.tsx+++ b/packages/docs-ui/src/views/paragraph-setting/Setting.tsx@@ -14,6 +14,7 @@* limitations under the License.*/+import type { ReactNode } from 'react';import { HorizontalAlign, LocaleService, SpacingRule } from '@univerjs/core';import { borderClassName, clsx, InputNumber, Select, Tooltip } from '@univerjs/design';import { AlignTextBothIcon, HorizontallyIcon, LeftJustifyingIcon, RightJustifyingIcon } from '@univerjs/icons';@@ -31,6 +32,49 @@ import {useFirstParagraphSpaceBelow,} from './hook/utils';+const PARAGRAPH_SETTING_CONTROL_CLASS = 'univer-w-full';++const ParagraphSettingSection = (props: {+ title: ReactNode;+ children: ReactNode;+ first?: boolean;+}) => {+ const { title, children, first = false } = props;++ return (+ <section className={clsx(!first && 'univer-mt-5')}>+ <div className="univer-text-sm univer-font-medium univer-leading-5">{title}</div>+ <div className="univer-mt-3">{children}</div>+ </section>+ );+};++const ParagraphSettingRow = (props: {+ label: ReactNode;+ children: ReactNode;+}) => {+ const { label, children } = props;++ return (+ <div+ className="univer-grid univer-min-h-8 univer-items-center univer-gap-3"+ style={{ gridTemplateColumns: 'minmax(0, 1fr) minmax(160px, 180px)' }}+ >+ <div+ className="+ univer-min-w-0 univer-text-xs univer-leading-5 univer-text-gray-900+ dark:!univer-text-gray-100+ "+ >+ {label}+ </div>+ <div className="univer-w-full univer-min-w-0">+ {children}+ </div>+ </div>+ );+};+const AutoFocusInputNumber = (props: {value: number;onChange: (v: number) => Promise<unknown>;@@ -38,12 +82,14 @@ const AutoFocusInputNumber = (props: {min?: number;max?: number;step?: number;+ precision?: number;}) => {- const { value, onChange, className = '', min = 0, max = 100, step = 1 } = props;+ const { value, onChange, className = '', min = 0, max = 100, step = 0.1, precision = 1 } = props;const ref = useRef<HTMLInputElement>(null);return (<InputNumberstep={step}+ precision={precision}ref={ref}min={min}max={max}@@ -58,7 +104,7 @@ const AutoFocusInputNumber = (props: {}, 30);});}}- className={className}+ className={clsx(PARAGRAPH_SETTING_CONTROL_CLASS, className)}/>);};@@ -87,114 +133,98 @@ export function ParagraphSetting() {const lineSpaceConfig = useMemo(() => {if (spacingRule === SpacingRule.AUTO) {- return { min: 1, max: 5, step: lineSpacing < 2 ? 0.5 : 1 };+ return { min: 1, max: 5, step: 0.1 };}return { min: 1, max: 100 };- }, [spacingRule, lineSpacing]);+ }, [spacingRule]);return (- <div>- <div className="univer-t-4 univer-text-sm univer-font-medium">{localeService.t('docs-ui.doc.paragraphSetting.alignment')}</div>- <div- className={clsx(`- univer-mt-4 univer-box-border univer-flex univer-w-full univer-items-center univer-justify-between- univer-gap-1 univer-rounded-md univer-p-1- `, borderClassName)}- >- {alignmentOptions.map((item) => {- return (- <Tooltip title={item.label} key={item.value} placement="bottom">- <span- className={clsx(`- hover:univer-bg-black/60- univer-flex univer-cursor-pointer univer-items-center univer-justify-center- univer-rounded univer-bg-none univer-px-3 univer-py-1- `, {- 'univer-bg-gray-200 dark:!univer-bg-gray-500': horizontalAlignValue === item.value,- })}- onClick={() => setHorizontalAlign(item.value)}- >- {item.icon}- </span>- </Tooltip>-- );- })}- </div>- <div className="univer-t-4 univer-text-sm univer-font-medium">{localeService.t('docs-ui.doc.paragraphSetting.indentation')}</div>- <div>- <div className="univer-item-center univer-flex univer-justify-between">- <div className="univer-mt-3 univer-text-xs">- {localeService.t('docs-ui.doc.paragraphSetting.left')}- (px)- </div>- <AutoFocusInputNumber className="univer-mt-4" value={indentStart} onChange={(v) => setIndentStart(v ?? 0)} />- </div>- <div className="univer-item-center univer-flex univer-justify-between">-- <div className="univer-mt-3 univer-text-xs">- {localeService.t('docs-ui.doc.paragraphSetting.right')}- (px)- </div>- <AutoFocusInputNumber className="univer-mt-4" value={indentEnd} onChange={(v) => setIndentEnd(v ?? 0)} />- </div>- <div className="univer-item-center univer-flex univer-justify-between">-- <div className="univer-mt-3 univer-text-xs">- {localeService.t('docs-ui.doc.paragraphSetting.firstLine')}- (px)- </div>- <AutoFocusInputNumber className="univer-mt-4" value={indentFirstLine} onChange={(v) => setIndentFirstLine(v ?? 0)} />- </div>- <div className="univer-item-center univer-flex univer-justify-between">-- <div className="univer-mt-3 univer-text-xs">- {localeService.t('docs-ui.doc.paragraphSetting.hanging')}- (px)- </div>- <AutoFocusInputNumber className="univer-mt-4" value={hanging} onChange={(v) => setHanging(v ?? 0)} />- </div>- </div>- <div className="univer-t-4 univer-text-sm univer-font-medium">{localeService.t('docs-ui.doc.paragraphSetting.spacing')}</div>- <div>- <div className="univer-justify-betweenuniver-item-center univer-flex">-- <div className="univer-mt-3 univer-text-xs">- {localeService.t('docs-ui.doc.paragraphSetting.before')}- (px)- </div>- <AutoFocusInputNumber className="univer-mt-4" value={spaceAbove} onChange={(v) => setSpaceAbove(v ?? 0)} />+ <div className="univer-box-border univer-w-full">+ <ParagraphSettingSection title={localeService.t('docs-ui.doc.paragraphSetting.alignment')} first>+ <div+ className={clsx(`+ univer-grid univer-h-10 univer-grid-cols-4 univer-items-stretch univer-gap-1 univer-rounded-lg+ univer-bg-white univer-p-1+ dark:!univer-bg-gray-900+ `, borderClassName)}+ >+ {alignmentOptions.map((item) => {+ return (+ <Tooltip title={item.label} key={item.value} placement="bottom">+ <button+ type="button"+ className={clsx(`+ univer-flex univer-h-full univer-w-full univer-cursor-pointer univer-items-center+ univer-justify-center univer-rounded-md univer-border-none univer-bg-transparent+ univer-p-0 univer-text-gray-900 univer-transition-colors+ hover:univer-bg-gray-100+ dark:!univer-text-gray-100+ dark:hover:!univer-bg-gray-700+ `, {+ 'univer-bg-gray-200 dark:!univer-bg-gray-700': horizontalAlignValue === item.value,+ })}+ onClick={() => setHorizontalAlign(item.value)}+ >+ <span+ className="+ univer-flex univer-size-5 univer-items-center univer-justify-center+ univer-text-lg+ "+ >+ {item.icon}+ </span>+ </button>+ </Tooltip>+ );+ })}</div>- <div className="univer-item-center univer-flex univer-justify-between">-- <div className="univer-mt-3 univer-text-xs">- {localeService.t('docs-ui.doc.paragraphSetting.after')}- (px)- </div>- <AutoFocusInputNumber className="univer-mt-4" value={spaceBelow} onChange={(v) => setSpaceBelow(v ?? 0)} />+ </ParagraphSettingSection>++ <ParagraphSettingSection title={localeService.t('docs-ui.doc.paragraphSetting.indentation')}>+ <div className="univer-grid univer-gap-3">+ <ParagraphSettingRow label={`${localeService.t('docs-ui.doc.paragraphSetting.left')}(px)`}>+ <AutoFocusInputNumber value={indentStart} onChange={(v) => setIndentStart(v ?? 0)} />+ </ParagraphSettingRow>+ <ParagraphSettingRow label={`${localeService.t('docs-ui.doc.paragraphSetting.right')}(px)`}>+ <AutoFocusInputNumber value={indentEnd} onChange={(v) => setIndentEnd(v ?? 0)} />+ </ParagraphSettingRow>+ <ParagraphSettingRow label={`${localeService.t('docs-ui.doc.paragraphSetting.firstLine')}(px)`}>+ <AutoFocusInputNumber value={indentFirstLine} onChange={(v) => setIndentFirstLine(v ?? 0)} />+ </ParagraphSettingRow>+ <ParagraphSettingRow label={`${localeService.t('docs-ui.doc.paragraphSetting.hanging')}(px)`}>+ <AutoFocusInputNumber value={hanging} onChange={(v) => setHanging(v ?? 0)} />+ </ParagraphSettingRow></div>- <div className="item-center univer-flex univer-justify-between">- <div className="univer-mt-3 univer-text-xs">{localeService.t('docs-ui.doc.paragraphSetting.lineSpace')}</div>- <div- className="univer-mt-4 univer-flex univer-w-[162px] univer-flex-col univer-gap-1.5"- >- <Select- value={`${spacingRule}`}- options={[- { label: localeService.t('docs-ui.doc.paragraphSetting.multiSpace'), value: `${SpacingRule.AUTO}` },- { label: localeService.t('docs-ui.doc.paragraphSetting.fixedValue'), value: `${SpacingRule.AT_LEAST}` },- ]}- onChange={(v) => setSpacingRule(Number(v))}- />- <AutoFocusInputNumber- {...lineSpaceConfig}- value={lineSpacing}- onChange={(v) => setLineSpacing(v ?? 0)}- />- </div>-+ </ParagraphSettingSection>++ <ParagraphSettingSection title={localeService.t('docs-ui.doc.paragraphSetting.spacing')}>+ <div className="univer-grid univer-gap-3">+ <ParagraphSettingRow label={`${localeService.t('docs-ui.doc.paragraphSetting.before')}(px)`}>+ <AutoFocusInputNumber value={spaceAbove} onChange={(v) => setSpaceAbove(v ?? 0)} />+ </ParagraphSettingRow>+ <ParagraphSettingRow label={`${localeService.t('docs-ui.doc.paragraphSetting.after')}(px)`}>+ <AutoFocusInputNumber value={spaceBelow} onChange={(v) => setSpaceBelow(v ?? 0)} />+ </ParagraphSettingRow>+ <ParagraphSettingRow label={localeService.t('docs-ui.doc.paragraphSetting.lineSpace')}>+ <div className="univer-flex univer-w-full univer-flex-col univer-gap-2">+ <Select+ className={PARAGRAPH_SETTING_CONTROL_CLASS}+ value={`${spacingRule}`}+ options={[+ { label: localeService.t('docs-ui.doc.paragraphSetting.multiSpace'), value: `${SpacingRule.AUTO}` },+ { label: localeService.t('docs-ui.doc.paragraphSetting.fixedValue'), value: `${SpacingRule.AT_LEAST}` },+ ]}+ onChange={(v) => setSpacingRule(Number(v))}+ />+ <AutoFocusInputNumber+ {...lineSpaceConfig}+ value={lineSpacing}+ onChange={(v) => setLineSpacing(v ?? 0)}+ />+ </div>+ </ParagraphSettingRow></div>- </div>+ </ParagraphSettingSection></div>);}diff --git a/packages/docs-ui/src/views/paragraph-setting/hook/utils.ts b/packages/docs-ui/src/views/paragraph-setting/hook/utils.tsindex a9be380aca..557fc764d3 100644--- a/packages/docs-ui/src/views/paragraph-setting/hook/utils.ts+++ b/packages/docs-ui/src/views/paragraph-setting/hook/utils.ts@@ -16,7 +16,7 @@import type { DocumentDataModel, IParagraph, ISectionBreak } from '@univerjs/core';import type { IDocParagraphSettingCommandParams } from '../../../commands/commands/doc-paragraph-setting.command';-import { BuildTextUtils, ICommandService, IUniverInstanceService, SpacingRule, UniverInstanceType } from '@univerjs/core';+import { BuildTextUtils, DEFAULT_DOCUMENT_PARAGRAPH_LINE_SPACING, DEFAULT_DOCUMENT_PARAGRAPH_SPACE_ABOVE, DEFAULT_DOCUMENT_PARAGRAPH_SPACE_BELOW, ICommandService, IUniverInstanceService, SpacingRule, UniverInstanceType } from '@univerjs/core';import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';import { getNumberUnitValue, IRenderManagerService } from '@univerjs/engine-render';import { useDependency } from '@univerjs/ui';@@ -200,7 +200,7 @@ export const useFirstParagraphIndentSpaceAbove = (paragraph: IParagraph[]) => {if (!firstParagraph) {return 0;}- return getNumberUnitValue(firstParagraph.paragraphStyle?.spaceAbove, 0);+ return getNumberUnitValue(firstParagraph.paragraphStyle?.spaceAbove, DEFAULT_DOCUMENT_PARAGRAPH_SPACE_ABOVE);});const setSpaceAbove = (v: number) => {setSpaceAboveInternal(v);@@ -219,7 +219,7 @@ export const useFirstParagraphSpaceBelow = (paragraph: IParagraph[]) => {if (!firstParagraph) {return 0;}- return getNumberUnitValue(firstParagraph.paragraphStyle?.spaceBelow, 0);+ return getNumberUnitValue(firstParagraph.paragraphStyle?.spaceBelow, DEFAULT_DOCUMENT_PARAGRAPH_SPACE_BELOW);});const setSpaceBelow = (v: number) => {setSpaceBelowInternal(v);@@ -249,9 +249,9 @@ export const useFirstParagraphLineSpacing = (paragraph: IParagraph[]) => {const [lineSpacing, setLineSpacingInternal] = useState(() => {const firstParagraph = paragraph[0];if (!firstParagraph) {- return 1;+ return 1.5;}- return firstParagraph.paragraphStyle?.lineSpacing ?? 1;+ return firstParagraph.paragraphStyle?.lineSpacing ?? DEFAULT_DOCUMENT_PARAGRAPH_LINE_SPACING;});const lineSpacingCache = useRef<number>(lineSpacing);diff --git a/packages/docs-ui/src/views/rich-text-editor/hooks/use-editor.ts b/packages/docs-ui/src/views/rich-text-editor/hooks/use-editor.tsindex 1b4b42f435..35d1f36175 100644--- a/packages/docs-ui/src/views/rich-text-editor/hooks/use-editor.ts+++ b/packages/docs-ui/src/views/rich-text-editor/hooks/use-editor.ts@@ -16,7 +16,7 @@import type { IDocumentData, Nullable } from '@univerjs/core';import type { RefObject } from 'react';-import type { Editor } from '../../../services/editor/editor';+import type { Editor, IEditorCanvasStyle } from '../../../services/editor/editor';import { Tools } from '@univerjs/core';import { useDependency } from '@univerjs/ui';import { useLayoutEffect, useMemo, useState } from 'react';@@ -28,10 +28,11 @@ export interface IUseEditorProps {container: RefObject<HTMLDivElement>;autoFocus?: boolean;isSingle?: boolean;+ canvasStyle?: IEditorCanvasStyle;}export function useEditor(opts: IUseEditorProps) {- const { editorId, initialValue, container, autoFocus: _autoFocus, isSingle } = opts;+ const { editorId, initialValue, container, autoFocus: _autoFocus, isSingle, canvasStyle } = opts;const autoFocus = useMemo(() => _autoFocus ?? false, []);const [editor, setEditor] = useState<Editor>();const editorService = useDependency(IEditorService);@@ -63,6 +64,7 @@ export function useEditor(opts: IUseEditorProps) {const dispose = editorService.register({autofocus: true,+ canvasStyle,editorUnitId: editorId,initialSnapshot: snapshot,},diff --git a/packages/drawing-ui/src/views/image-popup-menu/ImagePopupMenu.tsx b/packages/drawing-ui/src/views/image-popup-menu/ImagePopupMenu.tsxindex f065a07d9a..6304111014 100644--- a/packages/drawing-ui/src/views/image-popup-menu/ImagePopupMenu.tsx+++ b/packages/drawing-ui/src/views/image-popup-menu/ImagePopupMenu.tsx@@ -14,10 +14,11 @@* limitations under the License.*/-import type { IDrawingSearch } from '@univerjs/core';-import { ICommandService, LocaleService } from '@univerjs/core';-import { borderClassName, clsx, DropdownMenu } from '@univerjs/design';-import { AutofillDoubleIcon, MoreDownIcon } from '@univerjs/icons';+import type { DocumentDataModel } from '@univerjs/core';+import type * as React from 'react';+import { BooleanNumber, ICommandService, IUniverInstanceService, LocaleService, PositionedObjectLayoutType, UniverInstanceType } from '@univerjs/core';+import { borderClassName, clsx, Dropdown, DropdownMenu, Tooltip } from '@univerjs/design';+import { AutofillDoubleIcon, DeleteIcon, DocSettingIcon, MoreDownIcon } from '@univerjs/icons';import { useDependency } from '@univerjs/ui';import { useState } from 'react';@@ -25,12 +26,16 @@ export interface IImagePopupMenuItem {label: string;index: number;commandId: string;- commandParams?: IDrawingSearch[];+ commandParams?: object;disable: boolean;}export interface IImagePopupMenuExtraProps {menuItems: IImagePopupMenuItem[];+ variant?: 'doc-floating-toolbar';+ unitId?: string;+ subUnitId?: string;+ drawingId?: string;}export interface IImagePopupMenuProps {@@ -46,6 +51,22 @@ export function ImagePopupMenu(props: IImagePopupMenuProps) {if (!menuItems) return null;+ if (+ popup.extraProps?.variant === 'doc-floating-toolbar' &&+ popup.extraProps.unitId &&+ popup.extraProps.subUnitId &&+ popup.extraProps.drawingId+ ) {+ return (+ <DocImageFloatingToolbar+ menuItems={menuItems}+ unitId={popup.extraProps.unitId}+ subUnitId={popup.extraProps.subUnitId}+ drawingId={popup.extraProps.drawingId}+ />+ );+ }+const commandService = useDependency(ICommandService);const localeService = useDependency(LocaleService);@@ -109,3 +130,282 @@ export function ImagePopupMenu(props: IImagePopupMenuProps) {</div>);};++const UPDATE_DOC_DRAWING_WRAPPING_STYLE_COMMAND_ID = 'doc.command.update-doc-drawing-wrapping-style';++enum TextWrappingStyle {+ INLINE = 'inline',+ BEHIND_TEXT = 'behindText',+ IN_FRONT_OF_TEXT = 'inFrontOfText',+ WRAP_SQUARE = 'wrapSquare',+ WRAP_TOP_AND_BOTTOM = 'wrapTopAndBottom',+}++interface IDocImageFloatingToolbarProps {+ menuItems: IImagePopupMenuItem[];+ unitId: string;+ subUnitId: string;+ drawingId: string;+}++interface IToolbarDropdownOption<T extends string | number> {+ label: string;+ value: T;+ icon: React.ReactNode;+}++function getWrappingStyle(documentDataModel: DocumentDataModel | undefined, drawingId: string): TextWrappingStyle {+ const drawing = documentDataModel?.getSnapshot().drawings?.[drawingId];+ if (!drawing) {+ return TextWrappingStyle.INLINE;+ }++ if (drawing.layoutType === PositionedObjectLayoutType.WRAP_NONE) {+ return drawing.behindDoc === BooleanNumber.TRUE ? TextWrappingStyle.BEHIND_TEXT : TextWrappingStyle.IN_FRONT_OF_TEXT;+ }++ if (drawing.layoutType === PositionedObjectLayoutType.WRAP_SQUARE) {+ return TextWrappingStyle.WRAP_SQUARE;+ }++ if (drawing.layoutType === PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM) {+ return TextWrappingStyle.WRAP_TOP_AND_BOTTOM;+ }++ return TextWrappingStyle.INLINE;+}++function Divider() {+ return (+ <span+ className="+ univer-h-5 univer-w-px univer-bg-gray-200+ dark:!univer-bg-gray-700+ "+ />+ );+}++function ToolbarGroup(props: { children: React.ReactNode }) {+ return (+ <div className="univer-flex univer-h-7 univer-items-center univer-gap-1 univer-px-1">+ {props.children}+ </div>+ );+}++function ToolbarButton(props: { title: string; active?: boolean; disabled?: boolean; children: React.ReactNode; onClick: () => void }) {+ return (+ <Tooltip title={props.title} placement="bottom">+ <button+ type="button"+ disabled={props.disabled}+ onClick={props.onClick}+ className={clsx(`+ univer-flex univer-h-6 univer-w-6 univer-items-center univer-justify-center univer-rounded-md+ univer-border-none univer-bg-transparent univer-p-0 univer-text-sm univer-text-gray-700+ univer-transition-colors+ hover:univer-bg-gray-100+ disabled:univer-cursor-not-allowed disabled:univer-opacity-40+ dark:!univer-text-gray-100+ dark:hover:!univer-bg-gray-700+ `, {+ 'univer-bg-gray-100 univer-text-primary-600 dark:!univer-bg-gray-700 dark:!univer-text-primary-300': props.active,+ })}+ >+ {props.children}+ </button>+ </Tooltip>+ );+}++function TextWrapShapeIcon() {+ return (+ <svg viewBox="0 0 20 20" width="1em" height="1em" fill="none" aria-hidden="true">+ <path d="M2.5 4.5H8.2" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" />+ <path d="M11.8 4.5H17.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" />+ <path d="M2.5 10H5.7" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" />+ <path d="M14.3 10H17.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" />+ <path d="M2.5 15.5H8.2" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" />+ <path d="M11.8 15.5H17.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" />+ <rect x="6.8" y="7" width="6.4" height="6" rx="1" stroke="currentColor" strokeWidth="1.4" />+ </svg>+ );+}++function CropIcon() {+ return (+ <svg viewBox="0 0 20 20" width="1em" height="1em" fill="none" aria-hidden="true">+ <path d="M5 2.8V12.5C5 13.9 6.1 15 7.5 15H17.2" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />+ <path d="M2.8 5H12.5C13.9 5 15 6.1 15 7.5V17.2" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />+ <path d="M8.3 8.3H11.7V11.7H8.3V8.3Z" stroke="currentColor" strokeWidth="1.2" />+ </svg>+ );+}++function ToolbarDropdownButton<T extends string | number>(props: {+ title: string;+ value: T;+ options: Array<IToolbarDropdownOption<T>>;+ onChange: (value: T) => void;+}) {+ const [open, setOpen] = useState(false);+ const activeOption = props.options.find((option) => option.value === props.value) ?? props.options[0];++ return (+ <Dropdown+ open={open}+ onOpenChange={setOpen}+ overlay={(+ <div+ className={`+ univer-min-w-32 univer-rounded-lg univer-border univer-border-solid univer-border-gray-200+ univer-bg-white univer-p-1 univer-shadow-lg+ dark:!univer-border-gray-700 dark:!univer-bg-gray-900+ `}+ >+ {props.options.map((option) => (+ <button+ key={option.value}+ type="button"+ onClick={() => {+ props.onChange(option.value);+ setOpen(false);+ }}+ className={clsx(`+ univer-flex univer-h-8 univer-w-full univer-items-center univer-gap-2 univer-rounded-md+ univer-border-none univer-bg-transparent univer-px-2 univer-text-left univer-text-sm+ univer-text-gray-700 univer-transition-colors+ hover:univer-bg-gray-100+ dark:!univer-text-gray-100+ dark:hover:!univer-bg-gray-800+ `, {+ 'univer-bg-primary-50 univer-text-primary-600 dark:!univer-bg-gray-800 dark:!univer-text-primary-300': option.value === props.value,+ })}+ >+ <span className="univer-flex univer-size-4 univer-items-center univer-justify-center">{option.icon}</span>+ <span className="univer-flex-1">{option.label}</span>+ </button>+ ))}+ </div>+ )}+ >+ <span>+ <Tooltip title={props.title} placement="bottom">+ <button+ type="button"+ className={clsx(`+ univer-flex univer-h-6 univer-min-w-9 univer-items-center univer-justify-center univer-gap-1+ univer-rounded-md univer-border-none univer-bg-transparent univer-px-1.5 univer-text-sm+ univer-text-gray-700 univer-transition-colors+ hover:univer-bg-gray-100+ dark:!univer-text-gray-100+ dark:hover:!univer-bg-gray-700+ `, {+ 'univer-bg-gray-100 univer-text-primary-600 dark:!univer-bg-gray-700 dark:!univer-text-primary-300': open,+ })}+ >+ {activeOption.icon}+ <MoreDownIcon className="univer-text-xs" />+ </button>+ </Tooltip>+ </span>+ </Dropdown>+ );+}++function DocImageFloatingToolbar(props: IDocImageFloatingToolbarProps) {+ const commandService = useDependency(ICommandService);+ const localeService = useDependency(LocaleService);+ const univerInstanceService = useDependency(IUniverInstanceService);+ const documentDataModel = univerInstanceService.getUnit<DocumentDataModel>(props.unitId, UniverInstanceType.UNIVER_DOC) ?? undefined;+ const [wrappingStyle, setWrappingStyle] = useState(() => getWrappingStyle(documentDataModel, props.drawingId));+ const [hidden, setHidden] = useState(false);++ const getMenuItem = (label: string) => props.menuItems.find((item) => item.label === label);+ const editItem = getMenuItem('image-popup.edit');+ const cropItem = getMenuItem('image-popup.crop');+ const deleteItem = getMenuItem('image-popup.delete');+ const wrappingStyleOptions = [+ { label: localeService.t('image-text-wrap.inline'), value: TextWrappingStyle.INLINE, icon: <TextWrapShapeIcon /> },+ { label: localeService.t('image-text-wrap.square'), value: TextWrappingStyle.WRAP_SQUARE, icon: <TextWrapShapeIcon /> },+ { label: localeService.t('image-text-wrap.topAndBottom'), value: TextWrappingStyle.WRAP_TOP_AND_BOTTOM, icon: <TextWrapShapeIcon /> },+ { label: localeService.t('image-text-wrap.behindText'), value: TextWrappingStyle.BEHIND_TEXT, icon: <TextWrapShapeIcon /> },+ { label: localeService.t('image-text-wrap.inFrontText'), value: TextWrappingStyle.IN_FRONT_OF_TEXT, icon: <TextWrapShapeIcon /> },+ ];++ const executeMenuItem = (item: IImagePopupMenuItem | undefined) => {+ if (!item || item.disable) {+ return;+ }+ commandService.executeCommand(item.commandId, item.commandParams);+ };++ const updateWrappingStyle = (value: TextWrappingStyle) => {+ setWrappingStyle(value);+ commandService.executeCommand(UPDATE_DOC_DRAWING_WRAPPING_STYLE_COMMAND_ID, {+ unitId: props.unitId,+ subUnitId: props.subUnitId,+ drawings: [{ unitId: props.unitId, subUnitId: props.subUnitId, drawingId: props.drawingId }],+ wrappingStyle: value,+ });+ };++ if (hidden) {+ return null;+ }++ return (+ <div+ data-u-comp="doc-image-floating-toolbar"+ onMouseDown={(event) => {+ event.stopPropagation();+ event.preventDefault();+ }}+ className={clsx(`+ univer-box-border univer-flex univer-items-center univer-rounded univer-bg-white univer-px-1 univer-py-1+ univer-shadow-sm+ dark:!univer-border-gray-700 dark:!univer-bg-gray-900+ `, borderClassName)}+ >+ <ToolbarGroup>+ <ToolbarDropdownButton+ title={wrappingStyleOptions.find((option) => option.value === wrappingStyle)?.label ?? localeService.t('image-text-wrap.inline')}+ value={wrappingStyle}+ options={wrappingStyleOptions}+ onChange={updateWrappingStyle}+ />+ </ToolbarGroup>+ <Divider />+ <ToolbarGroup>+ <ToolbarButton+ title={editItem ? localeService.t(editItem.label) : localeService.t('image-popup.edit')}+ disabled={!editItem || editItem.disable}+ onClick={() => {+ setHidden(true);+ executeMenuItem(editItem);+ }}+ >+ <DocSettingIcon />+ </ToolbarButton>+ <ToolbarButton+ title={cropItem ? localeService.t(cropItem.label) : localeService.t('image-popup.crop')}+ disabled={!cropItem || cropItem.disable}+ onClick={() => executeMenuItem(cropItem)}+ >+ <CropIcon />+ </ToolbarButton>+ </ToolbarGroup>+ <Divider />+ <ToolbarGroup>+ <ToolbarButton+ title={deleteItem ? localeService.t(deleteItem.label) : localeService.t('image-popup.delete')}+ disabled={!deleteItem || deleteItem.disable}+ onClick={() => executeMenuItem(deleteItem)}+ >+ <DeleteIcon />+ </ToolbarButton>+ </ToolbarGroup>+ </div>+ );+}diff --git a/packages/engine-render/src/__tests__/engine-scene-viewport.spec.ts b/packages/engine-render/src/__tests__/engine-scene-viewport.spec.tsindex 05d00da3e8..49badccc39 100644--- a/packages/engine-render/src/__tests__/engine-scene-viewport.spec.ts+++ b/packages/engine-render/src/__tests__/engine-scene-viewport.spec.ts@@ -142,6 +142,99 @@ describe('engine scene viewport extra', () => {document.body.innerHTML = '';});+ it('keeps wheel scrolling visually consistent when the scene is scaled', () => {+ const getViewportWheelDelta = (scale: number) => {+ const container = document.createElement('div');+ document.body.appendChild(container);++ const engine = new Engine('unit-wheel', { elementWidth: 320, elementHeight: 180, dpr: 1 });+ engine.mount(container, false);++ const scene = new Scene('scene-wheel', engine);+ scene.transformByState({+ width: 700,+ height: 500,+ scaleX: 1,+ scaleY: 1,+ });++ const viewport = new Viewport('doc-like-vp', scene, {+ left: 0,+ top: 0,+ right: 0,+ bottom: 0,+ active: true,+ });++ new ScrollBar(viewport);+ scene.scale(scale, scale);+ viewport.resetCanvasSizeAndUpdateScroll();++ viewport.onMouseWheel(+ createInputEvent('wheel', { deltaY: 60 }),+ { stopPropagation: vi.fn() } as any+ );++ const delta = viewport.viewportScrollY;+ scene.dispose();+ engine.dispose();+ container.remove();++ return delta;+ };++ const normalScaleDelta = getViewportWheelDelta(1);+ const doubleScaleDelta = getViewportWheelDelta(2);++ expect(doubleScaleDelta * 2).toBeCloseTo(normalScaleDelta, 3);+ });++ it('locks out minor cross-axis wheel jitter in viewport scrolling', () => {+ const { engine, scene, viewport, container } = createFixture();+ viewport.scrollToViewportPos({ viewportScrollX: 20, viewportScrollY: 20 });++ viewport.onMouseWheel(+ createInputEvent('wheel', { deltaX: 8, deltaY: 20 }),+ { stopPropagation: vi.fn() } as any+ );+ expect(viewport.viewportScrollX).toBeCloseTo(20, 3);+ expect(viewport.viewportScrollY).toBeGreaterThan(20);++ viewport.onMouseWheel(+ createInputEvent('wheel', { deltaX: 20, deltaY: 8 }),+ { stopPropagation: vi.fn() } as any+ );+ expect(viewport.viewportScrollX).toBeGreaterThan(20);++ scene.dispose();+ engine.dispose();+ container.remove();+ });++ it('locks vertical wheel jitter by raw delta before doc scrollbar scaling', () => {+ const { engine, scene, viewport, container } = createFixture();+ scene.transformByState({+ width: 700,+ height: 2400,+ scaleX: 1,+ scaleY: 1,+ });+ viewport.resetCanvasSizeAndUpdateScroll();+ viewport.scrollToViewportPos({ viewportScrollX: 20, viewportScrollY: 20 });++ viewport.onMouseWheel(+ createInputEvent('wheel', { deltaX: 8, deltaY: 20 }),+ { stopPropagation: vi.fn() } as any+ );++ expect(viewport.viewportScrollX).toBeCloseTo(20, 3);+ expect(viewport.viewportScrollY).toBeGreaterThan(20);++ scene.dispose();+ engine.dispose();+ container.remove();+ });+it('covers scene, viewport, layer and render loop flows', () => {const { engine, scene, viewport, container } = createFixture();diff --git a/packages/engine-render/src/basics/__tests__/tools.spec.ts b/packages/engine-render/src/basics/__tests__/tools.spec.tsindex 9a1a71d4bd..272359f23b 100644--- a/packages/engine-render/src/basics/__tests__/tools.spec.ts+++ b/packages/engine-render/src/basics/__tests__/tools.spec.ts@@ -173,6 +173,13 @@ describe('tools extra', () => {expect(subscript.fontFamily).toBe('"Open Sans"');expect(subscript.fontSize).toBeCloseTo(6);+ const fontStack = getFontStyleString({+ fs: 12,+ ff: '"SF Mono", "Cascadia Code", Consolas, monospace',+ } as any);+ expect(fontStack.fontFamily).toBe('"SF Mono", "Cascadia Code", Consolas, monospace');+ expect(fontStack.fontString).toContain('"SF Mono", "Cascadia Code", Consolas, monospace');+const superscript = getFontStyleString({fs: 12,ff: 'Arial',diff --git a/packages/engine-render/src/basics/__tests__/zoom.spec.ts b/packages/engine-render/src/basics/__tests__/zoom.spec.tsnew file mode 100644index 0000000000..fef381c08e--- /dev/null+++ b/packages/engine-render/src/basics/__tests__/zoom.spec.ts@@ -0,0 +1,51 @@+/**+ * 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 { describe, expect, it } from 'vitest';+import { EventConstants } from '../i-events';+import { getNextWheelZoomRatio } from '../zoom';++describe('wheel zoom helpers', () => {+ it('uses small trackpad deltas proportionally instead of a fixed large zoom step', () => {+ expect(getNextWheelZoomRatio(1, {+ deltaMode: EventConstants.DOM_DELTA_PIXEL,+ deltaX: 0,+ deltaY: -4,+ })).toBe(1.03);+ });++ it('caps large wheel deltas and clamps zoom boundaries', () => {+ expect(getNextWheelZoomRatio(1, {+ deltaMode: EventConstants.DOM_DELTA_PIXEL,+ deltaX: 0,+ deltaY: -1000,+ })).toBe(1.14);++ expect(getNextWheelZoomRatio(4, {+ deltaMode: EventConstants.DOM_DELTA_PIXEL,+ deltaX: 0,+ deltaY: -1000,+ })).toBe(4);+ });++ it('normalizes line-mode wheel events', () => {+ expect(getNextWheelZoomRatio(1, {+ deltaMode: EventConstants.DOM_DELTA_LINE,+ deltaX: 0,+ deltaY: 3,+ })).toBe(0.86);+ });+});diff --git a/packages/engine-render/src/basics/index.ts b/packages/engine-render/src/basics/index.tsindex 14bc0c9db9..2ef84cb2ed 100644--- a/packages/engine-render/src/basics/index.ts+++ b/packages/engine-render/src/basics/index.ts@@ -31,3 +31,4 @@ export * from './text-rotation';export * from './tools';export * from './transform';export * from './vector2';+export * from './zoom';diff --git a/packages/engine-render/src/basics/tools.ts b/packages/engine-render/src/basics/tools.tsindex 791ff94ee5..fedece7a28 100644--- a/packages/engine-render/src/basics/tools.ts+++ b/packages/engine-render/src/basics/tools.ts@@ -245,7 +245,6 @@ export function fixLineWidthByScale(num: number, scale: number) {return Math.round(num * scale) / scale;}-// eslint-disable-next-line max-lines-per-functionexport function getFontStyleString(textStyle?: Nullable<IStyleBase>): IDocumentSkeletonFontStyle {@@ -287,26 +286,7 @@ export function getFontStyleString(}let fontSize = originFontSize;- let fontFamilyResult = defaultFont;- if (textStyle.ff) {- let fontFamily = textStyle.ff;-- fontFamily = fontFamily.replace(/"/g, '').replace(/'/g, '');-- if (fontFamily.indexOf(' ') > -1) {- fontFamily = `"${fontFamily}"`;- }-- // if (fontFamily != null && document.fonts && !document.fonts.check('12px ' + fontFamily)) {- // menuButton.addFontToList(fontFamily);- // }-- if (fontFamily == null) {- fontFamily = defaultFont;- }-- fontFamilyResult = fontFamily;- }+ const fontFamilyResult = normalizeFontFamily(textStyle.ff, defaultFont);const { va: baselineOffset } = textStyle;@@ -333,6 +313,21 @@ export function getFontStyleString(};}+function normalizeFontFamily(fontFamily: Nullable<string>, defaultFont: string): string {+ if (!fontFamily?.trim()) {+ return defaultFont;+ }++ return fontFamily+ .split(',')+ .map((item) => {+ const family = item.trim().replace(/^['"]|['"]$/g, '');+ return family.includes(' ') ? `"${family}"` : family;+ })+ .filter(Boolean)+ .join(', ');+}+// Whether it contains CJK characters, excluding symbolsconst CJK_LETTER_REG = cjk.letters().toRegExp();export function hasCJKText(text: string) {diff --git a/packages/engine-render/src/basics/zoom.ts b/packages/engine-render/src/basics/zoom.tsnew file mode 100644index 0000000000..28a98abde7--- /dev/null+++ b/packages/engine-render/src/basics/zoom.ts@@ -0,0 +1,64 @@+/**+ * 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 { IWheelEvent } from './i-events';+import { EventConstants } from './i-events';++const MIN_ZOOM_RATIO = 0.1;+const MAX_ZOOM_RATIO = 4;+const PIXEL_DELTA_TO_ZOOM_RATIO = 0.008;+const MAX_WHEEL_ZOOM_STEP = 0.14;+const MAX_WHEEL_ZOOM_STEP_BELOW_ONE = 0.07;+const LINE_DELTA_PIXEL_SIZE = 16;+const PAGE_DELTA_PIXEL_SIZE = 800;+const ZOOM_RATIO_PRECISION = 100;++function clamp(value: number, min: number, max: number): number {+ return Math.min(max, Math.max(min, value));+}++function normalizeWheelDelta(event: Pick<IWheelEvent, 'deltaMode' | 'deltaX' | 'deltaY' | 'wheelDelta'>): number {+ const deltaY = Number.isFinite(event.deltaY) ? event.deltaY : 0;+ const deltaX = Number.isFinite(event.deltaX) ? event.deltaX : 0;+ let delta = Math.abs(deltaY) >= Math.abs(deltaX) ? deltaY : deltaX;++ if (delta === 0 && typeof event.wheelDelta === 'number') {+ delta = -event.wheelDelta / 3;+ }++ if (event.deltaMode === EventConstants.DOM_DELTA_LINE) {+ delta *= LINE_DELTA_PIXEL_SIZE;+ } else if (event.deltaMode === EventConstants.DOM_DELTA_PAGE) {+ delta *= PAGE_DELTA_PIXEL_SIZE;+ }++ return delta;+}++export function getNextWheelZoomRatio(currentRatio: number, event: Pick<IWheelEvent, 'deltaMode' | 'deltaX' | 'deltaY' | 'wheelDelta'>): number {+ const validCurrentRatio = Number.isFinite(currentRatio) ? currentRatio : 1;++ const normalizedDelta = normalizeWheelDelta(event);+ if (normalizedDelta === 0) {+ return clamp(validCurrentRatio, MIN_ZOOM_RATIO, MAX_ZOOM_RATIO);+ }++ const maxStep = validCurrentRatio < 1 ? MAX_WHEEL_ZOOM_STEP_BELOW_ONE : MAX_WHEEL_ZOOM_STEP;+ const ratioDelta = clamp(-normalizedDelta * PIXEL_DELTA_TO_ZOOM_RATIO, -maxStep, maxStep);+ const nextRatio = Math.round((validCurrentRatio + ratioDelta) * ZOOM_RATIO_PRECISION) / ZOOM_RATIO_PRECISION;++ return clamp(nextRatio, MIN_ZOOM_RATIO, MAX_ZOOM_RATIO);+}diff --git a/packages/engine-render/src/components/docs/__tests__/document.spec.ts b/packages/engine-render/src/components/docs/__tests__/document.spec.tsindex 2c223eec62..ffe8fa6378 100644--- a/packages/engine-render/src/components/docs/__tests__/document.spec.ts+++ b/packages/engine-render/src/components/docs/__tests__/document.spec.ts@@ -14,15 +14,19 @@* limitations under the License.*/+import { DocumentFlavor } from '@univerjs/core';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { setupRenderTestEnv } from '../../../__tests__/render-test-utils';import { DocumentSkeletonPageType, GlyphType, LineType, PageLayoutType } from '../../../basics/i-document-skeleton-cached';import { Canvas } from '../../../canvas';import { Engine } from '../../../engine';import { MAIN_VIEW_PORT_KEY, Scene } from '../../../scene';+import { Path, Rect } from '../../../shape';import { Viewport } from '../../../viewport';+import { DocBackground } from '../doc-background';import { DOCS_EXTENSION_TYPE } from '../doc-extension';import { Documents } from '../document';+import { setDocsTableRenderViewportProvider } from '../table-render-viewport';function createGlyph(content: string, left: number, width = 16) {return {@@ -274,6 +278,593 @@ describe('documents render', () => {container.remove();document.body.innerHTML = '';vi.restoreAllMocks();+ setDocsTableRenderViewportProvider(null);+ });++ it('uses explicit table cell border width and skips no-border markers', () => {+ const skeleton = { getSkeletonData: () => ({ pages: [] }) } as any;+ const documents = new Documents('docs-border', skeleton, {+ pageLayoutType: PageLayoutType.VERTICAL,+ pageMarginLeft: 0,+ pageMarginTop: 0,+ });+ const cell = createPage(DocumentSkeletonPageType.CELL, 'cell-seg');+ cell.marginLeft = 0;+ cell.marginTop = 0;+ cell.pageWidth = 120;+ cell.pageHeight = 60;+ const row = {+ cells: [cell],+ rowSource: {+ tableCells: [{+ borderTop: { color: { rgb: '#ff0000' }, width: { v: 5 } },+ borderBottom: { color: { rgb: 'transparent' }, width: { v: 0 } },+ borderLeft: { color: { rgb: 'transparent' }, width: { v: 0 } },+ borderRight: { color: { rgb: 'transparent' }, width: { v: 0 } },+ }],+ },+ } as any;+ cell.parent = row;+ (documents as any)._drawLiquid = { x: 0, y: 0 };++ const lineWidths: number[] = [];+ const strokeStyles: string[] = [];+ const ctx = {+ save: vi.fn(),+ restore: vi.fn(),+ fillRectByPrecision: vi.fn(),+ setLineWidthByPrecision: vi.fn((width: number) => lineWidths.push(width)),+ beginPath: vi.fn(),+ moveToByPrecision: vi.fn(),+ lineToByPrecision: vi.fn(),+ setLineDash: vi.fn(),+ stroke: vi.fn(),+ closePathByEnv: vi.fn(),+ set strokeStyle(value: string) {+ strokeStyles.push(value);+ },+ } as any;++ (documents as any)._drawTableCellBordersAndBg(ctx, { marginLeft: 0, marginTop: 0 }, cell);++ expect(lineWidths).toEqual([5]);+ expect(strokeStyles).toEqual(['#ff0000']);+ expect(ctx.stroke).toHaveBeenCalledTimes(1);++ documents.dispose();+ });++ it('draws a docs workspace background behind traditional pages', () => {+ const page = createPage(DocumentSkeletonPageType.BODY, '');+ const skeleton = {+ getSkeletonData: () => ({ pages: [page] }),+ getViewModel: () => ({+ getDataModel: () => ({+ getSnapshot: () => ({+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ },+ }),+ }),+ }),+ } as any;+ const docBackground = new DocBackground('docs-background', skeleton, {+ pageLayoutType: PageLayoutType.VERTICAL,+ pageMarginLeft: 20,+ pageMarginTop: 20,+ });+ docBackground.resize(260, 480);++ const rectDraw = vi.spyOn(Rect, 'drawWith').mockImplementation(() => {});+ vi.spyOn(Path, 'drawWith').mockImplementation(() => {});++ const translate = vi.fn();+ docBackground.draw({+ restore: vi.fn(),+ save: vi.fn(),+ translate,+ } as any, {+ viewBound: { left: 100, top: 50, right: 700, bottom: 450 },+ cacheBound: { left: 80, top: 30, right: 760, bottom: 490 },+ } as any);++ expect(rectDraw.mock.calls.map(([, props]) => props.fill)).toEqual([+ '#fafafa',+ 'rgba(255, 255, 255, 1)',+ ]);+ expect(rectDraw.mock.calls[0][1]).toMatchObject({+ width: 680,+ height: 460,+ fill: '#fafafa',+ });+ expect(translate.mock.calls[0]).toEqual([80, 30]);++ docBackground.dispose();+ });++ it('treats unspecified document flavor as traditional when drawing the page background', () => {+ const page = createPage(DocumentSkeletonPageType.BODY, '');+ const skeleton = {+ getSkeletonData: () => ({ pages: [page] }),+ getViewModel: () => ({+ getDataModel: () => ({+ getSnapshot: () => ({+ documentStyle: {+ documentFlavor: DocumentFlavor.UNSPECIFIED,+ },+ }),+ }),+ }),+ } as any;+ const docBackground = new DocBackground('docs-background-unspecified', skeleton, {+ pageLayoutType: PageLayoutType.VERTICAL,+ pageMarginLeft: 20,+ pageMarginTop: 20,+ });+ docBackground.resize(260, 480);++ const rectDraw = vi.spyOn(Rect, 'drawWith').mockImplementation(() => {});+ vi.spyOn(Path, 'drawWith').mockImplementation(() => {});++ docBackground.draw({+ restore: vi.fn(),+ save: vi.fn(),+ translate: vi.fn(),+ } as any);++ expect(rectDraw.mock.calls.map(([, props]) => props.fill)).toEqual([+ '#fafafa',+ 'rgba(255, 255, 255, 1)',+ ]);++ docBackground.dispose();+ });++ it('draws the docs workspace background for modern documents', () => {+ const page = createPage(DocumentSkeletonPageType.BODY, '');+ const skeleton = {+ getSkeletonData: () => ({ pages: [page] }),+ getViewModel: () => ({+ getDataModel: () => ({+ getSnapshot: () => ({+ documentStyle: {+ documentFlavor: DocumentFlavor.MODERN,+ },+ }),+ }),+ }),+ } as any;+ const docBackground = new DocBackground('docs-background-modern', skeleton, {+ pageLayoutType: PageLayoutType.VERTICAL,+ pageMarginLeft: 20,+ pageMarginTop: 20,+ });+ docBackground.resize(260, 480);++ const rectDraw = vi.spyOn(Rect, 'drawWith').mockImplementation(() => {});+ vi.spyOn(Path, 'drawWith').mockImplementation(() => {});++ const translate = vi.fn();+ docBackground.draw({+ restore: vi.fn(),+ save: vi.fn(),+ translate,+ } as any, {+ viewBound: { left: 120, top: 60, right: 640, bottom: 420 },+ cacheBound: { left: 90, top: 40, right: 700, bottom: 480 },+ } as any);++ expect(rectDraw.mock.calls.map(([, props]) => props.fill)).toEqual(['rgba(255, 255, 255, 1)']);+ expect(rectDraw.mock.calls[0][1]).toMatchObject({+ width: 610,+ height: 440,+ fill: 'rgba(255, 255, 255, 1)',+ });+ expect(translate.mock.calls[0]).toEqual([90, 40]);++ docBackground.dispose();+ });++ it('uses configured transparent fills for embedded editor backgrounds', () => {+ const page = createPage(DocumentSkeletonPageType.BODY, '');+ const skeleton = {+ getSkeletonData: () => ({ pages: [page] }),+ getViewModel: () => ({+ getDataModel: () => ({+ getSnapshot: () => ({+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ },+ }),+ }),+ }),+ } as any;+ const docBackground = new DocBackground('docs-background-editor', skeleton, {+ pageLayoutType: PageLayoutType.VERTICAL,+ pageMarginLeft: 20,+ pageMarginTop: 20,+ backgroundFillColor: 'transparent',+ pageFillColor: 'transparent',+ pageStrokeColor: 'transparent',+ marginStrokeColor: 'transparent',+ });+ docBackground.resize(260, 480);++ const rectDraw = vi.spyOn(Rect, 'drawWith').mockImplementation(() => {});+ vi.spyOn(Path, 'drawWith').mockImplementation(() => {});++ docBackground.draw({+ restore: vi.fn(),+ save: vi.fn(),+ translate: vi.fn(),+ } as any);++ expect(rectDraw.mock.calls.map(([, props]) => props.fill)).toEqual([+ 'transparent',+ 'transparent',+ ]);+ expect(rectDraw.mock.calls[1][1].stroke).toBe('transparent');+ expect((Path.drawWith as any).mock.calls[0][1].stroke).toBe('transparent');++ docBackground.dispose();+ });++ it('draws unspecified table borders with the default table grid color', () => {+ const skeleton = { getSkeletonData: () => ({ pages: [] }) } as any;+ const documents = new Documents('docs-border-default', skeleton, {+ pageLayoutType: PageLayoutType.VERTICAL,+ pageMarginLeft: 0,+ pageMarginTop: 0,+ });+ const cell = createPage(DocumentSkeletonPageType.CELL, 'cell-seg');+ cell.marginLeft = 0;+ cell.marginTop = 0;+ cell.pageWidth = 120;+ cell.pageHeight = 60;+ const row = {+ cells: [cell],+ rowSource: {+ tableCells: [{}],+ },+ } as any;+ cell.parent = row;+ (documents as any)._drawLiquid = { x: 0, y: 0 };++ const strokeStyles: string[] = [];+ const ctx = {+ save: vi.fn(),+ restore: vi.fn(),+ fillRectByPrecision: vi.fn(),+ setLineWidthByPrecision: vi.fn(),+ beginPath: vi.fn(),+ moveToByPrecision: vi.fn(),+ lineToByPrecision: vi.fn(),+ setLineDash: vi.fn(),+ stroke: vi.fn(),+ closePathByEnv: vi.fn(),+ set strokeStyle(value: string) {+ strokeStyles.push(value);+ },+ } as any;++ (documents as any)._drawTableCellBordersAndBg(ctx, { marginLeft: 0, marginTop: 0 }, cell);++ expect(strokeStyles).toEqual(['#c7c9cc', '#c7c9cc', '#c7c9cc', '#c7c9cc']);++ documents.dispose();+ });++ it('draws each physical table grid line only once', () => {+ const skeleton = { getSkeletonData: () => ({ pages: [] }) } as any;+ const documents = new Documents('docs-border-canonical', skeleton, {+ pageLayoutType: PageLayoutType.VERTICAL,+ pageMarginLeft: 0,+ pageMarginTop: 0,+ });+ const cells = Array.from({ length: 4 }, (_, index) => {+ const cell = createPage(DocumentSkeletonPageType.CELL, `cell-${index}`);+ cell.marginLeft = 0;+ cell.marginTop = 0;+ cell.pageWidth = 50;+ cell.pageHeight = 30;+ return cell;+ });+ const row0 = {+ cells: [cells[0], cells[1]],+ index: 0,+ rowSource: { tableCells: [{}, {}] },+ } as any;+ const row1 = {+ cells: [cells[2], cells[3]],+ index: 1,+ rowSource: { tableCells: [{}, {}] },+ } as any;+ const table = { rows: [row0, row1] } as any;+ row0.parent = table;+ row1.parent = table;+ cells[0].parent = row0;+ cells[1].parent = row0;+ cells[2].parent = row1;+ cells[3].parent = row1;++ let currentSegment = '';+ const drawnSegments: string[] = [];+ const ctx = {+ save: vi.fn(),+ restore: vi.fn(),+ fillRectByPrecision: vi.fn(),+ setLineWidthByPrecision: vi.fn(),+ beginPath: vi.fn(),+ moveToByPrecision: vi.fn((x: number, y: number) => {+ currentSegment = `${x},${y}`;+ }),+ lineToByPrecision: vi.fn((x: number, y: number) => {+ currentSegment += `-${x},${y}`;+ drawnSegments.push(currentSegment);+ }),+ setLineDash: vi.fn(),+ stroke: vi.fn(),+ closePathByEnv: vi.fn(),+ set strokeStyle(_value: string) {},+ } as any;++ [+ { cell: cells[0], x: 0, y: 0 },+ { cell: cells[1], x: 50, y: 0 },+ { cell: cells[2], x: 0, y: 30 },+ { cell: cells[3], x: 50, y: 30 },+ ].forEach(({ cell, x, y }) => {+ (documents as any)._drawLiquid = { x, y };+ (documents as any)._drawTableCellBordersAndBg(ctx, { marginLeft: 0, marginTop: 0 }, cell);+ });++ expect(ctx.stroke).toHaveBeenCalledTimes(12);+ expect(new Set(drawnSegments).size).toBe(12);++ documents.dispose();+ });++ it('uses neighboring table cell borders for internal canonical edges', () => {+ const skeleton = { getSkeletonData: () => ({ pages: [] }) } as any;+ const documents = new Documents('docs-border-neighbor', skeleton, {+ pageLayoutType: PageLayoutType.VERTICAL,+ pageMarginLeft: 0,+ pageMarginTop: 0,+ });+ const cells = Array.from({ length: 2 }, (_, index) => {+ const cell = createPage(DocumentSkeletonPageType.CELL, `neighbor-cell-${index}`);+ cell.marginLeft = 0;+ cell.marginTop = 0;+ cell.pageWidth = 50;+ cell.pageHeight = 30;+ return cell;+ });+ const noBorder = { color: { rgb: 'transparent' }, width: { v: 0 } };+ const row = {+ cells,+ index: 0,+ rowSource: {+ tableCells: [+ {+ borderTop: noBorder,+ borderBottom: noBorder,+ borderLeft: noBorder,+ },+ {+ borderTop: noBorder,+ borderBottom: noBorder,+ borderLeft: { color: { rgb: '#ff0000' }, width: { v: 3 } },+ borderRight: noBorder,+ },+ ],+ },+ } as any;+ const table = { rows: [row] } as any;+ row.parent = table;+ cells[0].parent = row;+ cells[1].parent = row;++ const strokeStyles: string[] = [];+ const lineWidths: number[] = [];+ const ctx = {+ save: vi.fn(),+ restore: vi.fn(),+ fillRectByPrecision: vi.fn(),+ setLineWidthByPrecision: vi.fn((width: number) => lineWidths.push(width)),+ beginPath: vi.fn(),+ moveToByPrecision: vi.fn(),+ lineToByPrecision: vi.fn(),+ setLineDash: vi.fn(),+ stroke: vi.fn(),+ closePathByEnv: vi.fn(),+ set strokeStyle(value: string) {+ strokeStyles.push(value);+ },+ } as any;++ [+ { cell: cells[0], x: 0 },+ { cell: cells[1], x: 50 },+ ].forEach(({ cell, x }) => {+ (documents as any)._drawLiquid = { x, y: 0 };+ (documents as any)._drawTableCellBordersAndBg(ctx, { marginLeft: 0, marginTop: 0 }, cell);+ });++ expect(ctx.stroke).toHaveBeenCalledTimes(1);+ expect(lineWidths).toEqual([3]);+ expect(strokeStyles).toEqual(['#ff0000']);++ documents.dispose();+ });++ it('uses the document unit id to apply table horizontal viewport while drawing', () => {+ const bodyPage = createPage(DocumentSkeletonPageType.BODY, '');+ attachTable(bodyPage);++ const skeleton = {+ getViewModel: () => ({+ getDataModel: () => ({+ getUnitId: () => 'doc-unit-1',+ }),+ }),+ } as any;+ const documents = new Documents('not-the-unit-id', skeleton, {+ pageLayoutType: PageLayoutType.VERTICAL,+ pageMarginLeft: 0,+ pageMarginTop: 0,+ });++ const queriedUnitIds: string[] = [];+ setDocsTableRenderViewportProvider((unitId, tableId) => {+ queriedUnitIds.push(`${unitId}:${tableId}`);+ if (unitId !== 'doc-unit-1' || tableId !== 'table-1') {+ return null;+ }++ return {+ contentWidth: 240,+ scrollLeft: 80,+ viewportWidth: 120,+ };+ });++ const ctx = {+ save: vi.fn(),+ restore: vi.fn(),+ beginPath: vi.fn(),+ rectByPrecision: vi.fn(),+ closePath: vi.fn(),+ clip: vi.fn(),+ } as any;++ const translateCalls: Array<[number | undefined, number | undefined]> = [];+ const liquid = (documents as any)._drawLiquid;+ vi.spyOn(liquid, 'translate').mockImplementation((...args: unknown[]) => {+ const [x, y] = args as [number | undefined, number | undefined];+ translateCalls.push([x, y]);+ liquid.translateBy(liquid.x + (x ?? 0), liquid.y + (y ?? 0));+ });+ vi.spyOn(documents as any, '_drawTableCell').mockImplementation(() => {});++ (documents as any)._drawTable(+ ctx,+ bodyPage,+ bodyPage.skeTables,+ [],+ null,+ [],+ {} as any,+ 0,+ 0,+ {},+ { scaleX: 1, scaleY: 1 }+ );++ expect(queriedUnitIds).toEqual(['doc-unit-1:table-1']);+ expect(ctx.clip).toHaveBeenCalledTimes(1);+ expect(ctx.rectByPrecision).toHaveBeenCalledWith(20, 30, 124, 64);+ expect(translateCalls).toContainEqual([-80, 0]);++ documents.dispose();+ });++ it('clips oversized tables on first render before a table viewport state exists', () => {+ const bodyPage = createPage(DocumentSkeletonPageType.BODY, '');+ attachTable(bodyPage);+ const table = bodyPage.skeTables.get('table-1')!;+ table.width = 260;+ table.rows[0].cells[0].pageWidth = 260;++ const documents = new Documents('docs-main', {+ getSkeletonData: () => ({ pages: [bodyPage] }),+ } as any, {+ pageLayoutType: PageLayoutType.VERTICAL,+ pageMarginLeft: 0,+ pageMarginTop: 0,+ });++ const ctx = {+ save: vi.fn(),+ restore: vi.fn(),+ beginPath: vi.fn(),+ rectByPrecision: vi.fn(),+ closePath: vi.fn(),+ clip: vi.fn(),+ } as any;++ vi.spyOn(documents as any, '_drawTableCell').mockImplementation(() => {});++ (documents as any)._drawTable(+ ctx,+ bodyPage,+ bodyPage.skeTables,+ [],+ null,+ [],+ {} as any,+ 0,+ 0,+ {},+ { scaleX: 1, scaleY: 1 }+ );++ expect(ctx.clip).toHaveBeenCalledTimes(1);+ expect(ctx.rectByPrecision).toHaveBeenCalledWith(20, 30, 172, 64);++ documents.dispose();+ });++ it('uses explicit table cell border width and skips no-border markers', () => {+ const skeleton = { getSkeletonData: () => ({ pages: [] }) } as any;+ const documents = new Documents('docs-border', skeleton, {+ pageLayoutType: PageLayoutType.VERTICAL,+ pageMarginLeft: 0,+ pageMarginTop: 0,+ });+ const cell = createPage(DocumentSkeletonPageType.CELL, 'cell-seg');+ cell.marginLeft = 0;+ cell.marginTop = 0;+ cell.pageWidth = 120;+ cell.pageHeight = 60;+ const row = {+ cells: [cell],+ rowSource: {+ tableCells: [{+ borderTop: { color: { rgb: '#ff0000' }, width: { v: 5 } },+ borderBottom: { color: { rgb: 'transparent' }, width: { v: 0 } },+ borderLeft: { color: { rgb: 'transparent' }, width: { v: 0 } },+ borderRight: { color: { rgb: 'transparent' }, width: { v: 0 } },+ }],+ },+ } as any;+ cell.parent = row;+ (documents as any)._drawLiquid = { x: 0, y: 0 };++ const lineWidths: number[] = [];+ const strokeStyles: string[] = [];+ const ctx = {+ save: vi.fn(),+ restore: vi.fn(),+ fillRectByPrecision: vi.fn(),+ setLineWidthByPrecision: vi.fn((width: number) => lineWidths.push(width)),+ beginPath: vi.fn(),+ moveToByPrecision: vi.fn(),+ lineToByPrecision: vi.fn(),+ setLineDash: vi.fn(),+ stroke: vi.fn(),+ closePathByEnv: vi.fn(),+ set strokeStyle(value: string) {+ strokeStyles.push(value);+ },+ } as any;++ (documents as any)._drawTableCellBordersAndBg(ctx, { marginLeft: 0, marginTop: 0 }, cell);++ expect(lineWidths).toEqual([5]);+ expect(strokeStyles).toEqual(['#ff0000']);+ expect(ctx.stroke).toHaveBeenCalledTimes(1);++ documents.dispose();});it('draws body/header/footer/table flows with extension dispatch and page events', () => {diff --git a/packages/engine-render/src/components/docs/doc-background.ts b/packages/engine-render/src/components/docs/doc-background.tsindex 4ef64a8f9c..2a76b77a6d 100644--- a/packages/engine-render/src/components/docs/doc-background.ts+++ b/packages/engine-render/src/components/docs/doc-background.ts@@ -26,15 +26,24 @@ import { Liquid } from './liquid';const PAGE_STROKE_COLOR = 'rgba(198, 198, 198, 1)';const PAGE_FILL_COLOR = 'rgba(255, 255, 255, 1)';+const DOCS_WORKSPACE_FILL_COLOR = '#fafafa';const MARGIN_STROKE_COLOR = 'rgba(158, 158, 158, 1)';export class DocBackground extends DocComponent {private _drawLiquid: Liquid;+ private _backgroundFillColor?: string;+ private _pageFillColor?: string;+ private _pageStrokeColor?: string;+ private _marginStrokeColor?: string;constructor(oKey: string, documentSkeleton?: DocumentSkeleton, config?: IDocumentsConfig) {super(oKey, documentSkeleton, config);this._drawLiquid = new Liquid();+ this._backgroundFillColor = config?.backgroundFillColor;+ this._pageFillColor = config?.pageFillColor;+ this._pageStrokeColor = config?.pageStrokeColor;+ this._marginStrokeColor = config?.marginStrokeColor;this.makeDirty(true);}@@ -43,6 +52,23 @@ export class DocBackground extends DocComponent {return new DocBackground(oKey, documentSkeleton, config);}+ setFillColors(backgroundFillColor?: string, pageFillColor?: string, pageStrokeColor?: string, marginStrokeColor?: string) {+ if (+ this._backgroundFillColor === backgroundFillColor &&+ this._pageFillColor === pageFillColor &&+ this._pageStrokeColor === pageStrokeColor &&+ this._marginStrokeColor === marginStrokeColor+ ) {+ return;+ }++ this._backgroundFillColor = backgroundFillColor;+ this._pageFillColor = pageFillColor;+ this._pageStrokeColor = pageStrokeColor;+ this._marginStrokeColor = marginStrokeColor;+ this.makeDirty(true);+ }+override draw(ctx: UniverRenderingContext, bounds?: IViewportInfo) {const skeletonData = this.getSkeleton()?.getSkeletonData();const docDataModel = this.getSkeleton()?.getViewModel().getDataModel();@@ -53,7 +79,10 @@ export class DocBackground extends DocComponent {const { documentFlavor } = docDataModel.getSnapshot().documentStyle;- if (documentFlavor !== DocumentFlavor.TRADITIONAL) {+ const workspaceFill = this._backgroundFillColor ?? (documentFlavor === DocumentFlavor.MODERN ? PAGE_FILL_COLOR : DOCS_WORKSPACE_FILL_COLOR);+ this._drawWorkspaceBackground(ctx, workspaceFill, bounds);++ if (documentFlavor === DocumentFlavor.MODERN) {return;}@@ -90,8 +119,8 @@ export class DocBackground extends DocComponent {width: pageWidth ?? width,height: pageHeight ?? height,strokeWidth: 1,- stroke: PAGE_STROKE_COLOR,- fill: PAGE_FILL_COLOR,+ stroke: this._pageStrokeColor ?? PAGE_STROKE_COLOR,+ fill: this._pageFillColor ?? PAGE_FILL_COLOR,zIndex: 3,};@@ -137,7 +166,7 @@ export class DocBackground extends DocComponent {points: [pageWidth - marginRight, pageHeight - originMarginBottom + IDENTIFIER_WIDTH],}] as unknown as IPathProps['dataArray'],strokeWidth: 1.5,- stroke: MARGIN_STROKE_COLOR,+ stroke: this._marginStrokeColor ?? MARGIN_STROKE_COLOR,};Path.drawWith(ctx, marginIdentification);ctx.restore();@@ -154,6 +183,28 @@ export class DocBackground extends DocComponent {}}+ private _drawWorkspaceBackground(ctx: UniverRenderingContext, fill: string, bounds?: IViewportInfo) {+ const visibleBound = bounds?.cacheBound ?? bounds?.viewBound;+ const left = visibleBound?.left ?? 0;+ const top = visibleBound?.top ?? 0;+ const width = visibleBound == null ? this.width : visibleBound.right - visibleBound.left;+ const height = visibleBound == null ? this.height : visibleBound.bottom - visibleBound.top;++ if (width <= 0 || height <= 0) {+ return;+ }++ ctx.save();+ ctx.translate(left, top);+ Rect.drawWith(ctx, {+ width,+ height,+ fill,+ zIndex: 0,+ });+ ctx.restore();+ }+changeSkeleton(newSkeleton: DocumentSkeleton) {this.setSkeleton(newSkeleton);diff --git a/packages/engine-render/src/components/docs/doc-component.ts b/packages/engine-render/src/components/docs/doc-component.tsindex ff4980349c..84aa0a16eb 100644--- a/packages/engine-render/src/components/docs/doc-component.ts+++ b/packages/engine-render/src/components/docs/doc-component.ts@@ -31,6 +31,10 @@ export interface IPageMarginLayout {export interface IDocumentsConfig extends IPageMarginLayout {hasEditor?: boolean;+ backgroundFillColor?: string;+ pageFillColor?: string;+ pageStrokeColor?: string;+ marginStrokeColor?: string;}export abstract class DocComponent extends RenderComponent<diff --git a/packages/engine-render/src/components/docs/document.ts b/packages/engine-render/src/components/docs/document.tsindex 4663ad1147..d386bfa6b1 100644--- a/packages/engine-render/src/components/docs/document.ts+++ b/packages/engine-render/src/components/docs/document.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { IDocumentRenderConfig, IScale, ITableCellBorder, Nullable } from '@univerjs/core';+import type { IDocumentRenderConfig, IScale, ITableCell, ITableCellBorder, Nullable } from '@univerjs/core';import type { IDocumentSkeletonGlyph, IDocumentSkeletonLine, IDocumentSkeletonPage, IDocumentSkeletonRow, IDocumentSkeletonTable } from '../../basics/i-document-skeleton-cached';import type { Transform } from '../../basics/transform';@@ -24,7 +24,8 @@ import type { Scene } from '../../scene';import type { ComponentExtension, IDrawInfo, IExtensionConfig } from '../extension';import type { IDocumentsConfig, IPageMarginLayout } from './doc-component';import type { DocumentSkeleton } from './layout/doc-skeleton';-import { CellValueType, HorizontalAlign, VerticalAlign, WrapStrategy } from '@univerjs/core';+import type { IDocsTableRenderViewport } from './table-render-viewport';+import { CellValueType, DashStyleType, HorizontalAlign, VerticalAlign, WrapStrategy } from '@univerjs/core';import { Subject } from 'rxjs';import { BORDER_TYPE as BORDER_LTRB, drawLineByBorderType } from '../../basics';import { calculateRectRotate, getRotateOffsetAndFarthestHypotenuse } from '../../basics/draw';@@ -35,14 +36,17 @@ import { Vector2 } from '../../basics/vector2';import { DocumentsSpanAndLineExtensionRegistry } from '../extension';import { DocComponent } from './doc-component';import { DOCS_EXTENSION_TYPE } from './doc-extension';+import { getTableIdAndSliceIndex } from './layout/block/table';import { Liquid } from './liquid';+import { getDocsTableRenderViewport } from './table-render-viewport';import './extensions';const DEFAULT_BORDER_COLOR: ITableCellBorder = {color: {- rgb: '#dee0e3',+ rgb: '#c7c9cc',},};+const TABLE_VIEWPORT_BORDER_CLIP_PADDING = 2;export interface IPageRenderConfig {page: IDocumentSkeletonPage;@@ -520,20 +524,48 @@ export class Documents extends DocComponent {renderConfig: IDocumentRenderConfig,parentScale: IScale) {- for (const [_tableId, tableSkeleton] of skeTables) {+ const drawLiquid = this._drawLiquid;+ if (drawLiquid == null) {+ return;+ }++ const renderUnitId = this._getRenderUnitId();++ for (const [tableId, tableSkeleton] of skeTables) {const { top: tableTop, left: tableLeft, rows } = tableSkeleton;- this._drawLiquid?.translateSave();- this._drawLiquid?.translate(tableLeft, tableTop);+ const sourceTableId = getTableIdAndSliceIndex(tableId).tableId;+ const viewport = this._getTableViewport(page, tableSkeleton, renderUnitId, sourceTableId);+ drawLiquid.translateSave();+ drawLiquid.translate(tableLeft, tableTop);++ if (viewport && viewport.contentWidth > viewport.viewportWidth) {+ const { x, y } = drawLiquid;+ ctx.save();+ ctx.beginPath();+ ctx.rectByPrecision(+ x + page.marginLeft - TABLE_VIEWPORT_BORDER_CLIP_PADDING,+ y + page.marginTop - TABLE_VIEWPORT_BORDER_CLIP_PADDING,+ viewport.viewportWidth + TABLE_VIEWPORT_BORDER_CLIP_PADDING * 2,+ tableSkeleton.height + TABLE_VIEWPORT_BORDER_CLIP_PADDING * 2+ );+ ctx.closePath();+ ctx.clip();+ drawLiquid.translate(-viewport.scrollLeft, 0);+ }for (const row of rows) {const { top: rowTop, cells } = row;- this._drawLiquid?.translateSave();- this._drawLiquid?.translate(0, rowTop);+ drawLiquid.translateSave();+ drawLiquid.translate(0, rowTop);for (const cell of cells) {+ if ((cell as IDocumentSkeletonPage & { isMergedCellCovered?: boolean }).isMergedCellCovered) {+ continue;+ }+const { left: cellLeft } = cell;- this._drawLiquid?.translateSave();- this._drawLiquid?.translate(cellLeft, 0);+ drawLiquid.translateSave();+ drawLiquid.translate(cellLeft, 0);this._drawTableCell(ctx,@@ -549,16 +581,62 @@ export class Documents extends DocComponent {parentScale);- this._drawLiquid?.translateRestore();+ drawLiquid.translateRestore();}- this._drawLiquid?.translateRestore();+ drawLiquid.translateRestore();+ }++ if (viewport && viewport.contentWidth > viewport.viewportWidth) {+ ctx.restore();}- this._drawLiquid?.translateRestore();+ drawLiquid.translateRestore();}}+ private _getTableViewport(+ page: IDocumentSkeletonPage,+ tableSkeleton: IDocumentSkeletonTable,+ unitId: string,+ tableId: string+ ): Nullable<IDocsTableRenderViewport> {+ const viewport = getDocsTableRenderViewport(unitId, tableId);+ if (viewport) {+ return viewport;+ }++ const { pageWidth, marginLeft = 0, marginRight = 0 } = page;+ if (!Number.isFinite(pageWidth)) {+ return null;+ }++ const viewportWidth = Math.max(0, pageWidth - marginLeft - marginRight - tableSkeleton.left);+ if (viewportWidth <= 0 || tableSkeleton.width <= viewportWidth) {+ return null;+ }++ return {+ contentWidth: tableSkeleton.width,+ scrollLeft: 0,+ viewportWidth,+ };+ }++ private _getRenderUnitId(): string {+ const skeleton = this.getSkeleton() as {+ getViewModel?: () => {+ getDataModel?: () => {+ getUnitId?: () => string;+ };+ };+ } | undefined;+ const viewModel = skeleton?.getViewModel?.();+ const dataModel = viewModel?.getDataModel?.();++ return dataModel?.getUnitId?.() ?? this.oKey;+ }+private _drawBorderBottom(ctx: UniverRenderingContext,page: IDocumentSkeletonPage,@@ -777,15 +855,19 @@ export class Documents extends DocComponent {const { pageWidth, pageHeight } = cell;const rowSke = cell.parent as IDocumentSkeletonRow;const index = rowSke.cells.indexOf(cell);++ if (index < 0) {+ return;+ }+const cellSource = rowSke.rowSource.tableCells[index];+ const tableSke = rowSke.parent as IDocumentSkeletonTable | undefined;+ const rowIndexInTable = tableSke?.rows.indexOf(rowSke);+ const rowIndex = rowIndexInTable == null || rowIndexInTable < 0 ? rowSke.index ?? 0 : rowIndexInTable;- const {- borderTop = DEFAULT_BORDER_COLOR,- borderBottom = DEFAULT_BORDER_COLOR,- borderLeft = DEFAULT_BORDER_COLOR,- borderRight = DEFAULT_BORDER_COLOR,- backgroundColor,- } = cellSource;+ if (!cellSource || cellSource.rowSpan === 0 || cellSource.columnSpan === 0) {+ return;+ }if (this._drawLiquid == null) {return;@@ -796,57 +878,85 @@ export class Documents extends DocComponent {y += marginTop;// Draw cell bg.- if (backgroundColor && backgroundColor.rgb) {+ if (cellSource.backgroundColor?.rgb) {ctx.save();- ctx.fillStyle = backgroundColor.rgb;+ ctx.fillStyle = cellSource.backgroundColor.rgb;ctx.fillRectByPrecision(x, y, pageWidth, pageHeight);ctx.restore();}- ctx.save();- ctx.setLineWidthByPrecision (1);-- ctx.save();- ctx.strokeStyle = borderLeft.color.rgb ?? DEFAULT_BORDER_COLOR.color.rgb!;- drawLineByBorderType(ctx, BORDER_LTRB.LEFT, 0, {+ const position = {startX: x,startY: y,endX: x + pageWidth,endY: y + pageHeight,- });- ctx.restore();+ };- ctx.save();- ctx.strokeStyle = borderTop.color.rgb ?? DEFAULT_BORDER_COLOR.color.rgb!;- drawLineByBorderType(ctx, BORDER_LTRB.TOP, 0, {- startX: x,- startY: y,- endX: x + pageWidth,- endY: y + pageHeight,- });- ctx.restore();+ const rightCellSource = this._getTableCellSource(rowSke, index + 1);+ const bottomCellSource = tableSke ? this._getTableCellSource(tableSke.rows[rowIndex + 1], index) : undefined;+ this._drawTableCellBorder(ctx, this._resolveTableCellBorder(cellSource.borderRight, rightCellSource?.borderLeft), BORDER_LTRB.RIGHT, position);+ this._drawTableCellBorder(ctx, this._resolveTableCellBorder(cellSource.borderBottom, bottomCellSource?.borderTop), BORDER_LTRB.BOTTOM, position);- ctx.save();- ctx.strokeStyle = borderRight.color.rgb ?? DEFAULT_BORDER_COLOR.color.rgb!;- drawLineByBorderType(ctx, BORDER_LTRB.RIGHT, 0, {- startX: x,- startY: y,- endX: x + pageWidth,- endY: y + pageHeight,- });- ctx.restore();+ if (rowIndex <= 0) {+ this._drawTableCellBorder(ctx, this._resolveTableCellBorder(cellSource.borderTop), BORDER_LTRB.TOP, position);+ }- ctx.save();- ctx.strokeStyle = borderBottom.color.rgb ?? DEFAULT_BORDER_COLOR.color.rgb!;- drawLineByBorderType(ctx, BORDER_LTRB.BOTTOM, 0, {- startX: x,- startY: y,- endX: x + pageWidth,- endY: y + pageHeight,- });- ctx.restore();+ if (index <= 0) {+ this._drawTableCellBorder(ctx, this._resolveTableCellBorder(cellSource.borderLeft), BORDER_LTRB.LEFT, position);+ }+ }++ private _getTableCellSource(row: Nullable<IDocumentSkeletonRow>, column: number): Nullable<ITableCell> {+ return row?.rowSource.tableCells[column] ?? null;+ }- // restore setLineWidthByPrecision.+ private _resolveTableCellBorder(primary?: ITableCellBorder, secondary?: ITableCellBorder): Nullable<ITableCellBorder> {+ if (this._isDrawableTableCellBorder(primary)) {+ return primary!;+ }++ if (this._isDrawableTableCellBorder(secondary)) {+ return secondary!;+ }++ if (primary || secondary) {+ return null;+ }++ return DEFAULT_BORDER_COLOR;+ }++ private _isDrawableTableCellBorder(border?: ITableCellBorder): boolean {+ if (!border) {+ return false;+ }++ const lineWidth = border.width?.v ?? 1;+ const color = border.color?.rgb ?? DEFAULT_BORDER_COLOR.color.rgb!;+ return lineWidth > 0 && color !== 'transparent';+ }++ private _drawTableCellBorder(+ ctx: UniverRenderingContext,+ border: Nullable<ITableCellBorder>,+ type: BORDER_LTRB,+ position: { startX: number; startY: number; endX: number; endY: number }+ ) {+ if (!border) {+ return;+ }++ const lineWidth = border.width?.v ?? 1;+ const color = border.color?.rgb ?? DEFAULT_BORDER_COLOR.color.rgb!;+ if (lineWidth <= 0 || color === 'transparent') {+ return;+ }++ ctx.save();+ ctx.setLineWidthByPrecision(lineWidth);+ setTableCellBorderDash(ctx, border.dashStyle);+ ctx.strokeStyle = color;+ drawLineByBorderType(ctx, type, 0, position);ctx.restore();}@@ -1111,3 +1221,17 @@ export class Documents extends DocComponent {});}}++function setTableCellBorderDash(ctx: UniverRenderingContext, dashStyle?: DashStyleType) {+ if (dashStyle === DashStyleType.DOT) {+ ctx.setLineDash([2]);+ return;+ }++ if (dashStyle === DashStyleType.DASH) {+ ctx.setLineDash([6]);+ return;+ }++ ctx.setLineDash([0]);+}diff --git a/packages/engine-render/src/components/docs/layout/block/__tests__/table.spec.ts b/packages/engine-render/src/components/docs/layout/block/__tests__/table.spec.tsindex 2fb0a71dce..e19c389e72 100644--- a/packages/engine-render/src/components/docs/layout/block/__tests__/table.spec.ts+++ b/packages/engine-render/src/components/docs/layout/block/__tests__/table.spec.ts@@ -17,9 +17,24 @@import type { ITable } from '@univerjs/core';import type { IParagraphList } from '../../../../../basics/i-document-skeleton-cached';import type { DataStreamTreeNode } from '../../../view-model/data-stream-tree-node';-import { TableAlignmentType, TableSizeType } from '@univerjs/core';-import { describe, expect, it } from 'vitest';-import { getNullTableSkeleton, getTableIdAndSliceIndex, getTableSliceId, rollbackListCache } from '../table';+import { BooleanNumber, TableAlignmentType, TableRowHeightRule, TableSizeType, VerticalAlignmentType } from '@univerjs/core';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import {+ createTableSkeleton,+ createTableSkeletons,+ getNullTableSkeleton,+ getTableIdAndSliceIndex,+ getTableSliceId,+ rollbackListCache,+} from '../table';++const createSkeletonCellPagesMock = vi.fn();+const createNullCellPageMock = vi.fn();++vi.mock('../../model/page', () => ({+ createSkeletonCellPages: (...args: unknown[]) => createSkeletonCellPagesMock(...args),+ createNullCellPage: (...args: unknown[]) => createNullCellPageMock(...args),+}));function createMockTable(overrides: Partial<ITable> = {}): ITable {return {@@ -36,6 +51,97 @@ function createMockTable(overrides: Partial<ITable> = {}): ITable {} as ITable;}+function createRowNode(startIndex: number, endIndex: number, cellCount: number) {+ return {+ startIndex,+ endIndex,+ children: new Array(cellCount).fill(0).map((_, i) => ({+ startIndex: startIndex + i * 5,+ endIndex: startIndex + i * 5 + 4,+ children: [],+ })),+ };+}++function createContextAndTable() {+ const tableSource = {+ tableId: 'table-1',+ align: TableAlignmentType.START,+ indent: { v: 8 },+ tableRows: [+ {+ repeatHeaderRow: BooleanNumber.TRUE,+ trHeight: {+ hRule: TableRowHeightRule.AUTO,+ val: { v: 16 },+ },+ cantSplit: BooleanNumber.FALSE,+ tableCells: [+ { vAlign: VerticalAlignmentType.TOP },+ { vAlign: VerticalAlignmentType.CENTER },+ ],+ },+ {+ repeatHeaderRow: BooleanNumber.FALSE,+ trHeight: {+ hRule: TableRowHeightRule.AT_LEAST,+ val: { v: 28 },+ },+ cantSplit: BooleanNumber.TRUE,+ tableCells: [+ { vAlign: VerticalAlignmentType.BOTTOM },+ { vAlign: VerticalAlignmentType.TOP },+ ],+ },+ ],+ } as any;++ const viewModel = {+ getTableByStartIndex: vi.fn(() => ({ tableSource })),+ } as any;++ const tableNode = {+ startIndex: 0,+ endIndex: 80,+ children: [+ createRowNode(1, 20, 2),+ createRowNode(21, 40, 2),+ ],+ } as any;++ const curPage = {+ pageWidth: 400,+ pageHeight: 300,+ marginTop: 20,+ marginBottom: 20,+ marginLeft: 10,+ marginRight: 10,+ } as any;++ return {+ ctx: {} as any,+ sectionBreakConfig: {} as any,+ tableSource,+ viewModel,+ tableNode,+ curPage,+ };+}++function makeCellPage(width: number, height: number) {+ return {+ width,+ height,+ pageWidth: width,+ pageHeight: height,+ marginTop: 1,+ marginBottom: 1,+ originMarginTop: 1,+ originMarginBottom: 1,+ sections: [],+ };+}+describe('table utilities', () => {describe('getTableSliceId', () => {it('concatenates tableId and sliceIndex with delimiter', () => {@@ -149,3 +255,182 @@ describe('table utilities', () => {});});});++describe('docs table layout', () => {+ beforeEach(() => {+ createSkeletonCellPagesMock.mockReset();+ createNullCellPageMock.mockReset();++ createNullCellPageMock.mockImplementation(() => ({+ page: makeCellPage(60, 10),+ }));++ createSkeletonCellPagesMock.mockImplementation(+ (_ctx: unknown, _viewModel: unknown, _cellNode: unknown, _section: unknown, _table: unknown, row: number, col: number, availableHeight?: number) => {+ const baseHeight = row === 0 ? 20 : 24;+ if (row === 1 && col === 0 && typeof availableHeight === 'number' && availableHeight < 40) {+ return [makeCellPage(60, baseHeight), makeCellPage(60, 16)];+ }+ return [makeCellPage(60, baseHeight)];+ }+ );+ });++ it('creates table skeleton and applies row/cell alignment data', () => {+ const { ctx, curPage, viewModel, tableNode, sectionBreakConfig } = createContextAndTable();++ const skeleton = createTableSkeleton(ctx, curPage, viewModel, tableNode, sectionBreakConfig);+ expect(skeleton).toBeTruthy();+ expect(skeleton?.rows.length).toBe(2);+ expect(skeleton?.width).toBeGreaterThan(0);+ expect(skeleton?.height).toBeGreaterThan(0);+ expect(skeleton?.left).toBeGreaterThanOrEqual(0);+ expect(skeleton?.rows[0].cells[0].marginTop).toBeGreaterThanOrEqual(1);+ expect(skeleton?.rows[0].cells[1].marginTop).toBeGreaterThanOrEqual(1);+ });++ it('keeps covered merged cells as non-rendering layout placeholders', () => {+ const { ctx, curPage, viewModel, tableNode, sectionBreakConfig, tableSource } = createContextAndTable();+ createSkeletonCellPagesMock.mockImplementation(+ (_ctx: unknown, _viewModel: unknown, _cellNode: unknown, _section: unknown, table: any, row: number, col: number) => {+ const columnSpan = Math.max(1, table.tableRows[row].tableCells[col].columnSpan ?? 1);+ return [makeCellPage(60 * columnSpan, 20)];+ }+ );+ tableSource.tableRows[0].tableCells = [+ { columnSpan: 2, vAlign: VerticalAlignmentType.TOP },+ { rowSpan: 0, columnSpan: 0, vAlign: VerticalAlignmentType.TOP },+ { vAlign: VerticalAlignmentType.TOP },+ ];+ tableNode.children[0] = createRowNode(1, 30, 3) as any;++ const skeleton = createTableSkeleton(ctx, curPage, viewModel, tableNode, sectionBreakConfig);++ expect(skeleton).not.toBeNull();+ const cells = skeleton!.rows[0].cells;+ expect(cells).toHaveLength(3);+ expect((cells[1] as any).isMergedCellCovered).toBe(true);+ expect(cells[2].left).toBe(120);+ expect(createSkeletonCellPagesMock.mock.calls.some((call) => call[5] === 0 && call[6] === 1)).toBe(false);+ });++ it('does not shift cells after a same-row horizontally covered merged cell', () => {+ const { ctx, curPage, viewModel, tableNode, sectionBreakConfig, tableSource } = createContextAndTable();+ createSkeletonCellPagesMock.mockImplementation(+ (_ctx: unknown, _viewModel: unknown, _cellNode: unknown, _section: unknown, table: any, row: number, col: number) => {+ const columnSpan = Math.max(1, table.tableRows[row].tableCells[col].columnSpan ?? 1);+ return [makeCellPage(60 * columnSpan, 20)];+ }+ );+ tableSource.tableRows[0].tableCells = [+ { vAlign: VerticalAlignmentType.TOP },+ { columnSpan: 2, vAlign: VerticalAlignmentType.TOP },+ { rowSpan: 0, columnSpan: 0, vAlign: VerticalAlignmentType.TOP },+ { vAlign: VerticalAlignmentType.TOP },+ ];+ tableNode.children[0] = createRowNode(1, 30, 4) as any;++ const skeleton = createTableSkeleton(ctx, curPage, viewModel, tableNode, sectionBreakConfig);++ expect(skeleton?.rows[0].cells[3].left).toBe(180);+ });++ it('expands merged master cell height across spanned rows', () => {+ const { ctx, curPage, viewModel, tableNode, sectionBreakConfig, tableSource } = createContextAndTable();+ tableSource.tableRows[0].tableCells = [+ { rowSpan: 2, columnSpan: 2, vAlign: VerticalAlignmentType.TOP },+ { rowSpan: 0, columnSpan: 0, vAlign: VerticalAlignmentType.TOP },+ ];+ tableSource.tableRows[1].tableCells = [+ { rowSpan: 0, columnSpan: 0, vAlign: VerticalAlignmentType.TOP },+ { rowSpan: 0, columnSpan: 0, vAlign: VerticalAlignmentType.TOP },+ ];++ const skeleton = createTableSkeleton(ctx, curPage, viewModel, tableNode, sectionBreakConfig);++ expect(skeleton?.rows[0].cells[0].pageHeight).toBe(+ skeleton!.rows[0].height + skeleton!.rows[1].height+ );+ });++ it('treats explicit row height as a minimum so wrapped cell content remains visible', () => {+ const { ctx, curPage, viewModel, tableNode, sectionBreakConfig, tableSource } = createContextAndTable();+ tableSource.tableRows[0].trHeight = {+ hRule: TableRowHeightRule.EXACT,+ val: { v: 18 },+ };+ createSkeletonCellPagesMock.mockImplementation(+ (_ctx: unknown, _viewModel: unknown, _cellNode: unknown, _section: unknown, _table: unknown, row: number) =>+ [makeCellPage(60, row === 0 ? 48 : 20)]+ );++ const skeleton = createTableSkeleton(ctx, curPage, viewModel, tableNode, sectionBreakConfig);++ expect(skeleton?.rows[0].height).toBe(50);+ expect(skeleton?.rows[0].cells[0].pageHeight).toBe(50);+ });++ it('creates sliced tables when available height is limited', () => {+ const { ctx, curPage, viewModel, tableNode, sectionBreakConfig } = createContextAndTable();++ const result = createTableSkeletons(ctx, curPage, viewModel, tableNode, sectionBreakConfig, 90);+ expect(result.skeTables.length).toBeGreaterThan(0);+ expect(typeof result.fromCurrentPage).toBe('boolean');+ expect(result.skeTables[0].rows.length).toBeGreaterThan(0);++ if (result.skeTables.length > 1) {+ expect(result.skeTables[1].tableId).toContain('#-#');+ }+ });++ it('repeats multiple leading header rows on sliced table pages', () => {+ const { ctx, curPage, viewModel, tableNode, sectionBreakConfig, tableSource } = createContextAndTable();+ tableSource.tableRows[1].repeatHeaderRow = BooleanNumber.TRUE;+ tableSource.tableRows.push(+ {+ repeatHeaderRow: BooleanNumber.FALSE,+ trHeight: {+ hRule: TableRowHeightRule.EXACT,+ val: { v: 70 },+ },+ cantSplit: BooleanNumber.FALSE,+ tableCells: [+ { vAlign: VerticalAlignmentType.TOP },+ { vAlign: VerticalAlignmentType.TOP },+ ],+ },+ {+ repeatHeaderRow: BooleanNumber.FALSE,+ trHeight: {+ hRule: TableRowHeightRule.EXACT,+ val: { v: 40 },+ },+ cantSplit: BooleanNumber.FALSE,+ tableCells: [+ { vAlign: VerticalAlignmentType.TOP },+ { vAlign: VerticalAlignmentType.TOP },+ ],+ }+ );+ tableNode.children.push(createRowNode(41, 60, 2) as any, createRowNode(61, 80, 2) as any);++ const result = createTableSkeletons(ctx, curPage, viewModel, tableNode, sectionBreakConfig, 110);++ expect(result.skeTables.length).toBeGreaterThan(1);+ expect(result.skeTables[1].rows[0]).toMatchObject({ index: 0, isRepeatRow: true });+ expect(result.skeTables[1].rows[1]).toMatchObject({ index: 1, isRepeatRow: true });+ expect(result.skeTables[1].rows[2]).toMatchObject({ index: 2, isRepeatRow: false });+ });++ it('returns an empty slice result when the table is missing', () => {+ const { ctx, curPage, tableNode, sectionBreakConfig } = createContextAndTable();+ const noTableViewModel = {+ getTableByStartIndex: vi.fn(() => null),+ };++ expect(createTableSkeleton(ctx, curPage, noTableViewModel as any, tableNode, sectionBreakConfig)).toBeNull();+ const sliced = createTableSkeletons(ctx, curPage, noTableViewModel as any, tableNode, sectionBreakConfig, 100);+ expect(sliced.skeTables).toEqual([]);+ expect(sliced.fromCurrentPage).toBe(false);+ });+});diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/linebreaking.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/linebreaking.spec.tsindex 5151a4ba4b..51c0076cc7 100644--- a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/linebreaking.spec.ts+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/linebreaking.spec.ts@@ -14,11 +14,24 @@* limitations under the License.*/-import { describe, expect, it } from 'vitest';+import { DocumentFlavor } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';import { lineBreaking } from '../linebreaking';import { shaping } from '../shaping';import { createParagraphLayoutTestBed } from './create-paragraph-layout-test-bed';+function createContext() {+ return {+ paragraphConfigCache: new Map(),+ skeletonResourceReference: {+ skeHeaders: new Map(),+ skeFooters: new Map(),+ skeListLevel: new Map(),+ drawingAnchor: new Map(),+ },+ } as any;+}+describe('linebreaking', () => {it('lays out short text on a single page', () => {const { viewModel, ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('Hi');@@ -80,4 +93,365 @@ describe('linebreaking', () => {expect(result.length).toBe(1);});++ it('applies callout outer spacing as a temporary layout style without mutating the paragraph model', () => {+ const ctx = createContext();+ const paragraphStyle = { indentStart: { v: 60 }, indentEnd: { v: 20 } };+ const paragraph = {+ startIndex: 2,+ paragraphStyle,+ };+ const body = {+ paragraphs: [paragraph],+ blockRanges: [{+ blockId: 'callout-1',+ blockType: 'callout',+ startIndex: 0,+ endIndex: 6,+ }],+ };+ const viewModel = {+ getParagraph: vi.fn(() => paragraph),+ getBody: vi.fn(() => body),+ getCustomBlock: vi.fn(() => null),+ } as any;++ lineBreaking(+ ctx,+ viewModel,+ [],+ {+ segmentId: 'segment-1',+ pageNumber: 1,+ } as any,+ {+ endIndex: 5,+ startIndex: 2,+ blocks: [],+ children: [],+ } as any,+ {+ lists: [],+ localeService: {} as any,+ drawings: {},+ } as any,+ null+ );++ expect(ctx.paragraphConfigCache.get('segment-1')?.get(5)?.paragraphStyle).toEqual({+ indentStart: { v: 60 },+ indentEnd: { v: 20 },+ lineSpacing: 1.5,+ spaceAbove: { v: 34 },+ spaceBelow: { v: 34 },+ });+ expect(paragraphStyle).toEqual({ indentStart: { v: 60 }, indentEnd: { v: 20 } });+ });++ it('removes bottom outer spacing between adjacent layout block ranges', () => {+ const ctx = createContext();+ const firstCalloutParagraph = {+ startIndex: 1,+ paragraphStyle: {},+ };+ const secondCalloutParagraph = {+ startIndex: 4,+ paragraphStyle: {},+ };+ const body = {+ paragraphs: [firstCalloutParagraph, secondCalloutParagraph],+ blockRanges: [+ {+ blockId: 'callout-1',+ blockType: 'callout',+ startIndex: 0,+ endIndex: 2,+ },+ {+ blockId: 'quote-1',+ blockType: 'quote',+ startIndex: 3,+ endIndex: 5,+ },+ ],+ };+ const viewModel = {+ getParagraph: vi.fn(() => firstCalloutParagraph),+ getBody: vi.fn(() => body),+ getCustomBlock: vi.fn(() => null),+ } as any;++ lineBreaking(+ ctx,+ viewModel,+ [],+ {+ segmentId: 'segment-1',+ pageNumber: 1,+ } as any,+ {+ endIndex: 1,+ startIndex: 0,+ blocks: [],+ children: [],+ } as any,+ {+ lists: [],+ localeService: {} as any,+ drawings: {},+ } as any,+ null+ );++ expect(ctx.paragraphConfigCache.get('segment-1')?.get(1)?.paragraphStyle).toEqual({+ lineSpacing: 1.5,+ spaceAbove: { v: 34 },+ });+ });++ it('applies quote outer spacing with the same temporary layout rule', () => {+ const ctx = createContext();+ const firstParagraphStyle = { indentStart: { v: 22 } };+ const lastParagraphStyle = { indentStart: { v: 22 } };+ const firstParagraph = {+ startIndex: 2,+ paragraphStyle: firstParagraphStyle,+ };+ const lastParagraph = {+ startIndex: 4,+ paragraphStyle: lastParagraphStyle,+ };+ const body = {+ paragraphs: [firstParagraph, lastParagraph],+ blockRanges: [{+ blockId: 'quote-1',+ blockType: 'quote',+ startIndex: 0,+ endIndex: 6,+ }],+ };+ const viewModel = {+ getParagraph: vi.fn(() => firstParagraph),+ getBody: vi.fn(() => body),+ getCustomBlock: vi.fn(() => null),+ } as any;++ lineBreaking(+ ctx,+ viewModel,+ [],+ {+ segmentId: 'segment-1',+ pageNumber: 1,+ } as any,+ {+ endIndex: 2,+ startIndex: 0,+ blocks: [],+ children: [],+ } as any,+ {+ lists: [],+ localeService: {} as any,+ drawings: {},+ } as any,+ null+ );++ expect(ctx.paragraphConfigCache.get('segment-1')?.get(2)?.paragraphStyle).toEqual({+ indentStart: { v: 22 },+ lineSpacing: 1.5,+ spaceAbove: { v: 24 },+ });+ expect(firstParagraphStyle).toEqual({ indentStart: { v: 22 } });+ });++ it('applies code outer spacing with the same temporary layout rule', () => {+ const ctx = createContext();+ const paragraphStyle = { indentStart: { v: 20 }, indentEnd: { v: 20 } };+ const paragraph = {+ startIndex: 2,+ paragraphStyle,+ };+ const body = {+ paragraphs: [paragraph],+ blockRanges: [{+ blockId: 'code-1',+ blockType: 'code',+ startIndex: 0,+ endIndex: 6,+ }],+ };+ const viewModel = {+ getParagraph: vi.fn(() => paragraph),+ getBody: vi.fn(() => body),+ getCustomBlock: vi.fn(() => null),+ } as any;++ lineBreaking(+ ctx,+ viewModel,+ [],+ {+ segmentId: 'segment-1',+ pageNumber: 1,+ } as any,+ {+ endIndex: 5,+ startIndex: 2,+ blocks: [],+ children: [],+ } as any,+ {+ lists: [],+ localeService: {} as any,+ drawings: {},+ } as any,+ null+ );++ expect(ctx.paragraphConfigCache.get('segment-1')?.get(5)?.paragraphStyle).toEqual({+ indentStart: { v: 20 },+ indentEnd: { v: 20 },+ lineSpacing: 1.5,+ spaceAbove: { v: 32 },+ spaceBelow: { v: 32 },+ });+ expect(paragraphStyle).toEqual({ indentStart: { v: 20 }, indentEnd: { v: 20 } });+ });++ it('applies comfortable default spacing to normal paragraphs as layout-only style', () => {+ const ctx = createContext();+ const paragraphStyle = {};+ const paragraph = {+ startIndex: 3,+ paragraphStyle,+ };+ const viewModel = {+ getParagraph: vi.fn(() => paragraph),+ getBody: vi.fn(() => ({+ paragraphs: [paragraph],+ })),+ getCustomBlock: vi.fn(() => null),+ } as any;++ lineBreaking(+ ctx,+ viewModel,+ [],+ {+ segmentId: 'segment-1',+ pageNumber: 1,+ } as any,+ {+ endIndex: 3,+ startIndex: 0,+ blocks: [],+ children: [],+ } as any,+ {+ lists: [],+ localeService: {} as any,+ drawings: {},+ } as any,+ null+ );++ expect(ctx.paragraphConfigCache.get('segment-1')?.get(3)?.paragraphStyle).toEqual({+ spaceAbove: { v: 0 },+ lineSpacing: 1.5,+ spaceBelow: { v: 8 },+ });+ expect(paragraphStyle).toEqual({});+ });++ it('keeps embedded sheet cell documents on their explicit paragraph style only', () => {+ const ctx = createContext();+ const paragraphStyle = {};+ const paragraph = {+ startIndex: 3,+ paragraphStyle,+ };+ const viewModel = {+ getParagraph: vi.fn(() => paragraph),+ getBody: vi.fn(() => ({+ paragraphs: [paragraph],+ })),+ getSnapshot: vi.fn(() => ({+ documentStyle: {+ documentFlavor: DocumentFlavor.UNSPECIFIED,+ },+ })),+ getCustomBlock: vi.fn(() => null),+ } as any;++ lineBreaking(+ ctx,+ viewModel,+ [],+ {+ segmentId: 'segment-1',+ pageNumber: 1,+ } as any,+ {+ endIndex: 3,+ startIndex: 0,+ blocks: [],+ children: [],+ } as any,+ {+ lists: [],+ localeService: {} as any,+ drawings: {},+ } as any,+ null+ );++ expect(ctx.paragraphConfigCache.get('segment-1')?.get(3)?.paragraphStyle).toEqual({});+ expect(paragraphStyle).toEqual({});+ });++ it('keeps embedded sheet rich text documents without a flavor on their explicit paragraph style only', () => {+ const ctx = createContext();+ const paragraphStyle = {};+ const paragraph = {+ startIndex: 3,+ paragraphStyle,+ };+ const viewModel = {+ getParagraph: vi.fn(() => paragraph),+ getBody: vi.fn(() => ({+ paragraphs: [paragraph],+ })),+ getSnapshot: vi.fn(() => ({+ documentStyle: {},+ })),+ getCustomBlock: vi.fn(() => null),+ } as any;++ lineBreaking(+ ctx,+ viewModel,+ [],+ {+ segmentId: 'segment-1',+ pageNumber: 1,+ } as any,+ {+ endIndex: 3,+ startIndex: 0,+ blocks: [],+ children: [],+ } as any,+ {+ lists: [],+ localeService: {} as any,+ drawings: {},+ } as any,+ null+ );++ expect(ctx.paragraphConfigCache.get('segment-1')?.get(3)?.paragraphStyle).toEqual({});+ expect(paragraphStyle).toEqual({});+ });});diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/linebreaking.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/linebreaking.tsindex 5d17ac7012..b5f6f7da48 100644--- a/packages/engine-render/src/components/docs/layout/block/paragraph/linebreaking.ts+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/linebreaking.ts@@ -14,14 +14,14 @@* limitations under the License.*/-import type { IBullet, IDocDrawingBase, IDrawings, IParagraph, Nullable } from '@univerjs/core';+import type { IBullet, IDocDrawingBase, IDocumentBody, IDrawings, IParagraph, IParagraphStyle, Nullable } from '@univerjs/core';import type { IDocumentSkeletonBullet, IDocumentSkeletonDrawing, IDocumentSkeletonPage, IDocumentSkeletonTable, IParagraphList } from '../../../../../basics/i-document-skeleton-cached';import type { IParagraphConfig, ISectionBreakConfig } from '../../../../../basics/interfaces';import type { DataStreamTreeNode } from '../../../view-model/data-stream-tree-node';import type { DocumentViewModel } from '../../../view-model/document-view-model';import type { ILayoutContext } from '../../tools';import type { IShapedText } from './shaping';-import { DataStreamTreeTokenType, PositionedObjectLayoutType, Tools } from '@univerjs/core';+import { DataStreamTreeTokenType, DEFAULT_DOCUMENT_PARAGRAPH_LINE_SPACING, DEFAULT_DOCUMENT_PARAGRAPH_SPACE_ABOVE, DEFAULT_DOCUMENT_PARAGRAPH_SPACE_BELOW, DocumentFlavor, PositionedObjectLayoutType, Tools } from '@univerjs/core';import { BreakType } from '../../../../../basics/i-document-skeleton-cached';import { createSkeletonPage } from '../../model/page';import { setColumnFullState } from '../../model/section';@@ -29,6 +29,12 @@ import { getLastNotFullColumnInfo } from '../../tools';import { dealWithBullet } from './bullet';import { layoutParagraph } from './layout-ruler';+const BLOCK_LAYOUT_OUTER_SPACING_MAP = new Map([+ ['callout', 34],+ ['code', 32],+ ['quote', 24],+]);+function _getListLevelAncestors(bullet?: IBullet,listLevel?: Map<string, IParagraphList[][]>@@ -91,6 +97,110 @@ function _updateListLevelAncestors(listLevel?.set(listId, cacheItem);}+function _withMinSpacing(style: IParagraphStyle, key: 'spaceAbove' | 'spaceBelow', value: number) {+ const current = style[key];+ const nextValue = Math.max(current?.v ?? 0, value);++ style[key] = {+ ...current,+ v: nextValue,+ };+}++function _getNextAdjacentBlockRange(blockRanges: IDocumentBody['blockRanges'], blockRange: NonNullable<IDocumentBody['blockRanges']>[number]) {+ return blockRanges+ ?.filter((range) => range.startIndex > blockRange.endIndex)+ .sort((left, right) => left.startIndex - right.startIndex)[0];+}++function _hasNextAdjacentLayoutBlockRange(blockRanges: IDocumentBody['blockRanges'], blockRange: NonNullable<IDocumentBody['blockRanges']>[number]): boolean {+ const nextBlockRange = _getNextAdjacentBlockRange(blockRanges, blockRange);++ return (+ nextBlockRange != null &&+ BLOCK_LAYOUT_OUTER_SPACING_MAP.has(nextBlockRange.blockType) &&+ nextBlockRange.startIndex === blockRange.endIndex + 1+ );+}++function _applyDefaultLayoutParagraphStyle(style: IParagraphStyle, hasBlockRange: boolean) {+ if (style.lineSpacing == null) {+ style.lineSpacing = DEFAULT_DOCUMENT_PARAGRAPH_LINE_SPACING;+ }++ if (hasBlockRange) {+ return;+ }++ if (style.spaceAbove == null) {+ style.spaceAbove = { v: DEFAULT_DOCUMENT_PARAGRAPH_SPACE_ABOVE };+ }++ if (style.spaceBelow == null) {+ style.spaceBelow = { v: DEFAULT_DOCUMENT_PARAGRAPH_SPACE_BELOW };+ }+}++function _applyBlockRangeLayoutParagraphStyle(+ body: Nullable<IDocumentBody>,+ paragraph: IParagraph,+ paragraphStyle: IParagraphStyle,+ shouldApplyDocumentDefaults: boolean+): IParagraphStyle {+ const style = Tools.deepClone(paragraphStyle);+ const blockRanges = body?.blockRanges;++ if (!blockRanges?.length) {+ if (shouldApplyDocumentDefaults) {+ _applyDefaultLayoutParagraphStyle(style, false);+ }+ return style;+ }++ const blockRange = blockRanges.find((range) =>+ BLOCK_LAYOUT_OUTER_SPACING_MAP.has(range.blockType) &&+ paragraph.startIndex > range.startIndex &&+ paragraph.startIndex < range.endIndex+ );++ if (!blockRange) {+ if (shouldApplyDocumentDefaults) {+ _applyDefaultLayoutParagraphStyle(style, false);+ }+ return style;+ }++ _applyDefaultLayoutParagraphStyle(style, true);++ const blockParagraphs = (body?.paragraphs ?? [])+ .filter((item) => item.startIndex > blockRange.startIndex && item.startIndex < blockRange.endIndex)+ .sort((left, right) => left.startIndex - right.startIndex);+ const firstParagraph = blockParagraphs[0];+ const lastParagraph = blockParagraphs[blockParagraphs.length - 1];+ const outerSpacing = BLOCK_LAYOUT_OUTER_SPACING_MAP.get(blockRange.blockType) ?? 0;++ if (firstParagraph?.startIndex === paragraph.startIndex) {+ _withMinSpacing(style, 'spaceAbove', outerSpacing);+ }++ if (lastParagraph?.startIndex === paragraph.startIndex && !_hasNextAdjacentLayoutBlockRange(blockRanges, blockRange)) {+ _withMinSpacing(style, 'spaceBelow', outerSpacing);+ }++ return style;+}++function _shouldApplyDocumentDefaultParagraphStyle(viewModel: DocumentViewModel): boolean {+ const snapshot = viewModel.getSnapshot?.();+ const documentFlavor = snapshot?.documentStyle.documentFlavor;++ if (snapshot == null) {+ return true;+ }++ return documentFlavor != null && documentFlavor !== DocumentFlavor.UNSPECIFIED;+}+function _changeDrawingToSkeletonFormat(drawingIds: string[],drawings: IDrawings@@ -164,8 +274,12 @@ export function lineBreaking(const paragraphConfig: IParagraphConfig = {paragraphIndex: endIndex,- // TODO optimize this deepClone- paragraphStyle: Tools.deepClone(paragraphStyle),+ paragraphStyle: _applyBlockRangeLayoutParagraphStyle(+ viewModel.getBody?.() ?? null,+ paragraph,+ paragraphStyle,+ _shouldApplyDocumentDefaultParagraphStyle(viewModel)+ ),paragraphNonInlineSkeDrawings,paragraphInlineSkeDrawings,skeTablesInParagraph: tableSkeletondiff --git a/packages/engine-render/src/components/docs/layout/block/table.ts b/packages/engine-render/src/components/docs/layout/block/table.tsindex c32b0c659a..ca61636750 100644--- a/packages/engine-render/src/components/docs/layout/block/table.ts+++ b/packages/engine-render/src/components/docs/layout/block/table.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { INumberUnit, ITable, ITableRow, Nullable } from '@univerjs/core';+import type { INumberUnit, ITable, ITableCell, ITableRow, Nullable } from '@univerjs/core';import type { IDocumentSkeletonPage, IDocumentSkeletonRow, IDocumentSkeletonTable, IParagraphList, ISectionBreakConfig } from '../../../../basics';import type { DataStreamTreeNode } from '../../view-model/data-stream-tree-node';import type { DocumentViewModel } from '../../view-model/document-view-model';@@ -54,6 +54,18 @@ export function createTableSkeleton(for (const cellNode of cellNodes) {const col = cellNodes.indexOf(cellNode);+ const cellConfig = rowSource.tableCells[col];++ if (isCoveredTableCell(cellConfig)) {+ const cellPageSkeleton = createMergedCoveredCellPage(ctx, sectionBreakConfig, table, row, col, rowSkeleton);+ cellPageSkeleton.left = left;+ if (shouldAdvanceTableCellLeft(table, row, col)) {+ left += cellPageSkeleton.pageWidth;+ }+ rowSkeleton.cells.push(cellPageSkeleton);+ continue;+ }+const cellPageSkeleton = createSkeletonCellPages(ctx,viewModel,@@ -76,7 +88,7 @@ export function createTableSkeleton(if (hRule === TableRowHeightRule.AT_LEAST) {rowHeight = Math.max(rowHeight, val.v);} else if (hRule === TableRowHeightRule.EXACT) {- rowHeight = val.v;+ rowHeight = Math.max(rowHeight, val.v);}// Set row height to cell page height.@@ -125,6 +137,7 @@ export function createTableSkeleton(tableSkeleton.width = tableWidth;tableSkeleton.height = rowTop;+ applyMergedCellSpanHeights(tableSkeleton);const { pageWidth, marginLeft = 0, marginRight = 0 } = curPage;@@ -156,8 +169,8 @@ interface ICreateTableCache {rowTop: number;tableWidth: number;remainHeight: number;- repeatRow: Nullable<DataStreamTreeNode>;- repeatRowHeight: number;+ repeatRows: DataStreamTreeNode[];+ repeatRowsHeight: number;}// Create skeletons of a table, which may be divided into different pages according to the available height of the page.@@ -181,15 +194,15 @@ export function createTableSkeletons(};}- const needRepeatHeader = table.tableRows[0].repeatHeaderRow === BooleanNumber.TRUE;+ const repeatRows = getLeadingRepeatHeaderRows(table, rowNodes);const curTableSkeleton = getNullTableSkeleton(startIndex, endIndex, table);const createCache: ICreateTableCache = {rowTop: 0,tableWidth: 0,remainHeight: availableHeight,- repeatRow: needRepeatHeader ? rowNodes[0] : null,- repeatRowHeight: 0,+ repeatRows,+ repeatRowsHeight: 0,};skeTables.push(curTableSkeleton);@@ -232,6 +245,8 @@ function updateTableSkeletonsPosition(let tableIndex = 0;for (const tableSkeleton of skeTables) {+ applyMergedCellSpanHeights(tableSkeleton);+// Update table width and left.tableSkeleton.width = tableWidth;tableSkeleton.left = tableLeft;@@ -257,7 +272,7 @@ function getAvailableHeight(curPage: IDocumentSkeletonPage, cache: ICreateTableClet pageContentHeight = pageHeight - marginTop - marginBottom;if (hasRepeatHeader) {- pageContentHeight -= cache.repeatRowHeight;+ pageContentHeight -= cache.repeatRowsHeight;}return pageContentHeight;@@ -292,6 +307,23 @@ function dealWithTableRow(for (const cellNode of cellNodes) {const col = cellNodes.indexOf(cellNode);+ const cellConfig = rowSource.tableCells[col];+ if (isCoveredTableCell(cellConfig)) {+ if (rowSkeletons.length === 0) {+ rowSkeletons.push(createNullRowSkeletonWithCells(+ ctx,+ sectionBreakConfig,+ table,+ row,+ startIndex,+ endIndex,+ rowSource,+ isRepeatRow+ ));+ }+ continue;+ }+const cellPageSkeletons = createSkeletonCellPages(ctx,viewModel,@@ -305,25 +337,16 @@ function dealWithTableRow();while (rowSkeletons.length < cellPageSkeletons.length) {- const rowSkeleton = _getNullTableRowSkeleton(startIndex, endIndex, row, rowSource, isRepeatRow);- const colCount = cellNodes.length;-- // Fill the row with null cell pages.- rowSkeleton.cells = [...new Array(colCount)].map((_, i) => {- const cellSkeleton = createNullCellPage(- ctx,- sectionBreakConfig,- table,- row,- i- ).page;-- cellSkeleton.parent = rowSkeleton;-- return cellSkeleton;- });-- rowSkeletons.push(rowSkeleton);+ rowSkeletons.push(createNullRowSkeletonWithCells(+ ctx,+ sectionBreakConfig,+ table,+ row,+ startIndex,+ endIndex,+ rowSource,+ isRepeatRow+ ));}while (rowHeights.length < cellPageSkeletons.length) {@@ -349,18 +372,25 @@ function dealWithTableRow(if (hRule === TableRowHeightRule.AT_LEAST) {rowHeights[rowIndex] = Math.max(rowHeights[rowIndex], val.v);} else if (hRule === TableRowHeightRule.EXACT) {- rowHeights[rowIndex] = val.v;+ rowHeights[rowIndex] = Math.max(rowHeights[rowIndex], val.v);}rowHeights[rowIndex] = Math.min(rowHeights[rowIndex], pageContentHeight);let left = 0;// Set row height to cell page height.- for (const cellPageSkeleton of rowSke.cells) {+ for (let col = 0; col < rowSke.cells.length; col++) {+ const cellPageSkeleton = rowSke.cells[col];+ if (cellPageSkeleton == null) {+ continue;+ }+cellPageSkeleton.left = left;cellPageSkeleton.pageHeight = rowHeights[rowIndex];- left += cellPageSkeleton.pageWidth;+ if (shouldAdvanceTableCellLeft(table, rowSke.index, col)) {+ left += cellPageSkeleton.pageWidth;+ }cache.tableWidth = Math.max(cache.tableWidth, left);}@@ -369,8 +399,8 @@ function dealWithTableRow(rowSke.height = rowHeights[rowIndex];}- if (row === 0 && cache.repeatRow) {- cache.repeatRowHeight = rowHeights[rowHeights.length - 1];+ if (!isRepeatRow && row < cache.repeatRows.length) {+ cache.repeatRowsHeight += rowHeights.reduce((total, height) => total + height, 0);}// Handle vertical alignment in cell.@@ -390,23 +420,24 @@ function dealWithTableRow(curTableSkeleton = getNullTableSkeleton(startIndex, endIndex, table);skeTables.push(curTableSkeleton);- // Handle repeat first row.- // If the current row crosses pages, there is no need to repeat the header row on the second page.- if (cache.repeatRow && isRepeatRow === false && row !== 0 && rowSkeleton.index !== lastRow.index) {- const FIRST_ROW_INDEX = 0;+ // Repeat all leading header rows. If the current row crosses pages,+ // there is no need to repeat the header rows on the second slice.+ if (cache.repeatRows.length > 0 && isRepeatRow === false && row >= cache.repeatRows.length && rowSkeleton.index !== lastRow.index) {cache.remainHeight = getAvailableHeight(curPage, cache, false);- dealWithTableRow(- ctx,- curPage,- skeTables,- viewModel,- sectionBreakConfig,- cache.repeatRow,- FIRST_ROW_INDEX,- table,- cache,- true- );+ cache.repeatRows.forEach((repeatRow, repeatRowIndex) => {+ dealWithTableRow(+ ctx,+ curPage,+ skeTables,+ viewModel,+ sectionBreakConfig,+ repeatRow,+ repeatRowIndex,+ table,+ cache,+ true+ );+ });}}}@@ -424,6 +455,20 @@ function dealWithTableRow(}}+function getLeadingRepeatHeaderRows(table: ITable, rowNodes: DataStreamTreeNode[]): DataStreamTreeNode[] {+ const repeatRows: DataStreamTreeNode[] = [];++ for (let index = 0; index < rowNodes.length; index++) {+ if (table.tableRows[index]?.repeatHeaderRow !== BooleanNumber.TRUE) {+ break;+ }++ repeatRows.push(rowNodes[index]);+ }++ return repeatRows;+}+function _verticalAlignInCell(rowSkeleton: IDocumentSkeletonRow,rowSource: ITableRow@@ -465,6 +510,142 @@ function _verticalAlignInCell(}}+function createNullRowSkeletonWithCells(+ ctx: ILayoutContext,+ sectionBreakConfig: ISectionBreakConfig,+ table: ITable,+ row: number,+ startIndex: number,+ endIndex: number,+ rowSource: ITableRow,+ isRepeatRow = false+): IDocumentSkeletonRow {+ const rowSkeleton = _getNullTableRowSkeleton(startIndex, endIndex, row, rowSource, isRepeatRow);+ const colCount = rowSource.tableCells.length;++ rowSkeleton.cells = Array.from({ length: colCount }, (_, col) =>+ createMergedAwareNullCellPage(ctx, sectionBreakConfig, table, row, col, rowSkeleton));++ return rowSkeleton;+}++function createMergedCoveredCellPage(+ ctx: ILayoutContext,+ sectionBreakConfig: ISectionBreakConfig,+ table: ITable,+ row: number,+ col: number,+ rowSkeleton: IDocumentSkeletonRow+): IDocumentSkeletonPage {+ return createMergedAwareNullCellPage(ctx, sectionBreakConfig, table, row, col, rowSkeleton);+}++function applyMergedCellSpanHeights(tableSkeleton: IDocumentSkeletonTable): void {+ const tableRows = tableSkeleton.tableSource?.tableRows ?? [];+ if (tableRows.length === 0) {+ return;+ }++ const skeletonRowsByIndex = new Map(tableSkeleton.rows.map((row) => [row.index, row]));++ tableRows.forEach((rowSource, rowIndex) => {+ rowSource.tableCells.forEach((cellConfig, columnIndex) => {+ const rowSpan = cellConfig.rowSpan ?? 1;+ const columnSpan = cellConfig.columnSpan ?? 1;+ if (rowSpan <= 1 && columnSpan <= 1) {+ return;+ }++ const masterRow = skeletonRowsByIndex.get(rowIndex);+ const masterCell = masterRow?.cells[columnIndex];+ if (!masterCell || (masterCell as IDocumentSkeletonPage & { isMergedCellCovered?: boolean }).isMergedCellCovered) {+ return;+ }++ let pageHeight = 0;+ for (let row = rowIndex; row < rowIndex + rowSpan; row++) {+ pageHeight += skeletonRowsByIndex.get(row)?.height ?? 0;+ }++ if (pageHeight > 0) {+ masterCell.pageHeight = pageHeight;+ }+ });+ });+}++function createMergedAwareNullCellPage(+ ctx: ILayoutContext,+ sectionBreakConfig: ISectionBreakConfig,+ table: ITable,+ row: number,+ col: number,+ rowSkeleton: IDocumentSkeletonRow+): IDocumentSkeletonPage {+ const cellSkeleton = createNullCellPage(+ ctx,+ sectionBreakConfig,+ table,+ row,+ col+ ).page;++ cellSkeleton.parent = rowSkeleton;+ if (isCoveredTableCell(table.tableRows[row].tableCells[col])) {+ Object.assign(cellSkeleton, { isMergedCellCovered: true });+ }++ return cellSkeleton;+}++function shouldAdvanceTableCellLeft(table: ITable, row: number, col: number): boolean {+ const cellConfig = table.tableRows[row]?.tableCells[col];+ if (!isCoveredTableCell(cellConfig)) {+ return true;+ }++ const masterCell = findMergedMasterCell(table, row, col);+ if (masterCell == null) {+ return true;+ }++ return masterCell.row !== row;+}++function findMergedMasterCell(table: ITable, row: number, col: number): Nullable<{ row: number; col: number }> {+ for (let rowIndex = 0; rowIndex <= row; rowIndex++) {+ const rowSource = table.tableRows[rowIndex];+ if (rowSource == null) {+ continue;+ }++ for (let columnIndex = 0; columnIndex < rowSource.tableCells.length; columnIndex++) {+ const cellConfig = rowSource.tableCells[columnIndex];+ if (isCoveredTableCell(cellConfig)) {+ continue;+ }++ const rowSpan = Math.max(1, cellConfig.rowSpan ?? 1);+ const columnSpan = Math.max(1, cellConfig.columnSpan ?? 1);+ if (rowSpan <= 1 && columnSpan <= 1) {+ continue;+ }++ const containsRow = row >= rowIndex && row < rowIndex + rowSpan;+ const containsColumn = col >= columnIndex && col < columnIndex + columnSpan;+ if (containsRow && containsColumn) {+ return { row: rowIndex, col: columnIndex };+ }+ }+ }++ return null;+}++function isCoveredTableCell(cellConfig: ITableCell | undefined): boolean {+ return cellConfig?.rowSpan === 0 || cellConfig?.columnSpan === 0;+}+function _getTableLeft(pageWidth: number, tableWidth: number, align: TableAlignmentType, indent: INumberUnit = { v: 0 }) {switch (align) {case TableAlignmentType.START: {diff --git a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts b/packages/engine-render/src/components/docs/layout/doc-skeleton.tsindex 80c54095f3..caad2517b1 100644--- a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts+++ b/packages/engine-render/src/components/docs/layout/doc-skeleton.ts@@ -29,8 +29,10 @@ import { PRESET_LIST_TYPE, SectionType, Skeleton } from '@univerjs/core';import { Subject } from 'rxjs';import { DocumentSkeletonPageType, GlyphType, LineType, PageLayoutType } from '../../../basics/i-document-skeleton-cached';import { Liquid } from '../liquid';+import { getDocsTableRenderViewport } from '../table-render-viewport';import { DocumentEditArea } from '../view-model/document-view-model';import { dealWithSection } from './block/section';+import { getTableIdAndSliceIndex } from './block/table';import { Hyphen } from './hyphenation/hyphen';import { LanguageDetector } from './hyphenation/language-detector';import { createSkeletonPage } from './model/page';@@ -884,11 +886,24 @@ export class DocumentSkeleton extends Skeleton {let exactMatch = null;if (skeTables.size > 0) {+ const unitId = this._docViewModel.getDataModel().getUnitId?.() ?? '';for (const table of skeTables.values()) {const { top: tableTop, left: tableLeft, rows } = table;+ const sourceTableId = getTableIdAndSliceIndex(table.tableId).tableId;+ const viewport = getDocsTableRenderViewport(unitId, sourceTableId);this._findLiquid?.translateSave();this._findLiquid?.translate(tableLeft, tableTop);+ if (viewport && viewport.contentWidth > viewport.viewportWidth) {+ const visibleLeft = this._findLiquid.x;+ const visibleRight = visibleLeft + viewport.viewportWidth;+ if (x < visibleLeft || x > visibleRight) {+ this._findLiquid?.translateRestore();+ continue;+ }++ this._findLiquid?.translate(-viewport.scrollLeft, 0);+ }for (const row of rows) {const { top: rowTop, cells, isRepeatRow } = row;diff --git a/packages/engine-render/src/components/docs/layout/model/__tests__/page.spec.ts b/packages/engine-render/src/components/docs/layout/model/__tests__/page.spec.tsindex 236b7a533f..92cdb7932e 100644--- a/packages/engine-render/src/components/docs/layout/model/__tests__/page.spec.ts+++ b/packages/engine-render/src/components/docs/layout/model/__tests__/page.spec.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import { BooleanNumber, ColumnSeparatorType, PageOrientType } from '@univerjs/core';+import { BooleanNumber, ColumnSeparatorType, PageOrientType, PositionedObjectLayoutType } from '@univerjs/core';import { describe, expect, it, vi } from 'vitest';import { DocumentSkeletonPageType } from '../../../../../basics/i-document-skeleton-cached';@@ -22,6 +22,7 @@ import {createNullCellPage,createSkeletonCellPages,createSkeletonPage,+ expandCellPageHeightForInlineDrawings,} from '../page';const dealWithSectionMock = vi.fn();@@ -210,4 +211,134 @@ describe('page model', () => {expect(updateBlockIndexMock).toHaveBeenCalled();expect(updateInlineDrawingCoordsAndBorderMock).toHaveBeenCalled();});++ it('adds trailing block range spacing to table cell height when the block range is the last cell element', () => {+ dealWithSectionMock.mockImplementation((_ctx: any, _vm: any, _node: any, areaPage: any) => ({+ pages: [{+ ...areaPage,+ height: 20,+ sections: [+ {+ columns: [+ {+ lines: [{ paragraphIndex: 12, spaceBelowApply: 28 }],+ },+ ],+ },+ ],+ skeDrawings: new Map(),+ skeTables: new Map(),+ }],+ }));++ const ctx = {+ dataModel: {+ getBody: () => ({+ blockRanges: [{ blockId: 'callout-1', blockType: 'callout', startIndex: 10, endIndex: 14 }],+ paragraphs: [{ startIndex: 12 }],+ }),+ },+ layoutStartPointer: {},+ skeletonResourceReference: createSkeletonResourceReference(),+ isDirty: false,+ } as any;+ const pages = createSkeletonCellPages(+ ctx,+ {} as any,+ { startIndex: 9, endIndex: 16, children: [{}] } as any,+ {+ columnProperties: [],+ columnSeparatorType: ColumnSeparatorType.NONE,+ sectionType: 0,+ startIndex: 0,+ } as any,+ {+ tableId: 'table-1',+ tableRows: [{ tableCells: [{}] }],+ tableColumns: [{ size: { width: { v: 80 } } }],+ } as any,+ 0,+ 0+ );++ expect(pages[0].height).toBe(48);+ });++ it('expands table cell height to include inline drawings', () => {+ const page = {+ height: 20,+ skeDrawings: new Map([+ ['shape-1', {+ aTop: 6,+ height: 48,+ drawingOrigin: {+ layoutType: PositionedObjectLayoutType.INLINE,+ },+ }],+ ['float-1', {+ aTop: 10,+ height: 100,+ drawingOrigin: {+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,+ },+ }],+ ]),+ };++ expandCellPageHeightForInlineDrawings([page as never]);++ expect(page.height).toBe(54);+ });++ it('does not add trailing block range spacing when content follows in the cell', () => {+ dealWithSectionMock.mockImplementation((_ctx: any, _vm: any, _node: any, areaPage: any) => ({+ pages: [{+ ...areaPage,+ height: 20,+ sections: [+ {+ columns: [+ {+ lines: [{ paragraphIndex: 12, spaceBelowApply: 28 }],+ },+ ],+ },+ ],+ skeDrawings: new Map(),+ skeTables: new Map(),+ }],+ }));++ const ctx = {+ dataModel: {+ getBody: () => ({+ blockRanges: [{ blockId: 'callout-1', blockType: 'callout', startIndex: 10, endIndex: 14 }],+ paragraphs: [{ startIndex: 12 }, { startIndex: 15 }],+ }),+ },+ layoutStartPointer: {},+ skeletonResourceReference: createSkeletonResourceReference(),+ isDirty: false,+ } as any;+ const pages = createSkeletonCellPages(+ ctx,+ {} as any,+ { startIndex: 9, endIndex: 16, children: [{}] } as any,+ {+ columnProperties: [],+ columnSeparatorType: ColumnSeparatorType.NONE,+ sectionType: 0,+ startIndex: 0,+ } as any,+ {+ tableId: 'table-1',+ tableRows: [{ tableCells: [{}] }],+ tableColumns: [{ size: { width: { v: 80 } } }],+ } as any,+ 0,+ 0+ );++ expect(pages[0].height).toBe(20);+ });});diff --git a/packages/engine-render/src/components/docs/layout/model/glyph.ts b/packages/engine-render/src/components/docs/layout/model/glyph.tsindex dde6b7bbbe..b5e878f15b 100644--- a/packages/engine-render/src/components/docs/layout/model/glyph.ts+++ b/packages/engine-render/src/components/docs/layout/model/glyph.ts@@ -155,6 +155,8 @@ export function _createSkeletonWordOrLetter(DT.TABLE_ROW_END,DT.TABLE_CELL_START,DT.TABLE_CELL_END,+ DT.BLOCK_START,+ DT.BLOCK_END,DT.CUSTOM_RANGE_START,DT.CUSTOM_RANGE_END,DT.COLUMN_BREAK,diff --git a/packages/engine-render/src/components/docs/layout/model/page.ts b/packages/engine-render/src/components/docs/layout/model/page.tsindex d3d4ff1a88..2df0110220 100644--- a/packages/engine-render/src/components/docs/layout/model/page.ts+++ b/packages/engine-render/src/components/docs/layout/model/page.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { ITable, Nullable } from '@univerjs/core';+import type { IDocumentBody, ITable, Nullable } from '@univerjs/core';import type {IDocumentSkeletonHeaderFooter,IDocumentSkeletonPage,@@ -24,7 +24,7 @@ import type { ISectionBreakConfig } from '../../../../basics/interfaces';import type { DataStreamTreeNode } from '../../view-model/data-stream-tree-node';import type { DocumentViewModel } from '../../view-model/document-view-model';import type { ILayoutContext } from '../tools';-import { BooleanNumber, PageOrientType } from '@univerjs/core';+import { BooleanNumber, PageOrientType, PositionedObjectLayoutType } from '@univerjs/core';import { BreakType, DocumentSkeletonPageType } from '../../../../basics/i-document-skeleton-cached';import { dealWithSection } from '../block/section';import { resetContext, updateBlockIndex, updateInlineDrawingCoordsAndBorder } from '../tools';@@ -305,7 +305,10 @@ export function createNullCellPage(top = { v: 5 },bottom = { v: 5 },} = cellConfig.margin ?? cellMargin ?? {};- const pageWidth = tableColumns[col].size.width.v;+ const columnSpan = Math.max(1, cellConfig.columnSpan ?? 1);+ const pageWidth = tableColumns+ .slice(col, col + columnSpan)+ .reduce((sum, column) => sum + column.size.width.v, 0);const pageHeight = maxCellPageHeight;const cellSectionBreakConfig: ISectionBreakConfig = {@@ -383,11 +386,57 @@ export function createSkeletonCellPages(updateBlockIndex(pages, cellNode.startIndex);+ applyTrailingCellBlockRangeSpaceBelow(pages, ctx.dataModel?.getBody?.(), cellNode.endIndex);+updateInlineDrawingCoordsAndBorder(ctx, pages);+ expandCellPageHeightForInlineDrawings(pages);return pages;}+export function expandCellPageHeightForInlineDrawings(pages: IDocumentSkeletonPage[]) {+ for (const page of pages) {+ page.skeDrawings?.forEach((drawing) => {+ if (drawing.drawingOrigin?.layoutType !== PositionedObjectLayoutType.INLINE) {+ return;+ }++ const drawingBottom = (drawing.aTop ?? 0) + (drawing.height ?? 0);+ if (drawingBottom > page.height) {+ page.height = drawingBottom;+ }+ });+ }+}++function applyTrailingCellBlockRangeSpaceBelow(pages: IDocumentSkeletonPage[], body: Nullable<IDocumentBody>, cellEndIndex: number) {+ const blockRanges = body?.blockRanges;+ const trailingBlockRangeSpace = 28;+ if (!blockRanges?.length) {+ return;+ }++ for (const page of pages) {+ const lastLine = page.sections.at(-1)?.columns.at(-1)?.lines.at(-1);+ if (!lastLine) {+ continue;+ }++ const paragraphIndex = lastLine.paragraphIndex;+ const isBlockRangeParagraph = blockRanges.some((range) => range.startIndex < paragraphIndex && paragraphIndex < range.endIndex);+ if (!isBlockRangeParagraph) {+ continue;+ }++ const hasLaterParagraphInCell = body?.paragraphs?.some((paragraph) => paragraph.startIndex > paragraphIndex && paragraph.startIndex < cellEndIndex);+ if (hasLaterParagraphInCell) {+ continue;+ }++ page.height += lastLine.spaceBelowApply || trailingBlockRangeSpace;+ }+}+function _getVerticalMargin(marginTB: number,headerOrFooter: Nullable<IDocumentSkeletonHeaderFooter>,diff --git a/packages/engine-render/src/components/docs/layout/tools.ts b/packages/engine-render/src/components/docs/layout/tools.tsindex 1b095c0549..89c945bee4 100644--- a/packages/engine-render/src/components/docs/layout/tools.ts+++ b/packages/engine-render/src/components/docs/layout/tools.ts@@ -54,6 +54,9 @@ import {GridType,HorizontalAlign,mergeWith,+ MODERN_DOCUMENT_DEFAULT_MARGIN,+ MODERN_DOCUMENT_WIDTH,+ ModernDocumentWidthMode,NAMED_STYLE_MAP,NumberUnitType,ObjectMatrix,@@ -67,7 +70,7 @@ import {} from '@univerjs/core';import { DEFAULT_DOCUMENT_FONTSIZE } from '../../../basics/const';import { GlyphType } from '../../../basics/i-document-skeleton-cached';-import { getFontStyleString, isFunction, ptToPixel } from '../../../basics/tools';+import { getFontStyleString, isFunction } from '../../../basics/tools';import { updateInlineDrawingPosition } from './block/paragraph/layout-ruler';import { getCustomDecorationStyle } from './style/custom-decoration';import { getCustomRangeStyle } from './style/custom-range';@@ -988,13 +991,13 @@ export const DEFAULT_PAGE_SIZE = { width: Number.POSITIVE_INFINITY, height: Numbconst DEFAULT_MODERN_DOCUMENT_STYLE: IDocumentStyle = {pageNumberStart: 1,pageSize: {- width: ptToPixel(595),+ width: MODERN_DOCUMENT_WIDTH[ModernDocumentWidthMode.MEDIUM],height: Number.POSITIVE_INFINITY,},- marginTop: ptToPixel(50),- marginBottom: ptToPixel(50),- marginRight: ptToPixel(50),- marginLeft: ptToPixel(50),+ marginTop: MODERN_DOCUMENT_DEFAULT_MARGIN,+ marginBottom: MODERN_DOCUMENT_DEFAULT_MARGIN,+ marginRight: MODERN_DOCUMENT_DEFAULT_MARGIN,+ marginLeft: MODERN_DOCUMENT_DEFAULT_MARGIN,renderConfig: {vertexAngle: 0,centerAngle: 0,@@ -1030,8 +1033,14 @@ export function prepareSectionBreakConfig(ctx: ILayoutContext, nodeIndex: number// If the configuration is in modern mode, use the style configuration of modern mode to overwrite the original configuration.// In modern mode, there are no pages, no sections, no columns. There are no headers and footers, and margins are all defaults.if (documentFlavor === DocumentFlavor.MODERN) {+ const modernPageWidth = documentStyle.pageSize?.width ?? DEFAULT_MODERN_DOCUMENT_STYLE.pageSize!.width;sectionBreak = Object.assign({}, sectionBreak, DEFAULT_MODERN_SECTION_BREAK);- documentStyle = Object.assign({}, documentStyle, DEFAULT_MODERN_DOCUMENT_STYLE);+ documentStyle = Object.assign({}, documentStyle, DEFAULT_MODERN_DOCUMENT_STYLE, {+ pageSize: {+ ...DEFAULT_MODERN_DOCUMENT_STYLE.pageSize!,+ width: modernPageWidth,+ },+ });}const {diff --git a/packages/engine-render/src/components/docs/table-render-viewport.ts b/packages/engine-render/src/components/docs/table-render-viewport.tsnew file mode 100644index 0000000000..7b5448b678--- /dev/null+++ b/packages/engine-render/src/components/docs/table-render-viewport.ts@@ -0,0 +1,33 @@+/**+ * 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.+ */++export interface IDocsTableRenderViewport {+ contentWidth: number;+ scrollLeft: number;+ viewportWidth: number;+}++export type DocsTableRenderViewportProvider = (unitId: string, tableId: string) => IDocsTableRenderViewport | null | undefined;++let docsTableRenderViewportProvider: DocsTableRenderViewportProvider | null = null;++export function setDocsTableRenderViewportProvider(provider: DocsTableRenderViewportProvider | null): void {+ docsTableRenderViewportProvider = provider;+}++export function getDocsTableRenderViewport(unitId: string, tableId: string): IDocsTableRenderViewport | null {+ return docsTableRenderViewportProvider?.(unitId, tableId) ?? null;+}diff --git a/packages/engine-render/src/components/docs/view-model/__tests__/document-view-model.spec.ts b/packages/engine-render/src/components/docs/view-model/__tests__/document-view-model.spec.tsindex a407c3d4a9..18a2045794 100644--- a/packages/engine-render/src/components/docs/view-model/__tests__/document-view-model.spec.ts+++ b/packages/engine-render/src/components/docs/view-model/__tests__/document-view-model.spec.ts@@ -123,6 +123,65 @@ describe('DocumentViewModel', () => {.find((paragraph) => paragraph.blocks.length > 0);expect(paragraphWithCustomBlock?.blocks.length).toBe(1);});++ it('should ignore block range tokens while preserving inner paragraphs', () => {+ const ds = [+ DataStreamTreeTokenType.BLOCK_START,+ 'Callout',+ DataStreamTreeTokenType.PARAGRAPH,+ 'Content',+ DataStreamTreeTokenType.PARAGRAPH,+ DataStreamTreeTokenType.BLOCK_END,+ DataStreamTreeTokenType.SECTION_BREAK,+ ].join('');++ const { sectionList } = parseDataStreamToTree(ds);+ const paragraphs = sectionList[0].children;++ expect(paragraphs.map((paragraph) => paragraph.content)).toEqual([+ `${DataStreamTreeTokenType.BLOCK_START}Callout${DataStreamTreeTokenType.PARAGRAPH}`,+ `Content${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.BLOCK_END}${DataStreamTreeTokenType.SECTION_BREAK}`,+ ]);+ });++ it('keeps hidden block tokens in paragraph content so following offsets stay aligned', () => {+ const ds = [+ 'A',+ DataStreamTreeTokenType.PARAGRAPH,+ DataStreamTreeTokenType.BLOCK_START,+ 'B',+ DataStreamTreeTokenType.PARAGRAPH,+ DataStreamTreeTokenType.BLOCK_END,+ 'C',+ DataStreamTreeTokenType.PARAGRAPH,+ DataStreamTreeTokenType.SECTION_BREAK,+ ].join('');++ const { sectionList } = parseDataStreamToTree(ds);+ const paragraphs = sectionList[0].children;++ expect(paragraphs.map((paragraph) => ({+ content: paragraph.content,+ startIndex: paragraph.startIndex,+ endIndex: paragraph.endIndex,+ }))).toEqual([+ {+ content: `A${DataStreamTreeTokenType.PARAGRAPH}`,+ startIndex: 0,+ endIndex: 1,+ },+ {+ content: `${DataStreamTreeTokenType.BLOCK_START}B${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.BLOCK_END}`,+ startIndex: 2,+ endIndex: 4,+ },+ {+ content: `C${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}`,+ startIndex: 6,+ endIndex: 7,+ },+ ]);+ });});describe('DocumentViewModel class', () => {diff --git a/packages/engine-render/src/components/docs/view-model/document-view-model.ts b/packages/engine-render/src/components/docs/view-model/document-view-model.tsindex 6fcba6b648..fe2ac72ab5 100644--- a/packages/engine-render/src/components/docs/view-model/document-view-model.ts+++ b/packages/engine-render/src/components/docs/view-model/document-view-model.ts@@ -73,6 +73,18 @@ export function parseDataStreamToTree(dataStream: string, tables?: ICustomTable[const tableCellList: DataStreamTreeNode[] = [];const currentBlocks: number[] = [];+ const getParagraphList = () => tableCellList.length > 0 ? cellParagraphList : paragraphList;+ const appendToPreviousParagraph = (char: string) => {+ const tempParagraphList = getParagraphList();+ const lastParagraph = tempParagraphList[tempParagraphList.length - 1];+ if (lastParagraph) {+ lastParagraph.content = `${lastParagraph.content ?? ''}${char}`;+ return true;+ }++ return false;+ };+for (let i = 0; i < dataStreamLen; i++) {const char = dataStream[i];@@ -164,6 +176,12 @@ export function parseDataStreamToTree(dataStream: string, tables?: ICustomTable[const lastRow = tableRowList[tableRowList.length - 1];batchParent(lastRow, [cellNode!], DataStreamTreeNodeType.TABLE_ROW);+ } else if (char === DataStreamTreeTokenType.BLOCK_START) {+ content += char;+ } else if (char === DataStreamTreeTokenType.BLOCK_END) {+ if (content.length > 0 || !appendToPreviousParagraph(char)) {+ content += char;+ }} else if (char === DataStreamTreeTokenType.CUSTOM_BLOCK) {currentBlocks.push(i);content += char;diff --git a/packages/engine-render/src/components/sheets/util.ts b/packages/engine-render/src/components/sheets/util.tsindex 2e6d0ee2d5..1ce89dde85 100644--- a/packages/engine-render/src/components/sheets/util.ts+++ b/packages/engine-render/src/components/sheets/util.ts@@ -15,7 +15,7 @@*/import type { CellValueType, IDocumentData, IPaddingData, IStyleBase, IStyleData, ITextRotation, ITextStyle, Nullable, TextDirection } from '@univerjs/core';-import { DEFAULT_EMPTY_DOCUMENT_VALUE, DocumentDataModel, HorizontalAlign, VerticalAlign, WrapStrategy } from '@univerjs/core';+import { DEFAULT_EMPTY_DOCUMENT_VALUE, DocumentDataModel, DocumentFlavor, HorizontalAlign, VerticalAlign, WrapStrategy } from '@univerjs/core';import { convertTextRotation } from '../../basics/text-rotation';import { DEFAULT_PADDING_DATA } from './sheet.render-skeleton';@@ -70,10 +70,12 @@ export function createDocumentModelWithStyle(content: string, textStyle: ITextStwidth: Number.POSITIVE_INFINITY,height: Number.POSITIVE_INFINITY,},+ documentFlavor: DocumentFlavor.UNSPECIFIED,marginTop,marginBottom,marginRight,marginLeft,+ paragraphLineGapDefault: 0,renderConfig: {horizontalAlign,verticalAlign,diff --git a/packages/engine-render/src/index.ts b/packages/engine-render/src/index.tsindex 65e412ca3c..b3f88f9dfb 100644--- a/packages/engine-render/src/index.ts+++ b/packages/engine-render/src/index.ts@@ -30,6 +30,8 @@ export type { IFindNodeRestrictions } from './components/docs/layout/doc-skeletoexport { getCharSpaceApply, getLastLine, getNumberUnitValue, getPageFromPath, glyphIterator, lineIterator } from './components/docs/layout/tools';export { getLastColumn } from './components/docs/layout/tools';export { Liquid } from './components/docs/liquid';+export type { DocsTableRenderViewportProvider, IDocsTableRenderViewport } from './components/docs/table-render-viewport';+export { getDocsTableRenderViewport, setDocsTableRenderViewportProvider } from './components/docs/table-render-viewport';export { DataStreamTreeNode } from './components/docs/view-model/data-stream-tree-node';export { DocumentViewModel } from './components/docs/view-model/document-view-model';export { DocumentEditArea } from './components/docs/view-model/document-view-model';diff --git a/packages/engine-render/src/viewport.ts b/packages/engine-render/src/viewport.tsindex 4f0ec1663e..7285e37b76 100644--- a/packages/engine-render/src/viewport.ts+++ b/packages/engine-render/src/viewport.ts@@ -108,6 +108,7 @@ export interface IViewportReSizeParam {}const MOUSE_WHEEL_SPEED_SMOOTHING_FACTOR = 3;+const WHEEL_CROSS_AXIS_LOCK_RATIO = 2;export class Viewport {private _viewportKey: string = '';@@ -974,14 +975,26 @@ export class Viewport {let offsetY = 0;const allWidth = this._scene.width;const viewWidth = this.width || 1;- offsetX = (viewWidth / allWidth) * evt.deltaX;+ const scaleX = Math.abs(this._scene.scaleX) || 1;+ const scaleY = Math.abs(this._scene.scaleY) || 1;+ const rawOffsetX = evt.deltaX / scaleX;+ const rawOffsetY = evt.deltaY / scaleY;+ offsetX = (viewWidth / allWidth) * rawOffsetX;const allHeight = this._scene.height;const viewHeight = this.height || 1;if (evt.shiftKey) {- offsetX = (viewHeight / allHeight) * evt.deltaY * MOUSE_WHEEL_SPEED_SMOOTHING_FACTOR;+ offsetX = ((viewHeight / allHeight) * evt.deltaY * MOUSE_WHEEL_SPEED_SMOOTHING_FACTOR) / scaleX;} else {- offsetY = (viewHeight / allHeight) * evt.deltaY;+ offsetY = (viewHeight / allHeight) * rawOffsetY;++ const absOffsetX = Math.abs(rawOffsetX);+ const absOffsetY = Math.abs(rawOffsetY);+ if (absOffsetY >= absOffsetX * WHEEL_CROSS_AXIS_LOCK_RATIO) {+ offsetX = 0;+ } else if (absOffsetX >= absOffsetY * WHEEL_CROSS_AXIS_LOCK_RATIO) {+ offsetY = 0;+ }}const isLimitedStore = this.scrollByBarDeltaValue({diff --git a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx b/packages/sheets-formula-ui/src/views/formula-editor/index.tsxindex 12b67ba920..944b2884df 100644--- a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx+++ b/packages/sheets-formula-ui/src/views/formula-editor/index.tsx@@ -24,11 +24,14 @@ import type { IRefSelection } from './hooks/use-highlight';import {BuildTextUtils,createInternalEditorID,+ DocumentFlavor,generateRandomId,+ HorizontalAlign,IConfigService,IUniverInstanceService,noop,UniverInstanceType,+ VerticalAlign,} from '@univerjs/core';import { clsx } from '@univerjs/design';import { DocBackScrollRenderController, DocSelectionRenderService, IEditorService, useKeyboardEvent, useResize } from '@univerjs/docs-ui';@@ -80,6 +83,11 @@ export interface IFormulaEditorProps {disableSelectionOnClick?: boolean;disableContextMenu?: boolean;style?: CSSProperties;+ borderless?: boolean;+ canvasStyle?: {+ backgroundColor?: string;+ fontSize?: number;+ };}export interface IFormulaEditorRef {@@ -111,6 +119,8 @@ export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IFautofocus = true,disableContextMenu,style,+ borderless = false,+ canvasStyle,} = props;const editorService = useDependency(IEditorService);@@ -236,7 +246,26 @@ export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IFcustomDecorations: [],customRanges: [],},- documentStyle: {},+ documentStyle: {+ pageSize: {+ width: Number.POSITIVE_INFINITY,+ height: Number.POSITIVE_INFINITY,+ },+ documentFlavor: DocumentFlavor.UNSPECIFIED,+ marginTop: 0,+ marginBottom: 0,+ marginRight: 0,+ marginLeft: 0,+ paragraphLineGapDefault: 0,+ renderConfig: {+ horizontalAlign: HorizontalAlign.UNSPECIFIED,+ verticalAlign: VerticalAlign.TOP,+ },+ },+ },+ canvasStyle: {+ ...canvasStyle,+ backgroundColor: canvasStyle?.backgroundColor ?? '#fff',},}, formulaEditorContainerRef.current);const editor = editorService.getEditor(editorId)! as Editor;@@ -349,10 +378,11 @@ export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IFref={sheetEmbeddingRef}className={clsx(`univer-relative univer-box-border univer-flex univer-size-full univer-items-center- univer-justify-around univer-gap-2 univer-rounded-none univer-p-0 univer-ring-1+ univer-justify-around univer-gap-2 univer-rounded-none univer-p-0`, {- 'univer-ring-primary-500': isFocus,- 'univer-ring-red-500': isError,+ 'univer-ring-1': !borderless,+ 'univer-ring-primary-500': isFocus && !borderless,+ 'univer-ring-red-500': isError && !borderless,})}><divdiff --git a/packages/sheets-ui/src/controllers/editor/__tests__/end-edit.controller.spec.ts b/packages/sheets-ui/src/controllers/editor/__tests__/end-edit.controller.spec.tsindex a0c82fab98..56a99ccc71 100644--- a/packages/sheets-ui/src/controllers/editor/__tests__/end-edit.controller.spec.ts+++ b/packages/sheets-ui/src/controllers/editor/__tests__/end-edit.controller.spec.ts@@ -16,7 +16,7 @@import type { ICellData, IDocumentData, Univer, Workbook } from '@univerjs/core';import type { IFunctionService } from '@univerjs/engine-formula';-import { CellValueType, DEFAULT_TEXT_FORMAT_EXCEL, IConfigService, IContextService, Injector, LocaleService, LocaleType, Tools } from '@univerjs/core';+import { CellValueType, DEFAULT_TEXT_FORMAT_EXCEL, DocumentFlavor, IConfigService, IContextService, Injector, LocaleService, LocaleType, Tools } from '@univerjs/core';import { LexerTreeBuilder } from '@univerjs/engine-formula';import { SpreadsheetSkeleton } from '@univerjs/engine-render';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -56,6 +56,7 @@ const richTextDemo: IDocumentData = {width: Number.POSITIVE_INFINITY,height: Number.POSITIVE_INFINITY,},+ documentFlavor: DocumentFlavor.UNSPECIFIED,renderConfig: {centerAngle: 0,horizontalAlign: 0,@@ -68,6 +69,7 @@ const richTextDemo: IDocumentData = {marginBottom: 2,marginRight: 2,marginLeft: 2,+ paragraphLineGapDefault: 0,},};@@ -332,10 +334,12 @@ describe('Test EndEditController', () => {width: Infinity,height: Infinity,},+ documentFlavor: DocumentFlavor.UNSPECIFIED,marginTop: 0,marginBottom: 2,marginRight: 2,marginLeft: 2,+ paragraphLineGapDefault: 0,renderConfig: {horizontalAlign: 0,verticalAlign: 0,diff --git a/packages/sheets-ui/src/controllers/render-controllers/__tests__/scroll.render-controller.spec.ts b/packages/sheets-ui/src/controllers/render-controllers/__tests__/scroll.render-controller.spec.tsindex a99b55c0ea..78268b7c63 100644--- a/packages/sheets-ui/src/controllers/render-controllers/__tests__/scroll.render-controller.spec.ts+++ b/packages/sheets-ui/src/controllers/render-controllers/__tests__/scroll.render-controller.spec.ts@@ -62,11 +62,11 @@ describe('SheetsScrollRenderController', () => {const preventDefault = vi.fn();scene.onMouseWheel$.emit(- { ctrlKey: false, shiftKey: false, deltaX: 5, deltaY: 10, preventDefault },+ { ctrlKey: false, shiftKey: false, deltaX: 7, deltaY: 10, preventDefault },{ stopPropagation: () => { } });- expect(executeSpy).toHaveBeenCalledWith(SetScrollRelativeCommand.id, { offsetX: 5, offsetY: 10 });+ expect(executeSpy).toHaveBeenCalledWith(SetScrollRelativeCommand.id, { offsetX: 7, offsetY: 10 });// Avoid disposing here: faked render context does not implement all IDisposable contracts.void _controller;@@ -103,6 +103,59 @@ describe('SheetsScrollRenderController', () => {void controller;});+ it('normalizes wheel scroll offsets by sheet zoom ratio', () => {+ const scrollManagerService = createScrollManagerServiceMock();+ const testBed = createRenderTestBed({+ dependencies: [[SheetScrollManagerService, { useValue: scrollManagerService }]],+ });+ const { context, scene, contextService } = testBed;+ const commandService = testBed.get(ICommandService);+ const executeSpy = vi.spyOn(commandService, 'executeCommand');++ contextService.setContextValue(FOCUSING_SHEET, true);+ scene.scale(2, 2);++ const controller = testBed.injector.createInstance(SheetsScrollRenderController, context as any);+ const preventDefault = vi.fn();++ scene.onMouseWheel$.emit(+ { ctrlKey: false, shiftKey: false, deltaX: 12, deltaY: 20, preventDefault },+ { stopPropagation: () => { } }+ );++ expect(executeSpy).toHaveBeenCalledWith(SetScrollRelativeCommand.id, { offsetX: 6, offsetY: 10 });+ void controller;+ });++ it('locks out minor cross-axis touchpad jitter while wheel scrolling', () => {+ const scrollManagerService = createScrollManagerServiceMock();+ const testBed = createRenderTestBed({+ dependencies: [[SheetScrollManagerService, { useValue: scrollManagerService }]],+ });+ const { context, scene, contextService } = testBed;+ const commandService = testBed.get(ICommandService);+ const executeSpy = vi.spyOn(commandService, 'executeCommand');++ contextService.setContextValue(FOCUSING_SHEET, true);++ const controller = testBed.injector.createInstance(SheetsScrollRenderController, context as any);+ const preventDefault = vi.fn();++ scene.onMouseWheel$.emit(+ { ctrlKey: false, shiftKey: false, deltaX: 8, deltaY: 20, preventDefault },+ { stopPropagation: () => { } }+ );+ scene.onMouseWheel$.emit(+ { ctrlKey: false, shiftKey: false, deltaX: 20, deltaY: 8, preventDefault },+ { stopPropagation: () => { } }+ );++ expect(executeSpy).toHaveBeenNthCalledWith(1, SetScrollRelativeCommand.id, { offsetX: 0, offsetY: 20 });+ expect(executeSpy).toHaveBeenNthCalledWith(2, SetScrollRelativeCommand.id, { offsetX: 20, offsetY: 0 });++ void controller;+ });+it('updates scroll state from viewport events and executes ScrollCommand when scrolling bar', () => {const scrollManagerService = createScrollManagerServiceMock();const testBed = createRenderTestBed({diff --git a/packages/sheets-ui/src/controllers/render-controllers/scroll.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/scroll.render-controller.tsindex f14e0b6c29..85e13aa834 100644--- a/packages/sheets-ui/src/controllers/render-controllers/scroll.render-controller.ts+++ b/packages/sheets-ui/src/controllers/render-controllers/scroll.render-controller.ts@@ -41,6 +41,7 @@ import { SheetSkeletonManagerService } from '../../services/sheet-skeleton-managimport { getSheetObject } from '../utils/component-tools';const MOUSE_WHEEL_SPEED_SMOOTHING_FACTOR = 3;+const WHEEL_CROSS_AXIS_LOCK_RATIO = 2;/*** This controller handles scroll logic in sheet interaction.*/@@ -77,19 +78,29 @@ export class SheetsScrollRenderController extends Disposable implements IRenderMlet offsetX = 0;let offsetY = 0;+ const scaleX = Math.abs(scene.scaleX) || 1;+ const scaleY = Math.abs(scene.scaleY) || 1;// what????// const scrollNum = Math.abs(evt.deltaX);// offsetX = evt.deltaX > 0 ? scrollNum : -scrollNum;- offsetX = evt.deltaX;+ offsetX = evt.deltaX / scaleX;// with shift, scrollY will be scrollXif (evt.shiftKey) {// mac is weird, when using track pad, scroll vertical with shift key, should get delta value from deltaY.// but when using with mousewheel, scroll with shift key, only deltaX has value.- offsetX = (evt.deltaY || evt.deltaX) * MOUSE_WHEEL_SPEED_SMOOTHING_FACTOR;+ offsetX = ((evt.deltaY || evt.deltaX) * MOUSE_WHEEL_SPEED_SMOOTHING_FACTOR) / scaleX;} else {- offsetY = evt.deltaY;+ offsetY = evt.deltaY / scaleY;++ const absOffsetX = Math.abs(offsetX);+ const absOffsetY = Math.abs(offsetY);+ if (absOffsetY >= absOffsetX * WHEEL_CROSS_AXIS_LOCK_RATIO) {+ offsetX = 0;+ } else if (absOffsetX >= absOffsetY * WHEEL_CROSS_AXIS_LOCK_RATIO) {+ offsetY = 0;+ }}this._commandService.executeCommand(SetScrollRelativeCommand.id, { offsetX, offsetY });this._context.scene.makeDirty(true);diff --git a/packages/sheets-ui/src/controllers/render-controllers/zoom.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/zoom.render-controller.tsindex 0e4d3f0114..0436ca73ef 100644--- a/packages/sheets-ui/src/controllers/render-controllers/zoom.render-controller.ts+++ b/packages/sheets-ui/src/controllers/render-controllers/zoom.render-controller.ts@@ -17,6 +17,7 @@import type { Workbook } from '@univerjs/core';import type { IRenderContext, IRenderModule, IWheelEvent } from '@univerjs/engine-render';import { Disposable, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, FOCUSING_SHEET, ICommandService, IContextService, Inject, Optional } from '@univerjs/core';+import { getNextWheelZoomRatio } from '@univerjs/engine-render';import { SetZoomRatioCommand } from '../../commands/commands/set-zoom-ratio.command';import { IEditorBridgeService } from '../../services/editor-bridge.service';import { SheetSkeletonManagerService } from '../../services/sheet-skeleton-manager.service';@@ -68,23 +69,15 @@ export class SheetsZoomRenderController extends Disposable implements IRenderMod}}- const deltaFactor = Math.abs(e.deltaX);- let ratioDelta = deltaFactor < 40 ? 0.2 : deltaFactor < 80 ? 0.4 : 0.2;- ratioDelta *= e.deltaY > 0 ? -1 : 1;- if (scene.scaleX < 1) {- ratioDelta /= 2;- }-const workbook = this._context.unit;const sheet = workbook.getActiveSheet();if (!sheet) return;const currentRatio = sheet.getZoomRatio();- let nextRatio = +Number.parseFloat(`${currentRatio + ratioDelta}`).toFixed(1);- nextRatio = nextRatio >= 4 ? 4 : nextRatio <= 0.1 ? 0.1 : nextRatio;+ const nextRatio = getNextWheelZoomRatio(currentRatio, e);this._commandService.executeCommand(SetZoomRatioCommand.id, {- zoomRatio: Math.round(nextRatio * 10) / 10,+ zoomRatio: nextRatio,unitId: workbook.getUnitId(),subUnitId: sheet.getSheetId(),});diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/__snapshots__/sheet-paste.spec.ts.snap b/packages/sheets-ui/src/services/clipboard/__tests__/__snapshots__/sheet-paste.spec.ts.snapindex d2ba98caa9..b7030982e0 100644--- a/packages/sheets-ui/src/services/clipboard/__tests__/__snapshots__/sheet-paste.spec.ts.snap+++ b/packages/sheets-ui/src/services/clipboard/__tests__/__snapshots__/sheet-paste.spec.ts.snap@@ -46,6 +46,7 @@ exports[`Test clipboard > Test paste > test convert util func from excel 1`] = `],},"documentStyle": {+ "documentFlavor": 0,"marginBottom": 2,"marginLeft": 2,"marginRight": 2,@@ -54,6 +55,7 @@ exports[`Test clipboard > Test paste > test convert util func from excel 1`] = `"height": Infinity,"width": Infinity,},+ "paragraphLineGapDefault": 0,"renderConfig": {"cellValueType": undefined,"centerAngle": 0,@@ -680,6 +682,7 @@ exports[`Test clipboard > Test paste > test convert util func from excel 1`] = `],},"documentStyle": {+ "documentFlavor": 0,"marginBottom": 2,"marginLeft": 2,"marginRight": 2,@@ -688,6 +691,7 @@ exports[`Test clipboard > Test paste > test convert util func from excel 1`] = `"height": Infinity,"width": Infinity,},+ "paragraphLineGapDefault": 0,"renderConfig": {"cellValueType": undefined,"centerAngle": 0,@@ -3368,6 +3372,7 @@ exports[`Test clipboard > Test paste > test convert util func from google 1`] =],},"documentStyle": {+ "documentFlavor": 0,"marginBottom": 2,"marginLeft": 2,"marginRight": 2,@@ -3376,6 +3381,7 @@ exports[`Test clipboard > Test paste > test convert util func from google 1`] ="height": Infinity,"width": Infinity,},+ "paragraphLineGapDefault": 0,"renderConfig": {"cellValueType": undefined,"centerAngle": 0,@@ -3574,6 +3580,7 @@ exports[`Test clipboard > Test paste > test convert util func from google 1`] ="textRuns": [],},"documentStyle": {+ "documentFlavor": 0,"marginBottom": 2,"marginLeft": 2,"marginRight": 2,@@ -3582,6 +3589,7 @@ exports[`Test clipboard > Test paste > test convert util func from google 1`] ="height": Infinity,"width": Infinity,},+ "paragraphLineGapDefault": 0,"renderConfig": {"cellValueType": undefined,"centerAngle": 0,@@ -4134,6 +4142,7 @@ exports[`Test clipboard > Test paste > test convert util func from google 1`] ="textRuns": [],},"documentStyle": {+ "documentFlavor": 0,"marginBottom": 2,"marginLeft": 2,"marginRight": 2,@@ -4142,6 +4151,7 @@ exports[`Test clipboard > Test paste > test convert util func from google 1`] ="height": Infinity,"width": Infinity,},+ "paragraphLineGapDefault": 0,"renderConfig": {"cellValueType": undefined,"centerAngle": 0,@@ -4233,6 +4243,7 @@ exports[`Test clipboard > Test paste > test convert util func from google 1`] =],},"documentStyle": {+ "documentFlavor": 0,"marginBottom": 2,"marginLeft": 2,"marginRight": 2,@@ -4241,6 +4252,7 @@ exports[`Test clipboard > Test paste > test convert util func from google 1`] ="height": Infinity,"width": Infinity,},+ "paragraphLineGapDefault": 0,"renderConfig": {"cellValueType": undefined,"centerAngle": 0,@@ -4678,6 +4690,7 @@ exports[`Test clipboard > Test paste > test convert util func from google 1`] ="textRuns": [],},"documentStyle": {+ "documentFlavor": 0,"marginBottom": 2,"marginLeft": 2,"marginRight": 2,@@ -4686,6 +4699,7 @@ exports[`Test clipboard > Test paste > test convert util func from google 1`] ="height": Infinity,"width": Infinity,},+ "paragraphLineGapDefault": 0,"renderConfig": {"cellValueType": undefined,"centerAngle": 0,@@ -4780,6 +4794,7 @@ exports[`Test clipboard > Test paste > test convert util func from google 1`] =],},"documentStyle": {+ "documentFlavor": 0,"marginBottom": 2,"marginLeft": 2,"marginRight": 2,@@ -4788,6 +4803,7 @@ exports[`Test clipboard > Test paste > test convert util func from google 1`] ="height": Infinity,"width": Infinity,},+ "paragraphLineGapDefault": 0,"renderConfig": {"cellValueType": undefined,"centerAngle": 0,diff --git a/packages/sheets-ui/src/services/utils/doc-skeleton-util.ts b/packages/sheets-ui/src/services/utils/doc-skeleton-util.tsindex d3356c0794..9eda9b4313 100644--- a/packages/sheets-ui/src/services/utils/doc-skeleton-util.ts+++ b/packages/sheets-ui/src/services/utils/doc-skeleton-util.ts@@ -74,6 +74,9 @@ const calcDocGlyphPosition = (glyph: IDocumentSkeletonGlyph, skeleton: DocumentSconst { borderBoxPointGroup } = convertor.getRangePointData(startPosition, startPosition);const bounds = getLineBounding(borderBoxPointGroup);const rect = bounds[0];+ if (!rect) {+ return;+ }return {top: rect.top,diff --git a/packages/sheets-ui/src/views/editor-container/EditorContainer.tsx b/packages/sheets-ui/src/views/editor-container/EditorContainer.tsxindex 9fb09fb5aa..d39709c441 100644--- a/packages/sheets-ui/src/views/editor-container/EditorContainer.tsx+++ b/packages/sheets-ui/src/views/editor-container/EditorContainer.tsx@@ -203,6 +203,7 @@ export const EditorContainer: React.FC<ICellIEditorProps> = () => {}}disableSelectionOnClickdisableContextMenu={false}+ canvasStyle={{ backgroundColor: 'transparent' }}/>)}</div>diff --git a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsxindex 48e9a3a04e..32b74af20b 100644--- a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx+++ b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx@@ -360,17 +360,18 @@ export function FormulaBar(props: IProps) {<div className="univer-flex univer-w-full univer-flex-1 univer-overflow-hidden univer-pl-3"><divref={ref}- className="univer-relative univer-flex-1"+ className="+ univer-relative univer-flex-1 univer-bg-white+ dark:!univer-bg-gray-900+ "onPointerDown={handlePointerDown}onPointerUp={handlePointerUp}style={{ pointerEvents: hideEditor ? 'none' : 'auto' }}>{FormulaEditor && (<FormulaEditor- className={`- univer-relative univer-size-full univer-break-words univer-outline-none- [&>div]:univer-ring-transparent- `}+ className="univer-relative univer-size-full univer-break-words univer-outline-none"+ borderlessdisableSelectionOnClickeditorId={DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY}initValue=""@@ -393,6 +394,7 @@ export function FormulaBar(props: IProps) {}}autoScrollbar={false}disableContextMenu={false}+ canvasStyle={{ backgroundColor: '#fff' }}/>)}{/* When the editor is hidden, we just cover a div on the editor because re-instantiatediff --git a/packages/ui/src/components/menu/desktop/DesignTinyMenuGroup.tsx b/packages/ui/src/components/menu/desktop/DesignTinyMenuGroup.tsxindex 001d588b8d..52e0910fa6 100644--- a/packages/ui/src/components/menu/desktop/DesignTinyMenuGroup.tsx+++ b/packages/ui/src/components/menu/desktop/DesignTinyMenuGroup.tsx@@ -21,6 +21,7 @@ export interface ITinyMenuItem {onClick: () => void;className: string;Icon: ComponentType<{ className?: string }>;+ iconClassName?: string;key: string;active?: boolean;tooltip?: string;@@ -50,10 +51,13 @@ export function DesignTinyMenuGroup({ items }: ITinyMenuGroupProps) {onClick={() => item.onClick()}><item.Icon- className={`- univer-size-4 univer-text-gray-900- dark:!univer-text-gray-200- `}+ className={clsx(+ `+ univer-size-4 univer-text-gray-900+ dark:!univer-text-gray-200+ `,+ item.iconClassName+ )}/></div>);diff --git a/packages/ui/src/components/menu/desktop/TinyMenuGroup.tsx b/packages/ui/src/components/menu/desktop/TinyMenuGroup.tsxindex 289801541a..b7efadfc7d 100644--- a/packages/ui/src/components/menu/desktop/TinyMenuGroup.tsx+++ b/packages/ui/src/components/menu/desktop/TinyMenuGroup.tsx@@ -18,7 +18,7 @@ import type { IDisplayMenuItem, IMenuItem, IValueOption } from '../../../serviceimport type { IMenuSchema } from '../../../services/menu/menu-manager.service';import { convertObservableToBehaviorSubject, LocaleService } from '@univerjs/core';import { clsx } from '@univerjs/design';-import { useEffect, useState } from 'react';+import { useEffect, useMemo, useState } from 'react';import { combineLatest, of } from 'rxjs';import { ComponentManager } from '../../../common';import { useDependency, useObservable } from '../../../utils/di';@@ -26,16 +26,38 @@ import { DesignTinyMenuGroup } from './DesignTinyMenuGroup';interface IUIQuickMenuGroupProps {item: IMenuSchema;+ activeItemIds?: string[];+ hiddenItemIds?: string[];onOptionSelect?: (option: IValueOption) => void;}interface IUIQuickTileMenuItemProps {menuSchema: IMenuSchema;+ activeItemIds?: string[];onOptionSelect?: (option: IValueOption) => void;}+const EMPTY_HIDDEN_ITEM_IDS: string[] = [];++export function resolveMenuItemActiveState(itemId: string | undefined, observableActive: boolean, activeItemIds?: string[]): boolean {+ if (activeItemIds) {+ return Boolean(itemId && activeItemIds.includes(itemId));+ }++ return observableActive;+}++function getTinyMenuChildStateKey(child: IMenuSchema): string {+ return child.item?.id ?? child.key;+}++export function getVisibleTinyMenuChildren(children: IMenuSchema[], hiddenItemKeys: string[]): IMenuSchema[] {+ const hiddenSet = new Set(hiddenItemKeys);+ return children.filter((child) => !hiddenSet.has(getTinyMenuChildStateKey(child)));+}+function QuickTileMenuItem(props: IUIQuickTileMenuItemProps) {- const { menuSchema, onOptionSelect } = props;+ const { menuSchema, activeItemIds, onOptionSelect } = props;const componentManager = useDependency(ComponentManager);const localeService = useDependency(LocaleService);const menuItem = menuSchema.item as IDisplayMenuItem<IMenuItem> | undefined;@@ -68,7 +90,7 @@ function QuickTileMenuItem(props: IUIQuickTileMenuItemProps) {hover:univer-bg-gray-50dark:hover:!univer-bg-gray-600`,- activated && `+ resolveMenuItemActiveState(menuItem.id, activated, activeItemIds) && `univer-bg-primary-50 univer-text-primary-700 univer-ring-1 univer-ring-primary-600dark:!univer-bg-primary-900 dark:!univer-text-primary-100`@@ -103,8 +125,9 @@ function QuickTileMenuItem(props: IUIQuickTileMenuItemProps) {}export function UITinyMenuGroup(props: IUIQuickMenuGroupProps) {- const { item, onOptionSelect } = props;+ const { item, activeItemIds, hiddenItemIds = EMPTY_HIDDEN_ITEM_IDS, onOptionSelect } = props;const [activeItems, setActiveItems] = useState<string[]>([]);+ const [hiddenItems, setHiddenItems] = useState<string[]>([]);const componentManager = useDependency(ComponentManager);const localeService = useDependency(LocaleService);@@ -112,7 +135,9 @@ export function UITinyMenuGroup(props: IUIQuickMenuGroupProps) {if (!item.children) return;const observables = item.children.map((child) => convertObservableToBehaviorSubject(child.item?.activated$ ?? of(false), false));const subscription = combineLatest(observables).subscribe((activedArr) => {- const actived = activedArr.map((actived, index) => ({ actived, item: item.children![index].item!.id })).filter((actived) => actived.actived);+ const actived = activedArr+ .map((actived, index) => ({ actived, item: getTinyMenuChildStateKey(item.children![index]) }))+ .filter((actived) => actived.actived);if (actived.length === 0) {setActiveItems([]);} else {@@ -128,11 +153,38 @@ export function UITinyMenuGroup(props: IUIQuickMenuGroupProps) {};}, [item]);+ useEffect(() => {+ if (!item.children) return;+ const observables = item.children.map((child) => convertObservableToBehaviorSubject(child.item?.hidden$ ?? of(false), false));+ const subscription = combineLatest(observables).subscribe((hiddenArr) => {+ const hidden = hiddenArr+ .map((hidden, index) => ({ hidden, item: getTinyMenuChildStateKey(item.children![index]) }))+ .filter((hidden) => hidden.hidden);+ if (hidden.length === 0) {+ setHiddenItems([]);+ } else {+ setHiddenItems(hidden.map((hidden) => hidden.item));+ }+ });++ return () => {+ subscription.unsubscribe();+ observables.forEach((observable) => {+ observable.complete();+ });+ };+ }, [item]);++ const visibleChildren = useMemo(+ () => getVisibleTinyMenuChildren(item.children ?? [], [...hiddenItems, ...hiddenItemIds]),+ [hiddenItemIds, hiddenItems, item.children]+ );+if (!item.children) return null;return (<DesignTinyMenuGroup- items={item.children.map((child) => ({+ items={visibleChildren.map((child) => ({key: child.key,onClick: () => {onOptionSelect?.({@@ -143,15 +195,16 @@ export function UITinyMenuGroup(props: IUIQuickMenuGroupProps) {});},className: '',+ iconClassName: child.item?.icon === 'TextTypeIcon' ? '!univer-size-3.5' : undefined,Icon: componentManager.get(child.item!.icon as string)!,- active: activeItems.includes(child.item?.id ?? ''),+ active: resolveMenuItemActiveState(child.item?.id, activeItems.includes(child.item?.id ?? ''), activeItemIds),}))}/>);}export function UIQuickTileMenuGroup(props: IUIQuickMenuGroupProps) {- const { item, onOptionSelect } = props;+ const { item, activeItemIds, hiddenItemIds = EMPTY_HIDDEN_ITEM_IDS, onOptionSelect } = props;if (!item.children?.length) {return null;@@ -159,10 +212,11 @@ export function UIQuickTileMenuGroup(props: IUIQuickMenuGroupProps) {return (<div className="univer-item-center univer-grid univer-grid-cols-3 univer-gap-1.5 univer-py-1">- {item.children.map((menuSchema) => (+ {getVisibleTinyMenuChildren(item.children, hiddenItemIds).map((menuSchema) => (<QuickTileMenuItemkey={menuSchema.key}menuSchema={menuSchema}+ activeItemIds={activeItemIds}onOptionSelect={onOptionSelect}/>))}diff --git a/packages/ui/src/components/menu/desktop/__tests__/TinyMenuGroup.spec.ts b/packages/ui/src/components/menu/desktop/__tests__/TinyMenuGroup.spec.tsnew file mode 100644index 0000000000..b7d744bc42--- /dev/null+++ b/packages/ui/src/components/menu/desktop/__tests__/TinyMenuGroup.spec.ts@@ -0,0 +1,36 @@+/**+ * 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 { describe, expect, it } from 'vitest';+import { getVisibleTinyMenuChildren, resolveMenuItemActiveState } from '../TinyMenuGroup';++describe('TinyMenuGroup', () => {+ it('uses explicit active items as an override instead of merging with observable active state', () => {+ expect(resolveMenuItemActiveState('h1', true, ['normal-text'])).toBe(false);+ expect(resolveMenuItemActiveState('normal-text', false, ['normal-text'])).toBe(true);+ expect(resolveMenuItemActiveState('h1', true)).toBe(true);+ });++ it('filters hidden tiny menu children before rendering', () => {+ const children = [+ { key: 'h1', order: 0, item: { id: 'h1' } },+ { key: 'title', order: 1, item: { id: 'title' } },+ { key: 'subtitle', order: 2, item: { id: 'subtitle' } },+ ] as never;++ expect(getVisibleTinyMenuChildren(children, ['title', 'subtitle']).map((item) => item.key)).toEqual(['h1']);+ });+});diff --git a/packages/ui/src/services/__tests__/core-services.spec.ts b/packages/ui/src/services/__tests__/core-services.spec.tsindex 29938b7bd9..7fb4fc864f 100644--- a/packages/ui/src/services/__tests__/core-services.spec.ts+++ b/packages/ui/src/services/__tests__/core-services.spec.ts@@ -17,9 +17,10 @@import type { IMenuButtonItem } from '../menu/menu';import { BehaviorSubject, Subject } from 'rxjs';import { afterEach, describe, expect, it, vi } from 'vitest';+import { CONTEXT_MENU_SUBMENU_CLOSE_DELAY, hasRenderableContextMenuSchema } from '../../views/components/context-menu/ContextMenuPanel';import { MenuItemType } from '../menu/menu';import { MenuManagerService } from '../menu/menu-manager.service';-import { MenuManagerPosition, RibbonPosition, RibbonStartGroup } from '../menu/types';+import { ContextMenuGroup, ContextMenuPosition, MenuManagerPosition, RibbonPosition, RibbonStartGroup } from '../menu/types';import { UIPartsService } from '../parts/parts.service';import { DesktopRibbonService } from '../ribbon/ribbon.service';@@ -104,6 +105,79 @@ describe('MenuManagerService', () => {service.dispose();expect(complete).toHaveBeenCalledTimes(1);});++ it('sorts menu groups by order after independent merges', () => {+ const service = new MenuManagerService({ invoke: vi.fn((factory: any) => factory({})) } as any, { getConfig: vi.fn() } as any);++ service.mergeMenu({+ [ContextMenuPosition.PARAGRAPH]: {+ emptyParagraph: {+ [ContextMenuGroup.LAYOUT]: {+ order: 1,+ layoutItem: {+ order: 0,+ menuItemFactory: () => ({+ id: 'layoutItem',+ type: MenuItemType.BUTTON,+ } as IMenuButtonItem),+ },+ },+ },+ },+ });+ service.mergeMenu({+ [ContextMenuPosition.PARAGRAPH]: {+ emptyParagraph: {+ [ContextMenuGroup.QUICK]: {+ order: -1,+ quickItem: {+ order: 0,+ menuItemFactory: () => ({+ id: 'quickItem',+ type: MenuItemType.BUTTON,+ } as IMenuButtonItem),+ },+ },+ },+ },+ });++ expect(service.getMenuByPositionKey('emptyParagraph').map((item) => item.key)).toEqual([+ ContextMenuGroup.QUICK,+ ContextMenuGroup.LAYOUT,+ ]);+ });++ it('ignores nested context menu containers that have no direct renderable items', () => {+ expect(hasRenderableContextMenuSchema({+ key: 'emptyParagraph',+ children: [{+ key: ContextMenuGroup.QUICK,+ children: [{+ key: 'h1',+ item: {+ id: 'h1',+ type: MenuItemType.BUTTON,+ } as any,+ }],+ }],+ } as any)).toBe(false);++ expect(hasRenderableContextMenuSchema({+ key: ContextMenuGroup.LAYOUT,+ children: [{+ key: 'insertBelow',+ item: {+ id: 'insertBelow',+ type: MenuItemType.SUBITEMS,+ } as any,+ }],+ } as any)).toBe(true);+ });++ it('keeps nested context menus open long enough for pointer travel', () => {+ expect(CONTEXT_MENU_SUBMENU_CLOSE_DELAY).toBeGreaterThanOrEqual(400);+ });});describe('DesktopRibbonService', () => {diff --git a/packages/ui/src/services/clipboard/clipboard-interface.service.ts b/packages/ui/src/services/clipboard/clipboard-interface.service.tsindex 8ecff66baa..e597e155cc 100644--- a/packages/ui/src/services/clipboard/clipboard-interface.service.ts+++ b/packages/ui/src/services/clipboard/clipboard-interface.service.ts@@ -148,7 +148,7 @@ export interface IClipboardInterfaceService {* @param text* @param html*/- write(text: string, html: string): Promise<void>;+ write(text: string, html: string, customData?: Record<string, string>): Promise<void>;/*** Read plain text from clipboard. Use read() to read both plain text and html.@@ -184,7 +184,7 @@ export class BrowserClipboardService extends Disposable implements IClipboardIntsuper();}- async write(text: string, html: string): Promise<void> {+ async write(text: string, html: string, customData?: Record<string, string>): Promise<void> {if (!this.supportClipboard) {return this._legacyCopyHtml(html);}@@ -195,9 +195,24 @@ export class BrowserClipboardService extends Disposable implements IClipboardIntnew ClipboardItem({[PLAIN_TEXT_CLIPBOARD_MIME_TYPE]: new Blob([text], { type: PLAIN_TEXT_CLIPBOARD_MIME_TYPE }),[HTML_CLIPBOARD_MIME_TYPE]: new Blob([html], { type: HTML_CLIPBOARD_MIME_TYPE }),+ ...Object.fromEntries(Object.entries(customData ?? {}).map(([type, value]) => [type, new Blob([value], { type })])),}),]);} catch (error) {+ if (customData && Object.keys(customData).length) {+ try {+ return await navigator.clipboard.write([+ new ClipboardItem({+ [PLAIN_TEXT_CLIPBOARD_MIME_TYPE]: new Blob([text], { type: PLAIN_TEXT_CLIPBOARD_MIME_TYPE }),+ [HTML_CLIPBOARD_MIME_TYPE]: new Blob([html], { type: HTML_CLIPBOARD_MIME_TYPE }),+ }),+ ]);+ } catch (fallbackError) {+ this._logService.error('[BrowserClipboardService]', fallbackError);+ this._showClipboardAuthenticationNotification();+ return;+ }+ }this._logService.error('[BrowserClipboardService]', error);this._showClipboardAuthenticationNotification();}diff --git a/packages/ui/src/services/menu/menu-manager.service.ts b/packages/ui/src/services/menu/menu-manager.service.tsindex 179cd88c7c..b69cec4024 100644--- a/packages/ui/src/services/menu/menu-manager.service.ts+++ b/packages/ui/src/services/menu/menu-manager.service.ts@@ -55,6 +55,7 @@ export type MenuSchemaType = {title?: string;contextual?: boolean;quickLayout?: ContextMenuQuickLayout;+ tiny?: boolean;} | {[key: string]: MenuSchemaType;};@@ -293,6 +294,7 @@ export class MenuManagerService extends Disposable implements IMenuManagerServictitle: value.title,contextual: value.contextual,quickLayout: value.quickLayout,+ tiny: value.tiny,};if (value.menuItemFactory) {@@ -321,7 +323,7 @@ export class MenuManagerService extends Disposable implements IMenuManagerServic}}- return result;+ return result.sort((a, b) => normalizeMenuOrder(a.order) - normalizeMenuOrder(b.order));}/**@@ -371,3 +373,7 @@ export class MenuManagerService extends Disposable implements IMenuManagerServicreturn flatMenuItems(menu);}}++function normalizeMenuOrder(order: number | undefined): number {+ return order ?? 0;+}diff --git a/packages/ui/src/views/components/context-menu/ContextMenu.tsx b/packages/ui/src/views/components/context-menu/ContextMenu.tsxindex c54b715671..c41f35857c 100644--- a/packages/ui/src/views/components/context-menu/ContextMenu.tsx+++ b/packages/ui/src/views/components/context-menu/ContextMenu.tsx@@ -79,9 +79,11 @@ export function DesktopContextMenu() {onRequestClose={handleClose}onOptionSelect={(params) => {const { label: id, commandId, value } = params;+ const rawParams = typeof params.params === 'function' ? params.params() : params.params;+ const commandParams = typeof rawParams === 'undefined' ? { value } : rawParams;if (commandService) {- commandService.executeCommand(commandId ?? id as string, { value });+ commandService.executeCommand(commandId ?? id as string, commandParams);}const layoutService = injector.get(ILayoutService);diff --git a/packages/ui/src/views/components/context-menu/ContextMenuPanel.tsx b/packages/ui/src/views/components/context-menu/ContextMenuPanel.tsxindex bd77317262..bce53df6f7 100644--- a/packages/ui/src/views/components/context-menu/ContextMenuPanel.tsx+++ b/packages/ui/src/views/components/context-menu/ContextMenuPanel.tsx@@ -26,12 +26,12 @@ import type { IMenuSchema } from '../../../services/menu/menu-manager.service';import { isRealNum, LocaleService } from '@univerjs/core';import { borderBottomClassName, borderClassName, clsx, scrollbarClassName } from '@univerjs/design';import { CheckMarkIcon, MoreIcon } from '@univerjs/icons';-import { useEffect, useMemo, useRef, useState } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { createPortal } from 'react-dom';import { combineLatest, isObservable, of, scan, startWith } from 'rxjs';import { CustomLabel } from '../../../components/custom-label/CustomLabel';import { useScrollYOverContainer } from '../../../components/hooks/layout';-import { UIQuickTileMenuGroup, UITinyMenuGroup } from '../../../components/menu/desktop/TinyMenuGroup';+import { resolveMenuItemActiveState, UIQuickTileMenuGroup, UITinyMenuGroup } from '../../../components/menu/desktop/TinyMenuGroup';import { ILayoutService } from '../../../services/layout/layout.service';import { MenuItemType } from '../../../services/menu/menu';import { IMenuManagerService } from '../../../services/menu/menu-manager.service';@@ -41,6 +41,8 @@ interface IContextMenuPanelProps {menuType: string;menuSessionVersion?: number;className?: string;+ activeItemIds?: string[];+ hiddenItemIds?: string[];onOptionSelect?: (option: IValueOption) => void;}@@ -49,6 +51,8 @@ interface IContextMenuMenuProps {menuSessionVersion: number;submenuPortalContainer: HTMLElement | null;maxMenuHeight: number;+ activeItemIds?: string[];+ hiddenItemIds?: string[];onOptionSelect?: (option: IValueOption) => void;}@@ -58,6 +62,9 @@ interface IContextMenuMenuItemProps {menuSessionVersion: number;submenuPortalContainer: HTMLElement | null;maxMenuHeight: number;+ activeItemIds?: string[];+ hiddenItemIds?: string[];+ compact?: boolean;onOptionSelect?: (option: IValueOption) => void;}@@ -65,6 +72,7 @@ const contentClassName = 'univer-inline-flex univer-items-center univer-gap-2';const menuViewportPadding = 8;const submenuOverlapOffset = 2;const submenuVisualGap = 20;+export const CONTEXT_MENU_SUBMENU_CLOSE_DELAY = 500;export const CONTEXT_MENU_SUBMENU_PORTAL_ATTR = 'data-u-context-menu-submenu';type MenuLabel = IMenuItem['label'] | IValueOption['label'];@@ -77,8 +85,20 @@ function isNonHoverableLabel(label?: MenuLabel) {return typeof label === 'object' && label?.hoverable === false;}+export function hasRenderableContextMenuSchema(menuSchema: IMenuSchema): boolean {+ if (menuSchema.item) {+ return true;+ }++ if (!menuSchema.children?.length) {+ return false;+ }++ return menuSchema.children.some((childSchema) => Boolean(childSchema.item));+}+export function ContextMenuPanel(props: IContextMenuPanelProps) {- const { menuType, menuSessionVersion = 0, className, onOptionSelect } = props;+ const { menuType, menuSessionVersion = 0, className, activeItemIds, hiddenItemIds, onOptionSelect } = props;const menuManagerService = useDependency(IMenuManagerService);const layoutService = useDependency(ILayoutService);const [menuElement, setMenuElement] = useState<HTMLDivElement | null>(null);@@ -161,6 +181,8 @@ export function ContextMenuPanel(props: IContextMenuPanelProps) {menuSchemas={menuItems}menuSessionVersion={menuSessionVersion}submenuPortalContainer={submenuPortalContainer}+ activeItemIds={activeItemIds}+ hiddenItemIds={hiddenItemIds}onOptionSelect={onOptionSelect}maxMenuHeight={maxMenuHeight}/>@@ -169,12 +191,16 @@ export function ContextMenuPanel(props: IContextMenuPanelProps) {}function ContextMenuMenu(props: IContextMenuMenuProps) {- const { menuSchemas, menuSessionVersion, submenuPortalContainer, onOptionSelect, maxMenuHeight } = props;+ const { menuSchemas, menuSessionVersion, submenuPortalContainer, activeItemIds, hiddenItemIds, onOptionSelect, maxMenuHeight } = props;const localeService = useDependency(LocaleService);const hiddenGroupStates = useContextGroupHiddenStates(menuSchemas);const visibleSchemas = useMemo(() => {return menuSchemas.filter((item) => {+ if (!hasRenderableContextMenuSchema(item)) {+ return false;+ }+if (!item.children) {return true;}@@ -198,6 +224,7 @@ function ContextMenuMenu(props: IContextMenuMenuProps) {submenuPortalContainer={submenuPortalContainer}onOptionSelect={onOptionSelect}maxMenuHeight={maxMenuHeight}+ hiddenItemIds={hiddenItemIds}/>);}@@ -219,12 +246,16 @@ function ContextMenuMenu(props: IContextMenuMenuProps) {? (<UIQuickTileMenuGroupitem={menuSchema}+ activeItemIds={activeItemIds}+ hiddenItemIds={hiddenItemIds}onOptionSelect={onOptionSelect}/>): (<UITinyMenuGroupitem={menuSchema}+ activeItemIds={activeItemIds}+ hiddenItemIds={hiddenItemIds}onOptionSelect={onOptionSelect}/>)}@@ -232,6 +263,35 @@ function ContextMenuMenu(props: IContextMenuMenuProps) {);}+ if (menuSchema.tiny) {+ return (+ <div+ key={menuSchema.key}+ className={clsx(+ 'univer-flex univer-items-center univer-gap-1 univer-py-1',+ hasSeparator && borderBottomClassName+ )}+ >+ {menuSchema.children.map((childSchema) => (+ childSchema.item && (+ <ContextMenuMenuItem+ key={childSchema.key}+ menuKey={childSchema.key}+ menuItem={childSchema.item as IDisplayMenuItem<IMenuItem>}+ menuSessionVersion={menuSessionVersion}+ submenuPortalContainer={submenuPortalContainer}+ activeItemIds={activeItemIds}+ hiddenItemIds={hiddenItemIds}+ onOptionSelect={onOptionSelect}+ maxMenuHeight={maxMenuHeight}+ compact+ />+ )+ ))}+ </div>+ );+ }+return (<divkey={menuSchema.key}@@ -258,6 +318,8 @@ function ContextMenuMenu(props: IContextMenuMenuProps) {menuItem={childSchema.item as IDisplayMenuItem<IMenuItem>}menuSessionVersion={menuSessionVersion}submenuPortalContainer={submenuPortalContainer}+ activeItemIds={activeItemIds}+ hiddenItemIds={hiddenItemIds}onOptionSelect={onOptionSelect}maxMenuHeight={maxMenuHeight}/>@@ -271,7 +333,7 @@ function ContextMenuMenu(props: IContextMenuMenuProps) {}function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {- const { menuKey, menuItem, menuSessionVersion, submenuPortalContainer, onOptionSelect, maxMenuHeight } = props;+ const { menuKey, menuItem, menuSessionVersion, submenuPortalContainer, activeItemIds, hiddenItemIds = [], compact = false, onOptionSelect, maxMenuHeight } = props;const localeService = useDependency(LocaleService);const direction = useObservable(localeService.direction$);const menuManagerService = useDependency(IMenuManagerService);@@ -296,6 +358,7 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {const [submenuPlacement, setSubmenuPlacement] = useState<'left' | 'right'>('right');const menuItemElementRef = useRef<HTMLDivElement | null>(null);const submenuElementRef = useRef<HTMLDivElement | null>(null);+ const submenuCloseTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);const selections = useMemo(() => {if (menuItem.type !== MenuItemType.SELECTOR && menuItem.type !== MenuItemType.BUTTON_SELECTOR) {@@ -320,11 +383,31 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {const hasSelectionSubmenu = selections.length > 0;const hasSubItemSubmenu = subMenuItems.length > 0;const hasSubmenu = hasSelectionSubmenu || hasSubItemSubmenu;+ const selectionsCommandId = selectorItem.selectionsCommandId;++ const clearSubmenuCloseTimer = useCallback(() => {+ if (submenuCloseTimerRef.current == null) {+ return;+ }++ clearTimeout(submenuCloseTimerRef.current);+ submenuCloseTimerRef.current = null;+ }, []);++ const scheduleSubmenuClose = useCallback(() => {+ clearSubmenuCloseTimer();+ submenuCloseTimerRef.current = setTimeout(() => {+ submenuCloseTimerRef.current = null;+ setSubmenuVisible(false);+ }, CONTEXT_MENU_SUBMENU_CLOSE_DELAY);+ }, [clearSubmenuCloseTimer]);useEffect(() => {setInputValue(value);}, [value]);+ useEffect(() => () => clearSubmenuCloseTimer(), [clearSubmenuCloseTimer]);+useEffect(() => {if (!submenuVisible) {setSubmenuPositionReady(false);@@ -369,7 +452,9 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {};}, [submenuVisible, hasSelectionSubmenu, hasSubItemSubmenu]);- if (hidden) {+ const hiddenById = (menuItem.id != null && hiddenItemIds.includes(menuItem.id)) || hiddenItemIds.includes(menuKey);++ if (hidden || hiddenById) {return null;}@@ -380,16 +465,23 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {const onSubmenuOptionSelect = (option: IValueOption) => {onOptionSelect?.(option);+ clearSubmenuCloseTimer();setSubmenuVisible(false);};const itemClassName = clsx(- `- univer-relative univer-flex univer-min-h-8 univer-w-full univer-items-center univer-justify-between- univer-gap-3 univer-rounded-md univer-border-none univer-bg-transparent univer-px-2 univer-text-left- univer-text-sm- dark:!univer-text-white- `,+ compact+ ? `+ univer-relative univer-flex univer-size-8 univer-items-center univer-justify-center univer-rounded-md+ univer-border-none univer-bg-transparent univer-p-0 univer-text-left univer-text-sm+ dark:!univer-text-white+ `+ : `+ univer-relative univer-flex univer-min-h-8 univer-w-full univer-items-center univer-justify-between+ univer-gap-3 univer-rounded-md univer-border-none univer-bg-transparent univer-px-2 univer-text-left+ univer-text-sm+ dark:!univer-text-white+ `,disabled? 'univer-cursor-not-allowed univer-opacity-60': `@@ -397,7 +489,7 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {hover:univer-bg-gray-50dark:hover:!univer-bg-gray-600`,- activated && `+ resolveMenuItemActiveState(menuItem.id, activated, activeItemIds) && `univer-bg-gray-200dark:!univer-bg-gray-600`@@ -407,7 +499,7 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {<span className={contentClassName}><CustomLabelvalue={inputValue}- title={menuItem.title}+ title={compact ? undefined : menuItem.title}label={menuItem.label}icon={menuItem.icon}onChange={onChange}@@ -428,6 +520,7 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {ref={menuItemElementRef}className="univer-relative"onMouseEnter={() => {+ clearSubmenuCloseTimer();if (hasSubmenu && !disabled) {setSubmenuPositionReady(false);setSubmenuVisible(true);@@ -439,7 +532,7 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {if (nextTarget && submenuElementRef.current?.contains(nextTarget)) {return;}- setSubmenuVisible(false);+ scheduleSubmenuClose();}}}>@@ -465,8 +558,22 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {type="button"className={interactiveItemClassName}disabled={disabled}+ title={compact && typeof menuItem.tooltip === 'string' ? localeService.t(menuItem.tooltip) : undefined}onClick={() => {+ clearSubmenuCloseTimer();if (hasSubmenu) {+ if (canExecuteItem) {+ const item = menuItem as IDisplayMenuItem<IMenuButtonItem>;+ onOptionSelect?.({+ commandId: item.commandId,+ params: item.params,+ value: inputValue,+ id: item.id,+ label: menuKey,+ });+ return;+ }+setSubmenuPositionReady(false);setSubmenuVisible(true);return;@@ -479,6 +586,7 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {const item = menuItem as IDisplayMenuItem<IMenuButtonItem>;onOptionSelect?.({commandId: item.commandId,+ params: item.params,value: inputValue,id: item.id,label: menuKey,@@ -486,7 +594,7 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {}}>{contentNode}- {hasSubmenu && (+ {hasSubmenu && !compact && (<MoreIconclassName={`univer-size-3.5 univer-text-gray-400@@ -515,13 +623,14 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {visibility: submenuPositionReady ? 'visible' : 'hidden',pointerEvents: submenuPositionReady ? 'auto' : 'none',}}+ onMouseEnter={clearSubmenuCloseTimer}onMouseLeave={(event) => {const nextTarget = event.relatedTarget as Node | null;if (nextTarget && menuItemElementRef.current?.contains(nextTarget)) {return;}- setSubmenuVisible(false);+ scheduleSubmenuClose();}}onWheel={(event) => event.stopPropagation()}>@@ -587,7 +696,7 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {value: optionValue,id: menuItem.id,label: menuKey,- commandId: option.commandId,+ commandId: option.commandId ?? selectionsCommandId,});}}/>@@ -608,7 +717,7 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {...option,id: menuItem.id,label: menuKey,- commandId: option.commandId,+ commandId: option.commandId ?? selectionsCommandId,});}}>@@ -633,6 +742,8 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {menuSchemas={subMenuItems}menuSessionVersion={menuSessionVersion}submenuPortalContainer={submenuPortalContainer}+ activeItemIds={activeItemIds}+ hiddenItemIds={hiddenItemIds}onOptionSelect={onSubmenuOptionSelect}maxMenuHeight={maxMenuHeight}/>diff --git a/packages/ui/src/views/components/ribbon/Ribbon.tsx b/packages/ui/src/views/components/ribbon/Ribbon.tsxindex 8cf5e59689..2769f6d702 100644--- a/packages/ui/src/views/components/ribbon/Ribbon.tsx+++ b/packages/ui/src/views/components/ribbon/Ribbon.tsx@@ -168,7 +168,12 @@ export function Ribbon(props: IRibbonProps) {>{activeGroup.allGroups.map((groupItem, index) => (groupItem.children?.length || groupItem.item) && (<Fragment key={groupItem.key}>- <div className="univer-grid univer-shrink-0 univer-grid-flow-col univer-gap-2 univer-px-2">+ <div+ className="+ univer-grid univer-shrink-0 univer-grid-flow-col univer-gap-2 univer-px-2+ empty:univer-hidden+ "+ >{groupItem.children && groupItem.children?.map((child) => (child.item && (<ToolbarItem@@ -254,7 +259,12 @@ export function Ribbon(props: IRibbonProps) {>{activeGroup.visibleGroups.map((groupItem) => (groupItem.children?.length || groupItem.item) && (<Fragment key={groupItem.key}>- <div className="univer-grid univer-shrink-0 univer-grid-flow-col univer-gap-2 univer-px-2">+ <div+ className="+ univer-grid univer-shrink-0 univer-grid-flow-col univer-gap-2 univer-px-2+ empty:univer-hidden+ "+ >{groupItem.children && groupItem.children?.map((child) => (child.item && <ToolbarItem key={child.key} {...child.item} />))}diff --git a/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx b/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsxindex 5b942b5a90..75b190c7a0 100644--- a/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx+++ b/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx@@ -199,6 +199,11 @@ export function DropdownMenuWrapper({setDropdownVisible(visible);}+ function handleOptionSelect(option: IValueOption) {+ onOptionSelect(option);+ setDropdownVisible(false);+ }+useEffect(() => {const subscriptions: Subscription[] = [];@@ -243,7 +248,7 @@ export function DropdownMenuWrapper({key={index}value={value}option={option}- onOptionSelect={onOptionSelect}+ onOptionSelect={handleOptionSelect}/>))}>@@ -264,19 +269,25 @@ export function DropdownMenuWrapper({icon={option.icon}value={value}option={option}- onOptionSelect={onOptionSelect}+ onOptionSelect={handleOptionSelect}/>),disabled: option.disabled,onSelect: () => {if (typeof option.value === 'undefined') return;- onOptionSelect?.({+ handleOptionSelect({...option,});},}));+ if (filteredMenuItems.length) {+ items.push({+ type: 'separator',+ });+ }+for (const menuItem of filteredMenuItems) {if (!menuItem.item) continue;@@ -301,7 +312,7 @@ export function DropdownMenuWrapper({/>),onSelect: () => {- onOptionSelect?.({+ handleOptionSelect({commandId,id,});@@ -346,7 +357,7 @@ export function DropdownMenuWrapper({/>),onSelect: () => {- onOptionSelect?.({+ handleOptionSelect({commandId,id,});