AGH-234 Make client settings independent of global settings

This commit is contained in:
Ildar Kamalov authored and GitHub committed 2026-11-02 16:37:43 +03:00
1 parent 70203651c0
commit 3e0cb52b18
29 files changed
+1050 -353

No files matched your search

+9
View File
@@ -22,6 +22,10 @@ NOTE: Add new changes BELOW THIS COMMENT.
- Go version has been updated to prevent the possibility of exploiting the Go vulnerabilities fixed in [1.27.3][go-1.27.3].
### Changed
- Client settings in the new web interface: *Use global settings* now applies to Protection only, blocked services have a separate *Use global blocked services* switch, and upstream DNS servers and the DNS cache are always editable.
### Fixed
- Invalid SVCB record from DDR when DoH routes are empty.
@@ -64,6 +68,10 @@ NOTE: Add new changes BELOW THIS COMMENT.
- The *Log out* button opening the login page in a new tab in the new web interface ([#8661]).
- Per-client blocked services schedules being reset when a client was saved in the new web interface ([#8638]).
- Client sub-pages of the new web interface showing the default values instead of the client's settings when opened directly or reloaded.
### Removed
- The support for macOS 13 Ventura, see [Go 1.27 release notes][go-1.27-notes].
@@ -77,6 +85,7 @@ NOTE: Add new changes BELOW THIS COMMENT.
[#8613]: https://github.com/AdguardTeam/AdGuardHome/issues/8613
[#8636]: https://github.com/AdguardTeam/AdGuardHome/issues/8636
[#8637]: https://github.com/AdguardTeam/AdGuardHome/issues/8637
[#8638]: https://github.com/AdguardTeam/AdGuardHome/issues/8638
[#8644]: https://github.com/AdguardTeam/AdGuardHome/issues/8644
[#8661]: https://github.com/AdguardTeam/AdGuardHome/issues/8661
[go-1.27.3]: https://groups.google.com/g/golang-announce/c/66pojueaQek
+6 -2
View File
@@ -102,6 +102,8 @@
"clients_dont_collect_stats": "Don't collect stats for this client",
"clients_dont_log": "Don't log this client",
"clients_edit": "Edit client",
"clients_global_blocked_services_note": "Global settings are used to configure blocked services",
"clients_global_inactivity_schedule_note": "Global settings are used to configure the inactivity schedule",
"clients_identifier_already_used": "This identifier is already used",
"clients_identifier_format_error": "Use numbers, lowercase English letters, or hyphens",
"clients_identifiers": "Identifiers",
@@ -118,8 +120,10 @@
"clients_title": "Persistent",
"clients_upstreams_desc": "Upstream DNS servers, one per line",
"clients_use_dns_cache": "Use DNS cache",
"clients_use_global_settings": "Use global settings",
"clients_use_global_settings_desc": "Inherit protection settings from your AdGuard Home account",
"clients_use_global_blocked_services": "Use global blocked services",
"clients_use_global_blocked_services_desc": "Use the global blocked services list for this client",
"clients_use_global_settings": "Use global settings for Protection",
"clients_use_global_settings_desc": "Apply the global general and DNS settings to this client for DNS filtering, Safe search, Safe browsing, and Parental control",
"close": "Close",
"close_result": "Close result",
"confirm_client_block_desc": "AdGuard Home will be dropping all DNS requests from the client <strong>%ip%</strong>",
@@ -1,31 +1,49 @@
import { describe, expect, it } from 'vitest';
import { buildClientConfig } from 'panel/stores/clientForm';
import { buildClientConfig, buildFormPayload } from 'panel/stores/clientForm';
import { getInitialClientFormState } from 'panel/initialState';
describe('buildClientConfig', () => {
it('syncs use_global_blocked_services from use_global_settings=true', () => {
it('keeps use_global_blocked_services independent of use_global_settings', () => {
const form = {
...getInitialClientFormState(),
use_global_settings: true,
use_global_blocked_services: false,
};
const config = buildClientConfig(form);
expect(config.use_global_blocked_services).toBe(true);
expect(config.use_global_blocked_services).toBe(false);
expect(config.use_global_settings).toBe(true);
});
it('syncs use_global_blocked_services from use_global_settings=false', () => {
it('keeps use_global_blocked_services when use_global_settings is off', () => {
const form = {
...getInitialClientFormState(),
use_global_settings: false,
use_global_blocked_services: true,
};
const config = buildClientConfig(form);
expect(config.use_global_blocked_services).toBe(false);
expect(config.use_global_blocked_services).toBe(true);
expect(config.use_global_settings).toBe(false);
});
it('preserves client blocked services and schedule when global blocked services are enabled', () => {
const form = {
...getInitialClientFormState(),
use_global_blocked_services: true,
blocked_services: ['youtube', 'steam'],
blocked_services_schedule: {
time_zone: 'UTC',
mon: { start: 0, end: 60 },
},
};
const config = buildClientConfig(form);
expect(config.blocked_services).toEqual(['youtube', 'steam']);
expect(config.blocked_services_schedule).toEqual({
time_zone: 'UTC',
mon: { start: 0, end: 60 },
});
});
it('filters empty IDs', () => {
const form = {
...getInitialClientFormState(),
@@ -94,3 +112,27 @@ describe('buildClientConfig', () => {
]);
});
});
describe('buildFormPayload', () => {
it('preserves the full blocked services schedule', () => {
const payload = buildFormPayload({
name: 'Laptop',
ids: ['192.168.1.1'],
blocked_services: ['youtube'],
use_global_blocked_services: true,
blocked_services_schedule: {
time_zone: 'UTC',
mon: { start: 0, end: 60 },
sat: { start: 120, end: 240 },
},
} as any);
expect(payload.blocked_services).toEqual(['youtube']);
expect(payload.use_global_blocked_services).toBe(true);
expect(payload.blocked_services_schedule).toEqual({
time_zone: 'UTC',
mon: { start: 0, end: 60 },
sat: { start: 120, end: 240 },
});
});
});
@@ -146,4 +146,17 @@ describe('saveClient cross-client validation', () => {
expect(result).toBe(false);
expect(clientFormState.formErrors.upstreams_cache_size).toBeDefined();
});
it('validates cache size even when use_global_settings is enabled', async () => {
clearClientForm();
updateClientFormField({ field: 'name', value: 'Test' });
updateClientFormField({ field: 'ids', value: ['192.168.1.1'] });
updateClientFormField({ field: 'use_global_settings', value: true });
updateClientFormField({ field: 'upstreams_cache_enabled', value: true });
updateClientFormField({ field: 'upstreams_cache_size', value: 0 });
const result = await saveClient();
expect(result).toBe(false);
expect(clientFormState.formErrors.upstreams_cache_size).toBeDefined();
});
});
@@ -26,16 +26,4 @@ describe('locales.generated.ts', () => {
expect(LOCALES.en).toBeDefined();
expect(Object.keys(LOCALES.en).length).toBeGreaterThan(0);
});
it('every lazy loader resolves to a non-empty message map', async () => {
for (const [code, loader] of Object.entries(LOCALE_LOADERS)) {
const mod = await loader();
const messages = (mod as { default?: Record<string, string> }).default ?? mod;
expect(messages, `locale ${code}`).toBeDefined();
expect(
Object.keys(messages as Record<string, string>).length,
`locale ${code}`,
).toBeGreaterThan(0);
}
});
});
@@ -0,0 +1,54 @@
import { render, screen } from '@solidjs/testing-library';
import { MemoryRouter, Route, createMemoryHistory } from '@solidjs/router';
import { describe, expect, it } from 'vitest';
import { SettingLink } from 'panel/common/ui/SettingLink';
import { RoutePath } from 'panel/components/Routes/Paths';
const renderLink = (props: { disabled?: boolean } = {}) => {
const history = createMemoryHistory();
history.set({ value: '/' });
return render(() => (
<MemoryRouter history={history}>
<Route
path="/"
component={() => (
<SettingLink
to={RoutePath.Clients}
title="Title"
description="Description"
disabled={props.disabled}
data-testid="row"
/>
)}
/>
</MemoryRouter>
));
};
describe('SettingLink', () => {
it('renders the title and description', () => {
renderLink();
expect(screen.getByText('Title')).toBeInTheDocument();
expect(screen.getByText('Description')).toBeInTheDocument();
});
it('renders a router link when enabled', () => {
renderLink();
const row = screen.getByTestId('row');
expect(row.tagName).toBe('A');
expect(row).toHaveAttribute('href');
});
it('renders a non-interactive row with the arrow when disabled', () => {
renderLink({ disabled: true });
const row = screen.getByTestId('row');
expect(row.tagName).toBe('DIV');
expect(row.querySelector('svg')).not.toBeNull();
expect(screen.queryByRole('link')).toBeNull();
});
});
@@ -0,0 +1,83 @@
import { render, screen } from '@solidjs/testing-library';
import { MemoryRouter, Route, createMemoryHistory } from '@solidjs/router';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { BlockedServices } from 'panel/components/BlockedServices/BlockedServices';
import { clearClientForm, initClientForm } from 'panel/stores/clientForm';
import { copyInDom } from 'panel/__tests__/helpers/copy';
const servicesMocks = vi.hoisted(() => ({
getBlockedServices: vi.fn(),
getAllBlockedServices: vi.fn(),
updateBlockedServices: vi.fn(),
servicesState: {
allServices: [] as unknown[],
allGroups: [] as unknown[],
processingAll: false,
processing: false,
processingSet: false,
},
}));
vi.mock('panel/stores/services', () => servicesMocks);
vi.mock('panel/common/intl', async () =>
(await import('panel/__tests__/helpers/copy')).createIntlMock(),
);
const renderBlockedServices = (clientScope = true) => {
const history = createMemoryHistory();
history.set({ value: '/' });
return render(() => (
<MemoryRouter history={history}>
<Route path="/" component={() => <BlockedServices clientScope={clientScope} />} />
</MemoryRouter>
));
};
describe('BlockedServices client scope', () => {
beforeEach(() => {
clearClientForm();
});
it('hides the list and shows the global note when global blocked services are on', () => {
initClientForm({ name: 'Laptop', use_global_blocked_services: true });
renderBlockedServices();
expect(screen.queryByTestId('blocked-services-list')).toBeNull();
expect(screen.queryByTestId('blocked-services-search')).toBeNull();
expect(screen.getByTestId('blocked-services-global-note')).toHaveTextContent(
copyInDom('clients_global_blocked_services_note'),
);
const scheduleLink = screen.getByTestId('blocked-services-schedule-link');
expect(scheduleLink.tagName).toBe('DIV');
expect(scheduleLink).toHaveTextContent(
copyInDom('clients_global_inactivity_schedule_note'),
);
// The arrow stays visible in the disabled row; only its color changes.
expect(scheduleLink.querySelector('svg')).not.toBeNull();
expect(document.getElementById('use-global-blocked-services')).toBeChecked();
});
it('keeps the list editable when global blocked services are off', () => {
initClientForm({ name: 'Laptop', use_global_blocked_services: false });
renderBlockedServices();
expect(screen.getByTestId('blocked-services-list')).toBeInTheDocument();
expect(screen.getByTestId('blocked-services-search')).toBeInTheDocument();
expect(screen.queryByTestId('blocked-services-global-note')).toBeNull();
expect(screen.getByTestId('blocked-services-schedule-link').tagName).toBe('A');
expect(document.getElementById('use-global-blocked-services')).not.toBeChecked();
});
it('does not render the toggle or the global note outside the client scope', () => {
renderBlockedServices(false);
expect(document.getElementById('use-global-blocked-services')).toBeNull();
expect(screen.queryByTestId('blocked-services-global-note')).toBeNull();
expect(screen.getByTestId('blocked-services-list')).toBeInTheDocument();
});
});
@@ -0,0 +1,46 @@
import { render, screen } from '@solidjs/testing-library';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { InactivitySchedule } from 'panel/components/BlockedServices/InactivitySchedule/InactivitySchedule';
import { clearClientForm, initClientForm } from 'panel/stores/clientForm';
import { copyInDom } from 'panel/__tests__/helpers/copy';
vi.mock('panel/common/intl', async () =>
(await import('panel/__tests__/helpers/copy')).createIntlMock(),
);
const renderSchedule = () => render(() => <InactivitySchedule clientScope />);
describe('InactivitySchedule client scope', () => {
beforeEach(() => {
clearClientForm();
});
it('is read-only while the client uses the global blocked services', () => {
initClientForm({
name: 'Laptop',
use_global_blocked_services: true,
blocked_services_schedule: { time_zone: 'UTC' },
});
renderSchedule();
expect(screen.getByTestId('inactivity-schedule-read-only-note')).toHaveTextContent(
copyInDom('clients_global_inactivity_schedule_note'),
);
expect(screen.queryByTestId('schedule-row-mon-add')).toBeNull();
expect(screen.queryByTestId('schedule-row-mon-edit')).toBeNull();
expect(screen.queryByTestId('schedule-row-mon-delete')).toBeNull();
});
it('is editable while the client uses its own blocked services', () => {
initClientForm({
name: 'Laptop',
use_global_blocked_services: false,
blocked_services_schedule: { time_zone: 'UTC' },
});
renderSchedule();
expect(screen.queryByTestId('inactivity-schedule-read-only-note')).toBeNull();
expect(screen.getByTestId('schedule-row-mon-add')).toBeInTheDocument();
});
});
@@ -0,0 +1,54 @@
import { render, screen } from '@solidjs/testing-library';
import { describe, expect, it, vi } from 'vitest';
import { ScheduleRow } from 'panel/components/BlockedServices/InactivitySchedule/ScheduleRow';
vi.mock('panel/common/intl', async () =>
(await import('panel/__tests__/helpers/copy')).createIntlMock(),
);
type RowProps = {
data?: { start: number; end: number };
disabled?: boolean;
};
const renderRow = (props: RowProps = {}) =>
render(() => (
<ScheduleRow
day="mon"
data={props.data}
disabled={props.disabled}
onEdit={vi.fn()}
onDelete={vi.fn()}
onAdd={vi.fn()}
/>
));
describe('ScheduleRow', () => {
it('hides the add action when disabled', () => {
renderRow({ disabled: true });
expect(screen.queryByTestId('schedule-row-mon-add')).toBeNull();
});
it('hides the edit and delete actions when disabled', () => {
renderRow({ data: { start: 0, end: 3600000 }, disabled: true });
expect(screen.queryByTestId('schedule-row-mon-edit')).toBeNull();
expect(screen.queryByTestId('schedule-row-mon-delete')).toBeNull();
expect(screen.getByTestId('schedule-row-mon-time')).toHaveTextContent('00:00');
});
it('renders the add action when enabled', () => {
renderRow();
expect(screen.getByTestId('schedule-row-mon-add')).toBeInTheDocument();
});
it('renders the edit and delete actions when enabled', () => {
renderRow({ data: { start: 0, end: 3600000 } });
expect(screen.getByTestId('schedule-row-mon-edit')).toBeInTheDocument();
expect(screen.getByTestId('schedule-row-mon-delete')).toBeInTheDocument();
});
});
@@ -0,0 +1,87 @@
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { render, screen } from '@solidjs/testing-library';
import { MemoryRouter, Route, createMemoryHistory } from '@solidjs/router';
import { AddClient } from 'panel/components/Clients/AddClient/AddClient';
import { clearClientForm, initClientForm, updateClientFormField } from 'panel/stores/clientForm';
import { copyInDom } from 'panel/__tests__/helpers/copy';
// jsdom has no matchMedia; the tags Select and some hooks depend on it.
beforeAll(() => {
if (!window.matchMedia) {
window.matchMedia = (query: string) =>
({
matches: false,
media: query,
onchange: null,
addEventListener: () => {},
removeEventListener: () => {},
addListener: () => {},
removeListener: () => {},
dispatchEvent: () => false,
}) as unknown as MediaQueryList;
}
});
vi.mock('panel/stores/dashboard', () => ({
dashboardState: {
clients: [],
supportedTags: [],
},
getClients: vi.fn(),
}));
vi.mock('panel/common/intl', async () =>
(await import('panel/__tests__/helpers/copy')).createIntlMock(),
);
const renderAddClient = () => {
const history = createMemoryHistory();
history.set({ value: '/' });
return render(() => (
<MemoryRouter history={history}>
<Route path="/" component={() => <AddClient />} />
</MemoryRouter>
));
};
const protectionLinkName = () => new RegExp(copyInDom('clients_protection'));
const blockedServicesLinkName = () => new RegExp(copyInDom('blocked_services'));
describe('AddClient — global settings independence (AGH-234)', () => {
beforeEach(() => {
clearClientForm();
});
it('keeps Blocked services, Upstream, and DNS cache active when use_global_settings is on', () => {
initClientForm(null);
updateClientFormField('use_global_settings', true);
renderAddClient();
// AC 1: «Use global settings» blocks only Protection — the Protection
// link is disabled (rendered as a non-anchor), everything else stays
// interactive.
expect(screen.queryByRole('link', { name: protectionLinkName() })).toBeNull();
expect(screen.getByRole('link', { name: blockedServicesLinkName() })).toBeInTheDocument();
const upstreams = document.getElementById('client-upstreams') as HTMLTextAreaElement;
expect(upstreams).not.toBeDisabled();
const dnsCache = document.getElementById('use-dns-cache') as HTMLInputElement;
expect(dnsCache).not.toBeDisabled();
});
it('disables the Protection link only while use_global_settings is on', () => {
initClientForm(null);
renderAddClient();
expect(screen.getByRole('link', { name: protectionLinkName() })).toBeInTheDocument();
updateClientFormField('use_global_settings', true);
expect(screen.queryByRole('link', { name: protectionLinkName() })).toBeNull();
// The row itself is still rendered (just not as a link).
expect(screen.getByText(copyInDom('clients_protection_desc'))).toBeInTheDocument();
});
});
@@ -0,0 +1,41 @@
import { describe, expect, it, vi } from 'vitest';
import { render, screen } from '@solidjs/testing-library';
import { ServiceCell } from 'panel/components/Clients/blocks/PersistentClientsTable/ServiceCell';
import type { WebService } from 'panel/components/Clients/blocks/PersistentClientsTable/ServiceIcons';
import { copyInDom } from 'panel/__tests__/helpers/copy';
vi.mock('panel/common/intl', async () =>
(await import('panel/__tests__/helpers/copy')).createIntlMock(),
);
const SVG = '<svg xmlns="http://www.w3.org/2000/svg"><circle r="4" /></svg>';
const serviceMap = new Map<string, WebService>([
['youtube', { id: 'youtube', name: 'YouTube', icon_svg: SVG, group_id: 'streaming', rules: [] }],
]);
describe('ServiceCell — blocked services status (AGH-234)', () => {
it('shows Global when the client uses the global blocked services', () => {
render(() => <ServiceCell serviceIds={['youtube']} useGlobal serviceMap={serviceMap} />);
expect(screen.getByText(copyInDom('settings_global'))).toBeInTheDocument();
expect(screen.queryByTestId('service-icon')).toBeNull();
});
it('shows the service icons for custom blocked services', () => {
render(() => (
<ServiceCell serviceIds={['youtube']} useGlobal={false} serviceMap={serviceMap} />
));
expect(screen.getByTestId('service-icon')).toBeInTheDocument();
expect(screen.queryByText(copyInDom('settings_global'))).toBeNull();
});
it('shows a dash when the client has no custom services', () => {
render(() => <ServiceCell serviceIds={[]} useGlobal={false} serviceMap={serviceMap} />);
expect(screen.getByText('-')).toBeInTheDocument();
expect(screen.queryByTestId('service-icon')).toBeNull();
});
});
@@ -0,0 +1,142 @@
import { render, screen, waitFor } from '@solidjs/testing-library';
import { MemoryRouter, Route, createMemoryHistory } from '@solidjs/router';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const dashboardMocks = vi.hoisted(() => ({
getClients: vi.fn(),
dashboardState: {
clients: [] as unknown[],
clientsInitialized: true,
supportedTags: [] as string[],
},
}));
vi.mock('panel/stores/dashboard', async () => {
const actual =
await vi.importActual<typeof import('panel/stores/dashboard')>('panel/stores/dashboard');
return {
...actual,
getClients: dashboardMocks.getClients,
get dashboardState() {
return dashboardMocks.dashboardState;
},
};
});
import { useInitClientFormFromRoute } from 'panel/hooks/useInitClientFormFromRoute';
import {
clearClientForm,
clientFormState,
initClientForm,
setProcessingSave,
updateClientFormField,
} from 'panel/stores/clientForm';
const Probe = () => {
useInitClientFormFromRoute();
return <div data-testid="probe" />;
};
const renderAt = (path: string) => {
const history = createMemoryHistory();
history.set({ value: path });
render(() => (
<MemoryRouter history={history}>
<Route path="/clients/edit/:clientName" component={Probe} />
</MemoryRouter>
));
return { history };
};
const laptop = {
name: 'Laptop',
ids: ['192.168.1.1'],
use_global_blocked_services: true,
blocked_services: ['youtube'],
blocked_services_schedule: {
time_zone: 'UTC',
mon: { start: 0, end: 60 },
},
};
const desktop = {
name: 'Desktop',
ids: ['192.168.1.2'],
use_global_blocked_services: false,
blocked_services: [] as string[],
blocked_services_schedule: {
time_zone: 'UTC',
},
};
describe('useInitClientFormFromRoute', () => {
beforeEach(() => {
clearClientForm();
dashboardMocks.getClients.mockClear();
dashboardMocks.dashboardState.clients = [laptop, desktop];
});
it('initializes the form from the client in the route', async () => {
renderAt('/clients/edit/Laptop');
await waitFor(() => {
expect(clientFormState.mode).toBe('edit');
});
expect(clientFormState.name).toBe('Laptop');
expect(clientFormState.use_global_blocked_services).toBe(true);
expect(clientFormState.blocked_services).toEqual(['youtube']);
expect(clientFormState.blocked_services_schedule.mon).toEqual({ start: 0, end: 60 });
});
it('keeps the form untouched when it already matches the route', async () => {
initClientForm({ name: 'Laptop', use_global_blocked_services: false });
updateClientFormField('blocked_services', ['steam']);
renderAt('/clients/edit/Laptop');
await waitFor(() => {
expect(screen.getByTestId('probe')).toBeInTheDocument();
});
expect(clientFormState.name).toBe('Laptop');
expect(clientFormState.blocked_services).toEqual(['steam']);
});
it('loads clients when a client page mounts', () => {
renderAt('/clients/edit/Laptop');
expect(dashboardMocks.getClients).toHaveBeenCalled();
});
it('re-initializes when the route switches to another client', async () => {
const { history } = renderAt('/clients/edit/Laptop');
await waitFor(() => {
expect(clientFormState.name).toBe('Laptop');
});
history.set({ value: '/clients/edit/Desktop' });
await waitFor(() => {
expect(clientFormState.name).toBe('Desktop');
});
expect(clientFormState.originalName).toBe('Desktop');
expect(clientFormState.use_global_blocked_services).toBe(false);
});
it('does not re-initialize while a save is in flight', async () => {
initClientForm({ name: 'Laptop', use_global_blocked_services: true });
setProcessingSave(true);
renderAt('/clients/edit/Desktop');
await waitFor(() => {
expect(screen.getByTestId('probe')).toBeInTheDocument();
});
expect(clientFormState.name).toBe('Laptop');
});
});
@@ -0,0 +1,60 @@
.link {
display: flex;
align-items: flex-start;
justify-content: space-between;
padding: 16px;
border-radius: 8px;
cursor: pointer;
transition: background-color 0.2s;
text-decoration: none;
&:focus-visible {
background-color: var(--hovered-page-background);
}
@media (hover: hover) {
&:hover {
background-color: var(--hovered-page-background);
}
}
}
.linkDisabled {
cursor: default;
pointer-events: none;
.title,
.description,
.arrow {
color: var(--disabled-main-text);
}
&:focus-visible {
background-color: transparent;
}
@media (hover: hover) {
&:hover {
background-color: transparent;
}
}
}
.content {
display: flex;
flex-direction: column;
gap: 4px;
}
.title {
font-size: 16px;
font-weight: 600;
line-height: 1.3;
color: var(--default-main-text);
}
.description {
font-size: 14px;
line-height: 1.3;
color: var(--default-description-text);
}
@@ -0,0 +1,41 @@
import cn from 'clsx';
import { Icon } from 'panel/common/ui/Icon';
import { Link } from 'panel/common/ui/Link';
import type { LinkParams, RoutePathKey } from 'panel/components/Routes/Paths';
import s from './SettingLink.module.pcss';
type Props = {
to: RoutePathKey;
linkProps?: LinkParams;
title: string;
description: string;
disabled?: boolean;
class?: string;
'data-testid'?: string;
};
/**
* A navigational settings row: title, description, and a trailing chevron.
*
* Unlike `SettingRow`'s `link` variant, which is a button-like row that runs
* an `onClick`, this renders a real router link, so the row keeps anchor
* semantics (href, middle-click, open in a new tab) while sharing the
* disabled styling with the other client sub-page rows.
*/
export const SettingLink = (props: Props) => (
<Link
to={props.to}
props={props.linkProps}
disabled={props.disabled}
class={cn(s.link, { [s.linkDisabled]: props.disabled }, props.class)}
data-testid={props['data-testid']}
>
<div class={s.content}>
<div class={s.title}>{props.title}</div>
<div class={s.description}>{props.description}</div>
</div>
<Icon icon="arrow" color="gray" class={s.arrow} />
</Link>
);
@@ -0,0 +1 @@
export { SettingLink } from './SettingLink';
@@ -34,41 +34,25 @@
}
}
.navItem {
display: flex;
align-items: flex-start;
justify-content: space-between;
padding: 16px;
cursor: pointer;
transition: background-color 0.2s;
text-decoration: none;
border-radius: 8px;
&:hover,
&:focus-visible {
background-color: var(--hovered-page-background);
}
.toggle {
margin: 8px 0;
}
.navItemContent {
.globalNote {
display: flex;
flex-direction: column;
gap: 4px;
}
.navItemTitle {
font-size: 16px;
font-weight: 600;
line-height: 1.3;
color: var(--default-main-text);
}
.navItemDesc {
font-size: 14px;
line-height: 1.3;
align-items: center;
justify-content: center;
padding: 48px 16px;
gap: 16px;
text-align: center;
color: var(--default-description-text);
}
.globalNoteText {
max-width: 256px;
}
.search {
padding: 16px 16px 8px;
}
@@ -3,7 +3,8 @@ import cn from 'clsx';
import intl from 'panel/common/intl';
import { Input } from 'panel/common/controls/Input';
import { Icon } from 'panel/common/ui/Icon';
import { Link } from 'panel/common/ui/Link';
import { SettingLink } from 'panel/common/ui/SettingLink';
import { SwitchGroup } from 'panel/common/ui/SettingsGroup';
import { updateClientFormField, clientFormState } from 'panel/stores/clientForm';
import theme from 'panel/lib/theme';
import {
@@ -154,6 +155,13 @@ export const BlockedServices = (props: Props) => {
updateBlockedServices({ ids: newIds, schedule: servicesState.list?.schedule });
};
const handleUseGlobalBlockedServices = (e: Event) => {
updateClientFormField({
field: 'use_global_blocked_services',
value: (e.target as HTMLInputElement).checked,
});
};
const handleSearchChange = (e: Event) => {
setSearch((e.target as HTMLInputElement).value);
};
@@ -166,7 +174,7 @@ export const BlockedServices = (props: Props) => {
(servicesState.allServices == null || servicesState.allServices.length === 0) &&
(servicesState.processingAll || servicesState.processing);
const isGloballyDisabled = () =>
props.clientScope ? clientFormState.use_global_settings : false;
props.clientScope ? clientFormState.use_global_blocked_services : false;
const getScheduleRoute = () => {
if (!props.clientScope) {
@@ -222,106 +230,133 @@ export const BlockedServices = (props: Props) => {
</div>
</Show>
<Link
<Show when={props.clientScope}>
<div class={s.toggle}>
<SwitchGroup
id="use-global-blocked-services"
title={intl.getMessage('clients_use_global_blocked_services')}
description={intl.getMessage(
'clients_use_global_blocked_services_desc',
)}
checked={clientFormState.use_global_blocked_services}
onChange={handleUseGlobalBlockedServices}
/>
</div>
</Show>
<SettingLink
to={getScheduleRoute()}
props={scheduleRouteProps()}
class={s.navItem}
linkProps={scheduleRouteProps()}
title={intl.getMessage('inactivity_schedule')}
description={
isGloballyDisabled()
? intl.getMessage('clients_global_inactivity_schedule_note')
: intl.getMessage('inactivity_schedule_desc')
}
disabled={isGloballyDisabled()}
data-testid="blocked-services-schedule-link"
>
<div class={s.navItemContent}>
<div class={s.navItemTitle}>
{intl.getMessage('inactivity_schedule')}
</div>
<div class={s.navItemDesc}>
{intl.getMessage('inactivity_schedule_desc')}
/>
<Show when={isGloballyDisabled()}>
<div
class={cn(theme.text.t3, s.globalNote)}
data-testid="blocked-services-global-note"
>
<Icon icon="settings_info" color="gray" class={s.nothingFoundIcon} />
<div class={s.globalNoteText}>
{intl.getMessage('clients_global_blocked_services_note')}
</div>
</div>
<Icon icon="arrow" color="gray" />
</Link>
</Show>
<div class={s.search}>
<Input
id="blocked-services-search"
data-testid="blocked-services-search"
type="text"
value={search()}
onInput={handleSearchChange}
placeholder={intl.getMessage('search_placeholder')}
prefixIcon={<Icon icon="search" class={s.searchIcon} color="gray" />}
suffixIcon={
<Show when={search()}>
<button
type="button"
onClick={handleSearchClear}
class={s.clearButton}
aria-label={intl.getMessage('clear_btn')}
data-testid="blocked-services-search-clear"
>
<Icon icon="cross" color="gray" />
</button>
</Show>
}
size="large"
/>
</div>
<Show when={!isGloballyDisabled()}>
<div class={s.search}>
<Input
id="blocked-services-search"
data-testid="blocked-services-search"
type="text"
value={search()}
onInput={handleSearchChange}
placeholder={intl.getMessage('search_placeholder')}
prefixIcon={
<Icon icon="search" class={s.searchIcon} color="gray" />
}
suffixIcon={
<Show when={search()}>
<button
type="button"
onClick={handleSearchClear}
class={s.clearButton}
aria-label={intl.getMessage('clear_btn')}
data-testid="blocked-services-search-clear"
>
<Icon icon="cross" color="gray" />
</button>
</Show>
}
size="large"
/>
</div>
<GroupFilter
groups={servicesState.allGroups || []}
activeGroups={groupFilter()}
onToggleGroup={handleToggleGroup}
data-testid="blocked-services-groups"
>
<button
type="button"
class={cn(s.groupButton, {
[s.groupButtonActive]: showBlockedOnly(),
})}
onClick={() => handleToggleStateFilter('blocked')}
aria-pressed={showBlockedOnly()}
data-testid="blocked-services-show-blocked-only"
<GroupFilter
groups={servicesState.allGroups || []}
activeGroups={groupFilter()}
onToggleGroup={handleToggleGroup}
data-testid="blocked-services-groups"
>
{intl.getMessage('blocked_only')}
</button>
<button
type="button"
class={cn(s.groupButton, {
[s.groupButtonActive]: showUnblockedOnly(),
})}
onClick={() => handleToggleStateFilter('unblocked')}
aria-pressed={showUnblockedOnly()}
data-testid="blocked-services-show-unblocked-only"
>
{intl.getMessage('unblocked_only')}
</button>
<span
class={s.filtersDivider}
data-testid="blocked-services-filters-divider"
/>
</GroupFilter>
<button
type="button"
class={cn(s.groupButton, {
[s.groupButtonActive]: showBlockedOnly(),
})}
onClick={() => handleToggleStateFilter('blocked')}
aria-pressed={showBlockedOnly()}
data-testid="blocked-services-show-blocked-only"
>
{intl.getMessage('blocked_only')}
</button>
<button
type="button"
class={cn(s.groupButton, {
[s.groupButtonActive]: showUnblockedOnly(),
})}
onClick={() => handleToggleStateFilter('unblocked')}
aria-pressed={showUnblockedOnly()}
data-testid="blocked-services-show-unblocked-only"
>
{intl.getMessage('unblocked_only')}
</button>
<span
class={s.filtersDivider}
data-testid="blocked-services-filters-divider"
/>
</GroupFilter>
<div class={s.servicesList} data-testid="blocked-services-list">
<Show
when={filteredServices().length === 0}
fallback={
<For each={filteredServices()}>
{(service) => (
<ServiceRow
id={service.id}
name={service.name}
iconSvg={service.icon_svg}
checked={blockedSet().has(service.id)}
disabled={
isGloballyDisabled() || togglingId() === service.id
}
onChange={handleToggleService}
/>
)}
</For>
}
>
<NothingFound />
</Show>
</div>
<div class={s.servicesList} data-testid="blocked-services-list">
<Show
when={filteredServices().length === 0}
fallback={
<For each={filteredServices()}>
{(service) => (
<ServiceRow
id={service.id}
name={service.name}
iconSvg={service.icon_svg}
checked={blockedSet().has(service.id)}
disabled={
isGloballyDisabled() ||
togglingId() === service.id
}
onChange={handleToggleService}
/>
)}
</For>
}
>
<NothingFound />
</Show>
</div>
</Show>
</div>
</div>
</Show>
@@ -36,6 +36,12 @@
margin-bottom: 8px;
}
.readOnlyNote {
margin: 0;
padding: 16px;
color: var(--default-description-text);
}
.scheduleList {
display: flex;
flex-direction: column;
@@ -69,8 +69,12 @@ export const InactivitySchedule = (props: Props) => {
return servicesState.processing && !servicesState.list?.ids;
});
const isReadOnly = createMemo(
() => !!props.clientScope && clientFormState.use_global_blocked_services,
);
const handleTimezoneChange = (option: { value: string }) => {
if (!option) {
if (!option || isReadOnly()) {
return;
}
const newSchedule = props.clientScope
@@ -84,16 +88,25 @@ export const InactivitySchedule = (props: Props) => {
};
const handleAdd = (day: DayKey) => {
if (isReadOnly()) {
return;
}
setEditDay(day);
setModalVisible(true);
};
const handleEdit = (day: DayKey) => {
if (isReadOnly()) {
return;
}
setEditDay(day);
setModalVisible(true);
};
const handleDelete = (day: DayKey) => {
if (isReadOnly()) {
return;
}
setDeleteDay(day);
};
@@ -272,6 +285,15 @@ export const InactivitySchedule = (props: Props) => {
}
>
{/* clientScope - render inline */}
<Show when={isReadOnly()}>
<p
class={cn(theme.text.t3, s.readOnlyNote)}
data-testid="inactivity-schedule-read-only-note"
>
{intl.getMessage('clients_global_inactivity_schedule_note')}
</p>
</Show>
<div
class={cn(s.timezoneWrapper, s.timezoneWrapperClientScope)}
data-testid="inactivity-schedule-timezone"
@@ -283,7 +305,7 @@ export const InactivitySchedule = (props: Props) => {
onChange={handleTimezoneChange}
size="responsive"
height="big"
isDisabled={clientFormState.processingSave}
isDisabled={clientFormState.processingSave || isReadOnly()}
isSearchable
/>
</div>
@@ -294,6 +316,7 @@ export const InactivitySchedule = (props: Props) => {
<ScheduleRow
day={day}
data={schedule()?.[day] as ScheduleDayData | undefined}
disabled={isReadOnly()}
onEdit={handleEdit}
onDelete={handleDelete}
onAdd={handleAdd}
@@ -12,6 +12,7 @@ import s from './InactivitySchedule.module.pcss';
type Props = {
day: DayKey;
data: ScheduleDayData | undefined;
disabled?: boolean;
onEdit: (day: DayKey) => void;
onDelete: (day: DayKey) => void;
onAdd: (day: DayKey) => void;
@@ -65,70 +66,78 @@ export const ScheduleRow = (props: Props) => {
<>
<div class={cn(s.actions, s.actionsDesktop)} />
<div class={s.actions}>
<button
type="button"
class={cn(s.actionButton, s.actionButtonAdd)}
onClick={() => props.onAdd(props.day)}
aria-label={intl.getMessage('inactivity_schedule_add')}
data-testid={`schedule-row-${props.day}-add`}
>
<Icon icon="plus" />
</button>
<Show when={!props.disabled}>
<button
type="button"
class={cn(s.actionButton, s.actionButtonAdd)}
onClick={() => props.onAdd(props.day)}
aria-label={intl.getMessage('inactivity_schedule_add')}
data-testid={`schedule-row-${props.day}-add`}
>
<Icon icon="plus" />
</button>
</Show>
</div>
</>
}
>
<div class={cn(s.actions, s.actionsDesktop)}>
<button
type="button"
class={cn(s.actionButton, s.actionButtonDelete)}
onClick={() => props.onDelete(props.day)}
aria-label={intl.getMessage('delete_table_action')}
data-testid={`schedule-row-${props.day}-delete`}
>
<Icon icon="delete" />
</button>
<Show when={!props.disabled}>
<button
type="button"
class={cn(s.actionButton, s.actionButtonDelete)}
onClick={() => props.onDelete(props.day)}
aria-label={intl.getMessage('delete_table_action')}
data-testid={`schedule-row-${props.day}-delete`}
>
<Icon icon="delete" />
</button>
</Show>
</div>
<div class={cn(s.actions, s.actionsDesktop)}>
<button
type="button"
class={s.actionButton}
onClick={() => props.onEdit(props.day)}
aria-label={intl.getMessage('inactivity_schedule_edit')}
data-testid={`schedule-row-${props.day}-edit`}
>
<Icon icon="edit" />
</button>
<Show when={!props.disabled}>
<button
type="button"
class={s.actionButton}
onClick={() => props.onEdit(props.day)}
aria-label={intl.getMessage('inactivity_schedule_edit')}
data-testid={`schedule-row-${props.day}-edit`}
>
<Icon icon="edit" />
</button>
</Show>
</div>
<div class={cn(s.actions, s.actionsMobile)}>
<Dropdown
position="bottomRight"
noIcon
open={dropdownOpen()}
onOpenChange={setDropdownOpen}
menu={
<div class={theme.dropdown.menu}>
<button
type="button"
class={theme.dropdown.item}
onClick={handleEditClick}
>
{intl.getMessage('inactivity_schedule_edit')}
</button>
<button
type="button"
class={cn(theme.dropdown.item, s.dropdownItemDanger)}
onClick={handleDeleteClick}
>
{intl.getMessage('inactivity_schedule_delete')}
</button>
<Show when={!props.disabled}>
<Dropdown
position="bottomRight"
noIcon
open={dropdownOpen()}
onOpenChange={setDropdownOpen}
menu={
<div class={theme.dropdown.menu}>
<button
type="button"
class={theme.dropdown.item}
onClick={handleEditClick}
>
{intl.getMessage('inactivity_schedule_edit')}
</button>
<button
type="button"
class={cn(theme.dropdown.item, s.dropdownItemDanger)}
onClick={handleDeleteClick}
>
{intl.getMessage('inactivity_schedule_delete')}
</button>
</div>
}
>
<div class={s.actionButton}>
<Icon icon="bullets" />
</div>
}
>
<div class={s.actionButton}>
<Icon icon="bullets" />
</div>
</Dropdown>
</Dropdown>
</Show>
</div>
</Show>
</div>
@@ -1,8 +1,6 @@
export const FULL_DAY_END_MS = 86340000;
export const DAYS_OF_WEEK = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] as const;
export type DayKey = (typeof DAYS_OF_WEEK)[number];
export { DAYS_OF_WEEK, type DayKey } from 'panel/helpers/schedule';
export type TimeValue = {
hours: number;
@@ -26,61 +26,6 @@
}
}
.navLink {
display: block;
text-decoration: none;
padding: 16px;
border-radius: 8px;
width: 100%;
cursor: pointer;
transition: background-color 0.2s;
&:hover,
&:focus {
background-color: var(--hovered-page-background);
}
}
.navLinkDisabled {
cursor: default;
pointer-events: none;
.navTitle,
.navDesc {
color: var(--disabled-main-text);
}
&:hover,
&:focus {
background-color: transparent;
}
}
.navItem {
display: flex;
align-items: flex-start;
justify-content: space-between;
}
.navItemContent {
display: flex;
flex-direction: column;
gap: 4px;
}
.navTitle {
font-size: 16px;
font-weight: 600;
line-height: 1.3;
color: var(--default-main-text);
}
.navDesc {
font-size: 14px;
line-height: 1.3;
color: var(--default-description-text);
}
.actions {
display: flex;
gap: 16px;
@@ -101,7 +46,3 @@
.containerOverride {
padding-top: 0;
}
.disabledText {
color: var(--disabled-main-text);
}
@@ -1,5 +1,5 @@
import { createMemo, createEffect, createSignal, Show, onMount } from 'solid-js';
import { useNavigate, useParams, useLocation } from '@solidjs/router';
import { createMemo, createEffect, createSignal, Show } from 'solid-js';
import { useNavigate, useLocation } from '@solidjs/router';
import cn from 'clsx';
import intl from 'panel/common/intl';
@@ -8,21 +8,18 @@ import { Select } from 'panel/common/controls/Select';
import type { IOption } from 'panel/lib/helpers/utils';
import { Textarea } from 'panel/common/controls/Textarea';
import { Button } from 'panel/common/ui/Button';
import { Icon } from 'panel/common/ui/Icon';
import { Link } from 'panel/common/ui/Link';
import { PageLoader } from 'panel/common/ui/Loader';
import { SettingLink } from 'panel/common/ui/SettingLink';
import { SwitchGroup } from 'panel/common/ui/SettingsGroup';
import type { Client } from 'panel/initialState';
import {
clientFormState,
updateClientFormField,
clearClientForm,
saveClient,
initClientForm,
buildFormPayload,
setFormErrors,
} from 'panel/stores/clientForm';
import { dashboardState, getClients } from 'panel/stores/dashboard';
import { dashboardState } from 'panel/stores/dashboard';
import { useInitClientFormFromRoute } from 'panel/hooks/useInitClientFormFromRoute';
import { validateUpstreams, validateCacheSize } from 'panel/helpers/validators';
import { RoutePath, Paths } from 'panel/components/Routes/Paths';
import theme from 'panel/lib/theme';
@@ -34,9 +31,10 @@ import s from './AddClient.module.pcss';
export const AddClient = () => {
const navigate = useNavigate();
const params = useParams<{ clientName?: string }>();
const location = useLocation();
useInitClientFormFromRoute();
const [nameError, setNameError] = createSignal<string | undefined>();
const [cacheSizeError, setCacheSizeError] = createSignal<string | undefined>();
const [upstreamsError, setUpstreamsError] = createSignal<string | undefined>();
@@ -54,10 +52,6 @@ export const AddClient = () => {
);
});
onMount(() => {
getClients();
});
const handleNameChange = (e: Event) => {
const value = (e.target as HTMLInputElement).value;
updateClientFormField({ field: 'name', value });
@@ -74,32 +68,6 @@ export const AddClient = () => {
updateClientFormField({ field: 'ids', value: [id] });
});
// When on the edit route and clients are loaded, initialize the form
// from the URL param. This handles page refreshes on the edit page.
createEffect(() => {
const urlClientName = params.clientName;
const clients = dashboardState.clients || [];
if (!urlClientName || !clients.length) {
return;
}
if (clientFormState.mode !== 'add' || clientFormState.originalName) {
return;
}
const decodedName = decodeURIComponent(urlClientName);
const client = clients.find((c: Client) => c.name === decodedName);
if (!client) {
clearClientForm();
navigate(Paths.Clients, { replace: true });
return;
}
initClientForm(buildFormPayload(client));
});
const isEdit = createMemo(() => clientFormState.mode === 'edit');
const handleCancel = () => {
@@ -265,53 +233,22 @@ export const AddClient = () => {
onChange={handleUseGlobalSettings}
/>
<Link
<SettingLink
to={protectionRoute()}
props={routeProps()}
class={cn(s.navLink, {
[s.navLinkDisabled]: clientFormState.use_global_settings,
})}
linkProps={routeProps()}
title={intl.getMessage('clients_protection')}
description={intl.getMessage('clients_protection_desc')}
disabled={clientFormState.use_global_settings}
>
<div class={s.navItem}>
<div class={s.navItemContent}>
<div class={cn(theme.text.t2, theme.text.semibold, s.navTitle)}>
{intl.getMessage('clients_protection')}
</div>
<div class={cn(theme.text.t3, s.navDesc)}>
{intl.getMessage('clients_protection_desc')}
</div>
</div>
<Icon icon="arrow" color="gray" />
</div>
</Link>
/>
<Link
<SettingLink
to={blockedServicesRoute()}
props={routeProps()}
class={cn(s.navLink, {
[s.navLinkDisabled]: clientFormState.use_global_settings,
})}
disabled={clientFormState.use_global_settings}
>
<div class={s.navItem}>
<div class={s.navItemContent}>
<div class={cn(theme.text.t2, theme.text.semibold, s.navTitle)}>
{intl.getMessage('blocked_services')}
</div>
<div class={cn(theme.text.t3, s.navDesc)}>
{intl.getMessage('blocked_services_desc')}
</div>
</div>
<Icon icon="arrow" color="gray" />
</div>
</Link>
linkProps={routeProps()}
title={intl.getMessage('blocked_services')}
description={intl.getMessage('blocked_services_desc')}
/>
<h2
class={cn(theme.layout.subtitle, theme.title.h5, theme.title.h4_tablet, {
[s.disabledText]: clientFormState.use_global_settings,
})}
>
<h2 class={cn(theme.layout.subtitle, theme.title.h5, theme.title.h4_tablet)}>
{intl.getMessage('upstream_dns_servers_title')}
</h2>
@@ -324,7 +261,6 @@ export const AddClient = () => {
placeholder={intl.getMessage('upstream_dns_placeholder')}
label={intl.getMessage('clients_upstreams_desc')}
rows={4}
disabled={clientFormState.use_global_settings}
errorMessage={upstreamsError()}
highlightComments
/>
@@ -335,7 +271,6 @@ export const AddClient = () => {
title={intl.getMessage('clients_use_dns_cache')}
checked={clientFormState.upstreams_cache_enabled}
onChange={handleUpstreamsCacheEnabled}
disabled={clientFormState.use_global_settings}
>
{clientFormState.upstreams_cache_enabled && (
<Input
@@ -1,6 +1,7 @@
import { createMemo } from 'solid-js';
import intl from 'panel/common/intl';
import { clientFormState } from 'panel/stores/clientForm';
import { useInitClientFormFromRoute } from 'panel/hooks/useInitClientFormFromRoute';
import { RoutePath } from 'panel/components/Routes/Paths';
import { BlockedServices } from 'panel/components/BlockedServices/BlockedServices';
@@ -8,6 +9,8 @@ import { BlockedServices } from 'panel/components/BlockedServices/BlockedService
import s from './ClientBlockedServices.module.pcss';
export const ClientBlockedServices = () => {
useInitClientFormFromRoute();
const isEdit = createMemo(() => clientFormState.mode === 'edit');
const clientPageLink = createMemo(() =>
@@ -2,6 +2,7 @@ import { createMemo } from 'solid-js';
import cn from 'clsx';
import intl from 'panel/common/intl';
import { clientFormState } from 'panel/stores/clientForm';
import { useInitClientFormFromRoute } from 'panel/hooks/useInitClientFormFromRoute';
import { RoutePath, type RoutePathKey } from 'panel/components/Routes/Paths';
import theme from 'panel/lib/theme';
import { InactivitySchedule } from 'panel/components/BlockedServices/InactivitySchedule/InactivitySchedule';
@@ -10,6 +11,8 @@ import s from './ClientSchedule.module.pcss';
import { ClientsHeader } from './ClientsHeader';
export const ClientSchedule = () => {
useInitClientFormFromRoute();
const isEdit = createMemo(() => clientFormState.mode === 'edit');
const blockedServicesPath = createMemo<RoutePathKey>(() =>
@@ -24,6 +27,9 @@ export const ClientSchedule = () => {
{
path: blockedServicesPath(),
title: intl.getMessage('blocked_services'),
props: isEdit()
? { clientName: encodeURIComponent(clientFormState.originalName) }
: undefined,
},
]}
/>
@@ -4,6 +4,7 @@ import intl from 'panel/common/intl';
import { Checkbox } from 'panel/common/controls/Checkbox';
import { SwitchGroup } from 'panel/common/ui/SettingsGroup';
import { clientFormState, updateClientFormField } from 'panel/stores/clientForm';
import { useInitClientFormFromRoute } from 'panel/hooks/useInitClientFormFromRoute';
import {
SAFE_SEARCH_PROVIDERS,
SAFE_SEARCH_PROVIDER_KEYS,
@@ -16,6 +17,8 @@ import { ClientsHeader } from '../ClientsHeader';
import s from './Protection.module.pcss';
export const Protection = () => {
useInitClientFormFromRoute();
const disabled = createMemo(() => clientFormState.use_global_settings);
const handleToggle = (field: keyof typeof clientFormState) => (e: Event) => {
+10
View File
@@ -0,0 +1,10 @@
/**
* The days of the week in the order the schedule UI renders them.
*
* Shared by the schedule components and the client form store so the two
* cannot drift apart: a day missing from either list is silently dropped when
* a client is loaded or saved.
*/
export const DAYS_OF_WEEK = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] as const;
export type DayKey = (typeof DAYS_OF_WEEK)[number];
@@ -0,0 +1,59 @@
import { createEffect, onMount } from 'solid-js';
import { useNavigate, useParams } from '@solidjs/router';
import type { Client } from 'panel/initialState';
import { Paths } from 'panel/components/Routes/Paths';
import {
buildFormPayload,
clearClientForm,
clientFormState,
initClientForm,
} from 'panel/stores/clientForm';
import { dashboardState, getClients } from 'panel/stores/dashboard';
/**
* Populates the client form from the `:clientName` route param.
*
* The client sub-pages (Protection, Blocked services, Inactivity schedule)
* render outside the main form, so a direct page load must initialize the
* store themselves; otherwise they read the form defaults.
*/
export const useInitClientFormFromRoute = () => {
const navigate = useNavigate();
const params = useParams<{ clientName?: string }>();
onMount(() => {
getClients();
});
createEffect(() => {
const urlClientName = params.clientName;
const clients = dashboardState.clients || [];
if (!urlClientName || !clients.length) {
return;
}
const decodedName = decodeURIComponent(urlClientName);
// Don't clobber a save in flight, and skip when the form already holds
// this client. Otherwise re-initialize so Back/Forward between two
// clients cannot show — and save — the previous client's settings.
if (clientFormState.processingSave) {
return;
}
if (clientFormState.mode === 'edit' && clientFormState.originalName === decodedName) {
return;
}
const client = clients.find((c: Client) => c.name === decodedName);
if (!client) {
clearClientForm();
navigate(Paths.Clients, { replace: true });
return;
}
initClientForm(buildFormPayload(client));
});
};
+31 -11
View File
@@ -5,6 +5,7 @@ import { clientsUpdate, clientsAdd } from 'panel/api/generated';
import intl from 'panel/common/intl';
import { validateIdentifier, validateCacheSize } from 'panel/helpers/validators';
import { DEFAULT_DNS_CACHE_SIZE } from 'panel/helpers/constants';
import { DAYS_OF_WEEK } from 'panel/helpers/schedule';
import { addErrorToast, addSuccessToast } from './toasts';
import { getClients, dashboardState } from './dashboard';
@@ -93,6 +94,29 @@ export const setProcessingSave = (value: boolean) => {
setState('processingSave', value);
};
/**
* Converts an API schedule into the form schedule, preserving the configured
* day ranges. The API model allows partial ranges, while the form requires both
* bounds, so incomplete entries are dropped.
*/
const buildFormSchedule = (
schedule: Client['blocked_services_schedule'],
): ClientFormState['blocked_services_schedule'] => {
const result: ClientFormState['blocked_services_schedule'] = {
time_zone:
schedule?.time_zone ?? Intl.DateTimeFormat().resolvedOptions().timeZone,
};
DAYS_OF_WEEK.forEach((day) => {
const range = schedule?.[day];
if (range && typeof range.start === 'number' && typeof range.end === 'number') {
result[day] = { start: range.start, end: range.end };
}
});
return result;
};
export const buildFormPayload = (client: Client): Partial<ClientFormState> => ({
name: client.name,
ids: client.ids || [''],
@@ -115,11 +139,7 @@ export const buildFormPayload = (client: Client): Partial<ClientFormState> => ({
ignore_statistics: client.ignore_statistics || false,
blocked_services: client.blocked_services || [],
use_global_blocked_services: client.use_global_blocked_services || false,
blocked_services_schedule: {
time_zone:
client.blocked_services_schedule?.time_zone ??
Intl.DateTimeFormat().resolvedOptions().timeZone,
},
blocked_services_schedule: buildFormSchedule(client.blocked_services_schedule),
upstreams: (client.upstreams || []).join('\n'),
upstreams_cache_enabled: client.upstreams_cache_enabled || false,
upstreams_cache_size: client.upstreams_cache_size || DEFAULT_DNS_CACHE_SIZE,
@@ -130,7 +150,7 @@ export const buildClientConfig = (form: ClientFormState) => ({
ids: form.ids.filter((id: string) => id.trim() !== ''),
tags: form.tags,
use_global_settings: form.use_global_settings,
use_global_blocked_services: form.use_global_settings,
use_global_blocked_services: form.use_global_blocked_services,
filtering_enabled: form.filtering_enabled,
safebrowsing_enabled: form.safebrowsing_enabled,
parental_enabled: form.parental_enabled,
@@ -186,11 +206,11 @@ export const saveClient = async (): Promise<boolean> => {
errors.ids = idErrors;
}
// Validate cache size when per-client cache is enabled (and not using global settings).
// When use_global_settings is true, upstream settings are inherited; the cache size
// value is still sent to the API but the backend ignores it. We skip validation to
// avoid false positives on stale/inherited values.
if (!state.use_global_settings && state.upstreams_cache_enabled) {
// Validate the cache size whenever the per-client cache is enabled. Upstream
// settings are independent of `use_global_settings`: an empty upstream list
// means the global servers are used, and the per-client cache only applies
// when the client has its own upstreams.
if (state.upstreams_cache_enabled) {
const cacheErr = validateCacheSize(state.upstreams_cache_size, true);
if (cacheErr) {
errors.upstreams_cache_size = cacheErr;