Skip to content

🎥 Make videos programmatically with React

Replace native <input type="color"> with a custom color picker

Jonny Burgerc90618efed5f
diff --git a/packages/studio/src/components/ColorPicker/AlphaSlider.tsx b/packages/studio/src/components/ColorPicker/AlphaSlider.tsx
new file mode 100644
index 0000000000..ac73a2f1e2
--- /dev/null
+++ b/packages/studio/src/components/ColorPicker/AlphaSlider.tsx
@@ -0,0 +1,118 @@
+import React, {useCallback, useMemo, useRef} from 'react';
+import {clamp, hsvToRgb} from '../../helpers/color-conversion';
+import {
+ CHECKER_BACKGROUND_COLOR,
+ CHECKER_BACKGROUND_IMAGE,
+ CHECKER_BACKGROUND_POSITION,
+ CHECKER_BACKGROUND_SIZE,
+} from './checker';
+
+const SLIDER_HEIGHT = 12;
+const HANDLE_WIDTH = 8;
+
+const wrapperStyle: React.CSSProperties = {
+ position: 'relative',
+ height: SLIDER_HEIGHT,
+ width: '100%',
+ borderRadius: 3,
+ overflow: 'hidden',
+ cursor: 'ew-resize',
+ backgroundColor: CHECKER_BACKGROUND_COLOR,
+ backgroundImage: CHECKER_BACKGROUND_IMAGE,
+ backgroundSize: CHECKER_BACKGROUND_SIZE,
+ backgroundPosition: CHECKER_BACKGROUND_POSITION,
+ touchAction: 'none',
+};
+
+const innerStyle: React.CSSProperties = {
+ position: 'absolute',
+ inset: 0,
+};
+
+export const AlphaSlider: React.FC<{
+ readonly hue: number;
+ readonly saturation: number;
+ readonly value: number;
+ readonly alpha: number;
+ readonly onChange: (next: number) => void;
+ readonly onChangeComplete: (next: number) => void;
+}> = ({hue, saturation, value, alpha, onChange, onChangeComplete}) => {
+ const ref = useRef<HTMLDivElement>(null);
+
+ const opaqueColor = useMemo(() => {
+ const {r, g, b} = hsvToRgb({h: hue, s: saturation, v: value});
+ return `rgb(${r}, ${g}, ${b})`;
+ }, [hue, saturation, value]);
+
+ const gradientStyle: React.CSSProperties = useMemo(() => {
+ return {
+ ...innerStyle,
+ background: `linear-gradient(to right, rgba(0, 0, 0, 0), ${opaqueColor})`,
+ };
+ }, [opaqueColor]);
+
+ const updateFromEvent = useCallback(
+ (clientX: number, isFinal: boolean) => {
+ const {current} = ref;
+ if (!current) {
+ return;
+ }
+
+ const rect = current.getBoundingClientRect();
+ const next = clamp((clientX - rect.left) / rect.width, 0, 1);
+ if (isFinal) {
+ onChangeComplete(next);
+ } else {
+ onChange(next);
+ }
+ },
+ [onChange, onChangeComplete],
+ );
+
+ const onPointerDown = useCallback(
+ (e: React.PointerEvent<HTMLDivElement>) => {
+ if (e.button !== 0) {
+ return;
+ }
+
+ e.preventDefault();
+ updateFromEvent(e.clientX, false);
+
+ const onMove = (ev: PointerEvent) => {
+ updateFromEvent(ev.clientX, false);
+ };
+
+ const onUp = (ev: PointerEvent) => {
+ window.removeEventListener('pointermove', onMove);
+ window.removeEventListener('pointerup', onUp);
+ updateFromEvent(ev.clientX, true);
+ };
+
+ window.addEventListener('pointermove', onMove);
+ window.addEventListener('pointerup', onUp);
+ },
+ [updateFromEvent],
+ );
+
+ const handleStyle: React.CSSProperties = useMemo(() => {
+ return {
+ position: 'absolute',
+ top: -2,
+ left: `${alpha * 100}%`,
+ marginLeft: -HANDLE_WIDTH / 2,
+ width: HANDLE_WIDTH,
+ height: SLIDER_HEIGHT + 4,
+ borderRadius: 2,
+ border: '2px solid #fff',
+ boxShadow: '0 0 0 1px rgba(0, 0, 0, 0.6)',
+ pointerEvents: 'none',
+ };
+ }, [alpha]);
+
+ return (
+ <div ref={ref} style={wrapperStyle} onPointerDown={onPointerDown}>
+ <div style={gradientStyle} />
+ <div style={handleStyle} />
+ </div>
+ );
+};
diff --git a/packages/studio/src/components/ColorPicker/ColorPicker.tsx b/packages/studio/src/components/ColorPicker/ColorPicker.tsx
new file mode 100644
index 0000000000..12354d7de9
--- /dev/null
+++ b/packages/studio/src/components/ColorPicker/ColorPicker.tsx
@@ -0,0 +1,263 @@
+import {PlayerInternals} from '@remotion/player';
+import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
+import ReactDOM from 'react-dom';
+import {HigherZIndex, useZIndex} from '../../state/z-index';
+import {MENU_INITIATOR_CLASSNAME} from '../Menu/is-menu-item';
+import {getPortal} from '../Menu/portals';
+import {
+ fullScreenOverlay,
+ menuContainerTowardsBottom,
+ menuContainerTowardsTop,
+ outerPortal,
+} from '../Menu/styles';
+import type {RemInputStatus} from '../NewComposition/RemInput';
+import {getInputBorderColor} from '../NewComposition/RemInput';
+import {
+ CHECKER_BACKGROUND_COLOR,
+ CHECKER_BACKGROUND_IMAGE,
+ CHECKER_BACKGROUND_POSITION,
+ CHECKER_BACKGROUND_SIZE,
+} from './checker';
+import {ColorPickerPopup, POPUP_WIDTH} from './ColorPickerPopup';
+
+const swatchBaseStyle: React.CSSProperties = {
+ position: 'relative',
+ display: 'inline-block',
+ overflow: 'hidden',
+ padding: 0,
+ margin: 0,
+ cursor: 'pointer',
+ backgroundColor: CHECKER_BACKGROUND_COLOR,
+ backgroundImage: CHECKER_BACKGROUND_IMAGE,
+ backgroundSize: CHECKER_BACKGROUND_SIZE,
+ backgroundPosition: CHECKER_BACKGROUND_POSITION,
+ borderStyle: 'solid',
+ borderWidth: 1,
+ boxSizing: 'border-box',
+};
+
+const fillStyle: React.CSSProperties = {
+ position: 'absolute',
+ inset: 0,
+ display: 'block',
+};
+
+type Props = {
+ readonly value: string;
+ readonly onChange: (next: string) => void;
+ readonly onChangeComplete: (next: string) => void;
+ readonly status: RemInputStatus;
+ readonly disabled?: boolean;
+ readonly width?: number;
+ readonly height?: number;
+ readonly borderRadius?: number;
+ readonly title?: string;
+ readonly name?: string;
+ readonly className?: string;
+ readonly style?: React.CSSProperties;
+};
+
+export const ColorPicker: React.FC<Props> = ({
+ value,
+ onChange,
+ onChangeComplete,
+ status,
+ disabled,
+ width = 45,
+ height = 25,
+ borderRadius = 3,
+ title,
+ name,
+ className,
+ style: customStyle,
+}) => {
+ const [opened, setOpened] = useState(false);
+ const [isHovered, setIsHovered] = useState(false);
+ const [isFocused, setIsFocused] = useState(false);
+ const triggerRef = useRef<HTMLButtonElement>(null);
+ const {tabIndex, currentZIndex} = useZIndex();
+
+ const size = PlayerInternals.useElementSize(triggerRef, {
+ triggerOnWindowResize: true,
+ shouldApplyCssTransforms: true,
+ });
+ const refresh = size?.refresh;
+
+ const onHide = useCallback(() => {
+ setOpened(false);
+ }, []);
+
+ const swatchFill = useMemo<React.CSSProperties>(() => {
+ return {
+ ...fillStyle,
+ backgroundColor: value,
+ };
+ }, [value]);
+
+ const swatchStyle: React.CSSProperties = useMemo(() => {
+ return {
+ ...swatchBaseStyle,
+ width,
+ height,
+ borderRadius,
+ borderColor: getInputBorderColor({status, isFocused, isHovered}),
+ cursor: disabled ? 'not-allowed' : 'pointer',
+ opacity: disabled ? 0.5 : 1,
+ ...(customStyle ?? {}),
+ };
+ }, [
+ borderRadius,
+ customStyle,
+ disabled,
+ height,
+ isFocused,
+ isHovered,
+ status,
+ width,
+ ]);
+
+ const onMouseEnter = useCallback(() => setIsHovered(true), []);
+ const onMouseLeave = useCallback(() => setIsHovered(false), []);
+ const onFocus = useCallback(() => setIsFocused(true), []);
+ const onBlur = useCallback(() => setIsFocused(false), []);
+
+ // Toggle on pointerdown (matches Combobox) so the state flips before the
+ // HigherZIndex outside-click detection runs on pointerup. If we toggled in
+ // onClick, the popup would close in pointerup and immediately re-open in
+ // the click that follows.
+ const onTriggerPointerDown = useCallback(() => {
+ if (disabled) {
+ return;
+ }
+
+ setOpened((prev) => {
+ if (!prev) {
+ refresh?.();
+ }
+
+ return !prev;
+ });
+ }, [disabled, refresh]);
+
+ const onTriggerClick = useCallback(
+ (e: React.MouseEvent<HTMLButtonElement>) => {
+ if (disabled) {
+ return;
+ }
+
+ // Keyboard-initiated activations (Enter/Space) don't fire pointerdown,
+ // so handle them here. Mouse clicks are already handled by pointerdown
+ // above; ignore them.
+ const isKeyboardInitiated = e.detail === 0;
+ if (!isKeyboardInitiated) {
+ return;
+ }
+
+ setOpened((prev) => {
+ if (!prev) {
+ refresh?.();
+ }
+
+ return !prev;
+ });
+ },
+ [disabled, refresh],
+ );
+
+ const portalStyle = useMemo((): React.CSSProperties | null => {
+ if (!opened || !size) {
+ return null;
+ }
+
+ const margin = 6;
+ const popupHeight = 250;
+ const popupWidth = POPUP_WIDTH;
+
+ const spaceBelow = size.windowSize.height - (size.top + size.height);
+ const spaceAbove = size.top;
+ const openBelow =
+ spaceBelow >= popupHeight + margin || spaceBelow >= spaceAbove;
+
+ const spaceRight = size.windowSize.width - size.left;
+ // Try aligning the popup to the trigger's left edge first; fall back
+ // to right-aligning if it would clip the viewport.
+ const left =
+ spaceRight >= popupWidth + margin
+ ? size.left
+ : Math.max(margin, size.windowSize.width - popupWidth - margin);
+
+ if (openBelow) {
+ return {
+ ...menuContainerTowardsBottom,
+ top: size.top + size.height + margin,
+ left,
+ background: 'transparent',
+ boxShadow: 'none',
+ };
+ }
+
+ return {
+ ...menuContainerTowardsTop,
+ bottom: size.windowSize.height - size.top + margin,
+ left,
+ background: 'transparent',
+ boxShadow: 'none',
+ };
+ }, [opened, size]);
+
+ useEffect(() => {
+ if (!opened) {
+ return;
+ }
+
+ const onWindowBlur = () => setOpened(false);
+ window.addEventListener('blur', onWindowBlur);
+ return () => window.removeEventListener('blur', onWindowBlur);
+ }, [opened]);
+
+ return (
+ <>
+ <button
+ ref={triggerRef}
+ type="button"
+ className={
+ className
+ ? `${MENU_INITIATOR_CLASSNAME} ${className}`
+ : MENU_INITIATOR_CLASSNAME
+ }
+ disabled={disabled}
+ name={name}
+ title={title ?? value}
+ tabIndex={tabIndex}
+ style={swatchStyle}
+ onPointerDown={onTriggerPointerDown}
+ onClick={onTriggerClick}
+ onMouseEnter={onMouseEnter}
+ onMouseLeave={onMouseLeave}
+ onFocus={onFocus}
+ onBlur={onBlur}
+ >
+ <span style={swatchFill} />
+ </button>
+ {portalStyle
+ ? ReactDOM.createPortal(
+ <div style={fullScreenOverlay}>
+ <div style={outerPortal} className="css-reset">
+ <HigherZIndex onOutsideClick={onHide} onEscape={onHide}>
+ <div style={portalStyle}>
+ <ColorPickerPopup
+ value={value}
+ onChange={onChange}
+ onChangeComplete={onChangeComplete}
+ tabIndex={tabIndex}
+ />
+ </div>
+ </HigherZIndex>
+ </div>
+ </div>,
+ getPortal(currentZIndex),
+ )
+ : null}
+ </>
+ );
+};
diff --git a/packages/studio/src/components/ColorPicker/ColorPickerPopup.tsx b/packages/studio/src/components/ColorPicker/ColorPickerPopup.tsx
new file mode 100644
index 0000000000..2aa2c8ead0
--- /dev/null
+++ b/packages/studio/src/components/ColorPicker/ColorPickerPopup.tsx
@@ -0,0 +1,479 @@
+import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
+import {
+ formatRgba,
+ hsvaToRgba,
+ parseAnyColor,
+ rgbaToHsva,
+ type Hsva,
+} from '../../helpers/color-conversion';
+import {INPUT_BACKGROUND, LIGHT_TEXT} from '../../helpers/colors';
+import {EyedropperIcon} from '../../icons/eyedropper';
+import {AlphaSlider} from './AlphaSlider';
+import {
+ CHECKER_BACKGROUND_COLOR,
+ CHECKER_BACKGROUND_IMAGE,
+ CHECKER_BACKGROUND_POSITION,
+ CHECKER_BACKGROUND_SIZE,
+} from './checker';
+import {HueSlider} from './HueSlider';
+import {SaturationValueArea} from './SaturationValueArea';
+
+export const POPUP_WIDTH = 240;
+const POPUP_PADDING = 12;
+
+const popupShellStyle: React.CSSProperties = {
+ width: POPUP_WIDTH,
+ padding: POPUP_PADDING,
+ background: '#1f2428',
+ border: '1px solid rgba(0, 0, 0, 0.6)',
+ borderRadius: 4,
+ boxShadow: '0 4px 16px rgba(0, 0, 0, 0.5)',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 10,
+ color: 'white',
+ fontSize: 12,
+ userSelect: 'none',
+ WebkitUserSelect: 'none',
+};
+
+const sliderRowStyle: React.CSSProperties = {
+ display: 'flex',
+ alignItems: 'center',
+ gap: 8,
+};
+
+const previewSwatchStyle: React.CSSProperties = {
+ position: 'relative',
+ width: 28,
+ height: 28,
+ flex: '0 0 auto',
+ borderRadius: 14,
+ overflow: 'hidden',
+ border: '1px solid rgba(0, 0, 0, 0.6)',
+ backgroundColor: CHECKER_BACKGROUND_COLOR,
+ backgroundImage: CHECKER_BACKGROUND_IMAGE,
+ backgroundSize: CHECKER_BACKGROUND_SIZE,
+ backgroundPosition: CHECKER_BACKGROUND_POSITION,
+};
+
+const previewSwatchFillBase: React.CSSProperties = {
+ position: 'absolute',
+ inset: 0,
+};
+
+const slidersColumnStyle: React.CSSProperties = {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 6,
+ flex: 1,
+};
+
+const inputsRowStyle: React.CSSProperties = {
+ display: 'flex',
+ gap: 6,
+ alignItems: 'flex-end',
+};
+
+const inputColumnStyle: React.CSSProperties = {
+ display: 'flex',
+ flexDirection: 'column',
+ flex: 1,
+ minWidth: 0,
+};
+
+const labelStyle: React.CSSProperties = {
+ color: LIGHT_TEXT,
+ fontSize: 10,
+ textTransform: 'uppercase',
+ letterSpacing: 0.5,
+ marginBottom: 2,
+};
+
+const baseInputStyle: React.CSSProperties = {
+ width: '100%',
+ background: INPUT_BACKGROUND,
+ border: '1px solid rgba(0, 0, 0, 0.6)',
+ borderRadius: 3,
+ color: 'white',
+ padding: '4px 6px',
+ fontSize: 12,
+ textAlign: 'center',
+ boxSizing: 'border-box',
+};
+
+const eyedropperButtonStyle: React.CSSProperties = {
+ background: 'transparent',
+ border: '1px solid rgba(0, 0, 0, 0.6)',
+ borderRadius: 3,
+ padding: 0,
+ cursor: 'pointer',
+ color: LIGHT_TEXT,
+ width: 28,
+ height: 28,
+ display: 'inline-flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ flex: '0 0 auto',
+};
+
+const hasEyeDropper = (): boolean =>
+ typeof window !== 'undefined' && 'EyeDropper' in window;
+
+type ChannelInputProps = {
+ readonly label: string;
+ readonly value: number;
+ readonly min: number;
+ readonly max: number;
+ readonly tabIndex: number;
+ readonly onCommit: (next: number) => void;
+};
+
+const ChannelInput: React.FC<ChannelInputProps> = ({
+ label,
+ value,
+ min,
+ max,
+ tabIndex,
+ onCommit,
+}) => {
+ const [draft, setDraft] = useState<string>(String(Math.round(value)));
+
+ useEffect(() => {
+ setDraft(String(Math.round(value)));
+ }, [value]);
+
+ const onChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
+ setDraft(e.target.value);
+ }, []);
+
+ const onBlur = useCallback(() => {
+ const parsed = Number(draft);
+ if (Number.isNaN(parsed)) {
+ setDraft(String(Math.round(value)));
+ return;
+ }
+
+ const clamped = Math.max(min, Math.min(max, parsed));
+ setDraft(String(Math.round(clamped)));
+ onCommit(clamped);
+ }, [draft, max, min, onCommit, value]);
+
+ const onKeyDown = useCallback((e: React.KeyboardEvent<HTMLInputElement>) => {
+ if (e.key === 'Enter') {
+ (e.target as HTMLInputElement).blur();
+ }
+ }, []);
+
+ return (
+ <label style={inputColumnStyle}>
+ <span style={labelStyle}>{label}</span>
+ <input
+ type="text"
+ inputMode="numeric"
+ value={draft}
+ onChange={onChange}
+ onBlur={onBlur}
+ onKeyDown={onKeyDown}
+ style={baseInputStyle}
+ tabIndex={tabIndex}
+ />
+ </label>
+ );
+};
+
+const HexInput: React.FC<{
+ readonly value: string;
+ readonly onCommit: (next: string) => void;
+ readonly tabIndex: number;
+}> = ({value, onCommit, tabIndex}) => {
+ const [draft, setDraft] = useState(value);
+
+ useEffect(() => {
+ setDraft(value);
+ }, [value]);
+
+ const onChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
+ setDraft(e.target.value);
+ }, []);
+
+ const onBlur = useCallback(() => {
+ try {
+ const parsed = parseAnyColor(draft);
+ onCommit(formatRgba(parsed));
+ } catch {
+ setDraft(value);
+ }
+ }, [draft, onCommit, value]);
+
+ const onKeyDown = useCallback((e: React.KeyboardEvent<HTMLInputElement>) => {
+ if (e.key === 'Enter') {
+ (e.target as HTMLInputElement).blur();
+ }
+ }, []);
+
+ const style: React.CSSProperties = useMemo(() => {
+ return {
+ ...baseInputStyle,
+ textAlign: 'left',
+ };
+ }, []);
+
+ return (
+ <label style={inputColumnStyle}>
+ <span style={labelStyle}>Hex</span>
+ <input
+ type="text"
+ value={draft}
+ onChange={onChange}
+ onBlur={onBlur}
+ onKeyDown={onKeyDown}
+ style={style}
+ autoComplete="off"
+ spellCheck={false}
+ tabIndex={tabIndex}
+ />
+ </label>
+ );
+};
+
+export const ColorPickerPopup: React.FC<{
+ readonly value: string;
+ readonly onChange: (next: string) => void;
+ readonly onChangeComplete: (next: string) => void;
+ readonly tabIndex: number;
+}> = ({value, onChange, onChangeComplete, tabIndex}) => {
+ // HSV is the source of truth while the picker is open. We seed it from
+ // the incoming value but keep our own state so that hue and saturation
+ // don't snap back to 0 when the user drags into pure black/white.
+ const [hsva, setHsva] = useState<Hsva>(() =>
+ rgbaToHsva(parseAnyColor(value)),
+ );
+ const lastEmittedRef = useRef<string>(formatRgba(parseAnyColor(value)));
+
+ useEffect(() => {
+ // Sync from external value changes that didn't originate from us.
+ const incoming = formatRgba(parseAnyColor(value));
+ if (incoming === lastEmittedRef.current) {
+ return;
+ }
+
+ lastEmittedRef.current = incoming;
+ setHsva(rgbaToHsva(parseAnyColor(value)));
+ }, [value]);
+
+ const rgba = useMemo(() => hsvaToRgba(hsva), [hsva]);
+ const formatted = useMemo(() => formatRgba(rgba), [rgba]);
+
+ const emit = useCallback(
+ (next: Hsva, mode: 'change' | 'complete') => {
+ setHsva(next);
+ const nextRgba = hsvaToRgba(next);
+ const nextFormatted = formatRgba(nextRgba);
+ lastEmittedRef.current = nextFormatted;
+ if (mode === 'complete') {
+ onChangeComplete(nextFormatted);
+ } else {
+ onChange(nextFormatted);
+ }
+ },
+ [onChange, onChangeComplete],
+ );
+
+ const onSvChange = useCallback(
+ (next: {s: number; v: number}) => {
+ emit({...hsva, s: next.s, v: next.v}, 'change');
+ },
+ [emit, hsva],
+ );
+
+ const onSvComplete = useCallback(
+ (next: {s: number; v: number}) => {
+ emit({...hsva, s: next.s, v: next.v}, 'complete');
+ },
+ [emit, hsva],
+ );
+
+ const onHueChange = useCallback(
+ (next: number) => {
+ emit({...hsva, h: next}, 'change');
+ },
+ [emit, hsva],
+ );
+
+ const onHueComplete = useCallback(
+ (next: number) => {
+ emit({...hsva, h: next}, 'complete');
+ },
+ [emit, hsva],
+ );
+
+ const onAlphaChange = useCallback(
+ (next: number) => {
+ emit({...hsva, a: next}, 'change');
+ },
+ [emit, hsva],
+ );
+
+ const onAlphaComplete = useCallback(
+ (next: number) => {
+ emit({...hsva, a: next}, 'complete');
+ },
+ [emit, hsva],
+ );
+
+ const onChannelCommit = useCallback(
+ (channel: 'r' | 'g' | 'b' | 'a', next: number) => {
+ const updatedRgba = {...rgba, [channel]: next};
+ const newHsva = rgbaToHsva(updatedRgba);
+ // Preserve hue when transitioning through achromatic colors.
+ if (newHsva.s === 0) {
+ newHsva.h = hsva.h;
+ }
+
+ emit(newHsva, 'complete');
+ },
+ [emit, hsva.h, rgba],
+ );
+
+ const onHexCommit = useCallback(
+ (next: string) => {
+ const parsed = parseAnyColor(next);
+ const newHsva = rgbaToHsva(parsed);
+ if (newHsva.s === 0) {
+ newHsva.h = hsva.h;
+ }
+
+ emit(newHsva, 'complete');
+ },
+ [emit, hsva.h],
+ );
+
+ const onPickWithEyeDropper = useCallback(() => {
+ const Ctor = (
+ window as unknown as {
+ EyeDropper?: new () => {open: () => Promise<{sRGBHex: string}>};
+ }
+ ).EyeDropper;
+ if (!Ctor) {
+ return;
+ }
+
+ const dropper = new Ctor();
+ dropper
+ .open()
+ .then((result) => {
+ const parsed = parseAnyColor(result.sRGBHex);
+ // `EyeDropper` always returns full opacity; preserve the user's
+ // previously chosen alpha so opening it doesn't drop transparency.
+ parsed.a = rgba.a;
+ const newHsva = rgbaToHsva(parsed);
+ if (newHsva.s === 0) {
+ newHsva.h = hsva.h;
+ }
+
+ emit(newHsva, 'complete');
+ })
+ .catch(() => {
+ // Aborted; ignore.
+ });
+ }, [emit, hsva.h, rgba.a]);
+
+ const previewFill: React.CSSProperties = useMemo(() => {
+ return {
+ ...previewSwatchFillBase,
+ backgroundColor: formatted,
+ };
+ }, [formatted]);
+
+ const showEyeDropper = hasEyeDropper();
+
+ return (
+ <div style={popupShellStyle}>
+ <SaturationValueArea
+ hue={hsva.h}
+ saturation={hsva.s}
+ value={hsva.v}
+ onChange={onSvChange}
+ onChangeComplete={onSvComplete}
+ />
+ <div style={sliderRowStyle}>
+ {showEyeDropper ? (
+ <button
+ type="button"
+ style={eyedropperButtonStyle}
+ onClick={onPickWithEyeDropper}
+ tabIndex={tabIndex}
+ title="Pick color from screen"
+ aria-label="Pick color from screen"
+ >
+ <EyedropperIcon
+ style={{width: 14, height: 14}}
+ color="currentColor"
+ />
+ </button>
+ ) : null}
+ <div style={previewSwatchStyle} title={formatted}>
+ <div style={previewFill} />
+ </div>
+ <div style={slidersColumnStyle}>
+ <HueSlider
+ hue={hsva.h}
+ onChange={onHueChange}
+ onChangeComplete={onHueComplete}
+ />
+ <AlphaSlider
+ hue={hsva.h}
+ saturation={hsva.s}
+ value={hsva.v}
+ alpha={hsva.a}
+ onChange={onAlphaChange}
+ onChangeComplete={onAlphaComplete}
+ />
+ </div>
+ </div>
+ <div style={inputsRowStyle}>
+ <HexInput
+ value={formatted}
+ onCommit={onHexCommit}
+ tabIndex={tabIndex}
+ />
+ <ChannelInput
+ label="R"
+ value={rgba.r}
+ min={0}
+ max={255}
+ tabIndex={tabIndex}
+ onCommit={(next) => onChannelCommit('r', next)}
+ />
+ <ChannelInput
+ label="G"
+ value={rgba.g}
+ min={0}
+ max={255}
+ tabIndex={tabIndex}
+ onCommit={(next) => onChannelCommit('g', next)}
+ />
+ <ChannelInput
+ label="B"
+ value={rgba.b}
+ min={0}
+ max={255}
+ tabIndex={tabIndex}
+ onCommit={(next) => onChannelCommit('b', next)}
+ />
+ <ChannelInput
+ label="A%"
+ value={Math.round(hsva.a * 100)}
+ min={0}
+ max={100}
+ tabIndex={tabIndex}
+ onCommit={(next) => {
+ const clamped = Math.max(0, Math.min(100, next));
+ emit({...hsva, a: clamped / 100}, 'complete');
+ }}
+ />
+ </div>
+ </div>
+ );
+};
diff --git a/packages/studio/src/components/ColorPicker/HueSlider.tsx b/packages/studio/src/components/ColorPicker/HueSlider.tsx
new file mode 100644
index 0000000000..0c80d451a1
--- /dev/null
+++ b/packages/studio/src/components/ColorPicker/HueSlider.tsx
@@ -0,0 +1,89 @@
+import React, {useCallback, useMemo, useRef} from 'react';
+import {clamp} from '../../helpers/color-conversion';
+
+const SLIDER_HEIGHT = 12;
+const HANDLE_WIDTH = 8;
+
+const containerStyle: React.CSSProperties = {
+ position: 'relative',
+ height: SLIDER_HEIGHT,
+ width: '100%',
+ borderRadius: 3,
+ cursor: 'ew-resize',
+ background:
+ 'linear-gradient(to right, #f00 0%, #ff0 17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%)',
+ touchAction: 'none',
+};
+
+export const HueSlider: React.FC<{
+ readonly hue: number;
+ readonly onChange: (next: number) => void;
+ readonly onChangeComplete: (next: number) => void;
+}> = ({hue, onChange, onChangeComplete}) => {
+ const ref = useRef<HTMLDivElement>(null);
+
+ const updateFromEvent = useCallback(
+ (clientX: number, isFinal: boolean) => {
+ const {current} = ref;
+ if (!current) {
+ return;
+ }
+
+ const rect = current.getBoundingClientRect();
+ const x = clamp((clientX - rect.left) / rect.width, 0, 1);
+ const next = x * 360;
+ if (isFinal) {
+ onChangeComplete(next);
+ } else {
+ onChange(next);
+ }
+ },
+ [onChange, onChangeComplete],
+ );
+
+ const onPointerDown = useCallback(
+ (e: React.PointerEvent<HTMLDivElement>) => {
+ if (e.button !== 0) {
+ return;
+ }
+
+ e.preventDefault();
+ updateFromEvent(e.clientX, false);
+
+ const onMove = (ev: PointerEvent) => {
+ updateFromEvent(ev.clientX, false);
+ };
+
+ const onUp = (ev: PointerEvent) => {
+ window.removeEventListener('pointermove', onMove);
+ window.removeEventListener('pointerup', onUp);
+ updateFromEvent(ev.clientX, true);
+ };
+
+ window.addEventListener('pointermove', onMove);
+ window.addEventListener('pointerup', onUp);
+ },
+ [updateFromEvent],
+ );
+
+ const handleStyle: React.CSSProperties = useMemo(() => {
+ return {
+ position: 'absolute',
+ top: -2,
+ left: `${(hue / 360) * 100}%`,
+ marginLeft: -HANDLE_WIDTH / 2,
+ width: HANDLE_WIDTH,
+ height: SLIDER_HEIGHT + 4,
+ borderRadius: 2,
+ border: '2px solid #fff',
+ boxShadow: '0 0 0 1px rgba(0, 0, 0, 0.6)',
+ pointerEvents: 'none',
+ };
+ }, [hue]);
+
+ return (
+ <div ref={ref} style={containerStyle} onPointerDown={onPointerDown}>
+ <div style={handleStyle} />
+ </div>
+ );
+};
diff --git a/packages/studio/src/components/ColorPicker/SaturationValueArea.tsx b/packages/studio/src/components/ColorPicker/SaturationValueArea.tsx
new file mode 100644
index 0000000000..fcc257f9fd
--- /dev/null
+++ b/packages/studio/src/components/ColorPicker/SaturationValueArea.tsx
@@ -0,0 +1,124 @@
+import React, {useCallback, useMemo, useRef} from 'react';
+import {clamp, hsvToRgb} from '../../helpers/color-conversion';
+
+const AREA_HEIGHT = 140;
+
+const containerStyle: React.CSSProperties = {
+ position: 'relative',
+ width: '100%',
+ height: AREA_HEIGHT,
+ cursor: 'crosshair',
+ borderRadius: 3,
+ overflow: 'hidden',
+ touchAction: 'none',
+};
+
+const valueOverlay: React.CSSProperties = {
+ position: 'absolute',
+ inset: 0,
+ background: 'linear-gradient(to top, #000, transparent)',
+};
+
+const saturationOverlay: React.CSSProperties = {
+ position: 'absolute',
+ inset: 0,
+ background: 'linear-gradient(to right, #fff, transparent)',
+};
+
+export const SaturationValueArea: React.FC<{
+ readonly hue: number;
+ readonly saturation: number;
+ readonly value: number;
+ readonly onChange: (next: {s: number; v: number}) => void;
+ readonly onChangeComplete: (next: {s: number; v: number}) => void;
+}> = ({hue, saturation, value, onChange, onChangeComplete}) => {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const lastSV = useRef({s: saturation, v: value});
+
+ const baseColor = useMemo(() => {
+ const {r, g, b} = hsvToRgb({h: hue, s: 1, v: 1});
+ return `rgb(${r}, ${g}, ${b})`;
+ }, [hue]);
+
+ const updateFromEvent = useCallback(
+ (clientX: number, clientY: number, isFinal: boolean) => {
+ const {current} = containerRef;
+ if (!current) {
+ return;
+ }
+
+ const rect = current.getBoundingClientRect();
+ const x = clamp((clientX - rect.left) / rect.width, 0, 1);
+ const y = clamp((clientY - rect.top) / rect.height, 0, 1);
+ const next = {s: x, v: 1 - y};
+ lastSV.current = next;
+ if (isFinal) {
+ onChangeComplete(next);
+ } else {
+ onChange(next);
+ }
+ },
+ [onChange, onChangeComplete],
+ );
+
+ const onPointerDown = useCallback(
+ (e: React.PointerEvent<HTMLDivElement>) => {
+ if (e.button !== 0) {
+ return;
+ }
+
+ e.preventDefault();
+ (e.target as HTMLElement).setPointerCapture?.(e.pointerId);
+ updateFromEvent(e.clientX, e.clientY, false);
+
+ const onMove = (ev: PointerEvent) => {
+ updateFromEvent(ev.clientX, ev.clientY, false);
+ };
+
+ const onUp = (ev: PointerEvent) => {
+ window.removeEventListener('pointermove', onMove);
+ window.removeEventListener('pointerup', onUp);
+ updateFromEvent(ev.clientX, ev.clientY, true);
+ };
+
+ window.addEventListener('pointermove', onMove);
+ window.addEventListener('pointerup', onUp);
+ },
+ [updateFromEvent],
+ );
+
+ const containerWithBg: React.CSSProperties = useMemo(() => {
+ return {
+ ...containerStyle,
+ backgroundColor: baseColor,
+ };
+ }, [baseColor]);
+
+ const handleStyle: React.CSSProperties = useMemo(() => {
+ return {
+ position: 'absolute',
+ left: `${saturation * 100}%`,
+ top: `${(1 - value) * 100}%`,
+ width: 12,
+ height: 12,
+ marginLeft: -6,
+ marginTop: -6,
+ borderRadius: '50%',
+ border: '2px solid #fff',
+ boxShadow: '0 0 0 1px rgba(0, 0, 0, 0.6)',
+ pointerEvents: 'none',
+ };
+ }, [saturation, value]);
+
+ return (
+ <div
+ ref={containerRef}
+ style={containerWithBg}
+ onPointerDown={onPointerDown}
+ >
+ <div style={saturationOverlay} />
+ <div style={valueOverlay} />
+ <div style={handleStyle} />
+ </div>
+ );
+};
diff --git a/packages/studio/src/components/ColorPicker/checker.ts b/packages/studio/src/components/ColorPicker/checker.ts
new file mode 100644
index 0000000000..25aaad0df6
--- /dev/null
+++ b/packages/studio/src/components/ColorPicker/checker.ts
@@ -0,0 +1,8 @@
+// Checkerboard background used to indicate transparency in color swatches
+// and the alpha slider. Rendered as a CSS gradient so we don't need an asset.
+export const CHECKER_BACKGROUND_IMAGE =
+ 'linear-gradient(45deg, #888 25%, transparent 25%), linear-gradient(-45deg, #888 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #888 75%), linear-gradient(-45deg, transparent 75%, #888 75%)';
+
+export const CHECKER_BACKGROUND_SIZE = '8px 8px';
+export const CHECKER_BACKGROUND_POSITION = '0 0, 0 4px, 4px -4px, -4px 0';
+export const CHECKER_BACKGROUND_COLOR = '#444';
diff --git a/packages/studio/src/components/NewComposition/RemInputTypeColor.tsx b/packages/studio/src/components/NewComposition/RemInputTypeColor.tsx
deleted file mode 100644
index 43258c429a..0000000000
--- a/packages/studio/src/components/NewComposition/RemInputTypeColor.tsx
+++ /dev/null
@@ -1,87 +0,0 @@
-import React, {
- forwardRef,
- useEffect,
- useImperativeHandle,
- useMemo,
- useRef,
- useState,
-} from 'react';
-import {INPUT_BACKGROUND} from '../../helpers/colors';
-import {useZIndex} from '../../state/z-index';
-import type {RemInputStatus} from './RemInput';
-import {getInputBorderColor} from './RemInput';
-
-type Props = React.DetailedHTMLProps<
- React.InputHTMLAttributes<HTMLInputElement>,
- HTMLInputElement
-> & {
- readonly status: RemInputStatus;
- readonly name: string;
-};
-
-const inputBaseStyle: React.CSSProperties = {
- padding: 0,
- borderStyle: 'solid',
- borderWidth: 1,
-};
-
-const RemInputTypeColorForwardRef: React.ForwardRefRenderFunction<
- HTMLInputElement,
- Props
-> = ({status, ...props}, ref) => {
- const [isFocused, setIsFocused] = useState(false);
- const [isHovered, setIsHovered] = useState(false);
- const inputRef = useRef<HTMLInputElement>(null);
- const {tabIndex} = useZIndex();
-
- const style = useMemo(() => {
- return {
- backgroundColor: INPUT_BACKGROUND,
- ...inputBaseStyle,
- borderColor: getInputBorderColor({isFocused, isHovered, status}),
- ...(props.style ?? {}),
- };
- }, [isFocused, isHovered, props.style, status]);
-
- useImperativeHandle(ref, () => {
- return inputRef.current as HTMLInputElement;
- }, []);
-
- useEffect(() => {
- if (!inputRef.current) {
- return;
- }
-
- const {current} = inputRef;
-
- const onFocus = () => setIsFocused(true);
- const onBlur = () => setIsFocused(false);
- const onMouseEnter = () => setIsHovered(true);
- const onMouseLeave = () => setIsHovered(false);
-
- current.addEventListener('focus', onFocus);
- current.addEventListener('blur', onBlur);
- current.addEventListener('mouseenter', onMouseEnter);
- current.addEventListener('mouseleave', onMouseLeave);
-
- return () => {
- current.removeEventListener('focus', onFocus);
- current.removeEventListener('blur', onBlur);
- current.removeEventListener('mouseenter', onMouseEnter);
- current.removeEventListener('mouseleave', onMouseLeave);
- };
- }, [inputRef]);
-
- return (
- <input
- ref={inputRef}
- type="color"
- tabIndex={tabIndex}
- {...props}
- name={props.name}
- style={style}
- />
- );
-};
-
-export const RemInputTypeColor = forwardRef(RemInputTypeColorForwardRef);
diff --git a/packages/studio/src/components/RenderModal/SchemaEditor/ZodColorEditor.tsx b/packages/studio/src/components/RenderModal/SchemaEditor/ZodColorEditor.tsx
index 9c2f974f60..b6eeb302f4 100644
--- a/packages/studio/src/components/RenderModal/SchemaEditor/ZodColorEditor.tsx
+++ b/packages/studio/src/components/RenderModal/SchemaEditor/ZodColorEditor.tsx
@@ -1,13 +1,7 @@
import React, {useCallback, useMemo} from 'react';
-import {colorWithNewOpacity} from '../../../helpers/color-math';
-import {
- useZodIfPossible,
- useZodTypesIfPossible,
-} from '../../get-zod-if-possible';
+import {ColorPicker} from '../../ColorPicker/ColorPicker';
import {Row, Spacing} from '../../layout';
-import {InputDragger} from '../../NewComposition/InputDragger';
import {RemotionInput} from '../../NewComposition/RemInput';
-import {RemInputTypeColor} from '../../NewComposition/RemInputTypeColor';
import {Fieldset} from './Fieldset';
import {SchemaLabel} from './SchemaLabel';
import {zodSafeParse, type AnyZodSchema} from './zod-schema-type';
@@ -27,41 +21,24 @@ export const ZodColorEditor: React.FC<{
readonly onRemove: null | (() => void);
readonly mayPad: boolean;
}> = ({jsonPath, value, setValue, schema, onRemove, mayPad}) => {
- const z = useZodIfPossible();
- if (!z) {
- throw new Error('expected zod');
- }
-
- const zodTypes = useZodTypesIfPossible();
- if (!zodTypes) {
- throw new Error('expected zod color');
- }
-
const localValue = useMemo(
() => zodSafeParse(schema, value),
[schema, value],
);
- const {a, b, g, r} = localValue.success
- ? zodTypes.ZodZypesInternals.parseColor(value)
- : {a: 1, b: 0, g: 0, r: 0};
-
- const onChange: React.ChangeEventHandler<HTMLInputElement> = useCallback(
- (e) => {
- const newColor = colorWithNewOpacity(
- e.target.value,
- Math.round(a),
- zodTypes,
- );
- setValue(() => newColor, {shouldSave: false});
+ const onPickerChange = useCallback(
+ (next: string) => {
+ setValue(() => next, {shouldSave: false});
},
- [a, setValue, zodTypes],
+ [setValue],
);
- const onColorBlur: React.FocusEventHandler<HTMLInputElement> =
- useCallback(() => {
- setValue(() => value, {shouldSave: true});
- }, [setValue, value]);
+ const onPickerComplete = useCallback(
+ (next: string) => {
+ setValue(() => next, {shouldSave: true});
+ },
+ [setValue],
+ );
const onTextChange: React.ChangeEventHandler<HTMLInputElement> = useCallback(
(e) => {
@@ -76,56 +53,8 @@ export const ZodColorEditor: React.FC<{
setValue(() => value, {shouldSave: true});
}, [setValue, value]);
- const rgb = `#${r.toString(16).padStart(2, '0')}${g
- .toString(16)
- .padStart(2, '0')}${b.toString(16).padStart(2, '0')}`;
-
const status = localValue.success ? 'ok' : 'error';
- const colorPicker: React.CSSProperties = useMemo(() => {
- return {
- height: 39,
- width: 45,
- display: 'inline-block',
- };
- }, []);
-
- const onOpacityChange = useCallback(
- (newValue: string) => {
- const newColor = colorWithNewOpacity(
- value,
- Math.round((Number(newValue) / 100) * 255),
- zodTypes,
- );
- setValue(() => newColor, {shouldSave: true});
- },
- [setValue, value, zodTypes],
- );
-
- const onOpacityValueChange = useCallback(
- (newValue: number) => {
- const newColor = colorWithNewOpacity(
- value,
- Math.round((Number(newValue) / 100) * 255),
- zodTypes,
- );
- setValue(() => newColor, {shouldSave: false});
- },
- [setValue, value, zodTypes],
- );
-
- const onOpacityValueChangeEnd = useCallback(
- (newValue: number) => {
- const newColor = colorWithNewOpacity(
- value,
- Math.round((Number(newValue) / 100) * 255),
- zodTypes,
- );
- setValue(() => newColor, {shouldSave: true});
- },
- [setValue, value, zodTypes],
- );
-
return (
<Fieldset shouldPad={mayPad}>
<SchemaLabel
@@ -137,20 +66,15 @@ export const ZodColorEditor: React.FC<{
/>
<div style={fullWidth}>
<Row align="center">
- <div style={colorPicker}>
- <RemInputTypeColor
- type="color"
- style={{
- height: 39,
- }}
- value={rgb}
- onChange={onChange}
- onBlur={onColorBlur}
- className="__remotion_color_picker"
- status={status}
- name={jsonPath.join('.')}
- />
- </div>
+ <ColorPicker
+ value={value}
+ status={status}
+ onChange={onPickerChange}
+ onChangeComplete={onPickerComplete}
+ width={45}
+ height={39}
+ name={jsonPath.join('.')}
+ />
<Spacing x={1} block />
<RemotionInput
value={value}
@@ -160,19 +84,6 @@ export const ZodColorEditor: React.FC<{
onBlur={onTextBlur}
rightAlign={false}
/>
- <Spacing x={1} />
- <InputDragger
- onTextChange={onOpacityChange}
- onValueChange={onOpacityValueChange}
- onValueChangeEnd={onOpacityValueChangeEnd}
- status={status}
- value={(a / 255) * 100}
- min={0}
- max={100}
- step={1}
- formatter={(v) => `${Math.round(Number(v))}%`}
- rightAlign={false}
- />
</Row>
<ZodFieldValidation path={jsonPath} zodValidation={localValue} />
</div>
diff --git a/packages/studio/src/components/Timeline/TimelineColorField.tsx b/packages/studio/src/components/Timeline/TimelineColorField.tsx
index 4c3e45e3be..9080a5745a 100644
--- a/packages/studio/src/components/Timeline/TimelineColorField.tsx
+++ b/packages/studio/src/components/Timeline/TimelineColorField.tsx
@@ -1,20 +1,11 @@
-import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
+import React, {useCallback, useMemo} from 'react';
import type {CanUpdateSequencePropStatus} from 'remotion';
-import {NoReactInternals} from 'remotion/no-react';
-import {
- INPUT_BORDER_COLOR_HOVERED,
- INPUT_BORDER_COLOR_UNHOVERED,
-} from '../../helpers/colors';
import type {
SchemaFieldInfo,
TimelineFieldOnDragValueChange,
TimelineFieldOnSave,
} from '../../helpers/timeline-layout';
-import {EyedropperIcon} from '../../icons/eyedropper';
-import {useZIndex} from '../../state/z-index';
-
-const SWATCH_WIDTH = 20;
-const SWATCH_HEIGHT = 15;
+import {ColorPicker} from '../ColorPicker/ColorPicker';
const containerStyle: React.CSSProperties = {
display: 'flex',
@@ -22,72 +13,8 @@ const containerStyle: React.CSSProperties = {
gap: 3,
};
-const swatchWrapperBase: React.CSSProperties = {
- position: 'relative',
- width: SWATCH_WIDTH,
- height: SWATCH_HEIGHT,
- display: 'inline-block',
- borderRadius: 3,
- overflow: 'hidden',
- cursor: 'pointer',
- borderStyle: 'solid',
- borderWidth: 1,
-};
-
-const hiddenInputStyle: React.CSSProperties = {
- position: 'absolute',
- inset: 0,
- width: '100%',
- height: '100%',
- opacity: 0,
- cursor: 'pointer',
- border: 'none',
- padding: 0,
- margin: 0,
-};
-
-const swatchFillStyle: React.CSSProperties = {
- width: '100%',
- height: '100%',
-};
-
-const eyedropperButtonBase: React.CSSProperties = {
- background: 'transparent',
- border: 'none',
- padding: 0,
- margin: 0,
- cursor: 'pointer',
- display: 'inline-flex',
- alignItems: 'center',
- justifyContent: 'center',
- width: 20,
- height: 20,
- color: 'rgba(255, 255, 255, 0.7)',
-};
-
-const eyedropperIconStyle: React.CSSProperties = {
- width: 16,
- height: 16,
-};
-
-// Normalizes any color string the user provided (e.g. `red`, `rgb(...)`, `#fff`)
-// into a `#rrggbb` string that `<input type="color">` accepts.
-const toHex = (value: string): string => {
- try {
- const argb = NoReactInternals.processColor(value);
- const r = (argb >>> 16) & 0xff;
- const g = (argb >>> 8) & 0xff;
- const b = argb & 0xff;
- return `#${r.toString(16).padStart(2, '0')}${g
- .toString(16)
- .padStart(2, '0')}${b.toString(16).padStart(2, '0')}`;
- } catch {
- return '#000000';
- }
-};
-
-const hasEyeDropper = (): boolean =>
- typeof window !== 'undefined' && 'EyeDropper' in window;
+const SWATCH_WIDTH = 20;
+const SWATCH_HEIGHT = 15;
export const TimelineColorField: React.FC<{
readonly field: SchemaFieldInfo;
@@ -104,29 +31,6 @@ export const TimelineColorField: React.FC<{
onDragValueChange,
onDragEnd,
}) => {
- const inputRef = useRef<HTMLInputElement>(null);
- const [isHovered, setIsHovered] = useState(false);
- const [isFocused, setIsFocused] = useState(false);
- const {tabIndex} = useZIndex();
-
- const commitTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- const pendingCommitRef = useRef<(() => void) | null>(null);
-
- // `<input type="color">` doesn't fire an event when dismissed; debounce
- // commits and flush any pending commit on unmount so we never lose the
- // final value.
- useEffect(() => {
- return () => {
- if (commitTimeoutRef.current) {
- clearTimeout(commitTimeoutRef.current);
- }
-
- if (pendingCommitRef.current) {
- pendingCommitRef.current();
- }
- };
- }, []);
-
const currentValue =
typeof effectiveValue === 'string'
? effectiveValue
@@ -134,143 +38,52 @@ export const TimelineColorField: React.FC<{
? field.fieldSchema.default
: '';
- const hexValue = useMemo(() => toHex(currentValue), [currentValue]);
-
- const onColorChange: React.ChangeEventHandler<HTMLInputElement> = useCallback(
- (e) => {
- const newValue = e.target.value;
+ const onChange = useCallback(
+ (next: string) => {
if (!propStatus.canUpdate) {
return;
}
- onDragValueChange(newValue);
+ onDragValueChange(next);
+ },
+ [onDragValueChange, propStatus.canUpdate],
+ );
- if (commitTimeoutRef.current) {
- clearTimeout(commitTimeoutRef.current);
+ const onChangeComplete = useCallback(
+ (next: string) => {
+ if (!propStatus.canUpdate) {
+ return;
}
- const commit = () => {
- pendingCommitRef.current = null;
- if (propStatus.canUpdate && newValue !== propStatus.codeValue) {
- onSave(newValue);
- }
-
- onDragEnd();
- };
-
- pendingCommitRef.current = commit;
+ if (next !== propStatus.codeValue) {
+ onSave(next);
+ }
- commitTimeoutRef.current = setTimeout(() => {
- commitTimeoutRef.current = null;
- commit();
- }, 500);
+ onDragEnd();
},
- [onSave, onDragValueChange, onDragEnd, propStatus],
+ [onSave, onDragEnd, propStatus],
);
- const onPickColor = useCallback(() => {
- // `EyeDropper` is a Chromium-only API; it's feature-detected at render
- // time so this only runs in supported browsers.
- const EyeDropperCtor =
- typeof window !== 'undefined'
- ? (
- window as unknown as {
- EyeDropper?: new () => {open: () => Promise<{sRGBHex: string}>};
- }
- ).EyeDropper
- : undefined;
- if (!EyeDropperCtor) {
- return;
- }
-
- const eyeDropper = new EyeDropperCtor();
- eyeDropper
- .open()
- .then((result) => {
- if (propStatus.canUpdate && result.sRGBHex !== propStatus.codeValue) {
- onSave(result.sRGBHex);
- }
- })
- .catch(() => {
- // User aborted or picker failed; safe to ignore.
- });
- }, [onSave, propStatus]);
-
- const swatchWrapperStyle = useMemo<React.CSSProperties>(() => {
+ const swatchStyle = useMemo<React.CSSProperties>(() => {
return {
- ...swatchWrapperBase,
- borderColor:
- isHovered || isFocused
- ? INPUT_BORDER_COLOR_HOVERED
- : INPUT_BORDER_COLOR_UNHOVERED,
- cursor: propStatus.canUpdate ? 'pointer' : 'not-allowed',
marginLeft: 5,
};
- }, [isFocused, isHovered, propStatus.canUpdate]);
-
- const swatchFill = useMemo<React.CSSProperties>(() => {
- return {
- ...swatchFillStyle,
- backgroundColor: currentValue || hexValue,
- position: 'absolute',
- display: 'block',
- };
- }, [currentValue, hexValue]);
-
- const onMouseEnter = useCallback(() => setIsHovered(true), []);
- const onMouseLeave = useCallback(() => setIsHovered(false), []);
- const onFocus = useCallback(() => setIsFocused(true), []);
- const onBlur = useCallback(() => setIsFocused(false), []);
-
- const onSwatchClick = useCallback(() => {
- if (!propStatus.canUpdate) {
- return;
- }
-
- inputRef.current?.click();
- }, [propStatus.canUpdate]);
-
- const showEyeDropper = hasEyeDropper();
+ }, []);
return (
<span style={containerStyle}>
- <span
- style={swatchWrapperStyle}
- onMouseEnter={onMouseEnter}
- onMouseLeave={onMouseLeave}
- onClick={onSwatchClick}
+ <ColorPicker
+ value={currentValue}
+ status="ok"
+ onChange={onChange}
+ onChangeComplete={onChangeComplete}
+ width={SWATCH_WIDTH}
+ height={SWATCH_HEIGHT}
+ disabled={!propStatus.canUpdate}
+ name={field.key}
title={currentValue}
- >
- <span style={swatchFill} />
- <input
- ref={inputRef}
- type="color"
- value={hexValue}
- onChange={onColorChange}
- onFocus={onFocus}
- onBlur={onBlur}
- disabled={!propStatus.canUpdate}
- name={field.key}
- tabIndex={tabIndex}
- style={hiddenInputStyle}
- />
- </span>
- {showEyeDropper ? (
- <button
- type="button"
- onClick={onPickColor}
- disabled={!propStatus.canUpdate}
- style={eyedropperButtonBase}
- tabIndex={tabIndex}
- title="Pick color from screen"
- aria-label="Pick color from screen"
- >
- <EyedropperIcon
- style={eyedropperIconStyle}
- color="rgba(255, 255, 255, 0.7)"
- />
- </button>
- ) : null}
+ style={swatchStyle}
+ />
</span>
);
};
diff --git a/packages/studio/src/helpers/color-conversion.ts b/packages/studio/src/helpers/color-conversion.ts
new file mode 100644
index 0000000000..f8112b82e6
--- /dev/null
+++ b/packages/studio/src/helpers/color-conversion.ts
@@ -0,0 +1,150 @@
+import {NoReactInternals} from 'remotion/no-react';
+
+export type Rgba = {
+ r: number;
+ g: number;
+ b: number;
+ a: number;
+};
+
+export type Hsva = {
+ h: number;
+ s: number;
+ v: number;
+ a: number;
+};
+
+export const clamp = (value: number, min: number, max: number) => {
+ return Math.min(Math.max(value, min), max);
+};
+
+const componentToHex = (c: number) => {
+ return Math.round(clamp(c, 0, 255))
+ .toString(16)
+ .padStart(2, '0');
+};
+
+// Always returns a normalized {r, g, b, a (0-255)} object,
+// regardless of whether the input was a hex, rgb(), rgba(), or named color.
+// Falls back to opaque black when parsing fails.
+export const parseAnyColor = (input: string): Rgba => {
+ try {
+ const argb = NoReactInternals.processColor(input)
+ .toString(16)
+ .padStart(8, '0');
+ const a = parseInt(argb.slice(0, 2), 16);
+ const r = parseInt(argb.slice(2, 4), 16);
+ const g = parseInt(argb.slice(4, 6), 16);
+ const b = parseInt(argb.slice(6, 8), 16);
+ return {r, g, b, a};
+ } catch {
+ return {r: 0, g: 0, b: 0, a: 255};
+ }
+};
+
+export const formatRgba = ({r, g, b, a}: Rgba): string => {
+ if (a >= 255) {
+ return `#${componentToHex(r)}${componentToHex(g)}${componentToHex(b)}`;
+ }
+
+ const opacity = Number((a / 255).toFixed(2));
+ return `rgba(${Math.round(r)}, ${Math.round(g)}, ${Math.round(b)}, ${opacity})`;
+};
+
+export const formatRgbHex = ({r, g, b}: {r: number; g: number; b: number}) => {
+ return `#${componentToHex(r)}${componentToHex(g)}${componentToHex(b)}`;
+};
+
+export const rgbToHsv = ({
+ r,
+ g,
+ b,
+}: {
+ r: number;
+ g: number;
+ b: number;
+}): Hsva => {
+ const rn = r / 255;
+ const gn = g / 255;
+ const bn = b / 255;
+
+ const max = Math.max(rn, gn, bn);
+ const min = Math.min(rn, gn, bn);
+ const delta = max - min;
+
+ let h = 0;
+ if (delta !== 0) {
+ if (max === rn) {
+ h = ((gn - bn) / delta) % 6;
+ } else if (max === gn) {
+ h = (bn - rn) / delta + 2;
+ } else {
+ h = (rn - gn) / delta + 4;
+ }
+
+ h *= 60;
+ if (h < 0) {
+ h += 360;
+ }
+ }
+
+ const s = max === 0 ? 0 : delta / max;
+ const v = max;
+
+ return {h, s, v, a: 1};
+};
+
+export const hsvToRgb = ({
+ h,
+ s,
+ v,
+}: {
+ h: number;
+ s: number;
+ v: number;
+}): {r: number; g: number; b: number} => {
+ const c = v * s;
+ const hh = (h % 360) / 60;
+ const x = c * (1 - Math.abs((hh % 2) - 1));
+
+ let r1 = 0;
+ let g1 = 0;
+ let b1 = 0;
+
+ if (hh >= 0 && hh < 1) {
+ r1 = c;
+ g1 = x;
+ } else if (hh >= 1 && hh < 2) {
+ r1 = x;
+ g1 = c;
+ } else if (hh >= 2 && hh < 3) {
+ g1 = c;
+ b1 = x;
+ } else if (hh >= 3 && hh < 4) {
+ g1 = x;
+ b1 = c;
+ } else if (hh >= 4 && hh < 5) {
+ r1 = x;
+ b1 = c;
+ } else {
+ r1 = c;
+ b1 = x;
+ }
+
+ const m = v - c;
+ return {
+ r: Math.round((r1 + m) * 255),
+ g: Math.round((g1 + m) * 255),
+ b: Math.round((b1 + m) * 255),
+ };
+};
+
+export const rgbaToHsva = (rgba: Rgba): Hsva => {
+ const {h, s, v} = rgbToHsv(rgba);
+ return {h, s, v, a: rgba.a / 255};
+};
+
+export const hsvaToRgba = (hsva: Hsva): Rgba => {
+ const {r, g, b} = hsvToRgb(hsva);
+ return {r, g, b, a: Math.round(hsva.a * 255)};
+};
diff --git a/packages/studio/src/helpers/color-math.ts b/packages/studio/src/helpers/color-math.ts
deleted file mode 100644
index cceee3145f..0000000000
--- a/packages/studio/src/helpers/color-math.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import type {ZodTypesType} from '../components/get-zod-if-possible';
-
-export const colorWithNewOpacity = (
- color: string,
- opacity: number,
- zodTypes: ZodTypesType,
-) => {
- const {r, g, b} = zodTypes.ZodZypesInternals.parseColor(color);
- if (opacity >= 255) {
- return `#${r.toString(16).padStart(2, '0')}${g
- .toString(16)
- .padStart(2, '0')}${b.toString(16).padStart(2, '0')}`;
- }
-
- return `rgba(${r}, ${g}, ${b}, ${(opacity / 255).toFixed(2)})`;
-};
diff --git a/packages/studio/src/helpers/inject-css.ts b/packages/studio/src/helpers/inject-css.ts
index 42603bc4a4..0deb52e789 100644
--- a/packages/studio/src/helpers/inject-css.ts
+++ b/packages/studio/src/helpers/inject-css.ts
@@ -94,13 +94,6 @@ const makeDefaultGlobalCSS = () => {
inset -1px 1px #555;
}
- input[type='color'].__remotion_color_picker::-webkit-color-swatch-wrapper {
- padding: 0;
- }
- input[type='color'].__remotion_color_picker::-webkit-color-swatch {
- border: none;
- }
-
.__remotion_thumb,
.__remotion_thumb::-webkit-slider-thumb {
-webkit-appearance: none;
diff --git a/packages/studio/src/test/color-conversion.test.ts b/packages/studio/src/test/color-conversion.test.ts
new file mode 100644
index 0000000000..e85d30f6dd
--- /dev/null
+++ b/packages/studio/src/test/color-conversion.test.ts
@@ -0,0 +1,53 @@
+import {expect, test} from 'bun:test';
+import {
+ formatRgba,
+ hsvToRgb,
+ parseAnyColor,
+ rgbToHsv,
+} from '../helpers/color-conversion';
+
+test('parseAnyColor accepts hex', () => {
+ expect(parseAnyColor('#ff0000')).toEqual({r: 255, g: 0, b: 0, a: 255});
+});
+
+test('parseAnyColor accepts rgba', () => {
+ expect(parseAnyColor('rgba(255, 255, 255, 0.5)')).toEqual({
+ r: 255,
+ g: 255,
+ b: 255,
+ a: 128,
+ });
+});
+
+test('parseAnyColor accepts named colors', () => {
+ expect(parseAnyColor('red')).toEqual({r: 255, g: 0, b: 0, a: 255});
+});
+
+test('parseAnyColor falls back on garbage', () => {
+ expect(parseAnyColor('not a color')).toEqual({r: 0, g: 0, b: 0, a: 255});
+});
+
+test('formatRgba returns hex when fully opaque', () => {
+ expect(formatRgba({r: 255, g: 0, b: 0, a: 255})).toBe('#ff0000');
+});
+
+test('formatRgba returns rgba when transparent', () => {
+ expect(formatRgba({r: 255, g: 0, b: 0, a: 128})).toBe('rgba(255, 0, 0, 0.5)');
+});
+
+test('rgbToHsv / hsvToRgb roundtrip primaries', () => {
+ const reds = rgbToHsv({r: 255, g: 0, b: 0});
+ expect(Math.round(reds.h)).toBe(0);
+ expect(reds.s).toBe(1);
+ expect(reds.v).toBe(1);
+
+ const back = hsvToRgb({h: reds.h, s: reds.s, v: reds.v});
+ expect(back).toEqual({r: 255, g: 0, b: 0});
+});
+
+test('rgbToHsv / hsvToRgb roundtrip greens', () => {
+ const green = rgbToHsv({r: 0, g: 255, b: 0});
+ expect(Math.round(green.h)).toBe(120);
+ const back = hsvToRgb({h: green.h, s: green.s, v: green.v});
+ expect(back).toEqual({r: 0, g: 255, b: 0});
+});