init
This commit is contained in:
commit
b10790c212
40 changed files with 4149 additions and 0 deletions
26
frontend/js/api.js
Normal file
26
frontend/js/api.js
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
// js/api.js - 处理所有与后端API的通信
|
||||
|
||||
const API_BASE = '/v0/api';
|
||||
|
||||
async function handleResponse(response) {
|
||||
// 如果响应是重定向(通常是session过期), 则让浏览器自动跳转
|
||||
if (response.redirected) {
|
||||
window.location.href = response.url;
|
||||
// 返回一个永远不会 resolve 的 Promise 来中断后续的 .then() 链
|
||||
return new Promise(() => {});
|
||||
}
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({ error: `HTTP error! status: ${response.status}` }));
|
||||
throw new Error(errorData.error);
|
||||
}
|
||||
const text = await response.text();
|
||||
// 检查响应体是否为空, 避免解析空字符串时出错
|
||||
return text ? JSON.parse(text) : { success: true };
|
||||
}
|
||||
|
||||
export const api = {
|
||||
get: (endpoint) => fetch(`${API_BASE}${endpoint}`).then(handleResponse),
|
||||
post: (endpoint, body = {}) => fetch(`${API_BASE}${endpoint}`, { method: 'POST', body: JSON.stringify(body), headers: {'Content-Type': 'application/json'} }).then(handleResponse),
|
||||
put: (endpoint, body) => fetch(`${API_BASE}${endpoint}`, { method: 'PUT', body: JSON.stringify(body), headers: {'Content-Type': 'application/json'} }).then(handleResponse),
|
||||
delete: (endpoint) => fetch(`${API_BASE}${endpoint}`, { method: 'DELETE' }).then(handleResponse),
|
||||
};
|
||||
182
frontend/js/app.js
Normal file
182
frontend/js/app.js
Normal file
|
|
@ -0,0 +1,182 @@
|
|||
// js/app.js - 主应用入口
|
||||
|
||||
import { state } from './state.js';
|
||||
import { api } from './api.js';
|
||||
import { initTheme } from './theme.js';
|
||||
import { notification } from './notifications.js';
|
||||
import { DOMElements, switchView, renderConfigList, createCustomSelect, addKeyValueInput, fillForm, showRenderedConfig, updateCaddyStatusView, updateFormVisibility } from './ui.js';
|
||||
|
||||
const POLLING_INTERVAL = 5000;
|
||||
let caddyStatusInterval;
|
||||
|
||||
function getFormStateAsString() {
|
||||
const formData = new FormData(DOMElements.configForm);
|
||||
const data = {};
|
||||
for (const [key, value] of formData.entries()) {
|
||||
const el = DOMElements.configForm.querySelector(`[name="${key}"]`);
|
||||
if (el?.type === 'checkbox') data[key] = el.checked;
|
||||
else if (data[key]) {
|
||||
if (!Array.isArray(data[key])) data[key] = [data[key]];
|
||||
data[key].push(value);
|
||||
} else data[key] = value;
|
||||
}
|
||||
return JSON.stringify(data);
|
||||
}
|
||||
async function attemptExitForm() {
|
||||
if (getFormStateAsString() !== state.initialFormState) {
|
||||
if (await notification.confirm('您有未保存的更改。确定要放弃吗?')) switchView(DOMElements.configListPanel);
|
||||
} else switchView(DOMElements.configListPanel);
|
||||
}
|
||||
async function checkCaddyStatus() {
|
||||
try {
|
||||
const response = await api.get('/caddy/status');
|
||||
updateCaddyStatusView(response.message === 'Caddy is running' ? 'running' : 'stopped', caddyHandlers);
|
||||
} catch (error) { console.error('Error checking Caddy status:', error); updateCaddyStatusView('error', caddyHandlers); }
|
||||
}
|
||||
async function handleStartCaddy() {
|
||||
try {
|
||||
const result = await api.post('/caddy/run');
|
||||
notification.toast(result.message || '启动命令已发送。', 'success');
|
||||
setTimeout(checkCaddyStatus, 500);
|
||||
} catch (error) { notification.toast(`启动失败: ${error.message}`, 'error'); }
|
||||
}
|
||||
async function handleStopCaddy() {
|
||||
if (!await notification.confirm('您确定要停止 Caddy 实例吗?')) return;
|
||||
try {
|
||||
const result = await api.post('/caddy/stop');
|
||||
notification.toast(result.message || '停止命令已发送。', 'info');
|
||||
setTimeout(checkCaddyStatus, 500);
|
||||
} catch(error) { notification.toast(`操作失败: ${error.message}`, 'error'); }
|
||||
}
|
||||
async function handleReloadCaddy() {
|
||||
if (!await notification.confirm('确定要重载 Caddy 配置吗?')) return;
|
||||
try {
|
||||
const result = await api.post('/caddy/restart');
|
||||
notification.toast(result.message || '重载命令已发送。', 'success');
|
||||
setTimeout(checkCaddyStatus, 500);
|
||||
} catch(error) { notification.toast(`重载失败: ${error.message}`, 'error'); }
|
||||
}
|
||||
const caddyHandlers = { handleStartCaddy, handleStopCaddy, handleReloadCaddy };
|
||||
async function handleLogout() {
|
||||
if (!await notification.confirm('您确定要退出登录吗?')) return;
|
||||
notification.toast('正在退出...', 'info');
|
||||
setTimeout(() => { window.location.href = `/v0/api/auth/logout`; }, 500);
|
||||
}
|
||||
async function loadAllConfigs() {
|
||||
try {
|
||||
const filenames = await api.get('/config/filenames');
|
||||
renderConfigList(filenames);
|
||||
} catch(error) { if (error.message) notification.toast(`加载配置列表失败: ${error.message}`, 'error'); }
|
||||
}
|
||||
async function handleEditConfig(originalFilename) {
|
||||
try {
|
||||
const [config, rendered] = await Promise.all([
|
||||
api.get(`/config/file/${originalFilename}`),
|
||||
api.get('/config/files/rendered')
|
||||
]);
|
||||
state.isEditing = true;
|
||||
switchView(DOMElements.configFormPanel);
|
||||
DOMElements.formTitle.textContent = '编辑配置';
|
||||
fillForm(config, originalFilename);
|
||||
showRenderedConfig(rendered, originalFilename);
|
||||
updateFormVisibility(config.tmpl_type, state.availableTemplates);
|
||||
state.initialFormState = getFormStateAsString();
|
||||
} catch(error) { notification.toast(`加载配置详情失败: ${error.message}`, 'error'); }
|
||||
}
|
||||
async function handleDeleteConfig(filename) {
|
||||
if (!await notification.confirm(`确定要删除配置 "${filename}" 吗?`)) return;
|
||||
try {
|
||||
await api.delete(`/config/file/${filename}`);
|
||||
notification.toast('配置已成功删除。', 'success');
|
||||
loadAllConfigs();
|
||||
} catch(error) { notification.toast(`删除失败: ${error.message}`, 'error'); }
|
||||
}
|
||||
async function handleSaveConfig(e) {
|
||||
e.preventDefault();
|
||||
const formData = new FormData(DOMElements.configForm);
|
||||
const filename = formData.get('domain');
|
||||
if (!filename) {
|
||||
notification.toast('域名不能为空。', 'error');
|
||||
return;
|
||||
}
|
||||
const getHeadersMap = (keyName, valueName) => {
|
||||
const headers = {};
|
||||
formData.getAll(keyName).forEach((key, i) => {
|
||||
if (key) {
|
||||
if (!headers[key]) headers[key] = [];
|
||||
headers[key].push(formData.getAll(valueName)[i]);
|
||||
}
|
||||
});
|
||||
return headers;
|
||||
};
|
||||
const globalHeaders = getHeadersMap('header_key', 'header_value');
|
||||
const upstreamHeaders = getHeadersMap('upstream_header_key', 'upstream_header_value');
|
||||
const configData = {
|
||||
domain: filename,
|
||||
tmpl_type: formData.get('tmpl_type'),
|
||||
upstream: { upstream: formData.get('upstream'), muti_upstream: false, upstreams: [], upstream_headers: upstreamHeaders },
|
||||
file_server: { file_dir_path: formData.get('file_dir_path'), enable_browser: DOMElements.configForm.querySelector('#enable_browser').checked },
|
||||
headers: globalHeaders,
|
||||
log: { enable_log: DOMElements.configForm.querySelector('#enable_log').checked, log_domain: filename },
|
||||
error_page: { enable_error_page: DOMElements.configForm.querySelector('#enable_error_page').checked },
|
||||
encode: { enable_encode: DOMElements.configForm.querySelector('#enable_encode').checked }
|
||||
};
|
||||
try {
|
||||
const result = await api.put(`/config/file/${filename}`, configData);
|
||||
state.isEditing = false;
|
||||
notification.toast(result.message || '配置已成功保存。', 'success');
|
||||
setTimeout(() => {
|
||||
switchView(DOMElements.configListPanel);
|
||||
loadAllConfigs();
|
||||
}, 500);
|
||||
} catch(error) { notification.toast(`保存失败: ${error.message}`, 'error'); }
|
||||
}
|
||||
function init() {
|
||||
initTheme(DOMElements.themeToggleInput);
|
||||
notification.init(DOMElements.toastContainer, DOMElements.dialogContainer);
|
||||
loadAllConfigs();
|
||||
api.get('/config/templates')
|
||||
.then(templates => {
|
||||
state.availableTemplates = templates || [];
|
||||
const options = state.availableTemplates.length > 0 ? state.availableTemplates : ['无可用模板'];
|
||||
createCustomSelect('custom-select-tmpl', options, (selectedValue) => {
|
||||
updateFormVisibility(selectedValue, state.availableTemplates);
|
||||
});
|
||||
if (options[0] !== '无可用模板') updateFormVisibility(options[0], state.availableTemplates);
|
||||
})
|
||||
.catch(err => { if(err.message) notification.toast(`加载模板失败: ${err.message}`, 'error') });
|
||||
checkCaddyStatus();
|
||||
caddyStatusInterval = setInterval(checkCaddyStatus, POLLING_INTERVAL);
|
||||
DOMElements.menuToggleBtn.addEventListener('click', () => DOMElements.sidebar.classList.toggle('is-open'));
|
||||
DOMElements.mainContent.addEventListener('click', () => DOMElements.sidebar.classList.remove('is-open'));
|
||||
DOMElements.addNewConfigBtn.addEventListener('click', () => {
|
||||
state.isEditing = false;
|
||||
switchView(DOMElements.configFormPanel);
|
||||
DOMElements.formTitle.textContent = '创建新配置';
|
||||
DOMElements.configForm.reset();
|
||||
if (state.availableTemplates.length > 0) {
|
||||
const selectContainer = document.getElementById('custom-select-tmpl');
|
||||
selectContainer.querySelector('.select-selected').textContent = state.availableTemplates[0];
|
||||
selectContainer.querySelector('input[type="hidden"]').value = state.availableTemplates[0];
|
||||
updateFormVisibility(state.availableTemplates[0], state.availableTemplates);
|
||||
}
|
||||
state.initialFormState = getFormStateAsString();
|
||||
DOMElements.headersContainer.innerHTML = '';
|
||||
DOMElements.upstreamHeadersContainer.innerHTML = '';
|
||||
DOMElements.originalFilenameInput.value = '';
|
||||
});
|
||||
DOMElements.backToListBtn.addEventListener('click', attemptExitForm);
|
||||
DOMElements.cancelEditBtn.addEventListener('click', attemptExitForm);
|
||||
DOMElements.addHeaderBtn.addEventListener('click', () => addKeyValueInput(DOMElements.headersContainer, 'header_key', 'header_value'));
|
||||
DOMElements.addUpstreamHeaderBtn.addEventListener('click', () => addKeyValueInput(DOMElements.upstreamHeadersContainer, 'upstream_header_key', 'upstream_header_value'));
|
||||
DOMElements.configForm.addEventListener('submit', handleSaveConfig);
|
||||
DOMElements.logoutBtn.addEventListener('click', handleLogout);
|
||||
DOMElements.configListContainer.addEventListener('click', e => {
|
||||
const button = e.target.closest('button');
|
||||
if (!button) return;
|
||||
const filename = button.closest('.config-item').dataset.filename;
|
||||
if (button.classList.contains('edit-btn')) handleEditConfig(filename);
|
||||
if (button.classList.contains('delete-btn')) handleDeleteConfig(filename);
|
||||
});
|
||||
}
|
||||
init();
|
||||
150
frontend/js/init.js
Normal file
150
frontend/js/init.js
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
// js/init.js
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const DOMElements = {
|
||||
initForm: document.getElementById('init-form'),
|
||||
initButton: null,
|
||||
toastContainer: document.getElementById('toast-container'),
|
||||
usernameInput: document.getElementById('username'),
|
||||
passwordInput: document.getElementById('password'),
|
||||
confirmPasswordInput: document.getElementById('confirm_password'),
|
||||
};
|
||||
|
||||
const INIT_API_URL = '/v0/api/auth/init';
|
||||
const PASSWORD_MIN_LENGTH = 8;
|
||||
const TOAST_DEFAULT_DURATION = 3000;
|
||||
const REDIRECT_DELAY_SUCCESS = 1500;
|
||||
|
||||
const theme = {
|
||||
init: () => {
|
||||
const storedTheme = localStorage.getItem('theme');
|
||||
const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
|
||||
const currentTheme = storedTheme || (systemPrefersDark ? 'dark' : 'light');
|
||||
document.documentElement.dataset.theme = currentTheme;
|
||||
}
|
||||
};
|
||||
|
||||
const toast = {
|
||||
_container: null,
|
||||
_icons: { success: 'fa-check-circle', error: 'fa-times-circle', info: 'fa-info-circle' },
|
||||
|
||||
init: (containerElement) => {
|
||||
if (!containerElement) {
|
||||
console.error('Toast container element not found.');
|
||||
return;
|
||||
}
|
||||
toast._container = containerElement;
|
||||
toast._container.addEventListener('click', (e) => {
|
||||
if (e.target.dataset.toastClose !== undefined) {
|
||||
toast._hideToast(e.target.closest('.toast'));
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
show: (message, type = 'info', duration = TOAST_DEFAULT_DURATION) => {
|
||||
if (!toast._container) {
|
||||
console.error('Toast module not initialized. Container is missing.');
|
||||
return;
|
||||
}
|
||||
|
||||
const iconClass = toast._icons[type] || 'fa-info-circle';
|
||||
const toastElement = document.createElement('div');
|
||||
toastElement.className = `toast ${type}`;
|
||||
toastElement.innerHTML = `
|
||||
<i class="toast-icon fa-solid ${iconClass}"></i>
|
||||
<p class="toast-message">${message}</p>
|
||||
<button class="toast-close" data-toast-close>×</button>
|
||||
`;
|
||||
toast._container.appendChild(toastElement);
|
||||
requestAnimationFrame(() => toastElement.classList.add('show'));
|
||||
setTimeout(() => toast._hideToast(toastElement), duration);
|
||||
},
|
||||
|
||||
_hideToast: (toastElement) => {
|
||||
if (!toastElement) return;
|
||||
toastElement.classList.remove('show');
|
||||
toastElement.addEventListener('transitionend', () => toastElement.remove(), { once: true });
|
||||
}
|
||||
};
|
||||
|
||||
async function handleInitSubmit(e) {
|
||||
e.preventDefault();
|
||||
|
||||
// 1. 获取并修剪输入值
|
||||
const username = DOMElements.usernameInput.value.trim(); // 获取用户名并去除前后空格
|
||||
const password = DOMElements.passwordInput.value.trim();
|
||||
const confirmPassword = DOMElements.confirmPasswordInput.value.trim();
|
||||
|
||||
// 2. 添加用户名输入框的空值验证
|
||||
if (username === '') {
|
||||
toast.show('管理员用户名不能为空', 'error');
|
||||
DOMElements.usernameInput.focus();
|
||||
return;
|
||||
}
|
||||
// 其他密码验证逻辑不变
|
||||
if (password === '') {
|
||||
toast.show('密码不能为空', 'error');
|
||||
DOMElements.passwordInput.focus();
|
||||
return;
|
||||
}
|
||||
if (confirmPassword === '') {
|
||||
toast.show('确认密码不能为空', 'error');
|
||||
DOMElements.confirmPasswordInput.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
if (password !== confirmPassword) {
|
||||
toast.show('两次输入的密码不匹配', 'error');
|
||||
DOMElements.passwordInput.focus();
|
||||
return;
|
||||
}
|
||||
if (password.length < PASSWORD_MIN_LENGTH) {
|
||||
toast.show(`密码长度至少为 ${PASSWORD_MIN_LENGTH} 位`, 'error');
|
||||
DOMElements.passwordInput.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
DOMElements.initButton.disabled = true;
|
||||
DOMElements.initButton.querySelector('span').textContent = '设置中...';
|
||||
|
||||
try {
|
||||
const formData = new FormData(DOMElements.initForm);
|
||||
formData.set('username', username); // 确保发送的是修剪过的用户名
|
||||
formData.set('password', password); // 确保发送的是修剪过的密码
|
||||
formData.delete('confirm_password');
|
||||
|
||||
const response = await fetch(INIT_API_URL, {
|
||||
method: 'POST',
|
||||
body: new URLSearchParams(formData)
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (response.ok) {
|
||||
toast.show('管理员账户创建成功!正在跳转到登录页面...', 'success');
|
||||
setTimeout(() => { window.location.href = '/login.html'; }, REDIRECT_DELAY_SUCCESS);
|
||||
} else {
|
||||
throw new Error(result.error || `初始化失败: ${response.status}`);
|
||||
}
|
||||
} catch (error) {
|
||||
toast.show(error.message, 'error');
|
||||
DOMElements.initButton.disabled = false;
|
||||
DOMElements.initButton.querySelector('span').textContent = '完成设置';
|
||||
}
|
||||
}
|
||||
|
||||
function initApp() {
|
||||
theme.init();
|
||||
|
||||
if (DOMElements.initForm) {
|
||||
DOMElements.initButton = DOMElements.initForm.querySelector('button[type="submit"]');
|
||||
|
||||
toast.init(DOMElements.toastContainer);
|
||||
|
||||
DOMElements.initForm.addEventListener('submit', handleInitSubmit);
|
||||
} else {
|
||||
console.error('Init form element not found. Script may not function correctly.');
|
||||
}
|
||||
}
|
||||
|
||||
initApp();
|
||||
});
|
||||
89
frontend/js/login.js
Normal file
89
frontend/js/login.js
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
document.addEventListener('DOMContentLoaded', () => {
|
||||
|
||||
const DOMElements = {
|
||||
loginForm: document.getElementById('login-form'),
|
||||
toastContainer: document.getElementById('toast-container'),
|
||||
};
|
||||
const loginButton = DOMElements.loginForm.querySelector('button[type="submit"]');
|
||||
const LOGIN_API_URL = '/v0/api/auth/login';
|
||||
|
||||
const theme = {
|
||||
init: () => {
|
||||
const storedTheme = localStorage.getItem('theme');
|
||||
const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
|
||||
const currentTheme = storedTheme || (systemPrefersDark ? 'dark' : 'light');
|
||||
document.documentElement.dataset.theme = currentTheme;
|
||||
}
|
||||
};
|
||||
|
||||
const toast = {
|
||||
show: (message, type = 'info', duration = 3000) => {
|
||||
const icons = { success: 'fa-check-circle', error: 'fa-times-circle', info: 'fa-info-circle' };
|
||||
const iconClass = icons[type] || 'fa-info-circle';
|
||||
const toastElement = document.createElement('div');
|
||||
toastElement.className = `toast ${type}`;
|
||||
toastElement.innerHTML = `<i class="toast-icon fa-solid ${iconClass}"></i><p class="toast-message">${message}</p><button class="toast-close" data-toast-close>×</button>`;
|
||||
DOMElements.toastContainer.appendChild(toastElement);
|
||||
requestAnimationFrame(() => toastElement.classList.add('show'));
|
||||
const timeoutId = setTimeout(() => hideToast(toastElement), duration);
|
||||
toastElement.querySelector('[data-toast-close]').addEventListener('click', () => {
|
||||
clearTimeout(timeoutId);
|
||||
hideToast(toastElement);
|
||||
});
|
||||
}
|
||||
};
|
||||
function hideToast(toastElement) {
|
||||
if (!toastElement) return;
|
||||
toastElement.classList.remove('show');
|
||||
toastElement.addEventListener('transitionend', () => toastElement.remove(), { once: true });
|
||||
}
|
||||
|
||||
async function handleLogin(e) {
|
||||
e.preventDefault();
|
||||
|
||||
// 获取并确认值
|
||||
const username = DOMElements.loginForm.username.value.trim();
|
||||
const password = DOMElements.loginForm.password.value.trim();
|
||||
|
||||
if (username === '') {
|
||||
toast.show('用户名不能为空', 'error');
|
||||
DOMElements.loginForm.username.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
if (password === '') {
|
||||
toast.show('密码不能为空', 'error');
|
||||
DOMElements.loginForm.password.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
loginButton.disabled = true;
|
||||
loginButton.querySelector('span').textContent = '登录中...';
|
||||
|
||||
try {
|
||||
const response = await fetch(LOGIN_API_URL, {
|
||||
method: 'POST',
|
||||
body: new URLSearchParams(new FormData(DOMElements.loginForm))
|
||||
});
|
||||
const result = await response.json();
|
||||
if (response.ok) {
|
||||
toast.show('登录成功,正在跳转...', 'success');
|
||||
setTimeout(() => { window.location.href = '/'; }, 500);
|
||||
} else {
|
||||
throw new Error(result.error || `登录失败: ${response.status}`);
|
||||
}
|
||||
} catch (error) {
|
||||
toast.show(error.message, 'error');
|
||||
loginButton.disabled = false;
|
||||
loginButton.querySelector('span').textContent = '登录';
|
||||
}
|
||||
}
|
||||
|
||||
function init() {
|
||||
theme.init();
|
||||
if (DOMElements.loginForm) {
|
||||
DOMElements.loginForm.addEventListener('submit', handleLogin);
|
||||
}
|
||||
}
|
||||
init();
|
||||
});
|
||||
57
frontend/js/notifications.js
Normal file
57
frontend/js/notifications.js
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
// js/notifications.js - 提供Toast和Dialog两种通知
|
||||
|
||||
// 这个模块在初始化时需要知道容器的DOM元素
|
||||
let toastContainer;
|
||||
let dialogContainer;
|
||||
|
||||
function hideToast(toastElement) {
|
||||
if (!toastElement) return;
|
||||
toastElement.classList.remove('show');
|
||||
toastElement.addEventListener('transitionend', () => toastElement.remove(), { once: true });
|
||||
}
|
||||
|
||||
export const notification = {
|
||||
init: (toastEl, dialogEl) => {
|
||||
toastContainer = toastEl;
|
||||
dialogContainer = dialogEl;
|
||||
},
|
||||
toast: (message, type = 'info', duration = 3000) => {
|
||||
const icons = { success: 'fa-check-circle', error: 'fa-times-circle', info: 'fa-info-circle', warning: 'fa-exclamation-triangle' };
|
||||
const iconClass = icons[type] || 'fa-info-circle';
|
||||
const toastElement = document.createElement('div');
|
||||
toastElement.className = `toast ${type}`;
|
||||
toastElement.innerHTML = `<i class="toast-icon fa-solid ${iconClass}"></i><p class="toast-message">${message}</p><button class="toast-close" data-toast-close>×</button>`;
|
||||
toastContainer.appendChild(toastElement);
|
||||
requestAnimationFrame(() => toastElement.classList.add('show'));
|
||||
const timeoutId = setTimeout(() => hideToast(toastElement), duration);
|
||||
toastElement.querySelector('[data-toast-close]').addEventListener('click', () => {
|
||||
clearTimeout(timeoutId);
|
||||
hideToast(toastElement);
|
||||
});
|
||||
},
|
||||
confirm: (message) => {
|
||||
return new Promise(resolve => {
|
||||
const dialogHTML = `
|
||||
<div class="dialog-box">
|
||||
<p class="dialog-message">${message}</p>
|
||||
<div class="dialog-actions">
|
||||
<button class="btn btn-secondary" data-action="cancel">取消</button>
|
||||
<button class="btn btn-primary" data-action="confirm">确定</button>
|
||||
</div>
|
||||
</div>`;
|
||||
dialogContainer.innerHTML = dialogHTML;
|
||||
dialogContainer.classList.add('active');
|
||||
const eventHandler = (e) => {
|
||||
const actionButton = e.target.closest('[data-action]');
|
||||
if (!actionButton) return;
|
||||
closeDialog(actionButton.dataset.action === 'confirm');
|
||||
};
|
||||
const closeDialog = (result) => {
|
||||
dialogContainer.removeEventListener('click', eventHandler);
|
||||
dialogContainer.classList.remove('active');
|
||||
setTimeout(() => { dialogContainer.innerHTML = ''; resolve(result); }, 200);
|
||||
};
|
||||
dialogContainer.addEventListener('click', eventHandler);
|
||||
});
|
||||
}
|
||||
};
|
||||
7
frontend/js/state.js
Normal file
7
frontend/js/state.js
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
// js/state.js - 管理应用的共享状态
|
||||
|
||||
export const state = {
|
||||
isEditing: false,
|
||||
initialFormState: '', // 用于检测表单是否有未保存的更改
|
||||
availableTemplates: [], // 存储从后端获取的可用模板名称
|
||||
};
|
||||
26
frontend/js/theme.js
Normal file
26
frontend/js/theme.js
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
// js/theme.js - 处理深色/浅色主题切换
|
||||
|
||||
// 这个模块在初始化时需要知道切换按钮的DOM元素
|
||||
let themeToggleInput;
|
||||
|
||||
function applyTheme(themeName) {
|
||||
document.documentElement.dataset.theme = themeName;
|
||||
if (themeToggleInput) {
|
||||
themeToggleInput.checked = themeName === 'dark';
|
||||
}
|
||||
localStorage.setItem('theme', themeName);
|
||||
}
|
||||
|
||||
function handleToggle(e) {
|
||||
const newTheme = e.target.checked ? 'dark' : 'light';
|
||||
applyTheme(newTheme);
|
||||
}
|
||||
|
||||
export function initTheme(toggleElement) {
|
||||
themeToggleInput = toggleElement;
|
||||
const storedTheme = localStorage.getItem('theme');
|
||||
const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
|
||||
const currentTheme = storedTheme || (systemPrefersDark ? 'dark' : 'light');
|
||||
applyTheme(currentTheme);
|
||||
themeToggleInput.addEventListener('change', handleToggle);
|
||||
}
|
||||
176
frontend/js/ui.js
Normal file
176
frontend/js/ui.js
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
// js/ui.js - 管理所有与UI渲染和DOM操作相关的函数
|
||||
|
||||
// 集中管理所有需要操作的DOM元素
|
||||
export const DOMElements = {
|
||||
sidebar: document.getElementById('sidebar'),
|
||||
menuToggleBtn: document.getElementById('menu-toggle-btn'),
|
||||
mainContent: document.querySelector('.main-content'),
|
||||
configListPanel: document.getElementById('config-list-panel'),
|
||||
configFormPanel: document.getElementById('config-form-panel'),
|
||||
renderedOutputPanel: document.getElementById('rendered-output-panel'),
|
||||
configForm: document.getElementById('config-form'),
|
||||
formTitle: document.getElementById('form-title'),
|
||||
backToListBtn: document.getElementById('back-to-list-btn'),
|
||||
domainInput: document.getElementById('domain'),
|
||||
originalFilenameInput: document.getElementById('original-filename'),
|
||||
headersContainer: document.getElementById('headers-container'),
|
||||
addNewConfigBtn: document.getElementById('add-new-config-btn'),
|
||||
cancelEditBtn: document.getElementById('cancel-edit-btn'),
|
||||
addHeaderBtn: document.getElementById('add-header-btn'),
|
||||
configListContainer: document.getElementById('config-list'),
|
||||
renderedContentCode: document.getElementById('rendered-content'),
|
||||
toastContainer: document.getElementById('toast-container'),
|
||||
dialogContainer: document.getElementById('dialog-container'),
|
||||
themeToggleInput: document.getElementById('theme-toggle-input'),
|
||||
caddyStatusIndicator: document.getElementById('caddy-status-indicator'),
|
||||
caddyActionButtonContainer: document.getElementById('caddy-action-button-container'),
|
||||
logoutBtn: document.getElementById('logout-btn'),
|
||||
upstreamFieldset: document.getElementById('upstream-fieldset'),
|
||||
fileserverFieldset: document.getElementById('fileserver-fieldset'),
|
||||
upstreamHeadersContainer: document.getElementById('upstream-headers-container'),
|
||||
addUpstreamHeaderBtn: document.getElementById('add-upstream-header-btn'),
|
||||
};
|
||||
|
||||
export function switchView(viewToShow) {
|
||||
[DOMElements.configListPanel, DOMElements.configFormPanel, DOMElements.renderedOutputPanel]
|
||||
.forEach(view => view.classList.add('hidden'));
|
||||
if (viewToShow) viewToShow.classList.remove('hidden');
|
||||
DOMElements.addNewConfigBtn.disabled = (viewToShow === DOMElements.configFormPanel);
|
||||
}
|
||||
|
||||
export function renderConfigList(filenames) {
|
||||
DOMElements.configListContainer.innerHTML = '';
|
||||
if (!filenames || filenames.length === 0) {
|
||||
DOMElements.configListContainer.innerHTML = '<p>还没有任何配置,请创建一个。</p>';
|
||||
return;
|
||||
}
|
||||
filenames.forEach(filename => {
|
||||
const item = document.createElement('li');
|
||||
item.className = 'config-item';
|
||||
item.dataset.filename = filename;
|
||||
item.innerHTML = `<span class="config-item-name">${filename}</span><div class="config-item-actions"><button class="btn-icon edit-btn" title="编辑"><i class="fa-solid fa-pen-to-square"></i></button><button class="btn-icon delete-btn" title="删除"><i class="fa-solid fa-trash-can"></i></button></div>`;
|
||||
DOMElements.configListContainer.appendChild(item);
|
||||
});
|
||||
}
|
||||
|
||||
export function createCustomSelect(containerId, options, onSelect) {
|
||||
const container = document.getElementById(containerId);
|
||||
container.innerHTML = `<div class="select-selected"></div><div class="select-items"></div><input type="hidden" name="tmpl_type">`;
|
||||
const selectedDiv = container.querySelector('.select-selected');
|
||||
const itemsDiv = container.querySelector('.select-items');
|
||||
const hiddenInput = container.querySelector('input[type="hidden"]');
|
||||
itemsDiv.innerHTML = '';
|
||||
options.forEach((option, index) => {
|
||||
const item = document.createElement('div');
|
||||
item.textContent = option;
|
||||
item.dataset.value = option;
|
||||
if (index === 0) {
|
||||
selectedDiv.textContent = option;
|
||||
hiddenInput.value = option;
|
||||
}
|
||||
item.addEventListener('click', function(e) {
|
||||
selectedDiv.textContent = this.textContent;
|
||||
hiddenInput.value = this.dataset.value;
|
||||
itemsDiv.classList.remove('select-show');
|
||||
selectedDiv.classList.remove('select-arrow-active');
|
||||
onSelect && onSelect(this.dataset.value);
|
||||
e.stopPropagation();
|
||||
});
|
||||
itemsDiv.appendChild(item);
|
||||
});
|
||||
selectedDiv.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
document.querySelectorAll('.select-items.select-show').forEach(openSelect => {
|
||||
if (openSelect !== itemsDiv) {
|
||||
openSelect.classList.remove('select-show');
|
||||
openSelect.previousElementSibling.classList.remove('select-arrow-active');
|
||||
}
|
||||
});
|
||||
itemsDiv.classList.toggle('select-show');
|
||||
selectedDiv.classList.toggle('select-arrow-active');
|
||||
});
|
||||
document.addEventListener('click', () => {
|
||||
itemsDiv.classList.remove('select-show');
|
||||
selectedDiv.classList.remove('select-arrow-active');
|
||||
});
|
||||
}
|
||||
|
||||
export function addKeyValueInput(container, keyName, valueName, key = '', value = '') {
|
||||
const div = document.createElement('div');
|
||||
div.className = 'header-entry';
|
||||
div.innerHTML = `
|
||||
<input type="text" name="${keyName}" placeholder="Key" value="${key}">
|
||||
<input type="text" name="${valueName}" placeholder="Value" value="${value}">
|
||||
<button type="button" class="btn-icon" onclick="this.parentElement.remove()" title="移除此条目">
|
||||
<i class="fa-solid fa-xmark"></i>
|
||||
</button>`;
|
||||
container.appendChild(div);
|
||||
}
|
||||
|
||||
export function fillForm(config, originalFilename) {
|
||||
DOMElements.originalFilenameInput.value = originalFilename;
|
||||
DOMElements.domainInput.value = config.domain;
|
||||
document.getElementById('upstream').value = config.upstream?.upstream || '';
|
||||
document.getElementById('file_dir_path').value = config.file_server?.file_dir_path || '';
|
||||
document.getElementById('enable_browser').checked = config.file_server?.enable_browser || false;
|
||||
const selectContainer = document.getElementById('custom-select-tmpl');
|
||||
selectContainer.querySelector('.select-selected').textContent = config.tmpl_type;
|
||||
selectContainer.querySelector('input[type="hidden"]').value = config.tmpl_type;
|
||||
DOMElements.headersContainer.innerHTML = '';
|
||||
if (config.headers) Object.entries(config.headers).forEach(([k, v]) => v.forEach(val => addKeyValueInput(DOMElements.headersContainer, 'header_key', 'header_value', k, val)));
|
||||
DOMElements.upstreamHeadersContainer.innerHTML = '';
|
||||
if (config.upstream?.upstream_headers) Object.entries(config.upstream.upstream_headers).forEach(([k, v]) => v.forEach(val => addKeyValueInput(DOMElements.upstreamHeadersContainer, 'upstream_header_key', 'upstream_header_value', k, val)));
|
||||
document.getElementById('enable_log').checked = config.log?.enable_log || false;
|
||||
document.getElementById('enable_error_page').checked = config.error_page?.enable_error_page || false;
|
||||
document.getElementById('enable_encode').checked = config.encode?.enable_encode || false;
|
||||
}
|
||||
|
||||
export function showRenderedConfig(configs, filename) {
|
||||
const targetConfig = configs.find(c => c.filename === filename);
|
||||
if (targetConfig && targetConfig.rendered_content) {
|
||||
DOMElements.renderedContentCode.textContent = atob(targetConfig.rendered_content);
|
||||
DOMElements.renderedOutputPanel.classList.remove('hidden');
|
||||
} else {
|
||||
DOMElements.renderedOutputPanel.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
function createButton(text, className, onClick) {
|
||||
const button = document.createElement('button');
|
||||
button.className = `btn ${className}`;
|
||||
button.innerHTML = `<span>${text}</span>`;
|
||||
button.addEventListener('click', onClick);
|
||||
return button;
|
||||
}
|
||||
|
||||
export function updateCaddyStatusView(status, handlers) {
|
||||
const { handleReloadCaddy, handleStopCaddy, handleStartCaddy } = handlers;
|
||||
const dot = DOMElements.caddyStatusIndicator.querySelector('.status-dot');
|
||||
const text = DOMElements.caddyStatusIndicator.querySelector('.status-text');
|
||||
const buttonContainer = DOMElements.caddyActionButtonContainer;
|
||||
dot.className = 'status-dot';
|
||||
buttonContainer.innerHTML = '';
|
||||
let statusText, dotClass;
|
||||
switch (status) {
|
||||
case 'running':
|
||||
statusText = '运行中'; dotClass = 'running';
|
||||
buttonContainer.appendChild(createButton('重载配置', 'btn-warning', handleReloadCaddy));
|
||||
buttonContainer.appendChild(createButton('停止 Caddy', 'btn-danger', handleStopCaddy));
|
||||
break;
|
||||
case 'stopped':
|
||||
statusText = '已停止'; dotClass = 'stopped';
|
||||
buttonContainer.appendChild(createButton('启动 Caddy', 'btn-success', handleStartCaddy));
|
||||
break;
|
||||
case 'checking': statusText = '检查中...'; dotClass = 'checking'; break;
|
||||
default: statusText = '状态未知'; dotClass = 'error'; break;
|
||||
}
|
||||
text.textContent = statusText;
|
||||
dot.classList.add(dotClass);
|
||||
}
|
||||
|
||||
export function updateFormVisibility(selectedTemplate, availableTemplates) {
|
||||
const showUpstream = selectedTemplate === 'reverse_proxy' && availableTemplates.includes('reverse_proxy');
|
||||
const showFileServer = selectedTemplate === 'file_server' && availableTemplates.includes('file_server');
|
||||
DOMElements.upstreamFieldset.classList.toggle('hidden', !showUpstream);
|
||||
DOMElements.fileserverFieldset.classList.toggle('hidden', !showFileServer);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue