Skip to content
The Chat Archive
gemini-2.5-pro· Google LMArena Human Preference 140K

нужно чтобы можно было добавлять конечные точки в каждой ветви, в которых будет…

  1. User

    нужно чтобы можно было добавлять конечные точки в каждой ветви, в которых будет определено конечное косметическое средство как результат прохождения по всему дереву алгоритма - доработай программу:

    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;}
    
  2. Assistant

    Конечно, вот доработанная версия программы.

    Что было изменено:

    1. Структура данных узла: Узел теперь может содержать свойство product (строка). Если это свойство есть, узел считается конечной точкой (результатом). У таких узлов не может быть дочерних элементов.
    2. Новый интерфейс:
      • Добавлена кнопка "Добавить конечный продукт". Она позволяет добавить специальный узел-результат к выбранной ветке.
      • Поле для ввода теперь используется и для названий узлов-вопросов, и для названий конечных продуктов.
    3. Визуальное различие:
      • Конечные узлы-продукты выделяются зелёным цветом и имеют иконку "✔".
      • Они не могут быть "раскрыты", так как являются финальными в ветке.
    4. Логика:
      • При выборе узла-продукта кнопки "Добавить дочерний узел" и "Добавить конечный продукт" деактивируются, так как в результат нельзя ничего добавлять.
      • Двойной клик по узлу-продукту позволяет изменить название косметического средства. Двойной клик по обычному узлу, как и раньше, меняет его текст (вопрос/условие).
      • Функции сохранения в JSON и загрузки из него автоматически поддерживают новую структуру с полем product.

    Обновлённый код:

    Скопируйте и вставьте этот код в ваш 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; border: 1px solid transparent; }
        .selected > .label { background: #c2dbff; border-color: #99bfff; }
    
        /* Стили для обычных узлов */
        .node > .label::before { content: "▶"; display: inline-block; width: 1em; color: #555; }
        .node.open > .label::before { content: "▼"; }
        .node.leaf > .label::before { content: "•"; color: #999; } /* Обычный лист, не продукт */
    
        /* Стили для конечных узлов-продуктов */
        .product-node > .label {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
            font-weight: bold;
        }
        .product-node > .label::before {
            content: "✔"; /* Иконка для продукта */
            color: #155724;
            display: inline-block;
            width: 1em;
        }
    
        .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="addProduct" 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';
        if (node.product) {
            li.classList.add('product-node');
        } else if (node.children && node.children.length > 0) {
            li.classList.add('open'); // По умолчанию раскрываем узлы
        } else {
            li.classList.add('leaf');
        }
    
        const label = document.createElement('span');
        label.className = 'label';
        // Если узел - продукт, выводим его название
        if (node.product) {
            label.textContent = node.text + ": " + node.product;
        } else {
            label.textContent = node.text;
        }
        li.appendChild(label);
    
        label.onclick = e => {
            e.stopPropagation();
    
            // Снимаем выделение со всех узлов и выделяем текущий
            document.querySelectorAll('.selected').forEach(el => el.classList.remove('selected'));
            li.classList.add('selected');
            selectedNodeId = node.id;
            
            updateButtonStates();
    
            // Разворачивание/сворачивание только для не-продуктовых узлов
            if (!node.product && node.children && node.children.length) {
                li.classList.toggle('open');
            }
        };
    
        label.ondblclick = e => {
            e.stopPropagation();
            if (node.product) {
                // Редактируем название продукта
                const newProduct = prompt('Изменить название конечного продукта:', node.product);
                if (newProduct && newProduct.trim()) {
                    node.product = newProduct.trim();
                    renderTree();
                }
            } else {
                // Редактируем текст обычного узла
                const newText = prompt('Изменить текст узла:', node.text);
                if (newText && newText.trim()) {
                    node.text = newText.trim();
                    renderTree();
                }
            }
        };
    
        if (node.children && node.children.length) {
            const ul = document.createElement('ul');
            node.children.forEach(child => ul.appendChild(createNodeElement(child)));
            li.appendChild(ul);
        }
        
        // Если узел был выделен, сохраняем выделение после перерисовки
        if (node.id === selectedNodeId) {
            li.classList.add('selected');
        }
    
        return li;
    }
    
    function updateButtonStates() {
        const selectedNode = selectedNodeId ? findNode(treeData, selectedNodeId) : null;
        const isProductSelected = selectedNode && selectedNode.product;
    
        document.getElementById('deleteNode').disabled = !selectedNode;
        document.getElementById('addChild').disabled = !selectedNode || isProductSelected;
        document.getElementById('addProduct').disabled = !selectedNode || isProductSelected;
    }
    
    
    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, parentArr = null, index = -1) {
         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, arr[i], i)) {
                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.product) {
                alert('Нельзя добавить дочерний узел в конечный продукт.');
                return;
            }
            parent.children.push({
                id: ++idCounter,
                text: text,
                children: []
            });
            document.getElementById('nodeText').value = '';
            renderTree();
        }
    };
    
    document.getElementById('addProduct').onclick = () => {
        const productName = document.getElementById('nodeText').value.trim();
        if (!productName) return alert('Введите название конечного продукта');
        if (!selectedNodeId) return;
    
        const parent = findNode(treeData, selectedNodeId);
        if (parent) {
            if (parent.product) {
                alert('Нельзя добавить узел в конечный продукт.');
                return;
            }
            parent.children.push({
                id: ++idCounter,
                text: 'Результат', // Стандартный текст для узла-результата
                product: productName, // Название самого продукта
                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('Ошибка чтения файла. Убедитесь, что это корректный JSON-файл.');
            }
        };
        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: "Есть акне?", 
                    children: [
                        {
                            id: ++idCounter,
                            text: "Результат",
                            product: "Сыворотка с салициловой кислотой",
                            children: []
                        }
                    ]
                },
                {
                    id: ++idCounter,
                    text: "Результат",
                    product: "Легкий увлажняющий гель-крем",
                    children: []
                }
            ]
        },
        {
            id: ++idCounter,
            text: "Тип кожи: сухая?",
            children: [
                 {
                    id: ++idCounter,
                    text: "Результат",
                    product: "Питательный крем с церамидами",
                    children: []
                }
            ]
        }
    ];
    
    renderTree();
    </script>
    </body>
    </html>
    

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.