Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

fix(ui): use design controls and adjust docs menu layout (#7872)

白熱f74a9d5acd63
diff --git a/packages/design/src/components/input-number/InputNumber.tsx b/packages/design/src/components/input-number/InputNumber.tsx
index 1299644d24..a1e81c2a55 100644
--- a/packages/design/src/components/input-number/InputNumber.tsx
+++ b/packages/design/src/components/input-number/InputNumber.tsx
@@ -72,15 +72,18 @@ export const InputNumber = forwardRef<HTMLInputElement, IInputNumberProps>(
) => {
const { locale } = useContext(ConfigContext);
const [internalValue, setInternalValue] = useState<number | null>(
- value !== undefined ? value : defaultValue !== undefined ? defaultValue : null
+ () => {
+ if (value !== undefined) {
+ return value;
+ }
+ return defaultValue ?? null;
+ }
);
const lastValidValueRef = useRef<number | null>(internalValue);
const [inputValue, setInputValue] = useState<string>(() => formatValue(internalValue));
const inputRef = useRef<HTMLInputElement>(null);
- const longPressTimerRef = useRef<NodeJS.Timeout | null>(null);
- const longPressIntervalRef = useRef<NodeJS.Timeout | null>(null);
- const mergedRef = (node: HTMLInputElement) => {
+ const mergedRef = (node: HTMLInputElement | null) => {
if (ref) {
if (typeof ref === 'function') {
ref(node);
@@ -107,20 +110,10 @@ export const InputNumber = forwardRef<HTMLInputElement, IInputNumberProps>(
}
}, [internalValue]);
- // Clean up timers when component unmounts
- useEffect(() => {
- return () => {
- if (longPressTimerRef.current) {
- clearTimeout(longPressTimerRef.current);
- }
- if (longPressIntervalRef.current) {
- clearInterval(longPressIntervalRef.current);
- }
- };
- }, []);
-
function formatValue(val: number | null): string {
- if (val === null || val === undefined) return '';
+ if (val === null || val === undefined) {
+ return '';
+ }
let formattedValue: string | number = val;
@@ -138,7 +131,9 @@ export const InputNumber = forwardRef<HTMLInputElement, IInputNumberProps>(
}
function parseNumberValue(val: string): number | null {
- if (!val) return null;
+ if (!val) {
+ return null;
+ }
let parsedValue = val;
@@ -183,13 +178,15 @@ export const InputNumber = forwardRef<HTMLInputElement, IInputNumberProps>(
}
return result;
- } catch (e) {
+ } catch {
return null;
}
}
function clampValue(val: number | null): number | null {
- if (val === null) return null;
+ if (val === null) {
+ return null;
+ }
if (max !== undefined && val > max) {
return max;
@@ -201,10 +198,6 @@ export const InputNumber = forwardRef<HTMLInputElement, IInputNumberProps>(
return val;
}
- function parseValue(val: string): number | null {
- return clampValue(parseNumberValue(val));
- }
-
function handleInputChange(value: string) {
if (allowEmpty && value === '') {
setInputValue(value);
@@ -273,7 +266,9 @@ export const InputNumber = forwardRef<HTMLInputElement, IInputNumberProps>(
}
function handleStep(isUp: boolean) {
- if (disabled) return;
+ if (disabled) {
+ return;
+ }
const stepValue = isUp ? step : -step;
@@ -299,7 +294,9 @@ export const InputNumber = forwardRef<HTMLInputElement, IInputNumberProps>(
newValue = min;
}
// If we've hit a limit, don't change the value
- if (newValue === currentValue) return;
+ if (newValue === currentValue) {
+ return;
+ }
setInternalValue(newValue);
lastValidValueRef.current = newValue;
setInputValue(formatValue(newValue));
@@ -309,7 +306,9 @@ export const InputNumber = forwardRef<HTMLInputElement, IInputNumberProps>(
// Handle key down events for arrow keys
function handleKeyDown(e: KeyboardEvent<HTMLInputElement>) {
- if (disabled) return;
+ if (disabled) {
+ return;
+ }
onKeyDown?.(e);
@@ -325,7 +324,9 @@ export const InputNumber = forwardRef<HTMLInputElement, IInputNumberProps>(
}
function handleClick(isUp: boolean) {
- if (disabled) return;
+ if (disabled) {
+ return;
+ }
handleStep(isUp);
diff --git a/packages/design/src/components/input-number/__tests__/InputNumber.spec.tsx b/packages/design/src/components/input-number/__tests__/InputNumber.spec.tsx
index 259cb618cf..a29f8f6273 100644
--- a/packages/design/src/components/input-number/__tests__/InputNumber.spec.tsx
+++ b/packages/design/src/components/input-number/__tests__/InputNumber.spec.tsx
@@ -14,10 +14,14 @@
* limitations under the License.
*/
+import type { ComponentProps } from 'react';
import { cleanup, fireEvent, render } from '@testing-library/react';
import { useEffect, useRef, useState } from 'react';
-import { afterEach, describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import enUS from '../../../locale/en-US';
+import { ConfigProvider } from '../../config-provider/ConfigProvider';
import { InputNumber } from '../InputNumber';
+import '@testing-library/jest-dom/vitest';
function BlurOnControlledReset() {
const [value, setValue] = useState(24);
@@ -43,8 +47,6 @@ function BlurOnControlledReset() {
}
describe('InputNumber controlled reset', () => {
- afterEach(cleanup);
-
it('keeps the new controlled value when focus leaves during reset effects', () => {
const { container } = render(<BlurOnControlledReset />);
const input = container.querySelector('input')!;
@@ -56,3 +58,303 @@ describe('InputNumber controlled reset', () => {
expect(document.activeElement).not.toBe(input);
});
});
+
+function TestComponent(props: { onChange: (value: number | null) => void } & Omit<ComponentProps<typeof InputNumber>, 'value' | 'onChange'>) {
+ const { onChange, ...restProps } = props;
+ const [value, setValue] = useState(0);
+ function handleChange(newValue: number | null) {
+ setValue(newValue ?? 0);
+ onChange(newValue);
+ }
+
+ return <InputNumber value={value} onChange={handleChange} {...restProps} />;
+}
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe('InputNumber', () => {
+ const onChange = vi.fn();
+
+ it('should render with default value', () => {
+ const { getByRole } = render(<InputNumber defaultValue={5} />);
+ const input = getByRole('textbox') as HTMLInputElement;
+ expect(input.value).toBe('5');
+ });
+
+ it('should render with value (controlled)', () => {
+ const { getByRole } = render(<InputNumber value={10} />);
+ const input = getByRole('textbox') as HTMLInputElement;
+ expect(input.value).toBe('10');
+ });
+
+ it('should call onChange when input changes', () => {
+ const { container } = render(<TestComponent onChange={onChange} />);
+ fireEvent.change(container.querySelector('input')!, { target: { value: '123' } });
+ expect(onChange).toHaveBeenCalledWith(123);
+ });
+
+ it('should handle empty input', () => {
+ const { container } = render(<TestComponent onChange={onChange} />);
+ fireEvent.change(container.querySelector('input')!, { target: { value: '' } });
+ expect(onChange).toHaveBeenCalledWith(null);
+ });
+
+ it('should handle non-numeric input', () => {
+ const { container } = render(<TestComponent onChange={onChange} />);
+ fireEvent.change(container.querySelector('input')!, { target: { value: 'abc' } });
+ expect(onChange).toHaveBeenCalledWith(0);
+ });
+
+ it('should handle negative numbers', () => {
+ const { container } = render(<TestComponent onChange={onChange} />);
+ fireEvent.change(container.querySelector('input')!, { target: { value: '-123' } });
+ expect(onChange).toHaveBeenCalledWith(-123);
+ });
+
+ it('should handle decimal numbers', () => {
+ const { container } = render(<TestComponent onChange={onChange} />);
+ fireEvent.change(container.querySelector('input')!, { target: { value: '123.45' } });
+ expect(onChange).toHaveBeenCalledWith(123.45);
+ });
+
+ it('should emit blur event with final value', () => {
+ const { container } = render(<InputNumber defaultValue={0} onChange={onChange} />);
+ const input = container.querySelector('input')!;
+ fireEvent.change(input, { target: { value: '456' } });
+ fireEvent.blur(input);
+ expect(onChange).toHaveBeenCalledWith(456);
+
+ fireEvent.change(input, { target: { value: Infinity } });
+ fireEvent.blur(input);
+ expect(onChange).toHaveBeenLastCalledWith(0);
+ });
+
+ it('should emit blur event with final value & empty input', () => {
+ const { container } = render(<TestComponent onChange={onChange} allowEmpty />);
+ const input = container.querySelector('input')!;
+ fireEvent.change(input, { target: { value: '' } });
+ fireEvent.blur(input);
+ expect(onChange).toHaveBeenCalledWith(null);
+ });
+
+ it('should handle keydown events', () => {
+ const { container } = render(<TestComponent onChange={onChange} />);
+ const input = container.querySelector('input')!;
+
+ // Simulate keydown for increment
+ fireEvent.keyDown(input, { key: 'ArrowUp' });
+ expect(onChange).toHaveBeenCalledWith(1);
+
+ // Simulate keydown for decrement
+ fireEvent.keyDown(input, { key: 'ArrowDown' });
+ expect(onChange).toHaveBeenCalledWith(0);
+ });
+
+ it('should respect min/max and disable control buttons at bounds', () => {
+ onChange.mockClear();
+ const { container } = render(<InputNumber value={1} min={1} max={2} onChange={onChange} />);
+
+ const [incBtn, decBtn] = Array.from(container.querySelectorAll('[role="button"]')) as HTMLElement[];
+ expect(decBtn).toHaveAttribute('aria-disabled', 'true');
+ expect(incBtn).toHaveAttribute('aria-disabled', 'false');
+
+ fireEvent.click(decBtn);
+ expect(onChange).not.toHaveBeenCalled();
+
+ fireEvent.click(incBtn);
+ expect(onChange).toHaveBeenCalledWith(2);
+ });
+
+ it('should support formatter/parser/precision and press enter callback', () => {
+ const onPressEnter = vi.fn();
+ const { container } = render(
+ <InputNumber
+ defaultValue={1.236}
+ precision={2}
+ parser={(v) => (v ?? '').replace('$', '')}
+ formatter={(v) => `$${v}`}
+ onPressEnter={onPressEnter}
+ />
+ );
+
+ const input = container.querySelector('input') as HTMLInputElement;
+ expect(input.value).toBe('$1.24');
+
+ fireEvent.change(input, { target: { value: '$2.345' } });
+ fireEvent.blur(input);
+ expect(input.value).toBe('$2.35');
+
+ fireEvent.keyDown(input, { key: 'Enter' });
+ expect(onPressEnter).toHaveBeenCalled();
+ });
+
+ it('should hide controls when controls is false and keep input disabled', () => {
+ const { container } = render(<InputNumber defaultValue={3} controls={false} disabled />);
+ expect(container.querySelector('[role="button"]')).toBeNull();
+ const input = container.querySelector('input') as HTMLInputElement;
+ expect(input).toBeDisabled();
+ });
+
+ it('should clear an optional value while keeping increment and decrement controls', () => {
+ const onLocalChange = vi.fn();
+ const { container } = render(<InputNumber allowClear allowEmpty defaultValue={3} onChange={onLocalChange} />);
+
+ const clearButton = container.querySelector('button') as HTMLButtonElement;
+ expect(clearButton).not.toBeNull();
+ expect(container.querySelectorAll('[role="button"]')).toHaveLength(2);
+
+ fireEvent.click(clearButton);
+ expect(onLocalChange).toHaveBeenCalledWith(null);
+ });
+
+ it('should support ref callback and object ref', () => {
+ const callbackRef = vi.fn();
+ const objectRef = { current: null as HTMLInputElement | null };
+
+ const { unmount } = render(<InputNumber defaultValue={1} ref={callbackRef} />);
+ expect(callbackRef).toHaveBeenCalled();
+ unmount();
+
+ render(<InputNumber defaultValue={2} ref={objectRef} />);
+ expect(objectRef.current).not.toBeNull();
+ });
+
+ it('handles invalid custom parser output', () => {
+ const onLocalChange = vi.fn();
+ const { container } = render(
+ <InputNumber
+ defaultValue={1}
+ parser={() => null as unknown as string}
+ onChange={onLocalChange}
+ />
+ );
+
+ const input = container.querySelector('input') as HTMLInputElement;
+ fireEvent.change(input, { target: { value: '123' } });
+ expect(onLocalChange).toHaveBeenCalledWith(null);
+ });
+
+ it('strips nonnumeric characters before parsing', () => {
+ const onLocalChange = vi.fn();
+ const { container } = render(<InputNumber defaultValue={1} onChange={onLocalChange} />);
+ const input = container.querySelector('input') as HTMLInputElement;
+
+ fireEvent.change(input, { target: { value: '1e3' } });
+ expect(onLocalChange).toHaveBeenCalledWith(13);
+ fireEvent.blur(input);
+ expect(input.value).toBe('13');
+ });
+
+ it('should step from null value using min baseline and keep boundary', () => {
+ const onLocalChange = vi.fn();
+ const { container } = render(<InputNumber allowEmpty min={2} max={3} value={null} onChange={onLocalChange} />);
+ const [incBtn] = Array.from(container.querySelectorAll('[role="button"]')) as HTMLElement[];
+
+ fireEvent.click(incBtn);
+ expect(onLocalChange).toHaveBeenCalledWith(3);
+
+ fireEvent.click(incBtn);
+ expect(onLocalChange).toHaveBeenCalledTimes(1);
+ });
+
+ it('should handle NaN and clamp by min/max while typing', () => {
+ const onLocalChange = vi.fn();
+ const { container } = render(<InputNumber defaultValue={5} min={0} max={10} onChange={onLocalChange} />);
+ const input = container.querySelector('input') as HTMLInputElement;
+
+ fireEvent.change(input, { target: { value: '-' } });
+ expect(onLocalChange).toHaveBeenCalledWith(null);
+
+ fireEvent.change(input, { target: { value: '9999' } });
+ expect(onLocalChange).toHaveBeenCalledWith(10);
+ expect(input.value).toBe('10');
+
+ fireEvent.change(input, { target: { value: '-9999' } });
+ expect(onLocalChange).toHaveBeenCalledWith(0);
+ expect(input.value).toBe('0');
+ });
+
+ it('should restore last valid value on blur when current value is invalid', () => {
+ const onLocalChange = vi.fn();
+ const { container } = render(<InputNumber defaultValue={6} onChange={onLocalChange} />);
+ const input = container.querySelector('input') as HTMLInputElement;
+
+ fireEvent.change(input, { target: { value: '-' } });
+ fireEvent.blur(input);
+
+ expect(onLocalChange).toHaveBeenCalledWith(6);
+ expect(input.value).toBe('6');
+ });
+
+ it('should clamp out-of-range value on blur', () => {
+ const onLocalChange = vi.fn();
+ const { container } = render(<InputNumber defaultValue={1} min={0} max={10} onChange={onLocalChange} />);
+ const input = container.querySelector('input') as HTMLInputElement;
+
+ fireEvent.change(input, { target: { value: '100' } });
+ fireEvent.blur(input);
+ expect(onLocalChange).toHaveBeenCalledWith(10);
+ expect(input.value).toBe('10');
+
+ fireEvent.change(input, { target: { value: '-100' } });
+ fireEvent.blur(input);
+ expect(onLocalChange).toHaveBeenCalledWith(0);
+ expect(input.value).toBe('0');
+ });
+
+ it('should use last valid value as baseline when stepping from empty and support decrement click', () => {
+ const onLocalChange = vi.fn();
+ const { container } = render(<InputNumber allowEmpty defaultValue={2} onChange={onLocalChange} min={0} />);
+ const input = container.querySelector('input') as HTMLInputElement;
+ const [incBtn, decBtn] = Array.from(container.querySelectorAll('[role="button"]')) as HTMLElement[];
+
+ fireEvent.change(input, { target: { value: '' } });
+ fireEvent.click(incBtn);
+ expect(onLocalChange).toHaveBeenCalledWith(3);
+
+ fireEvent.click(decBtn);
+ expect(onLocalChange).toHaveBeenCalledWith(2);
+ });
+
+ it('should prevent interactions when disabled and prevent default on control mousedown', () => {
+ const onLocalChange = vi.fn();
+ const onKeyDown = vi.fn();
+ const { container } = render(<InputNumber defaultValue={2} disabled onChange={onLocalChange} onKeyDown={onKeyDown} />);
+ const input = container.querySelector('input') as HTMLInputElement;
+ const [incBtn, decBtn] = Array.from(container.querySelectorAll('[role="button"]')) as HTMLElement[];
+
+ const incMouseDown = new MouseEvent('mousedown', { bubbles: true, cancelable: true });
+ const decMouseDown = new MouseEvent('mousedown', { bubbles: true, cancelable: true });
+ expect(incBtn.dispatchEvent(incMouseDown)).toBe(false);
+ expect(decBtn.dispatchEvent(decMouseDown)).toBe(false);
+
+ fireEvent.keyDown(input, { key: 'ArrowUp' });
+ fireEvent.click(incBtn);
+ fireEvent.click(decBtn);
+
+ expect(onKeyDown).not.toHaveBeenCalled();
+ expect(onLocalChange).not.toHaveBeenCalled();
+ });
+
+ it('keeps labeled increment and decrement controls usable in RTL', () => {
+ const onLocalChange = vi.fn();
+ const { container } = render(
+ <ConfigProvider locale={enUS.design} mountContainer={document.body}>
+ <div dir="rtl">
+ <InputNumber defaultValue={1} onChange={onLocalChange} />
+ </div>
+ </ConfigProvider>
+ );
+
+ const incrementButton = container.querySelector(`[aria-label="${enUS.design.Accessibility.increment}"]`) as HTMLElement;
+ const decrementButton = container.querySelector(`[aria-label="${enUS.design.Accessibility.decrement}"]`) as HTMLElement;
+ fireEvent.click(incrementButton);
+ expect(onLocalChange).toHaveBeenCalledWith(2);
+
+ fireEvent.click(decrementButton);
+ expect(onLocalChange).toHaveBeenCalledWith(1);
+ });
+});
diff --git a/packages/design/src/components/input-number/__tests__/index.spec.tsx b/packages/design/src/components/input-number/__tests__/index.spec.tsx
deleted file mode 100644
index 5729fd2256..0000000000
--- a/packages/design/src/components/input-number/__tests__/index.spec.tsx
+++ /dev/null
@@ -1,344 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { ComponentProps } from 'react';
-import { cleanup, fireEvent, render } from '@testing-library/react';
-import { useState } from 'react';
-import { afterEach, describe, expect, it, vi } from 'vitest';
-import enUS from '../../../locale/en-US';
-import { ConfigProvider } from '../../config-provider/ConfigProvider';
-import { InputNumber } from '../InputNumber';
-import '@testing-library/jest-dom/vitest';
-
-afterEach(cleanup);
-
-describe('InputNumber', () => {
- const onChange = vi.fn();
-
- function TestComponent(props: { onChange: typeof onChange } & Omit<ComponentProps<typeof InputNumber>, 'value' | 'onChange'>) {
- const { onChange, ...restProps } = props;
- const [value, setValue] = useState(0);
- function handleChange(newValue: number | null) {
- setValue(newValue ?? 0);
- onChange(newValue);
- }
-
- return <InputNumber value={value} onChange={handleChange} {...restProps} />;
- }
-
- it('should render with default value', () => {
- const { getByRole } = render(<InputNumber defaultValue={5} />);
- const input = getByRole('textbox') as HTMLInputElement;
- expect(input.value).toBe('5');
- });
-
- it('should render with value (controlled)', () => {
- const { getByRole } = render(<InputNumber value={10} />);
- const input = getByRole('textbox') as HTMLInputElement;
- expect(input.value).toBe('10');
- });
-
- it('should call onChange when input changes', () => {
- const { container } = render(<TestComponent onChange={onChange} />);
- fireEvent.change(container.querySelector('input')!, { target: { value: '123' } });
- expect(onChange).toHaveBeenCalledWith(123);
- });
-
- it('should handle empty input', () => {
- const { container } = render(<TestComponent onChange={onChange} />);
- fireEvent.change(container.querySelector('input')!, { target: { value: '' } });
- expect(onChange).toHaveBeenCalledWith(null);
- });
-
- it('should handle non-numeric input', () => {
- const { container } = render(<TestComponent onChange={onChange} />);
- fireEvent.change(container.querySelector('input')!, { target: { value: 'abc' } });
- expect(onChange).toHaveBeenCalledWith(0);
- });
-
- it('should handle negative numbers', () => {
- const { container } = render(<TestComponent onChange={onChange} />);
- fireEvent.change(container.querySelector('input')!, { target: { value: '-123' } });
- expect(onChange).toHaveBeenCalledWith(-123);
- });
-
- it('should handle decimal numbers', () => {
- const { container } = render(<TestComponent onChange={onChange} />);
- fireEvent.change(container.querySelector('input')!, { target: { value: '123.45' } });
- expect(onChange).toHaveBeenCalledWith(123.45);
- });
-
- it('should emit blur event with final value', () => {
- const { container } = render(<TestComponent onChange={onChange} />);
- const input = container.querySelector('input')!;
- fireEvent.change(input, { target: { value: '456' } });
- fireEvent.blur(input);
- expect(onChange).toHaveBeenCalledWith(456);
-
- fireEvent.change(input, { target: { value: Infinity } });
- fireEvent.blur(input);
- expect(onChange).toHaveBeenCalledWith(0);
- });
-
- it('should emit blur event with final value & empty input', () => {
- const { container } = render(<TestComponent onChange={onChange} allowEmpty />);
- const input = container.querySelector('input')!;
- fireEvent.change(input, { target: { value: '' } });
- fireEvent.blur(input);
- expect(onChange).toHaveBeenCalledWith(null);
- });
-
- it('should handle keydown events', () => {
- const { container } = render(<TestComponent onChange={onChange} />);
- const input = container.querySelector('input')!;
-
- // Simulate keydown for increment
- fireEvent.keyDown(input, { key: 'ArrowUp' });
- expect(onChange).toHaveBeenCalledWith(1);
-
- // Simulate keydown for decrement
- fireEvent.keyDown(input, { key: 'ArrowDown' });
- expect(onChange).toHaveBeenCalledWith(0);
- });
-
- it('should respect min/max and disable control buttons at bounds', () => {
- onChange.mockClear();
- const { container } = render(<InputNumber value={1} min={1} max={2} onChange={onChange} />);
-
- const [incBtn, decBtn] = Array.from(container.querySelectorAll('[role="button"]')) as HTMLElement[];
- expect(decBtn).toHaveAttribute('aria-disabled', 'true');
- expect(incBtn).toHaveAttribute('aria-disabled', 'false');
-
- fireEvent.click(decBtn);
- expect(onChange).not.toHaveBeenCalled();
-
- fireEvent.click(incBtn);
- expect(onChange).toHaveBeenCalledWith(2);
- });
-
- it('should support formatter/parser/precision and press enter callback', () => {
- const onPressEnter = vi.fn();
- const { container } = render(
- <InputNumber
- defaultValue={1.236}
- precision={2}
- parser={(v) => (v ?? '').replace('$', '')}
- formatter={(v) => `$${v}`}
- onPressEnter={onPressEnter}
- />
- );
-
- const input = container.querySelector('input') as HTMLInputElement;
- expect(input.value).toBe('$1.24');
-
- fireEvent.change(input, { target: { value: '$2.345' } });
- fireEvent.blur(input);
- expect(input.value).toBe('$2.35');
-
- fireEvent.keyDown(input, { key: 'Enter' });
- expect(onPressEnter).toHaveBeenCalled();
- });
-
- it('should hide controls when controls is false and keep input disabled', () => {
- const { container } = render(<InputNumber defaultValue={3} controls={false} disabled />);
- expect(container.querySelector('[role="button"]')).toBeNull();
- const input = container.querySelector('input') as HTMLInputElement;
- expect(input).toBeDisabled();
- });
-
- it('should clear an optional value while keeping increment and decrement controls', () => {
- const onLocalChange = vi.fn();
- const { container } = render(<InputNumber allowClear allowEmpty defaultValue={3} onChange={onLocalChange} />);
-
- const clearButton = container.querySelector('button') as HTMLButtonElement;
- expect(clearButton).not.toBeNull();
- expect(container.querySelectorAll('[role="button"]')).toHaveLength(2);
-
- fireEvent.click(clearButton);
- expect(onLocalChange).toHaveBeenCalledWith(null);
- });
-
- it('should support ref callback and object ref', () => {
- const callbackRef = vi.fn();
- const objectRef = { current: null as HTMLInputElement | null };
-
- const { unmount } = render(<InputNumber defaultValue={1} ref={callbackRef} />);
- expect(callbackRef).toHaveBeenCalled();
- unmount();
-
- render(<InputNumber defaultValue={2} ref={objectRef} />);
- expect(objectRef.current).not.toBeNull();
- });
-
- it('should handle parser fallback and scientific notation', () => {
- const onLocalChange = vi.fn();
- const { container } = render(
- <InputNumber
- defaultValue={1}
- parser={() => null as unknown as string}
- onChange={onLocalChange}
- />
- );
-
- const input = container.querySelector('input') as HTMLInputElement;
- fireEvent.change(input, { target: { value: '123' } });
- expect(onLocalChange).toHaveBeenCalledWith(null);
-
- onLocalChange.mockClear();
- fireEvent.change(input, { target: { value: '1e3' } });
- expect(onLocalChange).toHaveBeenCalledWith(null);
- });
-
- it('should parse scientific notation without precision loss branch errors', () => {
- const onLocalChange = vi.fn();
- const { container } = render(<InputNumber defaultValue={1} onChange={onLocalChange} />);
- const input = container.querySelector('input') as HTMLInputElement;
-
- fireEvent.change(input, { target: { value: '1e3' } });
- expect(onLocalChange).toHaveBeenCalledWith(13);
- });
-
- it('should step from null value using min baseline and keep boundary', () => {
- const onLocalChange = vi.fn();
- const { container } = render(<InputNumber allowEmpty min={2} max={3} value={null} onChange={onLocalChange} />);
- const [incBtn] = Array.from(container.querySelectorAll('[role="button"]')) as HTMLElement[];
-
- fireEvent.click(incBtn);
- expect(onLocalChange).toHaveBeenCalledWith(3);
-
- fireEvent.click(incBtn);
- expect(onLocalChange).toHaveBeenCalledTimes(1);
- });
-
- it('should handle NaN and clamp by min/max while typing', () => {
- const onLocalChange = vi.fn();
- const { container } = render(<InputNumber defaultValue={5} min={0} max={10} onChange={onLocalChange} />);
- const input = container.querySelector('input') as HTMLInputElement;
-
- fireEvent.change(input, { target: { value: '-' } });
- expect(onLocalChange).toHaveBeenCalledWith(null);
-
- fireEvent.change(input, { target: { value: '9999' } });
- expect(onLocalChange).toHaveBeenCalledWith(10);
- expect(input.value).toBe('10');
-
- fireEvent.change(input, { target: { value: '-9999' } });
- expect(onLocalChange).toHaveBeenCalledWith(0);
- expect(input.value).toBe('0');
- });
-
- it('should restore last valid value on blur when current value is invalid', () => {
- const onLocalChange = vi.fn();
- const { container } = render(<InputNumber defaultValue={6} onChange={onLocalChange} />);
- const input = container.querySelector('input') as HTMLInputElement;
-
- fireEvent.change(input, { target: { value: '-' } });
- fireEvent.blur(input);
-
- expect(onLocalChange).toHaveBeenCalledWith(6);
- expect(input.value).toBe('6');
- });
-
- it('should clamp out-of-range value on blur', () => {
- const onLocalChange = vi.fn();
- const { container } = render(<InputNumber defaultValue={1} min={0} max={10} onChange={onLocalChange} />);
- const input = container.querySelector('input') as HTMLInputElement;
-
- fireEvent.change(input, { target: { value: '100' } });
- fireEvent.blur(input);
- expect(onLocalChange).toHaveBeenCalledWith(10);
- expect(input.value).toBe('10');
-
- fireEvent.change(input, { target: { value: '-100' } });
- fireEvent.blur(input);
- expect(onLocalChange).toHaveBeenCalledWith(0);
- expect(input.value).toBe('0');
- });
-
- it('should parse very large values in scientific-notation branches', () => {
- const onWithPrecision = vi.fn();
- const onWithoutPrecision = vi.fn();
- const { container: c1 } = render(<InputNumber precision={2} defaultValue={1} onChange={onWithPrecision} />);
- const { container: c2 } = render(<InputNumber defaultValue={1} onChange={onWithoutPrecision} />);
- const huge = '10000000000000000000000';
-
- fireEvent.change(c1.querySelector('input')!, { target: { value: huge } });
- fireEvent.change(c2.querySelector('input')!, { target: { value: huge } });
-
- expect(onWithPrecision).toHaveBeenCalled();
- expect(onWithoutPrecision).toHaveBeenCalled();
- });
-
- it('should use last valid value as baseline when stepping from empty and support decrement click', () => {
- const onLocalChange = vi.fn();
- const { container } = render(<InputNumber allowEmpty defaultValue={2} onChange={onLocalChange} min={0} />);
- const input = container.querySelector('input') as HTMLInputElement;
- const [incBtn, decBtn] = Array.from(container.querySelectorAll('[role="button"]')) as HTMLElement[];
-
- fireEvent.change(input, { target: { value: '' } });
- fireEvent.click(incBtn);
- expect(onLocalChange).toHaveBeenCalledWith(3);
-
- fireEvent.click(decBtn);
- expect(onLocalChange).toHaveBeenCalledWith(2);
- });
-
- it('should prevent interactions when disabled and prevent default on control mousedown', () => {
- const onLocalChange = vi.fn();
- const onKeyDown = vi.fn();
- const { container } = render(<InputNumber defaultValue={2} disabled onChange={onLocalChange} onKeyDown={onKeyDown} />);
- const input = container.querySelector('input') as HTMLInputElement;
- const [incBtn, decBtn] = Array.from(container.querySelectorAll('[role="button"]')) as HTMLElement[];
-
- const incMouseDown = new MouseEvent('mousedown', { bubbles: true, cancelable: true });
- const decMouseDown = new MouseEvent('mousedown', { bubbles: true, cancelable: true });
- expect(incBtn.dispatchEvent(incMouseDown)).toBe(false);
- expect(decBtn.dispatchEvent(decMouseDown)).toBe(false);
-
- fireEvent.keyDown(input, { key: 'ArrowUp' });
- fireEvent.click(incBtn);
- fireEvent.click(decBtn);
-
- expect(onKeyDown).not.toHaveBeenCalled();
- expect(onLocalChange).not.toHaveBeenCalled();
- });
-
- it('should support rtl layout classes and keep increment/decrement behavior', () => {
- const onLocalChange = vi.fn();
- const { container } = render(
- <ConfigProvider locale={enUS.design} mountContainer={document.body}>
- <div dir="rtl">
- <InputNumber defaultValue={1} onChange={onLocalChange} />
- </div>
- </ConfigProvider>
- );
-
- const incrementButton = container.querySelector(`[aria-label="${enUS.design.Accessibility.increment}"]`) as HTMLElement;
- const decrementButton = container.querySelector(`[aria-label="${enUS.design.Accessibility.decrement}"]`) as HTMLElement;
- const controlsWrapper = incrementButton.parentElement as HTMLElement;
-
- expect(controlsWrapper.className).toContain('rtl:univer-left-px');
- expect(controlsWrapper.className).toContain('rtl:univer-right-auto');
- expect(controlsWrapper.className).toContain('rtl:univer-rounded-l-md');
- expect(controlsWrapper.className).toContain('rtl:univer-border-r');
-
- fireEvent.click(incrementButton);
- expect(onLocalChange).toHaveBeenCalledWith(2);
-
- fireEvent.click(decrementButton);
- expect(onLocalChange).toHaveBeenCalledWith(1);
- });
-});
diff --git a/packages/design/src/components/input/Input.tsx b/packages/design/src/components/input/Input.tsx
index c5f5fe4c4f..f56885585e 100644
--- a/packages/design/src/components/input/Input.tsx
+++ b/packages/design/src/components/input/Input.tsx
@@ -49,7 +49,7 @@ export const inputVariants = cva(
}
);
-export interface IInputProps extends Pick<InputProps, 'dir' | 'onFocus' | 'onBlur'>,
+export interface IInputProps extends Omit<InputProps, 'onChange' | 'size' | 'slot' | 'value'>,
VariantProps<typeof inputVariants> {
autoFocus?: boolean;
className?: string;
diff --git a/packages/design/src/components/input/__tests__/index.spec.tsx b/packages/design/src/components/input/__tests__/Input.spec.tsx
similarity index 88%
rename from packages/design/src/components/input/__tests__/index.spec.tsx
rename to packages/design/src/components/input/__tests__/Input.spec.tsx
index d25a5dce3f..99a2d6ce13 100644
--- a/packages/design/src/components/input/__tests__/index.spec.tsx
+++ b/packages/design/src/components/input/__tests__/Input.spec.tsx
@@ -25,6 +25,20 @@ afterEach(() => {
});
describe('Input', () => {
+ it('forwards mobile keyboard, validation and focus attributes to the input', () => {
+ const onFocus = vi.fn();
+ const { getByLabelText } = render(
+ <Input aria-label="Amount" aria-invalid inputMode="decimal" required onFocus={onFocus} />
+ );
+ const input = getByLabelText('Amount') as HTMLInputElement;
+ input.focus();
+ expect(document.activeElement).toBe(input);
+ expect(input.inputMode).toBe('decimal');
+ expect(input.getAttribute('aria-invalid')).toBe('true');
+ expect(input.checkValidity()).toBe(false);
+ expect(onFocus).toHaveBeenCalledOnce();
+ });
+
it('renders the placeholder', () => {
const { getByPlaceholderText } = render(<Input placeholder="Test" />);
const inputElement = getByPlaceholderText('Test');
@@ -45,26 +59,16 @@ describe('Input', () => {
expect(container.querySelector('input')?.disabled).toBeTruthy();
});
- it('renders the size', () => {
- const { container } = render(<Input size="large" />);
-
- expect(container.innerHTML).contains('univer-h-12');
- });
-
- it('renders the clearable', () => {
- const { container } = render(<Input allowClear value="x" />);
-
- expect(container.innerHTML).contains('type="button"');
- });
-
it('change the value', () => {
- const { container } = render(<Input />);
+ const onChange = vi.fn();
+ const { container } = render(<Input onChange={onChange} />);
const inputElement = container.querySelector('input')!;
fireEvent.change(inputElement, { target: { value: 'Test' } });
expect(inputElement.value).toBe('Test');
+ expect(onChange).toHaveBeenCalledExactlyOnceWith('Test');
});
it('should clear value without bubbling click event', () => {
@@ -176,12 +180,6 @@ describe('Input', () => {
expect(input.style.paddingRight).toBe('26px');
});
- it('should preserve ltr right padding compatibility when no trailing content exists', () => {
- const { container } = render(<Input />);
- const input = container.querySelector('input') as HTMLInputElement;
- expect(input.style.paddingRight).toBe('0px');
- });
-
it('should not override rtl right padding when no trailing content exists', () => {
const { container } = render(
<ConfigProvider mountContainer={document.body} direction="rtl">
diff --git a/packages/design/src/components/radio/Radio.tsx b/packages/design/src/components/radio/Radio.tsx
index 5a409aea30..17d6d7fed0 100644
--- a/packages/design/src/components/radio/Radio.tsx
+++ b/packages/design/src/components/radio/Radio.tsx
@@ -20,6 +20,8 @@ import { clsx } from '../../helper/clsx';
export interface IRadioProps {
children?: ReactNode;
+ className?: string;
+ name?: string;
/**
* Used for setting the currently selected value
@@ -48,14 +50,16 @@ export interface IRadioProps {
* Radio Component
*/
export function Radio(props: IRadioProps) {
- const { children, checked, value, disabled = false, onChange } = props;
+ const { children, className, name, checked, value, disabled = false, onChange } = props;
const inputRef = useRef<HTMLInputElement>(null!);
function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
e.stopPropagation();
- if (!onChange || disabled) return;
+ if (!onChange || disabled) {
+ return;
+ }
if (typeof value !== 'undefined') {
onChange && onChange(value);
@@ -71,13 +75,14 @@ export function Radio(props: IRadioProps) {
className={clsx('univer-box-border univer-inline-flex univer-items-center univer-gap-2 univer-text-sm', {
'univer-cursor-pointer univer-text-gray-900 dark:!univer-text-gray-0': !disabled,
'univer-text-gray-400': disabled,
- })}
+ }, className)}
>
<span className="univer-relative univer-block">
<input
ref={inputRef}
className="univer-absolute univer-size-0 univer-opacity-0"
type="radio"
+ name={name}
checked={checked}
disabled={disabled}
onChange={handleChange}
diff --git a/packages/design/src/components/radio/__tests__/index.spec.tsx b/packages/design/src/components/radio/__tests__/Radio.spec.tsx
similarity index 62%
rename from packages/design/src/components/radio/__tests__/index.spec.tsx
rename to packages/design/src/components/radio/__tests__/Radio.spec.tsx
index 1d91cd2fde..14aa37f243 100644
--- a/packages/design/src/components/radio/__tests__/index.spec.tsx
+++ b/packages/design/src/components/radio/__tests__/Radio.spec.tsx
@@ -21,9 +21,24 @@ import { Radio } from '../Radio';
afterEach(cleanup);
describe('Radio', () => {
+ it('keeps named options mutually exclusive using native radio behavior', () => {
+ const { getByLabelText } = render(
+ <>
+ <Radio name="update-mode" value="pages">Page numbers</Radio>
+ <Radio name="update-mode" value="all">Entire table</Radio>
+ </>
+ );
+ const pages = getByLabelText('Page numbers') as HTMLInputElement;
+ const all = getByLabelText('Entire table') as HTMLInputElement;
+ fireEvent.click(pages);
+ fireEvent.click(all);
+ expect(pages.checked).toBe(false);
+ expect(all.checked).toBe(true);
+ });
+
const component = <Radio value="0">text</Radio>;
- it('click Radio', async () => {
+ it('click Radio', () => {
const { container } = render(component);
fireEvent.click(container.querySelector('input')!);
diff --git a/packages/design/src/components/select/MobileSelect.tsx b/packages/design/src/components/select/MobileSelect.tsx
index 510482e8a1..04fb799bf8 100644
--- a/packages/design/src/components/select/MobileSelect.tsx
+++ b/packages/design/src/components/select/MobileSelect.tsx
@@ -38,7 +38,10 @@ export function MobileSelect(props: IMobileSelectProps) {
disabled = false,
options = EMPTY_OPTIONS,
borderless = false,
+ side,
+ avoidCollisions,
onChange,
+ ...triggerProps
} = props;
const [open, setOpen] = useState(false);
const items: IMobileDropdownMenuProps['items'] = useMemo(() => {
@@ -91,9 +94,12 @@ export function MobileSelect(props: IMobileSelectProps) {
open={open}
items={items}
disabled={disabled}
+ side={side}
+ avoidCollisions={avoidCollisions}
onOpenChange={setOpen}
>
<button
+ {...triggerProps}
type="button"
disabled={disabled}
aria-expanded={open}
@@ -105,14 +111,14 @@ export function MobileSelect(props: IMobileSelectProps) {
'univer-cursor-pointer': !disabled,
}, className)}
>
- <div
+ <span
className="
univer-flex-1 univer-truncate univer-text-base univer-text-gray-500
dark:!univer-text-gray-0
"
>
{displayValue}
- </div>
+ </span>
<MoreDownIcon
className="
univer-flex-shrink-0
diff --git a/packages/design/src/components/select/Select.tsx b/packages/design/src/components/select/Select.tsx
index 4c0d794eb6..39d88f3c64 100644
--- a/packages/design/src/components/select/Select.tsx
+++ b/packages/design/src/components/select/Select.tsx
@@ -14,12 +14,13 @@
* limitations under the License.
*/
-import type { ReactNode } from 'react';
+import type { ButtonHTMLAttributes, ReactNode } from 'react';
import type { IDropdownMenuProps } from '../dropdown-menu/DropdownMenu';
import { MoreDownIcon } from '@univerjs/icons';
import { useMemo, useState } from 'react';
import { borderClassName } from '../../helper/class-utilities';
import { clsx } from '../../helper/clsx';
+import { Button } from '../button/Button';
import { DropdownMenu } from '../dropdown-menu/DropdownMenu';
interface IOption {
@@ -33,7 +34,7 @@ interface IOptionSeparator {
type: 'separator';
}
-export interface ISelectProps {
+export interface ISelectProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'children' | 'onChange' | 'value'> {
className?: string;
/**
@@ -77,16 +78,19 @@ export const selectClassName = clsx(`
dark:!univer-bg-gray-700 dark:!univer-text-gray-0
`, borderClassName);
+const EMPTY_OPTIONS: NonNullable<ISelectProps['options']> = [];
+
export function Select(props: ISelectProps) {
const {
className,
value,
disabled = false,
- options = [],
+ options = EMPTY_OPTIONS,
borderless = false,
side,
avoidCollisions,
onChange,
+ ...triggerProps
} = props;
const [open, setOpen] = useState(false);
@@ -128,7 +132,7 @@ export function Select(props: ISelectProps) {
onChange(item);
},
}];
- }, [options]);
+ }, [onChange, options, value]);
const displayValue = useMemo(() => {
let label = null;
@@ -163,7 +167,10 @@ export function Select(props: ISelectProps) {
avoidCollisions={avoidCollisions}
onOpenChange={handleOpenChange}
>
- <div
+ <Button
+ {...triggerProps}
+ type="button"
+ disabled={disabled}
data-u-comp="select"
className={clsx(selectClassName, {
'univer-border-primary-600 univer-outline-none univer-ring-2 univer-ring-primary-50 dark:!univer-ring-primary-900': open && !borderless,
@@ -173,21 +180,21 @@ export function Select(props: ISelectProps) {
'univer-cursor-pointer': !disabled && !open,
}, className)}
>
- <div
+ <span
className={`
- univer-flex-1 univer-truncate univer-text-sm univer-text-gray-500
+ univer-flex-1 univer-truncate univer-text-start univer-text-sm univer-text-gray-500
dark:!univer-text-gray-0
`}
>
{displayValue}
- </div>
+ </span>
<MoreDownIcon
className={`
univer-flex-shrink-0
dark:!univer-text-gray-0
`}
/>
- </div>
+ </Button>
</DropdownMenu>
);
}
diff --git a/packages/design/src/components/select/__tests__/MobileSelect.spec.tsx b/packages/design/src/components/select/__tests__/MobileSelect.spec.tsx
new file mode 100644
index 0000000000..53754420f9
--- /dev/null
+++ b/packages/design/src/components/select/__tests__/MobileSelect.spec.tsx
@@ -0,0 +1,67 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import enUS from '../../../locale/en-US';
+import { ConfigProvider } from '../../config-provider/ConfigProvider';
+import { MobileSelect } from '../MobileSelect';
+import '@testing-library/jest-dom/vitest';
+
+const options = [
+ { label: 'Option 1', value: '1' },
+ { label: 'Option 2', value: '2' },
+ { label: 'Option 3', value: '3', disabled: true },
+ { label: 'Group', options: [
+ { label: 'G1', value: 'g1' },
+ { label: 'G2', value: 'g2' },
+ ] },
+];
+
+afterEach(cleanup);
+
+describe('MobileSelect', () => {
+ it('should render mobile options in a touch-first dialog explicitly', () => {
+ const handleChange = vi.fn();
+ render(
+ <ConfigProvider locale={enUS.design} mountContainer={document.body}>
+ <MobileSelect aria-label="Choice" value="1" options={options} onChange={handleChange} />
+ </ConfigProvider>
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'Choice' }));
+ expect(screen.getByRole('dialog')).toBeInTheDocument();
+ fireEvent.click(screen.getByText('Option 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', () => {
+ render(<MobileSelect value="fallback" options={[{ label: '', value: 'fallback' }]} onChange={() => {}} />);
+
+ expect(screen.getByText('fallback')).toBeInTheDocument();
+ });
+});
diff --git a/packages/design/src/components/select/__tests__/MultipleSelect.spec.tsx b/packages/design/src/components/select/__tests__/MultipleSelect.spec.tsx
new file mode 100644
index 0000000000..90852559b7
--- /dev/null
+++ b/packages/design/src/components/select/__tests__/MultipleSelect.spec.tsx
@@ -0,0 +1,64 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { cleanup, fireEvent, 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 { MultipleSelect } from '../MultipleSelect';
+
+afterEach(cleanup);
+const options = [{ label: 'First', value: 'first' }, { label: 'Second', value: 'second' }];
+
+describe('MultipleSelect', () => {
+ it('adds and removes items using the latest controlled selection', async () => {
+ const onChange = vi.fn();
+ const { container, rerender } = render(
+ <ConfigProvider locale={enUS.design} mountContainer={document.body}>
+ <MultipleSelect value={['first']} options={options} onChange={onChange} />
+ </ConfigProvider>
+ );
+ fireEvent.keyDown(container.querySelector('[data-u-comp="multiple-select"]')!, { key: 'ArrowDown' });
+ fireEvent.click(await screen.findByRole('menuitemcheckbox', { name: 'First' }));
+ expect(onChange).toHaveBeenLastCalledWith([]);
+ await waitFor(() => expect(screen.queryByRole('menu')).toBeNull());
+ rerender(
+ <ConfigProvider locale={enUS.design} mountContainer={document.body}>
+ <MultipleSelect value={[]} options={options} onChange={onChange} />
+ </ConfigProvider>
+ );
+ fireEvent.keyDown(container.querySelector('[data-u-comp="multiple-select"]')!, { key: 'ArrowDown' });
+ fireEvent.click(await screen.findByRole('menuitemcheckbox', { name: 'Second' }));
+ expect(onChange).toHaveBeenLastCalledWith(['second']);
+ });
+
+ it('removes a selected badge through its close action', () => {
+ const onChange = vi.fn();
+ render(
+ <ConfigProvider locale={enUS.design} mountContainer={document.body}>
+ <MultipleSelect value={['first', 'second']} options={options} onChange={onChange} />
+ </ConfigProvider>
+ );
+ fireEvent.click(screen.getAllByLabelText(enUS.design.Accessibility.closeBadge)[0]);
+ expect(onChange).toHaveBeenCalledExactlyOnceWith(['second']);
+ });
+
+ it('does not open options when disabled', () => {
+ const { container } = render(<MultipleSelect value={['first']} options={options} onChange={vi.fn()} disabled />);
+ fireEvent.keyDown(container.querySelector('[data-u-comp="multiple-select"]')!, { key: 'ArrowDown' });
+ expect(screen.queryByRole('menu')).toBeNull();
+ });
+});
diff --git a/packages/design/src/components/select/__tests__/Select.spec.tsx b/packages/design/src/components/select/__tests__/Select.spec.tsx
new file mode 100644
index 0000000000..6eb4cd4c5c
--- /dev/null
+++ b/packages/design/src/components/select/__tests__/Select.spec.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 { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import enUS from '../../../locale/en-US';
+import { ConfigProvider } from '../../config-provider/ConfigProvider';
+import { Select } from '../Select';
+
+afterEach(cleanup);
+const options = [
+ { label: 'First', value: 'first' },
+ { label: 'Second', value: 'second' },
+ { label: 'Unavailable', value: 'disabled', disabled: true },
+ { label: 'Group', options: [{ label: 'Grouped', value: 'grouped' }] },
+];
+
+describe('Select', () => {
+ it('supports labels, keyboard opening, grouped options and the latest controlled callback', async () => {
+ const originalChange = vi.fn();
+ const nextChange = vi.fn();
+ const { rerender } = render(
+ <ConfigProvider locale={enUS.design} mountContainer={document.body}>
+ <Select aria-label="Format" value="first" options={options} onChange={originalChange} />
+ </ConfigProvider>
+ );
+ const trigger = screen.getByRole('button', { name: 'Format' });
+ trigger.focus();
+ fireEvent.keyDown(trigger, { key: 'ArrowDown' });
+ expect((await screen.findByRole('menuitemradio', { name: 'First' })).getAttribute('aria-checked')).toBe('true');
+ expect(screen.getByRole('menuitemradio', { name: 'Unavailable' }).getAttribute('aria-disabled')).toBe('true');
+ rerender(
+ <ConfigProvider locale={enUS.design} mountContainer={document.body}>
+ <Select aria-label="Format" value="second" options={options} onChange={nextChange} />
+ </ConfigProvider>
+ );
+ expect(screen.getByRole('menuitemradio', { name: 'Second' }).getAttribute('aria-checked')).toBe('true');
+ fireEvent.click(screen.getByRole('menuitemradio', { name: 'Grouped' }));
+ expect(nextChange).toHaveBeenCalledExactlyOnceWith('grouped');
+ expect(originalChange).not.toHaveBeenCalled();
+ });
+
+ it('prevents interaction when disabled and never submits its containing form', () => {
+ const onSubmit = vi.fn((event: React.FormEvent) => event.preventDefault());
+ const { rerender } = render(
+ <form onSubmit={onSubmit}><Select aria-label="Format" value="first" options={options} onChange={vi.fn()} disabled /></form>
+ );
+ const trigger = screen.getByRole('button', { name: 'Format' }) as HTMLButtonElement;
+ expect(trigger.disabled).toBe(true);
+ fireEvent.keyDown(trigger, { key: 'ArrowDown' });
+ expect(screen.queryByRole('menu')).toBeNull();
+ rerender(<form onSubmit={onSubmit}><Select aria-label="Format" value="first" options={options} onChange={vi.fn()} /></form>);
+ fireEvent.click(trigger);
+ expect(onSubmit).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/design/src/components/select/__tests__/index.spec.tsx b/packages/design/src/components/select/__tests__/index.spec.tsx
deleted file mode 100644
index 9656bd163d..0000000000
--- a/packages/design/src/components/select/__tests__/index.spec.tsx
+++ /dev/null
@@ -1,174 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import { cleanup, fireEvent, render, screen } from '@testing-library/react';
-import { afterEach, describe, expect, it, vi } from 'vitest';
-import enUS from '../../../locale/en-US';
-import { ConfigProvider } from '../../config-provider/ConfigProvider';
-import { MobileSelect } from '../MobileSelect';
-import { MultipleSelect } from '../MultipleSelect';
-import { Select } from '../Select';
-import '@testing-library/jest-dom/vitest';
-
-const options = [
- { label: 'Option 1', value: '1' },
- { label: 'Option 2', value: '2' },
- { label: 'Option 3', value: '3', disabled: true },
- { label: 'Group', options: [
- { label: 'G1', value: 'g1' },
- { label: 'G2', value: 'g2' },
- ] },
-];
-
-afterEach(cleanup);
-
-describe('Select', () => {
- it('should render mobile options in a touch-first dialog explicitly', () => {
- const handleChange = vi.fn();
- render(
- <ConfigProvider locale={enUS.design} mountContainer={document.body}>
- <MobileSelect value="1" options={options} onChange={handleChange} />
- </ConfigProvider>
- );
-
- fireEvent.click(screen.getByRole('button', { name: 'Option 1' }));
- expect(screen.getByRole('dialog')).toBeInTheDocument();
- fireEvent.click(screen.getByText('Option 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', () => {
- render(<MobileSelect value="fallback" options={[{ label: '', value: 'fallback' }]} onChange={() => {}} />);
-
- expect(screen.getByText('fallback')).toBeInTheDocument();
- });
-
- it('should render with value', () => {
- const { getByText } = render(<Select value="1" options={options} onChange={() => {}} />);
- expect(getByText('Option 1')).toBeInTheDocument();
- });
-
- it('should render with group value', () => {
- const { getByText } = render(<Select value="g2" options={options} onChange={() => {}} />);
- expect(getByText('G2')).toBeInTheDocument();
- });
-
- it('should call onChange when select changes', () => {
- const handleChange = vi.fn();
- const { container } = render(<Select value="1" options={options} onChange={handleChange} />);
- const selectDiv = container.querySelector('[data-u-comp="select"]');
- if (selectDiv) {
- selectDiv.dispatchEvent(new MouseEvent('click', { bubbles: true }));
- const optionBtn = Array.from(document.querySelectorAll('button')).find((btn) => btn.textContent === 'Option 2');
- if (optionBtn) {
- optionBtn.dispatchEvent(new MouseEvent('click', { bubbles: true }));
- expect(handleChange).toHaveBeenCalledWith('2');
- }
- }
- });
-
- it('should not call onChange when disabled', () => {
- const handleChange = vi.fn();
- const { container } = render(<Select value="1" options={options} onChange={handleChange} disabled />);
- const selectDiv = container.querySelector('[data-u-comp="select"]');
- if (selectDiv) {
- selectDiv.dispatchEvent(new MouseEvent('click', { bubbles: true }));
- const optionBtn = Array.from(document.querySelectorAll('button')).find((btn) => btn.textContent === 'Option 2');
- if (optionBtn) {
- optionBtn.dispatchEvent(new MouseEvent('click', { bubbles: true }));
- expect(handleChange).not.toHaveBeenCalled();
- }
- }
- });
-
- it('should render borderless', () => {
- const { container } = render(<Select value="1" options={options} onChange={() => {}} borderless />);
- expect(container.querySelector('[data-u-comp="select"]')).toHaveClass('univer-border-transparent', { exact: false });
- });
-});
-
-describe('MultipleSelect', () => {
- it('should render with values', () => {
- const { getByText } = render(<MultipleSelect value={['1', '2']} options={options} onChange={() => {}} />);
- expect(getByText('Option 1')).toBeInTheDocument();
- expect(getByText('Option 2')).toBeInTheDocument();
- });
-
- it('should call onChange when select changes', () => {
- const handleChange = vi.fn();
- const { container } = render(<MultipleSelect value={['1']} options={options} onChange={handleChange} />);
- const selectDiv = container.querySelector('[data-u-comp="select"]');
- if (selectDiv) {
- selectDiv.dispatchEvent(new MouseEvent('click', { bubbles: true }));
- const optionBtn = Array.from(document.querySelectorAll('button')).find((btn) => btn.textContent === 'Option 2');
- if (optionBtn) {
- optionBtn.dispatchEvent(new MouseEvent('click', { bubbles: true }));
- expect(handleChange).toHaveBeenCalledWith(['1', '2']);
- }
- }
- });
-
- it('should not call onChange when disabled', () => {
- const handleChange = vi.fn();
- const { container } = render(<MultipleSelect value={['1']} options={options} onChange={handleChange} disabled />);
- const selectDiv = container.querySelector('[data-u-comp="select"]');
- if (selectDiv) {
- selectDiv.dispatchEvent(new MouseEvent('click', { bubbles: true }));
- const optionBtn = Array.from(document.querySelectorAll('button')).find((btn) => btn.textContent === 'Option 2');
- if (optionBtn) {
- optionBtn.dispatchEvent(new MouseEvent('click', { bubbles: true }));
- expect(handleChange).not.toHaveBeenCalled();
- }
- }
- });
-
- it('should remove badge value when close icon is clicked', () => {
- const handleChange = vi.fn();
- render(
- <ConfigProvider locale={enUS.design} mountContainer={document.body}>
- <MultipleSelect value={['1', '2']} options={options} onChange={handleChange} />
- </ConfigProvider>
- );
-
- const closeButtons = screen.getAllByLabelText(enUS.design.Accessibility.closeBadge);
- fireEvent.click(closeButtons[0]);
- expect(handleChange).toHaveBeenCalledWith(['2']);
- });
-
- it('should support borderless and disabled visual classes', () => {
- const { container, rerender } = render(<MultipleSelect value={['1']} options={options} onChange={() => {}} />);
- const trigger = container.querySelector('[data-u-comp="multiple-select"]') as HTMLDivElement;
-
- expect(trigger).toHaveClass('univer-cursor-pointer', { exact: false });
-
- rerender(<MultipleSelect value={['1']} options={options} onChange={() => {}} borderless />);
- expect((container.querySelector('[data-u-comp="multiple-select"]') as HTMLDivElement).className).toContain('univer-border-transparent');
-
- rerender(<MultipleSelect value={['1']} options={options} onChange={() => {}} disabled />);
- expect((container.querySelector('[data-u-comp="multiple-select"]') as HTMLDivElement).className).toContain('univer-cursor-not-allowed');
- });
-});
diff --git a/packages/design/src/components/select/__tests__/multiple-select.logic.spec.tsx b/packages/design/src/components/select/__tests__/multiple-select.logic.spec.tsx
deleted file mode 100644
index 6f0b35c264..0000000000
--- a/packages/design/src/components/select/__tests__/multiple-select.logic.spec.tsx
+++ /dev/null
@@ -1,88 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import { cleanup, fireEvent, render, screen } from '@testing-library/react';
-import { afterEach, describe, expect, it, vi } from 'vitest';
-import { MultipleSelect } from '../MultipleSelect';
-
-import '@testing-library/jest-dom/vitest';
-
-vi.mock('../../dropdown-menu/DropdownMenu', () => {
- return {
- DropdownMenu: ({ children, items = [], onOpenChange }: any) => (
- <div>
- <button type="button" data-testid="open-menu" onClick={() => onOpenChange?.(true)}>
- open
- </button>
- <button type="button" data-testid="close-menu" onClick={() => onOpenChange?.(false)}>
- close
- </button>
- {items.map((item: any) => (
- <button
- key={item.value}
- type="button"
- data-testid={`item-${item.value}`}
- onClick={() => item.onSelect?.(item.value)}
- >
- {String(item.value)}
- </button>
- ))}
- {children}
- </div>
- ),
- };
-});
-
-afterEach(() => {
- vi.restoreAllMocks();
- cleanup();
-});
-
-describe('MultipleSelect logic branches', () => {
- const options = [
- { label: 'Option 1', value: '1' },
- { label: 'Option 2', value: '2' },
- ];
-
- it('should handle open state and checkbox item select branches', () => {
- const onChange = vi.fn();
- const { container } = render(<MultipleSelect value={['1']} options={options} onChange={onChange} />);
-
- fireEvent.click(screen.getByTestId('open-menu'));
- expect((container.querySelector('[data-u-comp="multiple-select"]') as HTMLDivElement).className).toContain('univer-ring-2');
-
- fireEvent.click(screen.getByTestId('item-1'));
- expect(onChange).toHaveBeenCalledWith([]);
-
- fireEvent.click(screen.getByTestId('item-2'));
- expect(onChange).toHaveBeenCalledWith(['1', '2']);
-
- fireEvent.click(screen.getByTestId('close-menu'));
- expect((container.querySelector('[data-u-comp="multiple-select"]') as HTMLDivElement).className).toContain('univer-cursor-pointer');
- });
-
- it('uses the latest controlled value when selecting consecutive items', () => {
- const onChange = vi.fn();
- const { rerender } = render(<MultipleSelect value={[]} options={options} onChange={onChange} />);
-
- fireEvent.click(screen.getByTestId('item-1'));
- expect(onChange).toHaveBeenLastCalledWith(['1']);
-
- rerender(<MultipleSelect value={['1']} options={options} onChange={onChange} />);
- fireEvent.click(screen.getByTestId('item-2'));
- expect(onChange).toHaveBeenLastCalledWith(['1', '2']);
- });
-});
diff --git a/packages/docs-toc-ui/src/views/InsertTableOfContentsDialog.tsx b/packages/docs-toc-ui/src/views/InsertTableOfContentsDialog.tsx
index c76655f59b..4cc2833d89 100644
--- a/packages/docs-toc-ui/src/views/InsertTableOfContentsDialog.tsx
+++ b/packages/docs-toc-ui/src/views/InsertTableOfContentsDialog.tsx
@@ -17,6 +17,7 @@
import type { TableOfContentsFormat, TableOfContentsTabLeader } from '@univerjs/docs-toc';
import type { LocaleKey } from '../locale/types';
import { LocaleService } from '@univerjs/core';
+import { Checkbox, clsx, Select } from '@univerjs/design';
import { useDependency } from '@univerjs/ui';
import { useState } from 'react';
@@ -57,71 +58,58 @@ export function InsertTableOfContentsDialog(props: IInsertTableOfContentsDialogP
setValue(next);
props.onChange(next);
};
- const leader = value.tabLeader === 'dots' ? '··········' : value.tabLeader === 'dashes' ? '----------' : value.tabLeader === 'underline' ? '__________' : '';
+ const leader = { none: '', dots: '··········', dashes: '----------', underline: '__________' }[value.tabLeader];
+ const indent = { fromTemplate: 18, classic: 14, modern: 20, simple: 12 }[value.format];
return (
<div className="univer-grid univer-gap-4 univer-py-2" data-testid="table-of-contents-insert-dialog">
<div className="univer-grid univer-grid-cols-2 univer-gap-3">
<label className="univer-grid univer-gap-1 univer-text-sm">
<span>{localeService.t<LocaleKey>('docs-toc-ui.tableOfContents.levels')}</span>
- <select
- className="univer-h-8 univer-rounded-md univer-border univer-bg-transparent univer-px-2"
- value={value.levels}
- onChange={(event) => update({ levels: Number(event.target.value) })}
- >
- {Array.from({ length: 9 }, (_, index) => index + 1).map((level) => (
- <option key={level} value={level}>{level}</option>
- ))}
- </select>
+ <Select
+ aria-label={localeService.t<LocaleKey>('docs-toc-ui.tableOfContents.levels')}
+ value={String(value.levels)}
+ options={Array.from({ length: 9 }, (_, index) => ({ value: String(index + 1), label: String(index + 1) }))}
+ onChange={(levels) => update({ levels: Number(levels) })}
+ />
</label>
<label className="univer-grid univer-gap-1 univer-text-sm">
<span>{localeService.t<LocaleKey>('docs-toc-ui.tableOfContents.format')}</span>
- <select
- className="univer-h-8 univer-rounded-md univer-border univer-bg-transparent univer-px-2"
+ <Select
+ aria-label={localeService.t<LocaleKey>('docs-toc-ui.tableOfContents.format')}
value={value.format}
- onChange={(event) => update({ format: event.target.value as TableOfContentsFormat })}
- >
- {FORMAT_OPTIONS.map(([format, label]) => (
- <option key={format} value={format}>{localeService.t<LocaleKey>(label)}</option>
- ))}
- </select>
+ options={FORMAT_OPTIONS.map(([format, label]) => ({ value: format, label: localeService.t<LocaleKey>(label) }))}
+ onChange={(format) => update({ format: format as TableOfContentsFormat })}
+ />
</label>
</div>
<div className="univer-grid univer-gap-2 univer-text-sm">
- <label className="univer-flex univer-items-center univer-gap-2">
- <input
- type="checkbox"
- checked={value.showPageNumbers}
- onChange={(event) => update({
- showPageNumbers: event.target.checked,
- rightAlignPageNumbers: event.target.checked && value.rightAlignPageNumbers,
- })}
- />
- <span>{localeService.t<LocaleKey>('docs-toc-ui.tableOfContents.showPageNumbers')}</span>
- </label>
- <label className="univer-flex univer-items-center univer-gap-2">
- <input
- type="checkbox"
- checked={value.rightAlignPageNumbers}
- disabled={!value.showPageNumbers}
- onChange={(event) => update({ rightAlignPageNumbers: event.target.checked })}
- />
- <span>{localeService.t<LocaleKey>('docs-toc-ui.tableOfContents.rightAlignPageNumbers')}</span>
- </label>
+ <Checkbox
+ checked={value.showPageNumbers}
+ onChange={(checked) => update({
+ showPageNumbers: Boolean(checked),
+ rightAlignPageNumbers: Boolean(checked) && value.rightAlignPageNumbers,
+ })}
+ >
+ {localeService.t<LocaleKey>('docs-toc-ui.tableOfContents.showPageNumbers')}
+ </Checkbox>
+ <Checkbox
+ checked={value.rightAlignPageNumbers}
+ disabled={!value.showPageNumbers}
+ onChange={(checked) => update({ rightAlignPageNumbers: Boolean(checked) })}
+ >
+ {localeService.t<LocaleKey>('docs-toc-ui.tableOfContents.rightAlignPageNumbers')}
+ </Checkbox>
<label className="univer-flex univer-items-center univer-justify-between univer-gap-3">
<span>{localeService.t<LocaleKey>('docs-toc-ui.tableOfContents.tabLeader')}</span>
- <select
- className="
- univer-h-8 univer-min-w-40 univer-rounded-md univer-border univer-bg-transparent univer-px-2
- "
+ <Select
+ aria-label={localeService.t<LocaleKey>('docs-toc-ui.tableOfContents.tabLeader')}
+ className="univer-min-w-40"
value={value.tabLeader}
disabled={!value.showPageNumbers || !value.rightAlignPageNumbers}
- onChange={(event) => update({ tabLeader: event.target.value as TableOfContentsTabLeader })}
- >
- {LEADER_OPTIONS.map(([tabLeader, label]) => (
- <option key={tabLeader} value={tabLeader}>{localeService.t<LocaleKey>(label)}</option>
- ))}
- </select>
+ options={LEADER_OPTIONS.map(([tabLeader, label]) => ({ value: tabLeader, label: localeService.t<LocaleKey>(label) }))}
+ onChange={(tabLeader) => update({ tabLeader: tabLeader as TableOfContentsTabLeader })}
+ />
</label>
</div>
<section
@@ -136,13 +124,10 @@ export function InsertTableOfContentsDialog(props: IInsertTableOfContentsDialogP
{Array.from({ length: Math.min(value.levels, 3) }, (_, index) => index).map((level) => (
<div
key={level}
- className={`
- univer-flex univer-items-baseline univer-text-sm
- ${value.format === 'modern'
- ? 'univer-mb-2'
- : 'univer-mb-1'}
- `}
- style={{ marginInlineStart: `${level * (value.format === 'simple' ? 12 : value.format === 'classic' ? 14 : value.format === 'modern' ? 20 : 18)}px` }}
+ className={clsx('univer-flex univer-items-baseline univer-text-sm', value.format === 'modern'
+ ? 'univer-mb-2'
+ : 'univer-mb-1')}
+ style={{ marginInlineStart: `${level * indent}px` }}
>
<span>
{localeService.t<LocaleKey>('docs-toc-ui.tableOfContents.previewHeading')}
diff --git a/packages/docs-toc-ui/src/views/TableOfContentsDialog.tsx b/packages/docs-toc-ui/src/views/TableOfContentsDialog.tsx
index 6c4cfb6f8a..3e3c4a5d1b 100644
--- a/packages/docs-toc-ui/src/views/TableOfContentsDialog.tsx
+++ b/packages/docs-toc-ui/src/views/TableOfContentsDialog.tsx
@@ -16,6 +16,7 @@
import type { LocaleKey } from '../locale/types';
import { LocaleService } from '@univerjs/core';
+import { Radio, RadioGroup } from '@univerjs/design';
import { useDependency } from '@univerjs/ui';
import { useState } from 'react';
@@ -39,28 +40,27 @@ export function TableOfContentsDialog(props: ITableOfContentsDialogProps) {
<p className="univer-m-0 univer-text-sm">
{localeService.t<LocaleKey>('docs-toc-ui.tableOfContents.updateHint')}
</p>
- <fieldset className="univer-grid univer-gap-3 univer-border-0 univer-p-0">
+ <RadioGroup
+ direction="vertical"
+ className="univer-gap-3"
+ value={mode}
+ onChange={(nextMode) => {
+ const next = nextMode as ITableOfContentsDialogProps['mode'];
+ setMode(next);
+ props.onModeChange(next);
+ }}
+ >
{options.map(([value, label]) => (
- <label
+ <Radio
key={value}
+ name="toc-update-mode"
+ value={value}
className="univer-flex univer-gap-3 univer-rounded-lg univer-border univer-p-3"
>
- <input
- type="radio"
- name="toc-update-mode"
- value={value}
- checked={mode === value}
- onChange={() => {
- setMode(value);
- props.onModeChange(value);
- }}
- />
- <span className="univer-text-sm">
- {localeService.t<LocaleKey>(label)}
- </span>
- </label>
+ {localeService.t<LocaleKey>(label)}
+ </Radio>
))}
- </fieldset>
+ </RadioGroup>
</div>
);
}
diff --git a/packages/docs-toc-ui/src/views/__tests__/InsertTableOfContentsDialog.spec.tsx b/packages/docs-toc-ui/src/views/__tests__/InsertTableOfContentsDialog.spec.tsx
new file mode 100644
index 0000000000..a3bac86c67
--- /dev/null
+++ b/packages/docs-toc-ui/src/views/__tests__/InsertTableOfContentsDialog.spec.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 { Root } from 'react-dom/client';
+import type { IInsertTableOfContentsDialogProps } from '../InsertTableOfContentsDialog';
+import { LocaleService, LocaleType, Univer } from '@univerjs/core';
+import { ConfigProvider } from '@univerjs/design';
+import designEnUS from '@univerjs/design/locale/en-US';
+import { RediContext } from '@univerjs/ui';
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import enUS from '../../locale/en-US';
+import { InsertTableOfContentsDialog } from '../InsertTableOfContentsDialog';
+
+describe('InsertTableOfContentsDialog', () => {
+ let root: Root;
+ let container: HTMLDivElement;
+ let univer: Univer;
+
+ beforeEach(() => {
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
+ univer = new Univer({ locale: LocaleType.EN_US, locales: { [LocaleType.EN_US]: enUS } });
+ univer.__getInjector().get(LocaleService).setDirection('ltr');
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ });
+
+ afterEach(async () => {
+ await act(async () => root.unmount());
+ container.remove();
+ univer.dispose();
+ vi.unstubAllGlobals();
+ });
+
+ async function renderDialog(onChange: IInsertTableOfContentsDialogProps['onChange']) {
+ await act(async () => root.render(
+ <RediContext.Provider value={{ injector: univer.__getInjector() }}>
+ <ConfigProvider mountContainer={container} locale={designEnUS.design} direction="ltr">
+ <InsertTableOfContentsDialog
+ options={{ levels: 3, showPageNumbers: true, rightAlignPageNumbers: true, tabLeader: 'dots', format: 'fromTemplate' }}
+ onChange={onChange}
+ />
+ </ConfigProvider>
+ </RediContext.Provider>
+ ));
+ }
+
+ it('keeps page number, alignment and leader availability in sync', async () => {
+ const onChange = vi.fn();
+ await renderDialog(onChange);
+ const checkboxes = [...container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]')];
+ const label = enUS['docs-toc-ui'].tableOfContents.tabLeader;
+ const leader = container.querySelector<HTMLButtonElement>(`button[aria-label="${label}"]`)!;
+ expect(container.textContent).toContain('··········');
+ await act(async () => checkboxes[0].click());
+ expect(checkboxes[1].disabled).toBe(true);
+ expect(leader.disabled).toBe(true);
+ expect(container.textContent).not.toContain('··········');
+ expect(onChange).toHaveBeenLastCalledWith(expect.objectContaining({ showPageNumbers: false, rightAlignPageNumbers: false }));
+ await act(async () => checkboxes[0].click());
+ await act(async () => checkboxes[1].click());
+ expect(leader.disabled).toBe(false);
+ expect(onChange).toHaveBeenLastCalledWith(expect.objectContaining({ showPageNumbers: true, rightAlignPageNumbers: true }));
+ });
+
+ it('selects levels, format and leader without losing earlier edits', async () => {
+ const onChange = vi.fn();
+ await renderDialog(onChange);
+ const copy = enUS['docs-toc-ui'].tableOfContents;
+ for (const [label, option] of [[copy.levels, '9'], [copy.format, copy.formatModern], [copy.tabLeader, copy.leaderDashes]]) {
+ const trigger = container.querySelector<HTMLButtonElement>(`button[aria-label="${label}"]`)!;
+ await act(async () => {
+ trigger.focus();
+ trigger.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true }));
+ });
+ const item = await vi.waitFor(() => {
+ const optionElement = [...document.querySelectorAll<HTMLElement>('[role="menuitemradio"]')].find((node) => node.textContent === option);
+ expect(optionElement, `${label}: ${option}`).toBeDefined();
+ return optionElement!;
+ });
+ await act(async () => item.click());
+ await vi.waitFor(() => expect(document.querySelector('[role="menu"]')).toBeNull());
+ await vi.waitFor(() => expect(document.activeElement).toBe(trigger));
+ }
+ expect(onChange).toHaveBeenLastCalledWith({ levels: 9, format: 'modern', tabLeader: 'dashes', showPageNumbers: true, rightAlignPageNumbers: true });
+ expect(container.textContent).toContain('----------');
+ });
+});
diff --git a/packages/docs-toc-ui/src/views/__tests__/TableOfContentsDialog.spec.tsx b/packages/docs-toc-ui/src/views/__tests__/TableOfContentsDialog.spec.tsx
index 30abca4037..8da8820e03 100644
--- a/packages/docs-toc-ui/src/views/__tests__/TableOfContentsDialog.spec.tsx
+++ b/packages/docs-toc-ui/src/views/__tests__/TableOfContentsDialog.spec.tsx
@@ -15,107 +15,46 @@
*/
import type { Root } from 'react-dom/client';
-import { Injector, LocaleService, LocaleType } from '@univerjs/core';
+import { LocaleService, LocaleType, Univer } from '@univerjs/core';
import { RediContext } from '@univerjs/ui';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
-import { afterEach, describe, expect, it, vi } from 'vitest';
-import { InsertTableOfContentsDialog } from '../InsertTableOfContentsDialog';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import enUS from '../../locale/en-US';
import { TableOfContentsDialog } from '../TableOfContentsDialog';
-(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
-
describe('TableOfContentsDialog', () => {
- let root: Root | undefined;
- let container: HTMLDivElement | undefined;
+ let root: Root;
+ let container: HTMLDivElement;
+ let univer: Univer;
+
+ beforeEach(() => {
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
+ univer = new Univer({ locale: LocaleType.EN_US, locales: { [LocaleType.EN_US]: enUS } });
+ univer.__getInjector().get(LocaleService).setDirection('ltr');
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ });
afterEach(async () => {
- if (root) await act(async () => root?.unmount());
- container?.remove();
+ await act(async () => root.unmount());
+ container.remove();
+ univer.dispose();
+ vi.unstubAllGlobals();
});
- it('defaults to page-only update and allows selecting a full update', async () => {
- const injector = new Injector();
- injector.add([LocaleService, { useClass: LocaleService }]);
- injector.get(LocaleService).load({
- [LocaleType.EN_US]: {
- 'docs-toc-ui': {
- tableOfContents: {
- updatePageNumbersOnly: 'Update page numbers only',
- updateEntireTable: 'Update entire table',
- updateHint: 'Choose an update mode.',
- },
- },
- },
- });
+ it('defaults to page numbers and allows switching to a full update', async () => {
const onModeChange = vi.fn();
- container = document.createElement('div');
- document.body.appendChild(container);
- root = createRoot(container);
- await act(async () => root?.render(
- <RediContext.Provider value={{ injector }}>
+ await act(async () => root.render(
+ <RediContext.Provider value={{ injector: univer.__getInjector() }}>
<TableOfContentsDialog mode="pageNumbersOnly" onModeChange={onModeChange} />
</RediContext.Provider>
));
-
const radios = [...container.querySelectorAll<HTMLInputElement>('input[type="radio"]')];
expect(radios.map((radio) => radio.checked)).toEqual([true, false]);
await act(async () => radios[1].click());
expect(radios.map((radio) => radio.checked)).toEqual([false, true]);
- expect(onModeChange).toHaveBeenCalledWith('entireTable');
-
- injector.dispose();
- });
-
- it('edits custom TOC options and updates the preview', async () => {
- const injector = new Injector();
- injector.add([LocaleService, { useClass: LocaleService }]);
- injector.get(LocaleService).load({
- [LocaleType.EN_US]: {
- 'docs-toc-ui': {
- tableOfContents: {
- levels: 'Show levels',
- format: 'Formats',
- formatFromTemplate: 'From template',
- formatClassic: 'Classic',
- formatModern: 'Modern',
- formatSimple: 'Simple',
- showPageNumbers: 'Show page numbers',
- rightAlignPageNumbers: 'Right align page numbers',
- tabLeader: 'Tab leader',
- leaderNone: 'None',
- leaderDots: 'Dots',
- leaderDashes: 'Dashes',
- leaderUnderline: 'Underline',
- preview: 'Print preview',
- previewHeading: 'Heading',
- },
- },
- },
- });
- const onChange = vi.fn();
- container = document.createElement('div');
- document.body.appendChild(container);
- root = createRoot(container);
- await act(async () => root?.render(
- <RediContext.Provider value={{ injector }}>
- <InsertTableOfContentsDialog
- options={{ levels: 3, showPageNumbers: true, rightAlignPageNumbers: true, tabLeader: 'dots', format: 'fromTemplate' }}
- onChange={onChange}
- />
- </RediContext.Provider>
- ));
-
- const checkboxes = [...container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]')];
- const selects = [...container.querySelectorAll<HTMLSelectElement>('select')];
- expect(container.textContent).toContain('··········');
- await act(async () => {
- checkboxes[0].click();
- });
- expect(checkboxes.map((checkbox) => checkbox.checked)).toEqual([false, false]);
- expect(selects[2].disabled).toBe(true);
- expect(onChange).toHaveBeenLastCalledWith(expect.objectContaining({ showPageNumbers: false, rightAlignPageNumbers: false }));
-
- injector.dispose();
+ expect(onModeChange).toHaveBeenCalledExactlyOnceWith('entireTable');
});
});
diff --git a/packages/docs-ui/src/menu/schema.ts b/packages/docs-ui/src/menu/schema.ts
index 0f5a62d46c..46ef6b2681 100644
--- a/packages/docs-ui/src/menu/schema.ts
+++ b/packages/docs-ui/src/menu/schema.ts
@@ -340,15 +340,6 @@ export const menuSchema: MenuSchemaType = {
gridLayout: { row: 1, column: 3, rowSpan: 2, showLabel: true },
menuItemFactory: HeaderFooterMenuItemFactory,
},
- // [SwitchDocModeCommand.id]: {
- // order: 11,
- // menuItemFactory: DocSwitchModeMenuItemFactory,
- // },
- [DocOpenPageSettingCommand.id]: {
- order: 12,
- gridLayout: { row: 1, column: 4, rowSpan: 2, showLabel: true },
- menuItemFactory: PageSettingMenuItemFactory,
- },
},
[RibbonInsertGroup.MEDIA]: {
[TABLE_MENU_ID]: {
@@ -406,14 +397,19 @@ export const menuSchema: MenuSchemaType = {
},
},
[RibbonViewGroup.DISPLAY]: {
- [DOC_ZOOM_RATIO_MENU_ID]: {
+ [DocOpenPageSettingCommand.id]: {
order: 0,
- gridLayout: { row: 1, column: 1 },
+ gridLayout: { row: 1, column: 1, rowSpan: 2, showLabel: true },
+ menuItemFactory: PageSettingMenuItemFactory,
+ },
+ [DOC_ZOOM_RATIO_MENU_ID]: {
+ order: 1,
+ gridLayout: { row: 1, column: 2 },
menuItemFactory: DocZoomRatioMenuItemFactory,
},
[ToggleFullscreenOperation.id]: {
- order: 1,
- gridLayout: { row: 2, column: 1 },
+ order: 2,
+ gridLayout: { row: 2, column: 2 },
menuItemFactory: DocFullscreenMenuItemFactory,
},
},
diff --git a/packages/docs-ui/src/views/mobile-rich-text-toolbar/MobileRichTextToolbar.tsx b/packages/docs-ui/src/views/mobile-rich-text-toolbar/MobileRichTextToolbar.tsx
index 3d73278725..09f64e8540 100644
--- a/packages/docs-ui/src/views/mobile-rich-text-toolbar/MobileRichTextToolbar.tsx
+++ b/packages/docs-ui/src/views/mobile-rich-text-toolbar/MobileRichTextToolbar.tsx
@@ -18,8 +18,15 @@ import type { ITextStyle, Nullable } from '@univerjs/core';
import type { ReactNode } from 'react';
import type { LocaleKey } from '../../locale/types';
import type { Editor } from '../../services/editor/editor';
-import { BooleanNumber, BuildTextUtils, ICommandService, LocaleService, PresetListType, ThemeService } from '@univerjs/core';
-import { clsx, resetButtonClassName } from '@univerjs/design';
+import {
+ BooleanNumber,
+ BuildTextUtils,
+ ICommandService,
+ LocaleService,
+ PresetListType,
+ ThemeService,
+} from '@univerjs/core';
+import { Button, clsx, MobileColorPicker, MobileDropdown, resetButtonClassName } from '@univerjs/design';
import {
BoldIcon,
ColorWheelMultiIcon,
@@ -64,6 +71,38 @@ export interface IMobileRichTextToolbarProps {
}
export function MobileRichTextToolbar({ editorId, className }: IMobileRichTextToolbarProps) {
+ function resolveToolbarState(editor: Readonly<Nullable<Editor>>, defaultTextColor: string): {
+ bold: boolean;
+ italic: boolean;
+ underline: boolean;
+ strike: boolean;
+ color: string;
+ bulletList: boolean;
+ orderList: boolean;
+ } {
+ const body = editor?.getDocumentData().body;
+ const ranges = editor?.getSelectionRanges() ?? [];
+ const range = ranges.find((item) => item.isActive) ?? ranges[0];
+ if (!body || !range) {
+ return { bold: false, italic: false, underline: false, strike: false, color: defaultTextColor, bulletList: false, orderList: false };
+ }
+
+ const style: ITextStyle = getStyleInTextRange(body, range, {});
+ const paragraphs = BuildTextUtils.range.getParagraphsInRanges([range], body.paragraphs ?? [], body.dataStream);
+ const listTypes = paragraphs
+ .map((paragraph) => paragraph.bullet?.listType)
+ .filter((listType): listType is string => typeof listType === 'string');
+ return {
+ bold: style.bl === BooleanNumber.TRUE,
+ italic: style.it === BooleanNumber.TRUE,
+ underline: style.ul?.s === BooleanNumber.TRUE,
+ strike: style.st?.s === BooleanNumber.TRUE,
+ color: style.cl?.rgb ?? defaultTextColor,
+ bulletList: Boolean(listTypes.length && listTypes.every((listType) => listType.startsWith(PresetListType.BULLET_LIST))),
+ orderList: Boolean(listTypes.length && listTypes.every((listType) => listType.startsWith(PresetListType.ORDER_LIST))),
+ };
+ }
+
const commandService = useDependency(ICommandService);
const editorService = useDependency(IEditorService);
const localeService = useDependency(LocaleService);
@@ -80,7 +119,9 @@ export function MobileRichTextToolbar({ editorId, className }: IMobileRichTextTo
}, [editorId, editorService]);
useEffect(() => {
- if (!editor) return undefined;
+ if (!editor) {
+ return undefined;
+ }
const subscription = merge(editor.input$, editor.selectionChange$).subscribe(() => setRevision((value) => value + 1));
return () => subscription.unsubscribe();
}, [editor]);
@@ -183,28 +224,26 @@ export function MobileRichTextToolbar({ editorId, className }: IMobileRichTextTo
onClick={() => execute(SetInlineFormatTextColorCommand.id, { value: color })}
/>
))}
- <label
- aria-label={localeService.t<LocaleKey>('docs-ui.toolbar.textColor.main')}
- className={clsx(resetButtonClassName, `
- univer-relative univer-flex univer-size-7 univer-items-center univer-justify-center
- univer-justify-self-center univer-overflow-hidden univer-rounded-md univer-border-2
- univer-border-solid univer-border-transparent
- active:univer-scale-95
- `)}
+ <MobileDropdown
+ overlay={(
+ <div className="univer-px-4 univer-pb-2" onPointerDown={(event) => event.stopPropagation()}>
+ <MobileColorPicker
+ value={state.color}
+ onChange={(color) => execute(SetInlineFormatTextColorCommand.id, { value: color })}
+ />
+ </div>
+ )}
>
- <ColorWheelMultiIcon className="univer-size-6" />
- <input
+ <Button
+ type="button"
+ variant="text"
+ size="icon"
aria-label={localeService.t<LocaleKey>('docs-ui.toolbar.textColor.main')}
- className="
- univer-absolute univer-inset-0 univer-size-full univer-cursor-pointer univer-opacity-0
- "
- type="color"
- defaultValue={defaultTextColor}
- onChange={(event) => {
- execute(SetInlineFormatTextColorCommand.id, { value: event.target.value });
- }}
- />
- </label>
+ className="univer-size-7 univer-justify-self-center"
+ >
+ <ColorWheelMultiIcon className="!univer-size-6" />
+ </Button>
+ </MobileDropdown>
</div>
)}
</div>
@@ -229,35 +268,3 @@ function FormatButton(props: {
</button>
);
}
-
-function resolveToolbarState(editor: Readonly<Nullable<Editor>>, defaultTextColor: string): {
- bold: boolean;
- italic: boolean;
- underline: boolean;
- strike: boolean;
- color: string;
- bulletList: boolean;
- orderList: boolean;
-} {
- const body = editor?.getDocumentData().body;
- const ranges = editor?.getSelectionRanges() ?? [];
- const range = ranges.find((item) => item.isActive) ?? ranges[0];
- if (!body || !range) {
- return { bold: false, italic: false, underline: false, strike: false, color: defaultTextColor, bulletList: false, orderList: false };
- }
-
- const style: ITextStyle = getStyleInTextRange(body, range, {});
- const paragraphs = BuildTextUtils.range.getParagraphsInRanges([range], body.paragraphs ?? [], body.dataStream);
- const listTypes = paragraphs
- .map((paragraph) => paragraph.bullet?.listType)
- .filter((listType): listType is string => typeof listType === 'string');
- return {
- bold: style.bl === BooleanNumber.TRUE,
- italic: style.it === BooleanNumber.TRUE,
- underline: style.ul?.s === BooleanNumber.TRUE,
- strike: style.st?.s === BooleanNumber.TRUE,
- color: style.cl?.rgb ?? defaultTextColor,
- bulletList: Boolean(listTypes.length && listTypes.every((listType) => listType.startsWith(PresetListType.BULLET_LIST))),
- orderList: Boolean(listTypes.length && listTypes.every((listType) => listType.startsWith(PresetListType.ORDER_LIST))),
- };
-}
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 f5ca41f9e9..2a6f1c0709 100644
--- a/packages/drawing-ui/src/views/object-list-panel/ObjectListPanelBase.tsx
+++ b/packages/drawing-ui/src/views/object-list-panel/ObjectListPanelBase.tsx
@@ -15,7 +15,7 @@
*/
import type { ComponentProps, ComponentType, DragEvent, FocusEvent, KeyboardEvent, MouseEvent, ReactNode } from 'react';
-import { Button, clsx, Input, StateIconButton } from '@univerjs/design';
+import { Button, clsx, Input, StateIconButton, Textarea } from '@univerjs/design';
import {
ArrowDownIcon,
ArrowUpIcon,
@@ -771,7 +771,6 @@ export function ObjectDetailsEditor(props: {
{labels.name}
</span>
<InputComponent
-
value={draftName}
aria-label={labels.nameInput}
disabled={disabled}
@@ -799,16 +798,8 @@ export function ObjectDetailsEditor(props: {
>
{labels.description}
</span>
- <textarea
- 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
- focus:univer-border-primary-500 focus:univer-ring-1 focus:univer-ring-primary-100
- 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
- `)}
+ <Textarea
+ className={clsx('univer-min-h-16 univer-resize-none univer-text-sm', descriptionClassName)}
value={draftDescription}
disabled={disabled}
placeholder={labels.descriptionPlaceholder}
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 d658981187..d32e162817 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,13 +21,11 @@ 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, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import enUS from '../../../locale/en-US';
import { MobileObjectListPanel } from '../MobileObjectListPanel';
import { ObjectListPanelBase } from '../ObjectListPanelBase';
-Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { value: true, configurable: true });
-
describe.each([
{ name: 'desktop', PanelComponent: ObjectListPanelBase },
{ name: 'mobile', PanelComponent: MobileObjectListPanel },
@@ -39,6 +37,7 @@ describe.each([
let selectableChanges: Array<{ ids: string[]; selectable: boolean }>;
beforeEach(() => {
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
univer = new Univer({ locale: LocaleType.EN_US, locales: { [LocaleType.EN_US]: enUS } });
univer.__getInjector().get(LocaleService).setDirection('ltr');
container = document.createElement('div');
@@ -48,15 +47,16 @@ describe.each([
selectableChanges = [];
});
- afterEach(() => {
- act(() => root.unmount());
+ afterEach(async () => {
+ await act(async () => root.unmount());
container.remove();
univer.dispose();
+ vi.unstubAllGlobals();
});
- function render(element: ReactElement) {
- act(() => root.render(element));
- return { rerender: (next: ReactElement) => act(() => root.render(next)) };
+ async function render(element: ReactElement) {
+ await act(async () => root.render(element));
+ return { rerender: async (next: ReactElement) => act(async () => root.render(next)) };
}
function getButton(name: string): HTMLButtonElement {
@@ -67,8 +67,8 @@ describe.each([
return button;
}
- function click(button: HTMLButtonElement): void {
- act(() => button.click());
+ async function click(button: HTMLButtonElement) {
+ await act(async () => button.click());
}
function panel(items: IObjectListPanelItem[], props: Partial<IObjectListPanelBaseProps> = {}) {
@@ -90,54 +90,72 @@ describe.each([
);
}
- it('switches both bulk actions from current model state, including external updates', () => {
+ it('switches both bulk actions from current model state, including external updates', async () => {
const original = [{ id: 'a', name: 'A', visible: true }, { id: 'b', name: 'B', visible: true }];
- const view = render(panel(original));
- click(getButton('Hide all'));
+ const view = await render(panel(original));
+ await click(getButton('Hide all'));
expect(visibilityChanges).toEqual([{ ids: ['a', 'b'], visible: false }]);
- click(getButton('Lock all'));
+ await 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'));
+ await view.rerender(panel(original.map((item) => ({ ...item, visible: false, selectable: false }))));
+ await click(getButton('Show all'));
+ await 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));
+ await 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', () => {
+ it('includes collapsed children and ignores the search filter when normalizing mixed states', async () => {
const group = { id: 'group', name: 'Group', visible: true, selectable: false, isGroup: true, expanded: false };
- render(panel([group], {
+ await render(panel([group], {
allItems: [group, { id: 'child', visible: false, selectable: true }],
}));
const search = container.querySelector<HTMLInputElement>('input[placeholder="Search objects"]')!;
- act(() => {
+ await act(async () => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(search, 'unmatched');
search.dispatchEvent(new Event('input', { bubbles: true }));
});
- click(getButton('Show all'));
- click(getButton('Lock all'));
+ await click(getButton('Show all'));
+ await 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', () => {
+ it('excludes unavailable capabilities and disables actions when no targets exist', async () => {
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'));
+ const view = await render(panel(items));
+ await click(getButton('Hide all'));
+ await click(getButton('Lock all'));
expect(visibilityChanges).toEqual([{ ids: ['available'], visible: false }]);
expect(selectableChanges).toEqual([{ ids: ['available'], selectable: false }]);
- view.rerender(panel([]));
+ await view.rerender(panel([]));
expect(getButton('Show all').disabled).toBe(true);
expect(getButton('Lock all').disabled).toBe(true);
});
+
+ it('commits the description on blur and follows external updates', async () => {
+ const onCommitDescription = vi.fn();
+ const item = { id: 'a', name: 'A', description: 'Original', visible: true };
+ const props = { selectedIds: ['a'], onCommitDescription };
+ const view = await render(panel([item], props));
+ const description = container.querySelector<HTMLTextAreaElement>('textarea')!;
+ await act(async () => {
+ description.focus();
+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!.call(description, 'New description');
+ description.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ expect(onCommitDescription).not.toHaveBeenCalled();
+ await act(async () => description.blur());
+ expect(onCommitDescription).toHaveBeenCalledExactlyOnceWith('a', 'New description');
+ await view.rerender(panel([{ ...item, description: 'External update' }], props));
+ expect(description.value).toBe('External update');
+ });
});
diff --git a/packages/find-replace/src/views/mobile/MobileFindReplaceBar.tsx b/packages/find-replace/src/views/mobile/MobileFindReplaceBar.tsx
index b88e52811e..80b45d83fd 100644
--- a/packages/find-replace/src/views/mobile/MobileFindReplaceBar.tsx
+++ b/packages/find-replace/src/views/mobile/MobileFindReplaceBar.tsx
@@ -17,7 +17,7 @@
import type { ReactNode } from 'react';
import type { LocaleKey } from '../../locale/types';
import { ICommandService, LocaleService } from '@univerjs/core';
-import { clsx, Input, resetButtonClassName, useMobileKeyboardViewportLayout } from '@univerjs/design';
+import { Button, Input, useMobileKeyboardViewportLayout } from '@univerjs/design';
import { ArrowDownIcon, ArrowUpIcon, CloseIcon, ConfigureTabIcon, SearchIcon } from '@univerjs/icons';
import { IDialogService, useDependency, useObservable } from '@univerjs/ui';
import { useEffect, useRef, useState } from 'react';
@@ -267,22 +267,17 @@ interface IIconButtonProps {
function IconButton(props: IIconButtonProps) {
return (
- <button
+ <Button
type="button"
aria-label={props.label}
disabled={props.disabled}
- className={clsx(resetButtonClassName, `
- univer-flex univer-size-9 univer-flex-none univer-items-center univer-justify-center univer-rounded-full
- univer-text-lg univer-text-gray-700
- active:univer-bg-gray-100
- disabled:univer-opacity-35
- dark:!univer-text-gray-200
- dark:active:!univer-bg-gray-700
- `)}
+ variant="text"
+ size="icon"
+ className="univer-size-9 univer-flex-none univer-rounded-full"
onClick={props.onClick}
>
{props.children}
- </button>
+ </Button>
);
}
@@ -294,19 +289,15 @@ interface IActionButtonProps {
function ActionButton(props: IActionButtonProps) {
return (
- <button
+ <Button
type="button"
disabled={props.disabled}
- className={clsx(resetButtonClassName, `
- univer-h-10 univer-flex-none univer-whitespace-nowrap univer-rounded-lg univer-bg-primary-600 univer-px-3
- univer-text-sm univer-font-medium univer-text-gray-0
- active:univer-bg-primary-700
- disabled:univer-bg-gray-100 disabled:univer-text-gray-400
- dark:disabled:!univer-bg-gray-700 dark:disabled:!univer-text-gray-500
- `)}
+ variant="primary"
+ size="large"
+ className="univer-flex-none"
onClick={props.onClick}
>
{props.children}
- </button>
+ </Button>
);
}
diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/ColorScale.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/ColorScale.tsx
index 7bdf352f36..f8c46b65b0 100644
--- a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/ColorScale.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/ColorScale.tsx
@@ -20,13 +20,14 @@ import type { IFormulaEditorRef } from '@univerjs/sheets-formula-ui';
import type { LocaleKey } from '../../../locale/types';
import type { IStyleEditorProps } from './type';
import { IUniverInstanceService, LocaleService, UniverInstanceType } from '@univerjs/core';
-import { borderClassName, clsx, InputNumber, Select } from '@univerjs/design';
+import { borderClassName, clsx, Select } from '@univerjs/design';
import { CFRuleType, CFValueType, createDefaultValueByValueType } from '@univerjs/sheets-conditional-formatting';
import { FormulaEditor } from '@univerjs/sheets-formula-ui';
import { useDependency, useSidebarClick } from '@univerjs/ui';
import { useEffect, useMemo, useRef, useState } from 'react';
import { ColorPicker } from '../../ColorPicker';
import { ConditionalFormattingRulePreview } from '../../ConditionalFormattingRulePreview';
+import { RuleNumberInput } from './RuleNumberInput';
import { previewClassName } from './styles';
const createOptionItem = (text: CFValueType | 'none'): { label: LocaleKey; value: CFValueType | 'none' } => ({
@@ -100,7 +101,7 @@ const TextInput = (props: {
</div>
);
} else {
- return <InputNumber className={className} value={Number(props.value) || 0} onChange={(v) => props.onChange(v || 0)} {...config} />;
+ return <RuleNumberInput className={className} value={Number(props.value) || 0} onChange={(v) => props.onChange(v || 0)} {...config} />;
}
};
export const ColorScaleStyleEditor = (props: IStyleEditorProps) => {
diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/DataBar.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/DataBar.tsx
index 2e8829c9bc..a2011ff383 100644
--- a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/DataBar.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/DataBar.tsx
@@ -20,7 +20,7 @@ import type { IFormulaEditorRef } from '@univerjs/sheets-formula-ui';
import type { LocaleKey } from '../../../locale/types';
import type { IStyleEditorProps } from './type';
import { IUniverInstanceService, LocaleService, UniverInstanceType } from '@univerjs/core';
-import { borderClassName, Checkbox, clsx, InputNumber, Radio, RadioGroup, Select } from '@univerjs/design';
+import { borderClassName, Checkbox, clsx, Radio, RadioGroup, Select } from '@univerjs/design';
import {
CFRuleType,
CFValueType,
@@ -33,6 +33,7 @@ import { useDependency, useSidebarClick } from '@univerjs/ui';
import { useEffect, useMemo, useRef, useState } from 'react';
import { ColorPicker } from '../../ColorPicker';
import { ConditionalFormattingRulePreview } from '../../ConditionalFormattingRulePreview';
+import { RuleNumberInput } from './RuleNumberInput';
import { previewClassName } from './styles';
const createOptionItem = (text: CFValueType): { label: LocaleKey; value: CFValueType } => ({
@@ -104,7 +105,7 @@ const InputText = (props: {
);
}
return (
- <InputNumber
+ <RuleNumberInput
className={className}
value={Number(value) || 0}
disabled={disabled}
diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/HighlightCell.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/HighlightCell.tsx
index 4d818b1e08..581f6efff6 100644
--- a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/HighlightCell.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/HighlightCell.tsx
@@ -25,7 +25,7 @@ import type {
import type { LocaleKey } from '../../../locale/types';
import type { IStyleEditorProps } from './type';
import { LocaleService } from '@univerjs/core';
-import { Input, InputNumber, Select } from '@univerjs/design';
+import { Input, Select } from '@univerjs/design';
import {
CFNumberOperator,
CFRuleType,
@@ -39,6 +39,7 @@ import { useEffect, useMemo, useState } from 'react';
import { ConditionalFormattingRulePreview } from '../../ConditionalFormattingRulePreview';
import { ConditionalStyleEditor } from '../../ConditionalStyleEditor';
import { WrapperError } from '../../wrapper-error/WrapperError';
+import { RuleNumberInput } from './RuleNumberInput';
import { previewClassName } from './styles';
type IEditableHighlightCell = ITextHighlightCell | INumberHighlightCell | ITimePeriodHighlightCell | IDuplicateValuesHighlightCell | IUniqueValuesHighlightCell;
@@ -156,7 +157,7 @@ function HighlightCellInput(props: {
return (
<div className="univer-mt-3">
<WrapperError errorText={numberError}>
- <InputNumber
+ <RuleNumberInput
className="univer-w-full"
min={Number.MIN_SAFE_INTEGER}
max={Number.MAX_SAFE_INTEGER}
@@ -183,10 +184,10 @@ function HighlightCellInput(props: {
return (
<div className="univer-mt-3 univer-flex univer-items-center">
<WrapperError errorText={numberMinError}>
- <InputNumber min={Number.MIN_SAFE_INTEGER} max={Number.MAX_SAFE_INTEGER} value={inputNumberMin} onChange={onChangeMin} />
+ <RuleNumberInput min={Number.MIN_SAFE_INTEGER} max={Number.MAX_SAFE_INTEGER} value={inputNumberMin} onChange={onChangeMin} />
</WrapperError>
<WrapperError errorText={numberMaxError}>
- <InputNumber
+ <RuleNumberInput
className="univer-ml-3"
min={Number.MIN_SAFE_INTEGER}
max={Number.MAX_SAFE_INTEGER}
diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/IconSet.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/IconSet.tsx
index b7f3a3502b..aa0a874536 100644
--- a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/IconSet.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/IconSet.tsx
@@ -20,7 +20,7 @@ import type { IFormulaEditorRef } from '@univerjs/sheets-formula-ui';
import type { LocaleKey } from '../../../locale/types';
import type { IStyleEditorProps } from './type';
import { get, IUniverInstanceService, LocaleService, set, Tools, UniverInstanceType } from '@univerjs/core';
-import { borderClassName, Checkbox, clsx, Dropdown, InputNumber, Select } from '@univerjs/design';
+import { borderClassName, Checkbox, clsx, Dropdown, Select } from '@univerjs/design';
import { MoreDownIcon, SlashDoubleIcon } from '@univerjs/icons';
import {
CFNumberOperator,
@@ -37,6 +37,7 @@ import {
import { FormulaEditor } from '@univerjs/sheets-formula-ui';
import { useDependency, useObservable, useSidebarClick } from '@univerjs/ui';
import { useEffect, useMemo, useRef, useState } from 'react';
+import { RuleNumberInput } from './RuleNumberInput';
const getIcon = (iconType: IIconSetType, iconId: string | number) => {
const arr = iconMap[iconType] || [];
@@ -69,7 +70,7 @@ const TextInput = (props: {
{type !== CFValueType.formula
? (
<>
- <InputNumber
+ <RuleNumberInput
className={clsx({
'univer-border-red-500': error,
})}
diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/RuleNumberInput.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/RuleNumberInput.tsx
new file mode 100644
index 0000000000..361045bc00
--- /dev/null
+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/RuleNumberInput.tsx
@@ -0,0 +1,58 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { Input } from '@univerjs/design';
+import { useState } from 'react';
+
+interface IRuleNumberInputProps {
+ value: number;
+ onChange: (value: number) => void;
+ min?: number;
+ max?: number;
+ disabled?: boolean;
+ className?: string;
+}
+
+export function RuleNumberInput({ value, onChange, min = Number.MIN_SAFE_INTEGER, max = Number.MAX_SAFE_INTEGER, disabled, className }: IRuleNumberInputProps) {
+ const [draftState, setDraftState] = useState({ value, text: String(value) });
+ if (!Object.is(draftState.value, value)) {
+ setDraftState({ value, text: String(value) });
+ }
+ const draft = draftState.text;
+ const setDraft = (text: string) => setDraftState({ value, text });
+
+ return (
+ <Input
+ className={className}
+ disabled={disabled}
+ inputMode="decimal"
+ value={draft}
+ aria-invalid={!Number.isFinite(Number(draft))}
+ onChange={(next) => {
+ setDraft(next);
+ const number = Number(next);
+ if (Number.isFinite(number)) {
+ const bounded = Math.min(max, Math.max(min, number));
+ if (bounded !== number) {
+ setDraft(String(bounded));
+ }
+ onChange(bounded);
+ }
+ }}
+ onBlur={() => setDraft(String(value))}
+ />
+ );
+}
diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/__tests__/RuleNumberInput.spec.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/__tests__/RuleNumberInput.spec.tsx
new file mode 100644
index 0000000000..fb53e70f09
--- /dev/null
+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/__tests__/RuleNumberInput.spec.tsx
@@ -0,0 +1,95 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ComponentProps, ReactNode } from 'react';
+import type { Root } from 'react-dom/client';
+import { act, useState } from 'react';
+import { createRoot } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { RuleNumberInput } from '../RuleNumberInput';
+
+let root: Root;
+let container: HTMLDivElement;
+beforeEach(() => {
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+afterEach(async () => {
+ await act(async () => root.unmount());
+ container.remove();
+ vi.unstubAllGlobals();
+});
+async function render(node: ReactNode) {
+ await act(async () => root.render(node));
+}
+async function edit(input: HTMLInputElement, value: string) {
+ await act(async () => {
+ input.focus();
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, value);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+}
+
+function ControlledInput(props: ComponentProps<typeof RuleNumberInput>) {
+ const [value, setValue] = useState(props.value);
+ return (
+ <RuleNumberInput
+ {...props}
+ value={value}
+ onChange={(next) => {
+ setValue(next);
+ props.onChange(next);
+ }}
+ />
+ );
+}
+
+it('retains unfinished exponents and emits their numeric value when completed', async () => {
+ const onChange = vi.fn();
+ await render(<ControlledInput value={2} onChange={onChange} />);
+ const input = container.querySelector('input')!;
+ for (const draft of ['1', '1e', '1e-', '1e-3']) {
+ await edit(input, draft);
+ if (draft === '1e' || draft === '1e-') {
+ expect(input.value).toBe(draft);
+ expect(onChange).toHaveBeenLastCalledWith(1);
+ }
+ }
+ expect(onChange).toHaveBeenLastCalledWith(0.001);
+ await edit(input, '1e3');
+ expect(onChange).toHaveBeenLastCalledWith(1000);
+ await edit(input, '1e999');
+ expect(onChange).toHaveBeenLastCalledWith(1000);
+ await act(async () => input.blur());
+ expect(input.value).toBe('1000');
+});
+
+it('preserves percentage bounds and the zero value for an empty condition', async () => {
+ const onChange = vi.fn();
+ await render(<ControlledInput value={20} min={0} max={100} onChange={onChange} />);
+ const input = container.querySelector('input')!;
+ await edit(input, '1e3');
+ expect(onChange).toHaveBeenLastCalledWith(100);
+ expect(input.value).toBe('100');
+ await edit(input, '-1e3');
+ expect(onChange).toHaveBeenLastCalledWith(0);
+ await edit(input, '');
+ await act(async () => input.blur());
+ expect(onChange).toHaveBeenLastCalledWith(0);
+ expect(input.value).toBe('0');
+});
diff --git a/packages/sheets-formula-ui/src/views/mobile/formula-editor/mobile-function-panel/MobileFunctionPanel.tsx b/packages/sheets-formula-ui/src/views/mobile/formula-editor/mobile-function-panel/MobileFunctionPanel.tsx
index 0807f7eab1..6b1e4ee158 100644
--- a/packages/sheets-formula-ui/src/views/mobile/formula-editor/mobile-function-panel/MobileFunctionPanel.tsx
+++ b/packages/sheets-formula-ui/src/views/mobile/formula-editor/mobile-function-panel/MobileFunctionPanel.tsx
@@ -17,7 +17,7 @@
import type { IFunctionInfo, ISearchItem } from '@univerjs/engine-formula';
import type { LocaleKey } from '../../../../locale/types';
import { LocaleService } from '@univerjs/core';
-import { clsx, scrollbarClassName } from '@univerjs/design';
+import { clsx, Input, scrollbarClassName } from '@univerjs/design';
import { FunctionType, IDescriptionService } from '@univerjs/engine-formula';
import { useDependency } from '@univerjs/ui';
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
@@ -247,18 +247,11 @@ export function MobileFunctionPanel(props: {
: (
<>
<div className="univer-px-4 univer-pb-3">
- <input
+ <Input
value={query}
aria-label={copy.search}
placeholder={copy.search}
- className="
- univer-box-border univer-h-11 univer-w-full univer-rounded-xl univer-border
- univer-border-solid univer-border-gray-200 univer-bg-gray-50 univer-px-4
- univer-text-base univer-outline-none
- focus:univer-border-primary-500
- dark:!univer-border-gray-700 dark:!univer-bg-gray-800 dark:!univer-text-gray-0
- "
- onChange={(event) => setQuery(event.target.value)}
+ onChange={setQuery}
/>
</div>
{!query && (
diff --git a/packages/sheets-numfmt-ui/src/views/mobile/MobileCustomFormat.tsx b/packages/sheets-numfmt-ui/src/views/mobile/MobileCustomFormat.tsx
index 1d1a7395ee..634c2d6e49 100644
--- a/packages/sheets-numfmt-ui/src/views/mobile/MobileCustomFormat.tsx
+++ b/packages/sheets-numfmt-ui/src/views/mobile/MobileCustomFormat.tsx
@@ -46,7 +46,6 @@ export function MobileCustomFormat(props: IMobileCustomFormatProps) {
>
<Input
className="univer-shrink-0"
- size="large"
aria-label={title}
value={pattern}
placeholder={title}
diff --git a/packages/sheets-table-ui/src/views/components/MobileSheetTableConditionPanel.tsx b/packages/sheets-table-ui/src/views/components/MobileSheetTableConditionPanel.tsx
index f0bdf88ea8..1eb9bbc162 100644
--- a/packages/sheets-table-ui/src/views/components/MobileSheetTableConditionPanel.tsx
+++ b/packages/sheets-table-ui/src/views/components/MobileSheetTableConditionPanel.tsx
@@ -30,7 +30,6 @@ import {
DatePicker,
DateRangePicker,
Input,
- InputNumber,
MobileDropdown,
MobileSelect,
} from '@univerjs/design';
@@ -55,6 +54,25 @@ export function MobileSheetTableConditionPanel(props: IMobileSheetTableCondition
const { conditionInfo, onChange } = props;
const localeService = useDependency(LocaleService);
const injector = useDependency(Injector);
+ const [numberDraftState, setNumberDraftState] = useState({ value: conditionInfo.info.number, type: conditionInfo.type, compare: conditionInfo.compare, text: String(conditionInfo.info.number ?? '') });
+ if (!Object.is(numberDraftState.value, conditionInfo.info.number) || numberDraftState.type !== conditionInfo.type || numberDraftState.compare !== conditionInfo.compare) {
+ setNumberDraftState({ value: conditionInfo.info.number, type: conditionInfo.type, compare: conditionInfo.compare, text: String(conditionInfo.info.number ?? '') });
+ }
+ const numberDraft = numberDraftState.text;
+ const setNumberDraft = (text: string) => setNumberDraftState({ value: conditionInfo.info.number, type: conditionInfo.type, compare: conditionInfo.compare, text });
+ const [minDraftState, setMinDraftState] = useState({ value: conditionInfo.info.numberRange?.[0], type: conditionInfo.type, compare: conditionInfo.compare, text: String(conditionInfo.info.numberRange?.[0] ?? '') });
+ if (!Object.is(minDraftState.value, conditionInfo.info.numberRange?.[0]) || minDraftState.type !== conditionInfo.type || minDraftState.compare !== conditionInfo.compare) {
+ setMinDraftState({ value: conditionInfo.info.numberRange?.[0], type: conditionInfo.type, compare: conditionInfo.compare, text: String(conditionInfo.info.numberRange?.[0] ?? '') });
+ }
+ const minDraft = minDraftState.text;
+ const setMinDraft = (text: string) => setMinDraftState({ value: conditionInfo.info.numberRange?.[0], type: conditionInfo.type, compare: conditionInfo.compare, text });
+ const [maxDraftState, setMaxDraftState] = useState({ value: conditionInfo.info.numberRange?.[1], type: conditionInfo.type, compare: conditionInfo.compare, text: String(conditionInfo.info.numberRange?.[1] ?? '') });
+ if (!Object.is(maxDraftState.value, conditionInfo.info.numberRange?.[1]) || maxDraftState.type !== conditionInfo.type || maxDraftState.compare !== conditionInfo.compare) {
+ setMaxDraftState({ value: conditionInfo.info.numberRange?.[1], type: conditionInfo.type, compare: conditionInfo.compare, text: String(conditionInfo.info.numberRange?.[1] ?? '') });
+ }
+ const maxDraft = maxDraftState.text;
+ const setMaxDraft = (text: string) => setMaxDraftState({ value: conditionInfo.info.numberRange?.[1], type: conditionInfo.type, compare: conditionInfo.compare, text });
+
const [conditionVisible, setConditionVisible] = useState(false);
const [defaultDate] = useState(() => new Date());
const cascaderOptions = getCascaderListOptions(injector);
@@ -147,13 +165,16 @@ export function MobileSheetTableConditionPanel(props: IMobileSheetTableCondition
/>
)
: (
- <InputNumber
+ <Input
className="univer-h-7 univer-w-full"
- value={conditionInfo.info.number}
- controls={false}
+ inputMode="decimal"
+ value={numberDraft}
+ aria-invalid={numberDraft !== '' && !Number.isFinite(Number(numberDraft))}
+ onBlur={() => setNumberDraft(String(conditionInfo.info.number ?? ''))}
onChange={(value) => {
- if (value !== null) {
- handleConditionInfo({ number: value });
+ setNumberDraft(value);
+ if (value.trim() !== '' && Number.isFinite(Number(value))) {
+ handleConditionInfo({ number: Number(value) });
}
}}
/>
@@ -183,24 +204,30 @@ export function MobileSheetTableConditionPanel(props: IMobileSheetTableCondition
)}
{subComponentType === ConditionSubComponentEnum.Inputs && (
<div className="univer-flex univer-items-center univer-gap-2">
- <InputNumber
+ <Input
className="univer-w-full"
- value={conditionInfo.info.numberRange?.[0]}
- controls={false}
+ inputMode="decimal"
+ value={minDraft}
+ aria-invalid={minDraft !== '' && !Number.isFinite(Number(minDraft))}
+ onBlur={() => setMinDraft(String(conditionInfo.info.numberRange?.[0] ?? ''))}
onChange={(value) => {
- if (value !== null) {
- handleConditionInfo({ numberRange: [value, conditionInfo.info.numberRange?.[1]] });
+ setMinDraft(value);
+ if (value.trim() !== '' && Number.isFinite(Number(value))) {
+ handleConditionInfo({ numberRange: [Number(value), conditionInfo.info.numberRange?.[1]] });
}
}}
/>
<span> - </span>
- <InputNumber
+ <Input
className="univer-w-full"
- value={conditionInfo.info.numberRange?.[1]}
- controls={false}
+ inputMode="decimal"
+ value={maxDraft}
+ aria-invalid={maxDraft !== '' && !Number.isFinite(Number(maxDraft))}
+ onBlur={() => setMaxDraft(String(conditionInfo.info.numberRange?.[1] ?? ''))}
onChange={(value) => {
- if (value !== null) {
- handleConditionInfo({ numberRange: [conditionInfo.info.numberRange?.[0], value] });
+ setMaxDraft(value);
+ if (value.trim() !== '' && Number.isFinite(Number(value))) {
+ handleConditionInfo({ numberRange: [conditionInfo.info.numberRange?.[0], Number(value)] });
}
}}
/>
diff --git a/packages/sheets-table-ui/src/views/components/SheetTableConditionPanel.tsx b/packages/sheets-table-ui/src/views/components/SheetTableConditionPanel.tsx
index e833ddf14c..debd2ec26e 100644
--- a/packages/sheets-table-ui/src/views/components/SheetTableConditionPanel.tsx
+++ b/packages/sheets-table-ui/src/views/components/SheetTableConditionPanel.tsx
@@ -18,7 +18,7 @@ import type { ITableFilterItem } from '@univerjs/sheets-table';
import type { LocaleKey } from '../../locale/types';
import type { IConditionCompareTypeEnum, IConditionExpect, IConditionInfo, ITableConditionTypeEnumWithoutLogic } from './type';
import { Injector, LocaleService } from '@univerjs/core';
-import { borderClassName, CascaderList, clsx, DatePicker, DateRangePicker, Dropdown, Input, InputNumber, Select } from '@univerjs/design';
+import { borderClassName, CascaderList, clsx, DatePicker, DateRangePicker, Dropdown, Input, Select } from '@univerjs/design';
import { MoreDownIcon } from '@univerjs/icons';
import { TableConditionTypeEnum, TableDateCompareTypeEnum, TableStringCompareTypeEnum } from '@univerjs/sheets-table';
import { useDependency } from '@univerjs/ui';
@@ -40,6 +40,25 @@ export const SheetTableConditionPanel = (props: IConditionFilterProps) => {
const { conditionInfo, onChange } = props;
const localeService = useDependency(LocaleService);
+ const [numberDraftState, setNumberDraftState] = useState({ value: conditionInfo.info.number, type: conditionInfo.type, compare: conditionInfo.compare, text: String(conditionInfo.info.number ?? '') });
+ if (!Object.is(numberDraftState.value, conditionInfo.info.number) || numberDraftState.type !== conditionInfo.type || numberDraftState.compare !== conditionInfo.compare) {
+ setNumberDraftState({ value: conditionInfo.info.number, type: conditionInfo.type, compare: conditionInfo.compare, text: String(conditionInfo.info.number ?? '') });
+ }
+ const numberDraft = numberDraftState.text;
+ const setNumberDraft = (text: string) => setNumberDraftState({ value: conditionInfo.info.number, type: conditionInfo.type, compare: conditionInfo.compare, text });
+ const [minDraftState, setMinDraftState] = useState({ value: conditionInfo.info.numberRange?.[0], type: conditionInfo.type, compare: conditionInfo.compare, text: String(conditionInfo.info.numberRange?.[0] ?? '') });
+ if (!Object.is(minDraftState.value, conditionInfo.info.numberRange?.[0]) || minDraftState.type !== conditionInfo.type || minDraftState.compare !== conditionInfo.compare) {
+ setMinDraftState({ value: conditionInfo.info.numberRange?.[0], type: conditionInfo.type, compare: conditionInfo.compare, text: String(conditionInfo.info.numberRange?.[0] ?? '') });
+ }
+ const minDraft = minDraftState.text;
+ const setMinDraft = (text: string) => setMinDraftState({ value: conditionInfo.info.numberRange?.[0], type: conditionInfo.type, compare: conditionInfo.compare, text });
+ const [maxDraftState, setMaxDraftState] = useState({ value: conditionInfo.info.numberRange?.[1], type: conditionInfo.type, compare: conditionInfo.compare, text: String(conditionInfo.info.numberRange?.[1] ?? '') });
+ if (!Object.is(maxDraftState.value, conditionInfo.info.numberRange?.[1]) || maxDraftState.type !== conditionInfo.type || maxDraftState.compare !== conditionInfo.compare) {
+ setMaxDraftState({ value: conditionInfo.info.numberRange?.[1], type: conditionInfo.type, compare: conditionInfo.compare, text: String(conditionInfo.info.numberRange?.[1] ?? '') });
+ }
+ const maxDraft = maxDraftState.text;
+ const setMaxDraft = (text: string) => setMaxDraftState({ value: conditionInfo.info.numberRange?.[1], type: conditionInfo.type, compare: conditionInfo.compare, text });
+
const [conditionVisible, setConditionVisible] = useState(false);
const injector = useDependency(Injector);
@@ -137,13 +156,16 @@ export const SheetTableConditionPanel = (props: IConditionFilterProps) => {
/>
)
: (
- <InputNumber
+ <Input
className="univer-h-7 univer-w-full"
- value={conditionInfo.info.number}
- controls={false}
+ inputMode="decimal"
+ value={numberDraft}
+ aria-invalid={numberDraft !== '' && !Number.isFinite(Number(numberDraft))}
+ onBlur={() => setNumberDraft(String(conditionInfo.info.number ?? ''))}
onChange={(v) => {
- if (v !== null) {
- handleConditionInfo({ number: v });
+ setNumberDraft(v);
+ if (v.trim() !== '' && Number.isFinite(Number(v))) {
+ handleConditionInfo({ number: Number(v) });
}
}}
/>
@@ -176,24 +198,30 @@ export const SheetTableConditionPanel = (props: IConditionFilterProps) => {
)}
{subComponentType === ConditionSubComponentEnum.Inputs && (
<div className="univer-flex univer-items-center univer-gap-2">
- <InputNumber
+ <Input
className="univer-w-full"
- value={conditionInfo.info.numberRange?.[0]}
+ inputMode="decimal"
+ value={minDraft}
+ aria-invalid={minDraft !== '' && !Number.isFinite(Number(minDraft))}
+ onBlur={() => setMinDraft(String(conditionInfo.info.numberRange?.[0] ?? ''))}
onChange={(v) => {
- if (v !== null) {
- handleConditionInfo({ numberRange: [v, conditionInfo.info.numberRange?.[1]] });
+ setMinDraft(v);
+ if (v.trim() !== '' && Number.isFinite(Number(v))) {
+ handleConditionInfo({ numberRange: [Number(v), conditionInfo.info.numberRange?.[1]] });
}
}}
- controls={false}
/>
<span> - </span>
- <InputNumber
+ <Input
className="univer-w-full"
- value={conditionInfo.info.numberRange?.[1]}
- controls={false}
+ inputMode="decimal"
+ value={maxDraft}
+ aria-invalid={maxDraft !== '' && !Number.isFinite(Number(maxDraft))}
+ onBlur={() => setMaxDraft(String(conditionInfo.info.numberRange?.[1] ?? ''))}
onChange={(v) => {
- if (v !== null) {
- handleConditionInfo({ numberRange: [conditionInfo.info.numberRange?.[0], v] });
+ setMaxDraft(v);
+ if (v.trim() !== '' && Number.isFinite(Number(v))) {
+ handleConditionInfo({ numberRange: [conditionInfo.info.numberRange?.[0], Number(v)] });
}
}}
/>
diff --git a/packages/sheets-table-ui/src/views/components/__tests__/MobileSheetTableConditionPanel.spec.tsx b/packages/sheets-table-ui/src/views/components/__tests__/MobileSheetTableConditionPanel.spec.tsx
new file mode 100644
index 0000000000..aa1738d742
--- /dev/null
+++ b/packages/sheets-table-ui/src/views/components/__tests__/MobileSheetTableConditionPanel.spec.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 { Root } from 'react-dom/client';
+import type { IConditionInfo } from '../type';
+import { LocaleService, LocaleType, Univer } from '@univerjs/core';
+import { TableConditionTypeEnum, TableNumberCompareTypeEnum } from '@univerjs/sheets-table';
+import { RediContext } from '@univerjs/ui';
+import { act, useState } from 'react';
+import { createRoot } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import enUS from '../../../locale/en-US';
+import { MobileSheetTableConditionPanel } from '../MobileSheetTableConditionPanel';
+
+function Harness({ condition, onChange }: { condition: IConditionInfo; onChange: (next: IConditionInfo) => void }) {
+ const [value, setValue] = useState(condition);
+ return (
+ <MobileSheetTableConditionPanel
+ unitId="unit"
+ subUnitId="sheet"
+ tableId="table"
+ columnIndex={0}
+ tableFilter={undefined}
+ conditionInfo={value}
+ onChange={(next) => {
+ setValue(next);
+ onChange(next);
+ }}
+ />
+ );
+}
+
+let univer: Univer;
+let root: Root;
+let container: HTMLDivElement;
+beforeEach(() => {
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
+ univer = new Univer({ locale: LocaleType.EN_US, locales: { [LocaleType.EN_US]: enUS } });
+ univer.__getInjector().get(LocaleService).setDirection('ltr');
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+afterEach(async () => {
+ await act(async () => root.unmount());
+ univer.dispose();
+ container.remove();
+ vi.unstubAllGlobals();
+});
+
+it.each([
+ [TableNumberCompareTypeEnum.Equal, 0, '1e3', { number: 1000 }],
+ [TableNumberCompareTypeEnum.Between, 0, '1e-3', { numberRange: [0.001, 10] }],
+ [TableNumberCompareTypeEnum.Between, 1, '1e3', { numberRange: [5, 1000] }],
+] as const)('parses scientific values for %s operand %s', async (compare, index, draft, expected) => {
+ const onChange = vi.fn();
+ const condition: IConditionInfo = { type: TableConditionTypeEnum.Number, compare, info: { number: 5, numberRange: [5, 10] } };
+ await act(async () => root.render(
+ <RediContext.Provider value={{ injector: univer.__getInjector() }}><Harness condition={condition} onChange={onChange} /></RediContext.Provider>
+ ));
+ const input = container.querySelectorAll<HTMLInputElement>('input[inputmode="decimal"]')[index];
+ for (const next of ['1e', draft]) {
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, next);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ if (next === '1e') {
+ expect(input.value).toBe(next);
+ expect(onChange).not.toHaveBeenCalled();
+ }
+ }
+ expect(onChange).toHaveBeenLastCalledWith({ type: TableConditionTypeEnum.Number, compare, info: expected });
+});
diff --git a/packages/sheets-table-ui/src/views/components/__tests__/SheetTableConditionPanel.spec.tsx b/packages/sheets-table-ui/src/views/components/__tests__/SheetTableConditionPanel.spec.tsx
new file mode 100644
index 0000000000..ccee784586
--- /dev/null
+++ b/packages/sheets-table-ui/src/views/components/__tests__/SheetTableConditionPanel.spec.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 { Root } from 'react-dom/client';
+import type { IConditionInfo } from '../type';
+import { LocaleService, LocaleType, Univer } from '@univerjs/core';
+import { TableConditionTypeEnum, TableNumberCompareTypeEnum } from '@univerjs/sheets-table';
+import { RediContext } from '@univerjs/ui';
+import { act, useState } from 'react';
+import { createRoot } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import enUS from '../../../locale/en-US';
+import { SheetTableConditionPanel } from '../SheetTableConditionPanel';
+
+function Harness({ condition, onChange }: { condition: IConditionInfo; onChange: (next: IConditionInfo) => void }) {
+ const [value, setValue] = useState(condition);
+ return (
+ <SheetTableConditionPanel
+ unitId="unit"
+ subUnitId="sheet"
+ tableId="table"
+ columnIndex={0}
+ tableFilter={undefined}
+ conditionInfo={value}
+ onChange={(next) => {
+ setValue(next);
+ onChange(next);
+ }}
+ />
+ );
+}
+
+let univer: Univer;
+let root: Root;
+let container: HTMLDivElement;
+beforeEach(() => {
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
+ univer = new Univer({ locale: LocaleType.EN_US, locales: { [LocaleType.EN_US]: enUS } });
+ univer.__getInjector().get(LocaleService).setDirection('ltr');
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+afterEach(async () => {
+ await act(async () => root.unmount());
+ univer.dispose();
+ container.remove();
+ vi.unstubAllGlobals();
+});
+
+it.each([
+ [TableNumberCompareTypeEnum.Equal, 0, '1e3', { number: 1000 }],
+ [TableNumberCompareTypeEnum.Between, 0, '1e-3', { numberRange: [0.001, 10] }],
+ [TableNumberCompareTypeEnum.Between, 1, '1e3', { numberRange: [5, 1000] }],
+] as const)('parses scientific values for %s operand %s', async (compare, index, draft, expected) => {
+ const onChange = vi.fn();
+ const condition: IConditionInfo = { type: TableConditionTypeEnum.Number, compare, info: { number: 5, numberRange: [5, 10] } };
+ await act(async () => root.render(
+ <RediContext.Provider value={{ injector: univer.__getInjector() }}><Harness condition={condition} onChange={onChange} /></RediContext.Provider>
+ ));
+ const input = container.querySelectorAll<HTMLInputElement>('input[inputmode="decimal"]')[index];
+ for (const next of ['1e', draft]) {
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, next);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ if (next === '1e') {
+ expect(input.value).toBe(next);
+ expect(onChange).not.toHaveBeenCalled();
+ }
+ }
+ expect(onChange).toHaveBeenLastCalledWith({ type: TableConditionTypeEnum.Number, compare, info: expected });
+});
diff --git a/packages/sheets-ui/src/views/dropdown/ListDropDown.tsx b/packages/sheets-ui/src/views/dropdown/ListDropDown.tsx
index 7495446fb7..8faa4043b0 100644
--- a/packages/sheets-ui/src/views/dropdown/ListDropDown.tsx
+++ b/packages/sheets-ui/src/views/dropdown/ListDropDown.tsx
@@ -20,7 +20,7 @@ import type { CSSProperties } from 'react';
import type { LocaleKey } from '../../locale/types';
import type { IBaseDropdownProps } from './type';
import { ColorKit, LocaleService, ThemeService } from '@univerjs/core';
-import { borderClassName, borderTopClassName, clsx, scrollbarClassName } from '@univerjs/design';
+import { borderClassName, borderTopClassName, clsx, Input, scrollbarClassName } from '@univerjs/design';
import { CheckMarkIcon } from '@univerjs/icons';
import {
RangeProtectionPermissionEditPoint,
@@ -84,8 +84,8 @@ function SelectList(props: ISelectListProps) {
return options.filter((item) => lowerFilter ? item.label.toLowerCase().includes(lowerFilter) : true);
}, [options, lowerFilter]);
- const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
- setLowerFilter(e.target.value.toLowerCase());
+ const handleSearchChange = (value: string) => {
+ setLowerFilter(value.toLowerCase());
};
const sheetPermissionCheckController = useDependency(SheetPermissionCheckController);
@@ -111,14 +111,8 @@ function SelectList(props: ISelectListProps) {
>
{showSearchOnDropdown && (
<div className="univer-box-border univer-flex univer-w-full univer-px-2">
- <input
+ <Input
ref={searchRef}
- className={clsx(`
- univer-w-full univer-rounded-md univer-bg-gray-0 univer-px-2 univer-py-1 univer-text-sm
- univer-text-gray-900
- focus:univer-border-primary-500 focus:univer-outline-none
- dark:!univer-bg-gray-1000 dark:!univer-text-gray-0
- `, borderClassName)}
type="text"
value={lowerFilter}
autoFocus
@@ -163,7 +157,9 @@ function SelectList(props: ISelectListProps) {
const backgroundColor = isThemeColor
? themeService.getColorFromTheme(item.color!)
: item.color;
- const isDark = new ColorKit(backgroundColor).isDark();
+ const color = new ColorKit(backgroundColor);
+ const hasBackground = Boolean(backgroundColor) && backgroundColor !== 'transparent' && color.getAlpha() > 0;
+ const isDark = color.isDark();
return (
<div
@@ -181,8 +177,8 @@ function SelectList(props: ISelectListProps) {
univer-inline-flex univer-h-4 univer-w-fit univer-items-center univer-truncate
univer-rounded-full univer-px-1.5 univer-text-xs
`, {
- 'univer-text-gray-900': isThemeColor || !isDark,
- 'univer-text-gray-0': !isThemeColor && isDark,
+ 'univer-text-gray-900': hasBackground && (isThemeColor || !isDark),
+ 'univer-text-gray-0': hasBackground && !isThemeColor && isDark,
})}
style={{ background: backgroundColor }}
>
@@ -245,7 +241,9 @@ export function ListDropDown(props: { popup: IPopupWithExtraProps<IListDropdownP
const { worksheet } = location;
const [localValue, setLocalValue] = useState(defaultValue);
- if (!worksheet) return null;
+ if (!worksheet) {
+ return null;
+ }
const cellWidth = (anchorRect?.right ?? 0) - (anchorRect?.left ?? 0);
return (
diff --git a/packages/sheets-ui/src/views/mobile/sheet-bar/MobileSheetBar.tsx b/packages/sheets-ui/src/views/mobile/sheet-bar/MobileSheetBar.tsx
index 4be7dd8654..818b01ba17 100644
--- a/packages/sheets-ui/src/views/mobile/sheet-bar/MobileSheetBar.tsx
+++ b/packages/sheets-ui/src/views/mobile/sheet-bar/MobileSheetBar.tsx
@@ -318,7 +318,6 @@ function MobileSheetBarImpl(props: { workbook: Workbook }) {
<div className="univer-grid univer-gap-2">
<Input
autoFocus
- size="large"
value={renameValue}
onChange={(value) => {
setRenameValue(value);