Мне нужно чтобы конечный результат был выделен только жирным цветом и он был изображен на том же уровне, что и само условие, а не в раскрывающемся списке, так как при наличии результата не должно быть раскрывающегося списка вообще и нельзя было добавлять с ним параллельно другие узлы
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Понял вашу задачу. Вот исправленная версия, где конечный результат отображается на том же уровне, что и условие, без вложенности:
html
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Конструктор алгоритма косметического средства</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
h2 { margin-top: 0; }
#controls { margin-bottom: 14px; }
#controls input { padding: 4px; width: 250px; }
#controls button { padding: 6px 10px; margin-right: 4px; cursor: pointer; }
#controls button:disabled { cursor: not-allowed; opacity: 0.6; }
ul, li { list-style: none; margin: 0; padding-left: 20px; }
.node > .label {
cursor: pointer;
user-select: none;
padding: 2px 4px;
display: inline-block;
border-radius: 3px;
}
.selected > .label { background: #c2dbff; }
.node > .label::before {
content: "▶";
display: inline-block;
width: 1em;
color: #555;
}
.node.open > .label::before { content: "▼"; }
/* Стиль для результата (просто жирный текст) */
.result {
font-weight: bold;
margin-left: 10px;
}
.node ul { display: none; }
.node.open > ul { display: block; }
</style>
</head>
<body>
<h2>Конструктор алгоритма определения косметического средства</h2>
<div id="controls">
<input type="text" id="nodeText" placeholder="Текст узла / Название продукта">
<button id="addRoot">Добавить корневой узел</button>
<button id="addChild" disabled>Добавить дочерний узел</button>
<button id="addResult" disabled>Добавить результат</button>
<button id="deleteNode" disabled>Удалить узел</button>
<button id="saveTree">Сохранить JSON</button>
<input type="file" id="loadFile" accept=".json" style="margin-left: 10px;">
</div>
<div id="treeContainer"></div>
<script>
let treeData = [];
let selectedNodeId = null;
let idCounter = 0;
function renderTree() {
const container = document.getElementById('treeContainer');
container.innerHTML = '';
treeData.forEach(node => container.appendChild(createNodeElement(node)));
updateButtonStates();
}
function createNodeElement(node) {
const li = document.createElement('li');
li.dataset.id = node.id;
li.className = node.children?.length ? 'node open' : 'node';
const label = document.createElement('span');
label.className = 'label';
label.textContent = node.text;
li.appendChild(label);
// Если есть результат, добавляем его на том же уровне
if (node.result) {
const resultSpan = document.createElement('span');
resultSpan.className = 'result';
resultSpan.textContent = '→ ' + node.result;
li.appendChild(resultSpan);
}
label.onclick = e => {
e.stopPropagation();
document.querySelectorAll('.selected').forEach(el => el.classList.remove('selected'));
li.classList.add('selected');
selectedNodeId = node.id;
updateButtonStates();
// Разворачивать только если есть дочерние элементы и нет результата
if (!node.result && node.children?.length) {
li.classList.toggle('open');
}
};
label.ondblclick = e => {
e.stopPropagation();
const newText = prompt('Изменить текст узла:', node.text);
if (newText?.trim()) {
node.text = newText.trim();
renderTree();
}
};
// Добавляем возможность редактировать результат по двойному клику
if (node.result) {
li.querySelector('.result').ondblclick = e => {
e.stopPropagation();
const newResult = prompt('Изменить результат:', node.result);
if (newResult?.trim()) {
node.result = newResult.trim();
renderTree();
}
};
}
if (node.children?.length && !node.result) {
const ul = document.createElement('ul');
node.children.forEach(child => ul.appendChild(createNodeElement(child)));
li.appendChild(ul);
}
return li;
}
function updateButtonStates() {
const selectedNode = selectedNodeId ? findNode(treeData, selectedNodeId) : null;
const hasResult = selectedNode?.result;
document.getElementById('deleteNode').disabled = !selectedNode;
document.getElementById('addChild').disabled = !selectedNode || hasResult;
document.getElementById('addResult').disabled = !selectedNode || hasResult;
}
function findNode(arr, id) {
for (const node of arr) {
if (node.id === id) return node;
if (node.children) {
const found = findNode(node.children, id);
if (found) return found;
}
}
return null;
}
function deleteNode(arr, id) {
for (let i = 0; i < arr.length; i++) {
if (arr[i].id === id) {
arr.splice(i, 1);
return true;
}
if (arr[i].children && deleteNode(arr[i].children, id)) {
return true;
}
}
return false;
}
document.getElementById('addRoot').onclick = () => {
const text = document.getElementById('nodeText').value.trim();
if (!text) return alert('Введите текст узла');
treeData.push({
id: ++idCounter,
text: text,
children: []
});
document.getElementById('nodeText').value = '';
renderTree();
};
document.getElementById('addChild').onclick = () => {
const text = document.getElementById('nodeText').value.trim();
if (!text) return alert('Введите текст узла');
if (!selectedNodeId) return;
const parent = findNode(treeData, selectedNodeId);
if (parent) {
if (parent.result) {
alert('Нельзя добавить дочерний узел к узлу с результатом');
return;
}
if (!parent.children) parent.children = [];
parent.children.push({
id: ++idCounter,
text: text,
children: []
});
document.getElementById('nodeText').value = '';
renderTree();
}
};
document.getElementById('addResult').onclick = () => {
const result = document.getElementById('nodeText').value.trim();
if (!result) return alert('Введите результат');
if (!selectedNodeId) return;
const node = findNode(treeData, selectedNodeId);
if (node) {
if (node.result) {
alert('У узла уже есть результат');
return;
}
node.result = result;
node.children = []; // Удаляем все дочерние элементы
document.getElementById('nodeText').value = '';
renderTree();
}
};
document.getElementById('deleteNode').onclick = () => {
if (!selectedNodeId) return;
if (!confirm('Удалить выбранный узел и все его подветки?')) return;
deleteNode(treeData, selectedNodeId);
selectedNodeId = null;
renderTree();
};
document.getElementById('saveTree').onclick = () => {
const blob = new Blob([JSON.stringify(treeData, null, 2)], {type: 'application/json'});
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'cosmetic_algorithm.json';
a.click();
URL.revokeObjectURL(a.href);
};
document.getElementById('loadFile').onchange = e => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = event => {
try {
const data = JSON.parse(event.target.result);
if (!Array.isArray(data)) throw new Error("Invalid format");
treeData = data;
idCounter = Math.max(...getAllIds(treeData), 0);
selectedNodeId = null;
renderTree();
} catch (err) {
alert('Ошибка чтения файла');
}
};
reader.readAsText(file);
e.target.value = '';
};
function getAllIds(arr) {
let ids = [];
for (const node of arr) {
ids.push(node.id);
if (node.children) {
ids = ids.concat(getAllIds(node.children));
}
}
return ids;
}
// Пример начального дерева
treeData = [
{
id: ++idCounter,
text: "Тип кожи: жирная?",
children: [
{
id: ++idCounter,
text: "Есть акне?",
result: "Сыворотка с салициловой кислотой"
},
{
id: ++idCounter,
text: "Нет акне",
result: "Легкий увлажняющий гель-крем"
}
]
},
{
id: ++idCounter,
text: "Тип кожи: сухая?",
result: "Питательный крем с церамидами"
}
];
renderTree();
</script>
</body>
</html>
Основные изменения:
Результат теперь отображается на том же уровне, что и условие
При добавлении результата удаляются все дочерние элементы
Нельзя добавлять дочерние элементы к узлу с результатом
Упрощен внешний вид - результат выделяется только жирным шрифтом
Двойной клик по результату позволяет его редактировать
Структура данных изменена - теперь результат хранится в свойстве result узла
Теперь дерево выглядит более логично и соответствует вашим требованиям. Каждый узел либо имеет дочерние элементы, либо результат, но не может иметь оба варианта одновременно.