wikijs-metabot/metapage.js.html

89 lines
2.8 KiB
HTML

<script>
// https://git.ctdo.de/ctdo/wikijs-metabot/
async function graphql(query) {
const res = await fetch('/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ query }),
});
return await res.json();
}
async function loadPageLists() {
console.log('populating page lists');
const pagelists = [...document.getElementsByClassName('pagelist')];
pagelists.forEach(async (element) => {
console.log('processing', element);
const parameters = element
.getAttribute('data-query')
.replaceAll("'", '"');
const query = `query { pages { list(${parameters}) { path, title } } }`;
const result = await graphql(query);
console.log({ query, result });
const pages = result.data.pages.list.filter(
(page) => !page.path.includes('/_')
);
appendLinks(pages, element);
});
}
async function loadSubpageLists(parentId) {
console.log('populating subpage lists');
const pagelists = [...document.getElementsByClassName('subpagelist')];
pagelists.forEach(async (element) => {
console.log('processing', element);
/* currently not working, GraphQL gives wrong ID
// get page id from the given page
const parameters = element.getAttribute('data-query');
let query = `query { pages { singleByPath(path:"${parameters}", locale: "de") {id, path, title } }}`;
let result = await graphql(query);
console.log({ query, result });
*/
//const pageId = result.data.pages.singleByPath.id;
let pageId = element.getAttribute('data-page-id');
const query = `query { pages { tree(parent: ${pageId}, mode: ALL, locale: "de") { id, path, title } } }`;
const result = await graphql(query);
console.log({ query, result });
const pages = result.data.pages.tree.filter(
(page) => !page.path.includes('/_')
);
appendLinks(pages, element);
});
}
function appendLinks(pages, element) {
const pagelist = pages.map((page) => {
const link = document.createElement('a');
link.href = `/${page.path}`;
link.classList.add('is-internal-link');
link.classList.add('is-valid-page');
link.textContent = page.title;
const listItem = document.createElement('li');
listItem.appendChild(link);
return listItem;
});
pagelist.forEach((page) => element.appendChild(page));
}
async function isElementLoaded(selector) {
while (document.querySelector(selector) === null) {
await new Promise((resolve) => requestAnimationFrame(resolve));
}
return document.querySelector(selector);
}
isElementLoaded('.contents').then(() => {
loadPageLists();
loadSubpageLists();
});
</script>