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.

10.1 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 { Workbook } from '@univerjs/core';
import type { ICollaborator, UnitAction } from '@univerjs/protocol';
import {
    IAuthzIoService,
    ICommandService,
    ILogService,
    IPermissionService,
    IUniverInstanceService,
    LocaleService,
    UniverInstanceType,
} from '@univerjs/core';
import { ActionRow, borderTopClassName, Button, clsx, Switch } from '@univerjs/design';
import { ObjectScope, UnitObject, UnitRole } from '@univerjs/protocol';
import {
    getAllWorksheetPermissionPoint,
    SetWorksheetPermissionPointsCommand,
    WorksheetProtectionPointModel,
} from '@univerjs/sheets';
import { IDialogService, useDependency } from '@univerjs/ui';
import { useEffect, useState } from 'react';
import type { LocaleKey } from '../../locale/types';
import {
    defaultWorksheetUnitActionList,
    subUnitPermissionTypeMap,
    UNIVER_SHEET_PERMISSION_DIALOG_ID,
} from '../../consts/permission';
import Spin from './Spin';

interface IPermissionMap {
    [key: string]: {
        text: string;
        allowed: boolean;
    };
}

export interface ISheetPermissionDialogProps {
    ActionRowComponent?: typeof ActionRow;
}

export const SheetPermissionDialog = ({ ActionRowComponent = ActionRow }: ISheetPermissionDialogProps = {}) => {
    const localeService = useDependency(LocaleService);
    const logService = useDependency(ILogService);
    const univerInstanceService = useDependency(IUniverInstanceService);
    const authzIoService = useDependency(IAuthzIoService);
    const worksheetProtectionPointRuleModel = useDependency(WorksheetProtectionPointModel);
    const dialogService = useDependency(IDialogService);
    const permissionService = useDependency(IPermissionService);
    const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
    const worksheet = workbook.getActiveSheet();
    const unitId = workbook.getUnitId();
    const subUnitId = worksheet.getSheetId();

    const [collaborators, setCollaborators] = useState<ICollaborator[]>([]);
    const commandService = useDependency(ICommandService);
    const [loading, setLoading] = useState(() => {
        const pointRule = worksheetProtectionPointRuleModel.getRule(unitId, subUnitId);
        return !!pointRule;
    });

    const [permissionMap, setPermissionMap] = useState(() => {
        return Object.keys(subUnitPermissionTypeMap).reduce((acc, action) => {
            acc[action] = {
                text: localeService.t(`sheets-ui.permission.panel.${subUnitPermissionTypeMap[Number(action) as UnitAction]}`),
                allowed: true,
            };
            return acc;
        }, {} as IPermissionMap);
    });

    useEffect(() => {
        let cancelled = false;

        authzIoService.listCollaborators({
            objectID: unitId,
            unitID: unitId,
        }).then((collaborators) => {
            if (!cancelled) {
                setCollaborators(collaborators);
            }
        }).catch((error) => logService.error(error));

        return () => {
            cancelled = true;
        };
    }, [authzIoService, logService, unitId]);

    useEffect(() => {
        let cancelled = false;
        let loadingTimer: ReturnType<typeof setTimeout> | undefined;

        const worksheetPointRule = worksheetProtectionPointRuleModel.getRule(unitId, subUnitId);
        if (worksheetPointRule) {
            setLoading(true);

            authzIoService.list({
                unitID: unitId,
                objectIDs: [worksheetPointRule.permissionId],
                actions: defaultWorksheetUnitActionList,
            }).then((result) => {
                if (cancelled) {
                    return;
                }

                const actions = result[0].strategies.reduce((p, c) => {
                    if (subUnitPermissionTypeMap[c.action]) {
                        p[c.action] = {
                            text: localeService.t(`sheets-ui.permission.panel.${subUnitPermissionTypeMap[c.action]}`),
                            allowed: c.role !== UnitRole.Owner,
                        };
                    }
                    return p;
                }, {} as IPermissionMap);
                setPermissionMap(actions);
                loadingTimer = setTimeout(() => {
                    setLoading(false);
                }, 100);
            }).catch((error) => logService.error(error));
        }

        return () => {
            cancelled = true;
            if (loadingTimer !== undefined) {
                clearTimeout(loadingTimer);
            }
        };
    }, [authzIoService, localeService, logService, subUnitId, unitId, worksheetProtectionPointRuleModel]);

    const handleChangeActionPermission = async () => {
        const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
        const worksheet = workbook?.getActiveSheet();
        if (!worksheet) {
            throw new Error('No active sheet found');
        }
        const unitId = workbook.getUnitId();
        const subUnitId = worksheet.getSheetId();
        const pointRule = worksheetProtectionPointRuleModel.getRule(unitId, subUnitId);

        const actions = Object.keys(permissionMap).map((action) => {
            return {
                action: Number(action) as UnitAction,
                role: permissionMap[action].allowed ? UnitRole.Editor : UnitRole.Owner,
            };
        });

        let permissionId = pointRule?.permissionId;

        if (!permissionId) {
            permissionId = await authzIoService.create({
                objectType: UnitObject.Worksheet,
                worksheetObject: {
                    unitID: unitId,
                    collaborators,
                    name: '',
                    strategies: actions,
                    scope: {
                        read: ObjectScope.AllCollaborator,
                        edit: ObjectScope.AllCollaborator,
                    },
                },
            });

            commandService.executeCommand(SetWorksheetPermissionPointsCommand.id, {
                rule: {
                    permissionId,
                    unitId,
                    subUnitId,
                },
            });
        } else {
            authzIoService.update({
                objectType: UnitObject.Worksheet,
                objectID: permissionId,
                unitID: unitId,
                strategies: actions,
                share: undefined,
                name: '',
                scope: {
                    read: ObjectScope.AllCollaborator,
                    edit: ObjectScope.AllCollaborator,
                },
                collaborators: undefined,
            }).then(() => {
                getAllWorksheetPermissionPoint().forEach((F) => {
                    const instance = new F(unitId, subUnitId);
                    const unitActionName = instance.subType;
                    const action = actions.find((item) => item.action === unitActionName);
                    if (action) {
                        permissionService.updatePermissionPoint(instance.id, action.role === UnitRole.Editor);
                    }
                });
            });
        }
    };

    return (
        <Spin loading={loading}>
            <div className={clsx('univer-flex univer-flex-col univer-gap-2 univer-pt-2', borderTopClassName)}>
                {Object.keys(permissionMap).map((action) => {
                    const actionItem = permissionMap[action];
                    const { text, allowed } = actionItem;
                    return (
                        <div
                            key={text}
                            className="univer-flex univer-h-5 univer-items-center univer-justify-between"
                        >
                            <span className="univer-text-sm">{text}</span>
                            <Switch
                                aria-label={text}
                                defaultChecked={allowed}
                                onChange={() => {
                                    setPermissionMap({
                                        ...permissionMap,
                                        [action]: {
                                            ...actionItem,
                                            allowed: !allowed,
                                        },
                                    });
                                }}
                            />
                        </div>
                    );
                })}

                <ActionRowComponent
                    className={clsx(`
                      univer-flex univer-h-9 univer-items-center univer-justify-end univer-gap-2 univer-pt-2
                    `, borderTopClassName)}
                >
                    <Button
                        onClick={() => {
                            dialogService.close(UNIVER_SHEET_PERMISSION_DIALOG_ID);
                        }}
                    >
                        {localeService.t<LocaleKey>('sheets-ui.permission.button.cancel')}
                    </Button>
                    <Button
                        variant="primary"
                        onClick={() => {
                            handleChangeActionPermission();
                            dialogService.close(UNIVER_SHEET_PERMISSION_DIALOG_ID);
                        }}
                    >
                        {localeService.t<LocaleKey>('sheets-ui.permission.button.confirm')}
                    </Button>
                </ActionRowComponent>
            </div>
        </Spin>
    );
};