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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat(permission): persist object policies and stabilize Docs editing (#7634)
Univer9ac4614f2db2
diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 20f4b1262d..d0d1c46b74 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -106,6 +106,13 @@ export { DesktopLogService, ILogService, LogLevel } from './services/log/log.serexport { MentionIOLocalService } from './services/mention-io/mention-io-local.service';export { IMentionIOService } from './services/mention-io/type';export type { IListMentionParam, IListMentionResponse, ITypeMentionList } from './services/mention-io/type';+export { ObjectPermissionRuleModel } from './services/permission/object-permission-rule.model';+export type {+ IObjectPermissionRule,+ ISetObjectPermissionRuleMutationParams,+} from './services/permission/object-permission-rule.model';+export { OBJECT_PERMISSION_CONFIG_KEY, ObjectPermissionService } from './services/permission/object-permission.service';+export type { IObjectPermissionPolicy, IObjectPermissionTarget } from './services/permission/object-permission.service';export { PermissionService } from './services/permission/permission.service';export { IPermissionService, PermissionStatus } from './services/permission/type';export type { IPermissionParam } from './services/permission/type';@@ -181,5 +188,6 @@ export type {IDataValidationRuleOptions,ISheetDataValidationRule,} from './types/interfaces/i-data-validation';+export { Univer } from './univer';export type { IUniverConfig } from './univer';diff --git a/packages/core/src/services/error/error.service.ts b/packages/core/src/services/error/error.service.tsindex 750316b016..9ca0a9b584 100644--- a/packages/core/src/services/error/error.service.ts+++ b/packages/core/src/services/error/error.service.ts@@ -19,6 +19,8 @@ import { Disposable } from '../../shared/lifecycle';export interface IError {errorKey: string;+ code?: 'PERMISSION_DENIED';+ permissionTarget?: string;}export class ErrorService extends Disposable {@@ -29,6 +31,14 @@ export class ErrorService extends Disposable {this._error$.complete();}+ emitPermissionDenied(unitId: string, objectIds: Iterable<string> = []): void {+ this._error$.next({+ errorKey: 'Permission denied.',+ code: 'PERMISSION_DENIED',+ permissionTarget: JSON.stringify([unitId, [...new Set(objectIds)].sort()]),+ });+ }+emit(key: string): void {this._error$.next({ errorKey: key });}diff --git a/packages/core/src/services/permission/__tests__/object-permission.service.spec.ts b/packages/core/src/services/permission/__tests__/object-permission.service.spec.tsnew file mode 100644index 0000000000..9605f30629--- /dev/null+++ b/packages/core/src/services/permission/__tests__/object-permission.service.spec.ts@@ -0,0 +1,273 @@+/**+ * 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 {+ IAllowedRequest,+ ICreateRequest,+ IListPermPointResponse,+ IUpdatePermPointRequest,+} from '@univerjs/protocol';+import type { ISetObjectPermissionRuleMutationParams } from '../object-permission-rule.model';+import { ObjectScope, UnitAction, UnitObject, UnitRole } from '@univerjs/protocol';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { UniverInstanceType } from '../../../common/unit';+import { Univer } from '../../../univer';+import { IAuthzIoService } from '../../authz-io/type';+import { CommandType, ICommandService } from '../../command/command.service';+import { IConfigService } from '../../config/config.service';+import { IUniverInstanceService } from '../../instance/instance.service';+import { IResourceManagerService } from '../../resource-manager/type';+import { IUndoRedoService } from '../../undoredo/undoredo.service';+import { UserManagerService } from '../../user-manager/user-manager.service';+import { ObjectPermissionRuleModel } from '../object-permission-rule.model';+import { OBJECT_PERMISSION_CONFIG_KEY, ObjectPermissionService } from '../object-permission.service';+import { IPermissionService, PermissionStatus } from '../type';++const univers: Univer[] = [];+afterEach(() => univers.splice(0).forEach((univer) => univer.dispose()));+const types = [UnitObject.DocumentParagraph, UnitObject.SlideElement, UnitObject.BaseField, UnitObject.BoardElement];+const roots = [UnitObject.Document, UnitObject.Slide, UnitObject.Base, UnitObject.Board];+class TestRuleModel extends ObjectPermissionRuleModel {+ constructor(@IResourceManagerService resources: IResourceManagerService) {+ super(resources, 'UNIVER_TEST_PERMISSION_PLUGIN', UniverInstanceType.UNIVER_DOC, types);+ }+}+function createAuthz() {+ let policies: IListPermPointResponse['objects'] = [];+ let editorAllowed = true;+ let sequence = 0;+ const authz = {+ create: vi.fn(async (request: ICreateRequest) => {+ const payload = request.documentObject ?? request.slideObject ?? request.baseObject ?? request.boardObject!;+ const objectID = `permission-${++sequence}`;+ policies.push({ ...payload, objectID, objectType: request.objectType, creator: undefined, actions: [], shareOn: false, shareRole: UnitRole.Reader, shareScope: 0 });+ return objectID;+ }),+ list: vi.fn(async ({ objectIDs }: { objectIDs: string[] }) => policies.filter((policy) => objectIDs.includes(policy.objectID))),+ listCollaborators: vi.fn(async () => []),+ allowed: vi.fn(async ({ actions }: IAllowedRequest) => actions.map((action) => ({ action, allowed: true }))),+ batchAllowed: vi.fn(async (requests: IAllowedRequest[]) => requests.map((request) => ({ ...request, actions: request.actions.map((action) => ({ action, allowed: editorAllowed })) }))),+ update: vi.fn(async (request: IUpdatePermPointRequest) => {+ policies = policies.filter((policy) => policy.objectID !== request.objectID);+ policies.push({ ...request, creator: undefined, actions: [], shareOn: false, shareRole: UnitRole.Reader, shareScope: 0 });+ }),+ };+ return { authz, setAllowed: (allowed: boolean) => {+ editorAllowed = allowed;+ } };+}+function createClient(authz: ReturnType<typeof createAuthz>['authz'], enabled = true) {+ const univer = new Univer({ override: [[IAuthzIoService, { useValue: authz }]] });+ univers.push(univer);+ const injector = univer.__getInjector();+ injector.add([TestRuleModel]);+ const model = injector.get(TestRuleModel);+ const service = injector.get(ObjectPermissionService);+ const commands = injector.get(ICommandService);+ commands.registerCommand({ id: 'test.mutation.permission', type: CommandType.MUTATION, handler: (_, params: ISetObjectPermissionRuleMutationParams) => model.setRule(params.unitId, params.objectType, params.objectId, params.rule) });+ roots.forEach((root) => service.registerRuleModel(root, model, 'test.mutation.permission'));+ injector.get(IConfigService).setConfig(OBJECT_PERMISSION_CONFIG_KEY, enabled ? [...types, ...roots] : []);+ univer.createUnit(UniverInstanceType.UNIVER_DOC, { id: 'unit', body: { dataStream: '\r\n' } });+ injector.get(IUniverInstanceService).focusUnit('unit');+ return { service, model, commands, resources: injector.get(IResourceManagerService), history: injector.get(IUndoRedoService), permissions: injector.get(IPermissionService), users: injector.get(UserManagerService) };+}+function target(objectType: UnitObject, objectId = 'element/page/a') {+ return { unitId: 'unit', objectId, objectType };+}+function point(objectType: UnitObject) {+ return { id: `${objectType}.${UnitAction.Edit}_unit_element/page/a`, unitId: 'unit', objectId: 'element/page/a', type: objectType, subType: UnitAction.Edit, value: true, status: PermissionStatus.INIT };+}+const restriction = { edit: 'owner' as const, collaborators: [], strategies: [] };++describe('ObjectPermissionService', () => {+ it.each(types)('preserves local overrides without remote opt-in (%s)', async (objectType) => {+ const backend = createAuthz();+ const client = createClient(backend.authz, false);+ await client.service.setPoint(target(objectType), point(objectType), false);+ expect(client.permissions.getPermissionPoint(point(objectType).id)?.value).toBe(false);+ await client.service.setPoint(target(objectType), point(objectType), true);+ expect(client.permissions.getPermissionPoint(point(objectType).id)?.value).toBe(true);+ await expect(client.service.save(target(objectType), restriction)).rejects.toThrow('not supported');+ expect(backend.authz.create).not.toHaveBeenCalled();+ expect(backend.authz.list).not.toHaveBeenCalled();+ expect(backend.authz.update).not.toHaveBeenCalled();+ });++ it.each(types)('persists server-issued IDs in resources and resolves effective rights after reload (%s)', async (objectType) => {+ const backend = createAuthz();+ const first = createClient(backend.authz);+ backend.setAllowed(false);+ await first.service.setPoint(target(objectType), point(objectType), false);+ const rule = first.model.getRule('unit', objectType, 'element/page/a')!;+ expect(rule.permissionId).toBe('permission-1');+ expect(backend.authz.update).not.toHaveBeenCalled();+ expect(first.permissions.getPermissionPoint(point(objectType).id)?.value).toBe(false);+ const second = createClient(backend.authz);+ second.resources.loadResources('unit', first.resources.getResources('unit', UniverInstanceType.UNIVER_DOC));+ await second.service.refreshUnit('unit');+ expect(second.model.getRules('unit')).toEqual([rule]);+ expect(second.permissions.getPermissionPoint(point(objectType).id)?.value).toBe(false);+ expect(second.service.hasPolicy(target(objectType))).toBe(true);+ expect(backend.authz.list.mock.calls.every(([request]) => request.objectIDs.length > 0 && !request.objectIDs.includes('element/page/a'))).toBe(true);+ await second.service.save(target(objectType), restriction);+ expect(backend.authz.update).toHaveBeenCalledWith(expect.objectContaining({ objectID: rule.permissionId, objectType, unitID: 'unit' }));+ expect(backend.authz.create).toHaveBeenCalledTimes(1);+ });++ it('removes only the binding and reuses the Authz rule on undo and collaboration replay', async () => {+ const backend = createAuthz();+ backend.setAllowed(false);+ const client = createClient(backend.authz);+ const object = target(UnitObject.BoardElement);+ await client.service.save(object, restriction);+ await client.service.remove(object);+ expect(client.model.getRules('unit')).toEqual([]);+ expect(client.permissions.getPermissionPoint(point(object.objectType).id)?.value).toBe(true);+ const undo = client.history.pitchTopUndoElement()!;+ expect(undo.undoMutations).toHaveLength(1);+ await client.commands.executeCommand(undo.undoMutations[0].id, undo.undoMutations[0].params);+ await client.service.refreshUnit('unit');+ expect(client.service.hasPolicy(object)).toBe(true);+ expect(client.permissions.getPermissionPoint(point(object.objectType).id)?.value).toBe(false);+ const peer = createClient(backend.authz);+ await peer.commands.executeCommand(undo.undoMutations[0].id, undo.undoMutations[0].params);+ await peer.service.refreshUnit('unit');+ expect(peer.model.getRules('unit')).toEqual(client.model.getRules('unit'));+ await client.commands.executeCommand(undo.redoMutations[0].id, undo.redoMutations[0].params);+ expect(client.model.getRules('unit')).toEqual([]);+ expect(backend.authz.create).toHaveBeenCalledTimes(1);+ expect(backend.authz.update).not.toHaveBeenCalled();+ });++ it('does not publish a binding or undo entry when creation fails', async () => {+ const backend = createAuthz();+ const client = createClient(backend.authz);+ backend.authz.create.mockRejectedValueOnce(new Error('Forbidden'));+ await expect(client.service.save(target(UnitObject.BoardElement), restriction)).rejects.toThrow('Forbidden');+ expect(client.model.getRules('unit')).toEqual([]);+ expect(client.history.pitchTopUndoElement()).toBeNull();+ });++ it('keeps owner effective access distinct from the saved policy and rejects failed updates', async () => {+ const backend = createAuthz();+ const client = createClient(backend.authz);+ const object = target(UnitObject.BoardElement);+ await client.service.save(object, restriction);+ expect(client.permissions.getPermissionPoint(point(object.objectType).id)?.value).toBe(true);+ expect(client.service.hasPolicy(object)).toBe(true);+ backend.authz.update.mockRejectedValueOnce(new Error('Forbidden'));+ await expect(client.service.save(object, { ...restriction, edit: 'all' })).rejects.toThrow('Forbidden');+ expect(client.service.hasPolicy(object)).toBe(true);+ });++ it.each(types)('checks Create on the file, Manage and Delete on the persisted rule (%s)', async (objectType) => {+ const backend = createAuthz();+ const client = createClient(backend.authz);+ backend.authz.allowed.mockImplementation(async ({ actions }) => actions.map((action) => ({ action, allowed: action === UnitAction.CreatePermissionObject })));+ await client.service.save(target(objectType), restriction);+ expect(backend.authz.allowed).toHaveBeenCalledWith({ unitID: 'unit', objectID: 'unit', objectType: roots[types.indexOf(objectType)], actions: [UnitAction.CreatePermissionObject] });+ await expect(client.service.save(target(objectType), restriction)).rejects.toThrow('denied');+ await expect(client.service.remove(target(objectType))).rejects.toThrow('denied');+ expect(backend.authz.allowed).toHaveBeenLastCalledWith({ unitID: 'unit', objectID: 'permission-1', objectType, actions: [UnitAction.Delete] });+ expect(client.model.getRules('unit')).toHaveLength(1);+ });++ it('allows the server-declared creator while keeping Authz write enforcement', async () => {+ const backend = createAuthz();+ const client = createClient(backend.authz);+ const object = target(UnitObject.BoardElement);+ await client.service.save(object, restriction);+ const [policy] = await backend.authz.list({ objectIDs: ['permission-1'] });+ backend.authz.list.mockResolvedValue([{ ...policy, creator: { userID: 'creator', name: 'Creator', avatar: '' } }]);+ backend.authz.allowed.mockResolvedValue([{ action: UnitAction.ManageCollaborator, allowed: false }]);+ client.users.setCurrentUser({ userID: 'creator', name: 'Creator' });+ expect(await client.service.canManage(object)).toBe(true);+ backend.authz.update.mockRejectedValueOnce(new Error('Forbidden'));+ await expect(client.service.save(object, restriction)).rejects.toThrow('Forbidden');+ client.users.setCurrentUser({ userID: 'editor', name: 'Editor' });+ expect(await client.service.canManage(object)).toBe(false);+ });++ it('preserves unrelated strategies and read scope when updating one point', async () => {+ const backend = createAuthz();+ const client = createClient(backend.authz);+ const object = target(UnitObject.BoardElement);+ await client.service.save(object, restriction);+ await backend.authz.update({ unitID: 'unit', objectID: 'permission-1', objectType: object.objectType, name: 'Object', share: undefined, strategies: [{ action: UnitAction.Copy, role: UnitRole.Owner }], scope: { edit: ObjectScope.AllCollaborator, read: ObjectScope.SomeCollaborator }, collaborators: undefined });+ await client.service.setPoint(object, point(object.objectType), false);+ expect(backend.authz.update).toHaveBeenLastCalledWith(expect.objectContaining({ name: 'Object', strategies: expect.arrayContaining([{ action: UnitAction.Copy, role: UnitRole.Owner }]), scope: { edit: ObjectScope.OneSelf, read: ObjectScope.SomeCollaborator } }));+ });++ it('does not overwrite a concurrent binding while Authz creation is pending', async () => {+ const backend = createAuthz();+ const client = createClient(backend.authz);+ const object = target(UnitObject.BoardElement);+ let finish!: (id: string) => void;+ backend.authz.create.mockImplementationOnce(() => new Promise((resolve) => {+ finish = resolve;+ }));+ const save = client.service.save(object, restriction);+ const rejected = expect(save).rejects.toThrow('binding changed');+ await vi.waitFor(() => expect(backend.authz.create).toHaveBeenCalledTimes(1));+ const rule = { objectId: object.objectId, objectType: object.objectType, permissionId: 'remote-rule' };+ await client.commands.executeCommand('test.mutation.permission', { ...object, rule });+ expect(client.permissions.getPermissionPoint(point(object.objectType).id)?.value).toBe(false);+ finish('local-rule');+ await rejected;+ expect(client.model.getRules('unit')).toEqual([rule]);+ expect(client.history.pitchTopUndoElement()).toBeNull();+ expect(client.commands.syncExecuteCommand('test.mutation.permission', { ...object })).toBe(false);+ expect(client.model.getRules('unit')).toEqual([rule]);+ });++ it('does not reinterpret an unresolved persisted rule as permission to create a replacement', async () => {+ const backend = createAuthz();+ const client = createClient(backend.authz);+ const object = target(UnitObject.BoardElement);+ await client.service.save(object, restriction);+ backend.authz.list.mockResolvedValue([]);+ expect(await client.service.canManage(object)).toBe(false);+ await expect(client.service.save(object, restriction)).rejects.toThrow('denied');+ expect(backend.authz.create).toHaveBeenCalledTimes(1);+ expect(client.model.getRules('unit')[0].permissionId).toBe('permission-1');+ });++ it('preserves file membership when changing root operation permissions', async () => {+ const backend = createAuthz();+ const client = createClient(backend.authz);+ const object = target(UnitObject.Board, 'unit');+ await client.service.save(object, restriction);+ expect(backend.authz.update).toHaveBeenCalledWith(expect.objectContaining({ objectID: 'unit', collaborators: undefined }));+ await expect(client.service.save(object, { ...restriction, edit: 'members' })).rejects.toThrow('sharing service');+ expect(client.model.getRules('unit')).toEqual([]);+ expect(backend.authz.create).not.toHaveBeenCalled();+ });++ it('discards a refresh completed after the Unit was disposed', async () => {+ const backend = createAuthz();+ const client = createClient(backend.authz);+ await client.service.save(target(UnitObject.BoardElement), restriction);+ let finish!: (policies: IListPermPointResponse['objects']) => void;+ backend.authz.list.mockImplementationOnce(() => new Promise((resolve) => {+ finish = resolve;+ }));+ const refresh = client.service.refreshUnit('unit');+ client.service.clearUnit('unit');+ finish([]);+ await refresh;+ expect(client.service.getPolicies('unit')).toEqual([]);+ });+});diff --git a/packages/core/src/services/permission/object-permission-rule.model.ts b/packages/core/src/services/permission/object-permission-rule.model.tsnew file mode 100644index 0000000000..5af25dcad2--- /dev/null+++ b/packages/core/src/services/permission/object-permission-rule.model.ts@@ -0,0 +1,103 @@+/**+ * 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 { UnitObject } from '@univerjs/protocol';+import type { UniverInstanceType } from '../../common/unit';+import type { IResourceManagerService, IResourceName } from '../resource-manager/type';+import { Subject } from 'rxjs';+import { Disposable } from '../../shared/lifecycle';+import { Tools } from '../../shared/tools';++export interface IObjectPermissionRule {+ objectId: string;+ objectType: UnitObject;+ permissionId: string;+}++export interface ISetObjectPermissionRuleMutationParams {+ unitId: string;+ objectId: string;+ objectType: UnitObject;+ rule: IObjectPermissionRule | null;+}++/** Shared storage only; each product owns its rule type, resource name and mutation. */+export abstract class ObjectPermissionRuleModel<T extends IObjectPermissionRule = IObjectPermissionRule> extends Disposable {+ private readonly _rules = new Map<string, Map<string, T>>();+ private readonly _changes = new Subject<string>();+ readonly changed$ = this._changes.asObservable();++ protected constructor(resources: IResourceManagerService, name: IResourceName, business: UniverInstanceType, private readonly _objectTypes: readonly UnitObject[]) {+ super();+ this.disposeWithMe(resources.registerPluginResource<T[]>({+ pluginName: name,+ businesses: [business],+ toJson: (unitId) => JSON.stringify(this.getRules(unitId)),+ parseJson: (json) => {+ const rules: unknown = JSON.parse(json);+ if (!Array.isArray(rules) || rules.some((rule) => !rule || typeof rule.objectId !== 'string' ||+ typeof rule.permissionId !== 'string' || !rule.permissionId || !this._objectTypes.includes(rule.objectType))) {+ throw new Error('Invalid object permission resource.');+ }+ return rules;+ },+ onLoad: (unitId, rules) => {+ this._rules.set(unitId, new Map(rules.map((rule) => [this._key(rule.objectType, rule.objectId), Tools.deepClone(rule)])));+ this._changes.next(unitId);+ },+ onUnLoad: (unitId) => {+ this._rules.delete(unitId);+ this._changes.next(unitId);+ },+ }));+ this.disposeWithMe(() => {+ this._rules.clear();+ this._changes.complete();+ });+ }++ getRules(unitId: string): T[] {+ return [...(this._rules.get(unitId)?.values() ?? [])].map((rule) => Tools.deepClone(rule));+ }++ getRule(unitId: string, objectType: UnitObject, objectId: string): T | undefined {+ const rule = this._rules.get(unitId)?.get(this._key(objectType, objectId));+ return rule && Tools.deepClone(rule);+ }++ setRule(unitId: string, objectType: UnitObject, objectId: string, rule: T | null): boolean {+ if (!unitId || !objectId || !this._objectTypes.includes(objectType) || (rule !== null &&+ (!rule || rule.objectId !== objectId || rule.objectType !== objectType || typeof rule.permissionId !== 'string' || !rule.permissionId))) {+ return false;+ }+ let rules = this._rules.get(unitId);+ if (!rules) {+ rules = new Map();+ this._rules.set(unitId, rules);+ }+ if (rule) {+ rules.set(this._key(objectType, objectId), Tools.deepClone(rule));+ } else {+ rules.delete(this._key(objectType, objectId));+ }+ this._changes.next(unitId);+ return true;+ }++ private _key(objectType: UnitObject, objectId: string): string {+ return `${objectType}/${objectId}`;+ }+}diff --git a/packages/core/src/services/permission/object-permission.service.ts b/packages/core/src/services/permission/object-permission.service.tsnew file mode 100644index 0000000000..04125d0517--- /dev/null+++ b/packages/core/src/services/permission/object-permission.service.ts@@ -0,0 +1,467 @@+/**+ * 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 { IBatchAllowedResponse, ICollaborator, ICreateRequest, IListPermPointResponse } from '@univerjs/protocol';+import type { IDisposable } from '../../common/di';+import type { IObjectPermissionRule, ObjectPermissionRuleModel } from './object-permission-rule.model';+import type { IPermissionPoint } from './type';+import { ObjectScope, UnitAction, UnitObject, UnitRole } from '@univerjs/protocol';+import { BehaviorSubject, Subject } from 'rxjs';+import { Inject, Injector } from '../../common/di';+import { Disposable, toDisposable } from '../../shared/lifecycle';+import { IAuthzIoService } from '../authz-io/type';+import { ICommandService } from '../command/command.service';+import { IConfigService } from '../config/config.service';+import { ILogService } from '../log/log.service';+import { IUndoRedoService } from '../undoredo/undoredo.service';+import { UserManagerService } from '../user-manager/user-manager.service';+import { IPermissionService, PermissionStatus } from './type';++export interface IObjectPermissionTarget {+ unitId: string;+ objectId: string;+ objectType: IPermissionPoint['type'];+}++export interface IObjectPermissionPolicy {+ /** All Unit editors, the object owner, or selected Unit collaborators. Parent restrictions still apply. */+ edit: 'all' | 'owner' | 'members';+ collaborators: ICollaborator[];+ strategies: IListPermPointResponse['objects'][number]['strategies'];+}++/** Frontend opt-in; does not change the Authz service interface or existing local setters. */+export const OBJECT_PERMISSION_CONFIG_KEY = 'objectPermissionTypes';++const ROOT_OBJECT_TYPES: Partial<Record<UnitObject, UnitObject>> = {+ [UnitObject.Document]: UnitObject.Document,+ [UnitObject.DocumentSection]: UnitObject.Document,+ [UnitObject.DocumentParagraph]: UnitObject.Document,+ [UnitObject.DocumentEntity]: UnitObject.Document,+ [UnitObject.Slide]: UnitObject.Slide,+ [UnitObject.SlidePage]: UnitObject.Slide,+ [UnitObject.SlideElement]: UnitObject.Slide,+ [UnitObject.SlideMaster]: UnitObject.Slide,+ [UnitObject.Base]: UnitObject.Base,+ [UnitObject.BaseTable]: UnitObject.Base,+ [UnitObject.BaseField]: UnitObject.Base,+ [UnitObject.BaseRecord]: UnitObject.Base,+ [UnitObject.BaseView]: UnitObject.Base,+ [UnitObject.BaseDashboard]: UnitObject.Base,+ [UnitObject.Board]: UnitObject.Board,+ [UnitObject.BoardElement]: UnitObject.Board,+};++/** Coordinates Authz policy writes and the current user's effective permission cache. */+export class ObjectPermissionService extends Disposable {+ private readonly _models = new Map<UnitObject, { model: ObjectPermissionRuleModel; mutationId: string }>();+ private readonly _initialized = new Set<string>();+ private readonly _policies = new Map<string, IListPermPointResponse['objects'][number][]>();+ private readonly _generations = new Map<string, number>();+ private _nextGeneration = 0;+ private readonly _revision = new BehaviorSubject(0);+ readonly changed$ = this._revision.asObservable();+ private readonly _unitChanges = new Subject<string>();+ readonly unitChanges$ = this._unitChanges.asObservable();++ constructor(+ @Inject(Injector) private readonly _injector: Injector,+ @IPermissionService private readonly _permissions: IPermissionService,+ @ILogService private readonly _logService: ILogService,+ @Inject(UserManagerService) private readonly _users: UserManagerService,+ @IConfigService private readonly _config: IConfigService,+ @ICommandService private readonly _commands: ICommandService+ ) {+ super();+ this.disposeWithMe(this._permissions.permissionPointUpdate$.subscribe((point) => {+ if (point.subType === UnitAction.Edit && ROOT_OBJECT_TYPES[point.type] === point.type) {+ this._revision.next(this._revision.value + 1);+ }+ }));+ this.disposeWithMe(() => {+ this._initialized.clear();+ this._policies.clear();+ this._generations.clear();+ this._revision.complete();+ this._unitChanges.complete();+ });+ }++ private get _authz(): IAuthzIoService {+ return this._injector.get(IAuthzIoService);+ }++ registerRuleModel(rootType: UnitObject, model: ObjectPermissionRuleModel, mutationId: string): IDisposable {+ if (this._models.has(rootType)) {+ throw new Error('Object permission rule model already registered.');+ }+ this._models.set(rootType, { model, mutationId });+ const subscription = model.changed$.subscribe((unitId) => {+ this._generations.delete(unitId);+ this._policies.delete(unitId);+ // A replayed binding takes effect immediately; do not leave old editable rights while Authz loads.+ model.getRules(unitId).forEach((rule) => {+ if (!this.supports({ unitId, objectId: rule.objectId, objectType: rule.objectType })) {+ return;+ }+ const id = `${rule.objectType}.${UnitAction.Edit}_${unitId}_${rule.objectId}`;+ if (!this._permissions.getPermissionPoint(id)) {+ this._permissions.addPermissionPoint({ id, type: rule.objectType, subType: UnitAction.Edit, value: false, status: PermissionStatus.INIT, unitId, objectId: rule.objectId } as IPermissionPoint);+ } else {+ this._permissions.updatePermissionPoint(id, false);+ }+ });+ this._revision.next(this._revision.value + 1);+ if (this._initialized.has(unitId)) {+ this.refreshUnit(unitId).catch((error: unknown) => this._logService.error(error));+ }+ });+ return this.disposeWithMe(toDisposable(() => {+ subscription.unsubscribe();+ this._models.delete(rootType);+ }));+ }++ private _getRule(target: IObjectPermissionTarget): IObjectPermissionRule | undefined {+ return this._models.get(ROOT_OBJECT_TYPES[target.objectType]!)?.model.getRule(target.unitId, target.objectType, target.objectId);+ }++ private _getAuthzId(target: IObjectPermissionTarget): string | undefined {+ return target.objectId === target.unitId ? target.unitId : this._getRule(target)?.permissionId;+ }++ initializeUnit(target: IObjectPermissionTarget): void {+ if (!this.supports(target) || this._initialized.has(target.unitId)) {+ return;+ }+ this._initialized.add(target.unitId);+ const ids: string[] = [];+ this._permissions.getAllPermissionPoint().forEach((point$) => {+ const subscription = point$.subscribe((point) => {+ if ('unitId' in point && point.unitId === target.unitId) {+ ids.push(point.id);+ }+ });+ subscription.unsubscribe();+ });+ ids.forEach((id) => this._permissions.updatePermissionPoint(id, false));+ this.refreshUnit(target.unitId).catch((error: unknown) => {+ this._logService.error(error);+ });+ }++ supports(target: IObjectPermissionTarget): boolean {+ return this._config.getConfig<UnitObject[]>(OBJECT_PERMISSION_CONFIG_KEY)?.includes(target.objectType) === true &&+ this._models.has(ROOT_OBJECT_TYPES[target.objectType]!);+ }++ getPolicies(unitId: string): readonly IListPermPointResponse['objects'][number][] {+ return this._policies.get(unitId) ?? [];+ }++ hasPolicy(target: IObjectPermissionTarget): boolean {+ const policy = this.getPolicies(target.unitId).find((item) =>+ item.objectID === target.objectId && item.objectType === target.objectType);+ return !!policy && (policy.scope?.edit === ObjectScope.OneSelf ||+ policy.scope?.edit === ObjectScope.SomeCollaborator ||+ policy.strategies.some((strategy) => strategy.role === UnitRole.Owner));+ }++ /** Match Sheet's permission-list entry: require effective file editing, not child editing. */+ canView(target: IObjectPermissionTarget): boolean {+ const rootType = ROOT_OBJECT_TYPES[target.objectType];+ return this.supports(target) && rootType !== undefined &&+ this._permissions.getPermissionPoint(`${rootType}.${UnitAction.Edit}_${target.unitId}`)?.value === true;+ }++ async canManage(target: IObjectPermissionTarget): Promise<boolean> {+ if (!this.supports(target)) {+ return false;+ }+ const object = await this._getPolicy(target);+ if (!this._getRule(target) && target.objectId !== target.unitId) {+ const rootType = ROOT_OBJECT_TYPES[target.objectType];+ return rootType !== undefined && this._allowed({ ...target, objectId: target.unitId, objectType: rootType }, UnitAction.CreatePermissionObject);+ }+ return (target.objectId === target.unitId || !!object) && this._canChangeRule(target, object, UnitAction.ManageCollaborator);+ }++ async canDelete(target: IObjectPermissionTarget): Promise<boolean> {+ if (!this.supports(target) || target.objectId === target.unitId) {+ return false;+ }+ const object = await this._getPolicy(target);+ return !!object && this._canChangeRule(target, object, UnitAction.Delete);+ }++ /** Must be called from a product permission Command; removal restores inheritance by detaching the rule. */+ async remove(target: IObjectPermissionTarget): Promise<void> {+ const permissionId = this._getRule(target)?.permissionId;+ if (!await this.canDelete(target)) {+ throw new Error('Object permission deletion denied.');+ }+ await this._commitRule(target, null, permissionId);+ await this.refreshUnit(target.unitId);+ }++ private async _commitRule(target: IObjectPermissionTarget, rule: IObjectPermissionRule | null, expectedId: string | undefined): Promise<void> {+ const registration = this._models.get(ROOT_OBJECT_TYPES[target.objectType]!);+ if (!registration) {+ throw new Error('Object permission rule model is not registered.');+ }+ const previous = this._getRule(target) ?? null;+ if (previous?.permissionId !== expectedId) {+ throw new Error('Object permission binding changed during the request.');+ }+ const redo = { id: registration.mutationId, params: { ...target, rule } };+ const undo = { id: registration.mutationId, params: { ...target, rule: previous } };+ if (!await this._commands.executeCommand(redo.id, redo.params)) {+ throw new Error('Could not update the object permission binding.');+ }+ this._injector.get(IUndoRedoService).pushUndoRedo({ unitID: target.unitId, redoMutations: [redo], undoMutations: [undo] });+ }++ private async _getPolicy(target: IObjectPermissionTarget) {+ const objectID = this._getAuthzId(target);+ if (!objectID) {+ return undefined;+ }+ const objects = await this._authz.list({ unitID: target.unitId, objectIDs: [objectID], actions: [] });+ return objects.find((item) => item.unitID === target.unitId && item.objectID === objectID && item.objectType === target.objectType);+ }++ private async _allowed(target: IObjectPermissionTarget, action: UnitAction): Promise<boolean> {+ const objectID = this._getAuthzId(target);+ if (!objectID) {+ return false;+ }+ const actions = await this._authz.allowed({ unitID: target.unitId, objectID, objectType: target.objectType, actions: [action] });+ return actions.some((item) => item.action === action && item.allowed === true);+ }++ private async _canChangeRule(target: IObjectPermissionTarget, object: IListPermPointResponse['objects'][number] | undefined, action: UnitAction): Promise<boolean> {+ if (await this._allowed(target, action)) {+ return true;+ }+ // Match Sheet's rule-creator access using server metadata, never the local object's author.+ const creatorId = object?.creator?.userID;+ return !!creatorId && creatorId === this._users.getCurrentUser().userID;+ }++ async read(target: IObjectPermissionTarget): Promise<IObjectPermissionPolicy> {+ const objectID = this._getAuthzId(target);+ if (!objectID) {+ return { edit: 'all', collaborators: [], strategies: [] };+ }+ const [object, collaborators] = await Promise.all([+ this._getPolicy(target),+ target.objectId === target.unitId ? [] : this._authz.listCollaborators({ unitID: target.unitId, objectID }),+ ]);+ let edit: IObjectPermissionPolicy['edit'] = 'all';+ if (object?.scope?.edit === ObjectScope.OneSelf) {+ edit = 'owner';+ } else if (object?.scope?.edit === ObjectScope.SomeCollaborator) {+ edit = 'members';+ } else if (object?.strategies.some((strategy) => strategy.action === UnitAction.Edit && strategy.role === UnitRole.Owner)) {+ edit = 'owner';+ }+ return { edit, collaborators, strategies: object?.strategies ?? [] };+ }++ async setPoint(target: IObjectPermissionTarget, point: IPermissionPoint, value: boolean): Promise<void> {+ // Preserve local overrides until the provider opts this object type into remote management.+ if (!this.supports(target)) {+ if (!this._permissions.getPermissionPoint(point.id)) {+ this._permissions.addPermissionPoint(point);+ }+ this._permissions.updatePermissionPoint(point.id, value);+ return;+ }+ this._assertSupported(target);+ const policy = await this.read(target);+ policy.strategies = policy.strategies.filter((strategy) => strategy.action !== point.subType);+ policy.strategies.push({ action: point.subType, role: value ? UnitRole.Editor : UnitRole.Owner });+ if (point.subType === UnitAction.Edit) {+ policy.edit = value ? 'all' : 'owner';+ }+ await this.save(target, policy);+ }++ /** Must be called from a product permission Command. */+ async save(target: IObjectPermissionTarget, policy: IObjectPermissionPolicy): Promise<void> {+ this._assertSupported(target);+ const permissionId = this._getRule(target)?.permissionId;+ if (!await this.canManage(target)) {+ throw new Error('Object permission management denied.');+ }+ if (target.objectId === target.unitId && policy.edit === 'members') {+ throw new Error('File membership must be managed through the sharing service.');+ }+ if (policy.edit === 'members' && !policy.collaborators.length) {+ throw new Error('Select at least one collaborator.');+ }+ const previous = await this._getPolicy(target);+ const strategies = policy.strategies.filter((strategy) => strategy.action !== UnitAction.Edit);+ strategies.push({ action: UnitAction.Edit, role: policy.edit === 'owner' ? UnitRole.Owner : UnitRole.Editor });+ let editScope = ObjectScope.AllCollaborator;+ if (policy.edit === 'members') {+ editScope = ObjectScope.SomeCollaborator;+ } else if (policy.edit === 'owner') {+ editScope = ObjectScope.OneSelf;+ }+ const scope = { read: previous?.scope?.read ?? ObjectScope.AllCollaborator, edit: editScope };+ let objectID = this._getAuthzId(target);+ if (!objectID) {+ const payload = {+ unitID: target.unitId,+ name: target.objectId,+ strategies,+ scope,+ collaborators: policy.edit === 'members' ? policy.collaborators : [],+ };+ const request: ICreateRequest = { objectType: target.objectType };+ switch (ROOT_OBJECT_TYPES[target.objectType]) {+ case UnitObject.Document:+ request.documentObject = payload;+ break;+ case UnitObject.Slide:+ request.slideObject = payload;+ break;+ case UnitObject.Base:+ request.baseObject = payload;+ break;+ case UnitObject.Board:+ request.boardObject = payload;+ break;+ default: throw new Error('Unsupported object permission type.');+ }+ objectID = await this._authz.create(request);+ if (!objectID) {+ throw new Error('Authz did not return a permission ID.');+ }+ await this._commitRule(target, { objectId: target.objectId, objectType: target.objectType, permissionId: objectID }, permissionId);+ } else {+ if (this._getRule(target)?.permissionId !== permissionId) {+ throw new Error('Object permission binding changed during the request.');+ }+ await this._authz.update({+ unitID: target.unitId,+ objectID,+ objectType: target.objectType,+ name: previous?.name ?? target.objectId,+ share: undefined,+ strategies,+ scope,+ collaborators: target.objectId === target.unitId ? undefined : { collaborators: policy.edit === 'members' ? policy.collaborators : [] },+ });+ }+ // Never use the requested boolean as this user's result: owners and collaborators differ.+ await this.refreshUnit(target.unitId);+ }++ async refreshUnit(unitId: string): Promise<void> {+ if (this._disposed) {+ return;+ }+ const bindings = [...this._models.values()].flatMap(({ model }) => model.getRules(unitId));+ const bindingMap = new Map(bindings.map((rule) => [`${rule.objectType}/${rule.objectId}`, rule]));+ const requests = new Map<string, { unitID: string; objectID: string; objectType: UnitObject; actions: UnitAction[]; targetId: string }>();+ const include = (objectID: string, objectType: UnitObject, targetId: string, actions: UnitAction[]) => {+ if (!this.supports({ unitId, objectId: targetId, objectType })) {+ return;+ }+ const key = `${objectType}/${objectID}`;+ const previous = requests.get(key);+ requests.set(key, { unitID: unitId, objectID, objectType, targetId, actions: [...new Set([...(previous?.actions ?? []), ...actions])] });+ };+ const inheritedPoints: string[] = [];+ bindings.forEach((rule) => include(rule.permissionId, rule.objectType, rule.objectId, [UnitAction.Edit]));+ this._permissions.getAllPermissionPoint().forEach((point$) => {+ const subscription = point$.subscribe((point) => {+ if (!('unitId' in point) || point.unitId !== unitId) {+ return;+ }+ const objectId = 'objectId' in point && typeof point.objectId === 'string' ? point.objectId : unitId;+ const binding = bindingMap.get(`${point.type}/${objectId}`);+ if (objectId === unitId) {+ include(unitId, point.type, unitId, [point.subType]);+ } else if (binding) {+ include(binding.permissionId, point.type, objectId, [point.subType]);+ } else if (this.supports({ unitId, objectId, objectType: point.type })) {+ // Unbound objects inherit. Business checks still enforce all containing-object restrictions.+ inheritedPoints.push(point.id);+ }+ });+ subscription.unsubscribe();+ });+ inheritedPoints.forEach((id) => this._permissions.updatePermissionPoint(id, true));+ const generation = ++this._nextGeneration;+ this._generations.set(unitId, generation);+ const values = [...requests.values()];+ if (values.length) {+ this._initialized.add(unitId);+ }+ const policies: IListPermPointResponse['objects'] = [];+ const results: IBatchAllowedResponse['objectActions'] = [];+ for (let offset = 0; offset < values.length; offset += 100) {+ const batch = values.slice(offset, offset + 100);+ const batchPolicies = await this._authz.list({ unitID: unitId, objectIDs: batch.map((item) => item.objectID), actions: [] });+ policies.push(...batchPolicies);+ batch.forEach((request) => {+ const policy = batchPolicies.find((item) => item.objectID === request.objectID && item.objectType === request.objectType);+ request.actions = [...new Set([...request.actions, ...(policy?.strategies.map((strategy) => strategy.action) ?? [])])];+ });+ results.push(...await this._authz.batchAllowed(batch.map(({ targetId, ...request }) => request)));+ }+ if (this._disposed || this._generations.get(unitId) !== generation) {+ return;+ }+ const resultMap = new Map(results.filter((item) => item.unitID === unitId).map((item) => [item.objectID, item]));+ const policyMap = new Map(policies.filter((item) => item.unitID === unitId).map((item) => [`${item.objectType}/${item.objectID}`, item]));+ values.forEach((request) => {+ const result = resultMap.get(request.objectID);+ const policy = policyMap.get(`${request.objectType}/${request.objectID}`);+ const actions = [...new Set([...request.actions, ...(policy?.strategies.map((strategy) => strategy.action) ?? [])])];+ actions.forEach((action) => {+ const id = `${request.objectType}.${action}_${unitId}${request.targetId === unitId ? '' : `_${request.targetId}`}`;+ if (!this._permissions.getPermissionPoint(id)) {+ this._permissions.addPermissionPoint({ id, type: request.objectType, subType: action, status: PermissionStatus.DONE, value: false, unitId, objectId: request.targetId } as IPermissionPoint);+ }+ this._permissions.updatePermissionPoint(id, result?.actions.some((item) => item.action === action && item.allowed === true) ?? false);+ });+ });+ this._policies.set(unitId, policies.filter((policy) => policy.unitID === unitId).map((policy) => ({+ ...policy,+ objectID: requests.get(`${policy.objectType}/${policy.objectID}`)?.targetId ?? policy.objectID,+ })));+ this._revision.next(this._revision.value + 1);+ this._unitChanges.next(unitId);+ }++ clearUnit(unitId: string): void {+ this._initialized.delete(unitId);+ this._generations.delete(unitId);+ this._policies.delete(unitId);+ this._revision.next(this._revision.value + 1);+ this._unitChanges.next(unitId);+ }++ private _assertSupported(target: IObjectPermissionTarget): void {+ if (!this.supports(target)) {+ throw new Error('Object permission management is not supported by this Authz provider.');+ }+ }+}diff --git a/packages/core/src/univer.ts b/packages/core/src/univer.tsindex 391aa997f0..f51d4df854 100644--- a/packages/core/src/univer.ts+++ b/packages/core/src/univer.ts@@ -38,6 +38,7 @@ import { LocaleService } from './services/locale/locale.service';import { DesktopLogService, ILogService } from './services/log/log.service';import { MentionIOLocalService } from './services/mention-io/mention-io-local.service';import { IMentionIOService } from './services/mention-io/type';+import { ObjectPermissionService } from './services/permission/object-permission.service';import { PermissionService } from './services/permission/permission.service';import { IPermissionService } from './services/permission/type';import { mergeOverrideWithDependencies } from './services/plugin/plugin-override';@@ -283,6 +284,7 @@ function createUniverInjector(parentInjector?: Injector, override?: DependencyOv// abstract services[IUniverInstanceService, { useClass: UniverInstanceService }],[IPermissionService, { useClass: PermissionService }],+ [ObjectPermissionService],[ILogService, { useClass: DesktopLogService, lazy: true }],[ICommandService, { useClass: CommandService }],[IUndoRedoService, { useClass: LocalUndoRedoService, lazy: true }],diff --git a/packages/design/src/components/button/StateIconButton.tsx b/packages/design/src/components/button/StateIconButton.tsxnew file mode 100644index 0000000000..bd19063594--- /dev/null+++ b/packages/design/src/components/button/StateIconButton.tsx@@ -0,0 +1,57 @@+/**+ * 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 { ComponentProps } from 'react';+import { clsx } from '../../helper/clsx';+import { Button } from './Button';++/** Active object states use the primary theme token in both light and dark themes. */+export function StateIconButton({ active, emphasizeActive = false, className, ...props }: ComponentProps<typeof Button> & { active: boolean; emphasizeActive?: boolean }) {+ return (+ <Button+ {...props}+ variant="ghost"+ size="icon"+ className={clsx(+ `+ univer-size-7 univer-shrink-0+ focus-visible:univer-outline focus-visible:univer-outline-2 focus-visible:univer-outline-offset-1+ focus-visible:univer-outline-primary-500+ `,+ active+ ? `+ !univer-text-primary-600+ dark:!univer-text-primary-400+ `+ : `+ !univer-text-gray-500+ hover:!univer-text-gray-900+ focus-visible:!univer-text-gray-900+ dark:!univer-text-gray-300+ dark:hover:!univer-text-gray-100+ dark:focus-visible:!univer-text-gray-100+ `,+ active && emphasizeActive && `+ !univer-border-primary-300 !univer-bg-primary-50+ hover:!univer-bg-primary-100+ dark:!univer-border-primary-700 dark:!univer-bg-primary-900 dark:!univer-text-primary-100+ dark:hover:!univer-bg-primary-800+ `,+ className+ )}+ />+ );+}diff --git a/packages/design/src/index.ts b/packages/design/src/index.tsindex 314b954f0e..b591272b05 100644--- a/packages/design/src/index.ts+++ b/packages/design/src/index.ts@@ -28,6 +28,7 @@ export { Button } from './components/button/Button';export type { IButtonProps } from './components/button/Button';export { ButtonGroup } from './components/button/ButtonGroup';export type { IButtonGroupProps } from './components/button/ButtonGroup';+export { StateIconButton } from './components/button/StateIconButton';export { Calendar } from './components/calendar/Calendar';export { CascaderList } from './components/cascader-list/CascaderList';export type { ICascaderListProps, ICascaderOption } from './components/cascader-list/CascaderList';@@ -138,4 +139,5 @@ export {export { clsx } from './helper/clsx';export { isBrowser } from './helper/is-browser';export { render, unmount } from './helper/react-dom';+export { cva } from 'class-variance-authority';diff --git a/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.tsindex ab845801b5..ba25226091 100644--- a/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts+++ b/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts@@ -40,6 +40,7 @@ import {PageOrientType,PaperType,PositionedObjectLayoutType,+ RANGE_DIRECTION,toDisposable,UniverInstanceType,} from '@univerjs/core';@@ -55,11 +56,13 @@ import {SetTextSelectionsOperation,UpdateTextCommand,} from '@univerjs/docs';-import { DocumentEditArea, GlyphType, IRenderManagerService } from '@univerjs/engine-render';+import { DocumentEditArea, DocumentSkeleton, GlyphType, IRenderManagerService } from '@univerjs/engine-render';import { ISidebarService } from '@univerjs/ui';import { Subject } from 'rxjs';import { afterEach, describe, expect, it, vi } from 'vitest';+import { DocMoveCursorController } from '../../../controllers/doc-move-cursor.controller';import { DocParagraphSettingController } from '../../../controllers/doc-paragraph-setting.controller';+import { DocBackScrollRenderController } from '../../../controllers/render-controllers/back-scroll.render-controller';import { DocAutoFormatService } from '../../../services/doc-auto-format.service';import { DocIMEInputManagerService } from '../../../services/doc-ime-input-manager.service';import { DocSelectionRenderService } from '../../../services/selection/doc-selection-render.service';@@ -84,7 +87,11 @@ import {MergeTwoParagraphCommand,RemoveHorizontalLineCommand,} from '../doc-delete.command';-import { CloseHeaderFooterCommand, CoreHeaderFooterCommand, OpenHeaderFooterPanelCommand } from '../doc-header-footer.command';+import {+ CloseHeaderFooterCommand,+ CoreHeaderFooterCommand,+ OpenHeaderFooterPanelCommand,+} from '../doc-header-footer.command';import { HorizontalLineCommand, InsertHorizontalLineBellowCommand } from '../doc-horizontal-line.command';import { DocPageSetupCommand } from '../doc-page-setup.command';import { DocParagraphSettingCommand } from '../doc-paragraph-setting.command';@@ -2195,6 +2202,52 @@ describe('misc document commands', () => {}));});+ it('extends and contracts a selection across a section break without selecting its invisible delimiter', async () => {+ const data = createBaseDoc('A\r\nBC\r\n');+ data.body!.paragraphs = [{ startIndex: 1, paragraphId: 'first' }, { startIndex: 5, paragraphId: 'second' }];+ data.body!.sectionBreaks = [{ startIndex: 2, sectionId: 'first' }, { startIndex: 6, sectionId: 'second' }];+ ({ univer, get } = createCommandTestBed(data, [+ [DocMoveCursorController],+ [DocBackScrollRenderController, { useValue: { scrollToRange: vi.fn() } }],+ ]));+ commandService = get(ICommandService);+ commandService.registerCommand(MoveSelectionOperation);+ commandService.registerCommand(SetTextSelectionsOperation);+ get(DocMoveCursorController);+ const skeletonManager = get(DocSkeletonManagerService);+ const skeleton = DocumentSkeleton.create(skeletonManager.getViewModel(), get(LocaleService));+ skeleton.calculate();+ vi.spyOn(skeletonManager, 'getSkeleton').mockReturnValue(skeleton);+ const selectionManager = get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: data.id, subUnitId: data.id });+ const refresh = vi.fn();+ const subscription = selectionManager.refreshSelection$.subscribe(refresh);+ selectionManager.__TEST_ONLY_add([{+ startOffset: 1,+ endOffset: 1,+ collapsed: true,+ isActive: true,+ }]);+ await commandService.executeCommand(MoveSelectionOperation.id, { direction: Direction.RIGHT });+ expect(refresh).toHaveBeenLastCalledWith(expect.objectContaining({+ docRanges: [expect.objectContaining({ startOffset: 1, endOffset: 3 })],+ }));+ selectionManager.__replaceTextRangesWithNoRefresh({+ ...selectionManager.getSelectionInfo()!,+ textRanges: [{ startOffset: 1, endOffset: 3, collapsed: false, isActive: true, direction: RANGE_DIRECTION.FORWARD }],+ rectRanges: [],+ segmentId: '',+ segmentPage: -1,+ isEditing: true,+ }, { unitId: data.id, subUnitId: data.id });+ await commandService.executeCommand(MoveSelectionOperation.id, { direction: Direction.LEFT });+ expect(refresh).toHaveBeenLastCalledWith(expect.objectContaining({+ docRanges: [expect.objectContaining({ startOffset: 1, endOffset: 1 })],+ }));+ subscription.unsubscribe();+ skeleton.dispose();+ });+it('reports cursor operations only when movement params are provided', async () => {({ univer, get } = createCommandTestBed(createBaseDoc()));commandService = get(ICommandService);diff --git a/packages/docs-ui/src/commands/operations/paragraph-permission.operation.ts b/packages/docs-ui/src/commands/operations/paragraph-permission.operation.tsnew file mode 100644index 0000000000..b82a54bae6--- /dev/null+++ b/packages/docs-ui/src/commands/operations/paragraph-permission.operation.ts@@ -0,0 +1,47 @@+/**+ * 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, ICommand } from '@univerjs/core';+import { CommandType, IUniverInstanceService, LocaleService, UniverInstanceType } from '@univerjs/core';+import { getDocumentParagraphPermissionObjectId, SetDocumentPermissionCommand } from '@univerjs/docs';+import { IRenderManagerService } from '@univerjs/engine-render';+import { UnitObject } from '@univerjs/protocol';++import { openObjectPermissionDialog } from '@univerjs/ui';+import { DocEventManagerService } from '../../services/doc-event-manager.service';++export const OpenDocParagraphPermissionOperation: ICommand = {+ id: 'doc.operation.open-paragraph-permission',+ type: CommandType.OPERATION,+ handler(accessor) {+ const model = accessor.get(IUniverInstanceService).getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);+ const target = model && accessor.get(IRenderManagerService).getRenderUnitById(model.getUnitId())?.with(DocEventManagerService).contextMenuParagraph;+ if (!target) {+ return false;+ }+ const { unitId, segmentId, paragraphId } = target;+ const exists = () => accessor.get(IUniverInstanceService).getUnit<DocumentDataModel>(unitId)?.getSelfOrHeaderFooterModel(segmentId)?.getBody()?.paragraphs?.some((item) => item.paragraphId === paragraphId) === true;+ if (!exists()) {+ return false;+ }+ return openObjectPermissionDialog(accessor, {+ target: { unitId, objectId: getDocumentParagraphPermissionObjectId(segmentId, paragraphId), objectType: UnitObject.DocumentParagraph },+ name: accessor.get(LocaleService).t('docs-ui.objectPermission.paragraph'),+ commandId: SetDocumentPermissionCommand.id,+ exists,+ });+ },+};diff --git a/packages/docs-ui/src/commands/operations/permission-panel.operation.ts b/packages/docs-ui/src/commands/operations/permission-panel.operation.tsnew file mode 100644index 0000000000..afb07e3b71--- /dev/null+++ b/packages/docs-ui/src/commands/operations/permission-panel.operation.ts@@ -0,0 +1,56 @@+/**+ * 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, ICommand } from '@univerjs/core';+import type { IObjectPermissionButtonProps } from '@univerjs/ui';+import { CommandType, isInternalEditorID, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';+import { getDocumentSectionPermissionObjectId, SetDocumentPermissionCommand } from '@univerjs/docs';+import { UnitObject } from '@univerjs/protocol';+import { openObjectPermissionPanel } from '@univerjs/ui';++export const OpenDocPermissionPanelOperation: ICommand = {+ id: 'doc.operation.open-permission-panel',+ type: CommandType.OPERATION,+ handler(accessor) {+ const currentModel = accessor.get(IUniverInstanceService).getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);+ if (!currentModel || isInternalEditorID(currentModel.getUnitId())) {+ return false;+ }+ const model = currentModel;+ const unitId = model.getUnitId();+ function* getTargets(): Iterable<IObjectPermissionButtonProps> {+ const snapshot = model.getSnapshot();+ const commandId = SetDocumentPermissionCommand.id;+ const segments = new Set(['', ...Object.keys(snapshot.headers ?? {}), ...Object.keys(snapshot.footers ?? {})]);+ for (const segmentId of segments) {+ const body = segmentId ? snapshot.headers?.[segmentId]?.body ?? snapshot.footers?.[segmentId]?.body : snapshot.body;+ for (const section of body?.sectionBreaks ?? []) {+ if (!section.sectionId) {+ continue;+ }+ const objectId = getDocumentSectionPermissionObjectId(segmentId, section.sectionId);+ yield {+ target: { unitId, objectId, objectType: UnitObject.DocumentSection },+ name: '',+ commandId,+ exists: () => model.getSelfOrHeaderFooterModel(segmentId)?.getBody()?.sectionBreaks?.some((item) => item.sectionId === section.sectionId) === true,+ };+ }+ }+ }+ return openObjectPermissionPanel(accessor, { unitId, target: { unitId, objectId: unitId, objectType: UnitObject.DocumentSection }, getTargets });+ },+};diff --git a/packages/docs-ui/src/controllers/__tests__/doc-render-controller.spec.ts b/packages/docs-ui/src/controllers/__tests__/doc-render-controller.spec.tsindex a8a49f7d0a..298be1154e 100644--- a/packages/docs-ui/src/controllers/__tests__/doc-render-controller.spec.ts+++ b/packages/docs-ui/src/controllers/__tests__/doc-render-controller.spec.ts@@ -18,7 +18,15 @@import type { ICommandInfo, IDocumentData, IExecutionOptions } from '@univerjs/core';import type { IDocLayoutMountIdentity } from '@univerjs/docs';-import { CustomDecorationType, CustomRangeType, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DocumentFlavor, JSONX, PositionedObjectLayoutType, TextXActionType } from '@univerjs/core';+import {+ CustomDecorationType,+ CustomRangeType,+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,+ DocumentFlavor,+ JSONX,+ PositionedObjectLayoutType,+ TextXActionType,+} from '@univerjs/core';import { DocLayoutSessionStatus, RichTextEditingMutation } from '@univerjs/docs';import { BehaviorSubject, Subject } from 'rxjs';import { describe, expect, it, vi } from 'vitest';@@ -927,7 +935,7 @@ describe('doc render controller', () => {controller.dispose();});- it('protects retained interaction pages when Main publishes only the edited page', async () => {+ it('allows Worker pages beyond the published Main window to refresh progressively', async () => {const { commandCallbacks, controller, skeletonManager } = createControllerFixture({useWorker: true,pages: Array.from({ length: 8 }, () => ({@@ -963,7 +971,7 @@ describe('doc render controller', () => {protectedRange: {mode: 'paginated',startPageIndex: 0,- endPageIndex: 4,+ endPageIndex: 0,},});});diff --git a/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts b/packages/docs-ui/src/controllers/doc-move-cursor.controller.tsindex 0f634137c0..a1b7d74da6 100644--- a/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts+++ b/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts@@ -230,11 +230,14 @@ export class DocMoveCursorController extends Disposable {if (direction === Direction.LEFT || direction === Direction.RIGHT) {const preGlyph = skeleton.findNodeByCharIndex(focusOffset - 1, segmentId, segmentPage);- const curGlyph = skeleton.findNodeByCharIndex(focusOffset, segmentId, segmentPage)!;+ const curGlyph = skeleton.findNodeByCharIndex(focusOffset, segmentId, segmentPage);focusOffset =- direction === Direction.RIGHT ? focusOffset + curGlyph.count : focusOffset - (preGlyph?.count ?? 0);+ direction === Direction.RIGHT ? focusOffset + (curGlyph?.count ?? 1) : focusOffset - (preGlyph?.count ?? 1);+ // Section and table delimiters have no caret geometry. Shift+Arrow+ // must skip them in both directions, as ordinary cursor movement does.+ focusOffset = this._normalizeCursorOffset(body.dataStream, customRanges, focusOffset, direction);focusOffset = Math.min(dataStreamLength - 2, Math.max(0, focusOffset));this._textSelectionManagerService.replaceDocRanges([diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-contextmenu.render-controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-contextmenu.render-controller.spec.tsindex 6a95201c71..43aeb6d54e 100644--- a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-contextmenu.render-controller.spec.ts+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-contextmenu.render-controller.spec.ts@@ -59,12 +59,13 @@ function createController(options?: {return { dispose: vi.fn() };}),} as never,- { isPointerOnNonChecklistBullet: vi.fn(() => options?.pointerOnBullet ?? false) } as never,+ { getParagraphByOffset: () => null, isPointerOnNonChecklistBullet: vi.fn(() => options?.pointerOnBullet ?? false) } as never,{ getTextRanges: vi.fn(() => options?.textRanges ?? []) } as never,{getContextValue: vi.fn((key) => key === FOCUSING_COMMON_DRAWINGS && (options?.focusingDrawing ?? false)),} as never,{+ getUnit: () => null,getCurrentUnitOfType: vi.fn((type) => type === UniverInstanceType.UNIVER_DOC? { getBody: () => ({ blockRanges: options?.blockRanges ?? [] }) }: null),diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-layout-progress.render-controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-layout-progress.render-controller.spec.tsindex d7d14c146e..beb3bba1d0 100644--- a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-layout-progress.render-controller.spec.ts+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-layout-progress.render-controller.spec.ts@@ -94,7 +94,7 @@ describe('document layout progress', () => {controller.dispose();});- it('does not flash for fast initial layout or later edits', () => {+ it('does not flash for fast initial layout or fast edits', () => {vi.useFakeTimers();const { controller, layoutProgress$, setProgress } = createController();@@ -103,12 +103,31 @@ describe('document layout progress', () => {layoutProgress$.next(createProgress({ complete: true, processedBlockCount: 100 }));vi.advanceTimersByTime(DOC_LAYOUT_PROGRESS_DELAY_MS);layoutProgress$.next(createProgress({ reason: 'edit' }));+ vi.advanceTimersByTime(500);+ layoutProgress$.next(createProgress({ reason: 'edit', complete: true }));vi.advanceTimersByTime(DOC_LAYOUT_PROGRESS_DELAY_MS);expect(setProgress).not.toHaveBeenCalled();controller.dispose();});+ it('shows progress for a slow edit after the initial layout has completed', () => {+ vi.useFakeTimers();+ const { controller, layoutProgress$, setProgress, clearProgress } = createController(true);++ layoutProgress$.next(createProgress({ reason: 'edit', processedBlockCount: 10, publishedPageCount: 1 }));+ vi.advanceTimersByTime(DOC_LAYOUT_PROGRESS_DELAY_MS - 1);+ expect(setProgress).not.toHaveBeenCalled();+ vi.advanceTimersByTime(1);+ expect(setProgress).toHaveBeenLastCalledWith('doc-1', 10);++ layoutProgress$.next(createProgress({ reason: 'edit', processedBlockCount: 60 }));+ expect(setProgress).toHaveBeenLastCalledWith('doc-1', 60);+ layoutProgress$.next(createProgress({ reason: 'edit', complete: true }));+ expect(clearProgress).toHaveBeenCalledOnce();+ controller.dispose();+ });+it('keeps the original delay across a cancelled Main to Worker handoff', () => {vi.useFakeTimers();const { controller, layoutProgress$, setProgress } = createController();@@ -141,6 +160,37 @@ describe('document layout progress', () => {controller.dispose();});+ it('starts a fresh delay after an abandoned edit without a successor', () => {+ vi.useFakeTimers();+ const { controller, layoutProgress$, setProgress } = createController(true);+ layoutProgress$.next(createProgress({ reason: 'edit' }));+ vi.advanceTimersByTime(500);+ layoutProgress$.next(createProgress({ reason: 'edit', cancelled: true }));+ vi.advanceTimersByTime(DOC_LAYOUT_PROGRESS_CANCEL_GRACE_MS + DOC_LAYOUT_PROGRESS_DELAY_MS);++ layoutProgress$.next(createProgress({ reason: 'edit', generation: 2 }));+ vi.advanceTimersByTime(DOC_LAYOUT_PROGRESS_DELAY_MS - 1);+ expect(setProgress).not.toHaveBeenCalled();+ vi.advanceTimersByTime(1);+ expect(setProgress).toHaveBeenCalledOnce();+ controller.dispose();+ });++ it('advances with reused page publications without treating a continuous page as completed work', () => {+ expect(resolveDocLayoutProgressPercent(createProgress({+ reason: 'edit',+ processedBlockCount: 1,+ publishedPageCount: 8,+ }))).toBe(80);+ expect(resolveDocLayoutProgressPercent(createProgress({+ mode: 'continuous',+ processedBlockCount: 1,+ publishedPageCount: 1,+ pageCount: 1,+ estimatedPageCount: 1,+ }))).toBe(1);+ });+it('calculates bounded progress from blocks and falls back to pages', () => {expect(resolveDocLayoutProgressPercent(createProgress({ processedBlockCount: 25 }))).toBe(25);expect(resolveDocLayoutProgressPercent(createProgress({ processedBlockCount: 200 }))).toBe(99);diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-selection-render.controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-selection-render.controller.spec.tsindex c5f6ae42e5..cd587b7f61 100644--- a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-selection-render.controller.spec.ts+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-selection-render.controller.spec.ts@@ -16,21 +16,49 @@// @vitest-environment jsdom+import type { IDocumentData } from '@univerjs/core';+import type { RenderUnit } from '@univerjs/engine-render';import type { EmbedInteractionBoundaryService } from '../../../services/doc-embed-integration.service';-import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY } from '@univerjs/core';import {+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,+ DocumentFlavor,+ ICommandService,+ IUniverInstanceService,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import {+ DocLayoutExecutorService,+ DocSelectionManagerService,+ DocSkeletonManagerService,+ SetTextSelectionsOperation,+} from '@univerjs/docs';+import {+ CanvasColorService,CURSOR_TYPE,DocumentEditArea,+ Documents,+ ICanvasColorService,+ IRenderManagerService,NORMAL_TEXT_SELECTION_PLUGIN_STYLE,+ RenderManagerService,+ Viewport,} from '@univerjs/engine-render';+import { DesktopLayoutService, ILayoutService } from '@univerjs/ui';import { Subject } from 'rxjs';import { afterEach, describe, expect, it, vi } from 'vitest';+import { VIEWPORT_KEY } from '../../../basics/docs-view-key';import { SetDocZoomRatioOperation } from '../../../commands/operations/set-doc-zoom-ratio.operation';-import { EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE, EmbedRuntimeFocusCoordinator } from '../../../services/doc-embed-integration.service';+import {+ EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE,+ EmbedRuntimeFocusCoordinator,+} from '../../../services/doc-embed-integration.service';+import { EditorService, IEditorService } from '../../../services/editor/editor-manager.service';+import { DocSelectionRenderService } from '../../../services/selection/doc-selection-render.service';import { DocSelectionRenderController } from '../doc-selection-render.controller';const neoGetDocObjectMock = vi.hoisted(() => vi.fn());-const findFirstCursorOffsetMock = vi.hoisted(() => vi.fn(() => 3));+const findFirstCursorOffsetMock = vi.hoisted(() => vi.fn<(snapshot: IDocumentData) => number>(() => 3));vi.mock('../../../basics/component-tools', async (importOriginal) => {const actual = await importOriginal<typeof import('../../../basics/component-tools')>();@@ -192,6 +220,81 @@ describe('DocSelectionRenderController', () => {findFirstCursorOffsetMock.mockClear();});+ it.each([DocumentFlavor.MODERN, DocumentFlavor.TRADITIONAL])('preserves the editing selection across synchronous layout publications (flavor %s)', async (documentFlavor) => {+ const componentTools = await vi.importActual<typeof import('../../../basics/component-tools')>('../../../basics/component-tools');+ const selectionTools = await vi.importActual<typeof import('../../../basics/selection')>('../../../basics/selection');+ neoGetDocObjectMock.mockImplementation(componentTools.neoGetDocObject);+ findFirstCursorOffsetMock.mockImplementation(selectionTools.findFirstCursorOffset);+ vi.useFakeTimers();+ const univer = new Univer();+ const root = document.createElement('div');+ document.body.appendChild(root);+ try {+ const injector = univer.__getInjector();+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);+ injector.add([ICanvasColorService, { useClass: CanvasColorService }]);+ injector.add([DocLayoutExecutorService]);+ injector.add([DocSelectionManagerService]);+ injector.add([IEditorService, { useClass: EditorService }]);+ injector.add([ILayoutService, { useClass: DesktopLayoutService }]);+ injector.get(ILayoutService).registerRootContainerElement(root);+ injector.get(ICommandService).registerCommand(SetTextSelectionsOperation);+ const dataStream = 'First paragraph\r\r\rLast paragraph\r\n';+ const unit = univer.createUnit(UniverInstanceType.UNIVER_DOC, {+ id: 'selection-layout-test',+ body: {+ dataStream,+ paragraphs: [...dataStream.matchAll(/\r/g)].map((match, index) => ({+ startIndex: match.index!,+ paragraphId: `paragraph-${index}`,+ })),+ sectionBreaks: [{ startIndex: dataStream.length - 1, sectionId: 'body' }],+ },+ documentStyle: {+ documentFlavor,+ pageSize: { width: 400, height: 600 },+ marginLeft: 20,+ marginRight: 20,+ marginTop: 20,+ marginBottom: 20,+ },+ });+ const unitId = unit.getUnitId();+ injector.get(IUniverInstanceService).setCurrentUnitForType(unitId);+ const render = injector.get(IRenderManagerService).createRender(unitId) as RenderUnit;+ render.deactivate();+ render.engine.resizeBySize(400, 600);+ render.addRenderDependencies([[DocSkeletonManagerService]]);+ const skeletonManager = render.with(DocSkeletonManagerService);+ expect(skeletonManager.supportsIncrementalLayout()).toBe(false);+ const documents = new Documents('doc-main', skeletonManager.getSkeleton(), { pageMarginTop: 20, pageMarginLeft: 0 });+ documents.resize(400, 600);+ render.mainComponent = documents;+ render.scene.addObject(documents);+ const viewport = new Viewport(VIEWPORT_KEY.VIEW_MAIN, render.scene, { left: 0, top: 0, width: 400, height: 600, active: true });+ viewport.resetCanvasSizeAndUpdateScroll();+ render.addRenderDependencies([[DocSelectionRenderService], [DocSelectionRenderController]]);+ render.with(DocSelectionRenderController);+ const selections = injector.get(DocSelectionManagerService);+ expect(selections.getActiveTextRange()?.startOffset).toBe(0);++ for (const [startOffset, endOffset] of [[1, 1], [2, 2], [3, 3], [5, 9]]) {+ selections.replaceSelectionInfoWithoutRefresh({+ ...selections.getSelectionInfo()!,+ textRanges: [{ startOffset, endOffset, collapsed: startOffset === endOffset, isActive: true }],+ isEditing: true,+ }, { unitId, subUnitId: unitId });+ skeletonManager.recalculate();+ expect(selections.getActiveTextRange()).toMatchObject({ startOffset, endOffset });+ expect(selections.getSelectionInfo()?.isEditing).toBe(true);+ }+ } finally {+ univer.dispose();+ root.remove();+ findFirstCursorOffsetMock.mockImplementation(() => 3);+ }+ });+it('syncs selection manager refreshes and inner render selections', () => {const { controller, refreshSelection$, textSelectionInner$, docSelectionRenderService, docSelectionManagerService } = createController();const docRanges = [{ startOffset: 1, endOffset: 2 }];diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc.render-controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc.render-controller.spec.tsindex a0a0ff4ea5..71cad07653 100644--- a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc.render-controller.spec.ts+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc.render-controller.spec.ts@@ -51,7 +51,10 @@ import {import { ILayoutService } from '@univerjs/ui';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { VIEWPORT_KEY } from '../../../basics/docs-view-key';+import { AfterSpaceCommand } from '../../../commands/commands/auto-format.command';+import { BreakLineCommand } from '../../../commands/commands/break-line.command';import { IMEInputCommand } from '../../../commands/commands/ime-input.command';+import { DocAutoFormatService } from '../../../services/doc-auto-format.service';import { DocIMEInputManagerService } from '../../../services/doc-ime-input-manager.service';import { DocLayoutInteractionService } from '../../../services/doc-layout-interaction.service';import { DocMenuStyleService } from '../../../services/doc-menu-style.service';@@ -66,7 +69,7 @@ import { DocInputController } from '../doc-input.controller';import { DocSelectionRenderController } from '../doc-selection-render.controller';import { DocRenderController } from '../doc.render-controller';-function createEditor(paragraphCount = 8, withDrawing = true, workerBeforeLayout = false) {+function createEditor(paragraphCount = 8, withDrawing = true, workerBeforeLayout = false, documentFlavor = DocumentFlavor.TRADITIONAL) {const univer = new Univer();const injector = univer.__getInjector();const root = document.createElement('div');@@ -88,15 +91,17 @@ function createEditor(paragraphCount = 8, withDrawing = true, workerBeforeLayoutlet registration = workerBeforeLayout ? registerWorker() : undefined;const startWorkerLayout = vi.spyOn(injector.get(DocLayoutExecutorService), 'startLayout');injector.add([DocSelectionManagerService]);+ injector.add([DocAutoFormatService]);injector.add([DocStateEmitService]);injector.add([DocMenuStyleService]);injector.add([IEditorService, { useClass: EditorService }]);const commands = injector.get(ICommandService);- [InsertTextCommand, IMEInputCommand, RichTextEditingMutation, SetTextSelectionsOperation]+ [InsertTextCommand, AfterSpaceCommand, BreakLineCommand, IMEInputCommand, RichTextEditingMutation, SetTextSelectionsOperation].forEach((command) => commands.registerCommand(command));const firstParagraph = 'Hello world';const drawingToken = withDrawing ? DataStreamTreeTokenType.CUSTOM_BLOCK : '';- const dataStream = `${firstParagraph}\r${drawingToken}${Array.from({ length: paragraphCount }, (_, i) => `Paragraph ${i} has enough words to wrap across several lines.\r`).join('')}\n`;+ const separator = documentFlavor === DocumentFlavor.MODERN ? '\r\r' : '\r';+ const dataStream = `${firstParagraph}\r${drawingToken}${Array.from({ length: paragraphCount }, (_, i) => `Paragraph ${i} has enough words to wrap across several lines.${separator}`).join('')}\n`;const model = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, {id: 'bounded-caret-test',// A drawing on the edited page deliberately keeps the conservative@@ -130,7 +135,7 @@ function createEditor(paragraphCount = 8, withDrawing = true, workerBeforeLayout},documentStyle: {...(workerBeforeLayout ? { autoHyphenation: BooleanNumber.FALSE } : {}),- documentFlavor: DocumentFlavor.TRADITIONAL,+ documentFlavor,pageSize: { width: 300, height: 700 },textStyle: { ff: 'Arial', fs: 14 },marginLeft: 20,@@ -215,6 +220,41 @@ describe('DocRenderController bounded input publication', () => {vi.useRealTimers();});+ it('keeps short Modern edits and spaces complete while Worker initialization is pending', async () => {+ const editor = createEditor(3, false, false, DocumentFlavor.MODERN);+ try {+ await vi.dynamicImportSettled();+ const beginExternalLayout = vi.spyOn(editor.skeleton, 'beginExternalLayout');+ const applyLayoutPublication = vi.spyOn(editor.skeleton, 'applyLayoutPublication');+ for (const [index, text] of ['A', ' ', '中', 'B'].entries()) {+ editor.input.textContent = text;+ editor.input.dispatchEvent(new InputEvent('input', { data: text, inputType: 'insertText' }));+ await Promise.resolve();+ await Promise.resolve();+ expect(editor.selectionManager.getActiveTextRange()?.endOffset).toBe(6 + index);+ expect(editor.selection.getActiveTextRange()?.endOffset).toBe(6 + index);+ expect(editor.skeleton.getLayoutProgress()?.complete ?? true).toBe(true);+ expect(editor.skeleton.findNodeByCharIndex(editor.model.getBody()!.dataStream.length - 3)).toBeDefined();+ }+ expect(editor.model.getBody()?.dataStream.startsWith('HelloA 中B world')).toBe(true);+ expect(await editor.commands.executeCommand(BreakLineCommand.id)).toBe(true);+ expect(editor.selection.getActiveTextRange()?.endOffset).toBe(10);+ editor.input.textContent = 'C';+ editor.input.dispatchEvent(new InputEvent('input', { data: 'C', inputType: 'insertText' }));+ await Promise.resolve();+ await Promise.resolve();+ expect(editor.model.getBody()?.dataStream.startsWith('HelloA 中B\rC world')).toBe(true);+ expect(editor.skeleton.getLayoutProgress()?.complete ?? true).toBe(true);+ await vi.advanceTimersByTimeAsync(1_000);+ expect(editor.startWorkerLayout).toHaveBeenCalledTimes(1);+ expect(beginExternalLayout).not.toHaveBeenCalled();+ expect(applyLayoutPublication).not.toHaveBeenCalled();+ expect(editor.selection.getActiveTextRange()?.endOffset).toBe(11);+ } finally {+ editor.dispose();+ }+ });+it.each([1, 500])('opens %i paragraphs without waiting for full Main pagination', async (paragraphCount) => {vi.stubGlobal('requestIdleCallback', (callback: IdleRequestCallback) =>window.setTimeout(() => callback({ didTimeout: false, timeRemaining: () => 10 }), 0));diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-contextmenu.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc-contextmenu.render-controller.tsindex 1948ef3997..421f75ead9 100644--- a/packages/docs-ui/src/controllers/render-controllers/doc-contextmenu.render-controller.ts+++ b/packages/docs-ui/src/controllers/render-controllers/doc-contextmenu.render-controller.ts@@ -73,6 +73,13 @@ export class DocContextMenuRenderController extends Disposable implements IRendereturn;}+ const bound = this._docEventManagerService.getParagraphByOffset(event.offsetX, event.offsetY);+ const model = this._univerInstanceService.getUnit<DocumentDataModel>(this._context.unitId);+ const segmentId = bound?.segmentId ?? '';+ const paragraph = bound && model?.getSelfOrHeaderFooterModel(segmentId)?.getBody()?.paragraphs?.find((item) => item.startIndex === bound.startIndex);+ this._docEventManagerService.contextMenuParagraph = paragraph?.paragraphId+ ? { unitId: this._context.unitId, segmentId, paragraphId: paragraph.paragraphId }+ : null;const position = this._contextService.getContextValue(FOCUSING_COMMON_DRAWINGS)? ContextMenuPosition.DRAWING: ContextMenuPosition.MAIN_AREA;diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-layout-progress.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc-layout-progress.render-controller.tsindex 9cd3ae0291..e1fb613a55 100644--- a/packages/docs-ui/src/controllers/render-controllers/doc-layout-progress.render-controller.ts+++ b/packages/docs-ui/src/controllers/render-controllers/doc-layout-progress.render-controller.ts@@ -29,16 +29,17 @@ export function resolveDocLayoutProgressPercent(progress: IDocumentLayoutProgresreturn 100;}- if (progress.totalBlockCount > 0) {- return Math.min(99, Math.max(0, Math.floor(progress.processedBlockCount / progress.totalBlockCount * 100)));- }-+ const blockProgress = progress.totalBlockCount > 0+ ? progress.processedBlockCount / progress.totalBlockCount+ : 0;const estimatedPageCount = Math.max(progress.estimatedPageCount, progress.pageCount);- if (estimatedPageCount > 0) {- return Math.min(99, Math.max(0, Math.floor(progress.publishedPageCount / estimatedPageCount * 100)));- }-- return 0;+ // A reused paginated tail still publishes page by page after block layout+ // stops advancing. Continuous mode has one physical page, so only its block+ // progress represents remaining work.+ const pageProgress = progress.mode === 'paginated' && estimatedPageCount > 0+ ? progress.publishedPageCount / estimatedPageCount+ : 0;+ return Math.min(99, Math.max(0, Math.floor(Math.max(blockProgress, pageProgress) * 100)));}export class DocLayoutProgressRenderController extends RxDisposable implements IRenderModule {@@ -48,7 +49,6 @@ export class DocLayoutProgressRenderController extends RxDisposable implements Iprivate _latestProgress: Nullable<IDocumentLayoutProgress> = null;private _layoutStartedAt: Nullable<number> = null;private _maxProgress = 0;- private _hasCompletedInitialLayout = false;constructor(private readonly _context: IRenderContext<DocumentDataModel>,@@ -59,7 +59,7 @@ export class DocLayoutProgressRenderController extends RxDisposable implements Ithis._docSkeletonManagerService.currentSkeleton$.pipe(switchMap((skeleton) => {- this._reset(skeleton?.hasCompleteLayout() ?? false);+ this._reset();return skeleton?.layoutProgress$ ?? EMPTY;}),takeUntil(this.dispose$)@@ -67,7 +67,7 @@ export class DocLayoutProgressRenderController extends RxDisposable implements I}override dispose(): void {- this._reset(true);+ this._reset();super.dispose();}@@ -81,11 +81,7 @@ export class DocLayoutProgressRenderController extends RxDisposable implements Ithis._clearCancelTimer();if (progress.complete) {- this._reset(true);- return;- }-- if (this._hasCompletedInitialLayout) {+ this._reset();return;}@@ -119,8 +115,7 @@ export class DocLayoutProgressRenderController extends RxDisposable implements Iif (this._visible ||this._latestProgress == null ||- this._latestProgress.complete ||- this._hasCompletedInitialLayout+ this._latestProgress.complete) {return;}@@ -130,7 +125,7 @@ export class DocLayoutProgressRenderController extends RxDisposable implements I}private _scheduleCancelledClear(): void {- if (!this._visible || this._cancelTimer != null) {+ if (this._cancelTimer != null) {return;}@@ -139,8 +134,7 @@ export class DocLayoutProgressRenderController extends RxDisposable implements Iif (this._latestProgress != null) {return;}- this._visible = false;- this._docLayoutProgressService.clearProgress(this._context.unitId);+ this._reset();}, DOC_LAYOUT_PROGRESS_CANCEL_GRACE_MS);}@@ -151,7 +145,7 @@ export class DocLayoutProgressRenderController extends RxDisposable implements I}}- private _reset(hasCompletedInitialLayout: boolean): void {+ private _reset(): void {if (this._delayTimer != null) {clearTimeout(this._delayTimer);this._delayTimer = null;@@ -162,6 +156,5 @@ export class DocLayoutProgressRenderController extends RxDisposable implements Ithis._latestProgress = null;this._layoutStartedAt = null;this._maxProgress = 0;- this._hasCompletedInitialLayout = hasCompletedInitialLayout;}}diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-selection-render.controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc-selection-render.controller.tsindex a566062bc0..ce9d7d159e 100644--- a/packages/docs-ui/src/controllers/render-controllers/doc-selection-render.controller.ts+++ b/packages/docs-ui/src/controllers/render-controllers/doc-selection-render.controller.ts@@ -44,7 +44,11 @@ import { filter, take } from 'rxjs';import { neoGetDocObject } from '../../basics/component-tools';import { findFirstCursorOffset } from '../../basics/selection';import { SetDocZoomRatioOperation } from '../../commands/operations/set-doc-zoom-ratio.operation';-import { DOC_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE, IDocEmbedInteractionBoundaryService, IDocEmbedRuntimeFocusCoordinator } from '../../services/doc-embed-integration.service';+import {+ DOC_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE,+ IDocEmbedInteractionBoundaryService,+ IDocEmbedRuntimeFocusCoordinator,+} from '../../services/doc-embed-integration.service';import { IEditorService } from '../../services/editor/editor-manager.service';import { DocSelectionRenderService } from '../../services/selection/doc-selection-render.service';@@ -326,6 +330,7 @@ export class DocSelectionRenderController extends Disposable implements IRenderM}private _skeletonListener() {+ let selectionInitialized = false;// Change text selection runtime(skeleton, scene) and update text selection manager current selection.this.disposeWithMe(this._docSkeletonManagerService.currentSkeleton$.subscribe((skeleton) => {if (!skeleton) return;@@ -341,6 +346,12 @@ export class DocSelectionRenderController extends Disposable implements IRenderMreturn;}+ // Synchronous layout publishes after every edit. Preserve the post-edit selection.+ if (selectionInitialized) {+ return;+ }+ selectionInitialized = true;+//TODO: @JOCS Only for docs. move to docs in the future.this._docSelectionRenderService.focus();const docDataModel = this._context.unit;diff --git a/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.tsindex f8fe34cc07..49637af7b0 100644--- a/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts+++ b/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts@@ -85,7 +85,12 @@ import { IEditorService } from '../../services/editor/editor-manager.service';import { NodePositionConvertToCursor } from '../../services/selection/convert-text-range';import { DocSelectionRenderService } from '../../services/selection/doc-selection-render.service';import { getAnchorBounding } from '../../services/selection/text-range';-import { getBodyTextXActions, getDocumentMutationLayoutImpact, getSingleBodyTextXActions, resolveMutationLayoutRequest } from './doc-mutation-layout';+import {+ getBodyTextXActions,+ getDocumentMutationLayoutImpact,+ getSingleBodyTextXActions,+ resolveMutationLayoutRequest,+} from './doc-mutation-layout';function getTextXActionLength(action: unknown): number | undefined {if (typeof action !== 'object' || action == null || !('t' in action) || !('len' in action)) {@@ -845,7 +850,9 @@ export class DocRenderController extends RxDisposable implements IRenderModule {workerOptions,protectedRange,mainThreadCallbacks,- preserveInactiveViewportAnchor+ preserveInactiveViewportAnchor,+ true,+ progress.mode === 'continuous' && progress.complete);});},@@ -1059,7 +1066,8 @@ export class DocRenderController extends RxDisposable implements IRenderModule {protectedRange: IDocumentLayoutProtectedRange | undefined,mainThreadCallbacks: DocLayoutCoordinatorCallbacks,preserveInactiveViewportAnchor: boolean,- allowRecovery = true+ allowRecovery = true,+ preserveCompletedLayout = false): void {if (layoutRequestId !== this._layoutRequestId) {return;@@ -1098,8 +1106,10 @@ export class DocRenderController extends RxDisposable implements IRenderModule {mainThreadCallbacks,preserveInactiveViewportAnchor,allowRecovery,- error- )+ error,+ preserveCompletedLayout+ ),+ preserveCompletedLayout);}@@ -1113,7 +1123,8 @@ export class DocRenderController extends RxDisposable implements IRenderModule {mainThreadCallbacks: DocLayoutCoordinatorCallbacks,preserveInactiveViewportAnchor: boolean,allowRecovery: boolean,- error: unknown+ error: unknown,+ preserveCompletedLayout: boolean): void {if (!allowRecovery) {this._logService.error('[DocRenderController]: Worker layout failed; using main-thread layout.', error);@@ -1138,7 +1149,8 @@ export class DocRenderController extends RxDisposable implements IRenderModule {protectedRange,mainThreadCallbacks,preserveInactiveViewportAnchor,- false+ false,+ preserveCompletedLayout);}).catch((recoveryError: unknown) => {this._logService.error('[DocRenderController]: document layout Worker recovery failed; using main-thread layout.', recoveryError);@@ -1343,23 +1355,13 @@ export class DocRenderController extends RxDisposable implements IRenderModule {return undefined;}- let endPageIndex = publishedEndPageIndex;- const maximumProtectedEndPageIndex = Math.min(- pages.length - 1,- startPageIndex + MATERIALIZED_PAGE_WINDOW_SIZE - 1- );- while (endPageIndex < maximumProtectedEndPageIndex) {- const nextPage = pages[endPageIndex + 1];- if (nextPage == null || nextPage.isLayoutPlaceholder || nextPage.isMaterializationPlaceholder) {- break;- }- endPageIndex++;- }-+ // Pages beyond Main's published boundary are retained previews. Keeping+ // them in the protected range would reject fresh Worker geometry until+ // the entire document completes, leaving the next page visibly stale.return {mode: 'paginated',startPageIndex,- endPageIndex,+ endPageIndex: publishedEndPageIndex,};}diff --git a/packages/docs-ui/src/controllers/ui.controller.ts b/packages/docs-ui/src/controllers/ui.controller.tsindex 3a651917c3..11e547f910 100644--- a/packages/docs-ui/src/controllers/ui.controller.ts+++ b/packages/docs-ui/src/controllers/ui.controller.ts@@ -35,8 +35,13 @@ import {} from '@univerjs/ui';import { CoreHeaderFooterCommand, OpenHeaderFooterPanelCommand } from '../commands/commands/doc-header-footer.command';import { SidebarDocHeaderFooterPanelOperation } from '../commands/operations/doc-header-footer-panel.operation';+import { OpenDocParagraphPermissionOperation } from '../commands/operations/paragraph-permission.operation';+import { OpenDocPermissionPanelOperation } from '../commands/operations/permission-panel.operation';import { floatToolbarMenuSchema, menuSchema } from '../menu/schema';-import { IDocEmbedInteractionBoundaryService, IDocEmbedRuntimeFocusCoordinator } from '../services/doc-embed-integration.service';+import {+ IDocEmbedInteractionBoundaryService,+ IDocEmbedRuntimeFocusCoordinator,+} from '../services/doc-embed-integration.service';import { DocSelectionRenderService } from '../services/selection/doc-selection-render.service';import { TabShortCut } from '../shortcuts/format.shortcut';import {@@ -114,6 +119,8 @@ export class DocUIController extends Disposable {private _initCommands(): void {[+ OpenDocPermissionPanelOperation,+ OpenDocParagraphPermissionOperation,CoreHeaderFooterCommand,OpenHeaderFooterPanelCommand,SidebarDocHeaderFooterPanelOperation,diff --git a/packages/docs-ui/src/locale/ar-SA.ts b/packages/docs-ui/src/locale/ar-SA.tsindex b193c9282f..a54c7c3573 100644--- a/packages/docs-ui/src/locale/ar-SA.ts+++ b/packages/docs-ui/src/locale/ar-SA.ts@@ -18,6 +18,12 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ objectPermission: {+ paragraphPermission: 'الأذونات',+ title: 'الأذونات',+ paragraph: 'الفقرة',+ section: 'القسم',+ },layout: {progress: 'جارٍ تنسيق المستند…',recovering: 'جارٍ استعادة تخطيط المستند…',diff --git a/packages/docs-ui/src/locale/ca-ES.ts b/packages/docs-ui/src/locale/ca-ES.tsindex baff950ba9..0fc26ee8df 100644--- a/packages/docs-ui/src/locale/ca-ES.ts+++ b/packages/docs-ui/src/locale/ca-ES.ts@@ -18,6 +18,12 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ objectPermission: {+ paragraphPermission: 'Permisos',+ title: 'Permisos',+ paragraph: 'Paràgraf',+ section: 'Secció',+ },layout: {progress: 'S’està maquetant el document…',recovering: 'S’està restaurant el disseny del document…',diff --git a/packages/docs-ui/src/locale/de-DE.ts b/packages/docs-ui/src/locale/de-DE.tsindex b62963df4b..a1192e7166 100644--- a/packages/docs-ui/src/locale/de-DE.ts+++ b/packages/docs-ui/src/locale/de-DE.ts@@ -18,6 +18,12 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ objectPermission: {+ paragraphPermission: 'Berechtigungen',+ title: 'Berechtigungen',+ paragraph: 'Absatz',+ section: 'Abschnitt',+ },layout: {progress: 'Dokument wird formatiert…',recovering: 'Dokumentlayout wird wiederhergestellt…',diff --git a/packages/docs-ui/src/locale/en-US.ts b/packages/docs-ui/src/locale/en-US.tsindex bd5eec7bb2..36e0711c4e 100644--- a/packages/docs-ui/src/locale/en-US.ts+++ b/packages/docs-ui/src/locale/en-US.ts@@ -16,6 +16,12 @@const locale = {'docs-ui': {+ objectPermission: {+ paragraphPermission: 'Permissions',+ title: 'Permissions',+ paragraph: 'Paragraph',+ section: 'Section',+ },layout: {progress: 'Laying out document…',recovering: 'Restoring document layout…',diff --git a/packages/docs-ui/src/locale/es-ES.ts b/packages/docs-ui/src/locale/es-ES.tsindex 7d2e12d0dd..8905e5d3b3 100644--- a/packages/docs-ui/src/locale/es-ES.ts+++ b/packages/docs-ui/src/locale/es-ES.ts@@ -18,6 +18,12 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ objectPermission: {+ paragraphPermission: 'Permisos',+ title: 'Permisos',+ paragraph: 'Párrafo',+ section: 'Sección',+ },layout: {progress: 'Maquetando el documento…',recovering: 'Restaurando el diseño del documento…',diff --git a/packages/docs-ui/src/locale/fa-IR.ts b/packages/docs-ui/src/locale/fa-IR.tsindex 6cbafc736f..1871b450e1 100644--- a/packages/docs-ui/src/locale/fa-IR.ts+++ b/packages/docs-ui/src/locale/fa-IR.ts@@ -18,6 +18,12 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ objectPermission: {+ paragraphPermission: 'مجوزها',+ title: 'مجوزها',+ paragraph: 'بند',+ section: 'بخش',+ },layout: {progress: 'در حال صفحهآرایی سند…',recovering: 'در حال بازیابی صفحهآرایی سند…',diff --git a/packages/docs-ui/src/locale/fr-FR.ts b/packages/docs-ui/src/locale/fr-FR.tsindex 2e85a27007..03acaa9b2c 100644--- a/packages/docs-ui/src/locale/fr-FR.ts+++ b/packages/docs-ui/src/locale/fr-FR.ts@@ -18,6 +18,12 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ objectPermission: {+ paragraphPermission: 'Autorisations',+ title: 'Autorisations',+ paragraph: 'Paragraphe',+ section: 'Section',+ },layout: {progress: 'Mise en page du document…',recovering: 'Restauration de la mise en page du document…',diff --git a/packages/docs-ui/src/locale/id-ID.ts b/packages/docs-ui/src/locale/id-ID.tsindex d6e2174dc6..a6728e8e16 100644--- a/packages/docs-ui/src/locale/id-ID.ts+++ b/packages/docs-ui/src/locale/id-ID.ts@@ -18,6 +18,12 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ objectPermission: {+ paragraphPermission: 'Izin',+ title: 'Izin',+ paragraph: 'Paragraf',+ section: 'Bagian',+ },layout: {progress: 'Menata dokumen…',recovering: 'Memulihkan tata letak dokumen…',diff --git a/packages/docs-ui/src/locale/it-IT.ts b/packages/docs-ui/src/locale/it-IT.tsindex a160bfa6ea..f309a45bf8 100644--- a/packages/docs-ui/src/locale/it-IT.ts+++ b/packages/docs-ui/src/locale/it-IT.ts@@ -18,6 +18,12 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ objectPermission: {+ paragraphPermission: 'Autorizzazioni',+ title: 'Autorizzazioni',+ paragraph: 'Paragrafo',+ section: 'Sezione',+ },layout: {progress: 'Impaginazione del documento…',recovering: 'Ripristino del layout del documento…',diff --git a/packages/docs-ui/src/locale/ja-JP.ts b/packages/docs-ui/src/locale/ja-JP.tsindex f1177e70eb..83f1ef7b2a 100644--- a/packages/docs-ui/src/locale/ja-JP.ts+++ b/packages/docs-ui/src/locale/ja-JP.ts@@ -18,6 +18,12 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ objectPermission: {+ paragraphPermission: '権限',+ title: '権限',+ paragraph: '段落',+ section: 'セクション',+ },layout: {progress: 'ドキュメントをレイアウトしています…',recovering: 'ドキュメントのレイアウトを復元しています…',diff --git a/packages/docs-ui/src/locale/ko-KR.ts b/packages/docs-ui/src/locale/ko-KR.tsindex ba2026e830..eb6d64b449 100644--- a/packages/docs-ui/src/locale/ko-KR.ts+++ b/packages/docs-ui/src/locale/ko-KR.ts@@ -18,6 +18,12 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ objectPermission: {+ paragraphPermission: '권한',+ title: '권한',+ paragraph: '단락',+ section: '섹션',+ },layout: {progress: '문서 레이아웃을 처리하는 중…',recovering: '문서 레이아웃을 복구하는 중…',diff --git a/packages/docs-ui/src/locale/pl-PL.ts b/packages/docs-ui/src/locale/pl-PL.tsindex ce46f5a936..b80f257e05 100644--- a/packages/docs-ui/src/locale/pl-PL.ts+++ b/packages/docs-ui/src/locale/pl-PL.ts@@ -18,6 +18,12 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ objectPermission: {+ paragraphPermission: 'Uprawnienia',+ title: 'Uprawnienia',+ paragraph: 'Akapit',+ section: 'Sekcja',+ },layout: {progress: 'Układanie dokumentu…',recovering: 'Przywracanie układu dokumentu…',diff --git a/packages/docs-ui/src/locale/pt-BR.ts b/packages/docs-ui/src/locale/pt-BR.tsindex f3583ac872..29ddfc7a9b 100644--- a/packages/docs-ui/src/locale/pt-BR.ts+++ b/packages/docs-ui/src/locale/pt-BR.ts@@ -18,6 +18,12 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ objectPermission: {+ paragraphPermission: 'Permissões',+ title: 'Permissões',+ paragraph: 'Parágrafo',+ section: 'Seção',+ },layout: {progress: 'Formatando o documento…',recovering: 'Restaurando o layout do documento…',diff --git a/packages/docs-ui/src/locale/ru-RU.ts b/packages/docs-ui/src/locale/ru-RU.tsindex fa8ac32710..2ed8208c77 100644--- a/packages/docs-ui/src/locale/ru-RU.ts+++ b/packages/docs-ui/src/locale/ru-RU.ts@@ -18,6 +18,12 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ objectPermission: {+ paragraphPermission: 'Права доступа',+ title: 'Права доступа',+ paragraph: 'Абзац',+ section: 'Раздел',+ },layout: {progress: 'Выполняется разметка документа…',recovering: 'Восстановление макета документа…',diff --git a/packages/docs-ui/src/locale/sk-SK.ts b/packages/docs-ui/src/locale/sk-SK.tsindex 2063ea7ca6..83f07f83ef 100644--- a/packages/docs-ui/src/locale/sk-SK.ts+++ b/packages/docs-ui/src/locale/sk-SK.ts@@ -18,6 +18,12 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ objectPermission: {+ paragraphPermission: 'Oprávnenia',+ title: 'Oprávnenia',+ paragraph: 'Odsek',+ section: 'Sekcia',+ },layout: {progress: 'Rozkladá sa dokument…',recovering: 'Obnovuje sa rozloženie dokumentu…',diff --git a/packages/docs-ui/src/locale/vi-VN.ts b/packages/docs-ui/src/locale/vi-VN.tsindex 13508803e6..5447d01e6f 100644--- a/packages/docs-ui/src/locale/vi-VN.ts+++ b/packages/docs-ui/src/locale/vi-VN.ts@@ -18,6 +18,12 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ objectPermission: {+ paragraphPermission: 'Quyền',+ title: 'Quyền',+ paragraph: 'Đoạn văn',+ section: 'Phần',+ },layout: {progress: 'Đang dàn trang tài liệu…',recovering: 'Đang khôi phục bố cục tài liệu…',diff --git a/packages/docs-ui/src/locale/zh-CN.ts b/packages/docs-ui/src/locale/zh-CN.tsindex 7bbdc7c119..936e1b87a7 100644--- a/packages/docs-ui/src/locale/zh-CN.ts+++ b/packages/docs-ui/src/locale/zh-CN.ts@@ -18,6 +18,12 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ objectPermission: {+ paragraphPermission: '权限',+ title: '权限',+ paragraph: '段落',+ section: '节',+ },layout: {progress: '正在排版文档…',recovering: '正在恢复文档排版…',diff --git a/packages/docs-ui/src/locale/zh-HK.ts b/packages/docs-ui/src/locale/zh-HK.tsindex 3c90792cae..75c4fa4c0a 100644--- a/packages/docs-ui/src/locale/zh-HK.ts+++ b/packages/docs-ui/src/locale/zh-HK.ts@@ -18,6 +18,12 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ objectPermission: {+ paragraphPermission: '權限',+ title: '權限',+ paragraph: '段落',+ section: '節',+ },layout: {progress: '正在排版文件…',recovering: '正在恢復文件排版…',diff --git a/packages/docs-ui/src/locale/zh-TW.ts b/packages/docs-ui/src/locale/zh-TW.tsindex 92f04fa256..75c9a5edb2 100644--- a/packages/docs-ui/src/locale/zh-TW.ts+++ b/packages/docs-ui/src/locale/zh-TW.ts@@ -18,6 +18,12 @@ import type enUS from './en-US';const locale: typeof enUS = {'docs-ui': {+ objectPermission: {+ paragraphPermission: '權限',+ title: '權限',+ paragraph: '段落',+ section: '節',+ },layout: {progress: '正在排版文件…',recovering: '正在復原文件排版…',diff --git a/packages/docs-ui/src/menu/menu.ts b/packages/docs-ui/src/menu/menu.tsindex f369756247..5f3d3cca56 100644--- a/packages/docs-ui/src/menu/menu.ts+++ b/packages/docs-ui/src/menu/menu.ts@@ -61,7 +61,7 @@ import {SYMBOL_PICKER_COMPONENT,} from '@univerjs/ui';-import { combineLatest, distinctUntilChanged, map, Observable, shareReplay, startWith } from 'rxjs';+import { combineLatest, distinctUntilChanged, map, Observable, of, shareReplay, startWith } from 'rxjs';import { OpenHeaderFooterPanelCommand } from '../commands/commands/doc-header-footer.command';import { HorizontalLineCommand } from '../commands/commands/doc-horizontal-line.command';import {@@ -959,7 +959,11 @@ export function FloatTextStyleMenuItemFactory(accessor: IAccessor): IMenuSelectoid: FLOAT_TEXT_STYLE_MENU_ID,commandId: SetParagraphNamedStyleCommand.id,type: MenuItemType.SELECTOR,- icon: 'TextTypeIcon',+ icon: of(''),+ label: {+ name: COMMON_LABEL_COMPONENT,+ props: { selections: FLOAT_TEXT_STYLE_OPTIONS },+ },tooltip: 'docs-ui.toolbar.heading.tooltip',selections: FLOAT_TEXT_STYLE_OPTIONS,value$: new Observable((subscriber) => {diff --git a/packages/docs-ui/src/menu/permission.menu.ts b/packages/docs-ui/src/menu/permission.menu.tsnew file mode 100644index 0000000000..8aac28c2b0--- /dev/null+++ b/packages/docs-ui/src/menu/permission.menu.ts@@ -0,0 +1,34 @@+/**+ * 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 { IMenuButtonItem } from '@univerjs/ui';+import { UniverInstanceType } from '@univerjs/core';+import { UnitObject } from '@univerjs/protocol';+import { objectPermissionMenuItemFactory } from '@univerjs/ui';+import { OpenDocParagraphPermissionOperation } from '../commands/operations/paragraph-permission.operation';+import { OpenDocPermissionPanelOperation } from '../commands/operations/permission-panel.operation';++export function DocPermissionMenuItemFactory(accessor: IAccessor): IMenuButtonItem {+ return objectPermissionMenuItemFactory(accessor, OpenDocPermissionPanelOperation.id, UniverInstanceType.UNIVER_DOC, UnitObject.DocumentSection);+}++export function DocParagraphPermissionMenuItemFactory(accessor: IAccessor): IMenuButtonItem {+ return {+ ...objectPermissionMenuItemFactory(accessor, OpenDocParagraphPermissionOperation.id, UniverInstanceType.UNIVER_DOC, UnitObject.DocumentParagraph),+ title: 'docs-ui.objectPermission.paragraphPermission',+ };+}diff --git a/packages/docs-ui/src/menu/schema.ts b/packages/docs-ui/src/menu/schema.tsindex e617297a06..5f9c79eadb 100644--- a/packages/docs-ui/src/menu/schema.ts+++ b/packages/docs-ui/src/menu/schema.ts@@ -79,6 +79,8 @@ import { DocParagraphSettingPanelOperation } from '../commands/operations/doc-paimport { DocSectionSettingPanelOperation } from '../commands/operations/doc-section-setting-panel.operation';import { InsertDocumentColumnBreakOperation } from '../commands/operations/insert-break.operation';import { DocOpenPageSettingCommand } from '../commands/operations/open-page-setting.operation';+import { OpenDocParagraphPermissionOperation } from '../commands/operations/paragraph-permission.operation';+import { OpenDocPermissionPanelOperation } from '../commands/operations/permission-panel.operation';import {CopyMenuFactory,CutMenuFactory,@@ -210,6 +212,7 @@ import {TableBlockPasteMenuItemFactory,TitleHeadingMenuItemFactory,} from './paragraph-menu';+import { DocParagraphPermissionMenuItemFactory, DocPermissionMenuItemFactory } from './permission.menu';export const floatToolbarMenuSchema: MenuSchemaType = {[FLOAT_TOOLBAR_MENU_POSITION]: {@@ -222,6 +225,13 @@ export const floatToolbarMenuSchema: MenuSchemaType = {export const menuSchema: MenuSchemaType = {...floatToolbarMenuSchema,+ [RibbonStartGroup.OTHERS]: {+ [OpenDocPermissionPanelOperation.id]: {+ order: 0,+ gridLayout: { row: 1, column: 1, rowSpan: 2, showLabel: true },+ menuItemFactory: DocPermissionMenuItemFactory,+ },+ },[RibbonStartGroup.FORMAT]: {[SetInlineFormatBoldCommand.id]: {order: 0,@@ -379,6 +389,12 @@ export const menuSchema: MenuSchemaType = {},},[ContextMenuPosition.MAIN_AREA]: {+ [ContextMenuGroup.OTHERS]: {+ [OpenDocParagraphPermissionOperation.id]: {+ order: 10,+ menuItemFactory: DocParagraphPermissionMenuItemFactory,+ },+ },[ContextMenuGroup.QUICK]: ({quickLayout: 'tile',[DocCopyCommand.name]: {diff --git a/packages/docs-ui/src/services/__tests__/doc-layout-coordinator.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-layout-coordinator.service.spec.tsindex dd65f0a839..4a24fa4ddd 100644--- a/packages/docs-ui/src/services/__tests__/doc-layout-coordinator.service.spec.ts+++ b/packages/docs-ui/src/services/__tests__/doc-layout-coordinator.service.spec.ts@@ -19,7 +19,9 @@import type { IDocLayoutMountIdentity, IDocLayoutStartResult } from '@univerjs/docs';import type { IDocumentLayoutProgress } from '@univerjs/engine-render';import type { DocumentLayoutSchedulingSkeleton } from '../doc-layout-coordinator.service';+import { createDocumentModelWithStyle, DocumentFlavor, LocaleService, Univer } from '@univerjs/core';import { DocLayoutSessionStatus } from '@univerjs/docs';+import { DocumentSkeleton, DocumentViewModel } from '@univerjs/engine-render';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { DocLayoutCoordinatorService } from '../doc-layout-coordinator.service';@@ -65,6 +67,150 @@ describe('DocLayoutCoordinatorService', () => {vi.useRealTimers();});+ it('finishes a short Modern edit with empty paragraphs before yielding the input frame', async () => {+ const univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([DocLayoutCoordinatorService]);+ const coordinator = injector.get(DocLayoutCoordinatorService);+ const content = 'First paragraph\r\rSecond paragraph\r\rThird paragraph\r\rLast paragraph\r';+ const model = createDocumentModelWithStyle(content, {});+ model.updateDocumentStyle({ documentFlavor: DocumentFlavor.MODERN, pageSize: { width: 600, height: 800 } });+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), injector.get(LocaleService));+ skeleton.calculate();+ await vi.dynamicImportSettled();+ const onProgress = vi.fn();+ const onForegroundReady = vi.fn();+ try {+ coordinator.schedule(skeleton, {+ reason: 'edit',+ anchor: 0,+ foregroundEndOffset: model.getBody()!.dataStream.length - 2,+ reuseUnaffectedTail: false,+ }, { onProgress, onForegroundReady });++ expect(onForegroundReady).toHaveBeenCalledWith(expect.objectContaining({ complete: true }));+ expect(onProgress).toHaveBeenLastCalledWith(expect.objectContaining({ complete: true }));+ expect(skeleton.getLayoutProgress()?.complete ?? true).toBe(true);+ expect(coordinator.hasScheduledLayout()).toBe(false);+ } finally {+ skeleton.dispose();+ univer.dispose();+ }+ });++ it('keeps completed Main geometry while Worker synchronizes its revision', async () => {+ const univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([DocLayoutCoordinatorService]);+ const coordinator = injector.get(DocLayoutCoordinatorService);+ const model = createDocumentModelWithStyle('First\r\rLast\r', {});+ model.updateDocumentStyle({ documentFlavor: DocumentFlavor.MODERN });+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), injector.get(LocaleService));+ skeleton.calculate();+ const completedGeometry = skeleton.getSkeletonData();+ const beginExternalLayout = vi.spyOn(skeleton, 'beginExternalLayout');+ const cancelExternalLayout = vi.spyOn(skeleton, 'cancelExternalLayout');+ let identity: IDocLayoutMountIdentity;+ const step = (overrides: Partial<IDocumentLayoutProgress>) => ({+ ...identity,+ modelRevision: 2,+ metricsRevision: 1,+ publication: null,+ progress: createProgress({ mode: 'continuous', anchorReady: true, ...overrides }),+ });+ const executor = {+ startLayout: vi.fn(async (request: IDocLayoutMountIdentity): Promise<IDocLayoutStartResult> => {+ identity = request;+ return { status: DocLayoutSessionStatus.ACCEPTED, step: step({ didPublish: true }) };+ }),+ publishBacklog: vi.fn(async () => step({ didPublish: false })),+ stepLayout: vi.fn(async () => step({ didPublish: true, complete: true })),+ getLayoutPage: vi.fn(),+ cancelLayout: vi.fn(async () => {}),+ disposeLayoutMount: vi.fn(async () => {}),+ };+ const onProgress = vi.fn();+ const onComplete = vi.fn();+ const onError = vi.fn();+ try {+ coordinator.scheduleWorker(+ model.getUnitId(),+ skeleton,+ executor,+ { reason: 'edit' },+ undefined,+ { onProgress, onComplete },+ onError,+ true+ );+ expect(beginExternalLayout).not.toHaveBeenCalled();+ await vi.runAllTimersAsync();+ expect(executor.startLayout).toHaveBeenCalledTimes(1);+ expect(executor.stepLayout).toHaveBeenCalledTimes(1);+ expect(onComplete).toHaveBeenCalledWith(expect.objectContaining({ complete: true }));+ expect(onProgress).not.toHaveBeenCalled();+ expect(onError).not.toHaveBeenCalled();+ expect(skeleton.getSkeletonData()).toBe(completedGeometry);+ expect(coordinator.hasScheduledLayout()).toBe(false);++ coordinator.scheduleWorker(+ model.getUnitId(),+ skeleton,+ executor,+ { reason: 'edit' },+ undefined,+ { onProgress },+ onError,+ true+ );+ coordinator.cancel();+ await vi.runAllTimersAsync();+ expect(executor.cancelLayout).toHaveBeenCalledTimes(1);+ expect(cancelExternalLayout).not.toHaveBeenCalled();+ expect(onProgress).not.toHaveBeenCalled();+ expect(skeleton.getSkeletonData()).toBe(completedGeometry);+ } finally {+ skeleton.dispose();+ univer.dispose();+ }+ });++ it('yields the remaining Modern paragraphs when the synchronous budget is exhausted', async () => {+ const univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([DocLayoutCoordinatorService]);+ const coordinator = injector.get(DocLayoutCoordinatorService);+ const model = createDocumentModelWithStyle('Text\r\r'.repeat(100), {});+ model.updateDocumentStyle({ documentFlavor: DocumentFlavor.MODERN });+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), injector.get(LocaleService));+ skeleton.calculate();+ await vi.dynamicImportSettled();+ const onForegroundReady = vi.fn();+ // A monotonic platform clock makes budget exhaustion independent of CI speed.+ let elapsed = 0;+ const now = vi.spyOn(performance, 'now').mockImplementation(() => ++elapsed);+ try {+ coordinator.schedule(skeleton, {+ reason: 'edit',+ anchor: 0,+ foregroundEndOffset: model.getBody()!.dataStream.length - 2,+ foregroundBudgetMs: 1,+ reuseUnaffectedTail: false,+ }, { onProgress: vi.fn(), onForegroundReady });+ expect(onForegroundReady).not.toHaveBeenCalled();+ expect(coordinator.hasScheduledLayout()).toBe(true);+ expect(skeleton.getLayoutProgress()).toMatchObject({ complete: false, anchorReady: true });+ expect(skeleton.getLayoutProgress()!.processedBlockCount).toBeLessThan(10);+ now.mockRestore();+ await vi.runAllTimersAsync();+ expect(onForegroundReady).toHaveBeenCalledWith(expect.objectContaining({ complete: true }));+ } finally {+ now.mockRestore();+ skeleton.dispose();+ univer.dispose();+ }+ });+it('uses foreground slices until the anchor is ready and then finishes in idle slices', () => {const steps = [createProgress({ anchorReady: false }),diff --git a/packages/docs-ui/src/services/__tests__/doc-popup-manager.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-popup-manager.service.spec.tsindex 936172ac01..43938b5350 100644--- a/packages/docs-ui/src/services/__tests__/doc-popup-manager.service.spec.ts+++ b/packages/docs-ui/src/services/__tests__/doc-popup-manager.service.spec.ts@@ -17,13 +17,31 @@import type { DocumentDataModel, IDocumentData } from '@univerjs/core';import type { RenderUnit } from '@univerjs/engine-render';import type { IPopup } from '@univerjs/ui';-import { BooleanNumber, DocumentFlavor, EventSubject, ICommandService, Injector, IUniverInstanceService, Univer, UniverInstanceType } from '@univerjs/core';+import {+ BooleanNumber,+ DocumentFlavor,+ EventSubject,+ ICommandService,+ Injector,+ IUniverInstanceService,+ RANGE_DIRECTION,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';import { DocLayoutExecutorService, DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';-import { CanvasColorService, Documents, ICanvasColorService, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';+import {+ CanvasColorService,+ Documents,+ ICanvasColorService,+ IRenderManagerService,+ RenderManagerService,+} from '@univerjs/engine-render';import { ICanvasPopupService } from '@univerjs/ui';import { describe, expect, it, vi } from 'vitest';import { SetDocZoomRatioOperation } from '../../commands/operations/set-doc-zoom-ratio.operation';-import { DocCanvasPopupLayoutInteractionController } from '../../controllers/render-controllers/doc-canvas-popup-layout-interaction.controller';+import {+ DocCanvasPopupLayoutInteractionController,+} from '../../controllers/render-controllers/doc-canvas-popup-layout-interaction.controller';import { calcDocGlyphPosition } from '../doc-event-manager.service';import { DocLayoutInteractionService } from '../doc-layout-interaction.service';import {@@ -528,6 +546,28 @@ describe('DocCanvasPopManagerService', () => {expect(popupService.removedIds).toContain('popup-1');});+ it.each([RANGE_DIRECTION.FORWARD, RANGE_DIRECTION.BACKWARD])('anchors at the %s selection focus while preserving all exclusion bounds', (direction) => {+ const { service, popupService } = createService();+ const rangeSpy = vi.spyOn(NodePositionConvertToCursor.prototype, 'getRangePointData').mockReturnValue({+ borderBoxPointGroup: [+ [{ x: 10, y: 10 }, { x: 40, y: 10 }, { x: 40, y: 20 }, { x: 10, y: 20 }],+ [{ x: 12, y: 30 }, { x: 70, y: 30 }, { x: 70, y: 40 }, { x: 12, y: 40 }],+ ],+ } as never);+ const disposable = service.attachPopupToRange(+ { startOffset: 0, endOffset: 4, collapsed: false, direction },+ { componentKey: 'focus-menu', direction: 'top-left', rangeAnchor: 'selection-end' },+ 'doc-1'+ );+ const popup = popupService.popups.get('popup-1');+ expect(popup?.anchorRect).toEqual(direction === 'backward'+ ? { left: 20, right: 20, top: 30, bottom: 40 }+ : { left: 80, right: 80, top: 50, bottom: 60 });+ expect(popup?.excludeRects).toHaveLength(2);+ disposable.dispose();+ rangeSpy.mockRestore();+ });+it('keeps the last range popup anchor when its render is stale during refresh', () => {const { service, popupService, renderManagerService, commandService } = createService();const rangeSpy = vi.spyOn(NodePositionConvertToCursor.prototype, 'getRangePointData').mockImplementation(() => ({diff --git a/packages/docs-ui/src/services/__tests__/float-menu.service.spec.ts b/packages/docs-ui/src/services/__tests__/float-menu.service.spec.tsindex 38d3b39e65..f770364501 100644--- a/packages/docs-ui/src/services/__tests__/float-menu.service.spec.ts+++ b/packages/docs-ui/src/services/__tests__/float-menu.service.spec.ts@@ -68,12 +68,14 @@ class RecordingDocCanvasPopManagerService {readonly ranges: string[] = [];readonly directions: string[] = [];readonly offsets: Array<[number, number] | undefined> = [];+ onDismiss?: () => void;disposedCount = 0;- attachPopupToRange(range: { startOffset: number; endOffset: number }, options: { direction: string; offset?: [number, number] }) {+ attachPopupToRange(range: { startOffset: number; endOffset: number }, options: { direction: string; offset?: [number, number]; extraProps?: { onDismiss?: () => void } }) {this.ranges.push(`${range.startOffset}:${range.endOffset}`);this.directions.push(options.direction);this.offsets.push(options.offset);+ this.onDismiss = options.extraProps?.onDismiss;return {dispose: () => {@@ -216,7 +218,7 @@ describe('DocFloatMenuService', () => {const popupService = injector.get(DocCanvasPopManagerService) as unknown as RecordingDocCanvasPopManagerService;const layoutInteractionService = injector.get(DocLayoutInteractionService);expect(popupService.ranges).toEqual(['0:5']);- expect(popupService.offsets).toEqual([[0, 10]]);+ expect(popupService.offsets).toEqual([[0, 8]]);expect(service.floatMenu).toMatchObject({ start: 0, end: 5 });expect(layoutInteractionService.isActive).toBe(true);@@ -639,7 +641,34 @@ describe('DocFloatMenuService', () => {expect(popupService.ranges).toEqual(['0:10', '0:10']);});- it('places the floating toolbar below a forward selection that spans multiple lines', () => {+ it('does not restore a dismissed toolbar until a new selection gesture', () => {+ const unitId = 'doc-dismissed-menu';+ const { popupService, selectionManager, selectionRenderService, service, injector } = createActiveFloatMenuHarness(unitId, {+ dataStream: 'Hello world\r\n',+ paragraphs: [{ paragraphId: 'paragraph', startIndex: 11 }],+ });+ const selection = {+ textRanges: [{ startOffset: 0, endOffset: 5, collapsed: false }],+ rectRanges: [],+ segmentId: '',+ segmentPage: -1,+ style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE,+ isEditing: true,+ };+ selectionManager.__replaceTextRangesWithNoRefresh(selection, { unitId, subUnitId: unitId });+ popupService.onDismiss?.();+ expect(service.floatMenu).toBeNull();+ selectionManager.__replaceTextRangesWithNoRefresh(selection, { unitId, subUnitId: unitId });+ expect(service.floatMenu).toBeNull();+ expect(popupService.ranges).toHaveLength(1);+ selectionRenderService.emitSelectionStart();+ selectionManager.__replaceTextRangesWithNoRefresh(selection, { unitId, subUnitId: unitId });+ expect(service.floatMenu).toMatchObject({ start: 0, end: 5 });+ service.dispose();+ injector.dispose();+ });++ it('places the floating toolbar above the focus end of a multiline selection', () => {const unitId = 'doc-direction-menu';const { popupService, selectionManager, service } = createActiveFloatMenuHarness(unitId, {dataStream: 'First line\rSecond line\r\n',@@ -671,7 +700,7 @@ describe('DocFloatMenuService', () => {expect(service.floatMenu).toMatchObject({ start: 0, end: 18 });expect(popupService.ranges).toEqual(['0:18']);- expect(popupService.directions).toEqual(['bottom-center']);+ expect(popupService.directions).toEqual(['top-left']);service.dispose();expect(popupService.disposedCount).toBe(1);diff --git a/packages/docs-ui/src/services/clipboard/clipboard.service.ts b/packages/docs-ui/src/services/clipboard/clipboard.service.tsindex b550e84249..be27e32e53 100644--- a/packages/docs-ui/src/services/clipboard/clipboard.service.ts+++ b/packages/docs-ui/src/services/clipboard/clipboard.service.ts@@ -27,6 +27,7 @@ import {DOC_RANGE_TYPE,DOCS_NORMAL_EDITOR_UNIT_ID_KEY,DrawingTypeEnum,+ ErrorService,generateRandomId,getBodySlice,ICommandService,@@ -259,6 +260,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ@ICommandService private readonly _commandService: ICommandService,@IPermissionService private readonly _permissionService: IPermissionService,@IClipboardInterfaceService private readonly _clipboardInterfaceService: IClipboardInterfaceService,+ @Inject(ErrorService) private readonly _errorService: ErrorService,@Inject(DocHtmlExportService) docHtmlExportService: DocHtmlExportService,@Inject(DocSelectionManagerService) private readonly _docSelectionManagerService: DocSelectionManagerService) {@@ -389,7 +391,11 @@ export class DocClipboardService extends Disposable implements IDocClipboardServgetDocumentEditTargetObjectIds(document, range.segmentId ?? '', range).forEach((objectId) => objectIds.add(objectId));});- return canEditDocumentTargets(this._permissionService, document.getUnitId(), objectIds);+ const canEdit = canEditDocumentTargets(this._permissionService, document.getUnitId(), objectIds);+ if (!canEdit) {+ this._errorService.emitPermissionDenied(document.getUnitId(), objectIds);+ }+ return canEdit;}private async _cut(ranges?: ITextRangeWithStyle[]): Promise<boolean> {diff --git a/packages/docs-ui/src/services/doc-event-manager.service.ts b/packages/docs-ui/src/services/doc-event-manager.service.tsindex 53877dcfab..37b00c90d2 100644--- a/packages/docs-ui/src/services/doc-event-manager.service.ts+++ b/packages/docs-ui/src/services/doc-event-manager.service.ts@@ -30,7 +30,14 @@ import type {} from '@univerjs/engine-render';import { Disposable, fromEventSubject, Inject, PresetListType } from '@univerjs/core';import { DocSkeletonManagerService } from '@univerjs/docs';-import { CURSOR_TYPE, documentSkeletonLineIterator, documentSkeletonTableIterator, getDocsTableRenderViewport, getTableIdAndSliceIndex, TRANSFORM_CHANGE_OBSERVABLE_TYPE } from '@univerjs/engine-render';+import {+ CURSOR_TYPE,+ documentSkeletonLineIterator,+ documentSkeletonTableIterator,+ getDocsTableRenderViewport,+ getTableIdAndSliceIndex,+ TRANSFORM_CHANGE_OBSERVABLE_TYPE,+} from '@univerjs/engine-render';import { BehaviorSubject, distinctUntilChanged, filter, map, Subject, switchMap, take, tap, throttleTime } from 'rxjs';import { DOC_VERTICAL_PADDING } from '../types/const/padding';import { transformOffset2Bound } from './doc-popup-manager.service';@@ -1112,6 +1119,12 @@ export class DocEventManagerService extends Disposable implements IRenderModulereturn paragraphBounds;}+ contextMenuParagraph: { unitId: string; segmentId: string; paragraphId: string } | null = null;++ getParagraphByOffset(offsetX: number, offsetY: number): Nullable<IMutiPageParagraphBound> {+ return this._calcActiveParagraph(transformOffset2Bound(offsetX, offsetY, this._context.scene));+ }+private _calcActiveParagraph(evt: { x: number; y: number }): Nullable<IMutiPageParagraphBound> {const { x, y } = evt;this._buildTableBounds();diff --git a/packages/docs-ui/src/services/doc-layout-coordinator.service.ts b/packages/docs-ui/src/services/doc-layout-coordinator.service.tsindex 1180c29ef3..bf3b1c19cd 100644--- a/packages/docs-ui/src/services/doc-layout-coordinator.service.ts+++ b/packages/docs-ui/src/services/doc-layout-coordinator.service.ts@@ -14,8 +14,19 @@* limitations under the License.*/-import type { DocLayoutExecutorService, IDocLayoutMountIdentity, IDocLayoutPageResult, IDocLayoutStartOptions, IDocLayoutStepResult } from '@univerjs/docs';-import type { DocumentLayoutReason, DocumentSkeleton, IDocumentLayoutProgress, IDocumentLayoutProtectedRange } from '@univerjs/engine-render';+import type {+ DocLayoutExecutorService,+ IDocLayoutMountIdentity,+ IDocLayoutPageResult,+ IDocLayoutStartOptions,+ IDocLayoutStepResult,+} from '@univerjs/docs';+import type {+ DocumentLayoutReason,+ DocumentSkeleton,+ IDocumentLayoutProgress,+ IDocumentLayoutProtectedRange,+} from '@univerjs/engine-render';import { Disposable } from '@univerjs/core';import { DocLayoutSessionStatus } from '@univerjs/docs';@@ -124,6 +135,7 @@ interface IScheduledWorkerLayout extends IScheduledLayoutBase {viewportEpoch: number;skeleton: ExternalLayoutPresentation;executorService: DocLayoutSchedulingExecutor;+ preserveCompletedLayout: boolean;options: IDocLayoutStartOptions;generation: number | null;modelRevision: number | null;@@ -225,18 +237,17 @@ export class DocLayoutCoordinatorService extends Disposable {synchronousStepCount++;}const foregroundLayout = this._scheduledLayout;- const shouldYieldContinuationToVisualFrame = foregroundLayout?.executor === 'main-thread' && (- !foregroundLayout.anchorReady || foregroundLayout.callbacks.onForegroundReady != null- );if (foregroundLayout?.executor === 'main-thread' &&- !shouldYieldContinuationToVisualFrame &&foregroundLayout.anchorReady &&foregroundLayout.foregroundEndOffset != null &&foregroundLayout.foregroundElapsedMs < foregroundLayout.foregroundBudgetMs) {+ // Modern has no retained page preview below the edited paragraph.+ // Spend at most one foreground slice filling its visible suffix so+ // short documents finish before Canvas paints a truncated prefix.this._runSlice(- foregroundLayout.foregroundBudgetMs - foregroundLayout.foregroundElapsedMs,+ Math.min(FOREGROUND_BUDGET_MS, foregroundLayout.foregroundBudgetMs - foregroundLayout.foregroundElapsedMs),false,false);@@ -277,7 +288,8 @@ export class DocLayoutCoordinatorService extends Disposable {options: IDocLayoutStartOptions,protectedRange: IDocumentLayoutProtectedRange | undefined,callbacks: IDocLayoutCoordinatorCallbacks,- onError: (error: unknown) => void+ onError: (error: unknown) => void,+ preserveCompletedLayout = false): void {this.cancel();const previousMount = this._workerMount;@@ -307,10 +319,12 @@ export class DocLayoutCoordinatorService extends Disposable {mountEpoch: this._mountEpoch,viewportEpoch,};- skeleton.beginExternalLayout({- reason: options.reason,- protectedRange,- });+ if (!preserveCompletedLayout) {+ skeleton.beginExternalLayout({+ reason: options.reason,+ protectedRange,+ });+ }const backgroundResumeDelayMs = getBackgroundResumeDelay(options.reason);this._scheduledLayout = {executor: 'worker',@@ -320,6 +334,7 @@ export class DocLayoutCoordinatorService extends Disposable {viewportEpoch,skeleton,executorService,+ preserveCompletedLayout,options,generation: null,modelRevision: null,@@ -407,7 +422,7 @@ export class DocLayoutCoordinatorService extends Disposable {generation: scheduledLayout.generation,}).catch(scheduledLayout.onError);}- if (scheduledLayout.executor === 'worker') {+ if (scheduledLayout.executor === 'worker' && !scheduledLayout.preserveCompletedLayout) {scheduledLayout.skeleton.cancelExternalLayout();}}@@ -554,7 +569,9 @@ export class DocLayoutCoordinatorService extends Disposable {if (this._scheduledLayout !== scheduledLayout) {return;}- scheduledLayout.skeleton.cancelExternalLayout();+ if (!scheduledLayout.preserveCompletedLayout) {+ scheduledLayout.skeleton.cancelExternalLayout();+ }this._scheduledLayout = null;this._cancelCallbacks();scheduledLayout.onError(error);@@ -598,7 +615,7 @@ export class DocLayoutCoordinatorService extends Disposable {}scheduledLayout.anchorReady = progress.anchorReady;- const publishedProgress = progress.complete && scheduledLayout.callbacks.onForegroundReady != null+ const publishedProgress = progress.complete && progress.mode !== 'continuous' && scheduledLayout.callbacks.onForegroundReady != null? { ...progress, complete: false }: progress;scheduledLayout.callbacks.onProgress(publishedProgress);@@ -903,7 +920,12 @@ export class DocLayoutCoordinatorService extends Disposable {try {scheduledLayout.anchorReady = result.progress.anchorReady;- scheduledLayout.callbacks.onProgress(result.progress, result.publication);+ // Main already finalized this Modern revision. Keep its+ // geometry and selection while Worker catches up its model+ // and layout baseline; partial Worker blocks would hide text.+ if (!scheduledLayout.preserveCompletedLayout) {+ scheduledLayout.callbacks.onProgress(result.progress, result.publication);+ }if (result.progress.complete) {this._scheduledLayout = null;scheduledLayout.callbacks.onComplete?.(result.progress);diff --git a/packages/docs-ui/src/services/doc-popup-manager.service.ts b/packages/docs-ui/src/services/doc-popup-manager.service.tsindex 34cf175484..935dc563e1 100644--- a/packages/docs-ui/src/services/doc-popup-manager.service.ts+++ b/packages/docs-ui/src/services/doc-popup-manager.service.ts@@ -90,6 +90,8 @@ export interface IDocCanvasPopup extends Omit<IPopup, 'anchorRect$' | 'children'mask?: boolean;extraProps?: Record<string, unknown>;multipleDirection?: IPopup['direction'];+ /** Anchor at the focus end while retaining the entire selection for outside-click exclusion. */+ rangeAnchor?: 'selection-end';}export const calcDocRangePositions = (range: ITextRangeParam, currentRender: IRender): IBoundRectNoAngle[] | undefined => {@@ -406,14 +408,23 @@ export class DocCanvasPopManagerService extends Disposable {const popupManagerService = this._resolvePopupManagerService(popupInjector);const { positions: bounds, positions$: bounds$, disposable } = this._createRangePositionObserver(range, currentRender);- const position$ = bounds$.pipe(map((bounds) => direction.includes('top') ? bounds[0] : bounds[bounds.length - 1]));+ const getAnchor = (bounds: IBoundRectNoAngle[]) => {+ if (popup.rangeAnchor === 'selection-end') {+ const backward = range.direction === 'backward';+ const bound = backward ? bounds[0] : bounds[bounds.length - 1];+ const x = backward ? bound.left : bound.right;+ return { ...bound, left: x, right: x };+ }+ return direction.includes('top') ? bounds[0] : bounds[bounds.length - 1];+ };+ const position$ = bounds$.pipe(map(getAnchor));const id = popupManagerService.addPopup({...popup,unitId,subUnitId: 'default',connectorInjector: popupInjector,- anchorRect: direction.includes('top') ? bounds[0] : bounds[bounds.length - 1],+ anchorRect: getAnchor(bounds),anchorRect$: position$,excludeRects: bounds,excludeRects$: bounds$,diff --git a/packages/docs-ui/src/services/float-menu.service.ts b/packages/docs-ui/src/services/float-menu.service.tsindex ad5cec66e9..80fa0525ce 100644--- a/packages/docs-ui/src/services/float-menu.service.ts+++ b/packages/docs-ui/src/services/float-menu.service.ts@@ -15,10 +15,9 @@*/import type { DocumentDataModel, IDisposable, ITextRangeParam, Nullable } from '@univerjs/core';-import type { INodePosition, IRenderContext, IRenderModule, ITextRangeWithStyle } from '@univerjs/engine-render';+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';import {DataStreamTreeTokenType,- deepCompare,Disposable,DocumentBlockRangeType,FOCUSING_COMMON_DRAWINGS,@@ -38,16 +37,6 @@ import { DocLayoutInteractionService } from './doc-layout-interaction.service';import { DocCanvasPopManagerService } from './doc-popup-manager.service';import { DocSelectionRenderService } from './selection/doc-selection-render.service';-function isInSameLine(startNodePosition: Nullable<INodePosition>, endNodePosition: Nullable<INodePosition>) {- if (startNodePosition == null || endNodePosition == null) {- return false;- }- const { glyph: _startGlyph, ...startRest } = startNodePosition;- const { glyph: _endGlyph, ...endRest } = endNodePosition;-- return deepCompare(startRest, endRest);-}-const SKIP_SYMBOLS: string[] = [DataStreamTreeTokenType.CUSTOM_BLOCK,DataStreamTreeTokenType.PARAGRAPH,@@ -241,8 +230,15 @@ export class DocFloatMenuService extends Disposable implements IRenderModule {range,{componentKey: FLOAT_MENU_COMPONENT_KEY,- direction: range.direction === 'backward' || isInSameLine((range as ITextRangeWithStyle).startNodePosition, (range as ITextRangeWithStyle).endNodePosition) ? 'top-center' : 'bottom-center',- offset: [0, 10],+ direction: 'top-left',+ rangeAnchor: 'selection-end',+ offset: [0, 8],+ extraProps: {+ onDismiss: () => {+ this._invalidatedSelection = this._getSelectionKey(range);+ this._hideFloatMenu();+ },+ },},unitId);diff --git a/packages/docs-ui/src/views/float-toolbar/FloatToolbar.tsx b/packages/docs-ui/src/views/float-toolbar/FloatToolbar.tsxindex 03ddb50a3a..c664b927e0 100644--- a/packages/docs-ui/src/views/float-toolbar/FloatToolbar.tsx+++ b/packages/docs-ui/src/views/float-toolbar/FloatToolbar.tsx@@ -14,9 +14,15 @@* limitations under the License.*/-import type { IMenuManagerService as IMenuManagerServiceType, IMenuSchema } from '@univerjs/ui';+import type { IMenuSchema } from '@univerjs/ui';import { borderClassName, clsx } from '@univerjs/design';-import { IMenuManagerService, MenuManagerPosition, preventBrowserZoomInContainers, ToolbarItem, useDependency } from '@univerjs/ui';+import {+ IMenuManagerService,+ MenuManagerPosition,+ preventBrowserZoomInContainers,+ ToolbarItem,+ useDependency,+} from '@univerjs/ui';import { useEffect, useRef, useState } from 'react';import {SetInlineFormatBoldCommand,@@ -33,6 +39,7 @@ import { FLOAT_TEXT_STYLE_MENU_ID, FLOAT_TOOLBAR_MENU_POSITION } from '../../meninterface IFloatToolbarProps {avaliableMenus?: Array<string | IFloatToolbarMenuConfig>;+ popup?: { extraProps?: { onDismiss?: () => void } };}interface IFloatToolbarMenuConfig {@@ -63,7 +70,7 @@ const DEFAULT_AVALIABLE_MENUS: Array<string | IFloatToolbarMenuConfig> = [];export function resolveFloatToolbarMenus(- menuManagerService: IMenuManagerServiceType,+ menuManagerService: IMenuManagerService,avaliableMenus: Array<string | IFloatToolbarMenuConfig>): { menus: IFloatToolbarMenuSchema[]; extraMenus: IMenuSchema[] } {const floatToolbarMenus = menuManagerService.getMenuByPositionKey(FLOAT_TOOLBAR_MENU_POSITION);@@ -90,9 +97,12 @@ export function resolveFloatToolbarMenus(export function FloatToolbar(props: IFloatToolbarProps) {const { avaliableMenus = DEFAULT_AVALIABLE_MENUS } = props;+ const onDismiss = props.popup?.extraProps?.onDismiss;const menuManagerService = useDependency(IMenuManagerService);const toolbarRef = useRef<HTMLDivElement>(null);+ const hoveredRef = useRef(false);+ const dismissedRef = useRef(false);const [menus, setMenus] = useState<IFloatToolbarMenuSchema[]>([]);const [extraMenus, setExtraMenus] = useState<IMenuSchema[]>([]);@@ -122,32 +132,86 @@ export function FloatToolbar(props: IFloatToolbarProps) {return preventBrowserZoomInContainers([toolbar]);}, []);+ useEffect(() => {+ const toolbar = toolbarRef.current;+ if (!toolbar || !onDismiss) {+ return;+ }+ const onPointerMove = (event: PointerEvent) => {+ if (hoveredRef.current || dismissedRef.current || event.pointerType === 'touch') {+ return;+ }+ const rect = toolbar.getBoundingClientRect();+ const distance = Math.max(rect.left - event.clientX, event.clientX - rect.right, rect.top - event.clientY, event.clientY - rect.bottom, 0);+ // Give the pointer a 10px safe area, then fade over the next 80px.+ const opacity = Math.max(0, 1 - Math.max(0, distance - 10) / 80);+ toolbar.style.opacity = String(opacity);+ if (opacity === 0) {+ dismissedRef.current = true;+ onDismiss();+ }+ };+ toolbar.ownerDocument.addEventListener('pointermove', onPointerMove);+ return () => toolbar.ownerDocument.removeEventListener('pointermove', onPointerMove);+ }, [onDismiss]);++ const retainToolbar = () => {+ hoveredRef.current = true;+ if (toolbarRef.current) {+ toolbarRef.current.style.opacity = '1';+ }+ };+ const selectors = menus.filter((menu) => menu.key === FLOAT_TEXT_STYLE_MENU_ID || menu.key === SetInlineFormatFontSizeCommand.id);+ const formatting = menus.filter((menu) => !selectors.includes(menu));+return (<divref={toolbarRef}+ data-doc-float-toolbar+ onPointerEnter={retainToolbar}+ onFocusCapture={retainToolbar}className={clsx(`- univer-box-border univer-flex univer-rounded univer-bg-gray-0 univer-py-1.5 univer-shadow-sm+ univer-box-border univer-flex univer-flex-col univer-gap-1 univer-rounded univer-bg-gray-0 univer-p-1+ univer-shadow-smdark:!univer-border-gray-700 dark:!univer-bg-gray-900`, borderClassName)}>- {menus.map((groupItem) => groupItem.item && (- <div key={groupItem.key} className="univer-flex univer-flex-nowrap univer-gap-2 univer-px-2">- <ToolbarItem key={groupItem.key} {...groupItem.item} iconColor={groupItem.iconColor} />- </div>- ))}- {extraMenus.length > 0 && (- <div- className="- univer-my-1 univer-w-px univer-bg-gray-200- dark:univer-bg-gray-700- "- />- )}- {extraMenus.map((groupItem) => groupItem.item && (- <div key={groupItem.key} className="univer-flex univer-flex-nowrap univer-gap-2 univer-px-2">- <ToolbarItem key={groupItem.key} {...groupItem.item} />- </div>- ))}+ <div+ className="+ univer-flex univer-items-center univer-gap-1+ [&_.univer-toolbar-selector-root]:univer-text-xs+ "+ >+ {selectors.map((menu) => menu.item && (+ <div+ key={menu.key}+ className={menu.key === FLOAT_TEXT_STYLE_MENU_ID+ ? `+ univer-min-w-0 univer-flex-1+ [&_.univer-toolbar-selector-root]:univer-box-border+ [&_.univer-toolbar-selector-root]:univer-w-full+ [&_.univer-toolbar-selector-root]:univer-justify-between+ `+ : 'univer-shrink-0'}+ >+ <ToolbarItem {...menu.item} iconSize={14} iconColor={menu.iconColor} />+ </div>+ ))}+ {selectors.length > 0 && extraMenus.length > 0 && (+ <div+ className="+ univer-mx-0.5 univer-h-4 univer-w-px univer-bg-gray-200+ dark:univer-bg-gray-700+ "+ />+ )}+ {extraMenus.map((menu) => menu.item && <ToolbarItem key={menu.key} {...menu.item} iconSize={14} />)}+ </div>+ <div className="univer-flex univer-items-center univer-gap-0.5">+ {formatting.map((menu) => menu.item && (+ <ToolbarItem key={menu.key} {...menu.item} iconSize={14} iconColor={menu.iconColor} />+ ))}+ </div></div>);}diff --git a/packages/docs-ui/src/views/float-toolbar/__tests__/FloatToolbar.spec.tsx b/packages/docs-ui/src/views/float-toolbar/__tests__/FloatToolbar.spec.tsxindex 9e05d09ac3..6e441b9e32 100644--- a/packages/docs-ui/src/views/float-toolbar/__tests__/FloatToolbar.spec.tsx+++ b/packages/docs-ui/src/views/float-toolbar/__tests__/FloatToolbar.spec.tsx@@ -40,7 +40,7 @@ import {import { act } from 'react';import { createRoot } from 'react-dom/client';import { Subject } from 'rxjs';-import { afterEach, describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import {SetInlineFormatBoldCommand,SetInlineFormatTextBackgroundColorCommand,@@ -183,7 +183,7 @@ function createToolbarTestBed() {};}-function renderToolbar(injector: Injector, avaliableMenus: string[]) {+function renderToolbar(injector: Injector, avaliableMenus: string[], onDismiss?: () => void) {const container = document.createElement('div');document.body.appendChild(container);const root = createRoot(container);@@ -191,7 +191,7 @@ function renderToolbar(injector: Injector, avaliableMenus: string[]) {act(() => {root.render(<RediContext.Provider value={{ injector }}>- <FloatToolbar avaliableMenus={avaliableMenus} />+ <FloatToolbar avaliableMenus={avaliableMenus} popup={{ extraProps: { onDismiss } }} /></RediContext.Provider>);});@@ -224,6 +224,45 @@ describe('FloatToolbar', () => {container = undefined;});+ it('fades outside the safe area and dismisses only once without prior hover', () => {+ const testBed = createToolbarTestBed();+ const onDismiss = vi.fn();+ ({ root, container } = renderToolbar(testBed.injector, [], onDismiss));+ const toolbar = container.querySelector<HTMLElement>('[data-doc-float-toolbar]')!;+ vi.spyOn(toolbar, 'getBoundingClientRect').mockReturnValue({ left: 100, right: 300, top: 100, bottom: 160 } as DOMRect);+ const move = (y: number) => act(() => document.dispatchEvent(new PointerEvent('pointermove', { clientX: 200, clientY: y })));++ move(170);+ expect(toolbar.style.opacity).toBe('1');+ move(210);+ expect(toolbar.style.opacity).toBe('0.5');+ move(170);+ expect(toolbar.style.opacity).toBe('1');+ move(250);+ move(260);+ expect(onDismiss).toHaveBeenCalledTimes(1);+ testBed.injector.dispose();+ });++ it('stays fully visible after hover even when the pointer leaves the menu', () => {+ const testBed = createToolbarTestBed();+ const onDismiss = vi.fn();+ ({ root, container } = renderToolbar(testBed.injector, [], onDismiss));+ const toolbar = container.querySelector<HTMLElement>('[data-doc-float-toolbar]')!;+ vi.spyOn(toolbar, 'getBoundingClientRect').mockReturnValue({ left: 100, right: 300, top: 100, bottom: 160 } as DOMRect);+ act(() => document.dispatchEvent(new PointerEvent('pointermove', { clientX: 200, clientY: 210 })));+ expect(toolbar.style.opacity).toBe('0.5');+ act(() => toolbar.dispatchEvent(new PointerEvent('pointerover', { bubbles: true })));+ act(() => document.dispatchEvent(new PointerEvent('pointermove', { clientX: 800, clientY: 800 })));+ expect(toolbar.style.opacity).toBe('1');+ expect(onDismiss).not.toHaveBeenCalled();+ act(() => root!.unmount());+ root = undefined;+ act(() => document.dispatchEvent(new PointerEvent('pointermove', { clientX: 1000, clientY: 1000 })));+ expect(onDismiss).not.toHaveBeenCalled();+ testBed.injector.dispose();+ });+it('keeps whitelisted toolbar menus ordered and separates direct extension menus', () => {const textStyleItem = createMenuItem(FLOAT_TEXT_STYLE_MENU_ID);const boldItem = createMenuItem(SetInlineFormatBoldCommand.id);diff --git a/packages/docs-ui/src/views/paragraph-setting/Setting.tsx b/packages/docs-ui/src/views/paragraph-setting/Setting.tsxindex 39503c336c..d35492894e 100644--- a/packages/docs-ui/src/views/paragraph-setting/Setting.tsx+++ b/packages/docs-ui/src/views/paragraph-setting/Setting.tsx@@ -216,7 +216,6 @@ export function ParagraphSetting() {</ParagraphSettingRow></div></ParagraphSettingSection>-</div>);}diff --git a/packages/docs-ui/src/views/permission/DocObjectPermissionEntry.tsx b/packages/docs-ui/src/views/permission/DocObjectPermissionEntry.tsxnew file mode 100644index 0000000000..578f813973--- /dev/null+++ b/packages/docs-ui/src/views/permission/DocObjectPermissionEntry.tsx@@ -0,0 +1,82 @@+/**+ * 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 { LocaleKey } from '../../locale/types';+import { IUniverInstanceService, LocaleService, ObjectPermissionService } from '@univerjs/core';+import { Button, Separator } from '@univerjs/design';+import {+ getDocumentParagraphPermissionObjectId,+ getDocumentSectionPermissionObjectId,+ SetDocumentPermissionCommand,+} from '@univerjs/docs';+import { UnitObject } from '@univerjs/protocol';+import { openObjectPermissionDialog, useDependency, useInjector, useObservable } from '@univerjs/ui';++interface IDocObjectPermissionEntryProps {+ unitId?: string;+ id?: string;+ objectType: UnitObject.DocumentParagraph | UnitObject.DocumentSection;+ segmentId?: string;+}++export function DocObjectPermissionEntry({ unitId, id, objectType, segmentId = '' }: IDocObjectPermissionEntryProps) {+ const injector = useInjector();+ const instances = useDependency(IUniverInstanceService);+ const permissions = useDependency(ObjectPermissionService);+ const localeService = useDependency(LocaleService);+ useObservable(permissions.changed$, 0);+ useObservable(localeService.currentLocale$);+ if (!unitId || !id) {+ return null;+ }+ const isParagraph = objectType === UnitObject.DocumentParagraph;+ const target = {+ unitId,+ objectId: isParagraph+ ? getDocumentParagraphPermissionObjectId(segmentId, id)+ : getDocumentSectionPermissionObjectId(segmentId, id),+ objectType,+ };+ const exists = () => {+ const body = instances.getUnit<DocumentDataModel>(unitId)?.getSelfOrHeaderFooterModel(segmentId)?.getBody();+ return isParagraph+ ? body?.paragraphs?.some((paragraph) => paragraph.paragraphId === id) === true+ : body?.sectionBreaks?.some((section) => section.sectionId === id) === true;+ };+ if (!permissions.supports(target) || !exists()) {+ return null;+ }+ return (+ <div className="univer-mt-5">+ <Separator className="univer-mb-3" />+ <Button+ disabled={!permissions.canView(target)}+ type="button"+ variant="text"+ className="univer-w-full univer-justify-start"+ onClick={() => openObjectPermissionDialog(injector, {+ target,+ name: localeService.t<LocaleKey>(isParagraph ? 'docs-ui.objectPermission.paragraph' : 'docs-ui.objectPermission.section'),+ commandId: SetDocumentPermissionCommand.id,+ exists,+ })}+ >+ {localeService.t<LocaleKey>('docs-ui.objectPermission.title')}+ </Button>+ </div>+ );+}diff --git a/packages/docs-ui/src/views/permission/__tests__/DocObjectPermissionEntry.spec.tsx b/packages/docs-ui/src/views/permission/__tests__/DocObjectPermissionEntry.spec.tsxnew file mode 100644index 0000000000..5402d09a57--- /dev/null+++ b/packages/docs-ui/src/views/permission/__tests__/DocObjectPermissionEntry.spec.tsx@@ -0,0 +1,145 @@+/**+ * 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 { IDialogPartMethodOptions, IObjectPermissionButtonProps } from '@univerjs/ui';+import type { ReactNode } from 'react';+import {+ IConfigService,+ IPermissionService,+ IUniverInstanceService,+ LocaleType,+ OBJECT_PERMISSION_CONFIG_KEY,+ PermissionStatus,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { SetDocumentPermissionCommand, UniverDocsPlugin } from '@univerjs/docs';+import { UnitAction, UnitObject } from '@univerjs/protocol';+import { DesktopDialogService, IDialogService, IUIPartsService, RediProvider, UIPartsService } from '@univerjs/ui';+import uiEnUS from '@univerjs/ui/locale/en-US';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { firstValueFrom } from 'rxjs';+import { afterEach, describe, expect, it } from 'vitest';+import enUS from '../../../locale/en-US';+import { DocObjectPermissionEntry } from '../DocObjectPermissionEntry';++Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, value: true });++const univers: Univer[] = [];+const views: Array<{ unmount: () => void }> = [];+function render(node: ReactNode) {+ const container = document.createElement('div');+ document.body.appendChild(container);+ const root = createRoot(container);+ act(() => root.render(node));+ const view = { container, unmount: () => {+ act(() => root.unmount());+ container.remove();+ } };+ views.push(view);+ return view;+}+afterEach(() => {+ views.splice(0).forEach((view) => view.unmount());+ univers.splice(0).forEach((univer) => univer.dispose());+});++function setup(supportedTypes: UnitObject[] = []) {+ const univer = new Univer({+ locale: LocaleType.EN_US,+ locales: { [LocaleType.EN_US]: { ...uiEnUS, ...enUS } },+ });+ univers.push(univer);+ univer.__getInjector().get(IConfigService).setConfig(OBJECT_PERMISSION_CONFIG_KEY, supportedTypes);+ univer.registerPlugin(UniverDocsPlugin);+ univer.createUnit(UniverInstanceType.UNIVER_DOC, {+ id: 'doc',+ body: {+ dataStream: 'One\rTwo\r\n',+ paragraphs: [{ startIndex: 3, paragraphId: 'shared/id' }, { startIndex: 7, paragraphId: 'second' }],+ sectionBreaks: [{ startIndex: 8, sectionId: 'section/one' }],+ },+ headers: {+ 'header/one': {+ headerId: 'header/one',+ body: { dataStream: 'Header\r\n', paragraphs: [{ startIndex: 6, paragraphId: 'shared/id' }] },+ },+ },+ });+ const injector = univer.__getInjector();+ injector.get(IPermissionService).addPermissionPoint({ id: `${UnitObject.Document}.${UnitAction.Edit}_doc`, type: UnitObject.Document, subType: UnitAction.Edit, value: true, status: PermissionStatus.DONE });+ injector.add([IUIPartsService, { useClass: UIPartsService }]);+ injector.add([IDialogService, { useClass: DesktopDialogService }]);+ return { injector, dialogs: injector.get(IDialogService) };+}++function getDialogProps(dialog: IDialogPartMethodOptions): IObjectPermissionButtonProps {+ const label = dialog.children?.label;+ if (!label || typeof label !== 'object' || !('props' in label)) {+ throw new Error('Expected a hosted object permission dialog.');+ }+ return label.props as IObjectPermissionButtonProps;+}++describe('DocObjectPermissionEntry', () => {+ it.each([UnitObject.DocumentParagraph, UnitObject.DocumentSection] as const)('hides the entry and separator without support for object type %s', (objectType) => {+ const { injector } = setup([UnitObject.Document]);+ const { container } = render(+ <RediProvider value={{ injector }}>+ <DocObjectPermissionEntry unitId="doc" id={objectType === UnitObject.DocumentParagraph ? 'shared/id' : 'section/one'} objectType={objectType} />+ </RediProvider>+ );+ expect(container.innerHTML).toBe('');+ });++ it.each([+ { objectType: UnitObject.DocumentParagraph, id: 'shared/id', segmentId: '', objectId: 'paragraph//shared%2Fid' },+ { objectType: UnitObject.DocumentParagraph, id: 'shared/id', segmentId: 'header/one', objectId: 'paragraph/header%2Fone/shared%2Fid' },+ { objectType: UnitObject.DocumentSection, id: 'section/one', segmentId: '', objectId: 'section//section%2Fone' },+ ] as const)('opens a stable $objectId target and retains it after the panel unmounts', async ({ objectType, id, segmentId, objectId }) => {+ const { injector, dialogs } = setup([objectType]);+ const view = render(+ <RediProvider value={{ injector }}>+ <DocObjectPermissionEntry unitId="doc" id={id} objectType={objectType} segmentId={segmentId} />+ </RediProvider>+ );+ expect(view.container.querySelector('[data-u-comp="separator"]')).not.toBeNull();+ const opened = firstValueFrom(dialogs.getDialogs$());+ const button = view.container.querySelector('button')!;+ expect(button.textContent).toBe('Permissions');+ act(() => button.click());+ const [dialog] = await opened;+ view.unmount();+ expect(dialog.open).toBe(true);+ const props = getDialogProps(dialog);+ expect(props.target).toEqual({ unitId: 'doc', objectId, objectType });+ expect(props.commandId).toBe(SetDocumentPermissionCommand.id);+ expect(props.exists?.()).toBe(true);+ injector.get(IUniverInstanceService).disposeUnit('doc');+ expect(props.exists?.()).toBe(false);+ });++ it.each([undefined, 'deleted-id'])('hides the entry without a single existing target (%s)', (id) => {+ const { injector } = setup([UnitObject.DocumentParagraph]);+ const { container } = render(+ <RediProvider value={{ injector }}>+ <DocObjectPermissionEntry unitId="doc" id={id} objectType={UnitObject.DocumentParagraph} />+ </RediProvider>+ );+ expect(container.innerHTML).toBe('');+ });+});diff --git a/packages/docs-ui/src/views/section-setting/Setting.tsx b/packages/docs-ui/src/views/section-setting/Setting.tsxindex d647cc280b..2ed33a9e9f 100644--- a/packages/docs-ui/src/views/section-setting/Setting.tsx+++ b/packages/docs-ui/src/views/section-setting/Setting.tsx@@ -18,9 +18,11 @@ import type { ReactNode } from 'react';import type { LocaleKey } from '../../locale/types';import { ColumnSeparatorType, LocaleService, PageOrientType, SectionType } from '@univerjs/core';import { InputNumber, Select } from '@univerjs/design';+import { UnitObject } from '@univerjs/protocol';import { useDependency, useObservable } from '@univerjs/ui';import { useEffect } from 'react';import { DocSectionSettingController } from '../../controllers/doc-section-setting.controller';+import { DocObjectPermissionEntry } from '../permission/DocObjectPermissionEntry';import { useSectionSetting } from './use-section-setting';function SettingRow(props: { label: ReactNode; unit?: string; children: ReactNode }) {@@ -249,6 +251,11 @@ export function SectionSetting() {/></SettingRow></div>+ <DocObjectPermissionEntry+ unitId={setting.unitId}+ id={setting.selectedSectionId}+ objectType={UnitObject.DocumentSection}+ /></div>);}diff --git a/packages/docs-ui/src/views/section-setting/use-section-setting.ts b/packages/docs-ui/src/views/section-setting/use-section-setting.tsindex d4a0b2313d..d5e473d201 100644--- a/packages/docs-ui/src/views/section-setting/use-section-setting.ts+++ b/packages/docs-ui/src/views/section-setting/use-section-setting.ts@@ -199,6 +199,7 @@ export function useSectionSetting() {);return {+ unitId: documentDataModel?.getUnitId(),valid: Boolean(documentDataModel && sections.length > 0),selectedCount: sections.length,sectionOptions: allSections.map((section, index) => ({diff --git a/packages/docs/src/commands/commands/__tests__/set-document-permission.command.spec.ts b/packages/docs/src/commands/commands/__tests__/set-document-permission.command.spec.tsnew file mode 100644index 0000000000..58df8f3701--- /dev/null+++ b/packages/docs/src/commands/commands/__tests__/set-document-permission.command.spec.ts@@ -0,0 +1,72 @@+/**+ * 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 {+ IAuthzIoService,+ ICommandService,+ IConfigService,+ IPermissionService,+ OBJECT_PERMISSION_CONFIG_KEY,+ ObjectPermissionService,+ Univer,+} from '@univerjs/core';+import { UnitAction, UnitObject } from '@univerjs/protocol';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { DocumentPermissionRuleModel } from '../../../services/permission/document-permission-rule.model';++import { SetDocumentPermissionRuleMutation } from '../../mutations/set-document-permission-rule.mutation';+import { SetDocumentPermissionCommand } from '../set-document-permission.command';++const univers: Univer[] = [];+afterEach(() => univers.splice(0).forEach((univer) => univer.dispose()));++describe('SetDocumentPermissionCommand', () => {+ it('awaits the Authz write and propagates failure without changing effective permissions', async () => {+ const list = vi.fn(async () => [] as Array<{ unitID: string; objectID: string; objectType: UnitObject }>);+ const create = vi.fn(async () => {+ throw new Error('Authz rejected');+ });+ const univer = new Univer({ override: [[IAuthzIoService, { useValue: {+ list,+ listCollaborators: async () => [],+ allowed: async ({ actions }: { actions: UnitAction[] }) => actions.map((action) => ({ action, allowed: true })),+ create,+ } }]] });+ univers.push(univer);+ const injector = univer.__getInjector();+ const commands = injector.get(ICommandService);+ injector.add([DocumentPermissionRuleModel]);+ injector.get(IConfigService).setConfig(OBJECT_PERMISSION_CONFIG_KEY, [UnitObject.Document, UnitObject.DocumentParagraph]);+ injector.get(ObjectPermissionService).registerRuleModel(UnitObject.Document, injector.get(DocumentPermissionRuleModel), SetDocumentPermissionRuleMutation.id);+ commands.registerCommand(SetDocumentPermissionRuleMutation);+ commands.registerCommand(SetDocumentPermissionCommand);+ await expect(commands.executeCommand(SetDocumentPermissionCommand.id, { unitId: 'unit', objectId: 'paragraph//a', action: UnitAction.Edit, value: false })).rejects.toThrow('Authz rejected');+ expect(create).toHaveBeenCalledWith(expect.objectContaining({ objectType: UnitObject.DocumentParagraph, documentObject: expect.objectContaining({ unitID: 'unit' }) }));+ expect(injector.get(DocumentPermissionRuleModel).getRules('unit')).toEqual([]);+ expect(injector.get(IPermissionService).getPermissionPoint(`${UnitObject.DocumentParagraph}.${UnitAction.Edit}_unit_paragraph//a`)).toBeUndefined();+ });++ it('rejects unsupported child actions in policy payloads before calling Authz', async () => {+ const update = vi.fn();+ const univer = new Univer({ override: [[IAuthzIoService, { useValue: { update } }]] });+ univers.push(univer);+ const commands = univer.__getInjector().get(ICommandService);+ commands.registerCommand(SetDocumentPermissionCommand);+ const result = await commands.executeCommand(SetDocumentPermissionCommand.id, { unitId: 'unit', objectId: 'paragraph//a', action: UnitAction.Edit, value: false, policy: { edit: 'owner', collaborators: [], strategies: [{ action: UnitAction.Print, role: 2 }] } });+ expect(result).toBe(false);+ expect(update).not.toHaveBeenCalled();+ });+});diff --git a/packages/docs/src/commands/commands/set-document-permission.command.ts b/packages/docs/src/commands/commands/set-document-permission.command.tsindex 3689b24f84..8833eb9126 100644--- a/packages/docs/src/commands/commands/set-document-permission.command.ts+++ b/packages/docs/src/commands/commands/set-document-permission.command.ts@@ -14,13 +14,13 @@* limitations under the License.*/-import type { ICommand } from '@univerjs/core';+import type { ICommand, IObjectPermissionPolicy } from '@univerjs/core';import type { DocumentUnitPermissionAction } from '../../services/permission/document-permission';-import { CommandType, IPermissionService } from '@univerjs/core';+import { CommandType, ObjectPermissionService } from '@univerjs/core';import { UnitAction } from '@univerjs/protocol';import {+ createDocumentPermissionPoint,DOCUMENT_UNIT_PERMISSION_ACTIONS,- setDocumentPermissionValue,} from '../../services/permission/document-permission';export interface ISetDocumentPermissionCommandParams {@@ -28,12 +28,15 @@ export interface ISetDocumentPermissionCommandParams {objectId: string;action: DocumentUnitPermissionAction;value: boolean;+ policy?: IObjectPermissionPolicy;+ /** Remove the child permission rule and restore inherited rights; never deletes content. */+ remove?: boolean;}export const SetDocumentPermissionCommand: ICommand<ISetDocumentPermissionCommandParams> = {type: CommandType.COMMAND,id: 'doc.command.set-permission',- handler(accessor, params) {+ async handler(accessor, params) {if (!params || !DOCUMENT_UNIT_PERMISSION_ACTIONS.includes(params.action)) {return false;}@@ -41,13 +44,21 @@ export const SetDocumentPermissionCommand: ICommand<ISetDocumentPermissionCommanreturn false;}- setDocumentPermissionValue(- accessor.get(IPermissionService),- params.unitId,- params.objectId,- params.action,- params.value- );+ if (params.policy && (!['all', 'owner', 'members'].includes(params.policy.edit) ||+ params.policy.strategies.some((strategy) => !DOCUMENT_UNIT_PERMISSION_ACTIONS.includes(strategy.action as typeof params.action) ||+ (params.objectId !== params.unitId && strategy.action !== UnitAction.Edit)))) {+ return false;+ }+ const point = createDocumentPermissionPoint(params.unitId, params.objectId, params.action);+ const target = { unitId: params.unitId, objectId: params.objectId, objectType: point.type };+ const service = accessor.get(ObjectPermissionService);+ if (params.remove) {+ await service.remove(target);+ } else if (params.policy) {+ await service.save(target, params.policy);+ } else {+ await service.setPoint(target, point, params.value);+ }return true;},};diff --git a/packages/docs/src/commands/mutations/__tests__/set-document-permission-rule.mutation.spec.ts b/packages/docs/src/commands/mutations/__tests__/set-document-permission-rule.mutation.spec.tsnew file mode 100644index 0000000000..cd47e7b535--- /dev/null+++ b/packages/docs/src/commands/mutations/__tests__/set-document-permission-rule.mutation.spec.ts@@ -0,0 +1,53 @@+/**+ * 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 { ICommandService, IResourceManagerService, Univer, UniverInstanceType } from '@univerjs/core';+import { UnitObject } from '@univerjs/protocol';+import { afterEach, expect, it } from 'vitest';+import { DocumentPermissionRuleModel } from '../../../services/permission/document-permission-rule.model';+import { SetDocumentPermissionRuleMutation } from '../set-document-permission-rule.mutation';++const univers: Univer[] = [];+afterEach(() => univers.splice(0).forEach((univer) => univer.dispose()));+function setup() {+ const univer = new Univer();+ univers.push(univer);+ const injector = univer.__getInjector();+ injector.add([DocumentPermissionRuleModel]);+ const model = injector.get(DocumentPermissionRuleModel);+ univer.createUnit(UniverInstanceType.UNIVER_DOC, { id: 'unit', body: { dataStream: '\r\n' } });+ const commands = injector.get(ICommandService);+ commands.registerCommand(SetDocumentPermissionRuleMutation);+ return { univer, model, commands, resources: injector.get(IResourceManagerService) };+}+it('round trips bindings through the business resource and deterministically replays removal and restoration', () => {+ const first = setup();+ const params = { unitId: 'unit', objectId: 'stable/object', objectType: UnitObject.DocumentParagraph, rule: { objectId: 'stable/object', objectType: UnitObject.DocumentParagraph, permissionId: 'authz-rule-1' } };+ expect(first.commands.syncExecuteCommand(SetDocumentPermissionRuleMutation.id, params)).toBe(true);+ const second = setup();+ second.resources.loadResources('unit', first.resources.getResources('unit', UniverInstanceType.UNIVER_DOC));+ expect(second.model.getRules('unit')).toEqual([params.rule]);+ expect(second.commands.syncExecuteCommand(SetDocumentPermissionRuleMutation.id, { ...params, rule: null })).toBe(true);+ expect(second.model.getRules('unit')).toEqual([]);+ expect(second.commands.syncExecuteCommand(SetDocumentPermissionRuleMutation.id, params)).toBe(true);+ const copy = second.model.getRules('unit');+ copy[0].permissionId = 'changed';+ expect(second.model.getRules('unit')).toEqual([params.rule]);+ expect(second.commands.syncExecuteCommand(SetDocumentPermissionRuleMutation.id, { ...params, unitId: 'missing' })).toBe(false);+ expect(second.commands.syncExecuteCommand(SetDocumentPermissionRuleMutation.id, { ...params, objectType: UnitObject.Worksheet })).toBe(false);+ second.resources.unloadResources('unit', UniverInstanceType.UNIVER_DOC);+ expect(second.model.getRules('unit')).toEqual([]);+});diff --git a/packages/docs/src/commands/mutations/set-document-permission-rule.mutation.ts b/packages/docs/src/commands/mutations/set-document-permission-rule.mutation.tsnew file mode 100644index 0000000000..f50be77e1a--- /dev/null+++ b/packages/docs/src/commands/mutations/set-document-permission-rule.mutation.ts@@ -0,0 +1,30 @@+/**+ * 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 { IMutation, ISetObjectPermissionRuleMutationParams } from '@univerjs/core';+import { CommandType, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';+import { DocumentPermissionRuleModel } from '../../services/permission/document-permission-rule.model';++export const SetDocumentPermissionRuleMutation: IMutation<ISetObjectPermissionRuleMutationParams> = {+ id: 'doc.mutation.set-permission-rule',+ type: CommandType.MUTATION,+ handler: (accessor, params) => {+ if (!params || !accessor.get(IUniverInstanceService).getUnit(params.unitId, UniverInstanceType.UNIVER_DOC)) {+ return false;+ }+ return accessor.get(DocumentPermissionRuleModel).setRule(params.unitId, params.objectType, params.objectId, params.rule);+ },+};diff --git a/packages/docs/src/controllers/__tests__/doc-permission.controller.spec.ts b/packages/docs/src/controllers/__tests__/doc-permission.controller.spec.tsindex d6426db426..1f08d7a641 100644--- a/packages/docs/src/controllers/__tests__/doc-permission.controller.spec.ts+++ b/packages/docs/src/controllers/__tests__/doc-permission.controller.spec.ts@@ -20,6 +20,7 @@ import {CommandType,DocumentFlavor,DrawingTypeEnum,+ ErrorService,ICommandService,IPermissionService,IUndoRedoService,@@ -142,9 +143,19 @@ describe('DocPermissionController', () => {it('enforces document edit permission through the facade and command pipeline', async () => {await document.getPermission().setReadOnly();+ const targets: Array<string | undefined> = [];+ const subscription = get(ErrorService).error$.subscribe((error) => targets.push(error.permissionTarget));expect(document.getPermission().canEdit()).toBe(false);expect(document.getParagraph('paragraph-one')!.setText('Denied')).toBe(false);+ expect(document.getParagraph('paragraph-two')!.setText('Also denied')).toBe(false);+ expect(document.getParagraph('paragraph-one')!.setText('Denied again')).toBe(false);+ expect(targets).toHaveLength(3);+ expect(targets[0]).toBeDefined();+ expect(targets[1]).not.toBe(targets[0]);+ expect(targets[2]).toBe(targets[0]);expect(document.getParagraph('paragraph-one')!.getText()).toBe('One');+ expect(document.getParagraph('paragraph-two')!.getText()).toBe('Two');+ subscription.unsubscribe();});it('uses section and paragraph ids as hierarchical edit boundaries', async () => {@@ -194,12 +205,22 @@ describe('DocPermissionController', () => {it('accepts collaboration mutations despite local edit permission', async () => {await document.getPermission().setReadOnly();+ const errors: string[] = [];+ const subscription = get(ErrorService).error$.subscribe((error) => errors.push(error.code ?? ''));+ expect(get(ICommandService).syncExecuteCommand(DocsRenameMutation.id, {+ unitId: document.getId(),+ name: 'Blocked local name',+ })).toBe(false);+ expect(errors).toEqual(['PERMISSION_DENIED']);+ errors.length = 0;await expect(get(ICommandService).executeCommand(DocsRenameMutation.id, {unitId: document.getId(),name: 'Remote name',}, { fromCollab: true })).resolves.toBe(true);expect(document.getName()).toBe('Remote name');+ expect(errors).toEqual([]);+ subscription.unsubscribe();});it('applies incoming changesets without creating local Undo history', async () => {diff --git a/packages/docs/src/controllers/doc-permission.controller.ts b/packages/docs/src/controllers/doc-permission.controller.tsindex 9a505f8e59..1060a5a72e 100644--- a/packages/docs/src/controllers/doc-permission.controller.ts+++ b/packages/docs/src/controllers/doc-permission.controller.ts@@ -21,8 +21,12 @@ import type {IUpdateTextCommandParams,} from '../commands/commands/core-editing.command';import type { ICreateHeaderFooterCommandParams } from '../commands/commands/create-header-footer.command';-import type { ISetSectionHeaderFooterLinkCommandParams } from '../commands/commands/set-section-header-footer-link.command';-import type { IUpdateDocumentParagraphStyleCommandParams } from '../commands/commands/update-document-paragraph-style.command';+import type {+ ISetSectionHeaderFooterLinkCommandParams,+} from '../commands/commands/set-section-header-footer-link.command';+import type {+ IUpdateDocumentParagraphStyleCommandParams,+} from '../commands/commands/update-document-paragraph-style.command';import type {IDeleteDocumentSectionBreakCommandParams,IInsertDocumentColumnBreakCommandParams,@@ -34,12 +38,16 @@ import {CustomCommandExecutionError,DeleteDirection,Disposable,+ ErrorService,ICommandService,+ Inject,+ Injector,IPermissionService,IUniverInstanceService,+ ObjectPermissionService,UniverInstanceType,} from '@univerjs/core';-import { UnitAction } from '@univerjs/protocol';+import { UnitAction, UnitObject } from '@univerjs/protocol';import { DeleteTextCommand, InsertTextCommand, UpdateTextCommand } from '../commands/commands/core-editing.command';import { CreateHeaderFooterCommand } from '../commands/commands/create-header-footer.command';import { SetDocumentPermissionCommand } from '../commands/commands/set-document-permission.command';@@ -86,6 +94,7 @@ const DERIVED_DOCUMENT_MUTATION_IDS = new Set([export class DocPermissionController extends Disposable {constructor(+ @Inject(Injector) private readonly _injector: Injector,@ICommandService private readonly _commandService: ICommandService,@IPermissionService private readonly _permissionService: IPermissionService,@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService@@ -101,10 +110,13 @@ export class DocPermissionController extends Disposable {}));this.disposeWithMe(this._univerInstanceService.getTypeOfUnitDisposed$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)- .subscribe((unit) => clearDocumentPermissionValuesForUnit(- this._permissionService,- unit.getUnitId()- )));+ .subscribe((unit) => {+ this._injector.get(ObjectPermissionService).clearUnit(unit.getUnitId());+ clearDocumentPermissionValuesForUnit(+ this._permissionService,+ unit.getUnitId()+ );+ }));}private _registerUnitPermissionPoints(unitId: string): void {@@ -114,6 +126,7 @@ export class DocPermissionController extends Disposable {this._permissionService.addPermissionPoint(point);}});+ this._injector.get(ObjectPermissionService).initializeUnit({ unitId, objectId: unitId, objectType: UnitObject.Document });}private _check(commandInfo: Readonly<ICommandInfo>, options?: IExecutionOptions): void {@@ -129,6 +142,7 @@ export class DocPermissionController extends Disposable {}if (unitAction) {if (!getDocumentPermissionValue(this._permissionService, unitId, unitId, unitAction)) {+ this._injector.get(ErrorService).emitPermissionDenied(unitId);throw new CustomCommandExecutionError(`Document ${UnitAction[unitAction]} permission denied.`);}return;@@ -145,6 +159,7 @@ export class DocPermissionController extends Disposable {return;}if (!canEditDocumentTargets(this._permissionService, unitId, targetObjectIds)) {+ this._injector.get(ErrorService).emitPermissionDenied(unitId, targetObjectIds);throw new CustomCommandExecutionError('Document edit permission denied.');}}diff --git a/packages/docs/src/facade/__tests__/f-document.spec.ts b/packages/docs/src/facade/__tests__/f-document.spec.tsindex 75610ca4f0..59ada7a319 100644--- a/packages/docs/src/facade/__tests__/f-document.spec.ts+++ b/packages/docs/src/facade/__tests__/f-document.spec.ts@@ -16,7 +16,20 @@import type { IDocumentData, Univer } from '@univerjs/core';import type { FDocument } from '../f-document';-import { BlockType, ColumnSeparatorType, DataStreamTreeTokenType, DocumentFlavor, DrawingTypeEnum, ICommandService, IResourceManagerService, IUndoRedoService, PageOrientType, PositionedObjectLayoutType, SectionType, UniverInstanceType } from '@univerjs/core';+import {+ BlockType,+ ColumnSeparatorType,+ DataStreamTreeTokenType,+ DocumentFlavor,+ DrawingTypeEnum,+ ICommandService,+ IResourceManagerService,+ IUndoRedoService,+ PageOrientType,+ PositionedObjectLayoutType,+ SectionType,+ UniverInstanceType,+} from '@univerjs/core';import { DocSelectionManagerService, InsertTextCommand } from '@univerjs/docs';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { createDocumentData, createSimpleDocument, createTestBed } from './create-test-bed';@@ -99,7 +112,8 @@ describe('FDocument', () => {parseJson: (bytes: string) => JSON.parse(bytes),});- expect(document.save().resources).toEqual([+ const resources = document.save().resources ?? [];+ expect(resources.filter((resource) => resource.name === 'DOC_TEST_RESOURCE_PLUGIN')).toEqual([{name: 'DOC_TEST_RESOURCE_PLUGIN',data: '{"value":1}',diff --git a/packages/docs/src/index.ts b/packages/docs/src/index.tsindex 7b384062c9..5d22fbed55 100644--- a/packages/docs/src/index.ts+++ b/packages/docs/src/index.ts@@ -42,6 +42,7 @@ export { DeleteDocumentSectionBreakCommand, InsertDocumentColumnBreakCommand, Inexport type { IDeleteDocumentSectionBreakCommandParams, IDocumentSectionConfig, IDocumentSectionUpdate, IInsertDocumentColumnBreakCommandParams, IInsertDocumentSectionBreakCommandParams, IUpdateDocumentSectionCommandParams } from './commands/commands/update-document-section.command';export { DocHistoryAction, RichTextEditingMutation, transformDocumentTextRanges } from './commands/mutations/core-editing.mutation';export type { IRichTextEditingMutationParams } from './commands/mutations/core-editing.mutation';+export { SetDocumentPermissionRuleMutation } from './commands/mutations/set-document-permission-rule.mutation';export { SetTextSelectionsOperation } from './commands/operations/text-selection.operation';export type { ISetTextSelectionsOperationParams } from './commands/operations/text-selection.operation';export type { IUniverDocsConfig } from './config/config';@@ -128,6 +129,7 @@ export type {export {canEditDocumentTargets,createDocumentPermissionPoint,+ DOCUMENT_UNIT_PERMISSION_ACTIONS,getDocumentEntityPermissionObjectId,getDocumentParagraphPermissionObjectId,getDocumentPermissionValue,diff --git a/packages/docs/src/layout-worker/__tests__/worker-runtime.spec.ts b/packages/docs/src/layout-worker/__tests__/worker.spec.tssimilarity index 97%rename from packages/docs/src/layout-worker/__tests__/worker-runtime.spec.tsrename to packages/docs/src/layout-worker/__tests__/worker.spec.tsindex a36a12e8cb..dac5601aad 100644--- a/packages/docs/src/layout-worker/__tests__/worker-runtime.spec.ts+++ b/packages/docs/src/layout-worker/__tests__/worker.spec.ts@@ -241,18 +241,20 @@ describe('DocsLayoutWorkerRuntime', () => {let result = start.step;const publications = [result.publication];- for (let step = 0; step < 1_000 && !result.progress.complete; step++) {- result = await runtime.stepLayout({- ...mountIdentity,- unitId,- mountId: 'mount-1',- generation: start.step.progress.generation,- budgetMs: 0,- });- publications.push(result.publication);- }-- expect(result.progress.complete).toBe(true);+ // Hyphenation patterns load asynchronously; slice count is not a loading deadline.+ await expect.poll(async () => {+ if (!result.progress.complete) {+ result = await runtime.stepLayout({+ ...mountIdentity,+ unitId,+ mountId: 'mount-1',+ generation: start.step.progress.generation,+ budgetMs: 0,+ });+ publications.push(result.publication);+ }+ return result.progress.complete;+ }, { timeout: 5_000, interval: 5 }).toBe(true);expect(result.modelRevision).toBe(1);expect(publications.flatMap((publication) =>publication?.kind === 'page' ? publication.pages : []diff --git a/packages/docs/src/plugin.ts b/packages/docs/src/plugin.tsindex 30313fcfa0..541fb34ffd 100644--- a/packages/docs/src/plugin.ts+++ b/packages/docs/src/plugin.ts@@ -22,19 +22,29 @@ import {Inject,Injector,merge,+ ObjectPermissionService,Plugin,} from '@univerjs/core';+import { UnitObject } from '@univerjs/protocol';import pkg from '../package.json';import { DeleteTextCommand, InsertTextCommand, UpdateTextCommand } from './commands/commands/core-editing.command';import { CreateHeaderFooterCommand } from './commands/commands/create-header-footer.command';-import { SetDocumentDefaultParagraphStyleCommand } from './commands/commands/set-document-default-paragraph-style.command';+import {+ SetDocumentDefaultParagraphStyleCommand,+} from './commands/commands/set-document-default-paragraph-style.command';import { SetDocumentNameCommand } from './commands/commands/set-document-name.command';import { SetDocumentPermissionCommand } from './commands/commands/set-document-permission.command';import { SetSectionHeaderFooterLinkCommand } from './commands/commands/set-section-header-footer-link.command';import { UpdateDocumentParagraphStyleCommand } from './commands/commands/update-document-paragraph-style.command';-import { DeleteDocumentSectionBreakCommand, InsertDocumentColumnBreakCommand, InsertDocumentSectionBreakCommand, UpdateDocumentSectionCommand } from './commands/commands/update-document-section.command';+import {+ DeleteDocumentSectionBreakCommand,+ InsertDocumentColumnBreakCommand,+ InsertDocumentSectionBreakCommand,+ UpdateDocumentSectionCommand,+} from './commands/commands/update-document-section.command';import { RichTextEditingMutation } from './commands/mutations/core-editing.mutation';import { DocsRenameMutation } from './commands/mutations/docs-rename.mutation';+import { SetDocumentPermissionRuleMutation } from './commands/mutations/set-document-permission-rule.mutation';import { SetTextSelectionsOperation } from './commands/operations/text-selection.operation';import { defaultPluginConfig, DOCS_PLUGIN_CONFIG_KEY } from './config/config';import { DocCustomRangeController } from './controllers/custom-range.controller';@@ -46,6 +56,7 @@ import { DocSelectionManagerService } from './services/doc-selection-manager.serimport { DocStateChangeManagerService } from './services/doc-state-change-manager.service';import { DocStateEmitService } from './services/doc-state-emit.service';import { DocTextResolverService } from './services/doc-text-resolver.service';+import { DocumentPermissionRuleModel } from './services/permission/document-permission-rule.model';export class UniverDocsPlugin extends Plugin {static override pluginName = 'DOCS_PLUGIN';@@ -70,6 +81,13 @@ export class UniverDocsPlugin extends Plugin {}override onStarting(): void {+ this._injector.add([DocumentPermissionRuleModel]);+ this.disposeWithMe(this._injector.get(ICommandService).registerCommand(SetDocumentPermissionRuleMutation));+ this.disposeWithMe(this._injector.get(ObjectPermissionService).registerRuleModel(+ UnitObject.Document,+ this._injector.get(DocumentPermissionRuleModel),+ SetDocumentPermissionRuleMutation.id+ ));this._initializeDependencies();this._initializeCommands();}diff --git a/packages/docs/src/services/permission/document-permission-rule.model.ts b/packages/docs/src/services/permission/document-permission-rule.model.tsnew file mode 100644index 0000000000..a4a2359dbc--- /dev/null+++ b/packages/docs/src/services/permission/document-permission-rule.model.ts@@ -0,0 +1,28 @@+/**+ * 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 { IResourceManagerService, ObjectPermissionRuleModel, UniverInstanceType } from '@univerjs/core';+import { UnitObject } from '@univerjs/protocol';++export class DocumentPermissionRuleModel extends ObjectPermissionRuleModel {+ constructor(@IResourceManagerService resources: IResourceManagerService) {+ super(resources, 'DOC_OBJECT_PERMISSION_PLUGIN', UniverInstanceType.UNIVER_DOC, [+ UnitObject.DocumentSection,+ UnitObject.DocumentParagraph,+ UnitObject.DocumentEntity,+ ]);+ }+}diff --git a/packages/drawing-ui/src/locale/ar-SA.ts b/packages/drawing-ui/src/locale/ar-SA.tsindex 5690430812..7f3bf56565 100644--- a/packages/drawing-ui/src/locale/ar-SA.ts+++ b/packages/drawing-ui/src/locale/ar-SA.ts@@ -22,10 +22,12 @@ const locale: typeof enUS = {error: 'لا يمكن قص الكائنات غير الصورية.',},objectListPanel: {- title: 'الكائنات',+ title: 'الطبقات',empty: 'لا توجد كائنات',showAll: 'إظهار الكل',hideAll: 'إخفاء الكل',+ lockAll: 'قفل الكل',+ unlockAll: 'إلغاء قفل الكل',moveForward: 'إحضار للأمام',moveBackward: 'إرسال للخلف',close: 'إغلاق',@@ -33,6 +35,8 @@ const locale: typeof enUS = {hide: 'إخفاء',lock: 'قفل',unlock: 'إلغاء القفل',+ lockHint: 'قفل لمنع التحديد غير المقصود',+ unlockHint: 'مقفل. انقر لإلغاء القفل',name: 'الاسم',nameInput: 'اسم الكائن',description: 'الوصف',diff --git a/packages/drawing-ui/src/locale/ca-ES.ts b/packages/drawing-ui/src/locale/ca-ES.tsindex 7e8b950512..e816dd1913 100644--- a/packages/drawing-ui/src/locale/ca-ES.ts+++ b/packages/drawing-ui/src/locale/ca-ES.ts@@ -22,10 +22,12 @@ const locale: typeof enUS = {error: 'No es poden retallar objectes que no siguin imatges.',},objectListPanel: {- title: 'Objectes',+ title: 'Capes',empty: 'Sense objectes',showAll: 'Mostra-ho tot',hideAll: 'Amaga-ho tot',+ lockAll: 'Bloqueja-ho tot',+ unlockAll: 'Desbloqueja-ho tot',moveForward: 'Porta endavant',moveBackward: 'Envia enrere',close: 'Tanca',@@ -33,6 +35,8 @@ const locale: typeof enUS = {hide: 'Amaga',lock: 'Bloqueja',unlock: 'Desbloqueja',+ lockHint: 'Bloqueja per evitar seleccions accidentals',+ unlockHint: 'Bloquejat. Fes clic per desbloquejar',name: 'Nom',nameInput: 'Nom de l\'objecte',description: 'Descripcio',diff --git a/packages/drawing-ui/src/locale/de-DE.ts b/packages/drawing-ui/src/locale/de-DE.tsindex 064f1a90d8..d83f1ad174 100644--- a/packages/drawing-ui/src/locale/de-DE.ts+++ b/packages/drawing-ui/src/locale/de-DE.ts@@ -22,10 +22,12 @@ const locale: typeof enUS = {error: 'Nicht-Bildobjekte können nicht zugeschnitten werden.',},objectListPanel: {- title: 'Objekte',+ title: 'Ebenen',empty: 'Keine Objekte',showAll: 'Alle anzeigen',hideAll: 'Alle ausblenden',+ lockAll: 'Alle sperren',+ unlockAll: 'Alle entsperren',moveForward: 'Eine Ebene nach vorne',moveBackward: 'Eine Ebene nach hinten',close: 'Schliessen',@@ -33,6 +35,8 @@ const locale: typeof enUS = {hide: 'Ausblenden',lock: 'Sperren',unlock: 'Entsperren',+ lockHint: 'Sperren, um versehentliches Auswählen zu verhindern',+ unlockHint: 'Gesperrt. Klicken zum Entsperren',name: 'Name',nameInput: 'Objektname',description: 'Beschreibung',diff --git a/packages/drawing-ui/src/locale/en-US.ts b/packages/drawing-ui/src/locale/en-US.tsindex ba32192e05..23e26ff6a7 100644--- a/packages/drawing-ui/src/locale/en-US.ts+++ b/packages/drawing-ui/src/locale/en-US.ts@@ -20,10 +20,12 @@ const locale = {error: 'Cannot crop non-image objects.',},objectListPanel: {- title: 'Object list',+ title: 'Layers',empty: 'No objects',showAll: 'Show all',hideAll: 'Hide all',+ lockAll: 'Lock all',+ unlockAll: 'Unlock all',moveForward: 'Bring forward',moveBackward: 'Send backward',close: 'Close',@@ -31,6 +33,8 @@ const locale = {hide: 'Hide',lock: 'Lock',unlock: 'Unlock',+ lockHint: 'Lock to prevent accidental selection',+ unlockHint: 'Locked. Click to unlock',name: 'Name',nameInput: 'Object name',description: 'Description',diff --git a/packages/drawing-ui/src/locale/es-ES.ts b/packages/drawing-ui/src/locale/es-ES.tsindex f6b566fd03..678af6504a 100644--- a/packages/drawing-ui/src/locale/es-ES.ts+++ b/packages/drawing-ui/src/locale/es-ES.ts@@ -22,10 +22,12 @@ const locale: typeof enUS = {error: 'No se pueden recortar objetos que no sean imágenes.',},objectListPanel: {- title: 'Objetos',+ title: 'Capas',empty: 'Sin objetos',showAll: 'Mostrar todo',hideAll: 'Ocultar todo',+ lockAll: 'Bloquear todo',+ unlockAll: 'Desbloquear todo',moveForward: 'Traer hacia delante',moveBackward: 'Enviar hacia atras',close: 'Cerrar',@@ -33,6 +35,8 @@ const locale: typeof enUS = {hide: 'Ocultar',lock: 'Bloquear',unlock: 'Desbloquear',+ lockHint: 'Bloquear para evitar selecciones accidentales',+ unlockHint: 'Bloqueado. Haz clic para desbloquear',name: 'Nombre',nameInput: 'Nombre del objeto',description: 'Descripcion',diff --git a/packages/drawing-ui/src/locale/fa-IR.ts b/packages/drawing-ui/src/locale/fa-IR.tsindex a1ac39cd0a..d7c10316df 100644--- a/packages/drawing-ui/src/locale/fa-IR.ts+++ b/packages/drawing-ui/src/locale/fa-IR.ts@@ -22,10 +22,12 @@ const locale: typeof enUS = {error: 'کراپ کردن اشیاء غیرتصویری امکانپذیر نیست.',},objectListPanel: {- title: 'اشیا',+ title: 'لایه\u200Cها',empty: 'هیچ شیئی وجود ندارد',showAll: 'نمایش همه',hideAll: 'پنهان کردن همه',+ lockAll: 'قفل کردن همه',+ unlockAll: 'باز کردن قفل همه',moveForward: 'آوردن به جلو',moveBackward: 'فرستادن به عقب',close: 'بستن',@@ -33,6 +35,8 @@ const locale: typeof enUS = {hide: 'پنهان کردن',lock: 'قفل',unlock: 'باز کردن قفل',+ lockHint: 'قفل کردن برای جلوگیری از انتخاب تصادفی',+ unlockHint: 'قفل شده است. برای باز کردن قفل کلیک کنید',name: 'نام',nameInput: 'نام شیء',description: 'توضیحات',diff --git a/packages/drawing-ui/src/locale/fr-FR.ts b/packages/drawing-ui/src/locale/fr-FR.tsindex 86bb462be3..246828913f 100644--- a/packages/drawing-ui/src/locale/fr-FR.ts+++ b/packages/drawing-ui/src/locale/fr-FR.ts@@ -22,10 +22,12 @@ const locale: typeof enUS = {error: 'Impossible de rogner des objets non image.',},objectListPanel: {- title: 'Objets',+ title: 'Calques',empty: 'Aucun objet',showAll: 'Tout afficher',hideAll: 'Tout masquer',+ lockAll: 'Tout verrouiller',+ unlockAll: 'Tout déverrouiller',moveForward: 'Avancer',moveBackward: 'Reculer',close: 'Fermer',@@ -33,6 +35,8 @@ const locale: typeof enUS = {hide: 'Masquer',lock: 'Verrouiller',unlock: 'Deverrouiller',+ lockHint: 'Verrouiller pour éviter une sélection accidentelle',+ unlockHint: 'Verrouillé. Cliquer pour déverrouiller',name: 'Nom',nameInput: 'Nom de l\'objet',description: 'Description',diff --git a/packages/drawing-ui/src/locale/id-ID.ts b/packages/drawing-ui/src/locale/id-ID.tsindex 02e42432da..e60827bc6f 100644--- a/packages/drawing-ui/src/locale/id-ID.ts+++ b/packages/drawing-ui/src/locale/id-ID.ts@@ -22,10 +22,12 @@ const locale: typeof enUS = {error: 'Tidak dapat memangkas objek non-gambar.',},objectListPanel: {- title: 'Objek',+ title: 'Lapisan',empty: 'Tidak ada objek',showAll: 'Tampilkan semua',hideAll: 'Sembunyikan semua',+ lockAll: 'Kunci semua',+ unlockAll: 'Buka kunci semua',moveForward: 'Bawa ke depan',moveBackward: 'Kirim ke belakang',close: 'Tutup',@@ -33,6 +35,8 @@ const locale: typeof enUS = {hide: 'Sembunyikan',lock: 'Kunci',unlock: 'Buka kunci',+ lockHint: 'Kunci untuk mencegah pemilihan tidak sengaja',+ unlockHint: 'Terkunci. Klik untuk membuka kunci',name: 'Nama',nameInput: 'Nama objek',description: 'Deskripsi',diff --git a/packages/drawing-ui/src/locale/it-IT.ts b/packages/drawing-ui/src/locale/it-IT.tsindex 47bea939ec..95e3241217 100644--- a/packages/drawing-ui/src/locale/it-IT.ts+++ b/packages/drawing-ui/src/locale/it-IT.ts@@ -22,10 +22,12 @@ const locale: typeof enUS = {error: 'Impossibile ritagliare oggetti non immagine.',},objectListPanel: {- title: 'Oggetti',+ title: 'Livelli',empty: 'Nessun oggetto',showAll: 'Mostra tutto',hideAll: 'Nascondi tutto',+ lockAll: 'Blocca tutto',+ unlockAll: 'Sblocca tutto',moveForward: 'Porta avanti',moveBackward: 'Manda indietro',close: 'Chiudi',@@ -33,6 +35,8 @@ const locale: typeof enUS = {hide: 'Nascondi',lock: 'Blocca',unlock: 'Sblocca',+ lockHint: 'Blocca per evitare selezioni accidentali',+ unlockHint: 'Bloccato. Fai clic per sbloccare',name: 'Nome',nameInput: 'Nome oggetto',description: 'Descrizione',diff --git a/packages/drawing-ui/src/locale/ja-JP.ts b/packages/drawing-ui/src/locale/ja-JP.tsindex 1e90c44747..3f8f08ff83 100644--- a/packages/drawing-ui/src/locale/ja-JP.ts+++ b/packages/drawing-ui/src/locale/ja-JP.ts@@ -22,10 +22,12 @@ const locale: typeof enUS = {error: '画像以外のオブジェクトはトリミングできません。',},objectListPanel: {- title: 'オブジェクト',+ title: 'レイヤー',empty: 'オブジェクトがありません',showAll: 'すべて表示',hideAll: 'すべて非表示',+ lockAll: 'すべてロック',+ unlockAll: 'すべてロック解除',moveForward: '前面へ移動',moveBackward: '背面へ移動',close: '閉じる',@@ -33,6 +35,8 @@ const locale: typeof enUS = {hide: '非表示',lock: 'ロック',unlock: 'ロック解除',+ lockHint: '誤選択を防ぐためにロック',+ unlockHint: 'ロック済み。クリックして解除',name: '名前',nameInput: 'オブジェクト名',description: '説明',diff --git a/packages/drawing-ui/src/locale/ko-KR.ts b/packages/drawing-ui/src/locale/ko-KR.tsindex e0a85b6def..39024c0eb6 100644--- a/packages/drawing-ui/src/locale/ko-KR.ts+++ b/packages/drawing-ui/src/locale/ko-KR.ts@@ -22,10 +22,12 @@ const locale: typeof enUS = {error: '이미지가 아닌 객체는 자를 수 없습니다.',},objectListPanel: {- title: '개체',+ title: '레이어',empty: '개체 없음',showAll: '모두 표시',hideAll: '모두 숨기기',+ lockAll: '모두 잠금',+ unlockAll: '모두 잠금 해제',moveForward: '앞으로 가져오기',moveBackward: '뒤로 보내기',close: '닫기',@@ -33,6 +35,8 @@ const locale: typeof enUS = {hide: '숨기기',lock: '잠금',unlock: '잠금 해제',+ lockHint: '실수로 선택하지 않도록 잠금',+ unlockHint: '잠김. 클릭하여 잠금 해제',name: '이름',nameInput: '개체 이름',description: '설명',diff --git a/packages/drawing-ui/src/locale/pl-PL.ts b/packages/drawing-ui/src/locale/pl-PL.tsindex 49bd9bd357..2b4d3d02e5 100644--- a/packages/drawing-ui/src/locale/pl-PL.ts+++ b/packages/drawing-ui/src/locale/pl-PL.ts@@ -22,10 +22,12 @@ const locale: typeof enUS = {error: 'Nie można przyciąć obiektów innych niż obraz.',},objectListPanel: {- title: 'Obiekty',+ title: 'Warstwy',empty: 'Brak obiektow',showAll: 'Pokaz wszystko',hideAll: 'Ukryj wszystko',+ lockAll: 'Zablokuj wszystko',+ unlockAll: 'Odblokuj wszystko',moveForward: 'Przesun do przodu',moveBackward: 'Przesun do tylu',close: 'Zamknij',@@ -33,6 +35,8 @@ const locale: typeof enUS = {hide: 'Ukryj',lock: 'Zablokuj',unlock: 'Odblokuj',+ lockHint: 'Zablokuj, aby zapobiec przypadkowemu zaznaczeniu',+ unlockHint: 'Zablokowano. Kliknij, aby odblokować',name: 'Nazwa',nameInput: 'Nazwa obiektu',description: 'Opis',diff --git a/packages/drawing-ui/src/locale/pt-BR.ts b/packages/drawing-ui/src/locale/pt-BR.tsindex c5e52f2ad8..8c3cc718fb 100644--- a/packages/drawing-ui/src/locale/pt-BR.ts+++ b/packages/drawing-ui/src/locale/pt-BR.ts@@ -22,10 +22,12 @@ const locale: typeof enUS = {error: 'Não é possível cortar objetos que não são imagens.',},objectListPanel: {- title: 'Objetos',+ title: 'Camadas',empty: 'Nenhum objeto',showAll: 'Mostrar tudo',hideAll: 'Ocultar tudo',+ lockAll: 'Bloquear tudo',+ unlockAll: 'Desbloquear tudo',moveForward: 'Trazer para frente',moveBackward: 'Enviar para tras',close: 'Fechar',@@ -33,6 +35,8 @@ const locale: typeof enUS = {hide: 'Ocultar',lock: 'Bloquear',unlock: 'Desbloquear',+ lockHint: 'Bloquear para evitar seleção acidental',+ unlockHint: 'Bloqueado. Clique para desbloquear',name: 'Nome',nameInput: 'Nome do objeto',description: 'Descricao',diff --git a/packages/drawing-ui/src/locale/ru-RU.ts b/packages/drawing-ui/src/locale/ru-RU.tsindex 9ce929c9f2..dcb91b2fca 100644--- a/packages/drawing-ui/src/locale/ru-RU.ts+++ b/packages/drawing-ui/src/locale/ru-RU.ts@@ -22,10 +22,12 @@ const locale: typeof enUS = {error: 'Невозможно обрезать не изображения.',},objectListPanel: {- title: 'Объекты',+ title: 'Слои',empty: 'Нет объектов',showAll: 'Показать все',hideAll: 'Скрыть все',+ lockAll: 'Заблокировать всё',+ unlockAll: 'Разблокировать всё',moveForward: 'Переместить вперед',moveBackward: 'Переместить назад',close: 'Закрыть',@@ -33,6 +35,8 @@ const locale: typeof enUS = {hide: 'Скрыть',lock: 'Заблокировать',unlock: 'Разблокировать',+ lockHint: 'Заблокировать для защиты от случайного выбора',+ unlockHint: 'Заблокировано. Нажмите, чтобы разблокировать',name: 'Имя',nameInput: 'Имя объекта',description: 'Описание',diff --git a/packages/drawing-ui/src/locale/sk-SK.ts b/packages/drawing-ui/src/locale/sk-SK.tsindex 7b3ac9487b..336c83a76b 100644--- a/packages/drawing-ui/src/locale/sk-SK.ts+++ b/packages/drawing-ui/src/locale/sk-SK.ts@@ -22,10 +22,12 @@ const locale: typeof enUS = {error: 'Nedá sa orezať neobrázkový objekt.',},objectListPanel: {- title: 'Objekty',+ title: 'Vrstvy',empty: 'Ziadne objekty',showAll: 'Zobrazit vsetko',hideAll: 'Skryt vsetko',+ lockAll: 'Zamknúť všetko',+ unlockAll: 'Odomknúť všetko',moveForward: 'Presunut dopredu',moveBackward: 'Presunut dozadu',close: 'Zavriet',@@ -33,6 +35,8 @@ const locale: typeof enUS = {hide: 'Skryt',lock: 'Zamknut',unlock: 'Odomknut',+ lockHint: 'Zamknúť, aby sa zabránilo náhodnému výberu',+ unlockHint: 'Zamknuté. Kliknutím odomknete',name: 'Nazov',nameInput: 'Nazov objektu',description: 'Popis',diff --git a/packages/drawing-ui/src/locale/vi-VN.ts b/packages/drawing-ui/src/locale/vi-VN.tsindex 0ce028cd8a..469a2c4b03 100644--- a/packages/drawing-ui/src/locale/vi-VN.ts+++ b/packages/drawing-ui/src/locale/vi-VN.ts@@ -22,10 +22,12 @@ const locale: typeof enUS = {error: 'Không thể cắt phần tử không phải hình ảnh',},objectListPanel: {- title: 'Doi tuong',+ title: 'Lớp',empty: 'Khong co doi tuong',showAll: 'Hien thi tat ca',hideAll: 'An tat ca',+ lockAll: 'Khóa tất cả',+ unlockAll: 'Mở khóa tất cả',moveForward: 'Dua len truoc',moveBackward: 'Dua ra sau',close: 'Dong',@@ -33,6 +35,8 @@ const locale: typeof enUS = {hide: 'An',lock: 'Khoa',unlock: 'Mo khoa',+ lockHint: 'Khóa để tránh chọn nhầm',+ unlockHint: 'Đã khóa. Nhấp để mở khóa',name: 'Ten',nameInput: 'Ten doi tuong',description: 'Mo ta',diff --git a/packages/drawing-ui/src/locale/zh-CN.ts b/packages/drawing-ui/src/locale/zh-CN.tsindex e68993d9e8..105a489c83 100644--- a/packages/drawing-ui/src/locale/zh-CN.ts+++ b/packages/drawing-ui/src/locale/zh-CN.ts@@ -22,10 +22,12 @@ const locale: typeof enUS = {error: '无法裁剪非图片元素',},objectListPanel: {- title: '对象',+ title: '图层',empty: '暂无对象',showAll: '全部显示',hideAll: '全部隐藏',+ lockAll: '全部锁定',+ unlockAll: '全部解锁',moveForward: '上移一层',moveBackward: '下移一层',close: '关闭',@@ -33,6 +35,8 @@ const locale: typeof enUS = {hide: '隐藏',lock: '锁定',unlock: '解锁',+ lockHint: '锁定,防止误选',+ unlockHint: '已锁定,点击解锁',name: '名称',nameInput: '对象名称',description: '描述',diff --git a/packages/drawing-ui/src/locale/zh-HK.ts b/packages/drawing-ui/src/locale/zh-HK.tsindex 14fdf30964..6866a90edd 100644--- a/packages/drawing-ui/src/locale/zh-HK.ts+++ b/packages/drawing-ui/src/locale/zh-HK.ts@@ -22,10 +22,12 @@ const locale: typeof enUS = {error: '無法裁切非圖片元素',},objectListPanel: {- title: '物件',+ title: '圖層',empty: '暫無物件',showAll: '全部顯示',hideAll: '全部隱藏',+ lockAll: '全部鎖定',+ unlockAll: '全部解鎖',moveForward: '上移一層',moveBackward: '下移一層',close: '關閉',@@ -33,6 +35,8 @@ const locale: typeof enUS = {hide: '隱藏',lock: '鎖定',unlock: '解鎖',+ lockHint: '鎖定,防止誤選',+ unlockHint: '已鎖定,點擊解鎖',name: '名稱',nameInput: '物件名稱',description: '描述',diff --git a/packages/drawing-ui/src/locale/zh-TW.ts b/packages/drawing-ui/src/locale/zh-TW.tsindex 9f04a6b882..9f455c159c 100644--- a/packages/drawing-ui/src/locale/zh-TW.ts+++ b/packages/drawing-ui/src/locale/zh-TW.ts@@ -22,10 +22,12 @@ const locale: typeof enUS = {error: '無法裁切非圖片元素',},objectListPanel: {- title: '物件',+ title: '圖層',empty: '暫無物件',showAll: '全部顯示',hideAll: '全部隱藏',+ lockAll: '全部鎖定',+ unlockAll: '全部解鎖',moveForward: '上移一層',moveBackward: '下移一層',close: '關閉',@@ -33,6 +35,8 @@ const locale: typeof enUS = {hide: '隱藏',lock: '鎖定',unlock: '解鎖',+ lockHint: '鎖定,防止誤選',+ unlockHint: '已鎖定,點擊解鎖',name: '名稱',nameInput: '物件名稱',description: '描述',diff --git a/packages/drawing-ui/src/views/object-list-panel/ObjectListPanelBase.tsx b/packages/drawing-ui/src/views/object-list-panel/ObjectListPanelBase.tsxindex 8824df78db..6b9318fef5 100644--- a/packages/drawing-ui/src/views/object-list-panel/ObjectListPanelBase.tsx+++ b/packages/drawing-ui/src/views/object-list-panel/ObjectListPanelBase.tsx@@ -14,8 +14,8 @@* limitations under the License.*/-import type { DragEvent, FocusEvent, KeyboardEvent, MouseEvent } from 'react';-import { Button, clsx, Input } from '@univerjs/design';+import type { DragEvent, FocusEvent, KeyboardEvent, MouseEvent, ReactNode } from 'react';+import { Button, clsx, Input, StateIconButton } from '@univerjs/design';import {ArrowDownIcon,ArrowUpIcon,@@ -65,6 +65,8 @@ export interface IObjectListPanelLabels {empty: string;showAll: string;hideAll: string;+ lockAll?: string;+ unlockAll?: string;moveForward: string;moveBackward: string;close: string;@@ -72,6 +74,8 @@ export interface IObjectListPanelLabels {hide: string;lock: string;unlock: string;+ lockHint?: string;+ unlockHint?: string;name: string;nameInput: string;description: string;@@ -115,6 +119,8 @@ const objectListPanelLabelKeys: Record<keyof IObjectListPanelLabels, string> = {empty: 'drawing-ui.objectListPanel.empty',showAll: 'drawing-ui.objectListPanel.showAll',hideAll: 'drawing-ui.objectListPanel.hideAll',+ lockAll: 'drawing-ui.objectListPanel.lockAll',+ unlockAll: 'drawing-ui.objectListPanel.unlockAll',moveForward: 'drawing-ui.objectListPanel.moveForward',moveBackward: 'drawing-ui.objectListPanel.moveBackward',close: 'drawing-ui.objectListPanel.close',@@ -122,6 +128,8 @@ const objectListPanelLabelKeys: Record<keyof IObjectListPanelLabels, string> = {hide: 'drawing-ui.objectListPanel.hide',lock: 'drawing-ui.objectListPanel.lock',unlock: 'drawing-ui.objectListPanel.unlock',+ lockHint: 'drawing-ui.objectListPanel.lockHint',+ unlockHint: 'drawing-ui.objectListPanel.unlockHint',name: 'drawing-ui.objectListPanel.name',nameInput: 'drawing-ui.objectListPanel.nameInput',description: 'drawing-ui.objectListPanel.description',@@ -154,7 +162,9 @@ export interface IObjectListPanelBaseProps {items: IObjectListPanelItem[];selectedIds: string[];allObjectIds?: string[];+ allItems?: Pick<IObjectListPanelItem, 'id' | 'visible' | 'selectable' | 'disabled' | 'capabilities'>[];focusedId?: string | null;+ renderPermissionAction?: (item: IObjectListPanelItem) => ReactNode;labels: IObjectListPanelLabels;showHeader?: boolean;capabilities?: IObjectListPanelCapabilities;@@ -166,6 +176,7 @@ export interface IObjectListPanelBaseProps {onMoveBackward?: (objectId: string) => void;onToggleExpanded?: (objectId: string) => void;onToggleSelectable?: (objectId: string) => void;+ onSetSelectable?: (objectIds: string[], selectable: boolean) => void;onLocate?: (objectId: string) => void;onReorder?: (sourceObjectId: string, targetObjectId: string) => void;}@@ -190,7 +201,7 @@ function normalizeText(value: string): string {function hasCapability(panelCapabilities: IObjectListPanelCapabilities | undefined,- item: IObjectListPanelItem | null | undefined,+ item: Pick<IObjectListPanelItem, 'capabilities'> | null | undefined,key: keyof IObjectListPanelCapabilities,fallback = true): boolean {@@ -202,6 +213,7 @@ export function ObjectListPanelBase(props: IObjectListPanelBaseProps) {items,selectedIds,allObjectIds,+ allItems = items,focusedId,labels,showHeader = true,@@ -214,8 +226,10 @@ export function ObjectListPanelBase(props: IObjectListPanelBaseProps) {onMoveBackward,onToggleExpanded,onToggleSelectable,+ onSetSelectable,onLocate,onReorder,+ renderPermissionAction,} = props;const selectedIdSet = useMemo(() => new Set(selectedIds), [selectedIds]);const [draggingId, setDraggingId] = useState<string | null>(null);@@ -265,7 +279,17 @@ export function ObjectListPanelBase(props: IObjectListPanelBaseProps) {return [...sectionMap.values()].sort((a, b) => (sectionOrder.get(a.id) ?? 3) - (sectionOrder.get(b.id) ?? 3));}, [visibleItems]);const showSectionHeaders = visibleItemSections.length > 1 || visibleItemSections.some((section) => section.id === OBJECT_LIST_FLOATING_SECTION_ID);- const allIds = useMemo(() => allObjectIds ?? items.map((item) => item.id), [allObjectIds, items]);+ const bulkItems = useMemo(() => {+ if (!allObjectIds) {+ return allItems;+ }+ const itemMap = new Map(allItems.map((item) => [item.id, item]));+ return allObjectIds.map((id) => itemMap.get(id) ?? { id, visible: true });+ }, [allObjectIds, allItems]);+ const visibilityItems = bulkItems.filter((item) => !item.disabled && hasCapability(capabilities, item, 'visible'));+ const selectableItems = bulkItems.filter((item) => !item.disabled && hasCapability(capabilities, item, 'selectable'));+ const allVisible = visibilityItems.length > 0 && visibilityItems.every((item) => item.visible);+ const allLocked = selectableItems.length > 0 && selectableItems.every((item) => item.selectable === false);const selectedIndex = selectedItem ? items.findIndex((item) => item.id === selectedItem.id) : -1;const canMoveForward = !!selectedItem && !!onMoveForward && !selectedItem.disabled && (selectedItem.canMoveForward ?? selectedIndex > 0@@ -343,12 +367,22 @@ export function ObjectListPanelBase(props: IObjectListPanelBaseProps) {<div className="univer-flex univer-min-w-0 univer-items-center univer-justify-between univer-gap-2"><div className="univer-flex univer-min-w-0 univer-gap-2">- <Button size="small" disabled={items.length === 0} onClick={() => onSetVisible(allIds, true)}>- {labels.showAll}- </Button>- <Button size="small" disabled={items.length === 0} onClick={() => onSetVisible(allIds, false)}>- {labels.hideAll}+ <Button+ size="small"+ disabled={visibilityItems.length === 0}+ onClick={() => onSetVisible(visibilityItems.map((item) => item.id), !allVisible)}+ >+ {allVisible ? labels.hideAll : labels.showAll}</Button>+ {onSetSelectable && (+ <Button+ size="small"+ disabled={selectableItems.length === 0}+ onClick={() => onSetSelectable(selectableItems.map((item) => item.id), allLocked)}+ >+ {allLocked ? (labels.unlockAll ?? labels.unlock) : (labels.lockAll ?? labels.lock)}+ </Button>+ )}</div><div className="univer-flex univer-shrink-0 univer-gap-1">{showLocateControl && (@@ -508,6 +542,7 @@ export function ObjectListPanelBase(props: IObjectListPanelBaseProps) {item={item}selected={selectedIdSet.has(item.id)}labels={labels}+ permissionAction={renderPermissionAction?.(item)}showLock={!!onToggleSelectable && hasCapability(capabilities, item, 'selectable')}showName={hasCapability(capabilities, item, 'name')}showVisible={hasCapability(capabilities, item, 'visible')}@@ -542,6 +577,7 @@ export function ObjectListPanelBase(props: IObjectListPanelBaseProps) {}function ObjectListRow(props: {+ permissionAction?: ReactNode;item: IObjectListPanelItem;selected: boolean;labels: IObjectListPanelLabels;@@ -559,7 +595,7 @@ function ObjectListRow(props: {onDragEnd: () => void;onDrop: () => void;}) {- const { item, selected, labels, showLock, showName, showVisible, draggable, dragging, onSelect, onToggleExpanded, onToggleVisible, onToggleSelectable, onCommitName, onDragStart, onDragEnd, onDrop } = props;+ const { permissionAction, item, selected, labels, showLock, showName, showVisible, draggable, dragging, onSelect, onToggleExpanded, onToggleVisible, onToggleSelectable, onCommitName, onDragStart, onDragEnd, onDrop } = props;const [draftName, setDraftName] = useState(item.name);const skipCommitOnBlurRef = useRef(false);const disabled = item.disabled === true;@@ -708,25 +744,29 @@ function ObjectListRow(props: {/>): <span className="univer-min-w-0 univer-flex-1 univer-truncate univer-px-1 univer-text-sm">{item.name}</span>}+ {permissionAction}{showLock && (- <button+ <StateIconButton+ active={locked}+ emphasizeActive+ aria-pressed={locked}type="button"- className={iconButtonClassName}disabled={disabled}- title={locked ? labels.unlock : labels.lock}+ title={locked ? (labels.unlockHint ?? labels.unlock) : (labels.lockHint ?? labels.lock)}aria-label={locked ? labels.unlock : labels.lock}onClick={(event) => {event.stopPropagation();onToggleSelectable();}}>- {locked ? <LockIcon /> : <UnlockIcon />}- </button>+ {locked ? <LockIcon aria-hidden="true" /> : <UnlockIcon aria-hidden="true" />}+ </StateIconButton>)}{showVisible && (- <button+ <StateIconButton+ active={!item.visible}+ aria-pressed={!item.visible}type="button"- className={iconButtonClassName}disabled={disabled}title={item.visible ? labels.hide : labels.show}aria-label={item.visible ? labels.hide : labels.show}@@ -736,7 +776,7 @@ function ObjectListRow(props: {}}>{item.visible ? <EyeIcon /> : <EyelashIcon />}- </button>+ </StateIconButton>)}</div>);diff --git a/packages/drawing-ui/src/views/object-list-panel/__tests__/ObjectListPanelBase.spec.tsx b/packages/drawing-ui/src/views/object-list-panel/__tests__/ObjectListPanelBase.spec.tsxnew file mode 100644index 0000000000..f52a00156e--- /dev/null+++ b/packages/drawing-ui/src/views/object-list-panel/__tests__/ObjectListPanelBase.spec.tsx@@ -0,0 +1,136 @@+/**+ * 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 { ReactElement } from 'react';+import type { Root } from 'react-dom/client';+import type { IObjectListPanelBaseProps, IObjectListPanelItem } from '../ObjectListPanelBase';+import { LocaleService, LocaleType, Univer } from '@univerjs/core';+import { RediContext } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, beforeEach, expect, it } from 'vitest';+import enUS from '../../../locale/en-US';+import { getObjectListPanelLabels, ObjectListPanelBase } from '../ObjectListPanelBase';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++let root: Root;+let container: HTMLDivElement;+let univer: Univer;+let visibilityChanges: Array<{ ids: string[]; visible: boolean }>;+let selectableChanges: Array<{ ids: string[]; selectable: boolean }>;++beforeEach(() => {+ univer = new Univer({ locale: LocaleType.EN_US, locales: { [LocaleType.EN_US]: enUS } });+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ visibilityChanges = [];+ selectableChanges = [];+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+ univer.dispose();+});++function render(element: ReactElement) {+ act(() => root.render(element));+ return { rerender: (next: ReactElement) => act(() => root.render(next)) };+}++function getButton(name: string): HTMLButtonElement {+ const button = Array.from(container.querySelectorAll('button')).find((item) => item.textContent === name);+ if (!button) {+ throw new Error(`Button not found: ${name}`);+ }+ return button;+}++function click(button: HTMLButtonElement): void {+ act(() => button.click());+}++function panel(items: IObjectListPanelItem[], props: Partial<IObjectListPanelBaseProps> = {}) {+ const injector = univer.__getInjector();+ return (+ <RediContext.Provider value={{ injector }}>+ <ObjectListPanelBase+ items={items}+ selectedIds={[]}+ labels={getObjectListPanelLabels(injector.get(LocaleService))}+ onSelect={() => {}}+ onCommitName={() => {}}+ onCommitDescription={() => {}}+ onSetVisible={(ids, visible) => visibilityChanges.push({ ids, visible })}+ onSetSelectable={(ids, selectable) => selectableChanges.push({ ids, selectable })}+ {...props}+ />+ </RediContext.Provider>+ );+}++it('switches both bulk actions from current model state, including external updates', () => {+ const original = [{ id: 'a', name: 'A', visible: true }, { id: 'b', name: 'B', visible: true }];+ const view = render(panel(original));+ click(getButton('Hide all'));+ expect(visibilityChanges).toEqual([{ ids: ['a', 'b'], visible: false }]);+ click(getButton('Lock all'));+ expect(selectableChanges).toEqual([{ ids: ['a', 'b'], selectable: false }]);++ view.rerender(panel(original.map((item) => ({ ...item, visible: false, selectable: false }))));+ click(getButton('Show all'));+ click(getButton('Unlock all'));+ expect(visibilityChanges[1]).toEqual({ ids: ['a', 'b'], visible: true });+ expect(selectableChanges[1]).toEqual({ ids: ['a', 'b'], selectable: true });++ view.rerender(panel(original));+ expect(getButton('Hide all')).toBeTruthy();+ expect(getButton('Lock all')).toBeTruthy();+});++it('includes collapsed children and ignores the search filter when normalizing mixed states', () => {+ const group = { id: 'group', name: 'Group', visible: true, selectable: false, isGroup: true, expanded: false };+ render(panel([group], {+ allItems: [group, { id: 'child', visible: false, selectable: true }],+ }));+ const search = container.querySelector<HTMLInputElement>('input[placeholder="Search objects"]')!;+ act(() => {+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(search, 'unmatched');+ search.dispatchEvent(new Event('input', { bubbles: true }));+ });+ click(getButton('Show all'));+ click(getButton('Lock all'));+ expect(visibilityChanges).toEqual([{ ids: ['group', 'child'], visible: true }]);+ expect(selectableChanges).toEqual([{ ids: ['group', 'child'], selectable: false }]);+});++it('excludes unavailable capabilities and disables actions when no targets exist', () => {+ const items = [+ { id: 'available', name: 'Available', visible: true },+ { id: 'disabled', name: 'Disabled', visible: false, disabled: true },+ { id: 'unsupported', name: 'Unsupported', visible: false, capabilities: { visible: false, selectable: false } },+ ];+ const view = render(panel(items));+ click(getButton('Hide all'));+ click(getButton('Lock all'));+ expect(visibilityChanges).toEqual([{ ids: ['available'], visible: false }]);+ expect(selectableChanges).toEqual([{ ids: ['available'], selectable: false }]);+ view.rerender(panel([]));+ expect((getButton('Show all') as HTMLButtonElement).disabled).toBe(true);+ expect((getButton('Lock all') as HTMLButtonElement).disabled).toBe(true);+});diff --git a/packages/engine-render/src/__tests__/worker-layout.spec.ts b/packages/engine-render/src/__tests__/worker-layout.spec.tsindex add24ee20f..c59c78e672 100644--- a/packages/engine-render/src/__tests__/worker-layout.spec.ts+++ b/packages/engine-render/src/__tests__/worker-layout.spec.ts@@ -1113,7 +1113,7 @@ describe('worker document layout session', () => {sourceModel.dispose();});- it('preserves tables, column groups, drawings, lists, headers and footers across Worker transport', () => {+ it.each([DocumentFlavor.TRADITIONAL, DocumentFlavor.MODERN])('preserves rich elements with bounded deferred snapshots across Worker transport (%s)', (flavor) => {vi.stubGlobal('document', undefined);vi.stubGlobal('OffscreenCanvas', class {getContext() {@@ -1385,7 +1385,7 @@ describe('worker document layout session', () => {},},documentStyle: {- documentFlavor: DocumentFlavor.TRADITIONAL,+ documentFlavor: flavor,pageSize: { width: 280, height: 220 },marginTop: 20,marginBottom: 20,@@ -1420,7 +1420,15 @@ describe('worker document layout session', () => {incrementalProgress = incrementalSkeleton.stepIncrementalLayout(incrementalGeneration, 0);}expect(incrementalProgress.complete).toBe(true);- targetSkeleton.beginExternalLayout({ reason: 'initial' });+ if (flavor === DocumentFlavor.MODERN) {+ targetSkeleton.calculate();+ }+ targetSkeleton.beginExternalLayout({+ reason: 'initial',+ protectedRange: flavor === DocumentFlavor.MODERN+ ? { mode: 'continuous', startOffset: 0, endOffset: dataStream.length }+ : undefined,+ });const generation = session.start({ reason: 'initial' });const publicationPayloads: string[] = [];@@ -1429,6 +1437,21 @@ describe('worker document layout session', () => {if (result.publication != null) {publicationPayloads.push(JSON.stringify(result.publication));targetSkeleton.applyLayoutPublication(structuredClone(result.publication), result.progress);+ if (result.publication.kind === 'block' && !result.progress.complete) {+ const deferred = (targetSkeleton as unknown as {+ _externalProtectedContinuousLayout: {+ pendingPublications: Array<Extract<NonNullable<LayoutPublication>, { kind: 'block' }>>;+ };+ })._externalProtectedContinuousLayout.pendingPublications;+ // Repeated snapshots must not retain one copy of all previous+ // tables, drawings and nested columns per published text delta.+ const retainedObjects = deferred.reduce((count, { block }) => count ++ block.skeTables.length + block.skeDrawings.length + block.skeColumnGroups.length, 0);+ const latest = result.publication.block;+ expect(retainedObjects).toBeLessThanOrEqual(+ latest.skeTables.length + latest.skeDrawings.length + latest.skeColumnGroups.length+ );+ }}if (result.progress.complete) {break;@@ -1437,7 +1460,11 @@ describe('worker document layout session', () => {}expect(result.progress).toMatchObject({ complete: true, cancelled: false });- expect(result.progress.pageCount).toBeGreaterThan(1);+ if (flavor === DocumentFlavor.MODERN) {+ expect(result.progress.pageCount).toBe(1);+ } else {+ expect(result.progress.pageCount).toBeGreaterThan(1);+ }expect(publicationPayloads.join('')).toContain(bodyDrawingId);expect(publicationPayloads.join('')).toContain(tableId);expect(publicationPayloads.join('')).not.toContain('"drawingOrigin"');@@ -1495,23 +1522,22 @@ describe('worker document layout session', () => {const targetData = targetSkeleton.getSkeletonData();const nestedElementIds = collectNestedElementIds(targetData);- expect(targetData?.skeHeaders.size).toBeGreaterThan(0);- expect(targetData?.skeFooters.size).toBeGreaterThan(0);+ expect(targetData?.skeHeaders.size).toBe(flavor === DocumentFlavor.MODERN ? 0 : 1);+ expect(targetData?.skeFooters.size).toBe(flavor === DocumentFlavor.MODERN ? 0 : 1);expect(targetData?.skeListLevel?.size).toBeGreaterThan(0);expect(nestedElementIds.drawingIds).toEqual(new Set([bodyDrawingId,tableDrawingId,columnDrawingId,- headerDrawingId,- footerDrawingId,+ ...(flavor === DocumentFlavor.MODERN ? [] : [headerDrawingId, footerDrawingId]),]));expect(nestedElementIds.tableIds.has(tableId)).toBe(true);expect(nestedElementIds.tableIds.has(columnTableId)).toBe(true);expect(nestedElementIds.columnGroupIds.has(columnGroupId)).toBe(true);const headerPages = [...targetData?.skeHeaders.get('worker-rich-elements-header')?.values() ?? []];const footerPages = [...targetData?.skeFooters.get('worker-rich-elements-footer')?.values() ?? []];- expect(headerPages.some((page) => page.skeDrawings.has(headerDrawingId))).toBe(true);- expect(footerPages.some((page) => page.skeDrawings.has(footerDrawingId))).toBe(true);+ expect(headerPages.some((page) => page.skeDrawings.has(headerDrawingId))).toBe(flavor === DocumentFlavor.TRADITIONAL);+ expect(footerPages.some((page) => page.skeDrawings.has(footerDrawingId))).toBe(flavor === DocumentFlavor.TRADITIONAL);session.dispose();targetSkeleton.dispose();diff --git a/packages/engine-render/src/components/docs/__tests__/doc-background.spec.ts b/packages/engine-render/src/components/docs/__tests__/doc-background.spec.tsindex a22b23d7f1..6f7f32f748 100644--- a/packages/engine-render/src/components/docs/__tests__/doc-background.spec.ts+++ b/packages/engine-render/src/components/docs/__tests__/doc-background.spec.ts@@ -15,11 +15,13 @@*/import type { IDocumentSkeletonPage } from '../../../basics/i-document-skeleton-cached';-import { DocumentFlavor } from '@univerjs/core';+import { createDocumentModelWithStyle, DocumentFlavor, LocaleService, Univer } from '@univerjs/core';import { afterEach, describe, expect, it, vi } from 'vitest';import { PageLayoutType } from '../../../basics/i-document-skeleton-cached';import { Path, Rect } from '../../../shape';import { DocBackground } from '../doc-background';+import { DocumentSkeleton } from '../layout/doc-skeleton';+import { DocumentViewModel } from '../view-model/document-view-model';function createCtx() {return {@@ -62,9 +64,93 @@ function createSkeleton(pages: IDocumentSkeletonPage[], documentFlavor = Documen} as any;}+function createModernLayout() {+ const univer = new Univer();+ const model = createDocumentModelWithStyle('First paragraph\r\rLast paragraph\r', {});+ model.updateDocumentStyle({ documentFlavor: DocumentFlavor.MODERN, pageSize: { width: 400, height: 600 } });+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), univer.__getInjector().get(LocaleService));+ skeleton.calculate();+ const background = DocBackground.create('modern-delayed-skeleton', skeleton);+ background.resize(400, 600);+ const ctx = Object.assign(createCtx(), {+ beginPath: vi.fn(),+ createLinearGradient: vi.fn(() => ({ addColorStop: vi.fn() })),+ fill: vi.fn(),+ roundRect: vi.fn(),+ fillStyle: '',+ });+ vi.spyOn(Rect, 'drawWith').mockImplementation(() => {});+ return { skeleton, background, ctx, dispose: () => {+ background.dispose();+ skeleton.dispose();+ univer.dispose();+ } };+}+describe('DocBackground', () => {afterEach(() => {vi.restoreAllMocks();+ vi.useRealTimers();+ });++ it.each(['initial', 'edit'] as const)('delays modern skeleton lines for two seconds during %s layout', (reason) => {+ vi.useFakeTimers();+ const fixture = createModernLayout();+ const { skeleton, background, ctx } = fixture;+ try {+ skeleton.beginExternalLayout({ reason });+ background.draw(ctx);+ expect(ctx.roundRect).not.toHaveBeenCalled();+ vi.advanceTimersByTime(1_999);+ background.draw(ctx);+ expect(ctx.roundRect).not.toHaveBeenCalled();+ vi.advanceTimersByTime(1);+ background.draw(ctx);+ expect(ctx.roundRect).toHaveBeenCalled();+ } finally {+ fixture.dispose();+ }+ });++ it('never flashes modern skeleton lines for edits completed within two seconds', () => {+ vi.useFakeTimers();+ const fixture = createModernLayout();+ const { skeleton, background, ctx } = fixture;+ try {+ for (let edit = 0; edit < 3; edit++) {+ const generation = skeleton.startIncrementalLayout({ reason: 'edit', anchor: 0 });+ background.draw(ctx);+ vi.advanceTimersByTime(300);+ expect(skeleton.stepIncrementalLayout(generation, Number.POSITIVE_INFINITY).complete).toBe(true);+ background.draw(ctx);+ vi.advanceTimersByTime(2_000);+ background.draw(ctx);+ }+ expect(ctx.roundRect).not.toHaveBeenCalled();+ } finally {+ fixture.dispose();+ }+ });++ it('starts a fresh delay after cancellation and cancels the pending timer on disposal', () => {+ vi.useFakeTimers();+ const fixture = createModernLayout();+ const { skeleton, background, ctx } = fixture;+ try {+ skeleton.beginExternalLayout({ reason: 'edit' });+ background.draw(ctx);+ vi.advanceTimersByTime(1_500);+ skeleton.cancelExternalLayout();+ skeleton.beginExternalLayout({ reason: 'edit' });+ background.draw(ctx);+ vi.advanceTimersByTime(500);+ background.draw(ctx);+ expect(ctx.roundRect).not.toHaveBeenCalled();+ background.dispose();+ expect(vi.getTimerCount()).toBe(0);+ } finally {+ fixture.dispose();+ }});it('draws traditional workspaces with gray 100 and pages with the gray 0 theme token', () => {diff --git a/packages/engine-render/src/components/docs/doc-background.ts b/packages/engine-render/src/components/docs/doc-background.tsindex 07238a3b3f..f1aa53f1d6 100644--- a/packages/engine-render/src/components/docs/doc-background.ts+++ b/packages/engine-render/src/components/docs/doc-background.ts@@ -34,6 +34,7 @@ const SKELETON_BASE_COLOR = 'rgba(148, 163, 184, 0.18)';const SKELETON_HIGHLIGHT_COLOR = 'rgba(255, 255, 255, 0.5)';const SKELETON_LINE_HEIGHT = 12;const SKELETON_LINE_GAP = 14;+const CONTINUOUS_SKELETON_DELAY_MS = 2_000;export class DocBackground extends DocComponent {private _drawLiquid: Liquid;@@ -43,6 +44,9 @@ export class DocBackground extends DocComponent {private _marginStrokeColor?: string;private _pageBackgroundSource?: string;private _pageBackgroundImage?: HTMLImageElement;+ private _continuousSkeletonGeneration: number | undefined;+ private _continuousSkeletonTimer: ReturnType<typeof setTimeout> | null = null;+ private _continuousSkeletonVisible = false;constructor(oKey: string, documentSkeleton?: DocumentSkeleton, config?: IDocumentsConfig) {super(oKey, documentSkeleton, config);@@ -60,6 +64,11 @@ export class DocBackground extends DocComponent {return new DocBackground(oKey, documentSkeleton, config);}+ override dispose(): void {+ this._resetContinuousSkeleton();+ super.dispose();+ }+setFillColors(backgroundFillColor?: string, pageFillColor?: string, pageStrokeColor?: string, marginStrokeColor?: string) {if (this._backgroundFillColor === backgroundFillColor &&@@ -299,7 +308,27 @@ export class DocBackground extends DocComponent {const skeleton = this.getSkeleton();const progress = skeleton?.getLayoutProgress?.();const page = skeleton?.getSkeletonData()?.pages[0];- if (progress == null || progress.complete || page == null) {+ if (progress == null || progress.complete || progress.cancelled || page == null) {+ this._resetContinuousSkeleton();+ return;+ }++ if (this._continuousSkeletonGeneration !== progress.generation) {+ this._resetContinuousSkeleton();+ this._continuousSkeletonGeneration = progress.generation;+ // Short edits finish without painting a loading overlay or animating the background.+ this._continuousSkeletonTimer = setTimeout(() => {+ this._continuousSkeletonTimer = null;+ const latest = this.getSkeleton()?.getLayoutProgress?.();+ if (this.getSkeleton() !== skeleton || latest == null || latest.generation !== progress.generation || latest.complete || latest.cancelled) {+ this._resetContinuousSkeleton();+ return;+ }+ this._continuousSkeletonVisible = true;+ this.makeDirty(true);+ }, CONTINUOUS_SKELETON_DELAY_MS);+ }+ if (!this._continuousSkeletonVisible) {return;}@@ -311,6 +340,15 @@ export class DocBackground extends DocComponent {this._drawSkeletonLines(ctx, startX, startY, width, Math.max(160, visibleBottom - startY), bounds);}+ private _resetContinuousSkeleton(): void {+ if (this._continuousSkeletonTimer != null) {+ clearTimeout(this._continuousSkeletonTimer);+ this._continuousSkeletonTimer = null;+ }+ this._continuousSkeletonGeneration = undefined;+ this._continuousSkeletonVisible = false;+ }+private _drawSkeletonLines(ctx: UniverRenderingContext,left: number,@@ -386,6 +424,9 @@ export class DocBackground extends DocComponent {}changeSkeleton(newSkeleton: DocumentSkeleton) {+ if (newSkeleton !== this.getSkeleton()) {+ this._resetContinuousSkeleton();+ }this.setSkeleton(newSkeleton);return this;diff --git a/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts b/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.tsindex a85096e70b..7b4891ae6b 100644--- a/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts+++ b/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts@@ -300,6 +300,41 @@ describe('doc skeleton', () => {}});+ it('does not clone the entire continuous page as a paginated interaction tail when editing its first paragraph', () => {+ const univer = new Univer();+ const localeService = univer.__getInjector().get(LocaleService);+ const content = 'Paragraph text\r\r'.repeat(100);+ const model = createDocumentModelWithStyle(content, {});+ model.updateDocumentStyle({ documentFlavor: DocumentFlavor.MODERN });+ const viewModel = new DocumentViewModel(model);+ const skeleton = DocumentSkeleton.create(viewModel, localeService);+ const nextModel = createDocumentModelWithStyle(`X${content}`, {});+ nextModel.updateDocumentStyle({ documentFlavor: DocumentFlavor.MODERN });+ const expected = DocumentSkeleton.create(new DocumentViewModel(nextModel), localeService);+ try {+ skeleton.calculate();+ viewModel.reset(nextModel);+ const generation = skeleton.startIncrementalLayout({+ reason: 'edit',+ anchor: 0,+ priorityAnchor: 1,+ invalidation: { oldStart: 0, oldEnd: 0, newEnd: 1 },+ reuseUnaffectedTail: false,+ });+ let progress = skeleton.stepIncrementalLayout(generation, 0, 1);+ expect(progress).toMatchObject({ complete: false, anchorReady: true, processedBlockCount: 1 });+ while (!progress.complete) {+ progress = skeleton.stepIncrementalLayout(generation, 8);+ }+ expected.calculate();+ expect(normalizeSkeleton(skeleton.getSkeletonData())).toEqual(normalizeSkeleton(expected.getSkeletonData()));+ } finally {+ expected.dispose();+ skeleton.dispose();+ univer.dispose();+ }+ });+it('does not resolve publication geometry while a distant edit anchor is still pending', () => {const univer = new Univer();const model = createDocumentModelWithStyle('Paragraph text.\r'.repeat(80), {});@@ -855,6 +890,86 @@ describe('doc skeleton', () => {expect(docViewModel.dispose).toHaveBeenCalled();});+ it('hit-tests imported sections throughout a modern page while Worker layout is pending', () => {+ const univer = new Univer();+ const content = 'Modern paragraph with an empty paragraph below.\r\r'.repeat(30);+ const model = createDocumentModelWithStyle(content, {});+ model.updateDocumentStyle({ documentFlavor: DocumentFlavor.MODERN });+ model.updateDocumentDataPageSize(240, 180);+ const importedSection = model.getBody()!.sectionBreaks![0];+ importedSection.pageSize = { width: 240, height: 180 };+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), univer.__getInjector().get(LocaleService));+ skeleton.calculate();+ const page = skeleton.getSkeletonData()!.pages[0];+ const section = page.sections[page.sections.length - 1];+ const column = section.columns[0];+ const line = column.lines[column.lines.length - 2];+ const divide = line.divides[0];+ const glyph = divide.glyphGroup[0];+ const coord = Vector2.FromArray([+ page.marginLeft + column.left + divide.left + glyph.left + glyph.width / 2,+ page.marginTop + section.top + line.top + line.lineHeight / 2,+ ]);+ expect(coord.y).toBeGreaterThan(180);+ expect(page.pageHeight).toBe(Number.POSITIVE_INFINITY);+ expect(importedSection.pageSize).toEqual({ width: 240, height: 180 });+ skeleton.beginExternalLayout({+ reason: 'edit',+ protectedRange: { mode: 'continuous', startOffset: 0, endOffset: content.length },+ });+ expect(skeleton.getLayoutProgress()?.complete).toBe(false);+ expect(skeleton.findEditAreaByCoord(coord, PageLayoutType.VERTICAL, 0, 0)).toMatchObject({+ editArea: 'BODY',+ pageNumber: 0,+ });+ const hit = skeleton.findNodeByCoord(coord, PageLayoutType.VERTICAL, 0, 0, {+ strict: false,+ segmentId: '',+ segmentPage: -1,+ });+ expect(hit?.node).toBe(glyph);+ expect(skeleton.findPositionByGlyph(hit!.node, -1)?.page).toBe(0);+ skeleton.dispose();+ model.dispose();+ univer.dispose();+ });++ it('keeps unaffected modern paragraphs clickable before the edited paragraph is ready', () => {+ const univer = new Univer();+ const text = 'Unchanged paragraph.\r\rChanged paragraph.\r';+ const model = createDocumentModelWithStyle(text, {});+ model.updateDocumentStyle({ documentFlavor: DocumentFlavor.MODERN });+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(model), univer.__getInjector().get(LocaleService));+ skeleton.calculate();+ const page = skeleton.getSkeletonData()!.pages[0];+ const section = page.sections[0];+ const column = section.columns[0];+ const pointForLine = (index: number) => {+ const line = column.lines[index];+ const divide = line.divides[0];+ const glyph = divide.glyphGroup[0];+ return Vector2.FromArray([+ page.marginLeft + column.left + divide.left + glyph.left + glyph.width / 2,+ page.marginTop + section.top + line.top + line.lineHeight / 2,+ ]);+ };+ const prefixPoint = pointForLine(0);+ const changedPoint = pointForLine(column.lines.length - 1);+ const anchor = text.indexOf('Changed');+ skeleton.startIncrementalLayout({+ reason: 'edit',+ anchor,+ priorityAnchor: anchor + 1,+ invalidation: { oldStart: anchor, oldEnd: anchor, newEnd: anchor + 1 },+ });+ expect(skeleton.getLayoutProgress()?.anchorReady).toBe(false);+ expect(skeleton.findNodeByCoord(prefixPoint, PageLayoutType.VERTICAL, 0, 0)?.node.content).toBe('U');+ expect(skeleton.findNodeByCoord(changedPoint, PageLayoutType.VERTICAL, 0, 0)).toBeNull();+ skeleton.dispose();+ model.dispose();+ univer.dispose();+ });+it('covers coordinate search helpers and nearest-node strategies', () => {const body = createPage(DocumentSkeletonPageType.BODY, 0);const header = createPage(DocumentSkeletonPageType.HEADER, 200);@@ -2566,6 +2681,47 @@ describe('doc skeleton', () => {univer.dispose();});+ it.each([DocumentFlavor.MODERN, DocumentFlavor.TRADITIONAL])(+ 'keeps text before empty paragraphs addressable after prefix reuse (flavor %s)',+ (documentFlavor) => {+ const univer = new Univer();+ const localeService = univer.__getInjector().get(LocaleService);+ const content = 'First paragraph\rSecond paragraph\r\r\r\rLast paragraph\r';+ const documentModel = createDocumentModelWithStyle(content, {});+ documentModel.updateDocumentStyle({ documentFlavor });+ const skeleton = DocumentSkeleton.create(new DocumentViewModel(documentModel), localeService);+ skeleton.calculate();+ const originalPage = skeleton.getSkeletonData()!.pages[0];+ const originalGlyph = originalPage.sections[0].columns[0].lines[0].divides[0].glyphGroup[0];++ for (let repeat = 0; repeat < 3; repeat++) {+ const generation = skeleton.startIncrementalLayout({+ reason: 'edit',+ anchor: content.indexOf('Last'),+ reuseUnaffectedTail: false,+ });+ let progress = skeleton.stepIncrementalLayout(generation, 0);+ for (let step = 0; step < 100 && !progress.complete; step++) {+ progress = skeleton.stepIncrementalLayout(generation, 0);+ }+ expect(progress.complete).toBe(true);++ const page = skeleton.getSkeletonData()!.pages[0];+ for (const line of page.sections[0].columns[0].lines) {+ const glyph = line.divides[0].glyphGroup[0];+ const position = skeleton.findPositionByGlyph(glyph, -1)!;+ expect(position.page).toBe(0);+ expect(skeleton.findCharIndexByPosition({ ...position, isBack: true })).toBe(line.st);+ }+ // Reusing a prefix must not reparent glyphs in the retained baseline.+ expect(originalGlyph.parent!.parent!.parent!.parent!.parent).toBe(originalPage);+ }++ skeleton.dispose();+ univer.dispose();+ }+ );+it('falls back to full incremental layout for a complex modern page', () => {const univer = new Univer();const localeService = univer.__getInjector().get(LocaleService);diff --git a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts b/packages/engine-render/src/components/docs/layout/doc-skeleton.tsindex 42abab3c49..0a4a9dadf4 100644--- a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts+++ b/packages/engine-render/src/components/docs/layout/doc-skeleton.ts@@ -15,16 +15,52 @@*/import type { ColumnSeparatorType, ISectionColumnProperties, LocaleService, Nullable } from '@univerjs/core';-import type { IDocumentSkeletonCached, IDocumentSkeletonColumn, IDocumentSkeletonColumnGroup, IDocumentSkeletonColumnGroupColumn, IDocumentSkeletonDivide, IDocumentSkeletonDrawing, IDocumentSkeletonDrawingAnchor, IDocumentSkeletonGlyph, IDocumentSkeletonLine, IDocumentSkeletonPage, IDocumentSkeletonRow, IDocumentSkeletonSection, IDocumentSkeletonTable, ISkeletonResourceReference } from '../../../basics/i-document-skeleton-cached';-import type { IDocsConfig, INodeInfo, INodePosition, INodeSearch, ISectionBreakConfig } from '../../../basics/interfaces';+import type {+ IDocumentSkeletonCached,+ IDocumentSkeletonColumn,+ IDocumentSkeletonColumnGroup,+ IDocumentSkeletonColumnGroupColumn,+ IDocumentSkeletonDivide,+ IDocumentSkeletonDrawing,+ IDocumentSkeletonDrawingAnchor,+ IDocumentSkeletonGlyph,+ IDocumentSkeletonLine,+ IDocumentSkeletonPage,+ IDocumentSkeletonRow,+ IDocumentSkeletonSection,+ IDocumentSkeletonTable,+ ISkeletonResourceReference,+} from '../../../basics/i-document-skeleton-cached';+import type {+ IDocsConfig,+ INodeInfo,+ INodePosition,+ INodeSearch,+ ISectionBreakConfig,+} from '../../../basics/interfaces';import type { IViewportInfo, Vector2 } from '../../../basics/vector2';import type { IDocsCustomBlockRenderViewport } from '../custom-block-render-viewport';import type { DataStreamTreeNode } from '../view-model/data-stream-tree-node';import type { DocumentViewModel } from '../view-model/document-view-model';import type { ISlicedTableSkeletonBuildState, ITableSkeletonBuildState } from './block/table';import type { IDocumentSkeletonPagePatch } from './document-layout-page-patch';-import type { IDocumentLayoutBlockGeometryPublication, IDocumentLayoutDrawingAnchorPublication, IDocumentLayoutGeometryPublication, IDocumentLayoutPagePublication, IDocumentLayoutResourcePublication } from './document-layout-publication';-import type { DocumentLayoutMode, DocumentLayoutReason, IDocumentLayoutApplyResult, IDocumentLayoutInvalidation, IDocumentLayoutPageRange, IDocumentLayoutProgress, IDocumentLayoutProtectedPageRange, IDocumentLayoutProtectedRange } from './document-layout-types';+import type {+ IDocumentLayoutBlockGeometryPublication,+ IDocumentLayoutDrawingAnchorPublication,+ IDocumentLayoutGeometryPublication,+ IDocumentLayoutPagePublication,+ IDocumentLayoutResourcePublication,+} from './document-layout-publication';+import type {+ DocumentLayoutMode,+ DocumentLayoutReason,+ IDocumentLayoutApplyResult,+ IDocumentLayoutInvalidation,+ IDocumentLayoutPageRange,+ IDocumentLayoutProgress,+ IDocumentLayoutProtectedPageRange,+ IDocumentLayoutProtectedRange,+} from './document-layout-types';import type { IDocumentPaginationMetrics, ILayoutContext } from './tools';import {BooleanNumber,@@ -37,7 +73,13 @@ import {Skeleton,} from '@univerjs/core';import { Subject } from 'rxjs';-import { BreakType, DocumentSkeletonPageType, GlyphType, LineType, PageLayoutType } from '../../../basics/i-document-skeleton-cached';+import {+ BreakType,+ DocumentSkeletonPageType,+ GlyphType,+ LineType,+ PageLayoutType,+} from '../../../basics/i-document-skeleton-cached';import { getDocsCustomBlockRenderViewport } from '../custom-block-render-viewport';import { getDocumentCompatibilityPolicy } from '../document-compatibility';import { Liquid } from '../liquid';@@ -55,7 +97,12 @@ import {stepTableSkeletonBuild,stepTableSkeletonsBuild,} from './block/table';-import { applyDocumentSkeletonContinuousBlock, hydrateDocumentSkeletonPage, hydrateDocumentSkeletonPageMaterializationPlaceholder, serializeDocumentSkeletonPage } from './document-layout-page-patch';+import {+ applyDocumentSkeletonContinuousBlock,+ hydrateDocumentSkeletonPage,+ hydrateDocumentSkeletonPageMaterializationPlaceholder,+ serializeDocumentSkeletonPage,+} from './document-layout-page-patch';import { Hyphen } from './hyphenation/hyphen';import { Lang } from './hyphenation/lang';import { LanguageDetector } from './hyphenation/language-detector';@@ -396,6 +443,35 @@ function mapPreviousOffsetToCurrent(return offset + (invalidation.newEnd - invalidation.oldEnd);}+function cloneLineFlowForPublish(+ source: IDocumentSkeletonLine,+ parent?: IDocumentSkeletonColumn+): IDocumentSkeletonLine {+ const line: IDocumentSkeletonLine = {+ ...source,+ divides: [],+ parent,+ };+ if (source.bullet != null) {+ line.bullet = { ...source.bullet };+ }+ // A retained or published line must own its full parent graph. Sharing+ // divides leaves hit-tested glyphs pointing at a page in the old skeleton.+ line.divides = source.divides.map((sourceDivide): IDocumentSkeletonDivide => {+ const divide: IDocumentSkeletonDivide = {+ ...sourceDivide,+ glyphGroup: [],+ parent: line,+ };+ divide.glyphGroup = sourceDivide.glyphGroup.map((glyph) => ({+ ...glyph,+ parent: divide,+ }));+ return divide;+ });+ return line;+}+function clonePageFlowForPublish(source: IDocumentSkeletonPage): IDocumentSkeletonPage {const page: IDocumentSkeletonPage = {...source,@@ -431,31 +507,7 @@ function clonePageFlowForPublish(source: IDocumentSkeletonPage): IDocumentSkeletlines: [],parent: section,};- column.lines = sourceColumn.lines.map((sourceLine) => {- const line: IDocumentSkeletonLine = {- ...sourceLine,- divides: [],- parent: column,- };- if (sourceLine.bullet != null) {- line.bullet = { ...sourceLine.bullet };- }- line.divides = sourceLine.divides.map((sourceDivide): IDocumentSkeletonDivide => {- const divide: IDocumentSkeletonDivide = {- ...sourceDivide,- glyphGroup: [],- parent: line,- };- // Published flow nodes own a separate parent graph. Clone glyph containers- // so selection hit testing resolves positions against the published page.- divide.glyphGroup = sourceDivide.glyphGroup.map((glyph) => ({- ...glyph,- parent: divide,- }));- return divide;- });- return line;- });+ column.lines = sourceColumn.lines.map((sourceLine) => cloneLineFlowForPublish(sourceLine, column));return column;});return section;@@ -1388,7 +1440,9 @@ export class DocumentSkeleton extends Skeleton {);const canResumePlainParagraph = blocks[anchorBlockIndex].block.nodeType === DataStreamTreeNodeType.PARAGRAPH &&blocks[anchorBlockIndex].block.children.length === 0;- if (reuseInteractionPagePrefix && canResumePlainParagraph) {+ // A Modern page can contain the entire document. Paginated tail reuse+ // deep-clones that page in one atomic step, bypassing the slice budget.+ if (mode === 'paginated' && reuseInteractionPagePrefix && canResumePlainParagraph) {const interactionPreviousAnchor = mapCurrentOffsetToPrevious(anchor, invalidation);const interactionPageIndex = interactionSkeleton == null? -1@@ -1573,7 +1627,7 @@ export class DocumentSkeleton extends Skeleton {}const retainedLines = previousColumn.lines.filter((line) => line.ed < previousAnchorStart)- .map((line) => ({ ...line }));+ .map((line) => cloneLineFlowForPublish(line));if (retainedLines.length === 0 && previousAnchorStart < getFirstBodyFlowCharIndex(previousPage)) {// A continued paragraph must be rebuilt from the page where it starts.return null;@@ -1734,7 +1788,7 @@ export class DocumentSkeleton extends Skeleton {const retainedLines = previousColumn.lines.filter((line) => line.ed < anchorBlock.startIndex)- .map((line) => ({ ...line }));+ .map((line) => cloneLineFlowForPublish(line));if (retainedLines.length === 0) {return null;}@@ -2495,7 +2549,21 @@ export class DocumentSkeleton extends Skeleton {? this._externalProtectedContinuousLayout: null;if (publication.kind === 'block' && protectedContinuousLayout != null) {- protectedContinuousLayout.pendingPublications.push(publication);+ // Flow patches are deltas, but embedded objects are a full snapshot+ // on every publication. Retaining every table snapshot while Main's+ // interaction window is protected grows quadratically with layout+ // progress. Only the final snapshot is needed when replaying deltas.+ protectedContinuousLayout.pendingPublications.push(progress.complete+ ? publication+ : {+ ...publication,+ block: {+ ...publication.block,+ skeTables: [],+ skeDrawings: [],+ skeColumnGroups: [],+ },+ });}const commitsProtectedContinuousLayout = progress.complete && protectedContinuousLayout != null;const publicationToApply = publication.kind === 'block' && protectedContinuousLayout != null && !commitsProtectedContinuousLayout@@ -3154,6 +3222,28 @@ export class DocumentSkeleton extends Skeleton {pageMarginLeft: number,pageMarginTop: number,restrictions?: IFindNodeRestrictions+ ): Nullable<INodeInfo> {+ const hit = this._findNodeByCoord(coord, pageLayoutType, pageMarginLeft, pageMarginTop, restrictions);+ const layout = this._activeLayout;+ if (hit != null && layout?.mode === 'continuous' && layout.reason === 'edit' && !layout.complete && !layout.anchorPublished) {+ // A continuous document has only one physical page. Its unaffected+ // paragraphs remain editable while the changed paragraph is laid out;+ // the page-based preview guard would otherwise disable the whole Doc.+ const dirtyStart = layout.invalidation?.oldStart ?? layout.priorityAnchor ?? 0;+ const paragraphEnd = hit.node.parent?.parent?.paragraphIndex;+ if (paragraphEnd == null || paragraphEnd >= dirtyStart) {+ return null;+ }+ }+ return hit;+ }++ private _findNodeByCoord(+ coord: Vector2,+ pageLayoutType: PageLayoutType,+ pageMarginLeft: number,+ pageMarginTop: number,+ restrictions?: IFindNodeRestrictions): Nullable<INodeInfo> {const { x, y } = coord;@@ -3181,7 +3271,7 @@ export class DocumentSkeleton extends Skeleton {// Before Main publishes the edited page, retained geometry is only a// visual preview. Only its unaffected prefix still accepts new pointers;// ongoing native input continues through the logical selection instead.- if (layout?.reason === 'edit' && !layout.complete && !layout.anchorPublished && pageNumber >= layout.stablePageCount) {+ if (layout?.mode === 'paginated' && layout.reason === 'edit' && !layout.complete && !layout.anchorPublished && pageNumber >= layout.stablePageCount) {return null;}const pageLength = pages.length;diff --git a/packages/engine-render/src/components/docs/layout/tools.ts b/packages/engine-render/src/components/docs/layout/tools.tsindex 459f355be5..b44e4e6a66 100644--- a/packages/engine-render/src/components/docs/layout/tools.ts+++ b/packages/engine-render/src/components/docs/layout/tools.ts@@ -81,7 +81,11 @@ import { DEFAULT_DOCUMENT_FONTSIZE } from '../../../basics/const';import { GlyphType, LineType } from '../../../basics/i-document-skeleton-cached';import { getFontStyleString, isFunction, ptToPixel } from '../../../basics/tools';import { getDocumentCompatibilityPolicy } from '../document-compatibility';-import { getDocsTableRenderViewport, getDocsTableViewportLeft, hasDocsTableHorizontalViewport } from '../table-render-viewport';+import {+ getDocsTableRenderViewport,+ getDocsTableViewportLeft,+ hasDocsTableHorizontalViewport,+} from '../table-render-viewport';import { updateInlineDrawingPosition } from './block/paragraph/layout-ruler';import { getCustomDecorationStyle } from './style/custom-decoration';import { getCustomRangeStyle } from './style/custom-range';@@ -1968,13 +1972,16 @@ export function prepareSectionBreakConfig(ctx: ILayoutContext, nodeIndex: number// In modern mode, there are no pages, no sections, no columns. There are no headers and footers, and margins are all defaults.if (documentFlavor === DocumentFlavor.MODERN) {const modernPageWidth = documentStyle.pageSize?.width ?? DEFAULT_MODERN_DOCUMENT_STYLE.pageSize!.width;- sectionBreak = Object.assign({}, sectionBreak, DEFAULT_MODERN_SECTION_BREAK);- documentStyle = Object.assign({}, documentStyle, DEFAULT_MODERN_DOCUMENT_STYLE, {- pageSize: {- ...DEFAULT_MODERN_DOCUMENT_STYLE.pageSize!,- width: modernPageWidth,- },- });+ const modernPageSize = {+ ...DEFAULT_MODERN_DOCUMENT_STYLE.pageSize!,+ width: modernPageWidth,+ };+ // Imported sections can retain their own paper size. It must not+ // override the continuous page when the document switches to modern+ // mode, otherwise layout still paginates and pointer bounds stop at+ // the first sheet of paper while rendering merges the entire document.+ sectionBreak = Object.assign({}, sectionBreak, DEFAULT_MODERN_SECTION_BREAK, { pageSize: modernPageSize });+ documentStyle = Object.assign({}, documentStyle, DEFAULT_MODERN_DOCUMENT_STYLE, { pageSize: modernPageSize });}const {diff --git a/packages/protocol/src/ts/universer/v1/authz.ts b/packages/protocol/src/ts/universer/v1/authz.tsindex 8a94fbf9b8..57a4acac85 100644--- a/packages/protocol/src/ts/universer/v1/authz.ts+++ b/packages/protocol/src/ts/universer/v1/authz.ts@@ -58,6 +58,19 @@ export interface ICreateRequest {objectType: UnitObject;selectRangeObject?: ICreateRequestSelectRangeObject | undefined;worksheetObject?: ICreateRequestWorksheetObject | undefined;+ /** Mirror these optional oneof payloads in univer-protocol before enabling the corresponding product. */+ documentObject?: ICreateRequestPermissionObject | undefined;+ slideObject?: ICreateRequestPermissionObject | undefined;+ baseObject?: ICreateRequestPermissionObject | undefined;+ boardObject?: ICreateRequestPermissionObject | undefined;+}++interface ICreateRequestPermissionObject {+ collaborators: ICollaborator[];+ unitID: string;+ name: string;+ strategies: IUnitPermissionStrategy[];+ scope: IObjScope | undefined;}export interface ICreateRequestSelectRangeObject {diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex e78ba193ac..838fe306a9 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -91,6 +91,7 @@"@univerjs/design": "workspace:*","@univerjs/engine-render": "workspace:*","@univerjs/icons": "1.38.0",+ "@univerjs/protocol": "workspace:*","@wendellhu/redi": "1.1.2"},"devDependencies": {diff --git a/packages/ui/src/common/object-permission-menu.ts b/packages/ui/src/common/object-permission-menu.tsnew file mode 100644index 0000000000..0e65770ba3--- /dev/null+++ b/packages/ui/src/common/object-permission-menu.ts@@ -0,0 +1,56 @@+/**+ * 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, UniverInstanceType } from '@univerjs/core';+import type { UnitObject } from '@univerjs/protocol';+import type { IMenuButtonItem } from '../services/menu/menu';+import { isInternalEditorID, IUniverInstanceService, ObjectPermissionService } from '@univerjs/core';+import { combineLatest, map, of, switchMap } from 'rxjs';+import { MenuItemType } from '../services/menu/menu';+import { IWorkbenchService } from '../services/workbench/workbench.service';++export function objectPermissionMenuItemFactory(+ accessor: IAccessor,+ id: string,+ unitType: UniverInstanceType,+ objectType: UnitObject+): IMenuButtonItem {+ const instances = accessor.get(IUniverInstanceService);+ const state$ = combineLatest([+ accessor.get(IWorkbenchService).rootUnitType$,+ instances.getCurrentTypeOfUnit$(unitType),+ ]).pipe(switchMap(([rootType, model]) => {+ if (rootType !== unitType || !model || isInternalEditorID(model.getUnitId())) {+ return of({ hidden: true, disabled: true });+ }+ // Resolve only after a product unit exists so late Authz overrides can register first.+ const permissions = accessor.get(ObjectPermissionService);+ const unitId = model.getUnitId();+ return permissions.changed$.pipe(map(() => ({+ disabled: !permissions.canView({ unitId, objectId: unitId, objectType }),+ hidden: !permissions.supports({ unitId, objectId: unitId, objectType }),+ })));+ }));+ return {+ id,+ type: MenuItemType.BUTTON,+ icon: 'ProtectIcon',+ title: 'ui.objectPermission.title',+ tooltip: 'ui.objectPermission.title',+ disabled$: state$.pipe(map((state) => state.disabled)),+ hidden$: state$.pipe(map((state) => state.hidden)),+ };+}diff --git a/packages/ui/src/controllers/__tests__/ui.controller.spec.ts b/packages/ui/src/controllers/__tests__/ui.controller.spec.tsindex 5803a11f6c..a2f59e925d 100644--- a/packages/ui/src/controllers/__tests__/ui.controller.spec.ts+++ b/packages/ui/src/controllers/__tests__/ui.controller.spec.ts@@ -15,7 +15,6 @@*/import { RedoCommand, UndoCommand } from '@univerjs/core';-import { Subject } from 'rxjs';import { describe, expect, it, vi } from 'vitest';import { OpenFeatureSearchOperation } from '../../commands/operations/open-feature-search.operation';import { ToggleShortcutPanelOperation } from '../../commands/operations/toggle-shortcut-panel.operation';@@ -23,33 +22,9 @@ import { menuSchema } from '../../menu/schema';import { ShortcutPanelMenuItemFactory } from '../../menu/shortcut-panel.menu';import { RibbonStartGroup } from '../../services/menu/types';import { KeyCode, MetaKeys } from '../../services/shortcut/keycode';-import { ErrorController } from '../error/error.controller';import { FeatureSearchController } from '../feature-search/feature-search.controller';import { ShortcutPanelController } from '../shortcut-display/shortcut-panel.controller';-describe('ErrorController', () => {- it('should forward errors to message service', () => {- const error$ = new Subject<{ errorKey: string }>();- const errorService = {- error$,- };- const messageService = {- show: vi.fn(),- };-- const controller = new ErrorController(errorService as any, messageService as any);- error$.next({ errorKey: 'boom' });-- expect(messageService.show).toHaveBeenCalledWith(- expect.objectContaining({- content: 'boom',- })- );-- controller.dispose();- });-});-describe('shortcut-display controllers', () => {it('should return shortcut panel menu item', () => {expect(ShortcutPanelMenuItemFactory()).toEqual({diff --git a/packages/ui/src/controllers/components.controller.ts b/packages/ui/src/controllers/components.controller.tsindex 67455a01a4..ea4e5ffb68 100644--- a/packages/ui/src/controllers/components.controller.ts+++ b/packages/ui/src/controllers/components.controller.ts@@ -22,6 +22,7 @@ import {IncreaseIcon,KeyboardIcon,MoreDownIcon,+ ProtectIcon,RedoIcon,ReduceIcon,ShortcutIcon,@@ -29,7 +30,8 @@ import {UndoIcon,} from '@univerjs/icons';import { ShortcutPanelComponentName } from '../commands/operations/toggle-shortcut-panel.operation';-import { ComponentManager, IconManager } from '../common';+import { ComponentManager } from '../common/component-manager';+import { IconManager } from '../common/icon-manager';import { COLOR_PICKER_COMPONENT } from '../views/color-picker/interface';import { COMMON_LABEL_COMPONENT, CommonLabel } from '../views/CommonLabel';import { FEATURE_SEARCH_COMPONENT, FeatureSearch } from '../views/components/feature-search/FeatureSearch';@@ -44,6 +46,8 @@ import {import { FontSize } from '../views/font-size/FontSize';import { FONT_SIZE_COMPONENT } from '../views/font-size/interface';import { HEADING_ITEM_COMPONENT, HeadingItem } from '../views/index';+import { OBJECT_PERMISSION_DIALOG, ObjectPermissionDialog } from '../views/object-permission/ObjectPermissionButton';+import { OBJECT_PERMISSION_PANEL, ObjectPermissionPanel } from '../views/object-permission/ObjectPermissionPanel';import { SYMBOL_PICKER_COMPONENT, SymbolPicker } from '../views/symbol-picker/index';export class ComponentsController extends Disposable {@@ -63,6 +67,7 @@ export class ComponentsController extends Disposable {IncreaseIcon,KeyboardIcon,MoreDownIcon,+ ProtectIcon,RedoIcon,ReduceIcon,FeatureSearchIcon,@@ -75,6 +80,8 @@ export class ComponentsController extends Disposable {private _registerComponents(): void {([[COMMON_LABEL_COMPONENT, CommonLabel],+ [OBJECT_PERMISSION_DIALOG, ObjectPermissionDialog],+ [OBJECT_PERMISSION_PANEL, ObjectPermissionPanel],[HEADING_ITEM_COMPONENT, HeadingItem],[FONT_FAMILY_COMPONENT, FontFamily],[FONT_FAMILY_ITEM_COMPONENT, FontFamilyItem],diff --git a/packages/ui/src/controllers/error/__tests__/error.controller.spec.ts b/packages/ui/src/controllers/error/__tests__/error.controller.spec.tsnew file mode 100644index 0000000000..4d8635b764--- /dev/null+++ b/packages/ui/src/controllers/error/__tests__/error.controller.spec.ts@@ -0,0 +1,132 @@+/**+ * 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 {+ ErrorService,+ Injector,+ IPermissionService,+ LocaleService,+ LocaleType,+ PermissionService,+} from '@univerjs/core';+import { MessageType } from '@univerjs/design';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import enUS from '../../../locale/en-US';+import zhCN from '../../../locale/zh-CN';+import { DesktopMessageService } from '../../../services/message/desktop-message.service';+import { IMessageService } from '../../../services/message/message.service';+import { IUIPartsService, UIPartsService } from '../../../services/parts/parts.service';+import { ErrorController } from '../error.controller';++describe('permission denied feedback', () => {+ let injector: Injector;++ beforeEach(() => {+ vi.useFakeTimers();+ injector = new Injector([+ [ErrorService],+ [LocaleService],+ [IPermissionService, { useClass: PermissionService }],+ [IUIPartsService, { useClass: UIPartsService }],+ [IMessageService, { useClass: DesktopMessageService }],+ [ErrorController],+ ]);+ const locale = injector.get(LocaleService);+ locale.load({ [LocaleType.EN_US]: enUS, [LocaleType.ZH_CN]: zhCN });+ locale.setLocale(LocaleType.EN_US);+ injector.get(ErrorController);+ });++ afterEach(() => {+ injector.dispose();+ vi.useRealTimers();+ vi.restoreAllMocks();+ });++ it('shows one warning for continuous attempts and allows a new warning after a quiet interval', () => {+ const show = vi.spyOn(injector.get(IMessageService), 'show');+ const errors = injector.get(ErrorService);+ errors.emitPermissionDenied('doc-1', ['paragraph-1']);+ for (let i = 0; i < 6; i++) {+ vi.advanceTimersByTime(1000);+ errors.emitPermissionDenied('doc-1', ['paragraph-1']);+ }+ expect(show).toHaveBeenCalledTimes(1);+ expect(show).toHaveBeenCalledWith(expect.objectContaining({+ content: enUS.ui.objectPermission.operationDenied,+ type: MessageType.Warning,+ duration: 3000,+ }));+ vi.advanceTimersByTime(3000);+ errors.emitPermissionDenied('doc-1', ['paragraph-1']);+ expect(show).toHaveBeenCalledTimes(2);+ });++ it('immediately refreshes the warning when switching objects or documents', () => {+ const show = vi.spyOn(injector.get(IMessageService), 'show');+ const errors = injector.get(ErrorService);+ errors.emitPermissionDenied('doc-1', ['paragraph-1']);+ errors.emitPermissionDenied('doc-1', ['paragraph-2']);+ expect(show).toHaveBeenCalledTimes(2);+ errors.emitPermissionDenied('doc-1', ['paragraph-2']);+ expect(show).toHaveBeenCalledTimes(2);+ errors.emitPermissionDenied('doc-2', ['paragraph-2']);+ errors.emitPermissionDenied('doc-1', ['paragraph-1']);+ expect(show).toHaveBeenCalledTimes(4);+ expect(new Set(show.mock.calls.map(([options]) => options.id)).size).toBe(1);+ });++ it('deduplicates the same multi-object selection regardless of target order or duplicates', () => {+ const show = vi.spyOn(injector.get(IMessageService), 'show');+ const errors = injector.get(ErrorService);+ errors.emitPermissionDenied('doc-1', ['section-1', 'paragraph-1', 'paragraph-2']);+ errors.emitPermissionDenied('doc-1', ['paragraph-2', 'paragraph-1', 'section-1', 'paragraph-1']);+ expect(show).toHaveBeenCalledTimes(1);+ errors.emitPermissionDenied('doc-1', ['paragraph-1']);+ expect(show).toHaveBeenCalledTimes(2);+ });++ it('honors the shared permission visibility setting without suppressing other errors', () => {+ const show = vi.spyOn(injector.get(IMessageService), 'show');+ injector.get(IPermissionService).setShowComponents(false);+ injector.get(ErrorService).emitPermissionDenied('doc-1', ['paragraph-1']);+ expect(show).not.toHaveBeenCalled();+ injector.get(ErrorService).emit('Network unavailable');+ expect(show).toHaveBeenCalledWith({ content: 'Network unavailable', type: MessageType.Error });+ injector.get(IPermissionService).setShowComponents(true);+ injector.get(ErrorService).emitPermissionDenied('doc-1', ['paragraph-1']);+ expect(show).toHaveBeenCalledTimes(2);+ });++ it('uses the current locale when an operation is rejected', () => {+ const show = vi.spyOn(injector.get(IMessageService), 'show');+ injector.get(LocaleService).setLocale(LocaleType.ZH_CN);+ injector.get(ErrorService).emitPermissionDenied('doc-1', ['paragraph-1']);+ expect(show).toHaveBeenCalledWith(expect.objectContaining({+ content: zhCN.ui.objectPermission.operationDenied,+ }));+ });++ it('stops feedback and dismisses its message on disposal', () => {+ const service = injector.get(IMessageService);+ const show = vi.spyOn(service, 'show');+ const remove = vi.spyOn(service, 'remove');+ injector.get(ErrorController).dispose();+ injector.get(ErrorService).emitPermissionDenied('doc-1', ['paragraph-1']);+ expect(show).not.toHaveBeenCalled();+ expect(remove).toHaveBeenCalledWith('ui.permission-denied');+ });+});diff --git a/packages/ui/src/controllers/error/error.controller.ts b/packages/ui/src/controllers/error/error.controller.tsindex bdfa96ebd3..e3027cc7eb 100644--- a/packages/ui/src/controllers/error/error.controller.ts+++ b/packages/ui/src/controllers/error/error.controller.ts@@ -14,22 +14,54 @@* limitations under the License.*/-import { Disposable, ErrorService, Inject } from '@univerjs/core';+import { Disposable, ErrorService, Inject, IPermissionService, LocaleService } from '@univerjs/core';import { MessageType } from '@univerjs/design';import { IMessageService } from '../../services/message/message.service';+const PERMISSION_MESSAGE_ID = 'ui.permission-denied';+const PERMISSION_MESSAGE_DURATION = 3000;+export class ErrorController extends Disposable {+ private _lastPermissionAttempt = Number.NEGATIVE_INFINITY;+ private _lastPermissionTarget: string | undefined;+constructor(@Inject(ErrorService) private readonly _errorService: ErrorService,- @IMessageService private readonly _messageService: IMessageService+ @IMessageService private readonly _messageService: IMessageService,+ @IPermissionService private readonly _permissionService: IPermissionService,+ @Inject(LocaleService) private readonly _localeService: LocaleService) {super();this.disposeWithMe(this._errorService.error$.subscribe((error) => {+ if (error.code === 'PERMISSION_DENIED') {+ if (!this._permissionService.getShowComponents()) {+ return;+ }+ const now = Date.now();+ const repeated = error.permissionTarget === this._lastPermissionTarget+ && now - this._lastPermissionAttempt < PERMISSION_MESSAGE_DURATION;+ this._lastPermissionAttempt = now;+ this._lastPermissionTarget = error.permissionTarget;+ if (!repeated) {+ this._messageService.show({+ id: PERMISSION_MESSAGE_ID,+ content: this._localeService.t('ui.objectPermission.operationDenied'),+ type: MessageType.Warning,+ duration: PERMISSION_MESSAGE_DURATION,+ });+ }+ return;+ }this._messageService.show({content: error.errorKey,type: MessageType.Error,});}));}++ override dispose(): void {+ this._messageService.remove(PERMISSION_MESSAGE_ID);+ super.dispose();+ }}diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.tsindex 81f5f7fbf3..2232064359 100644--- a/packages/ui/src/index.ts+++ b/packages/ui/src/index.ts@@ -21,6 +21,7 @@ export { ToggleShortcutPanelOperation } from './commands/operations/toggle-shortexport * from './common';export { getHeaderFooterMenuHiddenObservable, getMenuHiddenObservable } from './common/menu-hidden-observable';export { mergeMenuConfigs } from './common/menu-merge-configs';+export { objectPermissionMenuItemFactory } from './common/object-permission-menu';export { UI_PLUGIN_CONFIG_KEY } from './config/config';export type { IUniverUIConfig } from './config/config';export { MOBILE_UI_MODE, UNI_DISABLE_CHANGING_FOCUS_KEY } from './const';@@ -189,4 +190,10 @@ export { preventBrowserZoomInContainers } from './views/hooks/prevent-browser-zoexport * from './views/index';export { MobileMenu } from './views/menu/mobile/MobileMenu';export { type INotificationOptions } from './views/notification/Notification';++export { ObjectPermissionButton, openObjectPermissionDialog } from './views/object-permission/ObjectPermissionButton';+export type { IObjectPermissionButtonProps } from './views/object-permission/ObjectPermissionButton';++export { ObjectPermissionPanelButton, openObjectPermissionPanel } from './views/object-permission/ObjectPermissionPanel';+export { ProgressBar } from './views/progress-bar/ProgressBar';diff --git a/packages/ui/src/locale/ar-SA.ts b/packages/ui/src/locale/ar-SA.tsindex 7dde83beaf..4e08469365 100644--- a/packages/ui/src/locale/ar-SA.ts+++ b/packages/ui/src/locale/ar-SA.ts@@ -19,6 +19,64 @@ import emojiLocale from './emoji-locale/ar-SA.generated';const locale: typeof enUS = {ui: {+ objectPermission: {+ operationDenied: 'هذا المحتوى محمي. لا يُسمح بهذا الإجراء.',+ remove: 'إزالة الحماية',+ roleOwner: 'مالك الملف',+ roleEditor: 'محرر الملف',+ selectedCount: 'المحددون: {0}',+ searchPeople: 'البحث عن أشخاص',+ noMatchingPeople: 'لا يوجد أشخاص مطابقون',+ loadMore: 'تحميل المزيد',+ fileHint: 'تحدد مشاركة الملف العضوية. تقيد هذه الإعدادات إجراءات هؤلاء الأعضاء.',+ documentParent: 'تنطبق قيود تحرير المستند أيضًا على هذا القسم.',+ paragraphParent: 'تنطبق قيود تحرير المستند والقسم الذي يحتوي على هذه الفقرة أيضًا عليها.',+ documentObjectParent: 'قد تقيد أيضًا إعدادات المستند والأقسام والفقرات التي تحتوي على هذا الكائن أو تثبته عملية التحرير.',+ slideParent: 'تنطبق أيضًا قيود تحرير العرض التقديمي.',+ slideObjectParent: 'تنطبق أيضًا قيود تحرير العرض التقديمي والشريحة أو الشريحة الرئيسية التي تحتوي على هذا الكائن.',+ baseParent: 'تنطبق أيضًا قيود تحرير Base.',+ baseObjectParent: 'تنطبق أيضًا قيود تحرير Base والجدول الذي يحتوي على هذا الكائن.',+ recordParent: 'تظل قيود Base والجدول سارية. يتطلب تعديل قيمة أيضًا إذنًا لحقلها.',+ boardParent: 'تنطبق قيود تحرير اللوحة أيضًا على هذا الكائن.',+ ownerInherit: 'مالك الملف، وصول موروث',+ peopleError: 'تعذر تحميل الأشخاص. يرجى المحاولة مرة أخرى.',+ document: 'المستند',+ section: 'القسم',+ paragraph: 'الفقرة',+ entity: 'الكائن',+ presentation: 'العرض التقديمي',+ page: 'الشريحة',+ master: 'عرض الشريحة الرئيسية',+ base: 'Base',+ table: 'الجدول',+ field: 'الحقل',+ record: 'السجل',+ view: 'طريقة العرض',+ board: 'اللوحة',+ objectName: '{0}: {1}',++ search: 'البحث عن كائنات',+ empty: 'لا توجد كائنات مطابقة',+ more: 'يتم عرض أول 100 كائن. استخدم البحث لتضييق القائمة.',+ title: 'الأذونات',+ cancel: 'إلغاء',+ save: 'حفظ',+ saving: 'جارٍ الحفظ…',+ loading: 'جارٍ التحميل…',+ conflict: 'تم تغيير الأذونات. أعد التحميل قبل الحفظ.',+ error: 'تعذر تحميل الأذونات أو حفظها. تم الاحتفاظ بتغييراتك.',+ reload: 'إعادة التحميل',+ denied: 'لا يمكنك إدارة أذونات هذا الكائن.',+ edit: 'من يمكنه التحرير',+ all: 'جميع محرري الملف',+ owner: 'مالك الكائن فقط',+ members: 'أعضاء محددون',+ copy: 'السماح للمحررين بالنسخ',+ print: 'السماح للمحررين بالطباعة',+ export: 'السماح للمحررين بالتصدير',+ comment: 'السماح للمحررين بالتعليق',+ parentHint: 'تظل قيود الملف والكائن الأصل سارية.',+ },featureSearch: {title: 'بحث عن الميزات',placeholder: 'اكتب اسم ميزة أو قائمة...',diff --git a/packages/ui/src/locale/ca-ES.ts b/packages/ui/src/locale/ca-ES.tsindex c70c4bbb20..aefe250284 100644--- a/packages/ui/src/locale/ca-ES.ts+++ b/packages/ui/src/locale/ca-ES.ts@@ -19,6 +19,64 @@ import emojiLocale from './emoji-locale/ca-ES.generated';const locale: typeof enUS = {ui: {+ objectPermission: {+ operationDenied: 'Aquest contingut està protegit. No es pot fer aquesta acció.',+ remove: 'Elimina la protecció',+ roleOwner: 'Propietari del fitxer',+ roleEditor: 'Editor del fitxer',+ selectedCount: 'Seleccionats: {0}',+ searchPeople: 'Cerca persones',+ noMatchingPeople: 'No hi ha persones coincidents',+ loadMore: 'Carrega’n més',+ fileHint: 'La compartició del fitxer determina els membres. Aquests paràmetres limiten les accions d’aquests membres.',+ documentParent: 'Les restriccions d’edició del document també s’apliquen a aquesta secció.',+ paragraphParent: 'Les restriccions d’edició del document i de la secció que conté aquest paràgraf també s’hi apliquen.',+ documentObjectParent: 'El document i les seccions i paràgrafs que contenen o ancoren aquest objecte també poden restringir-ne l’edició.',+ slideParent: 'Les restriccions d’edició de la presentació també s’apliquen.',+ slideObjectParent: 'Les restriccions d’edició de la presentació i de la diapositiva o patró que conté aquest objecte també s’apliquen.',+ baseParent: 'Les restriccions d’edició de Base també s’apliquen.',+ baseObjectParent: 'Les restriccions d’edició de Base i de la taula que conté aquest objecte també s’apliquen.',+ recordParent: 'Les restriccions de Base i de la taula continuen vigents. Editar un valor també requereix permís per al seu camp.',+ boardParent: 'Les restriccions d’edició de la pissarra també s’apliquen a aquest objecte.',+ ownerInherit: 'Propietari del fitxer, accés heretat',+ peopleError: 'No s’han pogut carregar les persones. Torna-ho a provar.',+ document: 'Document',+ section: 'Secció',+ paragraph: 'Paràgraf',+ entity: 'Objecte',+ presentation: 'Presentació',+ page: 'Diapositiva',+ master: 'Vista del patró',+ base: 'Base',+ table: 'Taula',+ field: 'Camp',+ record: 'Registre',+ view: 'Vista',+ board: 'Pissarra',+ objectName: '{0}: {1}',++ search: 'Cerca objectes',+ empty: 'No hi ha objectes coincidents',+ more: 'Es mostren els primers 100 objectes. Fes servir la cerca per reduir la llista.',+ title: 'Permisos',+ cancel: 'Cancel·la',+ save: 'Desa',+ saving: 'S’està desant…',+ loading: 'S’està carregant…',+ conflict: 'Els permisos han canviat. Torna a carregar abans de desar.',+ error: 'No s’han pogut carregar o desar els permisos. S’han conservat els canvis.',+ reload: 'Torna a carregar',+ denied: 'No pots gestionar els permisos d’aquest objecte.',+ edit: 'Qui pot editar',+ all: 'Tots els editors del fitxer',+ owner: 'Només el propietari de l’objecte',+ members: 'Membres seleccionats',+ copy: 'Permet que els editors copiïn',+ print: 'Permet que els editors imprimeixin',+ export: 'Permet que els editors exportin',+ comment: 'Permet que els editors comentin',+ parentHint: 'Les restriccions del fitxer i de l’objecte superior continuen vigents.',+ },featureSearch: {title: 'Cerca funcions',placeholder: 'Escriviu una funció o un nom de menú...',diff --git a/packages/ui/src/locale/de-DE.ts b/packages/ui/src/locale/de-DE.tsindex e70cda9ba9..9eeb15ec88 100644--- a/packages/ui/src/locale/de-DE.ts+++ b/packages/ui/src/locale/de-DE.ts@@ -19,6 +19,64 @@ import emojiLocale from './emoji-locale/de-DE.generated';const locale: typeof enUS = {ui: {+ objectPermission: {+ operationDenied: 'Dieser Inhalt ist geschützt. Diese Aktion ist nicht erlaubt.',+ remove: 'Schutz entfernen',+ roleOwner: 'Dateieigentümer',+ roleEditor: 'Dateibearbeiter',+ selectedCount: 'Ausgewählt: {0}',+ searchPeople: 'Personen suchen',+ noMatchingPeople: 'Keine passenden Personen',+ loadMore: 'Mehr laden',+ fileHint: 'Die Dateifreigabe regelt die Mitgliedschaft. Diese Einstellungen schränken die Aktionen dieser Mitglieder ein.',+ documentParent: 'Die Bearbeitungseinschränkungen des Dokuments gelten auch für diesen Abschnitt.',+ paragraphParent: 'Die Bearbeitungseinschränkungen des Dokuments und des übergeordneten Abschnitts gelten auch für diesen Absatz.',+ documentObjectParent: 'Das Dokument sowie die Abschnitte und Absätze, die dieses Objekt enthalten oder verankern, können die Bearbeitung ebenfalls einschränken.',+ slideParent: 'Die Bearbeitungseinschränkungen der Präsentation gelten ebenfalls.',+ slideObjectParent: 'Die Bearbeitungseinschränkungen der Präsentation und der übergeordneten Folie oder des Masters gelten ebenfalls.',+ baseParent: 'Die Bearbeitungseinschränkungen von Base gelten ebenfalls.',+ baseObjectParent: 'Die Bearbeitungseinschränkungen von Base und der übergeordneten Tabelle gelten ebenfalls.',+ recordParent: 'Die Einschränkungen von Base und der Tabelle gelten weiterhin. Zum Bearbeiten eines Werts ist auch eine Berechtigung für das zugehörige Feld erforderlich.',+ boardParent: 'Die Bearbeitungseinschränkungen des Boards gelten auch für dieses Objekt.',+ ownerInherit: 'Dateieigentümer, geerbter Zugriff',+ peopleError: 'Personen konnten nicht geladen werden. Bitte versuchen Sie es erneut.',+ document: 'Dokument',+ section: 'Abschnitt',+ paragraph: 'Absatz',+ entity: 'Objekt',+ presentation: 'Präsentation',+ page: 'Folie',+ master: 'Masteransicht',+ base: 'Base',+ table: 'Tabelle',+ field: 'Feld',+ record: 'Datensatz',+ view: 'Ansicht',+ board: 'Board',+ objectName: '{0}: {1}',++ search: 'Objekte suchen',+ empty: 'Keine passenden Objekte',+ more: 'Die ersten 100 Objekte werden angezeigt. Grenzen Sie die Liste mit der Suche ein.',+ title: 'Berechtigungen',+ cancel: 'Abbrechen',+ save: 'Speichern',+ saving: 'Wird gespeichert…',+ loading: 'Wird geladen…',+ conflict: 'Die Berechtigungen wurden geändert. Laden Sie vor dem Speichern neu.',+ error: 'Berechtigungen konnten nicht geladen oder gespeichert werden. Ihre Änderungen wurden beibehalten.',+ reload: 'Neu laden',+ denied: 'Sie können die Berechtigungen für dieses Objekt nicht verwalten.',+ edit: 'Wer darf bearbeiten',+ all: 'Alle Dateibearbeiter',+ owner: 'Nur der Objekteigentümer',+ members: 'Ausgewählte Mitglieder',+ copy: 'Bearbeitern das Kopieren erlauben',+ print: 'Bearbeitern das Drucken erlauben',+ export: 'Bearbeitern das Exportieren erlauben',+ comment: 'Bearbeitern das Kommentieren erlauben',+ parentHint: 'Die Einschränkungen der Datei und des übergeordneten Objekts gelten weiterhin.',+ },featureSearch: {title: 'Funktionen suchen',placeholder: 'Funktion oder Menüname eingeben...',diff --git a/packages/ui/src/locale/en-US.ts b/packages/ui/src/locale/en-US.tsindex 62c81e8579..9c21801d6e 100644--- a/packages/ui/src/locale/en-US.ts+++ b/packages/ui/src/locale/en-US.ts@@ -18,6 +18,64 @@ import emojiLocale from './emoji-locale/en-US.generated';const locale = {ui: {+ objectPermission: {+ operationDenied: 'This content is protected. This action is not allowed.',+ remove: 'Remove protection',+ roleOwner: 'File owner',+ roleEditor: 'File editor',+ selectedCount: 'Selected: {0}',+ searchPeople: 'Search people',+ noMatchingPeople: 'No matching people',+ loadMore: 'Load more',+ fileHint: 'File sharing controls membership. These settings restrict actions within that membership.',+ documentParent: 'Document editing restrictions also apply to this section.',+ paragraphParent: 'Document and containing section editing restrictions also apply to this paragraph.',+ documentObjectParent: 'Document and the sections and paragraphs containing or anchoring this object may also restrict editing.',+ slideParent: 'Presentation editing restrictions also apply.',+ slideObjectParent: 'Presentation and the containing page or master editing restrictions also apply.',+ baseParent: 'Base editing restrictions also apply.',+ baseObjectParent: 'Base and containing table editing restrictions also apply.',+ recordParent: 'Base and table restrictions still apply. Editing a value also requires permission for its field.',+ boardParent: 'Board editing restrictions also apply to this object.',+ ownerInherit: 'File owner, inherited access',+ peopleError: 'Could not load people. Please retry.',+ document: 'Document',+ section: 'Section',+ paragraph: 'Paragraph',+ entity: 'Object',+ presentation: 'Presentation',+ page: 'Slide',+ master: 'Master view',+ base: 'Base',+ table: 'Table',+ field: 'Field',+ record: 'Record',+ view: 'View',+ board: 'Board',+ objectName: '{0}: {1}',++ search: 'Search objects',+ empty: 'No matching objects',+ more: 'Showing the first 100 objects. Search to narrow the list.',+ title: 'Permissions',+ cancel: 'Cancel',+ save: 'Save',+ saving: 'Saving…',+ loading: 'Loading…',+ conflict: 'Permissions changed. Reload before saving.',+ error: 'Could not load or save permissions. Your changes have been kept.',+ reload: 'Reload',+ denied: 'You cannot manage permissions for this object.',+ edit: 'Who can edit',+ all: 'All file editors',+ owner: 'Object owner only',+ members: 'Selected members',+ copy: 'Allow editors to copy',+ print: 'Allow editors to print',+ export: 'Allow editors to export',+ comment: 'Allow editors to comment',+ parentHint: 'File and parent object restrictions still apply.',+ },featureSearch: {title: 'Search features',placeholder: 'Type a feature or menu name...',diff --git a/packages/ui/src/locale/es-ES.ts b/packages/ui/src/locale/es-ES.tsindex 900451ad63..125f973d3b 100644--- a/packages/ui/src/locale/es-ES.ts+++ b/packages/ui/src/locale/es-ES.ts@@ -19,6 +19,64 @@ import emojiLocale from './emoji-locale/es-ES.generated';const locale: typeof enUS = {ui: {+ objectPermission: {+ operationDenied: 'Este contenido está protegido. No se permite esta acción.',+ remove: 'Eliminar protección',+ roleOwner: 'Propietario del archivo',+ roleEditor: 'Editor del archivo',+ selectedCount: 'Seleccionados: {0}',+ searchPeople: 'Buscar personas',+ noMatchingPeople: 'No hay personas que coincidan',+ loadMore: 'Cargar más',+ fileHint: 'El uso compartido del archivo determina los miembros. Estos ajustes limitan las acciones de esos miembros.',+ documentParent: 'Las restricciones de edición del documento también se aplican a esta sección.',+ paragraphParent: 'Las restricciones de edición del documento y de la sección que contiene este párrafo también se aplican.',+ documentObjectParent: 'El documento y las secciones y párrafos que contienen o anclan este objeto también pueden restringir su edición.',+ slideParent: 'Las restricciones de edición de la presentación también se aplican.',+ slideObjectParent: 'Las restricciones de edición de la presentación y de la diapositiva o patrón que contiene este objeto también se aplican.',+ baseParent: 'Las restricciones de edición de Base también se aplican.',+ baseObjectParent: 'Las restricciones de edición de Base y de la tabla que contiene este objeto también se aplican.',+ recordParent: 'Las restricciones de Base y de la tabla siguen aplicándose. Editar un valor también requiere permiso para su campo.',+ boardParent: 'Las restricciones de edición de la pizarra también se aplican a este objeto.',+ ownerInherit: 'Propietario del archivo, acceso heredado',+ peopleError: 'No se pudieron cargar las personas. Vuelve a intentarlo.',+ document: 'Documento',+ section: 'Sección',+ paragraph: 'Párrafo',+ entity: 'Objeto',+ presentation: 'Presentación',+ page: 'Diapositiva',+ master: 'Vista de patrón',+ base: 'Base',+ table: 'Tabla',+ field: 'Campo',+ record: 'Registro',+ view: 'Vista',+ board: 'Pizarra',+ objectName: '{0}: {1}',++ search: 'Buscar objetos',+ empty: 'No hay objetos que coincidan',+ more: 'Se muestran los primeros 100 objetos. Usa la búsqueda para acotar la lista.',+ title: 'Permisos',+ cancel: 'Cancelar',+ save: 'Guardar',+ saving: 'Guardando…',+ loading: 'Cargando…',+ conflict: 'Los permisos han cambiado. Vuelve a cargar antes de guardar.',+ error: 'No se pudieron cargar o guardar los permisos. Se han conservado tus cambios.',+ reload: 'Volver a cargar',+ denied: 'No puedes gestionar los permisos de este objeto.',+ edit: 'Quién puede editar',+ all: 'Todos los editores del archivo',+ owner: 'Solo el propietario del objeto',+ members: 'Miembros seleccionados',+ copy: 'Permitir que los editores copien',+ print: 'Permitir que los editores impriman',+ export: 'Permitir que los editores exporten',+ comment: 'Permitir que los editores comenten',+ parentHint: 'Las restricciones del archivo y del objeto superior siguen aplicándose.',+ },featureSearch: {title: 'Buscar funciones',placeholder: 'Escribe una función o nombre de menú...',diff --git a/packages/ui/src/locale/fa-IR.ts b/packages/ui/src/locale/fa-IR.tsindex 6fccbac47a..cf8073cfaa 100644--- a/packages/ui/src/locale/fa-IR.ts+++ b/packages/ui/src/locale/fa-IR.ts@@ -19,6 +19,64 @@ import emojiLocale from './emoji-locale/fa-IR.generated';const locale: typeof enUS = {ui: {+ objectPermission: {+ operationDenied: 'این محتوا محافظت شده است. انجام این عملیات مجاز نیست.',+ remove: 'حذف محافظت',+ roleOwner: 'مالک فایل',+ roleEditor: 'ویرایشگر فایل',+ selectedCount: 'انتخابشده: {0}',+ searchPeople: 'جستجوی افراد',+ noMatchingPeople: 'فردی مطابق جستجو یافت نشد',+ loadMore: 'بارگذاری بیشتر',+ fileHint: 'اشتراکگذاری فایل، اعضا را تعیین میکند. این تنظیمات اقدامات همان اعضا را محدود میکنند.',+ documentParent: 'محدودیتهای ویرایش سند برای این بخش نیز اعمال میشوند.',+ paragraphParent: 'محدودیتهای ویرایش سند و بخش دربرگیرندهٔ این بند، برای این بند نیز اعمال میشوند.',+ documentObjectParent: 'سند و بخشها و بندهایی که این شیء را دربر میگیرند یا محل اتصال آن هستند، ممکن است ویرایش را نیز محدود کنند.',+ slideParent: 'محدودیتهای ویرایش ارائه نیز اعمال میشوند.',+ slideObjectParent: 'محدودیتهای ویرایش ارائه و اسلاید یا الگوی دربرگیرندهٔ این شیء نیز اعمال میشوند.',+ baseParent: 'محدودیتهای ویرایش Base نیز اعمال میشوند.',+ baseObjectParent: 'محدودیتهای ویرایش Base و جدول دربرگیرندهٔ این شیء نیز اعمال میشوند.',+ recordParent: 'محدودیتهای Base و جدول همچنان اعمال میشوند. ویرایش مقدار به مجوز فیلد مربوطه نیز نیاز دارد.',+ boardParent: 'محدودیتهای ویرایش تخته برای این شیء نیز اعمال میشوند.',+ ownerInherit: 'مالک فایل، دسترسی بهارثرسیده',+ peopleError: 'بارگذاری افراد ممکن نشد. دوباره تلاش کنید.',+ document: 'سند',+ section: 'بخش',+ paragraph: 'بند',+ entity: 'شیء',+ presentation: 'ارائه',+ page: 'اسلاید',+ master: 'نمای الگو',+ base: 'Base',+ table: 'جدول',+ field: 'فیلد',+ record: 'رکورد',+ view: 'نما',+ board: 'تخته',+ objectName: '{0}: {1}',++ search: 'جستجوی اشیا',+ empty: 'شیئی مطابق جستجو یافت نشد',+ more: '۱۰۰ شیء نخست نمایش داده میشوند. برای محدود کردن فهرست جستجو کنید.',+ title: 'مجوزها',+ cancel: 'لغو',+ save: 'ذخیره',+ saving: 'در حال ذخیره…',+ loading: 'در حال بارگذاری…',+ conflict: 'مجوزها تغییر کردهاند. پیش از ذخیره دوباره بارگذاری کنید.',+ error: 'بارگذاری یا ذخیرهٔ مجوزها ممکن نشد. تغییرات شما حفظ شدهاند.',+ reload: 'بارگذاری مجدد',+ denied: 'نمیتوانید مجوزهای این شیء را مدیریت کنید.',+ edit: 'چه کسانی میتوانند ویرایش کنند',+ all: 'همهٔ ویرایشگران فایل',+ owner: 'فقط مالک شیء',+ members: 'اعضای انتخابشده',+ copy: 'اجازهٔ کپی به ویرایشگران',+ print: 'اجازهٔ چاپ به ویرایشگران',+ export: 'اجازهٔ خروجی گرفتن به ویرایشگران',+ comment: 'اجازهٔ نظر دادن به ویرایشگران',+ parentHint: 'محدودیتهای فایل و شیء والد همچنان اعمال میشوند.',+ },featureSearch: {title: 'جستجوی قابلیتها',placeholder: 'نام قابلیت یا منو را وارد کنید…',diff --git a/packages/ui/src/locale/fr-FR.ts b/packages/ui/src/locale/fr-FR.tsindex e9f4e0ca29..8eb943275e 100644--- a/packages/ui/src/locale/fr-FR.ts+++ b/packages/ui/src/locale/fr-FR.ts@@ -19,6 +19,64 @@ import emojiLocale from './emoji-locale/fr-FR.generated';const locale: typeof enUS = {ui: {+ objectPermission: {+ operationDenied: 'Ce contenu est protégé. Cette action est interdite.',+ remove: 'Supprimer la protection',+ roleOwner: 'Propriétaire du fichier',+ roleEditor: 'Éditeur du fichier',+ selectedCount: 'Sélectionnés : {0}',+ searchPeople: 'Rechercher des personnes',+ noMatchingPeople: 'Aucune personne correspondante',+ loadMore: 'Charger plus',+ fileHint: 'Le partage du fichier détermine les membres. Ces paramètres limitent les actions de ces membres.',+ documentParent: 'Les restrictions de modification du document s’appliquent également à cette section.',+ paragraphParent: 'Les restrictions de modification du document et de la section contenant ce paragraphe s’appliquent également.',+ documentObjectParent: 'Le document ainsi que les sections et paragraphes contenant ou ancrant cet objet peuvent également limiter sa modification.',+ slideParent: 'Les restrictions de modification de la présentation s’appliquent également.',+ slideObjectParent: 'Les restrictions de modification de la présentation et de la diapositive ou du masque contenant cet objet s’appliquent également.',+ baseParent: 'Les restrictions de modification de Base s’appliquent également.',+ baseObjectParent: 'Les restrictions de modification de Base et de la table contenant cet objet s’appliquent également.',+ recordParent: 'Les restrictions de Base et de la table restent applicables. Modifier une valeur nécessite également une autorisation sur son champ.',+ boardParent: 'Les restrictions de modification du tableau blanc s’appliquent également à cet objet.',+ ownerInherit: 'Propriétaire du fichier, accès hérité',+ peopleError: 'Impossible de charger les personnes. Veuillez réessayer.',+ document: 'Document',+ section: 'Section',+ paragraph: 'Paragraphe',+ entity: 'Objet',+ presentation: 'Présentation',+ page: 'Diapositive',+ master: 'Vue du masque',+ base: 'Base',+ table: 'Table',+ field: 'Champ',+ record: 'Enregistrement',+ view: 'Vue',+ board: 'Tableau blanc',+ objectName: '{0}: {1}',++ search: 'Rechercher des objets',+ empty: 'Aucun objet correspondant',+ more: 'Affichage des 100 premiers objets. Utilisez la recherche pour affiner la liste.',+ title: 'Autorisations',+ cancel: 'Annuler',+ save: 'Enregistrer',+ saving: 'Enregistrement…',+ loading: 'Chargement…',+ conflict: 'Les autorisations ont changé. Rechargez avant d’enregistrer.',+ error: 'Impossible de charger ou d’enregistrer les autorisations. Vos modifications ont été conservées.',+ reload: 'Recharger',+ denied: 'Vous ne pouvez pas gérer les autorisations de cet objet.',+ edit: 'Qui peut modifier',+ all: 'Tous les éditeurs du fichier',+ owner: 'Propriétaire de l’objet uniquement',+ members: 'Membres sélectionnés',+ copy: 'Autoriser les éditeurs à copier',+ print: 'Autoriser les éditeurs à imprimer',+ export: 'Autoriser les éditeurs à exporter',+ comment: 'Autoriser les éditeurs à commenter',+ parentHint: 'Les restrictions du fichier et de l’objet parent restent applicables.',+ },featureSearch: {title: 'Rechercher des fonctionnalités',placeholder: 'Saisissez une fonctionnalité ou un nom de menu...',diff --git a/packages/ui/src/locale/id-ID.ts b/packages/ui/src/locale/id-ID.tsindex 1e4618bec0..34deb28023 100644--- a/packages/ui/src/locale/id-ID.ts+++ b/packages/ui/src/locale/id-ID.ts@@ -19,6 +19,64 @@ import emojiLocale from './emoji-locale/id-ID.generated';const locale: typeof enUS = {ui: {+ objectPermission: {+ operationDenied: 'Konten ini dilindungi. Tindakan ini tidak diizinkan.',+ remove: 'Hapus perlindungan',+ roleOwner: 'Pemilik file',+ roleEditor: 'Editor file',+ selectedCount: 'Dipilih: {0}',+ searchPeople: 'Cari pengguna',+ noMatchingPeople: 'Tidak ada pengguna yang cocok',+ loadMore: 'Muat lebih banyak',+ fileHint: 'Berbagi file mengatur keanggotaan. Pengaturan ini membatasi tindakan anggota tersebut.',+ documentParent: 'Pembatasan pengeditan dokumen juga berlaku untuk bagian ini.',+ paragraphParent: 'Pembatasan pengeditan dokumen dan bagian yang memuat paragraf ini juga berlaku.',+ documentObjectParent: 'Dokumen serta bagian dan paragraf yang memuat atau menjadi jangkar objek ini juga dapat membatasi pengeditan.',+ slideParent: 'Pembatasan pengeditan presentasi juga berlaku.',+ slideObjectParent: 'Pembatasan pengeditan presentasi dan slide atau master yang memuat objek ini juga berlaku.',+ baseParent: 'Pembatasan pengeditan Base juga berlaku.',+ baseObjectParent: 'Pembatasan pengeditan Base dan tabel yang memuat objek ini juga berlaku.',+ recordParent: 'Pembatasan Base dan tabel tetap berlaku. Mengedit nilai juga memerlukan izin untuk kolomnya.',+ boardParent: 'Pembatasan pengeditan papan juga berlaku untuk objek ini.',+ ownerInherit: 'Pemilik file, akses yang diwariskan',+ peopleError: 'Tidak dapat memuat pengguna. Silakan coba lagi.',+ document: 'Dokumen',+ section: 'Bagian',+ paragraph: 'Paragraf',+ entity: 'Objek',+ presentation: 'Presentasi',+ page: 'Slide',+ master: 'Tampilan master',+ base: 'Base',+ table: 'Tabel',+ field: 'Kolom',+ record: 'Rekaman',+ view: 'Tampilan',+ board: 'Papan',+ objectName: '{0}: {1}',++ search: 'Cari objek',+ empty: 'Tidak ada objek yang cocok',+ more: 'Menampilkan 100 objek pertama. Cari untuk mempersempit daftar.',+ title: 'Izin',+ cancel: 'Batal',+ save: 'Simpan',+ saving: 'Menyimpan…',+ loading: 'Memuat…',+ conflict: 'Izin telah berubah. Muat ulang sebelum menyimpan.',+ error: 'Tidak dapat memuat atau menyimpan izin. Perubahan Anda tetap disimpan.',+ reload: 'Muat ulang',+ denied: 'Anda tidak dapat mengelola izin untuk objek ini.',+ edit: 'Siapa yang dapat mengedit',+ all: 'Semua editor file',+ owner: 'Hanya pemilik objek',+ members: 'Anggota yang dipilih',+ copy: 'Izinkan editor menyalin',+ print: 'Izinkan editor mencetak',+ export: 'Izinkan editor mengekspor',+ comment: 'Izinkan editor berkomentar',+ parentHint: 'Pembatasan file dan objek induk tetap berlaku.',+ },featureSearch: {title: 'Cari fitur',placeholder: 'Ketik nama fitur atau menu...',diff --git a/packages/ui/src/locale/it-IT.ts b/packages/ui/src/locale/it-IT.tsindex 4153ef0b9b..dd57a5192e 100644--- a/packages/ui/src/locale/it-IT.ts+++ b/packages/ui/src/locale/it-IT.ts@@ -19,6 +19,64 @@ import emojiLocale from './emoji-locale/it-IT.generated';const locale: typeof enUS = {ui: {+ objectPermission: {+ operationDenied: 'Questo contenuto è protetto. Questa azione non è consentita.',+ remove: 'Rimuovi protezione',+ roleOwner: 'Proprietario del file',+ roleEditor: 'Editor del file',+ selectedCount: 'Selezionati: {0}',+ searchPeople: 'Cerca persone',+ noMatchingPeople: 'Nessuna persona corrispondente',+ loadMore: 'Carica altro',+ fileHint: 'La condivisione del file determina i membri. Queste impostazioni limitano le azioni di tali membri.',+ documentParent: 'Le restrizioni di modifica del documento si applicano anche a questa sezione.',+ paragraphParent: 'Le restrizioni di modifica del documento e della sezione che contiene questo paragrafo si applicano anche al paragrafo.',+ documentObjectParent: 'Il documento e le sezioni e i paragrafi che contengono o ancorano questo oggetto possono limitarne la modifica.',+ slideParent: 'Si applicano anche le restrizioni di modifica della presentazione.',+ slideObjectParent: 'Si applicano anche le restrizioni di modifica della presentazione e della diapositiva o dello schema che contiene questo oggetto.',+ baseParent: 'Si applicano anche le restrizioni di modifica di Base.',+ baseObjectParent: 'Si applicano anche le restrizioni di modifica di Base e della tabella che contiene questo oggetto.',+ recordParent: 'Le restrizioni di Base e della tabella restano valide. La modifica di un valore richiede anche l’autorizzazione per il relativo campo.',+ boardParent: 'Le restrizioni di modifica della lavagna si applicano anche a questo oggetto.',+ ownerInherit: 'Proprietario del file, accesso ereditato',+ peopleError: 'Impossibile caricare le persone. Riprova.',+ document: 'Documento',+ section: 'Sezione',+ paragraph: 'Paragrafo',+ entity: 'Oggetto',+ presentation: 'Presentazione',+ page: 'Diapositiva',+ master: 'Visualizzazione schema',+ base: 'Base',+ table: 'Tabella',+ field: 'Campo',+ record: 'Record',+ view: 'Visualizzazione',+ board: 'Lavagna',+ objectName: '{0}: {1}',++ search: 'Cerca oggetti',+ empty: 'Nessun oggetto corrispondente',+ more: 'Sono visualizzati i primi 100 oggetti. Usa la ricerca per restringere l’elenco.',+ title: 'Autorizzazioni',+ cancel: 'Annulla',+ save: 'Salva',+ saving: 'Salvataggio…',+ loading: 'Caricamento…',+ conflict: 'Le autorizzazioni sono cambiate. Ricarica prima di salvare.',+ error: 'Impossibile caricare o salvare le autorizzazioni. Le modifiche sono state conservate.',+ reload: 'Ricarica',+ denied: 'Non puoi gestire le autorizzazioni di questo oggetto.',+ edit: 'Chi può modificare',+ all: 'Tutti gli editor del file',+ owner: 'Solo il proprietario dell’oggetto',+ members: 'Membri selezionati',+ copy: 'Consenti agli editor di copiare',+ print: 'Consenti agli editor di stampare',+ export: 'Consenti agli editor di esportare',+ comment: 'Consenti agli editor di commentare',+ parentHint: 'Le restrizioni del file e dell’oggetto padre restano valide.',+ },featureSearch: {title: 'Cerca funzionalità',placeholder: 'Digita una funzionalità o il nome di un menu...',diff --git a/packages/ui/src/locale/ja-JP.ts b/packages/ui/src/locale/ja-JP.tsindex 105c07e1ef..b81d04fc77 100644--- a/packages/ui/src/locale/ja-JP.ts+++ b/packages/ui/src/locale/ja-JP.ts@@ -19,6 +19,64 @@ import emojiLocale from './emoji-locale/ja-JP.generated';const locale: typeof enUS = {ui: {+ objectPermission: {+ operationDenied: 'このコンテンツは保護されているため、操作できません。',+ remove: '保護を削除',+ roleOwner: 'ファイル所有者',+ roleEditor: 'ファイル編集者',+ selectedCount: '選択済み: {0}',+ searchPeople: 'ユーザーを検索',+ noMatchingPeople: '一致するユーザーはいません',+ loadMore: 'さらに読み込む',+ fileHint: 'メンバーはファイルの共有設定で管理します。これらの設定はメンバーの操作を制限します。',+ documentParent: 'このセクションには文書の編集制限も適用されます。',+ paragraphParent: 'この段落には文書と所属するセクションの編集制限も適用されます。',+ documentObjectParent: '文書、およびこのオブジェクトを含むか固定先となるセクションや段落の編集制限も適用される場合があります。',+ slideParent: 'プレゼンテーションの編集制限も適用されます。',+ slideObjectParent: 'プレゼンテーションと所属するスライドまたはマスターの編集制限も適用されます。',+ baseParent: 'Base の編集制限も適用されます。',+ baseObjectParent: 'Base と所属するテーブルの編集制限も適用されます。',+ recordParent: 'Base とテーブルの制限も適用されます。値の編集にはフィールドの権限も必要です。',+ boardParent: 'このオブジェクトにはボードの編集制限も適用されます。',+ ownerInherit: 'ファイル所有者、継承されたアクセス権',+ peopleError: 'ユーザーを読み込めませんでした。再試行してください。',+ document: '文書',+ section: 'セクション',+ paragraph: '段落',+ entity: 'オブジェクト',+ presentation: 'プレゼンテーション',+ page: 'スライド',+ master: 'マスタービュー',+ base: 'Base',+ table: 'テーブル',+ field: 'フィールド',+ record: 'レコード',+ view: 'ビュー',+ board: 'ボード',+ objectName: '{0}: {1}',++ search: 'オブジェクトを検索',+ empty: '一致するオブジェクトはありません',+ more: '最初の 100 件を表示しています。検索して絞り込んでください。',+ title: '権限',+ cancel: 'キャンセル',+ save: '保存',+ saving: '保存中…',+ loading: '読み込み中…',+ conflict: '権限が変更されました。保存する前に再読み込みしてください。',+ error: '権限を読み込みまたは保存できませんでした。変更内容は保持されています。',+ reload: '再読み込み',+ denied: 'このオブジェクトの権限を管理することはできません。',+ edit: '編集できるユーザー',+ all: 'すべてのファイル編集者',+ owner: 'オブジェクト所有者のみ',+ members: '選択したメンバー',+ copy: '編集者によるコピーを許可',+ print: '編集者による印刷を許可',+ export: '編集者によるエクスポートを許可',+ comment: '編集者によるコメントを許可',+ parentHint: 'ファイルと親オブジェクトの制限も適用されます。',+ },featureSearch: {title: '機能を検索',placeholder: '機能またはメニュー名を入力…',diff --git a/packages/ui/src/locale/ko-KR.ts b/packages/ui/src/locale/ko-KR.tsindex 109782763b..de7882815c 100644--- a/packages/ui/src/locale/ko-KR.ts+++ b/packages/ui/src/locale/ko-KR.ts@@ -19,6 +19,64 @@ import emojiLocale from './emoji-locale/ko-KR.generated';const locale: typeof enUS = {ui: {+ objectPermission: {+ operationDenied: '이 콘텐츠는 보호되어 있어 작업을 수행할 수 없습니다.',+ remove: '보호 삭제',+ roleOwner: '파일 소유자',+ roleEditor: '파일 편집자',+ selectedCount: '선택됨: {0}',+ searchPeople: '사용자 검색',+ noMatchingPeople: '일치하는 사용자가 없습니다',+ loadMore: '더 불러오기',+ fileHint: '파일 공유 설정에서 구성원을 관리합니다. 이 설정은 해당 구성원의 작업을 제한합니다.',+ documentParent: '이 섹션에는 문서 편집 제한도 적용됩니다.',+ paragraphParent: '이 단락에는 문서와 상위 섹션의 편집 제한도 적용됩니다.',+ documentObjectParent: '문서와 이 개체를 포함하거나 고정하는 섹션 및 단락의 편집 제한도 적용될 수 있습니다.',+ slideParent: '프레젠테이션 편집 제한도 적용됩니다.',+ slideObjectParent: '프레젠테이션과 상위 슬라이드 또는 마스터의 편집 제한도 적용됩니다.',+ baseParent: 'Base 편집 제한도 적용됩니다.',+ baseObjectParent: 'Base와 상위 테이블의 편집 제한도 적용됩니다.',+ recordParent: 'Base와 테이블 제한도 적용됩니다. 값을 편집하려면 해당 필드의 권한도 필요합니다.',+ boardParent: '이 개체에는 보드 편집 제한도 적용됩니다.',+ ownerInherit: '파일 소유자, 상속된 액세스 권한',+ peopleError: '사용자를 불러올 수 없습니다. 다시 시도하세요.',+ document: '문서',+ section: '섹션',+ paragraph: '단락',+ entity: '개체',+ presentation: '프레젠테이션',+ page: '슬라이드',+ master: '마스터 보기',+ base: 'Base',+ table: '테이블',+ field: '필드',+ record: '레코드',+ view: '보기',+ board: '보드',+ objectName: '{0}: {1}',++ search: '개체 검색',+ empty: '일치하는 개체가 없습니다',+ more: '처음 100개 개체를 표시합니다. 검색하여 목록을 좁히세요.',+ title: '권한',+ cancel: '취소',+ save: '저장',+ saving: '저장 중…',+ loading: '불러오는 중…',+ conflict: '권한이 변경되었습니다. 저장하기 전에 새로고침하세요.',+ error: '권한을 불러오거나 저장할 수 없습니다. 변경 사항은 유지됩니다.',+ reload: '새로고침',+ denied: '이 개체의 권한을 관리할 수 없습니다.',+ edit: '편집할 수 있는 사용자',+ all: '모든 파일 편집자',+ owner: '개체 소유자만',+ members: '선택한 구성원',+ copy: '편집자의 복사 허용',+ print: '편집자의 인쇄 허용',+ export: '편집자의 내보내기 허용',+ comment: '편집자의 댓글 허용',+ parentHint: '파일 및 상위 개체의 제한도 적용됩니다.',+ },featureSearch: {title: '기능 검색',placeholder: '기능 또는 메뉴 이름 입력...',diff --git a/packages/ui/src/locale/pl-PL.ts b/packages/ui/src/locale/pl-PL.tsindex 0bf8ced7e3..d6ffc0d172 100644--- a/packages/ui/src/locale/pl-PL.ts+++ b/packages/ui/src/locale/pl-PL.ts@@ -19,6 +19,64 @@ import emojiLocale from './emoji-locale/pl-PL.generated';const locale: typeof enUS = {ui: {+ objectPermission: {+ operationDenied: 'Ta treść jest chroniona. Nie można wykonać tej czynności.',+ remove: 'Usuń ochronę',+ roleOwner: 'Właściciel pliku',+ roleEditor: 'Edytor pliku',+ selectedCount: 'Wybrano: {0}',+ searchPeople: 'Szukaj osób',+ noMatchingPeople: 'Brak pasujących osób',+ loadMore: 'Wczytaj więcej',+ fileHint: 'Udostępnianie pliku określa członkostwo. Te ustawienia ograniczają działania tych członków.',+ documentParent: 'Ograniczenia edycji dokumentu dotyczą również tej sekcji.',+ paragraphParent: 'Ograniczenia edycji dokumentu i sekcji zawierającej ten akapit dotyczą również tego akapitu.',+ documentObjectParent: 'Dokument oraz sekcje i akapity zawierające ten obiekt lub stanowiące jego zakotwiczenie również mogą ograniczać edycję.',+ slideParent: 'Ograniczenia edycji prezentacji również obowiązują.',+ slideObjectParent: 'Ograniczenia edycji prezentacji oraz slajdu lub wzorca zawierającego ten obiekt również obowiązują.',+ baseParent: 'Ograniczenia edycji Base również obowiązują.',+ baseObjectParent: 'Ograniczenia edycji Base i tabeli zawierającej ten obiekt również obowiązują.',+ recordParent: 'Ograniczenia Base i tabeli nadal obowiązują. Edycja wartości wymaga także uprawnienia do odpowiedniego pola.',+ boardParent: 'Ograniczenia edycji tablicy dotyczą również tego obiektu.',+ ownerInherit: 'Właściciel pliku, odziedziczony dostęp',+ peopleError: 'Nie udało się wczytać osób. Spróbuj ponownie.',+ document: 'Dokument',+ section: 'Sekcja',+ paragraph: 'Akapit',+ entity: 'Obiekt',+ presentation: 'Prezentacja',+ page: 'Slajd',+ master: 'Widok wzorca',+ base: 'Base',+ table: 'Tabela',+ field: 'Pole',+ record: 'Rekord',+ view: 'Widok',+ board: 'Tablica',+ objectName: '{0}: {1}',++ search: 'Szukaj obiektów',+ empty: 'Brak pasujących obiektów',+ more: 'Wyświetlono pierwszych 100 obiektów. Użyj wyszukiwania, aby zawęzić listę.',+ title: 'Uprawnienia',+ cancel: 'Anuluj',+ save: 'Zapisz',+ saving: 'Zapisywanie…',+ loading: 'Wczytywanie…',+ conflict: 'Uprawnienia uległy zmianie. Wczytaj ponownie przed zapisaniem.',+ error: 'Nie udało się wczytać lub zapisać uprawnień. Twoje zmiany zostały zachowane.',+ reload: 'Wczytaj ponownie',+ denied: 'Nie możesz zarządzać uprawnieniami tego obiektu.',+ edit: 'Kto może edytować',+ all: 'Wszyscy edytorzy pliku',+ owner: 'Tylko właściciel obiektu',+ members: 'Wybrani członkowie',+ copy: 'Zezwól edytorom na kopiowanie',+ print: 'Zezwól edytorom na drukowanie',+ export: 'Zezwól edytorom na eksportowanie',+ comment: 'Zezwól edytorom na komentowanie',+ parentHint: 'Ograniczenia pliku i obiektu nadrzędnego nadal obowiązują.',+ },featureSearch: {title: 'Wyszukaj funkcje',placeholder: 'Wpisz nazwę funkcji lub menu...',diff --git a/packages/ui/src/locale/pt-BR.ts b/packages/ui/src/locale/pt-BR.tsindex b39f73505f..d7ec77f6f4 100644--- a/packages/ui/src/locale/pt-BR.ts+++ b/packages/ui/src/locale/pt-BR.ts@@ -19,6 +19,64 @@ import emojiLocale from './emoji-locale/pt-BR.generated';const locale: typeof enUS = {ui: {+ objectPermission: {+ operationDenied: 'Este conteúdo está protegido. Esta ação não é permitida.',+ remove: 'Remover proteção',+ roleOwner: 'Proprietário do arquivo',+ roleEditor: 'Editor do arquivo',+ selectedCount: 'Selecionados: {0}',+ searchPeople: 'Buscar pessoas',+ noMatchingPeople: 'Nenhuma pessoa correspondente',+ loadMore: 'Carregar mais',+ fileHint: 'O compartilhamento do arquivo define os membros. Estas configurações restringem as ações desses membros.',+ documentParent: 'As restrições de edição do documento também se aplicam a esta seção.',+ paragraphParent: 'As restrições de edição do documento e da seção que contém este parágrafo também se aplicam.',+ documentObjectParent: 'O documento e as seções e parágrafos que contêm ou ancoram este objeto também podem restringir sua edição.',+ slideParent: 'As restrições de edição da apresentação também se aplicam.',+ slideObjectParent: 'As restrições de edição da apresentação e do slide ou mestre que contém este objeto também se aplicam.',+ baseParent: 'As restrições de edição do Base também se aplicam.',+ baseObjectParent: 'As restrições de edição do Base e da tabela que contém este objeto também se aplicam.',+ recordParent: 'As restrições do Base e da tabela continuam válidas. Editar um valor também requer permissão para seu campo.',+ boardParent: 'As restrições de edição do quadro também se aplicam a este objeto.',+ ownerInherit: 'Proprietário do arquivo, acesso herdado',+ peopleError: 'Não foi possível carregar as pessoas. Tente novamente.',+ document: 'Documento',+ section: 'Seção',+ paragraph: 'Parágrafo',+ entity: 'Objeto',+ presentation: 'Apresentação',+ page: 'Slide',+ master: 'Exibição mestre',+ base: 'Base',+ table: 'Tabela',+ field: 'Campo',+ record: 'Registro',+ view: 'Exibição',+ board: 'Quadro',+ objectName: '{0}: {1}',++ search: 'Buscar objetos',+ empty: 'Nenhum objeto correspondente',+ more: 'Exibindo os primeiros 100 objetos. Use a busca para refinar a lista.',+ title: 'Permissões',+ cancel: 'Cancelar',+ save: 'Salvar',+ saving: 'Salvando…',+ loading: 'Carregando…',+ conflict: 'As permissões foram alteradas. Recarregue antes de salvar.',+ error: 'Não foi possível carregar ou salvar as permissões. Suas alterações foram mantidas.',+ reload: 'Recarregar',+ denied: 'Você não pode gerenciar as permissões deste objeto.',+ edit: 'Quem pode editar',+ all: 'Todos os editores do arquivo',+ owner: 'Apenas o proprietário do objeto',+ members: 'Membros selecionados',+ copy: 'Permitir que editores copiem',+ print: 'Permitir que editores imprimam',+ export: 'Permitir que editores exportem',+ comment: 'Permitir que editores comentem',+ parentHint: 'As restrições do arquivo e do objeto pai continuam válidas.',+ },featureSearch: {title: 'Pesquisar recursos',placeholder: 'Digite um recurso ou nome de menu...',diff --git a/packages/ui/src/locale/ru-RU.ts b/packages/ui/src/locale/ru-RU.tsindex 35ac7dcc11..c9a8a4b575 100644--- a/packages/ui/src/locale/ru-RU.ts+++ b/packages/ui/src/locale/ru-RU.ts@@ -19,6 +19,64 @@ import emojiLocale from './emoji-locale/ru-RU.generated';const locale: typeof enUS = {ui: {+ objectPermission: {+ operationDenied: 'Этот контент защищён. Действие недоступно.',+ remove: 'Удалить защиту',+ roleOwner: 'Владелец файла',+ roleEditor: 'Редактор файла',+ selectedCount: 'Выбрано: {0}',+ searchPeople: 'Поиск пользователей',+ noMatchingPeople: 'Подходящие пользователи не найдены',+ loadMore: 'Загрузить ещё',+ fileHint: 'Состав участников определяется настройками общего доступа к файлу. Эти настройки ограничивают действия участников.',+ documentParent: 'Ограничения на редактирование документа также действуют для этого раздела.',+ paragraphParent: 'Ограничения на редактирование документа и содержащего раздела также действуют для этого абзаца.',+ documentObjectParent: 'Документ, а также разделы и абзацы, содержащие этот объект или служащие его привязкой, также могут ограничивать редактирование.',+ slideParent: 'Ограничения на редактирование презентации также действуют.',+ slideObjectParent: 'Ограничения на редактирование презентации и содержащего слайда или образца также действуют.',+ baseParent: 'Ограничения на редактирование Base также действуют.',+ baseObjectParent: 'Ограничения на редактирование Base и содержащей таблицы также действуют.',+ recordParent: 'Ограничения Base и таблицы сохраняются. Для изменения значения также требуется разрешение на редактирование его поля.',+ boardParent: 'Ограничения на редактирование доски также действуют для этого объекта.',+ ownerInherit: 'Владелец файла, унаследованный доступ',+ peopleError: 'Не удалось загрузить пользователей. Повторите попытку.',+ document: 'Документ',+ section: 'Раздел',+ paragraph: 'Абзац',+ entity: 'Объект',+ presentation: 'Презентация',+ page: 'Слайд',+ master: 'Режим образца',+ base: 'Base',+ table: 'Таблица',+ field: 'Поле',+ record: 'Запись',+ view: 'Представление',+ board: 'Доска',+ objectName: '{0}: {1}',++ search: 'Поиск объектов',+ empty: 'Подходящие объекты не найдены',+ more: 'Показаны первые 100 объектов. Используйте поиск, чтобы сузить список.',+ title: 'Права доступа',+ cancel: 'Отмена',+ save: 'Сохранить',+ saving: 'Сохранение…',+ loading: 'Загрузка…',+ conflict: 'Разрешения изменились. Перезагрузите их перед сохранением.',+ error: 'Не удалось загрузить или сохранить разрешения. Ваши изменения сохранены.',+ reload: 'Перезагрузить',+ denied: 'Вы не можете управлять разрешениями для этого объекта.',+ edit: 'Кто может редактировать',+ all: 'Все редакторы файла',+ owner: 'Только владелец объекта',+ members: 'Выбранные участники',+ copy: 'Разрешить редакторам копирование',+ print: 'Разрешить редакторам печать',+ export: 'Разрешить редакторам экспорт',+ comment: 'Разрешить редакторам комментарии',+ parentHint: 'Ограничения файла и родительского объекта сохраняются.',+ },featureSearch: {title: 'Поиск функций',placeholder: 'Введите название функции или меню...',diff --git a/packages/ui/src/locale/sk-SK.ts b/packages/ui/src/locale/sk-SK.tsindex b14c42fc6a..10ad4b4627 100644--- a/packages/ui/src/locale/sk-SK.ts+++ b/packages/ui/src/locale/sk-SK.ts@@ -19,6 +19,64 @@ import emojiLocale from './emoji-locale/sk-SK.generated';const locale: typeof enUS = {ui: {+ objectPermission: {+ operationDenied: 'Tento obsah je chránený. Túto akciu nemožno vykonať.',+ remove: 'Odstrániť ochranu',+ roleOwner: 'Vlastník súboru',+ roleEditor: 'Editor súboru',+ selectedCount: 'Vybrané: {0}',+ searchPeople: 'Hľadať osoby',+ noMatchingPeople: 'Žiadne zodpovedajúce osoby',+ loadMore: 'Načítať viac',+ fileHint: 'Zdieľanie súboru určuje členstvo. Tieto nastavenia obmedzujú činnosti týchto členov.',+ documentParent: 'Obmedzenia úprav dokumentu sa vzťahujú aj na túto sekciu.',+ paragraphParent: 'Obmedzenia úprav dokumentu a sekcie obsahujúcej tento odsek sa vzťahujú aj na tento odsek.',+ documentObjectParent: 'Dokument a sekcie či odseky, ktoré obsahujú alebo ukotvujú tento objekt, môžu tiež obmedzovať úpravy.',+ slideParent: 'Platia aj obmedzenia úprav prezentácie.',+ slideObjectParent: 'Platia aj obmedzenia úprav prezentácie a snímky alebo predlohy obsahujúcej tento objekt.',+ baseParent: 'Platia aj obmedzenia úprav Base.',+ baseObjectParent: 'Platia aj obmedzenia úprav Base a tabuľky obsahujúcej tento objekt.',+ recordParent: 'Obmedzenia Base a tabuľky naďalej platia. Úprava hodnoty vyžaduje aj oprávnenie pre príslušné pole.',+ boardParent: 'Obmedzenia úprav tabule sa vzťahujú aj na tento objekt.',+ ownerInherit: 'Vlastník súboru, zdedený prístup',+ peopleError: 'Osoby sa nepodarilo načítať. Skúste to znova.',+ document: 'Dokument',+ section: 'Sekcia',+ paragraph: 'Odsek',+ entity: 'Objekt',+ presentation: 'Prezentácia',+ page: 'Snímka',+ master: 'Zobrazenie predlohy',+ base: 'Base',+ table: 'Tabuľka',+ field: 'Pole',+ record: 'Záznam',+ view: 'Zobrazenie',+ board: 'Tabuľa',+ objectName: '{0}: {1}',++ search: 'Hľadať objekty',+ empty: 'Žiadne zodpovedajúce objekty',+ more: 'Zobrazuje sa prvých 100 objektov. Pomocou vyhľadávania zúžte zoznam.',+ title: 'Oprávnenia',+ cancel: 'Zrušiť',+ save: 'Uložiť',+ saving: 'Ukladá sa…',+ loading: 'Načítava sa…',+ conflict: 'Oprávnenia sa zmenili. Pred uložením ich znova načítajte.',+ error: 'Oprávnenia sa nepodarilo načítať alebo uložiť. Vaše zmeny zostali zachované.',+ reload: 'Znova načítať',+ denied: 'Nemôžete spravovať oprávnenia tohto objektu.',+ edit: 'Kto môže upravovať',+ all: 'Všetci editori súboru',+ owner: 'Iba vlastník objektu',+ members: 'Vybraní členovia',+ copy: 'Povoliť editorom kopírovanie',+ print: 'Povoliť editorom tlač',+ export: 'Povoliť editorom export',+ comment: 'Povoliť editorom komentovanie',+ parentHint: 'Obmedzenia súboru a nadradeného objektu naďalej platia.',+ },featureSearch: {title: 'Vyhľadať funkcie',placeholder: 'Zadajte názov funkcie alebo ponuky...',diff --git a/packages/ui/src/locale/vi-VN.ts b/packages/ui/src/locale/vi-VN.tsindex 6c1f610bd1..d810bfb98a 100644--- a/packages/ui/src/locale/vi-VN.ts+++ b/packages/ui/src/locale/vi-VN.ts@@ -19,6 +19,64 @@ import emojiLocale from './emoji-locale/vi-VN.generated';const locale: typeof enUS = {ui: {+ objectPermission: {+ operationDenied: 'Nội dung này được bảo vệ. Không thể thực hiện thao tác này.',+ remove: 'Xóa bảo vệ',+ roleOwner: 'Chủ sở hữu tệp',+ roleEditor: 'Người chỉnh sửa tệp',+ selectedCount: 'Đã chọn: {0}',+ searchPeople: 'Tìm người dùng',+ noMatchingPeople: 'Không có người dùng phù hợp',+ loadMore: 'Tải thêm',+ fileHint: 'Cài đặt chia sẻ tệp quản lý thành viên. Các cài đặt này giới hạn thao tác của những thành viên đó.',+ documentParent: 'Giới hạn chỉnh sửa tài liệu cũng áp dụng cho phần này.',+ paragraphParent: 'Giới hạn chỉnh sửa tài liệu và phần chứa đoạn văn cũng áp dụng cho đoạn văn này.',+ documentObjectParent: 'Tài liệu và các phần, đoạn văn chứa hoặc neo đối tượng này cũng có thể giới hạn việc chỉnh sửa.',+ slideParent: 'Giới hạn chỉnh sửa bản trình bày cũng áp dụng.',+ slideObjectParent: 'Giới hạn chỉnh sửa bản trình bày và trang chiếu hoặc trang chiếu cái chứa đối tượng cũng áp dụng.',+ baseParent: 'Giới hạn chỉnh sửa Base cũng áp dụng.',+ baseObjectParent: 'Giới hạn chỉnh sửa Base và bảng chứa đối tượng cũng áp dụng.',+ recordParent: 'Giới hạn của Base và bảng vẫn áp dụng. Chỉnh sửa giá trị cũng cần quyền đối với trường tương ứng.',+ boardParent: 'Giới hạn chỉnh sửa bảng vẽ cũng áp dụng cho đối tượng này.',+ ownerInherit: 'Chủ sở hữu tệp, quyền truy cập kế thừa',+ peopleError: 'Không thể tải người dùng. Vui lòng thử lại.',+ document: 'Tài liệu',+ section: 'Phần',+ paragraph: 'Đoạn văn',+ entity: 'Đối tượng',+ presentation: 'Bản trình bày',+ page: 'Trang chiếu',+ master: 'Chế độ xem trang chiếu cái',+ base: 'Base',+ table: 'Bảng',+ field: 'Trường',+ record: 'Bản ghi',+ view: 'Chế độ xem',+ board: 'Bảng vẽ',+ objectName: '{0}: {1}',++ search: 'Tìm đối tượng',+ empty: 'Không có đối tượng phù hợp',+ more: 'Đang hiển thị 100 đối tượng đầu tiên. Hãy tìm kiếm để thu hẹp danh sách.',+ title: 'Quyền',+ cancel: 'Hủy',+ save: 'Lưu',+ saving: 'Đang lưu…',+ loading: 'Đang tải…',+ conflict: 'Quyền đã thay đổi. Hãy tải lại trước khi lưu.',+ error: 'Không thể tải hoặc lưu quyền. Các thay đổi của bạn vẫn được giữ lại.',+ reload: 'Tải lại',+ denied: 'Bạn không thể quản lý quyền của đối tượng này.',+ edit: 'Ai có thể chỉnh sửa',+ all: 'Tất cả người chỉnh sửa tệp',+ owner: 'Chỉ chủ sở hữu đối tượng',+ members: 'Thành viên được chọn',+ copy: 'Cho phép người chỉnh sửa sao chép',+ print: 'Cho phép người chỉnh sửa in',+ export: 'Cho phép người chỉnh sửa xuất',+ comment: 'Cho phép người chỉnh sửa bình luận',+ parentHint: 'Giới hạn của tệp và đối tượng cấp trên vẫn áp dụng.',+ },featureSearch: {title: 'Tìm kiếm tính năng',placeholder: 'Nhập tên tính năng hoặc menu...',diff --git a/packages/ui/src/locale/zh-CN.ts b/packages/ui/src/locale/zh-CN.tsindex 42e9cc94f6..52a2af3e3d 100644--- a/packages/ui/src/locale/zh-CN.ts+++ b/packages/ui/src/locale/zh-CN.ts@@ -19,6 +19,64 @@ import emojiLocale from './emoji-locale/zh-CN.generated';const locale: typeof enUS = {ui: {+ objectPermission: {+ operationDenied: '该内容已受保护,无法执行此操作。',+ remove: '删除保护',+ roleOwner: '文件所有者',+ roleEditor: '文件编辑者',+ selectedCount: '已选择 {0} 人',+ searchPeople: '搜索人员',+ noMatchingPeople: '没有匹配的人员',+ loadMore: '加载更多',+ fileHint: '文件成员由分享功能管理;此处设置成员可以执行的操作。',+ documentParent: '此节同时受整文档编辑权限限制。',+ paragraphParent: '此段落同时受整文档及所在节的编辑权限限制。',+ documentObjectParent: '此对象还可能受到整文档及其所在或锚定段落、节的编辑权限限制。',+ slideParent: '同时受整份演示文稿的编辑权限限制。',+ slideObjectParent: '同时受整份演示文稿及所在页面或母版的编辑权限限制。',+ baseParent: '同时受整个 Base 的编辑权限限制。',+ baseObjectParent: '同时受整个 Base 及所在表的编辑权限限制。',+ recordParent: '同时受整个 Base 及所在表的限制;修改字段值还需具备对应字段的编辑权限。',+ boardParent: '此对象同时受整个白板的编辑权限限制。',+ ownerInherit: '文件所有者,继承权限',+ peopleError: '人员列表加载失败,请重试。',+ document: '文档',+ section: '节',+ paragraph: '段落',+ entity: '对象',+ presentation: '演示文稿',+ page: '页面',+ master: '母版视图',+ base: '多维表格',+ table: '数据表',+ field: '字段',+ record: '记录',+ view: '视图',+ board: '白板',+ objectName: '{0}:{1}',++ search: '搜索对象',+ empty: '没有匹配的对象',+ more: '显示前 100 个对象,请搜索以缩小范围。',+ title: '权限',+ cancel: '取消',+ save: '保存',+ saving: '正在保存…',+ loading: '正在加载…',+ conflict: '权限已被修改,请重新加载后再保存。',+ error: '无法读取或保存权限,已保留你的修改。',+ reload: '重新加载',+ denied: '你没有管理此对象权限的权限。',+ edit: '谁可以编辑',+ all: '所有文件编辑者',+ owner: '仅对象所有者',+ members: '指定成员',+ copy: '允许编辑者复制',+ print: '允许编辑者打印',+ export: '允许编辑者导出',+ comment: '允许编辑者评论',+ parentHint: '仍受文件及上级对象权限的限制。',+ },featureSearch: {title: '搜索功能',placeholder: '输入功能或菜单名称…',diff --git a/packages/ui/src/locale/zh-HK.ts b/packages/ui/src/locale/zh-HK.tsindex d737c94b59..c02afb2715 100644--- a/packages/ui/src/locale/zh-HK.ts+++ b/packages/ui/src/locale/zh-HK.ts@@ -19,6 +19,64 @@ import emojiLocale from './emoji-locale/zh-HK.generated';const locale: typeof enUS = {ui: {+ objectPermission: {+ operationDenied: '此內容已受保護,無法執行此操作。',+ remove: '刪除保護',+ roleOwner: '檔案擁有者',+ roleEditor: '檔案編輯者',+ selectedCount: '已選擇 {0} 人',+ searchPeople: '搜尋人員',+ noMatchingPeople: '沒有符合的人員',+ loadMore: '載入更多',+ fileHint: '檔案成員由分享功能管理;此處設定成員可以執行的操作。',+ documentParent: '此節同時受整份文件的編輯權限限制。',+ paragraphParent: '此段落同時受整份文件及所在節的編輯權限限制。',+ documentObjectParent: '此物件還可能受到整份文件及其所在或錨定段落、節的編輯權限限制。',+ slideParent: '同時受整份簡報的編輯權限限制。',+ slideObjectParent: '同時受整份簡報及所在頁面或母片的編輯權限限制。',+ baseParent: '同時受整個 Base 的編輯權限限制。',+ baseObjectParent: '同時受整個 Base 及所在表的編輯權限限制。',+ recordParent: '同時受整個 Base 及所在表的限制;修改欄位值還需具備對應欄位的編輯權限。',+ boardParent: '此物件同時受整個白板的編輯權限限制。',+ ownerInherit: '檔案擁有者,繼承權限',+ peopleError: '人員清單載入失敗,請重試。',+ document: '文件',+ section: '節',+ paragraph: '段落',+ entity: '物件',+ presentation: '簡報',+ page: '頁面',+ master: '母版檢視',+ base: '多維表格',+ table: '資料表',+ field: '欄位',+ record: '記錄',+ view: '檢視',+ board: '白板',+ objectName: '{0}:{1}',++ search: '搜尋物件',+ empty: '沒有匹配的物件',+ more: '顯示前 100 個物件,請搜尋以缩小範圍。',+ title: '權限',+ cancel: '取消',+ save: '儲存',+ saving: '正在儲存…',+ loading: '正在載入…',+ conflict: '權限已被修改,請重新載入后再儲存。',+ error: '无法讀取或儲存權限,已保留你的修改。',+ reload: '重新載入',+ denied: '你沒有管理此物件權限的權限。',+ edit: '誰可以編輯',+ all: '所有文件編輯者',+ owner: '僅物件所有者',+ members: '指定成員',+ copy: '允許編輯者複製',+ print: '允許編輯者列印',+ export: '允許編輯者匯出',+ comment: '允許編輯者評論',+ parentHint: '仍受檔案及上級物件權限的限制。',+ },featureSearch: {title: '搜尋功能',placeholder: '輸入功能或選單名稱…',diff --git a/packages/ui/src/locale/zh-TW.ts b/packages/ui/src/locale/zh-TW.tsindex dbb620c31b..88c9944109 100644--- a/packages/ui/src/locale/zh-TW.ts+++ b/packages/ui/src/locale/zh-TW.ts@@ -19,6 +19,64 @@ import emojiLocale from './emoji-locale/zh-TW.generated';const locale: typeof enUS = {ui: {+ objectPermission: {+ operationDenied: '此內容已受保護,無法執行此操作。',+ remove: '刪除保護',+ roleOwner: '檔案擁有者',+ roleEditor: '檔案編輯者',+ selectedCount: '已選擇 {0} 人',+ searchPeople: '搜尋人員',+ noMatchingPeople: '沒有符合的人員',+ loadMore: '載入更多',+ fileHint: '檔案成員由分享功能管理;此處設定成員可以執行的操作。',+ documentParent: '此節同時受整份文件的編輯權限限制。',+ paragraphParent: '此段落同時受整份文件及所在節的編輯權限限制。',+ documentObjectParent: '此物件還可能受到整份文件及其所在或錨定段落、節的編輯權限限制。',+ slideParent: '同時受整份簡報的編輯權限限制。',+ slideObjectParent: '同時受整份簡報及所在頁面或母片的編輯權限限制。',+ baseParent: '同時受整個 Base 的編輯權限限制。',+ baseObjectParent: '同時受整個 Base 及所在表的編輯權限限制。',+ recordParent: '同時受整個 Base 及所在表的限制;修改欄位值還需具備對應欄位的編輯權限。',+ boardParent: '此物件同時受整個白板的編輯權限限制。',+ ownerInherit: '檔案擁有者,繼承權限',+ peopleError: '人員清單載入失敗,請重試。',+ document: '文件',+ section: '節',+ paragraph: '段落',+ entity: '物件',+ presentation: '簡報',+ page: '頁面',+ master: '母版檢視',+ base: '多維表格',+ table: '資料表',+ field: '欄位',+ record: '記錄',+ view: '檢視',+ board: '白板',+ objectName: '{0}:{1}',++ search: '搜尋物件',+ empty: '沒有匹配的物件',+ more: '顯示前 100 個物件,請搜尋以缩小範圍。',+ title: '權限',+ cancel: '取消',+ save: '儲存',+ saving: '正在儲存…',+ loading: '正在載入…',+ conflict: '權限已被修改,請重新載入后再儲存。',+ error: '无法讀取或儲存權限,已保留你的修改。',+ reload: '重新載入',+ denied: '你沒有管理此物件權限的權限。',+ edit: '誰可以編輯',+ all: '所有文件編輯者',+ owner: '僅物件所有者',+ members: '指定成員',+ copy: '允許編輯者複製',+ print: '允許編輯者列印',+ export: '允許編輯者匯出',+ comment: '允許編輯者評論',+ parentHint: '仍受檔案及上級物件權限的限制。',+ },featureSearch: {title: '搜尋功能',placeholder: '輸入功能或選單名稱…',diff --git a/packages/ui/src/views/object-permission/ObjectPermissionButton.tsx b/packages/ui/src/views/object-permission/ObjectPermissionButton.tsxnew file mode 100644index 0000000000..fcc999f648--- /dev/null+++ b/packages/ui/src/views/object-permission/ObjectPermissionButton.tsx@@ -0,0 +1,312 @@+/**+ * 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, IObjectPermissionPolicy, IObjectPermissionTarget } from '@univerjs/core';+import type { LocaleKey } from '../../locale/types';+import {+ ICommandService,+ IUniverInstanceService,+ LocaleService,+ ObjectPermissionService,+ UserManagerService,+} from '@univerjs/core';+import { Button, Checkbox, Dialog, FormLayout, Radio, RadioGroup, StateIconButton } from '@univerjs/design';+import { ProtectIcon } from '@univerjs/icons';+import { UnitAction, UnitObject, UnitRole } from '@univerjs/protocol';+import { useEffect, useState } from 'react';+import { IDialogService } from '../../services/dialog/dialog.service';+import { useDependency, useObservable } from '../../utils/di';+import { ObjectPermissionMembers } from './ObjectPermissionMembers';++export interface IObjectPermissionButtonProps {+ target: IObjectPermissionTarget;+ name: string;+ commandId: string;+ actions?: readonly UnitAction[];+ /** Confirm the original object still exists before saving. */+ exists?: () => boolean;+}++export const OBJECT_PERMISSION_DIALOG = 'ui.object-permission-dialog';++/** Mount outside transient toolbars and context menus, retaining the original target until close. */+export function openObjectPermissionDialog(accessor: IAccessor, props: IObjectPermissionButtonProps): boolean {+ if (!accessor.get(ObjectPermissionService).canView(props.target) || (props.exists && !props.exists())) {+ return false;+ }+ const dialogs = accessor.get(IDialogService);+ dialogs.open({+ id: OBJECT_PERMISSION_DIALOG,+ width: 400,+ title: { label: accessor.get(LocaleService).t<LocaleKey>('ui.objectPermission.title') },+ closable: false,+ maskClosable: false,+ keyboard: false,+ children: { label: { name: OBJECT_PERMISSION_DIALOG, props: { ...props, hosted: true, onClose: () => dialogs.close(OBJECT_PERMISSION_DIALOG) } } },+ });+ return true;+}++/** Available only for explicitly capable Authz providers. The target remains fixed while the dialog is open. */+export function ObjectPermissionButton(props: IObjectPermissionButtonProps) {+ const permissions = useDependency(ObjectPermissionService);+ const localeService = useDependency(LocaleService);+ useObservable(permissions.changed$, 0);+ const [open, setOpen] = useState(false);+ if (!permissions.supports(props.target)) {+ return null;+ }+ return (+ <>+ <StateIconButton+ disabled={!permissions.canView(props.target)}+ active={permissions.hasPolicy(props.target)}+ emphasizeActive+ title={localeService.t<LocaleKey>('ui.objectPermission.title')}+ aria-label={localeService.t<LocaleKey>('ui.objectPermission.title')}+ onClick={(event) => {+ event.stopPropagation();+ setOpen(true);+ }}+ >+ <ProtectIcon />+ </StateIconButton>+ {open && <ObjectPermissionDialog {...props} onClose={() => setOpen(false)} />}+ </>+ );+}++const DEFAULT_ACTIONS = [UnitAction.Edit] as const;++export function ObjectPermissionDialog({ target, name, commandId, actions = DEFAULT_ACTIONS, exists, onClose, hosted = false }: IObjectPermissionButtonProps & { onClose: () => void; hosted?: boolean }) {+ const localeService = useDependency(LocaleService);+ const permissions = useDependency(ObjectPermissionService);+ const commandService = useDependency(ICommandService);+ const instances = useDependency(IUniverInstanceService);+ const users = useDependency(UserManagerService);+ const currentUser = useObservable(users.currentUser$, users.getCurrentUser());+ const [policy, setPolicy] = useState<IObjectPermissionPolicy | null>(null);+ useObservable(permissions.changed$, 0);+ const canView = permissions.canView(target);+ const [canManage, setCanManage] = useState(false);+ const [canDelete, setCanDelete] = useState(false);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState(false);+ const [attempt, setAttempt] = useState(0);+ const [dirty, setDirty] = useState(false);+ const [conflict, setConflict] = useState(false);+ const [loading, setLoading] = useState(true);+ const { unitId, objectId, objectType } = target;+ const editOptions: IObjectPermissionPolicy['edit'][] = objectId === unitId ? ['all', 'owner'] : ['all', 'owner', 'members'];+ useEffect(() => {+ const subscription = instances.unitDisposed$.subscribe((unit) => {+ if (unit.getUnitId() === unitId) {+ onClose();+ }+ });+ return () => subscription.unsubscribe();+ }, [instances, unitId, onClose]);++ useEffect(() => {+ let cancelled = false;+ setLoading(true);+ Promise.all([+ permissions.read({ unitId, objectId, objectType }),+ permissions.canManage({ unitId, objectId, objectType }),+ permissions.canDelete({ unitId, objectId, objectType }),+ ]).then(([loaded, allowed, deletable]) => {+ if (!cancelled) {+ setPolicy(loaded);+ setCanManage(allowed);+ setCanDelete(deletable);+ setDirty(false);+ setConflict(false);+ setError(false);+ setLoading(false);+ }+ }).catch(() => {+ if (!cancelled) {+ setError(true);+ setLoading(false);+ }+ });+ return () => {+ cancelled = true;+ };+ }, [permissions, unitId, objectId, objectType, attempt, currentUser.userID]);++ useEffect(() => {+ const subscription = permissions.unitChanges$.subscribe((changedUnitId) => {+ if (changedUnitId !== unitId) {+ return;+ }+ if (!saving) {+ if (dirty) {+ setConflict(true);+ } else {+ setAttempt((value) => value + 1);+ }+ }+ });+ return () => subscription.unsubscribe();+ }, [permissions, unitId, dirty, saving]);++ const save = async (remove = false) => {+ if (!policy || !canView || loading || saving || !(remove ? canDelete : canManage) || conflict) {+ return;+ }+ setSaving(true);+ setError(false);+ try {+ if (!instances.getUnit(unitId) || (exists && !exists())) {+ throw new Error('Object no longer exists.');+ }+ const result = await commandService.executeCommand(commandId, {+ unitId,+ objectId,+ action: UnitAction.Edit,+ value: policy.edit === 'all',+ policy: remove ? undefined : policy,+ remove,+ });+ if (!result) {+ throw new Error('Permission command rejected.');+ }+ onClose();+ } catch {+ setError(true);+ } finally {+ setSaving(false);+ }+ };+ const parentHints: Partial<Record<UnitObject, LocaleKey>> = {+ [UnitObject.DocumentSection]: 'ui.objectPermission.documentParent',+ [UnitObject.DocumentParagraph]: 'ui.objectPermission.paragraphParent',+ [UnitObject.DocumentEntity]: 'ui.objectPermission.documentObjectParent',+ [UnitObject.SlidePage]: 'ui.objectPermission.slideParent',+ [UnitObject.SlideMaster]: 'ui.objectPermission.slideParent',+ [UnitObject.SlideElement]: 'ui.objectPermission.slideObjectParent',+ [UnitObject.BaseTable]: 'ui.objectPermission.baseParent',+ [UnitObject.BaseDashboard]: 'ui.objectPermission.baseParent',+ [UnitObject.BaseField]: 'ui.objectPermission.baseObjectParent',+ [UnitObject.BaseView]: 'ui.objectPermission.baseObjectParent',+ [UnitObject.BaseRecord]: 'ui.objectPermission.recordParent',+ [UnitObject.BoardElement]: 'ui.objectPermission.boardParent',+ };+ const actionLabels: Partial<Record<UnitAction, LocaleKey>> = {+ [UnitAction.Copy]: 'ui.objectPermission.copy',+ [UnitAction.Print]: 'ui.objectPermission.print',+ [UnitAction.Export]: 'ui.objectPermission.export',+ [UnitAction.Comment]: 'ui.objectPermission.comment',+ };+ const footer = (+ <div className="univer-flex univer-justify-end univer-gap-2">+ {canDelete && (+ <Button disabled={!canView || loading || saving || conflict} onClick={() => save(true)}>+ {localeService.t<LocaleKey>('ui.objectPermission.remove')}+ </Button>+ )}+ <Button disabled={saving} onClick={onClose}>{localeService.t<LocaleKey>('ui.objectPermission.cancel')}</Button>+ <Button variant="primary" disabled={!policy || !canManage || !canView || loading || saving || conflict || (policy.edit === 'members' && !policy.collaborators.length)} onClick={() => save()}>+ {localeService.t<LocaleKey>(saving ? 'ui.objectPermission.saving' : 'ui.objectPermission.save')}+ </Button>+ </div>+ );+ const content = (+ <div className="univer-flex univer-flex-col univer-gap-4" onClick={(event) => event.stopPropagation()}>+ <div className="univer-break-words univer-font-medium">{name}</div>+ {!policy && !error && <p role="status">{localeService.t<LocaleKey>('ui.objectPermission.loading')}</p>}+ {(error || conflict) && (+ <div role="alert">+ {localeService.t<LocaleKey>(conflict ? 'ui.objectPermission.conflict' : 'ui.objectPermission.error')}+ <Button disabled={saving} onClick={() => setAttempt((value) => value + 1)}>{localeService.t<LocaleKey>('ui.objectPermission.reload')}</Button>+ </div>+ )}+ {policy && (+ <>+ {(!canManage || !canView) && <p>{localeService.t<LocaleKey>('ui.objectPermission.denied')}</p>}+ <FormLayout label={localeService.t<LocaleKey>('ui.objectPermission.edit')}>+ <RadioGroup+ value={policy.edit}+ disabled={!canManage || !canView || loading || saving || conflict}+ onChange={(value) => {+ setPolicy({ ...policy, edit: value as IObjectPermissionPolicy['edit'] });+ setDirty(true);+ }}+ className="univer-flex univer-flex-col univer-gap-2"+ >+ {editOptions.map((value) => (+ <Radio key={value} value={value}>+ {localeService.t<LocaleKey>(`ui.objectPermission.${value}`)}+ </Radio>+ ))}+ </RadioGroup>+ </FormLayout>+ {objectId !== unitId && policy.edit === 'members' && (+ <ObjectPermissionMembers+ key={`${unitId}/${objectType}/${objectId}/${currentUser.userID}`}+ unitId={unitId}+ value={policy.collaborators}+ disabled={!canManage || !canView || loading || saving || conflict}+ onChange={(collaborators) => {+ setPolicy({ ...policy, collaborators });+ setDirty(true);+ }}+ />+ )}+ {actions.filter((action) => action !== UnitAction.Edit && actionLabels[action]).map((action) => (+ <Checkbox+ key={action}+ disabled={!canManage || !canView || loading || saving || conflict}+ checked={!policy.strategies.some((strategy) => strategy.action === action && strategy.role === UnitRole.Owner)}+ onChange={(checked) => {+ setPolicy({ ...policy, strategies: [...policy.strategies.filter((strategy) => strategy.action !== action), { action, role: checked ? UnitRole.Editor : UnitRole.Owner }] });+ setDirty(true);+ }}+ >+ {localeService.t<LocaleKey>(actionLabels[action]!)}+ </Checkbox>+ ))}+ <p className="univer-text-sm univer-text-gray-500">{localeService.t<LocaleKey>(objectId === unitId ? 'ui.objectPermission.fileHint' : parentHints[objectType] ?? 'ui.objectPermission.parentHint')}</p>+ </>+ )}+ </div>+ );+ if (hosted) {+ return (+ <>+ {content}+ <div className="univer-mt-4">{footer}</div>+ </>+ );+ }+ return (+ <Dialog+ open+ width={400}+ title={localeService.t<LocaleKey>('ui.objectPermission.title')}+ closable={!saving}+ onClose={() => {+ if (!saving) {+ onClose();+ }+ }}+ footer={footer}+ >+ {content}+ </Dialog>+ );+}diff --git a/packages/ui/src/views/object-permission/ObjectPermissionMembers.tsx b/packages/ui/src/views/object-permission/ObjectPermissionMembers.tsxnew file mode 100644index 0000000000..c904ec20fa--- /dev/null+++ b/packages/ui/src/views/object-permission/ObjectPermissionMembers.tsx@@ -0,0 +1,150 @@+/**+ * 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 { ICollaborator } from '@univerjs/protocol';+import type { LocaleKey } from '../../locale/types';+import { IAuthzIoService, LocaleService, UserManagerService } from '@univerjs/core';+import { Avatar, borderClassName, Button, Checkbox, clsx, Input } from '@univerjs/design';+import { UnitRole } from '@univerjs/protocol';+import { useEffect, useState } from 'react';+import { useDependency } from '../../utils/di';++interface IObjectPermissionMembersProps {+ unitId: string;+ value: ICollaborator[];+ disabled: boolean;+ onChange: (value: ICollaborator[]) => void;+}++export function ObjectPermissionMembers({ unitId, value, disabled, onChange }: IObjectPermissionMembersProps) {+ const locale = useDependency(LocaleService);+ const authz = useDependency(IAuthzIoService);+ const userManager = useDependency(UserManagerService);+ const [query, setQuery] = useState('');+ const [candidates, setCandidates] = useState<ICollaborator[]>([]);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState(false);+ const [attempt, setAttempt] = useState(0);+ const inheritOwner = authz.getCfgEnableObjInherit?.() ?? false;+ useEffect(() => {+ let cancelled = false;+ authz.listCollaborators({ unitID: unitId, objectID: unitId }).then((users) => {+ if (!cancelled) {+ setCandidates(users.filter((user) => user.subject?.userID !== userManager.getCurrentUser().userID));+ setLoading(false);+ }+ }).catch(() => {+ if (!cancelled) {+ setError(true);+ setLoading(false);+ }+ });+ return () => {+ cancelled = true;+ };+ }, [authz, userManager, unitId, attempt]);++ // Keep existing members visible even when they are absent from the candidate response.+ // Unit collaborators supply the display role; object collaborators carry the saved grant.+ const people = new Map<string, ICollaborator>();+ for (const user of candidates) {+ people.set(user.subject?.userID || user.id, user);+ }+ for (const user of value) {+ const userId = user.subject?.userID || user.id;+ if (!people.has(userId)) {+ people.set(userId, user);+ }+ }+ const selected = new Set(value.map((user) => user.subject?.userID || user.id));+ const search = query.trim().toLocaleLowerCase();+ const users = Array.from(people.values()).filter((user) => (+ (selected.has(user.subject?.userID || user.id) || user.role === UnitRole.Owner || user.role === UnitRole.Editor) &&+ [user.subject?.name, user.subject?.userID, user.id].some((text) => text?.toLocaleLowerCase().includes(search))+ ));++ return (+ <div className={clsx('univer-flex univer-flex-col univer-gap-3 univer-rounded-lg univer-p-3', borderClassName)}>+ <Input+ className="univer-w-full"+ value={query}+ onChange={setQuery}+ placeholder={locale.t<LocaleKey>('ui.objectPermission.searchPeople')}+ aria-label={locale.t<LocaleKey>('ui.objectPermission.searchPeople')}+ />+ <span className="univer-text-xs univer-text-gray-500" aria-live="polite">+ {locale.t<LocaleKey>('ui.objectPermission.selectedCount', String(selected.size))}+ </span>+ <div className="univer-flex univer-max-h-60 univer-flex-col univer-gap-3 univer-overflow-y-auto">+ {loading && <p role="status">{locale.t<LocaleKey>('ui.objectPermission.loading')}</p>}+ {error && (+ <div role="alert">+ {locale.t<LocaleKey>('ui.objectPermission.peopleError')}+ <Button+ onClick={() => {+ setLoading(true);+ setError(false);+ setAttempt((value) => value + 1);+ }}+ >+ {locale.t<LocaleKey>('ui.objectPermission.reload')}+ </Button>+ </div>+ )}+ {!loading && !error && users.length === 0 && (+ <p role="status" className="univer-text-sm univer-text-gray-500">+ {locale.t<LocaleKey>('ui.objectPermission.noMatchingPeople')}+ </p>+ )}+ {users.map((user) => {+ const userId = user.subject?.userID || user.id;+ const name = user.subject?.name || userId;+ const inherited = inheritOwner && user.role === UnitRole.Owner;+ let roleLabel: LocaleKey = 'ui.objectPermission.roleEditor';+ if (user.role === UnitRole.Owner) {+ roleLabel = 'ui.objectPermission.roleOwner';+ }+ if (inherited) {+ roleLabel = 'ui.objectPermission.ownerInherit';+ }+ return (+ <Checkbox+ key={userId}+ disabled={disabled || loading || inherited}+ checked={selected.has(userId)}+ onChange={(checked) => onChange(checked+ ? [...value, { ...user, role: UnitRole.Editor }]+ : value.filter((member) => (member.subject?.userID || member.id) !== userId))}+ >+ <span className="univer-flex univer-min-w-0 univer-items-center univer-gap-2">+ <span aria-hidden="true"><Avatar size={24} src={user.subject?.avatar}>{Array.from(name)[0]}</Avatar></span>+ <span className="univer-min-w-0 univer-break-words" title={name}>{name}</span>+ <span+ className="+ univer-rounded univer-bg-gray-100 univer-px-1.5 univer-py-0.5 univer-text-xs+ univer-text-gray-500+ "+ >+ {locale.t<LocaleKey>(roleLabel)}+ </span>+ </span>+ </Checkbox>+ );+ })}+ </div>+ </div>+ );+}diff --git a/packages/ui/src/views/object-permission/ObjectPermissionPanel.tsx b/packages/ui/src/views/object-permission/ObjectPermissionPanel.tsxnew file mode 100644index 0000000000..924e0cc543--- /dev/null+++ b/packages/ui/src/views/object-permission/ObjectPermissionPanel.tsx@@ -0,0 +1,164 @@+/**+ * 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, IObjectPermissionTarget } from '@univerjs/core';+import type { LocaleKey } from '../../locale/types';+import type { IObjectPermissionButtonProps } from './ObjectPermissionButton';+import { Injector, IUniverInstanceService, LocaleService, ObjectPermissionService } from '@univerjs/core';+import { Button, Input } from '@univerjs/design';+import { ProtectIcon } from '@univerjs/icons';+import { UnitObject } from '@univerjs/protocol';+import { useEffect, useState } from 'react';+import { ISidebarService } from '../../services/sidebar/sidebar.service';+import { useDependency, useObservable } from '../../utils/di';+import { ObjectPermissionButton } from './ObjectPermissionButton';++export const OBJECT_PERMISSION_PANEL = 'ui.object-permission-panel';++export interface IObjectPermissionPanelProps {+ unitId: string;+ expandable?: UnitObject;+ /** A lazy iterator avoids materializing all records in large Bases. */+ getTargets: () => Iterable<IObjectPermissionButtonProps>;+}++export function openObjectPermissionPanel(+ accessor: IAccessor,+ props: IObjectPermissionPanelProps & { target: IObjectPermissionTarget }+): boolean {+ if (!accessor.get(ObjectPermissionService).canView(props.target)) {+ return false;+ }+ accessor.get(ISidebarService).open({+ id: OBJECT_PERMISSION_PANEL,+ width: 330,+ header: { title: accessor.get(LocaleService).t<LocaleKey>('ui.objectPermission.title') },+ children: { label: { name: OBJECT_PERMISSION_PANEL, props: { unitId: props.unitId, getTargets: props.getTargets, expandable: props.expandable } } },+ });+ return true;+}++export function ObjectPermissionPanelButton(props: IObjectPermissionPanelProps & { target: IObjectPermissionTarget }) {+ const permissions = useDependency(ObjectPermissionService);+ const accessor = useDependency(Injector);+ const localeService = useDependency(LocaleService);+ useObservable(permissions.changed$, 0);+ if (!permissions.supports(props.target)) {+ return null;+ }+ return (+ <Button+ variant="ghost"+ size="icon"+ className="univer-size-7 univer-shrink-0"+ disabled={!permissions.canView(props.target)}+ title={localeService.t<LocaleKey>('ui.objectPermission.title')}+ aria-label={localeService.t<LocaleKey>('ui.objectPermission.title')}+ onClick={() => openObjectPermissionPanel(accessor, props)}+ >+ <ProtectIcon />+ </Button>+ );+}++export function ObjectPermissionPanel({ unitId, getTargets, expandable }: IObjectPermissionPanelProps) {+ const localeService = useDependency(LocaleService);+ const permissions = useDependency(ObjectPermissionService);+ const [query, setQuery] = useState('');+ const [expanded, setExpanded] = useState(false);+ const [limit, setLimit] = useState(50);+ useObservable(permissions.changed$, 0);+ const instances = useDependency(IUniverInstanceService);+ const sidebar = useDependency(ISidebarService);+ useEffect(() => {+ const subscription = instances.unitDisposed$.subscribe((unit) => {+ if (unit.getUnitId() === unitId) {+ sidebar.close(OBJECT_PERMISSION_PANEL);+ }+ });+ return () => subscription.unsubscribe();+ }, [instances, sidebar, unitId]);+ const kinds: Partial<Record<UnitObject, LocaleKey>> = {+ [UnitObject.Document]: 'ui.objectPermission.document',+ [UnitObject.DocumentSection]: 'ui.objectPermission.section',+ [UnitObject.DocumentParagraph]: 'ui.objectPermission.paragraph',+ [UnitObject.DocumentEntity]: 'ui.objectPermission.entity',+ [UnitObject.Slide]: 'ui.objectPermission.presentation',+ [UnitObject.SlidePage]: 'ui.objectPermission.page',+ [UnitObject.SlideMaster]: 'ui.objectPermission.master',+ [UnitObject.SlideElement]: 'ui.objectPermission.entity',+ [UnitObject.Base]: 'ui.objectPermission.base',+ [UnitObject.BaseTable]: 'ui.objectPermission.table',+ [UnitObject.BaseField]: 'ui.objectPermission.field',+ [UnitObject.BaseRecord]: 'ui.objectPermission.record',+ [UnitObject.BaseView]: 'ui.objectPermission.view',+ [UnitObject.Board]: 'ui.objectPermission.board',+ [UnitObject.BoardElement]: 'ui.objectPermission.entity',+ };+ const items: IObjectPermissionButtonProps[] = [];+ let more = false;+ let ordinal = 0;+ const iterator = getTargets()[Symbol.iterator]();+ while (true) {+ if (expandable && !expanded && ordinal === 1) {+ break;+ }+ const next = iterator.next();+ if (next.done) {+ break;+ }+ const item = next.value;+ ordinal++;+ const name = localeService.t<LocaleKey>('ui.objectPermission.objectName', localeService.t<LocaleKey>(kinds[item.target.objectType] ?? 'ui.objectPermission.entity'), item.name || String(ordinal));+ if (!permissions.supports(item.target) || ((!expandable || expanded) && !name.toLocaleLowerCase().includes(query.toLocaleLowerCase()))) {+ continue;+ }+ if (items.length === limit) {+ more = true;+ break;+ }+ items.push({ ...item, name });+ }+ return (+ <div className="univer-flex univer-h-full univer-flex-col univer-gap-3 univer-p-4">+ {expandable && <Button aria-expanded={expanded} onClick={() => setExpanded((value) => !value)}>{localeService.t<LocaleKey>(kinds[expandable] ?? 'ui.objectPermission.entity')}</Button>}+ {(!expandable || expanded) && (+ <Input+ value={query}+ onChange={(value) => {+ setQuery(value);+ setLimit(50);+ }}+ placeholder={localeService.t<LocaleKey>('ui.objectPermission.search')}+ aria-label={localeService.t<LocaleKey>('ui.objectPermission.search')}+ />+ )}+ <div className="univer-flex-1 univer-overflow-auto">+ {items.map((item) => (+ <div+ key={`${unitId}/${item.target.objectType}/${item.target.objectId}`}+ className="univer-flex univer-items-center univer-gap-2 univer-py-2"+ >+ <span className="univer-min-w-0 univer-flex-1 univer-truncate" title={item.name}>{item.name}</span>+ <ObjectPermissionButton {...item} />+ </div>+ ))}+ {!items.length && <p>{localeService.t<LocaleKey>('ui.objectPermission.empty')}</p>}+ {more && <Button onClick={() => setLimit((value) => value + 50)}>{localeService.t<LocaleKey>('ui.objectPermission.loadMore')}</Button>}+ </div>+ </div>+ );+}diff --git a/packages/ui/src/views/object-permission/__tests__/ObjectPermissionButton.spec.tsx b/packages/ui/src/views/object-permission/__tests__/ObjectPermissionButton.spec.tsxnew file mode 100644index 0000000000..218805253f--- /dev/null+++ b/packages/ui/src/views/object-permission/__tests__/ObjectPermissionButton.spec.tsx@@ -0,0 +1,374 @@+/**+ * 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 { IObjectPermissionPolicy } from '@univerjs/core';+import type {+ IAllowedRequest,+ ICollaborator,+ ICreateRequest,+ IListPermPointResponse,+} from '@univerjs/protocol';+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import {+ CommandType,+ IAuthzIoService,+ ICommandService,+ IConfigService,+ IPermissionService,+ IResourceManagerService,+ LocaleType,+ OBJECT_PERMISSION_CONFIG_KEY,+ ObjectPermissionRuleModel,+ ObjectPermissionService,+ PermissionStatus,+ Univer,+ UniverInstanceType,+ UserManagerService,+} from '@univerjs/core';+import { UnitAction, UnitObject, UnitRole } from '@univerjs/protocol';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { ComponentManager } from '../../../common/component-manager';+import { IconManager } from '../../../common/icon-manager';+import enUS from '../../../locale/en-US';+import { DesktopDialogService } from '../../../services/dialog/desktop-dialog.service';+import { IDialogService } from '../../../services/dialog/dialog.service';+import { IUIPartsService, UIPartsService } from '../../../services/parts/parts.service';+import { RediProvider } from '../../../utils/di';+import { DialogPart } from '../../components/dialog-part/DialogPart';+import {+ OBJECT_PERMISSION_DIALOG,+ ObjectPermissionButton,+ ObjectPermissionDialog,+ openObjectPermissionDialog,+} from '../ObjectPermissionButton';++class TestRuleModel extends ObjectPermissionRuleModel {+ constructor(@IResourceManagerService resources: IResourceManagerService) {+ super(resources, 'DOC_TEST_PERMISSION_PLUGIN', UniverInstanceType.UNIVER_DOC, [UnitObject.DocumentEntity, UnitObject.DocumentSection]);+ }+}++const univers: Univer[] = [];+afterEach(() => {+ cleanup();+ univers.splice(0).forEach((univer) => univer.dispose());+});++function setup(options: { capable?: boolean; manage?: boolean; delete?: boolean; collaborators?: ICollaborator[]; inherit?: boolean; currentUser?: string } = {}) {+ let policies: IListPermPointResponse['objects'] = [];+ let members: ICollaborator[] = [];+ const create = vi.fn(async (request: ICreateRequest) => {+ const payload = request.documentObject!;+ members = payload.collaborators;+ policies = [{ ...payload, objectID: 'permission-1', objectType: request.objectType, shareOn: false, shareRole: UnitRole.Reader, shareScope: 0, creator: undefined, actions: [] }];+ return 'permission-1';+ });+ const listCollaborators = vi.fn(async ({ objectID }: { objectID: string }) => objectID === 'doc'+ ? options.collaborators ?? [{ id: 'editor', role: UnitRole.Editor, subject: { userID: 'editor', name: 'Editor', avatar: '' } }]+ : members);+ const authz = {+ getCfgEnableObjInherit: () => options.inherit ?? false,+ list: async () => policies,+ listCollaborators,+ allowed: async ({ actions }: IAllowedRequest) => actions.map((action) => ({ action, allowed: action === UnitAction.Delete ? options.delete === true : options.manage !== false })),+ batchAllowed: async (requests: IAllowedRequest[]) => requests.map(({ unitID, objectID, actions }) => ({ unitID, objectID, actions: actions.map((action) => ({ action, allowed: true })) })),+ create,+ };+ const univer = new Univer({ locale: LocaleType.EN_US, locales: { [LocaleType.EN_US]: enUS }, override: [[IAuthzIoService, { useValue: authz }]] });+ univers.push(univer);+ univer.createUnit(UniverInstanceType.UNIVER_DOC, { id: 'doc', title: 'Document', body: { dataStream: '\r\n' } });+ const injector = univer.__getInjector();+ injector.add([TestRuleModel]);+ const rules = injector.get(TestRuleModel);+ injector.get(IConfigService).setConfig(OBJECT_PERMISSION_CONFIG_KEY, options.capable === false ? [] : [UnitObject.Document, UnitObject.DocumentEntity]);+ injector.get(ObjectPermissionService).registerRuleModel(UnitObject.Document, rules, 'test.mutation.permission');+ if (options.currentUser) {+ injector.get(UserManagerService).setCurrentUser({ userID: options.currentUser, name: options.currentUser });+ }+ injector.get(IPermissionService).addPermissionPoint({ id: `${UnitObject.Document}.${UnitAction.Edit}_doc`, type: UnitObject.Document, subType: UnitAction.Edit, value: true, status: PermissionStatus.DONE });+ const service = injector.get(ObjectPermissionService);+ injector.get(ICommandService).registerCommand({ id: 'test.mutation.permission', type: CommandType.MUTATION, handler: (_, params: { unitId: string; objectId: string; objectType: UnitObject; rule: { objectId: string; objectType: UnitObject; permissionId: string } | null }) => rules.setRule(params.unitId, params.objectType, params.objectId, params.rule) });+ injector.get(ICommandService).registerCommand({+ id: 'test.command.set-permission',+ type: CommandType.COMMAND,+ handler: async (_, params: { policy: IObjectPermissionPolicy; remove?: boolean } | undefined) => {+ if (!params) {+ return false;+ }+ const target = { unitId: 'doc', objectId: 'entity//drawing/image', objectType: UnitObject.DocumentEntity };+ if (params.remove) {+ await service.remove(target);+ } else {+ await service.save(target, params.policy);+ }+ return true;+ },+ });+ const target = { unitId: 'doc', objectId: 'entity//drawing/image', objectType: UnitObject.DocumentEntity };+ const view = render(<RediProvider value={{ injector }}><ObjectPermissionButton target={target} name="Image" commandId="test.command.set-permission" /></RediProvider>);+ return { rules, create, listCollaborators, service, target, injector, view };+}++describe('ObjectPermissionButton', () => {+ it('hides the action for a provider without object management', () => {+ setup({ capable: false });+ expect(screen.queryByRole('button', { name: 'Permissions' })).toBeNull();+ });++ it('shows a read-only dialog when the user cannot manage the object', async () => {+ setup({ manage: false });+ fireEvent.click(screen.getByRole('button', { name: 'Permissions' }));+ await screen.findByText('You cannot manage permissions for this object.');+ expect(screen.getByRole('button', { name: 'Save' }).hasAttribute('disabled')).toBe(true);+ });++ it('rechecks an open dialog when the current user changes', async () => {+ const options = { manage: true, currentUser: 'manager' };+ const { injector, create } = setup(options);+ fireEvent.click(screen.getByRole('button', { name: 'Permissions' }));+ fireEvent.click(await screen.findByText('Object owner only'));+ expect(screen.getByRole('button', { name: 'Save' }).hasAttribute('disabled')).toBe(false);+ options.manage = false;+ act(() => injector.get(UserManagerService).setCurrentUser({ userID: 'editor', name: 'Editor' }));+ await screen.findByText('You cannot manage permissions for this object.');+ expect(screen.getByRole('button', { name: 'Save' }).hasAttribute('disabled')).toBe(true);+ expect(screen.getByRole('radio', { name: 'Object owner only' }).hasAttribute('disabled')).toBe(true);+ expect(create).not.toHaveBeenCalled();+ });++ it('disables the permission entry when file editing is revoked', () => {+ const { injector } = setup();+ act(() => injector.get(IPermissionService).updatePermissionPoint(`${UnitObject.Document}.${UnitAction.Edit}_doc`, false));+ expect(screen.getByRole('button', { name: 'Permissions' }).hasAttribute('disabled')).toBe(true);+ fireEvent.click(screen.getByRole('button', { name: 'Permissions' }));+ expect(screen.queryByRole('dialog')).toBeNull();+ });++ it('removes an existing rule through the product command and restores inheritance', async () => {+ const { service, target, rules } = setup({ delete: true });+ await act(() => service.save(target, { edit: 'owner', strategies: [], collaborators: [] }));+ fireEvent.click(screen.getByRole('button', { name: 'Permissions' }));+ fireEvent.click(await screen.findByRole('button', { name: 'Remove protection' }));+ await waitFor(() => expect(rules.getRules('doc')).toEqual([]));+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());+ expect(service.hasPolicy(target)).toBe(false);+ });++ it('saves a restriction through a Command and shows primary even when the owner can still edit', async () => {+ const { create, service, target } = setup();+ fireEvent.click(screen.getByRole('button', { name: 'Permissions' }));+ fireEvent.click(await screen.findByText('Object owner only'));+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));+ await waitFor(() => expect(create).toHaveBeenCalledTimes(1));+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());+ expect(service.hasPolicy(target)).toBe(true);+ expect(screen.getByRole('button', { name: 'Permissions' }).className).toContain('text-primary');+ });++ it('searches people inline, preserves hidden selections, and persists with one Save', async () => {+ const { create } = setup({ collaborators: [+ { id: 'alice', role: UnitRole.Editor, subject: { userID: 'alice', name: 'Alice', avatar: '' } },+ { id: 'bob', role: UnitRole.Editor, subject: { userID: 'bob', name: 'Bob', avatar: '' } },+ { id: 'reader', role: UnitRole.Reader, subject: { userID: 'reader', name: 'Reader', avatar: '' } },+ ] });+ fireEvent.click(screen.getByRole('button', { name: 'Permissions' }));+ fireEvent.click(await screen.findByText('Selected members'));+ expect(screen.getByRole('button', { name: 'Save' }).hasAttribute('disabled')).toBe(true);+ await screen.findByRole('checkbox', { name: /^Alice / });+ expect(screen.getAllByRole('dialog')).toHaveLength(1);+ expect(screen.queryByText('Reader')).toBeNull();+ const search = screen.getByRole('textbox', { name: 'Search people' });+ fireEvent.change(search, { target: { value: ' ALICE ' } });+ expect(screen.queryByText('Bob')).toBeNull();+ fireEvent.click(screen.getByRole('checkbox', { name: /^Alice / }));+ fireEvent.change(search, { target: { value: 'missing' } });+ expect(screen.getByText('No matching people')).toBeTruthy();+ expect(screen.getByText('Selected: 1')).toBeTruthy();+ fireEvent.change(search, { target: { value: 'bob' } });+ fireEvent.click(screen.getByRole('checkbox', { name: /^Bob / }));+ expect(create).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));+ await waitFor(() => expect(create).toHaveBeenCalledTimes(1));+ expect(create.mock.calls[0][0].documentObject?.collaborators.map((user) => user.id)).toEqual(['alice', 'bob']);+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());+ fireEvent.click(screen.getByRole('button', { name: 'Permissions' }));+ await waitFor(() => expect((screen.getByRole('checkbox', { name: /^Alice / }) as HTMLInputElement).checked).toBe(true));+ expect((screen.getByRole('checkbox', { name: /^Bob / }) as HTMLInputElement).checked).toBe(true);+ });++ it('discards unsaved choices on Cancel and supports deselecting a person inline', async () => {+ const { create } = setup();+ fireEvent.click(screen.getByRole('button', { name: 'Permissions' }));+ fireEvent.click(await screen.findByText('Selected members'));+ fireEvent.click(await screen.findByRole('checkbox', { name: /^Editor / }));+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());+ expect(create).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'Permissions' }));+ fireEvent.click(await screen.findByText('Selected members'));+ const editor = await screen.findByRole('checkbox', { name: /^Editor / });+ expect((editor as HTMLInputElement).checked).toBe(false);+ fireEvent.click(editor);+ expect(screen.getByRole('button', { name: 'Save' }).hasAttribute('disabled')).toBe(false);+ fireEvent.click(editor);+ expect(screen.getByText('Selected: 0')).toBeTruthy();+ expect(screen.getByRole('button', { name: 'Save' }).hasAttribute('disabled')).toBe(true);+ });++ it('loads candidates only for selected-member policies and supports retrying inline', async () => {+ const { listCollaborators, create } = setup();+ fireEvent.click(screen.getByRole('button', { name: 'Permissions' }));+ await screen.findByText('Selected members');+ expect(listCollaborators.mock.calls.map(([request]) => request.objectID)).toEqual([]);+ listCollaborators.mockRejectedValueOnce(new Error('Offline'));+ fireEvent.click(screen.getByText('Selected members'));+ expect(await screen.findByRole('alert')).toBeTruthy();+ expect(screen.getByRole('button', { name: 'Save' }).hasAttribute('disabled')).toBe(true);+ fireEvent.click(screen.getByRole('button', { name: 'Reload' }));+ expect(await screen.findByRole('checkbox', { name: /^Editor / })).toBeTruthy();+ fireEvent.change(screen.getByRole('textbox', { name: 'Search people' }), { target: { value: 'edi' } });+ expect(listCollaborators.mock.calls.map(([request]) => request.objectID)).toEqual(['doc', 'doc']);+ expect(create).not.toHaveBeenCalled();+ });++ it('separates names from file roles and respects inherited owner access', async () => {+ setup({ currentUser: 'me', inherit: true, collaborators: [+ { id: 'me', role: UnitRole.Editor, subject: { userID: 'me', name: 'Me', avatar: '' } },+ { id: 'owner', role: UnitRole.Owner, subject: { userID: 'owner', name: 'Alice', avatar: '' } },+ { id: 'editor', role: UnitRole.Editor, subject: { userID: 'editor', name: 'Bob', avatar: '' } },+ ] });+ fireEvent.click(screen.getByRole('button', { name: 'Permissions' }));+ fireEvent.click(await screen.findByText('Selected members'));+ const owner = await screen.findByRole('checkbox', { name: /^Alice / });+ expect(owner.hasAttribute('disabled')).toBe(true);+ expect(screen.getByText('File owner, inherited access')).toBeTruthy();+ expect(screen.getByText('File editor')).toBeTruthy();+ expect(screen.queryByText('Me')).toBeNull();+ });++ it('preserves members omitted by the candidate service and matches candidates by user ID', async () => {+ const { service, target } = setup({ collaborators: [+ { id: 'file-alice', role: UnitRole.Owner, subject: { userID: 'alice', name: 'Alice', avatar: '' } },+ ] });+ await act(() => service.save(target, {+ edit: 'members',+ strategies: [],+ collaborators: [+ { id: 'object-alice', role: UnitRole.Editor, subject: { userID: 'alice', name: 'Alice', avatar: '' } },+ { id: 'bob', role: UnitRole.Editor, subject: { userID: 'bob', name: 'Bob', avatar: '' } },+ ],+ }));+ fireEvent.click(screen.getByRole('button', { name: 'Permissions' }));+ await screen.findByText('File owner');+ expect(screen.getAllByRole('checkbox', { name: /^Alice / })).toHaveLength(1);+ expect((screen.getByRole('checkbox', { name: /^Alice / }) as HTMLInputElement).checked).toBe(true);+ expect((screen.getByRole('checkbox', { name: /^Bob / }) as HTMLInputElement).checked).toBe(true);+ fireEvent.click(screen.getByRole('checkbox', { name: /^Alice / }));+ expect(screen.getByText('Selected: 1')).toBeTruthy();+ });++ it('keeps selected people when saving fails and supports retrying Save', async () => {+ const { create } = setup();+ create.mockRejectedValueOnce(new Error('Offline'));+ fireEvent.click(screen.getByRole('button', { name: 'Permissions' }));+ fireEvent.click(await screen.findByText('Selected members'));+ fireEvent.click(await screen.findByRole('checkbox', { name: /^Editor / }));+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));+ await screen.findByRole('alert');+ expect((screen.getByRole('checkbox', { name: /^Editor / }) as HTMLInputElement).checked).toBe(true);+ expect(screen.getByRole('button', { name: 'Save' }).hasAttribute('disabled')).toBe(false);+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));+ await waitFor(() => expect(create).toHaveBeenCalledTimes(2));+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());+ expect(create.mock.calls[1][0].documentObject?.collaborators.map((user) => user.id)).toEqual(['editor']);+ });++ it('requires reloading when remote policy changes while a draft is being edited', async () => {+ const { service } = setup();+ fireEvent.click(screen.getByRole('button', { name: 'Permissions' }));+ fireEvent.click(await screen.findByText('Object owner only'));+ await act(() => service.refreshUnit('doc'));+ await screen.findByText('Permissions changed. Reload before saving.');+ expect(screen.getByRole('button', { name: 'Save' }).hasAttribute('disabled')).toBe(true);+ });+});++describe('workbench object permission dialog', () => {+ function openHostedDialog(exists: () => boolean = () => true) {+ const context = setup();+ context.view.unmount();+ const { injector, target } = context;+ injector.add([ComponentManager]);+ injector.add([IconManager]);+ injector.add([IUIPartsService, { useClass: UIPartsService }]);+ injector.add([IDialogService, { useClass: DesktopDialogService }]);+ injector.get(ComponentManager).register(OBJECT_PERMISSION_DIALOG, ObjectPermissionDialog);+ const openDialog = () => {+ expect(openObjectPermissionDialog(injector, {+ target,+ name: 'Original image',+ commandId: 'test.command.set-permission',+ exists,+ })).toBe(true);+ };+ const host = render(+ <RediProvider value={{ injector }}>+ <div><button onClick={openDialog}>Open from toolbar</button></div>+ <DialogPart />+ </RediProvider>+ );+ fireEvent.click(screen.getByRole('button', { name: 'Open from toolbar' }));+ host.rerender(+ <RediProvider value={{ injector }}>+ <div />+ <DialogPart />+ </RediProvider>+ );+ return context;+ }++ it('saves through the shared dialog after the originating toolbar unmounts', async () => {+ const { create } = openHostedDialog();+ await screen.findByText('Original image');+ fireEvent.click(await screen.findByText('Object owner only'));+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));+ await waitFor(() => expect(create).toHaveBeenCalledTimes(1));+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());+ });++ it('selects people inline in a hosted toolbar dialog and saves once', async () => {+ const { create } = openHostedDialog();+ fireEvent.click(await screen.findByText('Selected members'));+ fireEvent.change(screen.getByRole('textbox', { name: 'Search people' }), { target: { value: 'editor' } });+ fireEvent.click(await screen.findByRole('checkbox', { name: /^Editor / }));+ expect(screen.getAllByRole('dialog')).toHaveLength(1);+ expect(create).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));+ await waitFor(() => expect(create).toHaveBeenCalledTimes(1));+ expect(create.mock.calls[0][0].documentObject?.collaborators.map((user) => user.id)).toEqual(['editor']);+ });++ it('rejects saving if the original element was deleted while the dialog was open', async () => {+ let exists = true;+ const { create } = openHostedDialog(() => exists);+ fireEvent.click(await screen.findByText('Object owner only'));+ exists = false;+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));+ await screen.findByRole('alert');+ expect(create).not.toHaveBeenCalled();+ expect(screen.getByRole('dialog')).toBeTruthy();+ });+});diff --git a/packages/ui/src/views/object-permission/__tests__/ObjectPermissionPanel.spec.tsx b/packages/ui/src/views/object-permission/__tests__/ObjectPermissionPanel.spec.tsxnew file mode 100644index 0000000000..2692a15aec--- /dev/null+++ b/packages/ui/src/views/object-permission/__tests__/ObjectPermissionPanel.spec.tsx@@ -0,0 +1,85 @@+/**+ * 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 { IObjectPermissionButtonProps } from '../ObjectPermissionButton';+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';+import {+ CommandType,+ IAuthzIoService,+ ICommandService,+ IConfigService,+ IResourceManagerService,+ LocaleType,+ OBJECT_PERMISSION_CONFIG_KEY,+ ObjectPermissionRuleModel,+ ObjectPermissionService,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { UnitObject } from '@univerjs/protocol';+import { afterEach, expect, it, vi } from 'vitest';+import enUS from '../../../locale/en-US';+import { DesktopSidebarService } from '../../../services/sidebar/desktop-sidebar.service';+import { ISidebarService } from '../../../services/sidebar/sidebar.service';+import { RediProvider } from '../../../utils/di';+import { ObjectPermissionPanel } from '../ObjectPermissionPanel';++class TestRuleModel extends ObjectPermissionRuleModel {+ constructor(@IResourceManagerService resources: IResourceManagerService) {+ super(resources, 'DOC_TEST_PERMISSION_PLUGIN', UniverInstanceType.UNIVER_DOC, [UnitObject.DocumentEntity, UnitObject.DocumentSection]);+ }+}++let univer: Univer;+afterEach(() => {+ cleanup();+ univer?.dispose();+});+it('does not enumerate collapsed scopes or rescan them on editing commands, and loads more on demand', () => {+ const list = vi.fn();+ univer = new Univer({ locale: LocaleType.EN_US, locales: { [LocaleType.EN_US]: enUS }, override: [[IAuthzIoService, { useValue: {+ list,+ } }]] });+ univer.createUnit(UniverInstanceType.UNIVER_DOC, { id: 'doc', body: { dataStream: '\r\n' } });+ const injector = univer.__getInjector();+ injector.add([TestRuleModel]);+ const rules = injector.get(TestRuleModel);+ injector.get(IConfigService).setConfig(OBJECT_PERMISSION_CONFIG_KEY, [UnitObject.Document, UnitObject.DocumentSection]);+ injector.get(ObjectPermissionService).registerRuleModel(UnitObject.Document, rules, 'test.mutation.permission');+ injector.add([ISidebarService, { useClass: DesktopSidebarService }]);+ let enumerated = 0;+ function* getTargets(): Iterable<IObjectPermissionButtonProps> {+ yield { target: { unitId: 'doc', objectId: 'doc', objectType: UnitObject.Document }, name: 'Document', commandId: 'test.permission' };+ for (let i = 0; i < 10000; i++) {+ enumerated++;+ yield { target: { unitId: 'doc', objectId: `section/${i}`, objectType: UnitObject.DocumentSection }, name: String(i), commandId: 'test.permission' };+ }+ }+ render(<RediProvider value={{ injector }}><ObjectPermissionPanel unitId="doc" getTargets={getTargets} expandable={UnitObject.DocumentSection} /></RediProvider>);+ expect(enumerated).toBe(0);+ fireEvent.click(screen.getByRole('button', { name: 'Section' }));+ expect(enumerated).toBeLessThanOrEqual(51);+ expect(screen.getAllByRole('button', { name: 'Permissions' })).toHaveLength(50);+ const count = enumerated;+ injector.get(ICommandService).registerCommand({ id: 'test.edit', type: CommandType.COMMAND, handler: () => true });+ act(() => {+ injector.get(ICommandService).syncExecuteCommand('test.edit');+ });+ expect(enumerated).toBe(count);+ fireEvent.click(screen.getByRole('button', { name: 'Load more' }));+ expect(screen.getAllByRole('button', { name: 'Permissions' })).toHaveLength(100);+ expect(list).not.toHaveBeenCalled();+});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 73da0042ee..9fdd10b51c 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -2749,6 +2749,9 @@ importers:'@univerjs/icons':specifier: 1.38.0+ '@univerjs/protocol':+ specifier: workspace:*+ version: link:../protocol'@wendellhu/redi':specifier: 1.1.2version: 1.1.2([email protected])