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(docs-ui): add fit-to-width view scaling (#7100)

Univerf8eb48df5b12
diff --git a/packages/docs-ui/src/config/config.ts b/packages/docs-ui/src/config/config.ts
index d380e924e8..9728336d52 100644
--- a/packages/docs-ui/src/config/config.ts
+++ b/packages/docs-ui/src/config/config.ts
@@ -21,17 +21,42 @@ export const DOCS_UI_PLUGIN_CONFIG_KEY = 'docs-ui.config';
export const configSymbol = Symbol(DOCS_UI_PLUGIN_CONFIG_KEY);
+export type DocFitMode = 'none' | 'fit-width';
+export type DocFitTarget = 'viewport' | 'container';
+export type DocFitAlign = 'center' | 'start';
+export type DocFitPaddingX = number | `${number}%`;
+
+export interface IDocFitToWidthOptions {
+ mode?: DocFitMode;
+ target?: DocFitTarget;
+ paddingX?: DocFitPaddingX;
+ minScale?: number;
+ maxScale?: number;
+ align?: DocFitAlign;
+}
+
export interface IUniverDocsUIConfig {
menu?: MenuConfig;
container?: HTMLElement | string;
toc?: boolean;
footer?: boolean;
placeholder?: boolean;
+ fitToWidth?: IDocFitToWidthOptions;
override?: DependencyOverride;
}
+export const DEFAULT_DOC_FIT_TO_WIDTH_OPTIONS: Required<Omit<IDocFitToWidthOptions, 'maxScale'>> & Pick<IDocFitToWidthOptions, 'maxScale'> = {
+ mode: 'none',
+ target: 'viewport',
+ paddingX: 20,
+ minScale: 1,
+ maxScale: undefined,
+ align: 'center',
+};
+
export const defaultPluginConfig: IUniverDocsUIConfig = {
toc: false,
footer: true,
placeholder: true,
+ fitToWidth: DEFAULT_DOC_FIT_TO_WIDTH_OPTIONS,
};
diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/zoom.render-controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/zoom.render-controller.spec.ts
index 1ea476c376..f89c108f60 100644
--- a/packages/docs-ui/src/controllers/render-controllers/__tests__/zoom.render-controller.spec.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/zoom.render-controller.spec.ts
@@ -15,10 +15,34 @@
*/
import { DocumentFlavor } from '@univerjs/core';
-import { describe, expect, it } from 'vitest';
-import { shouldHandleDocWheelZoom } from '../zoom.render-controller';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { DocZoomRenderController, shouldHandleDocWheelZoom } from '../zoom.render-controller';
+
+const mockSceneScale = vi.hoisted(() => vi.fn());
+const mockClearSelectedObjects = vi.hoisted(() => vi.fn());
+
+vi.mock('../../../basics/component-tools', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../../basics/component-tools')>();
+
+ return {
+ ...actual,
+ neoGetDocObject: () => ({
+ scene: {
+ scale: mockSceneScale,
+ getTransformer: () => ({
+ clearSelectedObjects: mockClearSelectedObjects,
+ }),
+ },
+ }),
+ };
+});
describe('DocZoomRenderController', () => {
+ beforeEach(() => {
+ mockSceneScale.mockClear();
+ mockClearSelectedObjects.mockClear();
+ });
+
it('handles wheel zoom intent for focused modern docs', () => {
expect(shouldHandleDocWheelZoom({ ctrlKey: true, metaKey: false }, true, DocumentFlavor.MODERN)).toBe(true);
});
@@ -28,4 +52,28 @@ describe('DocZoomRenderController', () => {
expect(shouldHandleDocWheelZoom({ ctrlKey: false, metaKey: false }, true, DocumentFlavor.TRADITIONAL)).toBe(false);
expect(shouldHandleDocWheelZoom({ ctrlKey: true, metaKey: false }, false, DocumentFlavor.TRADITIONAL)).toBe(false);
});
+
+ it('applies composed view scale while receiving user zoom', () => {
+ const controller = Object.create(DocZoomRenderController.prototype) as DocZoomRenderController;
+ Object.assign(controller, {
+ _context: { unitId: 'doc-unit' },
+ _docViewScaleService: {
+ getViewScale: vi.fn(() => 1.875),
+ },
+ _editorService: {
+ isEditor: vi.fn(() => false),
+ },
+ _docPageLayoutService: {
+ calculatePagePosition: vi.fn(),
+ },
+ _textSelectionManagerService: {
+ refreshSelection: vi.fn(),
+ },
+ });
+
+ controller.updateViewZoom(1.25);
+
+ expect((controller as never as { _docViewScaleService: { getViewScale: ReturnType<typeof vi.fn> } })._docViewScaleService.getViewScale).toHaveBeenCalledWith(1.25);
+ expect(mockSceneScale).toHaveBeenCalledWith(1.875, 1.875);
+ });
});
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.ts
index d0ed7788a8..79ddec9aee 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
@@ -39,6 +39,7 @@ import { SetDocZoomRatioCommand } from '../../commands/commands/set-doc-zoom-rat
import { SwitchDocModeCommand } from '../../commands/commands/switch-doc-mode.command';
import { SetDocZoomRatioOperation } from '../../commands/operations/set-doc-zoom-ratio.operation';
import { DocPageLayoutService } from '../../services/doc-page-layout.service';
+import { DocViewScaleService } from '../../services/doc-view-scale';
import { DEFAULT_MODERN_DOC_ZOOM_RATIO, getDocEffectiveZoomRatio } from '../../services/doc-zoom';
import { IEditorService } from '../../services/editor/editor-manager.service';
@@ -64,7 +65,8 @@ export class DocZoomRenderController extends Disposable implements IRenderModule
@Inject(DocSelectionManagerService) private readonly _textSelectionManagerService: DocSelectionManagerService,
@IEditorService private readonly _editorService: IEditorService,
@Inject(DocPageLayoutService) private readonly _docPageLayoutService: DocPageLayoutService,
- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @Inject(DocViewScaleService) private readonly _docViewScaleService: DocViewScaleService
) {
super();
@@ -139,7 +141,8 @@ export class DocZoomRenderController extends Disposable implements IRenderModule
updateViewZoom(zoomRatio: number, needRefreshSelection = true) {
const docObject = neoGetDocObject(this._context);
- docObject.scene.scale(zoomRatio, zoomRatio);
+ const viewScale = this._docViewScaleService.getViewScale(zoomRatio);
+ docObject.scene.scale(viewScale, viewScale);
if (!this._editorService.isEditor(this._context.unitId)) {
this._docPageLayoutService.calculatePagePosition();
diff --git a/packages/docs-ui/src/index.ts b/packages/docs-ui/src/index.ts
index a7a7f1530c..69020f48f5 100644
--- a/packages/docs-ui/src/index.ts
+++ b/packages/docs-ui/src/index.ts
@@ -120,7 +120,8 @@ export { type IMoveCursorOperationParams, MoveSelectionOperation } from './comma
export { MoveCursorOperation } from './commands/operations/doc-cursor.operation';
export { type ISetDocZoomRatioOperationParams, SetDocZoomRatioOperation } from './commands/operations/set-doc-zoom-ratio.operation';
export { getCommandSkeleton } from './commands/util';
-export type { IUniverDocsUIConfig } from './config/config';
+export type { DocFitAlign, DocFitMode, DocFitTarget, IDocFitToWidthOptions, IUniverDocsUIConfig } from './config/config';
+export { DEFAULT_DOC_FIT_TO_WIDTH_OPTIONS } from './config/config';
export { DocBackScrollRenderController } from './controllers/render-controllers/back-scroll.render-controller';
export { DocParagraphPlaceholderRenderController } from './controllers/render-controllers/doc-paragraph-placeholder.render-controller';
export { DocRenderController } from './controllers/render-controllers/doc.render-controller';
diff --git a/packages/docs-ui/src/plugin.ts b/packages/docs-ui/src/plugin.ts
index 7a4b86f79d..447380c7cf 100644
--- a/packages/docs-ui/src/plugin.ts
+++ b/packages/docs-ui/src/plugin.ts
@@ -126,6 +126,7 @@ import { DocPageLayoutService } from './services/doc-page-layout.service';
import { DocParagraphMenuService } from './services/doc-paragraph-menu.service';
import { DocCanvasPopManagerService } from './services/doc-popup-manager.service';
import { DocPrintInterceptorService } from './services/doc-print-interceptor.service';
+import { DocViewScaleService } from './services/doc-view-scale';
import { DocsRenderService } from './services/docs-render.service';
import { EditorService, IEditorService } from './services/editor/editor-manager.service';
import { DocFloatMenuService } from './services/float-menu.service';
@@ -394,6 +395,7 @@ export class UniverDocsUIPlugin extends Plugin {
[DocSkeletonManagerService],
[DocSelectionRenderService],
[DocInterceptorService],
+ [DocViewScaleService],
[DocPageLayoutService],
[DocIMEInputManagerService],
[DocRenderController],
diff --git a/packages/docs-ui/src/services/__tests__/doc-page-layout.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-page-layout.service.spec.ts
new file mode 100644
index 0000000000..f1e3dc4f70
--- /dev/null
+++ b/packages/docs-ui/src/services/__tests__/doc-page-layout.service.spec.ts
@@ -0,0 +1,156 @@
+/**
+ * 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, vi } from 'vitest';
+import { DocPageLayoutService } from '../doc-page-layout.service';
+
+const mockDocObject = vi.hoisted(() => ({ current: null as unknown }));
+
+vi.mock('../../basics/component-tools', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../basics/component-tools')>();
+
+ return {
+ ...actual,
+ neoGetDocObject: () => mockDocObject.current,
+ };
+});
+
+function createFixture(options: {
+ engineWidth: number;
+ engineHeight: number;
+ docsWidth?: number;
+ docsHeight?: number;
+ viewScale: number;
+ sceneScale?: number;
+ align?: 'center' | 'start';
+ paddingX?: number | `${number}%`;
+}) {
+ const docsComponent = {
+ width: options.docsWidth ?? 960,
+ height: options.docsHeight ?? 1000,
+ pageMarginLeft: 20,
+ pageMarginTop: 20,
+ translate: vi.fn(),
+ };
+ const docBackground = {
+ translate: vi.fn(),
+ };
+ const viewport = {
+ scrollToViewportPos: vi.fn(),
+ };
+ const scene = {
+ scaleX: options.sceneScale ?? options.viewScale,
+ scaleY: options.sceneScale ?? options.viewScale,
+ getParent: vi.fn(() => ({ width: options.engineWidth, height: options.engineHeight })),
+ scale: vi.fn(),
+ resize: vi.fn(),
+ getViewport: vi.fn(() => viewport),
+ };
+ mockDocObject.current = {
+ document: docsComponent,
+ docBackground,
+ scene,
+ };
+
+ const viewScaleService = {
+ getViewScale: vi.fn(() => options.viewScale),
+ getAvailableWidth: vi.fn(() => options.engineWidth),
+ getOptions: vi.fn(() => ({
+ mode: 'fit-width',
+ target: 'viewport',
+ paddingX: options.paddingX ?? 20,
+ minScale: 0,
+ align: options.align ?? 'center',
+ })),
+ };
+ const service = new (DocPageLayoutService as unknown as new (...args: unknown[]) => DocPageLayoutService)(
+ {
+ unit: {
+ getSettings: () => ({ zoomRatio: 1 }),
+ getSnapshot: () => ({ documentStyle: {} }),
+ },
+ },
+ viewScaleService
+ );
+
+ return {
+ docBackground,
+ docsComponent,
+ scene,
+ service,
+ viewScaleService,
+ viewport,
+ };
+}
+
+describe('DocPageLayoutService', () => {
+ it('uses view scale for centered scene geometry', () => {
+ const { docsComponent, scene, service, viewport } = createFixture({
+ engineWidth: 1600,
+ engineHeight: 1200,
+ viewScale: 1.5,
+ });
+
+ service.calculatePagePosition();
+
+ expect(scene.resize).toHaveBeenCalledWith(1040, 773.3333333333334);
+ expect(docsComponent.translate).toHaveBeenCalledWith(53.333333333333336, 20);
+ expect(viewport.scrollToViewportPos).toHaveBeenCalledWith({ viewportScrollX: 0 });
+ });
+
+ it('starts at the container edge when configured with start alignment and no padding', () => {
+ const { docsComponent, service } = createFixture({
+ engineWidth: 480,
+ engineHeight: 800,
+ viewScale: 0.5,
+ align: 'start',
+ paddingX: 0,
+ });
+
+ service.calculatePagePosition();
+
+ expect(docsComponent.translate).toHaveBeenCalledWith(0, 20);
+ });
+
+ it('uses percentage padding for start-aligned fitting', () => {
+ const { docsComponent, service } = createFixture({
+ engineWidth: 1200,
+ engineHeight: 800,
+ viewScale: 1,
+ align: 'start',
+ paddingX: '10%',
+ });
+
+ service.calculatePagePosition();
+
+ expect(docsComponent.translate).toHaveBeenCalledWith(120, 20);
+ });
+
+ it('reapplies view scale when an early container measurement left the scene stale', () => {
+ const { scene, service } = createFixture({
+ engineWidth: 900,
+ engineHeight: 800,
+ viewScale: 1.5,
+ sceneScale: 1 / 600,
+ align: 'start',
+ paddingX: 0,
+ });
+
+ service.calculatePagePosition();
+
+ expect(scene.scale).toHaveBeenCalledWith(1.5, 1.5);
+ });
+});
diff --git a/packages/docs-ui/src/services/__tests__/doc-view-scale.spec.ts b/packages/docs-ui/src/services/__tests__/doc-view-scale.spec.ts
new file mode 100644
index 0000000000..25e1e5b69e
--- /dev/null
+++ b/packages/docs-ui/src/services/__tests__/doc-view-scale.spec.ts
@@ -0,0 +1,175 @@
+/**
+ * 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 { DocumentFlavor, MODERN_DOCUMENT_WIDTH, ModernDocumentWidthMode } from '@univerjs/core';
+import { afterEach, describe, expect, it } from 'vitest';
+import { DEFAULT_DOC_FIT_TO_WIDTH_OPTIONS } from '../../config/config';
+import { calcDocFitToWidthScale, DocViewScaleService, resolveDocFitBaseWidth, resolveDocViewScale } from '../doc-view-scale';
+
+describe('doc view scale helpers', () => {
+ afterEach(() => {
+ document.body.innerHTML = '';
+ });
+
+ it('does not fit when mode is none', () => {
+ expect(calcDocFitToWidthScale({
+ availableWidth: 1600,
+ baseWidth: 800,
+ options: DEFAULT_DOC_FIT_TO_WIDTH_OPTIONS,
+ })).toBe(1);
+ });
+
+ it('fits width with padding and min scale', () => {
+ expect(calcDocFitToWidthScale({
+ availableWidth: 1200,
+ baseWidth: 800,
+ options: { mode: 'fit-width', paddingX: 20, minScale: 1 },
+ })).toBe(1.45);
+ expect(calcDocFitToWidthScale({
+ availableWidth: 600,
+ baseWidth: 800,
+ options: { mode: 'fit-width', paddingX: 20, minScale: 1 },
+ })).toBe(1);
+ });
+
+ it('fits width with percentage padding relative to available width', () => {
+ expect(calcDocFitToWidthScale({
+ availableWidth: 1200,
+ baseWidth: 960,
+ options: { mode: 'fit-width', paddingX: '10%', minScale: 0 },
+ })).toBe(1);
+ });
+
+ it('allows embedded containers to shrink and clamp max scale', () => {
+ expect(calcDocFitToWidthScale({
+ availableWidth: 480,
+ baseWidth: 960,
+ options: { mode: 'fit-width', paddingX: 0, minScale: 0 },
+ })).toBe(0.5);
+ expect(calcDocFitToWidthScale({
+ availableWidth: 2400,
+ baseWidth: 960,
+ options: { mode: 'fit-width', paddingX: 0, minScale: 0, maxScale: 2 },
+ })).toBe(2);
+ });
+
+ it('resolves traditional and modern base widths without table overflow', () => {
+ expect(resolveDocFitBaseWidth({
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ documentStylePageWidth: 794,
+ skeletonPageWidth: 1254,
+ })).toBe(794);
+ expect(resolveDocFitBaseWidth({
+ documentFlavor: DocumentFlavor.MODERN,
+ documentStylePageWidth: undefined,
+ skeletonPageWidth: 1254,
+ })).toBe(MODERN_DOCUMENT_WIDTH[ModernDocumentWidthMode.MEDIUM]);
+ expect(resolveDocFitBaseWidth({
+ documentFlavor: DocumentFlavor.MODERN,
+ documentStylePageWidth: MODERN_DOCUMENT_WIDTH[ModernDocumentWidthMode.WIDE],
+ skeletonPageWidth: 1500,
+ })).toBe(MODERN_DOCUMENT_WIDTH[ModernDocumentWidthMode.WIDE]);
+ });
+
+ it('keeps user zoom separate from fit scale', () => {
+ expect(resolveDocViewScale(1.25, 0.5)).toBe(0.625);
+ expect(resolveDocViewScale(1, 1.5)).toBe(1.5);
+ });
+
+ it('computes view scale from engine width, document zoom, and configured page width', () => {
+ const context = {
+ engine: { width: 1440 },
+ unit: {
+ getSettings: () => ({ zoomRatio: 1.25 }),
+ getSnapshot: () => ({
+ documentStyle: {
+ documentFlavor: DocumentFlavor.MODERN,
+ pageSize: { width: 960, height: Number.POSITIVE_INFINITY },
+ },
+ }),
+ },
+ };
+ const service = new DocViewScaleService(
+ context as never,
+ { getConfig: () => ({ fitToWidth: { mode: 'fit-width', paddingX: 0, minScale: 0 } }) } as never
+ );
+
+ expect(service.getFitToWidthScale()).toBe(1.5);
+ expect(service.getViewScale()).toBe(1.875);
+ });
+
+ it('uses configured container width for container-targeted fitting', () => {
+ const context = {
+ engine: { width: 960 },
+ unit: {
+ getSettings: () => ({ zoomRatio: 1 }),
+ getSnapshot: () => ({
+ documentStyle: {
+ documentFlavor: DocumentFlavor.MODERN,
+ pageSize: { width: 960, height: Number.POSITIVE_INFINITY },
+ },
+ }),
+ },
+ };
+ const service = new DocViewScaleService(
+ context as never,
+ {
+ getConfig: () => ({
+ container: { clientWidth: 480 },
+ fitToWidth: { mode: 'fit-width', target: 'container', paddingX: 0, minScale: 0 },
+ }),
+ } as never
+ );
+
+ expect(service.getAvailableWidth()).toBe(480);
+ expect(service.getFitToWidthScale()).toBe(0.5);
+ });
+
+ it('resolves string containers as element ids for embedded fitting', () => {
+ const container = document.createElement('div');
+ container.id = 'univerdoc';
+ Object.defineProperty(container, 'clientWidth', {
+ configurable: true,
+ value: 480,
+ });
+ document.body.appendChild(container);
+
+ const context = {
+ engine: { width: 960 },
+ unit: {
+ getSettings: () => ({ zoomRatio: 1 }),
+ getSnapshot: () => ({
+ documentStyle: {
+ documentFlavor: DocumentFlavor.MODERN,
+ pageSize: { width: 960, height: Number.POSITIVE_INFINITY },
+ },
+ }),
+ },
+ };
+ const service = new DocViewScaleService(
+ context as never,
+ {
+ getConfig: () => ({
+ container: 'univerdoc',
+ fitToWidth: { mode: 'fit-width', target: 'container', paddingX: 0, minScale: 0 },
+ }),
+ } as never
+ );
+
+ expect(service.getAvailableWidth()).toBe(480);
+ expect(service.getFitToWidthScale()).toBe(0.5);
+ });
+});
diff --git a/packages/docs-ui/src/services/doc-page-layout.service.ts b/packages/docs-ui/src/services/doc-page-layout.service.ts
index 3d44a87aa1..86b1b57516 100644
--- a/packages/docs-ui/src/services/doc-page-layout.service.ts
+++ b/packages/docs-ui/src/services/doc-page-layout.service.ts
@@ -16,14 +16,15 @@
import type { DocumentDataModel } from '@univerjs/core';
import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
-import { Disposable } from '@univerjs/core';
+import { Disposable, Inject } from '@univerjs/core';
import { neoGetDocObject } from '../basics/component-tools';
import { VIEWPORT_KEY } from '../basics/docs-view-key';
-import { getDocEffectiveZoomRatio } from './doc-zoom';
+import { DocViewScaleService, resolveDocFitPaddingX } from './doc-view-scale';
export class DocPageLayoutService extends Disposable implements IRenderModule {
constructor(
- private _context: IRenderContext<DocumentDataModel>
+ private _context: IRenderContext<DocumentDataModel>,
+ @Inject(DocViewScaleService) private readonly _docViewScaleService: DocViewScaleService
) {
super();
}
@@ -32,13 +33,20 @@ export class DocPageLayoutService extends Disposable implements IRenderModule {
if (this._disposed) return;
const docObject = neoGetDocObject(this._context);
- const docDataModel = this._context.unit;
- const zoomRatio = getDocEffectiveZoomRatio(docDataModel);
+ const viewScale = this._docViewScaleService.getViewScale();
+ const fitOptions = this._docViewScaleService.getOptions();
+ const isStartAlignedFit = fitOptions.mode === 'fit-width' && fitOptions.align === 'start';
const { document: docsComponent, scene, docBackground } = docObject;
+ if (scene.scaleX !== viewScale || scene.scaleY !== viewScale) {
+ scene.scale(viewScale, viewScale);
+ }
const parent = scene?.getParent();
const { width: docsWidth, height: docsHeight, pageMarginLeft, pageMarginTop } = docsComponent;
+ const horizontalMargin = isStartAlignedFit
+ ? resolveDocFitPaddingX(this._docViewScaleService.getAvailableWidth(), fitOptions.paddingX) / viewScale
+ : pageMarginLeft;
if (parent == null || docsWidth === Number.POSITIVE_INFINITY || docsHeight === Number.POSITIVE_INFINITY) {
return;
@@ -53,21 +61,20 @@ export class DocPageLayoutService extends Disposable implements IRenderModule {
let scrollToX = Number.POSITIVE_INFINITY;
- if (engineWidth > (docsWidth + pageMarginLeft * 2) * zoomRatio) {
- docsLeft = engineWidth / 2 - (docsWidth * zoomRatio) / 2;
- docsLeft /= zoomRatio;
- sceneWidth = (engineWidth - pageMarginLeft * 2) / zoomRatio;
+ if (engineWidth > (docsWidth + horizontalMargin * 2) * viewScale) {
+ docsLeft = isStartAlignedFit ? horizontalMargin : (engineWidth / 2 - (docsWidth * viewScale) / 2) / viewScale;
+ sceneWidth = (engineWidth - horizontalMargin * 2) / viewScale;
scrollToX = 0;
} else {
- docsLeft = pageMarginLeft;
- sceneWidth = docsWidth + pageMarginLeft * 2;
+ docsLeft = horizontalMargin;
+ sceneWidth = docsWidth + horizontalMargin * 2;
- scrollToX = (sceneWidth - engineWidth / zoomRatio) / 2;
+ scrollToX = isStartAlignedFit ? 0 : (sceneWidth - engineWidth / viewScale) / 2;
}
if (engineHeight > docsHeight) {
- sceneHeight = (engineHeight - pageMarginTop * 2) / zoomRatio;
+ sceneHeight = (engineHeight - pageMarginTop * 2) / viewScale;
} else {
sceneHeight = docsHeight + pageMarginTop * 2;
}
diff --git a/packages/docs-ui/src/services/doc-view-scale.ts b/packages/docs-ui/src/services/doc-view-scale.ts
new file mode 100644
index 0000000000..8a40ee227e
--- /dev/null
+++ b/packages/docs-ui/src/services/doc-view-scale.ts
@@ -0,0 +1,162 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { DocumentDataModel } from '@univerjs/core';
+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import type { IDocFitToWidthOptions, IUniverDocsUIConfig } from '../config/config';
+import { Disposable, DocumentFlavor, IConfigService, MODERN_DOCUMENT_WIDTH, ModernDocumentWidthMode } from '@univerjs/core';
+import { DEFAULT_DOC_FIT_TO_WIDTH_OPTIONS, DOCS_UI_PLUGIN_CONFIG_KEY } from '../config/config';
+import { getDocEffectiveZoomRatio } from './doc-zoom';
+
+export interface ICalcDocFitToWidthScaleParams {
+ availableWidth: number;
+ baseWidth: number;
+ options?: IDocFitToWidthOptions;
+}
+
+export interface IResolveDocFitBaseWidthParams {
+ documentFlavor?: DocumentFlavor;
+ documentStylePageWidth?: number;
+ skeletonPageWidth?: number;
+}
+
+export function normalizeDocFitToWidthOptions(options?: IDocFitToWidthOptions) {
+ return {
+ ...DEFAULT_DOC_FIT_TO_WIDTH_OPTIONS,
+ ...options,
+ };
+}
+
+export function resolveDocFitPaddingX(availableWidth: number, paddingX: IDocFitToWidthOptions['paddingX']): number {
+ if (typeof paddingX === 'number') {
+ return Number.isFinite(paddingX) ? paddingX : 0;
+ }
+
+ if (typeof paddingX === 'string') {
+ const trimmedPadding = paddingX.trim();
+ if (trimmedPadding.endsWith('%')) {
+ const percent = Number(trimmedPadding.slice(0, -1));
+ return Number.isFinite(percent) ? availableWidth * percent / 100 : 0;
+ }
+ }
+
+ return 0;
+}
+
+export function calcDocFitToWidthScale(params: ICalcDocFitToWidthScaleParams): number {
+ const options = normalizeDocFitToWidthOptions(params.options);
+ if (options.mode !== 'fit-width') {
+ return 1;
+ }
+
+ if (!Number.isFinite(params.availableWidth) || !Number.isFinite(params.baseWidth) || params.baseWidth <= 0) {
+ return 1;
+ }
+
+ const paddingX = resolveDocFitPaddingX(params.availableWidth, options.paddingX);
+ const availableWidth = Math.max(0, params.availableWidth - paddingX * 2);
+ const rawScale = availableWidth / params.baseWidth;
+ const maxScale = options.maxScale ?? Number.POSITIVE_INFINITY;
+
+ return Math.min(maxScale, Math.max(options.minScale, rawScale));
+}
+
+export function resolveDocFitBaseWidth(params: IResolveDocFitBaseWidthParams): number {
+ if (params.documentStylePageWidth != null && Number.isFinite(params.documentStylePageWidth) && params.documentStylePageWidth > 0) {
+ return params.documentStylePageWidth;
+ }
+
+ if (params.documentFlavor === DocumentFlavor.MODERN) {
+ return MODERN_DOCUMENT_WIDTH[ModernDocumentWidthMode.MEDIUM];
+ }
+
+ if (params.skeletonPageWidth != null && Number.isFinite(params.skeletonPageWidth) && params.skeletonPageWidth > 0) {
+ return params.skeletonPageWidth;
+ }
+
+ return MODERN_DOCUMENT_WIDTH[ModernDocumentWidthMode.MEDIUM];
+}
+
+export function resolveDocViewScale(userZoomRatio: number, fitToWidthScale: number): number {
+ return userZoomRatio * fitToWidthScale;
+}
+
+export class DocViewScaleService extends Disposable implements IRenderModule {
+ constructor(
+ private readonly _context: IRenderContext<DocumentDataModel>,
+ @IConfigService private readonly _configService: IConfigService
+ ) {
+ super();
+ }
+
+ getPluginConfig(): Partial<IUniverDocsUIConfig> {
+ return this._configService.getConfig<IUniverDocsUIConfig>(DOCS_UI_PLUGIN_CONFIG_KEY) ?? {};
+ }
+
+ getOptions(): IDocFitToWidthOptions {
+ return this.getPluginConfig().fitToWidth ?? DEFAULT_DOC_FIT_TO_WIDTH_OPTIONS;
+ }
+
+ getBaseWidth(): number {
+ const documentStyle = this._context.unit.getSnapshot().documentStyle;
+ return resolveDocFitBaseWidth({
+ documentFlavor: documentStyle.documentFlavor,
+ documentStylePageWidth: documentStyle.pageSize?.width,
+ });
+ }
+
+ getAvailableWidth(): number {
+ const config = this.getPluginConfig();
+ const options = normalizeDocFitToWidthOptions(config.fitToWidth);
+ if (options.target === 'container') {
+ const container = this._resolveContainer(config.container);
+ const containerWidth = container?.clientWidth;
+ if (containerWidth != null && Number.isFinite(containerWidth) && containerWidth > 0) {
+ return containerWidth;
+ }
+ }
+
+ return this._context.engine.width;
+ }
+
+ getUserZoomRatio(): number {
+ return getDocEffectiveZoomRatio(this._context.unit);
+ }
+
+ getFitToWidthScale(): number {
+ return calcDocFitToWidthScale({
+ availableWidth: this.getAvailableWidth(),
+ baseWidth: this.getBaseWidth(),
+ options: this.getOptions(),
+ });
+ }
+
+ getViewScale(userZoomRatio = this.getUserZoomRatio()): number {
+ return resolveDocViewScale(userZoomRatio, this.getFitToWidthScale());
+ }
+
+ private _resolveContainer(container?: HTMLElement | string): HTMLElement | undefined {
+ if (container == null) {
+ return undefined;
+ }
+
+ if (typeof container === 'string') {
+ return document.querySelector<HTMLElement>(container) ?? document.getElementById(container) ?? undefined;
+ }
+
+ return container;
+ }
+}
diff --git a/packages/docs-ui/src/services/index.ts b/packages/docs-ui/src/services/index.ts
index d6d94824a4..73adb187e5 100644
--- a/packages/docs-ui/src/services/index.ts
+++ b/packages/docs-ui/src/services/index.ts
@@ -18,3 +18,5 @@ export { default as PastePluginLark } from './clipboard/html-to-udm/paste-plugin
export { default as PastePluginUniver } from './clipboard/html-to-udm/paste-plugins/plugin-univer';
export { default as PastePluginWord } from './clipboard/html-to-udm/paste-plugins/plugin-word';
export { type IPastePlugin } from './clipboard/html-to-udm/paste-plugins/type';
+export { calcDocFitToWidthScale, DocViewScaleService, normalizeDocFitToWidthOptions, resolveDocFitBaseWidth, resolveDocViewScale } from './doc-view-scale';
+export type { ICalcDocFitToWidthScaleParams, IResolveDocFitBaseWidthParams } from './doc-view-scale';