Skip to content

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

feat(ui): improve color picker and reset sheet tab colors (#7959)

白熱331fbb60c066
diff --git a/packages/design/src/components/color-picker/ColorInput.tsx b/packages/design/src/components/color-picker/ColorInput.tsx
index 9063a0537a..7d271efcc0 100644
--- a/packages/design/src/components/color-picker/ColorInput.tsx
+++ b/packages/design/src/components/color-picker/ColorInput.tsx
@@ -78,7 +78,7 @@ function HexInput({ hsv, onChange }: IInputProps) {
<>
<input
className={clsx(`
- univer-w-full univer-px-2 !univer-pl-4 univer-uppercase
+ univer-w-full univer-min-w-0 univer-px-2 !univer-pl-4 univer-uppercase
focus:univer-border-primary-500 focus:univer-outline-none
rtl:!univer-pl-2 rtl:!univer-pr-4
dark:!univer-text-gray-0
@@ -86,7 +86,16 @@ function HexInput({ hsv, onChange }: IInputProps) {
value={inputValue}
onChange={handleChange}
onBlur={handleBlur}
+ onPaste={(event) => {
+ const pastedValue = event.clipboardData.getData('text').trim();
+ if (!/^#[0-9A-Fa-f]{6}$/.test(pastedValue)) return;
+ event.preventDefault();
+ const hex = pastedValue.slice(1);
+ setInputValue(hex);
+ onChange?.(...hexToHsv(hex));
+ }}
maxLength={6}
+ aria-label="HEX"
spellCheck={false}
/>
<span
@@ -119,7 +128,7 @@ function RgbInput({ hsv, alpha, format, onChange }: IInputProps) {
if (color === 'a') {
if (value !== '' && !/^\d*\.?\d*$/.test(value)) return;
const numValue = value === '' ? 0 : Number.parseFloat(value);
- if (numValue > 1) return;
+ if (!Number.isFinite(numValue) || numValue > 1) return;
const newValues = { ...localValues, a: numValue };
setLocalValues(newValues);
if (onChange) {
@@ -163,18 +172,21 @@ function RgbInput({ hsv, alpha, format, onChange }: IInputProps) {
`}
>
<input
+ aria-label="R"
value={localValues.r}
onChange={(e) => handleChange('r', e.target.value)}
onBlur={handleBlur}
maxLength={3}
/>
<input
+ aria-label="G"
value={localValues.g}
onChange={(e) => handleChange('g', e.target.value)}
onBlur={handleBlur}
maxLength={3}
/>
<input
+ aria-label="B"
value={localValues.b}
onChange={(e) => handleChange('b', e.target.value)}
onBlur={handleBlur}
@@ -182,6 +194,7 @@ function RgbInput({ hsv, alpha, format, onChange }: IInputProps) {
/>
{format === 'rgba' && (
<input
+ aria-label="A"
value={localValues.a}
onChange={(e) => handleChange('a', e.target.value)}
onBlur={handleBlur}
diff --git a/packages/design/src/components/color-picker/ColorPicker.tsx b/packages/design/src/components/color-picker/ColorPicker.tsx
index 226a1bceb3..36562c843c 100644
--- a/packages/design/src/components/color-picker/ColorPicker.tsx
+++ b/packages/design/src/components/color-picker/ColorPicker.tsx
@@ -14,24 +14,17 @@
* limitations under the License.
*/
-import { memo, useCallback, useContext, useEffect, useState } from 'react';
+import { useCallback, useContext, useEffect, useLayoutEffect, useRef, useState } from 'react';
import { isBrowser } from '../../helper/is-browser';
import { Button } from '../button/Button';
import { ConfigContext } from '../config-provider/ConfigProvider';
-import { Dialog } from '../dialog/Dialog';
import { AlphaSlider } from './AlphaSlider';
-import { hexToHsv, hsvToHex, hsvToRgb, hsvToRgba, parseRgba, rgbToHex, rgbToHsv } from './color-conversion';
+import { hexToHsv, hsvToHex, hsvToRgba, parseRgba, rgbToHsv } from './color-conversion';
import { ColorInput } from './ColorInput';
import { ColorPresets } from './ColorPresets';
import { ColorSpectrum } from './ColorSpectrum';
import { HueSlider } from './HueSlider';
-const MemoizedColorSpectrum = memo(ColorSpectrum);
-const MemoizedHueSlider = memo(HueSlider);
-const MemoizedAlphaSlider = memo(AlphaSlider);
-const MemoizedColorInput = memo(ColorInput);
-const MemoizedColorPresets = memo(ColorPresets);
-
export interface IColorPickerProps {
format?: 'hex' | 'rgba';
value?: string;
@@ -40,32 +33,42 @@ export interface IColorPickerProps {
export function ColorPicker({ format = 'hex', value, onChange }: IColorPickerProps) {
const { direction, locale } = useContext(ConfigContext);
-
- const [hsv, setHsv] = useState<[number, number, number]>([0, 100, 100]);
+ const [selectedColor, setSelectedColor] = useState(value);
+ const [hsv, setHsv] = useState<[number, number, number]>([0, 0, 0]);
const [alpha, setAlpha] = useState(1);
- const [visible, setVisible] = useState(false);
+ const [custom, setCustom] = useState(false);
+ const returnFocusRef = useRef(false);
+ const moreButtonRef = useRef<HTMLButtonElement>(null);
+ const customPanelRef = useRef<HTMLDivElement>(null);
- const getRgb = useCallback((h: number, s: number, v: number) => {
- return hsvToRgb(h, s, v);
- }, []);
-
- useEffect(() => {
+ const resetDraft = useCallback((color?: string) => {
try {
- const actualValue = value || (format === 'hex' ? '#000000' : 'rgba(0, 0, 0, 1)');
if (format === 'hex') {
- const [h, s, v] = hexToHsv(actualValue);
- setHsv([h, s, v]);
+ setHsv(hexToHsv(color || '#000000'));
setAlpha(1);
- } else if (format === 'rgba') {
- const [r, g, b, a] = parseRgba(actualValue);
- const [h, s, v] = rgbToHsv(r, g, b);
- setHsv([h, s, v]);
+ } else {
+ const [r, g, b, a] = parseRgba(color || 'rgba(0, 0, 0, 1)');
+ setHsv(rgbToHsv(r, g, b));
setAlpha(a);
}
} catch (error) {
console.error('Invalid value:', error);
}
- }, [value, format]);
+ }, [format]);
+
+ useEffect(() => {
+ setSelectedColor(value);
+ resetDraft(value);
+ }, [value, resetDraft]);
+
+ useLayoutEffect(() => {
+ if (custom) {
+ customPanelRef.current?.querySelector('input')?.focus();
+ } else if (returnFocusRef.current) {
+ moreButtonRef.current?.focus();
+ returnFocusRef.current = false;
+ }
+ }, [custom]);
if (!isBrowser) {
return null;
@@ -75,122 +78,114 @@ export function ColorPicker({ format = 'hex', value, onChange }: IColorPickerPro
setHsv([h, s, v]);
}
- function handleAlphaChange(a: number) {
- setAlpha(a);
- }
-
- function handleColorChanged(h: number, s: number, v: number, a: number = alpha) {
- if (format === 'hex') {
- const [r, g, b] = getRgb(h, s, v);
- const hex = rgbToHex(r, g, b);
- onChange?.(hex);
- } else if (format === 'rgba') {
- const [r, g, b] = getRgb(h, s, v);
- onChange?.(`rgba(${r}, ${g}, ${b}, ${a})`);
- }
+ function applyColor(h: number, s: number, v: number, a: number) {
+ const color = format === 'hex' ? hsvToHex(h, s, v) : hsvToRgba(h, s, v, a);
+ setSelectedColor(color);
+ returnFocusRef.current = custom;
+ setCustom(false);
+ onChange?.(color);
}
- function handleConfirmCustomColor() {
- const [h, s, v] = hsv;
- if (format === 'hex') {
- const hex = hsvToHex(h, s, v);
- onChange?.(hex);
- } else if (format === 'rgba') {
- const [r, g, b] = getRgb(h, s, v);
- onChange?.(`rgba(${r}, ${g}, ${b}, ${alpha})`);
- }
- setVisible(false);
+ function cancelCustomColor() {
+ returnFocusRef.current = true;
+ resetDraft(selectedColor);
+ setCustom(false);
}
return (
<div
data-u-comp="color-picker"
dir={direction}
- className="univer-cursor-default univer-space-y-2 univer-rounded-lg"
- onClick={(e) => e.stopPropagation()}
+ className="univer-w-72 univer-max-w-full univer-cursor-default univer-rounded-lg"
+ onClick={(event) => event.stopPropagation()}
+ onKeyDown={(event) => {
+ if (custom) event.stopPropagation();
+ if (custom && event.key === 'Escape') {
+ event.preventDefault();
+ cancelCustomColor();
+ }
+ }}
>
- <MemoizedColorPresets
- hsv={hsv}
- onChange={(h, s, v) => {
- handleColorChange(h, s, v);
- handleAlphaChange(1);
- handleColorChanged(h, s, v, 1);
- }}
- />
-
- <div className="univer-flex univer-h-7 univer-items-center">
- <button
- type="button"
- className="
- univer-cursor-pointer univer-border-0 univer-bg-transparent univer-p-0 univer-text-sm
- univer-text-gray-900 univer-transition-opacity
- hover:univer-opacity-80
- dark:!univer-text-gray-0
- "
- onClick={() => setVisible(true)}
- >
- {locale?.ColorPicker.more}
- </button>
- </div>
-
- <Dialog
- className="!univer-z-[1090] !univer-w-fit !univer-p-2.5"
- overlayClassName="!univer-z-[1090]"
- closable={false}
- maskClosable={false}
- open={visible}
- onOpenChange={setVisible}
- >
- <div className="univer-grid univer-w-64 univer-gap-2">
- <MemoizedColorSpectrum
- hsv={hsv}
- onChange={handleColorChange}
- />
-
- <div className="univer-flex univer-items-center univer-gap-2">
- <div
- className="univer-size-6 univer-flex-shrink-0 univer-rounded-sm"
- style={{
- backgroundColor: format === 'hex' ? hsvToHex(...hsv) : hsvToRgba(...hsv, alpha),
+ {custom
+ ? (
+ <div
+ ref={customPanelRef}
+ className="univer-grid univer-gap-3"
+ onKeyDown={(event) => {
+ if (event.key === 'Enter' && event.target instanceof HTMLInputElement) {
+ event.preventDefault();
+ event.stopPropagation();
+ applyColor(...hsv, alpha);
+ }
+ }}
+ >
+ <div className="univer-h-40 univer-overflow-hidden univer-rounded-md">
+ <ColorSpectrum hsv={hsv} onChange={handleColorChange} />
+ </div>
+ <div className="univer-flex univer-items-center univer-gap-3">
+ <span
+ className="
+ univer-size-8 univer-shrink-0 univer-rounded-md univer-border univer-border-solid
+ univer-border-gray-200
+ dark:!univer-border-gray-600
+ "
+ style={{ backgroundColor: format === 'hex' ? hsvToHex(...hsv) : hsvToRgba(...hsv, alpha) }}
+ />
+ <div className="univer-flex-1 univer-space-y-3">
+ <HueSlider hsv={hsv} onChange={handleColorChange} />
+ {format === 'rgba' && <AlphaSlider hsv={hsv} alpha={alpha} onChange={setAlpha} />}
+ </div>
+ </div>
+ <ColorInput
+ hsv={hsv}
+ alpha={alpha}
+ format={format}
+ onChange={(h, s, v, a) => {
+ handleColorChange(h, s, v);
+ if (a !== undefined) setAlpha(a);
}}
/>
- <div className="univer-flex-1 univer-space-y-2">
- <MemoizedHueSlider
- hsv={hsv}
- onChange={handleColorChange}
- />
- {format === 'rgba' && (
- <MemoizedAlphaSlider
- hsv={hsv}
- alpha={alpha}
- onChange={handleAlphaChange}
+ <footer className="univer-flex univer-justify-end univer-gap-2">
+ <Button onClick={cancelCustomColor}>{locale?.ColorPicker.cancel}</Button>
+ <Button variant="primary" onClick={() => applyColor(...hsv, alpha)}>
+ {locale?.ColorPicker.confirm}
+ </Button>
+ </footer>
+ </div>
+ )
+ : (
+ <div className="univer-space-y-2">
+ <ColorPresets
+ hsv={selectedColor && alpha === 1 ? hsv : undefined}
+ onChange={(h, s, v) => {
+ handleColorChange(h, s, v);
+ setAlpha(1);
+ applyColor(h, s, v, 1);
+ }}
+ />
+ <Button
+ ref={moreButtonRef}
+ variant="ghost"
+ className="univer-w-full univer-justify-between"
+ onClick={() => {
+ resetDraft(selectedColor);
+ setCustom(true);
+ }}
+ >
+ {locale?.ColorPicker.more}
+ {selectedColor && (
+ <span
+ className="
+ univer-size-5 univer-rounded univer-border univer-border-solid
+ univer-border-gray-200
+ dark:!univer-border-gray-600
+ "
+ style={{ backgroundColor: selectedColor }}
/>
)}
- </div>
- </div>
-
- <MemoizedColorInput
- hsv={hsv}
- alpha={alpha}
- format={format}
- onChange={(h, s, v, a) => {
- handleColorChange(h, s, v);
- if (a !== undefined) {
- handleAlphaChange(a);
- }
- }}
- />
-
- <footer className="univer-flex univer-items-center univer-justify-end univer-gap-2">
- <Button onClick={() => setVisible(false)}>
- {locale?.ColorPicker.cancel}
</Button>
- <Button variant="primary" onClick={handleConfirmCustomColor}>
- {locale?.ColorPicker.confirm}
- </Button>
- </footer>
- </div>
- </Dialog>
+ </div>
+ )}
</div>
);
}
diff --git a/packages/design/src/components/color-picker/ColorPresets.tsx b/packages/design/src/components/color-picker/ColorPresets.tsx
index b41184b127..7787c82e46 100644
--- a/packages/design/src/components/color-picker/ColorPresets.tsx
+++ b/packages/design/src/components/color-picker/ColorPresets.tsx
@@ -20,7 +20,7 @@ import { hexToHsv, hsvToHex } from './color-conversion';
import { colorPresets } from './presets';
interface IColorPresetsProps {
- hsv: [number, number, number];
+ hsv?: [number, number, number];
onChange: (h: number, s: number, v: number) => void;
}
@@ -30,32 +30,48 @@ export function ColorPresets({ hsv, onChange }: IColorPresetsProps) {
onChange(h, s, v);
}, [onChange]);
- const currentColor = hsvToHex(hsv[0], hsv[1], hsv[2]);
+ const currentColor = hsv ? hsvToHex(...hsv) : '';
return (
<div
data-u-comp="color-picker-presets"
- className="univer-grid univer-content-center univer-gap-2"
+ className="univer-grid univer-content-center"
>
- {colorPresets.map((row, i) => (
+ {colorPresets.map((row) => (
<div
- key={i}
- className="univer-grid univer-grid-flow-col univer-items-center univer-justify-between univer-gap-2"
+ key={row[0]}
+ className="univer-grid univer-grid-flow-col univer-items-center univer-justify-between"
>
- {row.map((color, j) => (
+ {row.map((color) => (
<button
- key={j}
+ key={color}
type="button"
+ aria-label={color}
+ aria-pressed={color.toUpperCase() === currentColor.toUpperCase()}
+ title={color}
className={clsx(`
- univer-box-border univer-size-5 univer-cursor-pointer univer-rounded-full univer-border
- univer-border-solid univer-border-transparent univer-bg-gray-300 univer-transition-shadow
+ univer-box-border univer-flex univer-size-8 univer-cursor-pointer univer-items-center
+ univer-justify-center univer-rounded-md univer-border-0 univer-bg-transparent univer-p-1
+ univer-transition-colors
+ hover:univer-bg-gray-100
+ focus-visible:univer-outline focus-visible:univer-outline-2
+ focus-visible:univer-outline-primary-600
+ dark:hover:!univer-bg-gray-700
`, {
- 'univer-ring-2 univer-ring-offset-2 univer-ring-offset-gray-0 dark:!univer-ring-primary-600 dark:!univer-ring-offset-gray-600': color.toUpperCase() === currentColor.toUpperCase(),
- '!univer-border-gray-200': i === 0 && j === 0,
+ 'univer-bg-primary-50 dark:!univer-bg-gray-700': color.toUpperCase() === currentColor.toUpperCase(),
})}
- style={{ backgroundColor: color }}
onClick={() => handleSelectPreset(color)}
- />
+ >
+ <span
+ className={clsx(`
+ univer-box-border univer-size-6 univer-rounded univer-border univer-border-solid
+ univer-border-black/10
+ `, {
+ 'univer-ring-2 univer-ring-primary-600 univer-ring-offset-2 univer-ring-offset-gray-0 dark:!univer-ring-primary-400 dark:!univer-ring-offset-gray-700': color.toUpperCase() === currentColor.toUpperCase(),
+ })}
+ style={{ backgroundColor: color }}
+ />
+ </button>
))}
</div>
))}
diff --git a/packages/design/src/components/color-picker/ColorSpectrum.tsx b/packages/design/src/components/color-picker/ColorSpectrum.tsx
index e3c6a048e7..47944a2b2e 100644
--- a/packages/design/src/components/color-picker/ColorSpectrum.tsx
+++ b/packages/design/src/components/color-picker/ColorSpectrum.tsx
@@ -27,6 +27,7 @@ export function ColorSpectrum({ hsv, onChange, onChanged }: IColorSpectrumProps)
const canvasRef = useRef<HTMLCanvasElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const [isDragging, setIsDragging] = useState(false);
+ const [hue] = hsv;
useEffect(() => {
const canvas = canvasRef.current;
@@ -36,8 +37,8 @@ export function ColorSpectrum({ hsv, onChange, onChanged }: IColorSpectrumProps)
if (!ctx) return;
const gradientS = ctx.createLinearGradient(0, 0, canvas.width, 0);
- gradientS.addColorStop(0, `hsl(${hsv[0]}, 0%, 50%)`);
- gradientS.addColorStop(1, `hsl(${hsv[0]}, 100%, 50%)`);
+ gradientS.addColorStop(0, '#ffffff');
+ gradientS.addColorStop(1, `hsl(${hue}, 100%, 50%)`);
ctx.fillStyle = gradientS;
ctx.fillRect(0, 0, canvas.width, canvas.height);
@@ -46,7 +47,7 @@ export function ColorSpectrum({ hsv, onChange, onChanged }: IColorSpectrumProps)
gradientV.addColorStop(1, 'rgba(0, 0, 0, 1)');
ctx.fillStyle = gradientV;
ctx.fillRect(0, 0, canvas.width, canvas.height);
- }, [hsv[0]]);
+ }, [hue]);
const handlePointerEvent = (e: PointerEvent) => {
e.stopPropagation();
@@ -68,21 +69,19 @@ export function ColorSpectrum({ hsv, onChange, onChanged }: IColorSpectrumProps)
setIsDragging(false);
}, []);
- function handleChange() {
- onChanged?.(hsv[0], hsv[1], hsv[2]);
- }
-
useEffect(() => {
- containerRef.current?.addEventListener('mouseup', handleChange);
+ const container = containerRef.current;
+ const handleChange = () => onChanged?.(...hsv);
+ container?.addEventListener('mouseup', handleChange);
window.addEventListener('pointerup', handlePointerUp);
window.addEventListener('mouseup', handlePointerUp);
return () => {
- containerRef.current?.removeEventListener('mouseup', handleChange);
+ container?.removeEventListener('mouseup', handleChange);
window.removeEventListener('pointerup', handlePointerUp);
window.removeEventListener('mouseup', handlePointerUp);
};
- }, [hsv]);
+ }, [hsv, onChanged, handlePointerUp]);
// Calculate the position of the indicator
const getIndicatorStyles = () => {
@@ -94,20 +93,6 @@ export function ColorSpectrum({ hsv, onChange, onChanged }: IColorSpectrumProps)
};
};
- useEffect(() => {
- const handlePointerUp = () => {
- setIsDragging(false);
- };
-
- window.addEventListener('pointerup', handlePointerUp);
- window.addEventListener('mouseup', handlePointerUp);
-
- return () => {
- window.removeEventListener('pointerup', handlePointerUp);
- window.removeEventListener('mouseup', handlePointerUp);
- };
- }, []);
-
return (
<div
data-u-comp="color-picker-spectrum"
diff --git a/packages/design/src/components/color-picker/MobileColorPicker.tsx b/packages/design/src/components/color-picker/MobileColorPicker.tsx
index ca93ecb3b2..97be21c55d 100644
--- a/packages/design/src/components/color-picker/MobileColorPicker.tsx
+++ b/packages/design/src/components/color-picker/MobileColorPicker.tsx
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import type { IColorPickerProps } from './ColorPicker';
import { memo, useCallback, useContext, useEffect, useState } from 'react';
+import type { IColorPickerProps } from './ColorPicker';
import { isBrowser } from '../../helper/is-browser';
import { MobileActionRowGroup } from '../action-row/MobileActionRowGroup';
import { Button } from '../button/Button';
@@ -42,10 +42,12 @@ export function MobileColorPicker({ format = 'hex', value, onChange }: IMobileCo
const closeMobileDropdown = useContext(MobileDropdownCloseContext);
const [hsv, setHsv] = useState<[number, number, number]>([0, 100, 100]);
const [alpha, setAlpha] = useState(1);
+ const [hasSelectedColor, setHasSelectedColor] = useState(Boolean(value));
const [visible, setVisible] = useState(false);
const getRgb = useCallback((h: number, s: number, v: number) => hsvToRgb(h, s, v), []);
useEffect(() => {
+ setHasSelectedColor(Boolean(value));
try {
const actualValue = value || (format === 'hex' ? '#000000' : 'rgba(0, 0, 0, 1)');
if (format === 'hex') {
@@ -70,6 +72,7 @@ export function MobileColorPicker({ format = 'hex', value, onChange }: IMobileCo
}
function handleColorChanged(h: number, s: number, v: number, a: number = alpha) {
+ setHasSelectedColor(true);
if (format === 'hex') {
onChange?.(rgbToHex(...getRgb(h, s, v)));
} else {
@@ -94,7 +97,7 @@ export function MobileColorPicker({ format = 'hex', value, onChange }: IMobileCo
onClick={(event) => event.stopPropagation()}
>
<MemoizedMobileColorPresets
- value={hsvToHex(...hsv)}
+ value={hasSelectedColor && alpha === 1 ? hsvToHex(...hsv) : undefined}
onSelect={(color) => {
const [h, s, v] = hexToHsv(color);
handleColorChange(h, s, v);
diff --git a/packages/design/src/components/color-picker/__tests__/AlphaSlider.spec.tsx b/packages/design/src/components/color-picker/__tests__/AlphaSlider.spec.tsx
new file mode 100644
index 0000000000..3d66ef1f3e
--- /dev/null
+++ b/packages/design/src/components/color-picker/__tests__/AlphaSlider.spec.tsx
@@ -0,0 +1,108 @@
+/**
+ * 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 } from '@testing-library/react';
+import { useState } from 'react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { AlphaSlider } from '../AlphaSlider';
+import '@testing-library/jest-dom/vitest';
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+describe('AlphaSlider', () => {
+ it('should update alpha during pointer interaction and emit onChanged', () => {
+ const onChange = vi.fn();
+ const onChanged = vi.fn();
+
+ const { container } = render(
+ <AlphaSlider hsv={[0, 100, 100]} alpha={0.3} onChange={onChange} onChanged={onChanged} />
+ );
+
+ const slider = container.querySelector('[data-u-comp="color-picker-alpha-slider-track"]') as HTMLDivElement;
+ const thumb = container.querySelector('[data-u-comp="color-picker-alpha-slider-thumb"]') as HTMLDivElement;
+ expect(slider).toBeInTheDocument();
+ expect(thumb).toBeInTheDocument();
+
+ Object.defineProperty(thumb, 'clientWidth', { value: 10, configurable: true });
+ vi.spyOn(slider, 'getBoundingClientRect').mockReturnValue({
+ x: 0,
+ y: 0,
+ top: 0,
+ left: 0,
+ width: 100,
+ height: 8,
+ right: 100,
+ bottom: 8,
+ toJSON: () => ({}),
+ } as DOMRect);
+
+ fireEvent.pointerDown(slider, { clientX: 50 });
+ fireEvent.pointerMove(window, { clientX: 80 });
+ fireEvent.pointerUp(window);
+
+ expect(onChange).toHaveBeenCalled();
+ expect(onChanged).toHaveBeenCalledWith(0.3);
+ });
+
+ it('should emit latest alpha on pointer up after prop update', () => {
+ const onChange = vi.fn();
+ const onChanged = vi.fn();
+
+ function Wrapper() {
+ const [alpha, setAlpha] = useState(0.3);
+ return (
+ <AlphaSlider
+ hsv={[0, 100, 100]}
+ alpha={alpha}
+ onChange={(a) => {
+ setAlpha(a);
+ onChange(a);
+ }}
+ onChanged={onChanged}
+ />
+ );
+ }
+
+ const { container } = render(<Wrapper />);
+ const slider = container.querySelector('[data-u-comp="color-picker-alpha-slider-track"]') as HTMLDivElement;
+ const thumb = container.querySelector('[data-u-comp="color-picker-alpha-slider-thumb"]') as HTMLDivElement;
+
+ Object.defineProperty(thumb, 'clientWidth', { value: 10, configurable: true });
+ vi.spyOn(slider, 'getBoundingClientRect').mockReturnValue({
+ x: 0,
+ y: 0,
+ top: 0,
+ left: 0,
+ width: 100,
+ height: 8,
+ right: 100,
+ bottom: 8,
+ toJSON: () => ({}),
+ } as DOMRect);
+
+ fireEvent.pointerDown(slider, { clientX: 50 });
+ fireEvent.pointerMove(window, { clientX: 80 });
+ fireEvent.pointerUp(window);
+
+ expect(onChange).toHaveBeenCalled();
+ expect(onChanged).toHaveBeenCalled();
+ const lastCall = onChanged.mock.calls[onChanged.mock.calls.length - 1];
+ expect(lastCall[0]).toBeGreaterThan(0.3);
+ });
+});
diff --git a/packages/design/src/components/color-picker/__tests__/ColorInput.spec.tsx b/packages/design/src/components/color-picker/__tests__/ColorInput.spec.tsx
index cbd3fb314c..896a05823e 100644
--- a/packages/design/src/components/color-picker/__tests__/ColorInput.spec.tsx
+++ b/packages/design/src/components/color-picker/__tests__/ColorInput.spec.tsx
@@ -14,10 +14,14 @@
* limitations under the License.
*/
-import { fireEvent, render } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
+import { cleanup, fireEvent, render } from '@testing-library/react';
+import { useState } from 'react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import { hexToHsv } from '../color-conversion';
import { ColorInput } from '../ColorInput';
+import '@testing-library/jest-dom/vitest';
+
+afterEach(cleanup);
describe('ColorInput', () => {
it('preserves typed HEX selection during equivalent color updates and accepts external colors', () => {
@@ -25,7 +29,7 @@ describe('ColorInput', () => {
const { container, rerender } = render(
<ColorInput hsv={[0, 100, 100]} alpha={1} format="hex" onChange={onChange} />
);
- const input = container.querySelector<HTMLInputElement>('input[maxlength="6"]')!;
+ const input = container.querySelector<HTMLInputElement>('input[aria-label="HEX"]')!;
fireEvent.change(input, { target: { value: 'aB12Cd' } });
expect(onChange).toHaveBeenCalledWith(...hexToHsv('aB12Cd'));
input.setSelectionRange(1, 3);
@@ -35,4 +39,120 @@ describe('ColorInput', () => {
rerender(<ColorInput hsv={hexToHsv('00ff00')} alpha={1} format="hex" onChange={onChange} />);
expect(input.value.toLowerCase()).toBe('00ff00');
});
+
+ it('should handle hex input validation and reset invalid value on blur', () => {
+ const onChange = vi.fn();
+
+ function Wrapper() {
+ const [hsv, setHsv] = useState<[number, number, number]>([0, 100, 100]);
+ return (
+ <ColorInput
+ hsv={hsv}
+ alpha={1}
+ format="hex"
+ onChange={(h, s, v) => {
+ setHsv([h, s, v]);
+ onChange(h, s, v);
+ }}
+ />
+ );
+ }
+
+ const { container } = render(<Wrapper />);
+ const hexInput = container.querySelector('input[aria-label="HEX"]') as HTMLInputElement;
+ expect(hexInput).toBeInTheDocument();
+
+ fireEvent.change(hexInput, { target: { value: 'GGGGGG' } });
+ expect(onChange).not.toHaveBeenCalled();
+
+ fireEvent.change(hexInput, { target: { value: '00ff00' } });
+ expect(onChange).toHaveBeenCalled();
+
+ fireEvent.change(hexInput, { target: { value: '0' } });
+ fireEvent.blur(hexInput);
+ expect(hexInput.value.length).toBe(6);
+ });
+
+ it('should handle rgba channels and alpha bounds', () => {
+ const onChange = vi.fn();
+
+ function Wrapper() {
+ const [hsv, setHsv] = useState<[number, number, number]>([0, 100, 100]);
+ const [alpha, setAlpha] = useState(0.5);
+ return (
+ <ColorInput
+ hsv={hsv}
+ alpha={alpha}
+ format="rgba"
+ onChange={(h, s, v, a) => {
+ setHsv([h, s, v]);
+ setAlpha(a ?? alpha);
+ onChange(h, s, v, a);
+ }}
+ />
+ );
+ }
+
+ const { container } = render(<Wrapper />);
+ const rgbInputs = Array.from(container.querySelectorAll('input[maxlength="3"]')) as HTMLInputElement[];
+ const alphaInput = container.querySelector('input[maxlength="4"]') as HTMLInputElement;
+
+ fireEvent.change(rgbInputs[0], { target: { value: '255' } });
+ fireEvent.change(rgbInputs[1], { target: { value: '255' } });
+ fireEvent.change(rgbInputs[2], { target: { value: '255' } });
+ expect(onChange).toHaveBeenCalled();
+
+ const callCount = onChange.mock.calls.length;
+ fireEvent.change(alphaInput, { target: { value: '1.5' } });
+ expect(onChange.mock.calls.length).toBe(callCount);
+
+ fireEvent.change(alphaInput, { target: { value: '0.75' } });
+ expect(onChange).toHaveBeenCalled();
+ });
+
+ it('should guard invalid length and character input branches', () => {
+ const onChange = vi.fn();
+ const { container } = render(
+ <ColorInput hsv={[0, 100, 100]} alpha={0.5} format="rgba" onChange={onChange} />
+ );
+
+ const hexInput = container.querySelector('input[aria-label="HEX"]') as HTMLInputElement;
+ const rgbInputs = Array.from(container.querySelectorAll('input[maxlength="3"]')) as HTMLInputElement[];
+ const alphaInput = container.querySelector('input[maxlength="4"]') as HTMLInputElement;
+
+ fireEvent.change(hexInput, { target: { value: '1234567' } });
+ expect(onChange).not.toHaveBeenCalled();
+
+ fireEvent.change(rgbInputs[0], { target: { value: '1a' } });
+ fireEvent.change(rgbInputs[1], { target: { value: '300' } });
+ fireEvent.change(alphaInput, { target: { value: 'abc' } });
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('should reset rgb local values on blur to current hsv values', () => {
+ const onChange = vi.fn();
+ const { container } = render(
+ <ColorInput hsv={[0, 100, 100]} alpha={0.5} format="rgba" onChange={onChange} />
+ );
+
+ const rInput = container.querySelector('input[maxlength="3"]') as HTMLInputElement;
+ fireEvent.change(rInput, { target: { value: '1' } });
+ expect(onChange).toHaveBeenCalled();
+
+ fireEvent.blur(rInput);
+ expect(rInput.value).toBe('255');
+ });
+});
+
+it('accepts pasted hex colors with a hash and rejects incomplete alpha values', () => {
+ const onChange = vi.fn();
+ const view = render(<ColorInput hsv={[0, 100, 100]} alpha={1} format="rgba" onChange={onChange} />);
+ const hexInput = view.getByRole('textbox', { name: 'HEX' });
+ expect(hexInput).toHaveAttribute('maxlength', '6');
+ fireEvent.paste(hexInput, { clipboardData: { getData: () => '#123456' } });
+ expect(hexInput).toHaveValue('123456');
+ expect(onChange).toHaveBeenCalledExactlyOnceWith(...hexToHsv('#123456'));
+ onChange.mockClear();
+ fireEvent.change(view.getByRole('textbox', { name: 'A' }), { target: { value: '.' } });
+ expect(onChange).not.toHaveBeenCalled();
});
diff --git a/packages/design/src/components/color-picker/__tests__/ColorPicker.spec.tsx b/packages/design/src/components/color-picker/__tests__/ColorPicker.spec.tsx
new file mode 100644
index 0000000000..7da7f3e8f3
--- /dev/null
+++ b/packages/design/src/components/color-picker/__tests__/ColorPicker.spec.tsx
@@ -0,0 +1,125 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { cleanup, fireEvent, render } 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 { ColorPicker } from '../ColorPicker';
+import '@testing-library/jest-dom/vitest';
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+describe('ColorPicker', () => {
+ it('distinguishes an unset color from black and follows external color changes', () => {
+ const view = render(<ColorPicker value="" />);
+ expect(view.getByRole('button', { name: '#000000' })).toHaveAttribute('aria-pressed', 'false');
+ view.rerender(<ColorPicker value="#000000" />);
+ expect(view.getByRole('button', { name: '#000000' })).toHaveAttribute('aria-pressed', 'true');
+ view.rerender(<ColorPicker value="#3f83f8" />);
+ expect(view.getByRole('button', { name: '#3F83F8' })).toHaveAttribute('aria-pressed', 'true');
+ view.rerender(<ColorPicker value="" />);
+ expect(view.queryByRole('button', { pressed: true })).not.toBeInTheDocument();
+ });
+
+ it.each(['hex', 'rgba'] as const)('applies a preset immediately in %s format', (format) => {
+ const onChange = vi.fn();
+ const view = render(<ColorPicker format={format} onChange={onChange} />);
+ fireEvent.click(view.getByRole('button', { name: '#3F83F8' }));
+ expect(onChange).toHaveBeenCalledExactlyOnceWith(format === 'hex' ? '#3f83f8' : 'rgba(63, 131, 248, 1)');
+ expect(view.getByRole('button', { name: '#3F83F8' })).toHaveAttribute('aria-pressed', 'true');
+ });
+
+ it('edits in the same popover and applies a pasted hex color only on confirmation', () => {
+ const onChange = vi.fn();
+ const view = render(
+ <ConfigProvider mountContainer={document.body} locale={enUS.design}>
+ <ColorPicker value="#3F83F8" onChange={onChange} />
+ </ConfigProvider>
+ );
+ fireEvent.click(view.getByRole('button', { name: enUS.design.ColorPicker.more }));
+ expect(view.queryByRole('dialog')).not.toBeInTheDocument();
+ const input = view.getByRole('textbox', { name: 'HEX' });
+ expect(input).toHaveFocus();
+ fireEvent.paste(input, { clipboardData: { getData: () => '#12ab34' } });
+ expect(onChange).not.toHaveBeenCalled();
+ fireEvent.click(view.getByRole('button', { name: enUS.design.ColorPicker.confirm }));
+ expect(onChange).toHaveBeenCalledExactlyOnceWith('#12ab34');
+ expect(view.getByRole('button', { name: enUS.design.ColorPicker.more })).toHaveFocus();
+ });
+
+ it.each(['button', 'Escape'])('discards custom drafts using %s and restores focus', (cancel) => {
+ const onChange = vi.fn();
+ const parentKeyDown = vi.fn();
+ const view = render(
+ <ConfigProvider mountContainer={document.body} locale={enUS.design}>
+ <div onKeyDown={parentKeyDown}>
+ <ColorPicker value="#3F83F8" onChange={onChange} />
+ </div>
+ </ConfigProvider>
+ );
+ fireEvent.click(view.getByRole('button', { name: enUS.design.ColorPicker.more }));
+ fireEvent.change(view.getByRole('textbox', { name: 'HEX' }), { target: { value: 'aabbcc' } });
+ fireEvent.keyDown(view.getByRole('textbox', { name: 'HEX' }), { key: 'ArrowLeft' });
+ expect(parentKeyDown).not.toHaveBeenCalled();
+ if (cancel === 'button') {
+ fireEvent.click(view.getByRole('button', { name: enUS.design.ColorPicker.cancel }));
+ } else {
+ fireEvent.keyDown(view.getByRole('textbox', { name: 'HEX' }), { key: 'Escape' });
+ expect(parentKeyDown).not.toHaveBeenCalled();
+ }
+ expect(onChange).not.toHaveBeenCalled();
+ expect(view.getByRole('button', { name: enUS.design.ColorPicker.more })).toHaveFocus();
+ expect(view.getByRole('button', { name: '#3F83F8' })).toHaveAttribute('aria-pressed', 'true');
+ fireEvent.click(view.getByRole('button', { name: enUS.design.ColorPicker.more }));
+ expect(view.getByRole('textbox', { name: 'HEX' })).toHaveValue('3f83f8');
+ });
+
+ it('preserves alpha for custom colors and applies with Enter', () => {
+ const onChange = vi.fn();
+ const view = render(
+ <ConfigProvider mountContainer={document.body} locale={enUS.design}>
+ <ColorPicker format="rgba" value="rgba(63, 131, 248, 0.5)" onChange={onChange} />
+ </ConfigProvider>
+ );
+ expect(view.queryByRole('button', { pressed: true })).not.toBeInTheDocument();
+ fireEvent.click(view.getByRole('button', { name: enUS.design.ColorPicker.more }));
+ fireEvent.change(view.getByRole('textbox', { name: 'HEX' }), { target: { value: '123456' } });
+ fireEvent.keyDown(view.getByRole('textbox', { name: 'HEX' }), { key: 'Enter' });
+ expect(onChange).toHaveBeenCalledExactlyOnceWith('rgba(18, 52, 86, 0.5)');
+ });
+
+ it('keeps editing clicks inside the picker and follows RTL direction', () => {
+ const parentClick = vi.fn();
+ const view = render(
+ <ConfigProvider mountContainer={document.body} direction="rtl" locale={enUS.design}>
+ <div onClick={parentClick}><ColorPicker /></div>
+ </ConfigProvider>
+ );
+ fireEvent.click(view.getByRole('button', { name: enUS.design.ColorPicker.more }));
+ expect(parentClick).not.toHaveBeenCalled();
+ expect(view.container.querySelector('[data-u-comp="color-picker"]')).toHaveAttribute('dir', 'rtl');
+ });
+
+ it('reports invalid color input without crashing', () => {
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ render(<ColorPicker format="rgba" value="invalid-rgba" />);
+ expect(errorSpy).toHaveBeenCalled();
+ });
+});
diff --git a/packages/design/src/components/color-picker/__tests__/ColorPickerPanel.spec.tsx b/packages/design/src/components/color-picker/__tests__/ColorPickerPanel.spec.tsx
new file mode 100644
index 0000000000..ef75c1b070
--- /dev/null
+++ b/packages/design/src/components/color-picker/__tests__/ColorPickerPanel.spec.tsx
@@ -0,0 +1,38 @@
+/**
+ * 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 } 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 { ColorPickerPanel } from '../ColorPickerPanel';
+
+afterEach(cleanup);
+
+describe('ColorPickerPanel', () => {
+ it('commits a custom color only when the apply button is clicked', () => {
+ const onConfirm = vi.fn();
+ const { getByRole } = render(
+ <ConfigProvider locale={enUS.design} mountContainer={document.body}>
+ <ColorPickerPanel value="#3F83F8" onConfirm={onConfirm} />
+ </ConfigProvider>
+ );
+
+ expect(onConfirm).not.toHaveBeenCalled();
+ fireEvent.click(getByRole('button', { name: enUS.design.ColorPicker.confirm }));
+ expect(onConfirm).toHaveBeenCalledWith('#3f83f8');
+ });
+});
diff --git a/packages/design/src/components/color-picker/__tests__/color-spectrum-extra.spec.tsx b/packages/design/src/components/color-picker/__tests__/ColorSpectrum.spec.tsx
similarity index 85%
rename from packages/design/src/components/color-picker/__tests__/color-spectrum-extra.spec.tsx
rename to packages/design/src/components/color-picker/__tests__/ColorSpectrum.spec.tsx
index c8b8f613f4..c009040bd2 100644
--- a/packages/design/src/components/color-picker/__tests__/color-spectrum-extra.spec.tsx
+++ b/packages/design/src/components/color-picker/__tests__/ColorSpectrum.spec.tsx
@@ -24,7 +24,7 @@ afterEach(() => {
cleanup();
});
-describe('ColorSpectrum extra', () => {
+describe('ColorSpectrum', () => {
beforeEach(() => {
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(() => {
const gradient = { addColorStop: vi.fn() };
@@ -67,6 +67,17 @@ describe('ColorSpectrum extra', () => {
expect(onChanged).toHaveBeenCalledWith(120, 20, 80);
});
+ it('renders the zero-saturation edge as white at maximum value', () => {
+ const addColorStop = vi.fn();
+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({
+ createLinearGradient: () => ({ addColorStop }),
+ fillRect: vi.fn(),
+ fillStyle: '',
+ } as unknown as CanvasRenderingContext2D);
+ render(<ColorSpectrum hsv={[120, 0, 100]} onChange={vi.fn()} />);
+ expect(addColorStop).toHaveBeenCalledWith(0, '#ffffff');
+ });
+
it('positions the initial indicator from hsv without waiting for container measurements', () => {
const { container } = render(<ColorSpectrum hsv={[120, 20, 80]} onChange={vi.fn()} />);
diff --git a/packages/design/src/components/color-picker/__tests__/hue-slider-extra.spec.tsx b/packages/design/src/components/color-picker/__tests__/HueSlider.spec.tsx
similarity index 99%
rename from packages/design/src/components/color-picker/__tests__/hue-slider-extra.spec.tsx
rename to packages/design/src/components/color-picker/__tests__/HueSlider.spec.tsx
index bc27475f78..164c9ff38d 100644
--- a/packages/design/src/components/color-picker/__tests__/hue-slider-extra.spec.tsx
+++ b/packages/design/src/components/color-picker/__tests__/HueSlider.spec.tsx
@@ -25,7 +25,7 @@ afterEach(() => {
cleanup();
});
-describe('HueSlider extra', () => {
+describe('HueSlider', () => {
it('should stop propagation, handle drag and emit onChanged', () => {
const onChange = vi.fn();
const onChanged = vi.fn();
diff --git a/packages/design/src/components/color-picker/__tests__/MobileColorPicker.spec.tsx b/packages/design/src/components/color-picker/__tests__/MobileColorPicker.spec.tsx
new file mode 100644
index 0000000000..fffee33550
--- /dev/null
+++ b/packages/design/src/components/color-picker/__tests__/MobileColorPicker.spec.tsx
@@ -0,0 +1,106 @@
+/**
+ * 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 } from '@testing-library/react';
+import { afterEach, describe, expect, it } from 'vitest';
+import enUS from '../../../locale/en-US';
+import { ConfigProvider } from '../../config-provider/ConfigProvider';
+import { MobileDropdown } from '../../dropdown/MobileDropdown';
+import { MobileColorPicker } from '../MobileColorPicker';
+import '@testing-library/jest-dom/vitest';
+
+afterEach(cleanup);
+
+function getMoreColorButton(container: HTMLElement): HTMLButtonElement {
+ const button = Array.from(container.querySelectorAll<HTMLButtonElement>('button'))
+ .find((button) => button.textContent === enUS.design.ColorPicker.more);
+ if (!button) throw new Error('More color button was not rendered.');
+ return button;
+}
+
+describe('MobileColorPicker', () => {
+ it('does not select black for an unset tab color', () => {
+ const view = render(<MobileColorPicker value="" />);
+ expect(view.getByRole('button', { name: '#000000' })).toHaveAttribute('aria-pressed', 'false');
+ });
+
+ it('opens custom colors above the containing mobile dropdown', () => {
+ render(
+ <ConfigProvider locale={enUS.design} mountContainer={document.body}>
+ <MobileDropdown open overlay={<MobileColorPicker value="#FFFFFF" />}>
+ <button type="button">Color</button>
+ </MobileDropdown>
+ </ConfigProvider>
+ );
+
+ fireEvent.click(getMoreColorButton(document.body));
+
+ const dialogs = Array.from(document.querySelectorAll<HTMLElement>('[role="dialog"]'));
+ expect(dialogs).toHaveLength(2);
+ const input = document.querySelector<HTMLInputElement>('[data-u-comp="mobile-color-picker-custom"] input');
+ expect(input).toBeInTheDocument();
+ fireEvent.change(input!, { target: { value: '123456' } });
+ expect(input).toHaveValue('123456');
+ });
+
+ it('closes the containing mobile dropdown after selecting a preset color', () => {
+ render(
+ <ConfigProvider locale={enUS.design} mountContainer={document.body}>
+ <MobileDropdown overlay={<MobileColorPicker value="#FFFFFF" />}>
+ <button type="button">Color</button>
+ </MobileDropdown>
+ </ConfigProvider>
+ );
+
+ fireEvent.click(document.querySelector('button')!);
+ fireEvent.click(document.querySelectorAll('[data-u-comp="color-picker"] button')[1]);
+
+ expect(document.querySelector('[role="dialog"]')).not.toBeInTheDocument();
+ });
+
+ it('closes both color dialogs after confirming a custom color', () => {
+ render(
+ <ConfigProvider locale={enUS.design} mountContainer={document.body}>
+ <MobileDropdown overlay={<MobileColorPicker value="#FFFFFF" />}>
+ <button type="button">Color</button>
+ </MobileDropdown>
+ </ConfigProvider>
+ );
+
+ fireEvent.click(document.querySelector('button')!);
+ fireEvent.click(getMoreColorButton(document.body));
+ fireEvent.click(document.querySelector<HTMLButtonElement>('[data-u-comp="mobile-color-picker-custom"] button:last-child')!);
+
+ expect(document.querySelector('[role="dialog"]')).not.toBeInTheDocument();
+ });
+
+ it('keeps the containing mobile dropdown open after cancelling a custom color', () => {
+ render(
+ <ConfigProvider locale={enUS.design} mountContainer={document.body}>
+ <MobileDropdown overlay={<MobileColorPicker value="#FFFFFF" />}>
+ <button type="button">Color</button>
+ </MobileDropdown>
+ </ConfigProvider>
+ );
+
+ fireEvent.click(document.querySelector('button')!);
+ fireEvent.click(getMoreColorButton(document.body));
+ fireEvent.click(document.querySelector<HTMLButtonElement>('[data-u-comp="mobile-color-picker-custom"] button')!);
+
+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1);
+ expect(document.querySelector('[data-u-comp="color-picker"]')).toBeInTheDocument();
+ });
+});
diff --git a/packages/design/src/components/color-picker/__tests__/MobileColorPresets.spec.tsx b/packages/design/src/components/color-picker/__tests__/MobileColorPresets.spec.tsx
new file mode 100644
index 0000000000..7c12f10b17
--- /dev/null
+++ b/packages/design/src/components/color-picker/__tests__/MobileColorPresets.spec.tsx
@@ -0,0 +1,36 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { cleanup, fireEvent, render } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { MobileColorPresets } from '../MobileColorPresets';
+import { colorPresets } from '../presets';
+import '@testing-library/jest-dom/vitest';
+
+afterEach(cleanup);
+
+describe('MobileColorPresets', () => {
+ it('renders large preset targets and applies the selected color', () => {
+ const onSelect = vi.fn();
+ const { container } = render(<MobileColorPresets value="#FFFFFF" onSelect={onSelect} />);
+ const buttons = container.querySelectorAll('button');
+
+ expect(buttons[0]).toHaveAttribute('aria-pressed', 'true');
+
+ fireEvent.click(buttons[1]);
+ expect(onSelect).toHaveBeenCalledWith(colorPresets.flat()[1]);
+ });
+});
diff --git a/packages/design/src/components/color-picker/__tests__/alpha-and-input.spec.tsx b/packages/design/src/components/color-picker/__tests__/alpha-and-input.spec.tsx
deleted file mode 100644
index cd83f48353..0000000000
--- a/packages/design/src/components/color-picker/__tests__/alpha-and-input.spec.tsx
+++ /dev/null
@@ -1,209 +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 { fireEvent, render } from '@testing-library/react';
-import { useState } from 'react';
-import { describe, expect, it, vi } from 'vitest';
-import { AlphaSlider } from '../AlphaSlider';
-import { ColorInput } from '../ColorInput';
-import '@testing-library/jest-dom/vitest';
-
-describe('AlphaSlider', () => {
- it('should update alpha during pointer interaction and emit onChanged', () => {
- const onChange = vi.fn();
- const onChanged = vi.fn();
-
- const { container } = render(
- <AlphaSlider hsv={[0, 100, 100]} alpha={0.3} onChange={onChange} onChanged={onChanged} />
- );
-
- const slider = container.querySelector('[data-u-comp="color-picker-alpha-slider-track"]') as HTMLDivElement;
- const thumb = container.querySelector('[data-u-comp="color-picker-alpha-slider-thumb"]') as HTMLDivElement;
- expect(slider).toBeInTheDocument();
- expect(thumb).toBeInTheDocument();
-
- Object.defineProperty(thumb, 'clientWidth', { value: 10, configurable: true });
- vi.spyOn(slider, 'getBoundingClientRect').mockReturnValue({
- x: 0,
- y: 0,
- top: 0,
- left: 0,
- width: 100,
- height: 8,
- right: 100,
- bottom: 8,
- toJSON: () => ({}),
- } as DOMRect);
-
- fireEvent.pointerDown(slider, { clientX: 50 });
- fireEvent.pointerMove(window, { clientX: 80 });
- fireEvent.pointerUp(window);
-
- expect(onChange).toHaveBeenCalled();
- expect(onChanged).toHaveBeenCalledWith(0.3);
- });
-
- it('should emit latest alpha on pointer up after prop update', () => {
- const onChange = vi.fn();
- const onChanged = vi.fn();
-
- function Wrapper() {
- const [alpha, setAlpha] = useState(0.3);
- return (
- <AlphaSlider
- hsv={[0, 100, 100]}
- alpha={alpha}
- onChange={(a) => {
- setAlpha(a);
- onChange(a);
- }}
- onChanged={onChanged}
- />
- );
- }
-
- const { container } = render(<Wrapper />);
- const slider = container.querySelector('[data-u-comp="color-picker-alpha-slider-track"]') as HTMLDivElement;
- const thumb = container.querySelector('[data-u-comp="color-picker-alpha-slider-thumb"]') as HTMLDivElement;
-
- Object.defineProperty(thumb, 'clientWidth', { value: 10, configurable: true });
- vi.spyOn(slider, 'getBoundingClientRect').mockReturnValue({
- x: 0,
- y: 0,
- top: 0,
- left: 0,
- width: 100,
- height: 8,
- right: 100,
- bottom: 8,
- toJSON: () => ({}),
- } as DOMRect);
-
- fireEvent.pointerDown(slider, { clientX: 50 });
- fireEvent.pointerMove(window, { clientX: 80 });
- fireEvent.pointerUp(window);
-
- expect(onChange).toHaveBeenCalled();
- expect(onChanged).toHaveBeenCalled();
- const lastCall = onChanged.mock.calls[onChanged.mock.calls.length - 1];
- expect(lastCall[0]).toBeGreaterThan(0.3);
- });
-});
-
-describe('ColorInput', () => {
- it('should handle hex input validation and reset invalid value on blur', () => {
- const onChange = vi.fn();
-
- function Wrapper() {
- const [hsv, setHsv] = useState<[number, number, number]>([0, 100, 100]);
- return (
- <ColorInput
- hsv={hsv}
- alpha={1}
- format="hex"
- onChange={(h, s, v) => {
- setHsv([h, s, v]);
- onChange(h, s, v);
- }}
- />
- );
- }
-
- const { container } = render(<Wrapper />);
- const hexInput = container.querySelector('input[maxlength="6"]') as HTMLInputElement;
- expect(hexInput).toBeInTheDocument();
-
- fireEvent.change(hexInput, { target: { value: 'GGGGGG' } });
- expect(onChange).not.toHaveBeenCalled();
-
- fireEvent.change(hexInput, { target: { value: '00ff00' } });
- expect(onChange).toHaveBeenCalled();
-
- fireEvent.change(hexInput, { target: { value: '0' } });
- fireEvent.blur(hexInput);
- expect(hexInput.value.length).toBe(6);
- });
-
- it('should handle rgba channels and alpha bounds', () => {
- const onChange = vi.fn();
-
- function Wrapper() {
- const [hsv, setHsv] = useState<[number, number, number]>([0, 100, 100]);
- const [alpha, setAlpha] = useState(0.5);
- return (
- <ColorInput
- hsv={hsv}
- alpha={alpha}
- format="rgba"
- onChange={(h, s, v, a) => {
- setHsv([h, s, v]);
- setAlpha(a ?? alpha);
- onChange(h, s, v, a);
- }}
- />
- );
- }
-
- const { container } = render(<Wrapper />);
- const rgbInputs = Array.from(container.querySelectorAll('input[maxlength="3"]')) as HTMLInputElement[];
- const alphaInput = container.querySelector('input[maxlength="4"]') as HTMLInputElement;
-
- fireEvent.change(rgbInputs[0], { target: { value: '255' } });
- fireEvent.change(rgbInputs[1], { target: { value: '255' } });
- fireEvent.change(rgbInputs[2], { target: { value: '255' } });
- expect(onChange).toHaveBeenCalled();
-
- const callCount = onChange.mock.calls.length;
- fireEvent.change(alphaInput, { target: { value: '1.5' } });
- expect(onChange.mock.calls.length).toBe(callCount);
-
- fireEvent.change(alphaInput, { target: { value: '0.75' } });
- expect(onChange).toHaveBeenCalled();
- });
-
- it('should guard invalid length and character input branches', () => {
- const onChange = vi.fn();
- const { container } = render(
- <ColorInput hsv={[0, 100, 100]} alpha={0.5} format="rgba" onChange={onChange} />
- );
-
- const hexInput = container.querySelector('input[maxlength="6"]') as HTMLInputElement;
- const rgbInputs = Array.from(container.querySelectorAll('input[maxlength="3"]')) as HTMLInputElement[];
- const alphaInput = container.querySelector('input[maxlength="4"]') as HTMLInputElement;
-
- fireEvent.change(hexInput, { target: { value: '1234567' } });
- expect(onChange).not.toHaveBeenCalled();
-
- fireEvent.change(rgbInputs[0], { target: { value: '1a' } });
- fireEvent.change(rgbInputs[1], { target: { value: '300' } });
- fireEvent.change(alphaInput, { target: { value: 'abc' } });
- expect(onChange).not.toHaveBeenCalled();
- });
-
- it('should reset rgb local values on blur to current hsv values', () => {
- const onChange = vi.fn();
- const { container } = render(
- <ColorInput hsv={[0, 100, 100]} alpha={0.5} format="rgba" onChange={onChange} />
- );
-
- const rInput = container.querySelector('input[maxlength="3"]') as HTMLInputElement;
- fireEvent.change(rInput, { target: { value: '1' } });
- expect(onChange).toHaveBeenCalled();
-
- fireEvent.blur(rInput);
- expect(rInput.value).toBe('255');
- });
-});
diff --git a/packages/design/src/components/color-picker/__tests__/color-picker-extra.spec.tsx b/packages/design/src/components/color-picker/__tests__/color-picker-extra.spec.tsx
deleted file mode 100644
index 61d01c2cdc..0000000000
--- a/packages/design/src/components/color-picker/__tests__/color-picker-extra.spec.tsx
+++ /dev/null
@@ -1,105 +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 } from '@testing-library/react';
-import { afterEach, describe, expect, it, vi } from 'vitest';
-import { ColorPicker } from '../ColorPicker';
-import '@testing-library/jest-dom/vitest';
-
-afterEach(() => {
- vi.restoreAllMocks();
- cleanup();
-});
-
-function getMoreColorButton(container: HTMLElement): HTMLButtonElement {
- const button = Array.from(
- container.querySelectorAll<HTMLButtonElement>('[data-u-comp="color-picker"] button')
- ).at(-1);
- if (!button) throw new Error('More color button was not rendered.');
- return button;
-}
-
-describe('ColorPicker extra', () => {
- it('should handle rgba mode and confirm custom color', () => {
- const onChange = vi.fn();
- const { container } = render(
- <ColorPicker format="rgba" value="rgba(10, 20, 30, 0.5)" onChange={onChange} />
- );
-
- const moreButton = getMoreColorButton(container);
- fireEvent.click(moreButton);
-
- const buttons = Array.from(document.querySelectorAll('button'));
- const confirmBtn = buttons[buttons.length - 1] as HTMLButtonElement;
- expect(confirmBtn).toBeTruthy();
- fireEvent.click(confirmBtn);
- expect(onChange).toHaveBeenCalled();
- expect(onChange.mock.calls.some(([value]) => String(value).startsWith('rgba('))).toBe(true);
- });
-
- it('should log error when invalid value is provided', () => {
- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
- render(<ColorPicker format="rgba" value="invalid-rgba" />);
- expect(errorSpy).toHaveBeenCalled();
- });
-
- it('should stop click propagation on root container', () => {
- const parentClick = vi.fn();
- const { container } = render(
- <div onClick={parentClick}>
- <ColorPicker />
- </div>
- );
-
- const root = container.querySelector('[data-u-comp="color-picker"]') as HTMLElement;
- expect(root).toBeTruthy();
- fireEvent.click(root);
- expect(parentClick).not.toHaveBeenCalled();
- });
-
- it('should emit rgba from presets and confirm/cancel inside dialog', () => {
- const onChange = vi.fn();
- const { container } = render(<ColorPicker format="rgba" value="rgba(0, 0, 0, 1)" onChange={onChange} />);
-
- const presetButton = container.querySelector('[data-u-comp="color-picker-presets"] button') as HTMLButtonElement;
- fireEvent.click(presetButton);
- expect(onChange.mock.calls.some(([value]) => String(value).startsWith('rgba('))).toBe(true);
-
- const moreButton = getMoreColorButton(container);
- fireEvent.click(moreButton);
-
- const alphaInput = document.querySelector('input[maxlength="4"]') as HTMLInputElement;
- fireEvent.change(alphaInput, { target: { value: '0.6' } });
-
- const [cancelBtn, confirmBtn] = Array.from(document.querySelectorAll('footer button')) as HTMLButtonElement[];
- fireEvent.click(cancelBtn);
- fireEvent.click(moreButton);
- fireEvent.click(confirmBtn);
- expect(onChange).toHaveBeenCalled();
- });
-
- it('should confirm custom color in hex mode', () => {
- const onChange = vi.fn();
- const { container } = render(<ColorPicker format="hex" value="#00ff00" onChange={onChange} />);
- const moreButton = getMoreColorButton(container);
-
- fireEvent.click(moreButton);
- const confirmBtn = Array.from(document.querySelectorAll('footer button')).at(-1) as HTMLButtonElement;
- fireEvent.click(confirmBtn);
-
- expect(onChange.mock.calls.some(([value]) => String(value).startsWith('#'))).toBe(true);
- });
-});
diff --git a/packages/design/src/components/color-picker/__tests__/index.spec.tsx b/packages/design/src/components/color-picker/__tests__/index.spec.tsx
deleted file mode 100644
index efd07cd4ec..0000000000
--- a/packages/design/src/components/color-picker/__tests__/index.spec.tsx
+++ /dev/null
@@ -1,351 +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 { MobileDropdown } from '../../dropdown/MobileDropdown';
-import { ColorInput } from '../ColorInput';
-import { ColorPicker } from '../ColorPicker';
-import { ColorPickerPanel } from '../ColorPickerPanel';
-import { ColorSpectrum } from '../ColorSpectrum';
-import { HueSlider } from '../HueSlider';
-import { MobileColorPicker } from '../MobileColorPicker';
-import { MobileColorPresets } from '../MobileColorPresets';
-import { colorPresets } from '../presets';
-import '@testing-library/jest-dom/vitest';
-
-afterEach(cleanup);
-
-function getMoreColorButton(container: HTMLElement): HTMLButtonElement {
- const button = Array.from(
- container.querySelectorAll<HTMLButtonElement>('[data-u-comp="color-picker"] button')
- ).at(-1);
- if (!button) throw new Error('More color button was not rendered.');
- return button;
-}
-
-describe('ColorPicker', () => {
- it('should not contain duplicate preset colors', () => {
- const flattenedPresets = colorPresets.flat().map((color) => color.toUpperCase());
-
- expect(new Set(flattenedPresets).size).toBe(flattenedPresets.length);
- });
-
- it('should render correctly', () => {
- const { container } = render(<ColorPicker />);
-
- expect(container.querySelector('[data-u-comp="color-picker"]')).toBeTruthy();
- expect(container.querySelectorAll('[data-u-comp="color-picker-presets"] button').length).toBeGreaterThan(0);
- });
-
- it('should render with value', () => {
- const { container } = render(<ColorPicker value="#FF0000" />);
-
- expect(container.querySelector('[data-u-comp="color-picker"]')).toBeTruthy();
- expect(container.querySelectorAll('[data-u-comp="color-picker-presets"] button').length).toBeGreaterThan(0);
- });
-
- it('should apply rtl direction to the picker content', () => {
- const { container } = render(
- <ConfigProvider mountContainer={document.body} direction="rtl">
- <ColorPicker />
- </ConfigProvider>
- );
-
- expect(container.querySelector('[data-u-comp="color-picker"]')?.getAttribute('dir')).toBe('rtl');
- });
-
- it('should call onChange when color changes', () => {
- const handleChange = vi.fn();
- const { container } = render(<ColorPicker onChange={handleChange} />);
- const presetBtn = container.querySelector('[data-u-comp="color-picker-presets"] button');
- if (presetBtn) {
- presetBtn.dispatchEvent(new MouseEvent('click', { bubbles: true }));
- expect(handleChange).toHaveBeenCalled();
- }
- });
-
- it('should support format hex', () => {
- const { container } = render(<ColorPicker format="hex" value="#00FF00" />);
- expect(container.querySelector('[data-u-comp="color-picker"]')).toBeTruthy();
- expect(container.querySelectorAll('[data-u-comp="color-picker-presets"] button').length).toBeGreaterThan(0);
- });
-
- it('should open dialog when more is clicked', () => {
- const { container } = render(
- <ConfigProvider locale={enUS.design} mountContainer={document.body}>
- <ColorPicker />
- </ConfigProvider>
- );
- fireEvent.click(getMoreColorButton(container));
- expect(document.body.innerHTML).toContain('univer-grid univer-w-64 univer-gap-2');
- });
-
- it('should place custom color dialog above parent popovers', () => {
- const { container } = render(
- <ConfigProvider locale={enUS.design} mountContainer={document.body}>
- <ColorPicker />
- </ConfigProvider>
- );
- const moreButton = Array.from(container.querySelectorAll('[data-u-comp="color-picker"] button'))
- .find((button) => button.textContent === enUS.design.ColorPicker.more);
-
- if (!moreButton) throw new Error('Custom color button was not rendered.');
-
- fireEvent.click(moreButton);
-
- const dialog = document.querySelector('[role="dialog"]');
- const overlay = document.querySelector('[data-state="open"].univer-fixed.univer-inset-0');
-
- expect(dialog?.className).toContain('!univer-z-[1090]');
- expect(overlay?.className).toContain('!univer-z-[1090]');
- });
-
- it('should call onChange when rgb input changes in dialog', () => {
- const handleChange = vi.fn();
- const { container } = render(<ColorPicker onChange={handleChange} />);
- getMoreColorButton(container).dispatchEvent(new MouseEvent('click', { bubbles: true }));
- const rgbInputs = Array.from(document.querySelectorAll('input')).filter((input) => input.maxLength === 3);
- if (rgbInputs.length === 3) {
- rgbInputs[0].value = '1';
- rgbInputs[0].dispatchEvent(new Event('input', { bubbles: true }));
- rgbInputs[1].value = '2';
- rgbInputs[1].dispatchEvent(new Event('input', { bubbles: true }));
- rgbInputs[2].value = '3';
- rgbInputs[2].dispatchEvent(new Event('input', { bubbles: true }));
- const confirmBtn = Array.from(document.querySelectorAll('button')).find((btn) => btn.textContent?.includes('确定') || btn.textContent?.toLowerCase().includes('confirm'));
- if (confirmBtn) {
- confirmBtn.dispatchEvent(new MouseEvent('click', { bubbles: true }));
- expect(handleChange).toHaveBeenCalled();
- }
- }
- });
-});
-
-describe('mobile color picker views', () => {
- it('renders the touch-first picker explicitly', () => {
- const { container } = render(
- <ConfigProvider locale={enUS.design} mountContainer={document.body}>
- <MobileColorPicker value="#FFFFFF" />
- </ConfigProvider>
- );
-
- expect(container.querySelector('[data-u-comp="color-picker"][data-presentation="mobile"]')).toBeInTheDocument();
- expect(getMoreColorButton(container)).toHaveClass('univer-h-11');
- });
-
- it('uses the mobile action layout for custom color actions', () => {
- const { container } = render(
- <ConfigProvider locale={enUS.design} mountContainer={document.body}>
- <MobileColorPicker value="#FFFFFF" />
- </ConfigProvider>
- );
-
- fireEvent.click(getMoreColorButton(container));
-
- const confirmButton = Array.from(document.querySelectorAll('button'))
- .find((button) => button.textContent === enUS.design.ColorPicker.confirm);
- expect(confirmButton?.parentElement).toHaveClass('univer-w-full');
- });
-
- it('opens custom colors above the containing mobile dropdown', () => {
- render(
- <ConfigProvider locale={enUS.design} mountContainer={document.body}>
- <MobileDropdown open overlay={<MobileColorPicker value="#FFFFFF" />}>
- <button type="button">Color</button>
- </MobileDropdown>
- </ConfigProvider>
- );
-
- fireEvent.click(getMoreColorButton(document.body));
-
- const dialogs = Array.from(document.querySelectorAll<HTMLElement>('[role="dialog"]'));
- const customColorDialog = dialogs
- .find((dialog) => dialog.className.includes('!univer-z-[1420]'));
- const customColorOverlay = Array.from(document.querySelectorAll<HTMLElement>('[data-state="open"].univer-fixed.univer-inset-0'))
- .find((overlay) => overlay.className.includes('!univer-z-[1410]'));
- const customColorContent = customColorDialog?.querySelector<HTMLElement>('[data-u-comp="mobile-color-picker-custom"]');
- const spectrum = customColorContent?.querySelector<HTMLElement>('[data-u-comp="color-picker-spectrum"]');
- const spectrumContainer = spectrum?.parentElement;
-
- expect(dialogs).toHaveLength(2);
- expect(customColorDialog).toBeInTheDocument();
- expect(customColorOverlay).toBeInTheDocument();
- expect(customColorContent).toHaveClass('univer-w-full');
- expect(spectrumContainer).toHaveClass('univer-h-44', 'univer-w-full');
- expect(spectrum).toHaveClass('univer-size-full');
- });
-
- it('closes the containing mobile dropdown after selecting a preset color', () => {
- render(
- <ConfigProvider locale={enUS.design} mountContainer={document.body}>
- <MobileDropdown overlay={<MobileColorPicker value="#FFFFFF" />}>
- <button type="button">Color</button>
- </MobileDropdown>
- </ConfigProvider>
- );
-
- fireEvent.click(document.querySelector('button')!);
- fireEvent.click(document.querySelectorAll('[data-u-comp="color-picker"] button')[1]);
-
- expect(document.querySelector('[role="dialog"]')).not.toBeInTheDocument();
- });
-
- it('closes both color dialogs after confirming a custom color', () => {
- render(
- <ConfigProvider locale={enUS.design} mountContainer={document.body}>
- <MobileDropdown overlay={<MobileColorPicker value="#FFFFFF" />}>
- <button type="button">Color</button>
- </MobileDropdown>
- </ConfigProvider>
- );
-
- fireEvent.click(document.querySelector('button')!);
- fireEvent.click(getMoreColorButton(document.body));
- fireEvent.click(document.querySelector<HTMLButtonElement>('[data-u-comp="mobile-color-picker-custom"] button:last-child')!);
-
- expect(document.querySelector('[role="dialog"]')).not.toBeInTheDocument();
- });
-
- it('keeps the containing mobile dropdown open after cancelling a custom color', () => {
- render(
- <ConfigProvider locale={enUS.design} mountContainer={document.body}>
- <MobileDropdown overlay={<MobileColorPicker value="#FFFFFF" />}>
- <button type="button">Color</button>
- </MobileDropdown>
- </ConfigProvider>
- );
-
- fireEvent.click(document.querySelector('button')!);
- fireEvent.click(getMoreColorButton(document.body));
- fireEvent.click(document.querySelector<HTMLButtonElement>('[data-u-comp="mobile-color-picker-custom"] button')!);
-
- expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1);
- expect(document.querySelector('[data-u-comp="color-picker"]')).toBeInTheDocument();
- });
-
- it('renders large preset targets and applies the selected color', () => {
- const onSelect = vi.fn();
- const { container } = render(<MobileColorPresets value="#FFFFFF" onSelect={onSelect} />);
- const buttons = container.querySelectorAll('button');
-
- expect(buttons).toHaveLength(colorPresets.flat().length);
- expect(buttons[0]).toHaveAttribute('aria-pressed', 'true');
- expect(buttons[0].querySelector('span')).toHaveClass('univer-aspect-square', 'univer-w-8');
-
- fireEvent.click(buttons[1]);
- expect(onSelect).toHaveBeenCalledWith(colorPresets.flat()[1]);
- });
-
- it('commits a custom color only when the apply button is clicked', () => {
- const onConfirm = vi.fn();
- const { getByRole } = render(
- <ConfigProvider locale={enUS.design} mountContainer={document.body}>
- <ColorPickerPanel value="#3F83F8" onConfirm={onConfirm} />
- </ConfigProvider>
- );
-
- expect(onConfirm).not.toHaveBeenCalled();
- fireEvent.click(getByRole('button', { name: enUS.design.ColorPicker.confirm }));
- expect(onConfirm).toHaveBeenCalledWith('#3f83f8');
- });
-});
-
-describe('HueSlider', () => {
- const onChange = vi.fn();
-
- function TestComponent(props: { onChange: typeof onChange } & Omit<ComponentProps<typeof HueSlider>, 'hsv' | 'onChange'>) {
- const { onChange, ...restProps } = props;
- const [hsv, setHsv] = useState<[number, number, number]>([0, 100, 100]);
- function handleChange(h: number, s: number, v: number) {
- setHsv([h, s, v]);
- onChange([h, s, v]);
- }
-
- return <HueSlider hsv={hsv} onChange={handleChange} {...restProps} />;
- }
-
- it('should call onChange when hue changes by pointer', () => {
- const { container } = render(<TestComponent onChange={onChange} />);
- const slider = container.querySelector('[data-u-comp="color-picker-hue-slider"] > div');
- if (slider) {
- slider.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, clientX: 50 }));
- expect(onChange).toHaveBeenCalled();
- }
- });
-});
-
-describe('ColorSpectrum', () => {
- const onChange = vi.fn();
-
- function TestComponent(props: { onChange: typeof onChange } & Omit<ComponentProps<typeof ColorSpectrum>, 'hsv' | 'onChange'>) {
- const { onChange, ...restProps } = props;
- const [hsv, setHsv] = useState<[number, number, number]>([0, 100, 100]);
- function handleChange(h: number, s: number, v: number) {
- setHsv([h, s, v]);
- onChange([h, s, v]);
- }
-
- return <ColorSpectrum hsv={hsv} onChange={handleChange} {...restProps} />;
- }
-
- it('should call onChange when color changes by pointer', () => {
- const { container } = render(<TestComponent onChange={onChange} />);
- const spectrum = container.querySelector('[data-u-comp="color-picker-spectrum"] > [data-u-comp="color-picker-spectrum-canvas"]');
- if (spectrum) {
- spectrum.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, clientX: 50 }));
- expect(onChange).toHaveBeenCalled();
- }
- });
-});
-
-describe('ColorInput', () => {
- const onChange = vi.fn();
-
- function TestComponent(props: { onChange: typeof onChange } & Omit<ComponentProps<typeof ColorInput>, 'hsv' | 'onChange'>) {
- const { onChange, ...restProps } = props;
- const [value, setValue] = useState<[number, number, number]>([0, 100, 100]);
-
- function handleChange(h: number, s: number, v: number) {
- setValue([h, s, v]);
- onChange([h, s, v]);
- }
-
- return (
- <ColorInput hsv={value} onChange={handleChange} {...restProps} />
- );
- }
-
- it('should call onChange when color input changes', () => {
- const { container } = render(<TestComponent onChange={onChange} alpha={1} format="hex" />);
- const inputs = container.querySelectorAll('input[type="text"]') as unknown as HTMLInputElement[];
-
- const [rInput, gInput, bInput] = inputs;
- if (rInput && gInput && bInput) {
- rInput.value = '#FF0000';
- gInput.value = '#00FF00';
- bInput.value = '#0000FF';
- rInput.dispatchEvent(new Event('input', { bubbles: true }));
- gInput.dispatchEvent(new Event('input', { bubbles: true }));
- bInput.dispatchEvent(new Event('input', { bubbles: true }));
- expect(onChange).toHaveBeenCalledWith([0, 100, 100]); // Assuming #FF0000 corresponds to HSV [0, 100, 100]
- }
- });
-});
diff --git a/packages/sheets-ui/src/menu/__tests__/sheet.menu.spec.ts b/packages/sheets-ui/src/menu/__tests__/sheet.menu.spec.ts
new file mode 100644
index 0000000000..983a976336
--- /dev/null
+++ b/packages/sheets-ui/src/menu/__tests__/sheet.menu.spec.ts
@@ -0,0 +1,77 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { ICommandService, RedoCommand, UndoCommand } from '@univerjs/core';
+import { SetTabColorCommand, SetTabColorMutation, SetWorksheetActiveOperation } from '@univerjs/sheets';
+import { firstValueFrom } from 'rxjs';
+import { describe, expect, it } from 'vitest';
+import { createCommandTestBed } from '../../commands/commands/__tests__/create-command-test-bed';
+import { ChangeColorSheetMenuItemFactory } from '../sheet.menu';
+
+describe('sheet tab color menu', () => {
+ it('reads current tab colors and resets through the undoable tab color command', async () => {
+ const testBed = createCommandTestBed();
+ const commandService = testBed.get(ICommandService);
+ [SetTabColorCommand, SetTabColorMutation].forEach((command) => commandService.registerCommand(command));
+ const menu = ChangeColorSheetMenuItemFactory(testBed.univer.__getInjector());
+ if (!Array.isArray(menu.selections)) throw new Error('Missing color selections');
+ const reset = menu.selections.find((option) => option.value === '');
+ const picker = menu.selections.find((option) => option.value$);
+ expect(reset).toBeDefined();
+ expect(picker?.value$).toBeDefined();
+ const colors: string[] = [];
+ const subscription = picker!.value$!.subscribe((color) => colors.push(color));
+ try {
+ expect(colors.at(-1)).toBe('');
+ await commandService.executeCommand(SetTabColorCommand.id, { value: '#3f83f8' });
+ expect(colors.at(-1)).toBe('#3f83f8');
+ expect(await firstValueFrom(picker!.value$!)).toBe('#3f83f8');
+ await commandService.executeCommand(menu.id, { value: reset!.value });
+ expect(testBed.sheet.getActiveSheet().getTabColor()).toBe('');
+ expect(colors.at(-1)).toBe('');
+ await commandService.executeCommand(UndoCommand.id);
+ expect(colors.at(-1)).toBe('#3f83f8');
+ await commandService.executeCommand(RedoCommand.id);
+ expect(colors.at(-1)).toBe('');
+ subscription.unsubscribe();
+ await commandService.executeCommand(SetTabColorCommand.id, { value: '#ffffff' });
+ expect(colors.at(-1)).toBe('');
+ } finally {
+ subscription.unsubscribe();
+ testBed.univer.dispose();
+ }
+ });
+
+ it('follows the active tab when switching sheets', () => {
+ const testBed = createCommandTestBed();
+ const commandService = testBed.get(ICommandService);
+ commandService.registerCommand(SetWorksheetActiveOperation);
+ const sheet = testBed.sheet;
+ sheet.addWorksheet('sheet2', sheet.getSheets().length, { id: 'sheet2', name: 'Second', tabColor: '#f05252' });
+ const menu = ChangeColorSheetMenuItemFactory(testBed.univer.__getInjector());
+ if (!Array.isArray(menu.selections)) throw new Error('Missing color selections');
+ const picker = menu.selections.find((option) => option.value$)!;
+ const colors: string[] = [];
+ const subscription = picker.value$!.subscribe((color) => colors.push(color));
+ try {
+ commandService.syncExecuteCommand(SetWorksheetActiveOperation.id, { unitId: sheet.getUnitId(), subUnitId: 'sheet2' });
+ expect(colors.at(-1)).toBe('#f05252');
+ } finally {
+ subscription.unsubscribe();
+ testBed.univer.dispose();
+ }
+ });
+});
diff --git a/packages/sheets-ui/src/menu/sheet.menu.ts b/packages/sheets-ui/src/menu/sheet.menu.ts
index bb71fd2733..35c629dc25 100644
--- a/packages/sheets-ui/src/menu/sheet.menu.ts
+++ b/packages/sheets-ui/src/menu/sheet.menu.ts
@@ -17,13 +17,14 @@
import type { IAccessor, Workbook } from '@univerjs/core';
import type { IMenuButtonItem, IMenuSelectorItem } from '@univerjs/ui';
import type { Subscriber } from 'rxjs';
-import type { LocaleKey } from '../locale/types';
import { BooleanNumber, ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import {
CopySheetCommand,
InsertSheetMutation,
RemoveSheetMutation,
SetTabColorCommand,
+ SetTabColorMutation,
+ SetWorksheetActiveOperation,
SetWorksheetHideCommand,
SetWorksheetHideMutation,
SetWorksheetShowCommand,
@@ -35,6 +36,7 @@ import {
} from '@univerjs/sheets';
import { COLOR_PICKER_COMPONENT, getMenuHiddenObservable, MenuItemType } from '@univerjs/ui';
import { combineLatest, combineLatestWith, map, Observable } from 'rxjs';
+import type { LocaleKey } from '../locale/types';
import { RemoveSheetConfirmCommand } from '../commands/commands/remove-sheet-confirm.command';
import { ShowMenuListCommand } from '../commands/commands/unhide.command';
import { RenameSheetOperation } from '../commands/operations/rename-sheet.operation';
@@ -98,18 +100,38 @@ export function RenameSheetMenuItemFactory(accessor: IAccessor): IMenuButtonItem
};
}
-export function ChangeColorSheetMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<LocaleKey> {
+export function ChangeColorSheetMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<LocaleKey, string, string> {
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+ const commandService = accessor.get(ICommandService);
return {
id: SetTabColorCommand.id,
title: 'sheets-ui.sheetConfig.changeColor',
type: MenuItemType.SELECTOR,
selections: [
+ {
+ label: 'sheets-ui.toolbar.resetColor',
+ icon: 'NoColorDoubleIcon',
+ value: '',
+ },
{
label: {
name: COLOR_PICKER_COMPONENT,
hoverable: false,
selectable: false,
},
+ value$: new Observable<string>((subscriber) => {
+ const updateColor = () => {
+ const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);
+ subscriber.next(workbook?.getActiveSheet()?.getTabColor() ?? '');
+ };
+ updateColor();
+ const disposable = commandService.onCommandExecuted(({ id }) => {
+ if (id === SetTabColorMutation.id || id === SetWorksheetActiveOperation.id) {
+ updateColor();
+ }
+ });
+ return () => disposable.dispose();
+ }),
},
],
hidden$: getWorkbookPermissionDisable$(accessor, [WorkbookEditablePermission]),
diff --git a/packages/ui/src/views/components/context-menu/ContextMenuPanel.tsx b/packages/ui/src/views/components/context-menu/ContextMenuPanel.tsx
index 59b16a59e1..7a740ece0d 100644
--- a/packages/ui/src/views/components/context-menu/ContextMenuPanel.tsx
+++ b/packages/ui/src/views/components/context-menu/ContextMenuPanel.tsx
@@ -15,6 +15,12 @@
*/
import type { Dispatch, KeyboardEvent, SetStateAction } from 'react';
+import { isRealNum, LocaleService } from '@univerjs/core';
+import { borderBottomClassName, borderClassName, clsx, cva, scrollbarClassName } from '@univerjs/design';
+import { CheckMarkIcon, MoreLeftIcon, MoreRightIcon } from '@univerjs/icons';
+import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from 'react';
+import { createPortal } from 'react-dom';
+import { combineLatest, isObservable, map, merge, of, scan, startWith } from 'rxjs';
import type {
IDisplayMenuItem,
IMenuButtonItem,
@@ -24,12 +30,6 @@ import type {
MenuItemDefaultValueType,
} from '../../../services/menu/menu';
import type { IMenuSchema } from '../../../services/menu/menu-manager.service';
-import { isRealNum, LocaleService } from '@univerjs/core';
-import { borderBottomClassName, borderClassName, clsx, cva, scrollbarClassName } from '@univerjs/design';
-import { CheckMarkIcon, MoreLeftIcon, MoreRightIcon } from '@univerjs/icons';
-import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from 'react';
-import { createPortal } from 'react-dom';
-import { combineLatest, isObservable, map, merge, of, scan, startWith } from 'rxjs';
import { ILayoutService } from '../../../services/layout/layout.service';
import { MenuItemType } from '../../../services/menu/menu';
import { IMenuManagerService } from '../../../services/menu/menu-manager.service';
@@ -1190,7 +1190,9 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
clearSubmenuCloseTimer();
submenuCloseTimerRef.current = setTimeout(() => {
submenuCloseTimerRef.current = null;
- closeSubmenu();
+ if (!submenuElementRef.current?.contains(document.activeElement)) {
+ closeSubmenu();
+ }
}, CONTEXT_MENU_SUBMENU_CLOSE_DELAY);
}, [clearSubmenuCloseTimer, closeSubmenu]);
@@ -1261,11 +1263,16 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
};
const frameId = window.requestAnimationFrame(updateSubmenuPosition);
+ const resizeObserver = new ResizeObserver(updateSubmenuPosition);
+ if (submenuElementRef.current) {
+ resizeObserver.observe(submenuElementRef.current);
+ }
window.addEventListener('resize', updateSubmenuPosition);
window.addEventListener('scroll', updateSubmenuPosition, true);
return () => {
window.cancelAnimationFrame(frameId);
+ resizeObserver.disconnect();
window.removeEventListener('resize', updateSubmenuPosition);
window.removeEventListener('scroll', updateSubmenuPosition, true);
};
@@ -1339,6 +1346,9 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
}}
onMouseLeave={(event) => {
if (hasSubmenu) {
+ if (submenuElementRef.current?.contains(document.activeElement)) {
+ return;
+ }
const nextTarget = event.relatedTarget as Node | null;
if (nextTarget && submenuElementRef.current?.contains(nextTarget)) {
return;
@@ -1471,6 +1481,9 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
onMenuPointerEnter?.();
}}
onMouseLeave={(event) => {
+ if (submenuElementRef.current?.contains(document.activeElement)) {
+ return;
+ }
const nextTarget = event.relatedTarget as Node | null;
if (nextTarget && menuItemElementRef.current?.contains(nextTarget)) {
return;
diff --git a/packages/ui/src/views/components/context-menu/__tests__/ContextMenuPanel.spec.tsx b/packages/ui/src/views/components/context-menu/__tests__/ContextMenuPanel.spec.tsx
index abf50567f4..f8eb55c4ec 100644
--- a/packages/ui/src/views/components/context-menu/__tests__/ContextMenuPanel.spec.tsx
+++ b/packages/ui/src/views/components/context-menu/__tests__/ContextMenuPanel.spec.tsx
@@ -15,8 +15,6 @@
*/
import type { ReactElement } from 'react';
-import type { IValueOption } from '../../../../services/menu/menu';
-import type { IMenuSchema, MenuSchemaType } from '../../../../services/menu/menu-manager.service';
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import {
ConfigService,
@@ -34,6 +32,8 @@ import {
import { RediContext } from '@wendellhu/redi/react-bindings';
import { BehaviorSubject } from 'rxjs';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { IValueOption } from '../../../../services/menu/menu';
+import type { IMenuSchema, MenuSchemaType } from '../../../../services/menu/menu-manager.service';
import { ComponentManager } from '../../../../common/component-manager';
import { IconManager } from '../../../../common/icon-manager';
import enUS from '../../../../locale/en-US';
@@ -550,6 +550,11 @@ describe('ContextMenuPanel', () => {
fireEvent.click(screen.getByRole('button', { name: 'Pick a value' }));
+ screen.getByRole('button', { name: 'Pick a value' }).focus();
+ const submenu = document.querySelector(`[${CONTEXT_MENU_SUBMENU_PORTAL_ATTR}="true"]`)!;
+ fireEvent.mouseLeave(submenu, { relatedTarget: document.body });
+ fireEvent.mouseLeave(insertButton.parentElement!, { relatedTarget: document.body });
+
expect(onPickerClick).toHaveBeenCalledOnce();
expect(onOptionSelect).not.toHaveBeenCalled();
expect(screen.getByRole('button', { name: 'Pick a value' })).not.toBeNull();
@@ -655,6 +660,45 @@ describe('ContextMenuPanel', () => {
await waitFor(() => expect(screen.queryByText('docs-ui.printLayout')).toBeNull());
});
+ it('keeps a submenu inside the viewport when its color editor grows', async () => {
+ vi.stubGlobal('innerHeight', 600);
+ const resizeCallbacks = new Map<Element, () => void>();
+ const disconnect = vi.fn();
+ vi.stubGlobal('ResizeObserver', class {
+ constructor(private readonly callback: () => void) {}
+ observe(element: Element) { resizeCallbacks.set(element, this.callback); }
+ disconnect = disconnect;
+ });
+ const view = renderWithDependencies(
+ <ContextMenuPanel menuType="color-root" />,
+ {
+ 'color-root': [{
+ key: 'color',
+ order: 0,
+ item: {
+ id: 'color',
+ type: MenuItemType.SELECTOR,
+ title: 'Color',
+ selections: [{ label: 'Custom color', value: '#123456' }],
+ },
+ }],
+ }
+ );
+ const button = screen.getByRole('button', { name: 'Color' });
+ vi.spyOn(button.parentElement!, 'getBoundingClientRect').mockReturnValue(new DOMRect(100, 400, 160, 32));
+ fireEvent.click(button);
+ const submenu = document.querySelector<HTMLElement>(`[${CONTEXT_MENU_SUBMENU_PORTAL_ATTR}="true"]`)!;
+ let height = 100;
+ vi.spyOn(submenu, 'getBoundingClientRect').mockImplementation(() => new DOMRect(0, 0, 288, height));
+ await nextFrame();
+ height = 320;
+ act(() => resizeCallbacks.get(submenu)!());
+ expect(Number.parseFloat(submenu.style.top) + height).toBeLessThanOrEqual(window.innerHeight);
+ expect(Number.parseFloat(submenu.style.top)).toBeGreaterThanOrEqual(0);
+ view.unmount();
+ expect(disconnect).toHaveBeenCalled();
+ });
+
it('opens submenus to the left by default in rtl when there is enough space', async () => {
renderWithDependencies(
<ContextMenuPanel menuType="submenu-root" />,
diff --git a/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx b/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx
index c8e8829458..4a93a5336b 100644
--- a/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx
+++ b/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx
@@ -265,10 +265,6 @@ export function DropdownMenuLabel({ icon, value, option, preserveStrokeWidth, on
);
}
-function getOptionKey(option: IValueOption) {
- return String(option.id ?? option.commandId ?? option.value ?? (typeof option.label === 'string' ? option.label : option.label?.name));
-}
-
export function DropdownMenuWrapper({
menuId,
slot,
@@ -458,6 +454,10 @@ export function DropdownMenuWrapper({
keepInteractionInsideSameEmbedBoundary(event);
}
+ function getOptionKey(option: IValueOption) {
+ return String(option.id ?? option.commandId ?? option.value ?? (typeof option.label === 'string' ? option.label : option.label?.name));
+ }
+
function handleOptionSelect(option: IValueOption) {
const target = sheetTarget;
if (target && target !== sheetTargetRef.current) {
@@ -506,7 +506,7 @@ export function DropdownMenuWrapper({
const items: IDropdownMenuProps['items'] = options.map((option) => ({
type: 'item',
className: clsx({
- 'focus:univer-bg-gray-0 dark:focus:!univer-bg-gray-800':
+ 'focus:univer-bg-transparent dark:focus:!univer-bg-transparent':
typeof option.label !== 'string' && option.label?.hoverable === false,
'!univer-p-0': isSingleEmbeddedCustomPanel ||
(typeof option.label === 'object' && option.label.name === FONT_FAMILY_ITEM_COMPONENT),