|
1
|
import type { BaseSpec, DeepPartial } from "./types.js" |
|
2
|
|
|
3
|
function isSection(value: unknown): value is Record<string, unknown> { |
|
4
|
return typeof value === "object" && value !== null && !Array.isArray(value) |
|
5
|
} |
|
6
|
|
|
7
|
/** |
|
8
|
* Merges overrides into a default spec, section by section. |
|
9
|
* |
|
10
|
* Specs are one or two levels deep — a canvas, and a section per part of the |
|
11
|
* design — so overriding `content.fontSize` has to leave the rest of `content` |
|
12
|
* alone. Arrays are replaced rather than merged; see {@link DeepPartial}. |
|
13
|
*/ |
|
14
|
export function mergeSpec<T extends object>( |
|
15
|
base: T, |
|
16
|
overrides: DeepPartial<T> = {} |
|
17
|
): T { |
|
18
|
const merged = { ...base } as Record<string, unknown> |
|
19
|
|
|
20
|
for (const [key, value] of Object.entries(overrides)) { |
|
21
|
if (value === undefined) { |
|
22
|
continue |
|
23
|
} |
|
24
|
|
|
25
|
const current = merged[key] |
|
26
|
|
|
27
|
merged[key] = |
|
28
|
isSection(current) && isSection(value) ? mergeSpec(current, value) : value |
|
29
|
} |
|
30
|
|
|
31
|
return merged as T |
|
32
|
} |
|
33
|
|
|
34
|
/** |
|
35
|
* Builds a scaler that maps values measured at a design's reference resolution |
|
36
|
* onto whatever width the spec is being rendered at. |
|
37
|
* |
|
38
|
* Every distance in a spec is authored at its reference width, so overriding |
|
39
|
* `width` scales the whole design instead of leaving it stranded at one size. |
|
40
|
*/ |
|
41
|
export function scaler( |
|
42
|
spec: BaseSpec, |
|
43
|
reference: BaseSpec |
|
44
|
): (value: number) => number { |
|
45
|
const scale = spec.width / reference.width |
|
46
|
|
|
47
|
return (value: number): number => value * scale |
|
48
|
} |