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.

17.3 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 { IAccessor } from '@univerjs/core';
import type { Observable } from 'rxjs';
import { createIdentifier, Disposable, IConfigService, Inject, Injector, merge } from '@univerjs/core';
import { Subject } from 'rxjs';
import type { IMenuItem, MenuConfig } from './menu';
import { mergeMenuConfigs } from '../../common/menu-merge-configs';
import {
    ContextMenuGroup,
    ContextMenuPosition,
    FloatingObjectToolbarPosition,
    MenuManagerPosition,
    RibbonDataGroup,
    RibbonFormulasGroup,
    RibbonInsertGroup,
    RibbonOthersGroup,
    RibbonPosition,
    RibbonStartGroup,
    RibbonViewGroup,
} from './types';

export const IMenuManagerService = createIdentifier<IMenuManagerService>('univer.menu-manager-service');

export type ContextMenuQuickLayout = 'icon' | 'tile';
export type ContextMenuQuickLayoutVariant = 'default' | 'compact';
export type MobileMenuLayout = 'grid' | 'list';

export interface IRibbonGridLayout {
    /** 1-based row within the ribbon group's two rows. */
    row: number;
    /** 1-based column within the ribbon group. */
    column: number;
    /** Number of rows occupied. Defaults to 1; use 2 for a large button. */
    rowSpan?: number;
    /** Number of columns occupied. Defaults to 1. */
    columnSpan?: number;
    /** Whether to display the menu title alongside its icon. */
    showLabel?: boolean;
    /** Width in pixels. */
    width?: number;
    /** Width used before the ribbon moves this group into More. */
    minWidth?: number;
    /** Icon size in pixels. */
    iconSize?: number;
}

export interface IMenuSchema {
    key: string;
    order: number;
    title?: string;
    contextual?: boolean;
    item?: IMenuItem;
    headerActionItem?: IMenuItem;
    children?: IMenuSchema[];
    quickLayout?: ContextMenuQuickLayout;
    quickColumns?: number;
    quickLayoutVariant?: ContextMenuQuickLayoutVariant;
    mobileLayout?: MobileMenuLayout;
    tiny?: boolean;
    gridLayout?: IRibbonGridLayout;
}

export interface IMenuManagerService {
    readonly menuChanged$: Observable<void>;

    mergeMenu(source: MenuSchemaType, target?: MenuSchemaType): void;

    appendRootMenu(source: MenuSchemaType): void;

    updateMenuConfig(config: MenuConfig): void;

    getMenuByPositionKey(position: string): IMenuSchema[];

    getFlatMenuByPositionKey(position: string): IMenuSchema[];
}

export type MenuSchemaType = {
    order?: number;
    replace?: boolean;
    menuItemFactory?: (accessor: IAccessor) => IMenuItem;
    headerActionMenuItemFactory?: (accessor: IAccessor) => IMenuItem;
    title?: string;
    contextual?: boolean;
    quickLayout?: ContextMenuQuickLayout;
    quickColumns?: number;
    quickLayoutVariant?: ContextMenuQuickLayoutVariant;
    mobileLayout?: MobileMenuLayout;
    tiny?: boolean;
    gridLayout?: IRibbonGridLayout;
} | {
    [key: string]: MenuSchemaType;
};

export class MenuManagerService extends Disposable implements IMenuManagerService {
    readonly menuChanged$ = new Subject<void>();

