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(ui): add docs mobile editing and shared canvas interactions (#7636)

Univer606fda5ab51a
diff --git a/packages/core/src/common/__tests__/function.spec.ts b/packages/core/src/common/__tests__/function.spec.ts
new file mode 100644
index 0000000000..d7e80d173b
--- /dev/null
+++ b/packages/core/src/common/__tests__/function.spec.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 { afterEach, describe, expect, it, vi } from 'vitest';
+import { throttle } from '../function';
+
+afterEach(() => vi.useRealTimers());
+
+describe('throttle', () => {
+ it('does not replay a delayed old value after a newer leading call', () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(1000);
+ const render = vi.fn();
+ const update = throttle(render, 100);
+ update('initial');
+ vi.setSystemTime(1010);
+ update('old');
+ // A background tab can delay timers beyond the throttle interval.
+ vi.setSystemTime(1200);
+ update('latest');
+ vi.runAllTimers();
+ expect(render.mock.calls).toEqual([['initial'], ['latest']]);
+ });
+
+ it('still delivers the last value of a burst', () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(1000);
+ const render = vi.fn();
+ const update = throttle(render, 100);
+ update('initial');
+ update('middle');
+ update('latest');
+ vi.runAllTimers();
+ expect(render.mock.calls).toEqual([['initial'], ['latest']]);
+ });
+});
diff --git a/packages/core/src/common/function.ts b/packages/core/src/common/function.ts
index 1f7b6a2edd..f74ea7c473 100644
--- a/packages/core/src/common/function.ts
+++ b/packages/core/src/common/function.ts
@@ -36,6 +36,10 @@ export function throttle<T extends (...args: any[]) => any>(fn: T, wait: number
fn.apply(this, args);
}, wait) as unknown as number;
} else {
+ if (timer) {
+ clearTimeout(timer);
+ timer = null;
+ }
lastTime = now;
fn.apply(this, args);
}
diff --git a/packages/design/src/components/dialog/MobileDialog.tsx b/packages/design/src/components/dialog/MobileDialog.tsx
index 2d84b82ef4..83d10b4783 100644
--- a/packages/design/src/components/dialog/MobileDialog.tsx
+++ b/packages/design/src/components/dialog/MobileDialog.tsx
@@ -15,7 +15,7 @@
*/
import type { IDialogProps } from './Dialog';
-import { useContext } from 'react';
+import { useContext, useRef } from 'react';
import { clsx } from '../../helper/clsx';
import { Button } from '../button/Button';
import { ConfigContext } from '../config-provider/ConfigProvider';
@@ -50,6 +50,7 @@ export function MobileDialog(props: IMobileDialogProps) {
onOk,
onCancel,
} = props;
+ const contentRef = useRef<HTMLDivElement>(null);
const { locale, mountContainer, direction } = useContext(ConfigContext);
const maxHeight = globalThis.CSS?.supports('height', '1dvh') ? '80dvh' : '80vh';
const footer = propFooter ?? (showOk || showCancel
@@ -81,8 +82,8 @@ export function MobileDialog(props: IMobileDialogProps) {
<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-bottom-0 !univer-left-0 !univer-right-0 !univer-top-auto !univer-flex !univer-max-w-none
+ !univer-translate-x-0 !univer-translate-y-0 !univer-flex-col !univer-gap-4 !univer-overflow-hidden
!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
@@ -90,6 +91,11 @@ export function MobileDialog(props: IMobileDialogProps) {
[&_button[data-slot='close']]:!univer-right-3 [&_button[data-slot='close']]:!univer-top-3
[&_button[data-slot='close']]:!univer-size-10
`, className)}
+ ref={contentRef}
+ onOpenAutoFocus={(event) => {
+ event.preventDefault();
+ contentRef.current?.focus({ preventScroll: true });
+ }}
style={{
...style,
position: 'fixed',
@@ -106,7 +112,6 @@ export function MobileDialog(props: IMobileDialogProps) {
mountContainer={mountContainer}
overlayClassName={overlayClassName}
dir={direction}
- onClickClose={close}
onEscapeKeyDown={(event) => {
if (keyboard) {
close();
@@ -120,14 +125,16 @@ export function MobileDialog(props: IMobileDialogProps) {
event.preventDefault();
}}
>
- <DialogHeader className={title ? undefined : '!univer-hidden'}>
+ <DialogHeader className={title ? 'univer-shrink-0 univer-px-10' : '!univer-hidden'}>
<DialogTitle>{title}</DialogTitle>
<DialogDescription className="univer-hidden" />
</DialogHeader>
- {children}
+ <div className="univer-min-h-0 univer-min-w-0 univer-overflow-y-auto">
+ {children}
+ </div>
- {footer && <DialogFooter>{footer}</DialogFooter>}
+ {footer && <DialogFooter className="univer-shrink-0">{footer}</DialogFooter>}
</DialogContent>
</DialogProvider>
);
diff --git a/packages/design/src/components/dialog/__tests__/MobileDialog.spec.tsx b/packages/design/src/components/dialog/__tests__/MobileDialog.spec.tsx
new file mode 100644
index 0000000000..114e393346
--- /dev/null
+++ b/packages/design/src/components/dialog/__tests__/MobileDialog.spec.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 { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { MobileDialog } from '../MobileDialog';
+import '@testing-library/jest-dom/vitest';
+
+afterEach(cleanup);
+
+describe('MobileDialog', () => {
+ it('keeps keyboard focus out of input fields until the user edits', () => {
+ render(<MobileDialog open title="Print"><input aria-label="Page range" /></MobileDialog>);
+ expect(screen.getByRole('dialog')).toHaveFocus();
+ expect(screen.getByRole('textbox')).not.toHaveFocus();
+ screen.getByRole('textbox').focus();
+ expect(screen.getByRole('textbox')).toHaveFocus();
+ });
+
+ it('closes once when the close control is pressed', () => {
+ const onClose = vi.fn();
+ render(<MobileDialog open title="Print" onClose={onClose}>Preview</MobileDialog>);
+ fireEvent.click(screen.getByRole('button', { name: 'Close' }));
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/design/src/components/dropdown/MobileDropdownSurface.tsx b/packages/design/src/components/dropdown/MobileDropdownSurface.tsx
index 9e3956cc3a..85b47d5bca 100644
--- a/packages/design/src/components/dropdown/MobileDropdownSurface.tsx
+++ b/packages/design/src/components/dropdown/MobileDropdownSurface.tsx
@@ -15,7 +15,7 @@
*/
import type { ReactNode } from 'react';
-import { useContext } from 'react';
+import { useContext, useLayoutEffect, useState } from 'react';
import { ConfigContext } from '../config-provider/ConfigProvider';
import {
Dialog,
@@ -24,6 +24,7 @@ import {
DialogTitle,
DialogTrigger,
} from '../dialog/DialogPrimitive';
+import { MobileOverlayContext } from './mobile-overlay-context';
export function MobileDropdownSurface(props: {
children: ReactNode;
@@ -34,19 +35,28 @@ 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';
+ const mobileOverlay = useContext(MobileOverlayContext);
+ const [surface, setSurface] = useState<HTMLDivElement | null>(null);
+ const modal = mobileOverlay?.modal ?? true;
+ useLayoutEffect(() => {
+ if (open && surface) {
+ return mobileOverlay?.onMount(surface);
+ }
+ }, [open, surface, mobileOverlay]);
+ const viewportHeightUnit = globalThis.CSS?.supports('height', '1dvh') ? 'dvh' : 'vh';
return (
- <Dialog open={open} onOpenChange={onOpenChange} modal>
+ <Dialog open={open} onOpenChange={onOpenChange} modal={modal}>
<DialogTrigger asChild disabled={disabled}>
{children}
</DialogTrigger>
<DialogContent
+ ref={setSurface}
mountContainer={mountContainer}
overlayClassName="!univer-z-[1390]"
className="
- !univer-bottom-0 !univer-left-0 !univer-right-0 !univer-top-auto !univer-z-[1400] !univer-block
- !univer-w-full !univer-max-w-none !univer-translate-x-0 !univer-translate-y-0 !univer-overflow-y-auto
+ !univer-left-0 !univer-right-0 !univer-top-auto !univer-z-[1400] !univer-block !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
@@ -58,11 +68,14 @@ export function MobileDropdownSurface(props: {
insetInline: 0,
top: 'auto',
bottom: 0,
+ maxHeight: `80${viewportHeightUnit}`,
width: '100%',
- maxHeight,
maxWidth: 'none',
transform: 'none',
+ ...mobileOverlay?.contentProps.style,
}}
+ onOpenAutoFocus={mobileOverlay?.contentProps.onOpenAutoFocus}
+ onCloseAutoFocus={mobileOverlay?.contentProps.onCloseAutoFocus}
>
<div
aria-hidden="true"
diff --git a/packages/design/src/components/dropdown/__tests__/index.spec.tsx b/packages/design/src/components/dropdown/__tests__/index.spec.tsx
index 8180d78752..89ff1b7f2e 100644
--- a/packages/design/src/components/dropdown/__tests__/index.spec.tsx
+++ b/packages/design/src/components/dropdown/__tests__/index.spec.tsx
@@ -18,11 +18,12 @@
* @vitest-environment jsdom
*/
-import { cleanup, render, screen } from '@testing-library/react';
+import { cleanup, render, screen, waitFor } 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 { Dropdown } from '../Dropdown';
+import { MobileOverlayContext } from '../mobile-overlay-context';
import { MobileDropdown } from '../MobileDropdown';
afterEach(() => {
@@ -90,8 +91,63 @@ describe('Dropdown', () => {
const dialog = screen.getByRole('dialog');
expect(dialog.textContent).toContain('Overlay Content');
- expect(dialog.classList.contains('!univer-bottom-0')).toBe(true);
+ expect(dialog.style.bottom).toBe('0px');
expect(dialog.style.maxHeight).toBe('80vh');
expect(screen.getByText(enUS.design.Accessibility.menu)).toBeTruthy();
});
+
+ it('registers a non-modal object surface and releases it when closed', () => {
+ const release = vi.fn();
+ const onMount = vi.fn((_element: HTMLElement) => release);
+ const overlay = { modal: false, contentProps: {}, onMount };
+ const app = (open: boolean) => (
+ <ConfigProvider locale={enUS.design} mountContainer={document.body}>
+ <MobileOverlayContext.Provider value={overlay}>
+ <button type="button">Canvas action</button>
+ <MobileDropdown overlay={<div>Object options</div>} open={open}>
+ <button type="button">Trigger</button>
+ </MobileDropdown>
+ </MobileOverlayContext.Provider>
+ </ConfigProvider>
+ );
+ const view = render(app(true));
+ const dialog = screen.getByRole('dialog');
+ expect(onMount).toHaveBeenCalledWith(dialog);
+ expect(dialog.getAttribute('aria-modal')).not.toBe('true');
+ expect(screen.getByRole('button', { name: 'Canvas action' })).toBeTruthy();
+ expect(dialog.style.height).toBe('');
+ view.rerender(app(false));
+ expect(release).toHaveBeenCalledTimes(1);
+ });
+
+ it('applies host sizing and focus behavior independently of modality', async () => {
+ const onOpenAutoFocus = vi.fn((event: Event) => event.preventDefault());
+ const onCloseAutoFocus = vi.fn((event: Event) => event.preventDefault());
+ const overlay = {
+ modal: false,
+ contentProps: { style: { height: 240, maxHeight: 320 }, onOpenAutoFocus, onCloseAutoFocus },
+ onMount: vi.fn(),
+ };
+ const app = (open: boolean) => (
+ <ConfigProvider locale={enUS.design} mountContainer={document.body}>
+ <MobileOverlayContext.Provider value={overlay}>
+ <input aria-label="Editor" />
+ <MobileDropdown overlay={<input aria-label="Options" />} open={open}>
+ <button type="button">Trigger</button>
+ </MobileDropdown>
+ </MobileOverlayContext.Provider>
+ </ConfigProvider>
+ );
+ const view = render(app(false));
+ const editor = screen.getByRole('textbox', { name: 'Editor' });
+ editor.focus();
+ view.rerender(app(true));
+ expect(screen.getByRole('dialog').style.height).toBe('240px');
+ expect(screen.getByRole('dialog').style.maxHeight).toBe('320px');
+ expect(document.activeElement).toBe(editor);
+ expect(onOpenAutoFocus).toHaveBeenCalledOnce();
+ view.rerender(app(false));
+ await waitFor(() => expect(onCloseAutoFocus).toHaveBeenCalledOnce());
+ expect(document.activeElement).toBe(editor);
+ });
});
diff --git a/packages/design/src/components/dropdown/mobile-overlay-context.ts b/packages/design/src/components/dropdown/mobile-overlay-context.ts
new file mode 100644
index 0000000000..06b7ede54d
--- /dev/null
+++ b/packages/design/src/components/dropdown/mobile-overlay-context.ts
@@ -0,0 +1,26 @@
+/**
+ * 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 { ComponentPropsWithoutRef } from 'react';
+import type { DialogContent } from '../dialog/DialogPrimitive';
+import { createContext } from 'react';
+
+/** The host supplies layout and focus behavior for nested mobile surfaces. */
+export const MobileOverlayContext = createContext<{
+ modal: boolean;
+ contentProps: Pick<ComponentPropsWithoutRef<typeof DialogContent>, 'style' | 'onOpenAutoFocus' | 'onCloseAutoFocus'>;
+ onMount: (element: HTMLElement) => void | (() => void);
+} | null>(null);
diff --git a/packages/design/src/components/gradient-color-picker/GradientColorPicker.tsx b/packages/design/src/components/gradient-color-picker/GradientColorPicker.tsx
index c398b7f5dd..2087bd63f4 100644
--- a/packages/design/src/components/gradient-color-picker/GradientColorPicker.tsx
+++ b/packages/design/src/components/gradient-color-picker/GradientColorPicker.tsx
@@ -43,6 +43,7 @@ export interface IGradientColorPickerProps {
compact?: boolean;
value?: IGradientValue;
onChange?: (value: IGradientValue) => void;
+ types?: readonly GradientType[];
}
const DEFAULT_VALUE: IGradientValue = {
@@ -260,7 +261,7 @@ export function GradientColorPicker(props: IGradientColorPickerProps) {
{ label: locale?.GradientColorPicker.radial, value: 'radial' },
{ label: locale?.GradientColorPicker.angular, value: 'angular' },
{ label: locale?.GradientColorPicker.diamond, value: 'diamond' },
- ].map((item) => {
+ ].filter((item) => !props.types || props.types.some((type) => type === item.value)).map((item) => {
const selected = draftValue.type === item.value;
return (
@@ -309,7 +310,7 @@ export function GradientColorPicker(props: IGradientColorPickerProps) {
{ label: locale?.GradientColorPicker.radial, value: 'radial' },
{ label: locale?.GradientColorPicker.angular, value: 'angular' },
{ label: locale?.GradientColorPicker.diamond, value: 'diamond' },
- ]}
+ ].filter((item) => !props.types || props.types.some((type) => type === item.value))}
value={draftValue.type}
onChange={(v) => handleTypeChange(v as GradientType)}
/>
diff --git a/packages/design/src/components/gradient-color-picker/MobileGradientColorPicker.tsx b/packages/design/src/components/gradient-color-picker/MobileGradientColorPicker.tsx
new file mode 100644
index 0000000000..6f95ee11ee
--- /dev/null
+++ b/packages/design/src/components/gradient-color-picker/MobileGradientColorPicker.tsx
@@ -0,0 +1,118 @@
+/**
+ * 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 { GradientType, IGradientColorPickerProps, IGradientStop } from './GradientColorPicker';
+import { DeleteIcon, IncreaseIcon } from '@univerjs/icons';
+import { useContext, useState } from 'react';
+import { clsx } from '../../helper/clsx';
+import { Button } from '../button/Button';
+import { MobileColorPicker } from '../color-picker/MobileColorPicker';
+import { ConfigContext } from '../config-provider/ConfigProvider';
+import { InputNumber } from '../input-number/InputNumber';
+import { MobileActionRow } from '../mobile-action-row/MobileActionRow';
+
+const GRADIENT_TYPES: readonly GradientType[] = ['linear', 'radial', 'angular', 'diamond'];
+const NUMBER_CLASS = 'univer-w-full [&_input]:!univer-h-12 [&_input]:!univer-text-base';
+
+export function MobileGradientColorPicker({ value = { type: 'linear', stops: [{ color: '#ffffff', offset: 0 }, { color: '#000000', offset: 100 }], angle: 0 }, onChange, types = GRADIENT_TYPES, className }: IGradientColorPickerProps) {
+ const { locale } = useContext(ConfigContext);
+ const [selectedIndex, setSelectedIndex] = useState(0);
+ const index = Math.min(selectedIndex, Math.max(0, value.stops.length - 1));
+ const selectedStop = value.stops[index];
+
+ function updateStop(patch: Partial<IGradientStop>) {
+ onChange?.({ ...value, stops: value.stops.map((stop, stopIndex) => stopIndex === index ? { ...stop, ...patch } : stop) });
+ }
+
+ function addStop() {
+ const stop = selectedStop ?? { color: '#ffffff', offset: 0 };
+ const nextOffset = value.stops.filter((item) => item.offset > stop.offset).reduce((offset, item) => Math.min(offset, item.offset), 100);
+ onChange?.({ ...value, stops: [...value.stops, { ...stop, offset: Math.round((stop.offset + nextOffset) / 2) }] });
+ setSelectedIndex(value.stops.length);
+ }
+
+ return (
+ <div className={clsx('univer-grid univer-w-full univer-min-w-0 univer-gap-4', className)}>
+ {types.length > 1 && (
+ <div className="univer-grid univer-grid-cols-2 univer-gap-2">
+ {types.map((type) => (
+ <MobileActionRow
+ key={type}
+ title={locale?.GradientColorPicker[type]}
+ aria-pressed={value.type === type}
+ className={value.type === type ? '!univer-bg-primary-50 !univer-text-primary-600' : undefined}
+ onClick={() => onChange?.({ ...value, type })}
+ />
+ ))}
+ </div>
+ )}
+ {(value.type === 'linear' || value.type === 'angular') && (
+ <label className="univer-grid univer-gap-2 univer-text-base">
+ {locale?.GradientColorPicker.angle}
+ <InputNumber className={NUMBER_CLASS} controls={false} value={value.angle ?? 0} min={0} max={360} onChange={(angle) => onChange?.({ ...value, angle: angle ?? 0 })} />
+ </label>
+ )}
+ <div className="univer-flex univer-flex-wrap univer-gap-2">
+ {value.stops.map((stop, stopIndex) => (
+ <button
+ key={stopIndex}
+ type="button"
+ aria-label={`${locale?.GradientColorPicker.offset} ${stop.offset}%`}
+ aria-pressed={index === stopIndex}
+ className={clsx(`
+ univer-flex univer-h-12 univer-min-w-12 univer-appearance-none univer-items-center
+ univer-justify-center univer-gap-2 univer-rounded-lg univer-border univer-border-solid
+ univer-bg-transparent univer-px-2 univer-text-sm
+ `, index === stopIndex
+ ? 'univer-border-primary-600 univer-text-primary-600'
+ : 'univer-border-gray-200')}
+ onClick={() => setSelectedIndex(stopIndex)}
+ >
+ <span className="univer-size-6 univer-shrink-0 univer-rounded" style={{ backgroundColor: stop.color, opacity: stop.opacity ?? 1 }} />
+ {`${stop.offset}%`}
+ </button>
+ ))}
+ <Button className="univer-size-12" aria-label={locale?.Accessibility.increment} onClick={addStop}><IncreaseIcon /></Button>
+ <Button
+ className="univer-size-12"
+ aria-label={locale?.GradientColorPicker.delete}
+ disabled={value.stops.length <= 2}
+ onClick={() => {
+ onChange?.({ ...value, stops: value.stops.filter((_, stopIndex) => stopIndex !== index) });
+ setSelectedIndex(0);
+ }}
+ >
+ <DeleteIcon />
+ </Button>
+ </div>
+ {selectedStop && (
+ <>
+ <div className="univer-grid univer-grid-cols-2 univer-gap-3">
+ <label className="univer-grid univer-gap-2 univer-text-base">
+ {locale?.GradientColorPicker.offset}
+ <InputNumber className={NUMBER_CLASS} controls={false} value={selectedStop.offset} min={0} max={100} onChange={(offset) => updateStop({ offset: offset ?? 0 })} />
+ </label>
+ <label className="univer-grid univer-gap-2 univer-text-base">
+ {locale?.GradientColorPicker.transparency}
+ <InputNumber className={NUMBER_CLASS} controls={false} value={Math.round((1 - (selectedStop.opacity ?? 1)) * 100)} min={0} max={100} onChange={(transparency) => updateStop({ opacity: 1 - (transparency ?? 0) / 100 })} />
+ </label>
+ </div>
+ <MobileColorPicker value={selectedStop.color} onChange={(color) => updateStop({ color })} />
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/packages/design/src/components/gradient-color-picker/__tests__/index.spec.tsx b/packages/design/src/components/gradient-color-picker/__tests__/index.spec.tsx
index 11658f4a20..e008425d89 100644
--- a/packages/design/src/components/gradient-color-picker/__tests__/index.spec.tsx
+++ b/packages/design/src/components/gradient-color-picker/__tests__/index.spec.tsx
@@ -20,11 +20,19 @@
import type { IGradientValue } from '../GradientColorPicker';
import { cleanup, fireEvent, render, waitFor } from '@testing-library/react';
-import { afterEach, describe, expect, it, vi } from 'vitest';
+import { useState } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import enUS from '../../../locale/en-US';
+import { ConfigProvider } from '../../config-provider/ConfigProvider';
import { GradientColorPicker } from '../GradientColorPicker';
+import { MobileGradientColorPicker } from '../MobileGradientColorPicker';
import '@testing-library/jest-dom/vitest';
-afterEach(cleanup);
+beforeEach(() => vi.stubGlobal('CSS', { ...globalThis.CSS, supports: () => false }));
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
const defaultValue: IGradientValue = {
type: 'linear',
@@ -35,6 +43,51 @@ const defaultValue: IGradientValue = {
angle: 0,
};
+describe('mobile GradientColorPicker', () => {
+ it('updates the selected stop, adds and removes stops without desktop hover controls', () => {
+ const onChange = vi.fn();
+ function Editor() {
+ const [value, setValue] = useState(defaultValue);
+ return (
+ <ConfigProvider mountContainer={document.body} locale={enUS.design}>
+ <MobileGradientColorPicker
+ value={value}
+ types={['linear']}
+ onChange={(next) => {
+ setValue(next);
+ onChange(next);
+ }}
+ />
+ </ConfigProvider>
+ );
+ }
+ const view = render(<Editor />);
+ expect(view.queryByText(enUS.design.GradientColorPicker.radial)).toBeNull();
+ fireEvent.click(view.getByRole('button', { name: enUS.design.Accessibility.increment }));
+ expect(onChange).toHaveBeenLastCalledWith(expect.objectContaining({ stops: [defaultValue.stops[0], defaultValue.stops[1], { ...defaultValue.stops[0], offset: 50 }] }));
+ expect(view.getByRole('button', { name: `${enUS.design.GradientColorPicker.offset} 50%` })).toHaveAttribute('aria-pressed', 'true');
+ fireEvent.change(view.getByLabelText(enUS.design.GradientColorPicker.angle), { target: { value: '180' } });
+ fireEvent.change(view.getByLabelText(enUS.design.GradientColorPicker.offset), { target: { value: '60' } });
+ fireEvent.change(view.getByLabelText(enUS.design.GradientColorPicker.transparency), { target: { value: '40' } });
+ expect(onChange).toHaveBeenLastCalledWith(expect.objectContaining({ angle: 180, stops: expect.arrayContaining([{ color: '#ffffff', offset: 60, opacity: 0.6 }]) }));
+ fireEvent.click(view.getByRole('button', { name: enUS.design.GradientColorPicker.delete }));
+ expect(onChange).toHaveBeenLastCalledWith({ ...defaultValue, angle: 180 });
+ expect(view.getByRole('button', { name: enUS.design.GradientColorPicker.delete })).toBeDisabled();
+ });
+
+ it('supports every registered gradient type and controlled value updates', () => {
+ const onChange = vi.fn();
+ const view = render(<ConfigProvider mountContainer={document.body} locale={enUS.design}><MobileGradientColorPicker value={defaultValue} onChange={onChange} /></ConfigProvider>);
+ for (const type of ['linear', 'radial', 'angular', 'diamond'] as const) {
+ fireEvent.click(view.getByRole('button', { name: enUS.design.GradientColorPicker[type] }));
+ expect(onChange).toHaveBeenLastCalledWith({ ...defaultValue, type });
+ }
+ view.rerender(<ConfigProvider mountContainer={document.body} locale={enUS.design}><MobileGradientColorPicker value={{ ...defaultValue, type: 'radial' }} onChange={onChange} /></ConfigProvider>);
+ expect(view.getByRole('button', { name: enUS.design.GradientColorPicker.radial })).toHaveAttribute('aria-pressed', 'true');
+ expect(view.queryByLabelText(enUS.design.GradientColorPicker.angle)).toBeNull();
+ });
+});
+
describe('GradientColorPicker', () => {
it('renders correctly', () => {
const { container } = render(<GradientColorPicker value={defaultValue} />);
diff --git a/packages/design/src/components/select/MobileSelect.tsx b/packages/design/src/components/select/MobileSelect.tsx
index 854e049586..510482e8a1 100644
--- a/packages/design/src/components/select/MobileSelect.tsx
+++ b/packages/design/src/components/select/MobileSelect.tsx
@@ -93,9 +93,12 @@ export function MobileSelect(props: IMobileSelectProps) {
disabled={disabled}
onOpenChange={setOpen}
>
- <div
+ <button
+ type="button"
+ disabled={disabled}
+ aria-expanded={open}
data-u-comp="mobile-select"
- className={clsx(selectClassName, {
+ className={clsx(selectClassName, '!univer-h-auto !univer-min-h-12 univer-text-left', {
'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,
@@ -104,7 +107,7 @@ export function MobileSelect(props: IMobileSelectProps) {
>
<div
className="
- univer-flex-1 univer-truncate univer-text-sm univer-text-gray-500
+ univer-flex-1 univer-truncate univer-text-base univer-text-gray-500
dark:!univer-text-gray-0
"
>
@@ -116,7 +119,7 @@ export function MobileSelect(props: IMobileSelectProps) {
dark:!univer-text-gray-0
"
/>
- </div>
+ </button>
</MobileDropdownMenu>
);
}
diff --git a/packages/design/src/components/select/__tests__/index.spec.tsx b/packages/design/src/components/select/__tests__/index.spec.tsx
index 7343855038..9656bd163d 100644
--- a/packages/design/src/components/select/__tests__/index.spec.tsx
+++ b/packages/design/src/components/select/__tests__/index.spec.tsx
@@ -38,16 +38,27 @@ afterEach(cleanup);
describe('Select', () => {
it('should render mobile options in a touch-first dialog explicitly', () => {
const handleChange = vi.fn();
- const { container } = render(
+ 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);
+ fireEvent.click(screen.getByRole('button', { name: 'Option 1' }));
expect(screen.getByRole('dialog')).toBeInTheDocument();
fireEvent.click(screen.getByText('Option 2'));
- expect(handleChange).toHaveBeenCalledWith('2');
+ expect(handleChange).toHaveBeenCalledExactlyOnceWith('2');
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
+ });
+
+ it('does not open a disabled mobile select', () => {
+ const onChange = vi.fn();
+ render(<MobileSelect value="1" options={options} disabled onChange={onChange} />);
+ const trigger = screen.getByRole('button', { name: 'Option 1' });
+ expect(trigger).toBeDisabled();
+ fireEvent.click(trigger);
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
+ expect(onChange).not.toHaveBeenCalled();
});
it('should fall back to the mobile select value when its option label is empty', () => {
diff --git a/packages/design/src/index.ts b/packages/design/src/index.ts
index 5821122f38..ac5ed150da 100644
--- a/packages/design/src/index.ts
+++ b/packages/design/src/index.ts
@@ -77,6 +77,7 @@ export { MobileDropdownMenu } from './components/dropdown-menu/MobileDropdownMen
export type { IMobileDropdownMenuProps } from './components/dropdown-menu/MobileDropdownMenu';
export { Dropdown } from './components/dropdown/Dropdown';
export type { IDropdownProps } from './components/dropdown/Dropdown';
+export { MobileOverlayContext } from './components/dropdown/mobile-overlay-context';
export { MobileDropdown } from './components/dropdown/MobileDropdown';
export type { IMobileDropdownProps } from './components/dropdown/MobileDropdown';
export { FormDualColumnLayout, FormLayout } from './components/form-layout';
@@ -90,6 +91,7 @@ export type {
IGradientStop,
IGradientValue,
} from './components/gradient-color-picker/GradientColorPicker';
+export { MobileGradientColorPicker } from './components/gradient-color-picker/MobileGradientColorPicker';
export { HoverCard } from './components/hover-card/HoverCard';
export type { IHoverCardProps } from './components/hover-card/HoverCard';
export { InputNumber } from './components/input-number/InputNumber';
diff --git a/packages/docs-drawing-ui/package.json b/packages/docs-drawing-ui/package.json
index d507c55980..6e3e807a06 100644
--- a/packages/docs-drawing-ui/package.json
+++ b/packages/docs-drawing-ui/package.json
@@ -82,6 +82,7 @@
"@univerjs/drawing": "workspace:*",
"@univerjs/drawing-ui": "workspace:*",
"@univerjs/engine-render": "workspace:*",
+ "@univerjs/icons": "1.38.0",
"@univerjs/ui": "workspace:*"
},
"devDependencies": {
diff --git a/packages/docs-drawing-ui/src/commands/operations/__tests__/open-drawing-panel.operation.spec.ts b/packages/docs-drawing-ui/src/commands/operations/__tests__/open-drawing-panel.operation.spec.ts
index 9a46db796b..314b91323b 100644
--- a/packages/docs-drawing-ui/src/commands/operations/__tests__/open-drawing-panel.operation.spec.ts
+++ b/packages/docs-drawing-ui/src/commands/operations/__tests__/open-drawing-panel.operation.spec.ts
@@ -50,11 +50,12 @@ describe('SidebarDocDrawingOperation', () => {
it('opens the doc drawing sidebar and clears focus when closed', async () => {
const { accessor, sidebarService, drawingManagerService } = createAccessor();
await expect(SidebarDocDrawingOperation.handler(accessor, { value: 'open' })).resolves.toBe(true);
- expect(sidebarService.open).toHaveBeenCalledWith(expect.objectContaining({
+ expect(sidebarService.open).toHaveBeenCalledWith({
header: { title: 'docs-drawing-ui.panel.title' },
children: { label: COMPONENT_DOC_DRAWING_PANEL },
+ onClose: expect.any(Function),
width: 360,
- }));
+ });
const onClose = sidebarService.open.mock.calls[0][0].onClose;
onClose();
expect(drawingManagerService.focusDrawing).toHaveBeenCalledWith(null);
diff --git a/packages/docs-drawing-ui/src/commands/operations/mobile/open-drawing-panel.operation.ts b/packages/docs-drawing-ui/src/commands/operations/mobile/open-drawing-panel.operation.ts
new file mode 100644
index 0000000000..b731b76f02
--- /dev/null
+++ b/packages/docs-drawing-ui/src/commands/operations/mobile/open-drawing-panel.operation.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 { IAccessor, ICommand } from '@univerjs/core';
+import type { IMobileSidebarMethodOptions } from '@univerjs/ui';
+import type { LocaleKey } from '../../../locale/types';
+import type { IUIComponentCommandParams } from '../open-drawing-panel.operation';
+import { CommandType, LocaleService } from '@univerjs/core';
+import { IDrawingManagerService } from '@univerjs/drawing';
+import { ISidebarService } from '@univerjs/ui';
+import { COMPONENT_DOC_DRAWING_PANEL } from '../../../views/doc-image-panel/component-name';
+import { SidebarDocDrawingOperation } from '../open-drawing-panel.operation';
+
+export const SidebarDocDrawingMobileOperation: ICommand = {
+ id: SidebarDocDrawingOperation.id,
+ type: CommandType.COMMAND,
+ handler: async (accessor: IAccessor, params: IUIComponentCommandParams) => {
+ const sidebarService = accessor.get(ISidebarService);
+ const localeService = accessor.get(LocaleService);
+ const drawingManagerService = accessor.get(IDrawingManagerService);
+
+ switch (params.value) {
+ case 'open': {
+ const options: IMobileSidebarMethodOptions = {
+ layout: 'canvas',
+ header: { title: localeService.t<LocaleKey>('docs-drawing-ui.panel.title') },
+ children: { label: COMPONENT_DOC_DRAWING_PANEL },
+ onClose: () => {
+ drawingManagerService.focusDrawing(null);
+ },
+ width: 360,
+ };
+ sidebarService.open(options);
+ break;
+ }
+ case 'close':
+ default:
+ sidebarService.close();
+ break;
+ }
+ return true;
+ },
+};
diff --git a/packages/docs-drawing-ui/src/commands/operations/open-drawing-panel.operation.ts b/packages/docs-drawing-ui/src/commands/operations/open-drawing-panel.operation.ts
index c3235a0e67..f2e416a949 100644
--- a/packages/docs-drawing-ui/src/commands/operations/open-drawing-panel.operation.ts
+++ b/packages/docs-drawing-ui/src/commands/operations/open-drawing-panel.operation.ts
@@ -19,7 +19,9 @@ import type { LocaleKey } from '../../locale/types';
import { CommandType, LocaleService } from '@univerjs/core';
import { IDrawingManagerService } from '@univerjs/drawing';
import { ISidebarService } from '@univerjs/ui';
-import { COMPONENT_DOC_DRAWING_PANEL } from '../../views/doc-image-panel/component-name';
+import {
+ COMPONENT_DOC_DRAWING_PANEL,
+} from '../../views/doc-image-panel/component-name';
export interface IUIComponentCommandParams {
value: string;
diff --git a/packages/docs-drawing-ui/src/config/config.ts b/packages/docs-drawing-ui/src/config/config.ts
index 8e8a0e220f..efa2aa3345 100644
--- a/packages/docs-drawing-ui/src/config/config.ts
+++ b/packages/docs-drawing-ui/src/config/config.ts
@@ -15,6 +15,7 @@
*/
export const DOCS_DRAWING_UI_PLUGIN_CONFIG_KEY = 'docs-drawing-ui.config';
+export const DOCS_DRAWING_UI_PLUGIN_NAME = 'DOC_DRAWING_UI_PLUGIN';
export const configSymbol = Symbol(DOCS_DRAWING_UI_PLUGIN_CONFIG_KEY);
diff --git a/packages/docs-drawing-ui/src/controllers/mobile/components.controller.ts b/packages/docs-drawing-ui/src/controllers/mobile/components.controller.ts
new file mode 100644
index 0000000000..799f4a24d3
--- /dev/null
+++ b/packages/docs-drawing-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 { ComponentManager } from '@univerjs/ui';
+import { COMPONENT_DOC_DRAWING_PANEL } from '../../views/doc-image-panel/component-name';
+import { MobileDocDrawingPanel } from '../../views/doc-image-panel/MobileDocDrawingPanel';
+
+export class MobileComponentsController extends Disposable {
+ constructor(@Inject(ComponentManager) componentManager: ComponentManager) {
+ super();
+ this.disposeWithMe(componentManager.register(COMPONENT_DOC_DRAWING_PANEL, MobileDocDrawingPanel));
+ }
+}
diff --git a/packages/docs-drawing-ui/src/controllers/mobile/drawing-popup-menu.controller.ts b/packages/docs-drawing-ui/src/controllers/mobile/drawing-popup-menu.controller.ts
new file mode 100644
index 0000000000..2243d2fe79
--- /dev/null
+++ b/packages/docs-drawing-ui/src/controllers/mobile/drawing-popup-menu.controller.ts
@@ -0,0 +1,479 @@
+/**
+ * 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, INeedCheckDisposable, Nullable } from '@univerjs/core';
+import type { BaseObject, Scene } from '@univerjs/engine-render';
+import {
+ DrawingTypeEnum,
+ FOCUSING_COMMON_DRAWINGS,
+ ICommandService,
+ IContextService,
+ Inject,
+ IPermissionService,
+ isInternalEditorID,
+ IUniverInstanceService,
+ RxDisposable,
+ toDisposable,
+ UniverInstanceType,
+} from '@univerjs/core';
+import {
+ canEditDocumentTargets,
+ getDocumentDrawingSegmentId,
+ getDocumentEntityParentPermissionObjectIds,
+ getDocumentEntityPermissionObjectId,
+} from '@univerjs/docs';
+import { IDocDrawingAdapterService, IDocDrawingService, RemoveDocDrawingCommand } from '@univerjs/docs-drawing';
+import { DocCanvasPopManagerService, MOBILE_DOC_ELEMENT_MENU } from '@univerjs/docs-ui';
+import { IDrawingManagerService } from '@univerjs/drawing';
+import {
+ COMPONENT_MOBILE_IMAGE_POPUP_MENU,
+ ImageCropperObject,
+ ImageResetSizeOperation,
+ OpenImageCropOperation,
+} from '@univerjs/drawing-ui';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { FloatingObjectToolbarPosition, IMenuManagerService, MenuItemType } from '@univerjs/ui';
+import { takeUntil } from 'rxjs';
+import { EditDocDrawingOperation } from '../../commands/operations/edit-doc-drawing.operation';
+import { SidebarDocDrawingMobileOperation } from '../../commands/operations/mobile/open-drawing-panel.operation';
+import { DocDrawingFloatingToolbarAdapterService } from '../../services/doc-drawing-floating-toolbar-adapter.service';
+
+interface IDrawingPopupTarget {
+ unitId: string;
+ subUnitId: string;
+ drawingId: string;
+}
+
+export class MobileDocDrawingPopupMenuController extends RxDisposable {
+ private _initImagePopupMenu = new Set<string>();
+ private _embeddedRenderUnits = new Set<string>();
+ private _popupMenuListeners = new Map<string, IDisposable>();
+ private _disposePopupsByUnit = new Map<string, INeedCheckDisposable[]>();
+ private _popupTargetsByUnit = new Map<string, IDrawingPopupTarget>();
+ private _isDrawingPanelOpen = false;
+
+ constructor(
+ @IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,
+ @Inject(DocCanvasPopManagerService) private readonly _canvasPopManagerService: DocCanvasPopManagerService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @IContextService private readonly _contextService: IContextService,
+ @IDocDrawingAdapterService private readonly _drawingAdapterService: IDocDrawingAdapterService,
+ @IDocDrawingService private readonly _docDrawingService: IDocDrawingService,
+ @Inject(DocDrawingFloatingToolbarAdapterService) private readonly _floatingToolbarAdapterService: DocDrawingFloatingToolbarAdapterService,
+ @ICommandService private readonly _commandService: ICommandService,
+ @IMenuManagerService private readonly _menuManagerService: IMenuManagerService,
+ @IPermissionService private readonly _permissionService: IPermissionService
+ ) {
+ super();
+
+ this._init();
+ }
+
+ // eslint-disable-next-line max-lines-per-function
+ private _init(): void {
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command) => {
+ const opensDrawingEditor = [...this._popupTargetsByUnit.values()].some((target) => {
+ const drawing = this._docDrawingService.getDrawingByParam(target);
+ const edit = drawing && this._drawingAdapterService.getEditDrawingCommandInfo({ ...target, drawing });
+ return edit?.commandId === command.id;
+ });
+ if (command.id === EditDocDrawingOperation.id || opensDrawingEditor) {
+ this._isDrawingPanelOpen = true;
+ this._clearPopups(undefined, true);
+ }
+ if (command.id === SidebarDocDrawingMobileOperation.id) {
+ const params = command.params as { value?: string } | undefined;
+ this._isDrawingPanelOpen = params?.value === 'open';
+ if (this._isDrawingPanelOpen) {
+ this._clearPopups(undefined, true);
+ }
+ }
+ })
+ );
+ this.disposeWithMe(
+ this._drawingManagerService.focus$.subscribe((params) => {
+ if (params.length === 0) {
+ this._isDrawingPanelOpen = false;
+ }
+ })
+ );
+ this.disposeWithMe(this._drawingManagerService.remove$.subscribe((drawings) => {
+ for (const drawing of drawings) {
+ for (const [unitId, target] of this._popupTargetsByUnit) {
+ if (
+ target.unitId === drawing.unitId &&
+ target.subUnitId === drawing.subUnitId &&
+ target.drawingId === drawing.drawingId
+ ) {
+ this._clearPopups(unitId, true);
+ this._renderManagerService.getRenderUnitById(unitId)?.scene.getTransformerByCreate().clearSelectedObjects();
+ }
+ }
+ }
+ }));
+ this.disposeWithMe(this._permissionService.permissionPointUpdate$.subscribe(() => {
+ for (const [popupUnitId, drawing] of this._popupTargetsByUnit) {
+ if (!this._canEditDrawing(drawing.unitId, drawing.drawingId)) {
+ this._clearPopups(popupUnitId, true);
+ }
+ }
+ }));
+
+ this.disposeWithMe(
+ this._univerInstanceService.getCurrentTypeOfUnit$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC).pipe(takeUntil(this.dispose$)).subscribe((documentDataModel) => this._create(documentDataModel))
+ );
+
+ this.disposeWithMe(
+ this._univerInstanceService.getTypeOfUnitDisposed$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC).pipe(takeUntil(this.dispose$)).subscribe((documentDataModel) => this._dispose(documentDataModel))
+ );
+
+ this.disposeWithMe(
+ this._renderManagerService.created$.pipe(takeUntil(this.dispose$)).subscribe((render) => {
+ if (render.type !== UniverInstanceType.UNIVER_DOC || render.isMainScene) {
+ return;
+ }
+
+ this._embeddedRenderUnits.add(render.unitId);
+ this._create(this._univerInstanceService.getUnit<DocumentDataModel>(render.unitId, UniverInstanceType.UNIVER_DOC));
+ })
+ );
+
+ this.disposeWithMe(
+ this._renderManagerService.disposed$.pipe(takeUntil(this.dispose$)).subscribe((unitId) => {
+ if (!this._embeddedRenderUnits.delete(unitId)) {
+ return;
+ }
+
+ this._disposePopupMenuListener(unitId);
+ })
+ );
+
+ this._univerInstanceService.getAllUnitsForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC).forEach((documentDataModel) => this._create(documentDataModel));
+ }
+
+ private _dispose(documentDataModel: DocumentDataModel) {
+ const unitId = documentDataModel.getUnitId();
+ this._clearPopups(unitId, true);
+ this._disposePopupMenuListener(unitId);
+ this._renderManagerService.removeRender(unitId);
+ }
+
+ private _clearPopups(unitId?: string, force = false) {
+ if (unitId == null) {
+ [...this._disposePopupsByUnit.keys()].forEach((popupUnitId) => this._clearPopups(popupUnitId, force));
+ return;
+ }
+
+ const popups = this._disposePopupsByUnit.get(unitId);
+ if (!popups) {
+ return;
+ }
+
+ for (let index = popups.length - 1; index >= 0; index -= 1) {
+ const popup = popups[index];
+ if (force || popup.canDispose()) {
+ popup.dispose();
+ popups.splice(index, 1);
+ }
+ }
+
+ if (popups.length === 0) {
+ this._disposePopupsByUnit.delete(unitId);
+ this._popupTargetsByUnit.delete(unitId);
+ }
+ }
+
+ private _getDisposePopups(unitId: string): INeedCheckDisposable[] {
+ const popups = this._disposePopupsByUnit.get(unitId);
+ if (popups) {
+ return popups;
+ }
+
+ const nextPopups: INeedCheckDisposable[] = [];
+ this._disposePopupsByUnit.set(unitId, nextPopups);
+ return nextPopups;
+ }
+
+ private _create(documentDataModel: Nullable<DocumentDataModel>) {
+ if (!documentDataModel) {
+ return;
+ }
+
+ const unitId = documentDataModel.getUnitId();
+ if (isInternalEditorID(unitId)) {
+ return;
+ }
+ if (this._renderManagerService.has(unitId) && !this._initImagePopupMenu.has(unitId)) {
+ const listener = this._popupMenuListener(unitId);
+ if (listener) {
+ this._popupMenuListeners.set(unitId, listener);
+ this._initImagePopupMenu.add(unitId);
+ }
+ }
+ }
+
+ private _disposePopupMenuListener(unitId: string) {
+ this._popupMenuListeners.get(unitId)?.dispose();
+ this._popupMenuListeners.delete(unitId);
+ this._initImagePopupMenu.delete(unitId);
+ this._clearPopups(unitId, true);
+ }
+
+ private _hasCropObject(scene: Scene) {
+ const objects = scene.getAllObjects();
+
+ for (const object of objects) {
+ if (object instanceof ImageCropperObject) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private _handleClearControl(
+ unitId: string,
+ transformer: ReturnType<Scene['getTransformerByCreate']>,
+ changeSelf: boolean
+ ): void {
+ this._clearPopups(unitId, changeSelf);
+ queueMicrotask(() => {
+ if (transformer.getSelectedObjectMap().size > 0) {
+ return;
+ }
+ this._contextService.setContextValue(FOCUSING_COMMON_DRAWINGS, false);
+ this._drawingManagerService.focusDrawing(null);
+ });
+ }
+
+ private _registerDrawingPopup(
+ unitId: string,
+ popup: INeedCheckDisposable,
+ drawing: IDrawingPopupTarget
+ ): void {
+ this.disposeWithMe(popup);
+ this._getDisposePopups(unitId).push(popup);
+ this._popupTargetsByUnit.set(unitId, drawing);
+
+ const focusDrawings = this._drawingManagerService.getFocusDrawings();
+ const alreadyFocused = focusDrawings.find((focusedDrawing) =>
+ focusedDrawing.unitId === drawing.unitId &&
+ focusedDrawing.subUnitId === drawing.subUnitId &&
+ focusedDrawing.drawingId === drawing.drawingId
+ );
+ if (!alreadyFocused) {
+ this._drawingManagerService.focusDrawing([drawing]);
+ }
+ }
+
+ private _isSamePopupTarget(previous: IDrawingPopupTarget | undefined, next: IDrawingPopupTarget): boolean {
+ return previous?.unitId === next.unitId &&
+ previous.subUnitId === next.subUnitId &&
+ previous.drawingId === next.drawingId;
+ }
+
+ // eslint-disable-next-line max-lines-per-function
+ private _popupMenuListener(unitId: string): IDisposable | undefined {
+ const scene = this._renderManagerService.getRenderUnitById(unitId)?.scene;
+ if (!scene) {
+ return;
+ }
+ const transformer = scene.getTransformerByCreate();
+
+ const subscriptions = [
+ // eslint-disable-next-line max-lines-per-function
+ transformer.createControl$.subscribe(() => {
+ if (this._hasCropObject(scene)) {
+ this._clearPopups(unitId, true);
+ return;
+ }
+
+ const selectedObjects = transformer.getSelectedObjectMap();
+ if (this._isDrawingPanelOpen || selectedObjects.size > 1) {
+ this._clearPopups(unitId, this._isDrawingPanelOpen);
+ return;
+ }
+
+ const object = selectedObjects.values().next().value as Nullable<BaseObject>;
+ if (!object) {
+ this._clearPopups(unitId);
+ return;
+ }
+
+ const drawingParam = this._drawingManagerService.getDrawingOKey(object.oKey);
+ if (
+ !drawingParam ||
+ drawingParam.drawingType === DrawingTypeEnum.DRAWING_DOM ||
+ drawingParam.drawingType === DrawingTypeEnum.DRAWING_SHAPE
+ ) {
+ this._clearPopups(unitId);
+ return;
+ }
+
+ const { unitId: drawingUnitId, subUnitId, drawingId, drawingType } = drawingParam;
+ if (!this._canEditDrawing(drawingUnitId, drawingId)) {
+ this._clearPopups(unitId, true);
+ return;
+ }
+ const disposePopups = this._disposePopupsByUnit.get(unitId);
+ const previousPopupTarget = this._popupTargetsByUnit.get(unitId);
+ const popupTarget = { unitId: drawingUnitId, subUnitId, drawingId };
+ if (this._isSamePopupTarget(previousPopupTarget, popupTarget) && disposePopups && disposePopups.length > 0) {
+ return;
+ }
+
+ this._clearPopups(unitId, previousPopupTarget != null);
+ const isImage = drawingType === DrawingTypeEnum.DRAWING_IMAGE;
+ // Charts use the document toolbar placement, while retaining chart-specific actions and controls.
+ const isChart = drawingType === DrawingTypeEnum.DRAWING_CHART;
+ const popup = this._canvasPopManagerService.attachPopupToObject(
+ object,
+ {
+ componentKey: isImage || isChart ? COMPONENT_MOBILE_IMAGE_POPUP_MENU : MOBILE_DOC_ELEMENT_MENU,
+ requiresStableLayout: false,
+ direction: isImage || isChart ? 'top-center' : 'horizontal',
+ offset: isImage || isChart ? [0, 8] : [2, 0],
+ extraProps: {
+ onClose: () => this._clearPopups(unitId, true),
+ onEdit: () => {
+ const drawing = this._docDrawingService.getDrawingByParam(drawingParam);
+ const edit = drawing && this._drawingAdapterService.getEditDrawingCommandInfo({
+ unitId: drawingUnitId,
+ subUnitId,
+ drawing,
+ });
+ this._clearPopups(unitId, true);
+ return this._commandService.executeCommand(edit?.commandId ?? EditDocDrawingOperation.id, edit?.commandParams ?? { unitId: drawingUnitId, subUnitId, drawingId });
+ },
+ onDelete: () => {
+ this._clearPopups(unitId, true);
+ return this._commandService.executeCommand(RemoveDocDrawingCommand.id, {
+ unitId: drawingUnitId,
+ drawings: [{ unitId: drawingUnitId, subUnitId, drawingId }],
+ });
+ },
+ menuItems: this._getDrawingPopupMenuItems(drawingUnitId, subUnitId, drawingId, drawingType),
+ variant: isImage ? 'doc-floating-toolbar' : isChart ? 'doc-chart-floating-toolbar' : undefined,
+ unitId: drawingUnitId,
+ subUnitId,
+ drawingId,
+ },
+ },
+ drawingUnitId
+ );
+
+ this._registerDrawingPopup(unitId, popup, { unitId: drawingUnitId, subUnitId, drawingId });
+ }),
+ transformer.clearControl$.subscribe((changeSelf) => this._handleClearControl(unitId, transformer, changeSelf)),
+ transformer.changing$.subscribe(() => {
+ this._clearPopups(unitId, true);
+ }),
+ ];
+ const disposable = toDisposable(() => subscriptions.forEach((subscription) => subscription.unsubscribe()));
+ this.disposeWithMe(disposable);
+ return disposable;
+ }
+
+ private _canEditDrawing(unitId: string, drawingId: string): boolean {
+ const documentDataModel = this._univerInstanceService.getUnit<DocumentDataModel>(
+ unitId,
+ UniverInstanceType.UNIVER_DOC
+ );
+ if (!documentDataModel) {
+ return false;
+ }
+ const segmentId = getDocumentDrawingSegmentId(documentDataModel, drawingId);
+ return canEditDocumentTargets(this._permissionService, unitId, [
+ ...getDocumentEntityParentPermissionObjectIds(documentDataModel, segmentId, 'drawing', drawingId),
+ getDocumentEntityPermissionObjectId(segmentId, 'drawing', drawingId),
+ ]);
+ }
+
+ private _getDrawingPopupMenuItems(unitId: string, subUnitId: string, drawingId: string, drawingType: number) {
+ const drawing = this._docDrawingService.getDrawingByParam({ unitId, subUnitId, drawingId });
+ const floatingToolbarMenuItems = drawing
+ ? this._floatingToolbarAdapterService.getItems({ unitId, subUnitId, drawing })
+ : null;
+ const editCommandInfo = drawing
+ ? this._drawingAdapterService.getEditDrawingCommandInfo({ unitId, subUnitId, drawing })
+ : null;
+
+ const defaultItems = [
+ {
+ label: editCommandInfo?.label ?? 'docs-drawing-ui.image-popup.edit',
+ index: 0,
+ commandId: editCommandInfo?.commandId ?? EditDocDrawingOperation.id,
+ commandParams: editCommandInfo?.commandParams ?? { unitId, subUnitId, drawingId },
+ disable: editCommandInfo?.disable ?? drawingType === DrawingTypeEnum.DRAWING_DOM,
+ hideOnClick: true,
+ icon: 'DrawingEditIcon',
+ },
+ {
+ label: 'docs-drawing-ui.image-popup.crop',
+ index: 1,
+ commandId: OpenImageCropOperation.id,
+ commandParams: { unitId, subUnitId, drawingId },
+ disable: drawingType === DrawingTypeEnum.DRAWING_DOM,
+ icon: 'DrawingCropIcon',
+ },
+ {
+ label: 'docs-drawing-ui.image-popup.delete',
+ index: 2,
+ commandId: RemoveDocDrawingCommand.id,
+ commandParams: { unitId, drawings: [{ unitId, subUnitId, drawingId }] },
+ disable: false,
+ icon: 'DrawingDeleteIcon',
+ },
+ {
+ label: 'docs-drawing-ui.image-popup.reset',
+ index: 3,
+ commandId: ImageResetSizeOperation.id,
+ commandParams: [{ unitId, subUnitId, drawingId }],
+ disable: true, // TODO: @JOCS, feature is not ready.
+ },
+ ];
+
+ if (drawingType === DrawingTypeEnum.DRAWING_IMAGE) {
+ return defaultItems.slice(0, 3);
+ }
+ if (drawingType === DrawingTypeEnum.DRAWING_CHART) {
+ return [{ ...defaultItems[0], label: 'docs-drawing-ui.image-popup.edit' }, defaultItems[2]];
+ }
+ return [...(floatingToolbarMenuItems ?? defaultItems), ...this._getFloatingObjectMenuItems()];
+ }
+
+ private _getFloatingObjectMenuItems() {
+ return this._menuManagerService
+ .getFlatMenuByPositionKey(FloatingObjectToolbarPosition.DOC)
+ .flatMap(({ item }, index) => {
+ if (!item || item.type !== MenuItemType.BUTTON || !item.title || typeof item.icon !== 'string') {
+ return [];
+ }
+
+ return [{
+ type: 'button' as const,
+ label: item.title,
+ index: 100 + index,
+ commandId: item.commandId ?? item.id,
+ commandParams: typeof item.params === 'function' ? item.params() : item.params,
+ disable: false,
+ icon: item.icon,
+ }];
+ });
+ }
+}
diff --git a/packages/docs-drawing-ui/src/controllers/mobile/ui.controller.ts b/packages/docs-drawing-ui/src/controllers/mobile/ui.controller.ts
new file mode 100644
index 0000000000..c7f01c12da
--- /dev/null
+++ b/packages/docs-drawing-ui/src/controllers/mobile/ui.controller.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 { Disposable, ICommandService } from '@univerjs/core';
+import { IMenuManagerService } from '@univerjs/ui';
+import { DeleteDocDrawingsCommand } from '../../commands/commands/delete-doc-drawing.command';
+import { GroupDocDrawingCommand } from '../../commands/commands/group-doc-drawing.command';
+import { InsertDocImageCommand } from '../../commands/commands/insert-image.command';
+import { InsertDocEllipseShapeCommand, InsertDocRectangleShapeCommand } from '../../commands/commands/insert-shape.command';
+import { MoveDocDrawingsCommand } from '../../commands/commands/move-drawings.command';
+import { UngroupDocDrawingCommand } from '../../commands/commands/ungroup-doc-drawing.command';
+import {
+ IMoveInlineDrawingCommand,
+ ITransformNonInlineDrawingCommand,
+ UpdateDocDrawingDistanceCommand,
+ UpdateDocDrawingWrapTextCommand,
+} from '../../commands/commands/update-doc-drawing.command';
+import { ClearDocDrawingTransformerOperation } from '../../commands/operations/clear-drawing-transformer.operation';
+import { EditDocDrawingOperation } from '../../commands/operations/edit-doc-drawing.operation';
+import { SidebarDocDrawingMobileOperation } from '../../commands/operations/mobile/open-drawing-panel.operation';
+import { menuSchema } from '../../menu/schema';
+
+export class MobileDocDrawingUIController extends Disposable {
+ constructor(
+ @IMenuManagerService private readonly _menuManagerService: IMenuManagerService,
+ @ICommandService private readonly _commandService: ICommandService
+ ) {
+ super();
+
+ this._initCommands();
+ this._initMenus();
+ }
+
+ private _initCommands(): void {
+ [
+ InsertDocImageCommand,
+ InsertDocRectangleShapeCommand,
+ InsertDocEllipseShapeCommand,
+ UpdateDocDrawingDistanceCommand,
+ UpdateDocDrawingWrapTextCommand,
+ IMoveInlineDrawingCommand,
+ ITransformNonInlineDrawingCommand,
+ SidebarDocDrawingMobileOperation,
+ ClearDocDrawingTransformerOperation,
+ EditDocDrawingOperation,
+ GroupDocDrawingCommand,
+ UngroupDocDrawingCommand,
+ MoveDocDrawingsCommand,
+ DeleteDocDrawingsCommand,
+ ].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));
+ }
+
+ private _initMenus(): void {
+ this._menuManagerService.mergeMenu(menuSchema);
+ }
+}
diff --git a/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-update.render-controller.spec.ts b/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-update.render-controller.spec.ts
index 4c0e737311..4cb6085541 100644
--- a/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-update.render-controller.spec.ts
+++ b/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-update.render-controller.spec.ts
@@ -14,21 +14,27 @@
* limitations under the License.
*/
-import { BooleanNumber, DrawingTypeEnum, FOCUSING_COMMON_DRAWINGS, ObjectRelativeFromH, ObjectRelativeFromV, PermissionService, PositionedObjectLayoutType } from '@univerjs/core';
-import { RichTextEditingMutation, setDocumentPermissionValue } from '@univerjs/docs';
-import { SetDocDrawingArrangeCommand, UpdateDrawingDocTransformCommand } from '@univerjs/docs-drawing';
-import { DocumentEditArea } from '@univerjs/engine-render';
+import { BooleanNumber, DrawingTypeEnum, FOCUSING_COMMON_DRAWINGS, ICommandService, IContextService, IImageIoService, Injector, IPermissionService, LocaleService, ObjectRelativeFromH, ObjectRelativeFromV, PermissionService, PositionedObjectLayoutType } from '@univerjs/core';
+import { DocSelectionManagerService, RichTextEditingMutation, setDocumentPermissionValue } from '@univerjs/docs';
+import { IDocDrawingService, SetDocDrawingArrangeCommand, UpdateDrawingDocTransformCommand } from '@univerjs/docs-drawing';
+import { DocSelectionRenderService } from '@univerjs/docs-ui';
+import { IDrawingManagerService } from '@univerjs/drawing';
+import { DocumentEditArea, IRenderManagerService } from '@univerjs/engine-render';
import { UnitAction } from '@univerjs/protocol';
+import { ILocalFileService, IMessageService } from '@univerjs/ui';
import { Subject } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
import { GroupDocDrawingCommand } from '../../../commands/commands/group-doc-drawing.command';
import { UngroupDocDrawingCommand } from '../../../commands/commands/ungroup-doc-drawing.command';
+import { DocRefreshDrawingsService } from '../../../services/doc-refresh-drawings.service';
import { DocDrawingUpdateRenderController } from '../doc-drawing-update.render-controller';
+import { MobileDocDrawingUpdateRenderController } from '../mobile/doc-drawing-update.render-controller';
function createController(options: {
editArea?: DocumentEditArea;
drawings?: Record<string, unknown>;
isFocusing?: boolean;
+ mobile?: boolean;
openFile?: () => Promise<File[]>;
saveImage?: (file: File) => Promise<unknown>;
} = {}) {
@@ -169,6 +175,7 @@ function createController(options: {
getFocusDrawings: vi.fn(() => focusDrawings),
};
const contextService = {
+ getContextValue: vi.fn(() => false),
setContextValue: vi.fn(),
};
const docSelectionRenderService = {
@@ -190,22 +197,25 @@ function createController(options: {
openFile: vi.fn(options.openFile ?? (async () => [])),
};
- const permissionService = new PermissionService();
- const controller = new DocDrawingUpdateRenderController(
- context as never,
- commandService as never,
- docSelectionManagerService as never,
- renderManagerSrv as never,
- imageIoService as never,
- docDrawingService as never,
- drawingManagerService as never,
- permissionService,
- contextService as never,
- { show: vi.fn() } as never,
- { t: vi.fn((key: string) => key) } as never,
- docSelectionRenderService as never,
- { refreshDrawings$ } as never,
- fileOpenerService as never
+ const injector = new Injector([
+ [IPermissionService, { useClass: PermissionService }],
+ [ICommandService, { useValue: commandService }],
+ [DocSelectionManagerService, { useValue: docSelectionManagerService }],
+ [IRenderManagerService, { useValue: renderManagerSrv }],
+ [IImageIoService, { useValue: imageIoService }],
+ [IDocDrawingService, { useValue: docDrawingService }],
+ [IDrawingManagerService, { useValue: drawingManagerService }],
+ [IContextService, { useValue: contextService }],
+ [IMessageService, { useValue: { show: vi.fn() } }],
+ [LocaleService],
+ [DocSelectionRenderService, { useValue: docSelectionRenderService }],
+ [DocRefreshDrawingsService, { useValue: { refreshDrawings$ } }],
+ [ILocalFileService, { useValue: fileOpenerService }],
+ ]);
+ const permissionService = injector.get(IPermissionService);
+ const controller = injector.createInstance(
+ options.mobile ? MobileDocDrawingUpdateRenderController : DocDrawingUpdateRenderController,
+ context as never
);
return {
@@ -404,6 +414,12 @@ describe('DocDrawingUpdateRenderController', () => {
vi.useRealTimers();
});
+ it.each([false, true])('configures selection-first movement for mobile mode %s', (mobile) => {
+ const { transformer } = createController({ mobile });
+
+ expect(transformer.resetProps).toHaveBeenCalledWith({ moveOnlyWhenSelected: mobile });
+ });
+
it('cancels an image insertion when the render controller is disposed while saving', async () => {
let finishSaving: (value: unknown) => void = () => {};
const saveImage = vi.fn(() => new Promise<unknown>((resolve) => {
diff --git a/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-crop.ts b/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-crop.ts
index 7d76559e84..33ff8cc017 100644
--- a/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-crop.ts
+++ b/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-crop.ts
@@ -14,27 +14,30 @@
* limitations under the License.
*/
+import type { IDrawingParam } from '@univerjs/core';
import type { IDocDrawing, IDrawingDocTransform } from '@univerjs/docs-drawing';
import type { IImageData } from '@univerjs/drawing';
import { BooleanNumber, DrawingTypeEnum, PositionedObjectLayoutType } from '@univerjs/core';
export function getDocImageCropUpdates(
- param: IImageData,
+ param: IDrawingParam & Partial<IImageData>,
docDrawing: IDocDrawing | undefined,
- renderDrawing: IImageData | undefined | null
+ renderDrawing: IDrawingParam | undefined | null
): IDrawingDocTransform[] {
const { drawingId, transform } = param;
- // Transformer updates also carry an undefined srcRect for uncropped images.
- // Their size is already persisted by the document transformer controller.
- if (transform == null || param.srcRect === undefined) {
- return [];
- }
-
if (docDrawing?.drawingType !== DrawingTypeEnum.DRAWING_IMAGE || renderDrawing?.transform == null) {
return [];
}
+ const shapeKeys: Array<'prstGeom' | 'adjustValues'> = ['prstGeom', 'adjustValues'];
+ const drawings: IDrawingDocTransform[] = shapeKeys
+ .filter((key) => Object.prototype.hasOwnProperty.call(param, key))
+ .map((key) => ({ drawingId, key, value: param[key] ?? null }));
+ // Transformer updates without crop data already persist size through the transformer controller.
+ if (transform == null || param.srcRect === undefined) {
+ return drawings;
+ }
const nextTransform = { ...renderDrawing.transform, ...transform };
- const drawings: IDrawingDocTransform[] = [{ drawingId, key: 'srcRect', value: param.srcRect }];
+ drawings.push({ drawingId, key: 'srcRect', value: param.srcRect });
if (nextTransform.width != null && nextTransform.height != null) {
drawings.push({
diff --git a/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-update.render-controller.ts b/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-update.render-controller.ts
index 76daf12c8a..5f90880732 100644
--- a/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-update.render-controller.ts
+++ b/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-update.render-controller.ts
@@ -17,7 +17,6 @@
import type { DocumentDataModel, ICommandInfo, IDocDrawingPosition, IDrawingParam, IImageIoServiceParam, ITextRangeParam, Nullable } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { IDocDrawing, IDrawingDocTransform, IInsertDocDrawingCommandParams, ISetDocDrawingArrangeCommandParams, IUpdateDrawingDocTransformCommandParams } from '@univerjs/docs-drawing';
-import type { IImageData } from '@univerjs/drawing';
import type { BaseObject, Documents, Image, IRenderContext, IRenderModule, ITransformerConfig } from '@univerjs/engine-render';
import type { LocaleKey } from '../../locale/types';
import {
@@ -331,7 +330,7 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen
private _updateImageCropListener() {
this.disposeWithMe(
this._drawingManagerService.featurePluginUpdate$.subscribe((params) => {
- const drawings = (params as IImageData[]).flatMap((param) => this._getImageCropUpdates(param));
+ const drawings = params.flatMap((param) => this._getImageCropUpdates(param));
if (drawings.length > 0) {
const { unitId } = this._context;
@@ -345,7 +344,7 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen
);
}
- private _getImageCropUpdates(param: IImageData): IDrawingDocTransform[] {
+ private _getImageCropUpdates(param: IDrawingParam): IDrawingDocTransform[] {
const { unitId, subUnitId, drawingId } = param;
if ([unitId, subUnitId].some((id) => id !== this._context.unitId)) {
return [];
@@ -353,7 +352,7 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen
return getDocImageCropUpdates(
param,
this._getDocDrawing(drawingId),
- this._drawingManagerService.getDrawingByParam({ unitId, subUnitId, drawingId }) as IImageData | undefined
+ this._drawingManagerService.getDrawingByParam({ unitId, subUnitId, drawingId }) ?? undefined
);
}
@@ -389,9 +388,19 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen
return { scene, transformer, docsLeft, docsTop };
}
+ protected _getTransformerInteractionOptions(): ITransformerConfig {
+ return { moveOnlyWhenSelected: false };
+ }
+
+ protected _isDocumentInteractionFocusing(unitId: string): boolean {
+ return this._docSelectionRenderService.isFocusing
+ || this._drawingManagerService.getFocusDrawings().some((drawing) => drawing.unitId === unitId);
+ }
+
private _transformDrawingListener() {
const res = this._getCurrentSceneAndTransformer();
if (res && res.transformer) {
+ res.transformer.resetProps(this._getTransformerInteractionOptions());
this.disposeWithMe(res.transformer.changeEnd$.pipe(debounceTime(30)).subscribe(() => {
this._docSelectionManagerService.refreshSelection();
}));
@@ -455,8 +464,7 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen
const snapshot = docDataModel.getSnapshot();
const { drawings } = collectDocDrawings(snapshot);
const isEditBody = viewModel.getEditArea() === DocumentEditArea.BODY;
- const isDocInteractionFocusing = this._docSelectionRenderService.isFocusing
- || this._drawingManagerService.getFocusDrawings().some((drawing) => drawing.unitId === unitId);
+ const isDocInteractionFocusing = this._isDocumentInteractionFocusing(unitId);
const contextKey = `${viewModel.getEditArea()}:${isDocInteractionFocusing}`;
const effectiveDrawingIds = drawingIds != null && contextKey === this._lastEditStatusContextKey
? drawingIds
diff --git a/packages/docs-drawing-ui/src/controllers/render-controllers/mobile/doc-drawing-update.render-controller.ts b/packages/docs-drawing-ui/src/controllers/render-controllers/mobile/doc-drawing-update.render-controller.ts
new file mode 100644
index 0000000000..9b54f6fa01
--- /dev/null
+++ b/packages/docs-drawing-ui/src/controllers/render-controllers/mobile/doc-drawing-update.render-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 { DocDrawingUpdateRenderController } from '../doc-drawing-update.render-controller';
+
+export class MobileDocDrawingUpdateRenderController extends DocDrawingUpdateRenderController {
+ protected override _getTransformerInteractionOptions() {
+ return { moveOnlyWhenSelected: true };
+ }
+
+ protected override _isDocumentInteractionFocusing(_unitId: string): boolean {
+ return true;
+ }
+}
diff --git a/packages/docs-drawing-ui/src/index.ts b/packages/docs-drawing-ui/src/index.ts
index 2359fcb308..cc1cff0bb3 100644
--- a/packages/docs-drawing-ui/src/index.ts
+++ b/packages/docs-drawing-ui/src/index.ts
@@ -30,6 +30,7 @@ export { DocFloatDomController } from './controllers/doc-float-dom.controller';
export { DOCS_IMAGE_MENU_ID } from './menu/image.menu';
export { menuSchema as DocsDrawingUIMenuSchema } from './menu/schema';
export { DOCS_SHAPE_BELOW_MENU_ID, DOCS_SHAPE_MENU_ID } from './menu/shape.menu';
+export { UniverDocsDrawingMobileUIPlugin } from './mobile-plugin';
export { UniverDocsDrawingUIPlugin } from './plugin';
export { DocDrawingFloatingToolbarAdapterService } from './services/doc-drawing-floating-toolbar-adapter.service';
export type {
@@ -42,3 +43,5 @@ export type {
} from './services/doc-drawing-floating-toolbar-adapter.service';
export { DocDrawingPosition } from './views/doc-image-panel/DocDrawingPosition';
export { DocDrawingTextWrap } from './views/doc-image-panel/DocDrawingTextWrap';
+export { MobileDocDrawingPosition } from './views/doc-image-panel/MobileDocDrawingPosition';
+export { MobileDocDrawingTextWrap } from './views/doc-image-panel/MobileDocDrawingTextWrap';
diff --git a/packages/docs-drawing-ui/src/menu/__tests__/drawing-popup-menu.controller.spec.ts b/packages/docs-drawing-ui/src/menu/__tests__/drawing-popup-menu.controller.spec.ts
index fcd899a6b8..84f5b66986 100644
--- a/packages/docs-drawing-ui/src/menu/__tests__/drawing-popup-menu.controller.spec.ts
+++ b/packages/docs-drawing-ui/src/menu/__tests__/drawing-popup-menu.controller.spec.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { IDrawingSearch } from '@univerjs/core';
import {
ContextService,
DocumentDataModel,
@@ -27,19 +28,22 @@ import {
toDisposable,
} from '@univerjs/core';
import { setDocumentPermissionValue } from '@univerjs/docs';
-import { IDocDrawingAdapterService } from '@univerjs/docs-drawing';
-import { DocCanvasPopManagerService } from '@univerjs/docs-ui';
+import { DocDrawingService, IDocDrawingAdapterService, IDocDrawingService, RemoveDocDrawingCommand } from '@univerjs/docs-drawing';
+import { DocCanvasPopManagerService, MOBILE_DOC_ELEMENT_MENU } from '@univerjs/docs-ui';
import { IDrawingManagerService } from '@univerjs/drawing';
+import { COMPONENT_MOBILE_IMAGE_POPUP_MENU, OpenImageCropOperation } from '@univerjs/drawing-ui';
import { IRenderManagerService } from '@univerjs/engine-render';
import { UnitAction } from '@univerjs/protocol';
import { IMenuManagerService } from '@univerjs/ui';
import { Subject } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
+import { EditDocDrawingOperation } from '../../commands/operations/edit-doc-drawing.operation';
+import { MobileDocDrawingPopupMenuController } from '../../controllers/mobile/drawing-popup-menu.controller';
import { DocDrawingFloatingToolbarAdapterService } from '../../services/doc-drawing-floating-toolbar-adapter.service';
import { DocDrawingPopupMenuController } from '../drawing-popup-menu.controller';
-function createControllerHarness() {
+function createControllerHarness(drawingType = DrawingTypeEnum.DRAWING_IMAGE, mobile = false) {
const unitId = 'doc-1';
const drawingId = 'drawing-1';
const injector = new Injector();
@@ -47,6 +51,7 @@ function createControllerHarness() {
const clearControl$ = new Subject<boolean>();
const changing$ = new Subject<void>();
const focus$ = new Subject<never[]>();
+ const remove$ = new Subject<IDrawingSearch[]>();
const currentDocument$ = new Subject<never>();
const disposedDocument$ = new Subject<never>();
const renderCreated$ = new Subject<never>();
@@ -61,7 +66,7 @@ function createControllerHarness() {
unitId,
subUnitId: unitId,
drawingId,
- drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ drawingType,
};
const documentDataModel = new DocumentDataModel({
id: unitId,
@@ -75,18 +80,22 @@ function createControllerHarness() {
clearControl$,
changing$,
getSelectedObjectMap: () => selectedObjects,
+ clearSelectedObjects: vi.fn(),
};
const scene = {
getAllObjects: () => [],
getTransformerByCreate: () => transformer,
};
+ const executeCommand = vi.fn();
injector.add([ICommandService, {
useValue: {
+ executeCommand,
onCommandExecuted: () => toDisposable(() => undefined),
} as never,
}]);
- injector.add([IContextService, { useValue: new ContextService() }]);
+ const contextService = new ContextService();
+ injector.add([IContextService, { useValue: contextService }]);
injector.add([IPermissionService, { useClass: PermissionService }]);
injector.add([IUniverInstanceService, {
useValue: {
@@ -108,6 +117,7 @@ function createControllerHarness() {
injector.add([IDrawingManagerService, {
useValue: {
focus$,
+ remove$,
focusDrawing: vi.fn(),
getDrawingByParam: () => drawing,
getDrawingOKey: () => drawing,
@@ -119,9 +129,11 @@ function createControllerHarness() {
getEditDrawingCommandInfo: () => null,
} as never,
}]);
+ injector.add([IDocDrawingService, { useClass: DocDrawingService }]);
+ const attachPopupToObject = vi.fn<DocCanvasPopManagerService['attachPopupToObject']>(() => popupDisposable);
injector.add([DocCanvasPopManagerService, {
useValue: {
- attachPopupToObject: () => popupDisposable,
+ attachPopupToObject,
} as never,
}]);
injector.add([IMenuManagerService, {
@@ -130,21 +142,116 @@ function createControllerHarness() {
} as never,
}]);
injector.add([DocDrawingFloatingToolbarAdapterService]);
- injector.add([DocDrawingPopupMenuController]);
+ if (mobile) {
+ injector.add([MobileDocDrawingPopupMenuController]);
+ } else {
+ injector.add([DocDrawingPopupMenuController]);
+ }
+ const controller = mobile
+ ? injector.get(MobileDocDrawingPopupMenuController)
+ : injector.get(DocDrawingPopupMenuController);
return {
clearControl$,
createControl$,
+ contextService,
+ controller,
+ executeCommand,
injector,
+ attachPopupToObject,
popupDisposable,
selectedObjects,
+ remove$,
+ transformer,
};
}
describe('DocDrawingPopupMenuController', () => {
- it('keeps an active popup during refresh and removes it after the selected drawing is deleted', () => {
- const { clearControl$, createControl$, injector, popupDisposable, selectedObjects } = createControllerHarness();
- const controller = injector.get(DocDrawingPopupMenuController);
+ it('keeps the mobile popup controller independent from the desktop controller', () => {
+ expect(MobileDocDrawingPopupMenuController.prototype).not.toBeInstanceOf(DocDrawingPopupMenuController);
+ });
+
+ it('does not expose mobile callbacks through the desktop popup', () => {
+ const harness = createControllerHarness();
+ const { controller } = harness;
+ try {
+ harness.createControl$.next();
+ const extraProps = harness.attachPopupToObject.mock.calls[0][1].extraProps;
+
+ expect(extraProps).not.toHaveProperty('onClose');
+ expect(extraProps).not.toHaveProperty('onEdit');
+ expect(extraProps).not.toHaveProperty('onDelete');
+ } finally {
+ controller.dispose();
+ harness.injector.dispose();
+ }
+ });
+
+ it('closes a mobile popup without clearing the object being edited', () => {
+ const harness = createControllerHarness(DrawingTypeEnum.DRAWING_CHART, true);
+ const { controller } = harness;
+ try {
+ harness.createControl$.next();
+ const onClose = harness.attachPopupToObject.mock.calls[0][1].extraProps?.onClose;
+ expect(onClose).toBeTypeOf('function');
+ if (typeof onClose === 'function') {
+ onClose();
+ }
+ expect(harness.popupDisposable.dispose).toHaveBeenCalledOnce();
+ expect(harness.selectedObjects.size).toBe(1);
+ expect(harness.transformer.clearSelectedObjects).not.toHaveBeenCalled();
+ } finally {
+ controller.dispose();
+ harness.injector.dispose();
+ }
+ });
+
+ it('keeps generic drawing edit and delete callbacks in the mobile controller', async () => {
+ const harness = createControllerHarness(DrawingTypeEnum.DRAWING_TABLE, true);
+ const { controller } = harness;
+ try {
+ harness.createControl$.next();
+ const popupOptions = harness.attachPopupToObject.mock.calls[0][1];
+ const extraProps = popupOptions.extraProps as typeof popupOptions.extraProps & {
+ onEdit?: () => unknown;
+ onDelete?: () => unknown;
+ };
+
+ expect(popupOptions.componentKey).toBe(MOBILE_DOC_ELEMENT_MENU);
+ await extraProps?.onEdit?.();
+ expect(harness.executeCommand).toHaveBeenCalledWith(EditDocDrawingOperation.id, {
+ unitId: 'doc-1',
+ subUnitId: 'doc-1',
+ drawingId: 'drawing-1',
+ });
+
+ await extraProps?.onDelete?.();
+ expect(harness.executeCommand).toHaveBeenCalledWith(RemoveDocDrawingCommand.id, {
+ unitId: 'doc-1',
+ drawings: [{ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'drawing-1' }],
+ });
+ } finally {
+ controller.dispose();
+ harness.injector.dispose();
+ }
+ });
+
+ it.each([false, true])('removes the floating menu and selection handles when its drawing is deleted (mobile: %s)', (mobile) => {
+ const { controller, createControl$, injector, popupDisposable, remove$, transformer } = createControllerHarness(DrawingTypeEnum.DRAWING_IMAGE, mobile);
+ try {
+ createControl$.next();
+ remove$.next([{ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'another-drawing' }]);
+ expect(popupDisposable.dispose).not.toHaveBeenCalled();
+ remove$.next([{ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'drawing-1' }]);
+ expect(popupDisposable.dispose).toHaveBeenCalledOnce();
+ expect(transformer.clearSelectedObjects).toHaveBeenCalledOnce();
+ } finally {
+ controller.dispose();
+ injector.dispose();
+ }
+ });
+ it.each([false, true])('keeps an active popup during refresh and removes it after the selected drawing is deleted (mobile: %s)', (mobile) => {
+ const { controller, clearControl$, createControl$, injector, popupDisposable, selectedObjects } = createControllerHarness(DrawingTypeEnum.DRAWING_IMAGE, mobile);
try {
createControl$.next();
@@ -161,9 +268,8 @@ describe('DocDrawingPopupMenuController', () => {
}
});
- it('removes an active popup when document editing is revoked even if drawing focus is empty', () => {
- const { createControl$, injector, popupDisposable } = createControllerHarness();
- const controller = injector.get(DocDrawingPopupMenuController);
+ it.each([false, true])('removes an active popup when document editing is revoked even if drawing focus is empty (mobile: %s)', (mobile) => {
+ const { controller, createControl$, injector, popupDisposable } = createControllerHarness(DrawingTypeEnum.DRAWING_IMAGE, mobile);
try {
createControl$.next();
@@ -177,4 +283,55 @@ describe('DocDrawingPopupMenuController', () => {
injector.dispose();
}
});
+
+ it('uses the mobile drawing menu for images and charts', () => {
+ const imageHarness = createControllerHarness(DrawingTypeEnum.DRAWING_IMAGE, true);
+ const imageController = imageHarness.controller;
+
+ try {
+ imageHarness.createControl$.next();
+ expect(imageHarness.attachPopupToObject).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ componentKey: COMPONENT_MOBILE_IMAGE_POPUP_MENU,
+ extraProps: expect.objectContaining({
+ variant: 'doc-floating-toolbar',
+ menuItems: [
+ expect.objectContaining({ commandId: EditDocDrawingOperation.id }),
+ expect.objectContaining({ commandId: OpenImageCropOperation.id }),
+ expect.objectContaining({ commandId: RemoveDocDrawingCommand.id }),
+ ],
+ }),
+ }),
+ 'doc-1'
+ );
+ } finally {
+ imageController.dispose();
+ imageHarness.injector.dispose();
+ }
+
+ const chartHarness = createControllerHarness(DrawingTypeEnum.DRAWING_CHART, true);
+ const chartController = chartHarness.controller;
+
+ try {
+ chartHarness.createControl$.next();
+ expect(chartHarness.attachPopupToObject).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ componentKey: COMPONENT_MOBILE_IMAGE_POPUP_MENU,
+ extraProps: expect.objectContaining({
+ variant: 'doc-chart-floating-toolbar',
+ menuItems: [
+ expect.objectContaining({ commandId: EditDocDrawingOperation.id, label: 'docs-drawing-ui.image-popup.edit' }),
+ expect.objectContaining({ commandId: RemoveDocDrawingCommand.id }),
+ ],
+ }),
+ }),
+ 'doc-1'
+ );
+ } finally {
+ chartController.dispose();
+ chartHarness.injector.dispose();
+ }
+ });
});
diff --git a/packages/docs-drawing-ui/src/menu/drawing-popup-menu.controller.ts b/packages/docs-drawing-ui/src/menu/drawing-popup-menu.controller.ts
index 01b09f21db..29ed5e9d00 100644
--- a/packages/docs-drawing-ui/src/menu/drawing-popup-menu.controller.ts
+++ b/packages/docs-drawing-ui/src/menu/drawing-popup-menu.controller.ts
@@ -15,7 +15,6 @@
*/
import type { DocumentDataModel, IDisposable, INeedCheckDisposable, Nullable } from '@univerjs/core';
-import type { IDocDrawing } from '@univerjs/docs-drawing';
import type { BaseObject, Scene } from '@univerjs/engine-render';
import {
DrawingTypeEnum,
@@ -36,7 +35,7 @@ import {
getDocumentEntityParentPermissionObjectIds,
getDocumentEntityPermissionObjectId,
} from '@univerjs/docs';
-import { IDocDrawingAdapterService, RemoveDocDrawingCommand } from '@univerjs/docs-drawing';
+import { IDocDrawingAdapterService, IDocDrawingService, RemoveDocDrawingCommand } from '@univerjs/docs-drawing';
import { DocCanvasPopManagerService } from '@univerjs/docs-ui';
import { IDrawingManagerService } from '@univerjs/drawing';
import {
@@ -73,6 +72,7 @@ export class DocDrawingPopupMenuController extends RxDisposable {
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@IContextService private readonly _contextService: IContextService,
@IDocDrawingAdapterService private readonly _drawingAdapterService: IDocDrawingAdapterService,
+ @IDocDrawingService private readonly _docDrawingService: IDocDrawingService,
@Inject(DocDrawingFloatingToolbarAdapterService) private readonly _floatingToolbarAdapterService: DocDrawingFloatingToolbarAdapterService,
@ICommandService private readonly _commandService: ICommandService,
@IMenuManagerService private readonly _menuManagerService: IMenuManagerService,
@@ -83,10 +83,16 @@ export class DocDrawingPopupMenuController extends RxDisposable {
this._init();
}
+ // eslint-disable-next-line max-lines-per-function
private _init(): void {
this.disposeWithMe(
this._commandService.onCommandExecuted((command) => {
- if (command.id === EditDocDrawingOperation.id) {
+ const opensDrawingEditor = [...this._popupTargetsByUnit.values()].some((target) => {
+ const drawing = this._docDrawingService.getDrawingByParam(target);
+ const edit = drawing && this._drawingAdapterService.getEditDrawingCommandInfo({ ...target, drawing });
+ return edit?.commandId === command.id;
+ });
+ if (command.id === EditDocDrawingOperation.id || opensDrawingEditor) {
this._isDrawingPanelOpen = true;
this._clearPopups(undefined, true);
}
@@ -106,6 +112,20 @@ export class DocDrawingPopupMenuController extends RxDisposable {
}
})
);
+ this.disposeWithMe(this._drawingManagerService.remove$.subscribe((drawings) => {
+ for (const drawing of drawings) {
+ for (const [unitId, target] of this._popupTargetsByUnit) {
+ if (
+ target.unitId === drawing.unitId &&
+ target.subUnitId === drawing.subUnitId &&
+ target.drawingId === drawing.drawingId
+ ) {
+ this._clearPopups(unitId, true);
+ this._renderManagerService.getRenderUnitById(unitId)?.scene.getTransformerByCreate().clearSelectedObjects();
+ }
+ }
+ }
+ }));
this.disposeWithMe(this._permissionService.permissionPointUpdate$.subscribe(() => {
for (const [popupUnitId, drawing] of this._popupTargetsByUnit) {
if (!this._canEditDrawing(drawing.unitId, drawing.drawingId)) {
@@ -267,6 +287,7 @@ export class DocDrawingPopupMenuController extends RxDisposable {
previous.drawingId === next.drawingId;
}
+ // eslint-disable-next-line max-lines-per-function
private _popupMenuListener(unitId: string): IDisposable | undefined {
const scene = this._renderManagerService.getRenderUnitById(unitId)?.scene;
if (!scene) {
@@ -323,8 +344,6 @@ export class DocDrawingPopupMenuController extends RxDisposable {
object,
{
componentKey: COMPONENT_IMAGE_POPUP_MENU,
- // Object anchors follow transform updates. Keeping this toolbar
- // open must not suspend publication after a resize or move.
requiresStableLayout: false,
direction: isImage || isChart ? 'top-center' : 'horizontal',
offset: isImage || isChart ? [0, 8] : [2, 0],
@@ -367,7 +386,7 @@ export class DocDrawingPopupMenuController extends RxDisposable {
}
private _getDrawingPopupMenuItems(unitId: string, subUnitId: string, drawingId: string, drawingType: number) {
- const drawing = this._drawingManagerService.getDrawingByParam({ unitId, subUnitId, drawingId }) as IDocDrawing | null;
+ const drawing = this._docDrawingService.getDrawingByParam({ unitId, subUnitId, drawingId });
const floatingToolbarMenuItems = drawing
? this._floatingToolbarAdapterService.getItems({ unitId, subUnitId, drawing })
: null;
@@ -410,10 +429,7 @@ export class DocDrawingPopupMenuController extends RxDisposable {
},
];
- return [
- ...(floatingToolbarMenuItems ?? defaultItems),
- ...this._getFloatingObjectMenuItems(),
- ];
+ return [...(floatingToolbarMenuItems ?? defaultItems), ...this._getFloatingObjectMenuItems()];
}
private _getFloatingObjectMenuItems() {
diff --git a/packages/docs-drawing-ui/src/mobile-plugin.ts b/packages/docs-drawing-ui/src/mobile-plugin.ts
new file mode 100644
index 0000000000..d077e2641b
--- /dev/null
+++ b/packages/docs-drawing-ui/src/mobile-plugin.ts
@@ -0,0 +1,104 @@
+/**
+ * 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 { IUniverDocsDrawingUIConfig } from './config/config';
+import { DependentOn, IConfigService, Inject, Injector, merge, Plugin, UniverInstanceType } from '@univerjs/core';
+import { UniverDocsPlugin } from '@univerjs/docs';
+import { UniverDocsDrawingPlugin } from '@univerjs/docs-drawing';
+import { UniverDocsMobileUIPlugin } from '@univerjs/docs-ui';
+import { UniverDrawingPlugin } from '@univerjs/drawing';
+import { UniverDrawingMobileUIPlugin } from '@univerjs/drawing-ui';
+import { IRenderManagerService, UniverRenderEnginePlugin } from '@univerjs/engine-render';
+import pkg from '../package.json';
+import { defaultPluginConfig, DOCS_DRAWING_UI_PLUGIN_CONFIG_KEY, DOCS_DRAWING_UI_PLUGIN_NAME } from './config/config';
+import { DocDrawingAddRemoveController } from './controllers/doc-drawing-notification.controller';
+import { DocDrawingPrintingController } from './controllers/doc-drawing-printing.controller';
+import { DocDrawingTransformerController } from './controllers/doc-drawing-transformer-update.controller';
+import { DocFloatDomController } from './controllers/doc-float-dom.controller';
+import { MobileComponentsController } from './controllers/mobile/components.controller';
+import { MobileDocDrawingPopupMenuController } from './controllers/mobile/drawing-popup-menu.controller';
+import { MobileDocDrawingUIController } from './controllers/mobile/ui.controller';
+import { DocDrawingTransformUpdateController } from './controllers/render-controllers/doc-drawing-transform-update.controller';
+import { DocDrawingUpdateRenderController } from './controllers/render-controllers/doc-drawing-update.render-controller';
+import { MobileDocDrawingUpdateRenderController } from './controllers/render-controllers/mobile/doc-drawing-update.render-controller';
+import { DocDrawingFloatingToolbarAdapterService } from './services/doc-drawing-floating-toolbar-adapter.service';
+import { DocRefreshDrawingsService } from './services/doc-refresh-drawings.service';
+
+@DependentOn(
+ UniverDocsPlugin,
+ UniverDrawingPlugin,
+ UniverRenderEnginePlugin,
+ UniverDocsDrawingPlugin,
+ UniverDocsMobileUIPlugin,
+ UniverDrawingMobileUIPlugin
+)
+export class UniverDocsDrawingMobileUIPlugin extends Plugin {
+ static override type = UniverInstanceType.UNIVER_DOC;
+ static override pluginName = DOCS_DRAWING_UI_PLUGIN_NAME;
+ static override packageName = pkg.name;
+ static override version = pkg.version;
+
+ constructor(
+ private readonly _config: Partial<IUniverDocsDrawingUIConfig> = defaultPluginConfig,
+ @Inject(Injector) protected override _injector: Injector,
+ @IRenderManagerService private readonly _renderManagerSrv: IRenderManagerService,
+ @IConfigService private readonly _configService: IConfigService
+ ) {
+ super();
+
+ const { ...rest } = merge(
+ {},
+ defaultPluginConfig,
+ this._config
+ );
+ this._configService.setConfig(DOCS_DRAWING_UI_PLUGIN_CONFIG_KEY, rest);
+ }
+
+ override onStarting(): void {
+ const dependencies: Dependency[] = [
+ [MobileComponentsController],
+ [MobileDocDrawingUIController],
+ [MobileDocDrawingPopupMenuController],
+ [DocDrawingTransformerController],
+ [DocDrawingAddRemoveController],
+ [DocRefreshDrawingsService],
+ [DocDrawingFloatingToolbarAdapterService],
+ [DocFloatDomController],
+ [DocDrawingPrintingController],
+ ];
+
+ dependencies.forEach((dependency) => this._injector.add(dependency));
+ this._injector.get(MobileComponentsController);
+ }
+
+ override onReady(): void {
+ ([
+ [DocDrawingUpdateRenderController, { useClass: MobileDocDrawingUpdateRenderController }],
+ [DocDrawingTransformUpdateController],
+ ] as Dependency[]).forEach((m) => this._renderManagerSrv.registerRenderModule(UniverInstanceType.UNIVER_DOC, m));
+
+ this._injector.get(DocDrawingAddRemoveController);
+ this._injector.get(MobileDocDrawingUIController);
+ this._injector.get(DocDrawingTransformerController);
+ this._injector.get(DocDrawingPrintingController);
+ }
+
+ override onRendered(): void {
+ this._injector.get(MobileDocDrawingPopupMenuController);
+ this._injector.get(DocFloatDomController);
+ }
+}
diff --git a/packages/docs-drawing-ui/src/plugin.ts b/packages/docs-drawing-ui/src/plugin.ts
index f0ff923597..8c67b2490a 100644
--- a/packages/docs-drawing-ui/src/plugin.ts
+++ b/packages/docs-drawing-ui/src/plugin.ts
@@ -24,7 +24,7 @@ import { UniverDrawingPlugin } from '@univerjs/drawing';
import { UniverDrawingUIPlugin } from '@univerjs/drawing-ui';
import { IRenderManagerService, UniverRenderEnginePlugin } from '@univerjs/engine-render';
import pkg from '../package.json';
-import { defaultPluginConfig, DOCS_DRAWING_UI_PLUGIN_CONFIG_KEY } from './config/config';
+import { defaultPluginConfig, DOCS_DRAWING_UI_PLUGIN_CONFIG_KEY, DOCS_DRAWING_UI_PLUGIN_NAME } from './config/config';
import { ComponentsController } from './controllers/components.controller';
import { DocDrawingAddRemoveController } from './controllers/doc-drawing-notification.controller';
import { DocDrawingPrintingController } from './controllers/doc-drawing-printing.controller';
@@ -51,7 +51,7 @@ import { DocRefreshDrawingsService } from './services/doc-refresh-drawings.servi
)
export class UniverDocsDrawingUIPlugin extends Plugin {
static override type = UniverInstanceType.UNIVER_DOC;
- static override pluginName = 'DOC_DRAWING_UI_PLUGIN';
+ static override pluginName = DOCS_DRAWING_UI_PLUGIN_NAME;
static override packageName = pkg.name;
static override version = pkg.version;
diff --git a/packages/docs-drawing-ui/src/services/doc-drawing-floating-toolbar-adapter.service.ts b/packages/docs-drawing-ui/src/services/doc-drawing-floating-toolbar-adapter.service.ts
index d82e684b09..3adf39e09a 100644
--- a/packages/docs-drawing-ui/src/services/doc-drawing-floating-toolbar-adapter.service.ts
+++ b/packages/docs-drawing-ui/src/services/doc-drawing-floating-toolbar-adapter.service.ts
@@ -16,6 +16,7 @@
import type { IDisposable } from '@univerjs/core';
import type { IDocDrawing } from '@univerjs/docs-drawing';
+import type { IValueOption } from '@univerjs/ui';
import { toDisposable } from '@univerjs/core';
export interface IDocDrawingFloatingToolbarParams {
@@ -26,7 +27,7 @@ export interface IDocDrawingFloatingToolbarParams {
export interface IDocDrawingFloatingToolbarOption {
icon?: string;
- label: unknown;
+ label: IValueOption['label'];
value: string;
}
diff --git a/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingPosition.tsx b/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingPosition.tsx
index c1a4e88732..ae52ae32b6 100644
--- a/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingPosition.tsx
+++ b/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingPosition.tsx
@@ -14,31 +14,13 @@
* limitations under the License.
*/
-import type { DocumentDataModel, ICommandInfo, IDrawingParam, IObjectPositionH, IObjectPositionV, Nullable } from '@univerjs/core';
-import type { IDocDrawing, IUpdateDrawingDocTransformCommandParams } from '@univerjs/docs-drawing';
-import type { IDocumentSkeletonDrawing } from '@univerjs/engine-render';
+import type { IDrawingParam } from '@univerjs/core';
import type { LocaleKey } from '../../locale/types';
-import {
- DocumentFlavor,
- ICommandService,
- IUniverInstanceService,
- LocaleService,
- ObjectRelativeFromH,
- ObjectRelativeFromV,
- PositionedObjectLayoutType,
- UniverInstanceType,
-} from '@univerjs/core';
+
import { Checkbox, clsx, InputNumber, Select } from '@univerjs/design';
-import { DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';
-import { UpdateDrawingDocTransformCommand } from '@univerjs/docs-drawing';
-import { DocSelectionRenderService } from '@univerjs/docs-ui';
-import { IDrawingManagerService } from '@univerjs/drawing';
import { IRenderManagerService } from '@univerjs/engine-render';
import { useDependency } from '@univerjs/ui';
-import { useEffect, useState } from 'react';
-
-const MIN_OFFSET = -1000;
-const MAX_OFFSET = 1000;
+import { useDocDrawingPosition } from './use-doc-drawing-position';
export interface IDocDrawingPositionProps {
drawings: IDrawingParam[];
@@ -53,321 +35,7 @@ export const DocDrawingPosition = (props: IDocDrawingPositionProps) => {
};
function DocDrawingPositionContent(props: IDocDrawingPositionProps) {
- const commandService = useDependency(ICommandService);
- const localeService = useDependency(LocaleService);
- const drawingManagerService = useDependency(IDrawingManagerService);
- const renderManagerService = useDependency(IRenderManagerService);
- const univerInstanceService = useDependency(IUniverInstanceService);
-
- const { drawings } = props;
-
- const drawingParam = drawings[0] as IDocDrawing;
-
- const { unitId } = drawingParam;
-
- const documentDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
-
- const documentFlavor = documentDataModel?.getSnapshot().documentStyle.documentFlavor;
-
- const renderObject = renderManagerService.getRenderUnitById(unitId);
- const scene = renderObject!.scene!;
- const transformer = scene.getTransformerByCreate();
-
- const HORIZONTAL_RELATIVE_FROM = [{
- label: localeService.t<LocaleKey>('docs-drawing-ui.image-position.column'),
- value: String(ObjectRelativeFromH.COLUMN),
- }, {
- label: localeService.t<LocaleKey>('docs-drawing-ui.image-position.page'),
- value: String(ObjectRelativeFromH.PAGE),
- }, {
- label: localeService.t<LocaleKey>('docs-drawing-ui.image-position.margin'),
- value: String(ObjectRelativeFromH.MARGIN),
- }];
-
- const VERTICAL_RELATIVE_FROM = [{
- label: localeService.t<LocaleKey>('docs-drawing-ui.image-position.line'),
- value: String(ObjectRelativeFromV.LINE),
- disabled: documentFlavor === DocumentFlavor.MODERN,
- }, {
- label: localeService.t<LocaleKey>('docs-drawing-ui.image-position.page'),
- value: String(ObjectRelativeFromV.PAGE),
- disabled: documentFlavor === DocumentFlavor.MODERN,
- }, {
- label: localeService.t<LocaleKey>('docs-drawing-ui.image-position.margin'),
- value: String(ObjectRelativeFromV.MARGIN),
- disabled: documentFlavor === DocumentFlavor.MODERN,
- }, {
- label: localeService.t<LocaleKey>('docs-drawing-ui.image-position.paragraph'),
- value: String(ObjectRelativeFromV.PARAGRAPH),
- }];
-
- const [disabled, setDisabled] = useState(true);
- const [hPosition, setHPosition] = useState<IObjectPositionH>({
- relativeFrom: ObjectRelativeFromH.PAGE,
- posOffset: 0,
- });
- const [vPosition, setVPosition] = useState<IObjectPositionV>({
- relativeFrom: ObjectRelativeFromV.PAGE,
- posOffset: 0,
- });
- const [followTextMove, setFollowTextMove] = useState(true);
- const [showPanel, setShowPanel] = useState(true);
-
- function handlePositionChange(
- direction: 'positionH' | 'positionV',
- value: IObjectPositionH | IObjectPositionV
- ) {
- if (direction === 'positionH') {
- setHPosition(value as IObjectPositionH);
- } else {
- setVPosition(value as IObjectPositionV);
- }
-
- const focusDrawings = drawingManagerService.getFocusDrawings();
- if (focusDrawings.length === 0) {
- return;
- }
-
- const drawings = focusDrawings.map((drawing) => {
- return {
- unitId: drawing.unitId,
- subUnitId: drawing.subUnitId,
- drawingId: drawing.drawingId,
- };
- });
-
- commandService.executeCommand<IUpdateDrawingDocTransformCommandParams>(UpdateDrawingDocTransformCommand.id, {
- unitId: focusDrawings[0].unitId,
- subUnitId: focusDrawings[0].unitId,
- drawings: drawings.map((drawing) => ({
- drawingId: drawing.drawingId,
- key: direction,
- value,
- })),
- });
-
- const docSelectionRenderService = renderManagerService.getRenderUnitById(unitId)?.with(DocSelectionRenderService);
-
- if (docSelectionRenderService) {
- docSelectionRenderService.blur();
- }
-
- transformer.refreshControls();
- }
-
- function handleHorizontalRelativeFromChange(value: string) {
- const prevRelativeFrom = hPosition.relativeFrom;
- const prevPosOffset = hPosition.posOffset;
- const relativeFrom = Number(value) as ObjectRelativeFromH;
-
- if (prevRelativeFrom === relativeFrom) {
- return;
- }
-
- const focusDrawings = drawingManagerService.getFocusDrawings();
- if (focusDrawings.length === 0) {
- return;
- }
-
- const drawingId = focusDrawings[0].drawingId;
- const unitId = focusDrawings[0].unitId;
-
- let drawing: Nullable<IDocumentSkeletonDrawing> = null;
- let pageMarginLeft = 0;
- const skeleton = renderManagerService.getRenderUnitById(unitId)
- ?.with(DocSkeletonManagerService)
- .getSkeleton();
-
- const skeletonData = skeleton?.getSkeletonData();
-
- if (skeletonData == null) {
- return;
- }
-
- const { pages, skeHeaders, skeFooters } = skeletonData;
-
- for (const page of pages) {
- const { marginLeft, skeDrawings, headerId, footerId, pageWidth } = page;
-
- if (skeDrawings.has(drawingId)) {
- drawing = skeDrawings.get(drawingId);
- pageMarginLeft = marginLeft;
- break;
- }
-
- const headerPage = skeHeaders.get(headerId)?.get(pageWidth);
- if (headerPage?.skeDrawings.has(drawingId)) {
- drawing = headerPage?.skeDrawings.get(drawingId);
- pageMarginLeft = marginLeft;
- break;
- }
-
- const footerPage = skeFooters.get(footerId)?.get(pageWidth);
- if (footerPage?.skeDrawings.has(drawingId)) {
- drawing = footerPage?.skeDrawings.get(drawingId);
- pageMarginLeft = marginLeft;
- break;
- }
- }
-
- if (drawing == null) {
- return;
- }
-
- let delta = 0;
-
- if (prevRelativeFrom === ObjectRelativeFromH.COLUMN) {
- delta -= drawing.columnLeft;
- } else if (prevRelativeFrom === ObjectRelativeFromH.MARGIN) {
- delta -= pageMarginLeft;
- }
-
- if (relativeFrom === ObjectRelativeFromH.COLUMN) {
- delta += drawing.columnLeft;
- } else if (relativeFrom === ObjectRelativeFromH.MARGIN) {
- delta += pageMarginLeft;
- } else if (relativeFrom === ObjectRelativeFromH.PAGE) {
- // Do nothing.
- }
-
- const newPositionH = {
- relativeFrom,
- posOffset: (prevPosOffset ?? 0) - delta,
- };
-
- handlePositionChange('positionH', newPositionH);
- }
-
- function handleVerticalRelativeFromChange(value: string) {
- const prevRelativeFrom = vPosition.relativeFrom;
- const prevPosOffset = vPosition.posOffset;
- const relativeFrom = Number(value) as ObjectRelativeFromV;
-
- if (prevRelativeFrom === relativeFrom) {
- return;
- }
-
- const focusDrawings = drawingManagerService.getFocusDrawings();
- if (focusDrawings.length === 0) {
- return;
- }
-
- const { drawingId, unitId } = focusDrawings[0];
- const documentDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
- const skeleton = renderManagerService.getRenderUnitById(unitId)
- ?.with(DocSkeletonManagerService)
- .getSkeleton();
-
- const docSelectionRenderService = renderManagerService.getRenderUnitById(unitId)?.with(DocSelectionRenderService);
-
- const segmentId = docSelectionRenderService?.getSegment();
- const segmentPage = docSelectionRenderService?.getSegmentPage();
-
- const drawing = documentDataModel?.getSelfOrHeaderFooterModel(segmentId)?.getBody()?.customBlocks?.find((c) => c.blockId === drawingId);
-
- if (drawing == null || skeleton == null || docSelectionRenderService == null) {
- return;
- }
-
- const { startIndex } = drawing;
-
- const glyph = skeleton.findNodeByCharIndex(startIndex, segmentId, segmentPage);
- const line = glyph?.parent?.parent;
- const column = line?.parent;
- const paragraphStartLine = column?.lines.find((l) => l.paragraphIndex === line?.paragraphIndex && l.paragraphStart);
- const page = column?.parent?.parent;
-
- if (glyph == null || line == null || paragraphStartLine == null || column == null || page == null) {
- return;
- }
-
- let delta = 0;
-
- if (prevRelativeFrom === ObjectRelativeFromV.PARAGRAPH) {
- delta -= paragraphStartLine.top;
- } else if (prevRelativeFrom === ObjectRelativeFromV.LINE) {
- delta -= line.top;
- } else if (prevRelativeFrom === ObjectRelativeFromV.PAGE) {
- delta += page.marginTop;
- }
-
- if (relativeFrom === ObjectRelativeFromV.PARAGRAPH) {
- delta += paragraphStartLine.top;
- } else if (relativeFrom === ObjectRelativeFromV.LINE) {
- delta += line.top;
- } else if (relativeFrom === ObjectRelativeFromV.PAGE) {
- delta -= page.marginTop;
- }
-
- const newPositionV = {
- relativeFrom,
- posOffset: (prevPosOffset ?? 0) - delta,
- };
-
- handlePositionChange('positionV', newPositionV);
- }
-
- function updateState(drawingParam: IDrawingParam) {
- const snapshot = documentDataModel?.getSnapshot();
- const drawing = snapshot?.drawings?.[drawingParam.drawingId];
- if (drawing == null) {
- return;
- }
-
- const { layoutType } = drawing;
- const {
- positionH,
- positionV,
- } = drawing.docTransform;
-
- setHPosition(positionH);
- setVPosition(positionV);
- setDisabled(layoutType === PositionedObjectLayoutType.INLINE);
- setFollowTextMove(positionV.relativeFrom === ObjectRelativeFromV.PARAGRAPH || positionV.relativeFrom === ObjectRelativeFromV.LINE);
- }
-
- function updateFocusDrawingState() {
- const focusDrawings = drawingManagerService.getFocusDrawings();
- if (focusDrawings.length === 0) {
- return;
- }
-
- updateState(focusDrawings[0]);
- }
-
- function handleFollowTextMoveCheck(val: string | number | boolean) {
- setFollowTextMove(val as boolean);
-
- handleVerticalRelativeFromChange(val ? String(ObjectRelativeFromV.PARAGRAPH) : String(ObjectRelativeFromV.PAGE));
- }
-
- useEffect(() => {
- // Get the init focus drawing position.
- updateFocusDrawingState();
-
- // Need to update focus drawing position when focus drawing changes.
- const subscription = drawingManagerService.focus$.subscribe((drawingParams) => {
- if (drawingParams.length === 0) {
- setShowPanel(false);
- return;
- }
-
- setShowPanel(true);
- updateState(drawingParams[0]);
- });
-
- // Need to update focus drawing position when focus drawing wrap style changed or other edit which will affect the position.
- const mutationListener = commandService.onCommandExecuted(async (command: ICommandInfo) => {
- if (command.id === RichTextEditingMutation.id) {
- updateFocusDrawingState();
- }
- });
-
- return () => {
- subscription.unsubscribe();
- mutationListener.dispose();
- };
- }, []);
+ const { localeService, showPanel, disabled, hPosition, vPosition, followTextMove, HORIZONTAL_RELATIVE_FROM, VERTICAL_RELATIVE_FROM, handlePositionChange, handleHorizontalRelativeFromChange, handleVerticalRelativeFromChange, handleFollowTextMoveCheck, MIN_OFFSET, MAX_OFFSET } = useDocDrawingPosition(props);
return (
<div
@@ -408,9 +76,12 @@ function DocDrawingPositionContent(props: IDocDrawingPositionProps) {
disabled={disabled}
value={hPosition.posOffset}
onChange={(val) => {
+ if (val == null) {
+ return;
+ }
handlePositionChange('positionH', {
relativeFrom: hPosition.relativeFrom,
- posOffset: val as number,
+ posOffset: val,
});
}}
/>
@@ -450,9 +121,12 @@ function DocDrawingPositionContent(props: IDocDrawingPositionProps) {
disabled={disabled}
value={vPosition.posOffset}
onChange={(val) => {
+ if (val == null) {
+ return;
+ }
handlePositionChange('positionV', {
relativeFrom: vPosition.relativeFrom,
- posOffset: val as number,
+ posOffset: val,
});
}}
/>
diff --git a/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingTextWrap.tsx b/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingTextWrap.tsx
index 67c57cab28..271c4af68b 100644
--- a/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingTextWrap.tsx
+++ b/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingTextWrap.tsx
@@ -14,44 +14,22 @@
* limitations under the License.
*/
-import type { DocumentDataModel, ICommandInfo, IDrawingParam, Nullable } from '@univerjs/core';
-import type { IDocDrawing } from '@univerjs/docs-drawing';
+import type { IDrawingParam } from '@univerjs/core';
import type { LocaleKey } from '../../locale/types';
import {
- BooleanNumber,
- ICommandService,
- IUniverInstanceService,
- LocaleService,
- PositionedObjectLayoutType,
- UniverInstanceType,
WrapTextType,
} from '@univerjs/core';
import { clsx, InputNumber, Radio, RadioGroup } from '@univerjs/design';
-import { RichTextEditingMutation } from '@univerjs/docs';
-import { TextWrappingStyle, UpdateDocDrawingWrappingStyleCommand } from '@univerjs/docs-drawing';
-import { IDrawingManagerService } from '@univerjs/drawing';
+import { TextWrappingStyle } from '@univerjs/docs-drawing';
import { IRenderManagerService } from '@univerjs/engine-render';
import { useDependency } from '@univerjs/ui';
-import { useEffect, useState } from 'react';
-import {
- UpdateDocDrawingDistanceCommand,
- UpdateDocDrawingWrapTextCommand,
-} from '../../commands/commands/update-doc-drawing.command';
-const MIN_MARGIN = 0;
-const MAX_MARGIN = 100;
+import { useDocDrawingTextWrap } from './use-doc-drawing-text-wrap';
export interface IDocDrawingTextWrapProps {
drawings: IDrawingParam[];
}
-interface IDistToText {
- distT: number;
- distL: number;
- distB: number;
- distR: number;
-}
-
export const DocDrawingTextWrap = (props: IDocDrawingTextWrapProps) => {
const renderManagerService = useDependency(IRenderManagerService);
const drawingParam = props.drawings[0];
@@ -61,215 +39,7 @@ export const DocDrawingTextWrap = (props: IDocDrawingTextWrapProps) => {
};
function DocDrawingTextWrapContent(props: IDocDrawingTextWrapProps) {
- const commandService = useDependency(ICommandService);
- const localeService = useDependency(LocaleService);
- const drawingManagerService = useDependency(IDrawingManagerService);
- const univerInstanceService = useDependency(IUniverInstanceService);
-
- const { drawings } = props;
-
- const drawingParam = drawings[0] as IDocDrawing;
-
- const { unitId } = drawingParam;
-
- const documentDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
-
- const [disableWrapText, setDisableWrapText] = useState(true);
- const [disableDistTB, setDisableDistTB] = useState(true);
- const [disableDistLR, setDisableDistLR] = useState(true);
- const [wrappingStyle, setWrappingStyle] = useState(TextWrappingStyle.INLINE);
- const [wrapText, setWrapText] = useState('');
- const [distToText, setDistToText] = useState<IDistToText>({
- distT: 0,
- distL: 0,
- distB: 0,
- distR: 0,
- });
- const [showPanel, setShowPanel] = useState(true);
-
- function handleWrappingStyleChange(value: number | string | boolean) {
- setWrappingStyle(value as TextWrappingStyle);
-
- const focusDrawings = drawingManagerService.getFocusDrawings();
- if (focusDrawings.length === 0) {
- return;
- }
-
- const { unitId, subUnitId } = focusDrawings[0];
-
- const drawings = focusDrawings.map(({ unitId, subUnitId, drawingId }) => ({
- unitId,
- subUnitId,
- drawingId,
- }));
-
- commandService.executeCommand(UpdateDocDrawingWrappingStyleCommand.id, {
- unitId,
- subUnitId,
- drawings,
- wrappingStyle: value as TextWrappingStyle,
- });
- }
-
- function handleWrapTextChange(value: number | string | boolean) {
- setWrapText(value as string);
-
- const focusDrawings = drawingManagerService.getFocusDrawings();
- if (focusDrawings.length === 0) {
- return;
- }
-
- const drawings = focusDrawings.map((drawing) => {
- return {
- unitId: drawing.unitId,
- subUnitId: drawing.subUnitId,
- drawingId: drawing.drawingId,
- };
- });
-
- commandService.executeCommand(UpdateDocDrawingWrapTextCommand.id, {
- unitId: focusDrawings[0].unitId,
- subUnitId: focusDrawings[0].unitId,
- drawings,
- wrapText: value as WrapTextType,
- });
- }
-
- function handleDistToTextChange(value: Nullable<number>, direction: keyof IDistToText) {
- if (value == null) {
- return;
- }
-
- const newDistToText = { ...distToText, [direction]: value };
- setDistToText(newDistToText as IDistToText);
-
- const focusDrawings = drawingManagerService.getFocusDrawings();
- if (focusDrawings.length === 0) {
- return;
- }
-
- const drawings = focusDrawings.map((drawing) => {
- return {
- unitId: drawing.unitId,
- subUnitId: drawing.subUnitId,
- drawingId: drawing.drawingId,
- };
- });
-
- commandService.executeCommand(UpdateDocDrawingDistanceCommand.id, {
- unitId: focusDrawings[0].unitId,
- subUnitId: focusDrawings[0].unitId,
- drawings,
- dist: {
- [direction]: value,
- },
- });
- }
-
- function updateFocusDrawingState() {
- const focusDrawings = drawingManagerService.getFocusDrawings();
- if (focusDrawings.length === 0) {
- return;
- }
-
- updateState(focusDrawings[0]);
- }
-
- function updateState(drawingParam: IDrawingParam) {
- const drawing = documentDataModel?.getSnapshot()?.drawings?.[drawingParam.drawingId];
- if (drawing == null) {
- return;
- }
-
- const {
- distT = 0,
- distL = 0,
- distB = 0,
- distR = 0,
- layoutType = PositionedObjectLayoutType.INLINE,
- behindDoc = BooleanNumber.FALSE,
- wrapText = WrapTextType.BOTH_SIDES,
- } = drawing;
- const distToText = {
- distT,
- distL,
- distB,
- distR,
- };
-
- setDistToText(distToText);
-
- setWrapText(wrapText as unknown as string);
-
- setDisableWrapText(layoutType !== PositionedObjectLayoutType.WRAP_SQUARE);
-
- if (
- layoutType === PositionedObjectLayoutType.WRAP_NONE ||
- layoutType === PositionedObjectLayoutType.INLINE
- ) {
- setDisableDistTB(true);
- } else {
- setDisableDistTB(false);
- }
-
- if (
- layoutType === PositionedObjectLayoutType.WRAP_NONE ||
- layoutType === PositionedObjectLayoutType.INLINE ||
- layoutType === PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM
- ) {
- setDisableDistLR(true);
- } else {
- setDisableDistLR(false);
- }
-
- if (layoutType === PositionedObjectLayoutType.WRAP_NONE) {
- if (behindDoc === BooleanNumber.TRUE) {
- setWrappingStyle(TextWrappingStyle.BEHIND_TEXT);
- } else {
- setWrappingStyle(TextWrappingStyle.IN_FRONT_OF_TEXT);
- }
- } else {
- switch (layoutType) {
- case PositionedObjectLayoutType.INLINE:
- setWrappingStyle(TextWrappingStyle.INLINE);
- break;
- case PositionedObjectLayoutType.WRAP_SQUARE:
- setWrappingStyle(TextWrappingStyle.WRAP_SQUARE);
- break;
- case PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM:
- setWrappingStyle(TextWrappingStyle.WRAP_TOP_AND_BOTTOM);
- break;
- default:
- throw new Error(`Unsupported layout type: ${layoutType}`);
- }
- }
- }
-
- useEffect(() => {
- updateFocusDrawingState();
-
- const subscription = drawingManagerService.focus$.subscribe((drawingParams) => {
- if (drawingParams.length === 0) {
- setShowPanel(false);
- return;
- }
-
- setShowPanel(true);
- updateState(drawingParams[0]);
- });
-
- // Need to update focus drawing position when focus drawing wrap style changed or other edit which will affect the position.
- const mutationListener = commandService.onCommandExecuted(async (command: ICommandInfo) => {
- if (command.id === RichTextEditingMutation.id) {
- updateFocusDrawingState();
- }
- });
-
- return () => {
- subscription.unsubscribe();
- mutationListener.dispose();
- };
- }, []);
+ const { localeService, showPanel, wrappingStyle, wrapText, distToText, disableWrapText, disableDistTB, disableDistLR, handleWrappingStyleChange, handleWrapTextChange, handleDistToTextChange, MIN_MARGIN, MAX_MARGIN } = useDocDrawingTextWrap(props);
return (
<div
@@ -315,10 +85,10 @@ function DocDrawingTextWrapContent(props: IDocDrawingTextWrapProps) {
</div>
<div>
- <RadioGroup disabled={disableWrapText} value={wrapText} onChange={handleWrapTextChange} direction="horizontal">
- <Radio value={WrapTextType.BOTH_SIDES}>{localeService.t<LocaleKey>('docs-drawing-ui.image-text-wrap.bothSide')}</Radio>
- <Radio value={WrapTextType.LEFT}>{localeService.t<LocaleKey>('docs-drawing-ui.image-text-wrap.leftOnly')}</Radio>
- <Radio value={WrapTextType.RIGHT}>{localeService.t<LocaleKey>('docs-drawing-ui.image-text-wrap.rightOnly')}</Radio>
+ <RadioGroup disabled={disableWrapText} value={String(wrapText)} onChange={handleWrapTextChange} direction="horizontal">
+ <Radio value={String(WrapTextType.BOTH_SIDES)}>{localeService.t<LocaleKey>('docs-drawing-ui.image-text-wrap.bothSide')}</Radio>
+ <Radio value={String(WrapTextType.LEFT)}>{localeService.t<LocaleKey>('docs-drawing-ui.image-text-wrap.leftOnly')}</Radio>
+ <Radio value={String(WrapTextType.RIGHT)}>{localeService.t<LocaleKey>('docs-drawing-ui.image-text-wrap.rightOnly')}</Radio>
</RadioGroup>
</div>
diff --git a/packages/docs-drawing-ui/src/views/doc-image-panel/MobileDocDrawingPanel.tsx b/packages/docs-drawing-ui/src/views/doc-image-panel/MobileDocDrawingPanel.tsx
new file mode 100644
index 0000000000..1fa9880d86
--- /dev/null
+++ b/packages/docs-drawing-ui/src/views/doc-image-panel/MobileDocDrawingPanel.tsx
@@ -0,0 +1,74 @@
+/**
+ * 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 } from '@univerjs/core';
+import { MobileActionRow } from '@univerjs/design';
+import { IDrawingManagerService } from '@univerjs/drawing';
+import { DrawingCommonPanel } from '@univerjs/drawing-ui';
+import { useDependency, useObservable } from '@univerjs/ui';
+import { useState } from 'react';
+import { SidebarDocDrawingOperation } from '../../commands/operations/open-drawing-panel.operation';
+import { MobileDocDrawingPosition } from './MobileDocDrawingPosition';
+import { MobileDocDrawingTextWrap } from './MobileDocDrawingTextWrap';
+
+const tabs: { value: 'image' | 'wrap' | 'position'; label: LocaleKey }[] = [
+ { value: 'image', label: 'docs-drawing-ui.title' },
+ { value: 'wrap', label: 'docs-drawing-ui.image-text-wrap.title' },
+ { value: 'position', label: 'docs-drawing-ui.image-position.title' },
+];
+
+export function MobileDocDrawingPanel() {
+ const drawingManagerService = useDependency(IDrawingManagerService);
+ const drawings = useObservable(drawingManagerService.focus$, drawingManagerService.getFocusDrawings()) ?? [];
+ const localeService = useDependency(LocaleService);
+ const commandService = useDependency(ICommandService);
+ const [tab, setTab] = useState<'image' | 'wrap' | 'position'>('image');
+
+ return (
+ <div className="univer-flex univer-min-w-0 univer-flex-col univer-gap-4 univer-pb-2">
+ <div className="univer-grid univer-grid-cols-3 univer-gap-2" role="group">
+ {tabs.map((item) => (
+ <MobileActionRow
+ key={item.value}
+ aria-pressed={tab === item.value}
+ title={localeService.t<LocaleKey>(item.label)}
+ variant="subtle"
+ className="
+ univer-min-w-0 univer-px-2 univer-text-center univer-text-sm
+ aria-pressed:!univer-bg-primary-50 aria-pressed:!univer-text-primary-600
+ "
+ onClick={() => setTab(item.value)}
+ />
+ ))}
+ </div>
+ <div>
+ {tab === 'image' && (
+ <DrawingCommonPanel
+ drawings={drawings}
+ hasAlign={false}
+ hasCropper
+ hasGroup={false}
+ hasTransform={false}
+ onCropStart={() => commandService.executeCommand(SidebarDocDrawingOperation.id, { value: 'close' })}
+ />
+ )}
+ {tab === 'wrap' && <MobileDocDrawingTextWrap drawings={drawings} />}
+ {tab === 'position' && <MobileDocDrawingPosition drawings={drawings} />}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/docs-drawing-ui/src/views/doc-image-panel/MobileDocDrawingPosition.tsx b/packages/docs-drawing-ui/src/views/doc-image-panel/MobileDocDrawingPosition.tsx
new file mode 100644
index 0000000000..f04217a7c3
--- /dev/null
+++ b/packages/docs-drawing-ui/src/views/doc-image-panel/MobileDocDrawingPosition.tsx
@@ -0,0 +1,154 @@
+/**
+ * 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 { IObjectPositionH, IObjectPositionV } from '@univerjs/core';
+import type { LocaleKey } from '../../locale/types';
+import type { IDocDrawingPositionProps } from './DocDrawingPosition';
+import { DocumentFlavor, LocaleService } from '@univerjs/core';
+import { InputNumber, MobileActionRow } from '@univerjs/design';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { CheckMarkIcon } from '@univerjs/icons';
+import { useDependency } from '@univerjs/ui';
+import { useDocDrawingPosition } from './use-doc-drawing-position';
+
+interface IMobileDocDrawingPositionProps {
+ disabled: boolean;
+ followTextMove: boolean;
+ disableFollowTextMove: boolean;
+ hPosition: IObjectPositionH;
+ vPosition: IObjectPositionV;
+ horizontalOptions: { label: string; value: string }[];
+ verticalOptions: { label: string; value: string; disabled?: boolean }[];
+ minOffset: number;
+ maxOffset: number;
+ onHorizontalOffsetChange: (value: number) => void;
+ onVerticalOffsetChange: (value: number) => void;
+ onHorizontalReferenceChange: (value: string) => void;
+ onVerticalReferenceChange: (value: string) => void;
+ onFollowTextMoveChange: (value: boolean) => void;
+}
+
+function MobileDocDrawingPositionControls(props: IMobileDocDrawingPositionProps) {
+ const localeService = useDependency(LocaleService);
+ const axes: {
+ title: LocaleKey;
+ reference: LocaleKey;
+ position: IObjectPositionH | IObjectPositionV;
+ options: { label: string; value: string; disabled?: boolean }[];
+ onOffsetChange: (value: number) => void;
+ onReferenceChange: (value: string) => void;
+ }[] = [
+ {
+ title: 'docs-drawing-ui.image-position.horizontal',
+ reference: 'docs-drawing-ui.image-position.toTheRightOf',
+ position: props.hPosition,
+ options: props.horizontalOptions,
+ onOffsetChange: props.onHorizontalOffsetChange,
+ onReferenceChange: props.onHorizontalReferenceChange,
+ },
+ {
+ title: 'docs-drawing-ui.image-position.vertical',
+ reference: 'docs-drawing-ui.image-position.bellow',
+ position: props.vPosition,
+ options: props.verticalOptions,
+ onOffsetChange: props.onVerticalOffsetChange,
+ onReferenceChange: props.onVerticalReferenceChange,
+ },
+ ];
+
+ return (
+ <div className="univer-grid univer-gap-5">
+ {axes.map((axis) => (
+ <section key={axis.title} className="univer-grid univer-gap-3">
+ <h3 className="univer-m-0 univer-text-sm univer-font-medium">{localeService.t<LocaleKey>(axis.title)}</h3>
+ <label className="univer-grid univer-gap-2 univer-text-sm">
+ {localeService.t<LocaleKey>('docs-drawing-ui.image-position.absolutePosition')}
+ <InputNumber
+ disabled={props.disabled}
+ className="univer-h-12 univer-w-full"
+ inputClassName="[&_input]:!univer-h-12 [&_input]:!univer-text-base"
+ controls={false}
+ min={props.minOffset}
+ max={props.maxOffset}
+ precision={1}
+ value={axis.position.posOffset ?? 0}
+ onChange={(value) => {
+ if (value != null) {
+ axis.onOffsetChange(value);
+ }
+ }}
+ />
+ </label>
+ <div className="univer-grid univer-grid-cols-2 univer-gap-2" role="group" aria-label={localeService.t<LocaleKey>(axis.reference)}>
+ {axis.options.map((option) => (
+ <MobileActionRow
+ key={option.value}
+ title={option.label}
+ variant="subtle"
+ disabled={props.disabled || option.disabled}
+ aria-pressed={String(axis.position.relativeFrom) === option.value}
+ className="
+ univer-px-3 univer-text-center univer-text-sm
+ aria-pressed:!univer-bg-primary-50 aria-pressed:!univer-text-primary-600
+ "
+ onClick={() => axis.onReferenceChange(option.value)}
+ />
+ ))}
+ </div>
+ </section>
+ ))}
+ <MobileActionRow
+ role="switch"
+ title={localeService.t<LocaleKey>('docs-drawing-ui.image-position.moveObjectWithText')}
+ variant="subtle"
+ aria-checked={props.followTextMove}
+ disabled={props.disabled || props.disableFollowTextMove}
+ trailing={props.followTextMove ? <CheckMarkIcon className="univer-text-primary-600" /> : undefined}
+ onClick={() => props.onFollowTextMoveChange(!props.followTextMove)}
+ />
+ </div>
+ );
+}
+export function MobileDocDrawingPosition(props: IDocDrawingPositionProps) {
+ const renderManagerService = useDependency(IRenderManagerService);
+ const drawing = props.drawings[0];
+ return drawing && renderManagerService.getRenderUnitById(drawing.unitId)?.scene
+ ? <MobileDocDrawingPositionContent {...props} />
+ : null;
+}
+function MobileDocDrawingPositionContent(props: IDocDrawingPositionProps) {
+ const { showPanel, disabled, hPosition, vPosition, followTextMove, documentFlavor, HORIZONTAL_RELATIVE_FROM, VERTICAL_RELATIVE_FROM, handlePositionChange, handleHorizontalRelativeFromChange, handleVerticalRelativeFromChange, handleFollowTextMoveCheck, MIN_OFFSET, MAX_OFFSET } = useDocDrawingPosition(props);
+ return showPanel
+ ? (
+ <MobileDocDrawingPositionControls
+ disabled={disabled}
+ followTextMove={followTextMove}
+ disableFollowTextMove={documentFlavor === DocumentFlavor.MODERN}
+ hPosition={hPosition}
+ vPosition={vPosition}
+ horizontalOptions={HORIZONTAL_RELATIVE_FROM}
+ verticalOptions={VERTICAL_RELATIVE_FROM}
+ minOffset={MIN_OFFSET}
+ maxOffset={MAX_OFFSET}
+ onHorizontalOffsetChange={(posOffset) => handlePositionChange('positionH', { ...hPosition, posOffset })}
+ onVerticalOffsetChange={(posOffset) => handlePositionChange('positionV', { ...vPosition, posOffset })}
+ onHorizontalReferenceChange={handleHorizontalRelativeFromChange}
+ onVerticalReferenceChange={handleVerticalRelativeFromChange}
+ onFollowTextMoveChange={handleFollowTextMoveCheck}
+ />
+ )
+ : null;
+}
diff --git a/packages/docs-drawing-ui/src/views/doc-image-panel/MobileDocDrawingTextWrap.tsx b/packages/docs-drawing-ui/src/views/doc-image-panel/MobileDocDrawingTextWrap.tsx
new file mode 100644
index 0000000000..0905a8a58e
--- /dev/null
+++ b/packages/docs-drawing-ui/src/views/doc-image-panel/MobileDocDrawingTextWrap.tsx
@@ -0,0 +1,155 @@
+/**
+ * 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 { IDocDrawingBase } from '@univerjs/core';
+import type { LocaleKey } from '../../locale/types';
+import type { IDocDrawingTextWrapProps } from './DocDrawingTextWrap';
+import { LocaleService, WrapTextType } from '@univerjs/core';
+import { InputNumber, MobileActionRow } from '@univerjs/design';
+import { TextWrappingStyle } from '@univerjs/docs-drawing';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { CheckMarkIcon } from '@univerjs/icons';
+import { useDependency } from '@univerjs/ui';
+import { useDocDrawingTextWrap } from './use-doc-drawing-text-wrap';
+
+const styles: { value: TextWrappingStyle; label: LocaleKey }[] = [
+ { value: TextWrappingStyle.INLINE, label: 'docs-drawing-ui.image-text-wrap.inline' },
+ { value: TextWrappingStyle.WRAP_SQUARE, label: 'docs-drawing-ui.image-text-wrap.square' },
+ { value: TextWrappingStyle.WRAP_TOP_AND_BOTTOM, label: 'docs-drawing-ui.image-text-wrap.topAndBottom' },
+ { value: TextWrappingStyle.BEHIND_TEXT, label: 'docs-drawing-ui.image-text-wrap.behindText' },
+ { value: TextWrappingStyle.IN_FRONT_OF_TEXT, label: 'docs-drawing-ui.image-text-wrap.inFrontText' },
+];
+const sides: { value: WrapTextType; label: LocaleKey }[] = [
+ { value: WrapTextType.BOTH_SIDES, label: 'docs-drawing-ui.image-text-wrap.bothSide' },
+ { value: WrapTextType.LEFT, label: 'docs-drawing-ui.image-text-wrap.leftOnly' },
+ { value: WrapTextType.RIGHT, label: 'docs-drawing-ui.image-text-wrap.rightOnly' },
+];
+type DistanceKey = 'distT' | 'distB' | 'distL' | 'distR';
+const distances: { key: DistanceKey; label: LocaleKey }[] = [
+ { key: 'distT', label: 'docs-drawing-ui.image-text-wrap.top' },
+ { key: 'distB', label: 'docs-drawing-ui.image-text-wrap.bottom' },
+ { key: 'distL', label: 'docs-drawing-ui.image-text-wrap.left' },
+ { key: 'distR', label: 'docs-drawing-ui.image-text-wrap.right' },
+];
+
+interface IMobileDocDrawingTextWrapProps {
+ wrappingStyle: TextWrappingStyle;
+ wrapText: WrapTextType;
+ distToText: Pick<IDocDrawingBase, DistanceKey>;
+ minMargin: number;
+ maxMargin: number;
+ disableWrapText: boolean;
+ disableDistTB: boolean;
+ disableDistLR: boolean;
+ onStyleChange: (value: TextWrappingStyle) => void;
+ onWrapTextChange: (value: WrapTextType) => void;
+ onDistanceChange: (value: number | null, direction: DistanceKey) => void;
+}
+
+function MobileDocDrawingTextWrapControls(props: IMobileDocDrawingTextWrapProps) {
+ const localeService = useDependency(LocaleService);
+
+ return (
+ <div className="univer-flex univer-flex-col univer-gap-5">
+ <div
+ role="group"
+ aria-label={localeService.t<LocaleKey>('docs-drawing-ui.image-text-wrap.wrappingStyle')}
+ className="univer-grid univer-gap-2"
+ >
+ {styles.map((option) => (
+ <MobileActionRow
+ key={option.value}
+ title={localeService.t<LocaleKey>(option.label)}
+ variant="subtle"
+ aria-pressed={props.wrappingStyle === option.value}
+ className="aria-pressed:!univer-bg-primary-50 aria-pressed:!univer-text-primary-600"
+ trailing={props.wrappingStyle === option.value ? <CheckMarkIcon /> : undefined}
+ onClick={() => props.onStyleChange(option.value)}
+ />
+ ))}
+ </div>
+ {!props.disableWrapText && (
+ <section className="univer-grid univer-gap-2">
+ <h3 className="univer-m-0 univer-text-sm univer-font-medium">{localeService.t<LocaleKey>('docs-drawing-ui.image-text-wrap.wrapText')}</h3>
+ <div className="univer-grid univer-grid-cols-3 univer-gap-2">
+ {sides.map((option) => (
+ <MobileActionRow
+ key={option.value}
+ title={localeService.t<LocaleKey>(option.label)}
+ variant="subtle"
+ aria-pressed={props.wrapText === option.value}
+ className="
+ univer-px-2 univer-text-center univer-text-sm
+ aria-pressed:!univer-bg-primary-50 aria-pressed:!univer-text-primary-600
+ "
+ onClick={() => props.onWrapTextChange(option.value)}
+ />
+ ))}
+ </div>
+ </section>
+ )}
+ {(!props.disableDistTB || !props.disableDistLR) && (
+ <section className="univer-grid univer-gap-3">
+ <h3 className="univer-m-0 univer-text-sm univer-font-medium">{localeService.t<LocaleKey>('docs-drawing-ui.image-text-wrap.distanceFromText')}</h3>
+ <div className="univer-grid univer-grid-cols-2 univer-gap-3">
+ {distances.filter(({ key }) => (key === 'distT' || key === 'distB') ? !props.disableDistTB : !props.disableDistLR).map(({ key, label }) => (
+ <label key={key} className="univer-grid univer-gap-2 univer-text-sm">
+ {localeService.t<LocaleKey>(label)}
+ <InputNumber
+ className="univer-h-12 univer-w-full"
+ inputClassName="[&_input]:!univer-h-12 [&_input]:!univer-text-base"
+ controls={false}
+ min={props.minMargin}
+ max={props.maxMargin}
+ precision={1}
+ value={props.distToText[key] ?? 0}
+ onChange={(value) => props.onDistanceChange(value, key)}
+ />
+ </label>
+ ))}
+ </div>
+ </section>
+ )}
+ </div>
+ );
+}
+export function MobileDocDrawingTextWrap(props: IDocDrawingTextWrapProps) {
+ const renderManagerService = useDependency(IRenderManagerService);
+ const drawing = props.drawings[0];
+ return drawing && renderManagerService.getRenderUnitById(drawing.unitId)?.scene
+ ? <MobileDocDrawingTextWrapContent {...props} />
+ : null;
+}
+function MobileDocDrawingTextWrapContent(props: IDocDrawingTextWrapProps) {
+ const { showPanel, wrappingStyle, wrapText, distToText, disableWrapText, disableDistTB, disableDistLR, handleWrappingStyleChange, handleWrapTextChange, handleDistToTextChange, MIN_MARGIN, MAX_MARGIN } = useDocDrawingTextWrap(props);
+ return showPanel
+ ? (
+ <MobileDocDrawingTextWrapControls
+ wrappingStyle={wrappingStyle}
+ wrapText={wrapText}
+ distToText={distToText}
+ minMargin={MIN_MARGIN}
+ maxMargin={MAX_MARGIN}
+ disableWrapText={disableWrapText}
+ disableDistTB={disableDistTB}
+ disableDistLR={disableDistLR}
+ onStyleChange={handleWrappingStyleChange}
+ onWrapTextChange={handleWrapTextChange}
+ onDistanceChange={handleDistToTextChange}
+ />
+ )
+ : null;
+}
diff --git a/packages/docs-drawing-ui/src/views/doc-image-panel/__tests__/DocDrawingPosition.spec.tsx b/packages/docs-drawing-ui/src/views/doc-image-panel/__tests__/DocDrawingPosition.spec.tsx
index ae5df0e77a..410ffae8b2 100644
--- a/packages/docs-drawing-ui/src/views/doc-image-panel/__tests__/DocDrawingPosition.spec.tsx
+++ b/packages/docs-drawing-ui/src/views/doc-image-panel/__tests__/DocDrawingPosition.spec.tsx
@@ -16,7 +16,9 @@
import type { DependencyIdentifier, DocumentDataModel, ICommand, IDocumentData } from '@univerjs/core';
import type { Root } from 'react-dom/client';
+import { within } from '@testing-library/react';
import {
+ DocumentFlavor,
ICommandService,
IUniverInstanceService,
LocaleService,
@@ -27,6 +29,7 @@ import {
UniverInstanceType,
WrapTextType,
} from '@univerjs/core';
+import { ConfigProvider } from '@univerjs/design';
import { DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';
import { DocDrawingController, DocDrawingService, IDocDrawingService } from '@univerjs/docs-drawing';
import { DocSelectionRenderService } from '@univerjs/docs-ui';
@@ -39,6 +42,7 @@ import { afterEach, describe, expect, it } from 'vitest';
import { createDocUiTestBed } from '../../../__tests__/create-doc-ui-test-bed';
import locale from '../../../locale/en-US';
import { DocDrawingPosition } from '../DocDrawingPosition';
+import { MobileDocDrawingPosition } from '../MobileDocDrawingPosition';
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -209,6 +213,7 @@ function createDocData(): IDocumentData {
},
drawingsOrder: [DRAWING_ID],
documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
pageSize: {
width: 594.3,
height: 840.51,
@@ -252,13 +257,16 @@ function createPositionTestBed() {
return testBed;
}
-function renderPanel(root: Root, testBed: ReturnType<typeof createPositionTestBed>) {
+function renderPanel(root: Root, testBed: ReturnType<typeof createPositionTestBed>, mobile = false) {
+ const Panel = mobile ? MobileDocDrawingPosition : DocDrawingPosition;
const drawing = testBed.doc.getSnapshot().drawings![DRAWING_ID];
act(() => {
root.render(
<RediContext.Provider value={{ injector: testBed.injector }}>
- <DocDrawingPosition drawings={[drawing as never]} />
+ <ConfigProvider mountContainer={document.body}>
+ <Panel drawings={[drawing as never]} />
+ </ConfigProvider>
</RediContext.Provider>
);
});
@@ -310,6 +318,32 @@ describe('DocDrawingPosition', () => {
let container: HTMLDivElement | undefined;
let currentTestBed: ReturnType<typeof createPositionTestBed> | undefined;
+ it('applies mobile position options without a dropdown and keeps selected state in sync', async () => {
+ const testBed = createPositionTestBed();
+ currentTestBed = testBed;
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ renderPanel(root, testBed, true);
+ const view = within(container);
+ const marginButton = view.getAllByRole('button', { name: 'Margin' })[0];
+
+ await act(async () => marginButton.click());
+ expect(currentDrawing(testBed).docTransform.positionH).toEqual({
+ relativeFrom: ObjectRelativeFromH.MARGIN,
+ posOffset: -90,
+ });
+ expect(marginButton.getAttribute('aria-pressed')).toBe('true');
+
+ await act(async () => setInputValue(getNumberInput(container!, 0), '36.5'));
+ expect(currentDrawing(testBed).docTransform.positionH.posOffset).toBe(36.5);
+
+ const follow = view.getByRole('switch');
+ await act(async () => follow.click());
+ expect(follow.getAttribute('aria-checked')).toBe('false');
+ expect(currentDrawing(testBed).docTransform.positionV.relativeFrom).toBe(ObjectRelativeFromV.PAGE);
+ });
+
afterEach(() => {
act(() => {
root?.unmount();
diff --git a/packages/docs-drawing-ui/src/views/doc-image-panel/__tests__/DocDrawingTextWrap.spec.tsx b/packages/docs-drawing-ui/src/views/doc-image-panel/__tests__/DocDrawingTextWrap.spec.tsx
index f9db724544..7f7f6dd309 100644
--- a/packages/docs-drawing-ui/src/views/doc-image-panel/__tests__/DocDrawingTextWrap.spec.tsx
+++ b/packages/docs-drawing-ui/src/views/doc-image-panel/__tests__/DocDrawingTextWrap.spec.tsx
@@ -16,6 +16,7 @@
import type { DependencyIdentifier, DocumentDataModel, ICommand, IDocumentData } from '@univerjs/core';
import type { Root } from 'react-dom/client';
+import { within } from '@testing-library/react';
import {
BooleanNumber,
ICommandService,
@@ -28,6 +29,7 @@ import {
UniverInstanceType,
WrapTextType,
} from '@univerjs/core';
+import { ConfigProvider } from '@univerjs/design';
import { DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';
import { DocDrawingController, DocDrawingService, IDocDrawingService } from '@univerjs/docs-drawing';
import { DocSelectionRenderService } from '@univerjs/docs-ui';
@@ -46,6 +48,7 @@ import { DocDrawingAddRemoveController } from '../../../controllers/doc-drawing-
import locale from '../../../locale/en-US';
import { DocRefreshDrawingsService } from '../../../services/doc-refresh-drawings.service';
import { DocDrawingTextWrap } from '../DocDrawingTextWrap';
+import { MobileDocDrawingTextWrap } from '../MobileDocDrawingTextWrap';
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -240,13 +243,16 @@ function createPanelTestBed() {
return testBed;
}
-function renderPanel(root: Root, testBed: ReturnType<typeof createPanelTestBed>) {
+function renderPanel(root: Root, testBed: ReturnType<typeof createPanelTestBed>, mobile = false) {
+ const Panel = mobile ? MobileDocDrawingTextWrap : DocDrawingTextWrap;
const drawing = testBed.doc.getSnapshot().drawings![DRAWING_ID];
act(() => {
root.render(
<RediContext.Provider value={{ injector: testBed.injector }}>
- <DocDrawingTextWrap drawings={[drawing as never]} />
+ <ConfigProvider mountContainer={document.body}>
+ <Panel drawings={[drawing as never]} />
+ </ConfigProvider>
</RediContext.Provider>
);
});
@@ -278,6 +284,34 @@ describe('DocDrawingTextWrap', () => {
let container: HTMLDivElement | undefined;
let currentTestBed: ReturnType<typeof createPanelTestBed> | undefined;
+ it('applies mobile wrapping and distance controls and reflects the current model', async () => {
+ const testBed = createPanelTestBed();
+ currentTestBed = testBed;
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ renderPanel(root, testBed, true);
+ const view = within(container);
+
+ await act(async () => {
+ view.getByRole('button', { name: 'Right only' }).click();
+ });
+ expect(currentDrawing(testBed).wrapText).toBe(WrapTextType.RIGHT);
+ expect(view.getByRole('button', { name: 'Right only' }).getAttribute('aria-pressed')).toBe('true');
+
+ const topInput = view.getByLabelText<HTMLInputElement>('Top(px)');
+ await act(async () => setInputValue(topInput, '15'));
+ expect(currentDrawing(testBed).distT).toBe(15);
+
+ await act(async () => {
+ view.getByRole('button', { name: 'Top and Bottom' }).click();
+ });
+ expect(currentDrawing(testBed).layoutType).toBe(PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM);
+ expect(view.queryByRole('button', { name: 'Right only' })).toBeNull();
+ expect(view.queryByLabelText('Left(px)')).toBeNull();
+ expect(view.getByLabelText<HTMLInputElement>('Top(px)').value).toBe('15');
+ });
+
afterEach(() => {
act(() => {
root?.unmount();
diff --git a/packages/docs-drawing-ui/src/views/doc-image-panel/component-name.ts b/packages/docs-drawing-ui/src/views/doc-image-panel/component-name.ts
index af88f132dd..43b584e16e 100644
--- a/packages/docs-drawing-ui/src/views/doc-image-panel/component-name.ts
+++ b/packages/docs-drawing-ui/src/views/doc-image-panel/component-name.ts
@@ -15,3 +15,4 @@
*/
export const COMPONENT_DOC_DRAWING_PANEL = 'COMPONENT_DOC_DRAWING_PANEL';
+export const MOBILE_DOC_DRAWING_PANEL_DIALOG_ID = 'docs-drawing-ui.mobile-panel';
diff --git a/packages/docs-drawing-ui/src/views/doc-image-panel/use-doc-drawing-position.ts b/packages/docs-drawing-ui/src/views/doc-image-panel/use-doc-drawing-position.ts
new file mode 100644
index 0000000000..682489110c
--- /dev/null
+++ b/packages/docs-drawing-ui/src/views/doc-image-panel/use-doc-drawing-position.ts
@@ -0,0 +1,377 @@
+/**
+ * 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, ICommandInfo, IDrawingParam, IObjectPositionH, IObjectPositionV, Nullable } from '@univerjs/core';
+import type { IUpdateDrawingDocTransformCommandParams } from '@univerjs/docs-drawing';
+import type { IDocumentSkeletonDrawing } from '@univerjs/engine-render';
+import type { LocaleKey } from '../../locale/types';
+import type { IDocDrawingPositionProps } from './DocDrawingPosition';
+import {
+ DocumentFlavor,
+ ICommandService,
+ IUniverInstanceService,
+ LocaleService,
+ ObjectRelativeFromH,
+ ObjectRelativeFromV,
+ PositionedObjectLayoutType,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';
+import { UpdateDrawingDocTransformCommand } from '@univerjs/docs-drawing';
+import { DocSelectionRenderService } from '@univerjs/docs-ui';
+import { IDrawingManagerService } from '@univerjs/drawing';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { useDependency } from '@univerjs/ui';
+import { useEffect, useState } from 'react';
+
+const MIN_OFFSET = -1000;
+const MAX_OFFSET = 1000;
+
+export function useDocDrawingPosition(props: IDocDrawingPositionProps) {
+ const commandService = useDependency(ICommandService);
+ const localeService = useDependency(LocaleService);
+ const drawingManagerService = useDependency(IDrawingManagerService);
+ const renderManagerService = useDependency(IRenderManagerService);
+ const univerInstanceService = useDependency(IUniverInstanceService);
+
+ const { drawings } = props;
+
+ const drawingParam = drawings[0];
+
+ const { unitId } = drawingParam;
+
+ const documentDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
+
+ const documentFlavor = documentDataModel?.getSnapshot().documentStyle.documentFlavor;
+
+ const renderObject = renderManagerService.getRenderUnitById(unitId);
+ const scene = renderObject!.scene!;
+ const transformer = scene.getTransformerByCreate();
+
+ const HORIZONTAL_RELATIVE_FROM = [{
+ label: localeService.t<LocaleKey>('docs-drawing-ui.image-position.column'),
+ value: String(ObjectRelativeFromH.COLUMN),
+ }, {
+ label: localeService.t<LocaleKey>('docs-drawing-ui.image-position.page'),
+ value: String(ObjectRelativeFromH.PAGE),
+ }, {
+ label: localeService.t<LocaleKey>('docs-drawing-ui.image-position.margin'),
+ value: String(ObjectRelativeFromH.MARGIN),
+ }];
+
+ const VERTICAL_RELATIVE_FROM = [{
+ label: localeService.t<LocaleKey>('docs-drawing-ui.image-position.line'),
+ value: String(ObjectRelativeFromV.LINE),
+ disabled: documentFlavor === DocumentFlavor.MODERN,
+ }, {
+ label: localeService.t<LocaleKey>('docs-drawing-ui.image-position.page'),
+ value: String(ObjectRelativeFromV.PAGE),
+ disabled: documentFlavor === DocumentFlavor.MODERN,
+ }, {
+ label: localeService.t<LocaleKey>('docs-drawing-ui.image-position.margin'),
+ value: String(ObjectRelativeFromV.MARGIN),
+ disabled: documentFlavor === DocumentFlavor.MODERN,
+ }, {
+ label: localeService.t<LocaleKey>('docs-drawing-ui.image-position.paragraph'),
+ value: String(ObjectRelativeFromV.PARAGRAPH),
+ }];
+
+ const [disabled, setDisabled] = useState(true);
+ const [hPosition, setHPosition] = useState<IObjectPositionH>({
+ relativeFrom: ObjectRelativeFromH.PAGE,
+ posOffset: 0,
+ });
+ const [vPosition, setVPosition] = useState<IObjectPositionV>({
+ relativeFrom: ObjectRelativeFromV.PAGE,
+ posOffset: 0,
+ });
+ const [followTextMove, setFollowTextMove] = useState(true);
+ const [showPanel, setShowPanel] = useState(true);
+
+ function handlePositionChange(
+ direction: 'positionH' | 'positionV',
+ value: IObjectPositionH | IObjectPositionV
+ ) {
+ const focusDrawings = drawingManagerService.getFocusDrawings();
+ if (focusDrawings.length === 0) {
+ return;
+ }
+
+ const drawings = focusDrawings.map((drawing) => {
+ return {
+ unitId: drawing.unitId,
+ subUnitId: drawing.subUnitId,
+ drawingId: drawing.drawingId,
+ };
+ });
+
+ commandService.executeCommand<IUpdateDrawingDocTransformCommandParams>(UpdateDrawingDocTransformCommand.id, {
+ unitId: focusDrawings[0].unitId,
+ subUnitId: focusDrawings[0].subUnitId,
+ drawings: drawings.map((drawing) => ({
+ drawingId: drawing.drawingId,
+ key: direction,
+ value,
+ })),
+ });
+
+ const docSelectionRenderService = renderManagerService.getRenderUnitById(unitId)?.with(DocSelectionRenderService);
+
+ if (docSelectionRenderService) {
+ docSelectionRenderService.blur();
+ }
+
+ transformer.refreshControls();
+ }
+
+ function handleHorizontalRelativeFromChange(value: string) {
+ const prevRelativeFrom = hPosition.relativeFrom;
+ const prevPosOffset = hPosition.posOffset;
+ const relativeFrom = [ObjectRelativeFromH.COLUMN, ObjectRelativeFromH.PAGE, ObjectRelativeFromH.MARGIN]
+ .find((reference) => String(reference) === value);
+ if (relativeFrom == null) {
+ return;
+ }
+
+ if (prevRelativeFrom === relativeFrom) {
+ return;
+ }
+
+ const focusDrawings = drawingManagerService.getFocusDrawings();
+ if (focusDrawings.length === 0) {
+ return;
+ }
+
+ const drawingId = focusDrawings[0].drawingId;
+ const unitId = focusDrawings[0].unitId;
+
+ let drawing: Nullable<IDocumentSkeletonDrawing> = null;
+ let pageMarginLeft = 0;
+ const skeleton = renderManagerService.getRenderUnitById(unitId)
+ ?.with(DocSkeletonManagerService)
+ .getSkeleton();
+
+ const skeletonData = skeleton?.getSkeletonData();
+
+ if (skeletonData == null) {
+ return;
+ }
+
+ const { pages, skeHeaders, skeFooters } = skeletonData;
+
+ for (const page of pages) {
+ const { marginLeft, skeDrawings, headerId, footerId, pageWidth } = page;
+
+ if (skeDrawings.has(drawingId)) {
+ drawing = skeDrawings.get(drawingId);
+ pageMarginLeft = marginLeft;
+ break;
+ }
+
+ const headerPage = skeHeaders.get(headerId)?.get(pageWidth);
+ if (headerPage?.skeDrawings.has(drawingId)) {
+ drawing = headerPage?.skeDrawings.get(drawingId);
+ pageMarginLeft = marginLeft;
+ break;
+ }
+
+ const footerPage = skeFooters.get(footerId)?.get(pageWidth);
+ if (footerPage?.skeDrawings.has(drawingId)) {
+ drawing = footerPage?.skeDrawings.get(drawingId);
+ pageMarginLeft = marginLeft;
+ break;
+ }
+ }
+
+ if (drawing == null) {
+ return;
+ }
+
+ let delta = 0;
+
+ if (prevRelativeFrom === ObjectRelativeFromH.COLUMN) {
+ delta -= drawing.columnLeft;
+ } else if (prevRelativeFrom === ObjectRelativeFromH.MARGIN) {
+ delta -= pageMarginLeft;
+ }
+
+ if (relativeFrom === ObjectRelativeFromH.COLUMN) {
+ delta += drawing.columnLeft;
+ } else if (relativeFrom === ObjectRelativeFromH.MARGIN) {
+ delta += pageMarginLeft;
+ } else if (relativeFrom === ObjectRelativeFromH.PAGE) {
+ // Do nothing.
+ }
+
+ const newPositionH = {
+ relativeFrom,
+ posOffset: (prevPosOffset ?? 0) - delta,
+ };
+
+ handlePositionChange('positionH', newPositionH);
+ }
+
+ function handleVerticalRelativeFromChange(value: string) {
+ const prevRelativeFrom = vPosition.relativeFrom;
+ const prevPosOffset = vPosition.posOffset;
+ const relativeFrom = [ObjectRelativeFromV.LINE, ObjectRelativeFromV.PAGE, ObjectRelativeFromV.MARGIN, ObjectRelativeFromV.PARAGRAPH]
+ .find((reference) => String(reference) === value);
+ if (relativeFrom == null) {
+ return;
+ }
+
+ if (prevRelativeFrom === relativeFrom) {
+ return;
+ }
+
+ const focusDrawings = drawingManagerService.getFocusDrawings();
+ if (focusDrawings.length === 0) {
+ return;
+ }
+
+ const { drawingId, unitId } = focusDrawings[0];
+ const documentDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
+ const skeleton = renderManagerService.getRenderUnitById(unitId)
+ ?.with(DocSkeletonManagerService)
+ .getSkeleton();
+
+ const docSelectionRenderService = renderManagerService.getRenderUnitById(unitId)?.with(DocSelectionRenderService);
+
+ const segmentId = docSelectionRenderService?.getSegment();
+ const segmentPage = docSelectionRenderService?.getSegmentPage();
+
+ const drawing = documentDataModel?.getSelfOrHeaderFooterModel(segmentId)?.getBody()?.customBlocks?.find((c) => c.blockId === drawingId);
+
+ if (drawing == null || skeleton == null || docSelectionRenderService == null) {
+ return;
+ }
+
+ const { startIndex } = drawing;
+
+ const glyph = skeleton.findNodeByCharIndex(startIndex, segmentId, segmentPage);
+ const line = glyph?.parent?.parent;
+ const column = line?.parent;
+ const paragraphStartLine = column?.lines.find((l) => l.paragraphIndex === line?.paragraphIndex && l.paragraphStart);
+ const page = column?.parent?.parent;
+
+ if (glyph == null || line == null || paragraphStartLine == null || column == null || page == null) {
+ return;
+ }
+
+ let delta = 0;
+
+ if (prevRelativeFrom === ObjectRelativeFromV.PARAGRAPH) {
+ delta -= paragraphStartLine.top;
+ } else if (prevRelativeFrom === ObjectRelativeFromV.LINE) {
+ delta -= line.top;
+ } else if (prevRelativeFrom === ObjectRelativeFromV.PAGE) {
+ delta += page.marginTop;
+ }
+
+ if (relativeFrom === ObjectRelativeFromV.PARAGRAPH) {
+ delta += paragraphStartLine.top;
+ } else if (relativeFrom === ObjectRelativeFromV.LINE) {
+ delta += line.top;
+ } else if (relativeFrom === ObjectRelativeFromV.PAGE) {
+ delta -= page.marginTop;
+ }
+
+ const newPositionV = {
+ relativeFrom,
+ posOffset: (prevPosOffset ?? 0) - delta,
+ };
+
+ handlePositionChange('positionV', newPositionV);
+ }
+
+ function handleFollowTextMoveCheck(val: string | number | boolean) {
+ handleVerticalRelativeFromChange(val ? String(ObjectRelativeFromV.PARAGRAPH) : String(ObjectRelativeFromV.PAGE));
+ }
+
+ useEffect(() => {
+ function updateState(drawingParam: IDrawingParam) {
+ const snapshot = documentDataModel?.getSnapshot();
+ const drawing = snapshot?.drawings?.[drawingParam.drawingId];
+ if (drawing == null) {
+ return;
+ }
+
+ const { layoutType } = drawing;
+ const {
+ positionH,
+ positionV,
+ } = drawing.docTransform;
+
+ setHPosition(positionH);
+ setVPosition(positionV);
+ setDisabled(layoutType === PositionedObjectLayoutType.INLINE);
+ setFollowTextMove(positionV.relativeFrom === ObjectRelativeFromV.PARAGRAPH || positionV.relativeFrom === ObjectRelativeFromV.LINE);
+ }
+
+ function updateFocusDrawingState() {
+ const focusDrawings = drawingManagerService.getFocusDrawings();
+ if (focusDrawings.length === 0) {
+ return;
+ }
+
+ updateState(focusDrawings[0]);
+ }
+
+ // Get the init focus drawing position.
+ updateFocusDrawingState();
+
+ // Need to update focus drawing position when focus drawing changes.
+ const subscription = drawingManagerService.focus$.subscribe((drawingParams) => {
+ if (drawingParams.length === 0) {
+ setShowPanel(false);
+ return;
+ }
+
+ setShowPanel(true);
+ updateState(drawingParams[0]);
+ });
+
+ // Need to update focus drawing position when focus drawing wrap style changed or other edit which will affect the position.
+ const mutationListener = commandService.onCommandExecuted(async (command: ICommandInfo) => {
+ if (command.id === RichTextEditingMutation.id) {
+ updateFocusDrawingState();
+ }
+ });
+
+ return () => {
+ subscription.unsubscribe();
+ mutationListener.dispose();
+ };
+ }, [commandService, documentDataModel, drawingManagerService]);
+
+ return {
+ localeService,
+ showPanel,
+ disabled,
+ hPosition,
+ vPosition,
+ followTextMove,
+ documentFlavor,
+ HORIZONTAL_RELATIVE_FROM,
+ VERTICAL_RELATIVE_FROM,
+ handlePositionChange,
+ handleHorizontalRelativeFromChange,
+ handleVerticalRelativeFromChange,
+ handleFollowTextMoveCheck,
+ MIN_OFFSET,
+ MAX_OFFSET,
+ };
+}
diff --git a/packages/docs-drawing-ui/src/views/doc-image-panel/use-doc-drawing-text-wrap.ts b/packages/docs-drawing-ui/src/views/doc-image-panel/use-doc-drawing-text-wrap.ts
new file mode 100644
index 0000000000..222d10866e
--- /dev/null
+++ b/packages/docs-drawing-ui/src/views/doc-image-panel/use-doc-drawing-text-wrap.ts
@@ -0,0 +1,277 @@
+/**
+ * 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, ICommandInfo, IDrawingParam, Nullable } from '@univerjs/core';
+import type { IDocDrawingTextWrapProps } from './DocDrawingTextWrap';
+import {
+ BooleanNumber,
+ ICommandService,
+ IUniverInstanceService,
+ LocaleService,
+ PositionedObjectLayoutType,
+ UniverInstanceType,
+ WrapTextType,
+} from '@univerjs/core';
+import { RichTextEditingMutation } from '@univerjs/docs';
+import { TextWrappingStyle, UpdateDocDrawingWrappingStyleCommand } from '@univerjs/docs-drawing';
+import { IDrawingManagerService } from '@univerjs/drawing';
+import { useDependency } from '@univerjs/ui';
+import { useEffect, useState } from 'react';
+import {
+ UpdateDocDrawingDistanceCommand,
+ UpdateDocDrawingWrapTextCommand,
+} from '../../commands/commands/update-doc-drawing.command';
+
+const MIN_MARGIN = 0;
+const MAX_MARGIN = 100;
+
+interface IDistToText {
+ distT: number;
+ distL: number;
+ distB: number;
+ distR: number;
+}
+
+export function useDocDrawingTextWrap(props: IDocDrawingTextWrapProps) {
+ const commandService = useDependency(ICommandService);
+ const localeService = useDependency(LocaleService);
+ const drawingManagerService = useDependency(IDrawingManagerService);
+ const univerInstanceService = useDependency(IUniverInstanceService);
+
+ const { drawings } = props;
+
+ const drawingParam = drawings[0];
+
+ const { unitId } = drawingParam;
+
+ const documentDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
+
+ const [disableWrapText, setDisableWrapText] = useState(true);
+ const [disableDistTB, setDisableDistTB] = useState(true);
+ const [disableDistLR, setDisableDistLR] = useState(true);
+ const [wrappingStyle, setWrappingStyle] = useState(TextWrappingStyle.INLINE);
+ const [wrapText, setWrapText] = useState(WrapTextType.BOTH_SIDES);
+ const [distToText, setDistToText] = useState<IDistToText>({
+ distT: 0,
+ distL: 0,
+ distB: 0,
+ distR: 0,
+ });
+ const [showPanel, setShowPanel] = useState(true);
+
+ function handleWrappingStyleChange(value: number | string | boolean) {
+ const style = Object.values(TextWrappingStyle).find((style) => style === value);
+ if (style == null) {
+ return;
+ }
+
+ const focusDrawings = drawingManagerService.getFocusDrawings();
+ if (focusDrawings.length === 0) {
+ return;
+ }
+
+ const { unitId, subUnitId } = focusDrawings[0];
+
+ const drawings = focusDrawings.map(({ unitId, subUnitId, drawingId }) => ({
+ unitId,
+ subUnitId,
+ drawingId,
+ }));
+
+ commandService.executeCommand(UpdateDocDrawingWrappingStyleCommand.id, {
+ unitId,
+ subUnitId,
+ drawings,
+ wrappingStyle: style,
+ });
+ }
+
+ function handleWrapTextChange(value: number | string | boolean) {
+ const wrapText = [WrapTextType.BOTH_SIDES, WrapTextType.LEFT, WrapTextType.RIGHT].find((side) => String(side) === String(value));
+ if (wrapText == null) {
+ return;
+ }
+
+ const focusDrawings = drawingManagerService.getFocusDrawings();
+ if (focusDrawings.length === 0) {
+ return;
+ }
+
+ const drawings = focusDrawings.map((drawing) => {
+ return {
+ unitId: drawing.unitId,
+ subUnitId: drawing.subUnitId,
+ drawingId: drawing.drawingId,
+ };
+ });
+
+ commandService.executeCommand(UpdateDocDrawingWrapTextCommand.id, {
+ unitId: focusDrawings[0].unitId,
+ subUnitId: focusDrawings[0].subUnitId,
+ drawings,
+ wrapText,
+ });
+ }
+
+ function handleDistToTextChange(value: Nullable<number>, direction: keyof IDistToText) {
+ if (value == null) {
+ return;
+ }
+
+ const focusDrawings = drawingManagerService.getFocusDrawings();
+ if (focusDrawings.length === 0) {
+ return;
+ }
+
+ const drawings = focusDrawings.map((drawing) => {
+ return {
+ unitId: drawing.unitId,
+ subUnitId: drawing.subUnitId,
+ drawingId: drawing.drawingId,
+ };
+ });
+
+ commandService.executeCommand(UpdateDocDrawingDistanceCommand.id, {
+ unitId: focusDrawings[0].unitId,
+ subUnitId: focusDrawings[0].subUnitId,
+ drawings,
+ dist: {
+ [direction]: value,
+ },
+ });
+ }
+
+ useEffect(() => {
+ function updateFocusDrawingState() {
+ const focusDrawings = drawingManagerService.getFocusDrawings();
+ if (focusDrawings.length === 0) {
+ return;
+ }
+
+ updateState(focusDrawings[0]);
+ }
+
+ function updateState(drawingParam: IDrawingParam) {
+ const drawing = documentDataModel?.getSnapshot()?.drawings?.[drawingParam.drawingId];
+ if (drawing == null) {
+ return;
+ }
+
+ const {
+ distT = 0,
+ distL = 0,
+ distB = 0,
+ distR = 0,
+ layoutType = PositionedObjectLayoutType.INLINE,
+ behindDoc = BooleanNumber.FALSE,
+ wrapText = WrapTextType.BOTH_SIDES,
+ } = drawing;
+ const distToText = {
+ distT,
+ distL,
+ distB,
+ distR,
+ };
+
+ setDistToText(distToText);
+
+ setWrapText(wrapText);
+
+ setDisableWrapText(layoutType !== PositionedObjectLayoutType.WRAP_SQUARE);
+
+ if (
+ layoutType === PositionedObjectLayoutType.WRAP_NONE ||
+ layoutType === PositionedObjectLayoutType.INLINE
+ ) {
+ setDisableDistTB(true);
+ } else {
+ setDisableDistTB(false);
+ }
+
+ if (
+ layoutType === PositionedObjectLayoutType.WRAP_NONE ||
+ layoutType === PositionedObjectLayoutType.INLINE ||
+ layoutType === PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM
+ ) {
+ setDisableDistLR(true);
+ } else {
+ setDisableDistLR(false);
+ }
+
+ if (layoutType === PositionedObjectLayoutType.WRAP_NONE) {
+ if (behindDoc === BooleanNumber.TRUE) {
+ setWrappingStyle(TextWrappingStyle.BEHIND_TEXT);
+ } else {
+ setWrappingStyle(TextWrappingStyle.IN_FRONT_OF_TEXT);
+ }
+ } else {
+ switch (layoutType) {
+ case PositionedObjectLayoutType.INLINE:
+ setWrappingStyle(TextWrappingStyle.INLINE);
+ break;
+ case PositionedObjectLayoutType.WRAP_SQUARE:
+ setWrappingStyle(TextWrappingStyle.WRAP_SQUARE);
+ break;
+ case PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM:
+ setWrappingStyle(TextWrappingStyle.WRAP_TOP_AND_BOTTOM);
+ break;
+ default:
+ throw new Error(`Unsupported layout type: ${layoutType}`);
+ }
+ }
+ }
+
+ updateFocusDrawingState();
+
+ const subscription = drawingManagerService.focus$.subscribe((drawingParams) => {
+ if (drawingParams.length === 0) {
+ setShowPanel(false);
+ return;
+ }
+
+ setShowPanel(true);
+ updateState(drawingParams[0]);
+ });
+
+ // Need to update focus drawing position when focus drawing wrap style changed or other edit which will affect the position.
+ const mutationListener = commandService.onCommandExecuted(async (command: ICommandInfo) => {
+ if (command.id === RichTextEditingMutation.id) {
+ updateFocusDrawingState();
+ }
+ });
+
+ return () => {
+ subscription.unsubscribe();
+ mutationListener.dispose();
+ };
+ }, [commandService, documentDataModel, drawingManagerService]);
+
+ return {
+ localeService,
+ showPanel,
+ wrappingStyle,
+ wrapText,
+ distToText,
+ disableWrapText,
+ disableDistTB,
+ disableDistLR,
+ handleWrappingStyleChange,
+ handleWrapTextChange,
+ handleDistToTextChange,
+ MIN_MARGIN,
+ MAX_MARGIN,
+ };
+}
diff --git a/packages/docs-drawing/src/commands/commands/__tests__/update-doc-drawing-transform.command.spec.ts b/packages/docs-drawing/src/commands/commands/__tests__/update-doc-drawing-transform.command.spec.ts
index 14b989f1d8..648dc79383 100644
--- a/packages/docs-drawing/src/commands/commands/__tests__/update-doc-drawing-transform.command.spec.ts
+++ b/packages/docs-drawing/src/commands/commands/__tests__/update-doc-drawing-transform.command.spec.ts
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-import type { IUpdateDrawingDocTransformCommandParams } from '@univerjs/docs-drawing';
+import type { IUpdateDrawingDocTransformCommandParams } from '../update-doc-drawing-transform.command';
import { ICommandService, ImageSourceType } from '@univerjs/core';
import { DocHistoryAction, RichTextEditingMutation } from '@univerjs/docs';
-import { UpdateDrawingDocTransformCommand } from '@univerjs/docs-drawing';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createFacadeTestBed } from '../../../facade/__tests__/create-test-bed';
+import { UpdateDrawingDocTransformCommand } from '../update-doc-drawing-transform.command';
class MockImage {
width = 800;
@@ -49,6 +49,45 @@ describe('UpdateDrawingDocTransformCommand', () => {
vi.unstubAllGlobals();
});
+ it('persists image crop geometry and restores it through undo and redo', async () => {
+ const image = await testBed.document.insertImage({
+ source: 'data:image/png;base64,image',
+ imageSourceType: ImageSourceType.BASE64,
+ width: 160,
+ height: 90,
+ textRange: { startOffset: 3, endOffset: 3, collapsed: true, segmentId: '' },
+ });
+ if (!image) {
+ throw new Error('Image insertion failed');
+ }
+ const drawingId = image.getId();
+ const before = structuredClone(testBed.documentDataModel.getDrawings()?.[drawingId]);
+ const commandService = testBed.injector.get(ICommandService);
+ expect(commandService.syncExecuteCommand<IUpdateDrawingDocTransformCommandParams>(
+ UpdateDrawingDocTransformCommand.id,
+ {
+ unitId: 'test-doc',
+ subUnitId: 'test-doc',
+ drawings: [
+ { drawingId, key: 'prstGeom', value: 'roundRect' },
+ { drawingId, key: 'adjustValues', value: { adj: 25000 } },
+ { drawingId, key: 'srcRect', value: { left: 10, top: 0, right: 10, bottom: 0 } },
+ ],
+ }
+ )).toBe(true);
+ const after = structuredClone(testBed.documentDataModel.getDrawings()?.[drawingId]);
+ expect(after).toMatchObject({
+ prstGeom: 'roundRect',
+ adjustValues: { adj: 25000 },
+ srcRect: { left: 10, top: 0, right: 10, bottom: 0 },
+ docTransform: before?.docTransform,
+ });
+ expect(testBed.document.undo()).toBe(true);
+ expect(testBed.documentDataModel.getDrawings()?.[drawingId]).toEqual(before);
+ expect(testBed.document.redo()).toBe(true);
+ expect(testBed.documentDataModel.getDrawings()?.[drawingId]).toEqual(after);
+ });
+
it('marks image transforms for history action summaries', async () => {
const image = await testBed.document.insertImage({
source: 'data:image/png;base64,image',
diff --git a/packages/docs-drawing/src/commands/commands/update-doc-drawing-transform.command.ts b/packages/docs-drawing/src/commands/commands/update-doc-drawing-transform.command.ts
index f19e755f13..7731a6dac9 100644
--- a/packages/docs-drawing/src/commands/commands/update-doc-drawing-transform.command.ts
+++ b/packages/docs-drawing/src/commands/commands/update-doc-drawing-transform.command.ts
@@ -32,8 +32,8 @@ import { findDocDrawing } from '../../services/doc-drawing-source';
export interface IDrawingDocTransform {
drawingId: string;
- key: 'size' | 'angle' | 'positionH' | 'positionV' | 'flipX' | 'flipY' | 'srcRect';
- value: ISize | number | boolean | IObjectPositionH | IObjectPositionV | Nullable<ISrcRect>;
+ key: 'size' | 'angle' | 'positionH' | 'positionV' | 'flipX' | 'flipY' | 'srcRect' | 'prstGeom' | 'adjustValues';
+ value: ISize | number | boolean | IObjectPositionH | IObjectPositionV | Nullable<ISrcRect> | IDocImage['prstGeom'] | IDocImage['adjustValues'];
}
export interface IUpdateDrawingDocTransformCommandParams {
@@ -66,7 +66,7 @@ export const UpdateDrawingDocTransformCommand: ICommand = {
? DocHistoryAction.UpdateImage
: undefined;
const jsonX = JSONX.getInstance();
- const actions: JSONXActions = [];
+ const actions: JSONXActions[] = [];
for (const { drawingId, key, value } of drawings) {
const source = findDocDrawing(snapshot, drawingId);
@@ -74,24 +74,26 @@ export const UpdateDrawingDocTransformCommand: ICommand = {
return false;
}
const oldDrawing = source.drawing;
- const oldValue = key === 'srcRect'
- ? (oldDrawing as IDocImage | undefined)?.srcRect
+ const isImageProperty = key === 'srcRect' || key === 'prstGeom' || key === 'adjustValues';
+ const oldValue = isImageProperty
+ ? (key in oldDrawing ? Reflect.get(oldDrawing, key) : undefined)
: oldDrawing?.docTransform?.[key];
if (!Tools.diffValue(oldValue, value)) {
- const path = key === 'srcRect'
+ const path = isImageProperty
? [...source.path, key]
: [...source.path, 'docTransform', key];
// Optional transform fields such as flips do not exist in older documents.
- actions.push(oldValue === undefined
- ? jsonX.insertOp(path, value)!
- : jsonX.replaceOp(path, oldValue, value)!);
+ const action = oldValue === undefined
+ ? jsonX.insertOp(path, value)
+ : jsonX.replaceOp(path, oldValue, value);
+ actions.push(action);
}
}
return Boolean(commandService.syncExecuteCommand<IRichTextEditingMutationParams, IRichTextEditingMutationParams>(RichTextEditingMutation.id, {
unitId,
historyAction,
- actions: actions.reduce((acc, action) => JSONX.compose(acc, action as JSONXActions), null as JSONXActions),
+ actions: actions.reduce<JSONXActions>((acc, action) => JSONX.compose(acc, action), null),
textRanges: null,
debounce: true,
}));
diff --git a/packages/docs-hyper-link-ui/src/__tests__/docs-hyper-link-ui.integration.spec.ts b/packages/docs-hyper-link-ui/src/__tests__/docs-hyper-link-ui.integration.spec.ts
index 375dd80d3d..3fcdbeecda 100644
--- a/packages/docs-hyper-link-ui/src/__tests__/docs-hyper-link-ui.integration.spec.ts
+++ b/packages/docs-hyper-link-ui/src/__tests__/docs-hyper-link-ui.integration.spec.ts
@@ -20,10 +20,13 @@ import {
CustomRangeType,
ICommandService,
IUniverInstanceService,
+ toDisposable,
UniverInstanceType,
} from '@univerjs/core';
import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';
import { DocCanvasPopManagerService } from '@univerjs/docs-ui';
+import { IDialogService } from '@univerjs/ui';
+import { of } from 'rxjs';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AddDocHyperLinkCommand } from '../commands/commands/add-link.command';
import { DeleteDocHyperLinkCommand } from '../commands/commands/delete-link.command';
@@ -186,6 +189,14 @@ describe('docs-hyper-link-ui integration', () => {
it('shows and hides the info popup when the executed selection enters and leaves a hyperlink', async () => {
const popupManagerStub = createPopupManagerStub();
injector.add([DocCanvasPopManagerService, { useValue: popupManagerStub as unknown as DocCanvasPopManagerService }]);
+ injector.add([IDialogService, {
+ useValue: {
+ close: () => {},
+ closeAll: () => {},
+ getDialogs$: () => of([]),
+ open: () => toDisposable(() => {}),
+ },
+ }]);
injector.add([DocHyperLinkPopupService]);
injector.add([DocHyperLinkSelectionController]);
diff --git a/packages/docs-hyper-link-ui/src/commands/operations/__tests__/popup.operation.spec.ts b/packages/docs-hyper-link-ui/src/commands/operations/__tests__/popup.operation.spec.ts
index 661bfb7dc2..727550be36 100644
--- a/packages/docs-hyper-link-ui/src/commands/operations/__tests__/popup.operation.spec.ts
+++ b/packages/docs-hyper-link-ui/src/commands/operations/__tests__/popup.operation.spec.ts
@@ -19,6 +19,8 @@ import { CustomRangeType, ICommandService, toDisposable, Univer, UniverInstanceT
import { DocSelectionManagerService } from '@univerjs/docs';
import { DocCanvasPopManagerService } from '@univerjs/docs-ui';
import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
+import { IDialogService } from '@univerjs/ui';
+import { of } from 'rxjs';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { DocHyperLinkPopupService } from '../../../services/hyper-link-popup.service';
import {
@@ -75,6 +77,14 @@ describe('doc hyperlink popup operations', () => {
injector.add([DocSelectionManagerService]);
injector.add([DocCanvasPopManagerService, { useClass: TestDocCanvasPopManagerService as never }]);
injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
+ injector.add([IDialogService, {
+ useValue: {
+ close: () => {},
+ closeAll: () => {},
+ getDialogs$: () => of([]),
+ open: () => toDisposable(() => {}),
+ },
+ }]);
injector.add([DocHyperLinkPopupService]);
univer.createUnit(UniverInstanceType.UNIVER_DOC, createDocData());
diff --git a/packages/docs-hyper-link-ui/src/controllers/__tests__/doc-hyper-link-selection.controller.spec.ts b/packages/docs-hyper-link-ui/src/controllers/__tests__/doc-hyper-link-selection.controller.spec.ts
index 969648a38a..a437022ee7 100644
--- a/packages/docs-hyper-link-ui/src/controllers/__tests__/doc-hyper-link-selection.controller.spec.ts
+++ b/packages/docs-hyper-link-ui/src/controllers/__tests__/doc-hyper-link-selection.controller.spec.ts
@@ -21,7 +21,7 @@ import { BooleanNumber, CustomRangeType, DocumentFlavor, ICommandService, Univer
import { DocLayoutExecutorService, DocSelectionManagerService, DocSkeletonManagerService, SetTextSelectionsOperation } from '@univerjs/docs';
import { DocCanvasPopManagerService } from '@univerjs/docs-ui';
import { CanvasColorService, Documents, ICanvasColorService, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
-import { CanvasPopupService, ICanvasPopupService } from '@univerjs/ui';
+import { CanvasPopupService, DesktopDialogService, ICanvasPopupService, IDialogService, IUIPartsService, UIPartsService } from '@univerjs/ui';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { DocHyperLinkPopupService } from '../../services/hyper-link-popup.service';
import { DocHyperLinkSelectionController } from '../doc-hyper-link-selection.controller';
@@ -53,6 +53,8 @@ describe.each([1, 3])('DocHyperLinkSelectionController with a %i-character link'
injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
injector.add([ICanvasColorService, { useClass: CanvasColorService }]);
injector.add([ICanvasPopupService, { useClass: CanvasPopupService }]);
+ injector.add([IUIPartsService, { useClass: UIPartsService }]);
+ injector.add([IDialogService, { useClass: DesktopDialogService }]);
injector.add([DocLayoutExecutorService]);
injector.add([DocSelectionManagerService]);
injector.add([DocCanvasPopManagerService]);
diff --git a/packages/docs-hyper-link-ui/src/controllers/doc-hyper-link-selection.controller.ts b/packages/docs-hyper-link-ui/src/controllers/doc-hyper-link-selection.controller.ts
index dd72cf5e09..f5d1aeaa4c 100644
--- a/packages/docs-hyper-link-ui/src/controllers/doc-hyper-link-selection.controller.ts
+++ b/packages/docs-hyper-link-ui/src/controllers/doc-hyper-link-selection.controller.ts
@@ -16,7 +16,14 @@
import type { DocumentDataModel } from '@univerjs/core';
import type { ISetTextSelectionsOperationParams } from '@univerjs/docs';
-import { CustomRangeType, Disposable, ICommandService, Inject, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import {
+ CustomRangeType,
+ Disposable,
+ ICommandService,
+ Inject,
+ IUniverInstanceService,
+ UniverInstanceType,
+} from '@univerjs/core';
import { SetTextSelectionsOperation } from '@univerjs/docs';
import { DocHyperLinkPopupService } from '../services/hyper-link-popup.service';
@@ -40,6 +47,13 @@ export class DocHyperLinkSelectionController extends Disposable {
const doc = this._univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
const primary = ranges[0];
+ const editing = this._docHyperLinkService.editing;
+ // Opening the editor selects its own link; that is not a user dismissal.
+ if (editing?.unitId === unitId &&
+ (editing.segmentId ?? '') === (segmentId ?? '') &&
+ primary?.startOffset === editing.startIndex && primary.endOffset === editing.endIndex + 1) {
+ return;
+ }
if (primary?.collapsed && doc) {
const { startOffset, endOffset, segmentPage } = primary;
const customRanges = doc.getSelfOrHeaderFooterModel(segmentId)?.getBody()?.customRanges;
diff --git a/packages/docs-hyper-link-ui/src/controllers/mobile/components.controller.ts b/packages/docs-hyper-link-ui/src/controllers/mobile/components.controller.ts
new file mode 100644
index 0000000000..3e27b3399f
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/controllers/mobile/components.controller.ts
@@ -0,0 +1,50 @@
+/**
+ * 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 { MobileDocHyperLinkEdit } from '../../views/MobileDocHyperLinkEdit';
+import { MobileDocLinkPopup } from '../../views/MobileDocLinkPopup';
+
+export class MobileComponentsController extends Disposable {
+ constructor(
+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,
+ @Inject(IconManager) private readonly _iconManager: IconManager
+ ) {
+ super();
+
+ this._registerComponents();
+ this._registerIcons();
+ }
+
+ private _registerComponents(): void {
+ ([
+ [MobileDocHyperLinkEdit.componentKey, MobileDocHyperLinkEdit],
+ [MobileDocLinkPopup.componentKey, MobileDocLinkPopup],
+ ] as const).forEach(([key, comp]) => {
+ this.disposeWithMe(
+ this._componentManager.register(key, comp)
+ );
+ });
+ }
+
+ private _registerIcons(): void {
+ this.disposeWithMe(this._iconManager.register({
+ LinkIcon,
+ }));
+ }
+}
diff --git a/packages/docs-hyper-link-ui/src/controllers/render-controllers/__tests__/hyper-link-event.render-controller.spec.ts b/packages/docs-hyper-link-ui/src/controllers/render-controllers/__tests__/hyper-link-event.render-controller.spec.ts
index 5860c5177c..74e5a3c567 100644
--- a/packages/docs-hyper-link-ui/src/controllers/render-controllers/__tests__/hyper-link-event.render-controller.spec.ts
+++ b/packages/docs-hyper-link-ui/src/controllers/render-controllers/__tests__/hyper-link-event.render-controller.spec.ts
@@ -14,13 +14,154 @@
* limitations under the License.
*/
-import { CustomRangeType } from '@univerjs/core';
+import type { DocumentDataModel } from '@univerjs/core';
+import type { IRenderContext } from '@univerjs/engine-render';
+import { CustomRangeType, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, ICommandService, Univer } from '@univerjs/core';
+import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';
+import { DocEventManagerService } from '@univerjs/docs-ui';
import { config, Subject } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
+import { DeleteDocHyperLinkCommand } from '../../../commands/commands/delete-link.command';
import { ClickDocHyperLinkOperation } from '../../../commands/operations/popup.operation';
+import { DocHyperLinkPopupService } from '../../../services/hyper-link-popup.service';
import { DocHyperLinkEventRenderController } from '../hyper-link-event.render-controller';
+import { MobileDocHyperLinkEventRenderController } from '../mobile/hyper-link-event.render-controller';
+
+function createController(
+ context: IRenderContext<DocumentDataModel>,
+ events: DocEventManagerService,
+ commands: ICommandService,
+ popup: DocHyperLinkPopupService,
+ skeleton: DocSkeletonManagerService,
+ selection: DocSelectionManagerService
+) {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+ injector.add([DocEventManagerService, { useValue: events }]);
+ injector.add([DocHyperLinkPopupService, { useValue: popup }]);
+ injector.add([DocSkeletonManagerService, { useValue: skeleton }]);
+ injector.add([DocSelectionManagerService, { useValue: selection }]);
+ const child = injector.createChild([[ICommandService, { useValue: commands }]]);
+ const controller = child.createInstance(DocHyperLinkEventRenderController, context);
+ controller.disposeWithMe(() => univer.dispose());
+ return controller;
+}
describe('DocHyperLinkEventRenderController', () => {
+ it('keeps the mobile event controller independent from the desktop controller', () => {
+ expect(MobileDocHyperLinkEventRenderController.prototype).not.toBeInstanceOf(DocHyperLinkEventRenderController);
+ });
+
+ it('handles hyperlink menus and clicks in the standalone mobile controller', async () => {
+ const hoverCustomRanges$ = new Subject<unknown[]>();
+ const clickCustomRanges$ = new Subject<unknown>();
+ const pointerDownCustomRanges$ = new Subject<unknown[]>();
+ const commandService = { executeCommand: vi.fn() };
+ const popupService = {
+ canEditLink: vi.fn(() => true),
+ hideInfoPopupOnPointerDown: vi.fn(),
+ showEditPopup: vi.fn(),
+ showInfoPopup: vi.fn(),
+ };
+ const capture = vi.fn<(target: { onEdit: () => unknown; onDelete: () => unknown }) => boolean>(() => true);
+ const controller = new MobileDocHyperLinkEventRenderController(
+ { unitId: 'doc-unit' } as never,
+ { hoverCustomRanges$, clickCustomRanges$, pointerDownCustomRanges$ } as never,
+ commandService as never,
+ popupService as never,
+ { getSkeleton: vi.fn() } as never,
+ { capture } as never
+ );
+ const linkRange = {
+ range: {
+ rangeId: 'link-1',
+ rangeType: CustomRangeType.HYPERLINK,
+ startIndex: 4,
+ endIndex: 10,
+ },
+ segmentId: 'header-1',
+ segmentPageIndex: 0,
+ rects: [{ left: 10, top: 20, right: 50, bottom: 40 }],
+ };
+
+ pointerDownCustomRanges$.next([linkRange]);
+ const target = capture.mock.calls[0][0];
+ await target.onEdit();
+ await target.onDelete();
+
+ expect(popupService.showEditPopup).toHaveBeenCalledWith('doc-unit', {
+ unitId: 'doc-unit',
+ linkId: 'link-1',
+ segmentId: 'header-1',
+ segmentPage: 0,
+ startIndex: 4,
+ endIndex: 10,
+ });
+ expect(commandService.executeCommand).toHaveBeenCalledWith(DeleteDocHyperLinkCommand.id, {
+ unitId: 'doc-unit',
+ linkId: 'link-1',
+ segmentId: 'header-1',
+ segmentPage: 0,
+ startIndex: 4,
+ endIndex: 10,
+ });
+
+ clickCustomRanges$.next({ ...linkRange, ctrlKey: false, metaKey: false });
+ expect(popupService.showInfoPopup).toHaveBeenCalledWith(
+ expect.objectContaining({ unitId: 'doc-unit', linkId: 'link-1' }),
+ { pinned: true }
+ );
+
+ commandService.executeCommand.mockClear();
+ clickCustomRanges$.next({ ...linkRange, ctrlKey: true, metaKey: false });
+ expect(commandService.executeCommand).toHaveBeenCalledWith(ClickDocHyperLinkOperation.id, {
+ unitId: 'doc-unit',
+ linkId: 'link-1',
+ segmentId: 'header-1',
+ });
+
+ pointerDownCustomRanges$.next([]);
+ expect(popupService.hideInfoPopupOnPointerDown).toHaveBeenCalledOnce();
+ controller.dispose();
+
+ capture.mockClear();
+ popupService.showInfoPopup.mockClear();
+ pointerDownCustomRanges$.next([linkRange]);
+ clickCustomRanges$.next({ ...linkRange, ctrlKey: false, metaKey: false });
+ expect(capture).not.toHaveBeenCalled();
+ expect(popupService.showInfoPopup).not.toHaveBeenCalled();
+ });
+
+ it('does not register mobile hyperlink events for the normal internal editor', () => {
+ const hoverCustomRanges$ = new Subject<unknown[]>();
+ const clickCustomRanges$ = new Subject<unknown>();
+ const pointerDownCustomRanges$ = new Subject<unknown[]>();
+ const capture = vi.fn();
+ const showInfoPopup = vi.fn();
+ const controller = new MobileDocHyperLinkEventRenderController(
+ { unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY } as never,
+ { hoverCustomRanges$, clickCustomRanges$, pointerDownCustomRanges$ } as never,
+ { executeCommand: vi.fn() } as never,
+ { showInfoPopup } as never,
+ { getSkeleton: vi.fn() } as never,
+ { capture } as never
+ );
+
+ pointerDownCustomRanges$.next([{
+ range: { rangeType: CustomRangeType.HYPERLINK },
+ rects: [{ left: 0, top: 0, right: 1, bottom: 1 }],
+ }]);
+ clickCustomRanges$.next({
+ range: { rangeType: CustomRangeType.HYPERLINK },
+ ctrlKey: false,
+ metaKey: false,
+ });
+
+ expect(capture).not.toHaveBeenCalled();
+ expect(showInfoPopup).not.toHaveBeenCalled();
+ controller.dispose();
+ });
+
it('ignores hover ranges when the current selection has no text ranges', async () => {
const hoverCustomRanges$ = new Subject<unknown[]>();
const clickCustomRanges$ = new Subject<unknown>();
@@ -33,7 +174,7 @@ describe('DocHyperLinkEventRenderController', () => {
config.onUnhandledError = onUnhandledError;
try {
- const controller = new DocHyperLinkEventRenderController(
+ const controller = createController(
{ unitId: 'doc-unit' } as never,
{ hoverCustomRanges$, clickCustomRanges$, pointerDownCustomRanges$ } as never,
commandService as never,
@@ -65,7 +206,7 @@ describe('DocHyperLinkEventRenderController', () => {
showing: false,
showInfoPopup: vi.fn(),
};
- const controller = new DocHyperLinkEventRenderController(
+ const controller = createController(
{ unitId: 'doc-unit' } as never,
{ hoverCustomRanges$, clickCustomRanges$, pointerDownCustomRanges$ } as never,
commandService as never,
@@ -132,7 +273,7 @@ describe('DocHyperLinkEventRenderController', () => {
this.infoPopupPinned = options?.pinned ?? false;
}),
};
- const controller = new DocHyperLinkEventRenderController(
+ const controller = createController(
{ unitId: 'doc-unit' } as never,
{ hoverCustomRanges$, clickCustomRanges$, pointerDownCustomRanges$ } as never,
commandService as never,
@@ -175,7 +316,7 @@ describe('DocHyperLinkEventRenderController', () => {
infoPopupPinned: false,
scheduleHideInfoPopup: vi.fn(),
};
- const controller = new DocHyperLinkEventRenderController(
+ const controller = createController(
{ unitId: 'doc-unit' } as never,
{ hoverCustomRanges$, clickCustomRanges$, pointerDownCustomRanges$ } as never,
commandService as never,
@@ -203,7 +344,7 @@ describe('DocHyperLinkEventRenderController', () => {
showing: { linkId: 'link-1' },
hideInfoPopupOnPointerDown: vi.fn(),
};
- const controller = new DocHyperLinkEventRenderController(
+ const controller = createController(
{ unitId: 'doc-unit' } as never,
{ hoverCustomRanges$, clickCustomRanges$, pointerDownCustomRanges$ } as never,
commandService as never,
diff --git a/packages/docs-hyper-link-ui/src/controllers/render-controllers/__tests__/render.controller.spec.ts b/packages/docs-hyper-link-ui/src/controllers/render-controllers/__tests__/render.controller.spec.ts
index 53a32a7444..c6b2775e59 100644
--- a/packages/docs-hyper-link-ui/src/controllers/render-controllers/__tests__/render.controller.spec.ts
+++ b/packages/docs-hyper-link-ui/src/controllers/render-controllers/__tests__/render.controller.spec.ts
@@ -33,6 +33,7 @@ import {
} from '@univerjs/docs';
import { DocCanvasPopManagerService } from '@univerjs/docs-ui';
import { IRenderManagerService } from '@univerjs/engine-render';
+import { DesktopDialogService, IDialogService, IUIPartsService, UIPartsService } from '@univerjs/ui';
import { NEVER } from 'rxjs';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { DocHyperLinkPopupService } from '../../../services/hyper-link-popup.service';
@@ -63,6 +64,8 @@ describe('DocHyperLinkRenderController', () => {
attachPopupToRange: () => ({ dispose: disposePopup, canDispose: () => true }),
} as unknown as DocCanvasPopManagerService }]);
injector.add([DocHyperLinkPopupService]);
+ injector.add([IUIPartsService, { useClass: UIPartsService }]);
+ injector.add([IDialogService, { useClass: DesktopDialogService }]);
injector.add([DocHyperLinkRenderController, { useFactory: () => injector.createInstance(DocHyperLinkRenderController, context) }]);
const controller = injector.get(DocHyperLinkRenderController);
diff --git a/packages/docs-hyper-link-ui/src/controllers/render-controllers/hyper-link-event.render-controller.ts b/packages/docs-hyper-link-ui/src/controllers/render-controllers/hyper-link-event.render-controller.ts
index 7b801628bc..f861c39033 100644
--- a/packages/docs-hyper-link-ui/src/controllers/render-controllers/hyper-link-event.render-controller.ts
+++ b/packages/docs-hyper-link-ui/src/controllers/render-controllers/hyper-link-event.render-controller.ts
@@ -16,10 +16,19 @@
import type { DocumentDataModel } from '@univerjs/core';
import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
-import { CustomRangeType, Disposable, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, ICommandService, Inject } from '@univerjs/core';
+import {
+ CustomRangeType,
+ Disposable,
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ ICommandService,
+ Inject,
+} from '@univerjs/core';
import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';
import { DocEventManagerService } from '@univerjs/docs-ui';
-import { ClickDocHyperLinkOperation, ToggleDocHyperLinkInfoPopupOperation } from '../../commands/operations/popup.operation';
+import {
+ ClickDocHyperLinkOperation,
+ ToggleDocHyperLinkInfoPopupOperation,
+} from '../../commands/operations/popup.operation';
import { DocHyperLinkPopupService } from '../../services/hyper-link-popup.service';
export class DocHyperLinkEventRenderController extends Disposable implements IRenderModule {
@@ -59,7 +68,8 @@ export class DocHyperLinkEventRenderController extends Disposable implements IRe
private _initPointerDown() {
this.disposeWithMe(
this._docEventManagerService.pointerDownCustomRanges$.subscribe((ranges) => {
- if (!ranges.some((range) => range.range.rangeType === CustomRangeType.HYPERLINK)) {
+ const link = ranges.find((range) => range.range.rangeType === CustomRangeType.HYPERLINK);
+ if (!link) {
this._hyperLinkPopupService.hideInfoPopupOnPointerDown();
}
})
@@ -78,17 +88,17 @@ export class DocHyperLinkEventRenderController extends Disposable implements IRe
}
if (link) {
+ const info = {
+ unitId: this._context.unitId,
+ linkId: link.range.rangeId,
+ segmentId: link.segmentId,
+ segmentPage: link.segmentPageIndex,
+ startIndex: link.range.startIndex,
+ endIndex: link.range.endIndex,
+ };
this._commandService.executeCommand(
ToggleDocHyperLinkInfoPopupOperation.id,
- {
- unitId: this._context.unitId,
- linkId: link.range.rangeId,
- segmentId: link.segmentId,
- segmentPage: link.segmentPageIndex,
- rangeId: link.range.rangeId,
- startIndex: link.range.startIndex,
- endIndex: link.range.endIndex,
- }
+ info
);
} else {
this._hideInfoPopup();
diff --git a/packages/docs-hyper-link-ui/src/controllers/render-controllers/mobile/hyper-link-event.render-controller.ts b/packages/docs-hyper-link-ui/src/controllers/render-controllers/mobile/hyper-link-event.render-controller.ts
new file mode 100644
index 0000000000..a8f7b84820
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/controllers/render-controllers/mobile/hyper-link-event.render-controller.ts
@@ -0,0 +1,117 @@
+/**
+ * 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 } from '@univerjs/core';
+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import {
+ CustomRangeType,
+ Disposable,
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ ICommandService,
+ Inject,
+} from '@univerjs/core';
+import { DocSkeletonManagerService } from '@univerjs/docs';
+import { DocEventManagerService, DocMobileElementMenuService } from '@univerjs/docs-ui';
+import { DeleteDocHyperLinkCommand } from '../../../commands/commands/delete-link.command';
+import { ClickDocHyperLinkOperation } from '../../../commands/operations/popup.operation';
+import { DocHyperLinkPopupService } from '../../../services/hyper-link-popup.service';
+
+export class MobileDocHyperLinkEventRenderController extends Disposable implements IRenderModule {
+ get _skeleton() {
+ return this._docSkeletonManagerService.getSkeleton();
+ }
+
+ constructor(
+ private readonly _context: IRenderContext<DocumentDataModel>,
+ @Inject(DocEventManagerService) private readonly _docEventManagerService: DocEventManagerService,
+ @ICommandService private readonly _commandService: ICommandService,
+ @Inject(DocHyperLinkPopupService) private readonly _hyperLinkPopupService: DocHyperLinkPopupService,
+ @Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
+ @Inject(DocMobileElementMenuService) private readonly _mobileElementMenuService: DocMobileElementMenuService
+ ) {
+ super();
+
+ if (this._context.unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY) {
+ return;
+ }
+
+ this._initPointerDown();
+ this._initClick();
+ }
+
+ private _initPointerDown(): void {
+ this.disposeWithMe(this._docEventManagerService.pointerDownCustomRanges$.subscribe((ranges) => {
+ const link = ranges.find((range) => range.range.rangeType === CustomRangeType.HYPERLINK);
+ if (!link) {
+ this._hyperLinkPopupService.hideInfoPopupOnPointerDown();
+ return;
+ }
+
+ const info = {
+ unitId: this._context.unitId,
+ linkId: link.range.rangeId,
+ segmentId: link.segmentId,
+ segmentPage: link.segmentPageIndex,
+ startIndex: link.range.startIndex,
+ endIndex: link.range.endIndex,
+ };
+ const rect = link.rects[0];
+ if (rect && this._hyperLinkPopupService.canEditLink(info.unitId, info)) {
+ this._mobileElementMenuService.capture({
+ unitId: info.unitId,
+ rect,
+ onEdit: () => this._hyperLinkPopupService.showEditPopup(info.unitId, info),
+ onDelete: () => this._commandService.executeCommand(DeleteDocHyperLinkCommand.id, info),
+ });
+ }
+ }));
+ }
+
+ private _initClick(): void {
+ this.disposeWithMe(
+ this._docEventManagerService.clickCustomRanges$.subscribe((range) => {
+ const link = range.range;
+ if (link.rangeType !== CustomRangeType.HYPERLINK) {
+ return;
+ }
+
+ if (!range.ctrlKey && !range.metaKey) {
+ this._hyperLinkPopupService.showInfoPopup(
+ {
+ unitId: this._context.unitId,
+ linkId: link.rangeId,
+ segmentId: range.segmentId,
+ segmentPage: range.segmentPageIndex,
+ startIndex: link.startIndex,
+ endIndex: link.endIndex,
+ },
+ { pinned: true }
+ );
+ return;
+ }
+
+ this._commandService.executeCommand(
+ ClickDocHyperLinkOperation.id,
+ {
+ unitId: this._context.unitId,
+ linkId: link.rangeId,
+ segmentId: range.segmentId,
+ }
+ );
+ })
+ );
+ }
+}
diff --git a/packages/docs-hyper-link-ui/src/index.ts b/packages/docs-hyper-link-ui/src/index.ts
index a27b22bf67..17e0a209da 100644
--- a/packages/docs-hyper-link-ui/src/index.ts
+++ b/packages/docs-hyper-link-ui/src/index.ts
@@ -18,4 +18,5 @@ import './global.css';
export type { IUniverDocsHyperLinkUIConfig } from './config/config';
export { menuSchema as DocsHyperLinkUIMenuSchema } from './menu/schema';
+export { UniverDocsHyperLinkMobileUIPlugin } from './mobile-plugin';
export { UniverDocsHyperLinkUIPlugin } from './plugin';
diff --git a/packages/docs-hyper-link-ui/src/mobile-plugin.ts b/packages/docs-hyper-link-ui/src/mobile-plugin.ts
new file mode 100644
index 0000000000..ce1bd87a94
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/mobile-plugin.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 { Dependency } from '@univerjs/core';
+import type { IUniverDocsHyperLinkUIConfig } from './config/config';
+import { DependentOn, IConfigService, Inject, Injector, merge, Plugin, UniverInstanceType } from '@univerjs/core';
+import { UniverDocsPlugin } from '@univerjs/docs';
+import { UniverDocsHyperLinkPlugin } from '@univerjs/docs-hyper-link';
+import { UniverDocsMobileUIPlugin } from '@univerjs/docs-ui';
+import { IRenderManagerService, UniverRenderEnginePlugin } from '@univerjs/engine-render';
+import pkg from '../package.json';
+import { defaultPluginConfig, DOCS_HYPER_LINK_UI_PLUGIN_CONFIG_KEY } from './config/config';
+import { DocHyperLinkSelectionController } from './controllers/doc-hyper-link-selection.controller';
+import { MobileComponentsController } from './controllers/mobile/components.controller';
+import { MobileDocHyperLinkEventRenderController } from './controllers/render-controllers/mobile/hyper-link-event.render-controller';
+import { DocHyperLinkRenderController } from './controllers/render-controllers/render.controller';
+import { DocHyperLinkUIController } from './controllers/ui.controller';
+import { DocHyperLinkPopupService } from './services/hyper-link-popup.service';
+import { MobileDocHyperLinkPopupService } from './services/mobile/hyper-link-popup.service';
+import { DOC_HYPER_LINK_UI_PLUGIN } from './types/const';
+
+@DependentOn(
+ UniverDocsPlugin,
+ UniverRenderEnginePlugin,
+ UniverDocsHyperLinkPlugin,
+ UniverDocsMobileUIPlugin
+)
+export class UniverDocsHyperLinkMobileUIPlugin extends Plugin {
+ static override pluginName = DOC_HYPER_LINK_UI_PLUGIN;
+ static override packageName = pkg.name;
+ static override version = pkg.version;
+ static override type = UniverInstanceType.UNIVER_DOC;
+
+ constructor(
+ private readonly _config: Partial<IUniverDocsHyperLinkUIConfig> = defaultPluginConfig,
+ @Inject(Injector) protected override _injector: Injector,
+ @IRenderManagerService private readonly _renderManagerSrv: 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(DOCS_HYPER_LINK_UI_PLUGIN_CONFIG_KEY, rest);
+ }
+
+ override onStarting(): void {
+ const dependencies: Dependency[] = [
+ [MobileComponentsController],
+ [DocHyperLinkPopupService, { useClass: MobileDocHyperLinkPopupService }],
+ [DocHyperLinkUIController],
+ [DocHyperLinkSelectionController],
+ ];
+ dependencies.forEach((dep) => this._injector.add(dep));
+ this._injector.get(MobileComponentsController);
+ this._injector.get(DocHyperLinkUIController);
+ }
+
+ override onReady(): void {
+ this._injector.get(DocHyperLinkSelectionController);
+ }
+
+ override onRendered(): void {
+ ([
+ [DocHyperLinkRenderController],
+ [MobileDocHyperLinkEventRenderController],
+ ] as Dependency[]).forEach((dep) => {
+ this._renderManagerSrv.registerRenderModule(UniverInstanceType.UNIVER_DOC, dep);
+ });
+ }
+}
diff --git a/packages/docs-hyper-link-ui/src/plugin.ts b/packages/docs-hyper-link-ui/src/plugin.ts
index 72cc747c22..eaa17f4e91 100644
--- a/packages/docs-hyper-link-ui/src/plugin.ts
+++ b/packages/docs-hyper-link-ui/src/plugin.ts
@@ -64,17 +64,18 @@ export class UniverDocsHyperLinkUIPlugin extends Plugin {
}
override onStarting(): void {
- this._injector.add([ComponentsController]);
- this._injector.get(ComponentsController);
const deps: Dependency[] = [
+ [ComponentsController],
[DocHyperLinkPopupService],
[DocHyperLinkUIController],
[DocHyperLinkSelectionController],
];
+
deps.forEach((dep) => {
this._injector.add(dep);
});
+ this._injector.get(ComponentsController);
this._injector.get(DocHyperLinkUIController);
}
diff --git a/packages/docs-hyper-link-ui/src/services/__tests__/hyper-link-popup.service.spec.ts b/packages/docs-hyper-link-ui/src/services/__tests__/hyper-link-popup.service.spec.ts
index a566ddaa13..30491b64f2 100644
--- a/packages/docs-hyper-link-ui/src/services/__tests__/hyper-link-popup.service.spec.ts
+++ b/packages/docs-hyper-link-ui/src/services/__tests__/hyper-link-popup.service.spec.ts
@@ -16,6 +16,7 @@
import {
IPermissionService,
+ toDisposable,
Univer,
UniverInstanceType,
} from '@univerjs/core';
@@ -23,6 +24,8 @@ import { DocSelectionManagerService, setDocumentPermissionValue } from '@univerj
import { DocCanvasPopManagerService } from '@univerjs/docs-ui';
import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
import { UnitAction } from '@univerjs/protocol';
+import { IDialogService } from '@univerjs/ui';
+import { of } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
import { DocHyperLinkPopupService } from '../hyper-link-popup.service';
@@ -42,6 +45,14 @@ const CapturingDocCanvasPopManagerServiceCtor = CapturingDocCanvasPopManagerServ
function createService() {
const univer = new Univer();
const injector = univer.__getInjector();
+ injector.add([IDialogService, {
+ useValue: {
+ close: () => {},
+ closeAll: () => {},
+ getDialogs$: () => of([]),
+ open: () => toDisposable(() => {}),
+ },
+ }]);
injector.add([DocCanvasPopManagerService, { useClass: CapturingDocCanvasPopManagerServiceCtor }]);
injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
injector.add([DocSelectionManagerService]);
diff --git a/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts b/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts
index 40f7750f4b..57ef4c23be 100644
--- a/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts
+++ b/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts
@@ -14,11 +14,23 @@
* limitations under the License.
*/
-import { Disposable, DocumentDataModel, Inject, IPermissionService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import type { IDisposable, ITextRangeParam } from '@univerjs/core';
+import {
+ Disposable,
+ DocumentDataModel,
+ ICommandService,
+ Inject,
+ IPermissionService,
+ IUniverInstanceService,
+ LocaleService,
+ UniverInstanceType,
+} from '@univerjs/core';
import { canEditDocumentTargets, DocSelectionManagerService, getDocumentEntityParentPermissionObjectIds, getDocumentEntityPermissionObjectId } from '@univerjs/docs';
import { DocCanvasPopManagerService } from '@univerjs/docs-ui';
import { IRenderManagerService } from '@univerjs/engine-render';
+import { IDialogService } from '@univerjs/ui';
import { BehaviorSubject } from 'rxjs';
+import { DeleteDocHyperLinkCommand } from '../commands/commands/delete-link.command';
import { DocHyperLinkEdit } from '../views/DocHyperLinkEdit';
import { DocLinkPopup } from '../views/DocLinkPopup';
@@ -31,8 +43,6 @@ export interface ILinkInfo {
endIndex: number;
}
-type LinkPopupDisposable = ReturnType<DocCanvasPopManagerService['attachPopupToRange']>;
-
const INFO_POPUP_HIDE_DELAY = 150;
function isSameLinkInfo(current: ILinkInfo | null, next: ILinkInfo): boolean {
@@ -50,20 +60,23 @@ export class DocHyperLinkPopupService extends Disposable {
readonly editingLink$ = this._editingLink$.asObservable();
readonly showingLink$ = this._showingLink$.asObservable();
- private _editPopup: LinkPopupDisposable | null = null;
+ private _editPopup: IDisposable | null = null;
private _editPopupUnitId: string | null = null;
- private _infoPopup: LinkPopupDisposable | null = null;
+ private _infoPopup: IDisposable | null = null;
private _infoPopupPinned = false;
private _infoPopupHideTimer: ReturnType<typeof setTimeout> | null = null;
private _infoPopupSuppressed = false;
private _infoPopupSuppressionTimer: ReturnType<typeof setTimeout> | null = null;
constructor(
- @Inject(DocCanvasPopManagerService) private readonly _docCanvasPopupManagerService: DocCanvasPopManagerService,
+ @Inject(DocCanvasPopManagerService) protected readonly _docCanvasPopupManagerService: DocCanvasPopManagerService,
@Inject(DocSelectionManagerService) private readonly _textSelectionManagerService: DocSelectionManagerService,
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@IPermissionService private readonly _permissionService: IPermissionService,
- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @IDialogService protected readonly _dialogService: IDialogService,
+ @Inject(LocaleService) protected readonly _localeService: LocaleService,
+ @ICommandService private readonly _commandService: ICommandService
) {
super();
@@ -114,7 +127,7 @@ export class DocHyperLinkPopupService extends Disposable {
return this._infoPopupPinned;
}
- showEditPopup(unitId: string, linkInfo: ILinkInfo | null): LinkPopupDisposable | null {
+ showEditPopup(unitId: string, linkInfo: ILinkInfo | null): IDisposable | null {
if (!this.canEditLink(unitId, linkInfo)) {
return null;
}
@@ -144,15 +157,7 @@ export class DocHyperLinkPopupService extends Disposable {
}
if (activeRange) {
- this._editPopup = this._docCanvasPopupManagerService.attachPopupToRange(
- activeRange,
- {
- componentKey: DocHyperLinkEdit.componentKey,
- direction: 'bottom',
- offset: [0, 10],
- },
- unitId
- );
+ this._editPopup = this._openEditSurface(activeRange, unitId);
this._editPopupUnitId = unitId;
return this._editPopup;
}
@@ -162,12 +167,13 @@ export class DocHyperLinkPopupService extends Disposable {
hideEditPopup() {
this._editingLink$.next(null);
- this._editPopup?.dispose();
+ const popup = this._editPopup;
this._editPopup = null;
+ popup?.dispose();
this._editPopupUnitId = null;
}
- showInfoPopup(info: ILinkInfo, options?: { pinned?: boolean }): LinkPopupDisposable | null | undefined {
+ showInfoPopup(info: ILinkInfo, options?: { pinned?: boolean }): IDisposable | null | undefined {
this.cancelScheduledHideInfoPopup();
if (this._infoPopupSuppressed) {
return;
@@ -193,7 +199,21 @@ export class DocHyperLinkPopupService extends Disposable {
this._infoPopupPinned = options?.pinned ?? false;
this._showingLink$.next({ unitId, linkId, segmentId, segmentPage, startIndex, endIndex });
- this._infoPopup = this._docCanvasPopupManagerService.attachPopupToRange(
+ this._infoPopup = this._openInfoSurface(info);
+ return this._infoPopup;
+ }
+
+ protected _openEditSurface(activeRange: ITextRangeParam, unitId: string): IDisposable {
+ return this._docCanvasPopupManagerService.attachPopupToRange(activeRange, {
+ componentKey: DocHyperLinkEdit.componentKey,
+ direction: 'bottom',
+ offset: [0, 10],
+ }, unitId);
+ }
+
+ protected _openInfoSurface(info: ILinkInfo, componentKey = DocLinkPopup.componentKey): IDisposable {
+ const { unitId, linkId, segmentId, segmentPage, startIndex, endIndex } = info;
+ return this._docCanvasPopupManagerService.attachPopupToRange(
{
collapsed: false,
startOffset: startIndex,
@@ -202,7 +222,18 @@ export class DocHyperLinkPopupService extends Disposable {
segmentPage,
},
{
- componentKey: DocLinkPopup.componentKey,
+ componentKey,
+ extraProps: {
+ onEdit: () => {
+ this.hideInfoPopup();
+ this.showEditPopup(unitId, info);
+ },
+ onDelete: async () => {
+ if (await this._commandService.executeCommand(DeleteDocHyperLinkCommand.id, { unitId, linkId, segmentId })) {
+ this.hideInfoPopup();
+ }
+ },
+ },
direction: 'top-center',
multipleDirection: 'top',
offset: [0, 10],
@@ -212,15 +243,15 @@ export class DocHyperLinkPopupService extends Disposable {
},
unitId
);
- return this._infoPopup;
}
hideInfoPopup() {
this.cancelScheduledHideInfoPopup();
this._infoPopupPinned = false;
this._showingLink$.next(null);
- this._infoPopup?.dispose();
+ const popup = this._infoPopup;
this._infoPopup = null;
+ popup?.dispose();
}
scheduleHideInfoPopup() {
diff --git a/packages/docs-hyper-link-ui/src/services/mobile/hyper-link-popup.service.ts b/packages/docs-hyper-link-ui/src/services/mobile/hyper-link-popup.service.ts
new file mode 100644
index 0000000000..9875bc762c
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/services/mobile/hyper-link-popup.service.ts
@@ -0,0 +1,46 @@
+/**
+ * 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, ITextRangeParam } from '@univerjs/core';
+import type { ILinkInfo } from '../hyper-link-popup.service';
+import { MOBILE_DOC_ELEMENT_MENU } from '@univerjs/docs-ui';
+import { MobileDocHyperLinkEdit } from '../../views/MobileDocHyperLinkEdit';
+import { MobileDocLinkPopup } from '../../views/MobileDocLinkPopup';
+import { DocHyperLinkPopupService } from '../hyper-link-popup.service';
+
+export class MobileDocHyperLinkPopupService extends DocHyperLinkPopupService {
+ protected override _openEditSurface(_activeRange: ITextRangeParam, _unitId: string): IDisposable {
+ return this._dialogService.open({
+ id: 'doc-mobile-hyper-link-editor',
+ title: { title: this._localeService.t('docs-hyper-link-ui.menu.tooltip') },
+ children: { label: MobileDocHyperLinkEdit.componentKey },
+ maskClosable: false,
+ onClose: () => this.hideEditPopup(),
+ });
+ }
+
+ protected override _openInfoSurface(info: ILinkInfo): IDisposable {
+ if (this.canEditLink(info.unitId, info)) {
+ return super._openInfoSurface(info, MOBILE_DOC_ELEMENT_MENU);
+ }
+ return this._dialogService.open({
+ id: 'doc-mobile-hyper-link-viewer',
+ title: { title: this._localeService.t('docs-hyper-link-ui.menu.tooltip') },
+ children: { label: MobileDocLinkPopup.componentKey },
+ onClose: () => this.hideInfoPopup(),
+ });
+ }
+}
diff --git a/packages/docs-hyper-link-ui/src/views/DocHyperLinkEdit.tsx b/packages/docs-hyper-link-ui/src/views/DocHyperLinkEdit.tsx
index f3b759c01a..54d8bf29ca 100644
--- a/packages/docs-hyper-link-ui/src/views/DocHyperLinkEdit.tsx
+++ b/packages/docs-hyper-link-ui/src/views/DocHyperLinkEdit.tsx
@@ -14,110 +14,27 @@
* limitations under the License.
*/
-import type { DocumentDataModel } from '@univerjs/core';
import type { LocaleKey } from '../locale/types';
-import {
- BuildTextUtils,
- getBodySlice,
- ICommandService,
- IUniverInstanceService,
- LocaleService,
- Tools,
- UniverInstanceType,
-} from '@univerjs/core';
+import { LocaleService } from '@univerjs/core';
import { borderClassName, Button, clsx, FormLayout, Input } from '@univerjs/design';
-import { DocSelectionManagerService } from '@univerjs/docs';
-import { KeyCode, useDependency, useObservable } from '@univerjs/ui';
-import { useEffect, useState } from 'react';
-import { AddDocHyperLinkCommand } from '../commands/commands/add-link.command';
-import { UpdateDocHyperLinkCommand } from '../commands/commands/update-link.command';
-import { DocHyperLinkPopupService } from '../services/hyper-link-popup.service';
+import { KeyCode, useDependency } from '@univerjs/ui';
+import { useDocHyperLinkEdit } from './hyper-link-edit/use-doc-hyper-link-edit';
import { isBlankInput } from './hyper-link-edit/utils';
-function hasProtocol(urlString: string) {
- const pattern = /^[a-zA-Z]+:\/\//;
- return pattern.test(urlString);
-}
-
-function isEmail(url: string) {
- const pattern = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
- return pattern.test(url);
-}
-
-function transformUrl(urlStr: string) {
- return hasProtocol(urlStr) ? urlStr : isEmail(urlStr) ? `mailto://${urlStr}` : `https://${urlStr}`;
-}
-
export const DocHyperLinkEdit = () => {
- const hyperLinkService = useDependency(DocHyperLinkPopupService);
const localeService = useDependency(LocaleService);
- const editing = useObservable(hyperLinkService.editingLink$);
- const commandService = useDependency(ICommandService);
- const univerInstanceService = useDependency(IUniverInstanceService);
-
- const docSelectionManagerService = useDependency(DocSelectionManagerService);
- const [link, setLink] = useState('');
- const [label, setLabel] = useState('');
- const [showError, setShowError] = useState(false);
- const isLegal = Tools.isLegalUrl(link);
- const doc = editing
- ? univerInstanceService.getUnit<DocumentDataModel>(editing.unitId, UniverInstanceType.UNIVER_DOC) :
- univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
-
- useEffect(() => {
- const activeRange = docSelectionManagerService.getActiveTextRange();
- if (!activeRange) {
- return;
- }
-
- if (editing) {
- const body = doc?.getSelfOrHeaderFooterModel(editing.segmentId)?.getBody();
- const matchedRange = body?.customRanges?.find((i) => editing?.linkId === i.rangeId && i.startIndex === editing.startIndex && i.endIndex === editing.endIndex);
- if (doc && matchedRange) {
- setLink(matchedRange.properties?.url ?? '');
- setLabel(BuildTextUtils.transform.getPlainText(getBodySlice(body!, matchedRange.startIndex, matchedRange.endIndex + 1).dataStream));
- }
- return;
- }
-
- const body = doc?.getSelfOrHeaderFooterModel(activeRange.segmentId)?.getBody();
- const selection = body ? activeRange : null;
- const matchedRange = selection && BuildTextUtils.customRange.getCustomRangesInterestsWithSelection(selection, body?.customRanges ?? [])?.[0];
- if (doc && matchedRange) {
- setLink(matchedRange?.properties?.url ?? '');
- }
- }, [doc, editing, docSelectionManagerService, univerInstanceService]);
-
- const handleCancel = () => {
- hyperLinkService.hideEditPopup();
- };
- const handleConfirm = () => {
- setShowError(true);
- if (!isLegal || !doc) {
- return;
- }
- const linkFinal = transformUrl(link);
-
- if (!editing) {
- commandService.executeCommand(AddDocHyperLinkCommand.id, {
- unitId: doc.getUnitId(),
- payload: linkFinal,
- });
- } else {
- if (isBlankInput(label)) {
- return;
- }
-
- commandService.executeCommand(UpdateDocHyperLinkCommand.id, {
- unitId: doc.getUnitId(),
- payload: linkFinal,
- linkId: editing.linkId,
- label,
- segmentId: editing.segmentId,
- });
- }
- hyperLinkService.hideEditPopup();
- };
+ const {
+ doc,
+ editing,
+ handleCancel,
+ handleConfirm,
+ isLegal,
+ label,
+ link,
+ setLabel,
+ setLink,
+ showError,
+ } = useDocHyperLinkEdit();
if (!doc) {
return;
@@ -142,8 +59,8 @@ export const DocHyperLinkEdit = () => {
value={label}
onChange={setLabel}
autoFocus
- onKeyDown={(evt) => {
- if (evt.keyCode === KeyCode.ENTER) {
+ onKeyDown={(event) => {
+ if (event.keyCode === KeyCode.ENTER) {
handleConfirm();
}
}}
@@ -159,8 +76,8 @@ export const DocHyperLinkEdit = () => {
value={link}
onChange={setLink}
autoFocus
- onKeyDown={(evt) => {
- if (evt.keyCode === KeyCode.ENTER) {
+ onKeyDown={(event) => {
+ if (event.keyCode === KeyCode.ENTER) {
handleConfirm();
}
}}
diff --git a/packages/docs-hyper-link-ui/src/views/DocLinkPopup.tsx b/packages/docs-hyper-link-ui/src/views/DocLinkPopup.tsx
index 56b1d3ab46..e88f4e1841 100644
--- a/packages/docs-hyper-link-ui/src/views/DocLinkPopup.tsx
+++ b/packages/docs-hyper-link-ui/src/views/DocLinkPopup.tsx
@@ -38,7 +38,7 @@ export const DocLinkPopup = () => {
const commandService = useDependency(ICommandService);
const messageService = useDependency(IMessageService);
const localeService = useDependency(LocaleService);
- const currentPopup = useObservable(hyperLinkService.showingLink$);
+ const currentPopup = useObservable(hyperLinkService.showingLink$, hyperLinkService.showing);
const univerInstanceService = useDependency(IUniverInstanceService);
const permissionService = useDependency(IPermissionService);
if (!currentPopup) {
diff --git a/packages/docs-hyper-link-ui/src/views/MobileDocHyperLinkEdit.tsx b/packages/docs-hyper-link-ui/src/views/MobileDocHyperLinkEdit.tsx
new file mode 100644
index 0000000000..b0a13a3ca0
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/views/MobileDocHyperLinkEdit.tsx
@@ -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 { LocaleKey } from '../locale/types';
+import { LocaleService } from '@univerjs/core';
+import { Button, FormLayout, Input } from '@univerjs/design';
+import { KeyCode, useDependency } from '@univerjs/ui';
+import { useDocHyperLinkEdit } from './hyper-link-edit/use-doc-hyper-link-edit';
+import { isBlankInput } from './hyper-link-edit/utils';
+
+export function MobileDocHyperLinkEdit() {
+ const localeService = useDependency(LocaleService);
+ const {
+ doc,
+ editing,
+ handleCancel,
+ handleConfirm,
+ isLegal,
+ label,
+ link,
+ setLabel,
+ setLink,
+ showError,
+ } = useDocHyperLinkEdit();
+
+ if (!doc) {
+ return;
+ }
+
+ return (
+ <div
+ className="
+ univer-box-border univer-w-full univer-bg-gray-0 univer-py-2
+ dark:!univer-bg-gray-900
+ "
+ >
+ <div>
+ {editing
+ ? (
+ <FormLayout
+ label={localeService.t<LocaleKey>('docs-hyper-link-ui.edit.label')}
+ error={showError && isBlankInput(label) ? localeService.t<LocaleKey>('docs-hyper-link-ui.edit.labelError') : ''}
+ >
+ <Input
+ value={label}
+ onChange={setLabel}
+ autoFocus
+ onKeyDown={(event) => {
+ if (event.keyCode === KeyCode.ENTER) {
+ handleConfirm();
+ }
+ }}
+ />
+ </FormLayout>
+ )
+ : null}
+ <FormLayout
+ label={localeService.t<LocaleKey>('docs-hyper-link-ui.edit.address')}
+ error={showError && !isLegal ? localeService.t<LocaleKey>('docs-hyper-link-ui.edit.addressError') : ''}
+ >
+ <Input
+ value={link}
+ onChange={setLink}
+ autoFocus={!editing}
+ onKeyDown={(event) => {
+ if (event.keyCode === KeyCode.ENTER) {
+ handleConfirm();
+ }
+ }}
+ />
+ </FormLayout>
+ </div>
+ <div className="univer-mt-5 univer-flex univer-gap-3">
+ <Button className="univer-h-12 univer-flex-1" onClick={handleCancel}>
+ {localeService.t<LocaleKey>('docs-hyper-link-ui.edit.cancel')}
+ </Button>
+ <Button
+ variant="primary"
+ className="univer-h-12 univer-flex-1"
+ disabled={isBlankInput(link)}
+ onClick={handleConfirm}
+ >
+ {localeService.t<LocaleKey>('docs-hyper-link-ui.edit.confirm')}
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+MobileDocHyperLinkEdit.componentKey = 'univer.doc.mobile-hyper-link-edit';
diff --git a/packages/docs-hyper-link-ui/src/views/MobileDocLinkPopup.tsx b/packages/docs-hyper-link-ui/src/views/MobileDocLinkPopup.tsx
new file mode 100644
index 0000000000..584de63761
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/views/MobileDocLinkPopup.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 {
+ CustomRangeType,
+ DocumentDataModel,
+ ICommandService,
+ IPermissionService,
+ IUniverInstanceService,
+ LocaleService,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { MessageType, MobileActionRow } from '@univerjs/design';
+import { getDocumentPermissionValue } from '@univerjs/docs';
+import { UnitAction } from '@univerjs/protocol';
+import { IMessageService, useDependency, useObservable } from '@univerjs/ui';
+import { DeleteDocHyperLinkCommand } from '../commands/commands/delete-link.command';
+import { ShowDocHyperLinkEditPopupOperation } from '../commands/operations/popup.operation';
+import { DocHyperLinkPopupService } from '../services/hyper-link-popup.service';
+
+export function MobileDocLinkPopup() {
+ const commandService = useDependency(ICommandService);
+ const hyperLinkService = useDependency(DocHyperLinkPopupService);
+ const localeService = useDependency(LocaleService);
+ const messageService = useDependency(IMessageService);
+ const permissionService = useDependency(IPermissionService);
+ const univerInstanceService = useDependency(IUniverInstanceService);
+ const currentPopup = useObservable(hyperLinkService.showingLink$, hyperLinkService.showing);
+ if (!currentPopup) {
+ return null;
+ }
+
+ const { unitId, linkId, segmentId, startIndex, endIndex } = currentPopup;
+ const document = univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_DOC);
+ const body = document instanceof DocumentDataModel
+ ? document.getSelfOrHeaderFooterModel(segmentId)?.getBody()
+ : undefined;
+ const link = body?.customRanges?.find((range) => range.rangeId === linkId
+ && range.rangeType === CustomRangeType.HYPERLINK
+ && range.startIndex === startIndex
+ && range.endIndex === endIndex);
+ if (!link) {
+ return null;
+ }
+
+ const url = link.properties?.url;
+ const canEdit = hyperLinkService.canEditLink(unitId, currentPopup);
+ const canCopy = getDocumentPermissionValue(permissionService, unitId, unitId, UnitAction.Copy);
+
+ return (
+ <div className="univer-flex univer-flex-col univer-gap-2 univer-py-2">
+ <MobileActionRow
+ title={<span className="univer-truncate univer-text-primary-600">{url}</span>}
+ aria-label={url}
+ variant="subtle"
+ onClick={() => window.open(url, undefined, 'noopener noreferrer')}
+ />
+ {canCopy && (
+ <MobileActionRow
+ title={localeService.t<LocaleKey>('docs-hyper-link-ui.info.copy')}
+ aria-label={localeService.t<LocaleKey>('docs-hyper-link-ui.info.copy')}
+ variant="subtle"
+ onClick={() => navigator.clipboard.writeText(url).then(() => {
+ messageService.show({
+ content: localeService.t<LocaleKey>('docs-hyper-link-ui.info.coped'),
+ type: MessageType.Info,
+ });
+ }).catch(() => undefined)}
+ />
+ )}
+ {canEdit && (
+ <>
+ <MobileActionRow
+ title={localeService.t<LocaleKey>('docs-hyper-link-ui.info.edit')}
+ aria-label={localeService.t<LocaleKey>('docs-hyper-link-ui.info.edit')}
+ variant="subtle"
+ onClick={() => {
+ commandService.executeCommand(ShowDocHyperLinkEditPopupOperation.id, {
+ link: currentPopup,
+ }).catch(() => undefined);
+ }}
+ />
+ <MobileActionRow
+ title={localeService.t<LocaleKey>('docs-hyper-link-ui.info.cancel')}
+ aria-label={localeService.t<LocaleKey>('docs-hyper-link-ui.info.cancel')}
+ variant="subtle"
+ onClick={() => {
+ commandService.executeCommand(DeleteDocHyperLinkCommand.id, {
+ unitId,
+ linkId: link.rangeId,
+ segmentId,
+ }).catch(() => undefined);
+ }}
+ />
+ </>
+ )}
+ </div>
+ );
+}
+
+MobileDocLinkPopup.componentKey = 'univer.doc.mobile-link-info-popup';
diff --git a/packages/docs-hyper-link-ui/src/views/__tests__/DocLinkPopup.spec.tsx b/packages/docs-hyper-link-ui/src/views/__tests__/DocLinkPopup.spec.tsx
index bfcde3a0eb..604a80d817 100644
--- a/packages/docs-hyper-link-ui/src/views/__tests__/DocLinkPopup.spec.tsx
+++ b/packages/docs-hyper-link-ui/src/views/__tests__/DocLinkPopup.spec.tsx
@@ -16,6 +16,8 @@
import type { DocumentDataModel, IDocumentData } from '@univerjs/core';
import type { Root } from 'react-dom/client';
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
import {
CustomRangeType,
ICommandService,
@@ -31,9 +33,10 @@ import { DocSelectionManagerService, DocStateEmitService, RichTextEditingMutatio
import { DocCanvasPopManagerService } from '@univerjs/docs-ui';
import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
import { UnitAction } from '@univerjs/protocol';
-import { IMessageService, RediContext } from '@univerjs/ui';
+import { IDialogService, IMessageService, RediContext } from '@univerjs/ui';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
+import { of } from 'rxjs';
import { afterEach, describe, expect, it } from 'vitest';
import { AddDocHyperLinkCommand } from '../../commands/commands/add-link.command';
import { DeleteDocHyperLinkCommand } from '../../commands/commands/delete-link.command';
@@ -42,6 +45,7 @@ import { ShowDocHyperLinkEditPopupOperation } from '../../commands/operations/po
import { DocHyperLinkPopupService } from '../../services/hyper-link-popup.service';
import { DocHyperLinkEdit } from '../DocHyperLinkEdit';
import { DocLinkPopup } from '../DocLinkPopup';
+import { MobileDocHyperLinkEdit } from '../MobileDocHyperLinkEdit';
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -108,6 +112,14 @@ function createPopupTestBed() {
injector.add([DocCanvasPopManagerService, { useClass: TestDocCanvasPopManagerService as never }]);
injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
injector.add([IMessageService, { useClass: TestMessageService as never }]);
+ injector.add([IDialogService, {
+ useValue: {
+ close: () => {},
+ closeAll: () => {},
+ getDialogs$: () => of([]),
+ open: () => toDisposable(() => {}),
+ },
+ }]);
injector.add([DocHyperLinkPopupService]);
const doc = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, createDocData());
@@ -176,11 +188,11 @@ function renderPopup(root: Root, container: HTMLDivElement, testBed: ReturnType<
};
}
-function renderEditPopup(root: Root, testBed: ReturnType<typeof createPopupTestBed>) {
+function renderEditPopup(root: Root, testBed: ReturnType<typeof createPopupTestBed>, mobile = false) {
act(() => {
root.render(
<RediContext.Provider value={{ injector: testBed.injector }}>
- <DocHyperLinkEdit />
+ {mobile ? <MobileDocHyperLinkEdit /> : <DocHyperLinkEdit />}
</RediContext.Provider>
);
});
@@ -202,6 +214,14 @@ describe('DocLinkPopup', () => {
currentTestBed = undefined;
});
+ it('keeps desktop and mobile hyperlink edit components independent', () => {
+ const desktopSource = readFileSync(resolve(process.cwd(), 'src/views/DocHyperLinkEdit.tsx'), 'utf8');
+ const mobileSource = readFileSync(resolve(process.cwd(), 'src/views/MobileDocHyperLinkEdit.tsx'), 'utf8');
+
+ expect(desktopSource).not.toContain('props.mobile');
+ expect(mobileSource).not.toContain("from './DocHyperLinkEdit'");
+ });
+
it('opens the hyperlink edit popup for the currently displayed document link', async () => {
currentTestBed = createPopupTestBed();
showExistingLink(currentTestBed);
@@ -275,7 +295,7 @@ describe('DocLinkPopup', () => {
expect(body?.customRanges?.some((range) => range.rangeId === 'existing-link')).toBe(false);
});
- it('updates an existing document hyperlink from the edit form', async () => {
+ it.each([false, true])('updates an existing document hyperlink from the edit form (mobile: %s)', async (mobile) => {
currentTestBed = createPopupTestBed();
const selectionManager = currentTestBed.injector.get(DocSelectionManagerService);
selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: UNIT_ID, subUnitId: UNIT_ID });
@@ -298,11 +318,20 @@ describe('DocLinkPopup', () => {
document.body.appendChild(container);
root = createRoot(container);
- renderEditPopup(root, currentTestBed);
+ const focusedInputs: EventTarget[] = [];
+ container.addEventListener('focusin', (event) => {
+ if (event.target instanceof HTMLInputElement) {
+ focusedInputs.push(event.target);
+ }
+ });
+ renderEditPopup(root, currentTestBed, mobile);
const [labelInput, linkInput] = Array.from(container.querySelectorAll('input')) as HTMLInputElement[];
expect(labelInput.value).toBe('world');
expect(linkInput.value).toBe('https://univer.ai');
+ if (mobile) {
+ expect(focusedInputs).toEqual([labelInput]);
+ }
await act(async () => {
setInputText(labelInput, 'docs');
diff --git a/packages/docs-hyper-link-ui/src/views/hyper-link-edit/use-doc-hyper-link-edit.ts b/packages/docs-hyper-link-ui/src/views/hyper-link-edit/use-doc-hyper-link-edit.ts
new file mode 100644
index 0000000000..9ca5e3cd87
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/views/hyper-link-edit/use-doc-hyper-link-edit.ts
@@ -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 { DocumentDataModel } from '@univerjs/core';
+import {
+ BuildTextUtils,
+ getBodySlice,
+ ICommandService,
+ IUniverInstanceService,
+ Tools,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { DocSelectionManagerService } from '@univerjs/docs';
+import { useDependency, useObservable } from '@univerjs/ui';
+import { useEffect, useState } from 'react';
+import { AddDocHyperLinkCommand } from '../../commands/commands/add-link.command';
+import { UpdateDocHyperLinkCommand } from '../../commands/commands/update-link.command';
+import { DocHyperLinkPopupService } from '../../services/hyper-link-popup.service';
+import { isBlankInput } from './utils';
+
+function hasProtocol(url: string): boolean {
+ return /^[a-zA-Z]+:\/\//.test(url);
+}
+
+function isEmail(url: string): boolean {
+ return /^[\w.-]+@([\w-]+\.)+[\w-]{2,4}$/.test(url);
+}
+
+function transformUrl(url: string): string {
+ return hasProtocol(url) ? url : isEmail(url) ? `mailto://${url}` : `https://${url}`;
+}
+
+// eslint-disable-next-line max-lines-per-function
+export function useDocHyperLinkEdit() {
+ const hyperLinkService = useDependency(DocHyperLinkPopupService);
+ const editing = useObservable(hyperLinkService.editingLink$, hyperLinkService.editing);
+ const commandService = useDependency(ICommandService);
+ const univerInstanceService = useDependency(IUniverInstanceService);
+ const docSelectionManagerService = useDependency(DocSelectionManagerService);
+ const [link, setLink] = useState('');
+ const [label, setLabel] = useState('');
+ const [showError, setShowError] = useState(false);
+ const isLegal = Tools.isLegalUrl(link);
+ const doc = editing
+ ? univerInstanceService.getUnit<DocumentDataModel>(editing.unitId, UniverInstanceType.UNIVER_DOC)
+ : univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+
+ // eslint-disable-next-line complexity
+ useEffect(() => {
+ const activeRange = docSelectionManagerService.getActiveTextRange();
+ if (!activeRange) {
+ return;
+ }
+
+ if (editing) {
+ const body = doc?.getSelfOrHeaderFooterModel(editing.segmentId)?.getBody();
+ const matchedRange = body?.customRanges?.find((range) =>
+ editing.linkId === range.rangeId &&
+ range.startIndex === editing.startIndex &&
+ range.endIndex === editing.endIndex
+ );
+ if (doc && matchedRange) {
+ // Selection changes are the external source of truth for these controlled inputs.
+ // eslint-disable-next-line react/set-state-in-effect
+ setLink(matchedRange.properties?.url ?? '');
+ // eslint-disable-next-line react/set-state-in-effect
+ setLabel(BuildTextUtils.transform.getPlainText(getBodySlice(body!, matchedRange.startIndex, matchedRange.endIndex + 1).dataStream));
+ }
+ return;
+ }
+
+ const body = doc?.getSelfOrHeaderFooterModel(activeRange.segmentId)?.getBody();
+ const selection = body ? activeRange : null;
+ const matchedRange = selection && BuildTextUtils.customRange.getCustomRangesInterestsWithSelection(selection, body?.customRanges ?? [])?.[0];
+ if (doc && matchedRange) {
+ // eslint-disable-next-line react/set-state-in-effect
+ setLink(matchedRange.properties?.url ?? '');
+ }
+ }, [doc, docSelectionManagerService, editing]);
+
+ const handleCancel = () => hyperLinkService.hideEditPopup();
+ const handleConfirm = () => {
+ setShowError(true);
+ if (!isLegal || !doc) {
+ return;
+ }
+
+ const payload = transformUrl(link);
+ if (editing) {
+ if (isBlankInput(label)) {
+ return;
+ }
+ commandService.executeCommand(UpdateDocHyperLinkCommand.id, {
+ unitId: doc.getUnitId(),
+ payload,
+ linkId: editing.linkId,
+ label,
+ segmentId: editing.segmentId,
+ }).catch(() => undefined);
+ } else {
+ commandService.executeCommand(AddDocHyperLinkCommand.id, {
+ unitId: doc.getUnitId(),
+ payload,
+ }).catch(() => undefined);
+ }
+ hyperLinkService.hideEditPopup();
+ };
+
+ return {
+ doc,
+ editing,
+ handleCancel,
+ handleConfirm,
+ isLegal,
+ label,
+ link,
+ setLabel,
+ setLink,
+ showError,
+ };
+}
diff --git a/packages/docs-quick-insert-ui/package.json b/packages/docs-quick-insert-ui/package.json
index 33cbbac795..957d817b7f 100644
--- a/packages/docs-quick-insert-ui/package.json
+++ b/packages/docs-quick-insert-ui/package.json
@@ -88,6 +88,7 @@
},
"devDependencies": {
"@univerjs-infra/shared": "workspace:*",
+ "jest-canvas-mock": "^2.5.2",
"postcss": "^8.5.26",
"react": "18.3.1",
"rxjs": "^7.8.2",
diff --git a/packages/docs-quick-insert-ui/src/config/config.ts b/packages/docs-quick-insert-ui/src/config/config.ts
index 4bea3dbf0c..5486a890d3 100644
--- a/packages/docs-quick-insert-ui/src/config/config.ts
+++ b/packages/docs-quick-insert-ui/src/config/config.ts
@@ -17,6 +17,7 @@
import type { MenuConfig } from '@univerjs/ui';
export const DOCS_QUICK_INSERT_UI_PLUGIN_CONFIG_KEY = 'docs-quick-insert-ui.config';
+export const DOCS_QUICK_INSERT_UI_PLUGIN_NAME = 'DOC_QUICK_INSERT_UI_PLUGIN';
export const configSymbol = Symbol(DOCS_QUICK_INSERT_UI_PLUGIN_CONFIG_KEY);
diff --git a/packages/docs-quick-insert-ui/src/controllers/components.controller.ts b/packages/docs-quick-insert-ui/src/controllers/components.controller.ts
index 01d1515193..80cc8bff3b 100644
--- a/packages/docs-quick-insert-ui/src/controllers/components.controller.ts
+++ b/packages/docs-quick-insert-ui/src/controllers/components.controller.ts
@@ -24,7 +24,7 @@ import { QuickInsertPopup } from '../views/QuickInsertPopup';
export class ComponentsController extends Disposable {
constructor(
- @Inject(ComponentManager) private readonly _componentManager: ComponentManager,
+ @Inject(ComponentManager) protected readonly _componentManager: ComponentManager,
@Inject(IconManager) private readonly _iconManager: IconManager
) {
super();
@@ -40,9 +40,9 @@ export class ComponentsController extends Disposable {
}));
}
- private _registerComponents(): void {
+ protected _registerComponents(): void {
+ this._registerPopup();
([
- [QuickInsertPopup.componentKey, QuickInsertPopup],
[KeywordInputPlaceholder.componentKey, KeywordInputPlaceholder],
[QuickInsertPlaceholder.componentKey, QuickInsertPlaceholder],
[QuickInsertButton.componentKey, QuickInsertButton],
@@ -52,4 +52,8 @@ export class ComponentsController extends Disposable {
}
});
}
+
+ protected _registerPopup(): void {
+ this.disposeWithMe(this._componentManager.register(QuickInsertPopup.componentKey, QuickInsertPopup));
+ }
}
diff --git a/packages/docs-quick-insert-ui/src/controllers/mobile/components.controller.ts b/packages/docs-quick-insert-ui/src/controllers/mobile/components.controller.ts
new file mode 100644
index 0000000000..84bd8e34b6
--- /dev/null
+++ b/packages/docs-quick-insert-ui/src/controllers/mobile/components.controller.ts
@@ -0,0 +1,60 @@
+/**
+ * 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 { DividerIcon, TextIcon } from '@univerjs/icons';
+import { ComponentManager, IconManager } from '@univerjs/ui';
+import { KeywordInputPlaceholder } from '../../views/KeywordInputPlaceholder';
+import { MobileQuickInsertPopup } from '../../views/mobile/MobileQuickInsertPopup';
+import { QuickInsertButton } from '../../views/QuickInsertButton';
+import { QuickInsertPlaceholder } from '../../views/QuickInsertPlaceholder';
+import { QuickInsertPopup } from '../../views/QuickInsertPopup';
+
+export class MobileComponentsController extends Disposable {
+ constructor(
+ @Inject(ComponentManager) protected readonly _componentManager: ComponentManager,
+ @Inject(IconManager) private readonly _iconManager: IconManager
+ ) {
+ super();
+
+ this._registerIcons();
+ this._registerComponents();
+ }
+
+ private _registerIcons(): void {
+ this.disposeWithMe(this._iconManager.register({
+ DividerIcon,
+ TextIcon,
+ }));
+ }
+
+ protected _registerComponents(): void {
+ this._registerPopup();
+ ([
+ [KeywordInputPlaceholder.componentKey, KeywordInputPlaceholder],
+ [QuickInsertPlaceholder.componentKey, QuickInsertPlaceholder],
+ [QuickInsertButton.componentKey, QuickInsertButton],
+ ] as const).forEach(([key, comp]) => {
+ if (key) {
+ this.disposeWithMe(this._componentManager.register(key, comp));
+ }
+ });
+ }
+
+ protected _registerPopup(): void {
+ this.disposeWithMe(this._componentManager.register(QuickInsertPopup.componentKey, MobileQuickInsertPopup));
+ }
+}
diff --git a/packages/docs-quick-insert-ui/src/index.ts b/packages/docs-quick-insert-ui/src/index.ts
index c69194b409..e1e0bc889d 100644
--- a/packages/docs-quick-insert-ui/src/index.ts
+++ b/packages/docs-quick-insert-ui/src/index.ts
@@ -19,6 +19,7 @@ import './global.css';
export type { IUniverDocsQuickInsertUIConfig } from './config/config';
export { DocQuickInsertTriggerController } from './controllers/doc-quick-insert-trigger.controller';
export { DocQuickInsertUIController } from './controllers/ui.controller';
+export { UniverDocsQuickInsertMobileUIPlugin } from './mobile-plugin';
export { UniverDocsQuickInsertUIPlugin } from './plugin';
export type { DocPopupMenu, IDocPopup, IDocPopupGroupItem, IDocPopupMenuItem } from './services/doc-quick-insert-popup.service';
export { DocQuickInsertPopupService } from './services/doc-quick-insert-popup.service';
diff --git a/packages/docs-quick-insert-ui/src/mobile-plugin.ts b/packages/docs-quick-insert-ui/src/mobile-plugin.ts
new file mode 100644
index 0000000000..b43e4bef1c
--- /dev/null
+++ b/packages/docs-quick-insert-ui/src/mobile-plugin.ts
@@ -0,0 +1,93 @@
+/**
+ * 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 { IUniverDocsQuickInsertUIConfig } from './config/config';
+import { DependentOn, IConfigService, Inject, Injector, merge, Plugin, UniverInstanceType } from '@univerjs/core';
+import { UniverDocsPlugin } from '@univerjs/docs';
+import { UniverDocsDrawingPlugin } from '@univerjs/docs-drawing';
+import { UniverDocsDrawingMobileUIPlugin } from '@univerjs/docs-drawing-ui';
+import { UniverDocsMobileUIPlugin } from '@univerjs/docs-ui';
+import { UniverDrawingPlugin } from '@univerjs/drawing';
+import { UniverDrawingMobileUIPlugin } from '@univerjs/drawing-ui';
+import { IRenderManagerService, UniverRenderEnginePlugin } from '@univerjs/engine-render';
+import pkg from '../package.json';
+import { defaultPluginConfig, DOCS_QUICK_INSERT_UI_PLUGIN_CONFIG_KEY, DOCS_QUICK_INSERT_UI_PLUGIN_NAME } from './config/config';
+import { DocQuickInsertTriggerController } from './controllers/doc-quick-insert-trigger.controller';
+import { MobileComponentsController } from './controllers/mobile/components.controller';
+import { DocQuickInsertUIController } from './controllers/ui.controller';
+import { DocQuickInsertMenuController } from './menu/doc-quick-insert-menu.controller';
+import { DocQuickInsertPopupService } from './services/doc-quick-insert-popup.service';
+
+@DependentOn(
+ UniverDocsPlugin,
+ UniverDocsDrawingPlugin,
+ UniverDocsDrawingMobileUIPlugin,
+ UniverDocsMobileUIPlugin,
+ UniverDrawingPlugin,
+ UniverDrawingMobileUIPlugin,
+ UniverRenderEnginePlugin
+)
+export class UniverDocsQuickInsertMobileUIPlugin extends Plugin {
+ static override type = UniverInstanceType.UNIVER_DOC;
+ static override pluginName = DOCS_QUICK_INSERT_UI_PLUGIN_NAME;
+ static override packageName = pkg.name;
+ static override version = pkg.version;
+
+ constructor(
+ private readonly _config: Partial<IUniverDocsQuickInsertUIConfig> = defaultPluginConfig,
+ @Inject(Injector) protected override _injector: Injector,
+ @Inject(IRenderManagerService) private _renderManagerSrv: 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(DOCS_QUICK_INSERT_UI_PLUGIN_CONFIG_KEY, rest);
+ }
+
+ override onStarting(): void {
+ const dependencies: Dependency[] = [
+ [MobileComponentsController],
+ [DocQuickInsertUIController],
+ [DocQuickInsertTriggerController],
+ [DocQuickInsertPopupService],
+ ];
+
+ dependencies.forEach((dependency) => this._injector.add(dependency));
+
+ this._injector.get(MobileComponentsController);
+ this._injector.get(DocQuickInsertUIController);
+ }
+
+ override onRendered(): void {
+ this._injector.get(DocQuickInsertTriggerController);
+ this._injector.get(DocQuickInsertPopupService);
+
+ ([
+ [DocQuickInsertMenuController],
+ ] as Dependency[]).forEach((m) => {
+ this._renderManagerSrv.registerRenderModule(UniverInstanceType.UNIVER_DOC, m);
+ });
+ }
+}
diff --git a/packages/docs-quick-insert-ui/src/plugin.ts b/packages/docs-quick-insert-ui/src/plugin.ts
index 50f81cb6bd..3d3a978a3b 100644
--- a/packages/docs-quick-insert-ui/src/plugin.ts
+++ b/packages/docs-quick-insert-ui/src/plugin.ts
@@ -25,7 +25,7 @@ import { UniverDrawingPlugin } from '@univerjs/drawing';
import { UniverDrawingUIPlugin } from '@univerjs/drawing-ui';
import { IRenderManagerService, UniverRenderEnginePlugin } from '@univerjs/engine-render';
import pkg from '../package.json';
-import { defaultPluginConfig, DOCS_QUICK_INSERT_UI_PLUGIN_CONFIG_KEY } from './config/config';
+import { defaultPluginConfig, DOCS_QUICK_INSERT_UI_PLUGIN_CONFIG_KEY, DOCS_QUICK_INSERT_UI_PLUGIN_NAME } from './config/config';
import { ComponentsController } from './controllers/components.controller';
import { DocQuickInsertTriggerController } from './controllers/doc-quick-insert-trigger.controller';
import { DocQuickInsertUIController } from './controllers/ui.controller';
@@ -43,7 +43,7 @@ import { DocQuickInsertPopupService } from './services/doc-quick-insert-popup.se
)
export class UniverDocsQuickInsertUIPlugin extends Plugin {
static override type = UniverInstanceType.UNIVER_DOC;
- static override pluginName = 'DOC_QUICK_INSERT_UI_PLUGIN';
+ static override pluginName = DOCS_QUICK_INSERT_UI_PLUGIN_NAME;
static override packageName = pkg.name;
static override version = pkg.version;
@@ -68,9 +68,8 @@ export class UniverDocsQuickInsertUIPlugin extends Plugin {
}
override onStarting(): void {
- this._injector.add([ComponentsController]);
- this._injector.get(ComponentsController);
const dependencies: Dependency[] = [
+ [ComponentsController],
[DocQuickInsertUIController],
[DocQuickInsertTriggerController],
[DocQuickInsertPopupService],
@@ -78,6 +77,7 @@ export class UniverDocsQuickInsertUIPlugin extends Plugin {
dependencies.forEach((dependency) => this._injector.add(dependency));
+ this._injector.get(ComponentsController);
this._injector.get(DocQuickInsertUIController);
}
diff --git a/packages/docs-quick-insert-ui/src/services/__tests__/doc-quick-insert-popup.service.spec.ts b/packages/docs-quick-insert-ui/src/services/__tests__/doc-quick-insert-popup.service.spec.ts
index 0956b03249..db1ab48960 100644
--- a/packages/docs-quick-insert-ui/src/services/__tests__/doc-quick-insert-popup.service.spec.ts
+++ b/packages/docs-quick-insert-ui/src/services/__tests__/doc-quick-insert-popup.service.spec.ts
@@ -14,201 +14,108 @@
* limitations under the License.
*/
-import { DocSkeletonManagerService } from '@univerjs/docs';
-import { DocEventManagerService } from '@univerjs/docs-ui';
+import type { DocumentDataModel, IDocumentData } from '@univerjs/core';
+import { createRequire } from 'node:module';
+import { DocumentFlavor, Univer, UniverInstanceType } from '@univerjs/core';
+import { DocLayoutExecutorService, DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';
+import { DocCanvasPopManagerService, DocEventManagerService, DocLayoutInteractionService } from '@univerjs/docs-ui';
+import { CanvasColorService, Documents, ICanvasColorService, IRenderManagerService, RenderManagerService, RenderUnit } from '@univerjs/engine-render';
+import { CanvasPopupService, ICanvasPopupService } from '@univerjs/ui';
import { of } from 'rxjs';
-import { describe, expect, it, vi } from 'vitest';
-import { DeleteSearchKeyCommand } from '../../commands/commands/doc-quick-insert.command';
-import { KeywordInputPlaceholder } from '../../views/KeywordInputPlaceholder';
-import { QuickInsertPopup } from '../../views/QuickInsertPopup';
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { DocQuickInsertPopupService } from '../doc-quick-insert-popup.service';
-function createPopupDisposable() {
- return {
- dispose: vi.fn(),
- canDispose: vi.fn(() => true),
- };
-}
-
-function createServiceTestBed() {
- let dataStream = '/';
- const paragraphBound = {
- firstLine: { left: 0, top: 0, right: 10, bottom: 20 },
- };
- const popupEntries: Array<{
- rect: unknown;
- popup: { componentKey: string; extraProps?: unknown };
- disposable: ReturnType<typeof createPopupDisposable>;
- }> = [];
- const activeRange = {
- startOffset: 1,
- endOffset: 1,
- segmentId: '',
- segmentPage: -1,
- };
- const glyph = {
- content: '\r',
- ts: { fs: 11, ff: 'Arial' },
- fontStyle: {
- fontString: '14.6666666667px Arial',
- fontFamily: 'Arial',
- },
- bBox: {
- ba: 10,
- bd: 4,
- },
- };
- const docDataModel = {
- getBody: () => ({
- dataStream,
- paragraphs: [{ startIndex: 1, paragraphId: 'para_quick_insert_test' }],
- }),
- };
- const docEventManagerService = {
- findParagraphBoundByIndex: vi.fn(() => paragraphBound),
- };
- let layoutInteractionActive = false;
- const skeleton = {
- findNodeByCharIndex: vi.fn(() => glyph),
- findNodePositionByCharIndex: vi.fn(() => undefined),
- };
- const currentRender = {
- with: vi.fn((token: unknown) => {
- if (token === DocEventManagerService) {
- return docEventManagerService;
- }
- if (token === DocSkeletonManagerService) {
- return { getSkeleton: () => skeleton };
- }
- return undefined;
- }),
- mainComponent: {
- getOffsetConfig: () => ({ docsLeft: 0, docsTop: 0 }),
- },
- };
- const docCanvasPopupManagerService = {
- attachPopupToRect: vi.fn((rect: unknown, popup: { componentKey: string; extraProps?: unknown }) => {
- const disposable = createPopupDisposable();
- popupEntries.push({ rect, popup, disposable });
- return disposable;
- }),
- };
- const docLayoutInteractionService = {
- beginInteraction: vi.fn(() => {
- layoutInteractionActive = true;
- return {
- dispose: () => {
- layoutInteractionActive = false;
- },
- };
- }),
- };
- const commandService = {
- syncExecuteCommand: vi.fn(() => true),
- };
-
- const service = new DocQuickInsertPopupService(
- docCanvasPopupManagerService as never,
- {
- getCurrentUnitOfType: vi.fn(() => docDataModel),
- getUnit: vi.fn(() => docDataModel),
- } as never,
- commandService as never,
- {
- getRenderUnitById: vi.fn(() => currentRender),
- } as never,
- {
- getActiveTextRange: vi.fn(() => activeRange),
- } as never,
- docLayoutInteractionService as never
- );
-
- return {
- service,
- popupEntries,
- commandService,
- isLayoutInteractionActive: () => layoutInteractionActive,
- paragraphBound,
- setDataStream: (value: string) => {
- dataStream = value;
- },
- };
+beforeAll(() => {
+ vi.stubGlobal('jest', vi);
+ createRequire(import.meta.url)('jest-canvas-mock');
+});
+afterAll(() => vi.unstubAllGlobals());
+
+function createTestBed() {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
+ injector.add([ICanvasColorService, { useClass: CanvasColorService }]);
+ injector.add([ICanvasPopupService, { useClass: CanvasPopupService }]);
+ injector.add([DocLayoutExecutorService]);
+ injector.add([DocSelectionManagerService]);
+ injector.add([DocCanvasPopManagerService]);
+ injector.add([DocQuickInsertPopupService]);
+ return { univer, injector };
}
describe('DocQuickInsertPopupService', () => {
- it('registers popups, resolves them by trigger and emits selected menus after deleting the search key', () => {
- vi.useFakeTimers();
-
- const { service, commandService } = createServiceTestBed();
- const popup = {
- keyword: '/',
- menus$: of([]),
- };
- const menu = {
- id: 'menu-1',
- title: 'Text',
- };
- const onSelected = vi.fn();
-
- const unregisterPopup = service.registerPopup(popup);
- const unregisterHandler = service.onMenuSelected(onSelected);
-
- expect(service.resolvePopup('/')).toBe(popup);
-
- service.setInputOffset({ start: 2, end: 4 });
- service.emitMenuSelected(menu as never);
-
- expect(commandService.syncExecuteCommand).toHaveBeenCalledWith(DeleteSearchKeyCommand.id, { start: 2, end: 4 });
- expect(onSelected).not.toHaveBeenCalled();
-
- vi.runAllTimers();
- expect(onSelected).toHaveBeenCalledWith(menu);
-
- unregisterHandler();
- unregisterPopup();
- expect(service.resolvePopup('/')).toBeUndefined();
-
- service.dispose();
- vi.useRealTimers();
+ it('uses the target document layout interaction instead of a global service', () => {
+ const { univer, injector } = createTestBed();
+ try {
+ const model = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, {
+ id: 'quick-insert-doc',
+ body: {
+ dataStream: '/\r\n',
+ paragraphs: [{ startIndex: 1, paragraphId: 'paragraph-1' }],
+ sectionBreaks: [{ startIndex: 2, sectionId: 'body' }],
+ },
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 300, height: 400 },
+ marginTop: 20,
+ marginBottom: 20,
+ marginLeft: 20,
+ marginRight: 20,
+ },
+ });
+ const render = injector.get(IRenderManagerService).createRender(model.getUnitId());
+ if (!(render instanceof RenderUnit)) {
+ throw new TypeError('Expected a render unit');
+ }
+ render.deactivate();
+ render.engine.resizeBySize(300, 400);
+ render.addRenderDependencies([[DocSkeletonManagerService], [DocLayoutInteractionService]]);
+ const documents = new Documents('quick-insert-doc', render.with(DocSkeletonManagerService).getSkeleton());
+ render.mainComponent = documents;
+ render.scene.addObject(documents);
+ render.addRenderDependencies([[DocEventManagerService]]);
+ injector.get(DocSelectionManagerService).replaceDocRanges([{
+ startOffset: 1,
+ endOffset: 1,
+ collapsed: true,
+ segmentId: '',
+ }]);
+ const service = injector.get(DocQuickInsertPopupService);
+ const interaction = render.with(DocLayoutInteractionService);
+ const popup = { keyword: '/', menus$: of([]) };
+ const unregister = service.registerPopup(popup);
+ expect(service.resolvePopup('/')).toBe(popup);
+ service.showPopup({ popup, index: 0, unitId: model.getUnitId() });
+ expect(service.editPopup?.unitId).toBe(model.getUnitId());
+ expect(interaction.isActive).toBe(true);
+ service.setIsComposing(true);
+ service.setIsComposing(false);
+ service.closePopup();
+ service.closePopup();
+ expect(interaction.isActive).toBe(false);
+ expect(service.editPopup).toBeNull();
+ service.showPopup({ popup, index: 0, unitId: model.getUnitId() });
+ expect(interaction.isActive).toBe(true);
+ service.dispose();
+ service.dispose();
+ expect(interaction.isActive).toBe(false);
+ expect(injector.get(ICanvasPopupService).popups).toHaveLength(0);
+ unregister();
+ expect(service.resolvePopup('/')).toBeUndefined();
+ } finally {
+ univer.dispose();
+ }
});
- it('shows the popup on an empty line and remounts the keyword placeholder as input state changes', () => {
- const { service, popupEntries, isLayoutInteractionActive, setDataStream } = createServiceTestBed();
- const popup = {
- keyword: '/',
- menus$: of([]),
- };
-
- service.showPopup({ popup, index: 0, unitId: 'doc-1' });
-
- expect(popupEntries).toHaveLength(2);
- expect(popupEntries[0].popup.componentKey).toBe(KeywordInputPlaceholder.componentKey);
- expect(popupEntries[1].popup.componentKey).toBe(QuickInsertPopup.componentKey);
- expect(isLayoutInteractionActive()).toBe(true);
- expect(service.editPopup).toEqual(expect.objectContaining({ popup, anchor: 0, unitId: 'doc-1' }));
-
- setDataStream('/a');
- service.setInputOffset({ start: 0, end: 2 });
- expect(popupEntries[0].disposable.dispose).toHaveBeenCalledTimes(1);
-
- setDataStream('/');
- service.setInputOffset({ start: 0, end: 1 });
- expect(popupEntries).toHaveLength(3);
- expect(popupEntries[2].popup.componentKey).toBe(KeywordInputPlaceholder.componentKey);
-
- service.setIsComposing(true);
- expect(popupEntries[2].disposable.dispose).toHaveBeenCalledTimes(1);
-
- service.setIsComposing(false);
- expect(popupEntries).toHaveLength(4);
- expect(popupEntries[3].popup.componentKey).toBe(KeywordInputPlaceholder.componentKey);
-
- service.closePopup();
- expect(popupEntries[1].disposable.dispose).toHaveBeenCalledTimes(1);
- expect(popupEntries[3].disposable.dispose).toHaveBeenCalledTimes(1);
- expect(service.editPopup).toBeNull();
- expect(isLayoutInteractionActive()).toBe(false);
-
- service.dispose();
+ it('does not open a popup for a document without a render', () => {
+ const { univer, injector } = createTestBed();
+ try {
+ const service = injector.get(DocQuickInsertPopupService);
+ service.showPopup({ popup: { keyword: '/', menus$: of([]) }, index: 0, unitId: 'missing' });
+ expect(service.editPopup).toBeUndefined();
+ } finally {
+ univer.dispose();
+ }
});
});
diff --git a/packages/docs-quick-insert-ui/src/services/doc-quick-insert-popup.service.ts b/packages/docs-quick-insert-ui/src/services/doc-quick-insert-popup.service.ts
index 752243d99b..99d4ce674d 100644
--- a/packages/docs-quick-insert-ui/src/services/doc-quick-insert-popup.service.ts
+++ b/packages/docs-quick-insert-ui/src/services/doc-quick-insert-popup.service.ts
@@ -126,12 +126,18 @@ export class DocQuickInsertPopupService extends Disposable {
@Inject(IUniverInstanceService) private readonly _univerInstanceService: IUniverInstanceService,
@Inject(ICommandService) private readonly _commandService: ICommandService,
@Inject(IRenderManagerService) private readonly _renderManagerService: IRenderManagerService,
- @Inject(DocSelectionManagerService) private readonly _docSelectionManagerService: DocSelectionManagerService,
- @Inject(DocLayoutInteractionService) private readonly _docLayoutInteractionService: DocLayoutInteractionService
+ @Inject(DocSelectionManagerService) private readonly _docSelectionManagerService: DocSelectionManagerService
) {
super();
this.disposeWithMe(this._editPopup$);
+ this.disposeWithMe(this._isComposing$);
+ this.disposeWithMe(this._inputOffset$);
+ this.disposeWithMe(this._renderManagerService.disposed$.subscribe((unitId) => {
+ if (this.editPopup?.unitId === unitId) {
+ this.closePopup();
+ }
+ }));
const getBodySlice = (start: number, end: number) => this._univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)?.getBody()?.dataStream.slice(start, end);
@@ -173,6 +179,16 @@ export class DocQuickInsertPopupService extends Disposable {
]).subscribe());
}
+ override dispose(): void {
+ if (this._disposed) {
+ return;
+ }
+ this.closePopup();
+ this._menuSelectedCallbacks.clear();
+ this._popups.clear();
+ super.dispose();
+ }
+
resolvePopup(keyword: string) {
return Array.from(this._popups).find((popup) => popup.keyword === keyword);
}
@@ -306,6 +322,10 @@ export class DocQuickInsertPopupService extends Disposable {
showPopup(options: { popup: IDocPopup; index: number; unitId: string }) {
const { popup, index, unitId } = options;
this.closePopup();
+ const render = this._renderManagerService.getRenderUnitById(unitId);
+ if (!render) {
+ return;
+ }
const paragraphBound = this._getParagraphBound(unitId, index);
if (!paragraphBound) {
return;
@@ -314,7 +334,7 @@ export class DocQuickInsertPopupService extends Disposable {
this._inputPlaceholderRenderRoot = this._createInputPlaceholderRenderRoot(() => this._mountInputPlaceholder(unitId, paragraphBound.firstLine));
this._inputPlaceholderRenderRoot.mount();
- const layoutInteraction = this._docLayoutInteractionService.beginInteraction();
+ const layoutInteraction = render.with(DocLayoutInteractionService).beginInteraction();
const popupDisposable = this._docCanvasPopupManagerService.attachPopupToRect(
paragraphBound.firstLine,
{
diff --git a/packages/docs-quick-insert-ui/src/views/QuickInsertMenu.tsx b/packages/docs-quick-insert-ui/src/views/QuickInsertMenu.tsx
index fb4e68642f..c0576a61b2 100644
--- a/packages/docs-quick-insert-ui/src/views/QuickInsertMenu.tsx
+++ b/packages/docs-quick-insert-ui/src/views/QuickInsertMenu.tsx
@@ -131,14 +131,13 @@ export function QuickInsertMenu(props: IQuickInsertMenuProps) {
role="button"
tabIndex={-1}
className={clsx(`
- univer-relative univer-box-border univer-flex univer-min-h-8 univer-w-full univer-cursor-pointer
+ univer-relative univer-box-border univer-flex univer-w-full univer-cursor-pointer
univer-items-center univer-justify-between univer-gap-3 univer-rounded-md univer-border-none
univer-bg-transparent univer-px-2 univer-text-left univer-text-sm univer-text-gray-900
univer-outline-none
- hover:univer-bg-gray-50
dark:!univer-text-gray-0
- dark:hover:!univer-bg-gray-600
`, {
+ 'univer-min-h-8 hover:univer-bg-gray-50 dark:hover:!univer-bg-gray-600': true,
'hover:univer-bg-transparent': !isFocused,
'univer-bg-gray-50 dark:!univer-bg-gray-600': isFocused,
})}
@@ -160,11 +159,12 @@ export function QuickInsertMenu(props: IQuickInsertMenuProps) {
return (
<div
className={clsx(`
- univer-box-border univer-grid univer-max-h-[360px] univer-gap-1 univer-overflow-y-auto
- univer-overflow-x-hidden univer-overscroll-contain univer-rounded-md univer-bg-gray-0 univer-px-2
- univer-py-1 univer-text-sm univer-text-gray-900 univer-shadow-md
+ univer-box-border univer-grid univer-gap-1 univer-overflow-y-auto univer-overflow-x-hidden
+ univer-overscroll-contain univer-bg-gray-0 univer-px-2 univer-text-gray-900 univer-shadow-md
dark:!univer-bg-gray-700 dark:!univer-text-gray-0
- `, borderClassName, scrollbarClassName)}
+ `, borderClassName, scrollbarClassName, {
+ 'univer-max-h-[360px] univer-rounded-md univer-py-1 univer-text-sm': true,
+ })}
onWheel={(event) => event.stopPropagation()}
>
{renderMenus(menus)}
diff --git a/packages/docs-quick-insert-ui/src/views/QuickInsertPopup.tsx b/packages/docs-quick-insert-ui/src/views/QuickInsertPopup.tsx
index bf004bf55d..2fa717b4b4 100644
--- a/packages/docs-quick-insert-ui/src/views/QuickInsertPopup.tsx
+++ b/packages/docs-quick-insert-ui/src/views/QuickInsertPopup.tsx
@@ -14,108 +14,33 @@
* limitations under the License.
*/
-import type { DocPopupMenu, IDocPopupMenuItem } from '../services/doc-quick-insert-popup.service';
+import type { IDocPopupMenuItem } from '../services/doc-quick-insert-popup.service';
import {
CommandType,
Direction,
DisposableCollection,
generateRandomId,
ICommandService,
- LocaleService,
toDisposable,
} from '@univerjs/core';
-import { IShortcutService, KeyCode, useDependency, useObservable } from '@univerjs/ui';
+import { IShortcutService, KeyCode, useDependency } from '@univerjs/ui';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { CloseQuickInsertPopupOperation } from '../commands/operations/quick-insert-popup.operation';
-import { DocQuickInsertPopupService } from '../services/doc-quick-insert-popup.service';
import { getQuickInsertMenuLeafCount, QuickInsertMenu } from './QuickInsertMenu';
-import { QuickInsertPlaceholder } from './QuickInsertPlaceholder';
-function filterMenusByKeyword(menus: DocPopupMenu[], keyword: string) {
- return menus
- .map((menu) => ({ ...menu }))
- .filter((menu) => {
- if ('children' in menu) {
- menu.children = filterMenusByKeyword(menu.children!, keyword) as IDocPopupMenuItem[];
-
- return menu.children.length > 0;
- }
-
- const keywords = (menu as IDocPopupMenuItem).keywords;
-
- if (keywords) {
- return keywords.some((word) => word.includes(keyword));
- }
-
- return menu.title.toLowerCase().includes(keyword);
- });
-}
-
-function translateMenus(menus: DocPopupMenu[], localeService: LocaleService) {
- return menus.map((_menu) => {
- const menu = { ..._menu } as DocPopupMenu;
- if ('children' in menu) {
- menu.children = translateMenus(menu.children!, localeService) as IDocPopupMenuItem[];
- }
-
- menu.title = localeService.t(menu.title);
-
- if ('keywords' in menu) {
- menu.keywords = menu.keywords!
- .concat(menu.title)
- .map((word) => word.toLowerCase());
- }
-
- return menu;
- });
-}
+import { useQuickInsertPopup } from './use-quick-insert-popup';
const interceptKeys = [KeyCode.ARROW_UP, KeyCode.ARROW_DOWN, KeyCode.ENTER];
export const QuickInsertPopup = () => {
- const localeService = useDependency(LocaleService);
- const docQuickInsertPopupService = useDependency(DocQuickInsertPopupService);
const shortcutService = useDependency(IShortcutService);
const commandService = useDependency(ICommandService);
-
const id = useMemo(() => generateRandomId(), []);
-
+ const { filteredMenus, handleMenuSelect, Placeholder } = useQuickInsertPopup();
const [focusedMenuIndex, setFocusedMenuIndex] = useState(0);
const focusedMenuRef = useRef<IDocPopupMenuItem | null>(null);
-
- const filterKeyword = useObservable(docQuickInsertPopupService.filterKeyword$, '');
- const currentPopup = useObservable(docQuickInsertPopupService.editPopup$);
- const menus = useObservable<DocPopupMenu[]>(currentPopup?.popup.menus$, []);
-
- const translatedMenus = useMemo(() => {
- return translateMenus(menus, localeService);
- }, [menus]);
-
- const [filteredMenus, setFilteredMenus] = useState<DocPopupMenu[]>(() => {
- return filterMenusByKeyword(translatedMenus, filterKeyword.toLowerCase());
- });
- const filteredMenuCount = useMemo(() => getQuickInsertMenuLeafCount(filteredMenus), [filteredMenus]);
+ const filteredMenuCount = getQuickInsertMenuLeafCount(filteredMenus);
const filteredMenuCountRef = useRef(filteredMenuCount);
-
- useEffect(() => {
- filteredMenuCountRef.current = filteredMenuCount;
- }, [filteredMenuCount]);
-
- useEffect(() => {
- const id = requestIdleCallback(() => {
- setFilteredMenus(filterMenusByKeyword(translatedMenus, filterKeyword.toLowerCase()));
- });
-
- return () => {
- cancelIdleCallback(id);
- };
- }, [translatedMenus, filterKeyword]);
-
- const handleMenuSelect = (menu: IDocPopupMenuItem) => {
- docQuickInsertPopupService.emitMenuSelected(menu);
- commandService.executeCommand(CloseQuickInsertPopupOperation.id);
- };
-
+ filteredMenuCountRef.current = filteredMenuCount;
const handleFocusedMenuChange = useCallback((menu: IDocPopupMenuItem | null) => {
focusedMenuRef.current = menu;
}, []);
@@ -222,8 +147,6 @@ export const QuickInsertPopup = () => {
const hasMenus = filteredMenus.length > 0;
- const Placeholder = currentPopup?.popup.Placeholder || QuickInsertPlaceholder;
-
return (
<div className="univer-mt-2">
{hasMenus
diff --git a/packages/docs-quick-insert-ui/src/views/__tests__/QuickInsertPopup.spec.tsx b/packages/docs-quick-insert-ui/src/views/__tests__/QuickInsertPopup.spec.tsx
index c6465c24f7..6b2aea92f6 100644
--- a/packages/docs-quick-insert-ui/src/views/__tests__/QuickInsertPopup.spec.tsx
+++ b/packages/docs-quick-insert-ui/src/views/__tests__/QuickInsertPopup.spec.tsx
@@ -14,28 +14,18 @@
* limitations under the License.
*/
+import type { DocumentDataModel, IDocumentData } from '@univerjs/core';
import type { Root } from 'react-dom/client';
import type { DocPopupMenu } from '../../services/doc-quick-insert-popup.service';
-import {
- CommandService,
- CommandType,
- ConfigService,
- ContextService,
- DesktopLogService,
- ICommandService,
- IConfigService,
- IContextService,
- ILogService,
- Injector,
- IUniverInstanceService,
- LocaleService,
- LocaleType,
-} from '@univerjs/core';
-import { DocSelectionManagerService } from '@univerjs/docs';
+import { createRequire } from 'node:module';
+import { DocumentFlavor, ICommandService, LocaleService, LocaleType, Univer, UniverInstanceType } from '@univerjs/core';
+import { DocLayoutExecutorService, DocSelectionManagerService, DocSkeletonManagerService, DocStateEmitService, RichTextEditingMutation } from '@univerjs/docs';
import { CutContentCommand, DocCanvasPopManagerService, DocEventManagerService, DocLayoutInteractionService } from '@univerjs/docs-ui';
-import { IRenderManagerService } from '@univerjs/engine-render';
+import { CanvasColorService, Documents, ICanvasColorService, IRenderManagerService, RenderManagerService, RenderUnit } from '@univerjs/engine-render';
import {
+ CanvasPopupService,
ComponentManager,
+ ICanvasPopupService,
IconManager,
IPlatformService,
IShortcutService,
@@ -49,126 +39,80 @@ import {
import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { BehaviorSubject } from 'rxjs';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { DeleteSearchKeyCommand } from '../../commands/commands/doc-quick-insert.command';
import { CloseQuickInsertPopupOperation } from '../../commands/operations/quick-insert-popup.operation';
import { DocQuickInsertPopupService } from '../../services/doc-quick-insert-popup.service';
import { QuickInsertPlaceholder } from '../QuickInsertPlaceholder';
import { QuickInsertPopup } from '../QuickInsertPopup';
-(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+const testUnivers: Univer[] = [];
+beforeAll(() => {
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
+ vi.stubGlobal('jest', vi);
+ createRequire(import.meta.url)('jest-canvas-mock');
+});
+afterAll(() => vi.unstubAllGlobals());
const TEST_DOC_UNIT_ID = 'doc-quick-insert-test';
-class TestUniverInstanceService {
- dataStream = '/ta\r\n';
-
- private readonly _doc = {
- getUnitId: () => TEST_DOC_UNIT_ID,
- getBody: () => ({
- dataStream: this.dataStream,
- paragraphs: [{ startIndex: 3, paragraphId: 'para_quick_insert_popup_test' }],
- }),
- };
-
- getCurrentUnitOfType() {
- return this._doc;
- }
-
- getUnit() {
- return this._doc;
- }
-}
-
-class TestDocCanvasPopManagerService {
- readonly attachedPopups: Array<{
- componentKey?: string;
- disposed: boolean;
- }> = [];
-
- attachPopupToRect(_rect: unknown, popup: { componentKey?: string }) {
- const entry = {
- componentKey: popup.componentKey,
- disposed: false,
- };
-
- this.attachedPopups.push(entry);
-
- return {
- dispose: () => {
- entry.disposed = true;
- },
- };
- }
-}
-
-class TestDocLayoutInteractionService {
- beginInteraction() {
- return {
- dispose: () => {},
- };
- }
-}
-
-class TestRenderManagerService {
- getRenderUnitById() {
- return {
- with(token: unknown) {
- if (token === DocEventManagerService) {
- return {
- findParagraphBoundByIndex: () => ({
- firstLine: {
- left: 0,
- top: 0,
- right: 120,
- bottom: 24,
- },
- }),
- };
- }
-
- return undefined;
- },
- mainComponent: {
- getOffsetConfig: () => ({ docsLeft: 0, docsTop: 0 }),
- },
- };
- }
-}
-
-class TestDocSelectionManagerService {
- getActiveTextRange() {
- return null;
- }
-}
-
function createQuickInsertPopupTestBed(options?: {
dataStream?: string;
inputOffset?: { start: number; end: number };
}) {
- const injector = new Injector();
+ const univer = new Univer();
+ testUnivers.push(univer);
+ const injector = univer.__getInjector();
let cutContentParams: unknown;
let selectedMenu: unknown;
- injector.add([ILogService, { useClass: DesktopLogService }]);
- injector.add([IConfigService, { useClass: ConfigService }]);
- injector.add([IContextService, { useClass: ContextService }]);
- injector.add([ICommandService, { useClass: CommandService }]);
- injector.add([LocaleService, { useClass: LocaleService }]);
injector.add([IPlatformService, { useClass: PlatformService }]);
injector.add([IUIRuntimeScopeService, { useClass: UIRuntimeScopeService }]);
injector.add([IShortcutService, { useClass: ShortcutService }]);
injector.add([ComponentManager, { useClass: ComponentManager }]);
injector.add([IconManager, { useClass: IconManager }]);
- injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
- injector.add([DocCanvasPopManagerService, { useClass: TestDocCanvasPopManagerService as never }]);
- injector.add([DocLayoutInteractionService, { useClass: TestDocLayoutInteractionService as never }]);
- injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);
- injector.add([DocSelectionManagerService, { useClass: TestDocSelectionManagerService as never }]);
- injector.add([DocQuickInsertPopupService, { useClass: DocQuickInsertPopupService }]);
-
- const univerInstanceService = injector.get(IUniverInstanceService) as unknown as TestUniverInstanceService;
- univerInstanceService.dataStream = options?.dataStream ?? '/ta\r\n';
+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
+ injector.add([ICanvasColorService, { useClass: CanvasColorService }]);
+ injector.add([ICanvasPopupService, { useClass: CanvasPopupService }]);
+ injector.add([DocLayoutExecutorService]);
+ injector.add([DocSelectionManagerService]);
+ injector.add([DocStateEmitService]);
+ injector.add([DocCanvasPopManagerService]);
+ injector.add([DocQuickInsertPopupService]);
+ const dataStream = options?.dataStream ?? '/ta\r\n';
+ const model = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, {
+ id: TEST_DOC_UNIT_ID,
+ body: {
+ dataStream,
+ paragraphs: [{ startIndex: dataStream.length - 2, paragraphId: 'popup-paragraph' }],
+ sectionBreaks: [{ startIndex: dataStream.length - 1, sectionId: 'body' }],
+ },
+ documentStyle: {
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ pageSize: { width: 300, height: 400 },
+ marginTop: 20,
+ marginBottom: 20,
+ marginLeft: 20,
+ marginRight: 20,
+ },
+ });
+ const render = injector.get(IRenderManagerService).createRender(model.getUnitId());
+ if (!(render instanceof RenderUnit)) {
+ throw new TypeError('Expected a render unit');
+ }
+ render.deactivate();
+ render.engine.resizeBySize(300, 400);
+ render.addRenderDependencies([[DocSkeletonManagerService], [DocLayoutInteractionService]]);
+ const documents = new Documents(TEST_DOC_UNIT_ID, render.with(DocSkeletonManagerService).getSkeleton());
+ render.mainComponent = documents;
+ render.scene.addObject(documents);
+ render.addRenderDependencies([[DocEventManagerService]]);
+ injector.get(DocSelectionManagerService).replaceDocRanges([{
+ startOffset: dataStream.length - 2,
+ endOffset: dataStream.length - 2,
+ collapsed: true,
+ segmentId: '',
+ }]);
const localeService = injector.get(LocaleService);
localeService.load({
@@ -186,19 +130,19 @@ function createQuickInsertPopupTestBed(options?: {
},
});
+ localeService.setLocale(LocaleType.ZH_CN);
const componentManager = injector.get(ComponentManager);
componentManager.register(QuickInsertPlaceholder.componentKey, QuickInsertPlaceholder);
const commandService = injector.get(ICommandService);
commandService.registerCommand(CloseQuickInsertPopupOperation);
commandService.registerCommand(DeleteSearchKeyCommand);
- commandService.registerCommand({
- id: CutContentCommand.id,
- type: CommandType.COMMAND,
- handler: (_accessor, params) => {
- cutContentParams = params;
- return true;
- },
+ commandService.registerCommand(CutContentCommand);
+ commandService.registerCommand(RichTextEditingMutation);
+ commandService.onCommandExecuted((command) => {
+ if (command.id === CutContentCommand.id) {
+ cutContentParams = command.params;
+ }
});
const menus$ = new BehaviorSubject<DocPopupMenu[]>([
@@ -238,7 +182,8 @@ function createQuickInsertPopupTestBed(options?: {
getSelectedMenu: () => selectedMenu,
injector,
popupService,
- popupManagerService: injector.get(DocCanvasPopManagerService) as unknown as TestDocCanvasPopManagerService,
+ popupManagerService: injector.get(ICanvasPopupService),
+ model,
};
}
@@ -278,6 +223,7 @@ describe('QuickInsertPopup', () => {
root.unmount();
});
container.remove();
+ testUnivers.splice(0).forEach((univer) => univer.dispose());
if (scrollIntoViewDescriptor) {
Object.defineProperty(Element.prototype, 'scrollIntoView', scrollIntoViewDescriptor);
} else {
@@ -298,7 +244,7 @@ describe('QuickInsertPopup', () => {
});
it('filters the popup menu by the typed keyword and closes the popup after selecting a business menu item', async () => {
- const { getCutContentParams, getSelectedMenu, injector, popupManagerService, popupService } = createQuickInsertPopupTestBed();
+ const { getCutContentParams, getSelectedMenu, injector, model, popupManagerService, popupService } = createQuickInsertPopupTestBed();
await act(async () => {
root.render(
@@ -312,8 +258,8 @@ describe('QuickInsertPopup', () => {
expect(container.textContent).toContain('Table');
expect(container.textContent).not.toContain('Image');
- const tableMenuItem = Array.from(container.querySelectorAll('[role="button"]'))
- .find((node) => node.textContent === 'Table') as HTMLElement | undefined;
+ const tableMenuItem = Array.from(container.querySelectorAll<HTMLElement>('[role="button"]'))
+ .find((node) => node.textContent === 'Table');
expect(tableMenuItem).toBeDefined();
@@ -331,7 +277,8 @@ describe('QuickInsertPopup', () => {
selections: [expect.objectContaining({ startOffset: 0, endOffset: 3 })],
}));
expect(popupService.editPopup).toBeNull();
- expect(popupManagerService.attachedPopups.find((popup) => popup.componentKey === QuickInsertPopup.componentKey)?.disposed).toBe(true);
+ expect(popupManagerService.popups).toHaveLength(0);
+ expect(model.getBody()?.dataStream).toBe('\r\n');
});
it('uses popup keyboard commands to move focus and select the focused business menu item', async () => {
diff --git a/packages/docs-quick-insert-ui/src/views/mobile/MobileQuickInsertPopup.tsx b/packages/docs-quick-insert-ui/src/views/mobile/MobileQuickInsertPopup.tsx
new file mode 100644
index 0000000000..69aa354d1e
--- /dev/null
+++ b/packages/docs-quick-insert-ui/src/views/mobile/MobileQuickInsertPopup.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 { DocPopupMenu, IDocPopupMenuItem } from '../../services/doc-quick-insert-popup.service';
+import { Button, clsx, scrollbarClassName } from '@univerjs/design';
+import { IconManager, useDependency } from '@univerjs/ui';
+import { useQuickInsertPopup } from '../use-quick-insert-popup';
+
+function MobileQuickInsertItems({ menus, onSelect }: { menus: DocPopupMenu[]; onSelect: (menu: IDocPopupMenuItem) => void }) {
+ const iconManager = useDependency(IconManager);
+ return menus.map((menu) => {
+ const Icon = menu.icon ? iconManager.get(menu.icon) : null;
+ if ('children' in menu) {
+ return (
+ <section key={menu.id} className="univer-grid univer-gap-1 univer-py-2">
+ <div className="univer-px-3 univer-text-sm univer-font-medium">{menu.title}</div>
+ <MobileQuickInsertItems menus={menu.children ?? []} onSelect={onSelect} />
+ </section>
+ );
+ }
+ return (
+ <Button
+ key={menu.id}
+ variant="text"
+ className="univer-min-h-12 univer-w-full univer-justify-start univer-gap-2 univer-px-3"
+ onClick={() => onSelect(menu)}
+ >
+ {Icon && <Icon />}
+ <span className="univer-truncate">{menu.title}</span>
+ </Button>
+ );
+ });
+}
+
+export function MobileQuickInsertPopup() {
+ const { filteredMenus, handleMenuSelect, Placeholder } = useQuickInsertPopup();
+ return (
+ <div className="univer-mt-1">
+ {filteredMenus.length > 0
+ ? (
+ <div
+ className={clsx(`
+ univer-box-border univer-max-h-[min(42vh,360px)] univer-w-[min(360px,calc(100vw-24px))]
+ univer-overflow-y-auto univer-overscroll-contain univer-rounded-2xl univer-bg-gray-0
+ univer-p-2 univer-shadow-md
+ dark:!univer-bg-gray-700
+ `, scrollbarClassName)}
+ onWheel={(event) => event.stopPropagation()}
+ >
+ <MobileQuickInsertItems menus={filteredMenus} onSelect={handleMenuSelect} />
+ </div>
+ )
+ : Placeholder && <Placeholder />}
+ </div>
+ );
+}
diff --git a/packages/docs-quick-insert-ui/src/views/use-quick-insert-popup.ts b/packages/docs-quick-insert-ui/src/views/use-quick-insert-popup.ts
new file mode 100644
index 0000000000..29a4d608d9
--- /dev/null
+++ b/packages/docs-quick-insert-ui/src/views/use-quick-insert-popup.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 { DocPopupMenu, IDocPopupMenuItem } from '../services/doc-quick-insert-popup.service';
+import {
+ ICommandService,
+ LocaleService,
+} from '@univerjs/core';
+import { useDependency, useObservable } from '@univerjs/ui';
+import { useMemo } from 'react';
+import { CloseQuickInsertPopupOperation } from '../commands/operations/quick-insert-popup.operation';
+import { DocQuickInsertPopupService } from '../services/doc-quick-insert-popup.service';
+import { QuickInsertPlaceholder } from './QuickInsertPlaceholder';
+
+function filterMenusByKeyword(menus: DocPopupMenu[], keyword: string) {
+ return menus
+ .map((menu) => ({ ...menu }))
+ .filter((menu) => {
+ if ('children' in menu) {
+ menu.children = filterMenusByKeyword(menu.children!, keyword) as IDocPopupMenuItem[];
+
+ return menu.children.length > 0;
+ }
+
+ const keywords = (menu as IDocPopupMenuItem).keywords;
+
+ if (keywords) {
+ return keywords.some((word) => word.includes(keyword));
+ }
+
+ return menu.title.toLowerCase().includes(keyword);
+ });
+}
+
+function translateMenus(menus: DocPopupMenu[], localeService: LocaleService) {
+ return menus.map((_menu) => {
+ const menu = { ..._menu } as DocPopupMenu;
+ if ('children' in menu) {
+ menu.children = translateMenus(menu.children!, localeService) as IDocPopupMenuItem[];
+ }
+
+ menu.title = localeService.t(menu.title);
+
+ if ('keywords' in menu) {
+ menu.keywords = menu.keywords!
+ .concat(menu.title)
+ .map((word) => word.toLowerCase());
+ }
+
+ return menu;
+ });
+}
+
+export function useQuickInsertPopup() {
+ const localeService = useDependency(LocaleService);
+ const docQuickInsertPopupService = useDependency(DocQuickInsertPopupService);
+ const commandService = useDependency(ICommandService);
+ const locale = useObservable(localeService.currentLocale$);
+ const filterKeyword = useObservable(docQuickInsertPopupService.filterKeyword$, '');
+ const currentPopup = useObservable(docQuickInsertPopupService.editPopup$);
+ const menus = useObservable<DocPopupMenu[]>(currentPopup?.popup.menus$, []);
+ const filteredMenus = useMemo(
+ () => filterMenusByKeyword(translateMenus(menus, localeService), filterKeyword.toLowerCase()),
+ [menus, localeService, locale, filterKeyword]
+ );
+ const handleMenuSelect = (menu: IDocPopupMenuItem) => {
+ docQuickInsertPopupService.emitMenuSelected(menu);
+ commandService.executeCommand(CloseQuickInsertPopupOperation.id);
+ };
+ const Placeholder = currentPopup?.popup.Placeholder || QuickInsertPlaceholder;
+ return { filteredMenus, handleMenuSelect, Placeholder };
+}
diff --git a/packages/docs-thread-comment-ui/src/index.ts b/packages/docs-thread-comment-ui/src/index.ts
index ca796a33f4..4538e4d6e1 100644
--- a/packages/docs-thread-comment-ui/src/index.ts
+++ b/packages/docs-thread-comment-ui/src/index.ts
@@ -24,4 +24,5 @@ export { ShowCommentPanelOperation, StartAddCommentOperation } from './commands/
export type { IShowCommentPanelOperationParams } from './commands/operations/show-comment-panel.operation';
export type { IUniverDocsThreadCommentUIConfig } from './config/config';
export { menuSchema as DocsThreadCommentUIMenuSchema } from './menu/schema';
+export { UniverDocsThreadCommentMobileUIPlugin } from './mobile-plugin';
export { UniverDocsThreadCommentUIPlugin } from './plugin';
diff --git a/packages/docs-thread-comment-ui/src/mobile-plugin.ts b/packages/docs-thread-comment-ui/src/mobile-plugin.ts
new file mode 100644
index 0000000000..96155d84ae
--- /dev/null
+++ b/packages/docs-thread-comment-ui/src/mobile-plugin.ts
@@ -0,0 +1,93 @@
+/**
+ * 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 { IUniverDocsThreadCommentUIConfig } from './config/config';
+import { DependentOn, IConfigService, Inject, Injector, merge, Plugin, UniverInstanceType } from '@univerjs/core';
+import { UniverDocsPlugin } from '@univerjs/docs';
+import { UniverDocsThreadCommentPlugin } from '@univerjs/docs-thread-comment';
+import { UniverDocsMobileUIPlugin } from '@univerjs/docs-ui';
+import { UniverDrawingPlugin } from '@univerjs/drawing';
+import { IRenderManagerService, UniverRenderEnginePlugin } from '@univerjs/engine-render';
+import { UniverThreadCommentPlugin } from '@univerjs/thread-comment';
+import { UniverThreadCommentMobileUIPlugin } from '@univerjs/thread-comment-ui';
+import pkg from '../package.json';
+import { PLUGIN_NAME } from './common/const';
+import { defaultPluginConfig, DOCS_THREAD_COMMENT_UI_PLUGIN_CONFIG_KEY } from './config/config';
+import { ComponentsController } from './controllers/components.controller';
+import { DocThreadCommentSelectionController } from './controllers/doc-thread-comment-selection.controller';
+import { DocThreadCommentRenderController } from './controllers/render-controllers/render.controller';
+import { DocThreadCommentUIController } from './controllers/ui.controller';
+import { DocThreadCommentService } from './services/doc-thread-comment.service';
+
+@DependentOn(
+ UniverDocsPlugin,
+ UniverDocsThreadCommentPlugin,
+ UniverThreadCommentPlugin,
+ UniverDrawingPlugin,
+ UniverRenderEnginePlugin,
+ UniverDocsMobileUIPlugin,
+ UniverThreadCommentMobileUIPlugin
+)
+export class UniverDocsThreadCommentMobileUIPlugin extends Plugin {
+ static override pluginName = PLUGIN_NAME;
+ static override packageName = pkg.name;
+ static override version = pkg.version;
+ static override type = UniverInstanceType.UNIVER_DOC;
+
+ constructor(
+ private readonly _config: Partial<IUniverDocsThreadCommentUIConfig> = defaultPluginConfig,
+ @Inject(Injector) protected override _injector: Injector,
+ @IRenderManagerService private readonly _renderManagerSrv: 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(DOCS_THREAD_COMMENT_UI_PLUGIN_CONFIG_KEY, rest);
+ }
+
+ override onStarting(): void {
+ ([
+ [ComponentsController],
+ [DocThreadCommentUIController],
+ [DocThreadCommentSelectionController],
+ [DocThreadCommentService],
+ ] as Dependency[]).forEach((dep) => {
+ this._injector.add(dep);
+ });
+
+ this._injector.get(ComponentsController);
+ }
+
+ override onRendered(): void {
+ this._initRenderModule();
+
+ this._injector.get(DocThreadCommentSelectionController);
+ this._injector.get(DocThreadCommentUIController);
+ }
+
+ private _initRenderModule() {
+ this._renderManagerSrv.registerRenderModule(UniverInstanceType.UNIVER_DOC, [DocThreadCommentRenderController]);
+ }
+}
diff --git a/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts
index 2fd329d4cb..823c550cf3 100644
--- a/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts
+++ b/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts
@@ -95,7 +95,7 @@ import {
import { HorizontalLineCommand, InsertHorizontalLineBellowCommand } from '../doc-horizontal-line.command';
import { DocPageSetupCommand } from '../doc-page-setup.command';
import { DocParagraphSettingCommand } from '../doc-paragraph-setting.command';
-import { DocSelectAllCommand } from '../doc-select-all.command';
+import { DocSelectAllCommand, DocSelectWordCommand } from '../doc-select-all.command';
import { IMEInputCommand } from '../ime-input.command';
import { InsertCustomRangeCommand } from '../insert-custom-range.command';
import {
@@ -871,6 +871,30 @@ describe('misc document commands', () => {
subscription.unsubscribe();
});
+ it('selects the word at a collapsed mobile caret', async () => {
+ ({ univer, get } = createCommandTestBed(createBaseDoc()));
+ commandService = get(ICommandService);
+ commandService.registerCommand(DocSelectWordCommand);
+ setCollapsedSelection(1);
+
+ const selectionManager = get(DocSelectionManagerService);
+ const refreshEvents: Array<unknown> = [];
+ const subscription = selectionManager.refreshSelection$.subscribe((event) => event && refreshEvents.push(event));
+
+ const result = await commandService.executeCommand(DocSelectWordCommand.id);
+ await awaitTime(0);
+
+ expect(result).toBe(true);
+ expect(refreshEvents.at(-1)).toEqual(expect.objectContaining({
+ unitId: 'test-doc',
+ subUnitId: 'test-doc',
+ isEditing: false,
+ docRanges: [expect.objectContaining({ startOffset: 0, endOffset: 5 })],
+ }));
+
+ subscription.unsubscribe();
+ });
+
it('selects the whole document directly for a structural selection without an active text range', async () => {
({ univer, get } = createCommandTestBed(createColumnGroupDoc()));
commandService = get(ICommandService);
diff --git a/packages/docs-ui/src/commands/commands/doc-select-all.command.ts b/packages/docs-ui/src/commands/commands/doc-select-all.command.ts
index 4795b75507..4e3fc76aac 100644
--- a/packages/docs-ui/src/commands/commands/doc-select-all.command.ts
+++ b/packages/docs-ui/src/commands/commands/doc-select-all.command.ts
@@ -18,6 +18,7 @@ import type { DocumentDataModel, ICommand, ICustomColumnGroup, ICustomTable, IDo
import type { ISuccinctDocRangeParam } from '@univerjs/engine-render';
import { CommandType, DataStreamTreeTokenType, DOC_RANGE_TYPE, getParagraphContentStartOffsets, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { DocSelectionManagerService } from '@univerjs/docs';
+import { getWordBoundaryByIndex } from '../../services/selection/word-boundary';
interface ISelectAllCommandParams {
segmentId?: string;
@@ -78,6 +79,50 @@ export const DocSelectAllCommand: ICommand<ISelectAllCommandParams> = {
},
};
+export const DocSelectWordCommand: ICommand = {
+ id: 'doc.command.select-word',
+ type: CommandType.COMMAND,
+ handler: (accessor) => {
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+ const selectionManager = accessor.get(DocSelectionManagerService);
+ const docDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ const activeRange = selectionManager.getActiveTextRange();
+ if (!docDataModel || !activeRange?.collapsed || activeRange.startOffset == null) {
+ return false;
+ }
+
+ const body = docDataModel.getSelfOrHeaderFooterModel(activeRange.segmentId)?.getBody();
+ if (!body) {
+ return false;
+ }
+
+ const paragraphStarts = getParagraphContentStartOffsets(body);
+ const paragraph = body.paragraphs?.find((item) => {
+ const start = paragraphStarts.get(item.startIndex) ?? 0;
+ return start <= activeRange.startOffset && activeRange.startOffset <= item.startIndex;
+ });
+ if (!paragraph) {
+ return false;
+ }
+
+ const paragraphStart = paragraphStarts.get(paragraph.startIndex) ?? 0;
+ const content = body.dataStream.slice(paragraphStart, paragraph.startIndex);
+ const index = activeRange.startOffset - paragraphStart;
+ const boundary = getWordBoundaryByIndex(content, index, paragraphStart) ??
+ getWordBoundaryByIndex(content, index - 1, paragraphStart);
+ if (!boundary) {
+ return false;
+ }
+
+ const unitId = docDataModel.getUnitId();
+ selectionManager.replaceDocRanges([{
+ ...boundary,
+ rangeType: DOC_RANGE_TYPE.TEXT,
+ }], { unitId, subUnitId: unitId }, false);
+ return true;
+ },
+};
+
function getWholeDocumentRanges(body: IDocumentBody): ISuccinctDocRangeParam[] {
return getRangesForOffsets(body, 0, body.dataStream.length - 2);
}
diff --git a/packages/docs-ui/src/config/config.ts b/packages/docs-ui/src/config/config.ts
index a18d1aa3d5..4039617274 100644
--- a/packages/docs-ui/src/config/config.ts
+++ b/packages/docs-ui/src/config/config.ts
@@ -18,6 +18,7 @@ import type { DependencyOverride } from '@univerjs/core';
import type { MenuConfig } from '@univerjs/ui';
export const DOCS_UI_PLUGIN_CONFIG_KEY = 'docs-ui.config';
+export const DOCS_UI_PLUGIN_NAME = 'DOC_UI_PLUGIN';
export const configSymbol = Symbol(DOCS_UI_PLUGIN_CONFIG_KEY);
diff --git a/packages/docs-ui/src/consts/mobile-context.ts b/packages/docs-ui/src/consts/mobile-context.ts
new file mode 100644
index 0000000000..8823bef0f5
--- /dev/null
+++ b/packages/docs-ui/src/consts/mobile-context.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 DOC_CARET_MENU_ID = 'docs.contextMenu.caret';
+export const MOBILE_DOC_PINCH_ZOOMING = 'MOBILE_DOC_PINCH_ZOOMING';
diff --git a/packages/docs-ui/src/controllers/__tests__/doc-render-controller.spec.ts b/packages/docs-ui/src/controllers/__tests__/doc-render-controller.spec.ts
index 298be1154e..229e17e504 100644
--- a/packages/docs-ui/src/controllers/__tests__/doc-render-controller.spec.ts
+++ b/packages/docs-ui/src/controllers/__tests__/doc-render-controller.spec.ts
@@ -138,6 +138,7 @@ vi.mock('../../services/selection/convert-text-range', () => ({
function createControllerFixture(options?: {
documentFlavor?: DocumentFlavor;
+ mobile?: boolean;
fitToWidth?: {
align?: 'center' | 'start';
mode?: 'none' | 'fit-width';
@@ -186,6 +187,7 @@ function createControllerFixture(options?: {
supportsIncrementalLayout?: boolean;
engineBeginFrame$?: Subject<number>;
sceneParent?: { width: number; height: number };
+ bottomReserve?: number;
onWorkerStart?: (layoutInteractionService: DocLayoutInteractionService) => void;
}) {
mockScrollBarProps.length = 0;
@@ -335,6 +337,7 @@ function createControllerFixture(options?: {
},
engine: {
beginFrame$: options?.engineBeginFrame$,
+ onTransformChange$: { subscribeEvent: vi.fn(() => ({ dispose: vi.fn() })) },
canvasColorService,
runRenderLoop: vi.fn(),
stopRenderLoop: vi.fn(),
@@ -362,6 +365,7 @@ function createControllerFixture(options?: {
const editorRenderConfig = pendingEditorRenderConfig;
const pageLayoutService = {
calculatePagePosition: vi.fn(),
+ resolveSceneHeight: vi.fn((height: number) => height + (options?.bottomReserve ?? 0)),
};
const selectionManager = {
refreshSelection: vi.fn(),
@@ -473,6 +477,7 @@ function createControllerFixture(options?: {
{ currentTheme$, darkMode$ },
layoutExecutorService,
layoutInteractionService,
+ { getContextValue: vi.fn(() => options?.mobile ?? false) },
{ error: vi.fn(), warn: vi.fn() }
);
@@ -2670,6 +2675,34 @@ describe('doc render controller', () => {
expect(context.scene.transformByState).toHaveBeenCalledWith(expect.objectContaining({ height: 18_420 }));
});
+ it('keeps the temporary mobile bottom reserve during incremental layout publications', async () => {
+ const { commandCallbacks, context, pageLayoutService } = createControllerFixture({
+ bottomReserve: 388,
+ layoutProgress: [{
+ complete: false,
+ anchorReady: true,
+ elapsedTime: 8,
+ estimatedPageCount: 20,
+ estimatedHeight: 18_000,
+ processedBlockCount: 10,
+ totalBlockCount: 200,
+ }],
+ });
+
+ commandCallbacks[0]({
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId: 'doc-unit',
+ actions: [],
+ },
+ } satisfies ICommandInfo);
+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
+
+ expect(context.mainComponent?.height).toBe(18_420);
+ expect(pageLayoutService.resolveSceneHeight).toHaveBeenCalledWith(18_420);
+ expect(context.scene.transformByState).toHaveBeenCalledWith({ width: 640, height: 18_808 });
+ });
+
it('uses the first published page width instead of the default scene width on first open', async () => {
const { context, skeletonManager } = createControllerFixture({
hasCompleteLayout: false,
diff --git a/packages/docs-ui/src/controllers/mobile/components.controller.ts b/packages/docs-ui/src/controllers/mobile/components.controller.ts
new file mode 100644
index 0000000000..69cde3a85a
--- /dev/null
+++ b/packages/docs-ui/src/controllers/mobile/components.controller.ts
@@ -0,0 +1,140 @@
+/**
+ * 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 { AddImageIcon, AlignTextBothIcon, BoldIcon, ColumnIcon, CopyDoubleIcon, CutIcon, DeleteColumnDoubleIcon, DeleteIcon, DeleteRowDoubleIcon, DeleteTableDoubleIcon, DocSettingIcon, FontColorDoubleIcon, GridIcon, H1Icon, H2Icon, H3Icon, H4Icon, H5Icon, HeaderFooterIcon, HorizontallyIcon, InsertDoubleIcon, InsertRowAboveDoubleIcon, InsertRowBelowDoubleIcon, ItalicIcon, KeyboardIcon, LeftInsertColumnDoubleIcon, LeftJustifyingIcon, LineIndentDecreaseIcon, LineIndentIncreaseIcon, MenuIcon, MoreLeftIcon, MoreRightIcon, NoColorDoubleIcon, OrderIcon, PaintBucketDoubleIcon, PasteSpecialDoubleIcon, ReduceDoubleIcon, ReduceIcon, RightInsertColumnDoubleIcon, RightJustifyingIcon, ShapeIcon, SmileIcon, StrikethroughIcon, SubscriptIcon, SuperscriptIcon, SymbolsIcon, TextTypeIcon, TodoListDoubleIcon, UnderlineIcon, UnorderIcon } from '@univerjs/icons';
+import { ComponentManager, IconManager } from '@univerjs/ui';
+import { DOC_LAYOUT_RECOVERY_COMPONENT, DocLayoutRecovery } from '../../views/DocLayoutRecovery';
+import { COMPONENT_DOC_HEADER_FOOTER_PANEL } from '../../views/header-footer/panel/component-name';
+import { DefaultTextColorIcon, DocParagraphBackgroundColorSwatchIcon0, DocParagraphBackgroundColorSwatchIcon1, DocParagraphBackgroundColorSwatchIcon10, DocParagraphBackgroundColorSwatchIcon11, DocParagraphBackgroundColorSwatchIcon12, DocParagraphBackgroundColorSwatchIcon13, DocParagraphBackgroundColorSwatchIcon14, DocParagraphBackgroundColorSwatchIcon15, DocParagraphBackgroundColorSwatchIcon2, DocParagraphBackgroundColorSwatchIcon3, DocParagraphBackgroundColorSwatchIcon4, DocParagraphBackgroundColorSwatchIcon5, DocParagraphBackgroundColorSwatchIcon6, DocParagraphBackgroundColorSwatchIcon7, DocParagraphBackgroundColorSwatchIcon8, DocParagraphBackgroundColorSwatchIcon9, DocParagraphTextColorSwatchIcon0, DocParagraphTextColorSwatchIcon1, DocParagraphTextColorSwatchIcon2, DocParagraphTextColorSwatchIcon3, DocParagraphTextColorSwatchIcon4, DocParagraphTextColorSwatchIcon5, DocParagraphTextColorSwatchIcon6, HeaderTextColorIcon, SubtitleTypeIcon, TitleTypeIcon } from '../../views/Icon';
+import { BULLET_LIST_TYPE_COMPONENT, BulletListTypePicker, ORDER_LIST_TYPE_COMPONENT, OrderListTypePicker } from '../../views/list-type-picker/index';
+import { MOBILE_DOC_ELEMENT_MENU, MobileDocElementMenuPopup } from '../../views/mobile-element-menu/MobileDocElementMenu';
+import { MobileHeaderFooterPanel, MobilePageSettings, MobileParagraphSettings, MobileSectionSettings } from '../../views/mobile/MobileDocSettings';
+import { PAGE_SETTING_COMPONENT_ID } from '../../views/PageSettings';
+import { DOC_SECTION_SETTING_COMPONENT } from '../../views/section-setting/component-name';
+import { COMPONENT_DOC_CREATE_TABLE_CONFIRM } from '../../views/table/create/component-name';
+import { DocCreateTableConfirm } from '../../views/table/create/TableCreate';
+
+export class MobileComponentsController extends Disposable {
+ constructor(
+ @Inject(ComponentManager) protected readonly _componentManager: ComponentManager,
+ @Inject(IconManager) private readonly _iconManager: IconManager
+ ) {
+ super();
+
+ this._registerComponents();
+ this._registerParts();
+ this._registerIcons();
+ }
+
+ private _registerParts(): void {
+ const componentManager = this._componentManager;
+ this.disposeWithMe(componentManager.register(COMPONENT_DOC_CREATE_TABLE_CONFIRM, DocCreateTableConfirm));
+ }
+
+ private _registerIcons(): void {
+ this.disposeWithMe(this._iconManager.register({
+ AlignTextBothIcon,
+ AddImageIcon,
+ BoldIcon,
+ CopyDoubleIcon,
+ ColumnIcon,
+ CutIcon,
+ DeleteColumnDoubleIcon,
+ DeleteIcon,
+ DeleteRowDoubleIcon,
+ DeleteTableDoubleIcon,
+ DocSettingIcon,
+ FontColorDoubleIcon,
+ GridIcon,
+ H1Icon,
+ H2Icon,
+ H3Icon,
+ H4Icon,
+ H5Icon,
+ HeaderFooterIcon,
+ HorizontallyIcon,
+ InsertDoubleIcon,
+ InsertRowAboveDoubleIcon,
+ InsertRowBelowDoubleIcon,
+ ItalicIcon,
+ KeyboardIcon,
+ LeftInsertColumnDoubleIcon,
+ LeftJustifyingIcon,
+ LineIndentDecreaseIcon,
+ LineIndentIncreaseIcon,
+ MenuIcon,
+ TextTypeIcon,
+ NoColorDoubleIcon,
+ OrderIcon,
+ PaintBucketDoubleIcon,
+ PasteSpecialDoubleIcon,
+ ReduceDoubleIcon,
+ ReduceIcon,
+ RightInsertColumnDoubleIcon,
+ RightJustifyingIcon,
+ ShapeIcon,
+ SmileIcon,
+ StrikethroughIcon,
+ SubscriptIcon,
+ SuperscriptIcon,
+ SymbolsIcon,
+ TitleTypeIcon,
+ SubtitleTypeIcon,
+ TodoListDoubleIcon,
+ UnderlineIcon,
+ UnorderIcon,
+ DefaultTextColorIcon,
+ HeaderTextColorIcon,
+ MoreRightIcon,
+ MoreLeftIcon,
+ 'DocParagraphTextColorSwatchIcon.0': DocParagraphTextColorSwatchIcon0,
+ 'DocParagraphTextColorSwatchIcon.1': DocParagraphTextColorSwatchIcon1,
+ 'DocParagraphTextColorSwatchIcon.2': DocParagraphTextColorSwatchIcon2,
+ 'DocParagraphTextColorSwatchIcon.3': DocParagraphTextColorSwatchIcon3,
+ 'DocParagraphTextColorSwatchIcon.4': DocParagraphTextColorSwatchIcon4,
+ 'DocParagraphTextColorSwatchIcon.5': DocParagraphTextColorSwatchIcon5,
+ 'DocParagraphTextColorSwatchIcon.6': DocParagraphTextColorSwatchIcon6,
+ 'DocParagraphBackgroundColorSwatchIcon.0': DocParagraphBackgroundColorSwatchIcon0,
+ 'DocParagraphBackgroundColorSwatchIcon.1': DocParagraphBackgroundColorSwatchIcon1,
+ 'DocParagraphBackgroundColorSwatchIcon.2': DocParagraphBackgroundColorSwatchIcon2,
+ 'DocParagraphBackgroundColorSwatchIcon.3': DocParagraphBackgroundColorSwatchIcon3,
+ 'DocParagraphBackgroundColorSwatchIcon.4': DocParagraphBackgroundColorSwatchIcon4,
+ 'DocParagraphBackgroundColorSwatchIcon.5': DocParagraphBackgroundColorSwatchIcon5,
+ 'DocParagraphBackgroundColorSwatchIcon.6': DocParagraphBackgroundColorSwatchIcon6,
+ 'DocParagraphBackgroundColorSwatchIcon.7': DocParagraphBackgroundColorSwatchIcon7,
+ 'DocParagraphBackgroundColorSwatchIcon.8': DocParagraphBackgroundColorSwatchIcon8,
+ 'DocParagraphBackgroundColorSwatchIcon.9': DocParagraphBackgroundColorSwatchIcon9,
+ 'DocParagraphBackgroundColorSwatchIcon.10': DocParagraphBackgroundColorSwatchIcon10,
+ 'DocParagraphBackgroundColorSwatchIcon.11': DocParagraphBackgroundColorSwatchIcon11,
+ 'DocParagraphBackgroundColorSwatchIcon.12': DocParagraphBackgroundColorSwatchIcon12,
+ 'DocParagraphBackgroundColorSwatchIcon.13': DocParagraphBackgroundColorSwatchIcon13,
+ 'DocParagraphBackgroundColorSwatchIcon.14': DocParagraphBackgroundColorSwatchIcon14,
+ 'DocParagraphBackgroundColorSwatchIcon.15': DocParagraphBackgroundColorSwatchIcon15,
+ }));
+ }
+
+ protected _registerComponents(): void {
+ this.disposeWithMe(this._componentManager.register(COMPONENT_DOC_HEADER_FOOTER_PANEL, MobileHeaderFooterPanel));
+ this.disposeWithMe(this._componentManager.register('doc_ui_paragraph-setting-panel', MobileParagraphSettings));
+ this.disposeWithMe(this._componentManager.register(DOC_SECTION_SETTING_COMPONENT, MobileSectionSettings));
+ this.disposeWithMe(this._componentManager.register(PAGE_SETTING_COMPONENT_ID, MobilePageSettings));
+ this.disposeWithMe(this._componentManager.register(MOBILE_DOC_ELEMENT_MENU, MobileDocElementMenuPopup));
+ this.disposeWithMe(this._componentManager.register(BULLET_LIST_TYPE_COMPONENT, BulletListTypePicker));
+ this.disposeWithMe(this._componentManager.register(ORDER_LIST_TYPE_COMPONENT, OrderListTypePicker));
+ this.disposeWithMe(this._componentManager.register(DOC_LAYOUT_RECOVERY_COMPONENT, DocLayoutRecovery));
+ }
+}
diff --git a/packages/docs-ui/src/controllers/mobile/ui.controller.ts b/packages/docs-ui/src/controllers/mobile/ui.controller.ts
new file mode 100644
index 0000000000..1ba695f111
--- /dev/null
+++ b/packages/docs-ui/src/controllers/mobile/ui.controller.ts
@@ -0,0 +1,78 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { Disposable, ICommandService, Inject, Injector, UniverInstanceType } from '@univerjs/core';
+import { BuiltInUIPart, connectInjector, ILayoutService, IMenuManagerService, IUIPartsService } from '@univerjs/ui';
+import { CoreHeaderFooterCommand, OpenHeaderFooterPanelCommand } from '../../commands/commands/doc-header-footer.command';
+import { SidebarDocHeaderFooterPanelOperation } from '../../commands/operations/doc-header-footer-panel.operation';
+import { OpenDocParagraphPermissionOperation } from '../../commands/operations/paragraph-permission.operation';
+import { OpenDocPermissionPanelOperation } from '../../commands/operations/permission-panel.operation';
+import { mobileMenuSchema } from '../../menu/mobile-schema';
+import { menuSchema } from '../../menu/schema';
+import { MobileDocEditDoneButton, MobileDocToolbar } from '../../views/mobile-doc-toolbar/MobileDocToolbar';
+import { MobileDocCanvasViewport } from '../../views/mobile/MobileDocCanvasViewport';
+
+export class DocMobileUIController extends Disposable {
+ constructor(
+ @Inject(Injector) private readonly _injector: Injector,
+ @ICommandService private readonly _commandService: ICommandService,
+ @ILayoutService private readonly _layoutService: ILayoutService,
+ @IMenuManagerService private readonly _menuManagerService: IMenuManagerService,
+ @IUIPartsService private readonly _uiPartsService: IUIPartsService
+ ) {
+ super();
+
+ this._initMenus();
+ this._initFocusHandler();
+ this._initCommands();
+ this._initUiParts();
+ }
+
+ private _initUiParts(): void {
+ this.disposeWithMe(this._uiPartsService.registerComponent(
+ BuiltInUIPart.CONTENT,
+ () => connectInjector(MobileDocCanvasViewport, this._injector)
+ ));
+ this.disposeWithMe(this._uiPartsService.registerComponent(
+ BuiltInUIPart.FOOTER,
+ () => connectInjector(MobileDocToolbar, this._injector)
+ ));
+ this.disposeWithMe(this._uiPartsService.registerComponent(
+ BuiltInUIPart.HEADER_MENU,
+ () => connectInjector(MobileDocEditDoneButton, this._injector)
+ ));
+ }
+
+ private _initMenus(): void {
+ this._menuManagerService.mergeMenu(menuSchema);
+ this._menuManagerService.appendRootMenu(mobileMenuSchema);
+ }
+
+ private _initFocusHandler(): void {
+ // Only a direct canvas gesture may reopen the software keyboard.
+ this.disposeWithMe(this._layoutService.registerFocusHandler(UniverInstanceType.UNIVER_DOC, () => {}));
+ }
+
+ private _initCommands(): void {
+ [
+ OpenDocPermissionPanelOperation,
+ OpenDocParagraphPermissionOperation,
+ CoreHeaderFooterCommand,
+ OpenHeaderFooterPanelCommand,
+ SidebarDocHeaderFooterPanelOperation,
+ ].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));
+ }
+}
diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/back-scroll.render-controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/back-scroll.render-controller.spec.ts
index 5c98e93f45..9b88b9885f 100644
--- a/packages/docs-ui/src/controllers/render-controllers/__tests__/back-scroll.render-controller.spec.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/back-scroll.render-controller.spec.ts
@@ -17,22 +17,37 @@
// @vitest-environment jsdom
import type { DocumentDataModel, IDocumentData } from '@univerjs/core';
-import type { IPointerEvent, RenderUnit } from '@univerjs/engine-render';
-import { DocumentFlavor, ICommandService, IUniverInstanceService, Univer, UniverInstanceType } from '@univerjs/core';
+import type { IPointerEvent } from '@univerjs/engine-render';
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { DocumentFlavor, getDocsEmptySnapshot, ICommandService, IUniverInstanceService, LocaleType, RichTextBuilder, Univer, UniverInstanceType } from '@univerjs/core';
import { DocLayoutExecutorService, DocSelectionManagerService, DocSkeletonManagerService, SetTextSelectionsOperation } from '@univerjs/docs';
import {
CanvasColorService,
+ DocBackground,
Documents,
+ Engine,
ICanvasColorService,
IRenderManagerService,
RenderManagerService,
+ RenderUnit,
+ Scene,
ScrollBar,
Viewport,
} from '@univerjs/engine-render';
+import { DesktopLayoutService, ILayoutService } from '@univerjs/ui';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { VIEWPORT_KEY } from '../../../basics/docs-view-key';
+import { DOCS_VIEW_KEY, VIEWPORT_KEY } from '../../../basics/docs-view-key';
+import { DocPageLayoutService } from '../../../services/doc-page-layout.service';
+import { DocViewScaleService } from '../../../services/doc-view-scale';
import { EditorService, IEditorService } from '../../../services/editor/editor-manager.service';
+import { MobileDocSelectionRenderService } from '../../../services/mobile/doc-selection-render.service';
+import { MobileDocViewScaleService } from '../../../services/mobile/doc-view-scale';
+import { NodePositionConvertToCursor } from '../../../services/selection/convert-text-range';
+import { DocSelectionRenderService } from '../../../services/selection/doc-selection-render.service';
+import { getAnchorBounding } from '../../../services/selection/text-range';
import { DocBackScrollRenderController } from '../back-scroll.render-controller';
+import { MobileDocBackScrollRenderController } from '../mobile/back-scroll.render-controller';
function createEditor() {
const univer = new Univer();
@@ -42,6 +57,7 @@ function createEditor() {
injector.add([DocLayoutExecutorService]);
injector.add([DocSelectionManagerService]);
injector.add([IEditorService, { useClass: EditorService }]);
+ injector.add([ILayoutService, { useClass: DesktopLayoutService }]);
injector.get(ICommandService).registerCommand(SetTextSelectionsOperation);
const dataStream = `${Array.from({ length: 100 }, (_, i) => `Paragraph ${i} has enough text to wrap onto several lines.\r`).join('')}\n`;
const model = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, {
@@ -88,7 +104,7 @@ function createEditor() {
new ScrollBar(viewport, { mainScene: render.scene });
viewport.resetCanvasSizeAndUpdateScroll();
expect(viewport.isActive).toBe(true);
- render.addRenderDependencies([[DocBackScrollRenderController]]);
+ render.addRenderDependencies([[DocViewScaleService], [DocPageLayoutService], [DocSelectionRenderService], [DocBackScrollRenderController]]);
const controller = render.with(DocBackScrollRenderController);
const selections = injector.get(DocSelectionManagerService);
return {
@@ -112,22 +128,23 @@ function createEditor() {
};
}
+beforeEach(() => {
+ const context = new Proxy({
+ font: '',
+ webkitBackingStorePixelRatio: 1,
+ measureText: (text: string) => ({
+ width: text.length * 8,
+ actualBoundingBoxAscent: 8,
+ actualBoundingBoxDescent: 2,
+ fontBoundingBoxAscent: 8,
+ fontBoundingBoxDescent: 2,
+ }),
+ }, { get: (target, key) => key in target ? Reflect.get(target, key) : () => {} });
+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(context as never);
+});
+
describe('DocBackScrollRenderController', () => {
- beforeEach(() => {
- vi.useFakeTimers();
- const context = new Proxy({
- font: '',
- webkitBackingStorePixelRatio: 1,
- measureText: (text: string) => ({
- width: text.length * 8,
- actualBoundingBoxAscent: 8,
- actualBoundingBoxDescent: 2,
- fontBoundingBoxAscent: 8,
- fontBoundingBoxDescent: 2,
- }),
- }, { get: (target, key) => key in target ? Reflect.get(target, key) : () => {} });
- vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(context as never);
- });
+ beforeEach(() => vi.useFakeTimers());
afterEach(() => {
vi.restoreAllMocks();
@@ -256,3 +273,200 @@ describe('DocBackScrollRenderController', () => {
}
});
});
+
+describe('back scroll controller platform boundaries', () => {
+ it('keeps mobile-only state and services out of the desktop controller', () => {
+ const desktopSource = readFileSync(resolve(process.cwd(), 'src/controllers/render-controllers/back-scroll.render-controller.ts'), 'utf8');
+ const mobileSource = readFileSync(resolve(process.cwd(), 'src/controllers/render-controllers/mobile/back-scroll.render-controller.ts'), 'utf8');
+
+ expect(desktopSource).not.toContain('mobileKeyboard');
+ expect(desktopSource).not.toContain('_initViewportOcclusion');
+ expect(desktopSource).not.toContain('DocSelectionRenderService');
+ expect(desktopSource).not.toContain('DocPageLayoutService');
+ expect(desktopSource).not.toContain('setBottomReserve');
+ expect(mobileSource).toContain('extends DocBackScrollRenderController');
+ });
+});
+
+const cleanup: Array<() => void> = [];
+
+function createRender(mobile = true, documentFlavor = DocumentFlavor.MODERN, zoomRatio = 1) {
+ const originalViewport = window.visualViewport;
+ const visualViewport = Object.assign(new EventTarget(), {
+ height: 800,
+ width: 430,
+ offsetTop: 0,
+ offsetLeft: 0,
+ });
+ Object.defineProperty(window, 'visualViewport', { configurable: true, value: visualViewport });
+ cleanup.push(() => Object.defineProperty(window, 'visualViewport', {
+ configurable: true,
+ value: originalViewport,
+ }));
+
+ const univer = new Univer({ locale: LocaleType.EN_US });
+ cleanup.push(() => univer.dispose());
+ const injector = univer.__getInjector();
+ injector.add([ICanvasColorService, { useClass: CanvasColorService }]);
+ injector.add([ILayoutService, { useClass: DesktopLayoutService }]);
+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
+ injector.add([IEditorService, { useClass: EditorService }]);
+ injector.add([DocLayoutExecutorService]);
+ injector.add([DocSelectionManagerService]);
+
+ const data = getDocsEmptySnapshot('keyboard-doc', LocaleType.EN_US, 'Keyboard', documentFlavor);
+ data.settings = { ...data.settings, zoomRatio };
+ const builder = RichTextBuilder.create();
+ for (let index = 0; index < 80; index++) {
+ builder.paragraph({ spaceAfter: 8 }).span(`Mobile paragraph ${index}`, { fontSize: 18 });
+ }
+ const body = builder.getData().body;
+ if (!body) {
+ throw new Error('The keyboard regression document must have a body');
+ }
+ data.body = {
+ ...body,
+ sectionBreaks: [{ sectionId: 'keyboard-section', startIndex: body.dataStream.length - 1 }],
+ };
+ data.documentStyle = {
+ ...data.documentStyle,
+ pageSize: { width: 400, height: Infinity },
+ marginTop: 20,
+ marginBottom: 20,
+ marginLeft: 20,
+ marginRight: 20,
+ };
+ const doc = univer.createUnit(UniverInstanceType.UNIVER_DOC, data);
+ const engine = injector.createInstance(Engine, doc.getUnitId(), { elementWidth: 430, elementHeight: 800 });
+ cleanup.push(() => engine.dispose());
+ const scene = new Scene('document', engine);
+ cleanup.push(() => scene.dispose());
+ const render = injector.createInstance(RenderUnit, { unit: doc, engine, scene, isMainScene: true });
+ cleanup.push(() => render.dispose());
+ render.addRenderDependencies([
+ [DocSkeletonManagerService],
+ [DocViewScaleService, { useClass: mobile ? MobileDocViewScaleService : DocViewScaleService }],
+ [DocPageLayoutService],
+ [DocSelectionRenderService, { useClass: mobile ? MobileDocSelectionRenderService : DocSelectionRenderService }],
+ ]);
+ const skeleton = render.with(DocSkeletonManagerService).getSkeleton();
+ const documents = new Documents(DOCS_VIEW_KEY.MAIN, skeleton);
+ const background = new DocBackground(DOCS_VIEW_KEY.BACKGROUND, skeleton);
+ documents.resize(400, skeleton.getActualSize().actualHeight + 40);
+ render.mainComponent = documents;
+ render.components.set(DOCS_VIEW_KEY.BACKGROUND, background);
+ scene.addObjects([documents, background]);
+ const viewport = new Viewport(VIEWPORT_KEY.VIEW_MAIN, scene, { left: 0, top: 0, right: 0, bottom: 0 });
+ const scrollbar = new ScrollBar(viewport);
+ cleanup.push(() => scrollbar.dispose());
+ render.with(DocPageLayoutService).calculatePagePosition();
+ render.addRenderDependencies([[DocBackScrollRenderController, { useClass: mobile ? MobileDocBackScrollRenderController : DocBackScrollRenderController }]]);
+ render.with(DocBackScrollRenderController);
+ const selection = render.with(DocSelectionRenderService);
+ if (mobile) {
+ (selection as MobileDocSelectionRenderService).enterMobileEditMode();
+ }
+ const manager = injector.get(DocSelectionManagerService);
+
+ const getCaretBounds = (paragraph: number) => {
+ const offset = data.body?.paragraphs?.[paragraph].startIndex ?? 0;
+ const position = skeleton.findNodePositionByCharIndex(offset, true);
+ const converter = new NodePositionConvertToCursor(documents.getOffsetConfig(), skeleton);
+ const { contentBoxPointGroup } = converter.getRangePointData(position, position);
+ const bounds = getAnchorBounding(contentBoxPointGroup);
+ return { top: bounds.top + documents.top, bottom: bounds.top + documents.top + bounds.height, position };
+ };
+ const setCaret = (paragraph: number) => {
+ const offset = data.body?.paragraphs?.[paragraph].startIndex ?? 0;
+ manager.__TEST_ONLY_add([{ startOffset: offset, endOffset: offset, collapsed: true, isActive: true }]);
+ return getCaretBounds(paragraph);
+ };
+ const setKeyboardHeight = (height: number) => {
+ visualViewport.height = 800 - height;
+ visualViewport.dispatchEvent(new Event('resize'));
+ };
+ return { engine, scene, render, viewport, getCaretBounds, setCaret, setKeyboardHeight };
+}
+
+describe('DocBackScrollRenderController mobile keyboard visibility', () => {
+ afterEach(() => {
+ for (const dispose of cleanup.reverse()) {
+ dispose();
+ }
+ cleanup.length = 0;
+ vi.restoreAllMocks();
+ });
+
+ it.each([DocumentFlavor.MODERN, DocumentFlavor.TRADITIONAL])(
+ 'reveals an obscured caret synchronously before the next frame for document flavor %s',
+ (flavor) => {
+ const { viewport, engine, getCaretBounds, setCaret, setKeyboardHeight } = createRender(true, flavor);
+ const before = viewport.calcViewportInfo().viewBound;
+ let paragraph = 0;
+ while (paragraph < 79 && getCaretBounds(paragraph).bottom <= before.bottom - 380 - 48) {
+ paragraph++;
+ }
+ const caret = setCaret(paragraph);
+ expect(caret.bottom).toBeLessThan(before.bottom);
+ expect(caret.bottom).toBeGreaterThan(before.bottom - 380 - 48);
+
+ setKeyboardHeight(380);
+ const after = viewport.calcViewportInfo().viewBound;
+ expect(after.top).toBeGreaterThan(before.top);
+ expect(caret.bottom).toBeLessThanOrEqual(after.bottom - 380 - 48);
+ expect(caret.top - after.top).toBeCloseTo(
+ (after.bottom - after.top - 380 - 48 - (caret.bottom - caret.top)) * 0.4,
+ 0
+ );
+ expect(engine.height).toBe(800);
+ const scrollTop = viewport.viewportScrollY;
+ setKeyboardHeight(380);
+ expect(viewport.viewportScrollY).toBe(scrollTop);
+ }
+ );
+
+ it.each([0.5, 1, 2])('places an offscreen caret above center at scale %s without moving it again', (scale) => {
+ const { scene, render, viewport, setCaret, setKeyboardHeight } = createRender(true, DocumentFlavor.TRADITIONAL, scale);
+ expect(scene.getAncestorScale().scaleY).toBe(scale);
+ const caret = setCaret(40);
+ setKeyboardHeight(380);
+ const assertPosition = () => {
+ const bound = viewport.calcViewportInfo().viewBound;
+ const expectedTop = (bound.bottom - bound.top - 428 / scale - (caret.bottom - caret.top)) * 0.4;
+ // Viewport scrolling rounds to physical pixels.
+ expect(Math.abs(caret.top - bound.top - expectedTop) * scale).toBeLessThan(1);
+ };
+ assertPosition();
+
+ const controller = render.with(DocBackScrollRenderController);
+ const scroll = viewport.viewportScrollY;
+ controller.scrollToNode(caret.position);
+ expect(viewport.viewportScrollY).toBe(scroll);
+
+ viewport.scrollToViewportPos({ viewportScrollY: viewport.viewportScrollY + 400 / scale });
+ controller.scrollToNode(caret.position);
+ assertPosition();
+ });
+
+ it('does not move a visible caret or pull the document back as the keyboard closes', () => {
+ const { viewport, setCaret, setKeyboardHeight } = createRender();
+ setCaret(0);
+ const initialScroll = viewport.viewportScrollY;
+ setKeyboardHeight(380);
+ expect(viewport.viewportScrollY).toBe(initialScroll);
+
+ viewport.scrollToViewportPos({ viewportScrollY: 100 });
+ setKeyboardHeight(180);
+ expect(viewport.viewportScrollY).toBeCloseTo(100);
+ setKeyboardHeight(0);
+ expect(viewport.viewportScrollY).toBeCloseTo(100);
+ });
+
+ it('does not apply mobile keyboard compensation to desktop documents', () => {
+ const { viewport, setCaret, setKeyboardHeight } = createRender(false);
+ setCaret(15);
+ const initialScroll = viewport.viewportScrollY;
+ setKeyboardHeight(380);
+ expect(viewport.viewportScrollY).toBe(initialScroll);
+ });
+});
diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-selection-render.controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-selection-render.controller.spec.ts
index cd587b7f61..6e2268ec22 100644
--- a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-selection-render.controller.spec.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-selection-render.controller.spec.ts
@@ -18,11 +18,11 @@
import type { IDocumentData } from '@univerjs/core';
import type { RenderUnit } from '@univerjs/engine-render';
-import type { EmbedInteractionBoundaryService } from '../../../services/doc-embed-integration.service';
import {
DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
DocumentFlavor,
ICommandService,
+ IContextService,
IUniverInstanceService,
Univer,
UniverInstanceType,
@@ -44,18 +44,24 @@ import {
RenderManagerService,
Viewport,
} from '@univerjs/engine-render';
-import { DesktopLayoutService, ILayoutService } from '@univerjs/ui';
+import { CanvasPopupService, ContextMenuService, DesktopLayoutService, ICanvasPopupService, IContextMenuService, ILayoutService } from '@univerjs/ui';
import { Subject } from 'rxjs';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { VIEWPORT_KEY } from '../../../basics/docs-view-key';
import { SetDocZoomRatioOperation } from '../../../commands/operations/set-doc-zoom-ratio.operation';
+import { DOC_CARET_MENU_ID } from '../../../consts/mobile-context';
import {
EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE,
EmbedRuntimeFocusCoordinator,
+ IDocEmbedInteractionBoundaryService,
+ IDocEmbedRuntimeFocusCoordinator,
} from '../../../services/doc-embed-integration.service';
+import { DocMobileElementMenuService } from '../../../services/doc-mobile-element-menu.service';
+import { DocCanvasPopManagerService } from '../../../services/doc-popup-manager.service';
import { EditorService, IEditorService } from '../../../services/editor/editor-manager.service';
import { DocSelectionRenderService } from '../../../services/selection/doc-selection-render.service';
import { DocSelectionRenderController } from '../doc-selection-render.controller';
+import { MobileDocSelectionRenderController } from '../mobile/doc-selection-render.controller';
const neoGetDocObjectMock = vi.hoisted(() => vi.fn());
const findFirstCursorOffsetMock = vi.hoisted(() => vi.fn<(snapshot: IDocumentData) => number>(() => 3));
@@ -84,13 +90,14 @@ function createEventSubject() {
return {
subscribeEvent: vi.fn((handler: (evt: any, state?: any) => void) => {
handlers.add(handler);
- return { dispose: vi.fn(() => handlers.delete(handler)) };
+ const remove = vi.fn(() => handlers.delete(handler));
+ return { dispose: remove, unsubscribe: remove };
}),
emit: (evt: any, state?: any) => handlers.forEach((handler) => handler(evt, state)),
};
}
-function createController(options: { readonly?: boolean; hasEditor?: boolean; preserveHostFocus?: boolean; embedRecentInteraction?: boolean; embedContains?: boolean; unitId?: string; currentSelectionUnitId?: string; embedRuntimeFocusCoordinator?: EmbedRuntimeFocusCoordinator } = {}) {
+function createController(options: { readonly?: boolean; hasEditor?: boolean; preserveHostFocus?: boolean; embedRecentInteraction?: boolean; embedContains?: boolean; mobile?: boolean; editing?: boolean; mobileEditMode?: boolean; focusing?: boolean; activeOffset?: number; nextActiveOffset?: number; documentFlavor?: DocumentFlavor; scale?: number; unitId?: string; currentSelectionUnitId?: string; embedRuntimeFocusCoordinator?: EmbedRuntimeFocusCoordinator } = {}) {
const refreshSelection$ = new Subject<any>();
const textSelectionInner$ = new Subject<any>();
const currentSkeleton$ = new Subject<any>();
@@ -116,11 +123,43 @@ function createController(options: { readonly?: boolean; hasEditor?: boolean; pr
pageMarginTop: 16,
})),
};
+ const pointerDown$ = createEventSubject();
+ const pointerMove$ = createEventSubject();
+ const pointerUp$ = createEventSubject();
+ const viewport = {
+ transformVector2SceneCoord: vi.fn(() => ({ x: 1, y: 2 })),
+ scrollByViewportDeltaVal: vi.fn(),
+ };
+ const canvas = window.document.createElement('canvas');
+ canvas.getBoundingClientRect = () => ({
+ bottom: 700,
+ height: 500,
+ left: 100,
+ right: 530,
+ top: 200,
+ width: 430,
+ x: 100,
+ y: 200,
+ toJSON: () => ({}),
+ } as DOMRect);
+ const engine = {
+ width: 430,
+ height: 500,
+ getCanvasElement: vi.fn(() => canvas),
+ };
+ const transformer = { clearSelectedObjects: vi.fn() };
const scene = {
+ scaleX: options.scale ?? 1,
+ scaleY: options.scale ?? 1,
+ getTransformer: () => transformer,
resetCursor: vi.fn(),
- getViewports: vi.fn(() => [{
- transformVector2SceneCoord: vi.fn(() => ({ x: 1, y: 2 })),
- }]),
+ getEngine: vi.fn(() => engine),
+ getViewport: vi.fn(() => viewport),
+ getViewports: vi.fn(() => [viewport]),
+ onPointerDown$: pointerDown$,
+ onPointerMove$: pointerMove$,
+ onPointerUp$: pointerUp$,
+ onPointerCancel$: createEventSubject(),
};
neoGetDocObjectMock.mockReturnValue({ document, scene });
const skeleton = {
@@ -130,6 +169,7 @@ function createController(options: { readonly?: boolean; hasEditor?: boolean; pr
getEditArea: vi.fn(() => DocumentEditArea.FOOTER),
setEditArea: vi.fn(),
};
+ let activeOffset = options.activeOffset ?? 3;
const docSelectionRenderService = {
removeAllRanges: vi.fn(),
addDocRanges: vi.fn(),
@@ -139,9 +179,18 @@ function createController(options: { readonly?: boolean; hasEditor?: boolean; pr
__onPointDown: vi.fn(),
__handleDblClick: vi.fn(),
__handleTripleClick: vi.fn(),
- setCursorManually: vi.fn(),
- getActiveTextRange: vi.fn(() => ({ startOffset: 0, endOffset: 0 })),
+ setCursorManually: vi.fn(() => {
+ activeOffset = options.nextActiveOffset ?? activeOffset;
+ }),
+ getActiveTextRange: vi.fn(() => ({ collapsed: true, startOffset: activeOffset, endOffset: activeOffset })),
+ enterMobileEditMode: vi.fn(),
+ exitMobileEditMode: vi.fn(),
+ suspendMobileEditingInput: vi.fn(),
+ exitEditing: vi.fn(),
isOnPointerEvent: false,
+ isFocusing: options.focusing ?? false,
+ isEditing: options.editing ?? false,
+ isMobileEditMode: options.mobileEditMode ?? options.editing ?? false,
};
const docSelectionManagerService = {
refreshSelection$,
@@ -170,34 +219,73 @@ function createController(options: { readonly?: boolean; hasEditor?: boolean; pr
setCurrentUnitForType: vi.fn(),
focusUnit: vi.fn(),
};
- const controller = new DocSelectionRenderController(
- {
- unitId: options.unitId ?? 'doc-1',
- unit: { getSnapshot: vi.fn(() => ({ body: { dataStream: 'abc\r\n' } })) },
- } as never,
- {
+ const contextMenuService = {
+ visible: false,
+ triggerContextMenu: vi.fn(),
+ hideContextMenu: vi.fn(),
+ };
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+ let elementMenu: DocMobileElementMenuService | undefined;
+ if (options.mobile) {
+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
+ injector.add([ICanvasPopupService, { useClass: CanvasPopupService }]);
+ injector.add([DocCanvasPopManagerService]);
+ injector.add([DocMobileElementMenuService]);
+ elementMenu = injector.get(DocMobileElementMenuService);
+ }
+ const child = injector.createChild([
+ [ICommandService, { useValue: {
onCommandExecuted: vi.fn((handler) => {
commandHandlers.push(handler);
return { dispose: vi.fn() };
}),
- } as never,
- editorService as never,
- instanceService as never,
- docSelectionRenderService as never,
- {
+ } }],
+ [IEditorService, { useValue: editorService }],
+ [IUniverInstanceService, { useValue: instanceService }],
+ [DocSelectionRenderService, { useValue: docSelectionRenderService }],
+ [DocSkeletonManagerService, { useValue: {
getSkeleton: vi.fn(() => skeleton),
getViewModel: vi.fn(() => viewModel),
currentSkeleton$,
- } as never,
- docSelectionManagerService as never,
- embedInteractionBoundaryService as unknown as EmbedInteractionBoundaryService,
- options.embedRuntimeFocusCoordinator as never
- );
+ } }],
+ [DocSelectionManagerService, { useValue: docSelectionManagerService }],
+ [IContextService, { useValue: {
+ getContextValue: vi.fn(() => false),
+ } }],
+ [IContextMenuService, { useValue: contextMenuService }],
+ [IDocEmbedInteractionBoundaryService, { useValue: embedInteractionBoundaryService }],
+ ]);
+ if (options.embedRuntimeFocusCoordinator) {
+ child.add([IDocEmbedRuntimeFocusCoordinator, { useValue: options.embedRuntimeFocusCoordinator }]);
+ }
+ const renderContext = {
+ unitId: options.unitId ?? 'doc-1',
+ unit: {
+ getSnapshot: vi.fn(() => ({
+ body: { dataStream: 'abc\r\n' },
+ documentStyle: { documentFlavor: options.documentFlavor ?? DocumentFlavor.UNSPECIFIED },
+ })),
+ },
+ scene,
+ engine,
+ } as never;
+ const controller = options.mobile
+ ? child.createInstance(MobileDocSelectionRenderController, renderContext)
+ : child.createInstance(DocSelectionRenderController, renderContext);
+ controller.disposeWithMe(() => univer.dispose());
return {
+ elementMenu: elementMenu!,
controller,
+ transformer,
document,
scene,
+ canvas,
+ pointerDown$,
+ pointerMove$,
+ pointerUp$,
+ viewport,
skeleton,
viewModel,
refreshSelection$,
@@ -208,14 +296,68 @@ function createController(options: { readonly?: boolean; hasEditor?: boolean; pr
docSelectionManagerService,
editorService,
instanceService,
+ contextMenuService,
embedInteractionBoundaryService,
};
}
+const originalRequestAnimationFrame = globalThis.requestAnimationFrame;
+const originalCancelAnimationFrame = globalThis.cancelAnimationFrame;
+
describe('DocSelectionRenderController', () => {
+ it('keeps the mobile render controller independent from the desktop controller', () => {
+ expect(MobileDocSelectionRenderController.prototype).not.toBeInstanceOf(DocSelectionRenderController);
+ });
+
+ it.each([
+ { mobile: true, focusing: true, button: 0, prevented: true },
+ { mobile: true, focusing: false, button: 0, prevented: false },
+ { mobile: false, focusing: true, button: 0, prevented: false },
+ { mobile: true, focusing: true, button: 2, prevented: false },
+ ])('preserves input focus only for mobile primary canvas clicks: %j', ({ mobile, focusing, button, prevented }) => {
+ const { controller, canvas, docSelectionRenderService } = createController({ mobile, focusing });
+ const event = new MouseEvent('mousedown', { button, cancelable: true });
+
+ canvas.dispatchEvent(event);
+
+ expect(event.defaultPrevented).toBe(prevented);
+ expect(docSelectionRenderService.focus).not.toHaveBeenCalled();
+
+ controller.dispose();
+ const afterDispose = new MouseEvent('mousedown', { button, cancelable: true });
+ canvas.dispatchEvent(afterDispose);
+ expect(afterDispose.defaultPrevented).toBe(false);
+ });
+
+ it.each(['swipe', 'cancel', 'long press'])('does not open an element menu after a %s', (gesture) => {
+ vi.useFakeTimers();
+ const { controller, elementMenu, document, scene, pointerMove$, pointerUp$ } = createController({ mobile: true });
+ const show = vi.spyOn(elementMenu, 'show');
+ elementMenu.capture({
+ unitId: 'doc-1',
+ rect: { left: 10, top: 10, right: 100, bottom: 40 },
+ onEdit: vi.fn(),
+ onDelete: vi.fn(),
+ });
+ document.onPointerDown$.emit({ offsetX: 20, offsetY: 30, button: 0 }, { stopPropagation: vi.fn() });
+ if (gesture === 'swipe') {
+ pointerMove$.emit({ offsetX: 20, offsetY: 100 });
+ } else if (gesture === 'cancel') {
+ scene.onPointerCancel$.emit({});
+ } else {
+ vi.advanceTimersByTime(430);
+ }
+ pointerUp$.emit({ offsetX: 20, offsetY: 100 });
+ expect(show).not.toHaveBeenCalled();
+ expect(elementMenu.takeTarget('doc-1')).toBeNull();
+ controller.dispose();
+ });
+
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
+ vi.stubGlobal('requestAnimationFrame', originalRequestAnimationFrame);
+ vi.stubGlobal('cancelAnimationFrame', originalCancelAnimationFrame);
neoGetDocObjectMock.mockReset();
findFirstCursorOffsetMock.mockClear();
});
@@ -233,6 +375,10 @@ describe('DocSelectionRenderController', () => {
const injector = univer.__getInjector();
injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
injector.add([ICanvasColorService, { useClass: CanvasColorService }]);
+ injector.add([IContextMenuService, { useClass: ContextMenuService }]);
+ injector.add([ICanvasPopupService, { useClass: CanvasPopupService }]);
+ injector.add([DocCanvasPopManagerService]);
+ injector.add([DocMobileElementMenuService]);
injector.add([DocLayoutExecutorService]);
injector.add([DocSelectionManagerService]);
injector.add([IEditorService, { useClass: EditorService }]);
@@ -316,10 +462,12 @@ describe('DocSelectionRenderController', () => {
const { controller, currentSkeleton$, commandHandlers, docSelectionRenderService, docSelectionManagerService } = createController();
currentSkeleton$.next({ id: 'skeleton' });
+ currentSkeleton$.next({ id: 'republished-skeleton' });
commandHandlers[0]({ id: SetDocZoomRatioOperation.id, params: { unitId: 'other-doc' } });
commandHandlers[0]({ id: SetDocZoomRatioOperation.id, params: { unitId: 'doc-1' } });
- expect(docSelectionRenderService.focus).toHaveBeenCalled();
+ expect(docSelectionRenderService.focus).toHaveBeenCalledOnce();
+ expect(docSelectionManagerService.replaceSelectionInfoWithoutRefresh).toHaveBeenCalledOnce();
expect(docSelectionManagerService.replaceSelectionInfoWithoutRefresh).toHaveBeenCalledWith(
{
textRanges: [{
@@ -427,7 +575,7 @@ describe('DocSelectionRenderController', () => {
controller.dispose();
});
- it('still syncs embedded internal editor selections while a child session owns interaction', () => {
+ it.each([false, true])('still syncs embedded internal editor selections while a child session owns interaction (mobile: %s)', (mobile) => {
const focusCoordinator = new EmbedRuntimeFocusCoordinator();
const lease = focusCoordinator.acquireLease({
embedId: 'embed-1',
@@ -437,6 +585,7 @@ describe('DocSelectionRenderController', () => {
childUnitId: 'child-sheet',
});
const { controller, textSelectionInner$, docSelectionManagerService } = createController({
+ mobile,
unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
embedRuntimeFocusCoordinator: focusCoordinator,
});
@@ -539,6 +688,428 @@ describe('DocSelectionRenderController', () => {
controller.dispose();
});
+ it('keeps mobile text selection in reading mode until a tolerant double tap enters editing', () => {
+ vi.useFakeTimers();
+ const { controller, currentSkeleton$, document, pointerUp$, docSelectionRenderService, editorService } = createController({
+ hasEditor: true,
+ mobile: true,
+ });
+
+ currentSkeleton$.next({});
+ expect(docSelectionRenderService.focus).not.toHaveBeenCalled();
+ expect(docSelectionRenderService.exitMobileEditMode).toHaveBeenCalledOnce();
+
+ const preventDefault = vi.fn();
+ document.onPointerDown$.emit(
+ { offsetX: 11, offsetY: 22, button: 0, cancelable: true, preventDefault },
+ { stopPropagation: vi.fn() }
+ );
+ pointerUp$.emit({ offsetX: 11, offsetY: 22 });
+
+ expect(docSelectionRenderService.__onPointDown).not.toHaveBeenCalled();
+ expect(docSelectionRenderService.setCursorManually).not.toHaveBeenCalled();
+ expect(docSelectionRenderService.exitMobileEditMode).toHaveBeenCalledOnce();
+ expect(editorService.focus).not.toHaveBeenCalled();
+ expect(preventDefault).toHaveBeenCalledOnce();
+
+ vi.advanceTimersByTime(250);
+ document.onPointerDown$.emit(
+ { offsetX: 19, offsetY: 27, button: 0 },
+ { stopPropagation: vi.fn() }
+ );
+ pointerUp$.emit({ offsetX: 19, offsetY: 27 });
+
+ expect(editorService.focus).toHaveBeenCalledWith('doc-1');
+ expect(docSelectionRenderService.enterMobileEditMode).toHaveBeenCalledOnce();
+ expect(docSelectionRenderService.setCursorManually).toHaveBeenLastCalledWith(19, 27, true, true, { strict: false });
+
+ document.onDblclick$.emit({ offsetX: 19, offsetY: 27 });
+ document.onTripleClick$.emit({ offsetX: 19, offsetY: 27 });
+ expect(docSelectionRenderService.enterMobileEditMode).toHaveBeenCalledOnce();
+ expect(docSelectionRenderService.setCursorManually).toHaveBeenCalledOnce();
+ expect(docSelectionRenderService.__handleTripleClick).not.toHaveBeenCalled();
+
+ controller.dispose();
+ });
+
+ it('scrolls a modern mobile document vertically without creating a caret', () => {
+ const { controller, document, pointerMove$, pointerUp$, viewport, docSelectionRenderService, transformer } = createController({
+ hasEditor: true,
+ mobile: true,
+ documentFlavor: DocumentFlavor.MODERN,
+ });
+
+ document.onPointerDown$.emit({ offsetX: 20, offsetY: 30, button: 0 }, { stopPropagation: vi.fn() });
+ pointerMove$.emit({ offsetX: 24, offsetY: 48 });
+ pointerUp$.emit({ offsetX: 24, offsetY: 48 });
+
+ expect(viewport.scrollByViewportDeltaVal).toHaveBeenCalledWith({
+ viewportScrollX: 0,
+ viewportScrollY: -18,
+ });
+ expect(docSelectionRenderService.setCursorManually).not.toHaveBeenCalled();
+ expect(docSelectionRenderService.__onPointDown).not.toHaveBeenCalled();
+ expect(transformer.clearSelectedObjects).not.toHaveBeenCalled();
+
+ controller.dispose();
+ });
+
+ it('keeps touch scrolling at screen-pixel speed after zooming a traditional document', () => {
+ const { controller, document, pointerMove$, pointerUp$, viewport } = createController({
+ mobile: true,
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ scale: 2,
+ });
+
+ document.onPointerDown$.emit({ offsetX: 20, offsetY: 30, button: 0 }, { stopPropagation: vi.fn() });
+ pointerMove$.emit({ offsetX: 24, offsetY: 48 });
+ pointerUp$.emit({ offsetX: 24, offsetY: 48 });
+
+ expect(viewport.scrollByViewportDeltaVal).toHaveBeenCalledWith({
+ viewportScrollX: -2,
+ viewportScrollY: -9,
+ });
+
+ controller.dispose();
+ });
+
+ it('lets a mobile element handle a confirmed tap without opening the generic menu', () => {
+ vi.useFakeTimers();
+ const { controller, document, elementMenu, pointerUp$, docSelectionRenderService } = createController({ mobile: true });
+ const onTap = vi.fn();
+ const show = vi.spyOn(elementMenu, 'show');
+ elementMenu.capture({
+ unitId: 'doc-1',
+ rect: { left: 10, top: 10, right: 100, bottom: 40 },
+ onTap,
+ onEdit: vi.fn(),
+ onDelete: vi.fn(),
+ });
+
+ document.onPointerDown$.emit({ offsetX: 20, offsetY: 30, button: 0 }, { stopPropagation: vi.fn() });
+ vi.advanceTimersByTime(500);
+ expect(docSelectionRenderService.__handleDblClick).not.toHaveBeenCalled();
+ pointerUp$.emit({ offsetX: 20, offsetY: 30 });
+
+ expect(onTap).toHaveBeenCalledOnce();
+ expect(onTap).toHaveBeenCalledWith({ offsetX: 20, offsetY: 30 });
+ expect(show).not.toHaveBeenCalled();
+ controller.dispose();
+ });
+
+ it('routes a focused element drag to its selection without scrolling the document', () => {
+ const { controller, document, elementMenu, pointerMove$, pointerUp$, viewport } = createController({ mobile: true });
+ const onTap = vi.fn();
+ const onDrag = vi.fn();
+ elementMenu.capture({
+ unitId: 'doc-1',
+ rect: { left: 10, top: 10, right: 100, bottom: 80 },
+ onTap,
+ onDrag,
+ onEdit: vi.fn(),
+ onDelete: vi.fn(),
+ });
+
+ document.onPointerDown$.emit({ offsetX: 20, offsetY: 30, button: 0 }, { stopPropagation: vi.fn() });
+ pointerMove$.emit({ offsetX: 60, offsetY: 60 });
+ pointerUp$.emit({ offsetX: 60, offsetY: 60 });
+
+ expect(onDrag).toHaveBeenCalledWith({ offsetX: 60, offsetY: 60 });
+ expect(onTap).not.toHaveBeenCalled();
+ expect(viewport.scrollByViewportDeltaVal).not.toHaveBeenCalled();
+
+ document.onPointerDown$.emit({ offsetX: 20, offsetY: 90, button: 0 }, { stopPropagation: vi.fn() });
+ pointerMove$.emit({ offsetX: 20, offsetY: 120 });
+ pointerUp$.emit({ offsetX: 20, offsetY: 120 });
+ expect(viewport.scrollByViewportDeltaVal).toHaveBeenCalled();
+ controller.dispose();
+ });
+
+ it('scrolls a mobile document when a gesture starts on an unhandled floating object', () => {
+ const { controller, pointerDown$, pointerMove$, pointerUp$, viewport, docSelectionRenderService, transformer } = createController({
+ hasEditor: true,
+ mobile: true,
+ documentFlavor: DocumentFlavor.MODERN,
+ });
+ const preventDefault = vi.fn();
+ const stopPropagation = vi.fn();
+
+ pointerDown$.emit(
+ { offsetX: 20, offsetY: 30, button: 0, cancelable: true, preventDefault },
+ { stopPropagation }
+ );
+ pointerMove$.emit({ offsetX: 24, offsetY: 48 });
+ pointerUp$.emit({ offsetX: 24, offsetY: 48 });
+
+ expect(preventDefault).toHaveBeenCalledOnce();
+ expect(stopPropagation).toHaveBeenCalledOnce();
+ expect(viewport.scrollByViewportDeltaVal).toHaveBeenCalledWith({
+ viewportScrollX: 0,
+ viewportScrollY: -18,
+ });
+ expect(docSelectionRenderService.setCursorManually).not.toHaveBeenCalled();
+ expect(docSelectionRenderService.__handleDblClick).not.toHaveBeenCalled();
+ expect(transformer.clearSelectedObjects).not.toHaveBeenCalled();
+
+ controller.dispose();
+ });
+
+ it.each([false, true])('deselects drawings after a body tap in mobile edit mode %s', (editing) => {
+ const { controller, document, pointerUp$, transformer } = createController({ mobile: true, editing });
+ document.onPointerDown$.emit({ offsetX: 20, offsetY: 30, button: 0 }, { stopPropagation: vi.fn() });
+ expect(transformer.clearSelectedObjects).not.toHaveBeenCalled();
+ pointerUp$.emit({ offsetX: 20, offsetY: 30 });
+ expect(transformer.clearSelectedObjects).toHaveBeenCalledOnce();
+ controller.dispose();
+ });
+
+ it('deselects drawings when a mobile body long press starts selecting text', () => {
+ vi.useFakeTimers();
+ const { controller, document, transformer, docSelectionRenderService } = createController({ mobile: true });
+ document.onPointerDown$.emit({ offsetX: 20, offsetY: 30, button: 0 }, { stopPropagation: vi.fn() });
+ vi.advanceTimersByTime(500);
+ expect(transformer.clearSelectedObjects).toHaveBeenCalledOnce();
+ expect(docSelectionRenderService.__handleDblClick).toHaveBeenCalled();
+ controller.dispose();
+ });
+
+ it('retains horizontal scrolling for a traditional mobile document', () => {
+ const { controller, document, pointerMove$, pointerUp$, viewport } = createController({
+ mobile: true,
+ documentFlavor: DocumentFlavor.TRADITIONAL,
+ });
+
+ document.onPointerDown$.emit({ offsetX: 20, offsetY: 30, button: 0 }, { stopPropagation: vi.fn() });
+ pointerMove$.emit({ offsetX: 24, offsetY: 48 });
+ pointerUp$.emit({ offsetX: 24, offsetY: 48 });
+
+ expect(viewport.scrollByViewportDeltaVal).toHaveBeenCalledWith({
+ viewportScrollX: -4,
+ viewportScrollY: -18,
+ });
+
+ controller.dispose();
+ });
+
+ it('continues a mobile document flick with decelerating inertia and stops it on the next touch', () => {
+ let pendingFrame: FrameRequestCallback | undefined;
+ const requestAnimationFrame = vi.fn((callback: FrameRequestCallback) => {
+ pendingFrame = callback;
+ return requestAnimationFrame.mock.calls.length;
+ });
+ const cancelAnimationFrame = vi.fn();
+ vi.stubGlobal('requestAnimationFrame', requestAnimationFrame);
+ vi.stubGlobal('cancelAnimationFrame', cancelAnimationFrame);
+ vi.spyOn(performance, 'now')
+ .mockReturnValueOnce(0)
+ .mockReturnValueOnce(16)
+ .mockReturnValueOnce(32)
+ .mockReturnValueOnce(48);
+ const { controller, document, pointerMove$, pointerUp$, viewport } = createController({
+ mobile: true,
+ documentFlavor: DocumentFlavor.MODERN,
+ });
+
+ document.onPointerDown$.emit({ offsetX: 20, offsetY: 130, button: 0 }, { stopPropagation: vi.fn() });
+ pointerMove$.emit({ offsetX: 20, offsetY: 80 });
+ pointerMove$.emit({ offsetX: 20, offsetY: 30 });
+ pointerUp$.emit({ offsetX: 20, offsetY: 30 });
+
+ expect(requestAnimationFrame).toHaveBeenCalledOnce();
+ const firstFrame = pendingFrame;
+ firstFrame?.(64);
+ const secondFrame = pendingFrame;
+ secondFrame?.(80);
+
+ expect(viewport.scrollByViewportDeltaVal).toHaveBeenLastCalledWith({
+ viewportScrollX: 0,
+ viewportScrollY: expect.any(Number),
+ });
+ expect(viewport.scrollByViewportDeltaVal.mock.lastCall?.[0].viewportScrollY).toBeGreaterThan(0);
+
+ const activeAnimationId = requestAnimationFrame.mock.results.at(-1)?.value;
+ document.onPointerDown$.emit({ offsetX: 20, offsetY: 30, button: 0 }, { stopPropagation: vi.fn() });
+ expect(cancelAnimationFrame).toHaveBeenCalledWith(activeAnimationId);
+
+ controller.dispose();
+ });
+
+ it('moves the mobile caret on tap while preserving editing', () => {
+ const { controller, document, pointerUp$, docSelectionRenderService } = createController({
+ hasEditor: true,
+ mobile: true,
+ editing: true,
+ });
+
+ document.onPointerDown$.emit({ offsetX: 32, offsetY: 44, button: 0 }, { stopPropagation: vi.fn() });
+ pointerUp$.emit({ offsetX: 32, offsetY: 44 });
+
+ expect(docSelectionRenderService.__onPointDown).not.toHaveBeenCalled();
+ expect(docSelectionRenderService.setCursorManually).toHaveBeenCalledWith(32, 44, true, true, { strict: false });
+
+ controller.dispose();
+ });
+
+ it('uses canvas-relative client coordinates when iOS reports stale offsets after keyboard changes', () => {
+ const { controller, document, pointerUp$, docSelectionRenderService } = createController({
+ hasEditor: true,
+ mobile: true,
+ editing: true,
+ });
+ const event = {
+ offsetX: 32,
+ offsetY: -136,
+ clientX: 132,
+ clientY: 244,
+ button: 0,
+ };
+
+ document.onPointerDown$.emit(event, { stopPropagation: vi.fn() });
+ pointerUp$.emit(event);
+
+ expect(docSelectionRenderService.setCursorManually).toHaveBeenCalledWith(32, 44, true, true, { strict: false });
+
+ controller.dispose();
+ });
+
+ it('opens the mobile caret menu when the focused caret is tapped again', () => {
+ const { controller, document, pointerUp$, contextMenuService } = createController({
+ hasEditor: true,
+ mobile: true,
+ mobileEditMode: true,
+ focusing: true,
+ activeOffset: 7,
+ });
+ const event = { offsetX: 32, offsetY: 44, clientX: 132, clientY: 244, button: 0 };
+
+ document.onPointerDown$.emit(event, { stopPropagation: vi.fn() });
+ pointerUp$.emit(event);
+
+ expect(contextMenuService.triggerContextMenu).toHaveBeenCalledWith(
+ expect.objectContaining({ clientX: 132, clientY: 244 }),
+ DOC_CARET_MENU_ID,
+ { unitId: 'doc-1', subUnitId: 'doc-1', caretAnchor: true }
+ );
+
+ controller.dispose();
+ });
+
+ it('moves a focused caret without opening the menu when the target offset changes', () => {
+ const { controller, document, pointerUp$, contextMenuService } = createController({
+ mobile: true,
+ mobileEditMode: true,
+ focusing: true,
+ activeOffset: 7,
+ nextActiveOffset: 9,
+ });
+ const event = { offsetX: 32, offsetY: 44, button: 0 };
+
+ document.onPointerDown$.emit(event, { stopPropagation: vi.fn() });
+ pointerUp$.emit(event);
+
+ expect(contextMenuService.triggerContextMenu).not.toHaveBeenCalled();
+
+ controller.dispose();
+ });
+
+ it('treats small touch jitter as an editing tap', () => {
+ const { controller, document, pointerMove$, pointerUp$, viewport, docSelectionRenderService } = createController({
+ mobile: true,
+ editing: true,
+ });
+
+ document.onPointerDown$.emit({ offsetX: 32, offsetY: 44, button: 0 }, { stopPropagation: vi.fn() });
+ pointerMove$.emit({ offsetX: 40, offsetY: 47 });
+ pointerUp$.emit({ offsetX: 40, offsetY: 47 });
+
+ expect(viewport.scrollByViewportDeltaVal).not.toHaveBeenCalled();
+ expect(docSelectionRenderService.setCursorManually).toHaveBeenCalledWith(32, 44, true, true, { strict: false });
+
+ controller.dispose();
+ });
+
+ it('does not treat a canvas offset change during an iOS viewport resize as a drag', () => {
+ const { controller, document, pointerMove$, pointerUp$, viewport, docSelectionRenderService } = createController({
+ mobile: true,
+ editing: true,
+ });
+ const pointerDownEvent = { offsetX: 32, offsetY: 44, clientX: 132, clientY: 244, button: 0 };
+
+ document.onPointerDown$.emit(pointerDownEvent, { stopPropagation: vi.fn() });
+ pointerMove$.emit({ offsetX: 32, offsetY: 104, clientX: 135, clientY: 247 });
+ pointerUp$.emit({ offsetX: 32, offsetY: 104, clientX: 135, clientY: 247 });
+
+ expect(viewport.scrollByViewportDeltaVal).not.toHaveBeenCalled();
+ expect(docSelectionRenderService.suspendMobileEditingInput).not.toHaveBeenCalled();
+ expect(docSelectionRenderService.setCursorManually).toHaveBeenCalledWith(32, 44, true, true, { strict: false });
+
+ controller.dispose();
+ });
+
+ it('scrolls instead of selecting when dragging in mobile editing mode', () => {
+ const { controller, document, pointerMove$, pointerUp$, viewport, docSelectionRenderService } = createController({
+ mobile: true,
+ editing: true,
+ documentFlavor: DocumentFlavor.MODERN,
+ });
+
+ document.onPointerDown$.emit({ offsetX: 20, offsetY: 30, button: 0 }, { stopPropagation: vi.fn() });
+ pointerMove$.emit({ offsetX: 23, offsetY: 50 });
+
+ expect(docSelectionRenderService.suspendMobileEditingInput).not.toHaveBeenCalled();
+
+ pointerUp$.emit({ offsetX: 23, offsetY: 50 });
+
+ expect(viewport.scrollByViewportDeltaVal).toHaveBeenCalledWith({
+ viewportScrollX: 0,
+ viewportScrollY: -20,
+ });
+ expect(docSelectionRenderService.__onPointDown).not.toHaveBeenCalled();
+ expect(docSelectionRenderService.setCursorManually).not.toHaveBeenCalled();
+ expect(docSelectionRenderService.suspendMobileEditingInput).not.toHaveBeenCalled();
+
+ controller.dispose();
+ });
+
+ it('selects a mobile word on long press without entering editing', () => {
+ vi.useFakeTimers();
+ const { controller, document, pointerUp$, docSelectionRenderService, editorService } = createController({
+ hasEditor: true,
+ mobile: true,
+ });
+ const event = { offsetX: 20, offsetY: 30, button: 0 };
+
+ document.onPointerDown$.emit(event, { stopPropagation: vi.fn() });
+ vi.advanceTimersByTime(420);
+ pointerUp$.emit(event);
+
+ expect(docSelectionRenderService.__handleDblClick).toHaveBeenCalledWith(event, false, false);
+ expect(docSelectionRenderService.setCursorManually).not.toHaveBeenCalled();
+ expect(editorService.focus).not.toHaveBeenCalled();
+
+ controller.dispose();
+ });
+
+ it('selects on long press and keeps mobile edit mode active', () => {
+ vi.useFakeTimers();
+ const { controller, document, pointerUp$, docSelectionRenderService } = createController({
+ mobile: true,
+ editing: true,
+ });
+ const event = { offsetX: 20, offsetY: 30, button: 0 };
+
+ document.onPointerDown$.emit(event, { stopPropagation: vi.fn() });
+ vi.advanceTimersByTime(420);
+ pointerUp$.emit(event);
+
+ expect(docSelectionRenderService.__handleDblClick).toHaveBeenCalledWith(event, false, false);
+ expect(docSelectionRenderService.suspendMobileEditingInput).toHaveBeenCalledOnce();
+ expect(docSelectionRenderService.exitMobileEditMode).toHaveBeenCalledOnce();
+ expect(docSelectionRenderService.setCursorManually).not.toHaveBeenCalled();
+
+ controller.dispose();
+ });
+
it('cancels deferred editor focus when the render controller is disposed', () => {
vi.useFakeTimers();
const { controller, document, docSelectionRenderService, editorService } = createController({ hasEditor: true });
@@ -554,6 +1125,25 @@ describe('DocSelectionRenderController', () => {
expect(docSelectionRenderService.setCursorManually).not.toHaveBeenCalled();
});
+ it('cancels deferred editor focus for a mobile internal editor when disposed', () => {
+ vi.useFakeTimers();
+ const { controller, document, docSelectionRenderService, editorService } = createController({
+ hasEditor: true,
+ mobile: true,
+ unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ });
+
+ document.onPointerDown$.emit(
+ { offsetX: 11, offsetY: 22, button: 0 },
+ { stopPropagation: vi.fn() }
+ );
+ controller.dispose();
+ vi.runOnlyPendingTimers();
+
+ expect(editorService.focus).toHaveBeenCalledTimes(1);
+ expect(docSelectionRenderService.setCursorManually).not.toHaveBeenCalled();
+ });
+
it('preserves the host unit focus for configured editors', () => {
const { controller, document, editorService, instanceService } = createController({
hasEditor: true,
@@ -625,12 +1215,12 @@ describe('DocSelectionRenderController', () => {
controller.dispose();
});
- it('keeps embedded internal editors interactive inside their own embed boundary', () => {
+ it.each([false, true])('keeps embedded internal editors interactive inside their own embed boundary (mobile: %s)', (mobile) => {
const {
controller,
document,
docSelectionRenderService,
- } = createController({ hasEditor: true, unitId: '__INTERNAL_EDITOR__DOCS_NORMAL' });
+ } = createController({ hasEditor: true, mobile, unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY });
const stopPropagation = vi.fn();
const embedTarget = window.document.createElement('canvas');
embedTarget.setAttribute(EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE, 'embed-1');
diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc.render-controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc.render-controller.spec.ts
index 4662259e12..ef47252654 100644
--- a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc.render-controller.spec.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc.render-controller.spec.ts
@@ -19,6 +19,8 @@
import type { DocumentDataModel, IDocumentData } from '@univerjs/core';
import type { IDocLayoutExecutor } from '@univerjs/docs';
import type { Documents, IPointerEvent, RenderUnit } from '@univerjs/engine-render';
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
import {
BooleanNumber,
CustomRangeType,
@@ -49,7 +51,7 @@ import {
IRenderManagerService,
RenderManagerService,
} from '@univerjs/engine-render';
-import { ILayoutService } from '@univerjs/ui';
+import { CanvasPopupService, ContextMenuService, ICanvasPopupService, IContextMenuService, ILayoutService } from '@univerjs/ui';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { VIEWPORT_KEY } from '../../../basics/docs-view-key';
import { AfterSpaceCommand } from '../../../commands/commands/auto-format.command';
@@ -59,9 +61,13 @@ import { DocAutoFormatService } from '../../../services/doc-auto-format.service'
import { DocIMEInputManagerService } from '../../../services/doc-ime-input-manager.service';
import { DocLayoutInteractionService } from '../../../services/doc-layout-interaction.service';
import { DocMenuStyleService } from '../../../services/doc-menu-style.service';
+import { DocMobileElementMenuService } from '../../../services/doc-mobile-element-menu.service';
import { DocPageLayoutService } from '../../../services/doc-page-layout.service';
+import { DocCanvasPopManagerService } from '../../../services/doc-popup-manager.service';
import { DocViewScaleService } from '../../../services/doc-view-scale';
import { EditorService, IEditorService } from '../../../services/editor/editor-manager.service';
+import { MobileDocSelectionRenderService } from '../../../services/mobile/doc-selection-render.service';
+import { MobileDocViewScaleService } from '../../../services/mobile/doc-view-scale';
import { DocSelectionRenderService } from '../../../services/selection/doc-selection-render.service';
import { cursorConvertToTextRange } from '../../../services/selection/text-range';
import { DocBackScrollRenderController } from '../back-scroll.render-controller';
@@ -69,8 +75,11 @@ import { DocIMEInputController } from '../doc-ime-input.controller';
import { DocInputController } from '../doc-input.controller';
import { DocSelectionRenderController } from '../doc-selection-render.controller';
import { DocRenderController } from '../doc.render-controller';
+import { MobileDocBackScrollRenderController } from '../mobile/back-scroll.render-controller';
+import { MobileDocSelectionRenderController } from '../mobile/doc-selection-render.controller';
+import { MobileDocRenderController } from '../mobile/doc.render-controller';
-function createEditor(paragraphCount = 8, withDrawing = true, workerBeforeLayout = false, documentFlavor = DocumentFlavor.TRADITIONAL, withFootnote = false) {
+function createEditor(paragraphCount = 8, withDrawing = true, workerBeforeLayout = false, documentFlavor = DocumentFlavor.TRADITIONAL, withFootnote = false, mobile = false) {
if (workerBeforeLayout) {
// Model computation cost separately from fake timers so foreground work yields before Worker handoff.
let elapsed = 0;
@@ -85,6 +94,10 @@ function createEditor(paragraphCount = 8, withDrawing = true, workerBeforeLayout
registerContainerElement: () => ({ dispose() {} }),
} as unknown as ILayoutService }]);
injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
+ injector.add([ICanvasPopupService, { useClass: CanvasPopupService }]);
+ injector.add([IContextMenuService, { useClass: ContextMenuService }]);
+ injector.add([DocCanvasPopManagerService]);
+ injector.add([DocMobileElementMenuService]);
injector.add([ICanvasColorService, { useClass: CanvasColorService }]);
injector.add([DocLayoutExecutorService]);
// The transport boundary stays pending; the real controller and coordinator
@@ -176,20 +189,21 @@ function createEditor(paragraphCount = 8, withDrawing = true, workerBeforeLayout
render.deactivate();
render.addRenderDependencies([
[DocSkeletonManagerService],
- [DocSelectionRenderService],
- [DocViewScaleService],
+ [DocSelectionRenderService, { useClass: mobile ? MobileDocSelectionRenderService : DocSelectionRenderService }],
+ [DocViewScaleService, { useClass: mobile ? MobileDocViewScaleService : DocViewScaleService }],
[DocPageLayoutService],
[DocLayoutInteractionService],
- [DocRenderController],
- [DocBackScrollRenderController],
- [DocSelectionRenderController],
+ [DocRenderController, { useClass: mobile ? MobileDocRenderController : DocRenderController }],
+ [DocBackScrollRenderController, { useClass: mobile ? MobileDocBackScrollRenderController : DocBackScrollRenderController }],
+ [DocSelectionRenderController, { useClass: mobile ? MobileDocSelectionRenderController : DocSelectionRenderController }],
[DocInputController],
[DocIMEInputManagerService],
[DocIMEInputController],
]);
const selection = render.with(DocSelectionRenderService);
const selectionManager = injector.get(DocSelectionManagerService);
- const skeleton = render.with(DocSkeletonManagerService).getSkeleton();
+ const skeletonManager = render.with(DocSkeletonManagerService);
+ const skeleton = skeletonManager.getSkeleton();
if (!workerBeforeLayout) {
const firstLine = skeleton.getSkeletonData()!.pages[0].sections[0].columns[0].lines[0];
expect(firstLine.ed).toBe(firstParagraph.length);
@@ -211,6 +225,7 @@ function createEditor(paragraphCount = 8, withDrawing = true, workerBeforeLayout
selection,
selectionManager,
skeleton,
+ skeletonManager,
startWorkerLayout,
unitId,
dispose(): void {
@@ -222,6 +237,27 @@ function createEditor(paragraphCount = 8, withDrawing = true, workerBeforeLayout
}
describe('DocRenderController bounded input publication', () => {
+ it('keeps mobile layout state out of the desktop render controller', () => {
+ const desktopSource = readFileSync(resolve(process.cwd(), 'src/controllers/render-controllers/doc.render-controller.ts'), 'utf8');
+ const mobilePluginSource = readFileSync(resolve(process.cwd(), 'src/mobile-plugin.ts'), 'utf8');
+
+ expect(desktopSource).not.toContain('MOBILE_DOC_OUTER_MARGIN');
+ expect(desktopSource).not.toContain('_mobileModernPageWidth');
+ expect(desktopSource).not.toContain('_getMobileModernLayoutOptions');
+ expect(desktopSource).not.toContain('_initMobileResponsiveLayout');
+ expect(desktopSource).not.toContain('_initResponsiveLayout');
+ expect(mobilePluginSource).toContain('[DocRenderController, { useClass: MobileDocRenderController }]');
+ });
+
+ it('uses the mobile render providers without Modern horizontal scrolling', () => {
+ const editor = createEditor(8, true, false, DocumentFlavor.MODERN, false, true);
+ try {
+ expect(editor.render.scene.getViewport(VIEWPORT_KEY.VIEW_MAIN)?.getScrollBar()?.enableHorizontal).toBe(false);
+ } finally {
+ editor.dispose();
+ }
+ });
+
beforeEach(() => {
vi.useFakeTimers();
const context = new Proxy({
@@ -505,29 +541,60 @@ describe('DocRenderController bounded input publication', () => {
}
});
- it('starts IME from a pending logical caret and commits the composed text once', async () => {
- const editor = createEditor();
+ it.each([
+ { label: 'desktop', mobile: false },
+ { label: 'mobile', mobile: true },
+ ])('keeps $label IME focused across repeated space confirmations and layout refreshes', async ({ mobile }) => {
+ const editor = createEditor(8, true, false, DocumentFlavor.TRADITIONAL, false, mobile);
try {
+ if (mobile) {
+ (editor.selection as MobileDocSelectionRenderService).enterMobileEditMode();
+ }
+ editor.selection.focus();
editor.input.textContent = 'A';
editor.input.dispatchEvent(new InputEvent('input', { data: 'A', inputType: 'insertText' }));
await Promise.resolve();
await Promise.resolve();
expect(editor.skeleton.getLayoutProgress()?.anchorReady).toBe(false);
- editor.input.dispatchEvent(new CompositionEvent('compositionstart', { data: '' }));
- for (const text of ['n', 'ni', '你']) {
- editor.input.dispatchEvent(new CompositionEvent('compositionupdate', { data: text }));
+
+ const compositions = [
+ { updates: ['n', 'ni', '你'], result: '你' },
+ { updates: ['h', 'ha', 'hao', '好'], result: '好' },
+ { updates: ['s', 'sh', 'shi', '世'], result: '世' },
+ { updates: ['j', 'jie', '界'], result: '界' },
+ { updates: ['a', '啊'], result: '啊' },
+ ];
+
+ for (const [index, composition] of compositions.entries()) {
+ editor.input.dispatchEvent(new CompositionEvent('compositionstart', { data: '' }));
+ for (const text of composition.updates) {
+ editor.input.textContent = text;
+ editor.input.dispatchEvent(new CompositionEvent('compositionupdate', { data: text }));
+ for (let microtask = 0; microtask < 8; microtask++) {
+ await Promise.resolve();
+ }
+ }
+ editor.input.dispatchEvent(new KeyboardEvent('keydown', { key: ' ', code: 'Space', bubbles: true }));
+ editor.input.dispatchEvent(new CompositionEvent('compositionend', { data: composition.result }));
for (let index = 0; index < 8; index++) {
await Promise.resolve();
}
+
+ const committed = compositions.slice(0, index + 1).map(({ result }) => result).join('');
+ const expectedOffset = 6 + index + 1;
+ expect(editor.model.getBody()?.dataStream.startsWith(`HelloA${committed} world`)).toBe(true);
+ await vi.advanceTimersByTimeAsync(20);
+ expect(editor.selectionManager.getActiveTextRange()?.endOffset).toBe(expectedOffset);
+ expect(editor.selection.getActiveTextRange()?.endOffset).toBe(expectedOffset);
+ expect(editor.selection.isEditing).toBe(true);
+ expect(document.activeElement).toBe(editor.input);
+
+ editor.skeletonManager.recalculate();
+
+ expect(editor.selectionManager.getActiveTextRange()?.endOffset).toBe(expectedOffset);
+ expect(editor.selection.isEditing).toBe(true);
+ expect(document.activeElement).toBe(editor.input);
}
- editor.input.dispatchEvent(new CompositionEvent('compositionend', { data: '你' }));
- for (let index = 0; index < 8; index++) {
- await Promise.resolve();
- }
- expect(editor.model.getBody()?.dataStream.startsWith('HelloA你 world')).toBe(true);
- await vi.advanceTimersByTimeAsync(20);
- expect(editor.selectionManager.getActiveTextRange()?.endOffset).toBe(7);
- expect(editor.selection.getActiveTextRange()?.endOffset).toBe(7);
} finally {
editor.dispose();
}
diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/zoom.render-controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/zoom.render-controller.spec.ts
index 884376cf49..653e8a6fbd 100644
--- a/packages/docs-ui/src/controllers/render-controllers/__tests__/zoom.render-controller.spec.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/zoom.render-controller.spec.ts
@@ -16,7 +16,11 @@
import { DocumentFlavor } from '@univerjs/core';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { DocZoomRenderController, shouldHandleDocWheelZoom } from '../zoom.render-controller';
+import { resolveMobileDocPinchZoomRatio } from '../mobile/doc-pinch-zoom';
+import {
+ DocZoomRenderController,
+ shouldHandleDocWheelZoom,
+} from '../zoom.render-controller';
const mockSceneScale = vi.hoisted(() => vi.fn());
const mockClearSelectedObjects = vi.hoisted(() => vi.fn());
@@ -62,6 +66,13 @@ describe('DocZoomRenderController', () => {
expect(shouldHandleDocWheelZoom({ ctrlKey: true, metaKey: false }, false, DocumentFlavor.TRADITIONAL)).toBe(false);
});
+ it('resolves mobile pinch zoom relative to the fitted 100% baseline', () => {
+ expect(resolveMobileDocPinchZoomRatio(1, 100, 150)).toBe(1.5);
+ expect(resolveMobileDocPinchZoomRatio(1, 100, 20)).toBe(0.5);
+ expect(resolveMobileDocPinchZoomRatio(2, 100, 200)).toBe(3);
+ expect(resolveMobileDocPinchZoomRatio(1.25, 0, 200)).toBe(1.25);
+ });
+
it('applies composed view scale and immediately renders embedded docs while receiving user zoom', () => {
const controller = Object.create(DocZoomRenderController.prototype) as DocZoomRenderController;
const refreshSelection = vi.fn();
diff --git a/packages/docs-ui/src/controllers/render-controllers/back-scroll.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/back-scroll.render-controller.ts
index d69bd442dd..a3b605a30e 100644
--- a/packages/docs-ui/src/controllers/render-controllers/back-scroll.render-controller.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/back-scroll.render-controller.ts
@@ -37,7 +37,7 @@ export class DocBackScrollRenderController extends RxDisposable implements Engin
private _scrollingToRange = false;
constructor(
- private readonly _context: EngineRender.IRenderContext<DocumentDataModel>,
+ protected readonly _context: EngineRender.IRenderContext<DocumentDataModel>,
@Inject(DocSelectionManagerService) private readonly _textSelectionManagerService: DocSelectionManagerService,
@IEditorService private readonly _editorService: IEditorService,
@Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService
@@ -126,7 +126,7 @@ export class DocBackScrollRenderController extends RxDisposable implements Engin
};
}
- private _cancelPendingSelectionScroll(): void {
+ protected _cancelPendingSelectionScroll(): void {
if (this._pendingSelectionScrollFrame != null && typeof cancelAnimationFrame !== 'undefined') {
cancelAnimationFrame(this._pendingSelectionScrollFrame);
}
@@ -355,12 +355,7 @@ export class DocBackScrollRenderController extends RxDisposable implements Engin
const editorRenderConfig = this._editorService.getEditorRenderConfig(unitId);
const delta = editorRenderConfig ? editorRenderConfig.backScrollOffset ?? 0 : 100;
-
- if (top < boundTop) {
- offsetY = top - boundTop - delta;
- } else if (top > boundBottom - height) {
- offsetY = top - boundBottom + height + delta;
- }
+ offsetY = this._getVerticalScrollDelta(top, height, boundTop, boundBottom, delta);
if (left < boundLeft) {
offsetX = left - boundLeft;
@@ -368,12 +363,26 @@ export class DocBackScrollRenderController extends RxDisposable implements Engin
offsetX = left - boundRight + ANCHOR_WIDTH;
}
+ if (offsetX === 0 && offsetY === 0) {
+ return;
+ }
+
const config = viewportMain.transViewportScroll2ScrollValue(offsetX, offsetY);
viewportMain.scrollByBarDeltaValue(config);
}
+ protected _getVerticalScrollDelta(top: number, height: number, boundTop: number, boundBottom: number, delta: number): number {
+ if (top < boundTop) {
+ return top - boundTop - delta;
+ }
+ if (top > boundBottom - height) {
+ return top - boundBottom + height + delta;
+ }
+ return 0;
+ }
+
// Let the selection show on the current screen.
- private _scrollToSelection() {
+ protected _scrollToSelection() {
const activeTextRange = this._textSelectionManagerService.getActiveTextRange();
if (activeTextRange == null) {
return;
diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-selection-render.controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc-selection-render.controller.ts
index e34eb125f3..7f445d6574 100644
--- a/packages/docs-ui/src/controllers/render-controllers/doc-selection-render.controller.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/doc-selection-render.controller.ts
@@ -47,16 +47,17 @@ import { neoGetDocObject } from '../../basics/component-tools';
import { findFirstCursorOffset } from '../../basics/selection';
import { SetDocZoomRatioOperation } from '../../commands/operations/set-doc-zoom-ratio.operation';
import {
- DOC_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE,
IDocEmbedInteractionBoundaryService,
IDocEmbedRuntimeFocusCoordinator,
} from '../../services/doc-embed-integration.service';
import { IEditorService } from '../../services/editor/editor-manager.service';
import { DocSelectionRenderService } from '../../services/selection/doc-selection-render.service';
+import { isEmbedInteractionEvent } from './doc-selection-render.util';
export class DocSelectionRenderController extends Disposable implements IRenderModule {
private _loadedMap = new WeakSet<RenderComponentType>();
private _deferredEditorFocusTimer: ReturnType<typeof setTimeout> | null = null;
+ private _initialSelectionReady = false;
constructor(
private readonly _context: IRenderContext<DocumentDataModel>,
@@ -167,32 +168,10 @@ export class DocSelectionRenderController extends Disposable implements IRenderM
this._instanceSrv.focusUnit(unitId);
}
- const skeleton = this._docSkeletonManagerService.getSkeleton();
const { offsetX, offsetY } = evt;
- const coord = this._getTransformCoordForDocumentOffset(offsetX, offsetY);
-
- if (coord != null) {
- const {
- pageLayoutType = PageLayoutType.VERTICAL,
- pageMarginLeft,
- pageMarginTop,
- } = document.getOffsetConfig();
- const { editArea } = skeleton.findEditAreaByCoord(
- coord,
- pageLayoutType,
- pageMarginLeft,
- pageMarginTop
- );
-
- const viewModel = this._docSkeletonManagerService.getViewModel();
- const preEditArea = viewModel.getEditArea();
-
- if (preEditArea !== DocumentEditArea.BODY && editArea !== DocumentEditArea.BODY && editArea !== preEditArea) {
- viewModel.setEditArea(editArea);
- }
- }
+ this._syncEditArea(offsetX, offsetY);
- this._docSelectionRenderService.__onPointDown(evt);
+ this._docSelectionRenderService.__onPointDown(evt, true);
if (this._editorService.getEditor(unitId)) {
/**
@@ -232,6 +211,9 @@ export class DocSelectionRenderController extends Disposable implements IRenderM
return;
}
+ if (this._editorService.getEditor(unitId)) {
+ this._setEditorFocus(unitId);
+ }
this._docSelectionRenderService.__handleDblClick(evt);
}));
@@ -255,6 +237,33 @@ export class DocSelectionRenderController extends Disposable implements IRenderM
super.dispose();
}
+ private _syncEditArea(offsetX: number, offsetY: number): void {
+ const coord = this._getTransformCoordForDocumentOffset(offsetX, offsetY);
+ if (coord == null) {
+ return;
+ }
+
+ const { document } = neoGetDocObject(this._context);
+ const {
+ pageLayoutType = PageLayoutType.VERTICAL,
+ pageMarginLeft,
+ pageMarginTop,
+ } = document.getOffsetConfig();
+ const skeleton = this._docSkeletonManagerService.getSkeleton();
+ const { editArea } = skeleton.findEditAreaByCoord(
+ coord,
+ pageLayoutType,
+ pageMarginLeft,
+ pageMarginTop
+ );
+ const viewModel = this._docSkeletonManagerService.getViewModel();
+ const preEditArea = viewModel.getEditArea();
+
+ if (preEditArea !== DocumentEditArea.BODY && editArea !== DocumentEditArea.BODY && editArea !== preEditArea) {
+ viewModel.setEditArea(editArea);
+ }
+ }
+
private _getTransformCoordForDocumentOffset(evtOffsetX: number, evtOffsetY: number) {
const docObject = neoGetDocObject(this._context);
const { document, scene } = docObject;
@@ -333,10 +342,9 @@ export class DocSelectionRenderController extends Disposable implements IRenderM
}
private _skeletonListener() {
- let selectionInitialized = false;
// Change text selection runtime(skeleton, scene) and update text selection manager current selection.
this.disposeWithMe(this._docSkeletonManagerService.currentSkeleton$.subscribe((skeleton) => {
- if (!skeleton) return;
+ if (!skeleton || this._initialSelectionReady) return;
const { unitId } = this._context;
const isInternalEditor = isInternalEditorID(unitId);
@@ -348,12 +356,7 @@ export class DocSelectionRenderController extends Disposable implements IRenderM
if (this._isEmbedChildInteractionActive(unitId)) {
return;
}
-
- // Synchronous layout publishes after every edit. Preserve the post-edit selection.
- if (selectionInitialized) {
- return;
- }
- selectionInitialized = true;
+ this._initialSelectionReady = true;
//TODO: @JOCS Only for docs. move to docs in the future.
this._docSelectionRenderService.focus();
@@ -390,47 +393,3 @@ export class DocSelectionRenderController extends Disposable implements IRenderM
}));
}
}
-
-function isEmbedInteractionEvent(evt: IPointerEvent | IMouseEvent): boolean {
- const target = (evt as Event).target;
- if (typeof Element !== 'undefined' && target instanceof Element && target.closest(`[${DOC_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE}]`) != null) {
- return true;
- }
-
- if (typeof document === 'undefined') {
- return false;
- }
-
- const point = getEventClientPoint(evt, target);
- const clientX = point?.clientX;
- const clientY = point?.clientY;
- if (typeof clientX !== 'number' || typeof clientY !== 'number' || !Number.isFinite(clientX) || !Number.isFinite(clientY)) {
- return false;
- }
-
- if (typeof document.elementFromPoint !== 'function') {
- return false;
- }
-
- return document.elementFromPoint(clientX, clientY)?.closest(`[${DOC_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE}]`) != null;
-}
-
-function getEventClientPoint(evt: IPointerEvent | IMouseEvent, target: EventTarget | null): { clientX: number; clientY: number } | undefined {
- if (Number.isFinite(evt.clientX) && Number.isFinite(evt.clientY)) {
- return { clientX: evt.clientX, clientY: evt.clientY };
- }
-
- if (typeof Element !== 'undefined' && target instanceof Element && Number.isFinite(evt.offsetX) && Number.isFinite(evt.offsetY)) {
- const rect = target.getBoundingClientRect();
- return {
- clientX: rect.left + evt.offsetX,
- clientY: rect.top + evt.offsetY,
- };
- }
-
- if (Number.isFinite(evt.x) && Number.isFinite(evt.y)) {
- return { clientX: evt.x, clientY: evt.y };
- }
-
- return undefined;
-}
diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-selection-render.util.ts b/packages/docs-ui/src/controllers/render-controllers/doc-selection-render.util.ts
new file mode 100644
index 0000000000..3d73660ab8
--- /dev/null
+++ b/packages/docs-ui/src/controllers/render-controllers/doc-selection-render.util.ts
@@ -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 { IMouseEvent, IPointerEvent } from '@univerjs/engine-render';
+import { DOC_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE } from '../../services/doc-embed-integration.service';
+
+export function isEmbedInteractionEvent(evt: IPointerEvent | IMouseEvent): boolean {
+ const target = (evt as Event).target;
+ if (typeof Element !== 'undefined' && target instanceof Element && target.closest(`[${DOC_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE}]`) != null) {
+ return true;
+ }
+
+ if (typeof document === 'undefined') {
+ return false;
+ }
+
+ const point = getEventClientPoint(evt, target);
+ const clientX = point?.clientX;
+ const clientY = point?.clientY;
+ if (typeof clientX !== 'number' || typeof clientY !== 'number' || !Number.isFinite(clientX) || !Number.isFinite(clientY)) {
+ return false;
+ }
+
+ if (typeof document.elementFromPoint !== 'function') {
+ return false;
+ }
+
+ return document.elementFromPoint(clientX, clientY)?.closest(`[${DOC_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE}]`) != null;
+}
+
+export function getEventClientPoint(evt: IPointerEvent | IMouseEvent, target: EventTarget | null): { clientX: number; clientY: number } | undefined {
+ if (Number.isFinite(evt.clientX) && Number.isFinite(evt.clientY)) {
+ return { clientX: evt.clientX, clientY: evt.clientY };
+ }
+
+ if (typeof Element !== 'undefined' && target instanceof Element && Number.isFinite(evt.offsetX) && Number.isFinite(evt.offsetY)) {
+ const rect = target.getBoundingClientRect();
+ return {
+ clientX: rect.left + evt.offsetX,
+ clientY: rect.top + evt.offsetY,
+ };
+ }
+
+ if (Number.isFinite(evt.x) && Number.isFinite(evt.y)) {
+ return { clientX: evt.x, clientY: evt.y };
+ }
+
+ return undefined;
+}
diff --git a/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts
index 5307071610..1c84b2c2d3 100644
--- a/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts
@@ -92,6 +92,8 @@ import {
resolveMutationLayoutRequest,
} from './doc-mutation-layout';
+const DOC_PAGE_MARGIN = 20;
+
function getTextXActionLength(action: unknown): number | undefined {
if (typeof action !== 'object' || action == null || !('t' in action) || !('len' in action)) {
return undefined;
@@ -320,7 +322,7 @@ interface IDocLayoutWorkerEditBatch {
invalidation: IDocumentLayoutInvalidation | undefined;
}
-interface IDocLayoutScheduleOptions {
+export interface IDocLayoutScheduleOptions {
deferForeground?: boolean;
reuseMainBaseline?: boolean;
allowMetadataOnlyStructuralTailReuse?: boolean;
@@ -328,6 +330,8 @@ interface IDocLayoutScheduleOptions {
anchor?: number;
priorityAnchor?: number;
invalidation?: IDocumentLayoutInvalidation;
+ modernPageWidth?: number;
+ modernHorizontalMargin?: number;
}
function mapPreviousOffsetToCurrent(
@@ -506,10 +510,10 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
private _reservedLayoutHeight = 0;
constructor(
- private readonly _context: IRenderContext<DocumentDataModel>,
+ protected readonly _context: IRenderContext<DocumentDataModel>,
@ICommandService private readonly _commandService: ICommandService,
@Inject(DocSelectionRenderService) private readonly _docSelectionRenderService: DocSelectionRenderService,
- @Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
+ @Inject(DocSkeletonManagerService) protected readonly _docSkeletonManagerService: DocSkeletonManagerService,
@IEditorService private readonly _editorService: IEditorService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@@ -650,7 +654,7 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
return !result.requiresLayout;
}
- private _scheduleLayout(
+ protected _scheduleLayout(
unitId: string,
skeleton: DocumentSkeleton,
options: IDocLayoutScheduleOptions,
@@ -1639,15 +1643,19 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
});
}
- private _shouldEnableHorizontalScrollBar(): boolean {
+ protected _shouldEnableHorizontalScrollBar(): boolean {
const options = this._docViewScaleService.getOptions();
return !(options.mode === 'fit-width' && options.target === 'container' && options.align === 'start');
}
+ protected _getHorizontalPageMargin(): number {
+ return DOC_PAGE_MARGIN;
+ }
+
private _addComponent() {
const { scene, unit: documentModel, components } = this._context;
- const DEFAULT_PAGE_MARGIN_LEFT = 20;
- const DEFAULT_PAGE_MARGIN_TOP = 20;
+ const DEFAULT_PAGE_MARGIN_LEFT = this._getHorizontalPageMargin();
+ const DEFAULT_PAGE_MARGIN_TOP = DOC_PAGE_MARGIN;
const config = {
pageMarginLeft: DEFAULT_PAGE_MARGIN_LEFT,
pageMarginTop: DEFAULT_PAGE_MARGIN_TOP,
@@ -1707,7 +1715,7 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
}
this._recalculateSizeBySkeleton(skeleton);
- this._refreshPagePositionAndSelection();
+ this._refreshPagePositionAndSelection(this._getActiveEditingRange(unitId) != null);
}
private _initCommandListener() {
@@ -1955,6 +1963,7 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
documentFlavor,
layoutProgress
);
+ const sceneHeight = this._docPageLayoutService.resolveSceneHeight(height);
docsComponent.resize(width, height);
docBackground.resize(width, height);
@@ -1962,9 +1971,9 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
const editorRenderConfig = this._editorService.getEditorRenderConfig(unitId);
if (
(!editorRenderConfig || editorRenderConfig.scrollBar) &&
- (scene.width !== width || scene.height !== height)
+ (scene.width !== width || scene.height !== sceneHeight)
) {
- scene.transformByState({ width, height });
+ scene.transformByState({ width, height: sceneHeight });
}
}
diff --git a/packages/docs-ui/src/controllers/render-controllers/mobile/back-scroll.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/mobile/back-scroll.render-controller.ts
new file mode 100644
index 0000000000..1c978c67b2
--- /dev/null
+++ b/packages/docs-ui/src/controllers/render-controllers/mobile/back-scroll.render-controller.ts
@@ -0,0 +1,72 @@
+/**
+ * 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 } from '@univerjs/core';
+import type { IRenderContext } from '@univerjs/engine-render';
+import type { MobileDocSelectionRenderService } from '../../../services/mobile/doc-selection-render.service';
+import { Inject } from '@univerjs/core';
+import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';
+import { DocPageLayoutService } from '../../../services/doc-page-layout.service';
+import { IEditorService } from '../../../services/editor/editor-manager.service';
+import { DocSelectionRenderService } from '../../../services/selection/doc-selection-render.service';
+import { DocBackScrollRenderController } from '../back-scroll.render-controller';
+
+const MOBILE_CARET_MARGIN = 32;
+const MOBILE_TOOLBAR_HEIGHT = 48;
+const MOBILE_CARET_VIEWPORT_RATIO = 0.4;
+
+export class MobileDocBackScrollRenderController extends DocBackScrollRenderController {
+ private _mobileKeyboardInset = 0;
+
+ constructor(
+ context: IRenderContext<DocumentDataModel>,
+ @Inject(DocSelectionManagerService) textSelectionManagerService: DocSelectionManagerService,
+ @Inject(DocSelectionRenderService) private readonly _docSelectionRenderService: MobileDocSelectionRenderService,
+ @IEditorService editorService: IEditorService,
+ @Inject(DocSkeletonManagerService) docSkeletonManagerService: DocSkeletonManagerService,
+ @Inject(DocPageLayoutService) private readonly _docPageLayoutService: DocPageLayoutService
+ ) {
+ super(context, textSelectionManagerService, editorService, docSkeletonManagerService);
+
+ this.disposeWithMe(this._docSelectionRenderService.mobileKeyboardState$.subscribe(({ visible, inset }) => {
+ const previousInset = this._mobileKeyboardInset;
+ this._mobileKeyboardInset = visible ? inset + MOBILE_TOOLBAR_HEIGHT : 0;
+ this._docPageLayoutService.setBottomReserve(
+ visible ? this._mobileKeyboardInset + MOBILE_CARET_MARGIN : 0
+ );
+ if (this._mobileKeyboardInset > previousInset) {
+ // Apply occlusion and caret scrolling before the same viewport change is painted.
+ this._cancelPendingSelectionScroll();
+ this._scrollToSelection();
+ }
+ }));
+ }
+
+ override dispose(): void {
+ this._docPageLayoutService.setBottomReserve(0);
+ super.dispose();
+ }
+
+ protected override _getVerticalScrollDelta(top: number, height: number, boundTop: number, boundBottom: number, _delta: number): number {
+ const scaleY = Math.max(this._context.scene.getAncestorScale().scaleY, 0.01);
+ const visibleBottom = boundBottom - this._mobileKeyboardInset / scaleY;
+ if (top >= boundTop && top + height <= visibleBottom) {
+ return 0;
+ }
+ const targetOffset = Math.max(0, visibleBottom - boundTop - height) * MOBILE_CARET_VIEWPORT_RATIO;
+ return top - boundTop - targetOffset;
+ }
+}
diff --git a/packages/docs-ui/src/controllers/render-controllers/mobile/doc-pinch-zoom.ts b/packages/docs-ui/src/controllers/render-controllers/mobile/doc-pinch-zoom.ts
new file mode 100644
index 0000000000..a441c12706
--- /dev/null
+++ b/packages/docs-ui/src/controllers/render-controllers/mobile/doc-pinch-zoom.ts
@@ -0,0 +1,174 @@
+/**
+ * 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 { ICommandService, IContextService } from '@univerjs/core';
+import type { DocSelectionManagerService } from '@univerjs/docs';
+import type { Engine, Scene, Viewport } from '@univerjs/engine-render';
+import type { DocViewScaleService } from '../../../services/doc-view-scale';
+import { Disposable, toDisposable } from '@univerjs/core';
+import { Vector2 } from '@univerjs/engine-render';
+import { MobileZoomIndicator } from '@univerjs/ui';
+import { SetDocZoomRatioOperation } from '../../../commands/operations/set-doc-zoom-ratio.operation';
+import { MOBILE_DOC_PINCH_ZOOMING } from '../../../consts/mobile-context';
+
+const MOBILE_DOC_ZOOM_MIN = 0.5;
+const MOBILE_DOC_ZOOM_MAX = 3;
+
+export function resolveMobileDocPinchZoomRatio(
+ initialZoomRatio: number,
+ initialDistance: number,
+ currentDistance: number
+): number {
+ if (initialDistance <= 0 || !Number.isFinite(currentDistance)) {
+ return initialZoomRatio;
+ }
+
+ const ratio = initialZoomRatio * currentDistance / initialDistance;
+ return Math.round(Math.max(MOBILE_DOC_ZOOM_MIN, Math.min(MOBILE_DOC_ZOOM_MAX, ratio)) * 100) / 100;
+}
+
+interface IMobileDocPinchZoomGestureOptions {
+ canvasElement: HTMLCanvasElement;
+ commandService: ICommandService;
+ contextService: IContextService;
+ docViewScaleService: DocViewScaleService;
+ engine: Engine;
+ scene: Scene;
+ textSelectionManagerService: DocSelectionManagerService;
+ unitId: string;
+ viewport: Viewport;
+}
+
+export class MobileDocPinchZoomGesture extends Disposable {
+ private readonly _zoomIndicator: MobileZoomIndicator;
+ private _gestureOwned = false;
+ private _pinchZooming = false;
+ private _initialDistance = 0;
+ private _initialZoomRatio = 1;
+ private _anchor = Vector2.Zero();
+
+ constructor(private readonly _options: IMobileDocPinchZoomGestureOptions) {
+ super();
+
+ const { canvasElement } = _options;
+ this._zoomIndicator = new MobileZoomIndicator(canvasElement);
+ this.disposeWithMe(this._zoomIndicator);
+ canvasElement.addEventListener('touchstart', this._handleTouchStart, { passive: false });
+ canvasElement.addEventListener('touchmove', this._handleTouchMove, { passive: false });
+ canvasElement.addEventListener('touchend', this._handleTouchEnd, { passive: false });
+ canvasElement.addEventListener('touchcancel', this._handleTouchCancel, { passive: false });
+ this.disposeWithMe(toDisposable(() => {
+ canvasElement.removeEventListener('touchstart', this._handleTouchStart);
+ canvasElement.removeEventListener('touchmove', this._handleTouchMove);
+ canvasElement.removeEventListener('touchend', this._handleTouchEnd);
+ canvasElement.removeEventListener('touchcancel', this._handleTouchCancel);
+ this._finishPinch();
+ }));
+ }
+
+ private readonly _handleTouchStart = (event: TouchEvent): void => {
+ const { contextService, docViewScaleService, scene, viewport } = this._options;
+ if (event.touches.length !== 2 || scene.objectsEvented === false) {
+ return;
+ }
+
+ this._gestureOwned = true;
+ this._pinchZooming = true;
+ contextService.setContextValue(MOBILE_DOC_PINCH_ZOOMING, true);
+ const [touch1, touch2] = event.touches;
+ this._initialDistance = this._getTouchDistance(touch1, touch2);
+ this._initialZoomRatio = docViewScaleService.getUserZoomRatio();
+ this._anchor = viewport.transformVector2SceneCoord(this._getPinchCenter(touch1, touch2));
+ this._zoomIndicator.show(Math.round(this._initialZoomRatio * 100));
+ event.preventDefault();
+ };
+
+ private readonly _handleTouchMove = (event: TouchEvent): void => {
+ if (!this._gestureOwned || !this._pinchZooming || event.touches.length !== 2) {
+ return;
+ }
+
+ const { commandService, docViewScaleService, unitId, viewport } = this._options;
+ const [touch1, touch2] = event.touches;
+ const nextZoomRatio = resolveMobileDocPinchZoomRatio(
+ this._initialZoomRatio,
+ this._initialDistance,
+ this._getTouchDistance(touch1, touch2)
+ );
+ if (Math.abs(nextZoomRatio - docViewScaleService.getUserZoomRatio()) >= 0.01) {
+ commandService.syncExecuteCommand(SetDocZoomRatioOperation.id, { unitId, zoomRatio: nextZoomRatio });
+ }
+
+ const currentPoint = viewport.transformVector2SceneCoord(this._getPinchCenter(touch1, touch2));
+ viewport.scrollByViewportDeltaVal({
+ viewportScrollX: this._anchor.x - currentPoint.x,
+ viewportScrollY: this._anchor.y - currentPoint.y,
+ });
+ this._zoomIndicator.show(Math.round(nextZoomRatio * 100));
+ event.preventDefault();
+ };
+
+ private readonly _handleTouchEnd = (event: TouchEvent): void => {
+ if (!this._gestureOwned) {
+ return;
+ }
+ if (event.touches.length < 2 && this._pinchZooming) {
+ this._pinchZooming = false;
+ this._zoomIndicator.hide();
+ }
+ if (event.touches.length === 0) {
+ this._finishPinch();
+ }
+ };
+
+ private readonly _handleTouchCancel = (): void => this._finishPinch();
+
+ private _getTouchPoint(touch: Touch): Vector2 {
+ const { canvasElement, engine } = this._options;
+ const rect = canvasElement.getBoundingClientRect();
+ if (rect.width <= 0 || rect.height <= 0) {
+ return Vector2.FromArray([touch.clientX - rect.left, touch.clientY - rect.top]);
+ }
+
+ return Vector2.FromArray([
+ (touch.clientX - rect.left) * engine.width / rect.width,
+ (touch.clientY - rect.top) * engine.height / rect.height,
+ ]);
+ }
+
+ private _getPinchCenter(touch1: Touch, touch2: Touch): Vector2 {
+ const first = this._getTouchPoint(touch1);
+ const second = this._getTouchPoint(touch2);
+ return Vector2.FromArray([(first.x + second.x) / 2, (first.y + second.y) / 2]);
+ }
+
+ private _getTouchDistance(touch1: Touch, touch2: Touch): number {
+ const first = this._getTouchPoint(touch1);
+ const second = this._getTouchPoint(touch2);
+ return Math.hypot(first.x - second.x, first.y - second.y);
+ }
+
+ private _finishPinch(): void {
+ if (!this._gestureOwned) {
+ return;
+ }
+ this._gestureOwned = false;
+ this._pinchZooming = false;
+ this._options.contextService.setContextValue(MOBILE_DOC_PINCH_ZOOMING, false);
+ this._zoomIndicator.hide();
+ this._options.textSelectionManagerService.refreshSelection();
+ }
+}
diff --git a/packages/docs-ui/src/controllers/render-controllers/mobile/doc-selection-render.controller.ts b/packages/docs-ui/src/controllers/render-controllers/mobile/doc-selection-render.controller.ts
new file mode 100644
index 0000000000..89bd1a28f5
--- /dev/null
+++ b/packages/docs-ui/src/controllers/render-controllers/mobile/doc-selection-render.controller.ts
@@ -0,0 +1,751 @@
+/**
+ * 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, ICommandInfo } from '@univerjs/core';
+import type {
+ IMouseEvent,
+ IPointerEvent,
+ IRenderContext,
+ IRenderModule,
+ RenderComponentType,
+} from '@univerjs/engine-render';
+import type { ISetDocZoomRatioOperationParams } from '../../../commands/operations/set-doc-zoom-ratio.operation';
+import type { MobileDocSelectionRenderService } from '../../../services/mobile/doc-selection-render.service';
+import {
+ Disposable,
+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ DocumentFlavor,
+ ICommandService,
+ IContextService,
+ Inject,
+ isInternalEditorID,
+ IUniverInstanceService,
+ Optional,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';
+import {
+ CURSOR_TYPE,
+ DocumentEditArea,
+ NORMAL_TEXT_SELECTION_PLUGIN_STYLE,
+ PageLayoutType,
+ Vector2,
+} from '@univerjs/engine-render';
+import { IContextMenuService } from '@univerjs/ui';
+import { filter, fromEvent, take } from 'rxjs';
+import { neoGetDocObject } from '../../../basics/component-tools';
+import { VIEWPORT_KEY } from '../../../basics/docs-view-key';
+import { findFirstCursorOffset } from '../../../basics/selection';
+import { SetDocZoomRatioOperation } from '../../../commands/operations/set-doc-zoom-ratio.operation';
+import { DOC_CARET_MENU_ID, MOBILE_DOC_PINCH_ZOOMING } from '../../../consts/mobile-context';
+import {
+ IDocEmbedInteractionBoundaryService,
+ IDocEmbedRuntimeFocusCoordinator,
+} from '../../../services/doc-embed-integration.service';
+import { DocMobileElementMenuService } from '../../../services/doc-mobile-element-menu.service';
+import { IEditorService } from '../../../services/editor/editor-manager.service';
+import { DocSelectionRenderService } from '../../../services/selection/doc-selection-render.service';
+import { getEventClientPoint, isEmbedInteractionEvent } from '../doc-selection-render.util';
+
+const DOUBLE_TAP_INTERVAL = 450;
+const DOUBLE_TAP_DISTANCE = 28;
+const DRAG_THRESHOLD = 12;
+const INERTIA_DECELERATION_RATE = 0.992;
+const INERTIA_MIN_VELOCITY = 0.22;
+const INERTIA_MAX_VELOCITY = 12;
+
+export class MobileDocSelectionRenderController extends Disposable implements IRenderModule {
+ private _loadedMap = new WeakSet<RenderComponentType>();
+ private _deferredEditorFocusTimer: ReturnType<typeof setTimeout> | null = null;
+ private _gestureTimer: ReturnType<typeof setTimeout> | null = null;
+ private _gestureDisposables: Array<{ unsubscribe(): void }> = [];
+ private _lastTap: { x: number; y: number; time: number } | null = null;
+ private _inertiaAnimationId: number | null = null;
+ private _inertiaLastFrameTime = 0;
+ private _inertiaVelocity = { x: 0, y: 0 };
+ private _initialSelectionReady = false;
+
+ constructor(
+ private readonly _context: IRenderContext<DocumentDataModel>,
+ @ICommandService private readonly _commandService: ICommandService,
+ @IEditorService private readonly _editorService: IEditorService,
+ @IUniverInstanceService private readonly _instanceSrv: IUniverInstanceService,
+ @Inject(DocSelectionRenderService) private readonly _docSelectionRenderService: MobileDocSelectionRenderService,
+ @Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
+ @Inject(DocSelectionManagerService) private readonly _docSelectionManagerService: DocSelectionManagerService,
+ @IContextService private readonly _contextService: IContextService,
+ @IContextMenuService private readonly _contextMenuService: IContextMenuService,
+ @Inject(DocMobileElementMenuService) private readonly _mobileElementMenuService: DocMobileElementMenuService,
+ @Optional(IDocEmbedInteractionBoundaryService) _embedInteractionBoundaryService?: IDocEmbedInteractionBoundaryService,
+ @Optional(IDocEmbedRuntimeFocusCoordinator) private readonly _embedRuntimeFocusCoordinator?: IDocEmbedRuntimeFocusCoordinator
+ ) {
+ super();
+
+ this._initialize();
+ }
+
+ private _initialize(): void {
+ this._init();
+ this._refreshListener();
+ this._syncSelection();
+ this._skeletonListener();
+ this._commandExecutedListener();
+ }
+
+ private _init(): void {
+ const { unitId } = this._context;
+ const docObject = neoGetDocObject(this._context);
+ if (docObject == null || docObject.document == null) {
+ return;
+ }
+
+ if (!this._loadedMap.has(docObject.document)) {
+ this._initialMain(unitId);
+ this._loadedMap.add(docObject.document);
+ }
+ }
+
+ private _refreshListener(): void {
+ this.disposeWithMe(
+ this._docSelectionManagerService.refreshSelection$.subscribe((params) => {
+ if (params == null) {
+ return;
+ }
+
+ const { unitId, docRanges, isEditing, options } = params;
+ if (unitId !== this._context.unitId) {
+ return;
+ }
+
+ this._docSelectionRenderService.replaceDocRanges(docRanges, isEditing, options);
+ })
+ );
+ }
+
+ private _syncSelection(): void {
+ this.disposeWithMe(
+ this._docSelectionRenderService.textSelectionInner$.subscribe((params) => {
+ if (params == null) {
+ return;
+ }
+
+ if (!isInternalEditorID(this._context.unitId) && this._isEmbedChildInteractionActive(this._context.unitId)) {
+ return;
+ }
+
+ this._docSelectionManagerService.__replaceTextRangesWithNoRefresh(params, {
+ unitId: this._context.unitId,
+ subUnitId: this._context.unitId,
+ });
+ })
+ );
+ }
+
+ private _initialMain(unitId: string): void {
+ this.disposeWithMe(fromEvent<MouseEvent>(this._context.engine.getCanvasElement(), 'mousedown').subscribe((event) => {
+ // A compatibility mouse event must not steal focus after a WebKit touch.
+ if (event.button === 0 && this._docSelectionRenderService.isFocusing) {
+ event.preventDefault();
+ }
+ }));
+
+ if (isInternalEditorID(unitId)) {
+ this._initialEditor(unitId);
+ return;
+ }
+
+ const { document, scene } = neoGetDocObject(this._context);
+ this._docSelectionRenderService.exitMobileEditMode();
+ this.disposeWithMe(scene.onPointerDown$.subscribeEvent((event: IPointerEvent | IMouseEvent, state) => {
+ if (event.cancelable) {
+ event.preventDefault();
+ }
+ this._startGesture(event, this._docSelectionRenderService.isMobileEditMode, this._getDocumentOffset(event), false);
+ state.stopPropagation();
+ }));
+ this.disposeWithMe(document.onPointerDown$.subscribeEvent((event: IPointerEvent | IMouseEvent, state) => {
+ if (this._isEditorReadOnly(unitId) || this._isEmbedInteractionEvent(event, unitId)) {
+ return;
+ }
+
+ const current = this._instanceSrv.getCurrentUnitOfType(UniverInstanceType.UNIVER_DOC);
+ if (current?.getUnitId() !== unitId) {
+ this._instanceSrv.setCurrentUnitForType(unitId);
+ }
+ if (!this._editorService.getEditorRenderConfig(unitId)?.preserveHostFocus) {
+ this._instanceSrv.focusUnit(unitId);
+ }
+
+ const offset = this._getDocumentOffset(event);
+ this._syncEditArea(offset.offsetX, offset.offsetY);
+ if (event.cancelable) {
+ event.preventDefault();
+ }
+ this._startGesture(event, this._docSelectionRenderService.isMobileEditMode, offset);
+ if (event.button !== 2) {
+ state.stopPropagation();
+ }
+ }));
+ }
+
+ private _initialEditor(unitId: string): void {
+ const { document, scene } = neoGetDocObject(this._context);
+ this.disposeWithMe(document.onPointerEnter$.subscribeEvent(() => {
+ if (this._isEditorReadOnly(unitId)) {
+ return;
+ }
+ document.cursor = CURSOR_TYPE.TEXT;
+ }));
+
+ this.disposeWithMe(document.onPointerLeave$.subscribeEvent(() => {
+ document.cursor = CURSOR_TYPE.DEFAULT;
+ scene.resetCursor();
+ }));
+
+ this.disposeWithMe(document.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
+ if (this._isEditorReadOnly(unitId) || this._isEmbedInteractionEvent(evt, unitId)) {
+ return;
+ }
+
+ const docDataModel = this._instanceSrv.getCurrentUnitOfType(UniverInstanceType.UNIVER_DOC);
+ if (docDataModel?.getUnitId() !== unitId) {
+ this._instanceSrv.setCurrentUnitForType(unitId);
+ }
+ const isSheetEditor = unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY || unitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY;
+ if (!isSheetEditor && !this._editorService.getEditorRenderConfig(unitId)?.preserveHostFocus) {
+ this._instanceSrv.focusUnit(unitId);
+ }
+
+ const { offsetX, offsetY } = evt;
+ this._syncEditArea(offsetX, offsetY);
+ this._docSelectionRenderService.__onPointDown(evt, true);
+
+ if (this._editorService.getEditor(unitId)) {
+ this._setEditorFocus(unitId);
+ if (this._deferredEditorFocusTimer != null) {
+ clearTimeout(this._deferredEditorFocusTimer);
+ }
+ this._deferredEditorFocusTimer = setTimeout(() => {
+ this._deferredEditorFocusTimer = null;
+ if (unitId === this._editorService.getFocusId() || this._docSelectionRenderService.isOnPointerEvent) {
+ return;
+ }
+ this._setEditorFocus(unitId);
+ this._docSelectionRenderService.setCursorManually(offsetX, offsetY);
+ }, 0);
+ }
+
+ if (evt.button !== 2) {
+ state.stopPropagation();
+ }
+ }));
+
+ this.disposeWithMe(document.onDblclick$.subscribeEvent((evt: IPointerEvent | IMouseEvent) => {
+ if (this._isEditorReadOnly(unitId) || this._isEmbedInteractionEvent(evt, unitId)) {
+ return;
+ }
+
+ if (this._editorService.getEditor(unitId)) {
+ this._setEditorFocus(unitId);
+ }
+ this._docSelectionRenderService.__handleDblClick(evt);
+ }));
+
+ this.disposeWithMe(document.onTripleClick$.subscribeEvent((evt: IPointerEvent | IMouseEvent) => {
+ if (this._isEditorReadOnly(unitId) || this._isEmbedInteractionEvent(evt, unitId)) {
+ return;
+ }
+
+ this._docSelectionRenderService.__handleTripleClick(evt);
+ }));
+ }
+
+ override dispose(): void {
+ this._clearGesture();
+ this._stopInertia();
+ if (this._deferredEditorFocusTimer != null) {
+ clearTimeout(this._deferredEditorFocusTimer);
+ this._deferredEditorFocusTimer = null;
+ }
+ super.dispose();
+ }
+
+ private _syncEditArea(offsetX: number, offsetY: number): void {
+ const coord = this._getTransformCoordForDocumentOffset(offsetX, offsetY);
+ if (coord == null) {
+ return;
+ }
+
+ const { document } = neoGetDocObject(this._context);
+ const {
+ pageLayoutType = PageLayoutType.VERTICAL,
+ pageMarginLeft,
+ pageMarginTop,
+ } = document.getOffsetConfig();
+ const skeleton = this._docSkeletonManagerService.getSkeleton();
+ const { editArea } = skeleton.findEditAreaByCoord(
+ coord,
+ pageLayoutType,
+ pageMarginLeft,
+ pageMarginTop
+ );
+ const viewModel = this._docSkeletonManagerService.getViewModel();
+ const preEditArea = viewModel.getEditArea();
+
+ if (preEditArea !== DocumentEditArea.BODY && editArea !== DocumentEditArea.BODY && editArea !== preEditArea) {
+ viewModel.setEditArea(editArea);
+ }
+ }
+
+ // eslint-disable-next-line max-lines-per-function
+ private _startGesture(
+ evt: IPointerEvent | IMouseEvent,
+ startedWhileEditing: boolean,
+ documentOffset: { offsetX: number; offsetY: number },
+ allowTextInteraction = true
+ ): void {
+ this._clearGesture();
+ this._stopInertia();
+ const elementTarget = allowTextInteraction ? this._mobileElementMenuService.takeTarget(this._context.unitId) : null;
+ this._mobileElementMenuService.close();
+ if (this._contextMenuService.visible) {
+ this._contextMenuService.hideContextMenu();
+ }
+ const scene = this._context.scene;
+ const viewport = scene.getViewport(VIEWPORT_KEY.VIEW_MAIN) ?? scene.getViewports()[0];
+ const isModernDocument = this._context.unit.getSnapshot().documentStyle.documentFlavor === DocumentFlavor.MODERN;
+ const { x: startX, y: startY } = getGesturePoint(evt);
+ let [previousX, previousY] = [startX, startY];
+ let moved = false;
+ let selected = false;
+ const inertiaTracker = createInertiaTracker(isModernDocument);
+ const activeRange = this._docSelectionRenderService.getActiveTextRange();
+ const activeOffset = activeRange?.collapsed ? activeRange.startOffset ?? null : null;
+ const inputWasFocused = this._docSelectionRenderService.isFocusing;
+
+ if (allowTextInteraction && !elementTarget?.onTap && !elementTarget?.onDrag) {
+ this._gestureTimer = setTimeout(() => {
+ this._gestureTimer = null;
+ if (this._contextService.getContextValue(MOBILE_DOC_PINCH_ZOOMING)) {
+ return;
+ }
+ selected = true;
+ this._selectWord(evt, startedWhileEditing);
+ }, 420);
+ }
+
+ const moveDisposable = scene.onPointerMove$.subscribeEvent((moveEvent: IPointerEvent | IMouseEvent) => {
+ if (selected || this._contextService.getContextValue(MOBILE_DOC_PINCH_ZOOMING)) {
+ return;
+ }
+ const { x: moveX, y: moveY } = getGesturePoint(moveEvent);
+ const deltaX = moveX - previousX;
+ const deltaY = moveY - previousY;
+ if (!moved && Math.hypot(moveX - startX, moveY - startY) < DRAG_THRESHOLD) {
+ return;
+ }
+
+ moved = true;
+ this._lastTap = null;
+ this._clearGestureTimer();
+ if (elementTarget?.onDrag) {
+ elementTarget.onDrag(moveEvent);
+ } else {
+ this._scrollDocument(viewport, isModernDocument, deltaX, deltaY);
+ inertiaTracker.track(deltaX, deltaY);
+ }
+ previousX = moveX;
+ previousY = moveY;
+ });
+ const upDisposable = scene.onPointerUp$.subscribeEvent(() => {
+ if (this._contextService.getContextValue(MOBILE_DOC_PINCH_ZOOMING)) {
+ this._clearGesture();
+ return;
+ }
+ if (allowTextInteraction && !moved && !selected) {
+ if (elementTarget) {
+ if (elementTarget.onTap) {
+ elementTarget.onTap(documentOffset);
+ } else {
+ this._mobileElementMenuService.show(elementTarget);
+ }
+ } else {
+ this._handleTap(evt, documentOffset, startedWhileEditing, inputWasFocused, activeOffset);
+ }
+ }
+ if (moved && !elementTarget?.onDrag) {
+ this._startInertia(viewport, inertiaTracker.getVelocity());
+ }
+ this._clearGesture();
+ });
+ const cancelDisposable = scene.onPointerCancel$.subscribeEvent(() => this._clearGesture());
+ this._gestureDisposables = [moveDisposable, upDisposable, cancelDisposable];
+ }
+
+ private _handleTap(
+ evt: IPointerEvent | IMouseEvent,
+ documentOffset: { offsetX: number; offsetY: number },
+ startedWhileEditing: boolean,
+ inputWasFocused: boolean,
+ activeOffset: number | null
+ ): void {
+ const { offsetX, offsetY } = documentOffset;
+ this._context.scene.getTransformer()?.clearSelectedObjects();
+ if (startedWhileEditing) {
+ this._docSelectionRenderService.setCursorManually(offsetX, offsetY, true, true, { strict: false });
+ const nextRange = this._docSelectionRenderService.getActiveTextRange();
+ if (inputWasFocused && activeOffset != null && nextRange?.collapsed && nextRange.startOffset === activeOffset) {
+ this._showCaretMenu(evt);
+ }
+ return;
+ }
+
+ const now = Date.now();
+ const lastTap = this._lastTap;
+ const isDoubleTap = lastTap != null &&
+ now - lastTap.time <= DOUBLE_TAP_INTERVAL &&
+ Math.hypot(offsetX - lastTap.x, offsetY - lastTap.y) <= DOUBLE_TAP_DISTANCE;
+ if (isDoubleTap) {
+ this._lastTap = null;
+ this._enterEditing(this._context.unitId, evt);
+ } else {
+ this._lastTap = { x: offsetX, y: offsetY, time: now };
+ }
+ }
+
+ private _selectWord(evt: IPointerEvent | IMouseEvent, startedWhileEditing: boolean): void {
+ this._context.scene.getTransformer()?.clearSelectedObjects();
+ this._lastTap = null;
+ this._docSelectionRenderService.__handleDblClick(evt, false, false);
+ if (startedWhileEditing) {
+ this._docSelectionRenderService.suspendMobileEditingInput();
+ }
+ }
+
+ private _scrollDocument(
+ viewport: ReturnType<IRenderContext<DocumentDataModel>['scene']['getViewports']>[number] | undefined,
+ isModernDocument: boolean,
+ deltaX: number,
+ deltaY: number
+ ): void {
+ const { scaleX, scaleY } = this._context.scene;
+ viewport?.scrollByViewportDeltaVal({
+ viewportScrollX: isModernDocument ? 0 : normalizeScrollDelta(-deltaX, scaleX),
+ viewportScrollY: normalizeScrollDelta(-deltaY, scaleY),
+ });
+ }
+
+ private _startInertia(
+ viewport: ReturnType<IRenderContext<DocumentDataModel>['scene']['getViewports']>[number] | undefined,
+ velocity: { x: number; y: number }
+ ): void {
+ const maxVelocity = INERTIA_MAX_VELOCITY;
+ this._inertiaVelocity = {
+ x: Math.max(-maxVelocity, Math.min(maxVelocity, velocity.x)),
+ y: Math.max(-maxVelocity, Math.min(maxVelocity, velocity.y)),
+ };
+ if (Math.hypot(this._inertiaVelocity.x, this._inertiaVelocity.y) <= INERTIA_MIN_VELOCITY * 2) {
+ return;
+ }
+
+ this._inertiaLastFrameTime = 0;
+ const scroll = (currentTime: number) => {
+ if (this._inertiaLastFrameTime === 0) {
+ this._inertiaLastFrameTime = currentTime;
+ this._inertiaAnimationId = requestAnimationFrame(scroll);
+ return;
+ }
+
+ const deltaTime = currentTime - this._inertiaLastFrameTime;
+ this._inertiaLastFrameTime = currentTime;
+ const decelerationRate = INERTIA_DECELERATION_RATE;
+ const decelerationFactor = decelerationRate ** deltaTime;
+ this._inertiaVelocity.x *= decelerationFactor;
+ this._inertiaVelocity.y *= decelerationFactor;
+ const dampingFactor = -Math.log(decelerationRate);
+ const { scaleX, scaleY } = this._context.scene;
+ viewport?.scrollByViewportDeltaVal({
+ viewportScrollX: normalizeScrollDelta(
+ this._inertiaVelocity.x * (1 - decelerationFactor) / dampingFactor,
+ scaleX
+ ),
+ viewportScrollY: normalizeScrollDelta(
+ this._inertiaVelocity.y * (1 - decelerationFactor) / dampingFactor,
+ scaleY
+ ),
+ });
+
+ if (Math.hypot(this._inertiaVelocity.x, this._inertiaVelocity.y) > INERTIA_MIN_VELOCITY) {
+ this._inertiaAnimationId = requestAnimationFrame(scroll);
+ } else {
+ this._inertiaAnimationId = null;
+ this._inertiaLastFrameTime = 0;
+ }
+ };
+ this._inertiaAnimationId = requestAnimationFrame(scroll);
+ }
+
+ private _stopInertia(): void {
+ if (this._inertiaAnimationId != null) {
+ cancelAnimationFrame(this._inertiaAnimationId);
+ }
+ this._inertiaAnimationId = null;
+ this._inertiaLastFrameTime = 0;
+ this._inertiaVelocity = { x: 0, y: 0 };
+ }
+
+ private _enterEditing(unitId: string, evt: IPointerEvent | IMouseEvent): void {
+ if (this._editorService.getEditor(unitId)) {
+ this._setEditorFocus(unitId);
+ }
+ this._docSelectionRenderService.enterMobileEditMode();
+ const { offsetX, offsetY } = this._getDocumentOffset(evt);
+ this._docSelectionRenderService.setCursorManually(offsetX, offsetY, true, true, { strict: false });
+ }
+
+ private _getDocumentOffset(evt: IPointerEvent | IMouseEvent): { offsetX: number; offsetY: number } {
+ const engine = this._context.scene.getEngine();
+ const canvas = engine?.getCanvasElement();
+ if (!engine || !canvas || !Number.isFinite(evt.clientX) || !Number.isFinite(evt.clientY)) {
+ return { offsetX: evt.offsetX, offsetY: evt.offsetY };
+ }
+
+ const rect = canvas.getBoundingClientRect();
+ if (rect.width <= 0 || rect.height <= 0) {
+ return { offsetX: evt.offsetX, offsetY: evt.offsetY };
+ }
+
+ return {
+ offsetX: (evt.clientX - rect.left) * engine.width / rect.width,
+ offsetY: (evt.clientY - rect.top) * engine.height / rect.height,
+ };
+ }
+
+ private _showCaretMenu(evt: IPointerEvent | IMouseEvent): void {
+ const point = getEventClientPoint(evt, null);
+ this._contextMenuService.triggerContextMenu({
+ clientX: point?.clientX ?? evt.offsetX,
+ clientY: point?.clientY ?? evt.offsetY,
+ stopPropagation() {},
+ }, DOC_CARET_MENU_ID, {
+ caretAnchor: true,
+ unitId: this._context.unitId,
+ subUnitId: this._context.unitId,
+ });
+ }
+
+ private _clearGestureTimer(): void {
+ if (this._gestureTimer == null) {
+ return;
+ }
+ clearTimeout(this._gestureTimer);
+ this._gestureTimer = null;
+ }
+
+ private _clearGesture(): void {
+ this._clearGestureTimer();
+ this._gestureDisposables.forEach((disposable) => disposable.unsubscribe());
+ this._gestureDisposables = [];
+ }
+
+ private _getTransformCoordForDocumentOffset(evtOffsetX: number, evtOffsetY: number) {
+ const { document, scene } = neoGetDocObject(this._context);
+ const { documentTransform } = document.getOffsetConfig();
+ const activeViewport = scene.getViewports()[0];
+ if (activeViewport == null) {
+ return;
+ }
+
+ const originCoord = activeViewport.transformVector2SceneCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
+ return documentTransform.clone().invert().applyPoint(originCoord);
+ }
+
+ private _isEditorReadOnly(unitId: string): boolean {
+ return this._editorService.getEditor(unitId)?.isReadOnly() ?? false;
+ }
+
+ private _setEditorFocus(unitId: string): void {
+ this._editorService.focus(unitId);
+ }
+
+ private _isEmbedInteractionEvent(evt: IPointerEvent | IMouseEvent, unitId: string): boolean {
+ if (isInternalEditorID(unitId)) {
+ return false;
+ }
+
+ const target = (evt as Event).target;
+ if (this._embedRuntimeFocusCoordinator?.isChildUnitRuntimeEvent(unitId, target, evt as Event)) {
+ return false;
+ }
+ if (this._embedRuntimeFocusCoordinator?.isChildUnitInActiveSession(unitId)) {
+ return false;
+ }
+ if (this._embedRuntimeFocusCoordinator?.shouldSuppressHostInteraction(unitId, target, evt as Event)) {
+ return true;
+ }
+
+ return isEmbedInteractionEvent(evt);
+ }
+
+ private _isEmbedChildInteractionActive(unitId: string): boolean {
+ return this._embedRuntimeFocusCoordinator?.shouldSuppressHostInteraction(unitId) === true;
+ }
+
+ private _commandExecutedListener(): void {
+ const updateCommandList = [SetDocZoomRatioOperation.id];
+ this.disposeWithMe(this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (!updateCommandList.includes(command.id)) {
+ return;
+ }
+
+ const params = command.params as ISetDocZoomRatioOperationParams;
+ const { unitId: documentId } = params;
+ if (this._contextService.getContextValue(MOBILE_DOC_PINCH_ZOOMING)) {
+ return;
+ }
+
+ const unitId = this._docSelectionManagerService.__getCurrentSelection()?.unitId;
+ if (documentId !== unitId || this._isEmbedChildInteractionActive(documentId)) {
+ return;
+ }
+
+ this._docSelectionManagerService.refreshSelection();
+ }));
+ }
+
+ private _skeletonListener(): void {
+ this.disposeWithMe(this._docSkeletonManagerService.currentSkeleton$.subscribe((skeleton) => {
+ if (!skeleton || this._initialSelectionReady) {
+ return;
+ }
+
+ const { unitId } = this._context;
+ if (isInternalEditorID(unitId) || this._isEmbedChildInteractionActive(unitId)) {
+ return;
+ }
+ this._initialSelectionReady = true;
+
+ const snapshot = this._context.unit.getSnapshot();
+ const offset = findFirstCursorOffset(snapshot);
+ const selectionTarget = { unitId, subUnitId: unitId };
+ this._docSelectionManagerService.replaceSelectionInfoWithoutRefresh({
+ textRanges: [{
+ startOffset: offset,
+ endOffset: offset,
+ collapsed: true,
+ isActive: true,
+ }],
+ rectRanges: [],
+ segmentId: '',
+ segmentPage: -1,
+ isEditing: false,
+ style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE,
+ }, selectionTarget);
+ this._docSelectionManagerService.refreshSelection(selectionTarget, false);
+ if (this._docSelectionRenderService.getActiveTextRange() == null) {
+ this.disposeWithMe(skeleton.layoutProgress$
+ .pipe(
+ filter((progress) => progress?.anchorReady === true || progress?.complete === true),
+ take(1)
+ )
+ .subscribe(() => this._docSelectionManagerService.refreshSelection(selectionTarget, false)));
+ }
+ }));
+ }
+}
+
+function getGesturePoint(evt: IPointerEvent | IMouseEvent): { x: number; y: number } {
+ const point = getEventClientPoint(evt, null);
+ return {
+ x: point?.clientX ?? evt.offsetX,
+ y: point?.clientY ?? evt.offsetY,
+ };
+}
+
+function normalizeScrollDelta(delta: number, scale: number): number {
+ return delta / (Number.isFinite(scale) && scale > 0 ? scale : 1);
+}
+
+function createInertiaTracker(isModernDocument: boolean) {
+ const startTime = performance.now();
+ let lastMoveTime = startTime;
+ const history: Array<{ x: number; y: number }> = [];
+ const displacement = { x: 0, y: 0 };
+
+ return {
+ track(deltaX: number, deltaY: number): void {
+ const currentTime = performance.now();
+ const deltaTime = currentTime - lastMoveTime;
+ lastMoveTime = currentTime;
+ if (deltaTime <= 0) {
+ return;
+ }
+
+ const scrollDeltaX = isModernDocument ? 0 : -deltaX;
+ const scrollDeltaY = -deltaY;
+ history.push({
+ x: scrollDeltaX / deltaTime * 16,
+ y: scrollDeltaY / deltaTime * 16,
+ });
+ if (history.length > 5) {
+ history.shift();
+ }
+ displacement.x += Math.abs(scrollDeltaX);
+ displacement.y += Math.abs(scrollDeltaY);
+ },
+ getVelocity: () => calculateInertiaVelocity(history, performance.now() - startTime, displacement),
+ };
+}
+
+function calculateInertiaVelocity(
+ history: Array<{ x: number; y: number }>,
+ duration: number,
+ displacement: { x: number; y: number }
+): { x: number; y: number } {
+ if (history.length === 0) {
+ return { x: 0, y: 0 };
+ }
+
+ let totalWeight = 0;
+ let velocityX = 0;
+ let velocityY = 0;
+ history.forEach((sample, index) => {
+ const weight = (index + 1) ** 2;
+ totalWeight += weight;
+ velocityX += sample.x * weight;
+ velocityY += sample.y * weight;
+ });
+ velocityX /= totalWeight;
+ velocityY /= totalWeight;
+
+ const distance = Math.hypot(displacement.x, displacement.y);
+ const speed = Math.hypot(velocityX, velocityY);
+ const swipeSpeed = duration > 0 ? distance / duration : 0;
+ const isFlick = duration < 240 && distance > 30;
+ let multiplier = 0.05 * (0.5 + Math.min(speed / 5, 1) * 0.5);
+ if (isFlick) {
+ multiplier = 0.05 + (0.26 - 0.05) * Math.min(swipeSpeed / 2, 1);
+ if (duration < 150 && speed > 3) {
+ multiplier *= 1.3;
+ }
+ }
+ multiplier = Math.max(0.025, Math.min(0.39, multiplier));
+
+ return displacement.x > displacement.y
+ ? { x: velocityX * multiplier, y: 0 }
+ : { x: 0, y: velocityY * multiplier };
+}
diff --git a/packages/docs-ui/src/controllers/render-controllers/mobile/doc.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/mobile/doc.render-controller.ts
new file mode 100644
index 0000000000..639e1e5682
--- /dev/null
+++ b/packages/docs-ui/src/controllers/render-controllers/mobile/doc.render-controller.ts
@@ -0,0 +1,140 @@
+/**
+ * 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 } from '@univerjs/core';
+import type { DocumentSkeleton, IRenderContext } from '@univerjs/engine-render';
+import type { IDocLayoutScheduleOptions } from '../doc.render-controller';
+import {
+ DocumentFlavor,
+ fromEventSubject,
+ ICommandService,
+ ILogService,
+ Inject,
+ IUniverInstanceService,
+ ThemeService,
+} from '@univerjs/core';
+import { DocLayoutExecutorService, DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { animationFrameScheduler, takeUntil, throttleTime } from 'rxjs';
+import { DocLayoutInteractionService } from '../../../services/doc-layout-interaction.service';
+import { DocPageLayoutService } from '../../../services/doc-page-layout.service';
+import { DocViewScaleService } from '../../../services/doc-view-scale';
+import { IEditorService } from '../../../services/editor/editor-manager.service';
+import { DocSelectionRenderService } from '../../../services/selection/doc-selection-render.service';
+import { DocRenderController } from '../doc.render-controller';
+
+const MOBILE_DOC_OUTER_MARGIN = 12;
+
+export class MobileDocRenderController extends DocRenderController {
+ private _mobileModernPageWidth: number | undefined;
+
+ constructor(
+ context: IRenderContext<DocumentDataModel>,
+ @ICommandService commandService: ICommandService,
+ @Inject(DocSelectionRenderService) docSelectionRenderService: DocSelectionRenderService,
+ @Inject(DocSkeletonManagerService) docSkeletonManagerService: DocSkeletonManagerService,
+ @IEditorService editorService: IEditorService,
+ @IRenderManagerService renderManagerService: IRenderManagerService,
+ @IUniverInstanceService univerInstanceService: IUniverInstanceService,
+ @Inject(DocPageLayoutService) docPageLayoutService: DocPageLayoutService,
+ @Inject(DocSelectionManagerService) textSelectionManagerService: DocSelectionManagerService,
+ @Inject(DocViewScaleService) docViewScaleService: DocViewScaleService,
+ @Inject(ThemeService) themeService: ThemeService,
+ @Inject(DocLayoutExecutorService) docLayoutExecutorService: DocLayoutExecutorService,
+ @Inject(DocLayoutInteractionService) docLayoutInteractionService: DocLayoutInteractionService,
+ @ILogService logService: ILogService
+ ) {
+ super(
+ context,
+ commandService,
+ docSelectionRenderService,
+ docSkeletonManagerService,
+ editorService,
+ renderManagerService,
+ univerInstanceService,
+ docPageLayoutService,
+ textSelectionManagerService,
+ docViewScaleService,
+ themeService,
+ docLayoutExecutorService,
+ docLayoutInteractionService,
+ logService
+ );
+ this._mobileModernPageWidth = this._getMobileModernLayoutOptions().modernPageWidth;
+ this._initResponsiveLayout();
+ }
+
+ protected override _scheduleLayout(
+ unitId: string,
+ skeleton: DocumentSkeleton,
+ options: IDocLayoutScheduleOptions,
+ refreshMainSelection = true,
+ preserveInactiveViewportAnchor = false
+ ): void {
+ const layoutOptions = {
+ ...options,
+ ...this._getMobileModernLayoutOptions(),
+ };
+ this._mobileModernPageWidth = layoutOptions.modernPageWidth;
+ super._scheduleLayout(unitId, skeleton, layoutOptions, refreshMainSelection, preserveInactiveViewportAnchor);
+ }
+
+ protected override _shouldEnableHorizontalScrollBar(): boolean {
+ return this._context.unit.getSnapshot().documentStyle.documentFlavor !== DocumentFlavor.MODERN &&
+ super._shouldEnableHorizontalScrollBar();
+ }
+
+ private _getMobileModernLayoutOptions(): Pick<IDocLayoutScheduleOptions, 'modernPageWidth' | 'modernHorizontalMargin'> {
+ if (this._context.unit.getSnapshot().documentStyle.documentFlavor !== DocumentFlavor.MODERN) {
+ return {};
+ }
+
+ const parentWidth = this._context.scene.getParent()?.width;
+ const availableWidth = parentWidth != null && parentWidth > 1 ? parentWidth : this._context.engine.width;
+ if (!Number.isFinite(availableWidth) || availableWidth <= MOBILE_DOC_OUTER_MARGIN * 2) {
+ return {};
+ }
+
+ return {
+ modernPageWidth: availableWidth - MOBILE_DOC_OUTER_MARGIN * 2,
+ modernHorizontalMargin: super._getHorizontalPageMargin(),
+ };
+ }
+
+ private _initResponsiveLayout(): void {
+ if (this._context.unit.getSnapshot().documentStyle.documentFlavor !== DocumentFlavor.MODERN) {
+ return;
+ }
+
+ this.disposeWithMe(fromEventSubject(this._context.engine.onTransformChange$).pipe(
+ throttleTime(0, animationFrameScheduler),
+ takeUntil(this.dispose$)
+ ).subscribe(() => {
+ const modernPageWidth = this._getMobileModernLayoutOptions().modernPageWidth;
+ if (modernPageWidth == null || Math.abs(modernPageWidth - (this._mobileModernPageWidth ?? 0)) < 1) {
+ return;
+ }
+ const skeleton = this._docSkeletonManagerService.getSkeleton();
+ if (skeleton) {
+ this._scheduleLayout(this._context.unitId, skeleton, { reason: 'initial' });
+ }
+ }));
+ }
+
+ protected override _getHorizontalPageMargin(): number {
+ return MOBILE_DOC_OUTER_MARGIN;
+ }
+}
diff --git a/packages/docs-ui/src/controllers/render-controllers/mobile/zoom.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/mobile/zoom.render-controller.ts
new file mode 100644
index 0000000000..5df09ec853
--- /dev/null
+++ b/packages/docs-ui/src/controllers/render-controllers/mobile/zoom.render-controller.ts
@@ -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 { DocumentDataModel, ICommandInfo } from '@univerjs/core';
+import type { IRenderContext } from '@univerjs/engine-render';
+import type { IDocPageSetupCommandParams } from '../../../commands/commands/doc-page-setup.command';
+import type { ISetDocZoomRatioOperationParams } from '../../../commands/operations/set-doc-zoom-ratio.operation';
+import {
+ DocumentFlavor,
+ ICommandService,
+ IContextService,
+ Inject,
+ isInternalEditorID,
+ IUniverInstanceService,
+ Optional,
+} from '@univerjs/core';
+import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { VIEWPORT_KEY } from '../../../basics/docs-view-key';
+import { DocPageSetupCommand } from '../../../commands/commands/doc-page-setup.command';
+import { SetDocZoomRatioCommand } from '../../../commands/commands/set-doc-zoom-ratio.command';
+import { SwitchDocModeCommand } from '../../../commands/commands/switch-doc-mode.command';
+import { SetDocZoomRatioOperation } from '../../../commands/operations/set-doc-zoom-ratio.operation';
+import { MOBILE_DOC_PINCH_ZOOMING } from '../../../consts/mobile-context';
+import { IDocEmbedInteractionBoundaryService } from '../../../services/doc-embed-integration.service';
+import { DocPageLayoutService } from '../../../services/doc-page-layout.service';
+import { DocViewScaleService } from '../../../services/doc-view-scale';
+import { DEFAULT_MODERN_DOC_ZOOM_RATIO, getDocEffectiveZoomRatio } from '../../../services/doc-zoom';
+import { IEditorService } from '../../../services/editor/editor-manager.service';
+import { DocZoomRenderController } from '../zoom.render-controller';
+import { MobileDocPinchZoomGesture } from './doc-pinch-zoom';
+
+export class MobileDocZoomRenderController extends DocZoomRenderController {
+ constructor(
+ context: IRenderContext<DocumentDataModel>,
+ @IContextService contextService: IContextService,
+ @Inject(DocSkeletonManagerService) docSkeletonManagerService: DocSkeletonManagerService,
+ @IUniverInstanceService univerInstanceService: IUniverInstanceService,
+ @ICommandService commandService: ICommandService,
+ @Inject(DocSelectionManagerService) textSelectionManagerService: DocSelectionManagerService,
+ @IEditorService editorService: IEditorService,
+ @Inject(DocPageLayoutService) docPageLayoutService: DocPageLayoutService,
+ @IRenderManagerService renderManagerService: IRenderManagerService,
+ @Inject(DocViewScaleService) docViewScaleService: DocViewScaleService,
+ @Optional(IDocEmbedInteractionBoundaryService) embedInteractionBoundaryService?: IDocEmbedInteractionBoundaryService
+ ) {
+ super(
+ context,
+ contextService,
+ docSkeletonManagerService,
+ univerInstanceService,
+ commandService,
+ textSelectionManagerService,
+ editorService,
+ docPageLayoutService,
+ renderManagerService,
+ docViewScaleService,
+ embedInteractionBoundaryService
+ );
+
+ if (!isInternalEditorID(context.unitId)) {
+ this._initGestureZoom();
+ }
+ }
+
+ protected override _initCommandExecutedListener(): void {
+ const updateCommandList = [SetDocZoomRatioOperation.id];
+
+ this.disposeWithMe(this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (updateCommandList.includes(command.id) && (command.params as ISetDocZoomRatioOperationParams).unitId === this._context.unitId) {
+ const zoomRatio = getDocEffectiveZoomRatio(this._context.unit);
+ this.updateViewZoom(
+ zoomRatio,
+ !this._contextService.getContextValue(MOBILE_DOC_PINCH_ZOOMING)
+ );
+ }
+ }));
+
+ this.disposeWithMe(
+ this._commandService.beforeCommandExecuted((command: ICommandInfo) => {
+ const shouldResetZoom = command.id === SwitchDocModeCommand.id ||
+ (command.id === DocPageSetupCommand.id && (command.params as IDocPageSetupCommandParams | undefined)?.documentFlavor === DocumentFlavor.MODERN);
+
+ if (shouldResetZoom) {
+ this._commandService.executeCommand(SetDocZoomRatioCommand.id, {
+ zoomRatio: DEFAULT_MODERN_DOC_ZOOM_RATIO,
+ documentId: this._context.unitId,
+ });
+ }
+ })
+ );
+ }
+
+ private _initGestureZoom(): void {
+ if (
+ this._context.unit.getSnapshot().documentStyle.documentFlavor !== DocumentFlavor.TRADITIONAL
+ ) {
+ return;
+ }
+
+ const scene = this._context.scene;
+ const engine = scene.getEngine();
+ const canvasElement = engine?.getCanvasElement();
+ const viewport = scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
+ if (engine == null || canvasElement == null || viewport == null) {
+ return;
+ }
+
+ this.disposeWithMe(new MobileDocPinchZoomGesture({
+ canvasElement,
+ commandService: this._commandService,
+ contextService: this._contextService,
+ docViewScaleService: this._docViewScaleService,
+ engine,
+ scene,
+ textSelectionManagerService: this._textSelectionManagerService,
+ unitId: this._context.unitId,
+ viewport,
+ }));
+ }
+}
diff --git a/packages/docs-ui/src/controllers/render-controllers/zoom.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/zoom.render-controller.ts
index edf3285c0a..39807a0fd0 100644
--- a/packages/docs-ui/src/controllers/render-controllers/zoom.render-controller.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/zoom.render-controller.ts
@@ -23,6 +23,7 @@ import {
DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
DocumentFlavor,
FOCUSING_DOC,
+ fromEventSubject,
ICommandService,
IContextService,
Inject,
@@ -33,6 +34,7 @@ import {
} from '@univerjs/core';
import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';
import { getNextWheelZoomRatio, IRenderManagerService } from '@univerjs/engine-render';
+import { animationFrameScheduler, throttleTime } from 'rxjs';
import { neoGetDocObject } from '../../basics/component-tools';
import { DocPageSetupCommand } from '../../commands/commands/doc-page-setup.command';
import { SetDocZoomRatioCommand } from '../../commands/commands/set-doc-zoom-ratio.command';
@@ -56,24 +58,26 @@ export class DocZoomRenderController extends Disposable implements IRenderModule
private _isSheetEditor = false;
private _initTimer: number;
private _updateTimer: number;
+ private _fitToWidthAvailableWidth = 0;
constructor(
- private readonly _context: IRenderContext<DocumentDataModel>,
- @IContextService private readonly _contextService: IContextService,
+ protected readonly _context: IRenderContext<DocumentDataModel>,
+ @IContextService protected readonly _contextService: IContextService,
@Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
- @ICommandService private readonly _commandService: ICommandService,
- @Inject(DocSelectionManagerService) private readonly _textSelectionManagerService: DocSelectionManagerService,
+ @ICommandService protected readonly _commandService: ICommandService,
+ @Inject(DocSelectionManagerService) protected readonly _textSelectionManagerService: DocSelectionManagerService,
@IEditorService private readonly _editorService: IEditorService,
@Inject(DocPageLayoutService) private readonly _docPageLayoutService: DocPageLayoutService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @Inject(DocViewScaleService) private readonly _docViewScaleService: DocViewScaleService,
+ @Inject(DocViewScaleService) protected readonly _docViewScaleService: DocViewScaleService,
@Optional(IDocEmbedInteractionBoundaryService) private readonly _embedInteractionBoundaryService?: IDocEmbedInteractionBoundaryService
) {
super();
this._initSkeletonListener();
this._initCommandExecutedListener();
+ this._initFitToWidthResizeListener();
this._isSheetEditor = this._context.unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY;
const currentSheet = this._univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);
const sheetRenderer = currentSheet && this._renderManagerService.getRenderUnitById(currentSheet.getUnitId());
@@ -94,6 +98,7 @@ export class DocZoomRenderController extends Disposable implements IRenderModule
override dispose() {
window.clearTimeout(this._initTimer);
window.clearTimeout(this._updateTimer);
+ super.dispose();
}
private _initSkeletonListener() {
@@ -115,7 +120,7 @@ export class DocZoomRenderController extends Disposable implements IRenderModule
}));
}
- private _initCommandExecutedListener() {
+ protected _initCommandExecutedListener() {
const updateCommandList = [SetDocZoomRatioOperation.id];
this.disposeWithMe(this._commandService.onCommandExecuted((command: ICommandInfo) => {
@@ -141,6 +146,24 @@ export class DocZoomRenderController extends Disposable implements IRenderModule
);
}
+ private _initFitToWidthResizeListener(): void {
+ this.disposeWithMe(fromEventSubject(this._context.engine.onTransformChange$).pipe(
+ throttleTime(0, animationFrameScheduler)
+ ).subscribe(() => {
+ if (this._docViewScaleService.getOptions().mode !== 'fit-width') {
+ return;
+ }
+
+ const availableWidth = this._docViewScaleService.getAvailableWidth();
+ if (availableWidth <= 1 || Math.abs(availableWidth - this._fitToWidthAvailableWidth) < 1) {
+ return;
+ }
+
+ this._fitToWidthAvailableWidth = availableWidth;
+ this.updateViewZoom(getDocEffectiveZoomRatio(this._context.unit), false);
+ }));
+ }
+
updateViewZoom(zoomRatio: number, needRefreshSelection = true) {
const docObject = neoGetDocObject(this._context);
const viewScale = this._docViewScaleService.getViewScale(zoomRatio);
diff --git a/packages/docs-ui/src/facade/__tests__/f-document.spec.ts b/packages/docs-ui/src/facade/__tests__/f-document.spec.ts
index 40b07f6807..4b3c128043 100644
--- a/packages/docs-ui/src/facade/__tests__/f-document.spec.ts
+++ b/packages/docs-ui/src/facade/__tests__/f-document.spec.ts
@@ -22,14 +22,16 @@ import { BooleanNumber, DocumentFlavor, ICommandService, IUniverInstanceService,
import { FUniver } from '@univerjs/core/facade';
import { DocLayoutExecutorService, DocSelectionManagerService, DocSkeletonManagerService, DocStateEmitService, SetTextSelectionsOperation } from '@univerjs/docs';
import { CanvasColorService, ICanvasColorService, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
-import { ILayoutService } from '@univerjs/ui';
+import { CanvasPopupService, ContextMenuService, ICanvasPopupService, IContextMenuService, ILayoutService } from '@univerjs/ui';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { DocBackScrollRenderController } from '../../controllers/render-controllers/back-scroll.render-controller';
import { DocSelectionRenderController } from '../../controllers/render-controllers/doc-selection-render.controller';
import { DocRenderController } from '../../controllers/render-controllers/doc.render-controller';
import { DocLayoutInteractionService } from '../../services/doc-layout-interaction.service';
import { DocMenuStyleService } from '../../services/doc-menu-style.service';
+import { DocMobileElementMenuService } from '../../services/doc-mobile-element-menu.service';
import { DocPageLayoutService } from '../../services/doc-page-layout.service';
+import { DocCanvasPopManagerService } from '../../services/doc-popup-manager.service';
import { DocViewScaleService } from '../../services/doc-view-scale';
import { EditorService, IEditorService } from '../../services/editor/editor-manager.service';
import { DocSelectionRenderService } from '../../services/selection/doc-selection-render.service';
@@ -46,6 +48,10 @@ function createEditor() {
registerContainerElement: () => ({ dispose() {} }),
} as unknown as ILayoutService }]);
injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
+ injector.add([ICanvasPopupService, { useClass: CanvasPopupService }]);
+ injector.add([IContextMenuService, { useClass: ContextMenuService }]);
+ injector.add([DocCanvasPopManagerService]);
+ injector.add([DocMobileElementMenuService]);
injector.add([ICanvasColorService, { useClass: CanvasColorService }]);
injector.add([DocLayoutExecutorService]);
injector.add([DocSelectionManagerService]);
diff --git a/packages/docs-ui/src/index.ts b/packages/docs-ui/src/index.ts
index 5d32df8bfa..1111e3426b 100644
--- a/packages/docs-ui/src/index.ts
+++ b/packages/docs-ui/src/index.ts
@@ -206,6 +206,7 @@ export {
ParagraphMenuInsertBelowSubmenuItemFactory,
} from './menu/paragraph-menu';
export { menuSchema as DocsUIMenuSchema } from './menu/schema';
+export { UniverDocsMobileUIPlugin } from './mobile-plugin';
export { UniverDocsUIPlugin } from './plugin';
export * from './services';
export {
@@ -250,8 +251,10 @@ export { DocIMEInputManagerService } from './services/doc-ime-input-manager.serv
export { DocLayoutInteractionService } from './services/doc-layout-interaction.service';
export { SetDocInputStyleCommand } from './services/doc-menu-style.service';
export type { ISetDocInputStyleCommandParams } from './services/doc-menu-style.service';
+export { DocMobileElementMenuService } from './services/doc-mobile-element-menu.service';
export { DocPageLayoutService } from './services/doc-page-layout.service';
export { DocParagraphMenuService } from './services/doc-paragraph-menu.service';
+export type { IDocCanvasPopup } from './services/doc-popup-manager.service';
export { calcDocRangePositions, DocCanvasPopManagerService } from './services/doc-popup-manager.service';
export type { IDocPrintPreparationContext } from './services/doc-print-interceptor.service';
export { DocPrintInterceptorService } from './services/doc-print-interceptor.service';
@@ -276,6 +279,8 @@ export { getAnchorBounding, getLineBounding, TEXT_RANGE_LAYER_INDEX, TextRange }
export { whenDocAndEditorFocused } from './shortcuts/utils';
export { DOC_VERTICAL_PADDING } from './types/const/padding';
export { BulletListTypePicker, OrderListTypePicker } from './views/list-type-picker/Picker';
+export { MOBILE_DOC_ELEMENT_MENU, MobileDocElementMenu } from './views/mobile-element-menu/MobileDocElementMenu';
+export { MobileRichTextEditor } from './views/mobile-rich-text-editor/MobileRichTextEditor';
export { MobileRichTextToolbar } from './views/mobile-rich-text-toolbar/MobileRichTextToolbar';
export type { IMobileRichTextToolbarProps } from './views/mobile-rich-text-toolbar/MobileRichTextToolbar';
export {
diff --git a/packages/docs-ui/src/locale/ar-SA.ts b/packages/docs-ui/src/locale/ar-SA.ts
index a54c7c3573..065ed66dbf 100644
--- a/packages/docs-ui/src/locale/ar-SA.ts
+++ b/packages/docs-ui/src/locale/ar-SA.ts
@@ -24,6 +24,20 @@ const locale: typeof enUS = {
paragraph: 'الفقرة',
section: 'القسم',
},
+ mobile: {
+ insert: 'إدراج',
+ edit: 'تحرير',
+ done: 'تم',
+ more: 'المزيد',
+ back: 'رجوع',
+ close: 'إغلاق',
+ format: 'تنسيق',
+ layout: 'تخطيط',
+ keyboard: 'إظهار لوحة المفاتيح',
+ hideKeyboard: 'إخفاء لوحة المفاتيح',
+ expand: 'توسيع الأدوات',
+ collapse: 'طي الأدوات',
+ },
layout: {
progress: 'جارٍ تنسيق المستند…',
recovering: 'جارٍ استعادة تخطيط المستند…',
@@ -180,6 +194,8 @@ const locale: typeof enUS = {
copy: 'نسخ',
cut: 'قص',
paste: 'لصق',
+ select: 'تحديد',
+ selectAll: 'تحديد الكل',
delete: 'حذف',
bulletList: 'قائمة نقطية',
orderList: 'قائمة مرقمة',
diff --git a/packages/docs-ui/src/locale/ca-ES.ts b/packages/docs-ui/src/locale/ca-ES.ts
index 0fc26ee8df..da6a857a5c 100644
--- a/packages/docs-ui/src/locale/ca-ES.ts
+++ b/packages/docs-ui/src/locale/ca-ES.ts
@@ -24,6 +24,20 @@ const locale: typeof enUS = {
paragraph: 'Paràgraf',
section: 'Secció',
},
+ mobile: {
+ insert: 'Insereix',
+ edit: 'Edita',
+ done: 'Fet',
+ more: 'Més',
+ back: 'Enrere',
+ close: 'Tanca',
+ format: 'Format',
+ layout: 'Disseny',
+ keyboard: 'Mostra el teclat',
+ hideKeyboard: 'Amaga el teclat',
+ expand: 'Amplia les eines',
+ collapse: 'Redueix les eines',
+ },
layout: {
progress: 'S’està maquetant el document…',
recovering: 'S’està restaurant el disseny del document…',
@@ -180,6 +194,8 @@ const locale: typeof enUS = {
copy: 'Copia',
cut: 'Retalla',
paste: 'Enganxa',
+ select: 'Selecciona',
+ selectAll: 'Selecciona-ho tot',
delete: 'Elimina',
bulletList: 'Llista de pics',
orderList: 'Llista ordenada',
diff --git a/packages/docs-ui/src/locale/de-DE.ts b/packages/docs-ui/src/locale/de-DE.ts
index a1192e7166..eca35b577d 100644
--- a/packages/docs-ui/src/locale/de-DE.ts
+++ b/packages/docs-ui/src/locale/de-DE.ts
@@ -24,6 +24,20 @@ const locale: typeof enUS = {
paragraph: 'Absatz',
section: 'Abschnitt',
},
+ mobile: {
+ insert: 'Einfügen',
+ edit: 'Bearbeiten',
+ done: 'Fertig',
+ more: 'Mehr',
+ back: 'Zurück',
+ close: 'Schließen',
+ format: 'Format',
+ layout: 'Layout',
+ keyboard: 'Tastatur anzeigen',
+ hideKeyboard: 'Tastatur ausblenden',
+ expand: 'Werkzeuge erweitern',
+ collapse: 'Werkzeuge einklappen',
+ },
layout: {
progress: 'Dokument wird formatiert…',
recovering: 'Dokumentlayout wird wiederhergestellt…',
@@ -180,6 +194,8 @@ const locale: typeof enUS = {
copy: 'Kopieren',
cut: 'Ausschneiden',
paste: 'Einfügen',
+ select: 'Auswählen',
+ selectAll: 'Alles auswählen',
delete: 'Löschen',
bulletList: 'Aufzählungsliste',
orderList: 'Nummerierte Liste',
diff --git a/packages/docs-ui/src/locale/en-US.ts b/packages/docs-ui/src/locale/en-US.ts
index 36e0711c4e..4fa81bc1d5 100644
--- a/packages/docs-ui/src/locale/en-US.ts
+++ b/packages/docs-ui/src/locale/en-US.ts
@@ -22,6 +22,20 @@ const locale = {
paragraph: 'Paragraph',
section: 'Section',
},
+ mobile: {
+ insert: 'Insert',
+ edit: 'Edit',
+ done: 'Done',
+ more: 'More',
+ back: 'Back',
+ close: 'Close',
+ format: 'Format',
+ layout: 'Layout',
+ keyboard: 'Show keyboard',
+ hideKeyboard: 'Hide keyboard',
+ expand: 'Expand tools',
+ collapse: 'Collapse tools',
+ },
layout: {
progress: 'Laying out document…',
recovering: 'Restoring document layout…',
@@ -178,6 +192,8 @@ const locale = {
copy: 'Copy',
cut: 'Cut',
paste: 'Paste',
+ select: 'Select',
+ selectAll: 'Select all',
delete: 'Delete',
bulletList: 'Bullet list',
orderList: 'Ordered list',
diff --git a/packages/docs-ui/src/locale/es-ES.ts b/packages/docs-ui/src/locale/es-ES.ts
index 8905e5d3b3..41ec82e9e9 100644
--- a/packages/docs-ui/src/locale/es-ES.ts
+++ b/packages/docs-ui/src/locale/es-ES.ts
@@ -24,6 +24,20 @@ const locale: typeof enUS = {
paragraph: 'Párrafo',
section: 'Sección',
},
+ mobile: {
+ insert: 'Insertar',
+ edit: 'Editar',
+ done: 'Listo',
+ more: 'Más',
+ back: 'Atrás',
+ close: 'Cerrar',
+ format: 'Formato',
+ layout: 'Diseño',
+ keyboard: 'Mostrar teclado',
+ hideKeyboard: 'Ocultar teclado',
+ expand: 'Expandir herramientas',
+ collapse: 'Contraer herramientas',
+ },
layout: {
progress: 'Maquetando el documento…',
recovering: 'Restaurando el diseño del documento…',
@@ -180,6 +194,8 @@ const locale: typeof enUS = {
copy: 'Copiar',
cut: 'Cortar',
paste: 'Pegar',
+ select: 'Seleccionar',
+ selectAll: 'Seleccionar todo',
delete: 'Eliminar',
bulletList: 'Lista de viñetas',
orderList: 'Lista ordenada',
diff --git a/packages/docs-ui/src/locale/fa-IR.ts b/packages/docs-ui/src/locale/fa-IR.ts
index 1871b450e1..c6b0f43a24 100644
--- a/packages/docs-ui/src/locale/fa-IR.ts
+++ b/packages/docs-ui/src/locale/fa-IR.ts
@@ -24,6 +24,20 @@ const locale: typeof enUS = {
paragraph: 'بند',
section: 'بخش',
},
+ mobile: {
+ insert: 'درج',
+ edit: 'ویرایش',
+ done: 'انجام شد',
+ more: 'بیشتر',
+ back: 'بازگشت',
+ close: 'بستن',
+ format: 'قالب‌بندی',
+ layout: 'چیدمان',
+ keyboard: 'نمایش صفحه‌کلید',
+ hideKeyboard: 'پنهان کردن صفحه‌کلید',
+ expand: 'باز کردن ابزارها',
+ collapse: 'جمع کردن ابزارها',
+ },
layout: {
progress: 'در حال صفحه‌آرایی سند…',
recovering: 'در حال بازیابی صفحه‌آرایی سند…',
@@ -180,6 +194,8 @@ const locale: typeof enUS = {
copy: 'کپی',
cut: 'برش',
paste: 'چسباندن',
+ select: 'انتخاب',
+ selectAll: 'انتخاب همه',
delete: 'حذف',
bulletList: 'لیست بدون شماره',
orderList: 'لیست شماره‌دار',
diff --git a/packages/docs-ui/src/locale/fr-FR.ts b/packages/docs-ui/src/locale/fr-FR.ts
index 03acaa9b2c..edad18544f 100644
--- a/packages/docs-ui/src/locale/fr-FR.ts
+++ b/packages/docs-ui/src/locale/fr-FR.ts
@@ -24,6 +24,20 @@ const locale: typeof enUS = {
paragraph: 'Paragraphe',
section: 'Section',
},
+ mobile: {
+ insert: 'Insérer',
+ edit: 'Modifier',
+ done: 'Terminé',
+ more: 'Plus',
+ back: 'Retour',
+ close: 'Fermer',
+ format: 'Format',
+ layout: 'Mise en page',
+ keyboard: 'Afficher le clavier',
+ hideKeyboard: 'Masquer le clavier',
+ expand: 'Développer les outils',
+ collapse: 'Réduire les outils',
+ },
layout: {
progress: 'Mise en page du document…',
recovering: 'Restauration de la mise en page du document…',
@@ -180,6 +194,8 @@ const locale: typeof enUS = {
copy: 'Copier',
cut: 'Couper',
paste: 'Coller',
+ select: 'Sélectionner',
+ selectAll: 'Tout sélectionner',
delete: 'Supprimer',
bulletList: 'Liste non ordonnée',
orderList: 'Liste ordonnée',
diff --git a/packages/docs-ui/src/locale/id-ID.ts b/packages/docs-ui/src/locale/id-ID.ts
index a6728e8e16..b6a551eda7 100644
--- a/packages/docs-ui/src/locale/id-ID.ts
+++ b/packages/docs-ui/src/locale/id-ID.ts
@@ -24,6 +24,20 @@ const locale: typeof enUS = {
paragraph: 'Paragraf',
section: 'Bagian',
},
+ mobile: {
+ insert: 'Sisipkan',
+ edit: 'Edit',
+ done: 'Selesai',
+ more: 'Lainnya',
+ back: 'Kembali',
+ close: 'Tutup',
+ format: 'Format',
+ layout: 'Tata letak',
+ keyboard: 'Tampilkan papan ketik',
+ hideKeyboard: 'Sembunyikan papan ketik',
+ expand: 'Perluas alat',
+ collapse: 'Ciutkan alat',
+ },
layout: {
progress: 'Menata dokumen…',
recovering: 'Memulihkan tata letak dokumen…',
@@ -180,6 +194,8 @@ const locale: typeof enUS = {
copy: 'Salin',
cut: 'Potong',
paste: 'Tempel',
+ select: 'Pilih',
+ selectAll: 'Pilih semua',
delete: 'Hapus',
bulletList: 'Daftar poin',
orderList: 'Daftar berurut',
diff --git a/packages/docs-ui/src/locale/it-IT.ts b/packages/docs-ui/src/locale/it-IT.ts
index f309a45bf8..8d6a5f5bbc 100644
--- a/packages/docs-ui/src/locale/it-IT.ts
+++ b/packages/docs-ui/src/locale/it-IT.ts
@@ -24,6 +24,20 @@ const locale: typeof enUS = {
paragraph: 'Paragrafo',
section: 'Sezione',
},
+ mobile: {
+ insert: 'Inserisci',
+ edit: 'Modifica',
+ done: 'Fine',
+ more: 'Altro',
+ back: 'Indietro',
+ close: 'Chiudi',
+ format: 'Formato',
+ layout: 'Impaginazione',
+ keyboard: 'Mostra tastiera',
+ hideKeyboard: 'Nascondi tastiera',
+ expand: 'Espandi strumenti',
+ collapse: 'Comprimi strumenti',
+ },
layout: {
progress: 'Impaginazione del documento…',
recovering: 'Ripristino del layout del documento…',
@@ -180,6 +194,8 @@ const locale: typeof enUS = {
copy: 'Copia',
cut: 'Taglia',
paste: 'Incolla',
+ select: 'Seleziona',
+ selectAll: 'Seleziona tutto',
delete: 'Elimina',
bulletList: 'Elenco puntato',
orderList: 'Elenco ordinato',
diff --git a/packages/docs-ui/src/locale/ja-JP.ts b/packages/docs-ui/src/locale/ja-JP.ts
index 83f1ef7b2a..4b8d70913e 100644
--- a/packages/docs-ui/src/locale/ja-JP.ts
+++ b/packages/docs-ui/src/locale/ja-JP.ts
@@ -24,6 +24,20 @@ const locale: typeof enUS = {
paragraph: '段落',
section: 'セクション',
},
+ mobile: {
+ insert: '挿入',
+ edit: '編集',
+ done: '完了',
+ more: 'その他',
+ back: '戻る',
+ close: '閉じる',
+ format: '書式',
+ layout: 'レイアウト',
+ keyboard: 'キーボードを表示',
+ hideKeyboard: 'キーボードを隠す',
+ expand: 'ツールを展開',
+ collapse: 'ツールを折りたたむ',
+ },
layout: {
progress: 'ドキュメントをレイアウトしています…',
recovering: 'ドキュメントのレイアウトを復元しています…',
@@ -180,6 +194,8 @@ const locale: typeof enUS = {
copy: 'コピー',
cut: '切り取り',
paste: '貼り付け',
+ select: '選択',
+ selectAll: 'すべて選択',
delete: '削除',
bulletList: '箇条書き',
orderList: '番号付きリスト',
diff --git a/packages/docs-ui/src/locale/ko-KR.ts b/packages/docs-ui/src/locale/ko-KR.ts
index eb6d64b449..9d42e273d0 100644
--- a/packages/docs-ui/src/locale/ko-KR.ts
+++ b/packages/docs-ui/src/locale/ko-KR.ts
@@ -24,6 +24,20 @@ const locale: typeof enUS = {
paragraph: '단락',
section: '섹션',
},
+ mobile: {
+ insert: '삽입',
+ edit: '편집',
+ done: '완료',
+ more: '더보기',
+ back: '뒤로',
+ close: '닫기',
+ format: '서식',
+ layout: '레이아웃',
+ keyboard: '키보드 표시',
+ hideKeyboard: '키보드 숨기기',
+ expand: '도구 펼치기',
+ collapse: '도구 접기',
+ },
layout: {
progress: '문서 레이아웃을 처리하는 중…',
recovering: '문서 레이아웃을 복구하는 중…',
@@ -180,6 +194,8 @@ const locale: typeof enUS = {
copy: '복사',
cut: '잘라내기',
paste: '붙여넣기',
+ select: '선택',
+ selectAll: '모두 선택',
delete: '삭제',
bulletList: '글머리 기호 목록',
orderList: '번호 매기기 목록',
diff --git a/packages/docs-ui/src/locale/pl-PL.ts b/packages/docs-ui/src/locale/pl-PL.ts
index b80f257e05..081feb64b8 100644
--- a/packages/docs-ui/src/locale/pl-PL.ts
+++ b/packages/docs-ui/src/locale/pl-PL.ts
@@ -24,6 +24,20 @@ const locale: typeof enUS = {
paragraph: 'Akapit',
section: 'Sekcja',
},
+ mobile: {
+ insert: 'Wstaw',
+ edit: 'Edytuj',
+ done: 'Gotowe',
+ more: 'Więcej',
+ back: 'Wstecz',
+ close: 'Zamknij',
+ format: 'Format',
+ layout: 'Układ',
+ keyboard: 'Pokaż klawiaturę',
+ hideKeyboard: 'Ukryj klawiaturę',
+ expand: 'Rozwiń narzędzia',
+ collapse: 'Zwiń narzędzia',
+ },
layout: {
progress: 'Układanie dokumentu…',
recovering: 'Przywracanie układu dokumentu…',
@@ -180,6 +194,8 @@ const locale: typeof enUS = {
copy: 'Kopiuj',
cut: 'Wytnij',
paste: 'Wklej',
+ select: 'Zaznacz',
+ selectAll: 'Zaznacz wszystko',
delete: 'Usuń',
bulletList: 'Lista punktowana',
orderList: 'Lista numerowana',
diff --git a/packages/docs-ui/src/locale/pt-BR.ts b/packages/docs-ui/src/locale/pt-BR.ts
index 29ddfc7a9b..a54c8e53de 100644
--- a/packages/docs-ui/src/locale/pt-BR.ts
+++ b/packages/docs-ui/src/locale/pt-BR.ts
@@ -24,6 +24,20 @@ const locale: typeof enUS = {
paragraph: 'Parágrafo',
section: 'Seção',
},
+ mobile: {
+ insert: 'Inserir',
+ edit: 'Editar',
+ done: 'Concluído',
+ more: 'Mais',
+ back: 'Voltar',
+ close: 'Fechar',
+ format: 'Formatar',
+ layout: 'Layout',
+ keyboard: 'Mostrar teclado',
+ hideKeyboard: 'Ocultar teclado',
+ expand: 'Expandir ferramentas',
+ collapse: 'Recolher ferramentas',
+ },
layout: {
progress: 'Formatando o documento…',
recovering: 'Restaurando o layout do documento…',
@@ -180,6 +194,8 @@ const locale: typeof enUS = {
copy: 'Copiar',
cut: 'Recortar',
paste: 'Colar',
+ select: 'Selecionar',
+ selectAll: 'Selecionar tudo',
delete: 'Excluir',
bulletList: 'Lista com marcadores',
orderList: 'Lista ordenada',
diff --git a/packages/docs-ui/src/locale/ru-RU.ts b/packages/docs-ui/src/locale/ru-RU.ts
index 2ed8208c77..94c6337331 100644
--- a/packages/docs-ui/src/locale/ru-RU.ts
+++ b/packages/docs-ui/src/locale/ru-RU.ts
@@ -24,6 +24,20 @@ const locale: typeof enUS = {
paragraph: 'Абзац',
section: 'Раздел',
},
+ mobile: {
+ insert: 'Вставка',
+ edit: 'Редактировать',
+ done: 'Готово',
+ more: 'Ещё',
+ back: 'Назад',
+ close: 'Закрыть',
+ format: 'Формат',
+ layout: 'Макет',
+ keyboard: 'Показать клавиатуру',
+ hideKeyboard: 'Скрыть клавиатуру',
+ expand: 'Развернуть инструменты',
+ collapse: 'Свернуть инструменты',
+ },
layout: {
progress: 'Выполняется разметка документа…',
recovering: 'Восстановление макета документа…',
@@ -180,6 +194,8 @@ const locale: typeof enUS = {
copy: 'Копировать',
cut: 'Вырезать',
paste: 'Вставить',
+ select: 'Выбрать',
+ selectAll: 'Выбрать всё',
delete: 'Удалить',
bulletList: 'Неупорядоченный список',
orderList: 'Упорядоченный список',
diff --git a/packages/docs-ui/src/locale/sk-SK.ts b/packages/docs-ui/src/locale/sk-SK.ts
index 83f07f83ef..0a7b0d12af 100644
--- a/packages/docs-ui/src/locale/sk-SK.ts
+++ b/packages/docs-ui/src/locale/sk-SK.ts
@@ -24,6 +24,20 @@ const locale: typeof enUS = {
paragraph: 'Odsek',
section: 'Sekcia',
},
+ mobile: {
+ insert: 'Vložiť',
+ edit: 'Upraviť',
+ done: 'Hotovo',
+ more: 'Viac',
+ back: 'Späť',
+ close: 'Zavrieť',
+ format: 'Formát',
+ layout: 'Rozloženie',
+ keyboard: 'Zobraziť klávesnicu',
+ hideKeyboard: 'Skryť klávesnicu',
+ expand: 'Rozbaliť nástroje',
+ collapse: 'Zbaliť nástroje',
+ },
layout: {
progress: 'Rozkladá sa dokument…',
recovering: 'Obnovuje sa rozloženie dokumentu…',
@@ -180,6 +194,8 @@ const locale: typeof enUS = {
copy: 'Kopírovať',
cut: 'Vystrihnúť',
paste: 'Prilepiť',
+ select: 'Vybrať',
+ selectAll: 'Vybrať všetko',
delete: 'Odstrániť',
bulletList: 'Odrážkový zoznam',
orderList: 'Číslovaný zoznam',
diff --git a/packages/docs-ui/src/locale/vi-VN.ts b/packages/docs-ui/src/locale/vi-VN.ts
index 5447d01e6f..76a6c293a5 100644
--- a/packages/docs-ui/src/locale/vi-VN.ts
+++ b/packages/docs-ui/src/locale/vi-VN.ts
@@ -24,6 +24,20 @@ const locale: typeof enUS = {
paragraph: 'Đoạn văn',
section: 'Phần',
},
+ mobile: {
+ insert: 'Chèn',
+ edit: 'Chỉnh sửa',
+ done: 'Xong',
+ more: 'Thêm',
+ back: 'Quay lại',
+ close: 'Đóng',
+ format: 'Định dạng',
+ layout: 'Bố cục',
+ keyboard: 'Hiện bàn phím',
+ hideKeyboard: 'Ẩn bàn phím',
+ expand: 'Mở rộng công cụ',
+ collapse: 'Thu gọn công cụ',
+ },
layout: {
progress: 'Đang dàn trang tài liệu…',
recovering: 'Đang khôi phục bố cục tài liệu…',
@@ -180,6 +194,8 @@ const locale: typeof enUS = {
copy: 'Sao chép',
cut: 'Cắt',
paste: 'Dán',
+ select: 'Chọn',
+ selectAll: 'Chọn tất cả',
delete: 'Xóa',
bulletList: 'Danh sách không thứ tự',
orderList: 'Danh sách có thứ tự',
diff --git a/packages/docs-ui/src/locale/zh-CN.ts b/packages/docs-ui/src/locale/zh-CN.ts
index 936e1b87a7..108a857969 100644
--- a/packages/docs-ui/src/locale/zh-CN.ts
+++ b/packages/docs-ui/src/locale/zh-CN.ts
@@ -24,6 +24,20 @@ const locale: typeof enUS = {
paragraph: '段落',
section: '节',
},
+ mobile: {
+ insert: '插入',
+ edit: '编辑',
+ done: '完成',
+ more: '更多',
+ back: '返回',
+ close: '关闭',
+ format: '格式',
+ layout: '布局',
+ keyboard: '显示键盘',
+ hideKeyboard: '收起键盘',
+ expand: '展开工具',
+ collapse: '收起工具',
+ },
layout: {
progress: '正在排版文档…',
recovering: '正在恢复文档排版…',
@@ -180,6 +194,8 @@ const locale: typeof enUS = {
copy: '复制',
cut: '剪切',
paste: '粘贴',
+ select: '选择',
+ selectAll: '全选',
delete: '删除',
bulletList: '无序列表',
orderList: '有序列表',
diff --git a/packages/docs-ui/src/locale/zh-HK.ts b/packages/docs-ui/src/locale/zh-HK.ts
index 75c4fa4c0a..ca495a6c9d 100644
--- a/packages/docs-ui/src/locale/zh-HK.ts
+++ b/packages/docs-ui/src/locale/zh-HK.ts
@@ -24,6 +24,20 @@ const locale: typeof enUS = {
paragraph: '段落',
section: '節',
},
+ mobile: {
+ insert: '插入',
+ edit: '編輯',
+ done: '完成',
+ more: '更多',
+ back: '返回',
+ close: '關閉',
+ format: '格式',
+ layout: '版面',
+ keyboard: '顯示鍵盤',
+ hideKeyboard: '收起鍵盤',
+ expand: '展開工具',
+ collapse: '收起工具',
+ },
layout: {
progress: '正在排版文件…',
recovering: '正在恢復文件排版…',
@@ -180,6 +194,8 @@ const locale: typeof enUS = {
copy: '複製',
cut: '剪切',
paste: '貼上',
+ select: '選取',
+ selectAll: '全選',
delete: '刪除',
bulletList: '無序列表',
orderList: '有序列表',
diff --git a/packages/docs-ui/src/locale/zh-TW.ts b/packages/docs-ui/src/locale/zh-TW.ts
index 75c9a5edb2..68040ba123 100644
--- a/packages/docs-ui/src/locale/zh-TW.ts
+++ b/packages/docs-ui/src/locale/zh-TW.ts
@@ -24,6 +24,20 @@ const locale: typeof enUS = {
paragraph: '段落',
section: '節',
},
+ mobile: {
+ insert: '插入',
+ edit: '編輯',
+ done: '完成',
+ more: '更多',
+ back: '返回',
+ close: '關閉',
+ format: '格式',
+ layout: '版面',
+ keyboard: '顯示鍵盤',
+ hideKeyboard: '收合鍵盤',
+ expand: '展開工具',
+ collapse: '收合工具',
+ },
layout: {
progress: '正在排版文件…',
recovering: '正在復原文件排版…',
@@ -180,6 +194,8 @@ const locale: typeof enUS = {
copy: '複製',
cut: '剪切',
paste: '貼上',
+ select: '選取',
+ selectAll: '全選',
delete: '刪除',
bulletList: '無序列表',
orderList: '有序列表',
diff --git a/packages/docs-ui/src/menu/__tests__/context-menu.spec.ts b/packages/docs-ui/src/menu/__tests__/context-menu.spec.ts
index 4f293ff79b..fb7f8c19f2 100644
--- a/packages/docs-ui/src/menu/__tests__/context-menu.spec.ts
+++ b/packages/docs-ui/src/menu/__tests__/context-menu.spec.ts
@@ -17,11 +17,29 @@
import { Injector, IPermissionService, IUniverInstanceService, PermissionService, UniverInstanceType } from '@univerjs/core';
import { DocSelectionManagerService, setDocumentPermissionValue } from '@univerjs/docs';
import { UnitAction } from '@univerjs/protocol';
+import { ContextMenuGroup } from '@univerjs/ui';
import { firstValueFrom, of } from 'rxjs';
import { describe, expect, it } from 'vitest';
-import { CopyMenuFactory, ParagraphSettingMenuFactory, PasteMenuFactory, SectionSettingMenuFactory } from '../context-menu';
+import { DocPasteCommand } from '../../commands/commands/clipboard.command';
+import { DocSelectAllCommand, DocSelectWordCommand } from '../../commands/commands/doc-select-all.command';
+import { DOC_CARET_MENU_ID } from '../../consts/mobile-context';
+import { CopyMenuFactory, ParagraphSettingMenuFactory, PasteMenuFactory, SectionSettingMenuFactory, SelectAllMenuFactory, SelectWordMenuFactory } from '../context-menu';
+import { mobileMenuSchema } from '../mobile-schema';
describe('settings context menu factories', () => {
+ it('registers a dedicated three-action mobile caret menu', () => {
+ const caretMenu = Object.entries(mobileMenuSchema).find(([position]) => position === DOC_CARET_MENU_ID)?.[1];
+
+ expect(caretMenu).toEqual({
+ [ContextMenuGroup.QUICK]: {
+ quickLayout: 'tile',
+ [DocPasteCommand.id]: { order: 0, menuItemFactory: PasteMenuFactory },
+ [DocSelectWordCommand.id]: { order: 1, menuItemFactory: SelectWordMenuFactory },
+ [DocSelectAllCommand.id]: { order: 2, menuItemFactory: SelectAllMenuFactory },
+ },
+ });
+ });
+
it('does not show leading icons', () => {
const accessor = new Injector([
[DocSelectionManagerService, {
diff --git a/packages/docs-ui/src/menu/context-menu.ts b/packages/docs-ui/src/menu/context-menu.ts
index feea568a59..90cc0f9e0c 100644
--- a/packages/docs-ui/src/menu/context-menu.ts
+++ b/packages/docs-ui/src/menu/context-menu.ts
@@ -26,6 +26,7 @@ import { getMenuHiddenObservable, MenuItemType } from '@univerjs/ui';
import { combineLatest, map, Observable } from 'rxjs';
import { DocCopyCommand, DocCutCommand, DocPasteCommand } from '../commands/commands/clipboard.command';
import { DeleteLeftCommand } from '../commands/commands/doc-delete.command';
+import { DocSelectAllCommand, DocSelectWordCommand } from '../commands/commands/doc-select-all.command';
import {
DocTableDeleteColumnsCommand,
DocTableDeleteRowsCommand,
@@ -58,6 +59,20 @@ const getDisableOnCollapsedObservable = (accessor: IAccessor) => {
});
};
+const getDisableOnExpandedObservable = (accessor: IAccessor) => {
+ const docSelectionManagerService = accessor.get(DocSelectionManagerService);
+ return new Observable<boolean>((subscriber) => {
+ const emit = () => {
+ const ranges = docSelectionManagerService.getDocRanges();
+ const range = ranges[0];
+ subscriber.next(ranges.length !== 1 || !(range.collapsed === true || range.startOffset === range.endOffset));
+ };
+ emit();
+ const observable = docSelectionManagerService.textSelection$.subscribe(emit);
+ return () => observable.unsubscribe();
+ });
+};
+
function combineMenuDisabled(...states: Observable<boolean>[]): Observable<boolean> {
return combineLatest(states).pipe(map((values) => values.some(Boolean)));
}
@@ -170,6 +185,25 @@ export function PasteMenuFactory(accessor: IAccessor): IMenuButtonItem<LocaleKey
};
};
+export function SelectWordMenuFactory(accessor: IAccessor): IMenuButtonItem<LocaleKey> {
+ return {
+ id: DocSelectWordCommand.id,
+ type: MenuItemType.BUTTON,
+ title: 'docs-ui.rightClick.select',
+ disabled$: getDisableOnExpandedObservable(accessor),
+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
+ };
+}
+
+export function SelectAllMenuFactory(accessor: IAccessor): IMenuButtonItem<LocaleKey> {
+ return {
+ id: DocSelectAllCommand.id,
+ type: MenuItemType.BUTTON,
+ title: 'docs-ui.rightClick.selectAll',
+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
+ };
+}
+
export function DeleteMenuFactory(accessor: IAccessor): IMenuButtonItem<LocaleKey> {
return {
id: DeleteLeftCommand.id,
diff --git a/packages/docs-ui/src/menu/mobile-schema.ts b/packages/docs-ui/src/menu/mobile-schema.ts
new file mode 100644
index 0000000000..1e4c8b84e0
--- /dev/null
+++ b/packages/docs-ui/src/menu/mobile-schema.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 { MenuSchemaType } from '@univerjs/ui';
+import { ContextMenuGroup, ContextMenuPosition } from '@univerjs/ui';
+import { DocPasteCommand } from '../commands/commands/clipboard.command';
+import { DocSelectAllCommand, DocSelectWordCommand } from '../commands/commands/doc-select-all.command';
+import { DOC_CARET_MENU_ID } from '../consts/mobile-context';
+import { PasteMenuFactory, SelectAllMenuFactory, SelectWordMenuFactory } from './context-menu';
+
+export const mobileMenuSchema: MenuSchemaType = {
+ [ContextMenuPosition.MAIN_AREA]: {
+ [ContextMenuGroup.QUICK]: {
+ [DocSelectWordCommand.id]: { order: 3, menuItemFactory: SelectWordMenuFactory },
+ [DocSelectAllCommand.id]: { order: 4, menuItemFactory: SelectAllMenuFactory },
+ },
+ },
+ [DOC_CARET_MENU_ID]: {
+ [ContextMenuGroup.QUICK]: {
+ quickLayout: 'tile',
+ [DocPasteCommand.id]: {
+ order: 0,
+ menuItemFactory: PasteMenuFactory,
+ },
+ [DocSelectWordCommand.id]: {
+ order: 1,
+ menuItemFactory: SelectWordMenuFactory,
+ },
+ [DocSelectAllCommand.id]: {
+ order: 2,
+ menuItemFactory: SelectAllMenuFactory,
+ },
+ },
+ },
+
+};
diff --git a/packages/docs-ui/src/mobile-plugin.ts b/packages/docs-ui/src/mobile-plugin.ts
new file mode 100644
index 0000000000..d7e9e65237
--- /dev/null
+++ b/packages/docs-ui/src/mobile-plugin.ts
@@ -0,0 +1,456 @@
+/**
+ * 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, DocumentDataModel } from '@univerjs/core';
+import type { IUniverDocsUIConfig } from './config/config';
+import {
+ DependentOn,
+ ICommandService,
+ IConfigService,
+ Inject,
+ Injector,
+ IUniverInstanceService,
+ merge,
+ mergeOverrideWithDependencies,
+ Plugin,
+ touchDependencies,
+ UniverInstanceType,
+} from '@univerjs/core';
+import {
+ DocInterceptorService,
+ DocSkeletonManagerService,
+ IDocStateChangeInterceptorService,
+ UniverDocsPlugin,
+} from '@univerjs/docs';
+import { IRenderManagerService, UniverRenderEnginePlugin } from '@univerjs/engine-render';
+import { UniverMobileUIPlugin } from '@univerjs/ui';
+import pkg from '../package.json';
+import { AfterSpaceCommand, EnterCommand, TabCommand } from './commands/commands/auto-format.command';
+import { BreakLineCommand } from './commands/commands/break-line.command';
+import {
+ DocCopyCommand,
+ DocCopyCurrentParagraphCommand,
+ DocCutCommand,
+ DocCutCurrentParagraphCommand,
+ DocPasteCommand,
+} from './commands/commands/clipboard.command';
+import { CutContentCommand, InnerPasteCommand } from './commands/commands/clipboard.inner.command';
+import { MoveDocBlockCommand } from './commands/commands/doc-block-move.command';
+import {
+ DeleteCurrentParagraphCommand,
+ DeleteCustomBlockCommand,
+ DeleteLeftCommand,
+ DeleteRightCommand,
+ MergeTwoParagraphCommand,
+ RemoveHorizontalLineCommand,
+} from './commands/commands/doc-delete.command';
+import { CloseHeaderFooterCommand } from './commands/commands/doc-header-footer.command';
+import {
+ HorizontalLineCommand,
+ InsertHorizontalLineBellowCommand,
+} from './commands/commands/doc-horizontal-line.command';
+import { DocPageSetupCommand } from './commands/commands/doc-page-setup.command';
+import { DocParagraphSettingCommand } from './commands/commands/doc-paragraph-setting.command';
+import { DocSelectAllCommand, DocSelectWordCommand } from './commands/commands/doc-select-all.command';
+import { IMEInputCommand } from './commands/commands/ime-input.command';
+import {
+ ResetInlineFormatTextBackgroundColorCommand,
+ ResetInlineFormatTextColorCommand,
+ SetInlineFormatBoldCommand,
+ SetInlineFormatCommand,
+ SetInlineFormatFontFamilyCommand,
+ SetInlineFormatFontSizeCommand,
+ SetInlineFormatItalicCommand,
+ SetInlineFormatStrikethroughCommand,
+ SetInlineFormatSubscriptCommand,
+ SetInlineFormatSuperscriptCommand,
+ SetInlineFormatTextBackgroundColorCommand,
+ SetInlineFormatTextColorCommand,
+ SetInlineFormatTextFillCommand,
+ SetInlineFormatUnderlineCommand,
+} from './commands/commands/inline-format.command';
+import { InsertCustomRangeCommand } from './commands/commands/insert-custom-range.command';
+import { InsertSpecialCharacterCommand } from './commands/commands/insert-special-character.command';
+import {
+ BulletListCommand,
+ ChangeListNestingLevelCommand,
+ ChangeListTypeCommand,
+ CheckListCommand,
+ InsertBulletListBellowCommand,
+ InsertCheckListBellowCommand,
+ InsertOrderListBellowCommand,
+ ListOperationCommand,
+ OrderListCommand,
+ QuickListCommand,
+ ToggleCheckListCommand,
+} from './commands/commands/list.command';
+import {
+ AlignCenterCommand,
+ AlignJustifyCommand,
+ AlignLeftCommand,
+ AlignOperationCommand,
+ AlignRightCommand,
+} from './commands/commands/paragraph-align.command';
+import {
+ CoverContentCommand,
+ ReplaceSelectionCommand,
+ ReplaceSnapshotCommand,
+ ReplaceTextRunsCommand,
+} from './commands/commands/replace-content.command';
+import { SetDocZoomRatioCommand } from './commands/commands/set-doc-zoom-ratio.command';
+import {
+ H1HeadingCommand,
+ H2HeadingCommand,
+ H3HeadingCommand,
+ H4HeadingCommand,
+ H5HeadingCommand,
+ NormalTextHeadingCommand,
+ QuickHeadingCommand,
+ SetParagraphNamedStyleCommand,
+ SubtitleHeadingCommand,
+ TitleHeadingCommand,
+} from './commands/commands/set-heading.command';
+import { SwitchDocModeCommand } from './commands/commands/switch-doc-mode.command';
+import { CreateDocTableCommand } from './commands/commands/table/doc-table-create.command';
+import {
+ DocTableDeleteColumnsCommand,
+ DocTableDeleteRowsCommand,
+ DocTableDeleteTableCommand,
+} from './commands/commands/table/doc-table-delete.command';
+import {
+ DocTableInsertColumnCommand,
+ DocTableInsertColumnLeftCommand,
+ DocTableInsertColumnRightCommand,
+ DocTableInsertRowAboveCommand,
+ DocTableInsertRowBellowCommand,
+ DocTableInsertRowCommand,
+} from './commands/commands/table/doc-table-insert.command';
+import { DocTableTabCommand } from './commands/commands/table/doc-table-tab.command';
+import { MoveCursorOperation, MoveSelectionOperation } from './commands/operations/doc-cursor.operation';
+import { DocParagraphSettingPanelOperation } from './commands/operations/doc-paragraph-setting-panel.operation';
+import { DocSectionSettingPanelOperation } from './commands/operations/doc-section-setting-panel.operation';
+import { InsertDocumentColumnBreakOperation, InsertDocumentSectionBreakOperation } from './commands/operations/insert-break.operation';
+import { DocOpenPageSettingCommand } from './commands/operations/open-page-setting.operation';
+import { SetDocZoomRatioOperation } from './commands/operations/set-doc-zoom-ratio.operation';
+import { defaultPluginConfig, DOCS_UI_PLUGIN_CONFIG_KEY, DOCS_UI_PLUGIN_NAME } from './config/config';
+import { DocAutoFormatController } from './controllers/doc-auto-format.controller';
+import { DocHeaderFooterController } from './controllers/doc-header-footer.controller';
+import { DocMoveCursorController } from './controllers/doc-move-cursor.controller';
+import { DocParagraphSettingController } from './controllers/doc-paragraph-setting.controller';
+import { DocSectionSettingController } from './controllers/doc-section-setting.controller';
+import { DocTableController } from './controllers/doc-table.controller';
+import { MobileComponentsController } from './controllers/mobile/components.controller';
+import { DocMobileUIController } from './controllers/mobile/ui.controller';
+import { DocBackScrollRenderController } from './controllers/render-controllers/back-scroll.render-controller';
+import { DocCanvasPopupLayoutInteractionController } from './controllers/render-controllers/doc-canvas-popup-layout-interaction.controller';
+import { DocChecklistRenderController } from './controllers/render-controllers/doc-checklist.render-controller';
+import { DocClipboardController } from './controllers/render-controllers/doc-clipboard.controller';
+import { DocContextMenuRenderController } from './controllers/render-controllers/doc-contextmenu.render-controller';
+import { DocEditorBridgeController } from './controllers/render-controllers/doc-editor-bridge.controller';
+import { DocIMEInputController } from './controllers/render-controllers/doc-ime-input.controller';
+import { DocInputController } from './controllers/render-controllers/doc-input.controller';
+import { DocLayoutProgressRenderController } from './controllers/render-controllers/doc-layout-progress.render-controller';
+import { DocLayoutRecoveryRenderController } from './controllers/render-controllers/doc-layout-recovery.render-controller';
+import {
+ DocParagraphPlaceholderRenderController,
+} from './controllers/render-controllers/doc-paragraph-placeholder.render-controller';
+import { DocResizeRenderController } from './controllers/render-controllers/doc-resize.render-controller';
+import { DocRenderController } from './controllers/render-controllers/doc.render-controller';
+import { MobileDocBackScrollRenderController } from './controllers/render-controllers/mobile/back-scroll.render-controller';
+import { MobileDocSelectionRenderController } from './controllers/render-controllers/mobile/doc-selection-render.controller';
+import { MobileDocRenderController } from './controllers/render-controllers/mobile/doc.render-controller';
+import { MobileDocZoomRenderController } from './controllers/render-controllers/mobile/zoom.render-controller';
+import { DocZoomRenderController } from './controllers/render-controllers/zoom.render-controller';
+import { DocClipboardService, IDocClipboardService } from './services/clipboard/clipboard.service';
+import {
+ DocClipboardPasteAdapterService,
+ IDocClipboardPasteAdapterService,
+} from './services/clipboard/doc-paste-mutation-adapter.service';
+import { DocHtmlExportService } from './services/clipboard/udm-to-html/doc-html-export.service';
+import { DocAutoFormatService } from './services/doc-auto-format.service';
+import { DocEventManagerService } from './services/doc-event-manager.service';
+import { DocIMEInputManagerService } from './services/doc-ime-input-manager.service';
+import { DocIMEStateChangeInterceptorService } from './services/doc-ime-state-change-interceptor.service';
+import { DocLayoutInteractionService } from './services/doc-layout-interaction.service';
+import { DocLayoutProgressService } from './services/doc-layout-progress.service';
+import { DocMenuStyleService, SetDocInputStyleCommand } from './services/doc-menu-style.service';
+import { DocMobileElementMenuService } from './services/doc-mobile-element-menu.service';
+import { DocPageLayoutService } from './services/doc-page-layout.service';
+import { DocCanvasPopManagerService } from './services/doc-popup-manager.service';
+import { DocPrintInterceptorService } from './services/doc-print-interceptor.service';
+import { DocViewScaleService } from './services/doc-view-scale';
+import { DocsRenderService } from './services/docs-render.service';
+import { EditorService, IEditorService } from './services/editor/editor-manager.service';
+import { DocFloatMenuService } from './services/float-menu.service';
+import { MobileDocSelectionRenderService } from './services/mobile/doc-selection-render.service';
+import { MobileDocViewScaleService } from './services/mobile/doc-view-scale';
+import { MobileDocFloatMenuService } from './services/mobile/float-menu.service';
+import { DocSelectionRenderService } from './services/selection/doc-selection-render.service';
+
+@DependentOn(UniverDocsPlugin, UniverRenderEnginePlugin, UniverMobileUIPlugin)
+export class UniverDocsMobileUIPlugin extends Plugin {
+ static override pluginName = DOCS_UI_PLUGIN_NAME;
+ static override packageName = pkg.name;
+ static override version = pkg.version;
+ // static override type = UniverInstanceType.UNIVER_DOC;
+
+ constructor(
+ private readonly _config: Partial<IUniverDocsUIConfig> = {},
+ @Inject(Injector) override _injector: Injector,
+ @IRenderManagerService private readonly _renderManagerSrv: IRenderManagerService,
+ @ICommandService private _commandService: ICommandService,
+ @IConfigService private readonly _configService: IConfigService
+ ) {
+ super();
+
+ const mobileConfig: Partial<IUniverDocsUIConfig> = {
+ ...this._config,
+ fitToWidth: {
+ ...defaultPluginConfig.fitToWidth,
+ mode: 'fit-width',
+ target: 'viewport',
+ paddingX: 12,
+ minScale: 0,
+ maxScale: 1,
+ align: 'center',
+ ...this._config.fitToWidth,
+ },
+ };
+
+ // Manage the plugin configuration.
+ const { menu, ...rest } = merge(
+ {},
+ defaultPluginConfig,
+ mobileConfig
+ );
+ if (menu) {
+ this._configService.setConfig('menu', menu, { merge: true });
+ }
+ this._configService.setConfig(DOCS_UI_PLUGIN_CONFIG_KEY, rest);
+
+ this._initDependencies(_injector);
+ this._initCommand();
+ }
+
+ override onReady(): void {
+ this._initRenderBasics();
+ this._initAutoFocus();
+
+ touchDependencies(this._injector, [
+ [DocsRenderService],
+ ]);
+ }
+
+ override onRendered(): void {
+ this._initRenderModules();
+
+ touchDependencies(this._injector, [
+ [DocAutoFormatController],
+ [DocMoveCursorController],
+ [DocParagraphSettingController],
+ [DocSectionSettingController],
+ [DocTableController],
+ [MobileComponentsController],
+
+ // FIXME: LifecycleStages.Rendered must be used, otherwise the menu cannot be added to the DOM, but the sheet ui
+ // plugin can be added in LifecycleStages.Ready
+ [DocMobileUIController],
+ ]);
+ }
+
+ // eslint-disable-next-line max-lines-per-function
+ private _initCommand() {
+ [
+ DeleteLeftCommand,
+ DeleteRightCommand,
+ SetInlineFormatBoldCommand,
+ SetInlineFormatItalicCommand,
+ SetInlineFormatUnderlineCommand,
+ SetInlineFormatStrikethroughCommand,
+ SetInlineFormatSubscriptCommand,
+ SetInlineFormatSuperscriptCommand,
+ SetInlineFormatFontSizeCommand,
+ SetInlineFormatFontFamilyCommand,
+ SetInlineFormatTextColorCommand,
+ ResetInlineFormatTextColorCommand,
+ SetInlineFormatTextFillCommand,
+ ResetInlineFormatTextBackgroundColorCommand,
+ SetInlineFormatTextBackgroundColorCommand,
+ SetInlineFormatCommand,
+ SetDocInputStyleCommand,
+ BreakLineCommand,
+ DeleteCustomBlockCommand,
+ MoveDocBlockCommand,
+ MergeTwoParagraphCommand,
+ RemoveHorizontalLineCommand,
+ SetDocZoomRatioOperation,
+ OrderListCommand,
+ BulletListCommand,
+ ListOperationCommand,
+ AlignLeftCommand,
+ AlignCenterCommand,
+ AlignRightCommand,
+ AlignOperationCommand,
+ AlignJustifyCommand,
+ HorizontalLineCommand,
+ CreateDocTableCommand,
+ DocTableInsertRowCommand,
+ DocTableInsertRowAboveCommand,
+ DocTableInsertRowBellowCommand,
+ DocTableInsertColumnCommand,
+ DocTableInsertColumnLeftCommand,
+ DocTableInsertColumnRightCommand,
+ DocTableDeleteRowsCommand,
+ DocTableDeleteColumnsCommand,
+ DocTableDeleteTableCommand,
+ CloseHeaderFooterCommand,
+ DocTableTabCommand,
+ TabCommand,
+ AfterSpaceCommand,
+ EnterCommand,
+ ChangeListNestingLevelCommand,
+ ChangeListTypeCommand,
+ CheckListCommand,
+ ToggleCheckListCommand,
+ QuickListCommand,
+ IMEInputCommand,
+ SwitchDocModeCommand,
+ DocParagraphSettingCommand,
+ InnerPasteCommand,
+ CutContentCommand,
+ ReplaceSnapshotCommand,
+ CoverContentCommand,
+ SetDocZoomRatioCommand,
+ DocSelectAllCommand,
+ DocSelectWordCommand,
+ DocParagraphSettingPanelOperation,
+ DocSectionSettingPanelOperation,
+ InsertDocumentColumnBreakOperation,
+ InsertDocumentSectionBreakOperation,
+ MoveCursorOperation,
+ MoveSelectionOperation,
+ ReplaceTextRunsCommand,
+ ReplaceSelectionCommand,
+ InsertCustomRangeCommand,
+ InsertSpecialCharacterCommand,
+ SetParagraphNamedStyleCommand,
+ QuickHeadingCommand,
+ DocCopyCurrentParagraphCommand,
+ DocCutCurrentParagraphCommand,
+ H1HeadingCommand,
+ H2HeadingCommand,
+ H3HeadingCommand,
+ H4HeadingCommand,
+ H5HeadingCommand,
+ NormalTextHeadingCommand,
+ TitleHeadingCommand,
+ SubtitleHeadingCommand,
+ InsertBulletListBellowCommand,
+ InsertOrderListBellowCommand,
+ InsertCheckListBellowCommand,
+ InsertHorizontalLineBellowCommand,
+ DocPageSetupCommand,
+ DocOpenPageSettingCommand,
+ ].forEach((e) => {
+ this.disposeWithMe(this._commandService.registerCommand(e));
+ });
+
+ [DocCopyCommand, DocCutCommand, DocPasteCommand, DeleteCurrentParagraphCommand].forEach((command) => this.disposeWithMe(this._commandService.registerMultipleCommand(command)));
+ }
+
+ private _initDependencies(injector: Injector) {
+ const dependencies = mergeOverrideWithDependencies([
+ [DocPrintInterceptorService],
+ [DocClipboardController],
+ [DocEditorBridgeController],
+ [MobileComponentsController],
+ [DocMobileUIController],
+ [DocAutoFormatController],
+ [DocTableController],
+ [DocMoveCursorController],
+ [DocParagraphSettingController],
+ [DocSectionSettingController],
+ [IEditorService, { useClass: EditorService }],
+ [IDocClipboardService, { useClass: DocClipboardService }],
+ [DocClipboardPasteAdapterService],
+ [IDocClipboardPasteAdapterService, { useClass: DocClipboardPasteAdapterService }],
+ [DocHtmlExportService],
+ [DocCanvasPopManagerService],
+ [DocLayoutProgressService],
+ [DocMobileElementMenuService],
+ [DocsRenderService],
+ [IDocStateChangeInterceptorService, { useClass: DocIMEStateChangeInterceptorService }],
+ [DocAutoFormatService],
+ [DocMenuStyleService],
+
+ ], this._config.override);
+ dependencies.forEach((d) => injector.add(d));
+ }
+
+ private _initAutoFocus() {
+ const currentService = this._injector.get(IUniverInstanceService);
+ const editorService = this._injector.get(IEditorService);
+ this.disposeWithMe(currentService.getCurrentTypeOfUnit$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC).subscribe((doc) => {
+ if (!doc) {
+ return;
+ }
+
+ const id = doc.getUnitId();
+ if (!editorService.isEditor(id)) {
+ currentService.focusUnit(id);
+ }
+ }));
+ }
+
+ private _initRenderBasics(): void {
+ ([
+ [DocSkeletonManagerService],
+ [DocSelectionRenderService, { useClass: MobileDocSelectionRenderService }],
+ [DocInterceptorService],
+ [DocViewScaleService, { useClass: MobileDocViewScaleService }],
+ [DocPageLayoutService],
+ [DocLayoutInteractionService],
+ [DocCanvasPopupLayoutInteractionController],
+ [DocIMEInputManagerService],
+ [DocLayoutProgressRenderController],
+ [DocRenderController, { useClass: MobileDocRenderController }],
+ [DocZoomRenderController, { useClass: MobileDocZoomRenderController }],
+ [DocBackScrollRenderController, { useClass: MobileDocBackScrollRenderController }],
+ [MobileDocSelectionRenderController],
+ ] as Dependency[]).forEach((m) => {
+ this._renderManagerSrv.registerRenderModule(UniverInstanceType.UNIVER_DOC, m);
+ });
+ }
+
+ private _initRenderModules(): void {
+ ([
+ [DocEventManagerService],
+ [DocFloatMenuService, { useClass: MobileDocFloatMenuService }],
+ [DocHeaderFooterController],
+ [DocResizeRenderController],
+ [DocParagraphPlaceholderRenderController],
+ [DocContextMenuRenderController],
+ [DocChecklistRenderController],
+ [DocClipboardController],
+ [DocInputController],
+ [DocIMEInputController],
+ [DocLayoutRecoveryRenderController],
+ [DocEditorBridgeController],
+ ] as Dependency[]).forEach((m) => {
+ this._renderManagerSrv.registerRenderModule(UniverInstanceType.UNIVER_DOC, m);
+ });
+ }
+}
diff --git a/packages/docs-ui/src/plugin.ts b/packages/docs-ui/src/plugin.ts
index 437756240b..bc1c409c83 100644
--- a/packages/docs-ui/src/plugin.ts
+++ b/packages/docs-ui/src/plugin.ts
@@ -64,7 +64,7 @@ import {
} from './commands/commands/doc-horizontal-line.command';
import { DocPageSetupCommand } from './commands/commands/doc-page-setup.command';
import { DocParagraphSettingCommand } from './commands/commands/doc-paragraph-setting.command';
-import { DocSelectAllCommand } from './commands/commands/doc-select-all.command';
+import { DocSelectAllCommand, DocSelectWordCommand } from './commands/commands/doc-select-all.command';
import { IMEInputCommand } from './commands/commands/ime-input.command';
import {
ResetInlineFormatTextBackgroundColorCommand,
@@ -145,7 +145,7 @@ import { DocSectionSettingPanelOperation } from './commands/operations/doc-secti
import { InsertDocumentColumnBreakOperation, InsertDocumentSectionBreakOperation } from './commands/operations/insert-break.operation';
import { DocOpenPageSettingCommand } from './commands/operations/open-page-setting.operation';
import { SetDocZoomRatioOperation } from './commands/operations/set-doc-zoom-ratio.operation';
-import { defaultPluginConfig, DOCS_UI_PLUGIN_CONFIG_KEY } from './config/config';
+import { defaultPluginConfig, DOCS_UI_PLUGIN_CONFIG_KEY, DOCS_UI_PLUGIN_NAME } from './config/config';
import { ComponentsController } from './controllers/components.controller';
import { DocAutoFormatController } from './controllers/doc-auto-format.controller';
import { DocHeaderFooterController } from './controllers/doc-header-footer.controller';
@@ -184,6 +184,7 @@ import { DocIMEStateChangeInterceptorService } from './services/doc-ime-state-ch
import { DocLayoutInteractionService } from './services/doc-layout-interaction.service';
import { DocLayoutProgressService } from './services/doc-layout-progress.service';
import { DocMenuStyleService, SetDocInputStyleCommand } from './services/doc-menu-style.service';
+import { DocMobileElementMenuService } from './services/doc-mobile-element-menu.service';
import { DocPageLayoutService } from './services/doc-page-layout.service';
import { DocParagraphMenuService } from './services/doc-paragraph-menu.service';
import { DocCanvasPopManagerService } from './services/doc-popup-manager.service';
@@ -239,7 +240,7 @@ import {
@DependentOn(UniverDocsPlugin, UniverRenderEnginePlugin)
export class UniverDocsUIPlugin extends Plugin {
- static override pluginName = 'DOC_UI_PLUGIN';
+ static override pluginName = DOCS_UI_PLUGIN_NAME;
static override packageName = pkg.name;
static override version = pkg.version;
// static override type = UniverInstanceType.UNIVER_DOC;
@@ -359,6 +360,7 @@ export class UniverDocsUIPlugin extends Plugin {
CoverContentCommand,
SetDocZoomRatioCommand,
DocSelectAllCommand,
+ DocSelectWordCommand,
DocParagraphSettingPanelOperation,
DocSectionSettingPanelOperation,
InsertDocumentColumnBreakOperation,
@@ -457,6 +459,7 @@ export class UniverDocsUIPlugin extends Plugin {
[DocHtmlExportService],
[DocCanvasPopManagerService],
[DocLayoutProgressService],
+ [DocMobileElementMenuService],
[DocsRenderService],
[IDocStateChangeInterceptorService, { useClass: DocIMEStateChangeInterceptorService }],
[DocAutoFormatService],
@@ -481,7 +484,7 @@ export class UniverDocsUIPlugin extends Plugin {
}));
}
- private _initRenderBasics(): void {
+ private _initRenderBasics() {
([
[DocSkeletonManagerService],
[DocSelectionRenderService],
@@ -501,7 +504,7 @@ export class UniverDocsUIPlugin extends Plugin {
});
}
- private _initRenderModules(): void {
+ private _initRenderModules() {
([
[DocEventManagerService],
[DocFloatMenuService],
diff --git a/packages/docs-ui/src/services/__tests__/doc-mobile-element-menu.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-mobile-element-menu.service.spec.ts
new file mode 100644
index 0000000000..2777ac6528
--- /dev/null
+++ b/packages/docs-ui/src/services/__tests__/doc-mobile-element-menu.service.spec.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 { IDocMobileElementTarget } from '../doc-mobile-element-menu.service';
+import { Univer, UniverInstanceType } from '@univerjs/core';
+import { CanvasColorService, ICanvasColorService, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
+import { CanvasPopupService, ICanvasPopupService } from '@univerjs/ui';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { DocMobileElementMenuService } from '../doc-mobile-element-menu.service';
+import { DocCanvasPopManagerService } from '../doc-popup-manager.service';
+
+describe('DocMobileElementMenuService', () => {
+ let univer: Univer;
+ let service: DocMobileElementMenuService;
+ const target: IDocMobileElementTarget = {
+ unitId: 'doc',
+ rect: { left: 10, top: 500, right: 200, bottom: 580 },
+ onEdit: vi.fn(),
+ onDelete: vi.fn(),
+ };
+
+ beforeEach(() => {
+ univer = new Univer();
+ const injector = univer.__getInjector();
+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
+ injector.add([ICanvasColorService, { useClass: CanvasColorService }]);
+ injector.add([ICanvasPopupService, { useClass: CanvasPopupService }]);
+ injector.add([DocCanvasPopManagerService]);
+ injector.add([DocMobileElementMenuService]);
+ univer.createUnit(UniverInstanceType.UNIVER_DOC, { id: 'doc', body: { dataStream: '\r\n' } });
+ injector.get(IRenderManagerService).createRender('doc');
+ service = injector.get(DocMobileElementMenuService);
+ });
+
+ afterEach(() => univer.dispose());
+
+ it('retains the consumed object anchor while its floating menu closes for editing', async () => {
+ service.capture(target);
+ expect(service.takeTarget('doc')).toBe(target);
+ await Promise.resolve();
+ service.show(target);
+ service.close();
+ expect(service.getEditingBounds('doc')).toBe(target.rect);
+ expect(service.getEditingBounds('another-doc')).toBeNull();
+ });
+
+ it('clears the previous anchor on a non-object gesture and rejects unconsumed hits', async () => {
+ service.show(target);
+ expect(service.takeTarget('doc')).toBeNull();
+ expect(service.getEditingBounds('doc')).toBeNull();
+ service.capture(target);
+ await Promise.resolve();
+ expect(service.takeTarget('doc')).toBeNull();
+ });
+
+ it('replaces a previous object anchor when another editor opens', () => {
+ service.show(target);
+ const listBounds = { left: 10, top: 100, right: 10, bottom: 100 };
+ service.setEditingBounds('doc', listBounds);
+ service.close();
+ expect(service.getEditingBounds('doc')).toBe(listBounds);
+ expect(service.getEditingBounds('another-doc')).toBeNull();
+ });
+});
diff --git a/packages/docs-ui/src/services/__tests__/doc-page-layout.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-page-layout.service.spec.ts
index b601e33457..e1daae2af9 100644
--- a/packages/docs-ui/src/services/__tests__/doc-page-layout.service.spec.ts
+++ b/packages/docs-ui/src/services/__tests__/doc-page-layout.service.spec.ts
@@ -200,6 +200,29 @@ describe('DocPageLayoutService', () => {
expect(scene.viewport.scrollX).toBe(0);
});
+ it('adds and removes temporary bottom scroll reserve without changing document placement', () => {
+ const { documentComponent, scene, service } = createLayoutService({
+ documentWidth: 600,
+ documentHeight: 900,
+ pageMarginLeft: 40,
+ pageMarginTop: 20,
+ engineWidth: 500,
+ engineHeight: 800,
+ });
+
+ service.calculatePagePosition();
+ service.setBottomReserve(300);
+
+ expect(documentComponent.left).toBe(40);
+ expect(documentComponent.top).toBe(20);
+ expect(service.resolveSceneHeight(940)).toBe(1240);
+ expect(scene.height).toBe(1240);
+
+ service.setBottomReserve(0);
+
+ expect(scene.height).toBe(940);
+ });
+
it('uses fit-width start alignment padding instead of centering the page', () => {
TestDocViewScaleService.viewScale = 2;
TestDocViewScaleService.availableWidth = 1000;
diff --git a/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts
index a64519bbd8..4e148cc5ec 100644
--- a/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts
+++ b/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts
@@ -1353,6 +1353,7 @@ function createService(options: {
inputBefore$?: Subject<unknown>;
keydown$?: Subject<unknown>;
layoutInteractionService?: DocLayoutInteractionService;
+ mobile?: boolean;
replaceDocRanges?: ReturnType<typeof vi.fn>;
scrollAfter$?: { subscribeEvent: (callback: (event: { scrollY: number }) => void) => { dispose: () => void } };
selectionStart$?: Subject<unknown>;
@@ -1439,7 +1440,10 @@ function createService(options: {
}),
permissionPointUpdate$: new Subject(),
} as never,
- options.layoutInteractionService ?? new DocLayoutInteractionService()
+ options.layoutInteractionService ?? new DocLayoutInteractionService(),
+ {
+ getContextValue: () => options.mobile ?? false,
+ } as never
);
}
diff --git a/packages/docs-ui/src/services/__tests__/doc-view-scale.spec.ts b/packages/docs-ui/src/services/__tests__/doc-view-scale.spec.ts
index aa04435b8b..2fd1fe16fa 100644
--- a/packages/docs-ui/src/services/__tests__/doc-view-scale.spec.ts
+++ b/packages/docs-ui/src/services/__tests__/doc-view-scale.spec.ts
@@ -18,9 +18,19 @@
* @vitest-environment jsdom
*/
-import { DocumentFlavor, MODERN_DOCUMENT_WIDTH, ModernDocumentWidthMode } from '@univerjs/core';
+import type { IUniverDocsUIConfig } from '../../config/config';
+import {
+ createInternalEditorID,
+ DocumentFlavor,
+ IConfigService,
+ MODERN_DOCUMENT_WIDTH,
+ ModernDocumentWidthMode,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { CanvasColorService, Engine, ICanvasColorService, RenderUnit, Scene } from '@univerjs/engine-render';
import { afterEach, describe, expect, it } from 'vitest';
-import { DEFAULT_DOC_FIT_TO_WIDTH_OPTIONS } from '../../config/config';
+import { DEFAULT_DOC_FIT_TO_WIDTH_OPTIONS, DOCS_UI_PLUGIN_CONFIG_KEY } from '../../config/config';
import {
calcDocFitToWidthScale,
DocViewScaleService,
@@ -28,8 +38,47 @@ import {
resolveDocViewScale,
} from '../doc-view-scale';
+import { MobileDocViewScaleService } from '../mobile/doc-view-scale';
+
+const cleanup: Array<() => void> = [];
+
+function createRender(
+ mobile: boolean,
+ documentFlavor: DocumentFlavor,
+ availableWidth: number,
+ pageWidth: number,
+ zoomRatio = 1,
+ config: IUniverDocsUIConfig = { fitToWidth: { mode: 'fit-width', paddingX: 0, minScale: 0 } },
+ id = 'view-scale-test'
+) {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+ injector.add([ICanvasColorService, { useClass: CanvasColorService }]);
+ injector.get(IConfigService).setConfig(DOCS_UI_PLUGIN_CONFIG_KEY, config);
+ const unit = univer.createUnit(UniverInstanceType.UNIVER_DOC, {
+ id,
+ body: { dataStream: 'Text\r\n' },
+ settings: { zoomRatio },
+ documentStyle: { documentFlavor, pageSize: { width: pageWidth, height: Infinity } },
+ });
+ const engine = injector.createInstance(Engine, unit.getUnitId(), { elementWidth: availableWidth, elementHeight: 800 });
+ const scene = new Scene('view-scale', engine);
+ const render = injector.createInstance(RenderUnit, { unit, engine, scene, isMainScene: true });
+ render.addRenderDependencies([[DocViewScaleService, { useClass: mobile ? MobileDocViewScaleService : DocViewScaleService }]]);
+ cleanup.push(() => {
+ render.dispose();
+ scene.dispose();
+ engine.dispose();
+ univer.dispose();
+ });
+ return { service: render.with(DocViewScaleService), engine };
+}
+
describe('doc view scale helpers', () => {
afterEach(() => {
+ for (const dispose of cleanup.splice(0).reverse()) {
+ dispose();
+ }
document.body.innerHTML = '';
});
@@ -99,100 +148,39 @@ describe('doc view scale helpers', () => {
});
it('computes view scale from engine width, document zoom, and configured page width', () => {
- const context = {
- engine: { width: 1440 },
- unit: {
- getSettings: () => ({ zoomRatio: 1.25 }),
- getSnapshot: () => ({
- documentStyle: {
- documentFlavor: DocumentFlavor.MODERN,
- pageSize: { width: 960, height: Number.POSITIVE_INFINITY },
- },
- }),
- },
- };
- const service = new DocViewScaleService(
- context as never,
- { getConfig: () => ({ fitToWidth: { mode: 'fit-width', paddingX: 0, minScale: 0 } }) } as never
- );
-
+ const { service } = createRender(false, DocumentFlavor.MODERN, 1440, 960, 1.25);
expect(service.getFitToWidthScale()).toBe(1.5);
expect(service.getViewScale()).toBe(1.875);
});
- it('falls back to default modern width and zoom while embedded doc units are not resolved', () => {
- const service = new DocViewScaleService(
- {
- engine: { width: 960 },
- unit: null,
- } as never,
- { getConfig: () => ({ fitToWidth: { mode: 'fit-width', paddingX: 0, minScale: 0 } }) } as never
- );
-
- expect(service.getBaseWidth()).toBe(MODERN_DOCUMENT_WIDTH[ModernDocumentWidthMode.MEDIUM]);
- expect(service.getUserZoomRatio()).toBe(1);
- expect(service.getViewScale()).toBe(1);
- });
-
- it('uses configured container width for container-targeted fitting', () => {
- const context = {
- engine: { width: 960 },
- unit: {
- getSettings: () => ({ zoomRatio: 1 }),
- getSnapshot: () => ({
- documentStyle: {
- documentFlavor: DocumentFlavor.MODERN,
- pageSize: { width: 960, height: Number.POSITIVE_INFINITY },
- },
- }),
- },
- };
- const service = new DocViewScaleService(
- context as never,
- {
- getConfig: () => ({
- container: { clientWidth: 480 },
- fitToWidth: { mode: 'fit-width', target: 'container', paddingX: 0, minScale: 0 },
- }),
- } as never
- );
-
- expect(service.getAvailableWidth()).toBe(480);
- expect(service.getFitToWidthScale()).toBe(0.5);
- });
-
- it('resolves string containers as element ids for embedded fitting', () => {
+ it('uses configured element and string containers for container-targeted fitting', () => {
const container = document.createElement('div');
container.id = 'univerdoc';
- Object.defineProperty(container, 'clientWidth', {
- configurable: true,
- value: 480,
- });
+ Object.defineProperty(container, 'clientWidth', { configurable: true, value: 480 });
document.body.appendChild(container);
+ for (const target of [container, 'univerdoc']) {
+ const { service } = createRender(false, DocumentFlavor.MODERN, 960, 960, 1, {
+ container: target,
+ fitToWidth: { mode: 'fit-width', target: 'container', paddingX: 0, minScale: 0 },
+ });
+ expect(service.getAvailableWidth()).toBe(480);
+ expect(service.getFitToWidthScale()).toBe(0.5);
+ }
+ });
+
+ it('keeps mobile internal editor text at its own zoom across compact and expanded widths', () => {
+ const { service, engine } = createRender(true, DocumentFlavor.MODERN, 270, Infinity, 1, {
+ fitToWidth: { mode: 'fit-width', paddingX: 12, minScale: 0, maxScale: 1 },
+ }, createInternalEditorID('shape-text'));
+ expect(service.getViewScale()).toBe(1);
+ engine.resizeBySize(390, 700);
+ expect(service.getViewScale()).toBe(1);
+ expect(service.getViewScale(1.25)).toBe(1.25);
+ });
- const context = {
- engine: { width: 960 },
- unit: {
- getSettings: () => ({ zoomRatio: 1 }),
- getSnapshot: () => ({
- documentStyle: {
- documentFlavor: DocumentFlavor.MODERN,
- pageSize: { width: 960, height: Number.POSITIVE_INFINITY },
- },
- }),
- },
- };
- const service = new DocViewScaleService(
- context as never,
- {
- getConfig: () => ({
- container: 'univerdoc',
- fitToWidth: { mode: 'fit-width', target: 'container', paddingX: 0, minScale: 0 },
- }),
- } as never
- );
-
- expect(service.getAvailableWidth()).toBe(480);
- expect(service.getFitToWidthScale()).toBe(0.5);
+ it('keeps Modern documents at 1:1 scale on mobile while Traditional documents still fit', () => {
+ expect(createRender(true, DocumentFlavor.MODERN, 400, 800).service.getFitToWidthScale()).toBe(1);
+ expect(createRender(true, DocumentFlavor.TRADITIONAL, 400, 800).service.getFitToWidthScale()).toBe(0.5);
+ expect(createRender(false, DocumentFlavor.MODERN, 400, 800).service.getFitToWidthScale()).toBe(0.5);
});
});
diff --git a/packages/docs-ui/src/services/__tests__/float-menu.service.spec.ts b/packages/docs-ui/src/services/__tests__/float-menu.service.spec.ts
index f770364501..8af97e0dde 100644
--- a/packages/docs-ui/src/services/__tests__/float-menu.service.spec.ts
+++ b/packages/docs-ui/src/services/__tests__/float-menu.service.spec.ts
@@ -45,13 +45,18 @@ import {
} from '@univerjs/docs';
import { NORMAL_TEXT_SELECTION_PLUGIN_STYLE } from '@univerjs/engine-render';
import { UnitAction } from '@univerjs/protocol';
-import { ComponentManager } from '@univerjs/ui';
+import {
+ ComponentManager,
+ ContextMenuPosition,
+ IContextMenuService,
+} from '@univerjs/ui';
import { Subject } from 'rxjs';
import { describe, expect, it } from 'vitest';
import { EmbedRuntimeFocusCoordinator, IDocEmbedRuntimeFocusCoordinator } from '../doc-embed-integration.service';
import { DocLayoutInteractionService } from '../doc-layout-interaction.service';
import { DocCanvasPopManagerService } from '../doc-popup-manager.service';
import { DocFloatMenuService } from '../float-menu.service';
+import { MobileDocFloatMenuService } from '../mobile/float-menu.service';
import { DocSelectionRenderService } from '../selection/doc-selection-render.service';
class InertDocCanvasPopManagerService {
@@ -71,6 +76,10 @@ class RecordingDocCanvasPopManagerService {
onDismiss?: () => void;
disposedCount = 0;
+ getRangeBounds() {
+ return [{ left: 100, right: 200, top: 240, bottom: 260 }];
+ }
+
attachPopupToRange(range: { startOffset: number; endOffset: number }, options: { direction: string; offset?: [number, number]; extraProps?: { onDismiss?: () => void } }) {
this.ranges.push(`${range.startOffset}:${range.endOffset}`);
this.directions.push(options.direction);
@@ -85,6 +94,36 @@ class RecordingDocCanvasPopManagerService {
}
}
+class RecordingContextMenuService implements IContextMenuService {
+ disabled = false;
+ visible = false;
+ readonly triggers: Array<{ clientX: number; clientY: number; menuType: string }> = [];
+
+ enable(): void {
+ this.disabled = false;
+ }
+
+ disable(): void {
+ this.disabled = true;
+ }
+
+ triggerContextMenu(event: { clientX: number; clientY: number }, menuType: string): void {
+ if (this.disabled) {
+ return;
+ }
+ this.visible = true;
+ this.triggers.push({ clientX: event.clientX, clientY: event.clientY, menuType });
+ }
+
+ hideContextMenu(): void {
+ this.visible = false;
+ }
+
+ registerContextMenuHandler() {
+ return { dispose() {} };
+ }
+}
+
class ActiveDocSelectionRenderService {
private readonly _selectionStart$ = new Subject<void>();
readonly onSelectionStart$ = this._selectionStart$.asObservable();
@@ -103,13 +142,16 @@ function createActiveFloatMenuHarness(
unitId: string,
body: ConstructorParameters<typeof DocumentDataModel>[0]['body'],
runtimeFocusCoordinator?: EmbedRuntimeFocusCoordinator,
- headers?: ConstructorParameters<typeof DocumentDataModel>[0]['headers']
+ headers?: ConstructorParameters<typeof DocumentDataModel>[0]['headers'],
+ mobile = false
) {
const injector = new Injector();
+ const contextMenuService = new RecordingContextMenuService();
injector.add([IPermissionService, { useClass: PermissionService }]);
injector.add([ILogService, { useClass: DesktopLogService }]);
injector.add([IConfigService, { useClass: ConfigService }]);
injector.add([IContextService, { useClass: ContextService }]);
+ injector.add([IContextMenuService, { useValue: contextMenuService }]);
injector.add([ICommandService, { useClass: CommandService }]);
injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);
injector.add([DocSelectionManagerService]);
@@ -123,12 +165,13 @@ function createActiveFloatMenuHarness(
injector.get(ICommandService).registerCommand(SetTextSelectionsOperation);
const univerInstanceService = injector.get(IUniverInstanceService) as UniverInstanceService;
univerInstanceService.__addUnit(new DocumentDataModel({ id: unitId, body, headers }));
- const service = injector.createInstance(DocFloatMenuService, { unitId } as never);
+ const service = injector.createInstance(mobile ? MobileDocFloatMenuService : DocFloatMenuService, { unitId } as never);
const selectionManager = injector.get(DocSelectionManagerService);
selectionManager.__TEST_ONLY_setCurrentSelection({ unitId, subUnitId: unitId });
return {
injector,
+ contextMenuService,
popupService: injector.get(DocCanvasPopManagerService) as unknown as RecordingDocCanvasPopManagerService,
selectionManager,
service,
@@ -144,6 +187,7 @@ describe('DocFloatMenuService', () => {
injector.add([ILogService, { useClass: DesktopLogService }]);
injector.add([IConfigService, { useClass: ConfigService }]);
injector.add([IContextService, { useClass: ContextService }]);
+ injector.add([IContextMenuService, { useClass: RecordingContextMenuService }]);
injector.add([ICommandService, { useClass: CommandService }]);
injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);
injector.add([DocSelectionManagerService]);
@@ -164,6 +208,7 @@ describe('DocFloatMenuService', () => {
injector.add([ILogService, { useClass: DesktopLogService }]);
injector.add([IConfigService, { useClass: ConfigService }]);
injector.add([IContextService, { useClass: ContextService }]);
+ injector.add([IContextMenuService, { useClass: RecordingContextMenuService }]);
injector.add([ICommandService, { useClass: CommandService }]);
injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);
injector.add([DocSelectionManagerService]);
@@ -229,6 +274,37 @@ describe('DocFloatMenuService', () => {
expect(layoutInteractionService.isActive).toBe(false);
});
+ it('opens the mobile context menu above an expanded text selection instead of the desktop float toolbar', () => {
+ const unitId = 'doc-mobile-selection-menu';
+ const harness = createActiveFloatMenuHarness(unitId, {
+ dataStream: 'Mobile selection\r\n',
+ paragraphs: [{ paragraphId: 'para_docs_ui_mobile_selection_menu', startIndex: 16 }],
+ sectionBreaks: [],
+ customRanges: [],
+ tables: [],
+ textRuns: [],
+ }, undefined, undefined, true);
+
+ harness.selectionManager.__replaceTextRangesWithNoRefresh({
+ textRanges: [{ startOffset: 0, endOffset: 6, collapsed: false }],
+ rectRanges: [],
+ segmentId: '',
+ segmentPage: -1,
+ style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE,
+ isEditing: true,
+ }, { unitId, subUnitId: unitId });
+
+ expect(harness.contextMenuService.triggers).toEqual([{
+ clientX: 150,
+ clientY: 240,
+ menuType: ContextMenuPosition.MAIN_AREA,
+ }]);
+ expect(harness.popupService.ranges).toEqual([]);
+
+ harness.selectionRenderService.emitSelectionStart();
+ expect(harness.contextMenuService.visible).toBe(false);
+ });
+
it('hides the floating toolbar when document edit permission is revoked', () => {
const unitId = 'doc-read-only-float-menu';
const harness = createActiveFloatMenuHarness(unitId, {
@@ -399,6 +475,7 @@ describe('DocFloatMenuService', () => {
injector.add([ILogService, { useClass: DesktopLogService }]);
injector.add([IConfigService, { useClass: ConfigService }]);
injector.add([IContextService, { useClass: ContextService }]);
+ injector.add([IContextMenuService, { useClass: RecordingContextMenuService }]);
injector.add([ICommandService, { useClass: CommandService }]);
injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);
injector.add([DocSelectionManagerService]);
diff --git a/packages/docs-ui/src/services/doc-mobile-element-menu.service.ts b/packages/docs-ui/src/services/doc-mobile-element-menu.service.ts
new file mode 100644
index 0000000000..47e62c7211
--- /dev/null
+++ b/packages/docs-ui/src/services/doc-mobile-element-menu.service.ts
@@ -0,0 +1,116 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDisposable } from '@univerjs/core';
+import type { IBoundRectNoAngle, IMouseEvent, IPointerEvent } from '@univerjs/engine-render';
+import type { IMobileDocElementMenuProps } from '../views/mobile-element-menu/MobileDocElementMenu';
+import { Disposable, Inject, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { MOBILE_DOC_ELEMENT_MENU } from '../views/mobile-element-menu/MobileDocElementMenu';
+import { DocCanvasPopManagerService } from './doc-popup-manager.service';
+
+export interface IDocMobileElementTarget extends IMobileDocElementMenuProps {
+ unitId: string;
+ rect: IBoundRectNoAngle;
+ onTap?: (offset: { offsetX: number; offsetY: number }) => void;
+ onDrag?: (event: IPointerEvent | IMouseEvent) => void;
+}
+
+/** Element hit testing stays in its plugin; the document owns tap-versus-scroll recognition. */
+export class DocMobileElementMenuService extends Disposable {
+ private _pending: IDocMobileElementTarget | null = null;
+ private _editingBounds: { unitId: string; rect: IBoundRectNoAngle } | null = null;
+ private _popup: IDisposable | null = null;
+ private _unitId: string | null = null;
+
+ constructor(
+ @Inject(DocCanvasPopManagerService) private readonly _popupService: DocCanvasPopManagerService,
+ @IUniverInstanceService instanceService: IUniverInstanceService
+ ) {
+ super();
+ this.disposeWithMe(instanceService.getTypeOfUnitDisposed$(UniverInstanceType.UNIVER_DOC).subscribe((unit) => {
+ if (this._unitId === unit.getUnitId()) {
+ this.close();
+ }
+ if (this._pending?.unitId === unit.getUnitId()) {
+ this._pending = null;
+ }
+ if (this._editingBounds?.unitId === unit.getUnitId()) {
+ this._editingBounds = null;
+ }
+ }));
+ }
+
+ capture(target: IDocMobileElementTarget): boolean {
+ this._pending = target;
+ // A hit not consumed by the document gesture must not leak into the next touch.
+ queueMicrotask(() => {
+ if (this._pending === target) {
+ this._pending = null;
+ }
+ });
+ return true;
+ }
+
+ takeTarget(unitId: string): IDocMobileElementTarget | null {
+ const target = this._pending;
+ this._pending = null;
+ const current = target?.unitId === unitId ? target : null;
+ this._editingBounds = current;
+ return current;
+ }
+
+ setEditingBounds(unitId: string, rect: IBoundRectNoAngle): void {
+ this._editingBounds = { unitId, rect };
+ }
+
+ getEditingBounds(unitId: string): IBoundRectNoAngle | null {
+ return this._editingBounds?.unitId === unitId ? this._editingBounds.rect : null;
+ }
+
+ show(target: IDocMobileElementTarget): void {
+ this.close();
+ this.setEditingBounds(target.unitId, target.rect);
+ this._unitId = target.unitId;
+ this._popup = this._popupService.attachPopupToRect(target.rect, {
+ componentKey: MOBILE_DOC_ELEMENT_MENU,
+ direction: 'top-center',
+ onClickOutside: () => this.close(),
+ extraProps: {
+ onEdit: () => {
+ this.close();
+ return target.onEdit();
+ },
+ onDelete: () => {
+ this.close();
+ return target.onDelete();
+ },
+ },
+ }, target.unitId);
+ }
+
+ close(): void {
+ this._popup?.dispose();
+ this._popup = null;
+ this._unitId = null;
+ }
+
+ override dispose(): void {
+ this._pending = null;
+ this._editingBounds = null;
+ this.close();
+ super.dispose();
+ }
+}
diff --git a/packages/docs-ui/src/services/doc-page-layout.service.ts b/packages/docs-ui/src/services/doc-page-layout.service.ts
index 744b6327bf..e700d44f3e 100644
--- a/packages/docs-ui/src/services/doc-page-layout.service.ts
+++ b/packages/docs-ui/src/services/doc-page-layout.service.ts
@@ -22,6 +22,8 @@ import { VIEWPORT_KEY } from '../basics/docs-view-key';
import { DocViewScaleService, resolveDocFitPaddingX } from './doc-view-scale';
export class DocPageLayoutService extends Disposable implements IRenderModule {
+ private _bottomReserve = 0;
+
constructor(
private _context: IRenderContext<DocumentDataModel>,
@Inject(DocViewScaleService) private readonly _docViewScaleService: DocViewScaleService
@@ -29,6 +31,19 @@ export class DocPageLayoutService extends Disposable implements IRenderModule {
super();
}
+ setBottomReserve(height: number): void {
+ const bottomReserve = Math.max(0, height);
+ if (bottomReserve === this._bottomReserve) {
+ return;
+ }
+ this._bottomReserve = bottomReserve;
+ this.calculatePagePosition();
+ }
+
+ resolveSceneHeight(contentHeight: number): number {
+ return contentHeight + this._bottomReserve / Math.max(this._docViewScaleService.getViewScale(), 0.01);
+ }
+
calculatePagePosition() {
if (this._disposed) return;
@@ -78,6 +93,7 @@ export class DocPageLayoutService extends Disposable implements IRenderModule {
} else {
sceneHeight = docsHeight + pageMarginTop * 2;
}
+ sceneHeight = this.resolveSceneHeight(sceneHeight);
scene.transformByState({ width: sceneWidth, height: sceneHeight });
diff --git a/packages/docs-ui/src/services/doc-paragraph-menu.service.ts b/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
index c9a40c26ec..a0ac6f4673 100644
--- a/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
+++ b/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
@@ -18,7 +18,7 @@ import type { DocumentDataModel, ICustomBlock, ICustomTable, IDisposable, IDocum
import type { IBoundRectNoAngle, IRenderContext, IRenderModule, ITextRangeWithStyle } from '@univerjs/engine-render';
import type { IMutiPageParagraphBound, ITableBound, ITableParagraphBound } from './doc-event-manager.service';
import type { IEditorInputConfig } from './selection/doc-selection-render.service';
-import { BlockType, DataStreamTreeTokenType, Disposable, DOC_RANGE_TYPE, DocumentBlockType, getParagraphContentStartOffset, Inject, IPermissionService, isInternalEditorID, PresetListType } from '@univerjs/core';
+import { BlockType, DataStreamTreeTokenType, Disposable, DOC_RANGE_TYPE, DocumentBlockType, getParagraphContentStartOffset, IContextService, Inject, IPermissionService, isInternalEditorID, PresetListType } from '@univerjs/core';
import { canEditDocumentTargets, DocSelectionManagerService, DocSkeletonManagerService, getDocumentEditTargetObjectIds } from '@univerjs/docs';
import { DocumentEditArea } from '@univerjs/engine-render';
import { BehaviorSubject, combineLatest, first, throttleTime } from 'rxjs';
@@ -163,7 +163,8 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
@Inject(DocFloatMenuService) private _floatMenuService: DocFloatMenuService,
@Inject(DocSelectionRenderService) private _docSelectionRenderService: DocSelectionRenderService,
@IPermissionService private readonly _permissionService: IPermissionService,
- @Inject(DocLayoutInteractionService) private _docLayoutInteractionService: DocLayoutInteractionService
+ @Inject(DocLayoutInteractionService) private _docLayoutInteractionService: DocLayoutInteractionService,
+ @IContextService private readonly _contextService: IContextService
) {
super();
diff --git a/packages/docs-ui/src/services/doc-popup-manager.service.ts b/packages/docs-ui/src/services/doc-popup-manager.service.ts
index 282e50e2cb..4eab5d0a02 100644
--- a/packages/docs-ui/src/services/doc-popup-manager.service.ts
+++ b/packages/docs-ui/src/services/doc-popup-manager.service.ts
@@ -181,6 +181,11 @@ export class DocCanvasPopManagerService extends Disposable {
this._popupUnits$.next(new Set(this._popupCountByUnit.keys()));
}
+ getRangeBounds(range: ITextRangeParam, unitId: string): IBoundRectNoAngle[] | undefined {
+ const currentRender = this._renderManagerService.getRenderUnitById(unitId);
+ return currentRender ? calcDocRangePositions(range, currentRender) : undefined;
+ }
+
private _shouldUpdateForCommand(commandInfo: { id: string; params?: unknown }, unitId: string): boolean {
if (commandInfo.id !== SetDocZoomRatioOperation.id && commandInfo.id !== RichTextEditingMutation.id) {
return false;
diff --git a/packages/docs-ui/src/services/doc-view-scale.ts b/packages/docs-ui/src/services/doc-view-scale.ts
index 98d3615e47..380787f8e2 100644
--- a/packages/docs-ui/src/services/doc-view-scale.ts
+++ b/packages/docs-ui/src/services/doc-view-scale.ts
@@ -17,7 +17,13 @@
import type { DocumentDataModel } from '@univerjs/core';
import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
import type { IDocFitToWidthOptions, IUniverDocsUIConfig } from '../config/config';
-import { Disposable, DocumentFlavor, IConfigService, MODERN_DOCUMENT_WIDTH, ModernDocumentWidthMode } from '@univerjs/core';
+import {
+ Disposable,
+ DocumentFlavor,
+ IConfigService,
+ MODERN_DOCUMENT_WIDTH,
+ ModernDocumentWidthMode,
+} from '@univerjs/core';
import { DEFAULT_DOC_FIT_TO_WIDTH_OPTIONS, DOCS_UI_PLUGIN_CONFIG_KEY } from '../config/config';
import { getDocEffectiveZoomRatio } from './doc-zoom';
@@ -96,7 +102,7 @@ export function resolveDocViewScale(userZoomRatio: number, fitToWidthScale: numb
export class DocViewScaleService extends Disposable implements IRenderModule {
constructor(
- private readonly _context: IRenderContext<DocumentDataModel>,
+ protected readonly _context: IRenderContext<DocumentDataModel>,
@IConfigService private readonly _configService: IConfigService
) {
super();
diff --git a/packages/docs-ui/src/services/editor/__tests__/editor-manager.service.spec.ts b/packages/docs-ui/src/services/editor/__tests__/editor-manager.service.spec.ts
index 5101544729..617f5b287d 100644
--- a/packages/docs-ui/src/services/editor/__tests__/editor-manager.service.spec.ts
+++ b/packages/docs-ui/src/services/editor/__tests__/editor-manager.service.spec.ts
@@ -603,6 +603,36 @@ describe('EditorService', () => {
expect(() => service.register({ initialSnapshot: snapshot }, document.createElement('div'))).toThrow('disposed');
});
+ it('restores the host document when a focused embedded editor is disposed', () => {
+ const { service, univerInstanceService } = createService(TestRegisterRenderManagerService);
+ const hostUnitId = EDITOR_ID;
+ const commentEditorId = `${DOCS_COMMENT_EDITOR_UNIT_ID_KEY}_comment-1`;
+ const commentSnapshot = {
+ id: commentEditorId,
+ documentStyle: {},
+ body: {
+ dataStream: 'comment\r\n',
+ paragraphs: [{ startIndex: 7, paragraphId: createParagraphId(new Set()) }],
+ },
+ };
+ univerInstanceService.__addUnit(new DocumentDataModel(commentSnapshot));
+ univerInstanceService.setCurrentUnitForType(hostUnitId);
+ const disposable = service.register({
+ initialSnapshot: commentSnapshot,
+ preserveHostFocus: true,
+ }, document.createElement('div'));
+
+ service.focus(commentEditorId);
+ expect(univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)?.getUnitId())
+ .toBe(commentEditorId);
+
+ disposable.dispose();
+
+ expect(service.getFocusId()).toBeNull();
+ expect(univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)?.getUnitId())
+ .toBe(hostUnitId);
+ });
+
it('keeps render config without an editor when no render is available and removes it on dispose', () => {
const { service } = createService(TestMissingRenderManagerService);
const disposable = service.register({
diff --git a/packages/docs-ui/src/services/editor/editor-manager.service.ts b/packages/docs-ui/src/services/editor/editor-manager.service.ts
index eaecd1da0a..51ab5b85fa 100644
--- a/packages/docs-ui/src/services/editor/editor-manager.service.ts
+++ b/packages/docs-ui/src/services/editor/editor-manager.service.ts
@@ -84,6 +84,8 @@ export class EditorService extends Disposable implements IEditorService, IDispos
private _focusEditorUnitId: Nullable<string>;
+ private _preservedHostUnitId: Nullable<string>;
+
private readonly _blur$ = new Subject();
readonly blur$ = this._blur$.asObservable();
@@ -151,6 +153,7 @@ export class EditorService extends Disposable implements IEditorService, IDispos
blur(force?: boolean) {
const focusingEditor = this.getFocusEditor();
+ const preservedHostUnitId = this._preservedHostUnitId;
if (force) {
focusingEditor?.setSelectionRanges([]);
}
@@ -160,6 +163,13 @@ export class EditorService extends Disposable implements IEditorService, IDispos
this._contextService.setContextValue(FOCUSING_EDITOR_STANDALONE, false);
this._contextService.setContextValue(FOCUSING_COMMENT_EDITOR, false);
this._setFocusId(null);
+ this._preservedHostUnitId = null;
+ if (
+ preservedHostUnitId &&
+ this._univerInstanceService.getUnit(preservedHostUnitId, UniverInstanceType.UNIVER_DOC)
+ ) {
+ this._univerInstanceService.setCurrentUnitForType(preservedHostUnitId);
+ }
this._blur$.next(null);
}
@@ -179,6 +189,13 @@ export class EditorService extends Disposable implements IEditorService, IDispos
return;
}
+ const currentDoc = this._univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(
+ UniverInstanceType.UNIVER_DOC
+ );
+ this._preservedHostUnitId = this._editorRenderConfigs.get(editorUnitId)?.preserveHostFocus &&
+ currentDoc?.getUnitId() !== editorUnitId
+ ? currentDoc?.getUnitId()
+ : null;
this._univerInstanceService.setCurrentUnitForType(editorUnitId);
const dataStream = editor.getDocumentData().body?.dataStream ?? '';
const valueCount = dataStream.replace(/\r?\n/g, '').length;
@@ -327,6 +344,9 @@ export class EditorService extends Disposable implements IEditorService, IDispos
&& this._univerInstanceService.getUnitType(focusedHostId) === UniverInstanceType.UNIVER_DOC
? focusedHostId
: null;
+ if (this._focusEditorUnitId === editorUnitId) {
+ this.blur();
+ }
this._renderManagerService.removeRender(editorUnitId);
editor.dispose();
diff --git a/packages/docs-ui/src/services/editor/editor.ts b/packages/docs-ui/src/services/editor/editor.ts
index cba2cb84c0..f3d20fe8cd 100644
--- a/packages/docs-ui/src/services/editor/editor.ts
+++ b/packages/docs-ui/src/services/editor/editor.ts
@@ -260,6 +260,13 @@ export class Editor extends Disposable implements IEditor {
this._univerInstanceService.setCurrentUnitForType(editorUnitId);
}
+ // Newly mounted inputs can receive focus before their first layout is published.
+ // Establish a logical caret without replacing an existing selection.
+ if (isInternalEditorID(editorUnitId) && this.getSelectionRanges().length === 0) {
+ const offset = Math.max(0, (this.getDocumentData().body?.dataStream.length ?? 2) - 2);
+ this.setSelectionRanges([{ startOffset: offset, endOffset: offset }], false);
+ }
+
// Step 2: Focus this input element.
const docSelectionRenderService = this._param.render.with(DocSelectionRenderService);
docSelectionRenderService.focus();
diff --git a/packages/docs-ui/src/services/float-menu.service.ts b/packages/docs-ui/src/services/float-menu.service.ts
index 80fa0525ce..e09b3f8ea3 100644
--- a/packages/docs-ui/src/services/float-menu.service.ts
+++ b/packages/docs-ui/src/services/float-menu.service.ts
@@ -31,6 +31,7 @@ import {
UniverInstanceType,
} from '@univerjs/core';
import { canEditDocumentTargets, DocSelectionManagerService, getDocumentEditTargetObjectIds } from '@univerjs/docs';
+import { IContextMenuService } from '@univerjs/ui';
import { FLOAT_MENU_COMPONENT_KEY } from '../views/float-toolbar/FloatToolbar';
import { IDocEmbedRuntimeFocusCoordinator } from './doc-embed-integration.service';
import { DocLayoutInteractionService } from './doc-layout-interaction.service';
@@ -43,7 +44,7 @@ const SKIP_SYMBOLS: string[] = [
];
export class DocFloatMenuService extends Disposable implements IRenderModule {
- private _floatMenu: Nullable<{ disposable: IDisposable; start: number; end: number; segmentId: string }> = null;
+ protected _floatMenu: Nullable<{ disposable: IDisposable; start: number; end: number; segmentId: string }> = null;
private _suppressed = false;
private _embedSuppressed = false;
private _invalidatedSelection: Nullable<string> = null;
@@ -51,10 +52,11 @@ export class DocFloatMenuService extends Disposable implements IRenderModule {
constructor(
private _context: IRenderContext<DocumentDataModel>,
@Inject(DocSelectionManagerService) private readonly _docSelectionManagerService: DocSelectionManagerService,
- @Inject(DocCanvasPopManagerService) private readonly _docCanvasPopManagerService: DocCanvasPopManagerService,
+ @Inject(DocCanvasPopManagerService) protected readonly _docCanvasPopManagerService: DocCanvasPopManagerService,
@Inject(IUniverInstanceService) private readonly _univerInstanceService: IUniverInstanceService,
@Inject(DocSelectionRenderService) private readonly _docSelectionRenderService: DocSelectionRenderService,
@IContextService private readonly _contextService: IContextService,
+ @IContextMenuService protected readonly _contextMenuService: IContextMenuService,
@IPermissionService private readonly _permissionService: IPermissionService,
@Inject(DocLayoutInteractionService) private readonly _docLayoutInteractionService: DocLayoutInteractionService,
@Optional(IDocEmbedRuntimeFocusCoordinator) private readonly _embedRuntimeFocusCoordinator?: IDocEmbedRuntimeFocusCoordinator
@@ -226,6 +228,11 @@ export class DocFloatMenuService extends Disposable implements IRenderModule {
return;
}
+ return this._openSelectionMenu(unitId, range);
+ }
+
+ protected _openSelectionMenu(unitId: string, range: ITextRangeParam): IDisposable | undefined {
+ const segmentId = range.segmentId ?? '';
const popup = this._docCanvasPopManagerService.attachPopupToRange(
range,
{
diff --git a/packages/docs-ui/src/services/mobile/doc-selection-render.service.ts b/packages/docs-ui/src/services/mobile/doc-selection-render.service.ts
new file mode 100644
index 0000000000..43b5ad73a3
--- /dev/null
+++ b/packages/docs-ui/src/services/mobile/doc-selection-render.service.ts
@@ -0,0 +1,342 @@
+/**
+ * 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 } from '@univerjs/core';
+import type { IMouseEvent, IPointerEvent, IRenderContext } from '@univerjs/engine-render';
+import type { MobileTextRangeHandleType } from './mobile-text-selection-visuals';
+import {
+ DisposableCollection,
+ IContextService,
+ ILogService,
+ Inject,
+ isInternalEditorID,
+ IUniverInstanceService,
+ Optional,
+} from '@univerjs/core';
+import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';
+import { getSystemHighlightColor, ScrollTimer } from '@univerjs/engine-render';
+import { ILayoutService } from '@univerjs/ui';
+import { BehaviorSubject, distinctUntilChanged, map } from 'rxjs';
+import { neoGetDocObject } from '../../basics/component-tools';
+import { IDocEmbedInteractionBoundaryService, IDocEmbedRuntimeFocusCoordinator } from '../doc-embed-integration.service';
+import { DocSelectionRenderService } from '../selection/doc-selection-render.service';
+import { MobileTextSelectionVisuals } from './mobile-text-selection-visuals';
+
+const MOBILE_KEYBOARD_THRESHOLD = 80;
+const MOBILE_INPUT_VIEWPORT_INSET = 1;
+
+export class MobileDocSelectionRenderService extends DocSelectionRenderService {
+ private readonly _handleDragDisposables = new DisposableCollection();
+ private readonly _selectionVisuals: MobileTextSelectionVisuals;
+ private readonly _keyboardState$ = new BehaviorSubject({ visible: false, inset: 0 });
+ private readonly _editMode$ = new BehaviorSubject(false);
+ private _viewportBaselineHeight = 0;
+ private _viewportBaselineBottom = 0;
+ private _viewportBaselineWidth = 0;
+ private _pendingBlurEvent: Event | null = null;
+ readonly mobileKeyboardState$ = this._keyboardState$.asObservable();
+ readonly mobileKeyboardVisible$ = this.mobileKeyboardState$.pipe(
+ map(({ visible }) => visible),
+ distinctUntilChanged()
+ );
+
+ readonly mobileEditMode$ = this._editMode$.asObservable();
+
+ get isMobileEditMode() {
+ return this._editMode$.value;
+ }
+
+ constructor(
+ context: IRenderContext<DocumentDataModel>,
+ @ILayoutService layoutService: ILayoutService,
+ @ILogService logService: ILogService,
+ @IContextService contextService: IContextService,
+ @IUniverInstanceService univerInstanceService: IUniverInstanceService,
+ @Inject(DocSkeletonManagerService) private readonly _mobileDocSkeletonManagerService: DocSkeletonManagerService,
+ @Inject(DocSelectionManagerService) docSelectionManagerService: DocSelectionManagerService,
+ @Optional(IDocEmbedInteractionBoundaryService) embedInteractionBoundaryService?: IDocEmbedInteractionBoundaryService,
+ @Optional(IDocEmbedRuntimeFocusCoordinator) embedRuntimeFocusCoordinator?: IDocEmbedRuntimeFocusCoordinator
+ ) {
+ super(
+ context,
+ layoutService,
+ logService,
+ contextService,
+ univerInstanceService,
+ _mobileDocSkeletonManagerService,
+ docSelectionManagerService,
+ embedInteractionBoundaryService,
+ embedRuntimeFocusCoordinator
+ );
+
+ this._selectionVisuals = new MobileTextSelectionVisuals(this._context.scene);
+ this.disposeWithMe(this.textSelectionInner$.subscribe(() => this._syncMobileSelectionVisuals()));
+ this._initMobileKeyboardViewport();
+ }
+
+ override cancelPointerSelection(): void {
+ this._handleDragDisposables.dispose();
+ super.cancelPointerSelection();
+ }
+
+ enterMobileEditMode(shouldFocusInput = false): boolean {
+ this._editMode$.next(true);
+ return shouldFocusInput ? this.enterEditing() : true;
+ }
+
+ suspendMobileEditingInput(): void {
+ this.blur();
+ }
+
+ exitMobileEditMode(): void {
+ this._editMode$.next(false);
+ this.exitEditing();
+ }
+
+ override refreshRanges(): void {
+ super.refreshRanges();
+ this._syncMobileSelectionVisuals();
+ }
+
+ protected override _positionInput(_x: number, _y: number) {
+ // Keep the hidden editor inside the Portal subtree when possible to avoid focus-trap loops,
+ // then compensate coordinates if a transformed ancestor changes the fixed containing block.
+ this._ensureHostContainer();
+ this._container.style.position = 'fixed';
+ const visualViewport = typeof window === 'undefined' ? null : window.visualViewport;
+ let left = MOBILE_INPUT_VIEWPORT_INSET;
+ let top = MOBILE_INPUT_VIEWPORT_INSET;
+ const fixedContainer = this._container.offsetParent;
+ if (fixedContainer) {
+ const rect = fixedContainer.getBoundingClientRect();
+ left -= rect.left;
+ top -= rect.top;
+ } else {
+ left += visualViewport?.offsetLeft ?? 0;
+ top += visualViewport?.offsetTop ?? 0;
+ }
+
+ this._container.style.left = `${left}px`;
+ this._container.style.top = `${top}px`;
+ this._container.style.zIndex = '1000';
+ }
+
+ private _syncMobileSelectionVisuals(): void {
+ const activeRange = this._getActiveRangeInstance();
+ this._selectionVisuals.hide();
+ for (const range of this._rangeList) {
+ const caret = range.getAnchor();
+ if (this.isEditing && range === activeRange) {
+ caret?.show();
+ } else {
+ caret?.hide();
+ }
+ }
+
+ if (!activeRange || activeRange.collapsed || this.isEditing) {
+ return;
+ }
+
+ const { document } = neoGetDocObject(this._context);
+ if (!document) {
+ return;
+ }
+
+ const { r, g, b } = getSystemHighlightColor();
+ this._selectionVisuals.show(
+ activeRange,
+ document,
+ this._mobileDocSkeletonManagerService.getSkeleton(),
+ `rgb(${r}, ${g}, ${b})`,
+ (handle, event) => this._startSelectionHandleDrag(handle, event)
+ );
+ }
+
+ private _initMobileKeyboardViewport(): void {
+ if (
+ typeof window === 'undefined' ||
+ !window.visualViewport
+ ) {
+ return;
+ }
+
+ const visualViewport = window.visualViewport;
+ this._viewportBaselineHeight = visualViewport.height;
+ this._viewportBaselineBottom = visualViewport.offsetTop + visualViewport.height;
+ this._viewportBaselineWidth = visualViewport.width;
+ const update = () => this._updateMobileKeyboardState(visualViewport);
+ visualViewport.addEventListener('resize', update);
+ visualViewport.addEventListener('scroll', update);
+ this.disposeWithMe({
+ dispose: () => {
+ visualViewport.removeEventListener('resize', update);
+ visualViewport.removeEventListener('scroll', update);
+ },
+ });
+ }
+
+ protected override _updateInputPosition({ forceFocus = false, preserveFocus = false } = {}): void {
+ if (!forceFocus && !isInternalEditorID(this._context.unitId)) {
+ // Formatting may refresh selection without reopening the software keyboard.
+ this._positionInput(0, 0);
+ return;
+ }
+ super._updateInputPosition({ forceFocus, preserveFocus });
+ }
+
+ protected override _handleInputBlur(event: Event): void {
+ if (this.isEditing) {
+ this._pendingBlurEvent = event;
+ return;
+ }
+ super._handleInputBlur(event);
+ }
+
+ protected override _handleInputFocus(event: Event): void {
+ this._pendingBlurEvent = null;
+ super._handleInputFocus(event);
+ }
+
+ protected override _setEditing(isEditing: boolean): void {
+ if (!isEditing) {
+ this._setMobileKeyboardState(false, 0);
+ this._pendingBlurEvent = null;
+ }
+ super._setEditing(isEditing);
+ }
+
+ private _startSelectionHandleDrag(
+ handle: MobileTextRangeHandleType,
+ event: IPointerEvent | IMouseEvent
+ ): void {
+ this._handleDragDisposables.dispose();
+ const activeRange = this._getActiveRangeInstance();
+ const anchor = handle === 'start' ? activeRange?.endNodePosition : activeRange?.startNodePosition;
+ if (!activeRange || activeRange.collapsed || !anchor) {
+ return;
+ }
+
+ const { scene } = this._context;
+ const scrollTimer = ScrollTimer.create(scene);
+ let moved = false;
+ let previousX = event.offsetX;
+ let previousY = event.offsetY;
+
+ this._anchorNodePosition = { ...anchor };
+ this._focusNodePosition = null;
+ this._removeAllCacheRanges();
+ this._selectionVisuals.hide();
+ scene.disableObjectsEvent();
+ this._onPointerEvent = true;
+ scrollTimer.startScroll(event.offsetX, event.offsetY);
+ this._handleDragDisposables.add(() => {
+ scrollTimer.dispose();
+ this._onPointerEvent = false;
+ scene.enableObjectsEvent();
+ });
+
+ this._handleDragDisposables.add(scene.onPointerMove$.subscribeEvent((moveEvent: IPointerEvent | IMouseEvent) => {
+ const distance = Math.hypot(moveEvent.offsetX - previousX, moveEvent.offsetY - previousY);
+ if (distance < 2) {
+ return;
+ }
+
+ moved = true;
+ this._tryMoving(moveEvent.offsetX, moveEvent.offsetY);
+ scrollTimer.scrolling(moveEvent.offsetX, moveEvent.offsetY, () => {
+ this._tryMoving(moveEvent.offsetX, moveEvent.offsetY);
+ });
+ previousX = moveEvent.offsetX;
+ previousY = moveEvent.offsetY;
+ }));
+ const finishDrag = () => {
+ this._handleDragDisposables.dispose();
+
+ if (moved && (this._rangeListCache.length || this._rectRangeListCache.length)) {
+ for (const textRange of this._rangeListCache) {
+ this._addTextRange(textRange);
+ }
+ this._addRectRanges(this._rectRangeListCache);
+ this._rangeListCache = [];
+ this._rectRangeListCache = [];
+ } else {
+ this._removeAllCacheRanges();
+ }
+
+ this._anchorNodePosition = null;
+ this._focusNodePosition = null;
+ this._emitCurrentSelection(false);
+ };
+ this._handleDragDisposables.add(scene.onPointerUp$.subscribeEvent(finishDrag));
+ this._handleDragDisposables.add(scene.onPointerCancel$.subscribeEvent(finishDrag));
+ }
+
+ private _updateMobileKeyboardState(visualViewport: VisualViewport): void {
+ const visibleBottom = visualViewport.offsetTop + visualViewport.height;
+ if (Math.abs(this._viewportBaselineWidth - visualViewport.width) > 1) {
+ this._viewportBaselineHeight = visualViewport.height;
+ this._viewportBaselineBottom = visibleBottom;
+ this._viewportBaselineWidth = visualViewport.width;
+ }
+
+ const keyboardVisible = this._viewportBaselineHeight - visualViewport.height >= MOBILE_KEYBOARD_THRESHOLD;
+ if (!keyboardVisible) {
+ this._viewportBaselineHeight = Math.max(this._viewportBaselineHeight, visualViewport.height);
+ this._viewportBaselineBottom = Math.max(this._viewportBaselineBottom, visibleBottom);
+ }
+
+ if (!this.isMobileEditMode) {
+ this._setMobileKeyboardState(false, 0);
+ return;
+ }
+
+ if (keyboardVisible) {
+ this._setMobileKeyboardState(
+ true,
+ Math.max(0, Math.round(this._viewportBaselineBottom - visibleBottom))
+ );
+ return;
+ }
+
+ if (!this._keyboardState$.value.visible) {
+ return;
+ }
+
+ this._setMobileKeyboardState(false, 0);
+ const blurEvent = this._pendingBlurEvent;
+ this._pendingBlurEvent = null;
+ if (blurEvent) {
+ this._emitInputBlur(blurEvent);
+ }
+ }
+
+ private _setMobileKeyboardState(visible: boolean, inset: number): void {
+ const current = this._keyboardState$.value;
+ if (current.visible === visible && current.inset === inset) {
+ return;
+ }
+
+ this._keyboardState$.next({ visible, inset });
+ }
+
+ override dispose(): void {
+ this._handleDragDisposables.dispose();
+ this._selectionVisuals.dispose();
+ this._keyboardState$.complete();
+ this._editMode$.complete();
+ super.dispose();
+ }
+}
diff --git a/packages/docs-ui/src/services/mobile/doc-view-scale.ts b/packages/docs-ui/src/services/mobile/doc-view-scale.ts
new file mode 100644
index 0000000000..cc0a5c1ffc
--- /dev/null
+++ b/packages/docs-ui/src/services/mobile/doc-view-scale.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 { DocumentFlavor, isInternalEditorID } from '@univerjs/core';
+import { DocViewScaleService } from '../doc-view-scale';
+
+export class MobileDocViewScaleService extends DocViewScaleService {
+ override getFitToWidthScale(): number {
+ if (isInternalEditorID(this._context.unitId) ||
+ this._context.unit.getSnapshot().documentStyle.documentFlavor === DocumentFlavor.MODERN) {
+ return 1;
+ }
+ return super.getFitToWidthScale();
+ }
+}
diff --git a/packages/docs-ui/src/services/mobile/float-menu.service.ts b/packages/docs-ui/src/services/mobile/float-menu.service.ts
new file mode 100644
index 0000000000..bb027d0a6f
--- /dev/null
+++ b/packages/docs-ui/src/services/mobile/float-menu.service.ts
@@ -0,0 +1,41 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ITextRangeParam } from '@univerjs/core';
+import { toDisposable } from '@univerjs/core';
+import { ContextMenuPosition } from '@univerjs/ui';
+import { DocFloatMenuService } from '../float-menu.service';
+
+export class MobileDocFloatMenuService extends DocFloatMenuService {
+ protected override _openSelectionMenu(unitId: string, range: ITextRangeParam) {
+ const [anchor] = this._docCanvasPopManagerService.getRangeBounds(range, unitId) ?? [];
+ if (!anchor) {
+ return;
+ }
+ this._contextMenuService.triggerContextMenu({
+ clientX: (anchor.left + anchor.right) / 2,
+ clientY: anchor.top,
+ stopPropagation() {},
+ }, ContextMenuPosition.MAIN_AREA, { unitId, subUnitId: unitId });
+ this._floatMenu = {
+ disposable: toDisposable(() => this._contextMenuService.hideContextMenu()),
+ start: range.startOffset,
+ end: range.endOffset,
+ segmentId: range.segmentId ?? '',
+ };
+ return undefined;
+ }
+}
diff --git a/packages/docs-ui/src/services/mobile/mobile-text-selection-visuals.ts b/packages/docs-ui/src/services/mobile/mobile-text-selection-visuals.ts
new file mode 100644
index 0000000000..24f06177a0
--- /dev/null
+++ b/packages/docs-ui/src/services/mobile/mobile-text-selection-visuals.ts
@@ -0,0 +1,209 @@
+/**
+ * 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 type {
+ Documents,
+ DocumentSkeleton,
+ IMouseEvent,
+ INodePosition,
+ IPointerEvent,
+ Scene,
+} from '@univerjs/engine-render';
+import type { TextRange } from '../selection/text-range';
+import { generateRandomId } from '@univerjs/core';
+import { Rect } from '@univerjs/engine-render';
+import { NodePositionConvertToCursor } from '../selection/convert-text-range';
+import { getAnchorBounding, TEXT_RANGE_LAYER_INDEX } from '../selection/text-range';
+
+const MOBILE_HANDLE_TOUCH_SIZE = 32;
+const MOBILE_HANDLE_VISUAL_SIZE = 12;
+const MOBILE_HANDLE_STEM_WIDTH = 2;
+const ID_LENGTH = 6;
+const MOBILE_HANDLE_KEY_PREFIX = '__MobileTextSelectionHandle__';
+
+export type MobileTextRangeHandleType = 'start' | 'end';
+
+export class MobileTextSelectionVisuals {
+ private _startHandleShape: Nullable<Rect>;
+ private _endHandleShape: Nullable<Rect>;
+ private _startHandleStemShape: Nullable<Rect>;
+ private _endHandleStemShape: Nullable<Rect>;
+ private _onPointerDown: Nullable<(
+ handle: MobileTextRangeHandleType,
+ event: IPointerEvent | IMouseEvent
+ ) => void>;
+
+ constructor(private readonly _scene: Scene) {}
+
+ show(
+ range: TextRange,
+ document: Documents,
+ docSkeleton: DocumentSkeleton,
+ color: string,
+ onPointerDown: (handle: MobileTextRangeHandleType, event: IPointerEvent | IMouseEvent) => void
+ ): void {
+ this._onPointerDown = onPointerDown;
+ this._createShapes(color);
+ if (range.collapsed) {
+ this.hide();
+ return;
+ }
+
+ const start = this._getNodeCaretBounding(range.startNodePosition, document, docSkeleton);
+ const end = this._getNodeCaretBounding(range.endNodePosition, document, docSkeleton);
+ if (
+ !start ||
+ !end ||
+ !this._startHandleShape ||
+ !this._endHandleShape ||
+ !this._startHandleStemShape ||
+ !this._endHandleStemShape
+ ) {
+ this.hide();
+ return;
+ }
+
+ const { scaleX, scaleY } = this._scene.getAncestorScale();
+ const scale = Math.max(scaleX, scaleY, 0.01);
+ const touchSize = MOBILE_HANDLE_TOUCH_SIZE / scale;
+ const visualSize = MOBILE_HANDLE_VISUAL_SIZE / scale;
+ const stemWidth = MOBILE_HANDLE_STEM_WIDTH / scale;
+ const placeHandle = (
+ shape: Rect,
+ stem: Rect,
+ bounding: NonNullable<ReturnType<MobileTextSelectionVisuals['_getNodeCaretBounding']>>,
+ edge: MobileTextRangeHandleType
+ ) => {
+ const handleTop = edge === 'start'
+ ? bounding.top - touchSize / 2
+ : bounding.top + bounding.height - touchSize / 2;
+ stem.transformByState({
+ left: bounding.left - stemWidth / 2,
+ top: bounding.top,
+ width: stemWidth,
+ height: bounding.height,
+ });
+ shape.setProps({
+ radius: visualSize / 2,
+ visualWidth: visualSize,
+ visualHeight: visualSize,
+ });
+ shape.transformByState({
+ left: bounding.left - touchSize / 2,
+ top: handleTop,
+ width: touchSize,
+ height: touchSize,
+ });
+ stem.show();
+ shape.show();
+ };
+
+ placeHandle(this._startHandleShape, this._startHandleStemShape, start, 'start');
+ placeHandle(this._endHandleShape, this._endHandleStemShape, end, 'end');
+ }
+
+ hide(): void {
+ this._startHandleShape?.hide();
+ this._endHandleShape?.hide();
+ this._startHandleStemShape?.hide();
+ this._endHandleStemShape?.hide();
+ }
+
+ dispose(): void {
+ this._startHandleShape?.dispose();
+ this._startHandleShape = null;
+ this._endHandleShape?.dispose();
+ this._endHandleShape = null;
+ this._startHandleStemShape?.dispose();
+ this._startHandleStemShape = null;
+ this._endHandleStemShape?.dispose();
+ this._endHandleStemShape = null;
+ this._onPointerDown = null;
+ }
+
+ private _createShapes(color: string): void {
+ if (
+ this._startHandleShape &&
+ this._endHandleShape &&
+ this._startHandleStemShape &&
+ this._endHandleStemShape
+ ) {
+ this._startHandleShape.setProps({ fill: color });
+ this._endHandleShape.setProps({ fill: color });
+ this._startHandleStemShape.setProps({ fill: color });
+ this._endHandleStemShape.setProps({ fill: color });
+ return;
+ }
+
+ const createStem = () => {
+ const shape = new Rect(`${MOBILE_HANDLE_KEY_PREFIX}Stem${generateRandomId(ID_LENGTH)}`, {
+ fill: color,
+ evented: false,
+ debounceParentDirty: false,
+ });
+ this._scene.addObject(shape, TEXT_RANGE_LAYER_INDEX + 1);
+ return shape;
+ };
+ const createHandle = (handle: MobileTextRangeHandleType) => {
+ const shape = new Rect(`${MOBILE_HANDLE_KEY_PREFIX}${generateRandomId(ID_LENGTH)}`, {
+ width: MOBILE_HANDLE_TOUCH_SIZE,
+ height: MOBILE_HANDLE_TOUCH_SIZE,
+ radius: MOBILE_HANDLE_VISUAL_SIZE / 2,
+ visualWidth: MOBILE_HANDLE_VISUAL_SIZE,
+ visualHeight: MOBILE_HANDLE_VISUAL_SIZE,
+ fill: color,
+ evented: true,
+ debounceParentDirty: false,
+ });
+ shape.onPointerDown$.subscribeEvent((event, state) => {
+ state.stopPropagation();
+ this._onPointerDown?.(handle, event);
+ });
+ this._scene.addObject(shape, TEXT_RANGE_LAYER_INDEX + 1);
+ return shape;
+ };
+
+ this._startHandleStemShape = createStem();
+ this._endHandleStemShape = createStem();
+ this._startHandleShape = createHandle('start');
+ this._endHandleShape = createHandle('end');
+ }
+
+ private _getNodeCaretBounding(
+ position: Nullable<INodePosition>,
+ document: Documents,
+ docSkeleton: DocumentSkeleton
+ ) {
+ if (!position) {
+ return;
+ }
+
+ const { docsLeft, docsTop } = document.getOffsetConfig();
+ const convertor = new NodePositionConvertToCursor(document.getOffsetConfig(), docSkeleton);
+ const { contentBoxPointGroup } = convertor.getRangePointData(position, position);
+ if (contentBoxPointGroup.length === 0) {
+ return;
+ }
+
+ const bounding = getAnchorBounding(contentBoxPointGroup);
+ return {
+ ...bounding,
+ left: bounding.left + docsLeft,
+ top: bounding.top + docsTop,
+ };
+ }
+}
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 6736ff0fdf..f24ca2ed27 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
@@ -20,15 +20,17 @@ import type { IDisposable, IDocumentData, ITextRangeParam } from '@univerjs/core
import type { Mock } from 'vitest';
import {
DataStreamTreeTokenType,
+ DisposableCollection,
DOC_RANGE_TYPE,
DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
DocumentDataModel,
DocumentFlavor,
+ EventSubject,
Univer,
UniverInstanceType,
} from '@univerjs/core';
import { DocLayoutExecutorService, DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';
-import { GlyphType, NORMAL_TEXT_SELECTION_PLUGIN_STYLE, RenderUnit } from '@univerjs/engine-render';
+import { DeviceType, GlyphType, NORMAL_TEXT_SELECTION_PLUGIN_STYLE, PointerInput, RenderUnit } from '@univerjs/engine-render';
import { ILayoutService } from '@univerjs/ui';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
@@ -36,6 +38,7 @@ import {
EmbedInteractionBoundaryService,
EmbedRuntimeFocusCoordinator,
} from '../../doc-embed-integration.service';
+import { MobileDocSelectionRenderService } from '../../mobile/doc-selection-render.service';
import { DocSelectionRenderService } from '../doc-selection-render.service';
import { TextRange } from '../text-range';
@@ -46,6 +49,7 @@ const {
getRangeListFromSelectionMock,
getRectRangeFromCharIndexMock,
getTextRangeFromCharIndexMock,
+ mobileSelectionVisualsMock,
} = vi.hoisted(() => ({
cursorConvertToTextRangeMock: vi.fn(),
getCanvasOffsetByEngineMock: vi.fn(),
@@ -53,6 +57,19 @@ const {
getRangeListFromSelectionMock: vi.fn(),
getRectRangeFromCharIndexMock: vi.fn(),
getTextRangeFromCharIndexMock: vi.fn(),
+ mobileSelectionVisualsMock: {
+ dispose: vi.fn(),
+ hide: vi.fn(),
+ show: vi.fn(),
+ },
+}));
+
+vi.mock('../../mobile/mobile-text-selection-visuals', () => ({
+ MobileTextSelectionVisuals: class {
+ dispose = mobileSelectionVisualsMock.dispose;
+ hide = mobileSelectionVisualsMock.hide;
+ show = mobileSelectionVisualsMock.show;
+ },
}));
vi.mock('../selection-utils', async () => {
@@ -79,13 +96,22 @@ vi.mock('../text-range', async () => {
type VoidMock = Mock<() => void>;
type BooleanMock = Mock<() => boolean>;
-type AnchorMock = Mock<() => { left: number; top: number; visible: boolean } | null>;
+interface IFakeAnchor {
+ hide: VoidMock;
+ left: number;
+ show: VoidMock;
+ top: number;
+ visible: boolean;
+}
+
+type AnchorMock = Mock<() => IFakeAnchor | null>;
type IntersectionMock = Mock<(range: unknown) => boolean>;
interface IFakeTextRange {
activate: VoidMock;
deactivate: VoidMock;
dispose: VoidMock;
+ refresh: VoidMock;
getAnchor: AnchorMock;
isActive: BooleanMock;
isIntersection: IntersectionMock;
@@ -118,7 +144,8 @@ interface IServiceHarness {
_scenePointerUpSubs: Array<{ unsubscribe: VoidMock }>;
_scrollTimers: Array<{ dispose: VoidMock }>;
_selectionStyle: { strokeWidth: number };
- _textSelectionInner$: { next: Mock<(...args: unknown[]) => void> };
+ _textSelectionInner$: { next: Mock<(...args: unknown[]) => void>; value: { isEditing: boolean } | null };
+ _contextService: { getContextValue: Mock<() => boolean> };
focus: Mock<() => void>;
_getAllTextRanges: Mock<() => string[]>;
_getAllRectRanges: Mock<() => string[]>;
@@ -139,6 +166,7 @@ interface IServiceHarness {
_moving(moveOffsetX: number, moveOffsetY: number): void;
_isAnotherEditorFocused: Mock<() => boolean>;
_updateInputPosition(): void;
+ refreshRanges(): void;
addDocRanges(ranges: Array<Record<string, unknown>>, isEditing?: boolean, options?: Record<string, boolean>): void;
cancelPointerSelection(): void;
replaceDocRanges(ranges: Array<Record<string, unknown>>, isEditing?: boolean, options?: Record<string, boolean>): boolean;
@@ -146,11 +174,13 @@ interface IServiceHarness {
}
function createTextRange(overrides: Partial<IFakeTextRange> = {}): IFakeTextRange {
+ const anchor = { hide: vi.fn(), left: 12, show: vi.fn(), top: 34, visible: true };
return {
activate: vi.fn(),
deactivate: vi.fn(),
dispose: vi.fn(),
- getAnchor: vi.fn(() => ({ left: 12, top: 34, visible: true })),
+ refresh: vi.fn(),
+ getAnchor: vi.fn(() => anchor),
isActive: vi.fn(() => false),
isIntersection: vi.fn(() => false),
collapsed: false,
@@ -189,6 +219,8 @@ function createService() {
_scrollTimers: [],
_onPointerEvent: false,
_selectionStyle: { strokeWidth: 1 },
+ _mobileSelectionHandleColor: '#0f6bdc',
+ _mobileHandleDragDisposables: new DisposableCollection(),
_currentSegmentId: 'segment-1',
_currentSegmentPage: 2,
_context: {
@@ -203,11 +235,15 @@ function createService() {
_docSkeletonManagerService: {
getSkeleton: vi.fn(() => skeleton),
},
+ _contextService: {
+ getContextValue: vi.fn(() => false),
+ },
_logService: {
error: vi.fn(),
},
_textSelectionInner$: {
next: vi.fn(),
+ value: { isEditing: false },
},
_getAllTextRanges: vi.fn(() => ['serialized-text']),
_getAllRectRanges: vi.fn(() => ['serialized-rect']),
@@ -313,7 +349,9 @@ function createRealSelectionRenderService(options: {
embedInteractionBoundaryService?: Partial<EmbedInteractionBoundaryService>;
embedRuntimeFocusCoordinator?: EmbedRuntimeFocusCoordinator;
mainComponent?: unknown;
+ mobile?: boolean;
scene?: unknown;
+ unitId?: string;
} = {}) {
TestLayoutService.reset();
TestDocSkeletonManagerService.reset();
@@ -328,7 +366,7 @@ function createRealSelectionRenderService(options: {
injector.add([EmbedRuntimeFocusCoordinator, { useValue: options.embedRuntimeFocusCoordinator }]);
}
const documentData: IDocumentData = options.documentData ?? {
- id: 'selection-render-doc',
+ id: options.unitId ?? 'selection-render-doc',
body: {
dataStream: 'Hello\r\n',
paragraphs: [{ paragraphId: 'para_docs_ui_selection_fixture_1', startIndex: 5 }],
@@ -351,11 +389,11 @@ function createRealSelectionRenderService(options: {
}
renderUnit.addRenderDependencies([
[DocSkeletonManagerService, { useClass: TestDocSkeletonManagerService as never }],
- DocSelectionRenderService,
+ [DocSelectionRenderService, { useClass: options.mobile ? MobileDocSelectionRenderService : DocSelectionRenderService }],
] as never);
return {
- input: document.getElementById('__editor_selection-render-doc') as HTMLDivElement,
+ input: document.getElementById(`__editor_${documentData.id}`) as HTMLDivElement,
renderUnit,
service: renderUnit.with(DocSelectionRenderService),
univer,
@@ -1427,6 +1465,131 @@ describe('DocSelectionRenderService', () => {
expect(received).toEqual([{ start: 1, end: 3 }]);
});
+ it.each([
+ { mobile: false, unitId: 'selection-render-doc' },
+ { mobile: true, unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY },
+ ])('preserves automatic input focus outside mobile standalone docs ($mobile, $unitId)', (options) => {
+ const { input, renderUnit, service, univer } = createRealSelectionRenderService(options);
+ cleanup.push(() => renderUnit.dispose(), () => univer.dispose());
+ const focus = vi.spyOn(input, 'focus');
+ cleanup.push(() => focus.mockRestore());
+
+ service.sync();
+
+ expect(focus).toHaveBeenCalledOnce();
+ expect(service.isFocusing).toBe(true);
+ });
+
+ it('does not reopen the mobile keyboard when formatting refreshes a blurred selection', () => {
+ const { input, renderUnit, service: selectionService, univer } = createRealSelectionRenderService({ mobile: true });
+ const service = selectionService as MobileDocSelectionRenderService;
+ cleanup.push(() => renderUnit.dispose(), () => univer.dispose());
+ service.enterMobileEditMode();
+ service.focus();
+ service.suspendMobileEditingInput();
+ const focus = vi.spyOn(input, 'focus');
+ cleanup.push(() => focus.mockRestore());
+
+ for (let cycle = 0; cycle < 5; cycle++) {
+ service.replaceDocRanges([], true);
+ service.sync();
+ }
+
+ expect(focus).not.toHaveBeenCalled();
+ expect(service.isMobileEditMode).toBe(true);
+ expect(service.isFocusing).toBe(false);
+
+ service.activate(0, 0, true);
+ expect(focus).toHaveBeenCalledOnce();
+ expect(service.isFocusing).toBe(true);
+ focus.mockClear();
+ service.sync();
+ expect(service.isFocusing).toBe(true);
+ expect(focus).not.toHaveBeenCalled();
+ });
+
+ it('keeps mobile edit mode active without closing a newly focused keyboard', () => {
+ const originalVisualViewport = window.visualViewport;
+ const viewportTarget = new EventTarget();
+ const visualViewport = Object.assign(viewportTarget, {
+ height: 900,
+ offsetTop: 0,
+ offsetLeft: 0,
+ width: 430,
+ });
+ Object.defineProperty(window, 'visualViewport', {
+ configurable: true,
+ value: visualViewport,
+ });
+ cleanup.push(() => Object.defineProperty(window, 'visualViewport', {
+ configurable: true,
+ value: originalVisualViewport,
+ }));
+
+ const { renderUnit, service: selectionService, univer } = createRealSelectionRenderService({
+ mobile: true,
+ });
+ const service = selectionService as MobileDocSelectionRenderService;
+ cleanup.push(() => renderUnit.dispose(), () => univer.dispose());
+ const blurEvents: Event[] = [];
+ const keyboardVisibility: boolean[] = [];
+ const blurSubscription = service.onBlur$.subscribe((config) => blurEvents.push(config.event));
+ const keyboardSubscription = service.mobileKeyboardVisible$.subscribe((visible) => keyboardVisibility.push(visible));
+ cleanup.push(() => blurSubscription.unsubscribe(), () => keyboardSubscription.unsubscribe());
+
+ service.replaceDocRanges([], true);
+ service.enterMobileEditMode();
+ service.focus();
+ visualViewport.height = 500;
+ viewportTarget.dispatchEvent(new Event('resize'));
+ service.suspendMobileEditingInput();
+
+ expect(service.isEditing).toBe(true);
+ expect(blurEvents).toEqual([]);
+ expect(keyboardVisibility).toEqual([false, true]);
+
+ visualViewport.height = 900;
+ viewportTarget.dispatchEvent(new Event('resize'));
+
+ expect(service.isEditing).toBe(true);
+ expect(service.isMobileEditMode).toBe(true);
+ expect(blurEvents).toHaveLength(1);
+ expect(keyboardVisibility).toEqual([false, true, false]);
+
+ for (let cycle = 0; cycle < 5; cycle++) {
+ service.focus();
+ visualViewport.height = 500;
+ visualViewport.offsetTop = cycle % 2 === 0 ? 0 : 100;
+ viewportTarget.dispatchEvent(new Event('resize'));
+ visualViewport.height = cycle % 2 === 0 ? 880 : 900;
+ visualViewport.offsetTop = 0;
+ viewportTarget.dispatchEvent(new Event('resize'));
+ }
+
+ expect(service.isFocusing).toBe(true);
+ expect(blurEvents).toHaveLength(1);
+ expect(keyboardVisibility).toEqual([
+ false,
+ true,
+ false,
+ true,
+ false,
+ true,
+ false,
+ true,
+ false,
+ true,
+ false,
+ true,
+ false,
+ ]);
+
+ service.exitMobileEditMode();
+
+ expect(service.isEditing).toBe(false);
+ expect(service.isMobileEditMode).toBe(false);
+ });
+
it('does not publish host hidden editor events while a child session owns the host document', () => {
const focusCoordinator = new EmbedRuntimeFocusCoordinator();
const { input, renderUnit, service, univer } = createRealSelectionRenderService({
@@ -1531,11 +1694,14 @@ describe('DocSelectionRenderService', () => {
input.textContent = '拼';
input.dispatchEvent(new CompositionEvent('compositionstart', { bubbles: true, data: '拼' }));
+ expect(input.textContent).toBe('拼');
input.textContent = 'pin';
input.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'p' }));
input.dispatchEvent(new CompositionEvent('compositionupdate', { bubbles: true, data: '拼' }));
+ expect(input.textContent).toBe('pin');
input.textContent = '拼';
input.dispatchEvent(new CompositionEvent('compositionend', { bubbles: true, data: '拼' }));
+ expect(input.textContent).toBe('');
input.textContent = 'done';
input.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Enter' }));
@@ -1737,6 +1903,82 @@ describe('DocSelectionRenderService', () => {
expect(container.style.top).toBe('-153px');
});
+ it('parks the mobile hidden editor inside the visual viewport instead of moving it to the canvas caret', () => {
+ const originalVisualViewport = window.visualViewport;
+ const viewportEvents = new EventTarget();
+ Object.defineProperty(window, 'visualViewport', {
+ configurable: true,
+ value: {
+ addEventListener: viewportEvents.addEventListener.bind(viewportEvents),
+ removeEventListener: viewportEvents.removeEventListener.bind(viewportEvents),
+ height: 700,
+ width: 430,
+ offsetLeft: 5,
+ offsetTop: 120,
+ },
+ });
+ const { renderUnit, service, univer } = createRealSelectionRenderService({ mobile: true });
+ cleanup.push(
+ () => Object.defineProperty(window, 'visualViewport', {
+ configurable: true,
+ value: originalVisualViewport,
+ }),
+ () => renderUnit.dispose(),
+ () => univer.dispose()
+ );
+
+ service.activate(350, 470);
+
+ const container = document.getElementById('univer-doc-selection-container-selection-render-doc')!;
+ expect(container.style.left).toBe('6px');
+ expect(container.style.top).toBe('121px');
+ });
+
+ it('does not apply the visual viewport offset twice inside a fixed containing block', () => {
+ const originalVisualViewport = window.visualViewport;
+ const viewportEvents = new EventTarget();
+ const visualViewport = Object.assign(viewportEvents, {
+ height: 900,
+ width: 430,
+ offsetLeft: 0,
+ offsetTop: 0,
+ });
+ Object.defineProperty(window, 'visualViewport', {
+ configurable: true,
+ value: visualViewport,
+ });
+ const { renderUnit, service, univer } = createRealSelectionRenderService({ mobile: true });
+ cleanup.push(
+ () => Object.defineProperty(window, 'visualViewport', {
+ configurable: true,
+ value: originalVisualViewport,
+ }),
+ () => renderUnit.dispose(),
+ () => univer.dispose()
+ );
+ const container = document.getElementById('univer-doc-selection-container-selection-render-doc')!;
+ vi.spyOn(container, 'offsetParent', 'get').mockReturnValue(TestLayoutService.root);
+ vi.spyOn(TestLayoutService.root, 'getBoundingClientRect').mockImplementation(() => ({
+ left: 0,
+ top: -visualViewport.offsetTop,
+ } as DOMRect));
+
+ for (let cycle = 0; cycle < 5; cycle++) {
+ visualViewport.height = 500;
+ visualViewport.offsetTop = 120;
+ viewportEvents.dispatchEvent(new Event('resize'));
+ service.activate(350, 470);
+ expect(container.style.left).toBe('1px');
+ expect(container.style.top).toBe('121px');
+
+ visualViewport.height = 900;
+ visualViewport.offsetTop = 0;
+ viewportEvents.dispatchEvent(new Event('resize'));
+ service.activate(350, 470);
+ expect(container.style.top).toBe('1px');
+ }
+ });
+
it.each(['editor', 'button', 'input'] as const)('updates the caret position after scrolling without moving focus from the %s', (target) => {
getCanvasOffsetByEngineMock.mockReturnValue({ left: 1, top: 2 });
const scrollAfter$ = new TestRenderEvent<{ viewport: unknown }>();
@@ -1871,7 +2113,8 @@ describe('DocSelectionRenderService', () => {
});
cleanup.push(() => subscription.unsubscribe());
- service.__onPointDown({ offsetX: 10, offsetY: 10, button: 0 } as never);
+ service.blur();
+ service.__onPointDown({ offsetX: 10, offsetY: 10, button: 0 } as never, false);
pointerMove$.emit({ offsetX: 20, offsetY: 20 });
pointerUp$.emit({});
@@ -1880,6 +2123,76 @@ describe('DocSelectionRenderService', () => {
expect(clearSelectedObjects).toHaveBeenCalledTimes(1);
expect(setCursor).toHaveBeenCalledWith('text');
expect(selections.at(-1)).toBe('2:6');
+ expect(service.isFocusing).toBe(false);
+ });
+
+ it.each(['cancel', 'dispose'])('releases mobile handle events and scroll ownership on %s', (reason) => {
+ const pointerMove$ = new EventSubject<MouseEvent>();
+ const pointerUp$ = new EventSubject<MouseEvent>();
+ const pointerCancel$ = new EventSubject<MouseEvent>();
+ const enableObjectsEvent = vi.fn();
+ const scene = {
+ getViewports: () => [],
+ getEngine: () => null,
+ findViewportByPosToScene: () => null,
+ disableObjectsEvent: vi.fn(),
+ enableObjectsEvent,
+ onPointerMove$: pointerMove$,
+ onPointerUp$: pointerUp$,
+ onPointerCancel$: pointerCancel$,
+ };
+ const { renderUnit, service, univer } = createRealSelectionRenderService({ mainComponent: {}, scene, mobile: true });
+ cleanup.push(() => renderUnit.dispose(), () => univer.dispose());
+ const node = { page: 0, section: 0, column: 0, line: 0, divide: 0, glyph: 0, isBack: true };
+ const range = {
+ ...createTextRange({ isActive: vi.fn(() => true) }),
+ startOffset: 0,
+ endOffset: 3,
+ startNodePosition: node,
+ endNodePosition: { ...node, glyph: 3 },
+ };
+ getRangeListFromCharIndexMock.mockReturnValue({ textRanges: [range], rectRanges: [] });
+ service.addDocRanges([{ startOffset: 0, endOffset: 3 }], false, { shouldFocus: false });
+ const handlePointerDown = mobileSelectionVisualsMock.show.mock.calls[0]?.[4];
+ if (!handlePointerDown) {
+ throw new Error('The mobile selection did not expose its handles');
+ }
+ const event = Object.assign(new MouseEvent('pointerdown', { clientX: 10, clientY: 10 }), {
+ deviceType: DeviceType.Touch,
+ inputIndex: PointerInput.LeftClick,
+ currentState: null,
+ previousState: null,
+ });
+ handlePointerDown('end', event);
+ expect(scene.disableObjectsEvent).toHaveBeenCalledOnce();
+ expect(pointerMove$.observed).toBe(true);
+ if (reason === 'cancel') {
+ pointerCancel$.emitEvent(event);
+ expect(mobileSelectionVisualsMock.show).toHaveBeenCalledTimes(2);
+ } else {
+ renderUnit.dispose();
+ }
+ expect(enableObjectsEvent).toHaveBeenCalledOnce();
+ expect(pointerMove$.observed).toBe(false);
+ expect(pointerUp$.observed).toBe(false);
+ expect(pointerCancel$.observed).toBe(false);
+ });
+
+ it('shows mobile range controls only for the active non-editing selection', () => {
+ const { service, renderUnit, univer } = createRealSelectionRenderService({ mainComponent: {}, mobile: true });
+ cleanup.push(() => renderUnit.dispose(), () => univer.dispose());
+ const inactiveRange = createTextRange({ collapsed: false });
+ const activeRange = createTextRange({ collapsed: false, isActive: vi.fn(() => true) });
+ const inactiveAnchor = inactiveRange.getAnchor();
+ const activeAnchor = activeRange.getAnchor();
+ getRangeListFromCharIndexMock.mockReturnValue({ textRanges: [inactiveRange, activeRange], rectRanges: [] });
+ service.addDocRanges([{ startOffset: 0, endOffset: 3 }], false, { shouldFocus: false });
+ expect(inactiveAnchor?.hide).toHaveBeenCalled();
+ expect(activeAnchor?.hide).toHaveBeenCalled();
+ expect(mobileSelectionVisualsMock.show).toHaveBeenCalled();
+ service.addDocRanges([{ startOffset: 0, endOffset: 3 }], true, { shouldFocus: false });
+ expect(activeAnchor?.show).toHaveBeenCalled();
+ expect(mobileSelectionVisualsMock.hide).toHaveBeenCalled();
});
it('places the manual cursor from transformed document coordinates', () => {
@@ -1959,5 +2272,19 @@ describe('DocSelectionRenderService', () => {
segmentId: 'header-1',
segmentPage: 2,
});
+
+ findNodeByCoord.mockClear();
+ service.setCursorManually(12, 18, true, false, { strict: false });
+ expect(findNodeByCoord).toHaveBeenCalledWith(
+ transformedPoint,
+ 0,
+ 9,
+ 11,
+ {
+ strict: false,
+ segmentId: 'header-1',
+ segmentPage: 2,
+ }
+ );
});
});
diff --git a/packages/docs-ui/src/services/selection/__tests__/range-state.spec.ts b/packages/docs-ui/src/services/selection/__tests__/range-state.spec.ts
index b32143dbe6..15ece33f1f 100644
--- a/packages/docs-ui/src/services/selection/__tests__/range-state.spec.ts
+++ b/packages/docs-ui/src/services/selection/__tests__/range-state.spec.ts
@@ -80,6 +80,7 @@ function createTextRangeHarness(backgroundColor?: string, themeColors: Record<st
getRenderColor: (color: string) => themeColors[color] ?? color,
},
}),
+ getAncestorScale: () => ({ scaleX: 1, scaleY: 1 }),
};
const document = {
getOffsetConfig: () => ({
@@ -266,6 +267,8 @@ describe('selection range state', () => {
_segmentId: '',
_segmentPage: -1,
_current: false,
+ _caretVisible: true,
+ _mobileHandlesVisible: false,
_rangeShape: { dispose: vi.fn() },
_anchorShape: { dispose: vi.fn(), hide: vi.fn(), show: vi.fn(), setProps: vi.fn() },
_docSkeleton: {
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 90250cc995..1c815cafef 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
@@ -37,6 +37,7 @@ import type { RectRange } from './rect-range';
import {
DataStreamTreeTokenType,
DOC_RANGE_TYPE,
+ IContextService,
ILogService,
Inject,
isInternalEditorID,
@@ -57,11 +58,7 @@ import {
} from '@univerjs/engine-render';
import { ILayoutService, KeyCode } from '@univerjs/ui';
import { BehaviorSubject, filter, fromEvent, merge, Subject, takeUntil } from 'rxjs';
-import {
- DOC_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE,
- IDocEmbedInteractionBoundaryService,
- IDocEmbedRuntimeFocusCoordinator,
-} from '../doc-embed-integration.service';
+import { DOC_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE, IDocEmbedInteractionBoundaryService, IDocEmbedRuntimeFocusCoordinator } from '../doc-embed-integration.service';
import { compareNodePositionLogic } from './convert-text-range';
import {
getCanvasOffsetByEngine,
@@ -126,26 +123,26 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
private readonly _onPointerDown$ = new Subject<void>();
readonly onPointerDown$ = this._onPointerDown$.asObservable();
- private _container!: HTMLDivElement;
+ protected _container!: HTMLDivElement;
private _inputParent!: HTMLDivElement;
private _input!: HTMLDivElement;
private _scrollTimers: ScrollTimer[] = [];
- private _rangeList: TextRange[] = [];
+ protected _rangeList: TextRange[] = [];
// Use to cache range list in moving.
- private _rangeListCache: TextRange[] = [];
+ protected _rangeListCache: TextRange[] = [];
// Rect range list.
private _rectRangeList: RectRange[] = [];
// Use to cache rect range list in moving.
- private _rectRangeListCache: RectRange[] = [];
- private _anchorNodePosition: Nullable<INodePosition> = null;
- private _focusNodePosition: Nullable<INodePosition> = null;
+ protected _rectRangeListCache: RectRange[] = [];
+ protected _anchorNodePosition: Nullable<INodePosition> = null;
+ protected _focusNodePosition: Nullable<INodePosition> = null;
private _currentSegmentId: string = '';
private _currentSegmentPage: number = -1;
private readonly _segmentContext$ = new BehaviorSubject({ segmentId: '', segmentPage: -1 });
readonly segmentContext$ = this._segmentContext$.asObservable();
private _selectionStyle: ITextSelectionStyle = NORMAL_TEXT_SELECTION_PLUGIN_STYLE;
- private _onPointerEvent = false;
+ protected _onPointerEvent = false;
private _viewPortObserverMap = new Map<
string,
@@ -174,6 +171,10 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
return this._input === this._getOwnerDocument().activeElement;
}
+ get isEditing() {
+ return this._textSelectionInner$.value?.isEditing === true;
+ }
+
get canFocusing() {
const ownerDocument = this._getOwnerDocument();
const activeElement = ownerDocument.activeElement;
@@ -204,9 +205,10 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
}
constructor(
- private readonly _context: IRenderContext<DocumentDataModel>,
+ protected readonly _context: IRenderContext<DocumentDataModel>,
@ILayoutService private readonly _layoutService: ILayoutService,
@ILogService private readonly _logService: ILogService,
+ @IContextService private readonly _contextService: IContextService,
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
@Inject(DocSelectionManagerService) private readonly _docSelectionManagerService: DocSelectionManagerService,
@@ -524,9 +526,15 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
return true;
}
- setCursorManually(evtOffsetX: number, evtOffsetY: number) {
+ setCursorManually(
+ evtOffsetX: number,
+ evtOffsetY: number,
+ isEditing = false,
+ shouldFocusInput = false,
+ options?: { strict?: boolean }
+ ) {
const startNode = this._findNodeByCoord(evtOffsetX, evtOffsetY, {
- strict: true,
+ strict: options?.strict ?? true,
segmentId: this._currentSegmentId,
segmentPage: this._currentSegmentPage,
});
@@ -551,8 +559,12 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
segmentId: this._currentSegmentId,
segmentPage: this._currentSegmentPage,
style: this._selectionStyle,
- isEditing: false,
+ isEditing,
});
+
+ if (shouldFocusInput) {
+ this._updateInputPosition({ forceFocus: true });
+ }
}
// Sync canvas selection to dom selection.
@@ -572,22 +584,13 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
}
}
- private _positionInput(x: number, y: number) {
- // Keep the hidden editor inside the Portal subtree when possible to avoid focus-trap loops,
- // then compensate coordinates if a transformed ancestor changes the fixed containing block.
+ protected _positionInput(x: number, y: number) {
this._ensureHostContainer();
this._container.style.position = 'fixed';
- let left = x;
- let top = y;
const fixedContainer = this._container.offsetParent;
- if (fixedContainer) {
- const rect = fixedContainer.getBoundingClientRect();
- left -= rect.left;
- top -= rect.top;
- }
-
- this._container.style.left = `${left}px`;
- this._container.style.top = `${top}px`;
+ const rect = fixedContainer?.getBoundingClientRect();
+ this._container.style.left = `${x - (rect?.left ?? 0)}px`;
+ this._container.style.top = `${y - (rect?.top ?? 0)}px`;
this._container.style.zIndex = '1000';
}
@@ -613,7 +616,7 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
}
// Handler double click.
- __handleDblClick(evt: IPointerEvent | IMouseEvent) {
+ __handleDblClick(evt: IPointerEvent | IMouseEvent, isEditing = false, shouldFocusInput = true) {
const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
const startNode = this._findNodeByCoord(evtOffsetX, evtOffsetY, {
@@ -648,7 +651,10 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
},
];
- this.addDocRanges(textRanges, false, { forceFocus: true });
+ this.addDocRanges(textRanges, isEditing, {
+ forceFocus: shouldFocusInput,
+ shouldFocus: shouldFocusInput,
+ });
}
}
@@ -686,7 +692,7 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
// Handle pointer down.
// eslint-disable-next-line max-lines-per-function, complexity
- __onPointDown(evt: IPointerEvent | IMouseEvent) {
+ __onPointDown(evt: IPointerEvent | IMouseEvent, shouldFocusInput = true) {
const { scene, mainComponent } = this._context;
const skeleton = this._docSkeletonManagerService.getSkeleton();
@@ -816,20 +822,12 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
this._anchorNodePosition = null;
this._focusNodePosition = null;
- const selectionInfo = {
- textRanges: this._getAllTextRanges(),
- rectRanges: this._getAllRectRanges(),
- segmentId: this._currentSegmentId,
- segmentPage: this._currentSegmentPage,
- style: this._selectionStyle,
- isEditing: false,
- };
-
- this._textSelectionInner$.next(selectionInfo);
+ this._emitCurrentSelection(false);
this._disposeScrollTimers();
-
- this._updateInputPosition({ forceFocus: true });
+ if (shouldFocusInput) {
+ this._updateInputPosition({ forceFocus: true });
+ }
}));
}
@@ -844,6 +842,21 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
this.blur();
}
+ enterEditing(): boolean {
+ if (!this._getActiveRangeInstance()) {
+ return false;
+ }
+
+ this._setEditing(true);
+ this._updateInputPosition({ forceFocus: true });
+ return true;
+ }
+
+ exitEditing(): void {
+ this._setEditing(false);
+ this.blur();
+ }
+
removeAllRanges() {
this._pendingSelection = null;
this._removeAllRanges();
@@ -854,6 +867,29 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
return this._getActiveRangeInstance();
}
+ protected _setEditing(isEditing: boolean): void {
+ const selection = this._textSelectionInner$.value;
+ if (!selection || selection.isEditing === isEditing) {
+ return;
+ }
+
+ this._textSelectionInner$.next({
+ ...selection,
+ isEditing,
+ });
+ }
+
+ protected _emitCurrentSelection(isEditing: boolean): void {
+ this._textSelectionInner$.next({
+ textRanges: this._getAllTextRanges(),
+ rectRanges: this._getAllRectRanges(),
+ segmentId: this._currentSegmentId,
+ segmentPage: this._currentSegmentPage,
+ style: this._selectionStyle,
+ isEditing,
+ });
+ }
+
private _disposeScrollTimers() {
this._scrollTimers.forEach((timer) => {
timer?.dispose();
@@ -864,7 +900,6 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
private _setSystemHighlightColorToStyle() {
const { r, g, b, a } = getSystemHighlightColor();
-
// Only set selection use highlight color.
const style: ITextSelectionStyle = {
strokeWidth: 1,
@@ -908,7 +943,7 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
return serializeTextRange(activeRange);
}
- private _getActiveRangeInstance() {
+ protected _getActiveRangeInstance() {
return this._rangeList.find((range) => range.isActive());
}
@@ -981,7 +1016,7 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
`;
}
- private _ensureHostContainer(): void {
+ protected _ensureHostContainer(): void {
// Prefer the Univer root container (often inside a Portal) so focus stays within the modal subtree.
const host = this._layoutService.rootContainerElement;
if (host?.isConnected) {
@@ -1062,7 +1097,7 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
this._removeAllRectRanges();
}
- private _removeAllCacheRanges() {
+ protected _removeAllCacheRanges() {
this._rangeListCache.forEach((range) => {
range.dispose();
});
@@ -1132,7 +1167,7 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
this._rangeListCache.push(...textRanges);
}
- private _addTextRange(textRange: TextRange) {
+ protected _addTextRange(textRange: TextRange) {
this._deactivateAllTextRanges();
textRange.activate();
@@ -1143,7 +1178,7 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
this._rectRangeListCache.push(...rectRanges);
}
- private _addRectRanges(rectRanges: RectRange[]) {
+ protected _addRectRanges(rectRanges: RectRange[]) {
if (rectRanges.length === 0) {
return;
}
@@ -1223,7 +1258,7 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
return getCanvasOffsetByEngine(engine);
}
- private _updateInputPosition({ forceFocus = false, preserveFocus = false } = {}) {
+ protected _updateInputPosition({ forceFocus = false, preserveFocus = false } = {}) {
const activeRangeInstance = this._getActiveRangeInstance();
const anchor = activeRangeInstance?.getAnchor();
@@ -1254,7 +1289,7 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
}
}
- private _tryMoving(moveOffsetX: number, moveOffsetY: number) {
+ protected _tryMoving(moveOffsetX: number, moveOffsetY: number) {
try {
this._moving(moveOffsetX, moveOffsetY);
} catch (error) {
@@ -1541,9 +1576,7 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
if (this._shouldSuppressHostHiddenEditorEvent(e)) {
return;
}
- this._eventHandle(e, (config) => {
- this._onFocus$.next(config);
- });
+ this._handleInputFocus(e);
})
);
@@ -1560,9 +1593,7 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
if (this._shouldSuppressHostHiddenEditorEvent(e)) {
return;
}
- this._eventHandle(e, (config) => {
- this._onBlur$.next(config);
- });
+ this._handleInputBlur(e);
})
);
}
@@ -1575,6 +1606,23 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
}
}
+ protected _handleInputFocus(event: Event): void {
+ this._eventHandle(event, (config) => {
+ this._onFocus$.next(config);
+ });
+ }
+
+ protected _handleInputBlur(event: Event): void {
+ this._setEditing(false);
+ this._emitInputBlur(event);
+ }
+
+ protected _emitInputBlur(event: Event): void {
+ this._eventHandle(event, (config) => {
+ this._onBlur$.next(config);
+ });
+ }
+
private _eventHandle(
e: Event | CompositionEvent | KeyboardEvent,
func: (config: IEditorInputConfig) => void,
diff --git a/packages/docs-ui/src/views/PageSettings.tsx b/packages/docs-ui/src/views/PageSettings.tsx
index 181b7d09e9..2a492bb5c2 100644
--- a/packages/docs-ui/src/views/PageSettings.tsx
+++ b/packages/docs-ui/src/views/PageSettings.tsx
@@ -104,8 +104,8 @@ function SettingsLabel(props: { children: ReactNode; muted?: boolean }) {
);
}
-export function PageSettings(props: IConfirmChildrenProps) {
- const { hooks } = props;
+export function PageSettings(props: IConfirmChildrenProps & { InputNumberComponent?: typeof InputNumber; SelectComponent?: typeof Select }) {
+ const { hooks, InputNumberComponent = InputNumber, SelectComponent = Select } = props;
const univerInstanceService = useDependency(IUniverInstanceService);
const currentDoc = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)!;
const documentStyle = currentDoc.getDocumentStyle();
@@ -151,41 +151,12 @@ export function PageSettings(props: IConfirmChildrenProps) {
}));
};
- // const handleModeChange = (mode: IPageSettings['mode']) => {
- // setSettings((prev) => ({ ...prev, mode }));
- // };
-
const handleModernWidthChange = (modernWidth: ModernDocumentWidthMode) => {
setSettings((prev) => ({ ...prev, modernWidth }));
};
return (
<div className="univer-flex univer-flex-col univer-gap-4">
- {/* <div
- className="
- univer-grid univer-grid-cols-2 univer-rounded-lg univer-bg-gray-100 univer-p-1
- dark:!univer-bg-gray-800
- "
- >
- {([DocumentFlavor.MODERN, DocumentFlavor.TRADITIONAL] as const).map((mode) => (
- <button
- key={mode}
- type="button"
- className={clsx(`
- univer-h-8 univer-cursor-pointer univer-rounded-md univer-border-none univer-bg-transparent
- univer-text-sm univer-font-medium univer-text-gray-600 univer-transition-colors
- hover:univer-bg-gray-0 hover:univer-text-gray-900
- dark:!univer-text-gray-200
- dark:hover:!univer-bg-gray-700
- `, {
- 'univer-bg-gray-0 univer-text-gray-900 univer-shadow-sm dark:!univer-bg-gray-700 dark:!univer-text-gray-0': settings.mode === mode,
- })}
- onClick={() => handleModeChange(mode)}
- >
- {localeService.t<LocaleKey>(mode === DocumentFlavor.MODERN ? 'docs-ui.page-settings.modern-mode' : 'docs-ui.page-settings.classic-mode')}
- </button>
- ))}
- </div> */}
{settings.mode === DocumentFlavor.MODERN
? (
@@ -222,7 +193,8 @@ export function PageSettings(props: IConfirmChildrenProps) {
<SettingsLabel>
{localeService.t<LocaleKey>('docs-ui.page-settings.paper-size')}
</SettingsLabel>
- <Select
+ <SelectComponent
+ className="univer-w-full"
value={settings.paperSize}
onChange={handlePaperSizeChange}
options={PAPER_TYPES.map((p) => ({
@@ -240,7 +212,8 @@ export function PageSettings(props: IConfirmChildrenProps) {
<SettingsLabel muted>
{localeService.t<LocaleKey>('docs-ui.page-settings.top')}
</SettingsLabel>
- <InputNumber
+ <InputNumberComponent
+ className="univer-w-full"
precision={2}
min={0}
max={settings.pageSize.height / 2}
@@ -252,7 +225,8 @@ export function PageSettings(props: IConfirmChildrenProps) {
<SettingsLabel muted>
{localeService.t<LocaleKey>('docs-ui.page-settings.bottom')}
</SettingsLabel>
- <InputNumber
+ <InputNumberComponent
+ className="univer-w-full"
precision={2}
min={0}
max={settings.pageSize.height / 2}
@@ -266,7 +240,8 @@ export function PageSettings(props: IConfirmChildrenProps) {
<SettingsLabel muted>
{localeService.t<LocaleKey>('docs-ui.page-settings.left')}
</SettingsLabel>
- <InputNumber
+ <InputNumberComponent
+ className="univer-w-full"
precision={2}
min={0}
max={settings.pageSize.width / 2}
@@ -278,7 +253,8 @@ export function PageSettings(props: IConfirmChildrenProps) {
<SettingsLabel muted>
{localeService.t<LocaleKey>('docs-ui.page-settings.right')}
</SettingsLabel>
- <InputNumber
+ <InputNumberComponent
+ className="univer-w-full"
precision={2}
min={0}
max={settings.pageSize.width / 2}
diff --git a/packages/docs-ui/src/views/header-footer/panel/DocHeaderFooterOptions.tsx b/packages/docs-ui/src/views/header-footer/panel/DocHeaderFooterOptions.tsx
index 7d8c9ecd11..16d71bca76 100644
--- a/packages/docs-ui/src/views/header-footer/panel/DocHeaderFooterOptions.tsx
+++ b/packages/docs-ui/src/views/header-footer/panel/DocHeaderFooterOptions.tsx
@@ -14,71 +14,18 @@
* limitations under the License.
*/
-import type { DocumentDataModel, IDocumentStyle } from '@univerjs/core';
-import type { IHeaderFooterProps } from '@univerjs/docs';
-import type { IDocumentSkeletonPage } from '@univerjs/engine-render';
+import type { ComponentType } from 'react';
import type { LocaleKey } from '../../../locale/types';
-import {
- BooleanNumber,
- generateRandomId,
- getSectionHeaderFooterReferenceKey,
- ICommandService,
- IUniverInstanceService,
- LocaleService,
- resolveSectionHeaderFooterReference,
- UniverInstanceType,
-} from '@univerjs/core';
+import { BooleanNumber, LocaleService } from '@univerjs/core';
import { Button, Checkbox, InputNumber } from '@univerjs/design';
-import { DocSkeletonManagerService, SetSectionHeaderFooterLinkCommand } from '@univerjs/docs';
-import { DocumentEditArea, IRenderManagerService } from '@univerjs/engine-render';
-import { ILayoutService, useDependency, useObservable } from '@univerjs/ui';
-import { useState } from 'react';
-import {
- CloseHeaderFooterCommand,
- CoreHeaderFooterCommandId,
-} from '../../../commands/commands/doc-header-footer.command';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { useDependency, useObservable } from '@univerjs/ui';
import { DocSelectionRenderService } from '../../../services/selection/doc-selection-render.service';
-import { getDocPageSectionContext } from '../../../utils/section-header-footer';
-
-function getSegmentId(documentStyle: IDocumentStyle, editArea: DocumentEditArea, pageIndex: number, page?: IDocumentSkeletonPage): string {
- const {
- useFirstPageHeaderFooter,
- evenAndOddHeaders,
- defaultHeaderId,
- defaultFooterId,
- firstPageHeaderId,
- firstPageFooterId,
- evenPageHeaderId,
- evenPageFooterId,
- } = documentStyle;
- const isFirstPage = page ? page.pageNumber === page.pageNumberStart : pageIndex === 0;
- const isEvenPage = page ? page.pageNumber % 2 === 0 : pageIndex % 2 === 1;
-
- if (editArea === DocumentEditArea.HEADER) {
- if (useFirstPageHeaderFooter === BooleanNumber.TRUE) {
- if (isFirstPage) {
- return firstPageHeaderId!;
- } else {
- return evenAndOddHeaders === BooleanNumber.TRUE && isEvenPage ? evenPageHeaderId! : defaultHeaderId!;
- }
- } else {
- return evenAndOddHeaders === BooleanNumber.TRUE && isEvenPage ? evenPageHeaderId! : defaultHeaderId!;
- }
- } else {
- if (useFirstPageHeaderFooter === BooleanNumber.TRUE) {
- if (isFirstPage) {
- return firstPageFooterId!;
- } else {
- return evenAndOddHeaders === BooleanNumber.TRUE && isEvenPage ? evenPageFooterId! : defaultFooterId!;
- }
- } else {
- return evenAndOddHeaders === BooleanNumber.TRUE && isEvenPage ? evenPageFooterId! : defaultFooterId!;
- }
- }
-}
+import { useHeaderFooterOptions } from './use-header-footer-options';
export interface IDocHeaderFooterOptionsProps {
unitId: string;
+ ContentComponent?: ComponentType<{ unitId: string }>;
}
export const DocHeaderFooterOptions = (props: IDocHeaderFooterOptionsProps) => {
@@ -89,207 +36,18 @@ export const DocHeaderFooterOptions = (props: IDocHeaderFooterOptionsProps) => {
segmentPage: docSelectionRenderService.getSegmentPage(),
});
- return <DocHeaderFooterOptionsContent key={`${segmentContext?.segmentId ?? ''}:${segmentContext?.segmentPage ?? -1}`} {...props} />;
+ const ContentComponent = props.ContentComponent ?? DocHeaderFooterOptionsContent;
+ return <ContentComponent key={`${segmentContext?.segmentId ?? ''}:${segmentContext?.segmentPage ?? -1}`} {...props} />;
};
-function DocHeaderFooterOptionsContent(props: IDocHeaderFooterOptionsProps) {
+function DocHeaderFooterOptionsContent({ unitId }: { unitId: string }) {
const localeService = useDependency(LocaleService);
- const univerInstanceService = useDependency(IUniverInstanceService);
- const renderManagerService = useDependency(IRenderManagerService);
- const commandService = useDependency(ICommandService);
-
- const layoutService = useDependency(ILayoutService);
-
- const { unitId } = props;
-
- const docSelectionRenderService = renderManagerService.getRenderUnitById(unitId)!.with(DocSelectionRenderService)!;
- const docDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
-
- const getCurrentSectionContext = () => {
- const snapshot = docDataModel?.getSnapshot();
- const docSkeletonManagerService = renderManagerService.getRenderUnitById(unitId)?.with(DocSkeletonManagerService);
- const page = docSkeletonManagerService?.getSkeleton?.()?.getSkeletonData()?.pages[docSelectionRenderService.getSegmentPage()];
- return snapshot == null ? undefined : { ...getDocPageSectionContext(snapshot, page), page };
- };
- const [options, setOptions] = useState<IHeaderFooterProps>(() => {
- const config = getCurrentSectionContext()?.config;
- return {
- marginHeader: config?.marginHeader ?? 0,
- marginFooter: config?.marginFooter ?? 0,
- useFirstPageHeaderFooter: config?.useFirstPageHeaderFooter ?? BooleanNumber.FALSE,
- evenAndOddHeaders: config?.evenAndOddHeaders ?? BooleanNumber.FALSE,
- };
- });
- const sectionContext = getCurrentSectionContext();
- const editArea = renderManagerService.getRenderUnitById(unitId)?.with(DocSkeletonManagerService)?.getViewModel()?.getEditArea();
- const headerFooterKind = editArea === DocumentEditArea.FOOTER ? 'footer' : 'header';
- const variant = getHeaderFooterVariant(
- sectionContext?.config ?? {},
- docSelectionRenderService.getSegmentPage(),
- sectionContext?.page
- );
- const referenceKey = getSectionHeaderFooterReferenceKey(headerFooterKind, variant);
- const canLinkToPrevious = (sectionContext?.sectionIndex ?? -1) > 0;
- const [linkedToPrevious, setLinkedToPrevious] = useState(
- canLinkToPrevious && !sectionContext?.section?.[referenceKey]
- );
-
- const handleCheckboxChange = (val: boolean, type: 'useFirstPageHeaderFooter' | 'evenAndOddHeaders') => {
- setOptions((prev) => ({
- ...prev,
- [type]: val ? BooleanNumber.TRUE : BooleanNumber.FALSE,
- }));
-
- const sectionContext = getCurrentSectionContext();
- const documentStyle = sectionContext?.config;
- const docSkeletonManagerService = renderManagerService.getRenderUnitById(unitId)?.with(DocSkeletonManagerService);
- const viewModel = docSkeletonManagerService?.getViewModel();
-
- if (documentStyle == null || viewModel == null) {
- return;
- }
-
- const editArea = viewModel.getEditArea();
-
- let needCreateHeaderFooter = false;
- const segmentPage = docSelectionRenderService.getSegmentPage();
- const isFirstSectionPage = sectionContext?.page
- ? sectionContext.page.pageNumber === sectionContext.page.pageNumberStart
- : segmentPage === 0;
- const isEvenPage = sectionContext?.page ? sectionContext.page.pageNumber % 2 === 0 : segmentPage % 2 === 1;
- let needChangeSegmentId = false;
- if (type === 'useFirstPageHeaderFooter' && val === true) {
- if (editArea === DocumentEditArea.HEADER && !documentStyle.firstPageHeaderId) {
- needCreateHeaderFooter = true;
- } else if (editArea === DocumentEditArea.FOOTER && !documentStyle.firstPageFooterId) {
- needCreateHeaderFooter = true;
- }
-
- if (needCreateHeaderFooter && isFirstSectionPage) {
- needChangeSegmentId = true;
- }
- }
-
- if (type === 'evenAndOddHeaders' && val === true) {
- if (editArea === DocumentEditArea.HEADER && !documentStyle.evenPageHeaderId) {
- needCreateHeaderFooter = true;
- } else if (editArea === DocumentEditArea.FOOTER && !documentStyle.evenPageFooterId) {
- needCreateHeaderFooter = true;
- }
-
- if (needCreateHeaderFooter && isEvenPage) {
- needChangeSegmentId = true;
- }
- }
-
- if (needCreateHeaderFooter) {
- const SEGMENT_ID_LEN = 6;
- const segmentId = generateRandomId(SEGMENT_ID_LEN);
- // Set segment id first, then exec command.
- if (needChangeSegmentId) {
- docSelectionRenderService.setSegment(segmentId);
- }
-
- commandService.executeCommand(CoreHeaderFooterCommandId, {
- unitId,
- segmentId,
- headerFooterProps: {
- [type]: val ? BooleanNumber.TRUE : BooleanNumber.FALSE,
- },
- sectionId: sectionContext?.sectionId,
- });
- } else {
- const segmentPageIndex = docSelectionRenderService.getSegmentPage();
- const prevSegmentId = docSelectionRenderService.getSegment();
-
- const needFocusSegmentId = getSegmentId(
- {
- ...documentStyle,
- [type]: val ? BooleanNumber.TRUE : BooleanNumber.FALSE,
- },
- editArea,
- segmentPageIndex,
- sectionContext?.page
- );
-
- if (needFocusSegmentId && needFocusSegmentId !== prevSegmentId) {
- docSelectionRenderService.setSegment(needFocusSegmentId);
- }
-
- commandService.executeCommand(CoreHeaderFooterCommandId, {
- unitId,
- headerFooterProps: {
- [type]: val ? BooleanNumber.TRUE : BooleanNumber.FALSE,
- },
- sectionId: sectionContext?.sectionId,
- });
- }
-
- layoutService.focus();
- };
-
- const handleMarginChange = async (val: number, type: 'marginHeader' | 'marginFooter') => {
- setOptions((prev) => ({
- ...prev,
- [type]: val,
- }));
-
- await commandService.executeCommand(CoreHeaderFooterCommandId, {
- unitId,
- headerFooterProps: {
- [type]: val,
- },
- sectionId: getCurrentSectionContext()?.sectionId,
- });
-
- // To make sure input always has focus.
- docSelectionRenderService.removeAllRanges();
- docSelectionRenderService.blur();
- };
-
- const closeHeaderFooter = () => {
- commandService.executeCommand(CloseHeaderFooterCommand.id, {
- unitId,
- });
- };
-
- const handleLinkToPreviousChange = async (linked: boolean) => {
- const context = getCurrentSectionContext();
- if (!context?.sectionId || context.sectionIndex <= 0 || !docDataModel) {
- return;
- }
- const currentEditArea = renderManagerService.getRenderUnitById(unitId)?.with(DocSkeletonManagerService)?.getViewModel()?.getEditArea();
- const kind = currentEditArea === DocumentEditArea.FOOTER ? 'footer' : 'header';
- const currentVariant = getHeaderFooterVariant(context.config, docSelectionRenderService.getSegmentPage(), context.page);
- const key = getSectionHeaderFooterReferenceKey(kind, currentVariant);
- const segmentId = generateRandomId(6);
- const previousSegmentId = resolveSectionHeaderFooterReference(
- docDataModel.getDocumentStyle(),
- context.sections,
- context.sectionIndex - 1,
- key
- ).segmentId;
- const success = await commandService.executeCommand(SetSectionHeaderFooterLinkCommand.id, {
- unitId,
- sectionId: context.sectionId,
- kind,
- variant: currentVariant,
- linkedToPrevious: linked,
- ...(linked ? {} : { segmentId }),
- });
- if (!success) {
- return;
- }
- setLinkedToPrevious(linked);
- docSelectionRenderService.setSegment(linked ? previousSegmentId ?? '' : segmentId);
- layoutService.focus();
- };
-
+ const { canLinkToPrevious, linkedToPrevious, options, handleLinkToPreviousChange, handleCheckboxChange, handleMarginChange, closeHeaderFooter } = useHeaderFooterOptions(unitId);
return (
<div className="univer-grid univer-gap-4">
{canLinkToPrevious && (
<div>
- <Checkbox checked={linkedToPrevious} onChange={(val) => { handleLinkToPreviousChange(val as boolean); }}>
+ <Checkbox checked={linkedToPrevious} onChange={(val) => { handleLinkToPreviousChange(Boolean(val)); }}>
{localeService.t<LocaleKey>('docs-ui.headerFooter.linkToPrevious')}
</Checkbox>
</div>
@@ -298,7 +56,7 @@ function DocHeaderFooterOptionsContent(props: IDocHeaderFooterOptionsProps) {
<div>
<Checkbox
checked={options.useFirstPageHeaderFooter === BooleanNumber.TRUE}
- onChange={(val) => { handleCheckboxChange(val as boolean, 'useFirstPageHeaderFooter'); }}
+ onChange={(val) => { handleCheckboxChange(Boolean(val), 'useFirstPageHeaderFooter'); }}
>
{localeService.t<LocaleKey>('docs-ui.headerFooter.firstPageCheckBox')}
</Checkbox>
@@ -306,7 +64,7 @@ function DocHeaderFooterOptionsContent(props: IDocHeaderFooterOptionsProps) {
<div>
<Checkbox
checked={options.evenAndOddHeaders === BooleanNumber.TRUE}
- onChange={(val) => { handleCheckboxChange(val as boolean, 'evenAndOddHeaders'); }}
+ onChange={(val) => { handleCheckboxChange(Boolean(val), 'evenAndOddHeaders'); }}
>
{localeService.t<LocaleKey>('docs-ui.headerFooter.oddEvenCheckBox')}
</Checkbox>
@@ -322,7 +80,7 @@ function DocHeaderFooterOptionsContent(props: IDocHeaderFooterOptionsProps) {
max={200}
precision={1}
value={options.marginHeader}
- onChange={(val) => { handleMarginChange(val as number, 'marginHeader'); }}
+ onChange={(val) => { handleMarginChange(val ?? 0, 'marginHeader'); }}
/>
</div>
<div>
@@ -333,26 +91,16 @@ function DocHeaderFooterOptionsContent(props: IDocHeaderFooterOptionsProps) {
max={200}
precision={1}
value={options.marginFooter}
- onChange={(val) => { handleMarginChange(val as number, 'marginFooter'); }}
+ onChange={(val) => { handleMarginChange(val ?? 0, 'marginFooter'); }}
/>
</div>
</div>
<div className="univer-flex univer-justify-end">
- <Button onClick={closeHeaderFooter}>{localeService.t<LocaleKey>('docs-ui.headerFooter.closeHeaderFooter')}</Button>
+ <Button onClick={closeHeaderFooter}>
+ {localeService.t<LocaleKey>('docs-ui.headerFooter.closeHeaderFooter')}
+ </Button>
</div>
</div>
);
}
-
-function getHeaderFooterVariant(documentStyle: IDocumentStyle, pageIndex: number, page?: IDocumentSkeletonPage) {
- const isFirstPage = page ? page.pageNumber === page.pageNumberStart : pageIndex === 0;
- const isEvenPage = page ? page.pageNumber % 2 === 0 : pageIndex % 2 === 1;
- if (documentStyle.useFirstPageHeaderFooter === BooleanNumber.TRUE && isFirstPage) {
- return 'first' as const;
- }
- if (documentStyle.evenAndOddHeaders === BooleanNumber.TRUE && isEvenPage) {
- return 'even' as const;
- }
- return 'default' as const;
-}
diff --git a/packages/docs-ui/src/views/header-footer/panel/DocHeaderFooterPanel.tsx b/packages/docs-ui/src/views/header-footer/panel/DocHeaderFooterPanel.tsx
index 705b0792b7..725127cd28 100644
--- a/packages/docs-ui/src/views/header-footer/panel/DocHeaderFooterPanel.tsx
+++ b/packages/docs-ui/src/views/header-footer/panel/DocHeaderFooterPanel.tsx
@@ -16,6 +16,7 @@
import type { DocumentDataModel } from '@univerjs/core';
import type { LocaleKey } from '../../../locale/types';
+import type { IDocHeaderFooterOptionsProps } from './DocHeaderFooterOptions';
import { IUniverInstanceService, LocaleService, UniverInstanceType } from '@univerjs/core';
import { DocSkeletonManagerService } from '@univerjs/docs';
import { DocumentEditArea, IRenderManagerService } from '@univerjs/engine-render';
@@ -23,7 +24,7 @@ import { useDependency, useObservable } from '@univerjs/ui';
import { filter, map } from 'rxjs';
import { DocHeaderFooterOptions } from './DocHeaderFooterOptions';
-export const DocHeaderFooterPanel = () => {
+export const DocHeaderFooterPanel = (props: Pick<IDocHeaderFooterOptionsProps, 'ContentComponent'>) => {
const localeService = useDependency(LocaleService);
const renderManagerService = useDependency(IRenderManagerService);
const univerInstanceService = useDependency(IUniverInstanceService);
@@ -45,7 +46,7 @@ export const DocHeaderFooterPanel = () => {
return (
<div className="univer-text-sm">
{isEditHeaderFooter
- ? <DocHeaderFooterOptions unitId={unitId} />
+ ? <DocHeaderFooterOptions {...props} unitId={unitId} />
: <div className="univer-text-gray-400">{localeService.t<LocaleKey>('docs-ui.headerFooter.disableText')}</div>}
</div>
);
diff --git a/packages/docs-ui/src/views/header-footer/panel/use-header-footer-options.ts b/packages/docs-ui/src/views/header-footer/panel/use-header-footer-options.ts
new file mode 100644
index 0000000000..9e85a0ba09
--- /dev/null
+++ b/packages/docs-ui/src/views/header-footer/panel/use-header-footer-options.ts
@@ -0,0 +1,280 @@
+/**
+ * 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, IDocumentStyle } from '@univerjs/core';
+import type { IHeaderFooterProps } from '@univerjs/docs';
+import type { IDocumentSkeletonPage } from '@univerjs/engine-render';
+import {
+ BooleanNumber,
+ generateRandomId,
+ getSectionHeaderFooterReferenceKey,
+ ICommandService,
+ IUniverInstanceService,
+ resolveSectionHeaderFooterReference,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { DocSkeletonManagerService, SetSectionHeaderFooterLinkCommand } from '@univerjs/docs';
+import { DocumentEditArea, IRenderManagerService } from '@univerjs/engine-render';
+import { ILayoutService, useDependency } from '@univerjs/ui';
+import { useState } from 'react';
+import {
+ CloseHeaderFooterCommand,
+ CoreHeaderFooterCommandId,
+} from '../../../commands/commands/doc-header-footer.command';
+import { DocSelectionRenderService } from '../../../services/selection/doc-selection-render.service';
+import { getDocPageSectionContext } from '../../../utils/section-header-footer';
+
+function getSegmentId(documentStyle: IDocumentStyle, editArea: DocumentEditArea, pageIndex: number, page?: IDocumentSkeletonPage): string {
+ const {
+ useFirstPageHeaderFooter,
+ evenAndOddHeaders,
+ defaultHeaderId,
+ defaultFooterId,
+ firstPageHeaderId,
+ firstPageFooterId,
+ evenPageHeaderId,
+ evenPageFooterId,
+ } = documentStyle;
+ const isFirstPage = page ? page.pageNumber === page.pageNumberStart : pageIndex === 0;
+ const isEvenPage = page ? page.pageNumber % 2 === 0 : pageIndex % 2 === 1;
+
+ if (editArea === DocumentEditArea.HEADER) {
+ if (useFirstPageHeaderFooter === BooleanNumber.TRUE) {
+ if (isFirstPage) {
+ return firstPageHeaderId!;
+ } else {
+ return evenAndOddHeaders === BooleanNumber.TRUE && isEvenPage ? evenPageHeaderId! : defaultHeaderId!;
+ }
+ } else {
+ return evenAndOddHeaders === BooleanNumber.TRUE && isEvenPage ? evenPageHeaderId! : defaultHeaderId!;
+ }
+ } else {
+ if (useFirstPageHeaderFooter === BooleanNumber.TRUE) {
+ if (isFirstPage) {
+ return firstPageFooterId!;
+ } else {
+ return evenAndOddHeaders === BooleanNumber.TRUE && isEvenPage ? evenPageFooterId! : defaultFooterId!;
+ }
+ } else {
+ return evenAndOddHeaders === BooleanNumber.TRUE && isEvenPage ? evenPageFooterId! : defaultFooterId!;
+ }
+ }
+}
+
+export function useHeaderFooterOptions(unitId: string) {
+ const univerInstanceService = useDependency(IUniverInstanceService);
+ const renderManagerService = useDependency(IRenderManagerService);
+ const commandService = useDependency(ICommandService);
+
+ const layoutService = useDependency(ILayoutService);
+
+ const docSelectionRenderService = renderManagerService.getRenderUnitById(unitId)!.with(DocSelectionRenderService)!;
+ const docDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
+
+ const getCurrentSectionContext = () => {
+ const snapshot = docDataModel?.getSnapshot();
+ const docSkeletonManagerService = renderManagerService.getRenderUnitById(unitId)?.with(DocSkeletonManagerService);
+ const page = docSkeletonManagerService?.getSkeleton?.()?.getSkeletonData()?.pages[docSelectionRenderService.getSegmentPage()];
+ return snapshot == null ? undefined : { ...getDocPageSectionContext(snapshot, page), page };
+ };
+ const [options, setOptions] = useState<IHeaderFooterProps>(() => {
+ const config = getCurrentSectionContext()?.config;
+ return {
+ marginHeader: config?.marginHeader ?? 0,
+ marginFooter: config?.marginFooter ?? 0,
+ useFirstPageHeaderFooter: config?.useFirstPageHeaderFooter ?? BooleanNumber.FALSE,
+ evenAndOddHeaders: config?.evenAndOddHeaders ?? BooleanNumber.FALSE,
+ };
+ });
+ const sectionContext = getCurrentSectionContext();
+ const editArea = renderManagerService.getRenderUnitById(unitId)?.with(DocSkeletonManagerService)?.getViewModel()?.getEditArea();
+ const headerFooterKind = editArea === DocumentEditArea.FOOTER ? 'footer' : 'header';
+ const variant = getHeaderFooterVariant(
+ sectionContext?.config ?? {},
+ docSelectionRenderService.getSegmentPage(),
+ sectionContext?.page
+ );
+ const referenceKey = getSectionHeaderFooterReferenceKey(headerFooterKind, variant);
+ const canLinkToPrevious = (sectionContext?.sectionIndex ?? -1) > 0;
+ const [linkedToPrevious, setLinkedToPrevious] = useState(
+ canLinkToPrevious && !sectionContext?.section?.[referenceKey]
+ );
+
+ const handleCheckboxChange = (val: boolean, type: 'useFirstPageHeaderFooter' | 'evenAndOddHeaders') => {
+ setOptions((prev) => ({
+ ...prev,
+ [type]: val ? BooleanNumber.TRUE : BooleanNumber.FALSE,
+ }));
+
+ const sectionContext = getCurrentSectionContext();
+ const documentStyle = sectionContext?.config;
+ const docSkeletonManagerService = renderManagerService.getRenderUnitById(unitId)?.with(DocSkeletonManagerService);
+ const viewModel = docSkeletonManagerService?.getViewModel();
+
+ if (documentStyle == null || viewModel == null) {
+ return;
+ }
+
+ const editArea = viewModel.getEditArea();
+
+ let needCreateHeaderFooter = false;
+ const segmentPage = docSelectionRenderService.getSegmentPage();
+ const isFirstSectionPage = sectionContext?.page
+ ? sectionContext.page.pageNumber === sectionContext.page.pageNumberStart
+ : segmentPage === 0;
+ const isEvenPage = sectionContext?.page ? sectionContext.page.pageNumber % 2 === 0 : segmentPage % 2 === 1;
+ let needChangeSegmentId = false;
+ if (type === 'useFirstPageHeaderFooter' && val === true) {
+ if (editArea === DocumentEditArea.HEADER && !documentStyle.firstPageHeaderId) {
+ needCreateHeaderFooter = true;
+ } else if (editArea === DocumentEditArea.FOOTER && !documentStyle.firstPageFooterId) {
+ needCreateHeaderFooter = true;
+ }
+
+ if (needCreateHeaderFooter && isFirstSectionPage) {
+ needChangeSegmentId = true;
+ }
+ }
+
+ if (type === 'evenAndOddHeaders' && val === true) {
+ if (editArea === DocumentEditArea.HEADER && !documentStyle.evenPageHeaderId) {
+ needCreateHeaderFooter = true;
+ } else if (editArea === DocumentEditArea.FOOTER && !documentStyle.evenPageFooterId) {
+ needCreateHeaderFooter = true;
+ }
+
+ if (needCreateHeaderFooter && isEvenPage) {
+ needChangeSegmentId = true;
+ }
+ }
+
+ if (needCreateHeaderFooter) {
+ const SEGMENT_ID_LEN = 6;
+ const segmentId = generateRandomId(SEGMENT_ID_LEN);
+ // Set segment id first, then exec command.
+ if (needChangeSegmentId) {
+ docSelectionRenderService.setSegment(segmentId);
+ }
+
+ commandService.executeCommand(CoreHeaderFooterCommandId, {
+ unitId,
+ segmentId,
+ headerFooterProps: {
+ [type]: val ? BooleanNumber.TRUE : BooleanNumber.FALSE,
+ },
+ sectionId: sectionContext?.sectionId,
+ });
+ } else {
+ const segmentPageIndex = docSelectionRenderService.getSegmentPage();
+ const prevSegmentId = docSelectionRenderService.getSegment();
+
+ const needFocusSegmentId = getSegmentId(
+ {
+ ...documentStyle,
+ [type]: val ? BooleanNumber.TRUE : BooleanNumber.FALSE,
+ },
+ editArea,
+ segmentPageIndex,
+ sectionContext?.page
+ );
+
+ if (needFocusSegmentId && needFocusSegmentId !== prevSegmentId) {
+ docSelectionRenderService.setSegment(needFocusSegmentId);
+ }
+
+ commandService.executeCommand(CoreHeaderFooterCommandId, {
+ unitId,
+ headerFooterProps: {
+ [type]: val ? BooleanNumber.TRUE : BooleanNumber.FALSE,
+ },
+ sectionId: sectionContext?.sectionId,
+ });
+ }
+
+ layoutService.focus();
+ };
+
+ const handleMarginChange = async (val: number, type: 'marginHeader' | 'marginFooter') => {
+ setOptions((prev) => ({
+ ...prev,
+ [type]: val,
+ }));
+
+ await commandService.executeCommand(CoreHeaderFooterCommandId, {
+ unitId,
+ headerFooterProps: {
+ [type]: val,
+ },
+ sectionId: getCurrentSectionContext()?.sectionId,
+ });
+
+ // To make sure input always has focus.
+ docSelectionRenderService.removeAllRanges();
+ docSelectionRenderService.blur();
+ };
+
+ const closeHeaderFooter = () => {
+ commandService.executeCommand(CloseHeaderFooterCommand.id, {
+ unitId,
+ });
+ };
+
+ const handleLinkToPreviousChange = async (linked: boolean) => {
+ const context = getCurrentSectionContext();
+ if (!context?.sectionId || context.sectionIndex <= 0 || !docDataModel) {
+ return;
+ }
+ const currentEditArea = renderManagerService.getRenderUnitById(unitId)?.with(DocSkeletonManagerService)?.getViewModel()?.getEditArea();
+ const kind = currentEditArea === DocumentEditArea.FOOTER ? 'footer' : 'header';
+ const currentVariant = getHeaderFooterVariant(context.config, docSelectionRenderService.getSegmentPage(), context.page);
+ const key = getSectionHeaderFooterReferenceKey(kind, currentVariant);
+ const segmentId = generateRandomId(6);
+ const previousSegmentId = resolveSectionHeaderFooterReference(
+ docDataModel.getDocumentStyle(),
+ context.sections,
+ context.sectionIndex - 1,
+ key
+ ).segmentId;
+ const success = await commandService.executeCommand(SetSectionHeaderFooterLinkCommand.id, {
+ unitId,
+ sectionId: context.sectionId,
+ kind,
+ variant: currentVariant,
+ linkedToPrevious: linked,
+ ...(linked ? {} : { segmentId }),
+ });
+ if (!success) {
+ return;
+ }
+ setLinkedToPrevious(linked);
+ docSelectionRenderService.setSegment(linked ? previousSegmentId ?? '' : segmentId);
+ layoutService.focus();
+ };
+
+ return { canLinkToPrevious, linkedToPrevious, options, handleLinkToPreviousChange, handleCheckboxChange, handleMarginChange, closeHeaderFooter };
+}
+
+function getHeaderFooterVariant(documentStyle: IDocumentStyle, pageIndex: number, page?: IDocumentSkeletonPage) {
+ const isFirstPage = page ? page.pageNumber === page.pageNumberStart : pageIndex === 0;
+ const isEvenPage = page ? page.pageNumber % 2 === 0 : pageIndex % 2 === 1;
+ if (documentStyle.useFirstPageHeaderFooter === BooleanNumber.TRUE && isFirstPage) {
+ return 'first' as const;
+ }
+ if (documentStyle.evenAndOddHeaders === BooleanNumber.TRUE && isEvenPage) {
+ return 'even' as const;
+ }
+ return 'default' as const;
+}
diff --git a/packages/docs-ui/src/views/mobile-doc-toolbar/MobileDocToolbar.tsx b/packages/docs-ui/src/views/mobile-doc-toolbar/MobileDocToolbar.tsx
new file mode 100644
index 0000000000..87491dd802
--- /dev/null
+++ b/packages/docs-ui/src/views/mobile-doc-toolbar/MobileDocToolbar.tsx
@@ -0,0 +1,509 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IMenuSchema, IValueOption, MobileDrawerSnap } from '@univerjs/ui';
+import type { ReactNode } from 'react';
+import type { MobileDocSelectionRenderService } from '../../services/mobile/doc-selection-render.service';
+import { ICommandService, IUniverInstanceService, LocaleService, UniverInstanceType } from '@univerjs/core';
+import { clsx, resetButtonClassName } from '@univerjs/design';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import {
+ AlignTextBothIcon,
+ CheckMarkIcon,
+ CloseIcon,
+ KeyboardIcon,
+ MoreHorizontalIcon,
+ MoreLeftIcon,
+ QuickAddIcon,
+ TextIcon,
+ TextTypeIcon,
+ WriteIcon,
+} from '@univerjs/icons';
+import {
+ IMenuManagerService,
+ IWorkbenchService,
+ MobileDrawer,
+ MobileMenu,
+ RibbonInsertGroup,
+ RibbonStartGroup,
+ useDependency,
+ useObservable,
+} from '@univerjs/ui';
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import { map, startWith } from 'rxjs';
+import {
+ DOC_PARAGRAPH_T_ALIGN_MENU_ID,
+ DOC_PARAGRAPH_T_EDIT_MENU_ID,
+} from '../../menu/paragraph-menu';
+import { IEditorService } from '../../services/editor/editor-manager.service';
+import { DocSelectionRenderService } from '../../services/selection/doc-selection-render.service';
+
+type MobileDocDrawer = 'insert' | 'format' | 'more';
+type MobileDocQuickMenu = 'block' | 'align';
+
+interface IMobileDocMenuNavigation {
+ title?: string;
+ onBack: () => void;
+}
+
+interface IMobileDocMenuSchemas {
+ insert: IMenuSchema[];
+ format: IMenuSchema[];
+ more: IMenuSchema[];
+}
+
+interface IMobileDocToolbarButtonProps {
+ active: boolean;
+ label: string;
+ icon: ReactNode;
+ onClick: () => void;
+}
+
+const MOBILE_DOC_INSERT_GROUP = 'doc.mobile.insert';
+const MOBILE_DOC_FORMAT_QUICK_GROUP = 'doc.mobile.format.quick';
+const MOBILE_DOC_FORMAT_DETAIL_GROUP = 'doc.mobile.format.detail';
+const MOBILE_DOC_MORE_GROUP = 'doc.mobile.more';
+
+function getMobileDocFormatSchemas(schemas: IMenuSchema[]): IMenuSchema[] {
+ const quickSchemas = schemas.filter((schema) => schema.gridLayout?.row === 2);
+ const detailSchemas = schemas.filter((schema) => schema.gridLayout?.row !== 2);
+ const mobileSchemas: IMenuSchema[] = [];
+
+ if (quickSchemas.length) {
+ mobileSchemas.push({
+ key: MOBILE_DOC_FORMAT_QUICK_GROUP,
+ order: 0,
+ quickLayout: 'tile',
+ quickLayoutVariant: 'compact',
+ quickColumns: 4,
+ children: quickSchemas,
+ });
+ }
+
+ if (detailSchemas.length) {
+ mobileSchemas.push({
+ key: MOBILE_DOC_FORMAT_DETAIL_GROUP,
+ order: 1,
+ children: detailSchemas,
+ });
+ }
+
+ return mobileSchemas;
+}
+
+export function getMobileDocMenuSchemas(menuManagerService: IMenuManagerService): IMobileDocMenuSchemas {
+ const formatSchemas = menuManagerService.getMenuByPositionKey(RibbonStartGroup.FORMAT);
+ const moreSchemas = [
+ ...menuManagerService.getMenuByPositionKey(RibbonStartGroup.LAYOUT),
+ ...menuManagerService.getMenuByPositionKey(RibbonStartGroup.OTHERS),
+ ...menuManagerService.getMenuByPositionKey(RibbonInsertGroup.OTHERS),
+ ];
+
+ return {
+ insert: [{
+ key: MOBILE_DOC_INSERT_GROUP,
+ order: 0,
+ quickLayout: 'tile',
+ quickColumns: 4,
+ children: menuManagerService.getMenuByPositionKey(RibbonInsertGroup.MEDIA),
+ }],
+ format: getMobileDocFormatSchemas(formatSchemas),
+ more: [{
+ key: MOBILE_DOC_MORE_GROUP,
+ order: 0,
+ quickLayout: 'tile',
+ quickColumns: 4,
+ children: moreSchemas,
+ }],
+ };
+}
+
+export function getMobileDocMenuCommand(option: IValueOption): {
+ commandId: string;
+ params?: Record<string, unknown>;
+} | null {
+ const commandId = option.commandId ?? option.id;
+ if (!commandId) {
+ return null;
+ }
+
+ const fallbackParams = typeof option.params === 'function'
+ ? option.params(option.value)
+ : option.params;
+
+ return {
+ commandId,
+ params: typeof option.value === 'undefined' ? fallbackParams : { value: option.value },
+ };
+}
+
+function MobileDocToolbarButton(props: IMobileDocToolbarButtonProps) {
+ return (
+ <button
+ type="button"
+ aria-label={props.label}
+ aria-pressed={props.active}
+ className={clsx(resetButtonClassName, `
+ univer-flex univer-h-10 univer-min-w-0 univer-flex-1 univer-items-center univer-justify-center
+ univer-rounded-lg univer-text-xl univer-text-gray-700
+ active:univer-scale-95 active:univer-bg-gray-100
+ dark:!univer-text-gray-200
+ dark:active:!univer-bg-gray-700
+ `, props.active && `
+ univer-bg-primary-50 univer-text-primary-600
+ dark:!univer-bg-primary-900
+ `)}
+ onClick={props.onClick}
+ >
+ {props.icon}
+ </button>
+ );
+}
+
+function useMobileDocEditState() {
+ const editorService = useDependency(IEditorService);
+ const instanceService = useDependency(IUniverInstanceService);
+ const renderManagerService = useDependency(IRenderManagerService);
+ const currentDoc = useObservable(
+ () => instanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_DOC),
+ null,
+ true,
+ [instanceService]
+ );
+ const unitId = currentDoc?.getUnitId();
+ const selectionService = unitId
+ ? renderManagerService.getRenderUnitById(unitId)?.with(DocSelectionRenderService) as MobileDocSelectionRenderService | undefined
+ : undefined;
+ const isEditing = useObservable(
+ selectionService?.mobileEditMode$,
+ selectionService?.isMobileEditMode ?? false
+ );
+ return {
+ isEditing,
+ isReadOnly: unitId ? editorService.getEditor(unitId)?.isReadOnly() === true : true,
+ selectionService,
+ };
+}
+
+export function MobileDocEditDoneButton() {
+ const localeService = useDependency(LocaleService);
+ const { isEditing, isReadOnly, selectionService } = useMobileDocEditState();
+
+ if (!isEditing || isReadOnly) {
+ return null;
+ }
+
+ return (
+ <button
+ type="button"
+ aria-label={localeService.t('docs-ui.mobile.done')}
+ className={clsx(resetButtonClassName, `
+ univer-flex univer-size-10 univer-items-center univer-justify-center univer-rounded-lg
+ univer-text-primary-600
+ active:univer-bg-primary-50
+ dark:!univer-text-primary-400
+ dark:active:!univer-bg-primary-900
+ `)}
+ onClick={() => selectionService?.exitMobileEditMode()}
+ >
+ <CheckMarkIcon className="univer-size-6" />
+ </button>
+ );
+}
+
+export function MobileDocToolbar() {
+ const commandService = useDependency(ICommandService);
+ const localeService = useDependency(LocaleService);
+ const menuManagerService = useDependency(IMenuManagerService);
+ const workbenchService = useDependency(IWorkbenchService);
+ const rootUnitType = useObservable(workbenchService.rootUnitType$, null, true);
+ const { isEditing, isReadOnly, selectionService } = useMobileDocEditState();
+ const keyboardState = useObservable(
+ selectionService?.mobileKeyboardState$,
+ { visible: false, inset: 0 }
+ );
+ const keyboardVisible = keyboardState.visible;
+ const [drawer, setDrawer] = useState<MobileDocDrawer | null>(null);
+ const [quickMenu, setQuickMenu] = useState<MobileDocQuickMenu | null>(null);
+ const [drawerSnap, setDrawerSnap] = useState<MobileDrawerSnap>('compact');
+ const [navigation, setNavigation] = useState<IMobileDocMenuNavigation | null>(null);
+ const menuSchemas = useObservable(
+ () => menuManagerService.menuChanged$.pipe(
+ startWith(undefined),
+ map(() => getMobileDocMenuSchemas(menuManagerService))
+ ),
+ { insert: [], format: [], more: [] },
+ false,
+ [menuManagerService]
+ );
+
+ const closeDrawer = useCallback(() => {
+ setDrawer(null);
+ setDrawerSnap('compact');
+ setNavigation(null);
+ }, []);
+ useEffect(() => {
+ const subscription = selectionService?.onFocus$.subscribe(() => {
+ closeDrawer();
+ setQuickMenu(null);
+ });
+ return () => subscription?.unsubscribe();
+ }, [selectionService, closeDrawer]);
+ const drawerSchemas = useMemo(() => drawer ? menuSchemas[drawer] : [], [drawer, menuSchemas]);
+
+ if (rootUnitType !== UniverInstanceType.UNIVER_DOC) {
+ return null;
+ }
+
+ if (!isEditing) {
+ if (isReadOnly) {
+ return null;
+ }
+
+ return (
+ <button
+ type="button"
+ aria-label={localeService.t('docs-ui.mobile.edit')}
+ className={clsx(resetButtonClassName, `
+ univer-pointer-events-auto univer-absolute univer-bottom-4 univer-z-30 univer-flex univer-size-14
+ univer-items-center univer-justify-center univer-rounded-full univer-bg-primary-600 univer-text-2xl
+ univer-text-white univer-shadow-lg
+ active:univer-scale-95 active:univer-bg-primary-700
+ dark:!univer-bg-primary-500
+ dark:active:!univer-bg-primary-600
+ `)}
+ style={{
+ insetInlineEnd: '1rem',
+ marginBottom: 'env(safe-area-inset-bottom, 0px)',
+ }}
+ onClick={() => {
+ closeDrawer();
+ setQuickMenu(null);
+ selectionService?.enterMobileEditMode();
+ }}
+ >
+ <WriteIcon />
+ </button>
+ );
+ }
+
+ function executeMenuItem(option: IValueOption) {
+ const command = getMobileDocMenuCommand(option);
+ if (command) {
+ commandService.executeCommand(command.commandId, command.params).catch(() => undefined);
+ }
+ }
+
+ function openDrawer(nextDrawer: MobileDocDrawer) {
+ if (drawer === nextDrawer) {
+ closeDrawer();
+ return;
+ }
+
+ if (document.activeElement instanceof HTMLElement) {
+ document.activeElement.blur();
+ }
+ setQuickMenu(null);
+ setNavigation(null);
+ setDrawerSnap('compact');
+ setDrawer(nextDrawer);
+ }
+
+ function toggleQuickMenu(nextMenu: MobileDocQuickMenu) {
+ closeDrawer();
+ setQuickMenu((current) => current === nextMenu ? null : nextMenu);
+ }
+
+ function openKeyboard() {
+ closeDrawer();
+ setQuickMenu(null);
+ selectionService?.enterMobileEditMode(true);
+ }
+
+ function hideKeyboard() {
+ closeDrawer();
+ setQuickMenu(null);
+ selectionService?.suspendMobileEditingInput();
+ }
+
+ const drawerTitle = navigation?.title ?? localeService.t(
+ drawer === 'insert'
+ ? 'docs-ui.mobile.insert'
+ : drawer === 'format'
+ ? 'docs-ui.mobile.format'
+ : 'docs-ui.mobile.more'
+ );
+ const quickMenuType = quickMenu === 'block'
+ ? DOC_PARAGRAPH_T_EDIT_MENU_ID
+ : DOC_PARAGRAPH_T_ALIGN_MENU_ID;
+
+ return (
+ <>
+ {keyboardVisible && quickMenu && (
+ <div
+ className="
+ univer-pointer-events-auto univer-absolute univer-inset-x-3 univer-z-30 univer-overflow-hidden
+ "
+ style={{ bottom: `${keyboardState.inset + 48}px` }}
+ >
+ <MobileMenu
+ menuType={quickMenuType}
+ presentation="context-bar"
+ onOptionSelect={executeMenuItem}
+ />
+ </div>
+ )}
+
+ {keyboardVisible && !drawer && (
+ <div
+ className="
+ univer-pointer-events-auto univer-absolute univer-inset-x-0 univer-z-30 univer-box-border
+ univer-flex univer-h-12 univer-items-center univer-gap-0.5 univer-border-0 univer-border-t
+ univer-border-solid univer-border-gray-200 univer-bg-gray-0 univer-px-1
+ dark:!univer-border-gray-700 dark:!univer-bg-gray-800
+ "
+ style={{
+ bottom: `${keyboardState.inset}px`,
+ paddingBottom: 'env(safe-area-inset-bottom, 0px)',
+ }}
+ >
+ <MobileDocToolbarButton
+ active={false}
+ label={localeService.t('docs-ui.mobile.insert')}
+ icon={<QuickAddIcon />}
+ onClick={() => openDrawer('insert')}
+ />
+ <MobileDocToolbarButton
+ active={quickMenu === 'block'}
+ label={localeService.t('docs-ui.toolbar.heading.tooltip')}
+ icon={<TextTypeIcon />}
+ onClick={() => toggleQuickMenu('block')}
+ />
+ <MobileDocToolbarButton
+ active={false}
+ label={localeService.t('docs-ui.mobile.format')}
+ icon={<TextIcon />}
+ onClick={() => openDrawer('format')}
+ />
+ <MobileDocToolbarButton
+ active={quickMenu === 'align'}
+ label={localeService.t('docs-ui.paragraphMenu.alignAndIndent')}
+ icon={<AlignTextBothIcon />}
+ onClick={() => toggleQuickMenu('align')}
+ />
+ <MobileDocToolbarButton
+ active={false}
+ label={localeService.t('docs-ui.mobile.more')}
+ icon={<MoreHorizontalIcon />}
+ onClick={() => openDrawer('more')}
+ />
+ <MobileDocToolbarButton
+ active={false}
+ label={localeService.t('docs-ui.mobile.hideKeyboard')}
+ icon={<CloseIcon />}
+ onClick={hideKeyboard}
+ />
+ </div>
+ )}
+
+ {drawer && (
+ <MobileDrawer
+ componentName="mobile-doc-toolbar-drawer"
+ snap={drawerSnap}
+ expandLabel={localeService.t('docs-ui.mobile.expand')}
+ collapseLabel={localeService.t('docs-ui.mobile.collapse')}
+ onSnapChange={setDrawerSnap}
+ onClose={closeDrawer}
+ 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
+ "
+ >
+ <div>
+ {navigation && (
+ <button
+ type="button"
+ aria-label={localeService.t('docs-ui.mobile.back')}
+ className={clsx(resetButtonClassName, `
+ univer-flex univer-size-12 univer-items-center univer-justify-center
+ univer-rounded-lg univer-text-2xl univer-text-gray-700
+ active:univer-bg-gray-100
+ dark:!univer-text-gray-200
+ dark:active:!univer-bg-gray-700
+ `)}
+ onClick={navigation.onBack}
+ >
+ <MoreLeftIcon />
+ </button>
+ )}
+ </div>
+ <div
+ className="
+ univer-truncate univer-text-center univer-text-base univer-font-semibold
+ univer-text-gray-900
+ dark:!univer-text-gray-100
+ "
+ >
+ {drawerTitle}
+ </div>
+ <button
+ type="button"
+ aria-label={localeService.t('docs-ui.mobile.close')}
+ className={clsx(resetButtonClassName, `
+ univer-flex univer-size-12 univer-items-center univer-justify-center univer-rounded-lg
+ univer-text-2xl univer-text-gray-700
+ active:univer-bg-gray-100
+ dark:!univer-text-gray-200
+ dark:active:!univer-bg-gray-700
+ `)}
+ onClick={closeDrawer}
+ >
+ <CloseIcon />
+ </button>
+ </div>
+ )}
+ floatingActions={(
+ <button
+ type="button"
+ aria-label={localeService.t('docs-ui.mobile.keyboard')}
+ className={clsx(resetButtonClassName, `
+ univer-pointer-events-auto univer-flex univer-size-12 univer-items-center
+ univer-justify-center univer-rounded-full univer-bg-gray-0 univer-text-xl
+ univer-text-primary-600 univer-shadow-lg
+ active:univer-bg-gray-100
+ dark:!univer-bg-gray-800 dark:!univer-text-primary-400
+ dark:active:!univer-bg-gray-700
+ `)}
+ onClick={openKeyboard}
+ >
+ <KeyboardIcon />
+ </button>
+ )}
+ >
+ <MobileMenu
+ schemas={drawerSchemas}
+ menuManagerService={menuManagerService}
+ showHeader={false}
+ onNavigationChange={setNavigation}
+ onOptionSelect={executeMenuItem}
+ />
+ </MobileDrawer>
+ )}
+ </>
+ );
+}
diff --git a/packages/docs-ui/src/views/mobile-doc-toolbar/__tests__/MobileDocToolbar.spec.ts b/packages/docs-ui/src/views/mobile-doc-toolbar/__tests__/MobileDocToolbar.spec.ts
new file mode 100644
index 0000000000..d0401d05a5
--- /dev/null
+++ b/packages/docs-ui/src/views/mobile-doc-toolbar/__tests__/MobileDocToolbar.spec.ts
@@ -0,0 +1,253 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @vitest-environment jsdom
+ */
+
+import type { IMenuManagerService, IMenuSchema } from '@univerjs/ui';
+import type { Root } from 'react-dom/client';
+import {
+ ContextService,
+ DocumentDataModel,
+ IContextService,
+ ILogService,
+ Injector,
+ IUniverInstanceService,
+ LocaleService,
+ UniverInstanceService,
+} from '@univerjs/core';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { RediContext, RibbonInsertGroup, RibbonStartGroup } from '@univerjs/ui';
+import { act, createElement, StrictMode } from 'react';
+import { createRoot } from 'react-dom/client';
+import { EMPTY, Subject } from 'rxjs';
+import { afterEach, describe, expect, it } from 'vitest';
+import { IEditorService } from '../../../services/editor/editor-manager.service';
+import {
+ getMobileDocMenuCommand,
+ getMobileDocMenuSchemas,
+ MobileDocEditDoneButton,
+} from '../MobileDocToolbar';
+
+class TestLogService {
+ debug(): void {}
+ warn(): void {}
+}
+
+class TestEditorService implements IEditorService {
+ readonly blur$ = EMPTY;
+ readonly focus$ = EMPTY;
+
+ getEditor(): ReturnType<IEditorService['getEditor']> {
+ return null;
+ }
+
+ register(): ReturnType<IEditorService['register']> {
+ return { dispose: () => undefined };
+ }
+
+ getAllEditor(): ReturnType<IEditorService['getAllEditor']> {
+ return new Map();
+ }
+
+ isEditor(): boolean {
+ return false;
+ }
+
+ getEditorRenderConfig(): ReturnType<IEditorService['getEditorRenderConfig']> {
+ return null;
+ }
+
+ isSheetEditor(): boolean {
+ return false;
+ }
+
+ blur(): void {}
+ focus(): void {}
+
+ getFocusId(): ReturnType<IEditorService['getFocusId']> {
+ return null;
+ }
+
+ getFocusEditor(): ReturnType<IEditorService['getFocusEditor']> {
+ return null;
+ }
+}
+
+class TestRenderManagerService implements IRenderManagerService {
+ readonly created$ = EMPTY;
+ readonly disposed$ = EMPTY;
+
+ get defaultEngine(): IRenderManagerService['defaultEngine'] {
+ throw new Error('Not used in this test');
+ }
+
+ addRender(): void {}
+
+ createRender(): ReturnType<IRenderManagerService['createRender']> {
+ throw new Error('Not used in this test');
+ }
+
+ removeRender(): void {}
+
+ getRenderUnitById(): ReturnType<IRenderManagerService['getRenderUnitById']> {
+ return null;
+ }
+
+ getAllRenderersOfType(): ReturnType<IRenderManagerService['getAllRenderersOfType']> {
+ return [];
+ }
+
+ getRenderAll(): ReturnType<IRenderManagerService['getRenderAll']> {
+ return new Map();
+ }
+
+ has(): boolean {
+ return false;
+ }
+
+ registerRenderModule(): ReturnType<IRenderManagerService['registerRenderModule']> {
+ return { dispose: () => undefined };
+ }
+
+ dispose(): void {}
+}
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+function createMenuManager(entries: Array<[string, IMenuSchema[]]>): IMenuManagerService {
+ const schemas = new Map(entries);
+
+ return {
+ menuChanged$: new Subject<void>(),
+ mergeMenu: () => undefined,
+ appendRootMenu: () => undefined,
+ getMenuByPositionKey: (position) => schemas.get(position) ?? [],
+ getFlatMenuByPositionKey: (position) => schemas.get(position) ?? [],
+ };
+}
+
+describe('getMobileDocMenuCommand', () => {
+ it('uses an explicit command id and selected value', () => {
+ expect(getMobileDocMenuCommand({
+ id: 'menu-id',
+ commandId: 'command-id',
+ value: 'selected',
+ params: { ignored: true },
+ })).toEqual({
+ commandId: 'command-id',
+ params: { value: 'selected' },
+ });
+ });
+
+ it('resolves command parameters when no selected value is present', () => {
+ expect(getMobileDocMenuCommand({
+ id: 'command-id',
+ params: () => ({ enabled: true }),
+ })).toEqual({
+ commandId: 'command-id',
+ params: { enabled: true },
+ });
+ });
+
+ it('ignores options without a command', () => {
+ expect(getMobileDocMenuCommand({})).toBeNull();
+ });
+});
+
+describe('getMobileDocMenuSchemas', () => {
+ it('adapts standard ribbon groups into mobile insert, format, and more surfaces', () => {
+ const insertItem = { key: 'image', order: 0 };
+ const formatDetail = { key: 'font', order: 0, gridLayout: { row: 1, column: 1 } };
+ const formatQuick = { key: 'bold', order: 1, gridLayout: { row: 2, column: 1 } };
+ const layoutItem = { key: 'align', order: 0, gridLayout: { row: 1, column: 1 } };
+ const otherItem = { key: 'find', order: 0 };
+ const insertOtherItem = { key: 'object-list', order: 0 };
+ const menuManager = createMenuManager([
+ [RibbonInsertGroup.MEDIA, [insertItem]],
+ [RibbonStartGroup.FORMAT, [formatDetail, formatQuick]],
+ [RibbonStartGroup.LAYOUT, [layoutItem]],
+ [RibbonStartGroup.OTHERS, [otherItem]],
+ [RibbonInsertGroup.OTHERS, [insertOtherItem]],
+ ]);
+
+ const schemas = getMobileDocMenuSchemas(menuManager);
+
+ expect(schemas.insert[0].children).toEqual([insertItem]);
+ expect(schemas.insert[0].quickLayout).toBe('tile');
+ expect(schemas.format[0].children).toEqual([formatQuick]);
+ expect(schemas.format[0].quickLayoutVariant).toBe('compact');
+ expect(schemas.format[1].children).toEqual([formatDetail]);
+ expect(schemas.more[0].children).toEqual([layoutItem, otherItem, insertOtherItem]);
+ expect(schemas.more[0].quickLayout).toBe('tile');
+ });
+});
+
+describe('MobileDocEditDoneButton', () => {
+ let root: Root | undefined;
+ let container: HTMLElement | undefined;
+
+ afterEach(() => {
+ if (root) {
+ act(() => root?.unmount());
+ }
+ container?.remove();
+ root = undefined;
+ container = undefined;
+ });
+
+ it('mounts in strict mode without resubscribing during render', () => {
+ const injector = new Injector();
+ injector.add([ILogService, { useClass: TestLogService }]);
+ injector.add([IContextService, { useClass: ContextService }]);
+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);
+ injector.add([LocaleService]);
+ injector.add([IEditorService, { useClass: TestEditorService }]);
+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService }]);
+
+ const doc = new DocumentDataModel({
+ id: 'mobile-doc-toolbar-doc',
+ body: {
+ dataStream: '\r\n',
+ paragraphs: [],
+ sectionBreaks: [],
+ customRanges: [],
+ tables: [],
+ textRuns: [],
+ },
+ });
+ injector.get(IUniverInstanceService).__addUnit(doc);
+
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ act(() => {
+ root?.render(createElement(
+ StrictMode,
+ null,
+ createElement(
+ RediContext.Provider,
+ { value: { injector } },
+ createElement(MobileDocEditDoneButton)
+ )
+ ));
+ });
+
+ expect(container.innerHTML).toBe('');
+ });
+});
diff --git a/packages/docs-ui/src/views/mobile-element-menu/MobileDocElementMenu.tsx b/packages/docs-ui/src/views/mobile-element-menu/MobileDocElementMenu.tsx
new file mode 100644
index 0000000000..584af416bc
--- /dev/null
+++ b/packages/docs-ui/src/views/mobile-element-menu/MobileDocElementMenu.tsx
@@ -0,0 +1,50 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IMenuSchema, IPopupWithExtraProps } from '@univerjs/ui';
+import { MenuItemType, MobileMenu } from '@univerjs/ui';
+
+export const MOBILE_DOC_ELEMENT_MENU = 'docs-ui.mobile-element-menu';
+
+export interface IMobileDocElementMenuProps {
+ onEdit: () => unknown;
+ onDelete: () => unknown;
+}
+
+const schemas: IMenuSchema[] = [
+ { key: 'edit', order: 0, item: { id: 'edit', type: MenuItemType.BUTTON, title: 'docs-ui.mobile.edit' } },
+ { key: 'delete', order: 1, item: { id: 'delete', type: MenuItemType.BUTTON, title: 'docs-ui.rightClick.delete' } },
+];
+
+export function MobileDocElementMenu(props: IMobileDocElementMenuProps) {
+ return (
+ <MobileMenu
+ schemas={schemas}
+ presentation="context-bar"
+ onOptionSelect={async ({ id }) => {
+ if (id === 'edit') {
+ await props.onEdit();
+ } else if (id === 'delete') {
+ await props.onDelete();
+ }
+ }}
+ />
+ );
+}
+
+export function MobileDocElementMenuPopup({ popup }: { popup: IPopupWithExtraProps<IMobileDocElementMenuProps> }) {
+ return <MobileDocElementMenu {...popup.extraProps} />;
+}
diff --git a/packages/docs-ui/src/views/mobile-rich-text-editor/MobileRichTextEditor.tsx b/packages/docs-ui/src/views/mobile-rich-text-editor/MobileRichTextEditor.tsx
new file mode 100644
index 0000000000..768d363523
--- /dev/null
+++ b/packages/docs-ui/src/views/mobile-rich-text-editor/MobileRichTextEditor.tsx
@@ -0,0 +1,162 @@
+/**
+ * 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 '../../services/editor/editor';
+import type { IRichTextEditorProps } from '../RichTextEditor';
+import { Button, clsx } from '@univerjs/design';
+import { DocSkeletonManagerService } from '@univerjs/docs';
+import { CheckMarkIcon, CloseIcon, DownIcon } from '@univerjs/icons';
+import { MobileKeyboardInsetContext, useEvent, useMobileCanvasPanel } from '@univerjs/ui';
+import { useContext, useEffect, useRef, useState } from 'react';
+import { MobileRichTextToolbar } from '../mobile-rich-text-toolbar/MobileRichTextToolbar';
+import { RichTextEditor } from '../RichTextEditor';
+
+interface IMobileRichTextEditorProps extends Pick<IRichTextEditorProps, 'initialValue' | 'editorId' | 'autoFocus' | 'canvasStyle' | 'keyboardEventConfig' | 'onChange'> {
+ editorId: string;
+ expanded: boolean;
+ onExpandedChange: (expanded: boolean) => void;
+ onCancel: () => void;
+ onConfirm: () => void;
+ labels: { title: string; cancel: string; confirm: string; expand: string; collapse: string };
+}
+
+/** Compact object text input; expanding keeps the same document editor mounted. */
+export function MobileRichTextEditor(props: IMobileRichTextEditorProps) {
+ const { expanded, onExpandedChange, onCancel, onConfirm, labels } = props;
+ const containerRef = useRef<HTMLElement>(null);
+ const pointerStartedInsideRef = useRef(false);
+ const keyboardInset = useContext(MobileKeyboardInsetContext);
+ const keyboardWasVisibleRef = useRef(false);
+ const [editor, setEditor] = useState<Editor | null>(null);
+ const [contentHeight, setContentHeight] = useState(0);
+ const confirmOnDismiss = useEvent(onConfirm);
+ useMobileCanvasPanel(containerRef, expanded ? 'modal' : 'canvas');
+
+ useEffect(() => {
+ const subscription = editor?.render.with(DocSkeletonManagerService).currentSkeleton$.subscribe((skeleton) => {
+ if (skeleton) {
+ setContentHeight(skeleton.getActualSize().actualHeight);
+ }
+ });
+ return () => subscription?.unsubscribe();
+ }, [editor]);
+
+ useEffect(() => {
+ const visible = keyboardInset > 80;
+ if (keyboardWasVisibleRef.current && !visible) {
+ confirmOnDismiss();
+ }
+ keyboardWasVisibleRef.current = visible;
+ }, [confirmOnDismiss, keyboardInset]);
+
+ const buttonClassName = clsx('univer-h-12 univer-shrink-0 univer-text-lg', expanded
+ ? 'univer-flex-1'
+ : 'univer-w-10');
+ const expandButton = (
+ <Button
+ variant="ghost"
+ className={buttonClassName}
+ aria-label={expanded ? labels.collapse : labels.expand}
+ aria-expanded={expanded}
+ onPointerDown={(event) => event.preventDefault()}
+ onClick={() => onExpandedChange(!expanded)}
+ >
+ <DownIcon className={clsx('univer-size-5', !expanded && 'univer-rotate-180')} />
+ </Button>
+ );
+
+ return (
+ <section
+ ref={containerRef}
+ role="region"
+ aria-label={labels.title}
+ className={clsx(`
+ univer-pointer-events-auto univer-absolute univer-inset-x-0 univer-z-40 univer-flex univer-bg-gray-0
+ univer-shadow-lg
+ dark:!univer-bg-gray-800
+ `, expanded
+ ? 'univer-inset-0 univer-z-50 univer-size-full univer-flex-col'
+ : 'univer-min-h-12 univer-items-center')}
+ style={{
+ backgroundColor: props.canvasStyle?.backgroundColor,
+ bottom: expanded ? undefined : keyboardInset,
+ paddingBottom: expanded ? 'env(safe-area-inset-bottom, 0px)' : undefined,
+ paddingTop: expanded ? 'env(safe-area-inset-top, 0px)' : undefined,
+ }}
+ onPointerDownCapture={() => { pointerStartedInsideRef.current = true; }}
+ onPointerCancelCapture={() => { pointerStartedInsideRef.current = false; }}
+ onClickCapture={(event) => {
+ // Opening on canvas pointer-up must not activate controls inserted under that touch.
+ if (event.detail > 0 && !pointerStartedInsideRef.current) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ pointerStartedInsideRef.current = false;
+ }}
+ onPointerDown={(event) => event.stopPropagation()}
+ onPointerMove={(event) => event.stopPropagation()}
+ onPointerUp={(event) => event.stopPropagation()}
+ >
+ <div
+ className={clsx('univer-flex univer-shrink-0 univer-items-center', expanded && `
+ univer-h-12 univer-bg-gray-0
+ dark:!univer-bg-gray-800
+ `)}
+ >
+ <Button variant="ghost" className={buttonClassName} aria-label={labels.cancel} onPointerDown={(event) => event.preventDefault()} onClick={onCancel}>
+ <CloseIcon />
+ </Button>
+ <Button variant="ghost" className={clsx(buttonClassName, 'univer-text-primary-600')} aria-label={labels.confirm} onPointerDown={(event) => event.preventDefault()} onClick={onConfirm}>
+ <CheckMarkIcon />
+ </Button>
+ {expanded && expandButton}
+ </div>
+ {expanded && (
+ <MobileRichTextToolbar
+ editorId={props.editorId}
+ className="univer-shrink-0"
+ />
+ )}
+ <div
+ className={clsx('univer-min-w-0 univer-flex-1', expanded
+ ? 'univer-min-h-0 univer-overflow-hidden univer-p-3'
+ : 'univer-py-2')}
+ >
+ <RichTextEditor
+ className="
+ univer-w-full univer-text-base
+ [&>div]:!univer-h-full
+ "
+ style={{ height: expanded ? '100%' : Math.min(120, Math.ceil(contentHeight) + 8) }}
+ editorRef={setEditor}
+ editorId={props.editorId}
+ initialValue={props.initialValue}
+ autoFocus={props.autoFocus}
+ preserveHostFocus
+ moveCursor
+ noStyle
+ isSingle={!expanded}
+ canvasStyle={props.canvasStyle}
+ keyboardEventConfig={props.keyboardEventConfig}
+ defaultHeight={40}
+ maxHeight={expanded ? 10_000 : 120}
+ onChange={props.onChange}
+ />
+ </div>
+ {!expanded && expandButton}
+ </section>
+ );
+}
diff --git a/packages/docs-ui/src/views/mobile/MobileDocCanvasViewport.tsx b/packages/docs-ui/src/views/mobile/MobileDocCanvasViewport.tsx
new file mode 100644
index 0000000000..c4c30e0c3d
--- /dev/null
+++ b/packages/docs-ui/src/views/mobile/MobileDocCanvasViewport.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 { RefObject } from 'react';
+import { IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { DocSelectionManagerService } from '@univerjs/docs';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import {
+ getMobileCanvasPanDelta,
+ IWorkbenchService,
+ useDependency,
+ useMobileCanvasViewport,
+ useObservable,
+} from '@univerjs/ui';
+import { VIEWPORT_KEY } from '../../basics/docs-view-key';
+import { DocMobileElementMenuService } from '../../services/doc-mobile-element-menu.service';
+import { calcDocRangePositions, transformBound2OffsetBound } from '../../services/doc-popup-manager.service';
+
+export function MobileDocCanvasViewport({ containerRef, canvasRef }: {
+ containerRef: RefObject<HTMLElement | null>;
+ canvasRef: RefObject<HTMLElement | null>;
+}) {
+ const instances = useDependency(IUniverInstanceService);
+ const renders = useDependency(IRenderManagerService);
+ const elements = useDependency(DocMobileElementMenuService);
+ const selections = useDependency(DocSelectionManagerService);
+ const workbench = useDependency(IWorkbenchService);
+ const rootUnitType = useObservable(workbench.rootUnitType$, null, true);
+ useMobileCanvasViewport({
+ containerRef,
+ canvasRef,
+ // Docs UI is also loaded for embedded text editors in other products.
+ // Only a document workbench may resize this outer content container.
+ enabled: rootUnitType === UniverInstanceType.UNIVER_DOC,
+ panelsOnly: true,
+ onReveal: () => {
+ const doc = instances.getCurrentUnitOfType(UniverInstanceType.UNIVER_DOC);
+ const render = doc && renders.getRenderUnitById(doc.getUnitId());
+ const viewport = render?.scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
+ if (!render || !viewport) {
+ return;
+ }
+ const selected = render.scene.getTransformer()?.getSelectedObjectMap().values().next().value;
+ const target = elements.getEditingBounds(render.unitId);
+ let bounds = target
+ ? transformBound2OffsetBound(target, render.scene)
+ : selected && transformBound2OffsetBound({
+ left: selected.left,
+ top: selected.top,
+ right: selected.left + selected.width,
+ bottom: selected.top + selected.height,
+ }, render.scene);
+ if (!bounds) {
+ const range = selections.getActiveTextRange();
+ const rangeBounds = range && calcDocRangePositions(range, render)?.[0];
+ if (rangeBounds) {
+ const canvas = render.engine.getCanvasElement().getBoundingClientRect();
+ bounds = {
+ left: rangeBounds.left - canvas.left,
+ top: rangeBounds.top - canvas.top,
+ right: rangeBounds.right - canvas.left,
+ bottom: rangeBounds.bottom - canvas.top,
+ };
+ }
+ }
+ const canvasBounds = canvasRef.current?.getBoundingClientRect();
+ if (!bounds || !canvasBounds) {
+ return;
+ }
+ const delta = getMobileCanvasPanDelta({
+ left: bounds.left,
+ top: bounds.top,
+ width: bounds.right - bounds.left,
+ height: bounds.bottom - bounds.top,
+ }, canvasBounds);
+ if (delta.x === 0 && delta.y === 0) {
+ return;
+ }
+ const scale = render.scene.getAncestorScale();
+ viewport.scrollToViewportPos({
+ viewportScrollX: viewport.viewportScrollX - delta.x / scale.scaleX,
+ viewportScrollY: viewport.viewportScrollY - delta.y / scale.scaleY,
+ });
+ },
+ });
+ return null;
+}
diff --git a/packages/docs-ui/src/views/mobile/MobileDocSettings.tsx b/packages/docs-ui/src/views/mobile/MobileDocSettings.tsx
new file mode 100644
index 0000000000..a4da7136d1
--- /dev/null
+++ b/packages/docs-ui/src/views/mobile/MobileDocSettings.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 { IConfirmChildrenProps } from '@univerjs/ui';
+import type { ComponentProps, ReactNode } from 'react';
+import type { LocaleKey } from '../../locale/types';
+import type { IParagraphAlignmentButtonProps, IParagraphSettingProps } from '../paragraph-setting/Setting';
+import { BooleanNumber, LocaleService } from '@univerjs/core';
+import { Button, Checkbox, clsx, InputNumber, MobileSelect } from '@univerjs/design';
+import { useDependency } from '@univerjs/ui';
+import { forwardRef } from 'react';
+import { DocHeaderFooterPanel } from '../header-footer/panel/DocHeaderFooterPanel';
+import { useHeaderFooterOptions } from '../header-footer/panel/use-header-footer-options';
+import { PageSettings } from '../PageSettings';
+import { ParagraphSettingIndex } from '../paragraph-setting/index';
+import { SectionSettingIndex } from '../section-setting/index';
+
+function MobileSettingRow({ label, unit, children }: { label: ReactNode; unit?: string; children: ReactNode }) {
+ return (
+ <div className="univer-flex univer-min-h-12 univer-flex-col univer-gap-2">
+ <div
+ className="
+ univer-text-sm univer-text-gray-900
+ dark:!univer-text-gray-100
+ "
+ >
+ {label}
+ {unit}
+ </div>
+ <div className="univer-w-full univer-min-w-0">{children}</div>
+ </div>
+ );
+}
+
+const MobileSettingNumber = forwardRef<HTMLInputElement, ComponentProps<typeof InputNumber>>((props, ref) => (
+ <InputNumber
+ {...props}
+ ref={ref}
+ className={clsx(props.className, 'univer-h-12 univer-w-full')}
+ inputClassName={clsx(props.inputClassName, 'univer-text-base')}
+ />
+));
+
+function MobileSettingSelect(props: ComponentProps<typeof MobileSelect>) {
+ return <MobileSelect {...props} className={clsx(props.className, 'univer-h-12 univer-w-full')} />;
+}
+
+function MobileParagraphNumber({ min = 0, max = 100, step = 0.1, precision = 1, onChange, ...props }: ComponentProps<NonNullable<IParagraphSettingProps['NumberComponent']>>) {
+ return <MobileSettingNumber {...props} min={min} max={max} step={step} precision={precision} onChange={(value) => onChange(value ?? 0)} />;
+}
+
+function MobileParagraphAlignmentButton({ label, selected, onClick, children }: IParagraphAlignmentButtonProps) {
+ return (
+ <Button
+ type="button"
+ variant="text"
+ aria-label={label}
+ aria-pressed={selected}
+ className={clsx('univer-h-12 univer-w-full', { '!univer-bg-gray-200 dark:!univer-bg-gray-700': selected })}
+ onClick={onClick}
+ >
+ <span className="univer-flex univer-size-5 univer-items-center univer-justify-center univer-text-lg">
+ {children}
+ </span>
+ </Button>
+ );
+}
+
+export function MobilePageSettings(props: IConfirmChildrenProps) {
+ return <PageSettings {...props} InputNumberComponent={MobileSettingNumber} SelectComponent={MobileSettingSelect} />;
+}
+
+export function MobileParagraphSettings() {
+ return (
+ <ParagraphSettingIndex
+ RowComponent={MobileSettingRow}
+ NumberComponent={MobileParagraphNumber}
+ SelectComponent={MobileSettingSelect}
+ AlignmentButtonComponent={MobileParagraphAlignmentButton}
+ />
+ );
+}
+
+export function MobileSectionSettings() {
+ return <SectionSettingIndex RowComponent={MobileSettingRow} InputNumberComponent={MobileSettingNumber} SelectComponent={MobileSettingSelect} />;
+}
+
+export function MobileHeaderFooterPanel() {
+ return <DocHeaderFooterPanel ContentComponent={MobileHeaderFooterOptions} />;
+}
+
+function MobileHeaderFooterOptions({ unitId }: { unitId: string }) {
+ const localeService = useDependency(LocaleService);
+ const { canLinkToPrevious, linkedToPrevious, options, handleLinkToPreviousChange, handleCheckboxChange, handleMarginChange, closeHeaderFooter } = useHeaderFooterOptions(unitId);
+ return (
+ <div className="univer-grid univer-gap-4">
+ {canLinkToPrevious && (
+ <div className="univer-flex univer-min-h-12 univer-items-center">
+ <Checkbox checked={linkedToPrevious} onChange={(val) => { handleLinkToPreviousChange(Boolean(val)); }}>
+ {localeService.t<LocaleKey>('docs-ui.headerFooter.linkToPrevious')}
+ </Checkbox>
+ </div>
+ )}
+ <div className="univer-grid univer-gap-2">
+ <div className="univer-flex univer-min-h-12 univer-items-center">
+ <Checkbox
+ checked={options.useFirstPageHeaderFooter === BooleanNumber.TRUE}
+ onChange={(val) => { handleCheckboxChange(Boolean(val), 'useFirstPageHeaderFooter'); }}
+ >
+ {localeService.t<LocaleKey>('docs-ui.headerFooter.firstPageCheckBox')}
+ </Checkbox>
+ </div>
+ <div className="univer-flex univer-min-h-12 univer-items-center">
+ <Checkbox
+ checked={options.evenAndOddHeaders === BooleanNumber.TRUE}
+ onChange={(val) => { handleCheckboxChange(Boolean(val), 'evenAndOddHeaders'); }}
+ >
+ {localeService.t<LocaleKey>('docs-ui.headerFooter.oddEvenCheckBox')}
+ </Checkbox>
+ </div>
+ </div>
+
+ <div className="univer-mb-1 univer-flex univer-flex-col univer-gap-3">
+ <div className="univer-flex univer-flex-col univer-gap-2">
+ <span>{localeService.t<LocaleKey>('docs-ui.headerFooter.headerTopMargin')}</span>
+ <MobileSettingNumber
+ className="univer-h-12 univer-w-full"
+ min={0}
+ max={200}
+ precision={1}
+ value={options.marginHeader}
+ onChange={(val) => { handleMarginChange(val ?? 0, 'marginHeader'); }}
+ />
+ </div>
+ <div className="univer-flex univer-flex-col univer-gap-2">
+ <span>{localeService.t<LocaleKey>('docs-ui.headerFooter.footerBottomMargin')}</span>
+ <MobileSettingNumber
+ className="univer-h-12 univer-w-full"
+ min={0}
+ max={200}
+ precision={1}
+ value={options.marginFooter}
+ onChange={(val) => { handleMarginChange(val ?? 0, 'marginFooter'); }}
+ />
+ </div>
+ </div>
+
+ <div className="univer-flex">
+ <Button className="univer-h-12 univer-w-full" onClick={closeHeaderFooter}>
+ {localeService.t<LocaleKey>('docs-ui.headerFooter.closeHeaderFooter')}
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/docs-ui/src/views/paragraph-setting/Setting.tsx b/packages/docs-ui/src/views/paragraph-setting/Setting.tsx
index d35492894e..ba51147b7c 100644
--- a/packages/docs-ui/src/views/paragraph-setting/Setting.tsx
+++ b/packages/docs-ui/src/views/paragraph-setting/Setting.tsx
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ReactNode } from 'react';
+import type { ComponentType, ReactNode } from 'react';
import type { LocaleKey } from '../../locale/types';
import { HorizontalAlign, LocaleService } from '@univerjs/core';
import { borderClassName, Button, clsx, InputNumber, Select, Tooltip } from '@univerjs/design';
@@ -117,7 +117,44 @@ const AutoFocusInputNumber = (props: {
/>
);
};
-export function ParagraphSetting() {
+export interface IParagraphSettingProps {
+ RowComponent?: typeof ParagraphSettingRow;
+ NumberComponent?: typeof AutoFocusInputNumber;
+ SelectComponent?: typeof Select;
+ AlignmentButtonComponent?: ComponentType<IParagraphAlignmentButtonProps>;
+}
+
+export interface IParagraphAlignmentButtonProps {
+ label: string;
+ selected: boolean;
+ onClick: () => void;
+ children: ReactNode;
+}
+
+function ParagraphAlignmentButton({ label, selected, onClick, children }: IParagraphAlignmentButtonProps) {
+ return (
+ <Tooltip title={label} placement="bottom">
+ <Button
+ type="button"
+ variant="text"
+ aria-label={label}
+ className={clsx({ '!univer-bg-gray-200 dark:!univer-bg-gray-700': selected })}
+ onClick={onClick}
+ >
+ <span className="univer-flex univer-size-5 univer-items-center univer-justify-center univer-text-lg">
+ {children}
+ </span>
+ </Button>
+ </Tooltip>
+ );
+}
+
+export function ParagraphSetting({
+ RowComponent = ParagraphSettingRow,
+ NumberComponent = AutoFocusInputNumber,
+ SelectComponent = Select,
+ AlignmentButtonComponent = ParagraphAlignmentButton,
+}: IParagraphSettingProps) {
const localeService = useDependency(LocaleService);
const currentParagraph = useCurrentParagraph();
@@ -148,27 +185,18 @@ export function ParagraphSetting() {
>
{ALIGNMENT_OPTIONS.map((item) => {
return (
- <Tooltip title={localeService.t(item.label)} key={item.value} placement="bottom">
- <span className="univer-flex univer-w-full univer-items-center univer-justify-center">
- <Button
- type="button"
- variant="text"
- className={clsx({
- '!univer-bg-gray-200 dark:!univer-bg-gray-700': horizontalAlignValue === item.value,
- })}
- onClick={() => setHorizontalAlign(item.value)}
- >
- <span
- className="
- univer-flex univer-size-5 univer-items-center univer-justify-center
- univer-text-lg
- "
- >
- {item.icon}
- </span>
- </Button>
- </span>
- </Tooltip>
+ <span
+ key={item.value}
+ className="univer-flex univer-w-full univer-items-center univer-justify-center"
+ >
+ <AlignmentButtonComponent
+ label={localeService.t(item.label)}
+ selected={horizontalAlignValue === item.value}
+ onClick={() => setHorizontalAlign(item.value)}
+ >
+ {item.icon}
+ </AlignmentButtonComponent>
+ </span>
);
})}
</div>
@@ -176,44 +204,44 @@ export function ParagraphSetting() {
<ParagraphSettingSection title={localeService.t<LocaleKey>('docs-ui.doc.paragraphSetting.indentation')}>
<div className="univer-grid univer-gap-3">
- <ParagraphSettingRow label={localeService.t<LocaleKey>('docs-ui.doc.paragraphSetting.left')} unit="(px)">
- <AutoFocusInputNumber value={indentStart} onChange={(v) => setIndentStart(v ?? 0)} />
- </ParagraphSettingRow>
- <ParagraphSettingRow label={localeService.t<LocaleKey>('docs-ui.doc.paragraphSetting.right')} unit="(px)">
- <AutoFocusInputNumber value={indentEnd} onChange={(v) => setIndentEnd(v ?? 0)} />
- </ParagraphSettingRow>
- <ParagraphSettingRow label={localeService.t<LocaleKey>('docs-ui.doc.paragraphSetting.firstLine')} unit="(px)">
- <AutoFocusInputNumber value={indentFirstLine} onChange={(v) => setIndentFirstLine(v ?? 0)} />
- </ParagraphSettingRow>
- <ParagraphSettingRow label={localeService.t<LocaleKey>('docs-ui.doc.paragraphSetting.hanging')} unit="(px)">
- <AutoFocusInputNumber value={hanging} onChange={(v) => setHanging(v ?? 0)} />
- </ParagraphSettingRow>
+ <RowComponent label={localeService.t<LocaleKey>('docs-ui.doc.paragraphSetting.left')} unit="(px)">
+ <NumberComponent value={indentStart} onChange={(v) => setIndentStart(v ?? 0)} />
+ </RowComponent>
+ <RowComponent label={localeService.t<LocaleKey>('docs-ui.doc.paragraphSetting.right')} unit="(px)">
+ <NumberComponent value={indentEnd} onChange={(v) => setIndentEnd(v ?? 0)} />
+ </RowComponent>
+ <RowComponent label={localeService.t<LocaleKey>('docs-ui.doc.paragraphSetting.firstLine')} unit="(px)">
+ <NumberComponent value={indentFirstLine} onChange={(v) => setIndentFirstLine(v ?? 0)} />
+ </RowComponent>
+ <RowComponent label={localeService.t<LocaleKey>('docs-ui.doc.paragraphSetting.hanging')} unit="(px)">
+ <NumberComponent value={hanging} onChange={(v) => setHanging(v ?? 0)} />
+ </RowComponent>
</div>
</ParagraphSettingSection>
<ParagraphSettingSection title={localeService.t<LocaleKey>('docs-ui.doc.paragraphSetting.spacing')}>
<div className="univer-grid univer-gap-3">
- <ParagraphSettingRow label={localeService.t<LocaleKey>('docs-ui.doc.paragraphSetting.before')} unit="(px)">
- <AutoFocusInputNumber value={spaceAbove} onChange={(v) => setSpaceAbove(v ?? 0)} />
- </ParagraphSettingRow>
- <ParagraphSettingRow label={localeService.t<LocaleKey>('docs-ui.doc.paragraphSetting.after')} unit="(px)">
- <AutoFocusInputNumber value={spaceBelow} onChange={(v) => setSpaceBelow(v ?? 0)} />
- </ParagraphSettingRow>
- <ParagraphSettingRow label={localeService.t<LocaleKey>('docs-ui.doc.paragraphSetting.lineSpace')}>
+ <RowComponent label={localeService.t<LocaleKey>('docs-ui.doc.paragraphSetting.before')} unit="(px)">
+ <NumberComponent value={spaceAbove} onChange={(v) => setSpaceAbove(v ?? 0)} />
+ </RowComponent>
+ <RowComponent label={localeService.t<LocaleKey>('docs-ui.doc.paragraphSetting.after')} unit="(px)">
+ <NumberComponent value={spaceBelow} onChange={(v) => setSpaceBelow(v ?? 0)} />
+ </RowComponent>
+ <RowComponent label={localeService.t<LocaleKey>('docs-ui.doc.paragraphSetting.lineSpace')}>
<div className="univer-flex univer-w-full univer-flex-col univer-gap-2">
- <Select
+ <SelectComponent
className="univer-w-full"
value={`${spacingRule}`}
options={lineSpacingOptions}
onChange={(v) => setSpacingRule(Number(v))}
/>
- <AutoFocusInputNumber
+ <NumberComponent
{...lineSpaceConfig}
value={lineSpacing}
onChange={(v) => setLineSpacing(v ?? 0)}
/>
</div>
- </ParagraphSettingRow>
+ </RowComponent>
</div>
</ParagraphSettingSection>
</div>
diff --git a/packages/docs-ui/src/views/paragraph-setting/index.tsx b/packages/docs-ui/src/views/paragraph-setting/index.tsx
index f7c764d3ed..324c593e8f 100644
--- a/packages/docs-ui/src/views/paragraph-setting/index.tsx
+++ b/packages/docs-ui/src/views/paragraph-setting/index.tsx
@@ -16,6 +16,7 @@
import type { ITextRange } from '@univerjs/core';
import type { IRichTextEditingMutationParams, ISetTextSelectionsOperationParams } from '@univerjs/docs';
+import type { IParagraphSettingProps } from './Setting';
import { debounce, generateRandomId, ICommandService, LocaleService } from '@univerjs/core';
import { RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';
import { useDependency, useObservable } from '@univerjs/ui';
@@ -29,7 +30,7 @@ const isRangesEqual = (oldRanges: ITextRange[], ranges: ITextRange[]) => {
range.startOffset === oldRange.startOffset && range.endOffset === oldRange.endOffset));
};
-export function ParagraphSettingIndex() {
+export function ParagraphSettingIndex(props: IParagraphSettingProps) {
const commandService = useDependency(ICommandService);
const localeService = useDependency(LocaleService);
const currentLocale = useObservable(localeService.currentLocale$);
@@ -67,5 +68,5 @@ export function ParagraphSettingIndex() {
useEffect(() => () => debounceReset.cancel(), [debounceReset]);
- return <ParagraphSetting key={key} />;
+ return <ParagraphSetting {...props} key={key} />;
}
diff --git a/packages/docs-ui/src/views/section-setting/Setting.tsx b/packages/docs-ui/src/views/section-setting/Setting.tsx
index 2ed33a9e9f..d431f8a1fe 100644
--- a/packages/docs-ui/src/views/section-setting/Setting.tsx
+++ b/packages/docs-ui/src/views/section-setting/Setting.tsx
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ReactNode } from 'react';
+import type { ComponentType, ReactNode } from 'react';
import type { LocaleKey } from '../../locale/types';
import { ColumnSeparatorType, LocaleService, PageOrientType, SectionType } from '@univerjs/core';
import { InputNumber, Select } from '@univerjs/design';
@@ -27,7 +27,10 @@ import { useSectionSetting } from './use-section-setting';
function SettingRow(props: { label: ReactNode; unit?: string; children: ReactNode }) {
return (
- <div className="univer-grid univer-min-h-8 univer-items-center univer-gap-3" style={{ gridTemplateColumns: 'minmax(0, 1fr) minmax(140px, 160px)' }}>
+ <div
+ className="univer-grid univer-min-h-8 univer-items-center univer-gap-3"
+ style={{ gridTemplateColumns: 'minmax(0, 1fr) minmax(140px, 160px)' }}
+ >
<div
className="
univer-min-w-0 univer-text-xs univer-leading-5 univer-text-gray-900
@@ -42,7 +45,13 @@ function SettingRow(props: { label: ReactNode; unit?: string; children: ReactNod
);
}
-export function SectionSetting() {
+export interface ISectionSettingProps {
+ RowComponent?: ComponentType<{ label: ReactNode; unit?: string; children: ReactNode }>;
+ InputNumberComponent?: typeof InputNumber;
+ SelectComponent?: typeof Select;
+}
+
+export function SectionSetting({ RowComponent = SettingRow, InputNumberComponent = InputNumber, SelectComponent = Select }: ISectionSettingProps) {
const localeService = useDependency(LocaleService);
const controller = useDependency(DocSectionSettingController);
const setting = useSectionSetting();
@@ -71,8 +80,8 @@ export function SectionSetting() {
</div>
)}
<div className="univer-grid univer-gap-3">
- <SettingRow label={localeService.t<LocaleKey>('docs-ui.doc.slider.sectionSetting')}>
- <Select
+ <RowComponent label={localeService.t<LocaleKey>('docs-ui.doc.slider.sectionSetting')}>
+ <SelectComponent
className="univer-w-full"
value={setting.selectedSectionId ?? ''}
options={[
@@ -87,9 +96,9 @@ export function SectionSetting() {
]}
onChange={setting.selectSection}
/>
- </SettingRow>
- <SettingRow label={localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.columnCount')}>
- <InputNumber
+ </RowComponent>
+ <RowComponent label={localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.columnCount')}>
+ <InputNumberComponent
aria-label={localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.columnCount')}
className="univer-w-full"
min={1}
@@ -99,9 +108,9 @@ export function SectionSetting() {
value={setting.columnCount}
onChange={(value) => value != null && setting.setColumnCount(value)}
/>
- </SettingRow>
- <SettingRow label={localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.columnGap')} unit=" (px)">
- <InputNumber
+ </RowComponent>
+ <RowComponent label={localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.columnGap')} unit=" (px)">
+ <InputNumberComponent
aria-label={localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.columnGap')}
className="univer-w-full"
min={0}
@@ -111,9 +120,9 @@ export function SectionSetting() {
value={setting.columnGap}
onChange={(value) => value != null && setting.setColumnGap(value)}
/>
- </SettingRow>
- <SettingRow label={localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.columnSeparator')}>
- <Select
+ </RowComponent>
+ <RowComponent label={localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.columnSeparator')}>
+ <SelectComponent
className="univer-w-full"
value={setting.separatorType == null ? '' : `${setting.separatorType}`}
options={[
@@ -129,9 +138,9 @@ export function SectionSetting() {
]}
onChange={(value) => setting.setSeparatorType(Number(value))}
/>
- </SettingRow>
- <SettingRow label={localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.sectionStart')}>
- <Select
+ </RowComponent>
+ <RowComponent label={localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.sectionStart')}>
+ <SelectComponent
className="univer-w-full"
value={setting.sectionType == null ? '' : `${setting.sectionType}`}
options={[
@@ -151,12 +160,12 @@ export function SectionSetting() {
]}
onChange={(value) => setting.setSectionType(Number(value))}
/>
- </SettingRow>
+ </RowComponent>
<div className="univer-pt-2 univer-text-sm univer-font-medium">
{localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.pageSetup')}
</div>
- <SettingRow label={localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.pageWidth')} unit=" (px)">
- <InputNumber
+ <RowComponent label={localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.pageWidth')} unit=" (px)">
+ <InputNumberComponent
aria-label={localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.pageWidth')}
className="univer-w-full"
min={1}
@@ -165,9 +174,9 @@ export function SectionSetting() {
value={setting.pageWidth}
onChange={(value) => value != null && setting.setPageWidth(value)}
/>
- </SettingRow>
- <SettingRow label={localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.pageHeight')} unit=" (px)">
- <InputNumber
+ </RowComponent>
+ <RowComponent label={localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.pageHeight')} unit=" (px)">
+ <InputNumberComponent
aria-label={localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.pageHeight')}
className="univer-w-full"
min={1}
@@ -176,9 +185,9 @@ export function SectionSetting() {
value={setting.pageHeight}
onChange={(value) => value != null && setting.setPageHeight(value)}
/>
- </SettingRow>
- <SettingRow label={localeService.t<LocaleKey>('docs-ui.page-settings.orientation')}>
- <Select
+ </RowComponent>
+ <RowComponent label={localeService.t<LocaleKey>('docs-ui.page-settings.orientation')}>
+ <SelectComponent
className="univer-w-full"
value={setting.pageOrient == null ? '' : `${setting.pageOrient}`}
options={[
@@ -194,9 +203,9 @@ export function SectionSetting() {
]}
onChange={(value) => setting.setPageOrient(Number(value))}
/>
- </SettingRow>
- <SettingRow label={localeService.t<LocaleKey>('docs-ui.page-settings.top')} unit=" (px)">
- <InputNumber
+ </RowComponent>
+ <RowComponent label={localeService.t<LocaleKey>('docs-ui.page-settings.top')} unit=" (px)">
+ <InputNumberComponent
aria-label={localeService.t<LocaleKey>('docs-ui.page-settings.top')}
className="univer-w-full"
min={0}
@@ -205,9 +214,9 @@ export function SectionSetting() {
value={setting.marginTop}
onChange={(value) => value != null && setting.setMarginTop(value)}
/>
- </SettingRow>
- <SettingRow label={localeService.t<LocaleKey>('docs-ui.page-settings.bottom')} unit=" (px)">
- <InputNumber
+ </RowComponent>
+ <RowComponent label={localeService.t<LocaleKey>('docs-ui.page-settings.bottom')} unit=" (px)">
+ <InputNumberComponent
aria-label={localeService.t<LocaleKey>('docs-ui.page-settings.bottom')}
className="univer-w-full"
min={0}
@@ -216,9 +225,9 @@ export function SectionSetting() {
value={setting.marginBottom}
onChange={(value) => value != null && setting.setMarginBottom(value)}
/>
- </SettingRow>
- <SettingRow label={localeService.t<LocaleKey>('docs-ui.page-settings.left')} unit=" (px)">
- <InputNumber
+ </RowComponent>
+ <RowComponent label={localeService.t<LocaleKey>('docs-ui.page-settings.left')} unit=" (px)">
+ <InputNumberComponent
aria-label={localeService.t<LocaleKey>('docs-ui.page-settings.left')}
className="univer-w-full"
min={0}
@@ -227,9 +236,9 @@ export function SectionSetting() {
value={setting.marginLeft}
onChange={(value) => value != null && setting.setMarginLeft(value)}
/>
- </SettingRow>
- <SettingRow label={localeService.t<LocaleKey>('docs-ui.page-settings.right')} unit=" (px)">
- <InputNumber
+ </RowComponent>
+ <RowComponent label={localeService.t<LocaleKey>('docs-ui.page-settings.right')} unit=" (px)">
+ <InputNumberComponent
aria-label={localeService.t<LocaleKey>('docs-ui.page-settings.right')}
className="univer-w-full"
min={0}
@@ -238,9 +247,9 @@ export function SectionSetting() {
value={setting.marginRight}
onChange={(value) => value != null && setting.setMarginRight(value)}
/>
- </SettingRow>
- <SettingRow label={localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.pageNumberStart')}>
- <InputNumber
+ </RowComponent>
+ <RowComponent label={localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.pageNumberStart')}>
+ <InputNumberComponent
aria-label={localeService.t<LocaleKey>('docs-ui.doc.sectionSetting.pageNumberStart')}
className="univer-w-full"
min={1}
@@ -249,7 +258,7 @@ export function SectionSetting() {
value={setting.pageNumberStart}
onChange={(value) => value != null && setting.setPageNumberStart(value)}
/>
- </SettingRow>
+ </RowComponent>
</div>
<DocObjectPermissionEntry
unitId={setting.unitId}
diff --git a/packages/docs-ui/src/views/section-setting/index.tsx b/packages/docs-ui/src/views/section-setting/index.tsx
index e198d3c4fb..2ba500e335 100644
--- a/packages/docs-ui/src/views/section-setting/index.tsx
+++ b/packages/docs-ui/src/views/section-setting/index.tsx
@@ -15,13 +15,14 @@
*/
import type { ISetTextSelectionsOperationParams } from '@univerjs/docs';
+import type { ISectionSettingProps } from './Setting';
import { generateRandomId, ICommandService } from '@univerjs/core';
import { RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';
import { useDependency } from '@univerjs/ui';
import { useEffect, useState } from 'react';
import { SectionSetting } from './Setting';
-export function SectionSettingIndex() {
+export function SectionSettingIndex(props: ISectionSettingProps) {
const commandService = useDependency(ICommandService);
const [key, setKey] = useState(() => generateRandomId(4));
@@ -39,5 +40,5 @@ export function SectionSettingIndex() {
return () => disposable.dispose();
}, [commandService]);
- return <SectionSetting key={key} />;
+ return <SectionSetting {...props} key={key} />;
}
diff --git a/packages/docs/src/layout-worker/worker.ts b/packages/docs/src/layout-worker/worker.ts
index b94df489f3..98ef2cd301 100644
--- a/packages/docs/src/layout-worker/worker.ts
+++ b/packages/docs/src/layout-worker/worker.ts
@@ -227,6 +227,8 @@ export class DocsLayoutWorkerRuntime implements IDocsLayoutWorkerRuntime {
anchor: request.anchor,
priorityAnchor: request.priorityAnchor,
invalidation: request.invalidation,
+ modernPageWidth: request.modernPageWidth,
+ modernHorizontalMargin: request.modernHorizontalMargin,
});
mount.activeGeneration = generation;
mount.cancelledGeneration = null;
diff --git a/packages/docs/src/services/doc-layout-executor.service.ts b/packages/docs/src/services/doc-layout-executor.service.ts
index f90432834c..81482a8c42 100644
--- a/packages/docs/src/services/doc-layout-executor.service.ts
+++ b/packages/docs/src/services/doc-layout-executor.service.ts
@@ -128,6 +128,8 @@ export interface IDocLayoutStartRequest extends IDocLayoutMountIdentity {
anchor?: number;
priorityAnchor?: number;
invalidation?: IDocumentLayoutSessionStartOptions['invalidation'];
+ modernPageWidth?: number;
+ modernHorizontalMargin?: number;
customBlockViewports?: Record<string, IDocsCustomBlockRenderViewport>;
customBlockViewportPatch?: IDocLayoutRecordPatch<IDocsCustomBlockRenderViewport>;
customRangePresentations?: IDocLayoutCustomRangePresentationEntry[];
@@ -355,6 +357,8 @@ export interface IDocLayoutStartOptions {
anchor?: number;
priorityAnchor?: number;
invalidation?: IDocumentLayoutSessionStartOptions['invalidation'];
+ modernPageWidth?: number;
+ modernHorizontalMargin?: number;
}
export class DocLayoutExecutorService extends Disposable {
diff --git a/packages/drawing-ui/src/controllers/__tests__/image-cropper.controller.spec.ts b/packages/drawing-ui/src/controllers/__tests__/image-cropper.controller.spec.ts
index 15b02f8f9d..ad736983a6 100644
--- a/packages/drawing-ui/src/controllers/__tests__/image-cropper.controller.spec.ts
+++ b/packages/drawing-ui/src/controllers/__tests__/image-cropper.controller.spec.ts
@@ -15,16 +15,17 @@
*/
import type { ICommandInfo } from '@univerjs/core';
-import { DrawingTypeEnum } from '@univerjs/core';
+import { ContextService, DrawingTypeEnum, ICommandService, IContextService, Injector, IUniverInstanceService, LocaleService } from '@univerjs/core';
import { MessageType } from '@univerjs/design';
-import { getDrawingShapeKeyByDrawingSearch, SetDrawingSelectedOperation } from '@univerjs/drawing';
-import { CURSOR_TYPE, Image } from '@univerjs/engine-render';
-import { KeyCode } from '@univerjs/ui';
+import { getDrawingShapeKeyByDrawingSearch, IDrawingManagerService, SetDrawingSelectedOperation } from '@univerjs/drawing';
+import { CURSOR_TYPE, Image, IRenderManagerService } from '@univerjs/engine-render';
+import { ILayoutService, IMessageService, IShortcutService, KeyCode } from '@univerjs/ui';
import { Subject } from 'rxjs';
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import { AutoImageCropOperation, CloseImageCropOperation, CropType, OpenImageCropOperation } from '../../commands/operations/image-crop.operation';
import { ImageCropperObject } from '../../views/crop/image-cropper-object';
import { ImageCropperController } from '../image-cropper.controller';
+import { MobileImageCropperController } from '../mobile/image-cropper.controller';
function createImage(id: string) {
const img = document.createElement('img');
@@ -33,6 +34,44 @@ function createImage(id: string) {
return new Image(id, { image: img });
}
+const injectors: Injector[] = [];
+
+function createController(
+ command: ICommandService,
+ drawing: IDrawingManagerService,
+ render: IRenderManagerService,
+ instance: IUniverInstanceService,
+ message: IMessageService,
+ locale: LocaleService,
+ shortcut: IShortcutService,
+ layout: ILayoutService,
+ mobile = false
+) {
+ const injector = new Injector([
+ [ICommandService, { useValue: command }],
+ [IDrawingManagerService, { useValue: drawing }],
+ [IRenderManagerService, { useValue: render }],
+ [IUniverInstanceService, { useValue: instance }],
+ [IMessageService, { useValue: message }],
+ [LocaleService, { useValue: locale }],
+ [IShortcutService, { useValue: shortcut }],
+ [ILayoutService, { useValue: layout }],
+ [IContextService, { useClass: ContextService }],
+ ]);
+ injectors.push(injector);
+ if (mobile) {
+ injector.add([MobileImageCropperController]);
+ return injector.get(MobileImageCropperController);
+ }
+
+ injector.add([ImageCropperController]);
+ return injector.get(ImageCropperController);
+}
+
+afterEach(() => {
+ injectors.splice(0).forEach((injector) => injector.dispose());
+});
+
describe('ImageCropperController', () => {
it('auto crops focused image and opens crop panel', () => {
const focusDrawing = { unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'd1' };
@@ -73,7 +112,7 @@ describe('ImageCropperController', () => {
};
const renderManagerService = { getRenderUnitById: vi.fn(() => ({ scene })) };
- const controller = new ImageCropperController(
+ const controller = createController(
commandService as never,
drawingManagerService as never,
renderManagerService as never,
@@ -118,7 +157,7 @@ describe('ImageCropperController', () => {
};
const renderManagerService = { getRenderUnitById: vi.fn(() => ({ scene })) };
- const controller = new ImageCropperController(
+ const controller = createController(
commandService as never,
drawingManagerService as never,
renderManagerService as never,
@@ -138,7 +177,7 @@ describe('ImageCropperController', () => {
controller.dispose();
});
- it('opens crop mode for image and applies hover cursor changes', () => {
+ it.each([false, true])('opens crop mode with mobile hit targets only when mobile=%s', (mobile) => {
const focusDrawing = { unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'd1' };
const imageKey = getDrawingShapeKeyByDrawingSearch(focusDrawing);
const image = createImage(imageKey);
@@ -183,7 +222,7 @@ describe('ImageCropperController', () => {
const renderManagerService = { getRenderUnitById: vi.fn(() => ({ scene })) };
const layoutService = { focus: vi.fn() };
- const controller = new ImageCropperController(
+ const controller = createController(
commandService as never,
drawingManagerService as never,
renderManagerService as never,
@@ -191,13 +230,29 @@ describe('ImageCropperController', () => {
{ show: vi.fn() } as never,
{ t: vi.fn((key: string) => key) } as never,
{ registerShortcut: vi.fn(() => ({ dispose: vi.fn() })) } as never,
- layoutService as never
+ layoutService as never,
+ mobile
);
+ expect(controller instanceof ImageCropperController).toBe(!mobile);
+
// OpenImageCrop handler
commandHandlers[0]({ id: OpenImageCropOperation.id, params: focusDrawing } as never);
expect(createdCropper).not.toBeNull();
+ expect(createdCropper!.transformerConfig?.cropAnchorHitSize).toBe(mobile ? 44 : undefined);
+ const cropper = createdCropper!;
+ const originalImageState = image.getState();
+ const originalCropState = cropper.getState();
+ const objects = new Map([[cropper.oKey, cropper]]);
+ for (let attempt = 0; attempt < 5; attempt++) {
+ transformer.createControlForCopper.mockClear();
+ transformer.changeStart$.next({ objects });
+ transformer.changeEnd$.next({ objects });
+ expect(transformer.createControlForCopper).toHaveBeenCalledExactlyOnceWith(cropper);
+ expect(cropper.getState()).toEqual(originalCropState);
+ expect(image.getState()).toEqual(originalImageState);
+ }
createdCropper!.onPointerEnter$.emitEvent({} as never);
expect(createdCropper!.cursor).toBe(CURSOR_TYPE.MOVE);
createdCropper!.onPointerLeave$.emitEvent({} as never);
@@ -260,7 +315,7 @@ describe('ImageCropperController', () => {
const shortcutService = {
registerShortcut: vi.fn(() => shortcutDisposables.shift()!),
};
- const controller = new ImageCropperController(
+ const controller = createController(
commandService as never,
{
getDrawingByParam: vi.fn(() => ({ drawingType: DrawingTypeEnum.DRAWING_IMAGE })),
@@ -356,7 +411,7 @@ describe('ImageCropperController', () => {
return { attachTransformerTo: vi.fn() };
}),
};
- const controller = new ImageCropperController(
+ const controller = createController(
commandService as never,
drawingManagerService as never,
{ getRenderUnitById: vi.fn(() => ({ scene })) } as never,
diff --git a/packages/drawing-ui/src/controllers/__tests__/image-update.controller.spec.ts b/packages/drawing-ui/src/controllers/__tests__/image-update.controller.spec.ts
index f00b17040e..ea69019d4d 100644
--- a/packages/drawing-ui/src/controllers/__tests__/image-update.controller.spec.ts
+++ b/packages/drawing-ui/src/controllers/__tests__/image-update.controller.spec.ts
@@ -14,15 +14,51 @@
* limitations under the License.
*/
-import { DrawingTypeEnum, ImageSourceType, UniverInstanceType } from '@univerjs/core';
-import { SetDrawingSelectedOperation } from '@univerjs/drawing';
-import { Subject } from 'rxjs';
+import { ContextService, DrawingTypeEnum, ICommandService, IContextService, IImageIoService, ImageSourceType, Injector, IUniverInstanceService, LocaleService, ThemeService, UniverInstanceType } from '@univerjs/core';
+import { IDrawingManagerService, SetDrawingSelectedOperation } from '@univerjs/drawing';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { IDialogService, ILayoutService, IMessageService, IShortcutService } from '@univerjs/ui';
+import { NEVER, Subject } from 'rxjs';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { ImageResetSizeOperation } from '../../commands/operations/image-reset-size.operation';
-import { DOC_DRAWING_BEHIND_TEXT_LAYER_INDEX } from '../../services/drawing-render.service';
+import { DOC_DRAWING_BEHIND_TEXT_LAYER_INDEX, DrawingRenderService } from '../../services/drawing-render.service';
+import { ImageCropperController } from '../image-cropper.controller';
import { ImageUpdateController } from '../image-update.controller';
+const injectors: Injector[] = [];
+
+function createController(
+ command: ICommandService,
+ render: IRenderManagerService,
+ drawing: IDrawingManagerService,
+ dialog: IDialogService,
+ imageIo: IImageIoService,
+ instance: IUniverInstanceService,
+ drawingRender: DrawingRenderService
+) {
+ const injector = new Injector([
+ [ICommandService, { useValue: command }],
+ [IRenderManagerService, { useValue: render }],
+ [IDrawingManagerService, { useValue: drawing }],
+ [IDialogService, { useValue: dialog }],
+ [IImageIoService, { useValue: imageIo }],
+ [IUniverInstanceService, { useValue: { ...instance, getCurrentTypeOfUnit$: () => NEVER } }],
+ [DrawingRenderService, { useValue: drawingRender }],
+ [IContextService, { useClass: ContextService }],
+ [ThemeService],
+ [LocaleService],
+ [ILayoutService, { useValue: { focus: vi.fn() } }],
+ [IMessageService, { useValue: { show: vi.fn() } }],
+ [IShortcutService, { useValue: { registerShortcut: vi.fn(() => ({ dispose: vi.fn() })) } }],
+ [ImageCropperController],
+ [ImageUpdateController],
+ ]);
+ injectors.push(injector);
+ return injector.get(ImageUpdateController);
+}
+
afterEach(() => {
+ injectors.splice(0).forEach((injector) => injector.dispose());
vi.useRealTimers();
});
@@ -63,7 +99,7 @@ describe('ImageUpdateController', () => {
syncExecuteCommand: vi.fn(),
};
- const controller = new ImageUpdateController(
+ const controller = createController(
commandService as never,
{
getRenderUnitById: vi.fn(() => ({
@@ -118,7 +154,7 @@ describe('ImageUpdateController', () => {
};
const renderImages = vi.fn(async () => []);
- const controller = new ImageUpdateController(
+ const controller = createController(
{ onCommandExecuted: vi.fn(() => ({ dispose: vi.fn() })), syncExecuteCommand: vi.fn() } as never,
{
getRenderUnitById: vi.fn(() => ({
@@ -164,7 +200,7 @@ describe('ImageUpdateController', () => {
finishRendering = resolve;
}));
const refreshTransform = vi.fn();
- const controller = new ImageUpdateController(
+ const controller = createController(
{ onCommandExecuted: vi.fn(() => ({ dispose: vi.fn() })), syncExecuteCommand: vi.fn() } as never,
{
getRenderUnitById: vi.fn(() => ({
@@ -236,7 +272,7 @@ describe('ImageUpdateController', () => {
getDrawingByParam: vi.fn(() => imageParam),
};
- const controller = new ImageUpdateController(
+ const controller = createController(
{ onCommandExecuted: vi.fn(() => ({ dispose: vi.fn() })), syncExecuteCommand: vi.fn() } as never,
{
getRenderUnitById: vi.fn(() => ({ scene })),
diff --git a/packages/drawing-ui/src/controllers/components.controller.ts b/packages/drawing-ui/src/controllers/components.controller.ts
index e965e33810..b729c8cddd 100644
--- a/packages/drawing-ui/src/controllers/components.controller.ts
+++ b/packages/drawing-ui/src/controllers/components.controller.ts
@@ -32,6 +32,14 @@ import {
} from '../views/image-popup-menu/component-name';
import { ImagePopupMenu } from '../views/image-popup-menu/ImagePopupMenu';
+import { DRAWING_ALIGN_COMPONENT, DRAWING_ARRANGE_COMPONENT, DRAWING_GROUP_COMPONENT, DRAWING_TRANSFORM_COMPONENT, IMAGE_CROPPER_COMPONENT } from '../views/panel/component-name';
+import { DrawingAlign } from '../views/panel/DrawingAlign';
+import { DrawingArrange } from '../views/panel/DrawingArrange';
+
+import { DrawingGroup } from '../views/panel/DrawingGroup';
+import { DrawingTransform } from '../views/panel/DrawingTransform';
+import { ImageCropper } from '../views/panel/ImageCropper';
+
export class ComponentsController extends Disposable {
constructor(
@Inject(ComponentManager) private readonly _componentManager: ComponentManager,
@@ -46,6 +54,11 @@ export class ComponentsController extends Disposable {
private _registerComponents(): void {
([
[COMPONENT_IMAGE_POPUP_MENU, ImagePopupMenu],
+ [DRAWING_ARRANGE_COMPONENT, DrawingArrange],
+ [DRAWING_ALIGN_COMPONENT, DrawingAlign],
+ [DRAWING_GROUP_COMPONENT, DrawingGroup],
+ [DRAWING_TRANSFORM_COMPONENT, DrawingTransform],
+ [IMAGE_CROPPER_COMPONENT, ImageCropper],
] as const).forEach(([key, component]) => {
this.disposeWithMe(this._componentManager.register(key, component));
});
diff --git a/packages/drawing-ui/src/controllers/image-cropper.controller.ts b/packages/drawing-ui/src/controllers/image-cropper.controller.ts
index f78251b38c..19fde0ad0b 100644
--- a/packages/drawing-ui/src/controllers/image-cropper.controller.ts
+++ b/packages/drawing-ui/src/controllers/image-cropper.controller.ts
@@ -16,7 +16,7 @@
import type { ICommandInfo, IDrawingSearch, ISrcRect, ITransformState, Nullable, Workbook } from '@univerjs/core';
import type { IImageData } from '@univerjs/drawing';
-import type { BaseObject, Scene } from '@univerjs/engine-render';
+import type { Scene } from '@univerjs/engine-render';
import type { ICloseImageCropOperationParams, IOpenImageCropOperationBySrcRectParams } from '../commands/operations/image-crop.operation';
import type { LocaleKey } from '../locale/types';
import {
@@ -35,15 +35,16 @@ import {
IDrawingManagerService,
SetDrawingSelectedOperation,
} from '@univerjs/drawing';
-import { CURSOR_TYPE, degToRad, Image, IRenderManagerService, precisionTo, Vector2 } from '@univerjs/engine-render';
+import { CURSOR_TYPE, Image, IRenderManagerService, precisionTo } from '@univerjs/engine-render';
import { ILayoutService, IMessageService, IShortcutService, KeyCode } from '@univerjs/ui';
-import { of, switchMap } from 'rxjs';
+import { BehaviorSubject, of, switchMap } from 'rxjs';
import {
AutoImageCropOperation,
CloseImageCropOperation,
CropType,
OpenImageCropOperation,
} from '../commands/operations/image-crop.operation';
+import { getImageCropRect } from '../utils/image-crop-transform';
import { ImageCropperObject } from '../views/crop/image-cropper-object';
interface IImageCropSnapshot {
@@ -63,6 +64,8 @@ export class ImageCropperController extends Disposable {
private readonly _cropSnapshots = new WeakMap<ImageCropperObject, IImageCropSnapshot>();
private _pendingCropSnapshot: Nullable<IImageCropSnapshot> = null;
private _activeCropSession: Nullable<IImageCropSession> = null;
+ private readonly _cropping$ = new BehaviorSubject(false);
+ readonly cropping$ = this._cropping$.asObservable();
constructor(
@ICommandService private readonly _commandService: ICommandService,
@@ -77,6 +80,7 @@ export class ImageCropperController extends Disposable {
super();
this.disposeWithMe(this._cropShortcutDisposables);
+ this.disposeWithMe({ dispose: () => this._cropping$.complete() });
this._init();
}
@@ -277,11 +281,6 @@ export class ImageCropperController extends Disposable {
const imageShapeKey = getDrawingShapeKeyByDrawingSearch({ unitId, subUnitId, drawingId });
const imageShape = scene.getObject(imageShapeKey);
-
- if (imageShape == null) {
- return;
- }
-
if (!(imageShape instanceof Image)) {
this._messageService.show({
type: MessageType.Error,
@@ -303,6 +302,7 @@ export class ImageCropperController extends Disposable {
scene.addObject(imageCropperObject, imageShape.getLayerIndex() + 1).attachTransformerTo(imageCropperObject);
this._activeCropSession = { scene, imageShape, imageCropperObject };
+ this._cropping$.next(true);
transformer?.createControlForCopper(imageCropperObject);
this._addHoverForImageCopper(imageCropperObject);
@@ -310,7 +310,7 @@ export class ImageCropperController extends Disposable {
transformer?.refreshControls();
imageCropperObject.makeDirty(true);
- this._registerCropShortcuts();
+ this._registerCropShortcuts(imageCropperObject);
this._commandService.syncExecuteCommand(SetDrawingSelectedOperation.id, [{ unitId, subUnitId, drawingId }]);
this._layoutService.focus();
})
@@ -349,7 +349,7 @@ export class ImageCropperController extends Disposable {
if (params?.isCancel) {
this._restoreCropSnapshot(imageShape, imageCropperObject);
} else {
- const srcRect = this._getSrcRectByTransformState(imageShape, imageCropperObject);
+ const srcRect = getImageCropRect(imageShape, imageCropperObject);
const drawingParam = this._drawingManagerService.getDrawingOKey(imageShape.oKey);
if (drawingParam != null) {
const { left, top, height, width } = imageCropperObject;
@@ -374,6 +374,7 @@ export class ImageCropperController extends Disposable {
this._cropSnapshots.delete(imageCropperObject);
imageCropperObject.dispose();
+ this._cropping$.next(false);
this._cropShortcutDisposables.dispose();
})
);
@@ -419,8 +420,13 @@ export class ImageCropperController extends Disposable {
}
}
- private _registerCropShortcuts(): void {
+ private _registerCropShortcuts(imageCropperObject: ImageCropperObject): void {
this._cropShortcutDisposables.dispose();
+ this._cropShortcutDisposables.add(imageCropperObject.onDispose$.subscribeEvent(() => {
+ this._activeCropSession = null;
+ this._cropping$.next(false);
+ this._cropShortcutDisposables.dispose();
+ }));
this._cropShortcutDisposables.add(this._shortcutService.registerShortcut({
id: CloseImageCropOperation.id,
binding: KeyCode.ENTER,
@@ -465,6 +471,8 @@ export class ImageCropperController extends Disposable {
const { left, top, height, width, angle } = cropObject;
if (!checkIfMove({ left, top, height, width, angle }, startTransform)) {
+ // Pointer-down removes the handles even when the gesture ends without a drag.
+ transformer.createControlForCopper(cropObject);
return;
}
@@ -474,7 +482,7 @@ export class ImageCropperController extends Disposable {
return;
}
- const srcRect = this._getSrcRectByTransformState(applyObject, cropObject);
+ const srcRect = getImageCropRect(applyObject, cropObject);
cropObject.refreshSrcRect(srcRect.srcRect, applyObject.getState());
@@ -514,55 +522,4 @@ export class ImageCropperController extends Disposable {
})
);
}
-
- private _getSrcRectByTransformState(applyObject: BaseObject, imageCropperObject: ImageCropperObject) {
- const { left, top, height, width } = imageCropperObject;
-
- const { left: applyLeft, top: applyTop, width: applyWidth, height: applyHeight, angle: applyAngle } = applyObject;
-
- const newLeft = left - applyLeft;
- const newTop = top - applyTop;
-
- const srcRect = {
- left: newLeft,
- top: newTop,
- right: applyWidth - newLeft - width,
- bottom: applyHeight - newTop - height,
- };
-
- const srcRectAngle = { ...srcRect };
-
- // const offsetPoint = new Vector2(0, 0);
- if (applyAngle !== 0) {
- /**
- * Calculate the offset of the center rotation to correctly position the object entering the cropping.
- */
- const cx = left + width / 2;
- const cy = top + height / 2;
- const centerPoint = new Vector2(cx, cy);
-
- const newCx = applyWidth / 2 + applyLeft;
- const newCy = applyHeight / 2 + applyTop;
- const newCenterPoint = new Vector2(newCx, newCy);
-
- const vertexPoint = new Vector2(applyLeft, applyTop);
- vertexPoint.rotateByPoint(degToRad(applyAngle), newCenterPoint);
-
- const applyFinalPoint = vertexPoint.clone();
- applyFinalPoint.rotateByPoint(degToRad(-applyAngle), centerPoint);
-
- const newAngleLeft = left - applyFinalPoint.x;
- const newAngleTop = top - applyFinalPoint.y;
-
- srcRectAngle.left = newAngleLeft;
- srcRectAngle.top = newAngleTop;
- srcRectAngle.right = applyWidth - newAngleLeft - width;
- srcRectAngle.bottom = applyHeight - newAngleTop - height;
- }
-
- return {
- srcRect,
- srcRectAngle,
- };
- }
}
diff --git a/packages/drawing-ui/src/controllers/image-update.controller.ts b/packages/drawing-ui/src/controllers/image-update.controller.ts
index 76ceded371..0afe25ffc7 100644
--- a/packages/drawing-ui/src/controllers/image-update.controller.ts
+++ b/packages/drawing-ui/src/controllers/image-update.controller.ts
@@ -21,7 +21,6 @@ import {
Disposable,
DrawingTypeEnum,
ICommandService,
- IImageIoService,
ImageSourceType,
Inject,
IUniverInstanceService,
@@ -29,7 +28,6 @@ import {
} from '@univerjs/core';
import { getDrawingShapeKeyByDrawingSearch, IDrawingManagerService, SetDrawingSelectedOperation } from '@univerjs/drawing';
import { CURSOR_TYPE, IRenderManagerService } from '@univerjs/engine-render';
-import { IDialogService } from '@univerjs/ui';
import { bufferTime, filter, map } from 'rxjs';
import { ImageResetSizeOperation } from '../commands/operations/image-reset-size.operation';
import { DrawingRenderService, ensureDrawingRenderLayer } from '../services/drawing-render.service';
@@ -40,8 +38,6 @@ export class ImageUpdateController extends Disposable {
@ICommandService private readonly _commandService: ICommandService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
@IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,
- @IDialogService private readonly _dialogService: IDialogService,
- @IImageIoService private readonly _imageIoService: IImageIoService,
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
@Inject(DrawingRenderService) private readonly _drawingRenderService: DrawingRenderService
) {
@@ -287,12 +283,15 @@ export class ImageUpdateController extends Disposable {
}
private _addDialogForImage(o: Image) {
+ const preview = () => {
+ const native = o.getNative();
+ if (native) {
+ this._drawingRenderService.previewImage(`${o.oKey}-viewer-dialog`, native.src, o.getNativeSize().width, o.getNativeSize().height);
+ }
+ };
this.disposeWithMe(
toDisposable(
- o.onDblclick$.subscribeEvent(() => {
- const dialogId = `${o.oKey}-viewer-dialog`;
- this._drawingRenderService.previewImage(dialogId, o.getNative()!.src, o.getNativeSize().width, o.getNativeSize().height);
- })
+ o.onDblclick$.subscribeEvent(preview)
)
);
}
diff --git a/packages/drawing-ui/src/controllers/mobile/components.controller.ts b/packages/drawing-ui/src/controllers/mobile/components.controller.ts
index f588abf912..59db4f781b 100644
--- a/packages/drawing-ui/src/controllers/mobile/components.controller.ts
+++ b/packages/drawing-ui/src/controllers/mobile/components.controller.ts
@@ -30,12 +30,23 @@ 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';
+import { DRAWING_ALIGN_COMPONENT, DRAWING_ARRANGE_COMPONENT, DRAWING_GROUP_COMPONENT, DRAWING_TRANSFORM_COMPONENT, IMAGE_CROPPER_COMPONENT } from '../../views/panel/component-name';
+import { MobileDrawingArrange } from '../../views/panel/MobileDrawingArrange';
+import { MobileDrawingAlign, MobileDrawingGroup, MobileDrawingTransform } from '../../views/panel/MobileDrawingControls';
+
+import { MobileImageCropper } from '../../views/panel/MobileImageCropper';
+
export class MobileComponentsController extends Disposable {
constructor(
@Inject(ComponentManager) componentManager: ComponentManager,
@Inject(IconManager) iconManager: IconManager
) {
super();
+ this.disposeWithMe(componentManager.register(DRAWING_ALIGN_COMPONENT, MobileDrawingAlign));
+ this.disposeWithMe(componentManager.register(DRAWING_GROUP_COMPONENT, MobileDrawingGroup));
+ this.disposeWithMe(componentManager.register(DRAWING_TRANSFORM_COMPONENT, MobileDrawingTransform));
+ this.disposeWithMe(componentManager.register(DRAWING_ARRANGE_COMPONENT, MobileDrawingArrange));
+ this.disposeWithMe(componentManager.register(IMAGE_CROPPER_COMPONENT, MobileImageCropper));
this.disposeWithMe(componentManager.register(COMPONENT_MOBILE_IMAGE_POPUP_MENU, MobileImagePopupMenu));
this.disposeWithMe(iconManager.register({
diff --git a/packages/drawing-ui/src/controllers/mobile/image-cropper.controller.ts b/packages/drawing-ui/src/controllers/mobile/image-cropper.controller.ts
new file mode 100644
index 0000000000..46ef0401e9
--- /dev/null
+++ b/packages/drawing-ui/src/controllers/mobile/image-cropper.controller.ts
@@ -0,0 +1,474 @@
+/**
+ * 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 { ICommandInfo, IDrawingSearch, ISrcRect, ITransformState, Nullable, Workbook } from '@univerjs/core';
+import type { IImageData } from '@univerjs/drawing';
+import type { Scene } from '@univerjs/engine-render';
+import type { ICloseImageCropOperationParams, IOpenImageCropOperationBySrcRectParams } from '../../commands/operations/image-crop.operation';
+import type { LocaleKey } from '../../locale/types';
+import {
+ checkIfMove,
+ Disposable,
+ DisposableCollection,
+ ICommandService,
+ Inject,
+ IUniverInstanceService,
+ LocaleService,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { MessageType } from '@univerjs/design';
+import {
+ getDrawingShapeKeyByDrawingSearch,
+ IDrawingManagerService,
+ SetDrawingSelectedOperation,
+} from '@univerjs/drawing';
+import { CURSOR_TYPE, Image, IRenderManagerService, precisionTo } from '@univerjs/engine-render';
+import { ILayoutService, IMessageService, IShortcutService, KeyCode } from '@univerjs/ui';
+import { BehaviorSubject, of, switchMap } from 'rxjs';
+import {
+ AutoImageCropOperation,
+ CloseImageCropOperation,
+ CropType,
+ OpenImageCropOperation,
+} from '../../commands/operations/image-crop.operation';
+import { getImageCropRect } from '../../utils/image-crop-transform';
+import { ImageCropperObject } from '../../views/crop/image-cropper-object';
+
+const MOBILE_CROP_ANCHOR_HIT_SIZE = 44;
+
+interface IImageCropSnapshot {
+ transform: ITransformState;
+ srcRect: Nullable<ISrcRect>;
+}
+
+interface IImageCropSession {
+ scene: Scene;
+ imageShape: Image;
+ imageCropperObject: ImageCropperObject;
+}
+
+export class MobileImageCropperController extends Disposable {
+ private _sceneListenerOnImageMap: WeakSet<Scene> = new WeakSet();
+ private readonly _cropShortcutDisposables = new DisposableCollection();
+ private readonly _cropSnapshots = new WeakMap<ImageCropperObject, IImageCropSnapshot>();
+ private _pendingCropSnapshot: Nullable<IImageCropSnapshot> = null;
+ private _activeCropSession: Nullable<IImageCropSession> = null;
+ private readonly _cropping$ = new BehaviorSubject(false);
+ readonly cropping$ = this._cropping$.asObservable();
+
+ constructor(
+ @ICommandService private readonly _commandService: ICommandService,
+ @IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @IMessageService private readonly _messageService: IMessageService,
+ @Inject(LocaleService) private readonly _localeService: LocaleService,
+ @IShortcutService private readonly _shortcutService: IShortcutService,
+ @ILayoutService private readonly _layoutService: ILayoutService
+ ) {
+ super();
+
+ this.disposeWithMe(this._cropShortcutDisposables);
+ this.disposeWithMe({ dispose: () => this._cropping$.complete() });
+ this._init();
+ }
+
+ private _init(): void {
+ this._initOpenCrop();
+ this._initCloseCrop();
+ this._initAutoCrop();
+ }
+
+ private _initAutoCrop(): void {
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (command.id !== AutoImageCropOperation.id) {
+ return;
+ }
+
+ const params = command.params as IOpenImageCropOperationBySrcRectParams;
+ if (params == null) {
+ return;
+ }
+
+ const drawingParams = this._drawingManagerService.getFocusDrawings();
+ if (drawingParams.length !== 1) {
+ return;
+ }
+
+ const { cropType } = params;
+ const { unitId, subUnitId, drawingId } = drawingParams[0];
+ const scene = this._renderManagerService.getRenderUnitById(unitId)?.scene;
+
+ if (scene == null) {
+ return true;
+ }
+
+ if (this._searchCropObject(scene) != null) {
+ this._commandService.syncExecuteCommand(CloseImageCropOperation.id, { isAuto: true });
+ }
+
+ const imageShapeKey = getDrawingShapeKeyByDrawingSearch({ unitId, subUnitId, drawingId });
+ const imageShape = scene.getObject(imageShapeKey);
+
+ if (!(imageShape instanceof Image)) {
+ this._messageService.show({
+ type: MessageType.Error,
+ content: this._localeService.t<LocaleKey>('drawing-ui.image-cropper.error'),
+ });
+ return;
+ }
+
+ this._pendingCropSnapshot = this._captureCropSnapshot(imageShape);
+ try {
+ this._updateCropperObject(cropType, imageShape);
+ this._commandService.syncExecuteCommand(OpenImageCropOperation.id, { unitId, subUnitId, drawingId });
+ } finally {
+ this._pendingCropSnapshot = null;
+ }
+ })
+ );
+ }
+
+ private _calculateSrcRectByRatio(left: number, top: number, width: number, height: number, numerator: number, denominator: number) {
+ const srcRatio = width / height;
+ const ratio = numerator / denominator;
+
+ let newWidth = width;
+ let newHeight = height;
+
+ if (srcRatio > ratio) {
+ newWidth = height * ratio;
+ } else {
+ newHeight = width / ratio;
+ }
+
+ const newLeft = (width - newWidth) / 2;
+ const newTop = (height - newHeight) / 2;
+
+ return {
+ left: precisionTo(newLeft, 1),
+ top: precisionTo(newTop, 1),
+ right: precisionTo(width - (newLeft + newWidth), 1),
+ bottom: precisionTo(height - (newTop + newHeight), 1),
+ };
+ }
+
+ private _updateCropperObject(cropType: CropType, imageShape: Image): void {
+ const { left, top, width, height } = imageShape.calculateTransformWithSrcRect();
+
+ let newSrcRect: Nullable<ISrcRect>;
+ switch (cropType) {
+ case CropType.R1_1:
+ newSrcRect = this._calculateSrcRectByRatio(left, top, width, height, 1, 1);
+ break;
+ case CropType.R16_9:
+ newSrcRect = this._calculateSrcRectByRatio(left, top, width, height, 16, 9);
+ break;
+ case CropType.R9_16:
+ newSrcRect = this._calculateSrcRectByRatio(left, top, width, height, 9, 16);
+ break;
+ case CropType.R5_4:
+ newSrcRect = this._calculateSrcRectByRatio(left, top, width, height, 5, 4);
+ break;
+ case CropType.R4_5:
+ newSrcRect = this._calculateSrcRectByRatio(left, top, width, height, 4, 5);
+ break;
+ case CropType.R4_3:
+ newSrcRect = this._calculateSrcRectByRatio(left, top, width, height, 4, 3);
+ break;
+ case CropType.R3_4:
+ newSrcRect = this._calculateSrcRectByRatio(left, top, width, height, 3, 4);
+ break;
+ case CropType.R3_2:
+ newSrcRect = this._calculateSrcRectByRatio(left, top, width, height, 3, 2);
+ break;
+ case CropType.R2_3:
+ newSrcRect = this._calculateSrcRectByRatio(left, top, width, height, 2, 3);
+ break;
+ case CropType.FREE:
+ default:
+ break;
+ }
+
+ if (newSrcRect == null) {
+ return;
+ }
+
+ imageShape.setSrcRect(newSrcRect);
+ const { left: newLeft = 0, top: newTop = 0, bottom: newBottom = 0, right: newRight = 0 } = newSrcRect;
+ imageShape.transformByStateCloseCropper({
+ left: left + newLeft,
+ top: top + newTop,
+ width: width - newRight - newLeft,
+ height: height - newBottom - newTop,
+ });
+ }
+
+ private _initOpenCrop(): void {
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (command.id !== OpenImageCropOperation.id) {
+ return;
+ }
+
+ const params = command.params as IDrawingSearch;
+ if (params == null) {
+ return;
+ }
+
+ if (this._activeCropSession != null) {
+ this._commandService.syncExecuteCommand(CloseImageCropOperation.id, { isAuto: true });
+ }
+
+ const { unitId, subUnitId, drawingId } = params;
+ const scene = this._renderManagerService.getRenderUnitById(unitId)?.scene;
+
+ if (scene == null) {
+ return true;
+ }
+
+ if (!this._sceneListenerOnImageMap.has(scene)) {
+ this._addListenerOnImage(scene);
+ this._sceneListenerOnImageMap.add(scene);
+ }
+
+ const imageData = this._drawingManagerService.getDrawingByParam({ unitId, subUnitId, drawingId });
+ if (imageData == null) {
+ return;
+ }
+
+ const imageShapeKey = getDrawingShapeKeyByDrawingSearch({ unitId, subUnitId, drawingId });
+ const imageShape = scene.getObject(imageShapeKey);
+ if (!(imageShape instanceof Image)) {
+ this._messageService.show({
+ type: MessageType.Error,
+ content: this._localeService.t<LocaleKey>('drawing-ui.image-cropper.error'),
+ });
+ return;
+ }
+
+ const transformer = scene.getTransformer();
+ transformer?.clearControls();
+
+ const imageCropperObject = new ImageCropperObject(`${imageShapeKey}-crop`, {
+ srcRect: imageShape.srcRect,
+ prstGeom: imageShape.prstGeom,
+ applyTransform: imageShape.calculateTransformWithSrcRect(),
+ });
+ imageCropperObject.transformerConfig = {
+ ...imageCropperObject.transformerConfig,
+ cropAnchorHitSize: MOBILE_CROP_ANCHOR_HIT_SIZE,
+ };
+ this._cropSnapshots.set(imageCropperObject, this._pendingCropSnapshot ?? this._captureCropSnapshot(imageShape));
+ this._pendingCropSnapshot = null;
+
+ scene.addObject(imageCropperObject, imageShape.getLayerIndex() + 1).attachTransformerTo(imageCropperObject);
+ this._activeCropSession = { scene, imageShape, imageCropperObject };
+ this._cropping$.next(true);
+ transformer?.createControlForCopper(imageCropperObject);
+ this._addHoverForImageCopper(imageCropperObject);
+
+ imageShape.openRenderByCropper();
+ transformer?.refreshControls();
+ imageCropperObject.makeDirty(true);
+
+ this._registerCropShortcuts(imageCropperObject);
+ this._commandService.syncExecuteCommand(SetDrawingSelectedOperation.id, [{ unitId, subUnitId, drawingId }]);
+ this._layoutService.focus();
+ })
+ );
+ }
+
+ private _searchCropObject(scene: Scene): ImageCropperObject | undefined {
+ for (const object of scene.getAllObjectsByOrder()) {
+ if (object instanceof ImageCropperObject) {
+ return object;
+ }
+ }
+ }
+
+ private _initCloseCrop(): void {
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (command.id !== CloseImageCropOperation.id) {
+ return;
+ }
+
+ const cropSession = this._activeCropSession;
+ if (cropSession == null) {
+ return;
+ }
+
+ this._activeCropSession = null;
+ const { scene, imageShape, imageCropperObject } = cropSession;
+ const transformer = scene.getTransformerByCreate();
+ transformer.detachFrom(imageCropperObject);
+ transformer.clearCopperControl();
+
+ const params = command.params as ICloseImageCropOperationParams | undefined;
+ if (params?.isCancel) {
+ this._restoreCropSnapshot(imageShape, imageCropperObject);
+ } else {
+ const srcRect = getImageCropRect(imageShape, imageCropperObject);
+ const drawingParam = this._drawingManagerService.getDrawingOKey(imageShape.oKey);
+ if (drawingParam != null) {
+ const { left, top, height, width } = imageCropperObject;
+ this._drawingManagerService.featurePluginUpdateNotification([{
+ ...drawingParam,
+ transform: {
+ ...drawingParam.transform,
+ left,
+ top,
+ height,
+ width,
+ },
+ srcRect: srcRect.srcRectAngle,
+ }] as IImageData[]);
+ }
+ imageShape.setSrcRect({ ...srcRect.srcRectAngle });
+ }
+
+ imageShape.closeRenderByCropper();
+ imageShape.makeDirty(true);
+ transformer.refreshControls();
+
+ this._cropSnapshots.delete(imageCropperObject);
+ imageCropperObject.dispose();
+ this._cropping$.next(false);
+ this._cropShortcutDisposables.dispose();
+ })
+ );
+
+ const sheetUnit$ = this._univerInstanceService
+ .getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET)
+ .pipe(switchMap((workbook) => workbook ? workbook.activeSheet$ : of(null)));
+
+ this.disposeWithMe(sheetUnit$.subscribe(() => {
+ if (this._activeCropSession != null) {
+ this._commandService.syncExecuteCommand(CloseImageCropOperation.id);
+ }
+ }));
+ }
+
+ private _getApplyObjectByCropObject(cropObject: ImageCropperObject): Nullable<Image> {
+ const applyOKey = cropObject.oKey.slice(0, cropObject.oKey.length - 5);
+ const scene = cropObject.getScene();
+ if (!scene) {
+ return null;
+ }
+
+ return scene.getObject(applyOKey) as Image ?? null;
+ }
+
+ private _captureCropSnapshot(imageShape: Image): IImageCropSnapshot {
+ return {
+ transform: imageShape.getState(),
+ srcRect: imageShape.srcRect == null ? imageShape.srcRect : { ...imageShape.srcRect },
+ };
+ }
+
+ private _restoreCropSnapshot(imageShape: Image, imageCropperObject: ImageCropperObject): void {
+ const snapshot = this._cropSnapshots.get(imageCropperObject);
+ if (snapshot) {
+ imageShape.transformByStateCloseCropper(snapshot.transform);
+ imageShape.setSrcRect(snapshot.srcRect);
+ }
+ }
+
+ private _registerCropShortcuts(imageCropperObject: ImageCropperObject): void {
+ this._cropShortcutDisposables.dispose();
+ this._cropShortcutDisposables.add(imageCropperObject.onDispose$.subscribeEvent(() => {
+ this._activeCropSession = null;
+ this._cropping$.next(false);
+ this._cropShortcutDisposables.dispose();
+ }));
+ this._cropShortcutDisposables.add(this._shortcutService.registerShortcut({
+ id: CloseImageCropOperation.id,
+ binding: KeyCode.ENTER,
+ priority: 1000,
+ }));
+ this._cropShortcutDisposables.add(this._shortcutService.registerShortcut({
+ id: CloseImageCropOperation.id,
+ binding: KeyCode.ESC,
+ priority: 1000,
+ staticParameters: { isCancel: true },
+ }));
+ }
+
+ private _addListenerOnImage(scene: Scene): void {
+ const transformer = scene.getTransformerByCreate();
+ let startTransform: Nullable<ITransformState> = null;
+
+ this.disposeWithMe(
+ transformer.changeStart$.subscribe((state) => {
+ const cropObject = state.objects.values().next().value as ImageCropperObject;
+ if (!(cropObject instanceof ImageCropperObject)) {
+ return;
+ }
+
+ const { left, top, height, width, angle } = cropObject;
+ startTransform = { left, top, height, width, angle };
+ transformer.clearCopperControl();
+ })
+ );
+
+ this.disposeWithMe(
+ transformer.changeEnd$.subscribe((state) => {
+ const cropObject = state.objects.values().next().value as ImageCropperObject;
+ if (!(cropObject instanceof ImageCropperObject)) {
+ return;
+ }
+
+ const { left, top, height, width, angle } = cropObject;
+ if (!checkIfMove({ left, top, height, width, angle }, startTransform)) {
+ transformer.createControlForCopper(cropObject);
+ return;
+ }
+
+ const applyObject = this._getApplyObjectByCropObject(cropObject);
+ if (applyObject == null) {
+ return;
+ }
+
+ const srcRect = getImageCropRect(applyObject, cropObject);
+ cropObject.refreshSrcRect(srcRect.srcRect, applyObject.getState());
+ transformer.createControlForCopper(cropObject);
+ })
+ );
+ this._endCropListener(scene);
+ }
+
+ private _addHoverForImageCopper(cropper: ImageCropperObject): void {
+ this.disposeWithMe(cropper.onPointerEnter$.subscribeEvent(() => {
+ cropper.cursor = CURSOR_TYPE.MOVE;
+ }));
+ this.disposeWithMe(cropper.onPointerLeave$.subscribeEvent(() => {
+ cropper.cursor = CURSOR_TYPE.DEFAULT;
+ }));
+ }
+
+ private _endCropListener(scene: Scene): void {
+ const transformer = scene.getTransformerByCreate();
+ this.disposeWithMe(
+ transformer.clearControl$.subscribe((changeSelf) => {
+ if (changeSelf === true) {
+ this._commandService.syncExecuteCommand(CloseImageCropOperation.id);
+ }
+ })
+ );
+ }
+}
diff --git a/packages/drawing-ui/src/controllers/mobile/image-update.controller.ts b/packages/drawing-ui/src/controllers/mobile/image-update.controller.ts
new file mode 100644
index 0000000000..f41906f8e5
--- /dev/null
+++ b/packages/drawing-ui/src/controllers/mobile/image-update.controller.ts
@@ -0,0 +1,285 @@
+/**
+ * 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 { ICommandInfo, IDrawingSearch, Nullable } from '@univerjs/core';
+import type { IImageData } from '@univerjs/drawing';
+import type { Image, Scene } from '@univerjs/engine-render';
+import {
+ Disposable,
+ DrawingTypeEnum,
+ ICommandService,
+ ImageSourceType,
+ Inject,
+ IUniverInstanceService,
+ ThemeService,
+ toDisposable,
+} from '@univerjs/core';
+import { getDrawingShapeKeyByDrawingSearch, IDrawingManagerService, SetDrawingSelectedOperation } from '@univerjs/drawing';
+import { CURSOR_TYPE, IRenderManagerService } from '@univerjs/engine-render';
+import { bufferTime, combineLatest, filter, map } from 'rxjs';
+import { ImageResetSizeOperation } from '../../commands/operations/image-reset-size.operation';
+import { DrawingRenderService, ensureDrawingRenderLayer } from '../../services/drawing-render.service';
+import { MobileImagePreviewButton } from '../../views/image-preview/mobile-image-preview-button';
+import { getCurrentUnitInfo } from '../utils';
+import { MobileImageCropperController } from './image-cropper.controller';
+
+export class MobileImageUpdateController extends Disposable {
+ constructor(
+ @ICommandService private readonly _commandService: ICommandService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,
+ @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
+ @Inject(DrawingRenderService) private readonly _drawingRenderService: DrawingRenderService,
+ @Inject(ThemeService) private readonly _themeService: ThemeService,
+ @Inject(MobileImageCropperController) private readonly _imageCropperController: MobileImageCropperController
+ ) {
+ super();
+
+ this._initialize();
+ }
+
+ private _initialize(): void {
+ this._drawingAddListener();
+ this._commandExecutedListener();
+ this._imageUpdateListener();
+ }
+
+ private _commandExecutedListener(): void {
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (command.id === ImageResetSizeOperation.id) {
+ const params = command.params as IDrawingSearch[];
+ if (params == null) {
+ return;
+ }
+ this._resetImageSize(params);
+ }
+ })
+ );
+ }
+
+ private _getSceneAndTransformerByDrawingSearch(unitId: Nullable<string>) {
+ if (unitId == null) {
+ return;
+ }
+
+ const renderObject = this._renderManagerService.getRenderUnitById(unitId);
+ const scene = renderObject?.scene;
+
+ if (scene == null) {
+ return null;
+ }
+
+ return { scene, transformer: scene.getTransformerByCreate() };
+ }
+
+ private _resetImageSize(params: IDrawingSearch[]): void {
+ const updateParams: IImageData[] = [];
+ const sceneList: Scene[] = [];
+
+ params.forEach((param) => {
+ const { unitId, subUnitId, drawingId } = param;
+ const renderObject = this._getSceneAndTransformerByDrawingSearch(unitId);
+
+ if (renderObject == null) {
+ return;
+ }
+
+ const { scene } = renderObject;
+ const imageShapeKey = getDrawingShapeKeyByDrawingSearch({ unitId, subUnitId, drawingId });
+ const imageShape = scene.getObject(imageShapeKey);
+
+ if (imageShape == null) {
+ return true;
+ }
+
+ const imageData = this._drawingManagerService.getDrawingByParam(param);
+ if (imageData == null) {
+ return true;
+ }
+
+ if (imageData.drawingType !== DrawingTypeEnum.DRAWING_IMAGE) {
+ return;
+ }
+
+ (imageShape as Image).resetSize();
+ const { width, height } = (imageShape as Image).getNativeSize();
+
+ if (!sceneList.includes(scene)) {
+ sceneList.push(scene);
+ }
+
+ updateParams.push({
+ ...imageData,
+ transform: {
+ ...imageData.transform,
+ height,
+ width,
+ angle: 0,
+ },
+ srcRect: null,
+ prstGeom: null,
+ } as IImageData);
+ });
+
+ this._drawingManagerService.featurePluginUpdateNotification(updateParams);
+
+ sceneList.forEach((scene) => {
+ scene.getTransformerByCreate().refreshControls().changeNotification();
+ });
+
+ this._commandService.syncExecuteCommand(SetDrawingSelectedOperation.id, params);
+ }
+
+ private _drawingAddListener(): void {
+ this.disposeWithMe(
+ this._drawingManagerService.add$
+ .pipe(
+ bufferTime(33),
+ filter((batches) => batches.length > 0),
+ map((batches) => batches.flat()),
+ map((items) => {
+ const map = new Map<string, IDrawingSearch>();
+ for (const item of items) {
+ map.set(`${item.unitId}|${item.subUnitId}|${item.drawingId}`, item);
+ }
+ return [...map.values()];
+ }),
+ filter((items) => items.length > 0)
+ )
+ .subscribe((uniqueParams) => {
+ this._insertImages(uniqueParams);
+ })
+ );
+ }
+
+ private _insertImages(params: IDrawingSearch[]): void {
+ params.forEach(async (param) => {
+ const { unitId, subUnitId } = param;
+ const renderObject = this._getSceneAndTransformerByDrawingSearch(unitId);
+ const currentSubUnitId = getCurrentUnitInfo(this._currentUniverService, unitId)?.subUnitId;
+
+ if (renderObject == null || currentSubUnitId !== subUnitId) {
+ return;
+ }
+
+ const imageParam = this._drawingManagerService.getDrawingByParam(param) as IImageData;
+ if (imageParam == null) {
+ return;
+ }
+
+ const images = await this._drawingRenderService.renderImages(imageParam, renderObject.scene);
+ const currentImageParam = this._drawingManagerService.getDrawingByParam(param) as IImageData;
+ if (currentImageParam) {
+ this._drawingManagerService.refreshTransform([currentImageParam]);
+ }
+
+ if (images == null || images.length === 0) {
+ return;
+ }
+
+ for (const image of images) {
+ this._addHoverForImage(image);
+ this._addDialogForImage(image, param);
+ }
+ });
+ }
+
+ private _imageUpdateListener(): void {
+ this.disposeWithMe(
+ this._drawingManagerService.update$.subscribe((params) => {
+ params.forEach((param) => {
+ const { unitId, subUnitId, drawingId } = param;
+ const drawingParam = this._drawingManagerService.getDrawingByParam(param) as IImageData;
+
+ if (drawingParam == null) {
+ return;
+ }
+
+ const { transform, drawingType, srcRect, prstGeom, source, imageSourceType } = drawingParam;
+ if (drawingType !== DrawingTypeEnum.DRAWING_IMAGE) {
+ return;
+ }
+
+ const renderObject = this._getSceneAndTransformerByDrawingSearch(unitId);
+ if (renderObject == null) {
+ return;
+ }
+
+ const { scene } = renderObject;
+ if (transform == null) {
+ return true;
+ }
+
+ const drawingShapeKey = getDrawingShapeKeyByDrawingSearch({ unitId, subUnitId, drawingId });
+ const imageShape = scene.getObject(drawingShapeKey) as Image;
+ if (imageShape == null) {
+ return true;
+ }
+
+ const { left = 0, top = 0, width = 0, height = 0, angle = 0, flipX = false, flipY = false, skewX = 0, skewY = 0 } = transform;
+
+ imageShape.transformByState({ left, top, width, height, angle, flipX, flipY, skewX, skewY });
+ (imageShape as Image & { setClipBounds?: (clipBounds?: unknown) => void }).setClipBounds?.((transform as { clipBounds?: unknown }).clipBounds);
+ ensureDrawingRenderLayer(scene, imageShape, drawingParam);
+ imageShape.setSrcRect(srcRect);
+ imageShape.setPrstGeom(prstGeom);
+ if (source != null && source.length > 0 && (imageSourceType === ImageSourceType.BASE64 || imageSourceType === ImageSourceType.URL)) {
+ imageShape.changeSource(source);
+ }
+ });
+ })
+ );
+ }
+
+ private _addHoverForImage(image: Image): void {
+ this.disposeWithMe(toDisposable(image.onPointerEnter$.subscribeEvent(() => {
+ image.cursor = CURSOR_TYPE.GRAB;
+ })));
+ this.disposeWithMe(toDisposable(image.onPointerLeave$.subscribeEvent(() => {
+ image.cursor = CURSOR_TYPE.DEFAULT;
+ })));
+ }
+
+ private _addDialogForImage(image: Image, param: IDrawingSearch): void {
+ const preview = () => {
+ const native = image.getNative();
+ if (native) {
+ this._drawingRenderService.previewImage(
+ `${image.oKey}-viewer-dialog`,
+ native.src,
+ image.getNativeSize().width,
+ image.getNativeSize().height
+ );
+ }
+ };
+ const scene = image.getScene();
+ if (scene) {
+ const button = new MobileImagePreviewButton(image, scene, this._themeService, preview);
+ const registration = this.disposeWithMe(() => button.dispose());
+ button.disposeWithMe(() => registration.dispose());
+ button.disposeWithMe(combineLatest([
+ this._drawingManagerService.focus$,
+ this._imageCropperController.cropping$,
+ ]).subscribe(([drawings, cropping]) => {
+ button.setPreviewEnabled(!cropping && !drawings.some((drawing) =>
+ drawing.unitId === param.unitId && drawing.subUnitId === param.subUnitId && drawing.drawingId === param.drawingId));
+ }));
+ }
+
+ this.disposeWithMe(toDisposable(image.onDblclick$.subscribeEvent(preview)));
+ }
+}
diff --git a/packages/drawing-ui/src/controllers/mobile/ui.controller.ts b/packages/drawing-ui/src/controllers/mobile/ui.controller.ts
new file mode 100644
index 0000000000..6c556ebc0a
--- /dev/null
+++ b/packages/drawing-ui/src/controllers/mobile/ui.controller.ts
@@ -0,0 +1,92 @@
+/**
+ * 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, Inject, Injector } from '@univerjs/core';
+import { BuiltInUIPart, connectInjector, IMenuManagerService, IUIPartsService } from '@univerjs/ui';
+import {
+ SetDrawingAlignBottomOperation,
+ SetDrawingAlignCenterOperation,
+ SetDrawingAlignHorizonOperation,
+ SetDrawingAlignLeftOperation,
+ SetDrawingAlignMiddleOperation,
+ SetDrawingAlignOperation,
+ SetDrawingAlignRightOperation,
+ SetDrawingAlignTopOperation,
+ SetDrawingAlignVerticalOperation,
+} from '../../commands/operations/drawing-align.operation';
+import {
+ SetDrawingArrangeBackOperation,
+ SetDrawingArrangeBackwardOperation,
+ SetDrawingArrangeForwardOperation,
+ SetDrawingArrangeFrontOperation,
+ SetDrawingArrangeOperation,
+} from '../../commands/operations/drawing-arrange.operation';
+import { CancelDrawingGroupOperation, SetDrawingGroupOperation } from '../../commands/operations/drawing-group.operation';
+import { AutoImageCropOperation, CloseImageCropOperation, OpenImageCropOperation } from '../../commands/operations/image-crop.operation';
+import { ImageResetSizeOperation } from '../../commands/operations/image-reset-size.operation';
+import { menuSchema } from '../../menu/schema';
+import { MobileCropActions } from '../../views/crop/MobileCropActions';
+
+export class MobileDrawingUIController extends Disposable {
+ constructor(
+ @ICommandService private readonly _commandService: ICommandService,
+ @IMenuManagerService private readonly _menuManagerService: IMenuManagerService,
+ @IUIPartsService private readonly _uiPartsService: IUIPartsService,
+ @Inject(Injector) private readonly _injector: Injector
+ ) {
+ super();
+
+ this._initMenus();
+ this._initCommands();
+ this._initUiParts();
+ }
+
+ private _initMenus(): void {
+ this._menuManagerService.mergeMenu(menuSchema);
+ }
+
+ private _initCommands(): void {
+ [
+ OpenImageCropOperation,
+ CloseImageCropOperation,
+ ImageResetSizeOperation,
+ SetDrawingAlignOperation,
+ SetDrawingAlignLeftOperation,
+ SetDrawingAlignCenterOperation,
+ SetDrawingAlignRightOperation,
+ SetDrawingAlignTopOperation,
+ SetDrawingAlignMiddleOperation,
+ SetDrawingAlignBottomOperation,
+ SetDrawingAlignHorizonOperation,
+ SetDrawingAlignVerticalOperation,
+ AutoImageCropOperation,
+ SetDrawingGroupOperation,
+ CancelDrawingGroupOperation,
+ SetDrawingArrangeOperation,
+ SetDrawingArrangeFrontOperation,
+ SetDrawingArrangeForwardOperation,
+ SetDrawingArrangeBackOperation,
+ SetDrawingArrangeBackwardOperation,
+ ].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));
+ }
+
+ private _initUiParts(): void {
+ this.disposeWithMe(this._uiPartsService.registerComponent(
+ BuiltInUIPart.CONTENT,
+ () => connectInjector(MobileCropActions, this._injector)
+ ));
+ }
+}
diff --git a/packages/drawing-ui/src/index.ts b/packages/drawing-ui/src/index.ts
index d078a1fc0b..4dbd43c375 100644
--- a/packages/drawing-ui/src/index.ts
+++ b/packages/drawing-ui/src/index.ts
@@ -60,11 +60,14 @@ export {
writeImageSourceToClipboard,
} from './utils/clipboard-image';
export { getUpdateParams } from './utils/get-update-params';
+export { getImageCropRect } from './utils/image-crop-transform';
export { ImageCropperObject } from './views/crop/image-cropper-object';
export {
COMPONENT_IMAGE_POPUP_MENU,
COMPONENT_MOBILE_IMAGE_POPUP_MENU,
} from './views/image-popup-menu/component-name';
+export type { IImagePopupMenuItem } from './views/image-popup-menu/ImagePopupMenu';
+export { MobileObjectListPanel } from './views/object-list-panel/MobileObjectListPanel';
export {
getObjectListPanelSectionIdForDrawingType,
isFloatingObjectListDrawingType,
diff --git a/packages/drawing-ui/src/locale/ar-SA.ts b/packages/drawing-ui/src/locale/ar-SA.ts
index 7f3bf56565..0d0bff4f1b 100644
--- a/packages/drawing-ui/src/locale/ar-SA.ts
+++ b/packages/drawing-ui/src/locale/ar-SA.ts
@@ -18,6 +18,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'drawing-ui': {
+ mobile: { close: 'إغلاق', more: 'المزيد' },
'image-cropper': {
error: 'لا يمكن قص الكائنات غير الصورية.',
},
@@ -88,6 +89,8 @@ const locale: typeof enUS = {
lock: 'قفل النسبة (%)',
},
crop: {
+ cancel: 'إلغاء',
+ apply: 'تم',
title: 'قص',
start: 'بدء القص',
mode: 'حر',
diff --git a/packages/drawing-ui/src/locale/ca-ES.ts b/packages/drawing-ui/src/locale/ca-ES.ts
index e816dd1913..b256d5a9ca 100644
--- a/packages/drawing-ui/src/locale/ca-ES.ts
+++ b/packages/drawing-ui/src/locale/ca-ES.ts
@@ -18,6 +18,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'drawing-ui': {
+ mobile: { close: 'Tanca', more: 'Més' },
'image-cropper': {
error: 'No es poden retallar objectes que no siguin imatges.',
},
@@ -88,6 +89,8 @@ const locale: typeof enUS = {
lock: 'Bloca proporció (%)',
},
crop: {
+ cancel: 'Cancel·la',
+ apply: 'Fet',
title: 'Retalla',
start: 'Inicia retallada',
mode: 'Lliure',
diff --git a/packages/drawing-ui/src/locale/de-DE.ts b/packages/drawing-ui/src/locale/de-DE.ts
index d83f1ad174..e171a1ddd7 100644
--- a/packages/drawing-ui/src/locale/de-DE.ts
+++ b/packages/drawing-ui/src/locale/de-DE.ts
@@ -18,6 +18,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'drawing-ui': {
+ mobile: { close: 'Schließen', more: 'Mehr' },
'image-cropper': {
error: 'Nicht-Bildobjekte können nicht zugeschnitten werden.',
},
@@ -88,6 +89,8 @@ const locale: typeof enUS = {
lock: 'Verhältnis sperren (%)',
},
crop: {
+ cancel: 'Abbrechen',
+ apply: 'Fertig',
title: 'Zuschneiden',
start: 'Zuschneiden starten',
mode: 'Frei',
diff --git a/packages/drawing-ui/src/locale/en-US.ts b/packages/drawing-ui/src/locale/en-US.ts
index 23e26ff6a7..a37cee5d66 100644
--- a/packages/drawing-ui/src/locale/en-US.ts
+++ b/packages/drawing-ui/src/locale/en-US.ts
@@ -16,6 +16,7 @@
const locale = {
'drawing-ui': {
+ mobile: { close: 'Close', more: 'More' },
'image-cropper': {
error: 'Cannot crop non-image objects.',
},
@@ -86,6 +87,8 @@ const locale = {
lock: 'Lock Ratio (%)',
},
crop: {
+ cancel: 'Cancel',
+ apply: 'Done',
title: 'Crop',
start: 'Start Crop',
mode: 'Free',
diff --git a/packages/drawing-ui/src/locale/es-ES.ts b/packages/drawing-ui/src/locale/es-ES.ts
index 678af6504a..6979e7ed04 100644
--- a/packages/drawing-ui/src/locale/es-ES.ts
+++ b/packages/drawing-ui/src/locale/es-ES.ts
@@ -18,6 +18,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'drawing-ui': {
+ mobile: { close: 'Cerrar', more: 'Más' },
'image-cropper': {
error: 'No se pueden recortar objetos que no sean imágenes.',
},
@@ -88,6 +89,8 @@ const locale: typeof enUS = {
lock: 'Bloquear proporción (%)',
},
crop: {
+ cancel: 'Cancelar',
+ apply: 'Listo',
title: 'Recortar',
start: 'Iniciar recorte',
mode: 'Libre',
diff --git a/packages/drawing-ui/src/locale/fa-IR.ts b/packages/drawing-ui/src/locale/fa-IR.ts
index d7c10316df..fb9ec28b04 100644
--- a/packages/drawing-ui/src/locale/fa-IR.ts
+++ b/packages/drawing-ui/src/locale/fa-IR.ts
@@ -18,6 +18,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'drawing-ui': {
+ mobile: { close: 'بستن', more: 'بیشتر' },
'image-cropper': {
error: 'کراپ کردن اشیاء غیرتصویری امکان‌پذیر نیست.',
},
@@ -88,6 +89,8 @@ const locale: typeof enUS = {
lock: 'قفل نسبت (%)',
},
crop: {
+ cancel: 'لغو',
+ apply: 'انجام شد',
title: 'کراپ',
start: 'شروع کراپ',
mode: 'آزاد',
diff --git a/packages/drawing-ui/src/locale/fr-FR.ts b/packages/drawing-ui/src/locale/fr-FR.ts
index 246828913f..b3dd065914 100644
--- a/packages/drawing-ui/src/locale/fr-FR.ts
+++ b/packages/drawing-ui/src/locale/fr-FR.ts
@@ -18,6 +18,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'drawing-ui': {
+ mobile: { close: 'Fermer', more: 'Plus' },
'image-cropper': {
error: 'Impossible de rogner des objets non image.',
},
@@ -88,6 +89,8 @@ const locale: typeof enUS = {
lock: 'Verrouiller le ratio (%)',
},
crop: {
+ cancel: 'Annuler',
+ apply: 'Terminé',
title: 'Rogner',
start: 'Commencer à rogner',
mode: 'Libre',
diff --git a/packages/drawing-ui/src/locale/id-ID.ts b/packages/drawing-ui/src/locale/id-ID.ts
index e60827bc6f..85e75778e3 100644
--- a/packages/drawing-ui/src/locale/id-ID.ts
+++ b/packages/drawing-ui/src/locale/id-ID.ts
@@ -18,6 +18,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'drawing-ui': {
+ mobile: { close: 'Tutup', more: 'Lebih Banyak' },
'image-cropper': {
error: 'Tidak dapat memangkas objek non-gambar.',
},
@@ -88,6 +89,8 @@ const locale: typeof enUS = {
lock: 'Kunci Rasio (%)',
},
crop: {
+ cancel: 'Batal',
+ apply: 'Selesai',
title: 'Pangkas',
start: 'Mulai Pangkas',
mode: 'Bebas',
diff --git a/packages/drawing-ui/src/locale/it-IT.ts b/packages/drawing-ui/src/locale/it-IT.ts
index 95e3241217..141a489001 100644
--- a/packages/drawing-ui/src/locale/it-IT.ts
+++ b/packages/drawing-ui/src/locale/it-IT.ts
@@ -18,6 +18,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'drawing-ui': {
+ mobile: { close: 'Chiudi', more: 'Altro' },
'image-cropper': {
error: 'Impossibile ritagliare oggetti non immagine.',
},
@@ -88,6 +89,8 @@ const locale: typeof enUS = {
lock: 'Blocca proporzioni (%)',
},
crop: {
+ cancel: 'Annulla',
+ apply: 'Fine',
title: 'Ritaglia',
start: 'Inizia ritaglio',
mode: 'Libero',
diff --git a/packages/drawing-ui/src/locale/ja-JP.ts b/packages/drawing-ui/src/locale/ja-JP.ts
index 3f8f08ff83..ab467d0053 100644
--- a/packages/drawing-ui/src/locale/ja-JP.ts
+++ b/packages/drawing-ui/src/locale/ja-JP.ts
@@ -18,6 +18,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'drawing-ui': {
+ mobile: { close: '閉じる', more: 'もっと見る' },
'image-cropper': {
error: '画像以外のオブジェクトはトリミングできません。',
},
@@ -88,6 +89,8 @@ const locale: typeof enUS = {
lock: '縦横比を固定 (%)',
},
crop: {
+ cancel: 'キャンセル',
+ apply: '完了',
title: 'トリミング',
start: 'トリミングを開始',
mode: '自由モード',
diff --git a/packages/drawing-ui/src/locale/ko-KR.ts b/packages/drawing-ui/src/locale/ko-KR.ts
index 39024c0eb6..15f2b68156 100644
--- a/packages/drawing-ui/src/locale/ko-KR.ts
+++ b/packages/drawing-ui/src/locale/ko-KR.ts
@@ -18,6 +18,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'drawing-ui': {
+ mobile: { close: '닫기', more: '더 보기' },
'image-cropper': {
error: '이미지가 아닌 객체는 자를 수 없습니다.',
},
@@ -88,6 +89,8 @@ const locale: typeof enUS = {
lock: '비율 고정 (%)',
},
crop: {
+ cancel: '취소',
+ apply: '완료',
title: '자르기',
start: '자르기 시작',
mode: '자유 모드',
diff --git a/packages/drawing-ui/src/locale/pl-PL.ts b/packages/drawing-ui/src/locale/pl-PL.ts
index 2b4d3d02e5..e452aa33b2 100644
--- a/packages/drawing-ui/src/locale/pl-PL.ts
+++ b/packages/drawing-ui/src/locale/pl-PL.ts
@@ -18,6 +18,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'drawing-ui': {
+ mobile: { close: 'Zamknij', more: 'Więcej' },
'image-cropper': {
error: 'Nie można przyciąć obiektów innych niż obraz.',
},
@@ -88,6 +89,8 @@ const locale: typeof enUS = {
lock: 'Zablokuj proporcje (%)',
},
crop: {
+ cancel: 'Anuluj',
+ apply: 'Gotowe',
title: 'Przytnij',
start: 'Rozpocznij przycinanie',
mode: 'Dowolny',
diff --git a/packages/drawing-ui/src/locale/pt-BR.ts b/packages/drawing-ui/src/locale/pt-BR.ts
index 8c3cc718fb..06af83d9a8 100644
--- a/packages/drawing-ui/src/locale/pt-BR.ts
+++ b/packages/drawing-ui/src/locale/pt-BR.ts
@@ -18,6 +18,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'drawing-ui': {
+ mobile: { close: 'Fechar', more: 'Mais' },
'image-cropper': {
error: 'Não é possível cortar objetos que não são imagens.',
},
@@ -88,6 +89,8 @@ const locale: typeof enUS = {
lock: 'Bloquear proporção (%)',
},
crop: {
+ cancel: 'Cancelar',
+ apply: 'Concluído',
title: 'Cortar',
start: 'Iniciar corte',
mode: 'Livre',
diff --git a/packages/drawing-ui/src/locale/ru-RU.ts b/packages/drawing-ui/src/locale/ru-RU.ts
index dcb91b2fca..c9a6aef11e 100644
--- a/packages/drawing-ui/src/locale/ru-RU.ts
+++ b/packages/drawing-ui/src/locale/ru-RU.ts
@@ -18,6 +18,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'drawing-ui': {
+ mobile: { close: 'Закрыть', more: 'Больше' },
'image-cropper': {
error: 'Невозможно обрезать не изображения.',
},
@@ -88,6 +89,8 @@ const locale: typeof enUS = {
lock: 'Заблокировать пропорции (%)',
},
crop: {
+ cancel: 'Отмена',
+ apply: 'Готово',
title: 'Обрезка',
start: 'Начать обрезку',
mode: 'Свободный',
diff --git a/packages/drawing-ui/src/locale/sk-SK.ts b/packages/drawing-ui/src/locale/sk-SK.ts
index 336c83a76b..66944b3777 100644
--- a/packages/drawing-ui/src/locale/sk-SK.ts
+++ b/packages/drawing-ui/src/locale/sk-SK.ts
@@ -18,6 +18,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'drawing-ui': {
+ mobile: { close: 'Zavrieť', more: 'Viac' },
'image-cropper': {
error: 'Nedá sa orezať neobrázkový objekt.',
},
@@ -88,6 +89,8 @@ const locale: typeof enUS = {
lock: 'Uzamknúť pomer (%)',
},
crop: {
+ cancel: 'Zrušiť',
+ apply: 'Hotovo',
title: 'Orezanie',
start: 'Začať orezanie',
mode: 'Voľne',
diff --git a/packages/drawing-ui/src/locale/vi-VN.ts b/packages/drawing-ui/src/locale/vi-VN.ts
index 469a2c4b03..83f50ccdda 100644
--- a/packages/drawing-ui/src/locale/vi-VN.ts
+++ b/packages/drawing-ui/src/locale/vi-VN.ts
@@ -18,6 +18,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'drawing-ui': {
+ mobile: { close: 'Đóng', more: 'Thêm' },
'image-cropper': {
error: 'Không thể cắt phần tử không phải hình ảnh',
},
@@ -88,6 +89,8 @@ const locale: typeof enUS = {
lock: 'Khóa tỷ lệ (%)',
},
crop: {
+ cancel: 'Hủy',
+ apply: 'Xong',
title: 'Cắt',
start: 'Bắt đầu cắt',
mode: 'Cắt tự do tỷ lệ',
diff --git a/packages/drawing-ui/src/locale/zh-CN.ts b/packages/drawing-ui/src/locale/zh-CN.ts
index 105a489c83..d158201407 100644
--- a/packages/drawing-ui/src/locale/zh-CN.ts
+++ b/packages/drawing-ui/src/locale/zh-CN.ts
@@ -18,6 +18,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'drawing-ui': {
+ mobile: { close: '关闭', more: '更多' },
'image-cropper': {
error: '无法裁剪非图片元素',
},
@@ -88,6 +89,8 @@ const locale: typeof enUS = {
lock: '锁定比例 (%)',
},
crop: {
+ cancel: '取消',
+ apply: '完成',
title: '裁剪',
start: '开始裁剪',
mode: '自由比例裁剪',
diff --git a/packages/drawing-ui/src/locale/zh-HK.ts b/packages/drawing-ui/src/locale/zh-HK.ts
index 6866a90edd..d961c5f80b 100644
--- a/packages/drawing-ui/src/locale/zh-HK.ts
+++ b/packages/drawing-ui/src/locale/zh-HK.ts
@@ -18,6 +18,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'drawing-ui': {
+ mobile: { close: '關閉', more: '更多' },
'image-cropper': {
error: '無法裁切非圖片元素',
},
@@ -88,6 +89,8 @@ const locale: typeof enUS = {
lock: '鎖定比例 (%)',
},
crop: {
+ cancel: '取消',
+ apply: '完成',
title: '裁切',
start: '開始裁切',
mode: '自由比例裁切',
diff --git a/packages/drawing-ui/src/locale/zh-TW.ts b/packages/drawing-ui/src/locale/zh-TW.ts
index 9f455c159c..daf9ee6b67 100644
--- a/packages/drawing-ui/src/locale/zh-TW.ts
+++ b/packages/drawing-ui/src/locale/zh-TW.ts
@@ -18,6 +18,7 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'drawing-ui': {
+ mobile: { close: '關閉', more: '更多' },
'image-cropper': {
error: '無法裁切非圖片元素',
},
@@ -88,6 +89,8 @@ const locale: typeof enUS = {
lock: '鎖定比例 (%)',
},
crop: {
+ cancel: '取消',
+ apply: '完成',
title: '裁切',
start: '開始裁切',
mode: '自由比例裁切',
diff --git a/packages/drawing-ui/src/mobile-plugin.ts b/packages/drawing-ui/src/mobile-plugin.ts
index 36498690e3..9a687c03d7 100644
--- a/packages/drawing-ui/src/mobile-plugin.ts
+++ b/packages/drawing-ui/src/mobile-plugin.ts
@@ -22,10 +22,10 @@ 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 { MobileImageCropperController } from './controllers/mobile/image-cropper.controller';
+import { MobileImageUpdateController } from './controllers/mobile/image-update.controller';
+import { MobileDrawingUIController } from './controllers/mobile/ui.controller';
import { DrawingImageClipService } from './services/drawing-image-clip.service';
import { DrawingRenderService } from './services/drawing-render.service';
@@ -57,9 +57,9 @@ export class UniverDrawingMobileUIPlugin extends Plugin {
override onRendered(): void {
this._injector.get(DrawingUpdateController);
- this._injector.get(DrawingUIController);
- this._injector.get(ImageCropperController);
- this._injector.get(ImageUpdateController);
+ this._injector.get(MobileDrawingUIController);
+ this._injector.get(MobileImageCropperController);
+ this._injector.get(MobileImageUpdateController);
}
private _initDependencies(): void {
@@ -67,9 +67,9 @@ export class UniverDrawingMobileUIPlugin extends Plugin {
[DrawingImageClipService],
[DrawingRenderService],
[DrawingUpdateController],
- [DrawingUIController],
- [ImageCropperController],
- [ImageUpdateController],
+ [MobileDrawingUIController],
+ [MobileImageCropperController],
+ [MobileImageUpdateController],
];
dependencies.forEach((dependency) => this._injector.add(dependency));
diff --git a/packages/drawing-ui/src/utils/__tests__/image-crop-transform.spec.ts b/packages/drawing-ui/src/utils/__tests__/image-crop-transform.spec.ts
new file mode 100644
index 0000000000..ed618cfaa2
--- /dev/null
+++ b/packages/drawing-ui/src/utils/__tests__/image-crop-transform.spec.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 { describe, expect, it } from 'vitest';
+import { getImageCropRect } from '../image-crop-transform';
+
+describe('getImageCropRect', () => {
+ it('keeps asymmetric crop insets in image coordinates', () => {
+ const result = getImageCropRect({ left: 10, top: 20, width: 200, height: 100, angle: 0 }, { left: 30, top: 30, width: 150, height: 60 });
+ expect(result.srcRectAngle).toEqual({ left: 20, top: 10, right: 30, bottom: 30 });
+ expect(result.srcRect).toEqual(result.srcRectAngle);
+ });
+ it('accounts for different rotation centers without changing the crop size', () => {
+ const { srcRectAngle } = getImageCropRect({ left: 0, top: 0, width: 200, height: 100, angle: 90 }, { left: 50, top: 10, width: 100, height: 60 });
+ expect(srcRectAngle.left).toBeCloseTo(40);
+ expect(srcRectAngle.top).toBeCloseTo(20);
+ expect(srcRectAngle.right).toBeCloseTo(60);
+ expect(srcRectAngle.bottom).toBeCloseTo(20);
+ });
+});
diff --git a/packages/drawing-ui/src/utils/image-crop-transform.ts b/packages/drawing-ui/src/utils/image-crop-transform.ts
new file mode 100644
index 0000000000..5c23604549
--- /dev/null
+++ b/packages/drawing-ui/src/utils/image-crop-transform.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 { BaseObject } from '@univerjs/engine-render';
+import { degToRad, Vector2 } from '@univerjs/engine-render';
+
+/** Crop insets in image coordinates, accounting for rotation around different centers. */
+export function getImageCropRect(image: Pick<BaseObject, 'left' | 'top' | 'width' | 'height' | 'angle'>, crop: Pick<BaseObject, 'left' | 'top' | 'width' | 'height'>) {
+ const srcRect = {
+ left: crop.left - image.left,
+ top: crop.top - image.top,
+ right: image.left + image.width - crop.left - crop.width,
+ bottom: image.top + image.height - crop.top - crop.height,
+ };
+ const srcRectAngle = { ...srcRect };
+ if (image.angle) {
+ const origin = new Vector2(image.left, image.top);
+ origin.rotateByPoint(degToRad(image.angle), new Vector2(image.left + image.width / 2, image.top + image.height / 2));
+ origin.rotateByPoint(degToRad(-image.angle), new Vector2(crop.left + crop.width / 2, crop.top + crop.height / 2));
+ srcRectAngle.left = crop.left - origin.x;
+ srcRectAngle.top = crop.top - origin.y;
+ srcRectAngle.right = image.width - srcRectAngle.left - crop.width;
+ srcRectAngle.bottom = image.height - srcRectAngle.top - crop.height;
+ }
+ return { srcRect, srcRectAngle };
+}
diff --git a/packages/drawing-ui/src/views/__tests__/DrawingCommonPanelBehavior.spec.tsx b/packages/drawing-ui/src/views/__tests__/DrawingCommonPanelBehavior.spec.tsx
index 0bf6b7d553..19a306eb54 100644
--- a/packages/drawing-ui/src/views/__tests__/DrawingCommonPanelBehavior.spec.tsx
+++ b/packages/drawing-ui/src/views/__tests__/DrawingCommonPanelBehavior.spec.tsx
@@ -24,6 +24,7 @@ import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { Subject } from 'rxjs';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { ComponentsController } from '../../controllers/components.controller';
import { DrawingImageClipService } from '../../services/drawing-image-clip.service';
import { DrawingCommonPanel } from '../panel/DrawingCommonPanel';
@@ -136,6 +137,8 @@ describe('DrawingCommonPanel behavior', () => {
injector.add([IconManager]);
injector.add([ComponentManager]);
injector.add([DrawingImageClipService]);
+ injector.add([ComponentsController]);
+ injector.get(ComponentsController);
drawingManagerService = injector.get(IDrawingManagerService);
});
diff --git a/packages/drawing-ui/src/views/__tests__/DrawingPanelActions.spec.tsx b/packages/drawing-ui/src/views/__tests__/DrawingPanelActions.spec.tsx
index 5d138f5c6a..e5da9d7881 100644
--- a/packages/drawing-ui/src/views/__tests__/DrawingPanelActions.spec.tsx
+++ b/packages/drawing-ui/src/views/__tests__/DrawingPanelActions.spec.tsx
@@ -19,11 +19,11 @@ import type { IDrawingOrderUpdateParam } from '@univerjs/drawing';
import type { ReactElement } from 'react';
import type { Root } from 'react-dom/client';
import { ArrangeTypeEnum, CommandType, DrawingTypeEnum, ICommandService, LocaleType, Univer } from '@univerjs/core';
+import { ConfigProvider } from '@univerjs/design';
import { DrawingManagerService, IDrawingManagerService } from '@univerjs/drawing';
-import { ComponentManager, IconManager, IDialogService, RediContext } from '@univerjs/ui';
+import { ComponentManager, IconManager, IDialogService, IMenuManagerService, IUIPartsService, MenuManagerService, MobileDialogService, RediContext, UIPartsService } from '@univerjs/ui';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
-import { of } from 'rxjs';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { SetDrawingArrangeOperation } from '../../commands/operations/drawing-arrange.operation';
import {
@@ -33,10 +33,11 @@ import {
} from '../../commands/operations/image-crop.operation';
import { DrawingImageClipService } from '../../services/drawing-image-clip.service';
import { ImagePopupMenu } from '../image-popup-menu/ImagePopupMenu';
+import { MobileImagePopupMenu } from '../image-popup-menu/MobileImagePopupMenu';
import { DrawingArrange } from '../panel/DrawingArrange';
import { ImageCropper } from '../panel/ImageCropper';
-(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+Reflect.set(globalThis, 'IS_REACT_ACT_ENVIRONMENT', true);
const unitId = 'drawing-panel-unit';
const subUnitId = 'drawing-panel-subunit';
@@ -118,15 +119,10 @@ describe('drawing panel actions', () => {
injector.add([IDrawingManagerService, { useClass: DrawingManagerService }]);
injector.add([IconManager]);
injector.add([ComponentManager]);
+ injector.add([IMenuManagerService, { useClass: MenuManagerService }]);
injector.add([DrawingImageClipService]);
- injector.add([IDialogService, {
- useValue: {
- open: () => ({ dispose: () => undefined }),
- close: () => undefined,
- closeAll: () => undefined,
- getDialogs$: () => of([]),
- },
- }]);
+ injector.add([IUIPartsService, { useClass: UIPartsService }]);
+ injector.add([IDialogService, { useClass: MobileDialogService }]);
injector.get(IconManager).register({ DrawingEditIcon: () => <span /> });
commandService = injector.get(ICommandService);
@@ -396,4 +392,98 @@ describe('drawing panel actions', () => {
expect(document.querySelector('[data-testid="line-chart-icon"]')).not.toBeNull();
expect(document.querySelector('[data-testid="column-chart-icon"]')).not.toBeNull();
});
+
+ it('executes document image actions directly from the mobile context menu', async () => {
+ const executedCommands: ICommandInfo[] = [];
+ commandService.onCommandExecuted((command) => executedCommands.push(command));
+
+ const rendered = renderWithRediContext(
+ univer.__getInjector(),
+ <ConfigProvider mountContainer={document.body}>
+ <MobileImagePopupMenu
+ popup={{
+ extraProps: {
+ variant: 'doc-floating-toolbar',
+ menuItems: [{
+ label: 'drawing.edit',
+ index: 0,
+ commandId: chartEditCommandId,
+ commandParams: { source: 'mobile' },
+ disable: false,
+ }],
+ },
+ }}
+ />
+ </ConfigProvider>
+ );
+ root = rendered.root;
+ container = rendered.container;
+
+ expect(container.querySelector('button[aria-label="drawing-ui.mobile.more"]')).toBeNull();
+ const edit = Array.from(container.querySelectorAll('button')).find((button) => button.textContent === 'drawing.edit');
+ if (!edit) {
+ throw new Error('The document image edit action was not found');
+ }
+ clickElement(edit);
+ await flushPendingCommands();
+
+ expect(executedCommands).toContainEqual({
+ id: chartEditCommandId,
+ type: CommandType.OPERATION,
+ params: { source: 'mobile' },
+ });
+ expect(document.querySelector('[role="dialog"]')).toBeNull();
+ });
+
+ it('executes select options from the shared mobile drawing drawer', async () => {
+ const executedCommands: ICommandInfo[] = [];
+ commandService.onCommandExecuted((command) => executedCommands.push(command));
+
+ const rendered = renderWithRediContext(
+ univer.__getInjector(),
+ <ConfigProvider mountContainer={document.body}>
+ <MobileImagePopupMenu
+ popup={{
+ extraProps: {
+ menuItems: [{
+ type: 'select',
+ label: 'chart.type',
+ index: 0,
+ commandId: chartEditCommandId,
+ disable: false,
+ value: 'line',
+ options: [
+ { label: 'Line', value: 'line' },
+ { label: 'Column', value: 'column' },
+ ],
+ commandParamsFactory: (value) => ({ value }),
+ }],
+ },
+ }}
+ />
+ </ConfigProvider>
+ );
+ root = rendered.root;
+ container = rendered.container;
+
+ const select = Array.from(container.querySelectorAll('button')).find((button) => button.textContent?.includes('chart.type'));
+ if (!select) {
+ throw new Error('Mobile chart selector was not found');
+ }
+ clickElement(select);
+ const option = Array.from(document.querySelectorAll<HTMLButtonElement>('button[aria-pressed]'))
+ .find((button) => button.textContent === 'Column');
+ if (!option) {
+ throw new Error('Mobile chart option was not found.');
+ }
+ clickElement(option);
+ await flushPendingCommands();
+
+ expect(executedCommands).toContainEqual({
+ id: chartEditCommandId,
+ type: CommandType.OPERATION,
+ params: { value: 'column' },
+ });
+ expect(document.querySelector('[role="dialog"]')).toBeNull();
+ });
});
diff --git a/packages/drawing-ui/src/views/crop/MobileCropActions.tsx b/packages/drawing-ui/src/views/crop/MobileCropActions.tsx
new file mode 100644
index 0000000000..a63d4a1a7a
--- /dev/null
+++ b/packages/drawing-ui/src/views/crop/MobileCropActions.tsx
@@ -0,0 +1,60 @@
+/**
+ * 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 } from '@univerjs/core';
+import { MobileActionRow } from '@univerjs/design';
+import { CheckMarkIcon, CloseIcon } from '@univerjs/icons';
+import { useDependency, useObservable } from '@univerjs/ui';
+import { CloseImageCropOperation } from '../../commands/operations/image-crop.operation';
+import { MobileImageCropperController } from '../../controllers/mobile/image-cropper.controller';
+
+export function MobileCropActions() {
+ const commandService = useDependency(ICommandService);
+ const localeService = useDependency(LocaleService);
+ const cropperController = useDependency(MobileImageCropperController);
+ const cropping = useObservable(cropperController.cropping$, false);
+
+ if (!cropping) {
+ return null;
+ }
+
+ return (
+ <div
+ role="group"
+ aria-label={localeService.t<LocaleKey>('drawing-ui.image-panel.crop.title')}
+ className="
+ univer-absolute univer-inset-x-0 univer-bottom-0 univer-z-[1200] univer-grid univer-grid-cols-2
+ univer-gap-3 univer-bg-gray-0 univer-p-3 univer-pb-[max(12px,env(safe-area-inset-bottom))]
+ univer-shadow-lg
+ dark:!univer-bg-gray-900
+ "
+ >
+ <MobileActionRow
+ icon={<CloseIcon />}
+ title={localeService.t<LocaleKey>('drawing-ui.image-panel.crop.cancel')}
+ variant="subtle"
+ onClick={() => commandService.executeCommand(CloseImageCropOperation.id, { isCancel: true })}
+ />
+ <MobileActionRow
+ icon={<CheckMarkIcon />}
+ title={localeService.t<LocaleKey>('drawing-ui.image-panel.crop.apply')}
+ className="!univer-bg-primary-600 !univer-text-white"
+ onClick={() => commandService.executeCommand(CloseImageCropOperation.id)}
+ />
+ </div>
+ );
+}
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 2abf527477..de11282200 100644
--- a/packages/drawing-ui/src/views/image-popup-menu/ImagePopupMenu.tsx
+++ b/packages/drawing-ui/src/views/image-popup-menu/ImagePopupMenu.tsx
@@ -15,6 +15,7 @@
*/
import type { DocumentDataModel } from '@univerjs/core';
+import type { IValueOption } from '@univerjs/ui';
import type { ReactNode } from 'react';
import type { LocaleKey } from '../../locale/types';
import {
@@ -43,7 +44,7 @@ export interface IImagePopupMenuItem {
disable: boolean;
type?: 'button' | 'select';
value?: string;
- options?: Array<{ icon?: string; label: unknown; value: string }>;
+ options?: Array<{ icon?: string; label: IValueOption['label']; value: string }>;
commandParamsFactory?: (value: string) => object;
hideOnClick?: boolean;
icon?: string;
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 016e18850f..98287c121e 100644
--- a/packages/drawing-ui/src/views/image-popup-menu/MobileImagePopupMenu.tsx
+++ b/packages/drawing-ui/src/views/image-popup-menu/MobileImagePopupMenu.tsx
@@ -14,50 +14,69 @@
* limitations under the License.
*/
-import type { IImagePopupMenuExtraProps, IImagePopupMenuItem } from './ImagePopupMenu';
-import { ICommandService, LocaleService } from '@univerjs/core';
-import { MobileActionRow } from '@univerjs/design';
-import { IDialogService, useDependency } from '@univerjs/ui';
+import type { IMenuSchema } from '@univerjs/ui';
+import type { IImagePopupMenuExtraProps } from './ImagePopupMenu';
+import { ICommandService } from '@univerjs/core';
+import { IDialogService, MenuItemType, MobileMenu, useDependency } from '@univerjs/ui';
+import { of } from 'rxjs';
interface IMobileImagePopupMenuProps {
popup: {
- extraProps?: Pick<IImagePopupMenuExtraProps, 'menuItems'> & { dialogId?: string };
+ extraProps?: Pick<IImagePopupMenuExtraProps, 'menuItems' | 'variant'> & { dialogId?: string; onClose?: () => void };
};
}
export function MobileImagePopupMenu({ popup }: IMobileImagePopupMenuProps) {
- const menuItems = popup?.extraProps?.menuItems;
const commandService = useDependency(ICommandService);
- const localeService = useDependency(LocaleService);
const dialogService = useDependency(IDialogService);
-
+ const menuItems = popup.extraProps?.menuItems;
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);
- }
- };
+ const schemas: IMenuSchema[] = menuItems.map((item) => ({
+ key: item.commandId,
+ order: item.index,
+ item: item.type === 'select'
+ ? {
+ id: item.commandId,
+ type: MenuItemType.SELECTOR,
+ title: item.label,
+ value$: of(item.value),
+ disabled$: of(item.disable || !item.options?.length),
+ selections: item.options,
+ }
+ : {
+ id: item.commandId,
+ type: MenuItemType.BUTTON,
+ title: item.label,
+ disabled$: of(item.disable),
+ },
+ }));
return (
- <div className="univer-flex univer-flex-col univer-gap-2">
- {menuItems.map((item) => {
- const label = localeService.t(item.label);
-
- return (
- <MobileActionRow
- key={`${item.commandId}-${item.label}`}
- title={label}
- aria-label={label}
- variant="subtle"
- disabled={item.disable}
- onClick={() => handleSelect(item)}
- />
- );
- })}
- </div>
+ <MobileMenu
+ presentation={popup.extraProps?.variant ? 'context-bar' : 'drawer'}
+ schemas={schemas}
+ onOptionSelect={async ({ id, value }) => {
+ const item = menuItems.find((item) => item.commandId === id);
+ if (!item || item.disable) {
+ return;
+ }
+ if (item.type === 'select' && (typeof value !== 'string' || !item.options?.some((option) => option.value === value))) {
+ return;
+ }
+ const params = item.type === 'select' && typeof value === 'string'
+ ? item.commandParamsFactory?.(value) ?? { ...item.commandParams, value }
+ : item.commandParams;
+ await commandService.executeCommand(item.commandId, params);
+ if (item.hideOnClick !== false) {
+ popup.extraProps?.onClose?.();
+ if (popup.extraProps?.dialogId) {
+ dialogService.close(popup.extraProps.dialogId);
+ }
+ }
+ }}
+ />
);
}
diff --git a/packages/drawing-ui/src/views/image-preview/__tests__/mobile-image-preview-button.spec.ts b/packages/drawing-ui/src/views/image-preview/__tests__/mobile-image-preview-button.spec.ts
new file mode 100644
index 0000000000..9aa2712504
--- /dev/null
+++ b/packages/drawing-ui/src/views/image-preview/__tests__/mobile-image-preview-button.spec.ts
@@ -0,0 +1,116 @@
+/**
+ * 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 { Injector, ThemeService } from '@univerjs/core';
+import { DeviceType, Image, PointerInput, Scene, SceneViewer, Vector2, Viewport } from '@univerjs/engine-render';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { MobileImagePreviewButton } from '../mobile-image-preview-button';
+
+function pointer(type: string, x = 280, y = 30) {
+ const event = Object.assign(new MouseEvent(type, { clientX: x, clientY: y }), {
+ deviceType: DeviceType.Touch,
+ inputIndex: PointerInput.LeftClick,
+ currentState: null,
+ previousState: null,
+ });
+ Object.defineProperties(event, { offsetX: { value: x }, offsetY: { value: y } });
+ return event;
+}
+
+const cleanups: Array<() => void> = [];
+
+function setup() {
+ const injector = new Injector([[ThemeService]]);
+ const host = new SceneViewer('host');
+ const scene = new Scene('preview', host);
+ const viewport = new Viewport('main', scene, { left: 0, top: 0, width: 400, height: 600 });
+ const image = new Image('image', { image: document.createElement('img'), left: 20, top: 10, width: 280, height: 160 });
+ scene.addObject(image);
+ const preview = vi.fn();
+ const button = new MobileImagePreviewButton(image, scene, injector.get(ThemeService), preview);
+ cleanups.push(() => {
+ viewport.dispose();
+ host.dispose();
+ injector.dispose();
+ });
+ return { scene, image, preview, button };
+}
+
+afterEach(() => {
+ cleanups.splice(0).forEach((cleanup) => cleanup());
+ vi.useRealTimers();
+});
+
+describe('MobileImagePreviewButton', () => {
+ it('picks the preview button above its image and previews on one tap without moving the image', () => {
+ const { scene, image, button, preview } = setup();
+ const original = image.getState();
+ expect(scene.pick(new Vector2(280, 30))).toBe(button);
+ button.triggerPointerDown(pointer('pointerdown'));
+ button.triggerPointerUp(pointer('pointerup'));
+ expect(preview).toHaveBeenCalledOnce();
+ expect(image.getState()).toEqual(original);
+ });
+
+ it('allows the host to scroll when a gesture starts on the button without previewing or dragging the image', () => {
+ const { scene, image, button, preview } = setup();
+ const original = image.getState();
+ const down = vi.fn();
+ scene.onPointerDown$.subscribeEvent(down);
+ button.triggerPointerDown(pointer('pointerdown'));
+ scene.onPointerMove$.emitEvent(pointer('pointermove', 280, 70));
+ scene.onPointerUp$.emitEvent(pointer('pointerup', 280, 70));
+ expect(down).toHaveBeenCalledOnce();
+ expect(preview).not.toHaveBeenCalled();
+ expect(image.getState()).toEqual(original);
+ });
+
+ it('does not preview cancelled, long-press, or multi-pointer gestures', () => {
+ vi.useFakeTimers();
+ const { scene, button, preview } = setup();
+ button.triggerPointerDown(pointer('pointerdown'));
+ scene.onPointerCancel$.emitEvent(pointer('pointercancel'));
+ button.triggerPointerUp(pointer('pointerup'));
+ button.triggerPointerDown(pointer('pointerdown'));
+ vi.advanceTimersByTime(600);
+ button.triggerPointerUp(pointer('pointerup'));
+ button.triggerPointerDown(pointer('pointerdown'));
+ scene.onPointerDown$.emitEvent(pointer('pointerdown', 200, 100));
+ button.triggerPointerUp(pointer('pointerup'));
+ expect(preview).not.toHaveBeenCalled();
+ });
+
+ it('hides when selected or cropping, reappears when enabled, and is removed with the image', () => {
+ const { scene, image, button } = setup();
+ button.setPreviewEnabled(false);
+ expect(button.visible).toBe(false);
+ expect(scene.pick(new Vector2(280, 30))).toBe(image);
+ button.setPreviewEnabled(true);
+ expect(button.visible).toBe(true);
+ image.dispose();
+ expect(scene.getObject(button.oKey)).toBeFalsy();
+ });
+
+ it.each([0.5, 1, 2])('keeps the tap area screen-sized and follows the image at zoom %s', (scale) => {
+ const { scene, image, button } = setup();
+ scene.scale(scale, scale);
+ image.translate(60, 80);
+ expect(button.width * scale).toBe(44);
+ expect(button.height * scale).toBe(44);
+ expect(button.left + button.width).toBe(image.left + image.width);
+ expect(button.top).toBe(image.top);
+ });
+});
diff --git a/packages/drawing-ui/src/views/image-preview/mobile-image-preview-button.ts b/packages/drawing-ui/src/views/image-preview/mobile-image-preview-button.ts
new file mode 100644
index 0000000000..45c211ff5c
--- /dev/null
+++ b/packages/drawing-ui/src/views/image-preview/mobile-image-preview-button.ts
@@ -0,0 +1,171 @@
+/**
+ * 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 { ThemeService } from '@univerjs/core';
+import type { Image, Scene, UniverRenderingContext } from '@univerjs/engine-render';
+import { DisposableCollection } from '@univerjs/core';
+import { render, unmount } from '@univerjs/design';
+import { CURSOR_TYPE, Rect, Vector2 } from '@univerjs/engine-render';
+import { ExpandIcon } from '@univerjs/icons';
+import { createElement } from 'react';
+
+/** Transient canvas chrome: never part of the image model or its transformer. */
+export class MobileImagePreviewButton extends Rect {
+ private _enabled = true;
+ private readonly _icon = document.createElement('img');
+ private readonly _iconContainer = document.createElement('div');
+ private readonly _gesture = new DisposableCollection();
+ private _pressed = false;
+ private _background = '';
+ private _border = '';
+ private _pressedBackground = '';
+
+ constructor(
+ private readonly _image: Image,
+ private readonly _scene: Scene,
+ themeService: ThemeService,
+ preview: () => void
+ ) {
+ super(`${_image.oKey}-mobile-preview`, { width: 44, height: 44 });
+ this.cursor = CURSOR_TYPE.POINTER;
+ this.disposeWithMe(this._gesture);
+ this.disposeWithMe(_image.onDispose$.subscribeEvent(() => this.dispose()));
+ this.disposeWithMe(_image.onTransformChange$.subscribeEvent(() => this._syncPosition()));
+ this.disposeWithMe(_scene.onTransformChange$.subscribeEvent(() => this._syncPosition()));
+ this.disposeWithMe(_scene.beforeRender$.subscribe(() => this._syncPosition()));
+ this.disposeWithMe(themeService.currentTheme$.subscribe(() => {
+ this._background = themeService.getColorFromTheme('white');
+ this._border = themeService.getColorFromTheme('gray.200');
+ this._pressedBackground = themeService.getColorFromTheme('gray.100');
+ render(createElement(
+ ExpandIcon,
+ {
+ width: 20,
+ height: 20,
+ color: themeService.getColorFromTheme('gray.900'),
+ ref: (svg) => {
+ if (svg) {
+ this._icon.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(new XMLSerializer().serializeToString(svg))}`;
+ }
+ },
+ }
+ ), this._iconContainer);
+ this.makeDirty(true);
+ }));
+ this._icon.onload = () => this.makeDirty(true);
+ this.disposeWithMe(() => {
+ this._icon.onload = null;
+ unmount(this._iconContainer);
+ });
+ this.disposeWithMe(this.onPointerDown$.subscribeEvent((event) => {
+ this._gesture.dispose();
+ const start = { x: event.offsetX, y: event.offsetY, time: Date.now() };
+ let moved = false;
+ this._setPressed(true);
+ // Let the host handle scrolling, but never attach the image transformer to this button.
+ this._gesture.add(_scene.onPointerDown$.subscribeEvent((nextEvent) => {
+ if (nextEvent !== event) {
+ moved = true;
+ this._setPressed(false);
+ }
+ }));
+ this._gesture.add(_scene.onPointerMove$.subscribeEvent((moveEvent) => {
+ moved ||= Math.hypot(moveEvent.offsetX - start.x, moveEvent.offsetY - start.y) >= 12;
+ if (moved) {
+ this._setPressed(false);
+ }
+ }));
+ this._gesture.add(_scene.onPointerCancel$.subscribeEvent(() => {
+ this._gesture.dispose();
+ this._setPressed(false);
+ }));
+ this._gesture.add(_scene.onPointerUp$.subscribeEvent((upEvent) => {
+ this._gesture.dispose();
+ this._setPressed(false);
+ if (!moved && this.visible && Date.now() - start.time < 500 &&
+ Math.hypot(upEvent.offsetX - start.x, upEvent.offsetY - start.y) < 12) {
+ preview();
+ }
+ }));
+ }));
+ this.disposeWithMe(this.onClick$.subscribeEvent((_event, state) => state.stopPropagation()));
+ this.disposeWithMe(this.onDblclick$.subscribeEvent((_event, state) => state.stopPropagation()));
+ _scene.addObject(this, _image.getLayerIndex());
+ this._syncPosition();
+ }
+
+ setPreviewEnabled(enabled: boolean): void {
+ this._enabled = enabled;
+ this._syncPosition();
+ }
+
+ override dispose(): void {
+ if (this._disposed) {
+ return;
+ }
+ super.dispose();
+ }
+
+ private _setPressed(pressed: boolean): void {
+ this._pressed = pressed;
+ this.makeDirty(true);
+ }
+
+ private _syncPosition(): void {
+ const { scaleX, scaleY } = this._scene.getAncestorScale();
+ const width = 44 / Math.max(scaleX, 0.01);
+ const height = 44 / Math.max(scaleY, 0.01);
+ const visible = this._enabled && this._image.visible && !this._image.isInGroup &&
+ this._image.width >= width && this._image.height >= height;
+ if (visible !== this.visible) {
+ visible ? this.show() : this.hide();
+ }
+ if (!visible) {
+ return;
+ }
+ if (this.layer && this.getLayerIndex() !== this._image.getLayerIndex()) {
+ this._scene.removeObject(this);
+ this._scene.addObject(this, this._image.getLayerIndex());
+ }
+ const point = this._image.ancestorTransform.applyPoint(new Vector2(this._image.width, 0));
+ const left = point.x - width;
+ const top = point.y;
+ if (left !== this.left || top !== this.top || width !== this.width || height !== this.height) {
+ this.transformByState({ left, top, width, height });
+ }
+ if (this.zIndex !== this._image.zIndex + 0.5) {
+ this.zIndex = this._image.zIndex + 0.5;
+ }
+ }
+
+ protected override _draw(ctx: UniverRenderingContext): void {
+ ctx.save();
+ ctx.scale(this.width / 44, this.height / 44);
+ ctx.translate(6, 6);
+ Rect.drawWith(ctx, {
+ width: 32,
+ height: 32,
+ radius: 8,
+ fill: this._pressed ? this._pressedBackground : this._background,
+ stroke: this._border,
+ strokeWidth: 1,
+ });
+ if (this._icon.complete && this._icon.naturalWidth > 0) {
+ ctx.drawImage(this._icon, 6, 6, 20, 20);
+ }
+ ctx.restore();
+ }
+}
diff --git a/packages/drawing-ui/src/views/object-list-panel/MobileObjectListPanel.tsx b/packages/drawing-ui/src/views/object-list-panel/MobileObjectListPanel.tsx
new file mode 100644
index 0000000000..51984c5de9
--- /dev/null
+++ b/packages/drawing-ui/src/views/object-list-panel/MobileObjectListPanel.tsx
@@ -0,0 +1,359 @@
+/**
+ * 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 type { IObjectListPanelBaseProps, IObjectListRowProps } from './ObjectListPanelBase';
+import { Button, clsx, Input, StateIconButton } from '@univerjs/design';
+import { ArrowDownIcon, ArrowUpIcon, EyeIcon, EyelashIcon, LocateFixedIcon, LockIcon, MoreDownIcon, UnlockIcon } from '@univerjs/icons';
+import { hasCapability, ObjectDetailsEditor, useObjectListPanel, useObjectListRow } from './ObjectListPanelBase';
+
+const mobileIconButtonClassName = `
+ univer-flex univer-size-11 univer-shrink-0 univer-items-center univer-justify-center univer-rounded-xl
+ univer-border-0 univer-bg-gray-100 univer-p-0 univer-text-lg univer-text-gray-600 univer-outline-none
+ active:univer-scale-95 active:univer-bg-primary-100 active:univer-text-primary-600
+ disabled:univer-opacity-40
+ dark:!univer-bg-gray-800 dark:!univer-text-gray-200
+`;
+
+function MobileObjectListInput(props: ComponentProps<typeof Input>) {
+ return (
+ <Input
+ {...props}
+ className={clsx(props.className, 'univer-h-12')}
+ inputClass={clsx(props.inputClass, '!univer-text-base')}
+ />
+ );
+}
+
+export function MobileObjectListPanel(props: IObjectListPanelBaseProps) {
+ const { labels, capabilities, onSelect, onSetVisible, onCommitName, onCommitDescription, onMoveForward, onMoveBackward, onToggleExpanded, onToggleSelectable, onSetSelectable, onLocate, renderPermissionAction } = props;
+ const { selectedIdSet, draggingId, setDraggingId, searchQuery, setSearchQuery, filterMode, setFilterMode, collapsedSectionIds, selectedItem, visibleItems, visibleItemSections, showSectionHeaders, visibilityItems, selectableItems, allVisible, allLocked, canMoveForward, canMoveBackward, showArrangeControls, showLocateControl, canReorder, handleDrop, toggleSectionCollapsed } = useObjectListPanel(props);
+ return (
+ <div
+ className={clsx(`
+ univer-box-border univer-flex univer-min-w-0 univer-max-w-full univer-flex-col univer-gap-3 univer-py-2
+ univer-text-gray-700
+ dark:!univer-text-gray-200
+ `, 'univer-h-auto univer-overflow-visible univer-pb-4')}
+ data-drawing-object-list-panel="true"
+ >
+
+ <div className="univer-flex univer-min-w-0 univer-flex-col univer-gap-2">
+ <div className="univer-flex univer-w-full univer-min-w-0 univer-gap-2">
+ <Button
+ className="univer-h-12 univer-flex-1"
+ size="middle"
+ disabled={visibilityItems.length === 0}
+ onClick={() => onSetVisible(visibilityItems.map((item) => item.id), !allVisible)}
+ >
+ {allVisible ? labels.hideAll : labels.showAll}
+ </Button>
+ {onSetSelectable && (
+ <Button
+ size="middle"
+ className="univer-h-12 univer-flex-1"
+ disabled={selectableItems.length === 0}
+ onClick={() => onSetSelectable(selectableItems.map((item) => item.id), allLocked)}
+ >
+ {allLocked ? (labels.unlockAll ?? labels.unlock) : (labels.lockAll ?? labels.lock)}
+ </Button>
+ )}
+ </div>
+ <div className="univer-flex univer-shrink-0 univer-justify-end univer-gap-1">
+ {showLocateControl && (
+ <button
+ type="button"
+ className={mobileIconButtonClassName}
+
+ aria-label={labels.locate}
+ disabled={!selectedItem?.id}
+ onClick={() => selectedItem && onLocate?.(selectedItem.id)}
+ >
+ <LocateFixedIcon />
+ </button>
+ )}
+ {showArrangeControls && (
+ <>
+ <button
+ type="button"
+ className={mobileIconButtonClassName}
+
+ aria-label={labels.moveForward}
+ disabled={!canMoveForward}
+ onClick={() => selectedItem && onMoveForward?.(selectedItem.id)}
+ >
+ <ArrowUpIcon />
+ </button>
+ <button
+ type="button"
+ className={mobileIconButtonClassName}
+
+ aria-label={labels.moveBackward}
+ disabled={!canMoveBackward}
+ onClick={() => selectedItem && onMoveBackward?.(selectedItem.id)}
+ >
+ <ArrowDownIcon />
+ </button>
+ </>
+ )}
+ </div>
+ </div>
+
+ <div className="univer-flex univer-shrink-0 univer-flex-col univer-gap-2">
+ <Input
+ className="univer-h-12"
+ inputClass="!univer-text-base"
+ value={searchQuery}
+ aria-label={labels.search}
+ placeholder={labels.search}
+ onChange={setSearchQuery}
+ />
+ <div className="univer-flex univer-min-w-0 univer-gap-1">
+ {([
+ ['all', labels.filterAll],
+ ['hidden', labels.filterHidden],
+ ['locked', labels.filterLocked],
+ ] as const).map(([mode, label]) => (
+ <button
+ key={mode}
+ type="button"
+ className={clsx(
+ `
+ univer-min-w-0 univer-flex-1 univer-rounded-md univer-border univer-border-solid
+ univer-px-2 univer-text-xs univer-outline-none univer-transition-colors
+ dark:!univer-border-gray-700
+ `,
+ 'univer-h-11 univer-text-sm',
+ filterMode === mode
+ ? `
+ dark:!univer-bg-primary-900/30
+ univer-border-primary-500 univer-bg-primary-50 univer-text-primary-600
+ dark:!univer-text-primary-200
+ `
+ : clsx(`
+ univer-border-gray-200 univer-bg-gray-0 univer-text-gray-600
+ dark:!univer-bg-gray-900 dark:!univer-text-gray-300
+ `)
+ )}
+ aria-pressed={filterMode === mode}
+ onClick={() => setFilterMode(mode)}
+ >
+ <span className="univer-block univer-truncate">{label}</span>
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <div
+ className="univer-flex-none univer-overflow-visible"
+ >
+ {visibleItems.length === 0
+ ? <div className="univer-py-6 univer-text-center univer-text-sm univer-text-gray-500">{labels.empty}</div>
+ : (
+ <div className="univer-flex univer-min-w-0 univer-flex-col univer-gap-0.5">
+ {visibleItemSections.map((section) => (
+ <div
+ key={section.id || 'default'}
+ className="univer-flex univer-min-w-0 univer-flex-col univer-gap-0.5"
+ >
+ {showSectionHeaders && section.title && (() => {
+ const sectionCollapsed = !!section.id && collapsedSectionIds.has(section.id);
+
+ return (
+ <button
+ type="button"
+ className={clsx(`
+ univer-box-border univer-flex univer-h-11 univer-w-full
+ univer-items-center univer-gap-1 univer-rounded-md univer-border-0
+ univer-bg-transparent univer-px-2 univer-pt-1 univer-text-xs
+ univer-font-semibold univer-uppercase univer-text-gray-400
+ univer-outline-none
+ disabled:univer-cursor-default
+ dark:!univer-text-gray-500
+ `)}
+ aria-label={sectionCollapsed ? labels.expand : labels.collapse}
+ disabled={!section.id}
+ onClick={() => toggleSectionCollapsed(section.id)}
+ >
+ {section.id
+ ? (
+ <span
+ className="
+ univer-flex univer-size-4 univer-shrink-0
+ univer-items-center univer-justify-center
+ "
+ >
+ <MoreDownIcon
+ className={clsx({
+ '-univer-rotate-90 rtl:univer-rotate-90': sectionCollapsed,
+ })}
+ />
+ </span>
+ )
+ : <span className="univer-size-4 univer-shrink-0" />}
+ <span
+ className="
+ univer-min-w-0 univer-flex-1 univer-truncate univer-text-left
+ "
+ >
+ {section.title}
+ </span>
+ <span
+ className="
+ univer-shrink-0 univer-text-[10px] univer-font-medium
+ univer-text-gray-400
+ dark:!univer-text-gray-500
+ "
+ >
+ {section.items.length}
+ </span>
+ </button>
+ );
+ })()}
+ {(!section.id || !collapsedSectionIds.has(section.id)) && section.items.map((item) => (
+ <MobileObjectListRow
+ key={item.id}
+ item={item}
+ selected={selectedIdSet.has(item.id)}
+ labels={labels}
+ permissionAction={renderPermissionAction?.(item)}
+ showLock={!!onToggleSelectable && hasCapability(capabilities, item, 'selectable')}
+ showName={hasCapability(capabilities, item, 'name')}
+ showVisible={hasCapability(capabilities, item, 'visible')}
+ draggable={canReorder && hasCapability(capabilities, item, 'reorder') && !item.disabled && item.canReorder !== false}
+ dragging={draggingId === item.id}
+ onSelect={(multiSelect) => onSelect(item.id, multiSelect)}
+ onToggleExpanded={() => onToggleExpanded?.(item.id)}
+ onToggleVisible={() => onSetVisible([item.id], !item.visible)}
+ onToggleSelectable={() => onToggleSelectable?.(item.id)}
+ onCommitName={(value) => onCommitName(item.id, value)}
+ onDragStart={() => setDraggingId(item.id)}
+ onDragEnd={() => setDraggingId(null)}
+ onDrop={() => handleDrop(item.id)}
+ />
+ ))}
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+
+ <ObjectDetailsEditor
+ InputComponent={MobileObjectListInput}
+ descriptionClassName="!univer-text-base"
+ item={selectedItem}
+ labels={labels}
+ showName={hasCapability(capabilities, selectedItem, 'name')}
+ showDescription={hasCapability(capabilities, selectedItem, 'description')}
+ onCommitName={(value) => selectedItem && onCommitName(selectedItem.id, value)}
+ onCommitDescription={(value) => selectedItem && onCommitDescription(selectedItem.id, value)}
+ />
+ </div>
+ );
+}
+
+function MobileObjectListRow(props: IObjectListRowProps) {
+ const { item, selected, labels, showLock, showName, showVisible, permissionAction, onSelect, onToggleExpanded, onToggleVisible, onToggleSelectable } = props;
+ const { draftName, setDraftName, disabled, level, locked, handleBlur, handleKeyDown } = useObjectListRow(props);
+ return (
+ <div
+ className={clsx(`
+ univer-flex univer-min-h-12 univer-min-w-0 univer-items-center univer-gap-1.5 univer-rounded-xl
+ univer-py-1 univer-pr-1.5
+ `, selected
+ ? 'univer-bg-primary-50'
+ : `
+ univer-bg-gray-50
+ dark:!univer-bg-gray-800
+ `, disabled && 'univer-opacity-50')}
+ style={{ paddingLeft: level * 14 + 4 }}
+ onClick={() => !disabled && onSelect(false)}
+ >
+ {item.isGroup
+ ? (
+ <button
+ type="button"
+ className={mobileIconButtonClassName}
+ aria-label={item.expanded ? labels.collapse : labels.expand}
+ disabled={disabled}
+ onClick={(event) => {
+ event.stopPropagation();
+ onToggleExpanded();
+ }}
+ >
+ <MoreDownIcon
+ className={clsx(!item.expanded && `
+ -univer-rotate-90
+ rtl:univer-rotate-90
+ `)}
+ />
+ </button>
+ )
+ : <span className="univer-w-2 univer-shrink-0" />}
+ {showName
+ ? (
+ <MobileObjectListInput
+ className="univer-w-0 univer-min-w-0 univer-flex-1"
+ value={draftName}
+ disabled={disabled}
+ aria-label={labels.nameInput}
+ onChange={setDraftName}
+ onBlur={handleBlur}
+ onKeyDown={handleKeyDown}
+ onClick={(event) => {
+ event.stopPropagation();
+ if (!disabled) {
+ onSelect(false);
+ }
+ }}
+ />
+ )
+ : <span className="univer-min-w-0 univer-flex-1 univer-truncate univer-text-sm">{item.name}</span>}
+ {permissionAction}
+ {showLock && (
+ <StateIconButton
+ active={locked}
+ emphasizeActive
+ className={mobileIconButtonClassName}
+ disabled={disabled}
+ aria-pressed={locked}
+ aria-label={locked ? labels.unlock : labels.lock}
+ onClick={(event) => {
+ event.stopPropagation();
+ onToggleSelectable();
+ }}
+ >
+ {locked ? <LockIcon /> : <UnlockIcon />}
+ </StateIconButton>
+ )}
+ {showVisible && (
+ <StateIconButton
+ active={!item.visible}
+ className={mobileIconButtonClassName}
+ disabled={disabled}
+ aria-pressed={!item.visible}
+ aria-label={item.visible ? labels.hide : labels.show}
+ onClick={(event) => {
+ event.stopPropagation();
+ onToggleVisible();
+ }}
+ >
+ {item.visible ? <EyeIcon /> : <EyelashIcon />}
+ </StateIconButton>
+ )}
+ </div>
+ );
+}
diff --git a/packages/drawing-ui/src/views/object-list-panel/ObjectListPanelBase.tsx b/packages/drawing-ui/src/views/object-list-panel/ObjectListPanelBase.tsx
index 6b9318fef5..dc03be34b0 100644
--- a/packages/drawing-ui/src/views/object-list-panel/ObjectListPanelBase.tsx
+++ b/packages/drawing-ui/src/views/object-list-panel/ObjectListPanelBase.tsx
@@ -14,7 +14,8 @@
* limitations under the License.
*/
-import type { DragEvent, FocusEvent, KeyboardEvent, MouseEvent, ReactNode } from 'react';
+import type { LocaleService } from '@univerjs/core';
+import type { ComponentProps, ComponentType, DragEvent, FocusEvent, KeyboardEvent, MouseEvent, ReactNode } from 'react';
import { Button, clsx, Input, StateIconButton } from '@univerjs/design';
import {
ArrowDownIcon,
@@ -110,51 +111,43 @@ export type ObjectListPanelTypeNameKey =
| 'unit'
| 'video';
-interface IObjectListPanelLocaleService {
- t: (key: string) => string;
-}
-
-const objectListPanelLabelKeys: Record<keyof IObjectListPanelLabels, string> = {
- title: 'drawing-ui.objectListPanel.title',
- empty: 'drawing-ui.objectListPanel.empty',
- showAll: 'drawing-ui.objectListPanel.showAll',
- hideAll: 'drawing-ui.objectListPanel.hideAll',
- lockAll: 'drawing-ui.objectListPanel.lockAll',
- unlockAll: 'drawing-ui.objectListPanel.unlockAll',
- moveForward: 'drawing-ui.objectListPanel.moveForward',
- moveBackward: 'drawing-ui.objectListPanel.moveBackward',
- close: 'drawing-ui.objectListPanel.close',
- show: 'drawing-ui.objectListPanel.show',
- hide: 'drawing-ui.objectListPanel.hide',
- lock: 'drawing-ui.objectListPanel.lock',
- unlock: 'drawing-ui.objectListPanel.unlock',
- lockHint: 'drawing-ui.objectListPanel.lockHint',
- unlockHint: 'drawing-ui.objectListPanel.unlockHint',
- name: 'drawing-ui.objectListPanel.name',
- nameInput: 'drawing-ui.objectListPanel.nameInput',
- description: 'drawing-ui.objectListPanel.description',
- descriptionPlaceholder: 'drawing-ui.objectListPanel.descriptionPlaceholder',
- details: 'drawing-ui.objectListPanel.details',
- noSelection: 'drawing-ui.objectListPanel.noSelection',
- locate: 'drawing-ui.objectListPanel.locate',
- expand: 'drawing-ui.objectListPanel.expand',
- collapse: 'drawing-ui.objectListPanel.collapse',
- dragToReorder: 'drawing-ui.objectListPanel.dragToReorder',
- search: 'drawing-ui.objectListPanel.search',
- filterAll: 'drawing-ui.objectListPanel.filterAll',
- filterHidden: 'drawing-ui.objectListPanel.filterHidden',
- filterLocked: 'drawing-ui.objectListPanel.filterLocked',
- sectionCanvas: 'drawing-ui.objectListPanel.sectionCanvas',
- sectionFloating: 'drawing-ui.objectListPanel.sectionFloating',
-};
-
-export function getObjectListPanelLabels(localeService: IObjectListPanelLocaleService): IObjectListPanelLabels {
- return Object.fromEntries(
- Object.entries(objectListPanelLabelKeys).map(([labelKey, localeKey]) => [labelKey, localeService.t(localeKey)])
- ) as unknown as IObjectListPanelLabels;
+export function getObjectListPanelLabels(localeService: LocaleService): IObjectListPanelLabels {
+ return {
+ title: localeService.t('drawing-ui.objectListPanel.title'),
+ empty: localeService.t('drawing-ui.objectListPanel.empty'),
+ showAll: localeService.t('drawing-ui.objectListPanel.showAll'),
+ hideAll: localeService.t('drawing-ui.objectListPanel.hideAll'),
+ lockAll: localeService.t('drawing-ui.objectListPanel.lockAll'),
+ unlockAll: localeService.t('drawing-ui.objectListPanel.unlockAll'),
+ moveForward: localeService.t('drawing-ui.objectListPanel.moveForward'),
+ moveBackward: localeService.t('drawing-ui.objectListPanel.moveBackward'),
+ close: localeService.t('drawing-ui.objectListPanel.close'),
+ show: localeService.t('drawing-ui.objectListPanel.show'),
+ hide: localeService.t('drawing-ui.objectListPanel.hide'),
+ lock: localeService.t('drawing-ui.objectListPanel.lock'),
+ unlock: localeService.t('drawing-ui.objectListPanel.unlock'),
+ lockHint: localeService.t('drawing-ui.objectListPanel.lockHint'),
+ unlockHint: localeService.t('drawing-ui.objectListPanel.unlockHint'),
+ name: localeService.t('drawing-ui.objectListPanel.name'),
+ nameInput: localeService.t('drawing-ui.objectListPanel.nameInput'),
+ description: localeService.t('drawing-ui.objectListPanel.description'),
+ descriptionPlaceholder: localeService.t('drawing-ui.objectListPanel.descriptionPlaceholder'),
+ details: localeService.t('drawing-ui.objectListPanel.details'),
+ noSelection: localeService.t('drawing-ui.objectListPanel.noSelection'),
+ locate: localeService.t('drawing-ui.objectListPanel.locate'),
+ expand: localeService.t('drawing-ui.objectListPanel.expand'),
+ collapse: localeService.t('drawing-ui.objectListPanel.collapse'),
+ dragToReorder: localeService.t('drawing-ui.objectListPanel.dragToReorder'),
+ search: localeService.t('drawing-ui.objectListPanel.search'),
+ filterAll: localeService.t('drawing-ui.objectListPanel.filterAll'),
+ filterHidden: localeService.t('drawing-ui.objectListPanel.filterHidden'),
+ filterLocked: localeService.t('drawing-ui.objectListPanel.filterLocked'),
+ sectionCanvas: localeService.t('drawing-ui.objectListPanel.sectionCanvas'),
+ sectionFloating: localeService.t('drawing-ui.objectListPanel.sectionFloating'),
+ };
}
-export function getObjectListPanelTypeName(localeService: IObjectListPanelLocaleService, typeName: ObjectListPanelTypeNameKey): string {
+export function getObjectListPanelTypeName(localeService: LocaleService, typeName: ObjectListPanelTypeNameKey): string {
return localeService.t(`drawing-ui.objectListPanel.typeNames.${typeName}`);
}
@@ -199,7 +192,7 @@ function normalizeText(value: string): string {
return value.trim();
}
-function hasCapability(
+export function hasCapability(
panelCapabilities: IObjectListPanelCapabilities | undefined,
item: Pick<IObjectListPanelItem, 'capabilities'> | null | undefined,
key: keyof IObjectListPanelCapabilities,
@@ -208,28 +201,18 @@ function hasCapability(
return item?.capabilities?.[key] ?? panelCapabilities?.[key] ?? fallback;
}
-export function ObjectListPanelBase(props: IObjectListPanelBaseProps) {
+export function useObjectListPanel(props: IObjectListPanelBaseProps) {
const {
items,
selectedIds,
allObjectIds,
allItems = items,
focusedId,
- labels,
- showHeader = true,
capabilities,
- onSelect,
- onSetVisible,
- onCommitName,
- onCommitDescription,
onMoveForward,
onMoveBackward,
- onToggleExpanded,
- onToggleSelectable,
- onSetSelectable,
onLocate,
onReorder,
- renderPermissionAction,
} = props;
const selectedIdSet = useMemo(() => new Set(selectedIds), [selectedIds]);
const [draggingId, setDraggingId] = useState<string | null>(null);
@@ -342,13 +325,19 @@ export function ObjectListPanelBase(props: IObjectListPanelBaseProps) {
});
};
+ return { selectedIdSet, draggingId, setDraggingId, searchQuery, setSearchQuery, filterMode, setFilterMode, collapsedSectionIds, selectedItem, visibleItems, visibleItemSections, showSectionHeaders, visibilityItems, selectableItems, allVisible, allLocked, canMoveForward, canMoveBackward, showArrangeControls, showLocateControl, canReorder, handleDrop, toggleSectionCollapsed };
+}
+
+export function ObjectListPanelBase(props: IObjectListPanelBaseProps) {
+ const { labels, showHeader = true, capabilities, onSelect, onSetVisible, onCommitName, onCommitDescription, onMoveForward, onMoveBackward, onToggleExpanded, onToggleSelectable, onSetSelectable, onLocate, renderPermissionAction } = props;
+ const { selectedIdSet, draggingId, setDraggingId, searchQuery, setSearchQuery, filterMode, setFilterMode, collapsedSectionIds, selectedItem, visibleItems, visibleItemSections, showSectionHeaders, visibilityItems, selectableItems, allVisible, allLocked, canMoveForward, canMoveBackward, showArrangeControls, showLocateControl, canReorder, handleDrop, toggleSectionCollapsed } = useObjectListPanel(props);
return (
<div
- className="
- univer-box-border univer-flex univer-size-full univer-min-w-0 univer-max-w-full univer-flex-col
- univer-gap-3 univer-overflow-hidden univer-py-2 univer-text-gray-700
+ className={clsx(`
+ univer-box-border univer-flex univer-min-w-0 univer-max-w-full univer-flex-col univer-gap-3 univer-py-2
+ univer-text-gray-700
dark:!univer-text-gray-200
- "
+ `, 'univer-size-full univer-overflow-hidden')}
data-drawing-object-list-panel="true"
>
{showHeader && (
@@ -366,8 +355,9 @@ export function ObjectListPanelBase(props: IObjectListPanelBaseProps) {
)}
<div className="univer-flex univer-min-w-0 univer-items-center univer-justify-between univer-gap-2">
- <div className="univer-flex univer-min-w-0 univer-gap-2">
+ <div className="univer-flex univer-min-w-0 univer-flex-1 univer-gap-2">
<Button
+
size="small"
disabled={visibilityItems.length === 0}
onClick={() => onSetVisible(visibilityItems.map((item) => item.id), !allVisible)}
@@ -426,6 +416,7 @@ export function ObjectListPanelBase(props: IObjectListPanelBaseProps) {
<div className="univer-flex univer-shrink-0 univer-flex-col univer-gap-2">
<Input
+
value={searchQuery}
aria-label={labels.search}
placeholder={labels.search}
@@ -442,23 +433,24 @@ export function ObjectListPanelBase(props: IObjectListPanelBaseProps) {
type="button"
className={clsx(
`
- univer-h-7 univer-min-w-0 univer-flex-1 univer-rounded-md univer-border
- univer-border-solid univer-px-2 univer-text-xs univer-outline-none
- univer-transition-colors
+ univer-min-w-0 univer-flex-1 univer-rounded-md univer-border univer-border-solid
+ univer-px-2 univer-text-xs univer-outline-none univer-transition-colors
dark:!univer-border-gray-700
`,
+ 'univer-h-7',
filterMode === mode
? `
dark:!univer-bg-primary-900/30
univer-border-primary-500 univer-bg-primary-50 univer-text-primary-600
dark:!univer-text-primary-200
`
- : `
+ : clsx(`
univer-border-gray-200 univer-bg-gray-0 univer-text-gray-600
- hover:univer-bg-gray-50
dark:!univer-bg-gray-900 dark:!univer-text-gray-300
+ `, `
+ hover:univer-bg-gray-50
dark:hover:!univer-bg-gray-800
- `
+ `)
)}
aria-pressed={filterMode === mode}
onClick={() => setFilterMode(mode)}
@@ -469,7 +461,9 @@ export function ObjectListPanelBase(props: IObjectListPanelBaseProps) {
</div>
</div>
- <div className="univer-min-h-0 univer-flex-1 univer-overflow-y-auto univer-overflow-x-hidden">
+ <div
+ className="univer-min-h-0 univer-flex-1 univer-overflow-y-auto univer-overflow-x-hidden"
+ >
{visibleItems.length === 0
? <div className="univer-py-6 univer-text-center univer-text-sm univer-text-gray-500">{labels.empty}</div>
: (
@@ -485,18 +479,19 @@ export function ObjectListPanelBase(props: IObjectListPanelBaseProps) {
return (
<button
type="button"
- className="
+ className={clsx(`
univer-box-border univer-flex univer-h-7 univer-w-full
univer-items-center univer-gap-1 univer-rounded-md univer-border-0
univer-bg-transparent univer-px-2 univer-pt-1 univer-text-xs
univer-font-semibold univer-uppercase univer-text-gray-400
univer-outline-none
- hover:univer-bg-gray-50 hover:univer-text-gray-600
disabled:univer-cursor-default
- disabled:hover:univer-bg-transparent
dark:!univer-text-gray-500
+ `, `
+ hover:univer-bg-gray-50 hover:univer-text-gray-600
+ disabled:hover:univer-bg-transparent
dark:hover:!univer-bg-gray-800 dark:hover:!univer-text-gray-300
- "
+ `)}
aria-label={sectionCollapsed ? labels.expand : labels.collapse}
disabled={!section.id}
onClick={() => toggleSectionCollapsed(section.id)}
@@ -576,7 +571,7 @@ export function ObjectListPanelBase(props: IObjectListPanelBaseProps) {
);
}
-function ObjectListRow(props: {
+export interface IObjectListRowProps {
permissionAction?: ReactNode;
item: IObjectListPanelItem;
selected: boolean;
@@ -594,51 +589,20 @@ function ObjectListRow(props: {
onDragStart: () => void;
onDragEnd: () => void;
onDrop: () => void;
-}) {
- const { permissionAction, item, selected, labels, showLock, showName, showVisible, draggable, dragging, onSelect, onToggleExpanded, onToggleVisible, onToggleSelectable, onCommitName, onDragStart, onDragEnd, onDrop } = props;
- const [draftName, setDraftName] = useState(item.name);
- const skipCommitOnBlurRef = useRef(false);
- const disabled = item.disabled === true;
- const level = item.level ?? 0;
- const locked = item.selectable === false;
-
- useEffect(() => {
- setDraftName(item.name);
- }, [item.name]);
+}
- const handleBlur = (event: FocusEvent<HTMLInputElement>) => {
- if (disabled) {
- return;
- }
- if (skipCommitOnBlurRef.current) {
- skipCommitOnBlurRef.current = false;
- return;
- }
- if (event.currentTarget.value !== item.name) {
- onCommitName(event.currentTarget.value);
- }
- };
-
- const handleKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
- if (event.key === 'Enter') {
- event.currentTarget.blur();
- return;
- }
- if (event.key === 'Escape') {
- skipCommitOnBlurRef.current = true;
- setDraftName(item.name);
- event.currentTarget.blur();
- }
- };
+function ObjectListRow(props: IObjectListRowProps) {
+ const { permissionAction, item, selected, labels, showLock, showName, showVisible, draggable, dragging, onSelect, onToggleExpanded, onToggleVisible, onToggleSelectable, onDragStart, onDragEnd, onDrop } = props;
+ const { draftName, setDraftName, disabled, level, locked, handleBlur, handleKeyDown } = useObjectListRow(props);
return (
<div
className={clsx(
`
- univer-box-border univer-flex univer-h-8 univer-w-full univer-min-w-0 univer-max-w-full
- univer-items-center univer-gap-1.5 univer-overflow-hidden univer-rounded-md univer-pr-1.5
- univer-transition-colors
+ univer-box-border univer-flex univer-w-full univer-min-w-0 univer-max-w-full univer-items-center
+ univer-gap-1.5 univer-overflow-hidden univer-rounded-md univer-pr-1.5 univer-transition-colors
`,
+ 'univer-h-8',
!disabled && `
hover:univer-bg-gray-100
dark:hover:!univer-bg-gray-800
@@ -682,14 +646,16 @@ function ObjectListRow(props: {
? (
<button
type="button"
- className="
- univer-flex univer-size-5 univer-shrink-0 univer-items-center univer-justify-center
- univer-rounded univer-border-0 univer-bg-transparent univer-p-0 univer-text-gray-500
- univer-outline-none univer-transition-transform
- hover:univer-bg-gray-100 hover:univer-text-gray-900
+ className={clsx(`
+ univer-flex univer-shrink-0 univer-items-center univer-justify-center univer-rounded
+ univer-border-0 univer-bg-transparent univer-p-0 univer-text-gray-500 univer-outline-none
+ univer-transition-transform
dark:!univer-text-gray-300
+ `, `
+ univer-size-5
+ hover:univer-bg-gray-100 hover:univer-text-gray-900
dark:hover:!univer-bg-gray-800 dark:hover:!univer-text-gray-100
- "
+ `)}
title={item.expanded ? labels.collapse : labels.expand}
aria-label={item.expanded ? labels.collapse : labels.expand}
onClick={(event) => {
@@ -714,15 +680,16 @@ function ObjectListRow(props: {
`)}
inputClass={clsx(
`
- !univer-h-7 univer-min-w-0 univer-overflow-hidden univer-text-ellipsis
- univer-whitespace-nowrap !univer-rounded !univer-border-transparent !univer-bg-transparent
- !univer-px-1 univer-text-sm univer-text-gray-900 !univer-shadow-none
+ univer-min-w-0 univer-overflow-hidden univer-text-ellipsis univer-whitespace-nowrap
+ !univer-rounded !univer-border-transparent !univer-bg-transparent !univer-px-1
+ univer-text-sm univer-text-gray-900 !univer-shadow-none
focus:!univer-border-primary-500 focus:!univer-bg-gray-0 focus:!univer-ring-1
focus:!univer-ring-primary-100
disabled:!univer-bg-transparent disabled:univer-opacity-100
dark:!univer-text-gray-100
dark:focus:!univer-bg-gray-900 dark:focus:!univer-ring-primary-900
`,
+ '!univer-h-7',
disabled && `
univer-text-gray-400
dark:!univer-text-gray-500
@@ -751,6 +718,7 @@ function ObjectListRow(props: {
emphasizeActive
aria-pressed={locked}
type="button"
+
disabled={disabled}
title={locked ? (labels.unlockHint ?? labels.unlock) : (labels.lockHint ?? labels.lock)}
aria-label={locked ? labels.unlock : labels.lock}
@@ -767,6 +735,7 @@ function ObjectListRow(props: {
active={!item.visible}
aria-pressed={!item.visible}
type="button"
+
disabled={disabled}
title={item.visible ? labels.hide : labels.show}
aria-label={item.visible ? labels.hide : labels.show}
@@ -782,15 +751,17 @@ function ObjectListRow(props: {
);
}
-function ObjectDetailsEditor(props: {
+export function ObjectDetailsEditor(props: {
item: IObjectListPanelItem | null;
+ InputComponent?: ComponentType<ComponentProps<typeof Input>>;
+ descriptionClassName?: string;
labels: IObjectListPanelLabels;
showName: boolean;
showDescription: boolean;
onCommitName: (value: string) => void;
onCommitDescription: (value: string) => void;
}) {
- const { item, labels, showName, showDescription, onCommitName, onCommitDescription } = props;
+ const { item, InputComponent = Input, descriptionClassName, labels, showName, showDescription, onCommitName, onCommitDescription } = props;
const [draftName, setDraftName] = useState(item?.name ?? '');
const [draftDescription, setDraftDescription] = useState(item?.description ?? '');
const disabled = item?.disabled === true;
@@ -840,7 +811,8 @@ function ObjectDetailsEditor(props: {
>
{labels.name}
</span>
- <Input
+ <InputComponent
+
value={draftName}
aria-label={labels.nameInput}
disabled={disabled}
@@ -869,7 +841,7 @@ function ObjectDetailsEditor(props: {
{labels.description}
</span>
<textarea
- className="
+ className={clsx(descriptionClassName, `
univer-box-border univer-min-h-16 univer-w-full univer-resize-none univer-rounded-md
univer-border univer-border-solid univer-border-gray-200 univer-bg-gray-0 univer-p-2
univer-text-sm univer-text-gray-900 univer-outline-none
@@ -877,7 +849,7 @@ function ObjectDetailsEditor(props: {
disabled:univer-cursor-not-allowed disabled:univer-opacity-70
dark:!univer-border-gray-700 dark:!univer-bg-gray-900 dark:!univer-text-gray-100
dark:focus:!univer-ring-primary-900
- "
+ `)}
value={draftDescription}
disabled={disabled}
placeholder={labels.descriptionPlaceholder}
@@ -898,3 +870,41 @@ function ObjectDetailsEditor(props: {
export type IDrawingObjectListItem = IObjectListPanelItem;
export type IDrawingObjectListPanelLabels = IObjectListPanelLabels;
export type IDrawingObjectListPanelProps = IObjectListPanelBaseProps;
+export function useObjectListRow({ item, onCommitName }: Pick<IObjectListRowProps, 'item' | 'onCommitName'>) {
+ const [draftName, setDraftName] = useState(item.name);
+ const skipCommitOnBlurRef = useRef(false);
+ const disabled = item.disabled === true;
+ const level = item.level ?? 0;
+ const locked = item.selectable === false;
+
+ useEffect(() => {
+ setDraftName(item.name);
+ }, [item.name]);
+
+ const handleBlur = (event: FocusEvent<HTMLInputElement>) => {
+ if (disabled) {
+ return;
+ }
+ if (skipCommitOnBlurRef.current) {
+ skipCommitOnBlurRef.current = false;
+ return;
+ }
+ if (event.currentTarget.value !== item.name) {
+ onCommitName(event.currentTarget.value);
+ }
+ };
+
+ const handleKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
+ if (event.key === 'Enter') {
+ event.currentTarget.blur();
+ return;
+ }
+ if (event.key === 'Escape') {
+ skipCommitOnBlurRef.current = true;
+ setDraftName(item.name);
+ event.currentTarget.blur();
+ }
+ };
+
+ return { draftName, setDraftName, disabled, level, locked, handleBlur, handleKeyDown };
+}
diff --git a/packages/drawing-ui/src/views/object-list-panel/__tests__/ObjectListPanelBase.spec.tsx b/packages/drawing-ui/src/views/object-list-panel/__tests__/ObjectListPanelBase.spec.tsx
index f52a00156e..6b4ecd0acc 100644
--- a/packages/drawing-ui/src/views/object-list-panel/__tests__/ObjectListPanelBase.spec.tsx
+++ b/packages/drawing-ui/src/views/object-list-panel/__tests__/ObjectListPanelBase.spec.tsx
@@ -21,116 +21,122 @@ import { LocaleService, LocaleType, Univer } from '@univerjs/core';
import { RediContext } from '@univerjs/ui';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
-import { afterEach, beforeEach, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import enUS from '../../../locale/en-US';
+import { MobileObjectListPanel } from '../MobileObjectListPanel';
import { getObjectListPanelLabels, ObjectListPanelBase } from '../ObjectListPanelBase';
-(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { value: true, configurable: true });
-let root: Root;
-let container: HTMLDivElement;
-let univer: Univer;
-let visibilityChanges: Array<{ ids: string[]; visible: boolean }>;
-let selectableChanges: Array<{ ids: string[]; selectable: boolean }>;
+describe.each([
+ { name: 'desktop', PanelComponent: ObjectListPanelBase },
+ { name: 'mobile', PanelComponent: MobileObjectListPanel },
+])('$name object list', ({ PanelComponent }) => {
+ let root: Root;
+ let container: HTMLDivElement;
+ let univer: Univer;
+ let visibilityChanges: Array<{ ids: string[]; visible: boolean }>;
+ let selectableChanges: Array<{ ids: string[]; selectable: boolean }>;
-beforeEach(() => {
- univer = new Univer({ locale: LocaleType.EN_US, locales: { [LocaleType.EN_US]: enUS } });
- container = document.createElement('div');
- document.body.appendChild(container);
- root = createRoot(container);
- visibilityChanges = [];
- selectableChanges = [];
-});
+ beforeEach(() => {
+ univer = new Univer({ locale: LocaleType.EN_US, locales: { [LocaleType.EN_US]: enUS } });
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ visibilityChanges = [];
+ selectableChanges = [];
+ });
-afterEach(() => {
- act(() => root.unmount());
- container.remove();
- univer.dispose();
-});
+ afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ univer.dispose();
+ });
-function render(element: ReactElement) {
- act(() => root.render(element));
- return { rerender: (next: ReactElement) => act(() => root.render(next)) };
-}
+ function render(element: ReactElement) {
+ act(() => root.render(element));
+ return { rerender: (next: ReactElement) => act(() => root.render(next)) };
+ }
-function getButton(name: string): HTMLButtonElement {
- const button = Array.from(container.querySelectorAll('button')).find((item) => item.textContent === name);
- if (!button) {
- throw new Error(`Button not found: ${name}`);
+ function getButton(name: string): HTMLButtonElement {
+ const button = Array.from(container.querySelectorAll('button')).find((item) => item.textContent === name);
+ if (!button) {
+ throw new Error(`Button not found: ${name}`);
+ }
+ return button;
}
- return button;
-}
-function click(button: HTMLButtonElement): void {
- act(() => button.click());
-}
+ function click(button: HTMLButtonElement): void {
+ act(() => button.click());
+ }
-function panel(items: IObjectListPanelItem[], props: Partial<IObjectListPanelBaseProps> = {}) {
- const injector = univer.__getInjector();
- return (
- <RediContext.Provider value={{ injector }}>
- <ObjectListPanelBase
- items={items}
- selectedIds={[]}
- labels={getObjectListPanelLabels(injector.get(LocaleService))}
- onSelect={() => {}}
- onCommitName={() => {}}
- onCommitDescription={() => {}}
- onSetVisible={(ids, visible) => visibilityChanges.push({ ids, visible })}
- onSetSelectable={(ids, selectable) => selectableChanges.push({ ids, selectable })}
- {...props}
- />
- </RediContext.Provider>
- );
-}
+ function panel(items: IObjectListPanelItem[], props: Partial<IObjectListPanelBaseProps> = {}) {
+ const injector = univer.__getInjector();
+ return (
+ <RediContext.Provider value={{ injector }}>
+ <PanelComponent
+ items={items}
+ selectedIds={[]}
+ labels={getObjectListPanelLabels(injector.get(LocaleService))}
+ onSelect={() => {}}
+ onCommitName={() => {}}
+ onCommitDescription={() => {}}
+ onSetVisible={(ids, visible) => visibilityChanges.push({ ids, visible })}
+ onSetSelectable={(ids, selectable) => selectableChanges.push({ ids, selectable })}
+ {...props}
+ />
+ </RediContext.Provider>
+ );
+ }
-it('switches both bulk actions from current model state, including external updates', () => {
- const original = [{ id: 'a', name: 'A', visible: true }, { id: 'b', name: 'B', visible: true }];
- const view = render(panel(original));
- click(getButton('Hide all'));
- expect(visibilityChanges).toEqual([{ ids: ['a', 'b'], visible: false }]);
- click(getButton('Lock all'));
- expect(selectableChanges).toEqual([{ ids: ['a', 'b'], selectable: false }]);
+ it('switches both bulk actions from current model state, including external updates', () => {
+ const original = [{ id: 'a', name: 'A', visible: true }, { id: 'b', name: 'B', visible: true }];
+ const view = render(panel(original));
+ click(getButton('Hide all'));
+ expect(visibilityChanges).toEqual([{ ids: ['a', 'b'], visible: false }]);
+ click(getButton('Lock all'));
+ expect(selectableChanges).toEqual([{ ids: ['a', 'b'], selectable: false }]);
- view.rerender(panel(original.map((item) => ({ ...item, visible: false, selectable: false }))));
- click(getButton('Show all'));
- click(getButton('Unlock all'));
- expect(visibilityChanges[1]).toEqual({ ids: ['a', 'b'], visible: true });
- expect(selectableChanges[1]).toEqual({ ids: ['a', 'b'], selectable: true });
+ view.rerender(panel(original.map((item) => ({ ...item, visible: false, selectable: false }))));
+ click(getButton('Show all'));
+ click(getButton('Unlock all'));
+ expect(visibilityChanges[1]).toEqual({ ids: ['a', 'b'], visible: true });
+ expect(selectableChanges[1]).toEqual({ ids: ['a', 'b'], selectable: true });
- view.rerender(panel(original));
- expect(getButton('Hide all')).toBeTruthy();
- expect(getButton('Lock all')).toBeTruthy();
-});
+ view.rerender(panel(original));
+ expect(getButton('Hide all')).toBeTruthy();
+ expect(getButton('Lock all')).toBeTruthy();
+ });
-it('includes collapsed children and ignores the search filter when normalizing mixed states', () => {
- const group = { id: 'group', name: 'Group', visible: true, selectable: false, isGroup: true, expanded: false };
- render(panel([group], {
- allItems: [group, { id: 'child', visible: false, selectable: true }],
- }));
- const search = container.querySelector<HTMLInputElement>('input[placeholder="Search objects"]')!;
- act(() => {
- Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(search, 'unmatched');
- search.dispatchEvent(new Event('input', { bubbles: true }));
+ it('includes collapsed children and ignores the search filter when normalizing mixed states', () => {
+ const group = { id: 'group', name: 'Group', visible: true, selectable: false, isGroup: true, expanded: false };
+ render(panel([group], {
+ allItems: [group, { id: 'child', visible: false, selectable: true }],
+ }));
+ const search = container.querySelector<HTMLInputElement>('input[placeholder="Search objects"]')!;
+ act(() => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(search, 'unmatched');
+ search.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ click(getButton('Show all'));
+ click(getButton('Lock all'));
+ expect(visibilityChanges).toEqual([{ ids: ['group', 'child'], visible: true }]);
+ expect(selectableChanges).toEqual([{ ids: ['group', 'child'], selectable: false }]);
});
- click(getButton('Show all'));
- click(getButton('Lock all'));
- expect(visibilityChanges).toEqual([{ ids: ['group', 'child'], visible: true }]);
- expect(selectableChanges).toEqual([{ ids: ['group', 'child'], selectable: false }]);
-});
-it('excludes unavailable capabilities and disables actions when no targets exist', () => {
- const items = [
- { id: 'available', name: 'Available', visible: true },
- { id: 'disabled', name: 'Disabled', visible: false, disabled: true },
- { id: 'unsupported', name: 'Unsupported', visible: false, capabilities: { visible: false, selectable: false } },
- ];
- const view = render(panel(items));
- click(getButton('Hide all'));
- click(getButton('Lock all'));
- expect(visibilityChanges).toEqual([{ ids: ['available'], visible: false }]);
- expect(selectableChanges).toEqual([{ ids: ['available'], selectable: false }]);
- view.rerender(panel([]));
- expect((getButton('Show all') as HTMLButtonElement).disabled).toBe(true);
- expect((getButton('Lock all') as HTMLButtonElement).disabled).toBe(true);
+ it('excludes unavailable capabilities and disables actions when no targets exist', () => {
+ const items = [
+ { id: 'available', name: 'Available', visible: true },
+ { id: 'disabled', name: 'Disabled', visible: false, disabled: true },
+ { id: 'unsupported', name: 'Unsupported', visible: false, capabilities: { visible: false, selectable: false } },
+ ];
+ const view = render(panel(items));
+ click(getButton('Hide all'));
+ click(getButton('Lock all'));
+ expect(visibilityChanges).toEqual([{ ids: ['available'], visible: false }]);
+ expect(selectableChanges).toEqual([{ ids: ['available'], selectable: false }]);
+ view.rerender(panel([]));
+ expect(getButton('Show all').disabled).toBe(true);
+ expect(getButton('Lock all').disabled).toBe(true);
+ });
});
diff --git a/packages/drawing-ui/src/views/panel/DrawingAlign.tsx b/packages/drawing-ui/src/views/panel/DrawingAlign.tsx
index ae784b9de8..7caa331fd2 100644
--- a/packages/drawing-ui/src/views/panel/DrawingAlign.tsx
+++ b/packages/drawing-ui/src/views/panel/DrawingAlign.tsx
@@ -33,7 +33,7 @@ export const DrawingAlign = (props: IDrawingAlignProps) => {
const { drawings, alignShow } = props;
- const [alignValue, setAlignValue] = useState<string>(AlignType.default as string);
+ const [alignValue, setAlignValue] = useState<AlignType>(AlignType.default);
const alignOptions = [
{
label: localeService.t<LocaleKey>('drawing-ui.image-panel.align.default'),
@@ -86,9 +86,13 @@ export const DrawingAlign = (props: IDrawingAlignProps) => {
];
function handleAlignChange(value: string | number | boolean) {
- setAlignValue((value as string));
+ const alignType = Object.values(AlignType).find((option) => option === value);
+ if (alignType == null) {
+ return;
+ }
+ setAlignValue(alignType);
commandService.executeCommand(SetDrawingAlignOperation.id, {
- alignType: value as AlignType,
+ alignType,
drawings,
});
}
diff --git a/packages/drawing-ui/src/views/panel/DrawingCommonPanel.tsx b/packages/drawing-ui/src/views/panel/DrawingCommonPanel.tsx
index 1d0fe6d3a3..5a67f17733 100644
--- a/packages/drawing-ui/src/views/panel/DrawingCommonPanel.tsx
+++ b/packages/drawing-ui/src/views/panel/DrawingCommonPanel.tsx
@@ -20,14 +20,10 @@ import { LocaleService } from '@univerjs/core';
import { clsx } from '@univerjs/design';
import { IDrawingManagerService } from '@univerjs/drawing';
import { IRenderManagerService } from '@univerjs/engine-render';
-import { useDependency, useObservable } from '@univerjs/ui';
+import { ComponentManager, useDependency, useObservable } from '@univerjs/ui';
import { filter, map, merge } from 'rxjs';
import { getUpdateParams } from '../../utils/get-update-params';
-import { DrawingAlign } from './DrawingAlign';
-import { DrawingArrange } from './DrawingArrange';
-import { DrawingGroup } from './DrawingGroup';
-import { DrawingTransform } from './DrawingTransform';
-import { ImageCropper } from './ImageCropper';
+import { DRAWING_ALIGN_COMPONENT, DRAWING_ARRANGE_COMPONENT, DRAWING_GROUP_COMPONENT, DRAWING_TRANSFORM_COMPONENT, IMAGE_CROPPER_COMPONENT } from './component-name';
export interface IDrawingCommonPanelProps {
drawings: IDrawingParam[];
@@ -36,6 +32,7 @@ export interface IDrawingCommonPanelProps {
hasAlign?: boolean;
hasCropper?: boolean;
hasGroup?: boolean;
+ onCropStart?: () => void;
}
function getPanelShowState(drawings: IDrawingParam[]) {
@@ -69,6 +66,12 @@ function getPanelShowState(drawings: IDrawingParam[]) {
}
export const DrawingCommonPanel = (props: IDrawingCommonPanelProps) => {
+ const componentManager = useDependency(ComponentManager);
+ const DrawingArrange = componentManager.get(DRAWING_ARRANGE_COMPONENT);
+ const DrawingAlign = componentManager.get(DRAWING_ALIGN_COMPONENT);
+ const DrawingGroup = componentManager.get(DRAWING_GROUP_COMPONENT);
+ const DrawingTransform = componentManager.get(DRAWING_TRANSFORM_COMPONENT);
+ const ImageCropper = componentManager.get(IMAGE_CROPPER_COMPONENT);
const drawingManagerService = useDependency(IDrawingManagerService);
const renderManagerService = useDependency(IRenderManagerService);
const localeService = useDependency(LocaleService);
@@ -91,7 +94,7 @@ export const DrawingCommonPanel = (props: IDrawingCommonPanelProps) => {
),
transformer.changeStart$.pipe(
map((state) => getPanelShowState(
- getUpdateParams(state.objects, drawingManagerService) as IDrawingParam[]
+ getUpdateParams(state.objects, drawingManagerService).filter((drawing): drawing is IDrawingParam => drawing != null)
))
),
]
@@ -124,7 +127,7 @@ export const DrawingCommonPanel = (props: IDrawingCommonPanelProps) => {
<DrawingArrange arrangeShow={hasArrange === true ? arrangeShow : false} drawings={drawings} />
<DrawingTransform transformShow={hasTransform === true ? transformShow : false} drawings={drawings} />
<DrawingAlign alignShow={hasAlign === true ? alignShow : false} drawings={drawings} />
- <ImageCropper cropperShow={hasCropper === true ? cropperShow : false} drawings={drawings} />
+ <ImageCropper cropperShow={hasCropper === true ? cropperShow : false} drawings={drawings} onCropStart={props.onCropStart} />
<DrawingGroup hasGroup={hasGroup} drawings={drawings} />
</>
);
diff --git a/packages/drawing-ui/src/views/panel/DrawingTransform.tsx b/packages/drawing-ui/src/views/panel/DrawingTransform.tsx
index a6d737a996..2dc5ca44f6 100644
--- a/packages/drawing-ui/src/views/panel/DrawingTransform.tsx
+++ b/packages/drawing-ui/src/views/panel/DrawingTransform.tsx
@@ -343,8 +343,11 @@ function DrawingTransformContent(props: IDrawingTransformProps) {
});
const handleLockRatioChange = (val: string | number | boolean) => {
- setLockRatio(val as boolean);
- transformer.keepRatio = val as boolean;
+ if (typeof val !== 'boolean') {
+ return;
+ }
+ setLockRatio(val);
+ transformer.keepRatio = val;
};
return (
diff --git a/packages/drawing-ui/src/views/panel/ImageCropper.tsx b/packages/drawing-ui/src/views/panel/ImageCropper.tsx
index 11f25287d6..3e5565eae4 100644
--- a/packages/drawing-ui/src/views/panel/ImageCropper.tsx
+++ b/packages/drawing-ui/src/views/panel/ImageCropper.tsx
@@ -16,114 +16,23 @@
import type { IDrawingParam } from '@univerjs/core';
import type { LocaleKey } from '../../locale/types';
-import { ICommandService, LocaleService } from '@univerjs/core';
import { Button, clsx, Select } from '@univerjs/design';
import { CreateCopyIcon } from '@univerjs/icons';
-import { ComponentManager, useDependency, useObservable } from '@univerjs/ui';
-import { useEffect, useRef, useState } from 'react';
-import {
- AutoImageCropOperation,
- CloseImageCropOperation,
- CropType,
-} from '../../commands/operations/image-crop.operation';
-import { DrawingImageClipService, IMAGE_CLIP_SHAPE_PICKER_COMPONENT } from '../../services/drawing-image-clip.service';
+
+import { useImageCropper } from './use-image-cropper';
export interface IImageCropperProps {
drawings: IDrawingParam[];
cropperShow: boolean;
+ onCropStart?: () => void;
}
export const ImageCropper = (props: IImageCropperProps) => {
- const commandService = useDependency(ICommandService);
- const localeService = useDependency(LocaleService);
- const clipService = useDependency(DrawingImageClipService);
- const componentManager = useDependency(ComponentManager);
- const canUseShapeClip = useObservable(clipService.canUseShapeClip$, false);
-
- const { drawings, cropperShow } = props;
-
- const drawingParam = drawings[0];
- const [cropValue, setCropValue] = useState<string>(CropType.FREE as string);
- const cropStateRef = useRef(false);
-
- const cropOptions = [
- {
- label: localeService.t<LocaleKey>('drawing-ui.image-panel.crop.mode'),
- value: CropType.FREE,
- },
- {
- label: '1:1',
- value: CropType.R1_1,
- },
- {
- label: '16:9',
- value: CropType.R16_9,
- },
- {
- label: '9:16',
- value: CropType.R9_16,
- },
- {
- label: '5:4',
- value: CropType.R5_4,
- },
- {
- label: '4:5',
- value: CropType.R4_5,
- },
- {
- label: '4:3',
- value: CropType.R4_3,
- },
- {
- label: '3:4',
- value: CropType.R3_4,
- },
- {
- label: '3:2',
- value: CropType.R3_2,
- },
- {
- label: '2:3',
- value: CropType.R2_3,
- },
- ];
-
- useEffect(() => {
- const onChangeStartObserver = commandService.onCommandExecuted((command) => {
- if (command.id === CloseImageCropOperation.id) {
- const params = command.params as { isAuto?: boolean };
- if (!params?.isAuto) {
- cropStateRef.current = false;
- }
- }
- });
-
- return () => {
- onChangeStartObserver?.dispose();
- };
- }, []);
-
- if (drawingParam == null) {
+ const { drawingParam, cropperShow, localeService, cropValue, cropOptions, handleCropChange, onCropperBtnClick, ShapeClipPicker } = useImageCropper(props);
+ if (!drawingParam) {
return null;
}
- function handleCropChange(value: string | number | boolean) {
- setCropValue((value as string));
- if (cropStateRef.current) {
- commandService.executeCommand(AutoImageCropOperation.id, {
- cropType: value as CropType,
- });
- }
- }
-
- const onCropperBtnClick = (val: CropType) => {
- commandService.executeCommand(AutoImageCropOperation.id, {
- cropType: val,
- });
- cropStateRef.current = true;
- };
-
return (
<div
className={clsx('univer-grid univer-gap-2 univer-py-2 univer-text-gray-400', {
@@ -140,7 +49,7 @@ export const ImageCropper = (props: IImageCropperProps) => {
</header>
<div className="univer-flex univer-items-center univer-justify-center univer-gap-2">
- <Button onClick={() => { onCropperBtnClick(cropValue as CropType); }}>
+ <Button onClick={() => onCropperBtnClick(cropValue)}>
<CreateCopyIcon />
{localeService.t<LocaleKey>('drawing-ui.image-panel.crop.start')}
</Button>
@@ -148,12 +57,7 @@ export const ImageCropper = (props: IImageCropperProps) => {
<Select value={cropValue} options={cropOptions} onChange={handleCropChange} />
</div>
- {canUseShapeClip && (() => {
- const ShapeClipPicker = componentManager.get(IMAGE_CLIP_SHAPE_PICKER_COMPONENT);
- return ShapeClipPicker
- ? <ShapeClipPicker />
- : null;
- })()}
+ {ShapeClipPicker && <ShapeClipPicker />}
</div>
);
};
diff --git a/packages/drawing-ui/src/views/panel/MobileDrawingArrange.tsx b/packages/drawing-ui/src/views/panel/MobileDrawingArrange.tsx
new file mode 100644
index 0000000000..cf2aa416ce
--- /dev/null
+++ b/packages/drawing-ui/src/views/panel/MobileDrawingArrange.tsx
@@ -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 { IDrawingParam } from '@univerjs/core';
+import type { LocaleKey } from '../../locale/types';
+import { ArrangeTypeEnum, ICommandService, LocaleService } from '@univerjs/core';
+import { Button, clsx } from '@univerjs/design';
+import { IDrawingManagerService } from '@univerjs/drawing';
+import { IconManager, useDependency, useObservable } from '@univerjs/ui';
+import { SetDrawingArrangeOperation } from '../../commands/operations/drawing-arrange.operation';
+
+interface IMobileDrawingArrangeProps {
+ arrangeShow: boolean;
+ drawings: IDrawingParam[];
+}
+
+export function MobileDrawingArrange(props: IMobileDrawingArrangeProps) {
+ const { arrangeShow, drawings: focusDrawings } = props;
+ const localeService = useDependency(LocaleService);
+ const drawingManagerService = useDependency(IDrawingManagerService);
+ const commandService = useDependency(ICommandService);
+ const iconManager = useDependency(IconManager);
+ const MoveUpIcon = iconManager.get('MoveUpIcon');
+ const MoveDownIcon = iconManager.get('MoveDownIcon');
+ const TopmostIcon = iconManager.get('TopmostIcon');
+ const BottomIcon = iconManager.get('BottomIcon');
+ const drawings = useObservable(
+ () => drawingManagerService.focus$,
+ focusDrawings,
+ false,
+ [drawingManagerService]
+ );
+
+ const arrange = (arrangeType: ArrangeTypeEnum) => {
+ commandService.syncExecuteCommand(SetDrawingArrangeOperation.id, { arrangeType, drawings });
+ };
+
+ return (
+ <div
+ className={clsx('univer-grid univer-gap-2 univer-py-2 univer-text-gray-400', {
+ 'univer-hidden': !arrangeShow,
+ })}
+ >
+ <header
+ className="
+ univer-text-gray-600
+ dark:!univer-text-gray-200
+ "
+ >
+ <div>{localeService.t<LocaleKey>('drawing-ui.image-panel.arrange.title')}</div>
+ </header>
+
+ <div className="univer-grid univer-grid-cols-2 univer-gap-2">
+ <Button className="univer-h-12 univer-w-full" onClick={() => arrange(ArrangeTypeEnum.forward)}>
+ <MoveUpIcon />
+ {localeService.t<LocaleKey>('drawing-ui.image-panel.arrange.forward')}
+ </Button>
+ <Button className="univer-h-12 univer-w-full" onClick={() => arrange(ArrangeTypeEnum.backward)}>
+ <MoveDownIcon />
+ {localeService.t<LocaleKey>('drawing-ui.image-panel.arrange.backward')}
+ </Button>
+ <Button className="univer-h-12 univer-w-full" onClick={() => arrange(ArrangeTypeEnum.front)}>
+ <TopmostIcon />
+ {localeService.t<LocaleKey>('drawing-ui.image-panel.arrange.front')}
+ </Button>
+ <Button className="univer-h-12 univer-w-full" onClick={() => arrange(ArrangeTypeEnum.back)}>
+ <BottomIcon />
+ {localeService.t<LocaleKey>('drawing-ui.image-panel.arrange.back')}
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/drawing-ui/src/views/panel/MobileDrawingControls.tsx b/packages/drawing-ui/src/views/panel/MobileDrawingControls.tsx
new file mode 100644
index 0000000000..e478e2903f
--- /dev/null
+++ b/packages/drawing-ui/src/views/panel/MobileDrawingControls.tsx
@@ -0,0 +1,474 @@
+/**
+ * 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 { IDrawingParam, Nullable } from '@univerjs/core';
+import type { IChangeObserverConfig, Scene } from '@univerjs/engine-render';
+import type { ComponentProps } from 'react';
+import type { LocaleKey } from '../../locale/types';
+import { debounce, DrawingTypeEnum, ICommandService, LocaleService } from '@univerjs/core';
+import { Button, Checkbox, clsx, InputNumber, MobileSelect } from '@univerjs/design';
+import { IDrawingManagerService } from '@univerjs/drawing';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { IconManager, useDependency, useObservable } from '@univerjs/ui';
+import { useEffect, useState } from 'react';
+import { filter, map, merge } from 'rxjs';
+import { AlignType, SetDrawingAlignOperation } from '../../commands/operations/drawing-align.operation';
+import { CancelDrawingGroupOperation, SetDrawingGroupOperation } from '../../commands/operations/drawing-group.operation';
+import { MIN_DRAWING_HEIGHT_LIMIT, MIN_DRAWING_WIDTH_LIMIT, RANGE_DRAWING_ROTATION_LIMIT } from '../../utils/config';
+import { getUpdateParams } from '../../utils/get-update-params';
+import { resolveDrawingUIRotateEnabled } from '../../utils/rotate-enabled';
+import { createDrawingTransformRotationChangeHandler, isDrawingTransformRotationDisabled } from './drawing-transform-rotation';
+
+const INPUT_DEBOUNCE_TIME = 300;
+
+interface IMobileDrawingTransformProps {
+ transformShow: boolean;
+ drawings: IDrawingParam[];
+}
+
+interface IMobileDrawingAlignProps {
+ drawings: IDrawingParam[];
+ alignShow: boolean;
+}
+
+interface IMobileDrawingGroupProps {
+ drawings: IDrawingParam[];
+ hasGroup: boolean;
+}
+
+function MobileDrawingInputNumber(props: ComponentProps<typeof InputNumber>) {
+ return (
+ <InputNumber
+ {...props}
+ controls={false}
+ className={clsx('univer-h-12 univer-w-full', props.className)}
+ inputClassName={clsx('[&_input]:!univer-h-12 [&_input]:!univer-text-base', props.inputClassName)}
+ />
+ );
+}
+
+function MobileDrawingCheckbox(props: ComponentProps<typeof Checkbox>) {
+ return <Checkbox {...props} className={clsx('univer-flex univer-min-h-12 univer-items-center univer-justify-center', props.className)} />;
+}
+
+function MobileDrawingButton(props: ComponentProps<typeof Button>) {
+ return (
+ <Button
+ {...props}
+ className={clsx(`
+ univer-flex univer-min-h-12 univer-flex-1 univer-items-center univer-justify-center univer-gap-2
+ univer-text-base
+ `, props.className)}
+ />
+ );
+}
+
+export function MobileDrawingTransform(props: IMobileDrawingTransformProps) {
+ const renderManagerService = useDependency(IRenderManagerService);
+ const drawingParam = props.drawings[0];
+ const scene = drawingParam ? renderManagerService.getRenderUnitById(drawingParam.unitId)?.scene : undefined;
+ const topScene = scene?.getEngine()?.activeScene as Nullable<Scene>;
+
+ if (!drawingParam?.transform || !scene || !topScene) {
+ return null;
+ }
+
+ return <MobileDrawingTransformContent {...props} />;
+}
+
+function MobileDrawingTransformContent(props: IMobileDrawingTransformProps) {
+ const localeService = useDependency(LocaleService);
+ const drawingManagerService = useDependency(IDrawingManagerService);
+ const renderManagerService = useDependency(IRenderManagerService);
+ const { drawings, transformShow } = props;
+ const drawingParam = drawings[0]!;
+ const transform = drawingParam.transform!;
+ const { unitId, subUnitId, drawingId, drawingType } = drawingParam;
+ const scene = renderManagerService.getRenderUnitById(unitId)!.scene!;
+ const topScene = scene.getEngine()!.activeScene as Scene;
+ const transformer = scene.getTransformerByCreate();
+ const {
+ width: originWidth = 0,
+ height: originHeight = 0,
+ left: originX = 0,
+ top: originY = 0,
+ angle: originRotation = 0,
+ } = transform;
+ const [width, setWidth] = useState<number>(originWidth);
+ const [height, setHeight] = useState(originHeight);
+ const [xPosition, setXPosition] = useState(originX);
+ const [yPosition, setYPosition] = useState(originY);
+ const [rotation, setRotation] = useState(originRotation);
+ const [lockRatio, setLockRatio] = useState(transformer.keepRatio);
+ const rotateEnabled = resolveDrawingUIRotateEnabled(drawingParam, {
+ getChildren: (drawing) => drawingManagerService.getDrawingsByGroup(drawing),
+ });
+ const rotationDisabled = isDrawingTransformRotationDisabled(rotateEnabled);
+
+ const checkMoveBoundary = (left: number, top: number, drawingWidth: number, drawingHeight: number) => {
+ const { width: topSceneWidth, height: topSceneHeight } = topScene;
+ const { ancestorLeft, ancestorTop } = scene;
+ let limitLeft = left;
+ let limitTop = top;
+ let limitWidth = drawingWidth;
+ let limitHeight = drawingHeight;
+
+ if (left + ancestorLeft < 0) {
+ limitLeft = -ancestorLeft;
+ }
+ if (top + ancestorTop < 0) {
+ limitTop = -ancestorTop;
+ }
+
+ limitWidth = Math.max(topSceneWidth - limitLeft - ancestorLeft, MIN_DRAWING_WIDTH_LIMIT);
+ limitHeight = Math.max(topSceneHeight - limitTop - ancestorTop, MIN_DRAWING_HEIGHT_LIMIT);
+
+ if (left + limitWidth + ancestorLeft > topSceneWidth) {
+ limitLeft = topSceneWidth - drawingWidth - ancestorLeft;
+ }
+ if (top + limitHeight + ancestorTop > topSceneHeight) {
+ limitTop = topSceneHeight - drawingHeight - ancestorTop;
+ }
+
+ return { limitLeft, limitTop, limitWidth, limitHeight };
+ };
+
+ const syncTransform = (drawing: IDrawingParam) => {
+ const nextTransform = drawing.transform;
+ if (nextTransform == null) {
+ return;
+ }
+
+ const { width, height, left, top, angle } = nextTransform;
+ if (width != null) setWidth(width);
+ if (height != null) setHeight(height);
+ if (left != null) setXPosition(left);
+ if (top != null) setYPosition(top);
+ if (angle != null) setRotation(angle);
+ };
+
+ const changeObserver = (state: IChangeObserverConfig) => {
+ const params = getUpdateParams(state.objects, drawingManagerService);
+ if (params.length === 1 && params[0] != null) {
+ syncTransform(params[0]);
+ }
+ };
+
+ useEffect(() => {
+ const subscriptions = [
+ transformer.changeStart$.subscribe(changeObserver),
+ transformer.changing$.subscribe(changeObserver),
+ transformer.changeEnd$.subscribe(changeObserver),
+ drawingManagerService.focus$.subscribe((drawings) => {
+ if (drawings.length !== 1) {
+ return;
+ }
+ const drawing = drawingManagerService.getDrawingByParam(drawings[0]);
+ if (drawing != null) {
+ syncTransform(drawing);
+ }
+ }),
+ ];
+
+ return () => subscriptions.forEach((subscription) => subscription.unsubscribe());
+ }, []);
+
+ const notifyTransformChange = (updateParam: IDrawingParam) => {
+ drawingManagerService.featurePluginUpdateNotification([updateParam]);
+ transformer.refreshControls().changeNotification();
+ };
+
+ const handleWidthChange = debounce((value: number | null) => {
+ if (value == null) {
+ return;
+ }
+
+ const { limitWidth, limitHeight } = checkMoveBoundary(xPosition, yPosition, value, height);
+ const nextWidth = Math.min(value, limitWidth);
+ const updateParam: IDrawingParam = { unitId, subUnitId, drawingId, drawingType, transform: { width: nextWidth } };
+
+ if (lockRatio) {
+ const nextHeight = Math.max((nextWidth / width) * height, MIN_DRAWING_HEIGHT_LIMIT);
+ if (nextHeight > limitHeight) {
+ return;
+ }
+ setHeight(nextHeight);
+ updateParam.transform!.height = nextHeight;
+ }
+
+ setWidth(nextWidth);
+ notifyTransformChange(updateParam);
+ }, INPUT_DEBOUNCE_TIME);
+
+ const handleHeightChange = debounce((value: number | null) => {
+ if (value == null) {
+ return;
+ }
+
+ const { limitHeight, limitWidth } = checkMoveBoundary(xPosition, yPosition, width, value);
+ const nextHeight = Math.min(value, limitHeight);
+ const updateParam: IDrawingParam = { unitId, subUnitId, drawingId, drawingType, transform: { height: nextHeight } };
+
+ if (lockRatio) {
+ const nextWidth = Math.max((nextHeight / height) * width, MIN_DRAWING_WIDTH_LIMIT);
+ if (nextWidth > limitWidth) {
+ return;
+ }
+ setWidth(nextWidth);
+ updateParam.transform!.width = nextWidth;
+ }
+
+ setHeight(nextHeight);
+ notifyTransformChange(updateParam);
+ }, INPUT_DEBOUNCE_TIME);
+
+ const handleXChange = debounce((value: number | null) => {
+ if (value == null) {
+ return;
+ }
+ const { limitLeft } = checkMoveBoundary(value, yPosition, width, height);
+ setXPosition(limitLeft);
+ notifyTransformChange({ unitId, subUnitId, drawingId, drawingType, transform: { left: limitLeft } });
+ }, INPUT_DEBOUNCE_TIME);
+
+ const handleYChange = debounce((value: number | null) => {
+ if (value == null) {
+ return;
+ }
+ const { limitTop } = checkMoveBoundary(xPosition, value, width, height);
+ setYPosition(limitTop);
+ notifyTransformChange({ unitId, subUnitId, drawingId, drawingType, transform: { top: limitTop } });
+ }, INPUT_DEBOUNCE_TIME);
+
+ const handleRotationChange = createDrawingTransformRotationChangeHandler({
+ rotateEnabled,
+ drawingParam: { unitId, subUnitId, drawingId, drawingType },
+ setRotation,
+ emitUpdate: (updateParams) => drawingManagerService.featurePluginUpdateNotification(updateParams),
+ notifyChange: () => transformer.refreshControls().changeNotification(),
+ });
+
+ const handleLockRatioChange = (value: string | number | boolean) => {
+ if (typeof value !== 'boolean') {
+ return;
+ }
+ setLockRatio(value);
+ transformer.keepRatio = value;
+ };
+
+ return (
+ <div
+ className={clsx('univer-grid univer-gap-2 univer-py-2 univer-text-gray-400', {
+ 'univer-hidden': !transformShow,
+ })}
+ >
+ <header
+ className="
+ univer-text-gray-600
+ dark:!univer-text-gray-200
+ "
+ >
+ <div>{localeService.t<LocaleKey>('drawing-ui.image-panel.transform.title')}</div>
+ </header>
+
+ <div
+ className="
+ univer-grid univer-grid-cols-3 univer-gap-2
+ [&>div]:univer-grid [&>div]:univer-gap-2
+ "
+ >
+ <div>
+ <span>{localeService.t<LocaleKey>('drawing-ui.image-panel.transform.width')}</span>
+ <MobileDrawingInputNumber precision={1} value={width} min={MIN_DRAWING_WIDTH_LIMIT} onChange={handleWidthChange} />
+ </div>
+ <div>
+ <span>{localeService.t<LocaleKey>('drawing-ui.image-panel.transform.height')}</span>
+ <MobileDrawingInputNumber precision={1} value={height} min={MIN_DRAWING_HEIGHT_LIMIT} onChange={handleHeightChange} />
+ </div>
+ <div>
+ <span>{localeService.t<LocaleKey>('drawing-ui.image-panel.transform.lock')}</span>
+ <div className="univer-text-center">
+ <MobileDrawingCheckbox checked={lockRatio} onChange={handleLockRatioChange} />
+ </div>
+ </div>
+ </div>
+
+ <div
+ className="
+ univer-grid univer-grid-cols-3 univer-gap-2
+ [&>div]:univer-grid [&>div]:univer-gap-2
+ "
+ >
+ <div>
+ <span>{localeService.t<LocaleKey>('drawing-ui.image-panel.transform.x')}</span>
+ <MobileDrawingInputNumber precision={1} value={xPosition} onChange={handleXChange} />
+ </div>
+ <div>
+ <span>{localeService.t<LocaleKey>('drawing-ui.image-panel.transform.y')}</span>
+ <MobileDrawingInputNumber precision={1} value={yPosition} onChange={handleYChange} />
+ </div>
+ <div>
+ <span>{localeService.t<LocaleKey>('drawing-ui.image-panel.transform.rotate')}</span>
+ <MobileDrawingInputNumber
+ precision={1}
+ value={rotation}
+ min={RANGE_DRAWING_ROTATION_LIMIT[0]}
+ max={RANGE_DRAWING_ROTATION_LIMIT[1]}
+ disabled={rotationDisabled}
+ onChange={handleRotationChange}
+ />
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export function MobileDrawingAlign(props: IMobileDrawingAlignProps) {
+ const commandService = useDependency(ICommandService);
+ const localeService = useDependency(LocaleService);
+ const { drawings, alignShow } = props;
+ const [alignValue, setAlignValue] = useState<AlignType>(AlignType.default);
+ const alignOptions = [
+ {
+ label: localeService.t<LocaleKey>('drawing-ui.image-panel.align.default'),
+ value: AlignType.default,
+ },
+ {
+ options: [
+ { label: localeService.t<LocaleKey>('drawing-ui.image-panel.align.left'), value: AlignType.left },
+ { label: localeService.t<LocaleKey>('drawing-ui.image-panel.align.center'), value: AlignType.center },
+ { label: localeService.t<LocaleKey>('drawing-ui.image-panel.align.right'), value: AlignType.right },
+ ],
+ },
+ {
+ options: [
+ { label: localeService.t<LocaleKey>('drawing-ui.image-panel.align.top'), value: AlignType.top },
+ { label: localeService.t<LocaleKey>('drawing-ui.image-panel.align.middle'), value: AlignType.middle },
+ { label: localeService.t<LocaleKey>('drawing-ui.image-panel.align.bottom'), value: AlignType.bottom },
+ ],
+ },
+ {
+ options: [
+ { label: localeService.t<LocaleKey>('drawing-ui.image-panel.align.horizon'), value: AlignType.horizon },
+ { label: localeService.t<LocaleKey>('drawing-ui.image-panel.align.vertical'), value: AlignType.vertical },
+ ],
+ },
+ ];
+
+ const handleAlignChange = (value: string | number | boolean) => {
+ const alignType = Object.values(AlignType).find((option) => option === value);
+ if (alignType == null) {
+ return;
+ }
+ setAlignValue(alignType);
+ commandService.executeCommand(SetDrawingAlignOperation.id, { alignType, drawings });
+ };
+
+ return (
+ <div className={clsx('univer-relative univer-w-full', { 'univer-hidden': !alignShow })}>
+ <header
+ className="
+ univer-text-gray-600
+ dark:!univer-text-gray-200
+ "
+ >
+ <div>{localeService.t<LocaleKey>('drawing-ui.image-panel.align.title')}</div>
+ </header>
+ <div className="univer-relative univer-mt-2.5 univer-flex univer-h-full">
+ <div
+ className="
+ univer-w-full univer-text-gray-900
+ dark:!univer-text-gray-0
+ "
+ >
+ <MobileSelect value={alignValue} options={alignOptions} onChange={handleAlignChange} />
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export function MobileDrawingGroup(props: IMobileDrawingGroupProps) {
+ const localeService = useDependency(LocaleService);
+ const renderManagerService = useDependency(IRenderManagerService);
+ const drawingManagerService = useDependency(IDrawingManagerService);
+ const commandService = useDependency(ICommandService);
+ const iconManager = useDependency(IconManager);
+ const { hasGroup, drawings } = props;
+ const GroupIcon = iconManager.get('GroupIcon');
+ const UngroupIcon = iconManager.get('UngroupIcon');
+ const drawingParam = drawings[0];
+ const transformer = drawingParam
+ ? renderManagerService.getRenderUnitById(drawingParam.unitId)?.scene?.getTransformerByCreate()
+ : undefined;
+ const groupState = useObservable(
+ transformer
+ ? () => merge(
+ transformer.clearControl$.pipe(
+ filter((changeSelf) => changeSelf === true),
+ map(() => ({ groupShow: false, groupBtnShow: false, ungroupBtnShow: false }))
+ ),
+ transformer.changeStart$.pipe(map((state) => {
+ const params = getUpdateParams(state.objects, drawingManagerService);
+ const groupBtnShow = params.length > 1;
+ const ungroupBtnShow = params.some((item) => item?.drawingType === DrawingTypeEnum.DRAWING_GROUP);
+ return {
+ groupShow: groupBtnShow || ungroupBtnShow,
+ groupBtnShow,
+ ungroupBtnShow,
+ };
+ }))
+ )
+ : null,
+ { groupShow: false, groupBtnShow: true, ungroupBtnShow: true },
+ false,
+ [drawingManagerService, transformer]
+ );
+ const { groupShow, groupBtnShow, ungroupBtnShow } = groupState;
+
+ return (
+ <div
+ className={clsx('univer-grid univer-gap-2 univer-py-2 univer-text-gray-400', {
+ 'univer-hidden': (hasGroup && !groupShow) || !hasGroup,
+ })}
+ >
+ <header
+ className="
+ univer-text-gray-600
+ dark:!univer-text-gray-200
+ "
+ >
+ <div>{localeService.t<LocaleKey>('drawing-ui.image-panel.group.title')}</div>
+ </header>
+ <div className="univer-flex univer-items-center univer-justify-center univer-gap-2">
+ <MobileDrawingButton
+ className={clsx({ 'univer-hidden': !groupBtnShow })}
+ onClick={() => commandService.syncExecuteCommand(SetDrawingGroupOperation.id, { drawings })}
+ >
+ <GroupIcon />
+ {localeService.t<LocaleKey>('drawing-ui.image-panel.group.group')}
+ </MobileDrawingButton>
+ <MobileDrawingButton
+ className={clsx({ 'univer-hidden': !ungroupBtnShow })}
+ onClick={() => commandService.syncExecuteCommand(CancelDrawingGroupOperation.id, { drawings })}
+ >
+ <UngroupIcon />
+ {localeService.t<LocaleKey>('drawing-ui.image-panel.group.unGroup')}
+ </MobileDrawingButton>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/drawing-ui/src/views/panel/MobileImageCropper.tsx b/packages/drawing-ui/src/views/panel/MobileImageCropper.tsx
new file mode 100644
index 0000000000..02428005aa
--- /dev/null
+++ b/packages/drawing-ui/src/views/panel/MobileImageCropper.tsx
@@ -0,0 +1,83 @@
+/**
+ * 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 { CropType } from '../../commands/operations/image-crop.operation';
+import type { LocaleKey } from '../../locale/types';
+import type { IImageCropperProps } from './ImageCropper';
+import { LocaleService } from '@univerjs/core';
+import { MobileActionRow } from '@univerjs/design';
+import { CropIcon } from '@univerjs/icons';
+import { useDependency } from '@univerjs/ui';
+import { useImageCropper } from './use-image-cropper';
+
+interface IMobileImageCropperProps {
+ cropValue: CropType;
+ cropOptions: { label: string; value: CropType }[];
+ onCropChange: (value: CropType) => void;
+ onStartCrop: () => void;
+ children?: ReactNode;
+}
+
+function MobileImageCropperControls(props: IMobileImageCropperProps) {
+ const localeService = useDependency(LocaleService);
+
+ return (
+ <section className="univer-grid univer-gap-3 univer-py-3">
+ <h3 className="univer-m-0 univer-text-sm univer-font-medium">
+ {localeService.t<LocaleKey>('drawing-ui.image-panel.crop.title')}
+ </h3>
+ <div className="univer-grid univer-grid-cols-3 univer-gap-2">
+ {props.cropOptions.map((option) => (
+ <MobileActionRow
+ key={option.value}
+ title={option.label}
+ variant="subtle"
+ aria-pressed={props.cropValue === option.value}
+ className="
+ univer-px-2 univer-text-center
+ aria-pressed:!univer-bg-primary-50 aria-pressed:!univer-text-primary-600
+ "
+ onClick={() => props.onCropChange(option.value)}
+ />
+ ))}
+ </div>
+ <MobileActionRow
+ icon={<CropIcon />}
+ title={localeService.t<LocaleKey>('drawing-ui.image-panel.crop.start')}
+ className="!univer-bg-primary-600 !univer-text-white"
+ onClick={props.onStartCrop}
+ />
+ {props.children}
+ </section>
+ );
+}
+export function MobileImageCropper(props: IImageCropperProps) {
+ const { drawingParam, cropperShow, cropValue, cropOptions, handleCropChange, onCropperBtnClick, ShapeClipPicker } = useImageCropper(props);
+ if (!drawingParam || !cropperShow) {
+ return null;
+ }
+ return (
+ <MobileImageCropperControls
+ cropValue={cropValue}
+ cropOptions={cropOptions}
+ onCropChange={handleCropChange}
+ onStartCrop={() => onCropperBtnClick(cropValue)}
+ >
+ {ShapeClipPicker && <ShapeClipPicker />}
+ </MobileImageCropperControls>
+ );
+}
diff --git a/packages/drawing-ui/src/views/panel/__tests__/ImageCropper.spec.tsx b/packages/drawing-ui/src/views/panel/__tests__/ImageCropper.spec.tsx
new file mode 100644
index 0000000000..c1e535c8b7
--- /dev/null
+++ b/packages/drawing-ui/src/views/panel/__tests__/ImageCropper.spec.tsx
@@ -0,0 +1,93 @@
+/**
+ * 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 { ICommandInfo } from '@univerjs/core';
+import type { Root } from 'react-dom/client';
+import { DrawingTypeEnum, ICommandService, LocaleService, LocaleType, Univer } from '@univerjs/core';
+import { ConfigProvider } from '@univerjs/design';
+import { ComponentManager, RediContext } from '@univerjs/ui';
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { afterEach, describe, expect, it } from 'vitest';
+import { AutoImageCropOperation, CloseImageCropOperation, CropType } from '../../../commands/operations/image-crop.operation';
+import locale from '../../../locale/en-US';
+import { DrawingImageClipService } from '../../../services/drawing-image-clip.service';
+import { MobileImageCropper } from '../MobileImageCropper';
+
+describe('ImageCropper mobile', () => {
+ let univer: Univer | undefined;
+ let root: Root | undefined;
+ let container: HTMLDivElement | undefined;
+
+ afterEach(() => {
+ act(() => root?.unmount());
+ container?.remove();
+ univer?.dispose();
+ });
+
+ it('selects ratios in place and starts cropping once before releasing the drawer', async () => {
+ univer = new Univer();
+ const injector = univer.__getInjector();
+ injector.add([DrawingImageClipService]);
+ injector.add([ComponentManager]);
+ const localeService = injector.get(LocaleService);
+ localeService.load({ [LocaleType.EN_US]: locale });
+ localeService.setLocale(LocaleType.EN_US);
+ const commandService = injector.get(ICommandService);
+ commandService.registerCommand(AutoImageCropOperation);
+ commandService.registerCommand(CloseImageCropOperation);
+ const commands: ICommandInfo[] = [];
+ commandService.onCommandExecuted((command) => commands.push(command));
+ let cropStarts = 0;
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ act(() => root?.render(
+ <RediContext.Provider value={{ injector }}>
+ <ConfigProvider mountContainer={document.body}>
+ <MobileImageCropper
+ drawings={[{ unitId: 'doc', subUnitId: 'doc', drawingId: 'image', drawingType: DrawingTypeEnum.DRAWING_IMAGE }]}
+ cropperShow
+ onCropStart={() => { cropStarts++; }}
+ />
+ </ConfigProvider>
+ </RediContext.Provider>
+ ));
+ const buttons = Array.from(container.querySelectorAll('button'));
+ const ratio = buttons.find((button) => button.textContent === '16:9');
+ const start = buttons.find((button) => button.textContent === 'Start Crop');
+ if (!ratio || !start) {
+ throw new Error('Mobile crop actions are missing');
+ }
+ await act(async () => ratio.click());
+ expect(ratio.getAttribute('aria-pressed')).toBe('true');
+ expect(commands).toEqual([]);
+ expect(container.querySelector('[role="combobox"]')).toBeNull();
+
+ await act(async () => start.click());
+ expect(commands).toMatchObject([{ id: AutoImageCropOperation.id, params: { cropType: CropType.R16_9 } }]);
+ expect(cropStarts).toBe(1);
+
+ await act(async () => commandService.executeCommand(CloseImageCropOperation.id));
+ const square = buttons.find((button) => button.textContent === '1:1');
+ if (!square) {
+ throw new Error('Square crop option is missing');
+ }
+ await act(async () => square.click());
+ expect(commands.filter((command) => command.id === AutoImageCropOperation.id)).toHaveLength(1);
+ expect(square.getAttribute('aria-pressed')).toBe('true');
+ });
+});
diff --git a/packages/drawing-ui/src/views/panel/component-name.ts b/packages/drawing-ui/src/views/panel/component-name.ts
new file mode 100644
index 0000000000..5c05d90fa2
--- /dev/null
+++ b/packages/drawing-ui/src/views/panel/component-name.ts
@@ -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.
+ */
+
+export const DRAWING_ARRANGE_COMPONENT = 'drawing-ui.arrange';
+export const IMAGE_CROPPER_COMPONENT = 'drawing-ui.cropper';
+export const DRAWING_TRANSFORM_COMPONENT = 'drawing-ui.transform';
+export const DRAWING_ALIGN_COMPONENT = 'drawing-ui.align';
+export const DRAWING_GROUP_COMPONENT = 'drawing-ui.group';
diff --git a/packages/drawing-ui/src/views/panel/use-image-cropper.ts b/packages/drawing-ui/src/views/panel/use-image-cropper.ts
new file mode 100644
index 0000000000..3ddf59ca1c
--- /dev/null
+++ b/packages/drawing-ui/src/views/panel/use-image-cropper.ts
@@ -0,0 +1,127 @@
+/**
+ * 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 { ICommandInfo } from '@univerjs/core';
+import type { ICloseImageCropOperationParams } from '../../commands/operations/image-crop.operation';
+import type { LocaleKey } from '../../locale/types';
+import type { IImageCropperProps } from './ImageCropper';
+import { ICommandService, LocaleService } from '@univerjs/core';
+import { ComponentManager, useDependency, useObservable } from '@univerjs/ui';
+import { useEffect, useRef, useState } from 'react';
+import {
+ AutoImageCropOperation,
+ CloseImageCropOperation,
+ CropType,
+} from '../../commands/operations/image-crop.operation';
+
+import { DrawingImageClipService, IMAGE_CLIP_SHAPE_PICKER_COMPONENT } from '../../services/drawing-image-clip.service';
+
+export function useImageCropper(props: IImageCropperProps) {
+ const commandService = useDependency(ICommandService);
+ const localeService = useDependency(LocaleService);
+ const clipService = useDependency(DrawingImageClipService);
+ const componentManager = useDependency(ComponentManager);
+ const canUseShapeClip = useObservable(clipService.canUseShapeClip$, false);
+
+ const { drawings, cropperShow } = props;
+
+ const drawingParam = drawings[0];
+ const [cropValue, setCropValue] = useState(CropType.FREE);
+ const cropStateRef = useRef(false);
+
+ const cropOptions = [
+ {
+ label: localeService.t<LocaleKey>('drawing-ui.image-panel.crop.mode'),
+ value: CropType.FREE,
+ },
+ {
+ label: '1:1',
+ value: CropType.R1_1,
+ },
+ {
+ label: '16:9',
+ value: CropType.R16_9,
+ },
+ {
+ label: '9:16',
+ value: CropType.R9_16,
+ },
+ {
+ label: '5:4',
+ value: CropType.R5_4,
+ },
+ {
+ label: '4:5',
+ value: CropType.R4_5,
+ },
+ {
+ label: '4:3',
+ value: CropType.R4_3,
+ },
+ {
+ label: '3:4',
+ value: CropType.R3_4,
+ },
+ {
+ label: '3:2',
+ value: CropType.R3_2,
+ },
+ {
+ label: '2:3',
+ value: CropType.R2_3,
+ },
+ ];
+
+ useEffect(() => {
+ const onChangeStartObserver = commandService.onCommandExecuted((command: ICommandInfo<ICloseImageCropOperationParams>) => {
+ if (command.id === CloseImageCropOperation.id) {
+ const params = command.params;
+ if (!params?.isAuto) {
+ cropStateRef.current = false;
+ }
+ }
+ });
+
+ return () => {
+ onChangeStartObserver?.dispose();
+ };
+ }, [commandService]);
+
+ function handleCropChange(value: string | number | boolean) {
+ const cropType = cropOptions.find((option) => option.value === value)?.value;
+ if (cropType == null) {
+ return;
+ }
+ setCropValue(cropType);
+ if (cropStateRef.current) {
+ commandService.executeCommand(AutoImageCropOperation.id, {
+ cropType,
+ });
+ }
+ }
+
+ const onCropperBtnClick = async (val: CropType) => {
+ await commandService.executeCommand(AutoImageCropOperation.id, {
+ cropType: val,
+ });
+ cropStateRef.current = true;
+ props.onCropStart?.();
+ };
+
+ const ShapeClipPicker = canUseShapeClip ? componentManager.get(IMAGE_CLIP_SHAPE_PICKER_COMPONENT) : undefined;
+
+ return { drawingParam, cropperShow, localeService, cropValue, cropOptions, handleCropChange, onCropperBtnClick, ShapeClipPicker };
+}
diff --git a/packages/engine-render/src/__tests__/engine-scene-viewport.spec.ts b/packages/engine-render/src/__tests__/engine-scene-viewport.spec.ts
index 5c2c2710a9..0122bfa1a3 100644
--- a/packages/engine-render/src/__tests__/engine-scene-viewport.spec.ts
+++ b/packages/engine-render/src/__tests__/engine-scene-viewport.spec.ts
@@ -657,6 +657,37 @@ describe('engine scene viewport extra', () => {
engine.dispose();
});
+ it('uses canvas-relative client coordinates to pick touch targets', () => {
+ const { engine, scene } = createFixture();
+ scene.attachControl();
+ engine.getCanvasElement().getBoundingClientRect = () => ({
+ bottom: 560,
+ height: 360,
+ left: 100,
+ right: 740,
+ top: 200,
+ width: 640,
+ x: 100,
+ y: 200,
+ toJSON: () => ({}),
+ } as DOMRect);
+ const pick = vi.spyOn(scene, 'pick');
+
+ engine.onInputChanged$.emitEvent(createInputEvent('pointerdown', {
+ clientX: 136,
+ clientY: 240,
+ deviceType: DeviceType.Touch,
+ offsetX: 18,
+ offsetY: -160,
+ pointerType: 'touch',
+ }));
+
+ expect(pick).toHaveBeenCalledWith(expect.objectContaining({ x: 18, y: 20 }), DeviceType.Touch);
+
+ scene.dispose();
+ engine.dispose();
+ });
+
it('throws when subscribing clientRect$ without mounting container', () => {
const engine = new Engine('unit-b', { elementWidth: 1, elementHeight: 1, dpr: 1 });
const onError = vi.fn();
diff --git a/packages/engine-render/src/__tests__/scene.transformer.spec.ts b/packages/engine-render/src/__tests__/scene.transformer.spec.ts
index ff7abacf2f..d06a3c92c9 100644
--- a/packages/engine-render/src/__tests__/scene.transformer.spec.ts
+++ b/packages/engine-render/src/__tests__/scene.transformer.spec.ts
@@ -15,12 +15,37 @@
*/
import { afterEach, describe, expect, it, vi } from 'vitest';
+import { DeviceType, PointerInput } from '../basics/i-events';
+import { Vector2 } from '../basics/vector2';
import { Engine } from '../engine';
import { Scene } from '../scene';
import { Transformer } from '../scene.transformer';
+import { Control } from '../shape/control';
import { Rect } from '../shape/rect';
+import { Viewport } from '../viewport';
import { setupRenderTestEnv } from './render-test-utils';
+function createPointerEvent(type: string, offsetX: number, offsetY: number) {
+ const event = Object.assign(new PointerEvent(type, {
+ bubbles: true,
+ button: 0,
+ clientX: offsetX,
+ clientY: offsetY,
+ pointerId: 1,
+ pointerType: 'touch',
+ }), {
+ currentState: null,
+ deviceType: DeviceType.Touch,
+ inputIndex: PointerInput.LeftClick,
+ previousState: null,
+ });
+ Object.defineProperties(event, {
+ offsetX: { value: offsetX },
+ offsetY: { value: offsetY },
+ });
+ return event;
+}
+
describe('Transformer', () => {
const env = setupRenderTestEnv();
@@ -28,6 +53,170 @@ describe('Transformer', () => {
env.restore();
});
+ it.each([0.35, 1, 2])('keeps resize and rotation touch targets in screen pixels at scale %s', (scale) => {
+ const engine = new Engine('touch-controls-engine', { elementWidth: 1600, elementHeight: 1600, dpr: 1 });
+ const scene = new Scene('touch-controls-scene', engine);
+ const viewport = new Viewport('touch-controls-viewport', scene, { left: 0, top: 0, width: 1600, height: 1600 });
+ scene.scale(scale, scale);
+ const rect = new Rect('touch-object', { left: 200, top: 200, width: 400, height: 300 });
+ scene.addObject(rect);
+ const transformer = new Transformer(scene, { rotateEnabled: true });
+ try {
+ transformer.setSelectedControl(rect);
+ for (const key of ['ResizeRB', 'Rotate__']) {
+ const anchor = scene.getAllObjectsByOrderForPick().find((object) => object.oKey.includes(key));
+ if (!(anchor instanceof Control)) {
+ throw new TypeError(`Missing ${key} control`);
+ }
+ const artwork = anchor.getState();
+ const center = anchor.ancestorTransform.applyPoint(new Vector2(anchor.width / 2, anchor.height / 2));
+ const point = new Vector2(center.x * scale + 20, center.y * scale);
+ expect(scene.pick(point, DeviceType.Touch)).toBe(anchor);
+ expect(scene.pick(point, DeviceType.Mouse)).not.toBe(anchor);
+ expect(anchor.getState()).toEqual(artwork);
+ }
+ } finally {
+ transformer.dispose();
+ viewport.dispose();
+ scene.dispose();
+ engine.dispose();
+ }
+ });
+
+ it('chooses the nearest touch control and leaves mouse, hidden controls and overlays precise', () => {
+ const engine = new Engine('adjust-hit-engine', { elementWidth: 800, elementHeight: 800, dpr: 1 });
+ const scene = new Scene('adjust-hit-scene', engine);
+ const viewport = new Viewport('adjust-hit-viewport', scene, { left: 0, top: 0, width: 800, height: 800 });
+ const object = new Rect('object', { left: 0, top: 0, width: 400, height: 300 });
+ const a = new Control('adjust-a', { left: 100, top: 100, width: 8, height: 8, angle: 45 });
+ const b = new Control('adjust-b', { left: 120, top: 100, width: 8, height: 8 });
+ scene.addObject(object, 1);
+ scene.addObjects([a, b], 2);
+ scene.attachControl();
+ const down = vi.fn();
+ const subscription = a.onPointerDown$.subscribeEvent(down);
+ try {
+ const point = new Vector2(112, 110);
+ expect(scene.pick(point, DeviceType.Touch)).toBe(a);
+ expect(scene.pick(point, DeviceType.Mouse)).toBe(object);
+ engine.getCanvasElement().dispatchEvent(createPointerEvent('pointerdown', point.x, point.y));
+ expect(down).toHaveBeenCalledTimes(1);
+ engine.getCanvasElement().dispatchEvent(createPointerEvent('pointerup', point.x, point.y));
+ a.hide();
+ expect(scene.pick(point, DeviceType.Touch)).toBe(b);
+ b.evented = false;
+ expect(scene.pick(point, DeviceType.Touch)).toBe(object);
+ b.evented = true;
+ const overlay = new Rect('overlay', { left: 100, top: 100, width: 40, height: 40 });
+ scene.addObject(overlay, 3);
+ expect(scene.pick(point, DeviceType.Touch)).toBe(overlay);
+ } finally {
+ subscription.unsubscribe();
+ viewport.dispose();
+ scene.dispose();
+ engine.dispose();
+ }
+ });
+
+ it.each([0.5, 1, 2])('keeps all eight crop hit targets usable at scale %s without enlarging their artwork', (scale) => {
+ const engine = new Engine('crop-hit-engine', { elementWidth: 800, elementHeight: 800, dpr: 1 });
+ const scene = new Scene('crop-hit-scene', engine);
+ const viewport = new Viewport('crop-hit-viewport', scene, { left: 0, top: 0, width: 800, height: 800 });
+ scene.scale(scale, scale);
+ const crop = new Rect('crop-frame', { left: 100, top: 100, width: 400, height: 300, angle: 30 });
+ crop.transformerConfig = { isCropper: true, anchorSize: 24, cropAnchorHitSize: 44 };
+ const image = new Rect('underlying-image', crop.getState());
+ scene.addObject(image, 1);
+ scene.addObject(crop, 2);
+ const transformer = new Transformer(scene);
+ try {
+ transformer.createControlForCopper(crop);
+ transformer.setSelectedControl(image);
+ const anchors = scene.getAllObjectsByOrderForPick().filter((object) =>
+ object.getLayerIndex() === crop.getLayerIndex() && object.oKey.includes('TransformerResize'));
+ expect(anchors).toHaveLength(8);
+ for (const anchor of anchors) {
+ expect(Math.max(anchor.width, anchor.height)).toBe(24);
+ const halfWidth = Math.max(anchor.width, 44 / scale) / 2;
+ const halfHeight = Math.max(anchor.height, 44 / scale) / 2;
+ const hit = (x: number, y: number) => anchor.isHit(anchor.ancestorTransform.applyPoint(new Vector2(
+ anchor.width / 2 + x,
+ anchor.height / 2 + y
+ )));
+ expect(hit(halfWidth - 1 / scale, halfHeight - 1 / scale)).toBe(true);
+ expect(hit(-halfWidth + 1 / scale, -halfHeight + 1 / scale)).toBe(true);
+ expect(hit(halfWidth + 1 / scale, 0)).toBe(false);
+ const point = anchor.ancestorTransform.applyPoint(new Vector2(anchor.width / 2, anchor.height / 2));
+ expect(scene.pick(new Vector2(point.x * scale, point.y * scale))).toBe(anchor);
+ expect(scene.pick(new Vector2(point.x * scale, point.y * scale), DeviceType.Touch)).toBe(anchor);
+ }
+ } finally {
+ viewport.dispose();
+ transformer.dispose();
+ scene.dispose();
+ engine.dispose();
+ }
+ });
+
+ it('keeps desktop crop handles using their precise painted hit areas', () => {
+ const engine = new Engine('desktop-crop-engine', { elementWidth: 800, elementHeight: 800, dpr: 1 });
+ const scene = new Scene('desktop-crop-scene', engine);
+ const crop = new Rect('desktop-crop-frame', { width: 400, height: 300 });
+ crop.transformerConfig = { isCropper: true, anchorSize: 24 };
+ scene.addObject(crop);
+ const transformer = new Transformer(scene);
+ try {
+ transformer.createControlForCopper(crop);
+ const anchors = scene.getAllObjectsByOrderForPick().filter((object) => object.oKey.includes('TransformerResize'));
+ expect(anchors).toHaveLength(8);
+ for (const anchor of anchors) {
+ expect(anchor.isHit(anchor.ancestorTransform.applyPoint(new Vector2(anchor.width + 4, anchor.height / 2)))).toBe(false);
+ }
+ } finally {
+ transformer.dispose();
+ scene.dispose();
+ engine.dispose();
+ }
+ });
+
+ it.each(['takeover', 'pointercancel'])('finishes a move once on %s and releases the scene for viewport gestures', (reason) => {
+ const engine = new Engine('gesture-engine', { elementWidth: 800, elementHeight: 800, dpr: 1 });
+ const scene = new Scene('gesture-scene', engine, { width: 800, height: 800 });
+ const viewport = new Viewport('gesture-viewport', scene, { left: 0, top: 0, width: 800, height: 800 });
+ const rect = new Rect('gesture-object', { left: 100, top: 100, width: 100, height: 100 });
+ scene.addObject(rect);
+ const transformer = new Transformer(scene);
+ const ended = vi.fn();
+ const subscription = transformer.changeEnd$.subscribe(ended);
+ try {
+ transformer.attachTo(rect);
+ transformer.setSelectedControl(rect);
+ rect.onPointerDown$.emitEvent(createPointerEvent('pointerdown', 120, 120));
+ scene.onPointerMove$.emitEvent(createPointerEvent('pointermove', 160, 150));
+ if (reason === 'takeover') {
+ transformer.finishTransform();
+ } else {
+ scene.onPointerCancel$.emitEvent(createPointerEvent('pointercancel', 0, 0));
+ }
+ expect(ended).toHaveBeenCalledTimes(1);
+ expect(ended.mock.calls[0][0]).toMatchObject({ offsetX: 160, offsetY: 150 });
+ expect(rect.left).toBe(140);
+ expect(rect.top).toBe(130);
+ scene.onPointerMove$.emitEvent(createPointerEvent('pointermove', 300, 300));
+ scene.onPointerUp$.emitEvent(createPointerEvent('pointerup', 300, 300));
+ transformer.finishTransform();
+ expect(ended).toHaveBeenCalledTimes(1);
+ expect(rect.left).toBe(140);
+ expect(scene.pick(new Vector2(170, 160))).toBe(rect);
+ } finally {
+ subscription.unsubscribe();
+ transformer.dispose();
+ viewport.dispose();
+ scene.dispose();
+ engine.dispose();
+ }
+ });
+
it('releases hover subscriptions with its object subscription', () => {
const engine = new Engine('transformer-engine', { elementWidth: 100, elementHeight: 100, dpr: 1 });
const scene = new Scene('transformer-scene', engine);
@@ -53,6 +242,42 @@ describe('Transformer', () => {
engine.dispose();
});
+ it.each(['ResizeRB', 'Rotate__'])('releases %s controls when a pinch takes ownership', (controlKey) => {
+ const engine = new Engine('control-gesture-engine', { elementWidth: 800, elementHeight: 800, dpr: 1 });
+ const scene = new Scene('control-gesture-scene', engine, { width: 800, height: 800 });
+ const viewport = new Viewport('control-gesture-viewport', scene, { left: 0, top: 0, width: 800, height: 800 });
+ const rect = new Rect('control-gesture-object', { left: 100, top: 100, width: 100, height: 100 });
+ scene.addObject(rect);
+ const transformer = new Transformer(scene, { rotateEnabled: true });
+ const ended = vi.fn();
+ const subscription = transformer.changeEnd$.subscribe(ended);
+ try {
+ transformer.setSelectedControl(rect);
+ const anchor = scene.getAllObjectsByOrderForPick().find((object) => object.oKey.includes(controlKey));
+ if (!anchor) {
+ throw new Error(`Missing ${controlKey} control`);
+ }
+ const initial = rect.getState();
+ const point = anchor.ancestorTransform.applyPoint(new Vector2(anchor.width / 2, anchor.height / 2));
+ anchor.onPointerDown$.emitEvent(createPointerEvent('pointerdown', point.x, point.y));
+ scene.onPointerMove$.emitEvent(createPointerEvent('pointermove', point.x + 60, point.y + 40));
+ transformer.finishTransform();
+ expect(ended).toHaveBeenCalledTimes(1);
+ const transformed = rect.getState();
+ expect(transformed).not.toEqual(initial);
+ scene.onPointerMove$.emitEvent(createPointerEvent('pointermove', 500, 500));
+ scene.onPointerUp$.emitEvent(createPointerEvent('pointerup', 500, 500));
+ expect(ended).toHaveBeenCalledTimes(1);
+ expect(rect.getState()).toEqual(transformed);
+ } finally {
+ subscription.unsubscribe();
+ transformer.dispose();
+ viewport.dispose();
+ scene.dispose();
+ engine.dispose();
+ }
+ });
+
it('renders controls on the configured layer without moving the selected object', () => {
const engine = new Engine('transformer-layer-engine', { elementWidth: 100, elementHeight: 100, dpr: 1 });
const scene = new Scene('transformer-layer-scene', engine);
@@ -125,4 +350,44 @@ describe('Transformer', () => {
scene.dispose();
engine.dispose();
});
+
+ it('moves an object only on a gesture that starts after selection', () => {
+ const engine = new Engine('transformer-selection-engine', { elementWidth: 100, elementHeight: 100, dpr: 1 });
+ const scene = new Scene('transformer-selection-scene', engine);
+ const rect = new Rect('transformer-selection-rect', { width: 10, height: 10 });
+ scene.addObject(rect);
+ const transformer = new Transformer(scene, { moveOnlyWhenSelected: true });
+ const changeStart = vi.fn();
+ const changeStartSubscription = transformer.changeStart$.subscribe(changeStart);
+ const reattachSubscription = transformer.createControl$.subscribe(() => transformer.attachTo(rect));
+
+ transformer.attachTo(rect);
+ rect.onPointerDown$.emitEvent(createPointerEvent('pointerdown', 5, 5));
+ scene.onPointerMove$.emitEvent(createPointerEvent('pointermove', 25, 25));
+ scene.onPointerUp$.emitEvent(createPointerEvent('pointerup', 25, 25));
+
+ expect(transformer.getSelectedObjectMap().has(rect.oKey)).toBe(false);
+ expect(changeStart).not.toHaveBeenCalled();
+ expect(rect.left).toBe(0);
+ expect(rect.top).toBe(0);
+
+ rect.onPointerDown$.emitEvent(createPointerEvent('pointerdown', 5, 5));
+ scene.onPointerUp$.emitEvent(createPointerEvent('pointerup', 5, 5));
+
+ expect(transformer.getSelectedObjectMap().get(rect.oKey)).toBe(rect);
+
+ rect.onPointerDown$.emitEvent(createPointerEvent('pointerdown', 5, 5));
+ scene.onPointerMove$.emitEvent(createPointerEvent('pointermove', 25, 25));
+ scene.onPointerUp$.emitEvent(createPointerEvent('pointerup', 25, 25));
+
+ expect(changeStart).toHaveBeenCalledTimes(1);
+ expect(rect.left).toBe(20);
+ expect(rect.top).toBe(20);
+
+ reattachSubscription.unsubscribe();
+ changeStartSubscription.unsubscribe();
+ transformer.dispose();
+ scene.dispose();
+ engine.dispose();
+ });
});
diff --git a/packages/engine-render/src/basics/transformer-config.ts b/packages/engine-render/src/basics/transformer-config.ts
index 2020ea542b..65b836f244 100644
--- a/packages/engine-render/src/basics/transformer-config.ts
+++ b/packages/engine-render/src/basics/transformer-config.ts
@@ -21,6 +21,8 @@ import type { IMouseEvent, IPointerEvent } from './i-events';
export interface ITransformerConfig {
// for image copper
isCropper?: boolean;
+ /** Minimum crop-handle hit target in screen pixels; does not change its appearance. */
+ cropAnchorHitSize?: number;
hoverEnabled?: boolean;
hoverEnterFunc?: Nullable<(e: IPointerEvent | IMouseEvent) => void>;
@@ -49,6 +51,8 @@ export interface ITransformerConfig {
resizeEnabled?: boolean;
moveEnabled?: boolean;
+ /** Start moving only when the object was already selected before pointer down. */
+ moveOnlyWhenSelected?: boolean;
enabledAnchors?: number[];
anchorFill?: string;
anchorStroke?: string;
diff --git a/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts b/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts
index c4d6afaf60..983da2a25b 100644
--- a/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts
@@ -478,19 +478,22 @@ describe('doc skeleton', () => {
it.each(['ready', 'cancel', 'failure', 'header', 'footer'])('waits for cold hyphenation rules and matches a warm executor (%s)', async (scenario) => {
const univer = new Univer();
- const content = scenario === 'header' || scenario === 'footer'
- ? 'Este documento contiene información sobre la configuración y la administración de los servicios.'
- : `${'A continued paragraph crosses several physical pages. '.repeat(50)}Hello world ${'Further text keeps the paragraph flowing. '.repeat(100)}`;
+ const content = 'Este documento contiene información sobre la configuración y la administración de los servicios. '
+ .repeat(scenario === 'header' || scenario === 'footer' ? 1 : 4);
const snapshot: Partial<IDocumentData> = {
id: 'hyphen-readiness',
body: {
dataStream: `${content}\r\n`,
- paragraphs: [{ startIndex: content.length, paragraphId: 'hyphen-paragraph' }],
+ paragraphs: [{
+ startIndex: content.length,
+ paragraphId: 'hyphen-paragraph',
+ paragraphStyle: { lineSpacing: 18, spacingRule: SpacingRule.EXACT },
+ }],
sectionBreaks: [{ startIndex: content.length + 1, sectionId: 'hyphen-section' }],
},
documentStyle: {
documentFlavor: DocumentFlavor.TRADITIONAL,
- pageSize: { width: 600, height: 700 },
+ pageSize: { width: 120, height: 120 },
marginTop: 30,
marginBottom: 30,
marginLeft: 30,
@@ -546,6 +549,9 @@ describe('doc skeleton', () => {
}
await vi.waitFor(() => expect(cold.stepIncrementalLayout(coldGeneration, 8).complete).toBe(true));
completeIncrementalLayout(warm);
+ if (scenario !== 'header' && scenario !== 'footer') {
+ expect(cold.getSkeletonData()?.pages.length).toBeGreaterThan(1);
+ }
expect(normalizeSkeleton(cold.getSkeletonData())).toEqual(normalizeSkeleton(warm.getSkeletonData()));
} finally {
loader.mockRestore();
@@ -2973,6 +2979,59 @@ describe('doc skeleton', () => {
}
);
+ it('keeps mobile geometry when typing interrupts a modern viewport reflow', () => {
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+ const paragraphs = Array.from(
+ { length: 20 },
+ (_, index) => `Modern paragraph ${index} wraps at the available mobile width.\r`
+ );
+ const content = paragraphs.join('');
+ const initialModel = createDocumentModelWithStyle(content, {});
+ initialModel.updateDocumentStyle({
+ documentFlavor: DocumentFlavor.MODERN,
+ pageSize: { width: 960, height: Number.POSITIVE_INFINITY },
+ });
+ const viewModel = new DocumentViewModel(initialModel);
+ const skeleton = DocumentSkeleton.create(viewModel, localeService);
+ const mobileGeometry = { modernPageWidth: 366, modernHorizontalMargin: 20 };
+ skeleton.calculate();
+
+ const resizeGeneration = skeleton.startIncrementalLayout({ reason: 'initial', ...mobileGeometry });
+ const resizeProgress = skeleton.stepIncrementalLayout(resizeGeneration, 0);
+ expect(resizeProgress.complete).toBe(false);
+ expect(skeleton.getSkeletonData()?.pages[0].pageWidth).toBe(mobileGeometry.modernPageWidth);
+
+ const anchor = paragraphs[0].length + 5;
+ const nextModel = createDocumentModelWithStyle(`${content.slice(0, anchor)}输入${content.slice(anchor)}`, {});
+ nextModel.updateDocumentStyle({
+ documentFlavor: DocumentFlavor.MODERN,
+ pageSize: { width: 960, height: Number.POSITIVE_INFINITY },
+ });
+ viewModel.reset(nextModel);
+ const generation = skeleton.startIncrementalLayout({
+ reason: 'edit',
+ anchor,
+ invalidation: { oldStart: anchor, oldEnd: anchor, newEnd: anchor + 2 },
+ ...mobileGeometry,
+ });
+ let progress = skeleton.stepIncrementalLayout(generation, 0);
+ for (let step = 0; step < 100 && !progress.complete; step++) {
+ progress = skeleton.stepIncrementalLayout(generation, 0);
+ }
+ expect(progress.complete).toBe(true);
+ expect(skeleton.getSkeletonData()?.pages[0]).toMatchObject({
+ pageWidth: mobileGeometry.modernPageWidth,
+ marginLeft: mobileGeometry.modernHorizontalMargin,
+ marginRight: mobileGeometry.modernHorizontalMargin,
+ });
+
+ skeleton.dispose();
+ initialModel.dispose();
+ nextModel.dispose();
+ univer.dispose();
+ });
+
it('falls back to full incremental layout for a complex modern page', () => {
const univer = new Univer();
const localeService = univer.__getInjector().get(LocaleService);
diff --git a/packages/engine-render/src/components/docs/layout/__tests__/tools.spec.ts b/packages/engine-render/src/components/docs/layout/__tests__/tools.spec.ts
index c96cdecadc..af6f8ca9c9 100644
--- a/packages/engine-render/src/components/docs/layout/__tests__/tools.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/__tests__/tools.spec.ts
@@ -692,6 +692,8 @@ describe('docs layout tools extra', () => {
const ctx = {
docsConfig: { locale: 'zh-CN' },
+ modernPageWidth: 390,
+ modernHorizontalMargin: 20,
viewModel: {
getChildren: () => [{ endIndex: 9 }, { endIndex: 19 }],
getSectionBreak: vi.fn((endIndex: number) => {
@@ -729,7 +731,9 @@ describe('docs layout tools extra', () => {
};
const sectionConfig = prepareSectionBreakConfig(ctx as any, 0);
- expect(sectionConfig.pageSize?.width).toBeGreaterThan(0);
+ expect(sectionConfig.pageSize?.width).toBe(390);
+ expect(sectionConfig.marginLeft).toBe(20);
+ expect(sectionConfig.marginRight).toBe(20);
expect(sectionConfig.headerIds).toEqual({
defaultHeaderId: '',
evenPageHeaderId: '',
@@ -743,6 +747,15 @@ describe('docs layout tools extra', () => {
expect(sectionConfig.evenAndOddHeaders).toBe(BooleanNumber.FALSE);
expect(sectionConfig.useFirstPageHeaderFooter).toBe(BooleanNumber.FALSE);
+ const desktopSectionConfig = prepareSectionBreakConfig({
+ ...ctx,
+ modernPageWidth: undefined,
+ modernHorizontalMargin: undefined,
+ } as any, 0);
+ expect(desktopSectionConfig.pageSize?.width).toBe(800);
+ expect(desktopSectionConfig.marginLeft).toBe(30);
+ expect(desktopSectionConfig.marginRight).toBe(40);
+
const dirtyCtx = {
isDirty: true,
skeleton: { drawingAnchor: new Map([['a', 1]]) },
diff --git a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts b/packages/engine-render/src/components/docs/layout/doc-skeleton.ts
index f06ba50744..a2fa9bd53f 100644
--- a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts
+++ b/packages/engine-render/src/components/docs/layout/doc-skeleton.ts
@@ -1200,6 +1200,10 @@ export class DocumentSkeleton extends Skeleton {
private readonly _isolateIncrementalPublications: boolean;
+ private _modernPageWidth: number | undefined;
+
+ private _modernHorizontalMargin: number | undefined;
+
constructor(
private _docViewModel: DocumentViewModel,
localeService: LocaleService,
@@ -1263,6 +1267,8 @@ export class DocumentSkeleton extends Skeleton {
anchor?: number;
priorityAnchor?: number;
invalidation?: IDocumentLayoutInvalidation;
+ modernPageWidth?: number;
+ modernHorizontalMargin?: number;
bounds?: IViewportInfo;
reuseUnaffectedTail?: boolean;
/** The caller proved this edit only changes offset-preserving render metadata. */
@@ -1271,6 +1277,8 @@ export class DocumentSkeleton extends Skeleton {
/** Cooperative schedulers wait for code-split dictionaries before publishing. */
waitForHyphenationPatterns?: boolean;
}): number {
+ this._modernPageWidth = options?.modernPageWidth;
+ this._modernHorizontalMargin = options?.modernHorizontalMargin;
this.cancelIncrementalLayout();
this._externalLayoutProgress = null;
this._externalProtectedPages = null;
@@ -1787,6 +1795,12 @@ export class DocumentSkeleton extends Skeleton {
}
const previousPage = previousSkeleton.pages[0];
+ // Typing can interrupt a viewport reflow before its new geometry replaces
+ // the last complete checkpoint. Reusing that prefix would restore the old width.
+ if (!hasCompatiblePageGeometry(previousPage, prepareSectionBreakConfig(ctx, 0))) {
+ return null;
+ }
+
const previousSection = previousPage.sections[0];
const previousColumn = previousSection?.columns[0];
if (
@@ -4960,6 +4974,8 @@ export class DocumentSkeleton extends Skeleton {
skeleton,
skeletonResourceReference,
docsConfig,
+ modernPageWidth: this._modernPageWidth,
+ modernHorizontalMargin: this._modernHorizontalMargin,
layoutStartPointer: {
'': null, // '' is the main document.
},
diff --git a/packages/engine-render/src/components/docs/layout/tools.ts b/packages/engine-render/src/components/docs/layout/tools.ts
index 93743780af..fa1c19178d 100644
--- a/packages/engine-render/src/components/docs/layout/tools.ts
+++ b/packages/engine-render/src/components/docs/layout/tools.ts
@@ -1880,6 +1880,8 @@ export interface ILayoutContext {
// documentStyle: IDocumentStyle;
// Configuration for document layout.
docsConfig: IDocsConfig;
+ modernPageWidth?: number;
+ modernHorizontalMargin?: number;
// The initial layout skeleton, it will be the empty skeleton if it's the first layout.
skeleton: IDocumentSkeletonCached;
// The position coordinates of the layout,
@@ -1989,7 +1991,7 @@ export function prepareSectionBreakConfig(ctx: ILayoutContext, nodeIndex: number
// If the configuration is in modern mode, use the style configuration of modern mode to overwrite the original configuration.
// In modern mode, there are no pages, no sections, no columns. There are no headers and footers, and margins are all defaults.
if (documentFlavor === DocumentFlavor.MODERN) {
- const modernPageWidth = documentStyle.pageSize?.width ?? DEFAULT_MODERN_DOCUMENT_STYLE.pageSize!.width;
+ const modernPageWidth = ctx.modernPageWidth ?? documentStyle.pageSize?.width ?? DEFAULT_MODERN_DOCUMENT_STYLE.pageSize!.width;
const modernPageSize = {
...DEFAULT_MODERN_DOCUMENT_STYLE.pageSize!,
width: modernPageWidth,
@@ -1998,8 +2000,17 @@ export function prepareSectionBreakConfig(ctx: ILayoutContext, nodeIndex: number
// override the continuous page when the document switches to modern
// mode, otherwise layout still paginates and pointer bounds stop at
// the first sheet of paper while rendering merges the entire document.
- sectionBreak = Object.assign({}, sectionBreak, DEFAULT_MODERN_SECTION_BREAK, { pageSize: modernPageSize });
- documentStyle = Object.assign({}, documentStyle, DEFAULT_MODERN_DOCUMENT_STYLE, { pageSize: modernPageSize });
+ const modernLayout = {
+ pageSize: modernPageSize,
+ ...(ctx.modernHorizontalMargin == null
+ ? {}
+ : {
+ marginLeft: ctx.modernHorizontalMargin,
+ marginRight: ctx.modernHorizontalMargin,
+ }),
+ };
+ sectionBreak = Object.assign({}, sectionBreak, DEFAULT_MODERN_SECTION_BREAK, modernLayout);
+ documentStyle = Object.assign({}, documentStyle, DEFAULT_MODERN_DOCUMENT_STYLE, modernLayout);
}
const {
diff --git a/packages/engine-render/src/scene-viewer.ts b/packages/engine-render/src/scene-viewer.ts
index 02e4c8d33e..70086aefa2 100644
--- a/packages/engine-render/src/scene-viewer.ts
+++ b/packages/engine-render/src/scene-viewer.ts
@@ -15,6 +15,7 @@
*/
import type { Nullable } from '@univerjs/core';
+import type { DeviceType } from './basics/i-events';
import type { IObjectFullState } from './basics/interfaces';
import type { IViewportInfo, Vector2 } from './basics/vector2';
import type { UniverRenderingContext } from './context';
@@ -124,14 +125,14 @@ export class SceneViewer extends BaseObject {
}
// Determine the uniquely selected object
- pick(coord: Vector2) {
+ pick(coord: Vector2, deviceType?: DeviceType) {
if (this._activeSubScene === undefined) {
return;
}
const tCoord = this.transform.invert().applyPoint(coord);
- return this._activeSubScene?.pick(tCoord);
+ return this._activeSubScene?.pick(tCoord, deviceType);
}
override dispose() {
diff --git a/packages/engine-render/src/scene.input-manager.ts b/packages/engine-render/src/scene.input-manager.ts
index 57d2d076f4..9a52f66721 100644
--- a/packages/engine-render/src/scene.input-manager.ts
+++ b/packages/engine-render/src/scene.input-manager.ts
@@ -126,7 +126,7 @@ export class InputManager extends Disposable {
(evt as unknown as PointerEvent).pointerId = 0;
}
- const currentObject = this._getObjectAtPos(evt.offsetX, evt.offsetY);
+ const currentObject = this._getObjectAtEvent(evt);
const isStop = currentObject?.triggerClick(evt);
if (!isStop && this._shouldDispatchEventToScene(currentObject)) {
@@ -139,7 +139,7 @@ export class InputManager extends Disposable {
(evt as unknown as PointerEvent).pointerId = 0;
}
- const currentObject = this._getObjectAtPos(evt.offsetX, evt.offsetY);
+ const currentObject = this._getObjectAtEvent(evt);
const isStop = currentObject?.triggerDblclick(evt);
if (!isStop && this._shouldDispatchEventToScene(currentObject)) {
@@ -153,7 +153,7 @@ export class InputManager extends Disposable {
evt.pointerId = 0;
}
- this._currentObject = this._getObjectAtPos(evt.offsetX, evt.offsetY);
+ this._currentObject = this._getObjectAtEvent(evt);
this.mouseLeaveEnterHandler(evt);
}
@@ -176,7 +176,7 @@ export class InputManager extends Disposable {
if (this._pointerDownPosition && this._isPointerSwiping(evt.clientX, evt.clientY, this._pointerDownPosition)) {
this._pointerDragged = true;
}
- const currentObject = this._currentObject = this._getObjectAtPos(evt.offsetX, evt.offsetY);
+ const currentObject = this._currentObject = this._getObjectAtEvent(evt);
const isStop = (currentObject || this.capturedObject)?.triggerPointerMove(evt);
@@ -200,7 +200,7 @@ export class InputManager extends Disposable {
this._resetClickSequence();
}
- const currentObject = this._getObjectAtPos(evt.offsetX, evt.offsetY);
+ const currentObject = this._getObjectAtEvent(evt);
const isStop = currentObject?.triggerPointerDown(evt);
if (!isStop && this._shouldDispatchEventToScene(currentObject)) {
@@ -218,7 +218,7 @@ export class InputManager extends Disposable {
!this._isPointerSwiping(evt.clientX, evt.clientY, this._pointerDownPosition);
this._pointerDownPosition = null;
- const currentObject = this._getObjectAtPos(evt.offsetX, evt.offsetY);
+ const currentObject = this._getObjectAtEvent(evt);
const isStop = currentObject?.triggerPointerUp(evt);
if (!isStop && this._shouldDispatchEventToScene(currentObject)) {
@@ -236,13 +236,13 @@ export class InputManager extends Disposable {
this._pointerDownPosition = null;
this._resetClickSequence();
this._scene.onPointerCancel$.emitEvent(evt);
- const currentObject = this._getObjectAtPos(evt.offsetX, evt.offsetY);
+ const currentObject = this._getObjectAtEvent(evt);
currentObject?.triggerPointerCancel(evt);
}
_onPointerOut(evt: IPointerEvent) {
this._scene.onPointerOut$.emitEvent(evt);
- const currentObject = this._getObjectAtPos(evt.offsetX, evt.offsetY);
+ const currentObject = this._getObjectAtEvent(evt);
currentObject?.triggerPointerOut(evt);
}
@@ -410,8 +410,31 @@ export class InputManager extends Disposable {
* @param offsetX
* @param offsetY
*/
- private _getObjectAtPos(offsetX: number, offsetY: number) {
- return this._scene?.pick(Vector2.FromArray([offsetX, offsetY]));
+ private _getObjectAtPos(offsetX: number, offsetY: number, deviceType?: DeviceType) {
+ return this._scene?.pick(Vector2.FromArray([offsetX, offsetY]), deviceType);
+ }
+
+ private _getObjectAtEvent(evt: IMouseEvent) {
+ if (evt.deviceType !== DeviceType.Touch) {
+ return this._getObjectAtPos(evt.offsetX, evt.offsetY, evt.deviceType);
+ }
+
+ const engine = this._scene.getEngine();
+ const canvas = engine?.getCanvasElement();
+ if (!engine || !canvas || !Number.isFinite(evt.clientX) || !Number.isFinite(evt.clientY)) {
+ return this._getObjectAtPos(evt.offsetX, evt.offsetY, evt.deviceType);
+ }
+
+ const rect = canvas.getBoundingClientRect();
+ if (rect.width <= 0 || rect.height <= 0) {
+ return this._getObjectAtPos(evt.offsetX, evt.offsetY, evt.deviceType);
+ }
+
+ return this._getObjectAtPos(
+ (evt.clientX - rect.left) * engine.width / rect.width,
+ (evt.clientY - rect.top) * engine.height / rect.height,
+ evt.deviceType
+ );
}
/**
@@ -504,13 +527,13 @@ export class InputManager extends Disposable {
this._doubleClickOccurred += 1;
if (this._tripleClickState) {
- this._scene?.pick(Vector2.FromArray([evt.offsetX, evt.offsetY]))?.triggerTripleClick(evt);
+ this._getObjectAtEvent(evt)?.triggerTripleClick(evt);
this._scene.onTripleClick$.emitEvent(evt);
}
if (this._doubleClickOccurred === 2) {
- this._scene?.pick(Vector2.FromArray([evt.offsetX, evt.offsetY]))?.triggerDblclick(evt);
+ this._getObjectAtEvent(evt)?.triggerDblclick(evt);
this._scene.onDblclick$.emitEvent(evt);
this._resetDoubleClickParam();
diff --git a/packages/engine-render/src/scene.transformer.ts b/packages/engine-render/src/scene.transformer.ts
index d95761ef43..11b469a242 100644
--- a/packages/engine-render/src/scene.transformer.ts
+++ b/packages/engine-render/src/scene.transformer.ts
@@ -34,6 +34,7 @@ import { DEFAULT_TRANSFORMER_CONFIG } from './basics/transformer-config';
import { Vector2 } from './basics/vector2';
import { Group } from './group';
import { ScrollTimer } from './scroll-timer';
+import { Control } from './shape/control';
import { Line } from './shape/line';
import { Rect } from './shape/rect';
import { RegularPolygon } from './shape/regular-polygon';
@@ -129,7 +130,24 @@ class TransformerRotateIcon extends Rect {
}
}
-class TransformerAnchor extends Rect {
+class TransformerCropAnchor extends RegularPolygon {
+ constructor(key: string, props: IRegularPolygonProps, private readonly _hitSize: number) {
+ super(key, props);
+ }
+
+ override isHit(coord: Vector2): boolean {
+ if (this._hitSize <= 0) {
+ return super.isHit(coord);
+ }
+ const point = this.getInverseCoord(coord);
+ const scale = this.getScene()?.getAncestorScale();
+ const halfWidth = Math.max(this.width, this._hitSize / Math.max(scale?.scaleX ?? 1, 0.01)) / 2;
+ const halfHeight = Math.max(this.height, this._hitSize / Math.max(scale?.scaleY ?? 1, 0.01)) / 2;
+ return Math.abs(point.x - this.width / 2) <= halfWidth && Math.abs(point.y - this.height / 2) <= halfHeight;
+ }
+}
+
+class TransformerAnchor extends Control {
protected override _draw(ctx: UniverRenderingContext) {
if (!this.shadowColor || (!this.shadowBlur && !this.shadowOffsetX && !this.shadowOffsetY)) {
Rect.drawWith(ctx, this as IRectProps);
@@ -152,6 +170,8 @@ class TransformerAnchor extends Rect {
* when you resize them. Instead it changes `scaleX` and `scaleY` properties.
*/
export class Transformer extends Disposable implements ITransformerConfig {
+ private static readonly _selectionTapMovementThreshold = 12;
+
isCropper: boolean = false;
hoverEnabled = false;
@@ -159,6 +179,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
hoverLeaveFunc: Nullable<(e: IPointerEvent | IMouseEvent) => void>;
moveEnabled: boolean = DEFAULT_TRANSFORMER_CONFIG.moveEnabled;
+ moveOnlyWhenSelected = false;
resizeEnabled: boolean = DEFAULT_TRANSFORMER_CONFIG.resizeEnabled;
rotateEnabled: boolean = DEFAULT_TRANSFORMER_CONFIG.rotateEnabled;
@@ -249,15 +270,13 @@ export class Transformer extends Disposable implements ITransformerConfig {
private _viewportScrollX: number = -1;
private _viewportScrollY: number = -1;
- private _topScenePointerMoveSub: Nullable<Subscription>;
- private _topScenePointerUpSub: Nullable<Subscription>;
+ private _finishGesture: (() => void) | null = null;
private _cancelFocusSubscription: Nullable<Subscription>;
private _transformerControlMap = new Map<string, Group>();
private _selectedObjectMap = new Map<string, BaseObject>();
private _subscriptionObjectMap = new Map<string, Nullable<Subscription>>();
-
private _copperControl: Nullable<Group>;
private _copperSelectedObject: Nullable<BaseObject>;
@@ -291,6 +310,30 @@ export class Transformer extends Disposable implements ITransformerConfig {
return this._selectedObjectMap;
}
+ /** Complete the current object transform before another gesture takes ownership of the scene. */
+ finishTransform(): void {
+ this._finishGesture?.();
+ }
+
+ private _bindGestureEnd(scene: Scene, initialEvent: IPointerEvent | IMouseEvent, onEnd: (event: IPointerEvent | IMouseEvent) => void): void {
+ let latestEvent = initialEvent;
+ const subscriptions: Subscription[] = [];
+ subscriptions.push(scene.onPointerMove$.subscribeEvent((event) => {
+ latestEvent = event;
+ }));
+ const finish = (event = latestEvent) => {
+ if (this._finishGesture !== finish) {
+ return;
+ }
+ this._finishGesture = null;
+ subscriptions.forEach((subscription) => subscription.unsubscribe());
+ onEnd(event);
+ };
+ subscriptions.push(scene.onPointerUp$.subscribeEvent((event) => finish(event)));
+ subscriptions.push(scene.onPointerCancel$.subscribeEvent(() => finish()));
+ this._finishGesture = finish;
+ }
+
resetProps(config?: ITransformerConfig) {
this._initialProps(config);
}
@@ -358,6 +401,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
hoverEnterFunc,
hoverLeaveFunc,
moveEnabled,
+ moveOnlyWhenSelected,
resizeEnabled,
rotateEnabled,
rotationSnaps,
@@ -407,6 +451,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
hoverEnterFunc = objectTransformerConfig.hoverEnterFunc ?? hoverEnterFunc;
hoverLeaveFunc = objectTransformerConfig.hoverLeaveFunc ?? hoverLeaveFunc;
moveEnabled = objectTransformerConfig.moveEnabled ?? moveEnabled;
+ moveOnlyWhenSelected = objectTransformerConfig.moveOnlyWhenSelected ?? moveOnlyWhenSelected;
resizeEnabled = objectTransformerConfig.resizeEnabled ?? resizeEnabled;
rotateEnabled = objectTransformerConfig.rotateEnabled ?? rotateEnabled;
rotationSnaps = objectTransformerConfig.rotationSnaps ?? rotationSnaps;
@@ -457,6 +502,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
hoverEnterFunc,
hoverLeaveFunc,
moveEnabled,
+ moveOnlyWhenSelected,
resizeEnabled,
rotateEnabled,
rotationSnaps,
@@ -509,11 +555,42 @@ export class Transformer extends Disposable implements ITransformerConfig {
// eslint-disable-next-line max-lines-per-function
const observer = applyObject.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
+ this.finishTransform();
const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
this._startOffsetX = evtOffsetX;
this._startOffsetY = evtOffsetY;
- const { isCropper, moveEnabled } = this._getConfig(applyObject);
+ const { isCropper, moveEnabled, moveOnlyWhenSelected } = this._getConfig(applyObject);
+
+ if (!isCropper && moveOnlyWhenSelected && !this._selectedObjectMap.has(this._findGroupObject(applyObject).oKey)) {
+ const scene = this._getTopScene();
+ if (!scene) {
+ this._updateActiveObjectList(applyObject, evt);
+ return;
+ }
+
+ let moved = false;
+ let moveSubscription: Nullable<Subscription>;
+ let upSubscription: Nullable<Subscription>;
+ let cancelSubscription: Nullable<Subscription>;
+ const disposeGesture = () => {
+ moveSubscription?.unsubscribe();
+ upSubscription?.unsubscribe();
+ cancelSubscription?.unsubscribe();
+ };
+
+ moveSubscription = scene.onPointerMove$.subscribeEvent((moveEvent: IPointerEvent | IMouseEvent) => {
+ moved ||= Math.hypot(moveEvent.offsetX - evtOffsetX, moveEvent.offsetY - evtOffsetY) >= Transformer._selectionTapMovementThreshold;
+ });
+ upSubscription = scene.onPointerUp$.subscribeEvent(() => {
+ disposeGesture();
+ if (!moved) {
+ this._updateActiveObjectList(applyObject, evt);
+ }
+ });
+ cancelSubscription = scene.onPointerCancel$.subscribeEvent(disposeGesture);
+ return;
+ }
if (!isCropper && !moveEnabled) {
this._updateActiveObjectList(applyObject, evt);
@@ -567,9 +644,8 @@ export class Transformer extends Disposable implements ITransformerConfig {
});
});
- const scenePointerUpSub = scene.onPointerUp$.subscribeEvent((event) => {
+ this._bindGestureEnd(scene, evt, (event) => {
scenePointerMoveSub?.unsubscribe();
- scenePointerUpSub?.unsubscribe();
scene.enableObjectsEvent();
!isCropper && this.refreshControls();
scrollTimer.dispose();
@@ -619,19 +695,15 @@ export class Transformer extends Disposable implements ITransformerConfig {
}
override dispose() {
+ this.finishTransform();
super.dispose();
this._subscriptionObjectMap.forEach((subscription) => subscription?.unsubscribe());
this._subscriptionObjectMap.clear();
- this._topScenePointerMoveSub?.unsubscribe();
- this._topScenePointerUpSub?.unsubscribe();
-
this._cancelFocusSubscription?.unsubscribe();
this._cancelFocusSubscription = null;
- this._topScenePointerMoveSub = null;
- this._topScenePointerUpSub = null;
this._cancelFocusSubscription = null;
this._transformerControlMap.forEach((control) => control.dispose());
@@ -1104,6 +1176,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
toDisposable(
// eslint-disable-next-line max-lines-per-function
anchor.onPointerDown$.subscribeEvent((evt, state) => {
+ this.finishTransform();
const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
this._startOffsetX = evtOffsetX;
this._startOffsetY = evtOffsetY;
@@ -1143,7 +1216,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
}
this._moveBufferSkip = false;
- this._topScenePointerMoveSub = topScene.onPointerMove$.subscribeEvent((moveEvt: IPointerEvent | IMouseEvent) => {
+ const moveSubscription = topScene.onPointerMove$.subscribeEvent((moveEvt: IPointerEvent | IMouseEvent) => {
const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
this._anchorMoving(type, moveOffsetX, moveOffsetY, scrollTimer, keepRatio, isCropper, applyObject);
@@ -1153,11 +1226,8 @@ export class Transformer extends Disposable implements ITransformerConfig {
topScene.setCursor(cursor);
});
- this._topScenePointerUpSub = topScene.onPointerUp$.subscribeEvent((event) => {
- // topScene.onPointerMove$.remove(this._moveObserver);
- // topScene.onPointerUp$.remove(this._topScenePointerUpSub);
- this._topScenePointerMoveSub?.unsubscribe();
- this._topScenePointerUpSub?.unsubscribe();
+ this._bindGestureEnd(topScene, evt, (event) => {
+ moveSubscription.unsubscribe();
topScene.enableObjectsEvent();
topScene.resetCursor();
scrollTimer.dispose();
@@ -1223,6 +1293,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
this.disposeWithMe(
toDisposable(
rotateControl.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
+ this.finishTransform();
const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
this._startOffsetX = evtOffsetX;
@@ -1261,11 +1332,8 @@ export class Transformer extends Disposable implements ITransformerConfig {
topScene.setCursor(cursor);
});
- const topScenePointerUpSub = topScene.onPointerUp$.subscribeEvent((event) => {
- // topScenePointerMoveSub?.dispose();
- // topScenePointerUpSub?.dispose();
+ this._bindGestureEnd(topScene, evt, (event) => {
topScenePointerMoveSub?.unsubscribe();
- topScenePointerUpSub?.unsubscribe();
topScene.enableObjectsEvent();
topScene.resetCursor();
this.refreshControls();
@@ -1603,9 +1671,8 @@ export class Transformer extends Disposable implements ITransformerConfig {
const cursor = this._getRotateAnchorCursor(type);
- let anchor: BaseObject;
const oKey = `${type}_${zIndex}`;
- const config: IRectProps | IRegularPolygonProps = {
+ const config: IRegularPolygonProps = {
zIndex: zIndex - 1,
fill: anchorFill,
stroke: anchorStroke,
@@ -1614,42 +1681,44 @@ export class Transformer extends Disposable implements ITransformerConfig {
height: anchorSize,
left,
top,
+ pointsGroup: [],
};
const longEdge = anchorSize;
const shortEdge = anchorSize / 4;
if (cursor === CURSOR_TYPE.EAST_RESIZE) {
config.width = shortEdge;
config.height = longEdge;
- anchor = new Rect(oKey, config);
} else if (cursor === CURSOR_TYPE.WEST_RESIZE) {
config.width = shortEdge;
config.height = longEdge;
- anchor = new Rect(oKey, config);
} else if (cursor === CURSOR_TYPE.NORTH_RESIZE) {
config.width = longEdge;
config.height = shortEdge;
- anchor = new Rect(oKey, config);
} else if (cursor === CURSOR_TYPE.SOUTH_RESIZE) {
config.width = longEdge;
config.height = shortEdge;
- anchor = new Rect(oKey, config);
} else if (cursor === CURSOR_TYPE.NORTH_EAST_RESIZE) {
- (config as IRegularPolygonProps).pointsGroup = this._getNorthEastPoints(longEdge, shortEdge);
- anchor = new RegularPolygon(oKey, config as IRegularPolygonProps);
+ config.pointsGroup = this._getNorthEastPoints(longEdge, shortEdge);
} else if (cursor === CURSOR_TYPE.NORTH_WEST_RESIZE) {
- (config as IRegularPolygonProps).pointsGroup = this._getNorthWestPoints(longEdge, shortEdge);
- anchor = new RegularPolygon(oKey, config as IRegularPolygonProps);
+ config.pointsGroup = this._getNorthWestPoints(longEdge, shortEdge);
} else if (cursor === CURSOR_TYPE.SOUTH_EAST_RESIZE) {
- (config as IRegularPolygonProps).pointsGroup = this._getSouthEastPoints(longEdge, shortEdge);
- anchor = new RegularPolygon(oKey, config as IRegularPolygonProps);
+ config.pointsGroup = this._getSouthEastPoints(longEdge, shortEdge);
} else if (cursor === CURSOR_TYPE.SOUTH_WEST_RESIZE) {
- (config as IRegularPolygonProps).pointsGroup = this._getSouthWestPoints(longEdge, shortEdge);
- anchor = new RegularPolygon(oKey, config as IRegularPolygonProps);
+ config.pointsGroup = this._getSouthWestPoints(longEdge, shortEdge);
}
- this._attachHover(anchor!, cursor, CURSOR_TYPE.DEFAULT);
+ if (config.pointsGroup.length === 0) {
+ config.pointsGroup = [[
+ { x: 0, y: 0 },
+ { x: config.width ?? 0, y: 0 },
+ { x: config.width ?? 0, y: config.height ?? 0 },
+ { x: 0, y: config.height ?? 0 },
+ ]];
+ }
+ const anchor = new TransformerCropAnchor(oKey, config, applyObject.transformerConfig?.cropAnchorHitSize ?? 0);
+ this._attachHover(anchor, cursor, CURSOR_TYPE.DEFAULT);
- return anchor!;
+ return anchor;
}
private _getNorthEastPoints(longEdge: number, shortEdge: number): IPoint[][] {
diff --git a/packages/engine-render/src/scene.ts b/packages/engine-render/src/scene.ts
index 73a8bcedc0..f636b87702 100644
--- a/packages/engine-render/src/scene.ts
+++ b/packages/engine-render/src/scene.ts
@@ -29,12 +29,14 @@ import type { Viewport } from './viewport';
import { Disposable, EventSubject, sortRules, sortRulesByDesc, toDisposable, Tools } from '@univerjs/core';
import { BehaviorSubject } from 'rxjs';
import { CURSOR_TYPE, RENDER_CLASS_TYPE } from './basics/const';
+import { DeviceType } from './basics/i-events';
import { TRANSFORM_CHANGE_OBSERVABLE_TYPE } from './basics/interfaces';
import { precisionTo, requestNewFrame } from './basics/tools';
import { Transform } from './basics/transform';
import { Layer, scrollAndClearCanvas } from './layer';
import { InputManager } from './scene.input-manager';
import { Transformer } from './scene.transformer';
+import { Control } from './shape/control';
export const MAIN_VIEW_PORT_KEY = 'viewMain';
@@ -1276,7 +1278,7 @@ export class Scene extends Disposable {
* @param {Vector2} coord
* @return {Nullable<BaseObject | Scene>} object under the pointer
*/
- pick(coord: Vector2): Nullable<BaseObject | Scene> {
+ pick(coord: Vector2, deviceType?: DeviceType): Nullable<BaseObject | Scene> {
let pickedViewport = this.getActiveViewportByCoord(coord);
if (!pickedViewport) {
@@ -1299,12 +1301,24 @@ export class Scene extends Disposable {
const objectOrder = this.getAllObjectsByOrderForPick().reverse();
const objectLength = objectOrder.length;
+ let nearestControl: Control | null = null;
+ let controlDistance = Number.POSITIVE_INFINITY;
+
for (let i = 0; i < objectLength; i++) {
const testObject = objectOrder[i];
if (!testObject.visible || !testObject.evented || (testObject.isInGroup && testObject.parent?.classType === RENDER_CLASS_TYPE.GROUP && testObject.isDrawingObject)) {
continue;
}
const svCoord = vecFromSheetContent;
+ // Resolve overlapping touch targets by distance, without reaching through a higher overlay.
+ if (deviceType === DeviceType.Touch && testObject instanceof Control) {
+ const distance = testObject.getTouchHitDistance(svCoord);
+ if (distance < controlDistance) {
+ nearestControl = testObject;
+ controlDistance = distance;
+ }
+ continue;
+ }
// if (o.isInGroup && o.parent?.classType === RENDER_CLASS_TYPE.GROUP) {
// const { cumLeft, cumTop } = this._getGroupCumLeftRight(o);
// svCoord = svCoord.clone().add(Vector2.FromArray([-cumLeft, -cumTop]));
@@ -1312,7 +1326,7 @@ export class Scene extends Disposable {
if (testObject.isHit(svCoord)) {
if (testObject.classType === RENDER_CLASS_TYPE.SCENE_VIEWER) {
- const pickedObject = (testObject as SceneViewer).pick(svCoord);
+ const pickedObject = (testObject as SceneViewer).pick(svCoord, deviceType);
if (pickedObject) {
isPickedObject = pickedObject;
} else {
@@ -1326,7 +1340,7 @@ export class Scene extends Disposable {
testObject.classType === RENDER_CLASS_TYPE.SCENE_VIEWER &&
(testObject as SceneViewer).allowSelectedClipElement()
) {
- const pickedObject = (testObject as SceneViewer).pick(svCoord);
+ const pickedObject = (testObject as SceneViewer).pick(svCoord, deviceType);
if (pickedObject) {
isPickedObject = pickedObject;
break;
@@ -1334,6 +1348,10 @@ export class Scene extends Disposable {
}
}
+ if (nearestControl) {
+ return nearestControl;
+ }
+
if (!isPickedObject && this._parent.classType === RENDER_CLASS_TYPE.ENGINE) {
return this;
}
diff --git a/packages/engine-render/src/shape/control.ts b/packages/engine-render/src/shape/control.ts
index 6ccbd84c53..b7fc86364a 100644
--- a/packages/engine-render/src/shape/control.ts
+++ b/packages/engine-render/src/shape/control.ts
@@ -14,4 +14,20 @@
* limitations under the License.
*/
-export class Control {}
+import { Vector2 } from '../basics/vector2';
+import { Rect } from './rect';
+
+const CONTROL_TOUCH_HIT_RADIUS = 22;
+
+/** A precise mouse handle with a zoom-independent touch target. */
+export class Control extends Rect {
+ getTouchHitDistance(coord: Vector2): number {
+ const center = this.ancestorTransform.applyPoint(new Vector2(this.width / 2, this.height / 2));
+ const scale = this.getScene()?.getAncestorScale();
+ const distance = Math.hypot(
+ (coord.x - center.x) * (scale?.scaleX ?? 1),
+ (coord.y - center.y) * (scale?.scaleY ?? 1)
+ );
+ return distance <= CONTROL_TOUCH_HIT_RADIUS || this.isHit(coord) ? distance : Number.POSITIVE_INFINITY;
+ }
+}
diff --git a/packages/engine-render/src/worker-layout.ts b/packages/engine-render/src/worker-layout.ts
index 628964d111..77bebfe08d 100644
--- a/packages/engine-render/src/worker-layout.ts
+++ b/packages/engine-render/src/worker-layout.ts
@@ -34,6 +34,8 @@ export interface IDocumentLayoutSessionStartOptions {
priorityAnchor?: number;
invalidation?: IDocumentLayoutInvalidation;
waitForHyphenationPatterns?: boolean;
+ modernPageWidth?: number;
+ modernHorizontalMargin?: number;
}
export interface IDocumentLayoutStepResult {
diff --git a/packages/find-replace/src/views/dialog/FindReplaceDialog.tsx b/packages/find-replace/src/views/dialog/FindReplaceDialog.tsx
index 472db4907e..2268cc6c45 100644
--- a/packages/find-replace/src/views/dialog/FindReplaceDialog.tsx
+++ b/packages/find-replace/src/views/dialog/FindReplaceDialog.tsx
@@ -251,8 +251,10 @@ export const ReplaceDialog = forwardRef(function ReplaceDialogImpl(_props, ref)
<Checkbox
checked={caseSensitive}
onChange={(checked) => {
- findReplaceService.changeCaseSensitive(checked as boolean);
- if (findCompleted) findReplaceService.find();
+ findReplaceService.changeCaseSensitive(Boolean(checked));
+ if (findCompleted) {
+ findReplaceService.find();
+ }
}}
>
{localeService.t<LocaleKey>('find-replace.dialog.case-sensitive')}
@@ -261,7 +263,7 @@ export const ReplaceDialog = forwardRef(function ReplaceDialogImpl(_props, ref)
)}
{capabilities.matchesTheWholeCell && (
<FormLayout>
- <Checkbox checked={matchesTheWholeCell} onChange={(checked) => findReplaceService.changeMatchesTheWholeCell(checked as boolean)}>
+ <Checkbox checked={matchesTheWholeCell} onChange={(checked) => findReplaceService.changeMatchesTheWholeCell(Boolean(checked))}>
{localeService.t<LocaleKey>('find-replace.dialog.match-the-whole-cell')}
</Checkbox>
</FormLayout>
@@ -271,8 +273,10 @@ export const ReplaceDialog = forwardRef(function ReplaceDialogImpl(_props, ref)
<Checkbox
checked={matchesTheWholeWord}
onChange={(checked) => {
- findReplaceService.changeMatchesTheWholeWord(checked as boolean);
- if (findCompleted) findReplaceService.find();
+ findReplaceService.changeMatchesTheWholeWord(Boolean(checked));
+ if (findCompleted) {
+ findReplaceService.find();
+ }
}}
>
{localeService.t<LocaleKey>('find-replace.dialog.match-the-whole-word')}
diff --git a/packages/sheets-drawing-ui/src/views/sheet-image-panel/__tests__/SheetDrawingPanelBehavior.spec.tsx b/packages/sheets-drawing-ui/src/views/sheet-image-panel/__tests__/SheetDrawingPanelBehavior.spec.tsx
index f6b8ed6142..5500c9322f 100644
--- a/packages/sheets-drawing-ui/src/views/sheet-image-panel/__tests__/SheetDrawingPanelBehavior.spec.tsx
+++ b/packages/sheets-drawing-ui/src/views/sheet-image-panel/__tests__/SheetDrawingPanelBehavior.spec.tsx
@@ -18,7 +18,7 @@ import type { ISheetDrawing } from '@univerjs/sheets-drawing';
import type { Root } from 'react-dom/client';
import { DrawingTypeEnum, ImageSourceType } from '@univerjs/core';
import { IDrawingManagerService } from '@univerjs/drawing';
-import { DrawingImageClipService } from '@univerjs/drawing-ui';
+import { UniverDrawingUIPlugin } from '@univerjs/drawing-ui';
import { IRenderManagerService } from '@univerjs/engine-render';
import { InsertSheetDrawingCommand, ISheetDrawingService, SheetDrawingAnchorType } from '@univerjs/sheets-drawing';
import { ComponentManager, IconManager, RediContext } from '@univerjs/ui';
@@ -138,8 +138,8 @@ describe('SheetDrawingPanel behavior', () => {
[IRenderManagerService, { useClass: TestRenderManagerService as never }],
[IconManager],
[ComponentManager],
- [DrawingImageClipService],
]);
+ currentTestBed.injector.createInstance(UniverDrawingUIPlugin, {}).onStarting();
const drawingManagerService = currentTestBed.get(IDrawingManagerService);
const sheetDrawingService = currentTestBed.get(ISheetDrawingService);
const drawings = [
@@ -194,8 +194,8 @@ describe('SheetDrawingPanel behavior', () => {
[IRenderManagerService, { useClass: TestRenderManagerService as never }],
[IconManager],
[ComponentManager],
- [DrawingImageClipService],
]);
+ currentTestBed.injector.createInstance(UniverDrawingUIPlugin, {}).onStarting();
const drawingManagerService = currentTestBed.get(IDrawingManagerService);
const sheetDrawingService = currentTestBed.get(ISheetDrawingService);
const drawings = [
@@ -240,8 +240,8 @@ describe('SheetDrawingPanel behavior', () => {
[IRenderManagerService, { useClass: TestRenderManagerService as never }],
[IconManager],
[ComponentManager],
- [DrawingImageClipService],
]);
+ currentTestBed.injector.createInstance(UniverDrawingUIPlugin, {}).onStarting();
const drawingManagerService = currentTestBed.get(IDrawingManagerService);
const drawings = [
createSheetDrawing(currentTestBed.unitId, currentTestBed.subUnitId, 'drawing-a', SheetDrawingAnchorType.Position),
diff --git a/packages/sheets-hyper-link-ui/src/commands/operations/__tests__/popup.operations.spec.ts b/packages/sheets-hyper-link-ui/src/commands/operations/__tests__/popup.operations.spec.ts
index 05c3c209b2..a06a10760c 100644
--- a/packages/sheets-hyper-link-ui/src/commands/operations/__tests__/popup.operations.spec.ts
+++ b/packages/sheets-hyper-link-ui/src/commands/operations/__tests__/popup.operations.spec.ts
@@ -19,7 +19,7 @@ import { ICommandService, IUniverInstanceService } from '@univerjs/core';
import { SheetsSelectionsService } from '@univerjs/sheets';
import { IEditorBridgeService } from '@univerjs/sheets-ui';
import { describe, expect, it, vi } from 'vitest';
-import { SheetsHyperLinkPopupService } from '../../../services/popup.service';
+import { ISheetsHyperLinkPopupService } from '../../../services/popup.service';
import { HyperLinkEditSourceType } from '../../../types/enums/edit-source';
import {
CloseHyperLinkPopupOperation,
@@ -72,7 +72,7 @@ describe('hyper-link popup operations', () => {
const startAddEditing = vi.fn();
const startEditing = vi.fn();
const popupService = { startAddEditing, startEditing };
- const accessor = createAccessor([[SheetsHyperLinkPopupService, popupService]]);
+ const accessor = createAccessor([[ISheetsHyperLinkPopupService, popupService]]);
const startAddParams: IOpenHyperLinkEditPanelOperationParams = {
unitId: 'u1',
subUnitId: 's1',
@@ -96,7 +96,7 @@ describe('hyper-link popup operations', () => {
it('closes the popup edit session', () => {
const endEditing = vi.fn();
- const accessor = createAccessor([[SheetsHyperLinkPopupService, { endEditing }]]);
+ const accessor = createAccessor([[ISheetsHyperLinkPopupService, { endEditing }]]);
expect(CloseHyperLinkPopupOperation.handler(accessor)).toBe(true);
expect(endEditing).toHaveBeenCalledTimes(1);
@@ -134,20 +134,20 @@ describe('hyper-link popup operations', () => {
[IUniverInstanceService, createUniverInstanceService({ workbook: createWorkbook(disabledWorksheet) })],
[SheetsSelectionsService, { getCurrentSelections: () => [{ range: { startRow: 1, startColumn: 1 } }] }],
[ICommandService, { executeCommand }],
- [SheetsHyperLinkPopupService, { currentEditing: null }],
+ [ISheetsHyperLinkPopupService, { currentEditing: null }],
]))).toBe(false);
expect(InsertHyperLinkToolbarOperation.handler(createAccessor([
[IUniverInstanceService, createUniverInstanceService({ workbook: createWorkbook(enabledWorksheet) })],
[SheetsSelectionsService, { getCurrentSelections: () => [{ range: { startRow: 1, startColumn: 1 } }] }],
[ICommandService, { executeCommand }],
- [SheetsHyperLinkPopupService, { currentEditing: { row: 1 } }],
+ [ISheetsHyperLinkPopupService, { currentEditing: { row: 1 } }],
]))).toBe(true);
expect(InsertHyperLinkToolbarOperation.handler(createAccessor([
[IUniverInstanceService, createUniverInstanceService({ workbook: createWorkbook(enabledWorksheet) })],
[SheetsSelectionsService, { getCurrentSelections: () => [{ range: { startRow: 1, startColumn: 1 } }] }],
[ICommandService, { executeCommand }],
- [SheetsHyperLinkPopupService, { currentEditing: null }],
+ [ISheetsHyperLinkPopupService, { currentEditing: null }],
]))).toBe(true);
expect(executeCommand).toHaveBeenCalledWith(CloseHyperLinkPopupOperation.id);
diff --git a/packages/sheets-hyper-link-ui/src/commands/operations/popup.operations.ts b/packages/sheets-hyper-link-ui/src/commands/operations/popup.operations.ts
index 368daa23da..25ea11d210 100644
--- a/packages/sheets-hyper-link-ui/src/commands/operations/popup.operations.ts
+++ b/packages/sheets-hyper-link-ui/src/commands/operations/popup.operations.ts
@@ -19,7 +19,7 @@ import type { ISheetCommandSharedParams } from '@univerjs/sheets';
import { CommandType, ICommandService, IUniverInstanceService } from '@univerjs/core';
import { getSheetCommandTarget, SheetsSelectionsService } from '@univerjs/sheets';
import { IEditorBridgeService } from '@univerjs/sheets-ui';
-import { SheetsHyperLinkPopupService } from '../../services/popup.service';
+import { ISheetsHyperLinkPopupService } from '../../services/popup.service';
import { HyperLinkEditSourceType } from '../../types/enums/edit-source';
import { getShouldDisableCurrentCellLink } from '../../utils';
@@ -38,7 +38,7 @@ export const OpenHyperLinkEditPanelOperation: ICommand<IOpenHyperLinkEditPanelOp
return false;
}
- const popupService = accessor.get(SheetsHyperLinkPopupService);
+ const popupService = accessor.get(ISheetsHyperLinkPopupService);
if (!params.customRangeId) {
popupService.startAddEditing(params);
} else {
@@ -52,7 +52,7 @@ export const CloseHyperLinkPopupOperation: ICommand = {
type: CommandType.OPERATION,
id: 'sheet.operation.close-hyper-link-popup',
handler(accessor) {
- const popupService = accessor.get(SheetsHyperLinkPopupService);
+ const popupService = accessor.get(ISheetsHyperLinkPopupService);
popupService.endEditing();
return true;
@@ -97,7 +97,7 @@ export const InsertHyperLinkToolbarOperation: ICommand = {
return false;
}
const commandService = accessor.get(ICommandService);
- const popupService = accessor.get(SheetsHyperLinkPopupService);
+ const popupService = accessor.get(ISheetsHyperLinkPopupService);
if (popupService.currentEditing) {
return commandService.executeCommand(CloseHyperLinkPopupOperation.id);
} else {
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
index 2c0621393b..e53a3507a4 100644
--- 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
@@ -32,7 +32,7 @@ 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 { ISheetsHyperLinkPopupService } from '../../../services/popup.service';
import { SheetsHyperLinkMobilePopupController } from '../popup.controller';
class TestHoverManagerService {
@@ -121,7 +121,7 @@ class TestUniverInstanceService {
function createMobilePopupControllerTestBed() {
const injector = new Injector();
injector.add([HoverManagerService, { useClass: TestHoverManagerService as never }]);
- injector.add([SheetsHyperLinkPopupService, { useClass: TestSheetsHyperLinkPopupService as never }]);
+ injector.add([ISheetsHyperLinkPopupService, { 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 }]);
@@ -134,7 +134,7 @@ function createMobilePopupControllerTestBed() {
return {
hoverManagerService: injector.get(HoverManagerService) as unknown as TestHoverManagerService,
- popupService: injector.get(SheetsHyperLinkPopupService) as unknown as TestSheetsHyperLinkPopupService,
+ popupService: injector.get(ISheetsHyperLinkPopupService) as unknown as TestSheetsHyperLinkPopupService,
univerInstanceService: injector.get(IUniverInstanceService) as unknown as TestUniverInstanceService,
};
}
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
index 7d88f6e723..08ef78960e 100644
--- a/packages/sheets-hyper-link-ui/src/controllers/mobile/popup.controller.ts
+++ b/packages/sheets-hyper-link-ui/src/controllers/mobile/popup.controller.ts
@@ -48,13 +48,13 @@ import {
} from '@univerjs/sheets';
import { HoverManagerService, IEditorBridgeService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
import { map, switchMap } from 'rxjs';
-import { SheetsHyperLinkPopupService } from '../../services/popup.service';
+import { ISheetsHyperLinkPopupService } 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(ISheetsHyperLinkPopupService) private readonly _sheetsHyperLinkPopupService: ISheetsHyperLinkPopupService,
@Inject(IRenderManagerService) private readonly _renderManagerService: IRenderManagerService,
@Inject(IPermissionService) private readonly _permissionService: IPermissionService,
@Inject(SheetPermissionCheckController) private readonly _sheetPermissionCheckController: SheetPermissionCheckController,
diff --git a/packages/sheets-hyper-link-ui/src/controllers/popup.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/popup.controller.ts
index 384f4d3bd9..d683d8bc80 100644
--- a/packages/sheets-hyper-link-ui/src/controllers/popup.controller.ts
+++ b/packages/sheets-hyper-link-ui/src/controllers/popup.controller.ts
@@ -38,13 +38,13 @@ import {
} from '@univerjs/sheets';
import { HoverManagerService, HoverRenderController, IEditorBridgeService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
import { debounceTime, map, switchMap } from 'rxjs';
-import { SheetsHyperLinkPopupService } from '../services/popup.service';
+import { ISheetsHyperLinkPopupService } from '../services/popup.service';
import { HyperLinkEditSourceType } from '../types/enums/edit-source';
export class SheetsHyperLinkPopupController extends Disposable {
constructor(
@Inject(HoverManagerService) private readonly _hoverManagerService: HoverManagerService,
- @Inject(SheetsHyperLinkPopupService) private readonly _sheetsHyperLinkPopupService: SheetsHyperLinkPopupService,
+ @Inject(ISheetsHyperLinkPopupService) private readonly _sheetsHyperLinkPopupService: ISheetsHyperLinkPopupService,
@Inject(IRenderManagerService) private readonly _renderManagerService: IRenderManagerService,
@Inject(IPermissionService) private readonly _permissionService: IPermissionService,
@Inject(SheetPermissionCheckController) private readonly _sheetPermissionCheckController: SheetPermissionCheckController,
diff --git a/packages/sheets-hyper-link-ui/src/mobile-plugin.ts b/packages/sheets-hyper-link-ui/src/mobile-plugin.ts
index 7a356476c1..30992e687f 100644
--- a/packages/sheets-hyper-link-ui/src/mobile-plugin.ts
+++ b/packages/sheets-hyper-link-ui/src/mobile-plugin.ts
@@ -48,7 +48,7 @@ import { SheetsHyperLinkRenderController } from './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 { ISheetsHyperLinkPopupService } 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';
@@ -88,7 +88,6 @@ export class UniverSheetsHyperLinkMobileUIPlugin extends Plugin {
[MobileComponentsController],
[SheetsHyperLinkResolverService],
[ISheetsHyperLinkPopupService, { useClass: SheetsHyperLinkMobilePopupService }],
- [SheetsHyperLinkPopupService, { useExisting: ISheetsHyperLinkPopupService }],
[SheetsHyperLinkSidePanelService],
[SheetsHyperLinkMobilePopupController],
[SheetsHyperLinkUIController],
diff --git a/packages/sheets-hyper-link-ui/src/plugin.ts b/packages/sheets-hyper-link-ui/src/plugin.ts
index 52f68ef87c..eaf111d52d 100644
--- a/packages/sheets-hyper-link-ui/src/plugin.ts
+++ b/packages/sheets-hyper-link-ui/src/plugin.ts
@@ -79,7 +79,6 @@ export class UniverSheetsHyperLinkUIPlugin extends Plugin {
const dependencies: Dependency[] = [
[SheetsHyperLinkResolverService],
[ISheetsHyperLinkPopupService, { useClass: SheetsHyperLinkPopupService }],
- [SheetsHyperLinkPopupService, { useExisting: ISheetsHyperLinkPopupService }],
[SheetsHyperLinkSidePanelService],
[SheetsHyperLinkPopupController],
diff --git a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit.tsx b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit.tsx
index 0d12015110..43302cb087 100644
--- a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit.tsx
@@ -56,7 +56,7 @@ 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 { ISheetsHyperLinkPopupService } from '../services/popup.service';
import { SheetsHyperLinkResolverService } from '../services/resolver.service';
import { SheetsHyperLinkSidePanelService } from '../services/side-panel.service';
import { HyperLinkEditSourceType } from '../types/enums/edit-source';
@@ -73,7 +73,7 @@ export const CellLinkEdit = () => {
const definedNameService = useDependency(IDefinedNamesService);
const editorBridgeService = useDependency(IEditorBridgeService);
const univerInstanceService = useDependency(IUniverInstanceService);
- const popupService = useDependency(SheetsHyperLinkPopupService);
+ const popupService = useDependency(ISheetsHyperLinkPopupService);
const editing = useObservable(popupService.currentEditing$);
const parserService = useDependency(SheetsHyperLinkParserService);
const resolverService = useDependency(SheetsHyperLinkResolverService);
diff --git a/packages/sheets-hyper-link-ui/src/views/CellLinkPopup.tsx b/packages/sheets-hyper-link-ui/src/views/CellLinkPopup.tsx
index 37593abc54..739beeb658 100644
--- a/packages/sheets-hyper-link-ui/src/views/CellLinkPopup.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkPopup.tsx
@@ -28,7 +28,7 @@ import {
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 { ISheetsHyperLinkPopupService } from '../services/popup.service';
import { SheetsHyperLinkResolverService } from '../services/resolver.service';
import { HyperLinkEditSourceType } from '../types/enums/edit-source';
@@ -52,7 +52,7 @@ interface ICellLinkPopupPureProps {
}
export const CellLinkPopupPure = (props: ICellLinkPopupPureProps) => {
- const popupService = useDependency(SheetsHyperLinkPopupService);
+ const popupService = useDependency(ISheetsHyperLinkPopupService);
const commandService = useDependency(ICommandService);
const messageService = useDependency(IMessageService);
const localeService = useDependency(LocaleService);
@@ -197,7 +197,7 @@ export const CellLinkPopupPure = (props: ICellLinkPopupPureProps) => {
};
export const CellLinkPopup = () => {
- const popupService = useDependency(SheetsHyperLinkPopupService);
+ const popupService = useDependency(ISheetsHyperLinkPopupService);
const currentPopup = useObservable(popupService.currentPopup$, popupService.currentPopup);
const univerInstanceService = useDependency(IUniverInstanceService);
diff --git a/packages/sheets-hyper-link-ui/src/views/MobileCellLinkEdit.tsx b/packages/sheets-hyper-link-ui/src/views/MobileCellLinkEdit.tsx
index f97aade7a5..58cd909fd1 100644
--- a/packages/sheets-hyper-link-ui/src/views/MobileCellLinkEdit.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/MobileCellLinkEdit.tsx
@@ -56,7 +56,7 @@ 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 { ISheetsHyperLinkPopupService } from '../services/popup.service';
import { SheetsHyperLinkResolverService } from '../services/resolver.service';
import { SheetsHyperLinkSidePanelService } from '../services/side-panel.service';
import { HyperLinkEditSourceType } from '../types/enums/edit-source';
@@ -73,7 +73,7 @@ export const MobileCellLinkEdit = () => {
const definedNameService = useDependency(IDefinedNamesService);
const editorBridgeService = useDependency(IEditorBridgeService);
const univerInstanceService = useDependency(IUniverInstanceService);
- const popupService = useDependency(SheetsHyperLinkPopupService);
+ const popupService = useDependency(ISheetsHyperLinkPopupService);
const editing = useObservable(popupService.currentEditing$);
const parserService = useDependency(SheetsHyperLinkParserService);
const resolverService = useDependency(SheetsHyperLinkResolverService);
diff --git a/packages/sheets-hyper-link-ui/src/views/MobileCellLinkPopup.tsx b/packages/sheets-hyper-link-ui/src/views/MobileCellLinkPopup.tsx
index 99844a5162..e45b61dbaf 100644
--- a/packages/sheets-hyper-link-ui/src/views/MobileCellLinkPopup.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/MobileCellLinkPopup.tsx
@@ -27,7 +27,7 @@ import {
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 { ISheetsHyperLinkPopupService } from '../services/popup.service';
import { SheetsHyperLinkResolverService } from '../services/resolver.service';
import { HyperLinkEditSourceType } from '../types/enums/edit-source';
@@ -43,7 +43,7 @@ interface IMobileCellLinkPopupPureProps {
}
export function MobileCellLinkPopupPure(props: IMobileCellLinkPopupPureProps) {
- const popupService = useDependency(SheetsHyperLinkPopupService);
+ const popupService = useDependency(ISheetsHyperLinkPopupService);
const commandService = useDependency(ICommandService);
const messageService = useDependency(IMessageService);
const localeService = useDependency(LocaleService);
@@ -143,7 +143,7 @@ export function MobileCellLinkPopupPure(props: IMobileCellLinkPopupPureProps) {
}
export function MobileCellLinkPopup() {
- const popupService = useDependency(SheetsHyperLinkPopupService);
+ const popupService = useDependency(ISheetsHyperLinkPopupService);
const currentPopup = useObservable(popupService.currentPopup$, popupService.currentPopup);
const univerInstanceService = useDependency(IUniverInstanceService);
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 1ce6bc9f8c..956b53316f 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
@@ -58,7 +58,7 @@ import { createRoot } from 'react-dom/client';
import { of } from 'rxjs';
import { afterEach, describe, expect, it } from 'vitest';
import { CloseHyperLinkPopupOperation, OpenHyperLinkEditPanelOperation } from '../../commands/operations/popup.operations';
-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 { HyperLinkEditSourceType } from '../../types/enums/edit-source';
@@ -270,7 +270,7 @@ function createPopupTestBed() {
injector.add([SheetsSelectionsService]);
injector.add([SheetsHyperLinkParserService]);
injector.add([SheetsHyperLinkResolverService]);
- injector.add([SheetsHyperLinkPopupService]);
+ injector.add([ISheetsHyperLinkPopupService, { useClass: SheetsHyperLinkPopupService }]);
injector.add([SheetsHyperLinkSidePanelService]);
const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData(customRange));
@@ -492,7 +492,7 @@ describe('CellLinkEdit', () => {
container.dir = 'rtl';
document.body.appendChild(container);
root = createRoot(container);
- const popupService = currentTestBed.injector.get(SheetsHyperLinkPopupService);
+ const popupService = currentTestBed.injector.get(ISheetsHyperLinkPopupService);
act(() => {
popupService.startAddEditing({
@@ -525,7 +525,7 @@ describe('CellLinkEdit', () => {
container = document.createElement('div');
document.body.appendChild(container);
root = createRoot(container);
- const popupService = currentTestBed.injector.get(SheetsHyperLinkPopupService);
+ const popupService = currentTestBed.injector.get(ISheetsHyperLinkPopupService);
const renderManagerService = currentTestBed.injector.get(IRenderManagerService) as unknown as TestRenderManagerService;
act(() => {
@@ -575,7 +575,7 @@ describe('CellLinkEdit', () => {
container = document.createElement('div');
document.body.appendChild(container);
root = createRoot(container);
- const popupService = currentTestBed.injector.get(SheetsHyperLinkPopupService);
+ const popupService = currentTestBed.injector.get(ISheetsHyperLinkPopupService);
const renderManagerService = currentTestBed.injector.get(IRenderManagerService) as unknown as TestRenderManagerService;
act(() => {
diff --git a/packages/sheets-table-ui/src/commands/operations/mobile/open-table-filter-dialog.operation.ts b/packages/sheets-table-ui/src/commands/operations/mobile/open-table-filter-dialog.operation.ts
new file mode 100644
index 0000000000..185450c926
--- /dev/null
+++ b/packages/sheets-table-ui/src/commands/operations/mobile/open-table-filter-dialog.operation.ts
@@ -0,0 +1,42 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand } from '@univerjs/core';
+import type { IOpenTableFilterPanelOperationParams } from '../open-table-filter-dialog.opration';
+import { CommandType } from '@univerjs/core';
+import { TableManager } from '@univerjs/sheets-table';
+import { SheetsTableMobileComponentController } from '../../../controllers/mobile/sheet-table-component.controller';
+import { OpenTableFilterPanelOperation } from '../open-table-filter-dialog.opration';
+
+export const OpenTableFilterPanelMobileOperation: ICommand<IOpenTableFilterPanelOperationParams> = {
+ type: CommandType.OPERATION,
+ id: OpenTableFilterPanelOperation.id,
+ async handler(accessor, params) {
+ if (!params) {
+ return false;
+ }
+
+ const { row, col, unitId, subUnitId, tableId } = params;
+ const tableManager = accessor.get(TableManager);
+ const componentController = accessor.get(SheetsTableMobileComponentController);
+ if (!tableManager.getTable(unitId, tableId)) {
+ return false;
+ }
+
+ componentController.openOrToggleFilterPanel({ unitId, subUnitId, row, tableId, column: col });
+ return true;
+ },
+};
diff --git a/packages/sheets-table-ui/src/mobile-plugin.ts b/packages/sheets-table-ui/src/mobile-plugin.ts
index 5c5be535b2..dc617deb56 100644
--- a/packages/sheets-table-ui/src/mobile-plugin.ts
+++ b/packages/sheets-table-ui/src/mobile-plugin.ts
@@ -34,14 +34,13 @@ 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 { OpenTableFilterPanelMobileOperation } from './commands/operations/mobile/open-table-filter-dialog.operation';
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';
@@ -86,7 +85,6 @@ export class UniverSheetsTableMobileUIPlugin extends Plugin {
registerDependencies(this._injector, [
[SheetsTableMobileComponentController],
- [SheetsTableComponentController, { useExisting: SheetsTableMobileComponentController }],
[SheetsTableUiService],
[SheetTableMenuController],
[SheetTableThemeUIController],
@@ -129,7 +127,7 @@ export class UniverSheetsTableMobileUIPlugin extends Plugin {
private _initRegisterCommand(): void {
[
- OpenTableFilterPanelOperation,
+ OpenTableFilterPanelMobileOperation,
OpenTableSelectorOperation,
].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));
}
diff --git a/packages/sheets-table-ui/src/views/components/MobileSheetTableFilterPanel.tsx b/packages/sheets-table-ui/src/views/components/MobileSheetTableFilterPanel.tsx
index 4b1e190b68..28e34cd5cc 100644
--- a/packages/sheets-table-ui/src/views/components/MobileSheetTableFilterPanel.tsx
+++ b/packages/sheets-table-ui/src/views/components/MobileSheetTableFilterPanel.tsx
@@ -51,7 +51,7 @@ import {
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 { SheetsTableMobileComponentController } from '../../controllers/mobile/sheet-table-component.controller';
import { SheetsTableUiService } from '../../services/sheets-table-ui.service';
import { FilterByEnum } from '../../types';
import { MobileSheetTableColorFilterPanel } from './MobileSheetTableColorFilterPanel';
@@ -66,7 +66,7 @@ const FILTER_BY_OPTIONS: Array<{ label: LocaleKey; value: FilterByEnum }> = [
];
export function MobileSheetTableFilterPanel() {
- const sheetsTableComponentController = useDependency(SheetsTableComponentController);
+ const sheetsTableComponentController = useDependency(SheetsTableMobileComponentController);
const tableFilterPanelInfo = sheetsTableComponentController.getCurrentTableFilterInfo();
if (!tableFilterPanelInfo) {
return null;
@@ -87,7 +87,7 @@ function MobileSheetTableFilterPanelContent(props: IMobileSheetTableFilterPanelC
const commandService = useDependency(ICommandService);
const permissionService = useDependency(IPermissionService);
const undoRedoService = useDependency(IUndoRedoService);
- const sheetsTableComponentController = useDependency(SheetsTableComponentController);
+ const sheetsTableComponentController = useDependency(SheetsTableMobileComponentController);
const [detailFilterBy, setDetailFilterBy] = useState<FilterByEnum | null>(null);
const [drawerSnap, setDrawerSnap] = useState<MobileDrawerSnap>('expanded');
const layerRef = useRef<HTMLDivElement>(null);
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 9ca4540341..23eedc5c21 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
@@ -72,6 +72,7 @@ import { act, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { Subject } from 'rxjs';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import { SheetsTableMobileComponentController } from '../../../controllers/mobile/sheet-table-component.controller';
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';
@@ -96,6 +97,15 @@ class TestComponentController extends SheetsTableComponentController {
}
}
+class TestMobileComponentController extends SheetsTableMobileComponentController {
+ closeCount = 0;
+
+ override closeFilterPanel(): void {
+ this.closeCount += 1;
+ super.closeFilterPanel();
+ }
+}
+
class TestSheetCanvasPopManagerService {
attachPopupToCell(): IDisposable {
return toDisposable(() => {});
@@ -487,6 +497,7 @@ function createTestBed(): ITestBed {
[SheetCanvasPopManagerService, { useClass: TestSheetCanvasPopManagerService }],
[IDialogService, { useClass: TestDialogService }],
[SheetsTableComponentController, { useClass: TestComponentController }],
+ [SheetsTableMobileComponentController, { useClass: TestMobileComponentController }],
];
dependencies.forEach((dependency) => this._injector.add(dependency));
}
@@ -996,7 +1007,7 @@ describe('sheet table view components', () => {
it('shows table actions before opening a mobile filter detail drawer', () => {
testBed = createTestBed();
- const componentController = testBed.injector.get(SheetsTableComponentController) as TestComponentController;
+ const componentController = testBed.injector.get(SheetsTableMobileComponentController) as TestMobileComponentController;
componentController.setCurrentTableFilterInfo({
unitId: testBed.workbook.getUnitId(),
subUnitId: 'sheet1',
@@ -1056,7 +1067,7 @@ describe('sheet table view components', () => {
it('applies a table color filter from the mobile detail drawer', async () => {
testBed = createTestBed();
- const componentController = testBed.injector.get(SheetsTableComponentController) as TestComponentController;
+ const componentController = testBed.injector.get(SheetsTableMobileComponentController) as TestMobileComponentController;
componentController.setCurrentTableFilterInfo({
unitId: testBed.workbook.getUnitId(),
subUnitId: 'sheet1',
@@ -1092,7 +1103,7 @@ describe('sheet table view components', () => {
filterType: TableColumnFilterTypeEnum.manual,
values: ['book'],
});
- const componentController = testBed.injector.get(SheetsTableComponentController) as TestComponentController;
+ const componentController = testBed.injector.get(SheetsTableMobileComponentController) as TestMobileComponentController;
componentController.setCurrentTableFilterInfo({
unitId: testBed.workbook.getUnitId(),
subUnitId: 'sheet1',
@@ -1119,7 +1130,7 @@ describe('sheet table view components', () => {
it('undoes the mobile table sort state together with the reordered rows', async () => {
testBed = createTestBed();
- const componentController = testBed.injector.get(SheetsTableComponentController) as TestComponentController;
+ const componentController = testBed.injector.get(SheetsTableMobileComponentController) as TestMobileComponentController;
const unitId = testBed.workbook.getUnitId();
const worksheet = testBed.workbook.getSheetBySheetId('sheet1')!;
testBed.injector.get(IUniverInstanceService).focusUnit(unitId);
diff --git a/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-scroll.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-scroll.render-controller.ts
index 8210be12c3..614882f29a 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-scroll.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-scroll.render-controller.ts
@@ -29,8 +29,9 @@ import {
RANGE_TYPE,
toDisposable,
} from '@univerjs/core';
-import { IRenderManagerService, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
+import { DeviceType, IRenderManagerService, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
import { ScrollToCellOperation, SheetsSelectionsService } from '@univerjs/sheets';
+import { MobileZoomIndicator } from '@univerjs/ui';
import { ScrollCommand, SetScrollRelativeCommand } from '../../../commands/commands/set-scroll.command';
import { ExpandSelectionCommand, MoveSelectionCommand, MoveSelectionEnterAndTabCommand } from '../../../commands/commands/set-selection.command';
import { SetZoomRatioCommand } from '../../../commands/commands/set-zoom-ratio.command';
@@ -533,7 +534,7 @@ export class MobileSheetsScrollRenderController extends Disposable implements IR
let pinchSheetPos: { x: number; y: number } | null = null;
// Create zoom indicator overlay
- const zoomIndicator = this._createZoomIndicator(canvasElement);
+ const zoomIndicator = new MobileZoomIndicator(canvasElement);
/**
* Convert touch event to offset coordinates relative to canvas
@@ -754,7 +755,7 @@ export class MobileSheetsScrollRenderController extends Disposable implements IR
initializePinchZoom(touch1, touch2);
// Show zoom indicator
- this._showZoomIndicator(zoomIndicator, Math.round(initialZoomRatio * 100));
+ zoomIndicator.show(Math.round(initialZoomRatio * 100));
e.preventDefault();
return;
@@ -778,7 +779,7 @@ export class MobileSheetsScrollRenderController extends Disposable implements IR
// A drawing, selection handle, or another canvas overlay owns this gesture.
// Native touch listeners bypass the render event propagation chain, so the
// sheet scroller must explicitly yield to the picked overlay object.
- const pickedObject = scene.pick(Vector2.FromArray([offsetX, offsetY]));
+ const pickedObject = scene.pick(Vector2.FromArray([offsetX, offsetY]), DeviceType.Touch);
if (pickedObject && pickedObject !== spreadsheet) return;
lastTouchPos.x = offsetX;
@@ -834,7 +835,7 @@ export class MobileSheetsScrollRenderController extends Disposable implements IR
applyZoomWithFocus(newZoomRatio, currentZoom);
// Update zoom indicator
- this._showZoomIndicator(zoomIndicator, Math.round(newZoomRatio * 100));
+ zoomIndicator.show(Math.round(newZoomRatio * 100));
}
e.preventDefault();
@@ -929,7 +930,7 @@ export class MobileSheetsScrollRenderController extends Disposable implements IR
cancelInertiaAnimation();
velocityHistory.length = 0;
// Hide zoom indicator with delay
- this._hideZoomIndicator(zoomIndicator);
+ zoomIndicator.hide();
}
return;
}
@@ -984,7 +985,7 @@ export class MobileSheetsScrollRenderController extends Disposable implements IR
pinchCenterCellInfo = null;
pinchStartScrollPos = null;
pinchSheetPos = null;
- this._hideZoomIndicator(zoomIndicator);
+ zoomIndicator.hide();
}
if (_touchScrolling) {
_touchScrolling = false;
@@ -1006,10 +1007,7 @@ export class MobileSheetsScrollRenderController extends Disposable implements IR
canvasElement.removeEventListener('touchmove', handleTouchMove);
canvasElement.removeEventListener('touchend', handleTouchEnd);
canvasElement.removeEventListener('touchcancel', handleTouchCancel);
- // Remove zoom indicator
- if (zoomIndicator && zoomIndicator.parentElement) {
- zoomIndicator.parentElement.removeChild(zoomIndicator);
- }
+ zoomIndicator.dispose();
}));
// Note: We intentionally do NOT add handleScrollEnd listeners for onPointerLeave$/onPointerOut$
@@ -1018,67 +1016,6 @@ export class MobileSheetsScrollRenderController extends Disposable implements IR
// This fixes the issue where scrolling would stop when finger moves over row/column headers.
}
- /**
- * Create zoom indicator overlay element
- */
- private _createZoomIndicator(canvasElement: HTMLCanvasElement): HTMLDivElement {
- const container = canvasElement.parentElement;
- if (!container) {
- // Fallback: create a detached element
- const div = document.createElement('div');
- div.style.display = 'none';
- return div;
- }
-
- const indicator = document.createElement('div');
- indicator.style.cssText = `
- position: absolute;
- top: 50%;
- left: 50%;
- transform: translate(-50%, -50%);
- background-color: rgba(0, 0, 0, 0.7);
- color: white;
- padding: 12px 24px;
- border-radius: 8px;
- font-size: 24px;
- font-weight: bold;
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
- pointer-events: none;
- opacity: 0;
- transition: opacity 0.15s ease-in-out;
- z-index: 10000;
- user-select: none;
- -webkit-user-select: none;
- `;
-
- // Ensure container has relative positioning for absolute child
- const containerPosition = window.getComputedStyle(container).position;
- if (containerPosition === 'static') {
- container.style.position = 'relative';
- }
-
- container.appendChild(indicator);
- return indicator;
- }
-
- /**
- * Show zoom indicator with percentage
- */
- private _showZoomIndicator(indicator: HTMLDivElement, percentage: number): void {
- indicator.textContent = `${percentage}%`;
- indicator.style.opacity = '1';
- }
-
- /**
- * Hide zoom indicator with fade out
- */
- private _hideZoomIndicator(indicator: HTMLDivElement): void {
- // Delay hiding to show final zoom value briefly
- setTimeout(() => {
- indicator.style.opacity = '0';
- }, 300);
- }
-
private _updateSceneSize(param: ISheetSkeletonManagerParam) {
if (param == null) {
return;
diff --git a/packages/thread-comment-ui/src/locale/ar-SA.ts b/packages/thread-comment-ui/src/locale/ar-SA.ts
index e34bb42566..3a058e0f4c 100644
--- a/packages/thread-comment-ui/src/locale/ar-SA.ts
+++ b/packages/thread-comment-ui/src/locale/ar-SA.ts
@@ -18,7 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'thread-comment-ui': {
+ mobile: { back: 'رجوع' },
panel: {
+ title: 'إدارة التعليقات',
empty: 'لا توجد تعليقات بعد',
reset: 'إعادة ضبط التصفية',
addComment: 'إضافة تعليق',
diff --git a/packages/thread-comment-ui/src/locale/ca-ES.ts b/packages/thread-comment-ui/src/locale/ca-ES.ts
index 44a5b0d97b..b9141fe9ec 100644
--- a/packages/thread-comment-ui/src/locale/ca-ES.ts
+++ b/packages/thread-comment-ui/src/locale/ca-ES.ts
@@ -18,7 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'thread-comment-ui': {
+ mobile: { back: 'Enrere' },
panel: {
+ title: 'Gestió de comentaris',
empty: 'Encara no hi ha comentaris',
reset: 'Restableix el filtre',
addComment: 'Afegeix un comentari',
diff --git a/packages/thread-comment-ui/src/locale/de-DE.ts b/packages/thread-comment-ui/src/locale/de-DE.ts
index 57cf80ccf0..288f0d99f2 100644
--- a/packages/thread-comment-ui/src/locale/de-DE.ts
+++ b/packages/thread-comment-ui/src/locale/de-DE.ts
@@ -18,7 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'thread-comment-ui': {
+ mobile: { back: 'Zurück' },
panel: {
+ title: 'Kommentarverwaltung',
empty: 'Noch keine Kommentare',
reset: 'Filter zurücksetzen',
addComment: 'Kommentar hinzufügen',
diff --git a/packages/thread-comment-ui/src/locale/en-US.ts b/packages/thread-comment-ui/src/locale/en-US.ts
index baa858f0e6..f310e12c06 100644
--- a/packages/thread-comment-ui/src/locale/en-US.ts
+++ b/packages/thread-comment-ui/src/locale/en-US.ts
@@ -16,7 +16,9 @@
const locale = {
'thread-comment-ui': {
+ mobile: { back: 'Back' },
panel: {
+ title: 'Comment Management',
empty: 'No comments yet',
reset: 'Reset Filter',
addComment: 'Add Comment',
diff --git a/packages/thread-comment-ui/src/locale/es-ES.ts b/packages/thread-comment-ui/src/locale/es-ES.ts
index 72ed80f9db..e2d18e2caa 100644
--- a/packages/thread-comment-ui/src/locale/es-ES.ts
+++ b/packages/thread-comment-ui/src/locale/es-ES.ts
@@ -18,7 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'thread-comment-ui': {
+ mobile: { back: 'Atrás' },
panel: {
+ title: 'Gestión de comentarios',
empty: 'Aún no hay comentarios',
reset: 'Restablecer filtro',
addComment: 'Añadir comentario',
diff --git a/packages/thread-comment-ui/src/locale/fa-IR.ts b/packages/thread-comment-ui/src/locale/fa-IR.ts
index 75c5d40c78..fdbe21de39 100644
--- a/packages/thread-comment-ui/src/locale/fa-IR.ts
+++ b/packages/thread-comment-ui/src/locale/fa-IR.ts
@@ -18,7 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'thread-comment-ui': {
+ mobile: { back: 'بازگشت' },
panel: {
+ title: 'مدیریت نظرات',
empty: 'هنوز نظری وجود ندارد',
reset: 'بازنشانی فیلتر',
addComment: 'افزودن نظر',
diff --git a/packages/thread-comment-ui/src/locale/fr-FR.ts b/packages/thread-comment-ui/src/locale/fr-FR.ts
index 2512290310..b810e3c881 100644
--- a/packages/thread-comment-ui/src/locale/fr-FR.ts
+++ b/packages/thread-comment-ui/src/locale/fr-FR.ts
@@ -18,7 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'thread-comment-ui': {
+ mobile: { back: 'Retour' },
panel: {
+ title: 'Gestion des commentaires',
empty: 'Pas encore de commentaires',
reset: 'Réinitialiser le filtre',
addComment: 'Ajouter un commentaire',
diff --git a/packages/thread-comment-ui/src/locale/id-ID.ts b/packages/thread-comment-ui/src/locale/id-ID.ts
index 14093fe6a9..c7b65b90fe 100644
--- a/packages/thread-comment-ui/src/locale/id-ID.ts
+++ b/packages/thread-comment-ui/src/locale/id-ID.ts
@@ -18,7 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'thread-comment-ui': {
+ mobile: { back: 'Kembali' },
panel: {
+ title: 'Manajemen Komentar',
empty: 'Belum ada komentar',
reset: 'Atur Ulang Filter',
addComment: 'Tambah Komentar',
diff --git a/packages/thread-comment-ui/src/locale/it-IT.ts b/packages/thread-comment-ui/src/locale/it-IT.ts
index 2dc5d3faf2..46fc131e22 100644
--- a/packages/thread-comment-ui/src/locale/it-IT.ts
+++ b/packages/thread-comment-ui/src/locale/it-IT.ts
@@ -18,7 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'thread-comment-ui': {
+ mobile: { back: 'Indietro' },
panel: {
+ title: 'Gestione Commenti',
empty: 'Nessun commento',
reset: 'Reimposta filtro',
addComment: 'Aggiungi commento',
diff --git a/packages/thread-comment-ui/src/locale/ja-JP.ts b/packages/thread-comment-ui/src/locale/ja-JP.ts
index c8af2fff35..ab63d4627b 100644
--- a/packages/thread-comment-ui/src/locale/ja-JP.ts
+++ b/packages/thread-comment-ui/src/locale/ja-JP.ts
@@ -18,7 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'thread-comment-ui': {
+ mobile: { back: '戻る' },
panel: {
+ title: 'コメント管理',
empty: 'まだコメントはありません',
reset: 'フィルタをリセット',
addComment: 'コメントを追加',
diff --git a/packages/thread-comment-ui/src/locale/ko-KR.ts b/packages/thread-comment-ui/src/locale/ko-KR.ts
index b0893d4c10..173fb8e75e 100644
--- a/packages/thread-comment-ui/src/locale/ko-KR.ts
+++ b/packages/thread-comment-ui/src/locale/ko-KR.ts
@@ -18,7 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'thread-comment-ui': {
+ mobile: { back: '뒤로' },
panel: {
+ title: '댓글 관리',
empty: '아직 댓글이 없습니다',
reset: '필터 초기화',
addComment: '댓글 추가',
diff --git a/packages/thread-comment-ui/src/locale/pl-PL.ts b/packages/thread-comment-ui/src/locale/pl-PL.ts
index deffe04605..c0f3daf1e3 100644
--- a/packages/thread-comment-ui/src/locale/pl-PL.ts
+++ b/packages/thread-comment-ui/src/locale/pl-PL.ts
@@ -18,7 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'thread-comment-ui': {
+ mobile: { back: 'Wstecz' },
panel: {
+ title: 'Zarządzanie komentarzami',
empty: 'Brak komentarzy',
reset: 'Resetuj filtr',
addComment: 'Dodaj komentarz',
diff --git a/packages/thread-comment-ui/src/locale/pt-BR.ts b/packages/thread-comment-ui/src/locale/pt-BR.ts
index f151d4efef..7cbc878a5c 100644
--- a/packages/thread-comment-ui/src/locale/pt-BR.ts
+++ b/packages/thread-comment-ui/src/locale/pt-BR.ts
@@ -18,7 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'thread-comment-ui': {
+ mobile: { back: 'Voltar' },
panel: {
+ title: 'Gerenciamento de Comentários',
empty: 'Nenhum comentário ainda',
reset: 'Redefinir Filtro',
addComment: 'Adicionar Comentário',
diff --git a/packages/thread-comment-ui/src/locale/ru-RU.ts b/packages/thread-comment-ui/src/locale/ru-RU.ts
index 8b05abb544..87cf90dabc 100644
--- a/packages/thread-comment-ui/src/locale/ru-RU.ts
+++ b/packages/thread-comment-ui/src/locale/ru-RU.ts
@@ -18,7 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'thread-comment-ui': {
+ mobile: { back: 'Назад' },
panel: {
+ title: 'Управление комментариями',
empty: 'Комментариев пока нет',
reset: 'Сбросить фильтр',
addComment: 'Добавить комментарий',
diff --git a/packages/thread-comment-ui/src/locale/sk-SK.ts b/packages/thread-comment-ui/src/locale/sk-SK.ts
index b5474219e8..1120c41cc4 100644
--- a/packages/thread-comment-ui/src/locale/sk-SK.ts
+++ b/packages/thread-comment-ui/src/locale/sk-SK.ts
@@ -18,7 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'thread-comment-ui': {
+ mobile: { back: 'Späť' },
panel: {
+ title: 'Správa komentárov',
empty: 'Zatiaľ žiadne komentáre',
reset: 'Obnoviť filter',
addComment: 'Pridať komentár',
diff --git a/packages/thread-comment-ui/src/locale/vi-VN.ts b/packages/thread-comment-ui/src/locale/vi-VN.ts
index 7f0f54f1fc..1f14045ae0 100644
--- a/packages/thread-comment-ui/src/locale/vi-VN.ts
+++ b/packages/thread-comment-ui/src/locale/vi-VN.ts
@@ -18,7 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'thread-comment-ui': {
+ mobile: { back: 'Quay lại' },
panel: {
+ title: 'Quản lý Bình luận',
empty: 'Chưa có bình luận',
reset: 'Đặt lại',
addComment: 'Thêm bình luận',
diff --git a/packages/thread-comment-ui/src/locale/zh-CN.ts b/packages/thread-comment-ui/src/locale/zh-CN.ts
index 17ad672230..0606867e9d 100644
--- a/packages/thread-comment-ui/src/locale/zh-CN.ts
+++ b/packages/thread-comment-ui/src/locale/zh-CN.ts
@@ -18,7 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'thread-comment-ui': {
+ mobile: { back: '返回' },
panel: {
+ title: '评论管理',
empty: '暂无评论',
reset: '重置',
addComment: '添加评论',
diff --git a/packages/thread-comment-ui/src/locale/zh-HK.ts b/packages/thread-comment-ui/src/locale/zh-HK.ts
index e6cffc436c..038d44db2b 100644
--- a/packages/thread-comment-ui/src/locale/zh-HK.ts
+++ b/packages/thread-comment-ui/src/locale/zh-HK.ts
@@ -18,7 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'thread-comment-ui': {
+ mobile: { back: '返回' },
panel: {
+ title: '評論管理',
empty: '暫無評論',
reset: '重置',
addComment: '新增評論',
diff --git a/packages/thread-comment-ui/src/locale/zh-TW.ts b/packages/thread-comment-ui/src/locale/zh-TW.ts
index e6cffc436c..038d44db2b 100644
--- a/packages/thread-comment-ui/src/locale/zh-TW.ts
+++ b/packages/thread-comment-ui/src/locale/zh-TW.ts
@@ -18,7 +18,9 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'thread-comment-ui': {
+ mobile: { back: '返回' },
panel: {
+ title: '評論管理',
empty: '暫無評論',
reset: '重置',
addComment: '新增評論',
diff --git a/packages/thread-comment-ui/src/views/ThreadCommentPanel.tsx b/packages/thread-comment-ui/src/views/ThreadCommentPanel.tsx
index e1e6707c3c..49beea5940 100644
--- a/packages/thread-comment-ui/src/views/ThreadCommentPanel.tsx
+++ b/packages/thread-comment-ui/src/views/ThreadCommentPanel.tsx
@@ -50,9 +50,6 @@ export interface IThreadCommentPanelProps {
formatRef?: (comment: IThreadComment) => string;
onTempCommentClose?: () => void;
autoFocusActiveComment?: boolean;
- ActionRowComponent?: typeof ActionRow;
- SelectComponent?: typeof Select;
- ThreadCommentTreeComponent?: typeof ThreadCommentTree;
}
interface IThreadCommentWithUsers extends IThreadComment {
@@ -79,9 +76,6 @@ export const ThreadCommentPanel = (props: IThreadCommentPanelProps) => {
formatRef,
onTempCommentClose,
autoFocusActiveComment = false,
- ActionRowComponent = ActionRow,
- SelectComponent = Select,
- ThreadCommentTreeComponent = ThreadCommentTree,
} = props;
const [unit, setUnit] = useState('all');
const [status, setStatus] = useState('all');
@@ -221,7 +215,7 @@ export const ThreadCommentPanel = (props: IThreadCommentPanelProps) => {
}, [activeCommentId, location]);
const renderComment = (section: ThreadCommentPanelSection) => (comment: IThreadComment, index: number) => (
- <ThreadCommentTreeComponent
+ <ThreadCommentTree
full
location={location}
getSubUnitName={getSubUnitName}
@@ -279,7 +273,7 @@ export const ThreadCommentPanel = (props: IThreadCommentPanelProps) => {
<div className="univer-mt-3 univer-flex univer-flex-row univer-justify-between">
{type === UniverInstanceType.UNIVER_SHEET
? (
- <SelectComponent
+ <Select
borderless
value={unit}
options={[
@@ -296,7 +290,7 @@ export const ThreadCommentPanel = (props: IThreadCommentPanelProps) => {
/>
)
: null}
- <SelectComponent
+ <Select
borderless
value={status}
options={[
@@ -332,22 +326,22 @@ export const ThreadCommentPanel = (props: IThreadCommentPanelProps) => {
{localeService.t<LocaleKey>('thread-comment-ui.panel.empty')}
{isFiltering
? (
- <ActionRowComponent className="univer-mt-2 univer-flex univer-flex-row">
+ <ActionRow className="univer-mt-2 univer-flex univer-flex-row">
<Button onClick={onReset}>
{localeService.t<LocaleKey>('thread-comment-ui.panel.reset')}
</Button>
- </ActionRowComponent>
+ </ActionRow>
)
: !disableAdd
? (
- <ActionRowComponent
+ <ActionRow
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>
- </ActionRowComponent>
+ </ActionRow>
)
: null}
</div>
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 abbbac091a..5297a2ca7c 100644
--- a/packages/thread-comment-ui/src/views/__tests__/ThreadCommentPanel.spec.tsx
+++ b/packages/thread-comment-ui/src/views/__tests__/ThreadCommentPanel.spec.tsx
@@ -19,7 +19,6 @@ 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,
@@ -64,6 +63,7 @@ import { BehaviorSubject, Subject } from 'rxjs';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { SetActiveCommentOperation } from '../../commands/operations/comment.operations';
import { ThreadCommentPanelService } from '../../services/thread-comment-panel.service';
+import { MobileThreadCommentPanel } from '../mobile/MobileThreadCommentPanel';
import { transformTextNodes2Document } from '../thread-comment-editor/util';
import { ThreadCommentPanel } from '../ThreadCommentPanel';
@@ -72,13 +72,6 @@ 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;
data: IDocumentData;
@@ -449,7 +442,6 @@ describe('ThreadCommentPanel', () => {
beforeEach(() => {
document.body.innerHTML = '';
- renderedTreeProps = [];
});
afterEach(() => {
@@ -497,7 +489,7 @@ 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', () => {
+ it('auto-focuses the active comment when requested by the host panel', async () => {
const testBed = createPanelTestBed();
addRootComment(testBed.threadCommentModel, createComment({ id: 'comment-1', ref: 'A1' }));
testBed.panelService.setActiveComment({
@@ -515,11 +507,42 @@ describe('ThreadCommentPanel', () => {
onAdd={() => undefined}
getSubUnitName={(subUnitId) => subUnitId}
autoFocusActiveComment
- ThreadCommentTreeComponent={TestThreadCommentTree}
/>
));
- expect(renderedTreeProps.find((props) => props.id === 'comment-1')?.autoFocus).toBe(true);
+ await vi.waitFor(() => {
+ expect((testBed.injector.get(IEditorService) as unknown as TestEditorService).getFocusId()).toBeTruthy();
+ });
+ });
+
+ it('renders and closes the active comment in the mobile detail view', () => {
+ 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,
+ <MobileThreadCommentPanel
+ unitId={UNIT_ID}
+ subUnitId$={new BehaviorSubject<string | undefined>(SHEET_ID)}
+ type={UniverInstanceType.UNIVER_SHEET}
+ onAdd={() => undefined}
+ getSubUnitName={(subUnitId) => subUnitId}
+ />
+ ));
+
+ const backButton = container.querySelector<HTMLButtonElement>('[aria-label="thread-comment-ui.mobile.back"]');
+ expect(backButton).not.toBeNull();
+ expect(container.textContent).not.toContain('thread-comment-ui.filter.status.all');
+
+ act(() => backButton!.click());
+
+ expect(testBed.panelService.activeCommentId).toBeUndefined();
+ expect(container.textContent).toContain('thread-comment-ui.filter.status.all');
});
it('keeps an empty-id temporary target active and shows its editor', () => {
diff --git a/packages/thread-comment-ui/src/views/mobile/MobileThreadCommentPanel.tsx b/packages/thread-comment-ui/src/views/mobile/MobileThreadCommentPanel.tsx
index b8a2864503..5c91a0682e 100644
--- a/packages/thread-comment-ui/src/views/mobile/MobileThreadCommentPanel.tsx
+++ b/packages/thread-comment-ui/src/views/mobile/MobileThreadCommentPanel.tsx
@@ -14,18 +14,371 @@
* limitations under the License.
*/
+import type { ISelectProps } from '@univerjs/design';
+import type { IThreadComment } from '@univerjs/thread-comment';
+import type { LocaleKey } from '../../locale/types';
+import type { ThreadCommentPanelSection } from '../thread-comment-panel/util';
import type { IThreadCommentPanelProps } from '../ThreadCommentPanel';
-import { MobileActionRowGroup, MobileSelect } from '@univerjs/design';
-import { ThreadCommentPanel } from '../ThreadCommentPanel';
+import { ICommandService, LocaleService, UniverInstanceType, UserManagerService } from '@univerjs/core';
+import { Button, clsx, MobileActionRowGroup, resetButtonClassName } from '@univerjs/design';
+import { IncreaseIcon, MoreLeftIcon } from '@univerjs/icons';
+import { ThreadCommentModel } from '@univerjs/thread-comment';
+import { useDependency, useObservable } from '@univerjs/ui';
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { SetActiveCommentOperation } from '../../commands/operations/comment.operations';
+import { ThreadCommentPanelService } from '../../services/thread-comment-panel.service';
+import { getThreadCommentPanelItemKey, isSameThreadCommentTarget, shouldClearThreadCommentTarget } from '../thread-comment-panel/util';
+import { ThreadCommentTreeLocation } from '../ThreadCommentTree';
import { MobileThreadCommentTree } from './MobileThreadCommentTree';
-export function MobileThreadCommentPanel(props: IThreadCommentPanelProps) {
+interface IThreadCommentWithUsers extends IThreadComment {
+ users: Set<string>;
+}
+
+function MobileCommentFilter({ value, options = [], onChange }: ISelectProps) {
+ return (
+ <div
+ className="
+ univer-flex univer-gap-1 univer-overflow-x-auto univer-rounded-xl univer-bg-gray-100 univer-p-1
+ dark:!univer-bg-gray-800
+ "
+ >
+ {options.flatMap((option) => option.options ?? [option]).map((option) => (
+ <button
+ key={option.value}
+ type="button"
+ aria-pressed={option.value === value}
+ className={clsx(resetButtonClassName, `
+ univer-h-10 univer-shrink-0 univer-rounded-lg univer-px-3 univer-text-sm univer-text-gray-700
+ active:univer-scale-95
+ dark:!univer-text-gray-200
+ `, option.value === value && `
+ univer-bg-gray-0 univer-font-medium univer-text-primary-600 univer-shadow-sm
+ dark:!univer-bg-gray-700 dark:!univer-text-primary-300
+ `)}
+ onClick={() => option.value != null && onChange?.(option.value)}
+ >
+ {option.label}
+ </button>
+ ))}
+ </div>
+ );
+}
+
+function MobileCommentHeader({ comment: activeComment, displayRef }: { comment: IThreadComment; displayRef?: string }) {
+ const localeService = useDependency(LocaleService);
+ const commandService = useDependency(ICommandService);
return (
- <ThreadCommentPanel
- {...props}
- ActionRowComponent={MobileActionRowGroup}
- SelectComponent={MobileSelect}
- ThreadCommentTreeComponent={MobileThreadCommentTree}
+ <div
+ className="
+ univer-mt-2 univer-flex univer-min-h-12 univer-items-center univer-gap-2 univer-border-0 univer-border-b
+ univer-border-solid univer-border-gray-200 univer-pb-2
+ dark:!univer-border-gray-700
+ "
+ >
+ <button
+ type="button"
+ aria-label={localeService.t<LocaleKey>('thread-comment-ui.mobile.back')}
+ className={`
+ ${resetButtonClassName}
+ univer-flex univer-size-12 univer-shrink-0 univer-items-center univer-justify-center univer-rounded-xl
+ univer-text-2xl univer-text-gray-700
+ active:univer-bg-gray-100
+ dark:!univer-text-gray-200
+ dark:active:!univer-bg-gray-700
+ `}
+ onClick={() => commandService.executeCommand(SetActiveCommentOperation.id)}
+ >
+ <MoreLeftIcon />
+ </button>
+ <div className="univer-min-w-0 univer-flex-1">
+ <div
+ className="
+ univer-truncate univer-text-base univer-font-semibold univer-text-gray-900
+ dark:!univer-text-gray-0
+ "
+ >
+ {localeService.t<LocaleKey>('thread-comment-ui.panel.title')}
+ </div>
+ {activeComment.ref && (
+ <div
+ className="
+ univer-truncate univer-text-xs univer-text-gray-500
+ dark:!univer-text-gray-400
+ "
+ >
+ {displayRef ?? activeComment.ref}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function MobileAddComment({ onAdd }: { onAdd: () => void }) {
+ const localeService = useDependency(LocaleService);
+ return (
+ <MobileActionRowGroup className="univer-mt-3">
+ <Button className="univer-w-full" onClick={onAdd}>
+ <IncreaseIcon className="univer-mr-1.5" />
+ {localeService.t<LocaleKey>('thread-comment-ui.panel.addComment')}
+ </Button>
+ </MobileActionRowGroup>
+ );
+}
+
+export function MobileThreadCommentPanel(props: IThreadCommentPanelProps) {
+ const {
+ unitId,
+ subUnitId$,
+ type,
+ onAdd,
+ getSubUnitName,
+ onResolve,
+ sortComments,
+ onItemLeave,
+ onItemEnter,
+ disableAdd,
+ tempComment,
+ onAddComment,
+ onDeleteComment,
+ onAfterDeleteComment,
+ showComments,
+ formatRef,
+ onTempCommentClose,
+ autoFocusActiveComment = false,
+ } = props;
+ const [unit, setUnit] = useState('all');
+ const [status, setStatus] = useState('all');
+ const localeService = useDependency(LocaleService);
+ const userService = useDependency(UserManagerService);
+ const threadCommentModel = useDependency(ThreadCommentModel);
+ const panelService = useDependency(ThreadCommentPanelService);
+ const commandService = useDependency(ICommandService);
+ const activeCommentId = useObservable(panelService.activeCommentId$);
+ useObservable(threadCommentModel.commentUpdate$);
+ const subUnitId = useObservable(subUnitId$);
+ const currentUser = useObservable(userService.currentUser$);
+ const shouldScrollRef = useRef(true);
+ const location = ThreadCommentTreeLocation.PANEL;
+ const unitComments = threadCommentModel.getUnit(unitId);
+ const scopedTempComment = tempComment?.unitId === unitId ? tempComment : null;
+ const activeExists = activeCommentId
+ ? Boolean(
+ threadCommentModel.getComment(activeCommentId.unitId, activeCommentId.subUnitId, activeCommentId.commentId) ||
+ (scopedTempComment && isSameThreadCommentTarget(activeCommentId, scopedTempComment))
+ )
+ : false;
+ const shouldClearActiveTarget = shouldClearThreadCommentTarget(activeCommentId, unitId, activeExists);
+ const comments = useMemo(() => {
+ const allComments = unit === 'all' && type !== UniverInstanceType.UNIVER_SLIDE
+ ? unitComments
+ : unitComments.filter((comment) => comment.subUnitId === subUnitId);
+ const sortedComments = sortComments ?? ((commentList) => commentList);
+ const result: IThreadCommentWithUsers[] = allComments.map((comment) => ({
+ ...comment.root,
+ children: comment.children ?? [],
+ users: comment.relativeUsers,
+ }));
+
+ if (!showComments) {
+ return sortedComments(result) as IThreadCommentWithUsers[];
+ }
+
+ const commentMap = new Map(result.map((comment) => [comment.id, comment]));
+ return [...showComments, ''].map((id) => commentMap.get(id)).filter(Boolean) as IThreadCommentWithUsers[];
+ }, [showComments, sortComments, subUnitId, type, unit, unitComments]);
+ const commentsSorted = useMemo(() => [
+ ...comments.filter((comment) => !comment.resolved),
+ ...comments.filter((comment) => comment.resolved),
+ ], [comments]);
+ const statusComments = useMemo(() => {
+ if (status === 'resolved') {
+ return commentsSorted.filter((comment) => comment.resolved);
+ }
+ if (status === 'unsolved') {
+ return commentsSorted.filter((comment) => !comment.resolved);
+ }
+ if (status === 'concern_me' && currentUser?.userID) {
+ return commentsSorted.filter((comment) => comment.users.has(currentUser.userID));
+ }
+ return commentsSorted;
+ }, [commentsSorted, currentUser?.userID, status]);
+ const renderComments = scopedTempComment ? [scopedTempComment, ...statusComments] : statusComments;
+ const activeComment = activeCommentId
+ ? renderComments.find((comment) => isSameThreadCommentTarget(activeCommentId, comment))
+ : undefined;
+ const visibleComments = activeComment ? [activeComment] : renderComments;
+ const unsolvedComments = visibleComments.filter((comment) => !comment.resolved);
+ const solvedComments = visibleComments.filter((comment) => comment.resolved);
+ const isFiltering = status !== 'all' || unit !== 'all';
+ const unitFilterOptions = [
+ { value: 'current', label: localeService.t<LocaleKey>('thread-comment-ui.filter.sheet.current') },
+ { value: 'all', label: localeService.t<LocaleKey>('thread-comment-ui.filter.sheet.all') },
+ ];
+ const statusFilterOptions = [
+ { value: 'all', label: localeService.t<LocaleKey>('thread-comment-ui.filter.status.all') },
+ { value: 'resolved', label: localeService.t<LocaleKey>('thread-comment-ui.filter.status.resolved') },
+ { value: 'unsolved', label: localeService.t<LocaleKey>('thread-comment-ui.filter.status.unsolved') },
+ { value: 'concern_me', label: localeService.t<LocaleKey>('thread-comment-ui.filter.status.concernMe') },
+ ];
+
+ const handleReset = () => {
+ setStatus('all');
+ setUnit('all');
+ };
+
+ useEffect(() => {
+ if (shouldClearActiveTarget) {
+ panelService.setActiveComment(undefined);
+ }
+ }, [panelService, shouldClearActiveTarget]);
+
+ useEffect(() => {
+ if (tempComment && (tempComment.unitId !== unitId || (subUnitId && tempComment.subUnitId !== subUnitId))) {
+ onTempCommentClose?.();
+ }
+ }, [onTempCommentClose, subUnitId, tempComment, unitId]);
+
+ useEffect(() => {
+ if (!activeCommentId) {
+ return;
+ }
+
+ const handlePointerDown = (event: PointerEvent) => {
+ const activeTarget = panelService.activeCommentId;
+ const target = event.target;
+ if (event.button !== 0 || !activeTarget || !(target instanceof Element)) {
+ return;
+ }
+
+ const activeElement = document.getElementById(
+ `${location}-${activeTarget.unitId}-${activeTarget.subUnitId}-${activeTarget.commentId}`
+ );
+ if (
+ activeElement?.contains(target) ||
+ target.closest('button, input, textarea, select, a, [contenteditable="true"], [role="menu"], [role="menuitem"], [role="option"], [role="listbox"], [role="combobox"], [role="separator"]')
+ ) {
+ return;
+ }
+
+ commandService.executeCommand(SetActiveCommentOperation.id);
+ if (scopedTempComment && isSameThreadCommentTarget(activeTarget, scopedTempComment)) {
+ onTempCommentClose?.();
+ }
+ };
+
+ document.addEventListener('pointerdown', handlePointerDown, true);
+ return () => document.removeEventListener('pointerdown', handlePointerDown, true);
+ }, [activeCommentId, commandService, location, onTempCommentClose, panelService, scopedTempComment]);
+
+ useEffect(() => {
+ if (!activeCommentId) {
+ return;
+ }
+ if (!shouldScrollRef.current) {
+ shouldScrollRef.current = true;
+ return;
+ }
+ const { unitId: activeUnitId, subUnitId: activeSubUnitId, commentId } = activeCommentId;
+ document.getElementById(`${location}-${activeUnitId}-${activeSubUnitId}-${commentId}`)?.scrollIntoView({ block: 'center' });
+ }, [activeCommentId, location]);
+
+ const renderComment = (section: ThreadCommentPanelSection) => (comment: IThreadComment, index: number) => (
+ <MobileThreadCommentTree
+ full
+ location={location}
+ getSubUnitName={getSubUnitName}
+ key={getThreadCommentPanelItemKey(comment, index, section)}
+ id={comment.id}
+ unitId={comment.unitId}
+ subUnitId={comment.subUnitId}
+ refStr={comment.ref}
+ displayRef={formatRef?.(comment)}
+ type={type}
+ showEdit={!comment.id || isSameThreadCommentTarget(activeCommentId, comment)}
+ showHighlight={isSameThreadCommentTarget(activeCommentId, comment)}
+ autoFocus={autoFocusActiveComment && isSameThreadCommentTarget(activeCommentId, comment)}
+ onClick={() => {
+ shouldScrollRef.current = false;
+ if (comment.resolved) {
+ commandService.executeCommand(SetActiveCommentOperation.id);
+ return;
+ }
+ commandService.executeCommand(SetActiveCommentOperation.id, {
+ unitId: comment.unitId,
+ subUnitId: comment.subUnitId,
+ commentId: comment.id,
+ temp: false,
+ });
+ }}
+ onMouseEnter={() => {
+ panelService.setHoveredComment({
+ unitId: comment.unitId,
+ subUnitId: comment.subUnitId,
+ commentId: comment.id,
+ trigger: 'panel-hover',
+ });
+ onItemEnter?.(comment);
+ }}
+ onMouseLeave={() => {
+ if (isSameThreadCommentTarget(panelService.hoveredCommentId, comment)) {
+ panelService.setHoveredComment(undefined);
+ }
+ onItemLeave?.(comment);
+ }}
+ onAddComment={onAddComment}
+ onDeleteComment={onDeleteComment}
+ onAfterDeleteComment={onAfterDeleteComment}
+ onResolve={(resolved) => onResolve?.(comment.id, resolved)}
+ onClose={!comment.id ? onTempCommentClose : undefined}
/>
);
+
+ return (
+ <div className="univer-flex univer-min-h-full univer-flex-col univer-pb-3">
+ {activeComment && <MobileCommentHeader comment={activeComment} displayRef={formatRef?.(activeComment)} />}
+ {!activeComment && (
+ <div className="univer-mt-3 univer-flex univer-flex-col univer-gap-2">
+ {type === UniverInstanceType.UNIVER_SHEET && (
+ <MobileCommentFilter value={unit} options={unitFilterOptions} onChange={setUnit} />
+ )}
+ <MobileCommentFilter value={status} options={statusFilterOptions} onChange={setStatus} />
+ </div>
+ )}
+ {!activeComment && !disableAdd && !scopedTempComment && <MobileAddComment onAdd={onAdd} />}
+ {visibleComments.length === 0
+ ? (
+ <div
+ className="
+ univer-flex univer-flex-1 univer-flex-col univer-items-center univer-justify-center
+ univer-text-sm univer-text-gray-600
+ dark:!univer-text-gray-200
+ "
+ >
+ {localeService.t<LocaleKey>('thread-comment-ui.panel.empty')}
+ {isFiltering
+ ? (
+ <MobileActionRowGroup className="univer-mt-2 univer-flex univer-flex-row">
+ <Button onClick={handleReset}>
+ {localeService.t<LocaleKey>('thread-comment-ui.panel.reset')}
+ </Button>
+ </MobileActionRowGroup>
+ )
+ : null}
+ </div>
+ )
+ : (
+ <div className="univer-mt-3 univer-flex univer-flex-col univer-gap-3">
+ {unsolvedComments.map(renderComment('unsolved'))}
+ {solvedComments.length > 0 && (
+ <div className="univer-text-xs">
+ {localeService.t<LocaleKey>('thread-comment-ui.panel.solved')}
+ </div>
+ )}
+ {solvedComments.map(renderComment('solved'))}
+ </div>
+ )}
+ </div>
+ );
}
diff --git a/packages/ui/src/controllers/__tests__/ui.controller.spec.ts b/packages/ui/src/controllers/__tests__/ui.controller.spec.ts
index a2f59e925d..5179a11e58 100644
--- a/packages/ui/src/controllers/__tests__/ui.controller.spec.ts
+++ b/packages/ui/src/controllers/__tests__/ui.controller.spec.ts
@@ -19,23 +19,12 @@ import { describe, expect, it, vi } from 'vitest';
import { OpenFeatureSearchOperation } from '../../commands/operations/open-feature-search.operation';
import { ToggleShortcutPanelOperation } from '../../commands/operations/toggle-shortcut-panel.operation';
import { menuSchema } from '../../menu/schema';
-import { ShortcutPanelMenuItemFactory } from '../../menu/shortcut-panel.menu';
import { RibbonStartGroup } from '../../services/menu/types';
import { KeyCode, MetaKeys } from '../../services/shortcut/keycode';
import { FeatureSearchController } from '../feature-search/feature-search.controller';
import { ShortcutPanelController } from '../shortcut-display/shortcut-panel.controller';
describe('shortcut-display controllers', () => {
- it('should return shortcut panel menu item', () => {
- expect(ShortcutPanelMenuItemFactory()).toEqual({
- id: ToggleShortcutPanelOperation.id,
- title: 'ui.toggle-shortcut-panel',
- tooltip: 'ui.toggle-shortcut-panel',
- icon: 'KeyboardIcon',
- type: 0,
- });
- });
-
it('should register command and shortcut', () => {
const shortcutService = {
registerShortcut: vi.fn(() => ({ dispose: vi.fn() })),
diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts
index 82d443e9f7..849a3d2ca5 100644
--- a/packages/ui/src/index.ts
+++ b/packages/ui/src/index.ts
@@ -151,6 +151,7 @@ export { ThemeSwitcherService } from './services/theme-switcher/theme-switcher.s
export { UndoRedoGroupService } from './services/undo-redo/undo-redo-group.service';
export { IWorkbenchService, WorkbenchService } from './services/workbench/workbench.service';
export * from './utils';
+export { MobileCanvasGesture } from './utils/mobile-canvas-gesture';
export { COLOR_PICKER_COMPONENT } from './views/color-picker/interface';
export { ComponentContainer, useComponentsOfPart } from './views/components/ComponentContainer';
export type { IComponentContainerProps } from './views/components/ComponentContainer';
@@ -162,12 +163,14 @@ export { DesktopContextMenu as ContextMenu } from './views/components/context-me
export { ContextMenuPanel } from './views/components/context-menu/ContextMenuPanel';
export { MobileContextMenu } from './views/components/context-menu/MobileContextMenu';
export { type IDialogPartMethodOptions } from './views/components/dialog-part/interface';
+export type { IMobileDialogPartMethodOptions } from './views/components/dialog-part/MobileDialogPart';
export { FloatDomSingle } from './views/components/dom/FloatDom';
export { FloatDom } from './views/components/dom/FloatDom';
export { PrintFloatDomSingle } from './views/components/dom/Print';
export { HOVER_TRACK_HOST_CLASS_NAME, HoverTrack } from './views/components/hover-track/HoverTrack';
export { MobileDrawer } from './views/components/mobile-drawer/MobileDrawer';
export type { MobileDrawerSnap } from './views/components/mobile-drawer/MobileDrawer';
+export { MobileZoomIndicator } from './views/components/mobile-zoom-indicator/mobile-zoom-indicator';
export { CanvasPopup, SingleCanvasPopup } from './views/components/popup/CanvasPopup';
export { RectPopup } from './views/components/popup/RectPopup';
export type { RectPopupDirection } from './views/components/popup/RectPopup';
@@ -175,6 +178,7 @@ export { useToolbarItemStatus } from './views/components/ribbon/hook';
export { Ribbon } from './views/components/ribbon/Ribbon';
export { ToolbarButton } from './views/components/ribbon/ToolbarButton';
export { ToolbarItem } from './views/components/ribbon/ToolbarItem';
+export type { IMobileSidebarMethodOptions } from './views/components/sidebar/MobileSidebar';
export { Sidebar } from './views/components/sidebar/Sidebar';
export type { ISidebarMethodOptions } from './views/components/sidebar/Sidebar';
export { FONT_FAMILY_COMPONENT, FontFamily } from './views/font-family/FontFamily';
@@ -183,6 +187,7 @@ export { FontFamilyDropdown } from './views/font-family/FontFamilyDropdown';
export type { IFontFamilyDropdownProps } from './views/font-family/FontFamilyDropdown';
export { FONT_FAMILY_ITEM_COMPONENT, FontFamilyItem } from './views/font-family/FontFamilyItem';
export type { IFontFamilyItemProps } from './views/font-family/FontFamilyItem';
+export { MobileFontFamilyDropdown } from './views/font-family/MobileFontFamilyDropdown';
export { FontSize } from './views/font-size/FontSize';
export { FONT_SIZE_COMPONENT, FONT_SIZE_LIST, HEADING_LIST } from './views/font-size/interface';
export * from './views/hooks/index';
@@ -190,9 +195,11 @@ export { preventBrowserZoomInContainers } from './views/hooks/prevent-browser-zo
export * from './views/index';
export { MobileMenu } from './views/menu/mobile/MobileMenu';
export { MobileKeyboardInsetContext } from './views/mobile-workbench/mobile-keyboard-inset-context';
+export { getMobileCanvasPanDelta, useMobileCanvasPanel, useMobileCanvasViewport } from './views/mobile-workbench/MobileCanvasLayout';
+export type { MobilePanelLayout } from './views/mobile-workbench/MobileCanvasLayout';
export type { INotificationOptions } from './views/notification/Notification';
export { ObjectPermissionButton, openObjectPermissionDialog } from './views/object-permission/ObjectPermissionButton';
+
export type { IObjectPermissionButtonProps } from './views/object-permission/ObjectPermissionButton';
export { ObjectPermissionPanelButton, openObjectPermissionPanel } from './views/object-permission/ObjectPermissionPanel';
-
export { ProgressBar } from './views/progress-bar/ProgressBar';
diff --git a/packages/ui/src/services/contextmenu/contextmenu.service.ts b/packages/ui/src/services/contextmenu/contextmenu.service.ts
index 9e6898b45d..092664b023 100644
--- a/packages/ui/src/services/contextmenu/contextmenu.service.ts
+++ b/packages/ui/src/services/contextmenu/contextmenu.service.ts
@@ -20,6 +20,7 @@ import { createIdentifier, Disposable, toDisposable } from '@univerjs/core';
export interface IContextMenuTriggerContext {
autoFocus?: boolean;
+ caretAnchor?: boolean;
unitId?: string;
subUnitId?: string;
}
diff --git a/packages/ui/src/utils/__tests__/mobile-canvas-gesture.spec.ts b/packages/ui/src/utils/__tests__/mobile-canvas-gesture.spec.ts
new file mode 100644
index 0000000000..aef794e171
--- /dev/null
+++ b/packages/ui/src/utils/__tests__/mobile-canvas-gesture.spec.ts
@@ -0,0 +1,138 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { MobileCanvasGesture } from '../mobile-canvas-gesture';
+
+describe('MobileCanvasGesture', () => {
+ const gestures: MobileCanvasGesture[] = [];
+
+ afterEach(() => {
+ gestures.splice(0).forEach((gesture) => gesture.dispose());
+ vi.useRealTimers();
+ document.body.replaceChildren();
+ });
+
+ function setup(action: 'pan' | 'object' | 'ignore' = 'pan') {
+ const canvas = document.createElement('canvas');
+ document.body.appendChild(canvas);
+ const options = {
+ start: () => action,
+ tap: vi.fn(),
+ pan: vi.fn(),
+ pinch: vi.fn(),
+ finishObjectTransform: vi.fn(),
+ endPinch: vi.fn(),
+ };
+ const gesture = new MobileCanvasGesture(canvas, options);
+ gestures.push(gesture);
+ const pointer = (type: string, x: number, y: number, id = 1, pointerType = 'touch') => {
+ const event = Object.assign(new MouseEvent(type, { bubbles: true, cancelable: true, clientX: x, clientY: y }), {
+ pointerId: id,
+ pointerType,
+ });
+ canvas.dispatchEvent(event);
+ return event;
+ };
+ return { canvas, gesture, options, pointer };
+ }
+
+ it('selects on release without feeding an unselected object a drag', () => {
+ const { canvas, pointer, options } = setup();
+ const objectDown = vi.fn();
+ canvas.addEventListener('pointerdown', objectDown);
+ pointer('pointerdown', 40, 50);
+ pointer('pointermove', 43, 52);
+ expect(options.tap).not.toHaveBeenCalled();
+ pointer('pointerup', 43, 52);
+ expect(options.tap).toHaveBeenCalledExactlyOnceWith({ x: 43, y: 52 });
+ expect(options.pan).not.toHaveBeenCalled();
+ expect(objectDown).not.toHaveBeenCalled();
+ });
+
+ it('pans in screen pixels, ignores tap jitter and does not select after a swipe', () => {
+ const { pointer, options } = setup();
+ pointer('pointerdown', 20, 30);
+ pointer('pointermove', 23, 32);
+ expect(options.pan).not.toHaveBeenCalled();
+ pointer('pointermove', 40, 50);
+ pointer('pointermove', 55, 65);
+ expect(options.pan.mock.calls).toEqual([[{ x: 20, y: 20 }], [{ x: 15, y: 15 }]]);
+ pointer('pointercancel', 55, 65);
+ expect(options.tap).not.toHaveBeenCalled();
+ });
+
+ it.each(['object', 'ignore'] as const)('preserves existing %s manipulation', (action) => {
+ const { pointer, options } = setup(action);
+ expect(pointer('pointerdown', 10, 20).defaultPrevented).toBe(false);
+ expect(pointer('pointermove', 50, 60).defaultPrevented).toBe(false);
+ expect(pointer('pointerup', 50, 60).defaultPrevented).toBe(false);
+ expect(options.tap).not.toHaveBeenCalled();
+ expect(options.pan).not.toHaveBeenCalled();
+ });
+
+ it('hands a selected object to a centered pinch and consumes the remaining finger without jumping', () => {
+ const { canvas, pointer, options } = setup('object');
+ const cancel = vi.fn();
+ canvas.addEventListener('pointercancel', cancel);
+ pointer('pointerdown', 100, 100);
+ pointer('pointerdown', 200, 100, 2);
+ expect(options.finishObjectTransform).toHaveBeenCalledTimes(1);
+ expect(cancel).toHaveBeenCalledTimes(1);
+ expect(cancel.mock.calls[0][0].pointerId).toBe(1);
+ expect(pointer('pointermove', 300, 100, 2).defaultPrevented).toBe(true);
+ expect(options.pinch).toHaveBeenCalledExactlyOnceWith(2, { x: 150, y: 100 }, { x: 200, y: 100 });
+ pointer('pointerup', 300, 100, 2);
+ pointer('pointermove', 120, 110);
+ expect(options.pan).not.toHaveBeenCalled();
+ expect(options.pinch).toHaveBeenCalledTimes(1);
+ pointer('pointerup', 120, 110);
+ expect(options.endPinch).toHaveBeenCalledTimes(1);
+ expect(options.tap).not.toHaveBeenCalled();
+ });
+
+ it('continues a flick with inertia and stops immediately on a new touch', () => {
+ vi.useFakeTimers();
+ const { pointer, options } = setup();
+ pointer('pointerdown', 20, 30);
+ vi.advanceTimersByTime(16);
+ pointer('pointermove', 20, 70);
+ pointer('pointerup', 20, 70);
+ const dragCalls = options.pan.mock.calls.length;
+ vi.advanceTimersByTime(64);
+ expect(options.pan.mock.calls.length).toBeGreaterThan(dragCalls);
+ pointer('pointerdown', 20, 70);
+ const stoppedCalls = options.pan.mock.calls.length;
+ vi.advanceTimersByTime(100);
+ expect(options.pan).toHaveBeenCalledTimes(stoppedCalls);
+ });
+
+ it('does not suppress subsequent mouse input or leave listeners after disposal', () => {
+ const { canvas, gesture, pointer, options } = setup();
+ pointer('pointerdown', 30, 30);
+ pointer('pointerup', 30, 30);
+ pointer('pointerdown', 30, 30, 2, 'mouse');
+ const click = new MouseEvent('click', { bubbles: true, cancelable: true });
+ canvas.dispatchEvent(click);
+ expect(click.defaultPrevented).toBe(false);
+ gesture.dispose();
+ options.tap.mockClear();
+ pointer('pointerdown', 30, 30);
+ pointer('pointerup', 30, 30);
+ expect(options.tap).not.toHaveBeenCalled();
+ expect(canvas.style.touchAction).not.toBe('none');
+ });
+});
diff --git a/packages/ui/src/utils/mobile-canvas-gesture.ts b/packages/ui/src/utils/mobile-canvas-gesture.ts
new file mode 100644
index 0000000000..f27551c60d
--- /dev/null
+++ b/packages/ui/src/utils/mobile-canvas-gesture.ts
@@ -0,0 +1,252 @@
+/**
+ * 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 { IPoint } from '@univerjs/engine-render';
+import { Disposable, toDisposable } from '@univerjs/core';
+
+export interface IMobileCanvasGestureOptions {
+ start: (point: IPoint) => 'pan' | 'object' | 'ignore';
+ tap: (point: IPoint) => void;
+ pan: (delta: IPoint) => void;
+ pinch: (factor: number, previousCenter: IPoint, center: IPoint) => void;
+ finishObjectTransform: () => void;
+ endPinch: () => void;
+}
+
+/** Routes touch browsing separately from the canvas's existing object manipulation. */
+export class MobileCanvasGesture extends Disposable {
+ private readonly _points = new Map<number, IPoint>();
+ private _objectPointerId: number | null = null;
+ private _cancellingObject = false;
+ private _startPoint: IPoint | null = null;
+ private _moved = false;
+ private _pinching = false;
+ private _suppressClick = false;
+ private _lastMoveTime = 0;
+ private _velocity: IPoint = { x: 0, y: 0 };
+ private _frame: number | null = null;
+
+ constructor(private readonly _canvas: HTMLCanvasElement, private readonly _options: IMobileCanvasGestureOptions) {
+ super();
+ const touchAction = _canvas.style.touchAction;
+ _canvas.style.touchAction = 'none';
+ const down = (event: PointerEvent) => this._onDown(event);
+ const move = (event: PointerEvent) => this._onMove(event);
+ const up = (event: PointerEvent) => this._onEnd(event);
+ const blur = () => this._reset();
+ const click = (event: MouseEvent) => {
+ if (event.target === _canvas && this._suppressClick) {
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ }
+ };
+ window.addEventListener('pointerdown', down, true);
+ window.addEventListener('pointermove', move, true);
+ window.addEventListener('pointerup', up, true);
+ window.addEventListener('pointercancel', up, true);
+ window.addEventListener('click', click, true);
+ window.addEventListener('blur', blur);
+ this.disposeWithMe(toDisposable(() => {
+ this._reset();
+ _canvas.style.touchAction = touchAction;
+ window.removeEventListener('pointerdown', down, true);
+ window.removeEventListener('pointermove', move, true);
+ window.removeEventListener('pointerup', up, true);
+ window.removeEventListener('pointercancel', up, true);
+ window.removeEventListener('click', click, true);
+ window.removeEventListener('blur', blur);
+ }));
+ }
+
+ private _point(event: PointerEvent): IPoint {
+ const rect = this._canvas.getBoundingClientRect();
+ return { x: event.clientX - rect.left, y: event.clientY - rect.top };
+ }
+
+ private _consume(event: PointerEvent): void {
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ }
+
+ private _onDown(event: PointerEvent): void {
+ this._stopInertia();
+ if (event.target !== this._canvas || event.pointerType !== 'touch') {
+ this._suppressClick = false;
+ return;
+ }
+ const point = this._point(event);
+ if (this._points.size === 0) {
+ this._suppressClick = false;
+ const action = this._options.start(point);
+ if (action === 'ignore') {
+ return;
+ }
+ this._startPoint = point;
+ this._moved = false;
+ this._lastMoveTime = event.timeStamp;
+ this._points.set(event.pointerId, point);
+ if (action === 'object') {
+ this._objectPointerId = event.pointerId;
+ return;
+ }
+ } else {
+ this._points.set(event.pointerId, point);
+ if (!this._pinching) {
+ this._options.finishObjectTransform();
+ this._cancelObjectPointer();
+ this._pinching = true;
+ this._moved = true;
+ }
+ }
+ this._suppressClick = true;
+ this._consume(event);
+ }
+
+ private _onMove(event: PointerEvent): void {
+ const previous = this._points.get(event.pointerId);
+ if (!previous) {
+ return;
+ }
+ const point = this._point(event);
+ const previousPoints = Array.from(this._points.values());
+ this._points.set(event.pointerId, point);
+ if (this._pinching) {
+ const points = Array.from(this._points.values());
+ if (points.length >= 2) {
+ const [a, b] = previousPoints;
+ const [c, d] = points;
+ const distance = Math.hypot(a.x - b.x, a.y - b.y);
+ if (distance > 0) {
+ this._options.pinch(
+ Math.hypot(c.x - d.x, c.y - d.y) / distance,
+ { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 },
+ { x: (c.x + d.x) / 2, y: (c.y + d.y) / 2 }
+ );
+ }
+ }
+ this._consume(event);
+ return;
+ }
+ if (this._objectPointerId !== null) {
+ return;
+ }
+ if (!this._moved && this._startPoint && Math.hypot(point.x - this._startPoint.x, point.y - this._startPoint.y) >= 8) {
+ this._moved = true;
+ this._options.pan({ x: point.x - this._startPoint.x, y: point.y - this._startPoint.y });
+ } else if (this._moved) {
+ this._options.pan({ x: point.x - previous.x, y: point.y - previous.y });
+ }
+ const elapsed = Math.max(1, event.timeStamp - this._lastMoveTime);
+ this._velocity = { x: (point.x - previous.x) / elapsed, y: (point.y - previous.y) / elapsed };
+ this._lastMoveTime = event.timeStamp;
+ this._consume(event);
+ }
+
+ private _onEnd(event: PointerEvent): void {
+ if (this._cancellingObject) {
+ return;
+ }
+ if (!this._points.has(event.pointerId)) {
+ return;
+ }
+ this._points.delete(event.pointerId);
+ const objectPointer = this._objectPointerId === event.pointerId;
+ if (objectPointer) {
+ this._objectPointerId = null;
+ } else {
+ this._consume(event);
+ }
+ if (this._points.size !== 0) {
+ return;
+ }
+ if (this._pinching) {
+ this._options.endPinch();
+ } else if (!objectPointer && event.type !== 'pointercancel') {
+ if (!this._moved) {
+ this._options.tap(this._point(event));
+ } else if (event.timeStamp - this._lastMoveTime < 80) {
+ this._startInertia();
+ }
+ }
+ this._pinching = false;
+ this._startPoint = null;
+ }
+
+ private _startInertia(): void {
+ let velocity = {
+ x: Math.max(-3, Math.min(3, this._velocity.x)),
+ y: Math.max(-3, Math.min(3, this._velocity.y)),
+ };
+ let previousTime = performance.now();
+ const frame = (time: number) => {
+ const elapsed = Math.min(32, time - previousTime);
+ previousTime = time;
+ const decay = Math.exp(-0.005 * elapsed);
+ this._options.pan({ x: velocity.x * (1 - decay) / 0.005, y: velocity.y * (1 - decay) / 0.005 });
+ velocity = { x: velocity.x * decay, y: velocity.y * decay };
+ this._frame = Math.hypot(velocity.x, velocity.y) > 0.02 ? requestAnimationFrame(frame) : null;
+ };
+ if (Math.hypot(velocity.x, velocity.y) > 0.04) {
+ this._frame = requestAnimationFrame(frame);
+ }
+ }
+
+ private _stopInertia(): void {
+ if (this._frame !== null) {
+ cancelAnimationFrame(this._frame);
+ this._frame = null;
+ }
+ this._velocity = { x: 0, y: 0 };
+ }
+
+ private _reset(): void {
+ this._stopInertia();
+ if (this._objectPointerId !== null) {
+ this._options.finishObjectTransform();
+ this._cancelObjectPointer();
+ }
+ if (this._pinching) {
+ this._options.endPinch();
+ }
+ this._points.clear();
+ this._objectPointerId = null;
+ this._pinching = false;
+ this._startPoint = null;
+ }
+
+ private _cancelObjectPointer(): void {
+ const pointerId = this._objectPointerId;
+ const point = pointerId === null ? null : this._points.get(pointerId);
+ if (pointerId === null || !point) {
+ return;
+ }
+ const rect = this._canvas.getBoundingClientRect();
+ this._objectPointerId = null;
+ this._cancellingObject = true;
+ try {
+ // End the canvas's single-pointer interaction before pinch owns both fingers.
+ this._canvas.dispatchEvent(new PointerEvent('pointercancel', {
+ bubbles: true,
+ pointerId,
+ pointerType: 'touch',
+ clientX: rect.left + point.x,
+ clientY: rect.top + point.y,
+ }));
+ } finally {
+ this._cancellingObject = false;
+ }
+ }
+}
diff --git a/packages/ui/src/views/components/context-menu/MobileContextMenu.tsx b/packages/ui/src/views/components/context-menu/MobileContextMenu.tsx
index 797a213b3c..3498f2513f 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 { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
+import { createPortal } from 'react-dom';
import { IContextMenuHostService } from '../../../services/contextmenu/contextmenu-host.service';
import { IContextMenuService } from '../../../services/contextmenu/contextmenu.service';
import { ILayoutService } from '../../../services/layout/layout.service';
@@ -28,13 +28,32 @@ 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';
+const MOBILE_CONTEXT_MENU_POINTER_SIZE = 8;
+const MOBILE_CONTEXT_MENU_POINTER_EDGE_GAP = 12;
+
+export function resolveMobileCaretMenuPlacement(anchorX: number, containerLeft: number, containerWidth: number, menuWidth: number) {
+ const relativeAnchorX = anchorX - containerLeft;
+ const menuLeft = Math.min(
+ Math.max(relativeAnchorX - menuWidth / 2, 0),
+ Math.max(containerWidth - menuWidth, 0)
+ );
+ const pointerLeft = Math.min(
+ Math.max(relativeAnchorX - menuLeft - MOBILE_CONTEXT_MENU_POINTER_SIZE / 2, MOBILE_CONTEXT_MENU_POINTER_EDGE_GAP),
+ Math.max(menuWidth - MOBILE_CONTEXT_MENU_POINTER_EDGE_GAP - MOBILE_CONTEXT_MENU_POINTER_SIZE, MOBILE_CONTEXT_MENU_POINTER_EDGE_GAP)
+ );
+
+ return { menuLeft, pointerLeft };
+}
export function MobileContextMenu() {
const [visible, setVisible] = useState(false);
const [menuType, setMenuType] = useState('');
+ const [anchor, setAnchor] = useState({ x: 0, y: 0 });
+ const floatingMenuRef = useRef<HTMLDivElement>(null);
const [menuContext, setMenuContext] = useState<IContextMenuTriggerContext | undefined>();
const visibleRef = useRef(visible);
const contextMenuHostService = useDependency(IContextMenuHostService);
@@ -45,17 +64,20 @@ export function MobileContextMenu() {
const runtimeScopeService = useDependency(IUIRuntimeScopeService);
const localeService = useDependency(LocaleService);
const { mountContainer } = useContext(ConfigContext);
+ const isCaretAnchor = menuContext?.caretAnchor === true;
+ const isFloatingContextMenu = menuType === ContextMenuPosition.MAIN_AREA || isCaretAnchor;
visibleRef.current = visible;
const handleContextMenu = useCallback((
- _event: ContextMenuEvent,
+ 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);
}, [contextMenuHostService]);
@@ -86,6 +108,59 @@ export function MobileContextMenu() {
};
}, [contextMenuHostService, contextMenuService, handleClose, handleContextMenu]);
+ useEffect(() => {
+ if (!visible || !isFloatingContextMenu || !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, isFloatingContextMenu, mountContainer, visible]);
+
+ useLayoutEffect(() => {
+ if (!visible || !isCaretAnchor) {
+ return undefined;
+ }
+
+ const menu = floatingMenuRef.current;
+ const container = menu?.parentElement;
+ if (!menu || !container) {
+ return undefined;
+ }
+
+ const updatePlacement = () => {
+ const containerRect = container.getBoundingClientRect();
+ const menuWidth = menu.getBoundingClientRect().width;
+ const { menuLeft, pointerLeft } = resolveMobileCaretMenuPlacement(
+ anchor.x,
+ containerRect.left,
+ containerRect.width,
+ menuWidth
+ );
+
+ menu.style.left = `${menuLeft}px`;
+ menu.style.setProperty('--univer-mobile-context-menu-pointer-left', `${pointerLeft}px`);
+ };
+
+ updatePlacement();
+ const resizeObserver = new ResizeObserver(updatePlacement);
+ resizeObserver.observe(container);
+ resizeObserver.observe(menu);
+
+ return () => {
+ resizeObserver.disconnect();
+ menu.style.removeProperty('left');
+ menu.style.removeProperty('--univer-mobile-context-menu-pointer-left');
+ };
+ }, [anchor.x, isCaretAnchor, visible]);
+
const sheetTitle = useMemo(() => {
switch (menuType) {
case ContextMenuPosition.ROW_HEADER:
@@ -127,6 +202,59 @@ export function MobileContextMenu() {
activeCommandService.executeCommand(commandId, commandParams);
handleClose();
};
+ if (isFloatingContextMenu) {
+ 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-3 univer-z-[1080] univer-flex
+ univer-justify-center
+ "
+ style={{ top }}
+ >
+ <div
+ ref={floatingMenuRef}
+ className={`
+ univer-pointer-events-auto univer-min-w-0 univer-max-w-[560px]
+ ${isCaretAnchor
+ ? 'univer-absolute univer-left-0 univer-top-0 univer-w-fit'
+ : 'univer-relative 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: isCaretAnchor
+ ? 'var(--univer-mobile-context-menu-pointer-left, calc(50% - 4px))'
+ : pointerLeft,
+ }}
+ />
+ </div>
+ </div>,
+ mountContainer
+ );
+ }
return (
<MobileMenuDrawer
visible
diff --git a/packages/ui/src/views/components/context-menu/__tests__/MobileContextMenu.spec.ts b/packages/ui/src/views/components/context-menu/__tests__/MobileContextMenu.spec.ts
new file mode 100644
index 0000000000..482d5d9883
--- /dev/null
+++ b/packages/ui/src/views/components/context-menu/__tests__/MobileContextMenu.spec.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 { describe, expect, it } from 'vitest';
+import { resolveMobileCaretMenuPlacement } from '../MobileContextMenu';
+
+describe('MobileContextMenu', () => {
+ it('keeps the pointer aligned with the caret when the compact menu reaches viewport edges', () => {
+ expect(resolveMobileCaretMenuPlacement(200, 12, 400, 180)).toEqual({
+ menuLeft: 98,
+ pointerLeft: 86,
+ });
+ expect(resolveMobileCaretMenuPlacement(8, 12, 400, 180)).toEqual({
+ menuLeft: 0,
+ pointerLeft: 12,
+ });
+ expect(resolveMobileCaretMenuPlacement(420, 12, 400, 180)).toEqual({
+ menuLeft: 220,
+ pointerLeft: 160,
+ });
+ });
+});
diff --git a/packages/ui/src/views/components/dialog-part/MobileDialogPart.tsx b/packages/ui/src/views/components/dialog-part/MobileDialogPart.tsx
index dd5a18fe55..51b34a4619 100644
--- a/packages/ui/src/views/components/dialog-part/MobileDialogPart.tsx
+++ b/packages/ui/src/views/components/dialog-part/MobileDialogPart.tsx
@@ -16,6 +16,7 @@
import type { ReactNode } from 'react';
import type { LocaleKey } from '../../../locale/types';
+import type { MobilePanelLayout } from '../../mobile-workbench/MobileCanvasLayout';
import type { MobileDrawerSnap } from '../mobile-drawer/MobileDrawer';
import type { IDialogPartMethodOptions } from './interface';
import { LocaleService } from '@univerjs/core';
@@ -27,13 +28,17 @@ import { useDependency, useObservable } from '../../../utils/di';
import { CustomLabel } from '../../custom-label/CustomLabel';
import { MobileDrawer } from '../mobile-drawer/MobileDrawer';
-interface IMobileDialogOptions extends Omit<IDialogPartMethodOptions, 'children' | 'title' | 'footer'> {
+export interface IMobileDialogPartMethodOptions extends IDialogPartMethodOptions {
+ layout?: MobilePanelLayout;
+}
+
+interface IMobileDialogOptions extends Omit<IMobileDialogPartMethodOptions, 'children' | 'title' | 'footer'> {
children?: ReactNode;
title?: ReactNode;
footer?: ReactNode;
}
-function toMobileDialogOptions(options: IDialogPartMethodOptions): IMobileDialogOptions {
+function toMobileDialogOptions(options: IMobileDialogPartMethodOptions): IMobileDialogOptions {
const { children, title, footer, ...rest } = options;
return {
...rest,
@@ -49,16 +54,17 @@ export function MobileDialogPart() {
const dialogOptions = useObservable(dialogService.getDialogs$(), []);
const options = useMemo(() => {
const activeDialogs = dialogOptions.filter((item) => item.open !== false);
- const active = activeDialogs[activeDialogs.length - 1];
+ const active = activeDialogs[activeDialogs.length - 1] as IMobileDialogPartMethodOptions | undefined;
return active ? toMobileDialogOptions(active) : null;
}, [dialogOptions]);
- const [drawerSnap, setDrawerSnap] = useState<MobileDrawerSnap>('expanded');
+ const [snapOverride, setSnapOverride] = useState<{ id: string; snap: MobileDrawerSnap } | null>(null);
const layerRef = useRef<HTMLDivElement>(null);
const backdropPointerIdRef = useRef<number | null>(null);
if (!options) {
return null;
}
+ const defaultSnap = options.layout === 'canvas' ? 'compact' : 'expanded';
const close = () => {
dialogService.close(options.id);
@@ -69,42 +75,45 @@ export function MobileDialogPart() {
return (
<div
ref={layerRef}
- className="univer-fixed univer-inset-0 univer-z-[1200]"
+ className="univer-pointer-events-none univer-fixed univer-inset-0 univer-z-[1200]"
data-u-comp="mobile-dialog"
>
- <button
- type="button"
- aria-label={localeService.t<LocaleKey>('ui.sidebar.close')}
- className="
- univer-absolute univer-inset-0 univer-m-0 univer-appearance-none univer-rounded-none univer-border-0
- univer-bg-black/35 univer-p-0
- "
- onPointerDown={options.maskClosable === false
- ? undefined
- : (event) => {
- backdropPointerIdRef.current = event.pointerId;
- }}
- onPointerUp={options.maskClosable === false
- ? undefined
- : (event) => {
- if (backdropPointerIdRef.current !== event.pointerId) {
- return;
- }
+ {options.layout !== 'canvas' && (
+ <button
+ type="button"
+ aria-label={localeService.t<LocaleKey>('ui.sidebar.close')}
+ className="
+ univer-pointer-events-auto univer-absolute univer-inset-0 univer-m-0 univer-appearance-none
+ univer-rounded-none univer-border-0 univer-bg-black/35 univer-p-0
+ "
+ 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;
- close();
}}
- onPointerCancel={() => {
- backdropPointerIdRef.current = null;
- }}
- />
+ />
+ )}
<MobileDrawer
layerRef={layerRef}
+ layout={options.layout}
componentName="mobile-dialog-drawer"
- snap={drawerSnap}
+ snap={snapOverride?.id === options.id ? snapOverride.snap : defaultSnap}
expandLabel={localeService.t<LocaleKey>('ui.sidebar.resize')}
collapseLabel={localeService.t<LocaleKey>('ui.sidebar.resize')}
- onSnapChange={setDrawerSnap}
+ onSnapChange={(snap) => setSnapOverride({ id: options.id, snap })}
onClose={close}
role="dialog"
panelClassName="
diff --git a/packages/ui/src/views/components/mobile-drawer/MobileDrawer.tsx b/packages/ui/src/views/components/mobile-drawer/MobileDrawer.tsx
index b44261ae12..974ac5b539 100644
--- a/packages/ui/src/views/components/mobile-drawer/MobileDrawer.tsx
+++ b/packages/ui/src/views/components/mobile-drawer/MobileDrawer.tsx
@@ -15,8 +15,10 @@
*/
import type { AriaRole, PointerEvent, ReactNode, RefObject } from 'react';
-import { clsx, resetButtonClassName, scrollbarClassName } from '@univerjs/design';
-import { useContext, useImperativeHandle, useLayoutEffect, useRef, useState } from 'react';
+import type { MobilePanelLayout } from '../../mobile-workbench/MobileCanvasLayout';
+import { clsx, MobileOverlayContext, resetButtonClassName, scrollbarClassName } from '@univerjs/design';
+import { createContext, useCallback, useContext, useLayoutEffect, useMemo, useRef, useState } from 'react';
+import { useMobileCanvasPanel, useMobileOverlayRegistration } from '../../mobile-workbench/MobileCanvasLayout';
import { MobileDrawerCoordinatorContext } from './MobileDrawerCoordinator';
export type MobileDrawerSnap = 'compact' | 'expanded';
@@ -24,8 +26,17 @@ export type MobileDrawerRelease = MobileDrawerSnap | 'closed';
export type MobileDrawerOpenMode = 'replace' | 'push';
type MobileDrawerRef<T> = { current: T | null } | ((instance: T | null) => void) | null;
+function assignDrawerRef<T>(ref: MobileDrawerRef<T> | undefined, element: T | null) {
+ if (typeof ref === 'function') {
+ ref(element);
+ } else if (ref) {
+ ref.current = element;
+ }
+}
+
const MOBILE_DRAWER_COMPACT_PERCENT = 40;
const MOBILE_DRAWER_EXPANDED_PERCENT = 80;
+const MobileDrawerLayoutContext = createContext<MobilePanelLayout>('modal');
export function resolveMobileDrawerRelease(params: {
snap: MobileDrawerSnap;
@@ -60,6 +71,7 @@ export function MobileDrawer(props: {
footer?: ReactNode;
role?: AriaRole;
ariaLabel?: string;
+ layout?: MobilePanelLayout;
}) {
const {
snap,
@@ -80,6 +92,7 @@ export function MobileDrawer(props: {
footer,
role,
ariaLabel,
+ layout: requestedLayout,
} = props;
const coordinator = useContext(MobileDrawerCoordinatorContext);
const registerDrawer = coordinator?.register;
@@ -93,7 +106,34 @@ export function MobileDrawer(props: {
}
const drawerId = drawerIdRef.current;
const active = !coordinator || coordinator.activeDrawerId === drawerId;
+ const inheritedLayout = useContext(MobileDrawerLayoutContext);
+ const layout = requestedLayout ?? inheritedLayout;
+ const registerOverlay = useMobileOverlayRegistration(layout);
+ const viewportHeightUnit = globalThis.CSS?.supports('height', '1dvh') ? 'dvh' : 'vh';
+ const overlay = useMemo(() => ({
+ modal: layout === 'modal',
+ contentProps: {
+ style: layout === 'canvas'
+ ? {
+ height: `${MOBILE_DRAWER_COMPACT_PERCENT}${viewportHeightUnit}`,
+ maxHeight: `${MOBILE_DRAWER_COMPACT_PERCENT}${viewportHeightUnit}`,
+ }
+ : undefined,
+ // Nested canvas controls must not steal focus or restore it to a
+ // trigger after the user has resumed editing in the canvas.
+ onOpenAutoFocus: layout === 'canvas' ? (event: Event) => event.preventDefault() : undefined,
+ onCloseAutoFocus: layout === 'canvas' ? (event: Event) => event.preventDefault() : undefined,
+ },
+ onMount: registerOverlay,
+ }), [layout, registerOverlay, viewportHeightUnit]);
const [dragPercent, setDragPercent] = useState<number | null>(null);
+ const surfaceRef = useRef<HTMLElement>(null);
+ const setPanelRef = useCallback((element: HTMLElement | null) => {
+ surfaceRef.current = element;
+ panelElementRef.current = element;
+ assignDrawerRef(panelRef, element);
+ }, [panelRef]);
+ useMobileCanvasPanel(surfaceRef, layout, dragPercent !== null);
const suppressHandleClickRef = useRef(false);
const dragRef = useRef<{
startY: number;
@@ -105,9 +145,6 @@ 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) {
@@ -198,81 +235,88 @@ export function MobileDrawer(props: {
}
return (
- <>
- {floatingActions && (
- <div
- className="univer-pointer-events-none univer-absolute univer-right-4 univer-z-30"
- style={{ bottom: `calc(${drawerPercent}${viewportHeightUnit} + 12px)` }}
- >
- {floatingActions}
- </div>
- )}
- <section
- ref={panelElementRef}
- hidden={!active}
- role={role}
- aria-modal={role === 'dialog' || undefined}
- aria-label={ariaLabel}
- data-u-comp={componentName}
- data-snap={snap}
- className={clsx(`
- univer-absolute univer-inset-x-0 univer-bottom-0 univer-z-20 univer-flex univer-flex-col
- univer-overflow-hidden univer-rounded-t-[24px] univer-bg-gray-50 univer-shadow-2xl
- univer-transition-[height] univer-duration-200
- dark:!univer-bg-gray-900
- `, dragPercent != null && '!univer-transition-none', panelClassName)}
- style={{
- height: `${drawerPercent}${viewportHeightUnit}`,
- paddingBottom: 'env(safe-area-inset-bottom, 0px)',
- }}
- >
- <div
- className="
- univer-relative univer-flex univer-h-14 univer-shrink-0 univer-items-end univer-bg-gray-0
- dark:!univer-bg-gray-800
- "
- >
- <button
- type="button"
- aria-label={snap === 'compact' ? expandLabel : collapseLabel}
- className={clsx(resetButtonClassName, `
- 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={handlePointerCancel}
- onClick={() => {
- if (suppressHandleClickRef.current) {
- suppressHandleClickRef.current = false;
- return;
- }
- onSnapChange(snap === 'compact' ? 'expanded' : 'compact');
- }}
+ <MobileDrawerLayoutContext.Provider value={layout}>
+ <MobileOverlayContext.Provider value={overlay}>
+ {floatingActions && (
+ <div
+ className="univer-pointer-events-none univer-absolute univer-right-4 univer-z-30"
+ style={{ bottom: `calc(${drawerPercent}${viewportHeightUnit} + 12px)` }}
>
- <span
- className="
- univer-h-1 univer-w-10 univer-rounded-full univer-bg-gray-300
- dark:!univer-bg-gray-600
- "
- />
- </button>
- {header}
- </div>
- <div
- ref={contentRef}
- className={clsx(
- 'univer-flex-1 univer-overflow-y-auto univer-overflow-x-hidden univer-p-3',
- scrollbarClassName,
- contentClassName
- )}
+ {floatingActions}
+ </div>
+ )}
+ <section
+ ref={setPanelRef}
+ hidden={!active}
+ role={role}
+ aria-modal={(layout === 'modal' && role === 'dialog') || undefined}
+ aria-label={ariaLabel}
+ data-u-comp={componentName}
+ data-snap={snap}
+ // Small form text triggers iOS focus zoom. Keep this local to mobile
+ // drawers, without overriding document/contenteditable text styles.
+ className={clsx(`
+ univer-absolute univer-inset-x-0 univer-bottom-0 univer-z-20 univer-flex univer-flex-col
+ univer-overflow-hidden univer-rounded-t-[24px] univer-bg-gray-50 univer-shadow-2xl
+ univer-transition-[height] univer-duration-200
+ dark:!univer-bg-gray-900
+ [&_input]:!univer-text-base
+ [&_select]:!univer-text-base
+ [&_textarea]:!univer-text-base
+ `, 'univer-pointer-events-auto', dragPercent != null && '!univer-transition-none', panelClassName)}
+ style={{
+ height: `${drawerPercent}${viewportHeightUnit}`,
+ paddingBottom: 'env(safe-area-inset-bottom, 0px)',
+ }}
>
- {children}
- </div>
- {footer}
- </section>
- </>
+ <div
+ className="
+ univer-relative univer-flex univer-h-14 univer-shrink-0 univer-items-end univer-bg-gray-0
+ dark:!univer-bg-gray-800
+ "
+ >
+ <button
+ type="button"
+ aria-label={snap === 'compact' ? expandLabel : collapseLabel}
+ className={clsx(resetButtonClassName, `
+ 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
+ `)}
+ onPointerDown={handlePointerDown}
+ onPointerMove={handlePointerMove}
+ onPointerUp={handlePointerUp}
+ onPointerCancel={handlePointerCancel}
+ onClick={() => {
+ if (suppressHandleClickRef.current) {
+ suppressHandleClickRef.current = false;
+ return;
+ }
+ onSnapChange(snap === 'compact' ? 'expanded' : 'compact');
+ }}
+ >
+ <span
+ className="
+ univer-h-1 univer-w-10 univer-rounded-full univer-bg-gray-300
+ dark:!univer-bg-gray-600
+ "
+ />
+ </button>
+ {header}
+ </div>
+ <div
+ ref={contentRef}
+ className={clsx(
+ 'univer-flex-1 univer-overflow-y-auto univer-overflow-x-hidden univer-p-3',
+ scrollbarClassName,
+ contentClassName
+ )}
+ >
+ {children}
+ </div>
+ {footer}
+ </section>
+ </MobileOverlayContext.Provider>
+ </MobileDrawerLayoutContext.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.tsx
similarity index 78%
rename from packages/ui/src/views/components/mobile-drawer/__tests__/MobileDrawer.spec.ts
rename to packages/ui/src/views/components/mobile-drawer/__tests__/MobileDrawer.spec.tsx
index dbd81487e3..aae05c8762 100644
--- a/packages/ui/src/views/components/mobile-drawer/__tests__/MobileDrawer.spec.ts
+++ b/packages/ui/src/views/components/mobile-drawer/__tests__/MobileDrawer.spec.tsx
@@ -16,6 +16,8 @@
import type { MobileDrawerOpenMode } from '../MobileDrawer';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { ConfigProvider, MobileDropdown } from '@univerjs/design';
+import enUS from '@univerjs/design/locale/en-US';
import { createElement, useRef } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { MobileDrawer, resolveMobileDrawerRelease } from '../MobileDrawer';
@@ -48,6 +50,47 @@ afterEach(() => {
});
describe('mobile drawer snap behavior', () => {
+ it.each(['canvas', 'modal'] as const)('coordinates nested %s menus without changing the other layout', (layout) => {
+ vi.stubGlobal('CSS', { supports: () => false });
+ const app = (open: boolean) => (
+ <ConfigProvider locale={enUS.design} mountContainer={document.body}>
+ <MobileDrawer
+ snap="compact"
+ expandLabel="Expand"
+ collapseLabel="Collapse"
+ onSnapChange={vi.fn()}
+ onClose={vi.fn()}
+ layout={layout}
+ >
+ <button type="button">Canvas action</button>
+ <MobileDropdown open={open} overlay={<input aria-label="Option" />}>
+ <button type="button">Trigger</button>
+ </MobileDropdown>
+ </MobileDrawer>
+ </ConfigProvider>
+ );
+ const view = render(app(false));
+ const action = screen.getByRole('button', { name: 'Canvas action' });
+ action.focus();
+ view.rerender(app(true));
+ const dialog = screen.getByRole('dialog');
+ if (layout === 'canvas') {
+ expect(dialog.style.height).toBe('40vh');
+ expect(document.activeElement).toBe(action);
+ expect(document.body.style.pointerEvents).not.toBe('none');
+ } else {
+ expect(dialog.style.height).toBe('');
+ expect(dialog.style.maxHeight).toBe('80vh');
+ expect(dialog.contains(document.activeElement)).toBe(true);
+ }
+ view.rerender(app(false));
+ expect(screen.queryByRole('dialog')).toBeNull();
+ expect(document.body.style.pointerEvents).not.toBe('none');
+ if (layout === 'canvas') {
+ expect(document.activeElement).toBe(action);
+ }
+ });
+
it('falls back to viewport height units when dynamic viewport units are unavailable', () => {
vi.stubGlobal('CSS', { supports: () => false });
const { container } = render(createElement(MobileDrawer, {
@@ -101,7 +144,7 @@ describe('mobile drawer snap behavior', () => {
}, 'Drawer content'));
const handle = screen.getByRole('button', { name: 'Expand drawer' });
- expect(handle.style.touchAction).toBe('none');
+ expect(handle.classList.contains('univer-touch-none')).toBe(true);
fireEvent.pointerDown(handle, { pointerId: 1, clientY: 500 });
fireEvent.pointerMove(handle, { pointerId: 1, clientY: 450 });
fireEvent.pointerCancel(handle, { pointerId: 1, clientY: 0 });
diff --git a/packages/ui/src/views/components/mobile-zoom-indicator/__tests__/mobile-zoom-indicator.spec.ts b/packages/ui/src/views/components/mobile-zoom-indicator/__tests__/mobile-zoom-indicator.spec.ts
new file mode 100644
index 0000000000..9ac18fbf98
--- /dev/null
+++ b/packages/ui/src/views/components/mobile-zoom-indicator/__tests__/mobile-zoom-indicator.spec.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.
+ */
+
+// @vitest-environment jsdom
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { MobileZoomIndicator } from '../mobile-zoom-indicator';
+
+describe('MobileZoomIndicator', () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ document.body.replaceChildren();
+ });
+
+ it('shows the current percentage and fades after the gesture ends', () => {
+ vi.useFakeTimers();
+ const container = document.createElement('div');
+ const canvas = document.createElement('canvas');
+ const indicator = new MobileZoomIndicator(canvas);
+
+ expect(container.children).toHaveLength(0);
+ container.appendChild(canvas);
+ document.body.appendChild(container);
+ indicator.show(125);
+ const element = container.querySelector('div');
+ expect(element?.textContent).toBe('125%');
+ expect((element as HTMLElement).style.opacity).toBe('1');
+
+ indicator.hide();
+ vi.advanceTimersByTime(300);
+ expect((element as HTMLElement).style.opacity).toBe('0');
+
+ indicator.dispose();
+ expect(container.querySelector('div')).toBeNull();
+ });
+});
diff --git a/packages/ui/src/views/components/mobile-zoom-indicator/mobile-zoom-indicator.ts b/packages/ui/src/views/components/mobile-zoom-indicator/mobile-zoom-indicator.ts
new file mode 100644
index 0000000000..b11ba06739
--- /dev/null
+++ b/packages/ui/src/views/components/mobile-zoom-indicator/mobile-zoom-indicator.ts
@@ -0,0 +1,91 @@
+/**
+ * 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';
+
+export class MobileZoomIndicator extends Disposable {
+ private readonly _element: HTMLDivElement;
+ private _hideTimer: number | null = null;
+
+ constructor(private readonly _canvasElement: HTMLCanvasElement) {
+ super();
+
+ const element = document.createElement('div');
+ element.className = [
+ 'univer-absolute',
+ 'univer-left-1/2',
+ 'univer-top-1/2',
+ '-univer-translate-x-1/2',
+ '-univer-translate-y-1/2',
+ 'univer-select-none',
+ 'univer-rounded-lg',
+ 'univer-bg-gray-900',
+ 'univer-px-6',
+ 'univer-py-3',
+ 'univer-text-2xl',
+ 'univer-font-bold',
+ 'univer-text-gray-0',
+ 'univer-shadow-lg',
+ ].join(' ');
+ element.style.opacity = '0';
+ element.style.pointerEvents = 'none';
+ element.style.transition = 'opacity 150ms ease-in-out';
+ element.style.zIndex = '10000';
+ this._element = element;
+
+ this._mount();
+ }
+
+ show(percentage: number): void {
+ this._mount();
+ if (this._hideTimer != null) {
+ window.clearTimeout(this._hideTimer);
+ this._hideTimer = null;
+ }
+ this._element.textContent = `${percentage}%`;
+ this._element.style.opacity = '1';
+ }
+
+ hide(): void {
+ if (this._hideTimer != null) {
+ window.clearTimeout(this._hideTimer);
+ }
+ this._hideTimer = window.setTimeout(() => {
+ this._hideTimer = null;
+ this._element.style.opacity = '0';
+ }, 300);
+ }
+
+ override dispose(): void {
+ if (this._hideTimer != null) {
+ window.clearTimeout(this._hideTimer);
+ this._hideTimer = null;
+ }
+ this._element.remove();
+ super.dispose();
+ }
+
+ private _mount(): void {
+ const container = this._canvasElement.parentElement;
+ if (container == null || this._element.parentElement === container) {
+ return;
+ }
+ if (window.getComputedStyle(container).position === 'static') {
+ container.style.position = 'relative';
+ }
+ container.appendChild(this._element);
+ }
+}
diff --git a/packages/ui/src/views/components/popup/CanvasPopup.tsx b/packages/ui/src/views/components/popup/CanvasPopup.tsx
index dae75447f4..943813c12b 100644
--- a/packages/ui/src/views/components/popup/CanvasPopup.tsx
+++ b/packages/ui/src/views/components/popup/CanvasPopup.tsx
@@ -18,9 +18,9 @@ import type { ReactNode } from 'react';
import type { IPopup } from '../../../services/popup/canvas-popup.service';
import { useMemo } from 'react';
import { animationFrameScheduler, combineLatest, map, of, throttleTime } from 'rxjs';
-import { ComponentManager } from '../../../common';
+import { ComponentManager } from '../../../common/component-manager';
import { ICanvasPopupService } from '../../../services/popup/canvas-popup.service';
-import { connectInjector, useDependency, useObservable, useObservableRef } from '../../../utils/di';
+import { RediContext, useDependency, useObservable, useObservableRef } from '../../../utils/di';
import { RectPopup } from './RectPopup';
interface ISingleCanvasPopupProps {
@@ -107,23 +107,24 @@ export const SingleCanvasPopup = ({ popup, children }: ISingleCanvasPopupProps)
export function CanvasPopup() {
const popupService = useDependency(ICanvasPopupService);
- const componentManager = useDependency(ComponentManager);
const popups = useObservable(popupService.popups$, undefined, true);
- return popups.map((item) => {
- const [key, popup] = item;
- const Component = componentManager.get(popup.componentKey);
- const PopupComponent = Component && popup.connectorInjector
- ? connectInjector(Component, popup.connectorInjector)
- : Component;
+ return popups.map(([key, popup]) => (
+ <SingleCanvasPopup key={key} popup={popup}>
+ <CanvasPopupContent popup={popup} />
+ </SingleCanvasPopup>
+ ));
+}
- return (
- <SingleCanvasPopup
- key={key}
- popup={popup}
- >
- {PopupComponent && <PopupComponent popup={popup} />}
- </SingleCanvasPopup>
- );
- });
+function CanvasPopupContent({ popup }: { popup: IPopup }) {
+ const componentManager = useDependency(ComponentManager);
+ const Component = componentManager.get(popup.componentKey);
+ const connectorContext = useMemo(() => ({ injector: popup.connectorInjector ?? null }), [popup.connectorInjector]);
+ if (!Component) {
+ return null;
+ }
+ const content = <Component popup={popup} />;
+ return popup.connectorInjector
+ ? <RediContext.Provider value={connectorContext}>{content}</RediContext.Provider>
+ : content;
}
diff --git a/packages/ui/src/views/components/popup/__tests__/CanvasPopup.spec.tsx b/packages/ui/src/views/components/popup/__tests__/CanvasPopup.spec.tsx
index 8d39e83507..255f76c470 100644
--- a/packages/ui/src/views/components/popup/__tests__/CanvasPopup.spec.tsx
+++ b/packages/ui/src/views/components/popup/__tests__/CanvasPopup.spec.tsx
@@ -14,15 +14,17 @@
* limitations under the License.
*/
-import type { ComponentType, ReactElement } from 'react';
+import type { ReactElement } from 'react';
import type { IPopup, IPopupWithExtraProps } from '../../../../services/popup/canvas-popup.service';
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { ConfigService, IConfigService, Injector, LocaleService } from '@univerjs/core';
+import { useState } from 'react';
+import { createPortal } from 'react-dom';
import { BehaviorSubject } from 'rxjs';
import { afterEach, beforeEach, describe, expect, expectTypeOf, it } from 'vitest';
-import { ComponentManager } from '../../../../common';
+import { ComponentManager } from '../../../../common/component-manager';
import { CanvasPopupService, ICanvasPopupService } from '../../../../services/popup/canvas-popup.service';
-import { connectInjector } from '../../../../utils/di';
+import { RediContext } from '../../../../utils/di';
import { CanvasPopup } from '../CanvasPopup';
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -48,8 +50,7 @@ function renderWithDependencies(element: ReactElement) {
injector.get(ComponentManager).register('test-popup', TestPopup);
- const ConnectedTestRoot = connectInjector(() => element, injector) as ComponentType;
- const result = render(<ConnectedTestRoot />);
+ const result = render(<RediContext.Provider value={{ injector }}>{element}</RediContext.Provider>);
return {
...result,
@@ -57,6 +58,7 @@ function renderWithDependencies(element: ReactElement) {
dispose: () => {
result.unmount();
cleanup();
+ injector.dispose();
},
};
}
@@ -70,7 +72,79 @@ function createCanvasElement(rect: DOMRect): HTMLCanvasElement {
return canvasElement;
}
+function StatefulPopup() {
+ const [open, setOpen] = useState(false);
+ return <button type="button" onClick={() => setOpen(true)}>{open ? 'Style drawer opened' : 'Open styles'}</button>;
+}
+
+function PortaledPopup() {
+ const [open, setOpen] = useState(false);
+ return open
+ ? createPortal(<div role="dialog" aria-label="Table styles">Styles</div>, document.body)
+ : <button type="button" onClick={() => setOpen(true)}>Edit table</button>;
+}
+
describe('CanvasPopup', () => {
+ it('keeps an open portaled editor when resizing moves its anchor outside the canvas', async () => {
+ const rendered = renderWithDependencies(<CanvasPopup />);
+ rendered.injector.get(ComponentManager).register('portaled-popup', PortaledPopup);
+ const anchorRect$ = new BehaviorSubject({ left: 40, top: 620, right: 160, bottom: 680 });
+ let canvasRect = new DOMRect(0, 0, 390, 844);
+ const canvas = document.createElement('canvas');
+ Object.defineProperty(canvas, 'getBoundingClientRect', { value: () => canvasRect });
+ act(() => {
+ rendered.injector.get(ICanvasPopupService).addPopup({
+ unitId: 'board',
+ subUnitId: 'page',
+ componentKey: 'portaled-popup',
+ anchorRect$,
+ canvasElement: canvas,
+ hiddenType: 'hide',
+ });
+ });
+ fireEvent.click(await screen.findByRole('button', { name: 'Edit table' }));
+ await act(async () => {
+ canvasRect = new DOMRect(0, 0, 390, 500);
+ anchorRect$.next({ left: 40, top: 620, right: 160, bottom: 680 });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+ expect(screen.getByRole('dialog', { name: 'Table styles' })).toBeTruthy();
+ rendered.dispose();
+ });
+
+ it('preserves connected popup state when sibling popups change', async () => {
+ const rendered = renderWithDependencies(<CanvasPopup />);
+ const injector = rendered.injector;
+ injector.get(ComponentManager).register('stateful-popup', StatefulPopup);
+ const service = injector.get(ICanvasPopupService);
+ const popup: IPopup = {
+ unitId: 'board',
+ subUnitId: 'page',
+ componentKey: 'stateful-popup',
+ connectorInjector: injector,
+ canvasElement: createCanvasElement(new DOMRect(0, 0, 390, 844)),
+ anchorRect$: new BehaviorSubject({ left: 40, top: 60, right: 160, bottom: 100 }),
+ hideOnInvisible: false,
+ };
+ act(() => {
+ service.addPopup(popup);
+ });
+ fireEvent.click(await screen.findByRole('button', { name: 'Open styles' }));
+ expect(screen.getByRole('button', { name: 'Style drawer opened' })).toBeTruthy();
+ let sibling = '';
+ act(() => {
+ sibling = service.addPopup({ ...popup, componentKey: 'test-popup', extraProps: { label: 'Sibling' } });
+ });
+ expect(await screen.findByRole('button', { name: 'Sibling' })).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'Open styles' })).toBeNull();
+ expect(screen.getByRole('button', { name: 'Style drawer opened' })).toBeTruthy();
+ act(() => {
+ service.removePopup(sibling);
+ });
+ expect(screen.getByRole('button', { name: 'Style drawer opened' })).toBeTruthy();
+ rendered.dispose();
+ });
+
it('requires extraProps only for popups that declare them', () => {
expectTypeOf<IPopup['extraProps']>().toEqualTypeOf<Record<string, unknown> | undefined>();
expectTypeOf<IPopupWithExtraProps<{ label: string }>['extraProps']>().toEqualTypeOf<{ label: string }>();
diff --git a/packages/ui/src/views/components/ribbon/MobileRibbon.tsx b/packages/ui/src/views/components/ribbon/MobileRibbon.tsx
index 8e3760b7ca..506d6cec93 100644
--- a/packages/ui/src/views/components/ribbon/MobileRibbon.tsx
+++ b/packages/ui/src/views/components/ribbon/MobileRibbon.tsx
@@ -53,9 +53,12 @@ export function MobileRibbon(props: IMobileRibbonProps) {
const activatedTab = useObservable(ribbonService.activatedTab$, RibbonPosition.START);
const rootUnitType = useObservable(workbenchService.rootUnitType$, null, true);
- if (rootUnitType === UniverInstanceType.UNIVER_SHEET) {
+ if (
+ rootUnitType === UniverInstanceType.UNIVER_SHEET ||
+ rootUnitType === UniverInstanceType.UNIVER_DOC
+ ) {
return (
- <MobileSheetTopBar
+ <MobileCompactTopBar
ribbon={ribbon}
headerMenu={headerMenu}
headerMenuComponents={headerMenuComponents}
@@ -110,13 +113,14 @@ function MobileRibbonToolbar(props: IMobileRibbonProps & { ribbon: IMenuSchema[]
setCanScrollRight(scrollLeft + clientWidth < scrollWidth - 4);
};
- updateScrollState();
+ const animationFrame = requestAnimationFrame(updateScrollState);
const resizeObserver = new ResizeObserver(updateScrollState);
resizeObserver.observe(container);
container.addEventListener('scroll', updateScrollState, { passive: true });
return () => {
+ cancelAnimationFrame(animationFrame);
resizeObserver.disconnect();
container.removeEventListener('scroll', updateScrollState);
};
@@ -387,7 +391,7 @@ function MobileRibbonToolbar(props: IMobileRibbonProps & { ribbon: IMenuSchema[]
);
}
-function MobileSheetTopBar(props: IMobileRibbonProps & { ribbon: IMenuSchema[] }) {
+function MobileCompactTopBar(props: IMobileRibbonProps & { ribbon: IMenuSchema[] }) {
const { headerMenuComponents, headerMenu = true, ribbon } = props;
const [moreOpen, setMoreOpen] = useState(false);
const moreTriggerRef = useRef<HTMLButtonElement>(null);
@@ -419,7 +423,7 @@ function MobileSheetTopBar(props: IMobileRibbonProps & { ribbon: IMenuSchema[] }
onClick={() => setMoreOpen(false)}
/>
<div
- data-u-comp="mobile-sheet-more-menu"
+ data-u-comp="mobile-more-menu"
className={clsx(`
univer-fixed univer-z-[1400] univer-flex univer-w-60 univer-max-w-[calc(100vw-24px)] univer-flex-col
univer-gap-1 univer-rounded-2xl univer-bg-gray-0 univer-p-2 univer-shadow-lg
@@ -453,7 +457,7 @@ function MobileSheetTopBar(props: IMobileRibbonProps & { ribbon: IMenuSchema[] }
return (
<>
<div
- data-u-comp="mobile-sheet-top-bar"
+ data-u-comp="mobile-compact-top-bar"
className={clsx(`
univer-flex univer-h-12 univer-items-center univer-justify-end univer-gap-1 univer-bg-gray-0
univer-px-3
@@ -474,22 +478,11 @@ function MobileSheetTopBar(props: IMobileRibbonProps & { ribbon: IMenuSchema[] }
/>
))}
</div>
- {hasHeaderMenu && (
- <div
- className="
- univer-flex univer-items-center univer-gap-1
- [&>*]:univer-m-0 [&>*]:univer-inline-flex [&>*]:univer-min-h-10 [&>*]:univer-min-w-10
- [&>*]:univer-items-center [&>*]:univer-justify-center [&>*]:univer-rounded-lg
- "
- >
- <ComponentContainer components={headerMenuComponents!} />
- </div>
- )}
{moreItems.length > 0 && (
<button
ref={moreTriggerRef}
type="button"
- data-u-comp="mobile-sheet-more-trigger"
+ data-u-comp="mobile-more-trigger"
aria-label={localeService.t<LocaleKey>('ui.ribbon.more')}
aria-expanded={moreOpen}
className={clsx(resetButtonClassName, `
@@ -504,6 +497,17 @@ function MobileSheetTopBar(props: IMobileRibbonProps & { ribbon: IMenuSchema[] }
<MoreHorizontalIcon className="univer-size-5" preserveStrokeWidth />
</button>
)}
+ {hasHeaderMenu && (
+ <div
+ className="
+ univer-flex univer-items-center univer-gap-1
+ [&>*]:univer-m-0 [&>*]:univer-inline-flex [&>*]:univer-min-h-10 [&>*]:univer-min-w-10
+ [&>*]:univer-items-center [&>*]:univer-justify-center [&>*]:univer-rounded-lg
+ "
+ >
+ <ComponentContainer components={headerMenuComponents!} />
+ </div>
+ )}
</div>
{moreMenu}
</>
diff --git a/packages/ui/src/views/components/ribbon/__tests__/MobileRibbon.spec.tsx b/packages/ui/src/views/components/ribbon/__tests__/MobileRibbon.spec.tsx
index 8414ec1495..9af5ad11a4 100644
--- a/packages/ui/src/views/components/ribbon/__tests__/MobileRibbon.spec.tsx
+++ b/packages/ui/src/views/components/ribbon/__tests__/MobileRibbon.spec.tsx
@@ -51,4 +51,26 @@ describe('MobileRibbon', () => {
act(() => rootUnitType$.next(UniverInstanceType.UNIVER_SHEET));
}).not.toThrow();
});
+
+ it('keeps a stable hook order when the docs workbench becomes ready', () => {
+ const rootUnitType$ = new BehaviorSubject<UniverInstanceType | null>(null);
+ const injector = new Injector([
+ [LocaleService, { useValue: { t: (key: string) => key } }],
+ [IRibbonService, {
+ useValue: {
+ ribbon$: of([]),
+ activatedTab$: of(''),
+ setActivatedTab: () => {},
+ },
+ }],
+ [IWorkbenchService, { useValue: { rootUnitType$ } }],
+ ]);
+ const ConnectedMobileRibbon = connectInjector(MobileRibbon, injector);
+
+ render(<ConnectedMobileRibbon />);
+
+ expect(() => {
+ act(() => rootUnitType$.next(UniverInstanceType.UNIVER_DOC));
+ }).not.toThrow();
+ });
});
diff --git a/packages/ui/src/views/components/sidebar/MobileSidebar.tsx b/packages/ui/src/views/components/sidebar/MobileSidebar.tsx
index f0654f8607..545903ba39 100644
--- a/packages/ui/src/views/components/sidebar/MobileSidebar.tsx
+++ b/packages/ui/src/views/components/sidebar/MobileSidebar.tsx
@@ -15,8 +15,9 @@
*/
import type { LocaleKey } from '../../../locale/types';
+import type { MobilePanelLayout } from '../../mobile-workbench/MobileCanvasLayout';
import type { MobileDrawerSnap } from '../mobile-drawer/MobileDrawer';
-import type { ISidebarMethodOptions } from './Sidebar';
+import type { IRenderedSidebarOptions, ISidebarMethodOptions } from './Sidebar';
import { LocaleService } from '@univerjs/core';
import { MobileActionRowGroup } from '@univerjs/design';
import { CloseIcon } from '@univerjs/icons';
@@ -26,21 +27,30 @@ import { useDependency, useObservable } from '../../../utils/di';
import { MobileDrawer } from '../mobile-drawer/MobileDrawer';
import { renderSidebarOptions } from './Sidebar';
+export interface IMobileSidebarMethodOptions extends ISidebarMethodOptions {
+ layout?: MobilePanelLayout;
+}
+
+type IMobileRenderedSidebarOptions = IRenderedSidebarOptions & Pick<IMobileSidebarMethodOptions, 'layout'>;
+
export function MobileSidebar() {
const localeService = useDependency(LocaleService);
const sidebarService = useDependency(ISidebarService);
- const sidebarOptions = useObservable<ISidebarMethodOptions>(sidebarService.sidebarOptions$);
+ const sidebarOptions = useObservable(sidebarService.sidebarOptions$) as IMobileSidebarMethodOptions | undefined;
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]);
+ const [snapOverride, setSnapOverride] = useState<{ id?: string; snap: MobileDrawerSnap } | null>(null);
+ const options = useMemo(
+ () => renderSidebarOptions(sidebarOptions) as IMobileRenderedSidebarOptions | null,
+ [sidebarOptions]
+ );
useEffect(() => {
- if (options?.visible) {
+ if (options?.visible && options.layout !== 'canvas') {
closeButtonRef.current?.focus();
}
- }, [options?.visible]);
+ }, [options?.visible, options?.layout, options?.id]);
useEffect(() => {
const scrollElement = scrollRef.current;
@@ -56,31 +66,31 @@ export function MobileSidebar() {
if (!options?.visible) {
return null;
}
+ const defaultSnap = options.layout === 'canvas' ? 'compact' : 'expanded';
const close = () => sidebarService.close(sidebarOptions?.id);
return (
- <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')}
- className="
- 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={close}
- />
+ <div ref={layerRef} className="univer-pointer-events-none univer-fixed univer-inset-0 univer-z-[1100]" data-u-comp="mobile-sidebar">
+ {options.layout !== 'canvas' && (
+ <button
+ type="button"
+ aria-label={localeService.t<LocaleKey>('ui.sidebar.close')}
+ className="
+ univer-pointer-events-auto 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={close}
+ />
+ )}
<MobileDrawer
layerRef={layerRef}
+ layout={options.layout}
componentName="mobile-sidebar-drawer"
- snap={drawerSnap}
+ snap={snapOverride && snapOverride.id === options.id ? snapOverride.snap : defaultSnap}
expandLabel={localeService.t<LocaleKey>('ui.ribbon.more')}
collapseLabel={localeService.t<LocaleKey>('ui.ribbon.more')}
- onSnapChange={setDrawerSnap}
+ onSnapChange={(snap) => setSnapOverride({ id: options.id, snap })}
onClose={close}
role="dialog"
ariaLabel={localeService.t<LocaleKey>('ui.sidebar.panel')}
diff --git a/packages/ui/src/views/font-family/MobileFontFamilyDropdown.tsx b/packages/ui/src/views/font-family/MobileFontFamilyDropdown.tsx
new file mode 100644
index 0000000000..94a07ab2f7
--- /dev/null
+++ b/packages/ui/src/views/font-family/MobileFontFamilyDropdown.tsx
@@ -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 type { IFontFamilyDropdownProps } from './FontFamilyDropdown';
+import { LocaleService } from '@univerjs/core';
+import { clsx, MobileSelect } from '@univerjs/design';
+import { useDependency, useObservable } from '../../utils/di';
+import { useFontList } from './use-font-list';
+
+export function MobileFontFamilyDropdown(props: IFontFamilyDropdownProps) {
+ const localeService = useDependency(LocaleService);
+ const disabled = useObservable(props.disabled$);
+ const { fonts } = useFontList();
+ return (
+ <MobileSelect
+ aria-label={props.ariaLabel}
+ className={clsx('univer-h-12 univer-w-full univer-min-w-0 univer-text-base', props.className)}
+ value={props.value}
+ disabled={!!(props.disabled || disabled)}
+ options={fonts.map((font) => ({ value: font.value, label: localeService.t(font.label) }))}
+ onChange={props.onChange}
+ />
+ );
+}
diff --git a/packages/ui/src/views/menu/mobile/MobileMenu.tsx b/packages/ui/src/views/menu/mobile/MobileMenu.tsx
index ef9e0201a0..ad8ba8b798 100644
--- a/packages/ui/src/views/menu/mobile/MobileMenu.tsx
+++ b/packages/ui/src/views/menu/mobile/MobileMenu.tsx
@@ -63,6 +63,12 @@ interface IMobileMenuProps extends IBaseMenuProps {
}
export function MobileMenu(props: IMobileMenuProps) {
+ const schemaKey = props.schemas?.map((schema) => schema.key).join('|') ?? '';
+
+ return <MobileMenuContent key={`${props.menuType ?? ''}:${schemaKey}`} {...props} />;
+}
+
+function MobileMenuContent(props: IMobileMenuProps) {
const {
menuType,
onOptionSelect,
@@ -76,7 +82,6 @@ export function MobileMenu(props: IMobileMenuProps) {
const localeService = useDependency(LocaleService);
const menuManagerService = providedMenuManagerService ?? rootMenuManagerService;
const [viewStack, setViewStack] = useState<MobileMenuView[]>([]);
- const providedSchemaKey = providedSchemas?.map((schema) => schema.key).join('|');
const menuSchemaVersion$ = useMemo(() => {
return menuManagerService.menuChanged$.pipe(
@@ -84,23 +89,11 @@ export function MobileMenu(props: IMobileMenuProps) {
startWith(0)
);
}, [menuManagerService]);
- const menuSchemaVersion = useObservable(menuSchemaVersion$, 0);
-
- const menuSchemas = useMemo(() => {
- if (providedSchemas) {
- return providedSchemas;
- }
+ useObservable(menuSchemaVersion$, 0);
- if (!menuType) {
- return [];
- }
-
- return menuManagerService.getMenuByPositionKey(menuType);
- }, [providedSchemas, menuManagerService, menuSchemaVersion, menuType]);
-
- useEffect(() => {
- setViewStack([]);
- }, [menuType, providedSchemaKey]);
+ const menuSchemas = providedSchemas ?? (menuType
+ ? menuManagerService.getMenuByPositionKey(menuType)
+ : []);
const currentView = viewStack[viewStack.length - 1] ?? null;
const closeView = useCallback(() => setViewStack((stack) => stack.slice(0, -1)), []);
@@ -147,10 +140,8 @@ export function MobileMenu(props: IMobileMenuProps) {
className="
univer-flex univer-size-8 univer-appearance-none univer-items-center univer-justify-center
univer-rounded-full univer-border-0 univer-bg-transparent univer-p-0 univer-text-gray-700
- hover:univer-bg-gray-100
active:univer-bg-gray-200
dark:!univer-text-gray-300
- dark:hover:!univer-bg-gray-700
dark:active:!univer-bg-gray-600
"
onClick={closeView}
@@ -256,9 +247,10 @@ function MobileContextMenuBar(props: {
<div
role="menu"
data-u-comp="mobile-context-menu-bar"
+ style={{ maxWidth: 'min(100%, calc(100vw - 16px))' }}
className="
- univer-flex univer-h-12 univer-max-w-full univer-items-stretch univer-overflow-hidden univer-rounded-lg
- univer-bg-gray-0 univer-text-sm univer-text-gray-900 univer-shadow-lg
+ univer-flex univer-h-10 univer-max-w-full univer-items-stretch univer-overflow-hidden univer-rounded-lg
+ univer-bg-gray-0 univer-text-xs univer-text-gray-900 univer-shadow-lg
dark:!univer-bg-gray-700 dark:!univer-text-gray-0
"
>
@@ -267,7 +259,7 @@ function MobileContextMenuBar(props: {
type="button"
aria-label={localeService.t<LocaleKey>('ui.navigation.back')}
className="
- univer-flex univer-w-11 univer-shrink-0 univer-items-center univer-justify-center univer-border-0
+ univer-flex univer-w-9 univer-shrink-0 univer-items-center univer-justify-center univer-border-0
univer-border-r univer-border-solid univer-border-gray-200 univer-bg-transparent univer-text-base
univer-text-gray-700 univer-outline-none
focus-visible:univer-ring-2 focus-visible:univer-ring-inset focus-visible:univer-ring-primary-500
@@ -317,7 +309,7 @@ function MobileContextMenuBar(props: {
type="button"
aria-label={localeService.t<LocaleKey>('ui.navigation.next')}
className="
- univer-flex univer-w-11 univer-shrink-0 univer-items-center univer-justify-center univer-border-0
+ univer-flex univer-w-9 univer-shrink-0 univer-items-center univer-justify-center univer-border-0
univer-border-l univer-border-solid univer-border-gray-200 univer-bg-transparent univer-text-base
univer-text-gray-700 univer-outline-none
focus-visible:univer-ring-2 focus-visible:univer-ring-inset focus-visible:univer-ring-primary-500
@@ -355,9 +347,9 @@ function MobileContextMenuItem(props: {
role="menuitem"
disabled={interaction.disabled}
className="
- univer-flex univer-min-w-[72px] univer-shrink-0 univer-snap-start univer-items-center
+ univer-flex univer-min-w-[60px] univer-shrink-0 univer-snap-start univer-items-center
univer-justify-center univer-border-0 univer-border-r univer-border-solid univer-border-gray-200
- univer-bg-transparent univer-px-4 univer-text-sm univer-text-gray-900 univer-outline-none
+ univer-bg-transparent univer-px-3 univer-text-xs univer-text-gray-900 univer-outline-none
focus-visible:univer-ring-2 focus-visible:univer-ring-inset focus-visible:univer-ring-primary-500
enabled:active:univer-bg-gray-100
disabled:univer-opacity-40
@@ -392,9 +384,9 @@ function MobileContextMenuOption(props: {
aria-pressed={displayValue === currentValue}
disabled={disabled}
className="
- univer-flex univer-min-w-[72px] univer-shrink-0 univer-snap-start univer-items-center
+ univer-flex univer-min-w-[60px] univer-shrink-0 univer-snap-start univer-items-center
univer-justify-center univer-border-0 univer-border-r univer-border-solid univer-border-gray-200
- univer-bg-transparent univer-px-4 univer-text-sm univer-text-gray-900 univer-outline-none
+ univer-bg-transparent univer-px-3 univer-text-xs univer-text-gray-900 univer-outline-none
focus-visible:univer-ring-2 focus-visible:univer-ring-inset focus-visible:univer-ring-primary-500
enabled:active:univer-bg-gray-100
disabled:univer-opacity-40
@@ -406,7 +398,7 @@ function MobileContextMenuOption(props: {
value: displayValue,
id: menuItem.id,
label: menuKey,
- commandId: option.commandId,
+ commandId: option.commandId ?? menuItem.selectionsCommandId,
})}
>
<CustomLabel value$={option.value$} value={displayValue} label={option.label} />
@@ -464,6 +456,20 @@ function MobileSchemaList(props: {
return null;
}
+ if (schema.quickLayout) {
+ return (
+ <MobileQuickSchemaGroup
+ key={schema.key}
+ schema={schema}
+ menuManagerService={menuManagerService}
+ onExecute={onExecute}
+ onOpenView={onOpenView}
+ inheritedDisabled$={inheritedDisabled$}
+ bordered={index !== visibleSchemas.length - 1}
+ />
+ );
+ }
+
return (
<section
key={schema.key}
@@ -501,6 +507,102 @@ function MobileSchemaList(props: {
);
}
+function MobileQuickSchemaGroup(props: {
+ schema: IMenuSchema;
+ menuManagerService: IMenuManagerService;
+ onExecute?: IBaseMenuProps['onOptionSelect'];
+ onOpenView: (view: MobileMenuView) => void;
+ inheritedDisabled$?: Observable<boolean>;
+ bordered: boolean;
+}) {
+ const { schema, menuManagerService, onExecute, onOpenView, inheritedDisabled$, bordered } = props;
+ const localeService = useDependency(LocaleService);
+ const columns = Math.max(2, Math.min(schema.quickColumns ?? 4, 5));
+
+ return (
+ <section className={clsx('univer-p-3', bordered && borderBottomClassName)}>
+ {schema.title && (
+ <div
+ className="
+ univer-px-1 univer-pb-2 univer-text-sm univer-font-semibold univer-text-gray-900
+ dark:!univer-text-gray-100
+ "
+ >
+ {localeService.t(schema.title)}
+ </div>
+ )}
+ <div
+ className="univer-grid univer-gap-2"
+ style={{ gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` }}
+ >
+ {schema.children?.map((childSchema) => (
+ <MobileQuickSchemaItem
+ key={childSchema.key}
+ schema={childSchema}
+ menuManagerService={menuManagerService}
+ onExecute={onExecute}
+ onOpenView={onOpenView}
+ inheritedDisabled$={inheritedDisabled$}
+ compact={schema.quickLayoutVariant === 'compact'}
+ />
+ ))}
+ </div>
+ </section>
+ );
+}
+
+function MobileQuickSchemaItem(props: {
+ schema: IMenuSchema;
+ menuManagerService: IMenuManagerService;
+ onExecute?: IBaseMenuProps['onOptionSelect'];
+ onOpenView: (view: MobileMenuView) => void;
+ inheritedDisabled$?: Observable<boolean>;
+ compact: boolean;
+}) {
+ const { schema, menuManagerService, onExecute, onOpenView, inheritedDisabled$, compact } = props;
+ const interaction = useMobileSchemaInteraction({ schema, menuManagerService, onOpenView, inheritedDisabled$ });
+
+ if (!interaction || interaction.hidden) {
+ return null;
+ }
+
+ const { menuItem, activated, disabled, value, onPress } = interaction;
+
+ return (
+ <button
+ type="button"
+ disabled={disabled}
+ aria-pressed={menuItem.type === MenuItemType.BUTTON_SELECTOR ? activated : undefined}
+ className={clsx(`
+ univer-relative univer-flex univer-w-full univer-appearance-none univer-flex-col univer-items-center
+ univer-justify-center univer-gap-1 univer-rounded-xl univer-border-0 univer-bg-gray-50 univer-p-2
+ univer-text-center univer-text-gray-900 univer-outline-none
+ focus-visible:univer-ring-2 focus-visible:univer-ring-inset focus-visible:univer-ring-primary-500
+ enabled:active:univer-scale-[0.98] enabled:active:univer-bg-gray-100
+ disabled:univer-opacity-40
+ dark:!univer-bg-gray-700 dark:!univer-text-gray-100
+ dark:enabled:active:!univer-bg-gray-600
+ [&>span]:univer-line-clamp-2 [&>span]:univer-text-xs [&>span]:univer-font-medium
+ [&>svg]:univer-size-6 [&>svg]:univer-shrink-0
+ `, compact ? 'univer-min-h-12' : 'univer-min-h-20', activated && `
+ univer-bg-primary-50 univer-text-primary-600
+ dark:!univer-bg-primary-900 dark:!univer-text-primary-300
+ `)}
+ onClick={() => onPress(onExecute)}
+ >
+ <CustomLabel
+ value={value}
+ title={menuItem.title ?? menuItem.tooltip}
+ label={menuItem.label}
+ icon={menuItem.icon}
+ />
+ {activated && (
+ <CheckMarkIcon className="univer-absolute univer-right-1.5 univer-top-1.5 univer-size-3.5" />
+ )}
+ </button>
+ );
+}
+
function MobileSchemaRow(props: {
schema: IMenuSchema;
menuManagerService: IMenuManagerService;
@@ -575,11 +677,9 @@ function MobileSchemaRow(props: {
univer-border-0 univer-bg-gray-0 univer-px-4 univer-py-2 univer-text-left univer-outline-none
univer-transition-colors
focus-visible:univer-ring-2 focus-visible:univer-ring-inset focus-visible:univer-ring-primary-500
- enabled:hover:univer-bg-gray-50
enabled:active:univer-bg-gray-100
disabled:univer-cursor-not-allowed disabled:univer-opacity-40
dark:!univer-bg-gray-800
- dark:hover:!univer-bg-gray-700
dark:active:!univer-bg-gray-600
`,
bordered && borderBottomClassName
@@ -703,7 +803,7 @@ function MobileSelectionOptionRow(props: {
value: nextValue,
id: menuItem.id,
label: menuKey,
- commandId: option.commandId,
+ commandId: option.commandId ?? menuItem.selectionsCommandId,
});
}}
/>
@@ -721,11 +821,9 @@ function MobileSelectionOptionRow(props: {
univer-gap-3 univer-border-0 univer-bg-gray-0 univer-px-4 univer-py-2 univer-text-left
univer-outline-none univer-transition-colors
focus-visible:univer-ring-2 focus-visible:univer-ring-inset focus-visible:univer-ring-primary-500
- enabled:hover:univer-bg-gray-50
enabled:active:univer-bg-gray-100
disabled:univer-cursor-not-allowed disabled:univer-opacity-40
dark:!univer-bg-gray-800
- dark:hover:!univer-bg-gray-700
dark:active:!univer-bg-gray-600
`,
bordered && borderBottomClassName
@@ -741,7 +839,7 @@ function MobileSelectionOptionRow(props: {
value: displayValue,
id: menuItem.id,
label: menuKey,
- commandId: option.commandId,
+ commandId: option.commandId ?? menuItem.selectionsCommandId,
});
}}
>
@@ -824,7 +922,13 @@ function useMobileSchemaInteraction(props: {
const hasSubmenu = visibleSchemaChildren > 0 || selections.length > 0 || subMenuItems.length > 0;
const effectivelyDisabled = disabled || (menuItem.type === MenuItemType.SUBITEMS && !hasSubmenu);
- const currentValueText = typeof value === 'string' || typeof value === 'number' ? String(value) : '';
+ const selectedOption = selections.find((option) => option.value === value);
+ let currentValueText = '';
+ if (typeof selectedOption?.label === 'string') {
+ currentValueText = localeService.t(selectedOption.label);
+ } else if (selections.length === 0 && (typeof value === 'string' || typeof value === 'number')) {
+ currentValueText = String(value);
+ }
const onPress = (onExecute?: IBaseMenuProps['onOptionSelect']) => {
if (effectivelyDisabled) {
@@ -832,7 +936,7 @@ function useMobileSchemaInteraction(props: {
}
if (schemaChildren.length > 0) {
- const schemas = menuItem.type === MenuItemType.BUTTON_SELECTOR && selections.length === 0
+ const schemas = menuItem.type === MenuItemType.BUTTON_SELECTOR
? [{ ...schema, children: undefined }, ...schemaChildren]
: schemaChildren;
onOpenView({
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 3bcf125556..8533f9f12d 100644
--- a/packages/ui/src/views/menu/mobile/__tests__/MobileMenu.spec.tsx
+++ b/packages/ui/src/views/menu/mobile/__tests__/MobileMenu.spec.tsx
@@ -28,19 +28,23 @@ import {
} from '@univerjs/core';
import { BehaviorSubject } from 'rxjs';
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { ComponentManager, IconManager } from '../../../../common';
+import { ComponentManager } from '../../../../common/component-manager';
+import { IconManager } from '../../../../common/icon-manager';
import enUS from '../../../../locale/en-US';
import { MenuItemType } from '../../../../services/menu/menu';
import { IMenuManagerService, MenuManagerService } from '../../../../services/menu/menu-manager.service';
import { RediProvider } from '../../../../utils/di';
import { MobileMenu } from '../MobileMenu';
+const injectors: Injector[] = [];
+
function renderWithDependencies(
schemas: IMenuSchema[],
onOptionSelect: NonNullable<ComponentProps<typeof MobileMenu>['onOptionSelect']>,
props?: Pick<ComponentProps<typeof MobileMenu>, 'showHeader' | 'onNavigationChange' | 'presentation'>
) {
const injector = new Injector();
+ injectors.push(injector);
injector.add([IConfigService, { useClass: ConfigService }]);
injector.add([LocaleService]);
injector.get(LocaleService).load({ [LocaleType.EN_US]: enUS });
@@ -72,9 +76,118 @@ function renderWithDependencies(
};
}
-afterEach(cleanup);
+afterEach(() => {
+ cleanup();
+ injectors.splice(0).forEach((injector) => injector.dispose());
+});
describe('MobileMenu', () => {
+ it('shows the selected option label instead of its persisted identifier', () => {
+ const value$ = new BehaviorSubject('wideScreen16By9');
+ renderWithDependencies([{
+ key: 'size',
+ order: 0,
+ item: {
+ id: 'size',
+ type: MenuItemType.SELECTOR,
+ title: 'Page size',
+ value$,
+ selections: [
+ { value: 'wideScreen16By9', label: 'Widescreen (16:9)' },
+ { value: 'standard4By3', label: 'Standard (4:3)' },
+ ],
+ },
+ }], vi.fn());
+ expect(screen.getByRole('button', { name: 'Page size Widescreen (16:9)' })).toBeTruthy();
+ act(() => value$.next('standard4By3'));
+ expect(screen.getByRole('button', { name: 'Page size Standard (4:3)' })).toBeTruthy();
+ expect(screen.queryByText('wideScreen16By9')).toBeNull();
+ });
+
+ it('does not expose a custom picker internal identifier as its current label', () => {
+ renderWithDependencies([{
+ key: 'theme',
+ order: 0,
+ item: {
+ id: 'theme',
+ type: MenuItemType.SELECTOR,
+ title: 'Theme',
+ value$: new BehaviorSubject('office'),
+ selections: [{ label: { name: 'plain-custom-label', selectable: false } }],
+ },
+ }], vi.fn());
+ expect(screen.getByRole('button', { name: 'Theme' })).toBeTruthy();
+ expect(screen.queryByText('office')).toBeNull();
+ });
+
+ it.each(['drawer', 'context-bar'] as const)('preserves selection commands and option overrides in %s', (presentation) => {
+ const onOptionSelect = vi.fn();
+ renderWithDependencies([{
+ key: 'insert',
+ order: 0,
+ item: {
+ id: 'insert.menu',
+ type: MenuItemType.SELECTOR,
+ title: 'Insert',
+ selectionsCommandId: 'insert.command',
+ selections: [
+ { label: 'Basic', value: 'basic' },
+ { label: 'Special', value: 'special', commandId: 'special.command' },
+ ],
+ },
+ }], onOptionSelect, { presentation });
+ fireEvent.click(screen.getByRole(presentation === 'drawer' ? 'button' : 'menuitem', { name: 'Insert' }));
+ fireEvent.click(screen.getByRole(presentation === 'drawer' ? 'button' : 'menuitem', { name: 'Basic' }));
+ expect(onOptionSelect).toHaveBeenLastCalledWith(expect.objectContaining({ commandId: 'insert.command', value: 'basic' }));
+ fireEvent.click(screen.getByRole(presentation === 'drawer' ? 'button' : 'menuitem', { name: 'Special' }));
+ expect(onOptionSelect).toHaveBeenLastCalledWith(expect.objectContaining({ commandId: 'special.command', value: 'special' }));
+ });
+
+ it('forwards a custom picker value to its selector command', () => {
+ const onOptionSelect = vi.fn();
+ renderWithDependencies([{
+ key: 'picker',
+ order: 0,
+ item: {
+ id: 'picker.menu',
+ type: MenuItemType.SELECTOR,
+ title: 'Picker',
+ selectionsCommandId: 'picker.command',
+ selections: [{ label: { name: 'interactive-button-label' }, value: 0 }],
+ },
+ }], onOptionSelect);
+ fireEvent.click(screen.getByRole('button', { name: 'Picker' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Increase' }));
+ expect(onOptionSelect).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ commandId: 'picker.command', value: 1 }));
+ });
+
+ it('renders quick-layout groups as touch-friendly tiles', () => {
+ const onOptionSelect = vi.fn();
+ renderWithDependencies([{
+ key: 'common',
+ order: 0,
+ title: 'Common',
+ quickLayout: 'tile',
+ quickColumns: 3,
+ children: [{
+ key: 'image',
+ order: 0,
+ item: { id: 'image', type: MenuItemType.BUTTON, title: 'Image' },
+ }, {
+ key: 'table',
+ order: 1,
+ item: { id: 'table', type: MenuItemType.BUTTON, title: 'Table' },
+ }],
+ }], onOptionSelect);
+
+ expect(screen.getByText('Common')).toBeTruthy();
+ const image = screen.getByRole('button', { name: 'Image' });
+ expect(image.className).toContain('univer-min-h-20');
+ expect(image.parentElement?.getAttribute('style')).toContain('repeat(3');
+ fireEvent.click(image);
+ expect(onOptionSelect).toHaveBeenCalledWith(expect.objectContaining({ id: 'image' }));
+ });
+
it('renders grouped context menu items as a horizontal text-only bar', () => {
const onOptionSelect = vi.fn();
renderWithDependencies([{
@@ -99,7 +212,11 @@ describe('MobileMenu', () => {
const bar = document.querySelector('[data-u-comp="mobile-context-menu-bar"]');
const copy = screen.getByRole('menuitem', { name: 'Copy' });
expect(bar).toBeTruthy();
+ expect(bar?.className).toContain('univer-h-10');
+ expect(bar?.className).toContain('univer-text-xs');
expect(copy.querySelector('svg')).toBeNull();
+ expect(copy.className).toContain('univer-min-w-[60px]');
+ expect(copy.className).toContain('univer-px-3');
expect(copy.className).toContain('univer-snap-start');
expect(copy.className).toContain('univer-outline-none');
@@ -326,6 +443,37 @@ describe('MobileMenu', () => {
expect(toggle.getAttribute('aria-pressed')).toBe('true');
});
+ it('keeps button-selector choices available beside auxiliary submenu items', () => {
+ const onOptionSelect = vi.fn();
+
+ renderWithDependencies([{
+ key: 'color',
+ order: 0,
+ item: {
+ id: 'color.menu',
+ type: MenuItemType.BUTTON_SELECTOR,
+ title: 'Color',
+ value$: new BehaviorSubject('black'),
+ selections: [{ label: 'Black', value: 'black', commandId: 'color.command' }],
+ },
+ children: [{
+ key: 'color.reset',
+ order: 0,
+ item: { id: 'color.reset', type: MenuItemType.BUTTON, title: 'Reset' },
+ }],
+ }], onOptionSelect);
+
+ fireEvent.click(screen.getByRole('button', { name: /Color/ }));
+ fireEvent.click(screen.getByRole('button', { name: /Color/ }));
+ fireEvent.click(screen.getByRole('button', { name: 'Black' }));
+
+ expect(onOptionSelect).toHaveBeenCalledWith(expect.objectContaining({
+ id: 'color.menu',
+ commandId: 'color.command',
+ value: 'black',
+ }));
+ });
+
it('executes every supported actionable menu type with its command metadata', () => {
const onOptionSelect = vi.fn();
renderWithDependencies([
diff --git a/packages/ui/src/views/mobile-workbench/MobileCanvasLayout.tsx b/packages/ui/src/views/mobile-workbench/MobileCanvasLayout.tsx
new file mode 100644
index 0000000000..5c1f28805a
--- /dev/null
+++ b/packages/ui/src/views/mobile-workbench/MobileCanvasLayout.tsx
@@ -0,0 +1,208 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ReactElement, ReactNode, RefObject } from 'react';
+import { createContext, useCallback, useContext, useLayoutEffect, useMemo, useRef, useState } from 'react';
+
+export type MobilePanelLayout = 'canvas' | 'modal';
+
+interface IMobileCanvasPanel {
+ ref: RefObject<HTMLElement | null>;
+ layout: MobilePanelLayout;
+ dragging: boolean;
+}
+
+const MobileCanvasLayoutContext = createContext<{
+ panels: IMobileCanvasPanel[];
+ register: (panel: IMobileCanvasPanel) => () => void;
+} | null>(null);
+
+const MOBILE_CANVAS_VISIBLE_RATIO = 0.4;
+
+export function MobileCanvasLayoutProvider({ children }: { children: ReactNode }): ReactElement {
+ const [panels, setPanels] = useState<IMobileCanvasPanel[]>([]);
+ const register = useCallback((panel: IMobileCanvasPanel) => {
+ setPanels((current) => [...current, panel]);
+ return () => setPanels((current) => current.filter((item) => item !== panel));
+ }, []);
+ const value = useMemo(() => ({ panels, register }), [panels, register]);
+ return <MobileCanvasLayoutContext.Provider value={value}>{children}</MobileCanvasLayoutContext.Provider>;
+}
+
+/** Register the actual surface, not its full-screen portal container. */
+export function useMobileCanvasPanel(
+ ref: RefObject<HTMLElement | null>,
+ layout: MobilePanelLayout,
+ dragging = false
+): void {
+ const register = useContext(MobileCanvasLayoutContext)?.register;
+ useLayoutEffect(() => {
+ if (ref.current && register) {
+ return register({ ref, layout, dragging });
+ }
+ }, [ref, register, layout, dragging]);
+}
+
+/** Connect design-layer overlay surfaces to the current workbench layout. */
+export function useMobileOverlayRegistration(layout: MobilePanelLayout): (element: HTMLElement) => void | (() => void) {
+ const register = useContext(MobileCanvasLayoutContext)?.register;
+ return useCallback((element: HTMLElement) => register?.({ ref: { current: element }, layout, dragging: false }), [register, layout]);
+}
+
+/** Minimal viewport translation in CSS pixels. Large objects keep their leading edge visible. */
+export function getMobileCanvasPanDelta(
+ target: Pick<DOMRect, 'left' | 'top' | 'width' | 'height'>,
+ viewport: Pick<DOMRect, 'width' | 'height'>
+): { x: number; y: number } {
+ const reveal = (start: number, size: number, available: number) => {
+ const margin = Math.min(16, available / 4);
+ const end = start + Math.min(size, available - margin * 2);
+ if (start < margin) {
+ return margin - start;
+ }
+ return end > available - margin ? available - margin - end : 0;
+ };
+ return { x: reveal(target.left, target.width, viewport.width), y: reveal(target.top, target.height, viewport.height) };
+}
+
+/**
+ * Opt-in canvas host. Panels remain outside the resizable inner element so their
+ * measurement cannot feed back into their own containing block. No focus or zoom
+ * changes are performed here; each renderer owns its viewport translation.
+ */
+export function useMobileCanvasViewport(options: {
+ containerRef: RefObject<HTMLElement | null>;
+ canvasRef: RefObject<HTMLElement | null>;
+ enabled?: boolean;
+ /** Preserve the document's own keyboard viewport handling outside object panels. */
+ panelsOnly?: boolean;
+ onReveal: () => void;
+}): void {
+ const { containerRef, canvasRef, enabled = true, panelsOnly = false, onReveal } = options;
+ const context = useContext(MobileCanvasLayoutContext);
+ const revealRef = useRef(onReveal);
+ useLayoutEffect(() => {
+ revealRef.current = onReveal;
+ }, [onReveal]);
+ const previousHeightRef = useRef<number | null>(null);
+ const needsRevealRef = useRef(false);
+
+ useLayoutEffect(() => {
+ const container = containerRef.current;
+ const canvas = canvasRef.current;
+ if (!context || !enabled || !container || !canvas) {
+ return;
+ }
+
+ const panels = context.panels.flatMap(({ ref, layout, dragging }) =>
+ ref.current ? [{ element: ref.current, layout, dragging }] : []);
+ if (panelsOnly && !panels.some((panel) => panel.layout === 'canvas')) {
+ previousHeightRef.current = null;
+ needsRevealRef.current = false;
+ return;
+ }
+ const viewport = window.visualViewport;
+ let frame = 0;
+ let settleFrame = 0;
+ const originalHeight = canvas.style.height;
+ const originalBottom = canvas.style.bottom;
+ const originalTop = canvas.style.top;
+ const panelStyles = panels.map(({ element }) => ({
+ element,
+ bottom: element.style.bottom,
+ maxHeight: element.style.maxHeight,
+ }));
+
+ const settle = () => {
+ cancelAnimationFrame(settleFrame);
+ settleFrame = requestAnimationFrame(() => {
+ settleFrame = requestAnimationFrame(() => {
+ if (needsRevealRef.current && !panels.some((panel) => panel.dragging)) {
+ needsRevealRef.current = false;
+ revealRef.current();
+ }
+ });
+ });
+ };
+ const measure = () => {
+ const bounds = container.getBoundingClientRect();
+ const modal = panels.some((panel) => panel.layout === 'modal');
+ const visibleBottom = viewport ? viewport.offsetTop + viewport.height : window.innerHeight;
+ const top = modal ? bounds.top : Math.max(bounds.top, viewport?.offsetTop ?? 0);
+ let bottom = modal ? bounds.bottom : Math.min(bounds.bottom, visibleBottom);
+ const panelMaxHeight = Math.max(0, bottom - top) * (1 - MOBILE_CANVAS_VISIBLE_RATIO);
+ if (!modal) {
+ for (const { element, layout } of panels) {
+ if (layout !== 'canvas') {
+ continue;
+ }
+ const containingBlock = element.offsetParent;
+ const parentBottom = getComputedStyle(element).position === 'fixed' || !containingBlock
+ ? window.innerHeight
+ : containingBlock.getBoundingClientRect().bottom;
+ element.style.bottom = `${Math.max(0, parentBottom - visibleBottom)}px`;
+ element.style.maxHeight = `${panelMaxHeight}px`;
+ const rect = element.getBoundingClientRect();
+ if (rect.right > bounds.left && rect.left < bounds.right && rect.bottom > bounds.top) {
+ bottom = Math.min(bottom, rect.top);
+ }
+ }
+ }
+ const height = Math.max(0, bottom - top);
+ const oldHeight = previousHeightRef.current ?? bounds.height;
+ if (modal || height > oldHeight + 1) {
+ needsRevealRef.current = false;
+ }
+ needsRevealRef.current ||= !modal && height < oldHeight - 1;
+ previousHeightRef.current = height;
+ canvas.style.bottom = 'auto';
+ canvas.style.top = `${top - bounds.top}px`;
+ canvas.style.height = `${height}px`;
+ settle();
+ };
+ const schedule = () => {
+ cancelAnimationFrame(frame);
+ frame = requestAnimationFrame(measure);
+ };
+ const observer = new ResizeObserver(schedule);
+ const cancelReveal = () => {
+ needsRevealRef.current = false;
+ };
+ canvas.addEventListener('pointerdown', cancelReveal);
+ observer.observe(container);
+ panels.forEach(({ element }) => observer.observe(element));
+ viewport?.addEventListener('resize', schedule);
+ viewport?.addEventListener('scroll', schedule);
+ window.addEventListener('resize', schedule);
+ measure();
+ return () => {
+ observer.disconnect();
+ canvas.removeEventListener('pointerdown', cancelReveal);
+ cancelAnimationFrame(frame);
+ cancelAnimationFrame(settleFrame);
+ viewport?.removeEventListener('resize', schedule);
+ viewport?.removeEventListener('scroll', schedule);
+ window.removeEventListener('resize', schedule);
+ canvas.style.height = originalHeight;
+ canvas.style.bottom = originalBottom;
+ canvas.style.top = originalTop;
+ panelStyles.forEach(({ element, bottom, maxHeight }) => {
+ element.style.bottom = bottom;
+ element.style.maxHeight = maxHeight;
+ });
+ };
+ }, [context, enabled, panelsOnly, containerRef, canvasRef]);
+}
diff --git a/packages/ui/src/views/mobile-workbench/MobileWorkbench.tsx b/packages/ui/src/views/mobile-workbench/MobileWorkbench.tsx
index 875551026b..fab5c6e14d 100644
--- a/packages/ui/src/views/mobile-workbench/MobileWorkbench.tsx
+++ b/packages/ui/src/views/mobile-workbench/MobileWorkbench.tsx
@@ -31,6 +31,26 @@ import { MobileDrawerCoordinatorProvider } from '../components/mobile-drawer/Mob
import { MobileSidebar } from '../components/sidebar/MobileSidebar';
import { WorkbenchSkeleton } from '../components/workbench-skeleton/WorkbenchSkeleton';
import { MobileKeyboardInsetContext } from './mobile-keyboard-inset-context';
+import { MobileCanvasLayoutProvider } from './MobileCanvasLayout';
+
+const MOBILE_KEYBOARD_THRESHOLD = 80;
+
+export function resolveMobileKeyboardInset(stableHeight: number, visibleBottom: number, baselineInset: number): number {
+ const keyboardInset = Math.max(0, Math.round(stableHeight - visibleBottom) - baselineInset);
+ return keyboardInset >= MOBILE_KEYBOARD_THRESHOLD ? keyboardInset : 0;
+}
+
+export function shouldUpdateMobileStableHeight(
+ stableHeight: number,
+ nextHeight: number,
+ stableWidth: number,
+ nextWidth: number,
+ editing: boolean,
+ keyboardVisible: boolean
+): boolean {
+ return nextWidth !== stableWidth ||
+ (!editing && !keyboardVisible && stableHeight - nextHeight < MOBILE_KEYBOARD_THRESHOLD);
+}
export interface IUniverAppProps extends IWorkbenchOptions {
mountContainer: HTMLElement;
@@ -75,6 +95,7 @@ export function MobileWorkbench(props: IUniverAppProps) {
const themeSwitcherService = useDependency(ThemeSwitcherService);
const contentRef = useRef<HTMLDivElement>(null);
+ const canvasContainerRef = useRef<HTMLDivElement>(null);
const viewportRef = useRef<HTMLDivElement>(null);
const [keyboardInset, setKeyboardInset] = useState(0);
@@ -143,22 +164,59 @@ export function MobileWorkbench(props: IUniverAppProps) {
let stableHeight = Math.round(mountContainer.getBoundingClientRect().height || window.innerHeight);
let stableWidth = Math.round(mountContainer.getBoundingClientRect().width || window.innerWidth);
+ let baselineInset = Math.max(0, stableHeight - Math.round(
+ visualViewport ? visualViewport.offsetTop + visualViewport.height : window.innerHeight
+ ));
+ let keyboardVisible = false;
+
+ const isEditing = () => {
+ const activeElement = document.activeElement;
+ return activeElement instanceof HTMLInputElement ||
+ activeElement instanceof HTMLTextAreaElement ||
+ activeElement?.getAttribute('contenteditable') === 'true';
+ };
const updateKeyboardInset = () => {
const visibleBottom = visualViewport
? visualViewport.offsetTop + visualViewport.height
: window.innerHeight;
- setKeyboardInset(Math.max(0, Math.round(stableHeight - visibleBottom)));
+ const viewportInset = Math.max(0, Math.round(stableHeight - visibleBottom));
+ const keyboardInset = resolveMobileKeyboardInset(stableHeight, visibleBottom, baselineInset);
+ const editing = isEditing();
+
+ if (!editing) {
+ keyboardVisible = false;
+ if (keyboardInset === 0) {
+ baselineInset = viewportInset;
+ }
+ } else if (keyboardInset > 0) {
+ keyboardVisible = true;
+ } else if (keyboardVisible && keyboardInset === 0) {
+ keyboardVisible = false;
+ baselineInset = viewportInset;
+ }
+
+ viewportElement.style.setProperty(
+ '--univer-mobile-keyboard-inset',
+ `${keyboardVisible ? keyboardInset : 0}px`
+ );
+
+ setKeyboardInset(keyboardVisible ? keyboardInset : 0);
};
const updateStableViewport = () => {
+ const height = Math.round(mountContainer.getBoundingClientRect().height || window.innerHeight);
const width = Math.round(mountContainer.getBoundingClientRect().width || window.innerWidth);
- const activeElement = document.activeElement;
- const editing = activeElement instanceof HTMLInputElement ||
- activeElement instanceof HTMLTextAreaElement ||
- activeElement?.getAttribute('contenteditable') === 'true';
+ const editing = isEditing();
- if (!editing || width !== stableWidth) {
- stableHeight = Math.round(mountContainer.getBoundingClientRect().height || window.innerHeight);
+ if (shouldUpdateMobileStableHeight(
+ stableHeight,
+ height,
+ stableWidth,
+ width,
+ editing,
+ keyboardVisible
+ )) {
+ stableHeight = height;
stableWidth = width;
viewportElement.style.height = `${stableHeight}px`;
}
@@ -185,110 +243,122 @@ export function MobileWorkbench(props: IUniverAppProps) {
direction={direction}
mountContainer={portalContainer}
>
- <MobileKeyboardInsetContext.Provider value={keyboardInset}>
- <MobileDrawerCoordinatorProvider>
- <div
- ref={viewportRef}
- className="
- univer-relative univer-h-full univer-min-h-0
- [&_button:active]:!univer-opacity-70
- [&_button]:univer-touch-manipulation
- "
- >
+ <MobileCanvasLayoutProvider>
+ <MobileKeyboardInsetContext.Provider value={keyboardInset}>
+ <MobileDrawerCoordinatorProvider>
<div
- data-u-comp="app-layout"
- className={clsx(`
- univer-relative univer-flex univer-h-full univer-min-h-0 univer-flex-col univer-bg-gray-0
- dark:!univer-bg-gray-800
- `, {
- 'univer-dark': darkMode,
- })}
- tabIndex={-1}
- onBlur={(e) => e.stopPropagation()}
- onContextMenu={(e) => e.preventDefault()}
- dir={direction}
+ ref={viewportRef}
+ className="
+ univer-relative univer-h-full univer-min-h-0
+ [&_button:active]:!univer-opacity-70
+ [&_button]:univer-touch-manipulation
+ "
>
- {/* header */}
- {header && toolbar && (
- <header
- data-u-comp="headerbar"
- className="univer-relative univer-z-10 univer-w-full univer-overflow-hidden"
- >
- <ComponentContainer
- key="toolbar"
- components={toolbarComponents}
- sharedProps={{
- ribbonType,
- headerMenuComponents,
- headerMenu,
- }}
- />
- </header>
- )}
-
- {/* content */}
- <section
- className="univer-relative univer-flex univer-min-h-0 univer-flex-1 univer-flex-col"
+ <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}
>
- <div
- className={`
- univer-grid univer-h-full univer-grid-cols-[auto_1fr_auto] univer-grid-rows-[100%]
- univer-overflow-hidden
- `}
+ {/* 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"
>
- <aside className="univer-h-full">
- <ComponentContainer key="left-sidebar" components={leftSidebarComponents} />
- </aside>
-
- <section
- className={clsx(`
- univer-relative univer-grid univer-flex-1 univer-grid-rows-[auto_1fr]
- univer-overflow-hidden univer-bg-gray-0
- dark:!univer-bg-gray-800
- `, borderBottomClassName)}
+ <div
+ className={`
+ univer-grid univer-min-h-0 univer-flex-1 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={canvasContainerRef}
+ className="univer-relative univer-min-h-0 univer-overflow-hidden"
+ >
+ <div
+ ref={contentRef}
+ className="univer-absolute univer-inset-0 univer-overflow-hidden"
+ data-range-selector
+ onContextMenu={(e) => e.preventDefault()}
+ >
+ <ComponentContainer
+ key="content"
+ components={contentComponents}
+ sharedProps={{ containerRef: canvasContainerRef, canvasRef: contentRef }}
+ />
+ </div>
+ </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 className="univer-shrink-0">
+ <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>
- </MobileKeyboardInsetContext.Provider>
+ </MobileDrawerCoordinatorProvider>
+ </MobileKeyboardInsetContext.Provider>
+ </MobileCanvasLayoutProvider>
</ConfigProvider>
);
}
diff --git a/packages/ui/src/views/mobile-workbench/__tests__/MobileCanvasLayout.spec.tsx b/packages/ui/src/views/mobile-workbench/__tests__/MobileCanvasLayout.spec.tsx
new file mode 100644
index 0000000000..2b911f278b
--- /dev/null
+++ b/packages/ui/src/views/mobile-workbench/__tests__/MobileCanvasLayout.spec.tsx
@@ -0,0 +1,227 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/** @vitest-environment jsdom */
+
+import type { MobilePanelLayout } from '../MobileCanvasLayout';
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { useRef } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ getMobileCanvasPanDelta,
+ MobileCanvasLayoutProvider,
+ useMobileCanvasPanel,
+ useMobileCanvasViewport,
+} from '../MobileCanvasLayout';
+
+describe('mobile canvas layout', () => {
+ const reveal = vi.fn();
+ let panelTop = 540;
+ let viewportHeight = 900;
+ const viewportEvents = new EventTarget();
+ const resizeCallbacks = new Set<() => void>();
+
+ function Panel({ layout, dragging }: { layout: MobilePanelLayout; dragging?: boolean }) {
+ const ref = useRef<HTMLDivElement>(null);
+ useMobileCanvasPanel(ref, layout, dragging);
+ return <div ref={ref} role="region" aria-label="panel"><input aria-label="editor" /></div>;
+ }
+
+ function Canvas({ panelsOnly, enabled }: { panelsOnly?: boolean; enabled?: boolean }) {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const canvasRef = useRef<HTMLDivElement>(null);
+ useMobileCanvasViewport({ containerRef, canvasRef, panelsOnly, enabled, onReveal: reveal });
+ return <div ref={containerRef} role="region" aria-label="host"><div ref={canvasRef} role="region" aria-label="canvas" /></div>;
+ }
+
+ function App({ layout, dragging, panelsOnly, enabled }: { layout?: MobilePanelLayout; dragging?: boolean; panelsOnly?: boolean; enabled?: boolean }) {
+ return (
+ <MobileCanvasLayoutProvider>
+ <Canvas panelsOnly={panelsOnly} enabled={enabled} />
+ {layout && <Panel layout={layout} dragging={dragging} />}
+ </MobileCanvasLayoutProvider>
+ );
+ }
+
+ function flush() {
+ act(() => {
+ vi.advanceTimersByTime(100);
+ });
+ }
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ reveal.mockClear();
+ panelTop = 540;
+ viewportHeight = 900;
+ resizeCallbacks.clear();
+ vi.stubGlobal('innerHeight', 900);
+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => window.setTimeout(() => callback(0), 16));
+ vi.stubGlobal('cancelAnimationFrame', (id: number) => window.clearTimeout(id));
+ vi.stubGlobal('ResizeObserver', class {
+ constructor(private readonly callback: () => void) { resizeCallbacks.add(callback); }
+ observe() {}
+ disconnect() { resizeCallbacks.delete(this.callback); }
+ });
+ vi.stubGlobal('visualViewport', {
+ offsetTop: 0,
+ get height() { return viewportHeight; },
+ addEventListener: viewportEvents.addEventListener.bind(viewportEvents),
+ removeEventListener: viewportEvents.removeEventListener.bind(viewportEvents),
+ });
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) {
+ if (this.getAttribute('aria-label') === 'host') return new DOMRect(0, 44, 430, 856);
+ if (this.getAttribute('aria-label') === 'panel') {
+ const bottom = Number.parseFloat(this.style.bottom) || 0;
+ return new DOMRect(0, panelTop - bottom, 430, 900 - panelTop);
+ }
+ return new DOMRect(0, 0, 430, 900);
+ });
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+ });
+
+ it('resizes for an object panel and only reveals when the available area shrinks', () => {
+ const view = render(<App />);
+ expect(screen.getByRole('region', { name: 'canvas' }).style.height).toBe('856px');
+ view.rerender(<App layout="canvas" />);
+ flush();
+ expect(screen.getByRole('region', { name: 'canvas' }).style.height).toBe('496px');
+ expect(reveal).toHaveBeenCalledTimes(1);
+ act(() => resizeCallbacks.forEach((callback) => callback()));
+ flush();
+ expect(reveal).toHaveBeenCalledTimes(1);
+ view.rerender(<App />);
+ flush();
+ expect(screen.getByRole('region', { name: 'canvas' }).style.height).toBe('856px');
+ expect(reveal).toHaveBeenCalledTimes(1);
+ });
+
+ it('only resizes the canvas while its owning product enables the viewport', () => {
+ const view = render(<App panelsOnly enabled={false} layout="canvas" />);
+ const canvas = screen.getByRole('region', { name: 'canvas' });
+ flush();
+ expect(canvas.style.height).toBe('');
+ expect(reveal).not.toHaveBeenCalled();
+
+ view.rerender(<App panelsOnly enabled layout="canvas" />);
+ flush();
+ expect(canvas.style.height).toBe('496px');
+ expect(reveal).toHaveBeenCalledTimes(1);
+
+ view.rerender(<App panelsOnly enabled={false} layout="canvas" />);
+ act(() => resizeCallbacks.forEach((callback) => callback()));
+ flush();
+ expect(canvas.style.height).toBe('');
+ expect(canvas.style.top).toBe('');
+ expect(canvas.style.bottom).toBe('');
+ expect(reveal).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps the canvas unchanged for global settings', () => {
+ render(<App layout="modal" />);
+ viewportHeight = 500;
+ act(() => viewportEvents.dispatchEvent(new Event('resize')));
+ flush();
+ expect(screen.getByRole('region', { name: 'canvas' }).style.height).toBe('856px');
+ expect(reveal).not.toHaveBeenCalled();
+ });
+
+ it('leaves document keyboard layout alone outside object panels and restores the host on close', () => {
+ const view = render(<App panelsOnly />);
+ const canvas = screen.getByRole('region', { name: 'canvas' });
+ viewportHeight = 700;
+ act(() => viewportEvents.dispatchEvent(new Event('resize')));
+ flush();
+ expect(canvas.style.height).toBe('');
+ view.rerender(<App panelsOnly layout="canvas" />);
+ flush();
+ expect(canvas.style.height).toBe('296px');
+ expect(reveal).toHaveBeenCalledTimes(1);
+ view.rerender(<App panelsOnly />);
+ flush();
+ expect(canvas.style.height).toBe('');
+ expect(canvas.style.top).toBe('');
+ expect(canvas.style.bottom).toBe('');
+ view.rerender(<App panelsOnly layout="modal" />);
+ flush();
+ expect(canvas.style.height).toBe('');
+ expect(reveal).toHaveBeenCalledTimes(1);
+ });
+
+ it('counts keyboard and panel geometry once and retains input focus over repeated keyboard cycles', () => {
+ render(<App layout="canvas" />);
+ const input = screen.getByRole('textbox', { name: 'editor' });
+ input.focus();
+ for (let cycle = 0; cycle < 6; cycle++) {
+ viewportHeight = 700;
+ act(() => viewportEvents.dispatchEvent(new Event('resize')));
+ flush();
+ expect(screen.getByRole('region', { name: 'canvas' }).style.height).toBe('296px');
+ expect(document.activeElement).toBe(input);
+ viewportHeight = 900;
+ act(() => viewportEvents.dispatchEvent(new Event('resize')));
+ flush();
+ expect(screen.getByRole('region', { name: 'canvas' }).style.height).toBe('496px');
+ expect(document.activeElement).toBe(input);
+ }
+ });
+
+ it('resizes during drawer dragging but reveals only after release', () => {
+ const view = render(<App layout="canvas" dragging />);
+ flush();
+ expect(reveal).not.toHaveBeenCalled();
+ panelTop = 450;
+ act(() => resizeCallbacks.forEach((callback) => callback()));
+ flush();
+ expect(screen.getByRole('region', { name: 'canvas' }).style.height).toBe('406px');
+ expect(reveal).not.toHaveBeenCalled();
+ view.rerender(<App layout="canvas" />);
+ flush();
+ expect(reveal).toHaveBeenCalledTimes(1);
+ });
+
+ it('positions nested absolute panels against their containing block', () => {
+ render(<App layout="canvas" />);
+ const panel = screen.getByRole('region', { name: 'panel' });
+ const host = screen.getByRole('region', { name: 'host' });
+ Object.defineProperty(panel, 'offsetParent', { value: host });
+ viewportHeight = 700;
+ act(() => viewportEvents.dispatchEvent(new Event('resize')));
+ flush();
+ expect(panel.style.bottom).toBe('200px');
+ expect(screen.getByRole('region', { name: 'canvas' }).style.height).toBe('296px');
+ });
+
+ it('does not fight a manual canvas gesture with a pending reveal', () => {
+ render(<App layout="canvas" />);
+ fireEvent.pointerDown(screen.getByRole('region', { name: 'canvas' }));
+ flush();
+ expect(reveal).not.toHaveBeenCalled();
+ });
+
+ it('only pans hidden targets and retains scale-independent distances', () => {
+ const viewport = { width: 430, height: 400 };
+ expect(getMobileCanvasPanDelta({ left: 20, top: 20, width: 100, height: 80 }, viewport)).toEqual({ x: 0, y: 0 });
+ expect(getMobileCanvasPanDelta({ left: 20, top: 350, width: 100, height: 80 }, viewport)).toEqual({ x: 0, y: -46 });
+ expect(getMobileCanvasPanDelta({ left: 100, top: 350, width: 800, height: 600 }, viewport)).toEqual({ x: -84, y: -334 });
+ });
+});
diff --git a/packages/ui/src/views/mobile-workbench/__tests__/MobileWorkbench.spec.tsx b/packages/ui/src/views/mobile-workbench/__tests__/MobileWorkbench.spec.tsx
index 2484f9b9b0..22ba61121d 100644
--- a/packages/ui/src/views/mobile-workbench/__tests__/MobileWorkbench.spec.tsx
+++ b/packages/ui/src/views/mobile-workbench/__tests__/MobileWorkbench.spec.tsx
@@ -44,7 +44,7 @@ import { ISidebarService } from '../../../services/sidebar/sidebar.service';
import { ThemeSwitcherService } from '../../../services/theme-switcher/theme-switcher.service';
import { IWorkbenchService, WorkbenchService } from '../../../services/workbench/workbench.service';
import { MobileKeyboardInsetContext } from '../mobile-keyboard-inset-context';
-import { MobileWorkbench } from '../MobileWorkbench';
+import { MobileWorkbench, resolveMobileKeyboardInset, shouldUpdateMobileStableHeight } from '../MobileWorkbench';
function KeyboardBar() {
const bottom = useContext(MobileKeyboardInsetContext);
@@ -118,6 +118,9 @@ describe('MobileWorkbench keyboard positioning', () => {
const portalBars = portal.querySelectorAll<HTMLElement>('[data-testid="keyboard-bar"]');
const rootStyle = document.documentElement.getAttribute('style');
const bodyStyle = document.body.getAttribute('style');
+ const input = document.createElement('input');
+ document.body.appendChild(input);
+ input.focus();
act(() => {
viewport.height = 500;
@@ -129,11 +132,11 @@ describe('MobileWorkbench keyboard positioning', () => {
expect(portalBars[1].style.bottom).toBe('100px');
act(() => {
- viewport.offsetTop = 50;
+ viewport.offsetTop = 20;
viewport.dispatchEvent(new Event('scroll'));
});
- expect(firstBar.style.bottom).toBe('250px');
- expect(secondBar.style.bottom).toBe('50px');
+ expect(firstBar.style.bottom).toBe('280px');
+ expect(secondBar.style.bottom).toBe('80px');
act(() => {
viewport.height = 800;
@@ -144,9 +147,7 @@ describe('MobileWorkbench keyboard positioning', () => {
expect(secondBar.style.bottom).toBe('0px');
expect(document.documentElement.getAttribute('style')).toBe(rootStyle);
expect(document.body.getAttribute('style')).toBe(bodyStyle);
- expect([...first.container.querySelectorAll<HTMLElement>('[style]')].some((element) =>
- [...element.style].some((property) => property.startsWith('--')))).toBe(false);
-
+ input.remove();
first.unmount();
second.unmount();
expect(removeViewportListener.mock.calls.map(([event]) => event)).toEqual(['resize', 'scroll', 'resize', 'scroll']);
@@ -154,3 +155,31 @@ describe('MobileWorkbench keyboard positioning', () => {
injector.dispose();
});
});
+
+describe('resolveMobileKeyboardInset', () => {
+ it('excludes persistent browser chrome and reports only keyboard occlusion', () => {
+ expect(resolveMobileKeyboardInset(900, 700, 200)).toBe(0);
+ expect(resolveMobileKeyboardInset(900, 400, 200)).toBe(300);
+ });
+
+ it('uses the visual viewport bottom without displacing the canvas by offsetTop', () => {
+ expect(resolveMobileKeyboardInset(932, 180 + 500, 0)).toBe(252);
+ });
+});
+
+describe('shouldUpdateMobileStableHeight', () => {
+ it('fills newly available height without treating viewport growth as keyboard occlusion', () => {
+ expect(shouldUpdateMobileStableHeight(780, 860, 390, 390, false, false)).toBe(true);
+ expect(shouldUpdateMobileStableHeight(780, 870, 390, 390, false, false)).toBe(true);
+ expect(shouldUpdateMobileStableHeight(870, 780, 390, 390, false, false)).toBe(false);
+ expect(shouldUpdateMobileStableHeight(780, 870, 390, 390, true, false)).toBe(false);
+ expect(shouldUpdateMobileStableHeight(780, 870, 390, 390, false, true)).toBe(false);
+ });
+
+ it('does not capture an iOS keyboard-height viewport after focus is lost', () => {
+ expect(shouldUpdateMobileStableHeight(900, 520, 430, 430, false, true)).toBe(false);
+ expect(shouldUpdateMobileStableHeight(900, 520, 430, 430, false, false)).toBe(false);
+ expect(shouldUpdateMobileStableHeight(900, 860, 430, 430, false, false)).toBe(true);
+ expect(shouldUpdateMobileStableHeight(900, 430, 430, 900, false, true)).toBe(true);
+ });
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 910ad42ca2..dfb688baff 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -874,6 +874,9 @@ importers:
'@univerjs/engine-render':
specifier: workspace:*
version: link:../engine-render
+ '@univerjs/icons':
+ specifier: 1.38.0
'@univerjs/ui':
specifier: workspace:*
version: link:../ui
@@ -1050,6 +1053,9 @@ importers:
'@univerjs-infra/shared':
specifier: workspace:*
version: link:../../common/shared
+ jest-canvas-mock:
+ specifier: ^2.5.2
+ version: 2.5.8
postcss:
specifier: ^8.5.26
version: 8.5.26