11/**
22 * So we need the files to be in a hierarchy based off of depth, but they're
3- * given to us flattened. So, let's fix that in a way that's incredibly
4- * unfortunate but works!
5- * @param {ApiDocMetadataEntry[] } entries
6- * @returns {import('../types.d.ts').HierarchizedEntry[] }
3+ * given to us flattened. So, let's fix that.
4+ *
5+ * Assuming that {@link entries} is in the same order as the elements are in
6+ * the markdown, we can use the entry's depth property to reassemble the
7+ * hierarchy.
8+ *
9+ * If depth <= 1, it's a top-level element (aka a root).
10+ *
11+ * If it's depth is greater than the previous entry's depth, it's a child of
12+ * the previous entry. Otherwise (if it's less than or equal to the previous
13+ * entry's depth), we need to find the entry that it was the greater than. We
14+ * can do this by just looping through entries in reverse starting at the
15+ * current index - 1.
16+ *
17+ * @param {Array<ApiDocMetadataEntry> } entries
18+ * @returns {Array<import('../types.d.ts').HierarchizedEntry> }
719 */
820export function buildHierarchy ( entries ) {
921 const roots = [ ] ;
@@ -12,7 +24,8 @@ export function buildHierarchy(entries) {
1224 const entry = entries [ i ] ;
1325 const currentDepth = entry . heading . depth ;
1426
15- if ( currentDepth === 1 ) {
27+ // We're a top-level entry
28+ if ( currentDepth <= 1 ) {
1629 roots . push ( entry ) ;
1730 continue ;
1831 }
@@ -27,10 +40,12 @@ export function buildHierarchy(entries) {
2740 }
2841 previousEntry . hierarchyChildren . push ( entry ) ;
2942 } else {
43+ // Loop to find the entry we're a child of
3044 for ( let j = i - 2 ; j >= 0 ; j -- ) {
3145 const jEntry = entries [ j ] ;
3246 const jDepth = jEntry . heading . depth ;
3347 if ( currentDepth > jDepth ) {
48+ // Found it
3449 jEntry . hierarchyChildren . push ( entry ) ;
3550 break ;
3651 }
0 commit comments