-
-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathsnap-to-border-width.ts
More file actions
46 lines (38 loc) · 2.07 KB
/
snap-to-border-width.ts
File metadata and controls
46 lines (38 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import type { CSSToken, TokenDimension} from "@csstools/css-tokenizer";
import { isTokenDimension, NumberType, TokenType } from "@csstools/css-tokenizer";
import type { conversionOptions } from "../options";
import { convertUnit } from "../unit-conversions";
import { twoOfSameNumeric } from "./kind-of-number";
import { resultToCalculation } from "../functions/result-to-calculation";
import type { FunctionNode } from "@csstools/css-parser-algorithms";
import type { Calculation } from "../calculation";
export function snapAsBorderWidth(fnNode: FunctionNode, aToken: CSSToken, options: conversionOptions): Calculation | -1 {
if (!isTokenDimension(aToken)) {
return -1;
}
const devicePixelLength = options.devicePixelLength ?? 1;
const devicePixelLengthToken: TokenDimension = [TokenType.Dimension, `${devicePixelLength}px`, aToken[2], aToken[3], { value: devicePixelLength, type: NumberType.Integer, unit: 'px' }];
const aTokenAsPixels = convertUnit(devicePixelLengthToken, aToken);
if (!twoOfSameNumeric(aTokenAsPixels, devicePixelLengthToken)) {
return -1;
}
if (aTokenAsPixels[4].value < 0) {
// Assert: len is non-negative.
return -1;
}
if (Number.isInteger(aTokenAsPixels[4].value / devicePixelLength)) {
// If len is an integer number of device pixels, do nothing.
return resultToCalculation(fnNode, aToken, aToken[4].value);
}
if (aTokenAsPixels[4].value > 0 && aTokenAsPixels[4].value < devicePixelLength) {
// If len is greater than zero, but less than 1 device pixel, round len up to 1 device pixel.
return resultToCalculation(fnNode, aToken, convertUnit(aToken, devicePixelLengthToken)[4].value);
}
if (aTokenAsPixels[4].value > devicePixelLength) {
// If len is greater than 1 device pixel, round it down to the nearest integer number of device pixels.
const down = Math.floor(aTokenAsPixels[4].value / devicePixelLengthToken[4].value) * devicePixelLengthToken[4].value;
aTokenAsPixels[4].value = down;
return resultToCalculation(fnNode, aToken, convertUnit(aToken, aTokenAsPixels)[4].value);
}
return resultToCalculation(fnNode, aToken, aToken[4].value);
}