Skip to content

feat: Linear gradient support in CSS animations #7929

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,22 @@
*/

import React from 'react';
import { Text, View } from 'react-native';
import { View } from 'react-native';
import { createAnimatedComponent, css } from 'react-native-reanimated';

import { Screen } from '@/apps/css/components';
import { flex } from '@/theme';

const AnimatedView = createAnimatedComponent(View);

export default function Playground() {
return (
<Screen style={flex.center}>
<Text>Hello world!</Text>
<AnimatedView style={styles.parent}>
<View style={styles.row}>
<View style={[flex.grow, { backgroundColor: 'blue' }]} />
<View style={[flex.grow, { backgroundColor: 'lightblue' }]} />
<View style={[flex.grow, { backgroundColor: 'skyblue' }]} />
<View style={[flex.grow, { backgroundColor: 'powderblue' }]} />
</View>

<AnimatedView style={styles.child} />
</AnimatedView>
</Screen>
<View
style={[
{
flex: 1,
experimental_backgroundImage:
'linear-gradient(20rad, red,orange,yellow,green,blue,indigo,violet)',
},
]}
/>
);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { parseCssFunction } from '../backgroundImage';

describe(parseCssFunction, () => {
it('should parse linear-gradient', () => {
expect(
parseCssFunction('linear-gradient(to right, red, orange, yellow)')
).toEqual({
name: 'linear-gradient',
params: ['to right', 'red', 'orange', 'yellow'],
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import type { ValueProcessor } from '../types';
import {
type LinearGradientBackgroundImage,
processLinearGradient,
} from './gradients';

export const ERROR_MESSAGES = {
invalidBackgroundImage: (value: string) =>
`Invalid background image: ${value}`,
};

export function parseCssFunction(
value: string
): { name: string; params: string[] } | null {
const match = value.match(/^([a-zA-Z0-9-]+)\((.*)\)$/);
if (!match) return null;

const [, name, paramStr] = match;

const paramRegex = /(?:[^,(]+|\([^)]*\))+/g;
const params = Array.from(paramStr.matchAll(paramRegex), (m) => m[0].trim());

return { name, params };
}

export const processBackgroundImage: ValueProcessor<
string | LinearGradientBackgroundImage
> = (value) => {
if (typeof value === 'object') {
return value;
}

const parsed = parseCssFunction(value);
if (!parsed) {
throw new ReanimatedError(ERROR_MESSAGES.invalidBackgroundImage(value));
}

const { name, params } = parsed;

switch (name) {
case 'linear-gradient':
return processLinearGradient(params);
default:
throw new ReanimatedError(ERROR_MESSAGES.invalidBackgroundImage(value));
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './linear';
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import type { ValueProcessor } from '../../types';
import { processColor } from '../colors';

type ColorStop = {
color: number | string;
position: number | string | null;
};

export type LinearGradientBackgroundImage = {
type: 'linear-gradient';
direction: { type: 'angle'; value: number };
colorStops: ColorStop[];
};

const parseAngle = (angle: string): number | null => {
// Unit conversion factors (to radians)
const unitFactors: Record<string, number> = {
rad: 1,
deg: Math.PI / 180,
};

// Find position of the first non-numeric character (first character of the unit)
const pos = angle.search(/[^0-9.+-]/);

if (pos === -1) {
return null;
}

const numericPart = angle.substring(0, pos);
const unitPart = angle.substring(pos);

// Validate numeric part
if (!/^[-+]?\d*\.?\d+$/.test(numericPart)) {
return null;
}

// Lookup the unit and convert to radians
const factor = unitFactors[unitPart];
if (factor === undefined) {
return null;
}

const numericValue = parseFloat(numericPart);
return numericValue * factor;
};

const parseDirection = (direction: string): number | null => {
if (direction.startsWith('to ')) {
switch (direction.split(/\s+/)[1]) {
case 'top':
return 0;
case 'bottom':
return 180;
case 'left':
return 270;
case 'right':
return 90;
default:
return null;
}
}

return parseAngle(direction);
};

export const processLinearGradient: ValueProcessor<
string[],
LinearGradientBackgroundImage
> = (params) => {
if (!params.length) {
return undefined;
}

const direction = parseDirection(params[0]);
const stops: ColorStop[] = [];

for (let i = 1; i < params.length; i++) {
const param = params[i];
const color = processColor(param);
const position = parsePosition(param);
stops.push({ color, position });
}

// TODO: Parse color stops from remaining params
const colorStops: LinearGradientBackgroundImage['colorStops'] = [];

return {
type: 'linear-gradient',
direction: { type: 'angle', value: direction ?? 0 },
colorStops,
};
};
Loading