Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

feat: adopt grid ribbon layout (#7299)

白熱c3880d3036a3
diff --git a/common/debugger/package.json b/common/debugger/package.json
index db8f463d90..e06a4585f6 100644
--- a/common/debugger/package.json
+++ b/common/debugger/package.json
@@ -35,7 +35,7 @@
"@univerjs/design": "workspace:*",
"@univerjs/docs-drawing-ui": "workspace:*",
"@univerjs/engine-render": "workspace:*",
- "@univerjs/icons": "1.29.0",
+ "@univerjs/icons": "1.32.0",
"@univerjs/mockdata": "workspace:*",
"@univerjs/sheets": "workspace:*",
"@univerjs/sheets-drawing-ui": "workspace:*",
diff --git a/common/shared/package.json b/common/shared/package.json
index caec412fc5..b630fb77b2 100644
--- a/common/shared/package.json
+++ b/common/shared/package.json
@@ -51,8 +51,8 @@
"vitest": "^4.1.10"
},
"devDependencies": {
- "@univerjs/icons": "1.29.0",
- "@univerjs/icons-svg": "^1.29.0",
+ "@univerjs/icons": "1.32.0",
+ "@univerjs/icons-svg": "^1.32.0",
"typescript": "^6.0.3",
"vue-tsc": "^3.3.6"
}
diff --git a/e2e/smoking/sheets-ime-input.spec.ts b/e2e/smoking/sheets-ime-input.spec.ts
new file mode 100644
index 0000000000..21205976e1
--- /dev/null
+++ b/e2e/smoking/sheets-ime-input.spec.ts
@@ -0,0 +1,53 @@
+import { expect, test } from '@playwright/test';
+
+const SHEET_MAIN_CANVAS = '[id^="univer-sheet-main-canvas_"]';
+const SHEET_EDITOR_INPUT_CONTAINER = '#univer-doc-selection-container-__INTERNAL_EDITOR__DOCS_NORMAL';
+
+test('keeps the IME anchor on the active cell across edits', async ({ page }) => {
+ await page.goto('/sheets/');
+ await page.waitForTimeout(2000);
+ await page.evaluate(() => window.E2EControllerAPI.loadDefaultSheet());
+ await page.waitForTimeout(3000);
+ await page.locator('#app').evaluate((element) => {
+ element.style.width = 'calc(100% - 240px)';
+ element.style.transform = 'translateX(240px)';
+ });
+ await page.evaluate(() => window.dispatchEvent(new Event('resize')));
+
+ const canvas = page.locator(SHEET_MAIN_CANVAS);
+ const canvasBox = await canvas.boundingBox();
+ expect(canvasBox).not.toBeNull();
+
+ const inputContainer = page.locator(SHEET_EDITOR_INPUT_CONTAINER);
+ const initialAnchorBox = await inputContainer.boundingBox();
+ expect(initialAnchorBox).not.toBeNull();
+ expect(initialAnchorBox!.x).toBeLessThan(canvasBox!.x);
+
+ await page.mouse.click(canvasBox!.x + 200, canvasBox!.y + 120);
+ await expect.poll(async () => (await inputContainer.boundingBox())?.x).toBeGreaterThanOrEqual(canvasBox!.x);
+
+ const client = await page.context().newCDPSession(page);
+ const anchorPositions: Array<{ x: number; y: number }> = [];
+ for (const [composition, text] of [['a', '啊'], ['ai', '爱']]) {
+ await client.send('Input.imeSetComposition', {
+ text: composition,
+ selectionStart: composition.length,
+ selectionEnd: composition.length,
+ replacementStart: 0,
+ replacementEnd: 0,
+ });
+
+ const anchorBox = await inputContainer.boundingBox();
+ expect(anchorBox).not.toBeNull();
+ expect(anchorBox!.x).toBeGreaterThanOrEqual(canvasBox!.x);
+ expect(anchorBox!.x).toBeLessThan(canvasBox!.x + canvasBox!.width);
+ expect(anchorBox!.y).toBeGreaterThanOrEqual(canvasBox!.y);
+ expect(anchorBox!.y).toBeLessThan(canvasBox!.y + canvasBox!.height);
+ anchorPositions.push({ x: anchorBox!.x, y: anchorBox!.y });
+
+ await client.send('Input.insertText', { text });
+ await page.keyboard.press('Enter');
+ }
+
+ expect(anchorPositions[1].y).toBeGreaterThan(anchorPositions[0].y);
+});
diff --git a/e2e/visual-comparison/docs/docs-visual-comparison.spec.ts-snapshots/default-doc-ci-chromium-linux.png b/e2e/visual-comparison/docs/docs-visual-comparison.spec.ts-snapshots/default-doc-ci-chromium-linux.png
index 4a677889c3..8f7e1e0922 100644
Binary files a/e2e/visual-comparison/docs/docs-visual-comparison.spec.ts-snapshots/default-doc-ci-chromium-linux.png and b/e2e/visual-comparison/docs/docs-visual-comparison.spec.ts-snapshots/default-doc-ci-chromium-linux.png differ
diff --git a/e2e/visual-comparison/sheets/sheets-formula-related.spec.ts-snapshots/formula-filter-row-current-worksheet-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-formula-related.spec.ts-snapshots/formula-filter-row-current-worksheet-ci-chromium-linux.png
index ea6787da36..08319aab6f 100644
Binary files a/e2e/visual-comparison/sheets/sheets-formula-related.spec.ts-snapshots/formula-filter-row-current-worksheet-ci-chromium-linux.png and b/e2e/visual-comparison/sheets/sheets-formula-related.spec.ts-snapshots/formula-filter-row-current-worksheet-ci-chromium-linux.png differ
diff --git a/e2e/visual-comparison/sheets/sheets-formula-related.spec.ts-snapshots/formula-filter-row-other-worksheet-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-formula-related.spec.ts-snapshots/formula-filter-row-other-worksheet-ci-chromium-linux.png
index 5b614d37f9..c9a4878eb2 100644
Binary files a/e2e/visual-comparison/sheets/sheets-formula-related.spec.ts-snapshots/formula-filter-row-other-worksheet-ci-chromium-linux.png and b/e2e/visual-comparison/sheets/sheets-formula-related.spec.ts-snapshots/formula-filter-row-other-worksheet-ci-chromium-linux.png differ
diff --git a/e2e/visual-comparison/sheets/sheets-formula-related.spec.ts-snapshots/formula-hide-row-current-worksheet-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-formula-related.spec.ts-snapshots/formula-hide-row-current-worksheet-ci-chromium-linux.png
index 387a965353..64895dc976 100644
Binary files a/e2e/visual-comparison/sheets/sheets-formula-related.spec.ts-snapshots/formula-hide-row-current-worksheet-ci-chromium-linux.png and b/e2e/visual-comparison/sheets/sheets-formula-related.spec.ts-snapshots/formula-hide-row-current-worksheet-ci-chromium-linux.png differ
diff --git a/e2e/visual-comparison/sheets/sheets-gridlines.spec.ts-snapshots/sheets-no-gridlines-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-gridlines.spec.ts-snapshots/sheets-no-gridlines-ci-chromium-linux.png
index 06a48d57e4..7dbf3de70d 100644
Binary files a/e2e/visual-comparison/sheets/sheets-gridlines.spec.ts-snapshots/sheets-no-gridlines-ci-chromium-linux.png and b/e2e/visual-comparison/sheets/sheets-gridlines.spec.ts-snapshots/sheets-no-gridlines-ci-chromium-linux.png differ
diff --git a/e2e/visual-comparison/sheets/sheets-scroll.spec.ts-snapshots/arrayFormulaStatusBarCount-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-scroll.spec.ts-snapshots/arrayFormulaStatusBarCount-ci-chromium-linux.png
index d56286cf52..73e0c21662 100644
Binary files a/e2e/visual-comparison/sheets/sheets-scroll.spec.ts-snapshots/arrayFormulaStatusBarCount-ci-chromium-linux.png and b/e2e/visual-comparison/sheets/sheets-scroll.spec.ts-snapshots/arrayFormulaStatusBarCount-ci-chromium-linux.png differ
diff --git a/e2e/visual-comparison/sheets/sheets-scroll.spec.ts-snapshots/mergedCellsRenderingScrolling-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-scroll.spec.ts-snapshots/mergedCellsRenderingScrolling-ci-chromium-linux.png
index 7f2dee4395..8638c1d821 100644
Binary files a/e2e/visual-comparison/sheets/sheets-scroll.spec.ts-snapshots/mergedCellsRenderingScrolling-ci-chromium-linux.png and b/e2e/visual-comparison/sheets/sheets-scroll.spec.ts-snapshots/mergedCellsRenderingScrolling-ci-chromium-linux.png differ
diff --git a/e2e/visual-comparison/sheets/sheets-scroll.spec.ts-snapshots/renderingAfterScrollByAPI-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-scroll.spec.ts-snapshots/renderingAfterScrollByAPI-ci-chromium-linux.png
index 479a8ed06d..9ac86d779e 100644
Binary files a/e2e/visual-comparison/sheets/sheets-scroll.spec.ts-snapshots/renderingAfterScrollByAPI-ci-chromium-linux.png and b/e2e/visual-comparison/sheets/sheets-scroll.spec.ts-snapshots/renderingAfterScrollByAPI-ci-chromium-linux.png differ
diff --git a/e2e/visual-comparison/sheets/sheets-switching-render-unit.spec.ts-snapshots/switching-render-unit-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-switching-render-unit.spec.ts-snapshots/switching-render-unit-ci-chromium-linux.png
index bbcc3eb35d..239125ad93 100644
Binary files a/e2e/visual-comparison/sheets/sheets-switching-render-unit.spec.ts-snapshots/switching-render-unit-ci-chromium-linux.png and b/e2e/visual-comparison/sheets/sheets-switching-render-unit.spec.ts-snapshots/switching-render-unit-ci-chromium-linux.png differ
diff --git a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/dark-mode-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/dark-mode-ci-chromium-linux.png
index 394a8d2273..753ad9f7ef 100644
Binary files a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/dark-mode-ci-chromium-linux.png and b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/dark-mode-ci-chromium-linux.png differ
diff --git a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/default-sheet-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/default-sheet-ci-chromium-linux.png
index 17dae00233..6803a48ce1 100644
Binary files a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/default-sheet-ci-chromium-linux.png and b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/default-sheet-ci-chromium-linux.png differ
diff --git a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/default-sheet-fullpage-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/default-sheet-fullpage-ci-chromium-linux.png
index f2efbb1630..b35c18c804 100644
Binary files a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/default-sheet-fullpage-ci-chromium-linux.png and b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/default-sheet-fullpage-ci-chromium-linux.png differ
diff --git a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/defaultstyle-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/defaultstyle-ci-chromium-linux.png
index 1bf4c21cb6..a2281438cd 100644
Binary files a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/defaultstyle-ci-chromium-linux.png and b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/defaultstyle-ci-chromium-linux.png differ
diff --git a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/demo-sheet-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/demo-sheet-ci-chromium-linux.png
index 753088f271..0b1808c832 100644
Binary files a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/demo-sheet-ci-chromium-linux.png and b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/demo-sheet-ci-chromium-linux.png differ
diff --git a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/facade-sheet-hooks-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/facade-sheet-hooks-ci-chromium-linux.png
index 1bf4c21cb6..a2281438cd 100644
Binary files a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/facade-sheet-hooks-ci-chromium-linux.png and b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/facade-sheet-hooks-ci-chromium-linux.png differ
diff --git a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/mergedCellsRendering-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/mergedCellsRendering-ci-chromium-linux.png
index c003df1b80..ebb4a3d078 100644
Binary files a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/mergedCellsRendering-ci-chromium-linux.png and b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/mergedCellsRendering-ci-chromium-linux.png differ
diff --git a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/set-force-string-cell-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/set-force-string-cell-ci-chromium-linux.png
index 9beaff315f..f87ed7f703 100644
Binary files a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/set-force-string-cell-ci-chromium-linux.png and b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/set-force-string-cell-ci-chromium-linux.png differ
diff --git a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/set-text-format-number-cell-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/set-text-format-number-cell-ci-chromium-linux.png
index 80950cb48e..7cfbf2451b 100644
Binary files a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/set-text-format-number-cell-ci-chromium-linux.png and b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/set-text-format-number-cell-ci-chromium-linux.png differ
diff --git a/examples/package.json b/examples/package.json
index 8bea78702c..5594ec7ad8 100644
--- a/examples/package.json
+++ b/examples/package.json
@@ -36,7 +36,7 @@
"@univerjs/engine-formula": "workspace:*",
"@univerjs/engine-render": "workspace:*",
"@univerjs/find-replace": "workspace:*",
- "@univerjs/icons": "1.29.0",
+ "@univerjs/icons": "1.32.0",
"@univerjs/mockdata": "workspace:*",
"@univerjs/network": "workspace:*",
"@univerjs/preset-docs-core": "workspace:*",
diff --git a/examples/src/docs/main.ts b/examples/src/docs/main.ts
index ac6c3a3fe5..b1d5f38116 100644
--- a/examples/src/docs/main.ts
+++ b/examples/src/docs/main.ts
@@ -36,7 +36,7 @@ univer.registerPlugin(UniverRenderEnginePlugin);
univer.registerPlugin(UniverFormulaEnginePlugin);
univer.registerPlugin(UniverUIPlugin, {
container: 'app',
- ribbonType: 'classic',
+ ribbonType: 'grid',
});
univer.registerPlugin(UniverDocsPlugin);
diff --git a/examples/src/sheets/main.ts b/examples/src/sheets/main.ts
index 0bb475fdf5..351cb6a04a 100644
--- a/examples/src/sheets/main.ts
+++ b/examples/src/sheets/main.ts
@@ -88,6 +88,7 @@ function createNewInstance() {
[UniverRenderEnginePlugin],
[UniverUIPlugin, {
container: 'app',
+ ribbonType: 'grid',
customFontFamily: {
list: [
{ value: 'PingFang SC', label: '苹方(简)', category: 'sans-serif' },
diff --git a/examples/src/slides/main.ts b/examples/src/slides/main.ts
index 9101ff705d..7791b2539c 100644
--- a/examples/src/slides/main.ts
+++ b/examples/src/slides/main.ts
@@ -26,7 +26,7 @@ const univer = new Univer({
univer.registerPlugin(UniverRenderEnginePlugin);
univer.registerPlugin(UniverUIPlugin, {
container: 'app',
- ribbonType: 'classic',
+ ribbonType: 'grid',
});
univer.registerPlugin(UniverDocsPlugin);
univer.registerPlugin(UniverDocsUIPlugin);
diff --git a/packages/action-recorder/package.json b/packages/action-recorder/package.json
index 31cf06f9d8..27dacdea08 100644
--- a/packages/action-recorder/package.json
+++ b/packages/action-recorder/package.json
@@ -76,7 +76,7 @@
"dependencies": {
"@univerjs/core": "workspace:*",
"@univerjs/design": "workspace:*",
- "@univerjs/icons": "1.29.0",
+ "@univerjs/icons": "1.32.0",
"@univerjs/sheets": "workspace:*",
"@univerjs/sheets-filter": "workspace:*",
"@univerjs/sheets-ui": "workspace:*",
diff --git a/packages/core/src/common/__tests__/utility-primitives.spec.ts b/packages/core/src/common/__tests__/utility-primitives.spec.ts
index a7d0832bd1..268c3b9c89 100644
--- a/packages/core/src/common/__tests__/utility-primitives.spec.ts
+++ b/packages/core/src/common/__tests__/utility-primitives.spec.ts
@@ -25,6 +25,7 @@ import { mergeSets } from '../set';
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
+ vi.unstubAllGlobals();
});
describe('common utility primitives', () => {
@@ -99,6 +100,19 @@ describe('common utility primitives', () => {
it('should schedule immediate macro tasks and allow cancellation', async () => {
const events: string[] = [];
+ const port1Close = vi.fn();
+ const port2Close = vi.fn();
+ vi.stubGlobal('MessageChannel', class {
+ port1 = {
+ onmessage: null as null | (() => void),
+ close: port1Close,
+ };
+
+ port2 = {
+ postMessage: () => queueMicrotask(() => this.port1.onmessage?.()),
+ close: port2Close,
+ };
+ });
await new Promise<void>((resolve) => {
requestImmediateMacroTask(() => {
@@ -108,6 +122,8 @@ describe('common utility primitives', () => {
});
expect(events).toEqual(['ran']);
+ expect(port1Close).toHaveBeenCalledOnce();
+ expect(port2Close).toHaveBeenCalledOnce();
await new Promise<void>((resolve) => {
const cancel = requestImmediateMacroTask(() => {
@@ -119,5 +135,7 @@ describe('common utility primitives', () => {
});
expect(events).toEqual(['ran']);
+ expect(port1Close).toHaveBeenCalledTimes(2);
+ expect(port2Close).toHaveBeenCalledTimes(2);
});
});
diff --git a/packages/core/src/common/request-immediate-macro-task.ts b/packages/core/src/common/request-immediate-macro-task.ts
index 9ec0b91ac8..fc3d4a6474 100644
--- a/packages/core/src/common/request-immediate-macro-task.ts
+++ b/packages/core/src/common/request-immediate-macro-task.ts
@@ -18,20 +18,30 @@ export function requestImmediateMacroTask(callback: (value?: unknown) => void):
const channel = new MessageChannel();
let cancelled = false;
+ const close = () => {
+ channel.port1.onmessage = null;
+ channel.port1.close();
+ channel.port2.close();
+ };
+
const handler = () => {
if (!cancelled) {
+ cancelled = true;
+ close();
callback();
}
};
- // This would cause memory leak. But we cannot use addEventListener because it won't work in web worker.
+ // Use onmessage for web worker compatibility and clear it when the task settles.
channel.port1.onmessage = handler;
channel.port2.postMessage(null);
return () => {
+ if (cancelled) {
+ return;
+ }
+
cancelled = true;
- channel.port1.onmessage = null;
- channel.port1.close();
- channel.port2.close();
+ close();
};
}
diff --git a/packages/core/src/shared/__tests__/rxjs.spec.ts b/packages/core/src/shared/__tests__/rxjs.spec.ts
index 1b5f14c428..69f88b3fb3 100644
--- a/packages/core/src/shared/__tests__/rxjs.spec.ts
+++ b/packages/core/src/shared/__tests__/rxjs.spec.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { BehaviorSubject, of } from 'rxjs';
+import { BehaviorSubject, Observable, of } from 'rxjs';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { afterTime, bufferDebounceTime, convertObservableToBehaviorSubject, fromCallback, takeAfter } from '../rxjs';
@@ -26,6 +26,32 @@ describe('test custom rxjs utils', () => {
expect(acculated).toEqual([1, 2, 3]);
});
+ it('should unsubscribe from the source when a takeAfter subscriber unsubscribes', () => {
+ const teardown = vi.fn();
+ const source$ = new Observable<number>(() => teardown);
+
+ const subscription = source$.pipe(takeAfter(() => false)).subscribe();
+ subscription.unsubscribe();
+
+ expect(teardown).toHaveBeenCalledOnce();
+ });
+
+ it('should stop synchronous source work after the takeAfter condition matches', () => {
+ const visited: number[] = [];
+ const source$ = new Observable<number>((subscriber) => {
+ [1, 2, 3, 4, 5].forEach((value) => {
+ if (!subscriber.closed) {
+ visited.push(value);
+ subscriber.next(value);
+ }
+ });
+ });
+
+ source$.pipe(takeAfter((value) => value === 3)).subscribe();
+
+ expect(visited).toEqual([1, 2, 3]);
+ });
+
describe('test "createTimerObservable$"', () => {
beforeEach(() => vi.useFakeTimers());
diff --git a/packages/core/src/shared/rxjs.ts b/packages/core/src/shared/rxjs.ts
index b4ad4c0983..3595534520 100644
--- a/packages/core/src/shared/rxjs.ts
+++ b/packages/core/src/shared/rxjs.ts
@@ -16,7 +16,7 @@
import type { OperatorFunction } from 'rxjs';
import type { IDisposable } from '../common/di';
-import { BehaviorSubject, debounceTime, map, Observable, ReplaySubject, take, tap } from 'rxjs';
+import { BehaviorSubject, debounceTime, map, Observable, ReplaySubject, take, takeWhile, tap } from 'rxjs';
type CallbackFn<T extends readonly unknown[]> = (cb: (...args: T) => void) => IDisposable;
@@ -41,20 +41,7 @@ export function fromCallback<T extends readonly unknown[]>(callback: CallbackFn<
*/
export function takeAfter<T>(callback: (value: T) => boolean) {
return function complateAfter(source: Observable<T>) {
- return new Observable<T>((subscriber) => {
- source.subscribe({
- next: (v) => {
- subscriber.next(v);
- if (callback(v)) {
- subscriber.complete();
- }
- },
- complete: () => subscriber.complete(),
- error: (error) => subscriber.error(error),
- });
-
- return () => subscriber.unsubscribe();
- });
+ return source.pipe(takeWhile((value) => !callback(value), true));
};
}
diff --git a/packages/design/package.json b/packages/design/package.json
index 273f1fa954..556c6dfb28 100644
--- a/packages/design/package.json
+++ b/packages/design/package.json
@@ -81,9 +81,10 @@
"@radix-ui/react-popover": "^1.1.19",
"@radix-ui/react-separator": "^1.1.11",
"@radix-ui/react-slot": "^1.3.0",
- "@univerjs/icons": "1.29.0",
+ "@univerjs/icons": "1.32.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
+ "cmdk": "1.1.1",
"react-transition-group": "^4.4.5",
"sonner": "^2.0.7",
"tailwind-merge": "2.6.0"
diff --git a/packages/design/src/components/command/Command.tsx b/packages/design/src/components/command/Command.tsx
new file mode 100644
index 0000000000..9411cc3ff2
--- /dev/null
+++ b/packages/design/src/components/command/Command.tsx
@@ -0,0 +1,138 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ComponentProps } from 'react';
+import { SearchIcon } from '@univerjs/icons';
+import { Command as CommandPrimitive } from 'cmdk';
+import { clsx } from '../../helper/clsx';
+
+export function Command({ className, ...props }: ComponentProps<typeof CommandPrimitive>) {
+ return (
+ <CommandPrimitive
+ data-slot="command"
+ className={clsx(`
+ univer-flex univer-h-full univer-w-full univer-flex-col univer-overflow-hidden univer-rounded-md
+ univer-bg-white univer-text-gray-900
+ dark:!univer-bg-gray-700 dark:!univer-text-white
+ `, className)}
+ {...props}
+ />
+ );
+}
+
+export function CommandInput({ className, ...props }: ComponentProps<typeof CommandPrimitive.Input>) {
+ return (
+ <div
+ data-slot="command-input-wrapper"
+ className={`
+ univer-flex univer-h-10 univer-items-center univer-gap-2 univer-border-0 univer-border-b
+ univer-border-solid univer-border-gray-200 univer-px-3
+ dark:!univer-border-gray-600
+ [&>svg]:univer-size-4 [&>svg]:univer-shrink-0 [&>svg]:univer-text-gray-400
+ `}
+ >
+ <SearchIcon />
+ <CommandPrimitive.Input
+ data-slot="command-input"
+ className={clsx(`
+ univer-h-10 univer-w-full univer-border-none univer-bg-transparent univer-text-sm univer-outline-none
+ placeholder:univer-text-gray-400
+ `, className)}
+ {...props}
+ />
+ </div>
+ );
+}
+
+export function CommandList({ className, ...props }: ComponentProps<typeof CommandPrimitive.List>) {
+ return (
+ <CommandPrimitive.List
+ data-slot="command-list"
+ className={clsx(`
+ univer-max-h-[300px] univer-overflow-y-auto univer-overflow-x-hidden univer-p-1 [scroll-padding-block:4px]
+ `, className)}
+ {...props}
+ />
+ );
+}
+
+export function CommandEmpty({ className, ...props }: ComponentProps<typeof CommandPrimitive.Empty>) {
+ return (
+ <CommandPrimitive.Empty
+ data-slot="command-empty"
+ className={clsx('univer-py-6 univer-text-center univer-text-sm univer-text-gray-500', className)}
+ {...props}
+ />
+ );
+}
+
+export function CommandGroup({ className, ...props }: ComponentProps<typeof CommandPrimitive.Group>) {
+ return (
+ <CommandPrimitive.Group
+ data-slot="command-group"
+ className={clsx(`
+ univer-overflow-hidden univer-p-1
+ [&_[cmdk-group-heading]]:univer-px-2 [&_[cmdk-group-heading]]:univer-py-1.5
+ [&_[cmdk-group-heading]]:univer-text-xs [&_[cmdk-group-heading]]:univer-font-medium
+ [&_[cmdk-group-heading]]:univer-text-gray-500
+ `, className)}
+ {...props}
+ />
+ );
+}
+
+export function CommandItem({ className, ...props }: ComponentProps<typeof CommandPrimitive.Item>) {
+ return (
+ <CommandPrimitive.Item
+ data-slot="command-item"
+ className={clsx(`
+ univer-relative univer-flex univer-cursor-default univer-select-none univer-items-center univer-gap-2
+ univer-rounded univer-px-2 univer-py-1.5 univer-text-sm univer-outline-none
+ data-[disabled=true]:univer-pointer-events-none
+ data-[selected=true]:univer-bg-gray-100
+ data-[disabled=true]:univer-opacity-50
+ dark:data-[selected=true]:!univer-bg-gray-600
+ `, className)}
+ {...props}
+ />
+ );
+}
+
+export function CommandSeparator({ className, ...props }: ComponentProps<typeof CommandPrimitive.Separator>) {
+ return (
+ <CommandPrimitive.Separator
+ data-slot="command-separator"
+ className={clsx(`
+ univer-my-1 univer-h-px univer-bg-gray-200
+ dark:!univer-bg-gray-600
+ `, className)}
+ {...props}
+ />
+ );
+}
+
+export function CommandShortcut({ className, ...props }: ComponentProps<'span'>) {
+ return (
+ <span
+ data-slot="command-shortcut"
+ className={clsx(`
+ univer-ml-auto univer-text-xs univer-tracking-widest univer-text-gray-400
+ rtl:univer-ml-0 rtl:univer-mr-auto
+ `, className)}
+ {...props}
+ />
+ );
+}
diff --git a/packages/design/src/components/command/__tests__/index.spec.tsx b/packages/design/src/components/command/__tests__/index.spec.tsx
new file mode 100644
index 0000000000..7e517e4ab8
--- /dev/null
+++ b/packages/design/src/components/command/__tests__/index.spec.tsx
@@ -0,0 +1,48 @@
+/**
+ * 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, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from '../Command';
+
+afterEach(cleanup);
+
+describe('Command', () => {
+ it('renders grouped items and selects an enabled result', () => {
+ const onSelect = vi.fn();
+ render(
+ <Command>
+ <CommandInput aria-label="Search" />
+ <CommandList>
+ <CommandEmpty>None</CommandEmpty>
+ <CommandGroup heading="Actions">
+ <CommandItem value="run" onSelect={onSelect}>Run</CommandItem>
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ );
+
+ fireEvent.click(screen.getByText('Run'));
+ expect(onSelect).toHaveBeenCalledWith('run');
+ });
+});
diff --git a/packages/design/src/components/input-number/InputNumber.stories.tsx b/packages/design/src/components/input-number/InputNumber.stories.tsx
index f51fffc1ad..e9dda8ef6a 100644
--- a/packages/design/src/components/input-number/InputNumber.stories.tsx
+++ b/packages/design/src/components/input-number/InputNumber.stories.tsx
@@ -67,6 +67,12 @@ export const InputNumberHideControls = {
},
};
+export const InputNumberAllowClear = {
+ render() {
+ return <InputNumber allowClear allowEmpty defaultValue={12} />;
+ },
+};
+
export const InputNumberRtl = {
render() {
return (
diff --git a/packages/design/src/components/input-number/InputNumber.tsx b/packages/design/src/components/input-number/InputNumber.tsx
index f567f0ebc6..23d647b86a 100644
--- a/packages/design/src/components/input-number/InputNumber.tsx
+++ b/packages/design/src/components/input-number/InputNumber.tsx
@@ -40,6 +40,7 @@ export interface IInputNumberProps
onKeyDown?: (e: KeyboardEvent<HTMLInputElement>) => void;
onPressEnter?: (e: KeyboardEvent<HTMLInputElement>) => void;
allowEmpty?: boolean;
+ allowClear?: boolean;
}
export const InputNumber = forwardRef<HTMLInputElement, IInputNumberProps>(
@@ -65,6 +66,7 @@ export const InputNumber = forwardRef<HTMLInputElement, IInputNumberProps>(
onFocus,
onBlur,
allowEmpty = false,
+ allowClear = false,
},
ref
) => {
@@ -338,6 +340,7 @@ export const InputNumber = forwardRef<HTMLInputElement, IInputNumberProps>(
className={clsx('univer-box-border', inputClassName)}
size={size}
value={inputValue}
+ allowClear={allowClear}
disabled={disabled}
onChange={handleInputChange}
onFocus={onFocus}
diff --git a/packages/design/src/components/input-number/__tests__/index.spec.tsx b/packages/design/src/components/input-number/__tests__/index.spec.tsx
index fb65b83063..5729fd2256 100644
--- a/packages/design/src/components/input-number/__tests__/index.spec.tsx
+++ b/packages/design/src/components/input-number/__tests__/index.spec.tsx
@@ -159,6 +159,18 @@ describe('InputNumber', () => {
expect(input).toBeDisabled();
});
+ it('should clear an optional value while keeping increment and decrement controls', () => {
+ const onLocalChange = vi.fn();
+ const { container } = render(<InputNumber allowClear allowEmpty defaultValue={3} onChange={onLocalChange} />);
+
+ const clearButton = container.querySelector('button') as HTMLButtonElement;
+ expect(clearButton).not.toBeNull();
+ expect(container.querySelectorAll('[role="button"]')).toHaveLength(2);
+
+ fireEvent.click(clearButton);
+ expect(onLocalChange).toHaveBeenCalledWith(null);
+ });
+
it('should support ref callback and object ref', () => {
const callbackRef = vi.fn();
const objectRef = { current: null as HTMLInputElement | null };
diff --git a/packages/design/src/index.ts b/packages/design/src/index.ts
index dc191dedd4..9f53c3cb69 100644
--- a/packages/design/src/index.ts
+++ b/packages/design/src/index.ts
@@ -36,6 +36,16 @@ export type { ICheckboxProps } from './components/checkbox/Checkbox';
export { ColorPicker } from './components/color-picker/ColorPicker';
export type { IColorPickerProps } from './components/color-picker/ColorPicker';
export { ColorPresets } from './components/color-picker/ColorPresets';
+export {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+ CommandSeparator,
+ CommandShortcut,
+} from './components/command/Command';
export { ConfigContext, ConfigProvider } from './components/config-provider/ConfigProvider';
export type { IConfigProviderProps } from './components/config-provider/ConfigProvider';
export { Confirm } from './components/confirm/Confirm';
diff --git a/packages/docs-hyper-link-ui/package.json b/packages/docs-hyper-link-ui/package.json
index d6c9b669e1..a6e6d4b146 100644
--- a/packages/docs-hyper-link-ui/package.json
+++ b/packages/docs-hyper-link-ui/package.json
@@ -80,7 +80,7 @@
"@univerjs/docs-hyper-link": "workspace:*",
"@univerjs/docs-ui": "workspace:*",
"@univerjs/engine-render": "workspace:*",
- "@univerjs/icons": "1.29.0",
+ "@univerjs/icons": "1.32.0",
"@univerjs/ui": "workspace:*"
},
"devDependencies": {
diff --git a/packages/docs-quick-insert-ui/package.json b/packages/docs-quick-insert-ui/package.json
index d49c0988a0..ae67063fd3 100644
--- a/packages/docs-quick-insert-ui/package.json
+++ b/packages/docs-quick-insert-ui/package.json
@@ -83,7 +83,7 @@
"@univerjs/drawing": "workspace:*",
"@univerjs/drawing-ui": "workspace:*",
"@univerjs/engine-render": "workspace:*",
- "@univerjs/icons": "1.29.0",
+ "@univerjs/icons": "1.32.0",
"@univerjs/ui": "workspace:*"
},
"devDependencies": {
diff --git a/packages/docs-thread-comment-ui/package.json b/packages/docs-thread-comment-ui/package.json
index 774c2c3394..3ba65299ed 100644
--- a/packages/docs-thread-comment-ui/package.json
+++ b/packages/docs-thread-comment-ui/package.json
@@ -78,7 +78,7 @@
"@univerjs/docs": "workspace:*",
"@univerjs/docs-ui": "workspace:*",
"@univerjs/engine-render": "workspace:*",
- "@univerjs/icons": "1.29.0",
+ "@univerjs/icons": "1.32.0",
"@univerjs/thread-comment": "workspace:*",
"@univerjs/thread-comment-ui": "workspace:*",
"@univerjs/ui": "workspace:*"
diff --git a/packages/docs-ui/package.json b/packages/docs-ui/package.json
index b737ff645c..bc0fe12477 100644
--- a/packages/docs-ui/package.json
+++ b/packages/docs-ui/package.json
@@ -89,7 +89,7 @@
"@univerjs/design": "workspace:*",
"@univerjs/docs": "workspace:*",
"@univerjs/engine-render": "workspace:*",
- "@univerjs/icons": "1.29.0",
+ "@univerjs/icons": "1.32.0",
"@univerjs/ui": "workspace:*"
},
"devDependencies": {
diff --git a/packages/docs-ui/src/menu/__tests__/menu-lifecycle.spec.ts b/packages/docs-ui/src/menu/__tests__/menu-lifecycle.spec.ts
new file mode 100644
index 0000000000..c4f1dc6018
--- /dev/null
+++ b/packages/docs-ui/src/menu/__tests__/menu-lifecycle.spec.ts
@@ -0,0 +1,110 @@
+/**
+ * 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 { Subscriber } from 'rxjs';
+import { ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { DocSelectionManagerService } from '@univerjs/docs';
+import { DocumentEditArea, IRenderManagerService } from '@univerjs/engine-render';
+import { Observable } from 'rxjs';
+import { describe, expect, it } from 'vitest';
+import { HeaderFooterMenuItemFactory, TableMenuFactory } from '../menu';
+
+function createTrackedObservable<T>() {
+ const subscribers = new Set<Subscriber<T>>();
+ const observable = new Observable<T>((subscriber) => {
+ subscribers.add(subscriber);
+ return () => subscribers.delete(subscriber);
+ });
+
+ return {
+ observable,
+ emit: (value: T) => subscribers.forEach((subscriber) => subscriber.next(value)),
+ get subscriberCount() {
+ return subscribers.size;
+ },
+ };
+}
+
+describe('doc menu observable lifecycles', () => {
+ it('disposes header and footer menu listeners when no document is active', () => {
+ const focused = createTrackedObservable<string | null>();
+ let commandListenerCount = 0;
+ const univerInstanceService = {
+ focused$: focused.observable,
+ getCurrentUnitOfType: () => null,
+ getFocusedUnit: () => null,
+ getUnit: () => null,
+ getUnitType: () => UniverInstanceType.UNIVER_DOC,
+ };
+ const commandService = {
+ onCommandExecuted: () => {
+ commandListenerCount++;
+ return { dispose: () => commandListenerCount-- };
+ },
+ };
+ const accessor = {
+ get: (token: unknown) => {
+ if (token === IUniverInstanceService) return univerInstanceService;
+ if (token === ICommandService) return commandService;
+ throw new Error('Unexpected dependency');
+ },
+ };
+
+ const subscription = HeaderFooterMenuItemFactory(accessor as never).hidden$!.subscribe();
+ expect(focused.subscriberCount).toBe(2);
+ expect(commandListenerCount).toBe(1);
+
+ subscription.unsubscribe();
+ expect(focused.subscriberCount).toBe(0);
+ expect(commandListenerCount).toBe(0);
+ });
+
+ it('replaces and disposes the table menu edit-area listener when focus changes', () => {
+ const focused = createTrackedObservable<string | null>();
+ const editArea = createTrackedObservable<DocumentEditArea>();
+ const viewModel = { editAreaChange$: editArea.observable };
+ const univerInstanceService = {
+ focused$: focused.observable,
+ getCurrentUnitOfType: () => null,
+ getFocusedUnit: () => null,
+ getUnitType: () => UniverInstanceType.UNIVER_DOC,
+ };
+ const renderManagerService = {
+ getRenderById: () => ({
+ with: () => ({ getViewModel: () => viewModel }),
+ }),
+ };
+ const accessor = {
+ get: (token: unknown) => {
+ if (token === IUniverInstanceService) return univerInstanceService;
+ if (token === IRenderManagerService) return renderManagerService;
+ if (token === DocSelectionManagerService) return {};
+ throw new Error('Unexpected dependency');
+ },
+ };
+
+ const subscription = TableMenuFactory(accessor as never).hidden$!.subscribe();
+ focused.emit('doc-1');
+ expect(editArea.subscriberCount).toBe(1);
+
+ focused.emit('doc-2');
+ expect(editArea.subscriberCount).toBe(1);
+
+ editArea.emit(DocumentEditArea.BODY);
+ subscription.unsubscribe();
+ expect(editArea.subscriberCount).toBe(0);
+ });
+});
diff --git a/packages/docs-ui/src/menu/menu.ts b/packages/docs-ui/src/menu/menu.ts
index bd375edbbe..2366e09b12 100644
--- a/packages/docs-ui/src/menu/menu.ts
+++ b/packages/docs-ui/src/menu/menu.ts
@@ -87,8 +87,8 @@ import { CreateDocTableCommand } from '../commands/commands/table/doc-table-crea
import { DocCreateTableOperation } from '../commands/operations/doc-create-table.operation';
import { DocOpenPageSettingCommand } from '../commands/operations/open-page-setting.operation';
import { getCommandSkeleton } from '../commands/util';
-import { DocMenuStyleService } from '../services/doc-menu-style.service';
import { IDocEmbedRuntimeFocusCoordinator } from '../services/doc-embed-integration.service';
+import { DocMenuStyleService } from '../services/doc-menu-style.service';
import { BULLET_LIST_TYPE_COMPONENT, ORDER_LIST_TYPE_COMPONENT } from '../views/list-type-picker/index';
export function shouldSuppressDocMenuStateRefresh(accessor: IAccessor): boolean {
@@ -123,7 +123,11 @@ function getInsertTableHiddenObservable(
const renderManagerService = accessor.get(IRenderManagerService);
return new Observable((subscriber) => {
+ let editAreaSubscription: { unsubscribe: () => void } | null = null;
const subscription = univerInstanceService.focused$.subscribe((unitId) => {
+ editAreaSubscription?.unsubscribe();
+ editAreaSubscription = null;
+
if (unitId == null) {
return subscriber.next(true);
}
@@ -140,12 +144,15 @@ function getInsertTableHiddenObservable(
const viewModel = currentRender.with(DocSkeletonManagerService).getViewModel();
- viewModel.editAreaChange$.subscribe((editArea) => {
+ editAreaSubscription = viewModel.editAreaChange$.subscribe((editArea) => {
subscriber.next(editArea === DocumentEditArea.HEADER || editArea === DocumentEditArea.FOOTER);
});
});
- return () => subscription.unsubscribe();
+ return () => {
+ editAreaSubscription?.unsubscribe();
+ subscription.unsubscribe();
+ };
});
}
@@ -232,12 +239,8 @@ function getHeaderFooterMenuHiddenObservable(
const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
- if (docDataModel == null) {
- return subscriber.next(true);
- }
-
const documentFlavor = docDataModel?.getSnapshot().documentStyle.documentFlavor;
- subscriber.next(documentFlavor !== DocumentFlavor.TRADITIONAL);
+ subscriber.next(docDataModel == null || documentFlavor !== DocumentFlavor.TRADITIONAL);
return () => {
subscription0.dispose();
diff --git a/packages/docs-ui/src/menu/schema.ts b/packages/docs-ui/src/menu/schema.ts
index 096d3209df..0a97543197 100644
--- a/packages/docs-ui/src/menu/schema.ts
+++ b/packages/docs-ui/src/menu/schema.ts
@@ -207,42 +207,52 @@ export const menuSchema: MenuSchemaType = {
[RibbonStartGroup.FORMAT]: {
[SetInlineFormatBoldCommand.id]: {
order: 0,
+ gridLayout: { row: 2, column: 1 },
menuItemFactory: BoldMenuItemFactory,
},
[SetInlineFormatItalicCommand.id]: {
order: 1,
+ gridLayout: { row: 2, column: 2 },
menuItemFactory: ItalicMenuItemFactory,
},
[SetInlineFormatUnderlineCommand.id]: {
order: 2,
+ gridLayout: { row: 2, column: 3 },
menuItemFactory: UnderlineMenuItemFactory,
},
[SetInlineFormatStrikethroughCommand.id]: {
order: 3,
+ gridLayout: { row: 2, column: 4 },
menuItemFactory: StrikeThroughMenuItemFactory,
},
[SetInlineFormatSubscriptCommand.id]: {
order: 4,
+ gridLayout: { row: 2, column: 5 },
menuItemFactory: SubscriptMenuItemFactory,
},
[SetInlineFormatSuperscriptCommand.id]: {
order: 5,
+ gridLayout: { row: 2, column: 6 },
menuItemFactory: SuperscriptMenuItemFactory,
},
[SetParagraphNamedStyleCommand.id]: {
order: 5.5,
+ gridLayout: { row: 1, column: 1, columnSpan: 2, width: 100 },
menuItemFactory: HeadingSelectorMenuItemFactory,
},
[SetInlineFormatFontSizeCommand.id]: {
order: 6,
+ gridLayout: { row: 1, column: 7, width: 64 },
menuItemFactory: FontSizeSelectorMenuItemFactory,
},
[SetInlineFormatFontFamilyCommand.id]: {
order: 7,
+ gridLayout: { row: 1, column: 3, columnSpan: 4, width: 160 },
menuItemFactory: FontFamilySelectorMenuItemFactory,
},
[SetInlineFormatTextColorCommand.id]: {
order: 8,
+ gridLayout: { row: 2, column: 7 },
menuItemFactory: TextColorSelectorMenuItemFactory,
[ResetInlineFormatTextColorCommand.id]: {
order: 0,
@@ -251,6 +261,7 @@ export const menuSchema: MenuSchemaType = {
},
[SetInlineFormatTextBackgroundColorCommand.id]: {
order: 9,
+ gridLayout: { row: 2, column: 8 },
menuItemFactory: BackgroundColorSelectorMenuItemFactory,
[ResetInlineFormatTextBackgroundColorCommand.id]: {
order: 0,
@@ -261,22 +272,27 @@ export const menuSchema: MenuSchemaType = {
[RibbonStartGroup.LAYOUT]: {
[AlignOperationCommand.id]: {
order: 2,
+ gridLayout: { row: 1, column: 1 },
menuItemFactory: AlignMenuItemFactory,
},
[OrderListCommand.id]: {
order: 7,
+ gridLayout: { row: 2, column: 1 },
menuItemFactory: OrderListMenuItemFactory,
},
[BulletListCommand.id]: {
order: 8,
+ gridLayout: { row: 1, column: 2 },
menuItemFactory: BulletListMenuItemFactory,
},
[CheckListCommand.id]: {
order: 9,
+ gridLayout: { row: 2, column: 2 },
menuItemFactory: CheckListMenuItemFactory,
},
[OpenHeaderFooterPanelCommand.id]: {
order: 10,
+ gridLayout: { row: 1, column: 3, rowSpan: 2, showLabel: true },
menuItemFactory: HeaderFooterMenuItemFactory,
},
// [SwitchDocModeCommand.id]: {
@@ -285,12 +301,14 @@ export const menuSchema: MenuSchemaType = {
// },
[DocOpenPageSettingCommand.id]: {
order: 12,
+ gridLayout: { row: 1, column: 4, rowSpan: 2, showLabel: true },
menuItemFactory: PageSettingMenuItemFactory,
},
},
[RibbonInsertGroup.MEDIA]: {
[TABLE_MENU_ID]: {
order: 2,
+ gridLayout: { row: 1, column: 1, rowSpan: 2, showLabel: true },
menuItemFactory: TableMenuFactory,
[DocCreateTableOperation.id]: {
order: 0,
@@ -299,6 +317,7 @@ export const menuSchema: MenuSchemaType = {
},
[HorizontalLineCommand.id]: {
order: 3,
+ gridLayout: { row: 1, column: 2, rowSpan: 2, showLabel: true },
menuItemFactory: HorizontalLineFactory,
},
},
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.ts
index 351ea4db1c..de74cbd408 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
@@ -1325,6 +1325,7 @@ describe('DocSelectionRenderService', () => {
service.activate(35, 47);
+ expect(container.style.position).toBe('fixed');
expect(container.style.left).toBe('-65px');
expect(container.style.top).toBe('-153px');
});
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.ts
index d3d1103a8e..915476d635 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
@@ -372,10 +372,23 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
this._updateInputPosition();
}
+ setInputPosition(x: number, y: number) {
+ this._positionInput(x, y);
+ }
+
activate(x: number, y: number, force = false) {
+ this._positionInput(x, y);
+
+ if ((force && !this._shouldPreserveExternalFocus()) || (!force && this.canFocusing)) {
+ this.focus();
+ }
+ }
+
+ private _positionInput(x: number, y: number) {
// Keep the hidden editor inside the Portal subtree when possible to avoid focus-trap loops,
// then compensate coordinates if a transformed ancestor changes the fixed containing block.
this._ensureHostContainer();
+ this._container.style.position = 'fixed';
let left = x;
let top = y;
const fixedContainer = this._container.offsetParent;
@@ -388,10 +401,6 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
this._container.style.left = `${left}px`;
this._container.style.top = `${top}px`;
this._container.style.zIndex = '1000';
-
- if ((force && !this._shouldPreserveExternalFocus()) || (!force && this.canFocusing)) {
- this.focus();
- }
}
hasFocus(): boolean {
diff --git a/packages/drawing-ui/package.json b/packages/drawing-ui/package.json
index e321d15ed4..bdb9202091 100644
--- a/packages/drawing-ui/package.json
+++ b/packages/drawing-ui/package.json
@@ -78,7 +78,7 @@
"@univerjs/design": "workspace:*",
"@univerjs/drawing": "workspace:*",
"@univerjs/engine-render": "workspace:*",
- "@univerjs/icons": "1.29.0",
+ "@univerjs/icons": "1.32.0",
"@univerjs/ui": "workspace:*"
},
"devDependencies": {
diff --git a/packages/drawing-ui/src/menu/arrange.menu.ts b/packages/drawing-ui/src/menu/arrange.menu.ts
index c0222f73c2..7a40a6e122 100644
--- a/packages/drawing-ui/src/menu/arrange.menu.ts
+++ b/packages/drawing-ui/src/menu/arrange.menu.ts
@@ -14,9 +14,12 @@
* limitations under the License.
*/
+import type { IAccessor } from '@univerjs/core';
import type { IMenuButtonItem, IMenuSelectorItem } from '@univerjs/ui';
import type { LocaleKey } from '../locale/types';
+import { IDrawingManagerService } from '@univerjs/drawing';
import { MenuItemType } from '@univerjs/ui';
+import { map, startWith } from 'rxjs';
import {
SetDrawingArrangeBackOperation,
SetDrawingArrangeBackwardOperation,
@@ -25,12 +28,18 @@ import {
} from '../commands/operations/drawing-arrange.operation';
export const DRAWING_ARRANGE_CONTEXT_MENU_ID = 'contextMenu.drawing-arrange';
-export function DrawingArrangeContextMenuItemFactory(): IMenuSelectorItem<LocaleKey> {
+export function DrawingArrangeContextMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<LocaleKey> {
+ const drawingManagerService = accessor.get(IDrawingManagerService);
+
return {
id: DRAWING_ARRANGE_CONTEXT_MENU_ID,
type: MenuItemType.SUBITEMS,
icon: 'TopmostIcon',
title: 'drawing-ui.image-panel.arrange.title',
+ hidden$: drawingManagerService.focus$.pipe(
+ startWith(drawingManagerService.getFocusDrawings()),
+ map((drawings) => drawings.length === 0)
+ ),
};
}
diff --git a/packages/find-replace/package.json b/packages/find-replace/package.json
index e6e75726b3..484fd9d5a2 100644
--- a/packages/find-replace/package.json
+++ b/packages/find-replace/package.json
@@ -77,7 +77,7 @@
"@univerjs/core": "workspace:*",
"@univerjs/design": "workspace:*",
"@univerjs/engine-render": "workspace:*",
- "@univerjs/icons": "1.29.0",
+ "@univerjs/icons": "1.32.0",
"@univerjs/ui": "workspace:*"
},
"devDependencies": {
diff --git a/packages/find-replace/src/menu/schema.ts b/packages/find-replace/src/menu/schema.ts
index e9a7152248..37569540b8 100644
--- a/packages/find-replace/src/menu/schema.ts
+++ b/packages/find-replace/src/menu/schema.ts
@@ -23,6 +23,7 @@ export const menuSchema: MenuSchemaType = {
[RibbonDataGroup.ORGANIZATION]: {
[OpenFindDialogOperation.id]: {
order: 2,
+ gridLayout: { row: 1, column: 3 },
menuItemFactory: FindReplaceMenuItemFactory,
},
},
diff --git a/packages/network/src/services/http/interceptors/__tests__/merge-interceptor.spec.ts b/packages/network/src/services/http/interceptors/__tests__/merge-interceptor.spec.ts
index faa7d8b183..fe79dd7f51 100644
--- a/packages/network/src/services/http/interceptors/__tests__/merge-interceptor.spec.ts
+++ b/packages/network/src/services/http/interceptors/__tests__/merge-interceptor.spec.ts
@@ -16,6 +16,9 @@
import type { Injector } from '@univerjs/core';
import type { MockHTTPImplementation } from '../../__tests__/http-testing-utils';
+import type { HTTPHandlerFn } from '../../interceptor';
+import type { HTTPEvent } from '../../response';
+import { Observable } from 'rxjs';
import { afterEach, beforeEach, describe, expect, it, vitest } from 'vitest';
import { createHTTPTestBed } from '../../__tests__/http-testing-utils';
import { HTTPHeaders } from '../../headers';
@@ -105,4 +108,70 @@ describe('test "HTTPMergeInterceptor"', () => {
// The first two create requests and the last merge result in a new request, so the sequence number is 2
emitSuccess(2, response);
});
+
+ it('does not send a queued request after its subscriber unsubscribes', async () => {
+ let resolveFetch!: (value: boolean) => void;
+ const next: HTTPHandlerFn = vitest.fn(() => new Observable<HTTPEvent<unknown>>());
+ const interceptor = MergeInterceptorFactory<string, unknown>({
+ isMatch: () => true,
+ getParamsFromRequest: (request) => request.url,
+ mergeParamsToRequest: (_list, request) => request,
+ }, {
+ fetchCheck: () => new Promise((resolve) => {
+ resolveFetch = resolve;
+ }),
+ });
+ const request = new HTTPRequest('GET', 'http://example.com');
+
+ const subscription = interceptor(request, next).subscribe();
+ subscription.unsubscribe();
+ resolveFetch(true);
+ await Promise.resolve();
+
+ expect(next).not.toHaveBeenCalled();
+ });
+
+ it('cancels an active merged request when its subscriber unsubscribes', async () => {
+ const teardown = vitest.fn();
+ const next: HTTPHandlerFn = vitest.fn(() => new Observable<HTTPEvent<unknown>>(() => teardown));
+ const interceptor = MergeInterceptorFactory<string, unknown>({
+ isMatch: () => true,
+ getParamsFromRequest: (request) => request.url,
+ mergeParamsToRequest: (_list, request) => request,
+ }, {
+ fetchCheck: () => Promise.resolve(true),
+ });
+ const request = new HTTPRequest('GET', 'http://example.com');
+
+ const subscription = interceptor(request, next).subscribe();
+ await Promise.resolve();
+ expect(next).toHaveBeenCalledOnce();
+
+ subscription.unsubscribe();
+ expect(teardown).toHaveBeenCalledOnce();
+ });
+
+ it('keeps an active merged request until every subscriber unsubscribes', async () => {
+ const teardown = vitest.fn();
+ const next: HTTPHandlerFn = vitest.fn(() => new Observable<HTTPEvent<unknown>>(() => teardown));
+ const fetchCheck = vitest.fn()
+ .mockResolvedValueOnce(false)
+ .mockResolvedValueOnce(true);
+ const interceptor = MergeInterceptorFactory<string, unknown>({
+ isMatch: () => true,
+ getParamsFromRequest: (request) => request.url,
+ mergeParamsToRequest: (_list, request) => request,
+ }, { fetchCheck });
+
+ const firstSubscription = interceptor(new HTTPRequest('GET', 'http://example.com/first'), next).subscribe();
+ const secondSubscription = interceptor(new HTTPRequest('GET', 'http://example.com/second'), next).subscribe();
+ await Promise.resolve();
+ expect(next).toHaveBeenCalledOnce();
+
+ firstSubscription.unsubscribe();
+ expect(teardown).not.toHaveBeenCalled();
+
+ secondSubscription.unsubscribe();
+ expect(teardown).toHaveBeenCalledOnce();
+ });
});
diff --git a/packages/network/src/services/http/interceptors/__tests__/threshold-interceptor.spec.ts b/packages/network/src/services/http/interceptors/__tests__/threshold-interceptor.spec.ts
index f2b60d533a..d9fc024b88 100644
--- a/packages/network/src/services/http/interceptors/__tests__/threshold-interceptor.spec.ts
+++ b/packages/network/src/services/http/interceptors/__tests__/threshold-interceptor.spec.ts
@@ -17,12 +17,13 @@
import type { Injector } from '@univerjs/core';
import type { MockHTTPImplementation } from '../../__tests__/http-testing-utils';
import { awaitTime } from '@univerjs/core';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { Observable } from 'rxjs';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createHTTPTestBed } from '../../__tests__/http-testing-utils';
import { HTTPHeaders } from '../../headers';
import { HTTPService } from '../../http.service';
import { IHTTPImplementation } from '../../implementations/implementation';
-import { __TEST_ONLY_RESET_REQUEST_UID_DO_NOT_USE_IN_PRODUCTION } from '../../request';
+import { __TEST_ONLY_RESET_REQUEST_UID_DO_NOT_USE_IN_PRODUCTION, HTTPRequest } from '../../request';
import { HTTPResponse, HTTPResponseError } from '../../response';
import { ThresholdInterceptorFactory } from '../threshold-interceptor';
@@ -135,4 +136,15 @@ describe('test "HTTPThresholdInterceptor"', () => {
emitSuccess(1);
expect(await request1).toBeDefined();
});
+
+ it('should cancel an active request when its subscriber unsubscribes', () => {
+ const teardown = vi.fn();
+ const request = new HTTPRequest('GET', 'http://example.com');
+ const request$ = ThresholdInterceptorFactory()(request, () => new Observable(() => teardown));
+
+ const subscription = request$.subscribe();
+ subscription.unsubscribe();
+
+ expect(teardown).toHaveBeenCalledOnce();
+ });
});
diff --git a/packages/network/src/services/http/interceptors/merge-interceptor.ts b/packages/network/src/services/http/interceptors/merge-interceptor.ts
index 8c0c3b45b5..854018b83e 100644
--- a/packages/network/src/services/http/interceptors/merge-interceptor.ts
+++ b/packages/network/src/services/http/interceptors/merge-interceptor.ts
@@ -14,9 +14,10 @@
* limitations under the License.
*/
+import type { Subscription } from 'rxjs';
import type { HTTPHandlerFn } from '../interceptor';
import type { HTTPRequest } from '../request';
-import { noop } from '@univerjs/core';
+import { noop, remove } from '@univerjs/core';
import { Observable } from 'rxjs';
import { HTTPEventType, HTTPResponse } from '../response';
@@ -69,7 +70,9 @@ export const MergeInterceptorFactory = <T, C>(config: {
*/
distributeResult?: (result: C, list: T[]) => { config: T; result: C }[];
} = {}) => {
- interface IHook { next: (v: HTTPResponse<C>) => void; config: T; error: (error: string) => void };
+ interface IBatch { hooks: IHook[]; subscription?: Subscription };
+ interface IHook { next: (v: HTTPResponse<C>) => void; config: T; error: (error: string) => void; active: boolean; batch?: IBatch };
+
const { isMatch, getParamsFromRequest, mergeParamsToRequest } = config;
const { fetchCheck = createDefaultFetchCheck(300), distributeResult = createDistributeResult() } = options;
const hookList: IHook[] = [];
@@ -81,12 +84,16 @@ export const MergeInterceptorFactory = <T, C>(config: {
}
return new Observable<HTTPResponse<C>>((observer) => {
const params = getParamsFromRequest(requestConfig);
- hookList.push({
+ const hook: IHook = {
next: (v) => observer.next(v),
error: (error) => observer.error(error),
config: params,
- });
+ active: true,
+ };
+ hookList.push(hook);
+
const list = getPlainList(hookList);
+
fetchCheck(requestConfig).then((isFetch) => {
if (isFetch) {
// Pin down the queue that currently needs a request.
@@ -100,12 +107,18 @@ export const MergeInterceptorFactory = <T, C>(config: {
// There's no corresponding callback here. It could be that other operations have been handled and do not need to be handled.
}
});
+ const currentList = getPlainList(currentHookList);
+ if (!currentList.length) {
+ return;
+ }
- next(mergeParamsToRequest(list, requestConfig)).subscribe({
+ const batch: IBatch = { hooks: currentHookList };
+ currentHookList.forEach((hookItem) => hookItem.batch = batch);
+ batch.subscription = next(mergeParamsToRequest(currentList, requestConfig)).subscribe({
next: (e) => {
if (e.type === HTTPEventType.Response) {
const body = e.body as C;
- const configList = distributeResult(body, list);
+ const configList = distributeResult(body, currentList);
currentHookList.forEach((hookItem) => {
const res = configList.find((item) => item.config === hookItem.config);
if (res) {
@@ -127,6 +140,14 @@ export const MergeInterceptorFactory = <T, C>(config: {
});
}
});
+
+ return () => {
+ hook.active = false;
+ remove(hookList, hook);
+ if (hook.batch?.hooks.every((hookItem) => !hookItem.active)) {
+ hook.batch.subscription?.unsubscribe();
+ }
+ };
});
};
};
diff --git a/packages/network/src/services/http/interceptors/threshold-interceptor.ts b/packages/network/src/services/http/interceptors/threshold-interceptor.ts
index d143ff690d..79c70576b8 100644
--- a/packages/network/src/services/http/interceptors/threshold-interceptor.ts
+++ b/packages/network/src/services/http/interceptors/threshold-interceptor.ts
@@ -15,6 +15,7 @@
*/
import type { Nullable } from '@univerjs/core';
+import type { Subscription } from 'rxjs';
import type { HTTPInterceptorFnFactory } from '../interceptor';
import { remove } from '@univerjs/core';
import { Observable } from 'rxjs';
@@ -42,13 +43,17 @@ export const ThresholdInterceptorFactory: HTTPInterceptorFnFactory<[Nullable<ITh
return (request, next) => {
return new Observable((observer) => {
- const handler = () => next(request).subscribe({
- next: (event) => observer.next(event),
- error: (err) => observer.error(err),
- complete: () => observer.complete(),
- });
+ let requestSubscription: Subscription | undefined;
+ const handler = () => {
+ requestSubscription = next(request).subscribe({
+ next: (event) => observer.next(event),
+ error: (err) => observer.error(err),
+ complete: () => observer.complete(),
+ });
+ };
const teardown = () => {
+ requestSubscription?.unsubscribe();
ongoingHandlers.delete(handler);
remove(handlers, handler);
tick();
diff --git a/packages/sheets-conditional-formatting-ui/package.json b/packages/sheets-conditional-formatting-ui/package.json
index 3a7866a5b3..45a2dd3cc8 100644
--- a/packages/sheets-conditional-formatting-ui/package.json
+++ b/packages/sheets-conditional-formatting-ui/package.json
@@ -78,7 +78,7 @@
"@univerjs/design": "workspace:*",
"@univerjs/engine-formula": "workspace:*",
"@univerjs/engine-render": "workspace:*",
- "@univerjs/icons": "1.29.0",
+ "@univerjs/icons": "1.32.0",
"@univerjs/sheets": "workspace:*",
"@univerjs/sheets-conditional-formatting": "workspace:*",
"@univerjs/sheets-formula": "workspace:*",
diff --git a/packages/sheets-conditional-formatting-ui/src/menu/__tests__/manage-rule.spec.ts b/packages/sheets-conditional-formatting-ui/src/menu/__tests__/manage-rule.spec.ts
new file mode 100644
index 0000000000..ddca91d7c8
--- /dev/null
+++ b/packages/sheets-conditional-formatting-ui/src/menu/__tests__/manage-rule.spec.ts
@@ -0,0 +1,57 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDisposable } from '@univerjs/core';
+import { ICommandService, toDisposable } from '@univerjs/core';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createCfUiTestBed } from '../../__tests__/create-cf-ui-test-bed';
+import { FactoryManageConditionalFormattingRule } from '../manage-rule';
+
+describe('FactoryManageConditionalFormattingRule', () => {
+ let univer: IDisposable | undefined;
+
+ afterEach(() => {
+ univer?.dispose();
+ vi.restoreAllMocks();
+ });
+
+ it('disposes command listeners with the selections subscription', () => {
+ const testBed = createCfUiTestBed();
+ univer = testBed.univer;
+ const commandService = testBed.get(ICommandService);
+ const onCommandExecuted = commandService.onCommandExecuted.bind(commandService);
+ let activeListeners = 0;
+
+ vi.spyOn(commandService, 'onCommandExecuted').mockImplementation((listener) => {
+ activeListeners++;
+ const disposable = onCommandExecuted(listener);
+ return toDisposable(() => {
+ activeListeners--;
+ disposable.dispose();
+ });
+ });
+
+ const menu = FactoryManageConditionalFormattingRule(testBed.injector);
+ if (!menu.selections || Array.isArray(menu.selections)) {
+ throw new Error('Expected observable selections');
+ }
+ const subscription = menu.selections.subscribe();
+ expect(activeListeners).toBe(2);
+
+ subscription.unsubscribe();
+ expect(activeListeners).toBe(0);
+ });
+});
diff --git a/packages/sheets-conditional-formatting-ui/src/menu/manage-rule.ts b/packages/sheets-conditional-formatting-ui/src/menu/manage-rule.ts
index 2a30964845..bfbee0d4a5 100644
--- a/packages/sheets-conditional-formatting-ui/src/menu/manage-rule.ts
+++ b/packages/sheets-conditional-formatting-ui/src/menu/manage-rule.ts
@@ -189,15 +189,16 @@ export function FactoryManageConditionalFormattingRule(accessor: IAccessor): IMe
subscriber.next(hasPermission);
})
);
+
const selections$ = new Observable<IValueOption<LocaleKey>[]>((subscriber) => {
- clearRangeEnable$.subscribe((v) => {
+ const clearRangeSubscription = clearRangeEnable$.subscribe((v) => {
const item = commonSelections.find((item) => item.value === CF_MENU_OPERATION.clearRangeRules);
if (item) {
item.disabled = !v;
subscriber.next(commonSelections);
}
});
- clearSheetEnable$.subscribe((v) => {
+ const clearSheetSubscription = clearSheetEnable$.subscribe((v) => {
const item = commonSelections.find((item) => item.value === CF_MENU_OPERATION.clearWorkSheetRules);
if (item) {
item.disabled = !v;
@@ -205,7 +206,12 @@ export function FactoryManageConditionalFormattingRule(accessor: IAccessor): IMe
}
});
subscriber.next(commonSelections);
+ return () => {
+ clearRangeSubscription.unsubscribe();
+ clearSheetSubscription.unsubscribe();
+ };
});
+
return {
id: OpenConditionalFormattingOperator.id,
type: MenuItemType.SELECTOR,
diff --git a/packages/sheets-conditional-formatting-ui/src/menu/schema.ts b/packages/sheets-conditional-formatting-ui/src/menu/schema.ts
index 4c7a5d605c..7ff6f65289 100644
--- a/packages/sheets-conditional-formatting-ui/src/menu/schema.ts
+++ b/packages/sheets-conditional-formatting-ui/src/menu/schema.ts
@@ -36,6 +36,7 @@ export const menuSchema: MenuSchemaType = {
[RibbonDataGroup.RULES]: {
[OpenConditionalFormattingOperator.id]: {
order: 1,
+ gridLayout: { row: 2, column: 1, showLabel: true },
menuItemFactory: FactoryManageConditionalFormattingRule,
},
},
diff --git a/packages/sheets-conditional-formatting/package.json b/packages/sheets-conditional-formatting/package.json
index 5d0eb84f92..08e02a626b 100644
--- a/packages/sheets-conditional-formatting/package.json
+++ b/packages/sheets-conditional-formatting/package.json
@@ -92,7 +92,7 @@
},
"devDependencies": {
"@univerjs-infra/shared": "workspace:*",
- "@univerjs/icons-svg": "^1.29.0",
+ "@univerjs/icons-svg": "^1.32.0",
"@univerjs/sheets-formula": "workspace:*",
"rxjs": "^7.8.2",
"typescript": "^6.0.3",
diff --git a/packages/sheets-crosshair-highlight/package.json b/packages/sheets-crosshair-highlight/package.json
index 2025b66a97..4445dda76c 100644
--- a/packages/sheets-crosshair-highlight/package.json
+++ b/packages/sheets-crosshair-highlight/package.json
@@ -88,7 +88,7 @@
"@univerjs/core": "workspace:*",
"@univerjs/design": "workspace:*",
"@univerjs/engine-render": "workspace:*",
- "@univerjs/icons": "1.29.0",
+ "@univerjs/icons": "1.32.0",
"@univerjs/sheets": "workspace:*",
"@univerjs/sheets-ui": "workspace:*",
"@univerjs/ui": "workspace:*"
diff --git a/packages/sheets-crosshair-highlight/src/controllers/crosshair.controller.spec.tsx b/packages/sheets-crosshair-highlight/src/controllers/crosshair.controller.spec.tsx
index e90512100c..aa6423ab2e 100644
--- a/packages/sheets-crosshair-highlight/src/controllers/crosshair.controller.spec.tsx
+++ b/packages/sheets-crosshair-highlight/src/controllers/crosshair.controller.spec.tsx
@@ -46,8 +46,8 @@ describe('SheetsCrosshairHighlightController', () => {
expect(mergeMenu).toHaveBeenCalledWith(menuSchema);
expect(Object.keys(menuSchema).length).toBeGreaterThan(0);
- const viewVisibility = (menuSchema as Record<string, Record<string, unknown>>)[RibbonViewGroup.VISIBILITY];
- expect(viewVisibility).toHaveProperty(ToggleCrosshairHighlightOperation.id);
+ const viewVisibility = (menuSchema as Record<string, Record<string, { gridLayout?: unknown }>>)[RibbonViewGroup.VISIBILITY];
+ expect(viewVisibility[ToggleCrosshairHighlightOperation.id].gridLayout).toEqual({ row: 2, column: 1, showLabel: true });
controller.dispose();
});
diff --git a/packages/sheets-crosshair-highlight/src/menu/schema.ts b/packages/sheets-crosshair-highlight/src/menu/schema.ts
index 14a68b2912..3024d1b457 100644
--- a/packages/sheets-crosshair-highlight/src/menu/schema.ts
+++ b/packages/sheets-crosshair-highlight/src/menu/schema.ts
@@ -23,6 +23,7 @@ export const menuSchema: MenuSchemaType = {
[RibbonViewGroup.VISIBILITY]: {
[ToggleCrosshairHighlightOperation.id]: {
order: 1,
+ gridLayout: { row: 2, column: 1, showLabel: true },
menuItemFactory: CrosshairHighlightMenuItemFactory,
},
},
diff --git a/packages/sheets-data-validation-ui/package.json b/packages/sheets-data-validation-ui/package.json
index 6fa6988acb..a023fc3aba 100644
--- a/packages/sheets-data-validation-ui/package.json
+++ b/packages/sheets-data-validation-ui/package.json
@@ -80,7 +80,7 @@
"@univerjs/design": "workspace:*",
"@univerjs/engine-formula": "workspace:*",
"@univerjs/engine-render": "workspace:*",
- "@univerjs/icons": "1.29.0",
+ "@univerjs/icons": "1.32.0",
"@univerjs/sheets": "workspace:*",
"@univerjs/sheets-data-validation": "workspace:*",
"@univerjs/sheets-formula-ui": "workspace:*",
diff --git a/packages/sheets-data-validation-ui/src/menu/schema.ts b/packages/sheets-data-validation-ui/src/menu/schema.ts
index 751edebd68..4b5dcf7abb 100644
--- a/packages/sheets-data-validation-ui/src/menu/schema.ts
+++ b/packages/sheets-data-validation-ui/src/menu/schema.ts
@@ -51,6 +51,7 @@ export const menuSchema: MenuSchemaType = {
[RibbonDataGroup.RULES]: {
[DATA_VALIDATION_MENU_ID]: {
order: 0,
+ gridLayout: { row: 1, column: 1, showLabel: true },
menuItemFactory: dataValidationMenuFactory,
[OpenValidationPanelOperation.id]: {
order: 0,
diff --git a/packages/sheets-drawing-ui/src/menu/schema.ts b/packages/sheets-drawing-ui/src/menu/schema.ts
index ed7137bbad..b603b0c068 100644
--- a/packages/sheets-drawing-ui/src/menu/schema.ts
+++ b/packages/sheets-drawing-ui/src/menu/schema.ts
@@ -25,6 +25,7 @@ export const menuSchema: MenuSchemaType = {
[RibbonInsertGroup.MEDIA]: {
[SHEETS_IMAGE_MENU_ID]: {
order: 0,
+ gridLayout: { row: 1, column: 1, rowSpan: 2, showLabel: true },
menuItemFactory: ImageMenuFactory,
[InsertFloatImageCommand.id]: {
order: 0,
diff --git a/packages/sheets-filter-ui/package.json b/packages/sheets-filter-ui/package.json
index 1af4be2910..553b54e583 100644
--- a/packages/sheets-filter-ui/package.json
+++ b/packages/sheets-filter-ui/package.json
@@ -77,7 +77,7 @@
"@univerjs/core": "workspace:*",
"@univerjs/design": "workspace:*",
"@univerjs/engine-render": "workspace:*",
- "@univerjs/icons": "1.29.0",
+ "@univerjs/icons": "1.32.0",
"@univerjs/rpc": "workspace:*",
"@univerjs/sheets": "workspace:*",
"@univerjs/sheets-filter": "workspace:*",
diff --git a/packages/sheets-filter-ui/src/menu/schema.ts b/packages/sheets-filter-ui/src/menu/schema.ts
index ae75291aa0..9b3babf293 100644
--- a/packages/sheets-filter-ui/src/menu/schema.ts
+++ b/packages/sheets-filter-ui/src/menu/schema.ts
@@ -31,6 +31,7 @@ export const menuSchema: MenuSchemaType = {
[RibbonDataGroup.ORGANIZATION]: {
[SmartToggleSheetsFilterCommand.id]: {
order: 2,
+ gridLayout: { row: 1, column: 2 },
menuItemFactory: SmartToggleFilterMenuItemFactory,
[ClearSheetsFilterCriteriaCommand.id]: {
order: 0,
diff --git a/packages/sheets-formula-ui/package.json b/packages/sheets-formula-ui/package.json
index 9c865d48ac..3f6334969e 100644
--- a/packages/sheets-formula-ui/package.json
+++ b/packages/sheets-formula-ui/package.json
@@ -91,7 +91,7 @@
"@univerjs/docs-ui": "workspace:*",
"@univerjs/engine-formula": "workspace:*",
"@univerjs/engine-render": "workspace:*",
- "@univerjs/icons": "1.29.0",
+ "@univerjs/icons": "1.32.0",
"@univerjs/sheets": "workspace:*",
"@univerjs/sheets-formula": "workspace:*",
"@univerjs/sheets-ui": "workspace:*",
diff --git a/packages/sheets-formula-ui/src/menu/schema.ts b/packages/sheets-formula-ui/src/menu/schema.ts
index 5eb8b00975..a5ac5b0d31 100644
--- a/packages/sheets-formula-ui/src/menu/schema.ts
+++ b/packages/sheets-formula-ui/src/menu/schema.ts
@@ -41,6 +41,7 @@ export const menuSchema: MenuSchemaType = {
[RibbonFormulasGroup.BASIC]: {
[`${InsertFunctionOperation.id}.common`]: {
order: 0,
+ gridLayout: { row: 1, column: 1, rowSpan: 2, showLabel: false },
menuItemFactory: InsertCommonFunctionMenuItemFactory,
[MoreFunctionsOperation.id]: {
order: 0,
diff --git a/packages/sheets-hyper-link-ui/package.json b/packages/sheets-hyper-link-ui/package.json
index d533e1c649..f575576ed1 100644
--- a/packages/sheets-hyper-link-ui/package.json
+++ b/packages/sheets-hyper-link-ui/package.json
@@ -91,7 +91,7 @@
"@univerjs/docs-ui": "workspace:*",
"@univerjs/engine-formula": "workspace:*",
"@univerjs/engine-render": "workspace:*",
- "@univerjs/icons": "1.29.0",
+ "@univerjs/icons": "1.32.0",
"@univerjs/sheets": "workspace:*",
"@univerjs/sheets-data-validation": "workspace:*",
"@univerjs/sheets-formula-ui": "workspace:*",
diff --git a/packages/sheets-hyper-link-ui/src/menu/schema.ts b/packages/sheets-hyper-link-ui/src/menu/schema.ts
index 7cb368da16..b860a830bb 100644
--- a/packages/sheets-hyper-link-ui/src/menu/schema.ts
+++ b/packages/sheets-hyper-link-ui/src/menu/schema.ts
@@ -23,6 +23,7 @@ export const menuSchema: MenuSchemaType = {
[RibbonInsertGroup.MEDIA]: {
[InsertHyperLinkToolbarOperation.id]: {
order: 1,
+ gridLayout: { row: 1, column: 2, rowSpan: 2, showLabel: true },
menuItemFactory: insertLinkMenuToolbarFactory,
},
},
diff --git a/packages/sheets-note-ui/package.json b/packages/sheets-note-ui/package.json
index fe200e097f..eb219bb062 100644
--- a/packages/sheets-note-ui/package.json
+++ b/packages/sheets-note-ui/package.json
@@ -74,7 +74,7 @@
"@univerjs/core": "workspace:*",
"@univerjs/design": "workspace:*",
"@univerjs/engine-render": "workspace:*",
- "@univerjs/icons": "1.29.0",
+ "@univerjs/icons": "1.32.0",
"@univerjs/sheets": "workspace:*",
"@univerjs/sheets-note": "workspace:*",
"@univerjs/sheets-ui": "workspace:*",
diff --git a/packages/sheets-numfmt-ui/package.json b/packages/sheets-numfmt-ui/package.json
index dffdfcbcbd..c8e3be1591 100644
--- a/packages/sheets-numfmt-ui/package.json
+++ b/packages/sheets-numfmt-ui/package.json
@@ -78,7 +78,7 @@
"@univerjs/design": "workspace:*",
"@univerjs/engine-formula": "workspace:*",
"@univerjs/engine-render": "workspace:*",
- "@univerjs/icons": "1.29.0",
+ "@univerjs/icons": "1.32.0",
"@univerjs/sheets": "workspace:*",
"@univerjs/sheets-numfmt": "workspace:*",
"@univerjs/sheets-ui": "workspace:*",
diff --git a/packages/sheets-numfmt-ui/src/menu/schema.ts b/packages/sheets-numfmt-ui/src/menu/schema.ts
index 8d8ce901ce..1f68f8088c 100644
--- a/packages/sheets-numfmt-ui/src/menu/schema.ts
+++ b/packages/sheets-numfmt-ui/src/menu/schema.ts
@@ -21,25 +21,30 @@ import { OpenNumfmtPanelOperator } from '../commands/operations/open.numfmt.pane
import { AddDecimalMenuItem, CurrencySymbolIconMenuItem, FactoryOtherMenuItem, PercentMenuItem, SubtractDecimalMenuItem } from './menu';
export const menuSchema: MenuSchemaType = {
- [RibbonStartGroup.LAYOUT]: {
+ [RibbonStartGroup.NUMBER]: {
[OpenNumfmtPanelOperator.id]: {
order: 9,
+ gridLayout: { row: 1, column: 1, columnSpan: 4, width: 210 },
menuItemFactory: FactoryOtherMenuItem,
},
[SetPercentCommand.id]: {
order: 9.1,
+ gridLayout: { row: 2, column: 1 },
menuItemFactory: PercentMenuItem,
},
[SetCurrencyCommand.id]: {
order: 9.2,
+ gridLayout: { row: 2, column: 2 },
menuItemFactory: CurrencySymbolIconMenuItem,
},
[AddDecimalCommand.id]: {
order: 9.3,
+ gridLayout: { row: 2, column: 3 },
menuItemFactory: AddDecimalMenuItem,
},
[SubtractDecimalCommand.id]: {
order: 9.4,
+ gridLayout: { row: 2, column: 4 },
menuItemFactory: SubtractDecimalMenuItem,
},
},
diff --git a/packages/sheets-sort-ui/package.json b/packages/sheets-sort-ui/package.json
index ee085874e9..481f57bee2 100644
--- a/packages/sheets-sort-ui/package.json
+++ b/packages/sheets-sort-ui/package.json
@@ -77,7 +77,7 @@
"@univerjs/core": "workspace:*",
"@univerjs/design": "workspace:*",
"@univerjs/engine-formula": "workspace:*",
- "@univerjs/icons": "1.29.0",
+ "@univerjs/icons": "1.32.0",
"@univerjs/sheets": "workspace:*",
"@univerjs/sheets-sort": "workspace:*",
"@univerjs/sheets-ui": "workspace:*",
diff --git a/packages/sheets-sort-ui/src/menu/schema.ts b/packages/sheets-sort-ui/src/menu/schema.ts
index d30a221d3c..b24863298c 100644
--- a/packages/sheets-sort-ui/src/menu/schema.ts
+++ b/packages/sheets-sort-ui/src/menu/schema.ts
@@ -49,6 +49,7 @@ export const menuSchema: MenuSchemaType = {
[RibbonDataGroup.ORGANIZATION]: {
[SHEETS_SORT_MENU_ID]: {
order: 3,
+ gridLayout: { row: 2, column: 2 },
menuItemFactory: sortRangeMenuFactory,
[SortRangeAscCommand.id]: {
order: 0,
diff --git a/packages/sheets-table-ui/package.json b/packages/sheets-table-ui/package.json
index e100427b46..4e34446a66 100644
--- a/packages/sheets-table-ui/package.json
+++ b/packages/sheets-table-ui/package.json
@@ -79,7 +79,7 @@
"@univerjs/design": "workspace:*",
"@univerjs/engine-formula": "workspace:*",
"@univerjs/engine-render": "workspace:*",
- "@univerjs/icons": "1.29.0",
+ "@univerjs/icons": "1.32.0",
"@univerjs/sheets": "workspace:*",
"@univerjs/sheets-formula-ui": "workspace:*",
"@univerjs/sheets-sort": "workspace:*",
diff --git a/packages/sheets-table-ui/src/menu/menu.ts b/packages/sheets-table-ui/src/menu/menu.ts
index 1da819718d..c2b6dfd1c6 100644
--- a/packages/sheets-table-ui/src/menu/menu.ts
+++ b/packages/sheets-table-ui/src/menu/menu.ts
@@ -29,7 +29,7 @@ import {
} from '@univerjs/sheets-table';
import { getCurrentRangeDisable$ } from '@univerjs/sheets-ui';
import { getMenuHiddenObservable, MenuItemType } from '@univerjs/ui';
-import { of, switchMap } from 'rxjs';
+import { of, startWith, switchMap } from 'rxjs';
import { OpenTableSelectorOperation } from '../commands/operations/open-table-selector.operation';
export const SHEET_TABLE_CONTEXT_INSERT_MENU_ID = 'sheet.table.context-insert_menu-id';
@@ -113,6 +113,7 @@ export function getSheetTableRowColOperationHidden$(accessor: IAccessor): Observ
switchMap((sheet) => {
if (!sheet) return of(true);
return sheetsSelectionsService.selectionMoveEnd$.pipe(
+ startWith(sheetsSelectionsService.getCurrentSelections()),
switchMap((selections) => {
if (!selections.length || selections.length > 1) return of(true);
const selection = selections[0];
@@ -145,6 +146,7 @@ export function getSheetTableHeaderOperationHidden$(accessor: IAccessor): Observ
switchMap((sheet) => {
if (!sheet) return of(true);
return sheetsSelectionsService.selectionMoveEnd$.pipe(
+ startWith(sheetsSelectionsService.getCurrentSelections()),
switchMap((selections) => {
if (!selections.length || selections.length > 1) return of(true);
const selection = selections[0];
diff --git a/packages/sheets-table-ui/src/menu/schema.ts b/packages/sheets-table-ui/src/menu/schema.ts
index 0852a16a43..93a018f1ee 100644
--- a/packages/sheets-table-ui/src/menu/schema.ts
+++ b/packages/sheets-table-ui/src/menu/schema.ts
@@ -24,6 +24,7 @@ export const menuSchema: MenuSchemaType = {
[RibbonDataGroup.ORGANIZATION]: {
[OpenTableSelectorOperation.id]: {
order: 0,
+ gridLayout: { row: 1, column: 1 },
menuItemFactory: sheetTableToolbarInsertMenuFactory,
},
},
diff --git a/packages/sheets-thread-comment-ui/package.json b/packages/sheets-thread-comment-ui/package.json
index 59ccfbad33..30138ad402 100644
--- a/packages/sheets-thread-comment-ui/package.json
+++ b/packages/sheets-thread-comment-ui/package.json
@@ -77,7 +77,7 @@
"@univerjs/core": "workspace:*",
"@univerjs/engine-formula": "workspace:*",
"@univerjs/engine-render": "workspace:*",
- "@univerjs/icons": "1.29.0",
+ "@univerjs/icons": "1.32.0",
"@univerjs/sheets": "workspace:*",
"@univerjs/sheets-thread-comment": "workspace:*",
"@univerjs/sheets-ui": "workspace:*",
diff --git a/packages/sheets-thread-comment-ui/src/menu/schema.ts b/packages/sheets-thread-comment-ui/src/menu/schema.ts
index 9703981d71..e5578238e5 100644
--- a/packages/sheets-thread-comment-ui/src/menu/schema.ts
+++ b/packages/sheets-thread-comment-ui/src/menu/schema.ts
@@ -23,6 +23,7 @@ export const menuSchema: MenuSchemaType = {
[RibbonInsertGroup.MEDIA]: {
[ToggleSheetCommentPanelOperation.id]: {
order: 2,
+ gridLayout: { row: 1, column: 3, rowSpan: 2, showLabel: true },
menuItemFactory: threadPanelMenuFactory,
},
},
diff --git a/packages/sheets-ui/package.json b/packages/sheets-ui/package.json
index cbc732ec00..7f5a6e5a59 100644
--- a/packages/sheets-ui/package.json
+++ b/packages/sheets-ui/package.json
@@ -91,7 +91,7 @@
"@univerjs/docs-ui": "workspace:*",
"@univerjs/engine-formula": "workspace:*",
"@univerjs/engine-render": "workspace:*",
- "@univerjs/icons": "1.29.0",
+ "@univerjs/icons": "1.32.0",
"@univerjs/protocol": "workspace:*",
"@univerjs/sheets": "workspace:*",
"@univerjs/telemetry": "workspace:*",
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.ts
index 2f6e137e41..444a37a451 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
@@ -19,7 +19,6 @@
import type { EmbedRuntimeFocusCoordinator } from '../../../services/sheet-embed-integration.service';
import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY, FOCUSING_FX_BAR_EDITOR, FOCUSING_SHEET } from '@univerjs/core';
import { DocSelectionRenderService } from '@univerjs/docs-ui';
-import { EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE } from '../../../services/sheet-embed-integration.service';
import { DeviceInputEventType } from '@univerjs/engine-render';
import { ClearSelectionFormatCommand, SetWorksheetActiveOperation } from '@univerjs/sheets';
import { Subject } from 'rxjs';
@@ -28,6 +27,7 @@ import { SetZoomRatioCommand } from '../../../commands/commands/set-zoom-ratio.c
import { SetActivateCellEditOperation } from '../../../commands/operations/activate-cell-edit.operation';
import { SetCellEditVisibleOperation } from '../../../commands/operations/cell-edit.operation';
import { SHEET_VIEW_KEY } from '../../../common/keys';
+import { EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE } from '../../../services/sheet-embed-integration.service';
import { EditorBridgeRenderController } from '../editor-bridge.render-controller';
function createEventSubject() {
@@ -114,7 +114,10 @@ function createController(options?: {
[SHEET_VIEW_KEY.LEFT_TOP, spreadsheetLeftTopPlaceholder],
]),
};
- const docSelectionRenderService = { onInputBefore$: inputBefore$ };
+ const docSelectionRenderService = {
+ onInputBefore$: inputBefore$,
+ setInputPosition: vi.fn(),
+ };
const renderManagerService = {
created$: new Subject<any>(),
getRenderById: vi.fn((unitId: string) => unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY
@@ -126,6 +129,10 @@ function createController(options?: {
};
const editorBridgeService = {
getEditCellState: vi.fn(() => options?.currentEditCellState ?? null),
+ getEditCellLayout: vi.fn(() => ({
+ position: { startX: 120, startY: 80 },
+ canvasOffset: { left: 30, top: 20 },
+ })),
getEditLocation: vi.fn(() => options?.currentEditLocation ?? null),
isVisible: vi.fn(() => ({ visible: options?.editorVisible ?? false })),
isForceKeepVisible: vi.fn(() => options?.forceKeepVisible ?? false),
@@ -195,6 +202,7 @@ function createController(options?: {
return {
commandService,
controller,
+ docSelectionRenderService,
editorBridgeService,
inputBefore$,
selectionMoveEnd$,
@@ -306,6 +314,25 @@ describe('EditorBridgeRenderController business flows', () => {
controller.dispose();
});
+ it('moves the hidden input when the user finishes selecting a cell', () => {
+ const { controller, docSelectionRenderService, selectionMoveEnd$ } = createController();
+
+ selectionMoveEnd$.next([{
+ primary: {
+ actualRow: 3,
+ actualColumn: 4,
+ startRow: 3,
+ startColumn: 4,
+ endRow: 3,
+ endColumn: 4,
+ },
+ }]);
+
+ expect(docSelectionRenderService.setInputPosition).toHaveBeenCalledWith(150, 100);
+
+ 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.ts
index c80f6957fe..dc733289b7 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
@@ -84,10 +84,15 @@ export class EditorBridgeRenderController extends RxDisposable implements IRende
private _initSelectionChangeListener(d: DisposableCollection) {
d.add(merge(
- this._selectionManagerService.selectionMoveEnd$,
this._selectionManagerService.selectionSet$,
this._selectionManagerService.selectionMoveStart$
).subscribe((params) => this._updateEditorPosition(params)));
+ d.add(this._selectionManagerService.selectionMoveEnd$.subscribe((params) => {
+ this._updateEditorPosition(params);
+ if (params?.[params.length - 1]?.primary) {
+ this._updateInputPosition();
+ }
+ }));
}
private _updateEditorPosition(params: Nullable<ISelectionWithStyle[]>) {
@@ -129,6 +134,26 @@ export class EditorBridgeRenderController extends RxDisposable implements IRende
}
}
+ private _updateInputPosition() {
+ if (this._editorBridgeService.isVisible().visible) {
+ return;
+ }
+
+ const layout = this._editorBridgeService.getEditCellLayout();
+ const docSelectionRenderService = this._renderManagerService
+ .getRenderById(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)
+ ?.with(DocSelectionRenderService);
+ if (!layout || !docSelectionRenderService) {
+ return;
+ }
+
+ const { position, canvasOffset } = layout;
+ docSelectionRenderService.setInputPosition(
+ canvasOffset.left + position.startX,
+ canvasOffset.top + position.startY
+ );
+ }
+
refreshEditorPosition() {
const workbookSelections = this._selectionManagerService.getWorkbookSelections(this._context.unitId);
if (workbookSelections) {
diff --git a/packages/sheets-ui/src/menu/menu-util.ts b/packages/sheets-ui/src/menu/menu-util.ts
index d596865372..303f5168b3 100644
--- a/packages/sheets-ui/src/menu/menu-util.ts
+++ b/packages/sheets-ui/src/menu/menu-util.ts
@@ -14,11 +14,38 @@
* limitations under the License.
*/
-import type { IAccessor, IPermissionTypes, IRange, Nullable, Workbook, WorkbookPermissionPointConstructor, Worksheet } from '@univerjs/core';
+import type {
+ IAccessor,
+ IPermissionTypes,
+ IRange,
+ Nullable,
+ Workbook,
+ WorkbookPermissionPointConstructor,
+ Worksheet,
+} from '@univerjs/core';
import type { Observable } from 'rxjs';
import type { IEditorBridgeServiceVisibleParam } from '../services/editor-bridge.service';
-import { FOCUSING_COMMON_DRAWINGS, FOCUSING_FX_BAR_EDITOR, FOCUSING_SHAPE_TEXT_EDITOR, IContextService, IPermissionService, IUniverInstanceService, Rectangle, Tools, UniverInstanceType, UserManagerService } from '@univerjs/core';
-import { IExclusiveRangeService, RangeProtectionPermissionEditPoint, RangeProtectionRuleModel, SheetsSelectionsService, WorkbookEditablePermission, WorksheetEditPermission, WorksheetProtectionRuleModel } from '@univerjs/sheets';
+import {
+ FOCUSING_COMMON_DRAWINGS,
+ FOCUSING_FX_BAR_EDITOR,
+ FOCUSING_SHAPE_TEXT_EDITOR,
+ IContextService,
+ IPermissionService,
+ IUniverInstanceService,
+ Rectangle,
+ Tools,
+ UniverInstanceType,
+ UserManagerService,
+} from '@univerjs/core';
+import {
+ IExclusiveRangeService,
+ RangeProtectionPermissionEditPoint,
+ RangeProtectionRuleModel,
+ SheetsSelectionsService,
+ WorkbookEditablePermission,
+ WorksheetEditPermission,
+ WorksheetProtectionRuleModel,
+} from '@univerjs/sheets';
import { combineLatest, merge, of } from 'rxjs';
import { debounceTime, map, shareReplay, startWith, switchMap } from 'rxjs/operators';
import { IEditorBridgeService } from '../services/editor-bridge.service';
diff --git a/packages/sheets-ui/src/menu/schema.ts b/packages/sheets-ui/src/menu/schema.ts
index 905ff9fcc2..01015a9dd8 100644
--- a/packages/sheets-ui/src/menu/schema.ts
+++ b/packages/sheets-ui/src/menu/schema.ts
@@ -233,48 +233,59 @@ export const menuSchema: MenuSchemaType = {
[RibbonStartGroup.HISTORY]: {
[SetOnceFormatPainterCommand.id]: {
order: 2,
+ gridLayout: { row: 1, column: 2, showLabel: true },
menuItemFactory: FormatPainterMenuItemFactory,
},
[ClearSelectionAllCommand.id]: {
order: 3,
+ gridLayout: { row: 2, column: 2, showLabel: true },
menuItemFactory: ClearSelectionAllToolbarMenuItemFactory,
},
},
[RibbonStartGroup.FORMAT]: {
[SetRangeFontFamilyCommand.id]: {
order: 1,
+ gridLayout: { row: 1, column: 1, columnSpan: 4, width: 240 },
menuItemFactory: FontFamilySelectorMenuItemFactory,
},
[SetRangeFontSizeCommand.id]: {
order: 2,
+ gridLayout: { row: 1, column: 5, width: 72 },
menuItemFactory: FontSizeSelectorMenuItemFactory,
},
[SetRangeFontIncreaseCommand.id]: {
order: 2.1,
+ gridLayout: { row: 1, column: 6 },
menuItemFactory: FontSizeIncreaseMenuItemFactory,
},
[SetRangeFontDecreaseCommand.id]: {
order: 2.2,
+ gridLayout: { row: 1, column: 7 },
menuItemFactory: FontSizeDecreaseMenuItemFactory,
},
[SetRangeBoldCommand.id]: {
order: 5,
+ gridLayout: { row: 2, column: 1 },
menuItemFactory: BoldMenuItemFactory,
},
[SetRangeItalicCommand.id]: {
order: 6,
+ gridLayout: { row: 2, column: 2 },
menuItemFactory: ItalicMenuItemFactory,
},
[SetRangeUnderlineCommand.id]: {
order: 7,
+ gridLayout: { row: 2, column: 3 },
menuItemFactory: UnderlineMenuItemFactory,
},
[SetRangeStrickThroughCommand.id]: {
order: 8,
+ gridLayout: { row: 2, column: 4 },
menuItemFactory: StrikeThroughMenuItemFactory,
},
[SetRangeTextColorCommand.id]: {
order: 9,
+ gridLayout: { row: 2, column: 7 },
menuItemFactory: TextColorSelectorMenuItemFactory,
[ResetTextColorCommand.id]: {
order: 0,
@@ -283,6 +294,7 @@ export const menuSchema: MenuSchemaType = {
},
[SetBackgroundColorCommand.id]: {
order: 10,
+ gridLayout: { row: 2, column: 6 },
menuItemFactory: BackgroundColorSelectorMenuItemFactory,
[ResetBackgroundColorCommand.id]: {
order: 0,
@@ -291,32 +303,39 @@ export const menuSchema: MenuSchemaType = {
},
[SetBorderBasicCommand.id]: {
order: 11,
+ gridLayout: { row: 2, column: 5 },
menuItemFactory: CellBorderSelectorMenuItemFactory,
},
},
[RibbonStartGroup.LAYOUT]: {
[SetHorizontalTextAlignCommand.id]: {
order: 0,
+ gridLayout: { row: 1, column: 1 },
menuItemFactory: HorizontalAlignMenuItemFactory,
},
[SetVerticalTextAlignCommand.id]: {
order: 3,
+ gridLayout: { row: 2, column: 1 },
menuItemFactory: VerticalAlignMenuItemFactory,
},
[SetTextWrapCommand.id]: {
order: 6,
+ gridLayout: { row: 1, column: 2 },
menuItemFactory: WrapTextMenuItemFactory,
},
[SetShrinkToFitCommand.id]: {
order: 7,
+ gridLayout: { row: 2, column: 2 },
menuItemFactory: ShrinkToFitMenuItemFactory,
},
[SetTextRotationCommand.id]: {
order: 8,
+ gridLayout: { row: 1, column: 3 },
menuItemFactory: TextRotateMenuItemFactory,
},
[AddWorksheetMergeCommand.id]: {
order: 9,
+ gridLayout: { row: 2, column: 3 },
menuItemFactory: CellMergeMenuItemFactory,
[AddWorksheetMergeAllCommand.id]: {
order: 0,
@@ -339,6 +358,7 @@ export const menuSchema: MenuSchemaType = {
[RibbonStartGroup.OTHERS]: {
[AddRangeProtectionFromToolbarCommand.id]: {
order: 0,
+ gridLayout: { row: 1, column: 1, rowSpan: 2, showLabel: true },
menuItemFactory: sheetPermissionToolbarMenuFactory,
},
},
@@ -347,20 +367,24 @@ export const menuSchema: MenuSchemaType = {
[RibbonViewGroup.DISPLAY]: {
[SHEET_FROZEN_TOOLBAR_MENU_ID]: {
order: 0,
+ gridLayout: { row: 1, column: 1, rowSpan: 2, showLabel: true },
menuItemFactory: SheetFrozenToolbarMenuItemFactory,
},
[ZOOM_RATIO_MENU_ID]: {
order: 1,
+ gridLayout: { row: 1, column: 2, width: 112 },
menuItemFactory: ZoomRatioMenuItemFactory,
},
[ToggleFullscreenOperation.id]: {
order: 2,
+ gridLayout: { row: 2, column: 2, showLabel: true, width: 112 },
menuItemFactory: FullscreenMenuItemFactory,
},
},
[RibbonViewGroup.VISIBILITY]: {
[ToggleGridlinesCommand.id]: {
order: 0,
+ gridLayout: { row: 1, column: 1, showLabel: true },
menuItemFactory: ToggleGridlinesMenuFactory,
},
},
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.ts
index 7c6b2aa0b7..27c50446dc 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
@@ -15,7 +15,14 @@
*/
import type { ICellData, Injector, IStyleData, Nullable, Univer } from '@univerjs/core';
-import { CellValueType, DEFAULT_TEXT_FORMAT_EXCEL, ICommandService, IUniverInstanceService, LocaleType, RANGE_TYPE } from '@univerjs/core';
+import {
+ CellValueType,
+ DEFAULT_TEXT_FORMAT_EXCEL,
+ ICommandService,
+ IUniverInstanceService,
+ LocaleType,
+ RANGE_TYPE,
+} from '@univerjs/core';
import {
AddWorksheetMergeMutation,
MoveRangeMutation,
@@ -31,7 +38,15 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { SheetSkeletonManagerService } from '../../sheet-skeleton-manager.service';
import { ISheetClipboardService } from '../clipboard.service';
import { clipboardTestBed } from './clipboard-test-bed';
-import { excelSample, excelSample2, excelSample3, excelSample4, excelSample5, excelSample6, excelSample7 } from './constant';
+import {
+ excelSample,
+ excelSample2,
+ excelSample3,
+ excelSample4,
+ excelSample5,
+ excelSample6,
+ excelSample7,
+} from './constant';
describe('Test clipboard', () => {
let univer: Univer;
diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-state.service.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-state.service.spec.ts
index 1129ddf7de..b6235738f6 100644
--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-state.service.spec.ts
+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-state.service.spec.ts
@@ -36,7 +36,12 @@ import {
Workbook,
} from '@univerjs/core';
import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
-import { SetSelectionsOperation, SetWorksheetActiveOperation, SheetSkeletonService, SheetsSelectionsService } from '@univerjs/sheets';
+import {
+ SetSelectionsOperation,
+ SetWorksheetActiveOperation,
+ SheetSkeletonService,
+ SheetsSelectionsService,
+} from '@univerjs/sheets';
import {
IClipboardInterfaceService,
INotificationService,
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.ts
index c1ddb17af3..040c005de5 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
@@ -17,8 +17,33 @@
/* eslint-disable ts/no-explicit-any */
import type { Dependency, IDisposable, IWorkbookData, Workbook } from '@univerjs/core';
-import { DisposableCollection, ILogService, Inject, Injector, IUniverInstanceService, LocaleService, LocaleType, LogLevel, Plugin, Univer, UniverInstanceType } from '@univerjs/core';
-import { CalculateFormulaService, DefinedNamesService, FormulaCurrentConfigService, FormulaDataModel, FormulaRuntimeService, HyperlinkEngineFormulaService, ICalculateFormulaService, IDefinedNamesService, IFormulaCurrentConfigService, IFormulaRuntimeService, IHyperlinkEngineFormulaService, LexerTreeBuilder } from '@univerjs/engine-formula';
+import {
+ DisposableCollection,
+ ILogService,
+ Inject,
+ Injector,
+ IUniverInstanceService,
+ LocaleService,
+ LocaleType,
+ LogLevel,
+ Plugin,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import {
+ CalculateFormulaService,
+ DefinedNamesService,
+ FormulaCurrentConfigService,
+ FormulaDataModel,
+ FormulaRuntimeService,
+ HyperlinkEngineFormulaService,
+ ICalculateFormulaService,
+ IDefinedNamesService,
+ IFormulaCurrentConfigService,
+ IFormulaRuntimeService,
+ IHyperlinkEngineFormulaService,
+ LexerTreeBuilder,
+} from '@univerjs/engine-formula';
import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
import { SheetInterceptorService, SheetSkeletonService, SheetsSelectionsService } from '@univerjs/sheets';
import {
diff --git a/packages/sheets-ui/src/services/editor/cell-editor-resize.service.ts b/packages/sheets-ui/src/services/editor/cell-editor-resize.service.ts
index 6471683fd1..83bb3466b0 100644
--- a/packages/sheets-ui/src/services/editor/cell-editor-resize.service.ts
+++ b/packages/sheets-ui/src/services/editor/cell-editor-resize.service.ts
@@ -16,10 +16,27 @@
import type { DocumentDataModel, IPosition, Nullable } from '@univerjs/core';
import type { DocumentSkeleton, IDocumentLayoutObject, Scene } from '@univerjs/engine-render';
-import { Disposable, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, HorizontalAlign, IConfigService, IUniverInstanceService, Optional, UniverInstanceType, VerticalAlign, WrapStrategy } from '@univerjs/core';
+import {
+ Disposable,
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ HorizontalAlign,
+ IConfigService,
+ IUniverInstanceService,
+ Optional,
+ UniverInstanceType,
+ VerticalAlign,
+ WrapStrategy,
+} from '@univerjs/core';
import { DocSkeletonManagerService } from '@univerjs/docs';
import { DOCS_COMPONENT_MAIN_LAYER_INDEX, VIEWPORT_KEY } from '@univerjs/docs-ui';
-import { convertTextRotation, fixLineWidthByScale, getCurrentTypeOfRenderer, IRenderManagerService, Rect, ScrollBar } from '@univerjs/engine-render';
+import {
+ convertTextRotation,
+ fixLineWidthByScale,
+ getCurrentTypeOfRenderer,
+ IRenderManagerService,
+ Rect,
+ ScrollBar,
+} from '@univerjs/engine-render';
import { ILayoutService } from '@univerjs/ui';
import { getEditorObject } from '../../basics/editor/get-editor-object';
import { IEditorBridgeService } from '../editor-bridge.service';
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.ts
index fbcfa34abd..2aa14b2967 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
@@ -16,7 +16,16 @@
import type { IMutationInfo, IRange, IStyleData } from '@univerjs/core';
import type { Observable } from 'rxjs';
-import { createIdentifier, Disposable, ICommandService, ILogService, Inject, IUndoRedoService, ObjectMatrix, ThemeService } from '@univerjs/core';
+import {
+ createIdentifier,
+ Disposable,
+ ICommandService,
+ ILogService,
+ Inject,
+ IUndoRedoService,
+ ObjectMatrix,
+ ThemeService,
+} from '@univerjs/core';
import { SetRangeValuesMutation, SheetsSelectionsService } from '@univerjs/sheets';
import { BehaviorSubject } from 'rxjs';
import { IMarkSelectionService } from '../mark-selection/mark-selection.service';
diff --git a/packages/sheets-ui/src/services/mark-selection/__tests__/mark-selection.service.spec.ts b/packages/sheets-ui/src/services/mark-selection/__tests__/mark-selection.service.spec.ts
index aaeee34d9a..30b1bd20fb 100644
--- a/packages/sheets-ui/src/services/mark-selection/__tests__/mark-selection.service.spec.ts
+++ b/packages/sheets-ui/src/services/mark-selection/__tests__/mark-selection.service.spec.ts
@@ -28,7 +28,11 @@ import {
import { IRenderManagerService, SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';
import { SheetSkeletonService } from '@univerjs/sheets';
import { describe, expect, it } from 'vitest';
-import { createFakeScene, createFakeSkeleton, createFakeViewport } from '../../../controllers/render-controllers/__tests__/render-test-bed';
+import {
+ createFakeScene,
+ createFakeSkeleton,
+ createFakeViewport,
+} from '../../../controllers/render-controllers/__tests__/render-test-bed';
import { IMarkSelectionService, MarkSelectionService } from '../mark-selection.service';
class TestSheetSkeletonService {
diff --git a/packages/sheets-ui/src/services/mark-selection/mark-selection.service.ts b/packages/sheets-ui/src/services/mark-selection/mark-selection.service.ts
index d639aff0f1..7ed45d61e4 100644
--- a/packages/sheets-ui/src/services/mark-selection/mark-selection.service.ts
+++ b/packages/sheets-ui/src/services/mark-selection/mark-selection.service.ts
@@ -17,7 +17,15 @@
import type { Workbook } from '@univerjs/core';
import type { RenderUnit } from '@univerjs/engine-render';
import type { ISelectionWithStyle } from '@univerjs/sheets';
-import { createIdentifier, Disposable, generateRandomId, Inject, IUniverInstanceService, ThemeService, UniverInstanceType } from '@univerjs/core';
+import {
+ createIdentifier,
+ Disposable,
+ generateRandomId,
+ Inject,
+ IUniverInstanceService,
+ ThemeService,
+ UniverInstanceType,
+} from '@univerjs/core';
import { IRenderManagerService } from '@univerjs/engine-render';
import { attachSelectionWithCoord, SheetSkeletonService } from '@univerjs/sheets';
import { SELECTION_SHAPE_DEPTH } from '../selection/const';
diff --git a/packages/sheets-ui/src/views/sheet-slider/SheetZoomInput.tsx b/packages/sheets-ui/src/views/sheet-slider/SheetZoomInput.tsx
index 44a7e4bf38..96b1432faa 100644
--- a/packages/sheets-ui/src/views/sheet-slider/SheetZoomInput.tsx
+++ b/packages/sheets-ui/src/views/sheet-slider/SheetZoomInput.tsx
@@ -16,21 +16,22 @@
import type { IZoomInputProps } from '@univerjs/ui';
import { ICommandService } from '@univerjs/core';
+import { clsx } from '@univerjs/design';
import { useDependency, ZoomInput } from '@univerjs/ui';
import { SetZoomRatioFromToolbarCommand } from '../../commands/commands/set-zoom-ratio-from-toolbar.command';
export const SHEET_ZOOM_INPUT_COMPONENT = 'SHEET_ZOOM_INPUT_COMPONENT';
-export function SheetZoomInput(props: Omit<IZoomInputProps, 'className' | 'onChange'>) {
+export function SheetZoomInput({ className, ...props }: Omit<IZoomInputProps, 'onChange'>) {
const commandService = useDependency(ICommandService);
return (
<ZoomInput
{...props}
- className="
+ className={clsx(`
!univer-bg-transparent
dark:!univer-bg-transparent
- "
+ `, className)}
onChange={(value) => commandService.executeCommand(SetZoomRatioFromToolbarCommand.id, { value })}
/>
);
diff --git a/packages/sheets-ui/src/views/sheet-slider/__tests__/SheetZoomInput.spec.tsx b/packages/sheets-ui/src/views/sheet-slider/__tests__/SheetZoomInput.spec.tsx
new file mode 100644
index 0000000000..2b21c8545f
--- /dev/null
+++ b/packages/sheets-ui/src/views/sheet-slider/__tests__/SheetZoomInput.spec.tsx
@@ -0,0 +1,36 @@
+/**
+ * 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 { IZoomInputProps } from '@univerjs/ui';
+import type { ReactElement } from 'react';
+import { describe, expect, it, vi } from 'vitest';
+import { SheetZoomInput } from '../SheetZoomInput';
+
+vi.mock('@univerjs/ui', async (importOriginal) => ({
+ ...await importOriginal<typeof import('@univerjs/ui')>(),
+ useDependency: () => ({ executeCommand: () => true }),
+}));
+
+describe('SheetZoomInput', () => {
+ it('forwards a layout class to the shared zoom input', () => {
+ const element = SheetZoomInput({
+ className: '!univer-w-full',
+ shortcuts: [50, 100, 200],
+ } as IZoomInputProps) as ReactElement<IZoomInputProps>;
+
+ expect(element.props.className).toContain('!univer-w-full');
+ });
+});
diff --git a/packages/slides-ui/package.json b/packages/slides-ui/package.json
index 349bf96ff9..a2d3a6c48d 100644
--- a/packages/slides-ui/package.json
+++ b/packages/slides-ui/package.json
@@ -80,7 +80,7 @@
"@univerjs/docs-ui": "workspace:*",
"@univerjs/drawing": "workspace:*",
"@univerjs/engine-render": "workspace:*",
- "@univerjs/icons": "1.29.0",
+ "@univerjs/icons": "1.32.0",
"@univerjs/slides": "workspace:*",
"@univerjs/ui": "workspace:*"
},
diff --git a/packages/slides-ui/src/menu/schema.ts b/packages/slides-ui/src/menu/schema.ts
index 960db71504..5eea43eecd 100644
--- a/packages/slides-ui/src/menu/schema.ts
+++ b/packages/slides-ui/src/menu/schema.ts
@@ -27,10 +27,12 @@ export const menuSchema: MenuSchemaType = {
[RibbonStartGroup.FORMAT]: {
[SlideAddTextCommand.id]: {
order: 0,
+ gridLayout: { row: 1, column: 1, rowSpan: 2, showLabel: true },
menuItemFactory: SlideAddTextMenuItemFactory,
},
[SLIDES_IMAGE_MENU_ID]: {
order: 0,
+ gridLayout: { row: 1, column: 2, rowSpan: 2, showLabel: true },
menuItemFactory: SlideImageMenuFactory,
[InsertSlideFloatImageCommand.id]: {
order: 0,
@@ -39,6 +41,7 @@ export const menuSchema: MenuSchemaType = {
},
[SHAPE_MENU_ID]: {
order: 0,
+ gridLayout: { row: 1, column: 3, rowSpan: 2, showLabel: true },
menuItemFactory: SlideShapeMenuFactory,
[InsertSlideShapeRectangleCommand.id]: {
order: 0,
diff --git a/packages/thread-comment-ui/package.json b/packages/thread-comment-ui/package.json
index a35795522e..b678b8fbde 100644
--- a/packages/thread-comment-ui/package.json
+++ b/packages/thread-comment-ui/package.json
@@ -77,7 +77,7 @@
"@univerjs/core": "workspace:*",
"@univerjs/design": "workspace:*",
"@univerjs/docs-ui": "workspace:*",
- "@univerjs/icons": "1.29.0",
+ "@univerjs/icons": "1.32.0",
"@univerjs/thread-comment": "workspace:*",
"@univerjs/ui": "workspace:*"
},
diff --git a/packages/ui/package.json b/packages/ui/package.json
index 8868a6be45..b9d70a7dab 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -90,7 +90,7 @@
"@univerjs/core": "workspace:*",
"@univerjs/design": "workspace:*",
"@univerjs/engine-render": "workspace:*",
- "@univerjs/icons": "1.29.0",
+ "@univerjs/icons": "1.32.0",
"@wendellhu/redi": "1.1.2"
},
"devDependencies": {
diff --git a/packages/ui/src/commands/operations/open-feature-search.operation.ts b/packages/ui/src/commands/operations/open-feature-search.operation.ts
new file mode 100644
index 0000000000..99904e2d47
--- /dev/null
+++ b/packages/ui/src/commands/operations/open-feature-search.operation.ts
@@ -0,0 +1,42 @@
+/**
+ * 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 { IOperation } from '@univerjs/core';
+import { CommandType, LocaleService } from '@univerjs/core';
+import { IDialogService } from '../../services/dialog/dialog.service';
+import {
+ FEATURE_SEARCH_COMPONENT,
+ FEATURE_SEARCH_DIALOG_ID,
+} from '../../views/components/feature-search/FeatureSearch';
+
+export const OpenFeatureSearchOperation: IOperation = {
+ id: 'ui.operation.open-feature-search',
+ type: CommandType.OPERATION,
+ handler: (accessor) => {
+ const dialogService = accessor.get(IDialogService);
+ const localeService = accessor.get(LocaleService);
+
+ dialogService.open({
+ id: FEATURE_SEARCH_DIALOG_ID,
+ width: 560,
+ title: { title: localeService.t('ui.featureSearch.title') },
+ children: { label: FEATURE_SEARCH_COMPONENT },
+ onClose: () => dialogService.close(FEATURE_SEARCH_DIALOG_ID),
+ });
+
+ return true;
+ },
+};
diff --git a/packages/ui/src/common/__tests__/menu-hidden-observable.spec.ts b/packages/ui/src/common/__tests__/menu-hidden-observable.spec.ts
index ad4e353b06..d2648a2d6d 100644
--- a/packages/ui/src/common/__tests__/menu-hidden-observable.spec.ts
+++ b/packages/ui/src/common/__tests__/menu-hidden-observable.spec.ts
@@ -15,7 +15,7 @@
*/
import type { IAccessor } from '@univerjs/core';
-import { DocumentFlavor, UniverInstanceType } from '@univerjs/core';
+import { DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DocumentFlavor, UniverInstanceType } from '@univerjs/core';
import { Subject } from 'rxjs';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { getHeaderFooterMenuHiddenObservable, getMenuHiddenObservable } from '../menu-hidden-observable';
@@ -105,6 +105,23 @@ describe('getMenuHiddenObservable', () => {
sub.unsubscribe();
});
+ it('should treat the formula bar document as part of its sheet host', () => {
+ const { accessor } = createMenuAccessor({
+ focusedUnitId: DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
+ unitType: UniverInstanceType.UNIVER_DOC,
+ });
+ const sheetHiddenValues: boolean[] = [];
+ const docHiddenValues: boolean[] = [];
+ const sheetSub = getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET).subscribe((hidden) => sheetHiddenValues.push(hidden));
+ const docSub = getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC).subscribe((hidden) => docHiddenValues.push(hidden));
+
+ expect(sheetHiddenValues).toEqual([false]);
+ expect(docHiddenValues).toEqual([true]);
+
+ sheetSub.unsubscribe();
+ docSub.unsubscribe();
+ });
+
it('should hide when focused unit does not match matchUnitId', () => {
const { accessor, service } = createMenuAccessor({ focusedUnitId: 'expected-unit' });
const hiddenValues: boolean[] = [];
diff --git a/packages/ui/src/common/menu-hidden-observable.ts b/packages/ui/src/common/menu-hidden-observable.ts
index bbdceb0d8a..ff8155a229 100644
--- a/packages/ui/src/common/menu-hidden-observable.ts
+++ b/packages/ui/src/common/menu-hidden-observable.ts
@@ -15,7 +15,7 @@
*/
import type { DocumentDataModel, IAccessor } from '@univerjs/core';
-import { DocumentFlavor, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { DocumentFlavor, IUniverInstanceService, SHEET_EDITOR_UNITS, UniverInstanceType } from '@univerjs/core';
import { Observable } from 'rxjs';
export function getMenuHiddenObservable(
@@ -25,6 +25,9 @@ export function getMenuHiddenObservable(
needHideUnitId?: string | string[]
): Observable<boolean> {
const univerInstanceService = accessor.get(IUniverInstanceService);
+ const getUnitType = (unitId: string) => SHEET_EDITOR_UNITS.includes(unitId)
+ ? UniverInstanceType.UNIVER_SHEET
+ : univerInstanceService.getUnitType(unitId);
return new Observable((subscriber) => {
const subscription = univerInstanceService.focused$.subscribe((unitId) => {
@@ -38,7 +41,7 @@ export function getMenuHiddenObservable(
if (needHideUnitId && (Array.isArray(needHideUnitId) ? needHideUnitId.includes(unitId) : needHideUnitId === unitId)) {
return subscriber.next(true);
}
- const univerType = univerInstanceService.getUnitType(unitId);
+ const univerType = getUnitType(unitId);
subscriber.next(univerType !== targetUniverType);
});
@@ -49,7 +52,7 @@ export function getMenuHiddenObservable(
const currentUnit = univerInstanceService.getCurrentUnitOfType(targetUniverType);
subscriber.next(currentUnit == null);
} else {
- const univerType = univerInstanceService.getUnitType(focusedUniverInstance.getUnitId());
+ const univerType = getUnitType(focusedUniverInstance.getUnitId());
subscriber.next(univerType !== targetUniverType);
}
diff --git a/packages/ui/src/controllers/__tests__/misc-controllers.spec.ts b/packages/ui/src/controllers/__tests__/misc-controllers.spec.ts
index 989b599fcf..209a130835 100644
--- a/packages/ui/src/controllers/__tests__/misc-controllers.spec.ts
+++ b/packages/ui/src/controllers/__tests__/misc-controllers.spec.ts
@@ -14,13 +14,17 @@
* limitations under the License.
*/
+import { RedoCommand, UndoCommand } from '@univerjs/core';
import { Subject } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
+import { OpenFeatureSearchOperation } from '../../commands/operations/open-feature-search.operation';
import { ToggleShortcutPanelOperation } from '../../commands/operations/toggle-shortcut-panel.operation';
import { menuSchema } from '../../menu/schema';
+import { ShortcutPanelMenuItemFactory } from '../../menu/shortcut-panel.menu';
import { RibbonStartGroup } from '../../services/menu/types';
+import { KeyCode, MetaKeys } from '../../services/shortcut/keycode';
import { ErrorController } from '../error/error.controller';
-import { ShortcutPanelMenuItemFactory } from '../shortcut-display/menu';
+import { FeatureSearchController } from '../feature-search/feature-search.controller';
import { ShortcutPanelController } from '../shortcut-display/shortcut-panel.controller';
import { IUIController } from '../ui/ui.controller';
@@ -53,7 +57,7 @@ describe('shortcut-display controllers', () => {
id: ToggleShortcutPanelOperation.id,
title: 'ui.toggle-shortcut-panel',
tooltip: 'ui.toggle-shortcut-panel',
- icon: 'ShortcutIcon',
+ icon: 'KeyboardIcon',
type: 0,
});
});
@@ -79,6 +83,27 @@ describe('shortcut-display controllers', () => {
});
});
+describe('FeatureSearchController', () => {
+ it('registers the operation and a non-conflicting shortcut', () => {
+ const disposable = () => ({ dispose: vi.fn() });
+ const commandService = { registerCommand: vi.fn(disposable) };
+ const shortcutService = { registerShortcut: vi.fn(disposable) };
+ let controller: FeatureSearchController | undefined;
+
+ expect(() => {
+ controller = new FeatureSearchController(commandService as never, shortcutService as never);
+ }).not.toThrow();
+
+ expect(commandService.registerCommand).toHaveBeenCalledWith(OpenFeatureSearchOperation);
+ expect(shortcutService.registerShortcut).toHaveBeenCalledWith(expect.objectContaining({
+ id: OpenFeatureSearchOperation.id,
+ binding: MetaKeys.CTRL_COMMAND | MetaKeys.SHIFT | KeyCode.P,
+ }));
+
+ controller?.dispose();
+ });
+});
+
describe('menu schema and ui token', () => {
it('should expose static menu schema entries', () => {
const groupedSchema = menuSchema as Record<RibbonStartGroup.HISTORY | RibbonStartGroup.OTHERS, Record<string, unknown>>;
@@ -89,6 +114,11 @@ describe('menu schema and ui token', () => {
expect(others).toBeDefined();
expect(Object.keys(history).length).toBeGreaterThanOrEqual(2);
expect(Object.keys(others).length).toBeGreaterThanOrEqual(1);
+ expect((history[UndoCommand.id] as { gridLayout?: unknown }).gridLayout).toEqual({ row: 1, column: 1, iconSize: 18 });
+ expect((history[RedoCommand.id] as { gridLayout?: unknown }).gridLayout).toEqual({ row: 2, column: 1, iconSize: 18 });
+ const shortcutPanel = others[ToggleShortcutPanelOperation.id] as { order?: number; gridLayout?: unknown };
+ expect(shortcutPanel.order).toBe(1);
+ expect(shortcutPanel.gridLayout).toBeUndefined();
});
it('should expose ui controller identifier', () => {
diff --git a/packages/ui/src/controllers/components.controller.ts b/packages/ui/src/controllers/components.controller.ts
index 48694a18f7..41141fcbd1 100644
--- a/packages/ui/src/controllers/components.controller.ts
+++ b/packages/ui/src/controllers/components.controller.ts
@@ -16,11 +16,23 @@
import { Disposable, Inject } from '@univerjs/core';
import { ColorPicker } from '@univerjs/design';
-import { ExpandIcon, IncreaseIcon, MoreDownIcon, RedoIcon, ReduceIcon, ShortcutIcon, ShrinkIcon, UndoIcon } from '@univerjs/icons';
+import {
+ ExpandIcon,
+ FeatureSearchIcon,
+ IncreaseIcon,
+ KeyboardIcon,
+ MoreDownIcon,
+ RedoIcon,
+ ReduceIcon,
+ ShortcutIcon,
+ ShrinkIcon,
+ UndoIcon,
+} from '@univerjs/icons';
import { ShortcutPanelComponentName } from '../commands/operations/toggle-shortcut-panel.operation';
import { ComponentManager, IconManager } from '../common';
import { COLOR_PICKER_COMPONENT } from '../views/color-picker/interface';
import { COMMON_LABEL_COMPONENT, CommonLabel } from '../views/CommonLabel';
+import { FEATURE_SEARCH_COMPONENT, FeatureSearch } from '../views/components/feature-search/FeatureSearch';
import { ShortcutPanel } from '../views/components/shortcut-panel/ShortcutPanel';
import { EMOJI_PICKER_COMPONENT, EmojiPicker } from '../views/emoji-picker/index';
import {
@@ -48,9 +60,11 @@ export class ComponentsController extends Disposable {
this.disposeWithMe(this._iconManager.register({
ExpandIcon,
IncreaseIcon,
+ KeyboardIcon,
MoreDownIcon,
RedoIcon,
ReduceIcon,
+ FeatureSearchIcon,
ShortcutIcon,
ShrinkIcon,
UndoIcon,
@@ -66,6 +80,7 @@ export class ComponentsController extends Disposable {
[FONT_SIZE_COMPONENT, FontSize],
[COLOR_PICKER_COMPONENT, ColorPicker],
[EMOJI_PICKER_COMPONENT, EmojiPicker],
+ [FEATURE_SEARCH_COMPONENT, FeatureSearch],
] as const).forEach(([key, comp]) => {
this.disposeWithMe(
this._componentManager.register(key, comp)
diff --git a/packages/ui/src/controllers/feature-search/feature-search.controller.ts b/packages/ui/src/controllers/feature-search/feature-search.controller.ts
new file mode 100644
index 0000000000..8834cd136d
--- /dev/null
+++ b/packages/ui/src/controllers/feature-search/feature-search.controller.ts
@@ -0,0 +1,41 @@
+/**
+ * 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 { IShortcutItem } from '../../services/shortcut/shortcut.service';
+import { Disposable, ICommandService } from '@univerjs/core';
+import { OpenFeatureSearchOperation } from '../../commands/operations/open-feature-search.operation';
+import { KeyCode, MetaKeys } from '../../services/shortcut/keycode';
+import { IShortcutService } from '../../services/shortcut/shortcut.service';
+
+const FeatureSearchShortcut: IShortcutItem = {
+ id: OpenFeatureSearchOperation.id,
+ binding: MetaKeys.CTRL_COMMAND | MetaKeys.SHIFT | KeyCode.P,
+ description: 'ui.featureSearch.title',
+ group: '10_global-shortcut',
+ groupTitle: 'ui.global-shortcut',
+};
+
+export class FeatureSearchController extends Disposable {
+ constructor(
+ @ICommandService commandService: ICommandService,
+ @IShortcutService shortcutService: IShortcutService
+ ) {
+ super();
+
+ this.disposeWithMe(commandService.registerCommand(OpenFeatureSearchOperation));
+ this.disposeWithMe(shortcutService.registerShortcut(FeatureSearchShortcut));
+ }
+}
diff --git a/packages/ui/src/controllers/menus/__tests__/menus.spec.ts b/packages/ui/src/controllers/menus/__tests__/menus.spec.ts
index ea120c476f..95c0507bc8 100644
--- a/packages/ui/src/controllers/menus/__tests__/menus.spec.ts
+++ b/packages/ui/src/controllers/menus/__tests__/menus.spec.ts
@@ -15,11 +15,16 @@
*/
import type { IAccessor } from '@univerjs/core';
-import type { Observable } from 'rxjs';
-import { EDITOR_ACTIVATED, FOCUSING_FX_BAR_EDITOR, IContextService, IUndoRedoService, LocaleService } from '@univerjs/core';
-import { BehaviorSubject, isObservable, Subject } from 'rxjs';
+import {
+ EDITOR_ACTIVATED,
+ FOCUSING_FX_BAR_EDITOR,
+ IContextService,
+ IUndoRedoService,
+ LocaleService,
+} from '@univerjs/core';
+import { BehaviorSubject, Subject } from 'rxjs';
import { describe, expect, it } from 'vitest';
-import { RedoMenuItemFactory, UndoMenuItemFactory } from '../menus';
+import { RedoMenuItemFactory, UndoMenuItemFactory } from '../../../menu/history.menu';
function createAccessor() {
const undoRedoStatus$ = new BehaviorSubject({ undos: 1, redos: 1 });
@@ -98,36 +103,4 @@ describe('menus controller factories', () => {
sub.unsubscribe();
});
-
- it('should use rtl-specific undo and redo icons when locale direction changes', () => {
- const { accessor, direction$ } = createAccessor();
- const undoItem = UndoMenuItemFactory(accessor);
- const redoItem = RedoMenuItemFactory(accessor);
- const undoIcon$ = undoItem.icon as Observable<string>;
- const redoIcon$ = redoItem.icon as Observable<string>;
- const undoIcons: string[] = [];
- const redoIcons: string[] = [];
-
- expect(isObservable(undoItem.icon)).toBe(true);
- expect(isObservable(redoItem.icon)).toBe(true);
-
- const undoSub = undoIcon$.subscribe((icon) => undoIcons.push(icon));
- const redoSub = redoIcon$.subscribe((icon) => redoIcons.push(icon));
-
- expect(undoIcons.at(-1)).toBe('UndoIcon');
- expect(redoIcons.at(-1)).toBe('RedoIcon');
-
- direction$.next('rtl');
-
- expect(undoIcons.at(-1)).toBe('RedoIcon');
- expect(redoIcons.at(-1)).toBe('UndoIcon');
-
- direction$.next('ltr');
-
- expect(undoIcons.at(-1)).toBe('UndoIcon');
- expect(redoIcons.at(-1)).toBe('RedoIcon');
-
- undoSub.unsubscribe();
- redoSub.unsubscribe();
- });
});
diff --git a/packages/ui/src/controllers/ui/ui.controller.ts b/packages/ui/src/controllers/ui/ui.controller.ts
index 95924e31da..0543da2930 100644
--- a/packages/ui/src/controllers/ui/ui.controller.ts
+++ b/packages/ui/src/controllers/ui/ui.controller.ts
@@ -17,7 +17,7 @@
import type { IFontConfig } from '../../services/font.service';
import { createIdentifier } from '@univerjs/core';
-export type RibbonType = 'collapsed' | 'simple' | 'classic';
+export type RibbonType = 'collapsed' | 'simple' | 'classic' | 'grid';
export interface IWorkbenchOptions {
container?: string | HTMLElement;
diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts
index 9c5cd902d9..951e5bf5b4 100644
--- a/packages/ui/src/index.ts
+++ b/packages/ui/src/index.ts
@@ -36,7 +36,7 @@ export { ShortcutPanelController } from './controllers/shortcut-display/shortcut
export { DesktopUIController } from './controllers/ui/ui-desktop.controller';
export { SingleUnitUIController } from './controllers/ui/ui-shared.controller';
export { IUIController } from './controllers/ui/ui.controller';
-export type { IWorkbenchOptions } from './controllers/ui/ui.controller';
+export type { IWorkbenchOptions, RibbonType } from './controllers/ui/ui.controller';
export { menuSchema as UIMenuSchema } from './menu/schema';
export { UniverMobileUIPlugin } from './mobile-plugin';
export { DISABLE_AUTO_FOCUS_KEY, UniverUIPlugin } from './plugin';
@@ -91,8 +91,7 @@ export type {
MenuItemDefaultValueType,
} from './services/menu/menu';
export { IMenuManagerService, MenuManagerService } from './services/menu/menu-manager.service';
-export type { MenuSchemaType } from './services/menu/menu-manager.service';
-export { type IMenuSchema } from './services/menu/menu-manager.service';
+export type { IMenuSchema, IRibbonGridLayout, MenuSchemaType } from './services/menu/menu-manager.service';
export {
ContextMenuGroup,
ContextMenuPosition,
diff --git a/packages/ui/src/locale/ar-SA.ts b/packages/ui/src/locale/ar-SA.ts
index cf6fc33c45..1d44ed0fbc 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: {
+ featureSearch: {
+ title: 'بحث عن الميزات',
+ placeholder: 'اكتب اسم ميزة أو قائمة...',
+ empty: 'لم يتم العثور على ميزات متاحة',
+ ribbon: 'الشريط',
+ contextMenu: 'قائمة السياق',
+ },
emojiPicker: {
search: 'بحث',
random: 'رمز تعبيري عشوائي',
diff --git a/packages/ui/src/locale/ca-ES.ts b/packages/ui/src/locale/ca-ES.ts
index 83a73e1532..19ffa8e277 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: {
+ featureSearch: {
+ title: 'Cerca funcions',
+ placeholder: 'Escriviu una funció o un nom de menú...',
+ empty: 'No s\'han trobat funcions disponibles',
+ ribbon: 'Cinta',
+ contextMenu: 'Menú contextual',
+ },
emojiPicker: {
search: 'Cerca',
random: 'Emoji aleatori',
diff --git a/packages/ui/src/locale/de-DE.ts b/packages/ui/src/locale/de-DE.ts
index 616f00016f..b907fcef61 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: {
+ featureSearch: {
+ title: 'Funktionen suchen',
+ placeholder: 'Funktion oder Menüname eingeben...',
+ empty: 'Keine verfügbaren Funktionen gefunden',
+ ribbon: 'Menüband',
+ contextMenu: 'Kontextmenü',
+ },
emojiPicker: {
search: 'Suchen',
random: 'Zufälliges Emoji',
diff --git a/packages/ui/src/locale/en-US.ts b/packages/ui/src/locale/en-US.ts
index 3836155ea8..b66368a669 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: {
+ featureSearch: {
+ title: 'Search features',
+ placeholder: 'Type a feature or menu name...',
+ empty: 'No available features found',
+ ribbon: 'Ribbon',
+ contextMenu: 'Context menu',
+ },
emojiPicker: {
search: 'Search',
random: 'Random emoji',
diff --git a/packages/ui/src/locale/es-ES.ts b/packages/ui/src/locale/es-ES.ts
index 81f946b638..3afe7aaae5 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: {
+ featureSearch: {
+ title: 'Buscar funciones',
+ placeholder: 'Escribe una función o nombre de menú...',
+ empty: 'No se encontraron funciones disponibles',
+ ribbon: 'Cinta',
+ contextMenu: 'Menú contextual',
+ },
emojiPicker: {
search: 'Buscar',
random: 'Emoji aleatorio',
diff --git a/packages/ui/src/locale/fa-IR.ts b/packages/ui/src/locale/fa-IR.ts
index b56788d4c6..8ea3189d1a 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: {
+ featureSearch: {
+ title: 'جستجوی قابلیت‌ها',
+ placeholder: 'نام قابلیت یا منو را وارد کنید…',
+ empty: 'هیچ قابلیت در دسترسی یافت نشد',
+ ribbon: 'نوار ابزار',
+ contextMenu: 'منوی زمینه‌ای',
+ },
emojiPicker: {
search: 'جستجو',
random: 'ایموجی تصادفی',
diff --git a/packages/ui/src/locale/fr-FR.ts b/packages/ui/src/locale/fr-FR.ts
index 0f509cce81..16ac112ff1 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: {
+ featureSearch: {
+ title: 'Rechercher des fonctionnalités',
+ placeholder: 'Saisissez une fonctionnalité ou un nom de menu...',
+ empty: 'Aucune fonctionnalité disponible trouvée',
+ ribbon: 'Ruban',
+ contextMenu: 'Menu contextuel',
+ },
emojiPicker: {
search: 'Rechercher',
random: 'Emoji aléatoire',
diff --git a/packages/ui/src/locale/id-ID.ts b/packages/ui/src/locale/id-ID.ts
index 80a8c8553a..e304876237 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: {
+ featureSearch: {
+ title: 'Cari fitur',
+ placeholder: 'Ketik nama fitur atau menu...',
+ empty: 'Tidak ada fitur yang tersedia',
+ ribbon: 'Pita',
+ contextMenu: 'Menu konteks',
+ },
emojiPicker: {
search: 'Cari',
random: 'Emoji acak',
diff --git a/packages/ui/src/locale/it-IT.ts b/packages/ui/src/locale/it-IT.ts
index 1fbfabc6fe..34cee8446a 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: {
+ featureSearch: {
+ title: 'Cerca funzionalità',
+ placeholder: 'Digita una funzionalità o il nome di un menu...',
+ empty: 'Nessuna funzionalità disponibile trovata',
+ ribbon: 'Barra multifunzione',
+ contextMenu: 'Menu contestuale',
+ },
emojiPicker: {
search: 'Cerca',
random: 'Emoji casuale',
diff --git a/packages/ui/src/locale/ja-JP.ts b/packages/ui/src/locale/ja-JP.ts
index 64d964cb9f..1a0e59e774 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: {
+ featureSearch: {
+ title: '機能を検索',
+ placeholder: '機能またはメニュー名を入力…',
+ empty: '利用可能な機能が見つかりません',
+ ribbon: 'リボン',
+ contextMenu: 'コンテキストメニュー',
+ },
emojiPicker: {
search: '検索',
random: 'ランダム絵文字',
diff --git a/packages/ui/src/locale/ko-KR.ts b/packages/ui/src/locale/ko-KR.ts
index 62e1d21935..0966fdc157 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: {
+ featureSearch: {
+ title: '기능 검색',
+ placeholder: '기능 또는 메뉴 이름 입력...',
+ empty: '사용 가능한 기능을 찾을 수 없습니다',
+ ribbon: '리본',
+ contextMenu: '상황에 맞는 메뉴',
+ },
emojiPicker: {
search: '검색',
random: '무작위 이모지',
diff --git a/packages/ui/src/locale/pl-PL.ts b/packages/ui/src/locale/pl-PL.ts
index 4e594cd3d3..435f8ac531 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: {
+ featureSearch: {
+ title: 'Wyszukaj funkcje',
+ placeholder: 'Wpisz nazwę funkcji lub menu...',
+ empty: 'Nie znaleziono dostępnych funkcji',
+ ribbon: 'Wstążka',
+ contextMenu: 'Menu kontekstowe',
+ },
emojiPicker: {
search: 'Szukaj',
random: 'Losowe emoji',
diff --git a/packages/ui/src/locale/pt-BR.ts b/packages/ui/src/locale/pt-BR.ts
index 0891feae79..645bd9f04e 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: {
+ featureSearch: {
+ title: 'Pesquisar recursos',
+ placeholder: 'Digite um recurso ou nome de menu...',
+ empty: 'Nenhum recurso disponível encontrado',
+ ribbon: 'Faixa de opções',
+ contextMenu: 'Menu de contexto',
+ },
emojiPicker: {
search: 'Buscar',
random: 'Emoji aleatório',
diff --git a/packages/ui/src/locale/ru-RU.ts b/packages/ui/src/locale/ru-RU.ts
index 63808b12a9..f2d48158bf 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: {
+ featureSearch: {
+ title: 'Поиск функций',
+ placeholder: 'Введите название функции или меню...',
+ empty: 'Доступные функции не найдены',
+ ribbon: 'Лента',
+ contextMenu: 'Контекстное меню',
+ },
emojiPicker: {
search: 'Поиск',
random: 'Случайный эмодзи',
diff --git a/packages/ui/src/locale/sk-SK.ts b/packages/ui/src/locale/sk-SK.ts
index 8a9ead4c29..79668e77a3 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: {
+ featureSearch: {
+ title: 'Vyhľadať funkcie',
+ placeholder: 'Zadajte názov funkcie alebo ponuky...',
+ empty: 'Nenašli sa žiadne dostupné funkcie',
+ ribbon: 'Pás s nástrojmi',
+ contextMenu: 'Kontextová ponuka',
+ },
emojiPicker: {
search: 'Hľadať',
random: 'Náhodné emoji',
diff --git a/packages/ui/src/locale/vi-VN.ts b/packages/ui/src/locale/vi-VN.ts
index a5ad79047b..14c4d16716 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: {
+ featureSearch: {
+ title: 'Tìm kiếm tính năng',
+ placeholder: 'Nhập tên tính năng hoặc menu...',
+ empty: 'Không tìm thấy tính năng khả dụng',
+ ribbon: 'Dải băng',
+ contextMenu: 'Menu ngữ cảnh',
+ },
emojiPicker: {
search: 'Tìm kiếm',
random: 'Emoji ngẫu nhiên',
diff --git a/packages/ui/src/locale/zh-CN.ts b/packages/ui/src/locale/zh-CN.ts
index 59f854fdce..52a542aa75 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: {
+ featureSearch: {
+ title: '搜索功能',
+ placeholder: '输入功能或菜单名称…',
+ empty: '未找到当前可用的功能',
+ ribbon: '功能区',
+ contextMenu: '右键菜单',
+ },
emojiPicker: {
search: '搜索',
random: '随机表情',
diff --git a/packages/ui/src/locale/zh-HK.ts b/packages/ui/src/locale/zh-HK.ts
index 1505afee12..e75b170649 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: {
+ featureSearch: {
+ title: '搜尋功能',
+ placeholder: '輸入功能或選單名稱…',
+ empty: '找不到目前可用的功能',
+ ribbon: '功能區',
+ contextMenu: '內容選單',
+ },
emojiPicker: {
search: '搜尋',
random: '隨機表情',
diff --git a/packages/ui/src/locale/zh-TW.ts b/packages/ui/src/locale/zh-TW.ts
index 4cb0ae8512..63f797a4b8 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: {
+ featureSearch: {
+ title: '搜尋功能',
+ placeholder: '輸入功能或選單名稱…',
+ empty: '找不到目前可用的功能',
+ ribbon: '功能區',
+ contextMenu: '快顯功能表',
+ },
emojiPicker: {
search: '搜尋',
random: '隨機表情',
diff --git a/packages/ui/src/menu/feature-search.menu.ts b/packages/ui/src/menu/feature-search.menu.ts
new file mode 100644
index 0000000000..8704c0b308
--- /dev/null
+++ b/packages/ui/src/menu/feature-search.menu.ts
@@ -0,0 +1,30 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { LocaleKey } from '../locale/types';
+import type { IMenuButtonItem } from '../services/menu/menu';
+import { OpenFeatureSearchOperation } from '../commands/operations/open-feature-search.operation';
+import { MenuItemType } from '../services/menu/menu';
+
+export function FeatureSearchMenuItemFactory(): IMenuButtonItem<LocaleKey> {
+ return {
+ id: OpenFeatureSearchOperation.id,
+ title: 'ui.featureSearch.title',
+ tooltip: 'ui.featureSearch.title',
+ icon: 'FeatureSearchIcon',
+ type: MenuItemType.BUTTON,
+ };
+}
diff --git a/packages/ui/src/controllers/menus/menus.ts b/packages/ui/src/menu/history.menu.ts
similarity index 93%
rename from packages/ui/src/controllers/menus/menus.ts
rename to packages/ui/src/menu/history.menu.ts
index 2632fcb19e..07b7f0ffb4 100644
--- a/packages/ui/src/controllers/menus/menus.ts
+++ b/packages/ui/src/menu/history.menu.ts
@@ -15,8 +15,8 @@
*/
import type { IAccessor } from '@univerjs/core';
-import type { LocaleKey } from '../../locale/types';
-import type { IMenuButtonItem } from '../../services/menu/menu';
+import type { LocaleKey } from '../locale/types';
+import type { IMenuButtonItem } from '../services/menu/menu';
import {
EDITOR_ACTIVATED,
FOCUSING_FX_BAR_EDITOR,
@@ -28,7 +28,7 @@ import {
} from '@univerjs/core';
import { combineLatest, merge, of } from 'rxjs';
import { map } from 'rxjs/operators';
-import { MenuItemType } from '../../services/menu/menu';
+import { MenuItemType } from '../services/menu/menu';
const undoRedoDisableFactory$ = (accessor: IAccessor, isUndo: boolean) => {
const undoRedoService = accessor.get(IUndoRedoService);
diff --git a/packages/ui/src/menu/schema.ts b/packages/ui/src/menu/schema.ts
index 8c55b3b38a..25145ff1ff 100644
--- a/packages/ui/src/menu/schema.ts
+++ b/packages/ui/src/menu/schema.ts
@@ -16,19 +16,23 @@
import type { MenuSchemaType } from '../services/menu/menu-manager.service';
import { RedoCommand, UndoCommand } from '@univerjs/core';
+import { OpenFeatureSearchOperation } from '../commands/operations/open-feature-search.operation';
import { ToggleShortcutPanelOperation } from '../commands/operations/toggle-shortcut-panel.operation';
-import { RedoMenuItemFactory, UndoMenuItemFactory } from '../controllers/menus/menus';
-import { ShortcutPanelMenuItemFactory } from '../controllers/shortcut-display/menu';
import { RibbonStartGroup } from '../services/menu/types';
+import { FeatureSearchMenuItemFactory } from './feature-search.menu';
+import { RedoMenuItemFactory, UndoMenuItemFactory } from './history.menu';
+import { ShortcutPanelMenuItemFactory } from './shortcut-panel.menu';
export const menuSchema: MenuSchemaType = {
[RibbonStartGroup.HISTORY]: {
[UndoCommand.id]: {
order: 0,
+ gridLayout: { row: 1, column: 1, iconSize: 18 },
menuItemFactory: UndoMenuItemFactory,
},
[RedoCommand.id]: {
order: 1,
+ gridLayout: { row: 2, column: 1, iconSize: 18 },
menuItemFactory: RedoMenuItemFactory,
},
},
@@ -37,5 +41,9 @@ export const menuSchema: MenuSchemaType = {
order: 1,
menuItemFactory: ShortcutPanelMenuItemFactory,
},
+ [OpenFeatureSearchOperation.id]: {
+ order: 2,
+ menuItemFactory: FeatureSearchMenuItemFactory,
+ },
},
};
diff --git a/packages/ui/src/controllers/shortcut-display/menu.ts b/packages/ui/src/menu/shortcut-panel.menu.ts
similarity index 73%
rename from packages/ui/src/controllers/shortcut-display/menu.ts
rename to packages/ui/src/menu/shortcut-panel.menu.ts
index e5ca9995d4..da22b29361 100644
--- a/packages/ui/src/controllers/shortcut-display/menu.ts
+++ b/packages/ui/src/menu/shortcut-panel.menu.ts
@@ -14,17 +14,17 @@
* limitations under the License.
*/
-import type { LocaleKey } from '../../locale/types';
-import type { IMenuButtonItem } from '../../services/menu/menu';
-import { ToggleShortcutPanelOperation } from '../../commands/operations/toggle-shortcut-panel.operation';
-import { MenuItemType } from '../../services/menu/menu';
+import type { LocaleKey } from '../locale/types';
+import type { IMenuButtonItem } from '../services/menu/menu';
+import { ToggleShortcutPanelOperation } from '../commands/operations/toggle-shortcut-panel.operation';
+import { MenuItemType } from '../services/menu/menu';
export function ShortcutPanelMenuItemFactory(): IMenuButtonItem<LocaleKey> {
return {
id: ToggleShortcutPanelOperation.id,
title: 'ui.toggle-shortcut-panel',
tooltip: 'ui.toggle-shortcut-panel',
- icon: 'ShortcutIcon',
+ icon: 'KeyboardIcon',
type: MenuItemType.BUTTON,
};
}
diff --git a/packages/ui/src/mobile-plugin.ts b/packages/ui/src/mobile-plugin.ts
index 7fcf80399f..498fcbd084 100644
--- a/packages/ui/src/mobile-plugin.ts
+++ b/packages/ui/src/mobile-plugin.ts
@@ -15,7 +15,21 @@
*/
import type { IUniverUIConfig } from './config/config';
-import { DependentOn, generateRandomId, IConfigService, IConfirmService, IContextService, ILocalStorageService, Inject, Injector, merge, mergeOverrideWithDependencies, Plugin, registerDependencies, touchDependencies } from '@univerjs/core';
+import {
+ DependentOn,
+ generateRandomId,
+ IConfigService,
+ IConfirmService,
+ IContextService,
+ ILocalStorageService,
+ Inject,
+ Injector,
+ merge,
+ mergeOverrideWithDependencies,
+ Plugin,
+ registerDependencies,
+ touchDependencies,
+} from '@univerjs/core';
import { UniverRenderEnginePlugin } from '@univerjs/engine-render';
import pkg from '../package.json';
import { ComponentManager } from './common/component-manager';
@@ -24,6 +38,7 @@ import { ZIndexManager } from './common/z-index-manager';
import { defaultPluginConfig, UI_PLUGIN_CONFIG_KEY } from './config/config';
import { ComponentsController } from './controllers/components.controller';
import { ErrorController } from './controllers/error/error.controller';
+import { FeatureSearchController } from './controllers/feature-search/feature-search.controller';
import { SharedController } from './controllers/shared-shortcut.controller';
import { ShortcutPanelController } from './controllers/shortcut-display/shortcut-panel.controller';
import { MobileUIController } from './controllers/ui/ui-mobile.controller';
@@ -137,6 +152,7 @@ export class UniverMobileUIPlugin extends Plugin {
],
[SharedController],
[ErrorController],
+ [FeatureSearchController],
[ShortcutPanelController],
], this._config.override));
@@ -150,6 +166,7 @@ export class UniverMobileUIPlugin extends Plugin {
override onReady(): void {
touchDependencies(this._injector, [
[SharedController],
+ [FeatureSearchController],
]);
}
diff --git a/packages/ui/src/plugin.ts b/packages/ui/src/plugin.ts
index 4e6928ce04..6788735409 100644
--- a/packages/ui/src/plugin.ts
+++ b/packages/ui/src/plugin.ts
@@ -15,7 +15,21 @@
*/
import type { IUniverUIConfig } from './config/config';
-import { DependentOn, generateRandomId, IConfigService, IConfirmService, IContextService, ILocalStorageService, Inject, Injector, merge, mergeOverrideWithDependencies, Plugin, registerDependencies, touchDependencies } from '@univerjs/core';
+import {
+ DependentOn,
+ generateRandomId,
+ IConfigService,
+ IConfirmService,
+ IContextService,
+ ILocalStorageService,
+ Inject,
+ Injector,
+ merge,
+ mergeOverrideWithDependencies,
+ Plugin,
+ registerDependencies,
+ touchDependencies,
+} from '@univerjs/core';
import { UniverRenderEnginePlugin } from '@univerjs/engine-render';
import pkg from '../package.json';
import { ComponentManager } from './common/component-manager';
@@ -24,6 +38,7 @@ import { ZIndexManager } from './common/z-index-manager';
import { defaultPluginConfig, UI_PLUGIN_CONFIG_KEY } from './config/config';
import { ComponentsController } from './controllers/components.controller';
import { ErrorController } from './controllers/error/error.controller';
+import { FeatureSearchController } from './controllers/feature-search/feature-search.controller';
import { SharedController } from './controllers/shared-shortcut.controller';
import { ShortcutPanelController } from './controllers/shortcut-display/shortcut-panel.controller';
import { DesktopUIController } from './controllers/ui/ui-desktop.controller';
@@ -135,6 +150,7 @@ export class UniverUIPlugin extends Plugin {
}],
[SharedController],
[ErrorController],
+ [FeatureSearchController],
[ShortcutPanelController],
], this._config.override));
@@ -148,6 +164,7 @@ export class UniverUIPlugin extends Plugin {
override onReady(): void {
touchDependencies(this._injector, [
[SharedController],
+ [FeatureSearchController],
]);
}
diff --git a/packages/ui/src/services/menu/menu-manager.service.ts b/packages/ui/src/services/menu/menu-manager.service.ts
index 6902e03e4c..fd5665e316 100644
--- a/packages/ui/src/services/menu/menu-manager.service.ts
+++ b/packages/ui/src/services/menu/menu-manager.service.ts
@@ -27,6 +27,16 @@ export const IMenuManagerService = createIdentifier<IMenuManagerService>('univer
export type ContextMenuQuickLayout = 'icon' | 'tile';
export type ContextMenuQuickLayoutVariant = 'default' | 'compact';
+export interface IRibbonGridLayout {
+ row: number;
+ column: number;
+ rowSpan?: number;
+ columnSpan?: number;
+ showLabel?: boolean;
+ width?: number;
+ iconSize?: number;
+}
+
export interface IMenuSchema {
key: string;
order: number;
@@ -39,6 +49,7 @@ export interface IMenuSchema {
quickColumns?: number;
quickLayoutVariant?: ContextMenuQuickLayoutVariant;
tiny?: boolean;
+ gridLayout?: IRibbonGridLayout;
}
export interface IMenuManagerService {
@@ -64,6 +75,7 @@ export type MenuSchemaType = {
quickColumns?: number;
quickLayoutVariant?: ContextMenuQuickLayoutVariant;
tiny?: boolean;
+ gridLayout?: IRibbonGridLayout;
} | {
[key: string]: MenuSchemaType;
};
@@ -85,9 +97,12 @@ export class MenuManagerService extends Disposable implements IMenuManagerServic
[RibbonStartGroup.LAYOUT]: {
order: 2,
},
- [RibbonStartGroup.OTHERS]: {
+ [RibbonStartGroup.NUMBER]: {
order: 3,
},
+ [RibbonStartGroup.OTHERS]: {
+ order: 4,
+ },
},
[RibbonPosition.INSERT]: {
order: 1,
@@ -330,6 +345,7 @@ export class MenuManagerService extends Disposable implements IMenuManagerServic
quickColumns: value.quickColumns,
quickLayoutVariant: value.quickLayoutVariant,
tiny: value.tiny,
+ gridLayout: value.gridLayout,
};
if (value.menuItemFactory) {
diff --git a/packages/ui/src/services/menu/types.ts b/packages/ui/src/services/menu/types.ts
index 4294e3020a..9f313c98d5 100644
--- a/packages/ui/src/services/menu/types.ts
+++ b/packages/ui/src/services/menu/types.ts
@@ -32,6 +32,7 @@ export enum RibbonStartGroup {
HISTORY = 'ribbon.start.history',
FORMAT = 'ribbon.start.format',
LAYOUT = 'ribbon.start.layout',
+ NUMBER = 'ribbon.start.number',
OTHERS = 'ribbon.start.others',
}
diff --git a/packages/ui/src/services/ribbon/__tests__/ribbon.service.spec.ts b/packages/ui/src/services/ribbon/__tests__/ribbon.service.spec.ts
index e8b20eb4a1..783bfb3505 100644
--- a/packages/ui/src/services/ribbon/__tests__/ribbon.service.spec.ts
+++ b/packages/ui/src/services/ribbon/__tests__/ribbon.service.spec.ts
@@ -26,7 +26,7 @@ import {
IUniverInstanceService,
UniverInstanceService,
} from '@univerjs/core';
-import { BehaviorSubject } from 'rxjs';
+import { BehaviorSubject, Observable, Subject } from 'rxjs';
import { describe, expect, it } from 'vitest';
import { MenuItemType } from '../../menu/menu';
import { IMenuManagerService, MenuManagerService } from '../../menu/menu-manager.service';
@@ -185,6 +185,43 @@ describe('DesktopRibbonService', () => {
ribbonSub.unsubscribe();
});
+ it('filters a hidden command even when another hidden state has not emitted', () => {
+ const { service, menuManagerService } = createService();
+ const silentHidden$ = new Subject<boolean>();
+ const hidden$ = new BehaviorSubject(true);
+ let latestRibbon: IMenuSchema[] = [];
+ const ribbonSub = service.ribbon$.subscribe((ribbon) => latestRibbon = ribbon);
+
+ menuManagerService.appendRootMenu({
+ [MenuManagerPosition.RIBBON]: {
+ [RibbonPosition.START]: {
+ order: 0,
+ [`${RibbonPosition.START}.hidden-group`]: {
+ order: 0,
+ silentCommand: {
+ order: 0,
+ menuItemFactory: () => ({ id: 'silent-command', type: MenuItemType.BUTTON, hidden$: silentHidden$ }),
+ },
+ hiddenCommand: {
+ order: 1,
+ menuItemFactory: () => ({ id: 'hidden-command', type: MenuItemType.BUTTON, hidden$ }),
+ },
+ },
+ },
+ },
+ } as MenuSchemaType);
+
+ const commandKeys = latestRibbon
+ .find((group) => group.key === RibbonPosition.START)
+ ?.children
+ ?.flatMap((group) => group.children ?? [])
+ .map((child) => child.key);
+ expect(commandKeys).toContain('silentCommand');
+ expect(commandKeys).not.toContain('hiddenCommand');
+
+ ribbonSub.unsubscribe();
+ });
+
it('does not republish the ribbon when focus emits the same unit id', () => {
const focused$ = new BehaviorSubject<string | null>('unit-1');
const { service, menuManagerService } = createService({ focused$ });
@@ -217,4 +254,45 @@ describe('DesktopRibbonService', () => {
ribbonSub.unsubscribe();
});
+
+ it('unsubscribes hidden states that are no longer in the ribbon', () => {
+ const { menuManagerService } = createService();
+ let subscriptions = 0;
+ let unsubscriptions = 0;
+ const hidden$ = new Observable<boolean>(() => {
+ subscriptions += 1;
+ return () => {
+ unsubscriptions += 1;
+ };
+ });
+ const groupKey = `${RibbonPosition.START}.temporary-group`;
+
+ menuManagerService.appendRootMenu({
+ [MenuManagerPosition.RIBBON]: {
+ [RibbonPosition.START]: {
+ [groupKey]: {
+ order: 0,
+ temporaryCommand: {
+ order: 0,
+ menuItemFactory: () => ({ id: 'temporary-command', type: MenuItemType.BUTTON, hidden$ }),
+ },
+ },
+ },
+ },
+ } as MenuSchemaType);
+ expect(subscriptions).toBe(1);
+
+ menuManagerService.mergeMenu({
+ [groupKey]: {
+ replace: true,
+ order: 0,
+ visibleCommand: {
+ order: 0,
+ menuItemFactory: () => ({ id: 'visible-command', type: MenuItemType.BUTTON }),
+ },
+ },
+ } as MenuSchemaType);
+
+ expect(unsubscriptions).toBe(1);
+ });
});
diff --git a/packages/ui/src/services/ribbon/ribbon.service.ts b/packages/ui/src/services/ribbon/ribbon.service.ts
index 54be7c3831..3784d7c480 100644
--- a/packages/ui/src/services/ribbon/ribbon.service.ts
+++ b/packages/ui/src/services/ribbon/ribbon.service.ts
@@ -144,18 +144,16 @@ export class DesktopRibbonService extends Disposable implements IRibbonService {
}
}
+ this._hiddenSubscription?.unsubscribe();
+ this._hiddenSubscription = null;
+
if (hiddenObservableMap.length === 0) {
this._setRibbon(ribbon);
return;
}
- this._hiddenSubscription?.unsubscribe();
-
- this._hiddenSubscription = combineLatest(hiddenObservableMap)
- .pipe(
- startWith(new Array(hiddenObservableMap.length).fill(false)),
- distinctUntilChanged(isSameHiddenMap)
- )
+ this._hiddenSubscription = combineLatest(hiddenObservableMap.map((hidden$) => hidden$.pipe(startWith(false))))
+ .pipe(distinctUntilChanged(isSameHiddenMap))
.subscribe((hiddenMap) => {
const newRibbon: IMenuSchema[] = [];
diff --git a/packages/ui/src/views/components/context-menu/ContextMenuPanel.tsx b/packages/ui/src/views/components/context-menu/ContextMenuPanel.tsx
index 3fce91a306..73dac2166c 100644
--- a/packages/ui/src/views/components/context-menu/ContextMenuPanel.tsx
+++ b/packages/ui/src/views/components/context-menu/ContextMenuPanel.tsx
@@ -1178,6 +1178,12 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
useEffect(() => () => clearSubmenuCloseTimer(), [clearSubmenuCloseTimer]);
+ useEffect(() => {
+ if (disabled) {
+ closeSubmenu();
+ }
+ }, [closeSubmenu, disabled]);
+
useEffect(() => {
if (!submenuVisible) {
setSubmenuPositionReady(false);
diff --git a/packages/ui/src/views/components/context-menu/__tests__/ContextMenuPanel.spec.tsx b/packages/ui/src/views/components/context-menu/__tests__/ContextMenuPanel.spec.tsx
index 6dd6703822..ee82be61d4 100644
--- a/packages/ui/src/views/components/context-menu/__tests__/ContextMenuPanel.spec.tsx
+++ b/packages/ui/src/views/components/context-menu/__tests__/ContextMenuPanel.spec.tsx
@@ -518,6 +518,40 @@ describe('ContextMenuPanel', () => {
expect(screen.getByText('translated:docs-ui.fillColor')).not.toBeNull();
});
+ it('closes an open submenu when its parent becomes disabled', async () => {
+ const disabled$ = new BehaviorSubject(false);
+
+ renderWithDependencies(
+ <ContextMenuPanel menuType="submenu-root" />,
+ {
+ 'submenu-root': [
+ {
+ key: 'print',
+ order: 0,
+ item: {
+ id: 'print',
+ type: MenuItemType.SUBITEMS,
+ title: 'docs-ui.print',
+ disabled$,
+ },
+ },
+ ],
+ print: [
+ createButtonItem('print-layout', {
+ title: 'docs-ui.printLayout',
+ }),
+ ],
+ }
+ );
+
+ const printButton = screen.getByRole('button', { name: 'translated:docs-ui.print' });
+ fireEvent.mouseEnter(printButton.parentElement as HTMLElement);
+ expect(screen.getByText('translated:docs-ui.printLayout')).not.toBeNull();
+
+ act(() => disabled$.next(true));
+ await waitFor(() => expect(screen.queryByText('translated:docs-ui.printLayout')).toBeNull());
+ });
+
it('opens submenus to the left by default in rtl when there is enough space', async () => {
renderWithDependencies(
<ContextMenuPanel menuType="submenu-root" />,
diff --git a/packages/ui/src/views/components/feature-search/FeatureSearch.tsx b/packages/ui/src/views/components/feature-search/FeatureSearch.tsx
new file mode 100644
index 0000000000..ee5068958e
--- /dev/null
+++ b/packages/ui/src/views/components/feature-search/FeatureSearch.tsx
@@ -0,0 +1,286 @@
+/**
+ * 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 { IMenuCommandParams, IMenuItem, IValueOption, MenuItemDefaultValueType } from '../../../services/menu/menu';
+import type { IMenuSchema } from '../../../services/menu/menu-manager.service';
+import { ICommandService, LocaleService, Tools } from '@univerjs/core';
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from '@univerjs/design';
+import { useMemo } from 'react';
+import { combineLatest, isObservable, merge, of } from 'rxjs';
+import { map, startWith, switchMap } from 'rxjs/operators';
+import { IDialogService } from '../../../services/dialog/dialog.service';
+import { ILayoutService } from '../../../services/layout/layout.service';
+import { MenuItemType } from '../../../services/menu/menu';
+import { IMenuManagerService } from '../../../services/menu/menu-manager.service';
+import { MenuManagerPosition } from '../../../services/menu/types';
+import { IRibbonService } from '../../../services/ribbon/ribbon.service';
+import { useDependency, useObservable } from '../../../utils/di';
+
+export const FEATURE_SEARCH_COMPONENT = 'FeatureSearch';
+export const FEATURE_SEARCH_DIALOG_ID = 'FEATURE_SEARCH_DIALOG';
+
+export interface IFeatureSearchItem {
+ key: string;
+ title: string;
+ parentTitle?: string;
+ description: string;
+ path: string;
+ commandId: string;
+ params?: IMenuCommandParams;
+ getParams: () => IMenuCommandParams | undefined;
+}
+
+interface IMenuCandidate {
+ key: string;
+ item: IMenuItem;
+ path: string[];
+ ancestors: IMenuItem[];
+ parentTitle?: string;
+}
+
+function resolveParams(item: IMenuItem, value: MenuItemDefaultValueType) {
+ const params = typeof item.params === 'function' ? item.params() : item.params;
+ return params ?? (value === undefined ? undefined : { value });
+}
+
+function resolveOptionParams(option: IValueOption) {
+ const params = typeof option.params === 'function' ? option.params(option.value) : option.params;
+ return params ?? (option.value === undefined ? undefined : { value: option.value });
+}
+
+function deduplicate(items: IFeatureSearchItem[]) {
+ // ponytail: Menu inventories are small; replace this scan only if profiling shows it is a hot path.
+ return items.filter((item, index) => items.findIndex((candidate) => (
+ candidate.commandId === item.commandId && Tools.diffValue(candidate.params, item.params)
+ )) === index);
+}
+
+export function FeatureSearch() {
+ const menuManagerService = useDependency(IMenuManagerService);
+ const localeService = useDependency(LocaleService);
+ const commandService = useDependency(ICommandService);
+ const dialogService = useDependency(IDialogService);
+ const layoutService = useDependency(ILayoutService);
+ const ribbonService = useDependency(IRibbonService);
+ const items$ = useMemo(() => {
+ function getItemTitle(item: IMenuItem) {
+ const titleKey = item.title ?? item.tooltip ?? item.description;
+ return titleKey ? localeService.t(titleKey) : '';
+ }
+
+ function collectCandidates(
+ schemas: IMenuSchema[],
+ path: string[],
+ keyPath: string[],
+ ancestors: IMenuItem[] = [],
+ parentTitle?: string
+ ): IMenuCandidate[] {
+ return schemas.flatMap((schema, index) => {
+ const schemaTitle = localeService.t(schema.title ?? '');
+ const schemaPath = schemaTitle ? [...path, schemaTitle] : path;
+ const schemaKeyPath = [...keyPath, `${schema.key}:${index}`];
+ const result: IMenuCandidate[] = [];
+
+ if (schema.item) {
+ result.push({
+ key: `${schemaKeyPath.join('/')}:item`,
+ item: schema.item,
+ path: schemaPath,
+ ancestors,
+ parentTitle,
+ });
+ }
+
+ if (schema.headerActionItem) {
+ result.push({
+ key: `${schemaKeyPath.join('/')}:header`,
+ item: schema.headerActionItem,
+ path: schemaPath,
+ ancestors,
+ parentTitle,
+ });
+ }
+
+ if (schema.children) {
+ result.push(...collectCandidates(
+ schema.children,
+ schemaPath,
+ schemaKeyPath,
+ schema.item ? [...ancestors, schema.item] : ancestors,
+ schema.item ? getItemTitle(schema.item) : parentTitle
+ ));
+ }
+
+ return result;
+ });
+ }
+
+ function observeCandidate(candidate: IMenuCandidate) {
+ const { item } = candidate;
+ const hasOptions = item.type === MenuItemType.SELECTOR || item.type === MenuItemType.BUTTON_SELECTOR;
+ const selections = hasOptions ? item.selections : undefined;
+ const selections$ = isObservable(selections)
+ ? selections.pipe(startWith([]))
+ : of(selections ?? []);
+ const ancestorHidden$ = candidate.ancestors.length
+ ? combineLatest(candidate.ancestors.map((ancestor) => ancestor.hidden$?.pipe(startWith(true)) ?? of(false))).pipe(
+ map((states) => states.some(Boolean))
+ )
+ : of(false);
+ const ancestorDisabled$ = candidate.ancestors.length
+ ? combineLatest(candidate.ancestors.map((ancestor) => ancestor.disabled$?.pipe(startWith(true)) ?? of(false))).pipe(
+ map((states) => states.some(Boolean))
+ )
+ : of(false);
+
+ return combineLatest([
+ ancestorHidden$,
+ ancestorDisabled$,
+ item.hidden$?.pipe(startWith(true)) ?? of(false),
+ item.disabled$?.pipe(startWith(true)) ?? of(false),
+ item.value$?.pipe(startWith(undefined)) ?? of(undefined),
+ selections$,
+ ]).pipe(map(([ancestorHidden, ancestorDisabled, hidden, disabled, value, options]): IFeatureSearchItem[] => {
+ if (ancestorHidden || ancestorDisabled || hidden || disabled) {
+ return [];
+ }
+
+ const title = getItemTitle(item);
+ const path = candidate.path.join(' / ');
+ const result: IFeatureSearchItem[] = [];
+
+ if (title && item.type !== MenuItemType.SELECTOR && item.type !== MenuItemType.SUBITEMS) {
+ result.push({
+ key: candidate.key,
+ title,
+ parentTitle: candidate.parentTitle,
+ description: localeService.t(item.description ?? ''),
+ path,
+ commandId: item.commandId ?? item.id,
+ params: resolveParams(item, value),
+ getParams: () => resolveParams(item, value),
+ });
+ }
+
+ if (hasOptions) {
+ options.forEach((option, index) => {
+ if (option.disabled || typeof option.label !== 'string') {
+ return;
+ }
+
+ const commandId = option.commandId ?? option.id ?? item.selectionsCommandId ?? item.commandId ?? item.id;
+ result.push({
+ key: `${candidate.key}:option:${option.id ?? option.commandId ?? option.value ?? index}`,
+ title: localeService.t(option.label),
+ parentTitle: title,
+ description: '',
+ path,
+ commandId,
+ params: resolveOptionParams(option),
+ getParams: () => resolveOptionParams(option),
+ });
+ });
+ }
+
+ return result;
+ }));
+ }
+
+ return combineLatest([
+ ribbonService.ribbon$,
+ merge(
+ of(undefined),
+ menuManagerService.menuChanged$,
+ localeService.localeChanged$
+ ),
+ ]).pipe(switchMap(([ribbon]) => {
+ const candidates = [
+ ...collectCandidates(
+ ribbon,
+ [localeService.t('ui.featureSearch.ribbon')],
+ [MenuManagerPosition.RIBBON]
+ ),
+ ...collectCandidates(
+ menuManagerService.getMenuByPositionKey(MenuManagerPosition.CONTEXT_MENU),
+ [localeService.t('ui.featureSearch.contextMenu')],
+ [MenuManagerPosition.CONTEXT_MENU]
+ ),
+ ];
+
+ if (candidates.length === 0) {
+ return of([]);
+ }
+
+ return combineLatest(candidates.map(observeCandidate)).pipe(
+ map((items) => deduplicate(items.flat()))
+ );
+ }));
+ }, [localeService, menuManagerService, ribbonService]);
+ const items = useObservable(items$, []);
+
+ async function execute(item: IFeatureSearchItem) {
+ layoutService.focus();
+ const success = await commandService.executeCommand(
+ item.commandId,
+ item.getParams()
+ );
+
+ if (success) {
+ dialogService.close(FEATURE_SEARCH_DIALOG_ID);
+ }
+ }
+
+ return (
+ <Command label={localeService.t('ui.featureSearch.title')} loop>
+ <CommandInput autoFocus placeholder={localeService.t('ui.featureSearch.placeholder')} />
+ <CommandList>
+ <CommandEmpty>{localeService.t('ui.featureSearch.empty')}</CommandEmpty>
+ <CommandGroup>
+ {items.map((item) => (
+ <CommandItem
+ key={item.key}
+ value={item.key}
+ keywords={[item.parentTitle ?? '', item.title, item.description, item.path]}
+ onSelect={() => execute(item)}
+ >
+ <span className="univer-flex univer-min-w-0 univer-flex-1 univer-items-center univer-gap-1">
+ {item.parentTitle && (
+ <>
+ <span className="univer-shrink-0">{item.parentTitle}</span>
+ <span className="univer-text-gray-400">/</span>
+ </>
+ )}
+ <span className="univer-truncate">{item.title}</span>
+ </span>
+ {item.path && (
+ <span className="univer-max-w-1/2 univer-truncate univer-text-xs univer-text-gray-400">
+ {item.path}
+ </span>
+ )}
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ );
+}
diff --git a/packages/ui/src/views/components/feature-search/__tests__/FeatureSearch.spec.tsx b/packages/ui/src/views/components/feature-search/__tests__/FeatureSearch.spec.tsx
new file mode 100644
index 0000000000..9ddfc689f6
--- /dev/null
+++ b/packages/ui/src/views/components/feature-search/__tests__/FeatureSearch.spec.tsx
@@ -0,0 +1,363 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ReactElement } from 'react';
+import type { IValueOption } from '../../../../services/menu/menu';
+import type { IMenuSchema } from '../../../../services/menu/menu-manager.service';
+import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import { ICommandService, Injector, LocaleService } from '@univerjs/core';
+import { BehaviorSubject, Subject } from 'rxjs';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { ComponentManager } from '../../../../common/component-manager';
+import { IconManager } from '../../../../common/icon-manager';
+import { IDialogService } from '../../../../services/dialog/dialog.service';
+import { ILayoutService } from '../../../../services/layout/layout.service';
+import { MenuItemType } from '../../../../services/menu/menu';
+import { IMenuManagerService } from '../../../../services/menu/menu-manager.service';
+import { MenuManagerPosition } from '../../../../services/menu/types';
+import { IRibbonService } from '../../../../services/ribbon/ribbon.service';
+import { RediProvider } from '../../../../utils/di';
+import { FEATURE_SEARCH_DIALOG_ID, FeatureSearch } from '../FeatureSearch';
+
+const hidden$ = new BehaviorSubject(true);
+const disabled$ = new BehaviorSubject(true);
+const pendingHidden$ = new Subject<boolean>();
+const submenuHidden$ = new BehaviorSubject(false);
+const submenuDisabled$ = new BehaviorSubject(true);
+const selectorOptions: IValueOption[] = [
+ {
+ commandId: 'format.rows.command',
+ value: 'row',
+ label: 'Format rows',
+ params: (value) => ({ value, source: 'selector' }),
+ },
+ {
+ commandId: 'format.disabled.command',
+ value: 'disabled',
+ label: 'Disabled format',
+ disabled: true,
+ },
+];
+const selectorOptions$ = new BehaviorSubject<IValueOption[]>([]);
+
+const ribbon: IMenuSchema[] = [{
+ key: 'ribbon.start',
+ order: 0,
+ title: 'ui.ribbon.start',
+ children: [
+ {
+ key: 'run',
+ order: 0,
+ item: {
+ id: 'run.command',
+ type: MenuItemType.BUTTON,
+ title: 'test.run',
+ params: { source: 'menu' },
+ },
+ },
+ {
+ key: 'format',
+ order: 1,
+ item: {
+ id: 'format.command',
+ type: MenuItemType.SELECTOR,
+ title: 'test.format',
+ selections: selectorOptions$,
+ disabled$,
+ },
+ },
+ {
+ key: 'hidden',
+ order: 3,
+ item: {
+ id: 'hidden.command',
+ type: MenuItemType.BUTTON,
+ title: 'test.hidden',
+ hidden$,
+ },
+ },
+ {
+ key: 'disabled',
+ order: 4,
+ item: {
+ id: 'disabled.command',
+ type: MenuItemType.BUTTON,
+ title: 'test.disabled',
+ disabled$,
+ },
+ },
+ {
+ key: 'pending',
+ order: 5,
+ item: {
+ id: 'pending.command',
+ type: MenuItemType.BUTTON,
+ title: 'test.pending',
+ hidden$: pendingHidden$,
+ },
+ },
+ {
+ key: 'print',
+ order: 2,
+ item: {
+ id: 'print.menu',
+ type: MenuItemType.SUBITEMS,
+ title: 'test.print',
+ hidden$: submenuHidden$,
+ disabled$: submenuDisabled$,
+ },
+ children: [
+ {
+ key: 'print.action',
+ order: 0,
+ item: {
+ id: 'print.action',
+ type: MenuItemType.BUTTON,
+ title: 'test.print',
+ },
+ },
+ {
+ key: 'print.layout',
+ order: 1,
+ item: {
+ id: 'print.layout',
+ type: MenuItemType.BUTTON,
+ title: 'test.printLayout',
+ },
+ },
+ ],
+ },
+ ],
+}];
+
+const contextMenu: IMenuSchema[] = [{
+ key: 'contextMenu.mainArea',
+ order: 0,
+ children: [
+ {
+ key: 'run-context',
+ order: 0,
+ item: {
+ id: 'run.command',
+ type: MenuItemType.BUTTON,
+ title: 'test.run',
+ params: () => ({ source: 'menu' }),
+ },
+ },
+ {
+ key: 'run-context-variant',
+ order: 1,
+ item: {
+ id: 'run.command',
+ type: MenuItemType.BUTTON,
+ title: 'test.run',
+ params: { source: 'context' },
+ },
+ },
+ ],
+}];
+
+const contextualRibbon: IMenuSchema = {
+ key: 'ribbon.target',
+ order: 10,
+ title: 'test.targetTab',
+ contextual: true,
+ children: [{
+ key: 'ribbon.target.group',
+ order: 0,
+ children: [{
+ key: 'target.action',
+ order: 0,
+ item: {
+ id: 'target.action',
+ type: MenuItemType.BUTTON,
+ title: 'test.targetAction',
+ },
+ }],
+ }],
+};
+const visibleRibbon$ = new BehaviorSubject<IMenuSchema[]>(ribbon);
+
+class TestLocaleService {
+ readonly localeChanged$ = new Subject<void>();
+
+ t(key: string) {
+ return ({
+ 'ui.featureSearch.ribbon': 'Ribbon',
+ 'ui.featureSearch.contextMenu': 'Context menu',
+ 'ui.featureSearch.placeholder': 'Search features',
+ 'ui.featureSearch.empty': 'No features',
+ 'ui.ribbon.start': 'Start',
+ 'test.run': 'Run',
+ 'test.format': 'Format',
+ 'test.print': 'Print',
+ 'test.printLayout': 'Print layout',
+ 'test.hidden': 'Hidden',
+ 'test.disabled': 'Disabled',
+ 'test.pending': 'Pending',
+ 'test.targetTab': 'Target',
+ 'test.targetAction': 'Target action',
+ } as Record<string, string>)[key] ?? key;
+ }
+}
+
+class TestMenuManagerService {
+ readonly menuChanged$ = new Subject<void>();
+
+ getMenuByPositionKey(position: string) {
+ return position === MenuManagerPosition.RIBBON ? [...ribbon, contextualRibbon] : contextMenu;
+ }
+}
+
+function renderWithDependencies(element: ReactElement) {
+ const commandService = { executeCommand: vi.fn().mockResolvedValue(true) };
+ const dialogService = { close: vi.fn() };
+ const layoutService = { focus: vi.fn() };
+ const injector = new Injector();
+
+ injector.add([LocaleService, { useClass: TestLocaleService as never }]);
+ injector.add([IMenuManagerService, { useClass: TestMenuManagerService as never }]);
+ injector.add([IRibbonService, { useValue: { ribbon$: visibleRibbon$ } as never }]);
+ injector.add([ICommandService, { useValue: commandService as never }]);
+ injector.add([IDialogService, { useValue: dialogService as never }]);
+ injector.add([ILayoutService, { useValue: layoutService as never }]);
+ injector.add([ComponentManager]);
+ injector.add([IconManager]);
+
+ return {
+ ...render(<RediProvider value={{ injector }}>{element}</RediProvider>),
+ commandService,
+ dialogService,
+ layoutService,
+ };
+}
+
+afterEach(() => {
+ hidden$.next(true);
+ disabled$.next(true);
+ submenuHidden$.next(false);
+ submenuDisabled$.next(true);
+ selectorOptions$.next([]);
+ visibleRibbon$.next(ribbon);
+ cleanup();
+});
+
+describe('FeatureSearch', () => {
+ it('searches only currently visible ribbon tabs', async () => {
+ renderWithDependencies(<FeatureSearch />);
+
+ await screen.findAllByText('Run');
+ expect(screen.queryByText('Target action')).toBeNull();
+
+ act(() => visibleRibbon$.next([...ribbon, contextualRibbon]));
+ expect(await screen.findByText('Target action')).toBeTruthy();
+
+ act(() => visibleRibbon$.next(ribbon));
+ await waitFor(() => expect(screen.queryByText('Target action')).toBeNull());
+ });
+
+ it('hides hidden and disabled items', async () => {
+ renderWithDependencies(<FeatureSearch />);
+
+ const runLabels = await screen.findAllByText('Run');
+ expect(runLabels).toHaveLength(2);
+ expect(runLabels.filter((label) => (
+ label.closest('[cmdk-item]')?.getAttribute('data-selected') === 'true'
+ ))).toHaveLength(1);
+ expect(screen.queryByText('Hidden')).toBeNull();
+
+ expect(screen.queryByText('Disabled')).toBeNull();
+
+ act(() => hidden$.next(false));
+ expect(await screen.findByText('Hidden')).toBeTruthy();
+ });
+
+ it('does not expose stateful items before their availability is known', async () => {
+ renderWithDependencies(<FeatureSearch />);
+
+ await screen.findAllByText('Run');
+ expect(screen.queryByText('Pending')).toBeNull();
+
+ act(() => pendingHidden$.next(false));
+ expect(await screen.findByText('Pending')).toBeTruthy();
+ });
+
+ it('executes a button by click and closes the dialog', async () => {
+ const { commandService, dialogService, layoutService } = renderWithDependencies(<FeatureSearch />);
+
+ fireEvent.click((await screen.findAllByText('Run'))[0]);
+
+ await waitFor(() => {
+ expect(layoutService.focus).toHaveBeenCalledTimes(1);
+ expect(commandService.executeCommand).toHaveBeenCalledWith('run.command', { source: 'menu' });
+ expect(dialogService.close).toHaveBeenCalledWith(FEATURE_SEARCH_DIALOG_ID);
+ });
+ });
+
+ it('executes the selected button with Enter', async () => {
+ const { commandService } = renderWithDependencies(<FeatureSearch />);
+ const input = await screen.findByRole('combobox');
+
+ input.focus();
+ fireEvent.keyDown(input, { key: 'Enter' });
+
+ await waitFor(() => {
+ expect(commandService.executeCommand).toHaveBeenCalledWith('run.command', { source: 'menu' });
+ });
+ });
+
+ it('shows live selector options as executable results', async () => {
+ const { commandService, dialogService, layoutService } = renderWithDependencies(<FeatureSearch />);
+
+ act(() => selectorOptions$.next(selectorOptions));
+ expect(screen.queryByText('Format rows')).toBeNull();
+ expect(screen.queryByText('Disabled format')).toBeNull();
+
+ act(() => disabled$.next(false));
+ const optionLabel = await screen.findByText('Format rows');
+ const optionItem = optionLabel.closest('[cmdk-item]') as HTMLElement;
+ expect(within(optionItem).getByText('Format')).toBeTruthy();
+ expect(screen.queryByText('Disabled format')).toBeNull();
+ fireEvent.click(optionLabel);
+
+ await waitFor(() => {
+ expect(layoutService.focus).toHaveBeenCalledTimes(1);
+ expect(commandService.executeCommand).toHaveBeenCalledWith('format.rows.command', {
+ value: 'row',
+ source: 'selector',
+ });
+ expect(dialogService.close).toHaveBeenCalledWith(FEATURE_SEARCH_DIALOG_ID);
+ });
+ });
+
+ it('inherits hidden and disabled state from submenu ancestors', async () => {
+ const { commandService } = renderWithDependencies(<FeatureSearch />);
+
+ expect(screen.queryByText('Print layout')).toBeNull();
+
+ act(() => submenuDisabled$.next(false));
+ const layoutLabel = await screen.findByText('Print layout');
+ const layoutItem = layoutLabel.closest('[cmdk-item]') as HTMLElement;
+ expect(within(layoutItem).getByText('Print')).toBeTruthy();
+ const printItem = screen.getAllByRole('option').find((item) => item.getAttribute('data-value')?.includes('/print.action:0:item')) as HTMLElement;
+ expect(within(printItem).getAllByText('Print')).toHaveLength(2);
+ fireEvent.click(layoutLabel);
+ expect(commandService.executeCommand).toHaveBeenCalledWith('print.layout', undefined);
+
+ act(() => submenuHidden$.next(true));
+ await waitFor(() => expect(screen.queryByText('Print layout')).toBeNull());
+ });
+});
diff --git a/packages/ui/src/views/components/ribbon/Ribbon.tsx b/packages/ui/src/views/components/ribbon/Ribbon.tsx
index 6b6509344e..9cc0db282a 100644
--- a/packages/ui/src/views/components/ribbon/Ribbon.tsx
+++ b/packages/ui/src/views/components/ribbon/Ribbon.tsx
@@ -28,6 +28,8 @@ import { connectInjector, useDependency, useObservable } from '../../../utils/di
import { ComponentContainer } from '../ComponentContainer';
import { ClassicMenu } from './ribbon-menu/ClassicMenu';
import { DefaultMenu } from './ribbon-menu/DefaultMenu';
+import { RibbonGridMenu } from './ribbon-menu/RibbonGridMenu';
+import { RibbonGrid } from './RibbonGrid';
import { toolbarButtonClassName } from './ToolbarButton';
import { ToolbarItem } from './ToolbarItem';
import { ToolbarDropdownProvider } from './TooltipButtonWrapper';
@@ -120,7 +122,7 @@ export function Ribbon(props: IRibbonProps) {
}, [collapsedIds, ribbon, activatedTab]);
useEffect(() => {
- if (hideToolbar) {
+ if (hideToolbar || ribbonType === 'grid') {
toolbarItemRefs.current = {};
ribbonService.setCollapsedIds([]);
ribbonService.setFakeToolbarVisible(false);
@@ -172,7 +174,7 @@ export function Ribbon(props: IRibbonProps) {
timer && cancelAnimationFrame(timer);
observer.disconnect();
};
- }, [hideToolbar, ribbon, activatedTab, ribbonService]);
+ }, [hideToolbar, ribbon, activatedTab, ribbonService, ribbonType]);
const fakeToolbar = useMemo(() => {
return (
@@ -233,7 +235,7 @@ export function Ribbon(props: IRibbonProps) {
{...embedRibbonOverrideAttributes}
className={clsx('univer-relative univer-select-none', headerClassName, {
'univer-hidden': toolbarOnly,
- 'univer-h-9': !toolbarOnly && (ribbonType === 'classic' || (headerMenuComponents && headerMenuComponents.size > 0)),
+ 'univer-h-9': !toolbarOnly && (ribbonType === 'classic' || ribbonType === 'grid' || (headerMenuComponents && headerMenuComponents.size > 0)),
})}
>
{!toolbarOnly && ribbonOverride?.placeholderTitle && ribbon.length === 0 && (
@@ -262,6 +264,14 @@ export function Ribbon(props: IRibbonProps) {
/>
)}
+ {!toolbarOnly && ribbonType === 'grid' && ribbon.length >= 1 && (
+ <RibbonGridMenu
+ ribbon={ribbon}
+ activatedTab={activatedTab}
+ onSelectTab={handleSelectTab}
+ />
+ )}
+
{headerMenu && (headerMenuComponents && headerMenuComponents.size > 0) && (
<div
className={`
@@ -278,7 +288,15 @@ export function Ribbon(props: IRibbonProps) {
)}
</div>
- {!hideToolbar && (
+ {!hideToolbar && ribbonType === 'grid' && (
+ <RibbonGrid
+ {...embedRibbonOverrideAttributes}
+ groups={activeGroup.allGroups}
+ title={activatedTabTitle}
+ />
+ )}
+
+ {!hideToolbar && ribbonType !== 'grid' && (
<div
{...embedRibbonOverrideAttributes}
className={clsx(`
@@ -374,7 +392,7 @@ export function Ribbon(props: IRibbonProps) {
)}
{/* fake toolbar */}
- {fakeToolbar}
+ {ribbonType !== 'grid' && fakeToolbar}
</>
);
diff --git a/packages/ui/src/views/components/ribbon/RibbonGrid.tsx b/packages/ui/src/views/components/ribbon/RibbonGrid.tsx
new file mode 100644
index 0000000000..c4c9c5e413
--- /dev/null
+++ b/packages/ui/src/views/components/ribbon/RibbonGrid.tsx
@@ -0,0 +1,111 @@
+/**
+ * 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 { HTMLAttributes } from 'react';
+import type { IMenuSchema } from '../../../services/menu/menu-manager.service';
+import { LocaleService } from '@univerjs/core';
+import { borderBottomClassName, borderRightClassName, clsx } from '@univerjs/design';
+import { useDependency } from '../../../utils/di';
+import { placeRibbonGridItems } from './ribbon-grid-layout';
+import { ToolbarItem } from './ToolbarItem';
+import { ToolbarDropdownProvider } from './TooltipButtonWrapper';
+
+interface IRibbonGridProps extends Omit<HTMLAttributes<HTMLDivElement>, 'title'> {
+ groups: IMenuSchema[];
+ title: string;
+}
+
+export function RibbonGrid({ groups, title, className, ...props }: IRibbonGridProps) {
+ const localeService = useDependency(LocaleService);
+
+ return (
+ <div
+ {...props}
+ data-testid="ribbon-grid-toolbar"
+ data-u-comp="ribbon-grid-toolbar"
+ className={clsx(`
+ univer-box-border univer-flex univer-h-[88px] univer-overflow-x-auto univer-overflow-y-hidden
+ univer-bg-gray-50 univer-px-2 univer-text-sm
+ dark:!univer-bg-gray-900
+ `, borderBottomClassName, className)}
+ role="toolbar"
+ aria-label={localeService.t(title)}
+ >
+ <ToolbarDropdownProvider>
+ {groups.map((group) => {
+ const placements = placeRibbonGridItems(group.children ?? []);
+ return (
+ <div
+ key={group.key}
+ data-u-comp="ribbon-grid-group"
+ className="
+ univer-relative univer-box-border univer-flex univer-min-w-16 univer-shrink-0
+ univer-flex-col univer-px-2
+ "
+ >
+ <div
+ data-testid="ribbon-grid-group-grid"
+ className="
+ univer-grid univer-min-h-0 univer-flex-1 univer-grid-flow-col univer-grid-rows-2
+ univer-content-center univer-gap-x-1 univer-gap-y-3 univer-py-3.5
+ [&>div>span>span]:univer-h-full
+ "
+ >
+ {placements.map((placement) => placement.item.item && (
+ <div
+ key={placement.item.key}
+ className={clsx(`
+ univer-flex univer-items-stretch
+ [&>span>button]:univer-h-full
+ [&>span]:univer-h-full
+ `, placement.width && `
+ [&>span>span]:univer-w-full
+ [&>span]:univer-w-full
+ [&_[data-u-command]]:univer-w-full
+ `)}
+ style={{
+ gridRow: `${placement.row} / span ${placement.rowSpan}`,
+ gridColumn: `${placement.column} / span ${placement.columnSpan}`,
+ width: placement.width,
+ }}
+ >
+ <ToolbarItem
+ {...placement.item.item}
+ grid
+ large={placement.rowSpan > 1}
+ showLabel={placement.showLabel}
+ iconSize={placement.iconSize}
+ fullWidth={placement.width !== undefined}
+ />
+ </div>
+ ))}
+ </div>
+ <span
+ data-testid="ribbon-grid-group-divider"
+ className={clsx(`
+ univer-pointer-events-none univer-absolute univer-bottom-1.5 univer-right-0
+ univer-top-3.5 !univer-border-gray-300 univer-opacity-50
+ rtl:univer-left-0 rtl:univer-right-auto
+ `, borderRightClassName)}
+ aria-hidden="true"
+ />
+ </div>
+ );
+ })}
+ </ToolbarDropdownProvider>
+ </div>
+ );
+}
diff --git a/packages/ui/src/views/components/ribbon/ToolbarItem.tsx b/packages/ui/src/views/components/ribbon/ToolbarItem.tsx
index c8a4e7455f..6ecc15ec2b 100644
--- a/packages/ui/src/views/components/ribbon/ToolbarItem.tsx
+++ b/packages/ui/src/views/components/ribbon/ToolbarItem.tsx
@@ -17,7 +17,7 @@
import type { IDisplayMenuItem, IMenuItem, IMenuSelectorItem, IValueOption } from '../../../services/menu/menu';
import type { ITooltipWrapperRef } from './TooltipButtonWrapper';
import { ICommandService, LocaleService } from '@univerjs/core';
-import { cva } from '@univerjs/design';
+import { borderClassName, clsx, cva } from '@univerjs/design';
import { MoreDownIcon } from '@univerjs/icons';
import { forwardRef, useMemo } from 'react';
import { isObservable, Observable } from 'rxjs';
@@ -27,9 +27,17 @@ import { MenuItemType } from '../../../services/menu/menu';
import { useDependency, useObservable } from '../../../utils/di';
import { CustomLabel } from '../../custom-label/CustomLabel';
import { useToolbarItemStatus, useToolbarShortcutDisplay } from './hook';
-import { ToolbarButton } from './ToolbarButton';
+import { ToolbarButton, toolbarButtonVariants } from './ToolbarButton';
import { DropdownMenuWrapper, TooltipWrapper } from './TooltipButtonWrapper';
+type IToolbarItemProps = IDisplayMenuItem<IMenuItem> & {
+ grid?: boolean;
+ large?: boolean;
+ showLabel?: boolean;
+ iconSize?: number;
+ fullWidth?: boolean;
+};
+
const toolbarDisabledClassName = 'univer-pointer-events-none univer-cursor-not-allowed univer-text-gray-300 dark:!univer-text-gray-600';
const toolbarButtonSelectorRootVariants = cva(
@@ -179,7 +187,7 @@ const toolbarSelectorTriggerVariants = cva(`
},
});
-export const ToolbarItem = forwardRef<ITooltipWrapperRef, IDisplayMenuItem<IMenuItem>>((props, ref) => {
+export const ToolbarItem = forwardRef<ITooltipWrapperRef, IToolbarItemProps>((props, ref) => {
const localeService = useDependency(LocaleService);
const commandService = useDependency(ICommandService);
const layoutService = useDependency(ILayoutService);
@@ -192,7 +200,8 @@ export const ToolbarItem = forwardRef<ITooltipWrapperRef, IDisplayMenuItem<IMenu
commandService.executeCommand(commandId, params);
};
- const { tooltip, shortcut, icon, title, label, id, commandId, type, slot, params } = props;
+ const { tooltip, shortcut, icon, title, label, id, commandId, type, slot, params, grid, large, showLabel, iconSize, fullWidth } = props;
+ const gridLabel = title ?? tooltip;
const shortcutDisplay = useToolbarShortcutDisplay({ id, commandId, shortcut });
let tooltipTitle = tooltip ? localeService.t(tooltip) : '';
@@ -230,6 +239,7 @@ export const ToolbarItem = forwardRef<ITooltipWrapperRef, IDisplayMenuItem<IMenu
const selectionsCommandId = (props as IDisplayMenuItem<IMenuSelectorItem>).selectionsCommandId;
const bId = commandId ?? id;
const sId = selectionsCommandId ?? commandId ?? id;
+ const titleToDisplay = grid ? (showLabel ? gridLabel : large ? undefined : title) : title;
function handleSelect(option: IValueOption) {
if (disabled) return;
@@ -262,15 +272,22 @@ export const ToolbarItem = forwardRef<ITooltipWrapperRef, IDisplayMenuItem<IMenu
<div
data-u-command={id}
data-disabled={disabled}
- className={toolbarButtonSelectorRootVariants({ disabled })}
+ className={clsx(toolbarButtonSelectorRootVariants({ disabled }), {
+ 'univer-box-border univer-h-full univer-min-w-14 univer-flex-col !univer-pr-0': grid && large,
+ 'univer-box-border univer-h-full': grid && !large,
+ })}
>
<div
- className={toolbarButtonSelectorMainVariants({ active: activated, disabled })}
+ className={clsx(toolbarButtonSelectorMainVariants({ active: activated, disabled }), {
+ 'univer-h-full univer-w-full univer-flex-col univer-justify-center univer-rounded univer-px-1 univer-pb-4 [&>svg]:univer-size-8': grid && large,
+ '[&>svg]:univer-size-5': grid && !large,
+ })}
onClick={handleClick}
>
<CustomLabel
icon={iconToDisplay}
- title={title!}
+ iconSize={iconSize}
+ title={titleToDisplay}
value={value}
label={label}
onChange={handleSelectionsValueChange}
@@ -286,7 +303,10 @@ export const ToolbarItem = forwardRef<ITooltipWrapperRef, IDisplayMenuItem<IMenu
onOptionSelect={handleSelect}
>
<div
- className={toolbarButtonSelectorTriggerVariants({ disabled, active: activated })}
+ className={clsx(toolbarButtonSelectorTriggerVariants({ disabled, active: activated }), {
+ '!univer-top-auto univer-bottom-0 univer-h-4 univer-w-full univer-rounded-b univer-rounded-t-none': grid && large,
+ 'univer-h-full': grid && !large,
+ })}
data-disabled={disabled}
>
<MoreDownIcon />
@@ -306,20 +326,52 @@ export const ToolbarItem = forwardRef<ITooltipWrapperRef, IDisplayMenuItem<IMenu
>
<div
data-u-command={id}
- className={toolbarSelectorRootVariants({ disabled, active: activated })}
+ 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,
+ 'univer-bg-white dark:!univer-bg-gray-800': grid && !large && !icon,
+ '[&>svg]:univer-size-5': grid && !large,
+ }, grid && !large && !icon && borderClassName)}
>
- <CustomLabel
- icon={iconToDisplay}
- title={title!}
- value={value}
- label={label}
- onChange={handleSelectionsValueChange}
- />
- <div
- className={toolbarSelectorTriggerVariants({ disabled })}
- >
- <MoreDownIcon />
- </div>
+ {grid && large
+ ? (
+ <>
+ <CustomLabel icon={iconToDisplay} iconSize={iconSize} />
+ <div
+ className={clsx(
+ toolbarSelectorTriggerVariants({ disabled }),
+ 'univer-h-4 univer-justify-center univer-gap-0.5'
+ )}
+ >
+ <CustomLabel
+ title={titleToDisplay}
+ value={value}
+ label={label}
+ onChange={handleSelectionsValueChange}
+ />
+ <MoreDownIcon />
+ </div>
+ </>
+ )
+ : (
+ <>
+ <CustomLabel
+ icon={iconToDisplay}
+ iconSize={iconSize}
+ title={titleToDisplay}
+ value={value}
+ label={label}
+ onChange={handleSelectionsValueChange}
+ />
+ <div
+ className={clsx(toolbarSelectorTriggerVariants({ disabled }), {
+ 'univer-ml-auto rtl:univer-ml-0 rtl:univer-mr-auto': grid && !large && !icon,
+ })}
+ >
+ <MoreDownIcon />
+ </div>
+ </>
+ )}
</div>
</DropdownMenuWrapper>
);
@@ -328,11 +380,42 @@ export const ToolbarItem = forwardRef<ITooltipWrapperRef, IDisplayMenuItem<IMenu
function renderButtonType() {
const isCustomComponent = componentManager.get(typeof label === 'string' ? label : label?.name ?? '');
+ const buttonClassName = clsx(grid && !large && `
+ univer-h-full univer-min-w-8
+ [&>svg]:univer-size-5
+ `, grid && large
+ ? `
+ univer-h-full univer-min-w-14 univer-flex-col univer-gap-1 univer-px-1.5 univer-py-1 univer-text-xs
+ [&>svg]:univer-size-8
+ `
+ : showLabel
+ ? 'univer-gap-1 univer-px-1.5 univer-text-sm'
+ : 'univer-text-sm', grid && fullWidth && isCustomComponent && '!univer-px-0');
+ const buttonStyle = grid && large ? { textAlign: 'center', whiteSpace: 'normal' } as const : undefined;
+
+ if (isCustomComponent) {
+ return (
+ <span
+ data-u-command={id}
+ className={toolbarButtonVariants({ noIcon: !icon, active: activated, className: buttonClassName })}
+ style={buttonStyle}
+ aria-disabled={disabled}
+ >
+ <CustomLabel
+ className={grid && fullWidth ? '!univer-w-full' : undefined}
+ title={grid && showLabel ? gridLabel! : title!}
+ value={value}
+ label={label}
+ />
+ </span>
+ );
+ }
return (
<ToolbarButton
data-u-command={id}
- className="univer-text-sm"
+ className={buttonClassName}
+ style={buttonStyle}
noIcon={!icon}
active={activated}
disabled={disabled}
@@ -342,13 +425,9 @@ export const ToolbarItem = forwardRef<ITooltipWrapperRef, IDisplayMenuItem<IMenu
}}
onDoubleClick={() => props.subId && executeCommand(props.subId)}
>
- {isCustomComponent
- ? (
- <CustomLabel title={title!} value={value} label={label} />
- )
- : (
- icon ? <CustomLabel icon={icon} /> : <CustomLabel title={title!} />
- )}
+ {icon
+ ? <CustomLabel icon={icon} iconSize={iconSize} title={grid && (large || showLabel) ? gridLabel : undefined} />
+ : <CustomLabel title={title!} />}
</ToolbarButton>
);
}
diff --git a/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx b/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx
index 89232769a1..bdeab1590b 100644
--- a/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx
+++ b/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx
@@ -24,6 +24,7 @@ import {
forwardRef,
useCallback,
useContext,
+ useEffect,
useImperativeHandle,
useMemo,
useRef,
@@ -126,6 +127,29 @@ export const TooltipWrapper = forwardRef<ITooltipWrapperRef, ITooltipProps & { d
export function DropdownWrapper(props: Omit<Partial<IDropdownProps>, 'overlay'> & { overlay: ReactNode; align?: 'start' | 'end' | 'center' }) {
const { children, overlay, disabled, align = 'start' } = props;
const { dropdownVisible, setDropdownVisible } = useContext(TooltipWrapperContext);
+ const triggerRef = useRef<HTMLDivElement>(null);
+ const overlayRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (disabled) {
+ setDropdownVisible(false);
+ }
+ }, [disabled, setDropdownVisible]);
+
+ useEffect(() => {
+ const ownerDocument = triggerRef.current?.ownerDocument;
+ if (!dropdownVisible || !ownerDocument) return;
+
+ const handlePointerDown = (event: PointerEvent) => {
+ const target = event.target as Node | null;
+ if (!target || triggerRef.current?.contains(target) || overlayRef.current?.contains(target)) return;
+
+ setDropdownVisible(false);
+ };
+
+ ownerDocument.addEventListener('pointerdown', handlePointerDown, true);
+ return () => ownerDocument.removeEventListener('pointerdown', handlePointerDown, true);
+ }, [dropdownVisible, setDropdownVisible]);
function handleVisibleChange(visible: boolean) {
setDropdownVisible(visible);
@@ -135,7 +159,7 @@ export function DropdownWrapper(props: Omit<Partial<IDropdownProps>, 'overlay'>
<Dropdown
align={align}
overlay={(
- <div className="univer-grid univer-gap-2">
+ <div ref={overlayRef} className="univer-grid univer-gap-2">
{overlay}
</div>
)}
@@ -143,7 +167,7 @@ export function DropdownWrapper(props: Omit<Partial<IDropdownProps>, 'overlay'>
open={dropdownVisible}
onOpenChange={handleVisibleChange}
>
- <div className="univer-h-full" onClick={(e) => e.stopPropagation()}>
+ <div ref={triggerRef} className="univer-h-full" onClick={(e) => e.stopPropagation()}>
{children}
</div>
</Dropdown>
@@ -209,6 +233,12 @@ export function DropdownMenuWrapper({
}) {
const { dropdownVisible, setDropdownVisible } = useContext(TooltipWrapperContext);
+ useEffect(() => {
+ if (disabled) {
+ setDropdownVisible(false);
+ }
+ }, [disabled, setDropdownVisible]);
+
const menuManagerService = useDependency(IMenuManagerService);
const resolveMenuItems = () => menuId ? menuManagerService.getMenuByPositionKey(menuId) : [];
const menuItems = useObservable(
diff --git a/packages/ui/src/views/components/ribbon/__tests__/ToolbarItem.spec.tsx b/packages/ui/src/views/components/ribbon/__tests__/ToolbarItem.spec.tsx
index dc90b6d460..87fc3f959a 100644
--- a/packages/ui/src/views/components/ribbon/__tests__/ToolbarItem.spec.tsx
+++ b/packages/ui/src/views/components/ribbon/__tests__/ToolbarItem.spec.tsx
@@ -14,10 +14,10 @@
* limitations under the License.
*/
-import type { ComponentType, ReactElement } from 'react';
-import { cleanup, fireEvent, render } from '@testing-library/react';
+import type { ComponentType, CSSProperties, ReactElement } from 'react';
+import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react';
import { ICommandService, ILogService, Injector, LocaleService } from '@univerjs/core';
-import { Subject } from 'rxjs';
+import { BehaviorSubject, Subject } from 'rxjs';
import { afterEach, describe, expect, it } from 'vitest';
import { ComponentManager } from '../../../../common/component-manager';
import { IconManager } from '../../../../common/icon-manager';
@@ -76,12 +76,14 @@ function renderWithDependencies(element: ReactElement) {
injector.add([ILogService, { useClass: TestLogService as never }]);
injector.add([ComponentManager]);
injector.add([IconManager]);
- injector.get(ComponentManager).register('TestDynamicOption', ({ onChange }: { onChange: (value: string) => void }) => (
- <button type="button" onClick={() => onChange('dynamic-value')}>Choose dynamic value</button>
+ injector.get(ComponentManager).register('TestDynamicOption', ({ onChange, className }: { onChange: (value: string) => void; className?: string }) => (
+ <button type="button" className={className} onClick={() => onChange('dynamic-value')}>Choose dynamic value</button>
));
injector.get(IconManager).register({
- TestIcon: ({ className }: { className?: string }) => <span className={className} data-icon="test" />,
+ TestIcon: ({ className, style }: { className?: string; style?: CSSProperties }) => (
+ <span className={className} data-icon="test" style={style} />
+ ),
});
const ConnectedTestRoot = connectInjector(() => element, injector) as ComponentType;
@@ -94,6 +96,283 @@ function renderWithDependencies(element: ReactElement) {
afterEach(cleanup);
describe('ToolbarItem', () => {
+ it('closes open selector options when the parent becomes disabled', async () => {
+ const disabled$ = new BehaviorSubject(false);
+ const { container, findByText, queryByText } = renderWithDependencies(
+ <ToolbarItem
+ id="test-selector"
+ type={MenuItemType.SELECTOR}
+ icon="TestIcon"
+ title="Format"
+ selections={[{ label: 'Format rows', value: 'row' }]}
+ disabled$={disabled$}
+ />
+ );
+
+ fireEvent.pointerDown(container.querySelector('.univer-toolbar-selector-root') as HTMLElement, {
+ button: 0,
+ ctrlKey: false,
+ });
+ expect(await findByText('Format rows')).toBeTruthy();
+
+ act(() => disabled$.next(true));
+ await waitFor(() => expect(queryByText('Format rows')).toBeNull());
+ });
+
+ it('shows a title and vertical layout for a large Grid button', () => {
+ const { getByRole, getByText } = renderWithDependencies(
+ <ToolbarItem
+ id="test-grid-button"
+ type={MenuItemType.BUTTON}
+ icon="TestIcon"
+ title="Format"
+ grid
+ large
+ showLabel
+ />
+ );
+
+ expect(getByRole('button').className).toContain('univer-flex-col');
+ expect(getByRole('button').className).toContain('[&>svg]:univer-size-8');
+ expect(getByRole('button').style.whiteSpace).toBe('normal');
+ expect(getByText('Format')).toBeTruthy();
+ });
+
+ it('uses a vertical root for a large Grid button selector', () => {
+ const { container, getByText } = renderWithDependencies(
+ <ToolbarItem
+ id="test-grid-selector"
+ type={MenuItemType.BUTTON_SELECTOR}
+ icon="TestIcon"
+ title="Insert"
+ selections={[{ label: 'Image', value: 'image' }]}
+ grid
+ large
+ showLabel
+ />
+ );
+
+ expect(container.querySelector('.univer-toolbar-button-selector-root')?.className).toContain('univer-box-border');
+ expect(container.querySelector('.univer-toolbar-button-selector-root')?.className).toContain('univer-flex-col');
+ expect(container.querySelector('.univer-toolbar-button-selector-main')?.className).toContain('[&>svg]:univer-size-8');
+ expect(getByText('Insert')).toBeTruthy();
+ });
+
+ it('matches the sizing of a large Grid button for a large selector', () => {
+ const { container } = renderWithDependencies(
+ <ToolbarItem
+ id="test-grid-selector"
+ type={MenuItemType.SELECTOR}
+ icon="TestIcon"
+ title="Shape"
+ selections={[{ label: 'Rectangle', value: 'rectangle' }]}
+ grid
+ large
+ showLabel
+ />
+ );
+
+ const rootClassName = container.querySelector('.univer-toolbar-selector-root')?.className;
+
+ expect(rootClassName).toContain('univer-box-border');
+ expect(rootClassName).toContain('univer-min-w-14');
+ expect(rootClassName).toContain('univer-px-1.5');
+ expect(rootClassName).toContain('univer-text-xs');
+ expect(rootClassName).toContain('univer-py-1');
+ expect(rootClassName).not.toContain('univer-pb-4');
+
+ const trigger = container.querySelector('.univer-toolbar-selector-trigger');
+ expect(trigger?.className).not.toContain('univer-absolute');
+ expect(trigger?.textContent).toContain('Shape');
+ });
+
+ it('hides the title of a large Grid selector when showLabel is false', () => {
+ const { queryByText } = renderWithDependencies(
+ <ToolbarItem
+ id="test-grid-selector"
+ type={MenuItemType.SELECTOR}
+ icon="TestIcon"
+ title="Common Functions"
+ selections={[{ label: 'SUM', value: 'SUM' }]}
+ grid
+ large
+ />
+ );
+
+ expect(queryByText('Common Functions')).toBeNull();
+ });
+
+ it('keeps the title of a regular Grid selector', () => {
+ const { getByText } = renderWithDependencies(
+ <ToolbarItem
+ id="test-grid-selector"
+ type={MenuItemType.SELECTOR}
+ icon="TestIcon"
+ title="Financial"
+ selections={[{ label: 'FV', value: 'FV' }]}
+ grid
+ />
+ );
+
+ expect(getByText('Financial')).toBeTruthy();
+ });
+
+ it('uses a regular icon for a one-row Grid button', () => {
+ const { getByRole } = renderWithDependencies(
+ <ToolbarItem
+ id="test-grid-regular-button"
+ type={MenuItemType.BUTTON}
+ icon="TestIcon"
+ grid
+ />
+ );
+
+ expect(getByRole('button').className).toContain('[&>svg]:univer-size-5');
+ expect(getByRole('button').className).not.toContain('[&>svg]:univer-size-8');
+ expect(getByRole('button').className).toContain('univer-h-full');
+ expect(getByRole('button').className).toContain('univer-min-w-8');
+ });
+
+ it('does not wrap an interactive custom button label in another button', () => {
+ const { container } = renderWithDependencies(
+ <ToolbarItem
+ id="test-custom-button"
+ type={MenuItemType.BUTTON}
+ label={{ name: 'TestDynamicOption' }}
+ grid
+ />
+ );
+
+ expect(container.querySelector('[data-u-command="test-custom-button"]')).toBeTruthy();
+ expect(container.querySelector('button button')).toBeNull();
+ });
+
+ it('fills a custom component in a fixed-width Grid item', () => {
+ const { container, getByRole } = renderWithDependencies(
+ <ToolbarItem
+ id="test-custom-button"
+ type={MenuItemType.BUTTON}
+ label={{ name: 'TestDynamicOption' }}
+ grid
+ fullWidth
+ />
+ );
+
+ expect(getByRole('button', { name: 'Choose dynamic value' }).className).toContain('!univer-w-full');
+ expect(container.querySelector('[data-u-command="test-custom-button"]')?.className).toContain('!univer-px-0');
+ });
+
+ it('applies a configured Grid icon size without changing the button size', () => {
+ const { container, getByRole } = renderWithDependencies(
+ <ToolbarItem
+ id="test-grid-sized-icon"
+ type={MenuItemType.BUTTON}
+ icon="TestIcon"
+ grid
+ iconSize={18}
+ />
+ );
+
+ const icon = container.querySelector('[data-icon="test"]') as HTMLElement;
+ expect(icon.style.width).toBe('18px');
+ expect(icon.style.height).toBe('18px');
+ expect(getByRole('button').className).toContain('univer-min-w-8');
+ });
+
+ it('fills the row height for a regular Grid button selector', () => {
+ const { container } = renderWithDependencies(
+ <ToolbarItem
+ id="test-grid-button-selector"
+ type={MenuItemType.BUTTON_SELECTOR}
+ icon="TestIcon"
+ selections={[{ label: 'Red', value: 'red' }]}
+ grid
+ />
+ );
+
+ expect(container.querySelector('.univer-toolbar-button-selector-root')?.className).toContain('univer-h-full');
+ expect(container.querySelector('.univer-toolbar-button-selector-root')?.className).toContain('univer-box-border');
+ expect(container.querySelector('.univer-toolbar-button-selector-trigger')?.className).toContain('univer-h-full');
+ });
+
+ it('uses the tooltip as the label for a compact Grid button selector when requested', () => {
+ const { container, getByText } = renderWithDependencies(
+ <ToolbarItem
+ id="test-grid-button-selector"
+ type={MenuItemType.BUTTON_SELECTOR}
+ icon="TestIcon"
+ tooltip="Crosshair Highlight"
+ selections={[{ label: 'Green', value: 'green' }]}
+ grid
+ showLabel
+ />
+ );
+
+ expect(getByText('Crosshair Highlight')).toBeTruthy();
+ expect(container.querySelector('.univer-toolbar-button-selector-root')?.className).not.toContain('univer-flex-col');
+ });
+
+ it('fills the row height for a regular Grid selector', () => {
+ const { container } = renderWithDependencies(
+ <ToolbarItem
+ id="test-grid-selector"
+ type={MenuItemType.SELECTOR}
+ selections={[{ label: 'Arial', value: 'Arial' }]}
+ grid
+ />
+ );
+
+ expect(container.querySelector('.univer-toolbar-selector-root')?.className).toContain('univer-h-full');
+ expect(container.querySelector('.univer-toolbar-selector-root')?.className).toContain('univer-box-border');
+ expect(container.querySelector('.univer-toolbar-selector-root')?.className).toContain('univer-border-solid');
+ expect(container.querySelector('.univer-toolbar-selector-root')?.className).toContain('univer-bg-white');
+ expect(container.querySelector('.univer-toolbar-selector-trigger')?.className).toContain('univer-ml-auto');
+ expect(container.querySelector('.univer-toolbar-selector-trigger')?.className).toContain('rtl:univer-mr-auto');
+ });
+
+ it('uses the tooltip as the Grid label when title is absent', () => {
+ const { getByText } = renderWithDependencies(
+ <ToolbarItem
+ id="test-grid-tooltip-label"
+ type={MenuItemType.BUTTON}
+ icon="TestIcon"
+ tooltip="Protect"
+ grid
+ large
+ showLabel
+ />
+ );
+
+ expect(getByText('Protect')).toBeTruthy();
+ });
+
+ it('mirrors button selector dropdown trigger placement in rtl', () => {
+ const { container } = renderWithDependencies(
+ <div dir="rtl">
+ <ToolbarItem
+ id="test-button-selector"
+ type={MenuItemType.BUTTON_SELECTOR}
+ icon="TestIcon"
+ title="Filter"
+ selections={[{ label: 'Clear', value: 'clear' }]}
+ />
+ </div>
+ );
+
+ const root = container.querySelector('.univer-toolbar-button-selector-root') as HTMLElement;
+ const main = container.querySelector('.univer-toolbar-button-selector-main') as HTMLElement;
+ const trigger = container.querySelector('.univer-toolbar-button-selector-trigger') as HTMLElement;
+
+ expect(root.className).toContain('rtl:univer-pl-5');
+ expect(root.className).toContain('rtl:univer-pr-0');
+ expect(main.className).toContain('rtl:univer-rounded-l-none');
+ expect(main.className).toContain('rtl:univer-rounded-r');
+ expect(trigger.className).toContain('rtl:univer-left-0');
+ expect(trigger.className).toContain('rtl:univer-right-auto');
+ expect(trigger.className).toContain('rtl:univer-rounded-l');
+ expect(trigger.className).toContain('rtl:univer-rounded-r-none');
+ });
+
it('resolves menu params when clicking a button', () => {
const { getByRole, commandService } = renderWithDependencies(
<ToolbarItem
diff --git a/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsx b/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsx
index a6611b5119..59bb0bfab7 100644
--- a/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsx
+++ b/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsx
@@ -19,13 +19,13 @@
*/
import type { ComponentType, ReactElement } from 'react';
-import { fireEvent, render } from '@testing-library/react';
+import { cleanup, fireEvent, render } from '@testing-library/react';
import { ILogService, Injector, LocaleService } from '@univerjs/core';
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import { ComponentManager } from '../../../../common/component-manager';
import { IconManager } from '../../../../common/icon-manager';
import { connectInjector } from '../../../../utils/di';
-import { DropdownMenuLabel } from '../TooltipButtonWrapper';
+import { DropdownMenuLabel, DropdownWrapper, ToolbarDropdownProvider, TooltipWrapper } from '../TooltipButtonWrapper';
class TestLocaleService {
t(key: string) {
@@ -51,6 +51,8 @@ function renderWithDependencies(element: ReactElement) {
return render(<ConnectedTestRoot />);
}
+afterEach(cleanup);
+
describe('DropdownMenuLabel', () => {
it('preserves option metadata when a custom label emits a dynamic value', () => {
const onOptionSelect = vi.fn();
@@ -79,3 +81,23 @@ describe('DropdownMenuLabel', () => {
});
});
});
+
+describe('DropdownWrapper', () => {
+ it('closes on an outside pointerdown even when no click follows', async () => {
+ const { findByText, getByRole, queryByText } = render(
+ <ToolbarDropdownProvider>
+ <TooltipWrapper dropdownKey="test-dropdown">
+ <DropdownWrapper overlay={<div>Dropdown content</div>}>
+ <button type="button">Open dropdown</button>
+ </DropdownWrapper>
+ </TooltipWrapper>
+ </ToolbarDropdownProvider>
+ );
+
+ fireEvent.click(getByRole('button', { name: 'Open dropdown' }));
+ await findByText('Dropdown content');
+ fireEvent.pointerDown(document.body);
+
+ expect(queryByText('Dropdown content')).toBeNull();
+ });
+});
diff --git a/packages/ui/src/views/components/ribbon/ribbon-grid-layout.ts b/packages/ui/src/views/components/ribbon/ribbon-grid-layout.ts
new file mode 100644
index 0000000000..cd511a2df0
--- /dev/null
+++ b/packages/ui/src/views/components/ribbon/ribbon-grid-layout.ts
@@ -0,0 +1,110 @@
+/**
+ * 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 { IMenuSchema } from '../../../services/menu/menu-manager.service';
+
+const RIBBON_GRID_ROWS = 2;
+
+export interface IRibbonGridPlacement {
+ item: IMenuSchema;
+ row: number;
+ column: number;
+ rowSpan: number;
+ columnSpan: number;
+ showLabel: boolean;
+ width?: number;
+ iconSize?: number;
+}
+
+export function placeRibbonGridItems(items: IMenuSchema[]): IRibbonGridPlacement[] {
+ const occupied = new Set<string>();
+ const placements = new Map<IMenuSchema, IRibbonGridPlacement>();
+ const fallbackItems: IMenuSchema[] = [];
+ let maxExplicitColumn = 0;
+
+ for (const item of items) {
+ const layout = item.gridLayout;
+ if (!layout) {
+ fallbackItems.push(item);
+ continue;
+ }
+
+ const rowSpan = layout.rowSpan ?? 1;
+ const columnSpan = layout.columnSpan ?? 1;
+ const cells = getCells(layout.row, layout.column, rowSpan, columnSpan);
+ const valid = cells.length > 0
+ && layout.row + rowSpan - 1 <= RIBBON_GRID_ROWS
+ && (layout.width === undefined || (Number.isFinite(layout.width) && layout.width > 0))
+ && (layout.iconSize === undefined || (Number.isFinite(layout.iconSize) && layout.iconSize > 0))
+ && cells.every((cell) => !occupied.has(cell));
+
+ if (!valid) {
+ // eslint-disable-next-line node/prefer-global/process
+ if (process.env.NODE_ENV !== 'production') {
+ globalThis.console.warn(`[RibbonGrid] Invalid gridLayout for "${item.key}"; using fallback placement.`);
+ }
+ fallbackItems.push(item);
+ continue;
+ }
+
+ cells.forEach((cell) => occupied.add(cell));
+ maxExplicitColumn = Math.max(maxExplicitColumn, layout.column + columnSpan - 1);
+ placements.set(item, {
+ item,
+ row: layout.row,
+ column: layout.column,
+ rowSpan,
+ columnSpan,
+ showLabel: layout.showLabel ?? false,
+ width: layout.width,
+ iconSize: layout.iconSize,
+ });
+ }
+
+ let fallbackRow = 1;
+ let fallbackColumn = maxExplicitColumn + 1;
+ for (const item of fallbackItems) {
+ placements.set(item, {
+ item,
+ row: fallbackRow,
+ column: fallbackColumn,
+ rowSpan: 1,
+ columnSpan: 1,
+ showLabel: false,
+ });
+ fallbackRow += 1;
+ if (fallbackRow > RIBBON_GRID_ROWS) {
+ fallbackRow = 1;
+ fallbackColumn += 1;
+ }
+ }
+
+ return items.map((item) => placements.get(item)!);
+}
+
+function getCells(row: number, column: number, rowSpan: number, columnSpan: number): string[] {
+ if (![row, column, rowSpan, columnSpan].every(Number.isInteger) || Math.min(row, column, rowSpan, columnSpan) < 1) {
+ return [];
+ }
+
+ const cells: string[] = [];
+ for (let currentRow = row; currentRow < row + rowSpan; currentRow++) {
+ for (let currentColumn = column; currentColumn < column + columnSpan; currentColumn++) {
+ cells.push(`${currentRow}:${currentColumn}`);
+ }
+ }
+ return cells;
+}
diff --git a/packages/ui/src/views/components/ribbon/ribbon-menu/RibbonGridMenu.tsx b/packages/ui/src/views/components/ribbon/ribbon-menu/RibbonGridMenu.tsx
new file mode 100644
index 0000000000..cf610460d5
--- /dev/null
+++ b/packages/ui/src/views/components/ribbon/ribbon-menu/RibbonGridMenu.tsx
@@ -0,0 +1,78 @@
+/**
+ * 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 { IMenuSchema } from '../../../../services/menu/menu-manager.service';
+import { LocaleService } from '@univerjs/core';
+import { clsx } from '@univerjs/design';
+import { useDependency } from '../../../../utils/di';
+
+export function RibbonGridMenu({
+ ribbon,
+ activatedTab,
+ onSelectTab,
+}: {
+ ribbon: IMenuSchema[];
+ activatedTab: string;
+ onSelectTab: (tab: IMenuSchema) => void;
+}) {
+ const localeService = useDependency(LocaleService);
+
+ return (
+ <div
+ data-testid="ribbon-grid-menu"
+ data-u-comp="ribbon-grid-menu"
+ className="
+ univer-flex univer-h-full univer-items-end univer-justify-start univer-overflow-x-auto univer-bg-gray-50
+ univer-px-2
+ dark:!univer-bg-gray-900
+ "
+ role="tablist"
+ >
+ {ribbon.map((group) => {
+ const isActive = activatedTab === group.key;
+ const title = localeService.t(group.title || group.key);
+ return (
+ <button
+ key={group.key}
+ type="button"
+ role="tab"
+ aria-selected={isActive}
+ title={title}
+ onClick={() => onSelectTab(group)}
+ className={clsx(`
+ univer-relative univer-flex univer-h-9 univer-cursor-pointer univer-items-center
+ univer-whitespace-nowrap univer-border-0 univer-border-b-[3px] univer-bg-transparent
+ univer-px-3 univer-text-base univer-font-semibold univer-text-gray-700
+ univer-transition-colors
+ hover:univer-text-gray-900
+ focus-visible:univer-outline-none focus-visible:univer-ring-2 focus-visible:univer-ring-inset
+ focus-visible:univer-ring-primary-500
+ dark:!univer-text-gray-200
+ dark:hover:!univer-text-white
+ `, isActive
+ ? `
+ univer-border-primary-600 univer-text-primary-700
+ dark:!univer-text-primary-300
+ `
+ : 'univer-border-transparent')}
+ >
+ {title}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/packages/ui/src/views/components/sidebar/Sidebar.tsx b/packages/ui/src/views/components/sidebar/Sidebar.tsx
index 29ebd14f15..254d534982 100644
--- a/packages/ui/src/views/components/sidebar/Sidebar.tsx
+++ b/packages/ui/src/views/components/sidebar/Sidebar.tsx
@@ -256,8 +256,9 @@ export function Sidebar() {
type="button"
className={`
focus:univer-ring-primary-500/50
- univer-cursor-pointer univer-appearance-none univer-rounded-sm univer-border-none
- univer-bg-transparent univer-p-0 univer-text-gray-500
+ univer-flex univer-size-6 univer-cursor-pointer univer-appearance-none univer-items-center
+ univer-justify-center univer-rounded-sm univer-border-none univer-bg-transparent univer-p-0
+ univer-text-gray-500
focus:univer-outline-none focus:univer-ring-2
dark:!univer-text-gray-300
`}
diff --git a/packages/ui/src/views/custom-label/CustomLabel.tsx b/packages/ui/src/views/custom-label/CustomLabel.tsx
index 8c40f506d7..baf7c4f814 100644
--- a/packages/ui/src/views/custom-label/CustomLabel.tsx
+++ b/packages/ui/src/views/custom-label/CustomLabel.tsx
@@ -26,6 +26,8 @@ import { useDependency, useObservable } from '../../utils/di';
export type ICustomLabelProps<T = undefined> = {
className?: string;
+ iconSize?: number;
+
value?: string | number | undefined;
value$?: Observable<T>;
@@ -40,7 +42,7 @@ export type ICustomLabelProps<T = undefined> = {
* @param props
*/
export function CustomLabel(props: ICustomLabelProps) {
- const { className, title, icon, label, value, value$ } = props;
+ const { className, iconSize, title, icon, label, value, value$ } = props;
const localeService = useDependency(LocaleService);
const componentManager = useDependency(ComponentManager);
const iconManager = useDependency(IconManager);
@@ -72,6 +74,7 @@ export function CustomLabel(props: ICustomLabelProps) {
<Icon
key={index++}
className="univer-text-base"
+ style={iconSize ? { width: iconSize, height: iconSize } : undefined}
extend={{ colorChannel1: isValid ? String(realValue) : 'var(--univer-primary-600)' }}
/>
);
diff --git a/packages/ui/src/views/menu/mobile/MobileMenu.tsx b/packages/ui/src/views/menu/mobile/MobileMenu.tsx
index b31a4c8c54..7f28ffeb46 100644
--- a/packages/ui/src/views/menu/mobile/MobileMenu.tsx
+++ b/packages/ui/src/views/menu/mobile/MobileMenu.tsx
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { Observable } from 'rxjs';
import type { LocaleKey } from '../../../locale/types';
import type {
IDisplayMenuItem,
@@ -41,6 +42,7 @@ type MobileMenuView =
kind: 'schema';
title?: string;
schemas: IMenuSchema[];
+ disabled$?: Observable<boolean>;
}
| {
kind: 'options';
@@ -49,6 +51,7 @@ type MobileMenuView =
menuItem: IDisplayMenuItem<IMenuSelectorItem<string, MenuItemDefaultValueType, any>>;
menuKey: string;
currentValue: MenuItemDefaultValueType;
+ disabled$?: Observable<boolean>;
};
interface IMobileMenuProps extends IBaseMenuProps {
@@ -140,6 +143,7 @@ export function MobileMenu(props: IMobileMenuProps) {
menuType={menuType}
onExecute={onOptionSelect}
onOpenView={openView}
+ inheritedDisabled$={currentView?.disabled$}
/>
</div>
)}
@@ -151,6 +155,7 @@ export function MobileMenu(props: IMobileMenuProps) {
menuItem={currentView.menuItem}
options={currentView.options}
currentValue={currentView.currentValue}
+ inheritedDisabled$={currentView.disabled$}
onExecute={onOptionSelect}
/>
</div>
@@ -166,8 +171,9 @@ function MobileSchemaList(props: {
menuType?: string;
onExecute?: IBaseMenuProps['onOptionSelect'];
onOpenView: (view: MobileMenuView) => void;
+ inheritedDisabled$?: Observable<boolean>;
}) {
- const { schemas, menuManagerService, menuType, onExecute, onOpenView } = props;
+ const { schemas, menuManagerService, menuType, onExecute, onOpenView, inheritedDisabled$ } = props;
const localeService = useDependency(LocaleService);
const hiddenGroupStates = useContextGroupHiddenStates(schemas);
@@ -193,6 +199,7 @@ function MobileSchemaList(props: {
menuType={menuType}
onExecute={onExecute}
onOpenView={onOpenView}
+ inheritedDisabled$={inheritedDisabled$}
bordered={index !== visibleSchemas.length - 1}
/>
);
@@ -228,6 +235,7 @@ function MobileSchemaList(props: {
menuType={menuType}
onExecute={onExecute}
onOpenView={onOpenView}
+ inheritedDisabled$={inheritedDisabled$}
bordered={childIndex !== schema.children!.length - 1}
/>
))}
@@ -244,10 +252,11 @@ function MobileSchemaRow(props: {
menuType?: string;
onExecute?: IBaseMenuProps['onOptionSelect'];
onOpenView: (view: MobileMenuView) => void;
+ inheritedDisabled$?: Observable<boolean>;
bordered: boolean;
}) {
- const { schema, menuManagerService, menuType, onExecute, onOpenView, bordered } = props;
- const interaction = useMobileSchemaInteraction({ schema, menuManagerService, menuType, onOpenView });
+ const { schema, menuManagerService, menuType, onExecute, onOpenView, inheritedDisabled$, bordered } = props;
+ const interaction = useMobileSchemaInteraction({ schema, menuManagerService, menuType, onOpenView, inheritedDisabled$ });
if (!interaction || interaction.hidden) {
return null;
@@ -299,9 +308,11 @@ function MobileSelectionOptionsView(props: {
menuKey: string;
menuItem: IDisplayMenuItem<IMenuSelectorItem<string, MenuItemDefaultValueType, any>>;
currentValue: MenuItemDefaultValueType;
+ inheritedDisabled$?: Observable<boolean>;
onExecute?: IBaseMenuProps['onOptionSelect'];
}) {
- const { options, menuKey, menuItem, currentValue, onExecute } = props;
+ const { options, menuKey, menuItem, currentValue, inheritedDisabled$, onExecute } = props;
+ const inheritedDisabled = useObservable<boolean>(inheritedDisabled$, false);
return (
<>
@@ -312,6 +323,7 @@ function MobileSelectionOptionsView(props: {
menuKey={menuKey}
menuItem={menuItem}
currentValue={currentValue}
+ disabled={inheritedDisabled}
bordered={index !== options.length - 1}
onExecute={onExecute}
/>
@@ -325,13 +337,15 @@ function MobileSelectionOptionRow(props: {
menuKey: string;
menuItem: IDisplayMenuItem<IMenuSelectorItem<string, MenuItemDefaultValueType, any>>;
currentValue: MenuItemDefaultValueType;
+ disabled: boolean;
bordered: boolean;
onExecute?: IBaseMenuProps['onOptionSelect'];
}) {
- const { option, menuKey, menuItem, currentValue, bordered, onExecute } = props;
+ const { option, menuKey, menuItem, currentValue, disabled, bordered, onExecute } = props;
const optionValue = useObservable(option.value$);
const displayValue = option.value ?? optionValue;
const selected = displayValue === currentValue;
+ const optionDisabled = disabled || Boolean(option.disabled);
return (
<button
@@ -347,8 +361,12 @@ function MobileSelectionOptionRow(props: {
`,
bordered && borderBottomClassName
)}
- disabled={option.disabled}
+ disabled={optionDisabled}
onClick={() => {
+ if (optionDisabled) {
+ return;
+ }
+
onExecute?.({
...option,
value: displayValue,
@@ -377,12 +395,19 @@ function useMobileSchemaInteraction(props: {
menuManagerService: IMenuManagerService;
menuType?: string;
onOpenView: (view: MobileMenuView) => void;
+ inheritedDisabled$?: Observable<boolean>;
}) {
- const { schema, menuManagerService, menuType, onOpenView } = props;
+ const { schema, menuManagerService, menuType, onOpenView, inheritedDisabled$ } = props;
const localeService = useDependency(LocaleService);
const menuItem = schema.item as IDisplayMenuItem<IMenuItem> | undefined;
const selectorItem = menuItem as IDisplayMenuItem<IMenuSelectorItem<string, MenuItemDefaultValueType, any>> | undefined;
- const disabled = useObservable<boolean>(menuItem?.disabled$, false);
+ const disabled$ = useMemo(() => {
+ const sources = [inheritedDisabled$, menuItem?.disabled$].filter((source): source is Observable<boolean> => Boolean(source));
+ return sources.length
+ ? combineLatest(sources.map((source) => source.pipe(startWith(false)))).pipe(map((states) => states.some(Boolean)))
+ : undefined;
+ }, [inheritedDisabled$, menuItem?.disabled$]);
+ const disabled = useObservable<boolean>(disabled$, false);
const hidden = useObservable<boolean>(menuItem?.hidden$, false);
const value = useObservable<MenuItemDefaultValueType>(menuItem?.value$);
const selectionsFromObservable = useObservable(
@@ -418,11 +443,16 @@ function useMobileSchemaInteraction(props: {
const currentValueText = typeof value === 'string' || typeof value === 'number' ? String(value) : '';
const onPress = (onExecute?: IBaseMenuProps['onOptionSelect']) => {
+ if (disabled) {
+ return;
+ }
+
if (schemaChildren.length > 0) {
onOpenView({
kind: 'schema',
title: getMenuSchemaTitle(schema, localeService),
schemas: schemaChildren,
+ disabled$,
});
return;
}
@@ -435,6 +465,7 @@ function useMobileSchemaInteraction(props: {
menuItem: selectorItem,
menuKey: schema.key,
currentValue: value,
+ disabled$,
});
return;
}
@@ -444,6 +475,7 @@ function useMobileSchemaInteraction(props: {
kind: 'schema',
title: getMenuSchemaTitle(schema, localeService),
schemas: subMenuItems,
+ disabled$,
});
return;
}
diff --git a/packages/ui/src/views/menu/mobile/__tests__/MobileMenu.spec.tsx b/packages/ui/src/views/menu/mobile/__tests__/MobileMenu.spec.tsx
new file mode 100644
index 0000000000..12b5f94187
--- /dev/null
+++ b/packages/ui/src/views/menu/mobile/__tests__/MobileMenu.spec.tsx
@@ -0,0 +1,105 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ComponentProps, ComponentType } from 'react';
+import type { IMenuSchema } from '../../../../services/menu/menu-manager.service';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { ILogService, Injector, LocaleService } from '@univerjs/core';
+import { BehaviorSubject, Subject } from 'rxjs';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { ComponentManager, IconManager } from '../../../../common';
+import { MenuItemType } from '../../../../services/menu/menu';
+import { IMenuManagerService } from '../../../../services/menu/menu-manager.service';
+import { connectInjector } from '../../../../utils/di';
+import { MobileMenu } from '../MobileMenu';
+
+class TestLocaleService {
+ t(key: string) {
+ return key;
+ }
+}
+
+class TestMenuManagerService {
+ readonly menuChanged$ = new Subject<void>();
+
+ getMenuByPositionKey() {
+ return [];
+ }
+}
+
+class TestLogService {
+ warn(): void {}
+}
+
+function renderWithDependencies(
+ schemas: IMenuSchema[],
+ onOptionSelect: NonNullable<ComponentProps<typeof MobileMenu>['onOptionSelect']>
+) {
+ const injector = new Injector();
+ injector.add([LocaleService, { useClass: TestLocaleService as never }]);
+ injector.add([ILogService, { useClass: TestLogService as never }]);
+ injector.add([IMenuManagerService, { useClass: TestMenuManagerService as never }]);
+ injector.add([ComponentManager]);
+ injector.add([IconManager]);
+
+ const ConnectedTestRoot = connectInjector(() => (
+ <MobileMenu schemas={schemas} onOptionSelect={onOptionSelect} />
+ ), injector) as ComponentType;
+
+ return render(<ConnectedTestRoot />);
+}
+
+afterEach(cleanup);
+
+describe('MobileMenu', () => {
+ it('disables an open child view when its parent becomes disabled', async () => {
+ const disabled$ = new BehaviorSubject(false);
+ const onOptionSelect = vi.fn();
+
+ renderWithDependencies([
+ {
+ key: 'print',
+ order: 0,
+ item: {
+ id: 'print.menu',
+ type: MenuItemType.SUBITEMS,
+ title: 'Print',
+ disabled$,
+ },
+ children: [
+ {
+ key: 'print.layout',
+ order: 0,
+ item: {
+ id: 'print.layout',
+ type: MenuItemType.BUTTON,
+ title: 'Print layout',
+ },
+ },
+ ],
+ },
+ ], onOptionSelect);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Print' }));
+ const child = screen.getByRole('button', { name: 'Print layout' });
+ expect((child as HTMLButtonElement).disabled).toBe(false);
+
+ act(() => disabled$.next(true));
+ await waitFor(() => expect((child as HTMLButtonElement).disabled).toBe(true));
+ fireEvent.click(child);
+ expect(onOptionSelect).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/ui/src/views/slider/ZoomInput.tsx b/packages/ui/src/views/slider/ZoomInput.tsx
index 6ad2f54de2..66d4266abf 100644
--- a/packages/ui/src/views/slider/ZoomInput.tsx
+++ b/packages/ui/src/views/slider/ZoomInput.tsx
@@ -127,13 +127,13 @@ export function ZoomInput(props: IZoomInputProps) {
>
<Input
className={`
- univer-box-border univer-h-6 univer-w-[52px] univer-border-none univer-bg-transparent
+ univer-box-border univer-h-6 univer-min-w-0 univer-flex-1 univer-border-none univer-bg-transparent
[&_input:focus]:!univer-ring-0
- [&_input]:univer-h-6 [&_input]:univer-w-[52px] [&_input]:univer-border-none
+ [&_input]:univer-h-6 [&_input]:univer-w-full [&_input]:univer-border-none
[&_input]:!univer-bg-transparent [&_input]:univer-px-1 [&_input]:univer-text-center
[&_input]:univer-text-xs [&_input]:univer-tabular-nums
`}
- inputClass="univer-w-[52px]"
+ inputClass="univer-w-full"
size="mini"
value={inputValue}
disabled={disabled}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index f91de52fbc..780cd33c37 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -112,8 +112,8 @@ importers:
specifier: workspace:*
version: link:../../packages/engine-render
'@univerjs/icons':
- specifier: 1.29.0
+ specifier: 1.32.0
'@univerjs/mockdata':
specifier: workspace:*
version: link:../mockdata
@@ -355,11 +355,11 @@ importers:
devDependencies:
'@univerjs/icons':
- specifier: 1.29.0
+ specifier: 1.32.0
'@univerjs/icons-svg':
- specifier: ^1.29.0
- version: 1.29.0
+ specifier: ^1.32.0
+ version: 1.32.0
typescript:
specifier: ^6.0.3
version: 6.0.3
@@ -500,8 +500,8 @@ importers:
specifier: workspace:*
version: link:../packages/find-replace
'@univerjs/icons':
- specifier: 1.29.0
+ specifier: 1.32.0
'@univerjs/mockdata':
specifier: workspace:*
version: link:../common/mockdata
@@ -738,8 +738,8 @@ importers:
specifier: workspace:*
version: link:../design
'@univerjs/icons':
- specifier: 1.29.0
+ specifier: 1.32.0
'@univerjs/sheets':
specifier: workspace:*
version: link:../sheets
@@ -873,14 +873,17 @@ importers:
specifier: ^1.3.0
version: 1.3.0(@types/[email protected])([email protected])
'@univerjs/icons':
- specifier: 1.29.0
+ specifier: 1.32.0
class-variance-authority:
specifier: ^0.7.1
version: 0.7.1
clsx:
specifier: ^2.1.1
version: 2.1.1
+ cmdk:
+ specifier: 1.1.1
react-transition-group:
specifier: ^4.4.5
@@ -1064,8 +1067,8 @@ importers:
specifier: workspace:*
version: link:../engine-render
'@univerjs/icons':
- specifier: 1.29.0
+ specifier: 1.32.0
'@univerjs/ui':
specifier: workspace:*
version: link:../ui
@@ -1165,8 +1168,8 @@ importers:
specifier: workspace:*
version: link:../engine-render
'@univerjs/icons':
- specifier: 1.29.0
+ specifier: 1.32.0
'@univerjs/ui':
specifier: workspace:*
version: link:../ui
@@ -1208,8 +1211,8 @@ importers:
specifier: workspace:*
version: link:../engine-render
'@univerjs/icons':
- specifier: 1.29.0
+ specifier: 1.32.0
'@univerjs/thread-comment':
specifier: workspace:*
version: link:../thread-comment
@@ -1257,8 +1260,8 @@ importers:
specifier: workspace:*
version: link:../engine-render
'@univerjs/icons':
- specifier: 1.29.0
+ specifier: 1.32.0
'@univerjs/ui':
specifier: workspace:*
version: link:../ui
@@ -1331,8 +1334,8 @@ importers:
specifier: workspace:*
version: link:../engine-render
'@univerjs/icons':
- specifier: 1.29.0
+ specifier: 1.32.0
'@univerjs/ui':
specifier: workspace:*
version: link:../ui
@@ -1442,8 +1445,8 @@ importers:
specifier: workspace:*
version: link:../engine-render
'@univerjs/icons':
- specifier: 1.29.0
+ specifier: 1.32.0
'@univerjs/ui':
specifier: workspace:*
version: link:../ui
@@ -1602,8 +1605,8 @@ importers:
specifier: workspace:*
version: link:../../common/shared
'@univerjs/icons-svg':
- specifier: ^1.29.0
- version: 1.29.0
+ specifier: ^1.32.0
+ version: 1.32.0
'@univerjs/sheets-formula':
specifier: workspace:*
version: link:../sheets-formula
@@ -1632,8 +1635,8 @@ importers:
specifier: workspace:*
version: link:../engine-render
'@univerjs/icons':
- specifier: 1.29.0
+ specifier: 1.32.0
'@univerjs/sheets':
specifier: workspace:*
version: link:../sheets
@@ -1687,8 +1690,8 @@ importers:
specifier: workspace:*
version: link:../engine-render
'@univerjs/icons':
- specifier: 1.29.0
+ specifier: 1.32.0
'@univerjs/sheets':
specifier: workspace:*
version: link:../sheets
@@ -1773,8 +1776,8 @@ importers:
specifier: workspace:*
version: link:../engine-render
'@univerjs/icons':
- specifier: 1.29.0
+ specifier: 1.32.0
'@univerjs/sheets':
specifier: workspace:*
version: link:../sheets
@@ -1945,8 +1948,8 @@ importers:
specifier: workspace:*
version: link:../engine-render
'@univerjs/icons':
- specifier: 1.29.0
+ specifier: 1.32.0
'@univerjs/rpc':
specifier: workspace:*
version: link:../rpc
@@ -2074,8 +2077,8 @@ importers:
specifier: workspace:*
version: link:../engine-render
'@univerjs/icons':
- specifier: 1.29.0
+ specifier: 1.32.0
'@univerjs/sheets':
specifier: workspace:*
version: link:../sheets
@@ -2160,8 +2163,8 @@ importers:
specifier: workspace:*
version: link:../engine-render
'@univerjs/icons':
- specifier: 1.29.0
+ specifier: 1.32.0
'@univerjs/sheets':
specifier: workspace:*
version: link:../sheets
@@ -2246,8 +2249,8 @@ importers:
specifier: workspace:*
version: link:../engine-render
'@univerjs/icons':
- specifier: 1.29.0
+ specifier: 1.32.0
'@univerjs/sheets':
specifier: workspace:*
version: link:../sheets
@@ -2323,8 +2326,8 @@ importers:
specifier: workspace:*
version: link:../engine-render
'@univerjs/icons':
- specifier: 1.29.0
+ specifier: 1.32.0
'@univerjs/sheets':
specifier: workspace:*
version: link:../sheets
@@ -2394,8 +2397,8 @@ importers:
specifier: workspace:*
version: link:../engine-formula
'@univerjs/icons':
- specifier: 1.29.0
+ specifier: 1.32.0
'@univerjs/sheets':
specifier: workspace:*
version: link:../sheets
@@ -2480,8 +2483,8 @@ importers:
specifier: workspace:*
version: link:../engine-render
'@univerjs/icons':
- specifier: 1.29.0
+ specifier: 1.32.0
'@univerjs/sheets':
specifier: workspace:*
version: link:../sheets
@@ -2563,8 +2566,8 @@ importers:
specifier: workspace:*
version: link:../engine-render
'@univerjs/icons':
- specifier: 1.29.0
+ specifier: 1.32.0
'@univerjs/sheets':
specifier: workspace:*
version: link:../sheets
@@ -2627,8 +2630,8 @@ importers:
specifier: workspace:*
version: link:../engine-render
'@univerjs/icons':
- specifier: 1.29.0
+ specifier: 1.32.0
'@univerjs/protocol':
specifier: workspace:*
version: link:../protocol
@@ -2710,8 +2713,8 @@ importers:
specifier: workspace:*
version: link:../engine-render
'@univerjs/icons':
- specifier: 1.29.0
+ specifier: 1.32.0
'@univerjs/slides':
specifier: workspace:*
version: link:../slides
@@ -2794,8 +2797,8 @@ importers:
specifier: workspace:*
version: link:../docs-ui
'@univerjs/icons':
- specifier: 1.29.0
+ specifier: 1.32.0
'@univerjs/thread-comment':
specifier: workspace:*
version: link:../thread-comment
@@ -2840,8 +2843,8 @@ importers:
specifier: workspace:*
version: link:../engine-render
'@univerjs/icons':
- specifier: 1.29.0
+ specifier: 1.32.0
'@wendellhu/redi':
specifier: 1.1.2
version: 1.1.2([email protected])
@@ -6823,11 +6826,11 @@ packages:
resolution: {integrity: sha512-UexrHGnGTpbuQHct2ExOc2ZcFbGUS9FOesCxxqdBGcpI1BxYu/LZ6U8Aq6/72XtF/qRBk9nhuGHFJIXXMhPMdw==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
- '@univerjs/[email protected]':
- resolution: {integrity: sha512-aPCQrlIcI6XqHW6UG0AZoswlTHUKjiUWL3iArfmv+D0ORQhfEMkF5jeYbwXx3C0a0a8EkDc5JtMu0zo0SOjIfQ==}
+ '@univerjs/[email protected]':
+ resolution: {integrity: sha512-kQ+lM+JC4jeWZWYvF0x61PjSuyqU6Db+JoAVLxVKbwcxUv9ecBEL4U5uIZUKKdJGkFflyDh8T7qI4BgOuMcQxQ==}
- '@univerjs/[email protected]':
- resolution: {integrity: sha512-j+CwSb7aXVxG38EEfF/Q/Q6ay54pLbI4xpLeXO0I2ZRFyCJW7w1kP5a9mqGeEpGy0N0RpWMpxz/7la5rkUKCqg==}
+ '@univerjs/[email protected]':
+ resolution: {integrity: sha512-rVhC+58erUnV5JtdnIGPtnxgY+4VZU1fIrl87K0v6IStC3apJs45YUcHtXU62hPSLWIUFGpNwyMRWQHymL8ACQ==}
peerDependencies:
react: 19.2.7
react-dom: 19.2.7
@@ -7558,6 +7561,12 @@ packages:
resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==}
engines: {node: '>=6'}
+ resolution: {integrity: sha512-Vsv7kFaXm+ptHDMZ7izaRsP70GgrW9NBNGswt9OZaVBLlE0SNpDq8eu/VGXyF9r7M0azK3Wy7OlYXsuyYLFzHg==}
+ peerDependencies:
+ react: 19.2.7
+ react-dom: 19.2.7
+
resolution: {integrity: sha512-loKTxY1zCOuG4j9f6EPnuyyYkf58RnhhWTvRoZEokgB+WbdXehfjFviyOVYkqzEWz1Q5kRiZdBYS5SwxbQYwzw==}
@@ -14515,9 +14524,9 @@ snapshots:
'@typescript-eslint/types': 8.63.0
eslint-visitor-keys: 5.0.1
- '@univerjs/[email protected]': {}
+ '@univerjs/[email protected]': {}
dependencies:
react: 19.2.7
react-dom: 19.2.7([email protected])
@@ -15320,6 +15329,18 @@ snapshots:
+ dependencies:
+ '@radix-ui/react-compose-refs': 1.1.3(@types/[email protected])([email protected])
+ '@radix-ui/react-id': 1.1.2(@types/[email protected])([email protected])
+ react: 19.2.7
+ react-dom: 19.2.7([email protected])
+ transitivePeerDependencies:
+ - '@types/react'
+ - '@types/react-dom'
+