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(ui): harden high-priority editor interactions (#7629)
Univer97fb3fa48d90
diff --git a/packages/core/src/services/undoredo/__tests__/undoredo.service.spec.ts b/packages/core/src/services/undoredo/__tests__/undoredo.service.spec.tsindex 0970f020e9..66dab29e06 100644--- a/packages/core/src/services/undoredo/__tests__/undoredo.service.spec.ts+++ b/packages/core/src/services/undoredo/__tests__/undoredo.service.spec.ts@@ -19,6 +19,8 @@ import { BehaviorSubject } from 'rxjs';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY } from '../../../common/const';import { Injector } from '../../../common/di';+import { DocumentDataModel } from '../../../docs/data-model/document-data-model';+import { Univer } from '../../../univer';import { CommandService, CommandType, ICommandService } from '../../command/command.service';import { ConfigService, IConfigService } from '../../config/config.service';import { EDITOR_ACTIVATED, FOCUSING_FX_BAR_EDITOR, FOCUSING_SHEET } from '../../context/context';@@ -35,6 +37,46 @@ import {const MUTATION_ID = 'test.mutation';+describe('unit-specific undo redo status', () => {+ it('tracks an unfocused unit without changing focus or consuming either history', () => {+ const univer = new Univer();+ const injector = univer.__getInjector();+ const instanceService = injector.get(IUniverInstanceService);+ const historyService = injector.get(IUndoRedoService);+ const host = injector.createInstance(DocumentDataModel, { id: 'host' });+ const child = injector.createInstance(DocumentDataModel, { id: 'child' });+ instanceService.__addUnit(host);+ instanceService.__addUnit(child);+ instanceService.focusUnit(host.getUnitId());+ const focusedStatuses: Array<{ undos: number; redos: number }> = [];+ const subscription = historyService.undoRedoStatus$.subscribe((status) => focusedStatuses.push(status));+ try {+ expect(historyService.getUndoRedoStatus('missing')).toEqual({ undos: 0, redos: 0 });+ historyService.pushUndoRedo({ unitID: host.getUnitId(), undoMutations: [{ id: MUTATION_ID, params: {} }], redoMutations: [{ id: MUTATION_ID, params: {} }] });+ historyService.pushUndoRedo({ unitID: child.getUnitId(), undoMutations: [{ id: MUTATION_ID, params: {} }], redoMutations: [{ id: MUTATION_ID, params: {} }] });+ historyService.pushUndoRedo({ unitID: child.getUnitId(), undoMutations: [{ id: MUTATION_ID, params: {} }], redoMutations: [{ id: MUTATION_ID, params: {} }] });+ const notificationCount = focusedStatuses.length;+ expect(historyService.getUndoRedoStatus(child.getUnitId())).toEqual({ undos: 2, redos: 0 });+ expect(historyService.getUndoRedoStatus(host.getUnitId())).toEqual({ undos: 1, redos: 0 });+ expect(instanceService.getFocusedUnit()).toBe(host);+ expect(focusedStatuses).toHaveLength(notificationCount);+ expect(focusedStatuses[notificationCount - 1]).toEqual({ undos: 1, redos: 0 });++ instanceService.focusUnit(child.getUnitId());+ historyService.popUndoToRedo();+ instanceService.focusUnit(host.getUnitId());+ expect(historyService.getUndoRedoStatus(child.getUnitId())).toEqual({ undos: 1, redos: 1 });+ historyService.clearUndoRedo(child.getUnitId());+ expect(historyService.getUndoRedoStatus(child.getUnitId())).toEqual({ undos: 0, redos: 0 });+ expect(historyService.getUndoRedoStatus(host.getUnitId())).toEqual({ undos: 1, redos: 0 });+ expect(instanceService.getFocusedUnit()).toBe(host);+ } finally {+ subscription.unsubscribe();+ univer.dispose();+ }+ });+});+class FocusedUnit {constructor(private readonly _unitId: string) {}diff --git a/packages/core/src/services/undoredo/undoredo.service.ts b/packages/core/src/services/undoredo/undoredo.service.tsindex 92fbc9ea50..c1cbf6e7b3 100644--- a/packages/core/src/services/undoredo/undoredo.service.ts+++ b/packages/core/src/services/undoredo/undoredo.service.ts@@ -44,6 +44,9 @@ export interface IUndoRedoItem {export interface IUndoRedoService {undoRedoStatus$: Observable<IUndoRedoStatus>;+ /** Read a unit's history counts without changing the focused unit. */+ getUndoRedoStatus(unitId: string): IUndoRedoStatus;+pushUndoRedo(item: IUndoRedoItem): void;/**@@ -205,6 +208,13 @@ export class LocalUndoRedoService extends Disposable implements IUndoRedoServicethis.disposeWithMe(toDisposable(this._univerInstanceService.focused$.subscribe(() => this._updateStatus())));}+ getUndoRedoStatus(unitId: string): IUndoRedoStatus {+ return {+ undos: this._undoStacks.get(unitId)?.length ?? 0,+ redos: this._redoStacks.get(unitId)?.length ?? 0,+ };+ }+pushUndoRedo(item: IUndoRedoItem): void {const { unitID } = item;diff --git a/packages/design/src/components/color-picker/ColorInput.tsx b/packages/design/src/components/color-picker/ColorInput.tsxindex 65e48e46ae..f92aa31343 100644--- a/packages/design/src/components/color-picker/ColorInput.tsx+++ b/packages/design/src/components/color-picker/ColorInput.tsx@@ -15,7 +15,7 @@*/import type { ChangeEvent } from 'react';-import { useEffect, useMemo, useState } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { borderClassName } from '../../helper/class-utilities';import { clsx } from '../../helper/clsx';import { hexToHsv, hsvToHex, hsvToRgb, rgbToHsv } from './color-conversion';@@ -34,51 +34,102 @@ interface IInputProps {onChange?: (h: number, s: number, v: number, a?: number) => void;}+const FULL_HEX_COLOR_PATTERN = /^[0-9a-f]{6}$/i;+function HexInput({ hsv, onChange }: IInputProps) {+ const inputRef = useRef<HTMLInputElement>(null);+ const isComposingRef = useRef(false);const [inputValue, setInputValue] = useState('');const hexValue = useMemo(() => hsvToHex(hsv[0], hsv[1], hsv[2]), [hsv]);useEffect(() => {- setInputValue(hexValue.replace(/^#/, ''));- }, [hexValue]);-- const isValidHex = (hex: string) => {- return /^[0-9A-Fa-f]{6}$/.test(hex);- };-- const handleChange = (e: ChangeEvent<HTMLInputElement>) => {- const newValue = e.target.value.trim();+ if (isComposingRef.current) {+ return;+ }- if (newValue.length > 6) return;+ const nextValue = hexValue.replace(/^#/, '');+ // Preserve the user's casing so color echoes do not rewrite native selection or undo history.+ setInputValue((previous) => previous.toLowerCase() === nextValue ? previous : nextValue);+ }, [hexValue]);- if (newValue !== '' && !/^[0-9A-Fa-f]*$/.test(newValue)) return;+ const updateInputValue = useCallback((newValue: string) => {+ if (!/^[0-9a-f]{0,6}$/i.test(newValue)) {+ return;+ }setInputValue(newValue);- if (isValidHex(newValue)) {+ if (FULL_HEX_COLOR_PATTERN.test(newValue)) {const hsvValue = hexToHsv(newValue);if (hsvValue && onChange) {onChange(...hsvValue);}}+ }, [onChange]);++ const handleChange = (e: ChangeEvent<HTMLInputElement>) => {+ const newValue = e.target.value.trim();+ if (isComposingRef.current || (e.nativeEvent as InputEvent).isComposing) {+ setInputValue(newValue);+ return;+ }++ updateInputValue(newValue);};+ useEffect(() => {+ const input = inputRef.current;+ if (!input) {+ return;+ }++ const handleCompositionStart = (event: CompositionEvent) => {+ event.stopPropagation();+ isComposingRef.current = true;+ };+ const handleCompositionUpdate = (event: CompositionEvent) => {+ event.stopPropagation();+ };+ const handleCompositionEnd = (event: CompositionEvent) => {+ event.stopPropagation();+ isComposingRef.current = false;+ const value = input.value.trim();+ if (value !== '' && !FULL_HEX_COLOR_PATTERN.test(value)) {+ setInputValue(hexValue.replace(/^#/, ''));+ return;+ }+ updateInputValue(value);+ };++ // Stop native composition before it reaches the host editor's DOM listeners.+ input.addEventListener('compositionstart', handleCompositionStart);+ input.addEventListener('compositionupdate', handleCompositionUpdate);+ input.addEventListener('compositionend', handleCompositionEnd);+ return () => {+ input.removeEventListener('compositionstart', handleCompositionStart);+ input.removeEventListener('compositionupdate', handleCompositionUpdate);+ input.removeEventListener('compositionend', handleCompositionEnd);+ };+ }, [hexValue, updateInputValue]);+const handleBlur = () => {- if (!isValidHex(inputValue)) {- setInputValue(hexValue.replace(/^#/, ''));+ if (!FULL_HEX_COLOR_PATTERN.test(inputRef.current?.value ?? '')) {+ const nextValue = hexValue.replace(/^#/, '');+ setInputValue(nextValue);}};return (<><input+ ref={inputRef}+ value={inputValue}className={clsx(`univer-w-full univer-px-2 !univer-pl-4 univer-uppercasefocus:univer-border-primary-500 focus:univer-outline-nonertl:!univer-pl-2 rtl:!univer-pr-4dark:!univer-text-gray-0`, borderClassName)}- value={inputValue}onChange={handleChange}onBlur={handleBlur}maxLength={6}diff --git a/packages/design/src/components/color-picker/__tests__/ColorInput.spec.tsx b/packages/design/src/components/color-picker/__tests__/ColorInput.spec.tsxnew file mode 100644index 0000000000..bde3e76675--- /dev/null+++ b/packages/design/src/components/color-picker/__tests__/ColorInput.spec.tsx@@ -0,0 +1,166 @@+/**+ * 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 { fireEvent, render } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';+import { hexToHsv } from '../color-conversion';+import { ColorInput } from '../ColorInput';++describe('ColorInput', () => {+ it.each(['F05252', 'aB12Cd'])('preserves the native input value when its own color %s is echoed back', (value) => {+ const onChange = vi.fn();+ const { container, rerender } = render(+ <ColorInput hsv={[0, 100, 100]} alpha={1} format="hex" onChange={onChange} />+ );+ const input = container.querySelector('input[maxlength="6"]') as HTMLInputElement;+ fireEvent.change(input, { target: { value } });+ input.setSelectionRange(2, 4);+ const writeValue = vi.spyOn(input, 'value', 'set');++ expect(onChange).toHaveBeenLastCalledWith(...hexToHsv(value)!);+ rerender(<ColorInput hsv={hexToHsv(value)!} alpha={1} format="hex" onChange={onChange} />);++ expect(writeValue).not.toHaveBeenCalled();+ expect(input.value).toBe(value);+ expect([input.selectionStart, input.selectionEnd]).toEqual([2, 4]);+ writeValue.mockRestore();+ });++ it('synchronizes a different external color while a partial hex value is being edited', () => {+ const onChange = vi.fn();+ const { container, rerender } = render(+ <ColorInput hsv={[0, 100, 100]} alpha={1} format="hex" onChange={onChange} />+ );+ const input = container.querySelector('input[maxlength="6"]') as HTMLInputElement;+ fireEvent.change(input, { target: { value: 'F0' } });+ expect(onChange).not.toHaveBeenCalled();++ rerender(<ColorInput hsv={[120, 100, 100]} alpha={1} format="hex" onChange={onChange} />);++ expect(input.value).toBe('00ff00');+ expect(onChange).not.toHaveBeenCalled();+ });++ it('restores the latest accepted color when an incomplete edit loses focus', () => {+ const onChange = vi.fn();+ const { container, rerender } = render(+ <ColorInput hsv={[0, 100, 100]} alpha={1} format="hex" onChange={onChange} />+ );+ const input = container.querySelector('input[maxlength="6"]') as HTMLInputElement;+ fireEvent.change(input, { target: { value: 'F05252' } });+ rerender(<ColorInput hsv={hexToHsv('F05252')!} alpha={1} format="hex" onChange={onChange} />);+ fireEvent.change(input, { target: { value: 'F0' } });+ fireEvent.blur(input);++ expect(input.value).toBe('f05252');+ expect(onChange).toHaveBeenCalledTimes(1);+ });++ it('preserves native IME text until composition ends, then restores an invalid hex value', () => {+ const onChange = vi.fn();+ const { container } = render(+ <ColorInput hsv={[0, 100, 100]} alpha={1} format="hex" onChange={onChange} />+ );+ const input = container.querySelector('input[maxlength="6"]') as HTMLInputElement;++ fireEvent.compositionStart(input);+ fireEvent.compositionUpdate(input, { data: 'ni' });+ fireEvent.input(input, {+ inputType: 'insertCompositionText',+ isComposing: true,+ target: { value: 'ni' },+ });+ expect(input.value).toBe('ni');+ expect(onChange).not.toHaveBeenCalled();++ fireEvent.compositionEnd(input);+ expect(input.value).toBe('ff0000');+ expect(onChange).not.toHaveBeenCalled();+ });++ it('commits a valid hex value once native composition ends', () => {+ const onChange = vi.fn();+ const { container } = render(+ <ColorInput hsv={[0, 100, 100]} alpha={1} format="hex" onChange={onChange} />+ );+ const input = container.querySelector('input[maxlength="6"]') as HTMLInputElement;++ fireEvent.compositionStart(input);+ fireEvent.compositionUpdate(input, { data: 'F05252' });+ fireEvent.input(input, {+ inputType: 'insertCompositionText',+ isComposing: true,+ target: { value: 'F05252' },+ });+ expect(onChange).not.toHaveBeenCalled();++ fireEvent.compositionEnd(input);+ expect(onChange).toHaveBeenCalledOnce();+ expect(onChange).toHaveBeenCalledWith(...hexToHsv('F05252')!);+ });++ it.each(['F05252', 'ni'])('keeps composition %s local and uses current props after a rerender', (value) => {+ const previousOnChange = vi.fn();+ const onChange = vi.fn();+ const hostComposition = vi.fn();+ const { container, rerender, unmount } = render(+ <ColorInput hsv={[0, 100, 100]} alpha={1} format="hex" onChange={previousOnChange} />+ );+ const input = container.querySelector('input[maxlength="6"]') as HTMLInputElement;+ const events = ['compositionstart', 'compositionupdate', 'compositionend'];+ for (const event of events) {+ container.addEventListener(event, hostComposition);+ }+ try {+ fireEvent.compositionStart(input);+ fireEvent.compositionUpdate(input, { data: value });+ fireEvent.input(input, { isComposing: true, target: { value } });+ rerender(<ColorInput hsv={[120, 100, 100]} alpha={1} format="hex" onChange={onChange} />);+ expect(input.value).toBe(value);+ fireEvent.compositionEnd(input);++ expect(hostComposition).not.toHaveBeenCalled();+ expect(previousOnChange).not.toHaveBeenCalled();+ if (value === 'F05252') {+ expect(onChange).toHaveBeenCalledExactlyOnceWith(...hexToHsv(value)!);+ } else {+ expect(input.value).toBe('00ff00');+ expect(onChange).not.toHaveBeenCalled();+ }++ onChange.mockClear();+ unmount();+ fireEvent.compositionEnd(input);+ expect(onChange).not.toHaveBeenCalled();+ } finally {+ for (const event of events) {+ container.removeEventListener(event, hostComposition);+ }+ }+ });++ it.each(['F0!', 'F012345'])('rejects invalid draft %s without committing a color', (value) => {+ const onChange = vi.fn();+ const { container } = render(+ <ColorInput hsv={[0, 100, 100]} alpha={1} format="hex" onChange={onChange} />+ );+ const input = container.querySelector('input[maxlength="6"]') as HTMLInputElement;+ fireEvent.change(input, { target: { value: 'F0' } });+ fireEvent.change(input, { target: { value } });+ expect(input.value).toBe('F0');+ expect(onChange).not.toHaveBeenCalled();+ });+});diff --git a/packages/design/src/components/dialog/Dialog.tsx b/packages/design/src/components/dialog/Dialog.tsxindex 3ed9bda864..d439b94e7f 100644--- a/packages/design/src/components/dialog/Dialog.tsx+++ b/packages/design/src/components/dialog/Dialog.tsx@@ -27,6 +27,7 @@ import {Dialog as DialogProvider,DialogTitle,} from './DialogPrimitive';+import { useDialogFocus } from './use-dialog-focus';export interface IDialogProps {children: ReactNode;@@ -117,6 +118,9 @@ export interface IDialogProps {*/onClose?: () => void;+ /** Prevent default to provide a caller-owned focus destination when the dialog closes. */+ onCloseAutoFocus?: (event: Event) => void;+showOk?: boolean;showCancel?: boolean;@@ -282,11 +286,13 @@ export function Dialog(props: IDialogProps) {showCancel,onOpenChange,onClose,+ onCloseAutoFocus,onOk,onCancel,} = props;const { locale, mountContainer, direction } = useContext(ConfigContext);+ const { handleContentRef, handleOpenAutoFocus, handleCloseAutoFocus } = useDialogFocus(mask, onCloseAutoFocus);const { position, isDragging, setElementRef, handleMouseDown } = useDraggable({ defaultPosition, enabled: draggable });@@ -307,11 +313,12 @@ export function Dialog(props: IDialogProps) {): null);- const handleContentRef = useCallback((node: HTMLDivElement | null) => {+ const handleDraggableContentRef = useCallback((node: HTMLDivElement | null) => {+ handleContentRef(node);if (node && draggable) {setElementRef(node);}- }, [draggable, setElementRef]);+ }, [draggable, handleContentRef, setElementRef]);const handleOpenChange = useCallback((isOpen: boolean) => {if (!mask && !isOpen) {@@ -337,7 +344,7 @@ export function Dialog(props: IDialogProps) {modal={mask !== false}><DialogContent- ref={handleContentRef}+ ref={handleDraggableContentRef}className={clsx(className, {'!univer-animate-none': draggable,})}@@ -362,7 +369,14 @@ export function Dialog(props: IDialogProps) {overlayClassName={overlayClassName}dir={direction}onClickClose={handleClickClose}+ onOpenAutoFocus={handleOpenAutoFocus}+ onCloseAutoFocus={handleCloseAutoFocus}onEscapeKeyDown={(e) => {+ if (e.isComposing) {+ e.preventDefault();+ return;+ }+if (keyboard) {handleClickClose();}diff --git a/packages/design/src/components/dialog/MobileDialog.tsx b/packages/design/src/components/dialog/MobileDialog.tsxindex 2d84b82ef4..f10198cab1 100644--- a/packages/design/src/components/dialog/MobileDialog.tsx+++ b/packages/design/src/components/dialog/MobileDialog.tsx@@ -27,6 +27,7 @@ import {Dialog as DialogProvider,DialogTitle,} from './DialogPrimitive';+import { useDialogFocus } from './use-dialog-focus';export type IMobileDialogProps = IDialogProps;@@ -47,10 +48,12 @@ export function MobileDialog(props: IMobileDialogProps) {showCancel,onOpenChange,onClose,+ onCloseAutoFocus,onOk,onCancel,} = props;const { locale, mountContainer, direction } = useContext(ConfigContext);+ const { handleContentRef, handleOpenAutoFocus, handleCloseAutoFocus } = useDialogFocus(mask, onCloseAutoFocus);const maxHeight = globalThis.CSS?.supports('height', '1dvh') ? '80dvh' : '80vh';const footer = propFooter ?? (showOk || showCancel? (@@ -80,6 +83,7 @@ export function MobileDialog(props: IMobileDialogProps) {return (<DialogProvider open={open} onOpenChange={handleOpenChange} modal={mask !== false}><DialogContent+ ref={handleContentRef}className={clsx(`!univer-bottom-0 !univer-left-0 !univer-right-0 !univer-top-auto !univer-max-w-none!univer-translate-x-0 !univer-translate-y-0 !univer-gap-4 !univer-overflow-y-auto@@ -107,7 +111,13 @@ export function MobileDialog(props: IMobileDialogProps) {overlayClassName={overlayClassName}dir={direction}onClickClose={close}+ onOpenAutoFocus={handleOpenAutoFocus}+ onCloseAutoFocus={handleCloseAutoFocus}onEscapeKeyDown={(event) => {+ if (event.isComposing) {+ event.preventDefault();+ return;+ }if (keyboard) {close();}diff --git a/packages/design/src/components/dialog/__tests__/Dialog.spec.tsx b/packages/design/src/components/dialog/__tests__/Dialog.spec.tsxnew file mode 100644index 0000000000..3dfa19a688--- /dev/null+++ b/packages/design/src/components/dialog/__tests__/Dialog.spec.tsx@@ -0,0 +1,181 @@+/**+ * 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 { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { Dialog } from '../Dialog';+import { MobileDialog } from '../MobileDialog';++afterEach(cleanup);++describe.each([['Dialog', Dialog], ['MobileDialog', MobileDialog]] as const)('%s focus recovery', (_name, DialogComponent) => {+ it('keeps composition Escape inside the real dialog and allows ordinary Escape afterwards', async () => {+ const onClose = vi.fn();+ const onOpenChange = vi.fn();+ const { getByRole } = render(+ <DialogComponent open title="Color" onClose={onClose} onOpenChange={onOpenChange}>+ <input aria-label="Hex color" />+ </DialogComponent>+ );+ const input = getByRole('textbox', { name: 'Hex color' });+ await waitFor(() => expect(document.activeElement).toBe(input));++ fireEvent.compositionStart(input);+ const composingEscape = new KeyboardEvent('keydown', {+ key: 'Escape',+ isComposing: true,+ bubbles: true,+ cancelable: true,+ });+ fireEvent(input, composingEscape);+ expect(composingEscape.defaultPrevented).toBe(true);+ expect(onClose).not.toHaveBeenCalled();+ expect(onOpenChange).not.toHaveBeenCalled();+ expect(document.activeElement).toBe(input);+ expect(getByRole('dialog').contains(input)).toBe(true);++ fireEvent.compositionEnd(input);+ fireEvent.keyDown(input, { key: 'Escape' });+ expect(onClose).toHaveBeenCalledOnce();+ expect(onOpenChange).toHaveBeenCalledExactlyOnceWith(false);+ });++ it('restores input before delayed teardown and preserves subsequently chosen focus', async () => {+ const editor = document.createElement('input');+ const nextTarget = document.createElement('input');+ document.body.append(editor, nextTarget);+ try {+ editor.focus();+ const { rerender, getByRole } = render(<DialogComponent open title="Validation"><button>OK</button></DialogComponent>);+ await waitFor(() => expect(document.activeElement).toBe(getByRole('button', { name: 'OK' })));+ vi.useFakeTimers();+ await act(async () => {+ rerender(<DialogComponent open={false} title="Validation"><button>OK</button></DialogComponent>);+ await Promise.resolve();+ });+ expect(document.activeElement).toBe(editor);+ nextTarget.focus();+ act(() => vi.runOnlyPendingTimers());+ expect(document.activeElement).toBe(nextTarget);+ } finally {+ if (vi.isFakeTimers()) {+ act(() => vi.runOnlyPendingTimers());+ vi.useRealTimers();+ }+ editor.remove();+ nextTarget.remove();+ }+ });++ it('honors a caller override instead of restoring the transient opener', async () => {+ const opener = document.createElement('button');+ const returnTarget = document.createElement('button');+ document.body.append(opener, returnTarget);+ const restoreFocus = (event: Event) => {+ event.preventDefault();+ returnTarget.focus();+ };+ try {+ opener.focus();+ const { rerender, getByRole } = render(<DialogComponent open title="Validation" onCloseAutoFocus={restoreFocus}><button>OK</button></DialogComponent>);+ await waitFor(() => expect(document.activeElement).toBe(getByRole('button', { name: 'OK' })));+ rerender(<DialogComponent open={false} title="Validation" onCloseAutoFocus={restoreFocus}><button>OK</button></DialogComponent>);+ await waitFor(() => expect(document.activeElement).toBe(returnTarget));+ } finally {+ opener.remove();+ returnTarget.remove();+ }+ });++ it('returns focus through the parent modal before returning to the editor', async () => {+ const editor = document.createElement('input');+ document.body.appendChild(editor);+ try {+ editor.focus();+ const { rerender, getByRole } = render(+ <DialogComponent open title="Parent">+ <button>Parent action</button>+ <DialogComponent open={false} title="Child"><button>Child action</button></DialogComponent>+ </DialogComponent>+ );+ const parentAction = getByRole('button', { name: 'Parent action' });+ await waitFor(() => expect(document.activeElement).toBe(parentAction));+ rerender(+ <DialogComponent open title="Parent">+ <button>Parent action</button>+ <DialogComponent open title="Child"><button>Child action</button></DialogComponent>+ </DialogComponent>+ );+ await waitFor(() => expect(document.activeElement).toBe(getByRole('button', { name: 'Child action' })));+ rerender(+ <DialogComponent open title="Parent">+ <button>Parent action</button>+ <DialogComponent open={false} title="Child"><button>Child action</button></DialogComponent>+ </DialogComponent>+ );+ await waitFor(() => expect(document.activeElement).toBe(parentAction));+ rerender(<DialogComponent open={false} title="Parent"><button>Parent action</button></DialogComponent>);+ await waitFor(() => expect(document.activeElement).toBe(editor));+ } finally {+ editor.remove();+ }+ });++ it('captures the current editor separately on each open', async () => {+ const first = document.createElement('input');+ const second = document.createElement('input');+ document.body.append(first, second);+ try {+ const { rerender, getByRole } = render(<DialogComponent open={false} title="Validation"><button>OK</button></DialogComponent>);+ for (const editor of [first, second]) {+ editor.focus();+ rerender(<DialogComponent open title="Validation"><button>OK</button></DialogComponent>);+ await waitFor(() => expect(document.activeElement).toBe(getByRole('button', { name: 'OK' })));+ rerender(<DialogComponent open={false} title="Validation"><button>OK</button></DialogComponent>);+ await waitFor(() => expect(document.activeElement).toBe(editor));+ }+ } finally {+ first.remove();+ second.remove();+ }+ });++ it('does not focus a removed editor when closing', async () => {+ const editor = document.createElement('input');+ document.body.appendChild(editor);+ editor.focus();+ const { rerender, getByRole, queryByRole } = render(<DialogComponent open title="Validation"><button>OK</button></DialogComponent>);+ await waitFor(() => expect(document.activeElement).toBe(getByRole('button', { name: 'OK' })));+ editor.remove();+ rerender(<DialogComponent open={false} title="Validation"><button>OK</button></DialogComponent>);+ await waitFor(() => expect(queryByRole('dialog')).toBeNull());+ expect(document.activeElement).toBe(document.body);+ });++ it('returns focus to the editor after a programmatically opened modal closes', async () => {+ const editor = document.createElement('input');+ document.body.appendChild(editor);+ try {+ editor.focus();+ const { rerender, getByRole } = render(<DialogComponent open title="Validation"><button>OK</button></DialogComponent>);+ await waitFor(() => expect(document.activeElement).toBe(getByRole('button', { name: 'OK' })));+ rerender(<DialogComponent open={false} title="Validation"><button>OK</button></DialogComponent>);+ await waitFor(() => expect(document.activeElement).toBe(editor));+ } finally {+ editor.remove();+ }+ });+});diff --git a/packages/design/src/components/dialog/__tests__/logic.spec.tsx b/packages/design/src/components/dialog/__tests__/logic.spec.tsxindex e2ee765f4d..374cccd199 100644--- a/packages/design/src/components/dialog/__tests__/logic.spec.tsx+++ b/packages/design/src/components/dialog/__tests__/logic.spec.tsx@@ -38,7 +38,7 @@ vi.mock('../DialogPrimitive', async () => {ref={ref}role="dialog"tabIndex={0}- onKeyDown={(e) => onEscapeKeyDown?.(e)}+ onKeyDown={(e) => onEscapeKeyDown?.(e.nativeEvent)}onPointerDown={(e) => onPointerDownOutside?.(e)}><button type="button" data-slot="close" onClick={onClickClose}>@@ -108,6 +108,29 @@ describe('Dialog logic branches', () => {expect(onClose).toHaveBeenCalled();});+ it('should keep the dialog open when escape is used to cancel an IME composition', () => {+ const onOpenChange = vi.fn();+ const onClose = vi.fn();++ render(+ <Dialog open keyboard onOpenChange={onOpenChange} onClose={onClose}>+ content+ </Dialog>+ );++ const event = new KeyboardEvent('keydown', {+ bubbles: true,+ cancelable: true,+ isComposing: true,+ key: 'Escape',+ });+ screen.getByRole('dialog').dispatchEvent(event);++ expect(event.defaultPrevented).toBe(true);+ expect(onOpenChange).not.toHaveBeenCalled();+ expect(onClose).not.toHaveBeenCalled();+ });+it('should not close from pointer outside when maskClosable is false', () => {const onOpenChange = vi.fn();const onClose = vi.fn();diff --git a/packages/design/src/components/dialog/use-dialog-focus.ts b/packages/design/src/components/dialog/use-dialog-focus.tsnew file mode 100644index 0000000000..9b16ba43a4--- /dev/null+++ b/packages/design/src/components/dialog/use-dialog-focus.ts@@ -0,0 +1,62 @@+/**+ * 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 { useCallback, useRef } from 'react';++export function useDialogFocus(mask: boolean, onCloseAutoFocus?: (event: Event) => void) {+ const returnFocusRef = useRef<HTMLElement | null>(null);+ const contentRef = useRef<HTMLDivElement | null>(null);++ const handleContentRef = useCallback((node: HTMLDivElement | null) => {+ const previousContent = contentRef.current;+ contentRef.current = node;+ if (!node && previousContent && mask && !onCloseAutoFocus) {+ // Restore input after DOM removal, before FocusScope's deferred unmount timer.+ Promise.resolve().then(() => {+ const returnFocus = returnFocusRef.current;+ if (!contentRef.current && !previousContent.isConnected && returnFocus?.isConnected &&+ returnFocus.ownerDocument.activeElement === returnFocus.ownerDocument.body) {+ returnFocus.focus({ preventScroll: true });+ }+ });+ }+ }, [mask, onCloseAutoFocus]);++ function handleOpenAutoFocus() {+ const activeElement = document.activeElement;+ returnFocusRef.current = activeElement instanceof HTMLElement ? activeElement : null;+ }++ function handleCloseAutoFocus(event: Event) {+ const returnFocus = returnFocusRef.current;+ returnFocusRef.current = null;+ onCloseAutoFocus?.(event);+ if (event.defaultPrevented) {+ return;+ }+ if (mask && returnFocus?.isConnected) {+ // Controlled dialogs have no Radix Trigger to receive focus on close.+ event.preventDefault();+ const activeElement = returnFocus.ownerDocument.activeElement;+ const focusInClosingDialog = event.target instanceof HTMLElement && event.target.contains(activeElement);+ if (activeElement === returnFocus.ownerDocument.body || activeElement === returnFocus || focusInClosingDialog) {+ returnFocus.focus({ preventScroll: true });+ }+ }+ }++ return { handleContentRef, handleOpenAutoFocus, handleCloseAutoFocus };+}diff --git a/packages/design/src/components/dropdown-menu/DropdownMenuPrimitive.tsx b/packages/design/src/components/dropdown-menu/DropdownMenuPrimitive.tsxindex 01b69f51c5..9f06bb33af 100644--- a/packages/design/src/components/dropdown-menu/DropdownMenuPrimitive.tsx+++ b/packages/design/src/components/dropdown-menu/DropdownMenuPrimitive.tsx@@ -14,7 +14,7 @@* limitations under the License.*/-import type { ComponentProps } from 'react';+import type { ComponentProps, PointerEvent } from 'react';import {CheckboxItem,Content,@@ -33,9 +33,18 @@ import {Trigger,} from '@radix-ui/react-dropdown-menu';import { CheckMarkIcon, MoreRightIcon } from '@univerjs/icons';+import { useCallback, useRef } from 'react';import { borderClassName, scrollbarClassName } from '../../helper/class-utilities';import { clsx } from '../../helper/clsx';+function handleMenuPointerEvent<T extends HTMLElement>(event: PointerEvent<T>, handler?: (event: PointerEvent<T>) => void) {+ if (event.currentTarget.closest('[data-radix-menu-content]')?.getAttribute('data-state') === 'closed') {+ event.preventDefault();+ return;+ }+ handler?.(event);+}+function DropdownMenuPrimitive({...props}: ComponentProps<typeof Root>) {@@ -111,6 +120,8 @@ function DropdownMenuSubTrigger({className)}{...props}+ onPointerMove={(event) => handleMenuPointerEvent(event, props.onPointerMove)}+ onPointerLeave={(event) => handleMenuPointerEvent(event, props.onPointerLeave)}>{children}<MoreRightIcon className="ml-auto" />@@ -152,8 +163,26 @@ function DropdownMenuSubContent({function DropdownMenuContent({className,sideOffset = 4,+ ref,+ onPointerDownOutside,...props}: ComponentProps<typeof Content>) {+ const contentRef = useRef<HTMLDivElement>(null);+ const setContentRef = useCallback((node: HTMLDivElement | null) => {+ contentRef.current = node;+ if (typeof ref === 'function') {+ const cleanup = ref(node);+ if (typeof cleanup === 'function') {+ return () => {+ contentRef.current = null;+ cleanup();+ };+ }+ } else if (ref) {+ ref.current = node;+ }+ }, [ref]);+return (<Portal><Content@@ -179,6 +208,17 @@ function DropdownMenuContent({className)}{...props}+ ref={setContentRef}+ onPointerDownOutside={(event) => {+ onPointerDownOutside?.(event);+ const content = contentRef.current;+ const triggerId = content?.getAttribute('aria-labelledby');+ const trigger = triggerId ? content?.ownerDocument.getElementById(triggerId) : null;+ if (trigger?.contains(event.detail.originalEvent.target as Node)) {+ // The trigger already toggles this menu, including while its exit animation is running.+ event.preventDefault();+ }+ }}/></Portal>);@@ -215,6 +255,8 @@ function DropdownMenuItem({className)}{...props}+ onPointerMove={(event) => handleMenuPointerEvent(event, props.onPointerMove)}+ onPointerLeave={(event) => handleMenuPointerEvent(event, props.onPointerLeave)}/>);}@@ -245,6 +287,8 @@ function DropdownMenuCheckboxItem({)}checked={checked}{...props}+ onPointerMove={(event) => handleMenuPointerEvent(event, props.onPointerMove)}+ onPointerLeave={(event) => handleMenuPointerEvent(event, props.onPointerLeave)}>{!hideIndicator && (<span@@ -289,6 +333,8 @@ function DropdownMenuRadioItem({className)}{...props}+ onPointerMove={(event) => handleMenuPointerEvent(event, props.onPointerMove)}+ onPointerLeave={(event) => handleMenuPointerEvent(event, props.onPointerLeave)}>{!hideIndicator && (<spandiff --git a/packages/design/src/components/dropdown-menu/__tests__/DropdownMenuPrimitive.spec.tsx b/packages/design/src/components/dropdown-menu/__tests__/DropdownMenuPrimitive.spec.tsxnew file mode 100644index 0000000000..81519fc8f0--- /dev/null+++ b/packages/design/src/components/dropdown-menu/__tests__/DropdownMenuPrimitive.spec.tsx@@ -0,0 +1,177 @@+/**+ * 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 { Content, Portal } from '@radix-ui/react-dropdown-menu';+import { act, cleanup, createEvent, fireEvent, render, screen } from '@testing-library/react';+import { createRef } from 'react';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuItem, DropdownMenuPrimitive, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSub, DropdownMenuSubTrigger, DropdownMenuTrigger } from '../DropdownMenuPrimitive';+import '@testing-library/jest-dom/vitest';++afterEach(cleanup);++describe('dropdown trigger ownership', () => {+ it('reopens on its trigger before the closing animation finishes', async () => {+ const getComputedStyle = window.getComputedStyle.bind(window);+ const styleSpy = vi.spyOn(window, 'getComputedStyle').mockImplementation((element, pseudoElement) => {+ const styles = getComputedStyle(element, pseudoElement);+ if (element.getAttribute('data-slot') !== 'dropdown-menu-content') {+ return styles;+ }+ // Presence needs the browser's live animation style, which the test DOM does not animate.+ return new Proxy(styles, {+ get(target, property) {+ if (property === 'animationName') {+ return element.getAttribute('data-state') === 'closed' ? 'menu-exit' : 'none';+ }+ return Reflect.get(target, property);+ },+ });+ });+ try {+ render(+ <DropdownMenuPrimitive defaultOpen modal={false}>+ <DropdownMenuTrigger>Open</DropdownMenuTrigger>+ <DropdownMenuContent><DropdownMenuItem>Action</DropdownMenuItem></DropdownMenuContent>+ </DropdownMenuPrimitive>+ );+ const trigger = screen.getByRole('button', { name: 'Open' });+ for (const open of [false, true]) {+ await act(async () => new Promise((resolve) => setTimeout(resolve, 0)));+ const event = createEvent.pointerDown(trigger, { bubbles: true, cancelable: true });+ Object.defineProperties(event, { button: { value: 0 }, pointerType: { value: 'mouse' }, ctrlKey: { value: false } });+ fireEvent(trigger, event);+ expect(trigger).toHaveAttribute('aria-expanded', String(open));+ expect(screen.getByText('Action').closest('[data-radix-menu-content]')).toHaveAttribute('data-state', open ? 'open' : 'closed');+ }+ } finally {+ cleanup();+ styleSpy.mockRestore();+ }+ });++ it('opens and closes on its own trigger', async () => {+ render(+ <DropdownMenuPrimitive modal={false}>+ <DropdownMenuTrigger><span>Open</span></DropdownMenuTrigger>+ <DropdownMenuContent>+ <DropdownMenuItem>Action</DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenuPrimitive>+ );+ // DismissableLayer installs its document pointer listener on the next task.+ await act(async () => new Promise((resolve) => setTimeout(resolve, 0)));+ const event = createEvent.pointerDown(screen.getByText('Open'), { bubbles: true, cancelable: true });+ Object.defineProperties(event, { button: { value: 0 }, pointerType: { value: 'mouse' }, ctrlKey: { value: false } });+ fireEvent(screen.getByText('Open'), event);+ expect(screen.getByRole('button', { name: 'Open' })).toHaveAttribute('aria-expanded', 'true');+ await act(async () => new Promise((resolve) => setTimeout(resolve, 0)));+ const closeEvent = createEvent.pointerDown(screen.getByText('Open'), { bubbles: true, cancelable: true });+ Object.defineProperties(closeEvent, { button: { value: 0 }, pointerType: { value: 'mouse' }, ctrlKey: { value: false } });+ fireEvent(screen.getByText('Open'), closeEvent);+ expect(screen.getByRole('button', { name: 'Open' })).toHaveAttribute('aria-expanded', 'false');+ });++ it('closes for another trigger or outside target and preserves the outside callback', async () => {+ const onOutside = vi.fn();+ render(+ <>+ <button>Outside</button>+ {['First', 'Second'].map((name) => (+ <DropdownMenuPrimitive key={name} modal={false}>+ <DropdownMenuTrigger>{name}</DropdownMenuTrigger>+ <DropdownMenuContent onPointerDownOutside={onOutside}>+ <DropdownMenuItem>+ {name}+ {' '}+ action+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenuPrimitive>+ ))}+ </>+ );+ await act(async () => new Promise((resolve) => setTimeout(resolve, 0)));+ for (const name of ['First', 'Second', 'Outside']) {+ const button = screen.getByRole('button', { name });+ const event = createEvent.pointerDown(button, { bubbles: true, cancelable: true });+ Object.defineProperties(event, { button: { value: 0 }, pointerType: { value: 'mouse' }, ctrlKey: { value: false } });+ fireEvent(button, event);+ await act(async () => new Promise((resolve) => setTimeout(resolve, 0)));+ expect(screen.getByRole('button', { name: 'First' })).toHaveAttribute('aria-expanded', String(name === 'First'));+ expect(screen.getByRole('button', { name: 'Second' })).toHaveAttribute('aria-expanded', String(name === 'Second'));+ }+ expect(onOutside).toHaveBeenCalled();+ });++ it('forwards the mounted content and clears an object ref on unmount', () => {+ const ref = createRef<HTMLDivElement>();+ const { unmount } = render(+ <DropdownMenuPrimitive defaultOpen modal={false}>+ <DropdownMenuTrigger>Open</DropdownMenuTrigger>+ <DropdownMenuContent ref={ref}><DropdownMenuItem>Action</DropdownMenuItem></DropdownMenuContent>+ </DropdownMenuPrimitive>+ );+ expect(ref.current).toBe(screen.getByRole('menu'));+ unmount();+ expect(ref.current).toBeNull();+ });++ it('preserves callback ref cleanup', () => {+ const cleanupRef = vi.fn();+ const ref = vi.fn(() => cleanupRef);+ const { unmount } = render(+ <DropdownMenuPrimitive defaultOpen modal={false}>+ <DropdownMenuTrigger>Open</DropdownMenuTrigger>+ <DropdownMenuContent ref={ref}><DropdownMenuItem>Action</DropdownMenuItem></DropdownMenuContent>+ </DropdownMenuPrimitive>+ );+ expect(ref).toHaveBeenCalledWith(screen.getByRole('menu'));+ unmount();+ expect(cleanupRef).toHaveBeenCalledOnce();+ });+});++describe.each([+ ['normal', <DropdownMenuItem key="normal">Action</DropdownMenuItem>],+ ['checkbox', <DropdownMenuCheckboxItem key="checkbox">Action</DropdownMenuCheckboxItem>],+ ['radio', <DropdownMenuRadioGroup key="radio" value="a"><DropdownMenuRadioItem value="a">Action</DropdownMenuRadioItem></DropdownMenuRadioGroup>],+ ['submenu', <DropdownMenuSub key="submenu"><DropdownMenuSubTrigger>Action</DropdownMenuSubTrigger></DropdownMenuSub>],+])('closed %s dropdown pointer ownership', (_name, content) => {+ it.each(['pointerMove', 'pointerOut'] as const)('does not reclaim focus on %s while retained for exit', (eventType) => {+ render(+ <>+ <input aria-label="External" />+ <DropdownMenuPrimitive open={false} modal={false}>+ <DropdownMenuTrigger>Open</DropdownMenuTrigger>+ <Portal forceMount>+ <Content forceMount>+ {content}+ </Content>+ </Portal>+ </DropdownMenuPrimitive>+ </>+ );+ const external = screen.getByRole('textbox');+ const item = screen.getByText('Action');+ expect(item.closest('[data-radix-menu-content]')).toHaveAttribute('data-state', 'closed');+ external.focus();+ const event = createEvent[eventType](item, { bubbles: true, cancelable: true, relatedTarget: external });+ Object.defineProperty(event, 'pointerType', { value: 'mouse' });+ fireEvent(item, event);+ expect(external).toHaveFocus();+ });+});diff --git a/packages/design/src/components/tooltip/__tests__/index.spec.tsx b/packages/design/src/components/tooltip/__tests__/index.spec.tsxindex 574730c874..070bf6c052 100644--- a/packages/design/src/components/tooltip/__tests__/index.spec.tsx+++ b/packages/design/src/components/tooltip/__tests__/index.spec.tsx@@ -187,6 +187,27 @@ describe('Tooltip', () => {});});+ it('allows callers to make tooltip content pointer-transparent through className', async () => {+ render(+ <Tooltip title="pass-through-tip">+ interactive-trigger+ </Tooltip>+ );+ fireEvent.mouseEnter(screen.getByText('interactive-trigger'));+ expect(await screen.findByRole('tooltip')).toHaveClass('univer-pointer-events-auto');++ cleanup();+ render(+ <Tooltip title="pass-through-tip" className="univer-pointer-events-none">+ pass-through-trigger+ </Tooltip>+ );+ fireEvent.mouseEnter(screen.getByText('pass-through-trigger'));+ const tooltip = await screen.findByRole('tooltip');+ expect(tooltip).toHaveClass('univer-pointer-events-none');+ expect(tooltip).not.toHaveClass('univer-pointer-events-auto');+ });+it('should execute left-placement recompute branch on scroll', async () => {vi.restoreAllMocks();vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function getRect(this: HTMLElement) {diff --git a/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts b/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.tsindex ba05f27237..9227a3c257 100644--- a/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts+++ b/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts@@ -296,6 +296,7 @@ class TestDocDrawingUpdateRenderController {function setupDrawingTestBed(docData: IDocumentData, dependencies: Dependency[] = []) {const refreshControls = vi.fn();+ const focusSelection = vi.fn();const testBed = createDocUiTestBed(docData, [[IRenderManagerService, { useClass: RenderManagerService }],...dependencies,@@ -328,6 +329,7 @@ function setupDrawingTestBed(docData: IDocumentData, dependencies: Dependency[]setSegment: (segmentId: string) => currentSegment = segmentId,getSegmentPage: () => currentSegmentPage,setSegmentPage: (page: number) => currentSegmentPage = page,+ focus: focusSelection,} as T;}@@ -380,6 +382,7 @@ function setupDrawingTestBed(docData: IDocumentData, dependencies: Dependency[]docDrawingService: injector.get(IDocDrawingService),drawingManagerService: injector.get(IDrawingManagerService),refreshControls,+ focusSelection,};}@@ -621,6 +624,7 @@ describe('docs drawing commands integration', () => {expect(doc.getSnapshot().drawingsOrder).toEqual([]);expect(testBed.docDrawingService.getDrawingByParam({ unitId: 'test-doc', subUnitId: 'test-doc', drawingId: 'shape-1' })).toBeUndefined();expect(testBed.drawingManagerService.getDrawingByParam({ unitId: 'test-doc', subUnitId: 'test-doc', drawingId: 'shape-1' })).toBeUndefined();+ expect(testBed.focusSelection).toHaveBeenCalledTimes(2);testBed.univer.dispose();});diff --git a/packages/docs-drawing-ui/src/commands/commands/delete-doc-drawing.command.ts b/packages/docs-drawing-ui/src/commands/commands/delete-doc-drawing.command.tsindex 52ed64ac02..181d59775b 100644--- a/packages/docs-drawing-ui/src/commands/commands/delete-doc-drawing.command.ts+++ b/packages/docs-drawing-ui/src/commands/commands/delete-doc-drawing.command.ts@@ -18,11 +18,13 @@ import type { IAccessor, ICommand } from '@univerjs/core';import type { IDocDrawing, IRemoveDocDrawingCommandParams } from '@univerjs/docs-drawing';import { CommandType, ICommandService } from '@univerjs/core';import { IDocDrawingService, RemoveDocDrawingCommand } from '@univerjs/docs-drawing';+import { DocSelectionRenderService } from '@univerjs/docs-ui';+import { IRenderManagerService } from '@univerjs/engine-render';export const DeleteDocDrawingsCommand: ICommand = {id: 'doc.command.delete-drawing',type: CommandType.COMMAND,- handler: (accessor: IAccessor) => {+ handler: async (accessor: IAccessor) => {const commandService = accessor.get(ICommandService);const docDrawingService = accessor.get(IDocDrawingService);@@ -33,6 +35,12 @@ export const DeleteDocDrawingsCommand: ICommand = {}const { unitId } = drawings[0];+ const selectionRenderService = accessor.get(IRenderManagerService)+ .getRenderUnitById(unitId)+ ?.with(DocSelectionRenderService);++ // Keep the command and the immediately following shortcut on the document that owns the drawing.+ selectionRenderService?.focus();const newDrawings = drawings.map((drawing) => {const { unitId, subUnitId, drawingId, drawingType } = drawing as IDocDrawing;@@ -44,9 +52,13 @@ export const DeleteDocDrawingsCommand: ICommand = {drawingType,};});- return commandService.executeCommand<IRemoveDocDrawingCommandParams>(RemoveDocDrawingCommand.id, {+ const removed = await commandService.executeCommand<IRemoveDocDrawingCommandParams>(RemoveDocDrawingCommand.id, {unitId,drawings: newDrawings,});+ if (removed) {+ selectionRenderService?.focus();+ }+ return removed;},};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 ba25226091..2fd329d4cb 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@@ -2333,6 +2333,44 @@ describe('misc document commands', () => {expect(get(DocIMEInputManagerService).getUndoRedoMutationParamsCache().redoCache[0].noHistory).toBe(true);});+ it('restores selected text when an IME composition is canceled', async () => {+ ({ univer, get } = createCommandTestBed(createBaseDoc('Hello\r\n')));+ commandService = get(ICommandService);+ commandService.registerCommand(IMEInputCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);++ const imeInputManagerService = get(DocIMEInputManagerService);+ const activeRange = {+ startOffset: 1,+ endOffset: 4,+ collapsed: false,+ segmentId: '',+ };+ imeInputManagerService.setActiveRange(activeRange);+ imeInputManagerService.setPreviousDocRanges([activeRange]);++ expect(await commandService.executeCommand(IMEInputCommand.id, {+ unitId: 'test-doc',+ newText: 'nihao',+ oldTextLen: 0,+ isCompositionStart: true,+ isCompositionEnd: false,+ })).toBe(true);+ expect(getBody()?.dataStream).toBe('Hnihaoo\r\n');++ expect(await commandService.executeCommand(IMEInputCommand.id, {+ unitId: 'test-doc',+ newText: '',+ oldTextLen: 5,+ isCompositionStart: false,+ isCompositionEnd: true,+ isCompositionCanceled: true,+ })).toBe(true);+ await awaitTime(0);++ expect(getBody()?.dataStream).toBe('Hello\r\n');+ });+it('opens the create-table confirm flow and forwards the confirmed size to the table command', async () => {({ univer, get } = createCommandTestBed(createBaseDoc(), [[IConfirmService, { useClass: TestConfirmService }],diff --git a/packages/docs-ui/src/commands/commands/break-line.command.ts b/packages/docs-ui/src/commands/commands/break-line.command.tsindex fb6ddafe3d..24bb1a450e 100644--- a/packages/docs-ui/src/commands/commands/break-line.command.ts+++ b/packages/docs-ui/src/commands/commands/break-line.command.ts@@ -32,6 +32,7 @@ interface IBreakLineCommandParams {horizontalLine?: IParagraphBorder;insertionMode?: BreakLineInsertionMode;textRange?: ITextRangeParam;+ unitId?: string;}export const BreakLineCommand: ICommand<IBreakLineCommandParams> = {@@ -45,8 +46,14 @@ export const BreakLineCommand: ICommand<IBreakLineCommandParams> = {const univerInstanceService = accessor.get(IUniverInstanceService);const commandService = accessor.get(ICommandService);const docMenuStyleService = accessor.get(DocMenuStyleService);- const activeTextRange = params?.textRange ?? docSelectionManagerService.getActiveTextRange();- const rectRanges = docSelectionManagerService.getRectRanges();+ const selectionParams = params?.unitId+ ? { unitId: params.unitId, subUnitId: params.unitId }+ : undefined;+ const targetTextRanges = docSelectionManagerService.getTextRanges(selectionParams) ?? [];+ const activeTextRange = params?.textRange ?? (selectionParams+ ? targetTextRanges.find((range) => range.isActive)+ : docSelectionManagerService.getActiveTextRange());+ const rectRanges = docSelectionManagerService.getRectRanges(selectionParams);if (activeTextRange == null) {return false;}@@ -58,14 +65,16 @@ export const BreakLineCommand: ICommand<IBreakLineCommandParams> = {docSelectionManagerService.replaceDocRanges([{startOffset,endOffset: startOffset,- }]);+ }], selectionParams);return true;}const { horizontalLine, insertionMode = BreakLineInsertionMode.SplitParagraph } = params ?? {};const { segmentId } = activeTextRange;- const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);+ const docDataModel = params?.unitId+ ? univerInstanceService.getUnit<DocumentDataModel>(params.unitId, UniverInstanceType.UNIVER_DOC)+ : univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);const originBody = docDataModel?.getSelfOrHeaderFooterModel(segmentId ?? '')?.getBody();if (docDataModel == null || originBody == null) {@@ -112,7 +121,9 @@ export const BreakLineCommand: ICommand<IBreakLineCommandParams> = {return false;}- const activeRange = docSelectionManagerService.getActiveTextRange();+ const activeRange = selectionParams+ ? targetTextRanges.find((range) => range.isActive)+ : docSelectionManagerService.getActiveTextRange();if (originBody == null) {return false;diff --git a/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts b/packages/docs-ui/src/commands/commands/clipboard.inner.command.tsindex 926af5215d..7b76593f2a 100644--- a/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts+++ b/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts@@ -57,6 +57,7 @@ function hasRangeInTable(ranges: readonly ITextRangeWithStyle[]): boolean {}export interface IInnerPasteCommandParams {+ unitId?: string;segmentId: string;doc: Partial<IDocumentData>;textRanges: ITextRangeWithStyle[];@@ -76,22 +77,32 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {segmentId,textRanges,doc,+ unitId: targetUnitId,} = params;const commandService = accessor.get(ICommandService);const undoRedoService = accessor.get(IUndoRedoService);const docSelectionManagerService = accessor.get(DocSelectionManagerService);const univerInstanceService = accessor.get(IUniverInstanceService);const pasteAdapterService = getPasteAdapterService(accessor);- const selections = docSelectionManagerService.getTextRanges() ?? [];- const rectRanges = docSelectionManagerService.getRectRanges() ?? [];- const selectionInfo = docSelectionManagerService.getSelectionInfo();+ const currentSelection = docSelectionManagerService.__getCurrentSelection();+ let selectionParams;+ if (targetUnitId) {+ selectionParams = currentSelection?.unitId === targetUnitId+ ? currentSelection+ : { unitId: targetUnitId, subUnitId: targetUnitId };+ }+ const selections = docSelectionManagerService.getTextRanges(selectionParams) ?? [];+ const rectRanges = docSelectionManagerService.getRectRanges(selectionParams) ?? [];+ const selectionInfo = docSelectionManagerService.getSelectionInfo(selectionParams);const { body: sourceBody, tableSource, drawings } = doc;let body = sourceBody;if ((selections.length === 0 && rectRanges.length === 0) || body == null) {return false;}- const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);+ const docDataModel = targetUnitId+ ? univerInstanceService.getUnit<DocumentDataModel>(targetUnitId, UniverInstanceType.UNIVER_DOC)+ : univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);const originBody = docDataModel?.getSelfOrHeaderFooterModel(segmentId)?.getBody();if (docDataModel == null || originBody == null) {return false;@@ -828,6 +839,7 @@ export function getDocRangeInsertOffset(}export interface IInnerCutCommandParams {+ unitId?: string;segmentId: string;textRanges: ITextRangeWithStyle[];selections?: ITextRange[];@@ -845,12 +857,20 @@ export const CutContentCommand: ICommand<IInnerCutCommandParams> = {const commandService = accessor.get(ICommandService);const univerInstanceService = accessor.get(IUniverInstanceService);- const selectionInfo = docSelectionManagerService.getSelectionInfo();+ const targetUnitId = params.unitId;+ const currentSelection = docSelectionManagerService.__getCurrentSelection();+ let selectionParams;+ if (targetUnitId) {+ selectionParams = currentSelection?.unitId === targetUnitId+ ? currentSelection+ : { unitId: targetUnitId, subUnitId: targetUnitId };+ }+ const selectionInfo = docSelectionManagerService.getSelectionInfo(selectionParams);const {segmentId,textRanges,- selections = docSelectionManagerService.getTextRanges(),- rectRanges = docSelectionManagerService.getRectRanges(),+ selections = docSelectionManagerService.getTextRanges(selectionParams),+ rectRanges = docSelectionManagerService.getRectRanges(selectionParams),wholeBodySelected = selectionInfo?.options?.wholeDocument === true,} = params;@@ -861,7 +881,9 @@ export const CutContentCommand: ICommand<IInnerCutCommandParams> = {return false;}- const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);+ const docDataModel = targetUnitId+ ? univerInstanceService.getUnit<DocumentDataModel>(targetUnitId, UniverInstanceType.UNIVER_DOC)+ : univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);if (docDataModel == null) {return false;}diff --git a/packages/docs-ui/src/commands/commands/ime-input.command.ts b/packages/docs-ui/src/commands/commands/ime-input.command.tsindex 8cbe73be7d..de9d0b73a2 100644--- a/packages/docs-ui/src/commands/commands/ime-input.command.ts+++ b/packages/docs-ui/src/commands/commands/ime-input.command.ts@@ -31,6 +31,7 @@ export interface IIMEInputCommandParams {oldTextLen: number;isCompositionStart: boolean;isCompositionEnd: boolean;+ isCompositionCanceled?: boolean;}export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {@@ -40,7 +41,7 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {// eslint-disable-next-line max-lines-per-functionhandler: async (accessor, params: IIMEInputCommandParams) => {- const { unitId, newText, oldTextLen, isCompositionEnd, isCompositionStart } = params;+ const { unitId, newText, oldTextLen, isCompositionEnd, isCompositionStart, isCompositionCanceled } = params;const commandService = accessor.get(ICommandService);const renderManagerService = accessor.get(IRenderManagerService);const univerInstanceService = accessor.get(IUniverInstanceService);@@ -58,6 +59,32 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {return false;}+ if (isCompositionCanceled) {+ const historyParams = imeInputManagerService.fetchComposedUndoRedoMutationParams();+ if (historyParams == null) {+ return true;+ }++ const {+ undoMutationParams,+ previousActiveRange,+ previousDocRanges,+ previousSelectionOptions,+ } = historyParams;+ const rollbackMutationParams: IRichTextEditingMutationParams = {+ ...undoMutationParams,+ textRanges: previousDocRanges.length ? previousDocRanges : [previousActiveRange],+ options: previousSelectionOptions ?? undefined,+ noHistory: true,+ trigger: IMEInputCommand.id,+ };++ return Boolean(commandService.syncExecuteCommand<+ IRichTextEditingMutationParams,+ IRichTextEditingMutationParams+ >(RichTextEditingMutation.id, rollbackMutationParams));+ }+const { style, segmentId } = previousActiveRange;const body = docDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody();diff --git a/packages/docs-ui/src/controllers/__tests__/doc-ime-input.controller.spec.ts b/packages/docs-ui/src/controllers/__tests__/doc-ime-input.controller.spec.tsindex 280b0fd35a..8413f41f6b 100644--- a/packages/docs-ui/src/controllers/__tests__/doc-ime-input.controller.spec.ts+++ b/packages/docs-ui/src/controllers/__tests__/doc-ime-input.controller.spec.ts@@ -31,13 +31,19 @@ function createRange() {};}+interface ITestEditorInputConfig {+ activeRange: ReturnType<typeof createRange>;+ event?: { data: string };+ rangeList?: ReturnType<typeof createRange>[];+}+describe('doc ime input controller', () => {it('skips duplicate writes when compositionend data matches the last update', async () => {- const onCompositionstart$ = new Subject<any>();- const onCompositionupdate$ = new Subject<any>();- const onCompositionend$ = new Subject<any>();+ const onCompositionstart$ = new Subject<ITestEditorInputConfig>();+ const onCompositionupdate$ = new Subject<ITestEditorInputConfig>();+ const onCompositionend$ = new Subject<ITestEditorInputConfig>();const activeRange = createRange();- let storedActiveRange: any = null;+ let storedActiveRange: ReturnType<typeof createRange> | null = null;const docSelectionRenderService = {onCompositionstart$,@@ -66,7 +72,7 @@ describe('doc ime input controller', () => {getSelectionInfo: vi.fn(() => ({ options: null })),};- new DocIMEInputController(+ const controller = new DocIMEInputController({unitId: 'doc-unit',} as never,@@ -119,14 +125,15 @@ describe('doc ime input controller', () => {});expect(docImeInputManagerService.clearUndoRedoMutationParamsCache).toHaveBeenCalledTimes(2);expect(docImeInputManagerService.setActiveRange).toHaveBeenLastCalledWith(null);+ controller.dispose();});it('keeps the compositionend write when the final data differs from the latest update', async () => {- const onCompositionstart$ = new Subject<any>();- const onCompositionupdate$ = new Subject<any>();- const onCompositionend$ = new Subject<any>();+ const onCompositionstart$ = new Subject<ITestEditorInputConfig>();+ const onCompositionupdate$ = new Subject<ITestEditorInputConfig>();+ const onCompositionend$ = new Subject<ITestEditorInputConfig>();const activeRange = createRange();- let storedActiveRange: any = null;+ let storedActiveRange: ReturnType<typeof createRange> | null = null;const docSelectionRenderService = {onCompositionstart$,@@ -155,7 +162,7 @@ describe('doc ime input controller', () => {getSelectionInfo: vi.fn(() => ({ options: null })),};- new DocIMEInputController(+ const controller = new DocIMEInputController({unitId: 'doc-unit',} as never,@@ -192,5 +199,111 @@ describe('doc ime input controller', () => {isCompositionEnd: true,});expect(docStateEmitService.emitStateChangeInfo).not.toHaveBeenCalled();+ controller.dispose();+ });++ it('rolls back an active composition when compositionend data is empty', async () => {+ const onCompositionstart$ = new Subject<ITestEditorInputConfig>();+ const onCompositionupdate$ = new Subject<ITestEditorInputConfig>();+ const onCompositionend$ = new Subject<ITestEditorInputConfig>();+ const activeRange = createRange();++ const docSelectionRenderService = {+ onCompositionstart$,+ onCompositionupdate$,+ onCompositionend$,+ getAllRectRanges: vi.fn(() => []),+ };+ const docImeInputManagerService = {+ setActiveRange: vi.fn(),+ getActiveRange: vi.fn(() => activeRange),+ getPreviousDocRanges: vi.fn(() => []),+ getPreviousSelectionOptions: vi.fn(() => null),+ setPreviousDocRanges: vi.fn(),+ setPreviousSelectionOptions: vi.fn(),+ clearUndoRedoMutationParamsCache: vi.fn(),+ };+ const commandService = {+ executeCommand: vi.fn(() => Promise.resolve(true)),+ };+ const docStateEmitService = {+ emitStateChangeInfo: vi.fn(),+ };++ const controller = new DocIMEInputController(+ { unitId: 'doc-unit' } as never,+ docSelectionRenderService as never,+ docImeInputManagerService as never,+ { getSkeleton: vi.fn(() => ({})) } as never,+ docStateEmitService as never,+ { getSelectionInfo: vi.fn(() => ({ options: null })) } as never,+ commandService as never+ );++ onCompositionstart$.next({ activeRange });+ onCompositionupdate$.next({ event: { data: 'nihao' }, activeRange });+ await awaitTime(0);+ onCompositionupdate$.next({ event: { data: '' }, activeRange });+ await awaitTime(0);+ onCompositionend$.next({ event: { data: '' }, activeRange });+ await awaitTime(0);++ expect(commandService.executeCommand).toHaveBeenCalledTimes(2);+ expect(commandService.executeCommand).toHaveBeenNthCalledWith(2, IMEInputCommand.id, {+ unitId: 'doc-unit',+ newText: '',+ oldTextLen: 5,+ isCompositionStart: false,+ isCompositionEnd: true,+ isCompositionCanceled: true,+ });+ expect(docStateEmitService.emitStateChangeInfo).not.toHaveBeenCalled();+ expect(docImeInputManagerService.clearUndoRedoMutationParamsCache).toHaveBeenCalledTimes(2);+ expect(docImeInputManagerService.setActiveRange).toHaveBeenLastCalledWith(null);+ controller.dispose();+ });++ it('ends an empty composition without creating a history entry', async () => {+ const onCompositionstart$ = new Subject<ITestEditorInputConfig>();+ const onCompositionupdate$ = new Subject<ITestEditorInputConfig>();+ const onCompositionend$ = new Subject<ITestEditorInputConfig>();+ const activeRange = createRange();+ const commandService = {+ executeCommand: vi.fn(() => Promise.resolve(true)),+ };+ const docStateEmitService = {+ emitStateChangeInfo: vi.fn(),+ };++ const controller = new DocIMEInputController(+ { unitId: 'doc-unit' } as never,+ {+ onCompositionstart$,+ onCompositionupdate$,+ onCompositionend$,+ getAllRectRanges: vi.fn(() => []),+ } as never,+ {+ setActiveRange: vi.fn(),+ getActiveRange: vi.fn(() => activeRange),+ getPreviousDocRanges: vi.fn(() => []),+ getPreviousSelectionOptions: vi.fn(() => null),+ setPreviousDocRanges: vi.fn(),+ setPreviousSelectionOptions: vi.fn(),+ clearUndoRedoMutationParamsCache: vi.fn(),+ } as never,+ { getSkeleton: vi.fn(() => ({})) } as never,+ docStateEmitService as never,+ { getSelectionInfo: vi.fn(() => ({ options: null })) } as never,+ commandService as never+ );++ onCompositionstart$.next({ activeRange });+ onCompositionend$.next({ event: { data: '' }, activeRange });+ await awaitTime(0);++ expect(commandService.executeCommand).not.toHaveBeenCalled();+ expect(docStateEmitService.emitStateChangeInfo).not.toHaveBeenCalled();+ controller.dispose();});});diff --git a/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts b/packages/docs-ui/src/controllers/doc-move-cursor.controller.tsindex a1b7d74da6..8a3594b200 100644--- a/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts+++ b/packages/docs-ui/src/controllers/doc-move-cursor.controller.ts@@ -239,6 +239,19 @@ export class DocMoveCursorController extends Disposable {// 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));+ const normalizedFocusOffset = this._normalizeRenderableCursorOffset(+ skeleton,+ body.dataStream,+ customRanges,+ focusOffset,+ direction,+ normalizedSegmentId,+ normalizedSegmentPage+ );+ if (normalizedFocusOffset == null) {+ return;+ }+ focusOffset = normalizedFocusOffset;this._textSelectionManagerService.replaceDocRanges([{diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-clipboard.controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-clipboard.controller.spec.tsindex db18ce6082..28f5ba42b1 100644--- a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-clipboard.controller.spec.ts+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-clipboard.controller.spec.ts@@ -43,8 +43,8 @@ function createClipboardEvent(options: {}function createController(options?: { focusingDoc?: boolean; editorActivated?: boolean; editorExists?: boolean }) {- const onPaste$ = new Subject<any>();- const legacyPaste = vi.fn();+ const onPaste$ = new Subject<{ event: ReturnType<typeof createClipboardEvent> }>();+ const legacyPaste = vi.fn(() => Promise.resolve(true));const controller = new DocClipboardController({ unitId: 'doc-1' } as never,{} as never,@@ -85,6 +85,7 @@ describe('DocClipboardController', () => {internalJson: '{"body":true}',text: 'Hello',files: [imageFile],+ unitId: 'doc-1',});controller.dispose();diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-clipboard.controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc-clipboard.controller.tsindex 1a5f2b954b..192bbac4d6 100644--- a/packages/docs-ui/src/controllers/render-controllers/doc-clipboard.controller.ts+++ b/packages/docs-ui/src/controllers/render-controllers/doc-clipboard.controller.ts@@ -79,7 +79,13 @@ export class DocClipboardController extends RxDisposable implements IRenderModulhtmlContent = '';}- this._docClipboardService.legacyPaste({ html: htmlContent, internalJson, text: textContent, files });+ this._docClipboardService.legacyPaste({+ html: htmlContent,+ internalJson,+ text: textContent,+ files,+ unitId: this._context.unitId,+ }).catch(() => undefined);});}}diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-ime-input.controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc-ime-input.controller.tsindex 3c9e96bdca..6d8e4a9cf2 100644--- a/packages/docs-ui/src/controllers/render-controllers/doc-ime-input.controller.ts+++ b/packages/docs-ui/src/controllers/render-controllers/doc-ime-input.controller.ts@@ -124,6 +124,25 @@ export class DocIMEInputController extends Disposable implements IRenderModule {const content = e.data;+ if (isUpdate && content === '') {+ return;+ }++ if (!isUpdate && content === '') {+ if (this._previousIMEContent !== '') {+ await this._commandService.executeCommand(IMEInputCommand.id, {+ unitId,+ newText: '',+ oldTextLen: this._previousIMEContent.length,+ isCompositionStart: false,+ isCompositionEnd: true,+ isCompositionCanceled: true,+ });+ }+ this._resetIME();+ return;+ }+if (content === this._previousIMEContent && isUpdate) {return;}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 ce9d7d159e..e34eb125f3 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@@ -25,6 +25,8 @@ import type {import type { ISetDocZoomRatioOperationParams } from '../../commands/operations/set-doc-zoom-ratio.operation';import {Disposable,+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,ICommandService,Inject,isInternalEditorID,@@ -160,7 +162,8 @@ export class DocSelectionRenderController extends Disposable implements IRenderMthis._instanceSrv.setCurrentUnitForType(unitId);}// Host-owned editors need the current Doc unit for editing commands without replacing the host's global focus.- if (!this._editorService.getEditorRenderConfig(unitId)?.preserveHostFocus) {+ const isSheetEditor = unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY || unitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY;+ if (!isSheetEditor && !this._editorService.getEditorRenderConfig(unitId)?.preserveHostFocus) {this._instanceSrv.focusUnit(unitId);}diff --git a/packages/docs-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts b/packages/docs-ui/src/services/clipboard/__tests__/clipboard.service.spec.tsindex 8bd102c6a7..88059a5cbd 100644--- a/packages/docs-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts+++ b/packages/docs-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts@@ -26,7 +26,10 @@ import {ImageSourceType,IPermissionService,IUniverInstanceService,+ RedoCommand,SliceBodyType,+ Tools,+ UndoCommand,UniverInstanceType,validateDocBodyStructure,} from '@univerjs/core';@@ -282,6 +285,123 @@ describe('DocClipboardService table copy helpers', () => {testBed.univer.dispose();});+ it.each([5, 6])('pastes copied text with or without its paragraph mark and preserves history (end=%i)', async (endOffset) => {+ const documentData: IDocumentData = {+ id: 'partial-paragraph-paste',+ body: {+ dataStream: 'Alpha\rBeta\r\n',+ paragraphs: [+ { startIndex: 5, paragraphId: 'source-paragraph', paragraphStyle: { spaceAbove: { v: 12 } } },+ { startIndex: 10, paragraphId: 'target-paragraph', paragraphStyle: { spaceAbove: { v: 3 } } },+ ],+ textRuns: [{ st: 0, ed: 5, ts: { bl: BooleanNumber.TRUE } }],+ },+ documentStyle: {},+ };+ const testBed = createCommandTestBed(documentData, [+ [IClipboardInterfaceService, { useClass: TestClipboardInterfaceService }],+ [IDocClipboardService, { useClass: DocClipboardService }],+ ]);+ try {+ const commandService = testBed.get(ICommandService);+ [InnerPasteCommand, RichTextEditingMutation, SetTextSelectionsOperation]+ .forEach((command) => commandService.registerCommand(command));+ const selectionManager = testBed.get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: documentData.id, subUnitId: '' });+ selectionManager.__TEST_ONLY_add([{+ startOffset: 0,+ endOffset,+ collapsed: false,+ isActive: true,+ segmentId: '',+ }]);+ const service = testBed.get(IDocClipboardService);+ expect(await service.copy()).toBe(true);+ const clipboard = testBed.get(IClipboardInterfaceService) as unknown as TestClipboardInterfaceService;+ const copied = clipboard.writes[0];+ const model = testBed.get(IUniverInstanceService).getUnit<DocumentDataModel>(documentData.id)!;+ const readContent = () => {+ const body = model.getBody()!;+ return Tools.deepClone({+ dataStream: body.dataStream,+ textRuns: body.textRuns,+ paragraphs: body.paragraphs?.map(({ paragraphId, ...paragraph }) => paragraph),+ });+ };+ const before = Tools.deepClone(model.getBody());+ const beforeContent = readContent();+ selectionManager.__TEST_ONLY_add([{+ startOffset: 7,+ endOffset: 7,+ collapsed: true,+ isActive: true,+ segmentId: '',+ }]);+ expect(await service.legacyPaste({ html: copied.html, text: copied.text, files: [] })).toBe(true);+ const after = Tools.deepClone(model.getBody())!;+ expect(after.dataStream).toBe(`Alpha\rB${'Alpha\r'.slice(0, endOffset)}eta\r\n`);+ expect(validateDocBodyStructure(after)).toEqual([]);+ expect(after.textRuns).toContainEqual(expect.objectContaining({ st: 7, ed: 12, ts: { bl: BooleanNumber.TRUE } }));+ expect(after.paragraphs?.find((paragraph) => paragraph.startIndex === 10 + endOffset)?.paragraphStyle)+ .toEqual(before?.paragraphs?.[1].paragraphStyle);+ const afterContent = readContent();+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);+ expect(readContent()).toEqual(beforeContent);+ expect(validateDocBodyStructure(model.getBody()!)).toEqual([]);+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);+ expect(readContent()).toEqual(afterContent);+ expect(validateDocBodyStructure(model.getBody()!)).toEqual([]);+ } finally {+ testBed.univer.dispose();+ }+ });++ it.each([SliceBodyType.copy, SliceBodyType.cut])('copies cell text without a partial table resource (%s)', async (sliceType) => {+ const tokens = DataStreamTreeTokenType;+ const tableStream = `${tokens.TABLE_START}${tokens.TABLE_ROW_START}${tokens.TABLE_CELL_START}Alpha\r\n${tokens.TABLE_CELL_END}${tokens.TABLE_ROW_END}${tokens.TABLE_END}`;+ const documentData: IDocumentData = {+ id: 'copy-cell-text',+ body: {+ dataStream: `${tableStream}\r\n`,+ paragraphs: [{ paragraphId: 'cell-alpha', startIndex: 8 }],+ tables: [{ startIndex: 0, endIndex: tableStream.length, tableId: 'source-table' }],+ textRuns: [{ st: 3, ed: 8, ts: { bl: BooleanNumber.TRUE } }],+ },+ documentStyle: {},+ };+ const testBed = createCommandTestBed(documentData, [+ [IClipboardInterfaceService, { useClass: TestClipboardInterfaceService }],+ [IDocClipboardService, { useClass: DocClipboardService }],+ ]);+ try {+ const service = testBed.get(IDocClipboardService);+ const clipboard = testBed.get(IClipboardInterfaceService) as unknown as TestClipboardInterfaceService;+ expect(await service.copy(sliceType, [{+ startOffset: 3,+ endOffset: 8,+ collapsed: false,+ segmentId: '',+ }])).toBe(true);+ const fragment = parseInternalClipboardFragment(clipboard.writes[0].custom?.[DOC_INTERNAL_FRAGMENT_MIME]);+ expect(clipboard.writes[0].text).toBe('Alpha');+ expect(fragment?.body?.dataStream).toBe('Alpha');+ expect(fragment?.body?.tables ?? []).toEqual([]);+ expect(fragment?.tableSource).toBeUndefined();+ expect(fragment?.body?.textRuns).toEqual([{ st: 0, ed: 5, ts: { bl: BooleanNumber.TRUE } }]);++ expect(await service.copy(sliceType, [{+ startOffset: 0,+ endOffset: tableStream.length,+ collapsed: false,+ segmentId: '',+ }])).toBe(true);+ const wholeTable = parseInternalClipboardFragment(clipboard.writes[1].custom?.[DOC_INTERNAL_FRAGMENT_MIME]);+ expect(wholeTable?.body?.tables).toEqual(documentData.body!.tables);+ } finally {+ testBed.univer.dispose();+ }+ });+it('returns false when writing copied content to the clipboard fails', async () => {const documentData: IDocumentData = {id: 'failed-copy-doc',@@ -472,6 +592,79 @@ describe('DocClipboardService table copy helpers', () => {testBed.univer.dispose();});+ it.each(['switch', 'readonly', 'dispose'] as const)('keeps a pending cut bound to its source during %s', async (action) => {+ const source: IDocumentData = {+ id: 'pending-cut-source',+ body: {+ dataStream: 'Source text\r\n',+ paragraphs: [{ paragraphId: 'source-paragraph', startIndex: 11 }],+ sectionBreaks: [],+ customBlocks: [],+ textRuns: [],+ },+ documentStyle: {},+ };+ let releaseWrite!: () => void;+ const pendingWrite = new Promise<void>((resolve) => {+ releaseWrite = resolve;+ });+ const clipboard = new TestClipboardInterfaceService();+ vi.spyOn(clipboard, 'write').mockImplementation(async (text, html) => {+ clipboard.writes.push({ text, html });+ await pendingWrite;+ });+ const testBed = createCommandTestBed(source, [+ [IClipboardInterfaceService, { useValue: clipboard }],+ [IDocClipboardService, { useClass: DocClipboardService }],+ ]);+ try {+ const commands = testBed.get(ICommandService);+ commands.registerCommand(CutContentCommand);+ commands.registerCommand(RichTextEditingMutation);+ commands.registerCommand(SetTextSelectionsOperation);+ const selection = testBed.get(DocSelectionManagerService);+ selection.__TEST_ONLY_setCurrentSelection({ unitId: source.id, subUnitId: '' });+ const ranges: ITextRangeWithStyle[] = [{+ startOffset: 0,+ endOffset: 6,+ collapsed: false,+ isActive: true,+ segmentId: '',+ rangeType: DOC_RANGE_TYPE.TEXT,+ }];+ selection.__TEST_ONLY_add(ranges);+ const cut = testBed.get(IDocClipboardService).cut(ranges);+ await vi.waitFor(() => expect(clipboard.writes).toHaveLength(1));+ const instances = testBed.get(IUniverInstanceService);+ const peer = testBed.univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, {+ id: 'pending-cut-peer',+ body: { dataStream: 'Peer unchanged\r\n', paragraphs: [{ paragraphId: 'peer-paragraph', startIndex: 14 }] },+ documentStyle: {},+ });+ instances.focusUnit(peer.getUnitId());+ if (action === 'readonly') {+ setDocumentPermissionValue(testBed.get(IPermissionService), source.id, source.id, UnitAction.Edit, false);+ } else if (action === 'dispose') {+ instances.disposeUnit(source.id);+ }+ releaseWrite();+ await expect(cut).resolves.toBe(action === 'switch');+ expect(peer.getBody()?.dataStream).toBe('Peer unchanged\r\n');+ expect(clipboard.writes[0].text).toBe('Source');+ const sourceModel = instances.getUnit<DocumentDataModel>(source.id, UniverInstanceType.UNIVER_DOC);+ if (action === 'switch') {+ expect(sourceModel?.getBody()?.dataStream).toBe(' text\r\n');+ } else if (action === 'readonly') {+ expect(sourceModel?.getBody()?.dataStream).toBe('Source text\r\n');+ } else {+ expect(sourceModel).toBeNull();+ }+ } finally {+ releaseWrite();+ testBed.univer.dispose();+ }+ });+it('does not write to the clipboard when Cut lacks Unit Edit permission', async () => {const documentData: IDocumentData = {id: 'copy-only-cut-doc',@@ -1029,6 +1222,59 @@ describe('DocClipboardService table copy helpers', () => {testBed.univer.dispose();});+ it('pastes into an explicitly targeted embedded Document when another Document is current', async () => {+ const targetDocument: IDocumentData = {+ id: 'embedded-paste-target-doc',+ body: {+ dataStream: 'Target\r\n',+ paragraphs: [{ paragraphId: 'embedded-paste-target-paragraph', startIndex: 6 }],+ },+ documentStyle: {},+ };+ const currentDocument: IDocumentData = {+ id: 'embedded-paste-current-doc',+ body: {+ dataStream: 'Current\r\n',+ paragraphs: [{ paragraphId: 'embedded-paste-current-paragraph', startIndex: 7 }],+ },+ documentStyle: {},+ };+ const testBed = createCommandTestBed(targetDocument, [+ [IClipboardInterfaceService, { useClass: TestClipboardInterfaceService }],+ [IDocClipboardService, { useClass: DocClipboardService }],+ ]);+ const commandService = testBed.get(ICommandService);+ commandService.registerCommand(InnerPasteCommand);+ commandService.registerCommand(RichTextEditingMutation);+ commandService.registerCommand(SetTextSelectionsOperation);+ const selectionManager = testBed.get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: targetDocument.id, subUnitId: targetDocument.id });+ selectionManager.__TEST_ONLY_add([{+ startOffset: 6,+ endOffset: 6,+ collapsed: true,+ isActive: true,+ segmentId: '',+ }]);+ testBed.univer.createUnit(UniverInstanceType.UNIVER_DOC, currentDocument);+ testBed.get(IUniverInstanceService).focusUnit(currentDocument.id);++ const pasted = await testBed.get(IDocClipboardService).legacyPaste({+ text: ' embedded',+ files: [],+ unitId: targetDocument.id,+ });++ const instanceService = testBed.get(IUniverInstanceService);+ expect(pasted).toBe(true);+ expect(instanceService.getUnit<DocumentDataModel>(targetDocument.id, UniverInstanceType.UNIVER_DOC)?.getBody()?.dataStream)+ .toBe('Target embedded\r\n');+ expect(instanceService.getUnit<DocumentDataModel>(currentDocument.id, UniverInstanceType.UNIVER_DOC)?.getBody()?.dataStream)+ .toBe('Current\r\n');++ testBed.univer.dispose();+ });+it('turns pasted image files into inline document drawings through the image paste hook', async () => {class TestImage {naturalWidth = 20;diff --git a/packages/docs-ui/src/services/clipboard/clipboard.service.ts b/packages/docs-ui/src/services/clipboard/clipboard.service.tsindex 37f7fe4eac..57a7abc2d9 100644--- a/packages/docs-ui/src/services/clipboard/clipboard.service.ts+++ b/packages/docs-ui/src/services/clipboard/clipboard.service.ts@@ -194,7 +194,7 @@ export interface IDocClipboardService {copy(sliceType?: SliceBodyType, ranges?: ITextRangeWithStyle[]): Promise<boolean>;cut(ranges?: ITextRangeWithStyle[]): Promise<boolean>;paste(items?: ClipboardItem[]): Promise<boolean>;- legacyPaste(options: { html?: string; text?: string; internalJson?: string; files: File[] }): Promise<boolean>;+ legacyPaste(options: { html?: string; text?: string; internalJson?: string; files: File[]; unitId?: string }): Promise<boolean>;addClipboardHook(hook: IDocClipboardHook): IDisposable;}@@ -334,9 +334,9 @@ export class DocClipboardService extends Disposable implements IDocClipboardServinternalJson?: string;text?: string;files: File[];+ unitId?: string;}): Promise<boolean> {- const currentDocInstance = this._univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_DOC);- const docUnitId = currentDocInstance?.getUnitId() || '';+ const docUnitId = options.unitId ?? this._getCurrentDocumentUnitId() ?? '';if (!docUnitId || !this._canEditTargets(docUnitId)) {return false;}@@ -377,14 +377,17 @@ export class DocClipboardService extends Disposable implements IDocClipboardServexpectedUnitId?: string,ranges?: ReadonlyArray<ITextRangeWithStyle | IRectRangeWithStyle>): boolean {- const document = this._univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);- if (!document || (expectedUnitId && document.getUnitId() !== expectedUnitId)) {+ const document = expectedUnitId+ ? this._univerInstanceService.getUnit<DocumentDataModel>(expectedUnitId, UniverInstanceType.UNIVER_DOC)+ : this._univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);+ if (!document) {return false;}+ const selectionParams = this._getSelectionParams(document.getUnitId());const objectIds = new Set<string>();const targetRanges = ranges ?? [- ...(this._docSelectionManagerService.getTextRanges() ?? []),- ...(this._docSelectionManagerService.getRectRanges() ?? []),+ ...(this._docSelectionManagerService.getTextRanges(selectionParams) ?? []),+ ...(this._docSelectionManagerService.getRectRanges(selectionParams) ?? []),];targetRanges.forEach((range) => {if (range.startOffset == null || range.endOffset == null) {@@ -421,10 +424,14 @@ export class DocClipboardService extends Disposable implements IDocClipboardServreturn false;}+ const wholeBodySelected = this._docSelectionManagerService.getSelectionInfo()?.options?.wholeDocument === true;// Set content to clipboard.if (!await this.copy(SliceBodyType.cut, ranges)) {return false;}+ if (!this._canEditTargets(unitId, [...textRanges, ...rectRanges])) {+ return false;+ }try {let cursor = 0;@@ -455,13 +462,14 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ];return this._commandService.executeCommand(CutContentCommand.id, {+ unitId,segmentId,textRanges: newTextRanges,rectRanges,selections: textRanges,+ wholeBodySelected,});- // eslint-disable-next-line unused-imports/no-unused-vars- } catch (_e) {+ } catch {this._logService.error('[DocClipboardController] cut content failed');return false;}@@ -476,10 +484,14 @@ export class DocClipboardService extends Disposable implements IDocClipboardServlet body = normalizeBody(_body);- const currentDocument = this._univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);- if (!currentDocument || (expectedUnitId && currentDocument.getUnitId() !== expectedUnitId)) {+ const currentDocument = expectedUnitId+ ? this._univerInstanceService.getUnit<DocumentDataModel>(expectedUnitId, UniverInstanceType.UNIVER_DOC)+ : this._univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);+ if (!currentDocument) {return false;}+ const unitId = currentDocument.getUnitId();+ const selectionParams = this._getSelectionParams(unitId);if (currentDocument.getDocumentStyle().documentFlavor !== DocumentFlavor.TRADITIONAL) {body = omitClipboardNotes(body);@@ -494,6 +506,12 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ}});+ // Copy fragments retain trailing paragraph styles for HTML export even when the paragraph mark is not selected.+ // Only actual paragraph marks can become metadata in the inserted document body.+ if (body.paragraphs) {+ body.paragraphs = body.paragraphs.filter((paragraph) => body.dataStream[paragraph.startIndex] === '\r');+ }+// copy custom rangesconst customRangeMappings = body.customRanges?.map((sourceRange) => {const targetRange = BuildTextUtils.customRange.copyCustomRange(sourceRange);@@ -507,11 +525,11 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ}});- const activeRange = this._docSelectionManagerService.getActiveTextRange();- const docRanges = this._docSelectionManagerService.getDocRanges();+ const ranges = this._docSelectionManagerService.getTextRanges(selectionParams) ?? [];+ const activeRange = ranges.find((range) => range.isActive);+ const docRanges = this._docSelectionManagerService.getDocRanges(selectionParams);const insertionAnchor = activeRange ?? docRanges.find((range) => range.isActive) ?? docRanges[0];const { segmentId, endOffset: activeEndOffset, style } = insertionAnchor || {};- const ranges = this._docSelectionManagerService.getTextRanges() ?? [];if (segmentId == null) {this._logService.error('[DocClipboardController] segmentId does not exist!');@@ -550,6 +568,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ];return this._commandService.executeCommand(InnerPasteCommand.id, {+ unitId,doc: {...docData,body,@@ -616,6 +635,13 @@ export class DocClipboardService extends Disposable implements IDocClipboardServthis._memoryClipboardData = Tools.deepClone(internalDocData);}+ private _getSelectionParams(unitId: string): { unitId: string; subUnitId: string } {+ const currentSelection = this._docSelectionManagerService.__getCurrentSelection();+ return currentSelection?.unitId === unitId+ ? currentSelection+ : { unitId, subUnitId: unitId };+ }+addClipboardHook(hook: IDocClipboardHook): IDisposable {this._clipboardHooks.push(hook);@@ -682,6 +708,14 @@ export class DocClipboardService extends Disposable implements IDocClipboardServcontinue;}+ // Text inside a cell is not a nested table. Keep only completely copied table structures.+ if (docBody.tables?.length) {+ const completeTableIds = new Set(body.tables?.filter((table) => (+ table.startIndex >= startOffset && table.endIndex <= endOffset+ )).map((table) => table.tableId));+ docBody.tables = docBody.tables.filter((table) => completeTableIds.has(table.tableId));+ }+results.push(docBody);plainTextResults.push(copyContentHook?.(@@ -820,7 +854,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ}}));- return doc.documentElement.outerHTML;+ return /<(?:html|head)\b/i.test(html) ? doc.documentElement.outerHTML : doc.body.innerHTML;}private async _createImagePasteHtml(files: File[]) {diff --git a/packages/docs-ui/src/services/editor/__tests__/editor-manager.service.spec.ts b/packages/docs-ui/src/services/editor/__tests__/editor-manager.service.spec.tsindex 98dad1206d..5101544729 100644--- a/packages/docs-ui/src/services/editor/__tests__/editor-manager.service.spec.ts+++ b/packages/docs-ui/src/services/editor/__tests__/editor-manager.service.spec.ts@@ -531,14 +531,78 @@ describe('EditorService', () => {viewportScrollY: 0,});expect(univerInstanceService.getUnit<DocumentDataModel>(editorUnitId)?.getBody()?.dataStream).toBe('abc\r\n');+ service.focus(editorUnitId);+ expect(service.getFocusId()).toBe(editorUnitId);disposable.dispose();expect(service.isEditor(editorUnitId)).toBe(false);+ expect(service.getFocusId()).toBeNull();expect(TestRegisterRenderManagerService.removedRenderIds).toEqual([editorUnitId]);expect(univerInstanceService.getUnit<DocumentDataModel>(editorUnitId)).toBeUndefined();});+ it.each([false, true])('keeps replacement resources and releases old listeners (old container disposed first: %s)', (previousFirst) => {+ const { service, univerInstanceService } = createService(TestRegisterRenderManagerService);+ const snapshot = univerInstanceService.getUnit<DocumentDataModel>(EDITOR_ID)!.getSnapshot();+ const previousLease = service.register({ initialSnapshot: snapshot }, document.createElement('div'));+ const previousEditor = service.getEditor(EDITOR_ID)!;+ const oldInputs: string[] = [];+ previousEditor.input$.subscribe(({ content }) => oldInputs.push(content));+ service.focus(EDITOR_ID);+ const currentContainer = document.createElement('div');+ const currentLease = service.register({ initialSnapshot: snapshot }, currentContainer);+ const currentEditor = service.getEditor(EDITOR_ID)!;+ expect(currentEditor).not.toBe(previousEditor);+ const model = univerInstanceService.getUnit<DocumentDataModel>(EDITOR_ID)!;+ const currentInputs: string[] = [];+ currentEditor.input$.subscribe(({ content }) => currentInputs.push(content));+ const render = TestRegisterRenderManagerService.renders.get(EDITOR_ID)!;+ render.with(DocSelectionRenderService).onInput$.next({ event: new InputEvent('input'), content: 'new input' });+ expect(oldInputs).toEqual([]);+ expect(currentInputs).toEqual(['new input']);+ if (previousFirst) {+ previousLease.dispose();+ }+ expect(service.getEditor(EDITOR_ID)).toBe(currentEditor);+ expect(univerInstanceService.getUnit(EDITOR_ID)).toBe(model);+ expect(model.getSnapshot()).toEqual(snapshot);+ expect(TestRegisterRenderManagerService.renders.get(EDITOR_ID)?.container).toBe(currentContainer);+ expect(TestRegisterRenderManagerService.removedRenderIds).toEqual([]);+ service.focus(EDITOR_ID);+ expect(service.getFocusEditor()).toBe(currentEditor);+ currentLease.dispose();+ previousLease.dispose();+ currentLease.dispose();+ expect(service.getEditor(EDITOR_ID)).toBeUndefined();+ expect(univerInstanceService.getUnit(EDITOR_ID)).toBeUndefined();+ expect(TestRegisterRenderManagerService.removedRenderIds).toEqual([EDITOR_ID]);+ });++ it('releases registered editor listeners and units when the service is disposed', () => {+ const { injector, univerInstanceService } = createService(TestRegisterRenderManagerService);+ const service = injector.get(IEditorService) as EditorService;+ const snapshot = univerInstanceService.getUnit<DocumentDataModel>(EDITOR_ID)!.getSnapshot();+ const lease = service.register({ initialSnapshot: snapshot }, document.createElement('div'));+ const editor = service.getEditor(EDITOR_ID)!;+ let completed = false;+ editor.input$.subscribe({+ complete: () => {+ completed = true;+ },+ });++ service.dispose();+ service.dispose();+ lease.dispose();++ expect(completed).toBe(true);+ expect(service.getAllEditor().size).toBe(0);+ expect(univerInstanceService.getUnit(EDITOR_ID)).toBeUndefined();+ expect(TestRegisterRenderManagerService.removedRenderIds).toEqual([EDITOR_ID]);+ expect(() => service.register({ initialSnapshot: snapshot }, document.createElement('div'))).toThrow('disposed');+ });+it('keeps render config without an editor when no render is available and removes it on dispose', () => {const { service } = createService(TestMissingRenderManagerService);const disposable = service.register({diff --git a/packages/docs-ui/src/services/editor/editor-manager.service.ts b/packages/docs-ui/src/services/editor/editor-manager.service.tsindex c8f52d05d9..eaecd1da0a 100644--- a/packages/docs-ui/src/services/editor/editor-manager.service.ts+++ b/packages/docs-ui/src/services/editor/editor-manager.service.ts@@ -203,8 +203,16 @@ export class EditorService extends Disposable implements IEditorService, IDispos}override dispose(): void {- this._editors.clear();+ if (this._disposed) {+ return;+ }++ for (const editorUnitId of this._editors.keys()) {+ this._unRegister(editorUnitId);+ }this._editorRenderConfigs.clear();+ this._blur$.complete();+ this._focus$.complete();super.dispose();}@@ -222,14 +230,18 @@ export class EditorService extends Disposable implements IEditorService, IDispos}register(config: IEditorConfigParams, container: HTMLDivElement): IDisposable {+ this.ensureNotDisposed();const { initialSnapshot, canvasStyle = {} } = config;const editorUnitId = initialSnapshot.id;- this._editorRenderConfigs.set(editorUnitId, {+ this._editors.get(editorUnitId)?.dispose(false);+ this._editors.delete(editorUnitId);+ const renderConfig: IEditorRenderConfig = {canvasStyle,scrollBar: config.scrollBar,...(config.backScrollOffset === undefined ? {} : { backScrollOffset: config.backScrollOffset }),...(config.preserveHostFocus === undefined ? {} : { preserveHostFocus: config.preserveHostFocus }),- });+ };+ this._editorRenderConfigs.set(editorUnitId, renderConfig);const documentDataModel = this._univerInstanceService.getUnit<DocumentDataModel>(editorUnitId, UniverInstanceType.UNIVER_DOC);@@ -287,7 +299,10 @@ export class EditorService extends Disposable implements IEditorService, IDispos}}return toDisposable(() => {- this._unRegister(editorUnitId);+ // An older container may unmount after a replacement has registered the same ID.+ if (this._editorRenderConfigs.get(editorUnitId) === renderConfig) {+ this._unRegister(editorUnitId);+ }});}@@ -298,6 +313,10 @@ export class EditorService extends Disposable implements IEditorService, IDisposreturn;}+ if (this._focusEditorUnitId === editorUnitId) {+ this.blur(true);+ }+const preserveHostFocus = this._editorRenderConfigs.get(editorUnitId)?.preserveHostFocus === true;const currentDoc = this._univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);const focusedHost = preserveHostFocus ? this._univerInstanceService.getFocusedUnit() : null;diff --git a/packages/docs-ui/src/services/editor/editor.ts b/packages/docs-ui/src/services/editor/editor.tsindex 95bf966f7d..cba2cb84c0 100644--- a/packages/docs-ui/src/services/editor/editor.ts+++ b/packages/docs-ui/src/services/editor/editor.ts@@ -374,10 +374,23 @@ export class Editor extends Disposable implements IEditor {return this._undoRedoService.clearUndoRedo(editorUnitId);}- override dispose(): void {- const docDataModel = this._getDocDataModel();+ override dispose(disposeDocument = true): void {+ if (this._disposed) {+ return;+ }- docDataModel?.dispose();+ super.dispose();+ this._change$.complete();+ this._input$.complete();+ this._paste$.complete();+ this._focus$.complete();+ this._blur$.complete();+ this._selectionChange$.complete();++ // Rebinding a registered editor transfers its document to the next container.+ if (disposeDocument) {+ this._getDocDataModel()?.dispose();+ }}get cancelDefaultResizeListener() {diff --git a/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts b/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.tsindex cf6c6330a2..6736ff0fdf 100644--- a/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts+++ b/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts@@ -1282,6 +1282,22 @@ describe('DocSelectionRenderService', () => {expect(document.activeElement).toBe(input);});+ it.each(['input', 'textarea', 'select'])('preserves an embed-owned %s during selection synchronization', (tagName) => {+ const { input, renderUnit, service, univer } = createRealSelectionRenderService();+ cleanup.push(() => renderUnit.dispose(), () => univer.dispose());+ TestLayoutService.root.setAttribute(EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE, 'embed-1');+ input.setAttribute(EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE, 'embed-1');+ const control = document.createElement(tagName);+ TestLayoutService.root.appendChild(control);+ control.focus();+ expect(document.activeElement).toBe(control);+ expect(service.canFocusing).toBe(false);+ service.sync();+ expect(document.activeElement).toBe(control);+ service.activate(12, 34, true);+ expect(document.activeElement).toBe(control);+ });+it('allows the internal sheet cell editor to refocus from an embed-owned canvas', () => {const focusCoordinator = new EmbedRuntimeFocusCoordinator();const { input, renderUnit, service, univer } = createRealSelectionRenderService({@@ -1353,6 +1369,64 @@ describe('DocSelectionRenderService', () => {expect(input.textContent).toBe('');});+ it.each(['input', 'compositionupdate'])('retains the first %s content when before-input restores a missing caret', (type) => {+ const { input, renderUnit, service, univer } = createRealSelectionRenderService();+ cleanup.push(() => renderUnit.dispose(), () => univer.dispose());+ const caret = {+ ...createTextRange({ isActive: vi.fn(() => true), collapsed: true }),+ startOffset: 0,+ endOffset: 0,+ };+ const before = service.onInputBefore$.subscribe((config) => {+ expect(config?.activeRange).toBeNull();+ (service as unknown as { _rangeList: TextRange[] })._rangeList = [caret as never];+ });+ const received: Array<{ content?: string; start?: number; end?: number }> = [];+ const inputStream = type === 'input' ? service.onInput$ : service.onCompositionupdate$;+ const subscription = inputStream.subscribe((config) => {+ if (config) {+ received.push({+ content: config.content,+ start: config.activeRange?.startOffset,+ end: config.activeRange?.endOffset,+ });+ }+ });+ cleanup.push(() => before.unsubscribe(), () => subscription.unsubscribe());++ input.textContent = '首';+ input.dispatchEvent(type === 'input'+ ? new InputEvent(type, { bubbles: true, data: '首', inputType: 'insertText' })+ : new CompositionEvent(type, { bubbles: true, data: '首' }));++ expect(received).toEqual([{ content: '首', start: 0, end: 0 }]);+ });++ it('preserves an existing input selection snapshot when before-input changes the caret', () => {+ const { input, renderUnit, service, univer } = createRealSelectionRenderService();+ cleanup.push(() => renderUnit.dispose(), () => univer.dispose());+ const range = {+ ...createTextRange({ isActive: vi.fn(() => true) }),+ startOffset: 1,+ endOffset: 3,+ };+ (service as unknown as { _rangeList: TextRange[] })._rangeList = [range as never];+ const before = service.onInputBefore$.subscribe(() => {+ (service as unknown as { _rangeList: TextRange[] })._rangeList = [];+ });+ const received: Array<{ start?: number; end?: number }> = [];+ const subscription = service.onInput$.subscribe((config) => received.push({+ start: config.activeRange?.startOffset,+ end: config.activeRange?.endOffset,+ }));+ cleanup.push(() => before.unsubscribe(), () => subscription.unsubscribe());++ input.textContent = 'A';+ input.dispatchEvent(new InputEvent('input', { bubbles: true, data: 'A', inputType: 'insertText' }));++ expect(received).toEqual([{ start: 1, end: 3 }]);+ });+it('does not publish host hidden editor events while a child session owns the host document', () => {const focusCoordinator = new EmbedRuntimeFocusCoordinator();const { input, renderUnit, service, univer } = createRealSelectionRenderService({@@ -1663,7 +1737,7 @@ describe('DocSelectionRenderService', () => {expect(container.style.top).toBe('-153px');});- it('parks the active selection while scrolling and restores the editor when the selection remains in view', () => {+ it.each(['editor', 'button', 'input'] as const)('updates the caret position after scrolling without moving focus from the %s', (target) => {getCanvasOffsetByEngineMock.mockReturnValue({ left: 1, top: 2 });const scrollAfter$ = new TestRenderEvent<{ viewport: unknown }>();const scrollEnd$ = new TestRenderEvent<{ viewport: unknown }>();@@ -1686,8 +1760,17 @@ describe('DocSelectionRenderService', () => {getViewports: () => [viewport],getEngine: () => ({ name: 'engine' }),};- const { renderUnit, service, univer } = createRealSelectionRenderService({ scene });+ const { input, renderUnit, service, univer } = createRealSelectionRenderService({ scene });cleanup.push(() => renderUnit.dispose(), () => univer.dispose());+ TestLayoutService.root.setAttribute(EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE, 'embed-1');+ const focusTarget = target === 'editor' ? input : document.createElement(target);+ if (focusTarget !== input) {+ TestLayoutService.root.appendChild(focusTarget);+ focusTarget.focus();+ } else {+ service.focus();+ }+ expect(document.activeElement).toBe(focusTarget);const activeRange = {isActive: () => true,activeStatic,@@ -1701,6 +1784,7 @@ describe('DocSelectionRenderService', () => {scrollAfter$.emit({ viewport });scrollEnd$.emit({ viewport });+ expect(document.activeElement).toBe(focusTarget);const container = document.getElementById('univer-doc-selection-container-selection-render-doc')!;expect(activeStatic).toHaveBeenCalledTimes(1);expect(deactivateStatic).not.toHaveBeenCalled();diff --git a/packages/docs-ui/src/services/selection/doc-selection-render.service.ts b/packages/docs-ui/src/services/selection/doc-selection-render.service.tsindex a6bd7d0a13..90250cc995 100644--- a/packages/docs-ui/src/services/selection/doc-selection-render.service.ts+++ b/packages/docs-ui/src/services/selection/doc-selection-render.service.ts@@ -517,8 +517,10 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMooptions,});- if (!ranges.length || options?.shouldFocus === false) return true;- this._updateInputPosition(options?.forceFocus);+ if (!ranges.length || options?.shouldFocus === false) {+ return true;+ }+ this._updateInputPosition({ forceFocus: options?.forceFocus });return true;}@@ -827,7 +829,7 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMothis._disposeScrollTimers();- this._updateInputPosition(true);+ this._updateInputPosition({ forceFocus: true });}));}@@ -1221,12 +1223,12 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMoreturn getCanvasOffsetByEngine(engine);}- private _updateInputPosition(forceFocus = false) {+ private _updateInputPosition({ forceFocus = false, preserveFocus = false } = {}) {const activeRangeInstance = this._getActiveRangeInstance();const anchor = activeRangeInstance?.getAnchor();if (!anchor || (anchor && !anchor.visible) || this.activeViewPort == null) {- if (this._shouldPreserveExternalFocus() || (!forceFocus && this._isAnotherEditorFocused())) {+ if (preserveFocus || this._shouldPreserveExternalFocus() || (!forceFocus && this._isAnotherEditorFocused())) {return;}this.focus();@@ -1245,7 +1247,11 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMocanvasTop += y;- this.activate(canvasLeft, canvasTop, forceFocus);+ if (preserveFocus) {+ this._positionInput(canvasLeft, canvasTop);+ } else {+ this.activate(canvasLeft, canvasTop, forceFocus);+ }}private _tryMoving(moveOffsetX: number, moveOffsetY: number) {@@ -1419,7 +1425,8 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo}}- this._updateInputPosition();+ // A delayed scroll completion must not reclaim focus from a menu or another editor.+ this._updateInputPosition({ preserveFocus: true });});this._viewPortObserverMap.set(unitId, {@@ -1467,6 +1474,7 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMothis._eventHandle(e, (config) => {this._onInputBefore$.next(config);+ this._refreshMissingInputRange(config);this._onInput$.next(config);});})@@ -1511,6 +1519,7 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo}this._eventHandle(e, (config) => {this._onInputBefore$.next(config);+ this._refreshMissingInputRange(config);this._onCompositionupdate$.next(config);}, true);})@@ -1558,6 +1567,14 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo);}+ private _refreshMissingInputRange(config: IEditorInputConfig): void {+ // Opening a Sheet editor in before-input can establish its first caret after the event snapshot was captured.+ if (config.activeRange == null) {+ config.activeRange = this._getActiveRange();+ config.rangeList = this._getAllTextRanges();+ }+ }+private _eventHandle(e: Event | CompositionEvent | KeyboardEvent,func: (config: IEditorInputConfig) => void,@@ -1685,6 +1702,11 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMoconst ownerDocument = this._getOwnerDocument();const activeElement = ownerDocument.activeElement;const currentEmbedOwner = this._getCurrentEmbedOwner();+ // Sharing an embed runtime does not transfer focus away from its native controls.+ if (activeElement?.matches('input, textarea, select')) {+ return true;+ }+if (this._embedRuntimeFocusCoordinator?.isChildUnitInActiveSession(this._context.unitId)) {return false;}diff --git a/packages/docs-ui/src/views/count-bar/__tests__/ZoomSlider.spec.tsx b/packages/docs-ui/src/views/count-bar/__tests__/ZoomSlider.spec.tsxindex 5755bd40a7..2d6e7483eb 100644--- a/packages/docs-ui/src/views/count-bar/__tests__/ZoomSlider.spec.tsx+++ b/packages/docs-ui/src/views/count-bar/__tests__/ZoomSlider.spec.tsx@@ -23,6 +23,7 @@ import {CommandService,ConfigService,ContextService,+ DesktopLogService,DocumentDataModel,ICommandService,IConfigService,@@ -31,9 +32,11 @@ import {Injector,IUniverInstanceService,LocaleService,+ LocaleType,UniverInstanceService,} from '@univerjs/core';import { ComponentManager, IconManager, RediContext } from '@univerjs/ui';+import uiEnUS from '@univerjs/ui/locale/en-US';import { act } from 'react';import { createRoot } from 'react-dom/client';import { afterEach, describe, expect, it } from 'vitest';@@ -42,14 +45,9 @@ import { ZoomSlider } from '../ZoomSlider';(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;-class TestLogService {- debug(): void {}- warn(): void {}-}-function createZoomSliderTestBed() {const injector = new Injector();- injector.add([ILogService, { useClass: TestLogService as never }]);+ injector.add([ILogService, { useClass: DesktopLogService }]);injector.add([IConfigService, { useClass: ConfigService }]);injector.add([IContextService, { useClass: ContextService }]);injector.add([ICommandService, { useClass: CommandService }]);@@ -57,8 +55,12 @@ function createZoomSliderTestBed() {injector.add([LocaleService]);injector.add([ComponentManager]);injector.add([IconManager]);+ const localeService = injector.get(LocaleService);+ localeService.load({ [LocaleType.EN_US]: uiEnUS });+ localeService.setLocale(LocaleType.EN_US);+ localeService.setDirection('ltr');- const doc = new DocumentDataModel({+ const doc = injector.createInstance(DocumentDataModel, {id: 'zoom-slider-doc',body: {dataStream: '\r\n',@@ -76,13 +78,13 @@ function createZoomSliderTestBed() {return { injector, doc };}-function renderZoomSlider() {+async function renderZoomSlider() {const { injector, doc } = createZoomSliderTestBed();const container = document.createElement('div');document.body.appendChild(container);const root = createRoot(container);- act(() => {+ await act(async () => {root.render(<RediContext.Provider value={{ injector }}><ZoomSlider />@@ -90,32 +92,36 @@ function renderZoomSlider() {);});- return { container, doc, root };+ return { container, doc, root, injector };}describe('ZoomSlider', () => {let root: Root | undefined;let container: HTMLElement | undefined;+ let injector: Injector | undefined;- afterEach(() => {+ afterEach(async () => {if (root) {- act(() => root!.unmount());+ await act(async () => root!.unmount());}+ injector?.dispose();container?.remove();root = undefined;container = undefined;+ injector = undefined;});- it('applies toolbar zoom changes to the current document through the zoom operation', () => {- const rendered = renderZoomSlider();+ it('applies toolbar zoom changes to the current document through the zoom operation', async () => {+ const rendered = await renderZoomSlider();root = rendered.root;container = rendered.container;+ injector = rendered.injector;- const buttons = Array.from(container.querySelectorAll('button'));- const increaseButton = buttons[2];+ const increaseButton = container.querySelector<HTMLButtonElement>('button[aria-label="Zoom in"]');+ expect(increaseButton).not.toBeNull();- act(() => {- increaseButton.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await act(async () => {+ increaseButton!.dispatchEvent(new MouseEvent('click', { bubbles: true }));});expect(rendered.doc.zoomRatio).toBe(1.1);diff --git a/packages/docs/src/facade/__tests__/f-univer.spec.ts b/packages/docs/src/facade/__tests__/f-univer.spec.tsindex d85b17349a..1ef4087733 100644--- a/packages/docs/src/facade/__tests__/f-univer.spec.ts+++ b/packages/docs/src/facade/__tests__/f-univer.spec.ts@@ -51,4 +51,20 @@ describe('FUniver docs facade', () => {expect(created.getName()).toBe('Created');expect(univerAPI.getDocument('created-doc')?.save().body?.dataStream).toBe('Created\r\n');});++ it('creates an embedded document without changing the active document', () => {+ const created = univerAPI.createDocument({+ id: 'embedded-doc',+ title: 'Embedded',+ body: { dataStream: '\r\n' },+ documentStyle: DOCUMENT_STYLE,+ }, {+ embeddedRender: true,+ makeCurrent: false,+ skipAutoRender: true,+ });++ expect(created.getId()).toBe('embedded-doc');+ expect(univerAPI.getActiveDocument()?.getId()).toBe('test');+ });});diff --git a/packages/docs/src/facade/f-univer.ts b/packages/docs/src/facade/f-univer.tsindex 8b4385d8c3..072f197c14 100644--- a/packages/docs/src/facade/f-univer.ts+++ b/packages/docs/src/facade/f-univer.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { DocumentDataModel, IDocumentData } from '@univerjs/core';+import type { DocumentDataModel, ICreateUnitOptions, IDocumentData } from '@univerjs/core';import { IUniverInstanceService, UniverInstanceType } from '@univerjs/core';import { FUniver } from '@univerjs/core/facade';import { FDocument } from './f-document';@@ -26,6 +26,7 @@ export interface IFUniverDocsMixin {/*** Create a new document and get the API handler of that document.* @param {Partial<IDocumentData>} data The snapshot of the document.+ * @param {ICreateUnitOptions} options The options of creating the document.* @returns {FDocument} The document API instance.* @example* ```typescript@@ -33,7 +34,7 @@ export interface IFUniverDocsMixin {* console.log(fDocument);* ```*/- createDocument(data: Partial<IDocumentData>): FDocument;+ createDocument(data: Partial<IDocumentData>, options?: ICreateUnitOptions): FDocument;/*** Get the currently focused Univer document.@@ -60,9 +61,13 @@ export interface IFUniverDocsMixin {}export class FUniverDocsMixin extends FUniver implements IFUniverDocsMixin {- override createDocument(data: Partial<IDocumentData>): FDocument {+ override createDocument(data: Partial<IDocumentData>, options?: ICreateUnitOptions): FDocument {const instanceService = this._injector.get(IUniverInstanceService);- const document = instanceService.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, data);+ const document = instanceService.createUnit<IDocumentData, DocumentDataModel>(+ UniverInstanceType.UNIVER_DOC,+ data,+ options+ );return this._injector.createInstance(FDocument, document);}diff --git a/packages/docs/src/services/__tests__/doc-selection-manager.service.spec.ts b/packages/docs/src/services/__tests__/doc-selection-manager.service.spec.tsindex 6bb0011400..be884134fc 100644--- a/packages/docs/src/services/__tests__/doc-selection-manager.service.spec.ts+++ b/packages/docs/src/services/__tests__/doc-selection-manager.service.spec.ts@@ -45,6 +45,33 @@ function createService() {}describe('DocSelectionManagerService', () => {+ it('retains explicitly owned render selections before a global Doc becomes current', () => {+ const service = createService();+ const target = { unitId: 'embedded-doc', subUnitId: 'embedded-doc' };+ const ranges = [{ startOffset: 4, endOffset: 14, collapsed: false, isActive: true }];+ try {+ service.__replaceTextRangesWithNoRefresh({+ textRanges: ranges,+ rectRanges: [],+ segmentId: '',+ segmentPage: -1,+ isEditing: false,+ style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE,+ }, target);++ expect(service.getDocRanges(target)).toEqual(ranges);+ expect(service.__getCurrentSelection()).toBeNull();+ expect(service.getDocRanges()).toEqual([]);+ service.__TEST_ONLY_setCurrentSelection({ unitId: 'peer-doc', subUnitId: 'peer-doc' });+ expect(service.getDocRanges()).toEqual([]);+ expect(service.getDocRanges(target)).toEqual(ranges);+ service.__TEST_ONLY_setCurrentSelection(target);+ expect(service.getActiveTextRange()).toEqual(ranges[0]);+ } finally {+ service.dispose();+ }+ });+it('stores document text selections and exposes active/doc range ordering', () => {const service = createService();service.__TEST_ONLY_setCurrentSelection({ unitId: 'doc-1', subUnitId: 'doc-1' });@@ -127,6 +154,39 @@ describe('DocSelectionManagerService', () => {sub.unsubscribe();});+ it('does not replay a previous forced focus when refreshing an inactive document selection', () => {+ const service = createService();+ const target = { unitId: 'doc-1', subUnitId: 'doc-1' };+ const refreshes: unknown[] = [];+ const sub = service.refreshSelection$.subscribe((value) => refreshes.push(value));+ try {+ service.__replaceTextRangesWithNoRefresh({+ textRanges: [{ startOffset: 2, endOffset: 5, collapsed: false, isActive: true }],+ rectRanges: [],+ segmentId: '',+ segmentPage: -1,+ isEditing: false,+ style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE,+ options: { forceFocus: true, preserveCaret: true },+ }, target);+ service.__TEST_ONLY_setCurrentSelection({ unitId: 'doc-2', subUnitId: 'doc-2' });++ service.refreshSelection(target);++ expect(refreshes.at(-1)).toEqual(expect.objectContaining({+ unitId: 'doc-1',+ docRanges: [expect.objectContaining({ startOffset: 2, endOffset: 5 })],+ options: { forceFocus: false, preserveCaret: true },+ }));+ expect(service.__getCurrentSelection()?.unitId).toBe('doc-2');+ service.replaceDocRanges([{ startOffset: 3, endOffset: 3 }], target, false, { forceFocus: true });+ expect(refreshes.at(-1)).toEqual(expect.objectContaining({ options: { forceFocus: true } }));+ } finally {+ sub.unsubscribe();+ service.dispose();+ }+ });+it('preserves active editing state when refreshed layout geometry replaces the selection', () => {const service = createService();const refreshes: unknown[] = [];diff --git a/packages/docs/src/services/doc-selection-manager.service.ts b/packages/docs/src/services/doc-selection-manager.service.tsindex 1c31999f6f..4c41c7c40b 100644--- a/packages/docs/src/services/doc-selection-manager.service.ts+++ b/packages/docs/src/services/doc-selection-manager.service.ts@@ -220,10 +220,7 @@ export class DocSelectionManagerService extends RxDisposable {// Only use in doc-selection-render.controller.ts__replaceTextRangesWithNoRefresh(textSelectionInfo: IDocSelectionInnerParam, search: IDocSelectionManagerSearchParam) {- if (this._currentSelection == null) {- return;- }-+ // Embedded render selections have an explicit owner even while the host retains global focus.const params = {...textSelectionInfo,...search,@@ -297,7 +294,8 @@ export class DocSelectionManagerService extends RxDisposable {subUnitId,docRanges,isEditing,- options,+ // Forced focus belongs to the original interaction, not later layout refreshes.+ options: options?.forceFocus ? { ...options, forceFocus: false } : options,});}diff --git a/packages/drawing-ui/src/controllers/__tests__/image-cropper.controller.spec.ts b/packages/drawing-ui/src/controllers/__tests__/image-cropper.controller.spec.tsindex 653ecb22d7..15b02f8f9d 100644--- a/packages/drawing-ui/src/controllers/__tests__/image-cropper.controller.spec.ts+++ b/packages/drawing-ui/src/controllers/__tests__/image-cropper.controller.spec.ts@@ -292,9 +292,13 @@ describe('ImageCropperController', () => {expect(firstCropperDispose).toHaveBeenCalledOnce();const secondCropperDispose = vi.spyOn(createdCropper!, 'dispose');+ transformer.clearCopperControl.mockImplementationOnce(() => {+ commandService.syncExecuteCommand(CloseImageCropOperation.id, undefined);+ });commandHandlers[1]({ id: CloseImageCropOperation.id, params: { isCancel: true } } as never);expect(transformer.detachFrom).toHaveBeenCalledWith(createdCropper);expect(secondCropperDispose).toHaveBeenCalledOnce();+ expect(commandService.syncExecuteCommand).toHaveBeenLastCalledWith(CloseImageCropOperation.id, undefined);expect(firstEnterShortcutDisposable.dispose).toHaveBeenCalledOnce();expect(firstCancelShortcutDisposable.dispose).toHaveBeenCalledOnce();expect(secondEnterShortcutDisposable.dispose).toHaveBeenCalledOnce();diff --git a/packages/drawing-ui/src/controllers/image-cropper.controller.ts b/packages/drawing-ui/src/controllers/image-cropper.controller.tsindex 7cd83e9607..f78251b38c 100644--- a/packages/drawing-ui/src/controllers/image-cropper.controller.ts+++ b/packages/drawing-ui/src/controllers/image-cropper.controller.ts@@ -338,6 +338,7 @@ export class ImageCropperController extends Disposable {if (cropSession == null) {return;}+ this._activeCropSession = null;const { scene, imageShape, imageCropperObject } = cropSession;const transformer = scene.getTransformerByCreate();@@ -373,7 +374,6 @@ export class ImageCropperController extends Disposable {this._cropSnapshots.delete(imageCropperObject);imageCropperObject.dispose();- this._activeCropSession = null;this._cropShortcutDisposables.dispose();}));@@ -385,7 +385,9 @@ export class ImageCropperController extends Disposable {);this.disposeWithMe(sheetUnit$.subscribe(() => {- this._commandService.syncExecuteCommand(CloseImageCropOperation.id);+ if (this._activeCropSession != null) {+ this._commandService.syncExecuteCommand(CloseImageCropOperation.id);+ }}));}diff --git a/packages/engine-render/src/__tests__/scene.input-manager.spec.ts b/packages/engine-render/src/__tests__/scene.input-manager.spec.tsindex 58433fdcf7..5ccda86ef9 100644--- a/packages/engine-render/src/__tests__/scene.input-manager.spec.ts+++ b/packages/engine-render/src/__tests__/scene.input-manager.spec.ts@@ -14,55 +14,159 @@* limitations under the License.*/-import { afterEach, describe, expect, it, vi } from 'vitest';-import { DeviceType } from '../basics/i-events';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { DeviceType, PointerInput } from '../basics/i-events';+import { Engine } from '../engine';+import { MAIN_VIEW_PORT_KEY, Scene } from '../scene';import { InputManager } from '../scene.input-manager';+import { Rect } from '../shape/rect';+import { Viewport } from '../viewport';+import { setupRenderTestEnv } from './render-test-utils';++describe('InputManager click gestures', () => {+ let env: ReturnType<typeof setupRenderTestEnv>;+ let engine: Engine;+ let scene: Scene;+ let doubleClick: ReturnType<typeof vi.fn<() => void>>;+ let tripleClick: ReturnType<typeof vi.fn<() => void>>;++ function pointer(type: string, x = 20, y = 20, button = 0, deviceType = DeviceType.Mouse) {+ engine.onInputChanged$.emitEvent(Object.assign(new MouseEvent(type, { clientX: x, clientY: y, button }), {+ deviceType,+ inputIndex: PointerInput.LeftClick + button,+ previousState: null,+ currentState: null,+ pointerId: 1,+ }));+ }++ function click(x = 20, y = 20, button = 0) {+ pointer('pointerdown', x, y, button);+ pointer('pointerup', x, y, button);+ }++ beforeEach(() => {+ env = setupRenderTestEnv();+ vi.useFakeTimers();+ engine = new Engine('click-unit', { elementWidth: 300, elementHeight: 200, dpr: 1 });+ scene = new Scene('click-scene', engine);+ new Viewport(MAIN_VIEW_PORT_KEY, scene, { left: 0, top: 0, width: 300, height: 200 });+ const rect = new Rect('target', { left: 0, top: 0, width: 200, height: 150 });+ scene.addObject(rect);+ doubleClick = vi.fn();+ tripleClick = vi.fn();+ rect.onDblclick$.subscribeEvent(doubleClick);+ rect.onTripleClick$.subscribeEvent(tripleClick);+ scene.attachControl();+ });-function createScene() {- return {- onDblclick$: { emitEvent: vi.fn() },- onPointerUp$: { emitEvent: vi.fn() },- onTripleClick$: { emitEvent: vi.fn() },- pick: vi.fn(() => null),- };-}--function createPointerUpEvent(clientX: number, deviceType: DeviceType) {- return {- button: 0,- clientX,- clientY: 20,- deviceType,- offsetX: clientX,- offsetY: 20,- pointerId: 1,- };-}--describe('InputManager double click recognition', () => {afterEach(() => {+ scene.dispose();+ engine.dispose();+ vi.runOnlyPendingTimers();vi.useRealTimers();+ env.restore();+ vi.restoreAllMocks();});- it('allows natural finger drift between two touch taps', () => {- vi.useFakeTimers();- const scene = createScene();- const inputManager = new InputManager(scene as never);+ it('recognizes primary-button double and triple clicks', () => {+ click();+ click();+ expect(doubleClick).toHaveBeenCalledTimes(1);+ click();+ expect(tripleClick).toHaveBeenCalledTimes(1);+ });- inputManager._onPointerUp(createPointerUpEvent(20, DeviceType.Touch) as never);- inputManager._onPointerUp(createPointerUpEvent(26, DeviceType.Touch) as never);+ it('does not turn a drag ending at the last clicked cell into a double click', () => {+ click();+ pointer('pointerdown', 100, 80);+ pointer('pointermove', 60, 50);+ pointer('pointerup');+ expect(doubleClick).not.toHaveBeenCalled();+ click();+ expect(doubleClick).not.toHaveBeenCalled();+ click();+ expect(doubleClick).toHaveBeenCalledTimes(1);+ });- expect(scene.onDblclick$.emitEvent).toHaveBeenCalledTimes(1);+ it('does not treat a drag returning to its origin as a click', () => {+ click();+ pointer('pointerdown');+ pointer('pointermove', 100, 80);+ pointer('pointermove');+ pointer('pointerup');+ expect(doubleClick).not.toHaveBeenCalled();});- it('keeps the precise double-click threshold for mouse input', () => {- vi.useFakeTimers();- const scene = createScene();- const inputManager = new InputManager(scene as never);+ it.each([1, 2])('does not include button %s in a primary click sequence', (button) => {+ click();+ click(20, 20, button);+ expect(doubleClick).not.toHaveBeenCalled();+ click();+ expect(doubleClick).not.toHaveBeenCalled();+ click();+ expect(doubleClick).toHaveBeenCalledTimes(1);+ click(20, 20, button);+ expect(tripleClick).not.toHaveBeenCalled();+ });++ it('does not recognize a triple click at a different position', () => {+ click();+ click();+ click(100, 80);+ expect(tripleClick).not.toHaveBeenCalled();+ });++ it('starts a fresh sequence after pointer cancellation', () => {+ click();+ pointer('pointerdown');+ pointer('pointercancel');+ pointer('pointerup');+ click();+ expect(doubleClick).not.toHaveBeenCalled();+ click();+ expect(doubleClick).toHaveBeenCalledTimes(1);+ });++ it.each([1, 2])('starts a fresh sequence after leaving the canvas following %s clicks', (count) => {+ for (let index = 0; index < count; index += 1) {+ click();+ }+ const previousDoubleClicks = doubleClick.mock.calls.length;+ pointer('pointerleave');+ pointer('pointerenter');+ click();+ expect(doubleClick).toHaveBeenCalledTimes(previousDoubleClicks);+ expect(tripleClick).not.toHaveBeenCalled();+ click();+ expect(doubleClick).toHaveBeenCalledTimes(previousDoubleClicks + 1);+ });++ it('expires double and triple click sequences', () => {+ click();+ vi.advanceTimersByTime(InputManager.DoubleClickDelay + 1);+ click();+ expect(doubleClick).not.toHaveBeenCalled();+ click();+ vi.advanceTimersByTime(InputManager.TripleClickDelay + 1);+ click();+ expect(tripleClick).not.toHaveBeenCalled();+ });++ it('allows a small movement within the click tolerance', () => {+ click();+ pointer('pointerdown');+ pointer('pointermove', 21, 21);+ pointer('pointerup', 21, 21);+ expect(doubleClick).toHaveBeenCalledTimes(1);+ });- inputManager._onPointerUp(createPointerUpEvent(20, DeviceType.Mouse) as never);- inputManager._onPointerUp(createPointerUpEvent(26, DeviceType.Mouse) as never);+ it.each([DeviceType.Touch, DeviceType.Mouse])('uses the device-specific double-click threshold for %s', (deviceType) => {+ pointer('pointerdown', 20, 20, 0, deviceType);+ pointer('pointerup', 20, 20, 0, deviceType);+ pointer('pointerdown', 26, 20, 0, deviceType);+ pointer('pointerup', 26, 20, 0, deviceType);- expect(scene.onDblclick$.emitEvent).not.toHaveBeenCalled();+ expect(doubleClick).toHaveBeenCalledTimes(deviceType === DeviceType.Touch ? 1 : 0);});});diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/language-ruler.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/language-ruler.spec.tsindex 459ba15912..6b95d4031e 100644--- a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/language-ruler.spec.ts+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/language-ruler.spec.ts@@ -67,6 +67,19 @@ function createSectionBreakConfig(): ISectionBreakConfig {describe('language-ruler', () => {describe('otherHandler', () => {+ it.each(['é', 'ä́'])('keeps the combining sequence %s in one cursor-addressable glyph', (cluster) => {+ const text = `${cluster}x`;+ const { viewModel } = createViewModel(text);+ const paragraphNode = getParagraphNode(viewModel);+ const result = otherHandler(0, text, viewModel, paragraphNode, createSectionBreakConfig(), getParagraph(viewModel));++ expect(result.step).toBe(text.length);+ expect(result.glyphGroup.map((glyph) => ({ content: glyph.content, count: glyph.count }))).toEqual([+ { content: cluster, count: cluster.length },+ { content: 'x', count: 1 },+ ]);+ });+it('processes English characters and stops at space', () => {const { viewModel } = createViewModel('Hello world');const paragraphNode = getParagraphNode(viewModel);diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/language-ruler.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/language-ruler.tsindex e4b2875a42..4810404ebb 100644--- a/packages/engine-render/src/components/docs/layout/block/paragraph/language-ruler.ts+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/language-ruler.ts@@ -44,7 +44,8 @@ export function otherHandler(let src = charArray;while (src.length) {- const char = src.match(/^[\s\S]/gu)?.[0];+ // Keep ordinary ASCII cheap, but never expose a caret stop inside a combining sequence.+ const char = src.match(/^\p{ASCII}(?![\p{Mark}\u200D])/u)?.[0] ?? getFirstGrapheme(src);if (char == null) {break;diff --git a/packages/engine-render/src/components/sheets/__tests__/sheet.render-skeleton.spec.ts b/packages/engine-render/src/components/sheets/__tests__/sheet.render-skeleton.spec.tsindex c829115f72..90d15f2add 100644--- a/packages/engine-render/src/components/sheets/__tests__/sheet.render-skeleton.spec.ts+++ b/packages/engine-render/src/components/sheets/__tests__/sheet.render-skeleton.spec.ts@@ -14,9 +14,75 @@* limitations under the License.*/+import type { IWorkbookData, Workbook } from '@univerjs/core';+import { DocumentFlavor, LocaleType, Tools, Univer, UniverInstanceType } from '@univerjs/core';import { afterEach, describe, expect, it, vi } from 'vitest';+import { setupRenderTestEnv } from '../../../__tests__/render-test-utils';import { FontCache } from '../../docs/layout/shaping-engine/font-cache';-import { getGeneralNumberDisplayText } from '../sheet.render-skeleton';+import { getGeneralNumberDisplayText, SpreadsheetSkeleton } from '../sheet.render-skeleton';++describe('Rich-text render snapshot isolation', () => {+ it.each(['font cache', 'row height', 'column width'])(+ 'does not rewrite persisted rich text while calculating %s',+ (path) => {+ const environment = setupRenderTestEnv();+ const univer = new Univer({ locale: LocaleType.EN_US });+ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, {+ id: 'rich-render-isolation',+ sheetOrder: ['sheet'],+ sheets: {+ sheet: {+ id: 'sheet',+ name: 'Sheet',+ rowCount: 10,+ columnCount: 10,+ cellData: {+ 0: {+ 0: {+ v: '中文😀',+ p: {+ id: 'rich-cell',+ documentStyle: {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ pageSize: { width: 37, height: 80 },+ marginTop: 7,+ },+ body: {+ dataStream: '中文😀\r\n',+ paragraphs: [{ startIndex: 4, paragraphId: 'paragraph' }],+ sectionBreaks: [{ startIndex: 5, sectionId: 'section' }],+ textRuns: [{ st: 0, ed: 2, ts: { bl: 1 } }],+ },+ },+ },+ },+ },+ },+ },+ });+ const worksheet = workbook.getActiveSheet()!;+ const skeleton = univer.__getInjector().createInstance(SpreadsheetSkeleton, worksheet, workbook.getStyles());+ try {+ skeleton.calculate();+ const before = Tools.deepClone(workbook.getSnapshot());+ const cell = worksheet.getCellRaw(0, 0)!;+ if (path === 'font cache') {+ skeleton._setFontStylesCache(0, 0, cell, {}, false);+ expect(skeleton.stylesCache.fontMatrix.getValue(0, 0)?.documentSkeleton).toBeDefined();+ } else if (path === 'row height') {+ expect(skeleton.calculateAutoHeightForCell(0, 0)).toBeGreaterThan(0);+ } else {+ expect(skeleton._getMeasuredWidthByCell(cell, 0, 0, 0)).toBeGreaterThan(0);+ }+ expect(workbook.getSnapshot()).toEqual(before);+ } finally {+ skeleton.dispose();+ univer.dispose();+ environment.restore();+ }+ }+ );+});describe('General number display', () => {afterEach(() => {diff --git a/packages/engine-render/src/components/sheets/sheet.render-skeleton.ts b/packages/engine-render/src/components/sheets/sheet.render-skeleton.tsindex 02c964303e..01911cc267 100644--- a/packages/engine-render/src/components/sheets/sheet.render-skeleton.ts+++ b/packages/engine-render/src/components/sheets/sheet.render-skeleton.ts@@ -729,7 +729,7 @@ export class SpreadsheetSkeleton extends SheetSkeleton {colWidth -= sideGap;if (isRichText) {- const modelObject = cell && this.worksheet.getCellDocumentModel(cell, style);+ const modelObject = cell && this.worksheet.getCellDocumentModel(cell, style, { isDeepClone: true });if (modelObject == null) {return undefined;}@@ -957,7 +957,7 @@ export class SpreadsheetSkeleton extends SheetSkeleton {}}const style = this.worksheet.getComposedCellStyleByCellData(row, column, cell);- const modelObject = this.worksheet.getCellDocumentModel(cell, style);+ const modelObject = this.worksheet.getCellDocumentModel(cell, style, { isDeepClone: true });if (modelObject == null) {return measuredWidth;}@@ -1493,7 +1493,10 @@ export class SpreadsheetSkeleton extends SheetSkeleton {const isRichText = cellData?.p || vertexAngle || centerAngle;const modelObject = isRichText ?- this.worksheet.getCellDocumentModel(cellData, style, { displayRawFormula: this._renderRawFormula })+ this.worksheet.getCellDocumentModel(cellData, style, {+ isDeepClone: true,+ displayRawFormula: this._renderRawFormula,+ }): null;if (modelObject) {diff --git a/packages/engine-render/src/scene.input-manager.ts b/packages/engine-render/src/scene.input-manager.tsindex ecdaecc5b7..57d2d076f4 100644--- a/packages/engine-render/src/scene.input-manager.ts+++ b/packages/engine-render/src/scene.input-manager.ts@@ -53,6 +53,8 @@ export class InputManager extends Disposable {private _currentMouseEnterPicked: Nullable<BaseObject | Scene>;private _startingPosition = new Vector2(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY);+ private _pointerDownPosition: Nullable<Vector2>;+ private _pointerDragged = false;private _delayedTimeout: NodeJS.Timeout | number = -1;private _delayedTripeTimeout: NodeJS.Timeout | number = -1;private _doubleClickOccurred = 0;@@ -156,6 +158,7 @@ export class InputManager extends Disposable {}_onPointerLeave(evt: IPointerEvent) {+ this._resetClickSequence();// preserve compatibility with Safari when pointerId is not presentif (evt.pointerId === undefined) {evt.pointerId = 0;@@ -170,6 +173,9 @@ export class InputManager extends Disposable {if ((evt as IPointerEvent).pointerId === undefined) {(evt as unknown as PointerEvent).pointerId = 0;}+ if (this._pointerDownPosition && this._isPointerSwiping(evt.clientX, evt.clientY, this._pointerDownPosition)) {+ this._pointerDragged = true;+ }const currentObject = this._currentObject = this._getObjectAtPos(evt.offsetX, evt.offsetY);const isStop = (currentObject || this.capturedObject)?.triggerPointerMove(evt);@@ -188,6 +194,12 @@ export class InputManager extends Disposable {(evt as unknown as PointerEvent).pointerId = 0;}+ this._pointerDownPosition = new Vector2(evt.clientX, evt.clientY);+ this._pointerDragged = false;+ if (evt.button !== 0) {+ this._resetClickSequence();+ }+const currentObject = this._getObjectAtPos(evt.offsetX, evt.offsetY);const isStop = currentObject?.triggerPointerDown(evt);@@ -202,6 +214,10 @@ export class InputManager extends Disposable {evt.pointerId = 0;}+ const isClick = evt.button === 0 && this._pointerDownPosition != null && !this._pointerDragged &&+ !this._isPointerSwiping(evt.clientX, evt.clientY, this._pointerDownPosition);+ this._pointerDownPosition = null;+const currentObject = this._getObjectAtPos(evt.offsetX, evt.offsetY);const isStop = currentObject?.triggerPointerUp(evt);@@ -209,10 +225,16 @@ export class InputManager extends Disposable {this._scene.onPointerUp$.emitEvent(evt);}- this._prePointerDoubleOrTripleClick(evt);+ if (isClick) {+ this._prePointerDoubleOrTripleClick(evt);+ } else {+ this._resetClickSequence();+ }}_onPointerCancel(evt: IPointerEvent) {+ this._pointerDownPosition = null;+ this._resetClickSequence();this._scene.onPointerCancel$.emitEvent(evt);const currentObject = this._getObjectAtPos(evt.offsetX, evt.offsetY);currentObject?.triggerPointerCancel(evt);@@ -367,6 +389,8 @@ export class InputManager extends Disposable {* Detaches all event handlers*/detachControl() {+ this._pointerDownPosition = null;+ this._resetClickSequence();if (!this._alreadyAttached) {return;}@@ -448,10 +472,15 @@ export class InputManager extends Disposable {* @hidden* @returns Boolean if delta for pointer exceeds drag movement threshold*/- private _isPointerSwiping(pointerX: number, pointerY: number, threshold = InputManager.DragMovementThreshold): boolean {+ private _isPointerSwiping(+ pointerX: number,+ pointerY: number,+ origin = this._startingPosition,+ threshold = InputManager.DragMovementThreshold+ ): boolean {return (- Math.abs(this._startingPosition.x - pointerX) > threshold ||- Math.abs(this._startingPosition.y - pointerY) > threshold+ Math.abs(origin.x - pointerX) > threshold ||+ Math.abs(origin.y - pointerY) > threshold);}@@ -461,12 +490,13 @@ export class InputManager extends Disposable {? InputManager.TouchDoubleClickMovementThreshold: InputManager.DragMovementThreshold;- const isMoveThreshold = this._isPointerSwiping(clientX, clientY, movementThreshold);+ const isMoveThreshold = this._isPointerSwiping(clientX, clientY, this._startingPosition, movementThreshold);if (isMoveThreshold) {- this._resetDoubleClickParam();+ this._resetClickSequence();}+ clearTimeout(this._delayedTimeout);this._delayedTimeout = setTimeout(() => {this._resetDoubleClickParam();}, InputManager.DoubleClickDelay);@@ -502,6 +532,12 @@ export class InputManager extends Disposable {clearTimeout(this._delayedTimeout);}+ private _resetClickSequence() {+ this._resetDoubleClickParam();+ this._tripleClickState = false;+ clearTimeout(this._delayedTripeTimeout);+ }+get capturedObject() {return this._scene._capturedObject;}diff --git a/packages/find-replace/src/menu/__tests__/find-replace.menu.spec.ts b/packages/find-replace/src/menu/__tests__/find-replace.menu.spec.tsnew file mode 100644index 0000000000..5f3cb3bbaf--- /dev/null+++ b/packages/find-replace/src/menu/__tests__/find-replace.menu.spec.ts@@ -0,0 +1,83 @@+/**+ * 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 { EDITOR_ACTIVATED, FOCUSING_SHEET, IContextService, Univer } from '@univerjs/core';+import { afterEach, describe, expect, it } from 'vitest';+import { FIND_REPLACE_AVAILABLE } from '../../services/context-keys';+import { FindReplaceMenuItemFactory } from '../find-replace.menu';++describe('FindReplaceMenuItemFactory', () => {+ let univer: Univer | undefined;++ afterEach(() => {+ univer?.dispose();+ univer = undefined;+ });++ it.each([+ { availability: undefined, disabled: true, label: 'not initialized' },+ { availability: false, disabled: true, label: 'unavailable' },+ { availability: true, disabled: false, label: 'available' },+ ])('reflects a $label provider before any context changes', ({ availability, disabled }) => {+ univer = new Univer();+ const injector = univer.__getInjector();+ const contextService = injector.get(IContextService);+ contextService.setContextValue(EDITOR_ACTIVATED, false);+ contextService.setContextValue(FOCUSING_SHEET, true);+ if (availability !== undefined) {+ contextService.setContextValue(FIND_REPLACE_AVAILABLE, availability);+ }++ const values: boolean[] = [];+ const subscription = FindReplaceMenuItemFactory(injector).disabled$!.subscribe((value) => values.push(value));+ try {+ expect(values.length).toBeGreaterThan(0);+ expect(values[values.length - 1]).toBe(disabled);+ } finally {+ subscription.unsubscribe();+ }+ });++ it('tracks provider readiness and removal while preserving editor and focus restrictions', () => {+ univer = new Univer();+ const injector = univer.__getInjector();+ const contextService = injector.get(IContextService);+ contextService.setContextValue(EDITOR_ACTIVATED, false);+ contextService.setContextValue(FOCUSING_SHEET, true);+ const values: boolean[] = [];+ const subscription = FindReplaceMenuItemFactory(injector).disabled$!.subscribe((value) => values.push(value));+ try {+ expect(values[values.length - 1]).toBe(true);+ contextService.setContextValue(FIND_REPLACE_AVAILABLE, true);+ expect(values[values.length - 1]).toBe(false);+ contextService.setContextValue(EDITOR_ACTIVATED, true);+ expect(values[values.length - 1]).toBe(true);+ contextService.setContextValue(EDITOR_ACTIVATED, false);+ expect(values[values.length - 1]).toBe(false);+ contextService.setContextValue(FOCUSING_SHEET, false);+ expect(values[values.length - 1]).toBe(true);+ contextService.setContextValue(FOCUSING_SHEET, true);+ expect(values[values.length - 1]).toBe(false);+ contextService.setContextValue(FIND_REPLACE_AVAILABLE, false);+ expect(values[values.length - 1]).toBe(true);+ } finally {+ subscription.unsubscribe();+ }+ const finalCount = values.length;+ contextService.setContextValue(FIND_REPLACE_AVAILABLE, true);+ expect(values).toHaveLength(finalCount);+ });+});diff --git a/packages/find-replace/src/menu/find-replace.menu.ts b/packages/find-replace/src/menu/find-replace.menu.tsindex a274f64207..995dc1bdb3 100644--- a/packages/find-replace/src/menu/find-replace.menu.ts+++ b/packages/find-replace/src/menu/find-replace.menu.ts@@ -19,8 +19,9 @@ import type { IMenuButtonItem } from '@univerjs/ui';import type { LocaleKey } from '../locale/types';import { EDITOR_ACTIVATED, FOCUSING_SHEET, IContextService, UniverInstanceType } from '@univerjs/core';import { getMenuHiddenObservable, MenuItemType } from '@univerjs/ui';-import { combineLatest, map } from 'rxjs';+import { combineLatest, map, startWith } from 'rxjs';import { OpenFindDialogOperation } from '../commands/operations/find-replace.operation';+import { FIND_REPLACE_AVAILABLE } from '../services/context-keys';export function FindReplaceMenuItemFactory(accessor: IAccessor): IMenuButtonItem<LocaleKey> {const contextService = accessor.get(IContextService);@@ -34,6 +35,8 @@ export function FindReplaceMenuItemFactory(accessor: IAccessor): IMenuButtonItemdisabled$: combineLatest([contextService.subscribeContextValue$(EDITOR_ACTIVATED),contextService.subscribeContextValue$(FOCUSING_SHEET),- ]).pipe(map(([editorActivated, focusingSheet]) => editorActivated || !focusingSheet)),+ contextService.subscribeContextValue$(FIND_REPLACE_AVAILABLE)+ .pipe(startWith(contextService.getContextValue(FIND_REPLACE_AVAILABLE))),+ ]).pipe(map(([editorActivated, focusingSheet, available]) => editorActivated || !focusingSheet || !available)),};}diff --git a/packages/find-replace/src/views/dialog/FindReplaceDialog.tsx b/packages/find-replace/src/views/dialog/FindReplaceDialog.tsxindex b7d3b1c7ce..472db4907e 100644--- a/packages/find-replace/src/views/dialog/FindReplaceDialog.tsx+++ b/packages/find-replace/src/views/dialog/FindReplaceDialog.tsx@@ -47,9 +47,17 @@ const FIND_BY_OPTIONS: Array<{ label: LocaleKey; value: FindBy }> = [];function useFindInputFocus(findReplaceService: IFindReplaceService, ref: Parameters<typeof useImperativeHandle>[0]) {+ const pendingFocusFrameRef = useRef<number | null>(null);const focus = useCallback(() => {(document.querySelector('.univer-find-input input') as HTMLInputElement | null)?.focus();}, []);+ const focusAfterDialogClose = useCallback(() => {+ focus();+ pendingFocusFrameRef.current = requestAnimationFrame(() => {+ pendingFocusFrameRef.current = null;+ focus();+ });+ }, [focus]);const selectHasFocus = useCallback(() => {const allInputs = document.querySelectorAll('[data-u-comp=find-replace-dialog] [data-u-comp=search-input]');@@ -60,10 +68,15 @@ function useFindInputFocus(findReplaceService: IFindReplaceService, ref: ParametuseEffect(() => {const subscription = findReplaceService.focusSignal$.subscribe(() => focus());- return () => subscription.unsubscribe();+ return () => {+ subscription.unsubscribe();+ if (pendingFocusFrameRef.current !== null) {+ cancelAnimationFrame(pendingFocusFrameRef.current);+ }+ };}, [findReplaceService, focus]);- return { focus, selectHasFocus };+ return { focus, focusAfterDialogClose, selectHasFocus };}export const FindDialog = forwardRef(function FindDialogImpl(_props, ref) {@@ -147,7 +160,7 @@ export const ReplaceDialog = forwardRef(function ReplaceDialogImpl(_props, ref)[findReplaceService]);- const { focus } = useFindInputFocus(findReplaceService, ref);+ const { focusAfterDialogClose } = useFindInputFocus(findReplaceService, ref);const onClickFindButton = useCallback(() => {if (findString === inputtingFindString) {@@ -160,8 +173,8 @@ export const ReplaceDialog = forwardRef(function ReplaceDialogImpl(_props, ref)const onClickReplaceButton = useCallback(() => commandService.executeCommand(ReplaceCurrentMatchCommand.id), [commandService]);const onClickReplaceAllButton = useCallback(async () => {await commandService.executeCommand(ReplaceAllMatchesCommand.id);- focus();- }, [commandService, focus]);+ focusAfterDialogClose();+ }, [commandService, focusAfterDialogClose]);const onChangeFindDirection = useCallback((findDirection: string) => {findReplaceService.changeFindDirection(findDirection as FindDirection);diff --git a/packages/sheets-data-validation-ui/package.json b/packages/sheets-data-validation-ui/package.jsonindex b1d913d5ba..0bdde753f5 100644--- a/packages/sheets-data-validation-ui/package.json+++ b/packages/sheets-data-validation-ui/package.json@@ -89,6 +89,8 @@},"devDependencies": {"@univerjs-infra/shared": "workspace:*",+ "@univerjs/docs": "workspace:*",+ "@univerjs/docs-ui": "workspace:*","postcss": "^8.5.26","react": "18.3.1","rxjs": "^7.8.2",diff --git a/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-alert.controller.spec.ts b/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-alert.controller.spec.tsindex 000561715c..b16a995cb6 100644--- a/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-alert.controller.spec.ts+++ b/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-alert.controller.spec.ts@@ -14,9 +14,28 @@* limitations under the License.*/-import { DataValidationStatus } from '@univerjs/core';-import { Subject } from 'rxjs';+import type { IHoverCellPosition } from '@univerjs/sheets-ui';+import type { Subject } from 'rxjs';+import {+ DataValidationOperator,+ DataValidationStatus,+ DataValidationType,+ IUniverInstanceService,+ LocaleService,+} from '@univerjs/core';+import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';+import { IRefSelectionsService, RefSelectionsService, SetRangeValuesMutation } from '@univerjs/sheets';+import { AddSheetDataValidationCommand } from '@univerjs/sheets-data-validation';+import {+ CellAlertManagerService,+ CellPopupManagerService,+ HoverManagerService,+ SheetCanvasPopManagerService,+} from '@univerjs/sheets-ui';+import { CanvasPopupService, ICanvasPopupService } from '@univerjs/ui';import { afterEach, describe, expect, it, vi } from 'vitest';+import { createDvUiTestBed } from '../../__tests__/create-dv-ui-test-bed';+import enUS from '../../locale/en-US';import { DataValidationAlertController } from '../dv-alert.controller';afterEach(() => {@@ -24,66 +43,64 @@ afterEach(() => {});describe('DataValidationAlertController', () => {- it('shows an alert for invalid hovered cells and clears it on repeated hover', async () => {+ it.each(['active', 'inactive', 'disposed', 'switched-after-open'] as const)('handles delayed validation hover for a %s worksheet', async (state) => {vi.useFakeTimers();- const currentCell$ = new Subject<{ location: { unitId: string; subUnitId: string; row: number; col: number } }>();- const currentAlert = new Map<string, { alert: { location: { unitId: string; subUnitId: string; row: number; col: number } } }>();- const showAlert = vi.fn((alert) => currentAlert.set('SHEET_DATA_VALIDATION_ALERT', { alert }));- const removeAlert = vi.fn((key: string) => currentAlert.delete(key));- const dataValidationModel = {- getRuleByLocation: vi.fn(() => ({ uid: 'rule-1', type: 'list' })),- validator: vi.fn(() => DataValidationStatus.INVALID),- getValidator: vi.fn(() => ({ getRuleFinalError: vi.fn(() => 'invalid list value') })),- };-- const controller = new DataValidationAlertController(- { currentCell$ } as never,- { currentAlert, removeAlert, showAlert } as never,- { getUnit: vi.fn(() => ({ getSheetBySheetId: vi.fn(() => ({ getSheetId: () => 'sheet-1' })) })) } as never,- { t: (key: string) => key } as never,- dataValidationModel as never- );-- expect(controller).toBeTruthy();-- const location = { unitId: 'book-1', subUnitId: 'sheet-1', row: 1, col: 2 };- currentCell$.next({ location });- await vi.advanceTimersByTimeAsync(120);-- expect(showAlert).toHaveBeenCalledWith(expect.objectContaining({- key: 'SHEET_DATA_VALIDATION_ALERT',- title: 'sheets-data-validation-ui.error.title',- message: 'invalid list value',- location,- }));-- currentCell$.next({ location });- await vi.advanceTimersByTimeAsync(120);- expect(removeAlert).toHaveBeenCalledWith('SHEET_DATA_VALIDATION_ALERT');- });-- it('removes alerts when the hovered cell has no validation rule', async () => {- vi.useFakeTimers();- const currentCell$ = new Subject<{ location: { unitId: string; subUnitId: string; row: number; col: number } }>();- const removeAlert = vi.fn();-- const controller = new DataValidationAlertController(- { currentCell$ } as never,- { currentAlert: new Map(), removeAlert, showAlert: vi.fn() } as never,- { getUnit: vi.fn(() => ({ getSheetBySheetId: vi.fn(() => ({ getSheetId: () => 'sheet-1' })) })) } as never,- { t: (key: string) => key } as never,- {- getRuleByLocation: vi.fn(() => null),- validator: vi.fn(),- getValidator: vi.fn(),- } as never- );-- expect(controller).toBeTruthy();-- currentCell$.next({ location: { unitId: 'book-1', subUnitId: 'sheet-1', row: 3, col: 4 } });- await vi.advanceTimersByTimeAsync(120);-- expect(removeAlert).toHaveBeenCalledWith('SHEET_DATA_VALIDATION_ALERT');+ const { univer, injector, workbook, commandService, dataValidationModel } = createDvUiTestBed();+ try {+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);+ injector.add([ICanvasPopupService, { useClass: CanvasPopupService }]);+ injector.add([IRefSelectionsService, { useClass: RefSelectionsService }]);+ injector.add([SheetCanvasPopManagerService]);+ injector.add([CellPopupManagerService]);+ injector.add([CellAlertManagerService]);+ injector.add([HoverManagerService]);+ injector.add([DataValidationAlertController]);+ injector.get(LocaleService).load({ enUS });+ injector.get(DataValidationAlertController);+ const rule = {+ uid: 'delayed-alert-rule',+ type: DataValidationType.DECIMAL,+ operator: DataValidationOperator.GREATER_THAN,+ formula1: '111',+ ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }],+ };+ commandService.syncExecuteCommand(SetRangeValuesMutation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ cellValue: { 0: { 0: { v: 1 } } },+ });+ commandService.syncExecuteCommand(AddSheetDataValidationCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ rule,+ });+ const location = { unitId: 'test', subUnitId: 'sheet1', row: 0, col: 0 };+ const validation = { ...location, workbook, worksheet: workbook.getActiveSheet() };+ dataValidationModel.validator(rule, validation);+ await vi.advanceTimersByTimeAsync(0);+ expect(dataValidationModel.validator(rule, validation)).toBe(DataValidationStatus.INVALID);+ const hover = injector.get(HoverManagerService);+ const input = hover as unknown as { _currentCell$: Subject<IHoverCellPosition> };+ input._currentCell$.next({ location } as IHoverCellPosition);+ if (state === 'inactive') {+ workbook.setActiveSheet(workbook.getSheetBySheetId('sheet2')!);+ } else if (state === 'disposed') {+ injector.get(IUniverInstanceService).disposeUnit(workbook.getUnitId());+ }+ await vi.advanceTimersByTimeAsync(120);+ const alerts = injector.get(CellAlertManagerService);+ expect(alerts.currentAlert.size).toBe(state === 'active' || state === 'switched-after-open' ? 1 : 0);+ if (state === 'switched-after-open') {+ workbook.setActiveSheet(workbook.getSheetBySheetId('sheet2')!);+ expect(alerts.currentAlert.size).toBe(0);+ }+ if (state === 'active') {+ hover.triggerScroll();+ await vi.advanceTimersByTimeAsync(120);+ expect(alerts.currentAlert.size).toBe(0);+ }+ } finally {+ univer.dispose();+ }});});diff --git a/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-render.controller.spec.ts b/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-render.controller.spec.tsindex 84ee8db416..0d3f3d1b74 100644--- a/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-render.controller.spec.ts+++ b/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-render.controller.spec.ts@@ -14,110 +14,264 @@* limitations under the License.*/-import type { IWorkbookData, Workbook } from '@univerjs/core';-import { DataValidationStatus, DataValidationType, InterceptorEffectEnum, LocaleType, Univer, UniverInstanceType } from '@univerjs/core';-import { DataValidatorRegistryService } from '@univerjs/data-validation';-import { IRenderManagerService } from '@univerjs/engine-render';-import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';-import { DataValidationCacheService, SheetDataValidationModel } from '@univerjs/sheets-data-validation';-import { AutoHeightController } from '@univerjs/sheets-ui';-import { IMenuManagerService } from '@univerjs/ui';-import { Subject } from 'rxjs';-import { describe, expect, it, vi } from 'vitest';+import type { Ctor, ICommandInfo, IDisposable, IWorkbookData, Workbook } from '@univerjs/core';+import type { ISetWorksheetRowAutoHeightMutationParams } from '@univerjs/sheets';+import {+ DataValidationRenderMode,+ DataValidationStatus,+ DataValidationType,+ ICommandService,+ ILogService,+ InterceptorEffectEnum,+ IUniverInstanceService,+ LocaleService,+ LocaleType,+ LogLevel,+ Tools,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { AddDataValidationMutation, DataValidatorRegistryService } from '@univerjs/data-validation';+import { DocSelectionManagerService } from '@univerjs/docs';+import { EditorService, IEditorService } from '@univerjs/docs-ui';+import {+ CanvasColorService,+ ICanvasColorService,+ IRenderManagerService,+ RenderManagerService,+} from '@univerjs/engine-render';+import {+ INTERCEPTOR_POINT,+ IRefSelectionsService,+ SetWorksheetRowAutoHeightMutation,+ SheetInterceptorService,+ SheetsSelectionsService,+ UniverSheetsPlugin,+} from '@univerjs/sheets';+import { DataValidationCacheService, UniverSheetsDataValidationPlugin } from '@univerjs/sheets-data-validation';+import {+ AutoHeightController,+ EditorBridgeService,+ IEditorBridgeService,+ ISheetCellDropdownManagerService,+ SheetCanvasPopManagerService,+ SheetCellDropdownManagerService,+ SheetSkeletonManagerService,+} from '@univerjs/sheets-ui';+import { CanvasPopupService, ICanvasPopupService, IMenuManagerService, MenuManagerService } from '@univerjs/ui';+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import enUS from '../../locale/en-US';import { DataValidationDropdownManagerService } from '../../services/dropdown-manager.service';import { SheetsDataValidationRenderController } from '../dv-render.controller';+import { SheetsDataValidationMobileRenderController } from '../mobile/dv-render.controller';+import { SheetsDataValidationUIController } from '../ui.controller';-describe('SheetsDataValidationRenderController', () => {- it('adds invalid markers, dropdown canvas renderer and list-cell layout behavior through the cell interceptor', () => {- const univer = new Univer();- const injector = univer.__getInjector();- const canvasRender = {- calcCellAutoHeight: vi.fn(() => 36),- calcCellAutoWidth: vi.fn(() => 120),- };- const skeleton = {- worksheet: { getMergedCell: vi.fn(() => null) },- getCellWithCoordByIndex: vi.fn(() => ({ startX: 10, startY: 20 })),- };-- injector.add([IMenuManagerService, { useValue: { mergeMenu: vi.fn() } as never }]);- injector.add([IRenderManagerService, {- useValue: {- getRenderUnitById: vi.fn(() => ({- with: vi.fn(() => ({- getSkeletonParam: vi.fn(() => ({ skeleton })),- })),- })),- } as never,- }]);- injector.add([AutoHeightController, { useValue: { getUndoRedoParamsOfAutoHeight: vi.fn(() => ({ redos: [], undos: [] })) } as never }]);- injector.add([DataValidationDropdownManagerService, { useValue: { activeDropdown: null, hideDropdown: vi.fn(), showDropdown: vi.fn() } as never }]);- injector.add([SheetDataValidationModel, {- useValue: {- getRuleIdByLocation: vi.fn(() => 'rule-1'),- getRuleById: vi.fn(() => ({ uid: 'rule-1', type: DataValidationType.LIST })),- ruleChange$: new Subject(),- } as never,- }]);- injector.add([DataValidatorRegistryService, {- useValue: {- getValidatorItem: vi.fn(() => ({- canvasRender,- dropdownType: 'list',- skipDefaultFontRender: vi.fn(() => true),- getExtraStyle: vi.fn(() => ({ bg: { rgb: '#fff3cd' } })),- })),- } as never,- }]);- injector.add([SheetInterceptorService]);- injector.add([DataValidationCacheService, { useValue: { getValue: vi.fn(() => DataValidationStatus.INVALID) } as never }]);- injector.add([SheetsDataValidationRenderController]);-- const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, {- id: 'unit-1',- appVersion: '3.0.0-alpha',- locale: LocaleType.EN_US,- name: 'Test workbook',- styles: {},- sheetOrder: ['sheet-1'],- sheets: {- 'sheet-1': {- id: 'sheet-1',- name: 'Sheet 1',- cellData: { 1: { 2: { v: 'bad' } } },- },- },+vi.hoisted(() => {+ vi.stubGlobal('Path2D', class {});+});++afterAll(() => vi.unstubAllGlobals());++const controllers: Ctor<IDisposable>[] = [SheetsDataValidationRenderController, SheetsDataValidationMobileRenderController];++for (const Controller of controllers) {+ describe(Controller.name, () => {+ let univer: Univer;+ let peer: Workbook;+ let first: Workbook;+ let second: Workbook;++ beforeEach(() => {+ vi.useFakeTimers();+ // Only the unavailable Canvas backend is replaced; controllers and providers are real.+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(function (this: HTMLCanvasElement) {+ return {+ canvas: this,+ setTransform: vi.fn(),+ clearRect: vi.fn(),+ measureText: (text: string) => ({+ width: text.length * 7,+ fontBoundingBoxAscent: 10,+ fontBoundingBoxDescent: 4,+ actualBoundingBoxAscent: 10,+ actualBoundingBoxDescent: 4,+ }),+ } as unknown as CanvasRenderingContext2D;+ });+ univer = new Univer();+ univer.registerPlugin(UniverSheetsPlugin, { notExecuteFormula: true });+ univer.registerPlugin(UniverSheetsDataValidationPlugin);+ peer = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, workbookSnapshot('peer', 70));+ const injector = univer.__getInjector();+ injector.get(ILogService).setLogLevel(LogLevel.SILENT);+ injector.get(LocaleService).load({ enUS });+ injector.get(LocaleService).setLocale(LocaleType.EN_US);+ injector.add([ICanvasColorService, { useClass: CanvasColorService }]);+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);+ injector.add([AutoHeightController]);+ injector.add([DocSelectionManagerService]);+ injector.add([IEditorService, { useClass: EditorService }]);+ injector.add([IEditorBridgeService, { useClass: EditorBridgeService }]);+ injector.add([IRefSelectionsService, { useClass: SheetsSelectionsService }]);+ injector.add([ICanvasPopupService, { useClass: CanvasPopupService }]);+ injector.add([SheetCanvasPopManagerService]);+ injector.add([ISheetCellDropdownManagerService, { useClass: SheetCellDropdownManagerService }]);+ injector.add([DataValidationDropdownManagerService]);+ injector.add([IMenuManagerService, { useClass: MenuManagerService }]);+ injector.add([Controller]);+ injector.add([SheetsDataValidationUIController]);+ const instances = injector.get(IUniverInstanceService);+ first = instances.createUnit<IWorkbookData, Workbook>(+ UniverInstanceType.UNIVER_SHEET,+ workbookSnapshot('first', 50),+ { makeCurrent: false }+ );+ second = instances.createUnit<IWorkbookData, Workbook>(+ UniverInstanceType.UNIVER_SHEET,+ workbookSnapshot('second', 60),+ { makeCurrent: false }+ );+ const renders = injector.get(IRenderManagerService);+ renders.registerRenderModule(UniverInstanceType.UNIVER_SHEET, [SheetSkeletonManagerService]);+ for (const workbook of [peer, first, second]) {+ renders.createRender(workbook.getUnitId());+ }+ injector.get(SheetsDataValidationUIController);+ injector.get(Controller);});- const worksheet = workbook.getSheetBySheetId('sheet-1')!;- const controller = injector.get(SheetsDataValidationRenderController);- const rawCell = { v: 'bad', markers: { bl: { size: 1 } }, coverable: true } as never;- const result = injector.get(SheetInterceptorService).fetchThroughInterceptors(- INTERCEPTOR_POINT.CELL_CONTENT,- InterceptorEffectEnum.Style- )(rawCell, {- row: 1,- col: 2,- unitId: 'unit-1',- subUnitId: 'sheet-1',- rawData: rawCell,- workbook,- worksheet,++ afterEach(() => {+ vi.clearAllTimers();+ univer.dispose();+ vi.restoreAllMocks();+ vi.useRealTimers();+ });++ it('keeps each workbook and worksheet in a shared batch isolated after focus changes', async () => {+ const injector = univer.__getInjector();+ const instances = injector.get(IUniverInstanceService);+ instances.setCurrentUnitForType('first');+ const peerBefore = Tools.deepClone(peer.getSnapshot());+ const heights: ISetWorksheetRowAutoHeightMutationParams[] = [];+ const commands = injector.get(ICommandService);+ const listener = commands.onCommandExecuted((command: ICommandInfo) => {+ if (command.id === SetWorksheetRowAutoHeightMutation.id) {+ heights.push(command.params as ISetWorksheetRowAutoHeightMutationParams);+ }+ });+ addRule(univer, 'first', 'sheet1', 1, DataValidationType.LIST);+ addRule(univer, 'first', 'sheet1', 2, DataValidationType.LIST_MULTIPLE);+ addRule(univer, 'first', 'sheet2', 3, DataValidationType.LIST);+ addRule(univer, 'second', 'sheet1', 4, DataValidationType.LIST_MULTIPLE);+ instances.setCurrentUnitForType('peer');+ instances.focusUnit('peer');+ expect(first.getSheetBySheetId('sheet1')!.getRowHeight(1)).toBe(100);+ await vi.advanceTimersByTimeAsync(100);++ expect(first.getSheetBySheetId('sheet1')!.getRowHeight(1)).toBe(50);+ expect(first.getSheetBySheetId('sheet1')!.getRowHeight(2)).toBe(50);+ expect(first.getSheetBySheetId('sheet2')!.getRowHeight(3)).toBe(55);+ expect(second.getSheetBySheetId('sheet1')!.getRowHeight(4)).toBe(60);+ expect(first.getSheetBySheetId('sheet1')!.getRowHeight(4)).toBe(100);+ expect(peer.getSnapshot()).toEqual(peerBefore);+ expect(heights).toHaveLength(3);+ expect(heights).toEqual(expect.arrayContaining([+ { unitId: 'first', subUnitId: 'sheet1', rowsAutoHeightInfo: [{ row: 1, autoHeight: 50 }, { row: 2, autoHeight: 50 }] },+ { unitId: 'first', subUnitId: 'sheet2', rowsAutoHeightInfo: [{ row: 3, autoHeight: 55 }] },+ { unitId: 'second', subUnitId: 'sheet1', rowsAutoHeightInfo: [{ row: 4, autoHeight: 60 }] },+ ]));+ listener.dispose();+ });++ it('cancels buffered and future work when its controller is disposed', async () => {+ const injector = univer.__getInjector();+ injector.get(IUniverInstanceService).setCurrentUnitForType('first');+ addRule(univer, 'first', 'sheet1', 1, DataValidationType.LIST);+ injector.get(Controller).dispose();+ addRule(univer, 'first', 'sheet1', 2, DataValidationType.LIST);+ const before = Tools.deepClone(first.getSnapshot());+ await vi.advanceTimersByTimeAsync(200);+ expect(first.getSnapshot()).toEqual(before);+ });++ it('ignores patched changes and non-list rules without suppressing command-origin list changes', async () => {+ addRule(univer, 'first', 'sheet1', 1, DataValidationType.LIST, 'patched');+ addRule(univer, 'first', 'sheet1', 2, DataValidationType.WHOLE);+ addRule(univer, 'first', 'sheet1', 3, DataValidationType.LIST);+ await vi.advanceTimersByTimeAsync(100);+ const sheet = first.getSheetBySheetId('sheet1')!;+ expect([sheet.getRowHeight(1), sheet.getRowHeight(2), sheet.getRowHeight(3)]).toEqual([100, 100, 50]);+ });++ it('discards a disposed target without changing the current workbook', async () => {+ addRule(univer, 'first', 'sheet1', 1, DataValidationType.LIST);+ const before = Tools.deepClone(peer.getSnapshot());+ univer.__getInjector().get(IUniverInstanceService).disposeUnit('first');+ await vi.advanceTimersByTimeAsync(100);+ expect(peer.getSnapshot()).toEqual(before);+ });++ it('preserves invalid markers, custom rendering, and list layout through real cell interceptors', () => {+ const injector = univer.__getInjector();+ addRule(univer, 'peer', 'sheet1', 1, DataValidationType.LIST, 'patched');+ injector.get(DataValidationCacheService).ensureCache('peer', 'sheet1').setValue(1, 0, DataValidationStatus.INVALID);+ const worksheet = peer.getSheetBySheetId('sheet1')!;+ const raw = { v: 'bad', markers: { bl: { size: 1, color: '#112233' } } };+ const cell = injector.get(SheetInterceptorService).fetchThroughInterceptors(+ INTERCEPTOR_POINT.CELL_CONTENT,+ InterceptorEffectEnum.Style+ )(raw, { row: 1, col: 0, unitId: 'peer', subUnitId: 'sheet1', rawData: raw, workbook: peer, worksheet })!;+ const validator = injector.get(DataValidatorRegistryService).getValidatorItem(DataValidationType.LIST)!;++ expect(cell).not.toBe(raw);+ expect(cell.markers?.bl).toEqual(raw.markers.bl);+ expect(cell.markers?.tr?.size).toBeGreaterThan(0);+ expect(cell.customRender).toContain(validator.canvasRender);+ expect(cell.fontRenderExtension?.isSkip).toBe(true);+ expect(cell.coverable).toBe(false);+ expect(cell.interceptorAutoHeight?.()).toBeGreaterThan(0);+ expect(cell.interceptorAutoWidth?.()).toBeGreaterThan(0);});- const intercepted = result!;-- expect(intercepted).not.toBe(rawCell);- expect(intercepted.markers).toEqual(expect.objectContaining({- bl: { size: 1 },- tr: { size: 6, color: '#fe4b4b' },- }));- expect(intercepted.customRender).toContain(canvasRender);- expect(intercepted.fontRenderExtension?.isSkip).toBe(true);- expect(intercepted.interceptorStyle).toEqual({ bg: { rgb: '#fff3cd' } });- expect(intercepted.coverable).toBe(false);- expect(intercepted.interceptorAutoHeight?.()).toBe(36);- expect(intercepted.interceptorAutoWidth?.()).toBe(120);-- controller.dispose();- univer.dispose();});-});+}++function addRule(+ univer: Univer,+ unitId: string,+ subUnitId: string,+ row: number,+ type: DataValidationType,+ source: 'command' | 'patched' = 'command'+) {+ expect(univer.__getInjector().get(ICommandService).syncExecuteCommand(AddDataValidationMutation.id, {+ unitId,+ subUnitId,+ source,+ rule: {+ uid: `rule-${row}`,+ type,+ formula1: 'red,blue',+ ranges: [{ startRow: row, endRow: row, startColumn: 0, endColumn: 0 }],+ renderMode: DataValidationRenderMode.CUSTOM,+ },+ })).toBe(true);+}++function workbookSnapshot(id: string, defaultRowHeight: number): IWorkbookData {+ return {+ id,+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: id,+ styles: {},+ sheetOrder: ['sheet1', 'sheet2'],+ sheets: Object.fromEntries(['sheet1', 'sheet2'].map((sheetId, index) => [sheetId, {+ id: sheetId,+ name: sheetId,+ rowCount: 6,+ columnCount: 3,+ defaultRowHeight: defaultRowHeight + index * 5,+ rowData: { 1: { ah: 100 }, 2: { ah: 100 }, 3: { ah: 100 }, 4: { ah: 100 } },+ }])),+ };+}diff --git a/packages/sheets-data-validation-ui/src/controllers/dv-alert.controller.ts b/packages/sheets-data-validation-ui/src/controllers/dv-alert.controller.tsindex dc9a6c3b1e..06f46ca635 100644--- a/packages/sheets-data-validation-ui/src/controllers/dv-alert.controller.ts+++ b/packages/sheets-data-validation-ui/src/controllers/dv-alert.controller.ts@@ -27,7 +27,7 @@ import {} from '@univerjs/core';import { SheetDataValidationModel } from '@univerjs/sheets-data-validation';import { CellAlertManagerService, CellAlertType, HoverManagerService } from '@univerjs/sheets-ui';-import { debounceTime } from 'rxjs';+import { debounceTime, of, switchMap } from 'rxjs';const ALERT_KEY = 'SHEET_DATA_VALIDATION_ALERT';@@ -48,9 +48,17 @@ export class DataValidationAlertController extends Disposable {}private _initCellAlertPopup() {+ this.disposeWithMe(this._univerInstanceService.getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET).pipe(+ switchMap((workbook) => workbook?.activeSheet$ ?? of(null))+ ).subscribe(() => this._cellAlertManagerService.removeAlert(ALERT_KEY)));+this.disposeWithMe(this._hoverManagerService.currentCell$.pipe(debounceTime(100)).subscribe((cellPos) => {if (cellPos) {- const workbook = this._univerInstanceService.getUnit<Workbook>(cellPos.location.unitId, UniverInstanceType.UNIVER_SHEET)!;+ const workbook = this._univerInstanceService.getUnit<Workbook>(cellPos.location.unitId, UniverInstanceType.UNIVER_SHEET);+ if (!workbook || workbook.getActiveSheet()?.getSheetId() !== cellPos.location.subUnitId) {+ this._cellAlertManagerService.removeAlert(ALERT_KEY);+ return;+ }const worksheet = workbook.getSheetBySheetId(cellPos.location.subUnitId);if (!worksheet) return;const rule = this._dataValidationModel.getRuleByLocation(cellPos.location.unitId, cellPos.location.subUnitId, cellPos.location.row, cellPos.location.col);diff --git a/packages/sheets-data-validation-ui/src/controllers/dv-render.controller.ts b/packages/sheets-data-validation-ui/src/controllers/dv-render.controller.tsindex 6a27d5f9f5..8bf3a7aff8 100644--- a/packages/sheets-data-validation-ui/src/controllers/dv-render.controller.ts+++ b/packages/sheets-data-validation-ui/src/controllers/dv-render.controller.ts@@ -15,14 +15,26 @@*/import type { CellValue, ICellRenderContext, IRange, Nullable, Workbook } from '@univerjs/core';-import { DataValidationStatus, DataValidationType, ICommandService, Inject, InterceptorEffectEnum, IUniverInstanceService, Optional, RxDisposable, sequenceExecute, UniverInstanceType } from '@univerjs/core';+import type { IRuleChange } from '@univerjs/data-validation';+import {+ DataValidationStatus,+ DataValidationType,+ ICommandService,+ Inject,+ InterceptorEffectEnum,+ IUniverInstanceService,+ Optional,+ RxDisposable,+ sequenceExecute,+ UniverInstanceType,+} from '@univerjs/core';import { DataValidatorRegistryService } from '@univerjs/data-validation';import { IRenderManagerService } from '@univerjs/engine-render';import { InterceptCellContentPriority, INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';import { DataValidationCacheService, getCellValueOrigin, SheetDataValidationModel } from '@univerjs/sheets-data-validation';import { AutoHeightController, IEditorBridgeService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';import { IMenuManagerService } from '@univerjs/ui';-import { bufferTime, filter } from 'rxjs';+import { bufferTime, filter, takeUntil } from 'rxjs';import { menuSchema } from '../menu/schema';import { DataValidationDropdownManagerService } from '../services/dropdown-manager.service';@@ -250,26 +262,41 @@ export class SheetsDataValidationRenderController extends RxDisposable {// patched data-validation change don't need to re-calc row height// re-calc of row height will be triggered precisely by the origin commandfilter((change) => change.source === 'command'),- bufferTime(100)+ bufferTime(100),+ takeUntil(this.dispose$)).subscribe((infos) => {- if (infos.length === 0) {- return;- }-- const ranges: IRange[] = [];- infos.forEach((info) => {- if (info.rule.type === DataValidationType.LIST_MULTIPLE || info.rule.type === DataValidationType.LIST) {- if (info.rule?.ranges) {- ranges.push(...info.rule.ranges);- }- }- });-- if (ranges.length) {- const mutations = this._autoHeightController.getUndoRedoParamsOfAutoHeight(ranges);- sequenceExecute(mutations.redos, this._commandService);- }+ recalculateAutoHeight(infos, this._autoHeightController, this._commandService);});}}+export function recalculateAutoHeight(+ infos: IRuleChange[],+ autoHeightController: AutoHeightController,+ commandService: ICommandService+) {+ const rangesByUnit = new Map<string, Map<string, IRange[]>>();+ for (const { unitId, subUnitId, rule } of infos) {+ if (rule.type !== DataValidationType.LIST && rule.type !== DataValidationType.LIST_MULTIPLE) {+ continue;+ }+ if (!rule.ranges?.length) {+ continue;+ }+ let rangesBySheet = rangesByUnit.get(unitId);+ if (!rangesBySheet) {+ rangesBySheet = new Map();+ rangesByUnit.set(unitId, rangesBySheet);+ }+ const ranges = rangesBySheet.get(subUnitId) ?? [];+ ranges.push(...rule.ranges);+ rangesBySheet.set(subUnitId, ranges);+ }++ for (const [unitId, rangesBySheet] of rangesByUnit) {+ for (const [subUnitId, ranges] of rangesBySheet) {+ const mutations = autoHeightController.getUndoRedoParamsOfAutoHeight(ranges, subUnitId, undefined, unitId);+ sequenceExecute(mutations.redos, commandService);+ }+ }+}diff --git a/packages/sheets-data-validation-ui/src/controllers/mobile/dv-render.controller.ts b/packages/sheets-data-validation-ui/src/controllers/mobile/dv-render.controller.tsindex d9fa8d14be..042066af46 100644--- a/packages/sheets-data-validation-ui/src/controllers/mobile/dv-render.controller.ts+++ b/packages/sheets-data-validation-ui/src/controllers/mobile/dv-render.controller.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { ICellRenderContext, IRange } from '@univerjs/core';+import type { ICellRenderContext } from '@univerjs/core';import {DataValidationStatus,DataValidationType,@@ -22,14 +22,14 @@ import {Inject,InterceptorEffectEnum,RxDisposable,- sequenceExecute,} from '@univerjs/core';import { DataValidatorRegistryService } from '@univerjs/data-validation';import { IRenderManagerService } from '@univerjs/engine-render';import { InterceptCellContentPriority, INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';import { DataValidationCacheService, getCellValueOrigin, SheetDataValidationModel } from '@univerjs/sheets-data-validation';import { AutoHeightController, SheetSkeletonManagerService } from '@univerjs/sheets-ui';-import { bufferTime, filter } from 'rxjs';+import { bufferTime, filter, takeUntil } from 'rxjs';+import { recalculateAutoHeight } from '../dv-render.controller';const INVALID_MARK = {tr: {@@ -166,22 +166,11 @@ export class SheetsDataValidationMobileRenderController extends RxDisposable {this._sheetDataValidationModel.ruleChange$.pipe(filter((change) => change.source === 'command'),- bufferTime(16)+ bufferTime(16),+ takeUntil(this.dispose$)).subscribe((infos) => {- const ranges: IRange[] = [];- infos.forEach((info) => {- if (info.rule.type === DataValidationType.LIST_MULTIPLE || info.rule.type === DataValidationType.LIST) {- if (info.rule?.ranges) {- ranges.push(...info.rule.ranges);- }- }- });-- if (ranges.length) {- const mutations = this._autoHeightController.getUndoRedoParamsOfAutoHeight(ranges);- sequenceExecute(mutations.redos, this._commandService);- }+ recalculateAutoHeight(infos, this._autoHeightController, this._commandService);});}}diff --git a/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts b/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.tsindex ec56656933..2379b4b658 100644--- a/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts+++ b/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts@@ -853,7 +853,7 @@ export class SheetFindModel extends FindModel {}const isSame = isSamePosition(range, matchRange);- return stayIfOnMatch ? isSame : !isSame;+ return stayIfOnMatch || !isSame;});if (index === -1) {diff --git a/packages/sheets-formula-ui/package.json b/packages/sheets-formula-ui/package.jsonindex fd52deefbb..ee6f9c9a2c 100644--- a/packages/sheets-formula-ui/package.json+++ b/packages/sheets-formula-ui/package.json@@ -102,6 +102,7 @@"@univerjs-infra/shared": "workspace:*","postcss": "^8.5.26","react": "18.3.1",+ "react-dom": "18.3.1","rxjs": "^7.8.2","tailwindcss": "3.4.18","typescript": "^6.0.3",diff --git a/packages/sheets-formula-ui/src/controllers/__tests__/formula-clipboard.controller.spec.ts b/packages/sheets-formula-ui/src/controllers/__tests__/formula-clipboard.controller.spec.tsindex aca7554cd7..cf73353681 100644--- a/packages/sheets-formula-ui/src/controllers/__tests__/formula-clipboard.controller.spec.ts+++ b/packages/sheets-formula-ui/src/controllers/__tests__/formula-clipboard.controller.spec.ts@@ -100,7 +100,6 @@ interface ITestSheetClipboardService extends ISheetClipboardService {matrixFragment: Nullable<ObjectMatrix<ICellDataWithSpanInfo>>;copyId: string;};- _pasteInternal: (copyId: string, pasteType: string) => Promise<boolean>;}class testMarkSelectionService {@@ -595,7 +594,7 @@ describe('Test cut command with formulas', () => {},]);- await testSheetClipboardService._pasteInternal(copyId, PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE);+ expect(await sheetClipboardService.pasteByCopyId(copyId, PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE)).toBe(true);}it('cut-moving a referenced value range updates direct, range, mixed-absolute, cross-sheet, and shared formulas', async () => {diff --git a/packages/sheets-formula-ui/src/services/render-services/__tests__/ref-selections.render.service.spec.ts b/packages/sheets-formula-ui/src/services/render-services/__tests__/ref-selections.render.service.spec.tsindex 958072103a..329cfbc761 100644--- a/packages/sheets-formula-ui/src/services/render-services/__tests__/ref-selections.render.service.spec.ts+++ b/packages/sheets-formula-ui/src/services/render-services/__tests__/ref-selections.render.service.spec.ts@@ -15,7 +15,7 @@*/import type { IDisposable, IWorkbookData, Workbook } from '@univerjs/core';-import type { IRenderContext } from '@univerjs/engine-render';+import type { IPointerEvent, IRenderContext } from '@univerjs/engine-render';import type { ISelectionWithStyle } from '@univerjs/sheets';import {IContextService,@@ -33,13 +33,23 @@ import {Univer,UniverInstanceType,} from '@univerjs/core';-import { SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';+import {+ CanvasColorService,+ ICanvasColorService,+ IRenderManagerService,+ RenderManagerService,+ SHEET_VIEWPORT_KEY,+ Spreadsheet,+ Viewport,+} from '@univerjs/engine-render';import {IRefSelectionsService,REF_SELECTIONS_ENABLED,RefSelectionsService,SelectionMoveType,SELECTIONS_ENABLED,+ SheetInterceptorService,+ SheetSkeletonService,SheetsSelectionsService,} from '@univerjs/sheets';import {@@ -48,12 +58,114 @@ import {SHEET_VIEW_KEY,SheetSkeletonManagerService,} from '@univerjs/sheets-ui';-import { IShortcutService } from '@univerjs/ui';+import {+ IPlatformService,+ IShortcutService,+ IUIRuntimeScopeService,+ PlatformService,+ ShortcutService,+ UIRuntimeScopeService,+} from '@univerjs/ui';import { BehaviorSubject, Subject } from 'rxjs';-import { afterEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { MobileRefSelectionsRenderService } from '../mobile-ref-selections.render.service';import { RefSelectionsRenderService } from '../ref-selections.render.service';+describe('RefSelectionsRenderService additive modifiers with real render providers', () => {+ let univer: Univer;++ beforeEach(() => {+ vi.useFakeTimers();+ // Only the unavailable canvas backend is substituted.+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(function (this: HTMLCanvasElement) {+ return { canvas: this, setTransform: vi.fn(), clearRect: vi.fn() } as unknown as CanvasRenderingContext2D;+ });+ univer = new Univer();+ const injector = univer.__getInjector();+ injector.get(LocaleService).setLocale(LocaleType.EN_US);+ injector.add([ICanvasColorService, { useClass: CanvasColorService }]);+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);+ injector.add([SheetSkeletonService]);+ injector.add([SheetInterceptorService]);+ injector.add([SheetsSelectionsService]);+ injector.add([IRefSelectionsService, { useClass: RefSelectionsService }]);+ injector.add([IPlatformService, { useClass: PlatformService }]);+ injector.add([IUIRuntimeScopeService, { useClass: UIRuntimeScopeService }]);+ injector.add([IShortcutService, { useClass: ShortcutService }]);+ injector.get(SheetSkeletonService);+ injector.get(SheetInterceptorService);+ injector.get(IRenderManagerService).registerRenderModule(UniverInstanceType.UNIVER_SHEET, [SheetSkeletonManagerService]);+ });++ afterEach(() => {+ vi.clearAllTimers();+ univer.dispose();+ vi.restoreAllMocks();+ vi.useRealTimers();+ });++ for (const remainLast of [false, true]) {+ for (const modifier of ['none', 'ctrlKey', 'metaKey'] as const) {+ it(`keeps reference ownership with ${modifier} and remain-last ${remainLast}`, () => {+ const injector = univer.__getInjector();+ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, {+ id: 'ref-modifiers',+ name: 'Reference modifiers',+ sheetOrder: ['sheet1'],+ sheets: { sheet1: { id: 'sheet1', name: 'Sheet 1', rowCount: 20, columnCount: 10, cellData: {} } },+ });+ const renderManager = injector.get(IRenderManagerService);+ const render = renderManager.createRender(workbook.getUnitId());+ render.engine.resizeBySize(800, 600);+ new Viewport(SHEET_VIEWPORT_KEY.VIEW_MAIN, render.scene, { left: 0, top: 0, right: 0, bottom: 0 });+ const spreadsheet = new Spreadsheet(SHEET_VIEW_KEY.MAIN);+ render.mainComponent = spreadsheet;+ render.components.set(SHEET_VIEW_KEY.MAIN, spreadsheet);+ render.scene.addObject(spreadsheet);+ const skeletonManager = render.with(SheetSkeletonManagerService);+ skeletonManager.setCurrent({ sheetId: 'sheet1' });+ renderManager.registerRenderModule(UniverInstanceType.UNIVER_SHEET, [RefSelectionsRenderService]);+ const service = render.with(RefSelectionsRenderService);+ service.setRemainLastEnabled(remainLast);+ injector.get(IContextService).setContextValue(REF_SELECTIONS_ENABLED, true);+ service.enableSelectionChanging();+ const skeleton = skeletonManager.getCurrentSkeleton()!;++ for (const index of [0, 2]) {+ const cell = skeleton.getNoMergeCellWithCoordByIndex(index, index);+ const event = {+ offsetX: (cell.startX + cell.endX) / 2,+ offsetY: (cell.startY + cell.endY) / 2,+ button: 0,+ ...(index === 2 && modifier !== 'none' ? { [modifier]: true } : {}),+ } as IPointerEvent;+ spreadsheet.onPointerDown$.emitEvent(event);+ render.scene.onPointerUp$.emitEvent(event);+ }++ const selections = injector.get(IRefSelectionsService)+ .getWorkbookSelections(workbook.getUnitId())+ .getCurrentSelections();+ const ranges = selections.map(({ range }) => ({+ startRow: range.startRow,+ startColumn: range.startColumn,+ endRow: range.endRow,+ endColumn: range.endColumn,+ }));+ if (modifier === 'none') {+ expect(ranges).toEqual([{ startRow: 2, startColumn: 2, endRow: 2, endColumn: 2 }]);+ } else {+ expect(ranges).toEqual([+ { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 },+ { startRow: 2, startColumn: 2, endRow: 2, endColumn: 2 },+ ]);+ }+ expect(service.getSelectionControls()).toHaveLength(ranges.length);+ });+ }+ }+});+function createTestEvent<TEvent, TState = { stopPropagation: () => void }>() {const handlers = new Set<(evt: TEvent, state: TState) => void>();return {diff --git a/packages/sheets-formula-ui/src/services/render-services/ref-selections.render.service.ts b/packages/sheets-formula-ui/src/services/render-services/ref-selections.render.service.tsindex a1a17556f1..bb2671db99 100644--- a/packages/sheets-formula-ui/src/services/render-services/ref-selections.render.service.ts+++ b/packages/sheets-formula-ui/src/services/render-services/ref-selections.render.service.ts@@ -407,6 +407,7 @@ export class RefSelectionsRenderService extends BaseSelectionRenderService imple: null;const remainLastEnable = this._remainLastEnabled &&!evt.ctrlKey &&+ !evt.metaKey &&!evt.shiftKey &&!this._skipLastEnabled &&!this._singleSelectionEnabled;diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-sheet-selection-change.spec.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-sheet-selection-change.spec.tsnew file mode 100644index 0000000000..c9af1ee39b--- /dev/null+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-sheet-selection-change.spec.ts@@ -0,0 +1,50 @@+/**+ * 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 { IRange } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import { createSelectionChangeDuplicateEndGuard, createSelectionChangeHandler } from '../use-sheet-selection-change';++describe('formula reference selection gesture boundaries', () => {+ it.each([false, true])('accepts the same reference in a new editor after the previous gesture ends: %s', (completed) => {+ const duplicateEndGuard = createSelectionChangeDuplicateEndGuard<IRange>();+ const selectedRange = { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 };+ const firstChange = vi.fn();+ const first = createSelectionChangeHandler({+ initialSelectionsCount: 0,+ duplicateEndGuard,+ onSelectionsChange: firstChange,+ });+ first([selectedRange], false, { start: true });+ first(completed ? [selectedRange] : [], true);+ expect(firstChange).toHaveBeenCalledTimes(1);++ const nextChange = vi.fn();+ const commit = vi.fn();+ const next = createSelectionChangeHandler({+ initialSelectionsCount: 0,+ duplicateEndGuard,+ onSelectionsChange: nextChange,+ onDuplicateEnd: commit,+ });+ next([selectedRange], false, { start: true });+ next([selectedRange], false);+ next([selectedRange], true);++ expect(nextChange).toHaveBeenCalledExactlyOnceWith([selectedRange], false, false);+ expect(commit).toHaveBeenCalledExactlyOnceWith([selectedRange]);+ });+});diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-sheet-selection-change.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-sheet-selection-change.tsindex 1f9549f026..f8ebc5c9c8 100644--- a/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-sheet-selection-change.ts+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-sheet-selection-change.ts@@ -188,7 +188,7 @@ export function createSelectionChangeHandler<TSelection>(opts: {let pendingCtrlAddCount = 0;const duplicateEndGuard = opts.duplicateEndGuard ?? createSelectionChangeDuplicateEndGuard<TSelection>();- return (selections: TSelection[], isEnd: boolean, options?: { initial?: boolean }) => {+ return (selections: TSelection[], isEnd: boolean, options?: { initial?: boolean; start?: boolean }) => {if (options?.initial) {// Ignore the BehaviorSubject replay when subscribing; real user selections arrive through later move events.return;@@ -198,6 +198,11 @@ export function createSelectionChangeHandler<TSelection>(opts: {return;}+ if (options?.start) {+ // A new gesture may intentionally select the same reference after an edit was cancelled or committed.+ duplicateEndGuard.reset();+ }+const isCtrlAddMode = !options?.initial && prevSelectionsCount > 0 && selections.length > prevSelectionsCount;if (isCtrlAddMode && !isEnd) {pendingCtrlAddCount = selections.length;@@ -470,15 +475,21 @@ export const useSheetSelectionChange = (const disposableCollection = new DisposableCollection();disposableCollection.add(refSelectionsRenderService.selectionMoveStart$.subscribe((selections) => {- if (!isInteractionOwner()) return;- handleSelectionsChange(selections, false);+ if (!isInteractionOwner()) {+ return;+ }+ handleSelectionsChange(selections, false, { start: true });}));disposableCollection.add(refSelectionsRenderService.selectionMoving$.subscribe((selections) => {- if (!isInteractionOwner()) return;+ if (!isInteractionOwner()) {+ return;+ }handleSelectionsChange(selections, false);}));disposableCollection.add(refSelectionsRenderService.selectionMoveEnd$.subscribe((selections) => {- if (!isInteractionOwner()) return;+ if (!isInteractionOwner()) {+ return;+ }handleSelectionsChange(selections, true, { initial: isInitialMoveEnd });isInitialMoveEnd = false;}));diff --git a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx b/packages/sheets-formula-ui/src/views/formula-editor/index.tsxindex 64a5c366fa..210120b281 100644--- a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx+++ b/packages/sheets-formula-ui/src/views/formula-editor/index.tsx@@ -341,6 +341,7 @@ export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IFdispose = editorService.register({autofocus,editorUnitId: editorId,+ preserveHostFocus: editorId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,initialSnapshot: {id: editorId,body: {@@ -432,6 +433,11 @@ export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IFlet finalFocusRetryFrame = 0;const retryFocus = () => {+ // A delayed retry must not reclaim focus after another editor takes over.+ const focusedEditor = editorService.getFocusEditor();+ if (focusedEditor && focusedEditor.getEditorId() !== editorId) {+ return;+ }if (_isFocus && !docSelectionRenderService?.isFocusing) {focus();}@@ -457,7 +463,7 @@ export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IFcancelAnimationFrame(focusRetryFrame);cancelAnimationFrame(finalFocusRetryFrame);};- }, [_isFocus, docSelectionRenderService, editor, focus, resetSelection, resetSelectionOnBlur]);+ }, [_isFocus, docSelectionRenderService, editor, editorId, editorService, focus, resetSelection, resetSelectionOnBlur]);const { checkScrollBar } = useResize(editor, isSingle, autoScrollbar);useRefactorEffect(isFocus, isSelecting, unitId, editorId, disableContextMenu);diff --git a/packages/sheets-numfmt-ui/src/controllers/__tests__/numfmt.editor.controller.spec.ts b/packages/sheets-numfmt-ui/src/controllers/__tests__/numfmt.editor.controller.spec.tsnew file mode 100644index 0000000000..595b6e2144--- /dev/null+++ b/packages/sheets-numfmt-ui/src/controllers/__tests__/numfmt.editor.controller.spec.ts@@ -0,0 +1,152 @@+/**+ * 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 { ICellData, IWorkbookData, Workbook } from '@univerjs/core';+import {+ ICommandService,+ IUniverInstanceService,+ LocaleService,+ LocaleType,+ RedoCommand,+ Tools,+ UndoCommand,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import {+ AFTER_CELL_EDIT,+ INumfmtService,+ NumfmtService,+ RemoveNumfmtMutation,+ SetNumfmtMutation,+ SetRangeValuesCommand,+ SetRangeValuesMutation,+ SetSelectionsOperation,+ SetWorksheetActiveOperation,+ SheetInterceptorService,+ SheetsSelectionsService,+} from '@univerjs/sheets';+import { SheetsNumfmtCellContentController } from '@univerjs/sheets-numfmt';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { NumfmtEditorController } from '../numfmt.editor.controller';++describe('NumfmtEditorController explicit command targets', () => {+ let univer: Univer;++ beforeEach(() => {+ univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([INumfmtService, { useClass: NumfmtService }]);+ injector.add([SheetInterceptorService]);+ injector.add([SheetsSelectionsService]);+ injector.add([SheetsNumfmtCellContentController]);+ injector.add([NumfmtEditorController]);+ const locale = injector.get(LocaleService);+ locale.load({ [LocaleType.EN_US]: {} });+ locale.setLocale(LocaleType.EN_US);+ locale.setDirection('ltr');+ const commands = injector.get(ICommandService);+ for (const command of [+ SetRangeValuesCommand,+ SetRangeValuesMutation,+ SetNumfmtMutation,+ RemoveNumfmtMutation,+ SetSelectionsOperation,+ SetWorksheetActiveOperation,+ ]) {+ commands.registerCommand(command);+ }+ });++ afterEach(() => univer.dispose());++ for (const current of ['none', 'peer', 'other-worksheet'] as const) {+ for (const formatted of [false, true]) {+ it(`writes ${formatted ? 'parsed percentage' : 'plain numeric data'} with ${current} current and preserves history`, async () => {+ const injector = univer.__getInjector();+ const instances = injector.get(IUniverInstanceService);+ const peer = instances.createUnit<IWorkbookData, Workbook>(+ UniverInstanceType.UNIVER_SHEET,+ workbookData('peer'),+ { makeCurrent: false }+ );+ const child = instances.createUnit<IWorkbookData, Workbook>(+ UniverInstanceType.UNIVER_SHEET,+ workbookData('child'),+ { makeCurrent: false }+ );+ if (current !== 'none') {+ instances.setCurrentUnitForType(current === 'peer' ? 'peer' : 'child');+ }+ injector.get(NumfmtEditorController);+ const worksheet = child.getSheetBySheetId('sheet2')!;+ const before = Tools.deepClone(worksheet.getCellRaw(0, 0));+ const peerBefore = Tools.deepClone(peer.getSnapshot());+ const otherSheetBefore = Tools.deepClone(child.getSheetBySheetId('sheet1')!.getSnapshot());+ let value: ICellData = { v: 42 };+ if (formatted) {+ const interceptor = injector.get(SheetInterceptorService).writeCellInterceptor;+ value = interceptor.fetchThroughInterceptors(AFTER_CELL_EDIT)({ v: '50%' }, {+ workbook: child,+ worksheet,+ unitId: 'child',+ subUnitId: 'sheet2',+ row: 0,+ col: 0,+ origin: before,+ })!;+ }+ const commands = injector.get(ICommandService);+ expect(await commands.executeCommand(SetRangeValuesCommand.id, {+ unitId: 'child',+ subUnitId: 'sheet2',+ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },+ value,+ })).toBe(true);+ expect(worksheet.getCellRaw(0, 0)?.v).toBe(formatted ? 0.5 : 42);+ const pattern = injector.get(INumfmtService).getValue('child', 'sheet2', 0, 0)?.pattern;+ expect(pattern).toBe(formatted ? '0%' : undefined);+ expect(peer.getSnapshot()).toEqual(peerBefore);+ expect(child.getSheetBySheetId('sheet1')!.getSnapshot()).toEqual(otherSheetBefore);++ instances.focusUnit('child');+ expect(await commands.executeCommand(UndoCommand.id)).toBe(true);+ expect(worksheet.getCellRaw(0, 0)?.v).toBe(before?.v);+ expect(injector.get(INumfmtService).getValue('child', 'sheet2', 0, 0)?.pattern).toBeUndefined();+ expect(await commands.executeCommand(RedoCommand.id)).toBe(true);+ expect(worksheet.getCellRaw(0, 0)?.v).toBe(formatted ? 0.5 : 42);+ expect(injector.get(INumfmtService).getValue('child', 'sheet2', 0, 0)?.pattern).toBe(pattern);+ expect(peer.getSnapshot()).toEqual(peerBefore);+ expect(child.getSheetBySheetId('sheet1')!.getSnapshot()).toEqual(otherSheetBefore);+ });+ }+ }+});++function workbookData(id: string): IWorkbookData {+ return {+ id,+ name: id,+ appVersion: 'test',+ locale: LocaleType.EN_US,+ styles: {},+ sheetOrder: ['sheet1', 'sheet2'],+ sheets: {+ sheet1: { id: 'sheet1', name: 'Other', cellData: { 0: { 0: { v: 7 } } } },+ sheet2: { id: 'sheet2', name: 'Target', cellData: { 0: { 0: { v: 11 } } } },+ },+ };+}diff --git a/packages/sheets-numfmt-ui/src/controllers/numfmt.editor.controller.ts b/packages/sheets-numfmt-ui/src/controllers/numfmt.editor.controller.tsindex a8f6894264..737c5ad776 100644--- a/packages/sheets-numfmt-ui/src/controllers/numfmt.editor.controller.ts+++ b/packages/sheets-numfmt-ui/src/controllers/numfmt.editor.controller.ts@@ -14,12 +14,13 @@* limitations under the License.*/-import type { ICellData, ICellDataForSheetInterceptor, IDocumentBody, IRange, Nullable, Workbook } from '@univerjs/core';+import type { ICellData, ICellDataForSheetInterceptor, IDocumentBody, IRange, Nullable } from '@univerjs/core';import type {INumfmtItemWithCache,IRemoveNumfmtMutationParams,ISetCellsNumfmt,ISetNumfmtMutationParams,+ ISetRangeValuesMutationParams,} from '@univerjs/sheets';import {CellValueType,@@ -32,7 +33,6 @@ import {IUniverInstanceService,Optional,toDisposable,- UniverInstanceType,willLoseNumericPrecision,} from '@univerjs/core';import { stripErrorMargin } from '@univerjs/engine-formula';@@ -41,6 +41,7 @@ import {BEFORE_CELL_EDIT,factoryRemoveNumfmtUndoMutation,factorySetNumfmtUndoMutation,+ getSheetCommandTarget,INumfmtService,RemoveNumfmtMutation,SetNumfmtMutation,@@ -294,23 +295,26 @@ export class NumfmtEditorController extends Disposable {getMutations(command) {switch (command.id) {case SetRangeValuesCommand.id: {- const workbook = self._univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;- const unitId = workbook.getUnitId();- const subUnitId = workbook.getActiveSheet()?.getSheetId();- if (!subUnitId) {+ const effects = self._collectEffectMutation.getEffects();+ self._collectEffectMutation.clean();+ if (!effects.length) {return {redos: [],undos: [],};}- const list = self._collectEffectMutation.getEffects();- self._collectEffectMutation.clean();- if (!list.length) {+ const target = getSheetCommandTarget(+ self._univerInstanceService,+ command.params as ISetRangeValuesMutationParams+ );+ if (!target) {return {redos: [],undos: [],};}+ const { unitId, subUnitId } = target;+ const list = effects.filter((item) => item.unitId === unitId && item.subUnitId === subUnitId);const cells: ISetCellsNumfmt = list.filter((item) => !!item.value?.pattern).map((item) => ({diff --git a/packages/sheets-ui/src/commands/commands/__tests__/clipboard.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/clipboard.command.spec.tsnew file mode 100644index 0000000000..cb0d7e7a28--- /dev/null+++ b/packages/sheets-ui/src/commands/commands/__tests__/clipboard.command.spec.ts@@ -0,0 +1,75 @@+/**+ * 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 { IWorkbookData, Workbook } from '@univerjs/core';+import type { IClipboardInterfaceService } from '@univerjs/ui';+import { ICommandService, Injector, IUniverInstanceService, Tools, UniverInstanceType } from '@univerjs/core';+import {+ SetRangeValuesMutation,+ SetSelectionsOperation,+ SetWorksheetActiveOperation,+ SetWorksheetRowAutoHeightMutation,+ SheetsSelectionsService,+} from '@univerjs/sheets';+import { expect, it, vi } from 'vitest';+import { clipboardTestBed } from '../../../services/clipboard/__tests__/clipboard-test-bed';+import { PREDEFINED_HOOK_NAME_PASTE } from '../../../services/clipboard/clipboard.service';+import { SheetPasteCommand } from '../clipboard.command';++it.each([false, true])('silently cancels a delayed paste after target disposal (replacement: %s)', async (replace) => {+ let release = () => {};+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ const getType = vi.fn(async () => new Blob(['stale paste'], { type: 'text/plain' }));+ const boundary: IClipboardInterfaceService = {+ supportClipboard: true,+ write: async () => {},+ writeText: async () => {},+ readText: async () => '',+ read: vi.fn(async () => {+ await gate;+ return [{ presentationStyle: 'unspecified' as const, types: ['text/plain'], getType }];+ }),+ };+ const { univer, get, sheet } = clipboardTestBed(undefined, undefined, boundary);+ try {+ const commands = get(ICommandService);+ for (const command of [SetRangeValuesMutation, SetSelectionsOperation, SetWorksheetActiveOperation, SetWorksheetRowAutoHeightMutation]) {+ commands.registerCommand(command);+ }+ get(SheetsSelectionsService).setSelections('test', 'sheet1', [{+ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },+ primary: null,+ style: null,+ }]);+ const snapshot = Tools.deepClone(sheet.getSnapshot());+ const pending = SheetPasteCommand.handler(get(Injector), { value: PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE });+ expect(boundary.read).toHaveBeenCalledOnce();+ expect(get(IUniverInstanceService).disposeUnit(sheet.getUnitId())).toBe(true);+ const replacement = replace+ ? univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, snapshot)+ : null;+ const before = replacement ? JSON.stringify(replacement.getSnapshot()) : null;+ release();+ expect(await pending).toBe(false);+ expect(getType).not.toHaveBeenCalled();+ expect(replacement ? JSON.stringify(replacement.getSnapshot()) : null).toEqual(before);+ } finally {+ release();+ univer.dispose();+ }+});diff --git a/packages/sheets-ui/src/commands/commands/__tests__/confirm-and-clipboard.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/confirm-and-clipboard.command.spec.tsindex eb1dde520f..a5a9dad07c 100644--- a/packages/sheets-ui/src/commands/commands/__tests__/confirm-and-clipboard.command.spec.ts+++ b/packages/sheets-ui/src/commands/commands/__tests__/confirm-and-clipboard.command.spec.ts@@ -15,24 +15,41 @@*/import type { IAccessor, IRange, Workbook, Worksheet } from '@univerjs/core';+import type { IClipboardInterfaceService } from '@univerjs/ui';import {ICommandService,IConfirmService,+ Injector,IPermissionService,+ IUndoRedoService,IUniverInstanceService,LocaleService,+ RedoCommand,+ UndoCommand,} from '@univerjs/core';import {+ AddWorksheetMergeMutation,DeleteRangeMoveLeftCommand,DeleteRangeMoveUpCommand,InsertRangeMoveDownCommand,InsertRangeMoveRightCommand,- SheetPermissionCheckController,+ MoveRangeMutation,+ RemoveWorksheetMergeMutation,+ SetRangeValuesMutation,+ SetSelectionsOperation,+ SetWorksheetActiveOperation,+ SetWorksheetColWidthMutation,+ SetWorksheetRowAutoHeightMutation,+ SetWorksheetRowHeightMutation,SheetsSelectionsService,+ WorkbookCopyPermission,+ WorkbookEditablePermission,+ WorksheetSetCellStylePermission,+ WorksheetSetCellValuePermission,} from '@univerjs/sheets';import * as sheets from '@univerjs/sheets';-import { IClipboardInterfaceService } from '@univerjs/ui';import { afterEach, describe, expect, it, vi } from 'vitest';+import { clipboardTestBed } from '../../../services/clipboard/__tests__/clipboard-test-bed';import { ISheetClipboardService, PREDEFINED_HOOK_NAME_PASTE } from '../../../services/clipboard/clipboard.service';import {SheetCopyCommand,@@ -226,116 +243,204 @@ describe('insert/delete range confirm commands', () => {});describe('clipboard command branches', () => {- it('runs copy/cut/paste and optional-paste command handlers', async () => {- const copy = vi.fn(async () => true);- const cut = vi.fn(async () => true);- const paste = vi.fn(async () => true);- const pasteByCopyId = vi.fn(async () => true);- const legacyPaste = vi.fn();- const rePasteWithPasteType = vi.fn(async () => true);- const copyContentCache = vi.fn(() => ({ getLastCopyId: () => 'copy-1' }));- const clipboardService = {- copy,- cut,- paste,- pasteByCopyId,- legacyPaste,- rePasteWithPasteType,- copyContentCache,+ it.each(['copy', 'cut'] as const)('uses the internal %s cache without system clipboard support and restores history', async (mode) => {+ const boundary: IClipboardInterfaceService = {+ supportClipboard: false,+ write: vi.fn(async () => {}),+ writeText: vi.fn(async () => {}),+ readText: vi.fn(async () => ''),+ read: vi.fn(async () => []),};- const read = vi.fn(async () => [{ id: 'clip-1' }]);-- const accessor = createAccessor([- [ISheetClipboardService, clipboardService],- [IClipboardInterfaceService, { supportClipboard: true, read }],- [IUniverInstanceService, { getCurrentUnitOfType: vi.fn(() => null) }],- [IPermissionService, { getPermissionPoint: vi.fn(() => undefined) }],- [LocaleService, { t: vi.fn((key: string) => key) }],- [SheetPermissionCheckController, {- permissionCheckWithRanges: vi.fn(() => true),- blockExecuteWithoutPermission: vi.fn(),- }],- ]);-- expect(await SheetCopyCommand.handler(accessor)).toBe(true);- expect(await SheetCutCommand.handler(accessor)).toBe(true);- expect(await SheetPasteCommand.handler(accessor, { value: 'v' })).toBe(true);- expect(paste).toHaveBeenCalledWith({ id: 'clip-1' }, 'v');-- const accessorWithoutClipboardAPI = createAccessor([- [ISheetClipboardService, clipboardService],- [IClipboardInterfaceService, { supportClipboard: false, read: vi.fn(async () => []) }],- [IUniverInstanceService, { getCurrentUnitOfType: vi.fn(() => null) }],- [IPermissionService, { getPermissionPoint: vi.fn(() => undefined) }],- [LocaleService, { t: vi.fn((key: string) => key) }],- [SheetPermissionCheckController, {- permissionCheckWithRanges: vi.fn(() => true),- blockExecuteWithoutPermission: vi.fn(),- }],- ]);- expect(await SheetPasteCommand.handler(accessorWithoutClipboardAPI, { value: 'value-only' })).toBe(true);- expect(pasteByCopyId).toHaveBeenCalledWith('copy-1', 'value-only');-- const accessorNoData = createAccessor([- [ISheetClipboardService, {- ...clipboardService,- copyContentCache: () => ({ getLastCopyId: () => '' }),- }],- [IClipboardInterfaceService, { supportClipboard: true, read: vi.fn(async () => []) }],- [IUniverInstanceService, { getCurrentUnitOfType: vi.fn(() => null) }],- [IPermissionService, { getPermissionPoint: vi.fn(() => undefined) }],- [LocaleService, { t: vi.fn((key: string) => key) }],- [SheetPermissionCheckController, {- permissionCheckWithRanges: vi.fn(() => true),- blockExecuteWithoutPermission: vi.fn(),- }],- ]);- expect(await SheetPasteCommand.handler(accessorNoData, { value: 'none' })).toBe(false);-- expect(await SheetPasteShortKeyCommand.handler(accessor, {- htmlContent: '<b>x</b>',- textContent: 'x',- files: [],- formulaClipboardPayload: '{"formulas":[]}',- })).toBe(true);- expect(legacyPaste).toHaveBeenCalledWith('<b>x</b>', 'x', [], '{"formulas":[]}');-- expect(await SheetOptionalPasteCommand.handler(accessor, { type: PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_VALUE })).toBe(true);- expect(rePasteWithPasteType).toHaveBeenCalledWith(PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_VALUE);+ const { univer, get, sheet } = clipboardTestBed(undefined, undefined, boundary);+ try {+ const accessor = get(Injector);+ const commands = get(ICommandService);+ for (const command of [+ SetRangeValuesMutation,+ SetSelectionsOperation,+ SetWorksheetActiveOperation,+ SetWorksheetRowAutoHeightMutation,+ SetWorksheetRowHeightMutation,+ SetWorksheetColWidthMutation,+ AddWorksheetMergeMutation,+ RemoveWorksheetMergeMutation,+ MoveRangeMutation,+ ]) {+ commands.registerCommand(command);+ }+ const select = (column: number) => get(SheetsSelectionsService).setSelections('test', 'sheet1', [{+ range: { startRow: 0, endRow: 0, startColumn: column, endColumn: column },+ primary: null,+ style: null,+ }]);+ select(0);+ expect(await SheetPasteCommand.handler(accessor, { value: PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE })).toBe(false);+ commands.syncExecuteCommand(SetRangeValuesMutation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ cellValue: { 0: { 0: { v: 'cached-value', s: { bl: 1 } } } },+ });+ const copyCommand = mode === 'copy' ? SheetCopyCommand : SheetCutCommand;+ expect(await copyCommand.handler(accessor)).toBe(true);+ select(1);+ expect(await SheetPasteCommand.handler(accessor, { value: PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE })).toBe(true);+ const worksheet = sheet.getSheetBySheetId('sheet1')!;+ expect(worksheet.getCell(0, 1)?.v).toBe('cached-value');+ expect(worksheet.getCellStyle(0, 1)?.bl).toBe(1);+ expect(worksheet.getCell(0, 0)?.v).toBe(mode === 'copy' ? 'cached-value' : undefined);+ if (mode === 'copy') {+ expect(await SheetOptionalPasteCommand.handler(accessor, { type: 'SPECIAL_PASTE_VALUE' })).toBe(true);+ expect(worksheet.getCell(0, 1)?.v).toBe('cached-value');+ expect(worksheet.getCellStyle(0, 1)?.bl).not.toBe(1);+ }+ expect(await commands.executeCommand(UndoCommand.id)).toBe(true);+ expect(worksheet.getCell(0, 0)?.v).toBe('cached-value');+ expect(worksheet.getCell(0, 1)?.v).toBeUndefined();+ expect(await commands.executeCommand(RedoCommand.id)).toBe(true);+ expect(worksheet.getCell(0, 1)?.v).toBe('cached-value');+ expect(boundary.read).not.toHaveBeenCalled();+ } finally {+ univer.dispose();+ }});- it('checks clipboard permissions only after the sheet implementation is selected', async () => {- const copy = vi.fn(async () => true);- const cut = vi.fn(async () => true);- const legacyPaste = vi.fn();- const permissionCheckWithRanges = vi.fn(() => false);- const blockExecuteWithoutPermission = vi.fn((message: string) => {- throw new Error(message);+ it('keeps menu paste data and history on the selection captured before the system read', async () => {+ let releaseRead = () => {};+ const readGate = new Promise<void>((resolve) => {+ releaseRead = resolve;});- const accessor = createAccessor([- [ISheetClipboardService, {- copy,- cut,- legacyPaste,- }],- [IUniverInstanceService, { getCurrentUnitOfType: vi.fn(() => null) }],- [IPermissionService, { getPermissionPoint: vi.fn(() => undefined) }],- [LocaleService, { t: vi.fn((key: string) => `translated:${key}`) }],- [SheetPermissionCheckController, {- permissionCheckWithRanges,- blockExecuteWithoutPermission,- }],- ]);+ const boundary: IClipboardInterfaceService = {+ supportClipboard: true,+ write: vi.fn(async () => {}),+ writeText: vi.fn(async () => {}),+ readText: async () => 'system-value',+ read: async () => {+ await readGate;+ return [{+ presentationStyle: 'unspecified',+ types: ['text/plain'],+ getType: async () => new Blob(['system-value'], { type: 'text/plain' }),+ }];+ },+ };+ const { univer, get, sheet } = clipboardTestBed(undefined, undefined, boundary);+ try {+ const accessor = get(Injector);+ const commands = get(ICommandService);+ for (const command of [SetRangeValuesMutation, SetSelectionsOperation, SetWorksheetActiveOperation, SetWorksheetRowAutoHeightMutation]) {+ commands.registerCommand(command);+ }+ const select = (column: number) => get(SheetsSelectionsService).setSelections('test', 'sheet1', [{+ range: { startRow: 0, endRow: 0, startColumn: column, endColumn: column },+ primary: null,+ style: null,+ }]);+ select(0);+ expect(await SheetPasteShortKeyCommand.handler(accessor, { textContent: 'source-value' })).toBe(true);+ expect(await SheetCopyCommand.handler(accessor)).toBe(true);+ expect(boundary.write).toHaveBeenCalled();+ expect(await SheetCutCommand.handler(accessor)).toBe(true);+ select(1);+ const pendingPaste = SheetPasteCommand.handler(accessor, { value: PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE });+ select(2);+ releaseRead();+ expect(await pendingPaste).toBe(true);+ const worksheet = sheet.getSheetBySheetId('sheet1')!;+ expect(worksheet.getCell(0, 1)?.v).toBe('system-value');+ expect(worksheet.getCell(0, 0)?.v).toBe('source-value');+ expect(worksheet.getCell(0, 2)?.v).toBeUndefined();+ expect(await commands.executeCommand(UndoCommand.id)).toBe(true);+ expect(worksheet.getCell(0, 1)?.v).toBeUndefined();+ } finally {+ releaseRead();+ univer.dispose();+ }+ });- await expect(SheetCopyCommand.handler(accessor)).rejects.toThrow('translated:sheets-ui.permission.dialog.copyErr');- await expect(SheetCutCommand.handler(accessor)).rejects.toThrow('translated:sheets-ui.permission.dialog.cutErr');- await expect(SheetPasteCommand.handler(accessor, { value: PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE })).rejects.toThrow('translated:sheets-ui.permission.dialog.pasteErr');- await expect(SheetPasteShortKeyCommand.handler(accessor, {})).rejects.toThrow('translated:sheets-ui.permission.dialog.pasteErr');+ it.each([+ { name: 'cell value', PermissionPoint: WorksheetSetCellValuePermission },+ { name: 'cell style', PermissionPoint: WorksheetSetCellStylePermission },+ ])('rejects menu paste when $name permission is revoked during the system read', async ({ PermissionPoint }) => {+ let releaseRead = () => {};+ const readGate = new Promise<void>((resolve) => {+ releaseRead = resolve;+ });+ const getType = vi.fn(async () => new Blob(['forbidden'], { type: 'text/plain' }));+ const boundary: IClipboardInterfaceService = {+ supportClipboard: true,+ write: vi.fn(async () => {}),+ writeText: vi.fn(async () => {}),+ readText: vi.fn(async () => ''),+ read: vi.fn(async () => {+ await readGate;+ return [{ presentationStyle: 'unspecified' as const, types: ['text/plain'], getType }];+ }),+ };+ const { univer, get, sheet } = clipboardTestBed(undefined, undefined, boundary);+ try {+ get(SheetsSelectionsService).setSelections('test', 'sheet1', [{+ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },+ primary: null,+ style: null,+ }]);+ const permissions = get(IPermissionService);+ const point = new PermissionPoint('test', 'sheet1');+ if (!permissions.getPermissionPoint(point.id)) {+ permissions.addPermissionPoint(point);+ }+ permissions.updatePermissionPoint(point.id, true);+ const before = JSON.stringify(sheet.getSnapshot());+ const history = get(IUndoRedoService);+ const beforeHistory = history.getUndoRedoStatus('test');+ const pendingPaste = SheetPasteCommand.handler(get(Injector), { value: PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE });+ expect(boundary.read).toHaveBeenCalledOnce();+ permissions.updatePermissionPoint(point.id, false);+ releaseRead();+ await expect(pendingPaste).rejects.toThrow('have no permission');+ expect(getType).not.toHaveBeenCalled();+ expect(JSON.stringify(sheet.getSnapshot())).toBe(before);+ expect(history.getUndoRedoStatus('test')).toEqual(beforeHistory);+ } finally {+ releaseRead();+ univer.dispose();+ }+ });- expect(permissionCheckWithRanges).toHaveBeenCalledTimes(4);- expect(copy).not.toHaveBeenCalled();- expect(cut).not.toHaveBeenCalled();- expect(legacyPaste).not.toHaveBeenCalled();+ it('checks real clipboard permissions without calling the system boundary or changing cells', async () => {+ const boundary: IClipboardInterfaceService = {+ supportClipboard: true,+ write: vi.fn(async () => {}),+ writeText: vi.fn(async () => {}),+ readText: vi.fn(async () => ''),+ read: vi.fn(async () => []),+ };+ const { univer, get, sheet } = clipboardTestBed(undefined, undefined, boundary);+ try {+ const accessor = get(Injector);+ get(ISheetClipboardService);+ get(SheetsSelectionsService).setSelections('test', 'sheet1', [{+ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },+ primary: null,+ style: null,+ }]);+ const permissions = get(IPermissionService);+ for (const point of [new WorkbookCopyPermission('test'), new WorkbookEditablePermission('test')]) {+ if (!permissions.getPermissionPoint(point.id)) {+ permissions.addPermissionPoint(point);+ }+ permissions.updatePermissionPoint(point.id, false);+ }+ const before = JSON.stringify(sheet.getSnapshot());+ await expect(SheetCopyCommand.handler(accessor)).rejects.toThrow('have no permission');+ await expect(SheetCutCommand.handler(accessor)).rejects.toThrow('have no permission');+ await expect(SheetPasteCommand.handler(accessor, { value: PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE })).rejects.toThrow('have no permission');+ await expect(SheetPasteShortKeyCommand.handler(accessor, { textContent: 'forbidden' })).rejects.toThrow('have no permission');+ expect(boundary.read).not.toHaveBeenCalled();+ expect(boundary.write).not.toHaveBeenCalled();+ expect(JSON.stringify(sheet.getSnapshot())).toBe(before);+ } finally {+ univer.dispose();+ }});it('routes special paste commands to SheetPasteCommand', async () => {diff --git a/packages/sheets-ui/src/commands/commands/__tests__/set-format-painter.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/set-format-painter.command.spec.tsindex 4bc35ed6dc..d284cfc149 100644--- a/packages/sheets-ui/src/commands/commands/__tests__/set-format-painter.command.spec.ts+++ b/packages/sheets-ui/src/commands/commands/__tests__/set-format-painter.command.spec.ts@@ -15,12 +15,13 @@*/import type { Injector, Univer, Workbook } from '@univerjs/core';-import type { ISelectionWithCoord } from '@univerjs/sheets';+import type { ISelectionWithCoord, ISetRangeValuesMutationParams } from '@univerjs/sheets';import {Disposable,ICommandService,IUniverInstanceService,LocaleType,+ ObjectMatrix,RedoCommand,set,ThemeService,@@ -36,7 +37,7 @@ import {SetSelectionsOperation,} from '@univerjs/sheets';import { BehaviorSubject } from 'rxjs';-import { beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { FormatPainterController } from '../../../controllers/format-painter/format-painter.controller';import {FormatPainterService,@@ -237,6 +238,8 @@ describe('Test format painter rules in controller', () => {commandService.registerCommand(AddWorksheetMergeMutation);});+ afterEach(() => univer?.dispose());+describe('format painter', () => {it('toggles toolbar commands between active mode and off', async () => {const formatPainterService = get(IFormatPainterService);@@ -350,6 +353,65 @@ describe('Test format painter rules in controller', () => {});describe('format painter to single cell', () => {+ it('changes only styles and preserves target formulas through undo and redo', async () => {+ const workbook = get(IUniverInstanceService).getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;+ const worksheet = workbook.getSheetBySheetId('sheet-0011')!;+ const originalCell = { ...worksheet.getCell(0, 3)! };+ get(IUniverInstanceService).focusUnit(workbook.getUnitId());+ expect(await commandService.executeCommand(SetSelectionsOperation.id, {+ unitId: 'workbook-01',+ subUnitId: 'sheet-0011',++ selections: [+ {+ range: {+ startRow: 0,+ endRow: 0,+ startColumn: 0,+ endColumn: 0,+ },+ },+ ],+ })).toBeTruthy();++ expect(await commandService.executeCommand(SetOnceFormatPainterCommand.id)).toBeTruthy();++ const setRangeValuesParams: ISetRangeValuesMutationParams[] = [];+ const disposable = commandService.onCommandExecuted((command) => {+ if (command.id === SetRangeValuesMutation.id) {+ setRangeValuesParams.push(command.params as ISetRangeValuesMutationParams);+ }+ });++ expect(await commandService.executeCommand(ApplyFormatPainterCommand.id, {+ range: {+ startRow: 0,+ endRow: 0,+ startColumn: 3,+ endColumn: 3,+ },+ unitId: 'workbook-01',+ subUnitId: 'sheet-0011',+ })).toBeTruthy();++ disposable.dispose();++ expect(setRangeValuesParams.length).toBeGreaterThan(0);+ for (const params of setRangeValuesParams) {+ expect(params.trigger).toBe(ApplyFormatPainterCommand.id);+ new ObjectMatrix(params.cellValue).forValue((_row, _column, cell) => {+ expect(Object.keys(cell!)).toEqual(['s']);+ });+ }+ expect(worksheet.getCell(0, 3)).toMatchObject({ ...originalCell, s: 'yifA1t' });++ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);+ expect(worksheet.getCell(0, 3)).toMatchObject(originalCell);+ expect(worksheet.getCell(0, 3)?.s).toBeUndefined();++ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);+ expect(worksheet.getCell(0, 3)).toMatchObject({ ...originalCell, s: 'yifA1t' });+ });it('will copy whole original styles', async () => {expect(await commandService.executeCommand(SetSelectionsOperation.id, {unitId: 'workbook-01',diff --git a/packages/sheets-ui/src/commands/commands/__tests__/set-selections.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/set-selections.command.spec.tsindex 42e3bc235e..d3f88d67bd 100644--- a/packages/sheets-ui/src/commands/commands/__tests__/set-selections.command.spec.ts+++ b/packages/sheets-ui/src/commands/commands/__tests__/set-selections.command.spec.ts@@ -885,6 +885,22 @@ describe('Test commands used for change selections', () => {expectSelectionToBe(19, 19, 19, 19);});+ it('should preserve the primary selection when shift-tab moves a single-cell selection left', async () => {+ selectTopLeft();++ await commandService.executeCommand<IMoveSelectionEnterAndTabCommandParams>(MoveSelectionEnterAndTabCommand.id, {+ direction: Direction.RIGHT,+ keycode: KeyCode.TAB,+ });+ expectSelectionToBe(0, 1, 0, 1);++ await commandService.executeCommand<IMoveSelectionEnterAndTabCommandParams>(MoveSelectionEnterAndTabCommand.id, {+ direction: Direction.LEFT,+ keycode: KeyCode.TAB,+ });+ expectSelectionToBe(0, 0, 0, 0);+ });+it('should keep the original tab anchor across repeated tab moves before enter', async () => {selectTopLeft();diff --git a/packages/sheets-ui/src/commands/commands/clipboard.command.ts b/packages/sheets-ui/src/commands/commands/clipboard.command.tsindex 43d1957b6a..da096088aa 100644--- a/packages/sheets-ui/src/commands/commands/clipboard.command.ts+++ b/packages/sheets-ui/src/commands/commands/clipboard.command.ts@@ -14,7 +14,8 @@* limitations under the License.*/-import type { IAccessor, ICommand, IMultiCommand } from '@univerjs/core';+import type { IAccessor, ICommand, IMultiCommand, Workbook } from '@univerjs/core';+import type { ISheetRangeLocation } from '@univerjs/sheets';import type { LocaleKey } from '../../locale/types';import type { IPasteHookKeyType } from '../../services/clipboard/type';import { CommandType, ICommandService, IPermissionService, IUniverInstanceService, LocaleService } from '@univerjs/core';@@ -67,6 +68,7 @@ export const SheetCutCommand: IMultiCommand = {export interface ISheetPasteParams {value: string;+ target?: ISheetRangeLocation;}export interface ISheetPasteByShortKeyParams {@@ -74,6 +76,7 @@ export interface ISheetPasteByShortKeyParams {textContent?: string;files?: File[];formulaClipboardPayload?: string;+ target?: ISheetRangeLocation;}export const SheetPasteCommand: IMultiCommand = {@@ -84,26 +87,41 @@ export const SheetPasteCommand: IMultiCommand = {priority: SHEET_CLIPBOARD_PRIORITY,preconditions: whenSheetFocused,handler: async (accessor: IAccessor, params: ISheetPasteParams) => {- checkSheetClipboardPermission(accessor, PasteCommand.id, params);+ const sheetClipboardService = accessor.get(ISheetClipboardService);+ const target = params?.target ?? sheetClipboardService.capturePasteTarget();+ if (!target) {+ return false;+ }+ const instanceService = accessor.get(IUniverInstanceService);+ const workbook = instanceService.getUnit<Workbook>(target.unitId);+ const worksheet = workbook?.getSheetBySheetId(target.subUnitId);+ if (!workbook || !worksheet) {+ return false;+ }+ const pasteParams = { value: params?.value, target };+ checkSheetClipboardPermission(accessor, PasteCommand.id, pasteParams);// const messageService = accessor.get(IMessageService);// TODO: @yuhongz: check if there is excel content in the clipboard, if so// ask users to use shortcuts instead.- const sheetClipboardService = accessor.get(ISheetClipboardService);-const clipboardInterfaceService = accessor.get(IClipboardInterfaceService);if (clipboardInterfaceService.supportClipboard) {const clipboardItems = await clipboardInterfaceService.read();+ // A restored unit may reuse the same IDs but must not inherit an old clipboard request.+ if (instanceService.getUnit(target.unitId) !== workbook || workbook.getSheetBySheetId(target.subUnitId) !== worksheet) {+ return false;+ }if (clipboardItems.length !== 0) {- return sheetClipboardService.paste(clipboardItems[0], params?.value);+ checkSheetClipboardPermission(accessor, PasteCommand.id, pasteParams);+ return sheetClipboardService.paste(clipboardItems[0], params?.value, target);}}const lastCopyId = sheetClipboardService.copyContentCache().getLastCopyId();if (lastCopyId) {console.warn('Since the current environment does not support the Clipboard API, we will use the internal copyId to paste the content.');- return sheetClipboardService.pasteByCopyId(lastCopyId, params?.value);+ return sheetClipboardService.pasteByCopyId(lastCopyId, params?.value, target);}return false;@@ -114,12 +132,17 @@ export const SheetPasteShortKeyCommand: ICommand = {id: SheetPasteShortKeyCommandName,type: CommandType.COMMAND,handler: async (accessor: IAccessor, params: ISheetPasteByShortKeyParams) => {- checkSheetClipboardPermission(accessor, PasteCommand.id);const clipboardService = accessor.get(ISheetClipboardService);+ const target = params.target ?? clipboardService.capturePasteTarget();+ if (!target) {+ return false;+ }+ checkSheetClipboardPermission(accessor, PasteCommand.id, {+ value: PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE,+ target,+ });const { htmlContent, textContent, files, formulaClipboardPayload } = params;- clipboardService.legacyPaste(htmlContent, textContent, files, formulaClipboardPayload);-- return true;+ return clipboardService.legacyPaste(htmlContent, textContent, files, formulaClipboardPayload, target);},};@@ -176,6 +199,8 @@ function checkSheetPastePermission(permissionCheckController: SheetPermissionCheckController,params?: ISheetPasteParams): boolean {+ const target = params?.target;+ const ranges = target ? [target.range] : undefined;if (params?.value === PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_VALUE ||params?.value === PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_FORMULA ||@@ -185,7 +210,7 @@ function checkSheetPastePermission(workbookTypes: [WorkbookEditablePermission],worksheetTypes: [WorksheetSetCellStylePermission, WorksheetEditPermission],rangeTypes: [RangeProtectionPermissionEditPoint],- });+ }, ranges, target?.unitId, target?.subUnitId);}if (params?.value === PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_COL_WIDTH) {@@ -198,14 +223,14 @@ function checkSheetPastePermission(WorksheetSetColumnStylePermission,],rangeTypes: [RangeProtectionPermissionEditPoint],- });+ }, ranges, target?.unitId, target?.subUnitId);}return permissionCheckController.permissionCheckWithRanges({workbookTypes: [WorkbookEditablePermission],worksheetTypes: [WorksheetSetCellValuePermission, WorksheetSetCellStylePermission, WorksheetEditPermission],rangeTypes: [RangeProtectionPermissionEditPoint],- });+ }, ranges, target?.unitId, target?.subUnitId);}export const SheetPasteValueCommand: ICommand = {diff --git a/packages/sheets-ui/src/controllers/__tests__/auto-height.controller.spec.ts b/packages/sheets-ui/src/controllers/__tests__/auto-height.controller.spec.tsindex 458e599f9a..652df10453 100644--- a/packages/sheets-ui/src/controllers/__tests__/auto-height.controller.spec.ts+++ b/packages/sheets-ui/src/controllers/__tests__/auto-height.controller.spec.ts@@ -14,160 +14,255 @@* limitations under the License.*/-import type { IUniverInstanceService, Workbook } from '@univerjs/core';-import type { RenderManagerService } from '@univerjs/engine-render';-import type { SheetInterceptorService } from '@univerjs/sheets';+import type { IRange, IWorkbookData, Workbook } from '@univerjs/core';+import {+ BooleanNumber,+ ICommandService,+ IUniverInstanceService,+ LocaleService,+ LocaleType,+ RedoCommand,+ Tools,+ UndoCommand,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { CanvasColorService, ICanvasColorService, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';import {CancelMarkDirtyRowAutoHeightOperation,MarkDirtyRowAutoHeightOperation,+ SetColWidthCommand,+ SetWorksheetColWidthMutation,SetWorksheetRowAutoHeightMutation,+ SheetInterceptorService,+ SheetSkeletonService,+ SheetsSelectionsService,} from '@univerjs/sheets';-import { describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { SheetSkeletonManagerService } from '../../services/sheet-skeleton-manager.service';import { AutoHeightController } from '../auto-height.controller';-type AnyFn = (...args: unknown[]) => unknown;+const RANGE: IRange = { startRow: 1, endRow: 3, startColumn: 0, endColumn: 2 };describe('AutoHeightController', () => {- it('intercepts auto height and appends lazy mark-dirty redo/undo', () => {- const worksheet = {- getSheetId: () => 's-1',- } as unknown;-- const workbook = {- getUnitId: () => 'u-1',- getActiveSheet: () => worksheet,- getSheetBySheetId: (sheetId: string) => (sheetId === 's-1' ? worksheet : null),- } as unknown as Workbook;-- const univerInstanceService = {- getCurrentUnitOfType: () => workbook,- getUnit: () => workbook,- } as unknown as IUniverInstanceService;+ let univer: Univer;- const renderManagerService = {- getRenderUnitById: () => ({- with: () => ({- ensureSkeleton: () => null,- }),- }),- } as unknown as RenderManagerService;+ beforeEach(() => {+ // Happy DOM has no canvas backend; the render and skeleton services remain real.+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(function (this: HTMLCanvasElement) {+ return { canvas: this, setTransform: vi.fn(), clearRect: vi.fn() } as unknown as CanvasRenderingContext2D;+ });+ univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([ICanvasColorService, { useClass: CanvasColorService }]);+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);+ injector.add([SheetSkeletonService]);+ injector.add([SheetInterceptorService]);+ injector.add([SheetsSelectionsService]);+ injector.add([AutoHeightController]);+ injector.get(LocaleService).setLocale(LocaleType.EN_US);+ injector.get(SheetSkeletonService);+ injector.get(SheetInterceptorService);+ injector.get(IRenderManagerService).registerRenderModule(UniverInstanceType.UNIVER_SHEET, [SheetSkeletonManagerService]);+ injector.get(ICommandService).registerCommand(SetWorksheetRowAutoHeightMutation);+ injector.get(ICommandService).registerCommand(SetColWidthCommand);+ injector.get(ICommandService).registerCommand(SetWorksheetColWidthMutation);+ });- let getMutations: AnyFn | null = null;- const sheetInterceptorService = {- interceptAutoHeight: (config: { getMutations: AnyFn }) => {- getMutations = config.getMutations;- return { dispose: () => { } };- },- } as unknown as SheetInterceptorService;+ afterEach(() => {+ univer.dispose();+ vi.restoreAllMocks();+ });- const controller = new AutoHeightController(- renderManagerService,- sheetInterceptorService,- univerInstanceService- );+ for (const current of ['none', 'other-workbook', 'other-worksheet'] as const) {+ it(`updates only the explicit child worksheet with ${current} current and restores its height on undo`, () => {+ const injector = univer.__getInjector();+ const instances = injector.get(IUniverInstanceService);+ const renderManager = injector.get(IRenderManagerService);+ const peer = instances.createUnit<IWorkbookData, Workbook>(+ UniverInstanceType.UNIVER_SHEET,+ workbookSnapshot('peer'),+ { makeCurrent: false }+ );+ const child = instances.createUnit<IWorkbookData, Workbook>(+ UniverInstanceType.UNIVER_SHEET,+ workbookSnapshot('child'),+ { makeCurrent: false }+ );+ renderManager.createRender('peer');+ renderManager.createRender('child');+ if (current !== 'none') {+ instances.setCurrentUnitForType(current === 'other-workbook' ? 'peer' : 'child');+ }+ injector.get(AutoHeightController);+ const worksheet = child.getSheetBySheetId('sheet2')!;+ const peerBefore = Tools.deepClone(peer.getSnapshot());+ const otherSheetBefore = Tools.deepClone(child.getSheetBySheetId('sheet1')!.getSnapshot());+ const rowsBefore = Tools.deepClone(worksheet.getSnapshot().rowData);+ const result = injector.get(SheetInterceptorService).generateMutationsOfAutoHeight({+ unitId: 'child',+ subUnitId: 'sheet2',+ ranges: [RANGE],+ });- expect(controller).toBeTruthy();- expect(getMutations).not.toBeNull();+ expect(result.redos).toEqual([{+ id: SetWorksheetRowAutoHeightMutation.id,+ params: { unitId: 'child', subUnitId: 'sheet2', rowsAutoHeightInfo: [{ row: 1, autoHeight: 20 }] },+ }]);+ const commands = injector.get(ICommandService);+ for (const mutation of result.redos) {+ expect(commands.syncExecuteCommand(mutation.id, mutation.params)).toBe(true);+ }+ expect(worksheet.getRowHeight(1)).toBe(20);+ expect(worksheet.getRowHeight(3)).toBe(50);+ for (const mutation of result.undos) {+ expect(commands.syncExecuteCommand(mutation.id, mutation.params)).toBe(true);+ }+ expect(worksheet.getSnapshot().rowData).toEqual(rowsBefore);+ for (const mutation of result.redos) {+ expect(commands.syncExecuteCommand(mutation.id, mutation.params)).toBe(true);+ }+ expect(worksheet.getRowHeight(1)).toBe(20);+ expect(peer.getSnapshot()).toEqual(peerBefore);+ expect(child.getSheetBySheetId('sheet1')!.getSnapshot()).toEqual(otherSheetBefore);+ });+ }- const result = getMutations!({- unitId: 'u-1',- subUnitId: 's-1',- ranges: [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 0 }],- lazyAutoHeightRanges: [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 0 }],- }) as { redos: unknown[]; undos: unknown[] };+ for (const current of ['none', 'peer'] as const) {+ it(`completes explicit column resizing and its undo/redo with ${current} current`, async () => {+ const injector = univer.__getInjector();+ const instances = injector.get(IUniverInstanceService);+ const peer = instances.createUnit<IWorkbookData, Workbook>(+ UniverInstanceType.UNIVER_SHEET,+ workbookSnapshot('peer'),+ { makeCurrent: false }+ );+ const child = instances.createUnit<IWorkbookData, Workbook>(+ UniverInstanceType.UNIVER_SHEET,+ workbookSnapshot('child'),+ { makeCurrent: false }+ );+ injector.get(IRenderManagerService).createRender('peer');+ injector.get(IRenderManagerService).createRender('child');+ if (current === 'peer') {+ instances.setCurrentUnitForType('peer');+ instances.focusUnit('peer');+ }+ injector.get(AutoHeightController);+ const target = child.getSheetBySheetId('sheet2')!;+ const before = Tools.deepClone(target.getSnapshot());+ const peerBefore = Tools.deepClone(peer.getSnapshot());+ const commands = injector.get(ICommandService);- const redo = result.redos[0] as { params: { id: string } };- const undo = result.undos[0] as { params: { id: string } };- expect(redo.params.id).toEqual(expect.any(String));- expect(undo.params.id).toBe(redo.params.id);+ expect(await commands.executeCommand(SetColWidthCommand.id, {+ unitId: 'child',+ subUnitId: 'sheet2',+ ranges: [RANGE],+ value: 120,+ })).toBe(true);+ expect(target.getColumnWidth(1)).toBe(120);+ expect(target.getRowHeight(1)).toBe(20);+ expect(peer.getSnapshot()).toEqual(peerBefore);+ const resized = Tools.deepClone(target.getSnapshot());+ instances.focusUnit('child');+ expect(await commands.executeCommand(UndoCommand.id)).toBe(true);+ expect(target.getColumnWidth(1)).toBe(before.defaultColumnWidth);+ expect(target.getSnapshot().rowData).toEqual(before.rowData);+ expect(await commands.executeCommand(RedoCommand.id)).toBe(true);+ expect(target.getSnapshot()).toEqual(resized);+ expect(peer.getSnapshot()).toEqual(peerBefore);+ });+ }- // If our inline execution happened, we should have redo/undo mutations appended.- expect(result.redos).toEqual([- {- id: MarkDirtyRowAutoHeightOperation.id,- params: {- unitId: 'u-1',- subUnitId: 's-1',- ranges: [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 0 }],- id: redo.params.id,- },- options: {- onlyLocal: true,- },- },- ]);+ for (const missing of ['unit', 'worksheet', 'render'] as const) {+ it(`does not fall back to the current Sheet when the explicit target ${missing} is missing`, () => {+ const injector = univer.__getInjector();+ const peer = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, workbookSnapshot('peer'));+ injector.get(IRenderManagerService).createRender('peer');+ injector.get(IUniverInstanceService).createUnit<IWorkbookData, Workbook>(+ UniverInstanceType.UNIVER_SHEET,+ workbookSnapshot('child'),+ { makeCurrent: false }+ );+ if (missing !== 'render') {+ injector.get(IRenderManagerService).createRender('child');+ }+ injector.get(AutoHeightController);+ const before = Tools.deepClone(peer.getSnapshot());+ const result = injector.get(SheetInterceptorService).generateMutationsOfAutoHeight({+ unitId: missing === 'unit' ? 'missing' : 'child',+ subUnitId: missing === 'worksheet' ? 'missing' : 'sheet2',+ ranges: [RANGE],+ });+ expect(result).toEqual({ redos: [], undos: [], preRedos: [], preUndos: [] });+ expect(peer.getSnapshot()).toEqual(before);+ });+ }- expect(result.undos).toEqual([- {- id: CancelMarkDirtyRowAutoHeightOperation.id,- params: {- unitId: 'u-1',- subUnitId: 's-1',- id: redo.params.id,- },- options: {- onlyLocal: true,- },- },- ]);+ it('preserves implicit current-worksheet calls and filters unchanged or manually sized rows', () => {+ const injector = univer.__getInjector();+ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, workbookSnapshot('current'));+ workbook.setActiveSheet(workbook.getSheetBySheetId('sheet2')!);+ injector.get(IRenderManagerService).createRender('current');+ const result = injector.get(AutoHeightController).getUndoRedoParamsOfAutoHeight([RANGE]);+ expect(result.redos).toEqual([{+ id: SetWorksheetRowAutoHeightMutation.id,+ params: { unitId: 'current', subUnitId: 'sheet2', rowsAutoHeightInfo: [{ row: 1, autoHeight: 20 }] },+ }]);+ expect(result.undos).toEqual([{+ id: SetWorksheetRowAutoHeightMutation.id,+ params: { unitId: 'current', subUnitId: 'sheet2', rowsAutoHeightInfo: [{ row: 1, autoHeight: 40 }] },+ }]);});- it('builds row auto-height undo/redo only for rows whose calculated height changed', () => {- const worksheet = {- getSheetId: () => 's-1',- getRowHeight: (row: number) => row === 1 ? 20 : 30,- getRowManager: () => ({- getRow: (row: number) => row === 1 ? { ah: 20 } : { ah: 30 },- }),- getConfig: () => ({ defaultRowHeight: 18 }),- } as unknown;-- const workbook = {- getUnitId: () => 'u-1',- getActiveSheet: () => worksheet,- getSheetBySheetId: (sheetId: string) => (sheetId === 's-1' ? worksheet : null),- } as unknown as Workbook;-- const controller = new AutoHeightController(- {- getRenderUnitById: () => ({- with: () => ({- ensureSkeleton: () => ({- calculateAutoHeightInRange: () => [- { row: 1, autoHeight: 24 },- { row: 2, autoHeight: 30 },- { row: 3, autoHeight: 0 },- ],- }),- }),- }),- } as unknown as RenderManagerService,- { interceptAutoHeight: () => ({ dispose: () => { } }) } as unknown as SheetInterceptorService,- {- getCurrentUnitOfType: () => workbook,- getUnit: () => workbook,- } as unknown as IUniverInstanceService- );-- expect(controller.getUndoRedoParamsOfAutoHeight([- { startRow: 1, endRow: 3, startColumn: 0, endColumn: 0 },- ])).toEqual({- redos: [{- id: SetWorksheetRowAutoHeightMutation.id,- params: {- unitId: 'u-1',- subUnitId: 's-1',- rowsAutoHeightInfo: [{ row: 1, autoHeight: 24 }],- },- }],- undos: [{- id: SetWorksheetRowAutoHeightMutation.id,- params: {- unitId: 'u-1',- subUnitId: 's-1',- rowsAutoHeightInfo: [{ row: 1, autoHeight: 20 }],- },- }],- });+ it('keeps lazy dirty-row operations paired and unregisters the interceptor on disposal', () => {+ const injector = univer.__getInjector();+ univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, workbookSnapshot('current'));+ injector.get(IRenderManagerService).createRender('current');+ const controller = injector.get(AutoHeightController);+ const interceptor = injector.get(SheetInterceptorService);+ const context = { unitId: 'current', subUnitId: 'sheet2', ranges: [], lazyAutoHeightRanges: [RANGE] };+ const result = interceptor.generateMutationsOfAutoHeight(context);+ expect(result.redos).toEqual([{+ id: MarkDirtyRowAutoHeightOperation.id,+ params: { unitId: 'current', subUnitId: 'sheet2', ranges: [RANGE], id: expect.any(String) },+ options: { onlyLocal: true },+ }]);+ expect(result.undos).toEqual([{+ id: CancelMarkDirtyRowAutoHeightOperation.id,+ params: { unitId: 'current', subUnitId: 'sheet2', id: (result.redos[0].params as { id: string }).id },+ options: { onlyLocal: true },+ }]);+ controller.dispose();+ expect(interceptor.generateMutationsOfAutoHeight(context)).toEqual({ redos: [], undos: [], preRedos: [], preUndos: [] });});});++function workbookSnapshot(id: string): IWorkbookData {+ return {+ id,+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: id,+ styles: {},+ sheetOrder: ['sheet1', 'sheet2'],+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'Peer sheet',+ rowCount: 5,+ columnCount: 3,+ defaultRowHeight: 30,+ rowData: { 1: { ah: 60 } },+ },+ sheet2: {+ id: 'sheet2',+ name: 'Target sheet',+ rowCount: 5,+ columnCount: 3,+ defaultRowHeight: 20,+ rowData: { 1: { ah: 40 }, 2: { ah: 20 }, 3: { h: 50, ia: BooleanNumber.FALSE } },+ },+ },+ };+}diff --git a/packages/sheets-ui/src/controllers/auto-height.controller.ts b/packages/sheets-ui/src/controllers/auto-height.controller.tsindex f227de5fa5..81818e47dc 100644--- a/packages/sheets-ui/src/controllers/auto-height.controller.ts+++ b/packages/sheets-ui/src/controllers/auto-height.controller.ts@@ -14,9 +14,9 @@* limitations under the License.*/-import type { IMutationInfo, IRange, ObjectMatrix, Workbook } from '@univerjs/core';+import type { IMutationInfo, IRange, ObjectMatrix } from '@univerjs/core';import type { ISetWorksheetRowAutoHeightMutationParams } from '@univerjs/sheets';-import { Disposable, generateRandomId, Inject, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';+import { Disposable, generateRandomId, Inject, IUniverInstanceService } from '@univerjs/core';import { IRenderManagerService } from '@univerjs/engine-render';import {CancelMarkDirtyRowAutoHeightOperation,@@ -73,32 +73,26 @@ export class AutoHeightController extends Disposable {return redoUndoItem;}- getUndoRedoParamsOfAutoHeight(ranges: IRange[], subUnitIdParam?: string, currentCellHeights?: ObjectMatrix<number>): { redos: IMutationInfo[]; undos: IMutationInfo[] } {- const { _univerInstanceService: univerInstanceService } = this;- const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;-- // Better NOT use `getActiveWorksheet` method, because users may manipulate another worksheet in active sheet.- const unitId = workbook.getUnitId();- let worksheet = workbook.getActiveSheet();- let subUnitId = worksheet.getSheetId();- if (subUnitIdParam) {- const target = getSheetCommandTarget(univerInstanceService, { unitId, subUnitId: subUnitIdParam });- if (target) {- worksheet = target.worksheet;- subUnitId = worksheet.getSheetId();- }+ getUndoRedoParamsOfAutoHeight(+ ranges: IRange[],+ subUnitIdParam?: string,+ currentCellHeights?: ObjectMatrix<number>,+ unitIdParam?: string+ ): { redos: IMutationInfo[]; undos: IMutationInfo[] } {+ const target = getSheetCommandTarget(this._univerInstanceService, { unitId: unitIdParam, subUnitId: subUnitIdParam });+ if (!target) {+ return { redos: [], undos: [] };}- const sheetSkeletonService = this._renderManagerService.getRenderUnitById(unitId)!.with<SheetSkeletonManagerService>(SheetSkeletonManagerService);- // Better NOT use `getCurrentParam` method, because users may manipulate another worksheet in active sheet.- // const { skeleton } = sheetSkeletonService.getCurrentParam()!;- const skeleton = sheetSkeletonService.ensureSkeleton(subUnitId);+ const { unitId, subUnitId, worksheet } = target;+ const render = this._renderManagerService.getRenderUnitById(unitId);+ const skeleton = render?.with<SheetSkeletonManagerService>(SheetSkeletonManagerService).ensureSkeleton(subUnitId);if (!skeleton) {return {redos: [],undos: [],};- };+ }const rowsAutoHeightInfo = skeleton.calculateAutoHeightInRange(ranges, currentCellHeights);const updatedRowsAutoHeightInfo = rowsAutoHeightInfo.filter((info) => {@@ -147,7 +141,7 @@ export class AutoHeightController extends Disposable {getMutations: (info) => {const { unitId, subUnitId, ranges, autoHeightRanges, lazyAutoHeightRanges, cellHeights } = info;- const undoRedoItem = this.getUndoRedoParamsOfAutoHeight(autoHeightRanges ?? ranges, subUnitId, cellHeights);+ const undoRedoItem = this.getUndoRedoParamsOfAutoHeight(autoHeightRanges ?? ranges, subUnitId, cellHeights, unitId);return this._processLazyAutoHeight(undoRedoItem, unitId, subUnitId, lazyAutoHeightRanges);},}));diff --git a/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts b/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.tsindex 357dea4e2c..8fb8ba9211 100644--- a/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts+++ b/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts@@ -46,6 +46,7 @@ import {DEFAULT_WORKSHEET_COLUMN_WIDTH,DEFAULT_WORKSHEET_COLUMN_WIDTH_KEY,DOCS_NORMAL_EDITOR_UNIT_ID_KEY,+ EDITOR_ACTIVATED,extractPureTextFromCell,getNumfmtLocaleTag,getNumfmtParseValueFilter,@@ -59,6 +60,7 @@ import {IUniverInstanceService,LocaleService,ObjectMatrix,+ Optional,RxDisposable,Tools,UniverInstanceType,@@ -103,6 +105,7 @@ import {PREDEFINED_HOOK_NAME_COPY,PREDEFINED_HOOK_NAME_PASTE,} from '../../services/clipboard/clipboard.service';+import { ISheetEmbedRuntimeFocusCoordinator } from '../../services/sheet-embed-integration.service';import { SheetSkeletonManagerService } from '../../services/sheet-skeleton-manager.service';import { whenSheetEditorFocused } from '../shortcuts/utils';import { RemovePasteMenuCommands } from './const';@@ -143,7 +146,9 @@ export class SheetClipboardController extends RxDisposable {@ISheetClipboardService private readonly _sheetClipboardService: ISheetClipboardService,@IClipboardInterfaceService private readonly _clipboardInterfaceService: IClipboardInterfaceService,@IMessageService private readonly _messageService: IMessageService,- @Inject(LocaleService) private readonly _localService: LocaleService+ @Inject(LocaleService) private readonly _localService: LocaleService,+ @Optional(ISheetEmbedRuntimeFocusCoordinator)+ private readonly _embedRuntimeFocusCoordinator?: ISheetEmbedRuntimeFocusCoordinator) {super();this._init();@@ -158,7 +163,7 @@ export class SheetClipboardController extends RxDisposable {private _pasteWithDoc() {const sheetPasteShortKeyFn = (docSelectionRenderService: DocSelectionRenderService) => {docSelectionRenderService.onPaste$.pipe(takeUntil(this.dispose$)).subscribe(async (config) => {- if (!whenSheetEditorFocused(this._contextService)) {+ if (!this._isSheetGridPasteTarget()) {return;}@@ -169,13 +174,18 @@ export class SheetClipboardController extends RxDisposable {const htmlContent = clipboardEvent.clipboardData?.getData('text/html');const textContent = clipboardEvent.clipboardData?.getData('text/plain');const files = this._resolveClipboardFiles(clipboardEvent.clipboardData);+ const target = this._sheetClipboardService.capturePasteTarget();+ if (!target) {+ return;+ }const formulaClipboardPayload = await this._readFormulaClipboardPayload();- this._commandService.executeCommand(SheetPasteShortKeyCommand.id, {+ await this._commandService.executeCommand(SheetPasteShortKeyCommand.id, {htmlContent,textContent,files,formulaClipboardPayload,+ target,});});@@ -205,6 +215,25 @@ export class SheetClipboardController extends RxDisposable {});}+ private _isSheetGridPasteTarget(): boolean {+ if (whenSheetEditorFocused(this._contextService)) {+ return true;+ }++ const activeRuntime = this._embedRuntimeFocusCoordinator?.resolveActiveChildSessionRuntimeScope();+ if (+ activeRuntime?.childType !== UniverInstanceType.UNIVER_SHEET ||+ !activeRuntime.childUnitId ||+ this._contextService.getContextValue(EDITOR_ACTIVATED)+ ) {+ return false;+ }++ return this._instanceService+ .getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)+ ?.getUnitId() === activeRuntime.childUnitId;+ }+private _resolveClipboardFiles(clipboardData: DataTransfer | null) {if (!clipboardData) {return;diff --git a/packages/sheets-ui/src/controllers/editor/__tests__/editing-render-business.spec.ts b/packages/sheets-ui/src/controllers/editor/__tests__/editing-render-business.spec.tsindex a696dcdcab..203324d458 100644--- a/packages/sheets-ui/src/controllers/editor/__tests__/editing-render-business.spec.ts+++ b/packages/sheets-ui/src/controllers/editor/__tests__/editing-render-business.spec.ts@@ -23,6 +23,7 @@ import {FOCUSING_EDITOR_INPUT_FORMULA,FOCUSING_FX_BAR_EDITOR,LocaleType,+ Styles,UniverInstanceType,} from '@univerjs/core';import { InsertTextCommand } from '@univerjs/docs';@@ -77,7 +78,7 @@ function createController(initialDataStream = 'new value\r\n', isPercentFormat =getCellRaw: vi.fn(() => ({ v: 'old' })),getComposedCellStyleWithoutSelf: vi.fn(() => ({})),};- const styles = { get: vi.fn(() => undefined) };+ const styles = new Styles();const workbook = {getUnitId: vi.fn(() => 'unit-1'),getActiveSheet: vi.fn(() => worksheet),@@ -298,6 +299,25 @@ describe('EditingRenderController business methods', () => {expect(controller._undoRedoService.rollback).toHaveBeenCalledWith(expect.any(String), 'unit-1');});+ it('captures rich-text cell data independently from the reusable editor snapshot', async () => {+ const { controller } = createController();+ const snapshot = {+ body: {+ dataStream: 'rich text\r\n',+ textRuns: [{ st: 5, ed: 9, ts: { bl: 1 } }],+ },+ documentStyle: {},+ };++ await controller._submitEdit(snapshot);+ const submitted = controller._commandService.syncExecuteCommand.mock.calls+ .find(([id]: [string]) => id === SetRangeValuesCommand.id)?.[1];+ snapshot.body.textRuns = [];++ expect(submitted?.value.p).not.toBe(snapshot);+ expect(submitted?.value.p?.body?.textRuns).toEqual([{ st: 5, ed: 9, ts: { bl: 1 } }]);+ });+it('uses the whole current selection when committing an array edit', async () => {const { controller } = createController();diff --git a/packages/sheets-ui/src/controllers/editor/__tests__/editing.render-controller.spec.ts b/packages/sheets-ui/src/controllers/editor/__tests__/editing.render-controller.spec.tsnew file mode 100644index 0000000000..26f65a9eb2--- /dev/null+++ b/packages/sheets-ui/src/controllers/editor/__tests__/editing.render-controller.spec.ts@@ -0,0 +1,58 @@+/**+ * 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 { ICellData } from '@univerjs/core';+import { CellValueType, Styles, Tools } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { getComparableCellData } from '../editing.render-controller';++describe('cell editor commit comparison', () => {+ const unchanged: Array<{ name: string; previous: ICellData; incoming: ICellData }> = [+ { name: 'ordinary text after draft Undo', previous: { v: 'Committed', t: CellValueType.STRING }, incoming: { v: 'Committed' } },+ { name: 'number text', previous: { v: 42, t: CellValueType.NUMBER }, incoming: { v: '42' } },+ { name: 'zero', previous: { v: 0, t: CellValueType.NUMBER }, incoming: { v: '0' } },+ { name: 'true', previous: { v: 1, t: CellValueType.BOOLEAN }, incoming: { v: 'TRUE' } },+ { name: 'false', previous: { v: 0, t: CellValueType.BOOLEAN }, incoming: { v: 'FALSE' } },+ { name: 'forced text', previous: { v: '001', t: CellValueType.FORCE_STRING }, incoming: { v: '001', t: CellValueType.FORCE_STRING } },+ { name: 'inherited text format', previous: { v: '001', t: CellValueType.STRING, s: 'text' }, incoming: { v: '001', s: 'text' } },+ { name: 'resolved equivalent style', previous: { v: 'Styled', t: CellValueType.STRING, s: 'blue' }, incoming: { v: 'Styled', s: { cl: { rgb: '#0000ff' } } } },+ ];++ it.each(unchanged)('recognizes unchanged $name without mutating the input or styles', ({ previous, incoming }) => {+ const styles = new Styles({ text: { n: { pattern: '@' } }, blue: { cl: { rgb: '#0000ff' } } });+ const previousBefore = Tools.deepClone(previous);+ const incomingBefore = Tools.deepClone(incoming);+ expect(getComparableCellData(incoming, styles, previous)).toEqual(getComparableCellData(previous, styles, previous));+ expect(previous).toEqual(previousBefore);+ expect(incoming).toEqual(incomingBefore);+ expect(styles.get('text')).toEqual({ n: { pattern: '@' } });+ expect(styles.get('blue')).toEqual({ cl: { rgb: '#0000ff' } });+ });++ const changed: Array<{ name: string; previous: ICellData; incoming: ICellData }> = [+ { name: 'actual text edit', previous: { v: 'old', t: CellValueType.STRING }, incoming: { v: 'new' } },+ { name: 'numeric conversion from text', previous: { v: '001', t: CellValueType.STRING }, incoming: { v: '001' } },+ { name: 'removing forced text', previous: { v: '001', t: CellValueType.FORCE_STRING }, incoming: { v: '001' } },+ { name: 'boolean conversion', previous: { v: 'TRUE', t: CellValueType.STRING }, incoming: { v: 'TRUE' } },+ { name: 'format-only edit', previous: { v: 'same', t: CellValueType.STRING, s: { bl: 0 } }, incoming: { v: 'same', s: { bl: 1 } } },+ { name: 'formula replacement', previous: { v: 2, t: CellValueType.NUMBER, f: '=1+1' }, incoming: { v: null, f: '=1+2' } },+ ];++ it.each(changed)('preserves a meaningful $name', ({ previous, incoming }) => {+ const styles = new Styles();+ expect(getComparableCellData(incoming, styles, previous)).not.toEqual(getComparableCellData(previous, styles, previous));+ });+});diff --git a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts b/packages/sheets-ui/src/controllers/editor/editing.render-controller.tsindex 5cfc04a7e3..6f1e862a99 100644--- a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts+++ b/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts@@ -89,6 +89,8 @@ import { convertTextRotation, DeviceInputEventType, IRenderManagerService } fromimport {adjustRangeOnMutation,COMMAND_LISTENER_SKELETON_CHANGE,+ getCellType,+ getCellValue,InsertColMutation,InsertRowMutation,isCellImage,@@ -504,8 +506,12 @@ export class EditingRenderController extends Disposable {* the up, down, left, and right keys can no longer switch editing cells,* but move the cursor within the editor instead.*/- if (keycode != null &&- (this._cursorChange === CursorChange.CursorChange || this._contextService.getContextValue(FOCUSING_FX_BAR_EDITOR))) {+ // Shift+arrows select text even when typing opened the editor without a pointer or F2.+ if (keycode != null && (+ isShift ||+ this._cursorChange === CursorChange.CursorChange ||+ this._contextService.getContextValue(FOCUSING_FX_BAR_EDITOR)+ )) {this._moveInEditor(keycode, isShift);return;}@@ -812,14 +818,9 @@ export class EditingRenderController extends Disposable {const finalCell = this._sheetInterceptorService.onWriteCell(workbook, worksheet, row, column, cellData) as ICellData;// If the cell data after interceptor is the same as the raw cell data, there is no need to execute setRangeValue command, just return directly.- const finalCellCleaned = cleanCellDataObject(finalCell);- if (finalCellCleaned?.s) {- finalCellCleaned.s = workbook.getStyles().get(finalCellCleaned.s);- }- const rawCellCleaned = cleanCellDataObject(worksheet.getCellRaw(row, column));- if (rawCellCleaned?.s) {- rawCellCleaned.s = workbook.getStyles().get(rawCellCleaned.s);- }+ const rawCell = worksheet.getCellRaw(row, column);+ const finalCellCleaned = getComparableCellData(finalCell, workbook.getStyles(), rawCell);+ const rawCellCleaned = getComparableCellData(rawCell, workbook.getStyles(), rawCell);if (Tools.diffValue(finalCellCleaned, rawCellCleaned)) {return true;}@@ -838,7 +839,7 @@ export class EditingRenderController extends Disposable {subUnitId: sheetId,unitId,range,- value: finalCell,+ value: Tools.deepClone(finalCell),redoUndoId,});@@ -1226,13 +1227,35 @@ export function emptyBody(body: IDocumentBody, removeStyle = false) {}}-function cleanCellDataObject(cellData: Nullable<ICellData>): Nullable<ICellData> {- if (!cellData) return cellData;+export function getComparableCellData(+ cellData: Nullable<ICellData>,+ styles: Styles,+ originalCell: Nullable<ICellData>+): Nullable<ICellData> {+ if (!cellData) {+ return cellData;+ }+ const normalized = { ...cellData };+ if (cellData.v != null) {+ // Compare the value that SetRangeValuesMutation will persist, including its inferred type.+ const type = getCellType(styles, cellData, originalCell ?? {});+ normalized.t = type;+ normalized.v = getCellValue(type, cellData);+ }+ if (normalized.s) {+ normalized.s = styles.get(normalized.s);+ }return Object.fromEntries(- Object.entries(cellData).filter(([_, value]) => {- if (value === undefined || value === null) return false;- if (Array.isArray(value) && value.length === 0) return false;- if (typeof value === 'object' && Object.keys(value).length === 0) return false;+ Object.entries(normalized).filter(([_, value]) => {+ if (value === undefined || value === null) {+ return false;+ }+ if (Array.isArray(value) && value.length === 0) {+ return false;+ }+ if (typeof value === 'object' && Object.keys(value).length === 0) {+ return false;+ }return true;}));diff --git a/packages/sheets-ui/src/controllers/permission/__tests__/sheet-permission-interceptor-clipboard.controller.spec.ts b/packages/sheets-ui/src/controllers/permission/__tests__/sheet-permission-interceptor-clipboard.controller.spec.tsindex 4e9d742891..cd694bb6aa 100644--- a/packages/sheets-ui/src/controllers/permission/__tests__/sheet-permission-interceptor-clipboard.controller.spec.ts+++ b/packages/sheets-ui/src/controllers/permission/__tests__/sheet-permission-interceptor-clipboard.controller.spec.ts@@ -14,67 +14,88 @@* limitations under the License.*/-import { UnitAction } from '@univerjs/protocol';-import { describe, expect, it, vi } from 'vitest';+import type { Univer, Workbook } from '@univerjs/core';+import {+ CustomCommandExecutionError,+ IPermissionService,+ IUniverInstanceService,+ LocaleService,+ LocaleType,+ Tools,+ UniverInstanceType,+} from '@univerjs/core';+import { UnitObject } from '@univerjs/protocol';+import {+ EditStateEnum,+ RangeProtectionPermissionEditPoint,+ RangeProtectionRuleModel,+ SheetPermissionCheckController,+ SheetsSelectionsService,+ ViewStateEnum,+} from '@univerjs/sheets';+import { afterEach, describe, expect, it } from 'vitest';+import enUS from '../../../locale/en-US';+import { clipboardTestBed } from '../../../services/clipboard/__tests__/clipboard-test-bed';+import { ISheetClipboardService } from '../../../services/clipboard/clipboard.service';import { SHEET_PERMISSION_PASTE_PLUGIN, SheetPermissionInterceptorClipboardController } from '../sheet-permission-interceptor-clipboard.controller';-function createController(protectedCell?: { row: number; col: number }) {- let hook: any;- const worksheet = {- getCell: vi.fn((row: number, col: number) => protectedCell?.row === row && protectedCell?.col === col- ? { selectionProtection: [{ [UnitAction.Edit]: false }] }- : { selectionProtection: [{ [UnitAction.Edit]: true }] }),- };- const workbook = { getActiveSheet: vi.fn(() => worksheet) };- const permissionCheckController = { blockExecuteWithoutPermission: vi.fn() };- const controller = new SheetPermissionInterceptorClipboardController(- { getCurrentUnitOfType: vi.fn(() => workbook) } as any,- {- getCurrentLastSelection: vi.fn(() => ({- range: { startRow: 5, startColumn: 7 },- })),- } as any,- { t: vi.fn((key: string) => `translated:${key}`) } as any,- {- addClipboardHook: vi.fn((registeredHook) => {- hook = registeredHook;- return { dispose: vi.fn() };- }),- } as any,- permissionCheckController as any- );-- return { controller, hook, permissionCheckController, worksheet };-}-describe('SheetPermissionInterceptorClipboardController', () => {- it('allows paste when the target range has edit permission', () => {- const { controller, hook, permissionCheckController } = createController();-- expect(hook.id).toBe(SHEET_PERMISSION_PASTE_PLUGIN);- expect(hook.onBeforePaste({- range: {- rows: [0, 1],- cols: [0, 1],- },- })).toBe(true);- expect(permissionCheckController.blockExecuteWithoutPermission).not.toHaveBeenCalled();-- controller.dispose();- });-- it('blocks paste and shows permission feedback when any pasted cell is protected', () => {- const { controller, hook, permissionCheckController, worksheet } = createController({ row: 6, col: 8 });+ let univer: Univer;- expect(hook.onBeforePaste({- range: {- rows: [0, 1],- cols: [0, 1],- },- })).toBe(false);- expect(worksheet.getCell).toHaveBeenCalledWith(6, 8);- expect(permissionCheckController.blockExecuteWithoutPermission).toHaveBeenCalledWith('translated:sheets-ui.permission.dialog.pasteErr');+ afterEach(() => univer.dispose());+ it.each(['none', 'source', 'peer'] as const)('checks the original absolute paste range with protection on %s', (protectedTarget) => {+ const testBed = clipboardTestBed(undefined, [[SheetPermissionInterceptorClipboardController]]);+ univer = testBed.univer;+ const { get } = testBed;+ const localeService = get(LocaleService);+ localeService.load({ [LocaleType.EN_US]: enUS });+ localeService.setLocale(LocaleType.EN_US);+ const controller = get(SheetPermissionInterceptorClipboardController);+ const instances = get(IUniverInstanceService);+ const source = instances.getUnit<Workbook>('test', UniverInstanceType.UNIVER_SHEET)!;+ instances.createUnit(UniverInstanceType.UNIVER_SHEET, { ...Tools.deepClone(source.getSnapshot()), id: 'peer' });+ instances.setCurrentUnitForType('peer');+ get(SheetsSelectionsService).setSelections('peer', 'sheet1', [{+ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },+ primary: null,+ style: null,+ }]);+ if (protectedTarget !== 'none') {+ const unitId = protectedTarget === 'source' ? 'test' : 'peer';+ const permissionId = 'protected-paste-cell';+ get(RangeProtectionRuleModel).addRule(unitId, 'sheet1', {+ unitId,+ subUnitId: 'sheet1',+ id: 'rule',+ permissionId,+ ranges: [{ startRow: 6, endRow: 6, startColumn: 8, endColumn: 8 }],+ unitType: UnitObject.SelectRange,+ viewState: ViewStateEnum.OthersCanView,+ editState: EditStateEnum.OnlyMe,+ });+ const point = new RangeProtectionPermissionEditPoint(unitId, 'sheet1', permissionId);+ get(IPermissionService).addPermissionPoint(point);+ get(IPermissionService).updatePermissionPoint(point.id, false);+ }+ const clipboard = get(ISheetClipboardService);+ const hook = clipboard.getClipboardHooks().find((item) => item.id === SHEET_PERMISSION_PASTE_PLUGIN)!;+ const messages: string[] = [];+ const subscription = get(SheetPermissionCheckController).triggerPermissionUIEvent$.subscribe((message) => messages.push(message));+ const paste = () => hook.onBeforePaste!({+ unitId: 'test',+ subUnitId: 'sheet1',+ range: { rows: [5, 6], cols: [7, 8] },+ });+ if (protectedTarget === 'source') {+ expect(paste).toThrow(CustomCommandExecutionError);+ expect(messages).toEqual([enUS['sheets-ui'].permission.dialog.pasteErr]);+ } else {+ expect(paste()).toBe(true);+ expect(messages).toEqual([]);+ }+ subscription.unsubscribe();controller.dispose();+ expect(clipboard.getClipboardHooks().some((item) => item.id === SHEET_PERMISSION_PASTE_PLUGIN)).toBe(false);});});diff --git a/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-clipboard.controller.ts b/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-clipboard.controller.tsindex bc7559d2c2..ff4273a997 100644--- a/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-clipboard.controller.ts+++ b/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-clipboard.controller.ts@@ -18,26 +18,27 @@ import type { ICellDataForSheetInterceptor, IRange, Workbook } from '@univerjs/cimport type { LocaleKey } from '../../locale/types';import {Disposable,- DisposableCollection,Inject,IUniverInstanceService,LocaleService,UniverInstanceType,} from '@univerjs/core';import { UnitAction } from '@univerjs/protocol';-import { SheetPermissionCheckController, SheetsSelectionsService } from '@univerjs/sheets';+import {+ discreteRangeToRange,+ RangeProtectionPermissionEditPoint,+ SheetPermissionCheckController,+ WorkbookEditablePermission,+ WorksheetEditPermission,+} from '@univerjs/sheets';import { ISheetClipboardService } from '../../services/clipboard/clipboard.service';-import { virtualizeDiscreteRanges } from '../utils/range-tools';type ICellPermission = Record<UnitAction, boolean> & { ruleId?: string; ranges?: IRange[] };export const SHEET_PERMISSION_PASTE_PLUGIN = 'SHEET_PERMISSION_PASTE_PLUGIN';export class SheetPermissionInterceptorClipboardController extends Disposable {- disposableCollection = new DisposableCollection();-constructor(@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,- @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,@Inject(LocaleService) private readonly _localService: LocaleService,@Inject(ISheetClipboardService) private _sheetClipboardService: ISheetClipboardService,@Inject(SheetPermissionCheckController) private readonly _sheetPermissionCheckController: SheetPermissionCheckController@@ -51,30 +52,28 @@ export class SheetPermissionInterceptorClipboardController extends Disposable {this._sheetClipboardService.addClipboardHook({id: SHEET_PERMISSION_PASTE_PLUGIN,onBeforePaste: (pasteTo) => {- const [ranges] = virtualizeDiscreteRanges([pasteTo.range]).ranges;- const startRange = this._selectionManagerService.getCurrentLastSelection()?.range;- if (!startRange) {+ const { unitId, subUnitId, range } = pasteTo;+ const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);+ const worksheet = workbook?.getSheetBySheetId(subUnitId);+ if (!worksheet) {return false;}- const targetRange = {- startRow: startRange.startRow + ranges.startRow,- endRow: startRange.startRow + ranges.endRow,- startColumn: startRange.startColumn + ranges.startColumn,- endColumn: startRange.startColumn + ranges.endColumn,- };- const workbook = this._univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;- const worksheet = workbook.getActiveSheet();- if (!worksheet) {+ if (!this._sheetPermissionCheckController.permissionCheckWithRanges({+ workbookTypes: [WorkbookEditablePermission],+ worksheetTypes: [WorksheetEditPermission],+ rangeTypes: [RangeProtectionPermissionEditPoint],+ }, [discreteRangeToRange(range)], unitId, subUnitId)) {+ this._sheetPermissionCheckController.blockExecuteWithoutPermission(+ this._localService.t<LocaleKey>('sheets-ui.permission.dialog.pasteErr')+ );return false;}- const { startRow, endRow, startColumn, endColumn } = targetRange;-let hasPermission = true;- for (let row = startRow; row <= endRow; row++) {- for (let col = startColumn; col <= endColumn; col++) {+ for (const row of range.rows) {+ for (const col of range.cols) {const permission = (worksheet.getCell(row, col) as (ICellDataForSheetInterceptor & { selectionProtection: ICellPermission[] }))?.selectionProtection?.[0];if (permission?.[UnitAction.Edit] === false) {hasPermission = false;diff --git a/packages/sheets-ui/src/controllers/render-controllers/__tests__/editor-bridge-render-business.spec.ts b/packages/sheets-ui/src/controllers/render-controllers/__tests__/editor-bridge-render-business.spec.tsindex 9403816c78..5742de723a 100644--- a/packages/sheets-ui/src/controllers/render-controllers/__tests__/editor-bridge-render-business.spec.ts+++ b/packages/sheets-ui/src/controllers/render-controllers/__tests__/editor-bridge-render-business.spec.ts@@ -119,6 +119,8 @@ function createController(options?: {]),};const docSelectionRenderService = {+ focus: vi.fn(),+ isFocusing: false,onInputBefore$: inputBefore$,setInputPosition: vi.fn(),};@@ -162,6 +164,9 @@ function createController(options?: {selectionMoveStart$,selectionSet$,getWorkbookSelections: vi.fn(() => ({+ selectionMoveEnd$,+ selectionMoveStart$,+ selectionSet$,getCurrentSelections: vi.fn(() => [{primary: {actualRow: 3,@@ -356,6 +361,49 @@ describe('EditorBridgeRenderController business flows', () => {controller.dispose();});+ it('does not reopen mobile editing implicitly when a selection changes', () => {+ const { commandService, controller, selectionMoveEnd$, spreadsheet } = createController({+ editorVisible: true,+ disableAutoFocus: true,+ });++ spreadsheet.onPointerDown$.emit({});+ expect(commandService.syncExecuteCommand).toHaveBeenCalledWith(SetCellEditVisibleOperation.id, {+ visible: false,+ eventType: DeviceInputEventType.PointerDown,+ unitId: 'unit-1',+ });++ selectionMoveEnd$.next([{+ primary: {+ actualRow: 3,+ actualColumn: 4,+ startRow: 3,+ startColumn: 4,+ endRow: 3,+ endColumn: 4,+ },+ }]);++ expect(commandService.syncExecuteCommand).toHaveBeenCalledTimes(1);+ expect(commandService.executeCommand).not.toHaveBeenCalled();++ controller.dispose();+ });++ it('focuses the hidden input when an active embedded sheet clicks the unchanged cell', () => {+ const { controller, docSelectionRenderService, spreadsheet } = createController({+ focusedUnitId: 'host-unit',+ focusingSheet: false,+ isEmbedActiveSession: true,+ });++ spreadsheet.onPointerDown$.emit({});++ expect(docSelectionRenderService.focus).toHaveBeenCalledTimes(1);+ controller.dispose();+ });+it('opens sheet editing from keyboard input while the sheet is an active embed child session', () => {const { commandService, controller, inputBefore$ } = createController({focusingSheet: false,diff --git a/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.tsindex b9a1186f08..1a657614a0 100644--- a/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts+++ b/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts@@ -29,7 +29,7 @@ import {SetWorksheetActiveOperation,SheetsSelectionsService,} from '@univerjs/sheets';-import { DISABLE_AUTO_FOCUS_KEY } from '@univerjs/ui';+import { DISABLE_AUTO_FOCUS_KEY, getEmbedChildUnitId } from '@univerjs/ui';import { filter, merge } from 'rxjs';import { SetZoomRatioCommand } from '../../commands/commands/set-zoom-ratio.command';import { SetActivateCellEditOperation } from '../../commands/operations/activate-cell-edit.operation';@@ -85,11 +85,12 @@ export class EditorBridgeRenderController extends RxDisposable implements IRende}private _initSelectionChangeListener(d: DisposableCollection) {+ const selections = this._selectionManagerService.getWorkbookSelections(this._context.unitId);d.add(merge(- this._selectionManagerService.selectionSet$,- this._selectionManagerService.selectionMoveStart$+ selections.selectionSet$,+ selections.selectionMoveStart$).subscribe((params) => this._updateEditorPosition(params)));- d.add(this._selectionManagerService.selectionMoveEnd$.subscribe((params) => {+ d.add(selections.selectionMoveEnd$.subscribe((params) => {this._updateEditorPosition(params);if (params?.[params.length - 1]?.primary) {this._updateInputPosition();@@ -191,7 +192,10 @@ export class EditorBridgeRenderController extends RxDisposable implements IRende}));d.add(spreadsheet.onPointerDown$.subscribeEvent({- next: (payload) => this._tryHideEditor(resolvePointerEventPayload(payload)),+ next: (payload) => {+ this._tryHideEditor(resolvePointerEventPayload(payload));+ this._focusCellEditorInput();+ },priority: -1,}));d.add(spreadsheetColumnHeader.onPointerDown$.subscribeEvent({@@ -268,6 +272,17 @@ export class EditorBridgeRenderController extends RxDisposable implements IRende}private _focusCellEditorInput(): void {+ // Restoring the host context after a child command must not reclaim the child's keyboard focus.+ const focusedChildUnitId = getEmbedChildUnitId(typeof document === 'undefined' ? null : document.activeElement);+ if (+ (focusedChildUnitId != null && focusedChildUnitId !== this._context.unitId) ||+ !this._isCurrentSheetFocused() ||+ this._contextService.getContextValue(FOCUSING_FX_BAR_EDITOR) ||+ this._editorBridgeService.isVisible().visible+ ) {+ return;+ }+const render = this._renderManagerService.getRenderUnitById(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);const docSelectionRenderService = render?.with(DocSelectionRenderService);diff --git a/packages/sheets-ui/src/controllers/shortcuts/__tests__/editor.shortcut.spec.ts b/packages/sheets-ui/src/controllers/shortcuts/__tests__/editor.shortcut.spec.tsindex 9cac6dd433..d381f11712 100644--- a/packages/sheets-ui/src/controllers/shortcuts/__tests__/editor.shortcut.spec.ts+++ b/packages/sheets-ui/src/controllers/shortcuts/__tests__/editor.shortcut.spec.ts@@ -14,12 +14,57 @@* limitations under the License.*/+import {+ ContextService,+ Direction,+ EDITOR_ACTIVATED,+ FOCUSING_EDITOR_INPUT_FORMULA,+ FOCUSING_SHEET,+ FOCUSING_UNIVER_EDITOR,+ IContextService,+ Injector,+} from '@univerjs/core';+import { MoveCursorOperation, MoveSelectionOperation } from '@univerjs/docs-ui';import { DeviceInputEventType } from '@univerjs/engine-render';import { KeyCode, MetaKeys } from '@univerjs/ui';import { describe, expect, it } from 'vitest';-import { EditorCursorShiftEnterShortcut, EditorCursorShiftTabShortcut } from '../editor.shortcut';+import {+ EditorCursorShiftEnterShortcut,+ EditorCursorShiftTabShortcut,+ generateArrowSelectionShortCutItem,+} from '../editor.shortcut';describe('editor shortcuts', () => {+ it.each([false, true])('moves to line boundaries with selection extension=%s only in an active Sheet text editor', (extend) => {+ const injector = new Injector();+ injector.add([IContextService, { useClass: ContextService }]);+ const context = injector.get(IContextService);+ context.setContextValue(FOCUSING_SHEET, true);+ context.setContextValue(FOCUSING_UNIVER_EDITOR, true);+ context.setContextValue(EDITOR_ACTIVATED, true);+ const shortcuts = generateArrowSelectionShortCutItem();+ const shift = extend ? MetaKeys.SHIFT : 0;+ for (const [key, arrow, direction] of [+ [KeyCode.HOME, KeyCode.ARROW_LEFT, Direction.LEFT],+ [KeyCode.END, KeyCode.ARROW_RIGHT, Direction.RIGHT],+ ]) {+ const shortcut = shortcuts.find((item) => item.binding === (key | shift));+ expect(shortcut).toBeDefined();+ expect(shortcut).toMatchObject({+ id: extend ? MoveSelectionOperation.id : MoveCursorOperation.id,+ mac: arrow | MetaKeys.CTRL_COMMAND | shift,+ staticParameters: { direction, granularity: 'line' },+ });+ expect(shortcut!.preconditions!(context)).toBe(true);+ context.setContextValue(EDITOR_ACTIVATED, false);+ expect(shortcut!.preconditions!(context)).toBe(false);+ context.setContextValue(EDITOR_ACTIVATED, true);+ context.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, true);+ expect(shortcut!.preconditions!(context)).toBe(false);+ context.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, false);+ }+ injector.dispose();+ });it.each([['Shift+Enter', EditorCursorShiftEnterShortcut, KeyCode.ENTER],['Shift+Tab', EditorCursorShiftTabShortcut, KeyCode.TAB],diff --git a/packages/sheets-ui/src/controllers/shortcuts/editor.shortcut.ts b/packages/sheets-ui/src/controllers/shortcuts/editor.shortcut.tsindex d2ecbfc684..629b1323e9 100644--- a/packages/sheets-ui/src/controllers/shortcuts/editor.shortcut.ts+++ b/packages/sheets-ui/src/controllers/shortcuts/editor.shortcut.ts@@ -15,7 +15,14 @@*/import type { IShortcutItem } from '@univerjs/ui';-import { BreakLineCommand, DeleteLeftCommand, DeleteRightCommand } from '@univerjs/docs-ui';+import { Direction } from '@univerjs/core';+import {+ BreakLineCommand,+ DeleteLeftCommand,+ DeleteRightCommand,+ MoveCursorOperation,+ MoveSelectionOperation,+} from '@univerjs/docs-ui';import { DeviceInputEventType } from '@univerjs/engine-render';import { KeyCode, MetaKeys } from '@univerjs/ui';import { RepeatLastActionCommand } from '../../commands/commands/repeat-last-action.command';@@ -70,6 +77,23 @@ export function generateArrowSelectionShortCutItem() {});}+ // Sheet editors own focus, so Doc-only line navigation shortcuts do not apply here.+ for (const [binding, macArrow, direction] of [+ [KeyCode.HOME, KeyCode.ARROW_LEFT, Direction.LEFT],+ [KeyCode.END, KeyCode.ARROW_RIGHT, Direction.RIGHT],+ ]) {+ for (const extend of [false, true]) {+ const shift = extend ? MetaKeys.SHIFT : 0;+ shortcutList.push({+ id: extend ? MoveSelectionOperation.id : MoveCursorOperation.id,+ binding: binding | shift,+ mac: macArrow | MetaKeys.CTRL_COMMAND | shift,+ preconditions: whenEditorDidNotInputFormulaActivated,+ staticParameters: { direction, granularity: 'line' },+ });+ }+ }+return shortcutList;}diff --git a/packages/sheets-ui/src/mobile-plugin.ts b/packages/sheets-ui/src/mobile-plugin.tsindex 5b1d33ef7c..3ddd3ed593 100644--- a/packages/sheets-ui/src/mobile-plugin.ts+++ b/packages/sheets-ui/src/mobile-plugin.ts@@ -238,6 +238,7 @@ export class UniverSheetsMobileUIPlugin extends Plugin {touchDependencies(this._injector, [[SheetPermissionPanelModel],+ [SheetPermissionInterceptorClipboardController],[SheetClipboardController],[SheetClipboardMobileUIController],[FormulaEditorController],@@ -254,7 +255,6 @@ export class UniverSheetsMobileUIPlugin extends Plugin {override onSteady(): void {touchDependencies(this._injector, [[FormatPainterController],- [SheetPermissionInterceptorClipboardController],]);}diff --git a/packages/sheets-ui/src/plugin.ts b/packages/sheets-ui/src/plugin.tsindex 78a9a9f5e9..b4b03e8ee7 100644--- a/packages/sheets-ui/src/plugin.ts+++ b/packages/sheets-ui/src/plugin.ts@@ -240,6 +240,7 @@ export class UniverSheetsUIPlugin extends Plugin {touchDependencies(this._injector, [[SheetPermissionPanelModel],+ [SheetPermissionInterceptorClipboardController],[SheetClipboardController],[SheetClipboardUIController],[FormulaEditorController],@@ -258,7 +259,6 @@ export class UniverSheetsUIPlugin extends Plugin {touchDependencies(this._injector, [[FormatPainterController],[AutoFillUIController],- [SheetPermissionInterceptorClipboardController],]);}diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-form-excel.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-form-excel.spec.tsindex 31152ca1df..d69d29b669 100644--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-form-excel.spec.ts+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-form-excel.spec.ts@@ -18,6 +18,7 @@ import type { ICellData, Injector, IStyleData, Nullable, Univer, Workbook } fromimport {CellValueType,DEFAULT_TEXT_FORMAT_EXCEL,+ HorizontalAlign,ICommandService,IUniverInstanceService,LocaleType,@@ -202,14 +203,15 @@ describe('Test clipboard', () => {const cellStyle = getStyles(2, 3, 2, 3)?.[0]?.[0];expect(cellStyle?.vt).toBe(2);expect(cellStyle?.bg).toStrictEqual({ rgb: 'rgb(15,158,213)' });- const richTextStyle = getValues(2, 3, 2, 3)?.[0]?.[0]?.p;+ const richTextCell = getValues(2, 3, 2, 3)?.[0]?.[0];+ const layout = worksheet.getCellDocumentModel(richTextCell, cellStyle, { isDeepClone: true });+ expect(layout?.documentModel?.getBody()?.paragraphs?.[0]?.paragraphStyle?.horizontalAlign)+ .toBe(HorizontalAlign.UNSPECIFIED);+ const richTextStyle = richTextCell?.p;expect(richTextStyle?.body?.dataStream).toBe('Univer\r\n');expect(richTextStyle?.body?.paragraphs).toStrictEqual([{paragraphId: expect.stringMatching(/^para_/),- paragraphStyle: {- horizontalAlign: 0,- },startIndex: 6,},]);diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-from-google.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-from-google.spec.tsindex cda9fad3dd..65bba75ca4 100644--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-from-google.spec.ts+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-paste-from-google.spec.ts@@ -15,7 +15,14 @@*/import type { ICellData, Injector, IStyleData, Nullable, Univer, Workbook } from '@univerjs/core';-import { ICommandService, IUniverInstanceService, LocaleType, RANGE_TYPE, UniverInstanceType } from '@univerjs/core';+import {+ HorizontalAlign,+ ICommandService,+ IUniverInstanceService,+ LocaleType,+ RANGE_TYPE,+ UniverInstanceType,+} from '@univerjs/core';import {AddWorksheetMergeMutation,MoveRangeMutation,@@ -165,14 +172,15 @@ describe('Test clipboard', () => {const cellStyle = getStyles(2, 3, 2, 3)?.[0]?.[0];expect(cellStyle?.vt).toBe(3);expect(cellStyle?.bg).toStrictEqual({ rgb: 'rgb(255,0,0)' });- const richTextStyle = getValues(2, 3, 2, 3)?.[0]?.[0]?.p;+ const richTextCell = getValues(2, 3, 2, 3)?.[0]?.[0];+ const layout = worksheet.getCellDocumentModel(richTextCell, cellStyle, { isDeepClone: true });+ expect(layout?.documentModel?.getBody()?.paragraphs?.[0]?.paragraphStyle?.horizontalAlign)+ .toBe(HorizontalAlign.UNSPECIFIED);+ const richTextStyle = richTextCell?.p;expect(richTextStyle?.body?.dataStream).toBe('univer\r\n');expect(richTextStyle?.body?.paragraphs).toStrictEqual([{paragraphId: expect.stringMatching(/^para_/),- paragraphStyle: {- horizontalAlign: 0,- },startIndex: 6,},]);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 372a69e9e4..a07237396b 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@@ -558,7 +558,7 @@ export class testPlatformService {}// eslint-disable-next-line max-lines-per-function-export function clipboardTestBed(workbookData?: IWorkbookData, dependencies?: Dependency[]) {+export function clipboardTestBed(workbookData?: IWorkbookData, dependencies?: Dependency[], clipboardBoundary?: IClipboardInterfaceService) {const univer = new Univer();const injector = univer.__getInjector();const get = injector.get.bind(injector);@@ -584,7 +584,9 @@ export function clipboardTestBed(workbookData?: IWorkbookData, dependencies?: Deinjector.add([WorksheetProtectionRuleModel]);injector.add([RangeProtectionRuleModel]);injector.add([SheetPermissionCheckController]);- injector.add([IClipboardInterfaceService, { useClass: BrowserClipboardService, lazy: true }]);+ injector.add(clipboardBoundary+ ? [IClipboardInterfaceService, { useValue: clipboardBoundary }]+ : [IClipboardInterfaceService, { useClass: BrowserClipboardService, lazy: true }]);injector.add([ISheetClipboardService, { useClass: SheetClipboardService }]);injector.add([IMessageService, { useClass: DesktopMessageService, lazy: true }]);injector.add([diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard.service.spec.tsindex f1e208d037..4c5e715477 100644--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts@@ -16,7 +16,20 @@import type { ICellData, Injector, IRange, IStyleData, Nullable, Univer, Workbook } from '@univerjs/core';import type { IClipboardItem } from './mock-clipboard';-import { ICommandService, IUniverInstanceService, RANGE_TYPE, Rectangle, RedoCommand, UndoCommand, UniverInstanceType } from '@univerjs/core';+import {+ CustomCommandExecutionError,+ ICommandService,+ IPermissionService,+ IUndoRedoService,+ IUniverInstanceService,+ ObjectMatrix,+ RANGE_TYPE,+ Rectangle,+ RedoCommand,+ Tools,+ UndoCommand,+ UniverInstanceType,+} from '@univerjs/core';import {AddWorksheetMergeMutation,discreteRangeToRange,@@ -31,8 +44,10 @@ import {SetWorksheetRowAutoHeightMutation,SetWorksheetRowHeightMutation,SheetsSelectionsService,+ WorkbookEditablePermission,} from '@univerjs/sheets';import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { SheetPermissionInterceptorClipboardController } from '../../../controllers/permission/sheet-permission-interceptor-clipboard.controller';import { ISheetClipboardService, PREDEFINED_HOOK_NAME_PASTE } from '../clipboard.service';import { COPY_TYPE } from '../type';import { clipboardTestBed } from './clipboard-test-bed';@@ -77,7 +92,11 @@ describe('Test clipboard', () => {) => Array<Array<Nullable<IStyleData>>> | undefined;beforeEach(async () => {- const testBed = clipboardTestBed(undefined, [[MergeCellController], [RefRangeService]]);+ const testBed = clipboardTestBed(undefined, [+ [SheetPermissionInterceptorClipboardController],+ [MergeCellController],+ [RefRangeService],+ ]);univer = testBed.univer;get = testBed.get;testBed.sheet.addWorksheet('sheet2', 1, {@@ -156,6 +175,91 @@ describe('Test clipboard', () => {univer?.dispose();});+ it('keeps the original selection while clipboard data is read asynchronously', async () => {+ const clipboardService = get(ISheetClipboardService);+ const selections = get(SheetsSelectionsService);+ const selectColumn = (column: number) => selections.setSelections('test', 'sheet1', [{+ range: { startRow: 0, endRow: 0, startColumn: column, endColumn: column },+ primary: null,+ style: null,+ }]);+ selectColumn(0);+ const originalSource = getValues(0, 0, 0, 0);+ const originalPeer = getValues(0, 1, 0, 1);+ let releaseRead = () => {};+ const readGate = new Promise<void>((resolve) => {+ releaseRead = resolve;+ });+ const item: IClipboardItem = {+ presentationStyle: 'unspecified',+ types: ['text/plain'],+ getType: async () => {+ await readGate;+ return new Blob(['DEFERRED_PASTE'], { type: 'text/plain' });+ },+ };+ const pendingPaste = clipboardService.paste(item);+ selectColumn(1);+ releaseRead();+ expect(await pendingPaste).toBe(true);+ expect(getValues(0, 0, 0, 0)?.[0][0]?.v).toBe('DEFERRED_PASTE');+ expect(getValues(0, 1, 0, 1)).toEqual(originalPeer);+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);+ expect(getValues(0, 0, 0, 0)).toEqual(originalSource);+ expect(getValues(0, 1, 0, 1)).toEqual(originalPeer);+ });++ it.each(['disposed', 'read-only'] as const)('does not redirect a delayed paste when its source becomes %s', async (state) => {+ const clipboardService = get(ISheetClipboardService);+ get(SheetPermissionInterceptorClipboardController);+ const instances = get(IUniverInstanceService);+ const source = instances.getUnit<Workbook>('test', UniverInstanceType.UNIVER_SHEET)!;+ const snapshot = Tools.deepClone(source.getSnapshot());+ const peer = instances.createUnit(UniverInstanceType.UNIVER_SHEET, { ...snapshot, id: 'paste-peer' }, { makeCurrent: false });+ const peerBefore = Tools.deepClone(peer.getSnapshot());+ const selections = get(SheetsSelectionsService);+ const selection = [{+ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },+ primary: null,+ style: null,+ }];+ selections.setSelections('test', 'sheet1', selection);+ let releaseRead = () => {};+ const readGate = new Promise<void>((resolve) => {+ releaseRead = resolve;+ });+ const pendingPaste = clipboardService.paste({+ presentationStyle: 'unspecified',+ types: ['text/plain'],+ getType: async () => {+ await readGate;+ return new Blob(['MUST_NOT_WRITE'], { type: 'text/plain' });+ },+ });+ if (state === 'disposed') {+ instances.disposeUnit('test');+ } else {+ const permissions = get(IPermissionService);+ const point = new WorkbookEditablePermission('test');+ if (!permissions.getPermissionPoint(point.id)) {+ permissions.addPermissionPoint(point);+ }+ permissions.updatePermissionPoint(point.id, false);+ }+ instances.setCurrentUnitForType('paste-peer');+ selections.setSelections('paste-peer', 'sheet1', selection);+ releaseRead();+ if (state === 'read-only') {+ await expect(pendingPaste).rejects.toThrow(CustomCommandExecutionError);+ } else {+ expect(await pendingPaste).toBe(false);+ }+ expect(peer.getSnapshot()).toEqual(peerBefore);+ if (state === 'read-only') {+ expect(source.getSnapshot()).toEqual(snapshot);+ }+ });+describe('Test paste, the original data is a merged cell of 1 row and 2 columns, the current selection consists only of ordinary cells', () => {it('The current selection is a single cell in 1 row and 1 column', async () => {const selectionManager = get(SheetsSelectionsService);@@ -749,13 +853,112 @@ describe('Test clipboard', () => {});describe('Test cut command in single selection', () => {+ it('rejects cross-workbook cuts before running resource hooks and retains the cut for a valid retry', async () => {+ const instances = get(IUniverInstanceService);+ const source = instances.getUnit<Workbook>('test', UniverInstanceType.UNIVER_SHEET)!;+ const sourceBefore = Tools.deepClone(source.getSnapshot());+ const peer = instances.createUnit(UniverInstanceType.UNIVER_SHEET, {+ ...Tools.deepClone(sourceBefore),+ id: 'cut-peer',+ }, { makeCurrent: false });+ const peerBefore = Tools.deepClone(peer.getSnapshot());+ const history = get(IUndoRedoService);+ const peerHistory = history.getUndoRedoStatus('cut-peer');+ const sourceHistory = history.getUndoRedoStatus('test');+ const copyId = 'cross-workbook-cut';+ const matrix = new ObjectMatrix<ICellData>();+ matrix.setValue(0, 0, { v: 'A25' });+ sheetClipboardService.copyContentCache().set(copyId, {+ unitId: 'test',+ subUnitId: 'sheet1',+ range: { rows: [24], cols: [0] },+ matrix,+ copyType: COPY_TYPE.CUT,+ });+ let beforePasteCalls = 0;+ const hook = sheetClipboardService.addClipboardHook({+ id: 'cross-workbook-cut-resource-boundary',+ onBeforePaste: () => {+ beforePasteCalls += 1;+ return true;+ },+ });+ const range = { startRow: 24, endRow: 24, startColumn: 1, endColumn: 1 };+ expect(await sheetClipboardService.pasteByCopyId(copyId, undefined, {+ unitId: 'cut-peer',+ subUnitId: 'sheet1',+ range,+ })).toBe(false);+ expect(beforePasteCalls).toBe(0);+ expect(source.getSnapshot()).toEqual(sourceBefore);+ expect(peer.getSnapshot()).toEqual(peerBefore);+ expect(history.getUndoRedoStatus('test')).toEqual(sourceHistory);+ expect(history.getUndoRedoStatus('cut-peer')).toEqual(peerHistory);+ expect(sheetClipboardService.copyContentCache().get(copyId)?.matrix).toBe(matrix);+ hook.dispose();+ instances.setCurrentUnitForType('test');+ expect(await sheetClipboardService.pasteByCopyId(copyId, undefined, {+ unitId: 'test',+ subUnitId: 'sheet1',+ range,+ })).toBe(true);+ expect(getValues(24, 0, 24, 1)?.[0].map((cell) => cell?.v ?? null)).toEqual([null, 'A25']);+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);+ expect(getValues(24, 0, 24, 1)?.[0].map((cell) => cell?.v ?? null)).toEqual(['A25', 'B25']);+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);+ expect(getValues(24, 0, 24, 1)?.[0].map((cell) => cell?.v ?? null)).toEqual([null, 'A25']);+ expect(peer.getSnapshot()).toEqual(peerBefore);+ });++ it.each([COPY_TYPE.COPY, COPY_TYPE.CUT])('delegates cross-workbook focused-object %s to its hook without moving cells', async (copyType) => {+ const instances = get(IUniverInstanceService);+ const source = instances.getUnit<Workbook>('test', UniverInstanceType.UNIVER_SHEET)!;+ const sourceBefore = Tools.deepClone(source.getSnapshot());+ const peer = instances.createUnit(UniverInstanceType.UNIVER_SHEET, {+ ...Tools.deepClone(sourceBefore),+ id: 'object-peer',+ }, { makeCurrent: false });+ const peerBefore = Tools.deepClone(peer.getSnapshot());+ const copyId = 'focused-object';+ sheetClipboardService.copyContentCache().set(copyId, {+ unitId: 'test',+ subUnitId: 'sheet1',+ range: { rows: [24], cols: [0] },+ matrix: new ObjectMatrix({ 0: { 0: { v: '' } } }),+ copyType,+ skipCellCopy: true,+ });+ const handled: Array<{ source: string | undefined; target: string; copyType: COPY_TYPE | undefined }> = [];+ const hook = sheetClipboardService.addClipboardHook({+ id: 'focused-object-owner',+ onBeforeCopyFocusedObject: () => true,+ onPasteCells: (from, to, _data, payload) => {+ handled.push({ source: from?.unitId, target: to.unitId, copyType: payload.copyType });+ return { redos: [], undos: [] };+ },+ });+ expect(await sheetClipboardService.pasteByCopyId(copyId, undefined, {+ unitId: 'object-peer',+ subUnitId: 'sheet1',+ range: { startRow: 24, endRow: 24, startColumn: 1, endColumn: 1 },+ })).toBe(true);+ expect(handled).toEqual([{ source: 'test', target: 'object-peer', copyType }]);+ expect(source.getSnapshot()).toEqual(sourceBefore);+ expect(peer.getSnapshot()).toEqual(peerBefore);+ hook.dispose();+ });+it('cut value from A25 to B25', async () => {const unitId = 'test';const subUnitId = 'sheet1';const fromRange = { rows: [24], cols: [0] };const toRange = { startRow: 24, startColumn: 1, endRow: 24, endColumn: 1 };const copyContentCache = sheetClipboardService.copyContentCache();- const { matrixFragment, copyId } = (sheetClipboardService as any)._generateCopyContent(unitId, subUnitId, discreteRangeToRange(fromRange), []);+ const { matrixFragment, copyId } = sheetClipboardService.generateCopyContent(+ unitId,+ subUnitId,+ discreteRangeToRange(fromRange)+ )!;// cache the copy content for internal pastecopyContentCache.set(copyId, {@@ -776,7 +979,7 @@ describe('Test clipboard', () => {},]);- (sheetClipboardService as any)._pasteInternal(copyId, PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE);+ expect(await sheetClipboardService.pasteByCopyId(copyId, PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE)).toBe(true);expect(getValues(24, 0, 24, 0)![0][0]).toBe(null);expect(getValues(24, 1, 24, 1)![0][0]!.v).toBe('A25');diff --git a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts b/packages/sheets-ui/src/services/clipboard/clipboard.service.tsindex d07f261ed3..90182a7c34 100644--- a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts+++ b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts@@ -29,6 +29,7 @@ import type {ISetRangeValuesMutationParams,ISetSelectionsOperationParams,ISetWorksheetRowAutoHeightMutationParams,+ ISheetRangeLocation,} from '@univerjs/sheets';import type { Observable } from 'rxjs';import type { LocaleKey } from '../../locale/types';@@ -68,6 +69,7 @@ import {sequenceExecute,ThemeService,toDisposable,+ Tools,UniverInstanceType,} from '@univerjs/core';import { IRenderManagerService, withCurrentTypeOfRenderer } from '@univerjs/engine-render';@@ -191,9 +193,10 @@ export interface ISheetClipboardService {copy(options?: ICopyOptions): Promise<boolean>;cut(): Promise<boolean>;- paste(item: ClipboardItem, pasteType?: string): Promise<boolean>; // get content from a ClipboardItem and paste it.- pasteByCopyId(copyId: string, pasteType?: string): Promise<boolean>; // paste content by internal copyId.- legacyPaste(html?: string, text?: string, files?: File[], formulaClipboardPayload?: string): Promise<boolean>; // paste a HTML string or plain text directly.+ capturePasteTarget(): ISheetRangeLocation | null;+ paste(item: ClipboardItem, pasteType?: string, target?: ISheetRangeLocation | null): Promise<boolean>;+ pasteByCopyId(copyId: string, pasteType?: string, target?: ISheetRangeLocation | null): Promise<boolean>;+ legacyPaste(html?: string, text?: string, files?: File[], formulaClipboardPayload?: string, target?: ISheetRangeLocation | null): Promise<boolean>;rePasteWithPasteType(type: IPasteHookKeyType): boolean;disposePasteOptionsCache(): void;@@ -375,7 +378,24 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard});}- async paste(item: ClipboardItem, pasteType = PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE): Promise<boolean> {+ capturePasteTarget(): ISheetRangeLocation | null {+ const workbook = this._univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);+ const worksheet = workbook?.getActiveSheet();+ const selection = this._selectionManagerService.getCurrentLastSelection();+ if (!workbook || !worksheet || !selection) {+ return null;+ }+ return {+ unitId: workbook.getUnitId(),+ subUnitId: worksheet.getSheetId(),+ range: Tools.deepClone(selection.range),+ };+ }++ async paste(item: ClipboardItem, pasteType = PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE, target = this.capturePasteTarget()): Promise<boolean> {+ if (!target) {+ return false;+ }const types = item.types;const text =types.indexOf(PLAIN_TEXT_CLIPBOARD_MIME_TYPE) !== -1@@ -407,7 +427,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard// After the pop-up window prompts, can paste the contents of the clipboard as much as possible.}- return this._pasteHTML(html, pasteType, formulaClipboardPayload);+ return this._pasteHTML(html, pasteType, formulaClipboardPayload, target);}// clipboard item from excel may contain image, so we need to check if the clipboard item is from excel@@ -423,12 +443,12 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard{ type: imageMimeType });- return this._pasteFiles([file], pasteType);+ return this._pasteFiles([file], pasteType, target);}}if (text) {- return this._pastePlainText(text, pasteType);+ return this._pastePlainText(text, pasteType, target);}this._logService.error('[SheetClipboardService]', 'No valid data on clipboard');@@ -436,26 +456,32 @@ export class SheetClipboardService extends Disposable implements ISheetClipboardreturn false;}- async pasteByCopyId(copyId: string, pasteType = PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE): Promise<boolean> {- return this._pasteInternal(copyId, pasteType);+ async pasteByCopyId(copyId: string, pasteType = PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE, target = this.capturePasteTarget()): Promise<boolean> {+ if (!target) {+ return false;+ }+ return this._pasteInternal(copyId, pasteType, target);}- async legacyPaste(html?: string, text?: string, files?: File[], formulaClipboardPayload?: string): Promise<boolean> {+ async legacyPaste(html?: string, text?: string, files?: File[], formulaClipboardPayload?: string, target = this.capturePasteTarget()): Promise<boolean> {+ if (!target) {+ return false;+ }const isFromExcel = htmlIsFromExcel(html ?? '');if (files && !isFromExcel) {- return this._pasteFiles(files, PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE);+ return this._pasteFiles(files, PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE, target);} else if (html) {- return this._pasteHTML(html, PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE, formulaClipboardPayload);+ return this._pasteHTML(html, PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE, formulaClipboardPayload, target);} else if (text) {// Converts text with tabs and newlines into an HTML tableif (/[\n\t]/.test(text)) {- return this._pasteHTML(convertTextToTable(text), PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE);+ return this._pasteHTML(convertTextToTable(text), PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE, undefined, target);} else {- return this._pastePlainText(text, PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE);+ return this._pastePlainText(text, PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE, target);}} else {- return this._pasteUnrecognized();+ return this._pasteUnrecognized(target);}}@@ -685,8 +711,8 @@ export class SheetClipboardService extends Disposable implements ISheetClipboardunitId: string;subUnitId: string;range: IDiscreteRange;- }) => undefined | ({ undos: IMutationInfo[]; redos: IMutationInfo[] })): Promise<boolean> {- const target = this._getPastingTarget();+ }) => undefined | ({ undos: IMutationInfo[]; redos: IMutationInfo[] }), location: ISheetRangeLocation): Promise<boolean> {+ const target = this._getPastingTarget(location);if (!target.subUnitId || !target.selection) {return false;}@@ -728,7 +754,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboardif (result) {// add to undo redo servicesthis._undoRedoService.pushUndoRedo({- unitID: this._univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getUnitId(),+ unitID: unitId,undoMutations: undoMutationsInfo,redoMutations: redoMutationsInfo,});@@ -737,33 +763,33 @@ export class SheetClipboardService extends Disposable implements ISheetClipboardreturn result;}- private async _pasteFiles(files: File[], pasteType: IPasteHookValueType): Promise<boolean> {+ private async _pasteFiles(files: File[], pasteType: IPasteHookValueType, target: ISheetRangeLocation): Promise<boolean> {return this._executePaste((h, payload) => {return h.onPasteFiles?.(payload, files, { pasteType });- });+ }, target);}- private async _pastePlainText(text: string, pasteType: IPasteHookValueType): Promise<boolean> {+ private async _pastePlainText(text: string, pasteType: IPasteHookValueType, target: ISheetRangeLocation): Promise<boolean> {return this._executePaste((h, payload) => {return h.onPastePlainText?.(payload, text, { pasteType });- });+ }, target);}- private _pasteUnrecognized() {+ private _pasteUnrecognized(target: ISheetRangeLocation) {return this._executePaste((h, payload) => {return h.onPasteUnrecognized?.(payload);- });+ }, target);}- private async _pasteHTML(html: string, pasteType: IPasteHookValueType, formulaClipboardPayload?: string): Promise<boolean> {+ private async _pasteHTML(html: string, pasteType: IPasteHookValueType, formulaClipboardPayload: string | undefined, target: ISheetRangeLocation): Promise<boolean> {const copyId = extractId(html);if (copyId && this._copyContentCache.get(copyId)) {- return this._pasteInternal(copyId, pasteType);+ return this._pasteInternal(copyId, pasteType, target);}- return this._pasteExternal(html, pasteType, formulaClipboardPayload);+ return this._pasteExternal(html, pasteType, formulaClipboardPayload, target);}- private async _pasteExternal(html: string, pasteType: IPasteHookValueType, formulaClipboardPayload?: string): Promise<boolean> {+ private async _pasteExternal(html: string, pasteType: IPasteHookValueType, formulaClipboardPayload: string | undefined, target: ISheetRangeLocation): Promise<boolean> {// this._logService.log('[SheetClipboardService]', 'pasting external content', html);// steps of pasting:@@ -779,7 +805,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard? this._applyFormulaClipboardPayload(cellMatrix, formulaClipboardPayload): undefined;- return this._pasteExternalData({ rowProperties, colProperties, cellMatrix }, pasteType, sourceRange);+ return this._pasteExternalData({ rowProperties, colProperties, cellMatrix }, pasteType, sourceRange, target);}private _applyFormulaClipboardPayload(@@ -832,7 +858,8 @@ export class SheetClipboardService extends Disposable implements ISheetClipboardprivate _pasteExternalData(data: IUniverSheetCopyDataModel,pasteType: IPasteHookValueType,- sourceRange?: IDiscreteRange+ sourceRange: IDiscreteRange | undefined,+ target: ISheetRangeLocation): boolean {const { rowProperties, colProperties, cellMatrix } = data;if (!cellMatrix) {@@ -847,7 +874,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard// 3. call hooks with cell position and properties and get mutations (both do mutations and undo mutations)// we also handle 'copy value only' or 'copy style only' as this step- const pasteTarget = this._getPastedRange(cellMatrix);+ const pasteTarget = this._getPastedRange(cellMatrix, target);// pastedRange.endColumn = pastedRange.startColumn + colCount;// pastedRange.endRow = pastedRange.startRow + rowCount;@@ -900,15 +927,18 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard}// eslint-disable-next-line max-lines-per-function- private async _pasteInternal(copyId: string, pasteType: IPasteHookValueType): Promise<boolean> {- // const target = this._getPastingTarget();- // const { selection, unitId, subUnitId } = target;+ private async _pasteInternal(copyId: string, pasteType: IPasteHookValueType, target: ISheetRangeLocation): Promise<boolean> {const cachedData = this._copyContentCache.get(copyId);const { range, matrix: cachedMatrix, unitId: copyUnitId, subUnitId: copySubUnitId, skipCellCopy } = cachedData || {};if (!cachedMatrix || !cachedData || !range || !copyUnitId || !copySubUnitId) {return false;}+ // MoveRange only supports one workbook. Reject before resource hooks can apply a partial cut.+ if (!skipCellCopy && cachedData.copyType === COPY_TYPE.CUT && copyUnitId !== target.unitId) {+ return false;+ }+const { mapFunc } = virtualizeDiscreteRanges([range]);const worksheet = this._univerInstanceService.getUnit<Workbook>(copyUnitId, UniverInstanceType.UNIVER_SHEET)?.getSheetBySheetId(copySubUnitId);@@ -940,7 +970,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard}}});- const pasteTarget = this._getPastedRange(cellMatrix);+ const pasteTarget = this._getPastedRange(cellMatrix, target);if (!pasteTarget) return false;const pasteToWorksheet = this._univerInstanceService@@ -1005,9 +1035,11 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard});- if (cachedData.copyType === COPY_TYPE.CUT) {+ if (pasteRes && cachedData.copyType === COPY_TYPE.CUT) {this._copyContentCache.set(copyId, { ...cachedData, matrix: null });- this._copyMarkId && this._markSelectionService.removeShape(this._copyMarkId);+ if (this._copyMarkId) {+ this._markSelectionService.removeShape(this._copyMarkId);+ }this._copyMarkId = null;}@@ -1298,7 +1330,16 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard};}- private _getPastingTarget() {+ private _getPastingTarget(location?: ISheetRangeLocation) {+ if (location) {+ const worksheet = this._univerInstanceService.getUnit<Workbook>(location.unitId, UniverInstanceType.UNIVER_SHEET)+ ?.getSheetBySheetId(location.subUnitId);+ return {+ unitId: location.unitId,+ subUnitId: worksheet?.getSheetId(),+ selection: worksheet ? { range: location.range } : null,+ };+ }const workbook = this._univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;const worksheet = workbook.getActiveSheet();const selection = this._selectionManagerService.getCurrentLastSelection();@@ -1486,8 +1527,8 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard};}- private _getPastedRange(cellMatrix: ObjectMatrix<ICellDataWithSpanAndDisplay>) {- const target = this._getPastingTarget();+ private _getPastedRange(cellMatrix: ObjectMatrix<ICellDataWithSpanAndDisplay>, location: ISheetRangeLocation) {+ const target = this._getPastingTarget(location);const { selection, unitId, subUnitId } = target;if (!subUnitId || !selection) {return null;diff --git a/packages/sheets-ui/src/services/clipboard/html-to-usm/__tests__/converter.spec.ts b/packages/sheets-ui/src/services/clipboard/html-to-usm/__tests__/converter.spec.tsnew file mode 100644index 0000000000..1a71726f47--- /dev/null+++ b/packages/sheets-ui/src/services/clipboard/html-to-usm/__tests__/converter.spec.ts@@ -0,0 +1,45 @@+/**+ * 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 { describe, expect, it } from 'vitest';+import { HtmlToUSMService } from '../converter';+import { WordPastePlugin } from '../paste-plugins/plugin-word';++HtmlToUSMService.use(WordPastePlugin);++describe('HtmlToUSMService', () => {+ it.each([+ '<p class="MsoNormal"><b>Office回归中文🙂</b></p><p class="MsoNormal"><b>第二行 0</b></p>',+ '<span>Office回归中文🙂</span><br><span>第二行 0</span>',+ ])('keeps document terminators out of plain paragraph cell values: %s', (html) => {+ const converter = new HtmlToUSMService({ getCurrentSkeleton: () => null });+ const { cellMatrix } = converter.convert(html);++ expect(cellMatrix.getValue(0, 0)?.v).toBe('Office回归中文🙂');+ expect(cellMatrix.getValue(1, 0)?.v).toBe('第二行 0');+ expect(cellMatrix.getValue(2, 0)).toBeUndefined();+ });++ it('preserves intentional spaces and empty paragraphs when splitting cells', () => {+ const converter = new HtmlToUSMService({ getCurrentSkeleton: () => null });+ const { cellMatrix } = converter.convert('<p class="MsoNormal"> left </p><p class="MsoNormal"></p><p class="MsoNormal">right </p>');++ expect(cellMatrix.getValue(0, 0)?.v).toBe(' left ');+ expect(cellMatrix.getValue(1, 0)?.v).toBe('');+ expect(cellMatrix.getValue(2, 0)?.v).toBe('right ');+ expect(cellMatrix.getValue(3, 0)).toBeUndefined();+ });+});diff --git a/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts b/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.tsindex c7460f0b37..9a580beea6 100644--- a/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts+++ b/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts@@ -210,7 +210,8 @@ export class HtmlToUSMService {});const isEmptyMatrix = Object.keys(valueMatrix.getMatrix()).length === 0;valueMatrix.setValue(isEmptyMatrix ? 0 : valueMatrix.getLength(), 0, {- v: cellDataStream,+ // The document needs its terminal paragraph/section markers; the plain cell value does not.+ v: cellDataStream.slice(0, -2),p,});rowProperties.push({}); // TODO@yuhongzdiff --git a/packages/sheets-ui/src/services/format-painter/__tests__/format-painter.service.spec.ts b/packages/sheets-ui/src/services/format-painter/__tests__/format-painter.service.spec.tsindex 2ef609bc1b..f968d2cca2 100644--- a/packages/sheets-ui/src/services/format-painter/__tests__/format-painter.service.spec.ts+++ b/packages/sheets-ui/src/services/format-painter/__tests__/format-painter.service.spec.ts@@ -14,10 +14,10 @@* limitations under the License.*/+import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';import type { ISelectionFormatInfo } from '../format-painter.service';import {CommandService,- CommandType,ConfigService,ContextService,DesktopLogService,@@ -30,18 +30,27 @@ import {IUniverInstanceService,LocalUndoRedoService,ObjectMatrix,+ RedoCommand,ThemeService,+ UndoCommand,UniverInstanceService,Workbook,} from '@univerjs/core';import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';-import { SheetSkeletonService, SheetsSelectionsService } from '@univerjs/sheets';-import { describe, expect, it } from 'vitest';+import { SetRangeValuesMutation, SheetSkeletonService, SheetsSelectionsService } from '@univerjs/sheets';+import { afterEach, describe, expect, it } from 'vitest';import { IMarkSelectionService, MarkSelectionService } from '../../mark-selection/mark-selection.service';import { FormatPainterService, FormatPainterStatus, IFormatPainterService } from '../format-painter.service';+const injectors: Injector[] = [];++afterEach(() => {+ injectors.splice(0).forEach((injector) => injector.dispose());+});+function createService() {const injector = new Injector();+ injectors.push(injector);injector.add([ILogService, { useClass: DesktopLogService }]);injector.add([IConfigService, { useClass: ConfigService }]);injector.add([IContextService, { useClass: ContextService }]);@@ -67,38 +76,41 @@ function createService() {primary: null,}] as never);const commandService = injector.get(ICommandService);- commandService.registerCommand({- id: 'sheet.mutation.apply-style',- type: CommandType.MUTATION,- handler: () => true,- });- commandService.registerCommand({- id: 'sheet.mutation.revert-style',- type: CommandType.MUTATION,- handler: () => true,- });+ commandService.registerCommand(SetRangeValuesMutation);const executed: unknown[] = [];commandService.onCommandExecuted((command) => executed.push({ id: command.id, params: command.params }));return {service: injector.get(IFormatPainterService),markSelectionService: injector.get(IMarkSelectionService),undoRedoService: injector.get(IUndoRedoService),+ commandService,+ workbook,executed,};}describe('FormatPainterService', () => {it('applies collected format mutations and records undo-redo for a format painter action', async () => {- const { service, executed, undoRedoService, markSelectionService } = createService();+ const { service, executed, undoRedoService, markSelectionService, workbook, commandService } = createService();const statusChanges: FormatPainterStatus[] = [];const format: ISelectionFormatInfo = { styles: new ObjectMatrix(), merges: [] };+ const redoParams: ISetRangeValuesMutationParams = {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ cellValue: { 1: { 1: { s: { bl: 1 } } } },+ };+ const undoParams: ISetRangeValuesMutationParams = {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ cellValue: { 1: { 1: { s: null } } },+ };service.addHook({id: 'default',isDefaultHook: true,onStatusChange: (status) => statusChanges.push(status),onApply: () => ({- redos: [{ id: 'sheet.mutation.apply-style', params: { color: 'red' } }],- undos: [{ id: 'sheet.mutation.revert-style', params: { color: 'black' } }],+ redos: [{ id: SetRangeValuesMutation.id, params: redoParams }],+ undos: [{ id: SetRangeValuesMutation.id, params: undoParams }],}),});@@ -110,8 +122,42 @@ describe('FormatPainterService', () => {expect(service.getSelectionFormat()).toBe(format);expect(statusChanges).toEqual([FormatPainterStatus.ONCE]);expect(markSelectionService.getShapeMap().size).toBe(1);- await new Promise((resolve) => setTimeout(resolve, 0));- expect(executed).toEqual([{ id: 'sheet.mutation.apply-style', params: { color: 'red' } }]);+ expect(workbook.getStyles().getStyleByCell(workbook.getActiveSheet()!.getCell(1, 1))).toMatchObject({ bl: 1 });+ await expect.poll(() => executed).toEqual([{ id: SetRangeValuesMutation.id, params: redoParams }]);expect(undoRedoService.pitchTopUndoElement()).toMatchObject({ unitID: 'unit-1' });+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);+ expect(workbook.getActiveSheet()!.getCell(1, 1)?.s).toBeUndefined();+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);+ expect(workbook.getStyles().getStyleByCell(workbook.getActiveSheet()!.getCell(1, 1))).toMatchObject({ bl: 1 });+ });++ it('stops at a rejected mutation without changing a later target or recording undo history', () => {+ const { service, undoRedoService, workbook } = createService();+ const originalCell = workbook.getActiveSheet()!.getCell(1, 1);+ const originalHistory = undoRedoService.pitchTopUndoElement();+ const params: ISetRangeValuesMutationParams = {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ cellValue: { 1: { 1: { s: { bl: 1 } } } },+ };+ service.addHook({+ id: 'stale-target',+ onApply: () => ({+ redos: [+ { id: SetRangeValuesMutation.id, params: { ...params, subUnitId: 'removed-sheet' } },+ { id: SetRangeValuesMutation.id, params },+ ],+ undos: [{ id: SetRangeValuesMutation.id, params }],+ }),+ });++ expect(service.applyFormatPainter('unit-1', 'sheet-1', {+ startRow: 1,+ endRow: 1,+ startColumn: 1,+ endColumn: 1,+ })).toBe(false);+ expect(workbook.getActiveSheet()!.getCell(1, 1)).toEqual(originalCell);+ expect(undoRedoService.pitchTopUndoElement()).toBe(originalHistory);});});diff --git a/packages/sheets-ui/src/services/format-painter/format-painter.service.ts b/packages/sheets-ui/src/services/format-painter/format-painter.service.tsindex 2aa14b2967..1441db17fb 100644--- a/packages/sheets-ui/src/services/format-painter/format-painter.service.ts+++ b/packages/sheets-ui/src/services/format-painter/format-painter.service.ts@@ -24,6 +24,7 @@ import {Inject,IUndoRedoService,ObjectMatrix,+ sequenceExecute,ThemeService,} from '@univerjs/core';import { SetRangeValuesMutation, SheetsSelectionsService } from '@univerjs/sheets';@@ -179,7 +180,7 @@ export class FormatPainterService extends Disposable implements IFormatPainterSeredoMutationsInfo,});- const result = redoMutationsInfo.every((m) => this._commandService.executeCommand(m.id, m.params));+ const { result } = sequenceExecute(redoMutationsInfo, this._commandService);if (result) {// add to undo redo servicesthis._undoRedoService.pushUndoRedo({diff --git a/packages/sheets-ui/src/services/selection/__tests__/base-selection-render.service.spec.ts b/packages/sheets-ui/src/services/selection/__tests__/base-selection-render.service.spec.tsindex 97f1a205f1..78242ba73e 100644--- a/packages/sheets-ui/src/services/selection/__tests__/base-selection-render.service.spec.ts+++ b/packages/sheets-ui/src/services/selection/__tests__/base-selection-render.service.spec.ts@@ -94,18 +94,18 @@ class TestSelectionRenderService extends BaseSelectionRenderService {this._movingHandler(offsetX, offsetY, activeControl, rangeType);}- listenPointerMoveForTest(rangeType = RANGE_TYPE.NORMAL) {+ listenPointerMoveForTest(rangeType = RANGE_TYPE.NORMAL, start = { x: 0, y: 0 }) {const activeControl = this.getActiveSelectionControl()!;this._startRangeWhenPointerDown = activeControl.model as never;- this._startViewportPosX = 0;- this._startViewportPosY = 0;+ this._startViewportPosX = start.x;+ this._startViewportPosY = start.y;this._setupPointerMoveListener(this._scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN),activeControl,rangeType,ScrollTimerType.ALL,- 0,- 0+ start.x,+ start.y);}@@ -448,6 +448,44 @@ describe('BaseSelectionRenderService', () => {expect(movingSelections.length).toBeGreaterThan(0);});+ it.each([false, true])('preserves scrolled frozen-pane selection in reverse=%s', (reverse) => {+ const { service } = createSelectionRenderService();+ const { scene } = service.changeRuntimeForTest({+ freeze: { startRow: 2, startColumn: 2, xSplit: 2, ySplit: 2 },+ });+ const main = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN)!;+ main.left = 200;+ main.top = 40;+ main.scrollY = 200;+ main.viewportScrollY = 200;+ const resetScroll = vi.fn();+ Reflect.set(main, 'scrollToBarPos', resetScroll);+ scene.getActiveViewportByCoord = (point) => {+ if (point.y < 40) {+ return scene.getViewport(point.x < 200 ? SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP : SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP)!;+ }+ return scene.getViewport(point.x < 200 ? SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT : SHEET_VIEWPORT_KEY.VIEW_MAIN)!;+ };+ scene.getScrollXYInfoByViewport = (point, viewport) => {+ const target = viewport ?? scene.getActiveViewportByCoord(point)!;+ return { x: target.viewportScrollX, y: target.viewportScrollY };+ };+ const start = reverse ? { x: 350, y: 65 } : { x: 100, y: 20 };+ const end = reverse ? { x: 100, y: 20 } : { x: 350, y: 65 };+ const row = reverse ? 13 : 1;+ const column = reverse ? 3 : 1;+ service.resetSelectionsByModelData([createSelection({ startRow: row, endRow: row, startColumn: column, endColumn: column })]);+ service.listenPointerMoveForTest(RANGE_TYPE.NORMAL, start);+ (scene.onPointerMove$ as unknown as { emit: (evt: unknown) => void }).emit({+ offsetX: end.x,+ offsetY: end.y,+ buttons: 1,+ });+ expect(resetScroll).not.toHaveBeenCalled();+ expect(service.getActiveRange()).toEqual({ startRow: 1, endRow: 13, startColumn: 1, endColumn: 3 });+ expect(main.viewportScrollY).toBe(200);+ });+it('ends a leaked drag before handling pointer movement with no pressed buttons', () => {const { service } = createSelectionRenderService();const { scene } = service.changeRuntimeForTest();diff --git a/packages/sheets-ui/src/services/selection/__tests__/selection-render.service.spec.ts b/packages/sheets-ui/src/services/selection/__tests__/selection-render.service.spec.tsindex c329684c88..375cf506bd 100644--- a/packages/sheets-ui/src/services/selection/__tests__/selection-render.service.spec.ts+++ b/packages/sheets-ui/src/services/selection/__tests__/selection-render.service.spec.ts@@ -14,14 +14,32 @@* limitations under the License.*/-import type { IRange } from '@univerjs/core';+import type { IRange, IWorkbookData, Workbook } from '@univerjs/core';+import type { IPointerEvent } from '@univerjs/engine-render';import type { ISelectionWithStyle } from '@univerjs/sheets';-import { RANGE_TYPE } from '@univerjs/core';-import { SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';-import { IShortcutService } from '@univerjs/ui';-import { describe, expect, it } from 'vitest';+import { ICommandService, LocaleService, LocaleType, RANGE_TYPE, Univer, UniverInstanceType } from '@univerjs/core';+import {+ CanvasColorService,+ ICanvasColorService,+ IRenderManagerService,+ RenderManagerService,+ SHEET_VIEWPORT_KEY,+ Spreadsheet,+ Viewport,+} from '@univerjs/engine-render';+import { SetSelectionsOperation, SheetInterceptorService, SheetSkeletonService, SheetsSelectionsService } from '@univerjs/sheets';+import {+ IPlatformService,+ IShortcutService,+ IUIRuntimeScopeService,+ PlatformService,+ ShortcutService,+ UIRuntimeScopeService,+} from '@univerjs/ui';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { SHEET_VIEW_KEY } from '../../../common/keys';import { createRenderTestBed } from '../../../controllers/render-controllers/__tests__/render-test-bed';+import { SheetSkeletonManagerService } from '../../sheet-skeleton-manager.service';import { SheetSelectionRenderService } from '../selection-render.service';class TestShortcutService {@@ -238,3 +256,98 @@ describe('SheetSelectionRenderService', () => {univer.dispose();});});++describe('SheetSelectionRenderService additive pointer modifiers with real render providers', () => {+ let univer: Univer;++ beforeEach(() => {+ vi.useFakeTimers();+ // Happy DOM lacks a canvas backend; selection, render, and shortcut services remain real.+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(function (this: HTMLCanvasElement) {+ return { canvas: this, setTransform: vi.fn(), clearRect: vi.fn() } as unknown as CanvasRenderingContext2D;+ });+ univer = new Univer();+ const injector = univer.__getInjector();+ injector.get(LocaleService).setLocale(LocaleType.EN_US);+ injector.add([ICanvasColorService, { useClass: CanvasColorService }]);+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);+ injector.add([SheetSkeletonService]);+ injector.add([SheetInterceptorService]);+ injector.add([SheetsSelectionsService]);+ injector.add([IPlatformService, { useClass: PlatformService }]);+ injector.add([IUIRuntimeScopeService, { useClass: UIRuntimeScopeService }]);+ injector.add([IShortcutService, { useClass: ShortcutService }]);+ injector.get(SheetSkeletonService);+ injector.get(SheetInterceptorService);+ injector.get(ICommandService).registerCommand(SetSelectionsOperation);+ injector.get(IRenderManagerService).registerRenderModule(UniverInstanceType.UNIVER_SHEET, [SheetSkeletonManagerService]);+ });++ afterEach(() => {+ vi.clearAllTimers();+ univer.dispose();+ vi.restoreAllMocks();+ vi.useRealTimers();+ });++ for (const single of [false, true]) {+ for (const modifier of ['none', 'ctrlKey', 'metaKey', 'shiftKey'] as const) {+ it(`preserves the intended pointer range with ${modifier} and single selection ${single}`, () => {+ const injector = univer.__getInjector();+ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, {+ id: 'pointer-modifiers',+ name: 'Pointer modifiers',+ sheetOrder: ['sheet1'],+ sheets: { sheet1: { id: 'sheet1', name: 'Sheet 1', rowCount: 20, columnCount: 10, cellData: {} } },+ });+ const renderManager = injector.get(IRenderManagerService);+ const render = renderManager.createRender(workbook.getUnitId());+ render.engine.resizeBySize(800, 600);+ new Viewport(SHEET_VIEWPORT_KEY.VIEW_MAIN, render.scene, { left: 0, top: 0, right: 0, bottom: 0 });+ const spreadsheet = new Spreadsheet(SHEET_VIEW_KEY.MAIN);+ render.mainComponent = spreadsheet;+ render.components.set(SHEET_VIEW_KEY.MAIN, spreadsheet);+ render.scene.addObject(spreadsheet);+ const skeletonManager = render.with(SheetSkeletonManagerService);+ skeletonManager.setCurrent({ sheetId: 'sheet1' });+ renderManager.registerRenderModule(UniverInstanceType.UNIVER_SHEET, [SheetSelectionRenderService]);+ const service = render.with(SheetSelectionRenderService);+ service.setSingleSelectionEnabled(single);+ const skeleton = skeletonManager.getCurrentSkeleton()!;++ for (const index of [0, 2]) {+ const cell = skeleton.getNoMergeCellWithCoordByIndex(index, index);+ const event = {+ offsetX: (cell.startX + cell.endX) / 2,+ offsetY: (cell.startY + cell.endY) / 2,+ button: 0,+ ...(index === 2 && modifier !== 'none' ? { [modifier]: true } : {}),+ } as IPointerEvent;+ spreadsheet.onPointerDown$.emitEvent(event);+ render.scene.onPointerUp$.emitEvent(event);+ }++ const selections = injector.get(SheetsSelectionsService)+ .getWorkbookSelections(workbook.getUnitId())+ .getCurrentSelections();+ const ranges = selections.map(({ range }) => ({+ startRow: range.startRow,+ startColumn: range.startColumn,+ endRow: range.endRow,+ endColumn: range.endColumn,+ }));+ if (modifier === 'shiftKey') {+ expect(ranges).toEqual([{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }]);+ } else if (!single && modifier !== 'none') {+ expect(ranges).toEqual([+ { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 },+ { startRow: 2, startColumn: 2, endRow: 2, endColumn: 2 },+ ]);+ } else {+ expect(ranges).toEqual([{ startRow: 2, startColumn: 2, endRow: 2, endColumn: 2 }]);+ }+ expect(service.getSelectionControls()).toHaveLength(ranges.length);+ });+ }+ }+});diff --git a/packages/sheets-ui/src/services/selection/base-selection-render.service.ts b/packages/sheets-ui/src/services/selection/base-selection-render.service.tsindex 9346c52b1e..98a42ce823 100644--- a/packages/sheets-ui/src/services/selection/base-selection-render.service.ts+++ b/packages/sheets-ui/src/services/selection/base-selection-render.service.ts@@ -614,7 +614,7 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSeleconst shouldResetX = startXY.x !== endXY.x && isCrossingX && xCrossTime % 2 === 1;const shouldResetY = startXY.y !== endXY.y && isCrossingY && yCrossTime % 2 === 1;- if (shouldResetX || shouldResetY) {+ if (rangeType !== RANGE_TYPE.NORMAL && (shouldResetX || shouldResetY)) {viewportMain.scrollToBarPos({x: shouldResetX ? startXY.x : undefined,y: shouldResetY ? startXY.y : undefined,@@ -694,8 +694,8 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSeleconst targetViewport = this._getViewportByCell(currSelectionRange.endRow, currSelectionRange.endColumn) ?? viewportMain;const scrollXY = scene.getScrollXYInfoByViewport(- Vector2.FromArray([this._startViewportPosX, this._startViewportPosY]),- targetViewport+ Vector2.FromArray([offsetX, offsetY]),+ rangeType === RANGE_TYPE.NORMAL ? undefined : targetViewport);const { scaleX, scaleY } = scene.getAncestorScale();@@ -855,11 +855,12 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSeleprotected _checkClearPreviousControls(evt: IPointerEvent | IMouseEvent): void {const curControls = this.getSelectionControls();- if (curControls.length === 0) return;+ if (curControls.length === 0) {+ return;+ }- // In addition to pressing the ctrl or shift key, we must clear the previous selection.if (- (!evt.ctrlKey && !evt.shiftKey && !this._remainLastEnabled) ||+ (!evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !this._remainLastEnabled) ||(this._singleSelectionEnabled && !evt.shiftKey)) {this._clearAllSelectionControls();diff --git a/packages/sheets-ui/src/services/selection/selection-render.service.ts b/packages/sheets-ui/src/services/selection/selection-render.service.tsindex 8102059871..117b47f5b9 100644--- a/packages/sheets-ui/src/services/selection/selection-render.service.ts+++ b/packages/sheets-ui/src/services/selection/selection-render.service.ts@@ -409,6 +409,7 @@ export class SheetSelectionRenderService extends BaseSelectionRenderService implconst expandByShiftKey = evt.shiftKey && currentCell;const remainLastEnable = this._remainLastEnabled &&!evt.ctrlKey &&+ !evt.metaKey &&!evt.shiftKey &&!this._skipLastEnabled &&!this._singleSelectionEnabled;diff --git a/packages/sheets-ui/src/services/utils/__tests__/defined-name-utils.spec.ts b/packages/sheets-ui/src/services/utils/__tests__/defined-name-utils.spec.tsindex 82a5f02dbf..b37a970572 100644--- a/packages/sheets-ui/src/services/utils/__tests__/defined-name-utils.spec.ts+++ b/packages/sheets-ui/src/services/utils/__tests__/defined-name-utils.spec.ts@@ -14,8 +14,14 @@* limitations under the License.*/-import type { Workbook } from '@univerjs/core';-import type { IDefinedNamesServiceParam } from '@univerjs/engine-formula';+import type { IUniverInstanceService, Workbook } from '@univerjs/core';+import type {+ IDefinedNamesService,+ IDefinedNamesServiceParam,+ IFunctionService,+ ISuperTableService,+ LexerTreeBuilder,+} from '@univerjs/engine-formula';import type { ISelectionWithStyle } from '@univerjs/sheets';import { AbsoluteRefType } from '@univerjs/core';import { validateDefinedName } from '@univerjs/sheets';@@ -23,12 +29,16 @@ import { describe, expect, it, vi } from 'vitest';import { getAbsoluteRefStringFromSelection, resolveDefinedNameBoxAction } from '../defined-name-utils';function createWorkbookMock(sheetNames = ['Sheet1']) {- const sheets = new Map(sheetNames.map((name, index) => [`sheet-${index}`, { getName: () => name }]));+ const sheets = new Map(sheetNames.map((name, index) => [`sheet-${index}`, {+ getName: () => name,+ getRowCount: () => 1000,+ getColumnCount: () => 20,+ }]));return {getSheetOrders: () => Array.from(sheets.keys()),getSheetBySheetId: (sheetId: string) => sheets.get(sheetId),- getActiveSheet: () => ({ getName: () => 'Sheet1' }),+ getActiveSheet: () => sheets.get('sheet-0'),} as unknown as Workbook;}@@ -43,16 +53,16 @@ function createValidationDeps(overrides: {workbook: createWorkbookMock(),definedNamesService: {getValueByName: vi.fn(() => overrides.definedName ?? null),- } as any,+ } as unknown as IDefinedNamesService,superTableService: {hasTable: vi.fn(() => overrides.hasTable ?? false),- } as any,+ } as unknown as ISuperTableService,functionService: {hasExecutor: vi.fn(() => overrides.hasFunction ?? false),- } as any,+ } as unknown as IFunctionService,univerInstanceService: {getUnit: vi.fn(() => ({ getSheets: () => [{ getName: () => 'Sheet1' }] })),- } as any,+ } as unknown as IUniverInstanceService,};}@@ -108,6 +118,7 @@ describe('defined-name.utils', () => {rangeString: 'A1',unitId,formulaOrRefString: existingDefinedName.formulaOrRefString,+ worksheet: createWorkbookMock().getActiveSheet(),univerInstanceService,definedNamesService,superTableService,@@ -134,6 +145,7 @@ describe('defined-name.utils', () => {rangeString: 'A1',unitId,formulaOrRefString: '',+ worksheet: createWorkbookMock().getActiveSheet(),univerInstanceService,definedNamesService,superTableService,@@ -146,6 +158,32 @@ describe('defined-name.utils', () => {});});+ it('should reset when a typed reference is outside the worksheet bounds', () => {+ const {+ unitId,+ univerInstanceService,+ definedNamesService,+ superTableService,+ functionService,+ } = createValidationDeps();++ const action = resolveDefinedNameBoxAction({+ inputValue: 'Z200',+ rangeString: 'A1',+ unitId,+ formulaOrRefString: '',+ worksheet: createWorkbookMock().getActiveSheet(),+ univerInstanceService,+ definedNamesService,+ superTableService,+ functionService,+ });++ expect(action).toEqual({+ type: 'reset',+ });+ });+it('should resolve Enter on a valid new name to create a defined name', () => {const {unitId,@@ -160,6 +198,7 @@ describe('defined-name.utils', () => {rangeString: 'A1',unitId,formulaOrRefString: 'A1',+ worksheet: createWorkbookMock().getActiveSheet(),univerInstanceService,definedNamesService,superTableService,@@ -186,6 +225,7 @@ describe('defined-name.utils', () => {rangeString: 'A1',unitId,formulaOrRefString: '',+ worksheet: createWorkbookMock().getActiveSheet(),univerInstanceService,definedNamesService,superTableService,@@ -211,7 +251,7 @@ describe('defined-name.utils', () => {const absoluteRef = getAbsoluteRefStringFromSelection(createWorkbookMock(),selections,- { convertRefersToAbsolute } as any+ { convertRefersToAbsolute } as unknown as LexerTreeBuilder);expect(absoluteRef).toBe('ABS(Sheet1!A1)');@@ -232,7 +272,7 @@ describe('defined-name.utils', () => {const absoluteRef = getAbsoluteRefStringFromSelection(createWorkbookMock(),selections,- { convertRefersToAbsolute } as any+ { convertRefersToAbsolute } as unknown as LexerTreeBuilder);expect(absoluteRef).toBe('ABS(Sheet1!B2:C4)');diff --git a/packages/sheets-ui/src/services/utils/defined-name-utils.ts b/packages/sheets-ui/src/services/utils/defined-name-utils.tsindex f2336d93ed..48c3ac2dda 100644--- a/packages/sheets-ui/src/services/utils/defined-name-utils.ts+++ b/packages/sheets-ui/src/services/utils/defined-name-utils.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { IUniverInstanceService, Workbook } from '@univerjs/core';+import type { IUniverInstanceService, Workbook, Worksheet } from '@univerjs/core';import type {IDefinedNamesService,IDefinedNamesServiceParam,@@ -23,8 +23,12 @@ import type {LexerTreeBuilder,} from '@univerjs/engine-formula';import type { ISelectionWithStyle } from '@univerjs/sheets';-import { AbsoluteRefType } from '@univerjs/core';-import { isReferenceStringWithEffectiveColumn, serializeRangeWithSheet } from '@univerjs/engine-formula';+import { AbsoluteRefType, isValidRange } from '@univerjs/core';+import {+ deserializeRangeWithSheet,+ isReferenceStringWithEffectiveColumn,+ serializeRangeWithSheet,+} from '@univerjs/engine-formula';import { validateDefinedName } from '@univerjs/sheets';export enum DefinedNameBoxActionType {@@ -40,6 +44,7 @@ interface IResolveDefinedNameBoxActionParams {rangeString: string;unitId: string;formulaOrRefString: string;+ worksheet: Worksheet | null;univerInstanceService: IUniverInstanceService;definedNamesService: IDefinedNamesService;superTableService: ISuperTableService;@@ -54,7 +59,17 @@ type DefinedNameBoxAction =| { type: DefinedNameBoxActionType.Reset };export function resolveDefinedNameBoxAction(params: IResolveDefinedNameBoxActionParams): DefinedNameBoxAction {- const { inputValue, rangeString, unitId, formulaOrRefString, univerInstanceService, definedNamesService, superTableService, functionService } = params;+ const {+ inputValue,+ rangeString,+ unitId,+ formulaOrRefString,+ worksheet,+ univerInstanceService,+ definedNamesService,+ superTableService,+ functionService,+ } = params;if (inputValue === rangeString) {return { type: DefinedNameBoxActionType.Noop };@@ -69,6 +84,11 @@ export function resolveDefinedNameBoxAction(params: IResolveDefinedNameBoxAction}if (isReferenceStringWithEffectiveColumn(inputValue)) {+ const { range } = deserializeRangeWithSheet(inputValue);+ if (!worksheet || !isValidRange(range, worksheet)) {+ return { type: DefinedNameBoxActionType.Reset };+ }+return {type: DefinedNameBoxActionType.FocusSelection,refString: inputValue,diff --git a/packages/sheets-ui/src/views/defined-name/DefinedName.tsx b/packages/sheets-ui/src/views/defined-name/DefinedName.tsxindex 04f7d56c1b..6a28821762 100644--- a/packages/sheets-ui/src/views/defined-name/DefinedName.tsx+++ b/packages/sheets-ui/src/views/defined-name/DefinedName.tsx@@ -181,6 +181,7 @@ export function DefinedName({ disable }: { disable: boolean }) {rangeString,unitId,formulaOrRefString,+ worksheet: workbook.getActiveSheet(),univerInstanceService,definedNamesService,superTableService,diff --git a/packages/sheets-ui/src/views/editor-container/EditorContainer.tsx b/packages/sheets-ui/src/views/editor-container/EditorContainer.tsxindex 993af9a178..b5915cefcb 100644--- a/packages/sheets-ui/src/views/editor-container/EditorContainer.tsx+++ b/packages/sheets-ui/src/views/editor-container/EditorContainer.tsx@@ -36,6 +36,7 @@ import { DeviceInputEventType, IRenderManagerService } from '@univerjs/engine-reimport {ComponentManager,DISABLE_AUTO_FOCUS_KEY,+ getEmbedBoundaryOwner,MetaKeys,useDependency,useEvent,@@ -145,7 +146,7 @@ function isEmbedRuntimeInteractiveElement(element: HTMLElement): boolean {role === 'floating-menu';}-function shouldPreserveEmbedPopupFocus(embedId: string | undefined, ownerDocument: Document): boolean {+export function shouldPreserveEmbedControlFocus(embedId: string | undefined, ownerDocument: Document): boolean {if (!embedId) {return false;}@@ -155,18 +156,20 @@ function shouldPreserveEmbedPopupFocus(embedId: string | undefined, ownerDocumenreturn false;}- const ownerElement = activeElement.closest(`[${SHEET_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE}="${embedId}"]`);- if (!ownerElement) {+ if (getEmbedBoundaryOwner(activeElement) !== embedId) {return false;}const role = activeElement.getAttribute(SHEET_EMBED_RUNTIME_FOCUS_ROLE_ATTRIBUTE) ??activeElement.closest(`[${SHEET_EMBED_RUNTIME_FOCUS_ROLE_ATTRIBUTE}]`)?.getAttribute(SHEET_EMBED_RUNTIME_FOCUS_ROLE_ATTRIBUTE);- return role === 'child-popup' || role === 'floating-menu';+ // The cell input still needs selection synchronization; other owned editors must keep their focus.+ const isAnotherEditor = role === 'child-editor' && activeElement.id !== `__editor_${DOCS_NORMAL_EDITOR_UNIT_ID_KEY}`;+ // Native controls such as the Name Box inherit the runtime role, not a popup role.+ return activeElement.matches('input, textarea, select') || isAnotherEditor || role === 'child-popup' || role === 'floating-menu';}-function shouldPreserveEmbedInteractiveFocus(embedId: string | undefined, ownerDocument: Document): boolean {+export function shouldPreserveEmbedInteractiveFocus(embedId: string | undefined, ownerDocument: Document): boolean {if (!embedId) {return false;}@@ -176,15 +179,15 @@ function shouldPreserveEmbedInteractiveFocus(embedId: string | undefined, ownerDreturn false;}- const ownerElement = activeElement.closest(`[${SHEET_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE}="${embedId}"]`);- if (!ownerElement) {+ if (getEmbedBoundaryOwner(activeElement) !== embedId) {return false;}const role = activeElement.getAttribute(SHEET_EMBED_RUNTIME_FOCUS_ROLE_ATTRIBUTE) ??activeElement.closest(`[${SHEET_EMBED_RUNTIME_FOCUS_ROLE_ATTRIBUTE}]`)?.getAttribute(SHEET_EMBED_RUNTIME_FOCUS_ROLE_ATTRIBUTE);- return (role == null && activeElement.tagName !== 'CANVAS') ||+ return activeElement.matches('input, textarea, select') ||+ (role == null && activeElement.tagName !== 'CANVAS') ||role === 'child-editor' ||role === 'child-popup' ||role === 'floating-menu';@@ -401,7 +404,7 @@ export function EditorContainer({ hidden = false }: IEditorContainerProps) {const scope = rootRef.current? resolveSheetEmbedRuntimeDomScope(rootRef.current) ?? resolveActiveSheetEmbedRuntimeDomScope(ownerDocument): resolveActiveSheetEmbedRuntimeDomScope(ownerDocument);- if (shouldPreserveEmbedPopupFocus(scope?.embedId, ownerDocument)) {+ if (shouldPreserveEmbedControlFocus(scope?.embedId, ownerDocument)) {return;}@@ -490,7 +493,7 @@ export function EditorContainer({ hidden = false }: IEditorContainerProps) {const ownerDocument = rootRef.current.ownerDocument;let pointerRetryFrame = 0;const focusEditor = () => {- if (contextService.getContextValue(FOCUSING_FX_BAR_EDITOR) || shouldPreserveEmbedPopupFocus(scope.embedId, ownerDocument)) {+ if (contextService.getContextValue(FOCUSING_FX_BAR_EDITOR) || shouldPreserveEmbedControlFocus(scope.embedId, ownerDocument)) {return;}@@ -576,7 +579,7 @@ export function EditorContainer({ hidden = false }: IEditorContainerProps) {}, 0);};const focusHiddenEditor = () => {- if (shouldPreserveEmbedPopupFocus(activeSessionScope.embedId, ownerDocument)) {+ if (shouldPreserveEmbedControlFocus(activeSessionScope.embedId, ownerDocument)) {return;}@@ -603,6 +606,9 @@ export function EditorContainer({ hidden = false }: IEditorContainerProps) {}cancelAnimationFrame(pointerRetryFrame);+ if (event.type === 'click') {+ focusHiddenEditor();+ }pointerRetryFrame = requestAnimationFrame(focusHiddenEditor);};ownerDocument.addEventListener('pointerdown', refocusHiddenEditorAfterRuntimePointer, true);diff --git a/packages/sheets-ui/src/views/editor-container/__tests__/EditorContainer.spec.tsx b/packages/sheets-ui/src/views/editor-container/__tests__/EditorContainer.spec.tsxindex baef4bca1c..6a00c0387c 100644--- a/packages/sheets-ui/src/views/editor-container/__tests__/EditorContainer.spec.tsx+++ b/packages/sheets-ui/src/views/editor-container/__tests__/EditorContainer.spec.tsx@@ -55,10 +55,60 @@ import {ISheetEmbedInteractionBoundaryService,ISheetEmbedRuntimeFocusCoordinator,} from '../../../services/sheet-embed-integration.service';-import { EditorContainer, shouldRefocusCellEditorAfterPointerDown } from '../EditorContainer';+import {+ EditorContainer,+ shouldPreserveEmbedControlFocus,+ shouldPreserveEmbedInteractiveFocus,+ shouldRefocusCellEditorAfterPointerDown,+} from '../EditorContainer';(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+describe('embed editor focus handoff', () => {+ it.each([+ { name: 'Name Box input', tag: 'input', role: 'runtime', control: true, interactive: true },+ { name: 'textarea', tag: 'textarea', role: 'runtime', control: true, interactive: true },+ { name: 'native select', tag: 'select', role: 'runtime', control: true, interactive: true },+ { name: 'popup input', tag: 'input', role: 'child-popup', control: true, interactive: true },+ { name: 'floating menu', tag: 'button', role: 'floating-menu', control: true, interactive: true },+ { name: 'cell editor', tag: 'div', id: `__editor_${DOCS_NORMAL_EDITOR_UNIT_ID_KEY}`, role: 'child-editor', control: false, interactive: true },+ { name: 'Shape text editor', tag: 'div', id: '__editor_shape-text', role: 'child-editor', control: true, interactive: true },+ { name: 'nested Shape text editor', tag: 'div', id: '__editor_shape-text', role: 'child-editor', nested: true, control: false, interactive: false },+ { name: 'canvas', tag: 'canvas', role: 'runtime', control: false, interactive: false },+ { name: 'runtime', tag: 'div', role: 'runtime', control: false, interactive: false },+ { name: 'nested foreign input', tag: 'input', role: 'runtime', nested: true, control: false, interactive: false },+ { name: 'nested foreign popup', tag: 'input', role: 'child-popup', nested: true, control: false, interactive: false },+ ])('preserves the intended focus owner for $name', ({ tag, id, role, nested, control, interactive }) => {+ const runtime = document.createElement('div');+ runtime.setAttribute(EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE, 'embed-1');+ runtime.setAttribute(EMBED_RUNTIME_FOCUS_ROLE_ATTRIBUTE, role);+ const activeElement = document.createElement(tag);+ activeElement.tabIndex = 0;+ if (id) {+ activeElement.id = id;+ activeElement.contentEditable = 'true';+ }+ if (nested) {+ activeElement.setAttribute(EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE, 'embed-2');+ }+ runtime.appendChild(activeElement);+ document.body.appendChild(runtime);++ try {+ activeElement.focus();+ expect(document.activeElement).toBe(activeElement);+ expect(shouldPreserveEmbedControlFocus('embed-1', document)).toBe(control);+ expect(shouldPreserveEmbedInteractiveFocus('embed-1', document)).toBe(interactive);+ expect(shouldPreserveEmbedControlFocus('another-embed', document)).toBe(false);+ expect(shouldPreserveEmbedInteractiveFocus('another-embed', document)).toBe(false);+ expect(shouldPreserveEmbedControlFocus(undefined, document)).toBe(false);+ expect(shouldPreserveEmbedInteractiveFocus(undefined, document)).toBe(false);+ } finally {+ runtime.remove();+ }+ });+});+let latestFormulaEditorProps: {disableSelectionOnClick?: boolean;isFocus?: boolean;diff --git a/packages/sheets-ui/src/views/editor-container/hooks.ts b/packages/sheets-ui/src/views/editor-container/hooks.tsindex 7369b5b401..0358c3ca9b 100644--- a/packages/sheets-ui/src/views/editor-container/hooks.ts+++ b/packages/sheets-ui/src/views/editor-container/hooks.ts@@ -14,10 +14,10 @@* limitations under the License.*/-import { ICommandService } from '@univerjs/core';+import { ICommandService, Injector } from '@univerjs/core';import { DocSelectionRenderService } from '@univerjs/docs-ui';import { DeviceInputEventType, IRenderManagerService } from '@univerjs/engine-render';-import { KeyCode, useDependency, useObservable } from '@univerjs/ui';+import { IUIRuntimeScopeService, KeyCode, MetaKeys, useDependency, useObservable } from '@univerjs/ui';import { useMemo } from 'react';import { map, merge } from 'rxjs';import { SetCellEditVisibleOperation } from '../../commands/operations/cell-edit.operation';@@ -26,29 +26,40 @@ import { IEditorBridgeService } from '../../services/editor-bridge.service';export function useKeyEventConfig(unitId?: string) {const editorBridgeService = useDependency(IEditorBridgeService);const commandService = useDependency(ICommandService);+ const injector = useDependency(Injector);const keyCodeConfig = useMemo(() => ({keyCodes: [{ keyCode: KeyCode.ENTER },+ { keyCode: KeyCode.ENTER, metaKey: MetaKeys.SHIFT },{ keyCode: KeyCode.ESC },{ keyCode: KeyCode.TAB },+ { keyCode: KeyCode.TAB, metaKey: MetaKeys.SHIFT },],- handler: (keycode: KeyCode) => {+ handler: (keycode: KeyCode, metaKey?: MetaKeys) => {if (keycode === KeyCode.ENTER || keycode === KeyCode.ESC || keycode === KeyCode.TAB) {if (unitId == null) {return;}editorBridgeService.disableForceKeepVisible();- commandService.syncExecuteCommand(SetCellEditVisibleOperation.id, {+ // The shared editor can outlive the child runtime that first mounted it.+ const runtimeScope = injector.has(IUIRuntimeScopeService)+ ? injector.get(IUIRuntimeScopeService).get(unitId)+ : undefined;+ const targetCommandService = runtimeScope?.has(ICommandService)+ ? runtimeScope.get<ICommandService>(ICommandService)+ : commandService;+ targetCommandService.syncExecuteCommand(SetCellEditVisibleOperation.id, {visible: false,eventType: DeviceInputEventType.Keyboard,keycode,+ isShift: metaKey === MetaKeys.SHIFT,unitId,});}},- }), [commandService, editorBridgeService, unitId]);+ }), [commandService, editorBridgeService, injector, unitId]);return keyCodeConfig;}diff --git a/packages/sheets-ui/src/views/menu-item-input/MenuItemInput.tsx b/packages/sheets-ui/src/views/menu-item-input/MenuItemInput.tsxindex bf2fc456bb..484453f512 100644--- a/packages/sheets-ui/src/views/menu-item-input/MenuItemInput.tsx+++ b/packages/sheets-ui/src/views/menu-item-input/MenuItemInput.tsx@@ -19,7 +19,7 @@ import type { IMenuItemInputProps } from './interface';import { LocaleService } from '@univerjs/core';import { InputNumber } from '@univerjs/design';import { IContextMenuService, useDependency, useObservable } from '@univerjs/ui';-import { useEffect, useState } from 'react';+import { useEffect, useRef, useState } from 'react';export const MenuItemInput = (props: IMenuItemInputProps) => {const {@@ -36,6 +36,14 @@ export const MenuItemInput = (props: IMenuItemInputProps) => {const contextMenuService = useDependency(IContextMenuService);const disabled = useObservable(disabled$ ?? null, false);const [inputValue, setInputValue] = useState<string>(); // Initialized to an empty string+ const composingRef = useRef(false);+ const compositionEndTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);++ useEffect(() => () => {+ if (compositionEndTimerRef.current !== null) {+ clearTimeout(compositionEndTimerRef.current);+ }+ }, []);const handleChange = (value: number | null) => {if (!value) {@@ -71,13 +79,42 @@ export const MenuItemInput = (props: IMenuItemInputProps) => {}function handleKeyDown(event: KeyboardEvent<HTMLInputElement>) {+ if (event.key === 'Escape' && !event.nativeEvent.isComposing && !composingRef.current) {+ return;+ }event.stopPropagation();}+ function resetComposition() {+ if (compositionEndTimerRef.current !== null) {+ clearTimeout(compositionEndTimerRef.current);+ compositionEndTimerRef.current = null;+ }+ composingRef.current = false;+ }++ function handleCompositionStart() {+ resetComposition();+ composingRef.current = true;+ }++ function handleCompositionEnd() {+ resetComposition();+ composingRef.current = true;+ // Safari may dispatch the ending key after compositionend in the same task.+ compositionEndTimerRef.current = setTimeout(resetComposition, 0);+ }+return (<div className="univer-inline-flex univer-items-center univer-gap-1">{localeService.t(prefix)}- <div className="univer-w-16" onClick={(e) => e.stopPropagation()}>+ <div+ className="univer-w-16"+ onClick={(e) => e.stopPropagation()}+ onCompositionStart={handleCompositionStart}+ onCompositionEnd={handleCompositionEnd}+ onBlur={resetComposition}+ ><InputNumbervalue={Number(inputValue)}size="mini"diff --git a/packages/sheets-ui/src/views/menu-item-input/__tests__/MenuItemInput.spec.tsx b/packages/sheets-ui/src/views/menu-item-input/__tests__/MenuItemInput.spec.tsxindex 391b408899..fb9a856f48 100644--- a/packages/sheets-ui/src/views/menu-item-input/__tests__/MenuItemInput.spec.tsx+++ b/packages/sheets-ui/src/views/menu-item-input/__tests__/MenuItemInput.spec.tsx@@ -15,24 +15,19 @@*/import type { ReactElement } from 'react';-import { Injector, LocaleService } from '@univerjs/core';+import { Injector, LocaleService, LocaleType } from '@univerjs/core';import { ConfigProvider } from '@univerjs/design';-import enUS from '@univerjs/design/locale/en-US';+import designEnUS from '@univerjs/design/locale/en-US';import { ContextMenuService, IContextMenuService, RediContext } from '@univerjs/ui';import { act } from 'react';import { createRoot } from 'react-dom/client';import { BehaviorSubject } from 'rxjs';-import { afterEach, describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';+import enUS from '../../../locale/en-US';import { MenuItemInput } from '../MenuItemInput';(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;-class TestLocaleService {- t(key: string): string {- return key;- }-}-class ChangeRecords {static values: string[] = [];@@ -47,8 +42,12 @@ class ChangeRecords {function createInjector() {const injector = new Injector();- injector.add([LocaleService, { useClass: TestLocaleService as never }]);+ injector.add([LocaleService]);injector.add([IContextMenuService, { useClass: ContextMenuService }]);+ const localeService = injector.get(LocaleService);+ localeService.load({ [LocaleType.EN_US]: { ...enUS, ...designEnUS } });+ localeService.setLocale(LocaleType.EN_US);+ localeService.setDirection('ltr');return injector;}@@ -62,7 +61,7 @@ function renderWithDependencies(element: ReactElement) {act(() => {root.render(<RediContext.Provider value={{ injector }}>- <ConfigProvider locale={enUS.design} mountContainer={container}>+ <ConfigProvider locale={designEnUS.design} mountContainer={container}>{element}</ConfigProvider></RediContext.Provider>@@ -75,6 +74,7 @@ function renderWithDependencies(element: ReactElement) {unmount: () => {act(() => root.unmount());container.remove();+ injector.dispose();},};}@@ -95,7 +95,7 @@ function setInputText(input: HTMLInputElement, value: string) {}function clickIncrement(container: HTMLElement) {- const incrementButton = container.querySelector(`[aria-label="${enUS.design.Accessibility.increment}"]`);+ const incrementButton = container.querySelector(`[aria-label="${designEnUS.design.Accessibility.increment}"]`);if (!(incrementButton instanceof HTMLElement)) {throw new TypeError('Increment button not found');}@@ -109,13 +109,14 @@ describe('MenuItemInput', () => {afterEach(() => {disposals.splice(0).forEach((dispose) => dispose());ChangeRecords.reset();+ vi.useRealTimers();});it('clamps typed values to the configured maximum before reporting the command value', () => {const { container, unmount } = renderWithDependencies(<MenuItemInput- prefix="sheet.menu.before"- suffix="sheet.menu.after"+ prefix="sheets-ui.rightClick.insertRowsAbove"+ suffix="sheets-ui.rightClick.insertRowsAboveSuffix"value="12"min={5}max={20}@@ -136,8 +137,8 @@ describe('MenuItemInput', () => {const disabled$ = new BehaviorSubject(false);const { container, unmount } = renderWithDependencies(<MenuItemInput- prefix="sheet.menu.before"- suffix="sheet.menu.after"+ prefix="sheets-ui.rightClick.insertRowsAbove"+ suffix="sheets-ui.rightClick.insertRowsAboveSuffix"value="10"min={1}max={20}@@ -146,6 +147,7 @@ describe('MenuItemInput', () => {/>);disposals.push(unmount);+ disposals.push(() => disabled$.complete());act(() => {disabled$.next(true);@@ -167,4 +169,116 @@ describe('MenuItemInput', () => {expect(getInput(container).value).toBe('11');expect(ChangeRecords.values).toEqual(['11']);});++ it('lets Escape reach the enclosing menu without changing the input value', () => {+ const keys: string[] = [];+ const { container, unmount } = renderWithDependencies(+ <div onKeyDown={(event) => keys.push(event.key)}>+ <MenuItemInput+ prefix="sheets-ui.rightClick.insertRowsAbove"+ suffix="sheets-ui.rightClick.insertRowsAboveSuffix"+ value="2"+ min={1}+ onChange={(value) => ChangeRecords.push(value)}+ />+ </div>+ );+ disposals.push(unmount);+ act(() => getInput(container).dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })));++ expect(keys).toEqual(['Escape']);+ expect(getInput(container).value).toBe('2');+ expect(ChangeRecords.values).toEqual([]);+ });++ it('keeps editing keys and an active IME Escape inside the input', () => {+ const keys: string[] = [];+ const { container, unmount } = renderWithDependencies(+ <div onKeyDown={(event) => keys.push(event.key)}>+ <MenuItemInput+ prefix="sheets-ui.rightClick.insertRowsAbove"+ suffix="sheets-ui.rightClick.insertRowsAboveSuffix"+ value="2"+ min={1}+ onChange={(value) => ChangeRecords.push(value)}+ />+ </div>+ );+ disposals.push(unmount);+ const input = getInput(container);+ for (const key of ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End', 'Backspace', 'Delete', 'Enter']) {+ act(() => input.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true })));+ }+ for (const modifier of [{ ctrlKey: true }, { metaKey: true }]) {+ act(() => input.dispatchEvent(new KeyboardEvent('keydown', { key: 'a', bubbles: true, ...modifier })));+ }+ act(() => input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, isComposing: true })));++ expect(keys).toEqual([]);+ expect(input.value).toBe('2');+ });++ it('keeps the composition-ending Escape local and accepts a subsequent Escape', () => {+ vi.useFakeTimers();+ const keys: string[] = [];+ const { container, unmount } = renderWithDependencies(+ <div onKeyDown={(event) => keys.push(event.key)}>+ <MenuItemInput+ prefix="sheets-ui.rightClick.insertRowsAbove"+ suffix="sheets-ui.rightClick.insertRowsAboveSuffix"+ value="2"+ min={1}+ onChange={(value) => ChangeRecords.push(value)}+ />+ </div>+ );+ disposals.push(unmount);+ const input = getInput(container);+ act(() => {+ input.dispatchEvent(new CompositionEvent('compositionstart', { bubbles: true }));+ input.dispatchEvent(new CompositionEvent('compositionend', { bubbles: true }));+ // Safari can deliver the ending key after compositionend with isComposing already false.+ input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, isComposing: false }));+ });+ expect(keys).toEqual([]);+ expect(input.value).toBe('2');+ expect(ChangeRecords.values).toEqual([]);++ act(() => vi.runOnlyPendingTimers());+ act(() => input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })));+ expect(keys).toEqual(['Escape']);+ });++ it.each(['blur', 'unmount'])('cleans up the composition boundary on %s', (action) => {+ vi.useFakeTimers();+ const keys: string[] = [];+ const { container, unmount } = renderWithDependencies(+ <div onKeyDown={(event) => keys.push(event.key)}>+ <MenuItemInput+ prefix="sheets-ui.rightClick.insertRowsAbove"+ suffix="sheets-ui.rightClick.insertRowsAboveSuffix"+ value="2"+ min={1}+ onChange={(value) => ChangeRecords.push(value)}+ />+ </div>+ );+ disposals.push(unmount);+ const input = getInput(container);+ const initialTimers = vi.getTimerCount();+ act(() => {+ input.dispatchEvent(new CompositionEvent('compositionstart', { bubbles: true }));+ input.dispatchEvent(new CompositionEvent('compositionend', { bubbles: true }));+ });++ if (action === 'unmount') {+ disposals.pop()?.();+ } else {+ act(() => input.dispatchEvent(new FocusEvent('focusout', { bubbles: true })));+ act(() => input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })));+ expect(keys).toEqual(['Escape']);+ }+ expect(vi.getTimerCount()).toBe(initialTimers);+ expect(ChangeRecords.values).toEqual([]);+ });});diff --git a/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx b/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsxindex 64788a61e9..39023af1d4 100644--- a/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx+++ b/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx@@ -50,7 +50,7 @@ export function RenderSheetFooter() {const activeEmbedTab = useActiveSheetEmbedTabData(workbook);if (!workbook || !showFooter) return null;if (activeWorkbookEmbeddedRender) return null;- if (rootUnitType !== UniverInstanceType.UNIVER_SHEET) return null;+ if (rootUnitType !== UniverInstanceType.UNIVER_SHEET && !activeEmbedTab) return null;const footerMenus = menuManagerService.getMenuByPositionKey(ContextMenuPosition.FOOTER_MENU);const {@@ -123,27 +123,54 @@ export interface IRenderSheetContentProps {export function RenderSheetContent({ AutoFillPopupMenuComponent = AutoFillPopupMenu }: IRenderSheetContentProps = {}) {const config = useConfigValue<IUniverSheetsUIConfig>(SHEETS_UI_PLUGIN_CONFIG_KEY);const componentManager = useDependency(ComponentManager);+ const activeWorkbook = useActiveWorkbook();const workbook = useRootWorkbenchWorkbook();const activeEmbedTab = useActiveSheetEmbedTabData(workbook);const injector = useDependency(Injector);+ const activeUnitEmbeddedRender = useActiveWorkbookIsEmbeddedRender(activeWorkbook);const activeWorkbookEmbeddedRender = useActiveWorkbookIsEmbeddedRender(workbook);const rootUnitType = useWorkbenchRootUnitType();- const rootWorkbenchOwnsSheet = rootUnitType === UniverInstanceType.UNIVER_SHEET;+ const rootWorkbenchOwnsSheet = rootUnitType === UniverInstanceType.UNIVER_SHEET || Boolean(activeEmbedTab);// We use string keys to avoid a hard dependency on sheets-shape-ui.const ShapeTextEditorContainer = componentManager.get('SheetShapeTextEditorContainer') ?? componentManager.get('ShapeTextEditorContainer');const CellEditorContainer = componentManager.get(EMBEDDING_CELL_EDITOR_COMPONENT_KEY) ?? EditorContainer;useEffect(() => {- if (!workbook || activeEmbedTab || activeWorkbookEmbeddedRender || !rootWorkbenchOwnsSheet) {+ if (+ !workbook ||+ activeEmbedTab ||+ activeWorkbook?.getUnitId() !== workbook.getUnitId() ||+ activeUnitEmbeddedRender ||+ activeWorkbookEmbeddedRender ||+ !rootWorkbenchOwnsSheet+ ) {return;}const instanceService = injector.get(IUniverInstanceService);+ const currentWorkbook = instanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);+ const runtimeFocusCoordinator = injector.has(ISheetEmbedRuntimeFocusCoordinator)+ ? injector.get(ISheetEmbedRuntimeFocusCoordinator)+ : undefined;+ const currentRuntimeScope = runtimeFocusCoordinator?.resolveRuntimeScopeByChildUnitId(+ currentWorkbook?.getUnitId()+ );+ const currentWorkbookEmbeddedRender = currentWorkbook != null && (+ injector.get(IRenderManagerService).getRenderUnitById(currentWorkbook.getUnitId())?.isMainScene === false ||+ instanceService.getUnitCreateOptions(currentWorkbook.getUnitId())?.embeddedRender === true+ );+ if (+ currentWorkbook?.getUnitId() !== workbook.getUnitId() &&+ (currentRuntimeScope?.hostUnitId === workbook.getUnitId() || currentWorkbookEmbeddedRender)+ ) {+ return;+ }+instanceService.setCurrentUnitForType(workbook.getUnitId());instanceService.focusUnit(workbook.getUnitId());tryGetSheetEmbedRuntimeService(injector)?.clearTab();- }, [activeEmbedTab, activeWorkbookEmbeddedRender, injector, rootWorkbenchOwnsSheet, workbook]);+ }, [activeEmbedTab, activeUnitEmbeddedRender, activeWorkbook, activeWorkbookEmbeddedRender, injector, rootWorkbenchOwnsSheet, workbook]);if (!workbook) return null;if (!rootWorkbenchOwnsSheet) return null;diff --git a/packages/sheets/src/commands/commands/__tests__/set-range-values.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-range-values.command.spec.tsindex 4cd5724a4c..d066854faa 100644--- a/packages/sheets/src/commands/commands/__tests__/set-range-values.command.spec.ts+++ b/packages/sheets/src/commands/commands/__tests__/set-range-values.command.spec.ts@@ -280,6 +280,33 @@ describe('Test set range values commands', () => {expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();});+ it('keeps complex cell data independent from command parameters across undo and redo', async () => {+ const richText: IDocumentData = {+ id: 'rich-text',+ body: {+ dataStream: 'rich text\r\n',+ textRuns: [{ st: 5, ed: 9, ts: { bl: BooleanNumber.TRUE } }],+ },+ documentStyle: {},+ };+ const params: ISetRangeValuesCommandParams = {+ value: { p: richText, v: null },+ };++ expect(await commandService.executeCommand(SetRangeValuesCommand.id, params)).toBeTruthy();+ expect(getValue()?.p).not.toBe(richText);+ richText.body!.textRuns = [];+ expect(getValue()?.p?.body?.textRuns).toEqual([+ { st: 5, ed: 9, ts: { bl: BooleanNumber.TRUE } },+ ]);++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ expect(getValue()?.p?.body?.textRuns).toEqual([+ { st: 5, ed: 9, ts: { bl: BooleanNumber.TRUE } },+ ]);+ });+it('will set range values when there is a selected range, includes custom property', async () => {function getParams() {const params: ISetRangeValuesCommandParams = {diff --git a/packages/sheets/src/commands/commands/set-range-values.command.ts b/packages/sheets/src/commands/commands/set-range-values.command.tsindex fb21ece9d1..22f73ab1ee 100644--- a/packages/sheets/src/commands/commands/set-range-values.command.ts+++ b/packages/sheets/src/commands/commands/set-range-values.command.ts@@ -98,7 +98,11 @@ export const SetRangeValuesCommand: ICommand = {ranges = realCellValue ? [new ObjectMatrix(realCellValue).getStartEndScope()] : [];}- const setRangeValuesMutationRedoParams = { unitId, subUnitId, cellValue: realCellValue ?? cellValue.getMatrix() };+ const setRangeValuesMutationRedoParams = {+ unitId,+ subUnitId,+ cellValue: Tools.deepClone(realCellValue ?? cellValue.getMatrix()),+ };const setRangeValuesMutationUndoParams = SetRangeValuesUndoMutationFactory(accessor, setRangeValuesMutationRedoParams);const cellHeights = mapObjectMatrix(setRangeValuesMutationRedoParams.cellValue, (row, col) => worksheet.getCellHeight(row, col) || undefined);diff --git a/packages/sheets/src/commands/mutations/set-range-values.mutation.ts b/packages/sheets/src/commands/mutations/set-range-values.mutation.tsindex 5382b4e9e1..7497c2b0f4 100644--- a/packages/sheets/src/commands/mutations/set-range-values.mutation.ts+++ b/packages/sheets/src/commands/mutations/set-range-values.mutation.ts@@ -207,6 +207,6 @@ function updateCellProperty<K extends keyof ICellData>(} else if (value === null) {delete cell[key];} else {- cell[key] = value;+ cell[key] = Tools.deepClone(value);}}diff --git a/packages/sheets/src/controllers/__tests__/merge-cell.controller.spec.ts b/packages/sheets/src/controllers/__tests__/merge-cell.controller.spec.tsnew file mode 100644index 0000000000..a0d63bbb99--- /dev/null+++ b/packages/sheets/src/controllers/__tests__/merge-cell.controller.spec.ts@@ -0,0 +1,139 @@+/**+ * 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 { IRange, IWorkbookData, Univer, Workbook, Worksheet } from '@univerjs/core';+import {+ CellValueType,+ ICommandService,+ IUniverInstanceService,+ LocaleType,+ ObjectMatrix,+ RedoCommand,+ Tools,+ UndoCommand,+ UniverInstanceType,+} from '@univerjs/core';+import { afterEach, describe, expect, it } from 'vitest';+import { createCommandTestBed } from '../../commands/commands/__tests__/create-command-test-bed';+import { ClearSelectionAllCommand } from '../../commands/commands/clear-selection-all.command';+import { ClearSelectionFormatCommand } from '../../commands/commands/clear-selection-format.command';+import { AddWorksheetMergeMutation } from '../../commands/mutations/add-worksheet-merge.mutation';+import { RemoveWorksheetMergeMutation } from '../../commands/mutations/remove-worksheet-merge.mutation';+import { SetRangeValuesMutation } from '../../commands/mutations/set-range-values.mutation';+import { RefRangeService } from '../../services/ref-range/ref-range.service';+import { SheetsSelectionsService } from '../../services/selections/selection.service';+import { MergeCellController } from '../merge-cell.controller';++const TARGET_RANGE: IRange = { startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 };+const PEER_RANGE: IRange = { startRow: 5, endRow: 6, startColumn: 5, endColumn: 6 };++describe('MergeCellController clear-command ownership', () => {+ let univer: Univer;++ afterEach(() => univer.dispose());++ for (const command of [ClearSelectionFormatCommand, ClearSelectionAllCommand]) {+ for (const current of ['none', 'other-workbook', 'other-worksheet'] as const) {+ it(`${command.id} clears only the explicit target with ${current} current`, async () => {+ const testBed = createCommandTestBed(workbookSnapshot('test'), [[MergeCellController], [RefRangeService]]);+ univer = testBed.univer;+ const { get } = testBed;+ const instanceService = get(IUniverInstanceService);+ if (current === 'none') {+ instanceService.disposeUnit('test');+ }+ const child = instanceService.createUnit<IWorkbookData, Workbook>(+ UniverInstanceType.UNIVER_SHEET,+ workbookSnapshot('child'),+ { makeCurrent: false }+ );+ if (current === 'other-worksheet') {+ instanceService.setCurrentUnitForType('child');+ }+ const selections = get(SheetsSelectionsService);+ if (current !== 'none') {+ selections.setSelections(current === 'other-workbook' ? 'test' : 'child', 'sheet1', [{+ range: PEER_RANGE,+ primary: null,+ style: null,+ }]);+ }+ get(MergeCellController);+ const commandService = get(ICommandService);+ for (const registration of [command, AddWorksheetMergeMutation, RemoveWorksheetMergeMutation, SetRangeValuesMutation]) {+ commandService.registerCommand(registration);+ }+ const target = child.getSheetBySheetId('sheet2')!;+ const otherSheet = child.getSheetBySheetId('sheet1')!;+ const before = sheetState(target);+ const peerBefore = Tools.deepClone(otherSheet.getSnapshot());+ const hostBefore = current === 'none' ? undefined : Tools.deepClone(testBed.sheet.getSnapshot());++ expect(await commandService.executeCommand(command.id, {+ unitId: 'child',+ subUnitId: 'sheet2',+ ranges: [TARGET_RANGE],+ })).toBe(true);+ expect(target.getMergeData()).toEqual([PEER_RANGE]);+ expect(otherSheet.getSnapshot()).toEqual(peerBefore);+ if (hostBefore) {+ expect(testBed.sheet.getSnapshot()).toEqual(hostBefore);+ }+ const cleared = sheetState(target);+ instanceService.focusUnit('child');+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);+ expect(sheetState(target)).toEqual(before);+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);+ expect(sheetState(target)).toEqual(cleared);+ expect(otherSheet.getSnapshot()).toEqual(peerBefore);+ });+ }+ }+});++function workbookSnapshot(id: string): IWorkbookData {+ return {+ id,+ name: id,+ appVersion: '0.0.0',+ locale: LocaleType.EN_US,+ sheetOrder: ['sheet1', 'sheet2'],+ styles: {},+ sheets: Object.fromEntries(['sheet1', 'sheet2'].map((sheetId) => [sheetId, {+ id: sheetId,+ name: sheetId,+ rowCount: 10,+ columnCount: 10,+ mergeData: [Tools.deepClone(TARGET_RANGE), Tools.deepClone(PEER_RANGE)],+ cellData: {+ 1: { 1: { v: 'target', t: CellValueType.STRING, s: { bl: 1 } } },+ 5: { 5: { v: 'peer', t: CellValueType.STRING, s: { it: 1 } } },+ },+ }])),+ };+}++function sheetState(worksheet: Worksheet) {+ const snapshot = Tools.deepClone(worksheet.getSnapshot());+ // Undo may intern styles and append restored merges; compare their complete semantic state.+ new ObjectMatrix(snapshot.cellData).forValue((row, column, cell) => {+ if (cell?.s != null) {+ cell.s = Tools.deepClone(worksheet.getCellStyle(row, column));+ }+ });+ snapshot.mergeData.sort((left, right) => left.startRow - right.startRow || left.startColumn - right.startColumn);+ return snapshot;+}diff --git a/packages/sheets/src/controllers/merge-cell.controller.ts b/packages/sheets/src/controllers/merge-cell.controller.tsindex de3e8c969a..dd94a9e9ce 100644--- a/packages/sheets/src/controllers/merge-cell.controller.ts+++ b/packages/sheets/src/controllers/merge-cell.controller.ts@@ -14,8 +14,6 @@* limitations under the License.*/-/* eslint-disable max-lines-per-function */-import type {ICommandInfo,IMutationInfo,@@ -29,7 +27,8 @@ import type {IRemoveRowsMutationParams,IRemoveWorksheetMergeMutationParams,} from '../basics/interfaces/mutation-interface';-+import type { IClearSelectionAllCommandParams } from '../commands/commands/clear-selection-all.command';+import type { IClearSelectionFormatCommandParams } from '../commands/commands/clear-selection-format.command';import type { IDeleteRangeMoveLeftCommandParams } from '../commands/commands/delete-range-move-left.command';import type { IDeleteRangeMoveUpCommandParams } from '../commands/commands/delete-range-move-up.command';import type { IInsertRangeMoveDownCommandParams } from '../commands/commands/insert-range-move-down.command';@@ -51,10 +50,11 @@ import {InterceptorManager,IUniverInstanceService,Rectangle,+ toDisposable,Tools,UniverInstanceType,} from '@univerjs/core';-import { first } from 'rxjs';+import { filter, take } from 'rxjs';import { ClearSelectionAllCommand } from '../commands/commands/clear-selection-all.command';import { ClearSelectionFormatCommand } from '../commands/commands/clear-selection-format.command';import { DeleteRangeMoveLeftCommand } from '../commands/commands/delete-range-move-left.command';@@ -143,13 +143,14 @@ export class MergeCellController extends Disposable {@Inject(SheetsSelectionsService) private _selectionManagerService: SheetsSelectionsService) {super();+ this.disposeWithMe(this.disposableCollection);this._onRefRangeChange();this._initCommandInterceptor();this._commandExecutedListener();}private _initCommandInterceptor() {- this._sheetInterceptorService.interceptCommand({+ this.disposeWithMe(this._sheetInterceptorService.interceptCommand({getMutations: (commandInfo) => {switch (commandInfo.id) {case MoveRangeCommand.id: {@@ -166,17 +167,15 @@ export class MergeCellController extends Disposable {}case ClearSelectionAllCommand.id:case ClearSelectionFormatCommand.id: {- // TODO@Gggpound: get by unit id and subUnitId- const workbook = this._univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;- const unitId = workbook.getUnitId();- const worksheet = workbook?.getActiveSheet();- if (!worksheet) {+ const params = commandInfo.params as IClearSelectionAllCommandParams | IClearSelectionFormatCommandParams | undefined;+ const target = getSheetCommandTarget(this._univerInstanceService, params);+ if (!target) {return { redos: [], undos: [] };}- const subUnitId = worksheet.getSheetId();+ const { unitId, subUnitId, worksheet } = target;const mergeData = worksheet.getConfig().mergeData;- const selections = this._selectionManagerService.getCurrentSelections()?.map((s) => s.range);+ const selections = params?.ranges ?? this._selectionManagerService.getCurrentSelections()?.map((s) => s.range);if (selections && selections.length > 0) {const isHasMerge = selections.some((range) =>mergeData.some((item) => Rectangle.intersects(item, range))@@ -203,9 +202,9 @@ export class MergeCellController extends Disposable {return { redos: [], undos: [] };},- });+ }));- this._sheetInterceptorService.interceptRanges({+ this.disposeWithMe(this._sheetInterceptorService.interceptRanges({getMutations: ({ unitId, subUnitId, ranges }) => {const redos: IMutationInfo[] = [];const undos: IMutationInfo[] = [];@@ -242,7 +241,7 @@ export class MergeCellController extends Disposable {return emptyInterceptorArr;},- });+ }));}refRangeHandle(config: EffectRefRangeParams, unitId: string, subUnitId: string) {@@ -340,12 +339,18 @@ export class MergeCellController extends Disposable {}));- this._univerInstanceService.getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET).pipe(first((workbook) => !!workbook)).subscribe((workbook) => {- const sheet = workbook!.getActiveSheet();- if (!sheet) return;-- registerRefRange(workbook!.getUnitId(), sheet.getSheetId());- });+ this.disposeWithMe(toDisposable(+ this._univerInstanceService.getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET).pipe(+ filter((workbook): workbook is Workbook => !!workbook),+ take(1)+ ).subscribe((workbook) => {+ const sheet = workbook.getActiveSheet();+ if (!sheet) {+ return;+ }+ registerRefRange(workbook.getUnitId(), sheet.getSheetId());+ })+ ));}private _handleMoveRowsCommand(params: IMoveRowsCommandParams, unitId: string, subUnitId: string) {diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.tsindex 510f46f0ec..1c2e6a0fc5 100644--- a/packages/sheets/src/index.ts+++ b/packages/sheets/src/index.ts@@ -15,7 +15,8 @@*/export type { ICellOverGridPosition, ISheetOverGridPosition } from './basics/cell-position';-export { checkCellValueType, isCellImage } from './basics/cell-type';+export { checkCellValueType, getCellType, isCellImage } from './basics/cell-type';+export { getCellValue } from './basics/cell-value';export {COMMAND_LISTENER_SKELETON_CHANGE,COMMAND_LISTENER_VALUE_CHANGE,diff --git a/packages/thread-comment-ui/src/views/__tests__/ThreadCommentEditor.spec.tsx b/packages/thread-comment-ui/src/views/__tests__/ThreadCommentEditor.spec.tsxindex cd86f2213b..599596a361 100644--- a/packages/thread-comment-ui/src/views/__tests__/ThreadCommentEditor.spec.tsx+++ b/packages/thread-comment-ui/src/views/__tests__/ThreadCommentEditor.spec.tsx@@ -41,6 +41,7 @@ import {Injector,IUniverInstanceService,LocaleService,+ LocaleType,LogLevel,toDisposable,UniverInstanceType,@@ -52,14 +53,16 @@ import { createRoot } from 'react-dom/client';import { BehaviorSubject, Subject } from 'rxjs';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { SetActiveCommentOperation } from '../../commands/operations/comment.operations';+import enUS from '../../locale/en-US';import { ThreadCommentPanelService } from '../../services/thread-comment-panel.service';import { ThreadCommentEditor } from '../ThreadCommentEditor';(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;const EDITOR_ID = 'thread-comment-editor';-const REPLY_LABEL = 'thread-comment-ui.editor.reply';-const CANCEL_LABEL = 'thread-comment-ui.editor.cancel';+const REPLY_LABEL = enUS['thread-comment-ui'].editor.reply;+const CANCEL_LABEL = enUS['thread-comment-ui'].editor.cancel;+const testInjectors: Injector[] = [];const IRenderManagerService = createIdentifier<TestRenderManagerService>('engine-render.render-manager.service');interface IEditorRecord {@@ -316,12 +319,6 @@ class TestRenderManagerService {dispose(): void {}}-class TestLocaleService {- t(key: string) {- return key;- }-}-class TestShortcutService {readonly shortcutChanged$ = new Subject<void>();@@ -394,12 +391,13 @@ const DeleteRightCommand: ICommand = {function createEditorTestBed() {const injector = new Injector();+ testInjectors.push(injector);const dependencies: Dependency[] = [[ICommandService, { useClass: CommandService }],[ILogService, { useClass: DesktopLogService }],[IContextService, { useClass: ContextService }],[IConfigService, { useClass: ConfigService }],- [LocaleService, { useClass: TestLocaleService as never }],+ [LocaleService],[IEditorService, { useClass: TestEditorService as never }],[IRenderManagerService, { useClass: TestRenderManagerService as never }],[IShortcutService, { useClass: TestShortcutService as never }],@@ -410,6 +408,10 @@ function createEditorTestBed() {dependencies.forEach((dependency) => injector.add(dependency));injector.get(ILogService).setLogLevel(LogLevel.SILENT);+ const localeService = injector.get(LocaleService);+ localeService.load({ [LocaleType.EN_US]: enUS });+ localeService.setLocale(LocaleType.EN_US);+ localeService.setDirection('ltr');const commandService = injector.get(ICommandService);[SetActiveCommentOperation, BreakLineCommand, DeleteLeftCommand, DeleteRightCommand]@@ -464,6 +466,7 @@ describe('ThreadCommentEditor', () => {act(() => root!.unmount());}container?.remove();+ testInjectors.splice(0).forEach((injector) => injector.dispose());root = undefined;container = undefined;});diff --git a/packages/ui/src/__tests__/mobile-plugin.spec.ts b/packages/ui/src/__tests__/mobile-plugin.spec.tsnew file mode 100644index 0000000000..2062a3efc0--- /dev/null+++ b/packages/ui/src/__tests__/mobile-plugin.spec.ts@@ -0,0 +1,44 @@+/**+ * 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 { ConfigService, ContextService, IConfigService, IContextService, Injector } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { MOBILE_UI_MODE } from '../const';+import { UniverMobileUIPlugin } from '../mobile-plugin';++describe('UniverMobileUIPlugin', () => {+ it('exposes mobile interaction mode to consumers without changing another runtime', () => {+ const injector = new Injector([+ [IConfigService, { useClass: ConfigService }],+ [IContextService, { useClass: ContextService }],+ [UniverMobileUIPlugin, {+ useFactory: (injector: Injector) => injector.createInstance(UniverMobileUIPlugin, {}),+ deps: [Injector],+ }],+ ]);+ const peerInjector = new Injector([[IContextService, { useClass: ContextService }]]);+ try {+ const contextService = injector.get(IContextService);+ expect(contextService.getContextValue(MOBILE_UI_MODE)).toBeFalsy();+ injector.get(UniverMobileUIPlugin);+ expect(contextService.getContextValue(MOBILE_UI_MODE)).toBe(true);+ expect(peerInjector.get(IContextService).getContextValue(MOBILE_UI_MODE)).toBeFalsy();+ } finally {+ injector.dispose();+ peerInjector.dispose();+ }+ });+});diff --git a/packages/ui/src/const.ts b/packages/ui/src/const.tsindex 5846c3175f..f81f4071a2 100644--- a/packages/ui/src/const.ts+++ b/packages/ui/src/const.ts@@ -18,3 +18,5 @@* @ignore*/export const UNI_DISABLE_CHANGING_FOCUS_KEY = 'UNI_DISABLE_CHANGING_FOCUS';++export const MOBILE_UI_MODE = 'MOBILE_UI_MODE';diff --git a/packages/ui/src/controllers/__tests__/shared-shortcut.controller.spec.ts b/packages/ui/src/controllers/__tests__/shared-shortcut.controller.spec.tsindex 8faa6d4598..20fc3fca47 100644--- a/packages/ui/src/controllers/__tests__/shared-shortcut.controller.spec.ts+++ b/packages/ui/src/controllers/__tests__/shared-shortcut.controller.spec.ts@@ -14,9 +14,33 @@* limitations under the License.*/-import type { IContextService } from '@univerjs/core';-import { EDITOR_ACTIVATED, FOCUSING_FX_BAR_EDITOR, FOCUSING_UNIVER_EDITOR } from '@univerjs/core';-import { describe, expect, it, vi } from 'vitest';+/**+ * @vitest-environment jsdom+ */++import {+ CommandService,+ ConfigService,+ ContextService,+ DesktopLogService,+ EDITOR_ACTIVATED,+ FOCUSING_FX_BAR_EDITOR,+ FOCUSING_UNIVER_EDITOR,+ ICommandService,+ IConfigService,+ IContextService,+ ILogService,+ Injector,+ RedoCommand,+ UndoCommand,+} from '@univerjs/core';+import { afterEach, describe, expect, it } from 'vitest';+import { ToggleFullscreenOperation } from '../../commands/operations/toggle-fullscreen.operation';+import { CopyCommand } from '../../services/clipboard/clipboard.command';+import { IPlatformService } from '../../services/platform/platform.service';+import { IUIRuntimeScopeService, UIRuntimeScopeService } from '../../services/runtime-scope/ui-runtime-scope.service';+import { KeyCode } from '../../services/shortcut/keycode';+import { IShortcutService, ShortcutService } from '../../services/shortcut/shortcut.service';import {CopyShortcutItem,CutShortcutItem,@@ -26,16 +50,53 @@ import {UndoShortcutItem,} from '../shared-shortcut.controller';-function createContext(values: Record<string, boolean>): IContextService {+const injectors: Injector[] = [];++afterEach(() => {+ injectors.splice(0).forEach((injector) => injector.dispose());+ document.body.replaceChildren();+});++function createInjector(): Injector {+ const injector = new Injector();+ injectors.push(injector);+ injector.add([IContextService, { useClass: ContextService }]);+ return injector;+}++function createContextService(values: Record<string, boolean>): IContextService {+ const context = createInjector().get(IContextService);+ Object.entries(values).forEach(([key, value]) => context.setContextValue(key, value));+ return context;+}++function createControllerTestBed(platform: 'mac' | 'windows' | 'linux') {+ const injector = createInjector();+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IPlatformService, { useValue: {+ isMac: platform === 'mac',+ isWindows: platform === 'windows',+ isLinux: platform === 'linux',+ } }]);+ injector.add([IUIRuntimeScopeService, { useClass: UIRuntimeScopeService }]);+ injector.add([IShortcutService, { useClass: ShortcutService }]);+ injector.add([SharedController]);+ const context = injector.get(IContextService);+ context.setContextValue(FOCUSING_UNIVER_EDITOR, true);return {- getContextValue: (key: string) => values[key] ?? false,- } as unknown as IContextService;+ controller: injector.get(SharedController),+ commandService: injector.get(ICommandService),+ shortcutService: injector.get(IShortcutService),+ context,+ };}describe('shared shortcut items', () => {it('should require editor focus for copy/cut and never trigger display-only paste', () => {- const focused = createContext({ [FOCUSING_UNIVER_EDITOR]: true });- const notFocused = createContext({ [FOCUSING_UNIVER_EDITOR]: false });+ const focused = createContextService({ [FOCUSING_UNIVER_EDITOR]: true });+ const notFocused = createContextService({ [FOCUSING_UNIVER_EDITOR]: false });expect(CopyShortcutItem.preconditions!(focused)).toBe(true);expect(CopyShortcutItem.preconditions!(notFocused)).toBe(false);@@ -45,17 +106,17 @@ describe('shared shortcut items', () => {});it('should block undo/redo when editor or fx bar is activated', () => {- const allowed = createContext({+ const allowed = createContextService({[FOCUSING_UNIVER_EDITOR]: true,[EDITOR_ACTIVATED]: false,[FOCUSING_FX_BAR_EDITOR]: false,});- const blockedByEditor = createContext({+ const blockedByEditor = createContextService({[FOCUSING_UNIVER_EDITOR]: true,[EDITOR_ACTIVATED]: true,[FOCUSING_FX_BAR_EDITOR]: false,});- const blockedByFxBar = createContext({+ const blockedByFxBar = createContextService({[FOCUSING_UNIVER_EDITOR]: true,[EDITOR_ACTIVATED]: false,[FOCUSING_FX_BAR_EDITOR]: true,@@ -69,27 +130,102 @@ describe('shared shortcut items', () => {});describe('SharedController', () => {- it('should register clipboard commands and shared shortcuts on initialize', () => {- const registerMultipleCommand = vi.fn(() => ({ dispose: vi.fn() }));- const registerCommand = vi.fn(() => ({ dispose: vi.fn() }));- const registerShortcut = vi.fn(() => ({ dispose: vi.fn() }));-- const commandService = {- registerCommand,- registerMultipleCommand,- };- const shortcutService = {- registerShortcut,- };-- const controller = new SharedController(shortcutService as any, commandService as any);-- expect(registerMultipleCommand).toHaveBeenCalledTimes(3);- expect(registerCommand).toHaveBeenCalledWith(expect.objectContaining({- id: 'base-ui.operation.toggle-fullscreen',- }));- expect(registerShortcut).toHaveBeenCalledTimes(5);+ it.each((['mac', 'windows', 'linux'] as const).flatMap((platform) => [+ { platform, compact: false },+ { platform, compact: true },+ ]))('routes history from a focused command selector on $platform (compact: $compact)', ({ platform, compact }) => {+ const { controller, shortcutService, context } = createControllerTestBed(platform);+ context.setContextValue(FOCUSING_UNIVER_EDITOR, false);+ const container = document.createElement('div');+ const trigger = document.createElement(compact ? 'button' : 'div');+ if (compact) {+ container.setAttribute('data-embed-floating-menu', 'true');+ } else {+ trigger.dataset.uCommand = 'sheet.command.set-horizontal-text-align';+ trigger.setAttribute('role', 'button');+ }+ trigger.tabIndex = 0;+ container.appendChild(trigger);+ document.body.appendChild(container);+ trigger.focus();+ const undo = new KeyboardEvent('history-test', {+ keyCode: KeyCode.Z,+ metaKey: platform === 'mac',+ ctrlKey: platform !== 'mac',+ });+ const redo = new KeyboardEvent('history-test', {+ keyCode: platform === 'mac' ? KeyCode.Z : KeyCode.Y,+ shiftKey: platform === 'mac',+ metaKey: platform === 'mac',+ ctrlKey: platform !== 'mac',+ });+ trigger.dispatchEvent(undo);+ trigger.dispatchEvent(redo);+ expect(shortcutService.dispatch(undo)?.id).toBe(UndoCommand.id);+ expect(shortcutService.dispatch(redo)?.id).toBe(RedoCommand.id);++ for (const key of [EDITOR_ACTIVATED, FOCUSING_FX_BAR_EDITOR]) {+ context.setContextValue(key, true);+ expect(shortcutService.dispatch(undo)).toBeUndefined();+ expect(shortcutService.dispatch(redo)).toBeUndefined();+ context.setContextValue(key, false);+ }+ const input = document.createElement('input');+ trigger.appendChild(input);+ input.focus();+ input.dispatchEvent(undo);+ input.dispatchEvent(redo);+ expect(shortcutService.dispatch(undo)).toBeUndefined();+ expect(shortcutService.dispatch(redo)).toBeUndefined();+ trigger.focus();+ trigger.dispatchEvent(undo);+ trigger.blur();+ expect(shortcutService.dispatch(undo)).toBeUndefined();+ trigger.focus();+ trigger.removeAttribute('data-u-command');+ container.removeAttribute('data-embed-floating-menu');+ expect(shortcutService.dispatch(undo)).toBeUndefined();+ if (compact) {+ container.setAttribute('data-embed-floating-menu', 'true');+ } else {+ trigger.dataset.uCommand = 'sheet.command.set-horizontal-text-align';+ }+ controller.dispose();+ expect(shortcutService.dispatch(undo)).toBeUndefined();+ });++ it('registers working clipboard/history shortcuts and releases its registrations', () => {+ const { controller, commandService, shortcutService } = createControllerTestBed('windows');+ const copy = new KeyboardEvent('keydown', { keyCode: KeyCode.C, ctrlKey: true });+ const undo = new KeyboardEvent('keydown', { keyCode: KeyCode.Z, ctrlKey: true });+ expect(commandService.hasCommand(CopyCommand.id)).toBe(true);+ expect(commandService.hasCommand(ToggleFullscreenOperation.id)).toBe(true);+ expect(shortcutService.dispatch(copy)?.id).toBe(CopyCommand.id);+ expect(shortcutService.dispatch(undo)?.id).toBe(UndoCommand.id);+ controller.dispose();+ expect(commandService.hasCommand(CopyCommand.id)).toBe(false);+ expect(commandService.hasCommand(ToggleFullscreenOperation.id)).toBe(false);+ expect(shortcutService.dispatch(copy)).toBeUndefined();+ expect(shortcutService.dispatch(undo)).toBeUndefined();+ });++ it.each(['mac', 'windows', 'linux'] as const)('preserves redo bindings and editor isolation on %s', (platform) => {+ const { controller, shortcutService, context } = createControllerTestBed(platform);+ const modifier = { metaKey: platform === 'mac', ctrlKey: platform !== 'mac' };+ const legacyRedo = new KeyboardEvent('keydown', { ...modifier, keyCode: KeyCode.Y });+ const macRedo = new KeyboardEvent('keydown', { ...modifier, shiftKey: true, keyCode: KeyCode.Z });+ expect(shortcutService.dispatch(legacyRedo)?.id).toBe(RedoCommand.id);+ expect(shortcutService.dispatch(macRedo)?.id).toBe(platform === 'mac' ? RedoCommand.id : undefined);++ for (const editorContext of [EDITOR_ACTIVATED, FOCUSING_FX_BAR_EDITOR]) {+ context.setContextValue(editorContext, true);+ expect(shortcutService.dispatch(legacyRedo)).toBeUndefined();+ expect(shortcutService.dispatch(macRedo)).toBeUndefined();+ context.setContextValue(editorContext, false);+ }controller.dispose();+ expect(shortcutService.dispatch(legacyRedo)).toBeUndefined();+ expect(shortcutService.dispatch(macRedo)).toBeUndefined();});});diff --git a/packages/ui/src/controllers/shared-shortcut.controller.ts b/packages/ui/src/controllers/shared-shortcut.controller.tsindex 5b6ef65561..c4946cb625 100644--- a/packages/ui/src/controllers/shared-shortcut.controller.ts+++ b/packages/ui/src/controllers/shared-shortcut.controller.ts@@ -75,16 +75,6 @@ export const OnlyDisplayPasteShortcutItem: IShortcutItem = {preconditions: () => false,};-// For compatibility issues, paste from the shortcut should always go with the native paste event,-// see #1404.-// export const PasteShortcutItem: IShortcutItem = {-// id: PasteCommand.id,-// description: 'ui.shortcut.paste',-// group: '1_common-edit',-// binding: KeyCode.V | MetaKeys.CTRL_COMMAND,-// preconditions: supportClipboardAPI,-// };-export const UndoShortcutItem: IShortcutItem = {id: UndoCommand.id,description: 'ui.shortcut.undo',@@ -103,6 +93,12 @@ export const RedoShortcutItem: IShortcutItem = {preconditions: whenEditorFocusedButNotCellEditor,};+const RedoMacShortcutItem: IShortcutItem = {+ ...RedoShortcutItem,+ binding: undefined,+ mac: KeyCode.Z | MetaKeys.CTRL_COMMAND | MetaKeys.SHIFT,+};+/*** Define shared UI behavior across Univer business. Including undo / redo and clipboard operations.*/@@ -129,7 +125,24 @@ export class SharedController extends Disposable {}private _registerShortcuts(): void {- const shortcutItems = [UndoShortcutItem, RedoShortcutItem];+ const shortcutItems = [UndoShortcutItem, RedoShortcutItem, RedoMacShortcutItem];+ for (const shortcut of shortcutItems) {+ // Keyboard menu dismissal restores its command trigger, not the editor focus context.+ this.disposeWithMe(this._shortcutService.registerShortcut({+ ...shortcut,+ eventPreconditions: (event) => {+ const target = event.target;+ return target instanceof HTMLElement &&+ target === target.ownerDocument.activeElement &&+ !target.isContentEditable &&+ target.matches('button[data-u-command], [data-u-command][role="button"], [data-embed-floating-menu="true"] button');+ },+ preconditions: (contextService) => !(+ contextService.getContextValue(EDITOR_ACTIVATED) ||+ contextService.getContextValue(FOCUSING_FX_BAR_EDITOR)+ ),+ }));+ }shortcutItems.push(CutShortcutItem, CopyShortcutItem, OnlyDisplayPasteShortcutItem);shortcutItems.forEach((shortcut) => this.disposeWithMe(this._shortcutService.registerShortcut(shortcut)));diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.tsindex 0fc1323a65..82d443e9f7 100644--- a/packages/ui/src/index.ts+++ b/packages/ui/src/index.ts@@ -24,7 +24,7 @@ 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 { UNI_DISABLE_CHANGING_FOCUS_KEY } from './const';+export { MOBILE_UI_MODE, UNI_DISABLE_CHANGING_FOCUS_KEY } from './const';export { ErrorController } from './controllers/error/error.controller';export {CopyShortcutItem,diff --git a/packages/ui/src/locale/ar-SA.ts b/packages/ui/src/locale/ar-SA.tsindex 4e08469365..62d9187f83 100644--- a/packages/ui/src/locale/ar-SA.ts+++ b/packages/ui/src/locale/ar-SA.ts@@ -19,6 +19,13 @@ import emojiLocale from './emoji-locale/ar-SA.generated';const locale: typeof enUS = {ui: {+ accessibility: {+ menu: 'القائمة',+ zoom: 'التكبير والتصغير',+ zoomIn: 'تكبير',+ zoomOut: 'تصغير',+ resetZoom: 'إعادة ضبط التكبير',+ },objectPermission: {operationDenied: 'هذا المحتوى محمي. لا يُسمح بهذا الإجراء.',remove: 'إزالة الحماية',diff --git a/packages/ui/src/locale/ca-ES.ts b/packages/ui/src/locale/ca-ES.tsindex aefe250284..ecbec08ebf 100644--- a/packages/ui/src/locale/ca-ES.ts+++ b/packages/ui/src/locale/ca-ES.ts@@ -19,6 +19,13 @@ import emojiLocale from './emoji-locale/ca-ES.generated';const locale: typeof enUS = {ui: {+ accessibility: {+ menu: 'Menú',+ zoom: 'Zoom',+ zoomIn: 'Apropa',+ zoomOut: 'Allunya',+ resetZoom: 'Restableix el zoom',+ },objectPermission: {operationDenied: 'Aquest contingut està protegit. No es pot fer aquesta acció.',remove: 'Elimina la protecció',diff --git a/packages/ui/src/locale/de-DE.ts b/packages/ui/src/locale/de-DE.tsindex 9eeb15ec88..98565856e3 100644--- a/packages/ui/src/locale/de-DE.ts+++ b/packages/ui/src/locale/de-DE.ts@@ -19,6 +19,13 @@ import emojiLocale from './emoji-locale/de-DE.generated';const locale: typeof enUS = {ui: {+ accessibility: {+ menu: 'Menü',+ zoom: 'Zoom',+ zoomIn: 'Vergrößern',+ zoomOut: 'Verkleinern',+ resetZoom: 'Zoom zurücksetzen',+ },objectPermission: {operationDenied: 'Dieser Inhalt ist geschützt. Diese Aktion ist nicht erlaubt.',remove: 'Schutz entfernen',diff --git a/packages/ui/src/locale/en-US.ts b/packages/ui/src/locale/en-US.tsindex 9c21801d6e..6e9de1eac5 100644--- a/packages/ui/src/locale/en-US.ts+++ b/packages/ui/src/locale/en-US.ts@@ -18,6 +18,13 @@ import emojiLocale from './emoji-locale/en-US.generated';const locale = {ui: {+ accessibility: {+ menu: 'Menu',+ zoom: 'Zoom',+ zoomIn: 'Zoom in',+ zoomOut: 'Zoom out',+ resetZoom: 'Reset zoom',+ },objectPermission: {operationDenied: 'This content is protected. This action is not allowed.',remove: 'Remove protection',diff --git a/packages/ui/src/locale/es-ES.ts b/packages/ui/src/locale/es-ES.tsindex 125f973d3b..38485236c5 100644--- a/packages/ui/src/locale/es-ES.ts+++ b/packages/ui/src/locale/es-ES.ts@@ -19,6 +19,13 @@ import emojiLocale from './emoji-locale/es-ES.generated';const locale: typeof enUS = {ui: {+ accessibility: {+ menu: 'Menú',+ zoom: 'Zoom',+ zoomIn: 'Acercar',+ zoomOut: 'Alejar',+ resetZoom: 'Restablecer zoom',+ },objectPermission: {operationDenied: 'Este contenido está protegido. No se permite esta acción.',remove: 'Eliminar protección',diff --git a/packages/ui/src/locale/fa-IR.ts b/packages/ui/src/locale/fa-IR.tsindex cf8073cfaa..ad2a4e32ae 100644--- a/packages/ui/src/locale/fa-IR.ts+++ b/packages/ui/src/locale/fa-IR.ts@@ -19,6 +19,13 @@ import emojiLocale from './emoji-locale/fa-IR.generated';const locale: typeof enUS = {ui: {+ accessibility: {+ menu: 'منو',+ zoom: 'بزرگنمایی',+ zoomIn: 'بزرگنمایی',+ zoomOut: 'کوچکنمایی',+ resetZoom: 'بازنشانی بزرگنمایی',+ },objectPermission: {operationDenied: 'این محتوا محافظت شده است. انجام این عملیات مجاز نیست.',remove: 'حذف محافظت',diff --git a/packages/ui/src/locale/fr-FR.ts b/packages/ui/src/locale/fr-FR.tsindex 8eb943275e..905fa30d52 100644--- a/packages/ui/src/locale/fr-FR.ts+++ b/packages/ui/src/locale/fr-FR.ts@@ -19,6 +19,13 @@ import emojiLocale from './emoji-locale/fr-FR.generated';const locale: typeof enUS = {ui: {+ accessibility: {+ menu: 'Menu',+ zoom: 'Zoom',+ zoomIn: 'Zoom avant',+ zoomOut: 'Zoom arrière',+ resetZoom: 'Réinitialiser le zoom',+ },objectPermission: {operationDenied: 'Ce contenu est protégé. Cette action est interdite.',remove: 'Supprimer la protection',diff --git a/packages/ui/src/locale/id-ID.ts b/packages/ui/src/locale/id-ID.tsindex 34deb28023..8bf7e1439f 100644--- a/packages/ui/src/locale/id-ID.ts+++ b/packages/ui/src/locale/id-ID.ts@@ -19,6 +19,13 @@ import emojiLocale from './emoji-locale/id-ID.generated';const locale: typeof enUS = {ui: {+ accessibility: {+ menu: 'Menu',+ zoom: 'Zoom',+ zoomIn: 'Perbesar',+ zoomOut: 'Perkecil',+ resetZoom: 'Atur ulang zoom',+ },objectPermission: {operationDenied: 'Konten ini dilindungi. Tindakan ini tidak diizinkan.',remove: 'Hapus perlindungan',diff --git a/packages/ui/src/locale/it-IT.ts b/packages/ui/src/locale/it-IT.tsindex dd57a5192e..119dc4d51f 100644--- a/packages/ui/src/locale/it-IT.ts+++ b/packages/ui/src/locale/it-IT.ts@@ -19,6 +19,13 @@ import emojiLocale from './emoji-locale/it-IT.generated';const locale: typeof enUS = {ui: {+ accessibility: {+ menu: 'Menu',+ zoom: 'Zoom',+ zoomIn: 'Ingrandisci',+ zoomOut: 'Riduci',+ resetZoom: 'Reimposta zoom',+ },objectPermission: {operationDenied: 'Questo contenuto è protetto. Questa azione non è consentita.',remove: 'Rimuovi protezione',diff --git a/packages/ui/src/locale/ja-JP.ts b/packages/ui/src/locale/ja-JP.tsindex b81d04fc77..d59dbfeecf 100644--- a/packages/ui/src/locale/ja-JP.ts+++ b/packages/ui/src/locale/ja-JP.ts@@ -19,6 +19,13 @@ import emojiLocale from './emoji-locale/ja-JP.generated';const locale: typeof enUS = {ui: {+ accessibility: {+ menu: 'メニュー',+ zoom: 'ズーム',+ zoomIn: '拡大',+ zoomOut: '縮小',+ resetZoom: 'ズームをリセット',+ },objectPermission: {operationDenied: 'このコンテンツは保護されているため、操作できません。',remove: '保護を削除',diff --git a/packages/ui/src/locale/ko-KR.ts b/packages/ui/src/locale/ko-KR.tsindex de7882815c..a2f593cfde 100644--- a/packages/ui/src/locale/ko-KR.ts+++ b/packages/ui/src/locale/ko-KR.ts@@ -19,6 +19,13 @@ import emojiLocale from './emoji-locale/ko-KR.generated';const locale: typeof enUS = {ui: {+ accessibility: {+ menu: '메뉴',+ zoom: '확대/축소',+ zoomIn: '확대',+ zoomOut: '축소',+ resetZoom: '확대/축소 초기화',+ },objectPermission: {operationDenied: '이 콘텐츠는 보호되어 있어 작업을 수행할 수 없습니다.',remove: '보호 삭제',diff --git a/packages/ui/src/locale/pl-PL.ts b/packages/ui/src/locale/pl-PL.tsindex d6ffc0d172..c84e6411d8 100644--- a/packages/ui/src/locale/pl-PL.ts+++ b/packages/ui/src/locale/pl-PL.ts@@ -19,6 +19,13 @@ import emojiLocale from './emoji-locale/pl-PL.generated';const locale: typeof enUS = {ui: {+ accessibility: {+ menu: 'Menu',+ zoom: 'Powiększenie',+ zoomIn: 'Powiększ',+ zoomOut: 'Pomniejsz',+ resetZoom: 'Resetuj powiększenie',+ },objectPermission: {operationDenied: 'Ta treść jest chroniona. Nie można wykonać tej czynności.',remove: 'Usuń ochronę',diff --git a/packages/ui/src/locale/pt-BR.ts b/packages/ui/src/locale/pt-BR.tsindex d7ec77f6f4..81044a4ca5 100644--- a/packages/ui/src/locale/pt-BR.ts+++ b/packages/ui/src/locale/pt-BR.ts@@ -19,6 +19,13 @@ import emojiLocale from './emoji-locale/pt-BR.generated';const locale: typeof enUS = {ui: {+ accessibility: {+ menu: 'Menu',+ zoom: 'Zoom',+ zoomIn: 'Ampliar',+ zoomOut: 'Reduzir',+ resetZoom: 'Redefinir zoom',+ },objectPermission: {operationDenied: 'Este conteúdo está protegido. Esta ação não é permitida.',remove: 'Remover proteção',diff --git a/packages/ui/src/locale/ru-RU.ts b/packages/ui/src/locale/ru-RU.tsindex c9a8a4b575..9666e3f9c8 100644--- a/packages/ui/src/locale/ru-RU.ts+++ b/packages/ui/src/locale/ru-RU.ts@@ -19,6 +19,13 @@ import emojiLocale from './emoji-locale/ru-RU.generated';const locale: typeof enUS = {ui: {+ accessibility: {+ menu: 'Меню',+ zoom: 'Масштаб',+ zoomIn: 'Увеличить',+ zoomOut: 'Уменьшить',+ resetZoom: 'Сбросить масштаб',+ },objectPermission: {operationDenied: 'Этот контент защищён. Действие недоступно.',remove: 'Удалить защиту',diff --git a/packages/ui/src/locale/sk-SK.ts b/packages/ui/src/locale/sk-SK.tsindex 10ad4b4627..99c819cb85 100644--- a/packages/ui/src/locale/sk-SK.ts+++ b/packages/ui/src/locale/sk-SK.ts@@ -19,6 +19,13 @@ import emojiLocale from './emoji-locale/sk-SK.generated';const locale: typeof enUS = {ui: {+ accessibility: {+ menu: 'Ponuka',+ zoom: 'Priblíženie',+ zoomIn: 'Priblížiť',+ zoomOut: 'Oddialiť',+ resetZoom: 'Obnoviť priblíženie',+ },objectPermission: {operationDenied: 'Tento obsah je chránený. Túto akciu nemožno vykonať.',remove: 'Odstrániť ochranu',diff --git a/packages/ui/src/locale/vi-VN.ts b/packages/ui/src/locale/vi-VN.tsindex d810bfb98a..147872d2ab 100644--- a/packages/ui/src/locale/vi-VN.ts+++ b/packages/ui/src/locale/vi-VN.ts@@ -19,6 +19,13 @@ import emojiLocale from './emoji-locale/vi-VN.generated';const locale: typeof enUS = {ui: {+ accessibility: {+ menu: 'Trình đơn',+ zoom: 'Thu phóng',+ zoomIn: 'Phóng to',+ zoomOut: 'Thu nhỏ',+ resetZoom: 'Đặt lại thu phóng',+ },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ệ',diff --git a/packages/ui/src/locale/zh-CN.ts b/packages/ui/src/locale/zh-CN.tsindex 52a2af3e3d..54e84f33f0 100644--- a/packages/ui/src/locale/zh-CN.ts+++ b/packages/ui/src/locale/zh-CN.ts@@ -19,6 +19,13 @@ import emojiLocale from './emoji-locale/zh-CN.generated';const locale: typeof enUS = {ui: {+ accessibility: {+ menu: '菜单',+ zoom: '缩放',+ zoomIn: '放大',+ zoomOut: '缩小',+ resetZoom: '重置缩放',+ },objectPermission: {operationDenied: '该内容已受保护,无法执行此操作。',remove: '删除保护',diff --git a/packages/ui/src/locale/zh-HK.ts b/packages/ui/src/locale/zh-HK.tsindex c02afb2715..eea7bc5d32 100644--- a/packages/ui/src/locale/zh-HK.ts+++ b/packages/ui/src/locale/zh-HK.ts@@ -19,6 +19,13 @@ import emojiLocale from './emoji-locale/zh-HK.generated';const locale: typeof enUS = {ui: {+ accessibility: {+ menu: '選單',+ zoom: '縮放',+ zoomIn: '放大',+ zoomOut: '縮小',+ resetZoom: '重設縮放',+ },objectPermission: {operationDenied: '此內容已受保護,無法執行此操作。',remove: '刪除保護',diff --git a/packages/ui/src/locale/zh-TW.ts b/packages/ui/src/locale/zh-TW.tsindex 88c9944109..2e974c2296 100644--- a/packages/ui/src/locale/zh-TW.ts+++ b/packages/ui/src/locale/zh-TW.ts@@ -19,6 +19,13 @@ import emojiLocale from './emoji-locale/zh-TW.generated';const locale: typeof enUS = {ui: {+ accessibility: {+ menu: '選單',+ zoom: '縮放',+ zoomIn: '放大',+ zoomOut: '縮小',+ resetZoom: '重設縮放',+ },objectPermission: {operationDenied: '此內容已受保護,無法執行此操作。',remove: '刪除保護',diff --git a/packages/ui/src/mobile-plugin.ts b/packages/ui/src/mobile-plugin.tsindex a155c343e2..f9ee83fab2 100644--- a/packages/ui/src/mobile-plugin.ts+++ b/packages/ui/src/mobile-plugin.ts@@ -36,6 +36,7 @@ import { ComponentManager } from './common/component-manager';import { IconManager } from './common/icon-manager';import { ZIndexManager } from './common/z-index-manager';import { defaultPluginConfig, UI_PLUGIN_CONFIG_KEY } from './config/config';+import { MOBILE_UI_MODE } from './const';import { ErrorController } from './controllers/error/error.controller';import { MobileComponentsController } from './controllers/mobile/components.controller';import { SharedController } from './controllers/shared-shortcut.controller';@@ -109,6 +110,7 @@ export class UniverMobileUIPlugin extends Plugin {if (rest.disableAutoFocus) {this._contextService.setContextValue(DISABLE_AUTO_FOCUS_KEY, true);}+ this._contextService.setContextValue(MOBILE_UI_MODE, true);if (menu) {this._configService.setConfig('menu', menu, { merge: true });}diff --git a/packages/ui/src/services/layout/__tests__/layout.service.spec.ts b/packages/ui/src/services/layout/__tests__/layout.service.spec.tsindex b5424592f3..466a51d2f5 100644--- a/packages/ui/src/services/layout/__tests__/layout.service.spec.ts+++ b/packages/ui/src/services/layout/__tests__/layout.service.spec.ts@@ -136,6 +136,29 @@ describe('DesktopLayoutService', () => {expect(service.rootContainerElement).toBeNull();});+ it('focuses an explicit child without replacing the globally focused host', () => {+ const { injector, service, univerInstanceService } = createService();+ const child = injector.createInstance(TestSlideUnit, 'slide-child');+ univerInstanceService.__addUnit(child);+ const current = univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_SLIDE);+ const focused: string[] = [];+ const registration = service.registerFocusHandler(UniverInstanceType.UNIVER_SLIDE, (unitId) => focused.push(unitId));+ try {+ service.focus('slide-child');+ expect(focused).toEqual(['slide-child']);+ expect(univerInstanceService.getFocusedUnit()?.getUnitId()).toBe('slide-1');+ expect(univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_SLIDE)).toBe(current);++ service.focus('missing-child');+ expect(focused).toEqual(['slide-child']);+ service.focus();+ expect(focused).toEqual(['slide-child', 'slide-1']);+ } finally {+ registration.dispose();+ injector.dispose();+ }+ });+it('rejects duplicate registrations that would make focus ownership ambiguous', () => {const { service } = createService();const root = createElement('app-layout');diff --git a/packages/ui/src/services/layout/layout.service.ts b/packages/ui/src/services/layout/layout.service.tsindex 18ffa05ad9..fa109d7278 100644--- a/packages/ui/src/services/layout/layout.service.ts+++ b/packages/ui/src/services/layout/layout.service.ts@@ -47,8 +47,8 @@ export interface ILayoutService {readonly isFocused: boolean;get rootContainerElement(): Nullable<HTMLElement>;- /** Re-focus the currently focused Univer business instance. */- focus(): void;+ /** Re-focus a specific Univer business instance, or the currently focused one when omitted. */+ focus(unitId?: string): void;/** Register a focus handler to focus on certain type of Univer unit. */registerFocusHandler(type: UniverInstanceType, handler: FocusHandlerFn): IDisposable;@@ -98,8 +98,10 @@ export class DesktopLayoutService extends Disposable implements ILayoutService {return this._rootContainerElement;}- focus(): void {- const currentFocused = this._univerInstanceService.getFocusedUnit();+ focus(unitId?: string): void {+ const currentFocused = unitId === undefined+ ? this._univerInstanceService.getFocusedUnit()+ : this._univerInstanceService.getUnit(unitId);if (!currentFocused) {return;}diff --git a/packages/ui/src/services/shortcut/__tests__/shortcut.service.spec.ts b/packages/ui/src/services/shortcut/__tests__/shortcut.service.spec.tsindex 9cd1c912c2..8bc3698ff5 100644--- a/packages/ui/src/services/shortcut/__tests__/shortcut.service.spec.ts+++ b/packages/ui/src/services/shortcut/__tests__/shortcut.service.spec.ts@@ -18,12 +18,23 @@* @vitest-environment jsdom*/-import { ICommandService, IContextService, Injector } from '@univerjs/core';+import {+ CommandService,+ CommandType,+ ConfigService,+ ContextService,+ DesktopLogService,+ ICommandService,+ IConfigService,+ IContextService,+ ILogService,+ Injector,+} from '@univerjs/core';import { afterEach, describe, expect, it, vi } from 'vitest';import { EMBED_CHILD_UNIT_ID_ATTRIBUTE } from '../../../utils/embed-boundary';import { ILayoutService } from '../../layout/layout.service';-import { IPlatformService } from '../../platform/platform.service';-import { IUIRuntimeScopeService } from '../../runtime-scope/ui-runtime-scope.service';+import { IPlatformService, PlatformService } from '../../platform/platform.service';+import { IUIRuntimeScopeService, UIRuntimeScopeService } from '../../runtime-scope/ui-runtime-scope.service';import { KeyCode, MetaKeys } from '../keycode';import { NativeTextEditorShortcutBehavior, ShortcutService } from '../shortcut.service';@@ -119,6 +130,155 @@ describe('ShortcutService', () => {vi.unstubAllGlobals();});+ it.each([KeyCode.BACKSPACE, KeyCode.DELETE])('keeps toolbar input deletion key %s out of grid shortcuts', (keyCode) => {+ const injector = new Injector([+ [ICommandService, { useClass: CommandService }],+ [IConfigService, { useClass: ConfigService }],+ [IContextService, { useClass: ContextService }],+ [ILogService, { useClass: DesktopLogService }],+ [IPlatformService, { useClass: PlatformService }],+ [IUIRuntimeScopeService, { useClass: UIRuntimeScopeService }],+ [ShortcutService],+ ]);+ const control = document.createElement('div');+ control.dataset.uCommand = 'sheet.command.set-range-fontsize';+ const input = document.createElement('input');+ control.appendChild(input);+ document.body.appendChild(control);+ try {+ const service = injector.get(ShortcutService);+ service.registerShortcut({ id: 'test.grid-delete', binding: keyCode });+ const event = new KeyboardEvent('input-delete-test', { keyCode, cancelable: true });+ input.dispatchEvent(event);+ expect(service.dispatch(event)).toBeUndefined();+ expect(event.defaultPrevented).toBe(false);+ const canvas = document.createElement('canvas');+ const canvasEvent = new KeyboardEvent('input-delete-test', { keyCode });+ canvas.dispatchEvent(canvasEvent);+ expect(service.dispatch(canvasEvent)?.id).toBe('test.grid-delete');+ } finally {+ control.remove();+ injector.dispose();+ }+ });++ it.each([KeyCode.ENTER, KeyCode.SPACE, KeyCode.TAB, KeyCode.ESC, KeyCode.ARROW_DOWN, KeyCode.ARROW_UP, KeyCode.ARROW_LEFT, KeyCode.ARROW_RIGHT, KeyCode.HOME, KeyCode.END])(+ 'yields menu navigation key %s while retaining canvas shortcuts',+ (keyCode) => {+ const injector = new Injector();+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IPlatformService, { useClass: PlatformService }]);+ injector.add([IUIRuntimeScopeService, { useClass: UIRuntimeScopeService }]);+ injector.add([ShortcutService]);+ const container = document.createElement('div');+ document.body.appendChild(container);+ try {+ const service = injector.get(ShortcutService);+ service.registerShortcut({ id: 'test.grid-navigation', binding: keyCode });+ const trigger = document.createElement('div');+ trigger.dataset.uCommand = 'sheet.command.set-horizontal-text-align';+ trigger.setAttribute('role', 'button');+ const menu = document.createElement('div');+ menu.setAttribute('role', 'menu');+ const item = document.createElement('button');+ item.setAttribute('role', 'menuitem');+ menu.appendChild(item);+ const floatingMenu = document.createElement('div');+ floatingMenu.setAttribute('data-embed-floating-menu', 'true');+ const compactTrigger = document.createElement('button');+ floatingMenu.appendChild(compactTrigger);+ const fontControl = document.createElement('div');+ fontControl.dataset.uCommand = 'sheet.command.set-range-font-family';+ const fontInput = document.createElement('input');+ fontControl.appendChild(fontInput);+ container.append(trigger, menu, floatingMenu, fontControl);+ for (const target of [trigger, item, compactTrigger, fontInput]) {+ const event = new KeyboardEvent('navigation-test', { keyCode, cancelable: true });+ target.dispatchEvent(event);+ expect(service.dispatch(event)).toBeUndefined();+ expect(event.defaultPrevented).toBe(false);+ }+ const canvas = document.createElement('canvas');+ container.appendChild(canvas);+ const event = new KeyboardEvent('navigation-test', { keyCode });+ canvas.dispatchEvent(event);+ expect(service.dispatch(event)?.id).toBe('test.grid-navigation');+ } finally {+ container.remove();+ injector.dispose();+ }+ }+ );++ it.each([+ ['Enter', KeyCode.ENTER],+ ['Escape', KeyCode.ESC],+ ['ArrowLeft', KeyCode.ARROW_LEFT],+ ['ArrowRight', KeyCode.ARROW_RIGHT],+ ['Backspace', KeyCode.BACKSPACE],+ ['Tab', KeyCode.TAB],+ ])('yields composing %s to the IME and resumes the shortcut after composition', async (key, keyCode) => {+ const injector = new Injector();+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IPlatformService, { useClass: PlatformService }]);+ injector.add([IUIRuntimeScopeService, { useClass: UIRuntimeScopeService }]);+ injector.add([ShortcutService]);+ try {+ const service = injector.get(ShortcutService);+ const commandService = injector.get(ICommandService);+ let executionCount = 0;+ commandService.registerCommand({+ id: 'test.ime-shortcut',+ type: CommandType.OPERATION,+ handler: () => {+ executionCount += 1;+ return true;+ },+ });+ service.registerShortcut({+ id: 'test.ime-shortcut',+ binding: keyCode,+ nativeTextEditorBehavior: NativeTextEditorShortcutBehavior.OVERRIDE_NATIVE,+ });+ const composingEvent = new KeyboardEvent('keydown', {+ bubbles: true,+ cancelable: true,+ isComposing: true,+ key,+ keyCode,+ });+ expect(service.dispatch(composingEvent)).toBeUndefined();+ window.dispatchEvent(composingEvent);+ expect(executionCount).toBe(0);+ expect(composingEvent.defaultPrevented).toBe(false);++ // Safari may deliver the IME confirmation key after compositionend with keyCode 229.+ const confirmationEvent = new KeyboardEvent('keydown', {+ bubbles: true,+ cancelable: true,+ isComposing: false,+ key,+ keyCode: 229,+ });+ window.dispatchEvent(confirmationEvent);+ expect(executionCount).toBe(0);+ expect(confirmationEvent.defaultPrevented).toBe(false);++ const regularEvent = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, key, keyCode });+ window.dispatchEvent(regularEvent);+ await expect.poll(() => executionCount).toBe(1);+ expect(regularEvent.defaultPrevented).toBe(true);+ } finally {+ injector.dispose();+ }+ });+it('should register and unregister shortcuts', () => {const { service } = createService();const changed = vi.fn();@@ -196,8 +356,12 @@ describe('ShortcutService', () => {binding: KeyCode.A | MetaKeys.CTRL_COMMAND,});const escapedDisposable = escapedService.forceEscape();+ const nestedEscapedDisposable = escapedService.forceEscape();expect(escapedService.dispatch(createKeyboardEvent(KeyCode.A, { ctrlKey: true }))).toBeUndefined();escapedDisposable.dispose();+ expect(escapedService.dispatch(createKeyboardEvent(KeyCode.A, { ctrlKey: true }))).toBeUndefined();+ nestedEscapedDisposable.dispose();+ expect(escapedService.dispatch(createKeyboardEvent(KeyCode.A, { ctrlKey: true }))?.id).toBe('cmd.esc');escapedService.dispose();const disabledService = createService().service;diff --git a/packages/ui/src/services/shortcut/shortcut.service.ts b/packages/ui/src/services/shortcut/shortcut.service.tsindex 2fe9e6dd10..765bc75938 100644--- a/packages/ui/src/services/shortcut/shortcut.service.ts+++ b/packages/ui/src/services/shortcut/shortcut.service.ts@@ -25,6 +25,19 @@ import { IPlatformService } from '../platform/platform.service';import { IUIRuntimeScopeService } from '../runtime-scope/ui-runtime-scope.service';import { KeyCode, KeyCodeToChar, MetaKeys } from './keycode';+const MENU_NAVIGATION_KEYS = new Set([+ KeyCode.ENTER,+ KeyCode.SPACE,+ KeyCode.TAB,+ KeyCode.ESC,+ KeyCode.ARROW_DOWN,+ KeyCode.ARROW_UP,+ KeyCode.ARROW_LEFT,+ KeyCode.ARROW_RIGHT,+ KeyCode.HOME,+ KeyCode.END,+]);+/*** Defines whether a Univer shortcut should yield to the browser's native behavior* when the keyboard event originates from an editable text element.@@ -176,7 +189,7 @@ export class ShortcutService extends Disposable implements IShortcutService {private readonly _shortcutChanged$ = new Subject<void>();readonly shortcutChanged$ = this._shortcutChanged$.asObservable();- private _forceEscaped = false;+ private _forceEscapeCount = 0;private _forceDisabled = false;@@ -277,8 +290,10 @@ export class ShortcutService extends Disposable implements IShortcutService {}forceEscape(): IDisposable {- this._forceEscaped = true;- return toDisposable(() => (this._forceEscaped = false));+ this._forceEscapeCount += 1;+ return toDisposable(() => {+ this._forceEscapeCount = Math.max(0, this._forceEscapeCount - 1);+ });}forceDisable(): IDisposable {@@ -298,12 +313,34 @@ export class ShortcutService extends Disposable implements IShortcutService {}dispatch(e: KeyboardEvent): IShortcutItem<object> | undefined {+ // The capture listener runs before the editor can handle IME candidate keys.+ if (e.isComposing) {+ return;+ }++ if (+ (e.keyCode === KeyCode.BACKSPACE || e.keyCode === KeyCode.DELETE) &&+ e.target instanceof HTMLInputElement && e.target.closest('[data-u-command]')+ ) {+ return;+ }++ // Scoped editor context can remain active while a portalled menu owns DOM focus.+ if (+ !e.ctrlKey && !e.metaKey && !e.altKey && MENU_NAVIGATION_KEYS.has(e.keyCode) &&+ e.target instanceof HTMLElement &&+ (e.target.matches('button[data-u-command], [data-u-command][role="button"], [data-embed-floating-menu="true"] button, [data-u-command] input') ||+ e.target.closest('[role="menu"]'))+ ) {+ return;+ }+// Should get the container element of the Univer instance and see if// the event target is a descendant of the container element.// Also we should check through escape list and force catching list.// if the target is not focused on the univer instance we should ignore the keyboard event.// Maybe the user has forcibly disabled the shortcut keys, and the shortcut keys should not be processed at this time.- if (this._forceEscaped || this._forceDisabled) return;+ if (this._forceEscapeCount > 0 || this._forceDisabled) return;if (this._layoutService &&diff --git a/packages/ui/src/views/components/context-menu/AnchoredContextMenu.tsx b/packages/ui/src/views/components/context-menu/AnchoredContextMenu.tsxindex e573165373..8a1bd8c905 100644--- a/packages/ui/src/views/components/context-menu/AnchoredContextMenu.tsx+++ b/packages/ui/src/views/components/context-menu/AnchoredContextMenu.tsx@@ -191,6 +191,7 @@ export function AnchoredContextMenu(props: IAnchoredContextMenuProps) {<section ref={contentRef}>{menuType && (<ContextMenuPanel+ key={menuSessionVersionRef.current}menuType={menuType}autoFocus={autoFocus}menuManagerService={menuManagerService}diff --git a/packages/ui/src/views/components/context-menu/__tests__/AnchoredContextMenu.spec.tsx b/packages/ui/src/views/components/context-menu/__tests__/AnchoredContextMenu.spec.tsxindex b3c1ae8aa8..f77a05fd14 100644--- a/packages/ui/src/views/components/context-menu/__tests__/AnchoredContextMenu.spec.tsx+++ b/packages/ui/src/views/components/context-menu/__tests__/AnchoredContextMenu.spec.tsx@@ -16,6 +16,7 @@import type { PropsWithChildren } from 'react';import { cleanup, fireEvent, render, screen } from '@testing-library/react';+import { useState } from 'react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { AnchoredContextMenu } from '../AnchoredContextMenu';@@ -41,11 +42,16 @@ vi.mock('../../../../utils/di', () => ({vi.mock('../ContextMenuPanel', () => ({CONTEXT_MENU_SUBMENU_PORTAL_ATTR: 'data-u-context-menu-submenu',- ContextMenuPanel: (props: { autoFocus?: boolean; onCancel?: () => void }) => {+ ContextMenuPanel: (props: {+ autoFocus?: boolean;+ onCancel?: () => void;+ onOptionSelect?: (option: { label: string; value: string }) => void;+ }) => {+ const [value, setValue] = useState('2');panelProps(props);return (- <button- type="button"+ <div+ tabIndex={-1}onKeyDown={(event) => {if (event.key === 'Escape') {event.stopPropagation();@@ -53,8 +59,18 @@ vi.mock('../ContextMenuPanel', () => ({}}}>- Context menu item- </button>+ <button+ type="button"+ aria-label="Context menu item"+ onClick={() => props.onOptionSelect?.({ label: 'test.command.menu-value', value })}+ >+ <input+ aria-label="Menu value"+ value={value}+ onChange={(event) => setValue(event.target.value)}+ />+ </button>+ </div>);},}));@@ -203,4 +219,72 @@ describe('AnchoredContextMenu', () => {expect(panelProps).toHaveBeenCalledWith(expect.objectContaining({ autoFocus: true }));});++ it('keeps a draft during anchor movement but resets it when the menu reopens', () => {+ const selections: Array<{ label: string; value: string }> = [];+ const renderMenu = (visible: boolean, left: number) => (+ <AnchoredContextMenu+ hostId="desktop"+ visible={visible}+ anchorRect={{ left, top: 10, bottom: 10 }}+ menuType="drawing"+ onRequestClose={() => {}}+ onOptionSelect={(option) => selections.push(option as { label: string; value: string })}+ />+ );+ const view = render(renderMenu(true, 10));+ const input = screen.getByRole('textbox', { name: 'Menu value' }) as HTMLInputElement;+ input.focus();+ fireEvent.change(input, { target: { value: '3' } });++ view.rerender(renderMenu(true, 20));++ expect(screen.getByRole('textbox', { name: 'Menu value' })).toBe(input);+ expect(document.activeElement).toBe(input);+ expect(input.value).toBe('3');+ expect(selections).toEqual([]);++ view.rerender(renderMenu(false, 20));+ view.rerender(renderMenu(true, 20));+ const reopenedInput = screen.getByRole('textbox', { name: 'Menu value' }) as HTMLInputElement;+ expect(reopenedInput.value).toBe('2');+ fireEvent.click(reopenedInput.closest('button')!);+ expect(selections).toEqual([{ label: 'test.command.menu-value', value: '2' }]);+ });++ it.each(['container', 'button', 'input'] as const)(+ 'requests closure once when Escape comes from the %s',+ (targetKind) => {+ const close = vi.fn();+ const selection = vi.fn();+ const view = render(+ <AnchoredContextMenu+ hostId="desktop"+ visible+ anchorRect={{ left: 10, top: 10, bottom: 10 }}+ menuType="drawing"+ onRequestClose={close}+ onOptionSelect={selection}+ />+ );+ const input = screen.getByRole('textbox', { name: 'Menu value' });+ const targets = {+ input,+ button: input.closest('button'),+ container: input.closest('[tabindex="-1"]'),+ };+ const target = targets[targetKind];+ expect(target).not.toBeNull();++ fireEvent.keyDown(target!, { key: 'Escape', bubbles: true });++ expect(close).toHaveBeenCalledOnce();+ expect(selection).not.toHaveBeenCalled();+ expect((input as HTMLInputElement).value).toBe('2');++ view.unmount();+ fireEvent.keyDown(document.body, { key: 'Escape', bubbles: true });+ expect(close).toHaveBeenCalledOnce();+ }+ );});diff --git a/packages/ui/src/views/components/dom/FloatDom.tsx b/packages/ui/src/views/components/dom/FloatDom.tsxindex 64fa1aae8c..b93e944eb6 100644--- a/packages/ui/src/views/components/dom/FloatDom.tsx+++ b/packages/ui/src/views/components/dom/FloatDom.tsx@@ -19,7 +19,7 @@ import type { IFloatDom } from '../../../services/dom/canvas-dom-layer.service';import { DocumentDataModel, IUniverInstanceService } from '@univerjs/core';import { memo, useEffect, useMemo, useRef } from 'react';import { first } from 'rxjs';-import { ComponentManager } from '../../../common';+import { ComponentManager } from '../../../common/component-manager';import { CanvasFloatDomService, shouldForwardFloatDomEvents, shouldRenderFloatDomLayer } from '../../../services/dom/canvas-dom-layer.service';import { useDependency, useObservable } from '../../../utils/di';import { resolveFloatDomLayout } from './float-dom-layout';@@ -129,7 +129,10 @@ function FloatDomSingleContent(props: { layer: IFloatDom; id: string; Component?}}onPointerDown={(e) => {if (forwardEvents) {- e.currentTarget.setPointerCapture?.(e.pointerId);+ // Keep pointerup on the original descendant so its activation handler still runs.+ if (e.target instanceof Element) {+ e.target.setPointerCapture?.(e.pointerId);+ }layer.onPointerDown(e.nativeEvent);}}}@@ -141,8 +144,8 @@ function FloatDomSingleContent(props: { layer: IFloatDom; id: string; Component?try {layer.onPointerUp(e.nativeEvent);} finally {- if (e.currentTarget.hasPointerCapture?.(e.pointerId)) {- e.currentTarget.releasePointerCapture?.(e.pointerId);+ if (e.target instanceof Element && e.target.hasPointerCapture?.(e.pointerId)) {+ e.target.releasePointerCapture?.(e.pointerId);}}}}@@ -155,8 +158,8 @@ function FloatDomSingleContent(props: { layer: IFloatDom; id: string; Component?// The layer forwards the original event type, so the canvas receives pointercancel rather than pointerup.layer.onPointerUp(e.nativeEvent);} finally {- if (e.currentTarget.hasPointerCapture?.(e.pointerId)) {- e.currentTarget.releasePointerCapture?.(e.pointerId);+ if (e.target instanceof Element && e.target.hasPointerCapture?.(e.pointerId)) {+ e.target.releasePointerCapture?.(e.pointerId);}}}}diff --git a/packages/ui/src/views/components/dom/__tests__/FloatDom.spec.tsx b/packages/ui/src/views/components/dom/__tests__/FloatDom.spec.tsxindex 3fb412877c..e2a0b6f994 100644--- a/packages/ui/src/views/components/dom/__tests__/FloatDom.spec.tsx+++ b/packages/ui/src/views/components/dom/__tests__/FloatDom.spec.tsx@@ -180,7 +180,7 @@ describe('FloatDomSingle', () => {expect(onPointerDown).toHaveBeenCalledOnce();});- it('captures forwarded pointers and finishes the canvas gesture when the browser cancels it', async () => {+ it('captures forwarded pointers on the original descendant and finishes cancelled canvas gestures', async () => {const onPointerDown = vi.fn();const onPointerUp = vi.fn();const layer = { ...createFloatDom(), onPointerDown, onPointerUp };@@ -191,7 +191,9 @@ describe('FloatDomSingle', () => {const wrapper = inner.parentElement as HTMLDivElement;const setPointerCapture = vi.fn();const releasePointerCapture = vi.fn();- Object.defineProperties(wrapper, {+ const captureOnWrapper = vi.fn();+ Object.defineProperty(wrapper, 'setPointerCapture', { configurable: true, value: captureOnWrapper });+ Object.defineProperties(inner, {hasPointerCapture: { configurable: true, value: () => true },releasePointerCapture: { configurable: true, value: releasePointerCapture },setPointerCapture: { configurable: true, value: setPointerCapture },@@ -205,6 +207,7 @@ describe('FloatDomSingle', () => {expect(wrapper.style.touchAction).toBe('none');expect(setPointerCapture).toHaveBeenCalledWith(7);expect(setPointerCapture).toHaveBeenCalledWith(8);+ expect(captureOnWrapper).not.toHaveBeenCalled();expect(onPointerDown).toHaveBeenCalledTimes(2);expect(onPointerUp).toHaveBeenCalledWith(expect.objectContaining({ type: 'pointerup' }));expect(onPointerUp).toHaveBeenCalledWith(expect.objectContaining({ type: 'pointercancel' }));diff --git a/packages/ui/src/views/components/ribbon/ToolbarItem.tsx b/packages/ui/src/views/components/ribbon/ToolbarItem.tsxindex 2d5e1aa5c4..8d7d051d5c 100644--- a/packages/ui/src/views/components/ribbon/ToolbarItem.tsx+++ b/packages/ui/src/views/components/ribbon/ToolbarItem.tsx@@ -266,6 +266,13 @@ export const ToolbarItem = forwardRef<ITooltipWrapperRef, IToolbarItemProps>((prconst bId = commandId ?? id;const sId = selectionsCommandId ?? commandId ?? id;const titleToDisplay = grid ? (showLabel ? gridLabel : large ? undefined : title) : title;+ const customLabelName = typeof label === 'string' ? label : label?.name ?? '';+ const hasCustomLabel = Boolean(componentManager.get(customLabelName));+ const selectorAriaLabel = tooltip+ ? localeService.t(tooltip)+ : typeof titleToDisplay === 'string'+ ? localeService.t(titleToDisplay)+ : undefined;function handleSelect(option: IValueOption) {if (disabled) return;@@ -359,6 +366,10 @@ export const ToolbarItem = forwardRef<ITooltipWrapperRef, IToolbarItemProps>((pr><divdata-u-command={id}+ role={hasCustomLabel ? undefined : 'button'}+ tabIndex={hasCustomLabel ? undefined : disabled ? -1 : 0}+ aria-disabled={hasCustomLabel ? undefined : disabled}+ aria-label={hasCustomLabel ? undefined : selectorAriaLabel}className={clsx(toolbarSelectorRootVariants({ disabled, active: activated }), {'univer-box-border univer-h-full univer-min-w-14 univer-flex-col univer-justify-center univer-gap-1 univer-px-1.5 univer-py-1 univer-text-xs [&>svg]:univer-size-8': grid && large,'univer-box-border univer-h-full': grid && !large,@@ -418,6 +429,11 @@ export const ToolbarItem = forwardRef<ITooltipWrapperRef, IToolbarItemProps>((prfunction renderButtonType() {const isCustomComponent = componentManager.get(typeof label === 'string' ? label : label?.name ?? '');+ const buttonAriaLabel = tooltip+ ? localeService.t(tooltip)+ : typeof title === 'string'+ ? localeService.t(title)+ : undefined;const buttonClassName = clsx(grid && !large && `univer-h-full univer-min-w-8[&>svg]:univer-size-4@@ -462,6 +478,7 @@ export const ToolbarItem = forwardRef<ITooltipWrapperRef, IToolbarItemProps>((prreturn (<ToolbarButtondata-u-command={id}+ aria-label={buttonAriaLabel}className={buttonClassName}style={buttonStyle}noIcon={!icon}diff --git a/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx b/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsxindex c25a6b39ed..931ee6f982 100644--- a/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx+++ b/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx@@ -14,9 +14,11 @@* limitations under the License.*/+import type { Workbook } from '@univerjs/core';import type { IDropdownMenuProps, IDropdownProps, ITooltipProps } from '@univerjs/design';import type { ComponentType, ReactNode } from 'react';import type { IMenuItem, IValueOption } from '../../../services/menu/menu';+import { FOCUSING_SHEET, IContextService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';import {clsx,ConfigContext,@@ -36,10 +38,12 @@ import {useRef,useState,} from 'react';-import { combineLatest, map, merge, of, scan, startWith } from 'rxjs';+import { combineLatest, map, merge, of, scan, startWith, switchMap } from 'rxjs';+import { ILayoutService } from '../../../services/layout/layout.service';import { IMenuManagerService } from '../../../services/menu/menu-manager.service';+import { IShortcutService } from '../../../services/shortcut/shortcut.service';import { useDependency, useObservable } from '../../../utils/di';-import { keepInteractionInsideSameEmbedBoundary } from '../../../utils/embed-boundary';+import { getEmbedBoundaryOwner, keepInteractionInsideSameEmbedBoundary } from '../../../utils/embed-boundary';import { CustomLabel } from '../../custom-label/CustomLabel';const TooltipWrapperContext = createContext({@@ -78,7 +82,9 @@ export function ToolbarTooltip(props: IToolbarTooltipProps) {return (<Tooltip{...tooltipProps}- className={clsx('univer-fill-mode-backwards univer-delay-100', tooltipProps.className)}+ className={clsx('univer-fill-mode-backwards univer-delay-100', tooltipProps.className, `+ univer-pointer-events-none+ `)}visible={!popupOpen && tooltipVisible}onVisibleChange={(visible) => {if (!popupOpen) {@@ -286,6 +292,50 @@ export function DropdownMenuWrapper({dropdownMenuComponent?: ComponentType<IDropdownMenuProps>;}) {const { dropdownVisible, setDropdownVisible } = useContext(TooltipWrapperContext);+ const shortcutService = useDependency(IShortcutService);+ const contextService = useDependency(IContextService);+ const instanceService = useDependency(IUniverInstanceService);+ const layoutService = useDependency(ILayoutService);+ const editorFocusRef = useRef<{ element: HTMLElement; owner?: string } | null>(null);+ const sheetTargetRef = useRef<{ unitId: string; sheetId: string; valid: boolean } | null>(null);+ const sheetTarget = sheetTargetRef.current;++ useEffect(() => {+ const target = sheetTargetRef.current;+ if (!dropdownVisible || !target) {+ return undefined;+ }++ const subscription = instanceService.getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET).pipe(+ switchMap((workbook) => workbook+ ? workbook.activeSheet$.pipe(map((sheet) => ({ workbook, sheetId: sheet?.getSheetId() })))+ : of(null))+ ).subscribe((current) => {+ if (current?.workbook.getUnitId() !== target.unitId || current?.sheetId !== target.sheetId) {+ target.valid = false;+ editorFocusRef.current = null;+ setDropdownVisible(false);+ }+ });++ return () => subscription.unsubscribe();+ }, [dropdownVisible, instanceService, setDropdownVisible]);++ useEffect(() => () => {+ if (sheetTargetRef.current) {+ sheetTargetRef.current.valid = false;+ sheetTargetRef.current = null;+ }+ }, []);++ useEffect(() => {+ if (!dropdownVisible) {+ return undefined;+ }++ const shortcutEscape = shortcutService.forceEscape();+ return () => shortcutEscape.dispose();+ }, [dropdownVisible, shortcutService]);useEffect(() => {if (disabled && dropdownVisible) {@@ -331,14 +381,75 @@ export function DropdownMenuWrapper({}, [menuItems, hiddenStates]);function handleVisibleChange(visible: boolean) {+ if (visible) {+ const element = document.activeElement;+ const workbook = contextService.getContextValue(FOCUSING_SHEET)+ ? instanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)+ : null;+ const sheetId = workbook?.getActiveSheet()?.getSheetId();+ if (sheetTargetRef.current) {+ sheetTargetRef.current.valid = false;+ }+ sheetTargetRef.current = workbook && sheetId ? { unitId: workbook.getUnitId(), sheetId, valid: true } : null;+ const owner = getEmbedBoundaryOwner(element);+ editorFocusRef.current = element instanceof HTMLElement && element.dataset.uComp === 'editor'+ ? { element, owner }+ : null;+ }setDropdownVisible(visible);}+ function handleCloseAutoFocus(event: Event) {+ const editorFocus = editorFocusRef.current;+ editorFocusRef.current = null;+ if (sheetTargetRef.current && !sheetTargetRef.current.valid) {+ event.preventDefault();+ const activeElement = document.activeElement;+ const focusInClosingMenu = event.target instanceof HTMLElement && event.target.contains(activeElement);+ if (activeElement === document.body || focusInClosingMenu) {+ layoutService.focus();+ }+ return;+ }+ if (!editorFocus?.element.isConnected || getEmbedBoundaryOwner(editorFocus.element) !== editorFocus.owner) {+ return;+ }++ const activeElement = editorFocus.element.ownerDocument.activeElement;+ const focusInClosingMenu = event.target instanceof HTMLElement && event.target.contains(activeElement);+ if (activeElement !== editorFocus.element.ownerDocument.body && activeElement !== editorFocus.element && !focusInClosingMenu) {+ return;+ }++ event.preventDefault();+ editorFocus.element.focus({ preventScroll: true });+ }++ function handlePointerDownOutside(event: { currentTarget: EventTarget | null; target: EventTarget | null; preventDefault: () => void }) {+ if (editorFocusRef.current && (!editorFocusRef.current.owner || getEmbedBoundaryOwner(event.target) !== editorFocusRef.current.owner)) {+ editorFocusRef.current = null;+ }+ keepInteractionInsideSameEmbedBoundary(event);+ }+function handleEmbedBoundaryFocusOutside(event: { currentTarget: EventTarget | null; target: EventTarget | null; preventDefault: () => void }) {keepInteractionInsideSameEmbedBoundary(event);}function handleOptionSelect(option: IValueOption) {+ const target = sheetTarget;+ if (target && target !== sheetTargetRef.current) {+ return;+ }+ if (target && (+ !target.valid ||+ instanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)?.getUnitId() !== target.unitId ||+ instanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)?.getActiveSheet()?.getSheetId() !== target.sheetId+ )) {+ editorFocusRef.current = null;+ setDropdownVisible(false);+ return;+ }onOptionSelect(option);setDropdownVisible(false);}@@ -443,6 +554,8 @@ export function DropdownMenuWrapper({disabled={disabled}open={dropdownVisible}onOpenChange={handleVisibleChange}+ onCloseAutoFocus={handleCloseAutoFocus}+ onPointerDownOutside={handlePointerDownOutside}onFocusOutside={handleEmbedBoundaryFocusOutside}onInteractOutside={handleEmbedBoundaryFocusOutside}>@@ -494,6 +607,8 @@ export function DropdownMenuWrapper({disabled={disabled}open={dropdownVisible}onOpenChange={handleVisibleChange}+ onCloseAutoFocus={handleCloseAutoFocus}+ onPointerDownOutside={handlePointerDownOutside}onFocusOutside={handleEmbedBoundaryFocusOutside}onInteractOutside={handleEmbedBoundaryFocusOutside}>diff --git a/packages/ui/src/views/components/ribbon/__tests__/ToolbarItem.spec.tsx b/packages/ui/src/views/components/ribbon/__tests__/ToolbarItem.spec.tsxindex 89b59f3863..41cfabeebd 100644--- a/packages/ui/src/views/components/ribbon/__tests__/ToolbarItem.spec.tsx+++ b/packages/ui/src/views/components/ribbon/__tests__/ToolbarItem.spec.tsx@@ -17,7 +17,16 @@import type { ComponentType, ReactElement } from 'react';import type { IIconProps } from '../../../../common/icon-manager';import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react';-import { ICommandService, ILogService, Injector, LocaleService } from '@univerjs/core';+import {+ ContextService,+ ICommandService,+ IContextService,+ ILogService,+ Injector,+ IUniverInstanceService,+ LocaleService,+ UniverInstanceService,+} from '@univerjs/core';import { BehaviorSubject, Subject } from 'rxjs';import { afterEach, describe, expect, it } from 'vitest';import { ComponentManager } from '../../../../common/component-manager';@@ -25,7 +34,9 @@ import { IconManager } from '../../../../common/icon-manager';import { ILayoutService } from '../../../../services/layout/layout.service';import { MenuItemType } from '../../../../services/menu/menu';import { IMenuManagerService } from '../../../../services/menu/menu-manager.service';-import { IShortcutService } from '../../../../services/shortcut/shortcut.service';+import { IPlatformService, PlatformService } from '../../../../services/platform/platform.service';+import { IUIRuntimeScopeService, UIRuntimeScopeService } from '../../../../services/runtime-scope/ui-runtime-scope.service';+import { IShortcutService, ShortcutService } from '../../../../services/shortcut/shortcut.service';import { connectInjector } from '../../../../utils/di';import { ToolbarItem } from '../ToolbarItem';@@ -45,13 +56,9 @@ class TestCommandService {class TestLayoutService {focus(): void {}-}--class TestShortcutService {- readonly shortcutChanged$ = new Subject<void>();- getShortcutDisplayOfCommand(): null {- return null;+ checkElementInCurrentContainers(): boolean {+ return true;}}@@ -67,12 +74,19 @@ class TestLogService {warn(): void {}}+const testInjectors: Injector[] = [];+function renderWithDependencies(element: ReactElement) {const injector = new Injector();+ testInjectors.push(injector);injector.add([LocaleService, { useClass: TestLocaleService as never }]);injector.add([ICommandService, { useClass: TestCommandService as never }]);injector.add([ILayoutService, { useClass: TestLayoutService as never }]);- injector.add([IShortcutService, { useClass: TestShortcutService as never }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ injector.add([IPlatformService, { useClass: PlatformService }]);+ injector.add([IUIRuntimeScopeService, { useClass: UIRuntimeScopeService }]);+ injector.add([IShortcutService, { useClass: ShortcutService }]);injector.add([IMenuManagerService, { useClass: TestMenuManagerService as never }]);injector.add([ILogService, { useClass: TestLogService as never }]);injector.add([ComponentManager]);@@ -94,9 +108,51 @@ function renderWithDependencies(element: ReactElement) {};}-afterEach(cleanup);+afterEach(() => {+ cleanup();+ testInjectors.forEach((injector) => injector.dispose());+ testInjectors.length = 0;+});describe('ToolbarItem', () => {+ it('opens a selector menu from its keyboard-focusable trigger', async () => {+ const { container, findByText } = renderWithDependencies(+ <ToolbarItem+ id="test-keyboard-selector"+ type={MenuItemType.SELECTOR}+ tooltip="Format"+ icon="TestIcon"+ selections={[{ label: 'Format rows', value: 'row' }]}+ />+ );+ const trigger = container.querySelector('.univer-toolbar-selector-root') as HTMLElement;++ expect(trigger.getAttribute('role')).toBe('button');+ expect(trigger.getAttribute('tabindex')).toBe('0');+ expect(trigger.getAttribute('aria-label')).toBe('Format');+ trigger.focus();+ expect(document.activeElement).toBe(trigger);+ fireEvent.keyDown(trigger, { key: 'Enter' });++ expect(await findByText('Format rows')).toBeTruthy();+ });++ it('keeps a custom selector label as the only keyboard focus target', () => {+ const { container } = renderWithDependencies(+ <ToolbarItem+ id="test-custom-selector"+ type={MenuItemType.SELECTOR}+ label={{ name: 'TestDynamicOption' }}+ selections={[{ label: 'Format rows', value: 'row' }]}+ />+ );+ const trigger = container.querySelector('.univer-toolbar-selector-root') as HTMLElement;++ expect(trigger.getAttribute('role')).toBeNull();+ expect(trigger.getAttribute('tabindex')).toBeNull();+ expect(trigger.querySelector('button')).toBeTruthy();+ });+it('closes open selector options when the parent becomes disabled', async () => {const disabled$ = new BehaviorSubject(false);const { container, findByText, queryByText } = renderWithDependencies(@@ -136,6 +192,19 @@ describe('ToolbarItem', () => {expect(getByText('Format')).toBeTruthy();});+ it('uses the tooltip as the accessible name for an icon-only button', () => {+ const { getByRole } = renderWithDependencies(+ <ToolbarItem+ id="test-icon-button"+ type={MenuItemType.BUTTON}+ icon="TestIcon"+ tooltip="Undo"+ />+ );++ expect(getByRole('button', { name: 'Undo' })).toBeTruthy();+ });+it('shows a title for a large Grid button selector', () => {const { getByText } = renderWithDependencies(<ToolbarItemdiff --git a/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsx b/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsxindex 9342bd3328..eb3983760a 100644--- a/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsx+++ b/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsx@@ -19,17 +19,35 @@*/import type { ComponentType, ReactElement } from 'react';-import { cleanup, fireEvent, render } from '@testing-library/react';-import { ILogService, Injector, LocaleService } from '@univerjs/core';+import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react';+import {+ CommandService,+ ConfigService,+ ContextService,+ DesktopLogService,+ FOCUSING_SHEET,+ ICommandService,+ IConfigService,+ IContextService,+ ILogService,+ Injector,+ IUniverInstanceService,+ LocaleService,+ LocaleType,+ UniverInstanceService,+ Workbook,+} from '@univerjs/core';import { ConfigProvider, Dialog, Dropdown } from '@univerjs/design';import { useState } from 'react';-import { of } from 'rxjs';import { afterEach, describe, expect, it, vi } from 'vitest';-import { ComponentManager } from '../../../../common/component-manager';import { IconManager } from '../../../../common/icon-manager';+import { DesktopLayoutService, ILayoutService } from '../../../../services/layout/layout.service';import { MenuItemType } from '../../../../services/menu/menu';-import { IMenuManagerService } from '../../../../services/menu/menu-manager.service';+import { IMenuManagerService, MenuManagerService } from '../../../../services/menu/menu-manager.service';+import { IPlatformService, PlatformService } from '../../../../services/platform/platform.service';+import { IUIRuntimeScopeService, UIRuntimeScopeService } from '../../../../services/runtime-scope/ui-runtime-scope.service';+import { IShortcutService, ShortcutService } from '../../../../services/shortcut/shortcut.service';import { connectInjector } from '../../../../utils/di';import {DropdownMenuLabel,@@ -40,15 +58,7 @@ import {TooltipWrapper,} from '../TooltipButtonWrapper';-class TestLocaleService {- t(key: string) {- return key;- }-}--class TestLogService {- warn(): void {}-}+const testInjectors: Injector[] = [];function NestedDialogDropdown() {const [open, setOpen] = useState(false);@@ -68,28 +78,44 @@ function renderWithDependencies(menuItems: ReturnType<IMenuManagerService['getMenuByPositionKey']> = []) {const injector = new Injector();- injector.add([LocaleService, { useClass: TestLocaleService as never }]);- injector.add([ILogService, { useClass: TestLogService as never }]);+ testInjectors.push(injector);+ injector.add([LocaleService]);+ injector.add([ILogService, { useClass: DesktopLogService }]);injector.add([ComponentManager]);injector.add([IconManager]);- injector.add([IMenuManagerService, {- useValue: {- menuChanged$: of(undefined),- mergeMenu: () => {},- appendRootMenu: () => {},- getMenuByPositionKey: () => menuItems,- getFlatMenuByPositionKey: () => [],- },- }]);+ injector.add([IMenuManagerService, { useClass: MenuManagerService }]);+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ injector.add([ILayoutService, { useClass: DesktopLayoutService }]);+ injector.add([IPlatformService, { useClass: PlatformService }]);+ injector.add([IUIRuntimeScopeService, { useClass: UIRuntimeScopeService }]);+ injector.add([IShortcutService, { useClass: ShortcutService }]);+ const localeService = injector.get(LocaleService);+ localeService.load({ [LocaleType.EN_US]: { Reset: 'Reset' } });+ localeService.setLocale(LocaleType.EN_US);+ localeService.setDirection('ltr');+ injector.get(IMenuManagerService).appendRootMenu({+ 'test-menu': Object.fromEntries(menuItems.map((item) => [item.key, {+ order: item.order,+ menuItemFactory: () => item.item!,+ }])),+ });+ const forceEscape = vi.spyOn(injector.get(IShortcutService), 'forceEscape');injector.get(ComponentManager).register('TestDynamicOption', ({ onChange }: { onChange: (value: string) => void }) => (<button type="button" onClick={() => onChange('dynamic-value')}>Choose dynamic value</button>));const ConnectedTestRoot = connectInjector(() => element, injector) as ComponentType;- return render(<ConnectedTestRoot />);+ return { ...render(<ConnectedTestRoot />), forceEscape, injector };}-afterEach(cleanup);+afterEach(() => {+ cleanup();+ testInjectors.forEach((injector) => injector.dispose());+ testInjectors.length = 0;+});describe('ToolbarTooltip', () => {it('stays hidden after its popup closes until a new trigger interaction', () => {@@ -105,7 +131,9 @@ describe('ToolbarTooltip', () => {}fireEvent.mouseEnter(trigger);- expect(getByRole('tooltip').textContent).toBe('Fill');+ const tooltip = getByRole('tooltip');+ expect(tooltip.textContent).toBe('Fill');+ expect(tooltip.classList.contains('univer-pointer-events-none')).toBe(true);rerender(renderTooltip(true));expect(queryByRole('tooltip')).toBeNull();@@ -233,8 +261,143 @@ describe('DropdownWrapper', () => {});describe('DropdownMenuWrapper', () => {+ it.each(['worksheet', 'workbook'])(+ 'invalidates an open Sheet menu when its %s changes',+ async (change) => {+ const onOptionSelect = vi.fn();+ const { injector, getByRole, findByRole, queryByRole } = renderWithDependencies(+ <TooltipWrapper>+ <DropdownMenuWrapper+ menuId="test-menu"+ options={[{ label: { name: 'RetainedOption', selectable: false } }]}+ onOptionSelect={onOptionSelect}+ >+ <button type="button">Open scoped menu</button>+ </DropdownMenuWrapper>+ </TooltipWrapper>+ );+ let retainedChange: ((value: string) => void) | undefined;+ const registration = injector.get(ComponentManager).register('RetainedOption', ({ onChange }: {+ onChange: (value: string) => void;+ }) => {+ retainedChange = onChange;+ return <button type="button">Retained option</button>;+ });+ const editor = document.createElement('input');+ document.body.appendChild(editor);+ const workbook = injector.createInstance(Workbook, {+ id: 'original',+ sheetOrder: ['first', 'second'],+ sheets: { first: { id: 'first', name: 'First' }, second: { id: 'second', name: 'Second' } },+ });+ const peer = injector.createInstance(Workbook, {+ id: 'peer',+ sheetOrder: ['peer-sheet'],+ sheets: { 'peer-sheet': { id: 'peer-sheet', name: 'Peer' } },+ });+ const instances = injector.get(IUniverInstanceService);+ instances.__addUnit(workbook);+ instances.__addUnit(peer);+ instances.setCurrentUnitForType(workbook.getUnitId());+ injector.get(IContextService).setContextValue(FOCUSING_SHEET, true);+ editor.focus();+ fireEvent.pointerDown(getByRole('button', { name: 'Open scoped menu' }), { button: 0, ctrlKey: false });+ await findByRole('button', { name: 'Retained option' });+ const callback = retainedChange;+ act(() => workbook.setActiveSheet(workbook.getActiveSheet()));+ expect(queryByRole('button', { name: 'Retained option' })).not.toBeNull();+ act(() => {+ if (change === 'worksheet') {+ workbook.setActiveSheet(workbook.getSheetBySheetId('second')!);+ } else {+ instances.setCurrentUnitForType(peer.getUnitId());+ }+ callback?.('stale-value');+ });+ await waitFor(() => expect(queryByRole('button', { name: 'Retained option' })).toBeNull());+ expect(onOptionSelect).not.toHaveBeenCalled();+ act(() => {+ instances.setCurrentUnitForType(workbook.getUnitId());+ workbook.setActiveSheet(workbook.getSheetBySheetId('first')!);+ });+ fireEvent.pointerDown(getByRole('button', { name: 'Open scoped menu' }), { button: 0, ctrlKey: false });+ await findByRole('button', { name: 'Retained option' });+ act(() => callback?.('late-value-after-reopen'));+ expect(onOptionSelect).not.toHaveBeenCalled();+ expect(queryByRole('button', { name: 'Retained option' })).not.toBeNull();+ registration.dispose();+ editor.remove();+ workbook.dispose();+ peer.dispose();+ }+ );++ it.each([undefined, 'embed-1'].flatMap((owner) => (+ ['select', 'escape', 'outside', 'owner-change', 'command-focus'].map((closeAction) => ({ owner, closeAction }))+ )))(+ 'restores the editor with boundary $owner after $closeAction only while it still owns the interaction',+ async ({ owner, closeAction }) => {+ const editor = document.createElement('div');+ editor.tabIndex = 0;+ editor.dataset.uComp = 'editor';+ if (owner) {+ editor.dataset.embedInteractionBoundaryOwner = owner;+ }+ const outside = document.createElement('input');+ document.body.append(editor, outside);+ try {+ const { findByRole, getByRole } = renderWithDependencies(+ <ToolbarDropdownProvider>+ <TooltipWrapper dropdownKey="test-editor-focus">+ <DropdownMenuWrapper+ menuId="test-menu"+ options={[{ label: { name: 'TestDynamicOption', hoverable: false, selectable: false } }]}+ onOptionSelect={() => {+ if (closeAction === 'command-focus') {+ editor.focus();+ }+ }}+ >+ <button type="button">Open editor menu</button>+ </DropdownMenuWrapper>+ </TooltipWrapper>+ </ToolbarDropdownProvider>+ );+ const trigger = getByRole('button', { name: 'Open editor menu' });+ editor.focus();+ fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false });+ const option = await findByRole('button', { name: 'Choose dynamic value' });+ option.focus();++ if (closeAction === 'outside') {+ fireEvent.pointerDown(outside, { button: 0, ctrlKey: false });+ outside.focus();+ } else if (closeAction === 'escape') {+ fireEvent.keyDown(option, { key: 'Escape', keyCode: 27 });+ } else {+ if (closeAction === 'owner-change') {+ editor.dataset.embedInteractionBoundaryOwner = 'embed-2';+ }+ fireEvent.click(option);+ }++ await waitFor(() => expect(trigger.getAttribute('aria-expanded')).toBe('false'));+ if (closeAction === 'outside') {+ await waitFor(() => expect(document.activeElement).toBe(outside));+ } else if (closeAction === 'owner-change') {+ await waitFor(() => expect(document.activeElement).toBe(trigger));+ } else {+ await waitFor(() => expect(document.activeElement).toBe(editor));+ }+ } finally {+ editor.remove();+ outside.remove();+ }+ }+ );+it('renders a single embedded custom panel flush with the dropdown edge', async () => {- const { findByRole, getByRole } = renderWithDependencies(+ const { findByRole, forceEscape, getByRole } = renderWithDependencies(<ToolbarDropdownProvider><TooltipWrapper dropdownKey="test-custom-panel"><DropdownMenuWrapper@@ -262,6 +425,11 @@ describe('DropdownMenuWrapper', () => {expect(menuItem?.className).toContain('!univer-p-0');expect(menuContent?.className).toContain('!univer-p-0');+ expect(forceEscape).toHaveBeenCalledOnce();+ const disposeShortcutEscape = vi.spyOn(forceEscape.mock.results[0].value, 'dispose');++ fireEvent.click(option);+ await waitFor(() => expect(disposeShortcutEscape).toHaveBeenCalledOnce());});it('keeps padding around a non-embedded custom panel', async () => {diff --git a/packages/ui/src/views/components/sidebar/Sidebar.tsx b/packages/ui/src/views/components/sidebar/Sidebar.tsxindex 62cdbb6230..96e510ff87 100644--- a/packages/ui/src/views/components/sidebar/Sidebar.tsx+++ b/packages/ui/src/views/components/sidebar/Sidebar.tsx@@ -76,17 +76,41 @@ export function Sidebar() {const scrollRef = useRef<HTMLDivElement>(null);const sidebarRef = useRef<HTMLElement>(null);const closeButtonRef = useRef<HTMLButtonElement>(null);+ const returnFocusElementRef = useRef<HTMLElement | null>(null);+ const previousSidebarIdRef = useRef<string | undefined>(undefined);+ const wasVisibleRef = useRef(false);const [isDragging, setIsDragging] = useState(false);const dragWidthRef = useRef<number | null>(null);const options = useMemo(() => renderSidebarOptions(sidebarOptions), [sidebarOptions]);- // Focus management: move focus into the sidebar when it opensuseEffect(() => {- if (options?.visible && closeButtonRef.current) {- closeButtonRef.current.focus();+ const isVisible = !!options?.visible;+ const isNewPanel = isVisible && (!wasVisibleRef.current || previousSidebarIdRef.current !== options?.id);++ if (isNewPanel) {+ const activeElement = document.activeElement;+ if (+ activeElement instanceof HTMLElement &&+ activeElement !== document.body &&+ !sidebarRef.current?.contains(activeElement)+ ) {+ returnFocusElementRef.current = activeElement;+ }+ closeButtonRef.current?.focus();+ } else if (!isVisible && wasVisibleRef.current) {+ const activeElement = document.activeElement;+ const shouldRestoreFocus = activeElement === document.body || !!sidebarRef.current?.contains(activeElement);+ const returnFocusElement = returnFocusElementRef.current;+ if (shouldRestoreFocus && returnFocusElement?.isConnected) {+ returnFocusElement.focus({ preventScroll: true });+ }+ returnFocusElementRef.current = null;}- }, [options?.visible]);++ wasVisibleRef.current = isVisible;+ previousSidebarIdRef.current = options?.id;+ }, [options?.id, options?.visible]);// ESC key to close sidebaruseEffect(() => {@@ -192,13 +216,14 @@ export function Sidebar() {data-u-comp="sidebar"role="complementary"aria-expanded={!!options?.visible}+ aria-hidden={!options?.visible}aria-label={localeService.t<LocaleKey>('ui.sidebar.panel')}className={clsx(`univer-relative univer-h-full univer-flex-shrink-0 univer-bg-gray-0 univer-text-gray-900dark:!univer-bg-gray-900 dark:!univer-text-gray-0`, {'univer-w-96 univer-translate-x-0': options?.visible,- 'univer-w-0 univer-translate-x-full': !options?.visible,+ 'univer-pointer-events-none univer-invisible univer-w-0 univer-translate-x-full': !options?.visible,})}style={{ width: isDragging ? undefined : width }}>diff --git a/packages/ui/src/views/components/sidebar/__tests__/Sidebar.spec.tsx b/packages/ui/src/views/components/sidebar/__tests__/Sidebar.spec.tsxindex 931b3026f7..32828c2282 100644--- a/packages/ui/src/views/components/sidebar/__tests__/Sidebar.spec.tsx+++ b/packages/ui/src/views/components/sidebar/__tests__/Sidebar.spec.tsx@@ -91,7 +91,63 @@ describe('Sidebar', () => {expect(sidebarService.visible).toBe(false);expect(TestState.closes).toBe(1);- expect(screen.getByRole('complementary', { name: 'Sidebar panel' }).getAttribute('aria-expanded')).toBe('false');+ expect(screen.queryByRole('complementary', { name: 'Sidebar panel' })).toBeNull();+ expect(rendered.container.querySelector('[data-u-comp="sidebar"]')?.getAttribute('aria-expanded')).toBe('false');+ rendered.dispose();+ });++ it('restores the opener and removes closed content from keyboard navigation', () => {+ const rendered = renderWithDependencies(+ <>+ <button type="button">Open inspector</button>+ <Sidebar />+ </>+ );+ const sidebarService = rendered.injector.get(ISidebarService);+ const opener = screen.getByRole('button', { name: 'Open inspector' });+ opener.focus();++ act(() => {+ sidebarService.open({+ id: 'inspector',+ header: { title: <span>Inspector</span> },+ children: { title: <button type="button">Focusable content</button> },+ });+ });++ const closeButton = screen.getByRole('button', { name: 'Close sidebar' });+ expect(document.activeElement).toBe(closeButton);++ fireEvent.click(closeButton);++ expect(document.activeElement).toBe(opener);+ expect(screen.queryByRole('complementary', { name: 'Sidebar panel' })).toBeNull();+ expect(rendered.container.querySelector('[data-u-comp="sidebar"]')?.className).toContain('univer-invisible');+ rendered.dispose();+ });++ it('does not restore the opener after another control claims focus', () => {+ const rendered = renderWithDependencies(+ <>+ <button type="button">Open inspector</button>+ <button type="button">Next control</button>+ <Sidebar />+ </>+ );+ const sidebarService = rendered.injector.get(ISidebarService);+ screen.getByRole('button', { name: 'Open inspector' }).focus();++ act(() => {+ sidebarService.open({ id: 'inspector' });+ });++ const nextControl = screen.getByRole('button', { name: 'Next control' });+ nextControl.focus();+ act(() => {+ sidebarService.close('inspector');+ });++ expect(document.activeElement).toBe(nextControl);rendered.dispose();});diff --git a/packages/ui/src/views/font-family/FontFamily.tsx b/packages/ui/src/views/font-family/FontFamily.tsxindex 3b06767f4e..4b8a89a244 100644--- a/packages/ui/src/views/font-family/FontFamily.tsx+++ b/packages/ui/src/views/font-family/FontFamily.tsx@@ -19,7 +19,6 @@ import type { Observable } from 'rxjs';import type { ICustomComponentProps } from '../../services/menu/menu';import { LocaleService } from '@univerjs/core';import { clsx } from '@univerjs/design';-import { useMemo, useState } from 'react';import { useDependency, useObservable } from '../../utils/di';import { useFontList } from './use-font-list';@@ -71,7 +70,9 @@ export const FontFamily = ({ className, disabled: disabledProp, value, disabled$function handleKeyDown(e: KeyboardEvent<HTMLInputElement>) {e.stopPropagation();- if (disabled) return;+ if (disabled || e.nativeEvent.isComposing) {+ return;+ }if (e.key === 'Enter') {confirm();@@ -86,9 +87,15 @@ export const FontFamily = ({ className, disabled: disabledProp, value, disabled$}function confirm() {+ const query = inputValue.trim().toLowerCase();+ if (!query) {+ resetValue();+ return;+ }+const font = fonts.find((item) => {const label = localeService.t(item.label);- return label.toLowerCase().includes(inputValue.trim().toLowerCase());+ return label.toLowerCase().includes(query);});if (!font) {@@ -120,6 +127,7 @@ export const FontFamily = ({ className, disabled: disabledProp, value, disabled$`}type="text"value={inputValue}+ onPointerDown={(event) => event.stopPropagation()}onChange={handleChangeSelection}onKeyDown={handleKeyDown}onBlur={handleBlur}diff --git a/packages/ui/src/views/font-family/__tests__/FontFamily.spec.tsx b/packages/ui/src/views/font-family/__tests__/FontFamily.spec.tsxindex 25249b3307..5048936a38 100644--- a/packages/ui/src/views/font-family/__tests__/FontFamily.spec.tsx+++ b/packages/ui/src/views/font-family/__tests__/FontFamily.spec.tsx@@ -16,8 +16,9 @@import type { ICommand } from '@univerjs/core';import type { ReactElement } from 'react';-import { fireEvent, render } from '@testing-library/react';+import { createEvent, fireEvent, render } from '@testing-library/react';import { CommandType, ICommandService, LocaleService, LocaleType, Univer } from '@univerjs/core';+import { DropdownMenu } from '@univerjs/design';import { BehaviorSubject } from 'rxjs';import { afterEach, describe, expect, it } from 'vitest';import { FontService, IFontService } from '../../../services/font.service';@@ -51,6 +52,7 @@ function renderWithDependencies(element: ReactElement, direction: 'ltr' | 'rtl'const univer = new Univer();const injector = univer.__getInjector();injector.add([IFontService, { useClass: FontService }]);+ injector.get(LocaleService).setLocale(LocaleType.ZH_CN);injector.get(LocaleService).setDirection(direction);injector.get(LocaleService).load({[LocaleType.ZH_CN]: {@@ -95,6 +97,44 @@ describe('font input views', () => {TestState.reset();});+ it('keeps input pointer actions out of the surrounding menu trigger while the arrow still opens it', () => {+ const rendered = renderWithDependencies(+ <DropdownMenu items={[{ type: 'item', children: 'Font choice' }]}>+ <div>+ <FontFamily value="Arial" onChange={(value) => TestState.familyChanges.push(value)} />+ <span>Open fonts</span>+ </div>+ </DropdownMenu>+ );+ try {+ const input = rendered.container.querySelector('input')!;+ const inputPointer = createEvent.pointerDown(input, { bubbles: true, cancelable: true });+ Object.defineProperties(inputPointer, {+ button: { value: 0 },+ pointerType: { value: 'mouse' },+ ctrlKey: { value: false },+ });+ fireEvent(input, inputPointer);+ expect(inputPointer.defaultPrevented).toBe(false);+ expect(rendered.queryByRole('menu')).toBeNull();+ fireEvent.change(input, { target: { value: 'Times New Roman' } });+ expect(TestState.familyChanges).toEqual([]);+ fireEvent.keyDown(input, { key: 'Enter' });+ expect(TestState.familyChanges).toEqual(['Times New Roman']);+ const arrow = rendered.getByText('Open fonts');+ const arrowPointer = createEvent.pointerDown(arrow, { bubbles: true, cancelable: true });+ Object.defineProperties(arrowPointer, {+ button: { value: 0 },+ pointerType: { value: 'mouse' },+ ctrlKey: { value: false },+ });+ fireEvent(arrow, arrowPointer);+ expect(rendered.getByRole('menu')).toBeTruthy();+ } finally {+ rendered.dispose();+ }+ });+it('emits onChange when the typed text matches a known font', () => {const rendered = renderWithDependencies(<FontFamily@@ -130,6 +170,38 @@ describe('font input views', () => {rendered.dispose();});+ it.each(['', ' '])('rejects a blank font-family draft %j without emitting a format command', (draft) => {+ const rendered = renderWithDependencies(+ <FontFamily value="Times New Roman" onChange={(value) => TestState.familyChanges.push(value)} />+ );+ try {+ const input = rendered.container.querySelector('input')!;+ fireEvent.change(input, { target: { value: draft } });+ fireEvent.keyDown(input, { key: 'Enter' });+ expect(TestState.familyChanges).toEqual([]);+ expect(input.value).toBe('Times New Roman');+ } finally {+ rendered.dispose();+ }+ });++ it.each(['Enter', 'Escape'])('leaves the font-family draft intact during composing %s', (key) => {+ const rendered = renderWithDependencies(+ <FontFamily value="Arial" onChange={(value) => TestState.familyChanges.push(value)} />+ );+ try {+ const input = rendered.container.querySelector('input')!;+ fireEvent.change(input, { target: { value: 'Times New Roman' } });+ fireEvent.keyDown(input, { key, isComposing: true });+ expect(TestState.familyChanges).toEqual([]);+ expect(input.value).toBe('Times New Roman');+ fireEvent.keyDown(input, { key: 'Enter' });+ expect(TestState.familyChanges).toEqual(['Times New Roman']);+ } finally {+ rendered.dispose();+ }+ });+it('emits onChange when a font-family menu item is selected', () => {const rendered = renderWithDependencies(<FontFamilyItemdiff --git a/packages/ui/src/views/font-size/FontSize.tsx b/packages/ui/src/views/font-size/FontSize.tsxindex a42e304f08..0da720c24a 100644--- a/packages/ui/src/views/font-size/FontSize.tsx+++ b/packages/ui/src/views/font-size/FontSize.tsx@@ -17,32 +17,48 @@import type { KeyboardEvent } from 'react';import type { IFontSizeProps } from './interface';import { InputNumber } from '@univerjs/design';-import { useMemo, useState } from 'react';+import { useState } from 'react';import { useObservable } from '../../utils/di';export const FontSize = (props: IFontSizeProps) => {const { value, min, max, onChange, disabled$ } = props;const disabled = useObservable(disabled$);- const [realValue, setRealValue] = useState<number>(Number(value ?? 0));+ const [draft, setDraft] = useState<{ source: number; value: number | null } | null>(null);+ const inputValue = draft !== null && draft.source === value ? draft.value : Number(value ?? 0);- const _value = useMemo(() => Number(value ?? realValue), [value]);+ if (draft !== null && draft.source !== value) {+ setDraft(null);+ }- function handleChange(value: number | null) {- if (value === null) return;+ function handleChange(nextValue: number | null) {+ setDraft({ source: value, value: nextValue });+ }- setRealValue(value);+ function resetDraft() {+ setDraft(null);}function handleStopPropagation(e: KeyboardEvent<HTMLInputElement>) {e.stopPropagation();- if (e.code === 'Enter') {- onChange(realValue);+ if (disabled || e.nativeEvent.isComposing) {+ return;+ }++ if (e.key === 'Escape') {+ e.preventDefault();+ resetDraft();+ } else if (e.code === 'Enter') {+ resetDraft();+ if (inputValue !== null) {+ // Clamp on confirmation: a draft "2" must remain a valid prefix of "24".+ onChange(Math.min(max, Math.max(min, inputValue)));+ }}}return (- <div className="univer-h-6 univer-w-7 univer-text-sm">+ <div className="univer-h-6 univer-w-7 univer-text-sm" onPointerDown={(event) => event.stopPropagation()}><InputNumberclassName={`univer-block univer-h-6 univer-border-none univer-bg-transparent univer-leading-6@@ -50,12 +66,11 @@ export const FontSize = (props: IFontSizeProps) => {[&_input]:univer-h-6 [&_input]:univer-w-7 [&_input]:univer-border-none[&_input]:!univer-bg-transparent [&_input]:univer-p-0 [&_input]:univer-text-sm`}- value={_value}+ value={inputValue}controls={false}- min={min}- max={max}onKeyDown={handleStopPropagation}onChange={handleChange}+ onBlur={resetDraft}disabled={disabled}/></div>diff --git a/packages/ui/src/views/font-size/__tests__/FontSize.spec.tsx b/packages/ui/src/views/font-size/__tests__/FontSize.spec.tsxnew file mode 100644index 0000000000..64989874fd--- /dev/null+++ b/packages/ui/src/views/font-size/__tests__/FontSize.spec.tsx@@ -0,0 +1,189 @@+/**+ * 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 { cleanup, createEvent, fireEvent, render } from '@testing-library/react';+import { LocaleService, LocaleType, Univer } from '@univerjs/core';+import { DropdownMenu } from '@univerjs/design';+import { afterEach, describe, expect, it } from 'vitest';+import { ComponentManager } from '../../../common/component-manager';+import { IconManager } from '../../../common/icon-manager';+import { RediProvider } from '../../../utils/di';+import { CustomLabel } from '../../custom-label/CustomLabel';+import { FontSize } from '../FontSize';+import { FONT_SIZE_COMPONENT } from '../interface';++describe('FontSize input ownership', () => {+ afterEach(cleanup);++ it('keeps the toolbar mounted before its selected font size becomes available', () => {+ const univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([ComponentManager]);+ injector.add([IconManager]);+ injector.get(LocaleService).setLocale(LocaleType.EN_US);+ injector.get(LocaleService).setDirection('ltr');+ const registration = injector.get(ComponentManager).register(FONT_SIZE_COMPONENT, FontSize);+ const changes: Array<string | number> = [];+ const label = { name: FONT_SIZE_COMPONENT, props: { min: 1, max: 400 } };+ const onChange = (value: string | number) => changes.push(value);+ try {+ const rendered = render(+ <RediProvider value={{ injector }}>+ <CustomLabel label={label} onChange={onChange} />+ </RediProvider>+ );+ const input = rendered.container.querySelector('input')!;+ expect(input).not.toBeNull();+ expect(changes).toEqual([]);+ rendered.rerender(+ <RediProvider value={{ injector }}>+ <CustomLabel label={label} value={18} onChange={onChange} />+ </RediProvider>+ );+ expect(input.value).toBe('18');+ fireEvent.change(input, { target: { value: '24' } });+ fireEvent.keyDown(input, { key: 'Enter', code: 'Enter' });+ expect(changes).toEqual([24]);+ rendered.rerender(+ <RediProvider value={{ injector }}>+ <CustomLabel label={label} onChange={onChange} />+ </RediProvider>+ );+ expect(rendered.container.querySelector('input')).toBe(input);+ expect(changes).toEqual([24]);+ } finally {+ cleanup();+ registration.dispose();+ univer.dispose();+ }+ });++ it('preserves native pointer focus without opening the surrounding dropdown', () => {+ const changes: number[] = [];+ const rendered = render(+ <DropdownMenu items={[{ type: 'item', children: '24' }]}>+ <div>+ <FontSize value={11} min={6} max={400} onChange={(value) => changes.push(value)} />+ <span>Open sizes</span>+ </div>+ </DropdownMenu>+ );+ const input = rendered.container.querySelector('input')!;+ const pointer = createEvent.pointerDown(input, { bubbles: true, cancelable: true });+ Object.defineProperties(pointer, {+ button: { value: 0 },+ pointerType: { value: 'mouse' },+ ctrlKey: { value: false },+ });+ fireEvent(input, pointer);+ expect(pointer.defaultPrevented).toBe(false);+ expect(rendered.queryByRole('menu')).toBeNull();+ expect(changes).toEqual([]);+ });++ it.each(['Escape', 'blur'])('discards numeric and empty drafts on %s without a command', (action) => {+ const changes: number[] = [];+ const rendered = render(<FontSize value={11} min={6} max={400} onChange={(value) => changes.push(value)} />);+ const input = rendered.container.querySelector('input')!;+ for (const draft of ['24', '']) {+ fireEvent.change(input, { target: { value: draft } });+ expect(input.value).toBe(draft);+ if (action === 'blur') {+ fireEvent.blur(input);+ } else {+ fireEvent.keyDown(input, { key: action, code: action });+ }+ expect(input.value).toBe('11');+ expect(changes).toEqual([]);+ }+ });++ it('does not submit a previous draft when confirming an empty input', () => {+ const changes: number[] = [];+ const rendered = render(<FontSize value={11} min={6} max={400} onChange={(value) => changes.push(value)} />);+ const input = rendered.container.querySelector('input')!;+ fireEvent.change(input, { target: { value: '24' } });+ fireEvent.change(input, { target: { value: '' } });+ fireEvent.keyDown(input, { key: 'Enter', code: 'Enter' });+ expect(input.value).toBe('11');+ expect(changes).toEqual([]);+ });++ it('uses the new selected size instead of a stale draft after the controlled value changes', () => {+ const changes: number[] = [];+ const onChange = (value: number) => changes.push(value);+ const rendered = render(<FontSize value={11} min={6} max={400} onChange={onChange} />);+ const input = rendered.container.querySelector('input')!;+ fireEvent.change(input, { target: { value: '24' } });+ rendered.rerender(<FontSize value={18} min={6} max={400} onChange={onChange} />);+ expect(input.value).toBe('18');+ fireEvent.keyDown(input, { key: 'Enter', code: 'Enter' });+ expect(changes).toEqual([18]);+ });++ it.each(['24', ''])('does not revive draft "%s" when the controlled size returns to its original value', (draft) => {+ const changes: number[] = [];+ const onChange = (value: number) => changes.push(value);+ const rendered = render(<FontSize value={11} min={6} max={400} onChange={onChange} />);+ const input = rendered.container.querySelector('input')!;+ input.focus();+ fireEvent.change(input, { target: { value: draft } });+ expect(input.value).toBe(draft);+ rendered.rerender(<FontSize value={18} min={6} max={400} onChange={onChange} />);+ expect(input.value).toBe('18');+ rendered.rerender(<FontSize value={11} min={6} max={400} onChange={onChange} />);+ expect(document.activeElement).toBe(input);+ expect(input.value).toBe('11');+ expect(changes).toEqual([]);+ fireEvent.keyDown(input, { key: 'Enter', code: 'Enter' });+ expect(changes).toEqual([11]);+ });++ it.each([['2', 6], ['999', 400]] as const)('commits bounded size %s only after confirmation', (text, expected) => {+ const changes: number[] = [];+ const rendered = render(<FontSize value={11} min={6} max={400} onChange={(value) => changes.push(value)} />);+ const input = rendered.container.querySelector('input')!;+ fireEvent.change(input, { target: { value: text } });+ expect(input.value).toBe(text);+ expect(changes).toEqual([]);+ fireEvent.keyDown(input, { key: 'Enter', code: 'Enter' });+ expect(changes).toEqual([expected]);+ });++ it('retains a below-minimum prefix while typing a valid multi-digit size', () => {+ const changes: number[] = [];+ const rendered = render(<FontSize value={11} min={6} max={400} onChange={(value) => changes.push(value)} />);+ const input = rendered.container.querySelector('input')!;+ fireEvent.change(input, { target: { value: '2' } });+ expect(input.value).toBe('2');+ fireEvent.change(input, { target: { value: `${input.value}4` } });+ expect(input.value).toBe('24');+ fireEvent.keyDown(input, { key: 'Enter', code: 'Enter' });+ expect(changes).toEqual([24]);+ });++ it('does not commit while Enter accepts an IME candidate', () => {+ const changes: number[] = [];+ const rendered = render(<FontSize value={11} min={6} max={400} onChange={(value) => changes.push(value)} />);+ const input = rendered.container.querySelector('input')!;+ fireEvent.change(input, { target: { value: '24' } });+ fireEvent.keyDown(input, { key: 'Enter', code: 'Enter', isComposing: true });+ expect(input.value).toBe('24');+ expect(changes).toEqual([]);+ fireEvent.keyDown(input, { key: 'Enter', code: 'Enter' });+ expect(changes).toEqual([24]);+ });+});diff --git a/packages/ui/src/views/menu/desktop/DesignTinyMenuGroup.tsx b/packages/ui/src/views/menu/desktop/DesignTinyMenuGroup.tsxindex 10d9683afb..c9aae0b1d4 100644--- a/packages/ui/src/views/menu/desktop/DesignTinyMenuGroup.tsx+++ b/packages/ui/src/views/menu/desktop/DesignTinyMenuGroup.tsx@@ -200,7 +200,7 @@ export function DesignTinyMenuGroup({? (<Tooltipkey={item.key}- className="univer-fill-mode-backwards univer-delay-100"+ className="univer-fill-mode-backwards univer-pointer-events-none univer-delay-100"title={item.tooltip}>{ele}diff --git a/packages/ui/src/views/menu/desktop/__tests__/DesignTinyMenuGroup.spec.tsx b/packages/ui/src/views/menu/desktop/__tests__/DesignTinyMenuGroup.spec.tsxindex d92b6b87a6..c18d65ee47 100644--- a/packages/ui/src/views/menu/desktop/__tests__/DesignTinyMenuGroup.spec.tsx+++ b/packages/ui/src/views/menu/desktop/__tests__/DesignTinyMenuGroup.spec.tsx@@ -73,6 +73,26 @@ describe('DesignTinyMenuGroup', () => {expect(container.querySelector('button')?.getAttribute('title')).toBe('Heading 1');});+ it('keeps default tiny-menu tooltips from intercepting sibling actions', async () => {+ const Icon = () => <span data-testid="quick-icon" />;++ render(+ <DesignTinyMenuGroup+ items={[{+ key: 'center',+ Icon,+ className: '',+ onClick: () => undefined,+ tooltip: 'Center',+ }]}+ />+ );++ fireEvent.mouseEnter(screen.getByRole('button', { name: 'Center' }).parentElement!);++ expect((await screen.findByRole('tooltip')).classList.contains('univer-pointer-events-none')).toBe(true);+ });+it('uses the primary color channel for two-channel icons', () => {const Icon = ({ extend }: { className?: string; extend?: { colorChannel1?: string } }) => (React.createElement('span', { 'data-color-channel': extend?.colorChannel1 })diff --git a/packages/ui/src/views/slider/Slider.tsx b/packages/ui/src/views/slider/Slider.tsxindex a5d62f8b76..3cd9f8d9e1 100644--- a/packages/ui/src/views/slider/Slider.tsx+++ b/packages/ui/src/views/slider/Slider.tsx@@ -14,11 +14,12 @@* limitations under the License.*/-import type { PointerEvent as ReactPointerEvent } from 'react';+import type { KeyboardEvent, PointerEvent } from 'react';+import type { LocaleKey } from '../../locale/types';import { LocaleService } from '@univerjs/core';import { borderClassName, Button, clsx } from '@univerjs/design';import { useEffect, useRef, useState } from 'react';-import { IconManager } from '../../common';+import { IconManager } from '../../common/icon-manager';import { useDependency, useObservable } from '../../utils/di';import { ZoomInput } from './ZoomInput';@@ -88,13 +89,17 @@ export function Slider(props: ISliderProps) {}function handleReset() {- if (disabled) return;+ if (disabled) {+ return;+ }onChange && onChange(resetPoint);}function handleStep(offset: number) {- if (disabled) return;+ if (disabled) {+ return;+ }let result = value + offset;if (value + offset <= min) {@@ -105,6 +110,25 @@ export function Slider(props: ISliderProps) {onChange && onChange(result);}+ function handleSliderKeyDown(e: KeyboardEvent<HTMLButtonElement>) {+ let nextValue: number | null = null;+ if (e.key === 'ArrowLeft' || e.key === 'ArrowDown' || e.key === 'PageDown') {+ nextValue = e.key === 'PageDown' ? value - 100 : value - 10;+ } else if (e.key === 'ArrowRight' || e.key === 'ArrowUp' || e.key === 'PageUp') {+ nextValue = e.key === 'PageUp' ? value + 100 : value + 10;+ } else if (e.key === 'Home') {+ nextValue = min;+ } else if (e.key === 'End') {+ nextValue = max;+ }+ if (nextValue === null || disabled) {+ return;+ }+ e.preventDefault();+ e.stopPropagation();+ onChange?.(clampValue(nextValue));+ }+function getSliderOffset(sliderValue: number) {if (sliderValue <= resetPoint) {const ratio = 50 / (resetPoint - min);@@ -198,8 +222,10 @@ export function Slider(props: ISliderProps) {return nextValue;}- function handlePointerDown(e: ReactPointerEvent<HTMLElement>) {- if (disabled) return;+ function handlePointerDown(e: PointerEvent<HTMLElement>) {+ if (disabled) {+ return;+ }e.preventDefault();e.stopPropagation();@@ -209,7 +235,7 @@ export function Slider(props: ISliderProps) {setIsDragging(true);scheduleDragCommit(updateDragValue(e.clientX, rail));- function onPointerMove(e: PointerEvent) {+ function onPointerMove(e: globalThis.PointerEvent) {if (isDragging) {scheduleDragCommit(updateDragValue(e.clientX, rail));}@@ -225,7 +251,7 @@ export function Slider(props: ISliderProps) {flushDragCommit();}- function onPointerOut(e: PointerEvent) {+ function onPointerOut(e: globalThis.PointerEvent) {e.relatedTarget === null && onPointerUp();}@@ -251,6 +277,7 @@ export function Slider(props: ISliderProps) {className="univer-size-6 univer-p-0"size="small"variant="text"+ aria-label={localeService.t<LocaleKey>('ui.accessibility.zoomOut')}disabled={value <= min || disabled}onClick={() => handleStep(-10)}>@@ -301,7 +328,18 @@ export function Slider(props: ISliderProps) {dark:!univer-border-gray-700 dark:!univer-bg-gray-300`}role="button"+ tabIndex={disabled ? -1 : 0}+ aria-label={localeService.t<LocaleKey>('ui.accessibility.resetZoom')}+ aria-disabled={disabled}onClick={handleReset}+ onKeyDown={(e) => {+ if (e.key !== 'Enter' && e.key !== ' ') {+ return;+ }+ e.preventDefault();+ e.stopPropagation();+ handleReset();+ }}/><button@@ -318,14 +356,18 @@ export function Slider(props: ISliderProps) {'univer-scale-105 univer-border-primary-600 univer-shadow-md': isDragging,})}role="slider"+ aria-label={localeService.t<LocaleKey>('ui.accessibility.zoom')}aria-valuemin={min}aria-valuemax={max}aria-valuenow={visualValue}+ aria-valuetext={`${visualValue}%`}+ disabled={disabled}type="button"style={{left: `${handleOffset}%`,}}onPointerDown={handlePointerDown}+ onKeyDown={handleSliderKeyDown}/></div></div>@@ -335,6 +377,7 @@ export function Slider(props: ISliderProps) {className="univer-size-6 univer-p-0"size="small"variant="text"+ aria-label={localeService.t<LocaleKey>('ui.accessibility.zoomIn')}disabled={value >= max || disabled}onClick={() => handleStep(10)}>diff --git a/packages/ui/src/views/slider/ZoomInput.tsx b/packages/ui/src/views/slider/ZoomInput.tsxindex f9d706ad03..206b656116 100644--- a/packages/ui/src/views/slider/ZoomInput.tsx+++ b/packages/ui/src/views/slider/ZoomInput.tsx@@ -15,9 +15,12 @@*/import type { IDropdownMenuProps } from '@univerjs/design';+import type { KeyboardEvent } from 'react';+import type { LocaleKey } from '../../locale/types';+import { LocaleService } from '@univerjs/core';import { Button, clsx, DropdownMenu, Input } from '@univerjs/design';import { useEffect, useRef, useState } from 'react';-import { IconManager } from '../../common';+import { IconManager } from '../../common/icon-manager';import { useDependency } from '../../utils/di';export interface IZoomInputProps {@@ -32,6 +35,7 @@ export interface IZoomInputProps {export function ZoomInput(props: IZoomInputProps) {const iconManager = useDependency(IconManager);+ const localeService = useDependency(LocaleService);const {value = 100,min = 0,@@ -56,7 +60,9 @@ export function ZoomInput(props: IZoomInputProps) {}function handleSelect(value: number) {- if (disabled) return;+ if (disabled) {+ return;+ }setListVisible(false);onChange?.(value);@@ -64,23 +70,31 @@ export function ZoomInput(props: IZoomInputProps) {function parseInput(rawValue: string) {const normalizedValue = rawValue.trim().replace(/%$/, '').trim();- if (normalizedValue === '') return null;+ if (normalizedValue === '') {+ return null;+ }const parsedValue = Number(normalizedValue);- if (!Number.isFinite(parsedValue)) return null;+ if (!Number.isFinite(parsedValue)) {+ return null;+ }return Math.round(clampValue(parsedValue));}function handleFocus() {- if (disabled) return;+ if (disabled) {+ return;+ }isEditingRef.current = true;setInputValue(String(value));}function commitInput() {- if (disabled || !isEditingRef.current) return;+ if (disabled || !isEditingRef.current) {+ return;+ }const parsedValue = parseInput(inputValue);isEditingRef.current = false;@@ -96,7 +110,7 @@ export function ZoomInput(props: IZoomInputProps) {}}- function handleKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {+ function handleKeyDown(e: KeyboardEvent<HTMLInputElement>) {e.stopPropagation();if (e.key === 'Enter') {@@ -135,6 +149,7 @@ export function ZoomInput(props: IZoomInputProps) {`}inputClass="univer-w-full"size="mini"+ aria-label={localeService.t<LocaleKey>('ui.accessibility.zoom')}value={inputValue}disabled={disabled}type="text"@@ -155,6 +170,7 @@ export function ZoomInput(props: IZoomInputProps) {className="univer-h-6 univer-w-4 univer-rounded-none univer-p-0"size="small"variant="text"+ aria-label={localeService.t<LocaleKey>('ui.accessibility.menu')}disabled={disabled}><MoreDownIcondiff --git a/packages/ui/src/views/slider/__tests__/Slider.spec.tsx b/packages/ui/src/views/slider/__tests__/Slider.spec.tsxindex 08c7647605..84a100e472 100644--- a/packages/ui/src/views/slider/__tests__/Slider.spec.tsx+++ b/packages/ui/src/views/slider/__tests__/Slider.spec.tsx@@ -20,9 +20,12 @@import type { ISliderProps } from '../Slider';import { cleanup, fireEvent, render } from '@testing-library/react';-import { DesktopLogService, ILogService, Injector, LocaleService } from '@univerjs/core';+import { DesktopLogService, ILogService, Injector, LocaleService, LocaleType } from '@univerjs/core';import { afterEach, describe, expect, it } from 'vitest';-import { ComponentManager, IconManager } from '../../../common';+import { ComponentManager } from '../../../common/component-manager';+import { IconManager } from '../../../common/icon-manager';+import enUS from '../../../locale/en-US';+import zhCN from '../../../locale/zh-CN';import { RediProvider } from '../../../utils/di';import { Slider } from '../Slider';@@ -31,18 +34,28 @@ type SliderTestProps = Partial<Omit<ISliderProps, 'onChange'>> & {};describe('Slider', () => {+ const injectors: Injector[] = [];afterEach(() => {cleanup();+ injectors.splice(0).forEach((injector) => injector.dispose());});- function renderSlider(props: SliderTestProps = {}, direction: 'ltr' | 'rtl' = 'ltr') {+ function renderSlider(+ props: SliderTestProps = {},+ direction: 'ltr' | 'rtl' = 'ltr',+ locale = LocaleType.EN_US+ ) {const injector = new Injector([[ILogService, { useClass: DesktopLogService }],[LocaleService],[ComponentManager],[IconManager],]);- injector.get(LocaleService).setDirection(direction);+ injectors.push(injector);+ const localeService = injector.get(LocaleService);+ localeService.load({ [LocaleType.EN_US]: enUS, [LocaleType.ZH_CN]: zhCN });+ localeService.setLocale(locale);+ localeService.setDirection(direction);const { onChange = () => {}, ...sliderProps } = props;return render(@@ -162,6 +175,32 @@ describe('Slider', () => {expect(changes).toEqual([115, 100, 135]);});+ it.each([+ [LocaleType.EN_US, enUS.ui.accessibility],+ [LocaleType.ZH_CN, zhCN.ui.accessibility],+ ])('exposes UI-owned zoom labels and keyboard input in %s', (locale, labels) => {+ const changes: number[] = [];+ const { getByRole } = renderSlider(+ { value: 125, min: 10, max: 400, onChange: (value) => changes.push(value) },+ 'ltr',+ locale+ );+ const slider = getByRole('slider', { name: labels.zoom });++ expect(getByRole('button', { name: labels.zoomOut })).toBeTruthy();+ expect(getByRole('button', { name: labels.zoomIn })).toBeTruthy();+ expect(getByRole('button', { name: labels.resetZoom })).toBeTruthy();+ expect(getByRole('textbox', { name: labels.zoom })).toBeTruthy();+ expect(getByRole('button', { name: labels.menu })).toBeTruthy();++ fireEvent.keyDown(slider, { key: 'ArrowRight' });+ fireEvent.keyDown(slider, { key: 'PageUp' });+ fireEvent.keyDown(slider, { key: 'Home' });+ fireEvent.keyDown(slider, { key: 'End' });++ expect(changes).toEqual([135, 225, 10, 400]);+ });+it('clamps step buttons at the min and max boundaries', () => {const minChanges: number[] = [];const minRender = renderSlider({ value: 10, min: 10, onChange: (value) => minChanges.push(value) });diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 7f2c34b7e1..910ad42ca2 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1704,6 +1704,12 @@ importers:'@univerjs-infra/shared':specifier: workspace:*version: link:../../common/shared+ '@univerjs/docs':+ specifier: workspace:*+ version: link:../docs+ '@univerjs/docs-ui':+ specifier: workspace:*+ version: link:../docs-uipostcss:specifier: ^8.5.26version: 8.5.26@@ -1992,9 +1998,6 @@ importers:'@univerjs/ui':specifier: workspace:*version: link:../ui- react-dom:- specifier: 19.2.8- version: 19.2.8([email protected])devDependencies:'@univerjs-infra/shared':specifier: workspace:*@@ -2005,6 +2008,9 @@ importers:react:specifier: 19.2.8version: 19.2.8+ react-dom:+ specifier: 19.2.8+ version: 19.2.8([email protected])rxjs:specifier: ^7.8.2version: 7.8.2@@ -4765,9 +4771,6 @@ packages:'@jridgewell/[email protected]':resolution: {integrity: sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA==}- '@jridgewell/[email protected]':- resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==}-'@jridgewell/[email protected]':resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==}@@ -12544,7 +12547,7 @@ snapshots:'@jridgewell/[email protected]':dependencies:- '@jridgewell/sourcemap-codec': 1.5.5+ '@jridgewell/sourcemap-codec': 1.6.0'@jridgewell/trace-mapping': 0.3.31'@jridgewell/[email protected]':@@ -12559,14 +12562,12 @@ snapshots:'@jridgewell/gen-mapping': 0.3.13'@jridgewell/trace-mapping': 0.3.31- '@jridgewell/[email protected]': {}-'@jridgewell/[email protected]': {}'@jridgewell/[email protected]':dependencies:'@jridgewell/resolve-uri': 3.1.2- '@jridgewell/sourcemap-codec': 1.5.5+ '@jridgewell/sourcemap-codec': 1.6.0'@js-sdsl/[email protected]': {}@@ -15922,9 +15923,9 @@ snapshots:dependencies:format: 0.2.2optionalDependencies:- picomatch: 4.0.5+ picomatch: 4.0.7dependencies:@@ -16726,7 +16727,7 @@ snapshots:dependencies:- '@jridgewell/sourcemap-codec': 1.5.5+ '@jridgewell/sourcemap-codec': 1.6.0dependencies:@@ -18695,8 +18696,8 @@ snapshots:dependencies:- fdir: 6.5.0([email protected])- picomatch: 4.0.5+ fdir: 6.5.0([email protected])+ picomatch: 4.0.7@@ -18746,7 +18747,7 @@ snapshots:dependencies:- picomatch: 4.0.5+ picomatch: 4.0.7typescript: 6.0.3optional: true@@ -19017,7 +19018,7 @@ snapshots:[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]):dependencies:lightningcss: 1.33.0- picomatch: 4.0.5+ picomatch: 4.0.7postcss: 8.5.26rolldown: 1.0.0-rc.18tinyglobby: 0.2.17@@ -19034,7 +19035,7 @@ snapshots:[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]):dependencies:lightningcss: 1.33.0- picomatch: 4.0.5+ picomatch: 4.0.7postcss: 8.5.26rolldown: 1.0.0-rc.18tinyglobby: 0.2.17