refactor: replace react colour picker with svelte gradient picker

This commit is contained in:
Jones Jankovic committed 2026-11-02 18:55:31 +10:30
1 parent 52d5713234
commit 27520dc6ba
12 files changed
+885 -491

No files matched your search

-103
View File
@@ -1,103 +0,0 @@
div:has(> #rbgcp-wrapper) {
background: transparent !important;
}
#rbgcp-inputs-wrap {
padding-top: 4px !important;
margin-bottom: -8px;
#rbgcp-hex-input,
#rbgcp-input {
height: 28px !important;
}
}
.dark {
#rbgcp-wrapper {
div[style="padding-top: 11px; position: relative;"] div {
color: white !important;
}
#rbgcp-inputs-wrap #rbgcp-hex-input,
#rbgcp-inputs-wrap #rbgcp-input {
color: white !important;
background-color: #37373b !important;
border: none !important;
}
div:has(> #rbgcp-solid-btn),
div:has(> #rbgcp-advanced-btn),
#rbgcp-color-model-btn > div,
#rbgcp-gradient-controls-wrap {
background-color: #37373b !important;
color: white !important;
svg {
circle {
fill: white !important;
}
polyline,
line,
g,
path {
stroke: white !important;
}
}
#rbgcp-radial-btn,
#rbgcp-linear-btn {
&[style*="background: white;"] {
background-color: #28282b !important;
}
svg {
path,
g,
polyline,
circle {
stroke: white !important;
fill: transparent !important;
}
}
}
div:has(> #rbgcp-stop-input) svg {
path {
stroke: unset !important;
fill: white !important;
}
}
#rbgcp-comparibles-btn svg path {
fill: white !important;
}
> div {
color: white !important;
&[style*="background: white;"] {
background: #28282b !important;
}
}
}
div:has(> #rbgcp-degree-input) {
width: 70px !important;
}
#rbgcp-degree-input {
width: 50px !important;
}
#rbgcp-degree-input,
#rbgcp-stop-input {
color: white !important;
}
#rbgcp-gradient-controls-wrap > div,
#rbgcp-gradient-controls-wrap > div > div:not([role="button"]) {
background-color: #37373b !important;
}
}
}
+81 -75
View File
@@ -1,105 +1,113 @@
<script lang="ts">
import { onMount } from 'svelte'
import type { Component } from 'svelte'
import { animate } from 'motion';
import { delay } from '@/seqta/utils/delay.ts'
import { settingsState } from '@/seqta/utils/listeners/SettingsState.ts'
import { delay } from '@/seqta/utils/delay'
import { settingsState } from '@/seqta/utils/listeners/SettingsState'
import GradientPicker from './colourPicker/GradientPicker.svelte'
const { hidePicker, standalone = false, savePresets = true, customOnChange = null, customState = null } = $props<{
hidePicker?: () => void,
standalone?: boolean,
savePresets?: boolean,
customOnChange?: (color: string) => void,
customState?: string
}>();
const PRESETS_KEY = 'colorPickerPresets';
const MAX_PRESETS = 18;
const DEFAULT_PRESETS = [
"linear-gradient(30deg, rgba(229,209,218,1) 0%, RGBA(235,169,202,1) 46%, rgba(214,155,162,1) 100%)",
"linear-gradient(40deg, rgba(201,61,0,1) 0%, RGBA(170, 5, 58, 1) 100%)",
"linear-gradient(40deg, rgba(0, 141, 201, 0.76) 0%, rgba(8, 5, 170, 0.66) 100%)",
"linear-gradient(40deg, rgba(0, 201, 20, 0.76) 0%, rgba(4, 160, 105, 0.66) 100%)",
"linear-gradient(40deg, rgba(199, 20, 55, 0.76) 0%, rgba(95, 11, 160, 0.66) 100%)",
"linear-gradient(40deg, rgba(24, 20, 199, 0.76) 0%, rgba(23, 173, 65, 0.66) 100%)",
"radial-gradient(circle, rgba(20, 199, 178, 0.76) 32%, rgba(3, 120, 57, 0.66) 100%)",
"radial-gradient(circle, rgba(13, 15, 145, 0.76) 12%, rgba(103, 3, 120, 0.66) 100%)",
"linear-gradient(20deg, rgb(230, 21, 21) 0%, rgb(230, 109, 21) 12%, rgb(230, 34, 21) 26%, rgb(230, 21, 21) 39%, rgb(230, 84, 21) 48%, rgb(230, 34, 21) 58%, rgb(230, 96, 21) 69%, rgb(230, 34, 21) 80%, rgb(230, 71, 21) 89%, rgb(230, 21, 21) 100%)",
"rgba(114, 1, 170, 0.89)",
"rgba(93, 135, 63, 0.89)",
"rgba(4, 4, 138, 0.77)",
"rgba(21, 20, 20, 0.89)",
"linear-gradient(340deg, rgb(205, 74, 82) 18%, rgba(132, 8, 8, 0.89) 46%, rgb(204, 78, 85) 72%)",
"radial-gradient(circle, rgb(74, 205, 158) 0%, rgba(8, 72, 132, 0.89) 99%)",
"rgba(17, 94, 89, 1)",
"rgba(30, 64, 175, 0.89)",
"rgba(134, 25, 143, 1)",
"rgba(14, 165, 233, 0.9)",
];
const {
hidePicker,
standalone = false,
savePresets = true,
customOnChange = null,
customState = null,
}: {
hidePicker?: () => void;
standalone?: boolean;
savePresets?: boolean;
customOnChange?: ((color: string) => void) | null;
customState?: string | null;
} = $props();
let background = $state<HTMLDivElement | null>(null);
let content = $state<HTMLDivElement | null>(null);
let ReactAdapter = $state<Component | null>(null);
let ColourPickerEl = $state<unknown>(null);
let pickerReady = $state(false);
let presets = $state<string[]>(loadPresets());
let current = $state(initialColour());
const loadPicker = async () => {
const [adapterMod, pickerMod] = await Promise.all([
import('./utils/ReactAdapter.svelte'),
import('./ColourPicker.tsx'),
]);
ReactAdapter = adapterMod.default;
ColourPickerEl = pickerMod.default;
pickerReady = true;
};
function initialColour(): string {
return customState ?? settingsState.selectedColor ?? '';
}
function loadPresets(): string[] {
try {
const saved = JSON.parse(localStorage.getItem(PRESETS_KEY) ?? 'null');
return Array.isArray(saved) ? saved : DEFAULT_PRESETS;
} catch {
return DEFAULT_PRESETS;
}
}
function rememberPreset(colour: string) {
if (!colour || presets[0] === colour) return;
const updated = [colour, ...presets.filter((preset) => preset !== colour)].slice(0, MAX_PRESETS);
localStorage.setItem(PRESETS_KEY, JSON.stringify(updated));
}
function handleChange(colour: string) {
current = colour;
if (customOnChange) customOnChange(colour);
else settingsState.selectedColor = colour;
}
const closePicker = async () => {
if (standalone) return;
if (!background || !content) return;
if (standalone || !background || !content) return;
animate(
content,
{ scale: [1, 0.4], opacity: [1, 0] },
{
type: 'spring',
stiffness: 400,
damping: 30
}
);
animate(
background,
{ opacity: [1, 0] },
{ ease: [0.4, 0, 0.2, 1] }
);
animate(content, { scale: [1, 0.4], opacity: [1, 0] }, { type: 'spring', stiffness: 400, damping: 30 });
animate(background, { opacity: [1, 0] }, { ease: [0.4, 0, 0.2, 1] });
await delay(400);
hidePicker?.();
}
onMount(() => {
void loadPicker().then(() => {
if (standalone) return;
if (!background || !content) return;
if (!standalone && background && content) {
animate(background, { opacity: [0, 1] }, { duration: 0.3, ease: [0.4, 0, 0.2, 1] });
animate(content, { scale: [0.4, 1], opacity: [0, 1] }, { type: 'spring', stiffness: 400, damping: 30 });
}
animate(
background,
{ opacity: [0, 1] },
{ duration: 0.3, ease: [0.4, 0, 0.2, 1] }
);
animate(
content,
{ scale: [0.4, 1], opacity: [0, 1] },
{
type: 'spring',
stiffness: 400,
damping: 30
}
);
});
const handleEscapeKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
closePicker();
}
const handleEscapeKey = (event: KeyboardEvent) => {
if (event.key === 'Escape') closePicker();
};
document.addEventListener('keydown', handleEscapeKey);
return () => {
document.removeEventListener('keydown', handleEscapeKey);
if (savePresets && !customOnChange) rememberPreset(current);
};
});
function handleBackgroundClick(event: MouseEvent) {
if (event.target === background) {
closePicker();
}
if (event.target === background) closePicker();
}
</script>
{#if standalone}
<div class="h-auto overflow-clip rounded-xl {$settingsState.DarkMode ? 'dark' : ''}">
{#if pickerReady && ReactAdapter && ColourPickerEl}
<ReactAdapter customOnChange={customOnChange} customState={customState} savePresets={savePresets} el={ColourPickerEl} />
{/if}
<div class="h-auto {$settingsState.DarkMode ? 'dark' : ''}">
<GradientPicker value={customState ?? current} onchange={handleChange} {presets} />
</div>
{:else}
<!-- svelte-ignore a11y_no_static_element_interactions -->
@@ -107,15 +115,13 @@
bind:this={background}
class="flex absolute top-0 left-0 z-50 justify-center items-center w-full h-full shadow-2xl cursor-pointer bg-black/20 border border-[#DDDDDD]/30 dark:border-[#38373D]/30 {$settingsState.DarkMode ? 'dark' : ''}"
onclick={handleBackgroundClick}
onkeydown={(e) => { if (e.key === 'Enter') handleBackgroundClick(e as unknown as MouseEvent) }}
onkeydown={(event) => { if (event.key === 'Enter') handleBackgroundClick(event as unknown as MouseEvent) }}
>
<div
bind:this={content}
class="p-4 h-auto bg-white rounded-xl border shadow-lg cursor-auto dark:bg-zinc-800 border-zinc-100 dark:border-zinc-700"
>
{#if pickerReady && ReactAdapter && ColourPickerEl}
<ReactAdapter customOnChange={customOnChange} customState={customState} savePresets={savePresets} el={ColourPickerEl} />
{/if}
<GradientPicker value={current} onchange={handleChange} {presets} />
</div>
</div>
{/if}
-122
View File
@@ -1,122 +0,0 @@
import ColorPicker from "react-best-gradient-color-picker";
import { useEffect, useRef, useState } from "react";
import { settingsState } from "@/seqta/utils/listeners/SettingsState.ts";
const defaultPresets = [
"linear-gradient(30deg, rgba(229,209,218,1) 0%, RGBA(235,169,202,1) 46%, rgba(214,155,162,1) 100%)",
"linear-gradient(40deg, rgba(201,61,0,1) 0%, RGBA(170, 5, 58, 1) 100%)",
"linear-gradient(40deg, rgba(0, 141, 201, 0.76) 0%, rgba(8, 5, 170, 0.66) 100%)",
"linear-gradient(40deg, rgba(0, 201, 20, 0.76) 0%, rgba(4, 160, 105, 0.66) 100%)",
"linear-gradient(40deg, rgba(199, 20, 55, 0.76) 0%, rgba(95, 11, 160, 0.66) 100%)",
"linear-gradient(40deg, rgba(24, 20, 199, 0.76) 0%, rgba(23, 173, 65, 0.66) 100%)",
"radial-gradient(circle, rgba(20, 199, 178, 0.76) 32%, rgba(3, 120, 57, 0.66) 100%)",
"radial-gradient(circle, rgba(13, 15, 145, 0.76) 12%, rgba(103, 3, 120, 0.66) 100%)",
"linear-gradient(20deg, rgb(230, 21, 21) 0%, rgb(230, 109, 21) 12%, rgb(230, 34, 21) 26%, rgb(230, 21, 21) 39%, rgb(230, 84, 21) 48%, rgb(230, 34, 21) 58%, rgb(230, 96, 21) 69%, rgb(230, 34, 21) 80%, rgb(230, 71, 21) 89%, rgb(230, 21, 21) 100%)",
"rgba(114, 1, 170, 0.89)",
"rgba(93, 135, 63, 0.89)",
"rgba(4, 4, 138, 0.77)",
"rgba(21, 20, 20, 0.89)",
"linear-gradient(340deg, rgb(205, 74, 82) 18%, rgba(132, 8, 8, 0.89) 46%, rgb(204, 78, 85) 72%)",
"radial-gradient(circle, rgb(74, 205, 158) 0%, rgba(8, 72, 132, 0.89) 99%)",
"rgba(17, 94, 89, 1)",
"rgba(30, 64, 175, 0.89)",
"rgba(134, 25, 143, 1)",
"rgba(14, 165, 233, 0.9)",
];
interface PickerProps {
customOnChange?: (color: string) => void;
customState?: string;
savePresets?: boolean;
}
export default function Picker({
customOnChange,
customState,
savePresets = true,
}: PickerProps) {
const [customThemeColor, setCustomThemeColor] = useState<string | null>();
const [presets, setPresets] = useState<string[]>();
const latestValuesRef = useRef({
customThemeColor,
customOnChange,
savePresets,
presets,
});
useEffect(() => {
if (customState !== undefined && customState !== null) {
setCustomThemeColor(customState);
} else {
setCustomThemeColor(settingsState.selectedColor ?? null);
}
if (presets === undefined) {
const savedPresets = localStorage.getItem("colorPickerPresets");
setPresets(savedPresets ? JSON.parse(savedPresets) : defaultPresets);
}
}, []);
useEffect(() => {
latestValuesRef.current = {
customThemeColor,
customOnChange,
savePresets,
presets,
};
}, [customThemeColor, customOnChange, savePresets, presets]);
useEffect(() => {
return () => {
const { customThemeColor, customOnChange, savePresets, presets } =
latestValuesRef.current;
if (!(customThemeColor && !customOnChange && savePresets && presets))
return;
// Only proceed if presets are different (avoid unnecessary updates)
const existingIndex = presets.indexOf(customThemeColor);
let updatedPresets;
if (existingIndex === 0) {
// No need to update if the selected color is already the first element
return;
} else if (existingIndex > -1) {
updatedPresets = [
customThemeColor,
...presets.slice(0, existingIndex),
...presets.slice(existingIndex + 1),
];
} else {
updatedPresets = [customThemeColor, ...presets].slice(0, 18);
}
localStorage.setItem(
"colorPickerPresets",
JSON.stringify(updatedPresets),
);
};
}, []);
useEffect(() => {
if (customThemeColor && !customOnChange) {
settingsState.selectedColor = customThemeColor;
}
}, [customThemeColor, customOnChange]);
return (
<ColorPicker
disableDarkMode={true}
presets={presets}
value={customThemeColor ?? ""}
onChange={(color: string) => {
if (customOnChange) {
customOnChange(color);
setCustomThemeColor(color);
} else {
setCustomThemeColor(color);
}
}}
/>
);
}
@@ -0,0 +1,517 @@
<script lang="ts">
import { untrack } from "svelte";
import { slide } from "svelte/transition";
import {
clamp,
colourAt,
formatColour,
formatStops,
formatValue,
hsvaToRgba,
parseColour,
parseValue,
rgbaToHex,
rgbaToHsva,
type ColourValue,
type GradientStop,
type Hsva,
type Rgba,
} from "./colourValue";
type EyeDropperApi = { open: () => Promise<{ sRGBHex: string }> };
let {
value,
onchange,
presets = [],
}: {
value: string;
onchange: (value: string) => void;
presets?: string[];
} = $props();
const MODES = [
{ kind: "solid", label: "Solid" },
{ kind: "linear", label: "Linear" },
{ kind: "radial", label: "Radial" },
] as const;
const CHECKERBOARD = "repeating-conic-gradient(#d4d4d8 0% 25%, #ffffff 0% 50%) 50% / 8px 8px";
const EyeDropper = (globalThis as { EyeDropper?: new () => EyeDropperApi }).EyeDropper;
const initial = untrack(() => parseValue(value));
let model = $state<ColourValue>(initial);
let selected = $state(0);
let hsva = $state<Hsva>(rgbaToHsva(colourOf(initial, 0)));
let lastAngle = initial.kind === "linear" ? initial.angle : 90;
let lastEmitted = untrack(() => value);
let area = $state<HTMLDivElement>();
let bar = $state<HTMLDivElement>();
let dragging = $state<number | null>(null);
const active = $derived(colourOf(model, selected));
const hex = $derived(rgbaToHex(active));
const stops = $derived(model.kind === "solid" ? [] : model.stops);
const shownPresets = $derived([...new Set(presets)].slice(0, 18));
const modeIndex = $derived(MODES.findIndex((mode) => mode.kind === model.kind));
$effect(() => {
if (value === lastEmitted) return;
lastEmitted = value;
load(parseValue(value));
});
function asLayer(css: string): string {
return /gradient\(/i.test(css) ? css : `linear-gradient(${css}, ${css})`;
}
function colourOf(m: ColourValue, index: number): Rgba {
return m.kind === "solid" ? m.colour : m.stops[Math.min(index, m.stops.length - 1)].colour;
}
function load(next: ColourValue) {
if (next.kind === "linear") lastAngle = next.angle;
model = next;
selected = 0;
hsva = rgbaToHsva(colourOf(next, 0));
}
function commit(next: ColourValue) {
model = next;
lastEmitted = formatValue(next);
onchange(lastEmitted);
}
function snapshot(): ColourValue {
return $state.snapshot(model) as ColourValue;
}
function withStops(m: ColourValue, update: (stops: GradientStop[]) => GradientStop[]): ColourValue {
return m.kind === "solid" ? m : { ...m, stops: update(m.stops) };
}
function setActiveColour(colour: Rgba) {
const m = snapshot();
commit(
m.kind === "solid"
? { kind: "solid", colour }
: withStops(m, (all) => all.map((stop, i) => (i === selected ? { ...stop, colour } : stop))),
);
}
function updateHsva(next: Partial<Hsva>) {
hsva = { ...hsva, ...next };
setActiveColour(hsvaToRgba(hsva));
}
function setRgba(colour: Rgba) {
hsva = rgbaToHsva(colour);
setActiveColour(colour);
}
function selectStop(index: number) {
selected = index;
hsva = rgbaToHsva(colourOf(model, index));
}
function setMode(kind: ColourValue["kind"]) {
const m = snapshot();
if (m.kind === kind) return;
const colour = colourOf(m, selected);
const base = rgbaToHsva(colour);
const gradientStops =
m.kind === "solid"
? [
{ colour, position: 0 },
{ colour: hsvaToRgba({ ...base, h: (base.h + 60) % 360 }), position: 100 },
]
: m.stops;
const next: ColourValue =
kind === "solid"
? { kind, colour }
: kind === "linear"
? { kind, angle: lastAngle, stops: gradientStops }
: { kind, stops: gradientStops };
load(next);
commit(next);
}
function pickArea(event: PointerEvent) {
const rect = area!.getBoundingClientRect();
updateHsva({
s: clamp((event.clientX - rect.left) / rect.width, 0, 1) * 100,
v: (1 - clamp((event.clientY - rect.top) / rect.height, 0, 1)) * 100,
});
}
function areaKeys(event: KeyboardEvent) {
const step = event.shiftKey ? 10 : 1;
const moves: Record<string, Partial<Hsva>> = {
ArrowLeft: { s: clamp(hsva.s - step, 0, 100) },
ArrowRight: { s: clamp(hsva.s + step, 0, 100) },
ArrowDown: { v: clamp(hsva.v - step, 0, 100) },
ArrowUp: { v: clamp(hsva.v + step, 0, 100) },
};
if (!moves[event.key]) return;
event.preventDefault();
updateHsva(moves[event.key]);
}
function barPosition(event: PointerEvent): number {
const rect = bar!.getBoundingClientRect();
return Math.round(clamp((event.clientX - rect.left) / rect.width, 0, 1) * 100);
}
function moveStop(index: number, position: number) {
commit(withStops(snapshot(), (all) => all.map((stop, i) => (i === index ? { ...stop, position } : stop))));
}
function startStopDrag(event: PointerEvent, index: number) {
event.stopPropagation();
selectStop(index);
bar!.setPointerCapture(event.pointerId);
dragging = index;
}
function addStop(event: PointerEvent) {
const m = snapshot();
if (m.kind === "solid") return;
const position = barPosition(event);
const colour = colourAt(m.stops, position);
commit(withStops(m, (all) => [...all, { colour, position }]));
selectStop(m.stops.length);
bar!.setPointerCapture(event.pointerId);
dragging = m.stops.length;
}
function removeStop(index: number) {
const m = snapshot();
if (m.kind === "solid" || m.stops.length <= 2) return;
commit(withStops(m, (all) => all.filter((_, i) => i !== index)));
selectStop(Math.min(selected, m.stops.length - 2));
}
function stopKeys(event: KeyboardEvent, index: number) {
const step = event.shiftKey ? 10 : 1;
const position = stops[index].position;
if (event.key === "ArrowLeft") moveStop(index, clamp(position - step, 0, 100));
else if (event.key === "ArrowRight") moveStop(index, clamp(position + step, 0, 100));
else if (event.key === "Delete" || event.key === "Backspace") removeStop(index);
else return;
event.preventDefault();
}
function setAngle(angle: number) {
const m = snapshot();
if (m.kind !== "linear") return;
lastAngle = clamp(Math.round(angle), 0, 360);
commit({ ...m, angle: lastAngle });
}
function setHex(input: string, final = false) {
const digits = input.trim().replace(/^#/, "");
const complete = /^[0-9a-f]{6}$/i.test(digits) || (final && /^[0-9a-f]{3}$/i.test(digits));
const parsed = complete ? parseColour(`#${digits}`) : null;
if (parsed) setRgba({ ...parsed, a: active.a });
}
async function pickFromScreen() {
if (!EyeDropper) return;
try {
const { sRGBHex } = await new EyeDropper().open();
const parsed = parseColour(sRGBHex);
if (parsed) setRgba({ ...parsed, a: active.a });
} catch {
return;
}
}
function applyPreset(preset: string) {
const next = parseValue(preset);
load(next);
commit(next);
}
</script>
<div class="flex flex-col gap-3 w-72 max-w-full text-zinc-900 select-none dark:text-white">
<div>
<div class="grid relative grid-cols-3 p-0.5 rounded-lg bg-zinc-100 dark:bg-zinc-700/70" role="radiogroup" aria-label="Fill type">
<div
class="absolute left-0.5 inset-y-0.5 w-[calc((100%-0.25rem)/3)] rounded-md bg-white shadow-sm transition-transform duration-200 ease-out motion-reduce:transition-none dark:bg-zinc-600"
style="transform: translateX({modeIndex * 100}%);"
aria-hidden="true"
></div>
{#each MODES as mode (mode.kind)}
<button
type="button"
role="radio"
aria-checked={model.kind === mode.kind}
class="relative py-1 text-xs font-medium rounded-md transition-colors duration-200 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-zinc-900 dark:focus-visible:outline-white {model.kind === mode.kind
? 'text-zinc-900 dark:text-white'
: 'text-zinc-500 hover:text-zinc-900 dark:text-zinc-300 dark:hover:text-white'}"
onclick={() => setMode(mode.kind)}
>
{mode.label}
</button>
{/each}
</div>
{#if model.kind !== "solid"}
<div class="flex gap-2 items-center pt-3" transition:slide={{ duration: 180 }}>
<div
class="flex-1 px-2.5 py-1.5 cursor-copy touch-none"
role="group"
aria-label="Gradient stops"
onpointerdown={addStop}
onpointermove={(event) => {
if (dragging !== null) moveStop(dragging, barPosition(event));
}}
onpointerup={() => (dragging = null)}
onpointercancel={() => (dragging = null)}
>
<div
bind:this={bar}
class="relative h-3 rounded-full ring-1 ring-inset ring-black/10 dark:ring-white/10"
style="background: linear-gradient(to right, {formatStops(stops)}), {CHECKERBOARD};"
>
{#each stops as stop, index (index)}
<button
type="button"
class="absolute top-1/2 handle cursor-grab active:cursor-grabbing {index === selected ? 'handle-selected' : ''}"
style="left: {stop.position}%; --swatch: {formatColour(stop.colour)};"
aria-label="Colour stop at {Math.round(stop.position)}%"
aria-pressed={index === selected}
onpointerdown={(event) => startStopDrag(event, index)}
onkeydown={(event) => stopKeys(event, index)}
></button>
{/each}
</div>
</div>
{#if model.kind === "linear"}
<label class="flex shrink-0 items-center px-2 w-14 h-7 text-xs rounded-md bg-zinc-100 dark:bg-zinc-700/70">
<input
type="number"
min="0"
max="360"
class="p-0 w-full min-w-0 text-xs text-right bg-transparent border-0 outline-none select-text picker-number focus:ring-0"
aria-label="Gradient angle in degrees"
value={model.angle}
oninput={(event) => {
if (event.currentTarget.value !== "") setAngle(Number(event.currentTarget.value));
}}
/>
<span class="text-zinc-500 dark:text-zinc-400">°</span>
</label>
{/if}
<button
type="button"
class="grid shrink-0 place-items-center rounded-md transition size-7 text-zinc-500 hover:bg-zinc-100 hover:text-zinc-900 disabled:opacity-30 disabled:pointer-events-none focus-visible:outline-2 focus-visible:outline-zinc-900 dark:text-zinc-300 dark:hover:bg-zinc-700 dark:hover:text-white dark:focus-visible:outline-white"
aria-label="Remove selected stop"
disabled={stops.length <= 2}
onclick={() => removeStop(selected)}
>
<svg viewBox="0 0 24 24" class="size-4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M3 6h18M8 6V4h8v2m-9 0 1 14h8l1-14" />
</svg>
</button>
</div>
{/if}
</div>
<div
bind:this={area}
class="relative h-40 rounded-lg cursor-crosshair touch-none outline-none ring-1 ring-inset ring-black/10 focus-visible:ring-2 focus-visible:ring-zinc-900 dark:ring-white/10 dark:focus-visible:ring-white"
style="background: linear-gradient(to top, #000, transparent), linear-gradient(to right, #fff, hsl({hsva.h} 100% 50%));"
role="slider"
tabindex="0"
aria-label="Saturation and brightness"
aria-valuenow={Math.round(hsva.s)}
aria-valuetext="Saturation {Math.round(hsva.s)}%, brightness {Math.round(hsva.v)}%"
onpointerdown={(event) => {
area!.setPointerCapture(event.pointerId);
pickArea(event);
}}
onpointermove={(event) => {
if (area!.hasPointerCapture(event.pointerId)) pickArea(event);
}}
onkeydown={areaKeys}
>
<div
class="absolute pointer-events-none handle"
style="left: {hsva.s}%; top: {100 - hsva.v}%; --swatch: {hex};"
></div>
</div>
<div class="flex gap-3 items-center">
{#if EyeDropper}
<button
type="button"
class="grid shrink-0 place-items-center rounded-md transition size-8 text-zinc-500 hover:bg-zinc-100 hover:text-zinc-900 focus-visible:outline-2 focus-visible:outline-zinc-900 dark:text-zinc-300 dark:hover:bg-zinc-700 dark:hover:text-white dark:focus-visible:outline-white"
aria-label="Pick a colour from the screen"
onclick={pickFromScreen}
>
<svg viewBox="0 0 24 24" class="size-4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="m2 22 1-1h3l9-9M3 21v-3l9-9m3-3 3.5-3.5a2.1 2.1 0 0 1 3 3L18 9l.4.4a2.1 2.1 0 1 1-3 3l-3.8-3.8a2.1 2.1 0 1 1 3-3l.4.4Z" />
</svg>
</button>
{/if}
<div class="flex flex-col flex-1 gap-3">
<input
type="range"
min="0"
max="359"
class="picker-track"
style="background: linear-gradient(to right, #f00, #ff0, #0f0, #0ff, #00f, #f0f, #f00); --swatch: hsl({hsva.h} 100% 50%);"
aria-label="Hue"
value={Math.round(hsva.h)}
oninput={(event) => updateHsva({ h: Number(event.currentTarget.value) })}
/>
<input
type="range"
min="0"
max="100"
class="picker-track"
style="background: linear-gradient(to right, transparent, {hex}), {CHECKERBOARD}; --swatch: {formatColour(active)};"
aria-label="Opacity"
value={Math.round(hsva.a * 100)}
oninput={(event) => updateHsva({ a: Number(event.currentTarget.value) / 100 })}
/>
</div>
<div
class="shrink-0 rounded-md ring-1 ring-inset ring-black/10 size-8 dark:ring-white/10"
style="background: {asLayer(formatValue(model))}, {CHECKERBOARD};"
aria-hidden="true"
></div>
</div>
<div class="flex gap-2">
<label class="flex flex-1 gap-1.5 items-center px-2.5 min-w-0 h-8 text-xs rounded-md bg-zinc-100 dark:bg-zinc-700/70">
<span class="text-zinc-500 dark:text-zinc-400">#</span>
<input
class="flex-1 p-0 min-w-0 font-mono text-xs uppercase bg-transparent border-0 outline-none select-text focus:ring-0"
aria-label="Hex colour"
value={hex.slice(1)}
spellcheck="false"
autocomplete="off"
maxlength="7"
oninput={(event) => setHex(event.currentTarget.value)}
onkeydown={(event) => {
if (event.key === "Enter") event.currentTarget.blur();
}}
onblur={(event) => {
setHex(event.currentTarget.value, true);
event.currentTarget.value = hex.slice(1);
}}
/>
</label>
<label class="flex shrink-0 items-center px-2.5 w-16 h-8 text-xs rounded-md bg-zinc-100 dark:bg-zinc-700/70">
<input
type="number"
min="0"
max="100"
class="p-0 w-full min-w-0 text-xs text-right bg-transparent border-0 outline-none select-text picker-number focus:ring-0"
aria-label="Opacity percent"
value={Math.round(active.a * 100)}
oninput={(event) => {
if (event.currentTarget.value !== "") updateHsva({ a: clamp(Number(event.currentTarget.value), 0, 100) / 100 });
}}
/>
<span class="text-zinc-500 dark:text-zinc-400">%</span>
</label>
</div>
{#if shownPresets.length}
<div class="grid grid-cols-9 gap-1.5 pt-3 border-t border-zinc-100 dark:border-zinc-700">
{#each shownPresets as preset (preset)}
<button
type="button"
class="rounded-md ring-1 ring-inset transition aspect-square ring-black/10 hover:scale-110 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-zinc-900 dark:ring-white/10 dark:focus-visible:outline-white"
style="background: {asLayer(preset)}, {CHECKERBOARD};"
aria-label="Apply preset {preset}"
onclick={() => applyPreset(preset)}
></button>
{/each}
</div>
{/if}
</div>
<style>
.handle {
width: 1.125rem;
height: 1.125rem;
border-radius: 9999px;
border: 2px solid white;
background: linear-gradient(var(--swatch), var(--swatch)),
repeating-conic-gradient(#d4d4d8 0% 25%, #ffffff 0% 50%) 50% / 6px 6px;
box-shadow: 0 0 0 1px rgb(0 0 0 / 0.15), 0 1px 3px rgb(0 0 0 / 0.3);
transform: translate(-50%, -50%);
transition: transform 120ms ease, box-shadow 120ms ease;
}
.handle:focus-visible {
outline: none;
box-shadow: 0 0 0 2px rgb(24 24 27), 0 1px 3px rgb(0 0 0 / 0.3);
}
:global(.dark) .handle:focus-visible {
box-shadow: 0 0 0 2px white, 0 1px 3px rgb(0 0 0 / 0.3);
}
.handle-selected {
z-index: 1;
transform: translate(-50%, -50%) scale(1.2);
box-shadow: 0 0 0 2px rgb(24 24 27 / 0.85), 0 2px 6px rgb(0 0 0 / 0.35);
}
:global(.dark) .handle-selected {
box-shadow: 0 0 0 2px rgb(255 255 255 / 0.9), 0 2px 6px rgb(0 0 0 / 0.5);
}
.picker-number {
appearance: textfield;
}
.picker-number::-webkit-inner-spin-button,
.picker-number::-webkit-outer-spin-button {
appearance: none;
margin: 0;
}
.picker-track {
appearance: none;
display: block;
width: 100%;
height: 0.75rem;
border-radius: 9999px;
cursor: pointer;
box-shadow: inset 0 0 0 1px rgb(0 0 0 / 0.1);
}
.picker-track:focus-visible {
outline: 2px solid rgb(24 24 27);
outline-offset: 2px;
}
:global(.dark) .picker-track:focus-visible {
outline-color: white;
}
.picker-track::-webkit-slider-thumb {
appearance: none;
width: 1.125rem;
height: 1.125rem;
border: 2px solid white;
border-radius: 9999px;
background: var(--swatch);
box-shadow: 0 0 0 1px rgb(0 0 0 / 0.15), 0 1px 3px rgb(0 0 0 / 0.3);
}
.picker-track::-moz-range-thumb {
width: 1.125rem;
height: 1.125rem;
box-sizing: border-box;
border: 2px solid white;
border-radius: 9999px;
background: var(--swatch);
box-shadow: 0 0 0 1px rgb(0 0 0 / 0.15), 0 1px 3px rgb(0 0 0 / 0.3);
}
</style>
@@ -0,0 +1,95 @@
import { describe, expect, it } from "@jest/globals";
import {
colourAt,
formatValue,
hsvaToRgba,
parseColour,
parseValue,
rgbaToHex,
rgbaToHsva,
} from "./colourValue";
describe("parseColour", () => {
it.each([
["#fff", { r: 255, g: 255, b: 255, a: 1 }],
["#11588380", { r: 17, g: 88, b: 131, a: 0.5 }],
["rgba(17,88,131,1)", { r: 17, g: 88, b: 131, a: 1 }],
["RGBA(235,169,202,1)", { r: 235, g: 169, b: 202, a: 1 }],
["rgb(230, 21, 21)", { r: 230, g: 21, b: 21, a: 1 }],
["rgb(10 20 30 / 50%)", { r: 10, g: 20, b: 30, a: 0.5 }],
["hsl(0, 100%, 50%)", { r: 255, g: 0, b: 0, a: 1 }],
["transparent", { r: 0, g: 0, b: 0, a: 0 }],
])("parses %s", (input, expected) => {
expect(parseColour(input)).toEqual(expected);
});
it.each(["", "red", "#12345", "rgb(1, 2)", "rgba(a, b, c)"])("rejects %s", (input) => {
expect(parseColour(input)).toBeNull();
});
});
describe("parseValue", () => {
it("parses the default gradient", () => {
expect(parseValue("linear-gradient(45deg, rgba(17,88,131,1) 0%, rgba(18,106,98,1) 100%)")).toEqual({
kind: "linear",
angle: 45,
stops: [
{ colour: { r: 17, g: 88, b: 131, a: 1 }, position: 0 },
{ colour: { r: 18, g: 106, b: 98, a: 1 }, position: 100 },
],
});
});
it("parses radial gradients and skips the shape", () => {
const value = parseValue("radial-gradient(circle, rgba(20, 199, 178, 0.76) 32%, rgba(3, 120, 57, 0.66) 100%)");
expect(value.kind).toBe("radial");
expect(value.kind !== "solid" && value.stops.map((stop) => stop.position)).toEqual([32, 100]);
});
it("maps side keywords and fills missing stop positions", () => {
const value = parseValue("linear-gradient(to right, #000, #888, #fff)");
expect(value).toMatchObject({ kind: "linear", angle: 90 });
expect(value.kind !== "solid" && value.stops.map((stop) => stop.position)).toEqual([0, 50, 100]);
});
it("treats plain colours as solid and falls back on garbage", () => {
expect(parseValue("rgba(4, 4, 138, 0.77)")).toEqual({ kind: "solid", colour: { r: 4, g: 4, b: 138, a: 0.77 } });
expect(parseValue("not a colour").kind).toBe("solid");
});
});
describe("formatValue", () => {
it("round-trips gradients in the stored format", () => {
const css = "linear-gradient(45deg, rgba(17, 88, 131, 1) 0%, rgba(18, 106, 98, 1) 100%)";
expect(formatValue(parseValue(css))).toBe(css);
});
it("sorts stops by position", () => {
expect(
formatValue({
kind: "radial",
stops: [
{ colour: { r: 255, g: 255, b: 255, a: 1 }, position: 80 },
{ colour: { r: 0, g: 0, b: 0, a: 0.5 }, position: 10 },
],
}),
).toBe("radial-gradient(circle, rgba(0, 0, 0, 0.5) 10%, rgba(255, 255, 255, 1) 80%)");
});
});
describe("conversions", () => {
it("converts between RGB, HSV and hex", () => {
const colour = { r: 17, g: 88, b: 131, a: 1 };
expect(hsvaToRgba(rgbaToHsva(colour))).toEqual(colour);
expect(rgbaToHex(colour)).toBe("#115883");
});
it("interpolates colours between stops", () => {
const stops = [
{ colour: { r: 0, g: 0, b: 0, a: 1 }, position: 0 },
{ colour: { r: 200, g: 100, b: 50, a: 0 }, position: 100 },
];
expect(colourAt(stops, 50)).toEqual({ r: 100, g: 50, b: 25, a: 0.5 });
expect(colourAt(stops, 120)).toEqual(stops[1].colour);
});
});
@@ -0,0 +1,188 @@
export type Rgba = { r: number; g: number; b: number; a: number };
export type Hsva = { h: number; s: number; v: number; a: number };
export type GradientStop = { colour: Rgba; position: number };
export type ColourValue =
| { kind: "solid"; colour: Rgba }
| { kind: "linear"; angle: number; stops: GradientStop[] }
| { kind: "radial"; stops: GradientStop[] };
const FALLBACK: Rgba = { r: 17, g: 88, b: 131, a: 1 };
const SIDE_ANGLES: Record<string, number> = {
"to top": 0,
"to top right": 45,
"to right top": 45,
"to right": 90,
"to bottom right": 135,
"to right bottom": 135,
"to bottom": 180,
"to bottom left": 225,
"to left bottom": 225,
"to left": 270,
"to top left": 315,
"to left top": 315,
};
export const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));
const round = (value: number, digits = 0) => {
const factor = 10 ** digits;
return Math.round(value * factor) / factor;
};
function parseAlpha(part: string): number {
return clamp(part.endsWith("%") ? parseFloat(part) / 100 : parseFloat(part), 0, 1);
}
function hexToRgba(hex: string): Rgba | null {
const digits = hex.slice(1);
if (![3, 4, 6, 8].includes(digits.length)) return null;
const full = digits.length <= 4 ? [...digits].map((d) => d + d).join("") : digits;
const [r, g, b, a = 255] = full.match(/../g)!.map((pair) => parseInt(pair, 16));
return { r, g, b, a: round(a / 255, 2) };
}
function hslToRgba(h: number, s: number, l: number, a: number): Rgba {
const k = (n: number) => (n + h / 30) % 12;
const f = (n: number) => l - s * Math.min(l, 1 - l) * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1));
return { r: Math.round(f(0) * 255), g: Math.round(f(8) * 255), b: Math.round(f(4) * 255), a };
}
export function parseColour(input: string): Rgba | null {
const value = input.trim().toLowerCase();
if (value === "transparent") return { r: 0, g: 0, b: 0, a: 0 };
if (/^#[0-9a-f]+$/.test(value)) return hexToRgba(value);
const fn = value.match(/^(rgba?|hsla?)\(([^()]*)\)$/);
if (!fn) return null;
const parts = fn[2].split(/[\s,/]+/).filter(Boolean);
if (parts.length < 3 || parts.length > 4) return null;
const a = parts[3] === undefined ? 1 : parseAlpha(parts[3]);
if (Number.isNaN(a)) return null;
if (fn[1].startsWith("rgb")) {
const [r, g, b] = parts
.slice(0, 3)
.map((part) => clamp(Math.round(part.endsWith("%") ? parseFloat(part) * 2.55 : parseFloat(part)), 0, 255));
return [r, g, b].some(Number.isNaN) ? null : { r, g, b, a };
}
const [h, s, l] = [parseFloat(parts[0]), parseFloat(parts[1]) / 100, parseFloat(parts[2]) / 100];
return [h, s, l].some(Number.isNaN) ? null : hslToRgba(((h % 360) + 360) % 360, clamp(s, 0, 1), clamp(l, 0, 1), a);
}
export function formatColour({ r, g, b, a }: Rgba): string {
return `rgba(${r}, ${g}, ${b}, ${round(a, 2)})`;
}
export function rgbaToHex({ r, g, b }: Rgba): string {
return `#${[r, g, b].map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
}
export function rgbaToHsva({ r, g, b, a }: Rgba): Hsva {
const [red, green, blue] = [r / 255, g / 255, b / 255];
const max = Math.max(red, green, blue);
const delta = max - Math.min(red, green, blue);
let h = 0;
if (delta) {
if (max === red) h = ((green - blue) / delta) % 6;
else if (max === green) h = (blue - red) / delta + 2;
else h = (red - green) / delta + 4;
}
return { h: (h * 60 + 360) % 360, s: max ? (delta / max) * 100 : 0, v: max * 100, a };
}
export function hsvaToRgba({ h, s, v, a }: Hsva): Rgba {
const f = (n: number) => {
const k = (n + h / 60) % 6;
return Math.round((v / 100) * (1 - (s / 100) * Math.max(0, Math.min(k, 4 - k, 1))) * 255);
};
return { r: f(5), g: f(3), b: f(1), a };
}
function splitTopLevel(input: string): string[] {
const parts: string[] = [];
let depth = 0;
let current = "";
for (const char of input) {
if (char === "(") depth++;
if (char === ")") depth--;
if (char === "," && depth === 0) {
parts.push(current.trim());
current = "";
} else {
current += char;
}
}
if (current.trim()) parts.push(current.trim());
return parts;
}
function parseStop(part: string): { colour: Rgba; position?: number } | null {
const withPosition = part.match(/^(.+?)\s+(-?[\d.]+)%$/);
const colour = withPosition ? parseColour(withPosition[1]) : null;
if (colour) return { colour, position: clamp(parseFloat(withPosition![2]), 0, 100) };
const plain = parseColour(part);
return plain ? { colour: plain } : null;
}
function fillPositions(stops: { colour: Rgba; position?: number }[]): GradientStop[] {
const positions = stops.map((stop) => stop.position);
positions[0] ??= 0;
positions[positions.length - 1] ??= 100;
for (let i = 1; i < positions.length - 1; i++) {
if (positions[i] !== undefined) continue;
const next = positions.findIndex((position, j) => j > i && position !== undefined);
const start = positions[i - 1]!;
positions[i] = start + (positions[next]! - start) / (next - i + 1);
}
return stops.map((stop, i) => ({ colour: stop.colour, position: round(positions[i]!, 2) }));
}
export function parseValue(input: string): ColourValue {
const gradient = input.trim().match(/^(linear|radial)-gradient\(([\s\S]*)\)$/i);
if (!gradient) return { kind: "solid", colour: parseColour(input) ?? FALLBACK };
const kind = gradient[1].toLowerCase() as "linear" | "radial";
const args = splitTopLevel(gradient[2]);
let angle = 180;
if (args.length && !parseStop(args[0])) {
const direction = args.shift()!.toLowerCase().replace(/\s+/g, " ");
const degrees = direction.match(/^(-?[\d.]+)deg$/);
if (degrees) angle = ((parseFloat(degrees[1]) % 360) + 360) % 360;
else if (direction in SIDE_ANGLES) angle = SIDE_ANGLES[direction];
}
const stops = args.map(parseStop).filter((stop) => stop !== null);
if (stops.length < 2) return { kind: "solid", colour: stops[0]?.colour ?? FALLBACK };
const filled = fillPositions(stops);
return kind === "linear" ? { kind, angle, stops: filled } : { kind, stops: filled };
}
export function formatStops(stops: GradientStop[]): string {
return [...stops]
.sort((a, b) => a.position - b.position)
.map((stop) => `${formatColour(stop.colour)} ${round(stop.position)}%`)
.join(", ");
}
export function formatValue(value: ColourValue): string {
if (value.kind === "solid") return formatColour(value.colour);
if (value.kind === "linear") return `linear-gradient(${round(value.angle)}deg, ${formatStops(value.stops)})`;
return `radial-gradient(circle, ${formatStops(value.stops)})`;
}
export function colourAt(stops: GradientStop[], position: number): Rgba {
const sorted = [...stops].sort((a, b) => a.position - b.position);
const after = sorted.findIndex((stop) => stop.position >= position);
if (after <= 0) return { ...sorted[after === 0 ? 0 : sorted.length - 1].colour };
const [from, to] = [sorted[after - 1], sorted[after]];
const t = (position - from.position) / (to.position - from.position || 1);
const mix = (a: number, b: number) => a + (b - a) * t;
return {
r: Math.round(mix(from.colour.r, to.colour.r)),
g: Math.round(mix(from.colour.g, to.colour.g)),
b: Math.round(mix(from.colour.b, to.colour.b)),
a: round(mix(from.colour.a, to.colour.a), 2),
};
}
@@ -1,32 +0,0 @@
<script lang="ts">
import { createElement } from "react";
import { createRoot, type Root } from "react-dom/client";
import { onDestroy } from "svelte";
let adapterProps = $props();
let container = $state<HTMLDivElement | null>(null);
let root: Root | null = null;
$effect(() => {
if (!container) return;
const { el, children, class: className, ...rest } = adapterProps;
try {
root ??= createRoot(container);
root.render(createElement(el, rest, children));
} catch (err) {
console.warn(`react-adapter failed to mount.`, { err });
}
});
onDestroy(() => {
try {
root?.unmount();
} catch (err) {
console.warn(`react-adapter failed to unmount.`, { err });
}
root = null;
});
</script>
<div bind:this={container} class={adapterProps.class}></div>
-2
View File
@@ -1,5 +1,3 @@
@import "./components/ColourPicker.css" layer(base);
@import "../css/tailwind.css";
::-webkit-scrollbar {
+4 -7
View File
@@ -281,12 +281,12 @@
void themeManager.updatePreviewDebounced(snapshot);
});
type SettingType = 'switch' | 'button' | 'slider' | 'colourPicker' | 'select' | 'codeEditor' | 'imageUpload' | 'conditional' | 'lightDarkToggle';
type SettingType = 'switch' | 'button' | 'slider' | 'select' | 'codeEditor' | 'imageUpload' | 'conditional' | 'lightDarkToggle';
type SwitchProps = { state: boolean; onChange: (value: boolean) => void };
type ButtonProps = { onClick: () => void; text: string };
type SliderProps = { state: number; onChange: (value: number) => void; min?: number; max?: number };
type ColourPickerProps = { color: string; onChange: (color: string) => void };
type SelectProps = { options: Array<{ value: string; label: string }>; value: string; onChange: (value: string) => void };
type CodeEditorProps = { value: string; onChange: (value: string) => void };
type LightDarkToggleProps = { state: boolean; onChange: (value: boolean) => void };
@@ -296,7 +296,7 @@
children: SettingItem;
};
type ComponentProps = SwitchProps | ButtonProps | SliderProps | ColourPickerProps | SelectProps | CodeEditorProps | LightDarkToggleProps | ConditionalProps;
type ComponentProps = SwitchProps | ButtonProps | SliderProps | SelectProps | CodeEditorProps | LightDarkToggleProps | ConditionalProps;
type SettingItem = {
type: SettingType;
@@ -349,10 +349,7 @@
<Button {...(item.props as ButtonProps)} />
{:else if item.type === 'slider'}
<Slider {...(item.props as SliderProps)} />
{:else if item.type === 'colourPicker'}
{#key themeLoaded}
<ColourPicker savePresets={false} standalone={true} {...(item.props)} />
{/key}
{:else if item.type === 'codeEditor'}
{#if !codeEditorFullscreen}
{#key themeLoaded}