Skip to content
Merged
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
5 changes: 5 additions & 0 deletions packages/css-calc/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Changes to CSS Calc

### Unreleased (patch)

- Update `random()` to better handle floating point errors.
- Update `random()` to match the latest [specification](https://drafts.csswg.org/css-values-5/#randomness)

### 2.1.2

_February 23, 2025_
Expand Down
2 changes: 1 addition & 1 deletion packages/css-calc/dist/index.cjs

Large diffs are not rendered by default.

23 changes: 21 additions & 2 deletions packages/css-calc/dist/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,28 @@ export declare type conversionOptions = {
*/
rawPercentages?: boolean;
/**
* Seed the pseudo random number generator used in `random()`
* The values used to generate random value cache keys.
*/
randomSeed?: number;
randomCaching?: {
/**
* The name of the property the random function is used in.
*/
propertyName: string;
/**
* N is the index of the random function among other random functions in the same property value.
*/
propertyN: number;
/**
* An element ID identifying the element the style is being applied to.
* When omitted any `random()` call will not be computed.
*/
elementID: string;
/**
* A document ID identifying the Document the styles are from.
* When omitted any `random()` call will not be computed.
*/
documentID: string;
};
};

export declare type GlobalsWithStrings = Map<string, TokenDimension | TokenNumber | TokenPercentage | string>;
Expand Down
2 changes: 1 addition & 1 deletion packages/css-calc/dist/index.mjs

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion packages/css-calc/docs/css-calc.api.json
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@
},
{
"kind": "Content",
"text": ";\n precision?: number;\n toCanonicalUnits?: boolean;\n censorIntoStandardRepresentableValues?: boolean;\n rawPercentages?: boolean;\n randomSeed?: number;\n}"
"text": ";\n precision?: number;\n toCanonicalUnits?: boolean;\n censorIntoStandardRepresentableValues?: boolean;\n rawPercentages?: boolean;\n randomCaching?: {\n propertyName: string;\n propertyN: number;\n elementID: string;\n documentID: string;\n };\n}"
},
{
"kind": "Content",
Expand Down
7 changes: 6 additions & 1 deletion packages/css-calc/docs/css-calc.conversionoptions.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,12 @@ export type conversionOptions = {
toCanonicalUnits?: boolean;
censorIntoStandardRepresentableValues?: boolean;
rawPercentages?: boolean;
randomSeed?: number;
randomCaching?: {
propertyName: string;
propertyN: number;
elementID: string;
documentID: string;
};
};
```
**References:** [GlobalsWithStrings](./css-calc.globalswithstrings.md)
Expand Down
149 changes: 106 additions & 43 deletions packages/css-calc/src/functions/calc.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { Calculation } from '../calculation';
import type { ComponentValue, SimpleBlockNode } from '@csstools/css-parser-algorithms';
import type { Globals } from '../util/globals';
import { TokenType, NumberType, isTokenOpenParen, isTokenDelim, isTokenComma, isTokenIdent } from '@csstools/css-tokenizer';
import { TokenType, NumberType, isTokenOpenParen, isTokenDelim, isTokenComma, isTokenIdent, isTokenNumber } from '@csstools/css-tokenizer';
import { addition } from '../operation/addition';
import { division } from '../operation/division';
import { isCalculation, solve } from '../calculation';
Expand Down Expand Up @@ -32,6 +32,7 @@ import { unary } from '../operation/unary';
import { solveLog } from './log';
import { isNone } from '../util/is-none';
import type { conversionOptions } from '../options';
import type { RandomValueSharing} from './random';
import { solveRandom } from './random';

type mathFunction = (node: FunctionNode, globals: Globals, options: conversionOptions) => Calculation | -1
Expand Down Expand Up @@ -576,65 +577,127 @@ function log(logNode: FunctionNode, globals: Globals, options: conversionOptions
}

function random(randomNode: FunctionNode, globals: Globals, options: conversionOptions): Calculation | -1 {
const nodes: Array<ComponentValue> = randomNode.value.filter(x => !isWhiteSpaceOrCommentNode(x));
const randomValueSharingAndNodes = parseRandomValueSharing(
randomNode.value.filter(x => !isWhiteSpaceOrCommentNode(x)),
globals,
options,
);
if (randomValueSharingAndNodes === -1) {
return -1;
}

let randomCachingOptions = '';
const stepValues: Array<ComponentValue> = []
const values: Array<ComponentValue> = []
const [randomValueSharing, nodes] = randomValueSharingAndNodes;

{
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
if (!randomCachingOptions && values.length === 0 && isTokenNode(node) && isTokenIdent(node.value)) {
const token = node.value;
const tokenStr = token[4].value.toLowerCase();
if (tokenStr === 'per-element' || tokenStr.startsWith('--')) {
randomCachingOptions = tokenStr;
const randomArguments = variadicArguments(nodes, globals, options);
if (randomArguments === -1) {
return -1;
}

const nextNode = nodes[i + 1];
if (!isTokenNode(nextNode) || !isTokenComma(nextNode.value)) {
return -1;
}
const [a, b, c] = randomArguments;

i++;
continue;
}
if (!a || !b) {
return -1
}

return solveRandom(
randomNode,
randomValueSharing,
a,
b,
c,
options
);
}

function parseRandomValueSharing(nodes: Array<ComponentValue>, globals: Globals, options: conversionOptions): [RandomValueSharing, Array<ComponentValue>] | -1 {
const x: RandomValueSharing = {
isAuto: false,
dashedIdent: "",
fixed: -1,
elementShared: false,
};

const firstNode = nodes[0];
if (!isTokenNode(firstNode) || !isTokenIdent(firstNode.value)) {
return [x, nodes];
}

for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
if (!isTokenNode(node)) {
return -1;
}

if (isTokenComma(node.value)) {
return [x, nodes.slice(i+1)];
}

if (!isTokenIdent(node.value)) {
return -1;
}

const token = node.value;
const tokenStr = token[4].value.toLowerCase();

if (tokenStr === 'element-shared') {
if (x.fixed !== -1) {
return -1;
}

if (isTokenNode(node) && isTokenComma(node.value)) {
const nextNode = nodes[i + 1];
x.elementShared = true;
continue;
}

if (values.length > 0 && isTokenNode(nextNode) && isTokenIdent(nextNode.value)) {
const token = nextNode.value;
const tokenStr = token[4].value.toLowerCase();
if (tokenStr === 'by' || tokenStr.startsWith('--')) {
stepValues.push(...nodes.slice(i + 2));
// fixed <number [0,1]>
if (tokenStr === 'fixed') {
if (x.elementShared || x.dashedIdent || x.isAuto) {
return -1;
}

break;
}
}
i++;
const nextNode = nodes[i];
if (!nextNode) {
return -1;
}

const fixedNumber = solve(calc(calcWrapper([nextNode]), globals, options));
if (fixedNumber === -1) {
return -1;
}

if (!isTokenNumber(fixedNumber.value)) {
return -1;
}

if (fixedNumber.value[4].value < 0 || fixedNumber.value[4].value > 1) {
return -1;
}

values.push(node);
x.fixed = Math.max(0, Math.min(fixedNumber.value[4].value, 1 - 0.000_000_001));

continue;
}
}

const solvedValues = twoCommaSeparatedArguments(values, globals, options);
if (solvedValues === -1) {
return -1;
}
if (tokenStr === 'auto') {
if (x.fixed !== -1 || x.dashedIdent) {
return -1;
}

const [a, b] = solvedValues;
x.isAuto = true;
continue;
}

let solvedStepValue: TokenNode | -1 | null = null;
if (stepValues.length) {
solvedStepValue = singleArgument(stepValues, globals, options);
if (solvedStepValue === -1) {
return -1;
if (tokenStr.startsWith('--')) {
if (x.fixed !== -1 || x.isAuto) {
return -1;
}

x.dashedIdent = tokenStr;
continue;
}
}

return solveRandom(randomNode, randomCachingOptions, a, b, solvedStepValue, options);
return -1;
}

function calcWrapper(v: Array<ComponentValue>): FunctionNode {
Expand Down
Loading