Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
chore(examples): support mobile workbench previews (#7769)
白熱a9b238ad45ec
diff --git a/examples/src/__tests__/mount-example.spec.ts b/examples/src/__tests__/mount-example.spec.tsindex 13613e7099..b2a11e8deb 100644--- a/examples/src/__tests__/mount-example.spec.ts+++ b/examples/src/__tests__/mount-example.spec.ts@@ -236,6 +236,38 @@ describe('mounted Univer lifecycle', () => {});describe('createExampleSwitcher', () => {+ it('restarts the active example when its device changes and keeps other settings', async () => {+ const host = {} as HTMLElement;+ const options = { device: 'desktop', locale: 'frFR', darkMode: true } as IWorkbenchMountOptions;+ const events: string[] = [];+ const mount: MountExample = (_host, settings) => {+ events.push(`mount ${settings.device} ${settings.locale} ${settings.darkMode}`);+ return {+ dispose: () => events.push(`dispose ${settings.device}`),+ updateSettings: async (settings) => {+ events.push(`update ${settings.device} ${settings.darkMode}`);+ },+ };+ };+ const switcher = createExampleSwitcher(host, { sheets: async () => ({ mount }) });++ await switcher.open('sheets', options);+ await switcher.updateSettings({ ...options, device: 'mobile' });+ await switcher.updateSettings({ ...options, device: 'mobile', darkMode: false });+ await switcher.updateSettings(options);+ switcher.dispose();++ expect(events).toEqual([+ 'mount desktop frFR true',+ 'dispose desktop',+ 'mount mobile frFR true',+ 'update mobile false',+ 'dispose mobile',+ 'mount desktop frFR true',+ 'dispose desktop',+ ]);+ });+it('mounts only the latest requested example', async () => {const host = {} as HTMLElement;const docsDispose = vi.fn();diff --git a/examples/src/__tests__/workbench-settings.spec.ts b/examples/src/__tests__/workbench-settings.spec.tsindex 32aefaa748..7a3e2a890c 100644--- a/examples/src/__tests__/workbench-settings.spec.ts+++ b/examples/src/__tests__/workbench-settings.spec.ts@@ -21,6 +21,7 @@ function readStoredSettings(value: unknown) {describe('readWorkbenchSettings', () => {it('keeps supported settings and rejects unknown stored values', () => {expect(readStoredSettings({+ device: 'mobile',locale: 'arSA',region: 'frFR',direction: 'rtl',@@ -30,6 +31,7 @@ describe('readWorkbenchSettings', () => {uiChrome: 'no-ribbon',zoomRatio: 1.25,})).toEqual({+ device: 'mobile',locale: 'arSA',region: 'frFR',direction: 'rtl',@@ -40,6 +42,7 @@ describe('readWorkbenchSettings', () => {zoomRatio: 1.25,});expect(readStoredSettings({+ device: 'tablet',locale: 'unknown',region: 'moon',direction: 'sideways',@@ -72,6 +75,7 @@ describe('readWorkbenchSettings', () => {},};const settings = {+ device: 'mobile',locale: 'enUS',region: 'frFR',direction: 'rtl',diff --git a/examples/src/docs/mount.ts b/examples/src/docs/mount.tsindex 2a85c5c21b..70b9875be0 100644--- a/examples/src/docs/mount.ts+++ b/examples/src/docs/mount.ts@@ -1,15 +1,17 @@+import type { Plugin, PluginCtor } from '@univerjs/core';import type { MountExample } from '../mount-example';import type { IWorkbenchMountOptions } from '../workbench-settings';import { UniverDocsLayoutWorkerPlugin } from '@univerjs/docs';-import { SetDocZoomRatioOperation } from '@univerjs/docs-ui';+import { SetDocZoomRatioOperation, UniverDocsMobileUIPlugin } from '@univerjs/docs-ui';import { UniverDocsCorePreset } from '@univerjs/preset-docs-core';-import { UniverDocsDrawingPreset } from '@univerjs/preset-docs-drawing';-import { UniverDocsHyperLinkPreset } from '@univerjs/preset-docs-hyper-link';-import { UniverDocsThreadCommentPreset } from '@univerjs/preset-docs-thread-comment';+import { UniverDocsDrawingMobileUIPlugin, UniverDocsDrawingPreset, UniverDrawingMobileUIPlugin } from '@univerjs/preset-docs-drawing';+import { UniverDocsHyperLinkMobileUIPlugin, UniverDocsHyperLinkPreset } from '@univerjs/preset-docs-hyper-link';+import { UniverDocsThreadCommentMobileUIPlugin, UniverDocsThreadCommentPreset, UniverThreadCommentMobileUIPlugin } from '@univerjs/preset-docs-thread-comment';import { createUniver, LocaleType, UniverInstanceType } from '@univerjs/presets';+import { UniverMobileUIPlugin, UniverUIPlugin } from '@univerjs/ui';import { loadDocumentLocale } from 'virtual:univer-examples-document-locale';-import { applyWorkbenchUIChrome, createMountedUniver } from '../mount-example';+import { applyWorkbenchUIChrome, createMountedUniver, replacePresetPlugins } from '../mount-example';import { getEffectiveWorkbenchRegion } from '../workbench-settings';import { createDocumentFixture } from './create-document-fixture';import '@univerjs/ui/facade';@@ -37,9 +39,25 @@ const UNIVER_LOCALES = {[LocaleType.PL_PL]: LocaleType.PL_PL,} satisfies Record<IWorkbenchMountOptions['locale'], LocaleType>;+const MOBILE_PLUGINS = new Map<string, PluginCtor<Plugin>>([+ UniverDocsMobileUIPlugin,+ UniverDrawingMobileUIPlugin,+ UniverDocsDrawingMobileUIPlugin,+ UniverDocsHyperLinkMobileUIPlugin,+ UniverThreadCommentMobileUIPlugin,+ UniverDocsThreadCommentMobileUIPlugin,+].map((plugin) => [plugin.pluginName, plugin]));+MOBILE_PLUGINS.set(UniverUIPlugin.pluginName, UniverMobileUIPlugin);+export const mount: MountExample = async (host, options) => {const locale = await loadDocumentLocale(options.locale);const localeType = UNIVER_LOCALES[options.locale];+ const presets = [+ UniverDocsCorePreset({ container: host, ribbonType: options.ribbonType, toc: true }),+ UniverDocsDrawingPreset(),+ UniverDocsHyperLinkPreset(),+ UniverDocsThreadCommentPreset(),+ ];const { univer, univerAPI } = createUniver({locale: localeType,region: UNIVER_LOCALES[getEffectiveWorkbenchRegion(options)],@@ -49,12 +67,7 @@ export const mount: MountExample = async (host, options) => {theme: options.theme,darkMode: options.darkMode,direction: options.direction,- presets: [- UniverDocsCorePreset({ container: host, ribbonType: options.ribbonType, toc: true }),- UniverDocsDrawingPreset(),- UniverDocsHyperLinkPreset(),- UniverDocsThreadCommentPreset(),- ],+ presets: options.device === 'mobile' ? replacePresetPlugins(presets, MOBILE_PLUGINS) : presets,});univer.registerPlugin(UniverDocsLayoutWorkerPlugin, {workerFactory: () => new Worker(new URL('./worker.ts', import.meta.url), { type: 'module' }),diff --git a/examples/src/main.ts b/examples/src/main.tsindex aa9bf8ca34..2fc40e7174 100644--- a/examples/src/main.ts+++ b/examples/src/main.ts@@ -1,5 +1,6 @@import type { ExampleLoader } from './mount-example';import type {+ WorkbenchDevice,WorkbenchDirection,WorkbenchLocale,WorkbenchRegion,@@ -88,6 +89,8 @@ function renderWorkbenchSettings(currentSettings = settings) {document.documentElement.style.setProperty('--workbench-accent', theme.primary[600]);renderWorkbenchSettingsControl(settingsContainer, {settings: currentSettings,+ supportsMobile: getExampleName() !== 'slides',+ onDeviceChange,onLocaleChange,onRegionChange,onDirectionChange,@@ -189,6 +192,10 @@ async function onLocaleChange(locale: WorkbenchLocale) {});}+async function onDeviceChange(device: WorkbenchDevice) {+ await updateWorkbenchSettings({ ...settings, device });+}+async function onDirectionChange(direction: WorkbenchDirection) {await updateWorkbenchSettings({ ...settings, direction });}diff --git a/examples/src/mount-example.ts b/examples/src/mount-example.tsindex 92f3fae948..658c70c8d3 100644--- a/examples/src/mount-example.ts+++ b/examples/src/mount-example.ts@@ -1,5 +1,6 @@-import type { Univer } from '@univerjs/core';+import type { Plugin, PluginCtor, Univer } from '@univerjs/core';import type { FUniver } from '@univerjs/core/facade';+import type { IPreset } from '@univerjs/presets';import type { IWorkbenchMountOptions, WorkbenchLocale, WorkbenchUIChromeMode } from './workbench-settings';import { getEffectiveWorkbenchRegion, getWorkbenchUIChromeVisibility } from './workbench-settings';@@ -39,6 +40,16 @@ interface IPendingExampleLocale {pack: Awaited<ReturnType<LoadExampleLocale>>;}+export function replacePresetPlugins(presets: IPreset[], replacements: Map<string, PluginCtor<Plugin>>): IPreset[] {+ return presets.map((preset) => ({+ ...preset,+ plugins: preset.plugins.map((entry) => {+ const [plugin, config] = Array.isArray(entry) ? entry : [entry];+ return [replacements.get(plugin.pluginName) ?? plugin, config];+ }),+ }));+}+export function createUniverDisposer(host: HTMLElement, univer: Univer, univerAPI?: FUniver): DisposeExample {let disposed = false;const workbenchWindow = window as typeof window & IWorkbenchWindow;@@ -178,6 +189,7 @@ export function createMountedUniver(export function createExampleSwitcher<T extends string>(host: HTMLElement, loaders: Record<T, ExampleLoader>) {let generation = 0;+ let currentTarget: T | undefined;let current: IMountedExample | undefined;let latestSettings: IWorkbenchMountOptions | undefined;let mountQueue = Promise.resolve();@@ -191,65 +203,62 @@ export function createExampleSwitcher<T extends string>(host: HTMLElement, loade}return {- async open(target: T, options: IWorkbenchMountOptions) {+ async open(target: T, options: IWorkbenchMountOptions): Promise<void> {const request = ++generation;+ currentTarget = target;latestSettings = options;const previous = current;current = undefined;previous?.dispose();- const openTask = (async () => {- try {- const { mount } = await loaders[target]();+ const openTask = loaders[target]().then(({ mount }) => {+ if (request !== generation) {+ return;+ }++ const mountTask = mountQueue.then(async () => {if (request !== generation) {return;}- const mountTask = mountQueue.then(async () => {- if (request !== generation) {- return;- }-- const mounted = await mount(host, options);- if (request === generation) {- current = mounted;- if (latestSettings && latestSettings !== options) {- await enqueueSettingsUpdate(mounted, latestSettings);- }- } else {- mounted.dispose();- }- });- mountQueue = mountTask.catch(() => undefined);- await mountTask;- } catch (error) {+ const mounted = await mount(host, options);if (request === generation) {- throw error;+ current = mounted;+ if (latestSettings && latestSettings !== options) {+ await enqueueSettingsUpdate(mounted, latestSettings);+ }+ } else {+ mounted.dispose();}+ });+ mountQueue = mountTask.catch(() => undefined);+ return mountTask;+ }).catch((error) => {+ if (request === generation) {+ latestSettings = undefined;+ throw error;}- })();+ });pendingOpen = openTask;- try {- await openTask;- } finally {+ return openTask.finally(() => {if (pendingOpen === openTask) {pendingOpen = undefined;}- }+ });},- async updateSettings(options: IWorkbenchMountOptions) {- latestSettings = options;- const mounted = current;- if (!mounted) {- await pendingOpen;- return;+ async updateSettings(options: IWorkbenchMountOptions): Promise<void> {+ if (currentTarget !== undefined && options.device !== latestSettings?.device) {+ return this.open(currentTarget, options);}- await enqueueSettingsUpdate(mounted, options);+ latestSettings = options;+ const mounted = current;+ await (mounted ? enqueueSettingsUpdate(mounted, options) : pendingOpen);},dispose() {generation += 1;+ currentTarget = undefined;const mounted = current;current = undefined;mounted?.dispose();diff --git a/examples/src/sheets/mount.ts b/examples/src/sheets/mount.tsindex fdf75e75b3..960dedc843 100644--- a/examples/src/sheets/mount.ts+++ b/examples/src/sheets/mount.ts@@ -1,21 +1,28 @@+import type { Plugin, PluginCtor } from '@univerjs/core';import type { MountExample } from '../mount-example';import type { IWorkbenchMountOptions } from '../workbench-settings';import { LocaleType } from '@univerjs/core';-import { UniverSheetsConditionalFormattingPreset } from '@univerjs/preset-sheets-conditional-formatting';-import { UniverSheetsCorePreset } from '@univerjs/preset-sheets-core';-import { UniverSheetsDataValidationPreset } from '@univerjs/preset-sheets-data-validation';-import { UniverSheetsDrawingPreset } from '@univerjs/preset-sheets-drawing';-import { UniverSheetsFilterPreset } from '@univerjs/preset-sheets-filter';-import { UniverSheetsFindReplacePreset } from '@univerjs/preset-sheets-find-replace';-import { UniverSheetsHyperLinkPreset } from '@univerjs/preset-sheets-hyper-link';+import { UniverSheetsConditionalFormattingMobileUIPlugin, UniverSheetsConditionalFormattingPreset } from '@univerjs/preset-sheets-conditional-formatting';+import {+ UniverSheetsCorePreset,+ UniverSheetsFormulaMobileUIPlugin,+ UniverSheetsMobileUIPlugin,+ UniverSheetsNumfmtMobileUIPlugin,+} from '@univerjs/preset-sheets-core';+import { UniverSheetsDataValidationMobileUIPlugin, UniverSheetsDataValidationPreset } from '@univerjs/preset-sheets-data-validation';+import { UniverDrawingMobileUIPlugin, UniverSheetsDrawingMobileUIPlugin, UniverSheetsDrawingPreset } from '@univerjs/preset-sheets-drawing';+import { UniverSheetsFilterMobileUIPlugin, UniverSheetsFilterPreset } from '@univerjs/preset-sheets-filter';+import { UniverFindReplaceMobileUIPlugin, UniverSheetsFindReplaceMobileUIPlugin, UniverSheetsFindReplacePreset } from '@univerjs/preset-sheets-find-replace';+import { UniverSheetsHyperLinkMobileUIPlugin, UniverSheetsHyperLinkPreset } from '@univerjs/preset-sheets-hyper-link';import { UniverSheetsNotePreset } from '@univerjs/preset-sheets-note';-import { UniverSheetsSortPreset } from '@univerjs/preset-sheets-sort';-import { UniverSheetsTablePreset } from '@univerjs/preset-sheets-table';-import { UniverSheetsThreadCommentPreset } from '@univerjs/preset-sheets-thread-comment';-+import { UniverSheetsSortMobileUIPlugin, UniverSheetsSortPreset } from '@univerjs/preset-sheets-sort';+import { UniverSheetsTableMobileUIPlugin, UniverSheetsTablePreset } from '@univerjs/preset-sheets-table';+import { UniverSheetsThreadCommentMobileUIPlugin, UniverSheetsThreadCommentPreset, UniverThreadCommentMobileUIPlugin } from '@univerjs/preset-sheets-thread-comment';import { createUniver } from '@univerjs/presets';++import { UniverMobileUIPlugin, UniverUIPlugin } from '@univerjs/ui';import { loadSheetLocale } from 'virtual:univer-examples-sheet-locale';-import { applyWorkbenchUIChrome, createMountedUniver } from '../mount-example';+import { applyWorkbenchUIChrome, createMountedUniver, replacePresetPlugins } from '../mount-example';import { getEffectiveWorkbenchRegion } from '../workbench-settings';import { applyWorkbookZoom } from './apply-workbook-zoom';import { createSheetFixture } from './create-sheet-fixture';@@ -43,10 +50,42 @@ const UNIVER_LOCALES = {[LocaleType.PL_PL]: LocaleType.PL_PL,} satisfies Record<IWorkbenchMountOptions['locale'], LocaleType>;+const MOBILE_PLUGINS = new Map<string, PluginCtor<Plugin>>([+ UniverSheetsMobileUIPlugin,+ UniverSheetsFormulaMobileUIPlugin,+ UniverSheetsNumfmtMobileUIPlugin,+ UniverDrawingMobileUIPlugin,+ UniverSheetsDrawingMobileUIPlugin,+ UniverSheetsConditionalFormattingMobileUIPlugin,+ UniverSheetsFilterMobileUIPlugin,+ UniverSheetsHyperLinkMobileUIPlugin,+ UniverSheetsDataValidationMobileUIPlugin,+ UniverFindReplaceMobileUIPlugin,+ UniverSheetsFindReplaceMobileUIPlugin,+ UniverSheetsSortMobileUIPlugin,+ UniverSheetsTableMobileUIPlugin,+ UniverThreadCommentMobileUIPlugin,+ UniverSheetsThreadCommentMobileUIPlugin,+].map((plugin) => [plugin.pluginName, plugin]));+MOBILE_PLUGINS.set(UniverUIPlugin.pluginName, UniverMobileUIPlugin);+export const mount: MountExample = async (host, options) => {const { darkMode, direction, locale, ribbonType, theme, zoomRatio } = options;const univerLocale = UNIVER_LOCALES[locale];const localePack = await loadSheetLocale(locale);+ const presets = [+ UniverSheetsCorePreset({ container: host, ribbonType }),+ UniverSheetsDrawingPreset(),+ UniverSheetsConditionalFormattingPreset(),+ UniverSheetsFilterPreset(),+ UniverSheetsHyperLinkPreset(),+ UniverSheetsDataValidationPreset(),+ UniverSheetsFindReplacePreset(),+ UniverSheetsNotePreset(),+ UniverSheetsSortPreset(),+ UniverSheetsTablePreset(),+ UniverSheetsThreadCommentPreset(),+ ];const { univer, univerAPI } = createUniver({locale: univerLocale,region: UNIVER_LOCALES[getEffectiveWorkbenchRegion(options)],@@ -56,19 +95,7 @@ export const mount: MountExample = async (host, options) => {theme,darkMode,direction,- presets: [- UniverSheetsCorePreset({ container: host, ribbonType }),- UniverSheetsDrawingPreset(),- UniverSheetsConditionalFormattingPreset(),- UniverSheetsFilterPreset(),- UniverSheetsHyperLinkPreset(),- UniverSheetsDataValidationPreset(),- UniverSheetsFindReplacePreset(),- UniverSheetsNotePreset(),- UniverSheetsSortPreset(),- UniverSheetsTablePreset(),- UniverSheetsThreadCommentPreset(),- ],+ presets: options.device === 'mobile' ? replacePresetPlugins(presets, MOBILE_PLUGINS) : presets,});try {diff --git a/examples/src/workbench-settings-control.tsx b/examples/src/workbench-settings-control.tsxindex 07589368ef..a392fc1edd 100644--- a/examples/src/workbench-settings-control.tsx+++ b/examples/src/workbench-settings-control.tsx@@ -1,6 +1,7 @@import type { IDropdownMenuProps } from '@univerjs/design';import type {IWorkbenchSettings,+ WorkbenchDevice,WorkbenchDirection,WorkbenchLocale,WorkbenchRegion,@@ -13,6 +14,7 @@ import { Button, ConfigProvider, DropdownMenu, render, unmount } from '@univerjsimport { MoreDownIcon } from '@univerjs/icons';import {+ WORKBENCH_DEVICES,WORKBENCH_DIRECTIONS,WORKBENCH_LOCALE_META,WORKBENCH_LOCALES,@@ -23,6 +25,8 @@ import {WORKBENCH_ZOOM_RATIOS,} from './workbench-settings';+const DEVICE_LABELS = { desktop: 'Desktop', mobile: 'Mobile' } satisfies Record<WorkbenchDevice, string>;+const LOCALE_LABELS = {arSA: 'العربية',caES: 'Català',@@ -93,6 +97,8 @@ const UI_CHROME_LABELS = {interface IWorkbenchSettingsControlProps {settings: IWorkbenchSettings;+ supportsMobile: boolean;+ onDeviceChange: (device: WorkbenchDevice) => Promise<void>;onLocaleChange: (locale: WorkbenchLocale) => Promise<void>;onRegionChange: (region: WorkbenchRegion) => Promise<void>;onDirectionChange: (direction: WorkbenchDirection) => Promise<void>;@@ -107,7 +113,9 @@ interface IWorkbenchSettingsControlProps {function WorkbenchSettingsControl(props: IWorkbenchSettingsControlProps) {const {settings,+ supportsMobile,onDarkModeChange,+ onDeviceChange,onDirectionChange,onLocaleChange,onRegionChange,@@ -128,6 +136,22 @@ function WorkbenchSettingsControl(props: IWorkbenchSettingsControlProps) {}const items: IDropdownMenuProps['items'] = [+ {+ type: 'item',+ children: renderSettingLabel('Device', supportsMobile ? 'Restarts example' : 'Desktop only'),+ disabled: true,+ },+ {+ type: 'radio',+ value: supportsMobile ? settings.device : 'desktop',+ options: WORKBENCH_DEVICES.map((value) => ({+ value,+ label: DEVICE_LABELS[value],+ disabled: !supportsMobile,+ })),+ onSelect: (value) => onDeviceChange(value as WorkbenchDevice),+ },+ { type: 'separator' },{type: 'subItem',children: renderSettingLabel('Language', LOCALE_LABELS[settings.locale]),diff --git a/examples/src/workbench-settings.ts b/examples/src/workbench-settings.tsindex 27fe50d9ac..113d0c6a97 100644--- a/examples/src/workbench-settings.ts+++ b/examples/src/workbench-settings.ts@@ -32,6 +32,7 @@ export const WORKBENCH_LOCALES = ['arSA',] as const;export const WORKBENCH_DIRECTIONS = ['ltr', 'rtl'] as const;+export const WORKBENCH_DEVICES = ['desktop', 'mobile'] as const;export const WORKBENCH_THEMES = ['blue', 'green', 'orange', 'purple', 'red', 'yellow', 'dark-blue'] as const;export const WORKBENCH_RIBBON_TYPES = ['grid', 'classic', 'collapsed', 'simple'] as const satisfies readonly RibbonType[];export const WORKBENCH_REGIONS = ['auto', ...WORKBENCH_LOCALES] as const;@@ -41,6 +42,7 @@ export const WORKBENCH_SETTINGS_STORAGE_KEY = 'univer.examples.workbench.settingexport type WorkbenchLocale = (typeof WORKBENCH_LOCALES)[number];export type WorkbenchDirection = (typeof WORKBENCH_DIRECTIONS)[number];+export type WorkbenchDevice = (typeof WORKBENCH_DEVICES)[number];export type WorkbenchTheme = (typeof WORKBENCH_THEMES)[number];export type WorkbenchRibbonType = (typeof WORKBENCH_RIBBON_TYPES)[number];export type WorkbenchRegion = (typeof WORKBENCH_REGIONS)[number];@@ -48,6 +50,7 @@ export type WorkbenchUIChromeMode = (typeof WORKBENCH_UI_CHROME_MODES)[number];export type WorkbenchZoomRatio = (typeof WORKBENCH_ZOOM_RATIOS)[number];export interface IWorkbenchSettings {+ device: WorkbenchDevice;locale: WorkbenchLocale;region: WorkbenchRegion;direction: WorkbenchDirection;@@ -147,6 +150,7 @@ export function readWorkbenchSettings(storage: Pick<Storage, 'getItem'>): IWorkbconst locale = getAllowedValue(value.locale, WORKBENCH_LOCALES, defaults.locale);return {+ device: getAllowedValue(value.device, WORKBENCH_DEVICES, defaults.device),locale,region: getAllowedValue(value.region, WORKBENCH_REGIONS, defaults.region),direction: getAllowedValue(value.direction, WORKBENCH_DIRECTIONS, WORKBENCH_LOCALE_META[locale].direction),@@ -160,6 +164,7 @@ export function readWorkbenchSettings(storage: Pick<Storage, 'getItem'>): IWorkbexport function getDefaultWorkbenchSettings(): IWorkbenchSettings {return {+ device: 'desktop',locale: 'zhCN',region: 'auto',direction: 'ltr',diff --git a/packages/design/src/components/dropdown-menu/DropdownMenu.tsx b/packages/design/src/components/dropdown-menu/DropdownMenu.tsxindex e1d4719a95..eda217a1a9 100644--- a/packages/design/src/components/dropdown-menu/DropdownMenu.tsx+++ b/packages/design/src/components/dropdown-menu/DropdownMenu.tsx@@ -196,7 +196,7 @@ export function DropdownMenu(props: IDropdownMenuProps) {} else if (type === 'subItem') {return (<DropdownMenuSub key={index}>- <DropdownMenuSubTrigger>{item.children}</DropdownMenuSubTrigger>+ <DropdownMenuSubTrigger disabled={item.disabled}>{item.children}</DropdownMenuSubTrigger><DropdownMenuPortal><DropdownMenuSubContent sideOffset={12}>{item.options?.map((subItem, subIndex) => (diff --git a/packages/design/src/components/dropdown-menu/__tests__/index.spec.tsx b/packages/design/src/components/dropdown-menu/__tests__/DropdownMenu.spec.tsxsimilarity index 50%rename from packages/design/src/components/dropdown-menu/__tests__/index.spec.tsxrename to packages/design/src/components/dropdown-menu/__tests__/DropdownMenu.spec.tsxindex c254bbae04..837b82ae90 100644--- a/packages/design/src/components/dropdown-menu/__tests__/index.spec.tsx+++ b/packages/design/src/components/dropdown-menu/__tests__/DropdownMenu.spec.tsx@@ -17,7 +17,6 @@import { cleanup, fireEvent, render } from '@testing-library/react';import { afterEach, describe, expect, it, vi } from 'vitest';import { DropdownMenu } from '../DropdownMenu';-import { MobileDropdownMenu } from '../MobileDropdownMenu';import '@testing-library/jest-dom/vitest';afterEach(cleanup);@@ -28,99 +27,36 @@ describe('DropdownMenu', () => {{ type: 'item' as const, children: 'Item 1' },{ type: 'item' as const, children: 'Item 2', disabled: true, variant: 'destructive' as const },];- const { container } = render(+ const { getByRole } = render(<DropdownMenu open items={items}><button type="button">Trigger</button></DropdownMenu>);- const trigger = container.querySelector('button');- expect(trigger).toBeTruthy();- expect(trigger).toHaveAttribute('aria-haspopup', 'menu');- expect(trigger).toHaveAttribute('type', 'button');- expect(document.querySelector('[data-variant="destructive"]')).toHaveTextContent('Item 2');+ expect(getByRole('menuitem', { name: 'Item 1' })).toBeVisible();+ expect(getByRole('menuitem', { name: 'Item 2' })).toHaveAttribute('aria-disabled', 'true');});- it('should render with separator', () => {- const items = [- { type: 'item' as const, children: 'Item 1' },- { type: 'separator' as const },- { type: 'item' as const, children: 'Item 2' },- ];- const { container } = render(- <DropdownMenu items={items}>- <button type="button">Trigger</button>- </DropdownMenu>- );- const trigger = container.querySelector('button');- expect(trigger).toBeTruthy();- expect(trigger).toHaveAttribute('aria-haspopup', 'menu');- });-- it('should render with subItem', () => {- const items = [- {- type: 'subItem' as const,- children: 'More',- options: [- { type: 'item' as const, children: 'Sub 1' },- { type: 'item' as const, children: 'Sub 2' },- ],- },- ];- const { container } = render(- <DropdownMenu items={items}>+ it('keeps disabled submenus closed for pointer and keyboard input', () => {+ const { getByRole, queryByRole } = render(+ <DropdownMenu+ open+ items={[{+ type: 'subItem',+ children: 'More',+ disabled: true,+ options: [{ type: 'item', children: 'Sub item' }],+ }]}+ ><button type="button">Trigger</button></DropdownMenu>);- const trigger = container.querySelector('button');- expect(trigger).toBeTruthy();- expect(trigger).toHaveAttribute('aria-haspopup', 'menu');- });+ const submenu = getByRole('menuitem', { name: 'More' });- it('should render with radio group', () => {- const items = [- {- type: 'radio' as const,- value: 'a',- options: [- { label: 'A', value: 'a' },- { label: 'B', value: 'b' },- ],- },- ];- const { container } = render(- <DropdownMenu items={items}>- <button type="button">Trigger</button>- </DropdownMenu>- );- const trigger = container.querySelector('button');- expect(trigger).toBeTruthy();- expect(trigger).toHaveAttribute('aria-haspopup', 'menu');- });+ fireEvent.click(submenu);+ fireEvent.keyDown(submenu, { key: 'ArrowRight' });- it('should render with checkbox', () => {- const items = [- {- type: 'checkbox' as const,- value: 'c1',- label: 'Check 1',- checked: true,- },- {- type: 'checkbox' as const,- value: 'c2',- label: 'Check 2',- checked: false,- },- ];- const { container } = render(- <DropdownMenu items={items}>- <button type="button">Trigger</button>- </DropdownMenu>- );- const trigger = container.querySelector('button');- expect(trigger).toBeTruthy();- expect(trigger).toHaveAttribute('aria-haspopup', 'menu');+ expect(submenu).toHaveAttribute('aria-disabled', 'true');+ expect(queryByRole('menuitem', { name: 'Sub item' })).not.toBeInTheDocument();});it('should render custom content without wrapping it as a menu item', () => {@@ -190,22 +126,4 @@ describe('DropdownMenu', () => {)).toThrow('[DropdownMenu]: `value` is required');});-- it('should render full-width actionable rows from MobileDropdownMenu', () => {- const onSelect = vi.fn();- const { getByText } = render(- <MobileDropdownMenu- open- items={[{ type: 'item', children: 'Mobile item', onSelect }]}- onOpenChange={() => {}}- >- <button type="button">Trigger</button>- </MobileDropdownMenu>- );-- const item = getByText('Mobile item');- expect(item).toHaveClass('univer-w-full');- fireEvent.click(item);- expect(onSelect).toHaveBeenCalledTimes(1);- });});diff --git a/packages/design/src/components/dropdown-menu/__tests__/MobileDropdownMenu.spec.tsx b/packages/design/src/components/dropdown-menu/__tests__/MobileDropdownMenu.spec.tsxnew file mode 100644index 0000000000..3efb7bb841--- /dev/null+++ b/packages/design/src/components/dropdown-menu/__tests__/MobileDropdownMenu.spec.tsx@@ -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 { cleanup, fireEvent, render } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { MobileDropdownMenu } from '../MobileDropdownMenu';++afterEach(cleanup);++describe('MobileDropdownMenu', () => {+ it('invokes the selected menu action once', () => {+ const onSelect = vi.fn();+ const { getByText } = render(+ <MobileDropdownMenu+ open+ items={[{ type: 'item', children: 'Mobile item', onSelect }]}+ onOpenChange={() => {}}+ >+ <button type="button">Trigger</button>+ </MobileDropdownMenu>+ );++ fireEvent.click(getByText('Mobile item'));++ expect(onSelect).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/design/src/components/dropdown-menu/__tests__/primitive.spec.tsx b/packages/design/src/components/dropdown-menu/__tests__/primitive.spec.tsxdeleted file mode 100644index bd5a4eea7b..0000000000--- a/packages/design/src/components/dropdown-menu/__tests__/primitive.spec.tsx+++ /dev/null@@ -1,69 +0,0 @@-/**- * 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 { render } from '@testing-library/react';-import { describe, expect, it } from 'vitest';-import {- DropdownMenuCheckboxItem,- DropdownMenuContent,- DropdownMenuGroup,- DropdownMenuItem,- DropdownMenuLabel,- DropdownMenuPrimitive,- DropdownMenuRadioGroup,- DropdownMenuRadioItem,- DropdownMenuSeparator,- DropdownMenuShortcut,- DropdownMenuSub,- DropdownMenuSubContent,- DropdownMenuSubTrigger,- DropdownMenuTrigger,-} from '../DropdownMenuPrimitive';-import '@testing-library/jest-dom/vitest';--describe('DropdownMenuPrimitive', () => {- it('should render primitive wrappers and variants', () => {- const { container } = render(- <DropdownMenuPrimitive open>- <DropdownMenuTrigger>Trigger</DropdownMenuTrigger>- <DropdownMenuContent>- <DropdownMenuGroup>- <DropdownMenuLabel inset>Label</DropdownMenuLabel>- <DropdownMenuItem inset variant="destructive">Item</DropdownMenuItem>- <DropdownMenuCheckboxItem checked hideIndicator>- Check- </DropdownMenuCheckboxItem>- <DropdownMenuRadioGroup value="a">- <DropdownMenuRadioItem value="a" hideIndicator>- Radio A- </DropdownMenuRadioItem>- </DropdownMenuRadioGroup>- <DropdownMenuSeparator />- <DropdownMenuShortcut>Cmd+K</DropdownMenuShortcut>- <DropdownMenuSub>- <DropdownMenuSubTrigger inset>More</DropdownMenuSubTrigger>- <DropdownMenuSubContent>- <DropdownMenuItem>Sub Item</DropdownMenuItem>- </DropdownMenuSubContent>- </DropdownMenuSub>- </DropdownMenuGroup>- </DropdownMenuContent>- </DropdownMenuPrimitive>- );-- expect(container).toBeInTheDocument();- });-});diff --git a/packages/sheets-data-validation/src/services/__tests__/dv-validator.service.spec.ts b/packages/sheets-data-validation/src/services/__tests__/dv-validator.service.spec.tsindex 98f8d82b6a..0e331bc9d7 100644--- a/packages/sheets-data-validation/src/services/__tests__/dv-validator.service.spec.ts+++ b/packages/sheets-data-validation/src/services/__tests__/dv-validator.service.spec.ts@@ -23,7 +23,7 @@ import type {} from '@univerjs/core';import type { ISheetLocation } from '@univerjs/sheets';import { DataValidationStatus, Injector, IUniverInstanceService, LifecycleService, LifecycleStages, ObjectMatrix } from '@univerjs/core';-import { BehaviorSubject, Subject } from 'rxjs';+import { BehaviorSubject, defer, Subject } from 'rxjs';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { createFacadeTestBed } from '../../facade/__tests__/create-test-bed';import { SheetDataValidationModel } from '../../models/sheet-data-validation-model';@@ -38,12 +38,6 @@ function createService() {const dirtyRanges$ = new Subject<{ unitId: string; subUnitId: string; ranges: IRange[] }>();const lifecycle$ = new BehaviorSubject(LifecycleStages.Rendered);let lifecycleSubscribeCount = 0;- const lifecycleSubject = lifecycle$ as any;- const originalSubscribe = lifecycleSubject._subscribe.bind(lifecycleSubject);- lifecycleSubject._subscribe = (...args: unknown[]) => {- lifecycleSubscribeCount++;- return originalSubscribe(...args);- };const worksheet = {getSheetId: () => 'sheet-1',getMergedCell: vi.fn(() => null),@@ -81,7 +75,10 @@ function createService() {getCurrentUnitOfType: vi.fn(() => workbook),} as unknown as IUniverInstanceService;const lifecycleService = {- lifecycle$,+ lifecycle$: defer(() => {+ lifecycleSubscribeCount++;+ return lifecycle$;+ }),stage: LifecycleStages.Rendered,} as unknown as LifecycleService;@@ -103,7 +100,7 @@ function createService() {univerInstanceService,lifecycleService,getLifecycleSubscribeCount: () => lifecycleSubscribeCount,- service: injector.get(SheetsDataValidationValidatorService),+ injector,};}@@ -124,10 +121,10 @@ describe('SheetsDataValidationValidatorService', () => {beforeEach(() => {vi.useFakeTimers();- vi.stubGlobal('requestIdleCallback', (callback: IdleRequestCallback) => {+ vi.stubGlobal('requestIdleCallback', vi.fn((callback: IdleRequestCallback) => setTimeout(() => {callback({ didTimeout: false, timeRemaining: () => 1 } as IdleDeadline);- return 1;- });+ }, 50)));+ vi.stubGlobal('cancelIdleCallback', clearTimeout);});afterEach(() => {@@ -136,7 +133,8 @@ describe('SheetsDataValidationValidatorService', () => {});it('does not recursively reopen dirty range buffer when created after render', () => {- const { service, getLifecycleSubscribeCount } = createService();+ const { injector, getLifecycleSubscribeCount } = createService();+ const service = injector.get(SheetsDataValidationValidatorService);expect(getLifecycleSubscribeCount()).toBe(1);@@ -144,7 +142,8 @@ describe('SheetsDataValidationValidatorService', () => {});it('validates single cells, merged cells, ranges, worksheets, and workbooks', async () => {- const { service, worksheet, model, cacheService } = createService();+ const { injector, worksheet, model, cacheService } = createService();+ const service = injector.get(SheetsDataValidationValidatorService);await expect(service.validatorCell('missing', 'sheet-1', 0, 0)).rejects.toThrow('cannot find current workbook');await expect(service.validatorCell('unit-1', 'missing', 0, 0)).rejects.toThrow('cannot find current worksheet');@@ -168,7 +167,8 @@ describe('SheetsDataValidationValidatorService', () => {});it('returns matched data validations and reacts to dirty ranges after render', async () => {- const { service, dirtyRanges$, lifecycle$, model } = createService();+ const { injector, dirtyRanges$, lifecycle$, model } = createService();+ const service = injector.get(SheetsDataValidationValidatorService);const validatorRangesSpy = vi.spyOn(service, 'validatorRanges').mockResolvedValue([]);expect(service.getDataValidations('unit-1', 'sheet-1', [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }])).toEqual([@@ -193,7 +193,8 @@ describe('SheetsDataValidationValidatorService', () => {});it('limits validation and rule lookup to the worksheet bounds', async () => {- const { service, model } = createService();+ const { injector, model } = createService();+ const service = injector.get(SheetsDataValidationValidatorService);const oversizedRange = { startRow: 0, endRow: 1048575, startColumn: 0, endColumn: 16383 };const getValue = vi.fn(() => undefined);model.getRules = vi.fn(() => [createRule('rule-1', [oversizedRange])]);@@ -215,4 +216,24 @@ describe('SheetsDataValidationValidatorService', () => {await expect(service.validatorRanges('unit-1', 'sheet-1', [{ startRow: 20, endRow: 30, startColumn: 20, endColumn: 30 }])).resolves.toEqual([]);service.dispose();});++ it('cancels queued validation before the workbook is disposed', async () => {+ const { injector, dirtyRanges$, univerInstanceService, model } = createService();+ const service = injector.get(SheetsDataValidationValidatorService);+ vi.mocked(univerInstanceService.getCurrentUnitOfType).mockReturnValue(null);+ dirtyRanges$.next({+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }],+ });+ await vi.advanceTimersByTimeAsync(20);+ expect(requestIdleCallback).toHaveBeenCalledOnce();++ service.dispose();+ vi.mocked(univerInstanceService.getUnit).mockClear().mockReturnValue(null);+ await vi.runAllTimersAsync();++ expect(univerInstanceService.getUnit).not.toHaveBeenCalled();+ expect(model.validator).not.toHaveBeenCalled();+ });});diff --git a/packages/sheets-data-validation/src/services/dv-validator.service.ts b/packages/sheets-data-validation/src/services/dv-validator.service.tsindex f228b6ef88..71c643e8c7 100644--- a/packages/sheets-data-validation/src/services/dv-validator.service.ts+++ b/packages/sheets-data-validation/src/services/dv-validator.service.ts@@ -61,10 +61,13 @@ export class SheetsDataValidationValidatorService extends Disposable {Object.entries(map).forEach(([unitId, subUnitMap]) => {Object.entries(subUnitMap).forEach(([subUnitId, ranges]) => {if (workbook?.getUnitId() === unitId && worksheet?.getSheetId() === subUnitId) {- this.validatorRanges(unitId, subUnitId, ranges);+ this.validatorRanges(unitId, subUnitId, ranges).catch(console.error);} else {- requestIdleCallback(() => {- this.validatorRanges(unitId, subUnitId, ranges);+ let idleCallback: number;+ const disposeIdleCallback = this.disposeWithMe(() => cancelIdleCallback(idleCallback));+ idleCallback = requestIdleCallback(() => {+ disposeIdleCallback.dispose();+ this.validatorRanges(unitId, subUnitId, ranges).catch(console.error);});}});