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).
71 lines (70 loc) • 2.46 kB
JavaScript
/**
* Checks and type guards that the input page control init is of the given type.
*
* @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";
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]: '',
[BookPageControlType.Dropdown]: '',
[BookPageControlType.Hidden]: anySymbol,
[BookPageControlType.Number]: 0,
[BookPageControlType.Text]: '',
};
/**
* Checks that the given control init object is valid.
*
* @internal
*/
export function checkControls(controlsInit, pageName) {
if (!controlsInit) {
return [];
}
const errors = [];
Object.entries(controlsInit).forEach(([controlName, controlEntry,]) => {
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;
}