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): support default paragraph style (#7230)
Univer92f1702f872f
diff --git a/packages/core/src/docs/data-model/__tests__/empty-snapshot.spec.ts b/packages/core/src/docs/data-model/__tests__/empty-snapshot.spec.tsindex deb233f0c6..2fe24f0bcb 100644--- a/packages/core/src/docs/data-model/__tests__/empty-snapshot.spec.ts+++ b/packages/core/src/docs/data-model/__tests__/empty-snapshot.spec.ts@@ -19,7 +19,10 @@ import { getEmptySnapshot } from '../empty-snapshot';describe('getEmptySnapshot', () => {it('uses the configured paragraph spacing defaults for new docs', () => {- expect(getEmptySnapshot().body?.paragraphs?.[0].paragraphStyle).toEqual({+ const snapshot = getEmptySnapshot();++ expect(snapshot.body?.paragraphs?.[0].paragraphStyle).toEqual({});+ expect(snapshot.documentStyle.defaultParagraphStyle).toEqual({spaceAbove: { v: 0 },lineSpacing: 1.5,spaceBelow: { v: 12 },diff --git a/packages/core/src/docs/data-model/document-data-model.ts b/packages/core/src/docs/data-model/document-data-model.tsindex 9b574f2aa4..44853ced55 100644--- a/packages/core/src/docs/data-model/document-data-model.ts+++ b/packages/core/src/docs/data-model/document-data-model.ts@@ -56,6 +56,12 @@ function createDocumentSnapshot(snapshot: Partial<IDocumentData>): IDocumentData}});+ // Existing snapshots with a body must preserve the absence of document+ // defaults. The renderer provides the legacy flavor fallback for them.+ if (snapshot.body != null && snapshot.documentStyle?.defaultParagraphStyle === undefined) {+ delete mergedSnapshot.documentStyle.defaultParagraphStyle;+ }+return mergedSnapshot;}diff --git a/packages/core/src/docs/data-model/empty-snapshot.ts b/packages/core/src/docs/data-model/empty-snapshot.tsindex 54722d77a3..e74ef8a360 100644--- a/packages/core/src/docs/data-model/empty-snapshot.ts+++ b/packages/core/src/docs/data-model/empty-snapshot.ts@@ -87,7 +87,8 @@ export function getEmptySnapshot(// Set default values for modern document flavorif (documentFlavor === DocumentFlavor.MODERN) {- EMPTY_DOCUMENT_DATA.body!.paragraphs![0].paragraphStyle = {+ EMPTY_DOCUMENT_DATA.body!.paragraphs![0].paragraphStyle = {};+ EMPTY_DOCUMENT_DATA.documentStyle.defaultParagraphStyle = {spaceAbove: { v: DEFAULT_DOCUMENT_PARAGRAPH_SPACE_ABOVE },lineSpacing: DEFAULT_DOCUMENT_PARAGRAPH_LINE_SPACING,spaceBelow: { v: DEFAULT_DOCUMENT_PARAGRAPH_SPACE_BELOW },diff --git a/packages/core/src/docs/data-model/index.ts b/packages/core/src/docs/data-model/index.tsindex 5c1d1cedba..cd07b89237 100644--- a/packages/core/src/docs/data-model/index.ts+++ b/packages/core/src/docs/data-model/index.ts@@ -18,6 +18,8 @@ export * from './document-data-model';export { getEmptySnapshot as getDocsEmptySnapshot } from './empty-snapshot';export { JSON1, JSONX } from './json-x/json-x';export type { JSONXActions, JSONXPath } from './json-x/json-x';+export { resolveDocumentParagraphStyle } from './paragraph-style';+export type { IResolveDocumentParagraphStyleOptions } from './paragraph-style';export * from './preset-list-type';export { replaceInDocumentBody } from './replacement';export {diff --git a/packages/core/src/docs/data-model/paragraph-style.ts b/packages/core/src/docs/data-model/paragraph-style.tsnew file mode 100644index 0000000000..35c9067ca3--- /dev/null+++ b/packages/core/src/docs/data-model/paragraph-style.ts@@ -0,0 +1,77 @@+/**+ * 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 { Nullable } from '../../shared';+import type { IDocumentStyle, IParagraphStyle } from '../../types/interfaces';+import { Tools } from '../../shared';+import {+ DEFAULT_DOCUMENT_PARAGRAPH_LINE_SPACING,+ DEFAULT_DOCUMENT_PARAGRAPH_SPACE_ABOVE,+ DEFAULT_DOCUMENT_PARAGRAPH_SPACE_BELOW,+ NAMED_STYLE_SPACE_MAP,+} from '../../types/const';+import { DocumentFlavor } from '../../types/interfaces';++export interface IResolveDocumentParagraphStyleOptions {+ excludeDocumentOuterSpacing?: boolean;+ useLegacyModernDefaults?: boolean;+}++function _definedStyle(style: Nullable<IParagraphStyle>): IParagraphStyle {+ if (style == null) {+ return {};+ }++ return Object.fromEntries(+ Object.entries(style).filter(([, value]) => value != null)+ ) as IParagraphStyle;+}++export function resolveDocumentParagraphStyle(+ documentStyle: Nullable<IDocumentStyle>,+ paragraphStyle: Nullable<IParagraphStyle>,+ options: IResolveDocumentParagraphStyleOptions = {}+): IParagraphStyle {+ const useLegacyModernDefaults = options.useLegacyModernDefaults ??+ documentStyle?.documentFlavor === DocumentFlavor.MODERN;+ const legacyStyle: IParagraphStyle = useLegacyModernDefaults+ ? {+ lineSpacing: DEFAULT_DOCUMENT_PARAGRAPH_LINE_SPACING,+ spaceAbove: { v: DEFAULT_DOCUMENT_PARAGRAPH_SPACE_ABOVE },+ spaceBelow: { v: DEFAULT_DOCUMENT_PARAGRAPH_SPACE_BELOW },+ }+ : {};+ const documentDefaults = {+ ...legacyStyle,+ ..._definedStyle(documentStyle?.defaultParagraphStyle),+ };++ if (options.excludeDocumentOuterSpacing) {+ delete documentDefaults.spaceAbove;+ delete documentDefaults.spaceBelow;+ }++ const definedParagraphStyle = _definedStyle(paragraphStyle);+ const namedStyle = definedParagraphStyle.namedStyleType == null+ ? null+ : NAMED_STYLE_SPACE_MAP[definedParagraphStyle.namedStyleType];++ return Tools.deepClone({+ ...documentDefaults,+ ...namedStyle,+ ...definedParagraphStyle,+ });+}diff --git a/packages/core/src/types/interfaces/i-document-data.ts b/packages/core/src/types/interfaces/i-document-data.tsindex e7204ccd3e..4cbf1914a9 100644--- a/packages/core/src/types/interfaces/i-document-data.ts+++ b/packages/core/src/types/interfaces/i-document-data.ts@@ -503,6 +503,7 @@ export enum GridType {export interface IDocumentStyle extends IDocStyleBase, IDocumentLayout, IHeaderAndFooterBase {textStyle?: ITextStyle; // default style for text+ defaultParagraphStyle?: IDocumentDefaultParagraphStyle; // default style inherited by paragraphsbackground?: IDocumentBackground; // Page background image.}@@ -814,6 +815,12 @@ export interface IParagraphStyle extends IParagraphProperties {textStyle?: ITextStyle; // paragraph textStyle}+/**+ * Paragraph properties that may be inherited from the document defaults.+ * Paragraph identity and named/text styles have their own inheritance mechanisms.+ */+export type IDocumentDefaultParagraphStyle = Omit<IParagraphStyle, 'headingId' | 'namedStyleType' | 'textStyle'>;+export interface IParagraphProperties extends IIndentStart {headingId?: string; // headingIdnamedStyleType?: NamedStyleType; // namedStyleTypediff --git a/packages/docs-ui/src/views/paragraph-setting/hook/utils.ts b/packages/docs-ui/src/views/paragraph-setting/hook/utils.tsindex 19bd17e5fa..0002b48ff9 100644--- a/packages/docs-ui/src/views/paragraph-setting/hook/utils.ts+++ b/packages/docs-ui/src/views/paragraph-setting/hook/utils.ts@@ -14,15 +14,17 @@* limitations under the License.*/-import type { DocumentDataModel, IParagraph, ISectionBreak } from '@univerjs/core';+import type { DocumentDataModel, IDocumentBody, IDocumentStyle, IParagraph, ISectionBreak } from '@univerjs/core';import type { IDocParagraphSettingCommandParams } from '../../../commands/commands/doc-paragraph-setting.command';import {BuildTextUtils,DEFAULT_DOCUMENT_PARAGRAPH_LINE_SPACING,DEFAULT_DOCUMENT_PARAGRAPH_SPACE_ABOVE,DEFAULT_DOCUMENT_PARAGRAPH_SPACE_BELOW,+ DocumentBlockRangeType,ICommandService,IUniverInstanceService,+ resolveDocumentParagraphStyle,SpacingRule,UniverInstanceType,} from '@univerjs/core';@@ -42,6 +44,33 @@ import {getLineSpacingMetrics,} from '../line-spacing';+const PARAGRAPH_LAYOUT_BLOCK_TYPES = new Set([+ DocumentBlockRangeType.CALLOUT,+ DocumentBlockRangeType.CODE,+ DocumentBlockRangeType.QUOTE,+]);++export function resolveParagraphsForSettingPanel(+ paragraphs: IParagraph[],+ body: IDocumentBody,+ documentStyle: IDocumentStyle+) {+ return paragraphs.map((paragraph) => {+ const hasLayoutBlockRange = body.blockRanges?.some((range) =>+ PARAGRAPH_LAYOUT_BLOCK_TYPES.has(range.blockType) &&+ paragraph.startIndex > range.startIndex &&+ paragraph.startIndex < range.endIndex+ ) ?? false;++ return {+ ...paragraph,+ paragraphStyle: resolveDocumentParagraphStyle(documentStyle, paragraph.paragraphStyle, {+ excludeDocumentOuterSpacing: hasLayoutBlockRange,+ }),+ };+ });+}+const useDocRanges = () => {const docSelectionManagerService = useDependency(DocSelectionManagerService);const docParagraphSettingController = useDependency(DocParagraphSettingController);@@ -74,11 +103,14 @@ export const useCurrentParagraph = () => {const segmentId = docRanges[0].segmentId;const segment = docDataModel.getSelfOrHeaderFooterModel(segmentId);- const paragraphs = segment?.getBody()?.paragraphs ?? [];- const dataStream = segment?.getBody()?.dataStream ?? '';+ const body = segment?.getBody();+ const paragraphs = body?.paragraphs ?? [];+ const dataStream = body?.dataStream ?? '';const currentParagraphs = BuildTextUtils.range.getParagraphsInRanges(docRanges, paragraphs, dataStream) ?? [];- return currentParagraphs;+ return body == null+ ? currentParagraphs+ : resolveParagraphsForSettingPanel(currentParagraphs, body, docDataModel.getDocumentStyle());};export const useCurrentSections = (currentParagraphs: IParagraph[]) => {diff --git a/packages/docs/src/commands/commands/set-document-default-paragraph-style.command.ts b/packages/docs/src/commands/commands/set-document-default-paragraph-style.command.tsnew file mode 100644index 0000000000..ca5aff01af--- /dev/null+++ b/packages/docs/src/commands/commands/set-document-default-paragraph-style.command.ts@@ -0,0 +1,121 @@+/**+ * 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,+ IDocumentDefaultParagraphStyle,+ IMutationInfo,+ JSONXActions,+ Nullable,+} from '@univerjs/core';+import type { IRichTextEditingMutationParams } from '../mutations/core-editing.mutation';+import {+ CommandType,+ ICommandService,+ IUniverInstanceService,+ JSONX,+ Tools,+ UniverInstanceType,+} from '@univerjs/core';+import { RichTextEditingMutation } from '../mutations/core-editing.mutation';++export type IDocumentDefaultParagraphStylePatch = {+ [K in keyof IDocumentDefaultParagraphStyle]?: Nullable<IDocumentDefaultParagraphStyle[K]>;+};++export interface ISetDocumentDefaultParagraphStyleCommandParams {+ unitId: string;+ defaultParagraphStyle: Nullable<IDocumentDefaultParagraphStylePatch>;+}++export const SetDocumentDefaultParagraphStyleCommand: ICommand<ISetDocumentDefaultParagraphStyleCommandParams> = {+ id: 'doc.command.set-default-paragraph-style',+ type: CommandType.COMMAND,+ handler: (accessor, params) => {+ if (params == null) {+ return false;+ }++ const commandService = accessor.get(ICommandService);+ const univerInstanceService = accessor.get(IUniverInstanceService);+ const documentDataModel = univerInstanceService.getUnit<DocumentDataModel>(params.unitId, UniverInstanceType.UNIVER_DOC);++ if (documentDataModel == null) {+ return false;+ }++ const oldStyle = documentDataModel.getSnapshot().documentStyle.defaultParagraphStyle;+ const jsonX = JSONX.getInstance();+ const path = ['documentStyle', 'defaultParagraphStyle'];+ const rawActions: JSONXActions = [];++ if (params.defaultParagraphStyle == null) {+ if (oldStyle != null) {+ rawActions.push(jsonX.removeOp(path, oldStyle)!);+ }+ } else if (oldStyle == null) {+ const newStyle = Object.fromEntries(+ Object.entries(params.defaultParagraphStyle)+ .filter(([, value]) => value != null)+ .map(([key, value]) => [key, Tools.deepClone(value)])+ ) as IDocumentDefaultParagraphStyle;++ if (Object.keys(newStyle).length > 0) {+ rawActions.push(jsonX.insertOp(path, newStyle)!);+ }+ } else {+ Object.entries(params.defaultParagraphStyle).forEach(([key, value]) => {+ const styleKey = key as keyof IDocumentDefaultParagraphStyle;+ const oldValue = oldStyle[styleKey];+ const propertyPath = [...path, key];++ if (value == null) {+ if (oldValue != null) {+ rawActions.push(jsonX.removeOp(propertyPath, oldValue)!);+ }+ } else if (oldValue == null) {+ rawActions.push(jsonX.insertOp(propertyPath, Tools.deepClone(value))!);+ } else {+ rawActions.push(jsonX.replaceOp(propertyPath, oldValue, Tools.deepClone(value))!);+ }+ });+ }++ const actions = rawActions.reduce(+ (acc, action) => JSONX.compose(acc, action as JSONXActions),+ null as JSONXActions+ );++ if (rawActions.length === 0 || JSONX.isNoop(actions)) {+ return false;+ }++ const mutation: IMutationInfo<IRichTextEditingMutationParams> = {+ id: RichTextEditingMutation.id,+ params: {+ unitId: params.unitId,+ actions,+ textRanges: null,+ noNeedSetTextRange: true,+ debounce: true,+ isEditing: false,+ },+ };++ return Boolean(commandService.syncExecuteCommand(mutation.id, mutation.params));+ },+};diff --git a/packages/docs/src/index.ts b/packages/docs/src/index.tsindex 08b89bbded..74cfc3a88a 100644--- a/packages/docs/src/index.ts+++ b/packages/docs/src/index.ts@@ -26,6 +26,11 @@ export type {ICreateHeaderFooterCommandParams,IHeaderFooterProps,} from './commands/commands/create-header-footer.command';+export { SetDocumentDefaultParagraphStyleCommand } from './commands/commands/set-document-default-paragraph-style.command';+export type {+ IDocumentDefaultParagraphStylePatch,+ ISetDocumentDefaultParagraphStyleCommandParams,+} from './commands/commands/set-document-default-paragraph-style.command';export { RichTextEditingMutation } from './commands/mutations/core-editing.mutation';export type { IRichTextEditingMutationParams } from './commands/mutations/core-editing.mutation';export { SetTextSelectionsOperation } from './commands/operations/text-selection.operation';diff --git a/packages/docs/src/plugin.ts b/packages/docs/src/plugin.tsindex 67b3ad4c9e..07fa908741 100644--- a/packages/docs/src/plugin.ts+++ b/packages/docs/src/plugin.ts@@ -27,6 +27,7 @@ import {import pkg from '../package.json';import { DeleteTextCommand, InsertTextCommand, UpdateTextCommand } from './commands/commands/core-editing.command';import { CreateHeaderFooterCommand } from './commands/commands/create-header-footer.command';+import { SetDocumentDefaultParagraphStyleCommand } from './commands/commands/set-document-default-paragraph-style.command';import { RichTextEditingMutation } from './commands/mutations/core-editing.mutation';import { DocsRenameMutation } from './commands/mutations/docs-rename.mutation';import { SetTextSelectionsOperation } from './commands/operations/text-selection.operation';@@ -72,6 +73,7 @@ export class UniverDocsPlugin extends Plugin {DeleteTextCommand,UpdateTextCommand,CreateHeaderFooterCommand,+ SetDocumentDefaultParagraphStyleCommand,RichTextEditingMutation,DocsRenameMutation,SetTextSelectionsOperation,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 d049b0233e..1284006d0b 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@@ -18,6 +18,7 @@ import type {IBullet,IDocDrawingBase,IDocumentBody,+ IDocumentStyle,IDrawings,IParagraph,IParagraphStyle,@@ -40,11 +41,9 @@ import type { IShapedText } from './shaping';import {DataStreamTreeTokenType,DEFAULT_DOCUMENT_PARAGRAPH_LINE_SPACING,- DEFAULT_DOCUMENT_PARAGRAPH_SPACE_ABOVE,- DEFAULT_DOCUMENT_PARAGRAPH_SPACE_BELOW,DocumentBlockRangeType,PositionedObjectLayoutType,- Tools,+ resolveDocumentParagraphStyle,} from '@univerjs/core';import { BreakType, GlyphType } from '../../../../../basics/i-document-skeleton-cached';import { getDocumentCompatibilityPolicy, isTraditionalDocumentCompatibility } from '../../../document-compatibility';@@ -289,38 +288,17 @@ function _hasNextAdjacentLayoutBlockRange(blockRanges: IDocumentBody['blockRange);}-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+ documentStyle: Nullable<IDocumentStyle>,+ useLegacyModernDefaults: boolean): IParagraphStyle {- const style = Tools.deepClone(paragraphStyle);const blockRanges = body?.blockRanges;if (!blockRanges?.length) {- if (shouldApplyDocumentDefaults) {- _applyDefaultLayoutParagraphStyle(style, false);- }- return style;+ return resolveDocumentParagraphStyle(documentStyle, paragraphStyle, { useLegacyModernDefaults });}const blockRange = blockRanges.find((range) =>@@ -330,13 +308,19 @@ function _applyBlockRangeLayoutParagraphStyle();if (!blockRange) {- if (shouldApplyDocumentDefaults) {- _applyDefaultLayoutParagraphStyle(style, false);- }- return style;+ return resolveDocumentParagraphStyle(documentStyle, paragraphStyle, { useLegacyModernDefaults });}- _applyDefaultLayoutParagraphStyle(style, true);+ const style = resolveDocumentParagraphStyle(documentStyle, paragraphStyle, {+ excludeDocumentOuterSpacing: true,+ useLegacyModernDefaults,+ });++ // Keep the existing block line-height fallback when neither the document+ // nor the paragraph provides one.+ if (style.lineSpacing == null) {+ style.lineSpacing = DEFAULT_DOCUMENT_PARAGRAPH_LINE_SPACING;+ }const blockParagraphs = (body?.paragraphs ?? []).filter((item) => item.startIndex > blockRange.startIndex && item.startIndex < blockRange.endIndex)@@ -470,8 +454,9 @@ export function lineBreaking(const paragraph = viewModel.getParagraph(endIndex) || { startIndex: 0, paragraphId: 'para_render_fallback' };const { paragraphStyle = {}, bullet } = paragraph;+ const documentStyle = viewModel.getSnapshot?.()?.documentStyle;const documentCompatibilityPolicy = sectionBreakConfig.documentCompatibilityPolicy ??- getDocumentCompatibilityPolicy(viewModel.getSnapshot?.()?.documentStyle.documentFlavor);+ getDocumentCompatibilityPolicy(documentStyle?.documentFlavor);const shouldApplyDocumentDefaults = documentCompatibilityPolicy.applyDocumentDefaultParagraphStyle;const useWordStyleLineHeight = documentCompatibilityPolicy.useWordStyleLineHeight;@@ -496,6 +481,7 @@ export function lineBreaking(viewModel.getBody?.() ?? null,paragraph,paragraphStyle,+ documentStyle,shouldApplyDocumentDefaults),docxFallbackAnchorLeft: _getFollowingIndentedParagraphAnchorLeft(