    private _menu: MenuSchemaType = {
        [MenuManagerPosition.RIBBON]: {
            [RibbonPosition.START]: {
                order: 0,
                title: 'ui.ribbon.start',
                [RibbonStartGroup.HISTORY]: {
                    order: 0,
                    title: 'ui.ribbon.groups.clipboard',
                },
                [RibbonStartGroup.FORMAT]: {
                    order: 1,
                    title: 'ui.ribbon.groups.font',
                },
                [RibbonStartGroup.LAYOUT]: {
                    order: 2,
                    title: 'ui.ribbon.groups.layout',
                },
                [RibbonStartGroup.NUMBER]: {
                    order: 3,
                    title: 'ui.ribbon.groups.number',
                },
                [RibbonStartGroup.OTHERS]: {
                    order: 4,
                    title: 'ui.ribbon.groups.tools',
                },
            },
            [RibbonPosition.INSERT]: {
                order: 1,
                title: 'ui.ribbon.insert',
                [RibbonInsertGroup.EDIT]: {
                    order: 0,
                    title: 'ui.ribbon.groups.editing',
                },
                [RibbonInsertGroup.MEDIA]: {
                    order: 1,
                    title: 'ui.ribbon.groups.media',
                },
                [RibbonInsertGroup.CELL]: {
                    order: 2,
                    title: 'ui.ribbon.groups.cells',
                },
                [RibbonInsertGroup.OTHERS]: {
                    order: 3,
                    title: 'ui.ribbon.groups.tools',
                },
            },
            [RibbonPosition.FORMULAS]: {
                order: 2,
                title: 'ui.ribbon.formulas',
                [RibbonFormulasGroup.BASIC]: {
                    order: 0,
                    title: 'ui.ribbon.groups.formulas',
                },
                [RibbonFormulasGroup.OTHERS]: {
                    order: 1,
                    title: 'ui.ribbon.groups.tools',
                },
            },
            [RibbonPosition.DATA]: {
                order: 3,
                title: 'ui.ribbon.data',
                [RibbonDataGroup.FORMULAS]: {
                    order: 0,
                    title: 'ui.ribbon.groups.formulas',
                },
                [RibbonDataGroup.RULES]: {
                    order: 1,
                    title: 'ui.ribbon.groups.rules',
                },
                [RibbonDataGroup.ORGANIZATION]: {
                    order: 2,
                    title: 'ui.ribbon.groups.organization',
                },
                [RibbonDataGroup.OTHERS]: {
                    order: 3,
                    title: 'ui.ribbon.groups.tools',
                },
            },
            [RibbonPosition.VIEW]: {
                order: 4,
                title: 'ui.ribbon.view',
                [RibbonViewGroup.DISPLAY]: {
                    order: 0,
                    title: 'ui.ribbon.groups.display',
                },
                [RibbonViewGroup.VISIBILITY]: {
                    order: 0,
                    title: 'ui.ribbon.groups.visibility',
                },
                [RibbonViewGroup.OTHERS]: {
                    order: 0,
                    title: 'ui.ribbon.groups.tools',
                },
            },
            [RibbonPosition.OTHERS]: {
                order: 5,
                title: 'ui.ribbon.others',
                [RibbonOthersGroup.OTHERS]: {
                    order: 0,
                    title: 'ui.ribbon.groups.tools',
                },
            },
        },
        [MenuManagerPosition.CONTEXT_MENU]: {
            [ContextMenuPosition.MAIN_AREA]: {
                order: 0,
                [ContextMenuGroup.QUICK]: {
                    order: -1,
                    quickLayout: 'icon',
                },
                [ContextMenuGroup.FORMAT]: {
                    order: 0,
                },
                [ContextMenuGroup.LAYOUT]: {
                    order: 1,
                },
                [ContextMenuGroup.DATA]: {
                    order: 2,
                },
                [ContextMenuGroup.OTHERS]: {
                    order: 3,
                },
            },
            [ContextMenuPosition.PARAGRAPH]: {
                order: 0,
                [ContextMenuGroup.QUICK]: {
                    order: -1,
                    quickLayout: 'icon',
                },
                [ContextMenuGroup.FORMAT]: {
                    order: 0,
                },
                [ContextMenuGroup.LAYOUT]: {
                    order: 1,
                },
                [ContextMenuGroup.DATA]: {
                    order: 2,
                },
                [ContextMenuGroup.OTHERS]: {
                    order: 3,
                },
            },
            [ContextMenuPosition.COL_HEADER]: {
                order: 1,
                [ContextMenuGroup.QUICK]: {
                    order: -1,
                    quickLayout: 'icon',
                },
                [ContextMenuGroup.FORMAT]: {
                    order: 0,
                },
                [ContextMenuGroup.LAYOUT]: {
                    order: 1,
                },
                [ContextMenuGroup.DATA]: {
                    order: 2,
                },
                [ContextMenuGroup.OTHERS]: {
                    order: 3,
                },
            },
            [ContextMenuPosition.ROW_HEADER]: {
                order: 2,
                [ContextMenuGroup.QUICK]: {
                    order: -1,
                    quickLayout: 'icon',
                },
                [ContextMenuGroup.FORMAT]: {
                    order: 0,
                },
                [ContextMenuGroup.LAYOUT]: {
                    order: 1,
                },
                [ContextMenuGroup.DATA]: {
                    order: 2,
                },
                [ContextMenuGroup.OTHERS]: {
                    order: 3,
                },
            },
            [ContextMenuPosition.FOOTER_TABS]: {
                order: 3,
                [ContextMenuGroup.FORMAT]: {
                    order: 0,
                },
                [ContextMenuGroup.LAYOUT]: {
                    order: 1,
                },
                [ContextMenuGroup.DATA]: {
                    order: 2,
                },
                [ContextMenuGroup.OTHERS]: {
                    order: 3,
                },
            },
            [ContextMenuPosition.FOOTER_MENU]: {
                order: 4,
                [ContextMenuGroup.OTHERS]: {
                    order: 3,
                },
            },
            [ContextMenuPosition.DRAWING]: {
                order: 5,
                [ContextMenuGroup.OTHERS]: {
                    order: 3,
                },
            },
        },
        [FloatingObjectToolbarPosition.SHEET]: {},
        [FloatingObjectToolbarPosition.DOC]: {},
        [FloatingObjectToolbarPosition.SLIDE]: {},
        [FloatingObjectToolbarPosition.BOARD]: {},
    };

