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).
62 lines (61 loc) • 2.48 kB
JavaScript
import { combineErrors, extractErrorMessage } from '@augment-vir/common';
import { html, renderIf } from 'element-vir';
import { unsetInternalState } from '../../../../data/unset.js';
import { BookError } from '../../common/book-error.element.js';
import { defineBookElement } from '../../define-book-element.js';
export const BookElementExampleViewer = defineBookElement()({
tagName: 'book-element-example-viewer',
state() {
return {
isUnset: unsetInternalState,
};
},
render({ state, inputs, updateState }) {
try {
if (inputs.elementExampleNode.entry.errors.length) {
throw combineErrors(inputs.elementExampleNode.entry.errors);
}
if (
/** This is a check to make sure the input entry _does_ match the expected type. */
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
!inputs.elementExampleNode.entry.render ||
typeof inputs.elementExampleNode.entry.render === 'string') {
throw new Error(`Failed to render example '${inputs.elementExampleNode.entry.title}': render is not a function`);
}
if (state.isUnset === unsetInternalState) {
updateState({
isUnset: undefined,
...inputs.elementExampleNode.entry.state?.(),
});
}
const output = inputs.elementExampleNode.entry.render({
state,
updateState,
controls: inputs.currentPageControls,
});
if (output instanceof Promise) {
throw new TypeError('render output cannot be a promise');
}
return html `
${renderIf(!!inputs.elementExampleNode.entry.styles, html `
<style>
${inputs.elementExampleNode.entry.styles}
</style>
`)}
${output}
`;
}
catch (error) {
console.error('ERROR HERE', extractErrorMessage(error));
console.error(error);
return html `
<${BookError.assign({
message: `${inputs.elementExampleNode.entry.title} failed: ${extractErrorMessage(error)}`,
})}></${BookError}>
`;
}
},
options: {
allowPolymorphicState: true,
},
});