Инициализация проекта
Стабильный рабочий проект.
This commit is contained in:
11
Backend/admin/html/assets/js/dashboard.js
Normal file
11
Backend/admin/html/assets/js/dashboard.js
Normal file
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* Дашборд админ-панели vServer
|
||||
*/
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
// Каждая кнопка отдельно с возможностью настройки
|
||||
messageUp.send('#add-site-btn', '🌐 Страница добавления нового сайта в разработке', 'warning');
|
||||
messageUp.send('#add-cert-btn', '🔒 Страница добавления SSL-сертификата в разработке', 'warning');
|
||||
messageUp.send('.btn-icon', '⚙️ Функция настроек в разработке', 'warning');
|
||||
messageUp.send('.show-all-btn', '📋 Полный список в разработке', 'warning');
|
||||
});
|
90
Backend/admin/html/assets/js/json_loader.js
Normal file
90
Backend/admin/html/assets/js/json_loader.js
Normal file
@@ -0,0 +1,90 @@
|
||||
// Универсальный класс для загрузки JSON данных
|
||||
class JSONLoader {
|
||||
constructor(config) {
|
||||
this.url = config.url;
|
||||
this.container = config.container;
|
||||
this.requiredFields = config.requiredFields || [];
|
||||
this.displayTemplate = config.displayTemplate;
|
||||
this.errorMessage = config.errorMessage || 'Ошибка загрузки данных';
|
||||
}
|
||||
|
||||
// Загрузка данных
|
||||
async load() {
|
||||
try {
|
||||
const response = await fetch(this.url);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
// Проверяем структуру данных
|
||||
if (!this.validateData(data)) {
|
||||
throw new Error('Неверная структура данных');
|
||||
}
|
||||
|
||||
this.display(data);
|
||||
} catch (error) {
|
||||
console.error('Ошибка загрузки:', error);
|
||||
this.displayError();
|
||||
}
|
||||
}
|
||||
|
||||
// Простая проверка обязательных полей
|
||||
validateData(data) {
|
||||
if (!Array.isArray(data)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (let item of data) {
|
||||
for (let field of this.requiredFields) {
|
||||
if (!item.hasOwnProperty(field)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Отображение данных по шаблону
|
||||
display(data) {
|
||||
const container = document.querySelector(this.container);
|
||||
container.innerHTML = '';
|
||||
|
||||
data.forEach(item => {
|
||||
let html;
|
||||
|
||||
// Если шаблон - функция, вызываем её
|
||||
if (typeof this.displayTemplate === 'function') {
|
||||
html = this.displayTemplate(item);
|
||||
} else {
|
||||
// Иначе используем строковый шаблон с заменой
|
||||
html = this.displayTemplate;
|
||||
for (let key in item) {
|
||||
const value = item[key];
|
||||
html = html.replace(new RegExp(`{{${key}}}`, 'g'), value);
|
||||
}
|
||||
}
|
||||
|
||||
container.innerHTML += html;
|
||||
});
|
||||
}
|
||||
|
||||
// Отображение ошибки
|
||||
displayError() {
|
||||
const container = document.querySelector(this.container);
|
||||
if (container) {
|
||||
container.innerHTML = `
|
||||
<div style="text-align: center; padding: 2rem; color: #ff6b6b;">
|
||||
⚠️ ${this.errorMessage}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
// Перезагрузка данных
|
||||
reload() {
|
||||
this.load();
|
||||
}
|
||||
}
|
27
Backend/admin/html/assets/js/menu_loader.js
Normal file
27
Backend/admin/html/assets/js/menu_loader.js
Normal file
@@ -0,0 +1,27 @@
|
||||
// Функция для создания HTML пункта меню
|
||||
function getMenuTemplate(item) {
|
||||
const isActive = item.active ? 'active' : '';
|
||||
|
||||
return `
|
||||
<li class="nav-item ${isActive}">
|
||||
<a href="${item.url}" class="nav-link">
|
||||
<span class="nav-icon">${item.icon}</span>
|
||||
<span class="nav-text">${item.name}</span>
|
||||
</a>
|
||||
</li>
|
||||
`;
|
||||
}
|
||||
|
||||
// Создаем загрузчик меню
|
||||
const menuLoader = new JSONLoader({
|
||||
url: '/json/menu.json',
|
||||
container: '.nav-menu',
|
||||
requiredFields: ['name', 'icon', 'url', 'active'],
|
||||
displayTemplate: getMenuTemplate,
|
||||
errorMessage: 'Ошибка загрузки меню'
|
||||
});
|
||||
|
||||
// Запуск при загрузке страницы
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
menuLoader.load();
|
||||
});
|
153
Backend/admin/html/assets/js/metrics_loader.js
Normal file
153
Backend/admin/html/assets/js/metrics_loader.js
Normal file
@@ -0,0 +1,153 @@
|
||||
// Функция для создания HTML карточки метрики
|
||||
function createMetricCard(type, icon, name, data) {
|
||||
// Используем уже вычисленный процент для всех типов
|
||||
let value = Math.round(data.usage || data.usage_percent || 0);
|
||||
const progressClass = type === 'cpu' ? 'cpu-progress' :
|
||||
type === 'ram' ? 'ram-progress' : 'disk-progress';
|
||||
|
||||
// Определяем детали для каждого типа
|
||||
let details = '';
|
||||
if (type === 'cpu') {
|
||||
details = `
|
||||
<span class="metric-info">${data.model_name || 'CPU'}</span>
|
||||
<span class="metric-frequency">${data.frequency || ''} MHz</span>
|
||||
`;
|
||||
} else if (type === 'ram') {
|
||||
const usedGb = parseFloat(data.used_gb) || 0;
|
||||
details = `
|
||||
<span class="metric-info">${usedGb.toFixed(1)} GB из ${data.total_gb || 0} GB</span>
|
||||
<span class="metric-type">${data.type || 'RAM'}</span>
|
||||
`;
|
||||
} else if (type === 'disk') {
|
||||
const usedGb = parseFloat(data.used_gb) || 0;
|
||||
const freeGb = parseFloat(data.free_gb) || 0;
|
||||
details = `
|
||||
<span class="metric-info">Занято: ${usedGb.toFixed(0)} GB : Свободно: ${freeGb.toFixed(0)} GB</span>
|
||||
<span class="metric-speed">Размер: ${data.total_gb || 0}</span>
|
||||
`;
|
||||
}
|
||||
|
||||
return `
|
||||
<div class="metric-card ${type}">
|
||||
<div class="metric-icon-wrapper">
|
||||
<span class="metric-icon">${icon}</span>
|
||||
</div>
|
||||
<div class="metric-content">
|
||||
<div class="metric-header">
|
||||
<span class="metric-name">${name}</span>
|
||||
<span class="metric-value">${value}%</span>
|
||||
</div>
|
||||
<div class="metric-progress-bar">
|
||||
<div class="metric-progress ${progressClass}" style="width: ${value}%"></div>
|
||||
</div>
|
||||
<div class="metric-details">
|
||||
${details}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// Функция для создания всех метрик
|
||||
function renderMetrics(data) {
|
||||
const container = document.querySelector('.metrics-grid');
|
||||
if (!container) return;
|
||||
|
||||
const html = [
|
||||
createMetricCard('cpu', '🖥️', 'Процессор', data.cpu || {}),
|
||||
createMetricCard('ram', '💾', 'Оперативная память', data.memory || {}),
|
||||
createMetricCard('disk', '💿', data.disk.type, data.disk || {})
|
||||
].join('');
|
||||
|
||||
container.innerHTML = html;
|
||||
}
|
||||
|
||||
// Данные по умолчанию (будут заменены данными из API)
|
||||
const staticData = {
|
||||
cpu: {
|
||||
usage: 0,
|
||||
model_name: 'Загрузка...',
|
||||
frequency: '0',
|
||||
cores: '0'
|
||||
},
|
||||
memory: {
|
||||
usage_percent: 0,
|
||||
used_gb: 0,
|
||||
total_gb: 0,
|
||||
type: 'Загрузка...'
|
||||
},
|
||||
disk: {
|
||||
usage_percent: 0,
|
||||
used_gb: 0,
|
||||
free_gb: 0,
|
||||
total_gb: '0',
|
||||
type: 'Загрузка...',
|
||||
read_speed: '520 MB/s'
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
// Функция обновления метрик
|
||||
async function updateMetrics() {
|
||||
try {
|
||||
const response = await fetch('/api/metrics');
|
||||
const data = await response.json();
|
||||
|
||||
// Обновляем все данные из API
|
||||
if (data.cpu_name) staticData.cpu.model_name = data.cpu_name;
|
||||
if (data.cpu_ghz) staticData.cpu.frequency = data.cpu_ghz;
|
||||
if (data.cpu_cores) staticData.cpu.cores = data.cpu_cores;
|
||||
if (data.cpu_usage) staticData.cpu.usage = parseInt(data.cpu_usage);
|
||||
|
||||
if (data.disk_name) staticData.disk.type = data.disk_name;
|
||||
if (data.disk_size) staticData.disk.total_gb = data.disk_size;
|
||||
if (data.disk_used) staticData.disk.used_gb = parseFloat(data.disk_used);
|
||||
if (data.disk_free) staticData.disk.free_gb = parseFloat(data.disk_free);
|
||||
|
||||
if (data.ram_using) staticData.memory.used_gb = parseFloat(data.ram_using);
|
||||
if (data.ram_total) staticData.memory.total_gb = parseFloat(data.ram_total);
|
||||
|
||||
// Вычисляем процент использования памяти
|
||||
if (staticData.memory.used_gb && staticData.memory.total_gb) {
|
||||
staticData.memory.usage_percent = Math.round((staticData.memory.used_gb / staticData.memory.total_gb) * 100);
|
||||
}
|
||||
|
||||
// Вычисляем процент использования диска
|
||||
if (staticData.disk.used_gb && staticData.disk.total_gb) {
|
||||
const used = parseFloat(staticData.disk.used_gb.toString().replace(' GB', '')) || 0;
|
||||
const total = parseFloat(staticData.disk.total_gb.toString().replace(' GB', '')) || 1;
|
||||
staticData.disk.usage_percent = Math.round((used / total) * 100);
|
||||
}
|
||||
|
||||
// Обновляем uptime
|
||||
if (data.server_uptime) {
|
||||
const uptimeElement = document.querySelector('.uptime-value');
|
||||
if (uptimeElement) {
|
||||
uptimeElement.textContent = data.server_uptime;
|
||||
}
|
||||
}
|
||||
|
||||
// Перерисовываем только метрики
|
||||
renderMetrics(staticData);
|
||||
} catch (error) {
|
||||
console.error('Ошибка обновления метрик:', error);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
// Показываем статические данные когда DOM загружен
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
renderMetrics(staticData);
|
||||
|
||||
// Сразу загружаем актуальные данные
|
||||
updateMetrics();
|
||||
|
||||
// Обновляем метрики каждые 5 секунд
|
||||
setInterval(updateMetrics, 5000);
|
||||
});
|
||||
|
||||
|
||||
|
180
Backend/admin/html/assets/js/server_status.js
Normal file
180
Backend/admin/html/assets/js/server_status.js
Normal file
@@ -0,0 +1,180 @@
|
||||
// Функция для получения HTML шаблона сервера
|
||||
var patch_json = '/json/server_status.json';
|
||||
|
||||
function getServerTemplate(server) {
|
||||
// Определяем класс и текст статуса
|
||||
let statusClass, statusText;
|
||||
switch(server.Status.toLowerCase()) {
|
||||
case 'running':
|
||||
statusClass = 'running';
|
||||
statusText = 'Работает';
|
||||
break;
|
||||
case 'stopped':
|
||||
statusClass = 'stopped';
|
||||
statusText = 'Остановлен';
|
||||
break;
|
||||
case 'starting':
|
||||
statusClass = 'starting';
|
||||
statusText = 'Запускается';
|
||||
break;
|
||||
case 'stopping':
|
||||
statusClass = 'stopping';
|
||||
statusText = 'Завершается';
|
||||
break;
|
||||
default:
|
||||
statusClass = 'stopped';
|
||||
statusText = `Неизвестно (${server.Status})`;
|
||||
}
|
||||
|
||||
// Определяем иконку и состояние кнопки
|
||||
let buttonIcon, buttonDisabled, buttonClass;
|
||||
|
||||
if (statusClass === 'starting' || statusClass === 'stopping') {
|
||||
buttonIcon = '⏳';
|
||||
buttonDisabled = 'disabled';
|
||||
buttonClass = 'btn-icon disabled';
|
||||
} else if (statusClass === 'running') {
|
||||
buttonIcon = '⏹️';
|
||||
buttonDisabled = '';
|
||||
buttonClass = 'btn-icon';
|
||||
} else {
|
||||
buttonIcon = '▶️';
|
||||
buttonDisabled = '';
|
||||
buttonClass = 'btn-icon';
|
||||
}
|
||||
|
||||
return `
|
||||
<div class="server-item">
|
||||
<div class="server-status ${statusClass}"></div>
|
||||
<div class="server-info">
|
||||
<div class="server-name">${server.NameService}</div>
|
||||
<div class="server-details">Port ${server.Port} - ${statusText}</div>
|
||||
</div>
|
||||
<div class="server-actions">
|
||||
<button class="${buttonClass}" onclick="toggleServer('${server.NameService}')" ${buttonDisabled}>
|
||||
${buttonIcon}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// Создаем загрузчик серверов
|
||||
const serversLoader = new JSONLoader({
|
||||
url: patch_json,
|
||||
container: '.servers-grid',
|
||||
requiredFields: ['NameService', 'Port', 'Status'],
|
||||
displayTemplate: getServerTemplate,
|
||||
errorMessage: 'Ошибка загрузки статуса серверов'
|
||||
});
|
||||
|
||||
// Функция для показа временного статуса
|
||||
function showTempStatus(serviceName, tempStatus) {
|
||||
// Ищем элемент этого сервера на странице
|
||||
const serverElements = document.querySelectorAll('.server-item');
|
||||
serverElements.forEach(element => {
|
||||
const nameElement = element.querySelector('.server-name');
|
||||
if (nameElement && nameElement.textContent === serviceName) {
|
||||
// Создаем временный объект сервера с новым статусом
|
||||
fetch(patch_json)
|
||||
.then(response => response.json())
|
||||
.then(servers => {
|
||||
const server = servers.find(s => s.NameService === serviceName);
|
||||
if (server) {
|
||||
const tempServer = {...server, Status: tempStatus};
|
||||
// Заменяем только этот элемент
|
||||
element.outerHTML = getServerTemplate(tempServer);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Функция обновления одного сервера
|
||||
function updateSingleServer(serviceName) {
|
||||
fetch(patch_json)
|
||||
.then(response => response.json())
|
||||
.then(servers => {
|
||||
const server = servers.find(s => s.NameService === serviceName);
|
||||
if (server) {
|
||||
// Ищем элемент этого сервера на странице
|
||||
const serverElements = document.querySelectorAll('.server-item');
|
||||
serverElements.forEach(element => {
|
||||
const nameElement = element.querySelector('.server-name');
|
||||
if (nameElement && nameElement.textContent === serviceName) {
|
||||
// Заменяем только этот элемент
|
||||
element.outerHTML = getServerTemplate(server);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Универсальная функция управления сервером
|
||||
function serverAction(serviceName, startEndpoint, stopEndpoint, updateDelayMs) {
|
||||
// Получаем текущий статус сервера из JSON
|
||||
fetch(patch_json)
|
||||
.then(response => response.json())
|
||||
.then(servers => {
|
||||
const server = servers.find(s => s.NameService === serviceName);
|
||||
|
||||
// Блокируем действие если сервер в процессе изменения
|
||||
if (server.Status === 'starting' || server.Status === 'stopping') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (server.Status === 'running') {
|
||||
// Сервер запущен - останавливаем
|
||||
showTempStatus(serviceName, 'stopping');
|
||||
fetch(stopEndpoint, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
}).then(() => {
|
||||
setTimeout(() => {
|
||||
updateSingleServer(serviceName); // Обновляем только этот сервер
|
||||
}, updateDelayMs);
|
||||
});
|
||||
} else {
|
||||
// Сервер остановлен - запускаем
|
||||
showTempStatus(serviceName, 'starting');
|
||||
fetch(startEndpoint, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
}).then(() => {
|
||||
setTimeout(() => {
|
||||
updateSingleServer(serviceName); // Обновляем только этот сервер
|
||||
}, updateDelayMs);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Функция для переключения сервера
|
||||
function toggleServer(serviceName) {
|
||||
|
||||
if (serviceName === 'MySQL Server') {
|
||||
serverAction('MySQL Server', '/service/MySql_Start', '/service/MySql_Stop', 2000);
|
||||
}
|
||||
|
||||
if (serviceName === 'HTTP Server') {
|
||||
serverAction('HTTP Server', '/service/Http_Start', '/service/Http_Stop', 2000);
|
||||
}
|
||||
|
||||
if (serviceName === 'HTTPS Server') {
|
||||
serverAction('HTTPS Server', '/service/Https_Start', '/service/Https_Stop', 2000);
|
||||
}
|
||||
|
||||
if (serviceName === 'PHP Server') {
|
||||
serverAction('PHP Server', '/service/Php_Start', '/service/Php_Stop', 2000);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Запуск при загрузке страницы
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
serversLoader.load();
|
||||
});
|
55
Backend/admin/html/assets/js/site_list.js
Normal file
55
Backend/admin/html/assets/js/site_list.js
Normal file
@@ -0,0 +1,55 @@
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const sitesList = document.querySelector('.sites-list');
|
||||
if (sitesList) {
|
||||
fetch('/service/Site_List')
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
const sites = data.sites || [];
|
||||
|
||||
// Генерируем статистику
|
||||
updateSiteStats(sites);
|
||||
|
||||
// Отображаем список сайтов
|
||||
sitesList.innerHTML = sites.map(site => `
|
||||
<div class="site-item">
|
||||
<div class="site-status ${site.status === 'active' ? 'active' : 'inactive'}"></div>
|
||||
<div class="site-info">
|
||||
<span class="site-name">${site.host}</span>
|
||||
<span class="site-details">${site.type.toUpperCase()} • Протокол</span>
|
||||
</div>
|
||||
<div class="site-actions">
|
||||
<button class="btn-icon" title="Настройки">⚙️</button>
|
||||
</div>
|
||||
</div>
|
||||
`).join('');
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
function updateSiteStats(sites) {
|
||||
const totalSites = sites.length;
|
||||
const activeSites = sites.filter(site => site.status === 'active').length;
|
||||
const inactiveSites = totalSites - activeSites;
|
||||
|
||||
// Находим контейнер статистики
|
||||
const statsRow = document.querySelector('.stats-row');
|
||||
|
||||
// Создаём всю статистику через JavaScript
|
||||
statsRow.innerHTML = `
|
||||
<div class="stat-item">
|
||||
<div class="stat-number">${totalSites}</div>
|
||||
<div class="stat-label">Всего сайтов</div>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<div class="stat-number active-stat">${activeSites}</div>
|
||||
<div class="stat-label">Активных</div>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<div class="stat-number inactive-stat">${inactiveSites}</div>
|
||||
<div class="stat-label">Неактивных</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
|
||||
|
201
Backend/admin/html/assets/js/tools.js
Normal file
201
Backend/admin/html/assets/js/tools.js
Normal file
@@ -0,0 +1,201 @@
|
||||
/* Класс для показа уведомлений */
|
||||
class MessageUp {
|
||||
// Время автозакрытия уведомлений (в миллисекундах)
|
||||
static autoCloseTime = 3000;
|
||||
|
||||
// Типы уведомлений (легко редактировать тут)
|
||||
static TYPES = {
|
||||
info: {
|
||||
borderColor: 'rgb(52, 152, 219)',
|
||||
background: 'linear-gradient(135deg, rgb(30, 50, 70), rgb(35, 55, 75))'
|
||||
},
|
||||
success: {
|
||||
borderColor: 'rgb(46, 204, 113)',
|
||||
background: 'linear-gradient(135deg, rgb(25, 55, 35), rgb(30, 60, 40))'
|
||||
},
|
||||
warning: {
|
||||
borderColor: 'rgb(243, 156, 18)',
|
||||
background: 'linear-gradient(135deg, rgb(60, 45, 20), rgb(65, 50, 25))'
|
||||
},
|
||||
error: {
|
||||
borderColor: 'rgb(231, 76, 60)',
|
||||
background: 'linear-gradient(135deg, rgb(60, 25, 25), rgb(65, 30, 30))'
|
||||
}
|
||||
};
|
||||
|
||||
constructor() {
|
||||
this.addStyles();
|
||||
}
|
||||
|
||||
/* Показать уведомление */
|
||||
show(message, type = 'info') {
|
||||
const notification = document.createElement('div');
|
||||
notification.className = `message-up message-up-${type}`;
|
||||
|
||||
notification.innerHTML = `
|
||||
<div class="message-content">
|
||||
<span class="message-text">${message}</span>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Вычисляем позицию для нового уведомления
|
||||
const existingNotifications = document.querySelectorAll('.message-up');
|
||||
let topPosition = 2; // начальная позиция в rem
|
||||
|
||||
existingNotifications.forEach(existing => {
|
||||
const rect = existing.getBoundingClientRect();
|
||||
const currentTop = parseFloat(existing.style.top) || 2;
|
||||
const height = rect.height / 16; // переводим px в rem (примерно)
|
||||
topPosition = Math.max(topPosition, currentTop + height + 1); // добавляем отступ
|
||||
});
|
||||
|
||||
notification.style.top = `${topPosition}rem`;
|
||||
document.body.appendChild(notification);
|
||||
|
||||
// Показываем с анимацией
|
||||
setTimeout(() => {
|
||||
notification.classList.add('message-up-show');
|
||||
}, 10);
|
||||
|
||||
// Автоматическое закрытие и удаление
|
||||
if (MessageUp.autoCloseTime > 0) {
|
||||
setTimeout(() => {
|
||||
if (notification && notification.parentNode) {
|
||||
notification.classList.remove('message-up-show');
|
||||
notification.classList.add('message-up-hide');
|
||||
|
||||
setTimeout(() => {
|
||||
if (notification.parentNode) {
|
||||
notification.remove();
|
||||
// Пересчитываем позиции оставшихся уведомлений
|
||||
this.repositionNotifications();
|
||||
}
|
||||
}, 300);
|
||||
}
|
||||
}, MessageUp.autoCloseTime);
|
||||
}
|
||||
}
|
||||
|
||||
/* Пересчитать позиции всех уведомлений */
|
||||
repositionNotifications() {
|
||||
const notifications = document.querySelectorAll('.message-up');
|
||||
let currentTop = 2; // начальная позиция
|
||||
|
||||
notifications.forEach(notification => {
|
||||
notification.style.transition = 'all 0.3s ease';
|
||||
notification.style.top = `${currentTop}rem`;
|
||||
|
||||
const rect = notification.getBoundingClientRect();
|
||||
const height = rect.height / 16; // переводим px в rem
|
||||
currentTop += height + 1; // добавляем отступ
|
||||
});
|
||||
}
|
||||
|
||||
/* Показать сообщение напрямую или привязать к элементам */
|
||||
send(messageOrSelector, typeOrMessage = 'info', type = 'info') {
|
||||
// Если первый параметр строка и нет других элементов на странице с таким селектором
|
||||
// то показываем сообщение напрямую
|
||||
if (typeof messageOrSelector === 'string' &&
|
||||
document.querySelectorAll(messageOrSelector).length === 0) {
|
||||
// Показываем сообщение напрямую
|
||||
this.show(messageOrSelector, typeOrMessage);
|
||||
return;
|
||||
}
|
||||
|
||||
// Иначе привязываем к элементам (старый способ)
|
||||
this.bindToElements(messageOrSelector, typeOrMessage, type);
|
||||
}
|
||||
|
||||
/* Привязать уведомления к элементам */
|
||||
bindToElements(selector, message = 'Страница в разработке', type = 'info') {
|
||||
document.querySelectorAll(selector).forEach(element => {
|
||||
element.addEventListener('click', function(e) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
// Вызываем нужный тип уведомления
|
||||
window.messageUp.show(message, type);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/* Добавить стили для уведомлений */
|
||||
addStyles() {
|
||||
if (document.querySelector('#message-up-styles')) return;
|
||||
|
||||
const cfg = MessageUp.TYPES;
|
||||
|
||||
// Генерируем стили для типов уведомлений
|
||||
const typeStyles = Object.entries(cfg).map(([type, style]) => `
|
||||
.message-up-${type} {
|
||||
border-color: ${style.borderColor};
|
||||
background: ${style.background};
|
||||
}
|
||||
`).join('');
|
||||
|
||||
const style = document.createElement('style');
|
||||
style.id = 'message-up-styles';
|
||||
style.textContent = `
|
||||
.message-up {
|
||||
position: fixed;
|
||||
top: 2rem;
|
||||
right: 2rem;
|
||||
min-width: 300px;
|
||||
max-width: 400px;
|
||||
background: rgb(26, 37, 47);
|
||||
backdrop-filter: blur(15px);
|
||||
border-radius: 12px;
|
||||
padding: 1rem;
|
||||
color: #ecf0f1;
|
||||
font-size: 0.9rem;
|
||||
border: 2px solid;
|
||||
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
|
||||
z-index: 10000;
|
||||
opacity: 0;
|
||||
transform: translateX(100%);
|
||||
transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
font-family: 'Segoe UI', system-ui, sans-serif;
|
||||
}
|
||||
|
||||
.message-up-show {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
}
|
||||
|
||||
.message-up-hide {
|
||||
opacity: 0;
|
||||
transform: translateX(100%);
|
||||
}
|
||||
|
||||
${typeStyles}
|
||||
|
||||
.message-content {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.message-text {
|
||||
flex: 1;
|
||||
line-height: 1.4;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.message-up {
|
||||
top: 1rem;
|
||||
right: 1rem;
|
||||
left: 1rem;
|
||||
min-width: auto;
|
||||
max-width: none;
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Создаем глобальный экземпляр
|
||||
window.messageUp = new MessageUp();
|
Reference in New Issue
Block a user