    constructor(
        @Inject(Injector) private readonly _injector: Injector,
        @IConfigService private readonly _configService: IConfigService
    ) {
        super();
    }

    override dispose(): void {
        this.menuChanged$.complete();
        super.dispose();
    }

    /**
     * Merge source menu to target menu recursively
     * @param source
     * @param target default is root menu
     */
    mergeMenu(source: MenuSchemaType, target?: MenuSchemaType): void {
        const _target = target ?? this._menu;

        for (const [key, value] of Object.entries(_target)) {
            if (key in source) {
                const targetRecord = _target as Record<string, unknown>;
                const sourceRecord = source as Record<string, unknown>;
                targetRecord[key] = mergeMenuSchemaNode(targetRecord[key], sourceRecord[key]);

                this.menuChanged$.next();
            } else if (isMenuSchemaRecord(value)) {
                this.mergeMenu(source, value as MenuSchemaType);
            }
        }
    }

    appendRootMenu(source: MenuSchemaType): void {
        this._menu = merge({}, this._menu, source);
        this.menuChanged$.next();
    }

    updateMenuConfig(config: MenuConfig): void {
        this._configService.setConfig('menu', config, { merge: true });
        this.menuChanged$.next();
    }

    createScoped(injector: Injector): IMenuManagerService {
        const createScopedBuilder = () => {
            const service = new MenuManagerService(injector, this._configService);
            service._menu = this._menu;
            return service;
        };

        return {
            menuChanged$: this.menuChanged$,
            mergeMenu: (source: MenuSchemaType, target?: MenuSchemaType) => this.mergeMenu(source, target),
            appendRootMenu: (source: MenuSchemaType) => this.appendRootMenu(source),
            updateMenuConfig: (config: MenuConfig) => this.updateMenuConfig(config),
            getMenuByPositionKey: (position: string) => createScopedBuilder().getMenuByPositionKey(position),
            getFlatMenuByPositionKey: (position: string) => createScopedBuilder().getFlatMenuByPositionKey(position),
        };
    }

