55 lines
1.8 KiB
TypeScript
55 lines
1.8 KiB
TypeScript
import type { PrintConfig } from "./types";
|
|
|
|
export const PRINT_DEFAULTS: PrintConfig = {
|
|
columns: 2,
|
|
margin: 10,
|
|
gap: 5,
|
|
font: 3,
|
|
title: "",
|
|
pageNumbers: true,
|
|
timestamp: false,
|
|
cutMarks: true,
|
|
};
|
|
|
|
function toNumber(value: unknown, fallback: number): number {
|
|
const n = typeof value === "number" ? value : Number(value);
|
|
return Number.isFinite(n) ? n : fallback;
|
|
}
|
|
|
|
function toBoolean(value: unknown, fallback: boolean): boolean {
|
|
if (typeof value === "boolean") return value;
|
|
if (typeof value === "string") {
|
|
const s = value.trim().toLowerCase();
|
|
if (["true", "1", "yes", "on"].includes(s)) return true;
|
|
if (["false", "0", "no", "off"].includes(s)) return false;
|
|
}
|
|
return fallback;
|
|
}
|
|
|
|
function clamp(value: number, min: number, max: number): number {
|
|
return Math.min(max, Math.max(min, value));
|
|
}
|
|
|
|
/**
|
|
* Normalize directive attributes / YAML `data-config` into a usable config.
|
|
* Values may arrive as strings (directive attributes) or numbers/booleans
|
|
* (YAML `data-config`), so everything is coerced and clamped.
|
|
*/
|
|
export function normalizePrintConfig(
|
|
input: Partial<Record<keyof PrintConfig, unknown>> = {},
|
|
): PrintConfig {
|
|
return {
|
|
columns: Math.round(
|
|
clamp(toNumber(input.columns, PRINT_DEFAULTS.columns), 1, 4),
|
|
),
|
|
margin: clamp(toNumber(input.margin, PRINT_DEFAULTS.margin), 5, 40),
|
|
gap: clamp(toNumber(input.gap, PRINT_DEFAULTS.gap), 0, 20),
|
|
font: clamp(toNumber(input.font, PRINT_DEFAULTS.font), 2, 6),
|
|
title:
|
|
typeof input.title === "string" ? input.title : PRINT_DEFAULTS.title,
|
|
pageNumbers: toBoolean(input.pageNumbers, PRINT_DEFAULTS.pageNumbers),
|
|
timestamp: toBoolean(input.timestamp, PRINT_DEFAULTS.timestamp),
|
|
cutMarks: toBoolean(input.cutMarks, PRINT_DEFAULTS.cutMarks),
|
|
};
|
|
}
|