Skip to content
Open
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
86 changes: 57 additions & 29 deletions packages/core/ui/core/properties/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import { calc } from '@csstools/css-calc';
export { unsetValue } from './property-shared';

const cssPropertyNames: string[] = [];
// Probed with `unsetValue` (getCssShorthandLonghands) as well as called with values, so typed for any value.
const cssShorthandConverters = new Map<string, (value: any) => [any, any][]>();
// converter is probed with `unsetValue` (getCssShorthandLonghands) as well as called with values, so typed for any value.
const cssShorthands = new Map<string, { converter: (value: any) => [any, any][]; converterForStyle?: ShorthandPropertyOptions<string>['converterForStyle'] }>();
const cssShorthandLonghands = new Map<string, string[]>();
// Bumped per shorthand registration, so rules parsed before it can still expand it.
let cssShorthandsVersion = 0;
Expand Down Expand Up @@ -125,7 +125,7 @@ function getCssShorthandLonghands(cssName: string): string[] | undefined {
return known;
}

const converter = cssShorthandConverters.get(cssName);
const converter = cssShorthands.get(cssName)?.converter;
if (!converter) {
return undefined;
}
Expand Down Expand Up @@ -177,26 +177,26 @@ export function _getCssShorthandsVersion(): number {

/** Whether `cssName` is a registered shorthand. */
export function _isCssShorthand(cssName: string): boolean {
return cssShorthandConverters.has(cssName);
return cssShorthands.has(cssName);
}

/**
* Expand a shorthand declaration into its longhand declarations, or `undefined`
* when the property is not a shorthand, the value still has to be evaluated per
* view (`var()`/`calc()`), or it does not parse.
* view, or it does not parse.
*/
export function _expandCssShorthand(cssName: string, value: string): [string, any][] | undefined {
const converter = cssShorthandConverters.get(cssName);
if (!converter) {
export function _expandCssShorthand(cssName: string, value: string, preserveMath = false, style?: Style): [string, any][] | undefined {
const shorthand = cssShorthands.get(cssName);
if (!shorthand || (shorthand.converterForStyle && !style)) {
return undefined;
}

if (typeof value === 'string' && (isCssVariableExpression(value) || isCssCalcExpression(value))) {
if (typeof value === 'string' && (isCssVariableExpression(value) || (!preserveMath && isCssCalcExpression(value)))) {
return undefined;
}

try {
const converted = converter(value);
const converted = (style && shorthand.converterForStyle?.(value, style)) ?? shorthand.converter(value);
const expanded: [string, any][] = [];
for (let i = 0, length = converted.length; i < length; i++) {
expanded.push([converted[i][0].cssLocalName, converted[i][1]]);
Expand Down Expand Up @@ -225,8 +225,9 @@ export function isCssVariableExpression(value: string) {
/**
* Substitute the css-variables in a value.
* @param reads Collects every variable looked up, with the value the lookup returned.
* @param preserveMath Look up variables as specified, without their calc() reduced.
*/
export function _evaluateCssVariableExpression(view: ViewBase, cssName: string, value: string, reads?: Map<string, string | null>): string {
export function _evaluateCssVariableExpression(view: ViewBase, cssName: string, value: string, reads?: Map<string, string | null>, preserveMath = false): string {
if (typeof value !== 'string') {
return value;
}
Expand Down Expand Up @@ -257,15 +258,15 @@ export function _evaluateCssVariableExpression(view: ViewBase, cssName: string,
const commaIdx = body.indexOf(',');
const cssVariableName = (commaIdx === -1 ? body : body.substring(0, commaIdx)).trim();
const fallback = commaIdx === -1 ? '' : body.substring(commaIdx + 1).trim();
let cssVariableValue = view.style.getCssVariable(cssVariableName);
let cssVariableValue = view.style.getCssVariable(cssVariableName, preserveMath);
if (reads) {
reads.set(cssVariableName, cssVariableValue);
}
if (typeof cssVariableValue === 'string' && cssVariableValue.trim() === 'initial') {
cssVariableValue = null;
}
if (cssVariableValue === null && fallback) {
cssVariableValue = _evaluateCssVariableExpression(view, cssName, fallback, reads);
cssVariableValue = _evaluateCssVariableExpression(view, cssName, fallback, reads, preserveMath);
}

if (!cssVariableValue || cssVariableValue === 'unset') {
Expand Down Expand Up @@ -326,16 +327,25 @@ function hasCssExpression(value: unknown): value is string {
return typeof value === 'string' && (isCssVariableExpression(value) || isCssCalcExpression(value));
}

function preservesCssMath(view: ViewBase, property: string): boolean {
return view.style.preserveCssMath?.(property) === true;
}

/**
* Evaluate the css-variable and css-calc expressions of a value against the view,
* or `unsetValue` when they do not resolve.
* or `unsetValue` when they do not resolve. With `preserveMath`, only the variables
* are substituted.
*/
export function _evaluateCssExpressions(view: ViewBase, property: string, value: string, reads?: Map<string, string | null>) {
const newValue = _evaluateCssVariableExpression(view, property, value, reads);
export function _evaluateCssExpressions(view: ViewBase, property: string, value: string, reads?: Map<string, string | null>, preserveMath = preservesCssMath(view, property)) {
const newValue = _evaluateCssVariableExpression(view, property, value, reads, preserveMath);
if (newValue === 'unset') {
return unsetValue;
}

if (preserveMath) {
return newValue;
}

try {
return _evaluateCssCalcExpression(newValue);
} catch (e) {
Expand All @@ -347,12 +357,12 @@ export function _evaluateCssExpressions(view: ViewBase, property: string, value:

const NO_LONGHAND_VALUES: Record<string, unknown> = Object.freeze({});

function expandSubstitutedShorthand(view: ViewBase, shorthand: string, substituted: unknown): Record<string, unknown> {
function expandSubstitutedShorthand(view: ViewBase, shorthand: string, substituted: unknown, preserveMath: boolean): Record<string, unknown> {
if (substituted === unsetValue) {
return NO_LONGHAND_VALUES;
}

const expanded = _expandCssShorthand(shorthand, <string>substituted);
const expanded = _expandCssShorthand(shorthand, <string>substituted, preserveMath, view.style);
if (!expanded) {
Trace.write(`Failed to expand shorthand [${shorthand}] resolved to [${substituted}] for ${view}.`, Trace.categories.Style, Trace.messageType.warn);

Expand All @@ -376,9 +386,9 @@ export interface _SubstitutedCssShorthand {

type CssVariableReads = Map<string, string | null>;

function cssVariablesUnchanged(view: ViewBase, reads: CssVariableReads): boolean {
function cssVariablesUnchanged(view: ViewBase, reads: CssVariableReads, preserveMath: boolean): boolean {
for (const [name, value] of reads) {
if (view.style.getCssVariable(name) !== value) {
if (view.style.getCssVariable(name, preserveMath) !== value) {
return false;
}
}
Expand All @@ -392,9 +402,10 @@ function cssVariablesUnchanged(view: ViewBase, reads: CssVariableReads): boolean
*/
export function _substituteCssShorthand(view: ViewBase, pending: CssPendingSubstitution): _SubstitutedCssShorthand {
const reads: CssVariableReads = new Map();
const substituted = _evaluateCssExpressions(view, pending.shorthand, pending.value, reads);
const preserveMath = preservesCssMath(view, pending.shorthand);
const substituted = _evaluateCssExpressions(view, pending.shorthand, pending.value, reads, preserveMath);

return { substituted, values: expandSubstitutedShorthand(view, pending.shorthand, substituted), reads };
return { substituted, values: expandSubstitutedShorthand(view, pending.shorthand, substituted, preserveMath), reads };
}

function keepLocalCssExpression(style: Style, cssName: string, specified: string | CssPendingSubstitution, substituted: unknown, reads: CssVariableReads): void {
Expand All @@ -411,12 +422,22 @@ function releaseLocalCssExpression(style: Style, cssName: string): void {
}
}

// A substituted value can still hold calc() when its converter preserves math, so it must not be substituted again.
let substitutedCssWrite: { style: Style; cssName: string } | undefined;

/**
* Wrap a local setter: a string holding var()/calc() is written substituted and kept
* for the cascade to substitute again, any other write releases what was kept.
*/
function localCssExpressionSetter<T extends Style>(cssName: string, set: (this: T, value: unknown) => void): (this: T, value: unknown) => void {
return function (this: T, value: unknown): void {
if (substitutedCssWrite && substitutedCssWrite.style === this && substitutedCssWrite.cssName === cssName) {
substitutedCssWrite = undefined;
set.call(this, value);

return;
}

if (hasCssExpression(value)) {
const view = this.viewRef.get();
if (view) {
Expand All @@ -435,7 +456,12 @@ function localCssExpressionSetter<T extends Style>(cssName: string, set: (this:
}

function setLocalCssExpression(style: Style, cssName: string, specified: string | CssPendingSubstitution, substituted: unknown, reads: CssVariableReads, value: unknown): void {
style[cssName] = value;
substitutedCssWrite = { style, cssName };
try {
style[cssName] = value;
} finally {
substitutedCssWrite = undefined;
}
keepLocalCssExpression(style, cssName, specified, substituted, reads);
}

Expand Down Expand Up @@ -463,12 +489,13 @@ export function _reevaluateLocalCssExpressions(view: ViewBase): void {
const entries = Array.from(expressions);
for (let i = 0, length = entries.length; i < length; i++) {
const [cssName, expression] = entries[i];
const specified = expression.specified;
const preserveMath = preservesCssMath(view, specified instanceof CssPendingSubstitution ? specified.shorthand : cssName);
// A change listener may have replaced or released it meanwhile.
if (style._localCssExpressions?.get(cssName) !== expression || cssVariablesUnchanged(view, expression.reads)) {
if (style._localCssExpressions?.get(cssName) !== expression || cssVariablesUnchanged(view, expression.reads, preserveMath)) {
continue;
}

const specified = expression.specified;
let substituted: unknown;
let reads: CssVariableReads;
let value: unknown;
Expand All @@ -481,7 +508,7 @@ export function _reevaluateLocalCssExpressions(view: ViewBase): void {
if (!shorthand) {
reads = new Map();
// Expanded only when the substitution changed.
shorthand = { substituted: _evaluateCssExpressions(view, specified.shorthand, specified.value, reads), values: undefined, reads };
shorthand = { substituted: _evaluateCssExpressions(view, specified.shorthand, specified.value, reads, preserveMath), values: undefined, reads };
shorthands.set(specified, shorthand);
}
substituted = shorthand.substituted;
Expand All @@ -491,12 +518,12 @@ export function _reevaluateLocalCssExpressions(view: ViewBase): void {
continue;
}
if (!shorthand.values) {
shorthand.values = expandSubstitutedShorthand(view, specified.shorthand, substituted);
shorthand.values = expandSubstitutedShorthand(view, specified.shorthand, substituted, preserveMath);
}
value = cssName in shorthand.values ? shorthand.values[cssName] : unsetValue;
} else {
reads = new Map();
substituted = _evaluateCssExpressions(view, cssName, specified, reads);
substituted = _evaluateCssExpressions(view, cssName, specified, reads, preserveMath);
if (substituted === expression.substituted) {
expression.reads = reads;
continue;
Expand Down Expand Up @@ -1657,7 +1684,8 @@ export class ShorthandProperty<T extends Style, P> implements ShorthandProperty<

this.cssName = `css:${options.cssName}`;
this.cssLocalName = `${options.cssName}`;
cssShorthandConverters.set(options.cssName, options.converter as (value: any) => [any, any][]);
cssShorthands.set(options.cssName, options);
cssShorthandLonghands.delete(options.cssName);
cssShorthandsVersion++;

const converter = options.converter;
Expand Down
4 changes: 4 additions & 0 deletions packages/core/ui/core/properties/property-shared.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Shared property types, interfaces, and value helpers for properties and view-base modules.
// Only put platform-agnostic logic here.

import type { Style } from '../../styling/style';

/**
* Value specifying that Property should be set to its initial value.
*/
Expand Down Expand Up @@ -31,6 +33,8 @@ export interface ShorthandPropertyOptions<P> {
readonly name: string;
readonly cssName: string;
readonly converter: (value: string | P) => [any, any][];
/** Defer stylesheet conversion until the target style is known. Return undefined to use converter. */
readonly converterForStyle?: (value: string, style: Style) => [any, any][] | undefined;
readonly getter: (this: any) => string | P;
}
// TODO: revisit this after circular dependency issues are resolved to see if types can be retained.
Expand Down
3 changes: 1 addition & 2 deletions packages/core/ui/styling/css-selector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1000,8 +1000,7 @@ function pushDeclaration(declarations: Declaration[], property: string, value: s
return;
}

// A var()/calc() shorthand cannot be expanded yet - cascade one
// pending-substitution value per longhand instead.
// Cascade one pending-substitution value per longhand for deferred shorthands.
const pending = _pendingCssShorthandSubstitution(property, value);
if (pending) {
for (let i = 0, length = pending.length; i < length; i++) {
Expand Down
93 changes: 93 additions & 0 deletions packages/core/ui/styling/style-scope.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { parse } from '../../css/reworkcss.js';
import type { RuleSet } from './css-selector';
import { StackLayout } from '../layouts/stack-layout';
import { Label } from '../label';
import { CssProperty, ShorthandProperty } from '../core/properties';
import { Style } from './style';

/**
* Counts how many times css applies a value to a style property, by wrapping the
Expand Down Expand Up @@ -53,6 +55,97 @@ function styledWithParent(css: string, parentClassName: string): { view: any; pa
return { view, parent, scope };
}

describe('Style.preserveCssMath', () => {
const paint = new CssProperty<Style, string>({ name: 'rawPaint', cssName: 'raw-paint' });
paint.register(Style);
new ShorthandProperty<Style, string>({
name: 'rawPaintShorthand',
cssName: 'raw-paint-shorthand',
getter() {
return this[paint.name];
},
converter(value) {
return [[paint, value]];
},
}).register(Style);

it('substitutes inherited variables without reducing the selected expression', () => {
const { view, parent } = styledWithParent('.root { --paint: var(--base); --base: calc(0.2 + 0.3); } label { raw-paint: var(--paint); opacity: var(--paint); }', 'root');
view.style.preserveCssMath = (name: string) => name === 'raw-paint';
parent._cssState.onLoaded();
view._cssState.onLoaded();
expect(parent.style.getCssVariable('--paint')).toBe('0.5');
expect(view.style.rawPaint).toBe('calc(0.2 + 0.3)');
expect(view.style.opacity).toBe(0.5);
});

it('passes math through pending shorthands and keeps longhand priority', () => {
const { view } = styled('label { --base: 2px; raw-paint-shorthand: calc(var(--base) + 2px); raw-paint: 3px; }');
view.style.preserveCssMath = (name: string) => name === 'raw-paint-shorthand';
view._cssState.onLoaded();
expect(view.style.rawPaint).toBe('3px');
applyInlineStyle(view, 'raw-paint-shorthand: var(--missing, calc(2px + 2px));');
expect(view.style.rawPaint).toBe('calc(2px + 2px)');
});
});

describe('view-specific shorthand conversion', () => {
const horizontal = new CssProperty<Style, string>({ name: 'testHorizontal', cssName: 'test-horizontal' });
const vertical = new CssProperty<Style, string>({ name: 'testVertical', cssName: 'test-vertical' });
horizontal.register(Style);
vertical.register(Style);
const rawStyles = new WeakSet<Style>();
let parsed: string[] = [];
new ShorthandProperty<Style, string>({
name: 'testDirection',
cssName: 'test-direction',
getter() {
return this[horizontal.name];
},
converter(value) {
if (typeof value === 'string') {
parsed.push(value);
}
return [
[horizontal, value],
[vertical, value],
];
},
converterForStyle(value, style) {
return rawStyles.has(style) ? [[horizontal, value]] : undefined;
},
}).register(Style);

it('defers literal declarations and converts only for the matching view', () => {
parsed = [];
const css = 'label { test-direction: left; test-vertical: up; }';
const { view } = styled(css);
rawStyles.add(view.style);
expect(parsed).toEqual([]);
view._cssState.onLoaded();
expect(view.style.testHorizontal).toBe('left');
expect(view.style.testVertical).toBe('up');
expect(parsed).toEqual([]);

const { view: plainView } = styled(css);
plainView._cssState.onLoaded();
expect(plainView.style.testHorizontal).toBe('left');
expect(plainView.style.testVertical).toBe('up');
expect(parsed).toEqual(['left']);
});

it('preserves math and resolves variables before passing the value to the selected converter', () => {
parsed = [];
const { view } = styled('label { --base: 20px; test-direction: calc(var(--base) + 10px); }');
rawStyles.add(view.style);
view.style.preserveCssMath = (name) => name === 'test-direction';
view._cssState.onLoaded();
expect(view.style.testHorizontal).toBe('calc(20px + 10px)');
expect(view.style.testVertical).toBeUndefined();
expect(parsed).toEqual([]);
});
});

describe('CssState.setPropertyValues', () => {
it('applies matched declarations', () => {
const { view } = styled('label { color: red; }');
Expand Down
Loading
Loading