    private _buildMenuSchema(data: MenuSchemaType): IMenuSchema[] {
        const result: IMenuSchema[] = [];
        const menuConfig = this._configService.getConfig<MenuConfig>('menu');

        for (const [key, value] of Object.entries(data)) {
            if (key === 'replace') {
                continue;
            }

            const item: IMenuItem | undefined = value.menuItemFactory ? this._injector.invoke(value.menuItemFactory) : undefined;
            const config = menuConfig?.[item?.id ?? key];
            const menuItem: Partial<IMenuSchema> = {
                key,
                order: config?.order ?? value.order,
                title: value.title,
                contextual: value.contextual,
                quickLayout: value.quickLayout,
                quickColumns: value.quickColumns,
                quickLayoutVariant: value.quickLayoutVariant,
                mobileLayout: value.mobileLayout,
                tiny: value.tiny,
                gridLayout: config?.gridLayout ? { ...value.gridLayout, ...config.gridLayout } : value.gridLayout,
            };

            if (item) {
                menuItem.item = config ? mergeMenuConfigs(item, config) : item;
            }
            if (value.headerActionMenuItemFactory) {
                menuItem.headerActionItem = this._injector.invoke(value.headerActionMenuItemFactory);
            }
            if (typeof value === 'object') {
                const children = this._buildMenuSchema(value);
                if (children.length > 0) {
                    menuItem.children = children.sort((a, b) => a.order - b.order);
                }

                if (menuItem.item || menuItem.children) {
                    result.push(menuItem as IMenuSchema);
                }
            }
        }

        return result.sort((a, b) => normalizeMenuOrder(a.order) - normalizeMenuOrder(b.order));
    }

    /**
     * Get menu schema by position key
     * @param key
     * @returns Menu schema array or empty array if not found
     */
    getMenuByPositionKey(key: string): IMenuSchema[] {
        const findKey = (obj: any): any => {
            if (key in obj) {
                return this._buildMenuSchema(obj[key]);
            }

            for (const k in obj) {
                if (k === key) {
                    return this._buildMenuSchema(obj[k]);
                }
                if (typeof obj[k] === 'object') {
                    const result = findKey(obj[k]);
                    if (result) {
                        return result;
                    }
                }
            }
        };

        return findKey(this._menu) ?? [];
    }

    /**
     * Get flat menu schema by position key
     * @param key
     * @returns Flat menu schema array or empty array if not found
     */
    getFlatMenuByPositionKey(key: string): IMenuSchema[] {
        const menu = this.getMenuByPositionKey(key);

        function flatMenuItems(items: IMenuSchema[]): IMenuSchema[] {
            return items.reduce((acc, item) => {
                if (item.children) {
                    return [...acc, item, ...flatMenuItems(item.children)];
                }
                return [...acc, item];
            }, [] as IMenuSchema[]);
        }

        return flatMenuItems(menu);
    }
}

function normalizeMenuOrder(order: number | undefined): number {
    return order ?? 0;
}

function isMenuSchemaRecord(value: unknown): value is Record<string, unknown> {
    return value != null && typeof value === 'object' && !Array.isArray(value);
}

function cloneMenuSchemaNode<T>(source: T, preserveReplace = false): T {
    if (!isMenuSchemaRecord(source)) {
        return source;
    }

    const result: Record<string, unknown> = {};
    for (const [key, value] of Object.entries(source)) {
        if (key === 'replace' && !preserveReplace) {
            continue;
        }

        result[key] = cloneMenuSchemaNode(value, preserveReplace);
    }

    return result as T;
}

function mergeMenuSchemaNode(target: unknown, source: unknown): unknown {
    if (!isMenuSchemaRecord(source) || !isMenuSchemaRecord(target)) {
        return cloneMenuSchemaNode(source);
    }

    if (source.replace === true) {
        return cloneMenuSchemaNode(source, true);
    }

    if (target.replace === true) {
        return cloneMenuSchemaNode(target, true);
    }

    const result = merge({}, target) as Record<string, unknown>;
    for (const [key, value] of Object.entries(source)) {
        if (key === 'replace') {
            continue;
        }

        result[key] = key in result
            ? mergeMenuSchemaNode(result[key], value)
            : cloneMenuSchemaNode(value, true);
    }

    return result;
}