🎥 Make videos programmatically with React
`remotion`: Add modern CSS color format support to interpolateColors
Jonny Burgerbfdd9442b345
diff --git a/packages/animation-utils/src/transformation-helpers/interpolate-styles/utils.ts b/packages/animation-utils/src/transformation-helpers/interpolate-styles/utils.tsindex 121c52f978..563755b687 100644--- a/packages/animation-utils/src/transformation-helpers/interpolate-styles/utils.ts+++ b/packages/animation-utils/src/transformation-helpers/interpolate-styles/utils.ts@@ -6,6 +6,23 @@ function call(...args: unknown[]): string {return '\\(\\s*(' + args.join(')\\s*,\\s*(') + ')\\s*\\)';}+const MODERN_VALUE = '(?:none|[-+]?\\d*\\.?\\d+(?:%|deg|rad|grad|turn)?)';++function modernColorCall(name: string): RegExp {+ return new RegExp(+ name ++ '\\(\\s*(' ++ MODERN_VALUE ++ ')\\s+(' ++ MODERN_VALUE ++ ')\\s+(' ++ MODERN_VALUE ++ ')(?:\\s*\\/\\s*(' ++ MODERN_VALUE ++ '))?\\s*\\)',+ );+}+function getColorMatchers(): ColorMatchers {const cachedMatchers: ColorMatchers = {rgb: undefined,@@ -17,6 +34,11 @@ function getColorMatchers(): ColorMatchers {hex5: undefined,hex6: undefined,hex8: undefined,+ oklch: undefined,+ oklab: undefined,+ lab: undefined,+ lch: undefined,+ hwb: undefined,};if (cachedMatchers.rgb === undefined) {cachedMatchers.rgb = new RegExp('rgb' + call(NUMBER, NUMBER, NUMBER));@@ -34,6 +56,11 @@ function getColorMatchers(): ColorMatchers {/^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/;cachedMatchers.hex6 = /^#([0-9a-fA-F]{6})$/;cachedMatchers.hex8 = /^#([0-9a-fA-F]{8})$/;+ cachedMatchers.oklch = modernColorCall('oklch');+ cachedMatchers.oklab = modernColorCall('oklab');+ cachedMatchers.lab = modernColorCall('lab');+ cachedMatchers.lch = modernColorCall('lch');+ cachedMatchers.hwb = modernColorCall('hwb');}return cachedMatchers;@@ -124,7 +151,12 @@ const isColorValue = (value: string) => {matchers.hex4?.test(value) ||matchers.hex5?.test(value) ||matchers.hex6?.test(value) ||- matchers.hex8?.test(value)+ matchers.hex8?.test(value) ||+ matchers.oklch?.test(value) ||+ matchers.oklab?.test(value) ||+ matchers.lab?.test(value) ||+ matchers.lch?.test(value) ||+ matchers.hwb?.test(value));};diff --git a/packages/animation-utils/src/type.ts b/packages/animation-utils/src/type.tsindex 30818544dd..d6b84aba08 100644--- a/packages/animation-utils/src/type.ts+++ b/packages/animation-utils/src/type.ts@@ -100,6 +100,11 @@ type ColorMatchers = {hex5: MatcherType;hex6: MatcherType;hex8: MatcherType;+ oklch: MatcherType;+ oklab: MatcherType;+ lab: MatcherType;+ lch: MatcherType;+ hwb: MatcherType;};type Style = React.CSSProperties;diff --git a/packages/core/src/interpolate-colors.ts b/packages/core/src/interpolate-colors.tsindex 095cf843e9..3e2fbb868c 100644--- a/packages/core/src/interpolate-colors.ts+++ b/packages/core/src/interpolate-colors.ts@@ -15,6 +15,24 @@ function call(...args: unknown[]): string {return '\\(\\s*(' + args.join(')\\s*,\\s*(') + ')\\s*\\)';}+// Modern CSS Color Level 4 syntax: space-separated values with optional / alpha+const MODERN_VALUE = '(?:none|[-+]?\\d*\\.?\\d+(?:%|deg|rad|grad|turn)?)';++function modernColorCall(name: string): RegExp {+ return new RegExp(+ name ++ '\\(\\s*(' ++ MODERN_VALUE ++ ')\\s+(' ++ MODERN_VALUE ++ ')\\s+(' ++ MODERN_VALUE ++ ')(?:\\s*\\/\\s*(' ++ MODERN_VALUE ++ '))?\\s*\\)',+ );+}+// matchers use RegExp objects which needs to be created separately on JS and on// the UI thread. We keep separate cache of Regexes for UI and JS using the below// objects, then pick the right cache in getMatchers() method.@@ -28,6 +46,11 @@ type Matchers = {hex5: MatcherType;hex6: MatcherType;hex8: MatcherType;+ oklch: MatcherType;+ oklab: MatcherType;+ lab: MatcherType;+ lch: MatcherType;+ hwb: MatcherType;};function getMatchers(): Matchers {const cachedMatchers: Matchers = {@@ -40,6 +63,11 @@ function getMatchers(): Matchers {hex5: undefined,hex6: undefined,hex8: undefined,+ oklch: undefined,+ oklab: undefined,+ lab: undefined,+ lch: undefined,+ hwb: undefined,};if (cachedMatchers.rgb === undefined) {cachedMatchers.rgb = new RegExp('rgb' + call(NUMBER, NUMBER, NUMBER));@@ -57,6 +85,11 @@ function getMatchers(): Matchers {/^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/;cachedMatchers.hex6 = /^#([0-9a-fA-F]{6})$/;cachedMatchers.hex8 = /^#([0-9a-fA-F]{8})$/;+ cachedMatchers.oklch = modernColorCall('oklch');+ cachedMatchers.oklab = modernColorCall('oklab');+ cachedMatchers.lab = modernColorCall('lab');+ cachedMatchers.lch = modernColorCall('lch');+ cachedMatchers.hwb = modernColorCall('hwb');}return cachedMatchers;@@ -145,6 +178,128 @@ function parsePercentage(str: string): number {return int / 100;}+// Modern CSS Color Level 4 parsing helpers+function parseModernComponent(str: string, percentScale: number): number {+ if (str === 'none') return 0;+ if (str.endsWith('%')) {+ return (Number.parseFloat(str) / 100) * percentScale;+ }++ return Number.parseFloat(str);+}++function parseHueAngle(str: string): number {+ if (str === 'none') return 0;+ if (str.endsWith('rad')) {+ return (Number.parseFloat(str) * 180) / Math.PI;+ }++ if (str.endsWith('grad')) return Number.parseFloat(str) * 0.9;+ if (str.endsWith('turn')) return Number.parseFloat(str) * 360;+ // 'deg' suffix or plain number = degrees+ return Number.parseFloat(str);+}++function parseModernAlpha(str: string | undefined): number {+ if (str === undefined || str === 'none') return 1;+ if (str.endsWith('%')) {+ return Math.max(0, Math.min(1, Number.parseFloat(str) / 100));+ }++ return Math.max(0, Math.min(1, Number.parseFloat(str)));+}++// sRGB gamma correction+function linearToSrgb(c: number): number {+ if (c <= 0.0031308) return 12.92 * c;+ return 1.055 * c ** (1 / 2.4) - 0.055;+}++function clamp01(v: number): number {+ return Math.max(0, Math.min(1, v));+}++function rgbFloatToInt(r: number, g: number, b: number, alpha: number): number {+ const ri = Math.round(clamp01(r) * 255);+ const gi = Math.round(clamp01(g) * 255);+ const bi = Math.round(clamp01(b) * 255);+ const ai = Math.round(clamp01(alpha) * 255);+ return ((ri << 24) | (gi << 16) | (bi << 8) | ai) >>> 0;+}++// OKLab to sRGB conversion+function oklabToSrgb(+ L: number,+ a: number,+ b: number,+): [number, number, number] {+ const l_ = L + 0.3963377774 * a + 0.2158037573 * b;+ const m_ = L - 0.1055613458 * a - 0.0638541728 * b;+ const s_ = L - 0.0894841775 * a - 1.291485548 * b;++ const l = l_ * l_ * l_;+ const m = m_ * m_ * m_;+ const s = s_ * s_ * s_;++ const rLin = 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s;+ const gLin = -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s;+ const bLin = -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s;++ return [linearToSrgb(rLin), linearToSrgb(gLin), linearToSrgb(bLin)];+}++// CIE Lab to sRGB conversion (D65 illuminant)+function labToSrgb(L: number, a: number, b: number): [number, number, number] {+ const epsilon = 216 / 24389;+ const kappa = 24389 / 27;++ // D65 white point+ const Xn = 0.95047;+ const Yn = 1.0;+ const Zn = 1.08883;++ const fy = (L + 16) / 116;+ const fx = a / 500 + fy;+ const fz = fy - b / 200;++ const fx3 = fx * fx * fx;+ const fz3 = fz * fz * fz;++ const xr = fx3 > epsilon ? fx3 : (116 * fx - 16) / kappa;+ const yr = L > kappa * epsilon ? ((L + 16) / 116) ** 3 : L / kappa;+ const zr = fz3 > epsilon ? fz3 : (116 * fz - 16) / kappa;++ const X = xr * Xn;+ const Y = yr * Yn;+ const Z = zr * Zn;++ // XYZ to linear sRGB (D65)+ const rLin = 3.2404542 * X - 1.5371385 * Y - 0.4985314 * Z;+ const gLin = -0.969266 * X + 1.8760108 * Y + 0.041556 * Z;+ const bLin = 0.0556434 * X - 0.2040259 * Y + 1.0572252 * Z;++ return [linearToSrgb(rLin), linearToSrgb(gLin), linearToSrgb(bLin)];+}++// HWB to sRGB conversion+function hwbToSrgb(h: number, w: number, bk: number): [number, number, number] {+ // h is 0-1 (hue as fraction of 360), w and bk are 0-1+ if (w + bk >= 1) {+ const gray = w / (w + bk);+ return [gray, gray, gray];+ }++ // Get pure hue RGB (HSL with S=100%, L=50%)+ const q = 1; // l=0.5, s=1: q = 0.5*(1+1) = 1+ const p = 0; // 2*0.5 - 1 = 0+ const r = hue2rgb(p, q, h + 1 / 3);+ const g = hue2rgb(p, q, h);+ const bl = hue2rgb(p, q, h - 1 / 3);++ const factor = 1 - w - bk;+ return [r * factor + w, g * factor + w, bl * factor + w];+}+export const colorNames: {[key: string]: number} = {transparent: 0x00000000,@@ -414,6 +569,63 @@ function normalizeColor(color: string): number {}}+ if (matchers.oklch) {+ if ((match = matchers.oklch.exec(color))) {+ const L = parseModernComponent(match[1], 1); // 100% = 1+ const C = parseModernComponent(match[2], 0.4); // 100% = 0.4+ const H = parseHueAngle(match[3]);+ const alpha = parseModernAlpha(match[4]);+ const hRad = (H * Math.PI) / 180;+ const [r, g, b] = oklabToSrgb(L, C * Math.cos(hRad), C * Math.sin(hRad));+ return rgbFloatToInt(r, g, b, alpha);+ }+ }++ if (matchers.oklab) {+ if ((match = matchers.oklab.exec(color))) {+ const L = parseModernComponent(match[1], 1);+ const a = parseModernComponent(match[2], 0.4);+ const b = parseModernComponent(match[3], 0.4);+ const alpha = parseModernAlpha(match[4]);+ const [r, g, bl] = oklabToSrgb(L, a, b);+ return rgbFloatToInt(r, g, bl, alpha);+ }+ }++ if (matchers.lab) {+ if ((match = matchers.lab.exec(color))) {+ const L = parseModernComponent(match[1], 100); // 100% = 100+ const a = parseModernComponent(match[2], 125); // 100% = 125+ const b = parseModernComponent(match[3], 125);+ const alpha = parseModernAlpha(match[4]);+ const [r, g, bl] = labToSrgb(L, a, b);+ return rgbFloatToInt(r, g, bl, alpha);+ }+ }++ if (matchers.lch) {+ if ((match = matchers.lch.exec(color))) {+ const L = parseModernComponent(match[1], 100);+ const C = parseModernComponent(match[2], 150); // 100% = 150+ const H = parseHueAngle(match[3]);+ const alpha = parseModernAlpha(match[4]);+ const hRad = (H * Math.PI) / 180;+ const [r, g, bl] = labToSrgb(L, C * Math.cos(hRad), C * Math.sin(hRad));+ return rgbFloatToInt(r, g, bl, alpha);+ }+ }++ if (matchers.hwb) {+ if ((match = matchers.hwb.exec(color))) {+ const H = parseHueAngle(match[1]);+ const W = parseModernComponent(match[2], 1); // 100% = 1+ const B = parseModernComponent(match[3], 1);+ const alpha = parseModernAlpha(match[4]);+ const [r, g, bl] = hwbToSrgb(H / 360, W, B);+ return rgbFloatToInt(r, g, bl, alpha);+ }+ }+throw new Error(`invalid color string ${color} provided`);}diff --git a/packages/core/src/test/interpolateColors.test.ts b/packages/core/src/test/interpolateColors.test.tsindex e6eed9c79d..f21ccf0dc9 100644--- a/packages/core/src/test/interpolateColors.test.ts+++ b/packages/core/src/test/interpolateColors.test.ts@@ -93,3 +93,155 @@ describe('RGB', () => {).toBe('rgba(128, 128, 128, 1)');});});++describe('oklch', () => {+ test('oklch black', () => {+ expect(interpolateColors(1, [0, 1], ['oklch(0 0 0)', 'black'])).toBe(+ 'rgba(0, 0, 0, 1)',+ );+ });++ test('oklch white', () => {+ expect(interpolateColors(1, [0, 1], ['black', 'oklch(1 0 0)'])).toBe(+ 'rgba(255, 255, 255, 1)',+ );+ });++ test('oklch with alpha', () => {+ const result = interpolateColors(+ 1,+ [0, 1],+ ['black', 'oklch(1 0 0 / 0.5)'],+ );+ expect(result).toBe('rgba(255, 255, 255, 0.502)');+ });++ test('oklch with percentage lightness', () => {+ expect(interpolateColors(1, [0, 1], ['black', 'oklch(100% 0 0)'])).toBe(+ 'rgba(255, 255, 255, 1)',+ );+ });++ test('oklch interpolation', () => {+ const result = interpolateColors(+ 0.5,+ [0, 1],+ ['oklch(0 0 0)', 'oklch(1 0 0)'],+ );+ expect(result).toBe('rgba(128, 128, 128, 1)');+ });+});++describe('oklab', () => {+ test('oklab black', () => {+ expect(interpolateColors(1, [0, 1], ['oklab(0 0 0)', 'black'])).toBe(+ 'rgba(0, 0, 0, 1)',+ );+ });++ test('oklab white', () => {+ expect(interpolateColors(1, [0, 1], ['black', 'oklab(1 0 0)'])).toBe(+ 'rgba(255, 255, 255, 1)',+ );+ });++ test('oklab with alpha', () => {+ const result = interpolateColors(+ 1,+ [0, 1],+ ['black', 'oklab(1 0 0 / 0.5)'],+ );+ expect(result).toBe('rgba(255, 255, 255, 0.502)');+ });+});++describe('lab', () => {+ test('lab black', () => {+ expect(interpolateColors(1, [0, 1], ['lab(0 0 0)', 'black'])).toBe(+ 'rgba(0, 0, 0, 1)',+ );+ });++ test('lab white', () => {+ expect(interpolateColors(1, [0, 1], ['black', 'lab(100 0 0)'])).toBe(+ 'rgba(255, 255, 255, 1)',+ );+ });++ test('lab with alpha', () => {+ const result = interpolateColors(+ 1,+ [0, 1],+ ['black', 'lab(100 0 0 / 0.5)'],+ );+ expect(result).toBe('rgba(255, 255, 255, 0.502)');+ });+});++describe('lch', () => {+ test('lch black', () => {+ expect(interpolateColors(1, [0, 1], ['lch(0 0 0)', 'black'])).toBe(+ 'rgba(0, 0, 0, 1)',+ );+ });++ test('lch white', () => {+ expect(interpolateColors(1, [0, 1], ['black', 'lch(100 0 0)'])).toBe(+ 'rgba(255, 255, 255, 1)',+ );+ });++ test('lch with alpha', () => {+ const result = interpolateColors(+ 1,+ [0, 1],+ ['black', 'lch(100 0 0 / 0.5)'],+ );+ expect(result).toBe('rgba(255, 255, 255, 0.502)');+ });+});++describe('hwb', () => {+ test('hwb pure red', () => {+ expect(interpolateColors(1, [0, 1], ['black', 'hwb(0 0% 0%)'])).toBe(+ 'rgba(255, 0, 0, 1)',+ );+ });++ test('hwb white', () => {+ expect(interpolateColors(1, [0, 1], ['black', 'hwb(0 100% 0%)'])).toBe(+ 'rgba(255, 255, 255, 1)',+ );+ });++ test('hwb black', () => {+ expect(interpolateColors(1, [0, 1], ['white', 'hwb(0 0% 100%)'])).toBe(+ 'rgba(0, 0, 0, 1)',+ );+ });++ test('hwb gray', () => {+ expect(interpolateColors(1, [0, 1], ['black', 'hwb(0 50% 50%)'])).toBe(+ 'rgba(128, 128, 128, 1)',+ );+ });++ test('hwb with alpha', () => {+ const result = interpolateColors(+ 1,+ [0, 1],+ ['black', 'hwb(0 0% 0% / 0.5)'],+ );+ expect(result).toBe('rgba(255, 0, 0, 0.502)');+ });++ test('hwb interpolation', () => {+ const result = interpolateColors(+ 0.5,+ [0, 1],+ ['hwb(0 0% 0%)', 'hwb(0 100% 0%)'],+ );+ // Red to white at midpoint+ expect(result).toBe('rgba(255, 128, 128, 1)');+ });+});diff --git a/packages/docs/docs/interpolate-colors.mdx b/packages/docs/docs/interpolate-colors.mdxindex 29c2ae5cc0..332215efcf 100644--- a/packages/docs/docs/interpolate-colors.mdx+++ b/packages/docs/docs/interpolate-colors.mdx@@ -84,6 +84,49 @@ const frame = useCurrentFrame(); // 10const color = interpolateColors(frame, [0, 20], ['red', 'yellow']); // rgba(255, 128, 0, 1)```+## Interpolating `oklch` colors++<AvailableFrom v="4.0.439" />++Support for [`oklch()`](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/oklch) colors using space-separated syntax with optional alpha via `/`:++```ts twoslash+import {useCurrentFrame, interpolateColors} from 'remotion';++const frame = useCurrentFrame(); // 10++const color = interpolateColors(frame, [0, 20], ['oklch(0.5 0.2 240)', 'oklch(0.9 0.1 120)']);++// With alpha+const color2 = interpolateColors(frame, [0, 20], ['oklch(0.5 0.2 240 / 1)', 'oklch(0.9 0.1 120 / 0.5)']);+```++## Interpolating `oklab`, `lab`, `lch`, and `hwb` colors++<AvailableFrom v="4.0.439" />++The following CSS Color Level 4 formats are also supported:++```ts twoslash+import {useCurrentFrame, interpolateColors} from 'remotion';++const frame = useCurrentFrame(); // 10++// oklab+const a = interpolateColors(frame, [0, 20], ['oklab(0.5 -0.1 0.1)', 'oklab(0.9 0 0)']);++// lab+const b = interpolateColors(frame, [0, 20], ['lab(50 -20 40)', 'lab(90 0 0)']);++// lch+const c = interpolateColors(frame, [0, 20], ['lch(50 60 240)', 'lch(90 30 120)']);++// hwb+const d = interpolateColors(frame, [0, 20], ['hwb(0 0% 0%)', 'hwb(120 10% 10%)']);+```++All modern color functions support the optional `/ alpha` syntax (e.g., `oklch(0.7 0.15 180 / 0.5)`).+## Compatibility<CompatibilityTable chrome firefox safari nodejs bun serverlessFunctions clientSideRendering serverSideRendering player studio />