Revert "Refine settings and panel preferences"
This reverts commit 760ab62c10.
This commit is contained in:
@@ -31,4 +31,3 @@ Updated: 2026-04-02
|
||||
15. Added editable System settings with shared validation, a system update API, service/port conflict protection, and UI coverage for local save flows.
|
||||
16. Simplified the System tab layout by removing the redundant Runtime card and collapsing those fields into a compact settings section.
|
||||
17. Moved panel auth to server-issued expiring tokens with `sessionStorage` persistence and Compose-configurable credentials/TTL.
|
||||
18. Reworked Settings to store panel language/theme in `localStorage`, added RU/EN UI switching, and made service deletion warn before cascading linked-user removal.
|
||||
|
||||
@@ -29,8 +29,6 @@ Updated: 2026-04-02
|
||||
- `src/app.css`: full panel styling
|
||||
- `src/data/mockDashboard.ts`: default panel state and frontend fallback snapshot
|
||||
- `src/lib/3proxy.ts`: formatting and status helpers
|
||||
- `src/lib/panelPreferences.ts`: client-side `localStorage` preferences and theme application helpers
|
||||
- `src/lib/panelText.ts`: EN/RU panel copy and labels for translated UI chrome
|
||||
- `src/lib/3proxy.test.ts`: paranoia-oriented tests for core domain rules
|
||||
- `src/shared/contracts.ts`: shared panel, service, user, and API data contracts
|
||||
- `src/shared/validation.ts`: shared validation for user creation, system edits, protocol mapping, and quota conversion
|
||||
|
||||
@@ -153,24 +153,6 @@ describe('panel api', () => {
|
||||
expect(response.body.system.previewConfig).toContain('socks -p1180 -u2');
|
||||
expect(response.body.service.lastEvent).toBe('System configuration updated from panel');
|
||||
});
|
||||
|
||||
it('removes linked users when a service is deleted from settings', async () => {
|
||||
const app = await createTestApp();
|
||||
const token = await authorize(app);
|
||||
const initial = await request(app).get('/api/state').set('Authorization', `Bearer ${token}`);
|
||||
const system = createSystemPayload(initial.body);
|
||||
|
||||
system.services = system.services.filter((service) => service.id !== 'socks-main');
|
||||
|
||||
const response = await request(app).put('/api/system').set('Authorization', `Bearer ${token}`).send(system);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body.userRecords.some((user: { username: string }) => user.username === 'night-shift')).toBe(
|
||||
false,
|
||||
);
|
||||
expect(response.body.userRecords.some((user: { username: string }) => user.username === 'ops-east')).toBe(false);
|
||||
expect(response.body.service.lastEvent).toMatch(/removed 2 linked users/i);
|
||||
});
|
||||
});
|
||||
|
||||
async function createTestApp() {
|
||||
|
||||
@@ -129,23 +129,8 @@ export function createApp({ store, runtime, runtimeRootDir, auth }: AppServices)
|
||||
app.put('/api/system', async (request, response, next) => {
|
||||
try {
|
||||
const state = await store.read();
|
||||
const requestedSystem = request.body as Partial<UpdateSystemInput>;
|
||||
const nextServiceIds = new Set(
|
||||
(Array.isArray(requestedSystem.services) ? requestedSystem.services : []).map((service) => service.id),
|
||||
);
|
||||
const removedServiceIds = new Set(
|
||||
state.system.services
|
||||
.map((service) => service.id)
|
||||
.filter((serviceId) => !nextServiceIds.has(serviceId)),
|
||||
);
|
||||
|
||||
const removedUsers = state.userRecords.filter((user) => removedServiceIds.has(user.serviceId));
|
||||
state.userRecords = state.userRecords.filter((user) => !removedServiceIds.has(user.serviceId));
|
||||
state.system = validateSystemInput(requestedSystem, state.userRecords);
|
||||
state.service.lastEvent =
|
||||
removedUsers.length > 0
|
||||
? `System configuration updated from panel and removed ${removedUsers.length} linked users`
|
||||
: 'System configuration updated from panel';
|
||||
state.system = validateSystemInput(request.body as Partial<UpdateSystemInput>, state.userRecords);
|
||||
state.service.lastEvent = 'System configuration updated from panel';
|
||||
await persistRuntimeMutation(store, runtime, state, runtimePaths);
|
||||
response.json(await getSnapshot(store, runtime, runtimePaths));
|
||||
} catch (error) {
|
||||
|
||||
@@ -11,7 +11,6 @@ async function loginIntoPanel(user: ReturnType<typeof userEvent.setup>) {
|
||||
|
||||
beforeEach(() => {
|
||||
window.sessionStorage.clear();
|
||||
window.localStorage.clear();
|
||||
});
|
||||
|
||||
describe('App login gate', () => {
|
||||
@@ -51,23 +50,6 @@ describe('App login gate', () => {
|
||||
expect(screen.queryByRole('button', { name: /open panel/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('stores panel language in localStorage and restores it after a remount', async () => {
|
||||
const user = userEvent.setup();
|
||||
const firstRender = render(<App />);
|
||||
|
||||
await loginIntoPanel(user);
|
||||
await user.click(screen.getByRole('button', { name: /settings/i }));
|
||||
await user.selectOptions(screen.getByLabelText(/panel language/i), 'ru');
|
||||
|
||||
expect(screen.getByRole('button', { name: /панель/i })).toBeInTheDocument();
|
||||
|
||||
firstRender.unmount();
|
||||
render(<App />);
|
||||
|
||||
expect(screen.getByRole('button', { name: /панель/i })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /настройки/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens add-user flow in a modal and closes it on escape', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<App />);
|
||||
@@ -125,43 +107,26 @@ describe('App login gate', () => {
|
||||
expect(screen.queryByRole('dialog', { name: /delete user/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('saves service settings from the settings tab and applies them to the local fallback state', async () => {
|
||||
it('saves system settings from the system tab and applies them to the local fallback state', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<App />);
|
||||
|
||||
await loginIntoPanel(user);
|
||||
await user.click(screen.getByRole('button', { name: /settings/i }));
|
||||
await user.click(screen.getByRole('button', { name: /system/i }));
|
||||
|
||||
await user.clear(screen.getByLabelText(/public host/i));
|
||||
await user.type(screen.getByLabelText(/public host/i), 'ops-gateway.example.net');
|
||||
|
||||
const firstPortInput = screen.getAllByLabelText(/port/i)[0];
|
||||
await user.clear(firstPortInput);
|
||||
await user.type(firstPortInput, '1180');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /save settings/i }));
|
||||
await user.click(screen.getByRole('button', { name: /save system/i }));
|
||||
|
||||
expect(screen.getByText(/ops-gateway\.example\.net/i)).toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /users/i }));
|
||||
|
||||
expect(screen.getAllByText(/edge\.example\.net:1180/i).length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('warns before deleting a service and removes linked users after confirmation', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<App />);
|
||||
|
||||
await loginIntoPanel(user);
|
||||
await user.click(screen.getByRole('button', { name: /settings/i }));
|
||||
|
||||
await user.click(screen.getAllByRole('button', { name: /^remove$/i })[0]);
|
||||
|
||||
const dialog = screen.getByRole('dialog', { name: /delete service/i });
|
||||
expect(dialog).toBeInTheDocument();
|
||||
expect(within(dialog).getByText(/linked users to be removed/i)).toBeInTheDocument();
|
||||
expect(within(dialog).getByText(/night-shift, ops-east/i)).toBeInTheDocument();
|
||||
|
||||
await user.click(within(dialog).getByRole('button', { name: /^remove$/i }));
|
||||
await user.click(screen.getByRole('button', { name: /save settings/i }));
|
||||
await user.click(screen.getByRole('button', { name: /users/i }));
|
||||
|
||||
expect(screen.queryByText(/night-shift/i)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText(/ops-east/i)).not.toBeInTheDocument();
|
||||
expect(screen.getAllByText(/ops-gateway\.example\.net:1180/i).length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
219
src/App.tsx
219
src/App.tsx
@@ -4,12 +4,11 @@ import { fallbackDashboardSnapshot, panelAuth } from './data/mockDashboard';
|
||||
import {
|
||||
buildProxyLink,
|
||||
formatBytes,
|
||||
formatQuotaState,
|
||||
formatTrafficShare,
|
||||
getServiceTone,
|
||||
isQuotaExceeded,
|
||||
} from './lib/3proxy';
|
||||
import { applyPanelTheme, loadPanelPreferences, observeSystemTheme, savePanelPreferences, type PanelPreferences } from './lib/panelPreferences';
|
||||
import { getPanelText } from './lib/panelText';
|
||||
import type {
|
||||
CreateUserInput,
|
||||
DashboardSnapshot,
|
||||
@@ -23,10 +22,10 @@ import { quotaMbToBytes, validateCreateUserInput } from './shared/validation';
|
||||
|
||||
type TabId = 'dashboard' | 'users' | 'system';
|
||||
|
||||
const tabs: Array<{ id: TabId; textKey: 'dashboard' | 'users' | 'settings' }> = [
|
||||
{ id: 'dashboard', textKey: 'dashboard' },
|
||||
{ id: 'users', textKey: 'users' },
|
||||
{ id: 'system', textKey: 'settings' },
|
||||
const tabs: Array<{ id: TabId; label: string }> = [
|
||||
{ id: 'dashboard', label: 'Dashboard' },
|
||||
{ id: 'users', label: 'Users' },
|
||||
{ id: 'system', label: 'System' },
|
||||
];
|
||||
|
||||
const SESSION_KEY = '3proxy-ui-panel-session';
|
||||
@@ -37,14 +36,7 @@ interface StoredSession {
|
||||
expiresAt: string;
|
||||
}
|
||||
|
||||
function LoginGate({
|
||||
onUnlock,
|
||||
preferences,
|
||||
}: {
|
||||
onUnlock: (login: string, password: string) => Promise<void>;
|
||||
preferences: PanelPreferences;
|
||||
}) {
|
||||
const text = getPanelText(preferences.language);
|
||||
function LoginGate({ onUnlock }: { onUnlock: (login: string, password: string) => Promise<void> }) {
|
||||
const [login, setLogin] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
@@ -68,12 +60,12 @@ function LoginGate({
|
||||
<main className="login-shell">
|
||||
<section className="login-card">
|
||||
<div className="login-copy">
|
||||
<h1>{text.auth.title}</h1>
|
||||
<p>{text.auth.subtitle}</p>
|
||||
<h1>3proxy UI</h1>
|
||||
<p>Sign in to the control panel.</p>
|
||||
</div>
|
||||
<form className="login-form" onSubmit={handleSubmit}>
|
||||
<label>
|
||||
{text.auth.login}
|
||||
Login
|
||||
<input
|
||||
autoComplete="username"
|
||||
name="login"
|
||||
@@ -83,7 +75,7 @@ function LoginGate({
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{text.auth.password}
|
||||
Password
|
||||
<input
|
||||
autoComplete="current-password"
|
||||
name="password"
|
||||
@@ -94,7 +86,7 @@ function LoginGate({
|
||||
/>
|
||||
</label>
|
||||
<button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting ? text.auth.opening : text.auth.open}
|
||||
{isSubmitting ? 'Opening...' : 'Open panel'}
|
||||
</button>
|
||||
{error ? <p className="form-error">{error}</p> : null}
|
||||
</form>
|
||||
@@ -108,15 +100,12 @@ function AddUserModal({
|
||||
services,
|
||||
onClose,
|
||||
onCreate,
|
||||
preferences,
|
||||
}: {
|
||||
host: string;
|
||||
services: ProxyServiceRecord[];
|
||||
onClose: () => void;
|
||||
onCreate: (input: CreateUserInput) => Promise<void>;
|
||||
preferences: PanelPreferences;
|
||||
}) {
|
||||
const text = getPanelText(preferences.language);
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [serviceId, setServiceId] = useState(services[0]?.id ?? '');
|
||||
@@ -167,22 +156,22 @@ function AddUserModal({
|
||||
onClick={stopPropagation}
|
||||
>
|
||||
<div className="modal-header">
|
||||
<h2 id="add-user-title">{text.users.addUser}</h2>
|
||||
<h2 id="add-user-title">Add user</h2>
|
||||
<button type="button" className="button-secondary" onClick={onClose}>
|
||||
{text.common.close}
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
<form className="modal-form" onSubmit={handleSubmit}>
|
||||
<label>
|
||||
{text.users.username}
|
||||
Username
|
||||
<input autoFocus placeholder="night-shift-01" value={username} onChange={(event) => setUsername(event.target.value)} />
|
||||
</label>
|
||||
<label>
|
||||
{text.users.password}
|
||||
Password
|
||||
<input placeholder="generated-secret" value={password} onChange={(event) => setPassword(event.target.value)} />
|
||||
</label>
|
||||
<label>
|
||||
{text.users.service}
|
||||
Service
|
||||
<select value={serviceId} onChange={(event) => setServiceId(event.target.value)}>
|
||||
{services.map((service) => (
|
||||
<option key={service.id} value={service.id}>
|
||||
@@ -192,23 +181,23 @@ function AddUserModal({
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
{text.users.quotaMb}
|
||||
<input placeholder={text.common.optional} value={quotaMb} onChange={(event) => setQuotaMb(event.target.value)} />
|
||||
Quota (MB)
|
||||
<input placeholder="Optional" value={quotaMb} onChange={(event) => setQuotaMb(event.target.value)} />
|
||||
</label>
|
||||
<div className="modal-preview">
|
||||
<span>{text.common.endpoint}</span>
|
||||
<strong>{selectedService ? `${host}:${selectedService.port}` : text.common.unavailable}</strong>
|
||||
<span>Endpoint</span>
|
||||
<strong>{selectedService ? `${host}:${selectedService.port}` : 'Unavailable'}</strong>
|
||||
</div>
|
||||
<div className="modal-preview">
|
||||
<span>{text.common.protocol}</span>
|
||||
<strong>{selectedService ? selectedService.protocol : text.common.unavailable}</strong>
|
||||
<span>Protocol</span>
|
||||
<strong>{selectedService ? selectedService.protocol : 'Unavailable'}</strong>
|
||||
</div>
|
||||
{error ? <p className="form-error modal-error">{error}</p> : null}
|
||||
<div className="modal-actions">
|
||||
<button type="button" className="button-secondary" onClick={onClose}>
|
||||
{text.common.cancel}
|
||||
Cancel
|
||||
</button>
|
||||
<button type="submit">{text.common.createUser}</button>
|
||||
<button type="submit">Create user</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
@@ -220,14 +209,11 @@ function ConfirmDeleteModal({
|
||||
username,
|
||||
onClose,
|
||||
onConfirm,
|
||||
preferences,
|
||||
}: {
|
||||
username: string;
|
||||
onClose: () => void;
|
||||
onConfirm: () => Promise<void>;
|
||||
preferences: PanelPreferences;
|
||||
}) {
|
||||
const text = getPanelText(preferences.language);
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: globalThis.KeyboardEvent) => {
|
||||
if (event.key === 'Escape') {
|
||||
@@ -254,18 +240,18 @@ function ConfirmDeleteModal({
|
||||
onClick={stopPropagation}
|
||||
>
|
||||
<div className="modal-header">
|
||||
<h2 id="delete-user-title">{text.users.deleteTitle}</h2>
|
||||
<h2 id="delete-user-title">Delete user</h2>
|
||||
</div>
|
||||
<p className="confirm-copy">
|
||||
{text.users.deletePrompt} <strong>{username}</strong>
|
||||
{text.users.deletePromptSuffix}
|
||||
Remove profile <strong>{username}</strong>? This action will delete the user entry from the
|
||||
current panel state.
|
||||
</p>
|
||||
<div className="modal-actions">
|
||||
<button type="button" className="button-secondary" onClick={onClose}>
|
||||
{text.common.cancel}
|
||||
Cancel
|
||||
</button>
|
||||
<button type="button" className="button-danger" onClick={onConfirm}>
|
||||
{text.users.deleteAction}
|
||||
Delete user
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
@@ -276,65 +262,62 @@ function ConfirmDeleteModal({
|
||||
function DashboardTab({
|
||||
snapshot,
|
||||
onRuntimeAction,
|
||||
preferences,
|
||||
}: {
|
||||
snapshot: DashboardSnapshot;
|
||||
onRuntimeAction: (action: 'start' | 'restart') => Promise<void>;
|
||||
preferences: PanelPreferences;
|
||||
}) {
|
||||
const text = getPanelText(preferences.language);
|
||||
const serviceTone = getServiceTone(snapshot.service.status);
|
||||
|
||||
return (
|
||||
<section className="page-grid">
|
||||
<article className="panel-card">
|
||||
<div className="card-header">
|
||||
<h2>{text.dashboard.service}</h2>
|
||||
<span className={`status-pill ${serviceTone}`}>{text.status[snapshot.service.status]}</span>
|
||||
<h2>Service</h2>
|
||||
<span className={`status-pill ${serviceTone}`}>{snapshot.service.status}</span>
|
||||
</div>
|
||||
<dl className="kv-list">
|
||||
<div>
|
||||
<dt>{text.common.process}</dt>
|
||||
<dt>Process</dt>
|
||||
<dd>{snapshot.service.pidLabel}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{text.common.version}</dt>
|
||||
<dt>Version</dt>
|
||||
<dd>{snapshot.service.versionLabel}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{text.common.uptime}</dt>
|
||||
<dt>Uptime</dt>
|
||||
<dd>{snapshot.service.uptimeLabel}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{text.common.lastEvent}</dt>
|
||||
<dt>Last event</dt>
|
||||
<dd>{snapshot.service.lastEvent}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<div className="actions-row">
|
||||
<button type="button" onClick={() => onRuntimeAction('start')}>
|
||||
{text.dashboard.start}
|
||||
Start
|
||||
</button>
|
||||
<button type="button" className="button-secondary" onClick={() => onRuntimeAction('restart')}>
|
||||
{text.dashboard.restart}
|
||||
Restart
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
|
||||
<article className="panel-card">
|
||||
<div className="card-header">
|
||||
<h2>{text.dashboard.traffic}</h2>
|
||||
<h2>Traffic</h2>
|
||||
</div>
|
||||
<div className="stats-strip">
|
||||
<div>
|
||||
<span>{text.common.total}</span>
|
||||
<span>Total</span>
|
||||
<strong>{formatBytes(snapshot.traffic.totalBytes)}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>{text.common.connections}</span>
|
||||
<span>Connections</span>
|
||||
<strong>{snapshot.traffic.liveConnections}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>{text.common.activeUsers}</span>
|
||||
<span>Active users</span>
|
||||
<strong>{snapshot.traffic.activeUsers}</strong>
|
||||
</div>
|
||||
</div>
|
||||
@@ -342,7 +325,7 @@ function DashboardTab({
|
||||
|
||||
<article className="panel-card">
|
||||
<div className="card-header">
|
||||
<h2>{text.dashboard.dailyUsage}</h2>
|
||||
<h2>Daily usage</h2>
|
||||
</div>
|
||||
<div className="usage-list">
|
||||
{snapshot.traffic.daily.map((bucket) => (
|
||||
@@ -359,7 +342,7 @@ function DashboardTab({
|
||||
|
||||
<article className="panel-card">
|
||||
<div className="card-header">
|
||||
<h2>{text.dashboard.attention}</h2>
|
||||
<h2>Attention</h2>
|
||||
</div>
|
||||
<div className="event-list">
|
||||
{snapshot.attention.map((item) => (
|
||||
@@ -382,15 +365,12 @@ function UsersTab({
|
||||
onCreateUser,
|
||||
onTogglePause,
|
||||
onDeleteUser,
|
||||
preferences,
|
||||
}: {
|
||||
snapshot: DashboardSnapshot;
|
||||
onCreateUser: (input: CreateUserInput) => Promise<void>;
|
||||
onTogglePause: (userId: string) => Promise<void>;
|
||||
onDeleteUser: (userId: string) => Promise<void>;
|
||||
preferences: PanelPreferences;
|
||||
}) {
|
||||
const text = getPanelText(preferences.language);
|
||||
const [copiedId, setCopiedId] = useState<string | null>(null);
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
|
||||
@@ -415,37 +395,35 @@ function UsersTab({
|
||||
<article className="panel-card">
|
||||
<div className="table-toolbar">
|
||||
<div className="toolbar-title">
|
||||
<h2>{text.users.title}</h2>
|
||||
<p>
|
||||
{snapshot.userRecords.length} {text.users.accountsInProfile}
|
||||
</p>
|
||||
<h2>Users</h2>
|
||||
<p>{snapshot.userRecords.length} accounts in current profile</p>
|
||||
</div>
|
||||
<div className="toolbar-actions">
|
||||
<div className="summary-pills">
|
||||
<span>{snapshot.users.live} {text.users.live}</span>
|
||||
<span>{snapshot.users.nearQuota} {text.users.nearQuota}</span>
|
||||
<span>{snapshot.users.exceeded} {text.users.exceeded}</span>
|
||||
<span>{snapshot.users.live} live</span>
|
||||
<span>{snapshot.users.nearQuota} near quota</span>
|
||||
<span>{snapshot.users.exceeded} exceeded</span>
|
||||
</div>
|
||||
<button type="button" onClick={() => setIsModalOpen(true)} disabled={assignableServices.length === 0}>
|
||||
{text.users.newUser}
|
||||
New user
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{assignableServices.length === 0 ? (
|
||||
<p className="table-note">{text.users.enableServiceHint}</p>
|
||||
<p className="table-note">Enable an assignable service in System before creating new users.</p>
|
||||
) : null}
|
||||
<div className="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>{text.users.user}</th>
|
||||
<th>{text.users.endpoint}</th>
|
||||
<th>{text.common.status}</th>
|
||||
<th>{text.users.used}</th>
|
||||
<th>{text.users.remaining}</th>
|
||||
<th>{text.users.share}</th>
|
||||
<th>{text.users.proxy}</th>
|
||||
<th>{text.users.actions}</th>
|
||||
<th>User</th>
|
||||
<th>Endpoint</th>
|
||||
<th>Status</th>
|
||||
<th>Used</th>
|
||||
<th>Remaining</th>
|
||||
<th>Share</th>
|
||||
<th>Proxy</th>
|
||||
<th>Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -453,7 +431,7 @@ function UsersTab({
|
||||
const service = servicesById.get(user.serviceId);
|
||||
const endpoint = service
|
||||
? `${snapshot.system.publicHost}:${service.port}`
|
||||
: text.common.serviceMissing;
|
||||
: 'service missing';
|
||||
const proxyLink = service
|
||||
? buildProxyLink(
|
||||
user.username,
|
||||
@@ -475,17 +453,17 @@ function UsersTab({
|
||||
</td>
|
||||
<td>
|
||||
<div className="endpoint-cell">
|
||||
<strong>{service?.name ?? text.common.unknownService}</strong>
|
||||
<strong>{service?.name ?? 'Unknown service'}</strong>
|
||||
<span>{endpoint}</span>
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<span className={`status-pill ${getServiceTone(displayStatus)}`}>
|
||||
{text.status[displayStatus]}
|
||||
{displayStatus}
|
||||
</span>
|
||||
</td>
|
||||
<td>{formatBytes(user.usedBytes)}</td>
|
||||
<td>{formatQuotaStateLabel(user.usedBytes, user.quotaBytes, preferences.language)}</td>
|
||||
<td>{formatQuotaState(user.usedBytes, user.quotaBytes)}</td>
|
||||
<td>{formatTrafficShare(user.usedBytes, snapshot.traffic.totalBytes)}</td>
|
||||
<td>
|
||||
<button
|
||||
@@ -494,7 +472,7 @@ function UsersTab({
|
||||
onClick={() => handleCopy(user.id, proxyLink)}
|
||||
disabled={!service}
|
||||
>
|
||||
{copiedId === user.id ? text.common.copied : text.common.copy}
|
||||
{copiedId === user.id ? 'Copied' : 'Copy'}
|
||||
</button>
|
||||
</td>
|
||||
<td>
|
||||
@@ -504,14 +482,14 @@ function UsersTab({
|
||||
className="button-secondary button-small"
|
||||
onClick={() => onTogglePause(user.id)}
|
||||
>
|
||||
{user.paused ? text.users.resume : text.users.pause}
|
||||
{user.paused ? 'Resume' : 'Pause'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="button-danger button-small"
|
||||
onClick={() => setDeleteTargetId(user.id)}
|
||||
>
|
||||
{text.common.delete}
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
@@ -530,7 +508,6 @@ function UsersTab({
|
||||
services={assignableServices}
|
||||
onClose={() => setIsModalOpen(false)}
|
||||
onCreate={onCreateUser}
|
||||
preferences={preferences}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
@@ -542,7 +519,6 @@ function UsersTab({
|
||||
await onDeleteUser(deleteTarget.id);
|
||||
setDeleteTargetId(null);
|
||||
}}
|
||||
preferences={preferences}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
@@ -550,24 +526,9 @@ function UsersTab({
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const [preferences, setPreferences] = useState<PanelPreferences>(() => loadPanelPreferences());
|
||||
const [session, setSession] = useState<StoredSession | null>(() => loadStoredSession());
|
||||
const [activeTab, setActiveTab] = useState<TabId>('dashboard');
|
||||
const [snapshot, setSnapshot] = useState<DashboardSnapshot>(fallbackDashboardSnapshot);
|
||||
const text = getPanelText(preferences.language);
|
||||
|
||||
useEffect(() => {
|
||||
applyPanelTheme(preferences.theme);
|
||||
savePanelPreferences(preferences);
|
||||
}, [preferences]);
|
||||
|
||||
useEffect(() => {
|
||||
if (preferences.theme !== 'system') {
|
||||
return;
|
||||
}
|
||||
|
||||
return observeSystemTheme(() => applyPanelTheme('system'));
|
||||
}, [preferences.theme]);
|
||||
|
||||
const resetSession = () => {
|
||||
clearStoredSession();
|
||||
@@ -644,7 +605,7 @@ export default function App() {
|
||||
}, [session]);
|
||||
|
||||
if (!session) {
|
||||
return <LoginGate onUnlock={handleUnlock} preferences={preferences} />;
|
||||
return <LoginGate onUnlock={handleUnlock} />;
|
||||
}
|
||||
|
||||
const mutateSnapshot = async (
|
||||
@@ -799,7 +760,6 @@ export default function App() {
|
||||
}
|
||||
|
||||
if (!payload) {
|
||||
const nextServiceIds = new Set(input.services.map((service) => service.id));
|
||||
setSnapshot((current) =>
|
||||
withDerivedSnapshot({
|
||||
...current,
|
||||
@@ -807,7 +767,6 @@ export default function App() {
|
||||
...current.service,
|
||||
lastEvent: 'System configuration updated from panel',
|
||||
},
|
||||
userRecords: current.userRecords.filter((user) => nextServiceIds.has(user.serviceId)),
|
||||
system: {
|
||||
...input,
|
||||
previewConfig: current.system.previewConfig,
|
||||
@@ -829,15 +788,15 @@ export default function App() {
|
||||
</div>
|
||||
<div className="header-meta">
|
||||
<div>
|
||||
<span>{text.common.status}</span>
|
||||
<strong>{text.status[snapshot.service.status]}</strong>
|
||||
<span>Status</span>
|
||||
<strong>{snapshot.service.status}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>{text.common.version}</span>
|
||||
<span>Version</span>
|
||||
<strong>{snapshot.service.versionLabel}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>{text.common.users}</span>
|
||||
<span>Users</span>
|
||||
<strong>{snapshot.users.total}</strong>
|
||||
</div>
|
||||
<button
|
||||
@@ -845,7 +804,7 @@ export default function App() {
|
||||
className="button-secondary"
|
||||
onClick={resetSession}
|
||||
>
|
||||
{text.common.signOut}
|
||||
Sign out
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
@@ -858,31 +817,21 @@ export default function App() {
|
||||
className={activeTab === tab.id ? 'tab-button active' : 'tab-button'}
|
||||
onClick={() => setActiveTab(tab.id)}
|
||||
>
|
||||
{text.tabs[tab.textKey]}
|
||||
{tab.label}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
{activeTab === 'dashboard' ? (
|
||||
<DashboardTab snapshot={snapshot} onRuntimeAction={handleRuntimeAction} preferences={preferences} />
|
||||
) : null}
|
||||
{activeTab === 'dashboard' ? <DashboardTab snapshot={snapshot} onRuntimeAction={handleRuntimeAction} /> : null}
|
||||
{activeTab === 'users' ? (
|
||||
<UsersTab
|
||||
snapshot={snapshot}
|
||||
onCreateUser={handleCreateUser}
|
||||
onTogglePause={handleTogglePause}
|
||||
onDeleteUser={handleDeleteUser}
|
||||
preferences={preferences}
|
||||
/>
|
||||
) : null}
|
||||
{activeTab === 'system' ? (
|
||||
<SystemTab
|
||||
snapshot={snapshot}
|
||||
preferences={preferences}
|
||||
onPreferencesChange={setPreferences}
|
||||
onSaveSystem={handleSaveSystem}
|
||||
/>
|
||||
) : null}
|
||||
{activeTab === 'system' ? <SystemTab snapshot={snapshot} onSaveSystem={handleSaveSystem} /> : null}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -915,26 +864,6 @@ function withDerivedSnapshot(snapshot: DashboardSnapshot): DashboardSnapshot {
|
||||
};
|
||||
}
|
||||
|
||||
function formatQuotaStateLabel(
|
||||
usedBytes: number,
|
||||
quotaBytes: number | null,
|
||||
language: PanelPreferences['language'],
|
||||
): string {
|
||||
const text = getPanelText(language);
|
||||
|
||||
if (quotaBytes === null) {
|
||||
return text.common.unlimited;
|
||||
}
|
||||
|
||||
const remaining = quotaBytes - usedBytes;
|
||||
|
||||
if (remaining <= 0) {
|
||||
return text.common.exceeded;
|
||||
}
|
||||
|
||||
return `${formatBytes(remaining)} ${text.common.left}`;
|
||||
}
|
||||
|
||||
async function requestSnapshot(request: () => Promise<Response>): Promise<DashboardSnapshot | null> {
|
||||
try {
|
||||
const response = await request();
|
||||
|
||||
@@ -1,48 +1,22 @@
|
||||
import { FormEvent, useEffect, useMemo, useState } from 'react';
|
||||
import { FormEvent, useEffect, useState } from 'react';
|
||||
import type { DashboardSnapshot, ProxyServiceRecord, SystemSettings, UpdateSystemInput } from './shared/contracts';
|
||||
import type { PanelLanguage, PanelPreferences, PanelTheme } from './lib/panelPreferences';
|
||||
import { getPanelText, getThemeLabel } from './lib/panelText';
|
||||
import { getProtocolForCommand, validateSystemInput } from './shared/validation';
|
||||
|
||||
interface SystemTabProps {
|
||||
snapshot: DashboardSnapshot;
|
||||
preferences: PanelPreferences;
|
||||
onPreferencesChange: (next: PanelPreferences) => void;
|
||||
onSaveSystem: (input: UpdateSystemInput) => Promise<void>;
|
||||
}
|
||||
|
||||
export default function SystemTab({
|
||||
snapshot,
|
||||
preferences,
|
||||
onPreferencesChange,
|
||||
onSaveSystem,
|
||||
}: SystemTabProps) {
|
||||
export default function SystemTab({ snapshot, onSaveSystem }: SystemTabProps) {
|
||||
const [draft, setDraft] = useState<UpdateSystemInput>(() => cloneSystemSettings(snapshot.system));
|
||||
const [error, setError] = useState('');
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [removeServiceId, setRemoveServiceId] = useState<string | null>(null);
|
||||
const text = getPanelText(preferences.language);
|
||||
|
||||
useEffect(() => {
|
||||
setDraft(cloneSystemSettings(snapshot.system));
|
||||
setError('');
|
||||
}, [snapshot.system]);
|
||||
|
||||
const linkedUsersByService = useMemo(() => {
|
||||
const result = new Map<string, string[]>();
|
||||
|
||||
snapshot.userRecords.forEach((user) => {
|
||||
const usernames = result.get(user.serviceId) ?? [];
|
||||
usernames.push(user.username);
|
||||
result.set(user.serviceId, usernames);
|
||||
});
|
||||
|
||||
return result;
|
||||
}, [snapshot.userRecords]);
|
||||
|
||||
const removeTarget = draft.services.find((service) => service.id === removeServiceId) ?? null;
|
||||
const removeTargetUsers = removeTarget ? linkedUsersByService.get(removeTarget.id) ?? [] : [];
|
||||
|
||||
const updateService = (serviceId: string, updater: (service: ProxyServiceRecord) => ProxyServiceRecord) => {
|
||||
setDraft((current) => ({
|
||||
...current,
|
||||
@@ -56,9 +30,7 @@ export default function SystemTab({
|
||||
setError('');
|
||||
|
||||
try {
|
||||
const nextServiceIds = new Set(draft.services.map((service) => service.id));
|
||||
const remainingUsers = snapshot.userRecords.filter((user) => nextServiceIds.has(user.serviceId));
|
||||
const validated = validateSystemInput(draft, remainingUsers);
|
||||
const validated = validateSystemInput(draft, snapshot.userRecords);
|
||||
await onSaveSystem(validated);
|
||||
} catch (submitError) {
|
||||
setError(submitError instanceof Error ? submitError.message : 'Unable to save system settings.');
|
||||
@@ -68,51 +40,51 @@ export default function SystemTab({
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<form className="system-editor" onSubmit={handleSubmit}>
|
||||
<section className="page-grid single-column system-grid">
|
||||
<article className="panel-card">
|
||||
<article className="panel-card system-settings-card">
|
||||
<div className="card-header">
|
||||
<h2>{text.common.panelPreferences}</h2>
|
||||
<h2>Panel settings</h2>
|
||||
</div>
|
||||
<div className="system-fields">
|
||||
<label className="field-group">
|
||||
{text.common.language}
|
||||
<select
|
||||
value={preferences.language}
|
||||
onChange={(event) =>
|
||||
onPreferencesChange({
|
||||
...preferences,
|
||||
language: event.target.value as PanelLanguage,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="en">{text.common.english}</option>
|
||||
<option value="ru">{text.common.russian}</option>
|
||||
</select>
|
||||
Public host
|
||||
<input
|
||||
value={draft.publicHost}
|
||||
onChange={(event) => setDraft((current) => ({ ...current, publicHost: event.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
<label className="field-group">
|
||||
{text.common.theme}
|
||||
<select
|
||||
value={preferences.theme}
|
||||
onChange={(event) =>
|
||||
onPreferencesChange({
|
||||
...preferences,
|
||||
theme: event.target.value as PanelTheme,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="light">{getThemeLabel(preferences.language, 'light')}</option>
|
||||
<option value="dark">{getThemeLabel(preferences.language, 'dark')}</option>
|
||||
<option value="system">{getThemeLabel(preferences.language, 'system')}</option>
|
||||
</select>
|
||||
Config mode
|
||||
<input
|
||||
value={draft.configMode}
|
||||
onChange={(event) => setDraft((current) => ({ ...current, configMode: event.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
<label className="field-group">
|
||||
Reload mode
|
||||
<input
|
||||
value={draft.reloadMode}
|
||||
onChange={(event) => setDraft((current) => ({ ...current, reloadMode: event.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
<label className="field-group">
|
||||
Storage mode
|
||||
<input
|
||||
value={draft.storageMode}
|
||||
onChange={(event) => setDraft((current) => ({ ...current, storageMode: event.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<p className="system-hint">
|
||||
These values describe how the panel generates and reloads the 3proxy config. Saving keeps
|
||||
existing users attached only to enabled assignable services.
|
||||
</p>
|
||||
</article>
|
||||
|
||||
<article className="panel-card">
|
||||
<div className="card-header">
|
||||
<h2>{text.settings.title}</h2>
|
||||
<h2>Services</h2>
|
||||
<button
|
||||
type="button"
|
||||
className="button-secondary"
|
||||
@@ -123,7 +95,7 @@ export default function SystemTab({
|
||||
}))
|
||||
}
|
||||
>
|
||||
{text.common.addService}
|
||||
Add service
|
||||
</button>
|
||||
</div>
|
||||
<div className="service-editor-list">
|
||||
@@ -131,22 +103,25 @@ export default function SystemTab({
|
||||
<section key={service.id} className="service-editor-row">
|
||||
<div className="service-editor-header">
|
||||
<div>
|
||||
<strong>
|
||||
{text.settings.serviceLabel} {index + 1}
|
||||
</strong>
|
||||
<strong>Service {index + 1}</strong>
|
||||
<p>{service.id}</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="button-secondary button-small"
|
||||
onClick={() => setRemoveServiceId(service.id)}
|
||||
onClick={() =>
|
||||
setDraft((current) => ({
|
||||
...current,
|
||||
services: current.services.filter((entry) => entry.id !== service.id),
|
||||
}))
|
||||
}
|
||||
>
|
||||
{text.common.remove}
|
||||
Remove
|
||||
</button>
|
||||
</div>
|
||||
<div className="service-editor-grid">
|
||||
<label className="field-group">
|
||||
{text.settings.name}
|
||||
Name
|
||||
<input
|
||||
value={service.name}
|
||||
onChange={(event) =>
|
||||
@@ -155,7 +130,7 @@ export default function SystemTab({
|
||||
/>
|
||||
</label>
|
||||
<label className="field-group">
|
||||
{text.settings.port}
|
||||
Port
|
||||
<input
|
||||
inputMode="numeric"
|
||||
value={String(service.port)}
|
||||
@@ -168,7 +143,7 @@ export default function SystemTab({
|
||||
/>
|
||||
</label>
|
||||
<label className="field-group">
|
||||
{text.settings.serviceType}
|
||||
Command
|
||||
<select
|
||||
value={service.command}
|
||||
onChange={(event) =>
|
||||
@@ -183,13 +158,17 @@ export default function SystemTab({
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="socks">{text.settings.typeSocks}</option>
|
||||
<option value="proxy">{text.settings.typeProxy}</option>
|
||||
<option value="admin">{text.settings.typeAdmin}</option>
|
||||
<option value="socks">socks</option>
|
||||
<option value="proxy">proxy</option>
|
||||
<option value="admin">admin</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="field-group">
|
||||
Protocol
|
||||
<input value={service.protocol} readOnly />
|
||||
</label>
|
||||
<label className="field-group field-span-2">
|
||||
{text.settings.description}
|
||||
Description
|
||||
<input
|
||||
value={service.description}
|
||||
onChange={(event) =>
|
||||
@@ -213,7 +192,7 @@ export default function SystemTab({
|
||||
}))
|
||||
}
|
||||
/>
|
||||
{text.common.enabled}
|
||||
Enabled
|
||||
</label>
|
||||
<label className="toggle-check">
|
||||
<input
|
||||
@@ -227,7 +206,7 @@ export default function SystemTab({
|
||||
}))
|
||||
}
|
||||
/>
|
||||
{text.common.assignable}
|
||||
Assignable to users
|
||||
</label>
|
||||
</div>
|
||||
</section>
|
||||
@@ -243,66 +222,22 @@ export default function SystemTab({
|
||||
setError('');
|
||||
}}
|
||||
>
|
||||
{text.common.reset}
|
||||
Reset
|
||||
</button>
|
||||
<button type="submit" disabled={isSaving}>
|
||||
{isSaving ? `${text.common.save}...` : text.common.saveSettings}
|
||||
{isSaving ? 'Saving...' : 'Save system'}
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
|
||||
<article className="panel-card wide-card">
|
||||
<div className="card-header">
|
||||
<h2>{text.settings.generatedConfig}</h2>
|
||||
<h2>Generated config</h2>
|
||||
</div>
|
||||
<pre>{snapshot.system.previewConfig}</pre>
|
||||
</article>
|
||||
</section>
|
||||
</form>
|
||||
|
||||
{removeTarget ? (
|
||||
<div className="modal-backdrop" role="presentation" onClick={() => setRemoveServiceId(null)}>
|
||||
<section
|
||||
aria-labelledby="remove-service-title"
|
||||
aria-modal="true"
|
||||
className="modal-card confirm-card"
|
||||
role="dialog"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<div className="modal-header">
|
||||
<h2 id="remove-service-title">{text.settings.serviceRemoveTitle}</h2>
|
||||
</div>
|
||||
<p className="confirm-copy">
|
||||
<strong>{removeTarget.name}</strong>{' '}
|
||||
{removeTargetUsers.length > 0 ? text.settings.removeWarningUsers : text.settings.removeWarningNone}
|
||||
</p>
|
||||
{removeTargetUsers.length > 0 ? (
|
||||
<p className="confirm-copy">
|
||||
{text.settings.removeWarningCount} {removeTargetUsers.join(', ')}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="modal-actions">
|
||||
<button type="button" className="button-secondary" onClick={() => setRemoveServiceId(null)}>
|
||||
{text.common.cancel}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="button-danger"
|
||||
onClick={() => {
|
||||
setDraft((current) => ({
|
||||
...current,
|
||||
services: current.services.filter((service) => service.id !== removeTarget.id),
|
||||
}));
|
||||
setRemoveServiceId(null);
|
||||
}}
|
||||
>
|
||||
{text.common.remove}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
25
src/app.css
25
src/app.css
@@ -22,23 +22,6 @@
|
||||
--shadow: 0 1px 2px rgba(17, 24, 39, 0.04);
|
||||
}
|
||||
|
||||
:root[data-theme='dark'] {
|
||||
color-scheme: dark;
|
||||
--page-bg: #111827;
|
||||
--surface: #18212f;
|
||||
--surface-muted: #1f2937;
|
||||
--border: #334155;
|
||||
--border-strong: #475569;
|
||||
--text: #f8fafc;
|
||||
--muted: #94a3b8;
|
||||
--accent: #60a5fa;
|
||||
--accent-muted: rgba(96, 165, 250, 0.15);
|
||||
--success: #4ade80;
|
||||
--warning: #fbbf24;
|
||||
--danger: #f87171;
|
||||
--shadow: 0 1px 2px rgba(2, 6, 23, 0.35);
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
@@ -389,13 +372,13 @@ button,
|
||||
.usage-bar {
|
||||
height: 8px;
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--border) 70%, transparent);
|
||||
background: #eceff3;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.usage-bar div {
|
||||
height: 100%;
|
||||
background: color-mix(in srgb, var(--accent) 55%, var(--muted));
|
||||
background: #94a3b8;
|
||||
}
|
||||
|
||||
.event-row,
|
||||
@@ -625,8 +608,8 @@ pre {
|
||||
overflow: auto;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
background: color-mix(in srgb, var(--surface-muted) 80%, var(--surface));
|
||||
color: var(--text);
|
||||
background: #fbfbfc;
|
||||
color: #1f2937;
|
||||
font: 13px/1.55 Consolas, "Courier New", monospace;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
export type PanelLanguage = 'en' | 'ru';
|
||||
export type PanelTheme = 'light' | 'dark' | 'system';
|
||||
|
||||
export interface PanelPreferences {
|
||||
language: PanelLanguage;
|
||||
theme: PanelTheme;
|
||||
}
|
||||
|
||||
const PREFERENCES_KEY = '3proxy-ui-panel-preferences';
|
||||
|
||||
export const defaultPanelPreferences: PanelPreferences = {
|
||||
language: 'en',
|
||||
theme: 'system',
|
||||
};
|
||||
|
||||
export function loadPanelPreferences(): PanelPreferences {
|
||||
try {
|
||||
const raw = window.localStorage.getItem(PREFERENCES_KEY);
|
||||
|
||||
if (!raw) {
|
||||
return defaultPanelPreferences;
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(raw) as Partial<PanelPreferences>;
|
||||
|
||||
return {
|
||||
language: parsed.language === 'ru' ? 'ru' : 'en',
|
||||
theme: isPanelTheme(parsed.theme) ? parsed.theme : defaultPanelPreferences.theme,
|
||||
};
|
||||
} catch {
|
||||
return defaultPanelPreferences;
|
||||
}
|
||||
}
|
||||
|
||||
export function savePanelPreferences(preferences: PanelPreferences): void {
|
||||
window.localStorage.setItem(PREFERENCES_KEY, JSON.stringify(preferences));
|
||||
}
|
||||
|
||||
export function applyPanelTheme(theme: PanelTheme): void {
|
||||
document.documentElement.dataset.theme = resolvePanelTheme(theme);
|
||||
}
|
||||
|
||||
export function observeSystemTheme(onChange: () => void): () => void {
|
||||
if (typeof window.matchMedia !== 'function') {
|
||||
return () => undefined;
|
||||
}
|
||||
|
||||
const media = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
const listener = () => onChange();
|
||||
|
||||
if (typeof media.addEventListener === 'function') {
|
||||
media.addEventListener('change', listener);
|
||||
return () => media.removeEventListener('change', listener);
|
||||
}
|
||||
|
||||
media.addListener(listener);
|
||||
return () => media.removeListener(listener);
|
||||
}
|
||||
|
||||
function resolvePanelTheme(theme: PanelTheme): 'light' | 'dark' {
|
||||
if (theme === 'light' || theme === 'dark') {
|
||||
return theme;
|
||||
}
|
||||
|
||||
if (typeof window.matchMedia === 'function') {
|
||||
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
}
|
||||
|
||||
return 'light';
|
||||
}
|
||||
|
||||
function isPanelTheme(value: unknown): value is PanelTheme {
|
||||
return value === 'light' || value === 'dark' || value === 'system';
|
||||
}
|
||||
@@ -1,269 +0,0 @@
|
||||
import type { ServiceCommand } from '../shared/contracts';
|
||||
import type { PanelLanguage, PanelTheme } from './panelPreferences';
|
||||
|
||||
const text = {
|
||||
en: {
|
||||
tabs: {
|
||||
dashboard: 'Dashboard',
|
||||
users: 'Users',
|
||||
settings: 'Settings',
|
||||
},
|
||||
auth: {
|
||||
title: '3proxy UI',
|
||||
subtitle: 'Sign in to the control panel.',
|
||||
login: 'Login',
|
||||
password: 'Password',
|
||||
open: 'Open panel',
|
||||
opening: 'Opening...',
|
||||
},
|
||||
common: {
|
||||
close: 'Close',
|
||||
cancel: 'Cancel',
|
||||
reset: 'Reset',
|
||||
save: 'Save',
|
||||
saveSettings: 'Save settings',
|
||||
signOut: 'Sign out',
|
||||
addService: 'Add service',
|
||||
remove: 'Remove',
|
||||
delete: 'Delete',
|
||||
deleteUser: 'Delete user',
|
||||
copy: 'Copy',
|
||||
copied: 'Copied',
|
||||
createUser: 'Create user',
|
||||
create: 'Create',
|
||||
endpoint: 'Endpoint',
|
||||
protocol: 'Protocol',
|
||||
status: 'Status',
|
||||
version: 'Version',
|
||||
users: 'Users',
|
||||
enabled: 'Enabled',
|
||||
assignable: 'Assignable to users',
|
||||
unavailable: 'Unavailable',
|
||||
unknownService: 'Unknown service',
|
||||
serviceMissing: 'service missing',
|
||||
optional: 'Optional',
|
||||
activeUsers: 'Active users',
|
||||
total: 'Total',
|
||||
connections: 'Connections',
|
||||
process: 'Process',
|
||||
uptime: 'Uptime',
|
||||
lastEvent: 'Last event',
|
||||
settingsSaved: 'Settings updated from panel',
|
||||
left: 'left',
|
||||
unlimited: 'Unlimited',
|
||||
exceeded: 'Exceeded',
|
||||
panelPreferences: 'Panel preferences',
|
||||
language: 'Panel language',
|
||||
theme: 'Panel style',
|
||||
english: 'English',
|
||||
russian: 'Russian',
|
||||
light: 'Light',
|
||||
dark: 'Dark',
|
||||
system: 'System',
|
||||
},
|
||||
dashboard: {
|
||||
service: 'Service',
|
||||
traffic: 'Traffic',
|
||||
dailyUsage: 'Daily usage',
|
||||
attention: 'Attention',
|
||||
start: 'Start',
|
||||
restart: 'Restart',
|
||||
},
|
||||
users: {
|
||||
title: 'Users',
|
||||
accountsInProfile: 'accounts in current profile',
|
||||
newUser: 'New user',
|
||||
live: 'live',
|
||||
nearQuota: 'near quota',
|
||||
exceeded: 'exceeded',
|
||||
enableServiceHint: 'Enable an assignable service in Settings before creating new users.',
|
||||
user: 'User',
|
||||
endpoint: 'Endpoint',
|
||||
used: 'Used',
|
||||
remaining: 'Remaining',
|
||||
share: 'Share',
|
||||
proxy: 'Proxy',
|
||||
actions: 'Actions',
|
||||
addUser: 'Add user',
|
||||
username: 'Username',
|
||||
password: 'Password',
|
||||
service: 'Service',
|
||||
quotaMb: 'Quota (MB)',
|
||||
pause: 'Pause',
|
||||
resume: 'Resume',
|
||||
deleteTitle: 'Delete user',
|
||||
deletePrompt: 'Remove profile',
|
||||
deletePromptSuffix: '? This action will delete the user entry from the current panel state.',
|
||||
cancel: 'Cancel',
|
||||
deleteAction: 'Delete user',
|
||||
},
|
||||
settings: {
|
||||
title: 'Services',
|
||||
generatedConfig: 'Generated config',
|
||||
serviceLabel: 'Service',
|
||||
serviceType: 'Type',
|
||||
typeSocks: 'SOCKS5 proxy',
|
||||
typeProxy: 'HTTP proxy',
|
||||
typeAdmin: 'Admin interface',
|
||||
name: 'Name',
|
||||
port: 'Port',
|
||||
description: 'Description',
|
||||
serviceRemoveTitle: 'Delete service',
|
||||
removeWarningNone: 'Delete this service from the panel configuration?',
|
||||
removeWarningUsers: 'Delete this service and remove all linked users?',
|
||||
removeWarningCount: 'Linked users to be removed:',
|
||||
},
|
||||
status: {
|
||||
live: 'live',
|
||||
warn: 'warn',
|
||||
fail: 'fail',
|
||||
idle: 'idle',
|
||||
paused: 'paused',
|
||||
enabled: 'enabled',
|
||||
disabled: 'disabled',
|
||||
},
|
||||
},
|
||||
ru: {
|
||||
tabs: {
|
||||
dashboard: 'Панель',
|
||||
users: 'Пользователи',
|
||||
settings: 'Настройки',
|
||||
},
|
||||
auth: {
|
||||
title: '3proxy UI',
|
||||
subtitle: 'Войдите в панель управления.',
|
||||
login: 'Логин',
|
||||
password: 'Пароль',
|
||||
open: 'Открыть панель',
|
||||
opening: 'Открываем...',
|
||||
},
|
||||
common: {
|
||||
close: 'Закрыть',
|
||||
cancel: 'Отмена',
|
||||
reset: 'Сбросить',
|
||||
save: 'Сохранить',
|
||||
saveSettings: 'Сохранить настройки',
|
||||
signOut: 'Выйти',
|
||||
addService: 'Добавить сервис',
|
||||
remove: 'Удалить',
|
||||
delete: 'Удалить',
|
||||
deleteUser: 'Удалить пользователя',
|
||||
copy: 'Копировать',
|
||||
copied: 'Скопировано',
|
||||
createUser: 'Создать пользователя',
|
||||
create: 'Создать',
|
||||
endpoint: 'Точка входа',
|
||||
protocol: 'Протокол',
|
||||
status: 'Статус',
|
||||
version: 'Версия',
|
||||
users: 'Пользователи',
|
||||
enabled: 'Включен',
|
||||
assignable: 'Можно назначать пользователям',
|
||||
unavailable: 'Недоступно',
|
||||
unknownService: 'Неизвестный сервис',
|
||||
serviceMissing: 'сервис отсутствует',
|
||||
optional: 'Необязательно',
|
||||
activeUsers: 'Активные пользователи',
|
||||
total: 'Всего',
|
||||
connections: 'Соединения',
|
||||
process: 'Процесс',
|
||||
uptime: 'Время работы',
|
||||
lastEvent: 'Последнее событие',
|
||||
settingsSaved: 'Настройки обновлены из панели',
|
||||
left: 'осталось',
|
||||
unlimited: 'Без лимита',
|
||||
exceeded: 'Превышено',
|
||||
panelPreferences: 'Параметры панели',
|
||||
language: 'Язык панели',
|
||||
theme: 'Стиль панели',
|
||||
english: 'Английский',
|
||||
russian: 'Русский',
|
||||
light: 'Светлый',
|
||||
dark: 'Темный',
|
||||
system: 'Системный',
|
||||
},
|
||||
dashboard: {
|
||||
service: 'Сервис',
|
||||
traffic: 'Трафик',
|
||||
dailyUsage: 'Дневное использование',
|
||||
attention: 'Внимание',
|
||||
start: 'Запустить',
|
||||
restart: 'Перезапустить',
|
||||
},
|
||||
users: {
|
||||
title: 'Пользователи',
|
||||
accountsInProfile: 'аккаунтов в текущем профиле',
|
||||
newUser: 'Новый пользователь',
|
||||
live: 'в работе',
|
||||
nearQuota: 'близко к лимиту',
|
||||
exceeded: 'превышено',
|
||||
enableServiceHint: 'Сначала включите назначаемый сервис во вкладке Настройки.',
|
||||
user: 'Пользователь',
|
||||
endpoint: 'Точка входа',
|
||||
used: 'Использовано',
|
||||
remaining: 'Остаток',
|
||||
share: 'Доля',
|
||||
proxy: 'Прокси',
|
||||
actions: 'Действия',
|
||||
addUser: 'Добавить пользователя',
|
||||
username: 'Имя пользователя',
|
||||
password: 'Пароль',
|
||||
service: 'Сервис',
|
||||
quotaMb: 'Лимит (МБ)',
|
||||
pause: 'Пауза',
|
||||
resume: 'Возобновить',
|
||||
deleteTitle: 'Удаление пользователя',
|
||||
deletePrompt: 'Удалить профиль',
|
||||
deletePromptSuffix: '? Это действие удалит пользователя из текущего состояния панели.',
|
||||
cancel: 'Отмена',
|
||||
deleteAction: 'Удалить пользователя',
|
||||
},
|
||||
settings: {
|
||||
title: 'Сервисы',
|
||||
generatedConfig: 'Сгенерированный конфиг',
|
||||
serviceLabel: 'Сервис',
|
||||
serviceType: 'Тип',
|
||||
typeSocks: 'SOCKS5 прокси',
|
||||
typeProxy: 'HTTP прокси',
|
||||
typeAdmin: 'Админ-интерфейс',
|
||||
name: 'Название',
|
||||
port: 'Порт',
|
||||
description: 'Описание',
|
||||
serviceRemoveTitle: 'Удаление сервиса',
|
||||
removeWarningNone: 'Удалить этот сервис из конфигурации панели?',
|
||||
removeWarningUsers: 'Удалить этот сервис и всех связанных с ним пользователей?',
|
||||
removeWarningCount: 'Будут удалены пользователи:',
|
||||
},
|
||||
status: {
|
||||
live: 'в работе',
|
||||
warn: 'предупреждение',
|
||||
fail: 'ошибка',
|
||||
idle: 'ожидание',
|
||||
paused: 'пауза',
|
||||
enabled: 'включен',
|
||||
disabled: 'выключен',
|
||||
},
|
||||
},
|
||||
} as const;
|
||||
|
||||
export function getPanelText(language: PanelLanguage) {
|
||||
return text[language];
|
||||
}
|
||||
|
||||
export function getThemeLabel(language: PanelLanguage, theme: PanelTheme): string {
|
||||
const t = getPanelText(language);
|
||||
return theme === 'light' ? t.common.light : theme === 'dark' ? t.common.dark : t.common.system;
|
||||
}
|
||||
|
||||
export function getServiceTypeLabel(language: PanelLanguage, command: ServiceCommand): string {
|
||||
const t = getPanelText(language);
|
||||
if (command === 'socks') {
|
||||
return t.settings.typeSocks;
|
||||
}
|
||||
|
||||
if (command === 'proxy') {
|
||||
return t.settings.typeProxy;
|
||||
}
|
||||
|
||||
return t.settings.typeAdmin;
|
||||
}
|
||||
Reference in New Issue
Block a user