add parsing functions for nodes of text to create indented tree
This commit is contained in:
parent
a092ee8840
commit
49140195f1
1 changed files with 42 additions and 1 deletions
|
|
@ -4,6 +4,47 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||||
fetch('/api/texts/' + textId)
|
fetch('/api/texts/' + textId)
|
||||||
.then(res => res.json())
|
.then(res => res.json())
|
||||||
.then(text => {
|
.then(text => {
|
||||||
document.getElementById('text-detail').textContent = text.name;
|
const h1 = document.createElement('h1');
|
||||||
|
h1.textContent = text.name;
|
||||||
|
document.getElementById('text-detail').appendChild(h1);
|
||||||
|
|
||||||
|
return fetch('/api/texts/' + textId + '/nodes');
|
||||||
|
})
|
||||||
|
.then(res => res.json())
|
||||||
|
.then(nodes => {
|
||||||
|
const tree = buildTree(nodes);
|
||||||
|
const ul = renderTree(tree);
|
||||||
|
document.getElementById('text-detail').appendChild(ul);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
function buildTree(nodes) {
|
||||||
|
const map = {};
|
||||||
|
nodes.forEach(node => {
|
||||||
|
map[node.id] = { ...node, children: [] };
|
||||||
|
});
|
||||||
|
|
||||||
|
const roots = [];
|
||||||
|
nodes.forEach(node => {
|
||||||
|
if (node.parentNodeId === null) {
|
||||||
|
roots.push(map[node.id]);
|
||||||
|
} else if (map[node.parentNodeId]) {
|
||||||
|
map[node.parentNodeId].children.push(map[node.id]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return roots;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderTree(nodes) {
|
||||||
|
const ul = document.createElement('ul');
|
||||||
|
nodes.forEach(node => {
|
||||||
|
const li = document.createElement('li');
|
||||||
|
li.textContent = node.title;
|
||||||
|
if (node.children.length > 0) {
|
||||||
|
li.appendChild(renderTree(node.children));
|
||||||
|
}
|
||||||
|
ul.appendChild(li);
|
||||||
|
});
|
||||||
|
return ul;
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue