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): align gradient angle preview (#6997)

Univerf6c70e9e5aef
diff --git a/packages/core/src/types/interfaces/i-document-data.ts b/packages/core/src/types/interfaces/i-document-data.ts
index c3dfce0298..3830d1d975 100644
--- a/packages/core/src/types/interfaces/i-document-data.ts
+++ b/packages/core/src/types/interfaces/i-document-data.ts
@@ -16,6 +16,7 @@
import type { ISize } from '../../shared/shape';
import type { BooleanNumber, CellValueType, HorizontalAlign, LocaleType, TextDirection, VerticalAlign, WrapStrategy } from '../enum';
+import type { ImageSourceType } from '../../services/image-io/image-io.service';
import type { IDrawingParam } from './i-drawing';
import type { IMention } from './i-mention';
import type { IColorStyle, IStyleBase } from './i-style-data';
@@ -710,11 +711,53 @@ export interface IChartProperties {}
/**
* Properties of text style
*/
+export type DocTextFillType = 'none' | 'solid' | 'gradient' | 'picture';
+
+export type DocTextFillGradientType = 'linear' | 'radial' | 'angular' | 'diamond';
+
+export type DocTextFillPictureMode = 'stretch' | 'tile';
+
+export interface IDocTextFillGradientStop {
+ /**
+ * Offset in percent. Values in the 0-1 range are also accepted by renderers
+ * for compatibility and normalized to percent.
+ */
+ offset: number;
+ color: string;
+ opacity?: number;
+}
+
+export interface IDocTextFill {
+ /**
+ * Hidden renderer-level text fill. Normal document UI does not expose it,
+ * but rich-text renderers honor it when present on a run style.
+ */
+ type: DocTextFillType;
+ color?: string;
+ opacity?: number;
+ gradient?: {
+ type?: DocTextFillGradientType;
+ angle?: number;
+ stops?: IDocTextFillGradientStop[];
+ };
+ picture?: {
+ source?: string;
+ sourceType?: ImageSourceType;
+ opacity?: number;
+ mode?: DocTextFillPictureMode;
+ scaleX?: number;
+ scaleY?: number;
+ offsetX?: number;
+ offsetY?: number;
+ };
+}
+
export interface ITextStyle extends IStyleBase {
// bo?: BaselineOffset; // BaselineOffset, sup, sub
sc?: number; // spacing
pos?: number; // position
sa?: number; // scale
+ textFill?: IDocTextFill;
}
export interface IIndentStart {
diff --git a/packages/design/src/components/gradient-color-picker/GradientColorPicker.stories.tsx b/packages/design/src/components/gradient-color-picker/GradientColorPicker.stories.tsx
index 45544c12ae..6f7d4bfb4c 100644
--- a/packages/design/src/components/gradient-color-picker/GradientColorPicker.stories.tsx
+++ b/packages/design/src/components/gradient-color-picker/GradientColorPicker.stories.tsx
@@ -38,7 +38,7 @@ export const Playground = {
{ color: '#409eff', offset: 0 },
{ color: '#67c23a', offset: 100 },
],
- angle: 90,
+ angle: 0,
});
return (
diff --git a/packages/design/src/components/gradient-color-picker/GradientColorPicker.tsx b/packages/design/src/components/gradient-color-picker/GradientColorPicker.tsx
index aaa6061e73..58e7d2dad4 100644
--- a/packages/design/src/components/gradient-color-picker/GradientColorPicker.tsx
+++ b/packages/design/src/components/gradient-color-picker/GradientColorPicker.tsx
@@ -29,6 +29,7 @@ export type GradientType = 'linear' | 'radial' | 'angular' | 'diamond';
export interface IGradientStop {
color: string;
offset: number;
+ opacity?: number;
}
export interface IGradientValue {
@@ -39,6 +40,7 @@ export interface IGradientValue {
export interface IGradientColorPickerProps {
className?: string;
+ compact?: boolean;
value?: IGradientValue;
onChange?: (value: IGradientValue) => void;
}
@@ -49,24 +51,86 @@ const DEFAULT_VALUE: IGradientValue = {
{ color: '#ffffff', offset: 0 },
{ color: '#000000', offset: 100 },
],
- angle: 90,
+ angle: 0,
};
+function clamp(value: number, min: number, max: number): number {
+ return Math.max(min, Math.min(max, value));
+}
+
+function getStopOpacity(stop: IGradientStop | undefined): number {
+ return clamp(stop?.opacity ?? 1, 0, 1);
+}
+
+function getColorWithOpacity(color: string, opacity: number): string {
+ if (opacity >= 1) {
+ return color;
+ }
+
+ const value = color.trim();
+ if (/^#[0-9a-f]{3}$/i.test(value)) {
+ const [, r, g, b] = value;
+ return `rgba(${Number.parseInt(r + r, 16)}, ${Number.parseInt(g + g, 16)}, ${Number.parseInt(b + b, 16)}, ${opacity})`;
+ }
+
+ if (/^#[0-9a-f]{6}$/i.test(value)) {
+ return `rgba(${Number.parseInt(value.slice(1, 3), 16)}, ${Number.parseInt(value.slice(3, 5), 16)}, ${Number.parseInt(value.slice(5, 7), 16)}, ${opacity})`;
+ }
+
+ const rgba = /^rgba?\(([^)]+)\)$/i.exec(value);
+ if (rgba) {
+ const parts = rgba[1].split(',').map((part) => part.trim());
+ const baseAlpha = parts[3] === undefined ? 1 : Number.parseFloat(parts[3]);
+ const alpha = Number.isFinite(baseAlpha) ? clamp(baseAlpha * opacity, 0, 1) : opacity;
+ return `rgba(${parts[0]}, ${parts[1]}, ${parts[2]}, ${alpha})`;
+ }
+
+ return color;
+}
+
+function getStopColor(stop: IGradientStop): string {
+ return getColorWithOpacity(stop.color, getStopOpacity(stop));
+}
+
+function getGradientAngle(value: IGradientValue): number {
+ return value.angle ?? DEFAULT_VALUE.angle ?? 0;
+}
+
+function getCssLinearGradientAngle(value: IGradientValue): number {
+ return (getGradientAngle(value) + 90) % 360;
+}
+
export function GradientColorPicker(props: IGradientColorPickerProps) {
- const { className, value = DEFAULT_VALUE, onChange } = props;
+ const { className, compact = false, value = DEFAULT_VALUE, onChange } = props;
const { locale } = useContext(ConfigContext);
+ const [draftValue, setDraftValue] = useState<IGradientValue>(value);
const [selectedIndex, setSelectedIndex] = useState<number>(0);
const barRef = useRef<HTMLDivElement>(null);
+ const valueRef = useRef<IGradientValue>(value);
const cleanupRef = useRef<(() => void) | null>(null);
+ useEffect(() => {
+ valueRef.current = draftValue;
+ }, [draftValue]);
+
+ useEffect(() => {
+ setDraftValue(value);
+ }, [value]);
+
+ const emitChange = (nextValue: IGradientValue) => {
+ valueRef.current = nextValue;
+ setDraftValue(nextValue);
+ onChange?.(nextValue);
+ };
+
useEffect(() => {
setSelectedIndex((prev) => {
- if (prev >= value.stops.length) {
- return Math.max(0, value.stops.length - 1);
+ if (prev >= draftValue.stops.length) {
+ return Math.max(0, draftValue.stops.length - 1);
}
return prev;
});
- }, [value.stops.length]);
+ }, [draftValue.stops.length]);
useEffect(() => {
return () => {
@@ -75,28 +139,38 @@ export function GradientColorPicker(props: IGradientColorPickerProps) {
}, []);
const stops = useMemo(() => {
- return [...value.stops].sort((a, b) => a.offset - b.offset);
- }, [value.stops]);
+ return [...draftValue.stops].sort((a, b) => a.offset - b.offset);
+ }, [draftValue.stops]);
const handleTypeChange = (type: GradientType) => {
- onChange?.({ ...value, type });
+ emitChange({ ...valueRef.current, type });
};
const handleAngleChange = (angle: number | null) => {
- onChange?.({ ...value, angle: angle ?? 0 });
+ emitChange({ ...valueRef.current, angle: angle ?? 0 });
};
const handleStopColorChange = (color: string) => {
- const newStops = [...value.stops];
+ const newStops = [...valueRef.current.stops];
newStops[selectedIndex] = { ...newStops[selectedIndex], color };
- onChange?.({ ...value, stops: newStops });
+ emitChange({ ...valueRef.current, stops: newStops });
};
const handleStopOffsetChange = (offset: number | null) => {
if (offset === null) return;
- const newStops = [...value.stops];
+ const newStops = [...valueRef.current.stops];
newStops[selectedIndex] = { ...newStops[selectedIndex], offset };
- onChange?.({ ...value, stops: newStops });
+ emitChange({ ...valueRef.current, stops: newStops });
+ };
+
+ const handleStopTransparencyChange = (transparency: number | null) => {
+ const nextTransparency = clamp(transparency ?? 0, 0, 100);
+ const newStops = [...valueRef.current.stops];
+ newStops[selectedIndex] = {
+ ...newStops[selectedIndex],
+ opacity: (100 - nextTransparency) / 100,
+ };
+ emitChange({ ...valueRef.current, stops: newStops });
};
// const handleFlip = () => {
@@ -116,70 +190,160 @@ export function GradientColorPicker(props: IGradientColorPickerProps) {
const leftStop = [...stops].reverse().find((s) => s.offset <= offset) || stops[0];
// const rightStop = stops.find((s) => s.offset >= offset) || stops[stops.length - 1];
- const newStop = { color: leftStop.color, offset };
- const newStops = [...value.stops, newStop];
- onChange?.({ ...value, stops: newStops });
+ const newStop = { color: leftStop.color, offset, opacity: getStopOpacity(leftStop) };
+ const newStops = [...valueRef.current.stops, newStop];
+ emitChange({ ...valueRef.current, stops: newStops });
setSelectedIndex(newStops.length - 1);
};
const handleRemoveStop = () => {
- if (value.stops.length <= 2) return;
- const newStops = value.stops.filter((_, i) => i !== selectedIndex);
- onChange?.({ ...value, stops: newStops });
+ if (draftValue.stops.length <= 2) return;
+ const newStops = valueRef.current.stops.filter((_, i) => i !== selectedIndex);
+ emitChange({ ...valueRef.current, stops: newStops });
setSelectedIndex(0);
};
const gradientPreview = useMemo(() => {
- const stopsStr = stops.map((s) => `${s.color} ${s.offset}%`).join(', ');
+ const stopsStr = stops.map((s) => `${getStopColor(s)} ${s.offset}%`).join(', ');
return `linear-gradient(to right, ${stopsStr})`;
}, [stops]);
const mainPreview = useMemo(() => {
- const stopsStr = stops.map((s) => `${s.color} ${s.offset}%`).join(', ');
- switch (value.type) {
+ const stopsStr = stops.map((s) => `${getStopColor(s)} ${s.offset}%`).join(', ');
+ switch (draftValue.type) {
case 'linear':
- return `linear-gradient(${value.angle}deg, ${stopsStr})`;
+ return `linear-gradient(${getCssLinearGradientAngle(draftValue)}deg, ${stopsStr})`;
case 'radial':
return `radial-gradient(circle, ${stopsStr})`;
case 'angular':
- return `conic-gradient(from ${value.angle}deg, ${stopsStr})`;
+ return `conic-gradient(from ${getGradientAngle(draftValue)}deg, ${stopsStr})`;
case 'diamond':
// Diamond is tricky in CSS, using a placeholder or approximation
return `radial-gradient(circle, ${stopsStr})`;
default:
- return `linear-gradient(${value.angle}deg, ${stopsStr})`;
+ return `linear-gradient(${getCssLinearGradientAngle(draftValue)}deg, ${stopsStr})`;
}
- }, [value, stops]);
+ }, [draftValue, stops]);
+
+ const showAngleEditor = draftValue.type === 'linear' || draftValue.type === 'angular';
return (
<div
- className={clsx(`
- univer-flex univer-w-64 univer-flex-col univer-gap-4 univer-rounded-lg univer-bg-white univer-p-4
- univer-shadow-lg
- dark:!univer-bg-gray-800
- `, className)}
+ className={clsx(
+ compact
+ ? `
+ univer-flex univer-w-full univer-min-w-0 univer-flex-col univer-gap-3 univer-rounded-md
+ univer-bg-transparent univer-p-0
+ dark:!univer-bg-transparent
+ `
+ : `
+ univer-flex univer-w-full univer-min-w-0 univer-max-w-80 univer-flex-col univer-gap-4
+ univer-rounded-lg univer-bg-white univer-p-4 univer-shadow-lg
+ dark:!univer-bg-gray-800
+ `,
+ className
+ )}
+ onClick={(e) => e.stopPropagation()}
+ onPointerDown={(e) => e.stopPropagation()}
>
- <Segmented
- items={[
- { label: locale?.GradientColorPicker.linear, value: 'linear' },
- { label: locale?.GradientColorPicker.radial, value: 'radial' },
- { label: locale?.GradientColorPicker.angular, value: 'angular' },
- { label: locale?.GradientColorPicker.diamond, value: 'diamond' },
- ]}
- value={value.type}
- onChange={(v) => handleTypeChange(v as GradientType)}
- />
+ {compact
+ ? (
+ <div
+ className="
+ univer-flex univer-min-w-0 univer-items-center univer-gap-4 univer-border-b
+ univer-border-gray-100
+ dark:!univer-border-gray-700
+ "
+ >
+ {[
+ { label: locale?.GradientColorPicker.linear, value: 'linear' },
+ { label: locale?.GradientColorPicker.radial, value: 'radial' },
+ { label: locale?.GradientColorPicker.angular, value: 'angular' },
+ { label: locale?.GradientColorPicker.diamond, value: 'diamond' },
+ ].map((item) => {
+ const selected = draftValue.type === item.value;
+
+ return (
+ <button
+ key={item.value}
+ type="button"
+ className={clsx(
+ `
+ univer-relative univer-min-w-0 univer-flex-1 univer-cursor-pointer
+ univer-truncate univer-border-none univer-bg-transparent univer-px-0
+ univer-pb-2 univer-pt-0 univer-text-xs univer-transition-colors
+ `,
+ selected
+ ? `
+ univer-font-medium univer-text-primary-600
+ dark:!univer-text-primary-300
+ `
+ : `
+ univer-text-gray-500
+ hover:univer-text-gray-900
+ dark:hover:!univer-text-white
+ `
+ )}
+ onClick={() => handleTypeChange(item.value as GradientType)}
+ >
+ {item.label}
+ {selected && (
+ <span
+ className="
+ univer-absolute univer-inset-x-2 -univer-bottom-px univer-h-0.5
+ univer-rounded-full univer-bg-primary-600
+ dark:!univer-bg-primary-300
+ "
+ />
+ )}
+ </button>
+ );
+ })}
+ </div>
+ )
+ : (
+ <Segmented
+ className="univer-w-full univer-min-w-0 univer-gap-1 univer-overflow-hidden"
+ items={[
+ { label: locale?.GradientColorPicker.linear, value: 'linear' },
+ { label: locale?.GradientColorPicker.radial, value: 'radial' },
+ { label: locale?.GradientColorPicker.angular, value: 'angular' },
+ { label: locale?.GradientColorPicker.diamond, value: 'diamond' },
+ ]}
+ value={draftValue.type}
+ onChange={(v) => handleTypeChange(v as GradientType)}
+ />
+ )}
+
+ {showAngleEditor && (
+ <div
+ data-u-comp="gradient-color-picker-angle"
+ className="univer-flex univer-items-center univer-justify-between univer-gap-3"
+ >
+ <span className="univer-text-xs univer-text-gray-500">{locale?.GradientColorPicker.angle}</span>
+ <InputNumber
+ className="univer-w-24"
+ value={getGradientAngle(draftValue)}
+ min={0}
+ max={360}
+ onChange={handleAngleChange}
+ />
+ </div>
+ )}
<div
data-u-comp="gradient-color-picker-preview"
- className={`
- univer-h-32 univer-w-full univer-rounded-md univer-border univer-border-gray-200
- dark:!univer-border-gray-600
- `}
+ className={clsx(
+ `
+ univer-w-full univer-rounded-md univer-border univer-border-gray-200
+ dark:!univer-border-gray-600
+ `,
+ compact ? 'univer-h-20' : 'univer-h-32'
+ )}
style={{ background: mainPreview }}
/>
- <div className="univer-relative univer-mt-4 univer-h-6">
+ <div className={clsx('univer-relative univer-h-6', compact ? 'univer-mt-1' : 'univer-mt-4')}>
<div
ref={barRef}
data-u-comp="gradient-color-picker-bar"
@@ -190,7 +354,7 @@ export function GradientColorPicker(props: IGradientColorPickerProps) {
style={{ background: gradientPreview }}
onClick={handleAddStop}
/>
- {value.stops.map((stop, index) => (
+ {draftValue.stops.map((stop, index) => (
<div
key={index}
data-u-comp="gradient-color-picker-stop"
@@ -205,26 +369,30 @@ export function GradientColorPicker(props: IGradientColorPickerProps) {
)}
style={{
left: `${stop.offset}%`,
- backgroundColor: stop.color,
+ backgroundColor: getStopColor(stop),
}}
onClick={(e) => {
e.stopPropagation();
setSelectedIndex(index);
}}
onPointerDown={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
const startX = e.clientX;
const startOffset = stop.offset;
+ setSelectedIndex(index);
const handlePointerMove = (moveEvent: PointerEvent) => {
if (!barRef.current) return;
+ moveEvent.preventDefault();
const rect = barRef.current.getBoundingClientRect();
const deltaX = moveEvent.clientX - startX;
const deltaOffset = (deltaX / rect.width) * 100;
const newOffset = Math.max(0, Math.min(100, Math.round(startOffset + deltaOffset)));
- const newStops = [...value.stops];
+ const newStops = [...valueRef.current.stops];
newStops[index] = { ...newStops[index], offset: newOffset };
- onChange?.({ ...value, stops: newStops });
+ emitChange({ ...valueRef.current, stops: newStops });
};
const handlePointerUp = () => {
@@ -243,32 +411,35 @@ export function GradientColorPicker(props: IGradientColorPickerProps) {
<div className="univer-flex univer-items-end univer-gap-2">
<div className="univer-flex-1">
- <div className="univer-mb-1 univer-text-xs univer-text-gray-500">{locale?.GradientColorPicker.offset}</div>
+ <div className="univer-mb-0.5 univer-text-xs univer-text-gray-500">{locale?.GradientColorPicker.offset}</div>
<InputNumber
- value={value.stops[selectedIndex]?.offset}
+ value={draftValue.stops[selectedIndex]?.offset}
min={0}
max={100}
onChange={handleStopOffsetChange}
/>
</div>
- {(value.type === 'linear' || value.type === 'angular') && (
- <div className="univer-flex-1">
- <div className="univer-mb-1 univer-text-xs univer-text-gray-500">{locale?.GradientColorPicker.angle}</div>
- <InputNumber
- value={value.angle}
- min={0}
- max={360}
- onChange={handleAngleChange}
- />
+ <div className="univer-flex-1">
+ <div className="univer-mb-0.5 univer-text-xs univer-text-gray-500">
+ {locale?.GradientColorPicker.transparency ?? 'Transparency'}
</div>
- )}
+ <InputNumber
+ value={Math.round((1 - getStopOpacity(draftValue.stops[selectedIndex])) * 100)}
+ min={0}
+ max={100}
+ step={10}
+ formatter={(v) => `${v}%`}
+ parser={(v) => v?.replace(/%/g, '') || ''}
+ onChange={handleStopTransparencyChange}
+ />
+ </div>
<div className="univer-flex univer-gap-1">
<Tooltip title={locale?.GradientColorPicker.delete}>
<Button
data-u-comp="gradient-color-picker-delete"
variant="danger"
onClick={handleRemoveStop}
- disabled={value.stops.length <= 2}
+ disabled={draftValue.stops.length <= 2}
>
<DeleteIcon />
</Button>
@@ -277,13 +448,16 @@ export function GradientColorPicker(props: IGradientColorPickerProps) {
</div>
<div
- className={`
- univer-border-t univer-border-gray-100 univer-pt-4
- dark:!univer-border-gray-700
- `}
+ className={clsx(
+ `
+ univer-border-t univer-border-gray-100
+ dark:!univer-border-gray-700
+ `,
+ compact ? 'univer-pt-3' : 'univer-pt-4'
+ )}
>
<ColorPicker
- value={value.stops[selectedIndex]?.color}
+ value={draftValue.stops[selectedIndex]?.color}
onChange={handleStopColorChange}
/>
</div>
diff --git a/packages/design/src/components/gradient-color-picker/__tests__/index.spec.tsx b/packages/design/src/components/gradient-color-picker/__tests__/index.spec.tsx
index 8ed246aaed..11658f4a20 100644
--- a/packages/design/src/components/gradient-color-picker/__tests__/index.spec.tsx
+++ b/packages/design/src/components/gradient-color-picker/__tests__/index.spec.tsx
@@ -32,7 +32,7 @@ const defaultValue: IGradientValue = {
{ color: '#ffffff', offset: 0 },
{ color: '#000000', offset: 100 },
],
- angle: 90,
+ angle: 0,
};
describe('GradientColorPicker', () => {
@@ -65,7 +65,7 @@ describe('GradientColorPicker', () => {
const { container } = render(<GradientColorPicker value={defaultValue} onChange={onChange} />);
const inputs = container.querySelectorAll('input');
- const offsetInput = inputs[0]; // First input is offset
+ const offsetInput = inputs[1]; // Second input is offset
fireEvent.change(offsetInput, { target: { value: '50' } });
@@ -81,7 +81,7 @@ describe('GradientColorPicker', () => {
const { container } = render(<GradientColorPicker value={defaultValue} onChange={onChange} />);
const inputs = container.querySelectorAll('input');
- const angleInput = inputs[1]; // Second input is angle for linear
+ const angleInput = inputs[0]; // First input is angle for linear
fireEvent.change(angleInput, { target: { value: '180' } });
@@ -90,6 +90,22 @@ describe('GradientColorPicker', () => {
}));
});
+ it('should call onChange when stop transparency changes', () => {
+ const onChange = vi.fn();
+ const { container } = render(<GradientColorPicker value={defaultValue} onChange={onChange} />);
+
+ const inputs = container.querySelectorAll('input');
+ const transparencyInput = inputs[2]; // Third input is stop transparency for linear
+
+ fireEvent.change(transparencyInput, { target: { value: '40' } });
+
+ expect(onChange).toHaveBeenCalledWith(expect.objectContaining({
+ stops: expect.arrayContaining([
+ expect.objectContaining({ opacity: 0.6 }),
+ ]),
+ }));
+ });
+
it('should select stop when clicked', () => {
const { container } = render(<GradientColorPicker value={defaultValue} />);
const stops = container.querySelectorAll('[data-u-comp="gradient-color-picker-stop"]');
@@ -161,7 +177,7 @@ describe('GradientColorPicker', () => {
const onChange = vi.fn();
const { container } = render(<GradientColorPicker value={defaultValue} onChange={onChange} />);
const inputs = container.querySelectorAll('input');
- const offsetInput = inputs[0] as HTMLInputElement;
+ const offsetInput = inputs[1] as HTMLInputElement;
fireEvent.change(offsetInput, { target: { value: '' } });
expect(onChange).not.toHaveBeenCalled();
diff --git a/packages/design/src/components/input-number/InputNumber.tsx b/packages/design/src/components/input-number/InputNumber.tsx
index e440ce1532..1975bf9a4f 100644
--- a/packages/design/src/components/input-number/InputNumber.tsx
+++ b/packages/design/src/components/input-number/InputNumber.tsx
@@ -133,7 +133,7 @@ export const InputNumber = forwardRef<HTMLInputElement, IInputNumberProps>(
return String(formattedValue);
}
- function parseValue(val: string): number | null {
+ function parseNumberValue(val: string): number | null {
if (!val) return null;
let parsedValue = val;
@@ -178,29 +178,42 @@ export const InputNumber = forwardRef<HTMLInputElement, IInputNumberProps>(
}
}
- if (max !== undefined && result > max) {
- result = max;
- }
- if (min !== undefined && result < min) {
- result = min;
- }
-
return result;
} catch (e) {
return null;
}
}
- function handleInputChange(value: string) {
- setInputValue(value);
+ function clampValue(val: number | null): number | null {
+ if (val === null) return null;
+
+ if (max !== undefined && val > max) {
+ return max;
+ }
+ if (min !== undefined && val < min) {
+ return min;
+ }
+ return val;
+ }
+
+ function parseValue(val: string): number | null {
+ return clampValue(parseNumberValue(val));
+ }
+
+ function handleInputChange(value: string) {
if (allowEmpty && value === '') {
+ setInputValue(value);
setInternalValue(null);
onChange?.(null);
return;
}
- const parsedValue = parseValue(value);
+ const parsedNumber = parseNumberValue(value);
+ const parsedValue = clampValue(parsedNumber);
+ const isOutOfRange = parsedNumber !== null && parsedValue !== parsedNumber;
+
+ setInputValue(isOutOfRange ? formatValue(parsedValue) : value);
setInternalValue(parsedValue);
onChange?.(parsedValue);
diff --git a/packages/design/src/components/input-number/__tests__/index.spec.tsx b/packages/design/src/components/input-number/__tests__/index.spec.tsx
index 3f143cf2e4..faef50f6a0 100644
--- a/packages/design/src/components/input-number/__tests__/index.spec.tsx
+++ b/packages/design/src/components/input-number/__tests__/index.spec.tsx
@@ -219,9 +219,11 @@ describe('InputNumber', () => {
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', () => {
diff --git a/packages/design/src/components/segmented/Segmented.tsx b/packages/design/src/components/segmented/Segmented.tsx
index 72d9b3edaf..1d986b15ad 100644
--- a/packages/design/src/components/segmented/Segmented.tsx
+++ b/packages/design/src/components/segmented/Segmented.tsx
@@ -100,7 +100,8 @@ export function Segmented<T extends ItemValue = ItemValue>({
data-u-comp="segmented"
ref={containerRef}
className={clsx(`
- univer-relative univer-box-border univer-flex univer-gap-4 univer-rounded-lg univer-bg-gray-100 univer-p-1
+ univer-relative univer-box-border univer-flex univer-min-w-0 univer-gap-1 univer-rounded-lg
+ univer-bg-gray-100 univer-p-1
dark:!univer-bg-gray-800
`, className)}
>
@@ -120,9 +121,9 @@ export function Segmented<T extends ItemValue = ItemValue>({
if (el) itemRefs.current.set(item.value, el);
}}
className={clsx(`
- univer-relative univer-box-border univer-flex-1 univer-cursor-pointer univer-border-none
- univer-bg-transparent univer-px-3 univer-py-1 univer-text-xs univer-font-medium
- univer-transition-colors
+ univer-relative univer-box-border univer-min-w-0 univer-flex-1 univer-cursor-pointer
+ univer-truncate univer-border-none univer-bg-transparent univer-px-3 univer-py-1 univer-text-xs
+ univer-font-medium univer-transition-colors
`, {
'univer-text-gray-900 dark:!univer-text-white': selectedItem === item.value,
'univer-text-gray-500 hover:univer-text-gray-900 dark:hover:!univer-text-white': selectedItem !== item.value,
diff --git a/packages/design/src/locale/ar-SA.ts b/packages/design/src/locale/ar-SA.ts
index 65479d4324..ad0b10231a 100644
--- a/packages/design/src/locale/ar-SA.ts
+++ b/packages/design/src/locale/ar-SA.ts
@@ -60,6 +60,7 @@ const locale: typeof enUS = {
angle: 'زاوية',
flip: 'قلب',
delete: 'حذف',
+ transparency: 'Transparency',
},
},
};
diff --git a/packages/design/src/locale/ca-ES.ts b/packages/design/src/locale/ca-ES.ts
index dbd4551524..5afb3f266a 100644
--- a/packages/design/src/locale/ca-ES.ts
+++ b/packages/design/src/locale/ca-ES.ts
@@ -60,6 +60,7 @@ const locale: typeof enUS = {
angle: 'Angle',
flip: 'Girar',
delete: 'Eliminar',
+ transparency: 'Transparency',
},
},
};
diff --git a/packages/design/src/locale/de-DE.ts b/packages/design/src/locale/de-DE.ts
index e7bf006bbb..924f44791a 100644
--- a/packages/design/src/locale/de-DE.ts
+++ b/packages/design/src/locale/de-DE.ts
@@ -60,6 +60,7 @@ const locale: typeof enUS = {
angle: 'Winkel',
flip: 'Umkehren',
delete: 'Löschen',
+ transparency: 'Transparency',
},
},
};
diff --git a/packages/design/src/locale/en-US.ts b/packages/design/src/locale/en-US.ts
index 08b21db067..81a9162885 100644
--- a/packages/design/src/locale/en-US.ts
+++ b/packages/design/src/locale/en-US.ts
@@ -58,6 +58,7 @@ const locale = {
angle: 'Angle',
flip: 'Flip',
delete: 'Delete',
+ transparency: 'Transparency',
},
},
};
diff --git a/packages/design/src/locale/es-ES.ts b/packages/design/src/locale/es-ES.ts
index 1ac78c4e96..f4b4289f86 100644
--- a/packages/design/src/locale/es-ES.ts
+++ b/packages/design/src/locale/es-ES.ts
@@ -60,6 +60,7 @@ const locale: typeof enUS = {
angle: 'Angle',
flip: 'Girar',
delete: 'Eliminar',
+ transparency: 'Transparency',
},
},
};
diff --git a/packages/design/src/locale/fa-IR.ts b/packages/design/src/locale/fa-IR.ts
index 3466896c9c..d089409f56 100644
--- a/packages/design/src/locale/fa-IR.ts
+++ b/packages/design/src/locale/fa-IR.ts
@@ -60,6 +60,7 @@ const locale: typeof enUS = {
angle: 'زاویه',
flip: 'برگردان',
delete: 'حذف',
+ transparency: 'Transparency',
},
},
};
diff --git a/packages/design/src/locale/fr-FR.ts b/packages/design/src/locale/fr-FR.ts
index 40cfe2f511..4abb551737 100644
--- a/packages/design/src/locale/fr-FR.ts
+++ b/packages/design/src/locale/fr-FR.ts
@@ -60,6 +60,7 @@ const locale: typeof enUS = {
angle: 'Angle',
flip: 'Retourner',
delete: 'Supprimer',
+ transparency: 'Transparency',
},
},
};
diff --git a/packages/design/src/locale/id-ID.ts b/packages/design/src/locale/id-ID.ts
index 2ec776a456..c35cac8805 100644
--- a/packages/design/src/locale/id-ID.ts
+++ b/packages/design/src/locale/id-ID.ts
@@ -60,6 +60,7 @@ const locale: typeof enUS = {
angle: 'Sudut',
flip: 'Balik',
delete: 'Hapus',
+ transparency: 'Transparency',
},
},
};
diff --git a/packages/design/src/locale/it-IT.ts b/packages/design/src/locale/it-IT.ts
index 262b8b11c2..4aae4f24b8 100644
--- a/packages/design/src/locale/it-IT.ts
+++ b/packages/design/src/locale/it-IT.ts
@@ -60,6 +60,7 @@ const locale: typeof enUS = {
angle: 'Angolo',
flip: 'Capovolgi',
delete: 'Elimina',
+ transparency: 'Transparency',
},
},
};
diff --git a/packages/design/src/locale/ja-JP.ts b/packages/design/src/locale/ja-JP.ts
index 57b4f38a8e..6d95c02aa0 100644
--- a/packages/design/src/locale/ja-JP.ts
+++ b/packages/design/src/locale/ja-JP.ts
@@ -60,6 +60,7 @@ const locale: typeof enUS = {
angle: '角度',
flip: '反転',
delete: '削除',
+ transparency: 'Transparency',
},
},
};
diff --git a/packages/design/src/locale/ko-KR.ts b/packages/design/src/locale/ko-KR.ts
index 7f9b84a2da..ff1039e986 100644
--- a/packages/design/src/locale/ko-KR.ts
+++ b/packages/design/src/locale/ko-KR.ts
@@ -60,6 +60,7 @@ const locale: typeof enUS = {
angle: '각도',
flip: '뒤집기',
delete: '삭제',
+ transparency: 'Transparency',
},
},
};
diff --git a/packages/design/src/locale/pl-PL.ts b/packages/design/src/locale/pl-PL.ts
index 913509af96..159adbe4e0 100644
--- a/packages/design/src/locale/pl-PL.ts
+++ b/packages/design/src/locale/pl-PL.ts
@@ -60,6 +60,7 @@ const locale: typeof enUS = {
angle: 'Kąt',
flip: 'Obrót',
delete: 'Usuń',
+ transparency: 'Transparency',
},
},
};
diff --git a/packages/design/src/locale/pt-BR.ts b/packages/design/src/locale/pt-BR.ts
index 999854a5b3..fd0904d162 100644
--- a/packages/design/src/locale/pt-BR.ts
+++ b/packages/design/src/locale/pt-BR.ts
@@ -60,6 +60,7 @@ const locale: typeof enUS = {
angle: 'Ângulo',
flip: 'Inverter',
delete: 'Excluir',
+ transparency: 'Transparency',
},
},
};
diff --git a/packages/design/src/locale/ru-RU.ts b/packages/design/src/locale/ru-RU.ts
index ab9869ff68..555556f1dc 100644
--- a/packages/design/src/locale/ru-RU.ts
+++ b/packages/design/src/locale/ru-RU.ts
@@ -60,6 +60,7 @@ const locale: typeof enUS = {
angle: 'угол',
flip: 'перевернуть',
delete: 'удалить',
+ transparency: 'Transparency',
},
},
};
diff --git a/packages/design/src/locale/sk-SK.ts b/packages/design/src/locale/sk-SK.ts
index ca3d5246cb..80638f278f 100644
--- a/packages/design/src/locale/sk-SK.ts
+++ b/packages/design/src/locale/sk-SK.ts
@@ -60,6 +60,7 @@ const locale: typeof enUS = {
angle: 'Uhol',
flip: 'Prevrátiť',
delete: 'Odstrániť',
+ transparency: 'Transparency',
},
},
};
diff --git a/packages/design/src/locale/vi-VN.ts b/packages/design/src/locale/vi-VN.ts
index 5912d1d404..685d50b94e 100644
--- a/packages/design/src/locale/vi-VN.ts
+++ b/packages/design/src/locale/vi-VN.ts
@@ -60,6 +60,7 @@ const locale: typeof enUS = {
angle: 'Góc',
flip: 'Lật',
delete: 'Xóa',
+ transparency: 'Transparency',
},
},
};
diff --git a/packages/design/src/locale/zh-CN.ts b/packages/design/src/locale/zh-CN.ts
index fcbd8c2df8..3f65b8b497 100644
--- a/packages/design/src/locale/zh-CN.ts
+++ b/packages/design/src/locale/zh-CN.ts
@@ -60,6 +60,7 @@ const locale: typeof enUS = {
angle: '角度',
flip: '翻转',
delete: '删除',
+ transparency: '透明度',
},
},
};
diff --git a/packages/design/src/locale/zh-HK.ts b/packages/design/src/locale/zh-HK.ts
index c27befcefc..e3c8a88e0c 100644
--- a/packages/design/src/locale/zh-HK.ts
+++ b/packages/design/src/locale/zh-HK.ts
@@ -60,6 +60,7 @@ const locale: typeof enUS = {
angle: '角度',
flip: '翻轉',
delete: '刪除',
+ transparency: '透明度',
},
},
};
diff --git a/packages/design/src/locale/zh-TW.ts b/packages/design/src/locale/zh-TW.ts
index c27befcefc..e3c8a88e0c 100644
--- a/packages/design/src/locale/zh-TW.ts
+++ b/packages/design/src/locale/zh-TW.ts
@@ -60,6 +60,7 @@ const locale: typeof enUS = {
angle: '角度',
flip: '翻轉',
delete: '刪除',
+ transparency: '透明度',
},
},
};
diff --git a/packages/docs-ui/src/commands/commands/inline-format.command.ts b/packages/docs-ui/src/commands/commands/inline-format.command.ts
index 80b263248d..ed5903f029 100644
--- a/packages/docs-ui/src/commands/commands/inline-format.command.ts
+++ b/packages/docs-ui/src/commands/commands/inline-format.command.ts
@@ -60,7 +60,7 @@ function handleInlineFormat(
export interface ISetInlineFormatCommandParams {
preCommandId: string;
- value?: string;
+ value?: string | Partial<ITextStyle> | null;
}
const SetInlineFormatBoldCommandId = 'doc.command.set-inline-format-bold';
@@ -198,6 +198,21 @@ export const SetInlineFormatTextColorCommand: ICommand = {
},
};
+const SetInlineFormatTextFillCommandId = 'doc.command.set-inline-format-text-fill';
+export const SetInlineFormatTextFillCommand: ICommand = {
+ id: SetInlineFormatTextFillCommandId,
+ type: CommandType.COMMAND,
+ handler: async (accessor, params) => {
+ const commandService = accessor.get(ICommandService);
+
+ return handleInlineFormat(
+ SetInlineFormatTextFillCommandId,
+ params,
+ commandService
+ );
+ },
+};
+
const SetInlineFormatTextBackgroundColorCommandId = 'doc.command.set-inline-format-text-background-color';
export const SetInlineFormatTextBackgroundColorCommand: ICommand = {
id: SetInlineFormatTextBackgroundColorCommandId,
@@ -279,6 +294,7 @@ export const SetInlineFormatCommand: ICommand<ISetInlineFormatCommandParams> = {
const unitId = docDataModel.getUnitId();
let formatValue;
+ let formatPatch: Partial<ITextStyle> | undefined;
switch (preCommandId) {
case SetInlineFormatBoldCommand.id: // fallthrough
@@ -316,6 +332,11 @@ export const SetInlineFormatCommand: ICommand<ISetInlineFormatCommandParams> = {
break;
}
+ case SetInlineFormatTextFillCommand.id: {
+ formatPatch = value as Partial<ITextStyle>;
+ break;
+ }
+
case ResetInlineFormatTextBackgroundColorCommand.id: {
formatValue = {
rgb: null,
@@ -360,17 +381,21 @@ export const SetInlineFormatCommand: ICommand<ISetInlineFormatCommandParams> = {
const cacheStyle = docMenuStyleService.getStyleCache();
const key = COMMAND_ID_TO_FORMAT_KEY_MAP[preCommandId];
- docMenuStyleService.setStyleCache(
- {
- [key]: cacheStyle?.[key] !== undefined && isNeedReverseValue(key)
- ? getReverseFormatValue(
- cacheStyle,
- key,
- preCommandId
- )
- : formatValue,
- }
- );
+ if (formatPatch) {
+ docMenuStyleService.setStyleCache(formatPatch);
+ } else {
+ docMenuStyleService.setStyleCache(
+ {
+ [key]: cacheStyle?.[key] !== undefined && isNeedReverseValue(key)
+ ? getReverseFormatValue(
+ cacheStyle,
+ key,
+ preCommandId
+ )
+ : formatValue,
+ }
+ );
+ }
continue;
}
@@ -380,7 +405,7 @@ export const SetInlineFormatCommand: ICommand<ISetInlineFormatCommandParams> = {
{
st: 0,
ed: endOffset - startOffset,
- ts: {
+ ts: formatPatch ?? {
[COMMAND_ID_TO_FORMAT_KEY_MAP[preCommandId]]: formatValue,
},
},
@@ -492,6 +517,7 @@ export function getStyleInTextRange(
style.st = textRuns.length && textRuns.every((t) => t.ts?.st?.s === BooleanNumber.TRUE) ? textRuns[0].ts?.st : style.st;
style.bg = textRuns.find((t) => t.ts?.bg != null)?.ts?.bg ?? style.bg;
style.cl = textRuns.find((t) => t.ts?.cl != null)?.ts?.cl ?? style.cl;
+ style.textFill = textRuns.find((t) => t.ts?.textFill != null)?.ts?.textFill ?? style.textFill;
const vas = textRuns.filter((t) => t?.ts?.va != null);
diff --git a/packages/docs-ui/src/index.ts b/packages/docs-ui/src/index.ts
index ed64a73c7b..4abc9745a9 100644
--- a/packages/docs-ui/src/index.ts
+++ b/packages/docs-ui/src/index.ts
@@ -57,7 +57,9 @@ export {
SetInlineFormatSuperscriptCommand,
SetInlineFormatTextBackgroundColorCommand,
SetInlineFormatTextColorCommand,
+ SetInlineFormatTextFillCommand,
SetInlineFormatUnderlineCommand,
+ getStyleInTextRange,
} from './commands/commands/inline-format.command';
export { type IInsertCustomRangeCommandParams, InsertCustomRangeCommand } from './commands/commands/insert-custom-range.command';
export {
diff --git a/packages/docs-ui/src/plugin.ts b/packages/docs-ui/src/plugin.ts
index 48587c3721..7eed42fb9f 100644
--- a/packages/docs-ui/src/plugin.ts
+++ b/packages/docs-ui/src/plugin.ts
@@ -59,6 +59,7 @@ import {
SetInlineFormatSuperscriptCommand,
SetInlineFormatTextBackgroundColorCommand,
SetInlineFormatTextColorCommand,
+ SetInlineFormatTextFillCommand,
SetInlineFormatUnderlineCommand,
} from './commands/commands/inline-format.command';
import { InsertCustomRangeCommand } from './commands/commands/insert-custom-range.command';
@@ -215,6 +216,7 @@ export class UniverDocsUIPlugin extends Plugin {
SetInlineFormatFontSizeCommand,
SetInlineFormatFontFamilyCommand,
SetInlineFormatTextColorCommand,
+ SetInlineFormatTextFillCommand,
ResetInlineFormatTextBackgroundColorCommand,
SetInlineFormatTextBackgroundColorCommand,
SetInlineFormatCommand,
diff --git a/packages/engine-render/src/components/docs/extensions/font-and-base-line.ts b/packages/engine-render/src/components/docs/extensions/font-and-base-line.ts
index 42c202cbca..8386f707e2 100644
--- a/packages/engine-render/src/components/docs/extensions/font-and-base-line.ts
+++ b/packages/engine-render/src/components/docs/extensions/font-and-base-line.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IScale } from '@univerjs/core';
+import type { IDocTextFill, IDocTextFillGradientStop, IScale } from '@univerjs/core';
import type { IBoundRectNoAngle } from '../../../basics';
import type { IDocumentSkeletonGlyph } from '../../../basics/i-document-skeleton-cached';
import type { UniverRenderingContext } from '../../../context';
@@ -48,6 +48,8 @@ export class FontAndBaseLine extends docExtension {
*/
actualFontMap: Record<string, string> = {};
+ private _textFillImageCache = new Map<string, HTMLImageElement>();
+
constructor() {
super();
}
@@ -92,21 +94,255 @@ export class FontAndBaseLine extends docExtension {
}
}
- const { cl: colorStyle, va: baselineOffset } = textStyle;
+ const { cl: colorStyle, va: baselineOffset, textFill } = textStyle;
const fontColor = getColorStyle(colorStyle) || COLOR_BLACK_RGB;
- if (fontColor && this._preFontColor !== fontColor) {
- ctx.fillStyle = fontColor;
- }
-
if (baselineOffset === BaselineOffset.SUPERSCRIPT) {
spanPointWithFont.y += -bBox.spo;
} else if (baselineOffset === BaselineOffset.SUBSCRIPT) {
spanPointWithFont.y += bBox.sbo;
}
+
+ if (this._fillTextWithTextFill(ctx, glyph, spanPointWithFont, textFill, fontColor)) {
+ return;
+ }
+
+ if (fontColor && this._preFontColor !== fontColor) {
+ ctx.fillStyle = fontColor;
+ }
+
this._fillText(ctx, glyph, spanPointWithFont);
}
+ private _fillTextWithTextFill(
+ ctx: UniverRenderingContext,
+ glyph: IDocumentSkeletonGlyph,
+ spanPointWithFont: Vector2,
+ textFill: IDocTextFill | undefined,
+ fallbackColor: string
+ ): boolean {
+ if (!textFill || textFill.type === 'none') {
+ return textFill?.type === 'none';
+ }
+
+ const { content, glyphType } = glyph;
+ if (content == null || glyphType === GlyphType.LIST) {
+ return false;
+ }
+
+ const { renderConfig } = this.extensionOffset;
+ const { vertexAngle, centerAngle } = renderConfig ?? {};
+ const VERTICAL_DEG = 90;
+ if (vertexAngle === VERTICAL_DEG && centerAngle === VERTICAL_DEG) {
+ return false;
+ }
+
+ const bounds = this._getGlyphPaintBounds(glyph, spanPointWithFont);
+ if (bounds.width <= 0 || bounds.height <= 0) {
+ return false;
+ }
+
+ const color = this._colorWithOpacity(textFill.color || fallbackColor, textFill.opacity);
+
+ if (textFill.type === 'solid') {
+ ctx.fillStyle = color;
+ this._fillText(ctx, glyph, spanPointWithFont);
+ return true;
+ }
+
+ if (textFill.type === 'gradient') {
+ const gradient = this._createTextGradient(ctx, bounds, textFill, fallbackColor);
+ if (!gradient) {
+ return false;
+ }
+
+ ctx.fillStyle = gradient;
+ this._fillText(ctx, glyph, spanPointWithFont);
+ return true;
+ }
+
+ if (textFill.type === 'picture') {
+ const pattern = this._createTextPicturePattern(ctx, bounds, textFill);
+ if (!pattern) {
+ return false;
+ }
+
+ ctx.fillStyle = pattern;
+ this._fillText(ctx, glyph, spanPointWithFont);
+ return true;
+ }
+
+ return false;
+ }
+
+ private _getGlyphPaintBounds(glyph: IDocumentSkeletonGlyph, spanPointWithFont: Vector2) {
+ const { width, bBox } = glyph;
+ const textWidth = Math.max(width, bBox.width, 1);
+ const textHeight = Math.max(bBox.aba + bBox.abd, 1);
+
+ return {
+ left: spanPointWithFont.x,
+ top: spanPointWithFont.y - bBox.aba,
+ width: textWidth,
+ height: textHeight,
+ };
+ }
+
+ private _createTextGradient(
+ ctx: UniverRenderingContext,
+ bounds: { left: number; top: number; width: number; height: number },
+ textFill: IDocTextFill,
+ fallbackColor: string
+ ): CanvasGradient | null {
+ const gradient = textFill.gradient;
+ const type = gradient?.type ?? 'linear';
+ const angle = gradient?.angle ?? 0;
+ const stops = this._normalizeGradientStops(gradient?.stops, textFill.color || fallbackColor);
+ const centerX = bounds.left + bounds.width / 2;
+ const centerY = bounds.top + bounds.height / 2;
+ let canvasGradient: CanvasGradient;
+
+ if (type === 'radial') {
+ const radius = Math.max(bounds.width, bounds.height) / 2;
+ canvasGradient = ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, radius);
+ } else if (type === 'angular' && 'createConicGradient' in ((ctx as unknown as { _context?: CanvasRenderingContext2D })._context ?? ctx)) {
+ const rawContext = ((ctx as unknown as { _context?: CanvasRenderingContext2D })._context ?? ctx) as CanvasRenderingContext2D & {
+ createConicGradient: (startAngle: number, x: number, y: number) => CanvasGradient;
+ };
+ canvasGradient = rawContext.createConicGradient(((angle - 90) * Math.PI) / 180, centerX, centerY);
+ } else if (type === 'diamond') {
+ const radius = Math.max(bounds.width, bounds.height) / 2;
+ canvasGradient = ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, radius);
+ } else {
+ const line = this._getLinearGradientLine(bounds, angle);
+ canvasGradient = ctx.createLinearGradient(line.x0, line.y0, line.x1, line.y1);
+ }
+
+ for (const stop of stops) {
+ const opacity = (textFill.opacity ?? 1) * (stop.opacity ?? 1);
+ canvasGradient.addColorStop(stop.offset, this._colorWithOpacity(stop.color, opacity));
+ }
+
+ return canvasGradient;
+ }
+
+ private _createTextPicturePattern(
+ ctx: UniverRenderingContext,
+ bounds: { left: number; top: number; width: number; height: number },
+ textFill: IDocTextFill
+ ): CanvasPattern | null {
+ const source = textFill.picture?.source;
+ if (!source) {
+ return null;
+ }
+
+ const image = this._getTextFillImage(source);
+ if (!image || !image.complete || !(image.naturalWidth || image.width)) {
+ return null;
+ }
+
+ const canvas = document.createElement('canvas');
+ canvas.width = Math.max(1, Math.ceil(bounds.width));
+ canvas.height = Math.max(1, Math.ceil(bounds.height));
+ const canvasContext = canvas.getContext('2d');
+ if (!canvasContext) {
+ return null;
+ }
+
+ const opacity = this._clamp(textFill.picture?.opacity ?? textFill.opacity ?? 1, 0, 1);
+ canvasContext.globalAlpha = opacity;
+
+ if (textFill.picture?.mode === 'tile') {
+ const scaleX = textFill.picture.scaleX ?? 1;
+ const scaleY = textFill.picture.scaleY ?? 1;
+ const cellWidth = Math.max(1, (image.naturalWidth || image.width) * scaleX);
+ const cellHeight = Math.max(1, (image.naturalHeight || image.height) * scaleY);
+ const offsetX = textFill.picture.offsetX ?? 0;
+ const offsetY = textFill.picture.offsetY ?? 0;
+
+ for (let x = ((offsetX % cellWidth) + cellWidth) % cellWidth - cellWidth; x < canvas.width; x += cellWidth) {
+ for (let y = ((offsetY % cellHeight) + cellHeight) % cellHeight - cellHeight; y < canvas.height; y += cellHeight) {
+ canvasContext.drawImage(image, x, y, cellWidth, cellHeight);
+ }
+ }
+ } else {
+ canvasContext.drawImage(image, 0, 0, canvas.width, canvas.height);
+ }
+
+ const pattern = ctx.createPattern(canvas, 'no-repeat');
+ pattern?.setTransform?.(new DOMMatrix().translate(bounds.left, bounds.top));
+
+ return pattern;
+ }
+
+ private _getTextFillImage(source: string): HTMLImageElement | null {
+ const cached = this._textFillImageCache.get(source);
+ if (cached) {
+ return cached;
+ }
+
+ const image = new Image();
+ image.crossOrigin = 'anonymous';
+ image.src = source;
+ this._textFillImageCache.set(source, image);
+
+ return image.complete ? image : null;
+ }
+
+ private _normalizeGradientStops(stops: IDocTextFillGradientStop[] | undefined, fallbackColor: string) {
+ const normalizedStops = stops && stops.length >= 2
+ ? stops
+ : [
+ { offset: 0, color: fallbackColor },
+ { offset: 100, color: '#ffffff' },
+ ];
+
+ return normalizedStops.map((stop) => ({
+ color: stop.color,
+ offset: this._clamp(stop.offset > 1 ? stop.offset / 100 : stop.offset, 0, 1),
+ opacity: stop.opacity,
+ }));
+ }
+
+ private _getLinearGradientLine(bounds: { left: number; top: number; width: number; height: number }, angle: number) {
+ const angleRad = (angle * Math.PI) / 180;
+ const centerX = bounds.left + bounds.width / 2;
+ const centerY = bounds.top + bounds.height / 2;
+ const cos = Math.cos(angleRad);
+ const sin = Math.sin(angleRad);
+ const halfDiagonal = (Math.abs(bounds.width * cos) + Math.abs(bounds.height * sin)) / 2;
+
+ return {
+ x0: centerX - cos * halfDiagonal,
+ y0: centerY - sin * halfDiagonal,
+ x1: centerX + cos * halfDiagonal,
+ y1: centerY + sin * halfDiagonal,
+ };
+ }
+
+ private _colorWithOpacity(color: string, opacity?: number): string {
+ if (opacity === undefined || opacity >= 1) {
+ return color;
+ }
+
+ const alpha = this._clamp(opacity, 0, 1);
+ const hex = color.trim();
+ if (/^#[0-9a-f]{3}$/i.test(hex)) {
+ const [, r, g, b] = hex;
+ return `rgba(${Number.parseInt(r + r, 16)}, ${Number.parseInt(g + g, 16)}, ${Number.parseInt(b + b, 16)}, ${alpha})`;
+ }
+
+ if (/^#[0-9a-f]{6}$/i.test(hex)) {
+ return `rgba(${Number.parseInt(hex.slice(1, 3), 16)}, ${Number.parseInt(hex.slice(3, 5), 16)}, ${Number.parseInt(hex.slice(5, 7), 16)}, ${alpha})`;
+ }
+
+ return color;
+ }
+
+ private _clamp(value: number, min: number, max: number): number {
+ return Math.max(min, Math.min(max, value));
+ }
+
private _fillText(ctx: UniverRenderingContext, glyph: IDocumentSkeletonGlyph, spanPointWithFont: Vector2) {
const { renderConfig, spanStartPoint, centerPoint } = this.extensionOffset;
const { content, width, bBox } = glyph;