Skip to content

Instantly share code, notes, and snippets.

@lornajane
Created December 1, 2023 20:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lornajane/17e2f04bf33e54be26ab24e1420c7fa7 to your computer and use it in GitHub Desktop.
Save lornajane/17e2f04bf33e54be26ab24e1420c7fa7 to your computer and use it in GitHub Desktop.
Sidebar munging
const fs = require('fs');
const yaml = require('js-yaml');
const cheerio = require("cheerio");
const sidebars_file = "sidebars.yaml";
async function getTitle(url) {
await fetch(url)
.then(result => result.text())
.then(html => {
const $ = cheerio.load(html);
const title = $('title').text();
return title;
}).catch(error => {
console.log(error);
})
}
async function prepare (entry, groups) {
// construct the object
item = new Object();
item.page = entry.page ? entry.page : "";
item.groups = groups;
if(entry.page) {
// it's a page
item.type = "page";
item.label = entry.label ? entry.label : "";
if (entry.page.substr(-3) == ".md") {
const slug = entry.page.substr(0,entry.page.length-3);
item.url = entry.page ? "https://beta-docs.redocly.com/" + slug: "";
if (item.label == "") {
item.label = await getTitle("http://localhost:4000/" + slug + "/");
}
}
} else if (entry.group) {
// it's a group
item.type = "group";
item.label = entry.group ? entry.group : "-";
item.url = entry.page ? "https://beta-docs.redocly.com/" + entry.page : "";
} else if (entry.separator) {
item.type = "separator";
}
if( item.label == "" && entry.group) {
item.label = entry.group;
}
// build output string
if(item.type == "page" || item.type == "group") {
console.log(
item.label
+ ", " + item.type
+ ", " + item.page
+ ", " + item.url
+ ", " + item.groups.join(",")
);
}
if(entry.items) {
let new_groups = Array.from(groups);
new_groups.push(entry.group);
process(entry.items, new_groups);
}
}
async function process(data, groups) {
if(data instanceof Array) {
data.forEach((entry) => {
prepare (entry, groups);
});
}
}
console.log(" > Sidebar started");
let rawdata = fs.readFileSync(sidebars_file);
let nav = yaml.load(rawdata);
process(nav, ["Main"]).then(() => {
console.log(" > Sidebars managed");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment