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.
This commit is contained in:
Zakk committed 2026-09-20 14:15:20 +10:00
1 parent 2d6c2f3c3d
commit fdb993eeac
46 files changed
+908 -296

No files matched your search

+10
View File
@@ -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);
});
});
+9
View File
@@ -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();
});
+4 -1
View File
@@ -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<string, number> = {};
let hold: Promise<void> | undefined;
+5
View File
@@ -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);
+20
View File
@@ -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');
});
+14
View File
@@ -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();
});
+13
View File
@@ -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();
+3 -1
View File
@@ -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;
};
+4 -3
View File
@@ -31,12 +31,13 @@ export function diagnose(sourceId: string, text: string, groups: Set<string>, 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 === '}') {
+13
View File
@@ -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<string, bigint>();
const operations = new Map<string, OperationState>();
+33 -1
View File
@@ -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<typeof probeSummary>[0]);
expect(summary).toEqual({key: 'policy.probeUnchanged', params: {healthy: 1, unavailable: 1, unknown: 1}});
});
+19 -24
View File
@@ -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<string, number> = {warm: 0, unknown: 1, mixed: 2, cold: 3};
const measurementRank: Record<string, number> = {
tcp_connect: 0,
http_headers: 1,
http_round_trip: 2,
quic_handshake: 3,
mixed: 4,
unknown: 5,
dns_round_trip: 6
};
export function preferredObservation<T extends HealthObservation>(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<Group['policy']['kind'], Key> = {
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<string>();
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<Connection, 'chain' | 'outbound'>, 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<Connection, 'chain' | 'outbound'>, names?: OutboundNames): string | null =>
row.outbound === 'direct' || row.outbound === 'block' ? row.outbound : (chainNames(row.chain, names).at(-1) ?? null);
export const lifecycleStates: Record<Runtime['lifecycle']['state'], Key> = {
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<string, 'healthy' | 'unavailable' | 'unknown'>();
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 {
+23 -2
View File
@@ -129,12 +129,32 @@ type Resource<T> = {
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<Api, Map<string, unknown>>();
function recall<T>(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<T>(resource: Resource<T>, {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<T>(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<T>(resource: Resource<T>, {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<T>(resource: Resource<T>, {every = 5000, deps = [], enabled
data => {
pending = undefined;
request.release();
remember(key.api, key.name, data);
if (!disposed) setState({data, loading: false, error: null});
},
reason => {
+10 -4
View File
@@ -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<string, bigint | null>();
@@ -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 (
<>
<div className="rp-quick">
@@ -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}) {
</TextTooltip>
)}
{!connections.data ? (
connections.error ? null : (
connections.error ? null : hasConnections ? (
<Loading>{t('act.loading')}</Loading>
) : (
<span className="rp-empty">{t('shell.notOfferedShort')}</span>
)
) : ranking.length === 0 ? (
<span className="rp-empty">{t('act.rankingEmpty')}</span>
@@ -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 ? (
<span className="rp-empty">{t(feed.available === false ? 'event.unavailable' : 'act.noIssues')}</span>
) : (
<div className="rp-list" role="list">
<div className="rp-list rp-feed" role="list">
{events.map(event => {
const summary = eventSummary(event, t);
return (
+10 -18
View File
@@ -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<OutboundMode | null>(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 (
<>
<div className="rp-card">
+3 -15
View File
@@ -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] ?? ' ';
+33 -30
View File
@@ -83,36 +83,39 @@ export function Wizard({
<h3 className="rp-h3">{t('config.wizardSubscriptions')}</h3>
<div className="rp-list">
{state.subscriptions.map((item, index) => (
<div className="rp-toolbar top" key={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.
<span className="rp-code rp-grow">{item.raw.trim()}</span>
) : (
<>
<TextField label={t('config.wizardSubscriptionName')} value={item.name} width={140} onChange={name => setSubscription(index, {name})} />
<TextField
label={t('config.wizardSubscription')}
value={item.url}
width={520}
placeholder="https://example.org/sub?token=…"
isInvalid={item.url !== '' && !isSubscriptionUrl(item.url)}
error={item.url !== '' && !isSubscriptionUrl(item.url) ? t('config.wizardSubscriptionHelp') : undefined}
description={index === 0 ? t('config.wizardSubscriptionHelp') : undefined}
onChange={url => setSubscription(index, {url})}
/>
</>
)}
<Button
quiet
small
label={t('config.wizardRemove', {name: item.name || item.raw?.trim() || ''})}
onPress={() => patch({subscriptions: state.subscriptions.filter((_, i) => i !== index)})}
>
<Close />
</Button>
</div>
))}
{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 : (
<div className="rp-toolbar top" key={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.
<span className="rp-code rp-grow">{item.raw.trim()}</span>
) : (
<>
<TextField label={t('config.wizardSubscriptionName')} value={item.name} width={140} onChange={name => setSubscription(index, {name})} />
<TextField
label={t('config.wizardSubscription')}
value={item.url}
width={520}
placeholder="https://example.org/sub?token=…"
isInvalid={item.url !== '' && !isSubscriptionUrl(item.url)}
error={item.url !== '' && !isSubscriptionUrl(item.url) ? t('config.wizardSubscriptionHelp') : undefined}
description={index === 0 ? t('config.wizardSubscriptionHelp') : undefined}
onChange={url => setSubscription(index, {url})}
/>
</>
)}
<Button
quiet
small
label={t('config.wizardRemove', {name: item.name || item.raw?.trim() || ''})}
onPress={() => patch({subscriptions: state.subscriptions.filter((_, i) => i !== index)})}
>
<Close />
</Button>
</div>
)
)}
<div>
<Button small onPress={() => patch({subscriptions: [...state.subscriptions, {name: `sub-${state.subscriptions.length + 1}`, url: ''}]})}>
{t('config.wizardAddSubscription')}
+15
View File
@@ -0,0 +1,15 @@
// The line range of the first top-level `name {` block, exclusive of its braces; null when the text has
// none. Nested sections reuse names (dns has a routing block of its own), so the depth is tracked from the
// start of the file and only a block opened at depth zero counts.
export function topLevelBlock(lines: string[], name: string): {open: number; close: number} | null {
const header = new RegExp(`^\\s*${name}\\s*\\{\\s*$`);
let depth = 0;
let open = -1;
for (let i = 0; i < lines.length; i++) {
const code = lines[i].replace(/#.*$/, '');
if (open === -1 && depth === 0 && header.test(code)) open = i;
depth += (code.match(/\{/g) ?? []).length - (code.match(/\}/g) ?? []).length;
if (open !== -1 && depth === 0) return {open, close: i};
}
return null;
}
+44
View File
@@ -0,0 +1,44 @@
import {useCapabilities, useConfig, useConfigEditor} from '../../api/store';
import {candidate} from './names';
import type {ConfigSource} from '../../api/model';
// One path for a control that rewrites the main source as a whole: read it, transform its text, validate in
// full, write it back with the hash it was read at, reload. The pages that stage a small edit (the outbound
// mode, a subscription's refresh interval) share it instead of each carrying the sequence.
export type MainSourceEdit = {
// The writable main source with its text, or null while the backend offers none.
main: ConfigSource | null;
// Whether the backend lets this page write at all: configuration content and writes both offered.
writable: boolean;
busy: boolean;
// Resolves to true when the write reached the engine; false when validation refused it (the count of errors
// is handed to `onInvalid`) or the transform threw.
apply: (transform: (text: string) => string, onInvalid?: (errors: number) => void) => Promise<boolean>;
};
export function useMainSourceEdit(): MainSourceEdit {
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 editor = useConfigEditor(config.refetch);
const main = config.data?.sources.find(source => source.kind === 'main' && source.writable && typeof source.content === 'string') ?? null;
return {
main,
writable,
busy: editor.busy !== null,
apply: async (transform, onInvalid) => {
if (!main) return false;
const content = transform(main.content!);
// The dry run is optional in the contract; without it the write's own validation answers instead.
if (resources?.config_validate.available && resources.config_validate.modes?.includes('full')) {
const check = await editor.validate({sources: [candidate(main, content)], mode: 'full'});
if (!check) return false;
if (!check.valid) {
onInvalid?.(check.diagnostics.filter(d => d.level === 'error').length);
return false;
}
}
return !!(await editor.save(main.id, content, main.content_sha256));
}
};
}
+4
View File
@@ -63,6 +63,10 @@ describe('quick setup text transforms', () => {
expect(out).toContain(' dip(geoip:cn) -> direct');
expect(readState(out).subscriptions.map(s => [s.name, s.url])).toEqual(state.subscriptions.map(s => [s.name, s.url]));
});
it('round-trips an untouched file, blank lines in the subscription block included', () => {
const spaced = main.replace(' # a file the engine reads\n', '\n # a file the engine reads\n');
expect(writeState(spaced, readState(spaced))).toBe(spaced);
});
it('replaces routing with a template routed to the first group', () => {
const out = writeState(main, {...readState(main), rules: 'gfw'});
expect(out).toContain('domain(geosite:gfw) -> proxy');
+1 -1
View File
@@ -49,7 +49,7 @@ export function readState(text: string): WizardState {
const match = /^\s*(?:'([^']*)'|([\w.-]+))\s*:\s*'([^']*)'\s*$/.exec(line.replace(/#.*$/, ''));
// Only an http(s) URL is edited in the form; a file or any other shape stays as written.
if (match && isSubscriptionUrl(match[3])) subscriptions.push({name: match[1] ?? match[2], url: match[3], raw: line});
else if (line.trim()) subscriptions.push({name: '', url: '', raw: line});
else subscriptions.push({name: '', url: '', raw: line});
}
// The first group's name, whatever characters it uses; comment lines are skipped.
const group = groupNames(found.find(s => s.name === 'group')?.body ?? [])[0] ?? null;
+10 -11
View File
@@ -1,11 +1,11 @@
import {useEffect, useMemo} from 'react';
import {Cell, Column, ColumnResizer, ResizableTableContainer, Row, Table, TableBody, TableHeader, TableLayout, Virtualizer} from 'react-aria-components';
import {chainLabel, chainLeaf, connectionStates, relativeStart, type OutboundNames} from '../../api/selectors';
import {OutboundMark} from '../policies/Mark';
import {chainLabel, connectionStates, relativeStart, type OutboundNames} from '../../api/selectors';
import {useCapabilities} from '../../api/store';
import type {Connection} from '../../api/model';
import {formatBytes} from '../../api/u64';
import {LOCALE, useLang, useT} from '../../i18n';
import {Badge, Loading, TextTooltip, fitColumns, tableLayout, useContentWidth} from '../../ui/ui';
import {Badge, Loading, TextTooltip, fitColumns, tableLayout, useContentWidth, useFillHeight, RuleRef} from '../../ui/ui';
import {columns, tableRows, type ConnectionView} from './view';
@@ -43,6 +43,10 @@ export function ConnectionTable({
),
[view.hidden, width]
);
// As tall as the screen allows, but no taller than the rows need.
const [fillRef, fill] = useFillHeight<HTMLDivElement>(442);
const rulesListed = useCapabilities().data?.resources.rules.available === true;
const height = Math.min(fill, 2 + tableLayout.headingHeight + Math.max(flatRows.length, 2) * tableLayout.rowHeight);
const selectedIndex = flatRows.findIndex(row => row?.id === selected);
useEffect(() => {
// Wait for RAC to commit the virtual content height before revealing a deep link.
@@ -60,15 +64,10 @@ export function ConnectionTable({
const cells: Record<string, React.ReactNode> = {
dst: <TextTooltip>{c.domain || c.dst || '—'}</TextTooltip>,
src: <TextTooltip className="rp-code">{c.src ?? '—'}</TextTooltip>,
chain: (
<span className="rp-chain">
<OutboundMark name={chainLeaf(c, names)} />
<TextTooltip>{chainLabel(c, t, names)}</TextTooltip>
</span>
),
chain: <TextTooltip className="rp-chain">{chainLabel(c, t, names)}</TextTooltip>,
rule: (
<span className="rp-rule">
<TextTooltip text={c.rule_expression ?? undefined}>{c.rule_expression ?? '—'}</TextTooltip>
<RuleRef expression={c.rule_expression} ruleId={c.rule_id} linked={rulesListed} />
{c.rule_source === 'recomputed' && <Badge>{t('conn.recomputed')}</Badge>}
</span>
),
@@ -95,7 +94,7 @@ export function ConnectionTable({
}
}}
>
<ResizableTableContainer className="rp-table">
<ResizableTableContainer ref={fillRef} className="rp-table" style={{height}}>
<Virtualizer layout={TableLayout} layoutOptions={tableLayout}>
<Table
ref={ref}
+3 -2
View File
@@ -162,9 +162,10 @@ export function Connections({go, query}: PageProps) {
{canClose && (
<CloseAllButton
count={shown.length}
// Network and source-IP filters are the bulk endpoint's own; a text or outbound filter is not.
// Network and source-IP filters are the bulk endpoint's own; a text or outbound filter is not. A
// truncated snapshot lists fewer rows than match, so it closes the listed ones only.
selection={
out === 'all' && (src || !needle)
out === 'all' && (src || !needle) && !resource.data?.truncated
? {query: {type: network as 'all' | 'tcp' | 'udp', src: src ?? undefined, all: true}}
: {ids: shown.map(c => c.id)}
}
+5 -3
View File
@@ -19,7 +19,8 @@ import {
downloadFile,
errorText,
toast,
exportName
exportName,
useDebounced
} from '../../ui/ui';
import Download from '../../ui/icons/Download';
import type {PageProps} from '../types';
@@ -160,7 +161,7 @@ export function Dns({go, query}: PageProps) {
)}
<span className="rp-grow" />
<FlushCacheButton
count={dns.cache.data?.total ?? 0}
count={dns.cache.data ? dns.cache.data.total : null}
busy={dns.busy === 'flush'}
isDisabled={!!dns.busy || !resources?.dns_cache.available || !resources.dns_cache.flush}
onFlush={() => void flush()}
@@ -227,7 +228,8 @@ function DnsLog({enabled, initialName}: {enabled: boolean; initialName: string})
const [name, setName] = useState(initialName);
const [type, setType] = useState('all');
const [src, setSrc] = useState('');
const log = useDnsLog({name, type, src}, enabled);
// Each text filter is a server-side query, so it reaches the request only after typing pauses.
const log = useDnsLog({name: useDebounced(name, 300), type, src: useDebounced(src, 300)}, enabled);
const rows = (log.data?.records ?? []).map(record => ({...record, id: record.id}));
return (
<>
+1 -10
View File
@@ -3,7 +3,6 @@ import {useT, formatNumber, useLang, LOCALE} from '../../i18n';
import type {GroupSummary, Node} from '../../api/model';
import {outboundLabel, policyKindLabels, preferredHealth} from '../../api/selectors';
import {Button, Chips, Light, NodeTile} from '../../ui/ui';
import {OutboundMark} from '../policies/Mark';
import {lanes, type FlowMap as FlowMapData, type MapNode} from './map';
// The status light says what kind of exit it is, nothing more: a proxy group, direct, block, or unknown.
@@ -47,11 +46,6 @@ export function FlowMap({
<div className="rp-lane" key={lane.outbound.id} data-dim={dim ? '' : undefined}>
<div className="rp-lane-title">
<Light tone={tones[kind]}>
<OutboundMark
name={
kind === 'group' ? (lane.node && !lane.node.node.unknown ? lane.node.node.label : null) : lane.outbound.unknown ? null : lane.outbound.label
}
/>
<strong>{outboundLabel(lane.outbound.unknown ? null : lane.outbound.label, t)}</strong>
</Light>
<span className="rp-label">{facts}</span>
@@ -64,8 +58,7 @@ export function FlowMap({
id: rule.node.id,
label: label(rule.node),
count: n(rule.count),
countLabel: t('flow.laneFlows', {n: n(rule.count)}),
icon: rule.node.unknown ? <OutboundMark name={null} /> : undefined
countLabel: t('flow.laneFlows', {n: n(rule.count)})
}))}
value={pinned && lane.rules.some(rule => rule.node.id === pinned) ? pinned : null}
onChange={onPin}
@@ -93,7 +86,6 @@ export function FlowMap({
<div className="rp-lane-node">
<NodeTile
name={label(lane.node.node)}
icon={<OutboundMark name={lane.node.node.unknown ? null : lane.node.node.label} />}
tcp={nodeHealth?.latency_ms ?? undefined}
alive={nodeHealth ? nodeHealth.state === 'healthy' : true}
unavailable={nodeHealth?.state === 'unavailable'}
@@ -107,7 +99,6 @@ export function FlowMap({
{/* A group with no live selection has nothing to show on the right; direct and block are themselves. */}
<NodeTile
name={kind === 'group' ? t('flow.laneNoNode') : outboundLabel(lane.outbound.label, t)}
icon={<OutboundMark name={lane.outbound.unknown || kind === 'group' ? null : lane.outbound.label} />}
description={kind === 'group' ? t('flow.laneNoNodeHelp') : t('flow.builtin')}
unavailable={kind === 'group'}
selected={pinned === lane.outbound.id}
+19 -8
View File
@@ -2,9 +2,22 @@ import {useMemo, useState} from 'react';
import {useCapabilities, useFlow, useFlows, useGroups, useNodes, useOutboundNames, useRules} from '../../api/store';
import {FlowMap} from './FlowMap';
import {flowMap, flowsThrough, nodeNames} from './map';
import {chainLabel, chainLeaf, connectionStates, flowStepFields, localTime, outboundLabel, relativeStart, traceGaps} from '../../api/selectors';
import {OutboundMark} from '../policies/Mark';
import {Badge, Button, DataTable, DetailPanel, ErrorMessage, Loading, TextTooltip, Kv, LabeledSelect, Segmented, panelQuery, useMediaQuery} from '../../ui/ui';
import {chainLabel, connectionStates, flowStepFields, localTime, outboundLabel, relativeStart, traceGaps} from '../../api/selectors';
import {
Badge,
Button,
DataTable,
DetailPanel,
ErrorMessage,
Loading,
TextTooltip,
Kv,
LabeledSelect,
Segmented,
panelQuery,
useMediaQuery,
RuleRef
} from '../../ui/ui';
import {Coverage} from './Coverage';
import type {PageProps} from '../types';
import {within} from '../../shell/route';
@@ -75,6 +88,7 @@ export function FlowRecords({go, query}: PageProps) {
const params = useMemo(() => new URLSearchParams(query), [query]);
const connectionId = params.get('connection_id') ?? undefined;
const resource = useFlows(connectionId);
const rulesListed = useCapabilities().data?.resources.rules.available === true;
const names = useOutboundNames();
const id = params.get('id');
const detail = useFlow(id);
@@ -143,12 +157,9 @@ export function FlowRecords({go, query}: PageProps) {
]}
render={f => [
<TextTooltip>{f.input?.domain || f.input?.dst || f.id}</TextTooltip>,
<span className="rp-chain">
<OutboundMark name={chainLeaf(f, names)} />
<TextTooltip>{chainLabel(f, t, names)}</TextTooltip>
</span>,
<TextTooltip className="rp-chain">{chainLabel(f, t, names)}</TextTooltip>,
<span className="rp-rule">
<TextTooltip text={f.rule_expression ?? undefined}>{f.rule_expression ?? '—'}</TextTooltip>
<RuleRef expression={f.rule_expression} ruleId={f.rule_id} linked={rulesListed} />
{f.rule_source === 'recomputed' && <small className="rp-provenance">{t('conn.recomputed')}</small>}
</span>,
f.network.toUpperCase(),
+12
View File
@@ -64,3 +64,15 @@ it('draws configured rules into their lanes before any flow used them, joined to
expect(flowsThrough(flows.flows, 'rule:' + matched.rule_id, nodeNames(nodes.nodes))).toContain(matched);
}
});
it('takes a one-element chain as the leaf node the flow left through', async () => {
const api = createMockApi();
const [flows, groups, nodes] = await Promise.all([api.flows(), api.groups(), api.nodes({limit: 1000})]);
const routed = flows.flows.find(flow => flow.chain.length > 1)!;
const leaf = routed.chain[routed.chain.length - 1];
const map = flowMap([{...routed, chain: [leaf]}], groups, nodes.nodes);
// Configured selections add their own node entries; the flow itself must be counted at its leaf, not at unknown.
const names = nodeNames(nodes.nodes);
expect(map.links.some(link => link.target === 'node:' + names.get(leaf) && link.count === 1)).toBe(true);
expect(map.nodes.some(node => node.stage === 'node' && node.unknown)).toBe(false);
});
+1 -1
View File
@@ -24,7 +24,7 @@ function stageLabel(flow: FlowSummary, stage: MapStage, names: NodeNames): {labe
return flow.outbound ? {label: flow.outbound, unknown: false} : {label: 'unknown', unknown: true};
case 'node': {
if (terminal(flow.outbound)) return null;
const leaf = flow.chain.length > 1 ? flow.chain[flow.chain.length - 1] : null;
const leaf = flow.chain.at(-1) ?? null;
return leaf ? {label: names.get(leaf) ?? leaf, unknown: false} : {label: 'unknown', unknown: true};
}
}
+3 -7
View File
@@ -1,10 +1,10 @@
import {useEffect, useState} from 'react';
import {useState} from 'react';
import {useT, useLang, LOCALE} from '../../i18n';
import type {Key} from '../../i18n/messages';
import {useCapabilities, useLogFeed} from '../../api/store';
import type {LogLevel} from '../../api/model';
import {localTime} from '../../api/selectors';
import {Button, DataTable, ErrorMessage, LabeledSelect, Light, Switch, TextField, TextTooltip, downloadFile, exportName} from '../../ui/ui';
import {Button, DataTable, ErrorMessage, LabeledSelect, Light, Switch, TextField, TextTooltip, downloadFile, exportName, useDebounced} from '../../ui/ui';
import Download from '../../ui/icons/Download';
const tones: Record<LogLevel, 'muted' | 'neutral' | 'info' | 'warn' | 'err'> = {trace: 'muted', debug: 'neutral', info: 'info', warn: 'warn', error: 'err'};
@@ -26,11 +26,7 @@ export function Logs() {
const [level, setLevel] = useState<LogLevel>('info');
const [target, setTarget] = useState('');
// The module filter restarts the stream, so it follows the field only after typing pauses.
const [targetFilter, setTargetFilter] = useState('');
useEffect(() => {
const timer = setTimeout(() => setTargetFilter(target.trim()), 300);
return () => clearTimeout(timer);
}, [target]);
const targetFilter = useDebounced(target.trim(), 300);
const [paused, setPaused] = useState(false);
const feed = useLogFeed({level, target: targetFilter, paused});
const levels = resources?.logs.levels ?? ['trace', 'debug', 'info', 'warn', 'error'];
+78 -8
View File
@@ -4,7 +4,9 @@ import type {Key} from '../../i18n/messages';
import {useCapabilities, useNodeManage, useNodeProbe, useNodes, useOutboundNames, useProviderRefresh, useProviders} from '../../api/store';
import type {Node, Provider} from '../../api/model';
import {addU64, formatBytes, millis} from '../../api/u64';
import {localTime, preferredHealth, relativeStart} from '../../api/selectors';
import {formatDuration, localTime, preferredHealth, relativeStart} from '../../api/selectors';
import {useMainSourceEdit} from '../config/mainSource';
import {readSubscriptions, writeInterval} from './subscriptions';
import {
Badge,
Button,
@@ -12,6 +14,7 @@ import {
ErrorMessage,
LabeledSelect,
Light,
MenuButton,
ModalDialog,
TextField,
TextTooltip,
@@ -27,6 +30,17 @@ import type {PageProps} from '../types';
// The row doona adds for configuration nodes when the backend lists no inline provider.
const INLINE = 'inline';
// The host of a redacted subscription URL; the backend blanks the query, not the origin.
function redactedHost(url: string | null): string | null {
if (!url) return null;
try {
return new URL(url).hostname || null;
} catch {
return null;
}
}
// The refresh intervals offered, in seconds; the engine's default is the last.
const INTERVALS = [3600, 21600, 43200, 86400];
const kinds: Record<Provider['kind'], Key> = {subscription: 'nodes.kind.subscription', file: 'nodes.kind.file', inline: 'nodes.kind.inline'};
const tones = {ok: 'ok', stale: 'warn', error: 'err'} as const;
const statuses: Record<Provider['status'], Key> = {ok: 'nodes.status.ok', stale: 'nodes.status.stale', error: 'nodes.status.error'};
@@ -47,13 +61,33 @@ export function Nodes({go, query}: PageProps) {
const n = (value: number) => formatNumber(value, locale);
const resources = useCapabilities().data?.resources;
const providers = useProviders(resources?.providers.available !== false);
const nodes = useNodes();
const nodes = useNodes(resources?.nodes.available !== false);
const reload = () => {
providers.refetch();
nodes.refetch();
};
const refresh = useProviderRefresh(reload);
const manage = useNodeManage(reload);
// The refresh interval of a subscription is a line in the main source, keyed by the tag its nodes carry.
const source = useMainSourceEdit();
const entries = useMemo(() => readSubscriptions(source.main?.content ?? ''), [source.main?.content]);
const intervals = useMemo(() => new Map(entries.map(e => [e.tag, e.interval])), [entries]);
const intervalLabel = (seconds: number) =>
seconds === 0
? t('nodes.manualOnly')
: INTERVALS.includes(seconds)
? t('nodes.everyHours', {n: n(seconds / 3600)})
: formatDuration(String(seconds), locale);
const setInterval = (name: string, seconds: number) => {
void source
.apply(
text => writeInterval(text, name, seconds),
errors => toast('negative', t('nodes.intervalInvalid', {n: n(errors)}))
)
.then(written => {
if (written) toast('positive', t('nodes.intervalSet', {name, interval: intervalLabel(seconds)}));
}, fail);
};
const probe = useNodeProbe(nodes.refetch);
const params = useMemo(() => new URLSearchParams(query), [query]);
const names = useOutboundNames();
@@ -61,11 +95,25 @@ export function Nodes({go, query}: PageProps) {
// `inline` provider is taken as is; one that does not gets a row for them here, so they stay reachable.
const {list, synthetic} = useMemo(() => {
// A subscription's name may be an opaque label; the tag its nodes carry is the name the configuration uses.
// A subscription without nodes (not fetched yet, or empty) is matched to its entry by URL host when the
// backend shows one, else by elimination: the one entry no named subscription claims.
const tags = new Map<string, string>();
for (const node of nodes.data ?? []) if (node.provider_id && node.subscription_tag) tags.set(node.provider_id, node.subscription_tag);
const rows = (providers.data?.providers ?? []).map(item =>
item.kind === 'subscription' && tags.has(item.id) ? {...item, name: tags.get(item.id)!} : item
);
const byHost = (item: Provider) => {
const hostname = redactedHost(item.url_redacted);
const same = hostname ? entries.filter(entry => entry.host === hostname) : [];
return same.length === 1 ? same[0].tag : undefined;
};
const named = new Map<string, string>();
const subscriptions = (providers.data?.providers ?? []).filter(item => item.kind === 'subscription');
for (const item of subscriptions) {
const tag = tags.get(item.id) ?? byHost(item);
if (tag) named.set(item.id, tag);
}
const unnamed = subscriptions.filter(item => !named.has(item.id));
const unclaimed = entries.filter(entry => ![...named.values()].includes(entry.tag));
if (unnamed.length === 1 && unclaimed.length === 1) named.set(unnamed[0].id, unclaimed[0].tag);
const rows = (providers.data?.providers ?? []).map(item => (named.has(item.id) ? {...item, name: named.get(item.id)!} : item));
const loose = (nodes.data ?? []).filter(node => node.provider_id === null).length;
if (!loose || rows.some(item => item.kind === 'inline')) return {list: rows, synthetic: false};
const inline: Provider = {
@@ -81,7 +129,7 @@ export function Nodes({go, query}: PageProps) {
last_error: null
};
return {list: [inline, ...rows], synthetic: true};
}, [providers.data, nodes.data, t]);
}, [providers.data, nodes.data, entries, t]);
const selectedId = params.get('provider') ?? list[0]?.id ?? null;
const provider = list.find(item => item.id === selectedId) ?? null;
// The row doona added stands for the nodes with no provider; a backend's own inline provider keeps its id.
@@ -144,8 +192,9 @@ export function Nodes({go, query}: PageProps) {
if (!dialog) return;
try {
if (dialog.kind === 'provider') {
// The backend's label for a subscription may be opaque; the toast names it as the user did.
const created = await manage.addProvider({name: form.name.trim(), kind: 'subscription', url: form.value.trim()});
if (created) toast('positive', t('nodes.added', {name: created.name}));
if (created) toast('positive', t('nodes.added', {name: form.name.trim()}));
} else if (dialog.kind === 'node') {
const created = await manage.addNode({name: form.name.trim(), link: form.value.trim()});
if (created) toast('positive', t('nodes.added', {name: created.name}));
@@ -200,12 +249,14 @@ export function Nodes({go, query}: PageProps) {
{id: 'count', label: t('nodes.count'), minWidth: 80, grow: 0, align: 'end'},
{id: 'usage', label: t('nodes.usage'), minWidth: 200, drop: 2},
{id: 'updated', label: t('nodes.updated'), minWidth: 140, drop: 3},
{id: 'interval', label: t('nodes.interval'), minWidth: 130, grow: 0, drop: 4},
{id: 'expires', label: t('nodes.expires'), minWidth: 140, drop: 1},
{id: 'status', label: t('ui.state'), minWidth: 110, grow: 0},
{id: 'actions', label: t('ui.actions'), minWidth: canManageProviders ? 120 : 96, grow: 0}
]}
render={item => {
const used = usage(item);
const interval = item.kind === 'subscription' ? intervals.get(item.name) : undefined;
return [
<span className="rp-chain">
<TextTooltip text={item.url_redacted ?? undefined}>{item.name}</TextTooltip>
@@ -214,6 +265,25 @@ export function Nodes({go, query}: PageProps) {
n(item.node_count),
used ? (used.total ? t('nodes.used', {used: formatBytes(used.used), total: formatBytes(used.total)}) : formatBytes(used.used)) : '—',
<TextTooltip text={item.updated_at ? localTime(item.updated_at, locale) : undefined}>{relativeStart(item.updated_at, locale)}</TextTooltip>,
interval === undefined ? (
'—'
) : source.writable ? (
<MenuButton
quiet
label={t('nodes.intervalOf', {name: item.name})}
value={String(interval)}
isDisabled={source.busy}
onChange={key => setInterval(item.name, Number(key))}
items={[0, ...INTERVALS, ...(INTERVALS.includes(interval) || interval === 0 ? [] : [interval])].map(seconds => ({
id: String(seconds),
label: intervalLabel(seconds)
}))}
>
{intervalLabel(interval)}
</MenuButton>
) : (
intervalLabel(interval)
),
item.expires_at ? localTime(item.expires_at, locale) : '—',
<Light small tone={tones[item.status]}>
<TextTooltip text={item.last_error?.message}>{t(statuses[item.status])}</TextTooltip>
@@ -333,7 +403,7 @@ export function Nodes({go, query}: PageProps) {
<SpeedFast />
</Button>
)}
{canManageNodes && inlineId !== null && node.provider_id === inlineId && (
{canManageNodes && inlineId !== null && node.provider_id === (synthetic && inlineId === INLINE ? null : inlineId) && (
<Button
small
quiet
+18
View File
@@ -42,6 +42,12 @@ export const messages = defineMessages({
'nodes.status.error': '失敗',
'nodes.refresh': '刷新 {name}',
'nodes.refreshed': '{name} 已刷新,{n} 個節點',
'nodes.interval': '自動更新',
'nodes.intervalOf': '{name} 的自動更新',
'nodes.manualOnly': '僅手動',
'nodes.everyHours': '每 {n} 小時',
'nodes.intervalSet': '{name} 的自動更新已寫入配置並重載:{interval}',
'nodes.intervalInvalid': '校驗發現 {n} 個錯誤,未寫入',
'nodes.noProviders': '沒有節點來源。',
'nodes.of': '{name} 的節點',
'nodes.node': '節點',
@@ -91,6 +97,12 @@ export const messages = defineMessages({
'nodes.status.error': '失败',
'nodes.refresh': '刷新 {name}',
'nodes.refreshed': '{name} 已刷新,{n} 个节点',
'nodes.interval': '自动更新',
'nodes.intervalOf': '{name} 的自动更新',
'nodes.manualOnly': '仅手动',
'nodes.everyHours': '每 {n} 小时',
'nodes.intervalSet': '{name} 的自动更新已写入配置并重载:{interval}',
'nodes.intervalInvalid': '校验发现 {n} 个错误,未写入',
'nodes.noProviders': '没有节点来源。',
'nodes.of': '{name} 的节点',
'nodes.node': '节点',
@@ -141,6 +153,12 @@ export const messages = defineMessages({
'nodes.status.error': 'Failed',
'nodes.refresh': 'Refresh {name}',
'nodes.refreshed': {one: '{name} refreshed, {n} node', other: '{name} refreshed, {n} nodes'},
'nodes.interval': 'Auto-refresh',
'nodes.intervalOf': 'Auto-refresh of {name}',
'nodes.manualOnly': 'Manual only',
'nodes.everyHours': {one: 'Every hour', other: 'Every {n} hours'},
'nodes.intervalSet': '{name} auto-refresh written to the configuration and reloaded: {interval}',
'nodes.intervalInvalid': {one: 'Validation found {n} error; nothing written', other: 'Validation found {n} errors; nothing written'},
'nodes.noProviders': 'No node sources.',
'nodes.of': 'Nodes of {name}',
'nodes.node': 'Node',
+88
View File
@@ -0,0 +1,88 @@
import {describe, expect, it} from 'vitest';
import {DEFAULT_INTERVAL, parseInterval, readSubscriptions, writeInterval} from './subscriptions';
const text = `global {
log_level: info
}
subscription {
primary: 'https://example.com/sub'
compatible: 'https://example.net/sub'(honk/1.0 like) # keep the agent
'https://example.org/no_tag_link'
'paid:https://example.com/paid'
detailed: {
url: 'https://example.org/sub'
ua: 'honk/1.0'
interval: '10000s'
}
manual: {
url: "https://example.org/manual"
interval: 0
}
squeezed: { url: 'https://example.org/one-line' }
}
dns {
routing {
request { fallback: alidns }
}
}
`;
describe('readSubscriptions', () => {
it('lists every entry form with its interval', () => {
expect(readSubscriptions(text).map(e => [e.tag, e.interval])).toEqual([
['primary', DEFAULT_INTERVAL],
['compatible', DEFAULT_INTERVAL],
['example.org', DEFAULT_INTERVAL],
['paid', DEFAULT_INTERVAL],
['detailed', 10000],
['manual', 0]
]);
});
it("keeps each entry's host for matching a provider by its URL", () => {
expect(readSubscriptions(text).map(e => e.host)).toEqual(['example.com', 'example.net', 'example.org', 'example.com', 'example.org', 'example.org']);
});
it('reads the engine duration grammar', () => {
expect(parseInterval('3600s')).toBe(3600);
expect(parseInterval('2h')).toBe(7200);
expect(parseInterval('90m')).toBe(5400);
expect(parseInterval('1500ms')).toBe(2);
expect(parseInterval('86400')).toBe(86400);
expect(parseInterval('soon')).toBeNull();
});
it('finds nothing without a subscription section', () => {
expect(readSubscriptions('global {}\n')).toEqual([]);
});
});
describe('writeInterval', () => {
it('turns a scalar entry into a block and keeps its agent', () => {
const next = writeInterval(text, 'compatible', 3600);
expect(next).toContain(
` compatible: {\n url: 'https://example.net/sub'\n ua: 'honk/1.0 like'\n interval: '3600s'\n }\n 'https://example.org/no_tag_link'`
);
expect(readSubscriptions(next).find(e => e.tag === 'compatible')?.interval).toBe(3600);
});
it('names a tagless entry after its host and drops an embedded tag from the url', () => {
expect(writeInterval(text, 'example.org', 0)).toContain(` example.org: {\n url: 'https://example.org/no_tag_link'\n interval: '0s'\n }`);
expect(writeInterval(text, 'paid', 21600)).toContain(` paid: {\n url: 'https://example.com/paid'\n interval: '21600s'\n }`);
});
it('replaces, removes or adds the interval line of a block entry', () => {
expect(writeInterval(text, 'detailed', 43200)).toContain(` ua: 'honk/1.0'\n interval: '43200s'\n }`);
expect(writeInterval(text, 'detailed', DEFAULT_INTERVAL)).toContain(` ua: 'honk/1.0'\n }`);
expect(writeInterval(text, 'manual', 3600)).toContain(` url: "https://example.org/manual"\n interval: '3600s'\n }`);
});
it('leaves the text alone when nothing changes', () => {
expect(writeInterval(text, 'primary', DEFAULT_INTERVAL)).toBe(text);
expect(writeInterval(text, 'detailed', 10000)).toBe(text);
expect(writeInterval(text, 'squeezed', 0)).toBe(text);
expect(writeInterval(text, 'missing', 0)).toBe(text);
});
});
+159
View File
@@ -0,0 +1,159 @@
import {topLevelBlock} from '../config/blocks';
// A subscription's refresh interval lives in the configuration: an entry written as `tag: 'url'` refreshes
// every day, and only the block form `tag: { url: '…' interval: '3600s' }` can say otherwise. doona reads
// the interval off the main source and rewrites one entry into block form when the user changes it.
export const DEFAULT_INTERVAL = 86400;
export type SubscriptionEntry = {
tag: string;
// The URL's host, which is how a provider whose nodes carry no tag is matched to its entry.
host: string | null;
// Seconds between refreshes; 0 means the subscription is only refreshed by hand.
interval: number;
// Line range in the source, inclusive; a scalar entry spans one line.
from: number;
to: number;
};
// A quoted string at the start of the text: its unquoted value and where it ends.
function quoted(text: string): {value: string; end: number} | null {
const quote = text[0];
if (quote !== "'" && quote !== '"') return null;
const end = text.indexOf(quote, 1);
return end === -1 ? null : {value: text.slice(1, end), end: end + 1};
}
// Strip a comment that starts at the beginning of the statement or after whitespace, outside quotes.
function uncomment(line: string): string {
let quote = '';
for (let i = 0; i < line.length; i++) {
const c = line[i];
if (quote) {
if (c === quote) quote = '';
} else if (c === "'" || c === '"') quote = c;
else if (c === '#' && (i === 0 || line[i - 1] === ' ' || line[i - 1] === '\t')) return line.slice(0, i);
}
return line;
}
// The engine's duration grammar: `30s`, `1m`, `2h`, `500ms` or a bare number of seconds.
export function parseInterval(text: string): number | null {
const found = /^(\d+(?:\.\d+)?)(ms|s|m|h)?$/.exec(text.trim());
if (!found) return null;
const scale: Record<string, number> = {ms: 1 / 1000, s: 1, m: 60, h: 3600};
return Math.ceil(Number(found[1]) * (scale[found[2] ?? 's'] ?? 1));
}
function host(url: string): string | null {
try {
return new URL(url).hostname || null;
} catch {
return null;
}
}
// The tag of a scalar entry line, following the engine's first-colon rule: a quoted head followed by a
// colon is an explicit tag, otherwise the text before the first colon unless that colon starts `://`;
// a tagless URL is named after its host.
function scalarTag(code: string): string | null {
const text = code.trim();
// A block squeezed onto one line is left alone: its interval is not read and it is not rewritten.
if (!text || text.includes('{')) return null;
const head = quoted(text);
if (head) {
if (/^\s*:/.test(text.slice(head.end))) return head.value;
return embeddedTag(head.value);
}
return embeddedTag(text);
}
function embeddedTag(text: string): string | null {
const colon = text.indexOf(':');
if (colon === -1) return null;
if (text.startsWith('://', colon)) return host(text);
return text.slice(0, colon).trim();
}
function keyOf(line: string): {key: string; value: string} | null {
const found = /^\s*(?:'([^']*)'|"([^"]*)"|([^:\s]+))\s*:\s*(.*)$/.exec(uncomment(line));
return found ? {key: found[1] ?? found[2] ?? found[3], value: found[4].trim()} : null;
}
const unquote = (text: string) => quoted(text)?.value ?? text;
export function readSubscriptions(text: string): SubscriptionEntry[] {
const lines = text.split('\n');
const block = topLevelBlock(lines, 'subscription');
if (!block) return [];
const entries: SubscriptionEntry[] = [];
for (let i = block.open + 1; i < block.close; i++) {
const code = uncomment(lines[i]);
const header = /^\s*(?:'([^']*)'|"([^"]*)"|([^:\s]+))\s*:\s*\{\s*$/.exec(code);
if (header) {
const tag = header[1] ?? header[2] ?? header[3];
let depth = 1;
let interval = DEFAULT_INTERVAL;
let url: string | null = null;
let j = i + 1;
for (; j < block.close && depth > 0; j++) {
const inner = uncomment(lines[j]);
depth += (inner.match(/\{/g) ?? []).length - (inner.match(/\}/g) ?? []).length;
const field = keyOf(inner);
if (field?.key === 'interval') interval = parseInterval(unquote(field.value)) ?? 0;
if (field?.key === 'url') url = unquote(field.value);
}
entries.push({tag, host: url ? host(url) : null, interval, from: i, to: j - 1});
i = j - 1;
continue;
}
const tag = scalarTag(code);
if (tag) entries.push({tag, host: host(scalarParts(code)?.url ?? ''), interval: DEFAULT_INTERVAL, from: i, to: i});
}
return entries;
}
// The pieces of a scalar entry that survive the move to block form: the URL and an optional `(UA)` suffix.
function scalarParts(code: string): {url: string; ua: string | null} | null {
let text = code.trim();
const head = quoted(text);
if (head && /^\s*:/.test(text.slice(head.end))) text = text.slice(head.end).replace(/^\s*:\s*/, '');
else if (!head) {
const colon = text.indexOf(':');
if (colon !== -1 && !text.startsWith('://', colon)) text = text.slice(colon + 1).trim();
}
const value = quoted(text);
if (!value) return {url: text, ua: null};
const suffix = text.slice(value.end).trim();
const ua = /^\((.*)\)$/.exec(suffix);
const url = value.value.replace(/^(?!https?:\/\/)[^:]*:/, '');
return {url, ua: ua ? unquote(ua[1]) : null};
}
const quoteTag = (tag: string) => (/^[\w.-]+$/.test(tag) ? tag : `'${tag}'`);
const quoteValue = (value: string) => `'${value.replace(/'/g, '')}'`;
// The text with `tag`'s entry set to refresh every `seconds` (0 for manual only). A scalar entry becomes a
// block; a block entry keeps its other fields and gets its interval line replaced, added or, at the default,
// removed. Unchanged text when the tag is not there or already reads that interval.
export function writeInterval(text: string, tag: string, seconds: number): string {
const entry = readSubscriptions(text).find(e => e.tag === tag);
if (!entry || entry.interval === seconds) return text;
const lines = text.split('\n');
const indent = lines[entry.from].match(/^\s*/)?.[0] ?? ' ';
const inner = indent + (indent.includes('\t') ? '\t' : ' ');
const intervalLine = `${inner}interval: '${seconds}s'`;
if (entry.from === entry.to) {
const parts = scalarParts(uncomment(lines[entry.from]));
if (!parts) return text;
const body = [`${indent}${quoteTag(tag)}: {`, `${inner}url: ${quoteValue(parts.url)}`];
if (parts.ua !== null) body.push(`${inner}ua: ${quoteValue(parts.ua)}`);
body.push(intervalLine, `${indent}}`);
lines.splice(entry.from, 1, ...body);
return lines.join('\n');
}
const at = lines.findIndex((line, i) => i > entry.from && i < entry.to && keyOf(line)?.key === 'interval');
if (at !== -1) lines.splice(at, 1, ...(seconds === DEFAULT_INTERVAL ? [] : [intervalLine]));
else if (seconds !== DEFAULT_INTERVAL) lines.splice(entry.to, 0, intervalLine);
return lines.join('\n');
}
+1 -1
View File
@@ -243,7 +243,7 @@ export function Overview() {
{t('ov.resources')}
</h3>
{capabilities.data ? (
<div className="rp-list">
<div className="rp-list rp-list-columns">
{resourceRows(capabilities.data).map(([key, available]) => (
<div key={key} className="rp-row">
<span>{t(resourceLabels[key])}</span>
-30
View File
@@ -1,30 +0,0 @@
import type {ReactNode} from 'react';
// Built-in outbounds get a mark, so a chain reads the same whether it ends in a node or not: an arrow straight
// through for direct, a barred circle for block, a dashed ring for unknown, a diamond for a node.
export type MarkKind = 'direct' | 'block' | 'unknown' | 'node';
const stroke = {fill: 'none', stroke: 'currentColor', strokeWidth: 1.5, strokeLinecap: 'round', strokeLinejoin: 'round'} as const;
const glyphs: Record<MarkKind, ReactNode> = {
// straight through
direct: <path d="M3 6h10M10 3l3 3-3 3" {...stroke} />,
// barred circle
block: <path d="M8 2.4a3.6 3.6 0 1 0 0 7.2a3.6 3.6 0 1 0 0-7.2M5.5 3.5l5 5" {...stroke} />,
// dashed ring
unknown: <circle cx="8" cy="6" r="3.6" {...stroke} strokeDasharray="2 1.6" />,
// one node
node: <path d="M8 1.8L12.2 6 8 10.2 3.8 6z" fill="currentColor" />
};
function Mark({kind, className}: {kind: MarkKind; className?: string}) {
return (
<span className={(className ?? 'flag') + ' mark'} data-kind={kind} role="img" aria-hidden="true">
<svg viewBox="0 0 16 12" width="16" height="12">
{glyphs[kind]}
</svg>
</span>
);
}
export function OutboundMark({name, className}: {name: string | null; className?: string}) {
if (name === 'direct' || name === 'block' || name === null || name === 'unknown')
return <Mark kind={name === 'direct' ? 'direct' : name === 'block' ? 'block' : 'unknown'} className={className} />;
return <Mark kind="node" className={className} />;
}
+13 -5
View File
@@ -6,6 +6,7 @@ import {
GridLayout,
GridList,
GridListItem,
ListLayout,
Menu,
MenuItem,
MenuSection,
@@ -20,14 +21,13 @@ import {
import ChevronDown from '../../ui/icons/ChevronDown';
import {regionOf} from './geo';
import {millis} from '../../api/u64';
import {OutboundMark} from './Mark';
import {Button, Check, InlineSelect, MenuButton, NodeTile, Switch, TextField, latencyTone, type NodeTileProps} from '../../ui/ui';
import type {Group, HealthObservation} from '../../api/model';
import {useT} from '../../i18n';
// `alive` false is an observed failure; `alive` undefined with no `tcp` is a node nothing has measured yet.
export type NodeInfo = {name: string; tcp?: number; alive?: boolean};
export type MemberInfo = Group['members'][number] & {health?: HealthObservation; leaf?: string};
export type MemberInfo = Group['members'][number] & {health?: HealthObservation};
const BIG = 12;
// Region facets for a node list, ordered by count.
@@ -93,7 +93,7 @@ export function NodeGrid({
</div>
);
}
const down = nodes.filter(n => n.health?.state === 'unavailable').length;
const down = shown.filter(n => n.health?.state === 'unavailable').length;
return (
<div className="rp-form">
<div className="rp-toolbar">
@@ -154,7 +154,6 @@ function MemberTile({n, ...props}: {n: MemberInfo} & Pick<NodeTileProps, 'select
<NodeTile
{...props}
name={n.name}
icon={n.kind === 'group' ? <OutboundMark name={n.leaf ?? null} /> : undefined}
nested={n.kind === 'group'}
tcp={health?.state === 'healthy' ? (health.latency_ms ?? undefined) : undefined}
unavailable={health?.state === 'unavailable'}
@@ -192,7 +191,7 @@ export function NodeMenu({nodes, value, onChange, label}: {nodes: NodeInfo[]; va
)}
</MenuItem>
);
const menu = (
const list = (
<Menu
className="rp-menu-scroll"
aria-label={label}
@@ -219,6 +218,15 @@ export function NodeMenu({nodes, value, onChange, label}: {nodes: NodeInfo[]; va
: nodes.map(item)}
</Menu>
);
// A long list draws only the rows in view: opening it costs the same for eighty nodes as for eight. The
// row heights are the ones the stylesheet gives items and section headers.
const menu = big ? (
<Virtualizer layout={ListLayout} layoutOptions={{rowHeight: 32, headingHeight: 26}}>
{list}
</Virtualizer>
) : (
list
);
return (
<MenuTrigger>
<Button appearance="select" label={label}>
+10 -9
View File
@@ -1,8 +1,8 @@
import {useT} from '../../i18n';
import {useCallback, useEffect, useMemo, useState} from 'react';
import Refresh from '../../ui/icons/Refresh';
import {useGroupControl, useGroups, useNodes} from '../../api/store';
import {groupConfigFields, groupLeaf, policyKindLabels, preferredHealth, probeSummary} from '../../api/selectors';
import {useGroupControl, useGroups, useNodes, useCapabilities} from '../../api/store';
import {groupConfigFields, policyKindLabels, preferredHealth, preferredObservation, probeSummary} from '../../api/selectors';
import type {HealthObservation} from '../../api/model';
import {Badge, Button, Disclosure, DisclosureGroup, ErrorMessage, Light, Loading, Kv, Segmented, Switch, errorText, toast} from '../../ui/ui';
import {NodeGrid} from './Nodes';
@@ -11,14 +11,12 @@ import type {PageProps} from '../types';
function PolicyCard({
id,
health,
leaves,
refreshGroups,
refreshNodes,
onLoaded
}: {
id: string;
health: Map<string, HealthObservation | undefined>;
leaves: Map<string, string | undefined>;
refreshGroups: () => void;
refreshNodes: () => void;
onLoaded: (id: string) => void;
@@ -35,7 +33,11 @@ function PolicyCard({
useEffect(() => {
if (settled) onLoaded(id);
}, [settled, id, onLoaded]);
const members = useMemo(() => g?.members.map(m => ({...m, health: health.get(m.id), leaf: leaves.get(m.id)})) ?? [], [g, health, leaves]);
// The group reports its members' health itself, nested groups included; the node list fills in when it does not.
const members = useMemo(
() => g?.members.map(m => ({...m, health: preferredObservation(g.runtime.health.filter(h => h.member_id === m.id)) ?? health.get(m.id)})) ?? [],
[g, health]
);
// Toasts name the member; the backend answers with its id.
const memberName = (id: string) => members.find(m => m.id === id)?.name ?? id;
const tcp = g?.runtime.selection.tcp?.member_id;
@@ -193,8 +195,9 @@ function PolicyCard({
}
export function Policies({query}: PageProps) {
const t = useT();
const resources = useCapabilities().data?.resources;
const groups = useGroups();
const nodes = useNodes();
const nodes = useNodes(resources?.nodes.available === true);
// `?group=` (from search) brings that card into view once every card has its full height, so the cards above
// it no longer grow after the scroll.
const focus = new URLSearchParams(query).get('group');
@@ -205,8 +208,6 @@ export function Policies({query}: PageProps) {
if (focus && ready) document.getElementById('group-' + focus)?.scrollIntoView({block: 'start'});
}, [focus, ready]);
const health = useMemo(() => new Map((nodes.data ?? []).map(n => [n.id, preferredHealth(n)])), [nodes.data]);
// Every group's current exit node, so headers and nested member tiles carry the flag the traffic actually leaves under.
const leaves = useMemo(() => new Map((groups.data ?? []).map(g => [g.id, groupLeaf(g.id, groups.data ?? [], nodes.data ?? [])])), [groups.data, nodes.data]);
return (
<div className="rp-page">
<p className="rp-note">{t('policy.note')}</p>
@@ -215,7 +216,7 @@ export function Policies({query}: PageProps) {
{groups.data?.length === 0 && <p className="rp-empty">{t('policy.empty')}</p>}
<DisclosureGroup>
{groups.data?.map(g => (
<PolicyCard key={g.id} id={g.id} health={health} leaves={leaves} refreshGroups={groups.refetch} refreshNodes={nodes.refetch} onLoaded={onLoaded} />
<PolicyCard key={g.id} id={g.id} health={health} refreshGroups={groups.refetch} refreshNodes={nodes.refetch} onLoaded={onLoaded} />
))}
</DisclosureGroup>
</div>
+25 -16
View File
@@ -46,12 +46,12 @@ const sourceFor = (list: ConfigSource[], file: string | undefined) =>
// how many retained flows it decided; a rule can be added before another or at the end, or removed, by
// rewriting that line of the source through the same validate-then-save path the editor uses. Without the
// dictionary, the retained flows are grouped by the rule that decided them.
export function RuleList({go}: Pick<PageProps, 'go'>) {
export function RuleList({go, query}: PageProps) {
const resources = useCapabilities().data?.resources;
return resources?.rules.available === true ? <Dictionary go={go} /> : <Distribution />;
return resources?.rules.available === true ? <Dictionary go={go} query={query} /> : <Distribution />;
}
function Dictionary({go}: Pick<PageProps, 'go'>) {
function Dictionary({go, query}: PageProps) {
const t = useT();
const locale = LOCALE[useLang()];
const resources = useCapabilities().data?.resources;
@@ -72,14 +72,31 @@ function Dictionary({go}: Pick<PageProps, 'go'>) {
const [dialog, setDialog] = useState<{kind: 'add'} | {kind: 'remove'; rule: RoutingRule} | null>(null);
const [form, setForm] = useState({condition: '', outbound: '', must: false, before: 'end'});
const list = rules.data?.rules ?? [];
// `?rule=` (from search) lands on that row: selected, and scrolled into view once the list is there.
const landed = new URLSearchParams(query).get('rule');
// The row picked by hand replaces the landed one; a new landing wins again.
const [picked, setPicked] = useState<{landed: string | null; row: string | null}>({landed, row: landed});
const selected = picked.landed === landed ? picked.row : landed;
const setSelected = (row: string | null) => setPicked({landed, row});
useEffect(() => {
if (landed && rules.data) document.querySelector(`[role="row"][data-key="${CSS.escape(landed)}"]`)?.scrollIntoView({block: 'nearest'});
}, [landed, rules.data]);
const configSources = config.data?.sources ?? [];
const writable = (rule: RoutingRule) => {
const source = sourceFor(configSources, rule.source?.file);
return !!source && source.writable && source.content !== undefined;
};
// Where a new rule can go: before the fallback when its line is known and writable, else before a writable rule.
const fallback = list.find(rule => rule.kind === 'fallback');
const positions = [
...(fallback && writable(fallback) ? [{id: 'end', label: t('rule.positionEnd')}] : []),
...list
.filter(rule => rule.kind === 'rule' && writable(rule))
.map(rule => ({id: rule.rule_id, label: t('rule.positionBefore', {n: String(rule.index + 1)}), desc: rule.expression}))
];
const outbounds = [...(groups.data ?? []).map(g => g.name), 'direct', 'block'];
const open = (next: NonNullable<typeof dialog>) => {
setForm({condition: '', outbound: (groups.data?.[0]?.name ?? 'direct') as string, must: false, before: 'end'});
setForm({condition: '', outbound: (groups.data?.[0]?.name ?? 'direct') as string, must: false, before: positions[0]?.id ?? 'end'});
setDialog(next);
};
// Writes one changed source: validated in full when the backend can, then saved against its accepted digest.
@@ -132,7 +149,7 @@ function Dictionary({go}: Pick<PageProps, 'go'>) {
)}
<span className="rp-grow" />
{canWrite && (
<Button small isDisabled={!list.length || !!editor.busy} onPress={() => open({kind: 'add'})}>
<Button small isDisabled={!positions.length || !!editor.busy} onPress={() => open({kind: 'add'})}>
{t('rule.add')}
</Button>
)}
@@ -142,6 +159,8 @@ function Dictionary({go}: Pick<PageProps, 'go'>) {
label={t('rule.listTitle')}
loading={rules.loading && !rules.data}
rows={list.map(rule => ({...rule, id: rule.rule_id}))}
selected={selected}
onSelect={setSelected}
height={560}
empty={t('rule.distributionEmpty')}
cols={[
@@ -225,17 +244,7 @@ function Dictionary({go}: Pick<PageProps, 'go'>) {
must
</Switch>
</div>
<LabeledSelect
label={t('rule.position')}
value={form.before}
onChange={before => setForm({...form, before})}
items={[
{id: 'end', label: t('rule.positionEnd')},
...list
.filter(rule => rule.kind === 'rule' && writable(rule))
.map(rule => ({id: rule.rule_id, label: t('rule.positionBefore', {n: String(rule.index + 1)}), desc: rule.expression}))
]}
/>
<LabeledSelect label={t('rule.position')} value={form.before} onChange={before => setForm({...form, before})} items={positions} />
</div>
)}
</ModalDialog>
+1 -1
View File
@@ -26,7 +26,7 @@ export function Rules({go, query}: PageProps) {
const rules = resources?.rules.available === true;
const tabs = [
...(flows ? [{id: 'map', label: t('rule.map'), content: <RoutingMap go={go} query={query} />}] : []),
...(flows || rules ? [{id: 'list', label: t('rule.listTitle'), content: <RuleList go={go} />}] : []),
...(flows || rules ? [{id: 'list', label: t('rule.listTitle'), content: <RuleList go={go} query={query} />}] : []),
...(flows ? [{id: 'flows', label: t('rule.flows'), content: <FlowRecords go={go} query={query} />}] : []),
...(resources?.routing_trace.available !== false ? [{id: 'trace', label: t('rule.trace'), content: <Trace />}] : [])
];
+1
View File
@@ -131,6 +131,7 @@ export function Settings({query}: PageProps) {
const save = (id?: string) => {
const profiles = editedProfiles();
if (profiles) persist(profiles, id ?? active?.id ?? profiles[0].id);
else toast('negative', t('settings.invalidUrl'));
};
const confirmProfile = () => {
if (dialog === 'delete') {
+10 -2
View File
@@ -31,7 +31,7 @@ import {
import Color from '../ui/icons/Color';
import type {PageProps} from '../features/types';
import {useRoute} from './route';
import {refetchAll, useCapabilities, useConfig, useConnections, useGroups, useNodes, useProviders, useVersion} from '../api/store';
import {refetchAll, useCapabilities, useConfig, useConnections, useGroups, useNodes, useProviders, useRules, useVersion} from '../api/store';
import {chainLabel, connectionRows} from '../api/selectors';
import {features, navAvailable, subpages, warmPage} from './registry';
import {SettingsContext} from '../features/settings/Settings';
@@ -143,11 +143,12 @@ function SearchDialog({onClose, go}: {onClose: () => void; go: PageProps['go']})
const [q, setQ] = useState('');
const capabilities = useCapabilities();
const resources = capabilities.data?.resources;
const connections = useConnections();
const connections = useConnections(undefined, resources?.connections.available === true);
const nodes = useNodes(resources?.nodes.available === true);
const groups = useGroups(resources?.groups.available === true);
const providers = useProviders(resources?.providers.available === true);
const config = useConfig(resources?.config.available === true);
const rules = useRules(resources?.rules.available === true);
const needle = q.trim().toLowerCase();
const limit = needle ? 8 : 5;
const match = (...values: Array<string | null | undefined>) => values.some(value => value?.toLowerCase().includes(needle));
@@ -174,6 +175,7 @@ function SearchDialog({onClose, go}: {onClose: () => void; go: PageProps['go']})
groups: (groups.data ?? []).filter(g => match(g.name)).slice(0, limit),
providers: (providers.data?.providers ?? []).filter(p => match(p.name)).slice(0, limit),
sources: (config.data?.sources ?? []).filter(source => match(source.path)).slice(0, limit),
rules: (rules.data?.rules ?? []).filter(rule => rule.kind === 'rule' && match(rule.expression, rule.outbound)).slice(0, limit),
pages: places.filter(place => match(place.title, place.parent && place.parent + ' ' + place.title)).slice(0, limit)
};
const error = connections.error ?? nodes.error ?? groups.error ?? capabilities.error;
@@ -188,6 +190,7 @@ function SearchDialog({onClose, go}: {onClose: () => void; go: PageProps['go']})
} else if (kind === 'group') go('policies', 'group=' + encodeURIComponent(id));
else if (kind === 'provider') go('nodes', 'provider=' + encodeURIComponent(id));
else if (kind === 'source') go('config', 'tab=source&source=' + encodeURIComponent(id));
else if (kind === 'rule') go('rules', 'tab=list&rule=' + encodeURIComponent(id));
else {
const [path, query] = id.split('?');
go(path, query);
@@ -255,6 +258,11 @@ function SearchDialog({onClose, go}: {onClose: () => void; go: PageProps['go']})
t('search.sources'),
hits.sources.map(source => ({key: 'source:' + source.id, label: source.path, desc: source.kind}))
)}
{section(
'rules',
t('nav.rules'),
hits.rules.map(rule => ({key: 'rule:' + rule.rule_id, label: rule.expression, desc: `#${rule.index + 1} → ${rule.outbound}`}))
)}
</ListBox>
</ModalDialog>
);
+2 -2
View File
@@ -77,7 +77,7 @@ export const features: Feature[] = [
path: 'dns',
nav: {group: 'grp.network', titleKey: 'nav.dns', hintKey: 'hint.dns', Icon: GlobeGrid},
Page: Dns,
requires: {resources: ['dns_query', 'dns_cache']}
requires: {resources: ['dns_query', 'dns_log', 'dns_cache']}
},
{
id: 'policies',
@@ -101,7 +101,7 @@ export const features: Feature[] = [
shortcut: 'n',
nav: {group: 'grp.proxy', titleKey: 'nav.nodes', hintKey: 'hint.nodes', Icon: Data},
Page: NodesPage,
requires: {resources: ['providers']}
requires: {resources: ['nodes', 'providers']}
},
{
id: 'config',
+59 -35
View File
@@ -1,7 +1,17 @@
// Recharts drawn with the Rosé Pine variables (read from the document so they follow the theme switch).
import {lazy, Suspense, useId, useMemo, useSyncExternalStore} from 'react';
import {lazy, Suspense, useId, useMemo, useState, useSyncExternalStore} from 'react';
import type {ComponentProps} from 'react';
import {formatNumber, useT, type Translator} from '../i18n';
// Charts re-lay out once a resize settles rather than on every event; a drag then costs one render per
// chart instead of dozens.
const RESIZE_DEBOUNCE = 120;
// The tooltip is shown only while the pointer is inside the chart's own box. Recharts hides it on its own
// mouseleave, but a pointer that jumps out (a fast flick, a touchpad gesture, a re-render while it left)
// can leave the last reading standing; the wrapper's pointer state settles it.
function useHover() {
const [inside, setInside] = useState(false);
return {inside, handlers: {onPointerEnter: () => setInside(true), onPointerLeave: () => setInside(false)}};
}
export type Series = {label: string; color: string; values: Array<number | null>};
const VARS = [
@@ -100,13 +110,17 @@ const LazyAreaChart = lazy(() =>
locale,
height = 150,
baseline = 'zero',
window
window,
fill
}: {
series: Series[];
timestamps: number[];
fmt: (v: number) => string;
locale: string;
height?: number;
// Grow with the card: `height` is then the floor, and a card stretched by its row neighbours fills
// the extra with chart rather than blank.
fill?: boolean;
// A fixed span for the x axis: the chart is read against the window, so a young session sits at the
// right edge instead of being stretched across the width. Without it the axis fits the data.
window?: {since: number; until: number};
@@ -115,6 +129,7 @@ const LazyAreaChart = lazy(() =>
}) {
const p = usePalette();
const uid = useId();
const hover = useHover();
const span = window ? window.until - window.since : timestamps.length ? timestamps[timestamps.length - 1] - timestamps[0] : 0;
const marks = window ? clockTicks(window.since, window.until) : undefined;
const withSeconds = marks ? marks.step < 60000 : span < 3 * 60 * 1000;
@@ -155,8 +170,8 @@ const LazyAreaChart = lazy(() =>
: [...new Set((withSeconds ? [0, Math.round(last / 2), last] : [0, Math.round(last / 3), Math.round((2 * last) / 3), last]).map(i => timestamps[i]))];
const domain: [number | string, number | string] = window ? [window.since, window.until] : ['dataMin', 'dataMax'];
return (
<div style={{height, width: '100%'}}>
<ResponsiveContainer width="100%" height="100%">
<div style={{height, width: '100%', flex: fill ? '1 1 auto' : undefined}} {...hover.handlers}>
<ResponsiveContainer width="100%" height="100%" debounce={RESIZE_DEBOUNCE}>
<RAreaChart data={data} margin={{top: 8, right: 0, bottom: 0, left: 20}}>
<defs>
{series.map((s, k) => (
@@ -191,6 +206,7 @@ const LazyAreaChart = lazy(() =>
width={64}
/>
<Tooltip
active={hover.inside ? undefined : false}
contentStyle={tip(p)}
itemStyle={{color: p['on-text']}}
labelFormatter={value => date.format(Number(value))}
@@ -220,7 +236,9 @@ const LazyAreaChart = lazy(() =>
export function AreaChart(props: ComponentProps<typeof LazyAreaChart>) {
return (
<Suspense fallback={<div style={{height: props.height ?? 150, width: '100%'}} />}>
<Suspense
fallback={<div style={props.fill ? {minHeight: props.height ?? 150, flex: '1 1 auto', width: '100%'} : {height: props.height ?? 150, width: '100%'}} />}
>
<LazyAreaChart {...props} />
</Suspense>
);
@@ -249,7 +267,7 @@ const LazySpark = lazy(() =>
hi = Math.max(Math.max(...known) * 1.05 || 1, floor);
return (
<div style={{height, width: '100%'}}>
<ResponsiveContainer width="100%" height="100%">
<ResponsiveContainer width="100%" height="100%" debounce={RESIZE_DEBOUNCE}>
<RAreaChart data={data} margin={{top: 2, right: 0, bottom: 2, left: 0}}>
<defs>
<linearGradient id={uid} x1="0" y1="0" x2="0" y2="1">
@@ -275,6 +293,8 @@ export function Spark(props: ComponentProps<typeof LazySpark>) {
</Suspense>
);
}
// The legend scrolls past six rows, so a deployment with dozens of outbounds never stretches the card the
// chart shares its row with; callers sort by size, so the rows in view are the ones that matter.
export function Donut({rows, total}: {rows: Array<{name: string; value: number | null; text: string; color: string}>; total: string}) {
const t = useT();
return (
@@ -304,37 +324,41 @@ const LazyDonut = lazy(() =>
default: function DonutPlot({rows}: Pick<ComponentProps<typeof Donut>, 'rows'>) {
const t = useT();
const p = usePalette();
const hover = useHover();
const data = rows.filter(r => r.value !== null && r.value > 0);
return (
<ResponsiveContainer width="100%" height="100%">
<PieChart margin={{top: 0, right: 0, bottom: 0, left: 0}}>
<Pie
data={data}
dataKey="value"
nameKey="name"
innerRadius={44}
outerRadius={56}
minAngle={6}
stroke="none"
startAngle={90}
endAngle={-270}
isAnimationActive={false}
>
{data.map(r => (
<Cell key={r.name} fill={r.color} />
))}
</Pie>
<Tooltip
contentStyle={tip(p)}
itemStyle={{color: p['on-text']}}
formatter={(v, name, item) => {
const payload: unknown = item.payload;
const bytes = payload && typeof payload === 'object' && 'text' in payload && typeof payload.text === 'string' ? payload.text : '';
return [t('ui.share', {bytes, percent: String(v)}), String(name)];
}}
/>
</PieChart>
</ResponsiveContainer>
<div style={{height: '100%', width: '100%'}} {...hover.handlers}>
<ResponsiveContainer width="100%" height="100%" debounce={RESIZE_DEBOUNCE}>
<PieChart margin={{top: 0, right: 0, bottom: 0, left: 0}}>
<Pie
data={data}
dataKey="value"
nameKey="name"
innerRadius={44}
outerRadius={56}
minAngle={6}
stroke="none"
startAngle={90}
endAngle={-270}
isAnimationActive={false}
>
{data.map(r => (
<Cell key={r.name} fill={r.color} />
))}
</Pie>
<Tooltip
active={hover.inside ? undefined : false}
contentStyle={tip(p)}
itemStyle={{color: p['on-text']}}
formatter={(v, name, item) => {
const payload: unknown = item.payload;
const bytes = payload && typeof payload === 'object' && 'text' in payload && typeof payload.text === 'string' ? payload.text : '';
return [t('ui.share', {bytes, percent: String(v)}), String(name)];
}}
/>
</PieChart>
</ResponsiveContainer>
</div>
);
}
}))
+3
View File
@@ -33,6 +33,7 @@ export const messages = defineMessages({
'cm.selectionDeleted': '已刪除選取範圍',
close: '關閉',
'toast.collapse': '收合',
'ui.openRule': '在規則列表中查看 {rule}',
'toast.clearAll': '全部清除',
clear: '清除',
'ui.all': '全部',
@@ -130,6 +131,7 @@ export const messages = defineMessages({
'cm.selectionDeleted': '已删除选区',
close: '关闭',
'toast.collapse': '折叠',
'ui.openRule': '在规则列表中查看 {rule}',
'toast.clearAll': '全部清除',
clear: '清除',
'ui.all': '全部',
@@ -227,6 +229,7 @@ export const messages = defineMessages({
'cm.selectionDeleted': 'Selection deleted',
close: 'Close',
'toast.collapse': 'Collapse',
'ui.openRule': 'Open {rule} in the rule list',
'toast.clearAll': 'Clear all',
clear: 'Clear',
'ui.all': 'All',
+40 -38
View File
@@ -1215,6 +1215,12 @@ input {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
}
/* A feed inside a card fills the card's height and scrolls past it, so the row's cards stay level. */
.rp-feed {
flex: 1 1 auto;
min-height: 0;
overflow-y: auto;
}
.rp-quick {
display: grid;
grid-template-columns: 1fr;
@@ -1412,6 +1418,7 @@ input {
.rp-seg .rp-btn[data-hovered] {
color: var(--rp-text);
transition-delay: 0ms;
}
/* Chips: a wrapping row of small toggles; the chosen one takes the selection tint. */
.rp-chips {
@@ -1536,41 +1543,6 @@ input {
.rp-il .ic {
margin-right: 0;
}
.flag {
display: inline-flex;
width: 16px;
height: 12px;
border-radius: 2px;
overflow: hidden;
box-shadow: 0 0 0 0.5px rgba(0, 0, 0, 0.18);
flex: none;
vertical-align: -1px;
}
.flag > svg {
width: 100%;
height: 100%;
display: block;
}
.flag.mark {
color: var(--rp-on-accent);
background: var(--rp-muted);
}
.flag.mark[data-kind='direct'] {
background: var(--rp-foam);
}
.flag.mark[data-kind='block'] {
background: var(--rp-love);
}
.flag.mark[data-kind='node'] {
background: var(--rp-pine);
}
/* Marks sit on the text baseline of the chain, chip or light they lead. */
.rp-chain > .flag,
.rp-chips .flag,
.rp-light > .flag {
translate: 0 0.5px;
}
.rp-light {
display: inline-flex;
align-items: center;
@@ -1651,6 +1623,15 @@ input {
flex-direction: column;
gap: 8px;
}
/* A long list of short rows folds into as many columns as the card holds, and spreads its rows over the card's
height, so it sits level with its neighbours either way. */
.rp-list-columns {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(128px, 1fr));
column-gap: 16px;
align-content: space-between;
flex: 1 1 auto;
}
.rp-legend {
display: flex;
@@ -1706,6 +1687,9 @@ input {
display: flex;
flex-direction: column;
gap: 4px;
/* Six rows; a longer legend scrolls rather than growing the card. */
max-height: 164px;
overflow-y: auto;
}
.rp-donut .r {
display: flex;
@@ -1791,6 +1775,15 @@ input {
height: 40px;
border-radius: 10px;
}
/* The field's own glyphs match button icons: 16px in the 32px field, 20px in the large header search. */
.rp-input .rp-icon {
width: 16px;
height: 16px;
}
.rp-input.lg > .rp-icon {
width: 20px;
height: 20px;
}
.rp-input .clear {
display: inline-flex;
align-items: center;
@@ -2362,6 +2355,8 @@ button.rp-node[data-focus-visible] {
border: 2px solid transparent;
position: relative;
z-index: 1;
/* Like a tab: the label recolours as the slider arrives. */
transition: color 120ms var(--rp-ease) 100ms;
}
/* Popovers, menus, tooltips: fade and drift 4px from the trigger side. */
.rp-popover,
@@ -2667,6 +2662,12 @@ button.rp-node[data-focus-visible] {
gap: 8px;
min-width: 0;
}
.rp-rule-link {
min-height: 24px;
height: 24px;
width: 24px;
flex: none;
}
.rp-rule > span {
overflow: hidden;
text-overflow: ellipsis;
@@ -2717,13 +2718,12 @@ button.rp-node[data-focus-visible] {
display: inline-flex;
}
.rp-tip {
/* Tooltips are portaled without a z-index
background: var(--rp-text);
color: var(--rp-on-text);
font-size: 12px;
padding: 4px 8px;
border-radius: 6px;
sticky table headers must not cover them. */
/* Tooltips are portaled without a z-index; sticky table headers must not cover them. */
z-index: 10;
max-width: min(480px, calc(100vw - 24px));
white-space: normal;
@@ -2927,10 +2927,12 @@ button.rp-node[data-focus-visible] {
color: var(--rp-subtle);
cursor: pointer;
outline: none;
transition: color 150ms var(--rp-ease);
/* The label takes the selection colour as the slider arrives, not the moment it leaves the old tab. */
transition: color 120ms var(--rp-ease) 100ms;
}
.rp-tab[data-hovered] {
color: var(--rp-text);
transition-delay: 0ms;
}
.rp-tab[data-selected] {
color: var(--rp-pine);
+56 -7
View File
@@ -53,6 +53,7 @@ import {
} from 'react-aria-components';
import ChevronDown from './icons/ChevronDown';
import Close from './icons/Close';
import ListBulleted from './icons/ListBulleted';
import Checkmark from './icons/Checkmark';
import CheckmarkCircle from './icons/CheckmarkCircle';
import AlertTriangle from './icons/AlertTriangle';
@@ -367,7 +368,8 @@ export function MenuButton({
label,
quiet,
chevron = true,
extra
extra,
isDisabled
}: {
children: ReactNode;
items?: Item[];
@@ -379,10 +381,11 @@ export function MenuButton({
quiet?: boolean;
chevron?: boolean;
extra?: {title: string; items: Item[]} & Picked;
isDisabled?: boolean;
}) {
return (
<MenuTrigger>
<RButton className={cx('rp-btn', quiet && 'quiet', !chevron && 'icon')} aria-label={label}>
<RButton className={cx('rp-btn', quiet && 'quiet', !chevron && 'icon')} aria-label={label} isDisabled={isDisabled}>
{children}
{chevron && <ChevronDown />}
</RButton>
@@ -576,6 +579,27 @@ export function CardLink({href, label, children}: {href: string; label: string;
</RLink>
);
}
// A routing rule named by a connection or flow: the expression, and a small link to its row in the rule
// list when the backend lists rules and the record carries the id. The link is its own target so a click on
// the row still selects the row.
export function RuleRef({expression, ruleId, linked}: {expression: string | null; ruleId: string | null; linked: boolean}) {
const t = useT();
if (!expression) return <>—</>;
return (
<>
<TextTooltip text={expression}>{expression}</TextTooltip>
{linked && ruleId && (
<RLink
href={'#/rules?tab=list&rule=' + encodeURIComponent(ruleId)}
className="rp-btn quiet icon rp-rule-link"
aria-label={t('ui.openRule', {rule: expression})}
>
<ListBulleted />
</RLink>
)}
</>
);
}
// `row` keeps each label beside its value on one line, for a strip that sits next to other one-line controls.
// A third element is the full value behind a shortened one, shown as a tooltip.
export function Kv({items, inline, row}: {items: Array<[string, string] | [string, string, string]>; inline?: boolean; row?: boolean}) {
@@ -599,7 +623,6 @@ export function Kv({items, inline, row}: {items: Array<[string, string] | [strin
// Virtual collections render the same tile body inside their own selectable item.
export type NodeTileProps = {
name: string;
icon?: ReactNode;
tcp?: number;
alive?: boolean;
unavailable?: boolean;
@@ -614,7 +637,6 @@ export type NodeTileProps = {
export const latencyTone = (ms: number) => (ms < 100 ? 'ok' : ms < 180 ? 'warn' : 'err');
export function NodeTile({
name,
icon,
tcp,
alive = true,
unavailable = !alive || tcp == null,
@@ -631,7 +653,6 @@ export function NodeTile({
<>
<span className="top">
<span className="n">
{icon && <span className="ic">{icon}</span>}
<TextTooltip>{name}</TextTooltip>
</span>
{nested ? (
@@ -690,6 +711,26 @@ export function useContentWidth<E extends HTMLElement>() {
}, []);
return [ref, width] as const;
}
// The height that takes an element to the bottom of the viewport, never below `min`: a page whose table is
// its last content shows as many rows as the screen holds instead of a fixed box over empty page.
export function useFillHeight<E extends HTMLElement>(min: number, gap = 24) {
const ref = useRef<E>(null);
const [height, setHeight] = useState(min);
useLayoutEffect(() => {
const el = ref.current;
if (!el) return;
const measure = () => setHeight(Math.max(min, Math.floor(window.innerHeight - el.getBoundingClientRect().top - gap)));
measure();
const observer = new ResizeObserver(measure);
observer.observe(document.body);
window.addEventListener('resize', measure);
return () => {
observer.disconnect();
window.removeEventListener('resize', measure);
};
}, [min, gap]);
return [ref, height] as const;
}
// Long lists are virtualised: only the visible rows are in the DOM, so a rule list of thousands stays light.
// Short ones render whole, which keeps every row reachable to assistive technology and find-in-page. A list
// that once reached the threshold stays virtualised for the life of the table, so a growing feed or a filter
@@ -1038,7 +1079,7 @@ export function Chips({
onChange
}: {
label: string;
items: Array<{id: string; label: string; count?: string; countLabel?: string; icon?: ReactNode}>;
items: Array<{id: string; label: string; count?: string; countLabel?: string}>;
value: string | null;
onChange: (id: string | null) => void;
}) {
@@ -1055,7 +1096,6 @@ export function Chips({
>
{items.map(item => (
<ToggleButton key={item.id} id={item.id} className="rp-btn sm">
{item.icon}
<span className="rp-truncate">{item.label}</span>
{item.count !== undefined && (
<span className="n" title={item.countLabel}>
@@ -1088,6 +1128,15 @@ export function csvLine(values: Array<string | number | null | undefined>): stri
return values.map(value => (value == null ? '' : /[",\n]/.test(String(value)) ? '"' + String(value).replace(/"/g, '""') + '"' : String(value))).join(',');
}
// The value as it stood once `ms` passed without a change; a text filter that costs a request waits on it.
export function useDebounced<T>(value: T, ms: number): T {
const [settled, setSettled] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setSettled(value), ms);
return () => clearTimeout(timer);
}, [value, ms]);
return settled;
}
export function useMediaQuery(query: string) {
const [matches, setMatches] = useState(() => typeof matchMedia === 'function' && matchMedia(query).matches);
useEffect(() => {