feat(frontend): Phase 5d-i — settings page shell + dirty tracking

Adds the settings entry as a new Vite multi-page input. Lays down the
shared page chrome (sidebar, save bar, restart, security alert) and the
AllSetting fetch/dirty-poll lifecycle so 5d-ii through 5d-vi can drop
in tab partials without re-implementing it.

- settings.html + src/settings.js: third Vite entry; mounts SettingsPage.
- SettingsPage.vue: page chrome with the legacy two-button save/restart
  bar, conf-alerts banner, and 5 a-tabs (4 always-visible + the formats
  tab gated on subJsonEnable || subClashEnable). Each tab body is an
  a-empty placeholder until 5d-ii…vi fill them in.
- useAllSetting.js composable: POST /panel/setting/all on mount, mirrors
  the legacy 1s busy-loop dirty check via setInterval, and exposes
  fetchAll/saveAll. saveDisabled flips off as soon as the user diverges
  from the server snapshot.
- restartPanel rebuilds the URL (host/port/scheme/base path) from the
  saved settings so users land on the new endpoint after a port or
  cert change.
- models/setting.js: adopts the @/utils alias and a leading file-level
  doc — semantics unchanged.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
MHSanaei 2026-05-08 13:04:06 +02:00
parent 732b3f51aa
commit 7838df211b
No known key found for this signature in database
GPG key ID: 7E4060F2FBE5AB7A
6 changed files with 415 additions and 1 deletions

13
frontend/settings.html Normal file
View file

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>3x-ui · Settings</title>
</head>
<body>
<div id="message"></div>
<div id="app"></div>
<script type="module" src="/src/settings.js"></script>
</body>
</html>

View file

@ -1,4 +1,9 @@
import { ObjectUtil } from '../utils/legacy.js'; // Mirrors web/assets/js/model/setting.js — every field on this class is
// round-tripped through `/panel/setting/all` and `/panel/setting/update`,
// so adding a field here without a matching Go-side change will silently
// drop it on save. Defaults match the legacy panel.
import { ObjectUtil } from '@/utils';
export class AllSetting { export class AllSetting {

View file

@ -0,0 +1,297 @@
<script setup>
import { computed, onMounted, ref } from 'vue';
import { theme as antdTheme, Modal } from 'ant-design-vue';
import {
SettingOutlined,
SafetyOutlined,
MessageOutlined,
CloudServerOutlined,
CodeOutlined,
} from '@ant-design/icons-vue';
import { HttpUtil, PromiseUtil } from '@/utils';
import { theme as themeState } from '@/composables/useTheme.js';
import { useMediaQuery } from '@/composables/useMediaQuery.js';
import AppSidebar from '@/components/AppSidebar.vue';
import { useAllSetting } from './useAllSetting.js';
const antdThemeConfig = computed(() => ({
algorithm: themeState.isDark ? antdTheme.darkAlgorithm : antdTheme.defaultAlgorithm,
}));
const { fetched, spinning, saveDisabled, allSetting, fetchAll, saveAll } = useAllSetting();
const { isMobile } = useMediaQuery();
const basePath = window.__X_UI_BASE_PATH__ || '';
const requestUri = window.location.pathname;
// `entry*` mirrors the URL the user opened the panel with so the page
// can rebuild it after a restart that may change host/port/scheme.
const entryHost = ref('');
const entryPort = ref('');
const entryIsIP = ref(false);
function isIp(h) {
if (typeof h !== 'string') return false;
// IPv4: four dot-separated octets 0-255.
const v4 = h.split('.');
if (v4.length === 4 && v4.every((p) => /^\d{1,3}$/.test(p) && Number(p) <= 255)) return true;
// IPv6: hex groups, optional single :: compression.
if (!h.includes(':') || h.includes(':::')) return false;
const parts = h.split('::');
if (parts.length > 2) return false;
const split = (s) => (s ? s.split(':').filter(Boolean) : []);
const head = split(parts[0]);
const tail = split(parts[1]);
const valid = (seg) => /^[0-9a-fA-F]{1,4}$/.test(seg);
if (![...head, ...tail].every(valid)) return false;
const groups = head.length + tail.length;
return parts.length === 2 ? groups < 8 : groups === 8;
}
onMounted(() => {
entryHost.value = window.location.hostname;
entryPort.value = window.location.port;
entryIsIP.value = isIp(entryHost.value);
});
// Rebuild the URL after a restart host/port/scheme may have changed
// (cert toggled on, port edited, base path edited).
function rebuildUrlAfterRestart() {
const { webDomain, webPort, webBasePath, webCertFile, webKeyFile } = allSetting;
const newProtocol = (webCertFile || webKeyFile) ? 'https:' : 'http:';
let base = webBasePath ? webBasePath.replace(/^\//, '') : '';
if (base && !base.endsWith('/')) base += '/';
if (!entryIsIP.value) {
const url = new URL(window.location.href);
url.pathname = `/${base}panel/settings`;
url.protocol = newProtocol;
return url.toString();
}
let finalHost = entryHost.value;
let finalPort = entryPort.value || '';
if (webDomain && isIp(webDomain)) finalHost = webDomain;
if (webPort && Number(webPort) !== Number(entryPort.value)) finalPort = String(webPort);
const url = new URL(`${newProtocol}//${finalHost}`);
if (finalPort) url.port = finalPort;
url.pathname = `/${base}panel/settings`;
return url.toString();
}
async function restartPanel() {
await new Promise((resolve, reject) => {
Modal.confirm({
title: 'Restart panel',
content: 'Restart the panel now? Your session will reconnect once it comes back.',
okText: 'Restart',
cancelText: 'Cancel',
onOk: () => resolve(),
onCancel: () => reject(new Error('cancelled')),
});
}).catch(() => null);
spinning.value = true;
try {
const msg = await HttpUtil.post('/panel/setting/restartPanel');
if (!msg?.success) return;
await PromiseUtil.sleep(5000);
window.location.replace(rebuildUrlAfterRestart());
} finally {
spinning.value = false;
}
}
// Conf alerts mirror the legacy banner pure derivation off allSetting.
const confAlerts = computed(() => {
const out = [];
if (window.location.protocol !== 'https:') {
out.push('Panel is served over plain HTTP — set up TLS for production.');
}
if (allSetting.webPort === 2053) {
out.push('Default port 2053 is well-known — change it to a random port.');
}
const segs = window.location.pathname.split('/').length < 4;
if (segs && allSetting.webBasePath === '/') {
out.push('Default base path "/" is well-known — change it to a random path.');
}
if (allSetting.subEnable) {
let subPath = allSetting.subPath;
if (allSetting.subURI) {
try { subPath = new URL(allSetting.subURI).pathname; } catch (_e) {}
}
if (subPath === '/sub/') {
out.push('Default subscription path "/sub/" is well-known — change it.');
}
}
if (allSetting.subJsonEnable) {
let p = allSetting.subJsonPath;
if (allSetting.subJsonURI) {
try { p = new URL(allSetting.subJsonURI).pathname; } catch (_e) {}
}
if (p === '/json/') {
out.push('Default JSON subscription path "/json/" is well-known — change it.');
}
}
return out;
});
const alertVisible = ref(true);
</script>
<template>
<a-config-provider :theme="antdThemeConfig">
<a-layout
class="settings-page"
:class="{ 'is-dark': themeState.isDark, 'is-ultra': themeState.isUltra }"
>
<AppSidebar :base-path="basePath" :request-uri="requestUri" />
<a-layout class="content-shell">
<a-layout-content id="content-layout" class="content-area">
<a-spin :spinning="spinning || !fetched" :delay="200" tip="Loading…" size="large">
<div v-if="!fetched" class="loading-spacer" />
<template v-else>
<a-alert
v-if="confAlerts.length > 0 && alertVisible"
type="error"
show-icon
closable
class="conf-alert"
@close="alertVisible = false"
>
<template #message>Security warnings</template>
<template #description>
<b>Your panel may be exposed:</b>
<ul>
<li v-for="(msg, i) in confAlerts" :key="i">{{ msg }}</li>
</ul>
</template>
</a-alert>
<a-row :gutter="[isMobile ? 8 : 16, isMobile ? 0 : 12]">
<a-col :span="24">
<a-card hoverable>
<a-row class="header-row">
<a-col :xs="24" :sm="10" class="header-actions">
<a-space direction="horizontal">
<a-button type="primary" :disabled="saveDisabled" @click="saveAll">
Save
</a-button>
<a-button type="primary" danger :disabled="!saveDisabled" @click="restartPanel">
Restart panel
</a-button>
</a-space>
</a-col>
<a-col :xs="24" :sm="14" class="header-info">
<a-back-top :target="() => document.getElementById('content-layout')" :visibility-height="200" />
<a-alert
type="warning"
show-icon
message="Save before restarting — unsaved changes are dropped on restart."
/>
</a-col>
</a-row>
</a-card>
</a-col>
<a-col :span="24">
<a-tabs default-active-key="1">
<a-tab-pane key="1" class="tab-pane">
<template #tab>
<SettingOutlined />
<span>Panel</span>
</template>
<a-empty description="General — coming in 5d-ii" />
</a-tab-pane>
<a-tab-pane key="2" class="tab-pane">
<template #tab>
<SafetyOutlined />
<span>Security</span>
</template>
<a-empty description="Security — coming in 5d-iii" />
</a-tab-pane>
<a-tab-pane key="3" class="tab-pane">
<template #tab>
<MessageOutlined />
<span>Telegram</span>
</template>
<a-empty description="Telegram — coming in 5d-iv" />
</a-tab-pane>
<a-tab-pane key="4" class="tab-pane">
<template #tab>
<CloudServerOutlined />
<span>Subscription</span>
</template>
<a-empty description="Subscription — coming in 5d-v" />
</a-tab-pane>
<a-tab-pane
v-if="allSetting.subJsonEnable || allSetting.subClashEnable"
key="5"
class="tab-pane"
>
<template #tab>
<CodeOutlined />
<span>Subscription (Formats)</span>
</template>
<a-empty description="Subscription formats — coming in 5d-vi" />
</a-tab-pane>
</a-tabs>
</a-col>
</a-row>
</template>
</a-spin>
</a-layout-content>
</a-layout>
</a-layout>
</a-config-provider>
</template>
<style scoped>
.settings-page {
--bg-page: #f0f2f5;
--bg-card: #ffffff;
min-height: 100vh;
background: var(--bg-page);
}
.settings-page.is-dark {
--bg-page: #0a1222;
--bg-card: #151f31;
}
.settings-page.is-dark.is-ultra {
--bg-page: #21242a;
--bg-card: #0c0e12;
}
.settings-page :deep(.ant-layout),
.settings-page :deep(.ant-layout-content) {
background: transparent;
}
.content-shell { background: transparent; }
.content-area { padding: 24px; }
.loading-spacer { min-height: calc(100vh - 120px); }
.conf-alert { margin-bottom: 10px; }
.header-row {
display: flex;
flex-wrap: wrap;
align-items: center;
}
.header-actions { padding: 4px; }
.header-info {
display: flex;
justify-content: flex-end;
}
.tab-pane { padding-top: 20px; }
</style>

View file

@ -0,0 +1,80 @@
// Centralizes the AllSetting fetch/save lifecycle the legacy panel
// scattered across data() + methods + a busy-loop dirty checker.
//
// The dirty flag is recomputed once per second (matching the legacy
// `while (true) sleep(1000)` poll) — we don't deep-watch because the
// settings tree has many nested fields and a poll is cheap enough.
import { onMounted, onUnmounted, reactive, ref } from 'vue';
import { HttpUtil } from '@/utils';
import { AllSetting } from '@/models/setting.js';
const DIRTY_POLL_MS = 1000;
export function useAllSetting() {
const fetched = ref(false);
const spinning = ref(false);
const saveDisabled = ref(true);
// Two reactive snapshots: the last server-side state and the one the
// user is editing. `equals` compares enumerable props field-by-field.
const oldAllSetting = reactive(new AllSetting());
const allSetting = reactive(new AllSetting());
function applyServerState(obj) {
const fresh = new AllSetting(obj);
Object.assign(oldAllSetting, fresh);
Object.assign(allSetting, fresh);
saveDisabled.value = true;
}
async function fetchAll() {
const msg = await HttpUtil.post('/panel/setting/all');
if (msg?.success) {
fetched.value = true;
applyServerState(msg.obj);
}
}
async function saveAll() {
spinning.value = true;
try {
const msg = await HttpUtil.post('/panel/setting/update', allSetting);
if (msg?.success) await fetchAll();
} finally {
spinning.value = false;
}
}
let timer = null;
function startDirtyPoll() {
if (timer != null) return;
timer = setInterval(() => {
// ObjectUtil.equals walks own enumerable props; reactive proxies
// expose them transparently so this works without cloning.
saveDisabled.value = oldAllSetting.equals(allSetting);
}, DIRTY_POLL_MS);
}
function stopDirtyPoll() {
if (timer != null) {
clearInterval(timer);
timer = null;
}
}
onMounted(() => {
fetchAll();
startDirtyPoll();
});
onUnmounted(stopDirtyPoll);
return {
fetched,
spinning,
saveDisabled,
oldAllSetting,
allSetting,
fetchAll,
saveAll,
};
}

18
frontend/src/settings.js Normal file
View file

@ -0,0 +1,18 @@
import { createApp } from 'vue';
import Antd, { message } from 'ant-design-vue';
import 'ant-design-vue/dist/reset.css';
import { setupAxios } from '@/api/axios-init.js';
// Importing useTheme triggers the boot side-effect that applies the
// stored theme to <body>/<html> before Vue mounts.
import '@/composables/useTheme.js';
import SettingsPage from '@/pages/settings/SettingsPage.vue';
setupAxios();
const messageContainer = document.getElementById('message');
if (messageContainer) {
message.config({ getContainer: () => messageContainer });
}
createApp(SettingsPage).use(Antd).mount('#app');

View file

@ -45,6 +45,7 @@ export default defineConfig({
input: { input: {
index: path.resolve(__dirname, 'index.html'), index: path.resolve(__dirname, 'index.html'),
login: path.resolve(__dirname, 'login.html'), login: path.resolve(__dirname, 'login.html'),
settings: path.resolve(__dirname, 'settings.html'),
}, },
}, },
}, },