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(mobile): stabilize keyboard inset positioning (#7646)

白熱44b664f51e29
diff --git a/packages/design/src/components/segmented/Segmented.tsx b/packages/design/src/components/segmented/Segmented.tsx
index 64bbaf2fee..83357cf7e5 100644
--- a/packages/design/src/components/segmented/Segmented.tsx
+++ b/packages/design/src/components/segmented/Segmented.tsx
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import type { CSSProperties, ReactNode } from 'react';
-import { useContext, useEffect, useRef, useState } from 'react';
+import type { ReactNode } from 'react';
+import { useContext, useLayoutEffect, useRef, useState } from 'react';
import { clsx } from '../../helper/clsx';
import { ConfigContext } from '../config-provider/ConfigProvider';
@@ -43,61 +43,26 @@ export function Segmented<T extends ItemValue = ItemValue>({
className = '',
}: ISegmentedProps<T>) {
const { direction } = useContext(ConfigContext);
- const [selectedItem, setSelectedItem] = useState<T>(
- value !== undefined ? value : (defaultValue || items[0].value)
- );
- const [slideStyle, setSlideStyle] = useState({});
- const itemRefs = useRef<Map<T, HTMLButtonElement>>(new Map());
+ const [internalValue, setInternalValue] = useState<T>(defaultValue ?? items[0].value);
+ const selectedItem = value ?? internalValue;
+ const itemsRef = useRef<Map<T, HTMLButtonElement>>(new Map());
const containerRef = useRef<HTMLDivElement>(null);
+ const sliderRef = useRef<HTMLDivElement>(null);
- // Update internal state when controlled value changes
- useEffect(() => {
- if (value !== undefined && value !== selectedItem) {
- setSelectedItem(value);
- }
- }, [value]);
-
- const updateSliderPosition = (newValue: T, oldValue?: T) => {
- const newItemElement = itemRefs.current.get(newValue);
- const oldItemElement = oldValue ? itemRefs.current.get(oldValue) : null;
-
- if (newItemElement && containerRef.current) {
+ useLayoutEffect(() => {
+ const selectedElement = itemsRef.current.get(selectedItem);
+ const slider = sliderRef.current;
+ if (selectedElement && containerRef.current && slider) {
const containerRect = containerRef.current.getBoundingClientRect();
- const newRect = newItemElement.getBoundingClientRect();
-
- // Calculate position relative to the fixed physical-left slider origin.
- const newLeft = newRect.left - containerRect.left - SEGMENTED_PADDING;
-
- if (oldItemElement) {
- const oldRect = oldItemElement.getBoundingClientRect();
- const oldLeft = oldRect.left - containerRect.left - SEGMENTED_PADDING;
-
- setSlideStyle({
- '--slide-from': `${oldLeft}px`,
- '--slide-to': `${newLeft}px`,
- left: `${SEGMENTED_PADDING}px`,
- width: `${newRect.width}px`,
- transform: `translateX(${newLeft}px)`,
- } as CSSProperties);
- } else {
- setSlideStyle({
- left: `${SEGMENTED_PADDING}px`,
- width: `${newRect.width}px`,
- transform: `translateX(${newLeft}px)`,
- } as CSSProperties);
- }
+ const selectedRect = selectedElement.getBoundingClientRect();
+ slider.style.width = `${selectedRect.width}px`;
+ slider.style.transform = `translateX(${selectedRect.left - containerRect.left - SEGMENTED_PADDING}px)`;
}
- };
-
- useEffect(() => {
- updateSliderPosition(selectedItem);
- }, [direction, selectedItem]);
+ }, [direction, items, selectedItem]);
const handleClick = (itemValue: T) => {
- const oldValue = selectedItem;
- setSelectedItem(itemValue);
+ setInternalValue(itemValue);
onChange?.(itemValue);
- updateSliderPosition(itemValue, oldValue);
};
return (
@@ -113,18 +78,19 @@ export function Segmented<T extends ItemValue = ItemValue>({
>
<div
className={`
- univer-animate-univer-slide univer-absolute univer-h-6 univer-rounded-md univer-bg-gray-0
- univer-shadow-sm univer-transition-all univer-duration-200
+ univer-absolute univer-h-6 univer-rounded-md univer-bg-gray-0 univer-shadow-sm univer-transition-all
+ univer-duration-200
dark:!univer-bg-gray-700 dark:!univer-text-gray-400
`}
- style={slideStyle}
+ ref={sliderRef}
+ style={{ left: SEGMENTED_PADDING }}
/>
{items.map((item) => (
<button
key={String(item.value)}
ref={(el) => {
- if (el) itemRefs.current.set(item.value, el);
+ if (el) itemsRef.current.set(item.value, el);
}}
className={clsx(`
univer-relative univer-box-border univer-min-w-0 univer-flex-1 univer-cursor-pointer
diff --git a/packages/design/src/components/segmented/__tests__/index.spec.tsx b/packages/design/src/components/segmented/__tests__/Segmented.spec.tsx
similarity index 99%
rename from packages/design/src/components/segmented/__tests__/index.spec.tsx
rename to packages/design/src/components/segmented/__tests__/Segmented.spec.tsx
index 8563f50277..737f2ed04a 100644
--- a/packages/design/src/components/segmented/__tests__/index.spec.tsx
+++ b/packages/design/src/components/segmented/__tests__/Segmented.spec.tsx
@@ -43,7 +43,7 @@ describe('Segmented', () => {
it('should call onChange when click', () => {
const handleChange = vi.fn();
const { getByText } = render(<Segmented items={items} onChange={handleChange} />);
- getByText('B').click();
+ fireEvent.click(getByText('B'));
expect(handleChange).toHaveBeenCalledWith('b');
});
diff --git a/packages/find-replace/src/views/mobile/MobileFindReplaceBar.tsx b/packages/find-replace/src/views/mobile/MobileFindReplaceBar.tsx
index b3baf00338..7ab6c5b399 100644
--- a/packages/find-replace/src/views/mobile/MobileFindReplaceBar.tsx
+++ b/packages/find-replace/src/views/mobile/MobileFindReplaceBar.tsx
@@ -19,8 +19,8 @@ import type { LocaleKey } from '../../locale/types';
import { ICommandService, LocaleService } from '@univerjs/core';
import { clsx, Input, resetButtonClassName } from '@univerjs/design';
import { ArrowDownIcon, ArrowUpIcon, CloseIcon, ConfigureTabIcon, SearchIcon } from '@univerjs/icons';
-import { IDialogService, useDependency, useObservable } from '@univerjs/ui';
-import { useEffect, useRef, useState } from 'react';
+import { IDialogService, MobileKeyboardInsetContext, useDependency, useObservable } from '@univerjs/ui';
+import { useContext, useEffect, useRef, useState } from 'react';
import { ReplaceAllMatchesCommand, ReplaceCurrentMatchCommand } from '../../commands/commands/replace.command';
import {
CloseFindDialogOperation,
@@ -47,6 +47,7 @@ export function MobileFindReplaceBar() {
}
function MobileFindReplaceBarContent() {
+ const keyboardInset = useContext(MobileKeyboardInsetContext);
const commandService = useDependency(ICommandService);
const dialogService = useDependency(IDialogService);
const findReplaceService = useDependency(IFindReplaceService);
@@ -165,7 +166,7 @@ function MobileFindReplaceBarContent() {
dark:!univer-bg-gray-800
"
style={{
- bottom: 'var(--univer-mobile-keyboard-inset, 0px)',
+ bottom: keyboardInset,
paddingBottom: 'calc(6px + env(safe-area-inset-bottom, 0px))',
}}
>
diff --git a/packages/sheets-ui/src/views/mobile/action-panel/MobileSheetActionPanel.tsx b/packages/sheets-ui/src/views/mobile/action-panel/MobileSheetActionPanel.tsx
index ae36fac15d..4e7020d97e 100644
--- a/packages/sheets-ui/src/views/mobile/action-panel/MobileSheetActionPanel.tsx
+++ b/packages/sheets-ui/src/views/mobile/action-panel/MobileSheetActionPanel.tsx
@@ -40,13 +40,14 @@ import {
IMenuManagerService,
IRibbonService,
MobileDrawer,
+ MobileKeyboardInsetContext,
MobileMenu,
RibbonPosition,
RibbonStartGroup,
useDependency,
useObservable,
} from '@univerjs/ui';
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { map, startWith } from 'rxjs';
import { ScrollCommand, SetScrollRelativeCommand } from '../../../commands/commands/set-scroll.command';
import { SetCellEditVisibleOperation } from '../../../commands/operations/cell-edit.operation';
@@ -155,6 +156,7 @@ export function MobileSheetActionPanel() {
}
function MobileSheetActionPanelContent() {
+ const keyboardInset = useContext(MobileKeyboardInsetContext);
const workbook = useActiveWorkbook();
const commandService = useDependency(ICommandService);
const contextService = useDependency(IContextService);
@@ -386,7 +388,7 @@ function MobileSheetActionPanelContent() {
active:univer-bg-primary-700
`)}
style={{
- bottom: `calc(var(--univer-mobile-keyboard-inset, 0px) + ${getMobileEditingMenuBottomOffset(formulaOperatorsVisible)}px)`,
+ bottom: keyboardInset + getMobileEditingMenuBottomOffset(formulaOperatorsVisible),
}}
onClick={() => openTools().catch(() => undefined)}
>
diff --git a/packages/sheets-ui/src/views/mobile/formula-bar/MobileFormulaBar.tsx b/packages/sheets-ui/src/views/mobile/formula-bar/MobileFormulaBar.tsx
index f2a1b162c8..d68f1d9e00 100644
--- a/packages/sheets-ui/src/views/mobile/formula-bar/MobileFormulaBar.tsx
+++ b/packages/sheets-ui/src/views/mobile/formula-bar/MobileFormulaBar.tsx
@@ -44,12 +44,13 @@ import {
ComponentContainer,
ComponentManager,
KeyCode,
+ MobileKeyboardInsetContext,
useComponentsOfPart,
useConfigValue,
useDependency,
useObservable,
} from '@univerjs/ui';
-import { useEffect, useMemo, useRef, useState } from 'react';
+import { useContext, useEffect, useMemo, useRef, useState } from 'react';
import { EMPTY, map, merge, of, switchMap } from 'rxjs';
import { SetCellEditVisibleOperation } from '../../../commands/operations/cell-edit.operation';
import { EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY } from '../../../common/keys';
@@ -109,6 +110,7 @@ export function MobileFormulaBar() {
}
function MobileFormulaBarEditor() {
+ const keyboardInset = useContext(MobileKeyboardInsetContext);
const commandService = useDependency(ICommandService);
const contextService = useDependency(IContextService);
const editorBridgeService = useDependency(IEditorBridgeService);
@@ -338,7 +340,7 @@ function MobileFormulaBarEditor() {
dark:!univer-bg-gray-800
`, expanded ? 'univer-fixed univer-top-0 univer-z-50' : 'univer-absolute')}
style={{
- bottom: 'var(--univer-mobile-keyboard-inset, 0px)',
+ bottom: keyboardInset,
paddingBottom: expanded ? undefined : 'env(safe-area-inset-bottom, 0px)',
paddingTop: expanded ? 'env(safe-area-inset-top, 0px)' : undefined,
}}
diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts
index 5f63fe8731..ed9d597fb5 100644
--- a/packages/ui/src/index.ts
+++ b/packages/ui/src/index.ts
@@ -189,11 +189,10 @@ export * from './views/hooks/index';
export { preventBrowserZoomInContainers } from './views/hooks/prevent-browser-zoom';
export * from './views/index';
export { MobileMenu } from './views/menu/mobile/MobileMenu';
-export { type INotificationOptions } from './views/notification/Notification';
-
+export { MobileKeyboardInsetContext } from './views/mobile-workbench/MobileKeyboardInsetContext';
+export type { INotificationOptions } from './views/notification/Notification';
export { ObjectPermissionButton, openObjectPermissionDialog } from './views/object-permission/ObjectPermissionButton';
export type { IObjectPermissionButtonProps } from './views/object-permission/ObjectPermissionButton';
-
export { ObjectPermissionPanelButton, openObjectPermissionPanel } from './views/object-permission/ObjectPermissionPanel';
export { ProgressBar } from './views/progress-bar/ProgressBar';
diff --git a/packages/ui/src/views/mobile-workbench/MobileKeyboardInsetContext.ts b/packages/ui/src/views/mobile-workbench/MobileKeyboardInsetContext.ts
new file mode 100644
index 0000000000..8ddf56fc27
--- /dev/null
+++ b/packages/ui/src/views/mobile-workbench/MobileKeyboardInsetContext.ts
@@ -0,0 +1,19 @@
+/**
+ * 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 { createContext } from 'react';
+
+export const MobileKeyboardInsetContext = createContext(0);
diff --git a/packages/ui/src/views/mobile-workbench/MobileWorkbench.tsx b/packages/ui/src/views/mobile-workbench/MobileWorkbench.tsx
index 5bb21f7dc2..fb95170697 100644
--- a/packages/ui/src/views/mobile-workbench/MobileWorkbench.tsx
+++ b/packages/ui/src/views/mobile-workbench/MobileWorkbench.tsx
@@ -19,7 +19,7 @@ import type { ComponentType } from 'react';
import type { IWorkbenchOptions } from '../../controllers/ui/ui.controller';
import { LifecycleService, LifecycleStages, LocaleService, ThemeService } from '@univerjs/core';
import { borderBottomClassName, clsx, ConfigProvider, render } from '@univerjs/design';
-import { useEffect, useLayoutEffect, useMemo, useRef } from 'react';
+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { map } from 'rxjs';
import { BuiltInUIPart } from '../../services/parts/parts.service';
import { ThemeSwitcherService } from '../../services/theme-switcher/theme-switcher.service';
@@ -30,6 +30,7 @@ import { MobileContextMenu } from '../components/context-menu/MobileContextMenu'
import { MobileDrawerCoordinatorProvider } from '../components/mobile-drawer/MobileDrawerCoordinator';
import { MobileSidebar } from '../components/sidebar/MobileSidebar';
import { WorkbenchSkeleton } from '../components/workbench-skeleton/WorkbenchSkeleton';
+import { MobileKeyboardInsetContext } from './MobileKeyboardInsetContext';
export interface IUniverAppProps extends IWorkbenchOptions {
mountContainer: HTMLElement;
@@ -75,6 +76,7 @@ export function MobileWorkbench(props: IUniverAppProps) {
const contentRef = useRef<HTMLDivElement>(null);
const viewportRef = useRef<HTMLDivElement>(null);
+ const [keyboardInset, setKeyboardInset] = useState(0);
const footerComponents = useComponentsOfPart(BuiltInUIPart.FOOTER);
const headerComponents = useComponentsOfPart(BuiltInUIPart.HEADER);
@@ -146,10 +148,7 @@ export function MobileWorkbench(props: IUniverAppProps) {
const visibleBottom = visualViewport
? visualViewport.offsetTop + visualViewport.height
: window.innerHeight;
- viewportElement.style.setProperty(
- '--univer-mobile-keyboard-inset',
- `${Math.max(0, Math.round(stableHeight - visibleBottom))}px`
- );
+ setKeyboardInset(Math.max(0, Math.round(stableHeight - visibleBottom)));
};
const updateStableViewport = () => {
const width = Math.round(mountContainer.getBoundingClientRect().width || window.innerWidth);
@@ -186,106 +185,110 @@ export function MobileWorkbench(props: IUniverAppProps) {
direction={direction}
mountContainer={portalContainer}
>
- <MobileDrawerCoordinatorProvider>
- <div
- ref={viewportRef}
- className="
- univer-relative univer-h-full univer-min-h-0
- [&_button:active]:!univer-opacity-70
- [&_button]:univer-touch-manipulation
- "
- >
+ <MobileKeyboardInsetContext.Provider value={keyboardInset}>
+ <MobileDrawerCoordinatorProvider>
<div
- data-u-comp="app-layout"
- className={clsx(`
- univer-relative univer-flex univer-h-full univer-min-h-0 univer-flex-col univer-bg-gray-0
- dark:!univer-bg-gray-800
- `, {
- 'univer-dark': darkMode,
- })}
- tabIndex={-1}
- onBlur={(e) => e.stopPropagation()}
- onContextMenu={(e) => e.preventDefault()}
- dir={direction}
+ ref={viewportRef}
+ className="
+ univer-relative univer-h-full univer-min-h-0
+ [&_button:active]:!univer-opacity-70
+ [&_button]:univer-touch-manipulation
+ "
>
- {/* header */}
- {header && toolbar && (
- <header
- data-u-comp="headerbar"
- className="univer-relative univer-z-10 univer-w-full univer-overflow-hidden"
- >
- <ComponentContainer
- key="toolbar"
- components={toolbarComponents}
- sharedProps={{
- ribbonType,
- headerMenuComponents,
- headerMenu,
- }}
- />
- </header>
- )}
+ <div
+ data-u-comp="app-layout"
+ className={clsx(`
+ univer-relative univer-flex univer-h-full univer-min-h-0 univer-flex-col univer-bg-gray-0
+ dark:!univer-bg-gray-800
+ `, {
+ 'univer-dark': darkMode,
+ })}
+ tabIndex={-1}
+ onBlur={(e) => e.stopPropagation()}
+ onContextMenu={(e) => e.preventDefault()}
+ dir={direction}
+ >
+ {/* header */}
+ {header && toolbar && (
+ <header
+ data-u-comp="headerbar"
+ className="univer-relative univer-z-10 univer-w-full univer-overflow-hidden"
+ >
+ <ComponentContainer
+ key="toolbar"
+ components={toolbarComponents}
+ sharedProps={{
+ ribbonType,
+ headerMenuComponents,
+ headerMenu,
+ }}
+ />
+ </header>
+ )}
- {/* content */}
- <section className="univer-relative univer-flex univer-min-h-0 univer-flex-1 univer-flex-col">
- <div
- className={`
- univer-grid univer-h-full univer-grid-cols-[auto_1fr_auto] univer-grid-rows-[100%]
- univer-overflow-hidden
- `}
+ {/* content */}
+ <section
+ className="univer-relative univer-flex univer-min-h-0 univer-flex-1 univer-flex-col"
>
- <aside className="univer-h-full">
- <ComponentContainer key="left-sidebar" components={leftSidebarComponents} />
- </aside>
-
- <section
- className={clsx(`
- univer-relative univer-grid univer-flex-1 univer-grid-rows-[auto_1fr]
- univer-overflow-hidden univer-bg-gray-0
- dark:!univer-bg-gray-800
- `, borderBottomClassName)}
+ <div
+ className={`
+ univer-grid univer-h-full univer-grid-cols-[auto_1fr_auto] univer-grid-rows-[100%]
+ univer-overflow-hidden
+ `}
>
- <header className="univer-w-screen">
- {header && <ComponentContainer key="header" components={headerComponents} />}
- </header>
+ <aside className="univer-h-full">
+ <ComponentContainer key="left-sidebar" components={leftSidebarComponents} />
+ </aside>
<section
- ref={contentRef}
- className="univer-relative univer-overflow-hidden"
- data-range-selector
- onContextMenu={(e) => e.preventDefault()}
+ className={clsx(`
+ univer-relative univer-grid univer-flex-1 univer-grid-rows-[auto_1fr]
+ univer-overflow-hidden univer-bg-gray-0
+ dark:!univer-bg-gray-800
+ `, borderBottomClassName)}
>
- <ComponentContainer key="content" components={contentComponents} />
+ <header className="univer-w-screen">
+ {header && <ComponentContainer key="header" components={headerComponents} />}
+ </header>
+
+ <section
+ ref={contentRef}
+ className="univer-relative univer-overflow-hidden"
+ data-range-selector
+ onContextMenu={(e) => e.preventDefault()}
+ >
+ <ComponentContainer key="content" components={contentComponents} />
+ </section>
</section>
- </section>
- <aside className="univer-h-full" />
- </div>
+ <aside className="univer-h-full" />
+ </div>
- {/* footer */}
- {footer && (
- <footer>
- <ComponentContainer key="footer" components={footerComponents} />
- </footer>
- )}
- </section>
+ {/* footer */}
+ {footer && (
+ <footer>
+ <ComponentContainer key="footer" components={footerComponents} />
+ </footer>
+ )}
+ </section>
+ </div>
+ {(!ready || externalSkeletonVisible) && (
+ <WorkbenchSkeleton darkMode={darkMode} direction={direction} overlay />
+ )}
+ </div>
+ <div
+ className="
+ [&_button:active]:!univer-opacity-70
+ [&_button]:univer-touch-manipulation
+ "
+ dir={direction}
+ >
+ <ComponentContainer key="global" components={globalComponents} />
+ {contextMenu && <MobileContextMenu />}
+ <MobileSidebar />
</div>
- {(!ready || externalSkeletonVisible) && (
- <WorkbenchSkeleton darkMode={darkMode} direction={direction} overlay />
- )}
- </div>
- <div
- className="
- [&_button:active]:!univer-opacity-70
- [&_button]:univer-touch-manipulation
- "
- dir={direction}
- >
- <ComponentContainer key="global" components={globalComponents} />
- {contextMenu && <MobileContextMenu />}
- <MobileSidebar />
- </div>
- </MobileDrawerCoordinatorProvider>
+ </MobileDrawerCoordinatorProvider>
+ </MobileKeyboardInsetContext.Provider>
</ConfigProvider>
);
}
diff --git a/packages/ui/src/views/mobile-workbench/__tests__/MobileWorkbench.spec.tsx b/packages/ui/src/views/mobile-workbench/__tests__/MobileWorkbench.spec.tsx
new file mode 100644
index 0000000000..363a927da8
--- /dev/null
+++ b/packages/ui/src/views/mobile-workbench/__tests__/MobileWorkbench.spec.tsx
@@ -0,0 +1,157 @@
+/**
+ * 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.
+ */
+
+/**
+ * @vitest-environment jsdom
+ */
+
+import type { ComponentType } from 'react';
+import { act, cleanup, render } from '@testing-library/react';
+import {
+ ContextService,
+ DesktopLogService,
+ IConfigService,
+ IContextService,
+ ILogService,
+ Injector,
+ IUniverInstanceService,
+ LifecycleService,
+ LifecycleStages,
+ LocaleService,
+ ThemeService,
+ UniverInstanceService,
+} from '@univerjs/core';
+import { useContext } from 'react';
+import { createPortal } from 'react-dom';
+import { of, Subject } from 'rxjs';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { BuiltInUIPart, IUIPartsService, UIPartsService } from '../../../services/parts/parts.service';
+import { ISidebarService } from '../../../services/sidebar/sidebar.service';
+import { ThemeSwitcherService } from '../../../services/theme-switcher/theme-switcher.service';
+import { IWorkbenchService, WorkbenchService } from '../../../services/workbench/workbench.service';
+import { connectInjector } from '../../../utils/di';
+import { MobileKeyboardInsetContext } from '../MobileKeyboardInsetContext';
+import { MobileWorkbench } from '../MobileWorkbench';
+
+function KeyboardBar() {
+ const bottom = useContext(MobileKeyboardInsetContext);
+ return <div data-testid="keyboard-bar" style={{ bottom }} />;
+}
+
+describe('MobileWorkbench keyboard positioning', () => {
+ afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ it('shares viewport changes with footer and portal bars per instance and removes listeners on unmount', () => {
+ const viewport = Object.assign(new EventTarget(), { height: 800, offsetTop: 0 });
+ vi.stubGlobal('visualViewport', viewport);
+ const removeViewportListener = vi.spyOn(viewport, 'removeEventListener');
+ const removeWindowListener = vi.spyOn(window, 'removeEventListener');
+ const injector = new Injector([
+ [LifecycleService, { useValue: { lifecycle$: of(LifecycleStages.Ready), stage: LifecycleStages.Ready } }],
+ [LocaleService, {
+ useValue: {
+ direction$: of('ltr'),
+ getDirection: () => 'ltr',
+ getLocales: () => ({ design: {} }),
+ localeChanged$: new Subject<void>(),
+ t: (key: string) => key,
+ },
+ }],
+ [ThemeService, {
+ useValue: {
+ currentTheme$: of({}),
+ darkMode$: of(false),
+ darkMode: false,
+ },
+ }],
+ [ThemeSwitcherService, { useValue: { injectThemeToHead: () => {} } }],
+ [IConfigService, { useValue: { getConfig: () => ({ popupRootId: 'test-popup-root' }) } }],
+ [IContextService, { useClass: ContextService }],
+ [ILogService, { useClass: DesktopLogService }],
+ [IUniverInstanceService, { useClass: UniverInstanceService }],
+ [IUIPartsService, { useClass: UIPartsService }],
+ [IWorkbenchService, { useClass: WorkbenchService }],
+ [ISidebarService, {
+ useValue: {
+ sidebarOptions$: of(null),
+ scrollEvent$: new Subject<Event>(),
+ visible: false,
+ close: () => {},
+ setContainer: () => {},
+ setWidth: () => {},
+ },
+ }],
+ ]);
+ const partsService = injector.get(IUIPartsService);
+ partsService.registerComponent(BuiltInUIPart.FOOTER, () => KeyboardBar);
+ const portal = document.createElement('div');
+ partsService.registerComponent(BuiltInUIPart.GLOBAL, () => () => createPortal(<KeyboardBar />, portal));
+ const ConnectedWorkbench = connectInjector(MobileWorkbench, injector) as ComponentType<{
+ mountContainer: HTMLElement;
+ contextMenu: boolean;
+ }>;
+ const firstMount = document.createElement('div');
+ const secondMount = document.createElement('div');
+ vi.spyOn(firstMount, 'getBoundingClientRect').mockReturnValue({ height: 800, width: 400 } as DOMRect);
+ vi.spyOn(secondMount, 'getBoundingClientRect').mockReturnValue({ height: 600, width: 400 } as DOMRect);
+ const first = render(<ConnectedWorkbench mountContainer={firstMount} contextMenu={false} />);
+ const second = render(<ConnectedWorkbench mountContainer={secondMount} contextMenu={false} />);
+ const firstBar = first.container.querySelector<HTMLElement>('[data-testid="keyboard-bar"]')!;
+ const secondBar = second.container.querySelector<HTMLElement>('[data-testid="keyboard-bar"]')!;
+ const portalBars = portal.querySelectorAll<HTMLElement>('[data-testid="keyboard-bar"]');
+ const rootStyle = document.documentElement.getAttribute('style');
+ const bodyStyle = document.body.getAttribute('style');
+
+ act(() => {
+ viewport.height = 500;
+ viewport.dispatchEvent(new Event('resize'));
+ });
+ expect(firstBar.style.bottom).toBe('300px');
+ expect(secondBar.style.bottom).toBe('100px');
+ expect(portalBars[0].style.bottom).toBe('300px');
+ expect(portalBars[1].style.bottom).toBe('100px');
+
+ act(() => {
+ viewport.offsetTop = 50;
+ viewport.dispatchEvent(new Event('scroll'));
+ });
+ expect(firstBar.style.bottom).toBe('250px');
+ expect(secondBar.style.bottom).toBe('50px');
+
+ act(() => {
+ viewport.height = 800;
+ viewport.offsetTop = 0;
+ viewport.dispatchEvent(new Event('resize'));
+ });
+ expect(firstBar.style.bottom).toBe('0px');
+ expect(secondBar.style.bottom).toBe('0px');
+ expect(document.documentElement.getAttribute('style')).toBe(rootStyle);
+ expect(document.body.getAttribute('style')).toBe(bodyStyle);
+ expect([...first.container.querySelectorAll<HTMLElement>('[style]')].some((element) =>
+ [...element.style].some((property) => property.startsWith('--')))).toBe(false);
+
+ first.unmount();
+ second.unmount();
+ expect(removeViewportListener.mock.calls.map(([event]) => event)).toEqual(['resize', 'scroll', 'resize', 'scroll']);
+ expect(removeWindowListener).toHaveBeenCalledWith('resize', expect.any(Function));
+ injector.dispose();
+ });
+});