packages/core/src/lib/style/resolve-length.ts
This is the source snapshot used to build these API details. View this revision on GitHub.
1 import {
2 layoutDiagnostic,
3 type LayoutDiagnosticContext,
4 } from './diagnostics.js';
5 import type { Length } from './types.js';
6
7 const DECIMAL_PERCENTAGE = /^[+-]?(?:\d+(?:\.\d+)?|\.\d+)%$/;
8
9 /**
10 * Resolves a numeric or percentage length; automatic sizing returns undefined.
11 *
12 * @param value - Logical length or percentage to resolve. See {@link Length}.
13 * @param reference - Reference length for percentages, or undefined if unavailable.
14 * @param property - Property name used in diagnostics.
15 * @param context - Component and property context for diagnostic messages. See
16 * {@link LayoutDiagnosticContext} .
17 * @returns The resolved logical length, or undefined for an unresolved automatic length.
18 *
19 * @see {@link Length}
20 * @see {@link LayoutDiagnosticContext}
21 */
22 export function resolveLength(
23 value: Length,
24 reference: number | undefined,
25 property: string,
26 context: Readonly<LayoutDiagnosticContext> = {},
27 ): number | undefined {
28 if (value === 'auto') return undefined;
29
30 if (typeof value === 'number') {
31 if (!Number.isFinite(value)) {
32 throw diagnostic(property, value, 'must be a finite number', context);
33 }
34 return value;
35 }
36
37 const percentage = parsePercentage(value, property, context);
38
39 if (reference === undefined || !Number.isFinite(reference)) {
40 throw diagnostic(
41 property,
42 value,
43 'requires a definite finite percentage reference',
44 context,
45 );
46 }
47 if (reference < 0) {
48 throw diagnostic(
49 property,
50 value,
51 'percentage reference must be nonnegative',
52 context,
53 );
54 }
55
56 const resolved = (percentage / 100) * reference;
57 if (!Number.isFinite(resolved)) {
58 throw diagnostic(
59 property,
60 value,
61 'resolved percentage arithmetic must remain finite',
62 context,
63 );
64 }
65 return resolved;
66 }
67
68 /** @internal Parse a percentage independently of its containing-size reference. */
69 export function parsePercentage(value: unknown, property: string, context: Readonly<LayoutDiagnosticContext> = {}): number {
70 if (typeof value !== 'string' || !DECIMAL_PERCENTAGE.test(value)) {
71 throw diagnostic(property, value, `uses an unsupported length value ${String(value)}`, context);
72 }
73 const percentage = Number.parseFloat(value);
74 if (!Number.isFinite(percentage)) {
75 throw diagnostic(property, value, 'percentage must be finite', context);
76 }
77 return percentage;
78 }
79
80 function diagnostic(
81 property: string,
82 value: unknown,
83 reason: string,
84 context: Readonly<LayoutDiagnosticContext>,
85 ) {
86 return layoutDiagnostic({ ...context, property, value, reason });
87 }
88
Documentation version
Section titled “Documentation version”Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.