Satur@it-depot.ru 2025-03-06 13:17:44 +03:00
parent cbb5367d64
commit 822c2d4c94
1 changed files with 70 additions and 16 deletions

View File

@ -159,6 +159,19 @@
}
.header-logo { display: flex; align-items: center; }
.header-logo img { height: 50px; margin-right: 10px; }
#sort-folders-btn {
background: #007bff;
color: white;
border: 1px solid #007bff;
padding: 5px 10px;
border-radius: 3px;
cursor: pointer;
margin-left: 5px;
transition: background 0.2s ease;
}
#sort-folders-btn:hover {
background: #0056b3;
}
</style>
</head>
<body>
@ -166,6 +179,7 @@
<h2>Папки</h2>
<div id="folder-tree"></div>
<button onclick="addFolder()">Добавить папку</button>
<button id="sort-folders-btn" onclick="sortFolders()">Сортировать ⬆️</button>
</div>
<div id="installs-container">
<h1 class="header-logo">
@ -264,7 +278,7 @@
'core': {
'data': function (node, cb) {
$.getJSON(`${API_URL}/folders`, function (data) {
console.log("Loaded folders:", data); // Лог для отладки
console.log("Loaded folders:", data);
allFolders = data; // Сохраняем все папки
const treeData = [
{ id: "root", text: "Корень", parent: "#" }
@ -284,19 +298,35 @@
$('#folder-tree').jstree('select_node', unsortedFolder.id);
loadInstalls(unsortedFolder.id);
updateFolderActions();
}, 100); // Задержка для инициализации jstree
}, 100);
}
}).fail(function(jqxhr, textStatus, error) {
console.error("Error loading folders:", textStatus, error);
});
},
'check_callback': true
'check_callback': true,
'sort': function (a, b) {
// Сортировка по имени при загрузке
const nodeA = this.get_node(a);
const nodeB = this.get_node(b);
if (nodeA.parent === nodeB.parent && nodeA.parent === '#') {
return nodeA.text.localeCompare(nodeB.text);
}
return 0;
}
},
'plugins': ['dnd', 'html_data']
'plugins': ['dnd', 'html_data'],
'dnd': {
'is_draggable': true
}
}).on('select_node.jstree', function (e, data) {
selectedFolderId = data.node.id === "root" ? null : data.node.id;
loadInstalls(selectedFolderId);
updateFolderActions();
}).on('move_node.jstree', function (e, data) {
const movedNode = data.node;
const newParentId = movedNode.parent === '#' ? null : movedNode.parent;
saveFolderPosition(movedNode.id, newParentId);
});
// Обработчики для поиска и выбора папки
@ -337,7 +367,7 @@
function loadInstalls(folderId) {
$.getJSON(`${API_URL}/installs`, function (data) {
console.log("Loaded installs:", data); // Лог для отладки
console.log("Loaded installs:", data);
allInstalls = data;
let filtered = folderId ? data.filter(i => i.folder_id == folderId && i.folder_id !== null) : data;
displayInstalls(filtered);
@ -353,19 +383,17 @@
const query = $('#search-input').val().toLowerCase().trim();
const folderId = $('#folder-select').val() || '';
console.log("Search query:", query, "Folder ID:", folderId); // Логируем для отладки
console.log("Search query:", query, "Folder ID:", folderId);
let filteredInstalls = [...allInstalls]; // Копируем массив, чтобы не изменять оригинал
let filteredInstalls = [...allInstalls];
// Фильтрация по папке, исключая удаленные или несуществующие папки
if (folderId) {
filteredInstalls = filteredInstalls.filter(i =>
i.folder_id == folderId &&
allFolders.some(f => f.id === i.folder_id) // Проверяем, существует ли папка
allFolders.some(f => f.id === i.folder_id)
);
}
// Фильтрация по запросу (по rust_id и computer_name)
if (query) {
filteredInstalls = filteredInstalls.filter(i =>
i.rust_id.toLowerCase().trim().includes(query) ||
@ -373,11 +401,11 @@
);
}
sortInstalls(null, filteredInstalls); // Сортируем и отображаем результаты
sortInstalls(null, filteredInstalls);
}
function displayInstalls(installs) {
console.log("Displaying installs:", installs); // Логируем для отладки
console.log("Displaying installs:", installs);
if (installs.length === 0) {
$('#installs-list').html('<p>Нет результатов</p>');
} else {
@ -443,7 +471,7 @@
contentType: 'application/json',
data: JSON.stringify({ name, parent_id: selectedFolderId }),
success: function () {
loadFolders(); // Обновляем список папок
loadFolders();
$('#folder-tree').jstree(true).refresh();
}
});
@ -459,7 +487,7 @@
contentType: 'application/json',
data: JSON.stringify({ name: newName }),
success: function () {
loadFolders(); // Обновляем список папок
loadFolders();
$('#folder-tree').jstree(true).refresh();
}
});
@ -478,7 +506,7 @@
moveInstallToFolder(item.id, null);
});
});
loadFolders(); // Обновляем список папок
loadFolders();
$('#folder-tree').jstree(true).refresh();
loadInstalls(selectedFolderId);
},
@ -725,12 +753,38 @@
}
}
// Функция для копирования в буфер обмена без алерта
function copyToClipboard(text) {
navigator.clipboard.writeText(text).catch(err => {
console.error('Ошибка копирования: ', err);
});
}
function sortFolders() {
const instance = $('#folder-tree').jstree(true);
instance.sort(instance.get_container().children('ul').find('li'), function (a, b) {
return instance.get_text(a).localeCompare(instance.get_text(b));
});
instance.refresh();
}
function saveFolderPosition(folderId, newParentId) {
$.ajax({
url: `${API_URL}/folders/${folderId}`,
type: 'PUT',
contentType: 'application/json',
data: JSON.stringify({ parent_id: newParentId }),
success: function () {
console.log(`Folder ${folderId} moved to parent ${newParentId}`);
loadFolders();
$('#folder-tree').jstree(true).refresh();
},
error: function (xhr, status, error) {
console.error("Error saving folder position:", status, error);
alert("Не удалось сохранить новое положение папки. Проверьте консоль.");
$('#folder-tree').jstree(true).refresh(); // Восстанавливаем предыдущее состояние
}
});
}
</script>
</body>
</html>