From 3ce6a91e6e96e53ad0c6669d9587c5c1f9c48fa6 Mon Sep 17 00:00:00 2001 From: Yisroel Baum Date: Sat, 18 Apr 2026 22:07:38 +0300 Subject: [PATCH] add and save button functionality --- public/js/text.js | 53 ++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 50 insertions(+), 3 deletions(-) diff --git a/public/js/text.js b/public/js/text.js index 8f7b72e..fc62744 100644 --- a/public/js/text.js +++ b/public/js/text.js @@ -43,15 +43,62 @@ function buildTree(nodes) { return roots; } -function renderTree(nodes) { +function renderTree(nodes, textId) { const ul = document.createElement('ul'); nodes.forEach(node => { const li = document.createElement('li'); - li.textContent = node.title; + + const titleSpan = document.createElement('span'); + titleSpan.textContent = node.title; + li.appendChild(titleSpan); + + const addBtn = document.createElement('button'); + addBtn.textContent = 'Add child'; + addBtn.className = 'add-child'; + addBtn.addEventListener('click', () => toggleAddForm(li, node.id, textId)); + li.appendChild(addBtn); + if (node.children.length > 0) { - li.appendChild(renderTree(node.children)); + li.appendChild(renderTree(node.children, textId)); } + ul.appendChild(li); }); return ul; } + +function toggleAddForm(li, parentNodeId, textId) { + const existing = li.querySelector('input.child-title'); + if (existing) { + existing.remove(); + li.querySelector('button.save-child').remove(); + return; + } + + const input = document.createElement('input'); + input.type = 'text'; + input.className = 'child-title'; + input.placeholder = 'Node title'; + + const saveBtn = document.createElement('button'); + saveBtn.textContent = 'Save'; + saveBtn.className = 'save-child'; + saveBtn.addEventListener('click', () => { + const title = input.value.trim(); + if (!title) return; + + fetch('/api/nodes', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ textId: parseInt(textId), title, parentNodeId }), + }) + .then(res => { + if (!res.ok) throw new Error('Failed to create node'); + return res.json(); + }) + .then(() => fetchAndRenderNodes(textId)); + }); + + li.appendChild(input); + li.appendChild(saveBtn); +}