Skip to content

packages/core/src/lib/style/normalize.ts

Read as Markdown

This is the source snapshot used to build these API details. View this revision on GitHub.

Back to reference

1 import type { Edges } from '../layout/types.js';
2 import {
3   layoutDiagnostic,
4   type LayoutDiagnosticContext,
5 } from './diagnostics.js';
6 import type { EdgeValues } from './types.js';
7 
8 /**
9  * Expands shorthand insets into four validated numeric edges.
10  *
11  * @param value - Edge shorthand to expand; undefined uses the empty edge defaults. See
12  * {@link EdgeValues} .
13  * @param property - Property name used in diagnostics.
14  * @param context - Component and property context for diagnostic messages. See
15  * {@link LayoutDiagnosticContext} .
16  * @returns Explicit top, right, bottom, and left edge values. See {@link Edges}.
17  *
18  * @see {@link EdgeValues}
19  * @see {@link LayoutDiagnosticContext}
20  * @see {@link Edges}
21  */
22 export function normalizeEdges(
23   value: EdgeValues | undefined,
24   property: string,
25   context: Readonly<LayoutDiagnosticContext> = {},
26 ): Edges {
27   if (value === undefined) return zeroEdges();
28   if (typeof value === 'number') {
29     const edge = validateEdge(value, property, context);
30     return { top: edge, right: edge, bottom: edge, left: edge };
31   }
32   if (value === null || typeof value !== 'object' || Array.isArray(value)) {
33     throw layoutDiagnostic({
34       ...context,
35       property,
36       value,
37       reason: `uses an unsupported edge value ${String(value)}`,
38     });
39   }
40 
41   return {
42     top: validateEdge(value.top ?? 0, `${property}.top`, context),
43     right: validateEdge(value.right ?? 0, `${property}.right`, context),
44     bottom: validateEdge(value.bottom ?? 0, `${property}.bottom`, context),
45     left: validateEdge(value.left ?? 0, `${property}.left`, context),
46   };
47 }
48 
49 function validateEdge(
50   value: number,
51   property: string,
52   context: Readonly<LayoutDiagnosticContext>,
53 ): number {
54   if (typeof value !== 'number' || !Number.isFinite(value)) {
55     throw layoutDiagnostic({
56       ...context,
57       property,
58       value,
59       reason: 'must be a finite number',
60     });
61   }
62   if (value < 0) {
63     throw layoutDiagnostic({
64       ...context,
65       property,
66       value,
67       reason: 'must be nonnegative',
68     });
69   }
70   return value;
71 }
72 
73 function zeroEdges(): Edges {
74   return { top: 0, right: 0, bottom: 0, left: 0 };
75 }
76 

Documentation built with @pibbl/core 0.0.2, revision 272a94a. ALPHA — NOT FOR PRODUCTION USE.