tree.js
1.4 kB · javascript · 47 lines
1import site from './site.js';23const ROUTE = { demos: '/demos/' };4const ID = `${site.prefix}tree`;5const FILE = '/demos/tree.json';67let shelves = null;89function block() {10 const el = typeof document === 'undefined' ? null : document.getElementById(ID);11 return el ? JSON.parse(el.textContent) : null;12}1314export function ready() {15 if (!shelves) shelves = block();16 return !!shelves;17}1819export function demos() {20 return ready() ? shelves : [];21}2223export async function load() {24 if (!ready()) shelves = await fetch(FILE).then((r) => r.json());25 return shelves;26}2728export function tree(lists = {}) {29 const filled = { demos: demos(), ...lists };30 return site.tree.map(({ fill, ...node }) => {31 const key = fill ?? node.name.toLowerCase();32 const href = node.href ?? ROUTE[key];33 const nodes = filled[key];34 return nodes?.length ? { ...node, href, nodes } : { ...node, href };35 });36}3738const word = (href) => {39 const slug = href.split('/').filter(Boolean).pop() ?? '';40 return slug ? (slug[0].toUpperCase() + slug.slice(1)).replace(/-/g, ' ') : '';41};4243const flat = (nodes) => nodes.flatMap((node) => (node.nodes?.length ? flat(node.nodes) : node.href ? [{ name: word(node.href), href: node.href }] : []));4445export function sidebar(lists = {}) {46 return tree(lists).map(({ nodes, ...node }) => (nodes?.length ? { ...node, nodes: flat(nodes).sort((a, b) => a.name.localeCompare(b.name)) } : node));47}