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(mobile): improve spreadsheet UI experience (#7642)

wpxp123456d58d3b08b487
diff --git a/packages/design/src/components/action-row/ActionRow.tsx b/packages/design/src/components/action-row/ActionRow.tsx
index 4d6948f18e..5e6fe8896b 100644
--- a/packages/design/src/components/action-row/ActionRow.tsx
+++ b/packages/design/src/components/action-row/ActionRow.tsx
@@ -15,23 +15,9 @@
*/
import type { HTMLAttributes } from 'react';
-import { useContext } from 'react';
-import { clsx } from '../../helper/clsx';
-import { ConfigContext } from '../config-provider/ConfigProvider';
export type IActionRowProps = HTMLAttributes<HTMLDivElement>;
export function ActionRow({ className, ...props }: IActionRowProps) {
- const { mobile } = useContext(ConfigContext);
-
- return (
- <div
- className={clsx(className, mobile && `
- univer-flex univer-w-full univer-justify-stretch univer-gap-3
- [&>button]:!univer-m-0 [&>button]:!univer-h-12 [&>button]:!univer-min-w-0 [&>button]:!univer-flex-1
- [&>button]:!univer-rounded-xl
- `)}
- {...props}
- />
- );
+ return <div className={className} {...props} />;
}
diff --git a/packages/design/src/components/action-row/MobileActionRowGroup.tsx b/packages/design/src/components/action-row/MobileActionRowGroup.tsx
new file mode 100644
index 0000000000..8bfacf3472
--- /dev/null
+++ b/packages/design/src/components/action-row/MobileActionRowGroup.tsx
@@ -0,0 +1,33 @@
+/**
+ * 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 { IActionRowProps } from './ActionRow';
+import { clsx } from '../../helper/clsx';
+
+export type IMobileActionRowGroupProps = IActionRowProps;
+
+export function MobileActionRowGroup({ className, ...props }: IMobileActionRowGroupProps) {
+ return (
+ <div
+ className={clsx(className, `
+ univer-flex univer-w-full univer-justify-stretch univer-gap-3
+ [&>button]:!univer-m-0 [&>button]:!univer-h-12 [&>button]:!univer-min-w-0 [&>button]:!univer-flex-1
+ [&>button]:!univer-rounded-xl
+ `)}
+ {...props}
+ />
+ );
+}
diff --git a/packages/design/src/components/action-row/__tests__/ActionRow.spec.tsx b/packages/design/src/components/action-row/__tests__/ActionRow.spec.tsx
deleted file mode 100644
index ae090b6dfe..0000000000
--- a/packages/design/src/components/action-row/__tests__/ActionRow.spec.tsx
+++ /dev/null
@@ -1,37 +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 { cleanup, render } from '@testing-library/react';
-import { afterEach, describe, expect, it } from 'vitest';
-import { ConfigProvider } from '../../config-provider/ConfigProvider';
-import { ActionRow } from '../ActionRow';
-
-afterEach(cleanup);
-
-describe('ActionRow', () => {
- it('applies touch-first button layout only in mobile presentation', () => {
- const desktop = render(<ActionRow><button type="button">Save</button></ActionRow>);
- expect(desktop.container.firstElementChild?.className).not.toContain('[&>button]:!univer-h-12');
- desktop.unmount();
-
- const mobile = render(
- <ConfigProvider mobile mountContainer={document.body}>
- <ActionRow><button type="button">Save</button></ActionRow>
- </ConfigProvider>
- );
- expect(mobile.container.firstElementChild?.className).toContain('[&>button]:!univer-h-12');
- });
-});
diff --git a/packages/design/src/components/color-picker/ColorPicker.tsx b/packages/design/src/components/color-picker/ColorPicker.tsx
index 191ab3adb0..226a1bceb3 100644
--- a/packages/design/src/components/color-picker/ColorPicker.tsx
+++ b/packages/design/src/components/color-picker/ColorPicker.tsx
@@ -15,7 +15,6 @@
*/
import { memo, useCallback, useContext, useEffect, useState } from 'react';
-import { clsx } from '../../helper/clsx';
import { isBrowser } from '../../helper/is-browser';
import { Button } from '../button/Button';
import { ConfigContext } from '../config-provider/ConfigProvider';
@@ -26,14 +25,12 @@ import { ColorInput } from './ColorInput';
import { ColorPresets } from './ColorPresets';
import { ColorSpectrum } from './ColorSpectrum';
import { HueSlider } from './HueSlider';
-import { MobileColorPresets } from './MobileColorPresets';
const MemoizedColorSpectrum = memo(ColorSpectrum);
const MemoizedHueSlider = memo(HueSlider);
const MemoizedAlphaSlider = memo(AlphaSlider);
const MemoizedColorInput = memo(ColorInput);
const MemoizedColorPresets = memo(ColorPresets);
-const MemoizedMobileColorPresets = memo(MobileColorPresets);
export interface IColorPickerProps {
format?: 'hex' | 'rgba';
@@ -42,7 +39,7 @@ export interface IColorPickerProps {
}
export function ColorPicker({ format = 'hex', value, onChange }: IColorPickerProps) {
- const { direction, locale, mobile } = useContext(ConfigContext);
+ const { direction, locale } = useContext(ConfigContext);
const [hsv, setHsv] = useState<[number, number, number]>([0, 100, 100]);
const [alpha, setAlpha] = useState(1);
@@ -70,7 +67,9 @@ export function ColorPicker({ format = 'hex', value, onChange }: IColorPickerPro
}
}, [value, format]);
- if (!isBrowser) return null;
+ if (!isBrowser) {
+ return null;
+ }
function handleColorChange(h: number, s: number, v: number) {
setHsv([h, s, v]);
@@ -110,46 +109,24 @@ export function ColorPicker({ format = 'hex', value, onChange }: IColorPickerPro
className="univer-cursor-default univer-space-y-2 univer-rounded-lg"
onClick={(e) => e.stopPropagation()}
>
- {mobile
- ? (
- <MemoizedMobileColorPresets
- value={hsvToHex(...hsv)}
- onSelect={(color) => {
- const [h, s, v] = hexToHsv(color);
- handleColorChange(h, s, v);
- handleAlphaChange(1);
- handleColorChanged(h, s, v, 1);
- }}
- />
- )
- : (
- <MemoizedColorPresets
- hsv={hsv}
- onChange={(h, s, v) => {
- handleColorChange(h, s, v);
- handleAlphaChange(1);
- handleColorChanged(h, s, v, 1);
- }}
- />
- )}
-
- <div className={clsx('univer-flex univer-items-center', mobile ? 'univer-h-12' : 'univer-h-7')}>
+ <MemoizedColorPresets
+ hsv={hsv}
+ onChange={(h, s, v) => {
+ handleColorChange(h, s, v);
+ handleAlphaChange(1);
+ handleColorChanged(h, s, v, 1);
+ }}
+ />
+
+ <div className="univer-flex univer-h-7 univer-items-center">
<button
type="button"
- className={clsx(`
- univer-cursor-pointer univer-border-0 univer-text-sm univer-text-gray-900
+ className="
+ univer-cursor-pointer univer-border-0 univer-bg-transparent univer-p-0 univer-text-sm
+ univer-text-gray-900 univer-transition-opacity
+ hover:univer-opacity-80
dark:!univer-text-gray-0
- `, mobile
- ? `
- univer-h-11 univer-w-full univer-rounded-xl univer-bg-gray-100 univer-font-medium
- active:univer-bg-gray-200
- dark:!univer-bg-gray-800
- dark:active:!univer-bg-gray-700
- `
- : `
- univer-bg-transparent univer-p-0 univer-transition-opacity
- hover:univer-opacity-80
- `)}
+ "
onClick={() => setVisible(true)}
>
{locale?.ColorPicker.more}
@@ -198,7 +175,9 @@ export function ColorPicker({ format = 'hex', value, onChange }: IColorPickerPro
format={format}
onChange={(h, s, v, a) => {
handleColorChange(h, s, v);
- if (a !== undefined) handleAlphaChange(a);
+ if (a !== undefined) {
+ handleAlphaChange(a);
+ }
}}
/>
diff --git a/packages/design/src/components/color-picker/ColorSpectrum.tsx b/packages/design/src/components/color-picker/ColorSpectrum.tsx
index 7f54716a91..e3c6a048e7 100644
--- a/packages/design/src/components/color-picker/ColorSpectrum.tsx
+++ b/packages/design/src/components/color-picker/ColorSpectrum.tsx
@@ -86,18 +86,11 @@ export function ColorSpectrum({ hsv, onChange, onChanged }: IColorSpectrumProps)
// Calculate the position of the indicator
const getIndicatorStyles = () => {
- const indicatorSize = 16; // 4rem = 16px
- const halfIndicatorSize = indicatorSize / 2;
-
- const w = containerRef.current?.clientWidth ?? 0;
- const h = containerRef.current?.clientHeight ?? 0;
-
- const x = (hsv[1] / 100) * w - halfIndicatorSize;
- const y = (100 - hsv[2]) / 100 * h - halfIndicatorSize;
-
return {
- transform: `translate(${x}px, ${y}px)`,
- transition: isDragging ? 'none' : 'transform 0.1s ease-out',
+ left: `${hsv[1]}%`,
+ top: `${100 - hsv[2]}%`,
+ transform: 'translate(-50%, -50%)',
+ transition: isDragging ? 'none' : 'left 0.1s ease-out, top 0.1s ease-out',
};
};
@@ -119,7 +112,7 @@ export function ColorSpectrum({ hsv, onChange, onChanged }: IColorSpectrumProps)
<div
data-u-comp="color-picker-spectrum"
ref={containerRef}
- className="univer-relative univer-overflow-hidden"
+ className="univer-relative univer-size-full univer-overflow-hidden"
>
<canvas
ref={canvasRef}
diff --git a/packages/design/src/components/color-picker/MobileColorPicker.tsx b/packages/design/src/components/color-picker/MobileColorPicker.tsx
new file mode 100644
index 0000000000..ca93ecb3b2
--- /dev/null
+++ b/packages/design/src/components/color-picker/MobileColorPicker.tsx
@@ -0,0 +1,168 @@
+/**
+ * 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 { IColorPickerProps } from './ColorPicker';
+import { memo, useCallback, useContext, useEffect, useState } from 'react';
+import { isBrowser } from '../../helper/is-browser';
+import { MobileActionRowGroup } from '../action-row/MobileActionRowGroup';
+import { Button } from '../button/Button';
+import { ConfigContext } from '../config-provider/ConfigProvider';
+import { MobileDialog } from '../dialog/MobileDialog';
+import { MobileDropdownCloseContext } from '../dropdown/MobileDropdown';
+import { AlphaSlider } from './AlphaSlider';
+import { hexToHsv, hsvToHex, hsvToRgb, hsvToRgba, parseRgba, rgbToHex, rgbToHsv } from './color-conversion';
+import { ColorInput } from './ColorInput';
+import { ColorSpectrum } from './ColorSpectrum';
+import { HueSlider } from './HueSlider';
+import { MobileColorPresets } from './MobileColorPresets';
+
+const MemoizedColorSpectrum = memo(ColorSpectrum);
+const MemoizedHueSlider = memo(HueSlider);
+const MemoizedAlphaSlider = memo(AlphaSlider);
+const MemoizedColorInput = memo(ColorInput);
+const MemoizedMobileColorPresets = memo(MobileColorPresets);
+
+export type IMobileColorPickerProps = IColorPickerProps;
+
+export function MobileColorPicker({ format = 'hex', value, onChange }: IMobileColorPickerProps) {
+ const { direction, locale } = useContext(ConfigContext);
+ const closeMobileDropdown = useContext(MobileDropdownCloseContext);
+ const [hsv, setHsv] = useState<[number, number, number]>([0, 100, 100]);
+ const [alpha, setAlpha] = useState(1);
+ const [visible, setVisible] = useState(false);
+ const getRgb = useCallback((h: number, s: number, v: number) => hsvToRgb(h, s, v), []);
+
+ useEffect(() => {
+ try {
+ const actualValue = value || (format === 'hex' ? '#000000' : 'rgba(0, 0, 0, 1)');
+ if (format === 'hex') {
+ setHsv(hexToHsv(actualValue));
+ setAlpha(1);
+ } else {
+ const [r, g, b, a] = parseRgba(actualValue);
+ setHsv(rgbToHsv(r, g, b));
+ setAlpha(a);
+ }
+ } catch (error) {
+ console.error('Invalid value:', error);
+ }
+ }, [format, value]);
+
+ if (!isBrowser) {
+ return null;
+ }
+
+ function handleColorChange(h: number, s: number, v: number) {
+ setHsv([h, s, v]);
+ }
+
+ function handleColorChanged(h: number, s: number, v: number, a: number = alpha) {
+ if (format === 'hex') {
+ onChange?.(rgbToHex(...getRgb(h, s, v)));
+ } else {
+ const [r, g, b] = getRgb(h, s, v);
+ onChange?.(`rgba(${r}, ${g}, ${b}, ${a})`);
+ }
+ closeMobileDropdown?.();
+ }
+
+ function handleConfirmCustomColor() {
+ const [h, s, v] = hsv;
+ setVisible(false);
+ handleColorChanged(h, s, v, alpha);
+ }
+
+ return (
+ <div
+ data-u-comp="color-picker"
+ data-presentation="mobile"
+ dir={direction}
+ className="univer-cursor-default univer-space-y-2 univer-rounded-lg"
+ onClick={(event) => event.stopPropagation()}
+ >
+ <MemoizedMobileColorPresets
+ value={hsvToHex(...hsv)}
+ onSelect={(color) => {
+ const [h, s, v] = hexToHsv(color);
+ handleColorChange(h, s, v);
+ setAlpha(1);
+ handleColorChanged(h, s, v, 1);
+ }}
+ />
+
+ <div className="univer-flex univer-h-12 univer-items-center">
+ <button
+ type="button"
+ className="
+ univer-h-11 univer-w-full univer-cursor-pointer univer-rounded-xl univer-border-0
+ univer-bg-gray-100 univer-text-sm univer-font-medium univer-text-gray-900
+ active:univer-bg-gray-200
+ dark:!univer-bg-gray-800 dark:!univer-text-gray-0
+ dark:active:!univer-bg-gray-700
+ "
+ onClick={() => setVisible(true)}
+ >
+ {locale?.ColorPicker.more}
+ </button>
+ </div>
+
+ <MobileDialog
+ className="!univer-z-[1420] !univer-p-2.5"
+ overlayClassName="!univer-z-[1410]"
+ closable={false}
+ maskClosable={false}
+ open={visible}
+ onOpenChange={setVisible}
+ >
+ <div data-u-comp="mobile-color-picker-custom" className="univer-grid univer-w-full univer-gap-2">
+ <div className="univer-h-44 univer-w-full univer-overflow-hidden univer-rounded-lg">
+ <MemoizedColorSpectrum hsv={hsv} onChange={handleColorChange} />
+ </div>
+
+ <div className="univer-flex univer-items-center univer-gap-2">
+ <div
+ className="univer-size-6 univer-flex-shrink-0 univer-rounded-sm"
+ style={{ backgroundColor: format === 'hex' ? hsvToHex(...hsv) : hsvToRgba(...hsv, alpha) }}
+ />
+ <div className="univer-flex-1 univer-space-y-2">
+ <MemoizedHueSlider hsv={hsv} onChange={handleColorChange} />
+ {format === 'rgba' && (
+ <MemoizedAlphaSlider hsv={hsv} alpha={alpha} onChange={setAlpha} />
+ )}
+ </div>
+ </div>
+
+ <MemoizedColorInput
+ hsv={hsv}
+ alpha={alpha}
+ format={format}
+ onChange={(h, s, v, a) => {
+ handleColorChange(h, s, v);
+ if (a !== undefined) {
+ setAlpha(a);
+ }
+ }}
+ />
+
+ <MobileActionRowGroup>
+ <Button onClick={() => setVisible(false)}>{locale?.ColorPicker.cancel}</Button>
+ <Button variant="primary" onClick={handleConfirmCustomColor}>{locale?.ColorPicker.confirm}</Button>
+ </MobileActionRowGroup>
+ </div>
+ </MobileDialog>
+ </div>
+ );
+}
diff --git a/packages/design/src/components/color-picker/__tests__/color-spectrum-extra.spec.tsx b/packages/design/src/components/color-picker/__tests__/color-spectrum-extra.spec.tsx
index 8ce24fd3ca..c8b8f613f4 100644
--- a/packages/design/src/components/color-picker/__tests__/color-spectrum-extra.spec.tsx
+++ b/packages/design/src/components/color-picker/__tests__/color-spectrum-extra.spec.tsx
@@ -66,4 +66,14 @@ describe('ColorSpectrum extra', () => {
expect(onChange).toHaveBeenCalled();
expect(onChanged).toHaveBeenCalledWith(120, 20, 80);
});
+
+ it('positions the initial indicator from hsv without waiting for container measurements', () => {
+ const { container } = render(<ColorSpectrum hsv={[120, 20, 80]} onChange={vi.fn()} />);
+
+ const indicator = container.querySelector('[data-u-comp="color-picker-spectrum"] > div') as HTMLDivElement;
+
+ expect(indicator.style.left).toBe('20%');
+ expect(indicator.style.top).toBe('20%');
+ expect(indicator.style.transform).toBe('translate(-50%, -50%)');
+ });
});
diff --git a/packages/design/src/components/color-picker/__tests__/index.spec.tsx b/packages/design/src/components/color-picker/__tests__/index.spec.tsx
index 703402dbf8..efd07cd4ec 100644
--- a/packages/design/src/components/color-picker/__tests__/index.spec.tsx
+++ b/packages/design/src/components/color-picker/__tests__/index.spec.tsx
@@ -20,11 +20,13 @@ import { useState } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import enUS from '../../../locale/en-US';
import { ConfigProvider } from '../../config-provider/ConfigProvider';
+import { MobileDropdown } from '../../dropdown/MobileDropdown';
import { ColorInput } from '../ColorInput';
import { ColorPicker } from '../ColorPicker';
import { ColorPickerPanel } from '../ColorPickerPanel';
import { ColorSpectrum } from '../ColorSpectrum';
import { HueSlider } from '../HueSlider';
+import { MobileColorPicker } from '../MobileColorPicker';
import { MobileColorPresets } from '../MobileColorPresets';
import { colorPresets } from '../presets';
import '@testing-library/jest-dom/vitest';
@@ -138,6 +140,107 @@ describe('ColorPicker', () => {
});
describe('mobile color picker views', () => {
+ it('renders the touch-first picker explicitly', () => {
+ const { container } = render(
+ <ConfigProvider locale={enUS.design} mountContainer={document.body}>
+ <MobileColorPicker value="#FFFFFF" />
+ </ConfigProvider>
+ );
+
+ expect(container.querySelector('[data-u-comp="color-picker"][data-presentation="mobile"]')).toBeInTheDocument();
+ expect(getMoreColorButton(container)).toHaveClass('univer-h-11');
+ });
+
+ it('uses the mobile action layout for custom color actions', () => {
+ const { container } = render(
+ <ConfigProvider locale={enUS.design} mountContainer={document.body}>
+ <MobileColorPicker value="#FFFFFF" />
+ </ConfigProvider>
+ );
+
+ fireEvent.click(getMoreColorButton(container));
+
+ const confirmButton = Array.from(document.querySelectorAll('button'))
+ .find((button) => button.textContent === enUS.design.ColorPicker.confirm);
+ expect(confirmButton?.parentElement).toHaveClass('univer-w-full');
+ });
+
+ it('opens custom colors above the containing mobile dropdown', () => {
+ render(
+ <ConfigProvider locale={enUS.design} mountContainer={document.body}>
+ <MobileDropdown open overlay={<MobileColorPicker value="#FFFFFF" />}>
+ <button type="button">Color</button>
+ </MobileDropdown>
+ </ConfigProvider>
+ );
+
+ fireEvent.click(getMoreColorButton(document.body));
+
+ const dialogs = Array.from(document.querySelectorAll<HTMLElement>('[role="dialog"]'));
+ const customColorDialog = dialogs
+ .find((dialog) => dialog.className.includes('!univer-z-[1420]'));
+ const customColorOverlay = Array.from(document.querySelectorAll<HTMLElement>('[data-state="open"].univer-fixed.univer-inset-0'))
+ .find((overlay) => overlay.className.includes('!univer-z-[1410]'));
+ const customColorContent = customColorDialog?.querySelector<HTMLElement>('[data-u-comp="mobile-color-picker-custom"]');
+ const spectrum = customColorContent?.querySelector<HTMLElement>('[data-u-comp="color-picker-spectrum"]');
+ const spectrumContainer = spectrum?.parentElement;
+
+ expect(dialogs).toHaveLength(2);
+ expect(customColorDialog).toBeInTheDocument();
+ expect(customColorOverlay).toBeInTheDocument();
+ expect(customColorContent).toHaveClass('univer-w-full');
+ expect(spectrumContainer).toHaveClass('univer-h-44', 'univer-w-full');
+ expect(spectrum).toHaveClass('univer-size-full');
+ });
+
+ it('closes the containing mobile dropdown after selecting a preset color', () => {
+ render(
+ <ConfigProvider locale={enUS.design} mountContainer={document.body}>
+ <MobileDropdown overlay={<MobileColorPicker value="#FFFFFF" />}>
+ <button type="button">Color</button>
+ </MobileDropdown>
+ </ConfigProvider>
+ );
+
+ fireEvent.click(document.querySelector('button')!);
+ fireEvent.click(document.querySelectorAll('[data-u-comp="color-picker"] button')[1]);
+
+ expect(document.querySelector('[role="dialog"]')).not.toBeInTheDocument();
+ });
+
+ it('closes both color dialogs after confirming a custom color', () => {
+ render(
+ <ConfigProvider locale={enUS.design} mountContainer={document.body}>
+ <MobileDropdown overlay={<MobileColorPicker value="#FFFFFF" />}>
+ <button type="button">Color</button>
+ </MobileDropdown>
+ </ConfigProvider>
+ );
+
+ fireEvent.click(document.querySelector('button')!);
+ fireEvent.click(getMoreColorButton(document.body));
+ fireEvent.click(document.querySelector<HTMLButtonElement>('[data-u-comp="mobile-color-picker-custom"] button:last-child')!);
+
+ expect(document.querySelector('[role="dialog"]')).not.toBeInTheDocument();
+ });
+
+ it('keeps the containing mobile dropdown open after cancelling a custom color', () => {
+ render(
+ <ConfigProvider locale={enUS.design} mountContainer={document.body}>
+ <MobileDropdown overlay={<MobileColorPicker value="#FFFFFF" />}>
+ <button type="button">Color</button>
+ </MobileDropdown>
+ </ConfigProvider>
+ );
+
+ fireEvent.click(document.querySelector('button')!);
+ fireEvent.click(getMoreColorButton(document.body));
+ fireEvent.click(document.querySelector<HTMLButtonElement>('[data-u-comp="mobile-color-picker-custom"] button')!);
+
+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1);
+ expect(document.querySelector('[data-u-comp="color-picker"]')).toBeInTheDocument();
+ });
+
it('renders large preset targets and applies the selected color', () => {
const onSelect = vi.fn();
const { container } = render(<MobileColorPresets value="#FFFFFF" onSelect={onSelect} />);
diff --git a/packages/design/src/components/config-provider/ConfigProvider.tsx b/packages/design/src/components/config-provider/ConfigProvider.tsx
index 16c75906f5..faf4059077 100644
--- a/packages/design/src/components/config-provider/ConfigProvider.tsx
+++ b/packages/design/src/components/config-provider/ConfigProvider.tsx
@@ -16,7 +16,7 @@
import type { ReactNode } from 'react';
import { DirectionProvider } from '@radix-ui/react-direction';
-import { createContext, useContext, useMemo } from 'react';
+import { createContext, useMemo } from 'react';
import { isBrowser } from '../../helper/is-browser';
export interface IConfigProviderProps {
@@ -24,10 +24,6 @@ export interface IConfigProviderProps {
locale?: any;
direction?: 'ltr' | 'rtl';
mountContainer: HTMLElement | null;
- /** Disable tooltip popovers for this provider subtree. */
- disableTooltips?: boolean;
- /** Use touch-first presentation for overlays in this provider subtree. */
- mobile?: boolean;
}
export const ConfigContext = createContext<Omit<IConfigProviderProps, 'children'>>({
@@ -35,20 +31,15 @@ export const ConfigContext = createContext<Omit<IConfigProviderProps, 'children'
});
export function ConfigProvider(props: IConfigProviderProps) {
- const { children, locale, mountContainer, direction, disableTooltips, mobile } = props;
- const parentConfig = useContext(ConfigContext);
- const resolvedDisableTooltips = disableTooltips ?? parentConfig.disableTooltips;
- const resolvedMobile = mobile ?? parentConfig.mobile;
+ const { children, locale, mountContainer, direction } = props;
const value = useMemo(() => {
return {
locale,
direction,
mountContainer,
- disableTooltips: resolvedDisableTooltips,
- mobile: resolvedMobile,
};
- }, [locale, direction, mountContainer, resolvedDisableTooltips, resolvedMobile]);
+ }, [locale, direction, mountContainer]);
return (
<ConfigContext.Provider value={value}>
diff --git a/packages/design/src/components/confirm/MobileConfirm.tsx b/packages/design/src/components/confirm/MobileConfirm.tsx
new file mode 100644
index 0000000000..e2ce27b754
--- /dev/null
+++ b/packages/design/src/components/confirm/MobileConfirm.tsx
@@ -0,0 +1,58 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IConfirmProps } from './Confirm';
+import { useContext } from 'react';
+import { MobileActionRowGroup } from '../action-row/MobileActionRowGroup';
+import { Button } from '../button/Button';
+import { ConfigContext } from '../config-provider/ConfigProvider';
+import { MobileDialog } from '../dialog/MobileDialog';
+
+export type IMobileConfirmProps = IConfirmProps;
+
+export function MobileConfirm(props: IMobileConfirmProps) {
+ const {
+ children,
+ visible = false,
+ title,
+ cancelText,
+ confirmText,
+ onClose,
+ onConfirm,
+ closable = true,
+ } = props;
+ const { locale } = useContext(ConfigContext);
+
+ return (
+ <MobileDialog
+ open={visible}
+ title={title}
+ maskClosable={false}
+ footer={(
+ <MobileActionRowGroup>
+ {closable && <Button onClick={onClose}>{cancelText ?? locale?.Confirm.cancel}</Button>}
+ <Button variant="primary" onClick={onConfirm}>
+ {confirmText ?? locale?.Confirm.confirm}
+ </Button>
+ </MobileActionRowGroup>
+ )}
+ onClose={onClose}
+ closable={closable}
+ >
+ {children}
+ </MobileDialog>
+ );
+}
diff --git a/packages/design/src/components/confirm/__tests__/index.spec.tsx b/packages/design/src/components/confirm/__tests__/index.spec.tsx
index 1fb650103d..db344b4589 100644
--- a/packages/design/src/components/confirm/__tests__/index.spec.tsx
+++ b/packages/design/src/components/confirm/__tests__/index.spec.tsx
@@ -14,9 +14,10 @@
* limitations under the License.
*/
-import { cleanup, render } from '@testing-library/react';
+import { cleanup, render, screen } from '@testing-library/react';
import { afterEach, describe, expect, it } from 'vitest';
import { Confirm } from '../Confirm';
+import { MobileConfirm } from '../MobileConfirm';
import '@testing-library/jest-dom/vitest';
afterEach(cleanup);
@@ -38,4 +39,11 @@ describe('Confirm', () => {
expect(getByText('No')).toBeInTheDocument();
expect(getByText('Yes')).toBeInTheDocument();
});
+
+ it('should render the mobile confirmation as a bottom surface', () => {
+ render(<MobileConfirm visible title="Mobile confirm" confirmText="Confirm">content</MobileConfirm>);
+
+ expect(document.querySelector('[role="dialog"]')).toHaveClass('!univer-bottom-0');
+ expect(screen.getByRole('button', { name: 'Confirm' }).parentElement).toHaveClass('univer-w-full');
+ });
});
diff --git a/packages/design/src/components/dialog/Dialog.tsx b/packages/design/src/components/dialog/Dialog.tsx
index e6a4f11d9f..3ed9bda864 100644
--- a/packages/design/src/components/dialog/Dialog.tsx
+++ b/packages/design/src/components/dialog/Dialog.tsx
@@ -27,7 +27,6 @@ import {
Dialog as DialogProvider,
DialogTitle,
} from './DialogPrimitive';
-import { MobileDialogContent } from './MobileDialogContent';
export interface IDialogProps {
children: ReactNode;
@@ -154,7 +153,9 @@ function useDraggable(
const initializedRef = useRef(false);
useEffect(() => {
- if (!elementRef.current || initializedRef.current || options.defaultPosition) return;
+ if (!elementRef.current || initializedRef.current || options.defaultPosition) {
+ return;
+ }
const { width, height } = elementRef.current.getBoundingClientRect();
const { innerWidth, innerHeight } = window;
@@ -168,7 +169,9 @@ function useDraggable(
}, [options.defaultPosition]);
const calculateBounds = useCallback((clientX: number, clientY: number) => {
- if (!elementRef.current) return { x: clientX, y: clientY };
+ if (!elementRef.current) {
+ return { x: clientX, y: clientY };
+ }
const rect = elementRef.current.getBoundingClientRect();
const { clientWidth, clientHeight } = document.documentElement;
@@ -176,16 +179,26 @@ function useDraggable(
let newX = startPosRef.current.x + (clientX - startClientRef.current.x);
let newY = startPosRef.current.y + (clientY - startClientRef.current.y);
- if (newX < 0) newX = 0;
- if (newY < 0) newY = 0;
- if (newX + rect.width > clientWidth) newX = clientWidth - rect.width;
- if (newY + rect.height > clientHeight) newY = clientHeight - rect.height;
+ if (newX < 0) {
+ newX = 0;
+ }
+ if (newY < 0) {
+ newY = 0;
+ }
+ if (newX + rect.width > clientWidth) {
+ newX = clientWidth - rect.width;
+ }
+ if (newY + rect.height > clientHeight) {
+ newY = clientHeight - rect.height;
+ }
return { x: newX, y: newY };
}, []);
const startDrag = useCallback((e: MouseEvent<HTMLElement> | MouseEvent) => {
- if (!enabled) return;
+ if (!enabled) {
+ return;
+ }
e.preventDefault();
e.stopPropagation();
@@ -198,7 +211,9 @@ function useDraggable(
}, [enabled, position]);
const onDrag = useCallback((e: globalThis.MouseEvent) => {
- if (!isDragging) return;
+ if (!isDragging) {
+ return;
+ }
e.preventDefault();
e.stopPropagation();
@@ -271,7 +286,7 @@ export function Dialog(props: IDialogProps) {
onCancel,
} = props;
- const { locale, mountContainer, direction, mobile } = useContext(ConfigContext);
+ const { locale, mountContainer, direction } = useContext(ConfigContext);
const { position, isDragging, setElementRef, handleMouseDown } = useDraggable({ defaultPosition, enabled: draggable });
@@ -315,15 +330,13 @@ export function Dialog(props: IDialogProps) {
onClose?.();
}
- const Content = mobile ? MobileDialogContent : DialogContent;
-
return (
<DialogProvider
open={open}
onOpenChange={handleOpenChange}
modal={mask !== false}
>
- <Content
+ <DialogContent
ref={handleContentRef}
className={clsx(className, {
'!univer-animate-none': draggable,
@@ -385,7 +398,7 @@ export function Dialog(props: IDialogProps) {
{footer}
</DialogFooter>
)}
- </Content>
+ </DialogContent>
</DialogProvider>
);
}
diff --git a/packages/design/src/components/dialog/DialogPrimitive.tsx b/packages/design/src/components/dialog/DialogPrimitive.tsx
index b4655e96fb..90338f35e9 100644
--- a/packages/design/src/components/dialog/DialogPrimitive.tsx
+++ b/packages/design/src/components/dialog/DialogPrimitive.tsx
@@ -127,6 +127,7 @@ const DialogFooter = ({
...props
}: HTMLAttributes<HTMLDivElement>) => (
<div
+ data-slot="dialog-footer"
className={clsx(
`
univer-flex univer-flex-col-reverse
diff --git a/packages/design/src/components/dialog/MobileDialog.tsx b/packages/design/src/components/dialog/MobileDialog.tsx
new file mode 100644
index 0000000000..2d84b82ef4
--- /dev/null
+++ b/packages/design/src/components/dialog/MobileDialog.tsx
@@ -0,0 +1,134 @@
+/**
+ * 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 { IDialogProps } from './Dialog';
+import { useContext } from 'react';
+import { clsx } from '../../helper/clsx';
+import { Button } from '../button/Button';
+import { ConfigContext } from '../config-provider/ConfigProvider';
+import {
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ Dialog as DialogProvider,
+ DialogTitle,
+} from './DialogPrimitive';
+
+export type IMobileDialogProps = IDialogProps;
+
+export function MobileDialog(props: IMobileDialogProps) {
+ const {
+ className,
+ overlayClassName,
+ children,
+ style,
+ open = false,
+ title,
+ footer: propFooter,
+ mask = true,
+ keyboard = true,
+ closable = true,
+ maskClosable = true,
+ showOk,
+ showCancel,
+ onOpenChange,
+ onClose,
+ onOk,
+ onCancel,
+ } = props;
+ const { locale, mountContainer, direction } = useContext(ConfigContext);
+ const maxHeight = globalThis.CSS?.supports('height', '1dvh') ? '80dvh' : '80vh';
+ const footer = propFooter ?? (showOk || showCancel
+ ? (
+ <div className="univer-flex univer-justify-end univer-gap-2">
+ {showCancel && <Button onClick={onCancel}>{locale?.Confirm.cancel}</Button>}
+ {showOk && <Button variant="primary" onClick={onOk}>{locale?.Confirm.confirm}</Button>}
+ </div>
+ )
+ : null);
+
+ function close() {
+ onOpenChange?.(false);
+ onClose?.();
+ }
+
+ function handleOpenChange(isOpen: boolean) {
+ if (!mask && !isOpen) {
+ return;
+ }
+
+ onOpenChange?.(isOpen);
+ if (!isOpen) {
+ onClose?.();
+ }
+ }
+
+ return (
+ <DialogProvider open={open} onOpenChange={handleOpenChange} modal={mask !== false}>
+ <DialogContent
+ className={clsx(`
+ !univer-bottom-0 !univer-left-0 !univer-right-0 !univer-top-auto !univer-max-w-none
+ !univer-translate-x-0 !univer-translate-y-0 !univer-gap-4 !univer-overflow-y-auto
+ !univer-rounded-t-2xl !univer-p-4
+ [&_[data-slot='dialog-footer']]:!univer-flex-row [&_[data-slot='dialog-footer']]:!univer-gap-3
+ [&_[data-slot='dialog-footer']_button]:!univer-h-12
+ [&_[data-slot='dialog-footer']_button]:!univer-flex-1
+ [&_button[data-slot='close']]:!univer-right-3 [&_button[data-slot='close']]:!univer-top-3
+ [&_button[data-slot='close']]:!univer-size-10
+ `, className)}
+ style={{
+ ...style,
+ position: 'fixed',
+ insetInline: 0,
+ top: 'auto',
+ bottom: 0,
+ width: '100%',
+ maxHeight,
+ maxWidth: 'none',
+ margin: 0,
+ transform: 'none',
+ }}
+ closable={closable}
+ mountContainer={mountContainer}
+ overlayClassName={overlayClassName}
+ dir={direction}
+ onClickClose={close}
+ onEscapeKeyDown={(event) => {
+ if (keyboard) {
+ close();
+ }
+ event.preventDefault();
+ }}
+ onPointerDownOutside={(event) => {
+ if (maskClosable) {
+ close();
+ }
+ event.preventDefault();
+ }}
+ >
+ <DialogHeader className={title ? undefined : '!univer-hidden'}>
+ <DialogTitle>{title}</DialogTitle>
+ <DialogDescription className="univer-hidden" />
+ </DialogHeader>
+
+ {children}
+
+ {footer && <DialogFooter>{footer}</DialogFooter>}
+ </DialogContent>
+ </DialogProvider>
+ );
+}
diff --git a/packages/design/src/components/dialog/MobileDialogContent.tsx b/packages/design/src/components/dialog/MobileDialogContent.tsx
deleted file mode 100644
index 82ec9b5da6..0000000000
--- a/packages/design/src/components/dialog/MobileDialogContent.tsx
+++ /dev/null
@@ -1,51 +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 type { ComponentProps, ComponentRef } from 'react';
-import { forwardRef } from 'react';
-import { clsx } from '../../helper/clsx';
-import { DialogContent } from './DialogPrimitive';
-
-export const MobileDialogContent = forwardRef<ComponentRef<typeof DialogContent>, ComponentProps<typeof DialogContent>>((props, ref) => {
- const { className, style, ...rest } = props;
-
- return (
- <DialogContent
- {...rest}
- ref={ref}
- className={clsx(`
- !univer-bottom-0 !univer-left-0 !univer-right-0 !univer-top-auto !univer-max-h-[80dvh] !univer-max-w-none
- !univer-translate-x-0 !univer-translate-y-0 !univer-gap-4 !univer-overflow-y-auto !univer-rounded-t-2xl
- !univer-p-4
- [&_[data-slot='dialog-footer']]:!univer-flex-row [&_[data-slot='dialog-footer']]:!univer-gap-3
- [&_[data-slot='dialog-footer']_button]:!univer-h-12 [&_[data-slot='dialog-footer']_button]:!univer-flex-1
- [&_button[data-slot='close']]:!univer-right-3 [&_button[data-slot='close']]:!univer-top-3
- [&_button[data-slot='close']]:!univer-size-10
- `, className)}
- style={{
- ...style,
- position: 'fixed',
- insetInline: 0,
- top: 'auto',
- bottom: 0,
- width: '100%',
- maxWidth: 'none',
- margin: 0,
- transform: 'none',
- }}
- />
- );
-});
diff --git a/packages/design/src/components/dialog/__tests__/MobileDialogContent.spec.tsx b/packages/design/src/components/dialog/__tests__/MobileDialogContent.spec.tsx
deleted file mode 100644
index 9404297cc0..0000000000
--- a/packages/design/src/components/dialog/__tests__/MobileDialogContent.spec.tsx
+++ /dev/null
@@ -1,39 +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 { cleanup, render, screen } from '@testing-library/react';
-import { afterEach, describe, expect, it } from 'vitest';
-import { Dialog as DialogProvider, DialogTitle } from '../DialogPrimitive';
-import { MobileDialogContent } from '../MobileDialogContent';
-import '@testing-library/jest-dom/vitest';
-
-afterEach(cleanup);
-
-describe('MobileDialogContent', () => {
- it('renders a full-width bottom surface', () => {
- render(
- <DialogProvider open>
- <MobileDialogContent>
- <DialogTitle>Mobile dialog</DialogTitle>
- </MobileDialogContent>
- </DialogProvider>
- );
-
- const dialog = screen.getByRole('dialog');
- expect(dialog).toHaveStyle({ bottom: '0px', position: 'fixed', width: '100%' });
- expect(dialog.className).toContain('!univer-rounded-t-2xl');
- });
-});
diff --git a/packages/design/src/components/dialog/__tests__/index.spec.tsx b/packages/design/src/components/dialog/__tests__/index.spec.tsx
index c1fca4dbac..a3e02edd9a 100644
--- a/packages/design/src/components/dialog/__tests__/index.spec.tsx
+++ b/packages/design/src/components/dialog/__tests__/index.spec.tsx
@@ -19,9 +19,13 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import enUS from '../../../locale/en-US';
import { ConfigProvider } from '../../config-provider/ConfigProvider';
import { Dialog } from '../Dialog';
+import { MobileDialog } from '../MobileDialog';
import '@testing-library/jest-dom/vitest';
-afterEach(cleanup);
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
describe('Dialog', () => {
it('should not render when open is false', () => {
@@ -140,4 +144,19 @@ describe('Dialog', () => {
mountContainer.remove();
});
+
+ it('should render a touch-first bottom surface from MobileDialog', () => {
+ vi.stubGlobal('CSS', { supports: () => false });
+ render(
+ <ConfigProvider locale={enUS.design} mountContainer={document.body}>
+ <MobileDialog open title="Mobile title" showOk>content</MobileDialog>
+ </ConfigProvider>
+ );
+
+ const dialog = document.querySelector('[role="dialog"]') as HTMLElement;
+ expect(dialog).toHaveClass('!univer-bottom-0');
+ expect(dialog).toHaveStyle({ bottom: '0px', position: 'fixed', width: '100%' });
+ expect(dialog.style.maxHeight).toBe('80vh');
+ expect(dialog.querySelector('[data-slot="dialog-footer"]')).toBeInTheDocument();
+ });
});
diff --git a/packages/design/src/components/dropdown-menu/DropdownMenu.tsx b/packages/design/src/components/dropdown-menu/DropdownMenu.tsx
index b1a73f7065..e1d4719a95 100644
--- a/packages/design/src/components/dropdown-menu/DropdownMenu.tsx
+++ b/packages/design/src/components/dropdown-menu/DropdownMenu.tsx
@@ -15,8 +15,7 @@
*/
import type { ComponentProps, ReactNode } from 'react';
-import { useContext, useState } from 'react';
-import { ConfigContext } from '../config-provider/ConfigProvider';
+import { useState } from 'react';
import {
DropdownMenuCheckboxItem,
DropdownMenuContent,
@@ -31,7 +30,6 @@ import {
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from './DropdownMenuPrimitive';
-import { MobileDropdownMenu } from './MobileDropdownMenu';
interface IDropdownMenuNormalItem {
type: 'item';
@@ -108,13 +106,14 @@ export function DropdownMenu(props: IDropdownMenuProps) {
} = props;
const [uncontrolledOpen, setUncontrolledOpen] = useState(false);
- const { mobile } = useContext(ConfigContext);
const isControlled = controlledOpen !== undefined;
const open = isControlled ? controlledOpen : uncontrolledOpen;
function handleChangeOpen(newOpen: boolean) {
- if (disabled) return;
+ if (disabled) {
+ return;
+ }
if (!isControlled) {
setUncontrolledOpen(newOpen);
@@ -210,19 +209,6 @@ export function DropdownMenu(props: IDropdownMenuProps) {
}
}
- if (mobile) {
- return (
- <MobileDropdownMenu
- open={open}
- disabled={disabled}
- items={items}
- onOpenChange={handleChangeOpen}
- >
- {children}
- </MobileDropdownMenu>
- );
- }
-
return (
<DropdownMenuPrimitive modal={false} open={open} onOpenChange={handleChangeOpen}>
<DropdownMenuTrigger asChild>
diff --git a/packages/design/src/components/dropdown-menu/MobileDropdownMenu.tsx b/packages/design/src/components/dropdown-menu/MobileDropdownMenu.tsx
index f02776d1a7..c8aa09222b 100644
--- a/packages/design/src/components/dropdown-menu/MobileDropdownMenu.tsx
+++ b/packages/design/src/components/dropdown-menu/MobileDropdownMenu.tsx
@@ -15,20 +15,30 @@
*/
import type { ReactNode } from 'react';
-import type { DropdownMenuType } from './DropdownMenu';
+import type { DropdownMenuType, IDropdownMenuProps } from './DropdownMenu';
+import { useState } from 'react';
import { clsx } from '../../helper/clsx';
import { MobileDropdownSurface } from '../dropdown/MobileDropdownSurface';
-interface IMobileDropdownMenuProps {
- children: ReactNode;
- items: DropdownMenuType[];
- disabled?: boolean;
- open: boolean;
- onOpenChange: (open: boolean) => void;
-}
+export type IMobileDropdownMenuProps = IDropdownMenuProps;
export function MobileDropdownMenu(props: IMobileDropdownMenuProps) {
- const { children, items, disabled, open, onOpenChange } = props;
+ const { children, items, disabled, open: controlledOpen, onOpenChange: controlledOnOpenChange } = props;
+ const [uncontrolledOpen, setUncontrolledOpen] = useState(false);
+ const isControlled = controlledOpen !== undefined;
+ const open = isControlled ? controlledOpen : uncontrolledOpen;
+
+ function handleChangeOpen(newOpen: boolean) {
+ if (disabled) {
+ return;
+ }
+
+ if (!isControlled) {
+ setUncontrolledOpen(newOpen);
+ }
+
+ controlledOnOpenChange?.(newOpen);
+ }
function renderMenuItem(item: DropdownMenuType, index: number): ReactNode {
if (item.type === 'separator') {
@@ -64,7 +74,7 @@ export function MobileDropdownMenu(props: IMobileDropdownMenuProps) {
className={mobileRowClassName(value === item.value)}
onClick={() => {
item.onSelect?.(value);
- onOpenChange(false);
+ handleChangeOpen(false);
}}
>
{option.label}
@@ -81,7 +91,7 @@ export function MobileDropdownMenu(props: IMobileDropdownMenuProps) {
className={clsx(mobileRowClassName(Boolean(item.checked)), item.className)}
onClick={() => {
item.onSelect?.(item.value);
- onOpenChange(false);
+ handleChangeOpen(false);
}}
>
{item.label}
@@ -99,7 +109,7 @@ export function MobileDropdownMenu(props: IMobileDropdownMenuProps) {
})}
onClick={() => {
item.onSelect?.(item);
- onOpenChange(false);
+ handleChangeOpen(false);
}}
>
{item.children}
@@ -120,7 +130,7 @@ export function MobileDropdownMenu(props: IMobileDropdownMenuProps) {
<MobileDropdownSurface
open={open}
disabled={disabled}
- onOpenChange={onOpenChange}
+ onOpenChange={handleChangeOpen}
content={<div className="univer-flex univer-flex-col univer-gap-2">{items.map(renderMenuItem)}</div>}
>
{children}
diff --git a/packages/design/src/components/dropdown-menu/__tests__/index.spec.tsx b/packages/design/src/components/dropdown-menu/__tests__/index.spec.tsx
index 81bea6dae7..c254bbae04 100644
--- a/packages/design/src/components/dropdown-menu/__tests__/index.spec.tsx
+++ b/packages/design/src/components/dropdown-menu/__tests__/index.spec.tsx
@@ -16,8 +16,8 @@
import { cleanup, fireEvent, render } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { ConfigProvider } from '../../config-provider/ConfigProvider';
import { DropdownMenu } from '../DropdownMenu';
+import { MobileDropdownMenu } from '../MobileDropdownMenu';
import '@testing-library/jest-dom/vitest';
afterEach(cleanup);
@@ -191,17 +191,16 @@ describe('DropdownMenu', () => {
).toThrow('[DropdownMenu]: `value` is required');
});
- it('should render full-width actionable rows under a mobile provider', () => {
+ it('should render full-width actionable rows from MobileDropdownMenu', () => {
const onSelect = vi.fn();
const { getByText } = render(
- <ConfigProvider mountContainer={document.body} mobile>
- <DropdownMenu
- open
- items={[{ type: 'item', children: 'Mobile item', onSelect }]}
- >
- <button type="button">Trigger</button>
- </DropdownMenu>
- </ConfigProvider>
+ <MobileDropdownMenu
+ open
+ items={[{ type: 'item', children: 'Mobile item', onSelect }]}
+ onOpenChange={() => {}}
+ >
+ <button type="button">Trigger</button>
+ </MobileDropdownMenu>
);
const item = getByText('Mobile item');
diff --git a/packages/design/src/components/dropdown/Dropdown.tsx b/packages/design/src/components/dropdown/Dropdown.tsx
index 5618c3cb9a..3050f44e7e 100644
--- a/packages/design/src/components/dropdown/Dropdown.tsx
+++ b/packages/design/src/components/dropdown/Dropdown.tsx
@@ -15,9 +15,7 @@
*/
import type { ComponentProps, ReactNode } from 'react';
-import { useContext, useState } from 'react';
-import { ConfigContext } from '../config-provider/ConfigProvider';
-import { MobileDropdownSurface } from './MobileDropdownSurface';
+import { useState } from 'react';
import { PopoverContent, PopoverPrimitive, PopoverTrigger } from './PopoverPrimitive';
export interface IDropdownProps extends ComponentProps<typeof PopoverContent> {
@@ -40,13 +38,14 @@ export function Dropdown(props: IDropdownProps) {
} = props;
const [uncontrolledOpen, setUncontrolledOpen] = useState(false);
- const { mobile } = useContext(ConfigContext);
const isControlled = controlledOpen !== undefined;
const open = isControlled ? controlledOpen : uncontrolledOpen;
function handleChangeOpen(newOpen: boolean) {
- if (disabled) return;
+ if (disabled) {
+ return;
+ }
if (!isControlled) {
setUncontrolledOpen(newOpen);
@@ -55,19 +54,6 @@ export function Dropdown(props: IDropdownProps) {
controlledOnOpenChange?.(newOpen);
}
- if (mobile) {
- return (
- <MobileDropdownSurface
- open={open}
- disabled={disabled}
- onOpenChange={handleChangeOpen}
- content={overlay}
- >
- {children}
- </MobileDropdownSurface>
- );
- }
-
return (
<PopoverPrimitive open={open} onOpenChange={handleChangeOpen}>
<PopoverTrigger asChild>
diff --git a/packages/design/src/components/dropdown/MobileDropdown.tsx b/packages/design/src/components/dropdown/MobileDropdown.tsx
new file mode 100644
index 0000000000..c2c0356762
--- /dev/null
+++ b/packages/design/src/components/dropdown/MobileDropdown.tsx
@@ -0,0 +1,62 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDropdownProps } from './Dropdown';
+import { createContext, useCallback, useState } from 'react';
+import { MobileDropdownSurface } from './MobileDropdownSurface';
+
+export type IMobileDropdownProps = IDropdownProps;
+
+export const MobileDropdownCloseContext = createContext<(() => void) | undefined>(undefined);
+
+export function MobileDropdown(props: IMobileDropdownProps) {
+ const {
+ children,
+ overlay,
+ disabled,
+ open: controlledOpen,
+ onOpenChange: controlledOnOpenChange,
+ } = props;
+ const [uncontrolledOpen, setUncontrolledOpen] = useState(false);
+ const isControlled = controlledOpen !== undefined;
+ const open = isControlled ? controlledOpen : uncontrolledOpen;
+
+ const handleChangeOpen = useCallback((newOpen: boolean) => {
+ if (disabled) {
+ return;
+ }
+
+ if (!isControlled) {
+ setUncontrolledOpen(newOpen);
+ }
+
+ controlledOnOpenChange?.(newOpen);
+ }, [controlledOnOpenChange, disabled, isControlled]);
+ const handleClose = useCallback(() => handleChangeOpen(false), [handleChangeOpen]);
+
+ return (
+ <MobileDropdownCloseContext.Provider value={handleClose}>
+ <MobileDropdownSurface
+ open={open}
+ disabled={disabled}
+ onOpenChange={handleChangeOpen}
+ content={overlay}
+ >
+ {children}
+ </MobileDropdownSurface>
+ </MobileDropdownCloseContext.Provider>
+ );
+}
diff --git a/packages/design/src/components/dropdown/MobileDropdownSurface.tsx b/packages/design/src/components/dropdown/MobileDropdownSurface.tsx
index bef36759ca..9e3956cc3a 100644
--- a/packages/design/src/components/dropdown/MobileDropdownSurface.tsx
+++ b/packages/design/src/components/dropdown/MobileDropdownSurface.tsx
@@ -34,6 +34,7 @@ export function MobileDropdownSurface(props: {
}) {
const { children, content, open, disabled, onOpenChange } = props;
const { locale, mountContainer } = useContext(ConfigContext);
+ const maxHeight = globalThis.CSS?.supports('height', '1dvh') ? '80dvh' : '80vh';
return (
<Dialog open={open} onOpenChange={onOpenChange} modal>
@@ -45,9 +46,8 @@ export function MobileDropdownSurface(props: {
overlayClassName="!univer-z-[1390]"
className="
!univer-bottom-0 !univer-left-0 !univer-right-0 !univer-top-auto !univer-z-[1400] !univer-block
- !univer-max-h-[80dvh] !univer-w-full !univer-max-w-none !univer-translate-x-0 !univer-translate-y-0
- !univer-overflow-y-auto !univer-rounded-t-2xl !univer-border-0 !univer-bg-gray-50 !univer-p-4
- !univer-pt-14
+ !univer-w-full !univer-max-w-none !univer-translate-x-0 !univer-translate-y-0 !univer-overflow-y-auto
+ !univer-rounded-t-2xl !univer-border-0 !univer-bg-gray-50 !univer-p-4 !univer-pt-14
dark:!univer-bg-gray-900
[&_button[data-slot='close']]:!univer-right-3 [&_button[data-slot='close']]:!univer-top-3
[&_button[data-slot='close']]:!univer-size-10
@@ -59,6 +59,7 @@ export function MobileDropdownSurface(props: {
top: 'auto',
bottom: 0,
width: '100%',
+ maxHeight,
maxWidth: 'none',
transform: 'none',
}}
diff --git a/packages/design/src/components/dropdown/__tests__/index.spec.tsx b/packages/design/src/components/dropdown/__tests__/index.spec.tsx
index f8a5bab6ca..8180d78752 100644
--- a/packages/design/src/components/dropdown/__tests__/index.spec.tsx
+++ b/packages/design/src/components/dropdown/__tests__/index.spec.tsx
@@ -23,8 +23,12 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import enUS from '../../../locale/en-US';
import { ConfigProvider } from '../../config-provider/ConfigProvider';
import { Dropdown } from '../Dropdown';
+import { MobileDropdown } from '../MobileDropdown';
-afterEach(cleanup);
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
describe('Dropdown', () => {
it('should render trigger and not show overlay by default', () => {
@@ -74,18 +78,20 @@ describe('Dropdown', () => {
expect(handleOpenChange).toHaveBeenCalled();
});
- it('should render a touch-first dialog surface under a mobile provider', () => {
+ it('should render a touch-first dialog surface from MobileDropdown', () => {
+ vi.stubGlobal('CSS', { supports: () => false });
render(
- <ConfigProvider locale={enUS.design} mountContainer={document.body} mobile>
- <Dropdown overlay={<div>Overlay Content</div>} open>
+ <ConfigProvider locale={enUS.design} mountContainer={document.body}>
+ <MobileDropdown overlay={<div>Overlay Content</div>} open>
<button type="button">Trigger</button>
- </Dropdown>
+ </MobileDropdown>
</ConfigProvider>
);
const dialog = screen.getByRole('dialog');
expect(dialog.textContent).toContain('Overlay Content');
expect(dialog.classList.contains('!univer-bottom-0')).toBe(true);
+ expect(dialog.style.maxHeight).toBe('80vh');
expect(screen.getByText(enUS.design.Accessibility.menu)).toBeTruthy();
});
});
diff --git a/packages/design/src/components/select/MobileSelect.tsx b/packages/design/src/components/select/MobileSelect.tsx
new file mode 100644
index 0000000000..854e049586
--- /dev/null
+++ b/packages/design/src/components/select/MobileSelect.tsx
@@ -0,0 +1,122 @@
+/**
+ * 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 { ReactNode } from 'react';
+import type { IMobileDropdownMenuProps } from '../dropdown-menu/MobileDropdownMenu';
+import type { ISelectProps } from './Select';
+import { MoreDownIcon } from '@univerjs/icons';
+import { useMemo, useState } from 'react';
+import { clsx } from '../../helper/clsx';
+import { MobileDropdownMenu } from '../dropdown-menu/MobileDropdownMenu';
+import { selectClassName } from './Select';
+
+interface IOptionSeparator {
+ type: 'separator';
+}
+
+const EMPTY_OPTIONS: NonNullable<ISelectProps['options']> = [];
+
+export type IMobileSelectProps = ISelectProps;
+
+export function MobileSelect(props: IMobileSelectProps) {
+ const {
+ className,
+ value,
+ disabled = false,
+ options = EMPTY_OPTIONS,
+ borderless = false,
+ onChange,
+ } = props;
+ const [open, setOpen] = useState(false);
+ const items: IMobileDropdownMenuProps['items'] = useMemo(() => {
+ const selectOptions: Array<IOptionSeparator | { label?: ReactNode; value: string; disabled?: boolean }> = [];
+
+ for (const option of options) {
+ if (option.options) {
+ for (const nestedOption of option.options) {
+ selectOptions.push({
+ label: nestedOption.label,
+ value: nestedOption.value!,
+ disabled: nestedOption.disabled,
+ });
+ }
+ selectOptions.push({ type: 'separator' });
+ } else {
+ selectOptions.push({
+ label: option.label,
+ value: option.value!,
+ disabled: option.disabled,
+ });
+ }
+ }
+
+ return [{
+ type: 'radio',
+ value,
+ hideIndicator: true,
+ options: selectOptions,
+ onSelect: onChange,
+ }];
+ }, [onChange, options, value]);
+ const displayValue = useMemo(() => {
+ for (const option of options) {
+ if (option.options) {
+ const nestedOption = option.options.find((item) => item.value === value);
+ if (nestedOption) {
+ return nestedOption.label || value;
+ }
+ } else if (option.value === value) {
+ return option.label || value;
+ }
+ }
+
+ return value;
+ }, [options, value]);
+
+ return (
+ <MobileDropdownMenu
+ open={open}
+ items={items}
+ disabled={disabled}
+ onOpenChange={setOpen}
+ >
+ <div
+ data-u-comp="mobile-select"
+ className={clsx(selectClassName, {
+ 'univer-border-primary-600 univer-outline-none univer-ring-2 univer-ring-primary-50 dark:!univer-ring-primary-900': open && !borderless,
+ 'univer-border-transparent univer-bg-transparent': borderless,
+ 'univer-cursor-not-allowed': disabled,
+ 'univer-cursor-pointer': !disabled,
+ }, className)}
+ >
+ <div
+ className="
+ univer-flex-1 univer-truncate univer-text-sm univer-text-gray-500
+ dark:!univer-text-gray-0
+ "
+ >
+ {displayValue}
+ </div>
+ <MoreDownIcon
+ className="
+ univer-flex-shrink-0
+ dark:!univer-text-gray-0
+ "
+ />
+ </div>
+ </MobileDropdownMenu>
+ );
+}
diff --git a/packages/design/src/components/select/__tests__/index.spec.tsx b/packages/design/src/components/select/__tests__/index.spec.tsx
index 0dad736d2d..7343855038 100644
--- a/packages/design/src/components/select/__tests__/index.spec.tsx
+++ b/packages/design/src/components/select/__tests__/index.spec.tsx
@@ -18,6 +18,7 @@ import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import enUS from '../../../locale/en-US';
import { ConfigProvider } from '../../config-provider/ConfigProvider';
+import { MobileSelect } from '../MobileSelect';
import { MultipleSelect } from '../MultipleSelect';
import { Select } from '../Select';
import '@testing-library/jest-dom/vitest';
@@ -35,6 +36,26 @@ const options = [
afterEach(cleanup);
describe('Select', () => {
+ it('should render mobile options in a touch-first dialog explicitly', () => {
+ const handleChange = vi.fn();
+ const { container } = render(
+ <ConfigProvider locale={enUS.design} mountContainer={document.body}>
+ <MobileSelect value="1" options={options} onChange={handleChange} />
+ </ConfigProvider>
+ );
+
+ fireEvent.click(container.querySelector('[data-u-comp="mobile-select"]') as HTMLElement);
+ expect(screen.getByRole('dialog')).toBeInTheDocument();
+ fireEvent.click(screen.getByText('Option 2'));
+ expect(handleChange).toHaveBeenCalledWith('2');
+ });
+
+ it('should fall back to the mobile select value when its option label is empty', () => {
+ render(<MobileSelect value="fallback" options={[{ label: '', value: 'fallback' }]} onChange={() => {}} />);
+
+ expect(screen.getByText('fallback')).toBeInTheDocument();
+ });
+
it('should render with value', () => {
const { getByText } = render(<Select value="1" options={options} onChange={() => {}} />);
expect(getByText('Option 1')).toBeInTheDocument();
diff --git a/packages/design/src/components/tooltip/Tooltip.tsx b/packages/design/src/components/tooltip/Tooltip.tsx
index 35576c7082..0116fcd4ac 100644
--- a/packages/design/src/components/tooltip/Tooltip.tsx
+++ b/packages/design/src/components/tooltip/Tooltip.tsx
@@ -72,14 +72,14 @@ export function Tooltip(props: ITooltipProps) {
onVisibleChange,
} = props;
- const { direction, disableTooltips } = useContext(ConfigContext);
+ const { direction } = useContext(ConfigContext);
// Internal state for uncontrolled mode
const [uncontrolledVisible, setUncontrolledVisible] = useState(false);
// Determine whether the tooltip is controlled or uncontrolled
const isControlled = controlledVisible !== undefined;
- const visible = !disableTooltips && (isControlled ? controlledVisible : uncontrolledVisible);
+ const visible = isControlled ? controlledVisible : uncontrolledVisible;
const triggerRef = useRef<HTMLElement | null>(null);
const tooltipRef = useRef<HTMLDivElement | null>(null);
@@ -93,8 +93,6 @@ export function Tooltip(props: ITooltipProps) {
}
function showTooltip() {
- if (disableTooltips) return;
-
if (isControlled) {
onVisibleChange?.(true);
} else {
@@ -103,8 +101,6 @@ export function Tooltip(props: ITooltipProps) {
}
function hideTooltip() {
- if (disableTooltips) return;
-
if (isControlled) {
onVisibleChange?.(false);
} else {
diff --git a/packages/design/src/components/tooltip/__tests__/index.spec.tsx b/packages/design/src/components/tooltip/__tests__/index.spec.tsx
index 8b5bfd707f..574730c874 100644
--- a/packages/design/src/components/tooltip/__tests__/index.spec.tsx
+++ b/packages/design/src/components/tooltip/__tests__/index.spec.tsx
@@ -16,7 +16,6 @@
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { ConfigProvider } from '../../config-provider/ConfigProvider';
import { Tooltip } from '../Tooltip';
import '@testing-library/jest-dom/vitest';
@@ -89,26 +88,6 @@ describe('Tooltip', () => {
expect(onVisibleChange).toHaveBeenCalledWith(false);
});
- it('should stay hidden when tooltips are disabled by the config provider', () => {
- const onVisibleChange = vi.fn();
- render(
- <ConfigProvider mountContainer={document.body} disableTooltips>
- <ConfigProvider mountContainer={document.body}>
- <Tooltip title="Disabled tip" visible={false} onVisibleChange={onVisibleChange}>
- Trigger
- </Tooltip>
- </ConfigProvider>
- </ConfigProvider>
- );
-
- const trigger = screen.getByText('Trigger');
- fireEvent.mouseEnter(trigger);
- fireEvent.focus(trigger);
-
- expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();
- expect(onVisibleChange).not.toHaveBeenCalled();
- });
-
it('should support non-asChild trigger and focus/blur events', async () => {
render(
<Tooltip title="From button" asChild={false}>
diff --git a/packages/design/src/index.ts b/packages/design/src/index.ts
index b591272b05..5821122f38 100644
--- a/packages/design/src/index.ts
+++ b/packages/design/src/index.ts
@@ -20,6 +20,8 @@ export { Accordion } from './components/accordion/Accordion';
export type { IAccordionProps } from './components/accordion/Accordion';
export { ActionRow } from './components/action-row/ActionRow';
export type { IActionRowProps } from './components/action-row/ActionRow';
+export { MobileActionRowGroup } from './components/action-row/MobileActionRowGroup';
+export type { IMobileActionRowGroupProps } from './components/action-row/MobileActionRowGroup';
export { Avatar } from './components/avatar/Avatar';
export type { IAvatarProps } from './components/avatar/Avatar';
export { Badge } from './components/badge/Badge';
@@ -41,6 +43,8 @@ export type { IColorPickerProps } from './components/color-picker/ColorPicker';
export { ColorPickerPanel } from './components/color-picker/ColorPickerPanel';
export type { IColorPickerPanelProps } from './components/color-picker/ColorPickerPanel';
export { ColorPresets } from './components/color-picker/ColorPresets';
+export { MobileColorPicker } from './components/color-picker/MobileColorPicker';
+export type { IMobileColorPickerProps } from './components/color-picker/MobileColorPicker';
export { MobileColorPresets } from './components/color-picker/MobileColorPresets';
export type { IMobileColorPresetsProps } from './components/color-picker/MobileColorPresets';
export {
@@ -57,16 +61,24 @@ export { ConfigContext, ConfigProvider } from './components/config-provider/Conf
export type { IConfigProviderProps } from './components/config-provider/ConfigProvider';
export { Confirm } from './components/confirm/Confirm';
export type { IConfirmProps } from './components/confirm/Confirm';
+export { MobileConfirm } from './components/confirm/MobileConfirm';
+export type { IMobileConfirmProps } from './components/confirm/MobileConfirm';
export { DatePicker } from './components/date-picker/DatePicker';
export { DateRangePicker } from './components/date-range-picker';
export { Dialog } from './components/dialog/Dialog';
export type { IDialogProps } from './components/dialog/Dialog';
+export { MobileDialog } from './components/dialog/MobileDialog';
+export type { IMobileDialogProps } from './components/dialog/MobileDialog';
export { DraggableList } from './components/draggable-list';
export type { IDraggableListProps } from './components/draggable-list';
export { DropdownMenu } from './components/dropdown-menu/DropdownMenu';
export type { IDropdownMenuProps } from './components/dropdown-menu/DropdownMenu';
+export { MobileDropdownMenu } from './components/dropdown-menu/MobileDropdownMenu';
+export type { IMobileDropdownMenuProps } from './components/dropdown-menu/MobileDropdownMenu';
export { Dropdown } from './components/dropdown/Dropdown';
export type { IDropdownProps } from './components/dropdown/Dropdown';
+export { MobileDropdown } from './components/dropdown/MobileDropdown';
+export type { IMobileDropdownProps } from './components/dropdown/MobileDropdown';
export { FormDualColumnLayout, FormLayout } from './components/form-layout';
export type { IFormDualColumnLayoutProps, IFormLayoutProps } from './components/form-layout';
export { Gallery } from './components/gallery/Gallery';
@@ -103,6 +115,8 @@ export type { IRadioProps } from './components/radio/Radio';
export { Segmented } from './components/segmented/Segmented';
export { SelectList } from './components/select-list/SelectList';
export type { ISelectListProps } from './components/select-list/SelectList';
+export { MobileSelect } from './components/select/MobileSelect';
+export type { IMobileSelectProps } from './components/select/MobileSelect';
export { MultipleSelect } from './components/select/MultipleSelect';
export type { IMultipleSelectProps } from './components/select/MultipleSelect';
export { Select, selectClassName } from './components/select/Select';
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 ea2f53c5bf..d9a1114ba4 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
@@ -1415,6 +1415,22 @@ describe('DocSelectionRenderService', () => {
]);
});
+ it('preserves the browser composing DOM until composition ends', () => {
+ const { input, renderUnit, univer } = createRealSelectionRenderService();
+ cleanup.push(() => renderUnit.dispose(), () => univer.dispose());
+
+ input.textContent = 'n';
+ input.dispatchEvent(new CompositionEvent('compositionstart', { bubbles: true, data: '' }));
+ expect(input.textContent).toBe('n');
+
+ input.textContent = '你';
+ input.dispatchEvent(new CompositionEvent('compositionupdate', { bubbles: true, data: '你' }));
+ expect(input.textContent).toBe('你');
+
+ input.dispatchEvent(new CompositionEvent('compositionend', { bubbles: true, data: '你' }));
+ expect(input.textContent).toBe('');
+ });
+
it('keeps embed-owned select-all keydown inside the child editor without blocking editor input handling', () => {
const { input, renderUnit, service, univer } = createRealSelectionRenderService();
cleanup.push(() => renderUnit.dispose(), () => univer.dispose());
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 3ea292ee18..bde37dcd26 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
@@ -1459,7 +1459,7 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
this._eventHandle(e, (config) => {
this._onCompositionstart$.next(config);
- });
+ }, true);
})
);
@@ -1484,7 +1484,7 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
this._eventHandle(e, (config) => {
this._onInputBefore$.next(config);
this._onCompositionupdate$.next(config);
- });
+ }, true);
})
);
@@ -1530,10 +1530,16 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
);
}
- private _eventHandle(e: Event | CompositionEvent | KeyboardEvent, func: (config: IEditorInputConfig) => void) {
+ private _eventHandle(
+ e: Event | CompositionEvent | KeyboardEvent,
+ func: (config: IEditorInputConfig) => void,
+ preserveInput = false
+ ) {
const content = this._input.textContent || '';
- this._input.innerHTML = '';
+ if (!preserveInput) {
+ this._input.innerHTML = '';
+ }
// Geometry remains on the previous page until the edited page is ready.
// Continue native input from the existing logical selection only while
diff --git a/packages/drawing-ui/src/controllers/components.controller.ts b/packages/drawing-ui/src/controllers/components.controller.ts
index 5f270602fd..e965e33810 100644
--- a/packages/drawing-ui/src/controllers/components.controller.ts
+++ b/packages/drawing-ui/src/controllers/components.controller.ts
@@ -27,7 +27,9 @@ import {
UngroupIcon,
} from '@univerjs/icons';
import { ComponentManager, IconManager } from '@univerjs/ui';
-import { COMPONENT_IMAGE_POPUP_MENU } from '../views/image-popup-menu/component-name';
+import {
+ COMPONENT_IMAGE_POPUP_MENU,
+} from '../views/image-popup-menu/component-name';
import { ImagePopupMenu } from '../views/image-popup-menu/ImagePopupMenu';
export class ComponentsController extends Disposable {
diff --git a/packages/drawing-ui/src/controllers/mobile/components.controller.ts b/packages/drawing-ui/src/controllers/mobile/components.controller.ts
new file mode 100644
index 0000000000..f588abf912
--- /dev/null
+++ b/packages/drawing-ui/src/controllers/mobile/components.controller.ts
@@ -0,0 +1,53 @@
+/**
+ * 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 { Disposable, Inject } from '@univerjs/core';
+import {
+ BottomIcon,
+ CropIcon,
+ DeleteIcon,
+ DocSettingIcon,
+ GroupIcon,
+ MoveDownIcon,
+ MoveUpIcon,
+ TopmostIcon,
+ UngroupIcon,
+} from '@univerjs/icons';
+import { ComponentManager, IconManager } from '@univerjs/ui';
+import { COMPONENT_MOBILE_IMAGE_POPUP_MENU } from '../../views/image-popup-menu/component-name';
+import { MobileImagePopupMenu } from '../../views/image-popup-menu/MobileImagePopupMenu';
+
+export class MobileComponentsController extends Disposable {
+ constructor(
+ @Inject(ComponentManager) componentManager: ComponentManager,
+ @Inject(IconManager) iconManager: IconManager
+ ) {
+ super();
+
+ this.disposeWithMe(componentManager.register(COMPONENT_MOBILE_IMAGE_POPUP_MENU, MobileImagePopupMenu));
+ this.disposeWithMe(iconManager.register({
+ BottomIcon,
+ DrawingCropIcon: CropIcon,
+ DrawingDeleteIcon: DeleteIcon,
+ DrawingEditIcon: DocSettingIcon,
+ GroupIcon,
+ MoveDownIcon,
+ MoveUpIcon,
+ TopmostIcon,
+ UngroupIcon,
+ }));
+ }
+}
diff --git a/packages/drawing-ui/src/index.ts b/packages/drawing-ui/src/index.ts
index 77d8120dbf..d078a1fc0b 100644
--- a/packages/drawing-ui/src/index.ts
+++ b/packages/drawing-ui/src/index.ts
@@ -44,6 +44,7 @@ export {
insertGroupObject,
} from './controllers/utils';
export { menuSchema as DrawingUIMenuSchema } from './menu/schema';
+export { UniverDrawingMobileUIPlugin } from './mobile-plugin';
export { UniverDrawingUIPlugin } from './plugin';
export { DrawingImageClipService, IMAGE_CLIP_SHAPE_PICKER_COMPONENT } from './services/drawing-image-clip.service';
export type { ImageShapeClipDelegate } from './services/drawing-image-clip.service';
@@ -60,7 +61,10 @@ export {
} from './utils/clipboard-image';
export { getUpdateParams } from './utils/get-update-params';
export { ImageCropperObject } from './views/crop/image-cropper-object';
-export { COMPONENT_IMAGE_POPUP_MENU } from './views/image-popup-menu/component-name';
+export {
+ COMPONENT_IMAGE_POPUP_MENU,
+ COMPONENT_MOBILE_IMAGE_POPUP_MENU,
+} from './views/image-popup-menu/component-name';
export {
getObjectListPanelSectionIdForDrawingType,
isFloatingObjectListDrawingType,
diff --git a/packages/drawing-ui/src/mobile-plugin.ts b/packages/drawing-ui/src/mobile-plugin.ts
new file mode 100644
index 0000000000..36498690e3
--- /dev/null
+++ b/packages/drawing-ui/src/mobile-plugin.ts
@@ -0,0 +1,77 @@
+/**
+ * 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 { Dependency } from '@univerjs/core';
+import type { IUniverDrawingUIConfig } from './config/config';
+import { DependentOn, IConfigService, Inject, Injector, merge, Plugin } from '@univerjs/core';
+import { UniverDrawingPlugin } from '@univerjs/drawing';
+import { UniverRenderEnginePlugin } from '@univerjs/engine-render';
+import pkg from '../package.json';
+import { defaultPluginConfig, DRAWING_UI_PLUGIN_CONFIG_KEY } from './config/config';
+import { DrawingUpdateController } from './controllers/drawing-update.controller';
+import { ImageCropperController } from './controllers/image-cropper.controller';
+import { ImageUpdateController } from './controllers/image-update.controller';
+import { MobileComponentsController } from './controllers/mobile/components.controller';
+import { DrawingUIController } from './controllers/ui.controller';
+import { DrawingImageClipService } from './services/drawing-image-clip.service';
+import { DrawingRenderService } from './services/drawing-render.service';
+
+@DependentOn(UniverDrawingPlugin, UniverRenderEnginePlugin)
+export class UniverDrawingMobileUIPlugin extends Plugin {
+ static override pluginName = 'UNIVER_DRAWING_UI_PLUGIN';
+ static override packageName = pkg.name;
+ static override version = pkg.version;
+
+ constructor(
+ private readonly _config: Partial<IUniverDrawingUIConfig> = defaultPluginConfig,
+ @Inject(Injector) protected readonly _injector: Injector,
+ @IConfigService private readonly _configService: IConfigService
+ ) {
+ super();
+
+ const { menu, ...rest } = merge({}, defaultPluginConfig, this._config);
+ if (menu) {
+ this._configService.setConfig('menu', menu, { merge: true });
+ }
+ this._configService.setConfig(DRAWING_UI_PLUGIN_CONFIG_KEY, rest);
+ }
+
+ override onStarting(): void {
+ this._injector.add([MobileComponentsController]);
+ this._injector.get(MobileComponentsController);
+ this._initDependencies();
+ }
+
+ override onRendered(): void {
+ this._injector.get(DrawingUpdateController);
+ this._injector.get(DrawingUIController);
+ this._injector.get(ImageCropperController);
+ this._injector.get(ImageUpdateController);
+ }
+
+ private _initDependencies(): void {
+ const dependencies: Dependency[] = [
+ [DrawingImageClipService],
+ [DrawingRenderService],
+ [DrawingUpdateController],
+ [DrawingUIController],
+ [ImageCropperController],
+ [ImageUpdateController],
+ ];
+
+ dependencies.forEach((dependency) => this._injector.add(dependency));
+ }
+}
diff --git a/packages/drawing-ui/src/views/image-popup-menu/ImagePopupMenu.tsx b/packages/drawing-ui/src/views/image-popup-menu/ImagePopupMenu.tsx
index c36496c5ba..2abf527477 100644
--- a/packages/drawing-ui/src/views/image-popup-menu/ImagePopupMenu.tsx
+++ b/packages/drawing-ui/src/views/image-popup-menu/ImagePopupMenu.tsx
@@ -25,16 +25,15 @@ import {
PositionedObjectLayoutType,
UniverInstanceType,
} from '@univerjs/core';
-import { borderClassName, clsx, ConfigContext, Dropdown, DropdownMenu, Separator, Tooltip } from '@univerjs/design';
+import { borderClassName, clsx, Dropdown, DropdownMenu, Separator, Tooltip } from '@univerjs/design';
import {
AutofillDoubleIcon,
ChartIcon,
MoreDownIcon,
TextWrapShapeIcon,
} from '@univerjs/icons';
-import { IconManager, IDialogService, useDependency } from '@univerjs/ui';
-import { useContext, useState } from 'react';
-import { MobileImagePopupMenu } from './MobileImagePopupMenu';
+import { IconManager, useDependency } from '@univerjs/ui';
+import { useState } from 'react';
export interface IImagePopupMenuItem {
label: string;
@@ -56,7 +55,6 @@ export interface IImagePopupMenuExtraProps {
unitId?: string;
subUnitId?: string;
drawingId?: string;
- dialogId?: string;
}
export interface IImagePopupMenuProps {
@@ -71,8 +69,6 @@ export function ImagePopupMenu(props: IImagePopupMenuProps) {
const menuItems = popup?.extraProps?.menuItems;
const commandService = useDependency(ICommandService);
const localeService = useDependency(LocaleService);
- const dialogService = useDependency(IDialogService);
- const { mobile } = useContext(ConfigContext);
const [visible, setVisible] = useState(false);
const [isHovered, setIsHovered] = useState(false);
@@ -98,21 +94,6 @@ export function ImagePopupMenu(props: IImagePopupMenuProps) {
return <DocChartFloatingToolbar menuItems={menuItems} />;
}
- if (mobile) {
- return (
- <MobileImagePopupMenu
- menuItems={menuItems}
- getLabel={(item) => localeService.t(item.label)}
- onSelect={async (item) => {
- await commandService.executeCommand(item.commandId, item.commandParams);
- if (popup.extraProps?.dialogId) {
- dialogService.close(popup.extraProps.dialogId);
- }
- }}
- />
- );
- }
-
const handleMouseEnter = () => {
setIsHovered(true);
};
diff --git a/packages/drawing-ui/src/views/image-popup-menu/MobileImagePopupMenu.tsx b/packages/drawing-ui/src/views/image-popup-menu/MobileImagePopupMenu.tsx
index da7b457407..016e18850f 100644
--- a/packages/drawing-ui/src/views/image-popup-menu/MobileImagePopupMenu.tsx
+++ b/packages/drawing-ui/src/views/image-popup-menu/MobileImagePopupMenu.tsx
@@ -14,20 +14,38 @@
* limitations under the License.
*/
-import type { IImagePopupMenuItem } from './ImagePopupMenu';
+import type { IImagePopupMenuExtraProps, IImagePopupMenuItem } from './ImagePopupMenu';
+import { ICommandService, LocaleService } from '@univerjs/core';
import { MobileActionRow } from '@univerjs/design';
+import { IDialogService, useDependency } from '@univerjs/ui';
interface IMobileImagePopupMenuProps {
- menuItems: IImagePopupMenuItem[];
- getLabel: (item: IImagePopupMenuItem) => string;
- onSelect: (item: IImagePopupMenuItem) => void;
+ popup: {
+ extraProps?: Pick<IImagePopupMenuExtraProps, 'menuItems'> & { dialogId?: string };
+ };
}
-export function MobileImagePopupMenu({ menuItems, getLabel, onSelect }: IMobileImagePopupMenuProps) {
+export function MobileImagePopupMenu({ popup }: IMobileImagePopupMenuProps) {
+ const menuItems = popup?.extraProps?.menuItems;
+ const commandService = useDependency(ICommandService);
+ const localeService = useDependency(LocaleService);
+ const dialogService = useDependency(IDialogService);
+
+ if (!menuItems) {
+ return null;
+ }
+
+ const handleSelect = async (item: IImagePopupMenuItem) => {
+ await commandService.executeCommand(item.commandId, item.commandParams);
+ if (popup.extraProps?.dialogId) {
+ dialogService.close(popup.extraProps.dialogId);
+ }
+ };
+
return (
<div className="univer-flex univer-flex-col univer-gap-2">
{menuItems.map((item) => {
- const label = getLabel(item);
+ const label = localeService.t(item.label);
return (
<MobileActionRow
@@ -36,7 +54,7 @@ export function MobileImagePopupMenu({ menuItems, getLabel, onSelect }: IMobileI
aria-label={label}
variant="subtle"
disabled={item.disable}
- onClick={() => onSelect(item)}
+ onClick={() => handleSelect(item)}
/>
);
})}
diff --git a/packages/drawing-ui/src/views/image-popup-menu/component-name.ts b/packages/drawing-ui/src/views/image-popup-menu/component-name.ts
index 4c9a047c8c..b3480e6d41 100644
--- a/packages/drawing-ui/src/views/image-popup-menu/component-name.ts
+++ b/packages/drawing-ui/src/views/image-popup-menu/component-name.ts
@@ -15,3 +15,4 @@
*/
export const COMPONENT_IMAGE_POPUP_MENU = 'COMPONENT_IMAGE_POPUP_MENU';
+export const COMPONENT_MOBILE_IMAGE_POPUP_MENU = 'COMPONENT_MOBILE_IMAGE_POPUP_MENU';
diff --git a/packages/engine-render/src/__tests__/scene.input-manager.spec.ts b/packages/engine-render/src/__tests__/scene.input-manager.spec.ts
new file mode 100644
index 0000000000..58433fdcf7
--- /dev/null
+++ b/packages/engine-render/src/__tests__/scene.input-manager.spec.ts
@@ -0,0 +1,68 @@
+/**
+ * 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 { afterEach, describe, expect, it, vi } from 'vitest';
+import { DeviceType } from '../basics/i-events';
+import { InputManager } from '../scene.input-manager';
+
+function createScene() {
+ return {
+ onDblclick$: { emitEvent: vi.fn() },
+ onPointerUp$: { emitEvent: vi.fn() },
+ onTripleClick$: { emitEvent: vi.fn() },
+ pick: vi.fn(() => null),
+ };
+}
+
+function createPointerUpEvent(clientX: number, deviceType: DeviceType) {
+ return {
+ button: 0,
+ clientX,
+ clientY: 20,
+ deviceType,
+ offsetX: clientX,
+ offsetY: 20,
+ pointerId: 1,
+ };
+}
+
+describe('InputManager double click recognition', () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('allows natural finger drift between two touch taps', () => {
+ vi.useFakeTimers();
+ const scene = createScene();
+ const inputManager = new InputManager(scene as never);
+
+ inputManager._onPointerUp(createPointerUpEvent(20, DeviceType.Touch) as never);
+ inputManager._onPointerUp(createPointerUpEvent(26, DeviceType.Touch) as never);
+
+ expect(scene.onDblclick$.emitEvent).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps the precise double-click threshold for mouse input', () => {
+ vi.useFakeTimers();
+ const scene = createScene();
+ const inputManager = new InputManager(scene as never);
+
+ inputManager._onPointerUp(createPointerUpEvent(20, DeviceType.Mouse) as never);
+ inputManager._onPointerUp(createPointerUpEvent(26, DeviceType.Mouse) as never);
+
+ expect(scene.onDblclick$.emitEvent).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/engine-render/src/scene.input-manager.ts b/packages/engine-render/src/scene.input-manager.ts
index 8052a5d7c5..ecdaecc5b7 100644
--- a/packages/engine-render/src/scene.input-manager.ts
+++ b/packages/engine-render/src/scene.input-manager.ts
@@ -35,6 +35,9 @@ export class InputManager extends Disposable {
/** Time in milliseconds with two consecutive clicks will be considered as a double or triple click */
static DoubleClickDelay = 500; // in milliseconds
+ /** The allowed distance between two consecutive touch taps. */
+ static TouchDoubleClickMovementThreshold = 10; // in pixels
+
static TripleClickDelay = 300; // in milliseconds
/** If you need to check double click without raising a single click at first click, enable this flag */
@@ -279,7 +282,7 @@ export class InputManager extends Disposable {
const engine = this._scene.getEngine();
if (!engine) return;
- // eslint-disable-next-line complexity, max-lines-per-function
+ // eslint-disable-next-line complexity
this._onInput$ = engine.onInputChanged$.subscribeEvent((eventData: IEvent) => {
const evt: IEvent = eventData;
// Pointer Events
@@ -445,17 +448,20 @@ export class InputManager extends Disposable {
* @hidden
* @returns Boolean if delta for pointer exceeds drag movement threshold
*/
- private _isPointerSwiping(pointerX: number, pointerY: number): boolean {
+ private _isPointerSwiping(pointerX: number, pointerY: number, threshold = InputManager.DragMovementThreshold): boolean {
return (
- Math.abs(this._startingPosition.x - pointerX) > InputManager.DragMovementThreshold ||
- Math.abs(this._startingPosition.y - pointerY) > InputManager.DragMovementThreshold
+ Math.abs(this._startingPosition.x - pointerX) > threshold ||
+ Math.abs(this._startingPosition.y - pointerY) > threshold
);
}
private _prePointerDoubleOrTripleClick(evt: IPointerEvent) {
const { clientX, clientY } = evt;
+ const movementThreshold = evt.deviceType === DeviceType.Touch
+ ? InputManager.TouchDoubleClickMovementThreshold
+ : InputManager.DragMovementThreshold;
- const isMoveThreshold = this._isPointerSwiping(clientX, clientY);
+ const isMoveThreshold = this._isPointerSwiping(clientX, clientY, movementThreshold);
if (isMoveThreshold) {
this._resetDoubleClickParam();
diff --git a/packages/find-replace/src/commands/operations/__tests__/find-replace.operation.spec.ts b/packages/find-replace/src/commands/operations/__tests__/find-replace.operation.spec.ts
index 347ca32464..7067f90bb8 100644
--- a/packages/find-replace/src/commands/operations/__tests__/find-replace.operation.spec.ts
+++ b/packages/find-replace/src/commands/operations/__tests__/find-replace.operation.spec.ts
@@ -21,6 +21,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createTestBed } from '../../../__tests__/create-test-bed';
import { FindReplaceService, IFindReplaceService } from '../../../services/find-replace.service';
import {
+ CloseFindDialogOperation,
FocusSelectionOperation,
GoToNextMatchOperation,
GoToPreviousMatchOperation,
@@ -55,6 +56,7 @@ describe('find-replace.operation', () => {
const commandService = get(ICommandService);
[
+ CloseFindDialogOperation,
OpenFindDialogOperation,
OpenReplaceDialogOperation,
GoToNextMatchOperation,
@@ -125,4 +127,16 @@ describe('find-replace.operation', () => {
expect(previousSpy).toHaveBeenCalledTimes(1);
expect(focusSpy).toHaveBeenCalledTimes(1);
});
+
+ it('should terminate the current session when closing the find UI', () => {
+ const commandService = get(ICommandService);
+ const service = get(IFindReplaceService);
+ service.registerFindReplaceProvider(createProvider());
+ service.start();
+ const terminateSpy = vi.spyOn(service, 'terminate');
+
+ expect(commandService.syncExecuteCommand(CloseFindDialogOperation.id)).toBe(true);
+ expect(terminateSpy).toHaveBeenCalledTimes(1);
+ expect(service.revealed).toBe(false);
+ });
});
diff --git a/packages/find-replace/src/commands/operations/find-replace.operation.ts b/packages/find-replace/src/commands/operations/find-replace.operation.ts
index 1d52879694..e5fd3f654b 100644
--- a/packages/find-replace/src/commands/operations/find-replace.operation.ts
+++ b/packages/find-replace/src/commands/operations/find-replace.operation.ts
@@ -50,6 +50,15 @@ export const OpenReplaceDialogOperation: IOperation = {
},
};
+export const CloseFindDialogOperation: IOperation = {
+ id: 'ui.operation.close-find-dialog',
+ type: CommandType.OPERATION,
+ handler: (accessor) => {
+ accessor.get(IFindReplaceService).terminate();
+ return true;
+ },
+};
+
export const GoToNextMatchOperation: IOperation = {
type: CommandType.OPERATION,
id: 'ui.operation.go-to-next-match',
diff --git a/packages/find-replace/src/const.ts b/packages/find-replace/src/const.ts
new file mode 100644
index 0000000000..c4967ee026
--- /dev/null
+++ b/packages/find-replace/src/const.ts
@@ -0,0 +1,18 @@
+/**
+ * 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.
+ */
+
+export const MOBILE_FIND_REPLACE_SETTINGS_COMPONENT = 'MobileFindReplaceSettings';
+export const MOBILE_FIND_REPLACE_SETTINGS_DIALOG_ID = 'MOBILE_FIND_REPLACE_SETTINGS_DIALOG';
diff --git a/packages/find-replace/src/controllers/find-replace.controller.ts b/packages/find-replace/src/controllers/find-replace.controller.ts
index e2115392f8..81466c5f87 100644
--- a/packages/find-replace/src/controllers/find-replace.controller.ts
+++ b/packages/find-replace/src/controllers/find-replace.controller.ts
@@ -28,6 +28,7 @@ import { IDialogService, ILayoutService, IMenuManagerService, IShortcutService }
import { takeUntil } from 'rxjs';
import { ReplaceAllMatchesCommand, ReplaceCurrentMatchCommand } from '../commands/commands/replace.command';
import {
+ CloseFindDialogOperation,
FocusSelectionOperation,
GoToNextMatchOperation,
GoToPreviousMatchOperation,
@@ -80,6 +81,7 @@ export class FindReplaceController extends RxDisposable {
[
OpenFindDialogOperation,
OpenReplaceDialogOperation,
+ CloseFindDialogOperation,
GoToNextMatchOperation,
GoToPreviousMatchOperation,
ReplaceAllMatchesCommand,
@@ -108,6 +110,8 @@ export class FindReplaceController extends RxDisposable {
this._findReplaceService.stateUpdates$.pipe(takeUntil(this.dispose$)).subscribe((newState) => {
if (newState.revealed === true) {
this._openPanel();
+ } else if (newState.revealed === false) {
+ this._closePanel(false);
}
});
}
@@ -138,6 +142,10 @@ export class FindReplaceController extends RxDisposable {
private _closingListenerDisposable: Nullable<IDisposable>;
closePanel(): void {
+ this._closePanel(true);
+ }
+
+ private _closePanel(terminateSession: boolean): void {
if (!this._closingListenerDisposable) {
return;
}
@@ -146,7 +154,9 @@ export class FindReplaceController extends RxDisposable {
this._closingListenerDisposable = null;
this._dialogService.close(FIND_REPLACE_DIALOG_ID);
- this._findReplaceService.terminate();
+ if (terminateSession) {
+ this._findReplaceService.terminate();
+ }
queueMicrotask(() => this._layoutService.focus());
}
diff --git a/packages/find-replace/src/controllers/mobile/components.controller.ts b/packages/find-replace/src/controllers/mobile/components.controller.ts
new file mode 100644
index 0000000000..7acf1af789
--- /dev/null
+++ b/packages/find-replace/src/controllers/mobile/components.controller.ts
@@ -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 { Disposable, Inject } from '@univerjs/core';
+import { SearchIcon } from '@univerjs/icons';
+import { ComponentManager, IconManager } from '@univerjs/ui';
+import { MOBILE_FIND_REPLACE_SETTINGS_COMPONENT } from '../../const';
+import { MobileFindReplaceSettings } from '../../views/mobile/MobileFindReplaceSettings';
+
+export class MobileComponentsController extends Disposable {
+ constructor(
+ @Inject(ComponentManager) componentManager: ComponentManager,
+ @Inject(IconManager) iconManager: IconManager
+ ) {
+ super();
+
+ this.disposeWithMe(iconManager.register({ SearchIcon }));
+ this.disposeWithMe(componentManager.register(
+ MOBILE_FIND_REPLACE_SETTINGS_COMPONENT,
+ MobileFindReplaceSettings
+ ));
+ }
+}
diff --git a/packages/find-replace/src/controllers/mobile/find-replace.controller.ts b/packages/find-replace/src/controllers/mobile/find-replace.controller.ts
new file mode 100644
index 0000000000..785f7cf48e
--- /dev/null
+++ b/packages/find-replace/src/controllers/mobile/find-replace.controller.ts
@@ -0,0 +1,84 @@
+/**
+ * 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 { ICommandService, Inject, Injector, IUniverInstanceService, RxDisposable } from '@univerjs/core';
+import { BuiltInUIPart, connectInjector, IDialogService, IMenuManagerService, IUIPartsService } from '@univerjs/ui';
+import { takeUntil } from 'rxjs';
+import { ReplaceAllMatchesCommand, ReplaceCurrentMatchCommand } from '../../commands/commands/replace.command';
+import {
+ CloseFindDialogOperation,
+ FocusSelectionOperation,
+ GoToNextMatchOperation,
+ GoToPreviousMatchOperation,
+ OpenFindDialogOperation,
+ OpenReplaceDialogOperation,
+} from '../../commands/operations/find-replace.operation';
+import { MOBILE_FIND_REPLACE_SETTINGS_DIALOG_ID } from '../../const';
+import { mobileMenuSchema } from '../../menu/mobile-schema';
+import { IFindReplaceService } from '../../services/find-replace.service';
+import { MobileFindReplaceBar } from '../../views/mobile/MobileFindReplaceBar';
+
+export class FindReplaceMobileController extends RxDisposable {
+ constructor(
+ @Inject(Injector) injector: Injector,
+ @ICommandService commandService: ICommandService,
+ @IDialogService dialogService: IDialogService,
+ @IFindReplaceService findReplaceService: IFindReplaceService,
+ @IMenuManagerService menuManagerService: IMenuManagerService,
+ @IUniverInstanceService univerInstanceService: IUniverInstanceService,
+ @IUIPartsService uiPartsService: IUIPartsService
+ ) {
+ super();
+
+ [
+ OpenFindDialogOperation,
+ OpenReplaceDialogOperation,
+ CloseFindDialogOperation,
+ GoToNextMatchOperation,
+ GoToPreviousMatchOperation,
+ ReplaceAllMatchesCommand,
+ ReplaceCurrentMatchCommand,
+ FocusSelectionOperation,
+ ].forEach((command) => this.disposeWithMe(commandService.registerCommand(command)));
+
+ menuManagerService.mergeMenu(mobileMenuSchema);
+ this.disposeWithMe(uiPartsService.registerComponent(
+ BuiltInUIPart.FOOTER,
+ () => connectInjector(MobileFindReplaceBar, injector)
+ ));
+
+ findReplaceService.stateUpdates$.pipe(takeUntil(this.dispose$)).subscribe((state) => {
+ if (state.revealed === false) {
+ dialogService.close(MOBILE_FIND_REPLACE_SETTINGS_DIALOG_ID);
+ }
+ });
+
+ let sessionUnitId: string | null = null;
+ findReplaceService.stateUpdates$.pipe(takeUntil(this.dispose$)).subscribe((state) => {
+ if (state.revealed === true) {
+ sessionUnitId = univerInstanceService.getFocusedUnit()?.getUnitId() ?? null;
+ } else if (state.revealed === false) {
+ sessionUnitId = null;
+ }
+ });
+
+ univerInstanceService.focused$.pipe(takeUntil(this.dispose$)).subscribe((focused) => {
+ if (sessionUnitId && focused !== sessionUnitId) {
+ findReplaceService.terminate();
+ }
+ });
+ }
+}
diff --git a/packages/find-replace/src/index.ts b/packages/find-replace/src/index.ts
index d1d97f7187..b3e4962604 100644
--- a/packages/find-replace/src/index.ts
+++ b/packages/find-replace/src/index.ts
@@ -18,6 +18,7 @@ import './global.css';
export { ReplaceAllMatchesCommand, ReplaceCurrentMatchCommand } from './commands/commands/replace.command';
export {
+ CloseFindDialogOperation,
GoToNextMatchOperation,
GoToPreviousMatchOperation,
OpenFindDialogOperation,
@@ -26,6 +27,7 @@ export {
export type { IUniverFindReplaceConfig } from './config/config';
export { FindReplaceController } from './controllers/find-replace.controller';
export { menuSchema as FindReplaceMenuSchema } from './menu/schema';
+export { UniverFindReplaceMobileUIPlugin } from './mobile-plugin';
export { UniverFindReplacePlugin } from './plugin';
export type {
IFindComplete,
diff --git a/packages/find-replace/src/locale/ar-SA.ts b/packages/find-replace/src/locale/ar-SA.ts
index db6c848c3b..81aba3766f 100644
--- a/packages/find-replace/src/locale/ar-SA.ts
+++ b/packages/find-replace/src/locale/ar-SA.ts
@@ -19,6 +19,13 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'find-replace': {
toolbar: 'بحث واستبدال',
+ mobile: {
+ settings: 'إعدادات البحث والاستبدال',
+ 'settings-title': 'إعدادات البحث والاستبدال',
+ 'previous-match': 'التطابق السابق',
+ 'next-match': 'التطابق التالي',
+ close: 'إغلاق البحث والاستبدال',
+ },
shortcut: {
'open-find-dialog': 'فتح مربع حوار البحث',
'open-replace-dialog': 'فتح مربع حوار الاستبدال',
diff --git a/packages/find-replace/src/locale/ca-ES.ts b/packages/find-replace/src/locale/ca-ES.ts
index 9b3d58d022..f7108dac7b 100644
--- a/packages/find-replace/src/locale/ca-ES.ts
+++ b/packages/find-replace/src/locale/ca-ES.ts
@@ -19,6 +19,13 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'find-replace': {
toolbar: 'Cerca i reemplaça',
+ mobile: {
+ settings: 'Configuració de cerca i reemplaçament',
+ 'settings-title': 'Configuració de cerca i reemplaçament',
+ 'previous-match': 'Coincidència anterior',
+ 'next-match': 'Coincidència següent',
+ close: 'Tanca la cerca i el reemplaçament',
+ },
shortcut: {
'open-find-dialog': 'Obrir el diàleg de cerca',
'open-replace-dialog': 'Obrir el diàleg de reemplaçament',
diff --git a/packages/find-replace/src/locale/de-DE.ts b/packages/find-replace/src/locale/de-DE.ts
index d8b3e75a7f..d68ca109d6 100644
--- a/packages/find-replace/src/locale/de-DE.ts
+++ b/packages/find-replace/src/locale/de-DE.ts
@@ -19,6 +19,13 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'find-replace': {
toolbar: 'Suchen & Ersetzen',
+ mobile: {
+ settings: 'Einstellungen für Suchen und Ersetzen',
+ 'settings-title': 'Suchen-und-Ersetzen-Einstellungen',
+ 'previous-match': 'Vorheriger Treffer',
+ 'next-match': 'Nächster Treffer',
+ close: 'Suchen und Ersetzen schließen',
+ },
shortcut: {
'open-find-dialog': 'Suchdialog öffnen',
'open-replace-dialog': 'Ersetzungsdialog öffnen',
diff --git a/packages/find-replace/src/locale/en-US.ts b/packages/find-replace/src/locale/en-US.ts
index 0b1b52ade6..15b52131b8 100644
--- a/packages/find-replace/src/locale/en-US.ts
+++ b/packages/find-replace/src/locale/en-US.ts
@@ -17,6 +17,13 @@
const locale = {
'find-replace': {
toolbar: 'Find & Replace',
+ mobile: {
+ settings: 'Find and replace settings',
+ 'settings-title': 'Find and Replace Settings',
+ 'previous-match': 'Previous match',
+ 'next-match': 'Next match',
+ close: 'Close find and replace',
+ },
shortcut: {
'open-find-dialog': 'Open Find Dialog',
'open-replace-dialog': 'Open Replace Dialog',
diff --git a/packages/find-replace/src/locale/es-ES.ts b/packages/find-replace/src/locale/es-ES.ts
index 7cdbca6e0a..3868834f34 100644
--- a/packages/find-replace/src/locale/es-ES.ts
+++ b/packages/find-replace/src/locale/es-ES.ts
@@ -19,6 +19,13 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'find-replace': {
toolbar: 'Buscar y reemplazar',
+ mobile: {
+ settings: 'Configuración de buscar y reemplazar',
+ 'settings-title': 'Configuración de buscar y reemplazar',
+ 'previous-match': 'Coincidencia anterior',
+ 'next-match': 'Coincidencia siguiente',
+ close: 'Cerrar buscar y reemplazar',
+ },
shortcut: {
'open-find-dialog': 'Abrir cuadro de diálogo de búsqueda',
'open-replace-dialog': 'Abrir cuadro de diálogo de reemplazo',
diff --git a/packages/find-replace/src/locale/fa-IR.ts b/packages/find-replace/src/locale/fa-IR.ts
index e946c3ae19..f22cf22d39 100644
--- a/packages/find-replace/src/locale/fa-IR.ts
+++ b/packages/find-replace/src/locale/fa-IR.ts
@@ -19,6 +19,13 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'find-replace': {
toolbar: 'یافتن و جایگزینی',
+ mobile: {
+ settings: 'تنظیمات یافتن و جایگزینی',
+ 'settings-title': 'تنظیمات یافتن و جایگزینی',
+ 'previous-match': 'مطابقت قبلی',
+ 'next-match': 'مطابقت بعدی',
+ close: 'بستن یافتن و جایگزینی',
+ },
shortcut: {
'open-find-dialog': 'باز کردن پنجره جستجو',
'open-replace-dialog': 'باز کردن پنجره جایگزینی',
diff --git a/packages/find-replace/src/locale/fr-FR.ts b/packages/find-replace/src/locale/fr-FR.ts
index abfa445af2..d80b9d69ad 100644
--- a/packages/find-replace/src/locale/fr-FR.ts
+++ b/packages/find-replace/src/locale/fr-FR.ts
@@ -19,6 +19,13 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'find-replace': {
toolbar: 'Rechercher & Remplacer',
+ mobile: {
+ settings: 'Paramètres de recherche et de remplacement',
+ 'settings-title': 'Paramètres de recherche et de remplacement',
+ 'previous-match': 'Occurrence précédente',
+ 'next-match': 'Occurrence suivante',
+ close: 'Fermer la recherche et le remplacement',
+ },
shortcut: {
'open-find-dialog': 'Ouvrir la boîte de dialogue de recherche',
'open-replace-dialog': 'Ouvrir la boîte de dialogue de remplacement',
diff --git a/packages/find-replace/src/locale/id-ID.ts b/packages/find-replace/src/locale/id-ID.ts
index b3d39cf390..8aed1f5003 100644
--- a/packages/find-replace/src/locale/id-ID.ts
+++ b/packages/find-replace/src/locale/id-ID.ts
@@ -19,6 +19,13 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'find-replace': {
toolbar: 'Cari & Ganti',
+ mobile: {
+ settings: 'Pengaturan cari dan ganti',
+ 'settings-title': 'Pengaturan Cari dan Ganti',
+ 'previous-match': 'Kecocokan sebelumnya',
+ 'next-match': 'Kecocokan berikutnya',
+ close: 'Tutup cari dan ganti',
+ },
shortcut: {
'open-find-dialog': 'Buka Dialog Cari',
'open-replace-dialog': 'Buka Dialog Ganti',
diff --git a/packages/find-replace/src/locale/it-IT.ts b/packages/find-replace/src/locale/it-IT.ts
index 46b771880b..a8edee4473 100644
--- a/packages/find-replace/src/locale/it-IT.ts
+++ b/packages/find-replace/src/locale/it-IT.ts
@@ -19,6 +19,13 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'find-replace': {
toolbar: 'Trova e sostituisci',
+ mobile: {
+ settings: 'Impostazioni trova e sostituisci',
+ 'settings-title': 'Impostazioni Trova e sostituisci',
+ 'previous-match': 'Corrispondenza precedente',
+ 'next-match': 'Corrispondenza successiva',
+ close: 'Chiudi trova e sostituisci',
+ },
shortcut: {
'open-find-dialog': 'Apri finestra Trova',
'open-replace-dialog': 'Apri finestra Sostituisci',
diff --git a/packages/find-replace/src/locale/ja-JP.ts b/packages/find-replace/src/locale/ja-JP.ts
index 36ca554c70..36b70ecb01 100644
--- a/packages/find-replace/src/locale/ja-JP.ts
+++ b/packages/find-replace/src/locale/ja-JP.ts
@@ -19,6 +19,13 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'find-replace': {
toolbar: '検索と置換',
+ mobile: {
+ settings: '検索と置換の設定',
+ 'settings-title': '検索と置換の設定',
+ 'previous-match': '前の一致項目',
+ 'next-match': '次の一致項目',
+ close: '検索と置換を閉じる',
+ },
shortcut: {
'open-find-dialog': '検索ダイアログを開く',
'open-replace-dialog': '置換ダイアログを開く',
diff --git a/packages/find-replace/src/locale/ko-KR.ts b/packages/find-replace/src/locale/ko-KR.ts
index 143191263a..d7890b3514 100644
--- a/packages/find-replace/src/locale/ko-KR.ts
+++ b/packages/find-replace/src/locale/ko-KR.ts
@@ -19,6 +19,13 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'find-replace': {
toolbar: '찾기 및 바꾸기',
+ mobile: {
+ settings: '찾기 및 바꾸기 설정',
+ 'settings-title': '찾기 및 바꾸기 설정',
+ 'previous-match': '이전 일치 항목',
+ 'next-match': '다음 일치 항목',
+ close: '찾기 및 바꾸기 닫기',
+ },
shortcut: {
'open-find-dialog': '찾기 대화 상자 열기',
'open-replace-dialog': '바꾸기 대화 상자 열기',
diff --git a/packages/find-replace/src/locale/pl-PL.ts b/packages/find-replace/src/locale/pl-PL.ts
index 93c962b3f0..5094a3a49f 100644
--- a/packages/find-replace/src/locale/pl-PL.ts
+++ b/packages/find-replace/src/locale/pl-PL.ts
@@ -19,6 +19,13 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'find-replace': {
toolbar: 'Znajdź i zamień',
+ mobile: {
+ settings: 'Ustawienia znajdowania i zamiany',
+ 'settings-title': 'Ustawienia znajdowania i zamiany',
+ 'previous-match': 'Poprzednie dopasowanie',
+ 'next-match': 'Następne dopasowanie',
+ close: 'Zamknij znajdowanie i zamianę',
+ },
shortcut: {
'open-find-dialog': 'Otwórz okno Znajdź',
'open-replace-dialog': 'Otwórz okno Zamień',
diff --git a/packages/find-replace/src/locale/pt-BR.ts b/packages/find-replace/src/locale/pt-BR.ts
index 1b592d141f..097c48c62c 100644
--- a/packages/find-replace/src/locale/pt-BR.ts
+++ b/packages/find-replace/src/locale/pt-BR.ts
@@ -19,6 +19,13 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'find-replace': {
toolbar: 'Localizar e Substituir',
+ mobile: {
+ settings: 'Configurações de localizar e substituir',
+ 'settings-title': 'Configurações de Localizar e Substituir',
+ 'previous-match': 'Correspondência anterior',
+ 'next-match': 'Próxima correspondência',
+ close: 'Fechar localizar e substituir',
+ },
shortcut: {
'open-find-dialog': 'Abrir Caixa de Localização',
'open-replace-dialog': 'Abrir Caixa de Substituição',
diff --git a/packages/find-replace/src/locale/ru-RU.ts b/packages/find-replace/src/locale/ru-RU.ts
index 36d1087f5b..aa371caa91 100644
--- a/packages/find-replace/src/locale/ru-RU.ts
+++ b/packages/find-replace/src/locale/ru-RU.ts
@@ -19,6 +19,13 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'find-replace': {
toolbar: 'Найти и заменить',
+ mobile: {
+ settings: 'Настройки поиска и замены',
+ 'settings-title': 'Настройки поиска и замены',
+ 'previous-match': 'Предыдущее совпадение',
+ 'next-match': 'Следующее совпадение',
+ close: 'Закрыть поиск и замену',
+ },
shortcut: {
'open-find-dialog': 'Открыть диалоговое окно поиска',
'open-replace-dialog': 'Открыть диалоговое окно замены',
diff --git a/packages/find-replace/src/locale/sk-SK.ts b/packages/find-replace/src/locale/sk-SK.ts
index 948165fd5c..3bcce49517 100644
--- a/packages/find-replace/src/locale/sk-SK.ts
+++ b/packages/find-replace/src/locale/sk-SK.ts
@@ -19,6 +19,13 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'find-replace': {
toolbar: 'Hľadať a nahradiť',
+ mobile: {
+ settings: 'Nastavenia hľadania a nahrádzania',
+ 'settings-title': 'Nastavenia hľadania a nahrádzania',
+ 'previous-match': 'Predchádzajúca zhoda',
+ 'next-match': 'Nasledujúca zhoda',
+ close: 'Zavrieť hľadanie a nahrádzanie',
+ },
shortcut: {
'open-find-dialog': 'Otvoriť dialógové okno hľadania',
'open-replace-dialog': 'Otvoriť dialógové okno nahradenia',
diff --git a/packages/find-replace/src/locale/vi-VN.ts b/packages/find-replace/src/locale/vi-VN.ts
index 30fd65adcb..ff314be08f 100644
--- a/packages/find-replace/src/locale/vi-VN.ts
+++ b/packages/find-replace/src/locale/vi-VN.ts
@@ -19,6 +19,13 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'find-replace': {
toolbar: 'Tìm kiếm và Thay thế',
+ mobile: {
+ settings: 'Cài đặt tìm kiếm và thay thế',
+ 'settings-title': 'Cài đặt Tìm kiếm và Thay thế',
+ 'previous-match': 'Kết quả trước',
+ 'next-match': 'Kết quả tiếp theo',
+ close: 'Đóng tìm kiếm và thay thế',
+ },
shortcut: {
'open-find-dialog': 'Mở hộp thoại Tìm kiếm',
'open-replace-dialog': 'Mở hộp thoại Thay thế',
diff --git a/packages/find-replace/src/locale/zh-CN.ts b/packages/find-replace/src/locale/zh-CN.ts
index 51807999e7..5799d2f9fb 100644
--- a/packages/find-replace/src/locale/zh-CN.ts
+++ b/packages/find-replace/src/locale/zh-CN.ts
@@ -19,6 +19,13 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'find-replace': {
toolbar: '查找替换',
+ mobile: {
+ settings: '查找替换设置',
+ 'settings-title': '查找替换设置',
+ 'previous-match': '上一个匹配项',
+ 'next-match': '下一个匹配项',
+ close: '关闭查找替换',
+ },
shortcut: {
'open-find-dialog': '打开查找对话框',
'open-replace-dialog': '打开替换对话框',
diff --git a/packages/find-replace/src/locale/zh-HK.ts b/packages/find-replace/src/locale/zh-HK.ts
index 631c9a88c7..d484ddf0dd 100644
--- a/packages/find-replace/src/locale/zh-HK.ts
+++ b/packages/find-replace/src/locale/zh-HK.ts
@@ -19,6 +19,13 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'find-replace': {
toolbar: '尋找替換',
+ mobile: {
+ settings: '尋找替換設定',
+ 'settings-title': '尋找替換設定',
+ 'previous-match': '上一個符合項目',
+ 'next-match': '下一個符合項目',
+ close: '關閉尋找替換',
+ },
shortcut: {
'open-find-dialog': '打開尋找對話框',
'open-replace-dialog': '打開取代對話框',
diff --git a/packages/find-replace/src/locale/zh-TW.ts b/packages/find-replace/src/locale/zh-TW.ts
index 631c9a88c7..d484ddf0dd 100644
--- a/packages/find-replace/src/locale/zh-TW.ts
+++ b/packages/find-replace/src/locale/zh-TW.ts
@@ -19,6 +19,13 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'find-replace': {
toolbar: '尋找替換',
+ mobile: {
+ settings: '尋找替換設定',
+ 'settings-title': '尋找替換設定',
+ 'previous-match': '上一個符合項目',
+ 'next-match': '下一個符合項目',
+ close: '關閉尋找替換',
+ },
shortcut: {
'open-find-dialog': '打開尋找對話框',
'open-replace-dialog': '打開取代對話框',
diff --git a/packages/find-replace/src/menu/mobile-schema.ts b/packages/find-replace/src/menu/mobile-schema.ts
new file mode 100644
index 0000000000..c7bb2d349d
--- /dev/null
+++ b/packages/find-replace/src/menu/mobile-schema.ts
@@ -0,0 +1,29 @@
+/**
+ * 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 { MenuSchemaType } from '@univerjs/ui';
+import { RibbonDataGroup } from '@univerjs/ui';
+import { OpenFindDialogOperation } from '../commands/operations/find-replace.operation';
+import { FindReplaceMenuItemFactory } from './find-replace.menu';
+
+export const mobileMenuSchema: MenuSchemaType = {
+ [RibbonDataGroup.ORGANIZATION]: {
+ [OpenFindDialogOperation.id]: {
+ order: 2,
+ menuItemFactory: FindReplaceMenuItemFactory,
+ },
+ },
+};
diff --git a/packages/find-replace/src/mobile-plugin.ts b/packages/find-replace/src/mobile-plugin.ts
new file mode 100644
index 0000000000..3179d0b48a
--- /dev/null
+++ b/packages/find-replace/src/mobile-plugin.ts
@@ -0,0 +1,56 @@
+/**
+ * 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 { Dependency } from '@univerjs/core';
+import type { IUniverFindReplaceConfig } from './config/config';
+import { DependentOn, IConfigService, Inject, Injector, merge, Plugin } from '@univerjs/core';
+import { UniverMobileUIPlugin } from '@univerjs/ui';
+import pkg from '../package.json';
+import { defaultPluginConfig, FIND_REPLACE_PLUGIN_CONFIG_KEY } from './config/config';
+import { MobileComponentsController } from './controllers/mobile/components.controller';
+import { FindReplaceMobileController } from './controllers/mobile/find-replace.controller';
+import { FindReplaceService, IFindReplaceService } from './services/find-replace.service';
+
+@DependentOn(UniverMobileUIPlugin)
+export class UniverFindReplaceMobileUIPlugin extends Plugin {
+ static override pluginName = 'UNIVER_FIND_REPLACE_PLUGIN';
+ static override packageName = pkg.name;
+ static override version = pkg.version;
+
+ constructor(
+ private readonly _config: Partial<IUniverFindReplaceConfig> = defaultPluginConfig,
+ @Inject(Injector) override readonly _injector: Injector,
+ @IConfigService private readonly _configService: IConfigService
+ ) {
+ super();
+
+ const { ...rest } = merge({}, defaultPluginConfig, this._config);
+ this._configService.setConfig(FIND_REPLACE_PLUGIN_CONFIG_KEY, rest);
+ }
+
+ override onStarting(): void {
+ this._injector.add([MobileComponentsController]);
+ this._injector.get(MobileComponentsController);
+ ([
+ [FindReplaceMobileController],
+ [IFindReplaceService, { useClass: FindReplaceService }],
+ ] as Dependency[]).forEach((dependency) => this._injector.add(dependency));
+ }
+
+ override onRendered(): void {
+ this._injector.get(FindReplaceMobileController);
+ }
+}
diff --git a/packages/find-replace/src/services/__tests__/find-replace.service.spec.ts b/packages/find-replace/src/services/__tests__/find-replace.service.spec.ts
index 7e4720ea79..a0f9335835 100644
--- a/packages/find-replace/src/services/__tests__/find-replace.service.spec.ts
+++ b/packages/find-replace/src/services/__tests__/find-replace.service.spec.ts
@@ -260,6 +260,22 @@ describe('FindReplaceService', () => {
service.dispose();
});
+ it('should hide replacement controls without terminating the find session', () => {
+ const { service, contextService } = createService();
+
+ expect(service.start(true)).toBe(true);
+ service.changeInputtingFindString('invoice');
+ service.hideReplace();
+
+ expect(service.revealed).toBe(true);
+ expect(service.replaceRevealed).toBe(false);
+ expect(service.getFindString()).toBe('invoice');
+ expect(contextService.values.at(-1)?.value).toBe(false);
+
+ service.terminate();
+ service.dispose();
+ });
+
it('should navigate across find models when the current unit has no next or previous match', async () => {
const { service, provider } = createService();
const match1: IFindMatch = { provider: 'p', unitId: 'u1', range: { row: 1 }, replaceable: true } as any;
diff --git a/packages/find-replace/src/services/find-replace.service.ts b/packages/find-replace/src/services/find-replace.service.ts
index 8e8eb3479d..c52945fc20 100644
--- a/packages/find-replace/src/services/find-replace.service.ts
+++ b/packages/find-replace/src/services/find-replace.service.ts
@@ -163,6 +163,7 @@ export interface IFindReplaceService {
focusFindInput(): void;
revealReplace(): void;
+ hideReplace(): void;
changeFindString(value: string): void;
changeInputtingFindString(value: string): void;
changeReplaceString(value: string): void;
@@ -877,6 +878,14 @@ export class FindReplaceService extends Disposable implements IFindReplaceServic
this._toggleRevealReplace(true);
}
+ hideReplace(): void {
+ this._state.changeState({
+ replaceRevealed: false,
+ findString: this._state.inputtingFindString,
+ });
+ this._toggleRevealReplace(false);
+ }
+
focusSelection(): void {
this._model?.focusSelection();
}
diff --git a/packages/find-replace/src/views/mobile/MobileFindReplaceBar.tsx b/packages/find-replace/src/views/mobile/MobileFindReplaceBar.tsx
new file mode 100644
index 0000000000..b3baf00338
--- /dev/null
+++ b/packages/find-replace/src/views/mobile/MobileFindReplaceBar.tsx
@@ -0,0 +1,309 @@
+/**
+ * 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 { ReactNode } from 'react';
+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 { ReplaceAllMatchesCommand, ReplaceCurrentMatchCommand } from '../../commands/commands/replace.command';
+import {
+ CloseFindDialogOperation,
+ GoToNextMatchOperation,
+ GoToPreviousMatchOperation,
+} from '../../commands/operations/find-replace.operation';
+import {
+ MOBILE_FIND_REPLACE_SETTINGS_COMPONENT,
+ MOBILE_FIND_REPLACE_SETTINGS_DIALOG_ID,
+} from '../../const';
+import { IFindReplaceService } from '../../services/find-replace.service';
+
+const SEARCH_DEBOUNCE_TIME = 500;
+
+export function MobileFindReplaceBar() {
+ const findReplaceService = useDependency(IFindReplaceService);
+ useObservable(findReplaceService.state$, undefined, true);
+
+ if (!findReplaceService.revealed) {
+ return null;
+ }
+
+ return <MobileFindReplaceBarContent />;
+}
+
+function MobileFindReplaceBarContent() {
+ const commandService = useDependency(ICommandService);
+ const dialogService = useDependency(IDialogService);
+ const findReplaceService = useDependency(IFindReplaceService);
+ const localeService = useDependency(LocaleService);
+ const state = useObservable(findReplaceService.state$, undefined, true);
+ const currentMatch = useObservable(findReplaceService.currentMatch$, null, true);
+ const replaceables = useObservable(findReplaceService.replaceables$, [], true);
+ const [findValue, setFindValue] = useState(() =>
+ state.replaceRevealed ? state.inputtingFindString : state.findString);
+ const inputRef = useRef<HTMLInputElement>(null);
+ const searchTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const suppressNextFocusRef = useRef(false);
+
+ useEffect(() => {
+ const frame = requestAnimationFrame(() => inputRef.current?.focus());
+ return () => cancelAnimationFrame(frame);
+ }, []);
+
+ useEffect(() => {
+ const subscription = findReplaceService.focusSignal$.subscribe(() => {
+ if (suppressNextFocusRef.current) {
+ suppressNextFocusRef.current = false;
+ return;
+ }
+
+ inputRef.current?.focus();
+ });
+ return () => subscription.unsubscribe();
+ }, [findReplaceService]);
+
+ useEffect(() => () => {
+ if (searchTimerRef.current) {
+ clearTimeout(searchTimerRef.current);
+ }
+ }, []);
+
+ function clearSearchTimer(): void {
+ if (searchTimerRef.current) {
+ clearTimeout(searchTimerRef.current);
+ searchTimerRef.current = null;
+ }
+ }
+
+ function commitSearch(value: string): void {
+ clearSearchTimer();
+ if (!value) {
+ findReplaceService.changeInputtingFindString('');
+ return;
+ }
+
+ if (findReplaceService.replaceRevealed) {
+ findReplaceService.changeInputtingFindString(value);
+ findReplaceService.changeFindString(value);
+ findReplaceService.find();
+ return;
+ }
+
+ findReplaceService.changeFindString(value);
+ }
+
+ function scheduleSearch(value: string): void {
+ clearSearchTimer();
+ if (!value) {
+ commitSearch(value);
+ return;
+ }
+
+ searchTimerRef.current = setTimeout(() => commitSearch(value), SEARCH_DEBOUNCE_TIME);
+ }
+
+ function blurActiveElement(): void {
+ if (document.activeElement instanceof HTMLElement) {
+ document.activeElement.blur();
+ }
+ }
+
+ function executeAfterBlur(commandId: string, suppressFocusSignal = false): void {
+ blurActiveElement();
+ if (findValue !== state.findString) {
+ commitSearch(findValue);
+ if (commandId === GoToNextMatchOperation.id || commandId === GoToPreviousMatchOperation.id) {
+ return;
+ }
+ }
+
+ suppressNextFocusRef.current = suppressFocusSignal;
+ const execution = commandService.executeCommand(commandId);
+ suppressNextFocusRef.current = false;
+ execution.catch(() => undefined);
+ }
+
+ function openSettings(): void {
+ commitSearch(findValue);
+ blurActiveElement();
+ dialogService.open({
+ id: MOBILE_FIND_REPLACE_SETTINGS_DIALOG_ID,
+ title: { title: localeService.t<LocaleKey>('find-replace.mobile.settings-title') },
+ children: { label: MOBILE_FIND_REPLACE_SETTINGS_COMPONENT },
+ });
+ }
+
+ const noResult = state.findCompleted && state.matchesCount === 0;
+ const resultText = noResult
+ ? localeService.t<LocaleKey>('find-replace.dialog.no-result')
+ : state.matchesCount > 0 ? `${state.matchesPosition}/${state.matchesCount}` : undefined;
+ const navigationDisabled = state.matchesCount === 0;
+ const replaceDisabled = state.matchesCount === 0 || !currentMatch?.replaceable;
+ const replaceAllDisabled = replaceables.length === 0;
+
+ return (
+ <div
+ data-u-comp="mobile-find-replace-bar"
+ className="
+ univer-fixed univer-inset-x-0 univer-z-40 univer-grid univer-gap-2 univer-bg-gray-0 univer-px-2
+ univer-pt-1.5 univer-shadow-[0_-4px_16px_rgba(0,0,0,0.08)]
+ dark:!univer-bg-gray-800
+ "
+ style={{
+ bottom: 'var(--univer-mobile-keyboard-inset, 0px)',
+ paddingBottom: 'calc(6px + env(safe-area-inset-bottom, 0px))',
+ }}
+ >
+ <div className="univer-flex">
+ <IconButton
+ label={localeService.t<LocaleKey>('find-replace.mobile.settings')}
+ onClick={openSettings}
+ >
+ <ConfigureTabIcon />
+ </IconButton>
+ <div className="univer-relative univer-mr-2 univer-min-w-0 univer-flex-1">
+ <SearchIcon
+ className="
+ univer-pointer-events-none univer-absolute univer-left-3 univer-top-1/2 univer-z-10
+ univer-size-5 -univer-translate-y-1/2 univer-text-gray-500
+ "
+ />
+ <Input
+ ref={inputRef}
+ size="middle"
+ allowClear
+ value={findValue}
+ placeholder={localeService.t<LocaleKey>('find-replace.dialog.find-placeholder')}
+ inputClass="!univer-pl-10"
+ slot={resultText
+ ? <span className="univer-text-xs univer-text-gray-400">{resultText}</span>
+ : undefined}
+ onChange={(value) => {
+ setFindValue(value);
+ scheduleSearch(value);
+ }}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter') {
+ executeAfterBlur(GoToNextMatchOperation.id);
+ }
+ }}
+ />
+ </div>
+ <IconButton
+ disabled={navigationDisabled}
+ label={localeService.t<LocaleKey>('find-replace.mobile.previous-match')}
+ onClick={() => executeAfterBlur(GoToPreviousMatchOperation.id, true)}
+ >
+ <ArrowUpIcon />
+ </IconButton>
+ <IconButton
+ disabled={navigationDisabled}
+ label={localeService.t<LocaleKey>('find-replace.mobile.next-match')}
+ onClick={() => executeAfterBlur(GoToNextMatchOperation.id, true)}
+ >
+ <ArrowDownIcon />
+ </IconButton>
+ <IconButton
+ label={localeService.t<LocaleKey>('find-replace.mobile.close')}
+ onClick={() => {
+ blurActiveElement();
+ commandService.executeCommand(CloseFindDialogOperation.id).catch(() => undefined);
+ }}
+ >
+ <CloseIcon />
+ </IconButton>
+ </div>
+ {state.replaceRevealed && (
+ <div className="univer-flex univer-gap-1 univer-pl-9">
+ <Input
+ size="middle"
+ className="univer-min-w-0 univer-flex-1"
+ value={state.replaceString}
+ placeholder={localeService.t<LocaleKey>('find-replace.dialog.replace-placeholder')}
+ onChange={(value) => findReplaceService.changeReplaceString(value)}
+ />
+ <ActionButton
+ disabled={replaceDisabled}
+ onClick={() => executeAfterBlur(ReplaceCurrentMatchCommand.id)}
+ >
+ {localeService.t<LocaleKey>('find-replace.dialog.replace')}
+ </ActionButton>
+ <ActionButton
+ disabled={replaceAllDisabled}
+ onClick={() => executeAfterBlur(ReplaceAllMatchesCommand.id)}
+ >
+ {localeService.t<LocaleKey>('find-replace.dialog.replace-all')}
+ </ActionButton>
+ </div>
+ )}
+ </div>
+ );
+}
+
+interface IIconButtonProps {
+ children: ReactNode;
+ disabled?: boolean;
+ label: string;
+ onClick: () => void;
+}
+
+function IconButton(props: IIconButtonProps) {
+ return (
+ <button
+ type="button"
+ aria-label={props.label}
+ disabled={props.disabled}
+ className={clsx(resetButtonClassName, `
+ univer-flex univer-size-9 univer-flex-none univer-items-center univer-justify-center univer-rounded-full
+ univer-text-lg univer-text-gray-700
+ active:univer-bg-gray-100
+ disabled:univer-opacity-35
+ dark:!univer-text-gray-200
+ dark:active:!univer-bg-gray-700
+ `)}
+ onClick={props.onClick}
+ >
+ {props.children}
+ </button>
+ );
+}
+
+interface IActionButtonProps {
+ children: ReactNode;
+ disabled?: boolean;
+ onClick: () => void;
+}
+
+function ActionButton(props: IActionButtonProps) {
+ return (
+ <button
+ type="button"
+ disabled={props.disabled}
+ className={clsx(resetButtonClassName, `
+ univer-h-10 univer-flex-none univer-whitespace-nowrap univer-rounded-lg univer-bg-primary-600 univer-px-3
+ univer-text-sm univer-font-medium univer-text-gray-0
+ active:univer-bg-primary-700
+ disabled:univer-bg-gray-100 disabled:univer-text-gray-400
+ dark:disabled:!univer-bg-gray-700 dark:disabled:!univer-text-gray-500
+ `)}
+ onClick={props.onClick}
+ >
+ {props.children}
+ </button>
+ );
+}
diff --git a/packages/find-replace/src/views/mobile/MobileFindReplaceSettings.tsx b/packages/find-replace/src/views/mobile/MobileFindReplaceSettings.tsx
new file mode 100644
index 0000000000..bb7fe0f0e7
--- /dev/null
+++ b/packages/find-replace/src/views/mobile/MobileFindReplaceSettings.tsx
@@ -0,0 +1,179 @@
+/**
+ * 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 { LocaleService } from '@univerjs/core';
+import { Checkbox, MobileSelect } from '@univerjs/design';
+import { useDependency, useObservable } from '@univerjs/ui';
+import { FindBy, FindDirection, FindScope, IFindReplaceService } from '../../services/find-replace.service';
+
+const FIND_SCOPE_OPTIONS: Array<{ label: LocaleKey; value: FindScope }> = [
+ { label: 'find-replace.dialog.find-scope.current-sheet', value: FindScope.SUBUNIT },
+ { label: 'find-replace.dialog.find-scope.workbook', value: FindScope.UNIT },
+];
+
+const FIND_DIRECTION_OPTIONS: Array<{ label: LocaleKey; value: FindDirection }> = [
+ { label: 'find-replace.dialog.find-direction.row', value: FindDirection.ROW },
+ { label: 'find-replace.dialog.find-direction.column', value: FindDirection.COLUMN },
+];
+
+const FIND_BY_OPTIONS: Array<{ label: LocaleKey; value: FindBy }> = [
+ { label: 'find-replace.dialog.find-by.value', value: FindBy.VALUE },
+ { label: 'find-replace.dialog.find-by.formula', value: FindBy.FORMULA },
+];
+
+export function MobileFindReplaceSettings() {
+ const findReplaceService = useDependency(IFindReplaceService);
+ const localeService = useDependency(LocaleService);
+ const state = useObservable(findReplaceService.state$, undefined, true);
+ const capabilities = useObservable(findReplaceService.providerCapabilities$, null, true);
+
+ function refreshSearch(force = false): void {
+ if (state.findString && (force || state.replaceRevealed)) {
+ findReplaceService.find();
+ }
+ }
+
+ const findScopeOptions = FIND_SCOPE_OPTIONS.map((option) => ({
+ ...option,
+ label: localeService.t<LocaleKey>(option.label),
+ }));
+ const findDirectionOptions = FIND_DIRECTION_OPTIONS.map((option) => ({
+ ...option,
+ label: localeService.t<LocaleKey>(option.label),
+ }));
+ const findByOptions = FIND_BY_OPTIONS.map((option) => ({
+ ...option,
+ label: localeService.t<LocaleKey>(option.label),
+ }));
+
+ return (
+ <div className="univer-grid univer-gap-2" data-u-comp="mobile-find-replace-settings">
+ <SettingCheckbox
+ checked={state.replaceRevealed}
+ label={localeService.t<LocaleKey>('find-replace.dialog.replace')}
+ onChange={(checked) => {
+ if (checked) {
+ findReplaceService.revealReplace();
+ } else {
+ findReplaceService.hideReplace();
+ }
+ refreshSearch(true);
+ }}
+ />
+ {capabilities?.findDirection && (
+ <SettingSelect
+ label={localeService.t<LocaleKey>('find-replace.dialog.find-direction.title')}
+ value={state.findDirection}
+ options={findDirectionOptions}
+ onChange={(value) => {
+ findReplaceService.changeFindDirection(value as FindDirection);
+ refreshSearch();
+ }}
+ />
+ )}
+ {capabilities?.findScope && (
+ <SettingSelect
+ label={localeService.t<LocaleKey>('find-replace.dialog.find-scope.title')}
+ value={state.findScope}
+ options={findScopeOptions}
+ onChange={(value) => {
+ findReplaceService.changeFindScope(value as FindScope);
+ refreshSearch();
+ }}
+ />
+ )}
+ {capabilities?.findBy && (
+ <SettingSelect
+ label={localeService.t<LocaleKey>('find-replace.dialog.find-by.title')}
+ value={state.findBy}
+ options={findByOptions}
+ onChange={(value) => {
+ findReplaceService.changeFindBy(value as FindBy);
+ refreshSearch();
+ }}
+ />
+ )}
+ {capabilities?.caseSensitive && (
+ <SettingCheckbox
+ checked={state.caseSensitive}
+ label={localeService.t<LocaleKey>('find-replace.dialog.case-sensitive')}
+ onChange={(checked) => {
+ findReplaceService.changeCaseSensitive(checked);
+ refreshSearch();
+ }}
+ />
+ )}
+ {capabilities?.matchesTheWholeCell && (
+ <SettingCheckbox
+ checked={state.matchesTheWholeCell}
+ label={localeService.t<LocaleKey>('find-replace.dialog.match-the-whole-cell')}
+ onChange={(checked) => {
+ findReplaceService.changeMatchesTheWholeCell(checked);
+ refreshSearch();
+ }}
+ />
+ )}
+ {capabilities?.matchesTheWholeWord && (
+ <SettingCheckbox
+ checked={state.matchesTheWholeWord}
+ label={localeService.t<LocaleKey>('find-replace.dialog.match-the-whole-word')}
+ onChange={(checked) => {
+ findReplaceService.changeMatchesTheWholeWord(checked);
+ refreshSearch();
+ }}
+ />
+ )}
+ </div>
+ );
+}
+
+interface ISettingSelectProps {
+ label: string;
+ value: string;
+ options: Array<{ label: string; value: string }>;
+ onChange: (value: string) => void;
+}
+
+function SettingSelect(props: ISettingSelectProps) {
+ return (
+ <label
+ className="
+ univer-grid univer-gap-1 univer-text-sm univer-text-gray-700
+ dark:!univer-text-gray-300
+ "
+ >
+ <span>{props.label}</span>
+ <MobileSelect value={props.value} options={props.options} onChange={props.onChange} />
+ </label>
+ );
+}
+
+interface ISettingCheckboxProps {
+ checked: boolean;
+ label: string;
+ onChange: (checked: boolean) => void;
+}
+
+function SettingCheckbox(props: ISettingCheckboxProps) {
+ return (
+ <div className="univer-flex univer-min-h-9 univer-items-center">
+ <Checkbox checked={props.checked} onChange={(checked) => props.onChange(Boolean(checked))}>
+ {props.label}
+ </Checkbox>
+ </div>
+ );
+}
diff --git a/packages/sheets-conditional-formatting-ui/src/const.ts b/packages/sheets-conditional-formatting-ui/src/const.ts
new file mode 100644
index 0000000000..ef389c97ab
--- /dev/null
+++ b/packages/sheets-conditional-formatting-ui/src/const.ts
@@ -0,0 +1,17 @@
+/**
+ * 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.
+ */
+
+export const CF_PANEL_KEY = 'sheet.conditional.formatting.panel';
diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/cf.panel.controller.ts b/packages/sheets-conditional-formatting-ui/src/controllers/cf.panel.controller.ts
index af07a679b8..8934dc867f 100644
--- a/packages/sheets-conditional-formatting-ui/src/controllers/cf.panel.controller.ts
+++ b/packages/sheets-conditional-formatting-ui/src/controllers/cf.panel.controller.ts
@@ -26,8 +26,7 @@ import {
UniverInstanceType,
} from '@univerjs/core';
import { ISidebarService } from '@univerjs/ui';
-
-const CF_PANEL_KEY = 'sheet.conditional.formatting.panel';
+import { CF_PANEL_KEY } from '../const';
export class ConditionalFormattingPanelController extends Disposable {
private _sidebarDisposable: IDisposable | null = null;
diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/components.controller.ts b/packages/sheets-conditional-formatting-ui/src/controllers/components.controller.ts
index a6c7957344..5a4be7a20b 100644
--- a/packages/sheets-conditional-formatting-ui/src/controllers/components.controller.ts
+++ b/packages/sheets-conditional-formatting-ui/src/controllers/components.controller.ts
@@ -17,10 +17,9 @@
import { Disposable, Inject } from '@univerjs/core';
import { ConditionsDoubleIcon, DataBarIcon, RatingIcon } from '@univerjs/icons';
import { ComponentManager, IconManager } from '@univerjs/ui';
+import { CF_PANEL_KEY } from '../const';
import { ConditionFormattingPanel } from '../views/ConditionFormattingPanel';
-const CF_PANEL_KEY = 'sheet.conditional.formatting.panel';
-
export class ComponentsController extends Disposable {
constructor(
@Inject(ComponentManager) private readonly _componentManager: ComponentManager,
diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/mobile/components.controller.ts b/packages/sheets-conditional-formatting-ui/src/controllers/mobile/components.controller.ts
new file mode 100644
index 0000000000..b273cd5642
--- /dev/null
+++ b/packages/sheets-conditional-formatting-ui/src/controllers/mobile/components.controller.ts
@@ -0,0 +1,33 @@
+/**
+ * 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 { Disposable, Inject } from '@univerjs/core';
+import { ConditionsDoubleIcon, DataBarIcon, RatingIcon } from '@univerjs/icons';
+import { ComponentManager, IconManager } from '@univerjs/ui';
+import { CF_PANEL_KEY } from '../../const';
+import { MobileConditionFormattingPanel } from '../../views/mobile/MobileConditionFormattingPanel';
+
+export class MobileComponentsController extends Disposable {
+ constructor(
+ @Inject(ComponentManager) componentManager: ComponentManager,
+ @Inject(IconManager) iconManager: IconManager
+ ) {
+ super();
+
+ this.disposeWithMe(componentManager.register(CF_PANEL_KEY, MobileConditionFormattingPanel));
+ this.disposeWithMe(iconManager.register({ ConditionsDoubleIcon, DataBarIcon, RatingIcon }));
+ }
+}
diff --git a/packages/sheets-conditional-formatting-ui/src/menu/mobile-cf.menu.controller.ts b/packages/sheets-conditional-formatting-ui/src/menu/mobile-cf.menu.controller.ts
new file mode 100644
index 0000000000..de69b72038
--- /dev/null
+++ b/packages/sheets-conditional-formatting-ui/src/menu/mobile-cf.menu.controller.ts
@@ -0,0 +1,29 @@
+/**
+ * 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 { Disposable } from '@univerjs/core';
+import { IMenuManagerService } from '@univerjs/ui';
+import { mobileMenuSchema } from './mobile-schema';
+
+export class ConditionalFormattingMobileMenuController extends Disposable {
+ constructor(
+ @IMenuManagerService menuManagerService: IMenuManagerService
+ ) {
+ super();
+
+ menuManagerService.mergeMenu(mobileMenuSchema);
+ }
+}
diff --git a/packages/sheets-conditional-formatting-ui/src/menu/mobile-schema.ts b/packages/sheets-conditional-formatting-ui/src/menu/mobile-schema.ts
new file mode 100644
index 0000000000..d86649359c
--- /dev/null
+++ b/packages/sheets-conditional-formatting-ui/src/menu/mobile-schema.ts
@@ -0,0 +1,22 @@
+/**
+ * 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 { MenuSchemaType } from '@univerjs/ui';
+import { conditionalFormattingRuleMenuSchema } from './schema';
+
+export const mobileMenuSchema: MenuSchemaType = {
+ ...conditionalFormattingRuleMenuSchema,
+};
diff --git a/packages/sheets-conditional-formatting-ui/src/menu/schema.ts b/packages/sheets-conditional-formatting-ui/src/menu/schema.ts
index 7ff6f65289..e0337a736f 100644
--- a/packages/sheets-conditional-formatting-ui/src/menu/schema.ts
+++ b/packages/sheets-conditional-formatting-ui/src/menu/schema.ts
@@ -22,6 +22,16 @@ import { OpenConditionalFormattingOperator } from '../commands/operations/open-c
import { FactoryManageConditionalFormattingRule } from './manage-rule';
import { quickDataBarMenuFactory, quickIconSetMenuFactory } from './quick-insert.menu';
+export const conditionalFormattingRuleMenuSchema: MenuSchemaType = {
+ [RibbonDataGroup.RULES]: {
+ [OpenConditionalFormattingOperator.id]: {
+ order: 1,
+ gridLayout: { row: 2, column: 1, showLabel: true },
+ menuItemFactory: FactoryManageConditionalFormattingRule,
+ },
+ },
+};
+
export const menuSchema: MenuSchemaType = {
[RibbonInsertGroup.CELL]: {
[AddDataBarConditionalRuleCommand.id]: {
@@ -33,11 +43,5 @@ export const menuSchema: MenuSchemaType = {
menuItemFactory: quickIconSetMenuFactory,
},
},
- [RibbonDataGroup.RULES]: {
- [OpenConditionalFormattingOperator.id]: {
- order: 1,
- gridLayout: { row: 2, column: 1, showLabel: true },
- menuItemFactory: FactoryManageConditionalFormattingRule,
- },
- },
+ ...conditionalFormattingRuleMenuSchema,
};
diff --git a/packages/sheets-conditional-formatting-ui/src/mobile-plugin.ts b/packages/sheets-conditional-formatting-ui/src/mobile-plugin.ts
index 22d8749cce..5d0cf5bf78 100644
--- a/packages/sheets-conditional-formatting-ui/src/mobile-plugin.ts
+++ b/packages/sheets-conditional-formatting-ui/src/mobile-plugin.ts
@@ -31,6 +31,7 @@ import { UniverRenderEnginePlugin } from '@univerjs/engine-render';
import { UniverSheetsPlugin } from '@univerjs/sheets';
import { SHEET_CONDITIONAL_FORMATTING_PLUGIN, UniverSheetsConditionalFormattingPlugin } from '@univerjs/sheets-conditional-formatting';
import { UniverSheetsFormulaPlugin } from '@univerjs/sheets-formula';
+import { UniverSheetsFormulaMobileUIPlugin } from '@univerjs/sheets-formula-ui';
import { UniverSheetsMobileUIPlugin } from '@univerjs/sheets-ui';
import pkg from '../package.json';
import { AddAverageCfCommand } from './commands/commands/add-average-cf.command';
@@ -51,18 +52,19 @@ import { ConditionalFormattingI18nController } from './controllers/cf.i18n.contr
import { ConditionalFormattingPanelController } from './controllers/cf.panel.controller';
import { ConditionalFormattingPermissionController } from './controllers/cf.permission.controller';
import { SheetsCfRenderController } from './controllers/cf.render.controller';
-import { ComponentsController } from './controllers/components.controller';
-import { ConditionalFormattingMenuController } from './menu/cf.menu.controller';
+import { MobileComponentsController } from './controllers/mobile/components.controller';
+import { ConditionalFormattingMobileMenuController } from './menu/mobile-cf.menu.controller';
@DependentOn(
UniverRenderEnginePlugin,
UniverSheetsPlugin,
UniverSheetsFormulaPlugin,
+ UniverSheetsFormulaMobileUIPlugin,
UniverSheetsConditionalFormattingPlugin,
UniverSheetsMobileUIPlugin
)
export class UniverSheetsConditionalFormattingMobileUIPlugin extends Plugin {
- static override pluginName = `${SHEET_CONDITIONAL_FORMATTING_PLUGIN}_MOBILE_UI_PLUGIN`;
+ static override pluginName = `${SHEET_CONDITIONAL_FORMATTING_PLUGIN}_UI_PLUGIN`;
static override packageName = pkg.name;
static override version = pkg.version;
static override type = UniverInstanceType.UNIVER_SHEET;
@@ -91,17 +93,17 @@ export class UniverSheetsConditionalFormattingMobileUIPlugin extends Plugin {
override onStarting(): void {
registerDependencies(this._injector, [
- [ComponentsController],
+ [MobileComponentsController],
[SheetsCfRenderController],
[ConditionalFormattingCopyPasteController],
[ConditionalFormattingPermissionController],
[ConditionalFormattingI18nController],
[ConditionalFormattingFormulaRefRangeController],
[ConditionalFormattingPanelController],
- [ConditionalFormattingMenuController],
+ [ConditionalFormattingMobileMenuController],
]);
touchDependencies(this._injector, [
- [ComponentsController],
+ [MobileComponentsController],
[SheetsCfRenderController],
[ConditionalFormattingFormulaRefRangeController],
]);
@@ -109,7 +111,7 @@ export class UniverSheetsConditionalFormattingMobileUIPlugin extends Plugin {
override onReady(): void {
touchDependencies(this._injector, [
- [ConditionalFormattingMenuController],
+ [ConditionalFormattingMobileMenuController],
[ConditionalFormattingPanelController],
]);
}
diff --git a/packages/sheets-conditional-formatting-ui/src/views/ColorPicker.tsx b/packages/sheets-conditional-formatting-ui/src/views/ColorPicker.tsx
index e30ce2d7f1..751f8e3575 100644
--- a/packages/sheets-conditional-formatting-ui/src/views/ColorPicker.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/views/ColorPicker.tsx
@@ -14,22 +14,33 @@
* limitations under the License.
*/
-import type { FC } from 'react';
+import type { IColorPickerProps, IDropdownProps } from '@univerjs/design';
+import type { ComponentType, FC } from 'react';
import { ColorKit } from '@univerjs/core';
import { clsx, Dropdown, ColorPicker as OriginColorPicker } from '@univerjs/design';
import { PaintBucketDoubleIcon } from '@univerjs/icons';
import { useMemo } from 'react';
-interface IColorPickerProps {
+export interface IConditionalColorPickerProps {
color: string;
onChange: (color: string) => void;
disable?: boolean;
Icon?: FC;
className?: string;
+ DropdownComponent?: ComponentType<IDropdownProps>;
+ PickerComponent?: ComponentType<IColorPickerProps>;
};
-export const ColorPicker = (props: IColorPickerProps) => {
- const { color, onChange, disable = false, Icon = PaintBucketDoubleIcon, className } = props;
+export const ColorPicker = (props: IConditionalColorPickerProps) => {
+ const {
+ color,
+ onChange,
+ disable = false,
+ Icon = PaintBucketDoubleIcon,
+ className,
+ DropdownComponent = Dropdown,
+ PickerComponent = OriginColorPicker,
+ } = props;
const colorKit = useMemo(() => new ColorKit(color), [color]);
@@ -46,10 +57,10 @@ export const ColorPicker = (props: IColorPickerProps) => {
return !disable
? (
- <Dropdown
+ <DropdownComponent
overlay={(
<div className="univer-rounded-lg univer-p-4">
- <OriginColorPicker value={color} onChange={onChange} />
+ <PickerComponent value={color} onChange={onChange} />
</div>
)}
>
@@ -62,7 +73,7 @@ export const ColorPicker = (props: IColorPickerProps) => {
>
{renderIcon()}
</span>
- </Dropdown>
+ </DropdownComponent>
)
: renderIcon();
};
diff --git a/packages/sheets-conditional-formatting-ui/src/views/ConditionFormattingPanel.tsx b/packages/sheets-conditional-formatting-ui/src/views/ConditionFormattingPanel.tsx
index 8c8f40e10a..70658e1f96 100644
--- a/packages/sheets-conditional-formatting-ui/src/views/ConditionFormattingPanel.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/views/ConditionFormattingPanel.tsx
@@ -19,9 +19,14 @@ import { useState } from 'react';
import { RuleEdit } from './panel/RuleEdit';
import { RuleList } from './panel/RuleList';
-interface IConditionFormattingPanelProps { rule?: IConditionFormattingRule };
+export interface IConditionFormattingPanelProps {
+ rule?: IConditionFormattingRule;
+ RuleEditComponent?: typeof RuleEdit;
+ RuleListComponent?: typeof RuleList;
+}
export const ConditionFormattingPanel = (props: IConditionFormattingPanelProps) => {
+ const { RuleEditComponent = RuleEdit, RuleListComponent = RuleList } = props;
const [currentEditRule, setCurrentEditRule] = useState<IConditionFormattingRule | undefined>(props.rule);
const [isShowRuleEditor, setIsShowRuleEditor] = useState(!!props.rule);
@@ -43,10 +48,10 @@ export const ConditionFormattingPanel = (props: IConditionFormattingPanelProps)
<div className="univer-flex univer-h-full univer-flex-col univer-justify-between univer-py-4">
{isShowRuleEditor
? (
- <RuleEdit onCancel={handleCancel} rule={currentEditRule} />
+ <RuleEditComponent onCancel={handleCancel} rule={currentEditRule} />
)
: (
- <RuleList onClick={handleRuleClick} onCreate={createCfRule} />
+ <RuleListComponent onClick={handleRuleClick} onCreate={createCfRule} />
)}
</div>
);
diff --git a/packages/sheets-conditional-formatting-ui/src/views/ConditionalStyleEditor.tsx b/packages/sheets-conditional-formatting-ui/src/views/ConditionalStyleEditor.tsx
index 8f6eca7444..f031df7f5e 100644
--- a/packages/sheets-conditional-formatting-ui/src/views/ConditionalStyleEditor.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/views/ConditionalStyleEditor.tsx
@@ -15,6 +15,8 @@
*/
import type { IHighlightCell } from '@univerjs/sheets-conditional-formatting';
+import type { ComponentType } from 'react';
+import type { IConditionalColorPickerProps } from './ColorPicker';
import { BooleanNumber } from '@univerjs/core';
import { clsx } from '@univerjs/design';
import { BoldIcon, FontColorDoubleIcon, ItalicIcon, StrikethroughIcon, UnderlineIcon } from '@univerjs/icons';
@@ -22,10 +24,11 @@ import { removeUndefinedAttr } from '@univerjs/sheets-conditional-formatting';
import { useEffect, useState } from 'react';
import { ColorPicker } from './ColorPicker';
-interface IConditionalStyleEditorProps {
+export interface IConditionalStyleEditorProps {
className?: string;
style?: IHighlightCell['style'];
onChange: (style: IHighlightCell['style']) => void;
+ ColorPickerComponent?: ComponentType<IConditionalColorPickerProps>;
};
const getAnotherBooleanNumber = (v: BooleanNumber | undefined) => {
@@ -33,7 +36,7 @@ const getAnotherBooleanNumber = (v: BooleanNumber | undefined) => {
};
const getBooleanFromNumber = (v: BooleanNumber) => v !== BooleanNumber.FALSE;
export const ConditionalStyleEditor = (props: IConditionalStyleEditorProps) => {
- const { style, onChange, className } = props;
+ const { style, onChange, className, ColorPickerComponent = ColorPicker } = props;
const [isBold, setIsBold] = useState<BooleanNumber | undefined>(() => {
const defaultV = undefined;
@@ -134,8 +137,8 @@ export const ConditionalStyleEditor = (props: IConditionalStyleEditorProps) => {
>
<StrikethroughIcon />
</div>
- <ColorPicker color={fontColor} onChange={setFontColor} Icon={FontColorDoubleIcon} />
- <ColorPicker color={bgColor} onChange={setBgColor} />
+ <ColorPickerComponent color={fontColor} onChange={setFontColor} Icon={FontColorDoubleIcon} />
+ <ColorPickerComponent color={bgColor} onChange={setBgColor} />
</div>
);
};
diff --git a/packages/sheets-conditional-formatting-ui/src/views/mobile/MobileColorPicker.tsx b/packages/sheets-conditional-formatting-ui/src/views/mobile/MobileColorPicker.tsx
new file mode 100644
index 0000000000..a52e9d67b8
--- /dev/null
+++ b/packages/sheets-conditional-formatting-ui/src/views/mobile/MobileColorPicker.tsx
@@ -0,0 +1,29 @@
+/**
+ * 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 { IConditionalColorPickerProps } from '../ColorPicker';
+import { MobileColorPicker, MobileDropdown } from '@univerjs/design';
+import { ColorPicker } from '../ColorPicker';
+
+export function MobileConditionalColorPicker(props: IConditionalColorPickerProps) {
+ return (
+ <ColorPicker
+ {...props}
+ DropdownComponent={MobileDropdown}
+ PickerComponent={MobileColorPicker}
+ />
+ );
+}
diff --git a/packages/sheets-conditional-formatting-ui/src/views/mobile/MobileConditionFormattingPanel.tsx b/packages/sheets-conditional-formatting-ui/src/views/mobile/MobileConditionFormattingPanel.tsx
new file mode 100644
index 0000000000..2ce33554c2
--- /dev/null
+++ b/packages/sheets-conditional-formatting-ui/src/views/mobile/MobileConditionFormattingPanel.tsx
@@ -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 { IConditionFormattingPanelProps } from '../ConditionFormattingPanel';
+import { ConditionFormattingPanel } from '../ConditionFormattingPanel';
+import { MobileRuleEdit } from './MobileRuleEdit';
+import { MobileRuleList } from './MobileRuleList';
+
+export function MobileConditionFormattingPanel(props: IConditionFormattingPanelProps) {
+ return (
+ <ConditionFormattingPanel
+ {...props}
+ RuleEditComponent={MobileRuleEdit}
+ RuleListComponent={MobileRuleList}
+ />
+ );
+}
diff --git a/packages/sheets-conditional-formatting-ui/src/views/mobile/MobileRuleEdit.tsx b/packages/sheets-conditional-formatting-ui/src/views/mobile/MobileRuleEdit.tsx
new file mode 100644
index 0000000000..40a3ecfab3
--- /dev/null
+++ b/packages/sheets-conditional-formatting-ui/src/views/mobile/MobileRuleEdit.tsx
@@ -0,0 +1,39 @@
+/**
+ * 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 { IRuleEditProps } from '../panel/RuleEdit';
+import { MobileDropdown, MobileSelect } from '@univerjs/design';
+import { MobileRangeSelector } from '@univerjs/sheets-formula-ui';
+import { EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY } from '@univerjs/sheets-ui';
+import { ComponentManager, useDependency } from '@univerjs/ui';
+import { RuleEdit } from '../panel/RuleEdit';
+import { MobileConditionalColorPicker } from './MobileColorPicker';
+
+export function MobileRuleEdit(props: IRuleEditProps) {
+ const componentManager = useDependency(ComponentManager);
+ const FormulaEditorComponent = componentManager.get(EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY);
+
+ return (
+ <RuleEdit
+ {...props}
+ SelectComponent={MobileSelect}
+ DropdownComponent={MobileDropdown}
+ ColorPickerComponent={MobileConditionalColorPicker}
+ RangeSelectorComponent={MobileRangeSelector}
+ FormulaEditorComponent={FormulaEditorComponent}
+ />
+ );
+}
diff --git a/packages/sheets-conditional-formatting-ui/src/views/mobile/MobileRuleList.tsx b/packages/sheets-conditional-formatting-ui/src/views/mobile/MobileRuleList.tsx
new file mode 100644
index 0000000000..d02f545f1a
--- /dev/null
+++ b/packages/sheets-conditional-formatting-ui/src/views/mobile/MobileRuleList.tsx
@@ -0,0 +1,23 @@
+/**
+ * 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 { IRuleListProps } from '../panel/RuleList';
+import { MobileSelect } from '@univerjs/design';
+import { RuleList } from '../panel/RuleList';
+
+export function MobileRuleList(props: IRuleListProps) {
+ return <RuleList {...props} SelectComponent={MobileSelect} />;
+}
diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/RuleEdit.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/RuleEdit.tsx
index d9d4bc0abd..ea29a482dc 100644
--- a/packages/sheets-conditional-formatting-ui/src/views/panel/RuleEdit.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/RuleEdit.tsx
@@ -15,13 +15,16 @@
*/
import type { IRange, Workbook } from '@univerjs/core';
+import type { IDropdownProps, ISelectProps } from '@univerjs/design';
import type { IRemoveSheetMutationParams } from '@univerjs/sheets';
import type {
IAddCfCommandParams,
IConditionFormattingRule,
ISetCfCommandParams,
} from '@univerjs/sheets-conditional-formatting';
+import type { ComponentType } from 'react';
import type { LocaleKey } from '../../locale/types';
+import type { IConditionalColorPickerProps } from '../ColorPicker';
import type { IStyleEditorProps } from './rule-edit/type';
import {
ICommandService,
@@ -45,7 +48,7 @@ import {
ConditionalFormattingRuleModel,
SetCfCommand,
} from '@univerjs/sheets-conditional-formatting';
-import { RangeSelector } from '@univerjs/sheets-formula-ui';
+import { FormulaEditor, RangeSelector } from '@univerjs/sheets-formula-ui';
import { useDependency } from '@univerjs/ui';
import { useEffect, useMemo, useRef, useState } from 'react';
import { ColorScaleStyleEditor } from './rule-edit/ColorScale';
@@ -56,15 +59,27 @@ import { IconSet } from './rule-edit/IconSet';
import { RankStyleEditor } from './rule-edit/Rank';
import { beforeSubmit, submit } from './rule-edit/type';
-interface IRuleEditProps {
+export interface IRuleEditProps {
rule?: IConditionFormattingRule;
onCancel: () => void;
+ SelectComponent?: ComponentType<ISelectProps>;
+ DropdownComponent?: ComponentType<IDropdownProps>;
+ ColorPickerComponent?: ComponentType<IConditionalColorPickerProps>;
+ RangeSelectorComponent?: typeof RangeSelector;
+ FormulaEditorComponent?: typeof FormulaEditor;
}
const getUnitId = (univerInstanceService: IUniverInstanceService) => univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getUnitId();
const getSubUnitId = (univerInstanceService: IUniverInstanceService) => univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()?.getSheetId();
export const RuleEdit = (props: IRuleEditProps) => {
+ const {
+ SelectComponent = Select,
+ DropdownComponent,
+ ColorPickerComponent,
+ RangeSelectorComponent = RangeSelector,
+ FormulaEditorComponent = FormulaEditor,
+ } = props;
const localeService = useDependency(LocaleService);
const commandService = useDependency(ICommandService);
const univerInstanceService = useDependency(IUniverInstanceService);
@@ -273,7 +288,7 @@ export const RuleEdit = (props: IRuleEditProps) => {
{localeService.t<LocaleKey>('sheets-conditional-formatting-ui.panel.range')}
</div>
<div className="univer-mt-4">
- <RangeSelector
+ <RangeSelectorComponent
unitId={unitId}
subUnitId={subUnitId}
initialValue={rangeString}
@@ -290,7 +305,7 @@ export const RuleEdit = (props: IRuleEditProps) => {
>
{localeService.t<LocaleKey>('sheets-conditional-formatting-ui.panel.styleType')}
</div>
- <Select
+ <SelectComponent
className="univer-mt-4 univer-w-full"
value={ruleType}
options={options}
@@ -300,6 +315,10 @@ export const RuleEdit = (props: IRuleEditProps) => {
interceptorManager={interceptorManager}
rule={props.rule?.rule as any}
onChange={onStyleChange}
+ SelectComponent={SelectComponent}
+ DropdownComponent={DropdownComponent}
+ ColorPickerComponent={ColorPickerComponent}
+ FormulaEditorComponent={FormulaEditorComponent}
/>
<div className="univer-mt-4 univer-flex univer-justify-end univer-gap-2">
<Button onClick={handleCancel}>{localeService.t<LocaleKey>('sheets-conditional-formatting-ui.panel.cancel')}</Button>
diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/RuleList.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/RuleList.tsx
index 009b66e659..682b6c51ac 100644
--- a/packages/sheets-conditional-formatting-ui/src/views/panel/RuleList.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/RuleList.tsx
@@ -15,11 +15,13 @@
*/
import type { IRange, Workbook } from '@univerjs/core';
+import type { ISelectProps } from '@univerjs/design';
import type {
IConditionFormattingRule,
IDeleteCfCommandParams,
IMoveCfCommandParams,
} from '@univerjs/sheets-conditional-formatting';
+import type { ComponentType } from 'react';
import type { LocaleKey } from '../../locale/types';
import {
ICommandService,
@@ -57,9 +59,10 @@ import { debounceTime, filter, map, merge, Observable, share, startWith } from '
import { ConditionalFormattingI18nController } from '../../controllers/cf.i18n.controller';
import { Preview } from '../Preview';
-interface IRuleListProps {
+export interface IRuleListProps {
onClick: (rule: IConditionFormattingRule) => void;
onCreate: () => void;
+ SelectComponent?: ComponentType<ISelectProps>;
};
const getRuleDescribe = (rule: IConditionFormattingRule, localeService: LocaleService) => {
const ruleConfig = rule.rule;
@@ -122,6 +125,7 @@ const getRuleDescribe = (rule: IConditionFormattingRule, localeService: LocaleSe
};
export function RuleList(props: IRuleListProps) {
+ const { SelectComponent = Select } = props;
const { onClick } = props;
const conditionalFormattingRuleModel = useDependency(ConditionalFormattingRuleModel);
const univerInstanceService = useDependency(IUniverInstanceService);
@@ -296,7 +300,7 @@ export function RuleList(props: IRuleListProps) {
<div className="univer-flex univer-items-center univer-gap-2">
{conditionalFormattingI18nController.tWithReactNode(
'sheets-conditional-formatting-ui.panel.managerRuleSelect',
- <Select
+ <SelectComponent
className="univer-w-36"
options={selectOption}
value={selectValue}
diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/ColorScale.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/ColorScale.tsx
index aafb6b8c80..d443166870 100644
--- a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/ColorScale.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/ColorScale.tsx
@@ -34,8 +34,15 @@ const createOptionItem = (text: CFValueType | 'none'): { label: LocaleKey; value
value: text,
});
-const TextInput = (props: { id: string; type: CFValueType | 'none'; value: number | string; onChange: (v: number | string) => void; className?: string }) => {
- const { type, className, onChange, value } = props;
+const TextInput = (props: {
+ id: string;
+ type: CFValueType | 'none';
+ value: number | string;
+ onChange: (v: number | string) => void;
+ className?: string;
+ FormulaEditorComponent: NonNullable<IStyleEditorProps['FormulaEditorComponent']>;
+}) => {
+ const { type, className, onChange, value, FormulaEditorComponent } = props;
const univerInstanceService = useDependency(IUniverInstanceService);
const unitId = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getUnitId();
const subUnitId = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()?.getSheetId();
@@ -70,7 +77,7 @@ const TextInput = (props: { id: string; type: CFValueType | 'none'; value: numbe
if (type === CFValueType.formula) {
return (
<div className="univer-w-full">
- <FormulaEditor
+ <FormulaEditorComponent
ref={formulaEditorRef}
className={clsx(`
univer-box-border univer-h-8 univer-w-full univer-cursor-pointer univer-items-center
@@ -97,7 +104,12 @@ const TextInput = (props: { id: string; type: CFValueType | 'none'; value: numbe
}
};
export const ColorScaleStyleEditor = (props: IStyleEditorProps) => {
- const { interceptorManager } = props;
+ const {
+ interceptorManager,
+ SelectComponent = Select,
+ ColorPickerComponent = ColorPicker,
+ FormulaEditorComponent = FormulaEditor,
+ } = props;
const localeService = useDependency(LocaleService);
const rule = props.rule?.type === CFRuleType.colorScale ? props.rule : undefined as IColorScale | undefined;
@@ -260,7 +272,7 @@ export const ColorScaleStyleEditor = (props: IStyleEditorProps) => {
{localeService.t<LocaleKey>('sheets-conditional-formatting-ui.valueType.min')}
</div>
<div className="univer-mt-3 univer-flex univer-h-8 univer-items-center univer-gap-2">
- <Select
+ <SelectComponent
className="univer-flex-shrink-0"
options={minOptions}
value={minType}
@@ -285,6 +297,7 @@ export const ColorScaleStyleEditor = (props: IStyleEditorProps) => {
id="min"
value={minValue}
type={minType}
+ FormulaEditorComponent={FormulaEditorComponent}
onChange={(v) => {
setMinValue(v);
handleChange({
@@ -300,7 +313,7 @@ export const ColorScaleStyleEditor = (props: IStyleEditorProps) => {
});
}}
/>
- <ColorPicker
+ <ColorPickerComponent
color={minColor}
onChange={(v) => {
setMinColor(v);
@@ -327,7 +340,7 @@ export const ColorScaleStyleEditor = (props: IStyleEditorProps) => {
{localeService.t<LocaleKey>('sheets-conditional-formatting-ui.panel.medianValue')}
</div>
<div className="univer-mt-3 univer-flex univer-h-8 univer-items-center univer-gap-2">
- <Select
+ <SelectComponent
className="univer-flex-shrink-0"
options={medianOptions}
value={medianType}
@@ -353,6 +366,7 @@ export const ColorScaleStyleEditor = (props: IStyleEditorProps) => {
id="median"
value={medianValue}
type={medianType}
+ FormulaEditorComponent={FormulaEditorComponent}
onChange={(v) => {
setMedianValue(v);
handleChange({
@@ -370,7 +384,7 @@ export const ColorScaleStyleEditor = (props: IStyleEditorProps) => {
/>
{medianType !== 'none'
? (
- <ColorPicker
+ <ColorPickerComponent
color={medianColor}
onChange={(v) => {
setMedianColor(v);
@@ -400,7 +414,7 @@ export const ColorScaleStyleEditor = (props: IStyleEditorProps) => {
{localeService.t<LocaleKey>('sheets-conditional-formatting-ui.valueType.max')}
</div>
<div className="univer-mt-3 univer-flex univer-h-8 univer-items-center univer-gap-2">
- <Select
+ <SelectComponent
className="univer-flex-shrink-0"
options={maxOptions}
value={maxType}
@@ -425,6 +439,7 @@ export const ColorScaleStyleEditor = (props: IStyleEditorProps) => {
id="max"
value={maxValue}
type={maxType}
+ FormulaEditorComponent={FormulaEditorComponent}
onChange={(v) => {
setMaxValue(v);
handleChange({
@@ -440,7 +455,7 @@ export const ColorScaleStyleEditor = (props: IStyleEditorProps) => {
});
}}
/>
- <ColorPicker
+ <ColorPickerComponent
color={maxColor}
onChange={(v) => {
setMaxColor(v);
diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/DataBar.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/DataBar.tsx
index 90ea2f7f30..5acc4f4d41 100644
--- a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/DataBar.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/DataBar.tsx
@@ -40,8 +40,16 @@ const createOptionItem = (text: CFValueType): { label: LocaleKey; value: CFValue
value: text,
});
-const InputText = (props: { disabled?: boolean; id: string; className?: string; type: CFValueType; value: string | number; onChange: (v: string | number) => void }) => {
- const { onChange, className, value, type, id, disabled = false } = props;
+const InputText = (props: {
+ disabled?: boolean;
+ id: string;
+ className?: string;
+ type: CFValueType;
+ value: string | number;
+ onChange: (v: string | number) => void;
+ FormulaEditorComponent: NonNullable<IStyleEditorProps['FormulaEditorComponent']>;
+}) => {
+ const { onChange, className, value, type, disabled = false, FormulaEditorComponent } = props;
const univerInstanceService = useDependency(IUniverInstanceService);
const unitId = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getUnitId();
const subUnitId = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()?.getSheetId();
@@ -72,7 +80,7 @@ const InputText = (props: { disabled?: boolean; id: string; className?: string;
const v = String(_value.current).startsWith('=') ? String(_value.current) || '' : '=';
return (
<div className="univer-w-full">
- <FormulaEditor
+ <FormulaEditorComponent
ref={formulaEditorRef}
className={clsx(`
univer-box-border univer-h-8 univer-w-full univer-cursor-pointer univer-items-center
@@ -108,7 +116,12 @@ const InputText = (props: { disabled?: boolean; id: string; className?: string;
);
};
export const DataBarStyleEditor = (props: IStyleEditorProps) => {
- const { interceptorManager } = props;
+ const {
+ interceptorManager,
+ SelectComponent = Select,
+ ColorPickerComponent = ColorPicker,
+ FormulaEditorComponent = FormulaEditor,
+ } = props;
const localeService = useDependency(LocaleService);
const rule = props.rule?.type === CFRuleType.dataBar ? props.rule : undefined;
@@ -356,7 +369,7 @@ export const DataBarStyleEditor = (props: IStyleEditorProps) => {
<div className="univer-text-xs">
{localeService.t<LocaleKey>('sheets-conditional-formatting-ui.panel.native')}
</div>
- <ColorPicker
+ <ColorPickerComponent
color={nativeColor}
onChange={handleNativeColorChange}
/>
@@ -365,7 +378,7 @@ export const DataBarStyleEditor = (props: IStyleEditorProps) => {
<div className="univer-text-xs">
{localeService.t<LocaleKey>('sheets-conditional-formatting-ui.panel.positive')}
</div>
- <ColorPicker
+ <ColorPickerComponent
color={positiveColor}
onChange={handlePositiveColorChange}
/>
@@ -383,7 +396,7 @@ export const DataBarStyleEditor = (props: IStyleEditorProps) => {
{localeService.t<LocaleKey>('sheets-conditional-formatting-ui.valueType.min')}
</div>
<div className="univer-mt-3 univer-flex univer-items-center univer-gap-2">
- <Select
+ <SelectComponent
className="univer-w-1/2 univer-flex-shrink-0"
options={minOptions}
value={minValueType}
@@ -409,6 +422,7 @@ export const DataBarStyleEditor = (props: IStyleEditorProps) => {
disabled={!isShowInput(minValueType)}
type={minValueType}
value={minValue}
+ FormulaEditorComponent={FormulaEditorComponent}
onChange={(v) => {
setMinValue(v || 0);
handleChange({
@@ -433,7 +447,7 @@ export const DataBarStyleEditor = (props: IStyleEditorProps) => {
{localeService.t<LocaleKey>('sheets-conditional-formatting-ui.valueType.max')}
</div>
<div className="univer-mt-3 univer-flex univer-items-center univer-gap-2">
- <Select
+ <SelectComponent
className="univer-w-1/2 univer-flex-shrink-0"
options={maxOptions}
value={maxValueType}
@@ -458,6 +472,7 @@ export const DataBarStyleEditor = (props: IStyleEditorProps) => {
id="max"
type={maxValueType}
value={maxValue}
+ FormulaEditorComponent={FormulaEditorComponent}
onChange={(v) => {
setMaxValue(v || 0);
handleChange({
diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/Formula.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/Formula.tsx
index ef9f661260..daf182a44d 100644
--- a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/Formula.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/Formula.tsx
@@ -34,7 +34,7 @@ import { Preview } from '../../Preview';
import { previewClassName } from './styles';
export const FormulaStyleEditor = (props: IStyleEditorProps) => {
- const { onChange, interceptorManager } = props;
+ const { onChange, interceptorManager, ColorPickerComponent, FormulaEditorComponent = FormulaEditor } = props;
const localeService = useDependency(LocaleService);
const lexerTreeBuilder = useDependency(LexerTreeBuilder);
const univerInstanceService = useDependency(IUniverInstanceService);
@@ -122,7 +122,7 @@ export const FormulaStyleEditor = (props: IStyleEditorProps) => {
{localeService.t<LocaleKey>('sheets-conditional-formatting-ui.panel.styleRule')}
</div>
<div className="univer-mt-3">
- <FormulaEditor
+ <FormulaEditorComponent
ref={formulaEditorRef}
className={clsx(`
univer-box-border univer-h-8 univer-w-full univer-cursor-pointer univer-items-center
@@ -161,6 +161,7 @@ export const FormulaStyleEditor = (props: IStyleEditorProps) => {
/>
</div>
<ConditionalStyleEditor
+ ColorPickerComponent={ColorPickerComponent}
style={rule?.style}
className="univer-mt-3"
onChange={(v) => {
diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/HighlightCell.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/HighlightCell.tsx
index 39e0bdd977..f7c975325c 100644
--- a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/HighlightCell.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/HighlightCell.tsx
@@ -249,7 +249,7 @@ const getOperatorOptions = (type: IEditableSubType) => {
}
};
export const HighlightCellStyleEditor = (props: IStyleEditorProps<any, IEditableHighlightCell>) => {
- const { interceptorManager, onChange } = props;
+ const { interceptorManager, onChange, SelectComponent = Select, ColorPickerComponent } = props;
const localeService = useDependency(LocaleService);
const rule = props.rule?.type === CFRuleType.highlightCell ? props.rule : undefined;
@@ -414,14 +414,14 @@ export const HighlightCellStyleEditor = (props: IStyleEditorProps<any, IEditable
{localeService.t<LocaleKey>('sheets-conditional-formatting-ui.panel.styleRule')}
</div>
<div className="univer-flex univer-justify-between univer-gap-4">
- <Select
+ <SelectComponent
className="univer-mt-3 univer-w-full"
onChange={onTypeChange}
value={subType}
options={typeOptions}
/>
{operatorOptions?.length && (
- <Select
+ <SelectComponent
className="univer-mt-3 univer-w-full"
onChange={onOperatorChange}
value={operator || ''}
@@ -442,6 +442,7 @@ export const HighlightCellStyleEditor = (props: IStyleEditorProps<any, IEditable
<Preview rule={getResult({})} />
</div>
<ConditionalStyleEditor
+ ColorPickerComponent={ColorPickerComponent}
style={rule?.style}
className="univer-ml-1"
onChange={(v) => {
diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/IconSet.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/IconSet.tsx
index b47f688295..b7f3a3502b 100644
--- a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/IconSet.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/IconSet.tsx
@@ -43,8 +43,15 @@ const getIcon = (iconType: IIconSetType, iconId: string | number) => {
return arr[Number(iconId)] || '';
};
-const TextInput = (props: { id: number; type: CFValueType; value: number | string; onChange: (v: number | string) => void; error?: string }) => {
- const { error, type, onChange } = props;
+const TextInput = (props: {
+ id: number;
+ type: CFValueType;
+ value: number | string;
+ onChange: (v: number | string) => void;
+ error?: string;
+ FormulaEditorComponent: NonNullable<IStyleEditorProps['FormulaEditorComponent']>;
+}) => {
+ const { error, type, onChange, FormulaEditorComponent } = props;
const univerInstanceService = useDependency(IUniverInstanceService);
const unitId = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getUnitId();
@@ -78,7 +85,7 @@ const TextInput = (props: { id: number; type: CFValueType; value: number | strin
)
: (
<div className="univer-w-full">
- <FormulaEditor
+ <FormulaEditorComponent
ref={formulaEditorRef}
className={clsx(`
univer-box-border univer-h-8 univer-w-full univer-cursor-pointer univer-items-center
@@ -259,8 +266,18 @@ const IconSetRuleEdit = (props: {
configList: IIconSet['config'];
onChange: (keys: string[], value: unknown) => void;
errorMap?: Record<string, string>;
+ DropdownComponent: NonNullable<IStyleEditorProps['DropdownComponent']>;
+ SelectComponent: NonNullable<IStyleEditorProps['SelectComponent']>;
+ FormulaEditorComponent: NonNullable<IStyleEditorProps['FormulaEditorComponent']>;
}) => {
- const { onChange, configList, errorMap = {} } = props;
+ const {
+ onChange,
+ configList,
+ errorMap = {},
+ DropdownComponent,
+ SelectComponent,
+ FormulaEditorComponent,
+ } = props;
const localeService = useDependency(LocaleService);
const options = [{
@@ -365,7 +382,7 @@ const IconSetRuleEdit = (props: {
"
>
<div className="univer-flex univer-items-center">
- <Dropdown
+ <DropdownComponent
overlay={(
<div className="univer-rounded-lg univer-p-4">
<IconItemList onClick={handleIconClick} iconId={item.iconId} iconType={item.iconType} />
@@ -386,11 +403,11 @@ const IconSetRuleEdit = (props: {
: <SlashDoubleIcon />}
<MoreDownIcon />
</div>
- </Dropdown>
+ </DropdownComponent>
</div>
{!isEnd
? (
- <Select
+ <SelectComponent
options={options}
value={item.operator}
onChange={(v) => { handleOperatorChange(v as CFNumberOperator, index); }}
@@ -430,7 +447,7 @@ const IconSetRuleEdit = (props: {
<div
className="univer-mt-3 univer-grid univer-grid-cols-2 univer-gap-4"
>
- <Select
+ <SelectComponent
options={valueTypeOptions}
value={item.value.type}
onChange={(v) => {
@@ -442,6 +459,7 @@ const IconSetRuleEdit = (props: {
type={item.value.type}
error={error}
value={item.value.value || ''}
+ FormulaEditorComponent={FormulaEditorComponent}
onChange={(v) => {
handleValueValueChange(v, index);
}}
@@ -453,11 +471,16 @@ const IconSetRuleEdit = (props: {
</div>
);
});
- }, [configList, errorMap]);
+ }, [configList, DropdownComponent, errorMap, FormulaEditorComponent, SelectComponent]);
return render;
};
export const IconSet = (props: IStyleEditorProps<unknown, IIconSet>) => {
- const { interceptorManager } = props;
+ const {
+ interceptorManager,
+ DropdownComponent = Dropdown,
+ SelectComponent = Select,
+ FormulaEditorComponent = FormulaEditor,
+ } = props;
const rule = props.rule?.type === CFRuleType.iconSet ? props.rule : undefined;
const localeService = useDependency(LocaleService);
const direction = useObservable(localeService.direction$, localeService.getDirection());
@@ -624,7 +647,7 @@ export const IconSet = (props: IStyleEditorProps<unknown, IIconSet>) => {
{localeService.t<LocaleKey>('sheets-conditional-formatting-ui.panel.styleRule')}
</div>
<div className="univer-mt-3">
- <Dropdown
+ <DropdownComponent
overlay={(
<div dir={direction} className="univer-rounded-lg univer-p-3">
<IconGroupList
@@ -645,7 +668,7 @@ export const IconSet = (props: IStyleEditorProps<unknown, IIconSet>) => {
{previewIcon}
<MoreDownIcon />
</div>
- </Dropdown>
+ </DropdownComponent>
</div>
<div
className="
@@ -668,7 +691,14 @@ export const IconSet = (props: IStyleEditorProps<unknown, IIconSet>) => {
{localeService.t<LocaleKey>('sheets-conditional-formatting-ui.iconSet.onlyShowIcon')}
</div>
</div>
- <IconSetRuleEdit errorMap={errorMap} onChange={handleChange} configList={configList} />
+ <IconSetRuleEdit
+ errorMap={errorMap}
+ onChange={handleChange}
+ configList={configList}
+ DropdownComponent={DropdownComponent}
+ SelectComponent={SelectComponent}
+ FormulaEditorComponent={FormulaEditorComponent}
+ />
</div>
);
};
diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/Rank.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/Rank.tsx
index be0268ff17..59b3fdb963 100644
--- a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/Rank.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/Rank.tsx
@@ -33,7 +33,7 @@ import { previewClassName } from './styles';
type IRankRuleType = 'isNotBottom' | 'isBottom' | 'greaterThanAverage' | 'lessThanAverage';
export const RankStyleEditor = (props: IStyleEditorProps) => {
- const { onChange, interceptorManager } = props;
+ const { onChange, interceptorManager, SelectComponent = Select, ColorPickerComponent } = props;
const localeService = useDependency(LocaleService);
const rule = props.rule?.type === CFRuleType.highlightCell ? props.rule : undefined;
@@ -156,7 +156,7 @@ export const RankStyleEditor = (props: IStyleEditorProps) => {
>
{localeService.t<LocaleKey>('sheets-conditional-formatting-ui.panel.styleRule')}
</div>
- <Select
+ <SelectComponent
className="univer-mt-3 univer-w-full"
value={type}
options={options}
@@ -206,6 +206,7 @@ export const RankStyleEditor = (props: IStyleEditorProps) => {
/>
</div>
<ConditionalStyleEditor
+ ColorPickerComponent={ColorPickerComponent}
style={rule?.style}
className="univer-mt-3"
onChange={(v) => {
diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/type.ts b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/type.ts
index a4eae0c6d2..6bf5f9cac1 100644
--- a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/type.ts
+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/type.ts
@@ -15,7 +15,11 @@
*/
import type { InterceptorManager } from '@univerjs/core';
+import type { IDropdownProps, ISelectProps } from '@univerjs/design';
import type { IConditionalFormattingRuleConfig } from '@univerjs/sheets-conditional-formatting';
+import type { FormulaEditor } from '@univerjs/sheets-formula-ui';
+import type { ComponentType } from 'react';
+import type { IConditionalColorPickerProps } from '../../ColorPicker';
import { createInterceptorKey } from '@univerjs/core';
export const beforeSubmit = createInterceptorKey<boolean, null>('beforeSubmit');
@@ -25,4 +29,8 @@ export interface IStyleEditorProps<S = any, R = IConditionalFormattingRuleConfig
onChange: (style: S) => void;
rule?: R;
interceptorManager: InterceptorManager<{ beforeSubmit: typeof beforeSubmit; submit: typeof submit }>;
+ SelectComponent?: ComponentType<ISelectProps>;
+ DropdownComponent?: ComponentType<IDropdownProps>;
+ ColorPickerComponent?: ComponentType<IConditionalColorPickerProps>;
+ FormulaEditorComponent?: typeof FormulaEditor;
};
diff --git a/packages/sheets-crosshair-highlight/src/const.ts b/packages/sheets-crosshair-highlight/src/const.ts
index b4500cc812..b38907b76d 100644
--- a/packages/sheets-crosshair-highlight/src/const.ts
+++ b/packages/sheets-crosshair-highlight/src/const.ts
@@ -15,3 +15,4 @@
*/
export const SHEETS_CROSSHAIR_HIGHLIGHT_Z_INDEX = 1;
+export const SHEETS_CROSSHAIR_HIGHLIGHT_PLUGIN_NAME = 'SHEET_CROSSHAIR_HIGHLIGHT_PLUGIN';
diff --git a/packages/sheets-crosshair-highlight/src/controllers/components.controller.ts b/packages/sheets-crosshair-highlight/src/controllers/components.controller.ts
index 048742781f..1e08ea4b47 100644
--- a/packages/sheets-crosshair-highlight/src/controllers/components.controller.ts
+++ b/packages/sheets-crosshair-highlight/src/controllers/components.controller.ts
@@ -18,7 +18,9 @@ import { Disposable, Inject } from '@univerjs/core';
import { CrossHighlightingIcon } from '@univerjs/icons';
import { ComponentManager, IconManager } from '@univerjs/ui';
import { CROSSHAIR_HIGHLIGHT_OVERLAY_COMPONENT } from '../menu/crosshair.menu';
+import { MOBILE_CROSSHAIR_HIGHLIGHT_PANEL } from '../menu/mobile-crosshair.menu';
import { CrosshairOverlay } from '../views/components/CrosshairHighlight';
+import { MobileCrosshairHighlightPanel } from '../views/mobile/MobileCrosshairHighlightPanel';
export class ComponentsController extends Disposable {
constructor(
@@ -33,6 +35,10 @@ export class ComponentsController extends Disposable {
private _registerComponents(): void {
this.disposeWithMe(this._componentManager.register(CROSSHAIR_HIGHLIGHT_OVERLAY_COMPONENT, CrosshairOverlay));
+ this.disposeWithMe(this._componentManager.register(
+ MOBILE_CROSSHAIR_HIGHLIGHT_PANEL,
+ MobileCrosshairHighlightPanel
+ ));
}
private _registerIcons(): void {
diff --git a/packages/sheets-crosshair-highlight/src/controllers/mobile/crosshair.controller.ts b/packages/sheets-crosshair-highlight/src/controllers/mobile/crosshair.controller.ts
new file mode 100644
index 0000000000..329fb705fb
--- /dev/null
+++ b/packages/sheets-crosshair-highlight/src/controllers/mobile/crosshair.controller.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 { Disposable, ICommandService } from '@univerjs/core';
+import { IMenuManagerService } from '@univerjs/ui';
+import {
+ DisableCrosshairHighlightOperation,
+ EnableCrosshairHighlightOperation,
+ SetCrosshairHighlightColorOperation,
+ ToggleCrosshairHighlightOperation,
+} from '../../commands/operations/operation';
+import { mobileMenuSchema } from '../../menu/mobile-schema';
+
+export class SheetsCrosshairHighlightMobileController extends Disposable {
+ constructor(
+ @ICommandService commandService: ICommandService,
+ @IMenuManagerService menuManagerService: IMenuManagerService
+ ) {
+ super();
+
+ [
+ ToggleCrosshairHighlightOperation,
+ SetCrosshairHighlightColorOperation,
+ EnableCrosshairHighlightOperation,
+ DisableCrosshairHighlightOperation,
+ ].forEach((command) => this.disposeWithMe(commandService.registerCommand(command)));
+ menuManagerService.mergeMenu(mobileMenuSchema);
+ }
+}
diff --git a/packages/sheets-crosshair-highlight/src/index.ts b/packages/sheets-crosshair-highlight/src/index.ts
index 7eede51a95..67a49cbf28 100644
--- a/packages/sheets-crosshair-highlight/src/index.ts
+++ b/packages/sheets-crosshair-highlight/src/index.ts
@@ -25,5 +25,6 @@ export {
export type { ISetCrosshairHighlightColorOperationParams } from './commands/operations/operation';
export type { IUniverSheetsCrosshairHighlightConfig } from './config/config';
export { menuSchema as SheetsCrosshairHighlightMenuSchema } from './menu/schema';
+export { UniverSheetsCrosshairHighlightMobileUIPlugin } from './mobile-plugin';
export { UniverSheetsCrosshairHighlightPlugin } from './plugin';
export { SheetsCrosshairHighlightService } from './services/crosshair.service';
diff --git a/packages/sheets-crosshair-highlight/src/menu/mobile-crosshair.menu.ts b/packages/sheets-crosshair-highlight/src/menu/mobile-crosshair.menu.ts
new file mode 100644
index 0000000000..0d61874dfa
--- /dev/null
+++ b/packages/sheets-crosshair-highlight/src/menu/mobile-crosshair.menu.ts
@@ -0,0 +1,44 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IAccessor } from '@univerjs/core';
+import type { IMenuSelectorItem } from '@univerjs/ui';
+import type { LocaleKey } from '../locale/types';
+import { UniverInstanceType } from '@univerjs/core';
+import { getMenuHiddenObservable, MenuItemType } from '@univerjs/ui';
+
+export const MOBILE_CROSSHAIR_HIGHLIGHT_MENU_ID = 'sheet.menu.mobile.crosshair-highlight';
+export const MOBILE_CROSSHAIR_HIGHLIGHT_PANEL = 'MOBILE_CROSSHAIR_HIGHLIGHT_PANEL';
+
+export function MobileCrosshairHighlightMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<LocaleKey> {
+ return {
+ id: MOBILE_CROSSHAIR_HIGHLIGHT_MENU_ID,
+ type: MenuItemType.SELECTOR,
+ icon: 'CrossHighlightingIcon',
+ title: 'sheets-crosshair-highlight.button.tooltip',
+ tooltip: 'sheets-crosshair-highlight.button.tooltip',
+ selections: [
+ {
+ label: {
+ name: MOBILE_CROSSHAIR_HIGHLIGHT_PANEL,
+ hoverable: false,
+ selectable: false,
+ },
+ },
+ ],
+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET),
+ };
+}
diff --git a/packages/sheets-crosshair-highlight/src/menu/mobile-schema.ts b/packages/sheets-crosshair-highlight/src/menu/mobile-schema.ts
new file mode 100644
index 0000000000..f426d0cb8e
--- /dev/null
+++ b/packages/sheets-crosshair-highlight/src/menu/mobile-schema.ts
@@ -0,0 +1,31 @@
+/**
+ * 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 { MenuSchemaType } from '@univerjs/ui';
+import { RibbonDataGroup } from '@univerjs/ui';
+import {
+ MOBILE_CROSSHAIR_HIGHLIGHT_MENU_ID,
+ MobileCrosshairHighlightMenuItemFactory,
+} from './mobile-crosshair.menu';
+
+export const mobileMenuSchema: MenuSchemaType = {
+ [RibbonDataGroup.ORGANIZATION]: {
+ [MOBILE_CROSSHAIR_HIGHLIGHT_MENU_ID]: {
+ order: 21,
+ menuItemFactory: MobileCrosshairHighlightMenuItemFactory,
+ },
+ },
+};
diff --git a/packages/sheets-crosshair-highlight/src/mobile-plugin.ts b/packages/sheets-crosshair-highlight/src/mobile-plugin.ts
new file mode 100644
index 0000000000..0e113d3915
--- /dev/null
+++ b/packages/sheets-crosshair-highlight/src/mobile-plugin.ts
@@ -0,0 +1,67 @@
+/**
+ * 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 { Dependency } from '@univerjs/core';
+import type { IUniverSheetsCrosshairHighlightConfig } from './config/config';
+import { DependentOn, IConfigService, Inject, Injector, merge, Plugin, UniverInstanceType } from '@univerjs/core';
+import { IRenderManagerService, UniverRenderEnginePlugin } from '@univerjs/engine-render';
+import { UniverSheetsPlugin } from '@univerjs/sheets';
+import { UniverSheetsMobileUIPlugin } from '@univerjs/sheets-ui';
+import { UniverMobileUIPlugin } from '@univerjs/ui';
+import pkg from '../package.json';
+import { defaultPluginConfig, SHEETS_CROSSHAIR_HIGHLIGHT_PLUGIN_CONFIG_KEY } from './config/config';
+import { SHEETS_CROSSHAIR_HIGHLIGHT_PLUGIN_NAME } from './const';
+import { ComponentsController } from './controllers/components.controller';
+import { SheetsCrosshairHighlightMobileController } from './controllers/mobile/crosshair.controller';
+import { SheetsCrosshairHighlightService } from './services/crosshair.service';
+import { SheetCrosshairHighlightRenderController } from './views/widgets/crosshair-highlight.render-controller';
+
+@DependentOn(UniverRenderEnginePlugin, UniverSheetsPlugin, UniverSheetsMobileUIPlugin, UniverMobileUIPlugin)
+export class UniverSheetsCrosshairHighlightMobileUIPlugin extends Plugin {
+ static override pluginName = SHEETS_CROSSHAIR_HIGHLIGHT_PLUGIN_NAME;
+ static override packageName = pkg.name;
+ static override version = pkg.version;
+ static override type = UniverInstanceType.UNIVER_SHEET;
+
+ constructor(
+ private readonly _config: Partial<IUniverSheetsCrosshairHighlightConfig> = defaultPluginConfig,
+ @Inject(Injector) protected readonly _injector: Injector,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @IConfigService private readonly _configService: IConfigService
+ ) {
+ super();
+
+ const { ...rest } = merge({}, defaultPluginConfig, this._config);
+ this._configService.setConfig(SHEETS_CROSSHAIR_HIGHLIGHT_PLUGIN_CONFIG_KEY, rest);
+ }
+
+ override onStarting(): void {
+ ([
+ [ComponentsController],
+ [SheetsCrosshairHighlightService],
+ [SheetsCrosshairHighlightMobileController],
+ ] as Dependency[]).forEach((dependency) => this._injector.add(dependency));
+ }
+
+ override onReady(): void {
+ this._injector.get(ComponentsController);
+ this._injector.get(SheetsCrosshairHighlightMobileController);
+ this.disposeWithMe(this._renderManagerService.registerRenderModule(
+ UniverInstanceType.UNIVER_SHEET,
+ [SheetCrosshairHighlightRenderController] as Dependency
+ ));
+ }
+}
diff --git a/packages/sheets-crosshair-highlight/src/plugin.ts b/packages/sheets-crosshair-highlight/src/plugin.ts
index 09b511dcee..225409e595 100644
--- a/packages/sheets-crosshair-highlight/src/plugin.ts
+++ b/packages/sheets-crosshair-highlight/src/plugin.ts
@@ -22,6 +22,7 @@ import { UniverSheetsPlugin } from '@univerjs/sheets';
import { UniverSheetsUIPlugin } from '@univerjs/sheets-ui';
import pkg from '../package.json';
import { defaultPluginConfig, SHEETS_CROSSHAIR_HIGHLIGHT_PLUGIN_CONFIG_KEY } from './config/config';
+import { SHEETS_CROSSHAIR_HIGHLIGHT_PLUGIN_NAME } from './const';
import { ComponentsController } from './controllers/components.controller';
import { SheetsCrosshairHighlightController } from './controllers/crosshair.controller';
import { SheetsCrosshairHighlightService } from './services/crosshair.service';
@@ -29,7 +30,7 @@ import { SheetCrosshairHighlightRenderController } from './views/widgets/crossha
@DependentOn(UniverRenderEnginePlugin, UniverSheetsPlugin, UniverSheetsUIPlugin)
export class UniverSheetsCrosshairHighlightPlugin extends Plugin {
- static override pluginName: string = 'SHEET_CROSSHAIR_HIGHLIGHT_PLUGIN';
+ static override pluginName: string = SHEETS_CROSSHAIR_HIGHLIGHT_PLUGIN_NAME;
static override packageName = pkg.name;
static override version = pkg.version;
static override type = UniverInstanceType.UNIVER_SHEET;
diff --git a/packages/sheets-crosshair-highlight/src/views/mobile/MobileCrosshairHighlightPanel.tsx b/packages/sheets-crosshair-highlight/src/views/mobile/MobileCrosshairHighlightPanel.tsx
new file mode 100644
index 0000000000..d5ee100d5f
--- /dev/null
+++ b/packages/sheets-crosshair-highlight/src/views/mobile/MobileCrosshairHighlightPanel.tsx
@@ -0,0 +1,100 @@
+/**
+ * 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 { ICommandService, LocaleService, ThemeService } from '@univerjs/core';
+import { clsx, resetButtonClassName, Switch } from '@univerjs/design';
+import { useDependency, useObservable } from '@univerjs/ui';
+import { map } from 'rxjs';
+import {
+ DisableCrosshairHighlightOperation,
+ EnableCrosshairHighlightOperation,
+ SetCrosshairHighlightColorOperation,
+} from '../../commands/operations/operation';
+import {
+ CROSSHAIR_HIGHLIGHT_COLOR_THEME_PATHS,
+ resolveCrosshairHighlightColors,
+ SheetsCrosshairHighlightService,
+} from '../../services/crosshair.service';
+
+export function MobileCrosshairHighlightPanel() {
+ const commandService = useDependency(ICommandService);
+ const crosshairHighlightService = useDependency(SheetsCrosshairHighlightService);
+ const localeService = useDependency(LocaleService);
+ const themeService = useDependency(ThemeService);
+ const enabled = useObservable(crosshairHighlightService.enabled$, false);
+ const currentColor = useObservable(crosshairHighlightService.color$);
+ const colors = useObservable(
+ () => themeService.currentTheme$.pipe(map(() => resolveCrosshairHighlightColors(themeService))),
+ resolveCrosshairHighlightColors(themeService),
+ false,
+ [themeService]
+ );
+
+ return (
+ <div className="univer-grid univer-w-full univer-gap-4 univer-p-4">
+ <div className="univer-flex univer-min-h-8 univer-items-center univer-gap-4">
+ <span
+ className="
+ univer-min-w-0 univer-flex-1 univer-text-base univer-font-medium univer-text-gray-900
+ dark:!univer-text-gray-100
+ "
+ >
+ {localeService.t<LocaleKey>('sheets-crosshair-highlight.button.tooltip')}
+ </span>
+ <Switch
+ defaultChecked={enabled}
+ onChange={(checked) => {
+ const operation = checked
+ ? EnableCrosshairHighlightOperation
+ : DisableCrosshairHighlightOperation;
+ commandService.executeCommand(operation.id).catch(() => undefined);
+ }}
+ />
+ </div>
+ <div className="univer-grid univer-grid-cols-8 univer-gap-3">
+ {colors.map((color, index) => {
+ const tokenPath = CROSSHAIR_HIGHLIGHT_COLOR_THEME_PATHS[index];
+ const selected = color === currentColor;
+
+ return (
+ <button
+ key={tokenPath}
+ type="button"
+ data-color-token={tokenPath}
+ title={color}
+ aria-pressed={selected}
+ className={clsx(resetButtonClassName, `
+ univer-box-border univer-size-8 univer-rounded-lg univer-border univer-border-solid
+ univer-border-gray-200 univer-ring-offset-2
+ active:univer-opacity-70
+ dark:!univer-border-gray-600
+ `, {
+ 'univer-ring-2 univer-ring-primary-600': selected,
+ })}
+ style={{ backgroundColor: color }}
+ onClick={() => {
+ commandService.executeCommand(SetCrosshairHighlightColorOperation.id, {
+ value: tokenPath,
+ }).catch(() => undefined);
+ }}
+ />
+ );
+ })}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/sheets-data-validation-ui/src/controllers/dv-render.controller.ts b/packages/sheets-data-validation-ui/src/controllers/dv-render.controller.ts
index 6b8fb33e1b..6a27d5f9f5 100644
--- a/packages/sheets-data-validation-ui/src/controllers/dv-render.controller.ts
+++ b/packages/sheets-data-validation-ui/src/controllers/dv-render.controller.ts
@@ -273,151 +273,3 @@ export class SheetsDataValidationRenderController extends RxDisposable {
});
}
}
-
-// The mobile version does not provide the ability to change data validation model.
-export class SheetsDataValidationMobileRenderController extends RxDisposable {
- constructor(
- @ICommandService private readonly _commandService: ICommandService,
- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @Inject(AutoHeightController) private readonly _autoHeightController: AutoHeightController,
- @Inject(DataValidatorRegistryService) private readonly _dataValidatorRegistryService: DataValidatorRegistryService,
- @Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,
- @Inject(SheetDataValidationModel) private readonly _sheetDataValidationModel: SheetDataValidationModel,
- @Inject(DataValidationCacheService) private readonly _dataValidationCacheService: DataValidationCacheService
- ) {
- super();
-
- this._initViewModelIntercept();
- this._initAutoHeight();
- }
-
- // eslint-disable-next-line max-lines-per-function
- private _initViewModelIntercept() {
- this.disposeWithMe(
- this._sheetInterceptorService.intercept(
- INTERCEPTOR_POINT.CELL_CONTENT,
- {
- effect: InterceptorEffectEnum.Style,
- // must be after numfmt
- priority: InterceptCellContentPriority.DATA_VALIDATION,
- // eslint-disable-next-line complexity, max-lines-per-function
- handler: (cell, pos, next) => {
- const { row, col, unitId, subUnitId, workbook, worksheet } = pos;
-
- const ruleId = this._sheetDataValidationModel.getRuleIdByLocation(unitId, subUnitId, row, col);
- if (!ruleId) {
- return next(cell);
- }
- const rule = this._sheetDataValidationModel.getRuleById(unitId, subUnitId, ruleId);
- if (!rule) {
- return next(cell);
- }
- const validStatus = this._dataValidationCacheService.getValue(unitId, subUnitId, row, col) ?? DataValidationStatus.VALID;
- const validator = this._dataValidatorRegistryService.getValidatorItem(rule.type);
- const cellOrigin = worksheet.getCellRaw(row, col);
- const cellValue = getCellValueOrigin(cellOrigin);
- const valueStr = `${cellValue ?? ''}`;
-
- if (!cell || cell === pos.rawData) {
- cell = { ...pos.rawData };
- }
-
- cell.markers = {
- ...cell?.markers,
- ...validStatus === DataValidationStatus.INVALID ? INVALID_MARK : null,
- };
- cell.customRender = [
- ...(cell?.customRender ?? []),
- ...(validator?.canvasRender ? [validator.canvasRender] : []),
- ];
- cell.fontRenderExtension = {
- ...cell?.fontRenderExtension,
- isSkip: cell?.fontRenderExtension?.isSkip || validator?.skipDefaultFontRender?.(rule, cellValue, pos),
- };
- cell.interceptorStyle = {
- ...cell?.interceptorStyle,
- ...validator?.getExtraStyle(rule, valueStr, {
- get style() {
- const styleMap = workbook.getStyles();
- return (typeof cell?.s === 'string' ? styleMap.get(cell?.s) : cell?.s) || {};
- },
- }, row, col),
- };
- cell.interceptorAutoHeight = () => {
- const skeleton = this._renderManagerService.getRenderUnitById(unitId)
- ?.with(SheetSkeletonManagerService)
- .getSkeletonParam(subUnitId)
- ?.skeleton;
- if (!skeleton) {
- return undefined;
- }
- const mergeCell = skeleton.worksheet.getMergedCell(row, col);
-
- const info: ICellRenderContext = {
- data: cell,
- style: workbook.getStyles().getStyleByCell(cell),
- primaryWithCoord: skeleton.getCellWithCoordByIndex(mergeCell?.startRow ?? row, mergeCell?.startColumn ?? col),
- unitId,
- subUnitId,
- row,
- col,
- workbook,
- worksheet,
- };
- return validator?.canvasRender?.calcCellAutoHeight?.(info);
- };
- cell.interceptorAutoWidth = () => {
- const skeleton = this._renderManagerService.getRenderUnitById(unitId)
- ?.with(SheetSkeletonManagerService)
- .getSkeletonParam(subUnitId)
- ?.skeleton;
- if (!skeleton) {
- return undefined;
- }
- const mergeCell = skeleton.worksheet.getMergedCell(row, col);
-
- const info: ICellRenderContext = {
- data: cell,
- style: workbook.getStyles().getStyleByCell(cell),
- primaryWithCoord: skeleton.getCellWithCoordByIndex(mergeCell?.startRow ?? row, mergeCell?.startColumn ?? col),
- unitId,
- subUnitId,
- row,
- col,
- workbook,
- worksheet,
- };
- return validator?.canvasRender?.calcCellAutoWidth?.(info);
- };
- cell.coverable = (cell?.coverable ?? true) && !(rule.type === DataValidationType.LIST || rule.type === DataValidationType.LIST_MULTIPLE);
-
- return next(cell);
- },
- }
- )
- );
- }
-
- private _initAutoHeight() {
- this._sheetDataValidationModel.ruleChange$
- .pipe(
- filter((change) => change.source === 'command'),
- bufferTime(16)
- )
- .subscribe((infos) => {
- const ranges: IRange[] = [];
- infos.forEach((info) => {
- if (info.rule.type === DataValidationType.LIST_MULTIPLE || info.rule.type === DataValidationType.LIST) {
- if (info.rule?.ranges) {
- ranges.push(...info.rule.ranges);
- }
- }
- });
-
- if (ranges.length) {
- const mutations = this._autoHeightController.getUndoRedoParamsOfAutoHeight(ranges);
- sequenceExecute(mutations.redos, this._commandService);
- }
- });
- }
-}
diff --git a/packages/sheets-data-validation-ui/src/controllers/mobile/components.controller.ts b/packages/sheets-data-validation-ui/src/controllers/mobile/components.controller.ts
new file mode 100644
index 0000000000..6a54f1129c
--- /dev/null
+++ b/packages/sheets-data-validation-ui/src/controllers/mobile/components.controller.ts
@@ -0,0 +1,37 @@
+/**
+ * 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 { Disposable, Inject } from '@univerjs/core';
+import { CheckboxIcon, DataValidationIcon, DatePickerIcon, DropdownListIcon } from '@univerjs/icons';
+import { ComponentManager, IconManager } from '@univerjs/ui';
+import { DROPDOWN_PRESETS_COMPONENT, DropdownPresets } from '../../views/components/DropdownPresets';
+
+export class MobileComponentsController extends Disposable {
+ constructor(
+ @Inject(ComponentManager) componentManager: ComponentManager,
+ @Inject(IconManager) iconManager: IconManager
+ ) {
+ super();
+
+ this.disposeWithMe(componentManager.register(DROPDOWN_PRESETS_COMPONENT, DropdownPresets));
+ this.disposeWithMe(iconManager.register({
+ CheckboxIcon,
+ DataValidationIcon,
+ DatePickerIcon,
+ DropdownListIcon,
+ }));
+ }
+}
diff --git a/packages/sheets-data-validation-ui/src/controllers/mobile/dv-render.controller.ts b/packages/sheets-data-validation-ui/src/controllers/mobile/dv-render.controller.ts
new file mode 100644
index 0000000000..d9fa8d14be
--- /dev/null
+++ b/packages/sheets-data-validation-ui/src/controllers/mobile/dv-render.controller.ts
@@ -0,0 +1,187 @@
+/**
+ * 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 { ICellRenderContext, IRange } from '@univerjs/core';
+import {
+ DataValidationStatus,
+ DataValidationType,
+ ICommandService,
+ Inject,
+ InterceptorEffectEnum,
+ RxDisposable,
+ sequenceExecute,
+} from '@univerjs/core';
+import { DataValidatorRegistryService } from '@univerjs/data-validation';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { InterceptCellContentPriority, INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';
+import { DataValidationCacheService, getCellValueOrigin, SheetDataValidationModel } from '@univerjs/sheets-data-validation';
+import { AutoHeightController, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import { bufferTime, filter } from 'rxjs';
+
+const INVALID_MARK = {
+ tr: {
+ size: 6,
+ color: '#fe4b4b',
+ },
+};
+
+// The mobile version does not provide the ability to change data validation model.
+export class SheetsDataValidationMobileRenderController extends RxDisposable {
+ constructor(
+ @ICommandService private readonly _commandService: ICommandService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @Inject(AutoHeightController) private readonly _autoHeightController: AutoHeightController,
+ @Inject(DataValidatorRegistryService) private readonly _dataValidatorRegistryService: DataValidatorRegistryService,
+ @Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,
+ @Inject(SheetDataValidationModel) private readonly _sheetDataValidationModel: SheetDataValidationModel,
+ @Inject(DataValidationCacheService) private readonly _dataValidationCacheService: DataValidationCacheService
+ ) {
+ super();
+
+ this._initViewModelIntercept();
+ this._initAutoHeight();
+ }
+
+ // eslint-disable-next-line max-lines-per-function
+ private _initViewModelIntercept() {
+ this.disposeWithMe(
+ this._sheetInterceptorService.intercept(
+ INTERCEPTOR_POINT.CELL_CONTENT,
+ {
+ effect: InterceptorEffectEnum.Style,
+ // must be after numfmt
+ priority: InterceptCellContentPriority.DATA_VALIDATION,
+ // eslint-disable-next-line complexity, max-lines-per-function
+ handler: (cell, pos, next) => {
+ const { row, col, unitId, subUnitId, workbook, worksheet } = pos;
+
+ const ruleId = this._sheetDataValidationModel.getRuleIdByLocation(unitId, subUnitId, row, col);
+ if (!ruleId) {
+ return next(cell);
+ }
+ const rule = this._sheetDataValidationModel.getRuleById(unitId, subUnitId, ruleId);
+ if (!rule) {
+ return next(cell);
+ }
+ const validStatus = this._dataValidationCacheService.getValue(unitId, subUnitId, row, col) ?? DataValidationStatus.VALID;
+ const validator = this._dataValidatorRegistryService.getValidatorItem(rule.type);
+ const cellOrigin = worksheet.getCellRaw(row, col);
+ const cellValue = getCellValueOrigin(cellOrigin);
+ const valueStr = `${cellValue ?? ''}`;
+
+ if (!cell || cell === pos.rawData) {
+ cell = { ...pos.rawData };
+ }
+
+ cell.markers = {
+ ...cell?.markers,
+ ...validStatus === DataValidationStatus.INVALID ? INVALID_MARK : null,
+ };
+ cell.customRender = [
+ ...(cell?.customRender ?? []),
+ ...(validator?.canvasRender ? [validator.canvasRender] : []),
+ ];
+ cell.fontRenderExtension = {
+ ...cell?.fontRenderExtension,
+ isSkip: cell?.fontRenderExtension?.isSkip || validator?.skipDefaultFontRender?.(rule, cellValue, pos),
+ };
+ cell.interceptorStyle = {
+ ...cell?.interceptorStyle,
+ ...validator?.getExtraStyle(rule, valueStr, {
+ get style() {
+ const styleMap = workbook.getStyles();
+ return (typeof cell?.s === 'string' ? styleMap.get(cell?.s) : cell?.s) || {};
+ },
+ }, row, col),
+ };
+ cell.interceptorAutoHeight = () => {
+ const skeleton = this._renderManagerService.getRenderUnitById(unitId)
+ ?.with(SheetSkeletonManagerService)
+ .getSkeletonParam(subUnitId)
+ ?.skeleton;
+ if (!skeleton) {
+ return undefined;
+ }
+ const mergeCell = skeleton.worksheet.getMergedCell(row, col);
+
+ const info: ICellRenderContext = {
+ data: cell,
+ style: workbook.getStyles().getStyleByCell(cell),
+ primaryWithCoord: skeleton.getCellWithCoordByIndex(mergeCell?.startRow ?? row, mergeCell?.startColumn ?? col),
+ unitId,
+ subUnitId,
+ row,
+ col,
+ workbook,
+ worksheet,
+ };
+ return validator?.canvasRender?.calcCellAutoHeight?.(info);
+ };
+ cell.interceptorAutoWidth = () => {
+ const skeleton = this._renderManagerService.getRenderUnitById(unitId)
+ ?.with(SheetSkeletonManagerService)
+ .getSkeletonParam(subUnitId)
+ ?.skeleton;
+ if (!skeleton) {
+ return undefined;
+ }
+ const mergeCell = skeleton.worksheet.getMergedCell(row, col);
+
+ const info: ICellRenderContext = {
+ data: cell,
+ style: workbook.getStyles().getStyleByCell(cell),
+ primaryWithCoord: skeleton.getCellWithCoordByIndex(mergeCell?.startRow ?? row, mergeCell?.startColumn ?? col),
+ unitId,
+ subUnitId,
+ row,
+ col,
+ workbook,
+ worksheet,
+ };
+ return validator?.canvasRender?.calcCellAutoWidth?.(info);
+ };
+ cell.coverable = (cell?.coverable ?? true) && !(rule.type === DataValidationType.LIST || rule.type === DataValidationType.LIST_MULTIPLE);
+
+ return next(cell);
+ },
+ }
+ )
+ );
+ }
+
+ private _initAutoHeight() {
+ this._sheetDataValidationModel.ruleChange$
+ .pipe(
+ filter((change) => change.source === 'command'),
+ bufferTime(16)
+ )
+ .subscribe((infos) => {
+ const ranges: IRange[] = [];
+ infos.forEach((info) => {
+ if (info.rule.type === DataValidationType.LIST_MULTIPLE || info.rule.type === DataValidationType.LIST) {
+ if (info.rule?.ranges) {
+ ranges.push(...info.rule.ranges);
+ }
+ }
+ });
+
+ if (ranges.length) {
+ const mutations = this._autoHeightController.getUndoRedoParamsOfAutoHeight(ranges);
+ sequenceExecute(mutations.redos, this._commandService);
+ }
+ });
+ }
+}
diff --git a/packages/sheets-data-validation-ui/src/mobile-plugin.ts b/packages/sheets-data-validation-ui/src/mobile-plugin.ts
index 5c329e7a91..94e3e71eca 100644
--- a/packages/sheets-data-validation-ui/src/mobile-plugin.ts
+++ b/packages/sheets-data-validation-ui/src/mobile-plugin.ts
@@ -24,28 +24,20 @@ import { UniverSheetsDataValidationPlugin } from '@univerjs/sheets-data-validati
import { UniverSheetsMobileUIPlugin } from '@univerjs/sheets-ui';
import { UniverMobileUIPlugin } from '@univerjs/ui';
import pkg from '../package.json';
+import { ClearQuickSheetDataValidationCommand, InsertQuickSheetDataValidationCommand } from './commands/commands/data-validation-ui.command';
import {
- AddSheetDataValidationAndOpenCommand,
- ClearQuickSheetDataValidationCommand,
- InsertQuickSheetDataValidationCommand,
-} from './commands/commands/data-validation-ui.command';
-import {
- CloseValidationPanelOperation,
HideDataValidationDropdown,
- OpenValidationPanelOperation,
ShowDataValidationDropdown,
- ToggleValidationPanelOperation,
} from './commands/operations/data-validation.operation';
import { defaultPluginConfig, SHEETS_DATA_VALIDATION_UI_PLUGIN_CONFIG_KEY } from './config/config';
-import { ComponentsController } from './controllers/components.controller';
import { DataValidationAlertController } from './controllers/dv-alert.controller';
import { DataValidationAutoFillController } from './controllers/dv-auto-fill.controller';
import { DataValidationCopyPasteController } from './controllers/dv-copy-paste.controller';
import { DataValidationPermissionController } from './controllers/dv-permission.controller';
-import { SheetsDataValidationRenderController } from './controllers/dv-render.controller';
import { SheetsDataValidationReRenderController } from './controllers/dv-rerender.controller';
+import { MobileComponentsController } from './controllers/mobile/components.controller';
+import { SheetsDataValidationMobileRenderController } from './controllers/mobile/dv-render.controller';
import { SheetsDataValidationUIController } from './controllers/ui.controller';
-import { DataValidationPanelService } from './services/data-validation-panel.service';
import { DataValidationDropdownManagerService } from './services/dropdown-manager.service';
@DependentOn(
@@ -83,14 +75,13 @@ export class UniverSheetsDataValidationMobileUIPlugin extends Plugin {
}
override onStarting(): void {
- this._injector.add([ComponentsController]);
- this._injector.get(ComponentsController);
+ this._injector.add([MobileComponentsController]);
+ this._injector.get(MobileComponentsController);
([
- [DataValidationPanelService],
[DataValidationDropdownManagerService],
[DataValidationAlertController],
[DataValidationAutoFillController],
- [SheetsDataValidationRenderController],
+ [SheetsDataValidationMobileRenderController],
[DataValidationPermissionController],
[DataValidationCopyPasteController],
[SheetsDataValidationUIController],
@@ -99,14 +90,10 @@ export class UniverSheetsDataValidationMobileUIPlugin extends Plugin {
});
[
- AddSheetDataValidationAndOpenCommand,
InsertQuickSheetDataValidationCommand,
ClearQuickSheetDataValidationCommand,
ShowDataValidationDropdown,
HideDataValidationDropdown,
- CloseValidationPanelOperation,
- OpenValidationPanelOperation,
- ToggleValidationPanelOperation,
].forEach((command) => {
this._commandService.registerCommand(command);
});
@@ -125,7 +112,7 @@ export class UniverSheetsDataValidationMobileUIPlugin extends Plugin {
override onRendered(): void {
this._injector.get(SheetsDataValidationUIController);
- this._injector.get(SheetsDataValidationRenderController);
+ this._injector.get(SheetsDataValidationMobileRenderController);
}
override onSteady(): void {
diff --git a/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-copy-paste.controller.spec.ts b/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-copy-paste.controller.spec.ts
index f841f5e41c..08bcb0f514 100644
--- a/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-copy-paste.controller.spec.ts
+++ b/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-copy-paste.controller.spec.ts
@@ -123,6 +123,48 @@ function createController(options?: { focusedDrawings?: IImageDrawing[]; drawing
}
describe('SheetsDrawingCopyPasteController', () => {
+ it('copies default position-anchored images contained in a cell range', () => {
+ const positionOnlyDrawing = createImageDrawing({
+ drawingId: 'position-only',
+ anchorType: undefined,
+ });
+ const { controller, hook, drawingService } = createController({
+ drawingData: {
+ [positionOnlyDrawing.drawingId]: positionOnlyDrawing,
+ },
+ });
+
+ hook.onBeforeCopy('unit-1', 'sheet-1', {
+ startRow: 0,
+ endRow: 1,
+ startColumn: 0,
+ endColumn: 1,
+ }, COPY_TYPE.COPY);
+ hook.onPasteCells(
+ {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ range: { rows: [0, 1], cols: [0, 1] },
+ },
+ {
+ unitId: 'unit-2',
+ subUnitId: 'sheet-2',
+ range: { rows: [2, 3], cols: [3, 4] },
+ },
+ new ObjectMatrix(),
+ { copyId: 'range-copy', copyType: COPY_TYPE.COPY, pasteType: PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE }
+ );
+
+ expect(drawingService.getBatchAddOp).toHaveBeenCalledTimes(1);
+ expect(drawingService.getBatchAddOp.mock.calls[0][0]).toMatchObject([{
+ unitId: 'unit-2',
+ subUnitId: 'sheet-2',
+ transform: { left: 35, top: 45, width: 10, height: 20 },
+ }]);
+
+ controller.dispose();
+ });
+
it('copies drawings contained in a cell range and pastes them with the range offset', () => {
const containedDrawing = createImageDrawing();
const outsideDrawing = createImageDrawing({
@@ -132,6 +174,11 @@ describe('SheetsDrawingCopyPasteController', () => {
const positionOnlyDrawing = createImageDrawing({
drawingId: 'position-only',
anchorType: SheetDrawingAnchorType.Position,
+ transform: { left: 50, top: 50, width: 10, height: 20 },
+ });
+ const unanchoredDrawing = createImageDrawing({
+ drawingId: 'unanchored',
+ anchorType: SheetDrawingAnchorType.None,
});
const { controller, hook, drawingService } = createController({
focusedDrawings: [outsideDrawing],
@@ -139,6 +186,7 @@ describe('SheetsDrawingCopyPasteController', () => {
[containedDrawing.drawingId]: containedDrawing,
[outsideDrawing.drawingId]: outsideDrawing,
[positionOnlyDrawing.drawingId]: positionOnlyDrawing,
+ [unanchoredDrawing.drawingId]: unanchoredDrawing,
chart: { drawingId: 'chart', drawingType: DrawingTypeEnum.DRAWING_CHART },
},
});
diff --git a/packages/sheets-drawing-ui/src/controllers/mobile/components.controller.ts b/packages/sheets-drawing-ui/src/controllers/mobile/components.controller.ts
new file mode 100644
index 0000000000..9a85028e86
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/controllers/mobile/components.controller.ts
@@ -0,0 +1,31 @@
+/**
+ * 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 { Disposable, Inject } from '@univerjs/core';
+import { ComponentManager } from '@univerjs/ui';
+import { BATCH_SAVE_IMAGES_DIALOG_ID } from '../../views/batch-save-images';
+import { MobileBatchSaveImagesDialog } from '../../views/batch-save-images/MobileBatchSaveImagesDialog';
+import { COMPONENT_SHEET_DRAWING_PANEL } from '../../views/sheet-image-panel/component-name';
+import { SheetDrawingPanel } from '../../views/sheet-image-panel/SheetDrawingPanel';
+
+export class MobileComponentsController extends Disposable {
+ constructor(@Inject(ComponentManager) componentManager: ComponentManager) {
+ super();
+
+ this.disposeWithMe(componentManager.register(COMPONENT_SHEET_DRAWING_PANEL, SheetDrawingPanel));
+ this.disposeWithMe(componentManager.register(BATCH_SAVE_IMAGES_DIALOG_ID, MobileBatchSaveImagesDialog));
+ }
+}
diff --git a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-copy-paste.controller.ts b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-copy-paste.controller.ts
index 5c486f7fe2..c7e1733ccf 100644
--- a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-copy-paste.controller.ts
+++ b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-copy-paste.controller.ts
@@ -241,10 +241,11 @@ export class SheetsDrawingCopyPasteController extends Disposable {
if (drawing.drawingType !== DrawingTypeEnum.DRAWING_IMAGE) {
return;
}
- const { transform } = drawing;
- if ((drawing as ISheetDrawing).anchorType !== SheetDrawingAnchorType.Both) {
+ const anchorType = (drawing as ISheetDrawing).anchorType ?? SheetDrawingAnchorType.Position;
+ if (anchorType === SheetDrawingAnchorType.None) {
return;
}
+ const { transform } = drawing;
if (!transform) {
return;
}
diff --git a/packages/sheets-drawing-ui/src/index.ts b/packages/sheets-drawing-ui/src/index.ts
index f4fe8c1338..2380cfd3f5 100644
--- a/packages/sheets-drawing-ui/src/index.ts
+++ b/packages/sheets-drawing-ui/src/index.ts
@@ -31,6 +31,7 @@ export { SheetDrawingUpdateController } from './controllers/sheet-drawing-update
export { registerSheetsDrawingFloatingHostCapability, SHEETS_DRAWING_FLOATING_HOST_DEPENDENCIES } from './embed';
export { SHEETS_IMAGE_MENU_ID } from './menu/image.menu';
export { menuSchema as SheetsDrawingUIMenuSchema } from './menu/schema';
+export { UniverSheetsDrawingMobileUIPlugin } from './mobile-plugin';
export { UniverSheetsDrawingUIPlugin } from './plugin';
export { BatchSaveImagesService, FileNamePart, IBatchSaveImagesService } from './services/batch-save-images.service';
export type { IBatchSaveImagesConfig, ICellImageInfo } from './services/batch-save-images.service';
diff --git a/packages/sheets-drawing-ui/src/menu/drawing-popup-menu.controller.ts b/packages/sheets-drawing-ui/src/menu/drawing-popup-menu.controller.ts
index 0160d00894..dc4309187b 100644
--- a/packages/sheets-drawing-ui/src/menu/drawing-popup-menu.controller.ts
+++ b/packages/sheets-drawing-ui/src/menu/drawing-popup-menu.controller.ts
@@ -24,16 +24,12 @@ import {
FOCUSING_COMMON_DRAWINGS,
ICommandService,
IContextService,
-
IImageIoService,
Inject,
IUniverInstanceService,
LocaleService,
-
RxDisposable,
- toDisposable,
UniverInstanceType,
-
} from '@univerjs/core';
import { MessageType } from '@univerjs/design';
import { IDrawingManagerService, SetDrawingSelectedOperation } from '@univerjs/drawing';
@@ -48,32 +44,27 @@ import { RemoveSheetDrawingCommand } from '@univerjs/sheets-drawing';
import { SheetCanvasPopManagerService } from '@univerjs/sheets-ui';
import {
FloatingObjectToolbarPosition,
- IDialogService,
IMenuManagerService,
IMessageService,
MenuItemType,
- MOBILE_UI_MODE,
} from '@univerjs/ui';
import { FlipSheetDrawingCommand } from '../commands/commands/flip-drawings.command';
import { EditSheetDrawingOperation } from '../commands/operations/edit-sheet-drawing.operation';
-const MOBILE_IMAGE_ACTIONS_DIALOG_ID = 'sheet-mobile-image-actions';
-
export class DrawingPopupMenuController extends RxDisposable {
private _initImagePopupMenu = new Set<string>();
constructor(
- @Inject(LocaleService) private readonly _localeService: LocaleService,
- @IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,
- @Inject(SheetCanvasPopManagerService) private readonly _canvasPopManagerService: SheetCanvasPopManagerService,
- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @Inject(LocaleService) protected readonly _localeService: LocaleService,
+ @IDrawingManagerService protected readonly _drawingManagerService: IDrawingManagerService,
+ @Inject(SheetCanvasPopManagerService) protected readonly _canvasPopManagerService: SheetCanvasPopManagerService,
+ @IRenderManagerService protected readonly _renderManagerService: IRenderManagerService,
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
- @IMessageService private readonly _messageService: IMessageService,
+ @IMessageService protected readonly _messageService: IMessageService,
@IMenuManagerService private readonly _menuManagerService: IMenuManagerService,
- @IContextService private readonly _contextService: IContextService,
+ @IContextService protected readonly _contextService: IContextService,
@IImageIoService private readonly _ioService: ImageIoService,
- @ICommandService private readonly _commandService: ICommandService,
- @IDialogService private readonly _dialogService: IDialogService
+ @ICommandService protected readonly _commandService: ICommandService
) {
super();
@@ -208,27 +199,6 @@ export class DrawingPopupMenuController extends RxDisposable {
...(menus || this._getImageMenuItems(unitId, subUnitId, drawingId, drawingType)),
...this._getFloatingObjectMenuItems(),
];
- const mobileDialogService = this._getMobileDialogService();
- if (mobileDialogService) {
- mobileDialogService.open({
- id: MOBILE_IMAGE_ACTIONS_DIALOG_ID,
- title: { title: 'sheets-drawing-ui.image-popup.edit' },
- children: {
- label: {
- name: COMPONENT_IMAGE_POPUP_MENU,
- props: {
- popup: {
- extraProps: {
- menuItems,
- dialogId: MOBILE_IMAGE_ACTIONS_DIALOG_ID,
- },
- },
- },
- },
- },
- });
- return toDisposable(() => mobileDialogService.close(MOBILE_IMAGE_ACTIONS_DIALOG_ID));
- }
return this.disposeWithMe(this._canvasPopManagerService.attachPopupToObject(object, {
componentKey: COMPONENT_IMAGE_POPUP_MENU,
@@ -241,10 +211,6 @@ export class DrawingPopupMenuController extends RxDisposable {
}));
}
- private _getMobileDialogService(): IDialogService | null {
- return this._contextService.getContextValue(MOBILE_UI_MODE) ? this._dialogService : null;
- }
-
private _getImageMenuItems(unitId: string, subUnitId: string, drawingId: string, drawingType: number) {
return [
{
diff --git a/packages/sheets-drawing-ui/src/menu/mobile-drawing-popup-menu.controller.ts b/packages/sheets-drawing-ui/src/menu/mobile-drawing-popup-menu.controller.ts
new file mode 100644
index 0000000000..32784674e9
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/menu/mobile-drawing-popup-menu.controller.ts
@@ -0,0 +1,386 @@
+/**
+ * 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, IDrawingSearch, Nullable, Workbook } from '@univerjs/core';
+import type { ImageIoService } from '@univerjs/drawing';
+import type { BaseObject, Scene } from '@univerjs/engine-render';
+import type { ISheetFloatDom } from '@univerjs/sheets-drawing';
+import type { LocaleKey } from '../locale/types';
+import {
+ DrawingTypeEnum,
+ FOCUSING_COMMON_DRAWINGS,
+ ICommandService,
+ IContextService,
+ IImageIoService,
+ Inject,
+ IUniverInstanceService,
+ LocaleService,
+ RxDisposable,
+ toDisposable,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { MessageType } from '@univerjs/design';
+import { IDrawingManagerService, SetDrawingSelectedOperation } from '@univerjs/drawing';
+import {
+ COMPONENT_MOBILE_IMAGE_POPUP_MENU,
+ ImageCropperObject,
+ ImageResetSizeOperation,
+ OpenImageCropOperation,
+} from '@univerjs/drawing-ui';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { RemoveSheetDrawingCommand } from '@univerjs/sheets-drawing';
+import { SheetCanvasPopManagerService } from '@univerjs/sheets-ui';
+import {
+ FloatingObjectToolbarPosition,
+ IDialogService,
+ ILayoutService,
+ IMenuManagerService,
+ IMessageService,
+ MenuItemType,
+} from '@univerjs/ui';
+import { FlipSheetDrawingCommand } from '../commands/commands/flip-drawings.command';
+import { EditSheetDrawingOperation } from '../commands/operations/edit-sheet-drawing.operation';
+
+const MOBILE_IMAGE_ACTIONS_DIALOG_ID = 'sheet-mobile-image-actions';
+const MOBILE_DRAWING_LONG_PRESS_DURATION = 500;
+
+export class MobileDrawingPopupMenuController extends RxDisposable {
+ private readonly _initImagePopupMenu = new Set<string>();
+
+ constructor(
+ @Inject(LocaleService) private readonly _localeService: LocaleService,
+ @IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,
+ @Inject(SheetCanvasPopManagerService)
+ private readonly _canvasPopManagerService: SheetCanvasPopManagerService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @IMessageService private readonly _messageService: IMessageService,
+ @IMenuManagerService private readonly _menuManagerService: IMenuManagerService,
+ @IContextService private readonly _contextService: IContextService,
+ @IImageIoService private readonly _ioService: ImageIoService,
+ @ICommandService private readonly _commandService: ICommandService,
+ @IDialogService private readonly _dialogService: IDialogService,
+ @ILayoutService private readonly _layoutService: ILayoutService
+ ) {
+ super();
+
+ this._init();
+ }
+
+ private _init(): void {
+ this.disposeWithMe(
+ this._univerInstanceService
+ .getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET)
+ .subscribe((workbook) => this._create(workbook))
+ );
+ this.disposeWithMe(
+ this._univerInstanceService
+ .getTypeOfUnitDisposed$<Workbook>(UniverInstanceType.UNIVER_SHEET)
+ .subscribe((workbook) => this._dispose(workbook))
+ );
+ this._univerInstanceService
+ .getAllUnitsForType<Workbook>(UniverInstanceType.UNIVER_SHEET)
+ .forEach((workbook) => this._create(workbook));
+
+ this._setupLoadingStatus();
+ }
+
+ private _setupLoadingStatus(): void {
+ const messageId = 'image-upload-loading';
+ let messageDisposable: IDisposable | undefined;
+
+ this.disposeWithMe(this._ioService.change$.subscribe((status) => {
+ if (status > 0 && !messageDisposable) {
+ messageDisposable = this._messageService.show({
+ id: messageId,
+ type: MessageType.Loading,
+ content: `${this._localeService.t<LocaleKey>('sheets-drawing-ui.uploadLoading.loading')}: ${status}`,
+ duration: 0,
+ });
+ } else if (status === 0) {
+ messageDisposable?.dispose();
+ messageDisposable = undefined;
+ }
+ }));
+ }
+
+ private _dispose(workbook: Workbook): void {
+ super.dispose();
+
+ const unitId = workbook.getUnitId();
+ this._renderManagerService.removeRender(unitId);
+ this._initImagePopupMenu.delete(unitId);
+ }
+
+ private _create(workbook: Nullable<Workbook>): void {
+ if (!workbook) {
+ return;
+ }
+
+ const unitId = workbook.getUnitId();
+ if (this._renderManagerService.has(unitId) && !this._initImagePopupMenu.has(unitId)) {
+ this._popupMenuListener(unitId);
+ this._initImagePopupMenu.add(unitId);
+ }
+ }
+
+ private _hasCropObject(scene: Scene): boolean {
+ for (const object of scene.getAllObjectsByOrder()) {
+ if (object instanceof ImageCropperObject) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private _openDrawingPopup(scene: Scene, object: BaseObject, closeCurrentPopup: () => void): Nullable<IDisposable> {
+ if (this._hasCropObject(scene)) {
+ return null;
+ }
+
+ const drawingParam = this._drawingManagerService.getDrawingOKey(object.oKey);
+ if (!drawingParam) {
+ return null;
+ }
+
+ const { unitId, subUnitId, drawingId, drawingType } = drawingParam;
+ const data = (drawingParam as ISheetFloatDom).data as Record<string, unknown> | undefined;
+ if (data && (data.disablePopup || (data.version === 1 && typeof data.embedId === 'string'))) {
+ return null;
+ }
+
+ const menus = this._canvasPopManagerService.getFeatureMenu(unitId, subUnitId, drawingId, drawingType);
+ const menuItems = [
+ ...(menus || this._getImageMenuItems(unitId, subUnitId, drawingId, drawingType)),
+ ...this._getFloatingObjectMenuItems(),
+ ];
+ const titleKey = this._canvasPopManagerService.getFeatureMenuTitle(drawingType) ??
+ (drawingType === DrawingTypeEnum.DRAWING_IMAGE
+ ? 'sheets-drawing-ui.title'
+ : 'sheets-drawing-ui.image-popup.edit');
+ closeCurrentPopup();
+ this._dialogService.open({
+ id: MOBILE_IMAGE_ACTIONS_DIALOG_ID,
+ title: { title: this._localeService.t(titleKey) },
+ children: {
+ label: {
+ name: COMPONENT_MOBILE_IMAGE_POPUP_MENU,
+ props: {
+ popup: {
+ extraProps: { menuItems, dialogId: MOBILE_IMAGE_ACTIONS_DIALOG_ID },
+ },
+ },
+ },
+ },
+ });
+ return toDisposable(() => this._dialogService.close(MOBILE_IMAGE_ACTIONS_DIALOG_ID));
+ }
+
+ private _trackActivePointer(clearLongPressTimer: () => void) {
+ const contentElement = this._layoutService.getContentElement();
+ let activePointerId: number | undefined;
+ const handlePointerDown = (event: PointerEvent) => {
+ if (event.isPrimary && event.button === 0) {
+ activePointerId = event.pointerId;
+ }
+ };
+ const handlePointerEnd = (event: PointerEvent) => {
+ if (event.pointerId === activePointerId) {
+ activePointerId = undefined;
+ clearLongPressTimer();
+ }
+ };
+
+ contentElement?.addEventListener('pointerdown', handlePointerDown, true);
+ contentElement?.addEventListener('pointerup', handlePointerEnd, true);
+ contentElement?.addEventListener('pointercancel', handlePointerEnd, true);
+
+ return {
+ getActivePointerId: () => activePointerId,
+ disposable: toDisposable(() => {
+ contentElement?.removeEventListener('pointerdown', handlePointerDown, true);
+ contentElement?.removeEventListener('pointerup', handlePointerEnd, true);
+ contentElement?.removeEventListener('pointercancel', handlePointerEnd, true);
+ }),
+ };
+ }
+
+ private _getSelectedDrawingObject(
+ transformer: { getSelectedObjectMap: () => Map<string, BaseObject> },
+ drawing: IDrawingSearch
+ ): Nullable<BaseObject> {
+ const selectedObjects = transformer.getSelectedObjectMap();
+ if (selectedObjects.size !== 1) {
+ return null;
+ }
+
+ const selectedObject = selectedObjects.values().next().value as Nullable<BaseObject>;
+ const selectedDrawing = selectedObject
+ ? this._drawingManagerService.getDrawingOKey(selectedObject.oKey)
+ : null;
+ return selectedObject &&
+ selectedDrawing?.unitId === drawing.unitId &&
+ selectedDrawing.subUnitId === drawing.subUnitId &&
+ selectedDrawing.drawingId === drawing.drawingId
+ ? selectedObject
+ : null;
+ }
+
+ private _popupMenuListener(unitId: string): void {
+ const scene = this._renderManagerService.getRenderUnitById(unitId)?.scene;
+ if (!scene) {
+ return;
+ }
+ const transformer = scene.getTransformerByCreate();
+ if (!transformer) {
+ return;
+ }
+
+ let singletonPopupDisposer: IDisposable;
+ let longPressTimer: ReturnType<typeof setTimeout> | undefined;
+ const clearLongPressTimer = () => {
+ if (longPressTimer === undefined) {
+ return;
+ }
+
+ clearTimeout(longPressTimer);
+ longPressTimer = undefined;
+ };
+ const pointerTracker = this._trackActivePointer(clearLongPressTimer);
+ this.disposeWithMe(pointerTracker.disposable);
+ this.disposeWithMe(toDisposable(() => {
+ clearLongPressTimer();
+ singletonPopupDisposer?.dispose();
+ }));
+ this.disposeWithMe(transformer.createControl$.subscribe(() => {
+ clearLongPressTimer();
+ this._contextService.setContextValue(FOCUSING_COMMON_DRAWINGS, true);
+ }));
+ this.disposeWithMe(transformer.changeStart$.subscribe(({ target, objects }) => {
+ clearLongPressTimer();
+ singletonPopupDisposer?.dispose();
+ if (pointerTracker.getActivePointerId() === undefined || !target || objects.size !== 1 || this._hasCropObject(scene)) {
+ return;
+ }
+
+ const drawingParam = this._drawingManagerService.getDrawingOKey(target.oKey);
+ if (!drawingParam) {
+ return;
+ }
+
+ longPressTimer = setTimeout(() => {
+ longPressTimer = undefined;
+ const selectedObject = this._getSelectedDrawingObject(transformer, drawingParam);
+ if (!selectedObject) {
+ return;
+ }
+
+ const popupDisposer = this._openDrawingPopup(
+ scene,
+ selectedObject,
+ () => singletonPopupDisposer?.dispose()
+ );
+ if (popupDisposer) {
+ singletonPopupDisposer = popupDisposer;
+ }
+ }, MOBILE_DRAWING_LONG_PRESS_DURATION);
+ }));
+ this.disposeWithMe(transformer.clearControl$.subscribe(() => {
+ clearLongPressTimer();
+ singletonPopupDisposer?.dispose();
+ this._contextService.setContextValue(FOCUSING_COMMON_DRAWINGS, false);
+ this._commandService.syncExecuteCommand(SetDrawingSelectedOperation.id, []);
+ }));
+ this.disposeWithMe(this._contextService.contextChanged$.subscribe((event) => {
+ if (event[FOCUSING_COMMON_DRAWINGS] === false) {
+ singletonPopupDisposer?.dispose();
+ }
+ }));
+ this.disposeWithMe(transformer.changing$.subscribe(() => {
+ clearLongPressTimer();
+ singletonPopupDisposer?.dispose();
+ }));
+ this.disposeWithMe(transformer.changeEnd$.subscribe(() => {
+ clearLongPressTimer();
+ }));
+ }
+
+ private _getImageMenuItems(unitId: string, subUnitId: string, drawingId: string, drawingType: number) {
+ return [
+ {
+ label: 'sheets-drawing-ui.image-popup.edit',
+ index: 0,
+ commandId: EditSheetDrawingOperation.id,
+ commandParams: { unitId, subUnitId, drawingId },
+ disable: drawingType === DrawingTypeEnum.DRAWING_DOM,
+ },
+ {
+ label: 'sheets-drawing-ui.image-popup.delete',
+ index: 1,
+ commandId: RemoveSheetDrawingCommand.id,
+ commandParams: { unitId, drawings: [{ unitId, subUnitId, drawingId }] },
+ disable: false,
+ },
+ {
+ label: 'sheets-drawing-ui.image-popup.crop',
+ index: 2,
+ commandId: OpenImageCropOperation.id,
+ commandParams: { unitId, subUnitId, drawingId },
+ disable: drawingType === DrawingTypeEnum.DRAWING_DOM,
+ },
+ {
+ label: 'sheets-drawing-ui.image-popup.flipH',
+ index: 2,
+ commandId: FlipSheetDrawingCommand.id,
+ commandParams: { unitId, flipH: true, drawings: [{ unitId, subUnitId, drawingId }] },
+ disable: drawingType === DrawingTypeEnum.DRAWING_DOM,
+ },
+ {
+ label: 'sheets-drawing-ui.image-popup.flipV',
+ index: 2,
+ commandId: FlipSheetDrawingCommand.id,
+ commandParams: { unitId, flipV: true, drawings: [{ unitId, subUnitId, drawingId }] },
+ disable: drawingType === DrawingTypeEnum.DRAWING_DOM,
+ },
+ {
+ label: 'sheets-drawing-ui.image-popup.reset',
+ index: 3,
+ commandId: ImageResetSizeOperation.id,
+ commandParams: [{ unitId, subUnitId, drawingId }],
+ disable: drawingType === DrawingTypeEnum.DRAWING_DOM,
+ },
+ ];
+ }
+
+ private _getFloatingObjectMenuItems() {
+ return this._menuManagerService
+ .getFlatMenuByPositionKey(FloatingObjectToolbarPosition.SHEET)
+ .flatMap(({ item }, index) => {
+ if (!item || item.type !== MenuItemType.BUTTON || !item.title) {
+ return [];
+ }
+
+ return [{
+ label: item.title,
+ index: 100 + index,
+ commandId: item.commandId ?? item.id,
+ commandParams: typeof item.params === 'function' ? item.params() : item.params,
+ disable: false,
+ }];
+ });
+ }
+}
diff --git a/packages/sheets-drawing-ui/src/mobile-plugin.ts b/packages/sheets-drawing-ui/src/mobile-plugin.ts
new file mode 100644
index 0000000000..30a5ee2e1d
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/mobile-plugin.ts
@@ -0,0 +1,152 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Dependency } from '@univerjs/core';
+import type { IUniverSheetsDrawingUIConfig } from './config/config';
+import {
+ DependentOn,
+ IConfigService,
+ Inject,
+ Injector,
+ merge,
+ mergeOverrideWithDependencies,
+ Plugin,
+ registerDependencies,
+ touchDependencies,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { UniverDocsDrawingPlugin } from '@univerjs/docs-drawing';
+import { UniverDrawingPlugin } from '@univerjs/drawing';
+import { UniverDrawingMobileUIPlugin } from '@univerjs/drawing-ui';
+import { IRenderManagerService, UniverRenderEnginePlugin } from '@univerjs/engine-render';
+import { UniverSheetsPlugin } from '@univerjs/sheets';
+import { UniverSheetsDrawingPlugin } from '@univerjs/sheets-drawing';
+import { UniverSheetsMobileUIPlugin } from '@univerjs/sheets-ui';
+import { UniverMobileUIPlugin } from '@univerjs/ui';
+import pkg from '../package.json';
+import { defaultPluginConfig, SHEETS_DRAWING_UI_PLUGIN_CONFIG_KEY } from './config/config';
+import { DrawingContextMenuController } from './controllers/drawing-context-menu.controller';
+import { MobileComponentsController } from './controllers/mobile/components.controller';
+import { SheetCellImageHoverRenderController } from './controllers/render-controllers/sheet-celll-image-hover.render-controller';
+import { SheetsDrawingRenderController } from './controllers/render-controllers/sheet-drawing.render-controller';
+import { SheetCellImageAutofillController } from './controllers/sheet-cell-image-autofill.controller';
+import { SheetCellImageCopyPasteController } from './controllers/sheet-cell-image-copy-paste.controller';
+import { SheetCellImageController } from './controllers/sheet-cell-image.controller';
+import { SheetDrawingActiveRenderController } from './controllers/sheet-drawing-active-render.controller';
+import { SheetsDrawingCopyPasteController } from './controllers/sheet-drawing-copy-paste.controller';
+import { SheetsDrawingGroupCopyPasteController } from './controllers/sheet-drawing-group-copy-paste.controller';
+import { SheetDrawingPermissionController } from './controllers/sheet-drawing-permission.controller';
+import { SheetDrawingPrintingController } from './controllers/sheet-drawing-printing.controller';
+import { SheetDrawingUpdateController } from './controllers/sheet-drawing-update.controller';
+import { SheetDrawingUIController } from './controllers/ui.controller';
+import { touchSheetsDrawingFloatingHostCapabilityWhenReady } from './embed/floating-host';
+import { MobileDrawingPopupMenuController } from './menu/mobile-drawing-popup-menu.controller';
+import { BatchSaveImagesService, IBatchSaveImagesService } from './services/batch-save-images.service';
+import { SheetCanvasFloatDomManagerService } from './services/canvas-float-dom-manager.service';
+import { DrawingContextMenuService, IDrawingContextMenuService } from './services/drawing-context-menu.service';
+import { SheetDrawingHitTestService } from './services/sheet-drawing-hit-test.service';
+
+@DependentOn(
+ UniverDrawingPlugin,
+ UniverRenderEnginePlugin,
+ UniverDocsDrawingPlugin,
+ UniverSheetsPlugin,
+ UniverSheetsDrawingPlugin,
+ UniverDrawingMobileUIPlugin,
+ UniverSheetsMobileUIPlugin,
+ UniverMobileUIPlugin
+)
+export class UniverSheetsDrawingMobileUIPlugin extends Plugin {
+ static override type = UniverInstanceType.UNIVER_SHEET;
+ static override pluginName = 'SHEET_IMAGE_UI_PLUGIN';
+ static override packageName = pkg.name;
+ static override version = pkg.version;
+
+ constructor(
+ private readonly _config: Partial<IUniverSheetsDrawingUIConfig> = defaultPluginConfig,
+ @Inject(Injector) protected readonly _injector: Injector,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @IConfigService private readonly _configService: IConfigService
+ ) {
+ super();
+
+ const { menu, ...rest } = merge({}, defaultPluginConfig, this._config);
+ if (menu) {
+ this._configService.setConfig('menu', menu, { merge: true });
+ }
+ this._configService.setConfig(SHEETS_DRAWING_UI_PLUGIN_CONFIG_KEY, rest);
+ }
+
+ override onStarting(): void {
+ const dependencies = [
+ [MobileComponentsController],
+ [SheetCanvasFloatDomManagerService],
+ [SheetDrawingHitTestService],
+ [SheetDrawingUIController],
+ [MobileDrawingPopupMenuController],
+ [SheetDrawingPrintingController],
+ [SheetDrawingPermissionController],
+ [SheetsDrawingCopyPasteController],
+ [SheetsDrawingGroupCopyPasteController],
+ [SheetCellImageController],
+ [SheetCellImageAutofillController],
+ [SheetCellImageCopyPasteController],
+ [IBatchSaveImagesService, { useClass: BatchSaveImagesService }],
+ [IDrawingContextMenuService, { useClass: DrawingContextMenuService }],
+ [DrawingContextMenuController],
+ ] as Dependency[];
+
+ registerDependencies(this._injector, mergeOverrideWithDependencies(dependencies, this._config.overrides));
+ touchSheetsDrawingFloatingHostCapabilityWhenReady(this._injector);
+ this._injector.get(MobileComponentsController);
+ }
+
+ override onReady(): void {
+ touchDependencies(this._injector, [
+ [SheetsDrawingCopyPasteController],
+ [SheetCellImageCopyPasteController],
+ [SheetsDrawingGroupCopyPasteController],
+ ]);
+ }
+
+ override onRendered(): void {
+ this._registerRenderModules();
+
+ touchDependencies(this._injector, [
+ [SheetDrawingPermissionController],
+ [SheetDrawingPrintingController],
+ [SheetDrawingUIController],
+ [SheetCellImageController],
+ [SheetCellImageAutofillController],
+ ]);
+ }
+
+ override onSteady(): void {
+ this._injector.get(MobileDrawingPopupMenuController);
+ this._injector.get(DrawingContextMenuController);
+ }
+
+ private _registerRenderModules(): void {
+ ([
+ [SheetDrawingUpdateController],
+ [SheetDrawingActiveRenderController],
+ [SheetsDrawingRenderController],
+ [SheetCellImageHoverRenderController],
+ ] as Dependency[]).forEach((module) => {
+ this.disposeWithMe(this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, module));
+ });
+ }
+}
diff --git a/packages/sheets-drawing-ui/src/views/batch-save-images/BatchSaveImagesDialog.tsx b/packages/sheets-drawing-ui/src/views/batch-save-images/BatchSaveImagesDialog.tsx
index cec4e68c30..7f8a1a293c 100644
--- a/packages/sheets-drawing-ui/src/views/batch-save-images/BatchSaveImagesDialog.tsx
+++ b/packages/sheets-drawing-ui/src/views/batch-save-images/BatchSaveImagesDialog.tsx
@@ -24,7 +24,11 @@ import { useCallback, useMemo, useState } from 'react';
import { FileNamePart, IBatchSaveImagesService } from '../../services/batch-save-images.service';
import { BATCH_SAVE_IMAGES_DIALOG_ID } from './component-name';
-export function BatchSaveImagesDialog() {
+export interface IBatchSaveImagesDialogProps {
+ SelectComponent?: typeof Select;
+}
+
+export function BatchSaveImagesDialog({ SelectComponent = Select }: IBatchSaveImagesDialogProps = {}) {
const localeService = useDependency(LocaleService);
const dialogService = useDependency(IDialogService);
const batchSaveService = useDependency(IBatchSaveImagesService);
@@ -132,7 +136,7 @@ export function BatchSaveImagesDialog() {
{showColumnSelect && (
<FormLayout label={localeService.t<LocaleKey>('sheets-drawing-ui.save.selectColumn')}>
- <Select
+ <SelectComponent
value={selectedColumn}
options={columnOptions}
onChange={handleColumnChange}
diff --git a/packages/sheets-drawing-ui/src/views/batch-save-images/MobileBatchSaveImagesDialog.tsx b/packages/sheets-drawing-ui/src/views/batch-save-images/MobileBatchSaveImagesDialog.tsx
new file mode 100644
index 0000000000..dd3358f677
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/views/batch-save-images/MobileBatchSaveImagesDialog.tsx
@@ -0,0 +1,22 @@
+/**
+ * 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 { MobileSelect } from '@univerjs/design';
+import { BatchSaveImagesDialog } from './BatchSaveImagesDialog';
+
+export function MobileBatchSaveImagesDialog() {
+ return <BatchSaveImagesDialog SelectComponent={MobileSelect} />;
+}
diff --git a/packages/sheets-filter-ui/src/controllers/mobile/components.controller.ts b/packages/sheets-filter-ui/src/controllers/mobile/components.controller.ts
new file mode 100644
index 0000000000..b4ee901119
--- /dev/null
+++ b/packages/sheets-filter-ui/src/controllers/mobile/components.controller.ts
@@ -0,0 +1,27 @@
+/**
+ * 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 { Disposable, Inject } from '@univerjs/core';
+import { FilterIcon } from '@univerjs/icons';
+import { IconManager } from '@univerjs/ui';
+
+export class MobileComponentsController extends Disposable {
+ constructor(@Inject(IconManager) iconManager: IconManager) {
+ super();
+
+ this.disposeWithMe(iconManager.register({ FilterIcon }));
+ }
+}
diff --git a/packages/sheets-filter-ui/src/controllers/mobile/ui.controller.ts b/packages/sheets-filter-ui/src/controllers/mobile/ui.controller.ts
new file mode 100644
index 0000000000..b988484cdc
--- /dev/null
+++ b/packages/sheets-filter-ui/src/controllers/mobile/ui.controller.ts
@@ -0,0 +1,85 @@
+/**
+ * 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 { Dependency } from '@univerjs/core';
+import { ICommandService, Inject, Injector, LocaleService, RxDisposable, UniverInstanceType } from '@univerjs/core';
+import { MessageType } from '@univerjs/design';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import {
+ ReCalcSheetsFilterMutation,
+ RemoveSheetsFilterMutation,
+ SetSheetsFilterCriteriaMutation,
+ SetSheetsFilterRangeMutation,
+ SheetsFilterService,
+} from '@univerjs/sheets-filter';
+import { SheetsRenderService } from '@univerjs/sheets-ui';
+import { BuiltInUIPart, connectInjector, IMessageService, IUIPartsService } from '@univerjs/ui';
+import {
+ ChangeFilterByOperation,
+ CloseFilterPanelOperation,
+ OpenFilterPanelOperation,
+} from '../../commands/operations/sheets-filter.operation';
+import { MobileSheetsFilterPanel } from '../../views/mobile/MobileSheetsFilterPanel';
+import { SheetsFilterRenderController } from '../../views/render-modules/sheets-filter.render-controller';
+
+export class SheetsFilterUIMobileController extends RxDisposable {
+ constructor(
+ @Inject(Injector) injector: Injector,
+ @ICommandService commandService: ICommandService,
+ @Inject(LocaleService) localeService: LocaleService,
+ @Inject(SheetsFilterService) sheetsFilterService: SheetsFilterService,
+ @IMessageService messageService: IMessageService,
+ @IUIPartsService uiPartsService: IUIPartsService,
+ @IRenderManagerService renderManagerService: IRenderManagerService,
+ @Inject(SheetsRenderService) sheetsRenderService: SheetsRenderService
+ ) {
+ super();
+
+ [
+ ChangeFilterByOperation,
+ OpenFilterPanelOperation,
+ CloseFilterPanelOperation,
+ ].forEach((command) => {
+ this.disposeWithMe(commandService.registerCommand(command));
+ });
+
+ [
+ SetSheetsFilterRangeMutation,
+ SetSheetsFilterCriteriaMutation,
+ RemoveSheetsFilterMutation,
+ ReCalcSheetsFilterMutation,
+ ].forEach((mutation) => {
+ this.disposeWithMe(sheetsRenderService.registerSkeletonChangingMutations(mutation.id));
+ });
+
+ this.disposeWithMe(renderManagerService.registerRenderModule(
+ UniverInstanceType.UNIVER_SHEET,
+ [SheetsFilterRenderController] as Dependency
+ ));
+ this.disposeWithMe(uiPartsService.registerComponent(
+ BuiltInUIPart.GLOBAL,
+ () => connectInjector(MobileSheetsFilterPanel, injector)
+ ));
+ this.disposeWithMe(sheetsFilterService.errorMsg$.subscribe((content) => {
+ if (content) {
+ messageService.show({
+ type: MessageType.Error,
+ content: localeService.t(content),
+ });
+ }
+ }));
+ }
+}
diff --git a/packages/sheets-filter-ui/src/controllers/ui-mobile.controller.ts b/packages/sheets-filter-ui/src/controllers/ui-mobile.controller.ts
deleted file mode 100644
index 844a6dfddd..0000000000
--- a/packages/sheets-filter-ui/src/controllers/ui-mobile.controller.ts
+++ /dev/null
@@ -1,48 +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 type { Dependency } from '@univerjs/core';
-import { Inject, RxDisposable, UniverInstanceType } from '@univerjs/core';
-import { IRenderManagerService } from '@univerjs/engine-render';
-import {
- ReCalcSheetsFilterMutation,
- RemoveSheetsFilterMutation,
- SetSheetsFilterCriteriaMutation,
- SetSheetsFilterRangeMutation,
-} from '@univerjs/sheets-filter';
-import { SheetsRenderService } from '@univerjs/sheets-ui';
-import { SheetsFilterRenderController } from '../views/render-modules/sheets-filter.render-controller';
-
-export class SheetsFilterUIMobileController extends RxDisposable {
- constructor(
- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @Inject(SheetsRenderService) private _sheetsRenderService: SheetsRenderService
- ) {
- super();
-
- [
- SetSheetsFilterRangeMutation,
- SetSheetsFilterCriteriaMutation,
- RemoveSheetsFilterMutation,
- ReCalcSheetsFilterMutation,
- ].forEach((m) => this.disposeWithMe(this._sheetsRenderService.registerSkeletonChangingMutations(m.id)));
-
- this.disposeWithMe(this._renderManagerService.registerRenderModule(
- UniverInstanceType.UNIVER_SHEET,
- [SheetsFilterRenderController] as Dependency
- ));
- }
-}
diff --git a/packages/sheets-filter-ui/src/controllers/ui.controller.ts b/packages/sheets-filter-ui/src/controllers/ui.controller.ts
index 74a8e3c1be..ff6851784d 100644
--- a/packages/sheets-filter-ui/src/controllers/ui.controller.ts
+++ b/packages/sheets-filter-ui/src/controllers/ui.controller.ts
@@ -14,11 +14,18 @@
* limitations under the License.
*/
-import type { IDisposable, Nullable } from '@univerjs/core';
-import { ICommandService, IContextService, Inject, Injector, LocaleService } from '@univerjs/core';
+import type { Dependency, IDisposable, Nullable } from '@univerjs/core';
+import { ICommandService, IContextService, Inject, Injector, LocaleService, RxDisposable, UniverInstanceType } from '@univerjs/core';
import { MessageType } from '@univerjs/design';
import { IRenderManagerService } from '@univerjs/engine-render';
-import { SheetsFilterService, SmartToggleSheetsFilterCommand } from '@univerjs/sheets-filter';
+import {
+ ReCalcSheetsFilterMutation,
+ RemoveSheetsFilterMutation,
+ SetSheetsFilterCriteriaMutation,
+ SetSheetsFilterRangeMutation,
+ SheetsFilterService,
+ SmartToggleSheetsFilterCommand,
+} from '@univerjs/sheets-filter';
import { SheetCanvasPopManagerService, SheetsRenderService } from '@univerjs/sheets-ui';
import { IMenuManagerService, IMessageService, IShortcutService } from '@univerjs/ui';
import { distinctUntilChanged } from 'rxjs';
@@ -31,13 +38,13 @@ import {
import { menuSchema } from '../menu/schema';
import { ISheetsFilterPanelService } from '../services/sheets-filter-panel.service';
import { FILTER_PANEL_POPUP_KEY } from '../views/components/SheetsFilterPanel';
+import { SheetsFilterRenderController } from '../views/render-modules/sheets-filter.render-controller';
import { SmartToggleFilterShortcut } from './sheets-filter.shortcut';
-import { SheetsFilterUIMobileController } from './ui-mobile.controller';
/**
* This controller controls the UI of "filter" features. Menus, commands and filter panel etc. Except for the rendering.
*/
-export class SheetsFilterUIDesktopController extends SheetsFilterUIMobileController {
+export class SheetsFilterUIDesktopController extends RxDisposable {
constructor(
@Inject(Injector) private readonly _injector: Injector,
@ISheetsFilterPanelService private readonly _sheetsFilterPanelService: ISheetsFilterPanelService,
@@ -52,7 +59,20 @@ export class SheetsFilterUIDesktopController extends SheetsFilterUIMobileControl
@Inject(SheetsRenderService) sheetsRenderService: SheetsRenderService,
@IRenderManagerService renderManagerService: IRenderManagerService
) {
- super(renderManagerService, sheetsRenderService);
+ super();
+
+ [
+ SetSheetsFilterRangeMutation,
+ SetSheetsFilterCriteriaMutation,
+ RemoveSheetsFilterMutation,
+ ReCalcSheetsFilterMutation,
+ ].forEach((mutation) => {
+ this.disposeWithMe(sheetsRenderService.registerSkeletonChangingMutations(mutation.id));
+ });
+ this.disposeWithMe(renderManagerService.registerRenderModule(
+ UniverInstanceType.UNIVER_SHEET,
+ [SheetsFilterRenderController] as Dependency
+ ));
this._initCommands();
this._initShortcuts();
diff --git a/packages/sheets-filter-ui/src/locale/ar-SA.ts b/packages/sheets-filter-ui/src/locale/ar-SA.ts
index e35e122154..5ad3430a0b 100644
--- a/packages/sheets-filter-ui/src/locale/ar-SA.ts
+++ b/packages/sheets-filter-ui/src/locale/ar-SA.ts
@@ -33,6 +33,13 @@ const locale: typeof enUS = {
'clear-filter': 'مسح التصفية',
cancel: 'إلغاء',
confirm: 'تأكيد',
+ mobile: {
+ resize: 'تغيير حجم لوحة التصفية',
+ back: 'رجوع',
+ column: 'العمود {0}',
+ 'previous-column': 'العمود السابق',
+ 'next-column': 'العمود التالي',
+ },
'by-values': 'حسب القيم',
'by-colors': 'حسب الألوان',
'filter-by-cell-fill-color': 'تصفية حسب لون تعبئة الخلية',
diff --git a/packages/sheets-filter-ui/src/locale/ca-ES.ts b/packages/sheets-filter-ui/src/locale/ca-ES.ts
index f64dcf035a..e24359b552 100644
--- a/packages/sheets-filter-ui/src/locale/ca-ES.ts
+++ b/packages/sheets-filter-ui/src/locale/ca-ES.ts
@@ -33,6 +33,13 @@ const locale: typeof enUS = {
'clear-filter': 'Neteja el filtre',
cancel: 'Cancel·la',
confirm: 'Confirma',
+ mobile: {
+ resize: 'Redimensiona el tauler de filtre',
+ back: 'Enrere',
+ column: 'Columna {0}',
+ 'previous-column': 'Columna anterior',
+ 'next-column': 'Columna següent',
+ },
'by-values': 'Per valors',
'by-colors': 'Per colors',
'filter-by-cell-fill-color': 'Filtra per color de fons de la cel·la',
diff --git a/packages/sheets-filter-ui/src/locale/de-DE.ts b/packages/sheets-filter-ui/src/locale/de-DE.ts
index 87db81f25d..b23488903d 100644
--- a/packages/sheets-filter-ui/src/locale/de-DE.ts
+++ b/packages/sheets-filter-ui/src/locale/de-DE.ts
@@ -33,6 +33,13 @@ const locale: typeof enUS = {
'clear-filter': 'Filter löschen',
cancel: 'Abbrechen',
confirm: 'Bestätigen',
+ mobile: {
+ resize: 'Größe des Filterbereichs ändern',
+ back: 'Zurück',
+ column: 'Spalte {0}',
+ 'previous-column': 'Vorherige Spalte',
+ 'next-column': 'Nächste Spalte',
+ },
'by-values': 'Nach Werten',
'by-colors': 'Nach Farben',
'filter-by-cell-fill-color': 'Nach Zellenfüllfarbe filtern',
diff --git a/packages/sheets-filter-ui/src/locale/en-US.ts b/packages/sheets-filter-ui/src/locale/en-US.ts
index a9dc16c8df..6ec0304e6e 100644
--- a/packages/sheets-filter-ui/src/locale/en-US.ts
+++ b/packages/sheets-filter-ui/src/locale/en-US.ts
@@ -31,6 +31,13 @@ const locale = {
'clear-filter': 'Clear Filter',
cancel: 'Cancel',
confirm: 'Confirm',
+ mobile: {
+ resize: 'Resize filter panel',
+ back: 'Back',
+ column: 'Column {0}',
+ 'previous-column': 'Previous column',
+ 'next-column': 'Next column',
+ },
'by-values': 'By Values',
'by-colors': 'By Colors',
'filter-by-cell-fill-color': 'Filter by cell fill color',
diff --git a/packages/sheets-filter-ui/src/locale/es-ES.ts b/packages/sheets-filter-ui/src/locale/es-ES.ts
index ae4fc790d5..e02c5b2a6b 100644
--- a/packages/sheets-filter-ui/src/locale/es-ES.ts
+++ b/packages/sheets-filter-ui/src/locale/es-ES.ts
@@ -33,6 +33,13 @@ const locale: typeof enUS = {
'clear-filter': 'Borrar filtro',
cancel: 'Cancelar',
confirm: 'Confirmar',
+ mobile: {
+ resize: 'Cambiar el tamaño del panel de filtro',
+ back: 'Volver',
+ column: 'Columna {0}',
+ 'previous-column': 'Columna anterior',
+ 'next-column': 'Columna siguiente',
+ },
'by-values': 'Por valores',
'by-colors': 'Por colores',
'filter-by-cell-fill-color': 'Filtrar por color de relleno de celda',
diff --git a/packages/sheets-filter-ui/src/locale/fa-IR.ts b/packages/sheets-filter-ui/src/locale/fa-IR.ts
index 9daa8dcedc..960c53366e 100644
--- a/packages/sheets-filter-ui/src/locale/fa-IR.ts
+++ b/packages/sheets-filter-ui/src/locale/fa-IR.ts
@@ -33,6 +33,13 @@ const locale: typeof enUS = {
'clear-filter': 'پاک کردن فیلتر',
cancel: 'انصراف',
confirm: 'تایید',
+ mobile: {
+ resize: 'تغییر اندازه پنل فیلتر',
+ back: 'بازگشت',
+ column: 'ستون {0}',
+ 'previous-column': 'ستون قبلی',
+ 'next-column': 'ستون بعدی',
+ },
'by-values': 'بر اساس مقادیر',
'by-colors': 'بر اساس رنگ‌ها',
'filter-by-cell-fill-color': 'فیلتر بر اساس رنگ پر کردن سلول',
diff --git a/packages/sheets-filter-ui/src/locale/fr-FR.ts b/packages/sheets-filter-ui/src/locale/fr-FR.ts
index 92e47e5f6c..ee44f3387f 100644
--- a/packages/sheets-filter-ui/src/locale/fr-FR.ts
+++ b/packages/sheets-filter-ui/src/locale/fr-FR.ts
@@ -33,6 +33,13 @@ const locale: typeof enUS = {
'clear-filter': 'Effacer le filtre',
cancel: 'Annuler',
confirm: 'Confirmer',
+ mobile: {
+ resize: 'Redimensionner le panneau de filtre',
+ back: 'Retour',
+ column: 'Colonne {0}',
+ 'previous-column': 'Colonne précédente',
+ 'next-column': 'Colonne suivante',
+ },
'by-values': 'Par valeurs',
'by-colors': 'Par couleurs',
'filter-by-cell-fill-color': 'Filtrer par couleur de remplissage de cellule',
diff --git a/packages/sheets-filter-ui/src/locale/id-ID.ts b/packages/sheets-filter-ui/src/locale/id-ID.ts
index ddac148926..1e85463048 100644
--- a/packages/sheets-filter-ui/src/locale/id-ID.ts
+++ b/packages/sheets-filter-ui/src/locale/id-ID.ts
@@ -33,6 +33,13 @@ const locale: typeof enUS = {
'clear-filter': 'Hapus Filter',
cancel: 'Batal',
confirm: 'Konfirmasi',
+ mobile: {
+ resize: 'Ubah ukuran panel filter',
+ back: 'Kembali',
+ column: 'Kolom {0}',
+ 'previous-column': 'Kolom sebelumnya',
+ 'next-column': 'Kolom berikutnya',
+ },
'by-values': 'Berdasarkan Nilai',
'by-colors': 'Berdasarkan Warna',
'filter-by-cell-fill-color': 'Filter berdasarkan warna isi sel',
diff --git a/packages/sheets-filter-ui/src/locale/it-IT.ts b/packages/sheets-filter-ui/src/locale/it-IT.ts
index 2787990bd3..e25e57355f 100644
--- a/packages/sheets-filter-ui/src/locale/it-IT.ts
+++ b/packages/sheets-filter-ui/src/locale/it-IT.ts
@@ -33,6 +33,13 @@ const locale: typeof enUS = {
'clear-filter': 'Cancella filtro',
cancel: 'Annulla',
confirm: 'Conferma',
+ mobile: {
+ resize: 'Ridimensiona il pannello filtro',
+ back: 'Indietro',
+ column: 'Colonna {0}',
+ 'previous-column': 'Colonna precedente',
+ 'next-column': 'Colonna successiva',
+ },
'by-values': 'Per valori',
'by-colors': 'Per colori',
'filter-by-cell-fill-color': 'Filtra per colore di riempimento cella',
diff --git a/packages/sheets-filter-ui/src/locale/ja-JP.ts b/packages/sheets-filter-ui/src/locale/ja-JP.ts
index 65cbd3e24c..5219f0776a 100644
--- a/packages/sheets-filter-ui/src/locale/ja-JP.ts
+++ b/packages/sheets-filter-ui/src/locale/ja-JP.ts
@@ -33,6 +33,13 @@ const locale: typeof enUS = {
'clear-filter': 'フィルタをクリア',
cancel: 'キャンセル',
confirm: '確認',
+ mobile: {
+ resize: 'フィルターパネルのサイズを変更',
+ back: '戻る',
+ column: '{0} 列',
+ 'previous-column': '前の列',
+ 'next-column': '次の列',
+ },
'by-values': '値でフィルタ',
'by-colors': '色でフィルタ',
'filter-by-cell-fill-color': 'セルの塗りつぶし色でフィルタ',
diff --git a/packages/sheets-filter-ui/src/locale/ko-KR.ts b/packages/sheets-filter-ui/src/locale/ko-KR.ts
index 447ee3036e..f2e9e50f54 100644
--- a/packages/sheets-filter-ui/src/locale/ko-KR.ts
+++ b/packages/sheets-filter-ui/src/locale/ko-KR.ts
@@ -33,6 +33,13 @@ const locale: typeof enUS = {
'clear-filter': '필터 지우기',
cancel: '취소',
confirm: '확인',
+ mobile: {
+ resize: '필터 패널 크기 조정',
+ back: '뒤로',
+ column: '{0} 열',
+ 'previous-column': '이전 열',
+ 'next-column': '다음 열',
+ },
'by-values': '값으로 필터',
'by-colors': '색상으로 필터',
'filter-by-cell-fill-color': '셀 채우기 색상으로 필터',
diff --git a/packages/sheets-filter-ui/src/locale/pl-PL.ts b/packages/sheets-filter-ui/src/locale/pl-PL.ts
index 175b87bc00..6416c4e89d 100644
--- a/packages/sheets-filter-ui/src/locale/pl-PL.ts
+++ b/packages/sheets-filter-ui/src/locale/pl-PL.ts
@@ -33,6 +33,13 @@ const locale: typeof enUS = {
'clear-filter': 'Wyczyść filtr',
cancel: 'Anuluj',
confirm: 'Potwierdź',
+ mobile: {
+ resize: 'Zmień rozmiar panelu filtra',
+ back: 'Wstecz',
+ column: 'Kolumna {0}',
+ 'previous-column': 'Poprzednia kolumna',
+ 'next-column': 'Następna kolumna',
+ },
'by-values': 'Według wartości',
'by-colors': 'Według kolorów',
'filter-by-cell-fill-color': 'Filtruj według koloru wypełnienia komórki',
diff --git a/packages/sheets-filter-ui/src/locale/pt-BR.ts b/packages/sheets-filter-ui/src/locale/pt-BR.ts
index 5f4e191bb4..57581ded3d 100644
--- a/packages/sheets-filter-ui/src/locale/pt-BR.ts
+++ b/packages/sheets-filter-ui/src/locale/pt-BR.ts
@@ -33,6 +33,13 @@ const locale: typeof enUS = {
'clear-filter': 'Limpar Filtro',
cancel: 'Cancelar',
confirm: 'Confirmar',
+ mobile: {
+ resize: 'Redimensionar o painel de filtro',
+ back: 'Voltar',
+ column: 'Coluna {0}',
+ 'previous-column': 'Coluna anterior',
+ 'next-column': 'Próxima coluna',
+ },
'by-values': 'Por Valores',
'by-colors': 'Por Cores',
'filter-by-cell-fill-color': 'Filtrar por cor de preenchimento da célula',
diff --git a/packages/sheets-filter-ui/src/locale/ru-RU.ts b/packages/sheets-filter-ui/src/locale/ru-RU.ts
index 04bd6addda..f1e3919e8e 100644
--- a/packages/sheets-filter-ui/src/locale/ru-RU.ts
+++ b/packages/sheets-filter-ui/src/locale/ru-RU.ts
@@ -33,6 +33,13 @@ const locale: typeof enUS = {
'clear-filter': 'Очистить фильтр',
cancel: 'Отмена',
confirm: 'Подтвердить',
+ mobile: {
+ resize: 'Изменить размер панели фильтра',
+ back: 'Назад',
+ column: 'Столбец {0}',
+ 'previous-column': 'Предыдущий столбец',
+ 'next-column': 'Следующий столбец',
+ },
'by-values': 'По значениям',
'by-colors': 'По цветам',
'filter-by-cell-fill-color': 'Фильтр по цвету заливки ячейки',
diff --git a/packages/sheets-filter-ui/src/locale/sk-SK.ts b/packages/sheets-filter-ui/src/locale/sk-SK.ts
index c529591c2b..1b915f2ea6 100644
--- a/packages/sheets-filter-ui/src/locale/sk-SK.ts
+++ b/packages/sheets-filter-ui/src/locale/sk-SK.ts
@@ -33,6 +33,13 @@ const locale: typeof enUS = {
'clear-filter': 'Vymazať filter',
cancel: 'Zrušiť',
confirm: 'Potvrdiť',
+ mobile: {
+ resize: 'Zmeniť veľkosť panela filtra',
+ back: 'Späť',
+ column: 'Stĺpec {0}',
+ 'previous-column': 'Predchádzajúci stĺpec',
+ 'next-column': 'Nasledujúci stĺpec',
+ },
'by-values': 'Podľa hodnôt',
'by-colors': 'Podľa farieb',
'filter-by-cell-fill-color': 'Filtrovať podľa farby výplne bunky',
diff --git a/packages/sheets-filter-ui/src/locale/vi-VN.ts b/packages/sheets-filter-ui/src/locale/vi-VN.ts
index 3298f5630f..1558163b27 100644
--- a/packages/sheets-filter-ui/src/locale/vi-VN.ts
+++ b/packages/sheets-filter-ui/src/locale/vi-VN.ts
@@ -33,6 +33,13 @@ const locale: typeof enUS = {
'clear-filter': 'Xóa lọc',
cancel: 'Hủy bỏ',
confirm: 'Xác nhận',
+ mobile: {
+ resize: 'Thay đổi kích thước bảng lọc',
+ back: 'Quay lại',
+ column: 'Cột {0}',
+ 'previous-column': 'Cột trước',
+ 'next-column': 'Cột tiếp theo',
+ },
'by-values': 'Theo giá trị',
'by-colors': 'Theo màu sắc',
'filter-by-cell-fill-color': 'Lọc theo màu nền ô',
diff --git a/packages/sheets-filter-ui/src/locale/zh-CN.ts b/packages/sheets-filter-ui/src/locale/zh-CN.ts
index 4813294155..a335871a9e 100644
--- a/packages/sheets-filter-ui/src/locale/zh-CN.ts
+++ b/packages/sheets-filter-ui/src/locale/zh-CN.ts
@@ -33,6 +33,13 @@ const locale: typeof enUS = {
'clear-filter': '清除筛选',
cancel: '取消',
confirm: '确认',
+ mobile: {
+ resize: '调整筛选面板',
+ back: '返回',
+ column: '{0} 列',
+ 'previous-column': '上一列',
+ 'next-column': '下一列',
+ },
'by-values': '按值',
'by-colors': '按颜色',
'filter-by-cell-fill-color': '按单元格填充颜色筛选',
diff --git a/packages/sheets-filter-ui/src/locale/zh-HK.ts b/packages/sheets-filter-ui/src/locale/zh-HK.ts
index 30409edf3c..e54be41239 100644
--- a/packages/sheets-filter-ui/src/locale/zh-HK.ts
+++ b/packages/sheets-filter-ui/src/locale/zh-HK.ts
@@ -33,6 +33,13 @@ const locale: typeof enUS = {
'clear-filter': '清除篩選',
cancel: '取消',
confirm: '確認',
+ mobile: {
+ resize: '調整篩選面板',
+ back: '返回',
+ column: '{0} 欄',
+ 'previous-column': '上一欄',
+ 'next-column': '下一欄',
+ },
'by-values': '按值',
'by-colors': '按顏色',
'filter-by-cell-fill-color': '按儲存格填充顏色篩選',
diff --git a/packages/sheets-filter-ui/src/locale/zh-TW.ts b/packages/sheets-filter-ui/src/locale/zh-TW.ts
index 30409edf3c..e54be41239 100644
--- a/packages/sheets-filter-ui/src/locale/zh-TW.ts
+++ b/packages/sheets-filter-ui/src/locale/zh-TW.ts
@@ -33,6 +33,13 @@ const locale: typeof enUS = {
'clear-filter': '清除篩選',
cancel: '取消',
confirm: '確認',
+ mobile: {
+ resize: '調整篩選面板',
+ back: '返回',
+ column: '{0} 欄',
+ 'previous-column': '上一欄',
+ 'next-column': '下一欄',
+ },
'by-values': '按值',
'by-colors': '按顏色',
'filter-by-cell-fill-color': '按儲存格填充顏色篩選',
diff --git a/packages/sheets-filter-ui/src/mobile-plugin.ts b/packages/sheets-filter-ui/src/mobile-plugin.ts
index 0fe5c53cac..ac7acd88c4 100644
--- a/packages/sheets-filter-ui/src/mobile-plugin.ts
+++ b/packages/sheets-filter-ui/src/mobile-plugin.ts
@@ -24,10 +24,11 @@ import { UniverSheetsMobileUIPlugin } from '@univerjs/sheets-ui';
import { UniverMobileUIPlugin } from '@univerjs/ui';
import pkg from '../package.json';
import { defaultPluginConfig, SHEETS_FILTER_UI_PLUGIN_CONFIG_KEY } from './config/config';
-import { ComponentsController } from './controllers/components.controller';
import { SheetsFilterMobileMenuController } from './controllers/mobile-menu.controller';
+import { MobileComponentsController } from './controllers/mobile/components.controller';
+import { SheetsFilterUIMobileController } from './controllers/mobile/ui.controller';
import { SheetsFilterPermissionController } from './controllers/sheets-filter-permission.controller';
-import { SheetsFilterUIMobileController } from './controllers/ui-mobile.controller';
+import { ISheetsFilterPanelService, SheetsFilterPanelService } from './services/sheets-filter-panel.service';
@DependentOn(
UniverRenderEnginePlugin,
@@ -62,9 +63,10 @@ export class UniverSheetsFilterMobileUIPlugin extends Plugin {
}
override onStarting(): void {
- this._injector.add([ComponentsController]);
- this._injector.get(ComponentsController);
+ this._injector.add([MobileComponentsController]);
+ this._injector.get(MobileComponentsController);
([
+ [ISheetsFilterPanelService, { useClass: SheetsFilterPanelService }],
[SheetsFilterPermissionController],
[SheetsFilterMobileMenuController],
[SheetsFilterUIMobileController],
diff --git a/packages/sheets-filter-ui/src/views/mobile/MobileFilterByColor.tsx b/packages/sheets-filter-ui/src/views/mobile/MobileFilterByColor.tsx
new file mode 100644
index 0000000000..8217755349
--- /dev/null
+++ b/packages/sheets-filter-ui/src/views/mobile/MobileFilterByColor.tsx
@@ -0,0 +1,115 @@
+/**
+ * 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 { ByColorsModel, IFilterByColorItem } from '../../services/sheets-filter-panel.service';
+import { LocaleService } from '@univerjs/core';
+import { clsx, resetButtonClassName } from '@univerjs/design';
+import { AIcon, BanIcon, CheckMarkIcon } from '@univerjs/icons';
+import { useDependency, useObservable } from '@univerjs/ui';
+
+function MobileColorOption(props: {
+ item: IFilterByColorItem;
+ label: string;
+ textColor?: boolean;
+ onSelect: () => void;
+}) {
+ const { item, label, textColor = false, onSelect } = props;
+
+ return (
+ <button
+ type="button"
+ aria-label={item.color ?? label}
+ aria-pressed={item.checked}
+ className={clsx(resetButtonClassName, `
+ univer-relative univer-flex univer-size-12 univer-items-center univer-justify-center univer-rounded-full
+ univer-border univer-border-solid univer-border-gray-200 univer-bg-gray-0
+ dark:!univer-border-gray-600 dark:!univer-bg-gray-800
+ `)}
+ style={!textColor && item.color ? { backgroundColor: item.color } : undefined}
+ onClick={onSelect}
+ >
+ {!item.color && <BanIcon className="univer-size-7" />}
+ {textColor && item.color && <AIcon className="univer-size-7" style={{ color: item.color }} />}
+ {item.checked && (
+ <span
+ className="
+ univer-absolute -univer-bottom-1 -univer-right-1 univer-flex univer-size-5 univer-items-center
+ univer-justify-center univer-rounded-full univer-bg-primary-600 univer-text-gray-0
+ "
+ >
+ <CheckMarkIcon className="univer-size-3" />
+ </span>
+ )}
+ </button>
+ );
+}
+
+export function MobileFilterByColor(props: { model: ByColorsModel }) {
+ const { model } = props;
+ const localeService = useDependency(LocaleService);
+ const cellFillColors = useObservable(model.cellFillColors$, [], true);
+ const cellTextColors = useObservable(model.cellTextColors$, [], true);
+ const fillLabel = localeService.t<LocaleKey>('sheets-filter-ui.panel.filter-by-cell-fill-color');
+ const textLabel = localeService.t<LocaleKey>('sheets-filter-ui.panel.filter-by-cell-text-color');
+ const hasMultipleColors = cellFillColors.length > 1 || cellTextColors.length > 1;
+
+ return (
+ <div
+ data-u-comp="mobile-sheets-filter-by-colors"
+ className="univer-flex univer-min-h-full univer-flex-col univer-gap-6"
+ >
+ {cellFillColors.length > 1 && (
+ <section>
+ <h3 className="univer-m-0 univer-mb-4 univer-text-base univer-font-medium">{fillLabel}</h3>
+ <div className="univer-flex univer-flex-wrap univer-gap-4">
+ {cellFillColors.map((item) => (
+ <MobileColorOption
+ key={item.color ?? 'none'}
+ item={item}
+ label={fillLabel}
+ onSelect={() => model.onFilterCheckToggled(item)}
+ />
+ ))}
+ </div>
+ </section>
+ )}
+ {cellTextColors.length > 1 && (
+ <section>
+ <h3 className="univer-m-0 univer-mb-4 univer-text-base univer-font-medium">{textLabel}</h3>
+ <div className="univer-flex univer-flex-wrap univer-gap-4">
+ {cellTextColors.map((item) => (
+ <MobileColorOption
+ key={item.color ?? 'none'}
+ item={item}
+ label={textLabel}
+ textColor
+ onSelect={() => model.onFilterCheckToggled(item, false)}
+ />
+ ))}
+ </div>
+ </section>
+ )}
+ {!hasMultipleColors && (
+ <div
+ className="univer-flex univer-flex-1 univer-items-center univer-justify-center univer-text-gray-500"
+ >
+ {localeService.t<LocaleKey>('sheets-filter-ui.panel.filter-by-color-none')}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/packages/sheets-filter-ui/src/views/mobile/MobileFilterByCondition.tsx b/packages/sheets-filter-ui/src/views/mobile/MobileFilterByCondition.tsx
new file mode 100644
index 0000000000..dc64fbed24
--- /dev/null
+++ b/packages/sheets-filter-ui/src/views/mobile/MobileFilterByCondition.tsx
@@ -0,0 +1,137 @@
+/**
+ * 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 { FilterOperator } from '../../models/conditions';
+import type { ByConditionsModel } from '../../services/sheets-filter-panel.service';
+import { LocaleService } from '@univerjs/core';
+import { Input, MobileSelect, Radio, RadioGroup } from '@univerjs/design';
+import { useDependency, useObservable } from '@univerjs/ui';
+import { FilterConditionItems } from '../../models/conditions';
+
+export function MobileFilterByCondition(props: { model: ByConditionsModel }) {
+ const { model } = props;
+ const localeService = useDependency(LocaleService);
+ const condition = useObservable(model.conditionItem$, undefined, true);
+ const formParams = useObservable(model.filterConditionFormParams$, undefined, true);
+ const secondaryOptions = FilterConditionItems.ALL_CONDITIONS
+ .filter((item) => item.numOfParameters !== 2)
+ .map((item) => ({ label: localeService.t(item.label), value: item.operator }));
+
+ if (!condition || !formParams) {
+ return null;
+ }
+
+ function renderSecondaryCondition(operator: FilterOperator, value: string, name: 'operator1' | 'operator2') {
+ const needsValue = FilterConditionItems.getItemByOperator(operator).numOfParameters === 1;
+ return (
+ <div className="univer-grid univer-gap-3">
+ {name === 'operator2' && (
+ <RadioGroup
+ value={formParams?.and ? 'AND' : 'OR'}
+ onChange={(join) => model.onConditionFormChange({ and: join === 'AND' })}
+ >
+ <Radio value="AND">{localeService.t<LocaleKey>('sheets-filter-ui.panel.and')}</Radio>
+ <Radio value="OR">{localeService.t<LocaleKey>('sheets-filter-ui.panel.or')}</Radio>
+ </RadioGroup>
+ )}
+ <MobileSelect
+ value={operator}
+ options={secondaryOptions}
+ onChange={(nextOperator) => model.onConditionFormChange({
+ [name]: nextOperator as FilterOperator,
+ })}
+ />
+ {needsValue && (
+ <Input
+ value={value}
+ placeholder={localeService.t<LocaleKey>('sheets-filter-ui.panel.input-values-placeholder')}
+ onChange={(nextValue) => model.onConditionFormChange({
+ [name === 'operator1' ? 'val1' : 'val2']: nextValue,
+ })}
+ />
+ )}
+ </div>
+ );
+ }
+
+ function renderConditionEditor() {
+ return (
+ <div className="univer-grid univer-gap-3 univer-pb-4 univer-pl-7">
+ {condition!.numOfParameters === 1 && (
+ <Input
+ value={formParams!.val1 ?? ''}
+ placeholder={localeService.t<LocaleKey>('sheets-filter-ui.panel.input-values-placeholder')}
+ onChange={(value) => model.onConditionFormChange({ val1: value })}
+ />
+ )}
+ {condition!.numOfParameters >= 2 && renderSecondaryCondition(
+ formParams!.operator1!,
+ formParams!.val1 ?? '',
+ 'operator1'
+ )}
+ {condition!.numOfParameters >= 2 && renderSecondaryCondition(
+ formParams!.operator2!,
+ formParams!.val2 ?? '',
+ 'operator2'
+ )}
+ <p className="univer-m-0 univer-text-xs univer-text-gray-500">
+ {localeService.t<LocaleKey>('sheets-filter-ui.panel.?')}
+ <br />
+ {localeService.t<LocaleKey>('sheets-filter-ui.panel.*')}
+ </p>
+ </div>
+ );
+ }
+
+ return (
+ <div data-u-comp="mobile-sheets-filter-by-conditions" className="univer-grid univer-gap-4">
+ <div
+ className="
+ univer-overflow-hidden univer-rounded-xl univer-bg-gray-0
+ dark:!univer-bg-gray-800
+ "
+ >
+ {FilterConditionItems.ALL_CONDITIONS.map((item) => {
+ const selected = condition.operator === item.operator;
+ return (
+ <div
+ key={item.operator}
+ data-u-comp="mobile-filter-condition-item"
+ data-selected={selected}
+ className="
+ univer-border-0 univer-border-b univer-border-solid univer-border-gray-200 univer-px-4
+ last:univer-border-b-0
+ dark:!univer-border-gray-700
+ "
+ >
+ <Radio
+ value={item.operator}
+ checked={selected}
+ onChange={(operator) => model.onPrimaryConditionChange(operator as FilterOperator)}
+ >
+ <span className="univer-flex univer-min-h-12 univer-items-center univer-text-base">
+ {localeService.t(item.label)}
+ </span>
+ </Radio>
+ {selected && condition.numOfParameters > 0 && renderConditionEditor()}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/sheets-filter-ui/src/views/mobile/MobileFilterByValue.tsx b/packages/sheets-filter-ui/src/views/mobile/MobileFilterByValue.tsx
new file mode 100644
index 0000000000..9481ee17fb
--- /dev/null
+++ b/packages/sheets-filter-ui/src/views/mobile/MobileFilterByValue.tsx
@@ -0,0 +1,130 @@
+/**
+ * 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 { ByValuesModel, IFilterByValueWithTreeItem } from '../../services/sheets-filter-panel.service';
+import { LocaleService } from '@univerjs/core';
+import { Checkbox, Input, resetButtonClassName, Tree } from '@univerjs/design';
+import { CloseIcon, SearchIcon } from '@univerjs/icons';
+import { useDependency, useObservable } from '@univerjs/ui';
+import { useState } from 'react';
+import { statisticFilterByValueItems } from '../../models/utils';
+
+function extractCheckedKeys(items: IFilterByValueWithTreeItem[]): string[] {
+ let checkedKeys: string[] = [];
+ items.forEach((item) => {
+ if (item.checked) {
+ checkedKeys.push(item.key);
+ }
+ if (item.children) {
+ checkedKeys = checkedKeys.concat(extractCheckedKeys(item.children));
+ }
+ });
+ return checkedKeys;
+}
+
+export function MobileFilterByValue(props: { model: ByValuesModel }) {
+ const { model } = props;
+ const localeService = useDependency(LocaleService);
+ const [searching, setSearching] = useState(false);
+ const searchText = useObservable(model.searchString$, '', true);
+ const items = useObservable(model.filterItems$, [], true);
+ const stat = statisticFilterByValueItems(items);
+ const allChecked = stat.checked > 0 && stat.unchecked === 0;
+ const indeterminate = stat.checked > 0 && stat.unchecked > 0;
+ const searchLabel = localeService.t<LocaleKey>('sheets-filter-ui.panel.search-placeholder');
+
+ return (
+ <div data-u-comp="mobile-sheets-filter-by-values" className="univer-flex univer-min-h-full univer-flex-col">
+ <div
+ className="
+ univer-flex univer-min-h-14 univer-items-center univer-border-0 univer-border-b univer-border-solid
+ univer-border-gray-200 univer-px-2
+ dark:!univer-border-gray-700
+ "
+ >
+ {searching
+ ? (
+ <>
+ <Input
+ autoFocus
+ className="univer-flex-1"
+ value={searchText}
+ placeholder={searchLabel}
+ onChange={(value) => model.setSearchString(value)}
+ />
+ <button
+ type="button"
+ aria-label={localeService.t<LocaleKey>('sheets-filter-ui.panel.cancel')}
+ className={`
+ ${resetButtonClassName}
+ univer-ml-2 univer-flex univer-size-10 univer-items-center univer-justify-center
+ `}
+ onClick={() => {
+ model.setSearchString('');
+ setSearching(false);
+ }}
+ >
+ <CloseIcon className="univer-size-5" />
+ </button>
+ </>
+ )
+ : (
+ <>
+ <Checkbox
+ className="univer-min-h-12 univer-flex-1 univer-text-base"
+ contentClassName="univer-flex univer-items-center univer-gap-1"
+ indeterminate={indeterminate}
+ disabled={items.length === 0}
+ checked={allChecked}
+ onChange={() => model.onCheckAllToggled(!allChecked)}
+ >
+ <span>{localeService.t<LocaleKey>('sheets-filter-ui.panel.select-all')}</span>
+ <span className="univer-text-sm univer-text-gray-500">
+ {`(${stat.checked}/${stat.checked + stat.unchecked})`}
+ </span>
+ </Checkbox>
+ <button
+ type="button"
+ aria-label={searchLabel}
+ className={`
+ ${resetButtonClassName}
+ univer-flex univer-size-12 univer-items-center univer-justify-center
+ `}
+ onClick={() => setSearching(true)}
+ >
+ <SearchIcon className="univer-size-6" />
+ </button>
+ </>
+ )}
+ </div>
+ <div className="univer-min-h-0 univer-flex-1 univer-py-2">
+ <Tree
+ data={items}
+ defaultExpandAll={false}
+ valueGroup={extractCheckedKeys(items)}
+ onChange={(node) => model.onFilterCheckToggled(node as IFilterByValueWithTreeItem)}
+ defaultCache={model.treeMapCache}
+ itemHeight={48}
+ treeNodeClassName="univer-h-full univer-pr-2 univer-text-base univer-text-gray-900 dark:!univer-text-gray-0"
+ attachRender={(item) => (
+ <span className="univer-ml-auto univer-text-sm univer-text-gray-500">{`(${item.count})`}</span>
+ )}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/packages/sheets-filter-ui/src/views/mobile/MobileSheetsFilterPanel.tsx b/packages/sheets-filter-ui/src/views/mobile/MobileSheetsFilterPanel.tsx
new file mode 100644
index 0000000000..12a0200ce1
--- /dev/null
+++ b/packages/sheets-filter-ui/src/views/mobile/MobileSheetsFilterPanel.tsx
@@ -0,0 +1,320 @@
+/**
+ * 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 { MobileDrawerSnap } from '@univerjs/ui';
+import type { LocaleKey } from '../../locale/types';
+import type {
+ ByColorsModel,
+ ByConditionsModel,
+ ByValuesModel,
+} from '../../services/sheets-filter-panel.service';
+import { ICommandService, IContextService, LocaleService, Tools } from '@univerjs/core';
+import {
+ Button,
+ MessageType,
+ MobileActionRow,
+ MobileActionRowGroup,
+ resetButtonClassName,
+ Switch,
+} from '@univerjs/design';
+import { MoreLeftIcon, MoreRightIcon } from '@univerjs/icons';
+import { FilterBy, SheetsFilterSyncController } from '@univerjs/sheets-filter';
+import { IMessageService, MobileDrawer, useDependency, useObservable } from '@univerjs/ui';
+import { useRef, useState } from 'react';
+import { map, of } from 'rxjs';
+import {
+ ChangeFilterByOperation,
+ CloseFilterPanelOperation,
+ FILTER_PANEL_OPENED_KEY,
+} from '../../commands/operations/sheets-filter.operation';
+import { ISheetsFilterPanelService } from '../../services/sheets-filter-panel.service';
+import { MobileFilterByColor } from './MobileFilterByColor';
+import { MobileFilterByCondition } from './MobileFilterByCondition';
+import { MobileFilterByValue } from './MobileFilterByValue';
+
+const FILTER_BY_OPTIONS: Array<{ label: LocaleKey; value: FilterBy }> = [
+ { label: 'sheets-filter-ui.panel.by-values', value: FilterBy.VALUES },
+ { label: 'sheets-filter-ui.panel.by-colors', value: FilterBy.COLORS },
+ { label: 'sheets-filter-ui.panel.by-conditions', value: FilterBy.CONDITIONS },
+];
+
+function MobileFilterSyncSwitch() {
+ const localeService = useDependency(LocaleService);
+ const messageService = useDependency(IMessageService);
+ const filterSyncController = useDependency(SheetsFilterSyncController);
+ const visible = useObservable(filterSyncController.visible$, false, true);
+ const enabled = useObservable(filterSyncController.enabled$, true, true);
+
+ if (!visible) {
+ return null;
+ }
+
+ return (
+ <div
+ className="
+ univer-flex univer-min-h-20 univer-items-center univer-gap-4 univer-rounded-xl univer-bg-gray-0
+ univer-px-4 univer-py-3
+ dark:!univer-bg-gray-800
+ "
+ >
+ <div className="univer-min-w-0 univer-flex-1">
+ <div
+ className="
+ univer-text-base univer-font-medium univer-text-gray-900
+ dark:!univer-text-gray-100
+ "
+ >
+ {localeService.t<LocaleKey>('sheets-filter-ui.sync.title')}
+ </div>
+ <div
+ className="
+ univer-mt-1 univer-text-sm univer-text-gray-500
+ dark:!univer-text-gray-400
+ "
+ >
+ {localeService.t<LocaleKey>(enabled
+ ? 'sheets-filter-ui.sync.statusTips.on'
+ : 'sheets-filter-ui.sync.statusTips.off')}
+ </div>
+ </div>
+ <Switch
+ defaultChecked={enabled}
+ onChange={(checked) => {
+ filterSyncController.setEnabled(checked);
+ messageService.show({
+ content: localeService.t<LocaleKey>(checked
+ ? 'sheets-filter-ui.sync.switchTips.on'
+ : 'sheets-filter-ui.sync.switchTips.off'),
+ type: MessageType.Success,
+ duration: 2000,
+ });
+ }}
+ />
+ </div>
+ );
+}
+
+export function MobileSheetsFilterPanel() {
+ const contextService = useDependency(IContextService);
+ const visible = useObservable(
+ () => contextService.subscribeContextValue$(FILTER_PANEL_OPENED_KEY).pipe(map(Boolean)),
+ Boolean(contextService.getContextValue(FILTER_PANEL_OPENED_KEY)),
+ false,
+ [contextService]
+ );
+
+ return visible ? <MobileSheetsFilterPanelContent /> : null;
+}
+
+function MobileSheetsFilterPanelContent() {
+ const commandService = useDependency(ICommandService);
+ const localeService = useDependency(LocaleService);
+ const panelService = useDependency(ISheetsFilterPanelService);
+ const filterBy = useObservable(panelService.filterBy$, FilterBy.VALUES, true);
+ const filterByModel = useObservable(panelService.filterByModel$, null);
+ const canApply = useObservable(() => filterByModel?.canApply$ ?? of(false), false, true, [filterByModel]);
+ const hasCriteria = useObservable(panelService.hasCriteria$, false, true);
+ const col = useObservable(panelService.col$, panelService.col, true);
+ const [detailOpen, setDetailOpen] = useState(false);
+ const [drawerSnap, setDrawerSnap] = useState<MobileDrawerSnap>('compact');
+ const layerRef = useRef<HTMLDivElement>(null);
+
+ const filterRange = panelService.filterModel?.getRange();
+ const title = detailOpen
+ ? localeService.t<LocaleKey>(FILTER_BY_OPTIONS.find((option) => option.value === filterBy)!.label)
+ : localeService.t<LocaleKey>('sheets-filter-ui.toolbar.smart-toggle-filter-tooltip');
+
+ async function closePanel() {
+ await commandService.executeCommand(CloseFilterPanelOperation.id);
+ }
+
+ async function openFilterBy(nextFilterBy: FilterBy) {
+ const changed = await commandService.executeCommand(ChangeFilterByOperation.id, { filterBy: nextFilterBy });
+ if (changed) {
+ setDetailOpen(true);
+ setDrawerSnap('expanded');
+ }
+ }
+
+ async function clearFilter() {
+ await filterByModel?.clear();
+ await closePanel();
+ }
+
+ async function applyFilter() {
+ await filterByModel?.apply();
+ await closePanel();
+ }
+
+ function goBack() {
+ if (detailOpen) {
+ setDetailOpen(false);
+ setDrawerSnap('compact');
+ return;
+ }
+
+ closePanel().catch(() => undefined);
+ }
+
+ function changeColumn(offset: number) {
+ const nextCol = col + offset;
+ if (!filterRange || nextCol < filterRange.startColumn || nextCol > filterRange.endColumn) {
+ return;
+ }
+
+ panelService.setupCol(panelService.filterModel!, nextCol);
+ }
+
+ return (
+ <div ref={layerRef} className="univer-pointer-events-none univer-fixed univer-inset-0 univer-z-[1100]">
+ <MobileDrawer
+ layerRef={layerRef}
+ componentName="mobile-sheets-filter-drawer"
+ snap={drawerSnap}
+ expandLabel={localeService.t<LocaleKey>('sheets-filter-ui.panel.mobile.resize')}
+ collapseLabel={localeService.t<LocaleKey>('sheets-filter-ui.panel.mobile.resize')}
+ onSnapChange={setDrawerSnap}
+ onClose={() => closePanel().catch(() => undefined)}
+ role="dialog"
+ ariaLabel={title}
+ panelClassName="univer-pointer-events-auto"
+ contentClassName="univer-min-h-0 univer-px-4 univer-pb-4"
+ header={(
+ <div
+ className="
+ univer-grid univer-h-12 univer-flex-1 univer-grid-cols-[56px_minmax(0,1fr)_56px]
+ univer-items-center univer-px-2
+ "
+ >
+ <button
+ type="button"
+ aria-label={localeService.t<LocaleKey>('sheets-filter-ui.panel.mobile.back')}
+ className={`
+ ${resetButtonClassName}
+ univer-flex univer-size-12 univer-items-center univer-justify-center
+ `}
+ onClick={goBack}
+ >
+ <MoreLeftIcon className="univer-size-6" />
+ </button>
+ <div className="univer-truncate univer-text-center univer-text-base univer-font-semibold">
+ {title}
+ </div>
+ </div>
+ )}
+ footer={detailOpen
+ ? (
+ <div
+ className="
+ univer-shrink-0 univer-border-0 univer-border-t univer-border-solid univer-border-gray-200
+ univer-p-4
+ dark:!univer-border-gray-700
+ "
+ >
+ <MobileActionRowGroup>
+ <Button onClick={() => closePanel().catch(() => undefined)}>
+ {localeService.t<LocaleKey>('sheets-filter-ui.panel.cancel')}
+ </Button>
+ <Button
+ variant="primary"
+ disabled={!canApply || !filterByModel}
+ onClick={() => applyFilter().catch(() => undefined)}
+ >
+ {localeService.t<LocaleKey>('sheets-filter-ui.panel.confirm')}
+ </Button>
+ </MobileActionRowGroup>
+ </div>
+ )
+ : undefined}
+ >
+ {detailOpen
+ ? (
+ <div className="univer-flex univer-min-h-full univer-flex-col">
+ <div
+ className="
+ univer-flex univer-min-h-14 univer-items-center univer-justify-between univer-px-2
+ "
+ >
+ <span className="univer-text-base univer-font-medium">
+ {localeService.t<LocaleKey>(
+ 'sheets-filter-ui.panel.mobile.column',
+ Tools.chatAtABC(col)
+ )}
+ </span>
+ <div className="univer-flex univer-gap-2">
+ <Button
+ disabled={!filterRange || col <= filterRange.startColumn}
+ onClick={() => changeColumn(-1)}
+ >
+ {localeService.t<LocaleKey>('sheets-filter-ui.panel.mobile.previous-column')}
+ </Button>
+ <Button
+ disabled={!filterRange || col >= filterRange.endColumn}
+ onClick={() => changeColumn(1)}
+ >
+ {localeService.t<LocaleKey>('sheets-filter-ui.panel.mobile.next-column')}
+ </Button>
+ </div>
+ </div>
+ <div className="univer-min-h-0 univer-flex-1">
+ {filterBy === FilterBy.VALUES && filterByModel
+ ? <MobileFilterByValue model={filterByModel as ByValuesModel} />
+ : null}
+ {filterBy === FilterBy.COLORS && filterByModel
+ ? <MobileFilterByColor model={filterByModel as ByColorsModel} />
+ : null}
+ {filterBy === FilterBy.CONDITIONS && filterByModel
+ ? <MobileFilterByCondition model={filterByModel as ByConditionsModel} />
+ : null}
+ </div>
+ </div>
+ )
+ : (
+ <div className="univer-grid univer-gap-4">
+ <div
+ className="
+ univer-overflow-hidden univer-rounded-xl univer-bg-gray-0
+ dark:!univer-bg-gray-800
+ "
+ >
+ {FILTER_BY_OPTIONS.map((option) => {
+ const label = localeService.t<LocaleKey>(option.label);
+ return (
+ <MobileActionRow
+ key={option.value}
+ title={label}
+ aria-label={label}
+ className="univer-rounded-none"
+ trailing={<MoreRightIcon className="univer-size-5 univer-text-gray-400" />}
+ onClick={() => openFilterBy(option.value).catch(() => undefined)}
+ />
+ );
+ })}
+ </div>
+ <MobileFilterSyncSwitch />
+ <Button
+ size="large"
+ disabled={!hasCriteria || !filterByModel}
+ onClick={() => clearFilter().catch(() => undefined)}
+ >
+ {localeService.t<LocaleKey>('sheets-filter-ui.panel.clear-filter')}
+ </Button>
+ </div>
+ )}
+ </MobileDrawer>
+ </div>
+ );
+}
diff --git a/packages/sheets-find-replace/src/controllers/__tests__/sheet-find-model.navigation.spec.ts b/packages/sheets-find-replace/src/controllers/__tests__/sheet-find-model.navigation.spec.ts
index ffb982e167..427d283c3d 100644
--- a/packages/sheets-find-replace/src/controllers/__tests__/sheet-find-model.navigation.spec.ts
+++ b/packages/sheets-find-replace/src/controllers/__tests__/sheet-find-model.navigation.spec.ts
@@ -15,7 +15,7 @@
*/
import type { IFindQuery } from '@univerjs/find-replace';
-import { FindBy, FindDirection, FindScope } from '@univerjs/find-replace';
+import { CloseFindDialogOperation, FindBy, FindDirection, FindScope } from '@univerjs/find-replace';
import { Subject } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
import { SheetFindModel, SheetsFindReplaceController } from '../sheet-find-replace.controller';
@@ -87,24 +87,28 @@ describe('SheetFindModel navigation', () => {
describe('SheetsFindReplaceController', () => {
it('should register provider and close on editor activated', () => {
const injector = { createInstance: vi.fn(() => ({ dispose: vi.fn() })) };
- const findReplaceController = { closePanel: vi.fn() };
const subscribeContextValue$ = vi.fn(() => ({ pipe: () => ({ subscribe: (fn: any) => {
fn(true);
return { unsubscribe: vi.fn() };
} }) }));
const contextService = { subscribeContextValue$ };
- const findReplaceService = { registerFindReplaceProvider: vi.fn(() => ({ dispose: vi.fn() })) };
- const commandService = { registerCommand: vi.fn(() => ({ dispose: vi.fn() })) };
+ const findReplaceService = {
+ registerFindReplaceProvider: vi.fn(() => ({ dispose: vi.fn() })),
+ terminate: vi.fn(),
+ };
+ const commandService = {
+ executeCommand: vi.fn(() => Promise.resolve(true)),
+ registerCommand: vi.fn(() => ({ dispose: vi.fn() })),
+ };
new SheetsFindReplaceController(
injector as any,
- findReplaceController as any,
contextService as any,
findReplaceService as any,
commandService as any
);
- expect(findReplaceController.closePanel).toHaveBeenCalledTimes(1);
+ expect(commandService.executeCommand).toHaveBeenCalledWith(CloseFindDialogOperation.id);
// Do not call `dispose` here: the controller stores rx subscriptions in a DisposableCollection,
// and our simplified stubs don't fully implement the IDisposable contract.
expect(findReplaceService.registerFindReplaceProvider).toHaveBeenCalled();
diff --git a/packages/sheets-find-replace/src/controllers/__tests__/sheet-find-replace.controller.spec.ts b/packages/sheets-find-replace/src/controllers/__tests__/sheet-find-replace.controller.spec.ts
index bec51b5132..ecffe2ad7c 100644
--- a/packages/sheets-find-replace/src/controllers/__tests__/sheet-find-replace.controller.spec.ts
+++ b/packages/sheets-find-replace/src/controllers/__tests__/sheet-find-replace.controller.spec.ts
@@ -18,7 +18,7 @@ import type { ICellData, IRange } from '@univerjs/core';
import type { IFindQuery } from '@univerjs/find-replace';
import { UniverInstanceType } from '@univerjs/core';
import { RENDER_RAW_FORMULA_KEY } from '@univerjs/engine-render';
-import { FindBy, FindDirection, FindScope } from '@univerjs/find-replace';
+import { CloseFindDialogOperation, FindBy, FindDirection, FindScope } from '@univerjs/find-replace';
import { SelectRangeCommand, SetRangeValuesCommand, SetWorksheetActivateCommand } from '@univerjs/sheets';
import { ScrollToCellCommand } from '@univerjs/sheets-ui';
import { Subject } from 'rxjs';
@@ -199,17 +199,17 @@ describe('SheetsFindReplaceController integration', () => {
}),
};
let provider: any;
+ const terminate = vi.fn();
const findReplaceService = {
registerFindReplaceProvider: vi.fn((registeredProvider) => {
provider = registeredProvider;
return { dispose: vi.fn() };
}),
+ terminate,
};
- const findReplaceController = { closePanel: vi.fn() };
const controller = new SheetsFindReplaceController(
injector as any,
- findReplaceController as any,
contextService as any,
findReplaceService as any,
commandService as any
@@ -219,14 +219,14 @@ describe('SheetsFindReplaceController integration', () => {
const [model] = await provider.find({ ...baseQuery, findString: ' ALPHA ' });
expect(commandService.registerCommand).toHaveBeenCalledWith(SheetReplaceCommand);
- expect(findReplaceController.closePanel).toHaveBeenCalledTimes(1);
+ expect(commandService.executeCommand).toHaveBeenCalledWith(CloseFindDialogOperation.id);
expect(model).toBeInstanceOf(SheetFindModel);
expect(model.matchesCount).toBe(2);
expect(model.getMatches().map((match: any) => match.range.range.startRow)).toEqual([0, 1]);
expect(model.getMatches().map((match: any) => match.replaceable)).toEqual([true, false]);
controller.dispose();
- expect(findReplaceController.closePanel).toHaveBeenCalledTimes(2);
+ expect(terminate).toHaveBeenCalledOnce();
});
it('returns no models when the provider has no active workbook', async () => {
@@ -240,13 +240,13 @@ describe('SheetsFindReplaceController integration', () => {
let provider: any;
const controller = new SheetsFindReplaceController(
injector as any,
- { closePanel: vi.fn() } as any,
{ subscribeContextValue$: vi.fn(() => new Subject<boolean>()) } as any,
{
registerFindReplaceProvider: vi.fn((registeredProvider) => {
provider = registeredProvider;
return { dispose: vi.fn() };
}),
+ terminate: vi.fn(),
} as any,
{ registerCommand: vi.fn(() => ({ dispose: vi.fn() })) } as any
);
diff --git a/packages/sheets-find-replace/src/controllers/mobile/sheet-find-replace-mobile.controller.ts b/packages/sheets-find-replace/src/controllers/mobile/sheet-find-replace-mobile.controller.ts
new file mode 100644
index 0000000000..3ec278d221
--- /dev/null
+++ b/packages/sheets-find-replace/src/controllers/mobile/sheet-find-replace-mobile.controller.ts
@@ -0,0 +1,128 @@
+/**
+ * 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 { Workbook } from '@univerjs/core';
+import type { IScrollToCellCommandParams } from '@univerjs/sheets-ui';
+import { Disposable, ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { convertTransformToOffsetY, IRenderManagerService } from '@univerjs/engine-render';
+import {
+ getCoordByCell,
+ getSheetObject,
+ getViewportByCell,
+ ScrollToCellCommand,
+ SetScrollRelativeCommand,
+ SheetSkeletonManagerService,
+} from '@univerjs/sheets-ui';
+
+const MOBILE_FIND_REPLACE_BAR_SELECTOR = '[data-u-comp="mobile-find-replace-bar"]';
+const MOBILE_FIND_MATCH_SAFE_PADDING = 8;
+
+export function getMobileFindMatchScrollOffset(cellBottom: number, barTop: number, safePadding: number): number {
+ return Math.max(0, cellBottom - barTop + safePadding);
+}
+
+export class SheetsFindReplaceMobileController extends Disposable {
+ private _pendingFrameId: number | null = null;
+
+ constructor(
+ @ICommandService private readonly _commandService: ICommandService,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService
+ ) {
+ super();
+
+ this.disposeWithMe(this._commandService.onCommandExecuted((command, options) => {
+ if (command.id !== ScrollToCellCommand.id || options?.fromFindReplace !== true) {
+ return;
+ }
+
+ const range = (command.params as IScrollToCellCommandParams | undefined)?.range;
+ if (!range) {
+ return;
+ }
+
+ const workbook = this._univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);
+ const worksheet = workbook?.getActiveSheet();
+ if (!workbook || !worksheet) {
+ return;
+ }
+
+ this._scheduleReveal(workbook.getUnitId(), worksheet.getSheetId(), range.endRow, range.endColumn);
+ }));
+ }
+
+ override dispose(): void {
+ if (this._pendingFrameId !== null) {
+ cancelAnimationFrame(this._pendingFrameId);
+ this._pendingFrameId = null;
+ }
+
+ super.dispose();
+ }
+
+ private _scheduleReveal(unitId: string, subUnitId: string, row: number, column: number): void {
+ if (this._pendingFrameId !== null) {
+ cancelAnimationFrame(this._pendingFrameId);
+ }
+
+ this._pendingFrameId = requestAnimationFrame(() => {
+ this._pendingFrameId = null;
+ this._revealMatch(unitId, subUnitId, row, column);
+ });
+ }
+
+ private _revealMatch(unitId: string, subUnitId: string, row: number, column: number): void {
+ const bar = document.querySelector<HTMLElement>(MOBILE_FIND_REPLACE_BAR_SELECTOR);
+ if (!bar) {
+ return;
+ }
+
+ const workbook = this._univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);
+ const worksheet = workbook?.getActiveSheet();
+ if (!workbook || !worksheet || workbook.getUnitId() !== unitId || worksheet.getSheetId() !== subUnitId) {
+ return;
+ }
+
+ const render = this._renderManagerService.getRenderUnitById(workbook.getUnitId());
+ const sheetObject = getSheetObject(workbook, this._renderManagerService);
+ const skeleton = render?.with(SheetSkeletonManagerService).getSkeleton(worksheet.getSheetId());
+ if (!sheetObject || !skeleton) {
+ return;
+ }
+
+ const { scene, engine } = sheetObject;
+ const viewport = getViewportByCell(row, column, scene, worksheet);
+ if (!viewport) {
+ return;
+ }
+
+ const { endY } = getCoordByCell(row, column, scene, skeleton);
+ const { scaleY } = scene.getAncestorScale();
+ const scrollXY = scene.getViewportScrollXY(viewport);
+ const canvasTop = engine.getCanvasElement().getBoundingClientRect().top;
+ const cellBottom = canvasTop + convertTransformToOffsetY(endY, scaleY, scrollXY);
+ const offsetY = getMobileFindMatchScrollOffset(
+ cellBottom,
+ bar.getBoundingClientRect().top,
+ MOBILE_FIND_MATCH_SAFE_PADDING
+ );
+ if (offsetY === 0) {
+ return;
+ }
+
+ this._commandService.executeCommand(SetScrollRelativeCommand.id, { offsetY }).catch(() => undefined);
+ }
+}
diff --git a/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts b/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts
index 2b7b52bac9..ec56656933 100644
--- a/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts
+++ b/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts
@@ -65,7 +65,14 @@ import {
UniverInstanceType,
} from '@univerjs/core';
import { IRenderManagerService, RENDER_RAW_FORMULA_KEY } from '@univerjs/engine-render';
-import { FindBy, FindDirection, FindModel, FindReplaceController, FindScope, IFindReplaceService } from '@univerjs/find-replace';
+import {
+ CloseFindDialogOperation,
+ FindBy,
+ FindDirection,
+ FindModel,
+ FindScope,
+ IFindReplaceService,
+} from '@univerjs/find-replace';
import {
SelectRangeCommand,
SetRangeValuesCommand,
@@ -92,7 +99,6 @@ export class SheetsFindReplaceController extends Disposable implements IDisposab
constructor(
@Inject(Injector) private readonly _injector: Injector,
- @Inject(FindReplaceController) private readonly _findReplaceController: FindReplaceController,
@IContextService private readonly _contextService: IContextService,
@IFindReplaceService private readonly _findReplaceService: IFindReplaceService,
@ICommandService private readonly _commandService: ICommandService
@@ -106,7 +112,7 @@ export class SheetsFindReplaceController extends Disposable implements IDisposab
override dispose(): void {
super.dispose();
- this._findReplaceController.closePanel();
+ this._findReplaceService.terminate();
this._provider.dispose();
}
@@ -119,7 +125,9 @@ export class SheetsFindReplaceController extends Disposable implements IDisposab
// The find replace panel should be closed when sheet cell editor is activated, or the formula editor is focused.
this.disposeWithMe(this._contextService.subscribeContextValue$(EDITOR_ACTIVATED)
.pipe(filter((v) => !!v))
- .subscribe(() => this._findReplaceController.closePanel()));
+ .subscribe(() => {
+ this._commandService.executeCommand(CloseFindDialogOperation.id).catch(() => undefined);
+ }));
}
private _initCommands(): void {
diff --git a/packages/sheets-find-replace/src/index.ts b/packages/sheets-find-replace/src/index.ts
index 678b6a5a45..def0f61e81 100644
--- a/packages/sheets-find-replace/src/index.ts
+++ b/packages/sheets-find-replace/src/index.ts
@@ -17,4 +17,5 @@
export { SheetReplaceCommand } from './commands/commands/sheet-replace.command';
export type { IUniverSheetsFindReplaceConfig } from './config/config';
export { SheetsFindReplaceController } from './controllers/sheet-find-replace.controller';
+export { UniverSheetsFindReplaceMobileUIPlugin } from './mobile-plugin';
export { UniverSheetsFindReplacePlugin } from './plugin';
diff --git a/packages/sheets-find-replace/src/mobile-plugin.ts b/packages/sheets-find-replace/src/mobile-plugin.ts
new file mode 100644
index 0000000000..a11784147a
--- /dev/null
+++ b/packages/sheets-find-replace/src/mobile-plugin.ts
@@ -0,0 +1,66 @@
+/**
+ * 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 { Dependency } from '@univerjs/core';
+import type { IUniverSheetsFindReplaceConfig } from './config/config';
+import { DependentOn, IConfigService, Inject, Injector, merge, Plugin, UniverInstanceType } from '@univerjs/core';
+import { UniverRenderEnginePlugin } from '@univerjs/engine-render';
+import { UniverFindReplaceMobileUIPlugin } from '@univerjs/find-replace';
+import { UniverSheetsPlugin } from '@univerjs/sheets';
+import { UniverSheetsMobileUIPlugin } from '@univerjs/sheets-ui';
+import pkg from '../package.json';
+import { defaultPluginConfig, SHEETS_FIND_REPLACE_PLUGIN_CONFIG_KEY } from './config/config';
+import { SheetsFindReplaceMobileController } from './controllers/mobile/sheet-find-replace-mobile.controller';
+import { SheetsFindReplaceController } from './controllers/sheet-find-replace.controller';
+
+@DependentOn(
+ UniverRenderEnginePlugin,
+ UniverSheetsPlugin,
+ UniverFindReplaceMobileUIPlugin,
+ UniverSheetsMobileUIPlugin
+)
+export class UniverSheetsFindReplaceMobileUIPlugin extends Plugin {
+ static override pluginName = 'SHEET_FIND_REPLACE_PLUGIN';
+ static override packageName = pkg.name;
+ static override version = pkg.version;
+ static override type = UniverInstanceType.UNIVER_SHEET;
+
+ constructor(
+ private readonly _config: Partial<IUniverSheetsFindReplaceConfig> = defaultPluginConfig,
+ @Inject(Injector) protected readonly _injector: Injector,
+ @IConfigService private readonly _configService: IConfigService
+ ) {
+ super();
+
+ const { ...rest } = merge({}, defaultPluginConfig, this._config);
+ this._configService.setConfig(SHEETS_FIND_REPLACE_PLUGIN_CONFIG_KEY, rest);
+ }
+
+ override onStarting(): void {
+ ([
+ [SheetsFindReplaceController],
+ [SheetsFindReplaceMobileController],
+ ] as Dependency[]).forEach((dependency) => this._injector.add(dependency));
+ }
+
+ override onRendered(): void {
+ this._injector.get(SheetsFindReplaceMobileController);
+ }
+
+ override onSteady(): void {
+ this._injector.get(SheetsFindReplaceController);
+ }
+}
diff --git a/packages/sheets-formula-ui/package.json b/packages/sheets-formula-ui/package.json
index d1993feb7d..fd52deefbb 100644
--- a/packages/sheets-formula-ui/package.json
+++ b/packages/sheets-formula-ui/package.json
@@ -82,6 +82,7 @@
},
"peerDependencies": {
"react": "^16.9.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc",
+ "react-dom": "^16.9.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc",
"rxjs": ">=7.0.0"
},
"dependencies": {
diff --git a/packages/sheets-formula-ui/src/controllers/mobile/components.controller.ts b/packages/sheets-formula-ui/src/controllers/mobile/components.controller.ts
new file mode 100644
index 0000000000..9abcfbe018
--- /dev/null
+++ b/packages/sheets-formula-ui/src/controllers/mobile/components.controller.ts
@@ -0,0 +1,73 @@
+/**
+ * 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 { Disposable, Inject } from '@univerjs/core';
+import {
+ DatabaseFunctionIcon,
+ DateFunctionIcon,
+ EngineeringFunctionIcon,
+ FinancialFunctionIcon,
+ FunctionIcon,
+ InformationFunctionIcon,
+ LogicalFunctionIcon,
+ LookupFunctionIcon,
+ MathFunctionIcon,
+ StatisticalFunctionIcon,
+ TextFunctionIcon,
+} from '@univerjs/icons';
+import { EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY, RANGE_SELECTOR_COMPONENT_KEY } from '@univerjs/sheets-ui';
+import { ComponentManager, IconManager } from '@univerjs/ui';
+import { MobileFormulaEditor } from '../../views/mobile/formula-editor/MobileFormulaEditor';
+import { MobileMoreFunctions } from '../../views/mobile/more-functions/MobileMoreFunctions';
+import { MORE_FUNCTIONS_COMPONENT } from '../../views/more-functions/interface';
+import { MobileRangeSelector } from '../../views/range-selector/MobileRangeSelector';
+
+export class MobileComponentsController extends Disposable {
+ constructor(
+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,
+ @Inject(IconManager) private readonly _iconManager: IconManager
+ ) {
+ super();
+
+ this._registerIcons();
+ this._registerComponents();
+ }
+
+ private _registerIcons(): void {
+ this.disposeWithMe(this._iconManager.register({
+ DatabaseFunctionIcon,
+ DateFunctionIcon,
+ EngineeringFunctionIcon,
+ FinancialFunctionIcon,
+ FunctionIcon,
+ InformationFunctionIcon,
+ LogicalFunctionIcon,
+ LookupFunctionIcon,
+ MathFunctionIcon,
+ StatisticalFunctionIcon,
+ TextFunctionIcon,
+ }));
+ }
+
+ private _registerComponents(): void {
+ this.disposeWithMe(this._componentManager.register(MORE_FUNCTIONS_COMPONENT, MobileMoreFunctions));
+ this.disposeWithMe(this._componentManager.register(RANGE_SELECTOR_COMPONENT_KEY, MobileRangeSelector));
+ this.disposeWithMe(this._componentManager.register(
+ EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY,
+ MobileFormulaEditor
+ ));
+ }
+}
diff --git a/packages/sheets-formula-ui/src/index.ts b/packages/sheets-formula-ui/src/index.ts
index 41bf2c0780..c971fdb158 100644
--- a/packages/sheets-formula-ui/src/index.ts
+++ b/packages/sheets-formula-ui/src/index.ts
@@ -29,6 +29,7 @@ export { genFormulaRefSelectionStyle } from './common/selection';
export type { IUniverSheetsFormulaUIConfig } from './config/config';
export { FormulaReorderController } from './controllers/formula-reorder.controller';
export { menuSchema as SheetsFormulaUIMenuSchema } from './menu/schema';
+export { UniverSheetsFormulaMobileUIPlugin } from './mobile-plugin';
export { UniverSheetsFormulaUIPlugin } from './plugin';
export { FORMULA_PROMPT_ACTIVATED } from './services/prompt.service';
export { GlobalRangeSelectorService } from './services/range-selector.service';
@@ -38,3 +39,4 @@ export { FormulaEditor } from './views/formula-editor/index';
export type { IFormulaEditorRef } from './views/formula-editor/index';
export { RangeSelector } from './views/range-selector/index';
export type { IRangeSelectorInstance, IRangeSelectorProps } from './views/range-selector/index';
+export { MobileRangeSelector } from './views/range-selector/MobileRangeSelector';
diff --git a/packages/sheets-formula-ui/src/mobile-plugin.ts b/packages/sheets-formula-ui/src/mobile-plugin.ts
new file mode 100644
index 0000000000..79e0939a3e
--- /dev/null
+++ b/packages/sheets-formula-ui/src/mobile-plugin.ts
@@ -0,0 +1,144 @@
+/**
+ * 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 { Dependency } from '@univerjs/core';
+import type { IUniverSheetsFormulaUIConfig } from './config/config';
+import {
+ DependentOn,
+ IConfigService,
+ Inject,
+ Injector,
+ merge,
+ Plugin,
+ registerDependencies,
+ touchDependencies,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';
+import { IRenderManagerService, UniverRenderEnginePlugin } from '@univerjs/engine-render';
+import { UniverSheetsPlugin } from '@univerjs/sheets';
+import { UniverSheetsFormulaPlugin } from '@univerjs/sheets-formula';
+import { UniverSheetsMobileUIPlugin } from '@univerjs/sheets-ui';
+import { BuiltInUIPart, connectInjector, IUIPartsService, UniverMobileUIPlugin } from '@univerjs/ui';
+import pkg from '../package.json';
+import { FORMULA_UI_PLUGIN_NAME } from './common/plugin-name';
+import {
+ defaultPluginConfig,
+ PLUGIN_CONFIG_KEY_BASE,
+} from './config/config';
+import { FormulaAlertRenderController } from './controllers/formula-alert-render.controller';
+import { FormulaClipboardController } from './controllers/formula-clipboard.controller';
+import { FormulaEditorShowController } from './controllers/formula-editor-show.controller';
+import { FormulaRenderManagerController } from './controllers/formula-render.controller';
+import { FormulaReorderController } from './controllers/formula-reorder.controller';
+import { ImageFormulaRenderController } from './controllers/image-formula-render.controller';
+import { MobileComponentsController } from './controllers/mobile/components.controller';
+import { FormulaUIController } from './controllers/ui.controller';
+import { FormulaPromptService, IFormulaPromptService } from './services/prompt.service';
+import { GlobalRangeSelectorService } from './services/range-selector.service';
+import { MobileRefSelectionsRenderService } from './services/render-services/mobile-ref-selections.render.service';
+import { RefSelectionsRenderService } from './services/render-services/ref-selections.render.service';
+import { MobileGlobalRangeSelector } from './views/range-selector/MobileGlobal';
+
+/**
+ * The configuration of the formula UI plugin.
+ */
+@DependentOn(
+ UniverFormulaEnginePlugin,
+ UniverRenderEnginePlugin,
+ UniverSheetsPlugin,
+ UniverSheetsFormulaPlugin,
+ UniverSheetsMobileUIPlugin,
+ UniverMobileUIPlugin
+)
+export class UniverSheetsFormulaMobileUIPlugin extends Plugin {
+ static override pluginName = FORMULA_UI_PLUGIN_NAME;
+ static override packageName = pkg.name;
+ static override version = pkg.version;
+ static override type = UniverInstanceType.UNIVER_SHEET;
+
+ constructor(
+ private readonly _config: Partial<IUniverSheetsFormulaUIConfig> = defaultPluginConfig,
+ @Inject(Injector) override readonly _injector: Injector,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @IConfigService private readonly _configService: IConfigService,
+ @IUIPartsService private readonly _uiPartsService: IUIPartsService
+ ) {
+ super();
+
+ // Manage the plugin configuration.
+ const { menu, ...rest } = merge(
+ defaultPluginConfig,
+ this._config
+ );
+ if (menu) {
+ this._configService.setConfig('menu', menu, { merge: true });
+ }
+ this._configService.setConfig(PLUGIN_CONFIG_KEY_BASE, rest, { merge: true });
+ }
+
+ override onStarting(): void {
+ this._injector.add([MobileComponentsController]);
+ this._injector.get(MobileComponentsController);
+ registerDependencies(this._injector, [
+ [IFormulaPromptService, { useClass: FormulaPromptService }],
+ [GlobalRangeSelectorService],
+ [FormulaUIController],
+ [FormulaClipboardController],
+ [FormulaEditorShowController],
+ [FormulaRenderManagerController],
+ [FormulaReorderController],
+ [ImageFormulaRenderController],
+ ]);
+
+ this._initUIPart();
+ }
+
+ override onReady(): void {
+ // render basics
+ ([
+ [RefSelectionsRenderService, { useClass: MobileRefSelectionsRenderService }],
+ ] as Dependency[]).forEach((dep) => {
+ this.disposeWithMe(this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, dep));
+ });
+ }
+
+ override onRendered(): void {
+ ([
+ [FormulaAlertRenderController],
+ ] as Dependency[]).forEach((dep) => {
+ this.disposeWithMe(this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, dep));
+ });
+
+ touchDependencies(this._injector, [
+ [FormulaUIController], // FormulaProgressBar relies on TriggerCalculationController, but it is necessary to ensure that the formula calculation is done after rendered.
+ [FormulaClipboardController],
+ [FormulaRenderManagerController],
+ [ImageFormulaRenderController],
+ ]);
+ }
+
+ override onSteady(): void {
+ this._injector.get(FormulaReorderController);
+ }
+
+ private _initUIPart(): void {
+ this.disposeWithMe(this._uiPartsService.registerComponent(
+ BuiltInUIPart.GLOBAL,
+ () => connectInjector(MobileGlobalRangeSelector, this._injector)
+ ));
+ }
+}
diff --git a/packages/sheets-formula-ui/src/services/render-services/__tests__/ref-selections.render.service.spec.ts b/packages/sheets-formula-ui/src/services/render-services/__tests__/ref-selections.render.service.spec.ts
index 6fd32cd036..958072103a 100644
--- a/packages/sheets-formula-ui/src/services/render-services/__tests__/ref-selections.render.service.spec.ts
+++ b/packages/sheets-formula-ui/src/services/render-services/__tests__/ref-selections.render.service.spec.ts
@@ -42,10 +42,16 @@ import {
SELECTIONS_ENABLED,
SheetsSelectionsService,
} from '@univerjs/sheets';
-import { SHEET_VIEW_KEY, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import {
+ MOBILE_EXPANDING_SELECTION,
+ MobileSelectionControl,
+ SHEET_VIEW_KEY,
+ SheetSkeletonManagerService,
+} from '@univerjs/sheets-ui';
import { IShortcutService } from '@univerjs/ui';
import { BehaviorSubject, Subject } from 'rxjs';
import { afterEach, describe, expect, it } from 'vitest';
+import { MobileRefSelectionsRenderService } from '../mobile-ref-selections.render.service';
import { RefSelectionsRenderService } from '../ref-selections.render.service';
function createTestEvent<TEvent, TState = { stopPropagation: () => void }>() {
@@ -194,10 +200,28 @@ function createFakeSkeleton(options?: {
rowHeaderWidthAndMarginLeft: 46,
columnHeaderHeightAndMarginTop: 20,
getCellWithCoordByIndex: (row: number, col: number) => ({
+ startRow: row,
+ endRow: row,
+ startColumn: col,
+ endColumn: col,
+ actualRow: row,
+ actualColumn: col,
+ isMerged: false,
+ isMergedMainCell: false,
startX: col * colWidth,
startY: row * rowHeight,
endX: (col + 1) * colWidth,
endY: (row + 1) * rowHeight,
+ mergeInfo: {
+ startRow: row,
+ endRow: row,
+ startColumn: col,
+ endColumn: col,
+ startX: col * colWidth,
+ startY: row * rowHeight,
+ endX: (col + 1) * colWidth,
+ endY: (row + 1) * rowHeight,
+ },
}),
getNoMergeCellWithCoordByIndex: (row: number, col: number) => ({
startX: col * colWidth,
@@ -225,6 +249,7 @@ function createFakeSkeleton(options?: {
},
getColumnCount: () => 20,
getRowCount: () => 20,
+ expandRangeByMerge: <TRange>(range: TRange) => range,
getLocation: options?.getLocation ?? (() => ['test', 'sheet1'] as [string, string]),
worksheet: options?.worksheet ?? {
getFreeze: () => ({ startRow: 0, startColumn: 0, xSplit: 0, ySplit: 0 }),
@@ -320,7 +345,7 @@ function createSelection(startRow: number, startColumn: number): ISelectionWithS
};
}
-function createRefSelectionTestBed() {
+function createRefSelectionTestBed(mobile = false) {
const univer = new Univer();
const injector = univer.__getInjector();
@@ -377,6 +402,7 @@ function createRefSelectionTestBed() {
const mainComponent = {
zIndex: 1,
onPointerDown$: createTestEvent<unknown>(),
+ onPointerUp$: createTestEvent<unknown>(),
makeForceDirty: () => undefined,
};
const context = {
@@ -394,7 +420,9 @@ function createRefSelectionTestBed() {
} as unknown as IRenderContext<Workbook>;
const skeleton = createFakeSkeleton();
const skeletonManager = injector.get(SheetSkeletonManagerService) as unknown as TestSheetSkeletonManagerService;
- const service = injector.createInstance(RefSelectionsRenderService, context);
+ const service = mobile
+ ? injector.createInstance(MobileRefSelectionsRenderService, context)
+ : injector.createInstance(RefSelectionsRenderService, context);
skeletonManager.emitCurrentSkeleton({
unitId: workbook.getUnitId(),
@@ -414,6 +442,7 @@ function createRefSelectionTestBed() {
leftTop: components.get(SHEET_VIEW_KEY.LEFT_TOP) as { onPointerDown$: ReturnType<typeof createTestEvent<unknown>> },
skeleton,
skeletonManager,
+ contextService,
refSelectionsService: injector.get(IRefSelectionsService),
};
}
@@ -638,3 +667,186 @@ describe('RefSelectionsRenderService', () => {
selectionChanging.dispose();
});
});
+
+describe('MobileRefSelectionsRenderService', () => {
+ const disposables: Array<ReturnType<typeof createRefSelectionTestBed>> = [];
+
+ afterEach(() => {
+ while (disposables.length > 0) {
+ disposables.pop()!.univer.dispose();
+ }
+ });
+
+ it('renders only the two mobile corner handles and disables dragging the selection border', () => {
+ const testBed = createRefSelectionTestBed(true);
+ disposables.push(testBed);
+ const { service } = testBed;
+ const selection = createSelection(1, 1);
+ selection.style = {
+ stroke: '#00aa00',
+ fill: 'rgba(0, 170, 0, 0.05)',
+ widgets: { tl: true, tc: true, tr: true, ml: true, mr: true, bl: true, bc: true, br: true },
+ widgetSize: 6,
+ };
+
+ service.resetSelectionsByModelData([selection]);
+ const control = service.getActiveSelectionControl<MobileSelectionControl>()!;
+
+ expect(control).toBeInstanceOf(MobileSelectionControl);
+ expect(control.currentStyle.stroke).toBe(selection.style.stroke);
+ expect(control.currentStyle.fill).toBe(selection.style.fill);
+ expect(control.currentStyle.widgets).toEqual({});
+ expect(control.currentStyle.expandCornerSize).toBe(48);
+ expect(control.fillControl.visible).toBe(false);
+ expect(control.expandControlTopLeft?.visible).toBe(true);
+ expect(control.expandControlBottomRight?.visible).toBe(true);
+ expect(control.expandControlTopLeft?.width).toBe(48);
+ expect(control.expandControlTopLeft?.visualWidth).toBe(12);
+ expect(control.expandControlTopLeft?.fill).toBe(selection.style.stroke);
+ expect(control.expandControlBottomRight?.width).toBe(48);
+ expect(control.expandControlBottomRight?.visualWidth).toBe(12);
+ expect(control.expandControlBottomRight?.fill).toBe(selection.style.stroke);
+ expect(control.topLeftWidget.visible).toBe(false);
+ expect(control.bottomRightWidget.visible).toBe(false);
+ expect(control.topCenterWidget.visible).toBe(false);
+ expect(control.topRightWidget.visible).toBe(false);
+ expect(control.middleLeftWidget.visible).toBe(false);
+ expect(control.middleRightWidget.visible).toBe(false);
+ expect(control.bottomLeftWidget.visible).toBe(false);
+ expect(control.bottomCenterWidget.visible).toBe(false);
+ expect(control.leftControl.evented).toBe(false);
+ expect(control.rightControl.evented).toBe(false);
+ expect(control.topControl.evented).toBe(false);
+ expect(control.bottomControl.evented).toBe(false);
+ });
+
+ it('expands a formula reference selection only from a mobile corner handle', () => {
+ const testBed = createRefSelectionTestBed(true);
+ disposables.push(testBed);
+ const { service, scene, contextService } = testBed;
+
+ service.resetSelectionsByModelData([createSelection(1, 1)]);
+ const control = service.getActiveSelectionControl<MobileSelectionControl>()!;
+
+ control.expandControlBottomRight!.onPointerDown$.emitEvent({ offsetX: 150, offsetY: 30 } as never);
+ expect(contextService.getContextValue(MOBILE_EXPANDING_SELECTION)).toBe(true);
+
+ scene.onPointerMove$.emit({ offsetX: 350, offsetY: 90 }, { stopPropagation: () => undefined });
+ expect(service.getActiveRange()).toEqual({
+ startRow: 1,
+ endRow: 4,
+ startColumn: 1,
+ endColumn: 3,
+ });
+
+ scene.onPointerUp$.emit({ offsetX: 350, offsetY: 90 }, { stopPropagation: () => undefined });
+ expect(contextService.getContextValue(MOBILE_EXPANDING_SELECTION)).toBe(false);
+ });
+
+ it('expands a formula reference selection from the top-left mobile corner handle', () => {
+ const testBed = createRefSelectionTestBed(true);
+ disposables.push(testBed);
+ const { service, scene } = testBed;
+ const selection = createSelection(2, 1);
+ selection.range.endRow = 4;
+ selection.range.endColumn = 3;
+
+ service.resetSelectionsByModelData([selection]);
+ const control = service.getActiveSelectionControl<MobileSelectionControl>()!;
+
+ control.expandControlTopLeft!.onPointerDown$.emitEvent({ offsetX: 150, offsetY: 50 } as never);
+ scene.onPointerMove$.emit({ offsetX: 50, offsetY: 10 }, { stopPropagation: () => undefined });
+
+ expect(service.getActiveRange()).toEqual({
+ startRow: 0,
+ endRow: 4,
+ startColumn: 0,
+ endColumn: 3,
+ });
+
+ scene.onPointerUp$.emit({ offsetX: 50, offsetY: 10 }, { stopPropagation: () => undefined });
+ });
+
+ it('expands the formula reference whose mobile corner handle is dragged', () => {
+ const testBed = createRefSelectionTestBed(true);
+ disposables.push(testBed);
+ const { service, scene } = testBed;
+
+ service.resetSelectionsByModelData([createSelection(1, 1), createSelection(5, 5)]);
+ const [firstControl] = service.getSelectionControls() as MobileSelectionControl[];
+
+ firstControl.expandControlBottomRight!.onPointerDown$.emitEvent({ offsetX: 150, offsetY: 30 } as never);
+ scene.onPointerMove$.emit({ offsetX: 350, offsetY: 90 }, { stopPropagation: () => undefined });
+
+ expect(service.getSelectionDataWithStyle().map(({ rangeWithCoord }) => ({
+ startRow: rangeWithCoord.startRow,
+ endRow: rangeWithCoord.endRow,
+ startColumn: rangeWithCoord.startColumn,
+ endColumn: rangeWithCoord.endColumn,
+ }))).toEqual([
+ { startRow: 1, endRow: 4, startColumn: 1, endColumn: 3 },
+ { startRow: 5, endRow: 5, startColumn: 5, endColumn: 5 },
+ ]);
+
+ scene.onPointerUp$.emit({ offsetX: 350, offsetY: 90 }, { stopPropagation: () => undefined });
+ });
+
+ it('keeps the formula reference selection unchanged when dragging the spreadsheet', () => {
+ const testBed = createRefSelectionTestBed(true);
+ disposables.push(testBed);
+ const { service, mainComponent, scene } = testBed;
+ const state = { stopPropagation: () => undefined };
+
+ service.resetSelectionsByModelData([createSelection(1, 1)]);
+ const selectionChanging = service.enableSelectionChanging();
+ mainComponent.onPointerDown$.emit({
+ offsetX: 150,
+ offsetY: 30,
+ button: 0,
+ }, state);
+ scene.onPointerMove$.emit({ offsetX: 350, offsetY: 90 }, state);
+ mainComponent.onPointerUp$.emit({
+ offsetX: 350,
+ offsetY: 90,
+ button: 0,
+ }, state);
+
+ expect(service.getActiveRange()).toEqual({
+ startRow: 1,
+ endRow: 1,
+ startColumn: 1,
+ endColumn: 1,
+ });
+
+ selectionChanging.dispose();
+ });
+
+ it('updates the formula reference selection when tapping the spreadsheet', () => {
+ const testBed = createRefSelectionTestBed(true);
+ disposables.push(testBed);
+ const { service, mainComponent } = testBed;
+ const state = { stopPropagation: () => undefined };
+
+ service.resetSelectionsByModelData([createSelection(1, 1)]);
+ const selectionChanging = service.enableSelectionChanging();
+ mainComponent.onPointerDown$.emit({
+ offsetX: 350,
+ offsetY: 90,
+ button: 0,
+ }, state);
+ mainComponent.onPointerUp$.emit({
+ offsetX: 350,
+ offsetY: 90,
+ button: 0,
+ }, state);
+
+ expect(service.getActiveRange()).toEqual({
+ startRow: 4,
+ endRow: 4,
+ startColumn: 3,
+ endColumn: 3,
+ });
+
+ selectionChanging.dispose();
+ });
+});
diff --git a/packages/sheets-formula-ui/src/services/render-services/mobile-ref-selections.render.service.ts b/packages/sheets-formula-ui/src/services/render-services/mobile-ref-selections.render.service.ts
new file mode 100644
index 0000000000..c31b9ebd42
--- /dev/null
+++ b/packages/sheets-formula-ui/src/services/render-services/mobile-ref-selections.render.service.ts
@@ -0,0 +1,387 @@
+/**
+ * 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 { ICellWithCoord, IDisposable, Nullable, Workbook } from '@univerjs/core';
+import type {
+ IMouseEvent,
+ IPointerEvent,
+ IRenderContext,
+ Scene,
+ Spreadsheet,
+ SpreadsheetColumnHeader,
+ SpreadsheetHeader,
+ SpreadsheetSkeleton,
+ Viewport,
+} from '@univerjs/engine-render';
+import type { ISelectionStyle, ISelectionWithStyle, SheetsSelectionsService } from '@univerjs/sheets';
+import { DisposableCollection, IContextService, Inject, Injector, RANGE_TYPE, ThemeService } from '@univerjs/core';
+import { ScrollTimer, ScrollTimerType, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
+import { attachSelectionWithCoord, IRefSelectionsService } from '@univerjs/sheets';
+import {
+ checkInHeaderRanges,
+ getAllSelection,
+ getCoordByOffset,
+ MOBILE_EXPANDING_SELECTION,
+ MOBILE_PINCH_ZOOMING,
+ MobileSelectionControl,
+ SheetSkeletonManagerService,
+} from '@univerjs/sheets-ui';
+import { IShortcutService } from '@univerjs/ui';
+import { RefSelectionsRenderService } from './ref-selections.render.service';
+
+enum ExpandingControl {
+ BOTTOM_RIGHT = 'bottom-right',
+ TOP_LEFT = 'top-left',
+ LEFT = 'left',
+ RIGHT = 'right',
+ TOP = 'top',
+ BOTTOM = 'bottom',
+}
+
+class MobileRefSelectionControl extends MobileSelectionControl {
+ protected override _updateLayoutOfSelectionControl(style: ISelectionStyle): void {
+ super._updateLayoutOfSelectionControl(style);
+
+ const expandCornerSize = this.currentStyle.expandCornerSize ?? 0;
+ const visibleSize = expandCornerSize / 4;
+ const props = {
+ radius: expandCornerSize / 2,
+ visualWidth: visibleSize,
+ visualHeight: visibleSize,
+ fill: this.currentStyle.stroke,
+ stroke: this.currentStyle.widgetStroke ?? this.currentStyle.autofillStroke,
+ strokeWidth: this.currentStyle.widgetStrokeWidth ?? this.currentStyle.autofillStrokeWidth,
+ };
+
+ this.expandControlTopLeft?.resize(expandCornerSize, expandCornerSize);
+ this.expandControlTopLeft?.setProps(props);
+ this.expandControlBottomRight?.resize(expandCornerSize, expandCornerSize);
+ this.expandControlBottomRight?.setProps(props);
+ this.fillControl.evented = false;
+ this.fillControl.hide();
+ }
+}
+
+export class MobileRefSelectionsRenderService extends RefSelectionsRenderService {
+ private _expandingControlMode = ExpandingControl.BOTTOM_RIGHT;
+
+ constructor(
+ context: IRenderContext<Workbook>,
+ @Inject(Injector) injector: Injector,
+ @Inject(ThemeService) themeService: ThemeService,
+ @IShortcutService shortcutService: IShortcutService,
+ @Inject(SheetSkeletonManagerService) sheetSkeletonManagerService: SheetSkeletonManagerService,
+ @IContextService contextService: IContextService,
+ @IRefSelectionsService refSelectionsService: SheetsSelectionsService
+ ) {
+ super(
+ context,
+ injector,
+ themeService,
+ shortcutService,
+ sheetSkeletonManagerService,
+ contextService,
+ refSelectionsService
+ );
+ }
+
+ override dispose(): void {
+ this._contextService.setContextValue(MOBILE_EXPANDING_SELECTION, false);
+ super.dispose();
+ }
+
+ protected override _initCanvasEventListeners(): IDisposable {
+ const sheetObject = this._getSheetObject();
+ const { spreadsheetRowHeader, spreadsheetColumnHeader, spreadsheet, spreadsheetLeftTopPlaceholder } = sheetObject;
+ const { scene } = sheetObject;
+ const listenerDisposables = new DisposableCollection();
+
+ this._initSpreadsheetEvents(listenerDisposables, spreadsheet);
+ this._initHeaderEvent(listenerDisposables, spreadsheetRowHeader, spreadsheet, scene, RANGE_TYPE.ROW);
+ this._initHeaderEvent(listenerDisposables, spreadsheetColumnHeader, spreadsheet, scene, RANGE_TYPE.COLUMN);
+
+ listenerDisposables.add(spreadsheetLeftTopPlaceholder.onPointerDown$.subscribeEvent((_evt, state) => {
+ if (!this.inRefSelectionMode()) {
+ return;
+ }
+
+ const skeleton = this._sheetSkeletonManagerService.getCurrentSkeleton();
+ if (!skeleton) {
+ return;
+ }
+
+ this._reset();
+ this._addSelectionControlByModelData(getAllSelection(skeleton));
+ this._selectionMoveStart$.next(this.getSelectionDataWithStyle());
+ this._selectionMoveEnd$.next(this.getSelectionDataWithStyle());
+ state.stopPropagation();
+ }));
+
+ return listenerDisposables;
+ }
+
+ private _initSpreadsheetEvents(listenerDisposables: DisposableCollection, spreadsheet: Spreadsheet): void {
+ const pointerDownPosition = { x: 0, y: 0 };
+
+ listenerDisposables.add(spreadsheet.onPointerDown$.subscribeEvent((evt, state) => {
+ if (!this.inRefSelectionMode() || this._contextService.getContextValue(MOBILE_PINCH_ZOOMING)) {
+ return;
+ }
+
+ pointerDownPosition.x = evt.offsetX;
+ pointerDownPosition.y = evt.offsetY;
+ state.stopPropagation();
+ }));
+
+ listenerDisposables.add(spreadsheet.onPointerUp$.subscribeEvent((evt, state) => {
+ if (!this.inRefSelectionMode() || this._contextService.getContextValue(MOBILE_PINCH_ZOOMING)) {
+ return;
+ }
+
+ const tapMovementThreshold = 10;
+ if (
+ Math.abs(evt.offsetX - pointerDownPosition.x) > tapMovementThreshold ||
+ Math.abs(evt.offsetY - pointerDownPosition.y) > tapMovementThreshold
+ ) {
+ return;
+ }
+
+ this._onPointerDown(evt, spreadsheet.zIndex + 1, RANGE_TYPE.NORMAL, this._getActiveViewport(evt));
+ this.endSelection();
+ state.stopPropagation();
+ }));
+ }
+
+ private _initHeaderEvent(
+ listenerDisposables: DisposableCollection,
+ header: SpreadsheetHeader | SpreadsheetColumnHeader,
+ spreadsheet: Spreadsheet,
+ scene: Scene,
+ rangeType: RANGE_TYPE.ROW | RANGE_TYPE.COLUMN
+ ): void {
+ listenerDisposables.add(header.onPointerDown$.subscribeEvent((evt, state) => {
+ if (!this.inRefSelectionMode()) {
+ return;
+ }
+
+ const skeleton = this._sheetSkeletonManagerService.getCurrentSkeleton();
+ if (!skeleton) {
+ return;
+ }
+
+ const coordinate = getCoordByOffset(evt.offsetX, evt.offsetY, scene, skeleton);
+ const index = rangeType === RANGE_TYPE.ROW ? coordinate.row : coordinate.column;
+ const matchSelectionData = checkInHeaderRanges(
+ this._workbookSelections.getCurrentSelections(),
+ index,
+ rangeType
+ );
+ if (matchSelectionData) {
+ return;
+ }
+
+ const scrollTimerType = rangeType === RANGE_TYPE.ROW ? ScrollTimerType.Y : ScrollTimerType.X;
+ this._onPointerDown(
+ evt,
+ (spreadsheet.zIndex || 1) + 1,
+ rangeType,
+ this._getActiveViewport(evt),
+ scrollTimerType
+ );
+ this.endSelection();
+ state.stopPropagation();
+ }));
+ }
+
+ override resetSelectionsByModelData(selectionsWithStyleList: readonly ISelectionWithStyle[]): void {
+ super.resetSelectionsByModelData(
+ selectionsWithStyleList.map((selection) => this._withMobileSelectionStyle(selection))
+ );
+ }
+
+ override newSelectionControl(
+ scene: Scene,
+ skeleton: SpreadsheetSkeleton,
+ selection: ISelectionWithStyle
+ ): MobileSelectionControl {
+ const {
+ rowHeaderWidth,
+ rowHeaderWidthAndMarginLeft,
+ columnHeaderHeight,
+ columnHeaderHeightAndMarginTop,
+ } = skeleton;
+ const rangeType = selection.range.rangeType ?? RANGE_TYPE.NORMAL;
+ const control = new MobileRefSelectionControl(scene, this._selectionControls.length, this._themeService, {
+ highlightHeader: this._highlightHeader,
+ rowHeaderWidth,
+ columnHeaderHeight,
+ rowHeaderOffsetX: Math.max(0, rowHeaderWidthAndMarginLeft - rowHeaderWidth),
+ columnHeaderOffsetY: Math.max(0, columnHeaderHeightAndMarginTop - columnHeaderHeight),
+ rangeType,
+ });
+ const selectionWithMobileStyle = this._withMobileSelectionStyle(selection);
+ const selectionWithCoord = attachSelectionWithCoord(selectionWithMobileStyle, skeleton);
+ control.updateRangeBySelectionWithCoord(selectionWithCoord, skeleton);
+ control.setEvent(false);
+ [
+ control.topLeftWidget,
+ control.topCenterWidget,
+ control.topRightWidget,
+ control.middleLeftWidget,
+ control.middleRightWidget,
+ control.bottomLeftWidget,
+ control.bottomCenterWidget,
+ control.bottomRightWidget,
+ ].forEach((widget) => {
+ widget.evented = false;
+ });
+ this._selectionControls.push(control);
+
+ const expandingModes = this._getExpandingModes(rangeType);
+ control.expandControlTopLeft?.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent) => {
+ this._startExpandingSelection(evt, control, rangeType, expandingModes.topLeft);
+ });
+ control.expandControlBottomRight?.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent) => {
+ this._startExpandingSelection(evt, control, rangeType, expandingModes.bottomRight);
+ });
+
+ return control;
+ }
+
+ private _withMobileSelectionStyle(selection: ISelectionWithStyle): ISelectionWithStyle {
+ return {
+ ...selection,
+ style: {
+ ...selection.style,
+ widgets: {},
+ expandCornerSize: 48,
+ },
+ };
+ }
+
+ private _getExpandingModes(rangeType: RANGE_TYPE): { topLeft: ExpandingControl; bottomRight: ExpandingControl } {
+ if (rangeType === RANGE_TYPE.ROW) {
+ return { topLeft: ExpandingControl.TOP, bottomRight: ExpandingControl.BOTTOM };
+ }
+ if (rangeType === RANGE_TYPE.COLUMN) {
+ return { topLeft: ExpandingControl.LEFT, bottomRight: ExpandingControl.RIGHT };
+ }
+ return { topLeft: ExpandingControl.TOP_LEFT, bottomRight: ExpandingControl.BOTTOM_RIGHT };
+ }
+
+ private _startExpandingSelection(
+ evt: IPointerEvent | IMouseEvent,
+ activeSelectionControl: MobileSelectionControl,
+ rangeType: RANGE_TYPE,
+ expandingControlMode: ExpandingControl
+ ): void {
+ const scene = this._scene;
+ if (!scene) {
+ return;
+ }
+
+ this.setActiveSelectionIndex(this._selectionControls.indexOf(activeSelectionControl));
+ this._expandingControlMode = expandingControlMode;
+ this._contextService.setContextValue(MOBILE_EXPANDING_SELECTION, true);
+ const anchorCell = this._changeCurrentCellWhenControlPointerDown(activeSelectionControl);
+ this._startRangeWhenPointerDown = {
+ ...anchorCell.mergeInfo,
+ startRow: anchorCell.mergeInfo?.startRow ?? anchorCell.actualRow,
+ endRow: anchorCell.mergeInfo?.endRow ?? anchorCell.actualRow,
+ startColumn: anchorCell.mergeInfo?.startColumn ?? anchorCell.actualColumn,
+ endColumn: anchorCell.mergeInfo?.endColumn ?? anchorCell.actualColumn,
+ };
+ this._selectionMoveStart$.next(this.getSelectionDataWithStyle());
+ this._clearUpdatingListeners();
+ this._addEndingListeners();
+ scene.getTransformer()?.clearSelectedObjects();
+
+ const relativeCoords = scene.getCoordRelativeToViewport(Vector2.FromArray([evt.offsetX, evt.offsetY]));
+ this._startViewportPosX = relativeCoords.x;
+ this._startViewportPosY = relativeCoords.y;
+ const viewportMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
+ this._setupPointerMoveListener(
+ viewportMain,
+ activeSelectionControl,
+ rangeType,
+ ScrollTimerType.ALL,
+ relativeCoords.x,
+ relativeCoords.y
+ );
+
+ this._escapeShortcutDisposable = this._shortcutService.forceEscape();
+ this._scenePointerUpSub = scene.onPointerUp$.subscribeEvent(() => {
+ this.endSelection();
+ this._contextService.setContextValue(MOBILE_EXPANDING_SELECTION, false);
+ this._expandingControlMode = ExpandingControl.BOTTOM_RIGHT;
+ });
+ }
+
+ private _changeCurrentCellWhenControlPointerDown(activeSelectionControl: MobileSelectionControl): ICellWithCoord {
+ const { startRow, startColumn, endRow, endColumn } = activeSelectionControl.model;
+ let currentCell: ICellWithCoord;
+
+ if (this._expandingControlMode === ExpandingControl.TOP_LEFT) {
+ currentCell = this._skeleton.getCellWithCoordByIndex(endRow, endColumn);
+ } else if (this._expandingControlMode === ExpandingControl.LEFT) {
+ currentCell = this._skeleton.getCellWithCoordByIndex(startRow, endColumn);
+ } else if (this._expandingControlMode === ExpandingControl.TOP) {
+ currentCell = this._skeleton.getCellWithCoordByIndex(endRow, startColumn);
+ } else {
+ currentCell = this._skeleton.getCellWithCoordByIndex(startRow, startColumn);
+ }
+
+ if (
+ this._expandingControlMode === ExpandingControl.LEFT ||
+ this._expandingControlMode === ExpandingControl.RIGHT ||
+ this._expandingControlMode === ExpandingControl.TOP ||
+ this._expandingControlMode === ExpandingControl.BOTTOM
+ ) {
+ currentCell.isMerged = false;
+ currentCell.isMergedMainCell = false;
+ }
+
+ activeSelectionControl.updateCurrCell(currentCell);
+ return currentCell;
+ }
+
+ protected override _setupPointerMoveListener(
+ viewportMain: Nullable<Viewport>,
+ activeSelectionControl: MobileSelectionControl,
+ rangeType: RANGE_TYPE,
+ scrollTimerType: ScrollTimerType = ScrollTimerType.ALL,
+ _moveStartPosX: number,
+ _moveStartPosY: number
+ ): void {
+ this._scrollTimer = ScrollTimer.create(this._scene, scrollTimerType);
+ this._scrollTimer.startScroll(viewportMain?.left ?? 0, viewportMain?.top ?? 0, viewportMain);
+
+ const scene = this._scene;
+ this._scenePointerMoveSub = scene.onPointerMove$.subscribeEvent((moveEvt: IPointerEvent | IMouseEvent) => {
+ if (this._contextService.getContextValue(MOBILE_PINCH_ZOOMING)) {
+ return;
+ }
+
+ const relativeCoords = scene.getCoordRelativeToViewport(
+ Vector2.FromArray([moveEvt.offsetX, moveEvt.offsetY])
+ );
+ this._movingHandler(relativeCoords.x, relativeCoords.y, activeSelectionControl, rangeType);
+ this._scrollTimer.scrolling(relativeCoords.x, relativeCoords.y, () => {
+ this._movingHandler(relativeCoords.x, relativeCoords.y, activeSelectionControl, rangeType);
+ });
+ });
+ }
+}
diff --git a/packages/sheets-formula-ui/src/services/render-services/ref-selections.render.service.ts b/packages/sheets-formula-ui/src/services/render-services/ref-selections.render.service.ts
index c05e6349cd..a1a17556f1 100644
--- a/packages/sheets-formula-ui/src/services/render-services/ref-selections.render.service.ts
+++ b/packages/sheets-formula-ui/src/services/render-services/ref-selections.render.service.ts
@@ -53,7 +53,7 @@ export function isSelectionRangeChanged(previous: Nullable<IRange>, current: Nul
*
*/
export class RefSelectionsRenderService extends BaseSelectionRenderService implements IRenderModule {
- private readonly _workbookSelections: WorkbookSelectionModel;
+ protected readonly _workbookSelections: WorkbookSelectionModel;
private _eventDisposables: Nullable<IDisposable>;
@@ -128,7 +128,7 @@ export class RefSelectionsRenderService extends BaseSelectionRenderService imple
this._disableSelectionChanging();
}
- private _initCanvasEventListeners(): IDisposable {
+ protected _initCanvasEventListeners(): IDisposable {
const sheetObject = this._getSheetObject();
const { spreadsheetRowHeader, spreadsheetColumnHeader, spreadsheet, spreadsheetLeftTopPlaceholder } = sheetObject;
const { scene } = this._context;
@@ -276,12 +276,12 @@ export class RefSelectionsRenderService extends BaseSelectionRenderService imple
}));
}
- private _getActiveViewport(evt: IPointerEvent | IMouseEvent): Nullable<Viewport> {
+ protected _getActiveViewport(evt: IPointerEvent | IMouseEvent): Nullable<Viewport> {
const sheetObject = this._getSheetObject();
return sheetObject?.scene.getActiveViewportByCoord(Vector2.FromArray([evt.offsetX, evt.offsetY]));
}
- private _getSheetObject() {
+ protected _getSheetObject() {
return getSheetObject(this._context.unit, this._context)!;
}
@@ -482,7 +482,7 @@ export class RefSelectionsRenderService extends BaseSelectionRenderService imple
* Diff between normal selection, no highlightHeader for ref selections.
* @param scene
* @param skeleton
- * @param selectionWithCoord
+ * @param selection
* @returns {SelectionControl} selectionControl just created
*/
override newSelectionControl(scene: Scene, skeleton: SpreadsheetSkeleton, selection: ISelectionWithStyle): SelectionControl {
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/formula-selection-business.spec.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/formula-selection-business.spec.ts
index cebc73af4a..f420aac508 100644
--- a/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/formula-selection-business.spec.ts
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/formula-selection-business.spec.ts
@@ -32,7 +32,6 @@ import {
isEventTargetInSameFormulaEmbedInteractionBoundary,
registerFormulaEditorRuntimePortal,
} from '../../formula-embed-integration.service';
-import { buildFormulaFunctionInsertion, buildFormulaOperatorInsertion } from '../../index';
import {
focusFormulaEditor,
hasActiveFormulaEmbedInteraction,
@@ -48,7 +47,7 @@ import {
shouldAddFormulaReference,
shouldSkipReferenceEditingByPointer,
} from '../use-formula-selection';
-import { calcHighlightRanges, createFormulaHighlightBody } from '../use-highlight';
+import { calcHighlightRanges, createFormulaHighlightBody, createHighlightTextRuns } from '../use-highlight';
import {
isFormulaEditorInteractionOwner,
shouldMoveFormulaSelectionFromCurrentSelection,
@@ -232,7 +231,7 @@ describe('formula selection update helpers', () => {
})).toBe(true);
});
- it('lets the mobile fx bar own formula selection when the canvas leaves no focused editor', () => {
+ it('lets the fx bar own formula selection when the canvas leaves no focused editor', () => {
expect(isFormulaEditorInteractionOwner(null, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, {
fxBarFocused: true,
allowMissingFocus: true,
@@ -318,7 +317,7 @@ describe('formula selection update helpers', () => {
expect(resolveFormulaSelectingIntent(false, false)).toBe(FormulaSelectingType.NOT_SELECT);
});
- it('only arms mobile reference picking after formula delimiters and operators', () => {
+ it('only arms reference picking after formula delimiters and operators', () => {
expect(shouldAddFormulaReference('=', 1)).toBe(true);
expect(shouldAddFormulaReference('=SUM(', 5)).toBe(true);
expect(shouldAddFormulaReference('=SUM(A1,', 8)).toBe(true);
@@ -328,32 +327,6 @@ describe('formula selection update helpers', () => {
expect(shouldAddFormulaReference('=A1', 3)).toBe(false);
});
- it('inserts a mobile function at the caret and leaves the caret inside its brackets', () => {
- expect(buildFormulaFunctionInsertion('=', { startOffset: 1, endOffset: 1 }, 'SUM')).toEqual({
- text: '=SUM()',
- caretOffset: 5,
- });
- expect(buildFormulaFunctionInsertion('=A1+', { startOffset: 4, endOffset: 4 }, 'AVERAGE')).toEqual({
- text: '=A1+AVERAGE()',
- caretOffset: 12,
- });
- expect(buildFormulaFunctionInsertion('plain', { startOffset: 5, endOffset: 5 }, 'COUNT')).toEqual({
- text: '=plainCOUNT()',
- caretOffset: 12,
- });
- });
-
- it('inserts a mobile formula operator at the caret or over selected text', () => {
- expect(buildFormulaOperatorInsertion('=A1B1', { startOffset: 3, endOffset: 3 }, '+')).toEqual({
- text: '=A1+B1',
- caretOffset: 4,
- });
- expect(buildFormulaOperatorInsertion('=A1+B1', { startOffset: 3, endOffset: 4 }, '*')).toEqual({
- text: '=A1*B1',
- caretOffset: 4,
- });
- });
-
it('reorders the active selection into the formula reference being edited and keeps ctrl-added ranges separate', () => {
const selections = [range(0, 0), range(1, 1), range(2, 2)];
@@ -666,6 +639,12 @@ describe('formula selection update helpers', () => {
});
describe('formula highlight helpers', () => {
+ it('does not cover the first highlighted character when there is no leading marker', () => {
+ const textRuns = [{ st: 0, ed: 12, ts: { cl: { rgb: '#ff0000' } } }];
+
+ expect(createHighlightTextRuns(textRuns, 0)).toEqual(textRuns);
+ });
+
it('does not copy stale paragraph metadata into a formula text replacement', () => {
const body = createFormulaHighlightBody('=F40', [
{ st: 0, ed: 1, ts: { fs: 11 } },
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-highlight.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-highlight.ts
index f2f7bed129..88f72f00ce 100644
--- a/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-highlight.ts
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-highlight.ts
@@ -270,7 +270,7 @@ export function useDocHight(_leadingCharacter: string = '') {
}
const highlightDataStream = getFormulaHighlightDataStream(_leadingCharacter, sequenceNodes, sourceText);
- const highlightTextRuns = [{ st: 0, ed: 1, ts: { fs: 11 } }, ...textRuns];
+ const highlightTextRuns = createHighlightTextRuns(textRuns, leadingCharacterLength);
let selections;
if (isNeedResetSelection) {
// Switching between uppercase and lowercase will trigger a reflow, causing the cursor to be misplaced. Let's refresh the cursor position here.
@@ -302,6 +302,12 @@ export function createFormulaHighlightBody(dataStream: string, textRuns: ITextRu
return { dataStream, textRuns };
}
+export function createHighlightTextRuns(textRuns: ITextRun[], leadingCharacterLength: number): ITextRun[] {
+ return leadingCharacterLength
+ ? [{ st: 0, ed: leadingCharacterLength, ts: { fs: 11 } }, ...textRuns]
+ : textRuns;
+}
+
interface IColorMap {
formulaRefColors: string[];
numberColor: string;
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx b/packages/sheets-formula-ui/src/views/formula-editor/index.tsx
index 6e9434bdf8..64a5c366fa 100644
--- a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx
+++ b/packages/sheets-formula-ui/src/views/formula-editor/index.tsx
@@ -73,7 +73,6 @@ import { useSheetSelectionChange } from './hooks/use-sheet-selection-change';
import { useStateRef } from './hooks/use-state-ref';
import { useSwitchSheet } from './hooks/use-switch-sheet';
import { useVerify } from './hooks/use-verify';
-import { MobileFunctionPanel } from './mobile-function-panel/MobileFunctionPanel';
import { SearchFunction } from './search-function/SearchFunction';
import { getFormulaText } from './utils/get-formula-text';
@@ -109,11 +108,6 @@ export interface IFormulaEditorProps {
backgroundColor?: string;
fontSize?: number;
};
- mobile?: boolean;
- mobileFxRequest?: number;
- mobileFunctionPanelRequest?: number;
- mobileOperatorRequest?: { id: number; value: string };
- onMobileFormulaActiveChange?: (active: boolean) => void;
}
export interface IFormulaEditorRef {
@@ -154,40 +148,6 @@ export function syncCounterpartFormulaEditorSelection(
editorService.getEditor(syncEditorId)?.setSelectionRanges(selections, false);
}
-export function buildFormulaFunctionInsertion(
- formulaText: string,
- selection: Pick<ITextRange, 'startOffset' | 'endOffset'> | undefined,
- functionName: string
-): { text: string; caretOffset: number } {
- const normalizedText = formulaText.replace(/\r?\n$/, '');
- const text = normalizedText.startsWith('=') ? normalizedText : `=${normalizedText}`;
- const selectionAdjustment = normalizedText.startsWith('=') ? 0 : 1;
- const startOffset = Math.max(1, Math.min(text.length, (selection?.startOffset ?? text.length) + selectionAdjustment));
- const endOffset = Math.max(startOffset, Math.min(text.length, (selection?.endOffset ?? startOffset) + selectionAdjustment));
-
- return {
- text: `${text.slice(0, startOffset)}${functionName}()${text.slice(endOffset)}`,
- caretOffset: startOffset + functionName.length + 1,
- };
-}
-
-export function buildFormulaOperatorInsertion(
- formulaText: string,
- selection: Pick<ITextRange, 'startOffset' | 'endOffset'> | undefined,
- value: string
-): { text: string; caretOffset: number } {
- const normalizedText = formulaText.replace(/\r?\n$/, '');
- const text = normalizedText.startsWith('=') ? normalizedText : `=${normalizedText}`;
- const selectionAdjustment = normalizedText.startsWith('=') ? 0 : 1;
- const startOffset = Math.max(1, Math.min(text.length, (selection?.startOffset ?? text.length) + selectionAdjustment));
- const endOffset = Math.max(startOffset, Math.min(text.length, (selection?.endOffset ?? startOffset) + selectionAdjustment));
-
- return {
- text: `${text.slice(0, startOffset)}${value}${text.slice(endOffset)}`,
- caretOffset: startOffset + value.length,
- };
-}
-
export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IFormulaEditorRef>) => {
const {
errorText,
@@ -212,14 +172,8 @@ export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IF
disableSelectionOnClick = false,
autofocus = true,
disableContextMenu,
- style,
borderless = false,
canvasStyle,
- mobile = false,
- mobileFxRequest,
- mobileFunctionPanelRequest,
- mobileOperatorRequest,
- onMobileFormulaActiveChange: propOnMobileFormulaActiveChange,
} = props;
const editorService = useDependency(IEditorService);
@@ -236,7 +190,6 @@ export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IF
},
}));
const onFormulaSelectingChange = useEvent(propOnFormulaSelectingChange);
- const onMobileFormulaActiveChange = useEvent(propOnMobileFormulaActiveChange);
const searchFunctionRef = useRef<HTMLElement>(null);
const editorRef = useRef<Editor>(undefined);
const [editor, setEditor] = useState<Editor>();
@@ -258,7 +211,6 @@ export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IF
const formulaTextRef = useStateRef(formulaText);
const formulaWithoutEqualSymbol = useMemo(() => getFormulaText(formulaText), [formulaText]);
const sequenceNodes = useMemo(() => getFormulaToken(formulaWithoutEqualSymbol), [formulaWithoutEqualSymbol, getFormulaToken]);
- const [mobileFunctionPanelOpen, setMobileFunctionPanelOpen] = useState(false);
const { isSelecting, isSelectingRef } = useFormulaSelecting({
unitId,
subUnitId,
@@ -266,7 +218,6 @@ export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IF
editorId,
isFocus,
disableOnClick: disableSelectionOnClick,
- resetSignal: mobile ? mobileFxRequest : undefined,
});
const highTextRef = useRef('');
const renderManagerService = useDependency(IRenderManagerService);
@@ -289,12 +240,6 @@ export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IF
onChange(formulaText);
}, [formulaText, onChange]);
- useEffect(() => {
- if (mobile) {
- onMobileFormulaActiveChange?.(formulaText.replace(/\r?\n$/, '').startsWith('='));
- }
- }, [formulaText, mobile, onMobileFormulaActiveChange]);
-
useEffect(() => {
if (!isFocus || !editor) {
return undefined;
@@ -322,21 +267,6 @@ export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IF
return () => subscription.unsubscribe();
}, [editor, editorId, editorService, isFocus]);
- const handledMobileFunctionPanelRequestRef = useRef(mobileFunctionPanelRequest);
- useEffect(() => {
- if (
- !mobile ||
- mobileFunctionPanelRequest === undefined ||
- mobileFunctionPanelRequest === handledMobileFunctionPanelRequestRef.current
- ) {
- return;
- }
-
- handledMobileFunctionPanelRequestRef.current = mobileFunctionPanelRequest;
- setMobileFunctionPanelOpen(true);
- editor?.blur();
- }, [editor, mobile, mobileFunctionPanelRequest]);
-
const highlightDoc = useDocHight('=');
const highlightSheet = useSheetHighlight(unitId, subUnitId);
const highlight = useEvent((text: string, isNeedResetSelection: boolean = true, isEnd?: boolean, newSelections?: ITextRange[]) => {
@@ -530,8 +460,8 @@ export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IF
}, [_isFocus, docSelectionRenderService, editor, focus, resetSelection, resetSelectionOnBlur]);
const { checkScrollBar } = useResize(editor, isSingle, autoScrollbar);
- useRefactorEffect(isFocus, isSelecting, unitId, editorId, disableContextMenu, mobile);
- useLeftAndRightArrow(Boolean(isFocus && isFocusing && moveCursor), selectingMode, editor, onMoveInEditor, getRefSelectionCount);
+ useRefactorEffect(isFocus, isSelecting, unitId, editorId, disableContextMenu);
+ useLeftAndRightArrow(Boolean(isFocus && moveCursor), selectingMode, editor, onMoveInEditor, getRefSelectionCount);
const handleSelectionChange = useEvent((refString: string, offset: number, isEnd: boolean) => {
if (!shouldApplyFormulaSelectionChange(
@@ -567,8 +497,7 @@ export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IF
isSupportAcrossSheet,
Boolean(selectingMode),
editor,
- handleSelectionChange,
- mobile
+ handleSelectionChange
);
useSwitchSheet(isFocus && Boolean(isSelecting && docFocusing), unitId, isSupportAcrossSheet, setIsFocus, onBlur, () => {
highlight(formulaTextRef.current, false, true);
@@ -582,7 +511,13 @@ export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IF
if (range.collapsed) {
const offset = res.offset;
setTimeout(() => {
- editor?.setSelectionRanges([{ startOffset: range.startOffset - offset, endOffset: range.endOffset - offset }]);
+ const nextSelections = [{
+ startOffset: range.startOffset - offset,
+ endOffset: range.endOffset - offset,
+ collapsed: true,
+ }];
+ editor?.setSelectionRanges(nextSelections);
+ syncCounterpartFormulaEditorSelection(editorService, editorId, nextSelections);
}, 30);
}
}
@@ -591,67 +526,6 @@ export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IF
}
};
- const closeMobileFunctionPanel = () => {
- setMobileFunctionPanelOpen(false);
- requestAnimationFrame(() => focus());
- };
-
- const applyMobileInsertion = useEvent((result: { text: string; caretOffset: number }) => {
- if (!editor) return;
- const selection = {
- startOffset: result.caretOffset,
- endOffset: result.caretOffset,
- collapsed: true,
- };
-
- editor.replaceText(result.text, false);
- editor.setSelectionRanges([selection], false);
-
- const counterpartEditorId = editorId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY
- ? DOCS_NORMAL_EDITOR_UNIT_ID_KEY
- : editorId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY
- ? DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY
- : null;
- if (counterpartEditorId) {
- const counterpartEditor = editorService.getEditor(counterpartEditorId);
- counterpartEditor?.replaceText(result.text, false);
- counterpartEditor?.setSelectionRanges([selection], false);
- }
-
- highlight(result.text, false, true, [selection]);
- requestAnimationFrame(() => focus());
- });
-
- const handledMobileOperatorRequestRef = useRef(mobileOperatorRequest?.id);
- useEffect(() => {
- if (
- !mobile ||
- !editor ||
- !mobileOperatorRequest?.value ||
- mobileOperatorRequest.id === handledMobileOperatorRequestRef.current
- ) {
- return;
- }
-
- handledMobileOperatorRequestRef.current = mobileOperatorRequest.id;
- const currentText = BuildTextUtils.transform.getPlainText(editor.getDocumentData().body?.dataStream ?? '');
- applyMobileInsertion(buildFormulaOperatorInsertion(
- currentText,
- editor.getSelectionRanges()?.[0],
- mobileOperatorRequest.value
- ));
- }, [applyMobileInsertion, editor, mobile, mobileOperatorRequest]);
-
- const handleMobileFunctionInsert = (functionName: string) => {
- if (!editor) return;
-
- const currentText = BuildTextUtils.transform.getPlainText(editor.getDocumentData().body?.dataStream ?? '');
- const currentSelection = editor.getSelectionRanges()?.[0];
- const result = buildFormulaFunctionInsertion(currentText, currentSelection, functionName);
- applyMobileInsertion(result);
- setMobileFunctionPanelOpen(false);
- };
-
const handleMouseUp = (event: React.MouseEvent<HTMLDivElement>) => {
if (hasActiveFormulaEmbedInteraction(formulaEditorContainerRef.current)) {
return;
@@ -693,7 +567,7 @@ export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IF
{errorText}
</div>
)}
- {(!mobile && functionScreenTips && editor && formulaWithoutEqualSymbol !== '') && (
+ {(functionScreenTips && editor && isFocusing && formulaWithoutEqualSymbol !== '') && (
<HelpFunction
editor={editor}
isFocus={isFocus}
@@ -708,14 +582,8 @@ export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IF
onSelect={handleFunctionSelect}
ref={searchFunctionRef}
editor={editor}
- mobile={mobile}
/>
)}
- <MobileFunctionPanel
- open={mobile && mobileFunctionPanelOpen}
- onClose={closeMobileFunctionPanel}
- onInsert={handleMobileFunctionInsert}
- />
</div>
);
});
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/search-function/SearchFunction.tsx b/packages/sheets-formula-ui/src/views/formula-editor/search-function/SearchFunction.tsx
index 94e811f87d..22b220b8ff 100644
--- a/packages/sheets-formula-ui/src/views/formula-editor/search-function/SearchFunction.tsx
+++ b/packages/sheets-formula-ui/src/views/formula-editor/search-function/SearchFunction.tsx
@@ -35,11 +35,10 @@ interface ISearchFunctionProps {
onChange?: (functionName: string) => void;
editor: Editor;
onClose?: () => void;
- mobile?: boolean;
};
export const SearchFunction = forwardRef<HTMLElement, ISearchFunctionProps>(SearchFunctionFactory);
function SearchFunctionFactory(props: ISearchFunctionProps, ref: any) {
- const { isFocus, sequenceNodes, onSelect, editor, onClose = noop, mobile = false } = props;
+ const { isFocus, sequenceNodes, onSelect, editor, onClose = noop } = props;
const editorId = editor.getEditorId();
const shortcutService = useDependency(IShortcutService);
const commandService = useDependency(ICommandService);
@@ -197,12 +196,12 @@ function SearchFunctionFactory(props: ISearchFunctionProps, ref: any) {
}
}}
data-u-comp="sheets-formula-editor"
- data-presentation={mobile ? 'mobile' : 'desktop'}
+ data-presentation="desktop"
className={clsx(`
univer-m-0 univer-box-border univer-list-none univer-overflow-y-auto univer-rounded-lg
univer-bg-gray-0 univer-p-2 univer-leading-5 univer-shadow-md univer-outline-none
dark:!univer-bg-gray-900
- `, mobile ? 'univer-max-h-[38dvh] univer-w-[calc(100vw-16px)]' : 'univer-max-h-[400px] univer-w-[250px]', borderClassName, scrollbarClassName)}
+ `, 'univer-max-h-[400px] univer-w-[250px]', borderClassName, scrollbarClassName)}
>
{searchList.map((item, index) => (
<li
@@ -211,7 +210,7 @@ function SearchFunctionFactory(props: ISearchFunctionProps, ref: any) {
univer-box-border univer-cursor-pointer univer-rounded univer-px-2 univer-py-1
univer-text-gray-900 univer-transition-colors
dark:!univer-text-gray-0
- `, { 'univer-flex univer-min-h-12 univer-flex-col univer-justify-center univer-px-3 univer-py-2': mobile }, {
+ `, {
'univer-bg-gray-200 dark:!univer-bg-gray-600': active === index,
})}
onMouseEnter={() => handleLiMouseEnter(index)}
diff --git a/packages/sheets-formula-ui/src/views/mobile/formula-editor/MobileFormulaEditor.tsx b/packages/sheets-formula-ui/src/views/mobile/formula-editor/MobileFormulaEditor.tsx
new file mode 100644
index 0000000000..368192c379
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/mobile/formula-editor/MobileFormulaEditor.tsx
@@ -0,0 +1,747 @@
+/**
+ * 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 { DocumentDataModel, IDisposable, ITextRange } from '@univerjs/core';
+import type { Editor, IKeyboardEventConfig } from '@univerjs/docs-ui';
+import type { KeyCode, MetaKeys } from '@univerjs/ui';
+import type { CSSProperties, ReactNode, Ref } from 'react';
+import type { IUniverSheetsFormulaUIConfig } from '../../../config/config';
+import type { FormulaSelectingType } from '../../formula-editor/hooks/use-formula-selection';
+import type { IRefSelection } from '../../formula-editor/hooks/use-highlight';
+import {
+ BuildTextUtils,
+ createInternalEditorID,
+ DisposableCollection,
+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ DocumentFlavor,
+ generateRandomId,
+ HorizontalAlign,
+ ICommandService,
+ IConfigService,
+ IContextService,
+ Injector,
+ IUniverInstanceService,
+ noop,
+ UniverInstanceType,
+ VerticalAlign,
+} from '@univerjs/core';
+import { clsx } from '@univerjs/design';
+import {
+ createEditorUndoRedoKeyboardConfig,
+ DocBackScrollRenderController,
+ DocSelectionRenderService,
+ IEditorService,
+ useKeyboardEvent,
+ useResize,
+} from '@univerjs/docs-ui';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { EMBEDDING_FORMULA_EDITOR, MOBILE_FORMULA_FUNCTION_PANEL_OPEN } from '@univerjs/sheets-ui';
+import { useDependency, useEvent, useObservable, useUpdateEffect } from '@univerjs/ui';
+import { forwardRef, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from 'react';
+import { map } from 'rxjs';
+import { PLUGIN_CONFIG_KEY_BASE } from '../../../config/config';
+import {
+ IFormulaEmbedInteractionBoundaryService,
+ IFormulaEmbedRuntimeFocusCoordinator,
+ registerFormulaEditorRuntimePortal,
+ resolveActiveFormulaEmbedRuntimeDomScope,
+ resolveFormulaEmbedRuntimeDomScope,
+} from '../../formula-editor/formula-embed-integration.service';
+import { hasActiveFormulaEmbedInteraction, shouldRefocusFormulaEditorOnMouseUp, useFocus } from '../../formula-editor/hooks/use-focus';
+import { getSelectionAfterLaggingFormulaInput, useFormulaSelecting } from '../../formula-editor/hooks/use-formula-selection';
+import { useFormulaToken } from '../../formula-editor/hooks/use-formula-token';
+import { useDocHight, useSheetHighlight } from '../../formula-editor/hooks/use-highlight';
+import { useLeftAndRightArrow } from '../../formula-editor/hooks/use-left-and-right-arrow';
+import { useRefactorEffect } from '../../formula-editor/hooks/use-refactor-effect';
+import { useResetSelection } from '../../formula-editor/hooks/use-reset-selection';
+import { useSheetSelectionChange } from '../../formula-editor/hooks/use-sheet-selection-change';
+import { useStateRef } from '../../formula-editor/hooks/use-state-ref';
+import { useSwitchSheet } from '../../formula-editor/hooks/use-switch-sheet';
+import { useVerify } from '../../formula-editor/hooks/use-verify';
+import { getFormulaText } from '../../formula-editor/utils/get-formula-text';
+import { findIndexFromSequenceNodes, findRefSequenceIndex } from '../../range-selector/utils/find-index-from-sequence-nodes';
+import { MobileFunctionPanel } from './mobile-function-panel/MobileFunctionPanel';
+import { MobileSearchFunction } from './search-function/MobileSearchFunction';
+
+export interface IMobileFormulaEditorProps {
+ unitId: string;
+ subUnitId: string;
+ initValue: `=${string}`;
+ autofocus?: boolean;
+ onChange: (text: string) => void;
+ errorText?: string | ReactNode;
+ onVerify?: (res: boolean, result: string) => void;
+ isFocus?: boolean;
+ onFocus?: () => void;
+ onBlur?: () => void;
+ isSupportAcrossSheet?: boolean;
+ className?: string;
+ editorId?: string;
+ moveCursor?: boolean;
+ onFormulaSelectingChange?: (isSelecting: FormulaSelectingType, isFocusing: boolean) => void;
+ keyboardEventConfig?: IKeyboardEventConfig;
+ onMoveInEditor?: (keyCode: KeyCode, metaKey?: MetaKeys) => void;
+ resetSelectionOnBlur?: boolean;
+ isSingle?: boolean;
+ autoScrollbar?: boolean;
+ /**
+ * Disable selection when click formula editor
+ */
+ disableSelectionOnClick?: boolean;
+ disableContextMenu?: boolean;
+ style?: CSSProperties;
+ borderless?: boolean;
+ canvasStyle?: {
+ backgroundColor?: string;
+ fontSize?: number;
+ };
+ mobileFxRequest?: number;
+ mobileFunctionPanelRequest?: number;
+ mobileOperatorRequest?: { id: number; value: string };
+ onMobileFormulaActiveChange?: (active: boolean) => void;
+}
+
+export interface IMobileFormulaEditorRef {
+ isClickOutSide: (e: MouseEvent) => boolean;
+}
+
+export function shouldApplyFormulaSelectionChange(
+ selectingMode: FormulaSelectingType | number,
+ isFocusing: boolean | undefined,
+ hasActiveInteraction: boolean
+): boolean {
+ return Boolean(selectingMode) || Boolean(isFocusing) || hasActiveInteraction;
+}
+
+interface IFormulaEditorSelectionSyncService {
+ getEditor: (editorId: string) => Pick<Editor, 'setSelectionRanges'> | null | undefined | void;
+}
+
+export function syncCounterpartFormulaEditorSelection(
+ editorService: IFormulaEditorSelectionSyncService,
+ editorId: string,
+ selections: ITextRange[] | undefined
+): void {
+ if (!selections?.length) {
+ return;
+ }
+
+ const syncEditorId = editorId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY
+ ? DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY
+ : editorId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY
+ ? DOCS_NORMAL_EDITOR_UNIT_ID_KEY
+ : null;
+
+ if (!syncEditorId) {
+ return;
+ }
+
+ editorService.getEditor(syncEditorId)?.setSelectionRanges(selections, false);
+}
+
+export function restoreMobileFormulaEditorHostFocus(
+ editorService: Pick<IEditorService, 'blur' | 'getFocusId'>,
+ univerInstanceService: Pick<IUniverInstanceService, 'focusUnit' | 'getCurrentUnitOfType' | 'getUnit'>,
+ editorId: string,
+ hostUnitId: string
+): void {
+ if (editorService.getFocusId() !== editorId) {
+ return;
+ }
+
+ editorService.blur(true);
+ const currentWorkbook = univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_SHEET);
+ if (
+ currentWorkbook?.getUnitId() !== hostUnitId ||
+ !univerInstanceService.getUnit(hostUnitId, UniverInstanceType.UNIVER_SHEET)
+ ) {
+ return;
+ }
+
+ univerInstanceService.focusUnit(hostUnitId);
+}
+
+export function buildFormulaFunctionInsertion(
+ formulaText: string,
+ selection: Pick<ITextRange, 'startOffset' | 'endOffset'> | undefined,
+ functionName: string
+): { text: string; caretOffset: number } {
+ const normalizedText = formulaText.replace(/\r?\n$/, '');
+ const text = normalizedText.startsWith('=') ? normalizedText : `=${normalizedText}`;
+ const selectionAdjustment = normalizedText.startsWith('=') ? 0 : 1;
+ const startOffset = Math.max(1, Math.min(text.length, (selection?.startOffset ?? text.length) + selectionAdjustment));
+ const endOffset = Math.max(startOffset, Math.min(text.length, (selection?.endOffset ?? startOffset) + selectionAdjustment));
+
+ return {
+ text: `${text.slice(0, startOffset)}${functionName}()${text.slice(endOffset)}`,
+ caretOffset: startOffset + functionName.length + 1,
+ };
+}
+
+export function buildFormulaOperatorInsertion(
+ formulaText: string,
+ selection: Pick<ITextRange, 'startOffset' | 'endOffset'> | undefined,
+ value: string
+): { text: string; caretOffset: number } {
+ const normalizedText = formulaText.replace(/\r?\n$/, '');
+ const text = normalizedText.startsWith('=') ? normalizedText : `=${normalizedText}`;
+ const selectionAdjustment = normalizedText.startsWith('=') ? 0 : 1;
+ const startOffset = Math.max(1, Math.min(text.length, (selection?.startOffset ?? text.length) + selectionAdjustment));
+ const endOffset = Math.max(startOffset, Math.min(text.length, (selection?.endOffset ?? startOffset) + selectionAdjustment));
+
+ return {
+ text: `${text.slice(0, startOffset)}${value}${text.slice(endOffset)}`,
+ caretOffset: startOffset + value.length,
+ };
+}
+
+export const MobileFormulaEditor = forwardRef((props: IMobileFormulaEditorProps, ref: Ref<IMobileFormulaEditorRef>) => {
+ const {
+ errorText,
+ initValue,
+ unitId,
+ subUnitId,
+ isFocus: _isFocus = true,
+ isSupportAcrossSheet = false,
+ onFocus = noop,
+ onBlur = noop,
+ onChange: propOnChange,
+ onVerify,
+ className,
+ editorId: propEditorId,
+ moveCursor = true,
+ onFormulaSelectingChange: propOnFormulaSelectingChange,
+ keyboardEventConfig,
+ onMoveInEditor,
+ resetSelectionOnBlur = true,
+ autoScrollbar = true,
+ isSingle = true,
+ disableSelectionOnClick = false,
+ autofocus = true,
+ disableContextMenu,
+ borderless = false,
+ canvasStyle,
+ mobileFxRequest,
+ mobileFunctionPanelRequest,
+ mobileOperatorRequest,
+ onMobileFormulaActiveChange: propOnMobileFormulaActiveChange,
+ } = props;
+
+ const editorService = useDependency(IEditorService);
+ const commandService = useDependency(ICommandService);
+ const contextService = useDependency(IContextService);
+ const injector = useDependency(Injector);
+ const sheetEmbeddingRef = useRef<HTMLDivElement>(null);
+ const onChange = useEvent(propOnChange);
+ useImperativeHandle(ref, () => ({
+ isClickOutSide: (e: MouseEvent) => {
+ if (sheetEmbeddingRef.current) {
+ return !sheetEmbeddingRef.current.contains(e.target as Node);
+ }
+ return false;
+ },
+ }));
+ const onFormulaSelectingChange = useEvent(propOnFormulaSelectingChange);
+ const onMobileFormulaActiveChange = useEvent(propOnMobileFormulaActiveChange);
+ const searchFunctionRef = useRef<HTMLElement>(null);
+ const editorRef = useRef<Editor>(undefined);
+ const [editor, setEditor] = useState<Editor>();
+ const [isFocus, setIsFocus] = useState(_isFocus);
+ const formulaEditorContainerRef = useRef<HTMLDivElement>(null);
+ const editorId = useMemo(() => propEditorId ?? createInternalEditorID(`${EMBEDDING_FORMULA_EDITOR}-${generateRandomId(4)}`), []);
+ const isError = errorText !== undefined;
+ const univerInstanceService = useDependency(IUniverInstanceService);
+ const document = univerInstanceService.getUnit<DocumentDataModel>(editorId);
+ const getFormulaToken = useFormulaToken();
+ const formulaText = useObservable(
+ document
+ ? () => document.change$.pipe(map(() => BuildTextUtils.transform.getPlainText(document.getBody()?.dataStream ?? '')))
+ : null,
+ BuildTextUtils.transform.getPlainText(document?.getBody()?.dataStream ?? ''),
+ false,
+ [document]
+ );
+ const formulaTextRef = useStateRef(formulaText);
+ const formulaWithoutEqualSymbol = useMemo(() => getFormulaText(formulaText), [formulaText]);
+ const sequenceNodes = useMemo(() => getFormulaToken(formulaWithoutEqualSymbol), [formulaWithoutEqualSymbol, getFormulaToken]);
+ const [mobileFunctionPanelOpen, setMobileFunctionPanelOpen] = useState(false);
+ const { isSelecting, isSelectingRef } = useFormulaSelecting({
+ unitId,
+ subUnitId,
+ editor,
+ editorId,
+ isFocus,
+ disableOnClick: disableSelectionOnClick,
+ resetSignal: mobileFxRequest,
+ });
+ const highTextRef = useRef('');
+ const renderManagerService = useDependency(IRenderManagerService);
+ const renderer = renderManagerService.getRenderUnitById(editorId);
+ const docSelectionRenderService = renderer?.with(DocSelectionRenderService);
+ const isFocusing = docSelectionRenderService?.isFocusing;
+ const currentDoc$ = useMemo(() => univerInstanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_DOC), [univerInstanceService]);
+ const currentDoc = useObservable(currentDoc$);
+ const docFocusing = currentDoc?.getUnitId() === editorId;
+ const refSelectionsRef = useRef([] as IRefSelection[]);
+ const getRefSelections = useEvent(() => refSelectionsRef.current);
+ const getRefSelectionCount = useEvent(() => getRefSelections().length);
+ const selectingMode = isSelecting;
+
+ // whether to hide formula search and help popup
+ const configService = useDependency(IConfigService);
+ const functionScreenTips = configService.getConfig<IUniverSheetsFormulaUIConfig>(PLUGIN_CONFIG_KEY_BASE)?.functionScreenTips ?? true;
+
+ useUpdateEffect(() => {
+ onChange(formulaText);
+ }, [formulaText, onChange]);
+
+ useEffect(() => {
+ onMobileFormulaActiveChange?.(formulaText.replace(/\r?\n$/, '').startsWith('='));
+ }, [formulaText, onMobileFormulaActiveChange]);
+
+ useEffect(() => {
+ if (!isFocus || !editor) {
+ return undefined;
+ }
+
+ const subscription = editor.input$.subscribe(({ content, isComposing }) => {
+ if (isComposing) {
+ return;
+ }
+
+ queueMicrotask(() => {
+ const selection = editor.getSelectionRanges()?.[0];
+ const dataStream = editor.getDocumentData().body?.dataStream ?? '';
+ const normalizedSelection = getSelectionAfterLaggingFormulaInput(dataStream, selection, content);
+ if (!normalizedSelection) {
+ return;
+ }
+
+ const selections = [normalizedSelection];
+ editor.setSelectionRanges(selections, false);
+ syncCounterpartFormulaEditorSelection(editorService, editorId, selections);
+ });
+ });
+
+ return () => subscription.unsubscribe();
+ }, [editor, editorId, editorService, isFocus]);
+
+ const handledMobileFunctionPanelRequestRef = useRef(mobileFunctionPanelRequest);
+ useEffect(() => {
+ if (
+ mobileFunctionPanelRequest === undefined ||
+ mobileFunctionPanelRequest === handledMobileFunctionPanelRequestRef.current
+ ) {
+ return;
+ }
+
+ handledMobileFunctionPanelRequestRef.current = mobileFunctionPanelRequest;
+ contextService.setContextValue(MOBILE_FORMULA_FUNCTION_PANEL_OPEN, true);
+ setMobileFunctionPanelOpen(true);
+ editor?.blur();
+ }, [contextService, editor, mobileFunctionPanelRequest]);
+
+ useEffect(() => () => {
+ contextService.setContextValue(MOBILE_FORMULA_FUNCTION_PANEL_OPEN, false);
+ }, [contextService]);
+
+ const highlightDoc = useDocHight('=');
+ const highlightSheet = useSheetHighlight(unitId, subUnitId);
+ const highlight = useEvent((text: string, isNeedResetSelection: boolean = true, isEnd?: boolean, newSelections?: ITextRange[]) => {
+ if (!editorRef.current) return;
+ highTextRef.current = text;
+ const formulaStr = text[0] === '=' ? text.slice(1) : '';
+ const sequenceNodes = getFormulaToken(formulaStr);
+ const ranges = highlightDoc(
+ editorRef.current,
+ sequenceNodes,
+ isNeedResetSelection,
+ newSelections,
+ formulaStr
+ );
+ refSelectionsRef.current = ranges;
+
+ if (isEnd) {
+ const currentDocSelections = newSelections ?? editor?.getSelectionRanges();
+ if (currentDocSelections?.length === 1) {
+ const docRange = currentDocSelections[0];
+ const offset = docRange.startOffset - 1;
+ const nodeIndex = findIndexFromSequenceNodes(sequenceNodes, offset, false);
+ const refIndex = findRefSequenceIndex(sequenceNodes, nodeIndex);
+ // make sure current editing selection is at the end
+ if (refIndex >= 0) {
+ const target = ranges.splice(refIndex, 1)[0];
+ target && ranges.push(target);
+ }
+ }
+
+ highlightSheet(isFocus ? ranges : [], editorRef.current, isEnd);
+ }
+ });
+
+ // re highlight when focus
+ useEffect(() => {
+ if (isFocus) {
+ highlight(formulaText, false, true);
+ }
+ }, [isFocus]);
+
+ // re highlight when formula text changed
+ useEffect(() => {
+ if (isFocus) {
+ if (highTextRef.current === formulaText) return;
+ highlight(formulaText, false, true);
+ }
+ }, [formulaText]);
+
+ useVerify(isFocus, onVerify, formulaText);
+ const focus = useFocus(editor);
+
+ const resetSelection = useResetSelection(isFocus, unitId, subUnitId);
+
+ useEffect(() => {
+ onFormulaSelectingChange(isSelecting, docSelectionRenderService?.isFocusing ?? true);
+ }, [onFormulaSelectingChange, isSelecting]);
+
+ const resolvedKeyboardEventConfig = useMemo(() => createEditorUndoRedoKeyboardConfig({
+ commandService,
+ univerInstanceService,
+ editorUnitId: editorId,
+ keyCodes: keyboardEventConfig?.keyCodes,
+ handler: keyboardEventConfig?.handler,
+ }), [commandService, editorId, keyboardEventConfig, univerInstanceService]);
+
+ useKeyboardEvent(isFocus, resolvedKeyboardEventConfig, editor);
+
+ useLayoutEffect(() => {
+ let dispose: IDisposable;
+ if (formulaEditorContainerRef.current) {
+ dispose = editorService.register({
+ autofocus,
+ editorUnitId: editorId,
+ initialSnapshot: {
+ id: editorId,
+ body: {
+ dataStream: `${initValue}\r\n`,
+ textRuns: [],
+ customBlocks: [],
+ customDecorations: [],
+ customRanges: [],
+ },
+ documentStyle: {
+ pageSize: {
+ width: Number.POSITIVE_INFINITY,
+ height: Number.POSITIVE_INFINITY,
+ },
+ documentFlavor: DocumentFlavor.UNSPECIFIED,
+ marginTop: 0,
+ marginBottom: 0,
+ marginRight: 0,
+ marginLeft: 0,
+ paragraphLineGapDefault: 0,
+ renderConfig: {
+ horizontalAlign: HorizontalAlign.UNSPECIFIED,
+ verticalAlign: VerticalAlign.TOP,
+ },
+ },
+ },
+ canvasStyle,
+ preserveHostFocus: true,
+ }, formulaEditorContainerRef.current);
+ const registeredEditor = editorService.getEditor(editorId)! as Editor;
+ editorRef.current = registeredEditor;
+ setEditor(registeredEditor);
+ highlight(initValue, false, true);
+ }
+
+ return () => {
+ editorRef.current = undefined;
+ restoreMobileFormulaEditorHostFocus(editorService, univerInstanceService, editorId, unitId);
+ dispose?.dispose();
+ };
+ }, []);
+
+ useEffect(() => {
+ const formulaEditorContainer = formulaEditorContainerRef.current;
+ if (!isFocus || !formulaEditorContainer || !injector.has(IFormulaEmbedRuntimeFocusCoordinator)) {
+ return undefined;
+ }
+
+ const focusCoordinator = injector.get(IFormulaEmbedRuntimeFocusCoordinator);
+ const scope = resolveFormulaEmbedRuntimeDomScope(formulaEditorContainer) ??
+ focusCoordinator.resolveRuntimeScopeByChildUnitId(editorId) ??
+ resolveActiveFormulaEmbedRuntimeDomScope(formulaEditorContainer.ownerDocument);
+ if (!scope) {
+ return undefined;
+ }
+
+ const collection = new DisposableCollection();
+ const interactionBoundaryService = injector.has(IFormulaEmbedInteractionBoundaryService)
+ ? injector.get(IFormulaEmbedInteractionBoundaryService)
+ : undefined;
+
+ collection.add(focusCoordinator.acquireLease({
+ embedId: scope.embedId,
+ role: 'child-editor',
+ owner: 'sheet-formula-editor',
+ hostUnitId: scope.hostUnitId,
+ childUnitId: scope.childUnitId,
+ associatedChildUnitIds: [editorId],
+ }));
+ if (interactionBoundaryService) {
+ collection.add(interactionBoundaryService.registerOwnedElement(scope.embedId, formulaEditorContainer));
+ }
+ collection.add(focusCoordinator.registerElement({
+ embedId: scope.embedId,
+ role: 'child-editor',
+ element: formulaEditorContainer,
+ }));
+ collection.add(registerFormulaEditorRuntimePortal({
+ embedId: scope.embedId,
+ editorId,
+ ownerDocument: formulaEditorContainer.ownerDocument,
+ interactionBoundaryService,
+ focusCoordinator,
+ }));
+
+ return () => collection.dispose();
+ }, [editorId, injector, isFocus]);
+
+ useLayoutEffect(() => {
+ let focusRetryFrame = 0;
+ let finalFocusRetryFrame = 0;
+
+ const retryFocus = () => {
+ if (_isFocus && !docSelectionRenderService?.isFocusing) {
+ focus();
+ }
+ };
+
+ if (_isFocus) {
+ setIsFocus(_isFocus);
+ focus();
+ // In Shadow DOM hosts, canvas dblclick can steal focus back after the editor becomes visible.
+ focusRetryFrame = requestAnimationFrame(() => {
+ retryFocus();
+ finalFocusRetryFrame = requestAnimationFrame(retryFocus);
+ });
+ } else {
+ if (resetSelectionOnBlur) {
+ editor?.blur();
+ resetSelection();
+ }
+ setIsFocus(_isFocus);
+ }
+
+ return () => {
+ cancelAnimationFrame(focusRetryFrame);
+ cancelAnimationFrame(finalFocusRetryFrame);
+ };
+ }, [_isFocus, docSelectionRenderService, editor, focus, resetSelection, resetSelectionOnBlur]);
+
+ const { checkScrollBar } = useResize(editor, isSingle, autoScrollbar);
+ useRefactorEffect(isFocus, isSelecting, unitId, editorId, disableContextMenu, true);
+ useLeftAndRightArrow(Boolean(isFocus && moveCursor), selectingMode, editor, onMoveInEditor, getRefSelectionCount);
+
+ const handleSelectionChange = useEvent((refString: string, offset: number, isEnd: boolean) => {
+ if (!shouldApplyFormulaSelectionChange(
+ selectingMode,
+ isFocusing,
+ hasActiveFormulaEmbedInteraction(formulaEditorContainerRef.current)
+ )) {
+ return;
+ }
+
+ const newSelections = offset !== -1 ? [{ startOffset: offset + 1, endOffset: offset + 1, collapsed: true }] : undefined;
+ highlight(`=${refString}`, true, isEnd, newSelections);
+ syncCounterpartFormulaEditorSelection(editorService, editorId, newSelections);
+ if (isEnd) {
+ focus();
+ if (offset !== -1) {
+ setTimeout(() => {
+ const range = { startOffset: offset + 1, endOffset: offset + 1 };
+ const docBackScrollRenderController = editor?.render.with(DocBackScrollRenderController);
+ docBackScrollRenderController?.scrollToRange({ ...range, collapsed: true });
+ }, 50);
+ }
+ checkScrollBar();
+ }
+ });
+ useSheetSelectionChange(
+ isFocus && Boolean(isSelecting),
+ isFocus,
+ isSelectingRef,
+ unitId,
+ subUnitId,
+ getRefSelections,
+ isSupportAcrossSheet,
+ Boolean(selectingMode),
+ editor,
+ handleSelectionChange,
+ true
+ );
+ useSwitchSheet(isFocus && Boolean(isSelecting && docFocusing), unitId, isSupportAcrossSheet, setIsFocus, onBlur, () => {
+ highlight(formulaTextRef.current, false, true);
+ });
+
+ const handleFunctionSelect = (res: { text: string; offset: number }) => {
+ if (res) {
+ const selections = editor?.getSelectionRanges();
+ if (selections && selections.length === 1) {
+ const range = selections[0];
+ if (range.collapsed) {
+ const offset = res.offset;
+ setTimeout(() => {
+ const nextSelections = [{
+ startOffset: range.startOffset - offset,
+ endOffset: range.endOffset - offset,
+ collapsed: true,
+ }];
+ editor?.setSelectionRanges(nextSelections);
+ syncCounterpartFormulaEditorSelection(editorService, editorId, nextSelections);
+ }, 30);
+ }
+ }
+ focus();
+ highlight(`=${res.text}`);
+ }
+ };
+
+ const closeMobileFunctionPanel = () => {
+ setMobileFunctionPanelOpen(false);
+ requestAnimationFrame(() => {
+ focus();
+ contextService.setContextValue(MOBILE_FORMULA_FUNCTION_PANEL_OPEN, false);
+ });
+ };
+
+ const applyMobileInsertion = useEvent((result: { text: string; caretOffset: number }) => {
+ if (!editor) return;
+ const selection = {
+ startOffset: result.caretOffset,
+ endOffset: result.caretOffset,
+ collapsed: true,
+ };
+
+ editor.replaceText(result.text, false);
+ editor.setSelectionRanges([selection], false);
+
+ const counterpartEditorId = editorId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY
+ ? DOCS_NORMAL_EDITOR_UNIT_ID_KEY
+ : editorId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY
+ ? DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY
+ : null;
+ if (counterpartEditorId) {
+ const counterpartEditor = editorService.getEditor(counterpartEditorId);
+ counterpartEditor?.replaceText(result.text, false);
+ counterpartEditor?.setSelectionRanges([selection], false);
+ }
+
+ highlight(result.text, false, true, [selection]);
+ requestAnimationFrame(() => focus());
+ });
+
+ const handledMobileOperatorRequestRef = useRef(mobileOperatorRequest?.id);
+ useEffect(() => {
+ if (
+ !editor ||
+ !mobileOperatorRequest?.value ||
+ mobileOperatorRequest.id === handledMobileOperatorRequestRef.current
+ ) {
+ return;
+ }
+
+ handledMobileOperatorRequestRef.current = mobileOperatorRequest.id;
+ const currentText = BuildTextUtils.transform.getPlainText(editor.getDocumentData().body?.dataStream ?? '');
+ applyMobileInsertion(buildFormulaOperatorInsertion(
+ currentText,
+ editor.getSelectionRanges()?.[0],
+ mobileOperatorRequest.value
+ ));
+ }, [applyMobileInsertion, editor, mobileOperatorRequest]);
+
+ const handleMobileFunctionInsert = (functionName: string) => {
+ if (!editor) return;
+
+ const currentText = BuildTextUtils.transform.getPlainText(editor.getDocumentData().body?.dataStream ?? '');
+ const currentSelection = editor.getSelectionRanges()?.[0];
+ const result = buildFormulaFunctionInsertion(currentText, currentSelection, functionName);
+ applyMobileInsertion(result);
+ setMobileFunctionPanelOpen(false);
+ requestAnimationFrame(() => {
+ contextService.setContextValue(MOBILE_FORMULA_FUNCTION_PANEL_OPEN, false);
+ });
+ };
+
+ const handleMouseUp = (event: React.MouseEvent<HTMLDivElement>) => {
+ if (hasActiveFormulaEmbedInteraction(formulaEditorContainerRef.current)) {
+ return;
+ }
+ if (!shouldRefocusFormulaEditorOnMouseUp({
+ target: event.target,
+ isFocusing,
+ isPointerSelecting: docSelectionRenderService?.isOnPointerEvent,
+ })) {
+ return;
+ }
+ setIsFocus(true);
+ onFocus();
+ focus();
+ };
+
+ return (
+ <div className={className}>
+ <div
+ ref={sheetEmbeddingRef}
+ className={clsx(`
+ univer-relative univer-box-border univer-flex univer-size-full univer-items-center
+ univer-justify-around univer-gap-2 univer-rounded-none univer-p-0
+ `, {
+ 'univer-ring-1': !borderless,
+ 'univer-ring-primary-500': isFocus && !borderless,
+ 'univer-ring-red-500': isError && !borderless,
+ })}
+ >
+ <div
+ ref={formulaEditorContainerRef}
+ data-u-comp="formula-editor"
+ className="univer-relative univer-size-full"
+ onMouseUp={handleMouseUp}
+ />
+ </div>
+ {(errorText !== undefined) && (
+ <div className="univer-my-1 univer-text-xs univer-text-red-500">
+ {errorText}
+ </div>
+ )}
+ {(functionScreenTips && !!editor) && (
+ <MobileSearchFunction
+ isFocus={isFocus}
+ sequenceNodes={sequenceNodes}
+ onSelect={handleFunctionSelect}
+ ref={searchFunctionRef}
+ editor={editor}
+ />
+ )}
+ <MobileFunctionPanel
+ open={mobileFunctionPanelOpen}
+ onClose={closeMobileFunctionPanel}
+ onInsert={handleMobileFunctionInsert}
+ />
+ </div>
+ );
+});
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/mobile-function-panel/MobileFunctionPanel.tsx b/packages/sheets-formula-ui/src/views/mobile/formula-editor/mobile-function-panel/MobileFunctionPanel.tsx
similarity index 99%
rename from packages/sheets-formula-ui/src/views/formula-editor/mobile-function-panel/MobileFunctionPanel.tsx
rename to packages/sheets-formula-ui/src/views/mobile/formula-editor/mobile-function-panel/MobileFunctionPanel.tsx
index 1b7248025d..41be4107ce 100644
--- a/packages/sheets-formula-ui/src/views/formula-editor/mobile-function-panel/MobileFunctionPanel.tsx
+++ b/packages/sheets-formula-ui/src/views/mobile/formula-editor/mobile-function-panel/MobileFunctionPanel.tsx
@@ -15,13 +15,13 @@
*/
import type { IFunctionInfo, ISearchItem } from '@univerjs/engine-formula';
-import type { LocaleKey } from '../../../locale/types';
+import type { LocaleKey } from '../../../../locale/types';
import { LocaleService } from '@univerjs/core';
import { clsx, scrollbarClassName } from '@univerjs/design';
import { FunctionType, IDescriptionService } from '@univerjs/engine-formula';
import { useDependency } from '@univerjs/ui';
import { useEffect, useMemo, useState } from 'react';
-import { getFunctionTypeValues } from '../../../services/utils';
+import { getFunctionTypeValues } from '../../../../services/utils';
const RECENT_FUNCTIONS_KEY = 'univer-mobile-recent-formula-functions';
const RECOMMENDED_FUNCTIONS = ['SUM', 'AVERAGE', 'COUNT', 'MAX', 'MIN', 'IF', 'XLOOKUP', 'ROUND'];
@@ -35,7 +35,6 @@ function readRecentFunctions(): string[] {
return [];
}
}
-
function rememberFunction(name: string): void {
try {
const recent = [name, ...readRecentFunctions().filter((item) => item !== name)].slice(0, 8);
@@ -132,7 +131,7 @@ export function MobileFunctionPanel(props: {
role="dialog"
aria-label={copy.title}
className="
- univer-absolute univer-inset-x-0 univer-bottom-0 univer-flex univer-h-[80dvh] univer-flex-col
+ univer-absolute univer-inset-x-0 univer-bottom-0 univer-flex univer-h-[80vh] univer-flex-col
univer-overflow-hidden univer-rounded-t-2xl univer-bg-gray-0 univer-shadow-lg
dark:!univer-bg-gray-900
"
diff --git a/packages/sheets-formula-ui/src/views/mobile/formula-editor/search-function/MobileSearchFunction.tsx b/packages/sheets-formula-ui/src/views/mobile/formula-editor/search-function/MobileSearchFunction.tsx
new file mode 100644
index 0000000000..b6b1d1bbde
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/mobile/formula-editor/search-function/MobileSearchFunction.tsx
@@ -0,0 +1,240 @@
+/**
+ * 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 { Editor } from '@univerjs/docs-ui';
+import type { FunctionType, ISequenceNode } from '@univerjs/engine-formula';
+import { CommandType, DisposableCollection, ICommandService, noop } from '@univerjs/core';
+import { borderClassName, clsx, scrollbarClassName } from '@univerjs/design';
+import { DeviceInputEventType } from '@univerjs/engine-render';
+import { IShortcutService, KeyCode, RectPopup, useDependency } from '@univerjs/ui';
+import { forwardRef, useEffect, useMemo, useRef, useState } from 'react';
+import { useEditorPosition } from '../../../formula-editor/hooks/use-editor-position';
+import { useFormulaSearch } from '../../../formula-editor/hooks/use-formula-search';
+import { useStateRef } from '../../../formula-editor/hooks/use-state-ref';
+
+interface IMobileSearchFunctionProps {
+ isFocus: boolean;
+ sequenceNodes: (string | ISequenceNode)[];
+ onSelect: (data: {
+ text: string;
+ offset: number;
+ }) => void;
+ onChange?: (functionName: string) => void;
+ editor: Editor;
+ onClose?: () => void;
+};
+export const MobileSearchFunction = forwardRef<HTMLElement, IMobileSearchFunctionProps>(MobileSearchFunctionFactory);
+function MobileSearchFunctionFactory(props: IMobileSearchFunctionProps, ref: any) {
+ const { isFocus, sequenceNodes, onSelect, editor, onClose = noop } = props;
+ const editorId = editor.getEditorId();
+ const shortcutService = useDependency(IShortcutService);
+ const commandService = useDependency(ICommandService);
+ const { searchList, searchText, handlerFormulaReplace, reset: resetFormulaSearch } = useFormulaSearch(isFocus, sequenceNodes, editor);
+ const visible = searchList.length > 0;
+ const ulRef = useRef<HTMLUListElement>(undefined);
+ const [active, setActive] = useState(0);
+ const isEnableMouseEnterOrOut = useRef(false);
+ const [position$] = useEditorPosition(editorId, visible, [searchText, searchList]);
+ const stateRef = useStateRef({ searchList, active });
+
+ const handleFunctionSelect = (v: string, functionType: FunctionType) => {
+ const res = handlerFormulaReplace(v, functionType);
+ if (res) {
+ resetFormulaSearch();
+ onSelect(res);
+ }
+ };
+
+ function handleLiMouseEnter(index: number) {
+ if (!isEnableMouseEnterOrOut.current) {
+ return;
+ }
+ setActive(index);
+ }
+
+ function handleLiMouseLeave() {
+ if (!isEnableMouseEnterOrOut.current) {
+ return;
+ }
+ setActive(-1);
+ }
+
+ useEffect(() => {
+ if (!searchList.length) {
+ return;
+ }
+ // Register arrow key events
+ const operationId = `sheet.formula-embedding-editor.search_function.${editorId}`;
+ const d = new DisposableCollection();
+ const handleKeycode = (keycode: KeyCode) => {
+ const { searchList, active } = stateRef.current;
+
+ switch (keycode) {
+ case KeyCode.ARROW_UP: {
+ setActive((pre) => {
+ const res = Math.max(0, pre - 1);
+ scrollToVisible(res);
+ return res;
+ });
+
+ break;
+ }
+ case KeyCode.ARROW_DOWN: {
+ setActive((pre) => {
+ const res = Math.min(searchList.length - 1, pre + 1);
+ scrollToVisible(res);
+ return res;
+ });
+ break;
+ }
+ case KeyCode.TAB:
+ case KeyCode.ENTER: {
+ const item = searchList[active];
+ handleFunctionSelect(item.name, item.functionType);
+ break;
+ }
+ case KeyCode.ESC: {
+ resetFormulaSearch();
+ onClose();
+ break;
+ }
+ }
+ };
+ d.add(commandService.registerCommand({
+ id: operationId,
+ type: CommandType.OPERATION,
+ handler(_event, params) {
+ const { keyCode } = params as { eventType: DeviceInputEventType; keyCode: KeyCode };
+ handleKeycode(keyCode);
+ },
+ }));
+
+ [KeyCode.ARROW_UP, KeyCode.ARROW_DOWN, KeyCode.ENTER, KeyCode.ESC, KeyCode.TAB].map((keyCode) => {
+ return {
+ id: operationId,
+ binding: keyCode,
+ preconditions: () => true,
+ priority: 1000,
+ staticParameters: {
+ eventType: DeviceInputEventType.Keyboard,
+ keyCode,
+ },
+ };
+ }).forEach((item) => {
+ d.add(shortcutService.registerShortcut(item));
+ });
+
+ return () => {
+ d.dispose();
+ };
+ }, [searchList]);
+
+ function scrollToVisible(liIndex: number) {
+ // Get the <li> element directly from children
+ const ulElement = ulRef.current;
+ if (!ulElement) return;
+
+ const liElement = ulElement.children[liIndex] as HTMLLIElement;
+ if (!liElement) return;
+
+ // Get the height of the <ul> element
+ const ulRect = ulElement.getBoundingClientRect();
+ const ulTop = ulRect.top;
+ const ulHeight = ulElement.offsetHeight;
+
+ // Get the position and height of the <li> element
+ const liRect = liElement.getBoundingClientRect();
+ const liTop = liRect.top;
+ const liHeight = liRect.height;
+
+ // If the <li> element is within the visible area, no scrolling operation is performed
+ if (liTop >= 0 && liTop > ulTop && liTop - ulTop + liHeight <= ulHeight) {
+ return;
+ }
+
+ // Calculate scroll position
+ const scrollTo = liElement.offsetTop - (ulHeight - liHeight) / 2;
+
+ // Perform scrolling operation
+ ulElement.scrollTo({
+ top: scrollTo,
+ behavior: 'smooth',
+ });
+ }
+
+ const debounceResetMouseState = useMemo(() => {
+ let time = '' as any;
+ return () => {
+ clearTimeout(time);
+ isEnableMouseEnterOrOut.current = true;
+ time = setTimeout(() => {
+ isEnableMouseEnterOrOut.current = false;
+ }, 300);
+ };
+ }, []);
+
+ return searchList.length > 0 && visible && (
+ <RectPopup portal anchorRect$={position$} direction="vertical">
+ <ul
+ ref={(v) => {
+ ulRef.current = v!;
+ if (ref) {
+ ref.current = v!;
+ }
+ }}
+ data-u-comp="sheets-formula-editor"
+ data-presentation="mobile"
+ className={clsx(`
+ univer-m-0 univer-box-border univer-list-none univer-overflow-y-auto univer-rounded-lg
+ univer-bg-gray-0 univer-p-2 univer-leading-5 univer-shadow-md univer-outline-none
+ dark:!univer-bg-gray-900
+ `, 'univer-max-h-[38vh] univer-w-[calc(100vw-16px)]', borderClassName, scrollbarClassName)}
+ >
+ {searchList.map((item, index) => (
+ <li
+ key={item.name}
+ className={clsx(`
+ univer-box-border univer-cursor-pointer univer-rounded univer-px-2 univer-py-1
+ univer-text-gray-900 univer-transition-colors
+ dark:!univer-text-gray-0
+ `, 'univer-flex univer-min-h-12 univer-flex-col univer-justify-center univer-px-3 univer-py-2', {
+ 'univer-bg-gray-200 dark:!univer-bg-gray-600': active === index,
+ })}
+ onMouseEnter={() => handleLiMouseEnter(index)}
+ onMouseLeave={handleLiMouseLeave}
+ onMouseMove={debounceResetMouseState}
+ onClick={() => {
+ handleFunctionSelect(item.name, item.functionType);
+ if (editor) {
+ editor.focus();
+ }
+ }}
+ >
+ <span className="univer-block univer-truncate univer-text-xs">
+ <span className="univer-text-red-500">{item.name.substring(0, searchText.length)}</span>
+ <span>{item.name.slice(searchText.length)}</span>
+ </span>
+ <span
+ className="univer-block univer-text-xs univer-text-gray-400"
+ >
+ {item.desc}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </RectPopup>
+ );
+}
diff --git a/packages/sheets-formula-ui/src/views/mobile/more-functions/MobileMoreFunctions.tsx b/packages/sheets-formula-ui/src/views/mobile/more-functions/MobileMoreFunctions.tsx
new file mode 100644
index 0000000000..a26677e97a
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/mobile/more-functions/MobileMoreFunctions.tsx
@@ -0,0 +1,22 @@
+/**
+ * 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 { MoreFunctions } from '../../more-functions/MoreFunctions';
+import { MobileSelectFunction } from './MobileSelectFunction';
+
+export function MobileMoreFunctions() {
+ return <MoreFunctions SelectFunctionComponent={MobileSelectFunction} />;
+}
diff --git a/packages/sheets-formula-ui/src/views/mobile/more-functions/MobileSelectFunction.tsx b/packages/sheets-formula-ui/src/views/mobile/more-functions/MobileSelectFunction.tsx
new file mode 100644
index 0000000000..8400d2764a
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/mobile/more-functions/MobileSelectFunction.tsx
@@ -0,0 +1,23 @@
+/**
+ * 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 { ISelectFunctionProps } from '../../more-functions/select-function/SelectFunction';
+import { MobileSelect } from '@univerjs/design';
+import { SelectFunction } from '../../more-functions/select-function/SelectFunction';
+
+export function MobileSelectFunction(props: ISelectFunctionProps) {
+ return <SelectFunction {...props} SelectComponent={MobileSelect} />;
+}
diff --git a/packages/sheets-formula-ui/src/views/more-functions/MoreFunctions.tsx b/packages/sheets-formula-ui/src/views/more-functions/MoreFunctions.tsx
index c251a1ff22..e342fba7e5 100644
--- a/packages/sheets-formula-ui/src/views/more-functions/MoreFunctions.tsx
+++ b/packages/sheets-formula-ui/src/views/more-functions/MoreFunctions.tsx
@@ -33,7 +33,11 @@ import { useState } from 'react';
import { InputParams } from './input-params/InputParams';
import { SelectFunction } from './select-function/SelectFunction';
-export function MoreFunctions() {
+export interface IMoreFunctionsProps {
+ SelectFunctionComponent?: typeof SelectFunction;
+}
+
+export function MoreFunctions({ SelectFunctionComponent = SelectFunction }: IMoreFunctionsProps = {}) {
const workbook = useActiveWorkbook();
const [selectFunction, setSelectFunction] = useState<boolean>(true);
const [inputParams, setInputParams] = useState<boolean>(false);
@@ -74,7 +78,7 @@ export function MoreFunctions() {
data-u-comp="sheets-formula-functions-panel"
className="univer-box-border univer-flex univer-h-full univer-flex-col univer-justify-between univer-py-2"
>
- {selectFunction && <SelectFunction onChange={setFunctionInfo} />}
+ {selectFunction && <SelectFunctionComponent onChange={setFunctionInfo} />}
{inputParams && <InputParams functionInfo={functionInfo} onChange={() => {}} />}
<div className="univer-flex univer-justify-end">
{/* TODO@Dushusir: open input params after range selector refactor */}
diff --git a/packages/sheets-formula-ui/src/views/more-functions/select-function/SelectFunction.tsx b/packages/sheets-formula-ui/src/views/more-functions/select-function/SelectFunction.tsx
index 95d9312a77..77bbba20b3 100644
--- a/packages/sheets-formula-ui/src/views/more-functions/select-function/SelectFunction.tsx
+++ b/packages/sheets-formula-ui/src/views/more-functions/select-function/SelectFunction.tsx
@@ -31,13 +31,14 @@ import { FunctionHelp } from '../function-help/FunctionHelp';
export interface ISelectFunctionProps {
onChange: (functionInfo: IFunctionInfo | null) => void;
+ SelectComponent?: typeof Select;
}
export function SelectFunction(props: ISelectFunctionProps) {
const configService = useDependency(IConfigService);
const customFunction = configService.getConfig<IUniverSheetsFormulaBaseConfig>(PLUGIN_CONFIG_KEY_BASE)?.function;
- const { onChange } = props;
+ const { onChange, SelectComponent = Select } = props;
const allTypeValue = '-1';
const [searchText, setSearchText] = useState<string>('');
@@ -159,7 +160,7 @@ export function SelectFunction(props: ISelectFunctionProps) {
return (
<div>
<div className="univer-flex univer-items-center univer-justify-between univer-gap-2">
- <Select value={typeSelected} options={options} onChange={handleSelectChange} />
+ <SelectComponent value={typeSelected} options={options} onChange={handleSelectChange} />
<Input
placeholder={localeService.t<LocaleKey>('sheets-formula-ui.moreFunctions.searchFunctionPlaceholder')}
diff --git a/packages/sheets-formula-ui/src/views/range-selector/MobileGlobal.tsx b/packages/sheets-formula-ui/src/views/range-selector/MobileGlobal.tsx
new file mode 100644
index 0000000000..00bc73533a
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/range-selector/MobileGlobal.tsx
@@ -0,0 +1,53 @@
+/**
+ * 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 { IRangeSelectorInstance } from './index';
+import { deserializeRangeWithSheet } from '@univerjs/engine-formula';
+import { useDependency, useObservable } from '@univerjs/ui';
+import { useEffect, useRef } from 'react';
+import { GlobalRangeSelectorService } from '../../services/range-selector.service';
+import { MobileRangeSelector } from './MobileRangeSelector';
+
+export function MobileGlobalRangeSelector() {
+ const rangeSelectorService = useDependency(GlobalRangeSelectorService);
+ const current = useObservable(rangeSelectorService.currentSelector$);
+ const instanceRef = useRef<IRangeSelectorInstance | null>(null);
+
+ useEffect(() => {
+ if (current) {
+ const instance = instanceRef.current;
+ instance?.showDialog(current.initialValue ?? []);
+
+ return () => {
+ instance?.hideDialog();
+ };
+ }
+ }, [current]);
+
+ return (
+ <MobileRangeSelector
+ unitId={current?.unitId ?? ''}
+ subUnitId={current?.subUnitId ?? ''}
+ maxRangeCount={current?.maxRangeCount}
+ hideEditor
+ selectorRef={instanceRef}
+ onClose={() => current?.callback([])}
+ onChange={(_, value) => {
+ current?.callback(value?.split(',').map((item) => deserializeRangeWithSheet(item)) ?? []);
+ }}
+ />
+ );
+}
diff --git a/packages/sheets-formula-ui/src/views/range-selector/MobileRangeSelector.tsx b/packages/sheets-formula-ui/src/views/range-selector/MobileRangeSelector.tsx
new file mode 100644
index 0000000000..359c750dfe
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/range-selector/MobileRangeSelector.tsx
@@ -0,0 +1,188 @@
+/**
+ * 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 { IUnitRangeName } from '@univerjs/core';
+import type { Editor } from '@univerjs/docs-ui';
+import type { ISetSelectionsOperationParams } from '@univerjs/sheets';
+import type { LocaleKey } from '../../locale/types';
+import type { IRangeSelectorProps } from './index';
+import { ICommandService, LocaleService, RichTextBuilder } from '@univerjs/core';
+import { clsx } from '@univerjs/design';
+import { IEditorService, RichTextEditor } from '@univerjs/docs-ui';
+import { SelectRangeIcon } from '@univerjs/icons';
+import { SetSelectionsOperation } from '@univerjs/sheets';
+import { useDependency, useEvent } from '@univerjs/ui';
+import { useEffect, useState } from 'react';
+import { useStateRef } from '../formula-editor/hooks/use-state-ref';
+import { useRangesHighlight } from './hooks/use-ranges-highlight';
+import { parseRanges, stringifyRanges } from './index';
+import { MobileRangeSelectorDialog } from './MobileRangeSelectorDialog';
+import { verifyRange } from './utils/verify-range';
+
+export function MobileRangeSelector(props: IRangeSelectorProps) {
+ const [editor, setEditor] = useState<Editor | null>(null);
+ const {
+ onVerify,
+ selectorRef,
+ unitId,
+ subUnitId,
+ maxRangeCount,
+ supportAcrossSheet,
+ keepSheetReference,
+ autoFocus,
+ onChange,
+ onRangeSelectorDialogVisibleChange,
+ onClickOutside,
+ onFocusChange,
+ forceShowDialogWhenSelectionChanged,
+ hideEditor,
+ resetRange,
+ onClose,
+ } = props;
+ const [focusing, setFocusing] = useState(autoFocus ?? false);
+ const [popupVisible, setPopupVisible] = useState(false);
+ const [rangeSelectorRanges, setRangeSelectorRanges] = useState<IUnitRangeName[]>([]);
+ const localeService = useDependency(LocaleService);
+ const editorService = useDependency(IEditorService);
+ const commandService = useDependency(ICommandService);
+ const { sequenceNodes } = useRangesHighlight(editor, focusing, unitId, subUnitId);
+ const sequenceNodesRef = useStateRef(sequenceNodes);
+ const blurEditor = useEvent(() => {
+ editor?.setSelectionRanges([]);
+ editor?.blur();
+ editorService.blur();
+ });
+ const openDialog = useEvent(() => {
+ blurEditor();
+ setRangeSelectorRanges(parseRanges(editor?.getDocumentDataModel()?.getPlainText() ?? ''));
+ setPopupVisible(true);
+ });
+
+ useEffect(() => {
+ if (!selectorRef) {
+ return;
+ }
+
+ selectorRef.current = {
+ get editor() {
+ return editor;
+ },
+ focus() {
+ editorService.focus(editor!.getEditorId());
+ },
+ blur: blurEditor,
+ verify: () => verifyRange(sequenceNodesRef.current),
+ showDialog: (ranges) => {
+ blurEditor();
+ setRangeSelectorRanges(ranges);
+ setPopupVisible(true);
+ },
+ hideDialog: () => {
+ setRangeSelectorRanges([]);
+ setPopupVisible(false);
+ },
+ getValue: () => editor?.getDocumentDataModel()?.getPlainText() ?? '',
+ };
+ }, [blurEditor, editor, editorService, selectorRef, sequenceNodesRef]);
+
+ useEffect(() => {
+ onVerify?.(verifyRange(sequenceNodes), editor?.getDocumentDataModel()?.getPlainText() ?? '');
+ }, [editor, onVerify, sequenceNodes]);
+
+ useEffect(() => {
+ onRangeSelectorDialogVisibleChange?.(popupVisible);
+ }, [onRangeSelectorDialogVisibleChange, popupVisible]);
+
+ useEffect(() => {
+ if (popupVisible && resetRange) {
+ return () => {
+ const params: ISetSelectionsOperationParams = {
+ unitId,
+ subUnitId,
+ selections: resetRange,
+ };
+ commandService.executeCommand(SetSelectionsOperation.id, params);
+ };
+ }
+ }, [commandService, popupVisible, resetRange, subUnitId, unitId]);
+
+ return (
+ <>
+ {!hideEditor && (
+ <RichTextEditor
+ isSingle
+ {...props}
+ className={clsx(props.className, 'rtl:[&>div]:univer-flex-row-reverse')}
+ preserveHostFocus
+ onFocusChange={(isFocusing, newValue) => {
+ setFocusing(isFocusing);
+ onFocusChange?.(isFocusing, newValue);
+ }}
+ editorRef={setEditor}
+ onClickOutside={() => {
+ setFocusing(false);
+ blurEditor();
+ onClickOutside?.();
+ }}
+ icon={(
+ <SelectRangeIcon
+ aria-label={localeService.t<LocaleKey>('sheets-formula-ui.rangeSelector.buttonTooltip')}
+ className="
+ -univer-translate-y-0.5 univer-cursor-pointer
+ dark:!univer-text-gray-300
+ "
+ onClick={openDialog}
+ />
+ )}
+ />
+ )}
+ <MobileRangeSelectorDialog
+ initialValue={rangeSelectorRanges}
+ unitId={unitId}
+ subUnitId={subUnitId}
+ visible={popupVisible}
+ maxRangeCount={maxRangeCount}
+ onConfirm={(ranges) => {
+ const resultStr = stringifyRanges(ranges);
+ const documentData = RichTextBuilder.create().insertText(resultStr).getData();
+ editor?.replaceText(resultStr, false);
+ onChange?.(documentData, resultStr);
+ setPopupVisible(false);
+ setRangeSelectorRanges([]);
+ requestAnimationFrame(() => {
+ blurEditor();
+ });
+ }}
+ onClose={() => {
+ setPopupVisible(false);
+ setRangeSelectorRanges([]);
+ onClose?.();
+ }}
+ supportAcrossSheet={supportAcrossSheet}
+ keepSheetReference={keepSheetReference}
+ onShowBySelection={(ranges) => {
+ if (focusing || forceShowDialogWhenSelectionChanged) {
+ setRangeSelectorRanges(ranges);
+ setPopupVisible(true);
+ return false;
+ }
+
+ return true;
+ }}
+ />
+ </>
+ );
+}
diff --git a/packages/sheets-formula-ui/src/views/range-selector/MobileRangeSelectorDialog.tsx b/packages/sheets-formula-ui/src/views/range-selector/MobileRangeSelectorDialog.tsx
index a8f855e019..39dcc8852c 100644
--- a/packages/sheets-formula-ui/src/views/range-selector/MobileRangeSelectorDialog.tsx
+++ b/packages/sheets-formula-ui/src/views/range-selector/MobileRangeSelectorDialog.tsx
@@ -15,47 +15,173 @@
*/
import type { MobileDrawerSnap } from '@univerjs/ui';
-import type { ReactNode } from 'react';
-import { ActionRow, Button } from '@univerjs/design';
-import { MobileDrawer } from '@univerjs/ui';
+import type { LocaleKey } from '../../locale/types';
+import type { IRangeSelectorDialogProps } from './index';
+import { LocaleService } from '@univerjs/core';
+import { Button, clsx, ConfigContext, Input, MobileActionRowGroup, scrollbarClassName } from '@univerjs/design';
+import {
+ deserializeRangeWithSheet,
+ LexerTreeBuilder,
+ sequenceNodeType,
+ serializeRange,
+ serializeRangeWithSheet,
+} from '@univerjs/engine-formula';
+import { DeleteIcon, IncreaseIcon } from '@univerjs/icons';
+import { MobileDrawer, useDependency } from '@univerjs/ui';
+import { useContext, useEffect, useRef, useState } from 'react';
+import { createPortal } from 'react-dom';
+import { useRangeSelectorSelectionChange } from './hooks/use-selection-change';
+import { rangePreProcess } from './utils/range-pre-process';
-interface IMobileRangeSelectorDialogProps {
- visible: boolean;
- snap: MobileDrawerSnap;
- title: string;
- cancelText: string;
- confirmText: string;
- children: ReactNode;
- onSnapChange: (snap: MobileDrawerSnap) => void;
- onClose: () => void;
- onConfirm: () => void;
-}
-
-export function MobileRangeSelectorDialog(props: IMobileRangeSelectorDialogProps) {
+export function MobileRangeSelectorDialog(props: IRangeSelectorDialogProps) {
const {
visible,
- snap,
- title,
- cancelText,
- confirmText,
- children,
- onSnapChange,
- onClose,
+ initialValue,
+ unitId,
+ subUnitId,
+ maxRangeCount = Infinity,
+ supportAcrossSheet,
+ keepSheetReference,
onConfirm,
+ onClose,
+ onShowBySelection,
} = props;
+ const localeService = useDependency(LocaleService);
+ const lexerTreeBuilder = useDependency(LexerTreeBuilder);
+ const [ranges, setRanges] = useState<string[]>([]);
+ const [focusIndex, setFocusIndex] = useState(0);
+ const [drawerSnap, setDrawerSnap] = useState<MobileDrawerSnap>('compact');
+ const layerRef = useRef<HTMLDivElement>(null);
+ const scrollbarRef = useRef<HTMLDivElement>(null);
+ const maxHeight = globalThis.CSS?.supports('height', '1dvh') ? '22dvh' : '22vh';
+ const { direction, mountContainer } = useContext(ConfigContext);
+
+ useEffect(() => {
+ if (visible && initialValue.length) {
+ const newRanges = initialValue.map((range) => range.sheetName
+ ? serializeRangeWithSheet(range.sheetName, range.range)
+ : serializeRange(range.range));
+ setRanges(newRanges);
+ setFocusIndex(newRanges.length - 1);
+ } else {
+ setRanges(['']);
+ setFocusIndex(0);
+ }
+ }, [initialValue, visible]);
+
+ useRangeSelectorSelectionChange({
+ unitId,
+ subUnitId,
+ supportAcrossSheet,
+ keepSheetReference,
+ onChange: (selections, isStart) => {
+ if (!visible && onShowBySelection?.(selections)) {
+ return;
+ }
- if (!visible) {
+ const current = new Set(ranges);
+ const selectionRanges = selections.map((range) => range.sheetName
+ ? serializeRangeWithSheet(range.sheetName, range.range)
+ : serializeRange(range.range));
+ const addedRanges = selectionRanges.filter((item) => !current.has(item));
+ if (!addedRanges.length) {
+ return;
+ }
+
+ const newRanges = [...ranges];
+ if (selectionRanges.length > 1) {
+ if (!isStart) {
+ newRanges.splice(focusIndex, 1);
+ }
+ newRanges.push(...addedRanges);
+ const finalRanges = newRanges.slice(0, maxRangeCount);
+ setRanges(finalRanges);
+ setFocusIndex(finalRanges.length - 1);
+ requestAnimationFrame(() => {
+ scrollbarRef.current?.scrollTo({ top: scrollbarRef.current.scrollHeight });
+ });
+ } else {
+ newRanges.splice(focusIndex, 1, ...addedRanges);
+ const finalRanges = newRanges.slice(0, maxRangeCount);
+ setRanges(finalRanges);
+ setFocusIndex(focusIndex + addedRanges.length - 1);
+ }
+ },
+ });
+
+ if (!visible || !mountContainer) {
return null;
}
- return (
- <div className="univer-pointer-events-none univer-visible univer-fixed univer-inset-0 univer-z-[1300]">
+ function confirmRanges() {
+ onConfirm(
+ ranges
+ .filter((text) => {
+ const nodes = lexerTreeBuilder.sequenceNodesBuilder(text);
+ return nodes && nodes.length === 1 && typeof nodes[0] !== 'string' && nodes[0].nodeType === sequenceNodeType.REFERENCE;
+ })
+ .map((text) => deserializeRangeWithSheet(text))
+ .map((unitRange) => ({ ...unitRange, range: rangePreProcess(unitRange.range) }))
+ );
+ }
+
+ function handleRangeInput(index: number, value: string) {
+ const newRanges = [...ranges];
+ newRanges[index] = value;
+ setRanges(newRanges);
+ }
+
+ function handleRangeRemove(index: number) {
+ setRanges(ranges.filter((_, rangeIndex) => rangeIndex !== index));
+ }
+
+ function renderRangeInput(text: string, index: number) {
+ return (
+ <div key={index} className="univer-mb-2 univer-flex univer-items-center univer-gap-2">
+ <Input
+ className={clsx('univer-box-border univer-h-10 univer-w-full', {
+ 'univer-border-primary-600': focusIndex === index,
+ })}
+ placeholder={localeService.t<LocaleKey>('sheets-formula-ui.rangeSelector.placeHolder')}
+ onFocus={() => setFocusIndex(index)}
+ value={text}
+ onChange={(value) => handleRangeInput(index, value)}
+ />
+ {ranges.length > 1 && (
+ <button
+ type="button"
+ className="
+ univer-flex univer-size-10 univer-shrink-0 univer-items-center univer-justify-center
+ univer-rounded-lg univer-border-0 univer-bg-transparent univer-text-gray-600
+ active:univer-bg-gray-100
+ dark:!univer-text-gray-300
+ dark:active:!univer-bg-gray-700
+ "
+ onClick={() => handleRangeRemove(index)}
+ >
+ <DeleteIcon className="univer-cursor-pointer" />
+ </button>
+ )}
+ </div>
+ );
+ }
+
+ const title = localeService.t<LocaleKey>('sheets-formula-ui.rangeSelector.title');
+
+ return createPortal(
+ <div
+ ref={layerRef}
+ dir={direction}
+ className="univer-pointer-events-none univer-visible univer-fixed univer-inset-0 univer-z-[1300]"
+ >
<MobileDrawer
+ layerRef={layerRef}
componentName="mobile-range-selector-drawer"
- snap={snap}
+ openMode="push"
+ snap={drawerSnap}
expandLabel={title}
collapseLabel={title}
- onSnapChange={onSnapChange}
+ onSnapChange={setDrawerSnap}
onClose={onClose}
role="dialog"
ariaLabel={title}
@@ -76,15 +202,39 @@ export function MobileRangeSelectorDialog(props: IMobileRangeSelectorDialogProps
)}
footer={(
<footer className="univer-box-border univer-shrink-0 univer-p-4">
- <ActionRow>
- <Button onClick={onClose}>{cancelText}</Button>
- <Button variant="primary" onClick={onConfirm}>{confirmText}</Button>
- </ActionRow>
+ <MobileActionRowGroup>
+ <Button onClick={onClose}>
+ {localeService.t<LocaleKey>('sheets-formula-ui.rangeSelector.cancel')}
+ </Button>
+ <Button variant="primary" onClick={confirmRanges}>
+ {localeService.t<LocaleKey>('sheets-formula-ui.rangeSelector.confirm')}
+ </Button>
+ </MobileActionRowGroup>
</footer>
)}
>
- {children}
+ <div
+ ref={scrollbarRef}
+ className={clsx('univer-overflow-y-auto', scrollbarClassName)}
+ style={{ maxHeight }}
+ >
+ {ranges.map(renderRangeInput)}
+ {ranges.length < maxRangeCount && (
+ <Button
+ className="univer-h-10 univer-w-full"
+ variant="link"
+ onClick={() => {
+ setRanges([...ranges, '']);
+ setFocusIndex(ranges.length);
+ }}
+ >
+ <IncreaseIcon />
+ <span>{localeService.t<LocaleKey>('sheets-formula-ui.rangeSelector.addAnotherRange')}</span>
+ </Button>
+ )}
+ </div>
</MobileDrawer>
- </div>
+ </div>,
+ mountContainer
);
}
diff --git a/packages/sheets-formula-ui/src/views/range-selector/__tests__/GlobalRangeSelector.spec.tsx b/packages/sheets-formula-ui/src/views/range-selector/__tests__/GlobalRangeSelector.spec.tsx
index 9c01dff04d..2fca8fbcab 100644
--- a/packages/sheets-formula-ui/src/views/range-selector/__tests__/GlobalRangeSelector.spec.tsx
+++ b/packages/sheets-formula-ui/src/views/range-selector/__tests__/GlobalRangeSelector.spec.tsx
@@ -40,6 +40,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { GlobalRangeSelectorService } from '../../../services/range-selector.service';
import { GlobalRangeSelector } from '../Global';
import { RangeSelector } from '../index';
+import { MobileGlobalRangeSelector } from '../MobileGlobal';
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -315,6 +316,30 @@ describe('GlobalRangeSelector', () => {
expect(document.body.textContent).not.toContain('Add range');
});
+ it('opens the mobile global selector with the mobile range surface', async () => {
+ const { injector, service } = createGlobalRangeSelectorTestBed();
+
+ await act(async () => {
+ root.render(
+ <RediContext.Provider value={{ injector }}>
+ <MobileGlobalRangeSelector />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ await act(async () => {
+ service.showRangeSelectorDialog({
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ callback: vi.fn(),
+ });
+ await Promise.resolve();
+ });
+
+ expect(document.body.querySelector('[data-u-comp="mobile-range-selector-drawer"]')).toBeTruthy();
+ });
+
it('calls the callback with an empty range when the global selector dialog is cancelled', async () => {
const { injector, service } = createGlobalRangeSelectorTestBed();
const callback = vi.fn();
diff --git a/packages/sheets-formula-ui/src/views/range-selector/__tests__/RangeSelectorDialog.spec.tsx b/packages/sheets-formula-ui/src/views/range-selector/__tests__/RangeSelectorDialog.spec.tsx
index 196ab3553e..c1a0b90416 100644
--- a/packages/sheets-formula-ui/src/views/range-selector/__tests__/RangeSelectorDialog.spec.tsx
+++ b/packages/sheets-formula-ui/src/views/range-selector/__tests__/RangeSelectorDialog.spec.tsx
@@ -31,8 +31,9 @@ import { RediContext } from '@univerjs/ui';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { Subject } from 'rxjs';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { RangeSelectorDialog } from '../index';
+import { MobileRangeSelectorDialog } from '../MobileRangeSelectorDialog';
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -165,6 +166,7 @@ describe('RangeSelectorDialog', () => {
root.unmount();
});
container.remove();
+ vi.unstubAllGlobals();
});
it('confirms only valid range inputs and normalizes reversed coordinates', async () => {
@@ -479,13 +481,13 @@ describe('RangeSelectorDialog', () => {
});
it('renders a compact mobile range picker and keeps the canvas area unmasked', async () => {
+ vi.stubGlobal('CSS', { supports: () => false });
const injector = createRangeDialogTestBed();
act(() => {
root.render(
<RediContext.Provider value={{ injector }}>
- <RangeSelectorDialog
+ <MobileRangeSelectorDialog
visible
- mobile
initialValue={[{
unitId: 'book-1',
sheetName: 'Sheet1',
@@ -512,6 +514,8 @@ describe('RangeSelectorDialog', () => {
const dialog = document.body.querySelector('[role="dialog"]');
const picker = dialog?.parentElement;
expect(picker).toBeTruthy();
+ expect(container.querySelector('[role="dialog"]')).toBeNull();
+ expect(picker?.parentElement).toBe(document.body);
expect(picker?.className).toContain('univer-pointer-events-none');
expect(dialog?.className).toContain('univer-pointer-events-auto');
const input = picker?.querySelector('input');
@@ -520,6 +524,7 @@ describe('RangeSelectorDialog', () => {
throw new TypeError('Mobile range selector input was not rendered.');
}
expect(input.value).toBe('Sheet1!A1:B2');
+ expect(input.parentElement?.parentElement?.parentElement?.getAttribute('style')).toContain('max-height: 22vh');
await emitSelection(injector, {
startRow: 3,
diff --git a/packages/sheets-formula-ui/src/views/range-selector/index.tsx b/packages/sheets-formula-ui/src/views/range-selector/index.tsx
index be7a5d15ef..e8401dd27c 100644
--- a/packages/sheets-formula-ui/src/views/range-selector/index.tsx
+++ b/packages/sheets-formula-ui/src/views/range-selector/index.tsx
@@ -17,11 +17,10 @@
import type { IUnitRangeName, Nullable } from '@univerjs/core';
import type { Editor, IRichTextEditorProps } from '@univerjs/docs-ui';
import type { ISelectionWithStyle, ISetSelectionsOperationParams } from '@univerjs/sheets';
-import type { MobileDrawerSnap } from '@univerjs/ui';
import type { RefObject } from 'react';
import type { LocaleKey } from '../../locale/types';
import { ICommandService, LocaleService, RichTextBuilder } from '@univerjs/core';
-import { Button, clsx, ConfigContext, Dialog, Input, scrollbarClassName, Tooltip } from '@univerjs/design';
+import { Button, clsx, Dialog, Input, scrollbarClassName, Tooltip } from '@univerjs/design';
import { IEditorService, RichTextEditor } from '@univerjs/docs-ui';
import {
deserializeRangeWithSheet,
@@ -34,11 +33,10 @@ import {
import { DeleteIcon, IncreaseIcon, SelectRangeIcon } from '@univerjs/icons';
import { SetSelectionsOperation } from '@univerjs/sheets';
import { useDependency, useEvent } from '@univerjs/ui';
-import { useContext, useEffect, useRef, useState } from 'react';
+import { useEffect, useRef, useState } from 'react';
import { useStateRef } from '../formula-editor/hooks/use-state-ref';
import { useRangesHighlight } from './hooks/use-ranges-highlight';
import { useRangeSelectorSelectionChange } from './hooks/use-selection-change';
-import { MobileRangeSelectorDialog } from './MobileRangeSelectorDialog';
import { rangePreProcess } from './utils/range-pre-process';
import { verifyRange } from './utils/verify-range';
@@ -81,7 +79,6 @@ export interface IRangeSelectorDialogProps {
onConfirm: (ranges: IUnitRangeName[]) => void;
onClose: () => void;
onShowBySelection?: (ranges: IUnitRangeName[]) => boolean;
- mobile?: boolean;
}
export function RangeSelectorDialog(props: IRangeSelectorDialogProps) {
@@ -96,13 +93,11 @@ export function RangeSelectorDialog(props: IRangeSelectorDialogProps) {
onConfirm,
onClose,
onShowBySelection,
- mobile = false,
} = props;
const localeService = useDependency(LocaleService);
const lexerTreeBuilder = useDependency(LexerTreeBuilder);
const [ranges, setRanges] = useState<string[]>([]);
const [focusIndex, setFocusIndex] = useState(0);
- const [drawerSnap, setDrawerSnap] = useState<MobileDrawerSnap>('compact');
const scrollbarRef = useRef<HTMLDivElement>(null);
useEffect(() => {
@@ -145,7 +140,9 @@ export function RangeSelectorDialog(props: IRangeSelectorDialogProps) {
const current = new Set(ranges);
const addedRangesOrigin = selections.map((range) => !range.sheetName ? serializeRange(range.range) : serializeRangeWithSheet(range.sheetName, range.range));
const addedRanges = addedRangesOrigin.filter((item) => !current.has(item));
- if (!addedRanges.length) return;
+ if (!addedRanges.length) {
+ return;
+ }
const newRanges = [...ranges];
if (addedRangesOrigin.length > 1) {
@@ -182,21 +179,15 @@ export function RangeSelectorDialog(props: IRangeSelectorDialogProps) {
);
};
- const rangeInputs = (mobileLayout = false) => (
+ const rangeInputs = () => (
<div
ref={scrollbarRef}
- className={clsx(
- 'univer-overflow-y-auto',
- scrollbarClassName,
- mobileLayout ? 'univer-max-h-[22dvh]' : '-univer-mx-6 univer-max-h-60 univer-px-6'
- )}
+ className={clsx('-univer-mx-6 univer-max-h-60 univer-overflow-y-auto univer-px-6', scrollbarClassName)}
>
{ranges.map((text, index) => (
<div
key={index}
- className={clsx('univer-mb-2 univer-flex univer-items-center', mobileLayout
- ? 'univer-gap-2'
- : 'univer-gap-4')}
+ className="univer-mb-2 univer-flex univer-items-center univer-gap-4"
>
<Input
className={clsx('univer-box-border univer-h-10 univer-w-full', {
@@ -225,7 +216,7 @@ export function RangeSelectorDialog(props: IRangeSelectorDialogProps) {
</div>
))}
{ranges.length < maxRangeCount && (
- <Button className={mobileLayout ? 'univer-h-10 univer-w-full' : undefined} variant="link" onClick={handleRangeAdd}>
+ <Button variant="link" onClick={handleRangeAdd}>
<IncreaseIcon />
<span>{localeService.t<LocaleKey>('sheets-formula-ui.rangeSelector.addAnotherRange')}</span>
</Button>
@@ -233,23 +224,6 @@ export function RangeSelectorDialog(props: IRangeSelectorDialogProps) {
</div>
);
- if (mobile) {
- return (
- <MobileRangeSelectorDialog
- visible={visible}
- snap={drawerSnap}
- title={localeService.t<LocaleKey>('sheets-formula-ui.rangeSelector.title')}
- cancelText={localeService.t<LocaleKey>('sheets-formula-ui.rangeSelector.cancel')}
- confirmText={localeService.t<LocaleKey>('sheets-formula-ui.rangeSelector.confirm')}
- onSnapChange={setDrawerSnap}
- onClose={onClose}
- onConfirm={confirmRanges}
- >
- {rangeInputs(true)}
- </MobileRangeSelectorDialog>
- );
- }
-
return (
<Dialog
width="328px"
@@ -288,7 +262,6 @@ export function stringifyRanges(ranges: IUnitRangeName[]) {
export function RangeSelector(props: IRangeSelectorProps) {
const [editor, setEditor] = useState<Editor | null>(null);
- const { mobile = false } = useContext(ConfigContext);
const {
onVerify,
selectorRef,
@@ -329,7 +302,9 @@ export function RangeSelector(props: IRangeSelectorProps) {
});
useEffect(() => {
- if (!selectorRef) return;
+ if (!selectorRef) {
+ return;
+ }
selectorRef.current = {
get editor() {
return editor;
@@ -411,7 +386,6 @@ export function RangeSelector(props: IRangeSelectorProps) {
unitId={unitId}
subUnitId={subUnitId}
visible={popupVisible}
- mobile={mobile}
maxRangeCount={maxRangeCount}
onConfirm={(ranges) => {
const resultStr = stringifyRanges(ranges);
diff --git a/packages/sheets-hyper-link-ui/src/controllers/components.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/components.controller.ts
index 20cc3ac128..f1cda01266 100644
--- a/packages/sheets-hyper-link-ui/src/controllers/components.controller.ts
+++ b/packages/sheets-hyper-link-ui/src/controllers/components.controller.ts
@@ -36,7 +36,7 @@ export class ComponentsController extends Disposable {
[CellLinkPopup.componentKey, CellLinkPopup],
[CellLinkEdit.componentKey, CellLinkEdit],
] as const).forEach(([key, comp]) => {
- this._componentManager.register(key, comp);
+ this.disposeWithMe(this._componentManager.register(key, comp));
});
}
diff --git a/packages/sheets-hyper-link-ui/src/controllers/mobile/__tests__/popup.controller.spec.ts b/packages/sheets-hyper-link-ui/src/controllers/mobile/__tests__/popup.controller.spec.ts
new file mode 100644
index 0000000000..2c0621393b
--- /dev/null
+++ b/packages/sheets-hyper-link-ui/src/controllers/mobile/__tests__/popup.controller.spec.ts
@@ -0,0 +1,243 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICellData } from '@univerjs/core';
+import type { IHoverRichTextInfo } from '@univerjs/sheets-ui';
+import type { IHyperLinkPopupOptions } from '../../../services/popup.service';
+import {
+ CustomRangeType,
+ ICommandService,
+ Injector,
+ IPermissionService,
+ IUniverInstanceService,
+ RichTextBuilder,
+ toDisposable,
+} from '@univerjs/core';
+import { DocSelectionManagerService } from '@univerjs/docs';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { SheetPermissionCheckController } from '@univerjs/sheets';
+import { HoverManagerService, IEditorBridgeService } from '@univerjs/sheets-ui';
+import { of, Subject } from 'rxjs';
+import { describe, expect, it } from 'vitest';
+import { SheetsHyperLinkPopupService } from '../../../services/popup.service';
+import { SheetsHyperLinkMobilePopupController } from '../popup.controller';
+
+class TestHoverManagerService {
+ readonly currentClickedCell$ = new Subject<IHoverRichTextInfo>();
+}
+
+class TestSheetsHyperLinkPopupService {
+ readonly shown: IHyperLinkPopupOptions[] = [];
+ hideCount = 0;
+
+ showPopup(location: IHyperLinkPopupOptions): void {
+ this.shown.push(location);
+ }
+
+ hideCurrentPopup(): void {
+ this.hideCount += 1;
+ }
+
+ endEditing(): void {}
+}
+
+class TestRenderManagerService {
+ getRenderUnitById() {
+ return {
+ with: () => ({
+ getSkeletonParam: () => ({
+ skeleton: {
+ overflowCache: {
+ forValue: () => {},
+ },
+ },
+ }),
+ }),
+ };
+ }
+}
+
+class TestPermissionService {
+ composePermission() {
+ return [{ value: true }];
+ }
+}
+
+class TestSheetPermissionCheckController {
+ permissionCheckWithRanges(): boolean {
+ return true;
+ }
+}
+
+class TestCommandService {
+ onCommandExecuted() {
+ return toDisposable(() => undefined);
+ }
+}
+
+class TestEditorBridgeService {
+ readonly currentEditCellState$ = of(null);
+ readonly visible$ = of({ visible: false });
+}
+
+class TestDocSelectionManagerService {
+ readonly textSelection$ = new Subject();
+}
+
+class TestUniverInstanceService {
+ cell: ICellData = {};
+
+ readonly worksheet = {
+ getCell: () => this.cell,
+ getCellRaw: () => ({}),
+ getCellStyleOnly: () => ({}),
+ };
+
+ readonly workbook = {
+ getSheetBySheetId: () => this.worksheet,
+ getStyles: () => ({
+ getStyleByCell: () => ({}),
+ }),
+ };
+
+ getUnit() {
+ return this.workbook;
+ }
+}
+
+function createMobilePopupControllerTestBed() {
+ const injector = new Injector();
+ injector.add([HoverManagerService, { useClass: TestHoverManagerService as never }]);
+ injector.add([SheetsHyperLinkPopupService, { useClass: TestSheetsHyperLinkPopupService as never }]);
+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);
+ injector.add([IPermissionService, { useClass: TestPermissionService as never }]);
+ injector.add([SheetPermissionCheckController, { useClass: TestSheetPermissionCheckController as never }]);
+ injector.add([ICommandService, { useClass: TestCommandService as never }]);
+ injector.add([IEditorBridgeService, { useClass: TestEditorBridgeService as never }]);
+ injector.add([DocSelectionManagerService, { useClass: TestDocSelectionManagerService as never }]);
+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
+ injector.add([SheetsHyperLinkMobilePopupController]);
+ injector.get(SheetsHyperLinkMobilePopupController);
+
+ return {
+ hoverManagerService: injector.get(HoverManagerService) as unknown as TestHoverManagerService,
+ popupService: injector.get(SheetsHyperLinkPopupService) as unknown as TestSheetsHyperLinkPopupService,
+ univerInstanceService: injector.get(IUniverInstanceService) as unknown as TestUniverInstanceService,
+ };
+}
+
+describe('SheetsHyperLinkMobilePopupController', () => {
+ it('opens the hyperlink popup when the hyperlink text is clicked', () => {
+ const { hoverManagerService, popupService } = createMobilePopupControllerTestBed();
+ const customRange = {
+ rangeId: 'link-1',
+ rangeType: CustomRangeType.HYPERLINK,
+ startIndex: 0,
+ endIndex: 5,
+ properties: { url: 'https://univer.ai' },
+ };
+
+ hoverManagerService.currentClickedCell$.next({
+ location: {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 2,
+ col: 3,
+ },
+ position: { startX: 0, startY: 0, endX: 20, endY: 20 },
+ customRange,
+ rect: { left: 0, top: 0, right: 20, bottom: 20 },
+ });
+
+ expect(popupService.shown).toEqual([
+ expect.objectContaining({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 2,
+ col: 3,
+ customRange,
+ editPermission: true,
+ copyPermission: true,
+ }),
+ ]);
+ expect(popupService.hideCount).toBe(0);
+ });
+
+ it('opens the hyperlink popup when the empty area of a hyperlink cell is clicked', () => {
+ const { hoverManagerService, popupService, univerInstanceService } = createMobilePopupControllerTestBed();
+ const documentData = RichTextBuilder.create()
+ .insertLink('Univer', 'https://univer.ai')
+ .getData();
+ const customRange = documentData.body!.customRanges![0];
+ univerInstanceService.cell = {
+ p: documentData,
+ };
+
+ hoverManagerService.currentClickedCell$.next({
+ location: {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 2,
+ col: 3,
+ },
+ position: { startX: 0, startY: 0, endX: 100, endY: 20 },
+ });
+
+ expect(popupService.shown).toEqual([
+ expect.objectContaining({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 2,
+ col: 3,
+ customRange,
+ editPermission: true,
+ copyPermission: true,
+ }),
+ ]);
+ expect(popupService.hideCount).toBe(0);
+ });
+
+ it('shows all hyperlinks when the empty area of a cell containing multiple hyperlinks is clicked', () => {
+ const { hoverManagerService, popupService, univerInstanceService } = createMobilePopupControllerTestBed();
+ const documentData = RichTextBuilder.create()
+ .insertLink('Univer', 'https://univer.ai')
+ .insertText(' ')
+ .insertLink('Docs', 'https://docs.univer.ai')
+ .getData();
+ const firstCustomRange = documentData.body!.customRanges![0];
+ univerInstanceService.cell = {
+ p: documentData,
+ };
+
+ hoverManagerService.currentClickedCell$.next({
+ location: {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 2,
+ col: 3,
+ },
+ position: { startX: 0, startY: 0, endX: 100, endY: 20 },
+ });
+
+ expect(popupService.shown).toEqual([
+ expect.objectContaining({
+ customRange: firstCustomRange,
+ showAll: true,
+ }),
+ ]);
+ expect(popupService.hideCount).toBe(0);
+ });
+});
diff --git a/packages/sheets-hyper-link-ui/src/controllers/mobile/components.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/mobile/components.controller.ts
new file mode 100644
index 0000000000..93e4a17edb
--- /dev/null
+++ b/packages/sheets-hyper-link-ui/src/controllers/mobile/components.controller.ts
@@ -0,0 +1,34 @@
+/**
+ * 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 { Disposable, Inject } from '@univerjs/core';
+import { LinkIcon } from '@univerjs/icons';
+import { ComponentManager, IconManager } from '@univerjs/ui';
+import { MobileCellLinkEdit } from '../../views/MobileCellLinkEdit';
+import { MobileCellLinkPopup } from '../../views/MobileCellLinkPopup';
+
+export class MobileComponentsController extends Disposable {
+ constructor(
+ @Inject(ComponentManager) componentManager: ComponentManager,
+ @Inject(IconManager) iconManager: IconManager
+ ) {
+ super();
+
+ this.disposeWithMe(componentManager.register(MobileCellLinkPopup.componentKey, MobileCellLinkPopup));
+ this.disposeWithMe(componentManager.register(MobileCellLinkEdit.componentKey, MobileCellLinkEdit));
+ this.disposeWithMe(iconManager.register({ LinkIcon }));
+ }
+}
diff --git a/packages/sheets-hyper-link-ui/src/controllers/mobile/popup.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/mobile/popup.controller.ts
new file mode 100644
index 0000000000..7d88f6e723
--- /dev/null
+++ b/packages/sheets-hyper-link-ui/src/controllers/mobile/popup.controller.ts
@@ -0,0 +1,298 @@
+/**
+ * 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 { ICustomRange, Nullable, Workbook, Worksheet } from '@univerjs/core';
+import type { ISheetLocationBase } from '@univerjs/sheets';
+import type { Subscription } from 'rxjs';
+import {
+ CustomRangeType,
+ Disposable,
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ ICommandService,
+ Inject,
+ IPermissionService,
+ IUniverInstanceService,
+ Rectangle,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { DocSelectionManagerService } from '@univerjs/docs';
+import { DocEventManagerService } from '@univerjs/docs-ui';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import {
+ ClearSelectionAllCommand,
+ ClearSelectionContentCommand,
+ ClearSelectionFormatCommand,
+ RangeProtectionPermissionEditPoint,
+ RangeProtectionPermissionViewPoint,
+ SheetPermissionCheckController,
+ WorkbookCopyPermission,
+ WorkbookEditablePermission,
+ WorkbookViewPermission,
+ WorksheetCopyPermission,
+ WorksheetEditPermission,
+ WorksheetInsertHyperlinkPermission,
+ WorksheetViewPermission,
+} from '@univerjs/sheets';
+import { HoverManagerService, IEditorBridgeService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import { map, switchMap } from 'rxjs';
+import { SheetsHyperLinkPopupService } from '../../services/popup.service';
+import { HyperLinkEditSourceType } from '../../types/enums/edit-source';
+
+export class SheetsHyperLinkMobilePopupController extends Disposable {
+ constructor(
+ @Inject(HoverManagerService) private readonly _hoverManagerService: HoverManagerService,
+ @Inject(SheetsHyperLinkPopupService) private readonly _sheetsHyperLinkPopupService: SheetsHyperLinkPopupService,
+ @Inject(IRenderManagerService) private readonly _renderManagerService: IRenderManagerService,
+ @Inject(IPermissionService) private readonly _permissionService: IPermissionService,
+ @Inject(SheetPermissionCheckController) private readonly _sheetPermissionCheckController: SheetPermissionCheckController,
+ @ICommandService private readonly _commandService: ICommandService,
+ @IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,
+ @Inject(DocSelectionManagerService) private readonly _textSelectionManagerService: DocSelectionManagerService,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService
+ ) {
+ super();
+
+ this._initClickListener();
+ this._initCommandListener();
+ this._initClickEditingListener();
+ this._initTextSelectionListener();
+ }
+
+ private _getLinkPermission(location: ISheetLocationBase) {
+ const { unitId, subUnitId, row, col } = location;
+ const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);
+ const worksheet = workbook?.getSheetBySheetId(subUnitId);
+ if (!worksheet) {
+ return {
+ viewPermission: false,
+ editPermission: false,
+ copyPermission: false,
+ };
+ }
+
+ const range = [{ startRow: row, startColumn: col, endRow: row, endColumn: col }];
+ const viewPermission = this._sheetPermissionCheckController.permissionCheckWithRanges({
+ workbookTypes: [WorkbookViewPermission],
+ worksheetTypes: [WorksheetViewPermission],
+ rangeTypes: [RangeProtectionPermissionViewPoint],
+ }, range, unitId, subUnitId);
+ let editPermission = this._sheetPermissionCheckController.permissionCheckWithRanges({
+ workbookTypes: [WorkbookEditablePermission],
+ worksheetTypes: [WorksheetEditPermission, WorksheetInsertHyperlinkPermission],
+ rangeTypes: [RangeProtectionPermissionEditPoint],
+ }, range, unitId, subUnitId);
+
+ const cell = worksheet.getCellRaw(row, col);
+ if (cell?.f?.startsWith('=HYPERLINK(')) {
+ editPermission = false;
+ }
+
+ const copyPermission = this._permissionService.composePermission([
+ new WorkbookCopyPermission(unitId).id,
+ new WorksheetCopyPermission(unitId, subUnitId).id,
+ ]).every((permission) => permission.value);
+
+ return {
+ viewPermission,
+ editPermission,
+ copyPermission,
+ };
+ }
+
+ private _getCellHyperLinkInfo(
+ worksheet: Worksheet,
+ row: number,
+ col: number,
+ clickedCustomRange?: Nullable<ICustomRange>
+ ) {
+ const customRanges = worksheet.getCell(row, col)?.p?.body?.customRanges ?? [];
+ const cellHyperLinks = customRanges.filter(
+ (customRange) => customRange.rangeType === CustomRangeType.HYPERLINK
+ );
+ const clickedHyperLink = clickedCustomRange?.rangeType === CustomRangeType.HYPERLINK
+ ? clickedCustomRange
+ : null;
+
+ return {
+ cellHyperLinks,
+ clickedHyperLink,
+ customRange: clickedHyperLink ?? cellHyperLinks[0],
+ };
+ }
+
+ private _initClickListener(): void {
+ this.disposeWithMe(this._hoverManagerService.currentClickedCell$.subscribe((currentCell) => {
+ if (!currentCell) {
+ this._sheetsHyperLinkPopupService.hideCurrentPopup();
+ return;
+ }
+
+ const { unitId, subUnitId, row, col } = currentCell.location;
+ const renderer = this._renderManagerService.getRenderUnitById(unitId);
+ const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);
+ const worksheet = workbook?.getSheetBySheetId(subUnitId);
+ if (!renderer || !workbook || !worksheet) {
+ return;
+ }
+
+ const skeleton = renderer.with(SheetSkeletonManagerService)
+ .getSkeletonParam(subUnitId)
+ ?.skeleton;
+ let targetRow = row;
+ let targetCol = col;
+ if (skeleton) {
+ skeleton.overflowCache.forValue((overflowRow, overflowCol, value) => {
+ if (Rectangle.contains(value, {
+ startColumn: col,
+ endColumn: col,
+ startRow: row,
+ endRow: row,
+ })) {
+ targetRow = overflowRow;
+ targetCol = overflowCol;
+ }
+ });
+ }
+
+ const { cellHyperLinks, clickedHyperLink, customRange } = this._getCellHyperLinkInfo(
+ worksheet,
+ targetRow,
+ targetCol,
+ currentCell.customRange
+ );
+ if (!customRange) {
+ this._sheetsHyperLinkPopupService.hideCurrentPopup();
+ return;
+ }
+
+ const location = { unitId, subUnitId, row: targetRow, col: targetCol };
+ const { viewPermission, editPermission, copyPermission } = this._getLinkPermission(location);
+ if (!viewPermission) {
+ this._sheetsHyperLinkPopupService.hideCurrentPopup();
+ return;
+ }
+
+ const cellStyle = worksheet.getCellStyleOnly(targetRow, targetCol);
+ const style = workbook.getStyles().getStyleByCell(cellStyle);
+ const showAll = Boolean(style?.tr?.a) || (!clickedHyperLink && cellHyperLinks.length > 1);
+
+ this._sheetsHyperLinkPopupService.showPopup({
+ ...location,
+ editPermission,
+ copyPermission,
+ customRange,
+ customRangeRect: currentCell.rect,
+ type: HyperLinkEditSourceType.VIEWING,
+ showAll,
+ });
+ }));
+ }
+
+ private _initClickEditingListener(): void {
+ let subscription: Nullable<Subscription> = null;
+ this.disposeWithMe(
+ this._editorBridgeService.currentEditCellState$
+ .pipe(switchMap((state) => this._editorBridgeService.visible$.pipe(map((visible) => ({ visible, state })))))
+ .subscribe(({ visible, state }) => {
+ if (!state || state.editorUnitId !== DOCS_NORMAL_EDITOR_UNIT_ID_KEY) {
+ return;
+ }
+
+ if (!visible.visible) {
+ subscription?.unsubscribe();
+ this._sheetsHyperLinkPopupService.hideCurrentPopup(HyperLinkEditSourceType.EDITING);
+ this._sheetsHyperLinkPopupService.endEditing(HyperLinkEditSourceType.EDITING);
+ return;
+ }
+
+ const { editorUnitId, unitId, sheetId, row, column } = state;
+ const renderer = this._renderManagerService.getRenderUnitById(editorUnitId);
+ if (!renderer) {
+ return;
+ }
+
+ const { editPermission, viewPermission, copyPermission } = this._getLinkPermission({
+ unitId,
+ subUnitId: sheetId,
+ row,
+ col: column,
+ });
+ if (!viewPermission) {
+ return;
+ }
+
+ const docEventService = renderer.with(DocEventManagerService);
+ subscription?.unsubscribe();
+ subscription = docEventService.clickCustomRanges$.subscribe((customRange) => {
+ if (customRange.range.rangeType !== CustomRangeType.HYPERLINK) {
+ this._sheetsHyperLinkPopupService.hideCurrentPopup();
+ return;
+ }
+
+ const rect = customRange.rects[customRange.rects.length - 1];
+ const skeleton = this._renderManagerService.getRenderUnitById(unitId)
+ ?.with(SheetSkeletonManagerService)
+ .getSkeletonParam(sheetId)
+ ?.skeleton;
+ if (!skeleton || !rect) {
+ return;
+ }
+
+ const canvasClientRect = renderer.engine.getCanvasElement().getBoundingClientRect();
+ this._sheetsHyperLinkPopupService.showPopup({
+ unitId,
+ subUnitId: sheetId,
+ row,
+ col: column,
+ customRange: customRange.range,
+ customRangeRect: {
+ left: rect.left + canvasClientRect.left,
+ top: rect.top + canvasClientRect.top,
+ bottom: rect.bottom + canvasClientRect.top,
+ right: rect.right + canvasClientRect.left,
+ },
+ editPermission,
+ copyPermission,
+ type: HyperLinkEditSourceType.EDITING,
+ });
+ });
+ })
+ );
+
+ this.disposeWithMe(() => subscription?.unsubscribe());
+ }
+
+ private _initTextSelectionListener(): void {
+ this.disposeWithMe(this._textSelectionManagerService.textSelection$.subscribe((selection) => {
+ if (selection?.unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY) {
+ this._sheetsHyperLinkPopupService.endEditing(HyperLinkEditSourceType.EDITING);
+ }
+ }));
+ }
+
+ private _initCommandListener(): void {
+ const hideCommandList = [
+ ClearSelectionContentCommand.id,
+ ClearSelectionAllCommand.id,
+ ClearSelectionFormatCommand.id,
+ ];
+ this.disposeWithMe(this._commandService.onCommandExecuted((command) => {
+ if (hideCommandList.includes(command.id)) {
+ this._sheetsHyperLinkPopupService.hideCurrentPopup();
+ }
+ }));
+ }
+}
diff --git a/packages/sheets-hyper-link-ui/src/index.ts b/packages/sheets-hyper-link-ui/src/index.ts
index 59ef61d061..bc42150a1d 100644
--- a/packages/sheets-hyper-link-ui/src/index.ts
+++ b/packages/sheets-hyper-link-ui/src/index.ts
@@ -26,8 +26,12 @@ export type { IUniverSheetsHyperLinkUIConfig } from './config/config';
export { SheetsHyperLinkCopyPasteController } from './controllers/copy-paste.controller';
export { InsertLinkShortcut } from './menu/menu';
export { menuSchema as SheetsHyperLinkUIMenuSchema } from './menu/schema';
+export { UniverSheetsHyperLinkMobileUIPlugin } from './mobile-plugin';
export { UniverSheetsHyperLinkUIPlugin } from './plugin';
-export { SheetsHyperLinkPopupService } from './services/popup.service';
+export {
+ ISheetsHyperLinkPopupService,
+ SheetsHyperLinkPopupService,
+} from './services/popup.service';
export { SheetsHyperLinkResolverService } from './services/resolver.service';
export { SheetsHyperLinkSidePanelService } from './services/side-panel.service';
export type { ICustomHyperLinkView } from './services/side-panel.service';
diff --git a/packages/sheets-hyper-link-ui/src/locale/ar-SA.ts b/packages/sheets-hyper-link-ui/src/locale/ar-SA.ts
index 1bdc1037fb..3f939daccd 100644
--- a/packages/sheets-hyper-link-ui/src/locale/ar-SA.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/ar-SA.ts
@@ -47,6 +47,8 @@ const locale: typeof enUS = {
coped: 'تم نسخ الرابط إلى الحافظة',
},
popup: {
+ title: 'ارتباط تشعبي',
+ open: 'فتح الرابط',
copy: 'نسخ الرابط',
edit: 'تحرير الرابط',
cancel: 'إلغاء الارتباط',
diff --git a/packages/sheets-hyper-link-ui/src/locale/ca-ES.ts b/packages/sheets-hyper-link-ui/src/locale/ca-ES.ts
index 6dd756c2d9..91ff2da23f 100644
--- a/packages/sheets-hyper-link-ui/src/locale/ca-ES.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/ca-ES.ts
@@ -47,6 +47,8 @@ const locale: typeof enUS = {
coped: 'Enllaç copiat al porta-retalls',
},
popup: {
+ title: 'Enllaç',
+ open: 'Obre l\'enllaç',
copy: 'Copia l\'enllaç',
edit: 'Edita l\'enllaç',
cancel: 'Cancel·la l\'enllaç',
diff --git a/packages/sheets-hyper-link-ui/src/locale/de-DE.ts b/packages/sheets-hyper-link-ui/src/locale/de-DE.ts
index e4e257878c..6868cad204 100644
--- a/packages/sheets-hyper-link-ui/src/locale/de-DE.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/de-DE.ts
@@ -47,6 +47,8 @@ const locale: typeof enUS = {
coped: 'Link in Zwischenablage kopiert',
},
popup: {
+ title: 'Hyperlink',
+ open: 'Link öffnen',
copy: 'Link kopieren',
edit: 'Link bearbeiten',
cancel: 'Link aufheben',
diff --git a/packages/sheets-hyper-link-ui/src/locale/en-US.ts b/packages/sheets-hyper-link-ui/src/locale/en-US.ts
index 45649a014c..cd711d896f 100644
--- a/packages/sheets-hyper-link-ui/src/locale/en-US.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/en-US.ts
@@ -45,6 +45,8 @@ const locale = {
coped: 'Link copied to clipboard',
},
popup: {
+ title: 'Hyperlink',
+ open: 'Open Link',
copy: 'Copy Link',
edit: 'Edit Link',
cancel: 'Cancel Link',
diff --git a/packages/sheets-hyper-link-ui/src/locale/es-ES.ts b/packages/sheets-hyper-link-ui/src/locale/es-ES.ts
index ecce6ff111..ad52d2a1ea 100644
--- a/packages/sheets-hyper-link-ui/src/locale/es-ES.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/es-ES.ts
@@ -47,6 +47,8 @@ const locale: typeof enUS = {
coped: 'Enlace copiado al portapapeles',
},
popup: {
+ title: 'Hipervínculo',
+ open: 'Abrir enlace',
copy: 'Copiar enlace',
edit: 'Editar enlace',
cancel: 'Cancelar enlace',
diff --git a/packages/sheets-hyper-link-ui/src/locale/fa-IR.ts b/packages/sheets-hyper-link-ui/src/locale/fa-IR.ts
index b5d6d31c78..3b6aac3671 100644
--- a/packages/sheets-hyper-link-ui/src/locale/fa-IR.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/fa-IR.ts
@@ -47,6 +47,8 @@ const locale: typeof enUS = {
coped: 'لینک به کلیپ بورد کپی شد',
},
popup: {
+ title: 'ابرپیوند',
+ open: 'باز کردن لینک',
copy: 'کپی لینک',
edit: 'ویرایش لینک',
cancel: 'لینک را لغو کنید',
diff --git a/packages/sheets-hyper-link-ui/src/locale/fr-FR.ts b/packages/sheets-hyper-link-ui/src/locale/fr-FR.ts
index 1efe1fc772..bba5837f95 100644
--- a/packages/sheets-hyper-link-ui/src/locale/fr-FR.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/fr-FR.ts
@@ -47,6 +47,8 @@ const locale: typeof enUS = {
coped: 'Lien copié dans le presse-papiers',
},
popup: {
+ title: 'Lien hypertexte',
+ open: 'Ouvrir le lien',
copy: 'Copier le lien',
edit: 'Modifier le lien',
cancel: 'Annuler le lien',
diff --git a/packages/sheets-hyper-link-ui/src/locale/id-ID.ts b/packages/sheets-hyper-link-ui/src/locale/id-ID.ts
index 1b7271c1b2..f3c561cc9e 100644
--- a/packages/sheets-hyper-link-ui/src/locale/id-ID.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/id-ID.ts
@@ -47,6 +47,8 @@ const locale: typeof enUS = {
coped: 'Tautan disalin ke clipboard',
},
popup: {
+ title: 'Tautan',
+ open: 'Buka Tautan',
copy: 'Salin Tautan',
edit: 'Edit Tautan',
cancel: 'Batalkan Tautan',
diff --git a/packages/sheets-hyper-link-ui/src/locale/it-IT.ts b/packages/sheets-hyper-link-ui/src/locale/it-IT.ts
index 163ecb429d..1233ceb113 100644
--- a/packages/sheets-hyper-link-ui/src/locale/it-IT.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/it-IT.ts
@@ -47,6 +47,8 @@ const locale: typeof enUS = {
coped: 'Collegamento copiato negli appunti',
},
popup: {
+ title: 'Collegamento ipertestuale',
+ open: 'Apri collegamento',
copy: 'Copia collegamento',
edit: 'Modifica collegamento',
cancel: 'Annulla collegamento',
diff --git a/packages/sheets-hyper-link-ui/src/locale/ja-JP.ts b/packages/sheets-hyper-link-ui/src/locale/ja-JP.ts
index aa0ec23eb0..4e59bd08d8 100644
--- a/packages/sheets-hyper-link-ui/src/locale/ja-JP.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/ja-JP.ts
@@ -47,6 +47,8 @@ const locale: typeof enUS = {
coped: 'リンクがクリップボードにコピーされました',
},
popup: {
+ title: 'ハイパーリンク',
+ open: 'リンクを開く',
copy: 'リンクをコピー',
edit: 'リンクの編集',
cancel: 'リンク解除',
diff --git a/packages/sheets-hyper-link-ui/src/locale/ko-KR.ts b/packages/sheets-hyper-link-ui/src/locale/ko-KR.ts
index d3d52bbfdc..e3975e4038 100644
--- a/packages/sheets-hyper-link-ui/src/locale/ko-KR.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/ko-KR.ts
@@ -47,6 +47,8 @@ const locale: typeof enUS = {
coped: '링크가 클립보드에 복사되었습니다',
},
popup: {
+ title: '하이퍼링크',
+ open: '링크 열기',
copy: '링크 복사',
edit: '링크 편집',
cancel: '링크 취소',
diff --git a/packages/sheets-hyper-link-ui/src/locale/pl-PL.ts b/packages/sheets-hyper-link-ui/src/locale/pl-PL.ts
index 655ee840d3..76a6ec476e 100644
--- a/packages/sheets-hyper-link-ui/src/locale/pl-PL.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/pl-PL.ts
@@ -47,6 +47,8 @@ const locale: typeof enUS = {
coped: 'Łącze skopiowane do schowka',
},
popup: {
+ title: 'Hiperłącze',
+ open: 'Otwórz łącze',
copy: 'Kopiuj łącze',
edit: 'Edytuj łącze',
cancel: 'Anuluj łącze',
diff --git a/packages/sheets-hyper-link-ui/src/locale/pt-BR.ts b/packages/sheets-hyper-link-ui/src/locale/pt-BR.ts
index e2221af5db..42ef20ce66 100644
--- a/packages/sheets-hyper-link-ui/src/locale/pt-BR.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/pt-BR.ts
@@ -47,6 +47,8 @@ const locale: typeof enUS = {
coped: 'Link copiado para a área de transferência',
},
popup: {
+ title: 'Hiperlink',
+ open: 'Abrir Link',
copy: 'Copiar Link',
edit: 'Editar Link',
cancel: 'Cancelar Link',
diff --git a/packages/sheets-hyper-link-ui/src/locale/ru-RU.ts b/packages/sheets-hyper-link-ui/src/locale/ru-RU.ts
index 22947c43b2..0d8af723e9 100644
--- a/packages/sheets-hyper-link-ui/src/locale/ru-RU.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/ru-RU.ts
@@ -47,6 +47,8 @@ const locale: typeof enUS = {
coped: 'Ссылка скопирована в буфер обмена',
},
popup: {
+ title: 'Гиперссылка',
+ open: 'Открыть ссылку',
copy: 'Копировать ссылку',
edit: 'Редактировать ссылку',
cancel: 'Отменить ссылку',
diff --git a/packages/sheets-hyper-link-ui/src/locale/sk-SK.ts b/packages/sheets-hyper-link-ui/src/locale/sk-SK.ts
index c8bfb2f35a..277bd7e2f0 100644
--- a/packages/sheets-hyper-link-ui/src/locale/sk-SK.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/sk-SK.ts
@@ -47,6 +47,8 @@ const locale: typeof enUS = {
coped: 'Odkaz skopírovaný do schránky',
},
popup: {
+ title: 'Hypertextový odkaz',
+ open: 'Otvoriť odkaz',
copy: 'Kopírovať odkaz',
edit: 'Upraviť odkaz',
cancel: 'Zrušiť odkaz',
diff --git a/packages/sheets-hyper-link-ui/src/locale/vi-VN.ts b/packages/sheets-hyper-link-ui/src/locale/vi-VN.ts
index f1c50f5e36..57383d3c98 100644
--- a/packages/sheets-hyper-link-ui/src/locale/vi-VN.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/vi-VN.ts
@@ -47,6 +47,8 @@ const locale: typeof enUS = {
coped: 'Liên kết đã được sao chép vào clipboard',
},
popup: {
+ title: 'Siêu liên kết',
+ open: 'Mở liên kết',
copy: 'Sao chép',
edit: 'Chỉnh sửa',
cancel: 'Hủy liên kết',
diff --git a/packages/sheets-hyper-link-ui/src/locale/zh-CN.ts b/packages/sheets-hyper-link-ui/src/locale/zh-CN.ts
index e6cae119ce..448959005d 100644
--- a/packages/sheets-hyper-link-ui/src/locale/zh-CN.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/zh-CN.ts
@@ -47,6 +47,8 @@ const locale: typeof enUS = {
coped: '链接已被复制到剪贴板',
},
popup: {
+ title: '超链接',
+ open: '打开链接',
copy: '复制',
edit: '编辑',
cancel: '取消链接',
diff --git a/packages/sheets-hyper-link-ui/src/locale/zh-HK.ts b/packages/sheets-hyper-link-ui/src/locale/zh-HK.ts
index 80c7b82fde..ecad8d6f2b 100644
--- a/packages/sheets-hyper-link-ui/src/locale/zh-HK.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/zh-HK.ts
@@ -47,6 +47,8 @@ const locale: typeof enUS = {
coped: '連結已複製到剪貼簿',
},
popup: {
+ title: '超連結',
+ open: '開啟連結',
copy: '複製',
edit: '編輯',
cancel: '取消連結',
diff --git a/packages/sheets-hyper-link-ui/src/locale/zh-TW.ts b/packages/sheets-hyper-link-ui/src/locale/zh-TW.ts
index 80c7b82fde..ecad8d6f2b 100644
--- a/packages/sheets-hyper-link-ui/src/locale/zh-TW.ts
+++ b/packages/sheets-hyper-link-ui/src/locale/zh-TW.ts
@@ -47,6 +47,8 @@ const locale: typeof enUS = {
coped: '連結已複製到剪貼簿',
},
popup: {
+ title: '超連結',
+ open: '開啟連結',
copy: '複製',
edit: '編輯',
cancel: '取消連結',
diff --git a/packages/sheets-hyper-link-ui/src/mobile-plugin.ts b/packages/sheets-hyper-link-ui/src/mobile-plugin.ts
new file mode 100644
index 0000000000..7a356476c1
--- /dev/null
+++ b/packages/sheets-hyper-link-ui/src/mobile-plugin.ts
@@ -0,0 +1,125 @@
+/**
+ * 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 { Dependency } from '@univerjs/core';
+import type { IUniverSheetsHyperLinkUIConfig } from './config/config';
+import {
+ DependentOn,
+ IConfigService,
+ Inject,
+ Injector,
+ merge,
+ Plugin,
+ registerDependencies,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { UniverDocsPlugin } from '@univerjs/docs';
+import { UniverDocsUIPlugin } from '@univerjs/docs-ui';
+import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';
+import { IRenderManagerService, UniverRenderEnginePlugin } from '@univerjs/engine-render';
+import { UniverSheetsPlugin } from '@univerjs/sheets';
+import { UniverSheetsHyperLinkPlugin } from '@univerjs/sheets-hyper-link';
+import { UniverSheetsMobileUIPlugin } from '@univerjs/sheets-ui';
+import { UniverMobileUIPlugin } from '@univerjs/ui';
+import pkg from '../package.json';
+import {
+ defaultPluginConfig,
+ SHEETS_HYPER_LINK_UI_PLUGIN_CONFIG_KEY,
+} from './config/config';
+import { SheetsHyperLinkAutoFillController } from './controllers/auto-fill.controller';
+import { SheetsHyperLinkCopyPasteController } from './controllers/copy-paste.controller';
+import { SheetsHyperLinkPermissionController } from './controllers/hyper-link-permission.controller';
+import { MobileComponentsController } from './controllers/mobile/components.controller';
+import { SheetsHyperLinkMobilePopupController } from './controllers/mobile/popup.controller';
+import { SheetsHyperLinkRenderController } from './controllers/render-controllers/render.controller';
+import { SheetsHyperLinkUIController } from './controllers/ui.controller';
+import { SheetHyperLinkUrlController } from './controllers/url.controller';
+import { SheetsHyperLinkMobilePopupService } from './services/mobile-popup.service';
+import { ISheetsHyperLinkPopupService, SheetsHyperLinkPopupService } from './services/popup.service';
+import { SheetsHyperLinkResolverService } from './services/resolver.service';
+import { SheetsHyperLinkSidePanelService } from './services/side-panel.service';
+import { SHEET_HYPER_LINK_UI_PLUGIN } from './types/const';
+
+@DependentOn(
+ UniverDocsPlugin,
+ UniverFormulaEnginePlugin,
+ UniverRenderEnginePlugin,
+ UniverSheetsPlugin,
+ UniverDocsUIPlugin,
+ UniverSheetsHyperLinkPlugin,
+ UniverSheetsMobileUIPlugin,
+ UniverMobileUIPlugin
+)
+export class UniverSheetsHyperLinkMobileUIPlugin extends Plugin {
+ static override pluginName: string = SHEET_HYPER_LINK_UI_PLUGIN;
+ static override packageName = pkg.name;
+ static override version = pkg.version;
+ static override type = UniverInstanceType.UNIVER_SHEET;
+
+ constructor(
+ private readonly _config: Partial<IUniverSheetsHyperLinkUIConfig> = defaultPluginConfig,
+ @Inject(Injector) protected readonly _injector: Injector,
+ @IConfigService private readonly _configService: IConfigService
+ ) {
+ super();
+
+ const { menu, ...rest } = merge({}, defaultPluginConfig, this._config);
+ if (menu) {
+ this._configService.setConfig('menu', menu, { merge: true });
+ }
+ this._configService.setConfig(SHEETS_HYPER_LINK_UI_PLUGIN_CONFIG_KEY, rest);
+ }
+
+ override onStarting(): void {
+ const dependencies = [
+ [MobileComponentsController],
+ [SheetsHyperLinkResolverService],
+ [ISheetsHyperLinkPopupService, { useClass: SheetsHyperLinkMobilePopupService }],
+ [SheetsHyperLinkPopupService, { useExisting: ISheetsHyperLinkPopupService }],
+ [SheetsHyperLinkSidePanelService],
+ [SheetsHyperLinkMobilePopupController],
+ [SheetsHyperLinkUIController],
+ [SheetsHyperLinkAutoFillController],
+ [SheetsHyperLinkCopyPasteController],
+ [SheetsHyperLinkPermissionController],
+ [SheetHyperLinkUrlController],
+ [SheetsHyperLinkRenderController],
+ ] as Dependency[];
+
+ registerDependencies(this._injector, dependencies);
+ this._injector.get(MobileComponentsController);
+ }
+
+ override onReady(): void {
+ const renderManager = this._injector.get(IRenderManagerService);
+ this.disposeWithMe(
+ renderManager.registerRenderModule(
+ UniverInstanceType.UNIVER_SHEET,
+ [SheetsHyperLinkRenderController] as Dependency
+ )
+ );
+
+ this._injector.get(SheetsHyperLinkAutoFillController);
+ this._injector.get(SheetsHyperLinkCopyPasteController);
+ this._injector.get(SheetsHyperLinkUIController);
+ }
+
+ override onRendered(): void {
+ this._injector.get(SheetsHyperLinkPermissionController);
+ this._injector.get(SheetHyperLinkUrlController);
+ this._injector.get(SheetsHyperLinkMobilePopupController);
+ }
+}
diff --git a/packages/sheets-hyper-link-ui/src/plugin.ts b/packages/sheets-hyper-link-ui/src/plugin.ts
index 80062e89f1..52f68ef87c 100644
--- a/packages/sheets-hyper-link-ui/src/plugin.ts
+++ b/packages/sheets-hyper-link-ui/src/plugin.ts
@@ -34,7 +34,7 @@ import { SheetsHyperLinkPopupController } from './controllers/popup.controller';
import { SheetsHyperLinkRenderController } from './controllers/render-controllers/render.controller';
import { SheetsHyperLinkUIController } from './controllers/ui.controller';
import { SheetHyperLinkUrlController } from './controllers/url.controller';
-import { SheetsHyperLinkPopupService } from './services/popup.service';
+import { ISheetsHyperLinkPopupService, SheetsHyperLinkPopupService } from './services/popup.service';
import { SheetsHyperLinkResolverService } from './services/resolver.service';
import { SheetsHyperLinkSidePanelService } from './services/side-panel.service';
import { SHEET_HYPER_LINK_UI_PLUGIN } from './types/const';
@@ -78,7 +78,8 @@ export class UniverSheetsHyperLinkUIPlugin extends Plugin {
this._injector.get(ComponentsController);
const dependencies: Dependency[] = [
[SheetsHyperLinkResolverService],
- [SheetsHyperLinkPopupService],
+ [ISheetsHyperLinkPopupService, { useClass: SheetsHyperLinkPopupService }],
+ [SheetsHyperLinkPopupService, { useExisting: ISheetsHyperLinkPopupService }],
[SheetsHyperLinkSidePanelService],
[SheetsHyperLinkPopupController],
diff --git a/packages/sheets-hyper-link-ui/src/services/mobile-popup.service.ts b/packages/sheets-hyper-link-ui/src/services/mobile-popup.service.ts
new file mode 100644
index 0000000000..a9b7762223
--- /dev/null
+++ b/packages/sheets-hyper-link-ui/src/services/mobile-popup.service.ts
@@ -0,0 +1,189 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICustomRange, INeedCheckDisposable, Nullable, Workbook } from '@univerjs/core';
+import type { IHyperLinkEditing, IHyperLinkPopupOptions } from './popup.service';
+import { BuildTextUtils, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, UniverInstanceType } from '@univerjs/core';
+import { getCustomRangePosition, getEditingCustomRangePosition } from '@univerjs/sheets-ui';
+import { HyperLinkEditSourceType } from '../types/enums/edit-source';
+import { MobileCellLinkEdit } from '../views/MobileCellLinkEdit';
+import { MobileCellLinkPopup } from '../views/MobileCellLinkPopup';
+import { SheetsHyperLinkPopupService } from './popup.service';
+
+const MOBILE_HYPER_LINK_EDITOR_DIALOG_ID = 'sheet-mobile-hyper-link-editor';
+const MOBILE_HYPER_LINK_VIEWER_DIALOG_ID = 'sheet-mobile-hyper-link-viewer';
+
+export class SheetsHyperLinkMobilePopupService extends SheetsHyperLinkPopupService {
+ override showPopup(location: IHyperLinkPopupOptions): void {
+ if (this.getIsKeepVisible()) {
+ return;
+ }
+
+ if (this._currentPopup && this._isEqualLink(location, this._currentPopup)) {
+ return;
+ }
+
+ this.hideCurrentPopup(undefined, true);
+ const currentEditing = this._currentEditing$.getValue();
+ if (currentEditing && this._isEqualLink(location, currentEditing)) {
+ return;
+ }
+
+ const { unitId, subUnitId, row, col, customRange } = location;
+ if (!location.showAll && !customRange) {
+ return;
+ }
+
+ const disposable: INeedCheckDisposable = {
+ canDispose: () => true,
+ dispose: () => this._dialogService.close(MOBILE_HYPER_LINK_VIEWER_DIALOG_ID),
+ };
+ this._currentPopup = {
+ unitId,
+ subUnitId,
+ disposable,
+ row,
+ col,
+ editPermission: !!location.editPermission,
+ copyPermission: !!location.copyPermission,
+ customRange,
+ type: location.type,
+ showAll: location.showAll,
+ };
+ this._currentPopup$.next(this._currentPopup);
+ this._dialogService.open({
+ id: MOBILE_HYPER_LINK_VIEWER_DIALOG_ID,
+ title: { title: 'sheets-hyper-link-ui.popup.title' },
+ children: { label: MobileCellLinkPopup.componentKey },
+ onClose: () => this.hideCurrentPopup(undefined, true),
+ });
+ }
+
+ override startAddEditing(link: IHyperLinkEditing): void {
+ const { unitId, subUnitId, type } = link;
+ let label: string;
+ if (type === HyperLinkEditSourceType.EDITING) {
+ const range = this._getEditingRange();
+ if (!range) {
+ return;
+ }
+
+ this._textSelectionManagerService.replaceDocRanges([{ ...range }], {
+ unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ subUnitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ });
+ label = range.label;
+ } else {
+ const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);
+ const worksheet = workbook?.getSheetBySheetId(subUnitId);
+ const cell = worksheet?.getCellRaw(link.row, link.col);
+ label = cell?.p
+ ? BuildTextUtils.transform.getPlainText(cell.p.body?.dataStream ?? '')
+ : (cell?.v ?? '').toString();
+ }
+
+ this._openMobileEditor({ ...link, label });
+ }
+
+ override startEditing(link: Required<IHyperLinkEditing>): void {
+ this._currentEditingPopup?.dispose();
+ this.hideCurrentPopup(undefined, true);
+
+ let customRange: ICustomRange;
+ let label: string;
+ if (link.type === HyperLinkEditSourceType.EDITING) {
+ const customRangeInfo = getEditingCustomRangePosition(
+ this._injector,
+ link.unitId,
+ link.subUnitId,
+ link.row,
+ link.col,
+ link.customRangeId
+ );
+ if (!customRangeInfo || !customRangeInfo.rects?.length) {
+ return;
+ }
+ customRange = customRangeInfo.customRange;
+ label = customRangeInfo.label;
+ this._textSelectionManagerService.replaceDocRanges([{
+ startOffset: customRange.startIndex,
+ endOffset: customRange.endIndex + 1,
+ }]);
+ } else {
+ const customRangeInfo = getCustomRangePosition(
+ this._injector,
+ link.unitId,
+ link.subUnitId,
+ link.row,
+ link.col,
+ link.customRangeId
+ );
+ if (!customRangeInfo || !customRangeInfo.rects?.length) {
+ return;
+ }
+ customRange = customRangeInfo.customRange;
+ label = customRangeInfo.label;
+ }
+
+ this._openMobileEditor({ ...link, customRange, label });
+ }
+
+ override endEditing(type?: HyperLinkEditSourceType): void {
+ if (this.getIsKeepVisible()) {
+ return;
+ }
+ const current = this._currentEditing$.getValue();
+ if (current && (!type || type === current.type)) {
+ this._currentEditingPopup?.dispose();
+ this._dialogService.close(MOBILE_HYPER_LINK_EDITOR_DIALOG_ID);
+ this._currentEditing$.next(null);
+ }
+ }
+
+ private _openMobileEditor(editing: IHyperLinkEditing & { customRange?: ICustomRange; label?: string }): void {
+ this._currentEditing$.next(editing);
+ this._dialogService.open({
+ id: MOBILE_HYPER_LINK_EDITOR_DIALOG_ID,
+ title: { title: 'sheets-hyper-link-ui.form.addTitle' },
+ children: { label: MobileCellLinkEdit.componentKey },
+ maskClosable: false,
+ onClose: () => this.endEditing(editing.type),
+ });
+ }
+
+ private _isEqualLink(
+ location: IHyperLinkPopupOptions,
+ current: {
+ unitId: string;
+ subUnitId: string;
+ row: number;
+ col: number;
+ customRange?: Nullable<ICustomRange>;
+ type: HyperLinkEditSourceType;
+ } | null
+ ): boolean {
+ if (!current) {
+ return false;
+ }
+
+ return location.unitId === current.unitId
+ && location.subUnitId === current.subUnitId
+ && location.row === current.row
+ && location.col === current.col
+ && location.customRange?.rangeId === current.customRange?.rangeId
+ && location.type === current.type;
+ }
+}
diff --git a/packages/sheets-hyper-link-ui/src/services/popup.service.ts b/packages/sheets-hyper-link-ui/src/services/popup.service.ts
index e86143558f..47bfad2fc8 100644
--- a/packages/sheets-hyper-link-ui/src/services/popup.service.ts
+++ b/packages/sheets-hyper-link-ui/src/services/popup.service.ts
@@ -18,12 +18,13 @@ import type { ICustomRange, IDisposable, INeedCheckDisposable, ITextRange, Nulla
import type { IBoundRectNoAngle } from '@univerjs/engine-render';
import type { ISheetLocationBase } from '@univerjs/sheets';
import type { ICanvasPopup } from '@univerjs/sheets-ui';
+import type { Observable } from 'rxjs';
import {
BuildTextUtils,
+ createIdentifier,
CustomRangeType,
Disposable,
DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
- IContextService,
Inject,
Injector,
IUniverInstanceService,
@@ -33,7 +34,7 @@ import { DocSelectionManagerService } from '@univerjs/docs';
import { calcDocRangePositions } from '@univerjs/docs-ui';
import { IRenderManagerService } from '@univerjs/engine-render';
import { getCustomRangePosition, getEditingCustomRangePosition, IEditorBridgeService, SheetCanvasPopManagerService } from '@univerjs/sheets-ui';
-import { IDialogService, MOBILE_UI_MODE } from '@univerjs/ui';
+import { IDialogService } from '@univerjs/ui';
import { BehaviorSubject, Subject } from 'rxjs';
import { HyperLinkEditSourceType } from '../types/enums/edit-source';
import { CellLinkEdit } from '../views/CellLinkEdit';
@@ -52,7 +53,7 @@ export interface IHyperLinkPopup {
showAll?: boolean;
}
-interface IHyperLinkEditing {
+export interface IHyperLinkEditing {
unitId: string;
subUnitId: string;
row: number;
@@ -61,8 +62,21 @@ interface IHyperLinkEditing {
type: HyperLinkEditSourceType;
}
-const MOBILE_HYPER_LINK_EDITOR_DIALOG_ID = 'sheet-mobile-hyper-link-editor';
-const MOBILE_HYPER_LINK_VIEWER_DIALOG_ID = 'sheet-mobile-hyper-link-viewer';
+export interface ISheetsHyperLinkPopupService {
+ readonly currentPopup: IHyperLinkPopup | null;
+ readonly currentPopup$: Observable<IHyperLinkPopup | null>;
+ readonly currentEditing: (IHyperLinkEditing & { customRange?: ICustomRange; label?: string }) | null;
+ readonly currentEditing$: Observable<(IHyperLinkEditing & { customRange?: ICustomRange; label?: string }) | null>;
+ setIsKeepVisible(value: boolean): void;
+ getIsKeepVisible(): boolean;
+ showPopup(location: IHyperLinkPopupOptions): void;
+ hideCurrentPopup(type?: HyperLinkEditSourceType, force?: boolean): void;
+ startAddEditing(link: IHyperLinkEditing): void;
+ startEditing(link: Required<IHyperLinkEditing>): void;
+ endEditing(type?: HyperLinkEditSourceType): void;
+}
+
+export const ISheetsHyperLinkPopupService = createIdentifier<ISheetsHyperLinkPopupService>('sheets-hyper-link-ui.popup.service');
const isEqualLink = (a: IHyperLinkPopupOptions, b: Omit<IHyperLinkPopup, 'disposable' | 'editPermission'>) => {
return (
@@ -75,7 +89,7 @@ const isEqualLink = (a: IHyperLinkPopupOptions, b: Omit<IHyperLinkPopup, 'dispos
);
};
-interface IHyperLinkPopupOptions extends ISheetLocationBase {
+export interface IHyperLinkPopupOptions extends ISheetLocationBase {
editPermission?: boolean;
copyPermission?: boolean;
customRange?: Nullable<ICustomRange>;
@@ -84,13 +98,13 @@ interface IHyperLinkPopupOptions extends ISheetLocationBase {
type: HyperLinkEditSourceType;
}
-export class SheetsHyperLinkPopupService extends Disposable {
- private _currentPopup: IHyperLinkPopup | null = null;
- private _currentPopup$ = new Subject<IHyperLinkPopup | null>();
+export class SheetsHyperLinkPopupService extends Disposable implements ISheetsHyperLinkPopupService {
+ protected _currentPopup: IHyperLinkPopup | null = null;
+ protected _currentPopup$ = new Subject<IHyperLinkPopup | null>();
currentPopup$ = this._currentPopup$.asObservable();
- private _currentEditingPopup: Nullable<IDisposable> = null;
+ protected _currentEditingPopup: Nullable<IDisposable> = null;
- private _currentEditing$ = new BehaviorSubject<(IHyperLinkEditing & { customRange?: ICustomRange; label?: string }) | null>(null);
+ protected _currentEditing$ = new BehaviorSubject<(IHyperLinkEditing & { customRange?: ICustomRange; label?: string }) | null>(null);
currentEditing$ = this._currentEditing$.asObservable();
private _isKeepVisible: boolean = false;
@@ -104,14 +118,13 @@ export class SheetsHyperLinkPopupService extends Disposable {
}
constructor(
- @Inject(SheetCanvasPopManagerService) private readonly _sheetCanvasPopManagerService: SheetCanvasPopManagerService,
- @Inject(Injector) private readonly _injector: Injector,
- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @Inject(SheetCanvasPopManagerService) protected readonly _sheetCanvasPopManagerService: SheetCanvasPopManagerService,
+ @Inject(Injector) protected readonly _injector: Injector,
+ @IUniverInstanceService protected readonly _univerInstanceService: IUniverInstanceService,
@IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,
- @Inject(DocSelectionManagerService) private readonly _textSelectionManagerService: DocSelectionManagerService,
- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @IContextService private readonly _contextService: IContextService,
- @IDialogService private readonly _dialogService: IDialogService
+ @Inject(DocSelectionManagerService) protected readonly _textSelectionManagerService: DocSelectionManagerService,
+ @IRenderManagerService protected readonly _renderManagerService: IRenderManagerService,
+ @IDialogService protected readonly _dialogService: IDialogService
) {
super();
@@ -144,36 +157,6 @@ export class SheetsHyperLinkPopupService extends Disposable {
}
const { unitId, subUnitId, row, col, customRangeRect, customRange } = location;
- const mobileDialogService = this._getMobileDialogService();
- if (mobileDialogService) {
- if (!location.showAll && !customRange) {
- return;
- }
- const disposable: INeedCheckDisposable = {
- canDispose: () => true,
- dispose: () => mobileDialogService.close(MOBILE_HYPER_LINK_VIEWER_DIALOG_ID),
- };
- this._currentPopup = {
- unitId,
- subUnitId,
- disposable,
- row,
- col,
- editPermission: !!location.editPermission,
- copyPermission: !!location.copyPermission,
- customRange,
- type: location.type,
- showAll: location.showAll,
- };
- this._currentPopup$.next(this._currentPopup);
- mobileDialogService.open({
- id: MOBILE_HYPER_LINK_VIEWER_DIALOG_ID,
- title: { title: 'sheets-hyper-link-ui.form.addTitle' },
- children: { label: CellLinkPopup.componentKey },
- onClose: () => this.hideCurrentPopup(undefined, true),
- });
- return;
- }
let disposable: Nullable<INeedCheckDisposable>;
const popup: ICanvasPopup = {
componentKey: CellLinkPopup.componentKey,
@@ -249,7 +232,7 @@ export class SheetsHyperLinkPopupService extends Disposable {
this._currentEditing$.complete();
}
- private _getEditingRange(): Nullable<ITextRange & { label: string }> {
+ protected _getEditingRange(): Nullable<ITextRange & { label: string }> {
const visible = this._editorBridgeService.isVisible().visible;
const state = this._editorBridgeService.getEditCellState();
if (visible && state) {
@@ -299,23 +282,6 @@ export class SheetsHyperLinkPopupService extends Disposable {
return popup;
}
- private _openMobileEditor(editing: IHyperLinkEditing & { customRange?: ICustomRange; label?: string }): void {
- const dialogService = this._getMobileDialogService();
- if (!dialogService) return;
- this._currentEditing$.next(editing);
- dialogService.open({
- id: MOBILE_HYPER_LINK_EDITOR_DIALOG_ID,
- title: { title: 'sheets-hyper-link-ui.form.addTitle' },
- children: { label: CellLinkEdit.componentKey },
- maskClosable: false,
- onClose: () => this.endEditing(editing.type),
- });
- }
-
- private _getMobileDialogService(): IDialogService | null {
- return this._contextService.getContextValue(MOBILE_UI_MODE) ? this._dialogService : null;
- }
-
startAddEditing(link: IHyperLinkEditing) {
const { unitId, subUnitId, type } = link;
if (type === HyperLinkEditSourceType.EDITING) {
@@ -326,10 +292,6 @@ export class SheetsHyperLinkPopupService extends Disposable {
}
this._textSelectionManagerService.replaceDocRanges([{ ...range }], { unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY, subUnitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY });
- if (this._getMobileDialogService()) {
- this._openMobileEditor({ ...link, label: range.label });
- return;
- }
const currentRender = this._renderManagerService.getRenderUnitById(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
if (!currentRender) {
return;
@@ -354,10 +316,6 @@ export class SheetsHyperLinkPopupService extends Disposable {
const worksheet = workbook?.getSheetBySheetId(subUnitId);
const cell = worksheet?.getCellRaw(link.row, link.col);
const label = cell?.p ? BuildTextUtils.transform.getPlainText(cell.p.body?.dataStream ?? '') : (cell?.v ?? '').toString();
- if (this._getMobileDialogService()) {
- this._openMobileEditor({ ...link, label });
- return;
- }
this._currentEditingPopup = this._sheetCanvasPopManagerService.attachPopupToCell(
link.row,
link.col,
@@ -377,7 +335,6 @@ export class SheetsHyperLinkPopupService extends Disposable {
this.hideCurrentPopup(undefined, true);
const { unitId, subUnitId } = link;
- const mobile = Boolean(this._getMobileDialogService());
let customRange;
let label;
if (link.type === HyperLinkEditSourceType.EDITING) {
@@ -393,14 +350,12 @@ export class SheetsHyperLinkPopupService extends Disposable {
endOffset: customRange.endIndex + 1,
},
]);
- if (!mobile) {
- this._currentEditingPopup = this._sheetCanvasPopManagerService.attachPopupToAbsolutePosition(
- customRangeInfo.rects.pop()!,
- this._editPopup,
- unitId,
- subUnitId
- );
- }
+ this._currentEditingPopup = this._sheetCanvasPopManagerService.attachPopupToAbsolutePosition(
+ customRangeInfo.rects.pop()!,
+ this._editPopup,
+ unitId,
+ subUnitId
+ );
} else {
const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);
const worksheet = workbook?.getSheetBySheetId(subUnitId);
@@ -414,27 +369,25 @@ export class SheetsHyperLinkPopupService extends Disposable {
}
customRange = customRangeInfo.customRange;
label = customRangeInfo.label;
- if (!mobile) {
- if (tr) {
- this._currentEditingPopup = this._sheetCanvasPopManagerService.attachPopupToCell(
- link.row,
- link.col,
- this._editPopup,
+ if (tr) {
+ this._currentEditingPopup = this._sheetCanvasPopManagerService.attachPopupToCell(
+ link.row,
+ link.col,
+ this._editPopup,
+ unitId,
+ subUnitId
+ );
+ } else {
+ this._currentEditingPopup = this._sheetCanvasPopManagerService.attachPopupByPosition(
+ customRangeInfo.rects.pop()!,
+ this._editPopup,
+ {
unitId,
- subUnitId
- );
- } else {
- this._currentEditingPopup = this._sheetCanvasPopManagerService.attachPopupByPosition(
- customRangeInfo.rects.pop()!,
- this._editPopup,
- {
- unitId,
- subUnitId,
- row: link.row,
- col: link.col,
- }
- );
- }
+ subUnitId,
+ row: link.row,
+ col: link.col,
+ }
+ );
}
}
const editing = {
@@ -442,10 +395,6 @@ export class SheetsHyperLinkPopupService extends Disposable {
customRange,
label,
};
- if (mobile) {
- this._openMobileEditor(editing);
- return;
- }
this._currentEditing$.next(editing);
}
@@ -456,7 +405,6 @@ export class SheetsHyperLinkPopupService extends Disposable {
const current = this._currentEditing$.getValue();
if (current && (!type || type === current.type)) {
this._currentEditingPopup?.dispose();
- this._getMobileDialogService()?.close(MOBILE_HYPER_LINK_EDITOR_DIALOG_ID);
this._currentEditing$.next(null);
}
}
diff --git a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit.tsx b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit.tsx
index 1dacb781bc..8ef3e2968b 100644
--- a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit.tsx
@@ -31,7 +31,7 @@ import {
Tools,
UniverInstanceType,
} from '@univerjs/core';
-import { ActionRow, borderClassName, Button, clsx, ConfigContext, FormLayout, Input, Select } from '@univerjs/design';
+import { ActionRow, borderClassName, Button, clsx, FormLayout, Input, Select } from '@univerjs/design';
import { DocSelectionManagerService } from '@univerjs/docs';
import { DocSelectionRenderService } from '@univerjs/docs-ui';
import {
@@ -53,7 +53,7 @@ import {
} from '@univerjs/sheets-hyper-link';
import { IEditorBridgeService, IMarkSelectionService, ScrollToRangeOperation } from '@univerjs/sheets-ui';
import { KeyCode, useDependency, useEvent, useObservable } from '@univerjs/ui';
-import { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { CloseHyperLinkPopupOperation } from '../commands/operations/popup.operations';
import { isLegalLink, serializeUrl } from '../common/util';
import { SheetsHyperLinkPopupService } from '../services/popup.service';
@@ -64,14 +64,12 @@ import { isBlankInput, resolveRangePayload } from './CellLinkEdit/utils';
export const CellLinkEdit = () => {
const [id, setId] = useState('');
- const [hide, setHide] = useState(false);
- const [display, _setDisplay] = useState('');
+ const [display, setDisplay] = useState('');
const [showLabel, setShowLabel] = useState(true);
const [type, setType] = useState<SheetHyperLinkType | string>(SheetHyperLinkType.URL);
const [payload, setPayload] = useState('');
const localeService = useDependency(LocaleService);
- const { mobile } = useContext(ConfigContext);
const definedNameService = useDependency(IDefinedNamesService);
const editorBridgeService = useDependency(IEditorBridgeService);
const univerInstanceService = useDependency(IUniverInstanceService);
@@ -112,9 +110,9 @@ export const CellLinkEdit = () => {
const subUnitId = workbook?.getActiveSheet().getSheetId() || '';
// to polyfill the display value on old version data
// case split tag is no longer needed
- const setDisplay = useCallback((value: string) => {
- _setDisplay(value.replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_START, '').replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_END, ''));
- }, [_setDisplay]);
+ const setNormalizedDisplay = useCallback((value: string) => {
+ setDisplay(value.replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_START, '').replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_END, ''));
+ }, [setDisplay]);
useEffect(() => {
if (editing?.row !== undefined && editing.col !== undefined) {
@@ -174,10 +172,10 @@ export const CellLinkEdit = () => {
const customLinkInfo = customLink.convert(link);
setType(customLinkInfo.type);
setPayload(customLinkInfo.payload);
- setDisplay(customLinkInfo.display);
+ setNormalizedDisplay(customLinkInfo.display);
return;
}
- setDisplay(link.display);
+ setNormalizedDisplay(link.display);
const linkInfo = parserService.parseHyperLink(link.payload);
setType(linkInfo.type === SheetHyperLinkType.INVALID ? SheetHyperLinkType.RANGE : linkInfo.type);
switch (linkInfo.type) {
@@ -332,7 +330,7 @@ export const CellLinkEdit = () => {
setPayload(newPayload);
if (getIsDisplaySyncedWithPayload() || !display) {
- setDisplay(newPayload);
+ setNormalizedDisplay(newPayload);
setDisplaySyncedWithPayload(true);
}
});
@@ -418,7 +416,7 @@ export const CellLinkEdit = () => {
});
}
- commandService.executeCommand(CloseHyperLinkPopupOperation.id);
+ await commandService.executeCommand(CloseHyperLinkPopupOperation.id);
};
if (!editing) {
@@ -429,12 +427,10 @@ export const CellLinkEdit = () => {
<div
className={clsx(
`
- univer-box-border univer-bg-gray-0
+ univer-box-border univer-w-[296px] univer-rounded-xl univer-bg-gray-0 univer-p-4 univer-shadow-md
dark:!univer-bg-gray-900
`,
- mobile
- ? 'univer-w-full univer-p-0'
- : clsx('univer-w-[296px] univer-rounded-xl univer-p-4 univer-shadow-md', borderClassName)
+ borderClassName
)}
>
{showLabel
@@ -446,7 +442,7 @@ export const CellLinkEdit = () => {
<Input
value={display}
onChange={(v) => {
- setDisplay(v);
+ setNormalizedDisplay(v);
setDisplaySyncedWithPayload(false);
}}
placeholder={localeService.t<LocaleKey>('sheets-hyper-link-ui.form.labelPlaceholder')}
@@ -480,7 +476,7 @@ export const CellLinkEdit = () => {
onChange={(newLink) => {
setPayload(newLink);
if (newLink && (getIsDisplaySyncedWithPayload() || !display || display === newLink)) {
- setDisplay(newLink);
+ setNormalizedDisplay(newLink);
setDisplaySyncedWithPayload(true);
}
}}
@@ -510,11 +506,9 @@ export const CellLinkEdit = () => {
if (editing.type !== HyperLinkEditSourceType.VIEWING) {
editorBridgeService.enableForceKeepVisible();
}
- setHide(true);
} else {
await resolverService.navigateToRange(editing.unitId, editing.subUnitId, { startRow: editing.row, endRow: editing.row, startColumn: editing.col, endColumn: editing.col }, true);
editorBridgeService.disableForceKeepVisible();
- setHide(false);
}
}}
onFocusChange={(focus) => setIsFocusRangeSelector(focus)}
@@ -532,7 +526,7 @@ export const CellLinkEdit = () => {
const label = sheetsOption.find((i) => i.value === newPayload)?.label;
const oldLabel = sheetsOption.find((i) => i.value === payload)?.label;
if (label && (getIsDisplaySyncedWithPayload() || !display || display === oldLabel)) {
- setDisplay(label);
+ setNormalizedDisplay(label);
setDisplaySyncedWithPayload(true);
}
}}
@@ -550,7 +544,7 @@ export const CellLinkEdit = () => {
const label = definedNames.find((i) => i.value === newValue)?.label;
const oldLabel = definedNames.find((i) => i.value === payload)?.label;
if (label && (getIsDisplaySyncedWithPayload() || !display || display === oldLabel)) {
- setDisplay(label);
+ setNormalizedDisplay(label);
setDisplaySyncedWithPayload(true);
}
}}
@@ -566,33 +560,26 @@ export const CellLinkEdit = () => {
getIsDisplaySyncedWithPayload={getIsDisplaySyncedWithPayload}
setDisplaySyncedWithPayload={setDisplaySyncedWithPayload}
setDisplay={(newLink) => {
- setDisplay(newLink);
+ setNormalizedDisplay(newLink);
setDisplaySyncedWithPayload(true);
}}
setPayload={setPayload}
/>
)}
- <ActionRow
- className={clsx(
- 'univer-flex univer-flex-row univer-justify-end univer-gap-2',
- mobile && 'univer-mt-5 univer-w-full'
- )}
- >
+ <ActionRow className="univer-flex univer-flex-row univer-justify-end univer-gap-2">
<Button
- onClick={() => {
+ onClick={async () => {
if (editing) {
- resolverService.navigateToRange(editing.unitId, editing.subUnitId, { startRow: editing.row, endRow: editing.row, startColumn: editing.col, endColumn: editing.col }, true);
+ await resolverService.navigateToRange(editing.unitId, editing.subUnitId, { startRow: editing.row, endRow: editing.row, startColumn: editing.col, endColumn: editing.col }, true);
}
- commandService.executeCommand(CloseHyperLinkPopupOperation.id);
+ await commandService.executeCommand(CloseHyperLinkPopupOperation.id);
}}
>
{localeService.t<LocaleKey>('sheets-hyper-link-ui.form.cancel')}
</Button>
<Button
variant="primary"
- onClick={async () => {
- handleSubmit();
- }}
+ onClick={handleSubmit}
>
{localeService.t<LocaleKey>('sheets-hyper-link-ui.form.ok')}
</Button>
diff --git a/packages/sheets-hyper-link-ui/src/views/CellLinkPopup.tsx b/packages/sheets-hyper-link-ui/src/views/CellLinkPopup.tsx
index 5b6f899ee3..37593abc54 100644
--- a/packages/sheets-hyper-link-ui/src/views/CellLinkPopup.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkPopup.tsx
@@ -17,7 +17,7 @@
import type { ICustomRange, Nullable, Workbook } from '@univerjs/core';
import type { LocaleKey } from '../locale/types';
import { ICommandService, IUniverInstanceService, LocaleService, UniverInstanceType } from '@univerjs/core';
-import { borderClassName, Button, clsx, ConfigContext, MessageType, Tooltip } from '@univerjs/design';
+import { borderClassName, Button, clsx, MessageType, Tooltip } from '@univerjs/design';
import { AllBorderIcon, CopyIcon, LinkIcon, SheetsMultiIcon, UnlinkIcon, WriteIcon } from '@univerjs/icons';
import {
CancelHyperLinkCommand,
@@ -27,12 +27,10 @@ import {
} from '@univerjs/sheets-hyper-link';
import { IEditorBridgeService } from '@univerjs/sheets-ui';
import { IMessageService, useDependency, useObservable } from '@univerjs/ui';
-import { useContext } from 'react';
import { OpenHyperLinkEditPanelOperation } from '../commands/operations/popup.operations';
import { SheetsHyperLinkPopupService } from '../services/popup.service';
import { SheetsHyperLinkResolverService } from '../services/resolver.service';
import { HyperLinkEditSourceType } from '../types/enums/edit-source';
-import { MobileCellLinkPopup } from './MobileCellLinkPopup';
const iconsMap = {
[SheetHyperLinkType.URL]: <LinkIcon />,
@@ -61,7 +59,6 @@ export const CellLinkPopupPure = (props: ICellLinkPopupPureProps) => {
const resolverService = useDependency(SheetsHyperLinkResolverService);
const editorBridgeService = useDependency(IEditorBridgeService);
const parserHyperLinkService = useDependency(SheetsHyperLinkParserService);
- const { mobile } = useContext(ConfigContext);
const { customRange, row, col, unitId, subUnitId, editPermission, copyPermission, type } = props;
if (!customRange?.properties?.url) {
@@ -70,65 +67,6 @@ export const CellLinkPopupPure = (props: ICellLinkPopupPureProps) => {
const linkObj = parserHyperLinkService.parseHyperLink(customRange.properties.url ?? '');
const isError = linkObj.type === SheetHyperLinkType.INVALID;
- if (mobile) {
- const close = () => popupService.hideCurrentPopup(undefined, true);
- return (
- <MobileCellLinkPopup
- name={linkObj.name}
- invalid={isError}
- copyPermission={Boolean(copyPermission)}
- editPermission={Boolean(editPermission)}
- copyText={localeService.t<LocaleKey>('sheets-hyper-link-ui.popup.copy')}
- editText={localeService.t<LocaleKey>('sheets-hyper-link-ui.popup.edit')}
- removeText={localeService.t<LocaleKey>('sheets-hyper-link-ui.popup.cancel')}
- onNavigate={() => {
- resolverService.navigate(linkObj);
- close();
- }}
- onCopy={() => {
- if (linkObj.type !== SheetHyperLinkType.URL) {
- const url = new URL(window.location.href);
- url.hash = linkObj.url.slice(1);
- navigator.clipboard.writeText(url.href);
- } else {
- navigator.clipboard.writeText(linkObj.url);
- }
- messageService.show({
- content: localeService.t<LocaleKey>('sheets-hyper-link-ui.message.coped'),
- type: MessageType.Info,
- });
- close();
- }}
- onEdit={() => {
- close();
- commandService.executeCommand(OpenHyperLinkEditPanelOperation.id, {
- unitId,
- subUnitId,
- row,
- col,
- customRangeId: customRange.rangeId,
- type,
- });
- }}
- onRemove={() => {
- const commandId = type === HyperLinkEditSourceType.EDITING
- ? CancelRichHyperLinkCommand.id
- : CancelHyperLinkCommand.id;
- if (commandService.syncExecuteCommand(commandId, {
- unitId,
- subUnitId,
- id: customRange.rangeId,
- row,
- column: col,
- documentId: editorBridgeService.getCurrentEditorId(),
- })) {
- close();
- }
- }}
- />
- );
- }
-
return (
<div
className={clsx(`
@@ -182,13 +120,13 @@ export const CellLinkPopupPure = (props: ICellLinkPopupPureProps) => {
disabled:!univer-pointer-events-auto
`, { 'univer-text-red-500': isError })}
disabled={!copyPermission || isError}
- onClick={() => {
+ onClick={async () => {
if (linkObj.type !== SheetHyperLinkType.URL) {
const url = new URL(window.location.href);
url.hash = linkObj.url.slice(1);
- navigator.clipboard.writeText(url.href);
+ await navigator.clipboard.writeText(url.href);
} else {
- navigator.clipboard.writeText(linkObj.url);
+ await navigator.clipboard.writeText(linkObj.url);
}
messageService.show({
content: localeService.t<LocaleKey>('sheets-hyper-link-ui.message.coped'),
@@ -211,7 +149,7 @@ export const CellLinkPopupPure = (props: ICellLinkPopupPureProps) => {
dark:hover:!univer-bg-gray-700
`}
onClick={() => {
- commandService.executeCommand(OpenHyperLinkEditPanelOperation.id, {
+ return commandService.executeCommand(OpenHyperLinkEditPanelOperation.id, {
unitId,
subUnitId,
row,
diff --git a/packages/sheets-hyper-link-ui/src/views/MobileCellLinkEdit.tsx b/packages/sheets-hyper-link-ui/src/views/MobileCellLinkEdit.tsx
new file mode 100644
index 0000000000..3ede83e0c8
--- /dev/null
+++ b/packages/sheets-hyper-link-ui/src/views/MobileCellLinkEdit.tsx
@@ -0,0 +1,588 @@
+/**
+ * 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 { DocumentDataModel, Nullable, Workbook } from '@univerjs/core';
+import type { ISelectionWithStyle } from '@univerjs/sheets';
+import type { LocaleKey } from '../locale/types';
+import {
+ BuildTextUtils,
+ ColorKit,
+ CustomRangeType,
+ DataStreamTreeTokenType,
+ DisposableCollection,
+ generateRandomId,
+ ICommandService,
+ IUniverInstanceService,
+ LocaleService,
+ ThemeService,
+ Tools,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { Button, FormLayout, Input, MobileActionRowGroup, MobileSelect } from '@univerjs/design';
+import { DocSelectionManagerService } from '@univerjs/docs';
+import { DocSelectionRenderService } from '@univerjs/docs-ui';
+import {
+ deserializeRangeWithSheet,
+ IDefinedNamesService,
+ serializeRange,
+ serializeRangeWithSheet,
+} from '@univerjs/engine-formula';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { SetWorksheetActiveOperation, SheetsSelectionsService } from '@univerjs/sheets';
+import { MobileRangeSelector } from '@univerjs/sheets-formula-ui';
+import {
+ AddHyperLinkCommand,
+ AddRichHyperLinkCommand,
+ SheetHyperLinkType,
+ SheetsHyperLinkParserService,
+ UpdateHyperLinkCommand,
+ UpdateRichHyperLinkCommand,
+} from '@univerjs/sheets-hyper-link';
+import { IEditorBridgeService, IMarkSelectionService, ScrollToRangeOperation } from '@univerjs/sheets-ui';
+import { KeyCode, useDependency, useEvent, useObservable } from '@univerjs/ui';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { CloseHyperLinkPopupOperation } from '../commands/operations/popup.operations';
+import { isLegalLink, serializeUrl } from '../common/util';
+import { SheetsHyperLinkPopupService } from '../services/popup.service';
+import { SheetsHyperLinkResolverService } from '../services/resolver.service';
+import { SheetsHyperLinkSidePanelService } from '../services/side-panel.service';
+import { HyperLinkEditSourceType } from '../types/enums/edit-source';
+import { isBlankInput, resolveRangePayload } from './CellLinkEdit/utils';
+
+export const MobileCellLinkEdit = () => {
+ const [id, setId] = useState('');
+ const [display, setDisplay] = useState('');
+ const [showLabel, setShowLabel] = useState(true);
+ const [type, setType] = useState<SheetHyperLinkType | string>(SheetHyperLinkType.URL);
+ const [payload, setPayload] = useState('');
+
+ const localeService = useDependency(LocaleService);
+ const definedNameService = useDependency(IDefinedNamesService);
+ const editorBridgeService = useDependency(IEditorBridgeService);
+ const univerInstanceService = useDependency(IUniverInstanceService);
+ const popupService = useDependency(SheetsHyperLinkPopupService);
+ const editing = useObservable(popupService.currentEditing$);
+ const parserService = useDependency(SheetsHyperLinkParserService);
+ const resolverService = useDependency(SheetsHyperLinkResolverService);
+ const commandService = useDependency(ICommandService);
+ const sidePanelService = useDependency(SheetsHyperLinkSidePanelService);
+ const sidePanelOptions = useMemo(() => sidePanelService.getOptions(), [sidePanelService]);
+ const renderManagerService = useDependency(IRenderManagerService);
+ const markSelectionService = useDependency(IMarkSelectionService);
+ const textSelectionService = useDependency(DocSelectionManagerService);
+ const themeService = useDependency(ThemeService);
+ const [selectorDialogVisible, setSelectorDialogVisible] = useState(false);
+ const sheetsSelectionService = useDependency(SheetsSelectionsService);
+ const selections = useMemo(() => sheetsSelectionService.getCurrentSelections(), []);
+
+ const customHyperLinkSidePanel = useMemo(() => {
+ if (sidePanelService.isBuiltInLinkType(type)) {
+ return;
+ }
+ return sidePanelService.getCustomHyperLink(type);
+ }, [sidePanelService, type]);
+
+ const [showError, setShowError] = useState(false);
+
+ const [isFocusRangeSelector, setIsFocusRangeSelector] = useState(false);
+
+ const isDisplaySyncedWithPayloadRef = useRef(false);
+ const getIsDisplaySyncedWithPayload = useEvent(() => isDisplaySyncedWithPayloadRef.current);
+ const setDisplaySyncedWithPayload = useEvent((synced: boolean) => {
+ isDisplaySyncedWithPayloadRef.current = synced;
+ });
+
+ const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);
+
+ const subUnitId = workbook?.getActiveSheet().getSheetId() || '';
+ // to polyfill the display value on old version data
+ // case split tag is no longer needed
+ const setNormalizedDisplay = useCallback((value: string) => {
+ setDisplay(value.replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_START, '').replaceAll(DataStreamTreeTokenType.CUSTOM_RANGE_END, ''));
+ }, [setDisplay]);
+
+ useEffect(() => {
+ if (editing?.row !== undefined && editing.col !== undefined) {
+ const { customRange, row, col } = editing;
+ let { label } = editing;
+ if (typeof label === 'number') {
+ label = `${label}`;
+ }
+
+ let link;
+ if (customRange) {
+ link = {
+ id: customRange?.rangeId ?? '',
+ display: label ?? '',
+ payload: customRange?.properties?.url ?? '',
+ row,
+ column: col,
+ };
+ } else {
+ if (editing.type === HyperLinkEditSourceType.VIEWING) {
+ const workbook = univerInstanceService.getUnit<Workbook>(editing.unitId);
+ const worksheet = workbook?.getSheetBySheetId(editing.subUnitId);
+ const cell = worksheet?.getCellRaw(editing.row, editing.col);
+ const range = cell?.p?.body?.customRanges?.find((range) => range.rangeType === CustomRangeType.HYPERLINK && range.properties?.url);
+ const cellValue = cell?.v;
+ if (cell && (!BuildTextUtils.transform.isEmptyDocument(cell.p?.body?.dataStream) || Tools.isDefine(cellValue))) {
+ setShowLabel(false);
+ }
+ link = {
+ id: '',
+ display: '',
+ payload: range?.properties?.url ?? '',
+ row,
+ column: col,
+ };
+ } else {
+ const doc = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ const currentSelection = textSelectionService.getActiveTextRange();
+ const body = doc?.getBody();
+ const selection = currentSelection && body ? currentSelection : null;
+ const customRange = selection && BuildTextUtils.customRange.getCustomRangesInterestsWithSelection(selection, body?.customRanges ?? [])?.[0];
+
+ setShowLabel(false);
+ link = {
+ id: '',
+ display: label ?? '',
+ payload: customRange?.properties?.url ?? '',
+ row,
+ column: col,
+ };
+ }
+ }
+
+ setId(link.id);
+ const customLink = sidePanelService.findCustomHyperLink(link);
+ if (customLink) {
+ const customLinkInfo = customLink.convert(link);
+ setType(customLinkInfo.type);
+ setPayload(customLinkInfo.payload);
+ setNormalizedDisplay(customLinkInfo.display);
+ return;
+ }
+ setNormalizedDisplay(link.display);
+ const linkInfo = parserService.parseHyperLink(link.payload);
+ setType(linkInfo.type === SheetHyperLinkType.INVALID ? SheetHyperLinkType.RANGE : linkInfo.type);
+ switch (linkInfo.type) {
+ case SheetHyperLinkType.URL: {
+ setPayload(linkInfo.url);
+ if (linkInfo.url === link.display) {
+ setDisplaySyncedWithPayload(true);
+ }
+ break;
+ }
+ case SheetHyperLinkType.RANGE: {
+ const params = linkInfo.searchObj!;
+ const sheetName = params.gid ?
+ univerInstanceService
+ .getUnit<Workbook>(editing.unitId)
+ ?.getSheetBySheetId(params.gid)
+ ?.getName()
+ ?? ''
+ : '';
+ const payload = (serializeRangeWithSheet(sheetName, deserializeRangeWithSheet(params.range!).range));
+ setPayload(payload);
+ if (payload === link.display) {
+ setDisplaySyncedWithPayload(true);
+ }
+ break;
+ }
+ case SheetHyperLinkType.SHEET: {
+ const params = linkInfo.searchObj!;
+ setPayload(params.gid!);
+ break;
+ }
+ case SheetHyperLinkType.DEFINE_NAME: {
+ const params = linkInfo.searchObj!;
+ setPayload(params.rangeid!);
+ break;
+ }
+ default:
+ setPayload('');
+ break;
+ }
+ }
+ }, [editing, resolverService, sidePanelService, textSelectionService, univerInstanceService]);
+
+ useEffect(() => {
+ let id: Nullable<string> = null;
+ if (editing && !editing.customRangeId && editing.type === HyperLinkEditSourceType.VIEWING && Tools.isDefine(editing.row) && Tools.isDefine(editing.col)) {
+ const workbook = univerInstanceService.getUnit<Workbook>(editing.unitId, UniverInstanceType.UNIVER_SHEET);
+ const worksheet = workbook?.getSheetBySheetId(editing.subUnitId);
+ const mergeInfo = worksheet?.getMergedCell(editing.row, editing.col);
+ const color = new ColorKit(themeService.getColorFromTheme('primary.600')).toRgb();
+ id = markSelectionService.addShape(
+ {
+ range: mergeInfo ?? {
+ startColumn: editing.col,
+ endColumn: editing.col,
+ startRow: editing.row,
+ endRow: editing.row,
+ },
+ style: {
+ // hasAutoFill: false,
+ fill: `rgb(${color.r}, ${color.g}, ${color.b}, 0.12)`,
+ strokeWidth: 1,
+ stroke: '#FFBD37',
+ widgets: {},
+ },
+ primary: null,
+ },
+ [],
+ -1
+ );
+ }
+ return () => {
+ if (id) {
+ markSelectionService.removeShape(id);
+ }
+ };
+ }, [editing, markSelectionService, themeService, univerInstanceService]);
+
+ useEffect(() => {
+ setIsFocusRangeSelector(type === SheetHyperLinkType.RANGE);
+ }, [type]);
+
+ useEffect(() => {
+ const render = renderManagerService.getRenderUnitById(editorBridgeService.getCurrentEditorId());
+ const disposeCollection = new DisposableCollection();
+
+ if (render) {
+ const selectionRenderService = render.with(DocSelectionRenderService);
+ selectionRenderService.setReserveRangesStatus(true);
+ disposeCollection.add(() => {
+ selectionRenderService.setReserveRangesStatus(false);
+ });
+ }
+
+ return () => {
+ editorBridgeService.disableForceKeepVisible();
+ disposeCollection.dispose();
+ };
+ }, [editorBridgeService, renderManagerService]);
+
+ useEffect(() => {
+ if (isFocusRangeSelector) {
+ popupService.setIsKeepVisible(isFocusRangeSelector);
+ }
+ popupService.setIsKeepVisible(selectorDialogVisible);
+
+ return () => {
+ popupService.setIsKeepVisible(false);
+ };
+ }, [isFocusRangeSelector, selectorDialogVisible, popupService]);
+
+ useEffect(() => {
+ if (isFocusRangeSelector) {
+ editorBridgeService.enableForceKeepVisible();
+
+ return () => {
+ editorBridgeService.disableForceKeepVisible();
+ };
+ }
+ }, [isFocusRangeSelector, editorBridgeService]);
+
+ const linkTypeOptions: Array<{
+ label: string;
+ value: SheetHyperLinkType | string;
+ }> = [
+ {
+ label: localeService.t<LocaleKey>('sheets-hyper-link-ui.form.link'),
+ value: SheetHyperLinkType.URL,
+ },
+ {
+ label: localeService.t<LocaleKey>('sheets-hyper-link-ui.form.range'),
+ value: SheetHyperLinkType.RANGE,
+ },
+ {
+ label: localeService.t<LocaleKey>('sheets-hyper-link-ui.form.worksheet'),
+ value: SheetHyperLinkType.SHEET,
+ },
+ {
+ label: localeService.t<LocaleKey>('sheets-hyper-link-ui.form.definedName'),
+ value: SheetHyperLinkType.DEFINE_NAME,
+ },
+ ...sidePanelOptions,
+ ];
+
+ const handleRangeChange = useEvent((rangeText: string) => {
+ const newPayload = resolveRangePayload(rangeText, workbook?.getActiveSheet()?.getName() || '');
+ if (!newPayload) {
+ setPayload('');
+ return;
+ }
+
+ setPayload(newPayload);
+
+ if (getIsDisplaySyncedWithPayload() || !display) {
+ setNormalizedDisplay(newPayload);
+ setDisplaySyncedWithPayload(true);
+ }
+ });
+
+ if (!workbook) {
+ return;
+ }
+
+ const hiddens = workbook.getHiddenWorksheets();
+ const sheetsOption = workbook.getSheets().map((sheet) => ({ label: sheet.getName(), value: sheet.getSheetId() })).filter((opt) => hiddens.indexOf(opt.value) === -1);
+ const definedNames = Object.values(definedNameService.getDefinedNameMap(workbook.getUnitId()) ?? {}).map((value) => ({
+ label: value.name,
+ value: value.id,
+ }));
+
+ const formatUrl = (type: SheetHyperLinkType | string, payload: string) => {
+ if (type === SheetHyperLinkType.URL) {
+ return serializeUrl(payload);
+ }
+
+ if (type === SheetHyperLinkType.RANGE) {
+ const info = deserializeRangeWithSheet(payload);
+ const worksheet = workbook.getSheetBySheetName(info.sheetName);
+ if (worksheet) {
+ return `#gid=${worksheet.getSheetId()}&range=${serializeRange(info.range)}`;
+ }
+ }
+
+ return `#${type}=${payload}`;
+ };
+
+ const handleSubmit = async () => {
+ if ((showLabel && isBlankInput(display)) || !payload || (type === SheetHyperLinkType.URL && !isLegalLink(payload))) {
+ setShowError(true);
+ return;
+ }
+
+ if (editing) {
+ if (id) {
+ const commandId = editing.type === HyperLinkEditSourceType.EDITING ? UpdateRichHyperLinkCommand.id : UpdateHyperLinkCommand.id;
+ await commandService.executeCommand(commandId, {
+ id,
+ unitId: editing.unitId,
+ subUnitId: editing.subUnitId,
+ payload: {
+ display: showLabel ? display : '',
+ payload: formatUrl(type, payload),
+ },
+ row: editing.row,
+ column: editing.col,
+ documentId: editorBridgeService.getCurrentEditorId(),
+ });
+ } else {
+ const commandId = editing.type === HyperLinkEditSourceType.EDITING ? AddRichHyperLinkCommand.id : AddHyperLinkCommand.id;
+ await commandService.executeCommand(commandId, {
+ unitId: editing.unitId,
+ subUnitId: editing.subUnitId,
+ link: {
+ id: generateRandomId(),
+ row: editing.row,
+ column: editing.col,
+ payload: formatUrl(type, payload),
+ display: showLabel ? display : '',
+ },
+ documentId: editorBridgeService.getCurrentEditorId(),
+ });
+ }
+ }
+ if (editing?.type === HyperLinkEditSourceType.VIEWING) {
+ await commandService.executeCommand(SetWorksheetActiveOperation.id, {
+ unitId: editing.unitId,
+ subUnitId: editing.subUnitId,
+ });
+
+ const GAP = 1;
+ await commandService.executeCommand(ScrollToRangeOperation.id, {
+ range: {
+ startRow: Math.max(editing.row - GAP, 0),
+ endRow: editing.row + GAP,
+ startColumn: Math.max(editing.col - GAP, 0),
+ endColumn: editing.col + GAP,
+ },
+ });
+ }
+
+ await commandService.executeCommand(CloseHyperLinkPopupOperation.id);
+ };
+
+ if (!editing) {
+ return null;
+ }
+
+ return (
+ <div
+ className="
+ univer-box-border univer-w-full univer-bg-gray-0 univer-p-0
+ dark:!univer-bg-gray-900
+ "
+ >
+ {showLabel
+ ? (
+ <FormLayout
+ label={localeService.t<LocaleKey>('sheets-hyper-link-ui.form.label')}
+ error={showError && isBlankInput(display) ? localeService.t<LocaleKey>('sheets-hyper-link-ui.form.inputError') : ''}
+ >
+ <Input
+ value={display}
+ onChange={(v) => {
+ setNormalizedDisplay(v);
+ setDisplaySyncedWithPayload(false);
+ }}
+ placeholder={localeService.t<LocaleKey>('sheets-hyper-link-ui.form.labelPlaceholder')}
+ autoFocus
+ onKeyDown={(e) => {
+ if (e.keyCode === KeyCode.ENTER) {
+ handleSubmit();
+ }
+ }}
+ />
+ </FormLayout>
+ )
+ : null}
+ <FormLayout label={localeService.t<LocaleKey>('sheets-hyper-link-ui.form.type')}>
+ <MobileSelect
+ className="univer-w-full"
+ options={linkTypeOptions}
+ value={type}
+ onChange={(newType) => {
+ setType(newType as SheetHyperLinkType);
+ setPayload('');
+ }}
+ />
+ </FormLayout>
+ {type === SheetHyperLinkType.URL && (
+ <FormLayout
+ error={showError ? !payload ? localeService.t<LocaleKey>('sheets-hyper-link-ui.form.inputError') : !isLegalLink(payload) ? localeService.t<LocaleKey>('sheets-hyper-link-ui.form.linkError') : '' : ''}
+ >
+ <Input
+ value={payload}
+ onChange={(newLink) => {
+ setPayload(newLink);
+ if (newLink && (getIsDisplaySyncedWithPayload() || !display || display === newLink)) {
+ setNormalizedDisplay(newLink);
+ setDisplaySyncedWithPayload(true);
+ }
+ }}
+ placeholder={localeService.t<LocaleKey>('sheets-hyper-link-ui.form.linkPlaceholder')}
+ autoFocus
+ onKeyDown={(e) => {
+ if (e.keyCode === KeyCode.ENTER) {
+ handleSubmit();
+ }
+ }}
+ />
+ </FormLayout>
+ )}
+ {type === SheetHyperLinkType.RANGE && (
+ <FormLayout error={showError && !payload ? localeService.t<LocaleKey>('sheets-hyper-link-ui.form.inputError') : ''}>
+ <MobileRangeSelector
+ unitId={workbook.getUnitId()}
+ subUnitId={subUnitId}
+ maxRangeCount={1}
+ supportAcrossSheet
+ initialValue={payload}
+ resetRange={selections as ISelectionWithStyle[]}
+ onChange={(_, text) => handleRangeChange(text)}
+ onRangeSelectorDialogVisibleChange={async (visible) => {
+ setSelectorDialogVisible(visible);
+ if (visible) {
+ if (editing.type !== HyperLinkEditSourceType.VIEWING) {
+ editorBridgeService.enableForceKeepVisible();
+ }
+ } else {
+ await resolverService.navigateToRange(editing.unitId, editing.subUnitId, { startRow: editing.row, endRow: editing.row, startColumn: editing.col, endColumn: editing.col }, true);
+ editorBridgeService.disableForceKeepVisible();
+ }
+ }}
+ onFocusChange={(focus) => setIsFocusRangeSelector(focus)}
+ />
+ </FormLayout>
+ )}
+ {type === SheetHyperLinkType.SHEET && (
+ <FormLayout error={showError && !payload ? localeService.t<LocaleKey>('sheets-hyper-link-ui.form.selectError') : ''}>
+ <MobileSelect
+ className="univer-w-full"
+ options={sheetsOption}
+ value={payload}
+ onChange={(newPayload) => {
+ setPayload(newPayload);
+ const label = sheetsOption.find((i) => i.value === newPayload)?.label;
+ const oldLabel = sheetsOption.find((i) => i.value === payload)?.label;
+ if (label && (getIsDisplaySyncedWithPayload() || !display || display === oldLabel)) {
+ setNormalizedDisplay(label);
+ setDisplaySyncedWithPayload(true);
+ }
+ }}
+ />
+ </FormLayout>
+ )}
+ {type === SheetHyperLinkType.DEFINE_NAME && (
+ <FormLayout error={showError && !payload ? localeService.t<LocaleKey>('sheets-hyper-link-ui.form.selectError') : ''}>
+ <MobileSelect
+ className="univer-w-full"
+ options={definedNames}
+ value={payload}
+ onChange={(newValue) => {
+ setPayload(newValue);
+ const label = definedNames.find((i) => i.value === newValue)?.label;
+ const oldLabel = definedNames.find((i) => i.value === payload)?.label;
+ if (label && (getIsDisplaySyncedWithPayload() || !display || display === oldLabel)) {
+ setNormalizedDisplay(label);
+ setDisplaySyncedWithPayload(true);
+ }
+ }}
+ />
+ </FormLayout>
+ )}
+ {customHyperLinkSidePanel?.Form && (
+ <customHyperLinkSidePanel.Form
+ linkId={id}
+ payload={payload}
+ display={display}
+ showError={showError}
+ getIsDisplaySyncedWithPayload={getIsDisplaySyncedWithPayload}
+ setDisplaySyncedWithPayload={setDisplaySyncedWithPayload}
+ setDisplay={(newLink) => {
+ setNormalizedDisplay(newLink);
+ setDisplaySyncedWithPayload(true);
+ }}
+ setPayload={setPayload}
+ />
+ )}
+ <MobileActionRowGroup className="univer-mt-5">
+ <Button
+ onClick={async () => {
+ if (editing) {
+ await resolverService.navigateToRange(editing.unitId, editing.subUnitId, { startRow: editing.row, endRow: editing.row, startColumn: editing.col, endColumn: editing.col }, true);
+ }
+ await commandService.executeCommand(CloseHyperLinkPopupOperation.id);
+ }}
+ >
+ {localeService.t<LocaleKey>('sheets-hyper-link-ui.form.cancel')}
+ </Button>
+ <Button
+ variant="primary"
+ onClick={handleSubmit}
+ >
+ {localeService.t<LocaleKey>('sheets-hyper-link-ui.form.ok')}
+ </Button>
+ </MobileActionRowGroup>
+ </div>
+ );
+};
+
+MobileCellLinkEdit.componentKey = 'univer.sheet.mobile-cell-link-edit';
diff --git a/packages/sheets-hyper-link-ui/src/views/MobileCellLinkPopup.tsx b/packages/sheets-hyper-link-ui/src/views/MobileCellLinkPopup.tsx
index 85582a27fe..99844a5162 100644
--- a/packages/sheets-hyper-link-ui/src/views/MobileCellLinkPopup.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/MobileCellLinkPopup.tsx
@@ -14,47 +14,165 @@
* limitations under the License.
*/
-import { MobileActionRow } from '@univerjs/design';
-
-interface IMobileCellLinkPopupProps {
- name: string;
- copyText: string;
- editText: string;
- removeText: string;
- invalid: boolean;
- copyPermission: boolean;
- editPermission: boolean;
- onNavigate: () => void;
- onCopy: () => void;
- onEdit: () => void;
- onRemove: () => void;
+import type { ICustomRange, Nullable, Workbook } from '@univerjs/core';
+import type { LocaleKey } from '../locale/types';
+import { ICommandService, IUniverInstanceService, LocaleService, UniverInstanceType } from '@univerjs/core';
+import { MessageType, MobileActionRow } from '@univerjs/design';
+import {
+ CancelHyperLinkCommand,
+ CancelRichHyperLinkCommand,
+ SheetHyperLinkType,
+ SheetsHyperLinkParserService,
+} from '@univerjs/sheets-hyper-link';
+import { IEditorBridgeService } from '@univerjs/sheets-ui';
+import { IMessageService, useDependency, useObservable } from '@univerjs/ui';
+import { OpenHyperLinkEditPanelOperation } from '../commands/operations/popup.operations';
+import { SheetsHyperLinkPopupService } from '../services/popup.service';
+import { SheetsHyperLinkResolverService } from '../services/resolver.service';
+import { HyperLinkEditSourceType } from '../types/enums/edit-source';
+
+interface IMobileCellLinkPopupPureProps {
+ customRange?: Nullable<ICustomRange>;
+ row: number;
+ col: number;
+ unitId: string;
+ subUnitId: string;
+ editPermission?: boolean;
+ copyPermission?: boolean;
+ type: HyperLinkEditSourceType;
}
-export function MobileCellLinkPopup(props: IMobileCellLinkPopupProps) {
+export function MobileCellLinkPopupPure(props: IMobileCellLinkPopupPureProps) {
+ const popupService = useDependency(SheetsHyperLinkPopupService);
+ const commandService = useDependency(ICommandService);
+ const messageService = useDependency(IMessageService);
+ const localeService = useDependency(LocaleService);
+ const resolverService = useDependency(SheetsHyperLinkResolverService);
+ const editorBridgeService = useDependency(IEditorBridgeService);
+ const parserHyperLinkService = useDependency(SheetsHyperLinkParserService);
+ const { customRange, row, col, unitId, subUnitId, editPermission, copyPermission, type } = props;
+
+ if (!customRange?.properties?.url) {
+ return null;
+ }
+
+ const linkObj = parserHyperLinkService.parseHyperLink(customRange.properties.url);
+ const isError = linkObj.type === SheetHyperLinkType.INVALID;
+ const close = () => popupService.hideCurrentPopup(undefined, true);
+
return (
<div className="univer-flex univer-flex-col univer-gap-2">
<MobileActionRow
- title={<span className="univer-truncate">{props.name}</span>}
- aria-label={props.name}
+ title={localeService.t<LocaleKey>('sheets-hyper-link-ui.popup.open')}
+ value={linkObj.name}
+ valueType="text"
+ aria-label={localeService.t<LocaleKey>('sheets-hyper-link-ui.popup.open')}
variant="subtle"
- disabled={props.invalid}
- onClick={props.onNavigate}
+ disabled={isError}
+ onClick={() => {
+ resolverService.navigate(linkObj);
+ close();
+ }}
/>
- {props.copyPermission && (
+ {copyPermission && (
<MobileActionRow
- title={props.copyText}
- aria-label={props.copyText}
+ title={localeService.t<LocaleKey>('sheets-hyper-link-ui.popup.copy')}
+ aria-label={localeService.t<LocaleKey>('sheets-hyper-link-ui.popup.copy')}
variant="subtle"
- disabled={props.invalid}
- onClick={props.onCopy}
+ disabled={isError}
+ onClick={() => {
+ let url = linkObj.url;
+ if (linkObj.type !== SheetHyperLinkType.URL) {
+ const currentUrl = new URL(window.location.href);
+ currentUrl.hash = linkObj.url.slice(1);
+ url = currentUrl.href;
+ }
+
+ return navigator.clipboard.writeText(url).then(() => {
+ messageService.show({
+ content: localeService.t<LocaleKey>('sheets-hyper-link-ui.message.coped'),
+ type: MessageType.Info,
+ });
+ close();
+ });
+ }}
/>
)}
- {props.editPermission && (
+ {editPermission && (
<>
- <MobileActionRow title={props.editText} aria-label={props.editText} variant="subtle" onClick={props.onEdit} />
- <MobileActionRow title={props.removeText} aria-label={props.removeText} variant="subtle" onClick={props.onRemove} />
+ <MobileActionRow
+ title={localeService.t<LocaleKey>('sheets-hyper-link-ui.popup.edit')}
+ aria-label={localeService.t<LocaleKey>('sheets-hyper-link-ui.popup.edit')}
+ variant="subtle"
+ onClick={() => {
+ close();
+ return commandService.executeCommand(OpenHyperLinkEditPanelOperation.id, {
+ unitId,
+ subUnitId,
+ row,
+ col,
+ customRangeId: customRange.rangeId,
+ type,
+ });
+ }}
+ />
+ <MobileActionRow
+ title={localeService.t<LocaleKey>('sheets-hyper-link-ui.popup.cancel')}
+ aria-label={localeService.t<LocaleKey>('sheets-hyper-link-ui.popup.cancel')}
+ variant="subtle"
+ onClick={() => {
+ const commandId = type === HyperLinkEditSourceType.EDITING
+ ? CancelRichHyperLinkCommand.id
+ : CancelHyperLinkCommand.id;
+ if (commandService.syncExecuteCommand(commandId, {
+ unitId,
+ subUnitId,
+ id: customRange.rangeId,
+ row,
+ column: col,
+ documentId: editorBridgeService.getCurrentEditorId(),
+ })) {
+ close();
+ }
+ }}
+ />
</>
)}
</div>
);
}
+
+export function MobileCellLinkPopup() {
+ const popupService = useDependency(SheetsHyperLinkPopupService);
+ const currentPopup = useObservable(popupService.currentPopup$, popupService.currentPopup);
+ const univerInstanceService = useDependency(IUniverInstanceService);
+
+ if (!currentPopup) {
+ return null;
+ }
+
+ if (currentPopup.showAll) {
+ const workbook = univerInstanceService.getUnit<Workbook>(currentPopup.unitId, UniverInstanceType.UNIVER_SHEET);
+ const worksheet = workbook?.getSheetBySheetId(currentPopup.subUnitId);
+ const cell = worksheet?.getCell(currentPopup.row, currentPopup.col);
+ const customRanges = cell?.p?.body?.customRanges;
+
+ return customRanges?.length
+ ? (
+ <div>
+ {customRanges.map((customRange) => (
+ <MobileCellLinkPopupPure
+ key={customRange.rangeId}
+ {...currentPopup}
+ customRange={customRange}
+ />
+ ))}
+ </div>
+ )
+ : null;
+ }
+
+ return <MobileCellLinkPopupPure {...currentPopup} />;
+}
+
+MobileCellLinkPopup.componentKey = 'univer.sheet.mobile-cell-link-popup';
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 cba2cf34b7..ede0486aa4 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 { MobileCellLinkPopupPure } from '../MobileCellLinkPopup';
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -277,6 +278,7 @@ function createPopupTestBed() {
[LocaleType.EN_US]: {
'sheets-hyper-link-ui': {
popup: {
+ open: 'Open link',
edit: 'Edit',
cancel: 'Remove link',
},
@@ -306,7 +308,6 @@ function createPopupTestBed() {
},
},
});
-
const commandService = injector.get(ICommandService);
commandService.registerCommand(SetRangeValuesMutation);
commandService.registerCommand(AddHyperLinkMutation);
@@ -423,6 +424,33 @@ describe('CellLinkPopupPure', () => {
});
});
+ it('labels the mobile navigation action and shows the hyperlink name', () => {
+ currentTestBed = createPopupTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ currentTestBed.injector.get(LocaleService).setLocale(LocaleType.EN_US);
+
+ act(() => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <MobileCellLinkPopupPure
+ unitId={UNIT_ID}
+ subUnitId={SUB_UNIT_ID}
+ row={0}
+ col={0}
+ customRange={currentTestBed!.customRange}
+ type={HyperLinkEditSourceType.VIEWING}
+ />
+ </RediContext.Provider>
+ );
+ });
+
+ const openLinkButton = container.querySelector('button');
+ expect(openLinkButton?.textContent).toContain('Open link');
+ expect(openLinkButton?.textContent).toContain('https://univer.ai');
+ });
+
it('removes the hyperlink custom range from the sheet cell', () => {
currentTestBed = createPopupTestBed();
container = document.createElement('div');
diff --git a/packages/sheets-numfmt-ui/src/controllers/mobile/components.controller.ts b/packages/sheets-numfmt-ui/src/controllers/mobile/components.controller.ts
new file mode 100644
index 0000000000..24c13a2ba9
--- /dev/null
+++ b/packages/sheets-numfmt-ui/src/controllers/mobile/components.controller.ts
@@ -0,0 +1,28 @@
+/**
+ * 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 { Disposable, Inject } from '@univerjs/core';
+import { ComponentManager } from '@univerjs/ui';
+import { MOBILE_CUSTOM_NUMFMT_COMPONENT } from '../../menu/mobile-menu';
+import { MobileCustomFormat } from '../../views/mobile/MobileCustomFormat';
+
+export class MobileComponentsController extends Disposable {
+ constructor(@Inject(ComponentManager) componentManager: ComponentManager) {
+ super();
+
+ this.disposeWithMe(componentManager.register(MOBILE_CUSTOM_NUMFMT_COMPONENT, MobileCustomFormat));
+ }
+}
diff --git a/packages/sheets-numfmt-ui/src/controllers/mobile/ui.controller.ts b/packages/sheets-numfmt-ui/src/controllers/mobile/ui.controller.ts
new file mode 100644
index 0000000000..e308e33c2a
--- /dev/null
+++ b/packages/sheets-numfmt-ui/src/controllers/mobile/ui.controller.ts
@@ -0,0 +1,80 @@
+/**
+ * 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 { Workbook } from '@univerjs/core';
+import type { ISetNumfmtMutationParams } from '@univerjs/sheets';
+import { Disposable, ICommandService, Inject, IUniverInstanceService, LocaleService, UniverInstanceType } from '@univerjs/core';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { RemoveNumfmtMutation, SetNumfmtMutation } from '@univerjs/sheets';
+import { SheetsNumfmtCellContentController } from '@univerjs/sheets-numfmt';
+import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import { merge, Observable } from 'rxjs';
+import { debounceTime } from 'rxjs/operators';
+import { SetMobileNumfmtCommand } from '../../commands/commands/set-mobile-numfmt.command';
+
+export class SheetNumfmtMobileUIController extends Disposable {
+ constructor(
+ @ICommandService private readonly _commandService: ICommandService,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @Inject(LocaleService) private readonly _localeService: LocaleService,
+ @Inject(SheetsNumfmtCellContentController)
+ private readonly _sheetsNumfmtCellContentController: SheetsNumfmtCellContentController
+ ) {
+ super();
+
+ this.disposeWithMe(this._commandService.registerCommand(SetMobileNumfmtCommand));
+ this._initNumfmtLocalChange();
+ this._initCommandExecutedListener();
+ }
+
+ private _initNumfmtLocalChange(): void {
+ this.disposeWithMe(
+ merge(
+ this._sheetsNumfmtCellContentController.locale$,
+ this._localeService.currentLocale$
+ ).subscribe(() => this._forceUpdate())
+ );
+ }
+
+ private _initCommandExecutedListener(): void {
+ const commandList = [RemoveNumfmtMutation.id, SetNumfmtMutation.id];
+ this.disposeWithMe(
+ new Observable<string>((subscribe) => {
+ const disposable = this._commandService.onCommandExecuted((command) => {
+ if (commandList.includes(command.id)) {
+ const params = command.params as ISetNumfmtMutationParams;
+ subscribe.next(params.unitId);
+ }
+ });
+ return () => disposable.dispose();
+ }).pipe(debounceTime(16)).subscribe((unitId) => this._forceUpdate(unitId))
+ );
+ }
+
+ private _forceUpdate(unitId?: string): void {
+ const resolvedUnitId = unitId ?? this._univerInstanceService
+ .getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)
+ ?.getUnitId();
+ if (!resolvedUnitId) {
+ return;
+ }
+
+ const renderUnit = this._renderManagerService.getRenderUnitById(resolvedUnitId);
+ renderUnit?.with(SheetSkeletonManagerService).reCalculate();
+ renderUnit?.mainComponent?.makeDirty();
+ }
+}
diff --git a/packages/sheets-numfmt-ui/src/controllers/ui.controller.ts b/packages/sheets-numfmt-ui/src/controllers/ui.controller.ts
index 3a9f2bb2de..238d8574c3 100644
--- a/packages/sheets-numfmt-ui/src/controllers/ui.controller.ts
+++ b/packages/sheets-numfmt-ui/src/controllers/ui.controller.ts
@@ -52,7 +52,6 @@ import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';
import { ISidebarService } from '@univerjs/ui';
import { combineLatest, merge, Observable } from 'rxjs';
import { debounceTime, map, switchMap, tap } from 'rxjs/operators';
-import { SetMobileNumfmtCommand } from '../commands/commands/set-mobile-numfmt.command';
import { CloseNumfmtPanelOperator } from '../commands/operations/close.numfmt.panel.operation';
import { OpenNumfmtPanelOperator } from '../commands/operations/open.numfmt.panel.operation';
@@ -189,7 +188,6 @@ export class SheetNumfmtUIController extends Disposable {
[
OpenNumfmtPanelOperator,
CloseNumfmtPanelOperator,
- SetMobileNumfmtCommand,
].forEach((config) => {
this.disposeWithMe(this._commandService.registerCommand(config));
});
diff --git a/packages/sheets-numfmt-ui/src/index.ts b/packages/sheets-numfmt-ui/src/index.ts
index 8e227d294f..238c0991a0 100644
--- a/packages/sheets-numfmt-ui/src/index.ts
+++ b/packages/sheets-numfmt-ui/src/index.ts
@@ -18,4 +18,5 @@ import './global.css';
export type { IUniverSheetsNumfmtUIConfig } from './config/config';
export { menuSchema as SheetsNumfmtUIMenuSchema } from './menu/schema';
+export { UniverSheetsNumfmtMobileUIPlugin } from './mobile-plugin';
export { UniverSheetsNumfmtUIPlugin } from './plugin';
diff --git a/packages/sheets-numfmt-ui/src/menu/menu.ts b/packages/sheets-numfmt-ui/src/menu/menu.ts
index e6aba7a404..2bcbba2108 100644
--- a/packages/sheets-numfmt-ui/src/menu/menu.ts
+++ b/packages/sheets-numfmt-ui/src/menu/menu.ts
@@ -18,7 +18,6 @@ import type { IAccessor } from '@univerjs/core';
import type { IMenuButtonItem, IMenuSelectorItem } from '@univerjs/ui';
import type { LocaleKey } from '../locale/types';
import {
- DEFAULT_TEXT_FORMAT_EXCEL,
fromCallback,
ICommandService,
isDefaultFormat,
@@ -39,11 +38,8 @@ import {
} from '@univerjs/sheets';
import {
AddDecimalCommand,
- CURRENCYFORMAT,
- DATEFMTLISG,
getCurrencySymbolByLocale,
getCurrencySymbolIconByLocale,
- NUMBERFORMAT,
SetCurrencyCommand,
SetPercentCommand,
SubtractDecimalCommand,
@@ -51,134 +47,9 @@ import {
import { deriveStateFromActiveSheet$, getCurrentRangeDisable$ } from '@univerjs/sheets-ui';
import { getMenuHiddenObservable, MenuItemType } from '@univerjs/ui';
import { filter, map, merge, Observable } from 'rxjs';
-import { SetMobileNumfmtCommand } from '../commands/commands/set-mobile-numfmt.command';
import { OpenNumfmtPanelOperator } from '../commands/operations/open.numfmt.panel.operation';
import { MORE_NUMFMT_TYPE_KEY, OPTIONS_KEY } from '../views/components/MoreNumfmtType';
-
-export const MENU_OPTIONS = (currencySymbol: string): Array<{
- label: LocaleKey;
- pattern: string | null;
-} | '|'> => {
- return [
- {
- label: 'sheets-numfmt-ui.general',
- pattern: null,
- },
- {
- label: 'sheets-numfmt-ui.text',
- pattern: DEFAULT_TEXT_FORMAT_EXCEL,
- },
- '|',
- {
- label: 'sheets-numfmt-ui.number',
- pattern: '0',
- },
- {
- label: 'sheets-numfmt-ui.percent',
- pattern: '0.00%',
- },
- {
- label: 'sheets-numfmt-ui.scientific',
- pattern: '0.00E+00',
- },
- '|',
- {
- label: 'sheets-numfmt-ui.accounting',
- pattern: `"${currencySymbol}" #,##0.00_);[Red]("${currencySymbol}"#,##0.00)`,
- },
- {
- label: 'sheets-numfmt-ui.financialValue',
- pattern: '#,##0.00;[Red]#,##0.00',
- },
- {
- label: 'sheets-numfmt-ui.currency',
- pattern: `"${currencySymbol}"#,##0.00_);[Red]("${currencySymbol}"#,##0.00)`,
- },
- {
- label: 'sheets-numfmt-ui.roundingCurrency',
- pattern: `"${currencySymbol}"#,##0;[Red]"${currencySymbol}"#,##0`,
- },
- '|',
- {
- label: 'sheets-numfmt-ui.date',
- pattern: 'yyyy-mm-dd;@',
- },
- {
- label: 'sheets-numfmt-ui.time',
- pattern: 'am/pm h":"mm":"ss',
- },
- {
- label: 'sheets-numfmt-ui.dateTime',
- pattern: 'yyyy-m-d am/pm h:mm',
- },
- {
- label: 'sheets-numfmt-ui.timeDuration',
- pattern: 'h:mm:ss',
- },
- '|',
- {
- label: 'sheets-numfmt-ui.moreFmt',
- pattern: '',
- },
- ];
-};
-
-export interface IMobileNumberFormatMenuConfig {
- kind: 'number-format';
- title: LocaleKey;
- commandId: string;
- detailTitle: LocaleKey;
- customTitle: LocaleKey;
- quickOptions: Array<{
- label: LocaleKey;
- commandId: string;
- value?: string;
- }>;
- decimalOptions: Array<{
- label: LocaleKey;
- commandId: string;
- }>;
- detailOptions: Array<{
- label?: LocaleKey;
- value?: string | null;
- divider?: boolean;
- custom?: boolean;
- }>;
- customPatterns: string[];
-}
-
-function createMobileNumberFormatMenuConfig(currencySymbol: string): IMobileNumberFormatMenuConfig {
- const detailOptions: IMobileNumberFormatMenuConfig['detailOptions'] = MENU_OPTIONS(currencySymbol)
- .slice(0, -1)
- .map((item) => item === '|'
- ? { divider: true }
- : { label: item.label, value: item.pattern });
- detailOptions.push({ label: 'sheets-numfmt-ui.customFormat', custom: true });
-
- return {
- kind: 'number-format',
- title: 'sheets-numfmt-ui.title',
- commandId: SetMobileNumfmtCommand.id,
- detailTitle: 'sheets-numfmt-ui.moreFmt',
- customTitle: 'sheets-numfmt-ui.customFormat',
- quickOptions: [
- { label: 'sheets-numfmt-ui.percent', commandId: SetPercentCommand.id },
- { label: 'sheets-numfmt-ui.currency', commandId: SetCurrencyCommand.id },
- { label: 'sheets-numfmt-ui.date', commandId: SetMobileNumfmtCommand.id, value: 'yyyy-mm-dd;@' },
- { label: 'sheets-numfmt-ui.text', commandId: SetMobileNumfmtCommand.id, value: DEFAULT_TEXT_FORMAT_EXCEL },
- ],
- decimalOptions: [
- { label: 'sheets-numfmt-ui.subtractDecimal', commandId: SubtractDecimalCommand.id },
- { label: 'sheets-numfmt-ui.addDecimal', commandId: AddDecimalCommand.id },
- ],
- detailOptions,
- customPatterns: [...new Set([
- ...CURRENCYFORMAT.map((item) => item.suffix(currencySymbol)),
- ...DATEFMTLISG.map((item) => item.suffix),
- ...NUMBERFORMAT.map((item) => item.suffix),
- ])],
- };
-}
+import { MENU_OPTIONS } from './number-format-options';
export function CurrencySymbolIconMenuItem(accessor: IAccessor): IMenuButtonItem<LocaleKey> {
const regionService = accessor.get(RegionService);
@@ -247,7 +118,7 @@ export function PercentMenuItem(accessor: IAccessor): IMenuButtonItem<LocaleKey>
};
};
-export function FactoryOtherMenuItem(accessor: IAccessor): IMenuSelectorItem<LocaleKey, string> & { mobileStyle: IMobileNumberFormatMenuConfig } {
+export function FactoryOtherMenuItem(accessor: IAccessor): IMenuSelectorItem<LocaleKey, string> {
const univerInstanceService = accessor.get(IUniverInstanceService);
const commandService = accessor.get(ICommandService);
const localeService = accessor.get(LocaleService);
@@ -320,6 +191,5 @@ export function FactoryOtherMenuItem(accessor: IAccessor): IMenuSelectorItem<Loc
worksheetTypes: [WorksheetSetCellStylePermission, WorksheetEditPermission],
rangeTypes: [RangeProtectionPermissionEditPoint],
}),
- mobileStyle: createMobileNumberFormatMenuConfig(getCurrencySymbolByLocale(regionService.getCurrentRegion())),
};
};
diff --git a/packages/sheets-numfmt-ui/src/menu/mobile-menu.ts b/packages/sheets-numfmt-ui/src/menu/mobile-menu.ts
new file mode 100644
index 0000000000..50af24323e
--- /dev/null
+++ b/packages/sheets-numfmt-ui/src/menu/mobile-menu.ts
@@ -0,0 +1,192 @@
+/**
+ * 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 { IAccessor } from '@univerjs/core';
+import type { IMenuSelectorItem } from '@univerjs/ui';
+import type { LocaleKey } from '../locale/types';
+import {
+ DEFAULT_TEXT_FORMAT_EXCEL,
+ fromCallback,
+ ICommandService,
+ isDefaultFormat,
+ isPatternEqualWithoutDecimal,
+ IUniverInstanceService,
+ LocaleService,
+ RegionService,
+ UniverInstanceType,
+} from '@univerjs/core';
+import {
+ RangeProtectionPermissionEditPoint,
+ RemoveNumfmtMutation,
+ SetNumfmtMutation,
+ SheetsSelectionsService,
+ WorkbookEditablePermission,
+ WorksheetEditPermission,
+ WorksheetSetCellStylePermission,
+} from '@univerjs/sheets';
+import {
+ AddDecimalCommand,
+ CURRENCYFORMAT,
+ DATEFMTLISG,
+ getCurrencySymbolByLocale,
+ NUMBERFORMAT,
+ SetCurrencyCommand,
+ SetPercentCommand,
+ SubtractDecimalCommand,
+} from '@univerjs/sheets-numfmt';
+import { deriveStateFromActiveSheet$, getCurrentRangeDisable$ } from '@univerjs/sheets-ui';
+import { getMenuHiddenObservable, MenuItemType } from '@univerjs/ui';
+import { filter, merge, Observable } from 'rxjs';
+import { SetMobileNumfmtCommand } from '../commands/commands/set-mobile-numfmt.command';
+import { MENU_OPTIONS } from './number-format-options';
+
+export const MOBILE_NUMFMT_MENU_ID = 'sheet.menu.mobile.numfmt';
+export const MOBILE_CUSTOM_NUMFMT_COMPONENT = 'sheets-numfmt-ui.mobile.custom-format';
+
+export interface IMobileNumberFormatMenuConfig {
+ kind: 'number-format';
+ title: LocaleKey;
+ commandId: string;
+ detailTitle: LocaleKey;
+ customTitle: LocaleKey;
+ customComponent: string;
+ quickOptions: Array<{
+ label: LocaleKey;
+ commandId: string;
+ value?: string;
+ }>;
+ decimalOptions: Array<{
+ label: LocaleKey;
+ commandId: string;
+ }>;
+ detailOptions: Array<{
+ label?: LocaleKey;
+ value?: string | null;
+ divider?: boolean;
+ custom?: boolean;
+ }>;
+ customPatterns: string[];
+}
+
+export function createMobileNumberFormatMenuConfig(currencySymbol: string): IMobileNumberFormatMenuConfig {
+ const detailOptions: IMobileNumberFormatMenuConfig['detailOptions'] = MENU_OPTIONS(currencySymbol)
+ .slice(0, -1)
+ .map((item) => item === '|'
+ ? { divider: true }
+ : { label: item.label, value: item.pattern });
+ detailOptions.push({ label: 'sheets-numfmt-ui.customFormat', custom: true });
+
+ return {
+ kind: 'number-format',
+ title: 'sheets-numfmt-ui.title',
+ commandId: SetMobileNumfmtCommand.id,
+ detailTitle: 'sheets-numfmt-ui.moreFmt',
+ customTitle: 'sheets-numfmt-ui.customFormat',
+ customComponent: MOBILE_CUSTOM_NUMFMT_COMPONENT,
+ quickOptions: [
+ { label: 'sheets-numfmt-ui.percent', commandId: SetPercentCommand.id },
+ { label: 'sheets-numfmt-ui.currency', commandId: SetCurrencyCommand.id },
+ { label: 'sheets-numfmt-ui.date', commandId: SetMobileNumfmtCommand.id, value: 'yyyy-mm-dd;@' },
+ {
+ label: 'sheets-numfmt-ui.text',
+ commandId: SetMobileNumfmtCommand.id,
+ value: DEFAULT_TEXT_FORMAT_EXCEL,
+ },
+ ],
+ decimalOptions: [
+ { label: 'sheets-numfmt-ui.subtractDecimal', commandId: SubtractDecimalCommand.id },
+ { label: 'sheets-numfmt-ui.addDecimal', commandId: AddDecimalCommand.id },
+ ],
+ detailOptions,
+ customPatterns: [...new Set([
+ ...CURRENCYFORMAT.map((item) => item.suffix(currencySymbol)),
+ ...DATEFMTLISG.map((item) => item.suffix),
+ ...NUMBERFORMAT.map((item) => item.suffix),
+ ])],
+ };
+}
+
+export function FactoryMobileOtherMenuItem(
+ accessor: IAccessor
+): IMenuSelectorItem<LocaleKey, string> & { mobileNumberFormat: IMobileNumberFormatMenuConfig } {
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+ const commandService = accessor.get(ICommandService);
+ const localeService = accessor.get(LocaleService);
+ const regionService = accessor.get(RegionService);
+ const selectionManagerService = accessor.get(SheetsSelectionsService);
+ const commandList = [RemoveNumfmtMutation.id, SetNumfmtMutation.id];
+ const value$ = deriveStateFromActiveSheet$(
+ univerInstanceService,
+ '',
+ ({ workbook, worksheet }) => new Observable((subscribe) =>
+ merge(
+ selectionManagerService.selectionMoveEnd$,
+ regionService.currentRegion$,
+ fromCallback(commandService.onCommandExecuted.bind(commandService)).pipe(
+ filter(([commandInfo]) => commandList.includes(commandInfo.id))
+ )
+ ).subscribe(() => {
+ const selection = selectionManagerService.getCurrentSelections()?.[0];
+ if (!selection) {
+ return;
+ }
+
+ const { startRow, startColumn } = selection.range;
+ const numfmtValue = workbook.getStyles().get(worksheet.getCell(startRow, startColumn)?.s)?.n;
+ const pattern = numfmtValue?.pattern;
+ const currencySymbol = getCurrencySymbolByLocale(regionService.getCurrentRegion());
+ let value = localeService.t<LocaleKey>('sheets-numfmt-ui.general');
+
+ if (isDefaultFormat(pattern)) {
+ subscribe.next(value);
+ return;
+ }
+
+ if (pattern) {
+ const item = MENU_OPTIONS(currencySymbol)
+ .filter((option) => typeof option === 'object' && option.pattern)
+ .find((option) => isPatternEqualWithoutDecimal(
+ pattern,
+ (option as { pattern: string }).pattern
+ ));
+ value = item && typeof item === 'object' && item.pattern
+ ? localeService.t<LocaleKey>(item.label)
+ : localeService.t<LocaleKey>('sheets-numfmt-ui.moreFmt');
+ }
+
+ subscribe.next(value);
+ })
+ )
+ );
+
+ return {
+ id: MOBILE_NUMFMT_MENU_ID,
+ title: 'sheets-numfmt-ui.title',
+ tooltip: 'sheets-numfmt-ui.title',
+ type: MenuItemType.SELECTOR,
+ selections: [],
+ value$,
+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET),
+ disabled$: getCurrentRangeDisable$(accessor, {
+ workbookTypes: [WorkbookEditablePermission],
+ worksheetTypes: [WorksheetSetCellStylePermission, WorksheetEditPermission],
+ rangeTypes: [RangeProtectionPermissionEditPoint],
+ }),
+ mobileNumberFormat: createMobileNumberFormatMenuConfig(
+ getCurrencySymbolByLocale(regionService.getCurrentRegion())
+ ),
+ };
+}
diff --git a/packages/sheets-numfmt-ui/src/menu/mobile-numfmt.menu.controller.ts b/packages/sheets-numfmt-ui/src/menu/mobile-numfmt.menu.controller.ts
new file mode 100644
index 0000000000..5a8a505137
--- /dev/null
+++ b/packages/sheets-numfmt-ui/src/menu/mobile-numfmt.menu.controller.ts
@@ -0,0 +1,29 @@
+/**
+ * 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 { Disposable } from '@univerjs/core';
+import { IMenuManagerService } from '@univerjs/ui';
+import { mobileMenuSchema } from './mobile-schema';
+
+export class MobileNumfmtMenuController extends Disposable {
+ constructor(
+ @IMenuManagerService menuManagerService: IMenuManagerService
+ ) {
+ super();
+
+ menuManagerService.mergeMenu(mobileMenuSchema);
+ }
+}
diff --git a/packages/sheets-numfmt-ui/src/menu/mobile-schema.ts b/packages/sheets-numfmt-ui/src/menu/mobile-schema.ts
new file mode 100644
index 0000000000..499335cf79
--- /dev/null
+++ b/packages/sheets-numfmt-ui/src/menu/mobile-schema.ts
@@ -0,0 +1,28 @@
+/**
+ * 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 { MenuSchemaType } from '@univerjs/ui';
+import { RibbonStartGroup } from '@univerjs/ui';
+import { FactoryMobileOtherMenuItem, MOBILE_NUMFMT_MENU_ID } from './mobile-menu';
+
+export const mobileMenuSchema: MenuSchemaType = {
+ [RibbonStartGroup.NUMBER]: {
+ [MOBILE_NUMFMT_MENU_ID]: {
+ order: 9,
+ menuItemFactory: FactoryMobileOtherMenuItem,
+ },
+ },
+};
diff --git a/packages/sheets-numfmt-ui/src/menu/number-format-options.ts b/packages/sheets-numfmt-ui/src/menu/number-format-options.ts
new file mode 100644
index 0000000000..2432992c58
--- /dev/null
+++ b/packages/sheets-numfmt-ui/src/menu/number-format-options.ts
@@ -0,0 +1,86 @@
+/**
+ * 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 { DEFAULT_TEXT_FORMAT_EXCEL } from '@univerjs/core';
+
+export const MENU_OPTIONS = (currencySymbol: string): Array<{
+ label: LocaleKey;
+ pattern: string | null;
+} | '|'> => {
+ return [
+ {
+ label: 'sheets-numfmt-ui.general',
+ pattern: null,
+ },
+ {
+ label: 'sheets-numfmt-ui.text',
+ pattern: DEFAULT_TEXT_FORMAT_EXCEL,
+ },
+ '|',
+ {
+ label: 'sheets-numfmt-ui.number',
+ pattern: '0',
+ },
+ {
+ label: 'sheets-numfmt-ui.percent',
+ pattern: '0.00%',
+ },
+ {
+ label: 'sheets-numfmt-ui.scientific',
+ pattern: '0.00E+00',
+ },
+ '|',
+ {
+ label: 'sheets-numfmt-ui.accounting',
+ pattern: `"${currencySymbol}" #,##0.00_);[Red]("${currencySymbol}"#,##0.00)`,
+ },
+ {
+ label: 'sheets-numfmt-ui.financialValue',
+ pattern: '#,##0.00;[Red]#,##0.00',
+ },
+ {
+ label: 'sheets-numfmt-ui.currency',
+ pattern: `"${currencySymbol}"#,##0.00_);[Red]("${currencySymbol}"#,##0.00)`,
+ },
+ {
+ label: 'sheets-numfmt-ui.roundingCurrency',
+ pattern: `"${currencySymbol}"#,##0;[Red]"${currencySymbol}"#,##0`,
+ },
+ '|',
+ {
+ label: 'sheets-numfmt-ui.date',
+ pattern: 'yyyy-mm-dd;@',
+ },
+ {
+ label: 'sheets-numfmt-ui.time',
+ pattern: 'am/pm h":"mm":"ss',
+ },
+ {
+ label: 'sheets-numfmt-ui.dateTime',
+ pattern: 'yyyy-m-d am/pm h:mm',
+ },
+ {
+ label: 'sheets-numfmt-ui.timeDuration',
+ pattern: 'h:mm:ss',
+ },
+ '|',
+ {
+ label: 'sheets-numfmt-ui.moreFmt',
+ pattern: '',
+ },
+ ];
+};
diff --git a/packages/sheets-numfmt-ui/src/mobile-plugin.ts b/packages/sheets-numfmt-ui/src/mobile-plugin.ts
new file mode 100644
index 0000000000..8a8b942863
--- /dev/null
+++ b/packages/sheets-numfmt-ui/src/mobile-plugin.ts
@@ -0,0 +1,102 @@
+/**
+ * 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 { Dependency } from '@univerjs/core';
+import type { IUniverSheetsNumfmtUIConfig } from './config/config';
+import {
+ DependentOn,
+ IConfigService,
+ Inject,
+ Injector,
+ merge,
+ Plugin,
+ registerDependencies,
+ touchDependencies,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { IRenderManagerService, UniverRenderEnginePlugin } from '@univerjs/engine-render';
+import { UniverSheetsPlugin } from '@univerjs/sheets';
+import { UniverSheetsNumfmtPlugin } from '@univerjs/sheets-numfmt';
+import { UniverSheetsMobileUIPlugin } from '@univerjs/sheets-ui';
+import { UniverMobileUIPlugin } from '@univerjs/ui';
+import pkg from '../package.json';
+import { defaultPluginConfig, SHEETS_NUMFMT_UI_PLUGIN_CONFIG_KEY } from './config/config';
+import { MobileComponentsController } from './controllers/mobile/components.controller';
+import { SheetNumfmtMobileUIController } from './controllers/mobile/ui.controller';
+import { NumfmtAlertRenderController } from './controllers/numfmt-alert-render.controller';
+import { NumfmtRepeatLastActionController } from './controllers/numfmt-repeat-last-action.controller';
+import { NumfmtEditorController } from './controllers/numfmt.editor.controller';
+import { MobileNumfmtMenuController } from './menu/mobile-numfmt.menu.controller';
+
+@DependentOn(
+ UniverRenderEnginePlugin,
+ UniverSheetsPlugin,
+ UniverSheetsNumfmtPlugin,
+ UniverSheetsMobileUIPlugin,
+ UniverMobileUIPlugin
+)
+export class UniverSheetsNumfmtMobileUIPlugin extends Plugin {
+ static override pluginName = 'SHEET_NUMFMT_UI_PLUGIN';
+ static override packageName = pkg.name;
+ static override version = pkg.version;
+ static override type = UniverInstanceType.UNIVER_SHEET;
+
+ constructor(
+ private readonly _config: Partial<IUniverSheetsNumfmtUIConfig> = defaultPluginConfig,
+ @Inject(Injector) override readonly _injector: Injector,
+ @IConfigService private readonly _configService: IConfigService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService
+ ) {
+ super();
+
+ const { menu, ...rest } = merge({}, defaultPluginConfig, this._config);
+ if (menu) {
+ this._configService.setConfig('menu', menu, { merge: true });
+ }
+ this._configService.setConfig(SHEETS_NUMFMT_UI_PLUGIN_CONFIG_KEY, rest);
+ }
+
+ override onStarting(): void {
+ registerDependencies(this._injector, [
+ [MobileComponentsController],
+ [SheetNumfmtMobileUIController],
+ [NumfmtEditorController],
+ [MobileNumfmtMenuController],
+ [NumfmtRepeatLastActionController],
+ ]);
+ touchDependencies(this._injector, [
+ [MobileComponentsController],
+ [SheetNumfmtMobileUIController],
+ ]);
+ }
+
+ override onRendered(): void {
+ const modules: Dependency[] = [
+ [NumfmtAlertRenderController],
+ ];
+ modules.forEach((module) => {
+ this.disposeWithMe(
+ this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, module)
+ );
+ });
+
+ touchDependencies(this._injector, [
+ [NumfmtEditorController],
+ [MobileNumfmtMenuController],
+ [NumfmtRepeatLastActionController],
+ ]);
+ }
+}
diff --git a/packages/sheets-numfmt-ui/src/views/components/MoreNumfmtType.tsx b/packages/sheets-numfmt-ui/src/views/components/MoreNumfmtType.tsx
index 62100a9797..1f84290f30 100644
--- a/packages/sheets-numfmt-ui/src/views/components/MoreNumfmtType.tsx
+++ b/packages/sheets-numfmt-ui/src/views/components/MoreNumfmtType.tsx
@@ -29,7 +29,7 @@ import {
import { ILayoutService, useDependency, useObservable } from '@univerjs/ui';
import { useMemo } from 'react';
import { OpenNumfmtPanelOperator } from '../../commands/operations/open.numfmt.panel.operation';
-import { MENU_OPTIONS } from '../../menu/menu';
+import { MENU_OPTIONS } from '../../menu/number-format-options';
export const MORE_NUMFMT_TYPE_KEY = 'sheets-numfmt-ui.moreNumfmtType';
export const OPTIONS_KEY = 'sheets-numfmt-ui.moreNumfmtType.options';
diff --git a/packages/sheets-numfmt-ui/src/views/mobile/MobileCustomFormat.tsx b/packages/sheets-numfmt-ui/src/views/mobile/MobileCustomFormat.tsx
new file mode 100644
index 0000000000..cd28612161
--- /dev/null
+++ b/packages/sheets-numfmt-ui/src/views/mobile/MobileCustomFormat.tsx
@@ -0,0 +1,89 @@
+/**
+ * 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 { LocaleService } from '@univerjs/core';
+import { Button, clsx, Input, MobileActionRow, MobileActionRowGroup, scrollbarClassName } from '@univerjs/design';
+import { CheckMarkIcon } from '@univerjs/icons';
+import { useDependency } from '@univerjs/ui';
+import { useState } from 'react';
+
+export interface IMobileCustomFormatProps {
+ patterns: string[];
+ onConfirm: (pattern: string) => void;
+}
+
+export function MobileCustomFormat(props: IMobileCustomFormatProps) {
+ const { patterns, onConfirm } = props;
+ const localeService = useDependency(LocaleService);
+ const [pattern, setPattern] = useState('');
+ const title = localeService.t<LocaleKey>('sheets-numfmt-ui.customFormat');
+
+ return (
+ <div
+ data-u-comp="mobile-custom-format"
+ className="univer-flex univer-h-full univer-min-h-0 univer-flex-col univer-gap-4"
+ >
+ <Input
+ className="univer-shrink-0"
+ size="large"
+ aria-label={title}
+ value={pattern}
+ placeholder={title}
+ onChange={setPattern}
+ />
+ <div
+ data-u-comp="mobile-custom-format-scroller"
+ className={clsx('univer-min-h-0 univer-flex-1 univer-overflow-y-auto', scrollbarClassName)}
+ >
+ <div
+ className="
+ univer-overflow-hidden univer-rounded-xl univer-bg-gray-0
+ dark:!univer-bg-gray-800
+ "
+ >
+ {patterns.map((item, index) => (
+ <MobileActionRow
+ key={item}
+ aria-label={item}
+ aria-pressed={pattern === item}
+ title={<span className="univer-break-all univer-font-mono univer-text-sm">{item}</span>}
+ trailing={pattern === item
+ ? <CheckMarkIcon className="univer-shrink-0 univer-text-primary-600" />
+ : undefined}
+ bordered={index !== patterns.length - 1}
+ className="!univer-rounded-none !univer-font-normal"
+ onClick={() => setPattern(item)}
+ />
+ ))}
+ </div>
+ <div
+ className="
+ univer-mt-4 univer-px-1 univer-text-sm univer-text-gray-600
+ dark:!univer-text-gray-200
+ "
+ >
+ {localeService.t<LocaleKey>('sheets-numfmt-ui.customFormatDes')}
+ </div>
+ </div>
+ <MobileActionRowGroup className="univer-shrink-0">
+ <Button variant="primary" disabled={!pattern.trim()} onClick={() => onConfirm(pattern.trim())}>
+ {localeService.t<LocaleKey>('sheets-numfmt-ui.confirm')}
+ </Button>
+ </MobileActionRowGroup>
+ </div>
+ );
+}
diff --git a/packages/sheets-sort-ui/src/controllers/mobile/components.controller.ts b/packages/sheets-sort-ui/src/controllers/mobile/components.controller.ts
new file mode 100644
index 0000000000..dbe2c13a78
--- /dev/null
+++ b/packages/sheets-sort-ui/src/controllers/mobile/components.controller.ts
@@ -0,0 +1,40 @@
+/**
+ * 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 { Disposable, Inject } from '@univerjs/core';
+import { AscendingIcon, CustomSortIcon, DescendingIcon, ExpandAscendingIcon, ExpandDescendingIcon } from '@univerjs/icons';
+import { ComponentManager, IconManager } from '@univerjs/ui';
+import { MobileCustomSortPanel } from '../../views/mobile/MobileCustomSortPanel';
+
+export const MOBILE_CUSTOM_SORT_PANEL = 'MobileCustomSortPanel';
+
+export class MobileComponentsController extends Disposable {
+ constructor(
+ @Inject(ComponentManager) componentManager: ComponentManager,
+ @Inject(IconManager) iconManager: IconManager
+ ) {
+ super();
+
+ this.disposeWithMe(iconManager.register({
+ AscendingIcon,
+ ExpandAscendingIcon,
+ DescendingIcon,
+ ExpandDescendingIcon,
+ CustomSortIcon,
+ }));
+ this.disposeWithMe(componentManager.register(MOBILE_CUSTOM_SORT_PANEL, MobileCustomSortPanel));
+ }
+}
diff --git a/packages/sheets-sort-ui/src/controllers/mobile/ui.controller.ts b/packages/sheets-sort-ui/src/controllers/mobile/ui.controller.ts
new file mode 100644
index 0000000000..4d94cf1397
--- /dev/null
+++ b/packages/sheets-sort-ui/src/controllers/mobile/ui.controller.ts
@@ -0,0 +1,95 @@
+/**
+ * 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 { ICommandService, Inject, LocaleService, RxDisposable } from '@univerjs/core';
+import { serializeRange } from '@univerjs/engine-formula';
+import { SortRangeCommand } from '@univerjs/sheets-sort';
+import { SheetsRenderService } from '@univerjs/sheets-ui';
+import { IDialogService, IMenuManagerService } from '@univerjs/ui';
+import { takeUntil } from 'rxjs';
+import {
+ SortRangeAscCommand,
+ SortRangeAscExtCommand,
+ SortRangeAscExtInCtxMenuCommand,
+ SortRangeAscInCtxMenuCommand,
+ SortRangeCustomCommand,
+ SortRangeCustomInCtxMenuCommand,
+ SortRangeDescCommand,
+ SortRangeDescExtCommand,
+ SortRangeDescExtInCtxMenuCommand,
+ SortRangeDescInCtxMenuCommand,
+} from '../../commands/commands/sheets-sort.command';
+import { mobileMenuSchema } from '../../menu/mobile-schema';
+import { SheetsSortUIService } from '../../services/sheets-sort-ui.service';
+import { MOBILE_CUSTOM_SORT_PANEL } from './components.controller';
+
+const MOBILE_CUSTOM_SORT_DIALOG_ID = 'mobile-custom-sort-dialog';
+
+export class SheetsSortMobileUIController extends RxDisposable {
+ constructor(
+ @ICommandService private readonly _commandService: ICommandService,
+ @IMenuManagerService private readonly _menuManagerService: IMenuManagerService,
+ @IDialogService private readonly _dialogService: IDialogService,
+ @Inject(SheetsRenderService) private readonly _sheetRenderService: SheetsRenderService,
+ @Inject(LocaleService) private readonly _localeService: LocaleService,
+ @Inject(SheetsSortUIService) private readonly _sheetsSortUIService: SheetsSortUIService
+ ) {
+ super();
+
+ this._initCommands();
+ this._menuManagerService.mergeMenu(mobileMenuSchema);
+ this._initCustomSortPanel();
+ }
+
+ private _initCommands(): void {
+ [
+ SortRangeAscCommand,
+ SortRangeAscExtCommand,
+ SortRangeDescCommand,
+ SortRangeDescExtCommand,
+ SortRangeCustomCommand,
+ SortRangeAscInCtxMenuCommand,
+ SortRangeAscExtInCtxMenuCommand,
+ SortRangeDescInCtxMenuCommand,
+ SortRangeDescExtInCtxMenuCommand,
+ SortRangeCustomInCtxMenuCommand,
+ ].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));
+
+ this.disposeWithMe(this._sheetRenderService.registerSkeletonChangingMutations(SortRangeCommand.id));
+ }
+
+ private _initCustomSortPanel(): void {
+ this._sheetsSortUIService.customSortState$.pipe(takeUntil(this.dispose$)).subscribe((state) => {
+ if (state?.show && state.location) {
+ this._dialogService.open({
+ id: MOBILE_CUSTOM_SORT_DIALOG_ID,
+ title: {
+ title: `${this._localeService.t<LocaleKey>('sheets-sort-ui.general.sort-custom')}: ${serializeRange(state.location.range)}`,
+ },
+ children: { label: MOBILE_CUSTOM_SORT_PANEL },
+ mask: true,
+ onClose: () => this._sheetsSortUIService.closeCustomSortPanel(),
+ });
+ return;
+ }
+
+ if (state && !state.show) {
+ this._dialogService.close(MOBILE_CUSTOM_SORT_DIALOG_ID);
+ }
+ });
+ }
+}
diff --git a/packages/sheets-sort-ui/src/index.ts b/packages/sheets-sort-ui/src/index.ts
index 562b9f6910..f954859ccd 100644
--- a/packages/sheets-sort-ui/src/index.ts
+++ b/packages/sheets-sort-ui/src/index.ts
@@ -30,4 +30,5 @@ export {
} from './commands/commands/sheets-sort.command';
export type { IUniverSheetsSortUIConfig } from './config/config';
export { menuSchema as SheetsSortUIMenuSchema } from './menu/schema';
+export { UniverSheetsSortMobileUIPlugin } from './mobile-plugin';
export { UniverSheetsSortUIPlugin } from './plugin';
diff --git a/packages/sheets-sort-ui/src/locale/ar-SA.ts b/packages/sheets-sort-ui/src/locale/ar-SA.ts
index d9afac1b93..7f638965cc 100644
--- a/packages/sheets-sort-ui/src/locale/ar-SA.ts
+++ b/packages/sheets-sort-ui/src/locale/ar-SA.ts
@@ -41,6 +41,7 @@ const locale: typeof enUS = {
'sort-reminder-no': 'الاحتفاظ بنطاق الفرز',
'first-row-check': 'الصف الأول لا يشارك في الفرز',
'add-condition': 'إضافة شرط',
+ 'delete-condition': 'حذف الشرط',
cancel: 'إلغاء',
confirm: 'تأكيد',
},
diff --git a/packages/sheets-sort-ui/src/locale/ca-ES.ts b/packages/sheets-sort-ui/src/locale/ca-ES.ts
index 10ab927e57..f734cb1ca8 100644
--- a/packages/sheets-sort-ui/src/locale/ca-ES.ts
+++ b/packages/sheets-sort-ui/src/locale/ca-ES.ts
@@ -41,6 +41,7 @@ const locale: typeof enUS = {
'sort-reminder-no': 'Mantenir l\'interval d\'ordenació',
'first-row-check': 'La primera fila no participa en l\'ordenació',
'add-condition': 'Afegeix condició',
+ 'delete-condition': 'Suprimeix la condició',
cancel: 'Cancel·lar',
confirm: 'Confirmar',
},
diff --git a/packages/sheets-sort-ui/src/locale/de-DE.ts b/packages/sheets-sort-ui/src/locale/de-DE.ts
index 4687ed3358..afcc719d1a 100644
--- a/packages/sheets-sort-ui/src/locale/de-DE.ts
+++ b/packages/sheets-sort-ui/src/locale/de-DE.ts
@@ -41,6 +41,7 @@ const locale: typeof enUS = {
'sort-reminder-no': 'Bereichssortierung beibehalten',
'first-row-check': 'Erste Zeile nimmt nicht am Sortieren teil',
'add-condition': 'Bedingung hinzufügen',
+ 'delete-condition': 'Bedingung löschen',
cancel: 'Abbrechen',
confirm: 'Bestätigen',
},
diff --git a/packages/sheets-sort-ui/src/locale/en-US.ts b/packages/sheets-sort-ui/src/locale/en-US.ts
index 4fe2874799..29d96f2c5a 100644
--- a/packages/sheets-sort-ui/src/locale/en-US.ts
+++ b/packages/sheets-sort-ui/src/locale/en-US.ts
@@ -39,6 +39,7 @@ const locale = {
'sort-reminder-no': 'Keep range sorting',
'first-row-check': 'First row does not participate in sorting',
'add-condition': 'Add condition',
+ 'delete-condition': 'Delete condition',
cancel: 'Cancel',
confirm: 'Confirm',
},
diff --git a/packages/sheets-sort-ui/src/locale/es-ES.ts b/packages/sheets-sort-ui/src/locale/es-ES.ts
index 5676de8fd2..100e7327c2 100644
--- a/packages/sheets-sort-ui/src/locale/es-ES.ts
+++ b/packages/sheets-sort-ui/src/locale/es-ES.ts
@@ -41,6 +41,7 @@ const locale: typeof enUS = {
'sort-reminder-no': 'Mantener el rango de ordenación',
'first-row-check': 'La primera fila no participa en la ordenación',
'add-condition': 'Agregar condición',
+ 'delete-condition': 'Eliminar condición',
cancel: 'Cancelar',
confirm: 'Confirmar',
},
diff --git a/packages/sheets-sort-ui/src/locale/fa-IR.ts b/packages/sheets-sort-ui/src/locale/fa-IR.ts
index 6ec211002b..2acc1fd82c 100644
--- a/packages/sheets-sort-ui/src/locale/fa-IR.ts
+++ b/packages/sheets-sort-ui/src/locale/fa-IR.ts
@@ -41,6 +41,7 @@ const locale: typeof enUS = {
'sort-reminder-no': 'حفظ مرتب‌سازی محدوده',
'first-row-check': 'ردیف اول در مرتب‌سازی شرکت نمی‌کند',
'add-condition': 'افزودن شرط',
+ 'delete-condition': 'حذف شرط',
cancel: 'انصراف',
confirm: 'تایید',
},
diff --git a/packages/sheets-sort-ui/src/locale/fr-FR.ts b/packages/sheets-sort-ui/src/locale/fr-FR.ts
index da8483d3ac..c4dcd89025 100644
--- a/packages/sheets-sort-ui/src/locale/fr-FR.ts
+++ b/packages/sheets-sort-ui/src/locale/fr-FR.ts
@@ -41,6 +41,7 @@ const locale: typeof enUS = {
'sort-reminder-no': 'Conserver le tri de la plage',
'first-row-check': 'La première ligne ne participe pas au tri',
'add-condition': 'Ajouter une condition',
+ 'delete-condition': 'Supprimer la condition',
cancel: 'Annuler',
confirm: 'Confirmer',
},
diff --git a/packages/sheets-sort-ui/src/locale/id-ID.ts b/packages/sheets-sort-ui/src/locale/id-ID.ts
index 9d6cb0d3f1..fe6bfeeeb8 100644
--- a/packages/sheets-sort-ui/src/locale/id-ID.ts
+++ b/packages/sheets-sort-ui/src/locale/id-ID.ts
@@ -41,6 +41,7 @@ const locale: typeof enUS = {
'sort-reminder-no': 'Pertahankan pengurutan rentang',
'first-row-check': 'Baris pertama tidak ikut dalam pengurutan',
'add-condition': 'Tambah kondisi',
+ 'delete-condition': 'Hapus kondisi',
cancel: 'Batal',
confirm: 'Konfirmasi',
},
diff --git a/packages/sheets-sort-ui/src/locale/it-IT.ts b/packages/sheets-sort-ui/src/locale/it-IT.ts
index 0f71db36eb..dd424667ff 100644
--- a/packages/sheets-sort-ui/src/locale/it-IT.ts
+++ b/packages/sheets-sort-ui/src/locale/it-IT.ts
@@ -41,6 +41,7 @@ const locale: typeof enUS = {
'sort-reminder-no': 'Mantieni ordinamento intervallo',
'first-row-check': 'La prima riga non partecipa all\'ordinamento',
'add-condition': 'Aggiungi condizione',
+ 'delete-condition': 'Elimina condizione',
cancel: 'Annulla',
confirm: 'Conferma',
},
diff --git a/packages/sheets-sort-ui/src/locale/ja-JP.ts b/packages/sheets-sort-ui/src/locale/ja-JP.ts
index aacd9b8e39..5063bf1c44 100644
--- a/packages/sheets-sort-ui/src/locale/ja-JP.ts
+++ b/packages/sheets-sort-ui/src/locale/ja-JP.ts
@@ -41,6 +41,7 @@ const locale: typeof enUS = {
'sort-reminder-no': '範囲を維持して並べ替え',
'first-row-check': '先頭行を並べ替えの対象に含めない',
'add-condition': '条件を追加',
+ 'delete-condition': '条件を削除',
cancel: 'キャンセル',
confirm: '確認',
},
diff --git a/packages/sheets-sort-ui/src/locale/ko-KR.ts b/packages/sheets-sort-ui/src/locale/ko-KR.ts
index a4bd7c360c..645a7fd741 100644
--- a/packages/sheets-sort-ui/src/locale/ko-KR.ts
+++ b/packages/sheets-sort-ui/src/locale/ko-KR.ts
@@ -41,6 +41,7 @@ const locale: typeof enUS = {
'sort-reminder-no': '범위 정렬 유지',
'first-row-check': '첫 번째 행은 정렬에 참여하지 않습니다',
'add-condition': '조건 추가',
+ 'delete-condition': '조건 삭제',
cancel: '취소',
confirm: '확인',
},
diff --git a/packages/sheets-sort-ui/src/locale/pl-PL.ts b/packages/sheets-sort-ui/src/locale/pl-PL.ts
index ccb5d3d849..34fd5a2075 100644
--- a/packages/sheets-sort-ui/src/locale/pl-PL.ts
+++ b/packages/sheets-sort-ui/src/locale/pl-PL.ts
@@ -41,6 +41,7 @@ const locale: typeof enUS = {
'sort-reminder-no': 'Zachowaj sortowanie zakresu',
'first-row-check': 'Pierwszy wiersz nie bierze udziału w sortowaniu',
'add-condition': 'Dodaj warunek',
+ 'delete-condition': 'Usuń warunek',
cancel: 'Anuluj',
confirm: 'Potwierdź',
},
diff --git a/packages/sheets-sort-ui/src/locale/pt-BR.ts b/packages/sheets-sort-ui/src/locale/pt-BR.ts
index 8ec46ec633..0317203b19 100644
--- a/packages/sheets-sort-ui/src/locale/pt-BR.ts
+++ b/packages/sheets-sort-ui/src/locale/pt-BR.ts
@@ -41,6 +41,7 @@ const locale: typeof enUS = {
'sort-reminder-no': 'Manter ordenação do intervalo',
'first-row-check': 'A primeira linha não participa da ordenação',
'add-condition': 'Adicionar condição',
+ 'delete-condition': 'Excluir condição',
cancel: 'Cancelar',
confirm: 'Confirmar',
},
diff --git a/packages/sheets-sort-ui/src/locale/ru-RU.ts b/packages/sheets-sort-ui/src/locale/ru-RU.ts
index b23d435e31..1e0f1b4a0a 100644
--- a/packages/sheets-sort-ui/src/locale/ru-RU.ts
+++ b/packages/sheets-sort-ui/src/locale/ru-RU.ts
@@ -41,6 +41,7 @@ const locale: typeof enUS = {
'sort-reminder-no': 'Оставить сортировку диапазона',
'first-row-check': 'Первая строка контента не участвует в сортировке',
'add-condition': 'Добавить условие',
+ 'delete-condition': 'Удалить условие',
cancel: 'Отмена',
confirm: 'Подтвердить',
},
diff --git a/packages/sheets-sort-ui/src/locale/sk-SK.ts b/packages/sheets-sort-ui/src/locale/sk-SK.ts
index 99b2603a4c..a1945f0825 100644
--- a/packages/sheets-sort-ui/src/locale/sk-SK.ts
+++ b/packages/sheets-sort-ui/src/locale/sk-SK.ts
@@ -41,6 +41,7 @@ const locale: typeof enUS = {
'sort-reminder-no': 'Zachovať triedenie rozsahu',
'first-row-check': 'Prvý riadok sa nezúčastňuje triedenia',
'add-condition': 'Pridať podmienku',
+ 'delete-condition': 'Odstrániť podmienku',
cancel: 'Zrušiť',
confirm: 'Potvrdiť',
},
diff --git a/packages/sheets-sort-ui/src/locale/vi-VN.ts b/packages/sheets-sort-ui/src/locale/vi-VN.ts
index 445545ad3a..acf60e2a68 100644
--- a/packages/sheets-sort-ui/src/locale/vi-VN.ts
+++ b/packages/sheets-sort-ui/src/locale/vi-VN.ts
@@ -41,6 +41,7 @@ const locale: typeof enUS = {
'sort-reminder-no': 'Giữ nguyên phạm vi sắp xếp được chọn',
'first-row-check': 'Hàng đầu tiên không tham gia sắp xếp',
'add-condition': 'Thêm điều kiện sắp xếp',
+ 'delete-condition': 'Xóa điều kiện',
cancel: 'Hủy bỏ',
confirm: 'Xác nhận',
},
diff --git a/packages/sheets-sort-ui/src/locale/zh-CN.ts b/packages/sheets-sort-ui/src/locale/zh-CN.ts
index f992245175..5715e45019 100644
--- a/packages/sheets-sort-ui/src/locale/zh-CN.ts
+++ b/packages/sheets-sort-ui/src/locale/zh-CN.ts
@@ -41,6 +41,7 @@ const locale: typeof enUS = {
'sort-reminder-no': '保持所选排序范围',
'first-row-check': '标题不参与排序',
'add-condition': '添加排序条件',
+ 'delete-condition': '删除排序条件',
cancel: '取消',
confirm: '确认',
},
diff --git a/packages/sheets-sort-ui/src/locale/zh-HK.ts b/packages/sheets-sort-ui/src/locale/zh-HK.ts
index 68971c040a..905089ee76 100644
--- a/packages/sheets-sort-ui/src/locale/zh-HK.ts
+++ b/packages/sheets-sort-ui/src/locale/zh-HK.ts
@@ -41,6 +41,7 @@ const locale: typeof enUS = {
'sort-reminder-no': '保持所選排序範圍',
'first-row-check': '標題不參與排序',
'add-condition': '新增排序條件',
+ 'delete-condition': '刪除排序條件',
cancel: '取消',
confirm: '確認',
},
diff --git a/packages/sheets-sort-ui/src/locale/zh-TW.ts b/packages/sheets-sort-ui/src/locale/zh-TW.ts
index 68971c040a..905089ee76 100644
--- a/packages/sheets-sort-ui/src/locale/zh-TW.ts
+++ b/packages/sheets-sort-ui/src/locale/zh-TW.ts
@@ -41,6 +41,7 @@ const locale: typeof enUS = {
'sort-reminder-no': '保持所選排序範圍',
'first-row-check': '標題不參與排序',
'add-condition': '新增排序條件',
+ 'delete-condition': '刪除排序條件',
cancel: '取消',
confirm: '確認',
},
diff --git a/packages/sheets-sort-ui/src/menu/mobile-schema.ts b/packages/sheets-sort-ui/src/menu/mobile-schema.ts
new file mode 100644
index 0000000000..54c1e14ca7
--- /dev/null
+++ b/packages/sheets-sort-ui/src/menu/mobile-schema.ts
@@ -0,0 +1,103 @@
+/**
+ * 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 { MenuSchemaType } from '@univerjs/ui';
+import { ContextMenuGroup, ContextMenuPosition, RibbonDataGroup } from '@univerjs/ui';
+import {
+ SortRangeAscCommand,
+ SortRangeAscExtCommand,
+ SortRangeAscExtInCtxMenuCommand,
+ SortRangeAscInCtxMenuCommand,
+ SortRangeCustomCommand,
+ SortRangeCustomInCtxMenuCommand,
+ SortRangeDescCommand,
+ SortRangeDescExtCommand,
+ SortRangeDescExtInCtxMenuCommand,
+ SortRangeDescInCtxMenuCommand,
+} from '../commands/commands/sheets-sort.command';
+import {
+ SHEETS_SORT_CTX_MENU_ID,
+ SHEETS_SORT_MENU_ID,
+ sortRangeAscCtxMenuFactory,
+ sortRangeAscExtCtxMenuFactory,
+ sortRangeAscExtMenuFactory,
+ sortRangeAscMenuFactory,
+ sortRangeCtxMenuFactory,
+ sortRangeCustomCtxMenuFactory,
+ sortRangeCustomMenuFactory,
+ sortRangeDescCtxMenuFactory,
+ sortRangeDescExtCtxMenuFactory,
+ sortRangeDescExtMenuFactory,
+ sortRangeDescMenuFactory,
+ sortRangeMenuFactory,
+} from './sheets-sort.menu';
+
+export const mobileMenuSchema: MenuSchemaType = {
+ [RibbonDataGroup.ORGANIZATION]: {
+ [SHEETS_SORT_MENU_ID]: {
+ order: 3,
+ menuItemFactory: sortRangeMenuFactory,
+ [SortRangeAscCommand.id]: {
+ order: 0,
+ menuItemFactory: sortRangeAscMenuFactory,
+ },
+ [SortRangeAscExtCommand.id]: {
+ order: 1,
+ menuItemFactory: sortRangeAscExtMenuFactory,
+ },
+ [SortRangeDescCommand.id]: {
+ order: 2,
+ menuItemFactory: sortRangeDescMenuFactory,
+ },
+ [SortRangeDescExtCommand.id]: {
+ order: 3,
+ menuItemFactory: sortRangeDescExtMenuFactory,
+ },
+ [SortRangeCustomCommand.id]: {
+ order: 4,
+ menuItemFactory: sortRangeCustomMenuFactory,
+ },
+ },
+ },
+ [ContextMenuPosition.MAIN_AREA]: {
+ [ContextMenuGroup.DATA]: {
+ [SHEETS_SORT_CTX_MENU_ID]: {
+ order: 0,
+ menuItemFactory: sortRangeCtxMenuFactory,
+ [SortRangeAscInCtxMenuCommand.id]: {
+ order: 0,
+ menuItemFactory: sortRangeAscCtxMenuFactory,
+ },
+ [SortRangeAscExtInCtxMenuCommand.id]: {
+ order: 1,
+ menuItemFactory: sortRangeAscExtCtxMenuFactory,
+ },
+ [SortRangeDescInCtxMenuCommand.id]: {
+ order: 2,
+ menuItemFactory: sortRangeDescCtxMenuFactory,
+ },
+ [SortRangeDescExtInCtxMenuCommand.id]: {
+ order: 3,
+ menuItemFactory: sortRangeDescExtCtxMenuFactory,
+ },
+ [SortRangeCustomInCtxMenuCommand.id]: {
+ order: 4,
+ menuItemFactory: sortRangeCustomCtxMenuFactory,
+ },
+ },
+ },
+ },
+};
diff --git a/packages/sheets-sort-ui/src/mobile-plugin.ts b/packages/sheets-sort-ui/src/mobile-plugin.ts
new file mode 100644
index 0000000000..856675affd
--- /dev/null
+++ b/packages/sheets-sort-ui/src/mobile-plugin.ts
@@ -0,0 +1,69 @@
+/**
+ * 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 { IUniverSheetsSortUIConfig } from './config/config';
+import {
+ DependentOn,
+ IConfigService,
+ Inject,
+ Injector,
+ merge,
+ Plugin,
+ registerDependencies,
+ touchDependencies,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { UniverSheetsPlugin } from '@univerjs/sheets';
+import { UniverSheetsSortPlugin } from '@univerjs/sheets-sort';
+import { UniverSheetsMobileUIPlugin } from '@univerjs/sheets-ui';
+import { UniverMobileUIPlugin } from '@univerjs/ui';
+import pkg from '../package.json';
+import { defaultPluginConfig, SHEETS_SORT_UI_PLUGIN_CONFIG_KEY } from './config/config';
+import { MobileComponentsController } from './controllers/mobile/components.controller';
+import { SheetsSortMobileUIController } from './controllers/mobile/ui.controller';
+import { SheetsSortUIService } from './services/sheets-sort-ui.service';
+
+@DependentOn(UniverSheetsPlugin, UniverSheetsSortPlugin, UniverSheetsMobileUIPlugin, UniverMobileUIPlugin)
+export class UniverSheetsSortMobileUIPlugin extends Plugin {
+ static override type = UniverInstanceType.UNIVER_SHEET;
+ static override pluginName = 'SHEET_SORT_UI_PLUGIN';
+ static override packageName = pkg.name;
+ static override version = pkg.version;
+
+ constructor(
+ private readonly _config: Partial<IUniverSheetsSortUIConfig> = defaultPluginConfig,
+ @Inject(Injector) protected override readonly _injector: Injector,
+ @IConfigService private readonly _configService: IConfigService
+ ) {
+ super();
+
+ const { ...rest } = merge({}, defaultPluginConfig, this._config);
+ this._configService.setConfig(SHEETS_SORT_UI_PLUGIN_CONFIG_KEY, rest);
+ }
+
+ override onStarting(): void {
+ registerDependencies(this._injector, [
+ [MobileComponentsController],
+ [SheetsSortUIService],
+ [SheetsSortMobileUIController],
+ ]);
+ touchDependencies(this._injector, [[MobileComponentsController]]);
+ }
+
+ override onRendered(): void {
+ touchDependencies(this._injector, [[SheetsSortMobileUIController]]);
+ }
+}
diff --git a/packages/sheets-sort-ui/src/views/mobile/MobileCustomSortPanel.tsx b/packages/sheets-sort-ui/src/views/mobile/MobileCustomSortPanel.tsx
new file mode 100644
index 0000000000..fc17ce49c3
--- /dev/null
+++ b/packages/sheets-sort-ui/src/views/mobile/MobileCustomSortPanel.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.
+ */
+
+import type { IOrderRule } from '@univerjs/sheets-sort';
+import type { LocaleKey } from '../../locale/types';
+import type { ISheetSortLocation } from '../../services/sheets-sort-ui.service';
+import { LocaleService } from '@univerjs/core';
+import { Button, Checkbox, MobileSelect } from '@univerjs/design';
+import { DeleteEmptyIcon } from '@univerjs/icons';
+import { SheetsSortService, SortType } from '@univerjs/sheets-sort';
+import { useDependency, useObservable } from '@univerjs/ui';
+import { useState } from 'react';
+import { SheetsSortUIService } from '../../services/sheets-sort-ui.service';
+
+export function MobileCustomSortPanel() {
+ const sheetsSortUIService = useDependency(SheetsSortUIService);
+ const state = useObservable(sheetsSortUIService.customSortState$);
+
+ if (!state?.location) {
+ return null;
+ }
+
+ return <MobileCustomSortPanelContent location={state.location} />;
+}
+
+function MobileCustomSortPanelContent({ location }: { location: ISheetSortLocation }) {
+ const sheetsSortService = useDependency(SheetsSortService);
+ const sheetsSortUIService = useDependency(SheetsSortUIService);
+ const localeService = useDependency(LocaleService);
+ const { range, unitId, subUnitId } = location;
+ const [hasTitle, setHasTitle] = useState(false);
+ const [orderRules, setOrderRules] = useState<IOrderRule[]>([
+ { type: SortType.ASC, colIndex: range.startColumn },
+ ]);
+ const titles = sheetsSortUIService.getTitles(hasTitle);
+ const canAddCondition = orderRules.length < titles.length;
+
+ function updateRule(index: number, update: Partial<IOrderRule>) {
+ setOrderRules((current) => current.map((rule, ruleIndex) =>
+ ruleIndex === index ? { ...rule, ...update } : rule));
+ }
+
+ function addCondition() {
+ setOrderRules((current) => {
+ const nextTitle = titles.find((title) => !current.some((rule) => rule.colIndex === title.index));
+ return nextTitle
+ ? [...current, { type: SortType.ASC, colIndex: nextTitle.index }]
+ : current;
+ });
+ }
+
+ function setTitle(value: boolean) {
+ setHasTitle(value);
+ sheetsSortUIService.setSelection(
+ unitId,
+ subUnitId,
+ value ? { ...range, startRow: range.startRow + 1 } : range
+ );
+ }
+
+ function apply() {
+ sheetsSortService.applySort({ range, orderRules, hasTitle }, unitId, subUnitId);
+ sheetsSortUIService.closeCustomSortPanel();
+ }
+
+ return (
+ <div className="univer-grid univer-gap-4">
+ <div className="univer-flex univer-items-center univer-justify-between univer-gap-3">
+ <Checkbox checked={hasTitle} onChange={(value) => setTitle(Boolean(value))}>
+ {localeService.t<LocaleKey>('sheets-sort-ui.dialog.first-row-check')}
+ </Checkbox>
+ <Button variant="text" disabled={!canAddCondition} onClick={addCondition}>
+ {localeService.t<LocaleKey>('sheets-sort-ui.dialog.add-condition')}
+ </Button>
+ </div>
+ <div className="univer-grid univer-gap-3">
+ {orderRules.map((rule, index) => {
+ const availableTitles = titles.filter((title) =>
+ title.index === rule.colIndex || !orderRules.some((item) => item.colIndex === title.index));
+
+ return (
+ <div
+ key={rule.colIndex}
+ className="
+ univer-grid univer-gap-2 univer-rounded-xl univer-bg-gray-50 univer-p-3
+ dark:!univer-bg-gray-800
+ "
+ >
+ <div className="univer-flex univer-items-center univer-gap-2">
+ <MobileSelect
+ className="!univer-min-w-0 univer-flex-1"
+ value={`${rule.colIndex}`}
+ options={availableTitles.map((title) => ({
+ label: title.label,
+ value: `${title.index}`,
+ }))}
+ onChange={(value) => updateRule(index, { colIndex: Number(value) })}
+ />
+ {orderRules.length > 1 && (
+ <Button
+ size="icon"
+ variant="text"
+ aria-label={localeService.t<LocaleKey>('sheets-sort-ui.dialog.delete-condition')}
+ onClick={() => setOrderRules((current) => current.filter((_, ruleIndex) => ruleIndex !== index))}
+ >
+ <DeleteEmptyIcon />
+ </Button>
+ )}
+ </div>
+ <MobileSelect
+ className="univer-w-full"
+ value={rule.type}
+ options={[
+ {
+ label: localeService.t<LocaleKey>('sheets-sort-ui.general.sort-asc'),
+ value: SortType.ASC,
+ },
+ {
+ label: localeService.t<LocaleKey>('sheets-sort-ui.general.sort-desc'),
+ value: SortType.DESC,
+ },
+ ]}
+ onChange={(value) => updateRule(index, { type: value as SortType })}
+ />
+ </div>
+ );
+ })}
+ </div>
+ <div
+ className="
+ univer-sticky univer-bottom-0 univer-grid univer-grid-cols-2 univer-gap-3 univer-bg-gray-0 univer-py-3
+ dark:!univer-bg-gray-900
+ "
+ >
+ <Button size="large" onClick={() => sheetsSortUIService.closeCustomSortPanel()}>
+ {localeService.t<LocaleKey>('sheets-sort-ui.dialog.cancel')}
+ </Button>
+ <Button size="large" variant="primary" onClick={apply}>
+ {localeService.t<LocaleKey>('sheets-sort-ui.dialog.confirm')}
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/sheets-table-ui/package.json b/packages/sheets-table-ui/package.json
index 3cb9412f39..e1b28dc968 100644
--- a/packages/sheets-table-ui/package.json
+++ b/packages/sheets-table-ui/package.json
@@ -72,6 +72,7 @@
},
"peerDependencies": {
"react": "^16.9.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc",
+ "react-dom": "^16.9.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc",
"rxjs": ">=7.0.0"
},
"dependencies": {
diff --git a/packages/sheets-table-ui/src/const.ts b/packages/sheets-table-ui/src/const.ts
index ff7c0ae3de..c7abf752bd 100644
--- a/packages/sheets-table-ui/src/const.ts
+++ b/packages/sheets-table-ui/src/const.ts
@@ -25,6 +25,7 @@ export const SHEET_TABLE_RENAME_DIALOG_ID = 'SHEET_TABLE_RENAME_DIALOG_ID';
export const SHEET_TABLE_THEME_PANEL_ID = 'SHEET_TABLE_THEME_PANEL_ID';
export const SHEET_TABLE_THEME_PANEL = 'SHEET_TABLE_THEME_PANEL';
export const SHEET_TABLE_MENU = 'SHEET_TABLE_MENU';
+export const SHEET_TABLE_MOBILE_MENU = 'SHEET_TABLE_MOBILE_MENU';
export const TABLE_CUSTOM_NAME_PREFIX = 'table-custom-';
export const TABLE_DEFAULT_NAME_PREFIX = 'table-default-';
diff --git a/packages/sheets-table-ui/src/controllers/mobile/components.controller.ts b/packages/sheets-table-ui/src/controllers/mobile/components.controller.ts
new file mode 100644
index 0000000000..65f1106137
--- /dev/null
+++ b/packages/sheets-table-ui/src/controllers/mobile/components.controller.ts
@@ -0,0 +1,51 @@
+/**
+ * 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 { Disposable, Inject } from '@univerjs/core';
+import { TableIcon } from '@univerjs/icons';
+import { ComponentManager, IconManager } from '@univerjs/ui';
+import {
+ SHEET_TABLE_MOBILE_MENU,
+ SHEET_TABLE_RENAME_DIALOG,
+ SHEET_TABLE_THEME_PANEL,
+ SHEETS_TABLE_FILTER_PANEL_OPENED_KEY,
+ TABLE_SELECTOR_DIALOG,
+} from '../../const';
+import { MobileSheetTableFilterPanel } from '../../views/components/MobileSheetTableFilterPanel';
+import { MobileSheetTableMenu } from '../../views/components/MobileSheetTableMenu';
+import { MobileSheetTableRenameDialog } from '../../views/components/MobileSheetTableRenameDialog';
+import { MobileSheetTableSelector } from '../../views/components/MobileSheetTableSelector';
+import { MobileSheetTableThemePanel } from '../../views/components/MobileSheetTableThemePanel';
+
+export class MobileComponentsController extends Disposable {
+ constructor(
+ @Inject(ComponentManager) componentManager: ComponentManager,
+ @Inject(IconManager) iconManager: IconManager
+ ) {
+ super();
+
+ ([
+ [SHEETS_TABLE_FILTER_PANEL_OPENED_KEY, MobileSheetTableFilterPanel],
+ [SHEET_TABLE_MOBILE_MENU, MobileSheetTableMenu],
+ [SHEET_TABLE_RENAME_DIALOG, MobileSheetTableRenameDialog],
+ [TABLE_SELECTOR_DIALOG, MobileSheetTableSelector],
+ [SHEET_TABLE_THEME_PANEL, MobileSheetTableThemePanel],
+ ] as const).forEach(([key, component]) => {
+ this.disposeWithMe(componentManager.register(key, component));
+ });
+ this.disposeWithMe(iconManager.register({ TableIcon }));
+ }
+}
diff --git a/packages/sheets-table-ui/src/controllers/mobile/sheet-table-component.controller.ts b/packages/sheets-table-ui/src/controllers/mobile/sheet-table-component.controller.ts
new file mode 100644
index 0000000000..edc2578886
--- /dev/null
+++ b/packages/sheets-table-ui/src/controllers/mobile/sheet-table-component.controller.ts
@@ -0,0 +1,35 @@
+/**
+ * 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 { SHEETS_TABLE_FILTER_PANEL_OPENED_KEY, UNIVER_SHEET_TABLE_FILTER_PANEL_ID } from '../../const';
+import { SheetsTableComponentController } from '../sheet-table-component.controller';
+
+export class SheetsTableMobileComponentController extends SheetsTableComponentController {
+ protected override _openFilterPopup(): void {
+ if (!this.getCurrentTableFilterInfo()) {
+ throw new Error('[SheetsFilterUIController]: no filter model when opening filter popup!');
+ }
+
+ this._dialogService.open({
+ id: UNIVER_SHEET_TABLE_FILTER_PANEL_ID,
+ title: { title: 'sheets-table-ui.filter.title' },
+ children: { label: SHEETS_TABLE_FILTER_PANEL_OPENED_KEY },
+ onClose: () => {
+ this._contextService.setContextValue(SHEETS_TABLE_FILTER_PANEL_OPENED_KEY, false);
+ },
+ });
+ }
+}
diff --git a/packages/sheets-table-ui/src/controllers/mobile/sheet-table-controls-render.controller.ts b/packages/sheets-table-ui/src/controllers/mobile/sheet-table-controls-render.controller.ts
new file mode 100644
index 0000000000..8d49cce406
--- /dev/null
+++ b/packages/sheets-table-ui/src/controllers/mobile/sheet-table-controls-render.controller.ts
@@ -0,0 +1,66 @@
+/**
+ * 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 { SheetTableMenuAction } from '../../views/components/SheetTableMenu';
+import { toDisposable } from '@univerjs/core';
+import { SHEET_TABLE_MOBILE_MENU } from '../../const';
+import { SheetTableControlsRenderController } from '../sheet-table-controls-render.controller';
+
+const SHEET_TABLE_MOBILE_MENU_DIALOG_ID = 'sheet-table-mobile-menu';
+
+export class SheetTableControlsMobileRenderController extends SheetTableControlsRenderController {
+ protected override _toggleTableMenu(unitId: string, subUnitId: string, tableId: string): void {
+ if (this._shape.getOpenedMenuTableId() === tableId) {
+ this._closeFloatingControls();
+ return;
+ }
+
+ const table = this._tableManager.getTableById(unitId, tableId);
+ const anchor = this._shape.getAnchorRegion(tableId);
+ if (!table || !anchor) {
+ return;
+ }
+
+ this._closeFloatingControls();
+ this._shape.setOpenedMenuTableId(tableId);
+ const extraProps = {
+ anchorWidth: anchor.width,
+ tableName: table.getDisplayName(),
+ labels: {
+ rename: this._localeService.t<LocaleKey>('sheets-table-ui.rename'),
+ 'update-range': this._localeService.t<LocaleKey>('sheets-table-ui.updateRange'),
+ 'set-theme': this._localeService.t<LocaleKey>('sheets-table-ui.setTheme'),
+ delete: this._localeService.t<LocaleKey>('sheets-table-ui.removeTable'),
+ },
+ onSelect: (action: SheetTableMenuAction) => this._handleTableMenuAction(action, unitId, subUnitId, tableId),
+ onClose: () => this._closeFloatingControls(),
+ };
+
+ this._dialogService.open({
+ id: SHEET_TABLE_MOBILE_MENU_DIALOG_ID,
+ title: { title: table.getDisplayName() },
+ children: {
+ label: {
+ name: SHEET_TABLE_MOBILE_MENU,
+ props: { menu: extraProps },
+ },
+ },
+ onClose: () => this._closeFloatingControls(),
+ });
+ this._menuPopup = toDisposable(() => this._dialogService.close(SHEET_TABLE_MOBILE_MENU_DIALOG_ID));
+ }
+}
diff --git a/packages/sheets-table-ui/src/controllers/sheet-table-component.controller.ts b/packages/sheets-table-ui/src/controllers/sheet-table-component.controller.ts
index bd4053e7e4..79c6a92526 100644
--- a/packages/sheets-table-ui/src/controllers/sheet-table-component.controller.ts
+++ b/packages/sheets-table-ui/src/controllers/sheet-table-component.controller.ts
@@ -17,11 +17,11 @@
import type { IDisposable, Nullable } from '@univerjs/core';
import { Disposable, IContextService, Inject } from '@univerjs/core';
import { SheetCanvasPopManagerService } from '@univerjs/sheets-ui';
-import { IDialogService, MOBILE_UI_MODE } from '@univerjs/ui';
+import { IDialogService } from '@univerjs/ui';
import { distinctUntilChanged, startWith } from 'rxjs';
import { SHEETS_TABLE_FILTER_PANEL_OPENED_KEY, UNIVER_SHEET_TABLE_FILTER_PANEL_ID } from '../const';
-interface ITableFilterPanelInfo {
+export interface ITableFilterPanelInfo {
unitId: string;
subUnitId: string;
tableId: string;
@@ -32,9 +32,9 @@ export class SheetsTableComponentController extends Disposable {
private _popupDisposable?: Nullable<IDisposable>;
private _currentTableFilterInfo: Nullable<ITableFilterPanelInfo> = null;
constructor(
- @IContextService private readonly _contextService: IContextService,
+ @IContextService protected readonly _contextService: IContextService,
@Inject(SheetCanvasPopManagerService) private _sheetCanvasPopupService: SheetCanvasPopManagerService,
- @Inject(IDialogService) private readonly _dialogService: IDialogService
+ @Inject(IDialogService) protected readonly _dialogService: IDialogService
) {
super();
@@ -90,24 +90,13 @@ export class SheetsTableComponentController extends Disposable {
this._contextService.setContextValue(SHEETS_TABLE_FILTER_PANEL_OPENED_KEY, false);
}
- private _openFilterPopup(): void {
+ protected _openFilterPopup(): void {
const currentFilterModel = this._currentTableFilterInfo;
if (!currentFilterModel) {
throw new Error('[SheetsFilterUIController]: no filter model when opening filter popup!');
}
const { row: startRow, column: col } = currentFilterModel;
- if (this._contextService.getContextValue(MOBILE_UI_MODE)) {
- this._dialogService.open({
- id: UNIVER_SHEET_TABLE_FILTER_PANEL_ID,
- title: { title: 'sheets-table-ui.filter.by-values' },
- children: { label: SHEETS_TABLE_FILTER_PANEL_OPENED_KEY },
- onClose: () => {
- this._contextService.setContextValue(SHEETS_TABLE_FILTER_PANEL_OPENED_KEY, false);
- },
- });
- return;
- }
this._popupDisposable = this._sheetCanvasPopupService.attachPopupToCell(startRow, col, {
componentKey: SHEETS_TABLE_FILTER_PANEL_OPENED_KEY,
direction: 'horizontal',
diff --git a/packages/sheets-table-ui/src/controllers/sheet-table-controls-render.controller.ts b/packages/sheets-table-ui/src/controllers/sheet-table-controls-render.controller.ts
index 2d7f2982af..13ef99750b 100644
--- a/packages/sheets-table-ui/src/controllers/sheet-table-controls-render.controller.ts
+++ b/packages/sheets-table-ui/src/controllers/sheet-table-controls-render.controller.ts
@@ -65,7 +65,7 @@ import {
SheetCanvasPopManagerService,
SheetSkeletonManagerService,
} from '@univerjs/sheets-ui';
-import { IDialogService, ISidebarService, MOBILE_UI_MODE } from '@univerjs/ui';
+import { IDialogService, ISidebarService } from '@univerjs/ui';
import { filter, merge } from 'rxjs';
import { openRangeSelector } from '../commands/operations/open-table-selector.operation';
import {
@@ -81,8 +81,6 @@ import { SheetTableThemeUIController } from './sheet-table-theme-ui.controller';
const TABLE_CONTROLS_LAYER_INDEX = 5002;
const TABLE_CONTROL_GAP_ROW = 0;
-const SHEET_TABLE_MOBILE_MENU_DIALOG_ID = 'sheet-table-mobile-menu';
-
const TABLE_RENDER_REFRESH_COMMANDS = new Set([
SetScrollOperation.id,
SetZoomRatioOperation.id,
@@ -106,27 +104,27 @@ function isSameTopGap(left: TopGapSnapshot, right: TopGapSnapshot): boolean {
}
export class SheetTableControlsRenderController extends Disposable implements IRenderModule {
- private readonly _shape: SheetTableControlsShape;
+ protected readonly _shape: SheetTableControlsShape;
private readonly _topGapBaseBySkeleton = new WeakMap<SpreadsheetSkeleton, TopGapSnapshot>();
- private _menuPopup: IDisposable | null = null;
+ protected _menuPopup: IDisposable | null = null;
constructor(
private readonly _context: IRenderContext<Workbook>,
@Inject(Injector) private readonly _injector: Injector,
@Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
@ICommandService private readonly _commandService: ICommandService,
- @Inject(TableManager) private readonly _tableManager: TableManager,
+ @Inject(TableManager) protected readonly _tableManager: TableManager,
@Inject(SheetRangeThemeModel) private readonly _rangeThemeModel: SheetRangeThemeModel,
@Inject(WorkbookPermissionService) private readonly _workbookPermissionService: WorkbookPermissionService,
@Inject(IPermissionService) private readonly _permissionService: IPermissionService,
@Inject(SheetsSelectionsService) private readonly _sheetsSelectionsService: SheetsSelectionsService,
@ISheetSelectionRenderService private readonly _selectionRenderService: ISheetSelectionRenderService,
@Inject(SheetTableThemeUIController) private readonly _sheetTableThemeUIController: SheetTableThemeUIController,
- @Inject(LocaleService) private readonly _localeService: LocaleService,
+ @Inject(LocaleService) protected readonly _localeService: LocaleService,
@IContextService private readonly _contextService: IContextService,
- @IDialogService private readonly _dialogService: IDialogService,
+ @IDialogService protected readonly _dialogService: IDialogService,
@ISidebarService private readonly _sidebarService: ISidebarService,
- @Inject(SheetCanvasPopManagerService) private readonly _sheetCanvasPopupService: SheetCanvasPopManagerService
+ @Inject(SheetCanvasPopManagerService) protected readonly _sheetCanvasPopupService: SheetCanvasPopManagerService
) {
super();
this._shape = new SheetTableControlsShape(
@@ -326,7 +324,7 @@ export class SheetTableControlsRenderController extends Disposable implements IR
}
}
- private _toggleTableMenu(unitId: string, subUnitId: string, tableId: string): void {
+ protected _toggleTableMenu(unitId: string, subUnitId: string, tableId: string): void {
if (this._shape.getOpenedMenuTableId() === tableId) {
this._closeFloatingControls();
return;
@@ -354,22 +352,6 @@ export class SheetTableControlsRenderController extends Disposable implements IR
onClose: () => this._closeFloatingControls(),
};
- if (this._contextService.getContextValue(MOBILE_UI_MODE)) {
- this._dialogService.open({
- id: SHEET_TABLE_MOBILE_MENU_DIALOG_ID,
- title: { title: table.getDisplayName() },
- children: {
- label: {
- name: SHEET_TABLE_MENU,
- props: { popup: { extraProps } },
- },
- },
- onClose: () => this._closeFloatingControls(),
- });
- this._menuPopup = toDisposable(() => this._dialogService.close(SHEET_TABLE_MOBILE_MENU_DIALOG_ID));
- return;
- }
-
this._menuPopup = this._sheetCanvasPopupService.attachPopupByPosition(
{
left: anchor.left,
@@ -395,7 +377,7 @@ export class SheetTableControlsRenderController extends Disposable implements IR
}
}
- private _handleTableMenuAction(action: SheetTableMenuAction, unitId: string, subUnitId: string, tableId: string): void | Promise<void> {
+ protected _handleTableMenuAction(action: SheetTableMenuAction, unitId: string, subUnitId: string, tableId: string): void | Promise<void> {
this._closeFloatingControls();
switch (action) {
@@ -595,7 +577,7 @@ export class SheetTableControlsRenderController extends Disposable implements IR
this._selectionRenderService.resetSelectionsByModelData(this._sheetsSelectionsService.getCurrentSelections());
}
- private _closeFloatingControls(): void {
+ protected _closeFloatingControls(): void {
const menuPopup = this._menuPopup;
this._menuPopup = null;
menuPopup?.dispose();
diff --git a/packages/sheets-table-ui/src/index.ts b/packages/sheets-table-ui/src/index.ts
index 476a10846a..4761408d15 100644
--- a/packages/sheets-table-ui/src/index.ts
+++ b/packages/sheets-table-ui/src/index.ts
@@ -18,4 +18,5 @@ import './global.css';
export type { IUniverSheetsTableUIConfig } from './config/config';
export { menuSchema as SheetsTableUIMenuSchema } from './menu/schema';
+export { UniverSheetsTableMobileUIPlugin } from './mobile-plugin';
export { UniverSheetsTableUIPlugin } from './plugin';
diff --git a/packages/sheets-table-ui/src/locale/ar-SA.ts b/packages/sheets-table-ui/src/locale/ar-SA.ts
index ec4ff32335..4434770720 100644
--- a/packages/sheets-table-ui/src/locale/ar-SA.ts
+++ b/packages/sheets-table-ui/src/locale/ar-SA.ts
@@ -140,8 +140,15 @@ const locale: typeof enUS = {
},
},
filter: {
+ title: 'تصفية',
'by-values': 'حسب القيم',
+ 'by-colors': 'حسب الألوان',
'by-conditions': 'حسب الشروط',
+ back: 'رجوع',
+ resize: 'تغيير الحجم',
+ 'filter-by-cell-fill-color': 'لون تعبئة الخلية',
+ 'filter-by-cell-text-color': 'لون نص الخلية',
+ 'filter-by-color-none': 'يحتوي هذا العمود على لون واحد فقط',
'clear-filter': 'مسح التصفية',
cancel: 'إلغاء',
confirm: 'تأكيد',
diff --git a/packages/sheets-table-ui/src/locale/ca-ES.ts b/packages/sheets-table-ui/src/locale/ca-ES.ts
index cb1560d019..5a16f07407 100644
--- a/packages/sheets-table-ui/src/locale/ca-ES.ts
+++ b/packages/sheets-table-ui/src/locale/ca-ES.ts
@@ -140,8 +140,15 @@ const locale: typeof enUS = {
},
},
filter: {
+ title: 'Filtre',
'by-values': 'Per valors',
+ 'by-colors': 'Per colors',
'by-conditions': 'Per condicions',
+ back: 'Enrere',
+ resize: 'Canvia la mida',
+ 'filter-by-cell-fill-color': 'Color de farciment de la cel·la',
+ 'filter-by-cell-text-color': 'Color del text de la cel·la',
+ 'filter-by-color-none': 'Aquesta columna només conté un color',
'clear-filter': 'Neteja el filtre',
cancel: 'Cancel·la',
confirm: 'Confirma',
diff --git a/packages/sheets-table-ui/src/locale/de-DE.ts b/packages/sheets-table-ui/src/locale/de-DE.ts
index a34fb65d91..ab3ccfaaea 100644
--- a/packages/sheets-table-ui/src/locale/de-DE.ts
+++ b/packages/sheets-table-ui/src/locale/de-DE.ts
@@ -140,8 +140,15 @@ const locale: typeof enUS = {
},
},
filter: {
+ title: 'Filter',
'by-values': 'Nach Werten',
+ 'by-colors': 'Nach Farben',
'by-conditions': 'Nach Bedingungen',
+ back: 'Zurück',
+ resize: 'Größe ändern',
+ 'filter-by-cell-fill-color': 'Zellfüllfarbe',
+ 'filter-by-cell-text-color': 'Zelltextfarbe',
+ 'filter-by-color-none': 'Diese Spalte enthält nur eine Farbe',
'clear-filter': 'Filter löschen',
cancel: 'Abbrechen',
confirm: 'Bestätigen',
diff --git a/packages/sheets-table-ui/src/locale/en-US.ts b/packages/sheets-table-ui/src/locale/en-US.ts
index a66cb2f497..0425033707 100644
--- a/packages/sheets-table-ui/src/locale/en-US.ts
+++ b/packages/sheets-table-ui/src/locale/en-US.ts
@@ -138,8 +138,15 @@ const locale = {
},
},
filter: {
+ title: 'Filter',
'by-values': 'By Values',
+ 'by-colors': 'By Colors',
'by-conditions': 'By Conditions',
+ back: 'Back',
+ resize: 'Resize',
+ 'filter-by-cell-fill-color': 'Cell fill color',
+ 'filter-by-cell-text-color': 'Cell text color',
+ 'filter-by-color-none': 'This column contains only one color',
'clear-filter': 'Clear Filter',
cancel: 'Cancel',
confirm: 'Confirm',
diff --git a/packages/sheets-table-ui/src/locale/es-ES.ts b/packages/sheets-table-ui/src/locale/es-ES.ts
index a2ca007d0c..54d0087d5f 100644
--- a/packages/sheets-table-ui/src/locale/es-ES.ts
+++ b/packages/sheets-table-ui/src/locale/es-ES.ts
@@ -140,8 +140,15 @@ const locale: typeof enUS = {
},
},
filter: {
+ title: 'Filtro',
'by-values': 'Por valores',
+ 'by-colors': 'Por colores',
'by-conditions': 'Por condiciones',
+ back: 'Atrás',
+ resize: 'Cambiar tamaño',
+ 'filter-by-cell-fill-color': 'Color de relleno de celda',
+ 'filter-by-cell-text-color': 'Color del texto de celda',
+ 'filter-by-color-none': 'Esta columna contiene un solo color',
'clear-filter': 'Borrar filtro',
cancel: 'Cancelar',
confirm: 'Confirmar',
diff --git a/packages/sheets-table-ui/src/locale/fa-IR.ts b/packages/sheets-table-ui/src/locale/fa-IR.ts
index 5d5ec8b0af..dd856ffcc5 100644
--- a/packages/sheets-table-ui/src/locale/fa-IR.ts
+++ b/packages/sheets-table-ui/src/locale/fa-IR.ts
@@ -142,8 +142,15 @@ const locale: typeof enUS = {
},
},
filter: {
+ title: 'فیلتر',
'by-values': 'بر اساس مقادیر',
+ 'by-colors': 'بر اساس رنگ‌ها',
'by-conditions': 'بر اساس شرایط',
+ back: 'بازگشت',
+ resize: 'تغییر اندازه',
+ 'filter-by-cell-fill-color': 'رنگ پس‌زمینه سلول',
+ 'filter-by-cell-text-color': 'رنگ متن سلول',
+ 'filter-by-color-none': 'این ستون فقط یک رنگ دارد',
'clear-filter': 'پاک کردن فیلتر',
cancel: 'انصراف',
confirm: 'تایید',
diff --git a/packages/sheets-table-ui/src/locale/fr-FR.ts b/packages/sheets-table-ui/src/locale/fr-FR.ts
index 086a025260..eb666b6923 100644
--- a/packages/sheets-table-ui/src/locale/fr-FR.ts
+++ b/packages/sheets-table-ui/src/locale/fr-FR.ts
@@ -141,8 +141,15 @@ const locale: typeof enUS = {
},
},
filter: {
+ title: 'Filtre',
'by-values': 'Par valeurs',
+ 'by-colors': 'Par couleurs',
'by-conditions': 'Par conditions',
+ back: 'Retour',
+ resize: 'Redimensionner',
+ 'filter-by-cell-fill-color': 'Couleur de remplissage de cellule',
+ 'filter-by-cell-text-color': 'Couleur du texte de cellule',
+ 'filter-by-color-none': 'Cette colonne ne contient qu’une seule couleur',
'clear-filter': 'Effacer le filtre',
cancel: 'Annuler',
confirm: 'Confirmer',
diff --git a/packages/sheets-table-ui/src/locale/id-ID.ts b/packages/sheets-table-ui/src/locale/id-ID.ts
index 36c733164c..eb696e984c 100644
--- a/packages/sheets-table-ui/src/locale/id-ID.ts
+++ b/packages/sheets-table-ui/src/locale/id-ID.ts
@@ -140,8 +140,15 @@ const locale: typeof enUS = {
},
},
filter: {
+ title: 'Filter',
'by-values': 'Berdasarkan Nilai',
+ 'by-colors': 'Berdasarkan Warna',
'by-conditions': 'Berdasarkan Kondisi',
+ back: 'Kembali',
+ resize: 'Ubah ukuran',
+ 'filter-by-cell-fill-color': 'Warna isian sel',
+ 'filter-by-cell-text-color': 'Warna teks sel',
+ 'filter-by-color-none': 'Kolom ini hanya berisi satu warna',
'clear-filter': 'Hapus Filter',
cancel: 'Batal',
confirm: 'Konfirmasi',
diff --git a/packages/sheets-table-ui/src/locale/it-IT.ts b/packages/sheets-table-ui/src/locale/it-IT.ts
index 127b1dee74..3658a7ba01 100644
--- a/packages/sheets-table-ui/src/locale/it-IT.ts
+++ b/packages/sheets-table-ui/src/locale/it-IT.ts
@@ -140,8 +140,15 @@ const locale: typeof enUS = {
},
},
filter: {
+ title: 'Filtro',
'by-values': 'Per Valori',
+ 'by-colors': 'Per Colori',
'by-conditions': 'Per Condizioni',
+ back: 'Indietro',
+ resize: 'Ridimensiona',
+ 'filter-by-cell-fill-color': 'Colore di riempimento cella',
+ 'filter-by-cell-text-color': 'Colore testo cella',
+ 'filter-by-color-none': 'Questa colonna contiene un solo colore',
'clear-filter': 'Cancella Filtro',
cancel: 'Annulla',
confirm: 'Conferma',
diff --git a/packages/sheets-table-ui/src/locale/ja-JP.ts b/packages/sheets-table-ui/src/locale/ja-JP.ts
index 525634f659..1733e055d9 100644
--- a/packages/sheets-table-ui/src/locale/ja-JP.ts
+++ b/packages/sheets-table-ui/src/locale/ja-JP.ts
@@ -140,8 +140,15 @@ const locale: typeof enUS = {
},
},
filter: {
+ title: 'フィルタ',
'by-values': '値でフィルタ',
+ 'by-colors': '色でフィルタ',
'by-conditions': '条件でフィルタ',
+ back: '戻る',
+ resize: 'サイズ変更',
+ 'filter-by-cell-fill-color': 'セルの塗りつぶし色',
+ 'filter-by-cell-text-color': 'セルの文字色',
+ 'filter-by-color-none': 'この列には 1 色のみ含まれています',
'clear-filter': 'フィルタをクリア',
cancel: 'キャンセル',
confirm: '確認',
diff --git a/packages/sheets-table-ui/src/locale/ko-KR.ts b/packages/sheets-table-ui/src/locale/ko-KR.ts
index 28a44028f6..7ee2e251c0 100644
--- a/packages/sheets-table-ui/src/locale/ko-KR.ts
+++ b/packages/sheets-table-ui/src/locale/ko-KR.ts
@@ -140,8 +140,15 @@ const locale: typeof enUS = {
},
},
filter: {
+ title: '필터',
'by-values': '값으로 필터',
+ 'by-colors': '색으로 필터',
'by-conditions': '조건으로 필터',
+ back: '뒤로',
+ resize: '크기 조절',
+ 'filter-by-cell-fill-color': '셀 채우기 색',
+ 'filter-by-cell-text-color': '셀 텍스트 색',
+ 'filter-by-color-none': '이 열에는 한 가지 색만 있습니다',
'clear-filter': '필터 지우기',
cancel: '취소',
confirm: '확인',
diff --git a/packages/sheets-table-ui/src/locale/pl-PL.ts b/packages/sheets-table-ui/src/locale/pl-PL.ts
index 3a681df9f0..26e062755c 100644
--- a/packages/sheets-table-ui/src/locale/pl-PL.ts
+++ b/packages/sheets-table-ui/src/locale/pl-PL.ts
@@ -140,8 +140,15 @@ const locale: typeof enUS = {
},
},
filter: {
+ title: 'Filtr',
'by-values': 'Według wartości',
+ 'by-colors': 'Według kolorów',
'by-conditions': 'Według warunków',
+ back: 'Wstecz',
+ resize: 'Zmień rozmiar',
+ 'filter-by-cell-fill-color': 'Kolor wypełnienia komórki',
+ 'filter-by-cell-text-color': 'Kolor tekstu komórki',
+ 'filter-by-color-none': 'Ta kolumna zawiera tylko jeden kolor',
'clear-filter': 'Wyczyść filtr',
cancel: 'Anuluj',
confirm: 'Potwierdź',
diff --git a/packages/sheets-table-ui/src/locale/pt-BR.ts b/packages/sheets-table-ui/src/locale/pt-BR.ts
index 6f46e94b84..4674abc7c0 100644
--- a/packages/sheets-table-ui/src/locale/pt-BR.ts
+++ b/packages/sheets-table-ui/src/locale/pt-BR.ts
@@ -140,8 +140,15 @@ const locale: typeof enUS = {
},
},
filter: {
+ title: 'Filtro',
'by-values': 'Por Valores',
+ 'by-colors': 'Por Cores',
'by-conditions': 'Por Condições',
+ back: 'Voltar',
+ resize: 'Redimensionar',
+ 'filter-by-cell-fill-color': 'Cor de preenchimento da célula',
+ 'filter-by-cell-text-color': 'Cor do texto da célula',
+ 'filter-by-color-none': 'Esta coluna contém apenas uma cor',
'clear-filter': 'Limpar Filtro',
cancel: 'Cancelar',
confirm: 'Confirmar',
diff --git a/packages/sheets-table-ui/src/locale/ru-RU.ts b/packages/sheets-table-ui/src/locale/ru-RU.ts
index 4094e5c100..6e9ccce564 100644
--- a/packages/sheets-table-ui/src/locale/ru-RU.ts
+++ b/packages/sheets-table-ui/src/locale/ru-RU.ts
@@ -142,8 +142,15 @@ const locale: typeof enUS = {
},
},
filter: {
+ title: 'Фильтр',
'by-values': 'По значениям',
+ 'by-colors': 'По цветам',
'by-conditions': 'По условиям',
+ back: 'Назад',
+ resize: 'Изменить размер',
+ 'filter-by-cell-fill-color': 'Цвет заливки ячейки',
+ 'filter-by-cell-text-color': 'Цвет текста ячейки',
+ 'filter-by-color-none': 'Этот столбец содержит только один цвет',
'clear-filter': 'Очистить фильтр',
cancel: 'Отмена',
confirm: 'Подтвердить',
diff --git a/packages/sheets-table-ui/src/locale/sk-SK.ts b/packages/sheets-table-ui/src/locale/sk-SK.ts
index c89bc28a30..c916733178 100644
--- a/packages/sheets-table-ui/src/locale/sk-SK.ts
+++ b/packages/sheets-table-ui/src/locale/sk-SK.ts
@@ -140,8 +140,15 @@ const locale: typeof enUS = {
},
},
filter: {
+ title: 'Filter',
'by-values': 'Podľa hodnôt',
+ 'by-colors': 'Podľa farieb',
'by-conditions': 'Podľa podmienok',
+ back: 'Späť',
+ resize: 'Zmeniť veľkosť',
+ 'filter-by-cell-fill-color': 'Farba výplne bunky',
+ 'filter-by-cell-text-color': 'Farba textu bunky',
+ 'filter-by-color-none': 'Tento stĺpec obsahuje iba jednu farbu',
'clear-filter': 'Vymazať filter',
cancel: 'Zrušiť',
confirm: 'Potvrdiť',
diff --git a/packages/sheets-table-ui/src/locale/vi-VN.ts b/packages/sheets-table-ui/src/locale/vi-VN.ts
index 2ca1cde09c..1ca3a0d448 100644
--- a/packages/sheets-table-ui/src/locale/vi-VN.ts
+++ b/packages/sheets-table-ui/src/locale/vi-VN.ts
@@ -142,8 +142,15 @@ const locale: typeof enUS = {
},
},
filter: {
+ title: 'Bộ lọc',
'by-values': 'Theo giá trị',
+ 'by-colors': 'Theo màu',
'by-conditions': 'Theo điều kiện',
+ back: 'Quay lại',
+ resize: 'Thay đổi kích thước',
+ 'filter-by-cell-fill-color': 'Màu nền ô',
+ 'filter-by-cell-text-color': 'Màu chữ ô',
+ 'filter-by-color-none': 'Cột này chỉ chứa một màu',
'clear-filter': 'Xóa lọc',
cancel: 'Hủy bỏ',
confirm: 'Xác nhận',
diff --git a/packages/sheets-table-ui/src/locale/zh-CN.ts b/packages/sheets-table-ui/src/locale/zh-CN.ts
index 6ee6cbe64c..95d6341b60 100644
--- a/packages/sheets-table-ui/src/locale/zh-CN.ts
+++ b/packages/sheets-table-ui/src/locale/zh-CN.ts
@@ -143,8 +143,15 @@ const locale: typeof enUS = {
},
},
filter: {
+ title: '筛选',
'by-values': '按值',
+ 'by-colors': '按颜色',
'by-conditions': '按条件',
+ back: '返回',
+ resize: '调整大小',
+ 'filter-by-cell-fill-color': '单元格填充颜色',
+ 'filter-by-cell-text-color': '单元格文本颜色',
+ 'filter-by-color-none': '此列仅包含一种颜色',
'clear-filter': '清除筛选',
cancel: '取消',
confirm: '确认',
diff --git a/packages/sheets-table-ui/src/locale/zh-HK.ts b/packages/sheets-table-ui/src/locale/zh-HK.ts
index f43b7864ce..c5ef608296 100644
--- a/packages/sheets-table-ui/src/locale/zh-HK.ts
+++ b/packages/sheets-table-ui/src/locale/zh-HK.ts
@@ -142,8 +142,15 @@ const locale: typeof enUS = {
},
},
filter: {
+ title: '篩選',
'by-values': '按值',
+ 'by-colors': '按顏色',
'by-conditions': '按條件',
+ back: '返回',
+ resize: '調整大小',
+ 'filter-by-cell-fill-color': '儲存格填滿顏色',
+ 'filter-by-cell-text-color': '儲存格文字顏色',
+ 'filter-by-color-none': '此欄僅包含一種顏色',
'clear-filter': '清除篩選',
cancel: '取消',
confirm: '確認',
diff --git a/packages/sheets-table-ui/src/locale/zh-TW.ts b/packages/sheets-table-ui/src/locale/zh-TW.ts
index f43b7864ce..c5ef608296 100644
--- a/packages/sheets-table-ui/src/locale/zh-TW.ts
+++ b/packages/sheets-table-ui/src/locale/zh-TW.ts
@@ -142,8 +142,15 @@ const locale: typeof enUS = {
},
},
filter: {
+ title: '篩選',
'by-values': '按值',
+ 'by-colors': '按顏色',
'by-conditions': '按條件',
+ back: '返回',
+ resize: '調整大小',
+ 'filter-by-cell-fill-color': '儲存格填滿顏色',
+ 'filter-by-cell-text-color': '儲存格文字顏色',
+ 'filter-by-color-none': '此欄僅包含一種顏色',
'clear-filter': '清除篩選',
cancel: '取消',
confirm: '確認',
diff --git a/packages/sheets-table-ui/src/mobile-plugin.ts b/packages/sheets-table-ui/src/mobile-plugin.ts
new file mode 100644
index 0000000000..5c5be535b2
--- /dev/null
+++ b/packages/sheets-table-ui/src/mobile-plugin.ts
@@ -0,0 +1,136 @@
+/**
+ * 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 { Dependency } from '@univerjs/core';
+import type { IUniverSheetsTableUIConfig } from './config/config';
+import {
+ DependentOn,
+ ICommandService,
+ IConfigService,
+ Inject,
+ Injector,
+ merge,
+ Plugin,
+ registerDependencies,
+ touchDependencies,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { IRenderManagerService, UniverRenderEnginePlugin } from '@univerjs/engine-render';
+import { UniverSheetsPlugin } from '@univerjs/sheets';
+import { UniverSheetsTablePlugin } from '@univerjs/sheets-table';
+import { UniverSheetsMobileUIPlugin } from '@univerjs/sheets-ui';
+import { UniverMobileUIPlugin } from '@univerjs/ui';
+import pkg from '../package.json';
+import { OpenTableFilterPanelOperation } from './commands/operations/open-table-filter-dialog.opration';
+import { OpenTableSelectorOperation } from './commands/operations/open-table-selector.operation';
+import { defaultPluginConfig, SHEETS_TABLE_UI_PLUGIN_CONFIG_KEY } from './config/config';
+import { PLUGIN_NAME } from './const';
+import { MobileComponentsController } from './controllers/mobile/components.controller';
+import { SheetsTableMobileComponentController } from './controllers/mobile/sheet-table-component.controller';
+import { SheetTableControlsMobileRenderController } from './controllers/mobile/sheet-table-controls-render.controller';
+import { SheetsTableComponentController } from './controllers/sheet-table-component.controller';
+import { SheetsTableFilterButtonRenderController } from './controllers/sheet-table-filter-button-render.controller';
+import { SheetsTableRenderController } from './controllers/sheet-table-render.controller';
+import { SheetTableSelectionController } from './controllers/sheet-table-selection.controller';
+import { SheetTableThemeUIController } from './controllers/sheet-table-theme-ui.controller';
+import { SheetTableMenuController } from './menu/sheet-table-menu.controller';
+import { SheetsTableUiService } from './services/sheets-table-ui.service';
+
+@DependentOn(
+ UniverRenderEnginePlugin,
+ UniverSheetsPlugin,
+ UniverSheetsTablePlugin,
+ UniverSheetsMobileUIPlugin,
+ UniverMobileUIPlugin
+)
+export class UniverSheetsTableMobileUIPlugin extends Plugin {
+ static override pluginName = PLUGIN_NAME;
+ static override packageName = pkg.name;
+ static override version = pkg.version;
+ static override type = UniverInstanceType.UNIVER_SHEET;
+
+ constructor(
+ private readonly _config: Partial<IUniverSheetsTableUIConfig> = defaultPluginConfig,
+ @Inject(Injector) protected override readonly _injector: Injector,
+ @Inject(ICommandService) private readonly _commandService: ICommandService,
+ @IConfigService private readonly _configService: IConfigService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService
+ ) {
+ super();
+
+ const { menu, ...rest } = merge({}, defaultPluginConfig, this._config);
+ if (menu) {
+ this._configService.setConfig('menu', menu, { merge: true });
+ }
+ this._configService.setConfig(SHEETS_TABLE_UI_PLUGIN_CONFIG_KEY, rest);
+
+ this._initRegisterCommand();
+ }
+
+ override onStarting(): void {
+ this._injector.add([MobileComponentsController]);
+ this._injector.get(MobileComponentsController);
+
+ registerDependencies(this._injector, [
+ [SheetsTableMobileComponentController],
+ [SheetsTableComponentController, { useExisting: SheetsTableMobileComponentController }],
+ [SheetsTableUiService],
+ [SheetTableMenuController],
+ [SheetTableThemeUIController],
+ [SheetTableSelectionController],
+ ]);
+ }
+
+ override onReady(): void {
+ touchDependencies(this._injector, [
+ [SheetsTableMobileComponentController],
+ [SheetsTableUiService],
+ [SheetTableMenuController],
+ [SheetTableThemeUIController],
+ [SheetTableSelectionController],
+ ]);
+ }
+
+ override onRendered(): void {
+ this._registerRenderModules();
+ }
+
+ private _registerRenderModules(): void {
+ const renderDependencies: Dependency[] = [];
+ if (this._config.hideAnchor !== true) {
+ renderDependencies.push([
+ SheetTableControlsMobileRenderController,
+ ]);
+ }
+ renderDependencies.push(
+ [SheetsTableFilterButtonRenderController],
+ [SheetsTableRenderController]
+ );
+
+ renderDependencies.forEach((dependency) => {
+ this.disposeWithMe(
+ this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, dependency)
+ );
+ });
+ }
+
+ private _initRegisterCommand(): void {
+ [
+ OpenTableFilterPanelOperation,
+ OpenTableSelectorOperation,
+ ].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));
+ }
+}
diff --git a/packages/sheets-table-ui/src/services/__tests__/sheets-table-ui.service.spec.ts b/packages/sheets-table-ui/src/services/__tests__/sheets-table-ui.service.spec.ts
index 05a0dbedfd..e81ccb9566 100644
--- a/packages/sheets-table-ui/src/services/__tests__/sheets-table-ui.service.spec.ts
+++ b/packages/sheets-table-ui/src/services/__tests__/sheets-table-ui.service.spec.ts
@@ -15,7 +15,17 @@
*/
import type { Dependency, IWorkbookData, Workbook } from '@univerjs/core';
-import { ICommandService, Inject, Injector, LocaleService, LocaleType, Plugin, Univer, UniverInstanceType } from '@univerjs/core';
+import {
+ ICommandService,
+ Inject,
+ Injector,
+ LocaleService,
+ LocaleType,
+ Plugin,
+ ThemeColorType,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
import { SetRangeValuesMutation } from '@univerjs/sheets';
import {
SetSheetTableFilterCommand,
@@ -55,11 +65,11 @@ function createWorkbookData(): IWorkbookData {
},
1: {
0: { v: 'book' },
- 1: { v: 12 },
+ 1: { v: 12, s: { bg: { rgb: '#ff0000' } } },
},
2: {
0: { v: 'pen' },
- 1: { v: 3 },
+ 1: { v: 3, s: { bg: { rgb: '#0000ff' } } },
},
3: {
1: { v: 8 },
@@ -165,6 +175,70 @@ describe('SheetsTableUiService', () => {
expect(service.getTableFilterCheckedItems(testBed.workbook.getUnitId(), 'table-orders', 0)).toEqual(['book', '(Empty)']);
});
+ it('builds color filter state and candidates after applying other table filters', async () => {
+ testBed = createTestBed();
+ const service = testBed.get(SheetsTableUiService);
+ await testBed.get(ICommandService).executeCommand(SetRangeValuesMutation.id, {
+ unitId: testBed.workbook.getUnitId(),
+ subUnitId: 'sheet1',
+ cellValue: {
+ 1: {
+ 1: { v: 12, s: { bg: { rgb: '#ff0000' }, cl: { rgb: null } } },
+ },
+ },
+ });
+ const table = testBed.get(TableManager).getTable(testBed.workbook.getUnitId(), 'table-orders')!;
+ table.setTableFilterColumn(1, {
+ filterType: TableColumnFilterTypeEnum.color,
+ cellFillColors: ['rgb(255, 0, 0)'],
+ });
+
+ expect(service.getTableFilterPanelInitProps(
+ testBed.workbook.getUnitId(),
+ 'sheet1',
+ 'table-orders',
+ 1
+ ).currentFilterBy).toBe(FilterByEnum.Color);
+ expect(service.getTableFilterColors(
+ testBed.workbook.getUnitId(),
+ 'sheet1',
+ 'table-orders',
+ 1
+ )).toEqual({
+ cellFillColors: [
+ { color: 'rgb(255,0,0)', checked: true },
+ { color: null, checked: false },
+ ],
+ cellTextColors: [
+ { color: 'rgb(0,0,0)', checked: false },
+ ],
+ });
+ });
+
+ it('includes theme colors in table filter candidates', async () => {
+ testBed = createTestBed();
+ const commandService = testBed.get(ICommandService);
+ await commandService.executeCommand(SetRangeValuesMutation.id, {
+ unitId: testBed.workbook.getUnitId(),
+ subUnitId: 'sheet1',
+ cellValue: {
+ 1: {
+ 1: { v: 12, s: { bg: { th: ThemeColorType.ACCENT1 } } },
+ },
+ },
+ });
+
+ expect(testBed.get(SheetsTableUiService).getTableFilterColors(
+ testBed.workbook.getUnitId(),
+ 'sheet1',
+ 'table-orders',
+ 1
+ ).cellFillColors).toEqual([
+ { color: 'rgb(68,114,196)', checked: false },
+ { color: null, checked: false },
+ ]);
+ });
+
it('builds candidate values after applying filters from other table columns', () => {
testBed = createTestBed();
const service = testBed.get(SheetsTableUiService);
diff --git a/packages/sheets-table-ui/src/services/sheets-table-ui.service.ts b/packages/sheets-table-ui/src/services/sheets-table-ui.service.ts
index f17c41f373..b4b1461285 100644
--- a/packages/sheets-table-ui/src/services/sheets-table-ui.service.ts
+++ b/packages/sheets-table-ui/src/services/sheets-table-ui.service.ts
@@ -14,14 +14,17 @@
* limitations under the License.
*/
-import type { Workbook } from '@univerjs/core';
+import type { Nullable, Workbook, Worksheet } from '@univerjs/core';
import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
import type { ISetSheetTableParams, ITableFilterItem } from '@univerjs/sheets-table';
import type { LocaleKey } from '../locale/types';
-import type { IFilterByValueWithTreeItem, ITableFilterItemList } from '../types';
+import type { IFilterByValueWithTreeItem, ITableFilterColorList, ITableFilterItemList } from '../types';
import {
cellToRange,
+ ColorKit,
+ DEFAULT_STYLES,
Disposable,
+ getColorStyle,
ICommandService,
Inject,
IUniverInstanceService,
@@ -31,6 +34,7 @@ import {
} from '@univerjs/core';
import { SetRangeValuesMutation } from '@univerjs/sheets';
import {
+ isColorTableFilter,
isConditionFilter,
isManualTableFilter,
SetSheetTableFilterCommand,
@@ -109,7 +113,9 @@ export class SheetsTableUiService extends Disposable {
unitId,
subUnitId,
tableFilter,
- currentFilterBy: isConditionFilter(tableFilter) ? FilterByEnum.Condition : FilterByEnum.Items,
+ currentFilterBy: isConditionFilter(tableFilter)
+ ? FilterByEnum.Condition
+ : isColorTableFilter(tableFilter) ? FilterByEnum.Color : FilterByEnum.Items,
tableId,
columnIndex: column - tableRange.startColumn,
};
@@ -127,10 +133,15 @@ export class SheetsTableUiService extends Disposable {
return checkedItems;
}
- setTableFilter(unitId: string, tableId: string, columnIndex: number, tableFilter: ITableFilterItem | undefined) {
+ async setTableFilter(
+ unitId: string,
+ tableId: string,
+ columnIndex: number,
+ tableFilter: ITableFilterItem | undefined
+ ): Promise<boolean> {
const table = this._tableManager.getTable(unitId, tableId);
if (!table) {
- return;
+ return false;
}
const setTableFilterParams: ISetSheetTableParams = {
unitId,
@@ -138,7 +149,62 @@ export class SheetsTableUiService extends Disposable {
column: columnIndex,
tableFilter,
};
- this._commandService.executeCommand(SetSheetTableFilterCommand.id, setTableFilterParams);
+ return this._commandService.executeCommand(SetSheetTableFilterCommand.id, setTableFilterParams);
+ }
+
+ getTableFilterColors(
+ unitId: string,
+ subUnitId: string,
+ tableId: string,
+ columnIndex: number
+ ): ITableFilterColorList {
+ const emptyResult = { cellFillColors: [], cellTextColors: [] };
+ const table = this._tableManager.getTable(unitId, tableId);
+ if (!table) {
+ return emptyResult;
+ }
+
+ const worksheet = this._univerInstanceService.getUnit<Workbook>(unitId)?.getSheetBySheetId(subUnitId);
+ if (!worksheet) {
+ return emptyResult;
+ }
+
+ const normalizeColor = (color: Nullable<string>) => color ? new ColorKit(color).toRgbString() : null;
+ const currentFilter = table.getTableFilterColumn(columnIndex);
+ const checkedFillColors = new Set(
+ isColorTableFilter(currentFilter) ? currentFilter.cellFillColors?.map(normalizeColor) : []
+ );
+ const checkedTextColors = new Set(
+ isColorTableFilter(currentFilter) ? currentFilter.cellTextColors?.map(normalizeColor) : []
+ );
+ const cellFillColors = new Map<string | null, boolean>();
+ const cellTextColors = new Map<string | null, boolean>();
+ const tableRange = table.getTableFilterRange();
+ const column = tableRange.startColumn + columnIndex;
+ const filteredRowsByOtherColumns = this._getFilteredRowsByOtherColumns(
+ worksheet,
+ tableId,
+ unitId,
+ columnIndex
+ );
+
+ for (let row = tableRange.startRow; row <= tableRange.endRow; row++) {
+ if (filteredRowsByOtherColumns.has(row)) {
+ continue;
+ }
+
+ const cellData = worksheet.getCell(row, column);
+ const style = worksheet.getComposedCellStyleByCellData(row, column, cellData);
+ const fillColor = normalizeColor(getColorStyle(style.bg));
+ const textColor = normalizeColor(getColorStyle(style.cl) ?? getColorStyle(DEFAULT_STYLES.cl));
+ cellFillColors.set(fillColor, checkedFillColors.has(fillColor));
+ cellTextColors.set(textColor, checkedTextColors.has(textColor));
+ }
+
+ return {
+ cellFillColors: Array.from(cellFillColors, ([color, checked]) => ({ color, checked })),
+ cellTextColors: Array.from(cellTextColors, ([color, checked]) => ({ color, checked })),
+ };
}
getTableFilterItems(unitId: string, subUnitId: string, tableId: string, columnIndex: number): ITableFilterItemList {
@@ -160,14 +226,12 @@ export class SheetsTableUiService extends Disposable {
const data: IFilterByValueWithTreeItem[] = [];
const map = new Map<string, number>();
- const filteredRowsByOtherColumns = new Set<number>();
- const tableFilters = table.getTableFilters();
- for (let i = tableRange.startColumn; i <= tableRange.endColumn; i++) {
- const currentColumnIndex = i - tableRange.startColumn;
- if (currentColumnIndex !== columnIndex && table.getTableFilterColumn(currentColumnIndex)) {
- tableFilters.doColumnFilter(worksheet, tableRange, currentColumnIndex, filteredRowsByOtherColumns);
- }
- }
+ const filteredRowsByOtherColumns = this._getFilteredRowsByOtherColumns(
+ worksheet,
+ tableId,
+ unitId,
+ columnIndex
+ );
let allItemsCount = 0;
for (let row = startRow; row <= endRow; row++) {
@@ -193,4 +257,27 @@ export class SheetsTableUiService extends Disposable {
this._itemsCache.set(tableId + columnIndex, { data, itemsCountMap: map, allItemsCount });
return { data, itemsCountMap: map, allItemsCount };
}
+
+ private _getFilteredRowsByOtherColumns(
+ worksheet: Worksheet,
+ tableId: string,
+ unitId: string,
+ columnIndex: number
+ ): Set<number> {
+ const filteredRows = new Set<number>();
+ const table = this._tableManager.getTable(unitId, tableId);
+ if (!table) {
+ return filteredRows;
+ }
+
+ const tableRange = table.getTableFilterRange();
+ const tableFilters = table.getTableFilters();
+ for (let column = tableRange.startColumn; column <= tableRange.endColumn; column++) {
+ const currentColumnIndex = column - tableRange.startColumn;
+ if (currentColumnIndex !== columnIndex && table.getTableFilterColumn(currentColumnIndex)) {
+ tableFilters.doColumnFilter(worksheet, tableRange, currentColumnIndex, filteredRows);
+ }
+ }
+ return filteredRows;
+ }
}
diff --git a/packages/sheets-table-ui/src/types.ts b/packages/sheets-table-ui/src/types.ts
index c70541f8ce..0084d09200 100644
--- a/packages/sheets-table-ui/src/types.ts
+++ b/packages/sheets-table-ui/src/types.ts
@@ -16,9 +16,20 @@
export enum FilterByEnum {
Items = 'items',
+ Color = 'color',
Condition = 'condition',
}
+export interface ITableFilterColorItem {
+ color: string | null;
+ checked: boolean;
+}
+
+export interface ITableFilterColorList {
+ cellFillColors: ITableFilterColorItem[];
+ cellTextColors: ITableFilterColorItem[];
+}
+
export interface IFilterByValueWithTreeItem {
title: string;
key: string;
diff --git a/packages/sheets-table-ui/src/views/components/MobileSheetTableColorFilterPanel.tsx b/packages/sheets-table-ui/src/views/components/MobileSheetTableColorFilterPanel.tsx
new file mode 100644
index 0000000000..50017c5cec
--- /dev/null
+++ b/packages/sheets-table-ui/src/views/components/MobileSheetTableColorFilterPanel.tsx
@@ -0,0 +1,128 @@
+/**
+ * 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 { ITableFilterColorItem, ITableFilterColorList } from '../../types';
+import { LocaleService } from '@univerjs/core';
+import { clsx, resetButtonClassName } from '@univerjs/design';
+import { AIcon, BanIcon, CheckMarkIcon } from '@univerjs/icons';
+import { useDependency } from '@univerjs/ui';
+
+interface IMobileSheetTableColorFilterPanelProps {
+ colors: ITableFilterColorList;
+ onChange: (colors: ITableFilterColorList) => void;
+}
+
+function MobileColorOption(props: {
+ item: ITableFilterColorItem;
+ label: string;
+ textColor?: boolean;
+ onClick: () => void;
+}) {
+ const { item, label, textColor = false, onClick } = props;
+ return (
+ <button
+ type="button"
+ aria-label={item.color ?? label}
+ aria-pressed={item.checked}
+ className={clsx(resetButtonClassName, `
+ univer-relative univer-flex univer-size-12 univer-items-center univer-justify-center univer-rounded-full
+ univer-border univer-border-solid univer-border-gray-200 univer-bg-gray-0
+ dark:!univer-border-gray-600 dark:!univer-bg-gray-800
+ `)}
+ style={!textColor && item.color ? { backgroundColor: item.color } : undefined}
+ onClick={onClick}
+ >
+ {!item.color && <BanIcon className="univer-size-7" />}
+ {textColor && item.color && <AIcon className="univer-size-7" style={{ color: item.color }} />}
+ {item.checked && (
+ <span
+ className="
+ univer-absolute -univer-bottom-1 -univer-right-1 univer-flex univer-size-5 univer-items-center
+ univer-justify-center univer-rounded-full univer-bg-primary-600 univer-text-gray-0
+ "
+ >
+ <CheckMarkIcon className="univer-size-3" />
+ </span>
+ )}
+ </button>
+ );
+}
+
+export function MobileSheetTableColorFilterPanel(props: IMobileSheetTableColorFilterPanelProps) {
+ const { colors, onChange } = props;
+ const localeService = useDependency(LocaleService);
+ const fillLabel = localeService.t<LocaleKey>('sheets-table-ui.filter.filter-by-cell-fill-color');
+ const textLabel = localeService.t<LocaleKey>('sheets-table-ui.filter.filter-by-cell-text-color');
+ const hasMultipleColors = colors.cellFillColors.length > 1 || colors.cellTextColors.length > 1;
+
+ function toggleColor(item: ITableFilterColorItem, fillColor: boolean) {
+ const key = fillColor ? 'cellFillColors' : 'cellTextColors';
+ const otherKey = fillColor ? 'cellTextColors' : 'cellFillColors';
+ onChange({
+ ...colors,
+ [key]: colors[key].map((color) => color.color === item.color
+ ? { ...color, checked: !color.checked }
+ : color),
+ [otherKey]: colors[otherKey].map((color) => ({ ...color, checked: false })),
+ });
+ }
+
+ return (
+ <div data-u-comp="mobile-sheet-table-filter-by-colors" className="univer-grid univer-gap-6">
+ {colors.cellFillColors.length > 1 && (
+ <section>
+ <h3 className="univer-m-0 univer-mb-4 univer-text-base univer-font-medium">{fillLabel}</h3>
+ <div className="univer-flex univer-flex-wrap univer-gap-4">
+ {colors.cellFillColors.map((item) => (
+ <MobileColorOption
+ key={item.color ?? 'none'}
+ item={item}
+ label={fillLabel}
+ onClick={() => toggleColor(item, true)}
+ />
+ ))}
+ </div>
+ </section>
+ )}
+ {colors.cellTextColors.length > 1 && (
+ <section>
+ <h3 className="univer-m-0 univer-mb-4 univer-text-base univer-font-medium">{textLabel}</h3>
+ <div className="univer-flex univer-flex-wrap univer-gap-4">
+ {colors.cellTextColors.map((item) => (
+ <MobileColorOption
+ key={item.color ?? 'none'}
+ item={item}
+ label={textLabel}
+ textColor
+ onClick={() => toggleColor(item, false)}
+ />
+ ))}
+ </div>
+ </section>
+ )}
+ {!hasMultipleColors && (
+ <div
+ className="
+ univer-flex univer-min-h-40 univer-items-center univer-justify-center univer-text-gray-500
+ "
+ >
+ {localeService.t<LocaleKey>('sheets-table-ui.filter.filter-by-color-none')}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/packages/sheets-table-ui/src/views/components/MobileSheetTableConditionPanel.tsx b/packages/sheets-table-ui/src/views/components/MobileSheetTableConditionPanel.tsx
new file mode 100644
index 0000000000..f0bdf88ea8
--- /dev/null
+++ b/packages/sheets-table-ui/src/views/components/MobileSheetTableConditionPanel.tsx
@@ -0,0 +1,220 @@
+/**
+ * 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 { ITableFilterItem } from '@univerjs/sheets-table';
+import type { LocaleKey } from '../../locale/types';
+import type {
+ IConditionCompareTypeEnum,
+ IConditionExpect,
+ IConditionInfo,
+ ITableConditionTypeEnumWithoutLogic,
+} from './type';
+import { Injector, LocaleService } from '@univerjs/core';
+import {
+ borderClassName,
+ CascaderList,
+ clsx,
+ DatePicker,
+ DateRangePicker,
+ Input,
+ InputNumber,
+ MobileDropdown,
+ MobileSelect,
+} from '@univerjs/design';
+import { MoreDownIcon } from '@univerjs/icons';
+import { TableConditionTypeEnum, TableDateCompareTypeEnum, TableStringCompareTypeEnum } from '@univerjs/sheets-table';
+import { useDependency } from '@univerjs/ui';
+import { useState } from 'react';
+import { ConditionSubComponentEnum } from './type';
+import { datePickerSet, getCascaderListOptions, getConditionDateSelect, getSubComponentType } from './util';
+
+interface IMobileSheetTableConditionPanelProps {
+ unitId: string;
+ subUnitId: string;
+ tableFilter: ITableFilterItem | undefined;
+ tableId: string;
+ columnIndex: number;
+ conditionInfo: IConditionInfo;
+ onChange: (conditionInfo: IConditionInfo) => void;
+}
+
+export function MobileSheetTableConditionPanel(props: IMobileSheetTableConditionPanelProps) {
+ const { conditionInfo, onChange } = props;
+ const localeService = useDependency(LocaleService);
+ const injector = useDependency(Injector);
+ const [conditionVisible, setConditionVisible] = useState(false);
+ const [defaultDate] = useState(() => new Date());
+ const cascaderOptions = getCascaderListOptions(injector);
+
+ function handleConditionInfo(
+ info: IConditionExpect,
+ type?: ITableConditionTypeEnumWithoutLogic,
+ compare?: IConditionCompareTypeEnum
+ ) {
+ onChange({
+ type: type ?? conditionInfo.type,
+ compare: compare ?? conditionInfo.compare,
+ info,
+ });
+ }
+
+ function handleChange(value: string[]) {
+ const type = value[0] as ITableConditionTypeEnumWithoutLogic;
+ const compare = value[1] as IConditionCompareTypeEnum;
+ if (compare) {
+ setConditionVisible(false);
+ }
+
+ const info: IConditionExpect = {};
+ if (type === TableConditionTypeEnum.Date) {
+ if (compare === TableDateCompareTypeEnum.Quarter) {
+ info.dateSelect = TableDateCompareTypeEnum.Q1;
+ } else if (compare === TableDateCompareTypeEnum.Month) {
+ info.dateSelect = TableDateCompareTypeEnum.M1;
+ } else if (datePickerSet.has(compare)) {
+ info.date = new Date();
+ } else {
+ info.dateRange = [new Date(), new Date()];
+ }
+ } else if (type === TableConditionTypeEnum.Number) {
+ info.number = 0;
+ } else if (type === TableConditionTypeEnum.String) {
+ info.string = '';
+ }
+ handleConditionInfo(info, type, compare ?? TableStringCompareTypeEnum.Equal);
+ }
+
+ const subComponentType = getSubComponentType(conditionInfo.type, conditionInfo.compare);
+ const selectType = conditionInfo.compare
+ ? `${localeService.t(`sheets-table-ui.condition.${conditionInfo.type}`)} - ${localeService.t(`sheets-table-ui.${conditionInfo.type}.compare.${conditionInfo.compare}`)}`
+ : localeService.t(`sheets-table-ui.condition.${conditionInfo.type}`);
+ const conditionDateOptions = getConditionDateSelect(injector, conditionInfo.compare as TableDateCompareTypeEnum);
+
+ return (
+ <div>
+ <MobileDropdown
+ align="start"
+ open={conditionVisible}
+ onOpenChange={setConditionVisible}
+ overlay={(
+ <CascaderList
+ value={[conditionInfo.type, conditionInfo.compare!]}
+ options={cascaderOptions}
+ onChange={handleChange}
+ contentClassName="univer-flex-1"
+ wrapperClassName="!univer-h-[150px]"
+ />
+ )}
+ >
+ <div
+ className={clsx(`
+ univer-box-border univer-flex univer-h-8 univer-w-full univer-items-center univer-justify-between
+ univer-rounded-md univer-bg-gray-0 univer-px-2 univer-text-sm univer-transition-colors
+ univer-duration-200
+ hover:univer-border-primary-600
+ focus:univer-border-primary-600 focus:univer-outline-none focus:univer-ring-2
+ dark:!univer-bg-gray-700 dark:!univer-text-gray-0
+ `, borderClassName)}
+ >
+ <span>{selectType}</span>
+ <MoreDownIcon />
+ </div>
+ </MobileDropdown>
+
+ <div className="univer-mt-3 univer-w-full">
+ {subComponentType === ConditionSubComponentEnum.Input && (
+ <>
+ {conditionInfo.type === TableConditionTypeEnum.String
+ ? (
+ <Input
+ className="univer-w-full"
+ placeholder={localeService.t<LocaleKey>('sheets-table-ui.filter.input-values-placeholder')}
+ value={conditionInfo.info.string}
+ onChange={(value) => handleConditionInfo({ string: value })}
+ />
+ )
+ : (
+ <InputNumber
+ className="univer-h-7 univer-w-full"
+ value={conditionInfo.info.number}
+ controls={false}
+ onChange={(value) => {
+ if (value !== null) {
+ handleConditionInfo({ number: value });
+ }
+ }}
+ />
+ )}
+ </>
+ )}
+ {subComponentType === ConditionSubComponentEnum.DatePicker && (
+ <div id="univer-table-date-picker-wrapper">
+ <DatePicker
+ className="univer-w-full"
+ value={conditionInfo.info.date ?? defaultDate}
+ onValueChange={(value) => handleConditionInfo({ date: value })}
+ />
+ </div>
+ )}
+ {subComponentType === ConditionSubComponentEnum.DateRange && (
+ <div id="univer-table-date-range-wrapper">
+ <DateRangePicker
+ className="univer-w-full"
+ value={[
+ conditionInfo.info.dateRange?.[0] ?? defaultDate,
+ conditionInfo.info.dateRange?.[1] ?? defaultDate,
+ ]}
+ onValueChange={(value) => handleConditionInfo(value ? { dateRange: value } : {})}
+ />
+ </div>
+ )}
+ {subComponentType === ConditionSubComponentEnum.Inputs && (
+ <div className="univer-flex univer-items-center univer-gap-2">
+ <InputNumber
+ className="univer-w-full"
+ value={conditionInfo.info.numberRange?.[0]}
+ controls={false}
+ onChange={(value) => {
+ if (value !== null) {
+ handleConditionInfo({ numberRange: [value, conditionInfo.info.numberRange?.[1]] });
+ }
+ }}
+ />
+ <span> - </span>
+ <InputNumber
+ className="univer-w-full"
+ value={conditionInfo.info.numberRange?.[1]}
+ controls={false}
+ onChange={(value) => {
+ if (value !== null) {
+ handleConditionInfo({ numberRange: [conditionInfo.info.numberRange?.[0], value] });
+ }
+ }}
+ />
+ </div>
+ )}
+ {subComponentType === ConditionSubComponentEnum.Select && (
+ <MobileSelect
+ className="univer-w-full"
+ value={conditionInfo.info.dateSelect ?? conditionDateOptions[0].value}
+ options={conditionDateOptions}
+ onChange={(value) => handleConditionInfo({ dateSelect: value })}
+ />
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/sheets-table-ui/src/views/components/MobileSheetTableFilterPanel.tsx b/packages/sheets-table-ui/src/views/components/MobileSheetTableFilterPanel.tsx
new file mode 100644
index 0000000000..4b1e190b68
--- /dev/null
+++ b/packages/sheets-table-ui/src/views/components/MobileSheetTableFilterPanel.tsx
@@ -0,0 +1,398 @@
+/**
+ * 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 { ISortRangeCommandParams } from '@univerjs/sheets-sort';
+import type {
+ ITableColorFilterItem,
+ ITableConditionFilterItem,
+ ITableManualFilterItem,
+} from '@univerjs/sheets-table';
+import type { MobileDrawerSnap } from '@univerjs/ui';
+import type { ITableFilterPanelInfo } from '../../controllers/sheet-table-component.controller';
+import type { LocaleKey } from '../../locale/types';
+import type { ITableFilterColorList } from '../../types';
+import type { IConditionInfo } from './type';
+import { generateRandomId, ICommandService, IPermissionService, IUndoRedoService, LocaleService } from '@univerjs/core';
+import { Button, MobileActionRow, MobileActionRowGroup, resetButtonClassName } from '@univerjs/design';
+import {
+ AscendingIcon,
+ DeleteColumnDoubleIcon,
+ DescendingIcon,
+ LeftInsertColumnDoubleIcon,
+ MoreLeftIcon,
+ MoreRightIcon,
+ RightInsertColumnDoubleIcon,
+} from '@univerjs/icons';
+import { WorkbookEditablePermission } from '@univerjs/sheets';
+import { SortRangeCommand, SortType } from '@univerjs/sheets-sort';
+import {
+ SetSheetTableSortStateCommand,
+ SheetsTableSortStateEnum,
+ SheetTableInsertColumnAtCommand,
+ SheetTableRemoveColumnAtCommand,
+ TABLE_FILTER_EMPTY_VALUE,
+ TableColumnFilterTypeEnum,
+ TableDateCompareTypeEnum,
+ TableManager,
+} from '@univerjs/sheets-table';
+import { MobileDrawer, useDependency } from '@univerjs/ui';
+import { useRef, useState } from 'react';
+import { createPortal } from 'react-dom';
+import { SheetsTableComponentController } from '../../controllers/sheet-table-component.controller';
+import { SheetsTableUiService } from '../../services/sheets-table-ui.service';
+import { FilterByEnum } from '../../types';
+import { MobileSheetTableColorFilterPanel } from './MobileSheetTableColorFilterPanel';
+import { MobileSheetTableConditionPanel } from './MobileSheetTableConditionPanel';
+import { MobileSheetTableItemsFilterPanel } from './MobileSheetTableItemsFilterPanel';
+import { getInitConditionInfo } from './util';
+
+const FILTER_BY_OPTIONS: Array<{ label: LocaleKey; value: FilterByEnum }> = [
+ { label: 'sheets-table-ui.filter.by-values', value: FilterByEnum.Items },
+ { label: 'sheets-table-ui.filter.by-colors', value: FilterByEnum.Color },
+ { label: 'sheets-table-ui.filter.by-conditions', value: FilterByEnum.Condition },
+];
+
+export function MobileSheetTableFilterPanel() {
+ const sheetsTableComponentController = useDependency(SheetsTableComponentController);
+ const tableFilterPanelInfo = sheetsTableComponentController.getCurrentTableFilterInfo();
+ if (!tableFilterPanelInfo) {
+ return null;
+ }
+
+ return <MobileSheetTableFilterPanelContent tableFilterPanelInfo={tableFilterPanelInfo} />;
+}
+
+interface IMobileSheetTableFilterPanelContentProps {
+ tableFilterPanelInfo: ITableFilterPanelInfo;
+}
+
+function MobileSheetTableFilterPanelContent(props: IMobileSheetTableFilterPanelContentProps) {
+ const { tableFilterPanelInfo } = props;
+ const localeService = useDependency(LocaleService);
+ const tableUiService = useDependency(SheetsTableUiService);
+ const tableManager = useDependency(TableManager);
+ const commandService = useDependency(ICommandService);
+ const permissionService = useDependency(IPermissionService);
+ const undoRedoService = useDependency(IUndoRedoService);
+ const sheetsTableComponentController = useDependency(SheetsTableComponentController);
+ const [detailFilterBy, setDetailFilterBy] = useState<FilterByEnum | null>(null);
+ const [drawerSnap, setDrawerSnap] = useState<MobileDrawerSnap>('expanded');
+ const layerRef = useRef<HTMLDivElement>(null);
+
+ const panelProps = tableUiService.getTableFilterPanelInitProps(
+ tableFilterPanelInfo.unitId,
+ tableFilterPanelInfo.subUnitId,
+ tableFilterPanelInfo.tableId,
+ tableFilterPanelInfo.column
+ );
+ const { unitId, subUnitId, tableId, tableFilter, columnIndex } = panelProps;
+ const currentTable = tableManager.getTable(unitId, tableId)!;
+
+ const items = tableUiService.getTableFilterItems(unitId, subUnitId, tableId, columnIndex);
+ const checkedItems = tableUiService.getTableFilterCheckedItems(unitId, tableId, columnIndex);
+ const [checkedItemSet, setCheckedItemSet] = useState<Set<string>>(() => new Set(
+ tableFilter?.filterType === TableColumnFilterTypeEnum.manual
+ ? checkedItems
+ : items.data.map((item) => item.title)
+ ));
+ const [conditionInfo, setConditionInfo] = useState<IConditionInfo>(
+ () => getInitConditionInfo(tableFilter) as IConditionInfo
+ );
+ const [colors, setColors] = useState<ITableFilterColorList>(
+ () => tableUiService.getTableFilterColors(unitId, subUnitId, tableId, columnIndex)
+ );
+ const tableRange = currentTable.getRange();
+ const canDeleteColumn = tableRange.endColumn > tableRange.startColumn;
+ const absoluteColumn = tableFilterPanelInfo.column;
+ const editable = permissionService.getPermissionPoint(new WorkbookEditablePermission(unitId).id)?.value;
+
+ function closePanel() {
+ sheetsTableComponentController.closeFilterPanel();
+ }
+
+ async function applySort(ascending: boolean) {
+ const range = currentTable.getTableFilterRange();
+ const undoRedoGroup = undoRedoService.beginUndoRedoGroup(unitId, generateRandomId(), 'append');
+ try {
+ const success = await commandService.executeCommand<ISortRangeCommandParams>(SortRangeCommand.id, {
+ unitId,
+ subUnitId,
+ range,
+ orderRules: [{ colIndex: columnIndex + range.startColumn, type: ascending ? SortType.ASC : SortType.DESC }],
+ hasTitle: false,
+ });
+ if (!success) {
+ return;
+ }
+
+ const sortStateSet = await commandService.executeCommand(SetSheetTableSortStateCommand.id, {
+ unitId,
+ tableId,
+ sortInfo: {
+ columnIndex,
+ sortState: ascending ? SheetsTableSortStateEnum.Asc : SheetsTableSortStateEnum.Desc,
+ },
+ });
+ if (sortStateSet) {
+ closePanel();
+ }
+ } finally {
+ undoRedoGroup.dispose();
+ }
+ }
+
+ async function insertColumn(side: 'left' | 'right') {
+ const success = await commandService.executeCommand(SheetTableInsertColumnAtCommand.id, {
+ unitId,
+ subUnitId,
+ tableId,
+ index: side === 'left' ? absoluteColumn : absoluteColumn + 1,
+ count: 1,
+ });
+ if (success) {
+ closePanel();
+ }
+ }
+
+ async function deleteColumn() {
+ if (!canDeleteColumn) {
+ return;
+ }
+
+ const success = await commandService.executeCommand(SheetTableRemoveColumnAtCommand.id, {
+ unitId,
+ subUnitId,
+ tableId,
+ index: absoluteColumn,
+ count: 1,
+ });
+ if (success) {
+ closePanel();
+ }
+ }
+
+ async function applyFilter() {
+ let filter: ITableColorFilterItem | ITableConditionFilterItem | ITableManualFilterItem | undefined;
+ if (detailFilterBy === FilterByEnum.Items) {
+ const emptyLabel = localeService.t<LocaleKey>('sheets-table-ui.condition.empty');
+ const values = items.data
+ .filter((item) => checkedItemSet.has(item.title))
+ .map((item) => item.title === emptyLabel ? TABLE_FILTER_EMPTY_VALUE : item.title);
+ filter = values.length === items.data.length
+ ? undefined
+ : { filterType: TableColumnFilterTypeEnum.manual, values } satisfies ITableManualFilterItem;
+ } else if (detailFilterBy === FilterByEnum.Color) {
+ const cellFillColors = colors.cellFillColors.filter((item) => item.checked).map((item) => item.color);
+ const cellTextColors = colors.cellTextColors.filter((item) => item.checked).map((item) => item.color);
+ if (cellFillColors.length) {
+ filter = { filterType: TableColumnFilterTypeEnum.color, cellFillColors } satisfies ITableColorFilterItem;
+ } else if (cellTextColors.length) {
+ filter = { filterType: TableColumnFilterTypeEnum.color, cellTextColors } satisfies ITableColorFilterItem;
+ }
+ } else if (detailFilterBy === FilterByEnum.Condition) {
+ const dynamicCompare = conditionInfo.compare === TableDateCompareTypeEnum.Quarter
+ || conditionInfo.compare === TableDateCompareTypeEnum.Month;
+ filter = {
+ filterType: TableColumnFilterTypeEnum.condition,
+ filterInfo: {
+ conditionType: conditionInfo.type,
+ compareType: dynamicCompare
+ ? Object.values(conditionInfo.info)[0] as IConditionInfo['compare']
+ : conditionInfo.compare,
+ expectedValue: dynamicCompare ? undefined : Object.values(conditionInfo.info)[0],
+ } as ITableConditionFilterItem['filterInfo'],
+ } satisfies ITableConditionFilterItem;
+ } else {
+ return;
+ }
+
+ const success = await tableUiService.setTableFilter(unitId, tableId, columnIndex, filter);
+ if (success) {
+ closePanel();
+ }
+ }
+
+ async function clearFilter() {
+ const success = await tableUiService.setTableFilter(unitId, tableId, columnIndex, undefined);
+ if (success) {
+ closePanel();
+ }
+ }
+
+ function openDetail(filterBy: FilterByEnum) {
+ if (filterBy === FilterByEnum.Items) {
+ setCheckedItemSet(new Set(
+ tableFilter?.filterType === TableColumnFilterTypeEnum.manual
+ ? checkedItems
+ : items.data.map((item) => item.title)
+ ));
+ } else if (filterBy === FilterByEnum.Color) {
+ setColors(tableUiService.getTableFilterColors(unitId, subUnitId, tableId, columnIndex));
+ } else if (filterBy === FilterByEnum.Condition) {
+ setConditionInfo(getInitConditionInfo(tableFilter) as IConditionInfo);
+ }
+ setDetailFilterBy(filterBy);
+ setDrawerSnap('expanded');
+ }
+
+ function closeDetail() {
+ setDetailFilterBy(null);
+ }
+
+ const detailOption = FILTER_BY_OPTIONS.find((option) => option.value === detailFilterBy);
+ const detailTitle = detailOption ? localeService.t<LocaleKey>(detailOption.label) : '';
+ const detailDrawer = detailFilterBy
+ ? createPortal(
+ <div ref={layerRef} className="univer-pointer-events-none univer-fixed univer-inset-0 univer-z-[1300]">
+ <MobileDrawer
+ layerRef={layerRef}
+ componentName="mobile-sheet-table-filter-detail"
+ openMode="push"
+ snap={drawerSnap}
+ expandLabel={localeService.t<LocaleKey>('sheets-table-ui.filter.resize')}
+ collapseLabel={localeService.t<LocaleKey>('sheets-table-ui.filter.resize')}
+ onSnapChange={setDrawerSnap}
+ onClose={closeDetail}
+ role="dialog"
+ ariaLabel={detailTitle}
+ panelClassName="univer-pointer-events-auto"
+ contentClassName="univer-min-h-0 univer-px-4 univer-pb-4"
+ header={(
+ <header
+ className="
+ univer-grid univer-h-12 univer-flex-1 univer-grid-cols-[48px_1fr_48px] univer-items-center
+ "
+ >
+ <button
+ type="button"
+ aria-label={localeService.t<LocaleKey>('sheets-table-ui.filter.back')}
+ className={`
+ ${resetButtonClassName}
+ univer-flex univer-size-12 univer-items-center univer-justify-center
+ `}
+ onClick={closeDetail}
+ >
+ <MoreLeftIcon className="univer-size-6" />
+ </button>
+ <div className="univer-truncate univer-text-center univer-text-base univer-font-semibold">
+ {detailTitle}
+ </div>
+ </header>
+ )}
+ footer={(
+ <footer
+ className="
+ univer-shrink-0 univer-border-0 univer-border-t univer-border-solid univer-border-gray-200
+ univer-p-4
+ dark:!univer-border-gray-700
+ "
+ >
+ <MobileActionRowGroup>
+ <Button onClick={closeDetail}>
+ {localeService.t<LocaleKey>('sheets-table-ui.filter.cancel')}
+ </Button>
+ <Button variant="primary" onClick={() => applyFilter().catch(() => undefined)}>
+ {localeService.t<LocaleKey>('sheets-table-ui.filter.confirm')}
+ </Button>
+ </MobileActionRowGroup>
+ </footer>
+ )}
+ >
+ {detailFilterBy === FilterByEnum.Items && (
+ <MobileSheetTableItemsFilterPanel
+ items={items}
+ checkedItemSet={checkedItemSet}
+ setCheckedItemSet={setCheckedItemSet}
+ />
+ )}
+ {detailFilterBy === FilterByEnum.Color && (
+ <MobileSheetTableColorFilterPanel colors={colors} onChange={setColors} />
+ )}
+ {detailFilterBy === FilterByEnum.Condition && (
+ <MobileSheetTableConditionPanel
+ tableFilter={tableFilter}
+ unitId={unitId}
+ subUnitId={subUnitId}
+ tableId={tableId}
+ columnIndex={columnIndex}
+ conditionInfo={conditionInfo}
+ onChange={setConditionInfo}
+ />
+ )}
+ </MobileDrawer>
+ </div>,
+ document.body
+ )
+ : null;
+
+ return (
+ <>
+ <div className="univer-flex univer-flex-col univer-gap-2">
+ {editable && (
+ <>
+ <MobileActionRow
+ variant="subtle"
+ icon={<LeftInsertColumnDoubleIcon />}
+ title={localeService.t<LocaleKey>('sheets-table-ui.columnMenu.insert-left')}
+ onClick={() => insertColumn('left').catch(() => undefined)}
+ />
+ <MobileActionRow
+ variant="subtle"
+ icon={<RightInsertColumnDoubleIcon />}
+ title={localeService.t<LocaleKey>('sheets-table-ui.columnMenu.insert-right')}
+ onClick={() => insertColumn('right').catch(() => undefined)}
+ />
+ <MobileActionRow
+ variant="subtle"
+ icon={<DeleteColumnDoubleIcon />}
+ title={localeService.t<LocaleKey>('sheets-table-ui.columnMenu.delete')}
+ disabled={!canDeleteColumn}
+ onClick={() => deleteColumn().catch(() => undefined)}
+ />
+ <MobileActionRow
+ variant="subtle"
+ icon={<AscendingIcon />}
+ title={localeService.t<LocaleKey>('sheets-table-ui.sort.sort-asc')}
+ onClick={() => applySort(true).catch(() => undefined)}
+ />
+ <MobileActionRow
+ variant="subtle"
+ icon={<DescendingIcon />}
+ title={localeService.t<LocaleKey>('sheets-table-ui.sort.sort-desc')}
+ onClick={() => applySort(false).catch(() => undefined)}
+ />
+ </>
+ )}
+ {FILTER_BY_OPTIONS.map((option) => (
+ <MobileActionRow
+ key={option.value}
+ variant="subtle"
+ title={localeService.t<LocaleKey>(option.label)}
+ trailing={<MoreRightIcon className="univer-size-5 univer-text-gray-400" />}
+ onClick={() => openDetail(option.value)}
+ />
+ ))}
+ <MobileActionRow
+ variant="subtle"
+ title={localeService.t<LocaleKey>('sheets-table-ui.filter.clear-filter')}
+ disabled={!tableFilter}
+ onClick={() => clearFilter().catch(() => undefined)}
+ />
+ </div>
+ {detailDrawer}
+ </>
+ );
+}
diff --git a/packages/sheets-table-ui/src/views/components/MobileSheetTableItemsFilterPanel.tsx b/packages/sheets-table-ui/src/views/components/MobileSheetTableItemsFilterPanel.tsx
new file mode 100644
index 0000000000..6ece0dc48d
--- /dev/null
+++ b/packages/sheets-table-ui/src/views/components/MobileSheetTableItemsFilterPanel.tsx
@@ -0,0 +1,126 @@
+/**
+ * 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 { Dispatch, SetStateAction } from 'react';
+import type { LocaleKey } from '../../locale/types';
+import type { ITableFilterItemList } from '../../types';
+import { LocaleService } from '@univerjs/core';
+import { Checkbox, Input } from '@univerjs/design';
+import { useDependency } from '@univerjs/ui';
+import { useMemo, useState } from 'react';
+
+interface IMobileSheetTableItemsFilterPanelProps {
+ items: ITableFilterItemList;
+ checkedItemSet: Set<string>;
+ setCheckedItemSet: Dispatch<SetStateAction<Set<string>>>;
+}
+
+export function MobileSheetTableItemsFilterPanel(props: IMobileSheetTableItemsFilterPanelProps) {
+ const { items, checkedItemSet, setCheckedItemSet } = props;
+ const localeService = useDependency(LocaleService);
+ const [searchText, setSearchText] = useState('');
+ const displayItems = useMemo(() => {
+ const normalizedSearchText = searchText.toLowerCase();
+ return normalizedSearchText
+ ? items.data.filter((item) => String(item.title).toLowerCase().includes(normalizedSearchText))
+ : items.data;
+ }, [items.data, searchText]);
+ const allDisplayedChecked = displayItems.length > 0
+ && displayItems.every((item) => checkedItemSet.has(item.title));
+ const someDisplayedChecked = displayItems.some((item) => checkedItemSet.has(item.title));
+
+ function toggleAllDisplayed() {
+ setCheckedItemSet((current) => {
+ const next = new Set(current);
+ for (const item of displayItems) {
+ if (allDisplayedChecked) {
+ next.delete(item.title);
+ } else {
+ next.add(item.title);
+ }
+ }
+ return next;
+ });
+ }
+
+ function toggleItem(title: string) {
+ setCheckedItemSet((current) => {
+ const next = new Set(current);
+ if (next.has(title)) {
+ next.delete(title);
+ } else {
+ next.add(title);
+ }
+ return next;
+ });
+ }
+
+ return (
+ <div data-u-comp="mobile-sheet-table-filter-by-values" className="univer-grid univer-gap-3">
+ <Input
+ value={searchText}
+ placeholder={localeService.t<LocaleKey>('sheets-table-ui.filter.search-placeholder')}
+ onChange={setSearchText}
+ />
+ <div
+ className="
+ univer-overflow-hidden univer-rounded-xl univer-bg-gray-0
+ dark:!univer-bg-gray-800
+ "
+ >
+ <div
+ className="
+ univer-border-0 univer-border-b univer-border-solid univer-border-gray-200 univer-px-4
+ dark:!univer-border-gray-700
+ "
+ >
+ <Checkbox
+ className="univer-flex univer-min-h-12 univer-items-center"
+ checked={allDisplayedChecked}
+ indeterminate={!allDisplayedChecked && someDisplayedChecked}
+ disabled={displayItems.length === 0}
+ onChange={toggleAllDisplayed}
+ >
+ {localeService.t<LocaleKey>('sheets-table-ui.filter.select-all')}
+ </Checkbox>
+ </div>
+ {displayItems.map((item) => (
+ <div
+ key={item.key}
+ className="
+ univer-border-0 univer-border-b univer-border-solid univer-border-gray-200 univer-px-4
+ last:univer-border-b-0
+ dark:!univer-border-gray-700
+ "
+ >
+ <Checkbox
+ className="univer-flex univer-min-h-12 univer-items-center"
+ checked={checkedItemSet.has(item.title)}
+ onChange={() => toggleItem(item.title)}
+ >
+ <span className="univer-flex univer-min-w-0 univer-flex-1 univer-items-center univer-gap-2">
+ <span className="univer-min-w-0 univer-flex-1 univer-truncate">{item.title}</span>
+ <span className="univer-shrink-0 univer-text-gray-400">
+ {`(${items.itemsCountMap.get(item.title) ?? 0})`}
+ </span>
+ </span>
+ </Checkbox>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/sheets-table-ui/src/views/components/MobileSheetTableMenu.tsx b/packages/sheets-table-ui/src/views/components/MobileSheetTableMenu.tsx
index 78c3fa301f..0a32bdca68 100644
--- a/packages/sheets-table-ui/src/views/components/MobileSheetTableMenu.tsx
+++ b/packages/sheets-table-ui/src/views/components/MobileSheetTableMenu.tsx
@@ -19,7 +19,11 @@ import { MobileActionRow } from '@univerjs/design';
const ACTIONS: SheetTableMenuAction[] = ['rename', 'update-range', 'set-theme', 'delete'];
-export function MobileSheetTableMenu({ menu }: { menu: ISheetTableMenuExtraProps }) {
+export function MobileSheetTableMenu({ menu }: { menu?: ISheetTableMenuExtraProps }) {
+ if (!menu) {
+ return null;
+ }
+
return (
<div className="univer-flex univer-flex-col univer-gap-2">
{ACTIONS.map((action) => (
diff --git a/packages/sheets-table-ui/src/views/components/MobileSheetTableRenameDialog.tsx b/packages/sheets-table-ui/src/views/components/MobileSheetTableRenameDialog.tsx
new file mode 100644
index 0000000000..9be7998272
--- /dev/null
+++ b/packages/sheets-table-ui/src/views/components/MobileSheetTableRenameDialog.tsx
@@ -0,0 +1,23 @@
+/**
+ * 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 { ISheetTableRenameDialogProps } from './SheetTableRenameDialog';
+import { MobileActionRowGroup } from '@univerjs/design';
+import { SheetTableRenameDialog } from './SheetTableRenameDialog';
+
+export function MobileSheetTableRenameDialog(props: ISheetTableRenameDialogProps) {
+ return <SheetTableRenameDialog {...props} ActionRowComponent={MobileActionRowGroup} />;
+}
diff --git a/packages/sheets-table-ui/src/views/components/MobileSheetTableSelector.tsx b/packages/sheets-table-ui/src/views/components/MobileSheetTableSelector.tsx
new file mode 100644
index 0000000000..ef624d625b
--- /dev/null
+++ b/packages/sheets-table-ui/src/views/components/MobileSheetTableSelector.tsx
@@ -0,0 +1,23 @@
+/**
+ * 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 { ISheetTableSelectorProps } from './SheetTableSelector';
+import { MobileActionRowGroup } from '@univerjs/design';
+import { SheetTableSelector } from './SheetTableSelector';
+
+export function MobileSheetTableSelector(props: ISheetTableSelectorProps) {
+ return <SheetTableSelector {...props} ActionRowComponent={MobileActionRowGroup} />;
+}
diff --git a/packages/sheets-table-ui/src/views/components/MobileSheetTableThemePanel.tsx b/packages/sheets-table-ui/src/views/components/MobileSheetTableThemePanel.tsx
new file mode 100644
index 0000000000..60ddc047da
--- /dev/null
+++ b/packages/sheets-table-ui/src/views/components/MobileSheetTableThemePanel.tsx
@@ -0,0 +1,29 @@
+/**
+ * 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 { ISheetTableThemePanelProps } from './SheetTableThemePanel';
+import { MobileColorPicker, MobileDropdown } from '@univerjs/design';
+import { SheetTableThemePanel } from './SheetTableThemePanel';
+
+export function MobileSheetTableThemePanel(props: ISheetTableThemePanelProps) {
+ return (
+ <SheetTableThemePanel
+ {...props}
+ ColorPickerComponent={MobileColorPicker}
+ DropdownComponent={MobileDropdown}
+ />
+ );
+}
diff --git a/packages/sheets-table-ui/src/views/components/SheetTableColorFilterPanel.tsx b/packages/sheets-table-ui/src/views/components/SheetTableColorFilterPanel.tsx
new file mode 100644
index 0000000000..184efe3b7d
--- /dev/null
+++ b/packages/sheets-table-ui/src/views/components/SheetTableColorFilterPanel.tsx
@@ -0,0 +1,123 @@
+/**
+ * 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 { ITableFilterColorItem, ITableFilterColorList } from '../../types';
+import { LocaleService } from '@univerjs/core';
+import { clsx, resetButtonClassName } from '@univerjs/design';
+import { AIcon, BanIcon, SuccessIcon } from '@univerjs/icons';
+import { useDependency } from '@univerjs/ui';
+
+interface ISheetTableColorFilterPanelProps {
+ colors: ITableFilterColorList;
+ onChange: (colors: ITableFilterColorList) => void;
+}
+
+function ColorOption(props: {
+ item: ITableFilterColorItem;
+ label: string;
+ textColor?: boolean;
+ onClick: () => void;
+}) {
+ const { item, label, textColor = false, onClick } = props;
+ return (
+ <button
+ type="button"
+ aria-label={item.color ?? label}
+ aria-pressed={item.checked}
+ className={clsx(resetButtonClassName, `
+ univer-relative univer-flex univer-size-6 univer-items-center univer-justify-center univer-rounded-full
+ univer-border univer-border-solid univer-border-gray-200 univer-bg-gray-0
+ hover:univer-ring-2 hover:univer-ring-offset-2
+ dark:!univer-border-gray-600 dark:!univer-bg-gray-800
+ `)}
+ style={!textColor && item.color ? { backgroundColor: item.color } : undefined}
+ onClick={onClick}
+ >
+ {!item.color && <BanIcon className="univer-size-5" />}
+ {textColor && item.color && <AIcon className="univer-size-5" style={{ color: item.color }} />}
+ {item.checked && (
+ <SuccessIcon
+ className="
+ univer-absolute -univer-bottom-1 -univer-right-1 univer-size-3 univer-rounded-full
+ univer-bg-gray-0 univer-text-green-600
+ "
+ />
+ )}
+ </button>
+ );
+}
+
+export function SheetTableColorFilterPanel(props: ISheetTableColorFilterPanelProps) {
+ const { colors, onChange } = props;
+ const localeService = useDependency(LocaleService);
+ const fillLabel = localeService.t<LocaleKey>('sheets-table-ui.filter.filter-by-cell-fill-color');
+ const textLabel = localeService.t<LocaleKey>('sheets-table-ui.filter.filter-by-cell-text-color');
+ const hasMultipleColors = colors.cellFillColors.length > 1 || colors.cellTextColors.length > 1;
+
+ function toggleColor(item: ITableFilterColorItem, fillColor: boolean) {
+ const key = fillColor ? 'cellFillColors' : 'cellTextColors';
+ const otherKey = fillColor ? 'cellTextColors' : 'cellFillColors';
+ onChange({
+ ...colors,
+ [key]: colors[key].map((color) => color.color === item.color
+ ? { ...color, checked: !color.checked }
+ : color),
+ [otherKey]: colors[otherKey].map((color) => ({ ...color, checked: false })),
+ });
+ }
+
+ return (
+ <div className="univer-grid univer-h-full univer-gap-4 univer-overflow-auto univer-rounded-md univer-p-2">
+ {colors.cellFillColors.length > 1 && (
+ <section>
+ <h3 className="univer-m-0 univer-mb-2 univer-text-sm univer-font-normal">{fillLabel}</h3>
+ <div className="univer-grid univer-grid-cols-8 univer-gap-2">
+ {colors.cellFillColors.map((item) => (
+ <ColorOption
+ key={item.color ?? 'none'}
+ item={item}
+ label={fillLabel}
+ onClick={() => toggleColor(item, true)}
+ />
+ ))}
+ </div>
+ </section>
+ )}
+ {colors.cellTextColors.length > 1 && (
+ <section>
+ <h3 className="univer-m-0 univer-mb-2 univer-text-sm univer-font-normal">{textLabel}</h3>
+ <div className="univer-grid univer-grid-cols-8 univer-gap-2">
+ {colors.cellTextColors.map((item) => (
+ <ColorOption
+ key={item.color ?? 'none'}
+ item={item}
+ label={textLabel}
+ textColor
+ onClick={() => toggleColor(item, false)}
+ />
+ ))}
+ </div>
+ </section>
+ )}
+ {!hasMultipleColors && (
+ <div className="univer-flex univer-size-full univer-items-center univer-justify-center univer-text-sm">
+ {localeService.t<LocaleKey>('sheets-table-ui.filter.filter-by-color-none')}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/packages/sheets-table-ui/src/views/components/SheetTableFilterPanel.tsx b/packages/sheets-table-ui/src/views/components/SheetTableFilterPanel.tsx
index 625ab5dd7c..cef319fedc 100644
--- a/packages/sheets-table-ui/src/views/components/SheetTableFilterPanel.tsx
+++ b/packages/sheets-table-ui/src/views/components/SheetTableFilterPanel.tsx
@@ -15,10 +15,15 @@
*/
import type { ISortRangeCommandParams } from '@univerjs/sheets-sort';
-import type { ITableConditionFilterItem, ITableManualFilterItem } from '@univerjs/sheets-table';
+import type {
+ ITableColorFilterItem,
+ ITableConditionFilterItem,
+ ITableManualFilterItem,
+} from '@univerjs/sheets-table';
import type { LocaleKey } from '../../locale/types';
+import type { ITableFilterColorList } from '../../types';
import type { IConditionInfo } from './type';
-import { ICommandService, IPermissionService, LocaleService } from '@univerjs/core';
+import { generateRandomId, ICommandService, IPermissionService, IUndoRedoService, LocaleService } from '@univerjs/core';
import { ActionRow, Button, ButtonGroup, Segmented } from '@univerjs/design';
import {
AscendingIcon,
@@ -30,6 +35,8 @@ import {
import { WorkbookEditablePermission } from '@univerjs/sheets';
import { SortRangeCommand, SortType } from '@univerjs/sheets-sort';
import {
+ isManualTableFilter,
+ SetSheetTableSortStateCommand,
SheetsTableSortStateEnum,
SheetTableInsertColumnAtCommand,
SheetTableRemoveColumnAtCommand,
@@ -43,12 +50,14 @@ import { useState } from 'react';
import { SheetsTableComponentController } from '../../controllers/sheet-table-component.controller';
import { SheetsTableUiService } from '../../services/sheets-table-ui.service';
import { FilterByEnum } from '../../types';
+import { SheetTableColorFilterPanel } from './SheetTableColorFilterPanel';
import { SheetTableConditionPanel } from './SheetTableConditionPanel';
import { SheetTableItemsFilterPanel } from './SheetTableItemsFilterPanel';
import { getInitConditionInfo } from './util';
const FILTER_BY_OPTIONS: Array<{ label: LocaleKey; value: FilterByEnum }> = [
{ label: 'sheets-table-ui.filter.by-values', value: FilterByEnum.Items },
+ { label: 'sheets-table-ui.filter.by-colors', value: FilterByEnum.Color },
{ label: 'sheets-table-ui.filter.by-conditions', value: FilterByEnum.Condition },
];
@@ -59,37 +68,39 @@ export function SheetTableFilterPanel() {
const tableManager = useDependency(TableManager);
const commandService = useDependency(ICommandService);
const permissionService = useDependency(IPermissionService);
+ const undoRedoService = useDependency(IUndoRedoService);
const sheetsTableComponentController = useDependency(SheetsTableComponentController);
const tableFilterPanelInfo = sheetsTableComponentController.getCurrentTableFilterInfo()!;
- const props = tableUiService.getTableFilterPanelInitProps(
+ const panelProps = tableUiService.getTableFilterPanelInitProps(
tableFilterPanelInfo.unitId,
tableFilterPanelInfo.subUnitId,
tableFilterPanelInfo.tableId,
tableFilterPanelInfo.column
);
- const { unitId, subUnitId, tableId, tableFilter, currentFilterBy, columnIndex } = props;
+ const { unitId, subUnitId, tableId, tableFilter, currentFilterBy, columnIndex } = panelProps;
const { data } = tableUiService.getTableFilterItems(unitId, subUnitId, tableId, columnIndex);
const checkedItems = tableUiService.getTableFilterCheckedItems(unitId, tableId, columnIndex);
- const [checkedItemSet, setCheckedItemSet] = useState<Set<string>>(() => new Set<string>(checkedItems));
+ const [checkedItemSet, setCheckedItemSet] = useState<Set<string>>(() => new Set<string>(
+ isManualTableFilter(tableFilter) ? checkedItems : data.map((item) => item.title)
+ ));
const [filterBy, setFilterBy] = useState(currentFilterBy || FilterByEnum.Items);
const [conditionInfo, setConditionInfo] = useState<IConditionInfo>(() => {
- const tableFilter = props.tableFilter;
+ const tableFilter = panelProps.tableFilter;
return getInitConditionInfo(tableFilter) as IConditionInfo;
});
+ const [colors, setColors] = useState<ITableFilterColorList>(
+ () => tableUiService.getTableFilterColors(unitId, subUnitId, tableId, columnIndex)
+ );
const table = tableManager.getTable(unitId, tableId);
if (!table) return null;
- const tableFilters = table.getTableFilters();
const tableRange = table.getRange();
- const sortState = tableFilters.getSortState();
- const isAsc = sortState.columnIndex === columnIndex && sortState.sortState === SheetsTableSortStateEnum.Asc;
- const isDesc = sortState.columnIndex === columnIndex && sortState.sortState === SheetsTableSortStateEnum.Desc;
const absoluteColumn = tableFilterPanelInfo.column;
const canDeleteColumn = tableRange.endColumn > tableRange.startColumn;
@@ -100,48 +111,69 @@ export function SheetTableFilterPanel() {
closeDialog();
};
- const applySort = (asc: boolean) => {
+ const applySort = async (asc: boolean) => {
const range = table.getTableFilterRange();
+ const undoRedoGroup = undoRedoService.beginUndoRedoGroup(unitId, generateRandomId(), 'append');
+ try {
+ const success = await commandService.executeCommand<ISortRangeCommandParams>(SortRangeCommand.id, {
+ unitId,
+ subUnitId,
+ range,
+ orderRules: [{ colIndex: columnIndex + range.startColumn, type: asc ? SortType.ASC : SortType.DESC }],
+ hasTitle: false,
+ });
+ if (!success) {
+ return;
+ }
- commandService.executeCommand<ISortRangeCommandParams>(SortRangeCommand.id, {
- unitId,
- subUnitId,
- range,
- orderRules: [{ colIndex: columnIndex + range.startColumn, type: asc ? SortType.ASC : SortType.DESC }],
- hasTitle: false,
- });
-
- tableFilters.setSortState(columnIndex, asc ? SheetsTableSortStateEnum.Asc : SheetsTableSortStateEnum.Desc);
- closeDialog();
+ const sortStateSet = await commandService.executeCommand(SetSheetTableSortStateCommand.id, {
+ unitId,
+ tableId,
+ sortInfo: {
+ columnIndex,
+ sortState: asc ? SheetsTableSortStateEnum.Asc : SheetsTableSortStateEnum.Desc,
+ },
+ });
+ if (sortStateSet) {
+ closeDialog();
+ }
+ } finally {
+ undoRedoGroup.dispose();
+ }
};
- const insertColumn = (side: 'left' | 'right') => {
- commandService.executeCommand(SheetTableInsertColumnAtCommand.id, {
+ const insertColumn = async (side: 'left' | 'right') => {
+ const success = await commandService.executeCommand(SheetTableInsertColumnAtCommand.id, {
unitId,
subUnitId,
tableId,
index: side === 'left' ? absoluteColumn : absoluteColumn + 1,
count: 1,
});
- closeDialog();
+ if (success) {
+ closeDialog();
+ }
};
- const deleteColumn = () => {
+ const deleteColumn = async () => {
if (!canDeleteColumn) {
return;
}
- commandService.executeCommand(SheetTableRemoveColumnAtCommand.id, {
+ const success = await commandService.executeCommand(SheetTableRemoveColumnAtCommand.id, {
unitId,
subUnitId,
tableId,
index: absoluteColumn,
count: 1,
});
- closeDialog();
+ if (success) {
+ closeDialog();
+ }
};
- const onApply = () => {
+ const onApply = async () => {
+ let filter: ITableColorFilterItem | ITableConditionFilterItem | ITableManualFilterItem | undefined;
if (filterBy === FilterByEnum.Items) {
// do items
const filteredItems: string[] = [];
@@ -151,22 +183,31 @@ export function SheetTableFilterPanel() {
filteredItems.push(itemInfo.title === emptyLabel ? TABLE_FILTER_EMPTY_VALUE : itemInfo.title);
}
}
- const originFilter = table.getTableFilterColumn(columnIndex) as ITableManualFilterItem | undefined;
- if (originFilter) {
+ const originFilter = table.getTableFilterColumn(columnIndex);
+ if (isManualTableFilter(originFilter)) {
const originValue = originFilter.values;
if (originValue.join(',') === filteredItems.join(',')) {
closeDialog();
return;
}
- } else if (filteredItems.length === 0) {
+ } else if (filteredItems.length === data.length && !originFilter) {
closeDialog();
return;
}
- const tableFilter: ITableManualFilterItem = {
- filterType: TableColumnFilterTypeEnum.manual,
- values: filteredItems,
- };
- tableUiService.setTableFilter(unitId, tableId, columnIndex, tableFilter);
+ filter = filteredItems.length === data.length
+ ? undefined
+ : {
+ filterType: TableColumnFilterTypeEnum.manual,
+ values: filteredItems,
+ };
+ } else if (filterBy === FilterByEnum.Color) {
+ const cellFillColors = colors.cellFillColors.filter((item) => item.checked).map((item) => item.color);
+ const cellTextColors = colors.cellTextColors.filter((item) => item.checked).map((item) => item.color);
+ if (cellFillColors.length) {
+ filter = { filterType: TableColumnFilterTypeEnum.color, cellFillColors };
+ } else if (cellTextColors.length) {
+ filter = { filterType: TableColumnFilterTypeEnum.color, cellTextColors };
+ }
} else {
let filterInfo;
if (conditionInfo.compare === TableDateCompareTypeEnum.Quarter || conditionInfo.compare === TableDateCompareTypeEnum.Month) {
@@ -181,18 +222,22 @@ export function SheetTableFilterPanel() {
expectedValue: Object.values(conditionInfo.info)[0],
};
}
- const tableFilter: ITableConditionFilterItem = {
+ filter = {
filterType: TableColumnFilterTypeEnum.condition,
// @ts-ignore
filterInfo,
};
- tableUiService.setTableFilter(unitId, tableId, columnIndex, tableFilter);
}
- closeDialog();
+ const success = await tableUiService.setTableFilter(unitId, tableId, columnIndex, filter);
+ if (success) {
+ closeDialog();
+ }
};
- const onClearFilter = () => {
- tableUiService.setTableFilter(unitId, tableId, columnIndex, undefined);
- closeDialog();
+ const onClearFilter = async () => {
+ const success = await tableUiService.setTableFilter(unitId, tableId, columnIndex, undefined);
+ if (success) {
+ closeDialog();
+ }
};
const workbookEditableId = new WorkbookEditablePermission(unitId).id;
@@ -225,7 +270,7 @@ export function SheetTableFilterPanel() {
dark:!univer-text-gray-0
dark:hover:!univer-bg-gray-600
`}
- onClick={() => insertColumn('left')}
+ onClick={() => insertColumn('left').catch(() => undefined)}
>
<LeftInsertColumnDoubleIcon className="univer-size-5" extend={{ colorChannel1: 'var(--univer-primary-600)' }} />
<span>{localeService.t<LocaleKey>('sheets-table-ui.columnMenu.insert-left')}</span>
@@ -241,7 +286,7 @@ export function SheetTableFilterPanel() {
dark:!univer-text-gray-0
dark:hover:!univer-bg-gray-600
`}
- onClick={() => insertColumn('right')}
+ onClick={() => insertColumn('right').catch(() => undefined)}
>
<RightInsertColumnDoubleIcon className="univer-size-5" extend={{ colorChannel1: 'var(--univer-primary-600)' }} />
<span>{localeService.t<LocaleKey>('sheets-table-ui.columnMenu.insert-right')}</span>
@@ -258,7 +303,7 @@ export function SheetTableFilterPanel() {
dark:hover:!univer-bg-gray-600
`}
disabled={!canDeleteColumn}
- onClick={deleteColumn}
+ onClick={() => deleteColumn().catch(() => undefined)}
>
<DeleteColumnDoubleIcon className="univer-size-5" extend={{ colorChannel1: 'var(--univer-primary-600)' }} />
<span>{localeService.t<LocaleKey>('sheets-table-ui.columnMenu.delete')}</span>
@@ -266,11 +311,11 @@ export function SheetTableFilterPanel() {
</div>
<div className="univer-mb-3 univer-flex">
<ButtonGroup className="univer-mb-3 !univer-flex univer-w-full">
- <Button className="univer-w-1/2" onClick={() => applySort(true)}>
+ <Button className="univer-w-1/2" onClick={() => applySort(true).catch(() => undefined)}>
<AscendingIcon className="univer-mr-1" />
{localeService.t<LocaleKey>('sheets-table-ui.sort.sort-asc')}
</Button>
- <Button className="univer-w-1/2" onClick={() => applySort(false)}>
+ <Button className="univer-w-1/2" onClick={() => applySort(false).catch(() => undefined)}>
<DescendingIcon className="univer-mr-1" />
{localeService.t<LocaleKey>('sheets-table-ui.sort.sort-desc')}
</Button>
@@ -287,29 +332,31 @@ export function SheetTableFilterPanel() {
</div>
<div className="univer-z-10 univer-h-60">
<div className="univer-mt-3 univer-size-full">
- {filterBy === FilterByEnum.Items
- ? (
- <SheetTableItemsFilterPanel
- tableFilter={tableFilter}
- unitId={unitId}
- subUnitId={subUnitId}
- tableId={tableId}
- columnIndex={columnIndex}
- checkedItemSet={checkedItemSet}
- setCheckedItemSet={setCheckedItemSet}
- />
- )
- : (
- <SheetTableConditionPanel
- tableFilter={tableFilter}
- unitId={unitId}
- subUnitId={subUnitId}
- tableId={tableId}
- columnIndex={columnIndex}
- conditionInfo={conditionInfo}
- onChange={setConditionInfo}
- />
- )}
+ {filterBy === FilterByEnum.Items && (
+ <SheetTableItemsFilterPanel
+ tableFilter={tableFilter}
+ unitId={unitId}
+ subUnitId={subUnitId}
+ tableId={tableId}
+ columnIndex={columnIndex}
+ checkedItemSet={checkedItemSet}
+ setCheckedItemSet={setCheckedItemSet}
+ />
+ )}
+ {filterBy === FilterByEnum.Color && (
+ <SheetTableColorFilterPanel colors={colors} onChange={setColors} />
+ )}
+ {filterBy === FilterByEnum.Condition && (
+ <SheetTableConditionPanel
+ tableFilter={tableFilter}
+ unitId={unitId}
+ subUnitId={subUnitId}
+ tableId={tableId}
+ columnIndex={columnIndex}
+ conditionInfo={conditionInfo}
+ onChange={setConditionInfo}
+ />
+ )}
</div>
</div>
<ActionRow
@@ -320,13 +367,15 @@ export function SheetTableFilterPanel() {
>
<Button
disabled={tableFilter === undefined}
- onClick={onClearFilter}
+ onClick={() => onClearFilter().catch(() => undefined)}
>
{localeService.t<LocaleKey>('sheets-table-ui.filter.clear-filter')}
</Button>
<ActionRow className="univer-flex univer-flex-1 univer-gap-x-2">
<Button onClick={onCancel}>{localeService.t<LocaleKey>('sheets-table-ui.filter.cancel')}</Button>
- <Button variant="primary" onClick={onApply}>{localeService.t<LocaleKey>('sheets-table-ui.filter.confirm')}</Button>
+ <Button variant="primary" onClick={() => onApply().catch(() => undefined)}>
+ {localeService.t<LocaleKey>('sheets-table-ui.filter.confirm')}
+ </Button>
</ActionRow>
</ActionRow>
</div>
diff --git a/packages/sheets-table-ui/src/views/components/SheetTableMenu.tsx b/packages/sheets-table-ui/src/views/components/SheetTableMenu.tsx
index 5f5466eb30..3366087169 100644
--- a/packages/sheets-table-ui/src/views/components/SheetTableMenu.tsx
+++ b/packages/sheets-table-ui/src/views/components/SheetTableMenu.tsx
@@ -15,9 +15,7 @@
*/
import type { ICanvasPopup } from '@univerjs/sheets-ui';
-import { ConfigContext, DropdownMenu } from '@univerjs/design';
-import { useContext } from 'react';
-import { MobileSheetTableMenu } from './MobileSheetTableMenu';
+import { DropdownMenu } from '@univerjs/design';
export type SheetTableMenuAction = 'rename' | 'update-range' | 'set-theme' | 'delete';
@@ -35,16 +33,11 @@ interface ISheetTableMenuProps {
export function SheetTableMenu({ popup }: ISheetTableMenuProps) {
const menu = popup.extraProps as unknown as ISheetTableMenuExtraProps | undefined;
- const { mobile } = useContext(ConfigContext);
if (!menu) {
return null;
}
- if (mobile) {
- return <MobileSheetTableMenu menu={menu} />;
- }
-
return (
<DropdownMenu
align="start"
diff --git a/packages/sheets-table-ui/src/views/components/SheetTableRenameDialog.tsx b/packages/sheets-table-ui/src/views/components/SheetTableRenameDialog.tsx
index 02998c4c22..829e0959e2 100644
--- a/packages/sheets-table-ui/src/views/components/SheetTableRenameDialog.tsx
+++ b/packages/sheets-table-ui/src/views/components/SheetTableRenameDialog.tsx
@@ -31,10 +31,11 @@ export interface ISheetTableRenameDialogProps {
unitId: string;
tableId: string;
onClose: () => void;
+ ActionRowComponent?: typeof ActionRow;
}
export function SheetTableRenameDialog(props: ISheetTableRenameDialogProps) {
- const { unitId, tableId, onClose } = props;
+ const { unitId, tableId, onClose, ActionRowComponent = ActionRow } = props;
const localeService = useDependency(LocaleService);
const commandService = useDependency(ICommandService);
const tableManager = useDependency<TableManager>(TableManager);
@@ -102,12 +103,12 @@ export function SheetTableRenameDialog(props: ISheetTableRenameDialogProps) {
autoFocus
/>
{error ? <div className="-univer-mt-2 univer-text-sm univer-text-red-500">{error}</div> : null}
- <ActionRow
+ <ActionRowComponent
className="univer-flex univer-w-full univer-items-center univer-justify-end univer-gap-2"
>
<Button className="univer-min-w-16" onClick={onClose}>{localeService.t<LocaleKey>('sheets-table-ui.cancel')}</Button>
<Button className="univer-min-w-16" variant="primary" onClick={handleConfirm}>{localeService.t<LocaleKey>('sheets-table-ui.confirm')}</Button>
- </ActionRow>
+ </ActionRowComponent>
</div>
);
}
diff --git a/packages/sheets-table-ui/src/views/components/SheetTableSelector.tsx b/packages/sheets-table-ui/src/views/components/SheetTableSelector.tsx
index 6c7493689b..dc8987c0ba 100644
--- a/packages/sheets-table-ui/src/views/components/SheetTableSelector.tsx
+++ b/packages/sheets-table-ui/src/views/components/SheetTableSelector.tsx
@@ -25,11 +25,14 @@ import { TableManager } from '@univerjs/sheets-table';
import { useDependency } from '@univerjs/ui';
import { useState } from 'react';
-export const SheetTableSelector = (props: ITableSelectionInfo & {
+export interface ISheetTableSelectorProps extends ITableSelectionInfo {
onConfirm: (info: ITableSelectionInfo) => void;
onCancel: () => void;
-}) => {
- const { unitId, subUnitId, range, onCancel, onConfirm, tableId } = props;
+ ActionRowComponent?: typeof ActionRow;
+}
+
+export const SheetTableSelector = (props: ISheetTableSelectorProps) => {
+ const { unitId, subUnitId, range, onCancel, onConfirm, tableId, ActionRowComponent = ActionRow } = props;
const tableManager = useDependency(TableManager);
const [selectedRange, setSelectedRange] = useState(range);
@@ -116,7 +119,7 @@ export const SheetTableSelector = (props: ITableSelectionInfo & {
</div>
)}
- <ActionRow className="univer-mt-4 univer-flex univer-justify-end univer-gap-2">
+ <ActionRowComponent className="univer-mt-4 univer-flex univer-justify-end univer-gap-2">
<Button onClick={onCancel}>{localeService.t<LocaleKey>('sheets-table-ui.cancel')}</Button>
<Button
variant="primary"
@@ -133,7 +136,7 @@ export const SheetTableSelector = (props: ITableSelectionInfo & {
>
{localeService.t<LocaleKey>('sheets-table-ui.confirm')}
</Button>
- </ActionRow>
+ </ActionRowComponent>
</>
);
};
diff --git a/packages/sheets-table-ui/src/views/components/SheetTableThemePanel.tsx b/packages/sheets-table-ui/src/views/components/SheetTableThemePanel.tsx
index ac7bfb4a12..4253ad820e 100644
--- a/packages/sheets-table-ui/src/views/components/SheetTableThemePanel.tsx
+++ b/packages/sheets-table-ui/src/views/components/SheetTableThemePanel.tsx
@@ -45,6 +45,8 @@ export interface ISheetTableThemePanelProps {
subUnitId: string;
tableId: string;
oldConfig: ITableSetConfig;
+ ColorPickerComponent?: typeof ColorPicker;
+ DropdownComponent?: typeof Dropdown;
}
interface ITableThemeStyle {
@@ -55,7 +57,13 @@ interface ITableThemeStyle {
}
export const SheetTableThemePanel = (props: ISheetTableThemePanelProps) => {
- const { unitId, subUnitId, tableId } = props;
+ const {
+ unitId,
+ subUnitId,
+ tableId,
+ ColorPickerComponent = ColorPicker,
+ DropdownComponent = Dropdown,
+ } = props;
const commandService = useDependency(ICommandService);
const localeService = useDependency(LocaleService);
const tableManager = useDependency(TableManager);
@@ -384,10 +392,10 @@ export const SheetTableThemePanel = (props: ISheetTableThemePanelProps) => {
>
<span className="univer-truncate">{row.label}</span>
</div>
- <Dropdown
+ <DropdownComponent
overlay={(
<div dir={direction} className="univer-p-2">
- <ColorPicker
+ <ColorPickerComponent
value={new ColorKit(row.background).toHexString()}
onChange={row.onChange}
/>
@@ -412,7 +420,7 @@ export const SheetTableThemePanel = (props: ISheetTableThemePanelProps) => {
/>
<DownIcon className="univer-size-3" />
</button>
- </Dropdown>
+ </DropdownComponent>
</div>
))}
</div>
diff --git a/packages/sheets-table-ui/src/views/components/__tests__/SheetTableComponents.spec.tsx b/packages/sheets-table-ui/src/views/components/__tests__/SheetTableComponents.spec.tsx
index 76545c4de0..9ca4540341 100644
--- a/packages/sheets-table-ui/src/views/components/__tests__/SheetTableComponents.spec.tsx
+++ b/packages/sheets-table-ui/src/views/components/__tests__/SheetTableComponents.spec.tsx
@@ -23,10 +23,12 @@ import {
Inject,
Injector,
IPermissionService,
+ IUniverInstanceService,
LocaleService,
LocaleType,
Plugin,
toDisposable,
+ UndoCommand,
Univer,
UniverInstanceType,
} from '@univerjs/core';
@@ -52,6 +54,7 @@ import {
SetSheetTableFilterCommand,
SetSheetTableFilterMutation,
SetSheetTableMutation,
+ SetSheetTableSortStateCommand,
SheetsTableSortStateEnum,
SheetTableInsertColumnAtCommand,
SheetTableRemoveColumnAtCommand,
@@ -72,6 +75,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { SheetsTableComponentController } from '../../../controllers/sheet-table-component.controller';
import { SheetTableThemeUIController } from '../../../controllers/sheet-table-theme-ui.controller';
import { SheetsTableUiService } from '../../../services/sheets-table-ui.service';
+import { MobileSheetTableFilterPanel } from '../MobileSheetTableFilterPanel';
import { SheetTableConditionPanel } from '../SheetTableConditionPanel';
import { SheetTableFilterPanel } from '../SheetTableFilterPanel';
import { SheetTableRenameDialog } from '../SheetTableRenameDialog';
@@ -429,11 +433,11 @@ function createWorkbookData(): IWorkbookData {
},
1: {
0: { v: 'book' },
- 1: { v: 12 },
+ 1: { v: 12, s: { bg: { rgb: '#ff0000' } } },
},
2: {
0: { v: 'pen' },
- 1: { v: 3 },
+ 1: { v: 3, s: { bg: { rgb: '#0000ff' } } },
},
3: {
1: { v: 8 },
@@ -530,11 +534,18 @@ function createTestBed(): ITestBed {
},
},
filter: {
+ title: 'Filter',
'by-values': 'Filter by values',
+ 'by-colors': 'Filter by colors',
'by-conditions': 'Filter by conditions',
+ back: 'Back',
+ resize: 'Resize',
cancel: 'Cancel',
'clear-filter': 'Clear filter',
confirm: 'Confirm',
+ 'filter-by-cell-fill-color': 'Cell fill color',
+ 'filter-by-cell-text-color': 'Cell text color',
+ 'filter-by-color-none': 'This column contains only one color',
'search-placeholder': 'Search',
'select-all': 'Select all',
},
@@ -559,6 +570,7 @@ function createTestBed(): ITestBed {
SetSheetTableMutation,
SetSheetTableFilterCommand,
SetSheetTableFilterMutation,
+ SetSheetTableSortStateCommand,
ReorderRangeCommand,
ReorderRangeMutation,
AddRangeThemeMutation,
@@ -982,6 +994,157 @@ describe('sheet table view components', () => {
expect(componentController.closeCount).toBe(1);
});
+ it('shows table actions before opening a mobile filter detail drawer', () => {
+ testBed = createTestBed();
+ const componentController = testBed.injector.get(SheetsTableComponentController) as TestComponentController;
+ componentController.setCurrentTableFilterInfo({
+ unitId: testBed.workbook.getUnitId(),
+ subUnitId: 'sheet1',
+ tableId: 'table-orders',
+ row: 0,
+ column: 0,
+ });
+ const rendered = renderWithRediContext(testBed, <MobileSheetTableFilterPanel />);
+ root = rendered.root;
+ container = rendered.container;
+
+ expect(container.textContent).toContain('Insert 1 table column left');
+ expect(container.textContent).toContain('Insert 1 table column right');
+ expect(container.textContent).toContain('Delete table column');
+ expect(container.textContent).toContain('Ascending');
+ expect(container.textContent).toContain('Descending');
+ expect(container.textContent).toContain('Filter by values');
+ expect(container.textContent).toContain('Filter by colors');
+ expect(container.textContent).toContain('Filter by conditions');
+ expect(container.querySelector('input')).toBeNull();
+ expect(getButtonByText(container, 'Insert 1 table column left').className).toContain('univer-bg-gray-100');
+ expect(getButtonByText(container, 'Insert 1 table column left').className).toContain('univer-rounded-xl');
+ expect(getButtonByText(container, 'Filter by values').className).toContain('univer-bg-gray-100');
+ expect(getButtonByText(container, 'Clear filter').className).toContain('univer-bg-gray-100');
+
+ clickButtonByText(container, 'Filter by values');
+
+ expect(document.querySelector('[data-u-comp="mobile-sheet-table-filter-detail"]')).toBeTruthy();
+ expect(document.querySelector('input')).toBeTruthy();
+ expect(document.body.textContent).toContain('Confirm');
+ expect(document.body.textContent).toContain('Cancel');
+ });
+
+ it('edits an existing color filter in the desktop table filter panel', () => {
+ testBed = createTestBed();
+ const table = testBed.injector.get(TableManager).getTable(testBed.workbook.getUnitId(), 'table-orders')!;
+ table.setTableFilterColumn(1, {
+ filterType: TableColumnFilterTypeEnum.color,
+ cellFillColors: ['rgb(255,0,0)'],
+ });
+ const componentController = testBed.injector.get(SheetsTableComponentController) as TestComponentController;
+ componentController.setCurrentTableFilterInfo({
+ unitId: testBed.workbook.getUnitId(),
+ subUnitId: 'sheet1',
+ tableId: 'table-orders',
+ row: 0,
+ column: 1,
+ });
+ const rendered = renderWithRediContext(testBed, <SheetTableFilterPanel />);
+ root = rendered.root;
+ container = rendered.container;
+
+ expect(container.textContent).toContain('Filter by colors');
+ expect(container.textContent).toContain('Cell fill color');
+ expect(container.querySelector('[aria-label="rgb(255,0,0)"]')?.getAttribute('aria-pressed')).toBe('true');
+ });
+
+ it('applies a table color filter from the mobile detail drawer', async () => {
+ testBed = createTestBed();
+ const componentController = testBed.injector.get(SheetsTableComponentController) as TestComponentController;
+ componentController.setCurrentTableFilterInfo({
+ unitId: testBed.workbook.getUnitId(),
+ subUnitId: 'sheet1',
+ tableId: 'table-orders',
+ row: 0,
+ column: 1,
+ });
+ const rendered = renderWithRediContext(testBed, <MobileSheetTableFilterPanel />);
+ root = rendered.root;
+ container = rendered.container;
+
+ clickButtonByText(container, 'Filter by colors');
+ const blueOption = document.body.querySelector('[aria-label="rgb(0,0,255)"]');
+ if (!blueOption) {
+ throw new Error('Blue color option was not found.');
+ }
+ clickElement(blueOption);
+ clickElement(getButtonByText(document.body, 'Confirm'));
+ await flushCommands();
+
+ const table = testBed.injector.get(TableManager).getTable(testBed.workbook.getUnitId(), 'table-orders')!;
+ expect(table.getTableFilterColumn(1)).toEqual({
+ filterType: TableColumnFilterTypeEnum.color,
+ cellFillColors: ['rgb(0,0,255)'],
+ });
+ expect(componentController.closeCount).toBe(1);
+ });
+
+ it('discards mobile value filter edits when the detail drawer is cancelled', async () => {
+ testBed = createTestBed();
+ const table = testBed.injector.get(TableManager).getTable(testBed.workbook.getUnitId(), 'table-orders')!;
+ table.setTableFilterColumn(0, {
+ filterType: TableColumnFilterTypeEnum.manual,
+ values: ['book'],
+ });
+ const componentController = testBed.injector.get(SheetsTableComponentController) as TestComponentController;
+ componentController.setCurrentTableFilterInfo({
+ unitId: testBed.workbook.getUnitId(),
+ subUnitId: 'sheet1',
+ tableId: 'table-orders',
+ row: 0,
+ column: 0,
+ });
+ const rendered = renderWithRediContext(testBed, <MobileSheetTableFilterPanel />);
+ root = rendered.root;
+ container = rendered.container;
+
+ clickButtonByText(container, 'Filter by values');
+ clickCheckboxByText(document.body, 'pen');
+ clickElement(getButtonByText(document.body, 'Cancel'));
+ clickButtonByText(container, 'Filter by values');
+ clickElement(getButtonByText(document.body, 'Confirm'));
+ await flushCommands();
+
+ expect(table.getTableFilterColumn(0)).toEqual({
+ filterType: TableColumnFilterTypeEnum.manual,
+ values: ['book'],
+ });
+ });
+
+ it('undoes the mobile table sort state together with the reordered rows', async () => {
+ testBed = createTestBed();
+ const componentController = testBed.injector.get(SheetsTableComponentController) as TestComponentController;
+ const unitId = testBed.workbook.getUnitId();
+ const worksheet = testBed.workbook.getSheetBySheetId('sheet1')!;
+ testBed.injector.get(IUniverInstanceService).focusUnit(unitId);
+ componentController.setCurrentTableFilterInfo({
+ unitId,
+ subUnitId: 'sheet1',
+ tableId: 'table-orders',
+ row: 0,
+ column: 0,
+ });
+ const rendered = renderWithRediContext(testBed, <MobileSheetTableFilterPanel />);
+ root = rendered.root;
+ container = rendered.container;
+
+ clickButtonByText(container, 'Descending');
+ await flushCommands();
+ await testBed.injector.get(ICommandService).executeCommand(UndoCommand.id);
+
+ const table = testBed.injector.get(TableManager).getTable(unitId, 'table-orders')!;
+ expect(worksheet.getCellRaw(1, 0)?.v).toBe('book');
+ expect(worksheet.getCellRaw(2, 0)?.v).toBe('pen');
+ expect(worksheet.getCellRaw(3, 0)?.v).toBe(undefined);
+ expect(table.getTableFilters().getSortState()).toEqual({});
+ });
+
it('leaves an unfiltered column unchanged when all values remain selected', async () => {
testBed = createTestBed();
const componentController = testBed.injector.get(SheetsTableComponentController) as TestComponentController;
diff --git a/packages/sheets-table-ui/src/views/components/util.ts b/packages/sheets-table-ui/src/views/components/util.ts
index 9d51d64442..365c8fdbbe 100644
--- a/packages/sheets-table-ui/src/views/components/util.ts
+++ b/packages/sheets-table-ui/src/views/components/util.ts
@@ -20,6 +20,7 @@ import type { LocaleKey } from '../../locale/types';
import type { IConditionCompareTypeEnum } from './type';
import { LocaleService } from '@univerjs/core';
import {
+ TableColumnFilterTypeEnum,
TableConditionTypeEnum,
TableDateCompareTypeEnum,
TableNumberCompareTypeEnum,
@@ -324,7 +325,7 @@ export function getSubComponentType(type: TableConditionTypeEnum, compare?: Tabl
// eslint-disable-next-line complexity
export function getInitConditionInfo(tableFilter?: ITableFilterItem) {
- if (!tableFilter || tableFilter.filterType !== 'condition') {
+ if (!tableFilter || tableFilter.filterType !== TableColumnFilterTypeEnum.condition) {
return {
type: TableConditionTypeEnum.String,
compare: TableStringCompareTypeEnum.Equal,
diff --git a/packages/sheets-table/src/commands/commands/__tests__/table-commands.spec.ts b/packages/sheets-table/src/commands/commands/__tests__/table-commands.spec.ts
index ed0864390b..fcaefb56c9 100644
--- a/packages/sheets-table/src/commands/commands/__tests__/table-commands.spec.ts
+++ b/packages/sheets-table/src/commands/commands/__tests__/table-commands.spec.ts
@@ -14,11 +14,13 @@
* limitations under the License.
*/
+import type { ITableManualFilterItem } from '../../../types/type';
import { ICommandService, ILogService, IUndoRedoService, IUniverInstanceService, LocaleService } from '@univerjs/core';
import { IDefinedNamesService } from '@univerjs/engine-formula';
import { AddRangeThemeMutation, RemoveRangeThemeMutation, SheetInterceptorService, SheetRangeThemeModel } from '@univerjs/sheets';
import { describe, expect, it, vi } from 'vitest';
import { TableManager } from '../../../models/table-manager';
+import { TableColumnFilterTypeEnum } from '../../../types/enum';
import { IRangeOperationTypeEnum, IRowColTypeEnum } from '../../../types/type';
import { AddSheetTableMutation } from '../../mutations/add-sheet-table.mutation';
import { DeleteSheetTableMutation } from '../../mutations/delete-sheet-table.mutation';
@@ -288,19 +290,28 @@ describe('sheets-table commands', () => {
}));
});
- it('SetSheetTableFilterCommand should execute mutation with generated table id', () => {
+ it('SetSheetTableFilterCommand should restore the previous filter on undo', () => {
const syncExecuteCommand = vi.fn(() => true);
const pushUndoRedo = vi.fn();
+ const previousFilter: ITableManualFilterItem = {
+ filterType: TableColumnFilterTypeEnum.manual,
+ values: ['Old'],
+ };
const accessor = createAccessor([
[IUndoRedoService, { pushUndoRedo }],
[ICommandService, { syncExecuteCommand }],
+ [TableManager, {
+ getTable: () => ({
+ getTableFilterColumn: () => previousFilter,
+ }),
+ }],
]);
const result = SetSheetTableFilterCommand.handler(accessor, {
unitId: 'u1',
- tableId: undefined as any,
+ tableId: 't1',
column: 1,
- tableFilter: { filterType: 'manual', values: ['A'] } as any,
+ tableFilter: { filterType: TableColumnFilterTypeEnum.manual, values: ['A'] },
});
expect(result).toBe(true);
@@ -308,16 +319,23 @@ describe('sheets-table commands', () => {
SetSheetTableFilterMutation.id,
expect.objectContaining({
unitId: 'u1',
+ tableId: 't1',
column: 1,
- tableFilter: { filterType: 'manual', values: ['A'] },
+ tableFilter: { filterType: TableColumnFilterTypeEnum.manual, values: ['A'] },
}),
undefined
);
- const firstCall = syncExecuteCommand.mock.calls[0] as Array<any> | undefined;
- const tableId = (firstCall?.[1] as { tableId?: string } | undefined)?.tableId;
- expect(typeof tableId).toBe('string');
- expect((tableId ?? '').length).toBeGreaterThan(0);
- expect(pushUndoRedo).toHaveBeenCalled();
+ expect(pushUndoRedo).toHaveBeenCalledWith(expect.objectContaining({
+ undoMutations: [{
+ id: SetSheetTableFilterMutation.id,
+ params: {
+ unitId: 'u1',
+ tableId: 't1',
+ column: 1,
+ tableFilter: previousFilter,
+ },
+ }],
+ }));
});
it('AddTableThemeCommand should register theme and update table style', () => {
diff --git a/packages/sheets-table/src/commands/commands/set-table-filter.command.ts b/packages/sheets-table/src/commands/commands/set-table-filter.command.ts
index d98b22b376..505d46c1c6 100644
--- a/packages/sheets-table/src/commands/commands/set-table-filter.command.ts
+++ b/packages/sheets-table/src/commands/commands/set-table-filter.command.ts
@@ -17,6 +17,7 @@
import type { ICommand, IMutationInfo } from '@univerjs/core';
import type { ISetSheetTableParams } from '../mutations/set-table-filter.mutation';
import { CommandType, generateRandomId, ICommandService, IUndoRedoService, sequenceExecute } from '@univerjs/core';
+import { TableManager } from '../../models/table-manager';
import { SetSheetTableFilterMutation } from '../mutations/set-table-filter.mutation';
export const SetSheetTableFilterCommand: ICommand<ISetSheetTableParams> = {
@@ -28,13 +29,15 @@ export const SetSheetTableFilterCommand: ICommand<ISetSheetTableParams> = {
}
const undoRedoService = accessor.get(IUndoRedoService);
const commandService = accessor.get(ICommandService);
+ const tableManager = accessor.get(TableManager);
const tableId = params.tableId || generateRandomId();
+ const previousFilter = tableManager.getTable(params.unitId, tableId)?.getTableFilterColumn(params.column);
const redos: IMutationInfo[] = [];
const undos: IMutationInfo[] = [];
redos.push({ id: SetSheetTableFilterMutation.id, params: { ...params, tableId } });
- undos.push({ id: SetSheetTableFilterMutation.id, params: { ...params, tableId, tableFilter: undefined } });
+ undos.push({ id: SetSheetTableFilterMutation.id, params: { ...params, tableId, tableFilter: previousFilter } });
const res = sequenceExecute(redos, commandService);
diff --git a/packages/sheets-table/src/commands/commands/set-table-sort-state.command.ts b/packages/sheets-table/src/commands/commands/set-table-sort-state.command.ts
new file mode 100644
index 0000000000..a9e67e2143
--- /dev/null
+++ b/packages/sheets-table/src/commands/commands/set-table-sort-state.command.ts
@@ -0,0 +1,65 @@
+/**
+ * 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 { ICommand } from '@univerjs/core';
+import type { ITableFilterJSON } from '../../types/type';
+import { CommandType, ICommandService, IUndoRedoService } from '@univerjs/core';
+import { TableManager } from '../../models/table-manager';
+import { SetSheetTableMutation } from '../mutations/set-sheet-table.mutation';
+
+export interface ISetSheetTableSortStateParams {
+ unitId: string;
+ tableId: string;
+ sortInfo: ITableFilterJSON['tableSortInfo'];
+}
+
+export const SetSheetTableSortStateCommand: ICommand<ISetSheetTableSortStateParams> = {
+ id: 'sheet.command.set-table-sort-state',
+ type: CommandType.COMMAND,
+ handler: (accessor, params) => {
+ if (!params) {
+ return false;
+ }
+
+ const table = accessor.get(TableManager).getTable(params.unitId, params.tableId);
+ if (!table) {
+ return false;
+ }
+
+ const previousSortInfo = table.getTableFilters().toJSON().tableSortInfo;
+ const commandService = accessor.get(ICommandService);
+ const mutationParams = {
+ unitId: params.unitId,
+ subUnitId: table.getSubunitId(),
+ tableId: params.tableId,
+ config: { sortInfo: params.sortInfo },
+ };
+ const success = commandService.syncExecuteCommand(SetSheetTableMutation.id, mutationParams);
+ if (!success) {
+ return false;
+ }
+
+ accessor.get(IUndoRedoService).pushUndoRedo({
+ unitID: params.unitId,
+ undoMutations: [{
+ id: SetSheetTableMutation.id,
+ params: { ...mutationParams, config: { sortInfo: previousSortInfo } },
+ }],
+ redoMutations: [{ id: SetSheetTableMutation.id, params: mutationParams }],
+ });
+ return true;
+ },
+};
diff --git a/packages/sheets-table/src/index.ts b/packages/sheets-table/src/index.ts
index f71e0cb1b9..824d16c780 100644
--- a/packages/sheets-table/src/index.ts
+++ b/packages/sheets-table/src/index.ts
@@ -23,6 +23,7 @@ export { RemoveTableThemeCommand } from './commands/commands/remove-table-theme.
export { SetSheetTableCommand } from './commands/commands/set-sheet-table.command';
export type { ISetSheetTableCommandParams } from './commands/commands/set-sheet-table.command';
export { SetSheetTableFilterCommand } from './commands/commands/set-table-filter.command';
+export { SetSheetTableSortStateCommand } from './commands/commands/set-table-sort-state.command';
export {
SheetTableInsertColCommand,
SheetTableInsertColumnAtCommand,
@@ -59,6 +60,7 @@ export {
TableStringCompareTypeEnum,
} from './types/enum';
export type {
+ ITableColorFilterItem,
ITableColumnJson,
ITableConditionFilterItem,
ITableData,
@@ -73,6 +75,6 @@ export type {
TableRelationTupleType,
} from './types/type';
export type { ITableJson, ITableSetConfig } from './types/type';
-export { getExistingNamesSet, isConditionFilter, isManualTableFilter } from './util';
+export { getExistingNamesSet, isColorTableFilter, isConditionFilter, isManualTableFilter } from './util';
export { validateSheetTableName } from './util/table-name';
export type { ISheetTableNameValidationResult, SheetTableNameValidationReason } from './util/table-name';
diff --git a/packages/sheets-table/src/models/__tests__/table-model.spec.ts b/packages/sheets-table/src/models/__tests__/table-model.spec.ts
index f016a92e1f..3132c02945 100644
--- a/packages/sheets-table/src/models/__tests__/table-model.spec.ts
+++ b/packages/sheets-table/src/models/__tests__/table-model.spec.ts
@@ -14,7 +14,8 @@
* limitations under the License.
*/
-import { CellValueType } from '@univerjs/core';
+import type { ITableColorFilterItem } from '../../types/type';
+import { CellValueType, ThemeColorType } from '@univerjs/core';
import { describe, expect, it } from 'vitest';
import { TABLE_FILTER_EMPTY_VALUE } from '../../const';
import {
@@ -165,4 +166,167 @@ describe('TableFilters', () => {
filters.dispose();
expect(filters.toJSON().tableColumnFilterList).toEqual([]);
});
+
+ it('filters rows by cell fill colors', () => {
+ const filters = new TableFilters();
+ const cells = [
+ { v: 'Red', s: { bg: { rgb: '#ff0000' } } },
+ { v: 'Blue', s: { bg: { rgb: '#0000ff' } } },
+ { v: 'Default' },
+ ];
+ const sheet = {
+ getCell(row: number) {
+ return cells[row] ?? null;
+ },
+ getCellRaw(row: number) {
+ return this.getCell(row);
+ },
+ getComposedCellStyleByCellData(_row: number, _column: number, cell: typeof cells[number]) {
+ return cell?.s ?? {};
+ },
+ };
+
+ filters.setColumnFilter(0, {
+ filterType: TableColumnFilterTypeEnum.color,
+ cellFillColors: ['rgb(255, 0, 0)'],
+ });
+
+ expect([...filters.doFilter(sheet as never, {
+ startRow: 0,
+ endRow: 2,
+ startColumn: 0,
+ endColumn: 0,
+ })]).toEqual([1, 2]);
+ });
+
+ it('filters rows by theme fill colors', () => {
+ const filters = new TableFilters();
+ const cells = [
+ { v: 'Theme', s: { bg: { th: ThemeColorType.ACCENT1 } } },
+ { v: 'Red', s: { bg: { rgb: '#ff0000' } } },
+ ];
+ const sheet = {
+ getCell(row: number) {
+ return cells[row] ?? null;
+ },
+ getCellRaw(row: number) {
+ return this.getCell(row);
+ },
+ getComposedCellStyleByCellData(_row: number, _column: number, cell: typeof cells[number]) {
+ return cell?.s ?? {};
+ },
+ };
+
+ filters.setColumnFilter(0, {
+ filterType: TableColumnFilterTypeEnum.color,
+ cellFillColors: ['rgb(68, 114, 196)'],
+ });
+
+ expect([...filters.doFilter(sheet as never, {
+ startRow: 0,
+ endRow: 1,
+ startColumn: 0,
+ endColumn: 0,
+ })]).toEqual([1]);
+ });
+
+ it('filters rows by the default fill color', () => {
+ const filters = new TableFilters();
+ const cells = [
+ { v: 'Red', s: { bg: { rgb: '#ff0000' } } },
+ { v: 'Default' },
+ ];
+ const sheet = {
+ getCell(row: number) {
+ return cells[row] ?? null;
+ },
+ getCellRaw(row: number) {
+ return this.getCell(row);
+ },
+ getComposedCellStyleByCellData(_row: number, _column: number, cell: typeof cells[number]) {
+ return cell?.s ?? {};
+ },
+ };
+
+ filters.setColumnFilter(0, {
+ filterType: TableColumnFilterTypeEnum.color,
+ cellFillColors: [null],
+ });
+
+ expect([...filters.doFilter(sheet as never, {
+ startRow: 0,
+ endRow: 1,
+ startColumn: 0,
+ endColumn: 0,
+ })]).toEqual([0]);
+ });
+
+ it('filters rows by cell text colors and preserves the filter in JSON', () => {
+ const filters = new TableFilters();
+ const cells = [
+ { v: 'Red', s: { cl: { rgb: '#ff0000' } } },
+ { v: 'Blue', s: { cl: { rgb: '#0000ff' } } },
+ { v: 'Default' },
+ ];
+ const sheet = {
+ getCell(row: number) {
+ return cells[row] ?? null;
+ },
+ getCellRaw(row: number) {
+ return this.getCell(row);
+ },
+ getComposedCellStyleByCellData(_row: number, _column: number, cell: typeof cells[number]) {
+ return cell?.s ?? {};
+ },
+ };
+ const filter: ITableColorFilterItem = {
+ filterType: TableColumnFilterTypeEnum.color,
+ cellTextColors: ['rgb(0, 0, 255)'],
+ };
+
+ filters.setColumnFilter(0, filter);
+
+ expect([...filters.doFilter(sheet as never, {
+ startRow: 0,
+ endRow: 2,
+ startColumn: 0,
+ endColumn: 0,
+ })]).toEqual([0, 2]);
+ expect(filters.toJSON().tableColumnFilterList).toEqual([filter]);
+
+ const restored = new TableFilters();
+ restored.fromJSON(filters.toJSON());
+ expect(restored.getColumnFilter(0)).toEqual(filter);
+ });
+
+ it('treats the default text color as black', () => {
+ const filters = new TableFilters();
+ const cells = [
+ { v: 'Blue', s: { cl: { rgb: '#0000ff' } } },
+ { v: 'Default', s: { cl: { rgb: null } } },
+ ];
+ const sheet = {
+ getCell(row: number) {
+ return cells[row] ?? null;
+ },
+ getCellRaw(row: number) {
+ return this.getCell(row);
+ },
+ getComposedCellStyleByCellData(_row: number, _column: number, cell: typeof cells[number]) {
+ return cell?.s ?? {};
+ },
+ };
+
+ filters.setColumnFilter(0, {
+ filterType: TableColumnFilterTypeEnum.color,
+ cellTextColors: ['rgb(0, 0, 0)'],
+ });
+
+ expect([...filters.doFilter(sheet as never, {
+ startRow: 0,
+ endRow: 1,
+ startColumn: 0,
+ endColumn: 0,
+ })]).toEqual([0]);
+ });
});
diff --git a/packages/sheets-table/src/models/table-filter.ts b/packages/sheets-table/src/models/table-filter.ts
index d79510bbab..edde9d8522 100644
--- a/packages/sheets-table/src/models/table-filter.ts
+++ b/packages/sheets-table/src/models/table-filter.ts
@@ -14,18 +14,18 @@
* limitations under the License.
*/
-import type { ICellData, Nullable, Worksheet } from '@univerjs/core';
+import type { ICellData, IStyleData, Nullable, Worksheet } from '@univerjs/core';
import type { SheetsTableButtonStateEnum } from '../types/enum';
import type { ICalculatedOptions, ITableFilterItem, ITableFilterJSON, ITableRange } from '../types/type';
-import { DateSystem } from '@univerjs/core';
+import { ColorKit, DateSystem, DEFAULT_STYLES, getColorStyle } from '@univerjs/core';
import { TABLE_FILTER_EMPTY_VALUE } from '../const';
import { SheetsTableSortStateEnum, TableColumnFilterTypeEnum, TableConditionTypeEnum } from '../types/enum';
-import { getTableFilterState, isConditionFilter } from '../util';
+import { getTableFilterState, isColorTableFilter, isConditionFilter } from '../util';
import { getCellValueWithConditionType, getConditionExecuteFunc, isNumberDynamicFilter } from './filter-util/condition';
export class TableFilters {
private _tableColumnFilterList: (ITableFilterItem | undefined)[];
- private _tableSortInfo: { columnIndex: number; sortState: SheetsTableSortStateEnum };
+ private _tableSortInfo?: { columnIndex: number; sortState: SheetsTableSortStateEnum };
private _filterOutRows: Set<number>;
constructor() {
this._tableColumnFilterList = [];
@@ -43,6 +43,10 @@ export class TableFilters {
this._tableSortInfo = { columnIndex, sortState };
}
+ setSortInfo(sortInfo: ITableFilterJSON['tableSortInfo']) {
+ this._tableSortInfo = sortInfo;
+ }
+
getColumnFilter(columnIndex: number): ITableFilterItem | undefined {
return this._tableColumnFilterList[columnIndex];
}
@@ -89,7 +93,15 @@ export class TableFilters {
const column = startColumn + columnIndex;
const executeFunc = this.getExecuteFunc(sheet, range, columnIndex, filter);
for (let row = startRow; row <= endRow; row++) {
- // const cellValue = sheet.getCell(row, column);
+ if (isColorTableFilter(filter)) {
+ const cellData = sheet.getCell(row, column);
+ const cellStyle = sheet.getComposedCellStyleByCellData(row, column, cellData);
+ if (!executeFunc(cellStyle)) {
+ filterOutRows.add(row);
+ }
+ continue;
+ }
+
const conditionType = isConditionFilter(filter) ? filter.filterInfo.conditionType : TableConditionTypeEnum.String;
const cellValue = getCellValueWithConditionType(sheet, row, column, conditionType, dateSystem);
if (cellValue === null && !executeFunc(cellValue)) {
@@ -134,11 +146,25 @@ export class TableFilters {
const isDynamic = isNumberDynamicFilter(filter.filterInfo.compareType);
const calculatedOptions = isDynamic ? this._getNumberCalculatedOptions(sheet, range, columnIndex) : undefined;
return getConditionExecuteFunc(filter, calculatedOptions);
+ } else if (filter.filterType === TableColumnFilterTypeEnum.color) {
+ const normalizeColor = (color: Nullable<string>) => color ? new ColorKit(color).toRgbString() : null;
+ if (filter.cellFillColors) {
+ const colors = new Set(filter.cellFillColors.map(normalizeColor));
+ return (style: Nullable<IStyleData>) => colors.has(normalizeColor(getColorStyle(style?.bg)));
+ }
+ if (filter.cellTextColors) {
+ const colors = new Set(filter.cellTextColors.map(normalizeColor));
+ return (style: Nullable<IStyleData>) => colors.has(normalizeColor(
+ getColorStyle(style?.cl) ?? getColorStyle(DEFAULT_STYLES.cl)
+ ));
+ }
} else {
- return (value: Nullable<ICellData>) => {
+ return (_value: Nullable<ICellData>) => {
return true;
};
}
+
+ return () => true;
}
toJSON(): ITableFilterJSON {
diff --git a/packages/sheets-table/src/models/table-manager.ts b/packages/sheets-table/src/models/table-manager.ts
index d50be8ee27..23d5b26a26 100644
--- a/packages/sheets-table/src/models/table-manager.ts
+++ b/packages/sheets-table/src/models/table-manager.ts
@@ -369,7 +369,7 @@ export class TableManager extends Disposable {
const table = unitMap?.get(tableId);
if (!table) return;
const subUnitId = table.getSubunitId();
- const { name, updateRange, rowColOperation, theme, options } = config;
+ const { name, updateRange, rowColOperation, theme, sortInfo, options } = config;
if (name) {
const oldTableName = table.getDisplayName();
table.setDisplayName(name);
@@ -399,6 +399,10 @@ export class TableManager extends Disposable {
});
}
+ if ('sortInfo' in config) {
+ table.getTableFilters().setSortInfo(sortInfo);
+ }
+
if (options) {
if (options.showHeader !== undefined) {
table.setShowHeader(options.showHeader);
diff --git a/packages/sheets-table/src/plugin.ts b/packages/sheets-table/src/plugin.ts
index 9026a07267..7ef34a9086 100644
--- a/packages/sheets-table/src/plugin.ts
+++ b/packages/sheets-table/src/plugin.ts
@@ -24,6 +24,7 @@ import { DeleteSheetTableCommand } from './commands/commands/delete-sheet-table.
import { RemoveTableThemeCommand } from './commands/commands/remove-table-theme.command';
import { SetSheetTableCommand } from './commands/commands/set-sheet-table.command';
import { SetSheetTableFilterCommand } from './commands/commands/set-table-filter.command';
+import { SetSheetTableSortStateCommand } from './commands/commands/set-table-sort-state.command';
import { SheetTableInsertColCommand, SheetTableInsertColumnAtCommand, SheetTableInsertRowAtCommand, SheetTableInsertRowCommand, SheetTableRemoveColCommand, SheetTableRemoveColumnAtCommand, SheetTableRemoveRowCommand } from './commands/commands/sheet-table-row-col.command';
import { AddSheetTableMutation } from './commands/mutations/add-sheet-table.mutation';
import { DeleteSheetTableMutation } from './commands/mutations/delete-sheet-table.mutation';
@@ -102,6 +103,7 @@ export class UniverSheetsTablePlugin extends Plugin {
DeleteSheetTableMutation,
SetSheetTableFilterMutation,
SetSheetTableFilterCommand,
+ SetSheetTableSortStateCommand,
SetSheetTableCommand,
SetSheetTableMutation,
AddTableThemeCommand,
diff --git a/packages/sheets-table/src/types/enum.ts b/packages/sheets-table/src/types/enum.ts
index b98eb5047a..3c9b36cb61 100644
--- a/packages/sheets-table/src/types/enum.ts
+++ b/packages/sheets-table/src/types/enum.ts
@@ -27,6 +27,7 @@ export enum TableColumnDataTypeEnum {
export enum TableColumnFilterTypeEnum {
manual = 'manual',
condition = 'condition',
+ color = 'color',
}
export enum TableConditionTypeEnum {
diff --git a/packages/sheets-table/src/types/type.ts b/packages/sheets-table/src/types/type.ts
index 8d1ec946ed..1bb92f8c68 100644
--- a/packages/sheets-table/src/types/type.ts
+++ b/packages/sheets-table/src/types/type.ts
@@ -60,7 +60,7 @@ export interface ITableFilterJSON {
tableSortInfo?: { columnIndex: number; sortState: SheetsTableSortStateEnum };
}
-export type ITableFilterItem = ITableManualFilterItem | ITableConditionFilterItem;
+export type ITableFilterItem = ITableManualFilterItem | ITableConditionFilterItem | ITableColorFilterItem;
export type TableMetaType = Record<string, any>;
/**
@@ -80,6 +80,15 @@ export interface ITableConditionFilterItem {
filterInfo: ITableDateFilterInfo | ITableStringFilterInfo | ITableNumberFilterInfo | ITableLogicFilterInfo;
}
+/**
+ * Represents the table filter item, filter data by cell fill or text colors.
+ */
+export interface ITableColorFilterItem {
+ filterType: TableColumnFilterTypeEnum.color;
+ cellFillColors?: Array<string | null>;
+ cellTextColors?: Array<string | null>;
+}
+
export interface ITableDateFilterInfo {
conditionType: TableConditionTypeEnum.Date;
compareType: TableDateCompareTypeEnum;
@@ -142,6 +151,7 @@ export interface ITableSetConfig {
updateRange?: ITableRangeUpdate;
rowColOperation?: ITableRangeRowColOperation;
theme?: string;
+ sortInfo?: ITableFilterJSON['tableSortInfo'];
options?: {
showHeader?: boolean;
};
diff --git a/packages/sheets-table/src/util.ts b/packages/sheets-table/src/util.ts
index 1abd9adbd1..27e80d83db 100644
--- a/packages/sheets-table/src/util.ts
+++ b/packages/sheets-table/src/util.ts
@@ -17,7 +17,12 @@
import type { ICellData, IDocumentData, IUniverInstanceService, Nullable, Workbook } from '@univerjs/core';
import type { IDefinedNamesService } from '@univerjs/engine-formula';
import type { TableManager } from './models/table-manager';
-import type { ITableConditionFilterItem, ITableFilterItem, ITableManualFilterItem } from './types/type';
+import type {
+ ITableColorFilterItem,
+ ITableConditionFilterItem,
+ ITableFilterItem,
+ ITableManualFilterItem,
+} from './types/type';
import { CellValueType, UniverInstanceType } from '@univerjs/core';
import { SheetsTableButtonStateEnum, SheetsTableSortStateEnum, TableColumnFilterTypeEnum } from './types/enum';
@@ -100,6 +105,13 @@ export function isManualTableFilter(filter: ITableFilterItem | undefined): filte
return filter.filterType === TableColumnFilterTypeEnum.manual;
}
+export function isColorTableFilter(filter: ITableFilterItem | undefined): filter is ITableColorFilterItem {
+ if (!filter) {
+ return false;
+ }
+ return filter.filterType === TableColumnFilterTypeEnum.color;
+}
+
/**
* Get existing names including sheet names, table names and defined names to check for duplicates table name.
*/
diff --git a/packages/sheets-thread-comment-ui/src/commands/operations/comment.operation.ts b/packages/sheets-thread-comment-ui/src/commands/operations/comment.operation.ts
index eaec8811ad..400d01ac12 100644
--- a/packages/sheets-thread-comment-ui/src/commands/operations/comment.operation.ts
+++ b/packages/sheets-thread-comment-ui/src/commands/operations/comment.operation.ts
@@ -24,11 +24,11 @@ import { ThreadCommentAnchorKind } from '@univerjs/thread-comment';
import { ThreadCommentDraftService, ThreadCommentPanelService } from '@univerjs/thread-comment-ui';
import { ISidebarService } from '@univerjs/ui';
import { SheetsThreadCommentPopupService } from '../../services/sheets-thread-comment-popup.service';
-import { SHEETS_THREAD_COMMENT_PANEL } from '../../types/const';
+import { SHEETS_THREAD_COMMENT_PANEL, SHOW_ADD_SHEET_COMMENT_OPERATION_ID } from '../../types/const';
export const ShowAddSheetCommentModalOperation: IOperation = {
type: CommandType.OPERATION,
- id: 'sheet.operation.show-comment-modal',
+ id: SHOW_ADD_SHEET_COMMENT_OPERATION_ID,
handler(accessor) {
const selectionManagerService = accessor.get(SheetsSelectionsService);
const univerInstanceService = accessor.get(IUniverInstanceService);
@@ -101,7 +101,7 @@ export const OpenSheetCommentPanelOperation: IOperation = {
},
};
-function openSheetCommentPanel(
+export function openSheetCommentPanel(
sidebarService: ISidebarService,
panelService: ThreadCommentPanelService
): void {
diff --git a/packages/sheets-thread-comment-ui/src/commands/operations/mobile/show-add-sheet-comment.operation.ts b/packages/sheets-thread-comment-ui/src/commands/operations/mobile/show-add-sheet-comment.operation.ts
new file mode 100644
index 0000000000..073abaecb3
--- /dev/null
+++ b/packages/sheets-thread-comment-ui/src/commands/operations/mobile/show-add-sheet-comment.operation.ts
@@ -0,0 +1,64 @@
+/**
+ * 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, IUniverInstanceService } from '@univerjs/core';
+import { getSheetCommandTarget, SheetsSelectionsService } from '@univerjs/sheets';
+import { SheetsThreadCommentModel } from '@univerjs/sheets-thread-comment';
+import { ThreadCommentDraftService, ThreadCommentPanelService } from '@univerjs/thread-comment-ui';
+import { ISidebarService } from '@univerjs/ui';
+import { MobileSheetCommentDraftService } from '../../../services/mobile/mobile-sheet-comment-draft.service';
+import { SHOW_ADD_SHEET_COMMENT_OPERATION_ID } from '../../../types/const';
+import { openSheetCommentPanel } from '../comment.operation';
+
+export const ShowAddSheetCommentMobileOperation: IOperation = {
+ type: CommandType.OPERATION,
+ id: SHOW_ADD_SHEET_COMMENT_OPERATION_ID,
+ handler(accessor) {
+ const activeCell = accessor.get(SheetsSelectionsService).getCurrentLastSelection()?.primary;
+ if (!activeCell) {
+ return false;
+ }
+
+ const target = getSheetCommandTarget(accessor.get(IUniverInstanceService));
+ if (!target) {
+ return false;
+ }
+
+ const { unitId, subUnitId } = target;
+ const row = activeCell.startRow;
+ const column = activeCell.startColumn;
+ const panelService = accessor.get(ThreadCommentPanelService);
+ const mobileDraftService = accessor.get(MobileSheetCommentDraftService);
+ const rootId = accessor.get(SheetsThreadCommentModel).getByLocation(unitId, subUnitId, row, column);
+
+ accessor.get(ThreadCommentDraftService).cancel();
+ if (rootId) {
+ mobileDraftService.cancel();
+ panelService.setActiveComment({
+ unitId,
+ subUnitId,
+ commentId: rootId,
+ });
+ } else {
+ panelService.setActiveComment(undefined);
+ mobileDraftService.place({ unitId, subUnitId, row, column });
+ }
+
+ openSheetCommentPanel(accessor.get(ISidebarService), panelService);
+ return true;
+ },
+};
diff --git a/packages/sheets-thread-comment-ui/src/controllers/mobile/components.controller.ts b/packages/sheets-thread-comment-ui/src/controllers/mobile/components.controller.ts
new file mode 100644
index 0000000000..d17f732638
--- /dev/null
+++ b/packages/sheets-thread-comment-ui/src/controllers/mobile/components.controller.ts
@@ -0,0 +1,33 @@
+/**
+ * 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 { Disposable, Inject } from '@univerjs/core';
+import { CommentIcon, InsertCommentDoubleIcon } from '@univerjs/icons';
+import { ComponentManager, IconManager } from '@univerjs/ui';
+import { SHEETS_THREAD_COMMENT_PANEL } from '../../types/const';
+import { MobileSheetsThreadCommentPanel } from '../../views/mobile/MobileSheetsThreadCommentPanel';
+
+export class MobileComponentsController extends Disposable {
+ constructor(
+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,
+ @Inject(IconManager) private readonly _iconManager: IconManager
+ ) {
+ super();
+
+ this.disposeWithMe(this._componentManager.register(SHEETS_THREAD_COMMENT_PANEL, MobileSheetsThreadCommentPanel));
+ this.disposeWithMe(this._iconManager.register({ CommentIcon, InsertCommentDoubleIcon }));
+ }
+}
diff --git a/packages/sheets-thread-comment-ui/src/controllers/mobile/sheets-thread-comment.controller.ts b/packages/sheets-thread-comment-ui/src/controllers/mobile/sheets-thread-comment.controller.ts
new file mode 100644
index 0000000000..168902b408
--- /dev/null
+++ b/packages/sheets-thread-comment-ui/src/controllers/mobile/sheets-thread-comment.controller.ts
@@ -0,0 +1,28 @@
+/**
+ * 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 { Disposable } from '@univerjs/core';
+import { IMenuManagerService } from '@univerjs/ui';
+import { mobileMenuSchema } from '../../menu/mobile-schema';
+
+export class SheetsThreadCommentMobileController extends Disposable {
+ constructor(
+ @IMenuManagerService menuManagerService: IMenuManagerService
+ ) {
+ super();
+ menuManagerService.mergeMenu(mobileMenuSchema);
+ }
+}
diff --git a/packages/sheets-thread-comment-ui/src/menu/mobile-menu.ts b/packages/sheets-thread-comment-ui/src/menu/mobile-menu.ts
new file mode 100644
index 0000000000..0b7061edc8
--- /dev/null
+++ b/packages/sheets-thread-comment-ui/src/menu/mobile-menu.ts
@@ -0,0 +1,61 @@
+/**
+ * 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 { IAccessor } from '@univerjs/core';
+import type { LocaleKey } from '../locale/types';
+import { UniverInstanceType } from '@univerjs/core';
+import { RangeProtectionPermissionViewPoint, SheetsSelectionsService, WorkbookCommentPermission, WorksheetViewPermission } from '@univerjs/sheets';
+import { SheetsThreadCommentModel } from '@univerjs/sheets-thread-comment';
+import { getCurrentRangeDisable$ } from '@univerjs/sheets-ui';
+import { getMenuHiddenObservable, MenuItemType } from '@univerjs/ui';
+import { ShowAddSheetCommentMobileOperation } from '../commands/operations/mobile/show-add-sheet-comment.operation';
+
+export function getMobileThreadCommentMenuTitle(accessor: IAccessor): LocaleKey {
+ const selectionService = accessor.get(SheetsSelectionsService);
+ const selection = selectionService.getCurrentLastSelection()?.primary;
+ const selectionParam = selectionService.currentSelectionParam;
+ if (!selection || !selectionParam) {
+ return 'sheets-thread-comment-ui.menu.addComment';
+ }
+
+ const commentId = accessor.get(SheetsThreadCommentModel).getByLocation(
+ selectionParam.unitId,
+ selectionParam.sheetId,
+ selection.startRow,
+ selection.startColumn
+ );
+ return commentId
+ ? 'sheets-thread-comment-ui.menu.openComments'
+ : 'sheets-thread-comment-ui.menu.addComment';
+}
+
+export const mobileThreadCommentMenuFactory = (accessor: IAccessor) => ({
+ id: ShowAddSheetCommentMobileOperation.id,
+ type: MenuItemType.BUTTON,
+ icon: 'InsertCommentDoubleIcon',
+ title: 'sheets-thread-comment-ui.menu.addComment',
+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET),
+ disabled$: getCurrentRangeDisable$(accessor, {
+ workbookTypes: [WorkbookCommentPermission],
+ worksheetTypes: [WorksheetViewPermission],
+ rangeTypes: [RangeProtectionPermissionViewPoint],
+ }),
+});
+
+export const mobileContextThreadCommentMenuFactory = (accessor: IAccessor) => ({
+ ...mobileThreadCommentMenuFactory(accessor),
+ title: getMobileThreadCommentMenuTitle(accessor),
+});
diff --git a/packages/sheets-thread-comment-ui/src/menu/mobile-schema.ts b/packages/sheets-thread-comment-ui/src/menu/mobile-schema.ts
new file mode 100644
index 0000000000..e3023b43e2
--- /dev/null
+++ b/packages/sheets-thread-comment-ui/src/menu/mobile-schema.ts
@@ -0,0 +1,59 @@
+/**
+ * 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 { MenuSchemaType } from '@univerjs/ui';
+import { ContextMenuGroup, ContextMenuPosition, FloatingObjectToolbarPosition, RibbonInsertGroup } from '@univerjs/ui';
+import { AddSheetDrawingCommentOperation, ToggleSheetCommentPanelOperation } from '../commands/operations/comment.operation';
+import { ShowAddSheetCommentMobileOperation } from '../commands/operations/mobile/show-add-sheet-comment.operation';
+import { drawingCommentMenuFactory, threadPanelMenuFactory } from './menu';
+import { mobileContextThreadCommentMenuFactory, mobileThreadCommentMenuFactory } from './mobile-menu';
+
+export const mobileMenuSchema: MenuSchemaType = {
+ [RibbonInsertGroup.MEDIA]: {
+ [ToggleSheetCommentPanelOperation.id]: {
+ order: 2,
+ gridLayout: { row: 1, column: 3, showLabel: true },
+ menuItemFactory: threadPanelMenuFactory,
+ },
+ [ShowAddSheetCommentMobileOperation.id]: {
+ order: 2.1,
+ gridLayout: { row: 2, column: 3, showLabel: true },
+ menuItemFactory: mobileThreadCommentMenuFactory,
+ },
+ },
+ [ContextMenuPosition.MAIN_AREA]: {
+ [ContextMenuGroup.OTHERS]: {
+ [ShowAddSheetCommentMobileOperation.id]: {
+ order: 0,
+ menuItemFactory: mobileContextThreadCommentMenuFactory,
+ },
+ },
+ },
+ [FloatingObjectToolbarPosition.SHEET]: {
+ [AddSheetDrawingCommentOperation.id]: {
+ order: 10,
+ menuItemFactory: drawingCommentMenuFactory,
+ },
+ },
+ [ContextMenuPosition.DRAWING]: {
+ [ContextMenuGroup.OTHERS]: {
+ [AddSheetDrawingCommentOperation.id]: {
+ order: 0,
+ menuItemFactory: drawingCommentMenuFactory,
+ },
+ },
+ },
+};
diff --git a/packages/sheets-thread-comment-ui/src/mobile-plugin.ts b/packages/sheets-thread-comment-ui/src/mobile-plugin.ts
index 212bee2893..5ff6417c1a 100644
--- a/packages/sheets-thread-comment-ui/src/mobile-plugin.ts
+++ b/packages/sheets-thread-comment-ui/src/mobile-plugin.ts
@@ -14,20 +14,32 @@
* limitations under the License.
*/
+import type { Dependency } from '@univerjs/core';
import type { IUniverSheetsThreadCommentUIConfig } from './config/config';
-import { DependentOn, ICommandService, IConfigService, Inject, Injector } from '@univerjs/core';
-import { IRenderManagerService, UniverRenderEnginePlugin } from '@univerjs/engine-render';
+import { DependentOn, ICommandService, IConfigService, Inject, Injector, merge, Plugin, UniverInstanceType } from '@univerjs/core';
+import { UniverRenderEnginePlugin } from '@univerjs/engine-render';
import { UniverSheetsPlugin } from '@univerjs/sheets';
import { UniverSheetsThreadCommentPlugin } from '@univerjs/sheets-thread-comment';
import { UniverSheetsMobileUIPlugin } from '@univerjs/sheets-ui';
import { UniverThreadCommentPlugin } from '@univerjs/thread-comment';
import { UniverThreadCommentMobileUIPlugin } from '@univerjs/thread-comment-ui';
import { UniverMobileUIPlugin } from '@univerjs/ui';
-import { defaultPluginConfig } from './config/config';
+import pkg from '../package.json';
+import {
+ AddSheetDrawingCommentOperation,
+ OpenSheetCommentPanelOperation,
+ ToggleSheetCommentPanelOperation,
+} from './commands/operations/comment.operation';
+import { ShowAddSheetCommentMobileOperation } from './commands/operations/mobile/show-add-sheet-comment.operation';
+import { defaultPluginConfig, SHEETS_THREAD_COMMENT_UI_PLUGIN_CONFIG_KEY } from './config/config';
+import { MobileComponentsController } from './controllers/mobile/components.controller';
+import { SheetsThreadCommentMobileController } from './controllers/mobile/sheets-thread-comment.controller';
+import { SheetsThreadCommentRenderController } from './controllers/render-controllers/render.controller';
import { SheetsThreadCommentCopyPasteController } from './controllers/sheets-thread-comment-copy-paste.controller';
import { SheetsThreadCommentPermissionController } from './controllers/sheets-thread-comment-permission.controller';
-import { SheetsThreadCommentPopupController } from './controllers/sheets-thread-comment-popup.controller';
-import { UniverSheetsThreadCommentUIPlugin } from './plugin';
+import { MobileSheetCommentDraftService } from './services/mobile/mobile-sheet-comment-draft.service';
+import { SheetsThreadCommentPopupService } from './services/sheets-thread-comment-popup.service';
+import { PLUGIN_NAME } from './types/const';
@DependentOn(
UniverRenderEnginePlugin,
@@ -38,22 +50,55 @@ import { UniverSheetsThreadCommentUIPlugin } from './plugin';
UniverMobileUIPlugin,
UniverSheetsMobileUIPlugin
)
-export class UniverSheetsThreadCommentMobileUIPlugin extends UniverSheetsThreadCommentUIPlugin {
- static override pluginName = UniverSheetsThreadCommentUIPlugin.pluginName;
+export class UniverSheetsThreadCommentMobileUIPlugin extends Plugin {
+ static override pluginName = PLUGIN_NAME;
+ static override packageName = pkg.name;
+ static override version = pkg.version;
+ static override type = UniverInstanceType.UNIVER_SHEET;
constructor(
- config: Partial<IUniverSheetsThreadCommentUIConfig> = defaultPluginConfig,
- @Inject(Injector) injector: Injector,
- @Inject(ICommandService) commandService: ICommandService,
- @IRenderManagerService renderManagerService: IRenderManagerService,
- @IConfigService configService: IConfigService
+ private readonly _config: Partial<IUniverSheetsThreadCommentUIConfig> = defaultPluginConfig,
+ @Inject(Injector) protected override _injector: Injector,
+ @Inject(ICommandService) private readonly _commandService: ICommandService,
+ @IConfigService private readonly _configService: IConfigService
) {
- super(config, injector, commandService, renderManagerService, configService);
+ super();
+
+ const { menu, ...rest } = merge({}, defaultPluginConfig, this._config);
+ if (menu) {
+ this._configService.setConfig('menu', menu, { merge: true });
+ }
+ this._configService.setConfig(SHEETS_THREAD_COMMENT_UI_PLUGIN_CONFIG_KEY, rest);
+ }
+
+ override onStarting(): void {
+ ([
+ [MobileComponentsController],
+ [SheetsThreadCommentMobileController],
+ [SheetsThreadCommentRenderController],
+ [SheetsThreadCommentCopyPasteController],
+ [SheetsThreadCommentPopupService],
+ [SheetsThreadCommentPermissionController],
+ [MobileSheetCommentDraftService],
+ ] as Dependency[]).forEach((dependency) => this._injector.add(dependency));
+ this._injector.get(MobileComponentsController);
+
+ [
+ AddSheetDrawingCommentOperation,
+ OpenSheetCommentPanelOperation,
+ ShowAddSheetCommentMobileOperation,
+ ToggleSheetCommentPanelOperation,
+ ].forEach((command) => this._commandService.registerCommand(command));
+
+ this._injector.get(SheetsThreadCommentMobileController);
+ }
+
+ override onReady(): void {
+ this._injector.get(SheetsThreadCommentRenderController);
}
override onRendered(): void {
this._injector.get(SheetsThreadCommentCopyPasteController);
- this._injector.get(SheetsThreadCommentPopupController);
this._injector.get(SheetsThreadCommentPermissionController);
}
}
diff --git a/packages/sheets-thread-comment-ui/src/services/mobile/mobile-sheet-comment-draft.service.ts b/packages/sheets-thread-comment-ui/src/services/mobile/mobile-sheet-comment-draft.service.ts
new file mode 100644
index 0000000000..7f45d4765a
--- /dev/null
+++ b/packages/sheets-thread-comment-ui/src/services/mobile/mobile-sheet-comment-draft.service.ts
@@ -0,0 +1,49 @@
+/**
+ * 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 { Nullable } from '@univerjs/core';
+import { Disposable } from '@univerjs/core';
+import { BehaviorSubject } from 'rxjs';
+
+export interface IMobileSheetCommentDraft {
+ unitId: string;
+ subUnitId: string;
+ row: number;
+ column: number;
+}
+
+export class MobileSheetCommentDraftService extends Disposable {
+ private readonly _draft$ = new BehaviorSubject<Nullable<IMobileSheetCommentDraft>>(null);
+
+ readonly draft$ = this._draft$.asObservable();
+
+ constructor() {
+ super();
+ this.disposeWithMe(() => this._draft$.complete());
+ }
+
+ get draft(): Nullable<IMobileSheetCommentDraft> {
+ return this._draft$.getValue();
+ }
+
+ place(draft: IMobileSheetCommentDraft): void {
+ this._draft$.next(draft);
+ }
+
+ cancel(): void {
+ this._draft$.next(null);
+ }
+}
diff --git a/packages/sheets-thread-comment-ui/src/types/const.ts b/packages/sheets-thread-comment-ui/src/types/const.ts
index 8f4ee32b1b..db1f9f8309 100644
--- a/packages/sheets-thread-comment-ui/src/types/const.ts
+++ b/packages/sheets-thread-comment-ui/src/types/const.ts
@@ -16,5 +16,6 @@
export const SHEETS_THREAD_COMMENT_MODAL = 'univer.sheet.thread-comment-modal';
export const SHEETS_THREAD_COMMENT_PANEL = 'univer.sheet.thread-comment-panel';
+export const SHOW_ADD_SHEET_COMMENT_OPERATION_ID = 'sheet.operation.show-comment-modal';
export const PLUGIN_NAME = 'SHEET_THREAD_COMMENT_UI_PLUGIN';
diff --git a/packages/sheets-thread-comment-ui/src/views/SheetsThreadCommentPanel.tsx b/packages/sheets-thread-comment-ui/src/views/SheetsThreadCommentPanel.tsx
index 5b1be18e5a..e4e8fdc329 100644
--- a/packages/sheets-thread-comment-ui/src/views/SheetsThreadCommentPanel.tsx
+++ b/packages/sheets-thread-comment-ui/src/views/SheetsThreadCommentPanel.tsx
@@ -27,7 +27,13 @@ import { map } from 'rxjs';
import { ShowAddSheetCommentModalOperation } from '../commands/operations/comment.operation';
import { SheetsThreadCommentPopupService } from '../services/sheets-thread-comment-popup.service';
-export const SheetsThreadCommentPanel = () => {
+export interface ISheetsThreadCommentPanelProps {
+ ThreadCommentPanelComponent?: typeof ThreadCommentPanel;
+}
+
+export const SheetsThreadCommentPanel = ({
+ ThreadCommentPanelComponent = ThreadCommentPanel,
+}: ISheetsThreadCommentPanelProps = {}) => {
const markSelectionService = useDependency(IMarkSelectionService);
const univerInstanceService = useDependency(IUniverInstanceService);
const sheetsThreadCommentPopupService = useDependency(SheetsThreadCommentPopupService);
@@ -166,7 +172,7 @@ export const SheetsThreadCommentPanel = () => {
}, [markSelectionService, panelVisible]);
return (
- <ThreadCommentPanel
+ <ThreadCommentPanelComponent
unitId={unitId}
subUnitId$={subUnitId$}
type={UniverInstanceType.UNIVER_SHEET}
diff --git a/packages/sheets-thread-comment-ui/src/views/mobile/MobileSheetsThreadCommentPanel.tsx b/packages/sheets-thread-comment-ui/src/views/mobile/MobileSheetsThreadCommentPanel.tsx
new file mode 100644
index 0000000000..efd4a6c045
--- /dev/null
+++ b/packages/sheets-thread-comment-ui/src/views/mobile/MobileSheetsThreadCommentPanel.tsx
@@ -0,0 +1,59 @@
+/**
+ * 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 { IThreadComment } from '@univerjs/thread-comment';
+import type { IThreadCommentPanelProps } from '@univerjs/thread-comment-ui';
+import { Tools, UserManagerService } from '@univerjs/core';
+import { MobileThreadCommentPanel } from '@univerjs/thread-comment-ui';
+import { useDependency, useObservable } from '@univerjs/ui';
+import { MobileSheetCommentDraftService } from '../../services/mobile/mobile-sheet-comment-draft.service';
+import { SheetsThreadCommentPanel } from '../SheetsThreadCommentPanel';
+
+function MobileSheetsThreadCommentPanelContent(props: IThreadCommentPanelProps) {
+ const draftService = useDependency(MobileSheetCommentDraftService);
+ const userManagerService = useDependency(UserManagerService);
+ const draft = useObservable(draftService.draft$, draftService.draft);
+ const tempCellComment: IThreadComment | null = draft?.unitId === props.unitId
+ ? {
+ id: '',
+ threadId: '',
+ unitId: draft.unitId,
+ subUnitId: draft.subUnitId,
+ ref: `${Tools.chatAtABC(draft.column)}${draft.row + 1}`,
+ dT: '',
+ personId: userManagerService.getCurrentUser().userID,
+ text: { dataStream: '\r\n' },
+ }
+ : null;
+
+ const handleTempCommentClose = () => {
+ draftService.cancel();
+ props.onTempCommentClose?.();
+ };
+
+ return (
+ <MobileThreadCommentPanel
+ {...props}
+ tempComment={props.tempComment ?? tempCellComment}
+ onTempCommentClose={handleTempCommentClose}
+ autoFocusActiveComment
+ />
+ );
+}
+
+export function MobileSheetsThreadCommentPanel() {
+ return <SheetsThreadCommentPanel ThreadCommentPanelComponent={MobileSheetsThreadCommentPanelContent} />;
+}
diff --git a/packages/sheets-ui/src/consts/mobile-context.ts b/packages/sheets-ui/src/consts/mobile-context.ts
index 427fe017ec..5e8f001f3e 100644
--- a/packages/sheets-ui/src/consts/mobile-context.ts
+++ b/packages/sheets-ui/src/consts/mobile-context.ts
@@ -32,15 +32,15 @@ export const MOBILE_EXPANDING_SELECTION = 'MOBILE_EXPANDING_SELECTION';
*/
export const MOBILE_TRIGGER_CONTEXT_MENU = 'MOBILE_TRIGGER_CONTEXT_MENU';
-/** Mobile sheets edit through the formula bar while the in-cell editor stays hidden. */
-export const MOBILE_SHEET_FX_EDITOR = 'MOBILE_SHEET_FX_EDITOR';
-
/** Whether the software keyboard currently occupies the mobile visual viewport. */
export const MOBILE_KEYBOARD_VISIBLE = 'MOBILE_KEYBOARD_VISIBLE';
/** Whether the mobile formula editor currently occupies the immersive full-screen surface. */
export const MOBILE_FX_EDITOR_EXPANDED = 'MOBILE_FX_EDITOR_EXPANDED';
+/** Whether the mobile formula function panel is open above the formula editor. */
+export const MOBILE_FORMULA_FUNCTION_PANEL_OPEN = 'MOBILE_FORMULA_FUNCTION_PANEL_OPEN';
+
/** Whether the compact mobile formula operator strip is currently visible. */
export const MOBILE_FORMULA_OPERATORS_VISIBLE = 'MOBILE_FORMULA_OPERATORS_VISIBLE';
diff --git a/packages/sheets-ui/src/controllers/clipboard/clipboard-ui.controller.ts b/packages/sheets-ui/src/controllers/clipboard/clipboard-ui.controller.ts
new file mode 100644
index 0000000000..29dae80f14
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/clipboard/clipboard-ui.controller.ts
@@ -0,0 +1,39 @@
+/**
+ * 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 { IUniverSheetsUIConfig } from '../../config/config';
+import { Disposable, IConfigService, Inject, Injector } from '@univerjs/core';
+import { BuiltInUIPart, connectInjector, IUIPartsService } from '@univerjs/ui';
+import { SHEETS_UI_PLUGIN_CONFIG_KEY } from '../../config/config';
+import { ClipboardPopupMenu } from '../../views/clipboard/ClipboardPopupMenu';
+
+export class SheetClipboardUIController extends Disposable {
+ constructor(
+ @Inject(Injector) injector: Injector,
+ @IConfigService configService: IConfigService,
+ @IUIPartsService uiPartsService: IUIPartsService
+ ) {
+ super();
+
+ const config = configService.getConfig<IUniverSheetsUIConfig>(SHEETS_UI_PLUGIN_CONFIG_KEY);
+ if (!config?.clipboardConfig?.hidePasteOptions) {
+ this.disposeWithMe(uiPartsService.registerComponent(
+ BuiltInUIPart.CONTENT,
+ () => connectInjector(ClipboardPopupMenu, injector)
+ ));
+ }
+ }
+}
diff --git a/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts b/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts
index b1fbc2ea32..357dea4e2c 100644
--- a/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts
+++ b/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts
@@ -81,7 +81,7 @@ import {
SetWorksheetColWidthMutation,
SetWorksheetColWidthMutationFactory,
} from '@univerjs/sheets';
-import { BuiltInUIPart, connectInjector, IClipboardInterfaceService, IMessageService, IUIPartsService } from '@univerjs/ui';
+import { IClipboardInterfaceService, IMessageService } from '@univerjs/ui';
import { Subject, takeUntil } from 'rxjs';
import {
SheetCopyCommand,
@@ -104,7 +104,6 @@ import {
PREDEFINED_HOOK_NAME_PASTE,
} from '../../services/clipboard/clipboard.service';
import { SheetSkeletonManagerService } from '../../services/sheet-skeleton-manager.service';
-import { ClipboardPopupMenu } from '../../views/clipboard/ClipboardPopupMenu';
import { whenSheetEditorFocused } from '../shortcuts/utils';
import { RemovePasteMenuCommands } from './const';
import {
@@ -144,13 +143,11 @@ export class SheetClipboardController extends RxDisposable {
@ISheetClipboardService private readonly _sheetClipboardService: ISheetClipboardService,
@IClipboardInterfaceService private readonly _clipboardInterfaceService: IClipboardInterfaceService,
@IMessageService private readonly _messageService: IMessageService,
- @Inject(LocaleService) private readonly _localService: LocaleService,
- @IUIPartsService protected readonly _uiPartsService: IUIPartsService
+ @Inject(LocaleService) private readonly _localService: LocaleService
) {
super();
this._init();
this._initCommandListener();
- this._initUIComponents();
this._pasteWithDoc();
}
@@ -887,15 +884,4 @@ export class SheetClipboardController extends RxDisposable {
})
);
}
-
- private _initUIComponents() {
- const sheetsUIConfig = this._configService.getConfig<IUniverSheetsUIConfig>(SHEETS_UI_PLUGIN_CONFIG_KEY);
- if (sheetsUIConfig?.clipboardConfig?.hidePasteOptions) {
- return;
- }
-
- this.disposeWithMe(
- this._uiPartsService.registerComponent(BuiltInUIPart.CONTENT, () => connectInjector(ClipboardPopupMenu, this._injector))
- );
- }
}
diff --git a/packages/sheets-ui/src/controllers/components.controller.ts b/packages/sheets-ui/src/controllers/components.controller.ts
index 2931383301..89a168dc12 100644
--- a/packages/sheets-ui/src/controllers/components.controller.ts
+++ b/packages/sheets-ui/src/controllers/components.controller.ts
@@ -16,91 +16,6 @@
import type { IUniverSheetsUIConfig } from '../config/config';
import { Disposable, IConfigService, Inject, Injector } from '@univerjs/core';
-import {
- AddImageIcon,
- AdjustHeightDoubleIcon,
- AdjustWidthDoubleIcon,
- AlignBottomIcon,
- AlignTopIcon,
- AllBorderIcon,
- AutoHeightDoubleIcon,
- AutoWidthDoubleIcon,
- AutowrapIcon,
- BackSlashDoubleIcon,
- BoldIcon,
- BrushIcon,
- CancelFreezeIcon,
- CancelMergeIcon,
- CheckMarkIcon,
- ClearFormatDoubleIcon,
- CodeIcon,
- ConvertToNumberIcon,
- CopyDoubleIcon,
- CutIcon,
- DeleteCellShiftLeftDoubleIcon,
- DeleteCellShiftUpDoubleIcon,
- DeleteColumnDoubleIcon,
- DeleteIcon,
- DeleteRowDoubleIcon,
- DownBorderDoubleIcon,
- DownloadImageIcon,
- EyeIcon,
- FontColorDoubleIcon,
- FontSizeIncreaseIcon,
- FontSizeReduceIcon,
- FreezeColumnIcon,
- FreezeRowIcon,
- FreezeToSelectedIcon,
- HideDoubleIcon,
- HideGridlinesIcon,
- HorizontalBorderDoubleIcon,
- HorizontallyIcon,
- HorizontalMergeIcon,
- InnerBorderDoubleIcon,
- InsertCellDownDoubleIcon,
- InsertCellShiftRightDoubleIcon,
- InsertDoubleIcon,
- InsertRowAboveDoubleIcon,
- InsertRowBelowDoubleIcon,
- ItalicIcon,
- LeftBorderDoubleIcon,
- LeftDoubleDiagonalDoubleIcon,
- LeftInsertColumnDoubleIcon,
- LeftJustifyingIcon,
- LeftRotationFortyFiveDegreesIcon,
- LeftRotationNinetyDegreesIcon,
- LeftTridiagonalDoubleIcon,
- LockIcon,
- MergeAllIcon,
- NoBorderIcon,
- NoColorDoubleIcon,
- NoRotationIcon,
- OuterBorderDoubleIcon,
- OverflowIcon,
- PaintBucketDoubleIcon,
- PasteSpecialDoubleIcon,
- ProtectIcon,
- ReduceDoubleIcon,
- RightBorderDoubleIcon,
- RightDoubleDiagonalDoubleIcon,
- RightInsertColumnDoubleIcon,
- RightJustifyingIcon,
- RightRotationFortyFiveDegreesIcon,
- RightRotationNinetyDegreesIcon,
- ShrinkToFitIcon,
- SlashDoubleIcon,
- StrikethroughIcon,
- SubscriptIcon,
- SuperscriptIcon,
- TruncationIcon,
- UnderlineIcon,
- UpBorderDoubleIcon,
- VerticalBorderDoubleIcon,
- VerticalCenterIcon,
- VerticalIntegrationIcon,
- VerticalTextIcon,
- WriteIcon,
-} from '@univerjs/icons';
import { ComponentManager, IconManager } from '@univerjs/ui';
import { SHEETS_UI_PLUGIN_CONFIG_KEY } from '../config/config';
import {
@@ -124,6 +39,7 @@ import { SheetPermissionDialog, SheetPermissionPanel, SheetPermissionUserDialog
import { AlertDialog } from '../views/permission/AlertDialog';
import { UNIVER_SHEET_PERMISSION_ALERT_DIALOG } from '../views/permission/error-msg-dialog/interface';
import { SHEET_ZOOM_INPUT_COMPONENT, SheetZoomInput } from '../views/sheet-slider/SheetZoomInput';
+import { sheetsUIIcons } from './sheets-ui-icons';
export class ComponentsController extends Disposable {
constructor(
@@ -183,97 +99,7 @@ export class ComponentsController extends Disposable {
});
}
- // eslint-disable-next-line max-lines-per-function
private _registerIcons(): void {
- this.disposeWithMe(this._iconManager.register({
- ProtectIcon,
- DeleteIcon,
- WriteIcon,
- CheckMarkIcon,
- LockIcon,
- }));
-
- this.disposeWithMe(this._iconManager.register({
- AdjustHeightDoubleIcon,
- AdjustWidthDoubleIcon,
- AddImageIcon,
- AlignBottomIcon,
- AlignTopIcon,
- AllBorderIcon,
- AutoHeightDoubleIcon,
- AutoWidthDoubleIcon,
- AutowrapIcon,
- BackSlashDoubleIcon,
- BoldIcon,
- BrushIcon,
- CancelFreezeIcon,
- CancelMergeIcon,
- ClearFormatDoubleIcon,
- CodeIcon,
- ConvertToNumberIcon,
- CopyDoubleIcon,
- CutIcon,
- DeleteCellShiftLeftDoubleIcon,
- DeleteCellShiftUpDoubleIcon,
- DeleteColumnDoubleIcon,
- DeleteRowDoubleIcon,
- DownBorderDoubleIcon,
- DownloadImageIcon,
- EyeIcon,
- FontColorDoubleIcon,
- FontSizeIncreaseIcon,
- FontSizeReduceIcon,
- FreezeColumnIcon,
- FreezeRowIcon,
- FreezeToSelectedIcon,
- HideDoubleIcon,
- HideGridlinesIcon,
- HorizontalBorderDoubleIcon,
- HorizontalMergeIcon,
- HorizontallyIcon,
- InnerBorderDoubleIcon,
- InsertCellDownDoubleIcon,
- InsertCellShiftRightDoubleIcon,
- InsertDoubleIcon,
- InsertRowAboveDoubleIcon,
- InsertRowBelowDoubleIcon,
- ItalicIcon,
- LeftBorderDoubleIcon,
- LeftDoubleDiagonalDoubleIcon,
- LeftInsertColumnDoubleIcon,
- LeftJustifyingIcon,
- LeftRotationFortyFiveDegreesIcon,
- LeftRotationNinetyDegreesIcon,
- LeftTridiagonalDoubleIcon,
- LockIcon,
- MergeAllIcon,
- NoBorderIcon,
- NoColorDoubleIcon,
- NoRotationIcon,
- OuterBorderDoubleIcon,
- OverflowIcon,
- PaintBucketDoubleIcon,
- PasteSpecialDoubleIcon,
- ProtectIcon,
- ReduceDoubleIcon,
- RightBorderDoubleIcon,
- RightDoubleDiagonalDoubleIcon,
- RightInsertColumnDoubleIcon,
- RightJustifyingIcon,
- RightRotationFortyFiveDegreesIcon,
- RightRotationNinetyDegreesIcon,
- ShrinkToFitIcon,
- SlashDoubleIcon,
- StrikethroughIcon,
- SubscriptIcon,
- SuperscriptIcon,
- TruncationIcon,
- UnderlineIcon,
- UpBorderDoubleIcon,
- VerticalBorderDoubleIcon,
- VerticalCenterIcon,
- VerticalIntegrationIcon,
- VerticalTextIcon,
- }));
+ this.disposeWithMe(this._iconManager.register(sheetsUIIcons));
}
}
diff --git a/packages/sheets-ui/src/controllers/editor/__tests__/data-sync.controller.spec.ts b/packages/sheets-ui/src/controllers/editor/__tests__/data-sync.controller.spec.ts
index 4aa6e7a8a6..b6ed21180c 100644
--- a/packages/sheets-ui/src/controllers/editor/__tests__/data-sync.controller.spec.ts
+++ b/packages/sheets-ui/src/controllers/editor/__tests__/data-sync.controller.spec.ts
@@ -14,11 +14,12 @@
* limitations under the License.
*/
-import type { DocumentDataModel, ICommandInfo, IDocumentData } from '@univerjs/core';
+import type { ICommandInfo, IDocumentBody, IDocumentData, IDrawings, Nullable } from '@univerjs/core';
import {
BooleanNumber,
DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ DocumentDataModel,
FOCUSING_FX_BAR_EDITOR,
ICommandService,
IContextService,
@@ -35,7 +36,6 @@ import {
} from '@univerjs/sheets';
import { BehaviorSubject, EMPTY } from 'rxjs';
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { MOBILE_SHEET_FX_EDITOR } from '../../../consts/mobile-context';
import { IEditorBridgeService } from '../../../services/editor-bridge.service';
import { IFormulaEditorManagerService } from '../../../services/editor/formula-editor-manager.service';
import { EditorDataSyncController } from '../data-sync.controller';
@@ -43,6 +43,12 @@ import { FormulaEditorController } from '../formula-editor.controller';
interface ITestableEditorDataSyncController {
_checkAndSetRenderStyleConfig: (documentDataModel: Pick<DocumentDataModel, 'getSnapshot'>) => void;
+ _syncContentAndRender: (
+ unitId: string,
+ body: IDocumentBody,
+ drawings: Nullable<IDrawings>,
+ drawingsOrder: Nullable<string[]>
+ ) => void;
}
class TestCommandService {
@@ -70,9 +76,9 @@ describe('EditorDataSyncController', () => {
function createController(options: {
isFocusFxBar?: boolean;
- mobile?: boolean;
themeTextColor?: string;
formulaBarPosition?: { width: number; height: number } | null;
+ documentDataModel?: DocumentDataModel;
} = {}) {
const commandService = new TestCommandService();
const editorBridgeService = {
@@ -87,16 +93,28 @@ describe('EditorDataSyncController', () => {
const contextService = {
getContextValue: vi.fn((key: string) => {
if (key === FOCUSING_FX_BAR_EDITOR) return options.isFocusFxBar ?? false;
- if (key === MOBILE_SHEET_FX_EDITOR) return options.mobile ?? false;
return false;
}),
subscribeContextValue$: vi.fn(() => EMPTY),
};
const currentTheme$ = new BehaviorSubject({});
+ const skeleton = { calculate: vi.fn() };
+ const documentViewModel = { reset: vi.fn() };
+ const currentRender = {
+ mainComponent: { makeDirty: vi.fn() },
+ with: vi.fn(() => ({
+ getSkeleton: () => skeleton,
+ getViewModel: () => documentViewModel,
+ })),
+ };
const injector = new Injector();
- injector.add([IUniverInstanceService, { useValue: {} as never }]);
- injector.add([IRenderManagerService, { useValue: {} as never }]);
+ injector.add([IUniverInstanceService, {
+ useValue: { getUnit: () => options.documentDataModel } as never,
+ }]);
+ injector.add([IRenderManagerService, {
+ useValue: { getRenderUnitById: () => options.documentDataModel ? currentRender : undefined } as never,
+ }]);
injector.add([IEditorBridgeService, { useValue: editorBridgeService as never }]);
injector.add([ICommandService, { useValue: commandService as never }]);
injector.add([RangeProtectionRuleModel, { useValue: { getRangeRuleInitState: () => true } as never }]);
@@ -133,6 +151,14 @@ describe('EditorDataSyncController', () => {
});
}
+ function syncContentAndRender(
+ controller: EditorDataSyncController,
+ body: IDocumentBody
+ ) {
+ const testableController = controller as unknown as ITestableEditorDataSyncController;
+ testableController._syncContentAndRender(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, body, null, null);
+ }
+
it('ignores a zero-width formula bar position', () => {
const { controller } = createController({ formulaBarPosition: { width: 0, height: 28 } });
const formulaBarSnapshot: IDocumentData = {
@@ -181,6 +207,29 @@ describe('EditorDataSyncController', () => {
expect(formulaBarSnapshot.documentStyle.pageSize?.width).toBe(320);
});
+ it('notifies formula bar content observers when the selected cell changes', () => {
+ const documentDataModel = new DocumentDataModel({
+ id: DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
+ documentStyle: {},
+ body: {
+ dataStream: '=SUM(A1)\r\n',
+ },
+ });
+ const { controller } = createController({ documentDataModel });
+ let observedDataStream = '';
+ const subscription = documentDataModel.change$.subscribe(() => {
+ observedDataStream = documentDataModel.getBody()?.dataStream ?? '';
+ });
+
+ syncContentAndRender(controller, { dataStream: '\r\n' });
+
+ expect(documentDataModel.getBody()?.dataStream).toBe('\r\n');
+ expect(observedDataStream).toBe('\r\n');
+
+ subscription.unsubscribe();
+ documentDataModel.dispose();
+ });
+
it('refreshes the current edit cell when set-values updates the edited cell', () => {
const { commandService, editorBridgeService } = createController();
@@ -284,30 +333,6 @@ describe('EditorDataSyncController', () => {
expect(formulaBarSnapshot.documentStyle.textStyle?.cl?.rgb).toBe('#f7f9fc');
});
- it('renders source rich-text styles in the mobile formula bar without changing the desktop behavior', () => {
- const desktop = createController().controller;
- const mobile = createController({ mobile: true }).controller;
- const createSnapshot = (): IDocumentData => ({
- id: DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
- body: {
- dataStream: 'Rich text\r\n',
- textRuns: [{ st: 0, ed: 4, ts: { bl: BooleanNumber.TRUE, cl: { rgb: '#ef4444' } } }],
- },
- documentStyle: {},
- });
- const desktopSnapshot = createSnapshot();
- const mobileSnapshot = createSnapshot();
-
- checkAndSetRenderStyleConfig(desktop, desktopSnapshot);
- checkAndSetRenderStyleConfig(mobile, mobileSnapshot);
-
- expect(desktopSnapshot.documentStyle.renderConfig?.isRenderStyle).toBe(BooleanNumber.FALSE);
- expect(mobileSnapshot.documentStyle.renderConfig?.isRenderStyle).toBe(BooleanNumber.TRUE);
- expect(mobileSnapshot.body?.textRuns).toEqual([
- { st: 0, ed: 4, ts: { bl: BooleanNumber.TRUE, cl: { rgb: '#ef4444' } } },
- ]);
- });
-
it('renders formula reference styles in the formula bar when the formula bar is focused', () => {
const { controller } = createController({ isFocusFxBar: true });
const cellEditorSnapshot: IDocumentData = {
diff --git a/packages/sheets-ui/src/controllers/editor/data-sync.controller.ts b/packages/sheets-ui/src/controllers/editor/data-sync.controller.ts
index fe87c7562a..f8294fddee 100644
--- a/packages/sheets-ui/src/controllers/editor/data-sync.controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/data-sync.controller.ts
@@ -43,7 +43,6 @@ import { ReplaceSnapshotCommand } from '@univerjs/docs-ui';
import { DeviceInputEventType, IRenderManagerService } from '@univerjs/engine-render';
import { MoveRangeMutation, RangeProtectionRuleModel, SetRangeValuesMutation, WorksheetProtectionRuleModel } from '@univerjs/sheets';
import { skip } from 'rxjs';
-import { MOBILE_SHEET_FX_EDITOR } from '../../consts/mobile-context';
import { IEditorBridgeService } from '../../services/editor-bridge.service';
import { IFormulaEditorManagerService } from '../../services/editor/formula-editor-manager.service';
import { FormulaEditorController } from './formula-editor.controller';
@@ -279,9 +278,12 @@ export class EditorDataSyncController extends Disposable {
return;
}
- docDataModel.getSnapshot().body = body;
- docDataModel.getSnapshot().drawings = drawings ?? {};
- docDataModel.getSnapshot().drawingsOrder = drawingsOrder ?? [];
+ docDataModel.reset({
+ ...docDataModel.getSnapshot(),
+ body,
+ drawings: drawings ?? {},
+ drawingsOrder: drawingsOrder ?? [],
+ });
this._checkAndSetRenderStyleConfig(docDataModel);
docViewModel.reset(docDataModel);
@@ -377,10 +379,7 @@ export class EditorDataSyncController extends Disposable {
const isFormula = (snapshot.body?.dataStream ?? '').startsWith('=');
if (!isFormula) {
- renderConfig.isRenderStyle = shouldRenderSourceStyle(
- isFormulaBar,
- this._contextService.getContextValue(MOBILE_SHEET_FX_EDITOR)
- );
+ renderConfig.isRenderStyle = this._getSourceStyleRenderValue(isFormulaBar);
return;
}
@@ -388,6 +387,10 @@ export class EditorDataSyncController extends Disposable {
renderConfig.isRenderStyle = isFormulaBar === isFocusFxBar ? BooleanNumber.TRUE : BooleanNumber.FALSE;
}
+ protected _getSourceStyleRenderValue(isFormulaBar: boolean): BooleanNumber {
+ return isFormulaBar ? BooleanNumber.FALSE : BooleanNumber.TRUE;
+ }
+
private _clearParagraph(paragraphs: IParagraph[]) {
const newParagraphs = Tools.deepClone(paragraphs);
for (const paragraph of newParagraphs) {
@@ -399,7 +402,3 @@ export class EditorDataSyncController extends Disposable {
return newParagraphs;
}
}
-
-function shouldRenderSourceStyle(isFormulaBar: boolean, mobile: boolean): BooleanNumber {
- return isFormulaBar && !mobile ? BooleanNumber.FALSE : BooleanNumber.TRUE;
-}
diff --git a/packages/sheets-ui/src/controllers/mobile/clipboard-ui.controller.ts b/packages/sheets-ui/src/controllers/mobile/clipboard-ui.controller.ts
new file mode 100644
index 0000000000..e3482c37d2
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/mobile/clipboard-ui.controller.ts
@@ -0,0 +1,39 @@
+/**
+ * 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 { IUniverSheetsUIConfig } from '../../config/config';
+import { Disposable, IConfigService, Inject, Injector } from '@univerjs/core';
+import { BuiltInUIPart, connectInjector, IUIPartsService } from '@univerjs/ui';
+import { SHEETS_UI_PLUGIN_CONFIG_KEY } from '../../config/config';
+import { MobileClipboardPopupMenu } from '../../views/mobile/clipboard/MobileClipboardPopupMenu';
+
+export class SheetClipboardMobileUIController extends Disposable {
+ constructor(
+ @Inject(Injector) injector: Injector,
+ @IConfigService configService: IConfigService,
+ @IUIPartsService uiPartsService: IUIPartsService
+ ) {
+ super();
+
+ const config = configService.getConfig<IUniverSheetsUIConfig>(SHEETS_UI_PLUGIN_CONFIG_KEY);
+ if (!config?.clipboardConfig?.hidePasteOptions) {
+ this.disposeWithMe(uiPartsService.registerComponent(
+ BuiltInUIPart.CONTENT,
+ () => connectInjector(MobileClipboardPopupMenu, injector)
+ ));
+ }
+ }
+}
diff --git a/packages/sheets-ui/src/controllers/mobile/components.controller.ts b/packages/sheets-ui/src/controllers/mobile/components.controller.ts
new file mode 100644
index 0000000000..4c83b0610a
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/mobile/components.controller.ts
@@ -0,0 +1,90 @@
+/**
+ * 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 { IUniverSheetsUIConfig } from '../../config/config';
+import { Disposable, IConfigService, Inject, Injector } from '@univerjs/core';
+import { ComponentManager, IconManager } from '@univerjs/ui';
+import { EMBEDDING_CELL_EDITOR_COMPONENT_KEY } from '../../common/keys';
+import { SHEETS_UI_PLUGIN_CONFIG_KEY } from '../../config/config';
+import {
+ UNIVER_SHEET_PERMISSION_DIALOG,
+ UNIVER_SHEET_PERMISSION_PANEL,
+ UNIVER_SHEET_PERMISSION_USER_DIALOG,
+ UNIVER_SHEET_PERMISSION_USER_PART,
+} from '../../consts/permission';
+import { BORDER_PANEL_COMPONENT } from '../../views/border-panel/interface';
+import { CELL_ALERT_KEY } from '../../views/cell-alert';
+import { CELL_POPUP_COMPONENT_KEY } from '../../views/cell-popup/config';
+import { CellPopup } from '../../views/CellPopup';
+import { DEFINED_NAME_CONTAINER } from '../../views/defined-name/component-name';
+import { CascaderDropdown } from '../../views/dropdown/CascaderDropdown';
+import { DateDropdown } from '../../views/dropdown/DateDropdown';
+import { ListDropDown } from '../../views/dropdown/ListDropDown';
+import { MENU_ITEM_FROZEN_COMPONENT, MenuItemFrozen } from '../../views/menu-item-frozen';
+import { MENU_ITEM_INPUT_COMPONENT } from '../../views/menu-item-input';
+import { MobileBorderPanel } from '../../views/mobile/border-panel/MobileBorderPanel';
+import { MobileCellAlert } from '../../views/mobile/cell-alert/MobileCellAlert';
+import { MobileDefinedNameContainer } from '../../views/mobile/defined-name/MobileDefinedNameContainer';
+import { MobileColorDropdown } from '../../views/mobile/dropdown/MobileColorDropdown';
+import { MobileEditorContainer } from '../../views/mobile/editor-container/MobileEditorContainer';
+import { MobileMenuItemInput } from '../../views/mobile/menu-item-input/MobileMenuItemInput';
+import { MobileSheetPermissionDialog } from '../../views/mobile/permission/MobileSheetPermissionDialog';
+import { MobileSheetPermissionPanel } from '../../views/mobile/permission/MobileSheetPermissionPanel';
+import { MobileSheetPermissionUserDialog } from '../../views/mobile/permission/MobileSheetPermissionUserDialog';
+import { AlertDialog } from '../../views/permission/AlertDialog';
+import { UNIVER_SHEET_PERMISSION_ALERT_DIALOG } from '../../views/permission/error-msg-dialog/interface';
+import { SHEET_ZOOM_INPUT_COMPONENT, SheetZoomInput } from '../../views/sheet-slider/SheetZoomInput';
+import { sheetsUIIcons } from '../sheets-ui-icons';
+
+export class MobileComponentsController extends Disposable {
+ constructor(
+ @Inject(ComponentManager) componentManager: ComponentManager,
+ @Inject(IconManager) iconManager: IconManager,
+ @Inject(Injector) injector: Injector
+ ) {
+ super();
+
+ this.disposeWithMe(componentManager.register(
+ EMBEDDING_CELL_EDITOR_COMPONENT_KEY,
+ MobileEditorContainer
+ ));
+ this.disposeWithMe(componentManager.register(CELL_ALERT_KEY, MobileCellAlert));
+ this.disposeWithMe(componentManager.register(MobileColorDropdown.componentKey, MobileColorDropdown));
+ this.disposeWithMe(componentManager.register(DateDropdown.componentKey, DateDropdown));
+ this.disposeWithMe(componentManager.register(ListDropDown.componentKey, ListDropDown));
+ this.disposeWithMe(componentManager.register(CascaderDropdown.componentKey, CascaderDropdown));
+ this.disposeWithMe(componentManager.register(MENU_ITEM_INPUT_COMPONENT, MobileMenuItemInput));
+ this.disposeWithMe(componentManager.register(MENU_ITEM_FROZEN_COMPONENT, MenuItemFrozen));
+ this.disposeWithMe(componentManager.register(SHEET_ZOOM_INPUT_COMPONENT, SheetZoomInput));
+ this.disposeWithMe(componentManager.register(BORDER_PANEL_COMPONENT, MobileBorderPanel));
+ this.disposeWithMe(componentManager.register(DEFINED_NAME_CONTAINER, MobileDefinedNameContainer));
+ this.disposeWithMe(componentManager.register(CELL_POPUP_COMPONENT_KEY, CellPopup));
+ this.disposeWithMe(componentManager.register(UNIVER_SHEET_PERMISSION_PANEL, MobileSheetPermissionPanel));
+ this.disposeWithMe(componentManager.register(UNIVER_SHEET_PERMISSION_DIALOG, MobileSheetPermissionDialog));
+ this.disposeWithMe(componentManager.register(
+ UNIVER_SHEET_PERMISSION_USER_DIALOG,
+ MobileSheetPermissionUserDialog
+ ));
+ this.disposeWithMe(componentManager.register(UNIVER_SHEET_PERMISSION_ALERT_DIALOG, AlertDialog));
+
+ const config = injector.get(IConfigService).getConfig<IUniverSheetsUIConfig>(SHEETS_UI_PLUGIN_CONFIG_KEY);
+ if (config?.protectedRangeUserSelector) {
+ const { component, framework } = config.protectedRangeUserSelector;
+ this.disposeWithMe(componentManager.register(UNIVER_SHEET_PERMISSION_USER_PART, component, { framework }));
+ }
+ this.disposeWithMe(iconManager.register(sheetsUIIcons));
+ }
+}
diff --git a/packages/sheets-ui/src/controllers/mobile/editor-data-sync.controller.ts b/packages/sheets-ui/src/controllers/mobile/editor-data-sync.controller.ts
new file mode 100644
index 0000000000..8dd487d9dd
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/mobile/editor-data-sync.controller.ts
@@ -0,0 +1,24 @@
+/**
+ * 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 { BooleanNumber } from '@univerjs/core';
+import { EditorDataSyncController } from '../editor/data-sync.controller';
+
+export class MobileEditorDataSyncController extends EditorDataSyncController {
+ protected override _getSourceStyleRenderValue(): BooleanNumber {
+ return BooleanNumber.TRUE;
+ }
+}
diff --git a/packages/sheets-ui/src/controllers/mobile/ui-mobile.controller.ts b/packages/sheets-ui/src/controllers/mobile/ui-mobile.controller.ts
index ef2cac938a..86a593ea8e 100644
--- a/packages/sheets-ui/src/controllers/mobile/ui-mobile.controller.ts
+++ b/packages/sheets-ui/src/controllers/mobile/ui-mobile.controller.ts
@@ -111,16 +111,16 @@ import { SheetPermissionOpenPanelOperation } from '../../commands/operations/she
import { SidebarDefinedNameOperation } from '../../commands/operations/sidebar-defined-name.operation';
import {
MOBILE_FORMULA_BAR_SUBMIT_COMMAND_ID,
+ MOBILE_FORMULA_FUNCTION_PANEL_OPEN,
MOBILE_FX_EDITOR_EXPANDED,
MOBILE_KEYBOARD_VISIBLE,
- MOBILE_SHEET_FX_EDITOR,
} from '../../consts/mobile-context';
import { menuSchema } from '../../menu/schema';
import { IEditorBridgeService } from '../../services/editor-bridge.service';
import { MobileSheetActionPanel } from '../../views/mobile/action-panel/MobileSheetActionPanel';
import { MobileFormulaBar } from '../../views/mobile/formula-bar/MobileFormulaBar';
import { MobileSheetBar } from '../../views/mobile/sheet-bar/MobileSheetBar';
-import { RenderSheetContent } from '../../views/sheet-container/SheetContainer';
+import { MobileRenderSheetContent } from '../../views/mobile/sheet-container/MobileRenderSheetContent';
import { EditingRenderController } from '../editor/editing.render-controller';
export const MobileFormulaBarBreakLineCommand: ICommand = {
@@ -212,7 +212,6 @@ export class SheetUIMobileController extends Disposable {
) {
super();
- this._contextService.setContextValue(MOBILE_SHEET_FX_EDITOR, true);
this._init();
}
@@ -314,7 +313,7 @@ export class SheetUIMobileController extends Disposable {
const injector = this._injector;
this.disposeWithMe(uiController.registerComponent(BuiltInUIPart.HEADER, () => connectInjector(MobileSheetBar, injector)));
- this.disposeWithMe(uiController.registerComponent(BuiltInUIPart.CONTENT, () => connectInjector(RenderSheetContent, injector)));
+ this.disposeWithMe(uiController.registerComponent(BuiltInUIPart.CONTENT, () => connectInjector(MobileRenderSheetContent, injector)));
this.disposeWithMe(uiController.registerComponent(BuiltInUIPart.FOOTER, () => connectInjector(MobileFormulaBar, injector)));
this.disposeWithMe(uiController.registerComponent(BuiltInUIPart.FOOTER, () => connectInjector(MobileSheetActionPanel, injector)));
}
@@ -363,11 +362,13 @@ export class SheetUIMobileController extends Disposable {
const keyboardVisible = isMobileKeyboardVisible(stableHeight, visibleBottom);
this._contextService.setContextValue(MOBILE_KEYBOARD_VISIBLE, keyboardVisible);
- if (
+ if (shouldHideMobileEditorOnKeyboardClose(
keyboardWasVisible &&
- !keyboardVisible &&
- !this._contextService.getContextValue(MOBILE_FX_EDITOR_EXPANDED)
- ) {
+ !keyboardVisible,
+ this._contextService.getContextValue(MOBILE_FX_EDITOR_EXPANDED),
+ this._contextService.getContextValue(MOBILE_FORMULA_FUNCTION_PANEL_OPEN),
+ this._editorBridgeService.isForceKeepVisible()
+ )) {
const visibleState = this._editorBridgeService.isVisible();
if (visibleState.visible) {
this._commandService.executeCommand(SetCellEditVisibleOperation.id, {
@@ -425,3 +426,12 @@ export class SheetUIMobileController extends Disposable {
export function isMobileKeyboardVisible(stableHeight: number, visibleBottom: number): boolean {
return stableHeight - visibleBottom > 80;
}
+
+export function shouldHideMobileEditorOnKeyboardClose(
+ keyboardClosed: boolean,
+ editorExpanded: boolean,
+ functionPanelOpen: boolean,
+ forceKeepVisible: boolean
+): boolean {
+ return keyboardClosed && !editorExpanded && !functionPanelOpen && !forceKeepVisible;
+}
diff --git a/packages/sheets-ui/src/controllers/permission/__tests__/sheet-permission-check-ui.controller.spec.ts b/packages/sheets-ui/src/controllers/permission/__tests__/sheet-permission-check-ui.controller.spec.ts
index ec65b558c2..f1d8d7ab41 100644
--- a/packages/sheets-ui/src/controllers/permission/__tests__/sheet-permission-check-ui.controller.spec.ts
+++ b/packages/sheets-ui/src/controllers/permission/__tests__/sheet-permission-check-ui.controller.spec.ts
@@ -96,6 +96,21 @@ describe('SheetPermissionCheckUIController', () => {
controller.dispose();
});
+ it.each([
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
+ ])('checks the current workbook when visibility is requested by internal sheet editor %s', (unitId) => {
+ const { controller, executeBefore, permissionCheckWithoutRange } = createController();
+
+ executeBefore({
+ id: SetCellEditVisibleOperation.id,
+ params: { visible: true, unitId },
+ });
+
+ expect(permissionCheckWithoutRange).toHaveBeenCalledWith(expect.any(Object), undefined);
+ controller.dispose();
+ });
+
it.each([
[InsertTextCommand.id, DOCS_NORMAL_EDITOR_UNIT_ID_KEY],
[IMEInputCommand.id, DOCS_NORMAL_EDITOR_UNIT_ID_KEY],
diff --git a/packages/sheets-ui/src/controllers/permission/sheet-permission-check-ui.controller.ts b/packages/sheets-ui/src/controllers/permission/sheet-permission-check-ui.controller.ts
index 1820d98c90..58fb8b675b 100644
--- a/packages/sheets-ui/src/controllers/permission/sheet-permission-check-ui.controller.ts
+++ b/packages/sheets-ui/src/controllers/permission/sheet-permission-check-ui.controller.ts
@@ -138,7 +138,7 @@ export class SheetPermissionCheckUIController extends Disposable {
workbookTypes: [WorkbookEditablePermission],
worksheetTypes: [WorksheetSetCellValuePermission, WorksheetEditPermission],
rangeTypes: [RangeProtectionPermissionEditPoint],
- }, params.unitId);
+ }, SHEET_EDITOR_UNITS.includes(params.unitId) ? undefined : params.unitId);
errorMsg = this._localeService.t<LocaleKey>('sheets-ui.permission.dialog.editErr');
break;
case ApplyFormatPainterCommand.id:
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 a92ef7c306..9403816c78 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
@@ -28,7 +28,6 @@ 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 { MOBILE_KEYBOARD_VISIBLE } from '../../../consts/mobile-context';
import { EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE } from '../../../services/sheet-embed-integration.service';
import { EditorBridgeRenderController } from '../editor-bridge.render-controller';
@@ -75,7 +74,6 @@ function createController(options?: {
isEmbedActiveSession?: boolean;
focusingSheet?: boolean;
disableAutoFocus?: boolean;
- keyboardVisible?: boolean;
isEmbedRuntimeEventImpl?: (unitId: string | undefined, target?: EventTarget | null, event?: Event) => boolean;
}) {
const workbook$ = new Subject<any>();
@@ -105,7 +103,6 @@ function createController(options?: {
[FOCUSING_SHEET, options?.focusingSheet ?? true],
[FOCUSING_FX_BAR_EDITOR, false],
[DISABLE_AUTO_FOCUS_KEY, options?.disableAutoFocus ?? false],
- [MOBILE_KEYBOARD_VISIBLE, options?.keyboardVisible ?? false],
]);
const focusingSheet$ = new Subject<boolean>();
const context = {
@@ -134,7 +131,7 @@ function createController(options?: {
}
: null),
};
- let editorVisible = options?.editorVisible ?? false;
+ const editorVisible = options?.editorVisible ?? false;
const editorBridgeService = {
getEditCellState: vi.fn(() => options?.currentEditCellState ?? null),
getEditCellLayout: vi.fn(() => ({
@@ -146,16 +143,7 @@ function createController(options?: {
isForceKeepVisible: vi.fn(() => options?.forceKeepVisible ?? false),
refreshEditCellState: vi.fn(),
};
- commandService.syncExecuteCommand.mockImplementation((commandId: string, params?: { visible?: boolean }) => {
- if (
- options?.keyboardVisible &&
- commandId === SetCellEditVisibleOperation.id &&
- typeof params?.visible === 'boolean'
- ) {
- editorVisible = params.visible;
- }
- return true;
- });
+ commandService.syncExecuteCommand.mockReturnValue(true);
const controller = new EditorBridgeRenderController(
context as any,
{
@@ -368,41 +356,6 @@ describe('EditorBridgeRenderController business flows', () => {
controller.dispose();
});
- it('commits and reopens editing on the selected cell while the mobile keyboard stays visible', () => {
- const { commandService, controller, selectionMoveEnd$, spreadsheet } = createController({
- editorVisible: true,
- keyboardVisible: true,
- });
-
- spreadsheet.onPointerDown$.emit({});
- expect(commandService.syncExecuteCommand).not.toHaveBeenCalled();
-
- selectionMoveEnd$.next([{
- primary: {
- actualRow: 3,
- actualColumn: 4,
- startRow: 3,
- startColumn: 4,
- endRow: 3,
- endColumn: 4,
- },
- }]);
-
- expect(commandService.syncExecuteCommand).toHaveBeenNthCalledWith(1, SetCellEditVisibleOperation.id, {
- visible: false,
- eventType: DeviceInputEventType.PointerDown,
- unitId: 'unit-1',
- });
- expect(commandService.executeCommand).toHaveBeenCalledWith(SetActivateCellEditOperation.id, expect.anything());
- expect(commandService.syncExecuteCommand).toHaveBeenNthCalledWith(2, SetCellEditVisibleOperation.id, {
- visible: true,
- eventType: DeviceInputEventType.PointerDown,
- unitId: 'unit-1',
- });
-
- controller.dispose();
- });
-
it('opens sheet editing from keyboard input while the sheet is an active embed child session', () => {
const { commandService, controller, inputBefore$ } = createController({
focusingSheet: false,
diff --git a/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts
index 777e62a6e7..b9a1186f08 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
@@ -34,7 +34,6 @@ import { filter, merge } from 'rxjs';
import { SetZoomRatioCommand } from '../../commands/commands/set-zoom-ratio.command';
import { SetActivateCellEditOperation } from '../../commands/operations/activate-cell-edit.operation';
import { SetCellEditVisibleOperation } from '../../commands/operations/cell-edit.operation';
-import { MOBILE_KEYBOARD_VISIBLE } from '../../consts/mobile-context';
import { IEditorBridgeService } from '../../services/editor-bridge.service';
import { ISheetEmbedRuntimeFocusCoordinator, SHEET_EMBED_RUNTIME_FOCUS_ROLE_ATTRIBUTE } from '../../services/sheet-embed-integration.service';
import { SheetSkeletonManagerService } from '../../services/sheet-skeleton-manager.service';
@@ -91,31 +90,6 @@ export class EditorBridgeRenderController extends RxDisposable implements IRende
this._selectionManagerService.selectionMoveStart$
).subscribe((params) => this._updateEditorPosition(params)));
d.add(this._selectionManagerService.selectionMoveEnd$.subscribe((params) => {
- if (
- this._contextService.getContextValue(MOBILE_KEYBOARD_VISIBLE) &&
- !this._editorBridgeService.isForceKeepVisible()
- ) {
- const primary = params?.[params.length - 1]?.primary;
- if (!primary) {
- return;
- }
-
- if (this._editorBridgeService.isVisible().visible) {
- this._commandService.syncExecuteCommand(SetCellEditVisibleOperation.id, {
- visible: false,
- eventType: DeviceInputEventType.PointerDown,
- unitId: this._context.unitId,
- });
- }
- this._updateEditorPosition(params);
- this._commandService.syncExecuteCommand(SetCellEditVisibleOperation.id, {
- visible: true,
- eventType: DeviceInputEventType.PointerDown,
- unitId: this._context.unitId,
- });
- return;
- }
-
this._updateEditorPosition(params);
if (params?.[params.length - 1]?.primary) {
this._updateInputPosition();
@@ -349,10 +323,6 @@ export class EditorBridgeRenderController extends RxDisposable implements IRende
}
private _tryHideEditor(evt?: Event | { target?: EventTarget | null; clientX?: number; clientY?: number; x?: number; y?: number }) {
- if (this._contextService.getContextValue(MOBILE_KEYBOARD_VISIBLE)) {
- return;
- }
-
// In the activated state of formula editing,
// prohibit closing the editor according to the state to facilitate generating selection reference text.
if (this._editorBridgeService.isForceKeepVisible()) {
diff --git a/packages/sheets-ui/src/controllers/render-controllers/mobile/__tests__/mobile-contextmenu.render-controller.spec.ts b/packages/sheets-ui/src/controllers/render-controllers/mobile/__tests__/mobile-contextmenu.render-controller.spec.ts
index f4f493442f..3bd6841d15 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/mobile/__tests__/mobile-contextmenu.render-controller.spec.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/mobile/__tests__/mobile-contextmenu.render-controller.spec.ts
@@ -16,29 +16,21 @@
// @vitest-environment jsdom
+import type { BehaviorSubject } from 'rxjs';
import { RANGE_TYPE } from '@univerjs/core';
-import { SelectionMoveType, SheetsSelectionsService } from '@univerjs/sheets';
-import { ContextMenuService, DesktopLayoutService, IContextMenuService, ILayoutService } from '@univerjs/ui';
+import { SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';
+import { SelectionMoveType, SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';
+import { ContextMenuPosition, ContextMenuService, DesktopLayoutService, IContextMenuService, ILayoutService } from '@univerjs/ui';
import { describe, expect, it, vi } from 'vitest';
import { createRenderTestBed } from '../../__tests__/render-test-bed';
import {
+ getMobileContextMenuPositionByViewportKey,
SheetContextMenuMobileRenderController,
shouldKeepCurrentSelectionForMobileContextMenu,
} from '../mobile-contextmenu.render-controller';
-function createEventSubject() {
- const listeners: Array<() => void> = [];
- return {
- subscribeEvent: (listener: () => void) => {
- listeners.push(listener);
- return { dispose: vi.fn() };
- },
- emit: () => listeners.forEach((listener) => listener()),
- };
-}
-
describe('mobile context menu helpers', () => {
- it('opens on a second tap inside the current selection', () => {
+ it('keeps the current selection when long-pressing inside it', () => {
expect(shouldKeepCurrentSelectionForMobileContextMenu([
{
range: { startRow: 1, endRow: 3, startColumn: 2, endColumn: 4, rangeType: RANGE_TYPE.NORMAL },
@@ -54,7 +46,7 @@ describe('mobile context menu helpers', () => {
})).toBe(true);
});
- it('keeps the menu closed when tapping outside the current selection', () => {
+ it('replaces the current selection when long-pressing outside it', () => {
expect(shouldKeepCurrentSelectionForMobileContextMenu([
{
range: { startRow: 1, endRow: 3, startColumn: 2, endColumn: 4, rangeType: RANGE_TYPE.NORMAL },
@@ -70,7 +62,17 @@ describe('mobile context menu helpers', () => {
})).toBe(false);
});
- it('delays the selected-tap menu so a double-tap remains available for editing', async () => {
+ it('maps sheet viewports to the corresponding mobile context menu', () => {
+ expect(getMobileContextMenuPositionByViewportKey(SHEET_VIEWPORT_KEY.VIEW_MAIN)).toBe(ContextMenuPosition.MAIN_AREA);
+ expect(getMobileContextMenuPositionByViewportKey(SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP)).toBe(ContextMenuPosition.MAIN_AREA);
+ expect(getMobileContextMenuPositionByViewportKey(SHEET_VIEWPORT_KEY.VIEW_ROW_TOP)).toBe(ContextMenuPosition.ROW_HEADER);
+ expect(getMobileContextMenuPositionByViewportKey(SHEET_VIEWPORT_KEY.VIEW_ROW_BOTTOM)).toBe(ContextMenuPosition.ROW_HEADER);
+ expect(getMobileContextMenuPositionByViewportKey(SHEET_VIEWPORT_KEY.VIEW_COLUMN_LEFT)).toBe(ContextMenuPosition.COL_HEADER);
+ expect(getMobileContextMenuPositionByViewportKey(SHEET_VIEWPORT_KEY.VIEW_COLUMN_RIGHT)).toBe(ContextMenuPosition.COL_HEADER);
+ expect(getMobileContextMenuPositionByViewportKey(SHEET_VIEWPORT_KEY.VIEW_LEFT_TOP)).toBeNull();
+ });
+
+ it('lets a feature handle a scrolled main-area long press at the touched cell', async () => {
vi.useFakeTimers();
const contentElement = document.createElement('div');
const canvas = document.createElement('canvas');
@@ -78,14 +80,13 @@ describe('mobile context menu helpers', () => {
document.body.appendChild(contentElement);
const triggerContextMenu = vi.fn();
- const onDblclick$ = createEventSubject();
const testBed = createRenderTestBed({
dependencies: [
[IContextMenuService, { useClass: ContextMenuService }],
[ILayoutService, { useClass: DesktopLayoutService }],
],
});
- const { context, injector, scene, sheet, skeleton } = testBed;
+ const { commandService, context, injector, scene, sheet, skeleton, viewportMap } = testBed;
const layoutRegistration = injector.get(ILayoutService).registerContentElement(contentElement);
const contextMenuRegistration = injector.get(IContextMenuService).registerContextMenuHandler({
visible: false,
@@ -94,77 +95,182 @@ describe('mobile context menu helpers', () => {
});
const worksheet = sheet.getActiveSheet();
const selectionManagerService = injector.get(SheetsSelectionsService);
+ commandService.registerCommand(SetSelectionsOperation);
selectionManagerService.setSelections(
sheet.getUnitId(),
worksheet.getSheetId(),
[{
- range: { startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 },
+ range: { startRow: 6, endRow: 6, startColumn: 3, endColumn: 3 },
primary: null,
style: null,
}],
SelectionMoveType.MOVE_END
);
+ viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_MAIN)!.viewportScrollX = 100;
Object.assign(scene, { pick: () => null });
Object.assign(skeleton, {
- getCellWithCoordByOffset: () => ({
- actualColumn: 1,
- actualRow: 1,
- endX: 200,
- endY: 40,
- isMerged: false,
- isMergedMainCell: false,
- mergeInfo: {
- endColumn: 1,
- endRow: 1,
- endX: 200,
- endY: 40,
- startColumn: 1,
- startRow: 1,
- startX: 100,
- startY: 20,
- },
- startX: 100,
- startY: 20,
- }),
+ getCellWithCoordByOffset: (
+ offsetX: number,
+ offsetY: number,
+ scaleX: number,
+ scaleY: number,
+ scrollXY: { x: number; y: number }
+ ) => {
+ const actualColumn = Math.floor((offsetX / scaleX + scrollXY.x - 46) / 100);
+ const actualRow = Math.floor((offsetY / scaleY + scrollXY.y - 20) / 20);
+ return {
+ actualColumn,
+ actualRow,
+ endX: (actualColumn + 1) * 100 + 46,
+ endY: (actualRow + 1) * 20 + 20,
+ isMerged: false,
+ isMergedMainCell: false,
+ mergeInfo: {
+ endColumn: actualColumn,
+ endRow: actualRow,
+ endX: (actualColumn + 1) * 100 + 46,
+ endY: (actualRow + 1) * 20 + 20,
+ startColumn: actualColumn,
+ startRow: actualRow,
+ startX: actualColumn * 100 + 46,
+ startY: actualRow * 20 + 20,
+ },
+ startX: actualColumn * 100 + 46,
+ startY: actualRow * 20 + 20,
+ };
+ },
});
const mainComponent = context.mainComponent;
if (!mainComponent) throw new Error('Expected the sheet render component to be available.');
- Object.assign(mainComponent, { onDblclick$ });
testBed.renderManagerService.removeRender(sheet.getUnitId());
const controller = injector.createInstance(SheetContextMenuMobileRenderController, context);
+ const handleLongPress = vi.fn();
+ const contextMenuInterceptor = Reflect.get(controller, 'contextMenuInterceptor') as undefined | {
+ getInterceptPoints: () => { MOBILE_CONTEXT_MENU: unknown };
+ intercept: (
+ point: unknown,
+ interceptor: { handler: (value: unknown, context: unknown) => boolean }
+ ) => () => void;
+ };
+ expect(contextMenuInterceptor).toBeDefined();
+ const disposeInterceptor = contextMenuInterceptor!.intercept(
+ contextMenuInterceptor!.getInterceptPoints().MOBILE_CONTEXT_MENU,
+ {
+ handler: (_value, longPressContext) => {
+ handleLongPress(longPressContext);
+ return true;
+ },
+ }
+ );
canvas.addEventListener('pointerup', (event) => event.stopPropagation());
const dispatchPointer = (type: string) => {
const event = new Event(type, { bubbles: true, cancelable: true });
Object.defineProperties(event, {
+ button: { value: 0 },
isPrimary: { value: true },
- clientX: { value: 20 },
- clientY: { value: 20 },
+ clientX: { value: 320 },
+ clientY: { value: 150 },
+ pointerId: { value: 1 },
});
canvas.dispatchEvent(event);
};
dispatchPointer('pointerdown');
expect(selectionManagerService.getCurrentLastSelection()?.range).toEqual({
- startRow: 1,
- endRow: 2,
- startColumn: 1,
- endColumn: 2,
+ startRow: 6,
+ endRow: 6,
+ startColumn: 3,
+ endColumn: 3,
+ });
+ expect(triggerContextMenu).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(499);
+ expect(triggerContextMenu).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(selectionManagerService.getCurrentLastSelection()?.range).toEqual({
+ startRow: 6,
+ endRow: 6,
+ startColumn: 3,
+ endColumn: 3,
+ });
+ expect(handleLongPress).toHaveBeenCalledWith({
+ col: 3,
+ menuPosition: ContextMenuPosition.MAIN_AREA,
+ row: 6,
+ subUnitId: worksheet.getSheetId(),
+ unitId: sheet.getUnitId(),
});
- dispatchPointer('pointerup');
-
expect(triggerContextMenu).not.toHaveBeenCalled();
- await vi.advanceTimersByTimeAsync(500);
- expect(triggerContextMenu).toHaveBeenCalledOnce();
-
- triggerContextMenu.mockClear();
- dispatchPointer('pointerdown');
dispatchPointer('pointerup');
+
+ disposeInterceptor();
dispatchPointer('pointerdown');
+ await vi.advanceTimersByTimeAsync(500);
+ expect(triggerContextMenu).toHaveBeenCalledWith(
+ expect.any(MouseEvent),
+ ContextMenuPosition.MAIN_AREA,
+ { unitId: sheet.getUnitId() }
+ );
dispatchPointer('pointerup');
- onDblclick$.emit();
+
+ controller.dispose();
+ contextMenuRegistration.dispose();
+ layoutRegistration.dispose();
+ contentElement.remove();
+ testBed.univer.dispose();
+ vi.useRealTimers();
+ });
+
+ it('cancels a pending row-header long press when the render is deactivated', async () => {
+ vi.useFakeTimers();
+ const contentElement = document.createElement('div');
+ const canvas = document.createElement('canvas');
+ contentElement.appendChild(canvas);
+ document.body.appendChild(contentElement);
+
+ const triggerContextMenu = vi.fn();
+ const testBed = createRenderTestBed({
+ dependencies: [
+ [IContextMenuService, { useClass: ContextMenuService }],
+ [ILayoutService, { useClass: DesktopLayoutService }],
+ ],
+ });
+ const { context, injector, renderManagerService, scene, sheet, viewportMap } = testBed;
+ const layoutRegistration = injector.get(ILayoutService).registerContentElement(contentElement);
+ const contextMenuRegistration = injector.get(IContextMenuService).registerContextMenuHandler({
+ visible: false,
+ handleContextMenu: triggerContextMenu,
+ hideContextMenu: vi.fn(),
+ });
+ Object.assign(scene, {
+ getActiveViewportByCoord: () => viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_ROW_TOP),
+ pick: () => null,
+ });
+ renderManagerService.removeRender(sheet.getUnitId());
+ const controller = injector.createInstance(SheetContextMenuMobileRenderController, context);
+
+ const event = new Event('pointerdown', { bubbles: true, cancelable: true });
+ Object.defineProperties(event, {
+ button: { value: 0 },
+ isPrimary: { value: true },
+ clientX: { value: 20 },
+ clientY: { value: 20 },
+ pointerId: { value: 1 },
+ });
+ canvas.dispatchEvent(event);
+ (context.activated$ as BehaviorSubject<boolean>).next(false);
await vi.advanceTimersByTimeAsync(500);
expect(triggerContextMenu).not.toHaveBeenCalled();
+ (context.activated$ as BehaviorSubject<boolean>).next(true);
+ canvas.dispatchEvent(event);
+ await vi.advanceTimersByTimeAsync(500);
+
+ expect(triggerContextMenu).toHaveBeenCalledWith(
+ expect.any(MouseEvent),
+ ContextMenuPosition.ROW_HEADER,
+ { unitId: sheet.getUnitId() }
+ );
+
controller.dispose();
contextMenuRegistration.dispose();
layoutRegistration.dispose();
diff --git a/packages/sheets-ui/src/controllers/render-controllers/mobile/__tests__/mobile-header-resize.render-controller.spec.ts b/packages/sheets-ui/src/controllers/render-controllers/mobile/__tests__/mobile-header-resize.render-controller.spec.ts
index f80f356d5a..ea2e0d6c0c 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/mobile/__tests__/mobile-header-resize.render-controller.spec.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/mobile/__tests__/mobile-header-resize.render-controller.spec.ts
@@ -58,6 +58,7 @@ function createController() {
};
const skeleton = {
rowHeaderWidth: 48,
+ rowHeaderWidthAndMarginLeft: 48,
columnHeaderHeight: 24,
columnTotalWidth: 1000,
rowTotalHeight: 2000,
@@ -150,4 +151,24 @@ describe('MobileHeaderResizeRenderController business methods', () => {
anchorCol: 1,
});
});
+
+ it('centers the row resize handle inside the row header when an outline gutter is present', () => {
+ const { controller, skeleton } = createController();
+ skeleton.rowHeaderWidthAndMarginLeft = 72;
+
+ controller._handleSelectionChange([{
+ range: { startRow: 2, endRow: 2, startColumn: 0, endColumn: 0, rangeType: RANGE_TYPE.ROW },
+ }]);
+
+ expect(controller._rowResizeButton.transformByState).toHaveBeenCalledWith({
+ left: 42,
+ top: 54,
+ });
+
+ controller._updateButtonPositionOnScroll();
+ expect(controller._rowResizeButton.transformByState).toHaveBeenLastCalledWith({
+ left: 42,
+ top: 54,
+ });
+ });
});
diff --git a/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-contextmenu.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-contextmenu.render-controller.ts
index 31955c2d1d..d66ecf289c 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-contextmenu.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-contextmenu.render-controller.ts
@@ -16,23 +16,51 @@
import type { ICellWithCoord, IRange, Nullable, Workbook } from '@univerjs/core';
import type { IRenderContext, IRenderModule, Viewport } from '@univerjs/engine-render';
-import type { ISelectionWithStyle } from '@univerjs/sheets';
-import { Disposable, IContextService, Inject, Rectangle, toDisposable } from '@univerjs/core';
+import type { ISelectionWithStyle, ISetSelectionsOperationParams } from '@univerjs/sheets';
+import {
+ createInterceptorKey,
+ Disposable,
+ ICommandService,
+ IContextService,
+ Inject,
+ InterceptorManager,
+ RANGE_TYPE,
+ Rectangle,
+ toDisposable,
+} from '@univerjs/core';
import { IRenderManagerService, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
-import { convertSelectionDataToRange, SheetsSelectionsService } from '@univerjs/sheets';
+import {
+ convertPrimaryWithCoordToPrimary,
+ convertSelectionDataToRange,
+ SelectionMoveType,
+ SetSelectionsOperation,
+ SheetsSelectionsService,
+} from '@univerjs/sheets';
import { ContextMenuPosition, IContextMenuService, ILayoutService } from '@univerjs/ui';
-import { MOBILE_EXPANDING_SELECTION, MOBILE_PINCH_ZOOMING } from '../../../consts/mobile-context';
+import {
+ MOBILE_EXPANDING_SELECTION,
+ MOBILE_PINCH_ZOOMING,
+ MOBILE_TRIGGER_CONTEXT_MENU,
+} from '../../../consts/mobile-context';
import { ISheetSelectionRenderService } from '../../../services/selection/base-selection-render.service';
import { SELECTION_MANAGER_KEY } from '../../../services/selection/selection-control';
import { SheetSkeletonManagerService } from '../../../services/sheet-skeleton-manager.service';
-const TAP_MOVE_THRESHOLD = 10;
-const TAP_MENU_DELAY = 500;
+const LONG_PRESS_DURATION = 500;
+const LONG_PRESS_MOVE_THRESHOLD = 10;
const MAIN_AREA_VIEWPORT_KEYS = new Set<string>([
SHEET_VIEWPORT_KEY.VIEW_MAIN,
+ SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP,
SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT,
SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP,
- SHEET_VIEWPORT_KEY.VIEW_LEFT_TOP,
+]);
+const ROW_HEADER_VIEWPORT_KEYS = new Set<string>([
+ SHEET_VIEWPORT_KEY.VIEW_ROW_TOP,
+ SHEET_VIEWPORT_KEY.VIEW_ROW_BOTTOM,
+]);
+const COLUMN_HEADER_VIEWPORT_KEYS = new Set<string>([
+ SHEET_VIEWPORT_KEY.VIEW_COLUMN_LEFT,
+ SHEET_VIEWPORT_KEY.VIEW_COLUMN_RIGHT,
]);
const SELECTION_OBJECT_PREFIXES = [
@@ -41,8 +69,8 @@ const SELECTION_OBJECT_PREFIXES = [
SELECTION_MANAGER_KEY.bottom,
SELECTION_MANAGER_KEY.left,
SELECTION_MANAGER_KEY.right,
- SELECTION_MANAGER_KEY.fillTopLeft,
- SELECTION_MANAGER_KEY.fillBottomRight,
+ SELECTION_MANAGER_KEY.expandTopLeft,
+ SELECTION_MANAGER_KEY.expandBottomRight,
SELECTION_MANAGER_KEY.backgroundTop,
SELECTION_MANAGER_KEY.backgroundMiddleLeft,
SELECTION_MANAGER_KEY.backgroundMiddleRight,
@@ -54,41 +82,76 @@ interface ITouchPosition {
clientY: number;
offsetX: number;
offsetY: number;
+ pointerId: number;
}
-interface ITapState {
+interface ILongPressTarget {
+ cell: Nullable<ICellWithCoord>;
+ menuPosition: ContextMenuPosition;
+ selectionObjectPicked: boolean;
+}
+
+interface ILongPressState {
activeTouch: Nullable<ITouchPosition>;
- menuTimer: Nullable<ReturnType<typeof setTimeout>>;
- shouldOpenMenu: boolean;
+ longPressTimer: Nullable<ReturnType<typeof setTimeout>>;
+ longPressTriggered: boolean;
selectionSnapshot: ISelectionWithStyle[];
+ target: Nullable<ILongPressTarget>;
+}
+
+export interface IMobileContextMenuInterceptorContext {
+ col?: number;
+ menuPosition: ContextMenuPosition;
+ row?: number;
+ subUnitId: string;
+ unitId: string;
}
+export const MOBILE_CONTEXT_MENU = createInterceptorKey<boolean, IMobileContextMenuInterceptorContext>(
+ 'mobile-context-menu'
+);
+
function isSelectionObjectKey(objectKey?: string | null): boolean {
return !!objectKey && SELECTION_OBJECT_PREFIXES.some((prefix) => objectKey.startsWith(prefix));
}
-export function shouldKeepCurrentSelectionForMobileContextMenu(currentSelections: Array<IRange | ISelectionWithStyle>, targetRange: IRange): boolean {
+export function getMobileContextMenuPositionByViewportKey(viewportKey: string): Nullable<ContextMenuPosition> {
+ if (MAIN_AREA_VIEWPORT_KEYS.has(viewportKey)) {
+ return ContextMenuPosition.MAIN_AREA;
+ }
+ if (ROW_HEADER_VIEWPORT_KEYS.has(viewportKey)) {
+ return ContextMenuPosition.ROW_HEADER;
+ }
+ if (COLUMN_HEADER_VIEWPORT_KEYS.has(viewportKey)) {
+ return ContextMenuPosition.COL_HEADER;
+ }
+ return null;
+}
+
+export function shouldKeepCurrentSelectionForMobileContextMenu(
+ currentSelections: Array<IRange | ISelectionWithStyle>,
+ targetRange: IRange
+): boolean {
return currentSelections.some((selection) => Rectangle.contains('range' in selection ? selection.range : selection, targetRange));
}
-/**
- * On mobile devices, tapping inside the current selection a second time opens
- * the context menu. Tapping elsewhere remains a normal selection gesture.
- *
- * @ignore
- */
+/** @ignore */
export class SheetContextMenuMobileRenderController extends Disposable implements IRenderModule {
+ readonly contextMenuInterceptor = new InterceptorManager({ MOBILE_CONTEXT_MENU });
+
constructor(
private readonly _context: IRenderContext<Workbook>,
@ILayoutService private readonly _layoutService: ILayoutService,
@IContextMenuService private readonly _contextMenuService: IContextMenuService,
@IContextService private readonly _contextService: IContextService,
+ @ICommandService private readonly _commandService: ICommandService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
@Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
@Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService
) {
super();
+ this.disposeWithMe(toDisposable(() => this.contextMenuInterceptor.dispose()));
this._init();
}
@@ -98,15 +161,22 @@ export class SheetContextMenuMobileRenderController extends Disposable implement
return;
}
- const state = this._createTapState();
- const handlePointerDown = (event: PointerEvent) => this._handlePointerDown(contentElement, state, event);
+ const state = this._createLongPressState();
+ let activated = false;
+ this.disposeWithMe(this._context.activated$.subscribe((value) => {
+ activated = value;
+ if (!activated) {
+ this._resetLongPressState(state);
+ }
+ }));
+ const handlePointerDown = (event: PointerEvent) => {
+ if (activated) {
+ this._handlePointerDown(contentElement, state, event);
+ }
+ };
const handlePointerMove = (event: PointerEvent) => this._handlePointerMove(contentElement, state, event);
const handlePointerUp = (event: PointerEvent) => this._handlePointerUp(state, event);
- const handlePointerCancel = () => this._resetTapState(state);
- const dblclickSubscription = this._context.mainComponent?.onDblclick$.subscribeEvent(() => this._cancelPendingMenu(state));
- if (dblclickSubscription) {
- this.disposeWithMe(dblclickSubscription);
- }
+ const handlePointerCancel = () => this._resetLongPressState(state);
contentElement.addEventListener('pointerdown', handlePointerDown, true);
contentElement.addEventListener('pointermove', handlePointerMove, true);
@@ -118,30 +188,33 @@ export class SheetContextMenuMobileRenderController extends Disposable implement
contentElement.removeEventListener('pointermove', handlePointerMove, true);
contentElement.removeEventListener('pointerup', handlePointerUp, true);
contentElement.removeEventListener('pointercancel', handlePointerCancel, true);
- this._cancelPendingMenu(state);
+ this._resetLongPressState(state);
}));
}
- private _createTapState(): ITapState {
+ private _createLongPressState(): ILongPressState {
return {
activeTouch: null,
- menuTimer: null,
- shouldOpenMenu: false,
+ longPressTimer: null,
+ longPressTriggered: false,
selectionSnapshot: [],
+ target: null,
};
}
- private _resetTapState(state: ITapState): void {
- state.activeTouch = null;
- state.shouldOpenMenu = false;
- }
-
- private _cancelPendingMenu(state: ITapState): void {
- if (state.menuTimer == null) {
+ private _clearLongPressTimer(state: ILongPressState): void {
+ if (state.longPressTimer == null) {
return;
}
- clearTimeout(state.menuTimer);
- state.menuTimer = null;
+ clearTimeout(state.longPressTimer);
+ state.longPressTimer = null;
+ }
+
+ private _resetLongPressState(state: ILongPressState): void {
+ this._clearLongPressTimer(state);
+ state.activeTouch = null;
+ state.longPressTriggered = false;
+ state.target = null;
}
private _getPointerOffset(contentElement: HTMLElement, event: PointerEvent): ITouchPosition {
@@ -151,34 +224,55 @@ export class SheetContextMenuMobileRenderController extends Disposable implement
clientY: event.clientY,
offsetX: event.clientX - rect.left,
offsetY: event.clientY - rect.top,
+ pointerId: event.pointerId,
};
}
- private _getMainAreaViewport(offsetX: number, offsetY: number): Nullable<Viewport> {
+ private _getTargetCellByOffset(offsetX: number, offsetY: number, viewport: Viewport): Nullable<ICellWithCoord> {
+ const skeleton = this._sheetSkeletonManagerService.getCurrentParam()?.skeleton;
const { scene } = this._context;
- const viewport = scene.getActiveViewportByCoord(Vector2.FromArray([offsetX, offsetY]));
-
- if (!viewport || !MAIN_AREA_VIEWPORT_KEYS.has(viewport.viewportKey)) {
+ if (!skeleton) {
return null;
}
- return viewport;
+ const relativeCoords = scene.getCoordRelativeToViewport(Vector2.FromArray([offsetX, offsetY]));
+ const scrollXY = scene.getScrollXYInfoByViewport(relativeCoords, viewport);
+ const { scaleX, scaleY } = scene.getAncestorScale();
+
+ return skeleton.getCellWithCoordByOffset(
+ relativeCoords.x,
+ relativeCoords.y,
+ scaleX,
+ scaleY,
+ scrollXY
+ );
}
- private _getTargetCellByOffset(offsetX: number, offsetY: number): Nullable<ICellWithCoord> {
- const skeleton = this._sheetSkeletonManagerService.getCurrentParam()?.skeleton;
- const viewport = this._getMainAreaViewport(offsetX, offsetY);
+ private _resolveLongPressTarget(offsetX: number, offsetY: number): Nullable<ILongPressTarget> {
const { scene } = this._context;
+ const viewport = scene.getActiveViewportByCoord(Vector2.FromArray([offsetX, offsetY]));
+ if (!viewport) {
+ return null;
+ }
- if (!skeleton || !viewport) {
+ const menuPosition = getMobileContextMenuPositionByViewportKey(viewport.viewportKey);
+ if (!menuPosition) {
return null;
}
- const relativeCoords = scene.getCoordRelativeToViewport(Vector2.FromArray([offsetX, offsetY]));
- const scrollXY = scene.getScrollXYInfoByViewport(relativeCoords, viewport);
- const { scaleX, scaleY } = scene.getAncestorScale();
+ if (menuPosition !== ContextMenuPosition.MAIN_AREA) {
+ return { cell: null, menuPosition, selectionObjectPicked: false };
+ }
+
+ const pickedObject = scene.pick(Vector2.FromArray([offsetX, offsetY]));
+ const pickedObjectKey = pickedObject && 'oKey' in pickedObject ? pickedObject.oKey : undefined;
+ const selectionObjectPicked = isSelectionObjectKey(pickedObjectKey);
+ if (pickedObject && pickedObject !== this._context.mainComponent && !selectionObjectPicked) {
+ return null;
+ }
- return skeleton.getCellWithCoordByOffset(relativeCoords.x - scrollXY.x, relativeCoords.y - scrollXY.y, scaleX, scaleY, scrollXY);
+ const cell = this._getTargetCellByOffset(offsetX, offsetY, viewport);
+ return cell ? { cell, menuPosition, selectionObjectPicked } : null;
}
private _getCurrentRenderSelections(): ISelectionWithStyle[] {
@@ -204,68 +298,122 @@ export class SheetContextMenuMobileRenderController extends Disposable implement
return this._cloneSelections(this._selectionManagerService.getCurrentSelections());
}
- private _openMenu(clientX: number, clientY: number): void {
+ private _selectTargetCell(targetCell: ICellWithCoord): boolean {
+ const worksheet = this._context.unit.getActiveSheet();
+ if (!worksheet) {
+ return false;
+ }
+
+ const { startRow, endRow, startColumn, endColumn } = targetCell.mergeInfo;
+ return this._commandService.syncExecuteCommand<ISetSelectionsOperationParams>(SetSelectionsOperation.id, {
+ unitId: this._context.unitId,
+ subUnitId: worksheet.getSheetId(),
+ type: SelectionMoveType.MOVE_END,
+ selections: [{
+ range: { startRow, endRow, startColumn, endColumn, rangeType: RANGE_TYPE.NORMAL },
+ primary: convertPrimaryWithCoordToPrimary(targetCell),
+ style: null,
+ }],
+ });
+ }
+
+ private _openMenu(clientX: number, clientY: number, menuPosition: ContextMenuPosition): void {
const event = new MouseEvent('contextmenu', { clientX, clientY });
- this._contextMenuService.triggerContextMenu(event, ContextMenuPosition.MAIN_AREA, { unitId: this._context.unitId });
+ this._contextMenuService.triggerContextMenu(event, menuPosition, { unitId: this._context.unitId });
}
- private _handlePointerDown(contentElement: HTMLElement, state: ITapState, event: PointerEvent): void {
- this._cancelPendingMenu(state);
+ private _triggerLongPress(state: ILongPressState): void {
+ state.longPressTimer = null;
+ const { activeTouch, target } = state;
+ if (!activeTouch || !target || this._contextMenuService.visible) {
+ return;
+ }
+ if (
+ this._contextService.getContextValue(MOBILE_PINCH_ZOOMING) ||
+ this._contextService.getContextValue(MOBILE_EXPANDING_SELECTION)
+ ) {
+ return;
+ }
+
+ if (
+ target.menuPosition === ContextMenuPosition.MAIN_AREA &&
+ target.cell &&
+ !target.selectionObjectPicked &&
+ !shouldKeepCurrentSelectionForMobileContextMenu(state.selectionSnapshot, target.cell.mergeInfo) &&
+ !this._selectTargetCell(target.cell)
+ ) {
+ return;
+ }
+
+ state.longPressTriggered = true;
+ this._contextService.setContextValue(MOBILE_TRIGGER_CONTEXT_MENU, true);
+ const worksheet = this._context.unit.getActiveSheet();
+ if (!worksheet) {
+ return;
+ }
+ const handled = this.contextMenuInterceptor.fetchThroughInterceptors(MOBILE_CONTEXT_MENU)(false, {
+ col: target.cell?.actualColumn,
+ menuPosition: target.menuPosition,
+ row: target.cell?.actualRow,
+ subUnitId: worksheet.getSheetId(),
+ unitId: this._context.unitId,
+ });
+ if (handled) {
+ return;
+ }
+ this._openMenu(activeTouch.clientX, activeTouch.clientY, target.menuPosition);
+ }
+
+ private _handlePointerDown(contentElement: HTMLElement, state: ILongPressState, event: PointerEvent): void {
+ this._resetLongPressState(state);
+ this._contextService.setContextValue(MOBILE_TRIGGER_CONTEXT_MENU, false);
if (this._contextMenuService.visible) {
this._contextMenuService.hideContextMenu();
- this._resetTapState(state);
return;
}
-
- if (!event.isPrimary || this._contextService.getContextValue(MOBILE_PINCH_ZOOMING) || this._contextService.getContextValue(MOBILE_EXPANDING_SELECTION)) {
- this._resetTapState(state);
+ if (
+ !event.isPrimary ||
+ event.button !== 0 ||
+ this._contextService.getContextValue(MOBILE_PINCH_ZOOMING) ||
+ this._contextService.getContextValue(MOBILE_EXPANDING_SELECTION)
+ ) {
return;
}
const touch = this._getPointerOffset(contentElement, event);
- const targetCell = this._getTargetCellByOffset(touch.offsetX, touch.offsetY);
- if (!targetCell) {
- this._resetTapState(state);
+ const target = this._resolveLongPressTarget(touch.offsetX, touch.offsetY);
+ if (!target) {
return;
}
- state.selectionSnapshot = this._getSelectionSnapshot();
state.activeTouch = touch;
- const pickedObject = this._context.scene.pick(Vector2.FromArray([touch.offsetX, touch.offsetY]));
- state.shouldOpenMenu = isSelectionObjectKey(pickedObject && 'oKey' in pickedObject ? pickedObject.oKey : undefined)
- || shouldKeepCurrentSelectionForMobileContextMenu(state.selectionSnapshot, targetCell.mergeInfo);
+ state.selectionSnapshot = this._getSelectionSnapshot();
+ state.target = target;
+ state.longPressTimer = setTimeout(() => this._triggerLongPress(state), LONG_PRESS_DURATION);
}
- private _handlePointerMove(contentElement: HTMLElement, state: ITapState, event: PointerEvent): void {
- if (!state.activeTouch || !event.isPrimary) {
- this._resetTapState(state);
+ private _handlePointerMove(contentElement: HTMLElement, state: ILongPressState, event: PointerEvent): void {
+ if (!state.activeTouch || !event.isPrimary || event.pointerId !== state.activeTouch.pointerId) {
+ this._resetLongPressState(state);
return;
}
const touch = this._getPointerOffset(contentElement, event);
if (
- Math.abs(touch.offsetX - state.activeTouch.offsetX) > TAP_MOVE_THRESHOLD ||
- Math.abs(touch.offsetY - state.activeTouch.offsetY) > TAP_MOVE_THRESHOLD
+ Math.abs(touch.offsetX - state.activeTouch.offsetX) > LONG_PRESS_MOVE_THRESHOLD ||
+ Math.abs(touch.offsetY - state.activeTouch.offsetY) > LONG_PRESS_MOVE_THRESHOLD
) {
- this._resetTapState(state);
+ this._resetLongPressState(state);
}
}
- private _handlePointerUp(state: ITapState, event: PointerEvent): void {
- if (
- state.activeTouch &&
- state.shouldOpenMenu &&
- !this._contextService.getContextValue(MOBILE_PINCH_ZOOMING) &&
- !this._contextService.getContextValue(MOBILE_EXPANDING_SELECTION)
- ) {
+ private _handlePointerUp(state: ILongPressState, event: PointerEvent): void {
+ if (state.activeTouch?.pointerId !== event.pointerId) {
+ return;
+ }
+ if (state.longPressTriggered) {
event.preventDefault();
- const { clientX, clientY } = state.activeTouch;
- state.menuTimer = setTimeout(() => {
- state.menuTimer = null;
- this._openMenu(clientX, clientY);
- }, TAP_MENU_DELAY);
}
-
- this._resetTapState(state);
+ this._resetLongPressState(state);
}
}
diff --git a/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-header-resize.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-header-resize.render-controller.ts
index 80daf7cedd..c9cae8cab2 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-header-resize.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-header-resize.render-controller.ts
@@ -183,7 +183,7 @@ export class MobileHeaderResizeRenderController extends Disposable implements IR
// Position button at the bottom of the selected row(s)
const rowEndOffset = skeleton.getOffsetByRow(endRow);
- const { rowHeaderWidth } = skeleton;
+ const { rowHeaderWidth, rowHeaderWidthAndMarginLeft } = skeleton;
const { scaleX, scaleY } = scene.getAncestorScale();
const scale = Math.max(scaleX, scaleY);
@@ -191,7 +191,7 @@ export class MobileHeaderResizeRenderController extends Disposable implements IR
// Position button in the row header area, centered horizontally, aligned to bottom of row
this._rowResizeButton.transformByState({
- left: rowHeaderWidth / 2 - buttonSize / 2,
+ left: rowHeaderWidthAndMarginLeft - rowHeaderWidth / 2 - buttonSize / 2,
top: rowEndOffset - buttonSize / 2,
});
@@ -245,10 +245,10 @@ export class MobileHeaderResizeRenderController extends Disposable implements IR
// Update row button position if visible - keep it at the row's bottom edge
if (this._rowResizeButton?.visible && this._currentRow >= 0) {
const rowEndOffset = skeleton.getOffsetByRow(this._currentRow);
- const { rowHeaderWidth } = skeleton;
+ const { rowHeaderWidth, rowHeaderWidthAndMarginLeft } = skeleton;
this._rowResizeButton.transformByState({
- left: rowHeaderWidth / 2 - buttonSize / 2,
+ left: rowHeaderWidthAndMarginLeft - rowHeaderWidth / 2 - buttonSize / 2,
top: rowEndOffset - buttonSize / 2,
});
}
diff --git a/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-hover.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-hover.render-controller.ts
new file mode 100644
index 0000000000..570f90ea6d
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-hover.render-controller.ts
@@ -0,0 +1,228 @@
+/**
+ * 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 { Nullable, Workbook } from '@univerjs/core';
+import type {
+ IMouseEvent,
+ IPointerEvent,
+ IRenderContext,
+ IRenderModule,
+ Spreadsheet,
+ SpreadsheetColumnHeader,
+ SpreadsheetHeader,
+} from '@univerjs/engine-render';
+import type { ISheetSkeletonManagerParam } from '@univerjs/sheets';
+import { Disposable, DisposableCollection, fromEventSubject, IContextService, Inject } from '@univerjs/core';
+import { SHEET_VIEW_KEY } from '../../../common/keys';
+import {
+ MOBILE_EXPANDING_SELECTION,
+ MOBILE_PINCH_ZOOMING,
+ MOBILE_TRIGGER_CONTEXT_MENU,
+} from '../../../consts/mobile-context';
+import { HoverManagerService } from '../../../services/hover-manager.service';
+import { SheetScrollManagerService } from '../../../services/scroll-manager.service';
+import { SheetSkeletonManagerService } from '../../../services/sheet-skeleton-manager.service';
+
+const TAP_MOVE_THRESHOLD = 10;
+
+interface IMobileTapState {
+ offsetX: number;
+ offsetY: number;
+ pointerId: number | undefined;
+}
+
+type MobilePointerEvent = IMouseEvent | IPointerEvent;
+
+function getPointerId(event: MobilePointerEvent): number | undefined {
+ return 'pointerId' in event ? event.pointerId : undefined;
+}
+
+function isPrimaryPointer(event: MobilePointerEvent): boolean {
+ return !('isPrimary' in event) || event.isPrimary !== false;
+}
+
+export class MobileHoverRenderController extends Disposable implements IRenderModule {
+ private _active = false;
+ private _tapState: Nullable<IMobileTapState> = null;
+
+ get active(): boolean {
+ return this._active;
+ }
+
+ constructor(
+ private readonly _context: IRenderContext<Workbook>,
+ @Inject(HoverManagerService) private readonly _hoverManagerService: HoverManagerService,
+ @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
+ @Inject(SheetScrollManagerService) private readonly _scrollManagerService: SheetScrollManagerService,
+ @IContextService private readonly _contextService: IContextService
+ ) {
+ super();
+
+ this._initPointerEvent();
+ this._initScrollEvent();
+ }
+
+ private _initPointerEvent(): void {
+ const disposeSet = new DisposableCollection();
+ const handleSkeletonChange = (skeletonParam: Nullable<ISheetSkeletonManagerParam>) => {
+ disposeSet.dispose();
+
+ if (!skeletonParam) {
+ return;
+ }
+
+ const { mainComponent, unitId, components } = this._context;
+ if (!mainComponent) {
+ return;
+ }
+
+ this._bindMainComponentEvents(disposeSet, mainComponent as Spreadsheet, unitId);
+ const rowHeader = components.get(SHEET_VIEW_KEY.ROW) as SpreadsheetHeader;
+ const colHeader = components.get(SHEET_VIEW_KEY.COLUMN) as SpreadsheetColumnHeader;
+ if (rowHeader) {
+ this._bindRowHeaderEvents(disposeSet, rowHeader, unitId);
+ }
+ if (colHeader) {
+ this._bindColumnHeaderEvents(disposeSet, colHeader, unitId);
+ }
+ };
+
+ handleSkeletonChange(this._sheetSkeletonManagerService.getCurrentParam());
+ this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(handleSkeletonChange));
+ this.disposeWithMe(disposeSet);
+ }
+
+ private _bindMainComponentEvents(disposeSet: DisposableCollection, mainComponent: Spreadsheet, unitId: string): void {
+ disposeSet.add(mainComponent.onPointerEnter$.subscribeEvent(() => {
+ this._active = true;
+ }));
+ disposeSet.add(fromEventSubject(mainComponent.onPointerMove$).subscribe((event) => {
+ this._active = true;
+ this._updateTapState(event);
+ this._hoverManagerService.triggerMouseMove(unitId, event);
+ }));
+ disposeSet.add(mainComponent.onPointerDown$.subscribeEvent((event) => {
+ this._startTap(event);
+ this._hoverManagerService.triggerPointerDown(unitId, event);
+ }));
+ disposeSet.add(mainComponent.onPointerUp$.subscribeEvent((event) => {
+ this._hoverManagerService.triggerPointerUp(unitId, event);
+ if (this._finishTap(event)) {
+ this._hoverManagerService.triggerClick(unitId, event.offsetX, event.offsetY);
+ }
+ }));
+ disposeSet.add(mainComponent.onDblclick$.subscribeEvent((event) => {
+ this._hoverManagerService.triggerDbClick(unitId, event.offsetX, event.offsetY);
+ }));
+ disposeSet.add(mainComponent.onPointerLeave$.subscribeEvent(() => {
+ this._active = false;
+ this._tapState = null;
+ }));
+ }
+
+ private _bindRowHeaderEvents(disposeSet: DisposableCollection, rowHeader: SpreadsheetHeader, unitId: string): void {
+ disposeSet.add(rowHeader.onPointerMove$.subscribeEvent((event) => {
+ this._hoverManagerService.triggerRowHeaderMouseMove(unitId, event.offsetX, event.offsetY);
+ }));
+ disposeSet.add(rowHeader.onPointerDown$.subscribeEvent((event) => {
+ this._hoverManagerService.triggerRowHeaderPoniterDown(unitId, event.offsetX, event.offsetY);
+ }));
+ disposeSet.add(rowHeader.onPointerUp$.subscribeEvent((event) => {
+ this._hoverManagerService.triggerRowHeaderPoniterUp(unitId, event.offsetX, event.offsetY);
+ if (!this._contextService.getContextValue(MOBILE_TRIGGER_CONTEXT_MENU)) {
+ this._hoverManagerService.triggerRowHeaderClick(unitId, event.offsetX, event.offsetY);
+ }
+ }));
+ disposeSet.add(rowHeader.onDblclick$.subscribeEvent((event) => {
+ this._hoverManagerService.triggerRowHeaderDbClick(unitId, event.offsetX, event.offsetY);
+ }));
+ }
+
+ private _bindColumnHeaderEvents(
+ disposeSet: DisposableCollection,
+ columnHeader: SpreadsheetColumnHeader,
+ unitId: string
+ ): void {
+ disposeSet.add(columnHeader.onPointerMove$.subscribeEvent((event) => {
+ this._hoverManagerService.triggerColHeaderMouseMove(unitId, event.offsetX, event.offsetY);
+ }));
+ disposeSet.add(columnHeader.onPointerDown$.subscribeEvent((event) => {
+ this._hoverManagerService.triggerColHeaderPoniterDown(unitId, event.offsetX, event.offsetY);
+ }));
+ disposeSet.add(columnHeader.onPointerUp$.subscribeEvent((event) => {
+ this._hoverManagerService.triggerColHeaderPoniterUp(unitId, event.offsetX, event.offsetY);
+ if (!this._contextService.getContextValue(MOBILE_TRIGGER_CONTEXT_MENU)) {
+ this._hoverManagerService.triggerColHeaderClick(unitId, event.offsetX, event.offsetY);
+ }
+ }));
+ disposeSet.add(columnHeader.onDblclick$.subscribeEvent((event) => {
+ this._hoverManagerService.triggerColHeaderDbClick(unitId, event.offsetX, event.offsetY);
+ }));
+ }
+
+ private _startTap(event: MobilePointerEvent): void {
+ if (
+ !isPrimaryPointer(event) ||
+ this._contextService.getContextValue(MOBILE_PINCH_ZOOMING) ||
+ this._contextService.getContextValue(MOBILE_EXPANDING_SELECTION)
+ ) {
+ this._tapState = null;
+ return;
+ }
+
+ this._tapState = {
+ offsetX: event.offsetX,
+ offsetY: event.offsetY,
+ pointerId: getPointerId(event),
+ };
+ }
+
+ private _updateTapState(event: MobilePointerEvent): void {
+ const pointerId = getPointerId(event);
+ if (!this._tapState || (pointerId != null && pointerId !== this._tapState.pointerId)) {
+ return;
+ }
+
+ if (
+ Math.abs(event.offsetX - this._tapState.offsetX) > TAP_MOVE_THRESHOLD ||
+ Math.abs(event.offsetY - this._tapState.offsetY) > TAP_MOVE_THRESHOLD
+ ) {
+ this._tapState = null;
+ }
+ }
+
+ private _finishTap(event: MobilePointerEvent): boolean {
+ const tapState = this._tapState;
+ this._tapState = null;
+ const pointerId = getPointerId(event);
+ if (!tapState || (pointerId != null && pointerId !== tapState.pointerId)) {
+ return false;
+ }
+
+ return Math.abs(event.offsetX - tapState.offsetX) <= TAP_MOVE_THRESHOLD
+ && Math.abs(event.offsetY - tapState.offsetY) <= TAP_MOVE_THRESHOLD
+ && !this._contextService.getContextValue(MOBILE_PINCH_ZOOMING)
+ && !this._contextService.getContextValue(MOBILE_EXPANDING_SELECTION)
+ && !this._contextService.getContextValue(MOBILE_TRIGGER_CONTEXT_MENU);
+ }
+
+ private _initScrollEvent(): void {
+ this.disposeWithMe(this._scrollManagerService.validViewportScrollInfo$.subscribe(() => {
+ this._tapState = null;
+ this._hoverManagerService.triggerScroll();
+ }));
+ }
+}
diff --git a/packages/sheets-ui/src/controllers/sheets-ui-icons.ts b/packages/sheets-ui/src/controllers/sheets-ui-icons.ts
new file mode 100644
index 0000000000..299f298733
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/sheets-ui-icons.ts
@@ -0,0 +1,188 @@
+/**
+ * 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 { IconMap } from '@univerjs/ui';
+import {
+ AddImageIcon,
+ AdjustHeightDoubleIcon,
+ AdjustWidthDoubleIcon,
+ AlignBottomIcon,
+ AlignTopIcon,
+ AllBorderIcon,
+ AutoHeightDoubleIcon,
+ AutoWidthDoubleIcon,
+ AutowrapIcon,
+ BackSlashDoubleIcon,
+ BoldIcon,
+ BrushIcon,
+ CancelFreezeIcon,
+ CancelMergeIcon,
+ CheckMarkIcon,
+ ClearFormatDoubleIcon,
+ CodeIcon,
+ ConvertToNumberIcon,
+ CopyDoubleIcon,
+ CutIcon,
+ DeleteCellShiftLeftDoubleIcon,
+ DeleteCellShiftUpDoubleIcon,
+ DeleteColumnDoubleIcon,
+ DeleteIcon,
+ DeleteRowDoubleIcon,
+ DownBorderDoubleIcon,
+ DownloadImageIcon,
+ EyeIcon,
+ FontColorDoubleIcon,
+ FontSizeIncreaseIcon,
+ FontSizeReduceIcon,
+ FreezeColumnIcon,
+ FreezeRowIcon,
+ FreezeToSelectedIcon,
+ HideDoubleIcon,
+ HideGridlinesIcon,
+ HorizontalBorderDoubleIcon,
+ HorizontallyIcon,
+ HorizontalMergeIcon,
+ InnerBorderDoubleIcon,
+ InsertCellDownDoubleIcon,
+ InsertCellShiftRightDoubleIcon,
+ InsertDoubleIcon,
+ InsertRowAboveDoubleIcon,
+ InsertRowBelowDoubleIcon,
+ ItalicIcon,
+ LeftBorderDoubleIcon,
+ LeftDoubleDiagonalDoubleIcon,
+ LeftInsertColumnDoubleIcon,
+ LeftJustifyingIcon,
+ LeftRotationFortyFiveDegreesIcon,
+ LeftRotationNinetyDegreesIcon,
+ LeftTridiagonalDoubleIcon,
+ LockIcon,
+ MergeAllIcon,
+ NoBorderIcon,
+ NoColorDoubleIcon,
+ NoRotationIcon,
+ OuterBorderDoubleIcon,
+ OverflowIcon,
+ PaintBucketDoubleIcon,
+ PasteSpecialDoubleIcon,
+ ProtectIcon,
+ ReduceDoubleIcon,
+ RightBorderDoubleIcon,
+ RightDoubleDiagonalDoubleIcon,
+ RightInsertColumnDoubleIcon,
+ RightJustifyingIcon,
+ RightRotationFortyFiveDegreesIcon,
+ RightRotationNinetyDegreesIcon,
+ ShrinkToFitIcon,
+ SlashDoubleIcon,
+ StrikethroughIcon,
+ SubscriptIcon,
+ SuperscriptIcon,
+ TruncationIcon,
+ UnderlineIcon,
+ UpBorderDoubleIcon,
+ VerticalBorderDoubleIcon,
+ VerticalCenterIcon,
+ VerticalIntegrationIcon,
+ VerticalTextIcon,
+ WriteIcon,
+} from '@univerjs/icons';
+
+export const sheetsUIIcons: IconMap = {
+ AddImageIcon,
+ AdjustHeightDoubleIcon,
+ AdjustWidthDoubleIcon,
+ AlignBottomIcon,
+ AlignTopIcon,
+ AllBorderIcon,
+ AutoHeightDoubleIcon,
+ AutoWidthDoubleIcon,
+ AutowrapIcon,
+ BackSlashDoubleIcon,
+ BoldIcon,
+ BrushIcon,
+ CancelFreezeIcon,
+ CancelMergeIcon,
+ CheckMarkIcon,
+ ClearFormatDoubleIcon,
+ CodeIcon,
+ ConvertToNumberIcon,
+ CopyDoubleIcon,
+ CutIcon,
+ DeleteCellShiftLeftDoubleIcon,
+ DeleteCellShiftUpDoubleIcon,
+ DeleteColumnDoubleIcon,
+ DeleteIcon,
+ DeleteRowDoubleIcon,
+ DownBorderDoubleIcon,
+ DownloadImageIcon,
+ EyeIcon,
+ FontColorDoubleIcon,
+ FontSizeIncreaseIcon,
+ FontSizeReduceIcon,
+ FreezeColumnIcon,
+ FreezeRowIcon,
+ FreezeToSelectedIcon,
+ HideDoubleIcon,
+ HideGridlinesIcon,
+ HorizontalBorderDoubleIcon,
+ HorizontallyIcon,
+ HorizontalMergeIcon,
+ InnerBorderDoubleIcon,
+ InsertCellDownDoubleIcon,
+ InsertCellShiftRightDoubleIcon,
+ InsertDoubleIcon,
+ InsertRowAboveDoubleIcon,
+ InsertRowBelowDoubleIcon,
+ ItalicIcon,
+ LeftBorderDoubleIcon,
+ LeftDoubleDiagonalDoubleIcon,
+ LeftInsertColumnDoubleIcon,
+ LeftJustifyingIcon,
+ LeftRotationFortyFiveDegreesIcon,
+ LeftRotationNinetyDegreesIcon,
+ LeftTridiagonalDoubleIcon,
+ LockIcon,
+ MergeAllIcon,
+ NoBorderIcon,
+ NoColorDoubleIcon,
+ NoRotationIcon,
+ OuterBorderDoubleIcon,
+ OverflowIcon,
+ PaintBucketDoubleIcon,
+ PasteSpecialDoubleIcon,
+ ProtectIcon,
+ ReduceDoubleIcon,
+ RightBorderDoubleIcon,
+ RightDoubleDiagonalDoubleIcon,
+ RightInsertColumnDoubleIcon,
+ RightJustifyingIcon,
+ RightRotationFortyFiveDegreesIcon,
+ RightRotationNinetyDegreesIcon,
+ ShrinkToFitIcon,
+ SlashDoubleIcon,
+ StrikethroughIcon,
+ SubscriptIcon,
+ SuperscriptIcon,
+ TruncationIcon,
+ UnderlineIcon,
+ UpBorderDoubleIcon,
+ VerticalBorderDoubleIcon,
+ VerticalCenterIcon,
+ VerticalIntegrationIcon,
+ VerticalTextIcon,
+ WriteIcon,
+};
diff --git a/packages/sheets-ui/src/index.ts b/packages/sheets-ui/src/index.ts
index 9cf2d2a011..b8b0847a69 100644
--- a/packages/sheets-ui/src/index.ts
+++ b/packages/sheets-ui/src/index.ts
@@ -115,6 +115,11 @@ export { EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY, RANGE_SELECTOR_COMPONENT_KEY, S
export { getCellRealRange, getViewportByCell } from './common/utils';
export type { IUniverSheetsUIConfig } from './config/config';
export { SHEETS_UI_PLUGIN_CONFIG_KEY } from './config/config';
+export {
+ MOBILE_EXPANDING_SELECTION,
+ MOBILE_FORMULA_FUNCTION_PANEL_OPEN,
+ MOBILE_PINCH_ZOOMING,
+} from './consts/mobile-context';
export { UNIVER_SHEET_PERMISSION_USER_PART } from './consts/permission';
export { SHEET_UI_PLUGIN_NAME } from './consts/plugin-name';
export { SheetsUIPart } from './consts/ui-name';
@@ -140,6 +145,13 @@ export {
HEADER_UNHIDE_RANGE_VISIBLE_CHECK,
HeaderUnhideRenderController,
} from './controllers/render-controllers/header-unhide.render-controller';
+export {
+ MOBILE_CONTEXT_MENU,
+ SheetContextMenuMobileRenderController,
+} from './controllers/render-controllers/mobile/mobile-contextmenu.render-controller';
+export type {
+ IMobileContextMenuInterceptorContext,
+} from './controllers/render-controllers/mobile/mobile-contextmenu.render-controller';
export { SheetsScrollRenderController } from './controllers/render-controllers/scroll.render-controller';
export { SheetRenderController } from './controllers/render-controllers/sheet.render-controller';
export type { ITelemetryData } from './controllers/render-controllers/sheet.render-controller';
@@ -248,6 +260,7 @@ export {
} from './services/selection/base-selection-render.service';
export { genNormalSelectionStyle } from './services/selection/const';
export { SELECTION_SHAPE_DEPTH } from './services/selection/const';
+export { MobileSelectionControl } from './services/selection/mobile-selection-shape';
export { SelectionControl, SelectionControl as SelectionShape } from './services/selection/selection-control';
export { SheetSelectionRenderService } from './services/selection/selection-render.service';
export { SelectionShapeExtension } from './services/selection/selection-shape-extension';
diff --git a/packages/sheets-ui/src/mobile-plugin.ts b/packages/sheets-ui/src/mobile-plugin.ts
index ed800c762e..5b1d33ef7c 100644
--- a/packages/sheets-ui/src/mobile-plugin.ts
+++ b/packages/sheets-ui/src/mobile-plugin.ts
@@ -39,24 +39,23 @@ import { UI_PLUGIN_CONFIG_KEY, UniverMobileUIPlugin } from '@univerjs/ui';
import { filter } from 'rxjs/operators';
import pkg from '../package.json';
import { defaultPluginConfig, SHEETS_UI_PLUGIN_CONFIG_KEY } from './config/config';
-import { AutoFillRenderController, AutoFillUIController } from './controllers/auto-fill-ui.controller';
import { AutoHeightController } from './controllers/auto-height.controller';
import { AutoWidthController } from './controllers/auto-width.controller';
import { CellCustomRenderController } from './controllers/cell-custom-render.controller';
import { CellPopupEditorController } from './controllers/cell-popup-editor.controller';
import { SheetCheckboxController } from './controllers/checkbox.controller';
import { SheetClipboardController } from './controllers/clipboard/clipboard.controller';
-import { ComponentsController } from './controllers/components.controller';
import { SheetsDefinedNameController } from './controllers/defined-name/defined-name.controller';
import { DragRenderController } from './controllers/drag-render.controller';
-import { EditorDataSyncController } from './controllers/editor/data-sync.controller';
import { EditingRenderController } from './controllers/editor/editing.render-controller';
import { FormulaEditorController } from './controllers/editor/formula-editor.controller';
import { ForceStringAlertRenderController } from './controllers/force-string-alert-render.controller';
import { ForceStringRenderController } from './controllers/force-string-render.controller';
import { FormatPainterController } from './controllers/format-painter/format-painter.controller';
-import { HoverRenderController } from './controllers/hover-render.controller';
import { MarkSelectionRenderController } from './controllers/mark-selection.controller';
+import { SheetClipboardMobileUIController } from './controllers/mobile/clipboard-ui.controller';
+import { MobileComponentsController } from './controllers/mobile/components.controller';
+import { MobileEditorDataSyncController } from './controllers/mobile/editor-data-sync.controller';
import { SheetUIMobileController } from './controllers/mobile/ui-mobile.controller';
import { MoveRangeRenderController } from './controllers/move-range.controller';
import { SheetPermissionCheckUIController } from './controllers/permission/sheet-permission-check-ui.controller';
@@ -87,6 +86,7 @@ import {
import {
MobileHeaderResizeRenderController,
} from './controllers/render-controllers/mobile/mobile-header-resize.render-controller';
+import { MobileHoverRenderController } from './controllers/render-controllers/mobile/mobile-hover.render-controller';
import {
MobileSheetsScrollRenderController,
} from './controllers/render-controllers/mobile/mobile-scroll.render-controller';
@@ -168,8 +168,8 @@ export class UniverSheetsMobileUIPlugin extends Plugin {
}
override onStarting(): void {
- this._injector.add([ComponentsController]);
- this._injector.get(ComponentsController);
+ this._injector.add([MobileComponentsController]);
+ this._injector.get(MobileComponentsController);
registerDependencies(this._injector, mergeOverrideWithDependencies([
[ShortcutExperienceService],
[IEditorBridgeService, { useClass: EditorBridgeService }],
@@ -198,10 +198,9 @@ export class UniverSheetsMobileUIPlugin extends Plugin {
[SheetsRenderService],
[SheetUIMobileController],
[StatusBarController],
- [AutoFillUIController],
[FormatPainterController],
[SheetsDefinedNameController],
- [EditorDataSyncController],
+ [MobileEditorDataSyncController],
[SheetCheckboxController],
[EditingRenderController],
@@ -221,6 +220,7 @@ export class UniverSheetsMobileUIPlugin extends Plugin {
registerDependencies(this._injector, [
[SheetClipboardController],
+ [SheetClipboardMobileUIController],
]);
this._registerRenderBasics();
@@ -239,12 +239,13 @@ export class UniverSheetsMobileUIPlugin extends Plugin {
touchDependencies(this._injector, [
[SheetPermissionPanelModel],
[SheetClipboardController],
+ [SheetClipboardMobileUIController],
[FormulaEditorController],
[SheetsDefinedNameController],
[StatusBarController],
[AutoHeightController],
[AutoWidthController],
- [EditorDataSyncController],
+ [MobileEditorDataSyncController],
[SheetCheckboxController],
[EditingRenderController],
]);
@@ -253,7 +254,6 @@ export class UniverSheetsMobileUIPlugin extends Plugin {
override onSteady(): void {
touchDependencies(this._injector, [
[FormatPainterController],
- [AutoFillUIController],
[SheetPermissionInterceptorClipboardController],
]);
}
@@ -288,14 +288,12 @@ export class UniverSheetsMobileUIPlugin extends Plugin {
[CellPopupEditorController],
[ForceStringAlertRenderController],
[MarkSelectionRenderController],
- [HoverRenderController],
+ [MobileHoverRenderController],
[DragRenderController],
[ForceStringRenderController],
[CellCustomRenderController],
- [SheetContextMenuMobileRenderController],
[MobileHeaderResizeRenderController],
[MoveRangeRenderController],
- [AutoFillRenderController],
// editor
[EditorBridgeRenderController],
@@ -311,6 +309,7 @@ export class UniverSheetsMobileUIPlugin extends Plugin {
const config = this._configService.getConfig<IUniverUIConfig>(UI_PLUGIN_CONFIG_KEY);
const showContextMenu = config?.contextMenu ?? true;
if (showContextMenu) {
+ modules.push([SheetContextMenuMobileRenderController]);
modules.push([HeaderMenuRenderController]);
}
diff --git a/packages/sheets-ui/src/plugin.ts b/packages/sheets-ui/src/plugin.ts
index 65932bd774..78a9a9f5e9 100644
--- a/packages/sheets-ui/src/plugin.ts
+++ b/packages/sheets-ui/src/plugin.ts
@@ -45,6 +45,7 @@ import { AutoWidthController } from './controllers/auto-width.controller';
import { CellCustomRenderController } from './controllers/cell-custom-render.controller';
import { CellPopupEditorController } from './controllers/cell-popup-editor.controller';
import { SheetCheckboxController } from './controllers/checkbox.controller';
+import { SheetClipboardUIController } from './controllers/clipboard/clipboard-ui.controller';
import { SheetClipboardController } from './controllers/clipboard/clipboard.controller';
import { ComponentsController } from './controllers/components.controller';
import { SheetsDefinedNameController } from './controllers/defined-name/defined-name.controller';
@@ -223,6 +224,7 @@ export class UniverSheetsUIPlugin extends Plugin {
registerDependencies(this._injector, [
[SheetClipboardController],
+ [SheetClipboardUIController],
]);
touchDependencies(this._injector, [
@@ -239,6 +241,7 @@ export class UniverSheetsUIPlugin extends Plugin {
touchDependencies(this._injector, [
[SheetPermissionPanelModel],
[SheetClipboardController],
+ [SheetClipboardUIController],
[FormulaEditorController],
[SheetsDefinedNameController],
[StatusBarController],
diff --git a/packages/sheets-ui/src/services/__tests__/canvas-pop-manager.service.spec.ts b/packages/sheets-ui/src/services/__tests__/canvas-pop-manager.service.spec.ts
index fa4a133e7a..24e8f48591 100644
--- a/packages/sheets-ui/src/services/__tests__/canvas-pop-manager.service.spec.ts
+++ b/packages/sheets-ui/src/services/__tests__/canvas-pop-manager.service.spec.ts
@@ -289,15 +289,18 @@ describe('SheetCanvasPopManagerService', () => {
disable: false,
}]);
- service.registerFeatureMenu('image' as never, callback);
+ service.registerFeatureMenu('image' as never, callback, 'feature.image.title');
expect(service.getFeatureMenu('unit-1', 'sheet-1', 'drawing-1', 'image' as never)).toEqual([
{ label: 'unit-1/sheet-1/drawing-1/image', index: 0, commandId: 'open', commandParams: { drawingId: 'drawing-1' }, disable: false },
]);
expect(service.getFeatureMenu('unit-1', 'sheet-1', 'drawing-1', 'chart' as never)).toBeUndefined();
+ expect(service.getFeatureMenuTitle('image' as never)).toBe('feature.image.title');
+ expect(service.getFeatureMenuTitle('chart' as never)).toBeUndefined();
service.dispose();
expect(service.getFeatureMenu('unit-1', 'sheet-1', 'drawing-1', 'image' as never)).toBeUndefined();
+ expect(service.getFeatureMenuTitle('image' as never)).toBeUndefined();
});
it('anchors a drawing popup with the registered menu offset and removes it when closed', () => {
diff --git a/packages/sheets-ui/src/services/__tests__/editor-bridge.service.spec.ts b/packages/sheets-ui/src/services/__tests__/editor-bridge.service.spec.ts
index 133d6d4385..abab0163f9 100644
--- a/packages/sheets-ui/src/services/__tests__/editor-bridge.service.spec.ts
+++ b/packages/sheets-ui/src/services/__tests__/editor-bridge.service.spec.ts
@@ -30,7 +30,11 @@ import { Subject } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
import { EditorBridgeService, IEditorBridgeService } from '../editor-bridge.service';
-function createService(options?: { disableAutoFocus?: boolean; hasFocusEditor?: boolean }) {
+function createService(options?: {
+ disableAutoFocus?: boolean;
+ hasFocusEditor?: boolean;
+ hasInternalEditorDocument?: boolean;
+}) {
const unitDisposed$ = new Subject<any>();
const workbook = {
getUnitId: () => 'unit-1',
@@ -55,9 +59,15 @@ function createService(options?: { disableAutoFocus?: boolean; hasFocusEditor?:
univerInstanceService: {
getTypeOfUnitDisposed$: vi.fn(() => unitDisposed$.asObservable()),
getCurrentUnitOfType: vi.fn((_type?: UniverInstanceType) => workbook),
- getUnit: vi.fn((unitId: string, type?: UniverInstanceType) => unitId === 'unit-1'
- ? mocks.univerInstanceService.getCurrentUnitOfType(type as never)
- : null),
+ getUnit: vi.fn((unitId: string, type?: UniverInstanceType) => {
+ if (unitId === 'unit-1') {
+ return mocks.univerInstanceService.getCurrentUnitOfType(type as never);
+ }
+
+ return unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY && options?.hasInternalEditorDocument
+ ? { getUnitId: () => DOCS_NORMAL_EDITOR_UNIT_ID_KEY }
+ : null;
+ }),
setCurrentUnitForType: vi.fn(),
},
editorService: {
@@ -224,7 +234,10 @@ describe('EditorBridgeService', () => {
});
it('selects the internal editor without focusing its DOM input when automatic focus is disabled', () => {
- const { service, mocks } = createService({ disableAutoFocus: true });
+ const { service, mocks } = createService({
+ disableAutoFocus: true,
+ hasInternalEditorDocument: true,
+ });
vi.spyOn(service, 'getLatestEditCellState').mockReturnValue(undefined);
service.setEditCell(createEditCellParam());
@@ -234,6 +247,16 @@ describe('EditorBridgeService', () => {
expect(mocks.contextService.setContextValue).not.toHaveBeenCalled();
});
+ it('does not select the internal editor before its document is registered', () => {
+ const { service, mocks } = createService({ disableAutoFocus: true });
+ vi.spyOn(service, 'getLatestEditCellState').mockReturnValue(undefined);
+
+ service.setEditCell(createEditCellParam());
+
+ expect(mocks.univerInstanceService.setCurrentUnitForType).not.toHaveBeenCalled();
+ expect(mocks.editorService.focus).not.toHaveBeenCalled();
+ });
+
it('manages visible/dirty/force-keep states and null-latest branches', () => {
const { service, mocks } = createService({ hasFocusEditor: true });
const visibleValues: any[] = [];
diff --git a/packages/sheets-ui/src/services/canvas-pop-manager.service.ts b/packages/sheets-ui/src/services/canvas-pop-manager.service.ts
index b686666cf5..138269150e 100644
--- a/packages/sheets-ui/src/services/canvas-pop-manager.service.ts
+++ b/packages/sheets-ui/src/services/canvas-pop-manager.service.ts
@@ -75,6 +75,7 @@ type getPopupMenuItemCallback = (unitId: string, subUnitId: string, drawingId: s
export class SheetCanvasPopManagerService extends Disposable {
// the DrawingTypeEnum should refer from drawing package, here we just use type, so no need to import the drawing package
private _popupMenuFeatureMap = new Map<DrawingTypeEnum, getPopupMenuItemCallback>();
+ private _popupMenuTitleMap = new Map<DrawingTypeEnum, string>();
private _popupMenuOffsetMap = new Map<DrawingTypeEnum, { offsetX: number; offsetY: number }>();
private readonly _popupDisposables = new Set<IDisposable>();
@@ -121,8 +122,11 @@ export class SheetCanvasPopManagerService extends Disposable {
/**
* Register a feature menu callback for a specific drawing type.such as image, chart, etc.
*/
- registerFeatureMenu(type: DrawingTypeEnum, getPopupMenuCallBack: getPopupMenuItemCallback) {
+ registerFeatureMenu(type: DrawingTypeEnum, getPopupMenuCallBack: getPopupMenuItemCallback, title?: string) {
this._popupMenuFeatureMap.set(type, getPopupMenuCallBack);
+ if (title) {
+ this._popupMenuTitleMap.set(type, title);
+ }
}
/**
@@ -150,11 +154,16 @@ export class SheetCanvasPopManagerService extends Disposable {
}
}
+ getFeatureMenuTitle(drawingType: DrawingTypeEnum): Nullable<string> {
+ return this._popupMenuTitleMap.get(drawingType);
+ }
+
override dispose(): void {
Array.from(this._popupDisposables).forEach((disposable) => disposable.dispose());
this._popupDisposables.clear();
super.dispose();
this._popupMenuFeatureMap.clear();
+ this._popupMenuTitleMap.clear();
this._popupMenuOffsetMap.clear();
}
diff --git a/packages/sheets-ui/src/services/editor-bridge.service.ts b/packages/sheets-ui/src/services/editor-bridge.service.ts
index 17bce01f5d..5fd6ae5b3e 100644
--- a/packages/sheets-ui/src/services/editor-bridge.service.ts
+++ b/packages/sheets-ui/src/services/editor-bridge.service.ts
@@ -258,7 +258,13 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServ
*/
if (!this._editorService.getFocusEditor()) {
if (this._contextService.getContextValue(DISABLE_AUTO_FOCUS_KEY)) {
- this._univerInstanceService.setCurrentUnitForType(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
+ const editorDocument = this._univerInstanceService.getUnit(
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ UniverInstanceType.UNIVER_DOC
+ );
+ if (editorDocument) {
+ this._univerInstanceService.setCurrentUnitForType(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
+ }
} else {
this._editorService.focus(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
/**
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 820d1cca00..e7c56d5059 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
@@ -14,6 +14,8 @@
* limitations under the License.
*/
+// @vitest-environment jsdom
+
import {
ContextService,
DesktopLogService,
@@ -109,12 +111,17 @@ describe('MarkSelectionService', () => {
primary: null,
} as never);
- expect(service.getShapeMap().get(firstId!)?.control?.getRange()).toMatchObject({
+ const firstControl = service.getShapeMap().get(firstId!)?.control;
+ expect(firstControl?.getRange()).toMatchObject({
startRow: 1,
endRow: 2,
startColumn: 3,
endColumn: 4,
});
+ expect(firstControl?.leftControl.evented).toBe(false);
+ expect(firstControl?.rightControl.evented).toBe(false);
+ expect(firstControl?.topControl.evented).toBe(false);
+ expect(firstControl?.bottomControl.evented).toBe(false);
expect(service.getShapeMap().get(secondId!)?.control).toBeNull();
service.refreshShapes();
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 a6124a882f..6f187a6d3f 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
@@ -49,7 +49,7 @@ interface IMarkSelectionInfo {
exits: string[];
}
-const DEFAULT_Z_INDEX = SELECTION_SHAPE_DEPTH.MARK_SELECTION; ;
+const DEFAULT_Z_INDEX = SELECTION_SHAPE_DEPTH.MARK_SELECTION;
export const IMarkSelectionService = createIdentifier<IMarkSelectionService>('univer.mark-selection-service');
/**
@@ -136,6 +136,7 @@ export class MarkSelectionService extends Disposable implements IMarkSelectionSe
});
const selectionWithCoord = attachSelectionWithCoord(selection, skeleton);
control.updateRangeBySelectionWithCoord(selectionWithCoord);
+ control.setEvent(false);
shape.control = control;
});
}
diff --git a/packages/sheets-ui/src/services/selection/__tests__/mobile-selection-render.service-behavior.spec.ts b/packages/sheets-ui/src/services/selection/__tests__/mobile-selection-render.service-behavior.spec.ts
index 13336673c9..80be159e13 100644
--- a/packages/sheets-ui/src/services/selection/__tests__/mobile-selection-render.service-behavior.spec.ts
+++ b/packages/sheets-ui/src/services/selection/__tests__/mobile-selection-render.service-behavior.spec.ts
@@ -15,24 +15,22 @@
*/
import { describe, expect, it } from 'vitest';
-import { shouldHandleMobileNormalSelectionPointerDown, shouldKeepCurrentSelectionOnMobileTap } from '../mobile-selection-render.service';
+import {
+ shouldHandleMobileNormalSelectionPointerDown,
+ shouldHandleMobileNormalSelectionPointerUp,
+} from '../mobile-selection-render.service';
describe('MobileSheetsSelectionRenderService', () => {
- it('keeps the current mobile selection when a tap stays inside an existing range', () => {
- expect(shouldKeepCurrentSelectionOnMobileTap(
- [{ startRow: 1, endRow: 3, startColumn: 1, endColumn: 3 }],
- { startRow: 2, endRow: 2, startColumn: 2, endColumn: 2 }
- )).toBe(true);
-
- expect(shouldKeepCurrentSelectionOnMobileTap(
- [{ startRow: 1, endRow: 3, startColumn: 1, endColumn: 3 }],
- { startRow: 4, endRow: 4, startColumn: 2, endColumn: 2 }
- )).toBe(false);
- });
-
it('lets the formula reference renderer own pointer down while reference selection is enabled', () => {
expect(shouldHandleMobileNormalSelectionPointerDown(true, false)).toBe(false);
expect(shouldHandleMobileNormalSelectionPointerDown(false, true)).toBe(false);
expect(shouldHandleMobileNormalSelectionPointerDown(false, false)).toBe(true);
});
+
+ it('does not finish a tap selection after a long press consumed the gesture', () => {
+ expect(shouldHandleMobileNormalSelectionPointerUp(false, false, true)).toBe(false);
+ expect(shouldHandleMobileNormalSelectionPointerUp(true, false, false)).toBe(false);
+ expect(shouldHandleMobileNormalSelectionPointerUp(false, true, false)).toBe(false);
+ expect(shouldHandleMobileNormalSelectionPointerUp(false, false, false)).toBe(true);
+ });
});
diff --git a/packages/sheets-ui/src/services/selection/__tests__/mobile-selection-render.service.spec.ts b/packages/sheets-ui/src/services/selection/__tests__/mobile-selection-render.service.spec.ts
index 6b4f737a9f..38d40ce2a9 100644
--- a/packages/sheets-ui/src/services/selection/__tests__/mobile-selection-render.service.spec.ts
+++ b/packages/sheets-ui/src/services/selection/__tests__/mobile-selection-render.service.spec.ts
@@ -29,7 +29,7 @@ import {
createTestEvent,
} from '../../../controllers/render-controllers/__tests__/render-test-bed';
import { SheetScrollManagerService } from '../../scroll-manager.service';
-import { MobileSheetsSelectionRenderService, shouldKeepCurrentSelectionOnMobileTap } from '../mobile-selection-render.service';
+import { MobileSheetsSelectionRenderService } from '../mobile-selection-render.service';
import { MobileSelectionControl } from '../mobile-selection-shape';
class TestThemeService {
@@ -154,7 +154,7 @@ function installCellLookupForMobileSelection(skeleton: ReturnType<typeof createF
(skeleton as never as { expandRangeByMerge: <T>(range: T) => T }).expandRangeByMerge = (range) => range;
}
-describe('shouldKeepCurrentSelectionOnMobileTap', () => {
+describe('MobileSheetsSelectionRenderService', () => {
beforeAll(() => {
globalThis.window = {
cancelAnimationFrame: () => { },
@@ -231,74 +231,14 @@ describe('shouldKeepCurrentSelectionOnMobileTap', () => {
testBed.univer.dispose();
});
- it('keeps the existing selection when a tap is inside it', () => {
- expect(shouldKeepCurrentSelectionOnMobileTap([
- {
- startRow: 1,
- endRow: 3,
- startColumn: 2,
- endColumn: 4,
- rangeType: RANGE_TYPE.NORMAL,
- },
- ], {
- startRow: 2,
- endRow: 2,
- startColumn: 3,
- endColumn: 3,
- rangeType: RANGE_TYPE.NORMAL,
- })).toBe(true);
- });
-
- it('does not keep the existing selection when a tap is outside it', () => {
- expect(shouldKeepCurrentSelectionOnMobileTap([
- {
- startRow: 1,
- endRow: 3,
- startColumn: 2,
- endColumn: 4,
- rangeType: RANGE_TYPE.NORMAL,
- },
- ], {
- startRow: 5,
- endRow: 5,
- startColumn: 5,
- endColumn: 5,
- rangeType: RANGE_TYPE.NORMAL,
- })).toBe(false);
- });
-
- it('checks all existing selections', () => {
- expect(shouldKeepCurrentSelectionOnMobileTap([
- {
- startRow: 1,
- endRow: 1,
- startColumn: 1,
- endColumn: 1,
- rangeType: RANGE_TYPE.NORMAL,
- },
- {
- startRow: 4,
- endRow: 6,
- startColumn: 4,
- endColumn: 6,
- rangeType: RANGE_TYPE.NORMAL,
- },
- ], {
- startRow: 5,
- endRow: 5,
- startColumn: 5,
- endColumn: 5,
- rangeType: RANGE_TYPE.NORMAL,
- })).toBe(true);
- });
-
it('positions mobile expand handles on normal selections', () => {
const control = createMobileControl(RANGE_TYPE.NORMAL);
- expect(control.fillControlTopLeft?.visible).toBe(true);
- expect(control.fillControlBottomRight?.visible).toBe(true);
- expect(control.fillControlTopLeft?.left).toBeLessThan(0);
- expect(control.fillControlBottomRight?.left).toBeGreaterThan(0);
+ expect(control.fillControl.visible).toBe(false);
+ expect(control.expandControlTopLeft?.visible).toBe(true);
+ expect(control.expandControlBottomRight?.visible).toBe(true);
+ expect(control.expandControlTopLeft?.left).toBeLessThan(0);
+ expect(control.expandControlBottomRight?.left).toBeGreaterThan(0);
expect(control.getViewportMainScrollInfo()).toMatchObject({
viewportScrollX: 0,
viewportScrollY: 0,
@@ -311,27 +251,27 @@ describe('shouldKeepCurrentSelectionOnMobileTap', () => {
const rowControl = createMobileControl(RANGE_TYPE.ROW);
rowControl.transformControlPoint(900, 0, 500, 500);
expect(rowControl.rangeType).toBe(RANGE_TYPE.ROW);
- expect(rowControl.fillControlTopLeft?.left).toBeLessThanOrEqual(500);
- expect(rowControl.fillControlBottomRight?.top).toBeGreaterThan(rowControl.fillControlTopLeft?.top ?? 0);
+ expect(rowControl.expandControlTopLeft?.left).toBeLessThanOrEqual(500);
+ expect(rowControl.expandControlBottomRight?.top).toBeGreaterThan(rowControl.expandControlTopLeft?.top ?? 0);
const columnControl = createMobileControl(RANGE_TYPE.COLUMN);
columnControl.transformControlPoint(0, 900, 500, 300);
expect(columnControl.rangeType).toBe(RANGE_TYPE.COLUMN);
- expect(columnControl.fillControlTopLeft?.top).toBeLessThanOrEqual(300);
- expect(columnControl.fillControlBottomRight?.left).toBeGreaterThan(columnControl.fillControlTopLeft?.left ?? 0);
+ expect(columnControl.expandControlTopLeft?.top).toBeLessThanOrEqual(300);
+ expect(columnControl.expandControlBottomRight?.left).toBeGreaterThan(columnControl.expandControlTopLeft?.left ?? 0);
});
it('keeps replacement mobile handles wired through disposal', () => {
const control = createMobileControl(RANGE_TYPE.NORMAL);
- const topLeft = control.fillControlTopLeft!;
- const bottomRight = control.fillControlBottomRight!;
+ const topLeft = control.expandControlTopLeft!;
+ const bottomRight = control.expandControlBottomRight!;
- control.fillControlTopLeft = topLeft;
- control.fillControlBottomRight = bottomRight;
+ control.expandControlTopLeft = topLeft;
+ control.expandControlBottomRight = bottomRight;
control.rangeType = RANGE_TYPE.ALL;
- expect(control.fillControlTopLeft).toBe(topLeft);
- expect(control.fillControlBottomRight).toBe(bottomRight);
+ expect(control.expandControlTopLeft).toBe(topLeft);
+ expect(control.expandControlBottomRight).toBe(bottomRight);
expect(control.rangeType).toBe(RANGE_TYPE.ALL);
control.dispose();
@@ -399,7 +339,7 @@ describe('shouldKeepCurrentSelectionOnMobileTap', () => {
const scrollManager = injector.get(SheetScrollManagerService) as never as TestSheetScrollManagerService;
scrollManager.validViewportScrollInfo$.next({ viewportScrollX: 240, viewportScrollY: 180 });
- expect(service.getActiveSelectionControl<MobileSelectionControl>()?.fillControlTopLeft?.left).toBeGreaterThan(0);
+ expect(service.getActiveSelectionControl<MobileSelectionControl>()?.expandControlTopLeft?.left).toBeGreaterThan(0);
const leftTopPlaceholder = context.components.get(SHEET_VIEW_KEY.LEFT_TOP)!;
let stopped = false;
@@ -446,7 +386,7 @@ describe('shouldKeepCurrentSelectionOnMobileTap', () => {
service.selectionMoving$.subscribe((selection) => movingSelections.push(selection));
const activeControl = service.getActiveSelectionControl<MobileSelectionControl>()!;
- activeControl.fillControlBottomRight!.onPointerDown$.emitEvent({ offsetX: 150, offsetY: 45 } as never);
+ activeControl.expandControlBottomRight!.onPointerDown$.emitEvent({ offsetX: 150, offsetY: 45 } as never);
expect(contextService.getContextValue('MOBILE_EXPANDING_SELECTION')).toBe(true);
(scene.onPointerMove$ as unknown as { emit: (evt: unknown, state?: unknown) => void }).emit({ offsetX: 360, offsetY: 90 });
@@ -456,6 +396,10 @@ describe('shouldKeepCurrentSelectionOnMobileTap', () => {
startColumn: 1,
endColumn: 3,
});
+ expect(service.getSelectionDataWithStyle()[0].primaryWithCoord).toMatchObject({
+ actualRow: 2,
+ actualColumn: 1,
+ });
expect(movingSelections.length).toBeGreaterThan(0);
(scene.onPointerUp$ as unknown as { emit: (evt: unknown, state?: unknown) => void }).emit({ offsetX: 360, offsetY: 90 });
@@ -553,21 +497,21 @@ describe('shouldKeepCurrentSelectionOnMobileTap', () => {
primary: null,
style: null,
}], SelectionMoveType.MOVE_END);
- spreadsheet.onPointerDown$.emit({ offsetX: 154, offsetY: 49, button: 0 }, {
+ spreadsheet.onPointerDown$.emit({ offsetX: 250, offsetY: 65, button: 0 }, {
stopPropagation: () => {
stopped = true;
},
});
- spreadsheet.onPointerUp$.emit({ offsetX: 154, offsetY: 49, button: 0 }, {
+ spreadsheet.onPointerUp$.emit({ offsetX: 250, offsetY: 65, button: 0 }, {
stopPropagation: () => {
stopped = true;
},
});
expect(service.getActiveRange()).toEqual({
- startRow: 2,
- endRow: 4,
- startColumn: 1,
- endColumn: 3,
+ startRow: 3,
+ endRow: 3,
+ startColumn: 2,
+ endColumn: 2,
});
expect(clearSelectedObjectsCount).toBe(2);
@@ -583,10 +527,10 @@ describe('shouldKeepCurrentSelectionOnMobileTap', () => {
},
});
expect(service.getActiveRange()).toEqual({
- startRow: 2,
- endRow: 4,
- startColumn: 1,
- endColumn: 3,
+ startRow: 3,
+ endRow: 3,
+ startColumn: 2,
+ endColumn: 2,
});
expect(clearSelectedObjectsCount).toBe(2);
contextService.setContextValue('MOBILE_PINCH_ZOOMING', false);
diff --git a/packages/sheets-ui/src/services/selection/mobile-selection-render.service.ts b/packages/sheets-ui/src/services/selection/mobile-selection-render.service.ts
index 2c6eca60b8..d9bc1ad653 100644
--- a/packages/sheets-ui/src/services/selection/mobile-selection-render.service.ts
+++ b/packages/sheets-ui/src/services/selection/mobile-selection-render.service.ts
@@ -35,7 +35,6 @@ import {
Inject,
Injector,
RANGE_TYPE,
- Rectangle,
ThemeService,
toDisposable,
} from '@univerjs/core';
@@ -43,7 +42,7 @@ import { ScrollTimer, ScrollTimerType, SHEET_VIEWPORT_KEY, Vector2 } from '@univ
import { attachSelectionWithCoord, convertSelectionDataToRange, REF_SELECTIONS_ENABLED, SelectionMoveType, SELECTIONS_ENABLED, SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';
import { IShortcutService } from '@univerjs/ui';
import { distinctUntilChanged, merge, startWith } from 'rxjs';
-import { MOBILE_EXPANDING_SELECTION, MOBILE_PINCH_ZOOMING } from '../../consts/mobile-context';
+import { MOBILE_EXPANDING_SELECTION, MOBILE_PINCH_ZOOMING, MOBILE_TRIGGER_CONTEXT_MENU } from '../../consts/mobile-context';
import { getCoordByOffset, getSheetObject } from '../../controllers/utils/component-tools';
import { isThisColSelected, isThisRowSelected } from '../../controllers/utils/selections-tools';
import { SheetScrollManagerService } from '../scroll-manager.service';
@@ -60,14 +59,18 @@ enum ExpandingControl {
BOTTOM = 'bottom',
}
-export function shouldKeepCurrentSelectionOnMobileTap(currentSelections: IRange[], targetRange: IRange): boolean {
- return currentSelections.some((selection) => Rectangle.contains(selection, targetRange));
-}
-
export function shouldHandleMobileNormalSelectionPointerDown(refSelectionsEnabled: boolean, pinchZooming: boolean): boolean {
return !refSelectionsEnabled && !pinchZooming;
}
+export function shouldHandleMobileNormalSelectionPointerUp(
+ refSelectionsEnabled: boolean,
+ pinchZooming: boolean,
+ contextMenuTriggered: boolean
+): boolean {
+ return !refSelectionsEnabled && !pinchZooming && !contextMenuTriggered;
+}
+
export class MobileSheetsSelectionRenderService extends BaseSelectionRenderService implements IRenderModule {
private readonly _workbookSelections: WorkbookSelectionModel;
private _renderDisposable: Nullable<IDisposable> = null;
@@ -246,9 +249,13 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
state.stopPropagation();
});
const spreadsheetPointerUpSub = spreadsheet?.onPointerUp$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
- if (this._normalSelectionDisabled()) return;
- // Don't create selection during pinch zoom
- if (this._contextService.getContextValue(MOBILE_PINCH_ZOOMING)) return;
+ if (!shouldHandleMobileNormalSelectionPointerUp(
+ this._normalSelectionDisabled(),
+ this._contextService.getContextValue(MOBILE_PINCH_ZOOMING),
+ this._contextService.getContextValue(MOBILE_TRIGGER_CONTEXT_MENU)
+ )) {
+ return;
+ }
const edge = 10;
if (Math.abs(evt.offsetX - pointerDownPos.x) > edge ||
@@ -344,16 +351,6 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
if (!selectCell) return;
scene.getTransformer()?.clearSelectedObjects();
- if (
- rangeType === RANGE_TYPE.NORMAL &&
- shouldKeepCurrentSelectionOnMobileTap(
- this._workbookSelections.getCurrentSelections().map((selection) => selection.range),
- selectCell
- )
- ) {
- return;
- }
-
switch (rangeType) {
case RANGE_TYPE.NORMAL:
break;
@@ -459,23 +456,23 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
}
})();
- control.fillControlTopLeft!.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent) => {
+ control.expandControlTopLeft!.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent) => {
this._expandingSelection = true;
this._contextService.setContextValue(MOBILE_EXPANDING_SELECTION, true);
this.expandingControlMode = expandingModeForTopLeft;
this._selectionMoveStart$.next(this.getSelectionDataWithStyle());
- this._fillControlPointerDownHandler(
+ this._expandControlPointerDownHandler(
evt,
rangeType,
this._activeViewport!
);
});
- control.fillControlBottomRight!.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent) => {
+ control.expandControlBottomRight!.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent) => {
this._expandingSelection = true;
this._contextService.setContextValue(MOBILE_EXPANDING_SELECTION, true);
this.expandingControlMode = expandingModeForBottomRight;
this._selectionMoveStart$.next(this.getSelectionDataWithStyle());
- this._fillControlPointerDownHandler(
+ this._expandControlPointerDownHandler(
evt,
rangeType,
this._activeViewport!
@@ -509,7 +506,7 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
return this._selectionControls;
}
- private _fillControlPointerDownHandler(
+ private _expandControlPointerDownHandler(
evt: IPointerEvent | IMouseEvent,
rangeType: RANGE_TYPE = RANGE_TYPE.NORMAL,
viewport?: Viewport,
@@ -747,7 +744,7 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
if (!newSelectionRange) {
return false;
}
- const newSelection: ISelectionWithStyle = { range: newSelectionRange, style: null, primary: null };
+ const newSelection: ISelectionWithStyle = { range: newSelectionRange, style: null, primary: undefined };
const newSelectionRangeWithCoord = attachSelectionWithCoord(newSelection, skeleton);
const rangeChanged =
diff --git a/packages/sheets-ui/src/services/selection/mobile-selection-shape.ts b/packages/sheets-ui/src/services/selection/mobile-selection-shape.ts
index 4d4949b398..1cf737630f 100644
--- a/packages/sheets-ui/src/services/selection/mobile-selection-shape.ts
+++ b/packages/sheets-ui/src/services/selection/mobile-selection-shape.ts
@@ -27,11 +27,11 @@ export class MobileSelectionControl extends SelectionControl {
/**
* topLeft controlPointer, it is not visible, just transparent, for handling event.
*/
- private _fillControlTopLeft: Rect | null;
+ private _expandControlTopLeft: Rect | null;
/**
* bottomRight controlPointer, it is not visible, just transparent, for handling event.
*/
- private _fillControlBottomRight: Rect | null;
+ private _expandControlBottomRight: Rect | null;
protected _rangeType: RANGE_TYPE = RANGE_TYPE.NORMAL;
@@ -39,9 +39,8 @@ export class MobileSelectionControl extends SelectionControl {
protected override _scene: Scene,
protected override _zIndex: number,
protected override readonly _themeService: ThemeService,
- options?: {
+ options: {
highlightHeader?: boolean;
- enableAutoFill?: boolean;
rowHeaderWidth: number;
columnHeaderHeight: number;
rowHeaderOffsetX?: number;
@@ -49,7 +48,7 @@ export class MobileSelectionControl extends SelectionControl {
rangeType?: RANGE_TYPE;
}
) {
- super(_scene, _zIndex, _themeService, options);
+ super(_scene, _zIndex, _themeService, { ...options, enableAutoFill: false });
this._rangeType = options?.rangeType || RANGE_TYPE.NORMAL;
this.initControlPoints();
}
@@ -58,43 +57,43 @@ export class MobileSelectionControl extends SelectionControl {
const defaultStyle = this.currentStyle;
const expandCornerSize = defaultStyle.expandCornerSize || 0;
const expandCornerInnerSize = (defaultStyle.expandCornerSize || 0) / 4;
- const AutofillStrokeWidth = defaultStyle.autofillStrokeWidth || 0;
+ const controlStrokeWidth = defaultStyle.autofillStrokeWidth || 0;
const stroke = defaultStyle.stroke!;
- const AutofillStroke = defaultStyle.autofillStroke!;
+ const controlStroke = defaultStyle.autofillStroke!;
const zIndex = this.zIndex;
// @transformControlPoint takes care of left & top
- this._fillControlTopLeft = new Rect(SELECTION_MANAGER_KEY.fillTopLeft + zIndex, {
+ this._expandControlTopLeft = new Rect(SELECTION_MANAGER_KEY.expandTopLeft + zIndex, {
zIndex: zIndex + 2,
width: expandCornerSize,
height: expandCornerSize,
radius: expandCornerSize / 2,
visualWidth: expandCornerInnerSize,
visualHeight: expandCornerInnerSize,
- strokeWidth: AutofillStrokeWidth,
+ strokeWidth: controlStrokeWidth,
});
- this._fillControlBottomRight = new Rect(SELECTION_MANAGER_KEY.fillBottomRight + zIndex, {
+ this._expandControlBottomRight = new Rect(SELECTION_MANAGER_KEY.expandBottomRight + zIndex, {
zIndex: zIndex + 2,
width: expandCornerSize,
height: expandCornerSize,
radius: expandCornerSize / 2,
visualHeight: expandCornerInnerSize,
visualWidth: expandCornerInnerSize,
- strokeWidth: AutofillStrokeWidth,
+ strokeWidth: controlStrokeWidth,
});
- const fillProps: IRectProps = {
+ const controlProps: IRectProps = {
fill: stroke,
- stroke: AutofillStroke,
+ stroke: controlStroke,
strokeScaleEnabled: false,
};
- this._fillControlTopLeft!.setProps({ ...fillProps });
- this._fillControlBottomRight!.setProps({ ...fillProps });
+ this._expandControlTopLeft!.setProps({ ...controlProps });
+ this._expandControlBottomRight!.setProps({ ...controlProps });
// put into scene
const objs = [
- this._fillControlTopLeft,
- this._fillControlBottomRight,
+ this._expandControlTopLeft,
+ this._expandControlBottomRight,
] as BaseObject[];
// do not use this.model.rangeType, model has not been initialized yet
@@ -113,20 +112,20 @@ export class MobileSelectionControl extends SelectionControl {
scene.addObjects(objs, SHEET_COMPONENT_SELECTION_LAYER_INDEX);
}
- get fillControlTopLeft(): Rect<IRectProps> | null {
- return this._fillControlTopLeft;
+ get expandControlTopLeft(): Rect<IRectProps> | null {
+ return this._expandControlTopLeft;
}
- set fillControlTopLeft(value: Rect) {
- this._fillControlTopLeft = value;
+ set expandControlTopLeft(value: Rect) {
+ this._expandControlTopLeft = value;
}
- get fillControlBottomRight(): Rect<IRectProps> | null {
- return this._fillControlBottomRight;
+ get expandControlBottomRight(): Rect<IRectProps> | null {
+ return this._expandControlBottomRight;
}
- set fillControlBottomRight(value: Rect) {
- this._fillControlBottomRight = value;
+ set expandControlBottomRight(value: Rect) {
+ this._expandControlBottomRight = value;
}
get rangeType(): RANGE_TYPE {
@@ -138,8 +137,8 @@ export class MobileSelectionControl extends SelectionControl {
}
override dispose(): void {
- this._fillControlBottomRight?.dispose();
- this._fillControlTopLeft?.dispose();
+ this._expandControlBottomRight?.dispose();
+ this._expandControlTopLeft?.dispose();
super.dispose();
}
@@ -160,16 +159,16 @@ export class MobileSelectionControl extends SelectionControl {
this.currentStyle = style;
// this condition is derived from selection-shape, I do not understand.
- if (this._enableAutoFill === true && !super._hasWidgets(widgets)) {
+ if (!super._hasWidgets(widgets)) {
const { viewportScrollX, viewportScrollY } = this.getViewportMainScrollInfo();
const { endX, endY } = this.selectionModel;
this.transformControlPoint(viewportScrollX, viewportScrollY, endX, endY);
- this.fillControlTopLeft!.show();
- this.fillControlBottomRight!.show();
+ this.expandControlTopLeft!.show();
+ this.expandControlBottomRight!.show();
} else {
- this.fillControlTopLeft?.hide();
- this.fillControlBottomRight?.hide();
+ this.expandControlTopLeft?.hide();
+ this.expandControlBottomRight?.hide();
}
}
@@ -203,11 +202,11 @@ export class MobileSelectionControl extends SelectionControl {
switch (rangeType) {
case RANGE_TYPE.NORMAL:
- this.fillControlTopLeft!.transformByState({
+ this.expandControlTopLeft!.transformByState({
left: -expandCornerSize / 2,
top: -expandCornerSize / 2,
});
- this.fillControlBottomRight!.transformByState({
+ this.expandControlBottomRight!.transformByState({
left: endX - startX - expandCornerSize / 2,
top: endY - startY - expandCornerSize / 2,
});
@@ -216,11 +215,11 @@ export class MobileSelectionControl extends SelectionControl {
case RANGE_TYPE.ROW: {
const left = Math.min(viewportW / 2 + viewportScrollX, sheetContentWidth);
const controlLeft = -expandCornerSize / 2 + left;
- this.fillControlTopLeft!.transformByState({
+ this.expandControlTopLeft!.transformByState({
left: controlLeft,
top: -expandCornerSize / 2,
});
- this.fillControlBottomRight!.transformByState({
+ this.expandControlBottomRight!.transformByState({
left: controlLeft,
top: -expandCornerSize / 2 + endY - startY,
});
@@ -231,11 +230,11 @@ export class MobileSelectionControl extends SelectionControl {
const top = Math.min(+viewportH / 2 + viewportScrollY, sheetContentHeight);
const controlTop = -expandCornerSize / 2 + top;
- this.fillControlTopLeft!.transformByState({
+ this.expandControlTopLeft!.transformByState({
left: -expandCornerSize / 2,
top: controlTop,
});
- this.fillControlBottomRight!.transformByState({
+ this.expandControlBottomRight!.transformByState({
left: -expandCornerSize / 2 + endX - startX,
top: controlTop,
});
diff --git a/packages/sheets-ui/src/services/selection/selection-control.ts b/packages/sheets-ui/src/services/selection/selection-control.ts
index d984ffcf1f..9e7d3d9f08 100644
--- a/packages/sheets-ui/src/services/selection/selection-control.ts
+++ b/packages/sheets-ui/src/services/selection/selection-control.ts
@@ -43,11 +43,8 @@ export enum SELECTION_MANAGER_KEY {
backgroundBottom = '__SpreadsheetSelectionBackgroundControlBottom__',
fill = '__SpreadsheetSelectionFillControl__',
- // fillTopLeft & fillBottomRight are used for mobile selection
- fillTopLeft = '__SpreadsheetSelectionFillControlTopLeft__',
- fillBottomRight = '__SpreadsheetSelectionFillControlBottomRight__',
- fillTopLeftInner = '__SpreadsheetSelectionFillControlTopLeftInner__',
- fillBottomRightInner = '__SpreadsheetSelectionFillControlBottomRightInner__',
+ expandTopLeft = '__SpreadsheetSelectionExpandControlTopLeft__',
+ expandBottomRight = '__SpreadsheetSelectionExpandControlBottomRight__',
lineMain = '__SpreadsheetDragLineMainControl__',
lineContent = '__SpreadsheetDragLineContentControl__',
diff --git a/packages/sheets-ui/src/views/auto-fill-popup-menu/AutoFillPopupMenu.tsx b/packages/sheets-ui/src/views/auto-fill-popup-menu/AutoFillPopupMenu.tsx
index 9876e70607..8fb3efa15a 100644
--- a/packages/sheets-ui/src/views/auto-fill-popup-menu/AutoFillPopupMenu.tsx
+++ b/packages/sheets-ui/src/views/auto-fill-popup-menu/AutoFillPopupMenu.tsx
@@ -41,7 +41,11 @@ export interface IAutoFillPopupMenuItem {
disable: boolean;
}
-export function AutoFillPopupMenu() {
+export interface IAutoFillPopupMenuProps {
+ DropdownMenuComponent?: typeof DropdownMenu;
+}
+
+export function AutoFillPopupMenu({ DropdownMenuComponent = DropdownMenu }: IAutoFillPopupMenuProps = {}) {
const commandService = useDependency(ICommandService);
const univerInstanceService = useDependency(IUniverInstanceService);
const renderManagerService = useDependency(IRenderManagerService);
@@ -168,7 +172,7 @@ export function AutoFillPopupMenu() {
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
- <DropdownMenu
+ <DropdownMenuComponent
align="start"
onCloseAutoFocus={(event) => {
event.preventDefault();
@@ -201,7 +205,7 @@ export function AutoFillPopupMenu() {
/>
{showMore && <MoreDownIcon className="dark:!univer-text-gray-0" />}
</div>
- </DropdownMenu>
+ </DropdownMenuComponent>
</div>
</div>
);
diff --git a/packages/sheets-ui/src/views/border-panel/BorderPanel.tsx b/packages/sheets-ui/src/views/border-panel/BorderPanel.tsx
index 47956f7d5d..e2c1171e50 100644
--- a/packages/sheets-ui/src/views/border-panel/BorderPanel.tsx
+++ b/packages/sheets-ui/src/views/border-panel/BorderPanel.tsx
@@ -42,7 +42,12 @@ function getBorderStyle(borderData: Nullable<IBorderData>): BorderStyleTypes | u
}
}
-export function BorderPanel(props: IBorderPanelProps) {
+export interface IResponsiveBorderPanelProps extends IBorderPanelProps {
+ ColorPickerComponent?: typeof ColorPicker;
+ DropdownComponent?: typeof Dropdown;
+}
+
+export function BorderPanel(props: IResponsiveBorderPanelProps) {
const iconManager = useDependency(IconManager);
const borderStyleManagerService = useDependency(BorderStyleManagerService);
const selectionManagerService = useDependency(SheetsSelectionsService);
@@ -52,7 +57,7 @@ export function BorderPanel(props: IBorderPanelProps) {
const color = isAllValuesSame ? getBorderColor(currentValue as Nullable<IBorderData>) : undefined;
const type = isAllValuesSame ? getBorderStyle(currentValue as Nullable<IBorderData>) : undefined;
- const { onChange, value } = props;
+ const { onChange, value, ColorPickerComponent = ColorPicker, DropdownComponent = Dropdown } = props;
function handleClick(v: string | number, type: keyof IBorderInfo) {
onChange?.({
@@ -100,10 +105,10 @@ export function BorderPanel(props: IBorderPanelProps) {
<div className="univer-flex univer-items-center univer-gap-2">
<div>
- <Dropdown
+ <DropdownComponent
overlay={(
<div className="univer-rounded-lg univer-p-4">
- <ColorPicker value={color} onChange={(value) => handleClick(value, 'color')} />
+ <ColorPickerComponent value={color} onChange={(value) => handleClick(value, 'color')} />
</div>
)}
>
@@ -125,11 +130,11 @@ export function BorderPanel(props: IBorderPanelProps) {
/>
<MoreDownIcon className="dark:!univer-text-gray-0" />
</button>
- </Dropdown>
+ </DropdownComponent>
</div>
<div>
- <Dropdown
+ <DropdownComponent
overlay={(
<section className="univer-rounded-lg univer-p-1.5">
<ul className="univer-m-0 univer-grid univer-list-none univer-gap-1 univer-p-0">
@@ -180,7 +185,7 @@ export function BorderPanel(props: IBorderPanelProps) {
/>
<MoreDownIcon className="dark:!univer-text-gray-0" />
</button>
- </Dropdown>
+ </DropdownComponent>
</div>
</div>
</section>
diff --git a/packages/sheets-ui/src/views/cell-alert/CellAlertPopup.tsx b/packages/sheets-ui/src/views/cell-alert/CellAlertPopup.tsx
index 86664b2185..c20033f7af 100644
--- a/packages/sheets-ui/src/views/cell-alert/CellAlertPopup.tsx
+++ b/packages/sheets-ui/src/views/cell-alert/CellAlertPopup.tsx
@@ -26,7 +26,12 @@ import { CellAlertType } from '../../services/cell-alert-manager.service';
* @param root0
* @param root0.popup
*/
-export function CellAlert({ popup }: { popup: ICanvasPopup }) {
+export interface ICellAlertProps {
+ popup: ICanvasPopup;
+ DropdownMenuComponent?: typeof DropdownMenu;
+}
+
+export function CellAlert({ popup, DropdownMenuComponent = DropdownMenu }: ICellAlertProps) {
const [visible, setVisible] = useState(false);
const [isHovered, setIsHovered] = useState(false);
const alert = popup.extraProps?.alert;
@@ -47,7 +52,7 @@ export function CellAlert({ popup }: { popup: ICanvasPopup }) {
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
>
- <DropdownMenu
+ <DropdownMenuComponent
align="start"
open={visible}
onOpenChange={setVisible}
@@ -92,7 +97,7 @@ export function CellAlert({ popup }: { popup: ICanvasPopup }) {
/>
)}
</button>
- </DropdownMenu>
+ </DropdownMenuComponent>
</div>
);
}
diff --git a/packages/sheets-ui/src/views/clipboard/ClipboardPopupMenu.tsx b/packages/sheets-ui/src/views/clipboard/ClipboardPopupMenu.tsx
index ac1a9b712d..6fa59adcb2 100644
--- a/packages/sheets-ui/src/views/clipboard/ClipboardPopupMenu.tsx
+++ b/packages/sheets-ui/src/views/clipboard/ClipboardPopupMenu.tsx
@@ -106,7 +106,11 @@ const useMenuPosition = (range?: IDiscreteRange) => {
};
};
-export const ClipboardPopupMenu = () => {
+export interface IClipboardPopupMenuProps {
+ DropdownMenuComponent?: typeof DropdownMenu;
+}
+
+export const ClipboardPopupMenu = ({ DropdownMenuComponent = DropdownMenu }: IClipboardPopupMenuProps = {}) => {
const clipboardService = useDependency(ISheetClipboardService);
const showMenu = useObservable(clipboardService.showMenu$, false);
// const clipboardController = useDependency(SheetClipboardController);
@@ -145,7 +149,7 @@ export const ClipboardPopupMenu = () => {
onMouseEnter={() => setMenuHovered(true)}
onMouseLeave={() => setMenuHovered(false)}
>
- <DropdownMenu
+ <DropdownMenuComponent
align="start"
items={SheetPasteOptions.map((item) => ({
type: 'checkbox',
@@ -175,7 +179,7 @@ export const ClipboardPopupMenu = () => {
/>
{showMore && <MoreDownIcon className="dark:!univer-text-gray-0" />}
</div>
- </DropdownMenu>
+ </DropdownMenuComponent>
</div>
</div>
);
diff --git a/packages/sheets-ui/src/views/defined-name/DefinedNameContainer.tsx b/packages/sheets-ui/src/views/defined-name/DefinedNameContainer.tsx
index e15f1fb646..0948096e85 100644
--- a/packages/sheets-ui/src/views/defined-name/DefinedNameContainer.tsx
+++ b/packages/sheets-ui/src/views/defined-name/DefinedNameContainer.tsx
@@ -37,7 +37,15 @@ import { useRef, useState } from 'react';
import { map, startWith } from 'rxjs';
import { DefinedNameInput } from './DefinedNameInput';
-export const DefinedNameContainer = () => {
+export interface IDefinedNameContainerProps {
+ ConfirmComponent?: typeof Confirm;
+ DefinedNameInputComponent?: typeof DefinedNameInput;
+}
+
+export const DefinedNameContainer = ({
+ ConfirmComponent = Confirm,
+ DefinedNameInputComponent = DefinedNameInput,
+}: IDefinedNameContainerProps = {}) => {
const commandService = useDependency(ICommandService);
const univerInstanceService = useDependency(IUniverInstanceService);
const localeService = useDependency(LocaleService);
@@ -254,7 +262,7 @@ export const DefinedNameContainer = () => {
<span className="univer-ml-1">{localeService.t<LocaleKey>('sheets-ui.definedName.addButton')}</span>
</Button>
{editState && (
- <DefinedNameInput
+ <DefinedNameInputComponent
confirm={insertConfirm}
cancel={closeInput}
state={editState}
@@ -364,16 +372,16 @@ export const DefinedNameContainer = () => {
)}
</div>
- <Confirm
+ <ConfirmComponent
visible={deleteConformKey === definedName.id}
onClose={handleDeleteClose}
onConfirm={() => { handleDeleteConfirm(definedName.id); }}
>
{localeService.t<LocaleKey>('sheets-ui.definedName.deleteConfirmText')}
- </Confirm>
+ </ConfirmComponent>
{definedName.id === editorKey && (
- <DefinedNameInput
+ <DefinedNameInputComponent
confirm={insertConfirm}
cancel={closeInput}
state={definedName.id === editorKey}
diff --git a/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsx b/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsx
index f0c6d5ce10..d5b58457e3 100644
--- a/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsx
+++ b/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsx
@@ -35,6 +35,7 @@ export interface IDefinedNameInputProps extends Omit<IDefinedNamesServiceParam,
confirm?: (param: IDefinedNamesServiceParam) => void;
cancel?: () => void;
id?: string;
+ SelectComponent?: typeof Select;
}
export const DefinedNameInput = (props: IDefinedNameInputProps) => {
@@ -57,6 +58,7 @@ function DefinedNameInputContent(props: IDefinedNameInputProps) {
localSheetId = SCOPE_WORKBOOK_VALUE_DEFINED_NAME,
hidden = false, // Whether to hide from users, compatible with Excel, not used for now.
id,
+ SelectComponent = Select,
} = props;
const univerInstanceService = useDependency(IUniverInstanceService);
const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
@@ -252,7 +254,7 @@ function DefinedNameInputContent(props: IDefinedNameInputProps) {
</div>
))}
<div>
- <Select
+ <SelectComponent
className="univer-w-full"
value={localSheetIdValue}
options={options}
diff --git a/packages/sheets-ui/src/views/dropdown/ColorDropdown.tsx b/packages/sheets-ui/src/views/dropdown/ColorDropdown.tsx
index e033341c76..1cc6a3421f 100644
--- a/packages/sheets-ui/src/views/dropdown/ColorDropdown.tsx
+++ b/packages/sheets-ui/src/views/dropdown/ColorDropdown.tsx
@@ -25,13 +25,14 @@ export interface IColorDropdownProps {
export function ColorDropdown(props: {
popup: IPopupWithExtraProps<IColorDropdownProps & IBaseDropdownProps>;
+ ColorPickerComponent?: typeof ColorPicker;
}) {
- const { popup } = props;
+ const { popup, ColorPickerComponent = ColorPicker } = props;
const { extraProps } = popup;
const { defaultValue, onChange } = extraProps;
return (
- <ColorPicker
+ <ColorPickerComponent
value={defaultValue}
onChange={onChange}
/>
diff --git a/packages/sheets-ui/src/views/editor-container/EditorContainer.tsx b/packages/sheets-ui/src/views/editor-container/EditorContainer.tsx
index ecbb8591d4..993af9a178 100644
--- a/packages/sheets-ui/src/views/editor-container/EditorContainer.tsx
+++ b/packages/sheets-ui/src/views/editor-container/EditorContainer.tsx
@@ -49,7 +49,6 @@ import {
SetCellEditVisibleOperation,
} from '../../commands/operations/cell-edit.operation';
import { EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY } from '../../common/keys';
-import { MOBILE_SHEET_FX_EDITOR } from '../../consts/mobile-context';
import { IEditorBridgeService } from '../../services/editor-bridge.service';
import { ICellEditorManagerService } from '../../services/editor/cell-editor-manager.service';
import { SheetCellEditorResizeService } from '../../services/editor/cell-editor-resize.service';
@@ -206,7 +205,11 @@ function isEmbedRuntimeEditorOrPopup(target: EventTarget | null | undefined): bo
* Cell editor container.
* @returns the rendered cell editor container.
*/
-export function EditorContainer() {
+export interface IEditorContainerProps {
+ hidden?: boolean;
+}
+
+export function EditorContainer({ hidden = false }: IEditorContainerProps) {
const [state, setState] = useState({
...EDITOR_DEFAULT_POSITION,
});
@@ -230,12 +233,6 @@ export function EditorContainer() {
undefined,
[contextService, DISABLE_AUTO_FOCUS_KEY]
);
- const mobileFxEditor = useObservable(
- () => contextService.subscribeContextValue$(MOBILE_SHEET_FX_EDITOR),
- contextService.getContextValue(MOBILE_SHEET_FX_EDITOR),
- undefined,
- [contextService]
- );
const FormulaEditor = componentManager.get(EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY);
const editState = useObservable(editorBridgeService.currentEditCellState$);
const workbook = editState
@@ -356,13 +353,13 @@ export function EditorContainer() {
}, [cellEditorResizeService, injector]);
useEffect(() => {
- if (!disableAutoFocus && !contextService.getContextValue(DISABLE_AUTO_FOCUS_KEY)) {
+ if (!hidden && !disableAutoFocus && !contextService.getContextValue(DISABLE_AUTO_FOCUS_KEY)) {
cellEditorManagerService.setFocus(true);
}
- }, [cellEditorManagerService, contextService, disableAutoFocus, state]);
+ }, [cellEditorManagerService, contextService, disableAutoFocus, hidden, state]);
useEffect(() => {
- if (!visible?.visible) {
+ if (hidden || !visible?.visible) {
return;
}
@@ -431,7 +428,7 @@ export function EditorContainer() {
ownerWindow.clearTimeout(delayedFocusTimer);
}
};
- }, [cellEditorResizeService, editorService, visible?.visible]);
+ }, [cellEditorResizeService, contextService, editorService, hidden, visible?.visible]);
useEffect(() => {
if (!visible?.visible || !rootRef.current || !focusCoordinator) {
@@ -636,7 +633,7 @@ export function EditorContainer() {
}, []);
const refocusEditorAfterPointerDown = useEvent((event: React.PointerEvent<HTMLDivElement>) => {
- if (!visible?.visible) {
+ if (hidden || !visible?.visible) {
return;
}
@@ -704,8 +701,8 @@ export function EditorContainer() {
top: state.top,
width: state.width,
height: state.height,
- opacity: mobileFxEditor ? 0 : undefined,
- pointerEvents: mobileFxEditor ? 'none' : undefined,
+ opacity: hidden ? 0 : undefined,
+ pointerEvents: hidden ? 'none' : undefined,
backgroundColor: getCellEditorHostBackgroundColor(editState, {
darkMode,
getColorFromTheme: themeService.getColorFromTheme.bind(themeService),
@@ -737,7 +734,7 @@ export function EditorContainer() {
`}
initValue=""
onChange={() => {}}
- isFocus={visible?.visible}
+ isFocus={!hidden && visible?.visible}
unitId={editState?.unitId}
subUnitId={editState?.sheetId}
keyboardEventConfig={keyCodeConfig}
diff --git a/packages/sheets-ui/src/views/editor-container/__tests__/EditorContainer.spec.tsx b/packages/sheets-ui/src/views/editor-container/__tests__/EditorContainer.spec.tsx
index 66e3cf634e..baef4bca1c 100644
--- a/packages/sheets-ui/src/views/editor-container/__tests__/EditorContainer.spec.tsx
+++ b/packages/sheets-ui/src/views/editor-container/__tests__/EditorContainer.spec.tsx
@@ -61,6 +61,7 @@ import { EditorContainer, shouldRefocusCellEditorAfterPointerDown } from '../Edi
let latestFormulaEditorProps: {
disableSelectionOnClick?: boolean;
+ isFocus?: boolean;
onFormulaSelectingChange?: (isSelecting: number, isFocusing: boolean) => void;
} | undefined;
@@ -236,9 +237,9 @@ function createTestBed(options: { disableAutoFocus?: boolean; docSelectionIsFocu
return { injector, editorBridgeService, focusCoordinator, interactionBoundaryService, docSelectionRenderService, cellEditorManagerService, cellEditorResizeService, validViewportScrollInfo$, activeSheet$, otherSheet };
}
-function renderEditorContainer(root: Root, injector: Injector): void {
- const ConnectedTestRoot = connectInjector(EditorContainer, injector) as ComponentType;
- root.render(<ConnectedTestRoot />);
+function renderEditorContainer(root: Root, injector: Injector, props: { hidden?: boolean } = {}): void {
+ const ConnectedTestRoot = connectInjector(EditorContainer, injector) as ComponentType<{ hidden?: boolean }>;
+ root.render(<ConnectedTestRoot {...props} />);
}
describe('EditorContainer embed focus lease', () => {
@@ -255,6 +256,24 @@ describe('EditorContainer embed focus lease', () => {
container = undefined;
});
+ it('keeps the cell editor mounted but non-interactive when hidden', async () => {
+ const { injector } = createTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await act(async () => {
+ renderEditorContainer(root!, injector, { hidden: true });
+ await Promise.resolve();
+ });
+
+ const editor = container.querySelector<HTMLElement>('[data-u-comp="editor"]');
+ expect(editor).not.toBeNull();
+ expect(editor?.style.opacity).toBe('0');
+ expect(editor?.style.pointerEvents).toBe('none');
+ expect(latestFormulaEditorProps?.isFocus).toBe(false);
+ });
+
it('holds a child-editor lease while the embedded sheet cell editor is visible', async () => {
const { injector, editorBridgeService, focusCoordinator, interactionBoundaryService } = createTestBed();
const selectionContainer = document.createElement('div');
diff --git a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
index 63dce80cf1..cd49cafae0 100644
--- a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
+++ b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
@@ -15,7 +15,6 @@
*/
import type { IUniverSheetsUIConfig } from '../../config/config';
-import type { LocaleKey } from '../../locale/types';
import type { IEditorBridgeServiceVisibleParam } from '../../services/editor-bridge.service';
import {
DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
@@ -23,7 +22,6 @@ import {
ICommandService,
IContextService,
IPermissionService,
- LocaleService,
} from '@univerjs/core';
import { borderBottomClassName, borderRightClassName, clsx } from '@univerjs/design';
import { IEditorService } from '@univerjs/docs-ui';
@@ -54,17 +52,12 @@ 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';
import { SHEETS_UI_PLUGIN_CONFIG_KEY } from '../../config/config';
-import {
- MOBILE_FORMULA_BAR_SUBMIT_COMMAND_ID,
- MOBILE_FORMULA_OPERATORS_VISIBLE,
-} from '../../consts/mobile-context';
import { SheetsUIPart } from '../../consts/ui-name';
import { IEditorBridgeService } from '../../services/editor-bridge.service';
import { IFormulaEditorManagerService } from '../../services/editor/formula-editor-manager.service';
import { DefinedName } from '../defined-name/DefinedName';
import { useKeyEventConfig } from '../editor-container/hooks';
import { useActiveWorkbook } from '../hook';
-import { MobileFormulaBarActions, MobileFormulaBarOverlays } from '../mobile/formula-bar/MobileFormulaBarControls';
enum ArrowDirection {
Down,
@@ -74,15 +67,11 @@ enum ArrowDirection {
interface IProps {
className?: string;
disableDefinedName?: boolean;
- mobile?: boolean;
- expanded?: boolean;
- onExpandedChange?: (expanded: boolean) => void;
}
export function FormulaBar(props: IProps) {
- const { className, disableDefinedName, expanded = false, mobile = false, onExpandedChange } = props;
+ const { className, disableDefinedName } = props;
const editorBridgeService = useDependency(IEditorBridgeService);
- const localeService = useDependency(LocaleService);
const iconActivated = useObservable(
() => editorBridgeService.visible$.pipe(map((visibleInfo) => visibleInfo.visible)),
false,
@@ -90,12 +79,6 @@ export function FormulaBar(props: IProps) {
[editorBridgeService]
);
const [arrowDirection, setArrowDirection] = useState<ArrowDirection>(ArrowDirection.Down);
- const [mobileFxRequest, setMobileFxRequest] = useState(0);
- const [mobileFunctionPanelRequest, setMobileFunctionPanelRequest] = useState(0);
- const [mobileFormulaActive, setMobileFormulaActive] = useState(false);
- const [mobileOperatorRequest, setMobileOperatorRequest] = useState({ id: 0, value: '' });
- const isExpanded = mobile ? expanded : arrowDirection === ArrowDirection.Up;
- const mobileFormulaOperatorsVisible = mobile && mobileFormulaActive && !isExpanded;
const formulaEditorManagerService = useDependency(IFormulaEditorManagerService);
const worksheetProtectionRuleModel = useDependency(WorksheetProtectionRuleModel);
const rangeProtectionRuleModel = useDependency(RangeProtectionRuleModel);
@@ -122,16 +105,6 @@ export function FormulaBar(props: IProps) {
useMemo(() => contextService.subscribeContextValue$(FOCUSING_FX_BAR_EDITOR), [contextService]),
contextService.getContextValue(FOCUSING_FX_BAR_EDITOR)
);
- useEffect(() => {
- if (mobile) {
- contextService.setContextValue(MOBILE_FORMULA_OPERATORS_VISIBLE, mobileFormulaOperatorsVisible);
- }
- }, [contextService, mobile, mobileFormulaOperatorsVisible]);
- useEffect(() => () => {
- if (mobile) {
- contextService.setContextValue(MOBILE_FORMULA_OPERATORS_VISIBLE, false);
- }
- }, [contextService, mobile]);
const workbookEditablePermission = useObservable(useMemo(() => {
if (!workbook) {
return undefined;
@@ -231,12 +204,6 @@ export function FormulaBar(props: IProps) {
}, [formulaEditorManagerService]);
function handleArrowClick() {
- if (mobile) {
- onExpandedChange?.(!isExpanded);
- setTimeout(() => formulaEditorManagerService.handleFoldBtnClick(isExpanded), 150);
- return;
- }
-
setArrowDirection(arrowDirection === ArrowDirection.Down ? ArrowDirection.Up : ArrowDirection.Down);
const ANIMATION_DURATION = 150;
@@ -256,19 +223,10 @@ export function FormulaBar(props: IProps) {
unitId: editState!.unitId,
});
}
- onExpandedChange?.(false);
}
// Handle click the "√" button.
- async function handleConfirmBtnClick() {
- if (mobile) {
- const submitted = await commandService.executeCommand(MOBILE_FORMULA_BAR_SUBMIT_COMMAND_ID);
- if (submitted) {
- onExpandedChange?.(false);
- }
- return;
- }
-
+ function handleConfirmBtnClick() {
const visibleState = editorBridgeService.isVisible();
if (visibleState.visible) {
commandService.executeCommand(SetCellEditVisibleOperation.id, {
@@ -277,19 +235,10 @@ export function FormulaBar(props: IProps) {
unitId: editState!.unitId,
});
}
- onExpandedChange?.(false);
}
function handlerFxBtnClick() {
- if (mobile) {
- const formulaEditor = editorService.getEditor(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);
- const formulaText = formulaEditor?.getDocumentData().body?.dataStream?.replace(/\r?\n$/, '') ?? '';
- if (formulaText.startsWith('=')) {
- setMobileFxRequest((value) => value + 1);
- setMobileFunctionPanelRequest((value) => value + 1);
- }
- }
- formulaEditorManagerService.handleFxBtnClick(mobile);
+ formulaEditorManagerService.handleFxBtnClick(true);
}
// TODO Is there a need to disable an editor here?
@@ -345,140 +294,89 @@ export function FormulaBar(props: IProps) {
const cellImage = isCellImage(editState?.documentLayoutObject.documentModel?.getSnapshot());
const hideEditor = cellImage || viewDisable;
- const cellStyle = editState
- ? workbook?.getSheetBySheetId(editState.sheetId)?.getCellStyle(editState.row, editState.column)
- : undefined;
- const editorBackground = mobile ? cellStyle?.bg?.rgb ?? undefined : undefined;
return (
<div
dir="ltr"
data-u-comp="formula-bar"
- data-expanded={isExpanded}
className={clsx(`
univer-box-border univer-flex univer-bg-gray-0 univer-text-gray-900 univer-transition-[height]
univer-ease-linear
dark:!univer-bg-gray-800
`, borderBottomClassName, className, {
- 'univer-relative': mobile,
- '!univer-h-12': mobile && !isExpanded,
- '!univer-h-full': mobile && isExpanded,
- 'univer-h-7': !mobile && !isExpanded,
- 'univer-h-20': !mobile && isExpanded,
+ 'univer-h-7': arrowDirection === ArrowDirection.Down,
+ 'univer-h-20': arrowDirection === ArrowDirection.Up,
'univer-pointer-events-none': editDisable,
})}
>
<div className="univer-relative univer-box-border univer-h-full univer-w-[100px]">
<DefinedName disable={disableDefinedName ?? editDisable} />
</div>
- {mobile && (
- <MobileFormulaBarOverlays
- expanded={isExpanded}
- formulaActive={mobileFormulaActive}
- operatorsVisible={mobileFormulaOperatorsVisible}
- editorId={DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY}
- onOperator={(value) => setMobileOperatorRequest(({ id }) => ({ id: id + 1, value }))}
- />
- )}
<div className="univer-flex univer-size-full">
- {mobile
- ? (
- <MobileFormulaBarActions
- expanded={isExpanded}
- cancelLabel={localeService.t<LocaleKey>('sheets-ui.button.cancel')}
- confirmLabel={localeService.t<LocaleKey>('sheets-ui.button.confirm')}
- formulaLabel={localeService.t<LocaleKey>('sheets-ui.mobile.formula')}
- collapseLabel={localeService.t<LocaleKey>('sheets-ui.mobile.collapseEditor')}
- onCancel={handleCloseBtnClick}
- onConfirm={handleConfirmBtnClick}
- onFormula={handlerFxBtnClick}
- onCollapse={handleArrowClick}
- />
- )
- : (
- <div
- className={clsx({
- 'univer-py-1.5': !mobile,
- 'univer-py-1': mobile,
- 'univer-cursor-not-allowed univer-text-gray-200': disabled,
+ <div className={clsx('univer-py-1.5', { 'univer-cursor-not-allowed univer-text-gray-200': disabled })}>
+ <div
+ data-u-comp="formula-bar-actions"
+ className={clsx(`
+ univer-relative univer-box-border univer-flex univer-h-full univer-w-20 univer-items-center
+ univer-justify-center univer-text-xs
+ `, borderRightClassName)}
+ >
+ {/* TODO: use buttons to replace these re-implementation of buttons. */}
+ <span
+ className={clsx(`
+ univer-flex univer-items-center univer-justify-center univer-rounded univer-p-1
+ univer-text-base
+ dark:!univer-text-gray-0
+ `, {
+ 'univer-cursor-pointer univer-text-red-600 hover:univer-bg-gray-100 dark:!univer-text-green-400 dark:hover:!univer-bg-gray-700': iconActivated,
})}
+ onClick={handleCloseBtnClick}
>
- <div
- data-u-comp="formula-bar-actions"
- className={clsx(`
- univer-relative univer-box-border univer-flex univer-h-full univer-w-20
- univer-items-center univer-justify-center univer-text-xs
- `, borderRightClassName, { '!univer-w-32': mobile })}
- >
- {/* TODO: use buttons to replace these re-implementation of buttons. */}
- <span
- className={clsx(`
- univer-flex univer-items-center univer-justify-center univer-rounded univer-p-1
- univer-text-base
- dark:!univer-text-gray-0
- `, {
- 'univer-cursor-pointer univer-text-red-600 hover:univer-bg-gray-100 dark:!univer-text-green-400 dark:hover:!univer-bg-gray-700': iconActivated,
- })}
- onClick={handleCloseBtnClick}
- >
- <CloseIcon />
- </span>
- <span
- className={clsx(`
- univer-flex univer-items-center univer-justify-center univer-rounded univer-p-1
- univer-text-base
- dark:!univer-text-gray-0
- `, {
- 'univer-cursor-pointer univer-text-green-600 hover:univer-bg-gray-100 dark:!univer-text-red-400 dark:hover:!univer-bg-gray-700': iconActivated,
- })}
- onClick={handleConfirmBtnClick}
- >
- <CheckMarkIcon />
- </span>
- <span
- className={`
- univer-flex univer-cursor-pointer univer-items-center univer-justify-center
- univer-rounded univer-p-1 univer-text-base
- hover:univer-bg-gray-100
- dark:!univer-text-gray-0
- dark:hover:!univer-bg-gray-700
- `}
- onClick={handlerFxBtnClick}
- >
- <FxIcon />
- </span>
- </div>
- </div>
- )}
+ <CloseIcon />
+ </span>
+ <span
+ className={clsx(`
+ univer-flex univer-items-center univer-justify-center univer-rounded univer-p-1
+ univer-text-base
+ dark:!univer-text-gray-0
+ `, {
+ 'univer-cursor-pointer univer-text-green-600 hover:univer-bg-gray-100 dark:!univer-text-red-400 dark:hover:!univer-bg-gray-700': iconActivated,
+ })}
+ onClick={handleConfirmBtnClick}
+ >
+ <CheckMarkIcon />
+ </span>
+ <span
+ className={`
+ univer-flex univer-cursor-pointer univer-items-center univer-justify-center univer-rounded
+ univer-p-1 univer-text-base
+ hover:univer-bg-gray-100
+ dark:!univer-text-gray-0
+ dark:hover:!univer-bg-gray-700
+ `}
+ onClick={handlerFxBtnClick}
+ >
+ <FxIcon />
+ </span>
+ </div>
+ </div>
- <div
- className={clsx(
- 'univer-flex univer-w-full univer-flex-1 univer-overflow-hidden',
- {
- 'univer-pl-3': !mobile,
- 'univer-pt-24': mobile && isExpanded,
- }
- )}
- >
+ <div className="univer-flex univer-w-full univer-flex-1 univer-overflow-hidden univer-pl-3">
<div
ref={ref}
- className={clsx(`
+ className="
univer-relative univer-flex-1 univer-bg-gray-0
dark:!univer-bg-gray-800
- `, {
- 'univer-box-border univer-pl-2': mobile,
- 'univer-my-2': mobile && !isExpanded,
- })}
+ "
onPointerDown={handlePointerDown}
onPointerUp={handlePointerUp}
- style={{ backgroundColor: editorBackground, pointerEvents: hideEditor ? 'none' : 'auto' }}
+ style={{ pointerEvents: hideEditor ? 'none' : 'auto' }}
>
{FormulaEditor && (
<FormulaEditor
className="univer-relative univer-size-full univer-break-words univer-outline-none"
borderless
- canvasStyle={{ backgroundColor: editorBackground }}
disableSelectionOnClick
editorId={DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY}
initValue=""
@@ -500,11 +398,6 @@ export function FormulaBar(props: IProps) {
}}
autoScrollbar={false}
disableContextMenu={false}
- mobile={mobile}
- mobileFxRequest={mobileFxRequest}
- mobileFunctionPanelRequest={mobileFunctionPanelRequest}
- mobileOperatorRequest={mobileOperatorRequest}
- onMobileFormulaActiveChange={setMobileFormulaActive}
/>
)}
{/* Cover the hidden editor instead of re-instantiating the formula editor. */}
@@ -518,27 +411,20 @@ export function FormulaBar(props: IProps) {
/>
)}
</div>
- {(!mobile || !isExpanded) && (
- <div
- data-u-comp="formula-bar-expand"
- className={clsx(`
- univer-flex univer-h-full univer-w-5 univer-cursor-pointer univer-items-center
- univer-justify-center univer-text-xs univer-text-gray-700
- dark:!univer-text-gray-200
- `, {
- 'univer-w-10': mobile,
- 'univer-cursor-not-allowed univer-text-gray-200 dark:!univer-text-gray-700': editDisable,
+ <div
+ className={clsx(`
+ univer-flex univer-h-full univer-w-5 univer-cursor-pointer univer-items-center
+ univer-justify-center univer-text-xs univer-text-gray-700
+ dark:!univer-text-gray-200
+ `, { 'univer-cursor-not-allowed univer-text-gray-200 dark:!univer-text-gray-700': editDisable })}
+ onClick={handleArrowClick}
+ >
+ <DownIcon
+ className={clsx({
+ 'univer-rotate-180': arrowDirection === ArrowDirection.Up,
})}
- onClick={handleArrowClick}
- >
- <DownIcon
- className={clsx({
- 'univer-size-5 univer-rotate-180': mobile,
- 'univer-rotate-180': !mobile && isExpanded,
- })}
- />
- </div>
- )}
+ />
+ </div>
</div>
</div>
diff --git a/packages/sheets-ui/src/views/formula-bar/__tests__/FormulaBar.spec.tsx b/packages/sheets-ui/src/views/formula-bar/__tests__/FormulaBar.spec.tsx
index 06caf0ea2b..38fd1c7f37 100644
--- a/packages/sheets-ui/src/views/formula-bar/__tests__/FormulaBar.spec.tsx
+++ b/packages/sheets-ui/src/views/formula-bar/__tests__/FormulaBar.spec.tsx
@@ -208,10 +208,17 @@ class TestLayoutService {
}
function TestFormulaEditor(props: {
+ canvasStyle?: { backgroundColor?: string };
editorId: string;
unitId?: string;
}) {
- return <div data-editor-id={props.editorId} data-unit-id={props.unitId} />;
+ return (
+ <div
+ data-canvas-background={props.canvasStyle?.backgroundColor}
+ data-editor-id={props.editorId}
+ data-unit-id={props.unitId}
+ />
+ );
}
function createWorkbookData(cellStyle?: IStyleData): IWorkbookData {
@@ -446,9 +453,25 @@ describe('FormulaBar', () => {
});
});
+ it('enters formula mode when the desktop fx button is clicked', async () => {
+ currentBed = createFormulaBarTestBed();
+ const forceFormulaMode: boolean[] = [];
+ const subscription = currentBed.injector.get(IFormulaEditorManagerService).fxBtnClick$.subscribe((value) => {
+ forceFormulaMode.push(value);
+ });
+ const rendered = renderWithDependencies(<FormulaBar disableDefinedName />, currentBed.injector);
+ root = rendered.root;
+ container = rendered.container;
+
+ await clickElement(getActionElement(rendered.container, 2));
+
+ expect(forceFormulaMode).toEqual([true]);
+ subscription.unsubscribe();
+ });
+
it('commits and moves down from the compact mobile formula bar', async () => {
currentBed = createFormulaBarTestBed();
- const rendered = renderWithDependencies(<FormulaBar disableDefinedName mobile />, currentBed.injector);
+ const rendered = renderWithDependencies(<MobileFormulaBar />, currentBed.injector);
root = rendered.root;
container = rendered.container;
@@ -461,26 +484,23 @@ describe('FormulaBar', () => {
expect(currentBed.editorBridgeService.visibleHistory.at(-1)?.visible).toBe(true);
});
- it('inherits the selected cell background in the mobile editor', () => {
+ it('renders the selected cell background on the mobile editor host without locking the canvas color', () => {
currentBed = createFormulaBarTestBed({
bg: { rgb: '#000000' },
cl: { rgb: '#0000FF' },
});
- const rendered = renderWithDependencies(<FormulaBar disableDefinedName mobile />, currentBed.injector);
+ const rendered = renderWithDependencies(<MobileFormulaBar />, currentBed.injector);
root = rendered.root;
container = rendered.container;
const editorHost = rendered.container.querySelector('[data-editor-id]')?.parentElement;
expect(editorHost?.style.backgroundColor).toBe('#000000');
+ expect(rendered.container.querySelector('[data-editor-id]')?.getAttribute('data-canvas-background')).toBeNull();
});
it('opens immersive mobile editing from the compact up arrow', async () => {
currentBed = createFormulaBarTestBed();
- const onExpandedChange = vi.fn();
- const rendered = renderWithDependencies(
- <FormulaBar disableDefinedName mobile onExpandedChange={onExpandedChange} />,
- currentBed.injector
- );
+ const rendered = renderWithDependencies(<MobileFormulaBar />, currentBed.injector);
root = rendered.root;
container = rendered.container;
@@ -491,36 +511,35 @@ describe('FormulaBar', () => {
if (!expandButton) throw new Error('Expected the formula bar expand button to be rendered.');
await clickElement(expandButton);
- expect(onExpandedChange).toHaveBeenCalledWith(true);
+ expect(rendered.container.querySelector('[data-u-comp="mobile-formula-bar"]')?.getAttribute('data-expanded')).toBe('true');
});
it('commits, moves down, and collapses immersive mobile editing', async () => {
currentBed = createFormulaBarTestBed();
- const onExpandedChange = vi.fn();
- const rendered = renderWithDependencies(
- <FormulaBar disableDefinedName expanded mobile onExpandedChange={onExpandedChange} />,
- currentBed.injector
- );
+ const rendered = renderWithDependencies(<MobileFormulaBar />, currentBed.injector);
root = rendered.root;
container = rendered.container;
+ const expandButton = rendered.container.querySelector<HTMLElement>('[data-u-comp="formula-bar-expand"]');
+ if (!expandButton) throw new Error('Expected the formula bar expand button to be rendered.');
+ await clickElement(expandButton);
await clickElement(getActionElement(rendered.container, 1));
expect(currentBed.mobileSubmit).toHaveBeenCalledOnce();
expect(currentBed.editorBridgeService.visibleHistory.at(-1)?.visible).toBe(true);
- expect(onExpandedChange).toHaveBeenCalledWith(false);
+ expect(rendered.container.querySelector('[data-u-comp="mobile-formula-bar"]')?.getAttribute('data-expanded')).toBe('false');
});
- it('fills the mobile viewport while the formula bar is expanded', () => {
+ it('fills the mobile viewport while the formula bar is expanded', async () => {
currentBed = createFormulaBarTestBed();
- const onExpandedChange = vi.fn();
- const rendered = renderWithDependencies(
- <FormulaBar disableDefinedName expanded mobile onExpandedChange={onExpandedChange} />,
- currentBed.injector
- );
+ const rendered = renderWithDependencies(<MobileFormulaBar />, currentBed.injector);
root = rendered.root;
container = rendered.container;
+ const expandButton = rendered.container.querySelector<HTMLElement>('[data-u-comp="formula-bar-expand"]');
+ if (!expandButton) throw new Error('Expected the formula bar expand button to be rendered.');
+ await clickElement(expandButton);
+
const formulaBar = rendered.container.querySelector('[data-u-comp="formula-bar"]');
const editorHost = rendered.container.querySelector('[data-editor-id]')?.parentElement;
expect(formulaBar?.getAttribute('data-expanded')).toBe('true');
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 0f1c120aec..ae36fac15d 100644
--- a/packages/sheets-ui/src/views/mobile/action-panel/MobileSheetActionPanel.tsx
+++ b/packages/sheets-ui/src/views/mobile/action-panel/MobileSheetActionPanel.tsx
@@ -139,6 +139,22 @@ export function getMobileMenuCommand(params: IValueOption | IMobileStyleCommand)
}
export function MobileSheetActionPanel() {
+ const contextService = useDependency(IContextService);
+ const focusingDrawing = useObservable(
+ () => contextService.subscribeContextValue$(FOCUSING_COMMON_DRAWINGS).pipe(map(Boolean)),
+ Boolean(contextService.getContextValue(FOCUSING_COMMON_DRAWINGS)),
+ false,
+ [contextService]
+ );
+
+ if (focusingDrawing) {
+ return null;
+ }
+
+ return <MobileSheetActionPanelContent />;
+}
+
+function MobileSheetActionPanelContent() {
const workbook = useActiveWorkbook();
const commandService = useDependency(ICommandService);
const contextService = useDependency(IContextService);
@@ -180,12 +196,6 @@ export function MobileSheetActionPanel() {
false,
[contextService]
);
- const focusingDrawing = useObservable(
- () => contextService.subscribeContextValue$(FOCUSING_COMMON_DRAWINGS).pipe(map(Boolean)),
- Boolean(contextService.getContextValue(FOCUSING_COMMON_DRAWINGS)),
- false,
- [contextService]
- );
const [activeTab, setActiveTab] = useState<MobileSheetPanelTab>('insert');
const [toolsOpen, setToolsOpen] = useState(false);
const [drawerSnap, setDrawerSnap] = useState<MobileDrawerSnap>('compact');
@@ -299,7 +309,7 @@ export function MobileSheetActionPanel() {
if (contentRef.current) contentRef.current.scrollTop = 0;
}, [activeTab, menuNavigation?.title, styleViewStack.length]);
- if (!workbook || focusingDrawing) {
+ if (!workbook) {
return null;
}
@@ -347,14 +357,21 @@ export function MobileSheetActionPanel() {
}).catch(() => undefined);
}
- function executeMenuItem(params: IValueOption | IMobileStyleCommand) {
+ function executeMenuItem(params: IValueOption | IMobileStyleCommand): boolean {
const command = getMobileMenuCommand(params);
if (!command) {
- return;
+ return false;
}
ensureSelectionPrimary();
- commandService.executeCommand(command.commandId, command.commandParams);
+ commandService.executeCommand(command.commandId, command.commandParams).catch(() => undefined);
+ return true;
+ }
+
+ function executeMenuItemAndClose(params: IValueOption | IMobileStyleCommand) {
+ if (executeMenuItem(params)) {
+ closeTools();
+ }
}
if (editing) {
@@ -520,7 +537,7 @@ export function MobileSheetActionPanel() {
menuManagerService={menuManagerService}
showHeader={false}
onNavigationChange={handleInsertNavigation}
- onOptionSelect={executeMenuItem}
+ onOptionSelect={executeMenuItemAndClose}
/>
)}
{activeTab === 'style' && (
@@ -533,7 +550,10 @@ export function MobileSheetActionPanel() {
setStyleViewStack((stack) => [...stack, view]);
}}
onBack={() => setStyleViewStack((stack) => stack.slice(0, -1))}
- onExecute={executeMenuItem}
+ onExecute={currentStyleView?.kind === 'number-format' ||
+ currentStyleView?.kind === 'custom-number-format'
+ ? executeMenuItemAndClose
+ : executeMenuItem}
onUseColor={(color) => setRecentColors((colors) => [
color,
...colors.filter((item) => item.toUpperCase() !== color.toUpperCase()),
@@ -548,7 +568,7 @@ export function MobileSheetActionPanel() {
menuManagerService={menuManagerService}
showHeader={false}
onNavigationChange={handleDataNavigation}
- onOptionSelect={executeMenuItem}
+ onOptionSelect={executeMenuItemAndClose}
/>
)}
{(!menuNavigation || menuNavigation.source === 'operation') && (
@@ -557,7 +577,7 @@ export function MobileSheetActionPanel() {
menuManagerService={menuManagerService}
showHeader={false}
onNavigationChange={handleOperationNavigation}
- onOptionSelect={executeMenuItem}
+ onOptionSelect={executeMenuItemAndClose}
/>
)}
</div>
diff --git a/packages/sheets-ui/src/views/mobile/action-panel/MobileStylePanel.tsx b/packages/sheets-ui/src/views/mobile/action-panel/MobileStylePanel.tsx
index bb93d23264..79eb4dd60f 100644
--- a/packages/sheets-ui/src/views/mobile/action-panel/MobileStylePanel.tsx
+++ b/packages/sheets-ui/src/views/mobile/action-panel/MobileStylePanel.tsx
@@ -19,7 +19,7 @@ import type { IDisplayMenuItem, IFontConfig, IMenuItem, IMenuSchema, IMenuSelect
import type { LocaleKey } from '../../../locale/types';
import { BorderStyleTypes, BorderType, LocaleService, ThemeService } from '@univerjs/core';
import { borderBottomClassName, clsx, ColorPickerPanel, MobileActionRow, MobileColorPresets, resetButtonClassName } from '@univerjs/design';
-import { CheckMarkIcon, MoreRightIcon, NoColorDoubleIcon } from '@univerjs/icons';
+import { CheckMarkIcon, MoreDownIcon, MoreRightIcon, NoColorDoubleIcon } from '@univerjs/icons';
import {
AddWorksheetMergeCommand,
ResetBackgroundColorCommand,
@@ -32,6 +32,7 @@ import {
SetVerticalTextAlignCommand,
} from '@univerjs/sheets';
import {
+ ComponentManager,
IconManager,
IFontService,
MenuItemType,
@@ -93,6 +94,7 @@ interface IMobileNumberFormatMenuConfig {
commandId: string;
detailTitle: string;
customTitle: string;
+ customComponent: string;
quickOptions: IMobileNumberFormatOption[];
decimalOptions: IMobileNumberFormatOption[];
detailOptions: IMobileNumberFormatOption[];
@@ -100,11 +102,11 @@ interface IMobileNumberFormatMenuConfig {
}
export type MobileNumberFormatItem = IDisplayMenuItem<IMenuSelectorItem<string, MenuItemDefaultValueType, unknown>> & {
- mobileStyle?: IMobileNumberFormatMenuConfig;
+ mobileNumberFormat?: IMobileNumberFormatMenuConfig;
};
type ConfiguredMobileNumberFormatItem = MobileNumberFormatItem & {
- mobileStyle: IMobileNumberFormatMenuConfig;
+ mobileNumberFormat: IMobileNumberFormatMenuConfig;
};
type MenuSchemaWithItem = IMenuSchema & {
@@ -298,7 +300,7 @@ function MobileStyleRoot(props: {
schema.item.id === SetTextRotationCommand.id && isMobileSelectorItem(schema.item));
const mergeSchema = items.find((schema) => schema.item.id === AddWorksheetMergeCommand.id);
const numberFormatSchema = items.find(isMobileNumberFormatSchema);
- const numberFormatConfig = numberFormatSchema?.item.mobileStyle;
+ const numberFormatConfig = numberFormatSchema?.item.mobileNumberFormat;
const numberFormatCommandIds = new Set([
...(numberFormatConfig?.quickOptions ?? []),
...(numberFormatConfig?.decimalOptions ?? []),
@@ -506,7 +508,7 @@ function MobileNumberFormatGroup(props: {
}) {
const { schemas, schema, onOpenView, onExecute } = props;
const item = schema.item;
- const config = item.mobileStyle;
+ const config = item.mobileNumberFormat;
const localeService = useDependency(LocaleService);
const status = useToolbarItemStatus(item);
@@ -705,88 +707,21 @@ function MobileCustomNumberFormat(props: {
onExecute: (params: IMobileStyleCommand) => void;
}) {
const { config, onBack, onExecute } = props;
- const localeService = useDependency(LocaleService);
- const [pattern, setPattern] = useState('');
- const title = localeService.t(config.customTitle);
+ const componentManager = useDependency(ComponentManager);
+ const CustomFormat = componentManager.get(config.customComponent);
+
+ if (!CustomFormat) {
+ return null;
+ }
return (
- <div className="univer-grid univer-gap-3">
- <div className="univer-grid univer-gap-2">
- <label
- className="
- univer-px-1 univer-text-xs univer-font-medium univer-text-gray-500
- dark:!univer-text-gray-400
- "
- >
- {title}
- </label>
- <input
- aria-label={title}
- value={pattern}
- placeholder={title}
- className="
- univer-h-11 univer-w-full univer-rounded-xl univer-border univer-border-solid
- univer-border-gray-200 univer-bg-gray-0 univer-px-3 univer-text-sm univer-text-gray-900
- univer-outline-none
- focus:univer-border-primary-500
- dark:!univer-border-gray-700 dark:!univer-bg-gray-800 dark:!univer-text-gray-100
- "
- onChange={(event) => setPattern(event.target.value)}
- />
- </div>
- <div
- className="
- univer-overflow-hidden univer-rounded-xl univer-bg-gray-0
- dark:!univer-bg-gray-800
- "
- >
- {config.customPatterns.map((item, index) => (
- <button
- key={item}
- type="button"
- aria-label={item}
- aria-pressed={pattern === item}
- className={clsx(resetButtonClassName, `
- univer-flex univer-min-h-11 univer-w-full univer-items-center univer-gap-3 univer-px-4
- univer-text-left univer-text-gray-900
- active:univer-bg-gray-100
- dark:!univer-text-gray-100
- dark:active:!univer-bg-gray-700
- `, index !== config.customPatterns.length - 1 && borderBottomClassName)}
- onClick={() => setPattern(item)}
- >
- <span className="univer-min-w-0 univer-flex-1 univer-truncate univer-font-mono univer-text-xs">
- {item}
- </span>
- {pattern === item && <CheckMarkIcon className="univer-shrink-0 univer-text-primary-600" />}
- </button>
- ))}
- </div>
- <button
- type="button"
- disabled={!pattern.trim()}
- className={clsx(resetButtonClassName, `
- univer-min-h-11 univer-w-full univer-rounded-xl univer-bg-primary-600 univer-px-4 univer-text-sm
- univer-font-medium univer-text-gray-0
- active:univer-bg-primary-700
- disabled:univer-opacity-40
- `)}
- onClick={() => {
- onExecute({ id: config.commandId, value: pattern.trim() });
- onBack();
- }}
- >
- {localeService.t<LocaleKey>('sheets-ui.mobile.confirm')}
- </button>
- <div
- className="
- univer-px-1 univer-text-xs univer-text-gray-500
- dark:!univer-text-gray-400
- "
- >
- {localeService.t<LocaleKey>('sheets-ui.mobile.customFormatDescription')}
- </div>
- </div>
+ <CustomFormat
+ patterns={config.customPatterns}
+ onConfirm={(pattern: string) => {
+ onExecute({ id: config.commandId, value: pattern });
+ onBack();
+ }}
+ />
);
}
@@ -974,8 +909,8 @@ function MobileStyleRootItem(props: { schema: MenuSchemaWithItem; onOpenView: (v
aria-label={title}
disabled={status.disabled}
className={clsx(resetButtonClassName, `
- univer-flex univer-min-h-12 univer-items-center univer-justify-center univer-rounded
- univer-text-gray-900
+ univer-flex univer-min-h-12 univer-items-center univer-justify-center univer-gap-1 univer-rounded
+ univer-px-2 univer-text-gray-900
active:univer-bg-gray-100
disabled:univer-opacity-40
dark:!univer-text-gray-100
@@ -991,10 +926,16 @@ function MobileStyleRootItem(props: { schema: MenuSchemaWithItem; onOpenView: (v
{Icon
? <Icon />
: (
- <span className="univer-max-w-full univer-truncate univer-px-1 univer-text-sm">
+ <span className="univer-min-w-0 univer-truncate univer-text-sm">
{String(displayValue ?? title)}
</span>
)}
+ <MoreDownIcon
+ className="
+ univer-shrink-0 univer-text-gray-500
+ dark:!univer-text-gray-400
+ "
+ />
</button>
);
}
@@ -1445,9 +1386,9 @@ function isMobileSelectorSchema(schema: MenuSchemaWithItem): schema is SelectorM
function isMobileNumberFormatSchema(
schema: MenuSchemaWithItem
): schema is MenuSchemaWithItem & { item: ConfiguredMobileNumberFormatItem } {
- if (!isMobileSelectorItem(schema.item) || !('mobileStyle' in schema.item)) return false;
+ if (!isMobileSelectorItem(schema.item) || !('mobileNumberFormat' in schema.item)) return false;
- const config = schema.item.mobileStyle;
+ const config = schema.item.mobileNumberFormat;
if (!config || typeof config !== 'object') return false;
return 'kind' in config
@@ -1460,6 +1401,8 @@ function isMobileNumberFormatSchema(
&& typeof config.detailTitle === 'string'
&& 'customTitle' in config
&& typeof config.customTitle === 'string'
+ && 'customComponent' in config
+ && typeof config.customComponent === 'string'
&& 'quickOptions' in config
&& Array.isArray(config.quickOptions)
&& 'decimalOptions' in config
diff --git a/packages/sheets-ui/src/views/mobile/action-panel/__tests__/MobileSheetActionPanel.spec.ts b/packages/sheets-ui/src/views/mobile/action-panel/__tests__/MobileSheetActionPanel.spec.ts
index 0e47770c62..5428add09c 100644
--- a/packages/sheets-ui/src/views/mobile/action-panel/__tests__/MobileSheetActionPanel.spec.ts
+++ b/packages/sheets-ui/src/views/mobile/action-panel/__tests__/MobileSheetActionPanel.spec.ts
@@ -14,15 +14,295 @@
* limitations under the License.
*/
-import { describe, expect, it } from 'vitest';
+import type { IMenuSchema } from '@univerjs/ui';
+import type { Root } from 'react-dom/client';
+import type { MobileNumberFormatItem } from '../MobileStylePanel';
+import {
+ CommandType,
+ FOCUSING_COMMON_DRAWINGS,
+ getSheetsEmptySnapshot,
+ ICommandService,
+ IContextService,
+ IUniverInstanceService,
+ LocaleService,
+ LocaleType,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { IEditorService } from '@univerjs/docs-ui';
+import { SheetsSelectionsService } from '@univerjs/sheets';
+import {
+ ComponentManager,
+ IconManager,
+ ILayoutService,
+ IMenuManagerService,
+ IRibbonService,
+ MenuItemType,
+ RediContext,
+ RibbonInsertGroup,
+ RibbonPosition,
+ RibbonStartGroup,
+} from '@univerjs/ui';
+import { act, createElement } from 'react';
+import { createRoot } from 'react-dom/client';
+import { BehaviorSubject, EMPTY } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import enUS from '../../../../locale/en-US';
+import { IEditorBridgeService } from '../../../../services/editor-bridge.service';
import {
getMobileCellCenterOffset,
getMobileCellRevealOffset,
getMobileEditingMenuBottomOffset,
getMobileMenuCommand,
+ MobileSheetActionPanel,
normalizeMobileSelectionPrimary,
} from '../MobileSheetActionPanel';
+Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, value: true, writable: true });
+
+const TEST_INSERT_MENU_ID = 'test.menu.insert-image';
+const TEST_INSERT_COMMAND_ID = 'test.command.insert-image';
+const TEST_NUMFMT_MENU_ID = 'test.menu.number-format';
+const TEST_NUMFMT_COMMAND_ID = 'test.command.set-number-format';
+const TEST_CUSTOM_NUMFMT_COMPONENT = 'test.component.custom-number-format';
+
+function createNumberFormatRibbon(): IMenuSchema[] {
+ const numberFormatItem: MobileNumberFormatItem = {
+ id: TEST_NUMFMT_MENU_ID,
+ type: MenuItemType.SELECTOR,
+ title: 'Number format',
+ selections: [],
+ value$: new BehaviorSubject('General'),
+ mobileNumberFormat: {
+ kind: 'number-format',
+ title: 'Number format',
+ commandId: TEST_NUMFMT_COMMAND_ID,
+ detailTitle: 'More formats',
+ customTitle: 'Custom format',
+ customComponent: TEST_CUSTOM_NUMFMT_COMPONENT,
+ quickOptions: [],
+ decimalOptions: [],
+ detailOptions: [
+ { label: 'General', value: null },
+ { label: 'Custom format', custom: true },
+ ],
+ customPatterns: ['0.00'],
+ },
+ };
+
+ return [{
+ key: RibbonPosition.START,
+ order: 0,
+ children: [{
+ key: RibbonStartGroup.NUMBER,
+ order: 0,
+ children: [{
+ key: TEST_NUMFMT_MENU_ID,
+ order: 0,
+ item: numberFormatItem,
+ }],
+ }],
+ }];
+}
+
+function renderMobileSheetActionPanel(ribbon: IMenuSchema[] = []) {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+ const contextService = injector.get(IContextService);
+
+ injector.get(LocaleService).load({ [LocaleType.EN_US]: enUS });
+ injector.get(LocaleService).setLocale(LocaleType.EN_US);
+ univer.createUnit(UniverInstanceType.UNIVER_SHEET, getSheetsEmptySnapshot('mobile-sheet'));
+ injector.get(IUniverInstanceService).focusUnit('mobile-sheet');
+ injector.add([IEditorBridgeService, {
+ useValue: {
+ visible$: new BehaviorSubject({ visible: false }),
+ getEditCellState: () => null,
+ refreshEditCellPosition: vi.fn(),
+ } as unknown as IEditorBridgeService,
+ }]);
+ injector.add([IEditorService, { useValue: { focus: vi.fn() } as unknown as IEditorService }]);
+ injector.add([ILayoutService, { useValue: { focus: vi.fn() } as unknown as ILayoutService }]);
+ injector.add([ComponentManager]);
+ injector.add([IconManager]);
+ injector.add([IMenuManagerService, {
+ useValue: {
+ menuChanged$: EMPTY,
+ getMenuByPositionKey: () => [],
+ } as unknown as IMenuManagerService,
+ }]);
+ injector.add([IRibbonService, {
+ useValue: { ribbon$: new BehaviorSubject(ribbon) } as unknown as IRibbonService,
+ }]);
+ injector.add([SheetsSelectionsService, {
+ useValue: {
+ selectionMoveEnd$: EMPTY,
+ getCurrentSelections: () => [],
+ getCurrentLastSelection: () => null,
+ setSelections: vi.fn(),
+ } as unknown as SheetsSelectionsService,
+ }]);
+
+ const container = document.createElement('div');
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ act(() => {
+ root.render(createElement(
+ RediContext.Provider,
+ { value: { injector } },
+ createElement(MobileSheetActionPanel)
+ ));
+ });
+
+ return { commandService: injector.get(ICommandService), container, contextService, root, univer };
+}
+
+function clickButton(container: HTMLElement, name: string) {
+ const button = Array.from(container.querySelectorAll('button')).find((item) =>
+ item.getAttribute('aria-label') === name || item.textContent?.includes(name));
+ if (!button) {
+ throw new Error(`Button "${name}" was not rendered.`);
+ }
+
+ act(() => button.dispatchEvent(new MouseEvent('click', { bubbles: true })));
+}
+
+function clickCommand(container: HTMLElement, commandId: string) {
+ const button = container.querySelector(`[data-u-command="${commandId}"]`);
+ if (!button) {
+ throw new Error(`Command "${commandId}" was not rendered.`);
+ }
+
+ act(() => button.dispatchEvent(new MouseEvent('click', { bubbles: true })));
+}
+
+function disposeRenderedPanel(root: Root, container: HTMLElement, univer: Univer) {
+ act(() => root.unmount());
+ container.remove();
+ univer.dispose();
+}
+
+describe('mobile sheet action panel visibility', () => {
+ it('does not reopen the previous sheet drawer after drawing focus ends', () => {
+ const { container, contextService, root, univer } = renderMobileSheetActionPanel();
+
+ try {
+ clickButton(container, 'Open sheet tools');
+ expect(container.querySelector('[data-u-comp="mobile-sheet-action-panel"]')).not.toBeNull();
+
+ act(() => contextService.setContextValue(FOCUSING_COMMON_DRAWINGS, true));
+ expect(container.querySelector('[data-u-comp="mobile-sheet-action-panel"]')).toBeNull();
+
+ act(() => contextService.setContextValue(FOCUSING_COMMON_DRAWINGS, false));
+ expect(container.querySelector('[data-u-comp="mobile-sheet-action-panel"]')).toBeNull();
+ } finally {
+ disposeRenderedPanel(root, container, univer);
+ }
+ });
+
+ it('closes the sheet drawer after executing a nested insert menu command', () => {
+ const execute = vi.fn(() => true);
+ const ribbon: IMenuSchema[] = [{
+ key: RibbonPosition.INSERT,
+ order: 0,
+ children: [{
+ key: RibbonInsertGroup.MEDIA,
+ order: 0,
+ children: [{
+ key: TEST_INSERT_MENU_ID,
+ order: 0,
+ item: {
+ id: TEST_INSERT_MENU_ID,
+ type: MenuItemType.SUBITEMS,
+ title: 'Insert image',
+ },
+ children: [{
+ key: TEST_INSERT_COMMAND_ID,
+ order: 0,
+ item: {
+ id: TEST_INSERT_COMMAND_ID,
+ type: MenuItemType.BUTTON,
+ title: 'Floating image',
+ },
+ }],
+ }],
+ }],
+ }];
+ const { commandService, container, root, univer } = renderMobileSheetActionPanel(ribbon);
+ commandService.registerCommand({
+ id: TEST_INSERT_COMMAND_ID,
+ type: CommandType.COMMAND,
+ handler: execute,
+ });
+
+ try {
+ clickButton(container, 'Open sheet tools');
+ clickCommand(container, TEST_INSERT_MENU_ID);
+ expect(container.querySelector('[data-u-comp="mobile-sheet-action-panel"]')).not.toBeNull();
+
+ clickCommand(container, TEST_INSERT_COMMAND_ID);
+
+ expect(execute).toHaveBeenCalledOnce();
+ expect(container.querySelector('[data-u-comp="mobile-sheet-action-panel"]')).toBeNull();
+ } finally {
+ disposeRenderedPanel(root, container, univer);
+ }
+ });
+
+ it('closes the sheet drawer after selecting a detailed number format', () => {
+ const execute = vi.fn(() => true);
+ const { commandService, container, root, univer } = renderMobileSheetActionPanel(createNumberFormatRibbon());
+ commandService.registerCommand({
+ id: TEST_NUMFMT_COMMAND_ID,
+ type: CommandType.COMMAND,
+ handler: execute,
+ });
+
+ try {
+ clickButton(container, 'Open sheet tools');
+ clickButton(container, 'Style');
+ clickButton(container, 'More formats');
+ clickButton(container, 'General');
+
+ expect(execute).toHaveBeenCalledOnce();
+ expect(container.querySelector('[data-u-comp="mobile-sheet-action-panel"]')).toBeNull();
+ } finally {
+ disposeRenderedPanel(root, container, univer);
+ }
+ });
+
+ it('closes the sheet drawer after confirming a custom number format', () => {
+ const execute = vi.fn(() => true);
+ const { commandService, container, root, univer } = renderMobileSheetActionPanel(createNumberFormatRibbon());
+ commandService.registerCommand({
+ id: TEST_NUMFMT_COMMAND_ID,
+ type: CommandType.COMMAND,
+ handler: execute,
+ });
+ univer.__getInjector().get(ComponentManager).register(
+ TEST_CUSTOM_NUMFMT_COMPONENT,
+ (props: { onConfirm: (pattern: string) => void }) => createElement('button', {
+ type: 'button',
+ 'aria-label': 'Confirm custom format',
+ onClick: () => props.onConfirm('0.00'),
+ })
+ );
+
+ try {
+ clickButton(container, 'Open sheet tools');
+ clickButton(container, 'Style');
+ clickButton(container, 'More formats');
+ clickButton(container, 'Custom format');
+ clickButton(container, 'Confirm custom format');
+
+ expect(execute).toHaveBeenCalledOnce();
+ expect(container.querySelector('[data-u-comp="mobile-sheet-action-panel"]')).toBeNull();
+ } finally {
+ disposeRenderedPanel(root, container, univer);
+ }
+ });
+});
+
describe('mobile active-cell reveal offset', () => {
it('moves only the distance outside the padded visible area', () => {
expect(getMobileCellRevealOffset(100, 130, 80, 500)).toBe(0);
diff --git a/packages/sheets-ui/src/views/mobile/action-panel/__tests__/MobileStylePanel.spec.tsx b/packages/sheets-ui/src/views/mobile/action-panel/__tests__/MobileStylePanel.spec.tsx
index 6e354037d6..c5ace700d8 100644
--- a/packages/sheets-ui/src/views/mobile/action-panel/__tests__/MobileStylePanel.spec.tsx
+++ b/packages/sheets-ui/src/views/mobile/action-panel/__tests__/MobileStylePanel.spec.tsx
@@ -47,7 +47,7 @@ import {
SetTextWrapCommand,
SetVerticalTextAlignCommand,
} from '@univerjs/sheets';
-import { FontService, IconManager, IFontService, MenuItemType, RediContext } from '@univerjs/ui';
+import { ComponentManager, FontService, IconManager, IFontService, MenuItemType, RediContext } from '@univerjs/ui';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { BehaviorSubject } from 'rxjs';
@@ -64,15 +64,20 @@ import {
import { BORDER_LINE_CHILDREN, BORDER_SIZE_CHILDREN } from '../../../border-panel/interface';
import { MobileStylePanel } from '../MobileStylePanel';
-function renderStylePanel(props: Partial<ComponentProps<typeof MobileStylePanel>> = {}) {
+function renderStylePanel(
+ props: Partial<ComponentProps<typeof MobileStylePanel>> = {},
+ configureInjector?: (injector: Injector) => void
+) {
const injector = new Injector();
injector.add([LocaleService]);
injector.add([ThemeService]);
injector.add([ILogService, { useClass: DesktopLogService }]);
injector.add([IConfigService, { useClass: ConfigService }]);
injector.add([IconManager]);
+ injector.add([ComponentManager]);
injector.add([IFontService, { useClass: FontService }]);
injector.get(LocaleService).load({ [LocaleType.ZH_CN]: {} });
+ configureInjector?.(injector);
const resolvedProps: ComponentProps<typeof MobileStylePanel> = {
groups: [],
currentView: null,
@@ -221,8 +226,12 @@ describe('MobileStylePanel', () => {
root = rendered.root;
container = rendered.container;
- expect(getButton(rendered.container, 'Font family').textContent).toContain('Arial');
- expect(getButton(rendered.container, 'Font size').textContent).toContain('10');
+ const fontFamilyButton = getButton(rendered.container, 'Font family');
+ const fontSizeButton = getButton(rendered.container, 'Font size');
+ expect(fontFamilyButton.textContent).toContain('Arial');
+ expect(fontSizeButton.textContent).toContain('10');
+ expect(fontFamilyButton.querySelector('svg')).not.toBeNull();
+ expect(fontSizeButton.querySelector('svg')).not.toBeNull();
clickButton(rendered.container, 'Font family');
expect(onOpenView).toHaveBeenCalledWith(expect.objectContaining({ kind: 'options', title: 'Font family' }));
});
@@ -357,6 +366,7 @@ describe('MobileStylePanel', () => {
commandId: 'set-pattern',
detailTitle: 'More formats',
customTitle: 'Custom format',
+ customComponent: 'test-mobile-custom-number-format',
quickOptions: [
{ label: 'Percent', commandId: 'percent' },
{ label: 'Currency', commandId: 'currency' },
@@ -381,7 +391,7 @@ describe('MobileStylePanel', () => {
type: MenuItemType.SELECTOR,
selections: [],
value$: new BehaviorSubject('General'),
- mobileStyle: numfmtConfig,
+ mobileNumberFormat: numfmtConfig,
};
const groups: IMenuSchema[] = [{
key: 'layout',
@@ -566,6 +576,7 @@ describe('MobileStylePanel', () => {
commandId: 'set-pattern',
detailTitle: 'More formats',
customTitle: 'Custom format',
+ customComponent: 'test-mobile-custom-number-format',
quickOptions: [],
decimalOptions: [],
detailOptions: [
@@ -581,7 +592,7 @@ describe('MobileStylePanel', () => {
type: MenuItemType.SELECTOR,
selections: [],
value$: new BehaviorSubject('Date'),
- mobileStyle: config,
+ mobileNumberFormat: config,
};
const rendered = renderStylePanel({
currentView: { kind: 'number-format', title: 'More formats', item, config },
@@ -601,12 +612,14 @@ describe('MobileStylePanel', () => {
it('applies a custom number format from the third-level view', () => {
const onExecute = vi.fn();
const onBack = vi.fn();
+ const customComponent = 'test-mobile-custom-number-format';
const config = {
kind: 'number-format' as const,
title: 'Number format',
commandId: 'set-pattern',
detailTitle: 'More formats',
customTitle: 'Custom format',
+ customComponent,
quickOptions: [],
decimalOptions: [],
detailOptions: [],
@@ -617,12 +630,17 @@ describe('MobileStylePanel', () => {
currentView: { kind: 'custom-number-format', title: 'Custom format', item, config },
onExecute,
onBack,
+ }, (injector) => {
+ injector.get(ComponentManager).register(customComponent, (props: { onConfirm: (pattern: string) => void }) => (
+ <button type="button" aria-label="Registered custom format" onClick={() => props.onConfirm('0.00')}>
+ Registered custom format
+ </button>
+ ));
});
root = rendered.root;
container = rendered.container;
- clickButton(rendered.container, '0.00');
- clickButton(rendered.container, 'sheets-ui.mobile.confirm');
+ clickButton(rendered.container, 'Registered custom format');
expect(onExecute).toHaveBeenCalledWith({ id: 'set-pattern', value: '0.00' });
expect(onBack).toHaveBeenCalledOnce();
});
diff --git a/packages/sheets-ui/src/views/mobile/border-panel/MobileBorderPanel.tsx b/packages/sheets-ui/src/views/mobile/border-panel/MobileBorderPanel.tsx
new file mode 100644
index 0000000000..da6cdfa3f1
--- /dev/null
+++ b/packages/sheets-ui/src/views/mobile/border-panel/MobileBorderPanel.tsx
@@ -0,0 +1,23 @@
+/**
+ * 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 { IResponsiveBorderPanelProps } from '../../border-panel/BorderPanel';
+import { MobileColorPicker, MobileDropdown } from '@univerjs/design';
+import { BorderPanel } from '../../border-panel/BorderPanel';
+
+export function MobileBorderPanel(props: IResponsiveBorderPanelProps) {
+ return <BorderPanel {...props} ColorPickerComponent={MobileColorPicker} DropdownComponent={MobileDropdown} />;
+}
diff --git a/packages/sheets-ui/src/views/mobile/cell-alert/MobileCellAlert.tsx b/packages/sheets-ui/src/views/mobile/cell-alert/MobileCellAlert.tsx
new file mode 100644
index 0000000000..a66569350e
--- /dev/null
+++ b/packages/sheets-ui/src/views/mobile/cell-alert/MobileCellAlert.tsx
@@ -0,0 +1,23 @@
+/**
+ * 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 { ICellAlertProps } from '../../cell-alert/CellAlertPopup';
+import { MobileDropdownMenu } from '@univerjs/design';
+import { CellAlert } from '../../cell-alert/CellAlertPopup';
+
+export function MobileCellAlert(props: ICellAlertProps) {
+ return <CellAlert {...props} DropdownMenuComponent={MobileDropdownMenu} />;
+}
diff --git a/packages/sheets-ui/src/views/mobile/clipboard/MobileClipboardPopupMenu.tsx b/packages/sheets-ui/src/views/mobile/clipboard/MobileClipboardPopupMenu.tsx
new file mode 100644
index 0000000000..1055f4f962
--- /dev/null
+++ b/packages/sheets-ui/src/views/mobile/clipboard/MobileClipboardPopupMenu.tsx
@@ -0,0 +1,22 @@
+/**
+ * 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 { MobileDropdownMenu } from '@univerjs/design';
+import { ClipboardPopupMenu } from '../../clipboard/ClipboardPopupMenu';
+
+export function MobileClipboardPopupMenu() {
+ return <ClipboardPopupMenu DropdownMenuComponent={MobileDropdownMenu} />;
+}
diff --git a/packages/sheets-ui/src/views/mobile/defined-name/MobileDefinedNameContainer.tsx b/packages/sheets-ui/src/views/mobile/defined-name/MobileDefinedNameContainer.tsx
new file mode 100644
index 0000000000..7b4a8d04bc
--- /dev/null
+++ b/packages/sheets-ui/src/views/mobile/defined-name/MobileDefinedNameContainer.tsx
@@ -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 { IDefinedNameContainerProps } from '../../defined-name/DefinedNameContainer';
+import { MobileConfirm } from '@univerjs/design';
+import { DefinedNameContainer } from '../../defined-name/DefinedNameContainer';
+import { MobileDefinedNameInput } from './MobileDefinedNameInput';
+
+export function MobileDefinedNameContainer(props: IDefinedNameContainerProps) {
+ return (
+ <DefinedNameContainer
+ {...props}
+ ConfirmComponent={MobileConfirm}
+ DefinedNameInputComponent={MobileDefinedNameInput}
+ />
+ );
+}
diff --git a/packages/sheets-ui/src/views/mobile/defined-name/MobileDefinedNameInput.tsx b/packages/sheets-ui/src/views/mobile/defined-name/MobileDefinedNameInput.tsx
new file mode 100644
index 0000000000..9f276dcbbc
--- /dev/null
+++ b/packages/sheets-ui/src/views/mobile/defined-name/MobileDefinedNameInput.tsx
@@ -0,0 +1,23 @@
+/**
+ * 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 { IDefinedNameInputProps } from '../../defined-name/DefinedNameInput';
+import { MobileSelect } from '@univerjs/design';
+import { DefinedNameInput } from '../../defined-name/DefinedNameInput';
+
+export function MobileDefinedNameInput(props: IDefinedNameInputProps) {
+ return <DefinedNameInput {...props} SelectComponent={MobileSelect} />;
+}
diff --git a/packages/sheets-ui/src/views/mobile/dropdown/MobileColorDropdown.tsx b/packages/sheets-ui/src/views/mobile/dropdown/MobileColorDropdown.tsx
new file mode 100644
index 0000000000..8cc29c92ba
--- /dev/null
+++ b/packages/sheets-ui/src/views/mobile/dropdown/MobileColorDropdown.tsx
@@ -0,0 +1,29 @@
+/**
+ * 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 { IPopupWithExtraProps } from '@univerjs/ui';
+import type { IColorDropdownProps } from '../../dropdown/ColorDropdown';
+import type { IBaseDropdownProps } from '../../dropdown/type';
+import { MobileColorPicker } from '@univerjs/design';
+import { ColorDropdown } from '../../dropdown/ColorDropdown';
+
+export function MobileColorDropdown(props: {
+ popup: IPopupWithExtraProps<IColorDropdownProps & IBaseDropdownProps>;
+}) {
+ return <ColorDropdown {...props} ColorPickerComponent={MobileColorPicker} />;
+}
+
+MobileColorDropdown.componentKey = ColorDropdown.componentKey;
diff --git a/packages/sheets-ui/src/views/mobile/editor-container/MobileEditorContainer.tsx b/packages/sheets-ui/src/views/mobile/editor-container/MobileEditorContainer.tsx
new file mode 100644
index 0000000000..a64575240c
--- /dev/null
+++ b/packages/sheets-ui/src/views/mobile/editor-container/MobileEditorContainer.tsx
@@ -0,0 +1,21 @@
+/**
+ * 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 { EditorContainer } from '../../editor-container/EditorContainer';
+
+export function MobileEditorContainer() {
+ return <EditorContainer hidden />;
+}
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 7f166334df..f2a1b162c8 100644
--- a/packages/sheets-ui/src/views/mobile/formula-bar/MobileFormulaBar.tsx
+++ b/packages/sheets-ui/src/views/mobile/formula-bar/MobileFormulaBar.tsx
@@ -14,19 +14,57 @@
* limitations under the License.
*/
+import type { IUniverSheetsUIConfig } from '../../../config/config';
+import type { LocaleKey } from '../../../locale/types';
+import type { IEditorBridgeServiceVisibleParam } from '../../../services/editor-bridge.service';
import {
DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
FOCUSING_FX_BAR_EDITOR,
+ ICommandService,
IContextService,
+ IPermissionService,
+ LocaleService,
} from '@univerjs/core';
-import { clsx } from '@univerjs/design';
+import { borderBottomClassName, clsx } from '@univerjs/design';
import { IEditorService } from '@univerjs/docs-ui';
-import { useDependency, useObservable } from '@univerjs/ui';
-import { useEffect, useState } from 'react';
-import { map } from 'rxjs';
-import { MOBILE_FX_EDITOR_EXPANDED } from '../../../consts/mobile-context';
+import { DeviceInputEventType } from '@univerjs/engine-render';
+import { DownIcon } from '@univerjs/icons';
+import { UnitAction } from '@univerjs/protocol';
+import {
+ isCellImage,
+ RangeProtectionCache,
+ RangeProtectionRuleModel,
+ SheetsSelectionsService,
+ WorkbookEditablePermission,
+ WorksheetEditPermission,
+ WorksheetProtectionRuleModel,
+ WorksheetViewPermission,
+} from '@univerjs/sheets';
+import {
+ ComponentContainer,
+ ComponentManager,
+ KeyCode,
+ useComponentsOfPart,
+ useConfigValue,
+ useDependency,
+ useObservable,
+} from '@univerjs/ui';
+import { 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';
+import { SHEETS_UI_PLUGIN_CONFIG_KEY } from '../../../config/config';
+import {
+ MOBILE_FORMULA_BAR_SUBMIT_COMMAND_ID,
+ MOBILE_FORMULA_OPERATORS_VISIBLE,
+ MOBILE_FX_EDITOR_EXPANDED,
+} from '../../../consts/mobile-context';
+import { SheetsUIPart } from '../../../consts/ui-name';
import { IEditorBridgeService } from '../../../services/editor-bridge.service';
-import { FormulaBar } from '../../formula-bar/FormulaBar';
+import { IFormulaEditorManagerService } from '../../../services/editor/formula-editor-manager.service';
+import { useKeyEventConfig } from '../../editor-container/hooks';
+import { useActiveWorkbook } from '../../hook';
+import { MobileFormulaBarActions, MobileFormulaBarOverlays } from './MobileFormulaBarControls';
export function MobileFormulaBar() {
const editorBridgeService = useDependency(IEditorBridgeService);
@@ -40,13 +78,13 @@ export function MobileFormulaBar() {
);
useEffect(() => {
- if (!visible) return undefined;
+ if (!visible) {
+ return undefined;
+ }
contextService.setContextValue(FOCUSING_FX_BAR_EDITOR, true);
let cursorFrame: number | undefined;
const contentFrame = requestAnimationFrame(() => {
- // The mobile formula editor is mounted lazily. Replay the selected cell after mount so
- // its current value is not lost when the earlier selection sync ran before this editor existed.
editorBridgeService.refreshEditCellState();
editorService.focus(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);
cursorFrame = requestAnimationFrame(() => {
@@ -71,18 +109,226 @@ export function MobileFormulaBar() {
}
function MobileFormulaBarEditor() {
+ const commandService = useDependency(ICommandService);
const contextService = useDependency(IContextService);
+ const editorBridgeService = useDependency(IEditorBridgeService);
+ const editorService = useDependency(IEditorService);
+ const formulaEditorManagerService = useDependency(IFormulaEditorManagerService);
+ const localeService = useDependency(LocaleService);
+ const worksheetProtectionRuleModel = useDependency(WorksheetProtectionRuleModel);
+ const rangeProtectionRuleModel = useDependency(RangeProtectionRuleModel);
+ const selectionManager = useDependency(SheetsSelectionsService);
+ const permissionService = useDependency(IPermissionService);
+ const rangeProtectionCache = useDependency(RangeProtectionCache);
+ const componentManager = useDependency(ComponentManager);
+ const workbook = useActiveWorkbook();
+ const editState = useObservable(editorBridgeService.currentEditCellState$);
+ const keyCodeConfig = useKeyEventConfig(editState?.unitId);
+ const FormulaEditor = componentManager.get(EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY);
+ const formulaAuxUIParts = useComponentsOfPart(SheetsUIPart.FORMULA_AUX);
+ const isFocusFxBar = useObservable(
+ useMemo(() => contextService.subscribeContextValue$(FOCUSING_FX_BAR_EDITOR), [contextService]),
+ contextService.getContextValue(FOCUSING_FX_BAR_EDITOR)
+ );
+ const workbookEditablePermission = useObservable(useMemo(() => {
+ if (!workbook) {
+ return undefined;
+ }
+
+ return permissionService.getPermissionPoint$(new WorkbookEditablePermission(workbook.getUnitId()).id);
+ }, [permissionService, workbook]));
+ const config = useConfigValue<IUniverSheetsUIConfig>(SHEETS_UI_PLUGIN_CONFIG_KEY);
+ const disableEdit = config?.disableEdit;
+ const editorRef = useRef<HTMLDivElement>(null);
+ const shouldSkipFocusRef = useRef(false);
const [expanded, setExpanded] = useState(false);
+ const [mobileFxRequest, setMobileFxRequest] = useState(0);
+ const [mobileFunctionPanelRequest, setMobileFunctionPanelRequest] = useState(0);
+ const [mobileFormulaActive, setMobileFormulaActive] = useState(false);
+ const [mobileOperatorRequest, setMobileOperatorRequest] = useState({ id: 0, value: '' });
+ const mobileFormulaOperatorsVisible = mobileFormulaActive && !expanded;
+
+ const disableInfo = useObservable(
+ () => {
+ if (!workbook) {
+ return EMPTY;
+ }
+
+ return workbook.activeSheet$.pipe(
+ switchMap((worksheet) => {
+ if (!worksheet) {
+ return EMPTY;
+ }
+
+ return merge(
+ worksheetProtectionRuleModel.ruleChange$,
+ rangeProtectionRuleModel.ruleChange$,
+ selectionManager.selectionMoveEnd$,
+ selectionManager.selectionSet$
+ ).pipe(
+ switchMap(() => {
+ const unitId = workbook.getUnitId();
+ const subUnitId = worksheet.getSheetId();
+ const range = selectionManager.getCurrentLastSelection()?.range;
+ if (!range) {
+ return EMPTY;
+ }
+ const primary = selectionManager.getCurrentLastSelection()?.primary;
+ if (!primary) {
+ return of(null);
+ }
+
+ return of({ unitId, subUnitId, primary });
+ })
+ );
+ }),
+ map((cellInfo) => {
+ if (cellInfo) {
+ const { unitId, subUnitId, primary } = cellInfo;
+ if (worksheetProtectionRuleModel.getRule(unitId, subUnitId)) {
+ const editDisable = !(permissionService.getPermissionPoint(new WorksheetEditPermission(unitId, subUnitId).id)?.value ?? true);
+ const viewDisable = !(permissionService.getPermissionPoint(new WorksheetViewPermission(unitId, subUnitId).id)?.value ?? true);
+ return { viewDisable, editDisable };
+ }
+
+ const { actualRow, actualColumn } = primary;
+ const cellInfoWithPermission = rangeProtectionCache.getCellInfo(unitId, subUnitId, actualRow, actualColumn);
+ return {
+ editDisable: !(cellInfoWithPermission?.[UnitAction.Edit] ?? true),
+ viewDisable: !(cellInfoWithPermission?.[UnitAction.View] ?? true),
+ };
+ }
+
+ return { viewDisable: false, editDisable: false };
+ })
+ );
+ },
+ { editDisable: false, viewDisable: false },
+ false,
+ [
+ permissionService,
+ rangeProtectionCache,
+ rangeProtectionRuleModel,
+ selectionManager,
+ workbook,
+ worksheetProtectionRuleModel,
+ ]
+ );
useEffect(() => {
- return () => contextService.setContextValue(MOBILE_FX_EDITOR_EXPANDED, false);
+ contextService.setContextValue(MOBILE_FORMULA_OPERATORS_VISIBLE, mobileFormulaOperatorsVisible);
+ }, [contextService, mobileFormulaOperatorsVisible]);
+
+ useEffect(() => () => {
+ contextService.setContextValue(MOBILE_FORMULA_OPERATORS_VISIBLE, false);
+ contextService.setContextValue(MOBILE_FX_EDITOR_EXPANDED, false);
}, [contextService]);
- function handleExpandedChange(nextExpanded: boolean) {
- contextService.setContextValue(MOBILE_FX_EDITOR_EXPANDED, nextExpanded);
- setExpanded(nextExpanded);
+ useEffect(() => {
+ const handleResize = () => {
+ if (!editorRef.current) {
+ return;
+ }
+
+ formulaEditorManagerService.setPosition(editorRef.current.getBoundingClientRect());
+ };
+
+ if (editorRef.current) {
+ handleResize();
+ const resizeObserver = new ResizeObserver(handleResize);
+ resizeObserver.observe(editorRef.current);
+ return () => resizeObserver.disconnect();
+ }
+ }, [formulaEditorManagerService]);
+
+ function handleArrowClick() {
+ contextService.setContextValue(MOBILE_FX_EDITOR_EXPANDED, !expanded);
+ setExpanded(!expanded);
+ setTimeout(() => formulaEditorManagerService.handleFoldBtnClick(expanded), 150);
+ }
+
+ function handleCloseBtnClick() {
+ const visibleState = editorBridgeService.isVisible();
+ if (visibleState.visible && editState) {
+ commandService.executeCommand(SetCellEditVisibleOperation.id, {
+ visible: false,
+ eventType: DeviceInputEventType.Keyboard,
+ keycode: KeyCode.ESC,
+ unitId: editState.unitId,
+ });
+ }
+ contextService.setContextValue(MOBILE_FX_EDITOR_EXPANDED, false);
+ setExpanded(false);
}
+ async function handleConfirmBtnClick() {
+ const submitted = await commandService.executeCommand(MOBILE_FORMULA_BAR_SUBMIT_COMMAND_ID);
+ if (submitted) {
+ contextService.setContextValue(MOBILE_FX_EDITOR_EXPANDED, false);
+ setExpanded(false);
+ }
+ }
+
+ function handleFxBtnClick() {
+ const formulaEditor = editorService.getEditor(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);
+ const formulaText = formulaEditor?.getDocumentData().body?.dataStream?.replace(/\r?\n$/, '') ?? '';
+ if (formulaText.startsWith('=')) {
+ setMobileFxRequest((value) => value + 1);
+ setMobileFunctionPanelRequest((value) => value + 1);
+ }
+ formulaEditorManagerService.handleFxBtnClick(true);
+ }
+
+ function handlePointerDown() {
+ try {
+ contextService.setContextValue(FOCUSING_FX_BAR_EDITOR, true);
+
+ const visibleState = editorBridgeService.isVisible();
+ if (visibleState.visible === false) {
+ const editDisable = disableInfo.editDisable || !!disableEdit;
+ const workbookEditDisable = !(workbookEditablePermission?.value ?? true);
+ if (editDisable || workbookEditDisable) {
+ editorService.focus(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);
+ return;
+ }
+
+ if (!editState) {
+ return;
+ }
+ const result = commandService.syncExecuteCommand(
+ SetCellEditVisibleOperation.id,
+ {
+ visible: true,
+ eventType: DeviceInputEventType.PointerDown,
+ unitId: editState.unitId,
+ } as IEditorBridgeServiceVisibleParam
+ );
+ if (!result) {
+ contextService.setContextValue(FOCUSING_FX_BAR_EDITOR, false);
+ shouldSkipFocusRef.current = true;
+ }
+ }
+ } catch (error) {
+ contextService.setContextValue(FOCUSING_FX_BAR_EDITOR, false);
+ shouldSkipFocusRef.current = true;
+ throw error;
+ }
+ }
+
+ function handlePointerUp() {
+ if (shouldSkipFocusRef.current) {
+ setTimeout(() => editorService.blur(true), 30);
+ }
+ shouldSkipFocusRef.current = false;
+ }
+
+ const { viewDisable, editDisable: permissionEditDisable } = disableInfo;
+ const editDisable = permissionEditDisable || !!disableEdit;
+ const hideEditor = isCellImage(editState?.documentLayoutObject.documentModel?.getSnapshot()) || viewDisable;
+ const editorBackground = editState
+ ? workbook?.getSheetBySheetId(editState.sheetId)?.getCellStyle(editState.row, editState.column)?.bg?.rgb ?? undefined
+ : undefined;
+
return (
<div
data-u-comp="mobile-formula-bar"
@@ -97,17 +343,115 @@ function MobileFormulaBarEditor() {
paddingTop: expanded ? 'env(safe-area-inset-top, 0px)' : undefined,
}}
>
- <FormulaBar
- className="
- univer-text-base
- [&>div:first-child]:!univer-hidden
+ <div
+ dir="ltr"
+ data-u-comp="formula-bar"
+ data-expanded={expanded}
+ className={clsx(`
+ univer-relative univer-box-border univer-flex univer-bg-gray-0 univer-text-base univer-text-gray-900
+ univer-transition-[height] univer-ease-linear
+ dark:!univer-bg-gray-800
[&_span]:!univer-min-h-8 [&_span]:!univer-min-w-8
- "
- disableDefinedName
- expanded={expanded}
- mobile
- onExpandedChange={handleExpandedChange}
- />
+ `, borderBottomClassName, expanded ? '!univer-h-full' : '!univer-h-12', {
+ 'univer-pointer-events-none': editDisable,
+ })}
+ >
+ <MobileFormulaBarOverlays
+ expanded={expanded}
+ formulaActive={mobileFormulaActive}
+ operatorsVisible={mobileFormulaOperatorsVisible}
+ editorId={DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY}
+ onOperator={(value) => setMobileOperatorRequest(({ id }) => ({ id: id + 1, value }))}
+ />
+ <div className="univer-flex univer-size-full">
+ <MobileFormulaBarActions
+ expanded={expanded}
+ cancelLabel={localeService.t<LocaleKey>('sheets-ui.button.cancel')}
+ confirmLabel={localeService.t<LocaleKey>('sheets-ui.button.confirm')}
+ formulaLabel={localeService.t<LocaleKey>('sheets-ui.mobile.formula')}
+ collapseLabel={localeService.t<LocaleKey>('sheets-ui.mobile.collapseEditor')}
+ onCancel={handleCloseBtnClick}
+ onConfirm={handleConfirmBtnClick}
+ onFormula={handleFxBtnClick}
+ onCollapse={handleArrowClick}
+ />
+ <div
+ className={clsx('univer-flex univer-w-full univer-flex-1 univer-overflow-hidden', {
+ 'univer-pt-24': expanded,
+ })}
+ >
+ <div
+ ref={editorRef}
+ className={clsx(`
+ univer-relative univer-box-border univer-flex-1 univer-bg-gray-0 univer-pl-2
+ dark:!univer-bg-gray-800
+ `, { 'univer-my-2': !expanded })}
+ onPointerDown={handlePointerDown}
+ onPointerUp={handlePointerUp}
+ style={{ backgroundColor: editorBackground, pointerEvents: hideEditor ? 'none' : 'auto' }}
+ >
+ {FormulaEditor && (
+ <FormulaEditor
+ className="univer-relative univer-size-full univer-break-words univer-outline-none"
+ borderless
+ disableSelectionOnClick
+ editorId={DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY}
+ initValue=""
+ onChange={() => { }}
+ isFocus={isFocusFxBar}
+ unitId={editState?.unitId}
+ subUnitId={editState?.sheetId}
+ isSupportAcrossSheet
+ resetSelectionOnBlur={false}
+ isSingle={false}
+ keyboardEventConfig={keyCodeConfig}
+ onFormulaSelectingChange={(isSelecting: 0 | 1 | 2, isFocusing: boolean) => {
+ if (!isFocusing) {
+ return;
+ }
+ if (isSelecting) {
+ editorBridgeService.enableForceKeepVisible();
+ } else {
+ editorBridgeService.disableForceKeepVisible();
+ }
+ }}
+ autoScrollbar={false}
+ disableContextMenu={false}
+ mobileFxRequest={mobileFxRequest}
+ mobileFunctionPanelRequest={mobileFunctionPanelRequest}
+ mobileOperatorRequest={mobileOperatorRequest}
+ onMobileFormulaActiveChange={setMobileFormulaActive}
+ />
+ )}
+ {hideEditor && (
+ <div
+ className="
+ univer-pointer-events-none univer-relative univer-left-0 univer-top-0
+ univer-z-[100] univer-size-full univer-cursor-not-allowed univer-bg-gray-0
+ dark:!univer-bg-gray-800
+ "
+ />
+ )}
+ </div>
+ {!expanded && (
+ <div
+ data-u-comp="formula-bar-expand"
+ className={clsx(`
+ univer-flex univer-h-full univer-w-10 univer-cursor-pointer univer-items-center
+ univer-justify-center univer-text-xs univer-text-gray-700
+ dark:!univer-text-gray-200
+ `, {
+ 'univer-cursor-not-allowed univer-text-gray-200 dark:!univer-text-gray-700': editDisable,
+ })}
+ onClick={handleArrowClick}
+ >
+ <DownIcon className="univer-size-5 univer-rotate-180" />
+ </div>
+ )}
+ </div>
+ </div>
+ <ComponentContainer key="formula-aux" components={formulaAuxUIParts} />
+ </div>
</div>
);
}
diff --git a/packages/sheets-ui/src/views/mobile/menu-item-input/MobileMenuItemInput.tsx b/packages/sheets-ui/src/views/mobile/menu-item-input/MobileMenuItemInput.tsx
new file mode 100644
index 0000000000..920e484b54
--- /dev/null
+++ b/packages/sheets-ui/src/views/mobile/menu-item-input/MobileMenuItemInput.tsx
@@ -0,0 +1,69 @@
+/**
+ * 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 { KeyboardEvent } from 'react';
+import type { IMenuItemInputProps } from '../../menu-item-input/interface';
+import { LocaleService } from '@univerjs/core';
+import { InputNumber } from '@univerjs/design';
+import { useDependency, useObservable } from '@univerjs/ui';
+
+export function MobileMenuItemInput(props: IMenuItemInputProps) {
+ const {
+ prefix,
+ suffix,
+ value,
+ min = Number.MIN_SAFE_INTEGER,
+ max = Number.MAX_SAFE_INTEGER,
+ disabled$,
+ onChange,
+ } = props;
+ const localeService = useDependency(LocaleService);
+ const disabled = useObservable(disabled$ ?? null, false);
+ const inputValue = Math.min(max, Math.max(min, Number(value)));
+
+ function handleChange(nextValue: number | null) {
+ if (nextValue == null) {
+ return;
+ }
+
+ onChange(nextValue.toString());
+ }
+
+ function handleKeyDown(event: KeyboardEvent<HTMLInputElement>) {
+ event.stopPropagation();
+ }
+
+ return (
+ <div className="univer-flex univer-min-w-0 univer-flex-1 univer-items-center univer-gap-2">
+ <span className="univer-shrink-0 univer-text-base univer-font-medium">{localeService.t(prefix)}</span>
+ <div className="univer-w-20 univer-shrink-0" onClick={(event) => event.stopPropagation()}>
+ <InputNumber
+ value={inputValue}
+ size="small"
+ precision={0}
+ min={min}
+ max={max}
+ disabled={disabled}
+ onKeyDown={handleKeyDown}
+ onChange={handleChange}
+ />
+ </div>
+ <span className="univer-min-w-0 univer-truncate univer-text-base univer-font-medium">
+ {localeService.t(suffix)}
+ </span>
+ </div>
+ );
+}
diff --git a/packages/sheets-ui/src/views/mobile/permission/MobilePermissionDetailFooterPart.tsx b/packages/sheets-ui/src/views/mobile/permission/MobilePermissionDetailFooterPart.tsx
new file mode 100644
index 0000000000..3fe2beb469
--- /dev/null
+++ b/packages/sheets-ui/src/views/mobile/permission/MobilePermissionDetailFooterPart.tsx
@@ -0,0 +1,23 @@
+/**
+ * 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 { MobileActionRowGroup } from '@univerjs/design';
+import { PermissionDetailFooterPart } from '../../permission/panel-detail/PermissionDetailFooterPart';
+
+export function MobilePermissionDetailFooterPart(props: ComponentProps<typeof PermissionDetailFooterPart>) {
+ return <PermissionDetailFooterPart {...props} ActionRowComponent={MobileActionRowGroup} />;
+}
diff --git a/packages/sheets-ui/src/views/mobile/permission/MobilePermissionDetailUserPart.tsx b/packages/sheets-ui/src/views/mobile/permission/MobilePermissionDetailUserPart.tsx
new file mode 100644
index 0000000000..1b60ff66de
--- /dev/null
+++ b/packages/sheets-ui/src/views/mobile/permission/MobilePermissionDetailUserPart.tsx
@@ -0,0 +1,29 @@
+/**
+ * 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 { IPermissionDetailUserPartProps } from '../../permission/panel-detail/PermissionDetailUserPart';
+import { MobileSelect } from '@univerjs/design';
+import { PermissionDetailUserPart } from '../../permission/panel-detail/PermissionDetailUserPart';
+
+export function MobilePermissionDetailUserPart(props: IPermissionDetailUserPartProps) {
+ return (
+ <PermissionDetailUserPart
+ {...props}
+ SelectComponent={MobileSelect}
+ userListClassName="!univer-h-auto univer-max-h-[40vh] univer-shrink-0"
+ />
+ );
+}
diff --git a/packages/sheets-ui/src/views/mobile/permission/MobileSheetPermissionDialog.tsx b/packages/sheets-ui/src/views/mobile/permission/MobileSheetPermissionDialog.tsx
new file mode 100644
index 0000000000..1fb0ab010d
--- /dev/null
+++ b/packages/sheets-ui/src/views/mobile/permission/MobileSheetPermissionDialog.tsx
@@ -0,0 +1,23 @@
+/**
+ * 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 { ISheetPermissionDialogProps } from '../../permission/SheetPermissionDialog';
+import { MobileActionRowGroup } from '@univerjs/design';
+import { SheetPermissionDialog } from '../../permission/SheetPermissionDialog';
+
+export function MobileSheetPermissionDialog(props: ISheetPermissionDialogProps) {
+ return <SheetPermissionDialog {...props} ActionRowComponent={MobileActionRowGroup} />;
+}
diff --git a/packages/sheets-ui/src/views/mobile/permission/MobileSheetPermissionPanel.tsx b/packages/sheets-ui/src/views/mobile/permission/MobileSheetPermissionPanel.tsx
new file mode 100644
index 0000000000..1f818635d4
--- /dev/null
+++ b/packages/sheets-ui/src/views/mobile/permission/MobileSheetPermissionPanel.tsx
@@ -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 { ISheetPermissionPanelProps } from '../../permission/SheetPermissionPanel';
+import { SheetPermissionPanel } from '../../permission/SheetPermissionPanel';
+import { MobileSheetPermissionPanelDetail } from './MobileSheetPermissionPanelDetail';
+import { MobileSheetPermissionPanelList } from './MobileSheetPermissionPanelList';
+
+export function MobileSheetPermissionPanel(props: ISheetPermissionPanelProps) {
+ return (
+ <SheetPermissionPanel
+ {...props}
+ DetailComponent={MobileSheetPermissionPanelDetail}
+ ListComponent={MobileSheetPermissionPanelList}
+ />
+ );
+}
diff --git a/packages/sheets-ui/src/views/mobile/permission/MobileSheetPermissionPanelDetail.tsx b/packages/sheets-ui/src/views/mobile/permission/MobileSheetPermissionPanelDetail.tsx
new file mode 100644
index 0000000000..a81d5c2997
--- /dev/null
+++ b/packages/sheets-ui/src/views/mobile/permission/MobileSheetPermissionPanelDetail.tsx
@@ -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 { ISheetPermissionPanelDetailProps } from '../../permission/panel-detail/PermissionDetailPanel';
+import { SheetPermissionPanelDetail } from '../../permission/panel-detail/PermissionDetailPanel';
+import { MobilePermissionDetailFooterPart } from './MobilePermissionDetailFooterPart';
+import { MobilePermissionDetailUserPart } from './MobilePermissionDetailUserPart';
+
+export function MobileSheetPermissionPanelDetail(props: ISheetPermissionPanelDetailProps) {
+ return (
+ <SheetPermissionPanelDetail
+ {...props}
+ FooterComponent={MobilePermissionDetailFooterPart}
+ UserComponent={MobilePermissionDetailUserPart}
+ />
+ );
+}
diff --git a/packages/sheets-ui/src/views/mobile/permission/MobileSheetPermissionPanelList.tsx b/packages/sheets-ui/src/views/mobile/permission/MobileSheetPermissionPanelList.tsx
new file mode 100644
index 0000000000..ed6d9373e7
--- /dev/null
+++ b/packages/sheets-ui/src/views/mobile/permission/MobileSheetPermissionPanelList.tsx
@@ -0,0 +1,23 @@
+/**
+ * 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 { ISheetPermissionPanelListProps } from '../../permission/SheetPermissionPanelList';
+import { MobileActionRowGroup } from '@univerjs/design';
+import { SheetPermissionPanelList } from '../../permission/SheetPermissionPanelList';
+
+export function MobileSheetPermissionPanelList(props: ISheetPermissionPanelListProps = {}) {
+ return <SheetPermissionPanelList {...props} ActionRowComponent={MobileActionRowGroup} />;
+}
diff --git a/packages/sheets-ui/src/views/mobile/permission/MobileSheetPermissionUserDialog.tsx b/packages/sheets-ui/src/views/mobile/permission/MobileSheetPermissionUserDialog.tsx
new file mode 100644
index 0000000000..533583fe07
--- /dev/null
+++ b/packages/sheets-ui/src/views/mobile/permission/MobileSheetPermissionUserDialog.tsx
@@ -0,0 +1,23 @@
+/**
+ * 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 { ISheetPermissionUserDialogProps } from '../../permission/SheetPermissionUserDialog';
+import { MobileActionRowGroup } from '@univerjs/design';
+import { SheetPermissionUserDialog } from '../../permission/SheetPermissionUserDialog';
+
+export function MobileSheetPermissionUserDialog(props: ISheetPermissionUserDialogProps) {
+ return <SheetPermissionUserDialog {...props} ActionRowComponent={MobileActionRowGroup} />;
+}
diff --git a/packages/sheets-ui/src/views/mobile/sheet-bar/MobileSheetBar.tsx b/packages/sheets-ui/src/views/mobile/sheet-bar/MobileSheetBar.tsx
index dff92c8c7e..a002adb501 100644
--- a/packages/sheets-ui/src/views/mobile/sheet-bar/MobileSheetBar.tsx
+++ b/packages/sheets-ui/src/views/mobile/sheet-bar/MobileSheetBar.tsx
@@ -19,7 +19,16 @@ import type { MouseEvent } from 'react';
import type { LocaleKey } from '../../../locale/types';
import type { IBaseSheetBarProps } from '../../sheet-bar/sheet-bar-tabs/SheetBarItem';
import { ICommandService, LocaleService, nameCharacterCheck } from '@univerjs/core';
-import { borderBottomClassName, borderLeftClassName, borderRightClassName, clsx, Dialog, Input, resetButtonClassName, scrollbarClassName } from '@univerjs/design';
+import {
+ borderBottomClassName,
+ borderLeftClassName,
+ borderRightClassName,
+ clsx,
+ Input,
+ MobileDialog,
+ resetButtonClassName,
+ scrollbarClassName,
+} from '@univerjs/design';
import { IncreaseIcon, MoreDownIcon } from '@univerjs/icons';
import {
InsertSheetCommand,
@@ -102,7 +111,9 @@ function MobileSheetBarImpl(props: { workbook: Workbook }) {
useEffect(() => {
const subscription = sheetBarService.renameId$.subscribe((sheetId) => {
const sheet = workbook.getSheetBySheetId(sheetId);
- if (!sheet) return;
+ if (!sheet) {
+ return;
+ }
setRenameSheetId(sheetId);
setRenameValue(sheet.getName());
@@ -138,7 +149,9 @@ function MobileSheetBarImpl(props: { workbook: Workbook }) {
}, [commandService, workbook]);
const confirmRename = useCallback(() => {
- if (!renameSheetId) return;
+ if (!renameSheetId) {
+ return;
+ }
const name = renameValue.trim();
if (!name) {
@@ -278,7 +291,7 @@ function MobileSheetBarImpl(props: { workbook: Workbook }) {
<IncreaseIcon />
</button>
</div>
- <Dialog
+ <MobileDialog
open={Boolean(renameSheetId)}
title={localeService.t<LocaleKey>('sheets-ui.sheetConfig.rename')}
showCancel
@@ -286,7 +299,9 @@ function MobileSheetBarImpl(props: { workbook: Workbook }) {
onCancel={() => setRenameSheetId(null)}
onOk={confirmRename}
onOpenChange={(open) => {
- if (!open) setRenameSheetId(null);
+ if (!open) {
+ setRenameSheetId(null);
+ }
}}
>
<div className="univer-grid univer-gap-2">
@@ -299,7 +314,9 @@ function MobileSheetBarImpl(props: { workbook: Workbook }) {
setRenameError('');
}}
onKeyDown={(event) => {
- if (event.key === 'Enter') confirmRename();
+ if (event.key === 'Enter') {
+ confirmRename();
+ }
}}
/>
{renameError && (
@@ -313,8 +330,8 @@ function MobileSheetBarImpl(props: { workbook: Workbook }) {
</div>
)}
</div>
- </Dialog>
- <Dialog
+ </MobileDialog>
+ <MobileDialog
open={unhideVisible}
title={localeService.t<LocaleKey>('sheets-ui.sheetConfig.unhide')}
footer={null}
@@ -349,7 +366,7 @@ function MobileSheetBarImpl(props: { workbook: Workbook }) {
</button>
))}
</div>
- </Dialog>
+ </MobileDialog>
</>
);
}
diff --git a/packages/sheets-ui/src/views/mobile/sheet-container/MobileRenderSheetContent.tsx b/packages/sheets-ui/src/views/mobile/sheet-container/MobileRenderSheetContent.tsx
new file mode 100644
index 0000000000..a980e1fba5
--- /dev/null
+++ b/packages/sheets-ui/src/views/mobile/sheet-container/MobileRenderSheetContent.tsx
@@ -0,0 +1,21 @@
+/**
+ * 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 { RenderSheetContent } from '../../sheet-container/SheetContainer';
+
+export function MobileRenderSheetContent() {
+ return <RenderSheetContent AutoFillPopupMenuComponent={null} />;
+}
diff --git a/packages/sheets-ui/src/views/permission/SheetPermissionDialog.tsx b/packages/sheets-ui/src/views/permission/SheetPermissionDialog.tsx
index eb3d1e589f..a7f7c017ea 100644
--- a/packages/sheets-ui/src/views/permission/SheetPermissionDialog.tsx
+++ b/packages/sheets-ui/src/views/permission/SheetPermissionDialog.tsx
@@ -48,7 +48,11 @@ interface IPermissionMap {
};
}
-export const SheetPermissionDialog = () => {
+export interface ISheetPermissionDialogProps {
+ ActionRowComponent?: typeof ActionRow;
+}
+
+export const SheetPermissionDialog = ({ ActionRowComponent = ActionRow }: ISheetPermissionDialogProps = {}) => {
const localeService = useDependency(LocaleService);
const univerInstanceService = useDependency(IUniverInstanceService);
const authzIoService = useDependency(IAuthzIoService);
@@ -230,7 +234,7 @@ export const SheetPermissionDialog = () => {
);
})}
- <ActionRow
+ <ActionRowComponent
className={clsx(`
univer-flex univer-h-9 univer-items-center univer-justify-end univer-gap-2 univer-pt-2
`, borderTopClassName)}
@@ -251,7 +255,7 @@ export const SheetPermissionDialog = () => {
>
{localeService.t<LocaleKey>('sheets-ui.permission.button.confirm')}
</Button>
- </ActionRow>
+ </ActionRowComponent>
</div>
</Spin>
);
diff --git a/packages/sheets-ui/src/views/permission/SheetPermissionPanel.tsx b/packages/sheets-ui/src/views/permission/SheetPermissionPanel.tsx
index a8df5bf62f..fd49dab2ee 100644
--- a/packages/sheets-ui/src/views/permission/SheetPermissionPanel.tsx
+++ b/packages/sheets-ui/src/views/permission/SheetPermissionPanel.tsx
@@ -23,14 +23,23 @@ import { SheetPermissionPanelModel } from '../../services/permission/sheet-permi
import { SheetPermissionPanelDetail } from './panel-detail/PermissionDetailPanel';
import { SheetPermissionPanelList } from './SheetPermissionPanelList';
-interface ISheetPermissionPanelProps {
+export interface ISheetPermissionPanelProps {
showDetail: boolean;
fromSheetBar: boolean;
rule?: IPermissionPanelRule;
oldRule?: IPermissionPanelRule;
+ DetailComponent?: typeof SheetPermissionPanelDetail;
+ ListComponent?: typeof SheetPermissionPanelList;
};
-export const SheetPermissionPanel = ({ showDetail, fromSheetBar, rule, oldRule }: ISheetPermissionPanelProps) => {
+export const SheetPermissionPanel = ({
+ showDetail,
+ fromSheetBar,
+ rule,
+ oldRule,
+ DetailComponent = SheetPermissionPanelDetail,
+ ListComponent = SheetPermissionPanelList,
+}: ISheetPermissionPanelProps) => {
const univerInstanceService = useDependency(IUniverInstanceService);
const sheetsSelectionsService = useDependency(SheetsSelectionsService);
const sheetPermissionPanelModel = useDependency(SheetPermissionPanelModel);
@@ -47,13 +56,13 @@ export const SheetPermissionPanel = ({ showDetail, fromSheetBar, rule, oldRule }
return (
showDetail
? (
- <SheetPermissionPanelDetail
+ <DetailComponent
fromSheetBar={fromSheetBar}
rule={rule}
oldRule={oldRule}
key={fromSheetBar ? 'sheet-bar' : 'normal'}
/>
)
- : <SheetPermissionPanelList key={key} />
+ : <ListComponent key={key} />
);
};
diff --git a/packages/sheets-ui/src/views/permission/SheetPermissionPanelList.tsx b/packages/sheets-ui/src/views/permission/SheetPermissionPanelList.tsx
index 5b88ecf111..db105bc9ef 100644
--- a/packages/sheets-ui/src/views/permission/SheetPermissionPanelList.tsx
+++ b/packages/sheets-ui/src/views/permission/SheetPermissionPanelList.tsx
@@ -52,14 +52,18 @@ import { panelListEmptyBase64 } from './panel-list/constant';
type IRuleItem = IRangeProtectionRule | IWorksheetProtectionRule;
-export function SheetPermissionPanelList() {
+export interface ISheetPermissionPanelListProps {
+ ActionRowComponent?: typeof ActionRow;
+}
+
+export function SheetPermissionPanelList({ ActionRowComponent = ActionRow }: ISheetPermissionPanelListProps = {}) {
const univerInstanceService = useDependency(IUniverInstanceService);
const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);
- return workbook ? <SheetPermissionPanelListContent /> : null;
+ return workbook ? <SheetPermissionPanelListContent ActionRowComponent={ActionRowComponent} /> : null;
}
-function SheetPermissionPanelListContent() {
+function SheetPermissionPanelListContent({ ActionRowComponent }: Required<ISheetPermissionPanelListProps>) {
const [isCurrentSheet, setIsCurrentSheet] = useState(true);
const [currentRuleRanges, setCurrentRuleRanges] = useState<IRange[]>([]);
@@ -405,7 +409,7 @@ function SheetPermissionPanelListContent() {
)}
{hasSetProtectPermission && (
- <ActionRow className="univer-mt-auto univer-py-5">
+ <ActionRowComponent className="univer-mt-auto univer-py-5">
<Button
className="univer-w-full"
variant="primary"
@@ -424,7 +428,7 @@ function SheetPermissionPanelListContent() {
<div>+ </div>
{localeService.t<LocaleKey>('sheets-ui.permission.button.addNewPermission')}
</Button>
- </ActionRow>
+ </ActionRowComponent>
)}
</div>
);
diff --git a/packages/sheets-ui/src/views/permission/SheetPermissionUserDialog.tsx b/packages/sheets-ui/src/views/permission/SheetPermissionUserDialog.tsx
index 885d93097c..b2ca6c73e8 100644
--- a/packages/sheets-ui/src/views/permission/SheetPermissionUserDialog.tsx
+++ b/packages/sheets-ui/src/views/permission/SheetPermissionUserDialog.tsx
@@ -26,7 +26,11 @@ import { UNIVER_SHEET_PERMISSION_USER_DIALOG_ID } from '../../consts/permission'
import { SheetPermissionUserManagerService } from '../../services/permission/sheet-permission-user-list.service';
import { UserEmptyBase64 } from './user-dialog/constant';
-export const SheetPermissionUserDialog = () => {
+export interface ISheetPermissionUserDialogProps {
+ ActionRowComponent?: typeof ActionRow;
+}
+
+export const SheetPermissionUserDialog = ({ ActionRowComponent = ActionRow }: ISheetPermissionUserDialogProps = {}) => {
const [inputValue, setInputValue] = useState('');
const localeService = useDependency(LocaleService);
const dialogService = useDependency(IDialogService);
@@ -120,7 +124,7 @@ export const SheetPermissionUserDialog = () => {
)}
</div>
<div className="univer-h-px univer-w-full univer-bg-gray-200" />
- <ActionRow
+ <ActionRowComponent
className="univer-flex univer-items-center univer-justify-end univer-gap-1 univer-py-2"
>
<Button
@@ -137,7 +141,7 @@ export const SheetPermissionUserDialog = () => {
>
{localeService.t<LocaleKey>('sheets-ui.permission.button.confirm')}
</Button>
- </ActionRow>
+ </ActionRowComponent>
</div>
);
};
diff --git a/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailFooterPart.tsx b/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailFooterPart.tsx
index 57d0a035d9..1a6e16ced6 100644
--- a/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailFooterPart.tsx
+++ b/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailFooterPart.tsx
@@ -50,10 +50,11 @@ interface IPermissionDetailFooterPartProps {
editState: EditStateEnum;
viewState: ViewStateEnum;
oldRule?: IPermissionPanelRule;
+ ActionRowComponent?: typeof ActionRow;
}
export const PermissionDetailFooterPart = (props: IPermissionDetailFooterPartProps) => {
- const { viewState, editState, permissionId, ranges, rangesErrMsg, desc, oldRule, id } = props;
+ const { viewState, editState, permissionId, ranges, rangesErrMsg, desc, oldRule, id, ActionRowComponent = ActionRow } = props;
const sheetPermissionPanelModel = useDependency(SheetPermissionPanelModel);
const sidebarService = useDependency(ISidebarService);
const authzIoService = useDependency(IAuthzIoService);
@@ -71,7 +72,7 @@ export const PermissionDetailFooterPart = (props: IPermissionDetailFooterPartPro
const subUnitId = worksheet.getSheetId();
return (
- <ActionRow
+ <ActionRowComponent
className="univer-mt-auto univer-flex univer-flex-row-reverse univer-gap-2 univer-py-5"
>
<Button
@@ -235,6 +236,6 @@ export const PermissionDetailFooterPart = (props: IPermissionDetailFooterPartPro
>
{localeService.t<LocaleKey>('sheets-ui.permission.button.cancel')}
</Button>
- </ActionRow>
+ </ActionRowComponent>
);
};
diff --git a/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailPanel.tsx b/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailPanel.tsx
index b413077cc6..7e19dd1b83 100644
--- a/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailPanel.tsx
+++ b/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailPanel.tsx
@@ -26,14 +26,22 @@ import { PermissionDetailFooterPart } from './PermissionDetailFooterPart';
import { PermissionDetailMainPart } from './PermissionDetailMainPart';
import { PermissionDetailUserPart } from './PermissionDetailUserPart';
-interface ISheetPermissionPanelDetailProps {
+export interface ISheetPermissionPanelDetailProps {
fromSheetBar: boolean;
rule?: IPermissionPanelRule;
oldRule?: IPermissionPanelRule;
+ FooterComponent?: typeof PermissionDetailFooterPart;
+ UserComponent?: typeof PermissionDetailUserPart;
}
export const SheetPermissionPanelDetail = (props: ISheetPermissionPanelDetailProps) => {
- const { fromSheetBar, rule, oldRule } = props;
+ const {
+ fromSheetBar,
+ rule,
+ oldRule,
+ FooterComponent = PermissionDetailFooterPart,
+ UserComponent = PermissionDetailUserPart,
+ } = props;
const injector = useDependency(Injector);
const componentManager = useDependency(ComponentManager);
const activeRule: IPermissionPanelRule = rule ? generateRuleByUnitType(injector, rule) : generateDefaultRule(injector, fromSheetBar);
@@ -46,7 +54,7 @@ export const SheetPermissionPanelDetail = (props: ISheetPermissionPanelDetailPro
const [editState, setEditState] = useState<EditStateEnum>(activeRule.editState ?? EditStateEnum.OnlyMe);
const [viewState, setViewState] = useState<ViewStateEnum>(activeRule.viewState ?? ViewStateEnum.OthersCanView);
const CustomPermissionDetailUserPart = componentManager.get(UNIVER_SHEET_PERMISSION_USER_PART);
- const PermissionDetailUser = CustomPermissionDetailUserPart ?? PermissionDetailUserPart;
+ const PermissionDetailUser = CustomPermissionDetailUserPart ?? UserComponent;
useEffect(() => {
const univerInstanceService = injector.get(IUniverInstanceService);
@@ -88,7 +96,7 @@ export const SheetPermissionPanelDetail = (props: ISheetPermissionPanelDetailPro
permissionId: activeRule.permissionId,
}}
/>
- <PermissionDetailFooterPart
+ <FooterComponent
permissionId={activeRule.permissionId}
id={activeRule.id}
ranges={ranges}
diff --git a/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailUserPart.tsx b/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailUserPart.tsx
index 281a67fc01..5fb80be4d3 100644
--- a/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailUserPart.tsx
+++ b/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailUserPart.tsx
@@ -42,10 +42,20 @@ export interface IPermissionDetailUserPartProps {
viewState: ViewStateEnum;
onViewStateChange: (v: ViewStateEnum) => void;
permissionId: string;
+ SelectComponent?: typeof Select;
+ userListClassName?: string;
}
export const PermissionDetailUserPart = (props: IPermissionDetailUserPartProps) => {
- const { editState, onEditStateChange, viewState, onViewStateChange, permissionId } = props;
+ const {
+ editState,
+ onEditStateChange,
+ viewState,
+ onViewStateChange,
+ permissionId,
+ SelectComponent = Select,
+ userListClassName,
+ } = props;
const localeService = useDependency(LocaleService);
const dialogService = useDependency(IDialogService);
const authzIoService = useDependency(IAuthzIoService);
@@ -144,7 +154,7 @@ export const PermissionDetailUserPart = (props: IPermissionDetailUserPartProps)
className={clsx(`
univer-mb-2 univer-flex univer-h-[270px] univer-flex-col univer-overflow-y-auto univer-rounded-lg
univer-p-3
- `, borderClassName)}
+ `, borderClassName, userListClassName)}
>
<div className="univer-flex univer-items-center univer-justify-between univer-text-sm">
<span>{localeService.t<LocaleKey>('sheets-ui.permission.panel.designedPerson')}</span>
@@ -171,7 +181,7 @@ export const PermissionDetailUserPart = (props: IPermissionDetailUserPartProps)
>
{item.subject?.name}
</span>
- <Select
+ <SelectComponent
className="!univer-w-[90px] univer-min-w-0 univer-cursor-pointer"
borderless
value="edit"
diff --git a/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx b/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx
index a35d777bdd..64788a61e9 100644
--- a/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx
+++ b/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx
@@ -25,6 +25,7 @@ import { IRenderManagerService } from '@univerjs/engine-render';
import { ComponentManager, ContextMenuPosition, IMenuManagerService, IWorkbenchService, ToolbarItem, useConfigValue, useDependency, useObservable } from '@univerjs/ui';
import { useEffect, useMemo } from 'react';
import { EMPTY, merge } from 'rxjs';
+import { EMBEDDING_CELL_EDITOR_COMPONENT_KEY } from '../../common/keys';
import { SHEETS_UI_PLUGIN_CONFIG_KEY } from '../../config/config';
import { getEmbedSheetsTabCustomData } from '../../embed-tab-anchor';
import { ISheetEmbedRuntimeFocusCoordinator } from '../../services/sheet-embed-integration.service';
@@ -115,7 +116,11 @@ export function RenderSheetHeader() {
/**
* We should not write into this component anymore.
*/
-export function RenderSheetContent() {
+export interface IRenderSheetContentProps {
+ AutoFillPopupMenuComponent?: typeof AutoFillPopupMenu | null;
+}
+
+export function RenderSheetContent({ AutoFillPopupMenuComponent = AutoFillPopupMenu }: IRenderSheetContentProps = {}) {
const config = useConfigValue<IUniverSheetsUIConfig>(SHEETS_UI_PLUGIN_CONFIG_KEY);
const componentManager = useDependency(ComponentManager);
const workbook = useRootWorkbenchWorkbook();
@@ -127,6 +132,7 @@ export function RenderSheetContent() {
// We use string keys to avoid a hard dependency on sheets-shape-ui.
const ShapeTextEditorContainer = componentManager.get('SheetShapeTextEditorContainer') ?? componentManager.get('ShapeTextEditorContainer');
+ const CellEditorContainer = componentManager.get(EMBEDDING_CELL_EDITOR_COMPONENT_KEY) ?? EditorContainer;
useEffect(() => {
if (!workbook || activeEmbedTab || activeWorkbookEmbeddedRender || !rootWorkbenchOwnsSheet) {
@@ -149,8 +155,8 @@ export function RenderSheetContent() {
return (
<>
{ShapeTextEditorContainer && <ShapeTextEditorContainer />}
- {!config?.disableEdit && <EditorContainer />}
- <AutoFillPopupMenu />
+ {!config?.disableEdit && <CellEditorContainer />}
+ {AutoFillPopupMenuComponent && <AutoFillPopupMenuComponent />}
</>
);
}
diff --git a/packages/thread-comment-ui/src/index.ts b/packages/thread-comment-ui/src/index.ts
index ff5e35e831..17466bfca3 100644
--- a/packages/thread-comment-ui/src/index.ts
+++ b/packages/thread-comment-ui/src/index.ts
@@ -30,6 +30,8 @@ export { ThreadCommentDraftService } from './services/thread-comment-draft.servi
export type { IThreadCommentDraft } from './services/thread-comment-draft.service';
export { ThreadCommentPanelService } from './services/thread-comment-panel.service';
export type { ActiveCommentInfo } from './services/thread-comment-panel.service';
+export { MobileThreadCommentPanel } from './views/mobile/MobileThreadCommentPanel';
+export { MobileThreadCommentTree } from './views/mobile/MobileThreadCommentTree';
export { ThreadCommentPanel } from './views/ThreadCommentPanel';
export type { IThreadCommentPanelProps } from './views/ThreadCommentPanel';
export { ThreadCommentTree, ThreadCommentTreeLocation } from './views/ThreadCommentTree';
diff --git a/packages/thread-comment-ui/src/mobile-plugin.ts b/packages/thread-comment-ui/src/mobile-plugin.ts
index 3875779652..c2b6bf9feb 100644
--- a/packages/thread-comment-ui/src/mobile-plugin.ts
+++ b/packages/thread-comment-ui/src/mobile-plugin.ts
@@ -14,24 +14,59 @@
* limitations under the License.
*/
+import type { Dependency } from '@univerjs/core';
import type { IUniverThreadCommentUIConfig } from './config/config';
-import { DependentOn, ICommandService, IConfigService, Inject, Injector } from '@univerjs/core';
+import {
+ DependentOn,
+ ICommandService,
+ IConfigService,
+ Inject,
+ Injector,
+ merge,
+ mergeOverrideWithDependencies,
+ Plugin,
+ UniverInstanceType,
+} from '@univerjs/core';
import { UniverDocsUIPlugin } from '@univerjs/docs-ui';
import { UniverThreadCommentPlugin } from '@univerjs/thread-comment';
import { UniverMobileUIPlugin } from '@univerjs/ui';
-import { defaultPluginConfig } from './config/config';
-import { UniverThreadCommentUIPlugin } from './plugin';
+import pkg from '../package.json';
+import { SetActiveCommentOperation } from './commands/operations/comment.operations';
+import { defaultPluginConfig, THREAD_COMMENT_UI_PLUGIN_CONFIG_KEY } from './config/config';
+import { ThreadCommentDraftService } from './services/thread-comment-draft.service';
+import { ThreadCommentPanelService } from './services/thread-comment-panel.service';
+import { PLUGIN_NAME } from './types/const';
@DependentOn(UniverThreadCommentPlugin, UniverDocsUIPlugin, UniverMobileUIPlugin)
-export class UniverThreadCommentMobileUIPlugin extends UniverThreadCommentUIPlugin {
- static override pluginName = UniverThreadCommentUIPlugin.pluginName;
+export class UniverThreadCommentMobileUIPlugin extends Plugin {
+ static override pluginName = PLUGIN_NAME;
+ static override packageName = pkg.name;
+ static override version = pkg.version;
+ static override type = UniverInstanceType.UNIVER_UNKNOWN;
constructor(
- config: Partial<IUniverThreadCommentUIConfig> = defaultPluginConfig,
- @Inject(Injector) injector: Injector,
- @ICommandService commandService: ICommandService,
- @IConfigService configService: IConfigService
+ private readonly _config: Partial<IUniverThreadCommentUIConfig> = defaultPluginConfig,
+ @Inject(Injector) protected override _injector: Injector,
+ @ICommandService private readonly _commandService: ICommandService,
+ @IConfigService private readonly _configService: IConfigService
) {
- super(config, injector, commandService, configService);
+ super();
+
+ const { menu, ...rest } = merge({}, defaultPluginConfig, this._config);
+ if (menu) {
+ this._configService.setConfig('menu', menu, { merge: true });
+ }
+ this._configService.setConfig(THREAD_COMMENT_UI_PLUGIN_CONFIG_KEY, rest);
+ }
+
+ override onStarting(): void {
+ (mergeOverrideWithDependencies([
+ [ThreadCommentDraftService],
+ [ThreadCommentPanelService],
+ ], this._config?.overrides) as Dependency[]).forEach((dependency) => {
+ this._injector.add(dependency);
+ });
+
+ this._commandService.registerCommand(SetActiveCommentOperation);
}
}
diff --git a/packages/thread-comment-ui/src/views/ThreadCommentEditor.tsx b/packages/thread-comment-ui/src/views/ThreadCommentEditor.tsx
index 4db8c9bed9..a71e960af1 100644
--- a/packages/thread-comment-ui/src/views/ThreadCommentEditor.tsx
+++ b/packages/thread-comment-ui/src/views/ThreadCommentEditor.tsx
@@ -43,6 +43,7 @@ export interface IThreadCommentEditorProps {
subUnitId: string;
type: UniverInstanceType;
editorId: string;
+ ActionRowComponent?: typeof ActionRow;
}
export interface IThreadCommentEditorInstance {
@@ -58,7 +59,7 @@ function getSnapshot(body: IDocumentBody): IDocumentData {
}
export const ThreadCommentEditor = forwardRef<IThreadCommentEditorInstance, IThreadCommentEditorProps>((props, ref) => {
- const { comment, onSave, id, onCancel, autoFocus, unitId, type, editorId } = props;
+ const { comment, onSave, id, onCancel, autoFocus, unitId, type, editorId, ActionRowComponent = ActionRow } = props;
const commandService = useDependency(ICommandService);
const localeService = useDependency(LocaleService);
const [editing, setEditing] = useState(false);
@@ -209,7 +210,7 @@ export const ThreadCommentEditor = forwardRef<IThreadCommentEditorInstance, IThr
</div>
{editing
? (
- <ActionRow
+ <ActionRowComponent
className="univer-mt-3 univer-flex univer-flex-row univer-justify-end univer-gap-2"
>
<Button
@@ -235,7 +236,7 @@ export const ThreadCommentEditor = forwardRef<IThreadCommentEditorInstance, IThr
>
{localeService.t<LocaleKey>(id ? 'thread-comment-ui.editor.save' : 'thread-comment-ui.editor.reply')}
</Button>
- </ActionRow>
+ </ActionRowComponent>
)
: null}
</div>
diff --git a/packages/thread-comment-ui/src/views/ThreadCommentPanel.tsx b/packages/thread-comment-ui/src/views/ThreadCommentPanel.tsx
index 682574c47a..e1e6707c3c 100644
--- a/packages/thread-comment-ui/src/views/ThreadCommentPanel.tsx
+++ b/packages/thread-comment-ui/src/views/ThreadCommentPanel.tsx
@@ -49,6 +49,10 @@ export interface IThreadCommentPanelProps {
showComments?: string[];
formatRef?: (comment: IThreadComment) => string;
onTempCommentClose?: () => void;
+ autoFocusActiveComment?: boolean;
+ ActionRowComponent?: typeof ActionRow;
+ SelectComponent?: typeof Select;
+ ThreadCommentTreeComponent?: typeof ThreadCommentTree;
}
interface IThreadCommentWithUsers extends IThreadComment {
@@ -74,6 +78,10 @@ export const ThreadCommentPanel = (props: IThreadCommentPanelProps) => {
showComments,
formatRef,
onTempCommentClose,
+ autoFocusActiveComment = false,
+ ActionRowComponent = ActionRow,
+ SelectComponent = Select,
+ ThreadCommentTreeComponent = ThreadCommentTree,
} = props;
const [unit, setUnit] = useState('all');
const [status, setStatus] = useState('all');
@@ -213,7 +221,7 @@ export const ThreadCommentPanel = (props: IThreadCommentPanelProps) => {
}, [activeCommentId, location]);
const renderComment = (section: ThreadCommentPanelSection) => (comment: IThreadComment, index: number) => (
- <ThreadCommentTree
+ <ThreadCommentTreeComponent
full
location={location}
getSubUnitName={getSubUnitName}
@@ -226,6 +234,7 @@ export const ThreadCommentPanel = (props: IThreadCommentPanelProps) => {
type={type}
showEdit={!comment.id || isSameThreadCommentTarget(activeCommentId, comment)}
showHighlight={isSameThreadCommentTarget(activeCommentId, comment)}
+ autoFocus={autoFocusActiveComment && isSameThreadCommentTarget(activeCommentId, comment)}
onClick={() => {
shouldScrollRef.current = false;
if (!comment.resolved) {
@@ -270,7 +279,7 @@ export const ThreadCommentPanel = (props: IThreadCommentPanelProps) => {
<div className="univer-mt-3 univer-flex univer-flex-row univer-justify-between">
{type === UniverInstanceType.UNIVER_SHEET
? (
- <Select
+ <SelectComponent
borderless
value={unit}
options={[
@@ -287,7 +296,7 @@ export const ThreadCommentPanel = (props: IThreadCommentPanelProps) => {
/>
)
: null}
- <Select
+ <SelectComponent
borderless
value={status}
options={[
@@ -323,22 +332,22 @@ export const ThreadCommentPanel = (props: IThreadCommentPanelProps) => {
{localeService.t<LocaleKey>('thread-comment-ui.panel.empty')}
{isFiltering
? (
- <ActionRow className="univer-mt-2 univer-flex univer-flex-row">
+ <ActionRowComponent className="univer-mt-2 univer-flex univer-flex-row">
<Button onClick={onReset}>
{localeService.t<LocaleKey>('thread-comment-ui.panel.reset')}
</Button>
- </ActionRow>
+ </ActionRowComponent>
)
: !disableAdd
? (
- <ActionRow
+ <ActionRowComponent
className="univer-mt-2 univer-flex univer-flex-row"
>
<Button onClick={onAdd}>
<IncreaseIcon className="univer-mr-1.5" />
{localeService.t<LocaleKey>('thread-comment-ui.panel.addComment')}
</Button>
- </ActionRow>
+ </ActionRowComponent>
)
: null}
</div>
diff --git a/packages/thread-comment-ui/src/views/ThreadCommentTree.tsx b/packages/thread-comment-ui/src/views/ThreadCommentTree.tsx
index 0bfbdc372c..9555c3b42e 100644
--- a/packages/thread-comment-ui/src/views/ThreadCommentTree.tsx
+++ b/packages/thread-comment-ui/src/views/ThreadCommentTree.tsx
@@ -74,6 +74,8 @@ export interface IThreadCommentTreeProps {
onAfterDeleteComment?: (comment: IThreadComment) => void | Promise<void>;
onResolve?: (resolved: boolean) => void;
style?: React.CSSProperties;
+ DropdownComponent?: typeof Dropdown;
+ EditorComponent?: typeof ThreadCommentEditor;
}
export interface IThreadCommentItemProps {
@@ -91,6 +93,8 @@ export interface IThreadCommentItemProps {
onAfterDeleteComment?: (comment: IThreadComment) => void | Promise<void>;
type: UniverInstanceType;
threadCommentEditorId: string;
+ DropdownComponent: typeof Dropdown;
+ EditorComponent: typeof ThreadCommentEditor;
}
const MOCK_ID = '__mock__';
@@ -125,6 +129,8 @@ const ThreadCommentItem = (props: IThreadCommentItemProps) => {
onAfterDeleteComment,
type,
threadCommentEditorId,
+ DropdownComponent,
+ EditorComponent,
} = props;
const commandService = useDependency(ICommandService);
const localeService = useDependency(LocaleService);
@@ -221,7 +227,7 @@ const ThreadCommentItem = (props: IThreadCommentItemProps) => {
)}
{isCommentBySelf && !isMock && !resolved
? (
- <Dropdown
+ <DropdownComponent
overlay={(
<div dir={direction} className="univer-rounded-lg">
<ul
@@ -273,7 +279,7 @@ const ThreadCommentItem = (props: IThreadCommentItemProps) => {
>
<MoreHorizontalIcon />
</button>
- </Dropdown>
+ </DropdownComponent>
)
: null}
</div>
@@ -293,7 +299,7 @@ const ThreadCommentItem = (props: IThreadCommentItemProps) => {
)}
{editing
? (
- <ThreadCommentEditor
+ <EditorComponent
type={type}
id={item.id}
comment={item}
@@ -385,6 +391,8 @@ export const ThreadCommentTree = (props: IThreadCommentTreeProps) => {
type,
style,
full,
+ DropdownComponent = Dropdown,
+ EditorComponent = ThreadCommentEditor,
} = props;
const threadCommentModel = useDependency(ThreadCommentModel);
const [isHover, setIsHover] = useState(false);
@@ -610,6 +618,8 @@ export const ThreadCommentTree = (props: IThreadCommentTreeProps) => {
resolved={comments?.root.resolved}
type={type}
threadCommentEditorId={threadCommentEditorId}
+ DropdownComponent={DropdownComponent}
+ EditorComponent={EditorComponent}
onClose={onClose}
onEditingChange={(editing) => {
if (editing) {
@@ -646,7 +656,7 @@ export const ThreadCommentTree = (props: IThreadCommentTreeProps) => {
</div>
{editorVisible && (
<div>
- <ThreadCommentEditor
+ <EditorComponent
key={`${autoFocus}`}
ref={editorRef}
type={type}
diff --git a/packages/thread-comment-ui/src/views/__tests__/ThreadCommentPanel.spec.tsx b/packages/thread-comment-ui/src/views/__tests__/ThreadCommentPanel.spec.tsx
index 90f9c7aa68..abbbac091a 100644
--- a/packages/thread-comment-ui/src/views/__tests__/ThreadCommentPanel.spec.tsx
+++ b/packages/thread-comment-ui/src/views/__tests__/ThreadCommentPanel.spec.tsx
@@ -19,6 +19,7 @@ import type { ISuccinctDocRangeParam } from '@univerjs/engine-render';
import type { IThreadComment } from '@univerjs/thread-comment';
import type { IShortcutItem } from '@univerjs/ui';
import type { Root } from 'react-dom/client';
+import type { IThreadCommentTreeProps } from '../ThreadCommentTree';
import {
CommandService,
ConfigService,
@@ -71,6 +72,12 @@ import { ThreadCommentPanel } from '../ThreadCommentPanel';
const UNIT_ID = 'unit-1';
const SHEET_ID = 'sheet-1';
const IRenderManagerService = createIdentifier<TestRenderManagerService>('engine-render.render-manager.service');
+let renderedTreeProps: IThreadCommentTreeProps[] = [];
+
+function TestThreadCommentTree(props: IThreadCommentTreeProps) {
+ renderedTreeProps.push(props);
+ return <div data-comment-id={props.id} />;
+}
interface IEditorRecord {
id: string;
@@ -442,6 +449,7 @@ describe('ThreadCommentPanel', () => {
beforeEach(() => {
document.body.innerHTML = '';
+ renderedTreeProps = [];
});
afterEach(() => {
@@ -489,6 +497,31 @@ describe('ThreadCommentPanel', () => {
expect(panelText.indexOf('thread-comment-ui.panel.solved')).toBeLessThan(panelText.indexOf('Resolved comment'));
});
+ it('auto-focuses the active comment when requested by the host panel', () => {
+ const testBed = createPanelTestBed();
+ addRootComment(testBed.threadCommentModel, createComment({ id: 'comment-1', ref: 'A1' }));
+ testBed.panelService.setActiveComment({
+ unitId: UNIT_ID,
+ subUnitId: SHEET_ID,
+ commentId: 'comment-1',
+ });
+
+ ({ container, root } = renderPanel(
+ testBed.injector,
+ <ThreadCommentPanel
+ unitId={UNIT_ID}
+ subUnitId$={new BehaviorSubject<string | undefined>(SHEET_ID)}
+ type={UniverInstanceType.UNIVER_SHEET}
+ onAdd={() => undefined}
+ getSubUnitName={(subUnitId) => subUnitId}
+ autoFocusActiveComment
+ ThreadCommentTreeComponent={TestThreadCommentTree}
+ />
+ ));
+
+ expect(renderedTreeProps.find((props) => props.id === 'comment-1')?.autoFocus).toBe(true);
+ });
+
it('keeps an empty-id temporary target active and shows its editor', () => {
const testBed = createPanelTestBed();
const onTempCommentClose = vi.fn();
diff --git a/packages/thread-comment-ui/src/views/mobile/MobileThreadCommentEditor.tsx b/packages/thread-comment-ui/src/views/mobile/MobileThreadCommentEditor.tsx
new file mode 100644
index 0000000000..220c761662
--- /dev/null
+++ b/packages/thread-comment-ui/src/views/mobile/MobileThreadCommentEditor.tsx
@@ -0,0 +1,24 @@
+/**
+ * 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 { IThreadCommentEditorInstance, IThreadCommentEditorProps } from '../ThreadCommentEditor';
+import { MobileActionRowGroup } from '@univerjs/design';
+import { forwardRef } from 'react';
+import { ThreadCommentEditor } from '../ThreadCommentEditor';
+
+export const MobileThreadCommentEditor = forwardRef<IThreadCommentEditorInstance, IThreadCommentEditorProps>(
+ (props, ref) => <ThreadCommentEditor {...props} ref={ref} ActionRowComponent={MobileActionRowGroup} />
+);
diff --git a/packages/thread-comment-ui/src/views/mobile/MobileThreadCommentPanel.tsx b/packages/thread-comment-ui/src/views/mobile/MobileThreadCommentPanel.tsx
new file mode 100644
index 0000000000..b8a2864503
--- /dev/null
+++ b/packages/thread-comment-ui/src/views/mobile/MobileThreadCommentPanel.tsx
@@ -0,0 +1,31 @@
+/**
+ * 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 { IThreadCommentPanelProps } from '../ThreadCommentPanel';
+import { MobileActionRowGroup, MobileSelect } from '@univerjs/design';
+import { ThreadCommentPanel } from '../ThreadCommentPanel';
+import { MobileThreadCommentTree } from './MobileThreadCommentTree';
+
+export function MobileThreadCommentPanel(props: IThreadCommentPanelProps) {
+ return (
+ <ThreadCommentPanel
+ {...props}
+ ActionRowComponent={MobileActionRowGroup}
+ SelectComponent={MobileSelect}
+ ThreadCommentTreeComponent={MobileThreadCommentTree}
+ />
+ );
+}
diff --git a/packages/thread-comment-ui/src/views/mobile/MobileThreadCommentTree.tsx b/packages/thread-comment-ui/src/views/mobile/MobileThreadCommentTree.tsx
new file mode 100644
index 0000000000..cd29f160f9
--- /dev/null
+++ b/packages/thread-comment-ui/src/views/mobile/MobileThreadCommentTree.tsx
@@ -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 { IThreadCommentTreeProps } from '../ThreadCommentTree';
+import { MobileDropdown } from '@univerjs/design';
+import { ThreadCommentTree } from '../ThreadCommentTree';
+import { MobileThreadCommentEditor } from './MobileThreadCommentEditor';
+
+export function MobileThreadCommentTree(props: IThreadCommentTreeProps) {
+ return (
+ <ThreadCommentTree
+ {...props}
+ DropdownComponent={MobileDropdown}
+ EditorComponent={MobileThreadCommentEditor}
+ />
+ );
+}
diff --git a/packages/ui/src/const.ts b/packages/ui/src/const.ts
index f81f4071a2..5846c3175f 100644
--- a/packages/ui/src/const.ts
+++ b/packages/ui/src/const.ts
@@ -18,5 +18,3 @@
* @ignore
*/
export const UNI_DISABLE_CHANGING_FOCUS_KEY = 'UNI_DISABLE_CHANGING_FOCUS';
-
-export const MOBILE_UI_MODE = 'MOBILE_UI_MODE';
diff --git a/packages/ui/src/controllers/mobile/components.controller.ts b/packages/ui/src/controllers/mobile/components.controller.ts
new file mode 100644
index 0000000000..6281725135
--- /dev/null
+++ b/packages/ui/src/controllers/mobile/components.controller.ts
@@ -0,0 +1,80 @@
+/**
+ * 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 { Disposable, Inject } from '@univerjs/core';
+import { MobileColorPicker } from '@univerjs/design';
+import {
+ ExpandIcon,
+ IncreaseIcon,
+ KeyboardIcon,
+ MoreDownIcon,
+ RedoIcon,
+ ReduceIcon,
+ ShrinkIcon,
+ UndoIcon,
+} from '@univerjs/icons';
+import { ComponentManager } from '../../common/component-manager';
+import { IconManager } from '../../common/icon-manager';
+import { COLOR_PICKER_COMPONENT } from '../../views/color-picker/interface';
+import { COMMON_LABEL_COMPONENT, CommonLabel } from '../../views/CommonLabel';
+import { EMOJI_PICKER_COMPONENT } from '../../views/emoji-picker/EmojiPicker';
+import { MobileEmojiPicker } from '../../views/emoji-picker/MobileEmojiPicker';
+import { FONT_FAMILY_COMPONENT, FontFamily } from '../../views/font-family/FontFamily';
+import { FONT_FAMILY_ITEM_COMPONENT, FontFamilyItem } from '../../views/font-family/FontFamilyItem';
+import { FontSize } from '../../views/font-size/FontSize';
+import { FONT_SIZE_COMPONENT } from '../../views/font-size/interface';
+import { HEADING_ITEM_COMPONENT, HeadingItem } from '../../views/HeadingItem';
+import { SYMBOL_PICKER_COMPONENT, SymbolPicker } from '../../views/symbol-picker/SymbolPicker';
+
+export class MobileComponentsController extends Disposable {
+ constructor(
+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,
+ @Inject(IconManager) private readonly _iconManager: IconManager
+ ) {
+ super();
+
+ this._registerIcons();
+ this._registerComponents();
+ }
+
+ private _registerIcons(): void {
+ this.disposeWithMe(this._iconManager.register({
+ ExpandIcon,
+ IncreaseIcon,
+ KeyboardIcon,
+ MoreDownIcon,
+ RedoIcon,
+ ReduceIcon,
+ ShrinkIcon,
+ UndoIcon,
+ }));
+ }
+
+ private _registerComponents(): void {
+ ([
+ [COMMON_LABEL_COMPONENT, CommonLabel],
+ [HEADING_ITEM_COMPONENT, HeadingItem],
+ [FONT_FAMILY_COMPONENT, FontFamily],
+ [FONT_FAMILY_ITEM_COMPONENT, FontFamilyItem],
+ [FONT_SIZE_COMPONENT, FontSize],
+ [COLOR_PICKER_COMPONENT, MobileColorPicker],
+ [EMOJI_PICKER_COMPONENT, MobileEmojiPicker],
+ [SYMBOL_PICKER_COMPONENT, SymbolPicker],
+ ] as const).forEach(([key, component]) => {
+ this.disposeWithMe(this._componentManager.register(key, component));
+ });
+ }
+}
diff --git a/packages/ui/src/controllers/ui/ui-mobile.controller.ts b/packages/ui/src/controllers/ui/ui-mobile.controller.ts
index 4677cc8850..7cfe3a76a9 100644
--- a/packages/ui/src/controllers/ui/ui-mobile.controller.ts
+++ b/packages/ui/src/controllers/ui/ui-mobile.controller.ts
@@ -20,7 +20,7 @@ import type { IUIController, IWorkbenchOptions } from './ui.controller';
import { Inject, Injector, IUniverInstanceService, LifecycleService, toDisposable } from '@univerjs/core';
import { unmount } from '@univerjs/design';
import { IRenderManagerService } from '@univerjs/engine-render';
-import { menuSchema } from '../../menu/schema';
+import { mobileMenuSchema } from '../../menu/mobile-schema';
import { ILayoutService } from '../../services/layout/layout.service';
import { IMenuManagerService } from '../../services/menu/menu-manager.service';
import { BuiltInUIPart, IUIPartsService } from '../../services/parts/parts.service';
@@ -44,7 +44,7 @@ export class MobileUIController extends SingleUnitUIController implements IUICon
) {
super(injector, instanceService, layoutService, lifecycleService, renderManagerService);
- menuManagerService.mergeMenu(menuSchema);
+ menuManagerService.mergeMenu(mobileMenuSchema);
this._initBuiltinComponents(uiPartsService);
this._bootstrapWorkbench();
}
diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts
index 2232064359..5f63fe8731 100644
--- a/packages/ui/src/index.ts
+++ b/packages/ui/src/index.ts
@@ -24,7 +24,7 @@ export { mergeMenuConfigs } from './common/menu-merge-configs';
export { objectPermissionMenuItemFactory } from './common/object-permission-menu';
export { UI_PLUGIN_CONFIG_KEY } from './config/config';
export type { IUniverUIConfig } from './config/config';
-export { MOBILE_UI_MODE, UNI_DISABLE_CHANGING_FOCUS_KEY } from './const';
+export { UNI_DISABLE_CHANGING_FOCUS_KEY } from './const';
export { ErrorController } from './controllers/error/error.controller';
export {
CopyShortcutItem,
diff --git a/packages/ui/src/menu/mobile-schema.ts b/packages/ui/src/menu/mobile-schema.ts
new file mode 100644
index 0000000000..6375c6b07c
--- /dev/null
+++ b/packages/ui/src/menu/mobile-schema.ts
@@ -0,0 +1,35 @@
+/**
+ * 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 { MenuSchemaType } from '../services/menu/menu-manager.service';
+import { RedoCommand, UndoCommand } from '@univerjs/core';
+import { RibbonStartGroup } from '../services/menu/types';
+import { RedoMenuItemFactory, UndoMenuItemFactory } from './history.menu';
+
+export const mobileMenuSchema: 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,
+ },
+ },
+};
diff --git a/packages/ui/src/mobile-plugin.ts b/packages/ui/src/mobile-plugin.ts
index 52ccc67eb2..a155c343e2 100644
--- a/packages/ui/src/mobile-plugin.ts
+++ b/packages/ui/src/mobile-plugin.ts
@@ -36,17 +36,14 @@ import { ComponentManager } from './common/component-manager';
import { IconManager } from './common/icon-manager';
import { ZIndexManager } from './common/z-index-manager';
import { defaultPluginConfig, UI_PLUGIN_CONFIG_KEY } from './config/config';
-import { MOBILE_UI_MODE } from './const';
-import { ComponentsController } from './controllers/components.controller';
import { ErrorController } from './controllers/error/error.controller';
-import { FeatureSearchController } from './controllers/feature-search/feature-search.controller';
+import { MobileComponentsController } from './controllers/mobile/components.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';
import { IUIController } from './controllers/ui/ui.controller';
import { DesktopBeforeCloseService, IBeforeCloseService } from './services/before-close/before-close.service';
import { BrowserClipboardService, IClipboardInterfaceService } from './services/clipboard/clipboard-interface.service';
-import { DesktopConfirmService } from './services/confirm/desktop-confirm.service';
+import { MobileConfirmService } from './services/confirm/mobile-confirm.service';
import { ContextMenuHostService, IContextMenuHostService } from './services/contextmenu/contextmenu-host.service';
import { ContextMenuService, IContextMenuService } from './services/contextmenu/contextmenu.service';
import { IDialogService } from './services/dialog/dialog.service';
@@ -73,7 +70,6 @@ import {
} from './services/presence/unit-presence-ui-adapter.service';
import { DesktopRibbonService, IRibbonService } from './services/ribbon/ribbon.service';
import { IUIRuntimeScopeService, UIRuntimeScopeService } from './services/runtime-scope/ui-runtime-scope.service';
-import { ShortcutPanelService } from './services/shortcut/shortcut-panel.service';
import { IShortcutService, ShortcutService } from './services/shortcut/shortcut.service';
import { DesktopSidebarService } from './services/sidebar/desktop-sidebar.service';
import { ISidebarService } from './services/sidebar/sidebar.service';
@@ -113,7 +109,6 @@ export class UniverMobileUIPlugin extends Plugin {
if (rest.disableAutoFocus) {
this._contextService.setContextValue(DISABLE_AUTO_FOCUS_KEY, true);
}
- this._contextService.setContextValue(MOBILE_UI_MODE, true);
if (menu) {
this._configService.setConfig('menu', menu, { merge: true });
}
@@ -124,12 +119,11 @@ export class UniverMobileUIPlugin extends Plugin {
registerDependencies(this._injector, mergeOverrideWithDependencies([
[ComponentManager],
[IconManager],
- [ComponentsController],
+ [MobileComponentsController],
[ThemeSwitcherService],
[UndoRedoGroupService],
[IWorkbenchService, { useClass: WorkbenchService }],
[ZIndexManager],
- [ShortcutPanelService],
[IUIPartsService, { useClass: UIPartsService }],
[ILayoutService, { useClass: DesktopLayoutService }],
[IRibbonService, { useClass: DesktopRibbonService }],
@@ -144,7 +138,7 @@ export class UniverMobileUIPlugin extends Plugin {
[INotificationService, { useClass: DesktopNotificationService, lazy: true }],
[IGalleryService, { useClass: DesktopGalleryService, lazy: true }],
[IDialogService, { useClass: MobileDialogService, lazy: true }],
- [IConfirmService, { useClass: DesktopConfirmService, lazy: true }],
+ [IConfirmService, { useClass: MobileConfirmService, lazy: true }],
[ISidebarService, { useClass: DesktopSidebarService, lazy: true }],
[IMessageService, { useClass: DesktopMessageService, lazy: true }],
[ILocalStorageService, { useClass: DesktopLocalStorageService, lazy: true }],
@@ -164,12 +158,10 @@ export class UniverMobileUIPlugin extends Plugin {
],
[SharedController],
[ErrorController],
- [FeatureSearchController],
- [ShortcutPanelController],
], this._config.override));
touchDependencies(this._injector, [
- [ComponentsController],
+ [MobileComponentsController],
[IUIController],
[ErrorController],
]);
@@ -178,13 +170,6 @@ export class UniverMobileUIPlugin extends Plugin {
override onReady(): void {
touchDependencies(this._injector, [
[SharedController],
- [FeatureSearchController],
- ]);
- }
-
- override onSteady(): void {
- touchDependencies(this._injector, [
- [ShortcutPanelController],
]);
}
}
diff --git a/packages/ui/src/services/confirm/mobile-confirm.service.ts b/packages/ui/src/services/confirm/mobile-confirm.service.ts
new file mode 100644
index 0000000000..71470f1374
--- /dev/null
+++ b/packages/ui/src/services/confirm/mobile-confirm.service.ts
@@ -0,0 +1,89 @@
+/**
+ * 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 { IConfirmService, IDisposable } from '@univerjs/core';
+import type { IConfirmPartMethodOptions } from '../../views/components/confirm-part/interface';
+import { Disposable, Inject, Injector, toDisposable } from '@univerjs/core';
+import { BehaviorSubject } from 'rxjs';
+import { connectInjector } from '../../utils/di';
+import { MobileConfirmPart } from '../../views/components/confirm-part/MobileConfirmPart';
+import { BuiltInUIPart, IUIPartsService } from '../parts/parts.service';
+
+export class MobileConfirmService extends Disposable implements IConfirmService<IConfirmPartMethodOptions> {
+ private _confirmOptions: IConfirmPartMethodOptions[] = [];
+ readonly confirmOptions$ = new BehaviorSubject<IConfirmPartMethodOptions[]>([]);
+
+ constructor(
+ @Inject(Injector) private readonly _injector: Injector,
+ @IUIPartsService uiPartsService: IUIPartsService
+ ) {
+ super();
+
+ this.disposeWithMe(
+ uiPartsService.registerComponent(
+ BuiltInUIPart.GLOBAL,
+ () => connectInjector(MobileConfirmPart, this._injector)
+ )
+ );
+ }
+
+ override dispose(): void {
+ super.dispose();
+ this._confirmOptions = [];
+ this.confirmOptions$.complete();
+ }
+
+ open(option: IConfirmPartMethodOptions): IDisposable {
+ const existing = this._confirmOptions.some((item) => item.id === option.id);
+ if (existing) {
+ this._confirmOptions = this._confirmOptions.map((item) => item.id === option.id
+ ? { ...option, visible: true }
+ : item);
+ } else {
+ this._confirmOptions.push({ ...option, visible: true });
+ }
+ this.confirmOptions$.next(this._confirmOptions);
+
+ return toDisposable(() => {
+ this._confirmOptions = [];
+ this.confirmOptions$.next([]);
+ });
+ }
+
+ confirm(params: IConfirmPartMethodOptions): Promise<boolean> {
+ return new Promise((resolve) => {
+ const disposable = this.open({
+ ...params,
+ onConfirm: () => {
+ disposable.dispose();
+ resolve(true);
+ },
+ onClose: () => {
+ disposable.dispose();
+ resolve(false);
+ },
+ });
+ });
+ }
+
+ close(id: string): void {
+ this._confirmOptions = this._confirmOptions.map((item) => ({
+ ...item,
+ visible: item.id === id ? false : item.visible,
+ }));
+ this.confirmOptions$.next([...this._confirmOptions]);
+ }
+}
diff --git a/packages/ui/src/views/components/confirm-part/MobileConfirmPart.tsx b/packages/ui/src/views/components/confirm-part/MobileConfirmPart.tsx
new file mode 100644
index 0000000000..31469630cb
--- /dev/null
+++ b/packages/ui/src/views/components/confirm-part/MobileConfirmPart.tsx
@@ -0,0 +1,95 @@
+/**
+ * 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 { IMobileConfirmProps } from '@univerjs/design';
+import type { ReactElement } from 'react';
+import type { IConfirmChildrenProps, IConfirmPartMethodOptions, IContextConfirmProps } from './interface';
+import { IConfirmService } from '@univerjs/core';
+import { MobileConfirm } from '@univerjs/design';
+import { cloneElement, useState } from 'react';
+import { useDependency, useObservable } from '../../../utils/di';
+import { CustomLabel } from '../../custom-label/CustomLabel';
+
+function MobileContextConfirm(props: IContextConfirmProps) {
+ const { children, onClose, onConfirm } = props;
+ const [hooks] = useState<IConfirmChildrenProps['hooks']>({});
+
+ // eslint-disable-next-line react/no-clone-element
+ const childrenWithHooks = children ? cloneElement(children, { hooks }) : null;
+
+ return (
+ <MobileConfirm
+ {...props}
+ onClose={() => {
+ const beforeClose = hooks.beforeClose;
+ if (beforeClose) {
+ const result = beforeClose();
+ if (result.cancel) {
+ return;
+ }
+ onClose?.(result);
+ return;
+ }
+
+ onClose?.();
+ }}
+ onConfirm={() => {
+ const beforeConfirm = hooks.beforeConfirm;
+ if (beforeConfirm) {
+ const result = beforeConfirm();
+ if (result.cancel) {
+ return;
+ }
+ onConfirm?.(result);
+ return;
+ }
+
+ onConfirm?.();
+ }}
+ >
+ {childrenWithHooks}
+ </MobileConfirm>
+ );
+}
+
+export function MobileConfirmPart() {
+ const confirmService = useDependency(IConfirmService) as IConfirmService<IConfirmPartMethodOptions>;
+ const confirmOptions = useObservable(confirmService.confirmOptions$, []);
+
+ const props = confirmOptions.map((options) => {
+ const { children, title, ...restProps } = options;
+ const confirmProps = restProps as IMobileConfirmProps & { id: string };
+
+ for (const key of ['children', 'title']) {
+ const optionKey = key as keyof IConfirmPartMethodOptions;
+ const customLabelProps = options[optionKey] as any;
+ if (customLabelProps) {
+ (confirmProps as any)[optionKey] = <CustomLabel {...customLabelProps} />;
+ }
+ }
+
+ return confirmProps;
+ });
+
+ return props.map((options) => (
+ <MobileContextConfirm
+ key={options.id}
+ {...options}
+ >
+ {options.children as ReactElement<IConfirmChildrenProps>}
+ </MobileContextConfirm>
+ ));
+}
diff --git a/packages/ui/src/views/components/confirm-part/__tests__/ConfirmPart.spec.tsx b/packages/ui/src/views/components/confirm-part/__tests__/ConfirmPart.spec.tsx
index 4cea50c919..8d662e4859 100644
--- a/packages/ui/src/views/components/confirm-part/__tests__/ConfirmPart.spec.tsx
+++ b/packages/ui/src/views/components/confirm-part/__tests__/ConfirmPart.spec.tsx
@@ -25,6 +25,7 @@ import { DesktopConfirmService } from '../../../../services/confirm/desktop-conf
import { IUIPartsService, UIPartsService } from '../../../../services/parts/parts.service';
import { RediProvider } from '../../../../utils/di';
import { ConfirmPart } from '../ConfirmPart';
+import { MobileConfirmPart } from '../MobileConfirmPart';
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -159,4 +160,22 @@ describe('ConfirmPart', () => {
disposable.dispose();
rendered.dispose();
});
+
+ it('renders service confirmations with the mobile confirm surface', async () => {
+ const rendered = renderWithDependencies(<MobileConfirmPart />);
+ const confirmService = rendered.injector.get(IConfirmService) as IConfirmService<IConfirmPartMethodOptions>;
+
+ act(() => {
+ confirmService.open({
+ id: 'mobile-confirm',
+ children: { title: <span>Mobile confirmation</span> },
+ confirmText: 'Confirm',
+ });
+ });
+
+ expect(await screen.findByText('Mobile confirmation')).toBeTruthy();
+ expect(screen.getByRole('dialog').classList.contains('!univer-bottom-0')).toBe(true);
+
+ rendered.dispose();
+ });
});
diff --git a/packages/ui/src/views/components/context-menu/MobileContextMenu.tsx b/packages/ui/src/views/components/context-menu/MobileContextMenu.tsx
index 7b2accc5df..797a213b3c 100644
--- a/packages/ui/src/views/components/context-menu/MobileContextMenu.tsx
+++ b/packages/ui/src/views/components/context-menu/MobileContextMenu.tsx
@@ -17,10 +17,10 @@
import type { ComponentProps } from 'react';
import type { LocaleKey } from '../../../locale/types';
import type { ContextMenuEvent, IContextMenuTriggerContext } from '../../../services/contextmenu/contextmenu.service';
+import type { MobileMenu } from '../../menu/mobile/MobileMenu';
import { ICommandService, LocaleService } from '@univerjs/core';
import { ConfigContext } from '@univerjs/design';
-import { useContext, useEffect, useMemo, useRef, useState } from 'react';
-import { createPortal } from 'react-dom';
+import { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { IContextMenuHostService } from '../../../services/contextmenu/contextmenu-host.service';
import { IContextMenuService } from '../../../services/contextmenu/contextmenu.service';
import { ILayoutService } from '../../../services/layout/layout.service';
@@ -28,7 +28,6 @@ import { IMenuManagerService } from '../../../services/menu/menu-manager.service
import { ContextMenuPosition } from '../../../services/menu/types';
import { IUIRuntimeScopeService } from '../../../services/runtime-scope/ui-runtime-scope.service';
import { useDependency } from '../../../utils/di';
-import { MobileMenu } from '../../menu/mobile/MobileMenu';
import { MobileMenuDrawer } from '../../menu/mobile/MobileMenuDrawer';
const MOBILE_CONTEXT_MENU_HOST_ID = 'mobile-context-menu';
@@ -37,9 +36,7 @@ export function MobileContextMenu() {
const [visible, setVisible] = useState(false);
const [menuType, setMenuType] = useState('');
const [menuContext, setMenuContext] = useState<IContextMenuTriggerContext | undefined>();
- const [anchor, setAnchor] = useState({ x: 0, y: 0 });
const visibleRef = useRef(visible);
- const floatingMenuRef = useRef<HTMLDivElement>(null);
const contextMenuHostService = useDependency(IContextMenuHostService);
const contextMenuService = useDependency(IContextMenuService);
const commandService = useDependency(ICommandService);
@@ -51,6 +48,22 @@ export function MobileContextMenu() {
visibleRef.current = visible;
+ const handleContextMenu = useCallback((
+ _event: ContextMenuEvent,
+ nextMenuType: string,
+ context?: IContextMenuTriggerContext
+ ) => {
+ contextMenuHostService.activateMenu(MOBILE_CONTEXT_MENU_HOST_ID);
+ setMenuType(nextMenuType);
+ setMenuContext(context);
+ setVisible(true);
+ }, [contextMenuHostService]);
+
+ const handleClose = useCallback(() => {
+ setVisible(false);
+ contextMenuHostService.deactivateMenu(MOBILE_CONTEXT_MENU_HOST_ID);
+ }, [contextMenuHostService]);
+
useEffect(() => {
const hostDisposable = contextMenuHostService.registerMenu(MOBILE_CONTEXT_MENU_HOST_ID, () => {
setVisible(false);
@@ -71,36 +84,7 @@ export function MobileContextMenu() {
hostDisposable.dispose();
contextMenuHostService.deactivateMenu(MOBILE_CONTEXT_MENU_HOST_ID);
};
- }, [contextMenuHostService, contextMenuService]);
-
- function handleContextMenu(event: ContextMenuEvent, nextMenuType: string, context?: IContextMenuTriggerContext) {
- contextMenuHostService.activateMenu(MOBILE_CONTEXT_MENU_HOST_ID);
- setMenuType(nextMenuType);
- setMenuContext(context);
- setAnchor({ x: event.clientX, y: event.clientY });
- setVisible(true);
- }
-
- function handleClose() {
- setVisible(false);
- contextMenuHostService.deactivateMenu(MOBILE_CONTEXT_MENU_HOST_ID);
- }
-
- useEffect(() => {
- if (!visible || menuType !== ContextMenuPosition.MAIN_AREA || !mountContainer) {
- return undefined;
- }
-
- const ownerDocument = mountContainer.ownerDocument;
- const handleOutsidePointerDown = (event: PointerEvent) => {
- if (!(event.target instanceof Node) || !floatingMenuRef.current?.contains(event.target)) {
- setVisible(false);
- contextMenuHostService.deactivateMenu(MOBILE_CONTEXT_MENU_HOST_ID);
- }
- };
- ownerDocument.addEventListener('pointerdown', handleOutsidePointerDown, true);
- return () => ownerDocument.removeEventListener('pointerdown', handleOutsidePointerDown, true);
- }, [contextMenuHostService, menuType, mountContainer, visible]);
+ }, [contextMenuHostService, contextMenuService, handleClose, handleContextMenu]);
const sheetTitle = useMemo(() => {
switch (menuType) {
@@ -143,53 +127,6 @@ export function MobileContextMenu() {
activeCommandService.executeCommand(commandId, commandParams);
handleClose();
};
- if (menuType === ContextMenuPosition.MAIN_AREA) {
- const viewportHeight = mountContainer.ownerDocument.defaultView?.innerHeight ?? 0;
- const placeBelow = anchor.y < 72;
- const top = placeBelow
- ? anchor.y + 12
- : Math.min(anchor.y - 56, Math.max(8, viewportHeight - 56));
- const pointerLeft = `clamp(20px, ${anchor.x - 8}px, calc(100% - 20px))`;
-
- return createPortal(
- <div
- className="
- univer-pointer-events-none univer-fixed univer-inset-x-2 univer-z-[1080] univer-flex
- univer-justify-center
- "
- style={{ top }}
- >
- <div
- ref={floatingMenuRef}
- className="
- univer-pointer-events-auto univer-relative univer-min-w-0 univer-max-w-[560px] univer-flex-1
- "
- >
- <MobileMenu
- menuType={menuType}
- menuManagerService={activeMenuManagerService}
- presentation="context-bar"
- onOptionSelect={handleOptionSelect}
- />
- <div
- aria-hidden="true"
- className={placeBelow
- ? `
- univer-absolute -univer-top-1 univer-size-2 univer-rotate-45 univer-bg-gray-0
- dark:!univer-bg-gray-700
- `
- : `
- univer-absolute -univer-bottom-1 univer-size-2 univer-rotate-45 univer-bg-gray-0
- dark:!univer-bg-gray-700
- `}
- style={{ left: pointerLeft }}
- />
- </div>
- </div>,
- mountContainer
- );
- }
-
return (
<MobileMenuDrawer
visible
diff --git a/packages/ui/src/views/components/dialog-part/MobileDialogPart.tsx b/packages/ui/src/views/components/dialog-part/MobileDialogPart.tsx
index 2821ee39cc..dd5a18fe55 100644
--- a/packages/ui/src/views/components/dialog-part/MobileDialogPart.tsx
+++ b/packages/ui/src/views/components/dialog-part/MobileDialogPart.tsx
@@ -19,9 +19,9 @@ import type { LocaleKey } from '../../../locale/types';
import type { MobileDrawerSnap } from '../mobile-drawer/MobileDrawer';
import type { IDialogPartMethodOptions } from './interface';
import { LocaleService } from '@univerjs/core';
-import { ActionRow } from '@univerjs/design';
+import { MobileActionRowGroup } from '@univerjs/design';
import { CloseIcon } from '@univerjs/icons';
-import { useMemo, useState } from 'react';
+import { useMemo, useRef, useState } from 'react';
import { IDialogService } from '../../../services/dialog/dialog.service';
import { useDependency, useObservable } from '../../../utils/di';
import { CustomLabel } from '../../custom-label/CustomLabel';
@@ -53,8 +53,12 @@ export function MobileDialogPart() {
return active ? toMobileDialogOptions(active) : null;
}, [dialogOptions]);
const [drawerSnap, setDrawerSnap] = useState<MobileDrawerSnap>('expanded');
+ const layerRef = useRef<HTMLDivElement>(null);
+ const backdropPointerIdRef = useRef<number | null>(null);
- if (!options) return null;
+ if (!options) {
+ return null;
+ }
const close = () => {
dialogService.close(options.id);
@@ -63,7 +67,11 @@ export function MobileDialogPart() {
};
return (
- <div className="univer-fixed univer-inset-0 univer-z-[1200]" data-u-comp="mobile-dialog">
+ <div
+ ref={layerRef}
+ className="univer-fixed univer-inset-0 univer-z-[1200]"
+ data-u-comp="mobile-dialog"
+ >
<button
type="button"
aria-label={localeService.t<LocaleKey>('ui.sidebar.close')}
@@ -71,9 +79,27 @@ export function MobileDialogPart() {
univer-absolute univer-inset-0 univer-m-0 univer-appearance-none univer-rounded-none univer-border-0
univer-bg-black/35 univer-p-0
"
- onClick={options.maskClosable === false ? undefined : close}
+ onPointerDown={options.maskClosable === false
+ ? undefined
+ : (event) => {
+ backdropPointerIdRef.current = event.pointerId;
+ }}
+ onPointerUp={options.maskClosable === false
+ ? undefined
+ : (event) => {
+ if (backdropPointerIdRef.current !== event.pointerId) {
+ return;
+ }
+
+ backdropPointerIdRef.current = null;
+ close();
+ }}
+ onPointerCancel={() => {
+ backdropPointerIdRef.current = null;
+ }}
/>
<MobileDrawer
+ layerRef={layerRef}
componentName="mobile-dialog-drawer"
snap={drawerSnap}
expandLabel={localeService.t<LocaleKey>('ui.sidebar.resize')}
@@ -82,9 +108,9 @@ export function MobileDialogPart() {
onClose={close}
role="dialog"
panelClassName="
- univer-bg-gray-0 univer-text-gray-900
- dark:!univer-bg-gray-900 dark:!univer-text-gray-0
- "
+ univer-bg-gray-0 univer-text-gray-900
+ dark:!univer-bg-gray-900 dark:!univer-text-gray-0
+ "
contentClassName="univer-min-h-0 univer-px-4 univer-pb-4"
header={(
<header
@@ -121,7 +147,7 @@ export function MobileDialogPart() {
dark:!univer-border-gray-700
"
>
- <ActionRow>{options.footer}</ActionRow>
+ <MobileActionRowGroup>{options.footer}</MobileActionRowGroup>
</footer>
)
: undefined}
diff --git a/packages/ui/src/views/components/dialog-part/__tests__/MobileDialogPart.spec.tsx b/packages/ui/src/views/components/dialog-part/__tests__/MobileDialogPart.spec.tsx
index 29389045cb..eb218b3ba8 100644
--- a/packages/ui/src/views/components/dialog-part/__tests__/MobileDialogPart.spec.tsx
+++ b/packages/ui/src/views/components/dialog-part/__tests__/MobileDialogPart.spec.tsx
@@ -17,6 +17,8 @@
import type { ReactElement } from 'react';
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
import { DesktopLogService, ILogService, Injector, LocaleService, LocaleType } from '@univerjs/core';
+import { useState } from 'react';
+import { createPortal } from 'react-dom';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { ComponentManager, IconManager } from '../../../../common';
import enUS from '../../../../locale/en-US';
@@ -25,6 +27,8 @@ import { IDialogService } from '../../../../services/dialog/dialog.service';
import { MobileDialogService } from '../../../../services/dialog/mobile-dialog.service';
import { IUIPartsService, UIPartsService } from '../../../../services/parts/parts.service';
import { RediProvider } from '../../../../utils/di';
+import { MobileDrawer } from '../../mobile-drawer/MobileDrawer';
+import { MobileDrawerCoordinatorProvider } from '../../mobile-drawer/MobileDrawerCoordinator';
import { MobileDialogPart } from '../MobileDialogPart';
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, value: true, writable: true });
@@ -41,11 +45,42 @@ function renderWithDependencies(element: ReactElement, mobileService = false) {
injector.add([IconManager]);
return {
- ...render(<RediProvider value={{ injector }}>{element}</RediProvider>),
+ ...render(
+ <RediProvider value={{ injector }}>
+ <MobileDrawerCoordinatorProvider>{element}</MobileDrawerCoordinatorProvider>
+ </RediProvider>
+ ),
injector,
};
}
+function NestedMobileLayer() {
+ const [open, setOpen] = useState(false);
+
+ return (
+ <>
+ <button type="button" onClick={() => setOpen(true)}>
+ Open nested layer
+ </button>
+ {open && createPortal(
+ <MobileDrawer
+ openMode="push"
+ snap="compact"
+ expandLabel="Nested drawer"
+ collapseLabel="Nested drawer"
+ onSnapChange={vi.fn()}
+ onClose={() => setOpen(false)}
+ role="dialog"
+ ariaLabel="Nested drawer"
+ >
+ <button type="button" onClick={() => setOpen(false)}>Close nested layer</button>
+ </MobileDrawer>,
+ document.body
+ )}
+ </>
+ );
+}
+
describe('MobileDialogPart', () => {
afterEach(() => {
cleanup();
@@ -111,6 +146,35 @@ describe('MobileDialogPart', () => {
expect(screen.getByRole('dialog')).toBeTruthy();
});
+ it('ignores the release of the pointer that opened the dialog before accepting a backdrop tap', () => {
+ const rendered = renderWithDependencies(
+ <>
+ <button type="button">Open on pointer down</button>
+ <MobileDialogPart />
+ </>
+ );
+ const dialogService = rendered.injector.get(IDialogService);
+ const trigger = screen.getByRole('button', { name: 'Open on pointer down' });
+ trigger.addEventListener('pointerdown', () => {
+ dialogService.open({
+ id: 'pointer-down-dialog',
+ children: { title: <span>Pointer down dialog</span> },
+ });
+ });
+
+ fireEvent.pointerDown(trigger, { pointerId: 1 });
+ const backdrop = screen.getAllByRole('button', { name: 'Close sidebar' })[0];
+ fireEvent.pointerUp(backdrop, { pointerId: 1 });
+ fireEvent.click(backdrop, { detail: 0 });
+
+ expect(screen.getByRole('dialog')).toBeTruthy();
+
+ fireEvent.pointerDown(backdrop, { pointerId: 2 });
+ fireEvent.pointerUp(backdrop, { pointerId: 2 });
+
+ expect(screen.queryByRole('dialog')).toBeNull();
+ });
+
it('makes re-entrant business close callbacks idempotent', () => {
const rendered = renderWithDependencies(<MobileDialogPart />, true);
const dialogService = rendered.injector.get(IDialogService);
@@ -128,4 +192,30 @@ describe('MobileDialogPart', () => {
expect(onClose).toHaveBeenCalledOnce();
expect(screen.queryByRole('dialog')).toBeNull();
});
+
+ it('hides a parent dialog while a pushed drawer is open and restores it after close', () => {
+ const rendered = renderWithDependencies(<MobileDialogPart />, true);
+ const dialogService = rendered.injector.get(IDialogService);
+ rendered.injector.get(ComponentManager).register('nested-mobile-layer', NestedMobileLayer);
+
+ act(() => {
+ dialogService.open({
+ id: 'parent-dialog',
+ children: { label: 'nested-mobile-layer' },
+ });
+ });
+
+ const dialogShell = document.querySelector<HTMLElement>('[data-u-comp="mobile-dialog"]');
+ expect(dialogShell?.hidden).toBe(false);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Open nested layer' }));
+
+ expect(dialogShell?.hidden).toBe(true);
+ expect(screen.getByRole('dialog', { name: 'Nested drawer' })).toBeTruthy();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Close nested layer' }));
+
+ expect(dialogShell?.hidden).toBe(false);
+ expect(screen.getByRole('button', { name: 'Open nested layer' })).toBeTruthy();
+ });
});
diff --git a/packages/ui/src/views/components/dom/FloatDom.tsx b/packages/ui/src/views/components/dom/FloatDom.tsx
index e44b1001e5..64fa1aae8c 100644
--- a/packages/ui/src/views/components/dom/FloatDom.tsx
+++ b/packages/ui/src/views/components/dom/FloatDom.tsx
@@ -76,6 +76,7 @@ function FloatDomSingleContent(props: { layer: IFloatDom; id: string; Component?
const floatDomOverflow = resolveFloatDomOverflow(layerProps);
const wrapperInset = layer.contentBox?.wrapperInset;
const contentInset = layer.contentBox?.contentInset;
+ const forwardEvents = shouldForwardFloatDomEvents(layer);
useEffect(() => {
const subscription = layer.position$.subscribe((position) => {
@@ -119,24 +120,48 @@ function FloatDomSingleContent(props: { layer: IFloatDom; id: string; Component?
style={{
...layout.wrapper,
overflow: floatDomOverflow.outerOverflow,
+ touchAction: forwardEvents ? 'none' : undefined,
}}
onPointerMove={(e) => {
- if (shouldForwardFloatDomEvents(layer)) {
+ if (forwardEvents) {
layer.onPointerMove(e.nativeEvent);
}
}}
onPointerDown={(e) => {
- if (shouldForwardFloatDomEvents(layer)) {
+ if (forwardEvents) {
+ e.currentTarget.setPointerCapture?.(e.pointerId);
layer.onPointerDown(e.nativeEvent);
}
}}
onPointerUp={(e) => {
- if (shouldForwardFloatDomEvents(layer)) {
+ if (!forwardEvents) {
+ return;
+ }
+
+ try {
+ layer.onPointerUp(e.nativeEvent);
+ } finally {
+ if (e.currentTarget.hasPointerCapture?.(e.pointerId)) {
+ e.currentTarget.releasePointerCapture?.(e.pointerId);
+ }
+ }
+ }}
+ onPointerCancel={(e) => {
+ if (!forwardEvents) {
+ return;
+ }
+
+ try {
+ // The layer forwards the original event type, so the canvas receives pointercancel rather than pointerup.
layer.onPointerUp(e.nativeEvent);
+ } finally {
+ if (e.currentTarget.hasPointerCapture?.(e.pointerId)) {
+ e.currentTarget.releasePointerCapture?.(e.pointerId);
+ }
}
}}
onWheel={(e) => {
- if (shouldForwardFloatDomEvents(layer)) {
+ if (forwardEvents) {
layer.onWheel(e.nativeEvent);
}
}}
diff --git a/packages/ui/src/views/components/dom/__tests__/FloatDom.spec.tsx b/packages/ui/src/views/components/dom/__tests__/FloatDom.spec.tsx
index 09a22ef21d..3fb412877c 100644
--- a/packages/ui/src/views/components/dom/__tests__/FloatDom.spec.tsx
+++ b/packages/ui/src/views/components/dom/__tests__/FloatDom.spec.tsx
@@ -173,13 +173,63 @@ describe('FloatDomSingle', () => {
const wrapper = inner.parentElement as HTMLDivElement;
expect(wrapper.className).toBe('univer-absolute univer-z-10 univer-origin-center');
expect(inner.className).toBe('univer-absolute univer-overflow-hidden');
- expect(wrapper.style.cssText).toBe('top: 20px; left: 10px; width: 98px; height: 98px; transform: rotate(0deg); opacity: 1; overflow: hidden;');
+ expect(wrapper.style.cssText).toBe('top: 20px; left: 10px; width: 98px; height: 98px; transform: rotate(0deg); opacity: 1; overflow: hidden; touch-action: none;');
expect(inner.style.cssText).toBe('width: 96px; height: 96px; left: 0px; top: 0px; right: auto; bottom: auto; overflow: hidden;');
fireEvent.pointerDown(inner);
expect(onPointerDown).toHaveBeenCalledOnce();
});
+ it('captures forwarded pointers and finishes the canvas gesture when the browser cancels it', async () => {
+ const onPointerDown = vi.fn();
+ const onPointerUp = vi.fn();
+ const layer = { ...createFloatDom(), onPointerDown, onPointerUp };
+
+ renderWithDependencies(<FloatDomSingle id="dom-1" layer={layer} />);
+
+ const inner = await waitFor(() => document.getElementById('dom-1') as HTMLDivElement);
+ const wrapper = inner.parentElement as HTMLDivElement;
+ const setPointerCapture = vi.fn();
+ const releasePointerCapture = vi.fn();
+ Object.defineProperties(wrapper, {
+ hasPointerCapture: { configurable: true, value: () => true },
+ releasePointerCapture: { configurable: true, value: releasePointerCapture },
+ setPointerCapture: { configurable: true, value: setPointerCapture },
+ });
+
+ fireEvent.pointerDown(inner, { pointerId: 7 });
+ fireEvent.pointerUp(inner, { pointerId: 7 });
+ fireEvent.pointerDown(inner, { pointerId: 8 });
+ fireEvent.pointerCancel(inner, { pointerId: 8 });
+
+ expect(wrapper.style.touchAction).toBe('none');
+ expect(setPointerCapture).toHaveBeenCalledWith(7);
+ expect(setPointerCapture).toHaveBeenCalledWith(8);
+ expect(onPointerDown).toHaveBeenCalledTimes(2);
+ expect(onPointerUp).toHaveBeenCalledWith(expect.objectContaining({ type: 'pointerup' }));
+ expect(onPointerUp).toHaveBeenCalledWith(expect.objectContaining({ type: 'pointercancel' }));
+ expect(releasePointerCapture).toHaveBeenCalledWith(7);
+ expect(releasePointerCapture).toHaveBeenCalledWith(8);
+ });
+
+ it('does not capture pointers owned by an interactive float dom', async () => {
+ const onPointerDown = vi.fn();
+ const layer = { ...createFloatDom(), eventPassThrough: false, onPointerDown };
+
+ renderWithDependencies(<FloatDomSingle id="dom-1" layer={layer} />);
+
+ const inner = await waitFor(() => document.getElementById('dom-1') as HTMLDivElement);
+ const wrapper = inner.parentElement as HTMLDivElement;
+ const setPointerCapture = vi.fn();
+ Object.defineProperty(wrapper, 'setPointerCapture', { configurable: true, value: setPointerCapture });
+
+ fireEvent.pointerDown(inner, { pointerId: 7 });
+
+ expect(wrapper.style.touchAction).toBe('');
+ expect(setPointerCapture).not.toHaveBeenCalled();
+ expect(onPointerDown).not.toHaveBeenCalled();
+ });
+
it('updates clipped placement, full content size, and anchors through position$', async () => {
const position$ = createFloatDom().position$ as BehaviorSubject<IFloatDomLayout>;
const layer = { ...createFloatDom(), contentBox: { wrapperInset: 0, contentInset: 0 }, position$ };
diff --git a/packages/ui/src/views/components/mobile-drawer/MobileDrawer.tsx b/packages/ui/src/views/components/mobile-drawer/MobileDrawer.tsx
index 3d4c91b273..b44261ae12 100644
--- a/packages/ui/src/views/components/mobile-drawer/MobileDrawer.tsx
+++ b/packages/ui/src/views/components/mobile-drawer/MobileDrawer.tsx
@@ -14,12 +14,14 @@
* limitations under the License.
*/
-import type { AriaRole, PointerEvent, ReactNode } from 'react';
+import type { AriaRole, PointerEvent, ReactNode, RefObject } from 'react';
import { clsx, resetButtonClassName, scrollbarClassName } from '@univerjs/design';
-import { useRef, useState } from 'react';
+import { useContext, useImperativeHandle, useLayoutEffect, useRef, useState } from 'react';
+import { MobileDrawerCoordinatorContext } from './MobileDrawerCoordinator';
export type MobileDrawerSnap = 'compact' | 'expanded';
export type MobileDrawerRelease = MobileDrawerSnap | 'closed';
+export type MobileDrawerOpenMode = 'replace' | 'push';
type MobileDrawerRef<T> = { current: T | null } | ((instance: T | null) => void) | null;
const MOBILE_DRAWER_COMPACT_PERCENT = 40;
@@ -51,6 +53,8 @@ export function MobileDrawer(props: {
componentName?: string;
panelRef?: MobileDrawerRef<HTMLElement>;
contentRef?: MobileDrawerRef<HTMLDivElement>;
+ layerRef?: RefObject<HTMLElement | null>;
+ openMode?: MobileDrawerOpenMode;
panelClassName?: string;
contentClassName?: string;
footer?: ReactNode;
@@ -69,12 +73,26 @@ export function MobileDrawer(props: {
componentName = 'mobile-drawer',
panelRef,
contentRef,
+ layerRef,
+ openMode = 'replace',
panelClassName,
contentClassName,
footer,
role,
ariaLabel,
} = props;
+ const coordinator = useContext(MobileDrawerCoordinatorContext);
+ const registerDrawer = coordinator?.register;
+ const unregisterDrawer = coordinator?.unregister;
+ const panelElementRef = useRef<HTMLElement>(null);
+ const drawerIdRef = useRef<symbol | null>(null);
+ const onCloseRef = useRef(onClose);
+ onCloseRef.current = onClose;
+ if (!drawerIdRef.current) {
+ drawerIdRef.current = Symbol(componentName);
+ }
+ const drawerId = drawerIdRef.current;
+ const active = !coordinator || coordinator.activeDrawerId === drawerId;
const [dragPercent, setDragPercent] = useState<number | null>(null);
const suppressHandleClickRef = useRef(false);
const dragRef = useRef<{
@@ -87,6 +105,27 @@ export function MobileDrawer(props: {
const drawerPercent = dragPercent ?? (snap === 'compact'
? MOBILE_DRAWER_COMPACT_PERCENT
: MOBILE_DRAWER_EXPANDED_PERCENT);
+ const viewportHeightUnit = globalThis.CSS?.supports('height', '1dvh') ? 'dvh' : 'vh';
+
+ useImperativeHandle(panelRef, () => panelElementRef.current!);
+
+ useLayoutEffect(() => {
+ if (!registerDrawer || !unregisterDrawer) {
+ return;
+ }
+
+ registerDrawer(drawerId, openMode, () => onCloseRef.current());
+ return () => unregisterDrawer(drawerId);
+ }, [drawerId, openMode, registerDrawer, unregisterDrawer]);
+
+ useLayoutEffect(() => {
+ const layer = layerRef?.current ?? (layerRef ? panelElementRef.current?.parentElement : null);
+ if (!layer) {
+ return;
+ }
+
+ layer.toggleAttribute('hidden', !active);
+ }, [active, layerRef]);
function beginDrag(clientY: number) {
dragRef.current = {
@@ -126,7 +165,11 @@ export function MobileDrawer(props: {
dragRef.current = null;
setDragPercent(null);
if (result === 'closed') {
- onClose();
+ if (coordinator) {
+ coordinator.close(drawerId);
+ } else {
+ onClose();
+ }
} else {
onSnapChange(result);
}
@@ -149,18 +192,24 @@ export function MobileDrawer(props: {
endDrag(event.clientY);
}
+ function handlePointerCancel() {
+ dragRef.current = null;
+ setDragPercent(null);
+ }
+
return (
<>
{floatingActions && (
<div
className="univer-pointer-events-none univer-absolute univer-right-4 univer-z-30"
- style={{ bottom: `calc(${drawerPercent}dvh + 12px)` }}
+ style={{ bottom: `calc(${drawerPercent}${viewportHeightUnit} + 12px)` }}
>
{floatingActions}
</div>
)}
<section
- ref={panelRef}
+ ref={panelElementRef}
+ hidden={!active}
role={role}
aria-modal={role === 'dialog' || undefined}
aria-label={ariaLabel}
@@ -173,7 +222,7 @@ export function MobileDrawer(props: {
dark:!univer-bg-gray-900
`, dragPercent != null && '!univer-transition-none', panelClassName)}
style={{
- height: `${drawerPercent}dvh`,
+ height: `${drawerPercent}${viewportHeightUnit}`,
paddingBottom: 'env(safe-area-inset-bottom, 0px)',
}}
>
@@ -190,10 +239,11 @@ export function MobileDrawer(props: {
univer-absolute univer-left-1/2 univer-top-0 univer-z-10 univer-flex univer-h-6 univer-w-16
-univer-translate-x-1/2 univer-touch-none univer-items-center univer-justify-center
`)}
+ style={{ touchAction: 'none' }}
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
- onPointerCancel={handlePointerUp}
+ onPointerCancel={handlePointerCancel}
onClick={() => {
if (suppressHandleClickRef.current) {
suppressHandleClickRef.current = false;
diff --git a/packages/ui/src/views/components/mobile-drawer/MobileDrawerCoordinator.tsx b/packages/ui/src/views/components/mobile-drawer/MobileDrawerCoordinator.tsx
new file mode 100644
index 0000000000..5f12a77c95
--- /dev/null
+++ b/packages/ui/src/views/components/mobile-drawer/MobileDrawerCoordinator.tsx
@@ -0,0 +1,84 @@
+/**
+ * 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 { ReactNode } from 'react';
+import type { MobileDrawerOpenMode } from './MobileDrawer';
+import { createContext, useCallback, useMemo, useRef, useState } from 'react';
+
+interface IMobileDrawerEntry {
+ id: symbol;
+ onClose: () => void;
+}
+
+interface IMobileDrawerCoordinatorContext {
+ activeDrawerId: symbol | null;
+ close: (id: symbol) => void;
+ register: (id: symbol, mode: MobileDrawerOpenMode, onClose: () => void) => void;
+ unregister: (id: symbol) => void;
+}
+
+export const MobileDrawerCoordinatorContext = createContext<IMobileDrawerCoordinatorContext | null>(null);
+
+export function MobileDrawerCoordinatorProvider(props: { children: ReactNode }) {
+ const entriesRef = useRef<IMobileDrawerEntry[]>([]);
+ const [activeDrawerId, setActiveDrawerId] = useState<symbol | null>(null);
+
+ const setEntries = useCallback((entries: IMobileDrawerEntry[]) => {
+ entriesRef.current = entries;
+ setActiveDrawerId(entries.length ? entries[entries.length - 1].id : null);
+ }, []);
+
+ const unregister = useCallback((id: symbol) => {
+ setEntries(entriesRef.current.filter((entry) => entry.id !== id));
+ }, [setEntries]);
+
+ const close = useCallback((id: symbol) => {
+ const entry = entriesRef.current.find((item) => item.id === id);
+ if (!entry) {
+ return;
+ }
+
+ unregister(id);
+ entry.onClose();
+ }, [unregister]);
+
+ const register = useCallback((id: symbol, mode: MobileDrawerOpenMode, onClose: () => void) => {
+ const entry = { id, onClose };
+ if (mode === 'push') {
+ setEntries([...entriesRef.current, entry]);
+ return;
+ }
+
+ const previousEntries = entriesRef.current;
+ setEntries([entry]);
+ for (let i = previousEntries.length - 1; i >= 0; i--) {
+ previousEntries[i].onClose();
+ }
+ }, [setEntries]);
+
+ const value = useMemo<IMobileDrawerCoordinatorContext>(() => ({
+ activeDrawerId,
+ close,
+ register,
+ unregister,
+ }), [activeDrawerId, close, register, unregister]);
+
+ return (
+ <MobileDrawerCoordinatorContext.Provider value={value}>
+ {props.children}
+ </MobileDrawerCoordinatorContext.Provider>
+ );
+}
diff --git a/packages/ui/src/views/components/mobile-drawer/__tests__/MobileDrawer.spec.ts b/packages/ui/src/views/components/mobile-drawer/__tests__/MobileDrawer.spec.ts
index 9d74fbe5be..dbd81487e3 100644
--- a/packages/ui/src/views/components/mobile-drawer/__tests__/MobileDrawer.spec.ts
+++ b/packages/ui/src/views/components/mobile-drawer/__tests__/MobileDrawer.spec.ts
@@ -14,14 +14,53 @@
* limitations under the License.
*/
+import type { MobileDrawerOpenMode } from '../MobileDrawer';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
-import { createElement } from 'react';
+import { createElement, useRef } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { MobileDrawer, resolveMobileDrawerRelease } from '../MobileDrawer';
+import { MobileDrawerCoordinatorProvider } from '../MobileDrawerCoordinator';
-afterEach(cleanup);
+function DrawerLayer(props: {
+ label: string;
+ mode?: MobileDrawerOpenMode;
+ onClose: () => void;
+}) {
+ const layerRef = useRef<HTMLDivElement>(null);
+
+ return createElement('div', {
+ ref: layerRef,
+ 'data-testid': `${props.label}-layer`,
+ }, createElement(MobileDrawer, {
+ layerRef,
+ snap: 'compact',
+ expandLabel: props.label,
+ collapseLabel: props.label,
+ onSnapChange: vi.fn(),
+ onClose: props.onClose,
+ openMode: props.mode,
+ }, props.label));
+}
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
describe('mobile drawer snap behavior', () => {
+ it('falls back to viewport height units when dynamic viewport units are unavailable', () => {
+ vi.stubGlobal('CSS', { supports: () => false });
+ const { container } = render(createElement(MobileDrawer, {
+ snap: 'compact',
+ expandLabel: 'Expand drawer',
+ collapseLabel: 'Collapse drawer',
+ onSnapChange: vi.fn(),
+ onClose: vi.fn(),
+ }, 'Drawer content'));
+
+ expect(container.querySelector('section')?.style.height).toBe('40vh');
+ });
+
it('supports expand, collapse, restore, and fast close gestures', () => {
expect(resolveMobileDrawerRelease({ snap: 'compact', deltaY: -40, durationMs: 300, percent: 45 })).toBe('expanded');
expect(resolveMobileDrawerRelease({ snap: 'expanded', deltaY: 40, durationMs: 300, percent: 75 })).toBe('compact');
@@ -50,6 +89,27 @@ describe('mobile drawer snap behavior', () => {
expect(onClose).not.toHaveBeenCalled();
});
+ it('reserves the drag handle for pointer gestures and cancels without changing the drawer', () => {
+ const onSnapChange = vi.fn();
+ const onClose = vi.fn();
+ render(createElement(MobileDrawer, {
+ snap: 'compact',
+ expandLabel: 'Expand drawer',
+ collapseLabel: 'Collapse drawer',
+ onSnapChange,
+ onClose,
+ }, 'Drawer content'));
+ const handle = screen.getByRole('button', { name: 'Expand drawer' });
+
+ expect(handle.style.touchAction).toBe('none');
+ fireEvent.pointerDown(handle, { pointerId: 1, clientY: 500 });
+ fireEvent.pointerMove(handle, { pointerId: 1, clientY: 450 });
+ fireEvent.pointerCancel(handle, { pointerId: 1, clientY: 0 });
+
+ expect(onSnapChange).not.toHaveBeenCalled();
+ expect(onClose).not.toHaveBeenCalled();
+ });
+
it('closes when the compact handle is flicked downward', () => {
const onSnapChange = vi.fn();
const onClose = vi.fn();
@@ -69,4 +129,45 @@ describe('mobile drawer snap behavior', () => {
expect(onClose).toHaveBeenCalledOnce();
expect(onSnapChange).not.toHaveBeenCalled();
});
+
+ it('closes the active drawer and suspended parents when another root drawer opens', () => {
+ const closeParent = vi.fn();
+ const closeChild = vi.fn();
+
+ render(createElement(MobileDrawerCoordinatorProvider, null, createElement(DrawerLayer, { label: 'Parent drawer', onClose: closeParent }), createElement(DrawerLayer, {
+ label: 'Child drawer',
+ mode: 'push',
+ onClose: closeChild,
+ }), createElement(DrawerLayer, { label: 'Replacement drawer', onClose: vi.fn() })));
+
+ expect(closeParent).toHaveBeenCalledOnce();
+ expect(closeChild).toHaveBeenCalledOnce();
+ expect(screen.getByTestId('Parent drawer-layer')).toHaveProperty('hidden', true);
+ expect(screen.getByTestId('Child drawer-layer')).toHaveProperty('hidden', true);
+ expect(screen.getByTestId('Replacement drawer-layer')).toHaveProperty('hidden', false);
+ });
+
+ it('restores a parent drawer after a pushed drawer closes', () => {
+ const closeParent = vi.fn();
+ const closeChild = vi.fn();
+
+ render(createElement(MobileDrawerCoordinatorProvider, null, createElement(DrawerLayer, { label: 'Parent drawer', onClose: closeParent }), createElement(DrawerLayer, {
+ label: 'Child drawer',
+ mode: 'push',
+ onClose: closeChild,
+ })));
+
+ expect(closeParent).not.toHaveBeenCalled();
+ expect(screen.getByTestId('Parent drawer-layer')).toHaveProperty('hidden', true);
+ expect(screen.getByTestId('Child drawer-layer')).toHaveProperty('hidden', false);
+
+ const childHandle = screen.getByRole('button', { name: 'Child drawer' });
+ fireEvent.pointerDown(childHandle, { pointerId: 1, clientY: 500 });
+ fireEvent.pointerMove(childHandle, { pointerId: 1, clientY: 650 });
+ fireEvent.pointerUp(childHandle, { pointerId: 1, clientY: 650 });
+
+ expect(closeChild).toHaveBeenCalledOnce();
+ expect(screen.getByTestId('Parent drawer-layer')).toHaveProperty('hidden', false);
+ expect(screen.getByTestId('Child drawer-layer')).toHaveProperty('hidden', true);
+ });
});
diff --git a/packages/ui/src/views/components/ribbon/MobileRibbon.tsx b/packages/ui/src/views/components/ribbon/MobileRibbon.tsx
index 3e843ae4da..8e3760b7ca 100644
--- a/packages/ui/src/views/components/ribbon/MobileRibbon.tsx
+++ b/packages/ui/src/views/components/ribbon/MobileRibbon.tsx
@@ -34,7 +34,7 @@ import { IRibbonService } from '../../../services/ribbon/ribbon.service';
import { IWorkbenchService } from '../../../services/workbench/workbench.service';
import { useDependency, useObservable } from '../../../utils/di';
import { ComponentContainer } from '../ComponentContainer';
-import { ToolbarItem } from './ToolbarItem';
+import { MobileToolbarItem } from './MobileToolbarItem';
interface IMobileRibbonProps {
headerMenuComponents?: Set<ComponentType>;
@@ -358,7 +358,7 @@ function MobileRibbonToolbar(props: IMobileRibbonProps & { ribbon: IMenuSchema[]
[&_input]:!univer-outline-none
`)}
>
- <ToolbarItem {...child.item} preserveStrokeWidth />
+ <MobileToolbarItem {...child.item} preserveStrokeWidth />
</div>
)
))}
@@ -442,7 +442,7 @@ function MobileSheetTopBar(props: IMobileRibbonProps & { ribbon: IMenuSchema[] }
"
onClick={() => setMoreOpen(false)}
>
- <ToolbarItem {...schema.item!} grid showLabel preserveStrokeWidth />
+ <MobileToolbarItem {...schema.item!} grid showLabel preserveStrokeWidth />
</div>
))}
</div>
@@ -468,7 +468,7 @@ function MobileSheetTopBar(props: IMobileRibbonProps & { ribbon: IMenuSchema[] }
"
>
{items.map((schema) => (
- <ToolbarItem
+ <MobileToolbarItem
key={schema.key}
{...schema.item!}
/>
diff --git a/packages/ui/src/views/components/ribbon/MobileToolbarItem.tsx b/packages/ui/src/views/components/ribbon/MobileToolbarItem.tsx
new file mode 100644
index 0000000000..99e88d6caf
--- /dev/null
+++ b/packages/ui/src/views/components/ribbon/MobileToolbarItem.tsx
@@ -0,0 +1,33 @@
+/**
+ * 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 { IToolbarItemProps } from './ToolbarItem';
+import type { ITooltipWrapperRef } from './TooltipButtonWrapper';
+import { MobileDropdown, MobileDropdownMenu } from '@univerjs/design';
+import { forwardRef } from 'react';
+import { ToolbarItem } from './ToolbarItem';
+
+export const MobileToolbarItem = forwardRef<ITooltipWrapperRef, IToolbarItemProps>((props, ref) => (
+ <ToolbarItem
+ {...props}
+ ref={ref}
+ title={props.title ?? props.tooltip}
+ tooltip={undefined}
+ shortcut={undefined}
+ dropdownComponent={MobileDropdown}
+ dropdownMenuComponent={MobileDropdownMenu}
+ />
+));
diff --git a/packages/ui/src/views/components/ribbon/ToolbarItem.tsx b/packages/ui/src/views/components/ribbon/ToolbarItem.tsx
index 460d814099..2d5e1aa5c4 100644
--- a/packages/ui/src/views/components/ribbon/ToolbarItem.tsx
+++ b/packages/ui/src/views/components/ribbon/ToolbarItem.tsx
@@ -14,6 +14,8 @@
* limitations under the License.
*/
+import type { IDropdownMenuProps, IDropdownProps } from '@univerjs/design';
+import type { ComponentType } from 'react';
import type { IDisplayMenuItem, IMenuItem, IMenuSelectorItem, IValueOption } from '../../../services/menu/menu';
import type { ITooltipWrapperRef } from './TooltipButtonWrapper';
import { ICommandService, LocaleService } from '@univerjs/core';
@@ -30,7 +32,7 @@ import { useToolbarItemStatus, useToolbarShortcutDisplay } from './hook';
import { ToolbarButton, toolbarButtonVariants } from './ToolbarButton';
import { DropdownMenuWrapper, TooltipWrapper } from './TooltipButtonWrapper';
-type IToolbarItemProps = IDisplayMenuItem<IMenuItem> & {
+export type IToolbarItemProps = IDisplayMenuItem<IMenuItem> & {
grid?: boolean;
large?: boolean;
showLabel?: boolean;
@@ -38,6 +40,8 @@ type IToolbarItemProps = IDisplayMenuItem<IMenuItem> & {
iconColor?: string;
fullWidth?: boolean;
preserveStrokeWidth?: boolean;
+ dropdownComponent?: ComponentType<IDropdownProps>;
+ dropdownMenuComponent?: ComponentType<IDropdownMenuProps>;
};
const toolbarDisabledClassName = 'univer-pointer-events-none univer-cursor-not-allowed univer-text-gray-300 dark:!univer-text-gray-600';
@@ -202,7 +206,27 @@ export const ToolbarItem = forwardRef<ITooltipWrapperRef, IToolbarItemProps>((pr
commandService.executeCommand(commandId, params);
};
- const { tooltip, shortcut, icon, title, label, id, commandId, type, slot, params, grid, large, showLabel, iconSize, iconColor, fullWidth, preserveStrokeWidth } = props;
+ const {
+ tooltip,
+ shortcut,
+ icon,
+ title,
+ label,
+ id,
+ commandId,
+ type,
+ slot,
+ params,
+ grid,
+ large,
+ showLabel,
+ iconSize,
+ iconColor,
+ fullWidth,
+ preserveStrokeWidth,
+ dropdownComponent,
+ dropdownMenuComponent,
+ } = props;
const gridLabel = title ?? tooltip;
const shortcutDisplay = useToolbarShortcutDisplay({ id, commandId, shortcut });
@@ -305,6 +329,8 @@ export const ToolbarItem = forwardRef<ITooltipWrapperRef, IToolbarItemProps>((pr
disabled={disabled}
preserveStrokeWidth={preserveStrokeWidth}
onOptionSelect={handleSelect}
+ dropdownComponent={dropdownComponent}
+ dropdownMenuComponent={dropdownMenuComponent}
>
<div
className={clsx(toolbarButtonSelectorTriggerVariants({ disabled, active: activated }), {
@@ -328,6 +354,8 @@ export const ToolbarItem = forwardRef<ITooltipWrapperRef, IToolbarItemProps>((pr
disabled={disabled}
preserveStrokeWidth={preserveStrokeWidth}
onOptionSelect={handleSelect}
+ dropdownComponent={dropdownComponent}
+ dropdownMenuComponent={dropdownMenuComponent}
>
<div
data-u-command={id}
diff --git a/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx b/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx
index f98ac7162c..c25a6b39ed 100644
--- a/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx
+++ b/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx
@@ -15,7 +15,7 @@
*/
import type { IDropdownMenuProps, IDropdownProps, ITooltipProps } from '@univerjs/design';
-import type { ReactNode } from 'react';
+import type { ComponentType, ReactNode } from 'react';
import type { IMenuItem, IValueOption } from '../../../services/menu/menu';
import {
clsx,
@@ -151,8 +151,12 @@ export const TooltipWrapper = forwardRef<ITooltipWrapperRef, ITooltipProps & { d
: content;
});
-export function DropdownWrapper(props: Omit<Partial<IDropdownProps>, 'overlay'> & { overlay: ReactNode; align?: 'start' | 'end' | 'center' }) {
- const { children, overlay, disabled, align } = props;
+export function DropdownWrapper(props: Omit<Partial<IDropdownProps>, 'overlay'> & {
+ overlay: ReactNode;
+ align?: 'start' | 'end' | 'center';
+ dropdownComponent?: ComponentType<IDropdownProps>;
+}) {
+ const { children, overlay, disabled, align, dropdownComponent: DropdownComponent = Dropdown } = props;
const { direction } = useContext(ConfigContext);
const { dropdownVisible, setDropdownVisible } = useContext(TooltipWrapperContext);
const triggerRef = useRef<HTMLDivElement>(null);
@@ -166,11 +170,22 @@ export function DropdownWrapper(props: Omit<Partial<IDropdownProps>, 'overlay'>
useEffect(() => {
const ownerDocument = triggerRef.current?.ownerDocument;
- if (!dropdownVisible || !ownerDocument) return;
+ 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;
+ const target = event.target as (Node & Partial<Pick<Element, 'closest'>>) | null;
+ const isPortaledOverlay = typeof target?.closest === 'function' &&
+ target.closest('[data-slot="popover-content"], [role="dialog"]') != null;
+ if (
+ !target ||
+ triggerRef.current?.contains(target) ||
+ overlayRef.current?.contains(target) ||
+ isPortaledOverlay
+ ) {
+ return;
+ }
setDropdownVisible(false);
};
@@ -184,7 +199,7 @@ export function DropdownWrapper(props: Omit<Partial<IDropdownProps>, 'overlay'>
}
return (
- <Dropdown
+ <DropdownComponent
align={align ?? (direction === 'rtl' ? 'end' : 'start')}
overlay={(
<div ref={overlayRef} className="univer-grid univer-gap-2">
@@ -198,7 +213,7 @@ export function DropdownWrapper(props: Omit<Partial<IDropdownProps>, 'overlay'>
<div ref={triggerRef} className="univer-h-full" onClick={(e) => e.stopPropagation()}>
{children}
</div>
- </Dropdown>
+ </DropdownComponent>
);
}
@@ -256,6 +271,8 @@ export function DropdownMenuWrapper({
disabled,
preserveStrokeWidth,
onOptionSelect,
+ dropdownComponent,
+ dropdownMenuComponent: DropdownMenuComponent = DropdownMenu,
}: {
menuId: string;
slot?: boolean;
@@ -265,6 +282,8 @@ export function DropdownMenuWrapper({
disabled?: boolean;
preserveStrokeWidth?: boolean;
onOptionSelect: (option: IValueOption) => void;
+ dropdownComponent?: ComponentType<IDropdownProps>;
+ dropdownMenuComponent?: ComponentType<IDropdownMenuProps>;
}) {
const { dropdownVisible, setDropdownVisible } = useContext(TooltipWrapperContext);
@@ -328,6 +347,7 @@ export function DropdownMenuWrapper({
return (
<DropdownWrapper
disabled={disabled}
+ dropdownComponent={dropdownComponent}
overlay={options.map((option) => (
<DropdownMenuLabel
key={getOptionKey(option)}
@@ -416,7 +436,7 @@ export function DropdownMenuWrapper({
}
return (
- <DropdownMenu
+ <DropdownMenuComponent
align="start"
className={clsx({ '!univer-p-0': isSingleEmbeddedCustomPanel })}
items={items}
@@ -427,7 +447,7 @@ export function DropdownMenuWrapper({
onInteractOutside={handleEmbedBoundaryFocusOutside}
>
{children}
- </DropdownMenu>
+ </DropdownMenuComponent>
);
} else {
const items: IDropdownMenuProps['items'] = [];
@@ -468,7 +488,7 @@ export function DropdownMenuWrapper({
}
return (
- <DropdownMenu
+ <DropdownMenuComponent
align="start"
items={items}
disabled={disabled}
@@ -478,7 +498,7 @@ export function DropdownMenuWrapper({
onInteractOutside={handleEmbedBoundaryFocusOutside}
>
{children}
- </DropdownMenu>
+ </DropdownMenuComponent>
);
}
}
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 c2c5367b77..9342bd3328 100644
--- a/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsx
+++ b/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsx
@@ -21,7 +21,8 @@
import type { ComponentType, ReactElement } from 'react';
import { cleanup, fireEvent, render } from '@testing-library/react';
import { ILogService, Injector, LocaleService } from '@univerjs/core';
-import { ConfigProvider } from '@univerjs/design';
+import { ConfigProvider, Dialog, Dropdown } from '@univerjs/design';
+import { useState } from 'react';
import { of } from 'rxjs';
import { afterEach, describe, expect, it, vi } from 'vitest';
@@ -49,6 +50,19 @@ class TestLogService {
warn(): void {}
}
+function NestedDialogDropdown() {
+ const [open, setOpen] = useState(false);
+
+ return (
+ <>
+ <Dropdown overlay={<button type="button" onClick={() => setOpen(true)}>More colors</button>}>
+ <button type="button">Border color</button>
+ </Dropdown>
+ <Dialog open={open}>Custom color</Dialog>
+ </>
+ );
+}
+
function renderWithDependencies(
element: ReactElement,
menuItems: ReturnType<IMenuManagerService['getMenuByPositionKey']> = []
@@ -192,6 +206,30 @@ describe('DropdownWrapper', () => {
expect(queryByText('Dropdown content')).toBeNull();
});
+
+ it('keeps the toolbar dropdown open when interacting with a nested portaled dropdown', () => {
+ const { getByRole } = render(
+ <ConfigProvider mountContainer={document.body}>
+ <ToolbarDropdownProvider>
+ <TooltipWrapper dropdownKey="border-dropdown">
+ <DropdownWrapper
+ overlay={<NestedDialogDropdown />}
+ >
+ <button type="button">Border</button>
+ </DropdownWrapper>
+ </TooltipWrapper>
+ </ToolbarDropdownProvider>
+ </ConfigProvider>
+ );
+
+ fireEvent.click(getByRole('button', { name: 'Border' }));
+ fireEvent.click(getByRole('button', { name: 'Border color' }));
+ const moreColorButton = getByRole('button', { name: 'More colors' });
+ fireEvent.pointerDown(moreColorButton);
+ fireEvent.click(moreColorButton);
+
+ expect(document.querySelector('[role="dialog"]')).not.toBeNull();
+ });
});
describe('DropdownMenuWrapper', () => {
diff --git a/packages/ui/src/views/components/sidebar/MobileSidebar.tsx b/packages/ui/src/views/components/sidebar/MobileSidebar.tsx
index d75404982e..f0654f8607 100644
--- a/packages/ui/src/views/components/sidebar/MobileSidebar.tsx
+++ b/packages/ui/src/views/components/sidebar/MobileSidebar.tsx
@@ -18,7 +18,7 @@ import type { LocaleKey } from '../../../locale/types';
import type { MobileDrawerSnap } from '../mobile-drawer/MobileDrawer';
import type { ISidebarMethodOptions } from './Sidebar';
import { LocaleService } from '@univerjs/core';
-import { ActionRow } from '@univerjs/design';
+import { MobileActionRowGroup } from '@univerjs/design';
import { CloseIcon } from '@univerjs/icons';
import { useEffect, useMemo, useRef, useState } from 'react';
import { ISidebarService } from '../../../services/sidebar/sidebar.service';
@@ -30,13 +30,16 @@ export function MobileSidebar() {
const localeService = useDependency(LocaleService);
const sidebarService = useDependency(ISidebarService);
const sidebarOptions = useObservable<ISidebarMethodOptions>(sidebarService.sidebarOptions$);
+ const layerRef = useRef<HTMLDivElement>(null);
const scrollRef = useRef<HTMLDivElement>(null);
const closeButtonRef = useRef<HTMLButtonElement>(null);
const [drawerSnap, setDrawerSnap] = useState<MobileDrawerSnap>('expanded');
const options = useMemo(() => renderSidebarOptions(sidebarOptions), [sidebarOptions]);
useEffect(() => {
- if (options?.visible) closeButtonRef.current?.focus();
+ if (options?.visible) {
+ closeButtonRef.current?.focus();
+ }
}, [options?.visible]);
useEffect(() => {
@@ -50,12 +53,18 @@ export function MobileSidebar() {
};
}, [options?.visible, sidebarService]);
- if (!options?.visible) return null;
+ if (!options?.visible) {
+ return null;
+ }
const close = () => sidebarService.close(sidebarOptions?.id);
return (
- <div className="univer-fixed univer-inset-0 univer-z-[1100]" data-u-comp="mobile-sidebar">
+ <div
+ ref={layerRef}
+ className="univer-fixed univer-inset-0 univer-z-[1100]"
+ data-u-comp="mobile-sidebar"
+ >
<button
type="button"
aria-label={localeService.t<LocaleKey>('ui.sidebar.close')}
@@ -66,6 +75,7 @@ export function MobileSidebar() {
onClick={close}
/>
<MobileDrawer
+ layerRef={layerRef}
componentName="mobile-sidebar-drawer"
snap={drawerSnap}
expandLabel={localeService.t<LocaleKey>('ui.ribbon.more')}
@@ -114,7 +124,7 @@ export function MobileSidebar() {
dark:!univer-border-gray-700
"
>
- <ActionRow>{options.footer}</ActionRow>
+ <MobileActionRowGroup>{options.footer}</MobileActionRowGroup>
</footer>
)
: undefined}
diff --git a/packages/ui/src/views/emoji-picker/EmojiPicker.tsx b/packages/ui/src/views/emoji-picker/EmojiPicker.tsx
index 444b0861a2..3a3b661b05 100644
--- a/packages/ui/src/views/emoji-picker/EmojiPicker.tsx
+++ b/packages/ui/src/views/emoji-picker/EmojiPicker.tsx
@@ -73,10 +73,11 @@ interface IEmojiPickerPopupProps {
recentStorageKey?: string;
}
-interface IEmojiPickerProps {
+export interface IEmojiPickerProps {
embedded?: boolean;
onChange?: (emoji: string) => void;
popup?: IPopup<IEmojiPickerPopupProps>;
+ DropdownComponent?: typeof Dropdown;
}
type EmojiSectionKey = 'recent' | EmojiCategory;
@@ -87,6 +88,7 @@ type EmojiVirtualRow =
| { items: IEmojiItem[]; key: string; type: 'emojis' };
export function EmojiPicker(props: IEmojiPickerProps) {
+ const { DropdownComponent = Dropdown } = props;
const extraProps = props.popup?.extraProps;
const localeService = useDependency(LocaleService);
const localStorageService = useDependency(ILocalStorageService);
@@ -265,6 +267,7 @@ export function EmojiPicker(props: IEmojiPickerProps) {
<RandomIcon />
</Button>
<SkinToneDropdown
+ DropdownComponent={DropdownComponent}
emojiTitles={emojiLocaleData.emojiTitles}
open={skinToneMenuOpen}
skinTone={skinTone}
@@ -299,6 +302,7 @@ export function EmojiPicker(props: IEmojiPickerProps) {
)
: (
<EmojiGrid
+ DropdownComponent={DropdownComponent}
key={row.key}
activeEmoji={activeEmoji}
emojiTitles={emojiLocaleData.emojiTitles}
@@ -358,6 +362,7 @@ function EmojiGrid(props: {
keyPrefix: string;
moreTitle: string;
onSelect: (item: IEmojiItem, options?: { keepOpen?: boolean }) => void;
+ DropdownComponent: typeof Dropdown;
}) {
return (
<div
@@ -367,6 +372,7 @@ function EmojiGrid(props: {
{props.items.map((item) => {
return (
<EmojiButton
+ DropdownComponent={props.DropdownComponent}
key={`${props.keyPrefix}-${item.emoji}-${item.title}`}
activeEmoji={props.activeEmoji}
emojiTitles={props.emojiTitles}
@@ -386,6 +392,7 @@ function EmojiButton(props: {
item: IEmojiItem;
moreTitle: string;
onSelect: (item: IEmojiItem, options?: { keepOpen?: boolean }) => void;
+ DropdownComponent: typeof Dropdown;
}) {
const [variantsOpen, setVariantsOpen] = useState(false);
const title = getLocalizedEmojiTitle(props.item, props.emojiTitles);
@@ -428,7 +435,7 @@ function EmojiButton(props: {
return (
<div className="univer-relative univer-size-7">
{button}
- <Dropdown
+ <props.DropdownComponent
align="end"
open={variantsOpen}
onOpenChange={setVariantsOpen}
@@ -471,7 +478,7 @@ function EmojiButton(props: {
>
<MoreDownIcon className="!univer-size-2.5" />
</button>
- </Dropdown>
+ </props.DropdownComponent>
</div>
);
}
@@ -512,6 +519,7 @@ function SkinToneDropdown(props: {
skinTone: EmojiSkinTone;
onChange: (skinTone: EmojiSkinTone) => void;
onOpenChange: (open: boolean) => void;
+ DropdownComponent: typeof Dropdown;
}) {
const currentOption = EMOJI_SKIN_TONE_OPTIONS.find((option) => option.value === props.skinTone)
?? EMOJI_SKIN_TONE_OPTIONS[0];
@@ -538,7 +546,7 @@ function SkinToneDropdown(props: {
return (
<div className="univer-flex-shrink-0" onClick={(event) => event.stopPropagation()}>
- <Dropdown
+ <props.DropdownComponent
align="end"
open={props.open}
onOpenChange={props.onOpenChange}
@@ -600,7 +608,7 @@ function SkinToneDropdown(props: {
"
/>
</Button>
- </Dropdown>
+ </props.DropdownComponent>
</div>
);
}
diff --git a/packages/ui/src/views/emoji-picker/MobileEmojiPicker.tsx b/packages/ui/src/views/emoji-picker/MobileEmojiPicker.tsx
new file mode 100644
index 0000000000..f275a0760d
--- /dev/null
+++ b/packages/ui/src/views/emoji-picker/MobileEmojiPicker.tsx
@@ -0,0 +1,23 @@
+/**
+ * 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 { IEmojiPickerProps } from './EmojiPicker';
+import { MobileDropdown } from '@univerjs/design';
+import { EmojiPicker } from './EmojiPicker';
+
+export function MobileEmojiPicker(props: IEmojiPickerProps) {
+ return <EmojiPicker {...props} DropdownComponent={MobileDropdown} />;
+}
diff --git a/packages/ui/src/views/menu/mobile/MobileMenu.tsx b/packages/ui/src/views/menu/mobile/MobileMenu.tsx
index 36515f1f87..ef9e0201a0 100644
--- a/packages/ui/src/views/menu/mobile/MobileMenu.tsx
+++ b/packages/ui/src/views/menu/mobile/MobileMenu.tsx
@@ -525,11 +525,13 @@ function MobileSchemaRow(props: {
aria-disabled={disabled}
className={clsx(
`
- univer-flex univer-min-h-12 univer-w-full univer-items-center univer-bg-gray-0 univer-px-4
- univer-py-2
+ univer-flex univer-min-h-12 univer-w-full univer-items-center univer-gap-3 univer-bg-gray-0
+ univer-px-4 univer-py-2
aria-disabled:univer-pointer-events-none aria-disabled:univer-opacity-40
dark:!univer-bg-gray-800
- [&>div]:univer-box-border [&>div]:!univer-w-full
+ [&>div]:univer-box-border [&>div]:univer-min-w-0 [&>div]:univer-flex-1
+ [&>svg]:univer-shrink-0 [&>svg]:univer-text-lg [&>svg]:univer-text-gray-700
+ dark:[&>svg]:!univer-text-gray-300
`,
bordered && borderBottomClassName
)}
diff --git a/packages/ui/src/views/menu/mobile/MobileMenuDrawer.tsx b/packages/ui/src/views/menu/mobile/MobileMenuDrawer.tsx
index efa298e24a..35d53ec0fa 100644
--- a/packages/ui/src/views/menu/mobile/MobileMenuDrawer.tsx
+++ b/packages/ui/src/views/menu/mobile/MobileMenuDrawer.tsx
@@ -21,7 +21,7 @@ import type { MobileDrawerSnap } from '../../components/mobile-drawer/MobileDraw
import { LocaleService } from '@univerjs/core';
import { clsx, ConfigContext, resetButtonClassName } from '@univerjs/design';
import { CloseIcon, MoreLeftIcon } from '@univerjs/icons';
-import { useContext, useState } from 'react';
+import { useContext, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { IMenuManagerService } from '../../../services/menu/menu-manager.service';
import { useDependency, useObservable } from '../../../utils/di';
@@ -54,13 +54,18 @@ function MobileMenuDrawerContent(props: IMobileMenuDrawerProps) {
const rootMenuManagerService = useDependency(IMenuManagerService);
const direction = useObservable(localeService.direction$);
const { mountContainer } = useContext(ConfigContext);
+ const layerRef = useRef<HTMLDivElement>(null);
if (!mountContainer) {
return null;
}
return createPortal(
- <div dir={direction} className="univer-fixed univer-inset-0 univer-z-[1080] univer-flex univer-items-end">
+ <div
+ ref={layerRef}
+ dir={direction}
+ className="univer-fixed univer-inset-0 univer-z-[1080] univer-flex univer-items-end"
+ >
<button
type="button"
aria-label={localeService.t<LocaleKey>('ui.rangeSelector.cancel')}
@@ -71,6 +76,7 @@ function MobileMenuDrawerContent(props: IMobileMenuDrawerProps) {
onClick={onClose}
/>
<MobileDrawer
+ layerRef={layerRef}
componentName="mobile-menu-drawer"
snap={drawerSnap}
expandLabel={localeService.t<LocaleKey>('ui.ribbon.more')}
diff --git a/packages/ui/src/views/menu/mobile/__tests__/MobileMenu.spec.tsx b/packages/ui/src/views/menu/mobile/__tests__/MobileMenu.spec.tsx
index 90e5ff7641..3bcf125556 100644
--- a/packages/ui/src/views/menu/mobile/__tests__/MobileMenu.spec.tsx
+++ b/packages/ui/src/views/menu/mobile/__tests__/MobileMenu.spec.tsx
@@ -486,6 +486,9 @@ describe('MobileMenu', () => {
const increase = screen.getByRole('button', { name: 'Increase' });
expect(increase.parentElement?.closest('button')).toBeNull();
+ const row = increase.closest('[role="group"]');
+ expect(row?.className).toContain('univer-gap-3');
+ expect(row?.className).not.toContain('[&>div]:!univer-w-full');
fireEvent.click(increase);
expect(onOptionSelect).toHaveBeenCalledWith(expect.objectContaining({
id: 'insert.rows',
diff --git a/packages/ui/src/views/mobile-workbench/MobileWorkbench.tsx b/packages/ui/src/views/mobile-workbench/MobileWorkbench.tsx
index 72c1d15099..5bb21f7dc2 100644
--- a/packages/ui/src/views/mobile-workbench/MobileWorkbench.tsx
+++ b/packages/ui/src/views/mobile-workbench/MobileWorkbench.tsx
@@ -27,6 +27,7 @@ import { IWorkbenchService } from '../../services/workbench/workbench.service';
import { connectInjector, useDependency, useObservable } from '../../utils/di';
import { ComponentContainer, useComponentsOfPart } from '../components/ComponentContainer';
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';
@@ -113,7 +114,7 @@ export function MobileWorkbench(props: IUniverAppProps) {
return () => {
sub.unsubscribe();
};
- }, []);
+ }, [themeService.currentTheme$, themeSwitcherService]);
useEffect(() => {
document.body.appendChild(portalContainer);
@@ -124,7 +125,7 @@ export function MobileWorkbench(props: IUniverAppProps) {
}, [mountContainer, portalContainer]);
useEffect(() => {
- portalContainer.dir = direction;
+ portalContainer.setAttribute('dir', direction);
}, [direction, portalContainer]);
useLayoutEffect(() => {
@@ -184,107 +185,107 @@ export function MobileWorkbench(props: IUniverAppProps) {
locale={locale?.design}
direction={direction}
mountContainer={portalContainer}
- disableTooltips
- mobile
>
- <div
- ref={viewportRef}
- className="
- univer-relative univer-h-full univer-min-h-0
- [&_button:active]:!univer-opacity-70
- [&_button]:univer-touch-manipulation
- "
- >
+ <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>
- )}
-
- {/* 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
- `}
- >
- <aside className="univer-h-full">
- <ComponentContainer key="left-sidebar" components={leftSidebarComponents} />
- </aside>
+ <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>
+ )}
- <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)}
+ {/* 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
+ `}
>
- <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>
</ConfigProvider>
);
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 9fdd10b51c..7f2c34b7e1 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1992,6 +1992,9 @@ importers:
'@univerjs/ui':
specifier: workspace:*
version: link:../ui
+ react-dom:
+ specifier: 19.2.8
+ version: 19.2.8([email protected])
devDependencies:
'@univerjs-infra/shared':
specifier: workspace:*
@@ -2404,6 +2407,9 @@ importers:
'@univerjs/ui':
specifier: workspace:*
version: link:../ui
+ react-dom:
+ specifier: 19.2.8
+ version: 19.2.8([email protected])
devDependencies:
'@univerjs-infra/shared':
specifier: workspace:*