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.

7.4 KB
Raw Blame
/**
 * 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 '@univerjs/core';
import { debounce } from '@univerjs/core';
import { DocSkeletonManagerService } from '@univerjs/docs';
import { ScrollBar } from '@univerjs/engine-render';
import { useCallback, useEffect, useLayoutEffect, useMemo } from 'react';
import type { Editor } from '../../../services/editor/editor';
import { DOCS_VIEW_KEY, VIEWPORT_KEY } from '../../../basics/docs-view-key';

interface IUseResizeReturn {
    resize: () => void;
    checkScrollBar: () => void;
}

export function resizeEditor(
    editor: Editor,
    isSingle: boolean,
    layoutSize?: Readonly<Pick<DOMRectReadOnly, 'width' | 'height'>>,
    pixelRatio?: number,
    documentLayoutSize?: Readonly<Pick<DOMRectReadOnly, 'width' | 'height'>>
): void {
    if (editor.render.isDisposed()) {
        return;
    }
    const selection = editor.docSelectionRenderService;
    // Stored logical ranges outlive the visible caret when another editor takes focus.
    const restoreSelection = selection.isFocusing ||
        selection.getAllTextRanges().length > 0 ||
        selection.getAllRectRanges().length > 0;
    const { scene, mainComponent } = editor.render;
    const docSkeletonManagerService = editor.render.with(DocSkeletonManagerService);
    const { width, height } = layoutSize ?? editor.getBoundingClientRect();

    if (layoutSize || documentLayoutSize || pixelRatio !== undefined) {
        editor.render.engine.resizeBySize(width, height);
    }
    if (pixelRatio !== undefined) {
        editor.render.engine.getCanvas().setPixelRatio(pixelRatio);
    }

    const documentWidth = documentLayoutSize?.width ?? width;
    docSkeletonManagerService.getViewModel().getDataModel().updateDocumentDataPageSize(
        isSingle ? Infinity : documentWidth,
        Infinity
    );
    scene.transformByState({
        width,
        height,
    });

    mainComponent?.resize(documentWidth, height);
    mainComponent?.translate(0, 0);
    editor.render.components.get(DOCS_VIEW_KEY.BACKGROUND)?.translate(0, 0);

    const selectionRanges = editor.getSelectionRanges();
    if (restoreSelection && selectionRanges.length > 0) {
        editor.setSelectionRanges(selectionRanges, false);
    }
}

export const useResize = (
    editor?: Editor,
    isSingle = true,
    autoScrollbar?: boolean,
    autoScroll?: boolean,
    layoutSize?: Readonly<Pick<DOMRectReadOnly, 'width' | 'height'>>,
    pixelRatio?: number,
    documentLayoutSize?: Readonly<Pick<DOMRectReadOnly, 'width' | 'height'>>
): IUseResizeReturn => {
    const resize = useCallback(() => {
        if (editor) {
            resizeEditor(editor, isSingle, layoutSize, pixelRatio, documentLayoutSize);
        }
    }, [documentLayoutSize, editor, isSingle, layoutSize, pixelRatio]);

    const checkScrollBar = useMemo(() => {
        // eslint-disable-next-line complexity
        return debounce(() => {
            if (!editor || editor.render.isDisposed()) {
                return;
            }

            const docSkeletonManagerService = editor.render.with(DocSkeletonManagerService);
            const { scene, mainComponent } = editor.render;
            const viewportMain = scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
            if (!autoScrollbar) {
                if (layoutSize && autoScroll === false) {
                    viewportMain?.scrollToBarPos({ x: 0, y: 0 });
                    viewportMain?.getScrollBar()?.dispose();
                }
                return;
            }
            const skeleton = docSkeletonManagerService.getSkeleton();
            const { actualWidth, actualHeight } = skeleton.getActualSize();
            const { width, height } = layoutSize ?? editor.getBoundingClientRect();
            let scrollBar = viewportMain?.getScrollBar() as Nullable<ScrollBar>;
            const contentWidth = Math.max(actualWidth, width);
            const contentHeight = Math.max(actualHeight, height);

            scene.transformByState({
                width: contentWidth,
                height: contentHeight,
            });

            mainComponent?.resize(contentWidth, contentHeight);
            if (!isSingle) {
                if (actualHeight > height) {
                    if (scrollBar == null) {
                        if (viewportMain) {
                            scrollBar = new ScrollBar(viewportMain, {
                                enableHorizontal: false,
                                enableVertical: true,
                                barSize: 8,
                                minThumbSizeV: 8,
                            });
                        }
                    } else {
                        viewportMain?.resetCanvasSizeAndUpdateScroll();
                    }
                    autoScroll && viewportMain?.scrollToBarPos({ x: 0, y: Infinity });
                } else {
                    scrollBar = null;
                    viewportMain?.scrollToBarPos({ x: 0, y: 0 });
                    viewportMain?.getScrollBar()?.dispose();
                }
            } else {
                if (actualWidth > width) {
                    if (scrollBar == null) {
                        viewportMain && new ScrollBar(viewportMain, {
                            barSize: 8,
                            enableVertical: false,
                            enableHorizontal: true,
                            minThumbSizeV: 8,
                        });
                    } else {
                        viewportMain?.resetCanvasSizeAndUpdateScroll();
                    }
                    autoScroll && viewportMain?.scrollToBarPos({ x: Infinity, y: 0 });
                } else {
                    scrollBar = null;
                    viewportMain?.scrollToBarPos({ x: 0, y: 0 });
                    viewportMain?.getScrollBar()?.dispose();
                }
            }
        }, 30);
    }, [editor, autoScrollbar, isSingle, autoScroll, layoutSize]);

    useLayoutEffect(() => {
        if (editor && (layoutSize || documentLayoutSize || pixelRatio !== undefined)) {
            resize();
        }
    }, [documentLayoutSize, editor, layoutSize, pixelRatio, resize]);

    useEffect(() => {
        if (!autoScrollbar) return;
        if (editor) {
            const time = setTimeout(() => {
                resize();
                checkScrollBar();
            }, 500);
            return () => {
                clearTimeout(time);
            };
        }
    }, [editor, autoScrollbar, resize, checkScrollBar]);

    useEffect(() => {
        if (!autoScrollbar && !(layoutSize && autoScroll === false)) {
            return;
        }
        if (editor) {
            const d = editor.input$.subscribe(() => {
                checkScrollBar();
            });
            return () => {
                d.unsubscribe();
            };
        }
    }, [autoScroll, editor, autoScrollbar, checkScrollBar, layoutSize]);

    return { resize, checkScrollBar };
};