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
fix(sheets): validate formula permissions before auto-fill (#7929)
wpxp1234567412fe0e3e0d
diff --git a/packages/sheets-formula/src/controllers/__tests__/formula-auto-fill.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/formula-auto-fill.controller.spec.tsindex 3525bf0f20..2c1bd89afe 100644--- a/packages/sheets-formula/src/controllers/__tests__/formula-auto-fill.controller.spec.ts+++ b/packages/sheets-formula/src/controllers/__tests__/formula-auto-fill.controller.spec.ts@@ -14,11 +14,55 @@* limitations under the License.*/-import type { Dependency, Direction, ICellData, Nullable } from '@univerjs/core';+import type {+ Dependency,+ Direction,+ ICellData,+ IObjectMatrixPrimitiveType,+ IRange,+ IWorkbookData,+ Nullable,+ Workbook,+} from '@univerjs/core';import type { IAutoFillLocation } from '@univerjs/sheets';-import { BooleanNumber, FormulaType } from '@univerjs/core';-import { LexerTreeBuilder } from '@univerjs/engine-formula';-import { AUTO_FILL_APPLY_TYPE, AUTO_FILL_DATA_TYPE, AutoFillService, IAutoFillService } from '@univerjs/sheets';+import {+ BooleanNumber,+ FormulaType,+ ICommandService,+ IPermissionService,+ IUndoRedoService,+ IUniverInstanceService,+ LocaleService,+ LocaleType,+ mergeWorksheetSnapshotWithDefault,+ RedoCommand,+ Tools,+ UndoCommand,+ UniverInstanceType,+} from '@univerjs/core';+import { FormulaDataModel, IDefinedNamesService, LexerTreeBuilder } from '@univerjs/engine-formula';+import {+ AddRangeProtectionMutation,+ AddWorksheetMergeMutation,+ AUTO_FILL_APPLY_TYPE,+ AUTO_FILL_DATA_TYPE,+ AutoFillCommand,+ AutoFillController,+ AutoFillService,+ EditStateEnum,+ IAutoFillService,+ InsertSheetMutation,+ RangeProtectionPermissionEditPoint,+ RangeProtectionPermissionViewPoint,+ RefillCommand,+ RemoveWorksheetMergeMutation,+ SetRangeValuesCommand,+ SetRangeValuesMutation,+ SetSelectionsOperation,+ SheetPermissionCheckController,+ SheetsSelectionsService,+ ViewStateEnum,+} from '@univerjs/sheets';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { createFacadeTestBed } from '../../facade/__tests__/create-test-bed';import { FormulaAutoFillController } from '../formula-auto-fill.controller';@@ -197,4 +241,565 @@ describe('FormulaAutoFillController', () => {}});++ describe('formula view permissions', () => {+ let commandService: ICommandService;+ let workbook: Workbook;+ let messages: string[];++ beforeEach(() => {+ const { injector } = testBed;+ injector.add([AutoFillController]);+ injector.add([SheetPermissionCheckController]);+ injector.get(AutoFillController);+ messages = [];+ injector.get(SheetPermissionCheckController).triggerPermissionUIEvent$.subscribe((message) => messages.push(message));+ const localeService = injector.get(LocaleService);+ localeService.setLocale(LocaleType.EN_US);+ localeService.setDirection('ltr');+ commandService = injector.get(ICommandService);+ workbook = injector.get(IUniverInstanceService).getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;+ for (const command of [+ AutoFillCommand,+ RefillCommand,+ SetRangeValuesMutation,+ SetSelectionsOperation,+ AddWorksheetMergeMutation,+ RemoveWorksheetMergeMutation,+ AddRangeProtectionMutation,+ InsertSheetMutation,+ SetRangeValuesCommand,+ ]) {+ commandService.registerCommand(command);+ }+ setCells({+ 4: { 1: { v: 123 }, 2: { f: '=B5' } },+ 6: { 1: { v: 'private value' }, 2: { v: 'existing target' } },+ });+ });++ function setCells(cellValue: IObjectMatrixPrimitiveType<ICellData>) {+ commandService.syncExecuteCommand(SetRangeValuesMutation.id, { unitId: 'test', subUnitId: 'sheet1', cellValue });+ }++ function protect(row: number, column: number, canView = false, subUnitId = 'sheet1', unitId = 'test') {+ const permissionId = `protected-${row}-${column}`;+ const view = new RangeProtectionPermissionViewPoint(unitId, subUnitId, permissionId);+ commandService.syncExecuteCommand(AddRangeProtectionMutation.id, {+ unitId,+ subUnitId,+ rules: [{+ id: permissionId,+ permissionId,+ unitId,+ subUnitId,+ ranges: [{ startRow: row, endRow: row, startColumn: column, endColumn: column }],+ unitType: view.type,+ viewState: canView ? ViewStateEnum.OthersCanView : ViewStateEnum.NoOneElseCanView,+ editState: EditStateEnum.OnlyMe,+ }],+ });+ const permissionService = testBed.injector.get(IPermissionService);+ view.value = canView;+ permissionService.addPermissionPoint(view);+ const edit = new RangeProtectionPermissionEditPoint(unitId, subUnitId, permissionId);+ edit.value = false;+ permissionService.addPermissionPoint(edit);+ }++ function fill(applyType = AUTO_FILL_APPLY_TYPE.COPY, sourceRange: IRange = {+ startRow: 4,+ endRow: 4,+ startColumn: 2,+ endColumn: 2,+ }, targetRange: IRange = { ...sourceRange, endRow: 14 }) {+ return commandService.executeCommand(AutoFillCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ sourceRange,+ targetRange,+ applyType,+ });+ }++ function snapshot() {+ return Tools.deepClone(workbook.getActiveSheet().getCellMatrix().getMatrix());+ }++ it.each([AUTO_FILL_APPLY_TYPE.COPY, AUTO_FILL_APPLY_TYPE.NO_FORMAT])(+ 'rejects a hidden reference in a shared follower before any writes (%s)',+ async (applyType) => {+ protect(6, 1);+ const before = snapshot();+ const undoRedoService = testBed.injector.get(IUndoRedoService);+ const history = undoRedoService.getUndoRedoStatus('test');+ const selectionService = testBed.injector.get(SheetsSelectionsService);+ const selections = Tools.deepClone(selectionService.getCurrentSelections());+ const mutations: string[] = [];+ commandService.onCommandExecuted(({ id }) => {+ if ([SetRangeValuesMutation.id, SetSelectionsOperation.id].includes(id)) {+ mutations.push(id);+ }+ });++ expect(await fill(applyType)).toBe(false);+ expect(snapshot()).toEqual(before);+ expect(mutations).toEqual([]);+ expect(selectionService.getCurrentSelections()).toEqual(selections);+ expect(undoRedoService.getUndoRedoStatus('test')).toEqual(history);+ expect(messages).toHaveLength(1);+ }+ );++ it('resolves a source cell that only contains a shared formula id', async () => {+ setCells({ 3: { 2: { f: '=B4', si: 'source-formula' } }, 4: { 2: { f: null, si: 'source-formula' } } });+ protect(6, 1);+ const before = snapshot();+ expect(await fill()).toBe(false);+ expect(snapshot()).toEqual(before);+ });++ it.each(['=$B5', '=sheet1!B5', '=SUM(B5:B6)'])(+ 'checks the final references for %s',+ async (formula) => {+ setCells({ 4: { 2: { f: formula } } });+ protect(6, 1);+ const before = snapshot();+ expect(await fill()).toBe(false);+ expect(snapshot()).toEqual(before);+ }+ );++ it('checks horizontal fill references', async () => {+ setCells({ 4: { 2: { f: '=B5' } } });+ protect(4, 3);+ const before = snapshot();+ expect(await fill(AUTO_FILL_APPLY_TYPE.COPY, { startRow: 4, endRow: 4, startColumn: 2, endColumn: 2 }, { startRow: 4, endRow: 4, startColumn: 2, endColumn: 4 })).toBe(false);+ expect(snapshot()).toEqual(before);+ });++ it.each([+ { sourceColumn: 2, startRow: 0, startColumn: 2, hiddenRow: 2, hiddenColumn: 1, formula: '=B5' },+ { sourceColumn: 4, startRow: 4, startColumn: 2, hiddenRow: 4, hiddenColumn: 1, formula: '=D5' },+ ])('checks references when filling up or left ($formula)', async (data) => {+ setCells({ 4: { [data.sourceColumn]: { f: data.formula } } });+ protect(data.hiddenRow, data.hiddenColumn);+ const before = snapshot();+ expect(await fill(AUTO_FILL_APPLY_TYPE.COPY, { startRow: 4, endRow: 4, startColumn: data.sourceColumn, endColumn: data.sourceColumn }, { startRow: data.startRow, endRow: 4, startColumn: data.startColumn, endColumn: data.sourceColumn })).toBe(false);+ expect(snapshot()).toEqual(before);+ });++ it.each([false, true])('checks references on another sheet (%s)', async (crossSheetReference) => {+ commandService.syncExecuteCommand(InsertSheetMutation.id, {+ unitId: 'test',+ index: 1,+ sheet: mergeWorksheetSnapshotWithDefault({+ id: 'sheet2',+ name: 'sheet2',+ cellData: { 4: { 2: { f: '=B5' } }, 6: { 1: { v: 'private value' } } },+ }),+ });+ protect(6, 1, false, 'sheet2');+ if (crossSheetReference) {+ setCells({ 4: { 2: { f: '=sheet2!B5' } } });+ }+ const before = Tools.deepClone(workbook.getSnapshot());+ expect(await commandService.executeCommand(AutoFillCommand.id, {+ unitId: 'test',+ subUnitId: crossSheetReference ? 'sheet1' : 'sheet2',+ sourceRange: { startRow: 4, endRow: 4, startColumn: 2, endColumn: 2 },+ targetRange: { startRow: 4, endRow: 14, startColumn: 2, endColumn: 2 },+ applyType: AUTO_FILL_APPLY_TYPE.COPY,+ })).toBe(false);+ expect(workbook.getSnapshot()).toEqual(before);+ });++ it('uses the same view permission check for direct formula entry and named references', async () => {+ protect(6, 1);+ const before = snapshot();+ expect(await commandService.executeCommand(SetRangeValuesCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ range: { startRow: 6, endRow: 6, startColumn: 2, endColumn: 2 },+ value: { f: '=B7' },+ })).toBe(false);+ expect(snapshot()).toEqual(before);++ testBed.injector.get(IDefinedNamesService).registerDefinedName('test', {+ id: 'private-cell',+ name: 'PrivateCell',+ formulaOrRefString: 'sheet1!$B$7',+ });+ setCells({ 4: { 2: { f: '=PrivateCell' } } });+ const beforeFill = snapshot();+ expect(await fill()).toBe(false);+ expect(snapshot()).toEqual(beforeFill);+ });++ it.each([+ '=SUM(PrivateCell)',+ '=PrivateAlias',+ '=PrivateCell&""',+ '=SUM(PrivateAlias,PrivateAlias)',+ ])('checks nested names in %s against view permissions', async (formula) => {+ const definedNames = testBed.injector.get(IDefinedNamesService);+ definedNames.registerDefinedName('test', {+ id: 'private-cell',+ name: 'PrivateCell',+ formulaOrRefString: 'sheet1!$B$7',+ });+ definedNames.registerDefinedName('test', {+ id: 'private-alias',+ name: 'PrivateAlias',+ formulaOrRefString: '=PrivateCell',+ });+ setCells({ 4: { 2: { f: formula } } });+ protect(6, 1);+ const before = snapshot();+ expect(await fill()).toBe(false);+ expect(snapshot()).toEqual(before);++ testBed.injector.get(IPermissionService).updatePermissionPoint(+ new RangeProtectionPermissionViewPoint('test', 'sheet1', 'protected-6-1').id,+ true+ );+ expect(await fill()).toBe(true);+ });++ it.each([+ { definition: '=$B$7', protectedSheet: 'sheet1', permitted: false },+ { definition: '=$B$7', protectedSheet: 'sheet2', permitted: true },+ { definition: '$B$7', protectedSheet: 'sheet1', permitted: false },+ { definition: '=PrivateAlias', protectedSheet: 'sheet1', permitted: false },+ { definition: '=sheet2!$B$7', protectedSheet: 'sheet1', permitted: true },+ { definition: '=sheet2!$B$7', protectedSheet: 'sheet2', permitted: false },+ ])('checks qualified names in their evaluation context ($definition, $protectedSheet)', async ({ definition, protectedSheet, permitted }) => {+ commandService.syncExecuteCommand(InsertSheetMutation.id, {+ unitId: 'test',+ index: 1,+ sheet: mergeWorksheetSnapshotWithDefault({+ id: 'sheet2',+ name: 'sheet2',+ cellData: { 6: { 1: { v: 'other sheet value' } } },+ }),+ });+ const definedNames = testBed.injector.get(IDefinedNamesService);+ definedNames.registerDefinedName('test', {+ id: 'qualified-private',+ name: 'QualifiedPrivate',+ formulaOrRefString: definition,+ });+ definedNames.registerDefinedName('test', {+ id: 'private-alias',+ name: 'PrivateAlias',+ formulaOrRefString: '=$B$7',+ });+ setCells({ 4: { 2: { f: '=sheet2!QualifiedPrivate' } } });+ protect(6, 1, false, protectedSheet);+ const before = Tools.deepClone(workbook.getSnapshot());+ expect(await fill()).toBe(permitted);+ if (!permitted) {+ expect(workbook.getSnapshot()).toEqual(before);+ }+ });++ it.each([+ { formula: '=sheet2!ScopedCell', localIsHidden: false },+ { formula: '=sheet2!ScopedCell', localIsHidden: true },+ { formula: '=sheet2!QualifiedPrivate', localIsHidden: false },+ { formula: '=sheet2!QualifiedPrivate', localIsHidden: true },+ ])('resolves qualified names in the target sheet scope ($formula, $localIsHidden)', async ({ formula, localIsHidden }) => {+ commandService.syncExecuteCommand(InsertSheetMutation.id, {+ unitId: 'test',+ index: 1,+ sheet: mergeWorksheetSnapshotWithDefault({ id: 'sheet2', name: 'sheet2' }),+ });+ const definedNames = testBed.injector.get(IDefinedNamesService);+ definedNames.registerDefinedName('test', {+ id: 'qualified-private',+ name: 'QualifiedPrivate',+ formulaOrRefString: '=ScopedCell',+ });+ definedNames.registerDefinedName('test', {+ id: 'workbook-cell',+ name: 'ScopedCell',+ formulaOrRefString: localIsHidden ? '=$B$5' : '=$B$7',+ });+ definedNames.registerDefinedName('test', {+ id: 'local-cell',+ name: 'ScopedCell',+ localSheetId: 'sheet1',+ formulaOrRefString: localIsHidden ? '=$B$7' : '=$B$5',+ });+ setCells({ 4: { 2: { f: formula } } });+ protect(6, 1);+ expect(await fill()).toBe(!localIsHidden);+ });++ it.each([undefined, 'sheet1'].flatMap((localSheetId) =>+ [false, true].map((canView) => ({ localSheetId, canView }))+ ))('checks names with a missing sheet prefix ($localSheetId, viewable: $canView)', async ({ localSheetId, canView }) => {+ testBed.injector.get(IDefinedNamesService).registerDefinedName('test', {+ id: 'hidden-global',+ name: 'HiddenGlobal',+ formulaOrRefString: '=sheet1!$B$7',+ localSheetId,+ });+ setCells({ 4: { 2: { f: '=MissingSheet!HiddenGlobal' } } });+ protect(6, 1, canView);+ const before = snapshot();+ const permitted = canView || localSheetId === 'sheet1';+ expect(await fill()).toBe(permitted);+ if (!permitted) {+ expect(snapshot()).toEqual(before);+ }+ });++ it.each(['external-book', 'Source.xlsx', 'source.XLSX', 'SOURCE'].flatMap((qualifier) =>+ [false, true].map((canView) => ({ qualifier, canView }))+ ))('checks workbook references by ID or name ($qualifier, viewable: $canView)', async ({ qualifier, canView }) => {+ testBed.univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, {+ id: 'external-book',+ name: 'Source.xlsx',+ locale: LocaleType.EN_US,+ appVersion: '1',+ sheets: { source: mergeWorksheetSnapshotWithDefault({ id: 'source', name: 'source' }) },+ sheetOrder: ['source'],+ styles: {},+ });+ protect(6, 1, canView, 'source', 'external-book');+ setCells({ 4: { 2: { f: `=[${qualifier}]source!$B$7` } } });+ const before = snapshot();+ expect(await fill()).toBe(canView);+ if (!canView) {+ expect(snapshot()).toEqual(before);+ }+ });++ it.each([+ { qualifier: 'Source.xlsx', permitted: false },+ { qualifier: 'Source', permitted: true },+ ])('preserves exact-name precedence and rejects ambiguous workbook resolution ($qualifier)', async ({ qualifier, permitted }) => {+ for (const [id, name] of [['external-book', 'Source.xlsx'], ['other-book', 'Source.xls']]) {+ testBed.univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, {+ id,+ name,+ locale: LocaleType.EN_US,+ appVersion: '1',+ sheets: { source: mergeWorksheetSnapshotWithDefault({ id: 'source', name: 'source' }) },+ sheetOrder: ['source'],+ styles: {},+ });+ }+ protect(6, 1, false, 'source', 'external-book');+ setCells({ 4: { 2: { f: `=[${qualifier}]source!$B$7` } } });+ expect(await fill()).toBe(permitted);+ });++ it('closes the previous fill menu when a new drag is rejected and allows a subsequent fill', async () => {+ protect(16, 1);+ const original = snapshot();+ expect(await fill()).toBe(true);+ const autoFillService = testBed.injector.get(IAutoFillService);+ const menuStates: boolean[] = [];+ const subscription = autoFillService.showMenu$.subscribe((show) => menuStates.push(show));+ const before = snapshot();+ const undoRedoService = testBed.injector.get(IUndoRedoService);+ const history = undoRedoService.getUndoRedoStatus('test');+ const selectionService = testBed.injector.get(SheetsSelectionsService);+ const selections = Tools.deepClone(selectionService.getCurrentSelections());+ const source = { startRow: 4, endRow: 14, startColumn: 2, endColumn: 2 };++ expect(await fill(AUTO_FILL_APPLY_TYPE.COPY, source, { ...source, endRow: 24 })).toBe(false);+ expect(menuStates[menuStates.length - 1]).toBe(false);+ expect(snapshot()).toEqual(before);+ expect(undoRedoService.getUndoRedoStatus('test')).toEqual(history);+ expect(selectionService.getCurrentSelections()).toEqual(selections);++ expect(await fill(AUTO_FILL_APPLY_TYPE.COPY, source, { ...source, endRow: 15 })).toBe(true);+ const after = snapshot();+ expect(menuStates[menuStates.length - 1]).toBe(true);+ subscription.unsubscribe();+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);+ expect(snapshot()).toEqual(before);+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);+ expect(snapshot()).toEqual(original);+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);+ expect(snapshot()).toEqual(before);+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);+ expect(snapshot()).toEqual(after);+ });++ it('checks nested names when entering a formula directly', async () => {+ testBed.injector.get(IDefinedNamesService).registerDefinedName('test', {+ id: 'private-cell',+ name: 'PrivateCell',+ formulaOrRefString: 'sheet1!$B$7',+ });+ protect(6, 1);+ const before = snapshot();+ expect(await commandService.executeCommand(SetRangeValuesCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ range: { startRow: 5, endRow: 5, startColumn: 2, endColumn: 2 },+ value: { f: '=SUM(PrivateCell)' },+ })).toBe(false);+ expect(snapshot()).toEqual(before);+ });++ it.each([+ { definition: 'sheet1!B1', row: 6, column: 3 },+ { definition: 'sheet1!$B1', row: 6, column: 1 },+ { definition: 'sheet1!B$1', row: 0, column: 3 },+ ])('resolves relative named references at each target cell ($definition)', async ({ definition, row, column }) => {+ testBed.injector.get(IDefinedNamesService).registerDefinedName('test', {+ id: 'relative-cell',+ name: 'RelativeCell',+ formulaOrRefString: definition,+ localSheetId: 'sheet1',+ });+ setCells({ 4: { 2: { f: '=RelativeCell' } } });+ protect(row, column);+ const before = snapshot();+ expect(await fill()).toBe(false);+ expect(snapshot()).toEqual(before);+ });++ it.each([false, true])('uses the sheet-local name before the workbook name (%s)', async (localIsHidden) => {+ const definedNames = testBed.injector.get(IDefinedNamesService);+ definedNames.registerDefinedName('test', {+ id: 'workbook-cell',+ name: 'ScopedCell',+ formulaOrRefString: localIsHidden ? 'sheet1!$B$5' : 'sheet1!$B$7',+ });+ definedNames.registerDefinedName('test', {+ id: 'local-cell',+ name: 'ScopedCell',+ localSheetId: 'sheet1',+ formulaOrRefString: localIsHidden ? 'sheet1!$B$7' : 'sheet1!$B$5',+ });+ setCells({ 4: { 2: { f: '=SUM(ScopedCell)' } } });+ protect(6, 1);+ expect(await fill()).toBe(!localIsHidden);+ });++ it.each([false, true])('terminates circular names while checking other references (%s)', async (hasHiddenReference) => {+ const definedNames = testBed.injector.get(IDefinedNamesService);+ definedNames.registerDefinedName('test', {+ id: 'circular-a',+ name: 'CircularA',+ formulaOrRefString: '=CircularB',+ });+ definedNames.registerDefinedName('test', {+ id: 'circular-b',+ name: 'CircularB',+ formulaOrRefString: '=CircularA',+ });+ setCells({ 4: { 2: { f: hasHiddenReference ? '=SUM(CircularA,$B$7)' : '=CircularA' } } });+ protect(6, 1);+ expect(await fill()).toBe(!hasHiddenReference);+ });++ it('checks the current name definition when refilling a cached formula', async () => {+ const definedNames = testBed.injector.get(IDefinedNamesService);+ const name = { id: 'changing-cell', name: 'ChangingCell', formulaOrRefString: 'sheet1!$B$5' };+ definedNames.registerDefinedName('test', name);+ setCells({ 4: { 2: { f: '=ChangingCell' } } });+ protect(6, 1);+ expect(await fill()).toBe(true);+ const before = snapshot();+ definedNames.registerDefinedName('test', { ...name, formulaOrRefString: 'sheet1!$B$7' });+ expect(await commandService.executeCommand(RefillCommand.id, { type: AUTO_FILL_APPLY_TYPE.COPY })).toBe(false);+ expect(snapshot()).toEqual(before);+ });++ it.each([true, false])('preserves source order after a rejected refill (vertical: %s)', async (vertical) => {+ const source: IRange = vertical+ ? { startRow: 6, endRow: 8, startColumn: 2, endColumn: 2 }+ : { startRow: 4, endRow: 4, startColumn: 6, endColumn: 8 };+ const target: IRange = vertical ? { ...source, startRow: 3 } : { ...source, startColumn: 3 };+ setCells(vertical+ ? {+ 6: { 2: { v: 'first', s: { bl: BooleanNumber.TRUE } } },+ 7: { 2: { v: 'second', s: { it: BooleanNumber.TRUE } } },+ 8: { 2: { f: '=B9' } },+ }+ : {+ 4: {+ 6: { v: 'first', s: { bl: BooleanNumber.TRUE } },+ 7: { v: 'second', s: { it: BooleanNumber.TRUE } },+ 8: { f: '=I4' },+ },+ });+ protect(vertical ? 5 : 3, vertical ? 1 : 5);+ const original = snapshot();+ expect(await fill(AUTO_FILL_APPLY_TYPE.ONLY_FORMAT, source, target)).toBe(true);+ const before = snapshot();+ expect(await commandService.executeCommand(RefillCommand.id, { type: AUTO_FILL_APPLY_TYPE.COPY })).toBe(false);+ expect(snapshot()).toEqual(before);+ expect(await commandService.executeCommand(RefillCommand.id, { type: AUTO_FILL_APPLY_TYPE.ONLY_FORMAT })).toBe(true);+ expect(snapshot()).toEqual(before);+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);+ expect(snapshot()).toEqual(original);+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);+ expect(snapshot()).toEqual(before);+ });++ it.each(['=$B$5', '=B$5'])('allows fixed references that remain viewable (%s)', async (formula) => {+ setCells({ 4: { 2: { f: formula } } });+ protect(6, 1);+ expect(await fill()).toBe(true);+ expect(messages).toEqual([]);+ });++ it('allows viewable read-only references and preserves undo/redo', async () => {+ protect(4, 1, true);+ protect(6, 1, true);+ const before = snapshot();+ expect(await fill()).toBe(true);+ const after = snapshot();+ expect(testBed.injector.get(FormulaDataModel).getFormulaStringByCell(6, 2, 'sheet1', 'test')).toBe('=B7');+ expect(messages).toEqual([]);+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);+ expect(snapshot()).toEqual(before);+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);+ expect(snapshot()).toEqual(after);+ });++ it('allows format-only filling and preserves it when a refill is rejected', async () => {+ protect(6, 1);+ expect(await fill(AUTO_FILL_APPLY_TYPE.ONLY_FORMAT)).toBe(true);+ const autoFillService = testBed.injector.get(IAutoFillService);+ const applyTypes: AUTO_FILL_APPLY_TYPE[] = [];+ const subscription = autoFillService.applyType$.subscribe((applyType) => applyTypes.push(applyType));+ const before = snapshot();+ const undoRedoService = testBed.injector.get(IUndoRedoService);+ const history = undoRedoService.getUndoRedoStatus('test');+ const selectionService = testBed.injector.get(SheetsSelectionsService);+ const selections = Tools.deepClone(selectionService.getCurrentSelections());++ const result = await commandService.executeCommand(RefillCommand.id, { type: AUTO_FILL_APPLY_TYPE.COPY });+ subscription.unsubscribe();+ expect(result).toBe(false);+ expect(snapshot()).toEqual(before);+ expect(undoRedoService.getUndoRedoStatus('test')).toEqual(history);+ expect(selectionService.getCurrentSelections()).toEqual(selections);+ expect(autoFillService.applyType).toBe(AUTO_FILL_APPLY_TYPE.ONLY_FORMAT);+ expect(applyTypes).toEqual([AUTO_FILL_APPLY_TYPE.ONLY_FORMAT]);+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);+ expect(workbook.getActiveSheet().getCellRaw(6, 2)?.v).toBe('existing target');+ });++ it('restores the original values when switching a valid fill to format-only', async () => {+ const before = snapshot();+ expect(await fill()).toBe(true);+ expect(await commandService.executeCommand(RefillCommand.id, { type: AUTO_FILL_APPLY_TYPE.ONLY_FORMAT })).toBe(true);+ expect(workbook.getActiveSheet().getCellRaw(6, 2)?.v).toBe('existing target');+ const after = snapshot();+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);+ expect(snapshot()).toEqual(before);+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);+ expect(snapshot()).toEqual(after);+ });+ });});diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.tsindex a07237396b..c8a377d9ce 100644--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts@@ -37,16 +37,20 @@ import {FormulaCurrentConfigService,FormulaDataModel,FormulaRuntimeService,+ FunctionService,HyperlinkEngineFormulaService,ICalculateFormulaService,IDefinedNamesService,IFormulaCurrentConfigService,IFormulaRuntimeService,+ IFunctionService,IHyperlinkEngineFormulaService,LexerTreeBuilder,} from '@univerjs/engine-formula';import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';import {+ AutoFillService,+ IAutoFillService,RangeProtectionRuleModel,SheetInterceptorService,SheetPermissionCheckController,@@ -583,6 +587,7 @@ export function clipboardTestBed(workbookData?: IWorkbookData, dependencies?: Deinjector.add([SheetsSelectionsService]);injector.add([WorksheetProtectionRuleModel]);injector.add([RangeProtectionRuleModel]);+ injector.add([IAutoFillService, { useClass: AutoFillService }]);injector.add([SheetPermissionCheckController]);injector.add(clipboardBoundary? [IClipboardInterfaceService, { useValue: clipboardBoundary }]@@ -609,6 +614,7 @@ export function clipboardTestBed(workbookData?: IWorkbookData, dependencies?: Deinjector.add([FormulaDataModel]);injector.add([LexerTreeBuilder]);injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);+ injector.add([IFunctionService, { useClass: FunctionService }]);injector.add([IHyperlinkEngineFormulaService, { useClass: HyperlinkEngineFormulaService }]);injector.add([IFormulaRuntimeService, { useClass: FormulaRuntimeService }]);injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);diff --git a/packages/sheets-ui/src/views/formula-bar/__tests__/FormulaBar.spec.tsx b/packages/sheets-ui/src/views/formula-bar/__tests__/FormulaBar.spec.tsxindex 8e61f8db48..4c88d69de1 100644--- a/packages/sheets-ui/src/views/formula-bar/__tests__/FormulaBar.spec.tsx+++ b/packages/sheets-ui/src/views/formula-bar/__tests__/FormulaBar.spec.tsx@@ -17,12 +17,6 @@import type { IDocumentData, IStyleData, IWorkbookData, Nullable, Workbook } from '@univerjs/core';import type { ReactElement } from 'react';import type { Root } from 'react-dom/client';-import type {- ICellEditorLayout,- ICellEditorState,- IEditorBridgeServiceParam,- IEditorBridgeServiceVisibleParam,-} from '../../../services/editor-bridge.service';import {CommandType,DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,@@ -39,6 +33,7 @@ import { DocSelectionManagerService } from '@univerjs/docs';import { EditorService, IEditorService } from '@univerjs/docs-ui';import {DefinedNamesService,+ FormulaDataModel,FunctionService,IDefinedNamesService,IFunctionService,@@ -48,6 +43,8 @@ import {} from '@univerjs/engine-formula';import { DeviceInputEventType, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';import {+ AutoFillService,+ IAutoFillService,RangeProtectionCache,RangeProtectionRuleModel,SheetInterceptorService,@@ -71,6 +68,12 @@ import { act } from 'react';import { createRoot } from 'react-dom/client';import { BehaviorSubject, EMPTY } from 'rxjs';import { afterEach, describe, expect, it, vi } from 'vitest';+import type {+ ICellEditorLayout,+ ICellEditorState,+ IEditorBridgeServiceParam,+ IEditorBridgeServiceVisibleParam,+} from '../../../services/editor-bridge.service';import { SetCellEditVisibleOperation } from '../../../commands/operations/cell-edit.operation';import { EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY } from '../../../common/keys';import { SHEETS_UI_PLUGIN_CONFIG_KEY } from '../../../config/config';@@ -283,6 +286,7 @@ function createFormulaBarTestBed(cellStyle?: IStyleData, realEditorServices = fainjector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);injector.add([ISuperTableService, { useClass: SuperTableService }]);injector.add([IFunctionService, { useClass: FunctionService }]);+ injector.add([FormulaDataModel]);injector.add([LexerTreeBuilder, { useClass: LexerTreeBuilder }]);injector.add([ComponentManager, { useClass: ComponentManager }]);injector.add([IUIPartsService, { useClass: UIPartsService }]);@@ -290,6 +294,7 @@ function createFormulaBarTestBed(cellStyle?: IStyleData, realEditorServices = fainjector.add([WorksheetProtectionRuleModel, { useClass: WorksheetProtectionRuleModel }]);injector.add([RangeProtectionRuleModel, { useClass: RangeProtectionRuleModel }]);injector.add([RangeProtectionCache, { useClass: RangeProtectionCache }]);+ injector.add([IAutoFillService, { useClass: AutoFillService }]);injector.add([SheetPermissionCheckController, { useClass: SheetPermissionCheckController }]);injector.add([IFormulaEditorManagerService, { useClass: FormulaEditorManagerService }]);if (realEditorServices) {diff --git a/packages/sheets/src/controllers/auto-fill.controller.ts b/packages/sheets/src/controllers/auto-fill.controller.tsindex 15f11128f5..64b14d5bc6 100644--- a/packages/sheets/src/controllers/auto-fill.controller.ts+++ b/packages/sheets/src/controllers/auto-fill.controller.ts@@ -14,7 +14,18 @@* limitations under the License.*/-import type { ICellData, IMutationInfo, IRange, Nullable, Workbook } from '@univerjs/core';+import type { ICellData, IMutationInfo, IObjectMatrixPrimitiveType, IRange, Nullable, Workbook } from '@univerjs/core';+import {+ Direction,+ Disposable,+ Inject,+ Injector,+ IUniverInstanceService,+ ObjectMatrix,+ Rectangle,+ Tools,+ UniverInstanceType,+} from '@univerjs/core';import type {IAddWorksheetMergeMutationParams,IRemoveWorksheetMergeMutationParams,@@ -27,17 +38,6 @@ import type {IAutoFillLocation,IAutoFillRuleConfirmedData,} from '../services/auto-fill/type';-import {- Direction,- Disposable,- Inject,- Injector,- IUniverInstanceService,- ObjectMatrix,- Rectangle,- Tools,- UniverInstanceType,-} from '@univerjs/core';import { discreteRangeToRange } from '../basics/utils';import {AddMergeUndoMutationFactory,@@ -60,6 +60,12 @@ import { getAddMergeMutationRangeByType } from './merge-cell.controller';const { getLenS, getDataIndex, fillCopy, fillCopyStyles, generateNullCellValueRowCol } = AutoFillTools;const { otherRule } = AutoFillRules;+interface IPreparedFillData {+ cellValue: IObjectMatrixPrimitiveType<ICellData>;+ applyMergeRanges: IRange[];+ hasStyle: boolean;+}+export class AutoFillController extends Disposable {private _beforeApplyData: Array<Array<Nullable<ICellData>>> = [];private _copyData: IAutoFillCopyDataPiece[] = [];@@ -91,8 +97,9 @@ export class AutoFillController extends Disposable {onBeforeFillData: (location: IAutoFillLocation, direction: Direction) => {return this._presetAndCacheData(location, direction);},- onFillData: (location: IAutoFillLocation, direction: Direction, applyType: AUTO_FILL_APPLY_TYPE) => {- return this._fillData(location, direction, applyType);+ onPrepareFillData: (location: IAutoFillLocation, direction: Direction, applyType: AUTO_FILL_APPLY_TYPE) => {+ const prepared = this._prepareFillData(location, direction, applyType);+ return () => this._fillData(location, direction, applyType, prepared);},}));}@@ -147,7 +154,7 @@ export class AutoFillController extends Disposable {return [];}- const applyDataInTypes: { [key: string]: any[] } = {};+ const applyDataInTypes: Record<string, Array<{ data: Array<Nullable<ICellData>>; index: number[] }>> = {};rules.forEach((r) => {applyDataInTypes[r.type] = [];@@ -178,7 +185,7 @@ export class AutoFillController extends Disposable {);const arrIndex = getDataIndex(csLen, asLen, copySquad.index);- applyDataInTypes[type].push({ data: arrData, index: arrIndex });+ applyDataInTypes[type].push({ data: arrData ?? [], index: arrIndex });});});@@ -388,42 +395,15 @@ export class AutoFillController extends Disposable {return applyMergeRanges;}- // auto fill entry- // eslint-disable-next-line max-lines-per-function, complexity- private _fillData(location: IAutoFillLocation, direction: Direction, applyType: AUTO_FILL_APPLY_TYPE) {- const undos: IMutationInfo[] = [];- const redos: IMutationInfo[] = [];-- let hasStyle = true;- if (applyType === AUTO_FILL_APPLY_TYPE.NO_FORMAT) {- hasStyle = false;- applyType = AUTO_FILL_APPLY_TYPE.SERIES;- }-- const { source, target, unitId, subUnitId } = location;-- if (!source || !target || direction == null) {- return {- undos,- redos,- };- }-- const sourceRange = discreteRangeToRange(source);- const targetRange = discreteRangeToRange(target);-- const { cols: targetCols, rows: targetRows } = target;- const { cols: sourceCols, rows: sourceRows } = source;-- const copyData = this._copyData;-- let csLen;- if (direction === Direction.DOWN || direction === Direction.UP) {- csLen = sourceRows.length;- } else {- csLen = sourceCols.length;- }-+ private _getFillCells(+ location: IAutoFillLocation,+ direction: Direction,+ applyType: AUTO_FILL_APPLY_TYPE,+ hasStyle: boolean,+ csLen: number+ ) {+ const { rows: targetRows, cols: targetCols } = location.target;+ const copyData = Tools.deepClone(this._copyData);const applyDatas: Array<Array<Nullable<ICellData>>> = [];if (direction === Direction.DOWN || direction === Direction.UP) {@@ -461,30 +441,47 @@ export class AutoFillController extends Disposable {});}- // deal with styles- let applyMergeRanges: IRange[] = [];- const style = this._univerInstanceService.getUnit<Workbook>(unitId)?.getStyles();- if (hasStyle) {- applyMergeRanges = this._getMergeApplyData(sourceRange, targetRange, direction, csLen, location);- applyDatas.forEach((row) => {- row.forEach((cellData) => {- if (cellData && style) {- if (style) {- cellData.s = style.getStyleByCell(cellData);- }- }- });- });+ return applyDatas;+ }++ private _prepareFillData(+ location: IAutoFillLocation,+ direction: Direction,+ applyType: AUTO_FILL_APPLY_TYPE+ ): IPreparedFillData {+ const hasStyle = applyType !== AUTO_FILL_APPLY_TYPE.NO_FORMAT;+ const effectiveApplyType = hasStyle ? applyType : AUTO_FILL_APPLY_TYPE.SERIES;+ const { source, target, unitId } = location;++ const sourceRange = discreteRangeToRange(source);+ const targetRange = discreteRangeToRange(target);++ const { cols: targetCols, rows: targetRows } = target;+ const { cols: sourceCols, rows: sourceRows } = source;++ let csLen;+ if (direction === Direction.DOWN || direction === Direction.UP) {+ csLen = sourceRows.length;} else {- applyDatas.forEach((row, rowIndex) => {- row.forEach((cellData, colIndex) => {- if (cellData && style) {- cellData.s = style.getStyleByCell(this._beforeApplyData[rowIndex][colIndex]) || null;- }- });- });+ csLen = sourceCols.length;}+ const applyDatas = this._getFillCells(location, direction, effectiveApplyType, hasStyle, csLen);++ const applyMergeRanges = hasStyle+ ? this._getMergeApplyData(sourceRange, targetRange, direction, csLen, location)+ : [];+ const style = this._univerInstanceService.getUnit<Workbook>(unitId)?.getStyles();+ applyDatas.forEach((row, rowIndex) => {+ row.forEach((cellData, colIndex) => {+ if (cellData && style) {+ cellData.s = hasStyle+ ? style.getStyleByCell(cellData)+ : style.getStyleByCell(this._beforeApplyData[rowIndex][colIndex]) || null;+ }+ });+ });+if (applyType === AUTO_FILL_APPLY_TYPE.ONLY_FORMAT) {applyDatas.forEach((row, rowIndex) => {row.forEach((cellData, colIndex) => {@@ -501,38 +498,64 @@ export class AutoFillController extends Disposable {});}- // delete cross merge- if (hasStyle) {- const deleteMergeRanges: IRange[] = [];- const mergeData = this._univerInstanceService- .getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET)- ?.getSheetBySheetId(subUnitId)- ?.getMergeData();-- if (mergeData) {- mergeData.forEach((merge) => {- if (Rectangle.intersects(merge, targetRange)) {- deleteMergeRanges.push(merge);- }- });- }+ const cellValue = new ObjectMatrix<ICellData>();+ targetRows.forEach((row, rowIndex) => {+ targetCols.forEach((col, colIndex) => {+ const cell = applyDatas[rowIndex][colIndex];+ if (cell) {+ cellValue.setValue(row, col, cell);+ }+ });+ });- if (deleteMergeRanges.length) {- const removeMergeMutationParams: IRemoveWorksheetMergeMutationParams = {- unitId,- subUnitId,- ranges: deleteMergeRanges,- };+ const cellValueMatrix = cellValue.getMatrix();+ this._autoFillService.getActiveHooks(applyType).forEach((hook) => {+ hook.onValidateFillData?.(location, direction, applyType, cellValueMatrix);+ });- const undoRemoveMergeMutationParams: IAddWorksheetMergeMutationParams = this._injector.invoke(- RemoveMergeUndoMutationFactory,- removeMergeMutationParams- );+ return { cellValue: cellValueMatrix, applyMergeRanges, hasStyle };+ }- redos.push({ id: RemoveWorksheetMergeMutation.id, params: removeMergeMutationParams });- undos.unshift({ id: AddWorksheetMergeMutation.id, params: undoRemoveMergeMutationParams });- }+ private _getRemoveMergeMutations(location: IAutoFillLocation) {+ const { unitId, subUnitId, target } = location;+ const targetRange = discreteRangeToRange(target);+ const undos: IMutationInfo[] = [];+ const redos: IMutationInfo[] = [];+ const deleteMergeRanges = this._univerInstanceService+ .getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET)+ ?.getSheetBySheetId(subUnitId)+ ?.getMergeData()+ .filter((merge) => Rectangle.intersects(merge, targetRange)) ?? [];++ if (deleteMergeRanges.length) {+ const removeMergeMutationParams: IRemoveWorksheetMergeMutationParams = {+ unitId,+ subUnitId,+ ranges: deleteMergeRanges,+ };++ const undoRemoveMergeMutationParams: IAddWorksheetMergeMutationParams = this._injector.invoke(+ RemoveMergeUndoMutationFactory,+ removeMergeMutationParams+ );++ redos.push({ id: RemoveWorksheetMergeMutation.id, params: removeMergeMutationParams });+ undos.unshift({ id: AddWorksheetMergeMutation.id, params: undoRemoveMergeMutationParams });}+ return { undos, redos };+ }++ private _fillData(+ location: IAutoFillLocation,+ direction: Direction,+ applyType: AUTO_FILL_APPLY_TYPE,+ prepared: IPreparedFillData+ ) {+ const { target, unitId, subUnitId } = location;+ const { cellValue, applyMergeRanges, hasStyle } = prepared;+ const { undos, redos } = hasStyle+ ? this._getRemoveMergeMutations(location)+ : { undos: [], redos: [] };// clear range valueconst clearMutationParams: ISetRangeValuesMutationParams = {@@ -546,24 +569,12 @@ export class AutoFillController extends Disposable {clearMutationParams);- // const intercepted = this._sheetInterceptorService.onCommandExecute({ id: ClearSelectionContentCommand.id });redos.push({ id: SetRangeValuesMutation.id, params: clearMutationParams });undos.unshift({ id: SetRangeValuesMutation.id, params: undoClearMutationParams });- // set range value- const cellValue = new ObjectMatrix<ICellData>();- targetRows.forEach((row, rowIndex) => {- targetCols.forEach((col, colIndex) => {- if (applyDatas[rowIndex][colIndex]) {- cellValue.setValue(row, col, applyDatas[rowIndex][colIndex]!);- }- });- });-- const cellValueMatrix = cellValue.getMatrix();const setRangeValuesMutationParams: ISetRangeValuesMutationParams = {subUnitId,unitId,- cellValue: cellValueMatrix,+ cellValue,};const undoSetRangeValuesMutationParams: ISetRangeValuesMutationParams = this._injector.invoke(@@ -571,8 +582,8 @@ export class AutoFillController extends Disposable {setRangeValuesMutationParams);- this._autoFillService.getActiveHooks().forEach((hook) => {- hook.onBeforeSubmit?.(location, direction, applyType, cellValueMatrix);+ this._autoFillService.getActiveHooks(applyType).forEach((hook) => {+ hook.onBeforeSubmit?.(location, direction, applyType, cellValue);});undos.unshift({ id: SetRangeValuesMutation.id, params: undoSetRangeValuesMutationParams });diff --git a/packages/sheets/src/controllers/permission/sheet-permission-check.controller.ts b/packages/sheets/src/controllers/permission/sheet-permission-check.controller.tsindex c8996ab9fc..9f404686e2 100644--- a/packages/sheets/src/controllers/permission/sheet-permission-check.controller.ts+++ b/packages/sheets/src/controllers/permission/sheet-permission-check.controller.ts@@ -26,6 +26,39 @@ import type {WorkbookPermissionPointConstructor,} from '@univerjs/core';import type { ISetDefinedNameMutationParam } from '@univerjs/engine-formula';+import type { UnitAction } from '@univerjs/protocol';+import {+ CustomCommandExecutionError,+ Direction,+ Disposable,+ DisposableCollection,+ ICommandService,+ Inject,+ IPermissionService,+ isICellData,+ IUniverInstanceService,+ LocaleService,+ MAX_COLUMN_COUNT,+ MAX_ROW_COUNT,+ moveRangeByOffset,+ ObjectMatrix,+ Rectangle,+ Tools,+ UniverInstanceType,+} from '@univerjs/core';+import {+ deserializeRangeWithSheetWithCache,+ FormulaDataModel,+ handleRefStringInfo,+ IDefinedNamesService,+ IFunctionService,+ LexerTreeBuilder,+ matchToken,+ normalizeFormulaUnitName,+ operatorToken,+ sequenceNodeType,+} from '@univerjs/engine-formula';+import { Subject } from 'rxjs';import type { IAutoFillCommandParams } from '../../commands/commands/auto-fill.command';import type { IClearSelectionAllCommandParams } from '../../commands/commands/clear-selection-all.command';import type { IClearSelectionContentCommandParams } from '../../commands/commands/clear-selection-content.command';@@ -56,32 +89,6 @@ import type {import type { ISetWorksheetShowCommandParams } from '../../commands/commands/set-worksheet-show.command';import type { ITextToNumberCommandParams } from '../../commands/commands/text-to-number.command';import type { LocaleKey } from '../../locale/types';-import {- CustomCommandExecutionError,- Direction,- Disposable,- DisposableCollection,- ICommandService,- Inject,- IPermissionService,- isICellData,- IUniverInstanceService,- LocaleService,- ObjectMatrix,- Rectangle,- Tools,- UniverInstanceType,-} from '@univerjs/core';-import {- deserializeRangeWithSheet,- deserializeRangeWithSheetWithCache,- IDefinedNamesService,- LexerTreeBuilder,- operatorToken,- sequenceNodeType,-} from '@univerjs/engine-formula';-import { UnitAction } from '@univerjs/protocol';-import { Subject } from 'rxjs';import { AutoFillCommand } from '../../commands/commands/auto-fill.command';import { ClearSelectionAllCommand } from '../../commands/commands/clear-selection-all.command';import { ClearSelectionContentCommand } from '../../commands/commands/clear-selection-content.command';@@ -121,29 +128,34 @@ import { TextToNumberCommand } from '../../commands/commands/text-to-number.commimport { getSheetCommandTarget } from '../../commands/commands/utils/target-util';import { SetWorksheetNameMutation } from '../../commands/mutations/set-worksheet-name.mutation';import { RangeProtectionRuleModel } from '../../models/range-protection-rule.model';+import { IAutoFillService } from '../../services/auto-fill/auto-fill.service';+import { AUTO_FILL_APPLY_TYPE } from '../../services/auto-fill/type';+import { RangeProtectionPermissionEditPoint } from '../../services/permission/permission-point/range/edit';+import { RangeProtectionPermissionViewPoint } from '../../services/permission/permission-point/range/view';+import { WorkbookDeleteColumnPermission } from '../../services/permission/permission-point/workbook/delete-column';+import { WorkbookDeleteRowPermission } from '../../services/permission/permission-point/workbook/delete-row';+import { WorkbookEditablePermission } from '../../services/permission/permission-point/workbook/editable';+import { WorkbookHideSheetPermission } from '../../services/permission/permission-point/workbook/hide-sheet';+import { WorkbookInsertColumnPermission } from '../../services/permission/permission-point/workbook/insert-column';+import { WorkbookInsertRowPermission } from '../../services/permission/permission-point/workbook/insert-row';+import { WorkbookMoveSheetPermission } from '../../services/permission/permission-point/workbook/move-sheet';+import { WorkbookRenameSheetPermission } from '../../services/permission/permission-point/workbook/rename-sheet';+import { WorksheetDeleteColumnPermission } from '../../services/permission/permission-point/worksheet/delete-column';+import { WorksheetDeleteRowPermission } from '../../services/permission/permission-point/worksheet/delete-row';+import { WorksheetEditPermission } from '../../services/permission/permission-point/worksheet/edit';+import { WorksheetInsertColumnPermission } from '../../services/permission/permission-point/worksheet/insert-column';+import { WorksheetInsertRowPermission } from '../../services/permission/permission-point/worksheet/insert-row';+import { WorksheetSetCellStylePermission } from '../../services/permission/permission-point/worksheet/set-cell-style';+import { WorksheetSetCellValuePermission } from '../../services/permission/permission-point/worksheet/set-cell-value';import {- RangeProtectionPermissionEditPoint,- WorkbookDeleteColumnPermission,- WorkbookDeleteRowPermission,- WorkbookEditablePermission,- WorkbookHideSheetPermission,- WorkbookInsertColumnPermission,- WorkbookInsertRowPermission,- WorkbookMoveSheetPermission,- WorkbookRenameSheetPermission,- WorksheetDeleteColumnPermission,- WorksheetDeleteRowPermission,- WorksheetEditPermission,- WorksheetInsertColumnPermission,- WorksheetInsertRowPermission,- WorksheetSetCellStylePermission,- WorksheetSetCellValuePermission,WorksheetSetColumnStylePermission,- WorksheetSetRowStylePermission,- WorksheetViewPermission,-} from '../../services/permission/permission-point';-import { WorksheetProtectionRuleModel } from '../../services/permission/worksheet-permission';-import { SheetsSelectionsService } from '../../services/selections';+} from '../../services/permission/permission-point/worksheet/set-column-style';+import { WorksheetSetRowStylePermission } from '../../services/permission/permission-point/worksheet/set-row-style';+import { WorksheetViewPermission } from '../../services/permission/permission-point/worksheet/view';+import {+ WorksheetProtectionRuleModel,+} from '../../services/permission/worksheet-permission/worksheet-permission-rule.model';+import { SheetsSelectionsService } from '../../services/selections/selection.service';import { SCOPE_WORKBOOK_VALUE_DEFINED_NAME } from '../defined-name-data.controller';/* eslint-disable complexity */@@ -151,6 +163,13 @@ import { SCOPE_WORKBOOK_VALUE_DEFINED_NAME } from '../defined-name-data.controlltype ICellPermission = Record<UnitAction, boolean> & { ruleId?: string; ranges?: IRange[] };+interface IFormulaPermissionContext {+ unitId: string;+ subUnitId: string;+ row: number;+ column: number;+}+export class SheetPermissionCheckController extends Disposable {disposableCollection = new DisposableCollection();@@ -166,7 +185,10 @@ export class SheetPermissionCheckController extends Disposable {@Inject(WorksheetProtectionRuleModel) private _worksheetProtectionRuleModel: WorksheetProtectionRuleModel,@Inject(LocaleService) private readonly _localeService: LocaleService,@Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder,- @IDefinedNamesService private readonly _definedNamesService: IDefinedNamesService+ @IDefinedNamesService private readonly _definedNamesService: IDefinedNamesService,+ @IAutoFillService private readonly _autoFillService: IAutoFillService,+ @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel,+ @IFunctionService private readonly _functionService: IFunctionService) {super();this._initialize();@@ -174,6 +196,37 @@ export class SheetPermissionCheckController extends Disposable {private _initialize(): void {this._commandExecutedListener();+ this.disposeWithMe(this._autoFillService.addHook({+ id: 'permission-check',+ onValidateFillData: ({ unitId, subUnitId }, _direction, applyType, cellValue) => {+ if (applyType === AUTO_FILL_APPLY_TYPE.ONLY_FORMAT) {+ return;+ }++ // Resolve shared followers from the proposed data without updating the formula model.+ const formulas = new ObjectMatrix(this._formulaDataModel.updateFormulaData(unitId, subUnitId, cellValue));+ new ObjectMatrix(cellValue).forValue((row, column) => {+ const formula = formulas.getValue(row, column);+ if (!formula?.f) {+ return;+ }++ const formulaString = this._lexerTreeBuilder.moveFormulaRefOffset(+ formula.f,+ formula.x ?? 0,+ formula.y ?? 0+ );+ if (!this._permissionCheckWithFormula({+ unitId,+ subUnitId,+ range: { startRow: row, endRow: row, startColumn: column, endColumn: column },+ value: { f: formulaString },+ })) {+ this.blockExecuteWithoutPermission(this._localeService.t<LocaleKey>('sheets.permission.dialog.formulaErr'));+ }+ });+ },+ }));}private _commandExecutedListener() {@@ -706,106 +759,166 @@ export class SheetPermissionCheckController extends Disposable {const target = getSheetCommandTarget(this._univerInstanceService, params);if (!target) return false;- const { workbook, unitId, subUnitId } = target;+ const { unitId, subUnitId } = target;const formulaString = (params.value as ICellData).f;if (formulaString) {- const definedNameStr = formulaString.substring(1);- const definedName = this._definedNamesService.getValueByName(unitId, definedNameStr);-- if (definedName) {- let formulaOrRefString = definedName.formulaOrRefString;- if (formulaOrRefString.startsWith(operatorToken.EQUALS)) {- formulaOrRefString = formulaOrRefString.slice(1);+ const ranges = params.range+ ? [params.range]+ : this._selectionManagerService.getCurrentSelections()?.map((selection) => selection.range) ?? [];+ for (const range of ranges) {+ for (let row = range.startRow; row <= range.endRow; row++) {+ for (let column = range.startColumn; column <= range.endColumn; column++) {+ if (!this._permissionCheckFormulaReferences(formulaString, { unitId, subUnitId, row, column })) {+ return false;+ }+ }}+ }- const refRangesArr = formulaOrRefString.split(',');-- for (let i = 0; i < refRangesArr.length; i++) {- const refRange = refRangesArr[i];- const { sheetName, range } = deserializeRangeWithSheet(refRange);+ return true;+ }- if (sheetName) {- const targetSheet = workbook.getSheetBySheetName(sheetName);- if (!targetSheet) {- // Formula errors need to be handled by the formula system, and permissions will not be blocked- return true;- }+ const { range } = params;+ if (range) {+ const rules = this._rangeProtectionRuleModel.getSubunitRuleList(unitId, subUnitId);+ if (rules.length === 0) return true;- const { startRow, endRow, startColumn, endColumn } = range;+ const permissionIds = rules+ .filter((rule) =>+ rule.ranges.some((ruleRange) => Rectangle.intersects(ruleRange, range))+ )+ .map((rule) => new RangeProtectionPermissionEditPoint(unitId, subUnitId, rule.permissionId).id);- for (let r = startRow; r <= endRow; r++) {- for (let c = startColumn; c <= endColumn; c++) {- const cell = targetSheet.getCell(r, c) as Nullable<ICellDataForSheetInterceptor & { selectionProtection: ICellPermission[] }>;- const permission = cell?.selectionProtection?.[0];- if (permission?.[UnitAction.View] === false) {- return false;- }- }- }- }- }+ return this._permissionService.composePermission(permissionIds).every((permission) => permission.value);+ }- return true;- } else {- const sequenceNodes = this._lexerTreeBuilder.sequenceNodesBuilder(formulaString);- if (!sequenceNodes) {- return true;- }+ return true;+ }- for (let i = 0; i < sequenceNodes.length; i++) {- const node = sequenceNodes[i];- if (typeof node === 'string' || node.nodeType !== sequenceNodeType.REFERENCE) {- continue;- }+ private _getFormulaReferenceWorkbook(unitId: string, qualifier: string): Nullable<Workbook> {+ const workbook = this._univerInstanceService.getUnit<Workbook>(+ qualifier || unitId,+ UniverInstanceType.UNIVER_SHEET+ );+ if (workbook || !qualifier) {+ return workbook;+ }- const { token } = node;- const { unitId: sequenceGridUnitId, sheetName, range } = deserializeRangeWithSheetWithCache(token);+ // Match calculation's name resolution against live workbooks without relying on worker-only services.+ const workbooks = this._univerInstanceService.getAllUnitsForType<Workbook>(UniverInstanceType.UNIVER_SHEET)+ .filter((item) => item.getSnapshot().name.length > 0);+ const exactMatches = workbooks.filter((item) => item.getSnapshot().name.toLowerCase() === qualifier.toLowerCase());+ const matches = exactMatches.length > 0+ ? exactMatches+ : workbooks.filter((item) => normalizeFormulaUnitName(item.getSnapshot().name) === normalizeFormulaUnitName(qualifier));+ return matches.length === 1 ? matches[0] : null;+ }- let sequenceGridWorkbook = workbook;- if (sequenceGridUnitId && sequenceGridUnitId !== unitId) {- const _sequenceGridWorkbook = this._univerInstanceService.getUnit<Workbook>(sequenceGridUnitId, UniverInstanceType.UNIVER_SHEET);- if (!_sequenceGridWorkbook) return true;- sequenceGridWorkbook = _sequenceGridWorkbook;- }+ private _permissionCheckFormulaReferences(+ formulaString: string,+ context: IFormulaPermissionContext,+ visitingNames = new Set<string>(),+ referenceOffset?: { x: number; y: number }+ ): boolean {+ const { unitId, subUnitId, row, column } = context;+ const sequenceNodes = this._lexerTreeBuilder.sequenceNodesBuilder(formulaString) ?? [];+ for (let index = 0; index < sequenceNodes.length; index++) {+ const node = sequenceNodes[index];+ if (typeof node === 'string'+ || (node.nodeType !== sequenceNodeType.REFERENCE && node.nodeType !== sequenceNodeType.FUNCTION)) {+ continue;+ }- const sequenceGridWorksheet = sheetName ? sequenceGridWorkbook.getSheetBySheetName(sheetName) : sequenceGridWorkbook.getActiveSheet();- if (!sequenceGridWorksheet) return true;+ const nextNode = sequenceNodes[index + 1];+ if (node.nodeType === sequenceNodeType.FUNCTION+ && typeof nextNode === 'string' && nextNode.trim() === matchToken.OPEN_BRACKET+ && this._functionService.hasExecutor(node.token.trim().toUpperCase())) {+ continue;+ }- if (sheetName) {- const viewPermission = this._permissionService.getPermissionPoint(new WorksheetViewPermission(sequenceGridWorkbook.getUnitId(), sequenceGridWorksheet.getSheetId()).id);- if (!viewPermission || viewPermission.value === false) return false;+ let nameToken = node.token.trim();+ if (node.nodeType === sequenceNodeType.FUNCTION) {+ const parts = nameToken.split('!');+ if (parts.length === 2) {+ const unqualifiedName = parts[1].trim();+ const unscopedName = this._definedNamesService.getValueByName(unitId, unqualifiedName);+ const localSheetId = unscopedName?.localSheetId;+ const localSheet = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET)+ ?.getSheetBySheetId(localSheetId ?? '');+ // The engine strips any prefix for global names, but requires a matching prefix for local names.+ if (unscopedName && (localSheetId == null+ || localSheetId === SCOPE_WORKBOOK_VALUE_DEFINED_NAME+ || localSheet?.getName() === parts[0])) {+ nameToken = unqualifiedName;}+ }+ }+ // Expanded names retain the formula's evaluation context.+ const definedName = this._definedNamesService.getValueByName(unitId, nameToken, subUnitId);+ if (definedName) {+ const nameKey = `${unitId}:${definedName.id}`;+ if (visitingNames.has(nameKey)) {+ continue;+ }- const { startRow, endRow, startColumn, endColumn } = range;-- for (let r = startRow; r <= endRow; r++) {- for (let c = startColumn; c <= endColumn; c++) {- const cell = sequenceGridWorksheet.getCell(r, c) as Nullable<ICellDataForSheetInterceptor & { selectionProtection: ICellPermission[] }>;- const permission = cell?.selectionProtection?.[0];- if (permission?.[UnitAction.View] === false) {- return false;- }- }- }+ visitingNames.add(nameKey);+ const definition = definedName.formulaOrRefString;+ const isFormula = definition.startsWith(operatorToken.EQUALS);+ const offset = isFormula+ ? undefined+ : {+ x: column - (definedName.localSheetId === SCOPE_WORKBOOK_VALUE_DEFINED_NAME ? 1 : 0),+ y: row,+ };+ const permitted = this._permissionCheckFormulaReferences(+ isFormula ? definition : `${operatorToken.EQUALS}${definition}`,+ context,+ visitingNames,+ offset+ );+ visitingNames.delete(nameKey);+ if (!permitted) {+ return false;}+ continue;+ }- return true;+ if (node.nodeType !== sequenceNodeType.REFERENCE) {+ continue;}- }- const { range } = params;- if (range) {- const rules = this._rangeProtectionRuleModel.getSubunitRuleList(unitId, subUnitId);- if (rules.length === 0) return true;+ const { unitQualifier, sheetName } = handleRefStringInfo(node.token.trim());+ const referenceWorkbook = this._getFormulaReferenceWorkbook(unitId, unitQualifier);+ const referenceWorksheet = sheetName+ ? referenceWorkbook?.getSheetBySheetName(sheetName)+ : referenceWorkbook?.getSheetBySheetId(subUnitId);+ if (!referenceWorkbook || !referenceWorksheet) {+ // Invalid references are handled by the formula engine.+ continue;+ }- const permissionIds = rules- .filter((rule) =>- rule.ranges.some((ruleRange) => Rectangle.intersects(ruleRange, range))- )- .map((rule) => new RangeProtectionPermissionEditPoint(unitId, subUnitId, rule.permissionId).id);+ const referenceUnitId = referenceWorkbook.getUnitId();+ const referenceSheetId = referenceWorksheet.getSheetId();+ const { range } = deserializeRangeWithSheetWithCache(node.token);+ const referenceRange = referenceOffset+ ? moveRangeByOffset({ ...range }, referenceOffset.x, referenceOffset.y)+ : range;+ if (referenceOffset) {+ // Relative names wrap at the sheet limits, matching formula-engine name resolution.+ const wrap = (value: number, limit: number) => ((value % limit) + limit) % limit;+ referenceRange.startRow = wrap(referenceRange.startRow, MAX_ROW_COUNT);+ referenceRange.endRow = wrap(referenceRange.endRow, MAX_ROW_COUNT);+ referenceRange.startColumn = wrap(referenceRange.startColumn, MAX_COLUMN_COUNT);+ referenceRange.endColumn = wrap(referenceRange.endColumn, MAX_COLUMN_COUNT);+ }- return this._permissionService.composePermission(permissionIds).every((permission) => permission.value);+ if (!this.permissionCheckWithRanges({+ worksheetTypes: [WorksheetViewPermission],+ rangeTypes: [RangeProtectionPermissionViewPoint],+ }, [referenceRange], referenceUnitId, referenceSheetId)) {+ return false;+ }}return true;diff --git a/packages/sheets/src/services/auto-fill/__tests__/auto-fill.service.spec.ts b/packages/sheets/src/services/auto-fill/__tests__/auto-fill.service.spec.tsindex 47e2de11af..71da6dd89c 100644--- a/packages/sheets/src/services/auto-fill/__tests__/auto-fill.service.spec.ts+++ b/packages/sheets/src/services/auto-fill/__tests__/auto-fill.service.spec.ts@@ -15,11 +15,11 @@*/import type { Injector, IRange, Univer, Workbook } from '@univerjs/core';-import type { IAutoFillRule } from '../type';import { Direction, ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { SetSelectionsOperation } from '../../../commands/operations/selection.operation';+import type { IAutoFillRule } from '../type';import { createTestBase, TEST_WORKBOOK_DATA_DEMO } from '../../__tests__/util';+import { SetSelectionsOperation } from '../../../commands/operations/selection.operation';import { SheetsSelectionsService } from '../../selections/selection.service';import { AutoFillService } from '../auto-fill.service';import { AUTO_FILL_APPLY_TYPE, AUTO_FILL_DATA_TYPE, AUTO_FILL_HOOK_TYPE } from '../type';@@ -140,6 +140,34 @@ describe('AutoFillService', () => {expect(service.fillData(AUTO_FILL_APPLY_TYPE.COPY)).toBe(false);});+ it('should select hooks using the requested type and commit it only after preparation', () => {+ service.autoFillLocation = {+ unitId,+ subUnitId,+ source: { rows: [0], cols: [0] },+ target: { rows: [1], cols: [0] },+ };+ service.applyType = AUTO_FILL_APPLY_TYPE.ONLY_FORMAT;+ const observedTypes: AUTO_FILL_APPLY_TYPE[] = [];+ service.addHook({+ id: 'copy-only',+ disable: (_location, _direction, applyType) => applyType !== AUTO_FILL_APPLY_TYPE.COPY,+ onPrepareFillData: (_location, _direction, applyType) => {+ expect(applyType).toBe(AUTO_FILL_APPLY_TYPE.COPY);+ observedTypes.push(service.applyType);+ return () => {+ observedTypes.push(service.applyType);+ return { undos: [], redos: [] };+ };+ },+ });++ expect(service.getActiveHooks()).toEqual([]);+ expect(service.fillData(AUTO_FILL_APPLY_TYPE.COPY)).toBe(true);+ expect(observedTypes).toEqual([AUTO_FILL_APPLY_TYPE.ONLY_FORMAT, AUTO_FILL_APPLY_TYPE.COPY]);+ expect(service.applyType).toBe(AUTO_FILL_APPLY_TYPE.COPY);+ });+it('should trigger auto fill and set direction for expansion', async () => {const source: IRange = { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 };diff --git a/packages/sheets/src/services/auto-fill/auto-fill.service.ts b/packages/sheets/src/services/auto-fill/auto-fill.service.tsindex 108f887292..7d97cd78df 100644--- a/packages/sheets/src/services/auto-fill/auto-fill.service.ts+++ b/packages/sheets/src/services/auto-fill/auto-fill.service.ts@@ -14,19 +14,47 @@* limitations under the License.*/-import type { IAccessor, IDisposable, IMutationInfo, IRange, IRowAutoHeightInfo, Nullable, Workbook, Worksheet } from '@univerjs/core';+import type {+ IAccessor,+ IDisposable,+ IMutationInfo,+ IRange,+ IRowAutoHeightInfo,+ Nullable,+ Workbook,+ Worksheet,+} from '@univerjs/core';import type { Observable } from 'rxjs';+import {+ createIdentifier,+ Direction,+ Disposable,+ ICommandService,+ Inject,+ Injector,+ IUndoRedoService,+ IUniverInstanceService,+ ObjectMatrix,+ RANGE_TYPE,+ Rectangle,+ toDisposable,+ UniverInstanceType,+} from '@univerjs/core';+import { BehaviorSubject } from 'rxjs';import type { ISetRangeValuesMutationParams } from '../../commands/mutations/set-range-values.mutation';-import type { ISetWorksheetRowAutoHeightMutationParams } from '../../commands/mutations/set-worksheet-row-height.mutation';+import type {+ ISetWorksheetRowAutoHeightMutationParams,+} from '../../commands/mutations/set-worksheet-row-height.mutation';import type { IAutoFillLocation, IAutoFillRule, ISheetAutoFillHook } from './type';-import { createIdentifier, Direction, Disposable, ICommandService, Inject, Injector, IUndoRedoService, IUniverInstanceService, ObjectMatrix, RANGE_TYPE, Rectangle, toDisposable, UniverInstanceType } from '@univerjs/core';-import { BehaviorSubject } from 'rxjs';import { discreteRangeToRange, rangeToDiscreteRange } from '../../basics/utils';import { AutoClearContentCommand } from '../../commands/commands/auto-fill.command';import { AFFECT_LAYOUT_STYLES } from '../../commands/commands/set-style.command';import { getPrimaryForRange } from '../../commands/commands/utils/selection-utils';import { SetRangeValuesMutation } from '../../commands/mutations/set-range-values.mutation';-import { SetWorksheetRowAutoHeightMutation, SetWorksheetRowAutoHeightMutationFactory } from '../../commands/mutations/set-worksheet-row-height.mutation';+import {+ SetWorksheetRowAutoHeightMutation,+ SetWorksheetRowAutoHeightMutationFactory,+} from '../../commands/mutations/set-worksheet-row-height.mutation';import { SetSelectionsOperation } from '../../commands/operations/selection.operation';import AutoFillRules from './rules';import { AUTO_FILL_APPLY_TYPE, AUTO_FILL_HOOK_TYPE } from './type';@@ -66,7 +94,7 @@ export interface IAutoFillService {registerRule(rule: IAutoFillRule): void;getAllHooks(): ISheetAutoFillHook[];- getActiveHooks(): ISheetAutoFillHook[];+ getActiveHooks(applyType?: AUTO_FILL_APPLY_TYPE): ISheetAutoFillHook[];addHook(hook: ISheetAutoFillHook): IDisposable;fillData(applyType: AUTO_FILL_APPLY_TYPE): boolean;@@ -227,6 +255,8 @@ export class AutoFillService extends Disposable implements IAutoFillService {return false;}+ // A new drag replaces the cached fill session; its old menu must not survive a rejected preparation.+ this.setShowMenu(false);this.direction = direction;const autoFillSource = this._injector.invoke((accessor: IAccessor) => rangeToDiscreteRange(source, accessor, unitId, subUnitId));@@ -314,13 +344,13 @@ export class AutoFillService extends Disposable implements IAutoFillService {return this._hooks;}- getActiveHooks() {+ getActiveHooks(applyType = this.applyType) {const { source, target, unitId, subUnitId } = this.autoFillLocation || {};if (!source || !target || !unitId || !subUnitId) {return [];}const enabledHooks = this._hooks.filter(- (h) => !h.disable?.({ source, target, unitId, subUnitId }, this._direction, this.applyType) === true+ (h) => !h.disable?.({ source, target, unitId, subUnitId }, this._direction, applyType) === true);const onlyHooks = enabledHooks.filter((h) => h.type === AUTO_FILL_HOOK_TYPE.ONLY);if (onlyHooks.length > 0) {@@ -390,7 +420,6 @@ export class AutoFillService extends Disposable implements IAutoFillService {// eslint-disable-next-line max-lines-per-functionfillData(applyType: AUTO_FILL_APPLY_TYPE) {- this.applyType = applyType;const activeWorkbook = this._univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);const activeUnitId = activeWorkbook?.getUnitId();const activeSubUnitId = activeWorkbook?.getActiveSheet()?.getSheetId();@@ -401,11 +430,23 @@ export class AutoFillService extends Disposable implements IAutoFillService {}const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);- if (!workbook) return false;+ if (!workbook) {+ return false;+ }const worksheet = workbook.getSheetBySheetId(subUnitId);- if (!worksheet) return false;+ if (!worksheet) {+ return false;+ }const direction = this.direction;+ const activeHooks = this.getActiveHooks(applyType);+ // Prepare and validate before updating the apply type, undoing a previous fill or changing the selection.+ const fillCallbacks = activeHooks.map((hook) => hook.onPrepareFillData?.(+ { source, target, unitId, subUnitId },+ direction,+ applyType+ ) ?? (() => hook.onFillData?.({ source, target, unitId, subUnitId }, direction, applyType)));+ this.applyType = applyType;if (this._prevUndos.length > 0) {this._prevUndos.forEach((undo) => {@@ -415,7 +456,6 @@ export class AutoFillService extends Disposable implements IAutoFillService {this._prevUndos = [];const selection = Rectangle.union(discreteRangeToRange(source), discreteRangeToRange(target));- const activeHooks = this.getActiveHooks();// If filling the active sheet, update the selection immediatelyif (unitId === activeUnitId && subUnitId === activeSubUnitId) {@@ -441,9 +481,8 @@ export class AutoFillService extends Disposable implements IAutoFillService {const undos: IMutationInfo[] = [];const redos: IMutationInfo[] = [];- activeHooks.forEach((hook) => {- const { undos: hookUndos, redos: hookRedos } =- hook.onFillData?.({ source, target, unitId, subUnitId }, direction, applyType) || {};+ fillCallbacks.forEach((fill) => {+ const { undos: hookUndos, redos: hookRedos } = fill() || {};if (hookUndos) {undos.push(...hookUndos);}diff --git a/packages/sheets/src/services/auto-fill/type.ts b/packages/sheets/src/services/auto-fill/type.tsindex 4544934f70..3b8df7e15d 100644--- a/packages/sheets/src/services/auto-fill/type.ts+++ b/packages/sheets/src/services/auto-fill/type.ts@@ -14,8 +14,15 @@* limitations under the License.*/-import type { Direction, IAccessor, ICellData, IMutationInfo, IObjectMatrixPrimitiveType, Nullable } from '@univerjs/core';-import type { IDiscreteRange } from '../../basics';+import type {+ Direction,+ IAccessor,+ ICellData,+ IMutationInfo,+ IObjectMatrixPrimitiveType,+ Nullable,+} from '@univerjs/core';+import type { IDiscreteRange } from '../../basics/interfaces/selection-config';export enum AUTO_FILL_APPLY_TYPE {COPY = 'COPY',@@ -56,6 +63,12 @@ export interface ISheetAutoFillHook {bindUnit?: string;disable?: (location: IAutoFillLocation, direction: Direction, applyType: AUTO_FILL_APPLY_TYPE) => boolean;onBeforeFillData?(location: IAutoFillLocation, direction: Direction): AUTO_FILL_APPLY_TYPE | void;+ /** Prepare and validate without mutations; the returned callback captures undo data after reverting a previous fill. */+ onPrepareFillData?(+ location: IAutoFillLocation,+ direction: Direction,+ applyType: AUTO_FILL_APPLY_TYPE+ ): () => { undos: IMutationInfo[]; redos: IMutationInfo[] };onFillData?(location: IAutoFillLocation,direction: Direction,@@ -65,6 +78,13 @@ export interface ISheetAutoFillHook {redos: IMutationInfo[];};onAfterFillData?(location: IAutoFillLocation, direction: Direction, applyType: AUTO_FILL_APPLY_TYPE): boolean | void;+ /** Validate proposed values before reverting or applying any fill mutations. Throw to reject the entire fill. */+ onValidateFillData?(+ location: IAutoFillLocation,+ direction: Direction,+ applyType: AUTO_FILL_APPLY_TYPE,+ cellValue: IObjectMatrixPrimitiveType<Nullable<ICellData>>+ ): void;onBeforeSubmit?: (location: IAutoFillLocation, direction: Direction, applyType: AUTO_FILL_APPLY_TYPE, cellValue: IObjectMatrixPrimitiveType<Nullable<ICellData>>) => void;}