directory-list
by Allie Yu
CSS
body {
color: #c7c7c7;
font-size: 14px;
font-family: monospace;
background-color: #252526;
}
ul {
list-style: none;
}
li:not([data-type]) {
cursor: pointer;
}
li[data-type] {
cursor: default;
}
li[data-type="css"] {
color: #5097b7;
}
li[data-type="js"] {
color: #bcbc3e;
}
li[data-type="html"] {
color: #b2632f;
}
li li {
display: none;
}
li.open > ul > li {
display: list-item;
}
li::before {
content: 'â–¸';
font-size: 20px;
font-weight: bold;
display: inline-block;
width: 1em;
margin-left: -1em;
}
li.open:not([data-type])::before {
color: #e8e8e8;
transform: rotate(45deg) translate(5px, 5px);
}
JavaScript
const json =
[{
"type": "folder",
"name": "app",
"children": [
{
"type": "folder",
"name": "css",
"children": [
{
"type": "folder",
"name": "lib",
},
{
"type": "file",
"name": "about.css"
}
]
},
{
"type": "folder",
"name": "img",
},
{
"type": "folder",
"name": "js",
"children": [
{
"type": "folder",
"name": "config",
"children": [
{
"type": "file",
"name": "language.en.js"
}
]
},
{
"type": "folder",
"name": "lib",
"children": [
{
"type": "file",
"name": "brain.js"
}
]
},
{
"type": "file",
"name": "about.js"
}
]
},
{
"type": "folder",
"name": "views",
"children": [
{
"type": "file",
"name": "about.html"
}
]
},
{
"type": "file",
"name": "index.html"
}
]
}]
function get_html_tree(json) {
let html = '<ul>'
for (const obj of json) {
const { type, name, children } = obj
if (type == 'file')
html += `<li data-type="${name.split('.').pop()}">${name}</li>`
else {
html += `<li>${name}`
if (children) html += `${get_html_tree(children)}</li>`
}
}
return `${html}</ul>`
}
document.body.innerHTML = get_html_tree(json)
document.querySelector('li').onclick = e => e.target.classList.toggle('open')