Отлично, давайте переработаем структуру и логику, чтобы конечные результаты выглядели именно так, как вы описали: выделены жирным шрифтом и находятся на том же уровне, что и предшествующее условие, без возможности добавлять дочерние узлы или параллельные ветки, если уже есть результат.
Мы изменим модель данных: узел, который является "ответом" или "ветвью", теперь может содержать свой finalProduct (строку с названием средства). Если finalProduct задан, то у этого узла не может быть children.
Вот обновленный код:
<!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[type="text"] {padding: 4px; width: 250px;}
#controls button {padding: 6px 10px; margin-right: 4px; white-space: nowrap;}
ul, li {list-style: none; margin: 0; padding-left: 20px;}
/* Основной узел ветви */
.node>.label {cursor: pointer; user-select: none; padding: 2px 4px; display: inline-block;}
.selected>.label {background: #c2dbff;}
/* Иконки для узлов */
.node>.label::before {content: "▶"; display: inline-block; width: 1em; color: #555;}
.node.open>.label::before {content: "▼";}
/* Стили для конечных узлов (листьев) */
.node.leaf>.label::before {content: "•"; color: #999;} /* Для обычных листьев, не являющихся продуктом */
/* Скрытие дочерних элементов по умолчанию */
.node ul {display: none;}
.node.open>ul {display: block;}
/* Стиль для текста конечного продукта */
.final-product-text {
font-weight: bold;
margin-left: 5px; /* Небольшой отступ от текста условия */
color: #000; /* Цвет жирного текста, если нужен другой */
}
/* Узел, у которого есть конечный продукт, не должен иметь стрелку разворачивания */
.node.has-product>.label::before {
content: "•"; /* Или можно убрать вообще: content: ""; display: none; */
color: #999;
}
.node.has-product.open>.label::before {
content: "•"; /* Сохраняем "точку" даже при попытке открыть */
}
</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="deleteNode" disabled>Удалить ветвь</button>
<button id="toggleProduct" 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)));
// После рендера, если узел был выбран, восстановим его выделение
if (selectedNodeId) {
const selectedLi = container.querySelector(`[data-id="${selectedNodeId}"]`);
if (selectedLi) {
selectedLi.classList.add('selected');
// Если выбранный узел был открыт, убедимся, что он развернут
if (findNode(treeData, selectedNodeId) && !findNode(treeData, selectedNodeId).finalProduct && findNode(treeData, selectedNodeId).children.length) {
selectedLi.classList.add('open');
}
// Обновим состояние кнопок после рендера
updateControlButtons();
}
} else {
// Если ничего не выбрано, кнопки деактивированы
updateControlButtons();
}
}
function createNodeElement(node) {
const li = document.createElement('li');
li.className = 'node';
li.dataset.id = node.id;
const label = document.createElement('span');
label.className = 'label';
label.textContent = node.text; // Это текст условия/ответа на ветке
li.appendChild(label);
// Если узел содержит конечный продукт
if (node.finalProduct) {
const productSpan = document.createElement('span');
productSpan.className = 'final-product-text';
productSpan.textContent = `: ${node.finalProduct}`;
li.appendChild(productSpan);
li.classList.add('has-product'); // Добавляем класс для стилизации
li.classList.add('leaf'); // Визуально это всегда лист
} else if (node.children.length === 0) {
// Если узел не имеет продукта и не имеет детей, это обычный лист
li.classList.add('leaf');
}
label.onclick = e => {
e.stopPropagation();
// Снятие выделения со всех узлов и выделение текущего
document.querySelectorAll('.selected').forEach(el => el.classList.remove('selected'));
li.classList.add('selected');
selectedNodeId = node.id;
updateControlButtons(); // Обновление состояния кнопок
// Разворачивание/сворачивание, только если узел не является продуктом и имеет детей
if (!node.finalProduct && node.children.length) {
li.classList.toggle('open');
}
};
label.ondblclick = e => {
e.stopPropagation();
const newText = prompt('Изменить текст ветви:', node.text);
if (newText && newText.trim()) {
node.text = newText.trim();
renderTree();
}
};
// Рендер дочерних элементов только если узел не является продуктом
if (!node.finalProduct && node.children.length) {
const ul = document.createElement('ul');
node.children.forEach(child => ul.appendChild(createNodeElement(child)));
li.appendChild(ul);
// Если узел был открыт до рендера, сохраняем это состояние
const originalNode = findNode(treeData, node.id);
if (originalNode && originalNode.isOpen) { // Добавим свойство isOpen в модель данных при сохранении/загрузке
li.classList.add('open');
}
}
return li;
}
// Вспомогательная функция для обновления состояния кнопок
function updateControlButtons() {
const selectedNode = findNode(treeData, selectedNodeId);
document.getElementById('addChild').disabled = !selectedNode || selectedNode.finalProduct;
document.getElementById('deleteNode').disabled = !selectedNode;
const toggleProductButton = document.getElementById('toggleProduct');
if (!selectedNode) {
toggleProductButton.disabled = true;
toggleProductButton.textContent = 'Добавить/Удалить продукт';
} else {
// Добавить/Удалить продукт можно только для узлов, у которых нет детей
toggleProductButton.disabled = selectedNode.children.length > 0;
toggleProductButton.textContent = selectedNode.finalProduct ? 'Удалить продукт' : 'Добавить продукт';
}
}
function findNode(arr, id) {
for (const node of arr) {
if (node.id === id) return node;
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 (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: [],
finalProduct: undefined // По умолчанию нет продукта
});
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 && !parent.finalProduct) { // Добавляем дочерний узел только если родитель не является продуктом
parent.children.push({
id: ++idCounter,
text: text,
children: [],
finalProduct: undefined
});
document.getElementById('nodeText').value = '';
renderTree();
} else if (parent && parent.finalProduct) {
alert('Нельзя добавить подветвь к узлу, который уже является конечным продуктом.');
}
};
document.getElementById('toggleProduct').onclick = () => {
if (!selectedNodeId) return;
const node = findNode(treeData, selectedNodeId);
if (node) {
if (node.children.length > 0) {
alert('Нельзя добавить или удалить продукт для узла, у которого есть дочерние ветви. Сначала удалите их.');
return;
}
if (node.finalProduct) {
// Удаляем продукт
delete node.finalProduct;
} else {
// Добавляем продукт
const productText = prompt('Введите название косметического средства:', node.text);
if (productText && productText.trim()) {
node.finalProduct = productText.trim();
} else {
return; // Если пользователь отменил или ввел пустоту
}
}
renderTree();
}
};
document.getElementById('deleteNode').onclick = () => {
if (!selectedNodeId) return;
if (!confirm('Удалить выбранную ветвь и все ее содержимое?')) return;
deleteNode(treeData, selectedNodeId);
selectedNodeId = null; // Сбрасываем выбранный узел
renderTree(); // Перерисовываем дерево
};
// Сериализация/десериализация дерева
function collectTreeState(nodes) {
return nodes.map(node => {
const stateNode = {
id: node.id,
text: node.text,
};
if (node.finalProduct !== undefined) {
stateNode.finalProduct = node.finalProduct;
}
// Сохраняем состояние раскрытия только для узлов-условий
if (!node.finalProduct && node.children.length) {
const liElement = document.querySelector(`[data-id="${node.id}"]`);
if (liElement) {
stateNode.isOpen = liElement.classList.contains('open');
}
}
stateNode.children = collectTreeState(node.children);
return stateNode;
});
}
document.getElementById('saveTree').onclick = () => {
const dataToSave = collectTreeState(treeData);
const blob = new Blob([JSON.stringify(dataToSave, null, 2)], {type: 'application/json'});
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'cosmetic_algorithm.json';
a.click();
};
document.getElementById('loadFile').onchange = e => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = event => {
try {
treeData = JSON.parse(event.target.result);
idCounter = Math.max(...getAllIds(treeData), 0);
selectedNodeId = null;
renderTree();
} catch (err) {
alert('Ошибка чтения файла: ' + err.message);
console.error(err);
}
};
reader.readAsText(file);
};
function getAllIds(arr) {
let ids = [];
for (const node of arr) {
ids.push(node.id);
ids = ids.concat(getAllIds(node.children));
}
return ids;
}
// Пример начального дерева с новой структурой
treeData = [
{
id: ++idCounter,
text: "Тип кожи", // Условие/вопрос
children: [
{
id: ++idCounter,
text: "Жирная кожа", // Ответ/ветвь
children: [
{
id: ++idCounter,
text: "С акне", // Условие/ветвь
children: [],
finalProduct: "Крем с салициловой кислотой 2% и азелаиновой" // Продукт для этой ветви
},
{
id: ++idCounter,
text: "Без акне", // Условие/ветвь
children: [],
finalProduct: "Матирующая сыворотка с ниацинамидом" // Продукт для этой ветви
}
],
finalProduct: undefined // У этой ветви нет продукта, она ведет к другим условиям
},
{
id: ++idCounter,
text: "Сухая кожа", // Ответ/ветвь
children: [],
finalProduct: "Питательный крем с церамидами и скваланом" // Продукт для этой ветви
},
{
id: ++idCounter,
text: "Чувствительная кожа", // Ответ/ветвь
children: [
{
id: ++idCounter,
text: "С покраснениями",
children: [],
finalProduct: "Гель для умывания с алоэ и успокаивающий тоник"
}
],
finalProduct: undefined
}
]
}
];
renderTree();
</script>
</body>
</html>
Ключевые изменения:
-
Модель данных:
- У каждого узла теперь есть необязательное свойство
finalProduct (строка). Если оно присутствует, значит, этот узел является конечной точкой, и его children должны быть пустыми.
- Убрано свойство
type (condition/result) из модели данных, так как теперь это определяется наличием finalProduct.
-
Отображение (createNodeElement):
- Текст ветви (ответа) (
node.text) и, если есть, текст продукта (node.finalProduct) теперь отображаются в одном элементе <li> на одном уровне.
- Для текста продукта создается отдельный
<span> с классом final-product-text для стилизации (жирный шрифт).
- Узлы, имеющие
finalProduct, получают класс has-product и leaf.
- Иконка
▶ (развернуть) теперь не отображается для узлов, которые являются конечными продуктами (показывается •).
-
Логика добавления/удаления:
- Кнопка "Добавить/Удалить продукт" (
toggleProduct) теперь позволяет переключать наличие finalProduct для выбранного узла.
- Эта кнопка отключается, если у выбранного узла уже есть дочерние элементы (
children.length > 0). Это предотвращает ситуацию, когда узел одновременно является и продуктом, и имеет дочерние ветви.
- Кнопка "Добавить подветвь" (
addChild) отключается, если выбранный родительский узел имеет finalProduct. Это гарантирует, что к узлу-продукту нельзя добавить новые ветви.
-
Сохранение/Загрузка:
- Функция
collectTreeState теперь корректно сохраняет finalProduct.
- Добавлено сохранение состояния
isOpen для узлов-условий, чтобы при загрузке дерево разворачивалось, как было.
Теперь вы можете строить дерево, где каждая "ветвь" (node.text) может либо продолжаться дальнейшими условиями (children), либо сразу указывать на конкретное косметическое средство (finalProduct).