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(sheet): disable zooming on editing (#1200)
Wenzhao Hubcc5373882a5
diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex f206b8efdb..e24e22b861 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -50,6 +50,7 @@ export {type IMutationInfo,type IOperation,type IOperationInfo,+ NilCommand,sequenceExecute,sequenceExecuteAsync,} from './services/command/command.service';diff --git a/packages/core/src/services/command/command.service.ts b/packages/core/src/services/command/command.service.tsindex 28f47d5a41..245ee14888 100644--- a/packages/core/src/services/command/command.service.ts+++ b/packages/core/src/services/command/command.service.ts@@ -206,6 +206,7 @@ export class CommandService implements ICommandService {@ILogService private readonly _logService: ILogService) {this._commandRegistry = new CommandRegistry();+ this._registerCommand(NilCommand);}registerCommand(command: ICommand): IDisposable {@@ -467,3 +468,9 @@ export function sequenceExecuteAsync(const promises = tasks.map((task) => () => commandService.executeCommand(task.id, task.params, options));return sequenceAsync(promises);}++export const NilCommand: ICommand = {+ id: 'nil',+ type: CommandType.COMMAND,+ handler: () => true,+};diff --git a/packages/core/src/services/context/__tests__/context.service.spec.ts b/packages/core/src/services/context/__tests__/context.service.spec.tsnew file mode 100644index 0000000000..f052722197--- /dev/null+++ b/packages/core/src/services/context/__tests__/context.service.spec.ts@@ -0,0 +1,57 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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 { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { ContextService } from '../context.service';++const TEXT_CONTEXT_KEY = 'TEST_CONTEXT_KEY';++describe('Test ContextService', () => {+ let contextService: ContextService;++ beforeEach(() => {+ contextService = new ContextService();+ });++ afterEach(() => {+ contextService.dispose();+ });++ it('Should "subscribeContextValue$" emit when context updated', () => {+ let firstSubscriptionValue: boolean | undefined;+ const firstSubscription = contextService.subscribeContextValue$(TEXT_CONTEXT_KEY).subscribe((value) => {+ firstSubscriptionValue = value;+ });+ expect(firstSubscriptionValue).toBeUndefined();+ contextService.setContextValue(TEXT_CONTEXT_KEY, false);+ expect(firstSubscriptionValue).toBeFalsy();++ firstSubscription.unsubscribe();+ contextService.setContextValue(TEXT_CONTEXT_KEY, true);+ expect(firstSubscriptionValue).toBeFalsy();++ let secondSubscriptionValue: boolean | undefined;+ const secondSubscription = contextService.subscribeContextValue$(TEXT_CONTEXT_KEY).subscribe((value) => {+ secondSubscriptionValue = value;+ });+ expect(secondSubscriptionValue).toBeTruthy();++ contextService.setContextValue(TEXT_CONTEXT_KEY, false);+ expect(secondSubscriptionValue).toBeFalsy();+ secondSubscription.unsubscribe();+ });+});diff --git a/packages/core/src/services/context/context.service.ts b/packages/core/src/services/context/context.service.tsindex ad5a97eddb..b00e8f0d9e 100644--- a/packages/core/src/services/context/context.service.ts+++ b/packages/core/src/services/context/context.service.ts@@ -15,23 +15,24 @@*/import { createIdentifier } from '@wendellhu/redi';-import type { Observable } from 'rxjs';-import { Subject } from 'rxjs';+import { filter, Observable, Subject } from 'rxjs';import { Disposable } from '../../shared/lifecycle';export interface IContextService {- readonly contextChanged$: Observable<void>;+ readonly contextChanged$: Observable<{ [key: string]: boolean }>;getContextValue(key: string): boolean;setContextValue(key: string, value: boolean): void;++ subscribeContextValue$(key: string): Observable<boolean>;}export const IContextService = createIdentifier<IContextService>('univer.context-service');export class ContextService extends Disposable implements IContextService {- private _contextChanged$ = new Subject<void>();- contextChanged$: Observable<void> = this._contextChanged$.asObservable();+ private _contextChanged$ = new Subject<{ [key: string]: boolean }>();+ readonly contextChanged$ = this._contextChanged$.asObservable();private readonly _contextMap = new Map<string, boolean>();@@ -46,6 +47,20 @@ export class ContextService extends Disposable implements IContextService {setContextValue(key: string, value: boolean): void {this._contextMap.set(key, value);- this._contextChanged$.next();+ this._contextChanged$.next({ [key]: value });+ }++ subscribeContextValue$(key: string): Observable<boolean> {+ return new Observable((observer) => {+ const contextChangeSubscription = this._contextChanged$+ .pipe(filter((event) => typeof event[key] !== 'undefined'))+ .subscribe((event) => observer.next(event[key]));++ if (this._contextMap.has(key)) {+ observer.next(this._contextMap.get(key) as boolean);+ }++ return () => contextChangeSubscription.unsubscribe();+ });}}diff --git a/packages/design/src/hooks/observable.ts b/packages/design/src/hooks/observable.tsindex bcb891f2cd..2aeb4d70e4 100644--- a/packages/design/src/hooks/observable.ts+++ b/packages/design/src/hooks/observable.ts@@ -14,52 +14,79 @@* limitations under the License.*/-/**- * Copyright 2023-present DreamNum Inc.- *- * 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.- */+/* eslint-disable @typescript-eslint/no-explicit-any */import type React from 'react';-import { useRef, useState } from 'react';+import { useEffect, useRef, useState } from 'react';import type { Observable, Subscription } from 'rxjs';-export function useObservable<T>(observable: Observable<T>, defaultValue?: T): T | undefined;-export function useObservable<T>(observable: Observable<T>, defaultValue?: T, shouldHaveSyncValue?: true): T;+type ObservableOrFn<T> = Observable<T> | (() => Observable<T>);++function unwrap<T>(o: ObservableOrFn<T>): Observable<T> {+ if (typeof o === 'function') {+ return o();+ }++ return o;+}++function showArrayNotEqual(arr1: unknown[], arr2: unknown[]): boolean {+ if (arr1.length !== arr2.length) {+ return true;+ }++ return arr1.some((value, index) => value !== arr2[index]);+}++export function useObservable<T>(observable: ObservableOrFn<T>, shouldHaveSyncValue: true): T;export function useObservable<T>(- observable: Observable<T>,+ observable: ObservableOrFn<T>,+ shouldHaveSyncValue?: false,defaultValue?: T,- shouldHaveSyncValue?: true+ deps?: any[]+): T | undefined;+export function useObservable<T>(+ observable: ObservableOrFn<T>,+ shouldHaveSyncValue?: boolean,+ defaultValue?: T,+ deps?: any[]): T | undefined {const observableRef = useRef<Observable<T> | null>(null);const subscriptionRef = useRef<Subscription | null>(null);+ const depsRef = useRef<any[] | undefined>(deps ?? undefined);+ const initializedRef = useRef<boolean>(false);let setValue: React.Dispatch<React.SetStateAction<T | undefined>>;- let initialized = false;let innerDefaultValue: T | undefined;- if (!observableRef.current || observableRef.current !== observable) {++ const shouldResubscribe = (() => {+ if (typeof depsRef.current !== 'undefined') {+ const _deps = deps ?? [];+ if (showArrayNotEqual(depsRef.current, _deps)) {+ depsRef.current = _deps;+ return true;+ }++ return false;+ }++ return observableRef.current !== observable;+ })();++ if (!subscriptionRef.current || shouldResubscribe) {+ observableRef.current = unwrap(observable);subscriptionRef.current?.unsubscribe();- subscriptionRef.current = observable.subscribe((v) => {+ subscriptionRef.current = observableRef.current.subscribe((value) => {if (setValue) {- setValue(v);+ setValue(value);} else {- innerDefaultValue = v;- initialized = true;+ innerDefaultValue = value;+ initializedRef.current = true;}});}- if (shouldHaveSyncValue && !initialized) {+ if (shouldHaveSyncValue && !initializedRef.current) {throw new Error('[useObservable]: expect shouldHaveSyncValue but not getting a sync value!');}@@ -67,5 +94,9 @@ export function useObservable<T>(const value = s[0];setValue = s[1];+ useEffect(() => {+ return () => subscriptionRef.current?.unsubscribe();+ }, []);+return value;}diff --git a/packages/find-replace/src/views/dialog/Dialog.tsx b/packages/find-replace/src/views/dialog/Dialog.tsxindex 10b5b46290..9a096b103f 100644--- a/packages/find-replace/src/views/dialog/Dialog.tsx+++ b/packages/find-replace/src/views/dialog/Dialog.tsx@@ -14,7 +14,7 @@* limitations under the License.*/-import { IContextService, LocaleService } from '@univerjs/core';+import { LocaleService } from '@univerjs/core';import { Button, FormLayout, Input, InputWithSlot, Pager, Select, useObservable } from '@univerjs/design';import { LayoutService } from '@univerjs/ui';import type { IDisposable } from '@wendellhu/redi';@@ -29,7 +29,6 @@ const FIND_THROTTLE_TIME = 500;export function FindReplaceDialog() {const findReplaceService = useDependency(IFindReplaceService);const localeService = useDependency(LocaleService);- const contextService = useDependency(IContextService);const layoutService = useDependency(LayoutService);const [findString, setFindString] = useState<string>('');@@ -37,7 +36,7 @@ export function FindReplaceDialog() {const dialogContainerRef = useRef<HTMLDivElement>(null);- const state = useObservable(findReplaceService.state$);+ const state = useObservable(findReplaceService.state$, true);const { matchesCount, matchesPosition } = state;const revealReplace = useCallback(() => findReplaceService.revealReplace(), [findReplaceService]);diff --git a/packages/sheets-ui/src/controllers/sheet-ui.controller.ts b/packages/sheets-ui/src/controllers/sheet-ui.controller.tsindex 1af435fb53..a287eb77a3 100644--- a/packages/sheets-ui/src/controllers/sheet-ui.controller.ts+++ b/packages/sheets-ui/src/controllers/sheet-ui.controller.ts@@ -213,7 +213,14 @@ import {SetUnderlineShortcutItem,} from './shortcuts/style.shortcut';import { ClearSelectionValueShortcutItem } from './shortcuts/value.shortcut';-import { ResetZoomShortcutItem, ZoomInShortcutItem, ZoomOutShortcutItem } from './shortcuts/view.shortcut';+import {+ PreventDefaultResetZoomShortcutItem,+ PreventDefaultZoomInShortcutItem,+ PreventDefaultZoomOutShortcutItem,+ ResetZoomShortcutItem,+ ZoomInShortcutItem,+ ZoomOutShortcutItem,+} from './shortcuts/view.shortcut';@OnLifecycle(LifecycleStages.Ready, SheetUIController)export class SheetUIController extends Disposable {@@ -409,6 +416,9 @@ export class SheetUIController extends Disposable {ZoomInShortcutItem,ZoomOutShortcutItem,ResetZoomShortcutItem,+ PreventDefaultResetZoomShortcutItem,+ PreventDefaultZoomInShortcutItem,+ PreventDefaultZoomOutShortcutItem,// toggle cell style shortcutsSetBoldShortcutItem,diff --git a/packages/sheets-ui/src/controllers/shortcuts/view.shortcut.ts b/packages/sheets-ui/src/controllers/shortcuts/view.shortcut.tsindex 23a2310f60..8a8a16ffa3 100644--- a/packages/sheets-ui/src/controllers/shortcuts/view.shortcut.ts+++ b/packages/sheets-ui/src/controllers/shortcuts/view.shortcut.ts@@ -14,37 +14,57 @@* limitations under the License.*/+import { NilCommand } from '@univerjs/core';import type { IShortcutItem } from '@univerjs/ui';import { KeyCode, MetaKeys } from '@univerjs/ui';import { ChangeZoomRatioCommand } from '../../commands/commands/set-zoom-ratio.command';+import { whenSheetEditorFocused } from './utils';export const ZoomInShortcutItem: IShortcutItem = {id: ChangeZoomRatioCommand.id,description: 'shortcut.sheet.zoom-in',binding: KeyCode.EQUAL | MetaKeys.CTRL_COMMAND,group: '3_sheet-view',+ preconditions: whenSheetEditorFocused,+ priority: 1,staticParameters: {delta: 0.2,},};+export const PreventDefaultZoomInShortcutItem: IShortcutItem = {+ id: NilCommand.id,+ binding: KeyCode.EQUAL | MetaKeys.CTRL_COMMAND,+};export const ZoomOutShortcutItem: IShortcutItem = {id: ChangeZoomRatioCommand.id,description: 'shortcut.sheet.zoom-out',binding: KeyCode.MINUS | MetaKeys.CTRL_COMMAND,group: '3_sheet-view',+ preconditions: whenSheetEditorFocused,+ priority: 1,staticParameters: {delta: -0.2,},};+export const PreventDefaultZoomOutShortcutItem: IShortcutItem = {+ id: NilCommand.id,+ binding: KeyCode.MINUS | MetaKeys.CTRL_COMMAND,+};export const ResetZoomShortcutItem: IShortcutItem = {id: ChangeZoomRatioCommand.id,description: 'shortcut.sheet.reset-zoom',binding: KeyCode.Digit0 | MetaKeys.CTRL_COMMAND,+ preconditions: whenSheetEditorFocused,group: '3_sheet-view',+ priority: 1,staticParameters: {reset: true,},};+export const PreventDefaultResetZoomShortcutItem: IShortcutItem = {+ id: NilCommand.id,+ binding: KeyCode.Digit0 | MetaKeys.CTRL_COMMAND,+};diff --git a/packages/sheets-ui/src/views/count-bar/ZoomSlider.tsx b/packages/sheets-ui/src/views/count-bar/ZoomSlider.tsxindex 54194878f7..3adc256168 100644--- a/packages/sheets-ui/src/views/count-bar/ZoomSlider.tsx+++ b/packages/sheets-ui/src/views/count-bar/ZoomSlider.tsx@@ -14,11 +14,18 @@* limitations under the License.*/-import { ICommandService, IUniverInstanceService } from '@univerjs/core';-import { Slider } from '@univerjs/design';+import {+ EDITOR_ACTIVATED,+ FOCUSING_UNIVER_EDITOR,+ ICommandService,+ IContextService,+ IUniverInstanceService,+} from '@univerjs/core';+import { Slider, useObservable } from '@univerjs/design';import { SetWorksheetActivateCommand } from '@univerjs/sheets';import { useDependency } from '@wendellhu/redi/react-bindings';import React, { useEffect, useState } from 'react';+import { combineLatest, debounceTime, map } from 'rxjs';import { SetZoomRatioCommand } from '../../commands/commands/set-zoom-ratio.command';import { SetZoomRatioOperation } from '../../commands/operations/set-zoom-ratio.operation';@@ -27,11 +34,29 @@ import { SHEET_ZOOM_RANGE } from '../../common/keys';// eslint-disable-next-line no-magic-numbersconst ZOOM_MAP = [50, 80, 100, 130, 150, 170, 200, 400];+const DISABLE_DEBOUNCE_TIME = 100;+export function ZoomSlider() {const commandService = useDependency(ICommandService);const univerInstanceService = useDependency(IUniverInstanceService);+ const contextService = useDependency(IContextService);+const currentZoom = getCurrentZoom();const [zoom, setZoom] = useState(currentZoom);+ const sheetEditorFocused = useObservable(+ () =>+ combineLatest(+ contextService.subscribeContextValue$(FOCUSING_UNIVER_EDITOR),+ contextService.subscribeContextValue$(EDITOR_ACTIVATED)+ ).pipe(+ map(([editorFocus, editorActivated]) => editorFocus && !editorActivated),+ debounceTime(DISABLE_DEBOUNCE_TIME)+ ),+ false,+ true,+ [FOCUSING_UNIVER_EDITOR]+ );+ const disabled = !sheetEditorFocused;useEffect(() => {const disposable = commandService.onCommandExecuted((commandInfo) => {@@ -68,5 +93,13 @@ export function ZoomSlider() {});}- return <Slider min={SHEET_ZOOM_RANGE[0]} value={zoom} shortcuts={ZOOM_MAP} onChange={handleChange} />;+ return (+ <Slider+ disabled={disabled}+ min={SHEET_ZOOM_RANGE[0]}+ value={zoom}+ shortcuts={ZOOM_MAP}+ onChange={handleChange}+ />+ );}