Skip to content

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

feat: support doc type (#7193)

wpxp123456a8c069ded381
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.png
index dbe3bb6bd2..7333df49fd 100644
Binary 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 differ
diff --git a/packages/core/src/docs/data-model/document-data-model.ts b/packages/core/src/docs/data-model/document-data-model.ts
index 5aacc2ca09..9b574f2aa4 100644
--- a/packages/core/src/docs/data-model/document-data-model.ts
+++ b/packages/core/src/docs/data-model/document-data-model.ts
@@ -18,6 +18,7 @@ import type { Nullable } from '../../shared';
import type { IDocumentBody, IDocumentData, IDocumentRenderConfig, IDocumentStyle, IDrawings, IListData } from '../../types/interfaces/i-document-data';
import type { IPaddingData } from '../../types/interfaces/i-style-data';
import type { JSONXActions } from './json-x/json-x';
+import { mergeWith } from 'lodash-es';
import { BehaviorSubject } from 'rxjs';
import { isInternalEditorID } from '../../common/const';
import { UnitModel, UniverInstanceType } from '../../common/unit';
@@ -39,39 +40,21 @@ function createDocumentSnapshot(snapshot: Partial<IDocumentData>): IDocumentData
return { ...DEFAULT_DOC, ...snapshot } as IDocumentData;
}
- const defaultSnapshot = getEmptySnapshot(snapshot.id, snapshot.locale, snapshot.title);
+ const defaultSnapshot = getEmptySnapshot(snapshot.id, snapshot.locale, snapshot.title, snapshot.documentStyle?.documentFlavor);
if (Tools.isEmptyObject(snapshot)) {
return defaultSnapshot;
}
- const mergedSnapshot = Tools.commonExtend<IDocumentData>(defaultSnapshot, snapshot);
- const { documentStyle, settings } = snapshot;
-
- if (documentStyle != null) {
- if (documentStyle.pageSize != null) {
- documentStyle.pageSize = {
- ...defaultSnapshot.documentStyle.pageSize,
- ...documentStyle.pageSize,
- };
+ const mergedSnapshot = mergeWith({}, defaultSnapshot, snapshot, (_objValue, srcValue, key) => {
+ if (Array.isArray(srcValue)) {
+ return srcValue;
}
- if (documentStyle.renderConfig != null) {
- documentStyle.renderConfig = {
- ...defaultSnapshot.documentStyle.renderConfig,
- ...documentStyle.renderConfig,
- };
+ if (key === 'body' && srcValue != null && typeof srcValue === 'object') {
+ return srcValue;
}
-
- mergedSnapshot.documentStyle = Tools.commonExtend(defaultSnapshot.documentStyle, documentStyle);
- }
-
- if (settings != null) {
- mergedSnapshot.settings = {
- ...defaultSnapshot.settings,
- ...settings,
- };
- }
+ });
return mergedSnapshot;
}
diff --git a/packages/core/src/docs/data-model/empty-snapshot.ts b/packages/core/src/docs/data-model/empty-snapshot.ts
index deb9db648f..54722d77a3 100644
--- a/packages/core/src/docs/data-model/empty-snapshot.ts
+++ b/packages/core/src/docs/data-model/empty-snapshot.ts
@@ -16,16 +16,17 @@
import type { IDocumentData } from '../../types/interfaces';
import { generateRandomId } from '../../shared/random-id';
-import { DEFAULT_DOCUMENT_PARAGRAPH_LINE_SPACING, DEFAULT_DOCUMENT_PARAGRAPH_SPACE_ABOVE, DEFAULT_DOCUMENT_PARAGRAPH_SPACE_BELOW, MODERN_DOCUMENT_WIDTH, ModernDocumentWidthMode } from '../../types/const';
+import { DEFAULT_DOCUMENT_PARAGRAPH_LINE_SPACING, DEFAULT_DOCUMENT_PARAGRAPH_SPACE_ABOVE, DEFAULT_DOCUMENT_PARAGRAPH_SPACE_BELOW, MODERN_DOCUMENT_WIDTH, ModernDocumentWidthMode, PAGE_SIZE } from '../../types/const';
import { BooleanNumber } from '../../types/enum';
import { LocaleType } from '../../types/enum/locale-type';
-import { DocumentFlavor } from '../../types/interfaces';
+import { DocumentFlavor, PaperType } from '../../types/interfaces';
import { createParagraphId } from '../paragraph-id';
export function getEmptySnapshot(
unitID = generateRandomId(6),
locale = LocaleType.EN_US,
- title = ''
+ title = '',
+ documentFlavor: DocumentFlavor = DocumentFlavor.MODERN
): IDocumentData {
const EMPTY_DOCUMENT_DATA: IDocumentData = {
id: unitID,
@@ -50,9 +51,7 @@ export function getEmptySnapshot(
startIndex: 0,
paragraphId: createParagraphId(new Set()),
paragraphStyle: {
- spaceAbove: { v: DEFAULT_DOCUMENT_PARAGRAPH_SPACE_ABOVE },
- lineSpacing: DEFAULT_DOCUMENT_PARAGRAPH_LINE_SPACING,
- spaceBelow: { v: DEFAULT_DOCUMENT_PARAGRAPH_SPACE_BELOW },
+ lineSpacing: 1,
},
},
],
@@ -63,23 +62,12 @@ export function getEmptySnapshot(
],
},
documentStyle: {
- pageSize: {
- width: MODERN_DOCUMENT_WIDTH[ModernDocumentWidthMode.MEDIUM],
- height: 842 / 0.75,
- },
- documentFlavor: DocumentFlavor.MODERN,
- marginTop: 50,
- marginBottom: 50,
- marginRight: 50,
- marginLeft: 50,
- renderConfig: {
- zeroWidthParagraphBreak: BooleanNumber.FALSE,
- vertexAngle: 0,
- centerAngle: 0,
- background: {
- rgb: '#ccc',
- },
- },
+ pageSize: PAGE_SIZE[PaperType.A4],
+ documentFlavor,
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 72,
+ marginLeft: 72,
autoHyphenation: BooleanNumber.TRUE,
doNotHyphenateCaps: BooleanNumber.FALSE,
consecutiveHyphenLimit: 2,
@@ -95,8 +83,32 @@ export function getEmptySnapshot(
marginFooter: 30,
},
settings: {},
-
};
+ // Set default values for modern document flavor
+ if (documentFlavor === DocumentFlavor.MODERN) {
+ EMPTY_DOCUMENT_DATA.body!.paragraphs![0].paragraphStyle = {
+ spaceAbove: { v: DEFAULT_DOCUMENT_PARAGRAPH_SPACE_ABOVE },
+ lineSpacing: DEFAULT_DOCUMENT_PARAGRAPH_LINE_SPACING,
+ spaceBelow: { v: DEFAULT_DOCUMENT_PARAGRAPH_SPACE_BELOW },
+ };
+ EMPTY_DOCUMENT_DATA.documentStyle.pageSize = {
+ width: MODERN_DOCUMENT_WIDTH[ModernDocumentWidthMode.MEDIUM],
+ height: 842 / 0.75,
+ };
+ EMPTY_DOCUMENT_DATA.documentStyle.marginTop = 50;
+ EMPTY_DOCUMENT_DATA.documentStyle.marginBottom = 50;
+ EMPTY_DOCUMENT_DATA.documentStyle.marginRight = 50;
+ EMPTY_DOCUMENT_DATA.documentStyle.marginLeft = 50;
+ EMPTY_DOCUMENT_DATA.documentStyle.renderConfig = {
+ zeroWidthParagraphBreak: BooleanNumber.FALSE,
+ vertexAngle: 0,
+ centerAngle: 0,
+ background: {
+ rgb: '#ccc',
+ },
+ };
+ }
+
return EMPTY_DOCUMENT_DATA;
}
diff --git a/packages/core/src/docs/data-model/index.ts b/packages/core/src/docs/data-model/index.ts
index 3358465624..2cdf8edb27 100644
--- a/packages/core/src/docs/data-model/index.ts
+++ b/packages/core/src/docs/data-model/index.ts
@@ -15,6 +15,7 @@
*/
export * from './document-data-model';
+export { getEmptySnapshot as getDocsEmptySnapshot } from './empty-snapshot';
export * from './preset-list-type';
export * from './text-x/build-utils';
export * from './types';
diff --git a/packages/docs-ui/src/menu/menu.ts b/packages/docs-ui/src/menu/menu.ts
index 804338071f..705d5ead4e 100644
--- a/packages/docs-ui/src/menu/menu.ts
+++ b/packages/docs-ui/src/menu/menu.ts
@@ -82,7 +82,7 @@ import {
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 { 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';
@@ -1267,33 +1267,33 @@ export function CheckListMenuItemFactory(accessor: IAccessor): IMenuButtonItem<L
};
}
-export function DocSwitchModeMenuItemFactory(accessor: IAccessor): IMenuButtonItem<LocaleKey> {
- const commandService = accessor.get(ICommandService);
- const univerInstanceService = accessor.get(IUniverInstanceService);
-
- return {
- id: SwitchDocModeCommand.id,
- type: MenuItemType.BUTTON,
- icon: 'KeyboardIcon',
- tooltip: 'docs-ui.toolbar.documentFlavor',
- hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
- activated$: new Observable<boolean>((subscriber) => {
- const subscription = commandService.onCommandExecuted((c) => {
- if (c.id === RichTextEditingMutation.id) {
- const instance = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
-
- subscriber.next(instance?.getSnapshot()?.documentStyle.documentFlavor === DocumentFlavor.MODERN);
- }
- });
-
- const instance = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
-
- subscriber.next(instance?.getSnapshot()?.documentStyle.documentFlavor === DocumentFlavor.MODERN);
-
- return () => subscription.dispose();
- }),
- };
-}
+// export function DocSwitchModeMenuItemFactory(accessor: IAccessor): IMenuButtonItem<LocaleKey> {
+// const commandService = accessor.get(ICommandService);
+// const univerInstanceService = accessor.get(IUniverInstanceService);
+
+// return {
+// id: SwitchDocModeCommand.id,
+// type: MenuItemType.BUTTON,
+// icon: 'KeyboardIcon',
+// tooltip: 'docs-ui.toolbar.documentFlavor',
+// hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
+// activated$: new Observable<boolean>((subscriber) => {
+// const subscription = commandService.onCommandExecuted((c) => {
+// if (c.id === RichTextEditingMutation.id) {
+// const instance = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+
+// subscriber.next(instance?.getSnapshot()?.documentStyle.documentFlavor === DocumentFlavor.MODERN);
+// }
+// });
+
+// const instance = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+
+// subscriber.next(instance?.getSnapshot()?.documentStyle.documentFlavor === DocumentFlavor.MODERN);
+
+// return () => subscription.dispose();
+// }),
+// };
+// }
export function ResetTextColorMenuItemFactory(accessor: IAccessor): IMenuButtonItem<LocaleKey> {
return {
diff --git a/packages/docs-ui/src/menu/schema.ts b/packages/docs-ui/src/menu/schema.ts
index 3a177122bb..5212cc62ef 100644
--- a/packages/docs-ui/src/menu/schema.ts
+++ b/packages/docs-ui/src/menu/schema.ts
@@ -63,7 +63,6 @@ import {
SubtitleHeadingCommand,
TitleHeadingCommand,
} from '../commands/commands/set-heading.command';
-import { SwitchDocModeCommand } from '../commands/commands/switch-doc-mode.command';
import {
DocTableDeleteColumnsCommand,
DocTableDeleteRowsCommand,
@@ -106,7 +105,7 @@ import {
BoldMenuItemFactory,
BulletListMenuItemFactory,
CheckListMenuItemFactory,
- DocSwitchModeMenuItemFactory,
+ // DocSwitchModeMenuItemFactory,
FLOAT_TEXT_STYLE_MENU_ID,
FLOAT_TOOLBAR_MENU_POSITION,
FloatTextStyleMenuItemFactory,
@@ -274,10 +273,10 @@ export const menuSchema: MenuSchemaType = {
order: 10,
menuItemFactory: HeaderFooterMenuItemFactory,
},
- [SwitchDocModeCommand.id]: {
- order: 11,
- menuItemFactory: DocSwitchModeMenuItemFactory,
- },
+ // [SwitchDocModeCommand.id]: {
+ // order: 11,
+ // menuItemFactory: DocSwitchModeMenuItemFactory,
+ // },
[DocOpenPageSettingCommand.id]: {
order: 12,
menuItemFactory: PageSettingMenuItemFactory,
diff --git a/packages/docs-ui/src/views/PageSettings.tsx b/packages/docs-ui/src/views/PageSettings.tsx
index 01d2e0a3ba..6924dffee5 100644
--- a/packages/docs-ui/src/views/PageSettings.tsx
+++ b/packages/docs-ui/src/views/PageSettings.tsx
@@ -152,9 +152,9 @@ export function PageSettings(props: IConfirmChildrenProps) {
}));
};
- const handleModeChange = (mode: IPageSettings['mode']) => {
- setSettings((prev) => ({ ...prev, mode }));
- };
+ // const handleModeChange = (mode: IPageSettings['mode']) => {
+ // setSettings((prev) => ({ ...prev, mode }));
+ // };
const handleModernWidthChange = (modernWidth: ModernDocumentWidthMode) => {
setSettings((prev) => ({ ...prev, modernWidth }));
@@ -162,7 +162,7 @@ export function PageSettings(props: IConfirmChildrenProps) {
return (
<div className="univer-flex univer-flex-col univer-gap-4">
- <div
+ {/* <div
className="
univer-grid univer-grid-cols-2 univer-rounded-lg univer-bg-gray-100 univer-p-1
dark:!univer-bg-gray-800
@@ -186,7 +186,7 @@ export function PageSettings(props: IConfirmChildrenProps) {
{localeService.t<LocaleKey>(mode === DocumentFlavor.MODERN ? 'docs-ui.page-settings.modern-mode' : 'docs-ui.page-settings.classic-mode')}
</button>
))}
- </div>
+ </div> */}
{settings.mode === DocumentFlavor.MODERN
? (
diff --git a/packages/docs-ui/src/views/__tests__/PageSettings.spec.tsx b/packages/docs-ui/src/views/__tests__/PageSettings.spec.tsx
deleted file mode 100644
index 7a855e6b0b..0000000000
--- a/packages/docs-ui/src/views/__tests__/PageSettings.spec.tsx
+++ /dev/null
@@ -1,168 +0,0 @@
-/**
- * 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 { IConfirmChildrenProps } from '@univerjs/ui';
-import type { Root } from 'react-dom/client';
-import {
- ContextService,
- DocumentDataModel,
- DocumentFlavor,
- IContextService,
- ILogService,
- Injector,
- IUniverInstanceService,
- LocaleService,
- LocaleType,
- ModernDocumentWidthMode,
- PageOrientType,
- UniverInstanceService,
-} from '@univerjs/core';
-import { RediContext } from '@univerjs/ui';
-import { act } from 'react';
-import { createRoot } from 'react-dom/client';
-import { afterEach, describe, expect, it } from 'vitest';
-import { PageSettings } from '../PageSettings';
-
-(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
-
-class TestLogService {
- debug(): void {}
-}
-
-function createPageSettingsTestBed() {
- const injector = new Injector();
- injector.add([ILogService, { useClass: TestLogService as never }]);
- injector.add([IContextService, { useClass: ContextService }]);
- injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);
- injector.add([LocaleService, { useClass: LocaleService }]);
-
- injector.get(LocaleService).load({
- [LocaleType.ZH_CN]: {
- 'docs-ui': {
- 'page-settings': {
- 'modern-mode': 'Modern',
- 'classic-mode': 'Classic',
- 'modern-width': 'Modern width',
- 'modern-width-narrow': 'Narrow',
- 'modern-width-medium': 'Medium',
- 'modern-width-wide': 'Wide',
- 'paper-size': 'Paper size',
- 'custom-paper-size': 'Custom paper size',
- top: 'Top',
- bottom: 'Bottom',
- left: 'Left',
- right: 'Right',
- 'page-size': {
- a4: 'A4',
- letter: 'Letter',
- legal: 'Legal',
- },
- },
- },
- },
- });
-
- const doc = new DocumentDataModel({
- id: 'page-settings-doc',
- documentStyle: {
- documentFlavor: DocumentFlavor.MODERN,
- pageSize: { width: 720, height: 960 },
- pageOrient: PageOrientType.PORTRAIT,
- marginTop: 24,
- marginBottom: 28,
- marginLeft: 32,
- marginRight: 36,
- },
- body: {
- dataStream: '\r\n',
- paragraphs: [],
- sectionBreaks: [],
- customRanges: [],
- tables: [],
- textRuns: [],
- },
- });
- (injector.get(IUniverInstanceService) as UniverInstanceService).__addUnit(doc);
-
- return { injector };
-}
-
-function renderPageSettings(hooks: IConfirmChildrenProps['hooks']) {
- const { injector } = createPageSettingsTestBed();
- const container = document.createElement('div');
- document.body.appendChild(container);
- const root = createRoot(container);
-
- act(() => {
- root.render(
- <RediContext.Provider value={{ injector }}>
- <PageSettings hooks={hooks} />
- </RediContext.Provider>
- );
- });
-
- return { container, root };
-}
-
-function clickButton(container: HTMLElement, text: string) {
- const button = Array.from(container.querySelectorAll('button')).find((button) => button.textContent?.includes(text));
- if (!button) {
- throw new Error(`Missing button: ${text}`);
- }
-
- button.dispatchEvent(new MouseEvent('click', { bubbles: true }));
-}
-
-describe('PageSettings', () => {
- let root: Root | undefined;
- let container: HTMLElement | undefined;
-
- afterEach(() => {
- if (root) {
- act(() => root!.unmount());
- }
- container?.remove();
- root = undefined;
- container = undefined;
- });
-
- it('returns the selected page mode and modern width through confirm hooks', () => {
- const hooks: IConfirmChildrenProps['hooks'] = {};
- const rendered = renderPageSettings(hooks);
- root = rendered.root;
- container = rendered.container;
-
- act(() => clickButton(container!, 'Wide'));
- expect(hooks.beforeConfirm?.()).toMatchObject({
- mode: DocumentFlavor.MODERN,
- modernWidth: ModernDocumentWidthMode.WIDE,
- pageSize: { width: 720, height: 960 },
- margins: {
- top: 24,
- bottom: 28,
- left: 32,
- right: 36,
- },
- });
-
- act(() => clickButton(container!, 'Classic'));
- expect(hooks.beforeClose?.()).toMatchObject({
- mode: DocumentFlavor.TRADITIONAL,
- paperSize: 'A4',
- pageSize: { width: 720, height: 960 },
- });
- });
-});