Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

feat: Gradient picker improvements (#5460)

Oleg Isonen725d4597da06
diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-gradient.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-gradient.tsx
index f6cf85664b..16c6252bc6 100644
--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-gradient.tsx
+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-gradient.tsx
@@ -4,9 +4,6 @@ import {
type UnitValue,
} from "@webstudio-is/css-engine";
import {
- parseLinearGradient,
- parseConicGradient,
- parseRadialGradient,
type ParsedGradient,
type ParsedLinearGradient,
type ParsedConicGradient,
@@ -45,7 +42,6 @@ import {
RepeatGridIcon,
XSmallIcon,
} from "@webstudio-is/icons";
-import { clamp } from "@react-aria/utils";
import {
useComputedStyleDecl,
$availableUnitVariables,
@@ -65,16 +61,18 @@ import {
formatGradientPositionValues,
formatGradientValue,
getDefaultAngle,
- getPercentUnit,
+ getStopPosition,
gradientPositionXOptions,
gradientPositionYOptions,
isConicGradient,
isLinearGradient,
isRadialGradient,
normalizeGradientInput,
+ parseAnyGradient,
parseGradientPositionValues,
percentUnitOptions,
pruneHintOverrides,
+ reindexHintOverrides,
removeHintOverride,
resolveAngleValue,
resolveGradientForPicker,
@@ -82,7 +80,9 @@ import {
resolveStopHintUpdate,
resolveStopPositionUpdate,
setHintOverride,
+ sortGradientStops,
styleValueToColor,
+ updateGradientStop,
} from "./gradient-utils";
import { BackgroundPositionControl } from "./background-position";
import { BackgroundCodeEditor } from "./background-code-editor";
@@ -129,33 +129,8 @@ type GradientEditorApplyFn = (
options?: { isEphemeral?: boolean }
) => void;
-const getStopPosition = (stop: GradientStop): number =>
- stop.position?.type === "unit" && stop.position.unit === "%"
- ? stop.position.value
- : 0;
-
-const reindexHintOverrides = (
- overrides: Map<number, PercentUnitValue>,
- deletedIndex: number
-): Map<number, PercentUnitValue> => {
- const reindexed = new Map<number, PercentUnitValue>();
- overrides.forEach((value, key) => {
- if (key < deletedIndex) {
- reindexed.set(key, value);
- } else if (key > deletedIndex) {
- reindexed.set(key - 1, value);
- }
- });
- return reindexed;
-};
-
const getAvailableUnitVariables = () => $availableUnitVariables.get();
-const clampPercentUnit = (value: PercentUnitValue): PercentUnitValue => ({
- ...value,
- value: clamp(value.value, 0, 100),
-});
-
export const BackgroundGradient = ({
index,
type: gradientType = "linear",
@@ -176,21 +151,9 @@ export const BackgroundGradient = ({
normalizeGradientInput(gradientString, gradientType);
const parsedGradient = useMemo(() => {
- if (gradientType === "linear") {
- const parsed =
- parseLinearGradient(normalizedGradientString) ??
- createDefaultGradient("linear");
- return ensureGradientHasStops(parsed);
- }
- if (gradientType === "conic") {
- const parsed =
- parseConicGradient(normalizedGradientString) ??
- createDefaultGradient("conic");
- return ensureGradientHasStops(parsed);
- }
const parsed =
- parseRadialGradient(normalizedGradientString) ??
- createDefaultGradient("radial");
+ parseAnyGradient(normalizedGradientString) ??
+ createDefaultGradient(gradientType);
return ensureGradientHasStops(parsed);
}, [gradientType, normalizedGradientString]);
@@ -236,8 +199,30 @@ export const BackgroundGradient = ({
const applyGradient = useCallback(
(nextGradient: ParsedGradient, options?: { isEphemeral?: boolean }) => {
const isEphemeral = options?.isEphemeral === true;
- setLocalGradient(nextGradient);
- const gradientValue = formatGradientValue(nextGradient);
+
+ // Only sort gradient stops on final (non-ephemeral) changes
+ // This allows stops to visually cross during ephemeral updates (e.g., typing in inputs)
+ let finalGradient: ParsedGradient;
+ let finalHints: Map<number, PercentUnitValue>;
+
+ if (isEphemeral) {
+ // During ephemeral changes, apply the gradient as-is without sorting
+ finalGradient = nextGradient;
+ finalHints = hintOverrides;
+ } else {
+ // On complete, sort stops and reindex hint overrides to keep them in sync
+ const { sortedGradient, reindexedHints } = sortGradientStops(
+ nextGradient,
+ hintOverrides
+ );
+ finalGradient = sortedGradient;
+ finalHints = reindexedHints;
+ }
+
+ setLocalGradient(finalGradient);
+ setHintOverrides(finalHints);
+
+ const gradientValue = formatGradientValue(finalGradient);
setRepeatedStyleItem(
styleDecl,
index,
@@ -248,7 +233,7 @@ export const BackgroundGradient = ({
saveLocalGradient();
}
},
- [index, saveLocalGradient, setLocalGradient, styleDecl]
+ [index, saveLocalGradient, setLocalGradient, styleDecl, hintOverrides]
);
return (
@@ -269,8 +254,6 @@ export const BackgroundGradient = ({
setHintOverrides={setHintOverrides}
setSelectedStopIndex={setSelectedStopIndex}
applyGradient={applyGradient}
- styleDecl={styleDecl}
- index={index}
selectedStopIndex={selectedStopIndex}
/>
<Separator />
@@ -309,8 +292,6 @@ type GradientPickerSectionProps = {
setHintOverrides: Dispatch<SetStateAction<Map<number, PercentUnitValue>>>;
setSelectedStopIndex: Dispatch<SetStateAction<number>>;
applyGradient: GradientEditorApplyFn;
- styleDecl: ReturnType<typeof useComputedStyleDecl>;
- index: number;
selectedStopIndex: number;
};
@@ -321,109 +302,14 @@ const GradientPickerSection = ({
setHintOverrides,
setSelectedStopIndex,
applyGradient,
- styleDecl,
- index,
selectedStopIndex,
}: GradientPickerSectionProps) => {
- const parsedComputedGradient = useMemo(() => {
- let computedStyleValue = styleDecl.computedValue;
- if (computedStyleValue?.type === "layers") {
- computedStyleValue = computedStyleValue.value[index];
- }
- const computedGradientString = toValue(computedStyleValue);
- const { normalizedGradientString } = normalizeGradientInput(
- computedGradientString,
- gradientType
- );
-
- if (gradientType === "linear") {
- const parsed =
- parseLinearGradient(normalizedGradientString) ??
- createDefaultGradient("linear");
- return ensureGradientHasStops(parsed);
- }
- if (gradientType === "conic") {
- const parsed =
- parseConicGradient(normalizedGradientString) ??
- createDefaultGradient("conic");
- return ensureGradientHasStops(parsed);
- }
- const parsed =
- parseRadialGradient(normalizedGradientString) ??
- createDefaultGradient("radial");
- return ensureGradientHasStops(parsed);
- }, [gradientType, index, styleDecl]);
-
- const computedGradientForPicker = useMemo(() => {
- if (parsedComputedGradient === undefined) {
- return;
- }
- return resolveGradientForPicker(
- parsedComputedGradient,
- new Map<number, PercentUnitValue>()
- );
- }, [parsedComputedGradient]);
-
- const [isInteracting, setIsInteracting] = useState(false);
-
- const gradientForPicker = useMemo(() => {
- const base = resolveGradientForPicker(gradient, hintOverrides);
- if (isInteracting || computedGradientForPicker === undefined) {
- return base;
- }
-
- const computedStops = computedGradientForPicker.stops;
- const stops = base.stops.map((stop, index) => {
- const computedStop = computedStops[index];
- if (computedStop === undefined) {
- return stop;
- }
- return {
- ...stop,
- color: computedStop.color ?? stop.color,
- position: computedStop.position ?? stop.position,
- hint: computedStop.hint ?? stop.hint,
- } satisfies GradientStop;
- });
-
- if (isLinearGradient(base) && isLinearGradient(computedGradientForPicker)) {
- return {
- ...base,
- angle: computedGradientForPicker.angle ?? base.angle,
- sideOrCorner:
- computedGradientForPicker.sideOrCorner ?? base.sideOrCorner,
- stops,
- } satisfies ParsedLinearGradient;
- }
-
- if (isConicGradient(base) && isConicGradient(computedGradientForPicker)) {
- return {
- ...base,
- angle: computedGradientForPicker.angle ?? base.angle,
- position: computedGradientForPicker.position ?? base.position,
- stops,
- } satisfies ParsedConicGradient;
- }
-
- if (isRadialGradient(base) && isRadialGradient(computedGradientForPicker)) {
- return {
- ...base,
- shape: computedGradientForPicker.shape ?? base.shape,
- size: computedGradientForPicker.size ?? base.size,
- position: computedGradientForPicker.position ?? base.position,
- stops,
- } satisfies ParsedRadialGradient;
- }
-
- return {
- ...base,
- stops,
- } as ParsedGradient;
- }, [computedGradientForPicker, gradient, hintOverrides, isInteracting]);
+ const gradientForPickerBase = useMemo(() => {
+ return resolveGradientForPicker(gradient, hintOverrides);
+ }, [gradient, hintOverrides]);
const handlePickerChange = useCallback(
(nextGradient: ParsedGradient) => {
- setIsInteracting(true);
applyGradient(nextGradient, { isEphemeral: true });
},
[applyGradient]
@@ -431,24 +317,21 @@ const GradientPickerSection = ({
const handlePickerChangeComplete = useCallback(
(nextGradient: ParsedGradient) => {
- setIsInteracting(false);
applyGradient(nextGradient);
},
[applyGradient]
);
- useEffect(() => {
- return () => {
- setIsInteracting(false);
- };
- }, []);
-
const handleThumbSelect = useCallback(
(index: number, _stop: GradientStop) => {
setSelectedStopIndex(index);
},
[setSelectedStopIndex]
);
+
+ // Gradient stops are already sorted in applyGradient, no need to sort here
+ const gradientForPicker = gradientForPickerBase;
+
const previewGradientForTrack = useMemo<ParsedLinearGradient>(() => {
const previewGradient: ParsedLinearGradient = {
type: "linear",
@@ -836,31 +719,44 @@ const GradientStopControls = ({
updater: (stop: GradientStop) => GradientStop,
options?: { isEphemeral?: boolean }
) => {
- const currentStop = gradient.stops[stopIndex];
- if (currentStop === undefined) {
- return;
- }
- const stops = gradient.stops.map((stop, index) =>
- index === stopIndex ? updater(stop) : stop
- );
- const nextGradient = { ...gradient, stops };
+ const nextGradient = updateGradientStop(gradient, stopIndex, updater);
applyGradient(nextGradient, options);
},
[applyGradient, gradient]
);
const handleAddStop = useCallback(() => {
+ // Calculate position for new stop between selected stop and adjacent stop
+ const clampedSelectedIndex = clampStopIndex(selectedStopIndex, gradient);
+ const currentStop = gradient.stops[clampedSelectedIndex];
+ const currentPosition = getStopPosition(currentStop);
+
+ // If last stop is selected, insert between it and the previous stop
+ const isLastStop = clampedSelectedIndex === gradient.stops.length - 1;
+
+ let newPosition: number;
+ if (isLastStop && gradient.stops.length > 1) {
+ const prevStop = gradient.stops[clampedSelectedIndex - 1];
+ const prevPosition = getStopPosition(prevStop);
+ newPosition = (prevPosition + currentPosition) / 2;
+ } else {
+ // Otherwise, insert between current and next stop
+ const nextStop = gradient.stops[clampedSelectedIndex + 1];
+ const nextPosition = nextStop ? getStopPosition(nextStop) : 100;
+ newPosition = (currentPosition + nextPosition) / 2;
+ }
+
applyGradient({
...gradient,
stops: [
...gradient.stops,
{
color: fallbackStopColor,
- position: createPercentUnitValue(50),
+ position: createPercentUnitValue(newPosition),
},
],
});
- }, [applyGradient, gradient]);
+ }, [applyGradient, gradient, selectedStopIndex]);
const handleDeleteStop = useCallback(
(stopIndex: number) => {
@@ -903,226 +799,215 @@ const GradientStopControls = ({
</Tooltip>
</Flex>
</Flex>
- {gradient.stops
- .map((stop, originalIndex) => ({ stop, originalIndex }))
- .sort((a, b) => getStopPosition(a.stop) - getStopPosition(b.stop))
- .map(({ stop, originalIndex: stopIndex }) => {
- const isSelected =
- stopIndex === clampStopIndex(selectedStopIndex, gradient);
- const stopPositionValue = stop.position;
- const stopHintOverride = hintOverrides.get(stopIndex);
- const stopHintValue = stop.hint ?? stopHintOverride;
-
- const handleStopPositionUpdate = (
- styleValue: StyleValue,
- options?: { isEphemeral?: boolean }
- ) => {
- const resolution = resolveStopPositionUpdate(styleValue);
- if (resolution.type === "none") {
- return;
- }
-
- updateStop(
- stopIndex,
- (stop) => ({
- ...stop,
- position: resolution.position,
- }),
- options
- );
+ {gradient.stops.map((stop, stopIndex) => {
+ const isSelected =
+ stopIndex === clampStopIndex(selectedStopIndex, gradient);
+ const stopPositionValue = stop.position;
+ const stopHintOverride = hintOverrides.get(stopIndex);
+ const stopHintValue = stop.hint ?? stopHintOverride;
+
+ const handleStopPositionUpdate = (
+ styleValue: StyleValue,
+ options?: { isEphemeral?: boolean }
+ ) => {
+ const resolution = resolveStopPositionUpdate(styleValue);
+ if (resolution.type === "none") {
+ return;
+ }
+
+ updateStop(
+ stopIndex,
+ (stop) => ({
+ ...stop,
+ position: resolution.position,
+ }),
+ options
+ );
- if (!options?.isEphemeral && resolution.clearHintOverrides) {
- setHintOverrides((previous) =>
- removeHintOverride(previous, stopIndex)
- );
- }
- };
-
- const handleStopPositionDelete = (options?: {
- isEphemeral?: boolean;
- }) => {
- updateStop(
- stopIndex,
- (stop) => {
- const { position: _omit, ...rest } = stop;
- return rest;
- },
- options
- );
- };
-
- const handleStopHintUpdate = (
- styleValue: StyleValue,
- options?: { isEphemeral?: boolean }
- ) => {
- const resolution = resolveStopHintUpdate(styleValue, {
- getPercentUnit,
- clampPercentUnit,
- });
-
- if (resolution.type === "none") {
- return;
- }
-
- updateStop(
- stopIndex,
- (stop) => ({
- ...stop,
- hint: resolution.hint,
- }),
- options
+ if (!options?.isEphemeral && resolution.clearHintOverrides) {
+ setHintOverrides((previous) =>
+ removeHintOverride(previous, stopIndex)
);
+ }
+ };
+
+ const handleStopPositionDelete = (options?: {
+ isEphemeral?: boolean;
+ }) => {
+ updateStop(
+ stopIndex,
+ (stop) => {
+ const { position: _omit, ...rest } = stop;
+ return rest;
+ },
+ options
+ );
+ };
+
+ const handleStopHintUpdate = (
+ styleValue: StyleValue,
+ options?: { isEphemeral?: boolean }
+ ) => {
+ const resolution = resolveStopHintUpdate(styleValue);
+
+ if (resolution.type === "none") {
+ return;
+ }
+
+ updateStop(
+ stopIndex,
+ (stop) => ({
+ ...stop,
+ hint: resolution.hint,
+ }),
+ options
+ );
- if (options?.isEphemeral) {
- return;
- }
-
- if (resolution.clearOverride) {
- setHintOverrides((previous) =>
- removeHintOverride(previous, stopIndex)
- );
- return;
- }
-
- const override = resolution.override;
- if (override !== undefined) {
- setHintOverrides((previous) =>
- setHintOverride(previous, stopIndex, override)
- );
- }
- };
-
- const handleStopHintDelete = (options?: {
- isEphemeral?: boolean;
- }) => {
- updateStop(
- stopIndex,
- (stop) => {
- const { hint: _omit, ...rest } = stop;
- return { ...rest };
- },
- options
+ if (options?.isEphemeral) {
+ return;
+ }
+
+ if (resolution.clearOverride) {
+ setHintOverrides((previous) =>
+ removeHintOverride(previous, stopIndex)
);
- if (!options?.isEphemeral) {
- setHintOverrides((previous) =>
- removeHintOverride(previous, stopIndex)
- );
- }
- };
-
- const handleStopColorChange = (
- styleValue: StyleValue | IntermediateColorValue | undefined
- ) => {
- const nextColor = styleValueToColor(styleValue);
- if (nextColor === undefined) {
- return;
- }
- updateStop(
- stopIndex,
- (stop) => ({
- ...stop,
- color: nextColor,
- }),
- { isEphemeral: true }
+ return;
+ }
+
+ const override = resolution.override;
+ if (override !== undefined) {
+ setHintOverrides((previous) =>
+ setHintOverride(previous, stopIndex, override)
);
- };
-
- const handleStopColorChangeComplete = (styleValue: StyleValue) => {
- const nextColor = styleValueToColor(styleValue);
- if (nextColor === undefined) {
- return;
- }
- updateStop(
- stopIndex,
- (stop) => ({
- ...stop,
- color: nextColor,
- }),
- { isEphemeral: false }
+ }
+ };
+
+ const handleStopHintDelete = (options?: { isEphemeral?: boolean }) => {
+ updateStop(
+ stopIndex,
+ (stop) => {
+ const { hint: _omit, ...rest } = stop;
+ return { ...rest };
+ },
+ options
+ );
+ if (!options?.isEphemeral) {
+ setHintOverrides((previous) =>
+ removeHintOverride(previous, stopIndex)
);
- };
-
- const stopColor = (stop.color ?? fallbackStopColor) as StyleValue;
-
- return (
- <Flex
- key={stopIndex}
+ }
+ };
+
+ const handleStopColorChange = (
+ styleValue: StyleValue | IntermediateColorValue | undefined
+ ) => {
+ const nextColor = styleValueToColor(styleValue);
+ if (nextColor === undefined) {
+ return;
+ }
+ updateStop(
+ stopIndex,
+ (stop) => ({
+ ...stop,
+ color: nextColor,
+ }),
+ { isEphemeral: true }
+ );
+ };
+
+ const handleStopColorChangeComplete = (styleValue: StyleValue) => {
+ const nextColor = styleValueToColor(styleValue);
+ if (nextColor === undefined) {
+ return;
+ }
+ updateStop(
+ stopIndex,
+ (stop) => ({
+ ...stop,
+ color: nextColor,
+ }),
+ { isEphemeral: false }
+ );
+ };
+
+ const stopColor = (stop.color ?? fallbackStopColor) as StyleValue;
+
+ return (
+ <Flex
+ key={stopIndex}
+ gap="1"
+ css={{
+ opacity: isSelected ? 1 : 0.6,
+ }}
+ onFocus={() => {
+ if (!isSelected) {
+ setSelectedStopIndex(stopIndex);
+ }
+ }}
+ >
+ <Grid
+ align="end"
gap="1"
- css={{
- opacity: isSelected ? 1 : 0.6,
- }}
- onFocus={() => {
- if (!isSelected) {
- setSelectedStopIndex(stopIndex);
- }
- }}
+ css={{ gridTemplateColumns: "1fr 1fr 2fr" }}
>
- <Grid
- align="end"
- gap="1"
- css={{ gridTemplateColumns: "1fr 1fr 2fr" }}
+ <Tooltip
+ content="Position of this gradient stop along the gradient line."
+ variant="wrapped"
>
- <Tooltip
- content="Position of this gradient stop along the gradient line."
- variant="wrapped"
- >
- <Box>
- <CssValueInputContainer
- property={"background-position-x"}
- styleSource="default"
- getOptions={getAvailableUnitVariables}
- value={stopPositionValue}
- unitOptions={percentUnitOptions}
- onUpdate={handleStopPositionUpdate}
- onDelete={handleStopPositionDelete}
- />
- </Box>
- </Tooltip>
- <Tooltip
- content="Midpoint position for color transition between this stop and the next."
- variant="wrapped"
- >
- <Box>
- <CssValueInputContainer
- property={"background-position-x"}
- styleSource="default"
- getOptions={getAvailableUnitVariables}
- value={stopHintValue}
- unitOptions={percentUnitOptions}
- onUpdate={handleStopHintUpdate}
- onDelete={handleStopHintDelete}
- />
- </Box>
- </Tooltip>
- <Tooltip
- content="Color of this gradient stop."
- variant="wrapped"
- >
- <Box>
- <ColorPickerControl
- property="color"
- value={stopColor}
- currentColor={stopColor}
- onChange={handleStopColorChange}
- onChangeComplete={handleStopColorChangeComplete}
- onAbort={() => {}}
- onReset={() => {}}
- />
- </Box>
- </Tooltip>
- </Grid>
- <Tooltip content="Delete stop" variant="wrapped">
- <IconButton
- aria-label="Delete stop"
- onClick={() => handleDeleteStop(stopIndex)}
- disabled={gradient.stops.length <= 2}
- >
- <MinusIcon />
- </IconButton>
+ <Box>
+ <CssValueInputContainer
+ property={"background-position-x"}
+ styleSource="default"
+ getOptions={getAvailableUnitVariables}
+ value={stopPositionValue}
+ unitOptions={percentUnitOptions}
+ onUpdate={handleStopPositionUpdate}
+ onDelete={handleStopPositionDelete}
+ />
+ </Box>
</Tooltip>
- </Flex>
- );
- })}
+ <Tooltip
+ content="Midpoint position for color transition between this stop and the next."
+ variant="wrapped"
+ >
+ <Box>
+ <CssValueInputContainer
+ property={"background-position-x"}
+ styleSource="default"
+ getOptions={getAvailableUnitVariables}
+ value={stopHintValue}
+ unitOptions={percentUnitOptions}
+ onUpdate={handleStopHintUpdate}
+ onDelete={handleStopHintDelete}
+ />
+ </Box>
+ </Tooltip>
+ <Tooltip content="Color of this gradient stop." variant="wrapped">
+ <Box>
+ <ColorPickerControl
+ property="color"
+ value={stopColor}
+ currentColor={stopColor}
+ onChange={handleStopColorChange}
+ onChangeComplete={handleStopColorChangeComplete}
+ onAbort={() => {}}
+ onReset={() => {}}
+ />
+ </Box>
+ </Tooltip>
+ </Grid>
+ <Tooltip content="Delete stop" variant="wrapped">
+ <IconButton
+ aria-label="Delete stop"
+ onClick={() => handleDeleteStop(stopIndex)}
+ disabled={gradient.stops.length <= 2}
+ >
+ <MinusIcon />
+ </IconButton>
+ </Tooltip>
+ </Flex>
+ );
+ })}
</Flex>
);
};
diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/gradient-utils.test.ts b/apps/builder/app/builder/features/style-panel/sections/backgrounds/gradient-utils.test.ts
index 0b5c44916b..52b09e8cec 100644
--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/gradient-utils.test.ts
+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/gradient-utils.test.ts
@@ -23,6 +23,7 @@ import {
normalizeGradientInput,
type PercentUnitValue,
pruneHintOverrides,
+ reindexHintOverrides,
removeHintOverride,
resolveAngleValue,
resolveGradientForPicker,
@@ -31,10 +32,12 @@ import {
resolveStopPositionUpdate,
setHintOverride,
sideOrCornerToAngle,
+ sortGradientStops,
styleValueToColor,
formatGradientForType,
formatGradientValue,
convertGradientToTarget,
+ updateGradientStop,
type GradientType,
} from "./gradient-utils";
@@ -713,10 +716,7 @@ describe("resolveStopHintUpdate", () => {
fallback,
};
- const result = resolveStopHintUpdate(styleValue, {
- getPercentUnit: () => undefined,
- clampPercentUnit: (value) => value,
- });
+ const result = resolveStopHintUpdate(styleValue);
expect(result.type).toBe("apply");
if (result.type !== "apply") {
@@ -740,25 +740,18 @@ describe("resolveStopHintUpdate", () => {
test("normalizes percent units and returns override", () => {
const styleValue: StyleValue = { type: "unit", unit: "%", value: 45 };
- const normalized: PercentUnitValue = {
- type: "unit",
- unit: "%",
- value: 50,
- };
- const result = resolveStopHintUpdate(styleValue, {
- getPercentUnit: () => ({ type: "unit", unit: "%", value: 45 }),
- clampPercentUnit: () => normalized,
- });
+ const result = resolveStopHintUpdate(styleValue);
expect(result.type).toBe("apply");
if (result.type !== "apply") {
throw new Error("Expected apply result");
}
+ // Value is clamped between 0-100
expect(result).toEqual({
type: "apply",
- hint: normalized,
- override: normalized,
+ hint: { type: "unit", unit: "%", value: 45 },
+ override: { type: "unit", unit: "%", value: 45 },
clearOverride: false,
});
});
@@ -766,10 +759,7 @@ describe("resolveStopHintUpdate", () => {
test("returns none when value unsupported", () => {
const styleValue: StyleValue = { type: "keyword", value: "auto" };
- const result = resolveStopHintUpdate(styleValue, {
- getPercentUnit: () => undefined,
- clampPercentUnit: (value) => value,
- });
+ const result = resolveStopHintUpdate(styleValue);
expect(result).toEqual({ type: "none" });
});
@@ -1606,3 +1596,423 @@ describe("detectBackgroundType", () => {
expect(detectBackgroundType(value)).toBe("image");
});
});
+
+describe("reindexHintOverrides", () => {
+ test("reindexes hints after deleting a stop before them", () => {
+ const overrides = new Map<number, PercentUnitValue>([
+ [1, { type: "unit", unit: "%", value: 25 }],
+ [3, { type: "unit", unit: "%", value: 75 }],
+ ]);
+ const result = reindexHintOverrides(overrides, 0);
+ expect(result.get(0)).toEqual({ type: "unit", unit: "%", value: 25 });
+ expect(result.get(2)).toEqual({ type: "unit", unit: "%", value: 75 });
+ expect(result.size).toBe(2);
+ });
+
+ test("removes hint for deleted stop", () => {
+ const overrides = new Map<number, PercentUnitValue>([
+ [1, { type: "unit", unit: "%", value: 25 }],
+ [2, { type: "unit", unit: "%", value: 50 }],
+ [3, { type: "unit", unit: "%", value: 75 }],
+ ]);
+ const result = reindexHintOverrides(overrides, 2);
+ expect(result.get(1)).toEqual({ type: "unit", unit: "%", value: 25 });
+ expect(result.get(2)).toEqual({ type: "unit", unit: "%", value: 75 });
+ expect(result.has(3)).toBe(false);
+ expect(result.size).toBe(2);
+ });
+
+ test("keeps hints before deleted index unchanged", () => {
+ const overrides = new Map<number, PercentUnitValue>([
+ [0, { type: "unit", unit: "%", value: 10 }],
+ [1, { type: "unit", unit: "%", value: 25 }],
+ ]);
+ const result = reindexHintOverrides(overrides, 3);
+ expect(result.get(0)).toEqual({ type: "unit", unit: "%", value: 10 });
+ expect(result.get(1)).toEqual({ type: "unit", unit: "%", value: 25 });
+ expect(result.size).toBe(2);
+ });
+
+ test("handles empty overrides map", () => {
+ const overrides = new Map<number, PercentUnitValue>();
+ const result = reindexHintOverrides(overrides, 1);
+ expect(result.size).toBe(0);
+ });
+});
+
+describe("sortGradientStops", () => {
+ const red: RgbValue = { type: "rgb", r: 255, g: 0, b: 0, alpha: 1 };
+ const blue: RgbValue = { type: "rgb", r: 0, g: 0, b: 255, alpha: 1 };
+ const green: RgbValue = { type: "rgb", r: 0, g: 255, b: 0, alpha: 1 };
+
+ test("sorts stops by position ascending", () => {
+ const gradient = createLinearGradient({
+ stops: [
+ { color: red, position: { type: "unit", unit: "%", value: 100 } },
+ { color: blue, position: { type: "unit", unit: "%", value: 0 } },
+ { color: green, position: { type: "unit", unit: "%", value: 50 } },
+ ],
+ });
+ const { sortedGradient } = sortGradientStops(gradient, new Map());
+
+ expect(sortedGradient.stops[0].position).toEqual({
+ type: "unit",
+ unit: "%",
+ value: 0,
+ });
+ expect(sortedGradient.stops[1].position).toEqual({
+ type: "unit",
+ unit: "%",
+ value: 50,
+ });
+ expect(sortedGradient.stops[2].position).toEqual({
+ type: "unit",
+ unit: "%",
+ value: 100,
+ });
+ });
+
+ test("reindexes hint overrides to match sorted positions", () => {
+ const gradient = createLinearGradient({
+ stops: [
+ { color: red, position: { type: "unit", unit: "%", value: 100 } }, // originalIndex: 0
+ { color: blue, position: { type: "unit", unit: "%", value: 0 } }, // originalIndex: 1
+ { color: green, position: { type: "unit", unit: "%", value: 50 } }, // originalIndex: 2
+ ],
+ });
+ const hintOverrides = new Map<number, PercentUnitValue>([
+ [0, { type: "unit", unit: "%", value: 90 }], // hint for stop at 100%
+ [2, { type: "unit", unit: "%", value: 40 }], // hint for stop at 50%
+ ]);
+ const { reindexedHints } = sortGradientStops(gradient, hintOverrides);
+
+ // After sorting: [0%, 50%, 100%]
+ // Hints should be at new indices: 1 (for 50%) and 2 (for 100%)
+ expect(reindexedHints.get(1)).toEqual({
+ type: "unit",
+ unit: "%",
+ value: 40,
+ });
+ expect(reindexedHints.get(2)).toEqual({
+ type: "unit",
+ unit: "%",
+ value: 90,
+ });
+ expect(reindexedHints.size).toBe(2);
+ });
+
+ test("handles stops without positions (defaults to 0)", () => {
+ const gradient = createLinearGradient({
+ stops: [
+ { color: red, position: { type: "unit", unit: "%", value: 50 } },
+ { color: blue }, // No position, should default to 0
+ { color: green, position: { type: "unit", unit: "%", value: 100 } },
+ ],
+ });
+ const { sortedGradient } = sortGradientStops(gradient, new Map());
+
+ expect(sortedGradient.stops[0].color).toEqual(blue); // No position = 0
+ expect(sortedGradient.stops[1].position).toEqual({
+ type: "unit",
+ unit: "%",
+ value: 50,
+ });
+ expect(sortedGradient.stops[2].position).toEqual({
+ type: "unit",
+ unit: "%",
+ value: 100,
+ });
+ });
+
+ test("preserves gradient properties other than stops", () => {
+ const gradient = createLinearGradient({
+ angle: { type: "unit", unit: "deg", value: 45 },
+ repeating: true,
+ stops: [
+ { color: red, position: { type: "unit", unit: "%", value: 100 } },
+ { color: blue, position: { type: "unit", unit: "%", value: 0 } },
+ ],
+ });
+ const { sortedGradient } = sortGradientStops(gradient, new Map());
+
+ expect(sortedGradient.type).toBe("linear");
+ if (sortedGradient.type === "linear") {
+ expect(sortedGradient.angle).toEqual({
+ type: "unit",
+ unit: "deg",
+ value: 45,
+ });
+ }
+ expect(sortedGradient.repeating).toBe(true);
+ });
+
+ test("handles empty hint overrides", () => {
+ const gradient = createLinearGradient({
+ stops: [
+ { color: red, position: { type: "unit", unit: "%", value: 50 } },
+ { color: blue, position: { type: "unit", unit: "%", value: 0 } },
+ ],
+ });
+ const { reindexedHints } = sortGradientStops(gradient, new Map());
+
+ expect(reindexedHints.size).toBe(0);
+ });
+
+ test("maintains stable sort for stops at same position", () => {
+ const gradient = createLinearGradient({
+ stops: [
+ { color: red, position: { type: "unit", unit: "%", value: 50 } },
+ { color: blue, position: { type: "unit", unit: "%", value: 50 } },
+ { color: green, position: { type: "unit", unit: "%", value: 50 } },
+ ],
+ });
+ const { sortedGradient } = sortGradientStops(gradient, new Map());
+
+ // Original order should be preserved for stops at the same position
+ expect(sortedGradient.stops[0].color).toEqual(red);
+ expect(sortedGradient.stops[1].color).toEqual(blue);
+ expect(sortedGradient.stops[2].color).toEqual(green);
+ });
+});
+
+describe("updateGradientStop", () => {
+ const red: RgbValue = { type: "rgb", r: 255, g: 0, b: 0, alpha: 1 };
+ const blue: RgbValue = { type: "rgb", r: 0, g: 0, b: 255, alpha: 1 };
+
+ test("returns same gradient when stop index is invalid", () => {
+ const gradient = createLinearGradient({
+ stops: [{ color: red, position: { type: "unit", unit: "%", value: 0 } }],
+ });
+
+ const result = updateGradientStop(gradient, -1, (stop) => stop);
+ expect(result).toBe(gradient);
+
+ const result2 = updateGradientStop(gradient, 5, (stop) => stop);
+ expect(result2).toBe(gradient);
+ });
+
+ test("updates stop without hint", () => {
+ const gradient = createLinearGradient({
+ stops: [
+ { color: red, position: { type: "unit", unit: "%", value: 0 } },
+ { color: blue, position: { type: "unit", unit: "%", value: 100 } },
+ ],
+ });
+
+ const result = updateGradientStop(gradient, 0, (stop) => ({
+ ...stop,
+ position: { type: "unit", unit: "%", value: 25 },
+ }));
+
+ expect(result.stops[0].position).toEqual({
+ type: "unit",
+ unit: "%",
+ value: 25,
+ });
+ expect(result.stops[0].hint).toBeUndefined();
+ });
+
+ test("maintains hint offset when position changes", () => {
+ const gradient = createLinearGradient({
+ stops: [
+ {
+ color: red,
+ position: { type: "unit", unit: "%", value: 20 },
+ hint: { type: "unit", unit: "%", value: 30 }, // offset = 10
+ },
+ { color: blue, position: { type: "unit", unit: "%", value: 100 } },
+ ],
+ });
+
+ const result = updateGradientStop(gradient, 0, (stop) => ({
+ ...stop,
+ position: { type: "unit", unit: "%", value: 50 },
+ }));
+
+ expect(result.stops[0].position).toEqual({
+ type: "unit",
+ unit: "%",
+ value: 50,
+ });
+ // Hint should maintain offset of 10: 50 + 10 = 60
+ expect(result.stops[0].hint).toEqual({
+ type: "unit",
+ unit: "%",
+ value: 60,
+ });
+ });
+
+ test("clamps hint to 0-100 range when maintaining offset", () => {
+ const gradient = createLinearGradient({
+ stops: [
+ {
+ color: red,
+ position: { type: "unit", unit: "%", value: 80 },
+ hint: { type: "unit", unit: "%", value: 95 }, // offset = 15
+ },
+ { color: blue, position: { type: "unit", unit: "%", value: 100 } },
+ ],
+ });
+
+ const result = updateGradientStop(gradient, 0, (stop) => ({
+ ...stop,
+ position: { type: "unit", unit: "%", value: 90 },
+ }));
+
+ // Hint should be clamped: 90 + 15 = 105 -> 100
+ expect(result.stops[0].hint).toEqual({
+ type: "unit",
+ unit: "%",
+ value: 100,
+ });
+ });
+
+ test("clamps hint to minimum 0 when offset is negative", () => {
+ const gradient = createLinearGradient({
+ stops: [
+ {
+ color: red,
+ position: { type: "unit", unit: "%", value: 50 },
+ hint: { type: "unit", unit: "%", value: 30 }, // offset = -20
+ },
+ { color: blue, position: { type: "unit", unit: "%", value: 100 } },
+ ],
+ });
+
+ const result = updateGradientStop(gradient, 0, (stop) => ({
+ ...stop,
+ position: { type: "unit", unit: "%", value: 10 },
+ }));
+
+ // Hint should be clamped: 10 + (-20) = -10 -> 0
+ expect(result.stops[0].hint).toEqual({
+ type: "unit",
+ unit: "%",
+ value: 0,
+ });
+ });
+
+ test("does not modify hint when position does not change", () => {
+ const gradient = createLinearGradient({
+ stops: [
+ {
+ color: red,
+ position: { type: "unit", unit: "%", value: 20 },
+ hint: { type: "unit", unit: "%", value: 30 },
+ },
+ { color: blue, position: { type: "unit", unit: "%", value: 100 } },
+ ],
+ });
+
+ const result = updateGradientStop(gradient, 0, (stop) => ({
+ ...stop,
+ color: blue, // Only change color, not position
+ }));
+
+ expect(result.stops[0].color).toEqual(blue);
+ expect(result.stops[0].position).toEqual({
+ type: "unit",
+ unit: "%",
+ value: 20,
+ });
+ // Hint should remain unchanged
+ expect(result.stops[0].hint).toEqual({
+ type: "unit",
+ unit: "%",
+ value: 30,
+ });
+ });
+
+ test("does not modify other stops", () => {
+ const gradient = createLinearGradient({
+ stops: [
+ {
+ color: red,
+ position: { type: "unit", unit: "%", value: 0 },
+ hint: { type: "unit", unit: "%", value: 10 },
+ },
+ {
+ color: blue,
+ position: { type: "unit", unit: "%", value: 100 },
+ hint: { type: "unit", unit: "%", value: 90 },
+ },
+ ],
+ });
+
+ const result = updateGradientStop(gradient, 0, (stop) => ({
+ ...stop,
+ position: { type: "unit", unit: "%", value: 20 },
+ }));
+
+ // Second stop should be unchanged
+ expect(result.stops[1]).toEqual(gradient.stops[1]);
+ });
+
+ test("handles stop without hint gracefully", () => {
+ const gradient = createLinearGradient({
+ stops: [
+ { color: red, position: { type: "unit", unit: "%", value: 0 } },
+ { color: blue, position: { type: "unit", unit: "%", value: 100 } },
+ ],
+ });
+
+ const result = updateGradientStop(gradient, 0, (stop) => ({
+ ...stop,
+ position: { type: "unit", unit: "%", value: 50 },
+ }));
+
+ expect(result.stops[0].position).toEqual({
+ type: "unit",
+ unit: "%",
+ value: 50,
+ });
+ expect(result.stops[0].hint).toBeUndefined();
+ });
+
+ test("handles non-percent hint units gracefully", () => {
+ const gradient = createLinearGradient({
+ stops: [
+ {
+ color: red,
+ position: { type: "unit", unit: "%", value: 20 },
+ hint: { type: "unit", unit: "px", value: 50 } as UnitValue,
+ },
+ { color: blue, position: { type: "unit", unit: "%", value: 100 } },
+ ],
+ });
+
+ const result = updateGradientStop(gradient, 0, (stop) => ({
+ ...stop,
+ position: { type: "unit", unit: "%", value: 50 },
+ }));
+
+ // Hint should not be modified for non-percent units
+ expect(result.stops[0].hint).toEqual({
+ type: "unit",
+ unit: "px",
+ value: 50,
+ });
+ });
+
+ test("preserves gradient properties other than stops", () => {
+ const gradient = createLinearGradient({
+ angle: { type: "unit", unit: "deg", value: 45 },
+ repeating: true,
+ stops: [
+ { color: red, position: { type: "unit", unit: "%", value: 0 } },
+ { color: blue, position: { type: "unit", unit: "%", value: 100 } },
+ ],
+ });
+
+ const result = updateGradientStop(gradient, 0, (stop) => ({
+ ...stop,
+ position: { type: "unit", unit: "%", value: 25 },
+ }));
+
+ expect(result.type).toBe("linear");
+ if (result.type === "linear") {
+ expect(result.angle).toEqual({ type: "unit", unit: "deg", value: 45 });
+ }
+ expect(result.repeating).toBe(true);
+ });
+});
diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/gradient-utils.ts b/apps/builder/app/builder/features/style-panel/sections/backgrounds/gradient-utils.ts
index 8241051bba..655b924c0b 100644
--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/gradient-utils.ts
+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/gradient-utils.ts
@@ -7,7 +7,6 @@ import {
type StyleValue,
type Unit,
type UnitValue,
- type VarFallback,
type VarValue,
} from "@webstudio-is/css-engine";
import {
@@ -61,6 +60,10 @@ const gradientFunctionNames: Record<
},
};
+/**
+ * Checks if a CSS value string starts with a gradient function of the specified type.
+ * Handles both base and repeating gradient functions (e.g., "linear-gradient" and "repeating-linear-gradient").
+ */
const startsWithGradientFunction = (value: string, type: GradientType) => {
const normalized = value.trim().toLowerCase();
const { base, repeating } = gradientFunctionNames[type];
@@ -88,23 +91,16 @@ export const percentUnitOptions: UnitOption[] = [
},
];
-const createKeywordValue = (value: string): KeywordValue => ({
- type: "keyword",
- value,
-});
-
-const createCenterKeyword = () => createKeywordValue("center");
-
export const gradientPositionXOptions: KeywordValue[] = [
- createCenterKeyword(),
- createKeywordValue("left"),
- createKeywordValue("right"),
+ { type: "keyword", value: "center" },
+ { type: "keyword", value: "left" },
+ { type: "keyword", value: "right" },
];
export const gradientPositionYOptions: KeywordValue[] = [
- createCenterKeyword(),
- createKeywordValue("top"),
- createKeywordValue("bottom"),
+ { type: "keyword", value: "center" },
+ { type: "keyword", value: "top" },
+ { type: "keyword", value: "bottom" },
];
const getAxisPositionValue = (
@@ -121,11 +117,15 @@ const getAxisPositionValue = (
return parsed;
};
+/**
+ * Parses a gradient position string into separate x and y StyleValues.
+ * Defaults to "center center" if position is undefined or parsing fails.
+ */
export const parseGradientPositionValues = (position?: string) => {
if (position === undefined) {
return {
- xValue: createCenterKeyword(),
- yValue: createCenterKeyword(),
+ xValue: { type: "keyword" as const, value: "center" },
+ yValue: { type: "keyword" as const, value: "center" },
} as const;
}
try {
@@ -135,27 +135,33 @@ export const parseGradientPositionValues = (position?: string) => {
// Use the real background-position longhand when parsing so we can reuse
// its CSS syntax rules, but assign the result to the gradient-specific
// custom property downstream.
- xValue:
- getAxisPositionValue(backgroundPositionXLonghand, xLonghand?.[1]) ??
- createCenterKeyword(),
- yValue:
- getAxisPositionValue(backgroundPositionYLonghand, yLonghand?.[1]) ??
- createCenterKeyword(),
+ xValue: getAxisPositionValue(
+ backgroundPositionXLonghand,
+ xLonghand?.[1]
+ ) ?? { type: "keyword" as const, value: "center" },
+ yValue: getAxisPositionValue(
+ backgroundPositionYLonghand,
+ yLonghand?.[1]
+ ) ?? { type: "keyword" as const, value: "center" },
} as const;
} catch {
return {
- xValue: createCenterKeyword(),
- yValue: createCenterKeyword(),
+ xValue: { type: "keyword" as const, value: "center" },
+ yValue: { type: "keyword" as const, value: "center" },
} as const;
}
};
+/**
+ * Formats x and y position values into a CSS position string.
+ * Omits "center center" as it's the default. Returns just x if y is center.
+ */
export const formatGradientPositionValues = (
xValue?: StyleValue,
yValue?: StyleValue
) => {
- const x = toValue(xValue ?? createCenterKeyword());
- const y = toValue(yValue ?? createCenterKeyword());
+ const x = toValue(xValue ?? { type: "keyword" as const, value: "center" });
+ const y = toValue(yValue ?? { type: "keyword" as const, value: "center" });
if (x === "center" && y === "center") {
return;
}
@@ -191,6 +197,11 @@ const angleUnitToDegrees = (value: UnitValue): number | undefined => {
}
};
+/**
+ * Converts a UnitValue to a PercentUnitValue.
+ * For percent units, clamps to 0-100. For angle units, converts to percent (0-100 representing 0-360deg).
+ * Returns undefined for unsupported unit types.
+ */
const toPercentUnitValue = (value: UnitValue): PercentUnitValue | undefined => {
if (value.unit === "%") {
return {
@@ -287,7 +298,7 @@ export const isRadialGradient = (
): gradient is ParsedRadialGradient => gradient.type === "radial";
/**
- * Get the default angle for a gradient according to CSS spec.
+ * Returns the CSS spec default angle for each gradient type:
* - linear-gradient: 180deg (to bottom)
* - conic-gradient: 0deg (from top)
* - radial-gradient: undefined (no angle)
@@ -331,6 +342,10 @@ export const getPercentUnit = (
}
};
+/**
+ * Converts repeating-*-gradient to *-gradient while preserving leading whitespace.
+ * Returns both the normalized string and whether it was originally repeating.
+ */
export const normalizeGradientInput = (
gradientString: string,
gradientType: GradientType
@@ -402,6 +417,10 @@ export const sideOrCornerToAngle = (
}
};
+/**
+ * Interpolates missing stop positions proportionally between defined positions.
+ * Only works with percent units - returns original gradient for non-percent units.
+ */
export const fillMissingStopPositions = <T extends ParsedGradient>(
gradient: T
): T => {
@@ -502,25 +521,9 @@ export const fillMissingStopPositions = <T extends ParsedGradient>(
} as T;
};
-const cloneVarValue = (value: VarValue): VarValue => ({
- ...value,
- fallback: value.fallback === undefined ? undefined : { ...value.fallback },
-});
-
-export const cloneVarFallback = (
- fallback: VarFallback | undefined
-): VarFallback | undefined => {
- if (fallback === undefined) {
- return;
- }
-
- if (fallback.type === "rgb") {
- return { ...fallback } satisfies VarFallback;
- }
-
- return { ...fallback } satisfies VarFallback;
-};
-
+/**
+ * Clones stop values, deep cloning var fallbacks to avoid shared references.
+ */
const cloneGradientStopValue = <
Value extends GradientStop["position"] | GradientStop["hint"],
>(
@@ -531,60 +534,57 @@ const cloneGradientStopValue = <
}
if (value.type === "var") {
- const fallback = value.fallback;
return {
...value,
- fallback: fallback === undefined ? undefined : { ...fallback },
- } as Value;
+ fallback: value.fallback && { ...value.fallback },
+ };
}
- return { ...value } as Value;
+ return { ...value };
};
+/**
+ * Clones colors, deep cloning var fallbacks to avoid shared references.
+ */
const cloneGradientStopColor = (
color: GradientStop["color"] | undefined
): GradientStop["color"] => {
if (color === undefined) {
- return { ...fallbackStopColor } satisfies GradientStop["color"];
+ return { ...fallbackStopColor };
}
if (color.type === "var") {
return {
...color,
- fallback: cloneVarFallback(color.fallback),
- } satisfies GradientStop["color"];
- }
- if (color.type === "rgb") {
- return { ...color } satisfies GradientStop["color"];
+ fallback: color.fallback && { ...color.fallback },
+ };
}
- return { ...color } satisfies GradientStop["color"];
-};
-
-const createSolidGradientStops = (color: GradientStop["color"]) => {
- const firstColor = cloneGradientStopColor(color);
- const secondColor = cloneGradientStopColor(color);
- return [
- {
- color: firstColor,
- position: { type: "unit", unit: "%", value: 0 },
- },
- {
- color: secondColor,
- position: { type: "unit", unit: "%", value: 100 },
- },
- ] satisfies GradientStop[];
+ return { ...color };
};
+/**
+ * Creates a solid color gradient (two identical stops at 0% and 100%).
+ */
export const createSolidLinearGradient = (
color: GradientStop["color"],
base?: ParsedLinearGradient
): ParsedLinearGradient => {
- const stops = createSolidGradientStops(color);
+ const firstColor = cloneGradientStopColor(color);
+ const secondColor = cloneGradientStopColor(color);
return {
type: "linear",
angle: base?.angle,
sideOrCorner: base?.sideOrCorner,
- stops,
- } satisfies ParsedLinearGradient;
+ stops: [
+ {
+ color: firstColor,
+ position: { type: "unit", unit: "%", value: 0 },
+ },
+ {
+ color: secondColor,
+ position: { type: "unit", unit: "%", value: 100 },
+ },
+ ],
+ };
};
type AngleUnitValue = UnitValue & { unit: AngleUnit };
@@ -598,14 +598,17 @@ const resolveAnglePrimitive = (
}
if (value.type === "var") {
- return cloneVarValue(value);
+ return {
+ ...value,
+ fallback: value.fallback && { ...value.fallback },
+ };
}
if (value.type === "unit" && isAngleUnit(value.unit)) {
return {
...value,
unit: value.unit,
- } satisfies AngleUnitValue;
+ };
}
return;
@@ -705,6 +708,9 @@ const normalizeStopsForPicker = <T extends ParsedGradient>(gradient: T): T => {
} as T;
};
+/**
+ * Converts conic angle units (deg, turn, etc.) to percent units for picker UI.
+ */
const convertConicStopsToPercent = <T extends ParsedGradient>(
gradient: T
): T => {
@@ -764,6 +770,9 @@ const convertConicStopsToPercent = <T extends ParsedGradient>(
} as T;
};
+/**
+ * Prepares gradient for picker UI: converts angles to percent, resolves vars, fills positions, applies hint overrides.
+ */
export const resolveGradientForPicker = <T extends ParsedGradient>(
gradient: T,
hintOverrides: ReadonlyMap<number, PercentUnitValue>
@@ -798,6 +807,9 @@ export const resolveGradientForPicker = <T extends ParsedGradient>(
} as T;
};
+/**
+ * Returns same map reference if unchanged for referential equality.
+ */
export const removeHintOverride = (
overrides: Map<number, PercentUnitValue>,
stopIndex: number
@@ -810,6 +822,9 @@ export const removeHintOverride = (
return next;
};
+/**
+ * Returns same map reference if unchanged for referential equality.
+ */
export const setHintOverride = (
overrides: Map<number, PercentUnitValue>,
stopIndex: number,
@@ -833,6 +848,9 @@ export const setHintOverride = (
return next;
};
+/**
+ * Returns same map reference if unchanged for referential equality.
+ */
export const pruneHintOverrides = (
overrides: Map<number, PercentUnitValue>,
stopCount: number
@@ -851,6 +869,65 @@ export const pruneHintOverrides = (
return changed ? next : overrides;
};
+export const getStopPosition = (stop: GradientStop): number =>
+ stop.position?.type === "unit" && stop.position.unit === "%"
+ ? stop.position.value
+ : 0;
+
+export const reindexHintOverrides = (
+ overrides: Map<number, PercentUnitValue>,
+ deletedIndex: number
+): Map<number, PercentUnitValue> => {
+ const reindexed = new Map<number, PercentUnitValue>();
+ overrides.forEach((value, key) => {
+ if (key < deletedIndex) {
+ reindexed.set(key, value);
+ } else if (key > deletedIndex) {
+ reindexed.set(key - 1, value);
+ }
+ });
+ return reindexed;
+};
+
+export const sortGradientStops = (
+ gradient: ParsedGradient,
+ hintOverrides: Map<number, PercentUnitValue>
+): {
+ sortedGradient: ParsedGradient;
+ reindexedHints: Map<number, PercentUnitValue>;
+} => {
+ // Create array of stops with their original indices and hint overrides
+ const stopsWithData = gradient.stops.map((stop, originalIndex) => ({
+ stop,
+ originalIndex,
+ hint: hintOverrides.get(originalIndex),
+ }));
+
+ // Sort by position
+ stopsWithData.sort((a, b) => {
+ const posA = getStopPosition(a.stop);
+ const posB = getStopPosition(b.stop);
+ return posA - posB;
+ });
+
+ // Extract sorted stops and rebuild hint overrides with new indices
+ const sortedStops = stopsWithData.map(({ stop }) => stop);
+ const reindexedHints = new Map<number, PercentUnitValue>();
+ stopsWithData.forEach(({ hint }, newIndex) => {
+ if (hint !== undefined) {
+ reindexedHints.set(newIndex, hint);
+ }
+ });
+
+ return {
+ sortedGradient: {
+ ...gradient,
+ stops: sortedStops,
+ },
+ reindexedHints,
+ };
+};
+
export type ReverseStopsResolution<T extends ParsedGradient> =
| {
type: "apply";
@@ -859,6 +936,9 @@ export type ReverseStopsResolution<T extends ParsedGradient> =
}
| { type: "none" };
+/**
+ * Reverses stops and mirrors percent positions (0% becomes 100%, etc.).
+ */
export const resolveReverseStops = <T extends ParsedGradient>(
gradient: T,
selectedStopIndex: number
@@ -901,7 +981,7 @@ export const resolveStopPositionUpdate = (
if (styleValue.type === "var") {
return {
type: "apply",
- position: cloneGradientStopValue(styleValue as GradientStop["position"]),
+ position: cloneGradientStopValue(styleValue),
clearHintOverrides: true,
} satisfies StopPositionUpdateResolution;
}
@@ -922,11 +1002,6 @@ export const resolveStopPositionUpdate = (
} satisfies StopPositionUpdateResolution;
};
-type StopHintUpdateHelpers = {
- getPercentUnit: (value: StyleValue) => PercentUnitValue | undefined;
- clampPercentUnit: (value: PercentUnitValue) => PercentUnitValue;
-};
-
export type StopHintUpdateResolution =
| {
type: "apply";
@@ -937,23 +1012,27 @@ export type StopHintUpdateResolution =
| { type: "none" };
export const resolveStopHintUpdate = (
- styleValue: StyleValue,
- helpers: StopHintUpdateHelpers
+ styleValue: StyleValue
): StopHintUpdateResolution => {
if (styleValue.type === "var") {
return {
type: "apply",
- hint: cloneGradientStopValue(styleValue as GradientStop["hint"]),
+ hint: cloneGradientStopValue(styleValue),
clearOverride: true,
};
}
- const percentUnit = helpers.getPercentUnit(styleValue);
+ const percentUnit = getPercentUnit(styleValue);
if (percentUnit === undefined) {
return { type: "none" };
}
- const normalized = helpers.clampPercentUnit(percentUnit);
+ // Clamp the value inline
+ const normalized: PercentUnitValue = {
+ ...percentUnit,
+ value: clamp(percentUnit.value, 0, 100),
+ };
+
return {
type: "apply",
hint: normalized,
@@ -988,6 +1067,61 @@ export const clampStopIndex = <T extends ParsedGradient>(
gradient: T
) => clamp(index, 0, Math.max(gradient.stops.length - 1, 0));
+/**
+ * Updates a gradient stop with automatic hint offset maintenance.
+ * When a stop's position changes and it has a hint, the hint is adjusted
+ * to maintain the same offset relative to the stop's new position.
+ * This matches the behavior of the gradient picker during drag operations.
+ */
+export const updateGradientStop = <T extends ParsedGradient>(
+ gradient: T,
+ stopIndex: number,
+ updater: (stop: GradientStop) => GradientStop
+): T => {
+ const currentStop = gradient.stops[stopIndex];
+ if (currentStop === undefined) {
+ return gradient;
+ }
+
+ // Calculate hint offset before updating (like gradient picker does)
+ const currentPosition = getStopPosition(currentStop);
+ const currentHint =
+ currentStop.hint?.type === "unit" && currentStop.hint.unit === "%"
+ ? currentStop.hint.value
+ : undefined;
+ const hintOffset =
+ currentHint !== undefined ? currentHint - currentPosition : 0;
+
+ const stops = gradient.stops.map((stop, index) => {
+ if (index !== stopIndex) {
+ return stop;
+ }
+
+ const updatedStop = updater(stop);
+
+ // If position changed and stop has a hint, maintain the hint offset
+ if (
+ hintOffset !== 0 &&
+ stop.hint?.type === "unit" &&
+ stop.hint.unit === "%" &&
+ updatedStop.position !== stop.position
+ ) {
+ const newPosition = getStopPosition(updatedStop);
+ return {
+ ...updatedStop,
+ hint: createPercentUnitValue(newPosition + hintOffset),
+ };
+ }
+
+ return updatedStop;
+ });
+
+ return {
+ ...gradient,
+ stops,
+ };
+};
+
const parseColorString = (value: string): GradientStop["color"] | undefined => {
const parsed = parseCssValue("color", value);
if (
@@ -1036,13 +1170,6 @@ export type BackgroundType =
| "radialGradient"
| "solid";
-const getGradientColorSignature = (color?: GradientStop["color"]) => {
- if (color === undefined) {
- return;
- }
- return toValue(color as StyleValue);
-};
-
export const isSolidLinearGradient = (gradient: ParsedLinearGradient) => {
// Only consider it a solid gradient if there are exactly 2 stops
if (gradient.stops.length !== 2) {
@@ -1055,8 +1182,8 @@ export const isSolidLinearGradient = (gradient: ParsedLinearGradient) => {
const secondStop = normalized.stops[1];
// Check if both stops have the same color
- const firstColor = getGradientColorSignature(firstStop?.color);
- const secondColor = getGradientColorSignature(secondStop?.color);
+ const firstColor = firstStop?.color ? toValue(firstStop.color) : undefined;
+ const secondColor = secondStop?.color ? toValue(secondStop.color) : undefined;
if (
firstColor === undefined ||
@@ -1115,7 +1242,9 @@ type GradientByType<T extends GradientType> = Extract<
{ type: T }
>;
-// Cache for parsed gradients - avoids re-parsing the same gradient string
+/**
+ * Cached to avoid re-parsing the same string.
+ */
const parsedGradientCache = new Map<string, ParsedGradient | undefined>();
export const parseAnyGradient = (value: string): ParsedGradient | undefined => {
@@ -1159,6 +1288,11 @@ export const convertGradientToTarget = <Target extends GradientType>(
return converted as GradientByType<Target>;
};
+/**
+ * Formats a gradient for a specific background type.
+ * Handles solid color conversion and gradient type conversions.
+ * Returns the formatted CSS gradient string.
+ */
export const formatGradientForType = (
styleValue: StyleValue | undefined,
target: Exclude<BackgroundType, "image">
@@ -1180,6 +1314,11 @@ export const formatGradientForType = (
return formatRadialGradient(parsed);
};
+/**
+ * Detects the background type from a StyleValue.
+ * Returns "solid" for uniform linear gradients, specific gradient types for gradients,
+ * and "image" for non-gradient values or unparseable gradients.
+ */
export const detectBackgroundType = (
styleValue?: StyleValue
): BackgroundType => {
@@ -1230,6 +1369,11 @@ export const detectBackgroundType = (
return "image";
};
+/**
+ * Gets a specific background layer item from a ComputedStyleDecl.
+ * For index 0, returns the first layer or the cascaded value itself.
+ * For index > 0, delegates to getRepeatedStyleItem.
+ */
export const getBackgroundStyleItem = (
styleDecl: ComputedStyleDecl,
index: number
diff --git a/packages/design-system/src/components/gradient-picker.tsx b/packages/design-system/src/components/gradient-picker.tsx
index 40b552473c..fe6a89a80c 100644
--- a/packages/design-system/src/components/gradient-picker.tsx
+++ b/packages/design-system/src/components/gradient-picker.tsx
@@ -9,6 +9,7 @@ import {
useCallback,
useRef,
useEffect,
+ useMemo,
type KeyboardEvent,
type MouseEvent,
type PointerEvent as ReactPointerEvent,
@@ -32,7 +33,7 @@ import {
extend([mixPlugin]);
-type GradientPickerProps<T extends ParsedGradient = ParsedGradient> = {
+export type GradientPickerProps<T extends ParsedGradient = ParsedGradient> = {
gradient: T;
backgroundImage: string;
onChange: (value: T) => void;
@@ -79,41 +80,180 @@ const toRgbColor = (
}
};
-const cloneColor = (
- color: GradientStop["color"] | undefined
-): GradientStop["color"] | undefined => {
- if (color === undefined) {
- return;
+const computePositionFromClientX = (
+ sliderElement: HTMLElement,
+ clientX: number
+) => {
+ const rect = sliderElement.getBoundingClientRect();
+ if (rect.width === 0) {
+ return 0;
}
+ const relativePosition = clientX - rect.left;
+ return clamp(Math.round((relativePosition / rect.width) * 100), 0, 100);
+};
- return { ...color };
+const getStopPositionValue = (stop: GradientStop): number => {
+ return stop.position?.type === "unit" ? stop.position.value : 0;
};
-export const GradientPicker = <T extends ParsedGradient>(
- props: GradientPickerProps<T>
-) => {
- const {
- gradient,
- backgroundImage,
- onChange,
- onChangeComplete,
- onThumbSelect,
- selectedStopIndex,
- } = props;
+const createPercentUnit = (value: number) => ({
+ type: "unit" as const,
+ unit: "%" as const,
+ value,
+});
+
+const createDragHandler = (threshold: number = DRAG_THRESHOLD) => {
+ let pointerAbortController: AbortController | undefined;
+ let clickAbortController: AbortController | undefined;
+
+ const handlePointerDown = (options: {
+ event: ReactPointerEvent<HTMLDivElement>;
+ onDragMove: (position: number) => void;
+ onDragStart?: () => void;
+ onDragEnd?: () => void;
+ }) => {
+ const { event } = options;
+ const pointerId = event.pointerId;
+ const target = event.currentTarget as HTMLDivElement;
+ const startX = event.clientX;
+ let hasDragged = false;
+
+ // Find the slider element using closest with data attribute
+ const sliderElement = target.closest("[data-gradient-slider]") as
+ | HTMLElement
+ | undefined;
+ if (sliderElement === undefined) {
+ return;
+ }
+
+ // Abort any previous drag session that might still be active
+ cleanup();
+
+ // Create a new abort controller for this drag session
+ pointerAbortController = new AbortController();
+ const pointerSignal = pointerAbortController.signal;
+
+ // Create a separate abort controller for the click handler
+ clickAbortController = new AbortController();
+ const clickSignal = clickAbortController.signal;
+
+ // Capture pointer immediately if threshold is 0 (e.g., for hints)
+ if (threshold === 0) {
+ event.preventDefault();
+ target.setPointerCapture(pointerId);
+ }
+
+ const handlePointerMove = (moveEvent: Event) => {
+ if (!(moveEvent instanceof PointerEvent)) {
+ return;
+ }
+ if (!hasDragged) {
+ if (Math.abs(moveEvent.clientX - startX) <= threshold) {
+ return;
+ }
+ hasDragged = true;
+ if (threshold !== 0) {
+ target.setPointerCapture(pointerId);
+ }
+ options.onDragStart?.();
+ }
+ const newPosition = computePositionFromClientX(
+ sliderElement,
+ moveEvent.clientX
+ );
+ options.onDragMove(newPosition);
+ };
+
+ // Prevent click event from firing if drag occurred
+ // Use document-level listener to catch clicks even if they happen outside the target
+ const handleClick = (event: Event) => {
+ if (hasDragged) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ // Cleanup after click fires
+ clickAbortController?.abort();
+ clickAbortController = undefined;
+ };
+ document.addEventListener("click", handleClick, {
+ capture: true,
+ signal: clickSignal,
+ });
+
+ const handlePointerUp = () => {
+ if (target.hasPointerCapture(pointerId)) {
+ target.releasePointerCapture(pointerId);
+ }
+ if (hasDragged) {
+ options.onDragEnd?.();
+ }
+ // Don't abort immediately - click event needs to fire first
+ // Defer cleanup to allow click event to be processed
+ setTimeout(() => {
+ pointerAbortController?.abort();
+ pointerAbortController = undefined;
+ }, 0);
+ };
+
+ document.addEventListener("pointermove", handlePointerMove, {
+ signal: pointerSignal,
+ });
+ document.addEventListener("pointerup", handlePointerUp, {
+ signal: pointerSignal,
+ });
+ document.addEventListener("pointercancel", handlePointerUp, {
+ signal: pointerSignal,
+ });
+ };
+
+ const cleanup = () => {
+ pointerAbortController?.abort();
+ pointerAbortController = undefined;
+ clickAbortController?.abort();
+ clickAbortController = undefined;
+ };
+
+ return { handlePointerDown, cleanup };
+};
+
+export const GradientPicker = <T extends ParsedGradient>({
+ gradient,
+ backgroundImage,
+ onChange,
+ onChangeComplete,
+ onThumbSelect,
+ selectedStopIndex,
+}: GradientPickerProps<T>) => {
const [stops, setStops] = useState<Array<GradientStop>>(gradient.stops);
const [selectedStop, setSelectedStop] = useState<number | undefined>();
const [isHoveredOnStop, setIsHoveredOnStop] = useState<boolean>(false);
+ const [draggingStop, setDraggingStop] = useState<number | undefined>();
const [colorPickerOpenStop, setColorPickerOpenStop] = useState<
number | undefined
>();
- const sliderRef = useRef<HTMLDivElement | null>(null);
- const thumbRefs = useRef<Array<HTMLDivElement | null>>([]);
+ const sliderRef = useRef<HTMLDivElement | undefined>(undefined);
+ const thumbRefs = useRef<Array<HTMLDivElement | undefined>>([]);
const stopsRef = useRef(stops);
+ const handleSliderRef = useCallback((element: HTMLDivElement | null) => {
+ sliderRef.current = element ?? undefined;
+ }, []);
+
useEffect(() => {
stopsRef.current = stops;
}, [stops]);
+ const thumbDragHandler = useMemo(() => createDragHandler(), []);
+
+ const hintDragHandler = useMemo(() => createDragHandler(0), []);
+
+ useEffect(() => {
+ return () => {
+ thumbDragHandler.cleanup();
+ hintDragHandler.cleanup();
+ };
+ }, [thumbDragHandler, hintDragHandler]);
+
useEffect(() => {
if (selectedStopIndex !== undefined) {
setSelectedStop(selectedStopIndex);
@@ -167,12 +307,14 @@ export const GradientPicker = <T extends ParsedGradient>(
)
.filter((item): item is number => item !== undefined);
const hints = gradient.stops
- .map((stop): number | undefined =>
+ .map((stop, index): { value: number; stopIndex: number } | undefined =>
stop.hint?.type === "unit" && stop.hint.unit === "%"
- ? stop.hint.value
+ ? { value: stop.hint.value, stopIndex: index }
: undefined
)
- .filter((item): item is number => item !== undefined);
+ .filter(
+ (item): item is { value: number; stopIndex: number } => item !== undefined
+ );
const updateStops = useCallback(
(
@@ -221,11 +363,29 @@ export const GradientPicker = <T extends ParsedGradient>(
}
return {
...stop,
- position: {
- type: "unit",
- unit: "%",
- value: nextValue,
- },
+ position: createPercentUnit(nextValue),
+ };
+ });
+ }, type);
+ },
+ [updateStops]
+ );
+
+ const updateStopHint = useCallback(
+ (index: number, value: number, type: "change" | "complete") => {
+ const nextValue = clamp(value, 0, 100);
+ updateStops((currentStops) => {
+ if (index < 0 || index >= currentStops.length) {
+ return currentStops;
+ }
+
+ return currentStops.map((stop, stopIndex) => {
+ if (stopIndex !== index) {
+ return stop;
+ }
+ return {
+ ...stop,
+ hint: createPercentUnit(nextValue),
};
});
}, type);
@@ -283,15 +443,6 @@ export const GradientPicker = <T extends ParsedGradient>(
}
}, [colorPickerOpenStop, stops.length]);
- const computePositionFromClientX = useCallback((clientX: number) => {
- const rect = sliderRef.current?.getBoundingClientRect();
- if (rect === undefined || rect.width === 0) {
- return 0;
- }
- const relativePosition = clientX - rect.left;
- return clamp(Math.round((relativePosition / rect.width) * 100), 0, 100);
- }, []);
-
const checkIfStopExistsAtPosition = useCallback(
(
clientX: number
@@ -299,10 +450,14 @@ export const GradientPicker = <T extends ParsedGradient>(
isStopExistingAtPosition: boolean;
newPosition: number;
} => {
- const rect = sliderRef.current?.getBoundingClientRect();
- const newPosition = computePositionFromClientX(clientX);
+ const sliderElement = sliderRef.current;
+ if (sliderElement === undefined) {
+ return { isStopExistingAtPosition: false, newPosition: 0 };
+ }
+ const rect = sliderElement.getBoundingClientRect();
+ const newPosition = computePositionFromClientX(sliderElement, clientX);
- if (rect === undefined || rect.width === 0) {
+ if (rect.width === 0) {
return { isStopExistingAtPosition: false, newPosition };
}
@@ -314,7 +469,7 @@ export const GradientPicker = <T extends ParsedGradient>(
return { isStopExistingAtPosition, newPosition };
},
- [computePositionFromClientX, positions]
+ [positions]
);
const handleStopSelected = useCallback(
@@ -337,71 +492,117 @@ export const GradientPicker = <T extends ParsedGradient>(
const handleThumbPointerDown = useCallback(
(index: number, stop: GradientStop) =>
(event: ReactPointerEvent<HTMLDivElement>) => {
- event.stopPropagation();
// Don't start drag if the color picker is open for this thumb
if (colorPickerOpenStop === index) {
+ event.stopPropagation();
return;
}
handleStopSelected(index, stop);
setIsHoveredOnStop(true);
- const pointerId = event.pointerId;
- const target = event.currentTarget as HTMLDivElement;
- const startX = event.clientX;
- let hasDragged = false;
- let isCleanedUp = false;
+ // Track the currently dragged stop index
+ let currentIndex = index;
+
+ // Calculate hint offset relative to stop position
+ const originalPosition = getStopPositionValue(stop);
+ const originalHint =
+ stop.hint?.type === "unit" ? stop.hint.value : undefined;
+ const hintOffset =
+ originalHint !== undefined ? originalHint - originalPosition : 0;
+
+ thumbDragHandler.handlePointerDown({
+ event,
+ onDragMove: (newPosition) => {
+ updateStops((currentStops) => {
+ if (currentIndex < 0 || currentIndex >= currentStops.length) {
+ return currentStops;
+ }
+
+ const clampedPosition = clamp(newPosition, 0, 100);
+
+ // Update the position of the dragged stop and maintain hint offset
+ const updatedStops = currentStops.map((stop, stopIndex) => {
+ if (stopIndex !== currentIndex) {
+ return stop;
+ }
- const cleanup = () => {
- if (isCleanedUp) {
- return;
- }
- isCleanedUp = true;
-
- target.removeEventListener("pointermove", handlePointerMove);
- target.removeEventListener("pointerup", handlePointerUp);
- target.removeEventListener("pointercancel", handlePointerUp);
- setIsHoveredOnStop(false);
- if (target.hasPointerCapture(pointerId)) {
- target.releasePointerCapture(pointerId);
- }
- };
+ const updatedStop: GradientStop = {
+ ...stop,
+ position: createPercentUnit(clampedPosition),
+ };
+
+ // Update hint to maintain the same offset relative to the stop
+ if (stop.hint?.type === "unit") {
+ const newHintPosition = clamp(
+ clampedPosition + hintOffset,
+ 0,
+ 100
+ );
+ updatedStop.hint = createPercentUnit(newHintPosition);
+ }
- const handlePointerMove = (moveEvent: PointerEvent) => {
- if (!hasDragged) {
- if (Math.abs(moveEvent.clientX - startX) <= DRAG_THRESHOLD) {
- return;
- }
- hasDragged = true;
- target.setPointerCapture(pointerId);
+ return updatedStop;
+ });
+
+ // Sort stops by position and track where our dragged stop ends up
+ const draggedStop = updatedStops[currentIndex];
+ const sortedStops = [...updatedStops].sort((stopA, stopB) => {
+ return (
+ getStopPositionValue(stopA) - getStopPositionValue(stopB)
+ );
+ });
+
+ // Find the new index of the dragged stop
+ const newIndex = sortedStops.findIndex(
+ (stop) => stop === draggedStop
+ );
+ if (newIndex !== -1 && newIndex !== currentIndex) {
+ currentIndex = newIndex;
+ setSelectedStop(newIndex);
+ setDraggingStop(newIndex);
+ }
+
+ return sortedStops;
+ }, "change");
+ },
+ onDragStart: () => {
setColorPickerOpenStop(undefined);
- }
- const newPosition = computePositionFromClientX(moveEvent.clientX);
- updateStopPosition(index, newPosition, "change");
- };
-
- const handlePointerUp = () => {
- cleanup();
- if (hasDragged) {
+ setDraggingStop(currentIndex);
+ },
+ onDragEnd: () => {
+ setIsHoveredOnStop(false);
+ setDraggingStop(undefined);
onChangeComplete(buildGradient(stopsRef.current));
- }
- hasDragged = false;
- };
-
- target.addEventListener("pointermove", handlePointerMove);
- target.addEventListener("pointerup", handlePointerUp);
- target.addEventListener("pointercancel", handlePointerUp);
+ },
+ });
},
[
colorPickerOpenStop,
- computePositionFromClientX,
- onChangeComplete,
handleStopSelected,
- updateStopPosition,
+ thumbDragHandler,
+ updateStops,
+ onChangeComplete,
buildGradient,
]
);
+ const handleHintPointerDown = useCallback(
+ (index: number) => (event: ReactPointerEvent<HTMLDivElement>) => {
+ event.stopPropagation();
+ hintDragHandler.handlePointerDown({
+ event,
+ onDragMove: (newPosition) => {
+ updateStopHint(index, newPosition, "change");
+ },
+ onDragEnd: () => {
+ onChangeComplete(buildGradient(stopsRef.current));
+ },
+ });
+ },
+ [hintDragHandler, updateStopHint, onChangeComplete, buildGradient]
+ );
+
const handleKeyDown = useCallback(
(event: KeyboardEvent<HTMLDivElement>) => {
if (selectedStop === undefined) {
@@ -504,7 +705,7 @@ export const GradientPicker = <T extends ParsedGradient>(
(event: ReactPointerEvent<HTMLDivElement>) => {
if (
event.target instanceof HTMLElement &&
- event.target.closest("[data-thumb='true']")
+ event.target.closest("[data-gradient-thumb='true']")
) {
return;
}
@@ -564,9 +765,9 @@ export const GradientPicker = <T extends ParsedGradient>(
b: interpolationColor.b,
};
} else if (prevColor !== undefined) {
- newColor = cloneColor(prevColor);
+ newColor = { ...prevColor };
} else if (nextColor !== undefined) {
- newColor = cloneColor(nextColor);
+ newColor = { ...nextColor };
} else {
newColor = { ...defaultStopColor };
}
@@ -639,7 +840,8 @@ export const GradientPicker = <T extends ParsedGradient>(
onKeyDown={handleKeyDown}
>
<SliderRoot
- ref={sliderRef}
+ ref={handleSliderRef}
+ data-gradient-slider
css={{ backgroundImage }}
isHoveredOnStop={isHoveredOnStop}
tabIndex={0}
@@ -654,6 +856,7 @@ export const GradientPicker = <T extends ParsedGradient>(
<SliderTrack />
{stops.map((stop, index) => {
const isSelected = selectedStop === index;
+ const isDragging = draggingStop === index;
if (
stop.color === undefined ||
stop.position?.type !== "unit" ||
@@ -667,9 +870,10 @@ export const GradientPicker = <T extends ParsedGradient>(
return (
<SliderThumb
key={index}
- data-thumb="true"
+ data-gradient-thumb="true"
style={{
left: `${stop.position.value}%`,
+ zIndex: isDragging ? 2 : 1,
}}
role="slider"
aria-orientation="horizontal"
@@ -680,7 +884,7 @@ export const GradientPicker = <T extends ParsedGradient>(
aria-selected={isSelected}
tabIndex={-1}
ref={(element) => {
- thumbRefs.current[index] = element;
+ thumbRefs.current[index] = element ?? undefined;
}}
onPointerDown={handleThumbPointerDown(index, stop)}
onClick={() => {
@@ -711,7 +915,7 @@ export const GradientPicker = <T extends ParsedGradient>(
width: THUMB_HEIGHT,
height: THUMB_HEIGHT,
}}
- data-thumb="true"
+ data-gradient-thumb="true"
/>
}
/>
@@ -720,11 +924,21 @@ export const GradientPicker = <T extends ParsedGradient>(
);
})}
- {hints.map((hint) => (
- <SliderHint key={hint} css={{ left: `${hint}%` }}>
- <ChevronFilledUpIcon size="100%" />
- </SliderHint>
- ))}
+ {hints.map((hint) => {
+ const stop = stops[hint.stopIndex];
+ const hintColor = stop?.color
+ ? colord(styleValueToRgbaColor(stop.color)).toHex()
+ : undefined;
+ return (
+ <SliderHint
+ key={`${hint.stopIndex}-${hint.value}`}
+ style={{ left: `${hint.value}%`, color: hintColor }}
+ onPointerDown={handleHintPointerDown(hint.stopIndex)}
+ >
+ <ChevronFilledUpIcon size="100%" />
+ </SliderHint>
+ );
+ })}
</SliderRoot>
</Flex>
);
@@ -810,13 +1024,17 @@ const SliderThumbPointer = styled("div", {
const SliderHint = styled(Flex, {
position: "absolute",
- top: `calc(-1 * ${theme.spacing[6]})`,
+ top: `100%`,
width: theme.spacing[7],
height: theme.spacing[7],
- pointerEvents: "none",
+ pointerEvents: "auto",
transform: "translateX(-50%)",
alignItems: "center",
justifyContent: "center",
+ cursor: "grab",
+ touchAction: "none",
+ userSelect: "none",
+ "&:active": {
+ cursor: "grabbing",
+ },
});
-
-export type { GradientPickerProps };