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.

fix(ui): measure contextual ribbon before paint (#7665)

wpxp1234564dd9e180b257
diff --git a/packages/design/src/components/input/Input.tsx b/packages/design/src/components/input/Input.tsx
index f08998a528..c5f5fe4c4f 100644
--- a/packages/design/src/components/input/Input.tsx
+++ b/packages/design/src/components/input/Input.tsx
@@ -49,7 +49,7 @@ export const inputVariants = cva(
}
);
-export interface IInputProps extends Pick<InputProps, 'onFocus' | 'onBlur'>,
+export interface IInputProps extends Pick<InputProps, 'dir' | 'onFocus' | 'onBlur'>,
VariantProps<typeof inputVariants> {
autoFocus?: boolean;
className?: string;
diff --git a/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts b/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts
index 7d3752548e..c4d6afaf60 100644
--- a/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts
@@ -480,7 +480,7 @@ describe('doc skeleton', () => {
const univer = new Univer();
const content = scenario === 'header' || scenario === 'footer'
? 'Este documento contiene información sobre la configuración y la administración de los servicios.'
- : `${'A continued paragraph crosses several physical pages. '.repeat(100)}Hello world ${'Further text keeps the paragraph flowing. '.repeat(200)}`;
+ : `${'A continued paragraph crosses several physical pages. '.repeat(50)}Hello world ${'Further text keeps the paragraph flowing. '.repeat(100)}`;
const snapshot: Partial<IDocumentData> = {
id: 'hyphen-readiness',
body: {
diff --git a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit.tsx b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit.tsx
index 8ef3e2968b..0d12015110 100644
--- a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit.tsx
@@ -472,6 +472,7 @@ export const CellLinkEdit = () => {
error={showError ? !payload ? localeService.t<LocaleKey>('sheets-hyper-link-ui.form.inputError') : !isLegalLink(payload) ? localeService.t<LocaleKey>('sheets-hyper-link-ui.form.linkError') : '' : ''}
>
<Input
+ dir="ltr"
value={payload}
onChange={(newLink) => {
setPayload(newLink);
diff --git a/packages/sheets-hyper-link-ui/src/views/MobileCellLinkEdit.tsx b/packages/sheets-hyper-link-ui/src/views/MobileCellLinkEdit.tsx
index 3ede83e0c8..f97aade7a5 100644
--- a/packages/sheets-hyper-link-ui/src/views/MobileCellLinkEdit.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/MobileCellLinkEdit.tsx
@@ -469,6 +469,7 @@ export const MobileCellLinkEdit = () => {
error={showError ? !payload ? localeService.t<LocaleKey>('sheets-hyper-link-ui.form.inputError') : !isLegalLink(payload) ? localeService.t<LocaleKey>('sheets-hyper-link-ui.form.linkError') : '' : ''}
>
<Input
+ dir="ltr"
value={payload}
onChange={(newLink) => {
setPayload(newLink);
diff --git a/packages/sheets-hyper-link-ui/src/views/__tests__/CellLinkPopup.spec.tsx b/packages/sheets-hyper-link-ui/src/views/__tests__/CellLinkPopup.spec.tsx
index ede0486aa4..1ce6bc9f8c 100644
--- a/packages/sheets-hyper-link-ui/src/views/__tests__/CellLinkPopup.spec.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/__tests__/CellLinkPopup.spec.tsx
@@ -64,6 +64,7 @@ import { SheetsHyperLinkSidePanelService } from '../../services/side-panel.servi
import { HyperLinkEditSourceType } from '../../types/enums/edit-source';
import { CellLinkEdit } from '../CellLinkEdit';
import { CellLinkPopupPure } from '../CellLinkPopup';
+import { MobileCellLinkEdit } from '../MobileCellLinkEdit';
import { MobileCellLinkPopupPure } from '../MobileCellLinkPopup';
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -485,6 +486,40 @@ describe('CellLinkEdit', () => {
currentTestBed = undefined;
});
+ it('inherits the page direction for labels and uses left-to-right direction for URLs', () => {
+ currentTestBed = createPopupTestBed();
+ container = document.createElement('div');
+ container.dir = 'rtl';
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const popupService = currentTestBed.injector.get(SheetsHyperLinkPopupService);
+
+ act(() => {
+ popupService.startAddEditing({
+ unitId: UNIT_ID,
+ subUnitId: SUB_UNIT_ID,
+ row: 1,
+ col: 0,
+ type: HyperLinkEditSourceType.VIEWING,
+ });
+ });
+
+ for (const LinkEdit of [CellLinkEdit, MobileCellLinkEdit]) {
+ act(() => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <LinkEdit />
+ </RediContext.Provider>
+ );
+ });
+
+ const inputs = Array.from(container.querySelectorAll('input'));
+ expect(inputs).toHaveLength(2);
+ expect(inputs[0].hasAttribute('dir')).toBe(false);
+ expect(inputs[1].dir).toBe('ltr');
+ }
+ });
+
it('adds a URL hyperlink to the current cell text and closes the popup', async () => {
currentTestBed = createPopupTestBed();
container = document.createElement('div');
diff --git a/packages/sheets-thread-comment-ui/src/menu/__tests__/menu.spec.ts b/packages/sheets-thread-comment-ui/src/menu/__tests__/menu.spec.ts
new file mode 100644
index 0000000000..fda4332713
--- /dev/null
+++ b/packages/sheets-thread-comment-ui/src/menu/__tests__/menu.spec.ts
@@ -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 {
+ FOCUSING_COMMON_DRAWINGS,
+ IContextService,
+ Injector,
+ IPermissionService,
+ IUniverInstanceService,
+ UserManagerService,
+} from '@univerjs/core';
+import { RangeProtectionRuleModel, SheetsSelectionsService, WorksheetProtectionRuleModel } from '@univerjs/sheets';
+import { BehaviorSubject, of, Subject } from 'rxjs';
+import { describe, expect, it } from 'vitest';
+import { drawingCommentMenuFactory } from '../menu';
+
+describe('drawingCommentMenuFactory', () => {
+ it('stays enabled for a focused drawing until comment permission is denied', () => {
+ const permissionValues$ = new BehaviorSubject([{ value: true }, { value: true }]);
+ const workbook = {
+ getUnitId: () => 'unit-1',
+ activeSheet$: of({ getSheetId: () => 'sheet-1' }),
+ };
+ const injector = new Injector([
+ [IContextService, {
+ useValue: {
+ subscribeContextValue$: (key: string) => of(key === FOCUSING_COMMON_DRAWINGS),
+ },
+ }],
+ [IPermissionService, {
+ useValue: {
+ permissionPointUpdate$: new Subject(),
+ composePermission$: () => permissionValues$,
+ },
+ }],
+ [IUniverInstanceService, {
+ useValue: {
+ focused$: new Subject(),
+ getCurrentTypeOfUnit$: () => of(workbook),
+ },
+ }],
+ [RangeProtectionRuleModel, { useValue: { getSubunitRuleList: () => [] } }],
+ [SheetsSelectionsService, {
+ useValue: {
+ selectionChanged$: new Subject(),
+ getWorkbookSelections: () => ({ getSelectionsOfWorksheet: () => [] }),
+ },
+ }],
+ [UserManagerService, { useValue: { currentUser$: of(null) } }],
+ [WorksheetProtectionRuleModel, { useValue: { getRule: () => null } }],
+ ]);
+ const disabledValues: boolean[] = [];
+ const subscription = drawingCommentMenuFactory(injector).disabled$.subscribe((disabled) => {
+ disabledValues.push(disabled);
+ });
+
+ expect(disabledValues).toEqual([false]);
+
+ permissionValues$.next([{ value: false }, { value: true }]);
+
+ expect(disabledValues).toEqual([false, true]);
+ subscription.unsubscribe();
+ injector.dispose();
+ });
+});
diff --git a/packages/sheets-thread-comment-ui/src/menu/menu.ts b/packages/sheets-thread-comment-ui/src/menu/menu.ts
index bf2525886d..6f3369c605 100644
--- a/packages/sheets-thread-comment-ui/src/menu/menu.ts
+++ b/packages/sheets-thread-comment-ui/src/menu/menu.ts
@@ -16,12 +16,28 @@
import type { IAccessor } from '@univerjs/core';
import type { IShortcutItem } from '@univerjs/ui';
-import { UniverInstanceType } from '@univerjs/core';
+import { IPermissionService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { RangeProtectionPermissionViewPoint, WorkbookCommentPermission, WorksheetViewPermission } from '@univerjs/sheets';
-import { getCurrentRangeDisable$, whenSheetEditorFocused } from '@univerjs/sheets-ui';
+import { deriveStateFromActiveSheet$, getCurrentRangeDisable$, whenSheetEditorFocused } from '@univerjs/sheets-ui';
import { getMenuHiddenObservable, KeyCode, MenuItemType, MetaKeys } from '@univerjs/ui';
+import { map } from 'rxjs';
import { AddSheetDrawingCommentOperation, ShowAddSheetCommentModalOperation, ToggleSheetCommentPanelOperation } from '../commands/operations/comment.operation';
+function getDrawingCommentDisable$(accessor: IAccessor) {
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+ const permissionService = accessor.get(IPermissionService);
+
+ return deriveStateFromActiveSheet$(univerInstanceService, true, ({ workbook, worksheet }) => {
+ const unitId = workbook.getUnitId();
+ const subUnitId = worksheet.getSheetId();
+
+ return permissionService.composePermission$([
+ new WorkbookCommentPermission(unitId).id,
+ new WorksheetViewPermission(unitId, subUnitId).id,
+ ]).pipe(map((permissions) => permissions.some((permission) => permission.value === false)));
+ });
+}
+
export const drawingCommentMenuFactory = (accessor: IAccessor) => ({
id: AddSheetDrawingCommentOperation.id,
type: MenuItemType.BUTTON,
@@ -29,10 +45,7 @@ export const drawingCommentMenuFactory = (accessor: IAccessor) => ({
title: 'sheets-thread-comment-ui.menu.addComment',
tooltip: 'sheets-thread-comment-ui.menu.addComment',
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET),
- disabled$: getCurrentRangeDisable$(accessor, {
- workbookTypes: [WorkbookCommentPermission],
- worksheetTypes: [WorksheetViewPermission],
- }),
+ disabled$: getDrawingCommentDisable$(accessor),
});
export const threadCommentMenuFactory = (accessor: IAccessor) => {
diff --git a/packages/ui/src/views/components/ribbon/Ribbon.tsx b/packages/ui/src/views/components/ribbon/Ribbon.tsx
index c1ef8a1a3f..ae501d642c 100644
--- a/packages/ui/src/views/components/ribbon/Ribbon.tsx
+++ b/packages/ui/src/views/components/ribbon/Ribbon.tsx
@@ -19,9 +19,8 @@ import type { RibbonType } from '../../../controllers/ui/ui.controller';
import type { IMenuSchema } from '../../../services/menu/menu-manager.service';
import { LocaleService, throttle } from '@univerjs/core';
import { borderBottomClassName, clsx, ConfigContext, ConfigProvider, divideXClassName, Dropdown } from '@univerjs/design';
-
import { MoreVerticalIcon } from '@univerjs/icons';
-import { Fragment, useCallback, useContext, useEffect, useMemo, useRef } from 'react';
+import { Fragment, useCallback, useContext, useLayoutEffect, useMemo, useRef } from 'react';
import { RibbonPosition } from '../../../services/menu/types';
import { IRibbonOverrideService } from '../../../services/ribbon/ribbon-override.service';
import { IRibbonService } from '../../../services/ribbon/ribbon.service';
@@ -53,6 +52,7 @@ export function Ribbon(props: IRibbonProps) {
const ribbonService = ribbonOverride?.ribbonService ?? defaultRibbonService;
const containerRef = useRef<HTMLDivElement>(null!);
+ const availableWidthRef = useRef(0);
const toolbarItemsRef = useRef<Record<string, {
el: HTMLElement;
key: string;
@@ -123,7 +123,7 @@ export function Ribbon(props: IRibbonProps) {
};
}, [collapsedIds, ribbon, effectiveActivatedTab]);
- useEffect(() => {
+ useLayoutEffect(() => {
if (hideToolbar || ribbonType === 'grid') {
toolbarItemsRef.current = {};
ribbonService.setCollapsedIds([]);
@@ -135,45 +135,18 @@ export function Ribbon(props: IRibbonProps) {
return;
}
- let timer: number | null = null;
const observer = new ResizeObserver(throttle((entries) => {
for (const entry of entries) {
+ availableWidthRef.current = entry.contentRect.width;
ribbonService.setFakeToolbarVisible(true);
-
- timer = requestAnimationFrame(() => {
- const { width: avaliableWidth } = entry.contentRect;
- const toolbarItems = Object.values(toolbarItemsRef.current);
- const sortedToolbarItems = toolbarItems.sort((a, b) => {
- return a.order - b.order || a.groupOrder - b.groupOrder || a.itemOrder - b.itemOrder;
- });
-
- const newCollapsedIds: string[] = [];
- let totalWidth = 32;
- const allGroups = ribbon.find((group) => group.key === effectiveActivatedTab)?.children ?? [];
-
- const gapWidth = (allGroups.length - 1) * 8;
- totalWidth += gapWidth;
-
- for (const { el, key } of sortedToolbarItems) {
- const { width } = el.getBoundingClientRect();
- totalWidth += width + 8;
-
- if (totalWidth > avaliableWidth) {
- newCollapsedIds.push(key);
- }
- }
-
- ribbonService.setCollapsedIds(newCollapsedIds);
-
- ribbonService.setFakeToolbarVisible(false);
- });
}
}, 10));
observer.observe(containerRef.current);
+ availableWidthRef.current = containerRef.current.getBoundingClientRect().width;
+ ribbonService.setFakeToolbarVisible(true);
return () => {
- timer && cancelAnimationFrame(timer);
observer.disconnect();
};
}, [hideToolbar, ribbon, effectiveActivatedTab, ribbonService, ribbonType]);
@@ -212,6 +185,8 @@ export function Ribbon(props: IRibbonProps) {
groupOrder: groupItem.order,
itemOrder: child.order,
};
+ } else {
+ delete toolbarItemsRef.current[child.key];
}
}}
/>
@@ -224,6 +199,29 @@ export function Ribbon(props: IRibbonProps) {
);
}, [activeGroup.allGroups, fakeToolbarVisible]);
+ useLayoutEffect(() => {
+ if (!fakeToolbarVisible || hideToolbar || ribbonType === 'grid') {
+ return;
+ }
+
+ const sortedToolbarItems = Object.values(toolbarItemsRef.current).sort((a, b) => {
+ return a.order - b.order || a.groupOrder - b.groupOrder || a.itemOrder - b.itemOrder;
+ });
+ const newCollapsedIds: string[] = [];
+ const allGroups = ribbon.find((group) => group.key === effectiveActivatedTab)?.children ?? [];
+ let totalWidth = 32 + (allGroups.length - 1) * 8;
+
+ for (const { el, key } of sortedToolbarItems) {
+ totalWidth += el.getBoundingClientRect().width + 8;
+ if (totalWidth > availableWidthRef.current) {
+ newCollapsedIds.push(key);
+ }
+ }
+
+ ribbonService.setCollapsedIds(newCollapsedIds);
+ ribbonService.setFakeToolbarVisible(false);
+ }, [effectiveActivatedTab, fakeToolbarVisible, hideToolbar, ribbon, ribbonService, ribbonType]);
+
const embedRibbonOverrideAttributes = ribbonOverride
? {
'data-embed-ribbon-override': 'true',
diff --git a/packages/ui/src/views/components/ribbon/__tests__/Ribbon.spec.tsx b/packages/ui/src/views/components/ribbon/__tests__/Ribbon.spec.tsx
index bb43239d3c..6300eaa317 100644
--- a/packages/ui/src/views/components/ribbon/__tests__/Ribbon.spec.tsx
+++ b/packages/ui/src/views/components/ribbon/__tests__/Ribbon.spec.tsx
@@ -20,16 +20,19 @@
import type { ComponentType } from 'react';
import type { IMenuSchema } from '../../../../services/menu/menu-manager.service';
-import { cleanup, render } from '@testing-library/react';
-import { Injector, LocaleService } from '@univerjs/core';
+import { act, cleanup, render } from '@testing-library/react';
+import { ICommandService, Injector, LocaleService } from '@univerjs/core';
import { connectInjector } from '@wendellhu/redi/react-bindings';
-import { of } from 'rxjs';
-
+import { BehaviorSubject, of, Subject } from 'rxjs';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { ComponentManager } from '../../../../common/component-manager';
+import { IconManager } from '../../../../common/icon-manager';
+import { ILayoutService } from '../../../../services/layout/layout.service';
+import { MenuItemType } from '../../../../services/menu/menu';
import { RibbonPosition } from '../../../../services/menu/types';
import { IRibbonOverrideService } from '../../../../services/ribbon/ribbon-override.service';
import { IRibbonService } from '../../../../services/ribbon/ribbon.service';
+import { IShortcutService } from '../../../../services/shortcut/shortcut.service';
import { Ribbon } from '../Ribbon';
describe('Ribbon override chrome', () => {
@@ -48,6 +51,7 @@ describe('Ribbon override chrome', () => {
afterEach(() => {
cleanup();
+ vi.restoreAllMocks();
vi.unstubAllGlobals();
});
@@ -110,6 +114,107 @@ describe('Ribbon override chrome', () => {
expect(getByRole('toolbar', { name: RibbonPosition.START })).toBeTruthy();
});
+
+ it('collapses newly activated tab items before paint', () => {
+ const resizeCallbacks: ResizeObserverCallback[] = [];
+ vi.stubGlobal('ResizeObserver', class {
+ constructor(callback: ResizeObserverCallback) {
+ resizeCallbacks.push(callback);
+ }
+
+ observe() {}
+ disconnect() {}
+ });
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) {
+ if (this.dataset.uComp === 'ribbon-toolbar') {
+ return { width: 120 } as DOMRect;
+ }
+
+ const fakeToolbar = this.closest('div[aria-hidden="true"]');
+ const width = fakeToolbar?.classList.contains('univer-hidden') ? 0 : 50;
+
+ return { width } as DOMRect;
+ });
+
+ const ribbon$ = new BehaviorSubject<IMenuSchema[]>([
+ {
+ key: RibbonPosition.START,
+ order: 0,
+ children: [{
+ key: 'start-group',
+ order: 0,
+ children: [{
+ key: 'start-item',
+ order: 0,
+ item: { id: 'start-item', type: MenuItemType.BUTTON, title: 'Start item' },
+ }],
+ }],
+ },
+ {
+ key: 'shape-format',
+ order: 1,
+ children: [{
+ key: 'shape-group',
+ order: 1,
+ children: [{
+ key: 'shape-item',
+ order: 0,
+ item: { id: 'shape-item', type: MenuItemType.BUTTON, title: 'Shape item' },
+ }, {
+ key: 'shape-item-2',
+ order: 1,
+ item: { id: 'shape-item-2', type: MenuItemType.BUTTON, title: 'Shape item 2' },
+ }],
+ }],
+ },
+ ]);
+ const activatedTab$ = new BehaviorSubject<string>(RibbonPosition.START);
+ const collapsedIds$ = new BehaviorSubject<string[]>([]);
+ const fakeToolbarVisible$ = new BehaviorSubject(false);
+ const ribbonService = {
+ ribbon$,
+ activatedTab$,
+ collapsedIds$,
+ fakeToolbarVisible$,
+ setActivatedTab: (tab: string) => activatedTab$.next(tab),
+ showContextualTab: () => {},
+ hideContextualTab: () => {},
+ hideAllContextualTabs: () => {},
+ setCollapsedIds: (ids: string[]) => collapsedIds$.next(ids),
+ setFakeToolbarVisible: (visible: boolean) => fakeToolbarVisible$.next(visible),
+ };
+ const injector = new Injector([
+ [ComponentManager],
+ [IconManager, { useValue: { get: () => null } }],
+ [ICommandService, { useValue: { executeCommand: () => {} } }],
+ [ILayoutService, { useValue: { focus: () => {} } }],
+ [LocaleService, { useValue: { t: (key: string) => key } }],
+ [IRibbonService, { useValue: ribbonService }],
+ [IRibbonOverrideService, {
+ useValue: {
+ override$: of(null),
+ getOverride: () => null,
+ activate: () => {},
+ clear: () => {},
+ },
+ }],
+ [IShortcutService, {
+ useValue: {
+ shortcutChanged$: new Subject<void>(),
+ getShortcutDisplayOfCommand: () => null,
+ },
+ }],
+ ]);
+ const ConnectedRibbon = connectInjector(Ribbon, injector) as ComponentType<{ ribbonType: 'classic' }>;
+ render(<ConnectedRibbon ribbonType="classic" />);
+
+ act(() => resizeCallbacks[0]([{ contentRect: { width: 120 } } as ResizeObserverEntry], {} as ResizeObserver));
+ expect(collapsedIds$.getValue()).toEqual([]);
+
+ act(() => activatedTab$.next('shape-format'));
+
+ expect(collapsedIds$.getValue()).toEqual(['shape-item-2']);
+ });
});
function createEmptyRibbonService() {