From fdb993eeac07dc14bf4e0796763d70143b00b61e Mon Sep 17 00:00:00 2001 From: Zakk Date: Sun, 20 Sep 2026 14:15:20 +1000 Subject: [PATCH] perf(ui): stabilize large lists and activity cards Virtualize long node menus and preserve previous data when revisiting pages. Improve chart resizing, usage cards and capability lists after the review passes. --- e2e/activity.spec.ts | 10 ++ e2e/flows.spec.ts | 9 ++ e2e/honest.spec.ts | 5 +- e2e/interactions.spec.ts | 5 + e2e/nodes.spec.ts | 20 +++ e2e/search.spec.ts | 14 ++ src/api/client.test.ts | 13 ++ src/api/client.ts | 4 +- src/api/mock/config.ts | 7 +- src/api/mock/index.ts | 13 ++ src/api/selectors.test.ts | 34 +++- src/api/selectors.ts | 43 +++-- src/api/store.ts | 25 ++- src/features/activity/Activity.tsx | 14 +- src/features/activity/ModeSwitch.tsx | 28 ++-- src/features/activity/mode.ts | 18 +-- src/features/config/Wizard.tsx | 63 ++++---- src/features/config/blocks.ts | 15 ++ src/features/config/mainSource.ts | 44 +++++ src/features/config/wizard.test.ts | 4 + src/features/config/wizard.ts | 2 +- src/features/connections/ConnectionTable.tsx | 21 ++- src/features/connections/Connections.tsx | 5 +- src/features/dns/Dns.tsx | 8 +- src/features/flows/FlowMap.tsx | 11 +- src/features/flows/Flows.tsx | 27 +++- src/features/flows/map.test.ts | 12 ++ src/features/flows/map.ts | 2 +- src/features/logs/Logs.tsx | 10 +- src/features/nodes/Nodes.tsx | 86 +++++++++- src/features/nodes/messages.ts | 18 +++ src/features/nodes/subscriptions.test.ts | 88 ++++++++++ src/features/nodes/subscriptions.ts | 159 +++++++++++++++++++ src/features/overview/Overview.tsx | 2 +- src/features/policies/Mark.tsx | 30 ---- src/features/policies/Nodes.tsx | 18 ++- src/features/policies/Policies.tsx | 19 +-- src/features/rules/RuleList.tsx | 41 +++-- src/features/rules/Rules.tsx | 2 +- src/features/settings/Settings.tsx | 1 + src/shell/Shell.tsx | 12 +- src/shell/registry.ts | 4 +- src/ui/Charts.tsx | 94 +++++++---- src/ui/messages.ts | 3 + src/ui/theme.css | 78 ++++----- src/ui/ui.tsx | 63 +++++++- 46 files changed, 908 insertions(+), 296 deletions(-) create mode 100644 src/features/config/blocks.ts create mode 100644 src/features/config/mainSource.ts create mode 100644 src/features/nodes/subscriptions.test.ts create mode 100644 src/features/nodes/subscriptions.ts delete mode 100644 src/features/policies/Mark.tsx diff --git a/e2e/activity.spec.ts b/e2e/activity.spec.ts index 88bc4323..fb0a7b18 100644 --- a/e2e/activity.spec.ts +++ b/e2e/activity.spec.ts @@ -77,3 +77,13 @@ test('the outbound mode is staged and applied as a configuration write with a re await expect(page.locator('.rp-toast.positive', {hasText: 'reloaded: Rule'})).toBeVisible(); await expect(await routing()).not.toContainText('doona: outbound mode'); }); + +test.describe('many outbounds', () => { + test.use({storage: {'doona-mock-big': '3000'}}); + test('the outbound usage legend scrolls instead of growing the card', async ({page}) => { + await page.goto('/#/activity'); + const legend = page.locator('.rp-donut .lst'); + await expect(legend.locator('.r')).toHaveCount(29); + expect(await legend.evaluate(el => el.scrollHeight > el.clientHeight && el.clientHeight <= 170)).toBe(true); + }); +}); diff --git a/e2e/flows.spec.ts b/e2e/flows.spec.ts index b0f6e8dc..275dd429 100644 --- a/e2e/flows.spec.ts +++ b/e2e/flows.spec.ts @@ -82,3 +82,12 @@ test.describe('flows unavailable', () => { await expect(page).toHaveURL(/#\/rules\?tab=map$/); }); }); + +test('a flow record links its rule into the rule list', async ({page}) => { + await page.goto('/#/rules?tab=flows'); + const link = page.getByRole('link', {name: /^Open .* in the rule list$/}).first(); + await expect(link).toBeVisible(); + await link.click(); + await expect(page).toHaveURL(/#\/rules\?tab=list&rule=/); + await expect(page.locator('[role="row"][aria-selected="true"]')).toBeVisible(); +}); diff --git a/e2e/honest.spec.ts b/e2e/honest.spec.ts index c78346d3..1815048a 100644 --- a/e2e/honest.spec.ts +++ b/e2e/honest.spec.ts @@ -86,7 +86,10 @@ test('refresh remains pending until completion, refetches non-polling resources, '/runtime/outbounds': await api.runtimeOutbounds(), '/runtime/traffic/history': await api.trafficHistory(), '/connections': await api.connections(), - '/nodes': await api.nodes() + '/nodes': await api.nodes(), + // The mode cards read the main source and the groups. + '/config': await api.config(), + '/groups': await api.groups() }; const counts: Record = {}; let hold: Promise | undefined; diff --git a/e2e/interactions.spec.ts b/e2e/interactions.spec.ts index 6ca1e5ec..45f8f9fc 100644 --- a/e2e/interactions.spec.ts +++ b/e2e/interactions.spec.ts @@ -75,6 +75,11 @@ test('a truncated table cell exposes the full value on hover and keyboard focus' await page.mouse.move(0, 0); await cell.hover(); await expect(page.getByRole('tooltip')).toHaveText(full); + // The tooltip is a box of its own, not bare text over the table. + expect(await page.getByRole('tooltip').evaluate(el => [getComputedStyle(el).backgroundColor !== 'rgba(0, 0, 0, 0)', getComputedStyle(el).padding])).toEqual([ + true, + '4px 8px' + ]); await page.keyboard.press('Escape'); await expect(page.getByRole('tooltip')).toBeHidden(); await page.mouse.move(0, 0); diff --git a/e2e/nodes.spec.ts b/e2e/nodes.spec.ts index 6df05ffa..7140dd93 100644 --- a/e2e/nodes.spec.ts +++ b/e2e/nodes.spec.ts @@ -99,3 +99,23 @@ test('node sources list their nodes and a subscription can be refreshed', async await page.getByRole('button', {name: 'Refresh sub-c', exact: true}).click(); await expect(page.locator('.rp-toast.positive')).toContainText('sub-c refreshed, 100 nodes'); }); + +test('a subscription refresh interval is written into the configuration', async ({page}) => { + await page.goto('/#/nodes'); + const sources = page.locator('.rp-table').first().locator('[role=rowgroup]:last-child [role=row][data-key]'); + await expect(sources.first()).toContainText('Every 24 hours'); + // The inline source keeps no interval of its own. + await expect(sources.nth(1)).not.toContainText('Every'); + await page.getByRole('button', {name: 'Auto-refresh of sub-c', exact: true}).click(); + await page.getByRole('menuitemradio', {name: 'Every 6 hours', exact: true}).click(); + await expect(page.locator('.rp-toast.positive')).toContainText('sub-c auto-refresh written to the configuration and reloaded: Every 6 hours'); + await expect(sources.first()).toContainText('Every 6 hours'); + await page.goto('/#/config'); + await expect(page.locator('.cm-content')).toContainText( + "sub-c: {\n url: 'https://sub.example.net/api/v1/client/subscribe?token=demo'\n interval: '21600s'\n }" + ); + await page.goto('/#/nodes'); + await page.getByRole('button', {name: 'Auto-refresh of sub-c', exact: true}).click(); + await page.getByRole('menuitemradio', {name: 'Manual only', exact: true}).click(); + await expect(sources.first()).toContainText('Manual only'); +}); diff --git a/e2e/search.spec.ts b/e2e/search.spec.ts index a875620c..b24eab98 100644 --- a/e2e/search.spec.ts +++ b/e2e/search.spec.ts @@ -40,3 +40,17 @@ test('search opens a node in its source, a group on its card, a subscription and await dialog.getByRole('option', {name: /rules\.dae/}).click(); await expect(page).toHaveURL(/#\/config\?tab=source&source=src-rules$/); }); + +test('search finds a routing rule by its condition and lands on its row', async ({page}) => { + await page.goto('/#/activity'); + await expect(page.locator('.rp-nav').first()).toBeVisible(); + const dialog = await open(page, 'doubleclick'); + // The connection to doubleclick.net is a hit too; the rule is the one that names its outbound. + const hit = dialog.getByRole('option', {name: /domain\(suffix: doubleclick\.net\).*→ block/}); + await expect(hit).toHaveCount(1); + await hit.click(); + await expect(page).toHaveURL(/#\/rules\?tab=list&rule=/); + const row = page.locator('[role="row"][aria-selected="true"]'); + await expect(row).toContainText('doubleclick'); + await expect(row).toBeInViewport(); +}); diff --git a/src/api/client.test.ts b/src/api/client.test.ts index db5bade7..2c3a2db4 100644 --- a/src/api/client.test.ts +++ b/src/api/client.test.ts @@ -86,6 +86,19 @@ describe('native transport', () => { await vi.advanceTimersByTimeAsync(1); await expect(result).resolves.toMatchObject({status: 'failed', error: {code: 'reload_failed'}}); }); + it('keeps a proxy prefix when following an operation href', async () => { + vi.useFakeTimers(); + const request = vi + .fn() + .mockResolvedValueOnce(json(acceptedBody, 202, {Location: acceptedBody.href, 'Retry-After': '1'})) + .mockResolvedValueOnce(json({operation_id: 'op-1', status: 'succeeded'})); + vi.stubGlobal('fetch', request); + const api = createApi('https://honk.test/doona'); + const result = api.pollOperation(await api.startReload()); + await vi.advanceTimersByTimeAsync(1000); + expect(String(request.mock.calls[1][0])).toBe('https://honk.test/doona' + acceptedBody.href); + await expect(result).resolves.toMatchObject({status: 'succeeded'}); + }); it('enforces the one-second floor and aborts without another GET', async () => { vi.useFakeTimers(); const request = vi.fn(); diff --git a/src/api/client.ts b/src/api/client.ts index c68a38bf..8be74f8c 100644 --- a/src/api/client.ts +++ b/src/api/client.ts @@ -35,9 +35,11 @@ export function createApi(base: string, token?: string): Api { // Every mutation the contract lets a client repeat safely carries a fresh key, so a retry after a lost // reply cannot start the same operation twice. const once = () => ({'Idempotency-Key': uuid()}); + // The contract pins an operation's href to an absolute /api/v1 path; a base URL that carries a proxy prefix + // keeps it, so the path is resolved under the base rather than against its origin. const resolveHref = (href: string) => { const root = new URL(baseUrl + '/', globalThis.location?.href); - const url = new URL(href, root); + const url = new URL(href.replace(/^\/+/, ''), root); if (url.origin !== root.origin) throw new ApiError(0, 'invalid_location', 'Operation URL has a different origin'); return url; }; diff --git a/src/api/mock/config.ts b/src/api/mock/config.ts index 314f54e7..6231f401 100644 --- a/src/api/mock/config.ts +++ b/src/api/mock/config.ts @@ -31,12 +31,13 @@ export function diagnose(sourceId: string, text: string, groups: Set, mo const line = index + 1; const code = raw.replace(/#.*$/, '').trim(); if (!code) return; - const open = /^([A-Za-z_][\w.-]*)\s*\{\s*(.*)$/.exec(code); + // A section is `name {`; an entry block inside one is `tag: {`, the tag quoted or bare. + const open = /^(?:'([^']*)'|"([^"]*)"|([A-Za-z_][\w.-]*))\s*:?\s*\{\s*(.*)$/.exec(code); if (open) { - const name = open[1]; + const name = open[1] ?? open[2] ?? open[3]; if (stack.length === 0 && !sections.has(name)) at(line, 1, 'error', 'unknown_section', `Unknown section "${name}"`); stack.push({name, line}); - if (/\}\s*$/.test(open[2])) stack.pop(); + if (/\}\s*$/.test(open[4])) stack.pop(); return; } if (code === '}') { diff --git a/src/api/mock/index.ts b/src/api/mock/index.ts index 116c3cf8..67857f1f 100644 --- a/src/api/mock/index.ts +++ b/src/api/mock/index.ts @@ -94,6 +94,19 @@ export function createMockApi(): Api { if (profile === 'm1') connections.visibility = 'partial'; const runtime = structuredClone(fixtures.runtime); const outbounds = structuredClone(fixtures.runtimeOutbounds); + // A large deployment lists dozens of outbounds, most of them idle. + if (big) + outbounds.outbounds.push( + ...Array.from({length: 24}, (_, i) => ({ + name: `kad.${['hk', 'jp', 'us'][i % 3]}.${String(i + 1).padStart(2, '0')}`, + kind: 'group' as const, + active_connections: 0, + total_connections: '1', + upload_bytes: '0', + download_bytes: String(Math.max(0, 900_000 - i * 60_000)), + errors: '0' + })) + ); const dnsCache = structuredClone(fixtures.dnsCache); const revisions = new Map(); const operations = new Map(); diff --git a/src/api/selectors.test.ts b/src/api/selectors.test.ts index 8a72e19e..1445937f 100644 --- a/src/api/selectors.test.ts +++ b/src/api/selectors.test.ts @@ -1,6 +1,6 @@ import {expect, it} from 'vitest'; import type {ApiEvent} from './model'; -import {routineGap, shortId} from './selectors'; +import {probeSummary, routineGap, shortId} from './selectors'; const gap = (reason: string, resource_id: string | null): ApiEvent => ({ @@ -23,3 +23,35 @@ it('shortens a UUID to its first block and leaves other ids alone', () => { expect(shortId('gen-41')).toBe('gen-41'); expect(shortId('—')).toBe('—'); }); + +it('counts each probed member once, by the row that says most', () => { + const row = (member_id: string, ip_version: 'ipv4' | 'ipv6', state: 'healthy' | 'unavailable' | 'unknown') => ({ + member_id, + ip_version, + state, + kind: 'tcp_connect', + transport: 'tcp', + purpose: 'data', + warmth: 'cold', + latency_ms: state === 'healthy' ? 0.2 : null, + error: state === 'healthy' ? null : {code: state === 'unknown' ? 'address_unavailable' : 'probe_failed', message: ''}, + health_updated: true, + observed_at: '2026-09-20T04:12:36.546Z', + resolved_leaf_node_id: member_id + }); + const summary = probeSummary({ + target: {type: 'group', group_id: 'g'}, + selection_changed: {tcp: false, udp: false}, + selection_before: {tcp: null, udp: null}, + selection_after: {tcp: null, udp: null}, + // Every member also gets an ipv6 row with no address; it must not hide the ipv4 answer. + results: [ + row('a', 'ipv4', 'healthy'), + row('a', 'ipv6', 'unknown'), + row('b', 'ipv6', 'unknown'), + row('b', 'ipv4', 'unavailable'), + row('c', 'ipv4', 'unknown') + ] + } as unknown as Parameters[0]); + expect(summary).toEqual({key: 'policy.probeUnchanged', params: {healthy: 1, unavailable: 1, unknown: 1}}); +}); diff --git a/src/api/selectors.ts b/src/api/selectors.ts index 2f2b4ae7..21be8ad6 100644 --- a/src/api/selectors.ts +++ b/src/api/selectors.ts @@ -7,7 +7,6 @@ import type { EventKind, FlowStep, Group, - GroupSummary, HealthObservation, Node, ProbeResult, @@ -21,12 +20,22 @@ import type {RuntimeOutbounds, TrafficHistory} from './model'; // The one TCP data observation a node's latency column shows. Backends differ in what they measure (honk's // periodic probe reports HTTP headers on an unknown-warmth session; a warm TCP connect is the cheapest), so // the pick is a ranking rather than a fixed tuple: warmth, then measurement cost, then IPv4 before IPv6. -const warmthRank = {warm: 0, unknown: 1, mixed: 2, cold: 3}; -const measurementRank = {tcp_connect: 0, http_headers: 1, http_round_trip: 2, quic_handshake: 3, mixed: 4, unknown: 5, dns_round_trip: 6}; -export function preferredHealth(node: Node): HealthObservation | undefined { - const rank = (h: HealthObservation) => warmthRank[h.warmth] * 100 + measurementRank[h.measurement] * 10 + (h.ip_version === 'ipv4' ? 0 : 1); - return node.health.filter(h => h.transport === 'tcp' && h.purpose === 'data').sort((a, b) => rank(a) - rank(b))[0]; +// Vocabulary a newer backend adds sorts with the unknown entries rather than falling out of the order. +const warmthRank: Record = {warm: 0, unknown: 1, mixed: 2, cold: 3}; +const measurementRank: Record = { + tcp_connect: 0, + http_headers: 1, + http_round_trip: 2, + quic_handshake: 3, + mixed: 4, + unknown: 5, + dns_round_trip: 6 +}; +export function preferredObservation(health: T[]): T | undefined { + const rank = (h: HealthObservation) => (warmthRank[h.warmth] ?? 1) * 100 + (measurementRank[h.measurement] ?? 5) * 10 + (h.ip_version === 'ipv4' ? 0 : 1); + return health.filter(h => h.transport === 'tcp' && h.purpose === 'data').sort((a, b) => rank(a) - rank(b))[0]; } +export const preferredHealth = (node: Node) => preferredObservation(node.health); export function outboundUsage(snapshot: RuntimeOutbounds | undefined) { const total = snapshot ? addU64(...snapshot.outbounds.map(row => row.download_bytes)) : null; @@ -71,19 +80,6 @@ export const policyKindLabels: Record = { random: 'policy.kind.random', score: 'policy.kind.score' }; -// The node a group currently exits through, following nested groups by their TCP selection; undefined when the -// chain is broken or cycles. Summaries carry member ids only, so node names come from the node list. -export function groupLeaf(groupId: string, groups: GroupSummary[], nodes: Node[]): string | undefined { - const byGroup = new Map(groups.map(group => [group.id, group])); - const byNode = new Map(nodes.map(node => [node.id, node.name])); - const seen = new Set(); - let id: string | null = groupId; - while (id && byGroup.has(id) && !seen.has(id)) { - seen.add(id); - id = byGroup.get(id)!.selection.tcp_member_id; - } - return id ? byNode.get(id) : undefined; -} // Built-in outbounds read in the user's language; group and node names stay as configured. export function outboundLabel(name: string | null, label: LabelFn): string { return name === 'direct' ? label('ui.direct') : name === 'block' ? label('ui.block') : name === null || name === 'unknown' ? label('ui.unknown') : name; @@ -95,10 +91,6 @@ export function chainLabel(row: Pick, label?: if (row.outbound === 'direct' || row.outbound === 'block') return label ? outboundLabel(row.outbound, label) : row.outbound; return chainNames(row.chain, names).join(' → ') || '—'; } -// The node a chain ends in, by name, for the mark beside it. -export const chainLeaf = (row: Pick, names?: OutboundNames): string | null => - row.outbound === 'direct' || row.outbound === 'block' ? row.outbound : (chainNames(row.chain, names).at(-1) ?? null); - export const lifecycleStates: Record = { starting: 'lifecycle.starting', running: 'lifecycle.running', @@ -316,11 +308,14 @@ export function groupConfigFields(group: Group): Array<[Key | MessageRef, string }); } +// A member gets one row per address family; the one that says most wins: a failure over a success, a +// success over a family with no address. +const probeRank = {unknown: 0, healthy: 1, unavailable: 2}; export function probeSummary(result: ProbeResult): MessageRef { const members = new Map(); for (const item of result.results) { const previous = members.get(item.member_id); - if (previous !== 'unavailable' && (previous !== 'unknown' || item.state === 'unavailable')) members.set(item.member_id, item.state); + if (!previous || probeRank[item.state] > probeRank[previous]) members.set(item.member_id, item.state); } const states = [...members.values()]; return { diff --git a/src/api/store.ts b/src/api/store.ts index 6e29fdea..4e94ef69 100644 --- a/src/api/store.ts +++ b/src/api/store.ts @@ -129,12 +129,32 @@ type Resource = { acceptEvent?: (event: ApiEvent) => boolean; }; +// The last answer for every resource, per backend: a page that mounts again paints it at once and refreshes +// behind it, instead of a loading placeholder that flashes before the same data arrives ten milliseconds later. +const remembered = new WeakMap>(); +function recall(api: Api, name: string): T | undefined { + return remembered.get(api)?.get(name) as T | undefined; +} +function remember(api: Api, name: string, data: unknown) { + let store = remembered.get(api); + if (!store) remembered.set(api, (store = new Map())); + store.set(name, data); +} +// Test seam: forget every remembered answer. +export function forgetResources() { + for (const api of [getApi()]) remembered.delete(api); +} + function useResource(resource: Resource, {every = 5000, deps = [], enabled = true}: {every?: number; deps?: DependencyList; enabled?: boolean} = {}) { const api = getApi(); const name = normalizeResourceKey(resource.key); const lane = resource.key[0]; const [key, setKey] = useState(() => ({api, name, every, enabled, deps})); - const [state, setState] = useState<{data: T | undefined; loading: boolean; error: Error | null}>({data: undefined, loading: enabled, error: null}); + const start = (api: Api, name: string, enabled: boolean) => { + const data = enabled ? recall(api, name) : undefined; + return {data, loading: enabled && data === undefined, error: null as Error | null}; + }; + const [state, setState] = useState<{data: T | undefined; loading: boolean; error: Error | null}>(() => start(api, name, enabled)); // Match React's dependency comparison without serializing API object identities. if ( key.api !== api || @@ -145,7 +165,7 @@ function useResource(resource: Resource, {every = 5000, deps = [], enabled deps.some((dep, i) => !Object.is(dep, key.deps[i])) ) { setKey({api, name, every, enabled, deps}); - setState({data: undefined, loading: enabled, error: null}); + setState(start(api, name, enabled)); } const current = useRef(resource.fetch); useEffect(() => { @@ -166,6 +186,7 @@ function useResource(resource: Resource, {every = 5000, deps = [], enabled data => { pending = undefined; request.release(); + remember(key.api, key.name, data); if (!disposed) setState({data, loading: false, error: null}); }, reason => { diff --git a/src/features/activity/Activity.tsx b/src/features/activity/Activity.tsx index abe74201..73956800 100644 --- a/src/features/activity/Activity.tsx +++ b/src/features/activity/Activity.tsx @@ -60,7 +60,8 @@ export function Activity({go}: {go: (page: string) => void}) { [nodesResource.data] ); const [by, setBy] = useState('dev'); - const connections = useConnections(); + const hasConnections = resources?.connections.available === true; + const connections = useConnections(undefined, hasConnections); const feed = useEventFeed(); const ranking = useMemo(() => { const totals = new Map(); @@ -105,7 +106,8 @@ export function Activity({go}: {go: (page: string) => void}) { // Only events a person acts on: an operation's outcome, a new generation, a real gap in the records, a lost // and regained stream. The per-second runtime and flow ticks drive the charts, and the ring's own // housekeeping is not a problem. - const events = feed.events.filter(event => event.event !== 'runtime.updated' && event.event !== 'flow.updated' && !routineGap(event)).slice(0, 6); + // As many as the card holds at its neighbours' height; past that the list scrolls inside the card. + const events = feed.events.filter(event => event.event !== 'runtime.updated' && event.event !== 'flow.updated' && !routineGap(event)).slice(0, 30); return ( <>
@@ -235,6 +237,7 @@ export function Activity({go}: {go: (page: string) => void}) { fmt={chartRate} locale={locale} height={120} + fill window={{since: series.since, until: series.until}} /> @@ -284,8 +287,10 @@ export function Activity({go}: {go: (page: string) => void}) { )} {!connections.data ? ( - connections.error ? null : ( + connections.error ? null : hasConnections ? ( {t('act.loading')} + ) : ( + {t('shell.notOfferedShort')} ) ) : ranking.length === 0 ? ( {t('act.rankingEmpty')} @@ -323,6 +328,7 @@ export function Activity({go}: {go: (page: string) => void}) { fmt={memoryBytes} locale={locale} height={150} + fill baseline="auto" window={{since: memoryHistory.since, until: memoryHistory.until}} /> @@ -351,7 +357,7 @@ export function Activity({go}: {go: (page: string) => void}) { ) : events.length === 0 ? ( {t(feed.available === false ? 'event.unavailable' : 'act.noIssues')} ) : ( -
+
{events.map(event => { const summary = eventSummary(event, t); return ( diff --git a/src/features/activity/ModeSwitch.tsx b/src/features/activity/ModeSwitch.tsx index 2f3b46ea..7a8eb479 100644 --- a/src/features/activity/ModeSwitch.tsx +++ b/src/features/activity/ModeSwitch.tsx @@ -1,8 +1,8 @@ import {useState} from 'react'; import {useT} from '../../i18n'; import type {Key} from '../../i18n/messages'; -import {useCapabilities, useConfig, useConfigEditor, useGroups} from '../../api/store'; -import {candidate} from '../config/names'; +import {useCapabilities, useGroups} from '../../api/store'; +import {useMainSourceEdit} from '../config/mainSource'; import {Button, Light, MenuButton, Segmented, errorText, toast} from '../../ui/ui'; import Shuffle from '../../ui/icons/Shuffle'; import Filter from '../../ui/icons/Filter'; @@ -17,11 +17,8 @@ const modeLabels: Record<(typeof order)[number], Key> = {rule: 'mode.rule', dire export function ModeCards() { const t = useT(); const resources = useCapabilities().data?.resources; - const writable = resources?.config.available === true && resources.config.writable === true && resources.config.content === true; - const config = useConfig(resources?.config.available === true); const groups = useGroups(resources?.groups.available === true); - const editor = useConfigEditor(config.refetch); - const main = config.data?.sources.find(source => source.kind === 'main' && source.writable && typeof source.content === 'string'); + const {main, writable, busy, apply: write} = useMainSourceEdit(); const current: OutboundMode = main ? readMode(main.content!) : {mode: 'rule'}; const [staged, setStaged] = useState(null); const shown = staged ?? current; @@ -34,27 +31,22 @@ export function ModeCards() { else if (mode === 'direct' || mode === 'rule') setStaged({mode}); }; const apply = async () => { - if (!main || !staged) return; - let content: string; + if (!staged) return; + let written: boolean; try { - content = writeMode(main.content!, staged); + written = await write( + text => writeMode(text, staged), + errors => toast('negative', t('act.modeInvalid', {n: String(errors)})) + ); } catch { toast('negative', t('act.modeNoRouting')); return; } - const check = await editor.validate({sources: [candidate(main, content)], mode: 'full'}); - if (!check) return; - if (!check.valid) { - toast('negative', t('act.modeInvalid', {n: String(check.diagnostics.filter(d => d.level === 'error').length)})); - return; - } - const result = await editor.save(main.id, content, main.content_sha256); - if (result) { + if (written) { setStaged(null); toast('positive', t('act.modeApplied', {mode: t(modeLabels[staged.mode])})); } }; - const busy = editor.busy !== null; return ( <>
diff --git a/src/features/activity/mode.ts b/src/features/activity/mode.ts index bc8235bd..0e40e8c0 100644 --- a/src/features/activity/mode.ts +++ b/src/features/activity/mode.ts @@ -1,3 +1,5 @@ +import {topLevelBlock} from '../config/blocks'; + // The outbound mode as a staged configuration edit: honk keeps no native mode switch, so doona writes one // catch-all rule into the routing section and reloads. `rule` is the configuration as written; `direct` // sends everything the must-rules leave straight out; `global` sends it all through one outbound. The rule @@ -15,26 +17,12 @@ export function readMode(text: string): OutboundMode { return {mode: 'rule'}; } -// The first top-level routing block's line range, exclusive of its braces; null when the text has none. -// The dns section has a routing block of its own, so the depth is tracked from the start of the file. -function routingBlock(lines: string[]): {open: number; close: number} | null { - let depth = 0; - let open = -1; - for (let i = 0; i < lines.length; i++) { - const code = lines[i].replace(/#.*$/, ''); - if (open === -1 && depth === 0 && /^\s*routing\s*\{\s*$/.test(code)) open = i; - depth += (code.match(/\{/g) ?? []).length - (code.match(/\}/g) ?? []).length; - if (open !== -1 && depth === 0) return {open, close: i}; - } - return null; -} - // Presets marked `(must)` keep applying in every mode, as the engine promises; the catch-all goes after the // last of them so LAN and resolver traffic stays where the author put it. export function writeMode(text: string, next: OutboundMode): string { const lines = text.split('\n').filter(line => !modeLine.test(line)); if (next.mode === 'rule') return lines.join('\n'); - const block = routingBlock(lines); + const block = topLevelBlock(lines, 'routing'); if (!block) throw new Error('no routing section'); const body = lines.slice(block.open + 1, block.close); const indent = body.find(line => line.trim())?.match(/^\s*/)?.[0] ?? ' '; diff --git a/src/features/config/Wizard.tsx b/src/features/config/Wizard.tsx index 6a107398..7eaba9e9 100644 --- a/src/features/config/Wizard.tsx +++ b/src/features/config/Wizard.tsx @@ -83,36 +83,39 @@ export function Wizard({

{t('config.wizardSubscriptions')}

- {state.subscriptions.map((item, index) => ( -
- {item.raw !== undefined && !item.name ? ( - // A line in a form the wizard does not model (a file, a multi-line entry) stays as written. - {item.raw.trim()} - ) : ( - <> - setSubscription(index, {name})} /> - setSubscription(index, {url})} - /> - - )} - -
- ))} + {state.subscriptions.map((item, index) => + // A blank line is kept for the round trip but is not a row. + item.raw !== undefined && !item.raw.trim() ? null : ( +
+ {item.raw !== undefined && !item.name ? ( + // A line in a form the wizard does not model (a file, a multi-line entry) stays as written. + {item.raw.trim()} + ) : ( + <> + setSubscription(index, {name})} /> + setSubscription(index, {url})} + /> + + )} + +
+ ) + )}