UNPKG

element-book

Version:

An [`element-vir`](https://npmjs.com/package/element-vir) drop-in element for building, testing, and demonstrating a collection of elements (or, in other words, a design system).

78 lines (77 loc) 2.82 kB
/** * Checks and type guards that the input page control init is of the given type. * * @category Internal */ export function isControlInitType(controlInit, specificType) { return controlInit.controlType === specificType; } /** * Define a page control. This doesn't do anything fancy (in fact it only returns the input) but it * helps immensely with type inference. * * @category Main */ export function definePageControl(controlInit) { return controlInit; } /** * All the supported page control types. One of these must be chosen when defining a page control. * * @category Main */ export var BookPageControlType; (function (BookPageControlType) { BookPageControlType["Checkbox"] = "checkbox"; BookPageControlType["Color"] = "color"; /** Custom controls render user-provided HTML directly. They have no editable value. */ BookPageControlType["Custom"] = "custom"; BookPageControlType["Dropdown"] = "dropdown"; /** Hidden controls allow any values but they aren't displayed to the user for editing. */ BookPageControlType["Hidden"] = "hidden"; BookPageControlType["Number"] = "number"; BookPageControlType["Text"] = "text"; })(BookPageControlType || (BookPageControlType = {})); const anySymbol = Symbol('any-type'); /** * Specifies the default value for each page control type, as well as its type. * * @category Internal */ export const controlValueTypes = { [BookPageControlType.Checkbox]: false, [BookPageControlType.Color]: '', /** Custom controls don't have a user-editable value. */ [BookPageControlType.Custom]: undefined, [BookPageControlType.Dropdown]: '', [BookPageControlType.Hidden]: anySymbol, [BookPageControlType.Number]: 0, [BookPageControlType.Text]: '', }; /** * Checks that the given control init object is valid. * * @category Internal */ export function checkControls(controlsInit, pageName) { if (!controlsInit) { return []; } const errors = []; Object.entries(controlsInit).forEach(([controlName, controlEntry,]) => { if (controlEntry.controlType === BookPageControlType.Custom) { return; } const expectedInitDefault = controlValueTypes[controlEntry.controlType]; if (expectedInitDefault === anySymbol) { return; } if (typeof expectedInitDefault !== typeof controlEntry.initValue) { errors.push(new Error(`Control '${controlName}' in page '${pageName}' has invalid initValue '${controlEntry.initValue}': expected initValue of type ${typeof expectedInitDefault} because the control is of type ${controlEntry.controlType}.`)); } if (!controlName) { errors.push(new Error(`'${pageName}' cannot have an empty control name.`)); } }); return errors; }