diff --git a/src/__tests__/compiler/compiler.test.tsx b/src/__tests__/compiler/compiler.test.tsx index 20743e03..01854195 100644 --- a/src/__tests__/compiler/compiler.test.tsx +++ b/src/__tests__/compiler/compiler.test.tsx @@ -181,23 +181,47 @@ test("animations preserve named keyframes and their timing contract", () => { ]); }); -test("breaks apart comma separated variables", () => { - const compiled = compile( - ` - :root { - --test: blue, green; - } - `, - { - inlineVariables: false, - }, - ); +// css-variables-1 §2.1: a custom property's value is its tokens, its commas among them +test.each([ + ["blue, green", [["blue"], ["green"]]], + ["blue ,green", [["blue"], ["green"]]], + ["blue/**/, green", [["blue"], ["green"]]], + ["blue green", ["blue", "green"]], + [ + "1px 2px #000, 3px 4px #fff", + [ + [1, 2, "#000"], + [3, 4, "#fff"], + ], + ], + ["1px 2px #000 3px 4px #fff", [1, 2, "#000", 3, 4, "#fff"]], +])("--test: %s keeps its separator", (value, expected) => { + const compiled = compile(`:root { --test: ${value}; }`, { + inlineVariables: false, + }); expect(compiled.stylesheet()).toStrictEqual({ - vr: [["test", [[["blue", "green"]]]]], + vr: [["test", [[expected]]]], }); }); +test.each([ + ["var(--a), var(--b)", [[[{}, "var", "a", 1]], [[{}, "var", "b", 1]]]], + [ + "var(--a) var(--b)", + [ + [{}, "var", "a", 1], + [{}, "var", "b", 1], + ], + ], +])("box-shadow: %s keeps its separator", (value, expected) => { + const compiled = compile(`.my-class { box-shadow: ${value}; }`); + + expect(compiled.stylesheet().s?.[0]?.[1][0]?.d).toStrictEqual([ + [[{}, "boxShadow", expected, 1], "boxShadow", 1], + ]); +}); + test("light-dark()", () => { const compiled = compile(` .my-class { diff --git a/src/__tests__/compiler/property.test.ts b/src/__tests__/compiler/property.test.ts index f6f0e37f..20ae04db 100644 --- a/src/__tests__/compiler/property.test.ts +++ b/src/__tests__/compiler/property.test.ts @@ -591,3 +591,17 @@ test("an @property under an @supports that fails is not registered", () => { expect(result.vp).toBeUndefined(); }); + +test("@property with a comma-separated repeated value keeps each item apart", () => { + const compiled = compile(` +@property --my-offsets { + syntax: "#"; + inherits: false; + initial-value: 10px, 20px; +} +`); + + expect(compiled.stylesheet().vp).toStrictEqual([ + ["my-offsets", false, [[10], [20]]], + ]); +}); diff --git a/src/__tests__/native/variable-lists.test.tsx b/src/__tests__/native/variable-lists.test.tsx new file mode 100644 index 00000000..3088e33c --- /dev/null +++ b/src/__tests__/native/variable-lists.test.tsx @@ -0,0 +1,408 @@ +import { processColor, StyleSheet } from "react-native"; + +import { render, screen } from "@testing-library/react-native"; +import type { StyleDescriptor } from "react-native-css/compiler"; +import { Text } from "react-native-css/components/Text"; +import { View } from "react-native-css/components/View"; +import { registerCSS, testID } from "react-native-css/jest"; +import { useNativeVariable } from "react-native-css/native"; + +import type { Getter } from "../../native/reactivity"; +import { resolveValue } from "../../native/styles/resolve"; + +// Observe the transition contract before Reanimated consumes it, as transitions.test.tsx does +jest.mock("../../native/reanimated", () => ({ + animatedComponentFamily: (component: unknown) => component, +})); + +const style = () => + StyleSheet.flatten(screen.getByTestId(testID).props.style) as + | Record + | undefined; + +// The compiler folds a variable declared once into the declaration that reads it, unless told to keep it +describe.each([ + ["folded", {}], + ["kept", { inlineVariables: false }], +] as const)( + "a list read through a variable the compiler has %s", + (_, options) => { + // css-variables-1 §3 substitutes a var() by its tokens, commas among them + test.each([ + [ + "box-shadow: var(--o) var(--b)", + "--o: 1px 2px; --b: 3px 4px #123;", + { + boxShadow: [ + { + offsetX: 1, + offsetY: 2, + blurRadius: 3, + spreadDistance: 4, + color: "#123", + }, + ], + }, + ], + [ + "box-shadow: var(--o), var(--b)", + "--o: 1px 2px 0 0 #123; --b: 3px 4px 0 0 #456;", + { + boxShadow: [ + { + offsetX: 1, + offsetY: 2, + blurRadius: 0, + spreadDistance: 0, + color: "#123", + }, + { + offsetX: 3, + offsetY: 4, + blurRadius: 0, + spreadDistance: 0, + color: "#456", + }, + ], + }, + ], + [ + "box-shadow: var(--a)", + "--b: 1px 2px; --a: var(--b) 3px 4px #123;", + { + boxShadow: [ + { + offsetX: 1, + offsetY: 2, + blurRadius: 3, + spreadDistance: 4, + color: "#123", + }, + ], + }, + ], + [ + "filter: var(--f)", + "--f: blur(2px) brightness(1.5);", + { filter: [{ blur: 2 }, { brightness: 1.5 }] }, + ], + [ + "transform: var(--t)", + "--t: rotate(45deg) translateX(10px);", + { transform: [{ rotate: "45deg" }, { translateX: 10 }] }, + ], + [ + "filter: var(--a) var(--b)", + "--a: blur(2px); --b: brightness(1.5);", + { filter: [{ blur: 2 }, { brightness: 1.5 }] }, + ], + [ + "box-shadow: var(--s), var(--s)", + "--s: 1px 1px 0 0 #123, 2px 2px 0 0 #456;", + { + boxShadow: [ + { + offsetX: 1, + offsetY: 1, + blurRadius: 0, + spreadDistance: 0, + color: "#123", + }, + { + offsetX: 2, + offsetY: 2, + blurRadius: 0, + spreadDistance: 0, + color: "#456", + }, + { + offsetX: 1, + offsetY: 1, + blurRadius: 0, + spreadDistance: 0, + color: "#123", + }, + { + offsetX: 2, + offsetY: 2, + blurRadius: 0, + spreadDistance: 0, + color: "#456", + }, + ], + }, + ], + [ + "box-shadow: var(--s) #456", + "--s: 1px 1px 0 0 #123, 2px 2px 0 0;", + { + boxShadow: [ + { + offsetX: 1, + offsetY: 1, + blurRadius: 0, + spreadDistance: 0, + color: "#123", + }, + { + offsetX: 2, + offsetY: 2, + blurRadius: 0, + spreadDistance: 0, + color: "#456", + }, + ], + }, + ], + [ + "transform: translate(var(--x), 20px)", + "--x: 10px;", + { transform: [{ translateX: 10 }, { translateY: 20 }] }, + ], + [ + "transform: scale(var(--s), 2)", + "--s: 3;", + { transform: [{ scaleX: 3 }, { scaleY: 2 }] }, + ], + [ + "transition-property: var(--p), height", + "--p: width;", + { transitionProperty: ["width", "height"] }, + ], + ])("%s over %s", (declaration, variables, expected) => { + registerCSS(`.a { ${variables} ${declaration}; }`, options); + render(); + expect(style()).toStrictEqual(expected); + }); + + // Reanimated's easing builders return instances of their own classes, so the held value is compared with the written one + test.each(["steps(4, end)", "cubic-bezier(0.25, 0.5, 0.75, 1)"])( + "transition-timing-function: var(--e) over --e: %s", + (easing) => { + registerCSS(`.a { transition-timing-function: ${easing}; }`, options); + render(); + const written = style(); + screen.unmount(); + registerCSS( + `.a { --e: ${easing}; transition-timing-function: var(--e); }`, + options, + ); + render(); + expect(style()).toEqual(written); + }, + ); + + // react-native-css maps translateZ() to nothing, so the list keeps the functions it maps + test("transform: var(--t) over --t: translateZ(10px) rotate(45deg)", () => { + registerCSS( + `.a { --t: translateZ(10px) rotate(45deg); transform: var(--t); }`, + options, + ); + render(); + expect(style()).toStrictEqual({ transform: [{ rotate: "45deg" }] }); + }); + + test("background-image: linear-gradient(to right, var(--c)) over --c: #123, #456", () => { + registerCSS( + `.a { --c: #123, #456; background-image: linear-gradient(to right, var(--c)); }`, + options, + ); + render(); + expect(style()).toStrictEqual({ + experimental_backgroundImage: "linear-gradient(to right, #123, #456)", + }); + }); + + test("background-color: rgb(var(--c) / 0.5) over --c: 255 0 0", () => { + registerCSS( + `.a { --c: 255 0 0; background-color: rgb(var(--c) / 0.5); }`, + options, + ); + render(); + expect(processColor(style()?.backgroundColor as string)).toBe( + processColor("rgba(255, 0, 0, 0.5)"), + ); + }); + + test("text-shadow: var(--o) var(--c) over --o: 1px 2px, --c: #123", () => { + registerCSS( + `.a { --o: 1px 2px; --c: #123; text-shadow: var(--o) var(--c); }`, + options, + ); + render(); + expect(style()).toStrictEqual({ + textShadowOffset: { width: 1, height: 2 }, + textShadowRadius: 0, + textShadowColor: "#123", + }); + }); + }, +); + +// A list the property's grammar refuses makes the declaration invalid at computed-value time (css-variables-1 §3.1), so it unsets what an earlier rule set +test.each([ + [ + "box-shadow: var(--o) var(--b)", + "--o: 1px 2px 0 0 #123; --b: 3px 4px 0 0 #456;", + "box-shadow: 5px 5px green;", + { boxShadow: [] }, + ], +])( + "%s over %s replaces an earlier rule's value with none", + (declaration, variables, earlier, expected) => { + registerCSS(`.earlier { ${earlier} } .a { ${variables} ${declaration}; }`, { + inlineVariables: false, + }); + render(); + expect(style()).toStrictEqual(expected); + }, +); + +test("linear-gradient(var(--c)) over --c: #123 #456 prints the space it was written with", () => { + registerCSS( + `.a { --c: #123 #456; background-image: linear-gradient(var(--c)); }`, + { inlineVariables: false }, + ); + render(); + expect(style()).toStrictEqual({ + experimental_backgroundImage: "linear-gradient(#123 #456)", + }); +}); + +test.each([ + [ + "box-shadow: var(--missing, 1px 2px) 3px 4px #123", + [ + { + offsetX: 1, + offsetY: 2, + blurRadius: 3, + spreadDistance: 4, + color: "#123", + }, + ], + ], + [ + "box-shadow: var(--missing, 1px 1px 0 0 #123, 2px 2px 0 0 #456)", + [ + { + offsetX: 1, + offsetY: 1, + blurRadius: 0, + spreadDistance: 0, + color: "#123", + }, + { + offsetX: 2, + offsetY: 2, + blurRadius: 0, + spreadDistance: 0, + color: "#456", + }, + ], + ], +])( + "%s substitutes its fallback's list as a variable's", + (declaration, boxShadow) => { + registerCSS(`.a { ${declaration}; }`); + render(); + expect(style()).toStrictEqual({ boxShadow }); + }, +); + +// The compiler folds a variable read in an unresolved colour's alpha away and drops the alpha, so this case keeps it +test("background-color: rgb(255 0 0 / var(--a)) over --a: 0.5 with the variable kept", () => { + registerCSS(`.a { --a: 0.5; background-color: rgb(255 0 0 / var(--a)); }`, { + inlineVariables: false, + }); + render(); + expect(processColor(style()?.backgroundColor as string)).toBe( + processColor("rgba(255, 0, 0, 0.5)"), + ); +}); + +// React Native's list props and the variable hook's callers take a list of one-token items as a flat array +test("transition-property: var(--p) over --p: width, opacity hands React Native a flat list", () => { + registerCSS(`.a { --p: width, opacity; transition-property: var(--p); }`, { + inlineVariables: false, + }); + render(); + expect(style()).toStrictEqual({ transitionProperty: ["width", "opacity"] }); +}); + +test("useNativeVariable reads --p: width, opacity as a flat list", () => { + registerCSS(`:root { --p: width, opacity; }`, { inlineVariables: false }); + function Sample() { + return ( + {JSON.stringify(useNativeVariable("--p"))} + ); + } + render(); + expect(screen.getByTestId(testID).props.children).toBe( + JSON.stringify(["width", "opacity"]), + ); +}); + +// A variable read twice in one element resolves the second time from the value the first read keeps +test.each<[string, readonly unknown[]]>([ + ["a space-separated list of tokens", [1, 2, "#123"]], + [ + "a space-separated list of objects", + [{ rotate: "45deg" }, { translateX: 10 }], + ], + [ + "a comma-separated list", + [ + [1, 1, 0, 0, "#123"], + [2, 2, 0, 0, "#456"], + ], + ], + [ + "a comma-separated list whose items start with an object and a string", + [ + [{ rotate: "45deg" }, "x"], + [{ rotate: "90deg" }, "y"], + ], + ], +])("%s resolves to itself once resolved", (_, list) => { + const get = (() => undefined) as unknown as Getter; + expect(resolveValue(list as StyleDescriptor, get, {})).toStrictEqual(list); +}); + +test.each<[string, readonly unknown[], readonly unknown[]]>([ + [ + "a list whose tokens all resolve to nothing", + [ + [{}, "var", "a", 1], + [{}, "var", "b", 1], + ], + [], + ], + [ + "a token list nested in a space-separated list", + [1, [2, 3], 4], + [1, 2, 3, 4], + ], + [ + "a comma-separated list with a lone token in an item's place, as React Native's list props take it", + [[1, 2, "#123"], "#456"], + [[1, 2, "#123"], ["#456"]], + ], +])("%s resolves as the list it stands for", (_, list, expected) => { + const get = (() => undefined) as unknown as Getter; + expect(resolveValue(list as StyleDescriptor, get, {})).toStrictEqual( + expected, + ); +}); + +test.each<[string, StyleDescriptor, unknown]>([ + [ + "rotate() over three comma-separated arguments", + [{}, "rotate", [["10deg"], ["20deg"], ["30deg"]]], + [{ rotateX: "10deg" }, { rotateY: "20deg" }, { rotateZ: "30deg" }], + ], + ["join() over one value", [{}, "join", "#123"], "#123"], +])("%s reads each argument", (_, descriptor, expected) => { + const get = (() => undefined) as unknown as Getter; + expect(resolveValue(descriptor, get, {})).toStrictEqual(expected); +}); diff --git a/src/compiler/compiler.ts b/src/compiler/compiler.ts index 4feefe92..d410171f 100644 --- a/src/compiler/compiler.ts +++ b/src/compiler/compiler.ts @@ -588,7 +588,13 @@ function parsePropertyInitialValue( // Unwrap single-child repeated values so downstream consumers get a // scalar instead of a 1-element array. For example, `+` with // initial-value `10px` should produce the same shape as ``. - return results.length === 1 ? results[0] : results; + if (results.length === 1) { + return results[0]; + } + + return component.value.multiplier.type === "comma" + ? results.map((result) => [result]) + : results; } default: return undefined; diff --git a/src/compiler/declarations.ts b/src/compiler/declarations.ts index 2f0b8a4a..52be116b 100644 --- a/src/compiler/declarations.ts +++ b/src/compiler/declarations.ts @@ -1106,8 +1106,9 @@ export function reduceParseUnparsed( } } - // Groups are the tokens grouped together by comma location - // If a group only has 1 item, it shouldn't be an array + // Groups are the tokens grouped together by comma location. Each stays an + // array, so a one-token item of a comma-separated list stays distinct from + // a token of a space-separated one (css-variables-1 §2.1) groups = groups.flatMap((group): StyleDescriptor[] => { if (!Array.isArray(group)) { return []; @@ -1121,7 +1122,7 @@ export function reduceParseUnparsed( if (first === undefined) { return []; } else { - return [first]; + return [[first]]; } } else if ( // This is a special case for values @@ -1133,13 +1134,19 @@ export function reduceParseUnparsed( ) ) { // eslint-disable-next-line @typescript-eslint/no-base-to-string - return [group.join(" ")]; + return [[group.join(" ")]]; } else { return [group]; } }); - return groups.length === 1 ? groups[0] : groups; + if (groups.length !== 1) { + return groups; + } + + // A lone group is the value, and a lone token the group + const group = groups[0] as StyleDescriptor[]; + return group.length === 1 ? group[0] : group; } export function unparsedFunction( @@ -2936,10 +2943,10 @@ export function parseUnresolvedColor( {}, "rgba", [ - round(color.r * 255), - round(color.g * 255), - round(color.b * 255), - parseUnparsed(color.alpha, builder, property), + [round(color.r * 255)], + [round(color.g * 255)], + [round(color.b * 255)], + [parseUnparsed(color.alpha, builder, property)], ], ]; case "hsl": @@ -2947,10 +2954,10 @@ export function parseUnresolvedColor( {}, color.type, [ - color.h, - color.s, - color.l, - parseUnparsed(color.alpha, builder, property), + [color.h], + [color.s], + [color.l], + [parseUnparsed(color.alpha, builder, property)], ], ]; case "light-dark": { @@ -3220,8 +3227,8 @@ function parseGradient( {}, "linear-gradient", [ - parseLineDirection(gradient.direction, builder), - ...gradient.items.map((item) => parseGradientItem(item, builder)), + [parseLineDirection(gradient.direction, builder)], + ...gradient.items.map((item) => [parseGradientItem(item, builder)]), ], ]; } diff --git a/src/compiler/stylesheet.ts b/src/compiler/stylesheet.ts index aaa5e0d5..97427904 100644 --- a/src/compiler/stylesheet.ts +++ b/src/compiler/stylesheet.ts @@ -430,7 +430,7 @@ export class StylesheetBuilder { } else { declarations.push([value, propPath]); } - } else if (Array.isArray(value) && value.some(isStyleFunction)) { + } else if (Array.isArray(value) && value.some(holdsStyleFunction)) { declarations.push([value, propPath]); } else if (typeof value === "string" && keywords.has(value)) { declarations.push([value, propPath]); @@ -636,6 +636,14 @@ function isStyleFunction( ); } +/** A comma-separated list holds each item as the array of its tokens, so a function may be one of an item's tokens. */ +function holdsStyleFunction(entry: StyleDescriptor): boolean { + return ( + isStyleFunction(entry) || + (Array.isArray(entry) && entry.some(isStyleFunction)) + ); +} + function postProcessStyleFunction(value: StyleDescriptor): [ // Should it be delayed boolean, diff --git a/src/native/api.tsx b/src/native/api.tsx index a83d997c..c6c5effb 100644 --- a/src/native/api.tsx +++ b/src/native/api.tsx @@ -4,6 +4,7 @@ import { Appearance, type ViewStyle } from "react-native"; import type { StyleDescriptor } from "react-native-css/compiler"; import { VariableContext } from "react-native-css/native-internal"; +import { commaListItems } from "react-native-css/utilities"; import type { ColorScheme, @@ -115,7 +116,9 @@ export function useNativeVariable(name: string) { return () => cleanupEffect(effect); }, [effect]); cleanupEffect(effect); - return resolveValue([{}, "var", [name]], effect.get, { inheritedVariables }); + return commaListItems( + resolveValue([{}, "var", [name]], effect.get, { inheritedVariables }), + ); } /** diff --git a/src/native/objects.ts b/src/native/objects.ts index 12e69ccd..433bf774 100644 --- a/src/native/objects.ts +++ b/src/native/objects.ts @@ -1,4 +1,6 @@ /* eslint-disable */ +import { commaListItems } from "react-native-css/utilities"; + import { ShortHandSymbol } from "../native/styles/constants"; import { transformKeys } from "../native/styles/defaults"; @@ -78,10 +80,19 @@ export function applyValue( target.transform.push(value); } return; - } else if (typeof value === "object" && value && ShortHandSymbol in value) { - delete value[ShortHandSymbol]; - Object.assign(target, value); - return; + } else if (typeof value === "object" && value) { + if (ShortHandSymbol in value) { + delete value[ShortHandSymbol]; + Object.assign(target, value); + return; + } + + // React Native's list props take a comma-separated list with one-token + // items bare. Tested only here, for objects, so a string or number pays + // nothing for it: applyValue runs for every dynamic declaration. + if (Array.isArray(value[0])) { + value = commaListItems(value); + } } target[prop] = value; diff --git a/src/native/styles/functions/animation-timing.ts b/src/native/styles/functions/animation-timing.ts index 2bd58078..1e942ca6 100644 --- a/src/native/styles/functions/animation-timing.ts +++ b/src/native/styles/functions/animation-timing.ts @@ -1,3 +1,5 @@ +import { commaListItems } from "react-native-css/utilities"; + import type { StyleFunctionResolver } from "../resolve"; /* eslint-disable @typescript-eslint/no-require-imports */ @@ -26,7 +28,7 @@ const timingFunctionResolver: StyleFunctionResolver = (resolveValue, value) => { return; } - const args = resolveValue(value[2]); + const args = commaListItems(resolveValue(value[2])); if (!Array.isArray(args)) { return; diff --git a/src/native/styles/functions/filters.ts b/src/native/styles/functions/filters.ts index 4a88a98a..75198dc6 100644 --- a/src/native/styles/functions/filters.ts +++ b/src/native/styles/functions/filters.ts @@ -102,7 +102,8 @@ export const dropShadow: StyleFunctionResolver = ( export const filter: StyleFunctionResolver = (resolveValue, descriptor) => { const value: unknown = resolveValue(descriptor[2]); if (Array.isArray(value)) { - const filters: unknown[] = value.flat(Infinity); + // resolveValue splices a var() in, so only a comma-separated list nests + const filters: unknown[] = Array.isArray(value[0]) ? value.flat() : value; return filters.filter( (entry) => entry !== undefined && entry !== "initial", ); diff --git a/src/native/styles/functions/platform-functions.ts b/src/native/styles/functions/platform-functions.ts index 57f095f5..2fe21849 100644 --- a/src/native/styles/functions/platform-functions.ts +++ b/src/native/styles/functions/platform-functions.ts @@ -1,9 +1,11 @@ import { PixelRatio, PlatformColor, StyleSheet } from "react-native"; +import { commaListItems } from "react-native-css/utilities"; + import type { StyleFunctionResolver } from "../resolve"; export const platformColor: StyleFunctionResolver = (resolveValue, value) => { - const color: unknown = resolveValue(value[2]); + const color: unknown = commaListItems(resolveValue(value[2])); if (Array.isArray(color)) { return PlatformColor(...(color as string[])); } else if (typeof color === "string") { diff --git a/src/native/styles/functions/string-functions.ts b/src/native/styles/functions/string-functions.ts index 8ab29a98..700a6dce 100644 --- a/src/native/styles/functions/string-functions.ts +++ b/src/native/styles/functions/string-functions.ts @@ -1,3 +1,5 @@ +import { isStyleDescriptorArray } from "react-native-css/utilities"; + import type { StyleFunctionResolver } from "../resolve"; export const gradientPosition: StyleFunctionResolver = ( @@ -19,14 +21,14 @@ export const colorStop: StyleFunctionResolver = (resolveValue, value) => { }; export const join: StyleFunctionResolver = (resolveValue, value) => { - const args = resolveValue(value[2]); + const args = value[2]; - if (!Array.isArray(args)) { - return args; + if (!isStyleDescriptorArray(args)) { + return resolveValue(args); } - const array: unknown = args[0]; - const separator: unknown = args[1] ?? ","; + const array: unknown = resolveValue(args[0]); + const separator: unknown = resolveValue(args[1]) ?? ","; if (!Array.isArray(array)) { return array; diff --git a/src/native/styles/functions/transform-functions.ts b/src/native/styles/functions/transform-functions.ts index 9a38d15e..851f469f 100644 --- a/src/native/styles/functions/transform-functions.ts +++ b/src/native/styles/functions/transform-functions.ts @@ -1,6 +1,7 @@ +import type { StyleDescriptor } from "react-native-css/compiler"; import { isStyleDescriptorArray } from "react-native-css/utilities"; -import type { StyleFunctionResolver } from "../resolve"; +import type { SimpleResolveValue, StyleFunctionResolver } from "../resolve"; import { scaleFactor } from "../scale-factor"; export const scale: StyleFunctionResolver = (resolveValue, descriptor) => { @@ -10,8 +11,8 @@ export const scale: StyleFunctionResolver = (resolveValue, descriptor) => { return { scale: scaleFactor(resolveValue(args)) }; } - const x = scaleFactor(resolveValue(args[0])); - const y = scaleFactor(resolveValue(args[1])); + const x = scaleFactor(argument(resolveValue, args[0])); + const y = scaleFactor(argument(resolveValue, args[1])); const isXValid = typeof x === "string" || typeof x === "number"; const isYValid = typeof y === "string" || typeof y === "number"; @@ -34,9 +35,9 @@ export const rotate: StyleFunctionResolver = (resolveValue, descriptor) => { return { rotate: resolveValue(args) }; } - const x = resolveValue(args[0]); - const y = resolveValue(args[1]); - const z = resolveValue(args[2]); + const x = argument(resolveValue, args[0]); + const y = argument(resolveValue, args[1]); + const z = argument(resolveValue, args[2]); const isXValid = typeof x === "string" || typeof x === "number"; const isYValid = typeof y === "string" || typeof y === "number"; @@ -68,8 +69,8 @@ export const translate: StyleFunctionResolver = (resolveValue, descriptor) => { return; } - const x = resolveValue(args[0]); - const y = resolveValue(args[1]); + const x = argument(resolveValue, args[0]); + const y = argument(resolveValue, args[1]); const isXValid = typeof x === "string" || typeof x === "number"; const isYValid = typeof y === "string" || typeof y === "number"; @@ -84,3 +85,16 @@ export const translate: StyleFunctionResolver = (resolveValue, descriptor) => { return; }; + +/** A comma-separated argument list holds each argument as the array of its tokens */ +function argument(resolveValue: SimpleResolveValue, arg: StyleDescriptor) { + // A descriptor, never a resolved value: a style function starts with its {} + // marker, so an array of one entry that isn't a plain object is an item. + // This skips isStyleFunction's Object.keys, which resolveValue runs anyway + const token = Array.isArray(arg) && arg.length === 1 ? arg[0] : undefined; + return resolveValue( + token !== undefined && (typeof token !== "object" || Array.isArray(token)) + ? token + : arg, + ); +} diff --git a/src/native/styles/resolve.ts b/src/native/styles/resolve.ts index 0cb40385..e68f779a 100644 --- a/src/native/styles/resolve.ts +++ b/src/native/styles/resolve.ts @@ -5,7 +5,11 @@ import type { StyleDescriptor, StyleFunction, } from "react-native-css/compiler"; -import { isStyleDescriptorArray } from "react-native-css/utilities"; +import { + isCommaList, + isStyleDescriptorArray, + isStyleFunction, +} from "react-native-css/utilities"; import type { RenderGuard } from "../conditions/guards"; import { type Getter, type VariableContextValue } from "../reactivity"; @@ -62,6 +66,8 @@ export function resolveValue( value: StyleDescriptor, get: Getter, options: ResolveValueOptions, + /** The caller has already found value to be a style function */ + isFunction?: boolean, ): any { const { castToArray } = options; @@ -90,26 +96,18 @@ export function resolveValue( return value; } - if (isStyleDescriptorArray(value)) { - value = value - .map((d) => resolveValue(d, get, options)) - .filter((d) => d !== undefined); - - if (castToArray && !Array.isArray(value)) { - return [value]; - } else { - return value; - } + if (!isFunction && isStyleDescriptorArray(value)) { + return resolveList(value, get, options); } - const name = value[1]; + const name = (value as StyleFunction)[1]; const simpleResolve: SimpleResolveValue = (value) => { return resolveValue(value, get, options); }; if (name === "var") { - return varResolver(simpleResolve, value, get, options); + return varResolver(simpleResolve, value as StyleFunction, get, options); } else if (name in functionResolvers) { const fn = functionResolvers[name as keyof typeof functionResolvers]; @@ -141,15 +139,9 @@ export function resolveValue( if (args === undefined) { return; } else if (Array.isArray(args)) { - let joinedArgs = args - .map((arg: unknown) => { - if (Array.isArray(arg)) { - return arg.flat().join(" "); - } - return arg; - }) - .filter((value) => value !== "/") - .join(", "); + let joinedArgs = isCommaList(args) + ? args.map((item: readonly unknown[]) => item.join(" ")).join(", ") + : args.join(" "); if (name === "radial-gradient") { // Nativewind / Tailwind CSS hack which can force the 'in oklab' color space @@ -166,3 +158,166 @@ export function resolveValue( } } } + +/** + * Resolves a list descriptor. A comma-separated list holds each item as the + * array of its tokens; anything else is a space-separated list of tokens. + * + * A token that resolves to a list is substituted by its tokens, as + * css-variables-1 §3 substitutes a var(): a space-separated list joins the + * current item, and a comma-separated one splits it. + * + * Resolved values are resolved again (variables cache them), so the result + * keeps the same shape: a flat array for a space-separated list, an array of + * arrays for a comma-separated one. + */ +function resolveList( + list: StyleDescriptor[], + get: Getter, + options: ResolveValueOptions, +): unknown[] { + // Classify the first entry once: a style function is a token, any other + // array is an item of a comma-separated list. Only an array led by a plain + // object needs isStyleFunction's Object.keys, and resolveValue is told the + // answer so it does not pay for it twice. + const first = list[0]; + let isCommaSeparated = false; + let firstIsFunction = false; + + if (Array.isArray(first)) { + const lead: unknown = first[0]; + if ( + typeof lead === "object" && + lead !== null && + !Array.isArray(lead) && + isStyleFunction(first) + ) { + firstIsFunction = true; + } else { + isCommaSeparated = true; + } + } + + if (!isCommaSeparated && list.length === 1) { + // Fast path for a lone token: its list, if it resolves to one, is the value + const resolved: unknown = resolveValue(first, get, options, firstIsFunction); + return Array.isArray(resolved) + ? resolved + : resolved === undefined + ? [] + : [resolved]; + } + + // Allocated only once the list turns out to be comma-separated + let items: unknown[][] | undefined = isCommaSeparated ? [] : undefined; + let item: unknown[] = []; + + // Indexed loops and the inlined common case of appendList: this runs for + // every list on every render, and Hermes pays for iterators and calls + for (let index = 0; index < list.length; index++) { + const entry = list[index]; + + if (isCommaSeparated && (index === 0 || isItem(entry))) { + const tokens = entry as StyleDescriptor[]; + + // In a comma-separated list the item is empty here, as each entry closes it + if (tokens.length === 1) { + // Fast path for a one-token item, as most are: no item to build and reset + const resolved: unknown = resolveValue(tokens[0], get, options); + if (!Array.isArray(resolved)) { + if (resolved !== undefined) items!.push([resolved]); + continue; + } + item = appendList(resolved, item, (items ??= [])); + } else { + for (let tokenIndex = 0; tokenIndex < tokens.length; tokenIndex++) { + const resolved: unknown = resolveValue( + tokens[tokenIndex], + get, + options, + ); + if (!Array.isArray(resolved)) { + if (resolved !== undefined) item.push(resolved); + } else { + item = appendList(resolved, item, (items ??= [])); + } + } + } + } else { + // A lone token in an item's place, or a space-separated list's token + const resolved: unknown = resolveValue( + entry, + get, + options, + index === 0 && firstIsFunction, + ); + if (!Array.isArray(resolved)) { + if (resolved !== undefined) item.push(resolved); + } else { + item = appendList(resolved, item, (items ??= [])); + } + } + + if (isCommaSeparated && item.length > 0) { + items!.push(item); + item = []; + } + } + + if (items === undefined || items.length === 0) { + return item; + } + + if (item.length > 0) items.push(item); + return items; +} + +/** + * Whether an entry after the first of a comma-separated list is an item, an + * array of tokens, rather than a lone token in an item's place. Only a style + * function, `[{}, name]`, is an array led by a plain object, so the full + * check runs only for one of those or for a resolved item led by an object, + * such as `[{ rotate }, "x"]`. + */ +function isItem(entry: StyleDescriptor): entry is StyleDescriptor[] { + if (!Array.isArray(entry)) return false; + const lead: unknown = entry[0]; + return ( + typeof lead !== "object" || + lead === null || + Array.isArray(lead) || + !isStyleFunction(entry) + ); +} + +/** + * Substitutes a resolved list into the current item and returns the item + * later tokens join. A resolved value holds no style functions, so a list led + * by an array is comma-separated: its first item continues the current one + * and each later item starts its own. Any other list joins the current item. + */ +function appendList( + resolved: unknown[], + item: unknown[], + items: unknown[][], +): unknown[] { + if (!Array.isArray(resolved[0])) { + for (let index = 0; index < resolved.length; index++) { + item.push(resolved[index]); + } + return item; + } + + for (let index = 0; index < resolved.length; index++) { + if (index > 0) { + items.push(item); + item = []; + } + const group = resolved[index] as unknown[]; + for (let valueIndex = 0; valueIndex < group.length; valueIndex++) { + item.push(group[valueIndex]); + } + } + + return item; +} diff --git a/src/native/styles/shorthands/box-shadow.ts b/src/native/styles/shorthands/box-shadow.ts index 20936e49..b3066f01 100644 --- a/src/native/styles/shorthands/box-shadow.ts +++ b/src/native/styles/shorthands/box-shadow.ts @@ -1,5 +1,7 @@ -import type { StyleDescriptor } from "react-native-css/compiler"; -import { isStyleDescriptorArray } from "react-native-css/utilities"; +import { + isCommaList, + isStyleDescriptorArray, +} from "react-native-css/utilities"; import type { StyleFunctionResolver } from "../resolve"; import { shorthandHandler } from "./_handler"; @@ -33,6 +35,8 @@ const handler = shorthandHandler( "object", ); +const alreadyResolved = (value: unknown) => value; + export const boxShadow: StyleFunctionResolver = ( resolveValue, func, @@ -45,41 +49,23 @@ export const boxShadow: StyleFunctionResolver = ( return args; } - // A flat array of primitives (e.g. [0, 4, 6, -1, "#000"]) is a single shadow - // resolved from a runtime variable. Pass it directly to the pattern handler. - // A nested array (e.g. [[0, 4, 6, -1, "#000"], [...]]) is multiple shadows. - if (args.length > 0 && !Array.isArray(args[0])) { - const result = handler(resolveValue, args, get, options); - if (result === undefined) { - return []; - } - const filtered = omitTransparentShadows(result); - return filtered !== undefined ? [normalizeInsetValue(filtered)] : []; - } + // A flat array of tokens (e.g. [0, 4, 6, -1, "#000"]) is a single shadow, + // written out or substituted from a variable. An array of arrays + // (e.g. [[0, 4, 6, -1, "#000"], [...]]) is a comma-separated list, one + // shadow per item. The compiler keeps the separator via the nested array. + const shadows = isCommaList(args) ? args : [args]; + const result: unknown[] = []; - return args - .flatMap(flattenShadowDescriptor) - .map((shadows) => { - if (shadows === undefined) { - return; - } else { - return normalizeInsetValue( - omitTransparentShadows(handler(resolveValue, shadows, get, options)), - ); - } - }) - .filter((v) => v !== undefined); -}; - -function flattenShadowDescriptor(arg: StyleDescriptor): StyleDescriptor[] { - if (isStyleDescriptorArray(arg) && isStyleDescriptorArray(arg[0])) { - return arg.map((arg) => { - return flattenShadowDescriptor(arg); - }); + for (const shadow of shadows) { + const value = normalizeInsetValue( + // alreadyResolved rather than resolveValue: don't walk through tokens and resolve all shadows when we've already resolved this one + omitTransparentShadows(handler(alreadyResolved, shadow, get, options)), + ); + if (value !== undefined) result.push(value); } - return [arg]; -} + return result; +}; function omitTransparentShadows(style: unknown) { if (typeof style === "object" && style && "color" in style) { diff --git a/src/utilities/style-descriptor.ts b/src/utilities/style-descriptor.ts index 7a166fa1..fc52ee59 100644 --- a/src/utilities/style-descriptor.ts +++ b/src/utilities/style-descriptor.ts @@ -17,3 +17,30 @@ export function isStyleFunction(value: unknown): value is StyleFunction { typeof value[1] === "string" ); } + +/** + * Whether a resolved value is a comma-separated list: an array of items, each + * the array of its tokens. A resolved value holds no style functions, so an + * array led by an array is one. For a descriptor, which can be led by a + * function, test its first entry with isStyleDescriptorArray instead. + */ +export function isCommaList(value: unknown): value is unknown[][] { + return Array.isArray(value) && Array.isArray(value[0]); +} + +/** + * A resolved comma-separated list with each one-token item unwrapped, the + * form function arguments and React Native's list props take. Anything else + * is returned as it is. + */ +export function commaListItems(value: unknown): unknown { + if (!isCommaList(value)) return value; + + // push, not map() or new Array(n), which Hermes runs slower: React + // Native's list props pass through here on every render + const items: unknown[] = []; + for (const item of value) { + items.push(item.length === 1 ? item[0] : item); + } + return items; +}