JSFiddle - React, Tailwind, and code Playground
HTML
Create dir tree: <br />
<div>
<input id="p_name" value="Project Name" />
</div>
<div>
<ul id='tree' class='tree'></ul>
</div>
<hr />
<div>
<p>Output:</p><br />
<pre id='out' cols='50' rows='20'></pre>
</div>
<div class='hidden' id='template'>
<ul>
<li class='tree-node'><input value='filename' />
<span class='controls'>
»
<a href='#' data-func='add-sibling' >+sibling</a> |
<a href='#' data-func='add-child'>+child</a> |
<a href='#' data-func='delete'>delete</a>
</span>
</li>
</ul>
</div>
CSS
ul.tree li {
list-style-type: disc;
margin-left: 2em;
}
.hidden {
display: none;
}
.controls {
display: none;
}
a:hover {
background-color: #ddd;
}
JavaScript
var prefix = "|-- ",
prefix_last = "`-- ",
spacer = "| ",
spacer_e = " ",
ul_template = $('#template > ul') ,
li_template = $('li', ul_template).first();
var action = {
"add-sibling" : function(obj) {
obj.after(li_template.clone());
},
"add-child" : function(obj) {
obj.append(ul_template.clone());
},
"delete" : function(obj) { obj.remove(); }
};
$(document).on('click', 'li.tree-node .controls > a', function() {
//console.log(this.getAttribute('data-func'));
action[this.getAttribute('data-func')]($(this).closest('li'));
rebuild_tree();
return false;
});
function get_subdir_text(obj, pad) {
var padding = pad || "",
out = "",
items = obj.children("li"),
last = items.length - 1;
items.each(function(index) {
var $this = $(this);
out += padding
+ ((index == last) ? prefix_last : prefix)
+ $this.children("input").val() + "\n";
var subdirs = $this.children("ul");
if (subdirs.length) {
out += get_subdir_text(subdirs,
padding + ((index == last) ? spacer_e : spacer ));
}
});
return out;
}
function rebuild_tree() {
$('#out').text($('#p_name').val()
+ "\n"
+ get_subdir_text($('#tree')));
}
$('#tree').append(li_template.clone());
$(document).on('keyup', '#tree input', rebuild_tree);
$('#p_name').on('keyup', rebuild_tree);
$('#tree').on('mouseover', 'li', function(e) {
$(this).children('.controls').show();
e.stopPropagation();
}).on('mouseout', 'li', function(e) {
$(this).children('.controls').hide();
e.stopPropagation();
});
rebuild_tree();