Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(editor): themed HSV + alpha color picker

esengine15d688f79e22
diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.ts
index d5cb0fbea..cc8cad9aa 100644
--- a/desktop/src/engine/SceneCommands.ts
+++ b/desktop/src/engine/SceneCommands.ts
@@ -13,7 +13,7 @@ import {
isRenderComponent,
userSchema,
angleZToQuat,
- hexToRgb,
+ hexToRgba,
prettyLabel,
} from './schema';
@@ -96,10 +96,9 @@ export function toModelValue(
}
case 'angle':
return angleZToQuat(Number(value));
- case 'color': {
- const a = (cur[key] as { a?: number } | undefined)?.a ?? 1;
- return { ...(cur[key] as object), ...hexToRgb(String(value)), a };
- }
+ case 'color':
+ // The hex carries alpha (#rrggbbaa), so it fully describes RGBA.
+ return { ...(cur[key] as object), ...hexToRgba(String(value)) };
default:
return value;
}
diff --git a/desktop/src/engine/schema.ts b/desktop/src/engine/schema.ts
index c33495c2e..9d9715e4b 100644
--- a/desktop/src/engine/schema.ts
+++ b/desktop/src/engine/schema.ts
@@ -132,20 +132,24 @@ const chan = (n: number) =>
Math.max(0, Math.min(255, Math.round(n * 255)))
.toString(16)
.padStart(2, '0');
-const rgbToHex = (c: { r: number; g: number; b: number }) =>
- `#${chan(c.r)}${chan(c.g)}${chan(c.b)}`;
-export const hexToRgb = (hex: string) => {
- const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim());
- if (!m) return { r: 1, g: 1, b: 1 };
- const n = parseInt(m[1], 16);
- return { r: ((n >> 16) & 255) / 255, g: ((n >> 8) & 255) / 255, b: (n & 255) / 255 };
+/** RGBA (0..1 channels) → `#rrggbbaa` — color fields carry alpha so it's editable. */
+const rgbaToHex = (c: { r: number; g: number; b: number; a?: number }) =>
+ `#${chan(c.r)}${chan(c.g)}${chan(c.b)}${chan(c.a ?? 1)}`;
+/** `#rrggbb` or `#rrggbbaa` → RGBA (0..1); alpha defaults to 1 for a 6-digit hex. */
+export const hexToRgba = (hex: string) => {
+ const m = /^#?([0-9a-f]{6}([0-9a-f]{2})?)$/i.exec(hex.trim());
+ if (!m) return { r: 1, g: 1, b: 1, a: 1 };
+ const h = m[1];
+ const n = parseInt(h.slice(0, 6), 16);
+ const a = h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1;
+ return { r: ((n >> 16) & 255) / 255, g: ((n >> 8) & 255) / 255, b: (n & 255) / 255, a };
};
/** Infer an editable field from a live component value + its key. */
export function inferField(key: string, v: unknown, isColor: boolean): InspectorField | null {
const label = prettyLabel(key);
if (isColor && v && typeof v === 'object') {
- return { key, label, type: 'color', value: rgbToHex(v as { r: number; g: number; b: number }) };
+ return { key, label, type: 'color', value: rgbaToHex(v as { r: number; g: number; b: number; a?: number }) };
}
if (typeof v === 'number') return { key, label, type: 'number', value: v };
if (typeof v === 'boolean') return { key, label, type: 'bool', value: v };
diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsx
index 32216e6bc..473b07580 100644
--- a/desktop/src/panels/Details.tsx
+++ b/desktop/src/panels/Details.tsx
@@ -37,7 +37,7 @@ import { SceneModel } from '@/engine/SceneModel';
import { SceneCommands, toModelValue } from '@/engine/SceneCommands';
import { PlayInspect } from '@/engine/PlayInspect';
import type { SceneData } from 'esengine';
-import { modelAddableComponentEntries, subscribeSchemas, getSchemaRevision, prettyLabel } from '@/engine/schema';
+import { modelAddableComponentEntries, subscribeSchemas, getSchemaRevision, prettyLabel, hexToRgba } from '@/engine/schema';
import { ProjectStore } from '@/project/ProjectStore';
import { ContextMenu } from '@/components/Menu';
import { Popover, usePopover } from '@/components/Popover';
@@ -481,33 +481,170 @@ function StringControl({
);
}
+// — Color math (0..1 channels) —
+const clamp01 = (n: number) => Math.max(0, Math.min(1, n));
+const hch = (n: number) => Math.max(0, Math.min(255, Math.round(n * 255))).toString(16).padStart(2, '0');
+const rgbaToHex8 = (r: number, g: number, b: number, a: number) => `#${hch(r)}${hch(g)}${hch(b)}${hch(a)}`;
+const rgbCss = (r: number, g: number, b: number) => `rgb(${Math.round(r * 255)},${Math.round(g * 255)},${Math.round(b * 255)})`;
+function rgbToHsv(r: number, g: number, b: number): [number, number, number] {
+ const max = Math.max(r, g, b);
+ const min = Math.min(r, g, b);
+ const d = max - min;
+ let h = 0;
+ if (d) {
+ if (max === r) h = ((g - b) / d) % 6;
+ else if (max === g) h = (b - r) / d + 2;
+ else h = (r - g) / d + 4;
+ h /= 6;
+ if (h < 0) h += 1;
+ }
+ return [h, max ? d / max : 0, max];
+}
+function hsvToRgb(h: number, s: number, v: number): [number, number, number] {
+ const i = Math.floor(h * 6);
+ const f = h * 6 - i;
+ const p = v * (1 - s);
+ const q = v * (1 - f * s);
+ const t = v * (1 - (1 - f) * s);
+ const seq: [number, number, number][] = [[v, t, p], [q, v, p], [p, v, t], [p, q, v], [t, p, v], [v, p, q]];
+ return seq[((i % 6) + 6) % 6];
+}
+
+// A drag track: pointer down/move within `ref` reports the normalized [0..1]
+// position (x, y). Used by the color picker's SV square, hue and alpha bars.
+function useDragTrack(onMove: (x: number, y: number) => void) {
+ const ref = useRef<HTMLDivElement>(null);
+ const active = useRef(false);
+ const handle = (clientX: number, clientY: number) => {
+ const el = ref.current;
+ if (!el) return;
+ const r = el.getBoundingClientRect();
+ onMove(clamp01(r.width ? (clientX - r.left) / r.width : 0), clamp01(r.height ? (clientY - r.top) / r.height : 0));
+ };
+ return {
+ ref,
+ onPointerDown: (e: React.PointerEvent) => {
+ if (e.button !== 0) return;
+ active.current = true;
+ e.currentTarget.setPointerCapture(e.pointerId);
+ handle(e.clientX, e.clientY);
+ },
+ onPointerMove: (e: React.PointerEvent) => {
+ if (active.current) handle(e.clientX, e.clientY);
+ },
+ onPointerUp: (e: React.PointerEvent) => {
+ active.current = false;
+ e.currentTarget.releasePointerCapture?.(e.pointerId);
+ },
+ };
+}
+
+// A themed HSV + alpha color picker. The field value is `#rrggbbaa`, so alpha is
+// editable (the native <input type=color> can't). Local HSV state preserves hue
+// while dragging at zero saturation/value; the whole picker session is one undo
+// step (begin on open, end on close). The hex box accepts 6- or 8-digit input.
function ColorControl({
value,
onBegin,
onEnd,
onChange,
}: ControlGesture & { value: string; onChange: (v: string) => void }) {
+ const pop = usePopover();
+ const sw = useRef<HTMLButtonElement>(null);
+ const { r, g, b, a } = hexToRgba(value);
+ const [hsv, setHsv] = useState<[number, number, number]>(() => rgbToHsv(r, g, b));
+ const [alpha, setAlpha] = useState(a);
+ const [editing, setEditing] = useState(false);
+ const [text, setText] = useState(value);
+
+ const emit = (h: number, s: number, v: number, al: number) => {
+ const [rr, gg, bb] = hsvToRgb(h, s, v);
+ onChange(rgbaToHex8(rr, gg, bb, al));
+ };
+ // Typed hex (6- or 8-digit): echo it raw, and on a valid value sync the picker
+ // cursors + commit. A hex box reuses the open popover's gesture (no double-begin).
+ const focusHex = () => {
+ setText(value);
+ setEditing(true);
+ if (!pop.isOpen) onBegin?.();
+ };
+ const blurHex = () => {
+ setEditing(false);
+ if (!pop.isOpen) onEnd?.();
+ };
+ const typeHex = (raw: string) => {
+ setText(raw);
+ if (/^#?[0-9a-f]{6}([0-9a-f]{2})?$/i.test(raw.trim())) {
+ const c = hexToRgba(raw);
+ setHsv(rgbToHsv(c.r, c.g, c.b));
+ setAlpha(c.a);
+ onChange(rgbaToHex8(c.r, c.g, c.b, c.a));
+ }
+ };
+ const open = () => {
+ const c = hexToRgba(value);
+ setHsv(rgbToHsv(c.r, c.g, c.b));
+ setAlpha(c.a);
+ setText(value);
+ onBegin?.();
+ pop.open(sw.current);
+ };
+ const close = () => {
+ pop.close();
+ onEnd?.();
+ };
+
+ const sv = useDragTrack((x, y) => {
+ const next: [number, number, number] = [hsv[0], x, 1 - y];
+ setHsv(next);
+ emit(next[0], next[1], next[2], alpha);
+ });
+ const hue = useDragTrack((x) => {
+ const next: [number, number, number] = [x, hsv[1], hsv[2]];
+ setHsv(next);
+ emit(next[0], next[1], next[2], alpha);
+ });
+ const alp = useDragTrack((x) => {
+ setAlpha(x);
+ emit(hsv[0], hsv[1], hsv[2], x);
+ });
+ const [hr, hg, hb] = hsvToRgb(hsv[0], 1, 1); // pure hue for the SV backdrop
+ const [cr, cg, cb] = hsvToRgb(hsv[0], hsv[1], hsv[2]);
+
return (
<>
- <label className="sw" style={{ background: value }}>
- <input
- type="color"
- value={value}
- onFocus={onBegin}
- onBlur={onEnd}
- onChange={(e) => onChange(e.target.value)}
- style={{ position: 'absolute', width: 0, height: 0, opacity: 0, pointerEvents: 'none' }}
- />
- </label>
+ <button ref={sw} type="button" className="sw" onMouseDown={(e) => e.stopPropagation()} onClick={open}>
+ <span className="sw-fill" style={{ background: rgbCss(r, g, b), opacity: a }} />
+ </button>
<span className="field">
- <input
- value={value}
- spellCheck={false}
- onFocus={onBegin}
- onBlur={onEnd}
- onChange={(e) => onChange(e.target.value)}
- />
+ <input value={editing ? text : value} spellCheck={false} onFocus={focusHex} onBlur={blurHex} onChange={(e) => typeHex(e.target.value)} />
</span>
+ {pop.anchor && (
+ <Popover anchor={pop.anchor} width={200} onClose={close}>
+ <div className="cp">
+ <div className="cp-sv" {...sv} style={{ background: rgbCss(hr, hg, hb) }}>
+ <div className="cp-sv-white" />
+ <div className="cp-sv-black" />
+ <div className="cp-dot" style={{ left: `${hsv[1] * 100}%`, top: `${(1 - hsv[2]) * 100}%` }} />
+ </div>
+ <div className="cp-hue" {...hue}>
+ <div className="cp-bar-dot" style={{ left: `${hsv[0] * 100}%` }} />
+ </div>
+ <div className="cp-alpha" {...alp}>
+ <div className="cp-alpha-fill" style={{ background: `linear-gradient(90deg, transparent, ${rgbCss(cr, cg, cb)})` }} />
+ <div className="cp-bar-dot" style={{ left: `${alpha * 100}%` }} />
+ </div>
+ <input
+ className="cp-hex"
+ value={editing ? text : value}
+ spellCheck={false}
+ onFocus={focusHex}
+ onBlur={blurHex}
+ onChange={(e) => typeHex(e.target.value)}
+ />
+ </div>
+ </Popover>
+ )}
</>
);
}
diff --git a/desktop/src/theme/inspector.css b/desktop/src/theme/inspector.css
index ff8a84de5..4e3dc1df9 100644
--- a/desktop/src/theme/inspector.css
+++ b/desktop/src/theme/inspector.css
@@ -114,7 +114,26 @@
.ax.w, .ax.h { background: var(--srf-5); color: var(--text-dim); }
.vfield input { width: 100%; min-width: 0; background: none; border: none; outline: none; padding: 0 5px; font-size: var(--fs-xs); color: var(--text); font-family: var(--mono); }
-.sw { width: 22px; height: 18px; border-radius: var(--r-xs); border: 1px solid var(--border-line); flex-shrink: 0; cursor: pointer; }
+.sw { position: relative; width: 28px; height: 18px; border-radius: var(--r-xs); border: 1px solid var(--border-line); flex-shrink: 0; cursor: pointer; overflow: hidden; padding: 0;
+ background-image: linear-gradient(45deg,#777 25%,transparent 25%),linear-gradient(-45deg,#777 25%,transparent 25%),linear-gradient(45deg,transparent 75%,#777 75%),linear-gradient(-45deg,transparent 75%,#777 75%);
+ background-size: 8px 8px; background-position: 0 0,0 4px,4px -4px,-4px 0; background-color: #fff; }
+.sw-fill { position: absolute; inset: 0; }
+
+/* themed HSV + alpha color picker (a Popover under the swatch) */
+.cp { display: flex; flex-direction: column; gap: 9px; padding: 6px; width: 100%; }
+.cp-sv { position: relative; width: 100%; height: 124px; border-radius: var(--r-xs); cursor: crosshair; touch-action: none; overflow: hidden; }
+.cp-sv-white { position: absolute; inset: 0; background: linear-gradient(90deg, #fff, rgba(255,255,255,0)); }
+.cp-sv-black { position: absolute; inset: 0; background: linear-gradient(0deg, #000, rgba(0,0,0,0)); }
+.cp-dot { position: absolute; width: 12px; height: 12px; border-radius: 50%; border: 2px solid #fff; box-shadow: 0 0 0 1px rgba(0,0,0,.5); transform: translate(-50%,-50%); pointer-events: none; }
+.cp-hue { position: relative; height: 12px; border-radius: var(--r-pill); cursor: pointer; touch-action: none;
+ background: linear-gradient(90deg, #f00, #ff0, #0f0, #0ff, #00f, #f0f, #f00); }
+.cp-alpha { position: relative; height: 12px; border-radius: var(--r-pill); cursor: pointer; touch-action: none; overflow: hidden;
+ background-image: linear-gradient(45deg,#777 25%,transparent 25%),linear-gradient(-45deg,#777 25%,transparent 25%),linear-gradient(45deg,transparent 75%,#777 75%),linear-gradient(-45deg,transparent 75%,#777 75%);
+ background-size: 8px 8px; background-position: 0 0,0 4px,4px -4px,-4px 0; background-color: #fff; }
+.cp-alpha-fill { position: absolute; inset: 0; }
+.cp-bar-dot { position: absolute; top: 50%; width: 14px; height: 14px; border-radius: 50%; background: #fff; border: 1px solid rgba(0,0,0,.4); box-shadow: var(--shadow-1); transform: translate(-50%,-50%); pointer-events: none; }
+.cp-hex { width: 100%; height: 24px; background: var(--inset); border: 1px solid var(--border); border-radius: var(--r-sm); padding: 0 8px; color: var(--text); font-family: var(--mono); font-size: var(--fs-sm); outline: none; }
+.cp-hex:focus { border-color: var(--acc); box-shadow: 0 0 0 2px var(--acc-soft); }
.slider { flex: 1; height: 6px; background: var(--inset); border-radius: var(--r-pill); position: relative; cursor: ew-resize; touch-action: none; }
.slider .fill { position: absolute; left: 0; top: 0; bottom: 0; background: var(--acc); border-radius: var(--r-pill); }
.slider .thumb { position: absolute; top: 50%; width: 11px; height: 11px; border-radius: 50%; background: var(--text); transform: translate(-50%,-50%); box-shadow: var(--shadow-1); }
diff --git a/desktop/tests/schema.test.ts b/desktop/tests/schema.test.ts
index 954720fd1..33314cf6d 100644
--- a/desktop/tests/schema.test.ts
+++ b/desktop/tests/schema.test.ts
@@ -6,7 +6,7 @@
* the JSON-first rewrite (REARCH_SERIALIZATION.md) will lean on.
*/
import { describe, it, expect } from 'vitest';
-import { prettyLabel, hexToRgb, angleZToQuat, inferField } from '@/engine/schema';
+import { prettyLabel, hexToRgba, angleZToQuat, inferField } from '@/engine/schema';
describe('prettyLabel', () => {
it('splits camelCase and capitalizes', () => {
@@ -16,17 +16,19 @@ describe('prettyLabel', () => {
});
});
-describe('hexToRgb', () => {
- it('parses #rrggbb into 0..1 channels', () => {
- expect(hexToRgb('#ffffff')).toEqual({ r: 1, g: 1, b: 1 });
- expect(hexToRgb('#000000')).toEqual({ r: 0, g: 0, b: 0 });
- const red = hexToRgb('#ff0000');
- expect(red.r).toBe(1);
- expect(red.g).toBe(0);
- expect(red.b).toBe(0);
+describe('hexToRgba', () => {
+ it('parses #rrggbb into 0..1 channels (alpha defaults to 1)', () => {
+ expect(hexToRgba('#ffffff')).toEqual({ r: 1, g: 1, b: 1, a: 1 });
+ expect(hexToRgba('#000000')).toEqual({ r: 0, g: 0, b: 0, a: 1 });
+ const red = hexToRgba('#ff0000');
+ expect([red.r, red.g, red.b, red.a]).toEqual([1, 0, 0, 1]);
});
- it('falls back to white on malformed input', () => {
- expect(hexToRgb('nope')).toEqual({ r: 1, g: 1, b: 1 });
+ it('parses the alpha byte of an #rrggbbaa hex', () => {
+ expect(hexToRgba('#ff000000').a).toBe(0);
+ expect(hexToRgba('#00ff00ff')).toEqual({ r: 0, g: 1, b: 0, a: 1 });
+ });
+ it('falls back to opaque white on malformed input', () => {
+ expect(hexToRgba('nope')).toEqual({ r: 1, g: 1, b: 1, a: 1 });
});
});
@@ -55,10 +57,10 @@ describe('inferField', () => {
expect(inferField('p', { x: 1, y: 2 }, false)).toMatchObject({ type: 'vec2', value: [1, 2] });
expect(inferField('p', { x: 1, y: 2, z: 3 }, false)).toMatchObject({ type: 'vec3', value: [1, 2, 3] });
});
- it('treats a color key as a hex color', () => {
- const f = inferField('color', { r: 1, g: 0, b: 0 }, true);
+ it('treats a color key as an #rrggbbaa hex color', () => {
+ const f = inferField('color', { r: 1, g: 0, b: 0, a: 1 }, true);
expect(f?.type).toBe('color');
- expect(f?.value).toBe('#ff0000');
+ expect(f?.value).toBe('#ff0000ff');
});
it('returns null for an unknown shape', () => {
expect(inferField('weird', { foo: 1 }, false)).toBeNull();