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).
66 lines (65 loc) • 2.34 kB
JavaScript
import { mapObjectValues } from '@augment-vir/common';
import { isBookTreeNode } from '../../book-tree/book-tree.js';
import { BookEntryType } from '../book-entry-type.js';
/**
* Find the controls at the given breadcrumbs.
*
* @category Internal
*/
export function traverseControls(controlsWrapper, fullUrlBreadcrumbs) {
return traverseAndInsertNewControls(controlsWrapper, [
/** Empty string represents the breadcrumb for the root node */
'',
...fullUrlBreadcrumbs,
], undefined);
}
function traverseAndInsertNewControls(controlsWrapper, urlBreadcrumbs, newValues) {
const nextBreadcrumbs = urlBreadcrumbs.slice(1);
const nextBreadcrumb = nextBreadcrumbs[0];
/** If we're at the end of the breadcrumbs, then it's time to insert the new controls. */
if (!nextBreadcrumb && newValues) {
controlsWrapper.controls = newValues;
}
const childControlsWrapper = controlsWrapper.children[nextBreadcrumb || ''];
const childrenControls = childControlsWrapper &&
traverseAndInsertNewControls(childControlsWrapper, nextBreadcrumbs, newValues);
const allControls = {
...controlsWrapper.controls,
...childrenControls,
};
return allControls;
}
/**
* Add new controls at the given breadcrumbs.
*
* @category Internal
*/
export function createNewControls(controlsWrapper, breadcrumbsForNewValue, newValues) {
const newControls = { ...controlsWrapper };
traverseAndInsertNewControls(newControls, [
/** Empty string represents the breadcrumb for the root node */
'',
...breadcrumbsForNewValue,
], newValues);
return newControls;
}
/**
* Add new controls from the given tree node.
*
* @category Internal
*/
export function updateTreeControls(node, existingControls) {
const controls = existingControls?.controls ||
(isBookTreeNode(node, BookEntryType.Page)
? mapObjectValues(node.entry.controls, (name, setup) => {
return setup.initValue;
})
: {});
const controlsWrapper = {
children: mapObjectValues(node.children, (childName, childTreeNode) => {
return updateTreeControls(childTreeNode, existingControls?.children?.[childTreeNode.urlBreadcrumb]);
}),
controls,
};
return controlsWrapper;
}