diff --git a/.prettierignore b/.prettierignore index aeaf51cd..2fb931a0 100644 --- a/.prettierignore +++ b/.prettierignore @@ -7,3 +7,4 @@ node_modules pnpm-lock.yaml *.html src/fonts-sc.css +src/fonts-tc.css diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7fcb120a..7d5d0b7e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -32,6 +32,21 @@ Create one folder for each feature under `src/features`. Keep a feature's pages, Use formal Traditional Chinese in `zh-TW`, idiomatic Simplified Chinese in `zh-CN`, and plain English in English messages. +## UI components + +React Spectrum S2 is the design reference: behaviour, spacing, states and wording follow it. Components are built on `react-aria-components` with doona's own CSS in `src/ui`; a new component starts from the S2 design and only then from React Aria. + +doona does not depend on `@react-spectrum/s2`. Version 1.7.1 unpacks to about 54 MB against about 6.6 MB for `react-aria-components`, and its styles come from `@parcel/macros`, a build-time macro that needs a bundler plugin. doona is served by routers and keeps gzip budgets of 275 KB for the startup shell and 655 KB for all JavaScript. + +What this leaves out, on purpose: + +- No S2 package, style macro or S2 theme tokens. Colours come from the official palettes in `src/ui/styles/palettes.css`. +- No S2 icon package. The icons doona uses are copied one at a time from Adobe Spectrum under Apache-2.0 (see NOTICE). +- No automatic S2 updates. When S2 changes a component's behaviour or look, doona follows by hand. +- No second component library beside React Aria. + +Revisit this if S2 stops requiring the macro or the size budgets stop applying. + ## Commit and pull request flow Use commit subjects in this form: diff --git a/contract/api-standardize/SOURCE.md b/contract/api-standardize/SOURCE.md index 22f4c1ec..9580bc60 100644 --- a/contract/api-standardize/SOURCE.md +++ b/contract/api-standardize/SOURCE.md @@ -1,6 +1,6 @@ -Pin: 01a6575 + 952e2e0 (PR #12) + 4cc28f4 (password login) +Pin: 01a6575 + 952e2e0 (PR #12) + 4cc28f4 and 62cfa46 (password login) -openapi.yaml is the generated bundle (`npm run bundle`) of daeuniverse/api-standardize, branch honk, commit 01a6575 plus PR #12 (`952e2e0`, recorder modes and the unredacted administrative surface, open as of 2026-09-22) plus `4cc28f4` on branch `auth-password-login` (password setup, login and logout with auth discovery, matching honk's password mode; not yet proposed upstream as of 2026-09-23). +openapi.yaml is the generated bundle (`npm run bundle`) of daeuniverse/api-standardize, branch honk, commit 01a6575 plus PR #12 (`952e2e0`, recorder modes and the unredacted administrative surface, open as of 2026-09-22) plus `4cc28f4` and `62cfa46` on branch `auth-password-login` (password setup, login and logout with auth discovery, matching honk's password mode; passwords of 8 to 128 characters; not yet proposed upstream as of 2026-09-23). That commit includes, all merged: PR #4 client fixes, #5 config, #6 observability with provider, node and geodata management, #7 connection close, #8 GroupOverrideCleared with the native outbound mode dropped. diff --git a/contract/api-standardize/openapi.yaml b/contract/api-standardize/openapi.yaml index 338cc564..e9839eb3 100644 --- a/contract/api-standardize/openapi.yaml +++ b/contract/api-standardize/openapi.yaml @@ -5932,9 +5932,9 @@ components: pattern: ^[A-Za-z0-9_.-]{1,64}$ password: type: string - minLength: 12 + minLength: 8 maxLength: 128 - description: 12 to 128 Unicode scalar values, at most 512 UTF-8 bytes; not normalised or trimmed. + description: 8 to 128 Unicode scalar values, at most 512 UTF-8 bytes; not normalised or trimmed. AuthSession: type: object required: diff --git a/e2e/a11y.spec.ts b/e2e/a11y.spec.ts index 89dd3a37..62e53dff 100644 --- a/e2e/a11y.spec.ts +++ b/e2e/a11y.spec.ts @@ -22,7 +22,9 @@ for (const [palette, scheme] of looks) await expect(page.locator('html')).toHaveAttribute('data-scheme', scheme); await expect(page.locator('.rp-content')).toBeVisible(); await expect(page.locator(`.rp-nav[href="#/${route}"]`)).toHaveAttribute('aria-current', 'page'); - await expect(page.locator('.rp-content').getByRole('status')).toHaveCount(0); + // A loading notice stays hidden for its first 150ms, and a role query skips hidden elements: select it by CSS so + // a fast machine does not scan the page before its data has arrived. + await expect(page.locator('.rp-content [role=status]')).toHaveCount(0); await page.evaluate(() => document.fonts.ready.then(() => undefined)); const results = await new AxeBuilder({page}).withTags(['wcag2a', 'wcag2aa']).analyze(); const findings = Object.fromEntries( diff --git a/e2e/activity.spec.ts b/e2e/activity.spec.ts index 3687cc7e..b44f4e91 100644 --- a/e2e/activity.spec.ts +++ b/e2e/activity.spec.ts @@ -145,7 +145,7 @@ test('the compact node menu selects by keyboard and returns focus to its trigger test('notices hide housekeeping events while the Events page retains them', async ({page}) => { await page.clock.install(); await page.goto('/#/activity'); - const notices = page.getByRole('region', {name: 'Notifications and issues'}); + const notices = page.getByRole('region', {name: 'Notifications', exact: true}); await expect(notices.getByRole('listitem').filter({hasText: 'Stream ready'})).toHaveCount(1); await page.clock.fastForward(10100); await expect(notices.getByRole('listitem').filter({hasText: /runtime\.updated|flow\.updated/})).toHaveCount(0); @@ -160,7 +160,7 @@ test('notices hide housekeeping events while the Events page retains them', asyn test('housekeeping cannot evict notices while the page is hidden', async ({page}) => { await page.clock.install(); await page.goto('/#/activity'); - const notices = page.getByRole('region', {name: 'Notifications and issues'}); + const notices = page.getByRole('region', {name: 'Notifications', exact: true}); const ready = notices.getByRole('listitem').filter({hasText: 'Stream ready'}); await expect(ready).toHaveCount(1); await page.evaluate(() => { diff --git a/e2e/capabilities.spec.ts b/e2e/capabilities.spec.ts index 58969aae..e2f80efb 100644 --- a/e2e/capabilities.spec.ts +++ b/e2e/capabilities.spec.ts @@ -95,10 +95,24 @@ test('without discovery, the nodes page reads its nodes but not the groups it on await expect(page.locator('.rp-content > .rp-alert')).toContainText('Discovery unavailable'); await nodesRead; await expect(page.getByRole('tab', {name: 'Latency'})).toHaveAttribute('aria-selected', 'true'); - await page.waitForTimeout(300); + // The chart has drawn from the nodes, long after the page asked for everything it reads. + await expect(page.getByRole('tabpanel', {name: 'Latency'}).getByRole('region', {name: 'Node latency'})).toBeVisible(); expect(backend.requests.filter(request => new URL(request.url()).pathname.endsWith('/api/v1/groups'))).toHaveLength(0); }); +test('a failed discovery is reported once, by the shell, on the activity and DNS pages', async ({page}) => { + const backend = await mockBackend(page); + backend.handlers['GET capabilities'] = async () => { + throw new ApiError(500, 'internal_error', 'Discovery failed'); + }; + for (const route of ['activity', 'dns']) { + await page.goto('/#/' + route); + await expect(page.locator('.rp-content > .rp-alert').first()).toContainText('Discovery failed'); + await expect(page.locator('.rp-alert', {hasText: 'Discovery failed'})).toHaveCount(1); + await expect(page.locator('.rp-content [role=status]')).toHaveCount(0); + } +}); + // The first honk-native profile exposes only runtime and userspace-observed connections. test.describe('first-release backend', () => { test.use({storage: {'doona-mock-profile': 'm1'}}); diff --git a/e2e/charts.spec.ts b/e2e/charts.spec.ts index b72d1852..96011a3a 100644 --- a/e2e/charts.spec.ts +++ b/e2e/charts.spec.ts @@ -16,7 +16,7 @@ test('DNS opens on its statistics, with each figure labelled and its sample coun await expect(fact(page, 'Median')).toHaveText(/^\d+ ms$/); await expect(fact(page, 'P95')).toHaveText(/^\d+ ms$/); await expect(fact(page, 'Cache hit rate')).toHaveText(/^\d+%$/); - await expect(page.getByText(/^\d+ loaded records: \d+ uncached, \d+ sent upstream;/)).toBeVisible(); + await expect(page.getByText(/^Loaded: \d+, uncached: \d+, sent upstream: \d+$/)).toBeVisible(); const outcomes = page.getByRole('img', {name: /^Outcomes: /}); for (const label of ['From the cache', 'Answered upstream', 'No such name', 'Failed']) await expect(outcomes).toHaveAccessibleName(new RegExp(label)); await expect(page.getByRole('img', {name: /^Upstream latency \(\d+ lookups\)$/})).toBeVisible(); diff --git a/e2e/chunks.spec.ts b/e2e/chunks.spec.ts index 4be5a25c..86c89fb5 100644 --- a/e2e/chunks.spec.ts +++ b/e2e/chunks.spec.ts @@ -206,8 +206,9 @@ test('Escape while the search dialog loads keeps it from opening late', async ({ await page.keyboard.press('Control+K'); await page.keyboard.press('Escape'); release(); - await loaded; - await page.waitForTimeout(300); + // Once the chunk has run here too, the page has had its chance to open the dialog. + const chunk = (await loaded).url(); + await page.evaluate(url => import(url).then(() => new Promise(requestAnimationFrame)), chunk); await expect(page.getByRole('dialog')).toHaveCount(0); await page.keyboard.press('Control+K'); await expect(page.getByRole('dialog')).toBeVisible(); diff --git a/e2e/config.spec.ts b/e2e/config.spec.ts index 8c9d4cf2..792fd9bd 100644 --- a/e2e/config.spec.ts +++ b/e2e/config.spec.ts @@ -338,7 +338,7 @@ test('modules list top-level counts and edit only routing through reload', async await expect(modules.getByRole('region', {name: 'subscription', exact: true})).toContainText('1 subscription'); await expect(modules.getByRole('region', {name: 'node', exact: true})).toContainText('5 nodes'); await expect(modules.getByRole('region', {name: 'group', exact: true})).toContainText( - '4 groups: proxy: fixed(0), resilient: min_avg10, gaming: min_last_delay, skylink: Fastest on average' + '4 groups: proxy: Manual, resilient: Fastest on average, gaming: Fastest on average, skylink: Fastest on average' ); await expect(modules.getByRole('region', {name: 'dns', exact: true})).toContainText('2 upstreams, 1 request rule, 0 response rules'); const routing = modules.getByRole('region', {name: 'routing', exact: true}); diff --git a/e2e/connections.spec.ts b/e2e/connections.spec.ts index 93d5510e..c889e441 100644 --- a/e2e/connections.spec.ts +++ b/e2e/connections.spec.ts @@ -554,3 +554,18 @@ test('plain connection cells truncate with a tooltip like other tables', async ( await expect(row.nth(index).locator('.rp-truncate')).toHaveCount(1); } }); + +test.describe('with motion', () => { + test.use({reducedMotion: 'no-preference'}); + test('a kept tab brings its open detail back without the entrance', async ({page}) => { + await page.goto('/#/connections?tab=list'); + await page.locator('.rp-table [data-key="c-0002"]').click(); + await expect(page.locator('.rp-panel .rp-h3')).toHaveText('cdn.bilibili.com'); + await page.getByRole('tab', {name: 'Traffic', exact: true}).click(); + await page.setViewportSize({width: 600, height: 900}); + await page.getByRole('tab', {name: 'Connections', exact: true}).click(); + await expect(page.locator('.rp-drawer .rp-h3')).toHaveText('cdn.bilibili.com'); + const running = await page.evaluate(() => document.getAnimations().filter(a => (a.effect as KeyframeEffect).target?.closest?.('.rp-underlay')).length); + expect(running).toBe(0); + }); +}); diff --git a/e2e/contrast.spec.ts b/e2e/contrast.spec.ts index f0180988..101c3050 100644 --- a/e2e/contrast.spec.ts +++ b/e2e/contrast.spec.ts @@ -1,10 +1,10 @@ import {expect, test} from './fixtures'; import type {PaletteId} from '../src/shell/preferences'; -// Every palette, both schemes: the accent and the status tones as text on the base and surface, text on an accent fill, -// and body text. +// Every palette, both schemes: the accent, the status tones and secondary text as text on the base, the surface, a +// tile (the overlay) and a selected tile, text on an accent fill, and body text. // Palettes keep their official values, so a failing pair is fixed by the token a use reads, never by a new colour. -// Glass is left out: its surfaces are translucent over a gradient. Kary's own light text on its light base is 4.1:1. +// Glass is left out: its surfaces are translucent over a gradient. const palettes = { 'rose-pine/main': 1, 'rose-pine/moon': 1, @@ -19,15 +19,35 @@ const palettes = { 'semi/semi': 1 } satisfies Record; const roles = ['accent', 'negative', 'notice', 'positive', 'info']; -// Kary's light tones sit at that same 4.1:1, and its accent and info text fall back to the body text; its body text on -// its own overlay is 3.9:1. Each known pair keeps a floor of its own. +// Page-level secondary text reads the palette's own subtle, a known exception on the base and surface as in the a11y +// spec: [base, surface] floors for each look under 4.5:1 on either, 4.5 on a side that passes. Tiles read +// --rp-subtle-text and get no exception. +const subtleFloors: Record = { + 'rose-pine/main light': [4, 4.2], + 'rose-pine/moon light': [4, 4.2], + 'rose-pine/moon dark': [4.5, 4.4], + 'catppuccin/frappe light': [4, 4.3], + 'catppuccin/macchiato light': [4, 4.3], + 'catppuccin/mocha light': [4, 4.3], + 'kary/kary light': [3.4, 3.6], + 'antd/antd light': [3.3, 3.3], + 'antd/antd dark': [4.4, 4.5], + 'arco/arco light': [3.2, 3.2] +}; +// Kary's light body text is 4.1:1 on its base, 4.3:1 on its surface, 3.9:1 on a tile and 3.4:1 on a selected tile; +// its tones sit at the same level and its accent, info and tile secondary text fall back to that body text. Its +// page-level subtle keeps the lower floors above. +const karyFloors: Record = {base: 4, surface: 4.2, tile: 3.8, 'selected tile': 3.4}; const known = new Map([ - ['kary/kary light text on base', 4], - ['kary/kary light text on overlay', 3.8], - ...roles.flatMap(role => [[`kary/kary light ${role} text on base`, 4] as const, [`kary/kary light ${role} text on surface`, 4] as const]) + ...Object.entries(karyFloors).flatMap(([ground, floor]) => + ['text', 'subtle text', ...roles.map(role => `${role} text`)].map(name => [`kary/kary light ${name} on ${ground}`, floor] as const) + ), + ...Object.entries(subtleFloors).flatMap(([look, [base, surface]]) => [ + [`${look} subtle text on base`, base] as const, + [`${look} subtle text on surface`, surface] as const + ]) ]); - -test('accent and status text and accent fills reach 4.5:1 in every palette', async ({page}) => { +test('accent, status and secondary text and accent fills reach 4.5:1 in every palette', async ({page}) => { await page.goto('/#/activity'); const failures: string[] = []; for (const [palette, checked] of Object.entries(palettes)) { @@ -41,11 +61,11 @@ test('accent and status text and accent fills reach 4.5:1 in every palette', asy const probe = document.createElement('i'); probe.style.color = value; document.body.append(probe); - const channels = getComputedStyle(probe) - .color.match(/[\d.]+/g)! - .map(Number); + const color = getComputedStyle(probe).color; probe.remove(); - return channels; + const channels = color.match(/[\d.]+/g)!.map(Number); + // A mixed colour computes to color(srgb r g b / a) with channels from 0 to 1. + return color.startsWith('color(') ? channels.map((channel, i) => (i < 3 ? channel * 255 : channel)) : channels; }; // A translucent colour is drawn over what lies beneath it: the background over the base, the text over that. const over = (value: number[], below: number[]) => { @@ -56,24 +76,33 @@ test('accent and status text and accent fills reach 4.5:1 in every palette', asy const [r, g, b] = channels.map(c => ((c /= 255) <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4)); return 0.2126 * r + 0.7152 * g + 0.0722 * b; }; - const base = rgb('var(--rp-base)'); - const ratio = (fg: string, bg: string) => { - const below = over(rgb(bg), base); + const pair = (fg: string, bg: string, page: string) => { + const below = over(rgb(bg), rgb(page)); const [hi, lo] = [luminance(over(rgb(fg), below)), luminance(below)].sort((x, y) => y - x); return (hi + 0.05) / (lo + 0.05); }; + const ratio = (fg: string, bg: string) => pair(fg, bg, 'var(--rp-base)'); + // Tiles sit in cards on the base and in panels on the surface; a translucent tile takes the lower of the two. + const tile = (fg: string, bg: string) => Math.min(pair(fg, bg, 'var(--rp-base)'), pair(fg, bg, 'var(--rp-surface)')); + const on = (fg: string) => ({ + base: ratio(fg, 'var(--rp-base)'), + surface: ratio(fg, 'var(--rp-surface)'), + tile: tile(fg, 'var(--rp-overlay)'), + 'selected tile': tile(fg, 'var(--rp-selected)') + }); + const each = (name: string, values: Record) => + Object.entries(values).map(([ground, value]): [string, number] => [`${name} on ${ground}`, value]); + // An undefined token falls back to transparent, which measures 1:1 instead of passing as inherited text. + const subtle = on('var(--rp-subtle-text, transparent)'); return { - // An undefined token falls back to transparent, which measures 1:1 instead of passing as inherited text. - ...Object.fromEntries( - roles.flatMap(role => [ - [`${role} text on base`, ratio(`var(--rp-${role}-text, transparent)`, 'var(--rp-base)')], - [`${role} text on surface`, ratio(`var(--rp-${role}-text, transparent)`, 'var(--rp-surface)')] - ]) - ), + ...Object.fromEntries(roles.flatMap(role => each(`${role} text`, on(`var(--rp-${role}-text, transparent)`)))), + // Page-level secondary text reads the palette's subtle; tiles read --rp-subtle-text. + 'subtle text on base': ratio('var(--rp-subtle)', 'var(--rp-base)'), + 'subtle text on surface': ratio('var(--rp-subtle)', 'var(--rp-surface)'), + 'subtle text on tile': subtle.tile, + 'subtle text on selected tile': subtle['selected tile'], 'text on accent': ratio('var(--rp-on-accent)', 'var(--rp-accent)'), - 'text on base': ratio('var(--rp-text)', 'var(--rp-base)'), - // Tab and segmented labels sit on the overlay track. - 'text on overlay': ratio('var(--rp-text)', 'var(--rp-overlay)') + ...Object.fromEntries(each('text', on('var(--rp-text)'))) }; }, [palette, scheme, roles] as const diff --git a/e2e/honest.spec.ts b/e2e/honest.spec.ts index ba4be79f..0e294e57 100644 --- a/e2e/honest.spec.ts +++ b/e2e/honest.spec.ts @@ -6,7 +6,7 @@ test('native activity shows the API version and follows runtime events', async ( await page.clock.install(); await page.goto('/#/activity'); await expect(page.locator('.rp-version')).toHaveText(`${version.engine.name} ${version.engine.version}`); - const notifications = page.getByRole('region', {name: 'Notifications and issues'}); + const notifications = page.getByRole('region', {name: 'Notifications', exact: true}); await page.clock.fastForward(5100); await expect(notifications.getByRole('listitem').filter({hasText: 'runtime.updated'})).toHaveCount(0); await page.goto('/#/events'); @@ -56,7 +56,7 @@ test('refresh remains pending until completion, refetches non-polling resources, }); await page.goto('/#/activity'); await expect(page.locator('.rp-version')).toHaveText(`${version.engine.name} ${version.engine.version}`); - await expect(page.locator('.rp-content').getByRole('status')).toHaveCount(0); + await expect(page.locator('.rp-content [role=status]')).toHaveCount(0); await expect.poll(() => Object.keys(counts).sort()).toEqual(Object.keys(responses).sort()); // Resources gated on capabilities start a moment after it lands; wait until the counts stop moving. await expect diff --git a/e2e/interactions.spec.ts b/e2e/interactions.spec.ts index d023af42..d06db080 100644 --- a/e2e/interactions.spec.ts +++ b/e2e/interactions.spec.ts @@ -200,3 +200,30 @@ for (const [route, column, tip] of [ await expect(page.getByRole('tooltip')).toHaveText(tip, {timeout: 1500}); }).toPass(); }); + +test('a kept tab panel is the same element after switching away and back', async ({page}) => { + await page.goto('/#/dns'); + const cache = page.getByRole('tab', {name: 'Cache', exact: true}); + await cache.click(); + const panel = page.getByRole('tabpanel', {name: 'Cache'}); + await expect(panel.getByRole('grid')).toBeVisible(); + await panel.getByRole('grid').evaluate(grid => ((grid as HTMLElement & {kept?: boolean}).kept = true)); + await page.getByRole('tab', {name: 'Statistics', exact: true}).click(); + await expect(panel).toBeHidden(); + await cache.click(); + expect(await panel.getByRole('grid').evaluate(grid => (grid as HTMLElement & {kept?: boolean}).kept)).toBe(true); +}); + +test('a segmented marker inside a hidden tab panel keeps its place', async ({page}) => { + await page.goto('/#/nodes?tab=latency'); + const by = page.getByRole('radiogroup', {name: 'Group by'}); + await by.getByRole('radio', {name: 'Protocol'}).click(); + await expect(by.locator('.rp-slider')).not.toHaveCSS('left', '0px'); + const slider = (await by.locator('.rp-slider').elementHandle())!; + const left = await slider.evaluate(el => (el as HTMLElement).style.left); + await page.getByRole('tab').first().click(); + await expect(by).toBeHidden(); + // The resize observer reports the hidden size before the next frame; the frame after it shows what it did. + await page.evaluate(() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(done)))); + expect(await slider.evaluate(el => (el as HTMLElement).style.left)).toBe(left); +}); diff --git a/e2e/language.spec.ts b/e2e/language.spec.ts index bc3867c5..88acef8b 100644 --- a/e2e/language.spec.ts +++ b/e2e/language.spec.ts @@ -14,7 +14,7 @@ for (const lang of ['zh-TW', 'zh-CN', 'en'] as const) { await expect(nav).toBeVisible(); } await expect(page.locator('.rp-nav').first()).toBeVisible(); - await expect(page.locator('.rp-content').getByRole('status')).toHaveCount(0); + await expect(page.locator('.rp-content [role=status]')).toHaveCount(0); }); test('editor completion suggestions have a localized accessible name', async ({page}) => { await page.goto('/#/config?tab=source'); @@ -100,6 +100,26 @@ test.describe('language loading', () => { expect(await scFaces()).toBeGreaterThan(0); }); + test('declares the TC ideograph faces only once zh-TW is chosen, before the page renders in it', async ({page}) => { + await page.goto('/#/activity'); + await expect(page.locator('html')).toHaveAttribute('lang', 'en-US'); + // Counted in the same task that switches the language, before the browser paints it. + const latin = await page.evaluate(() => { + const html = document.documentElement; + const count = () => [...document.fonts].filter(face => face.family.replace(/["']/g, '') === 'Noto Sans TC').length; + new MutationObserver((_, observer) => { + if (html.lang !== 'zh-TW') return; + html.dataset.tcFaces = String(count()); + observer.disconnect(); + }).observe(html, {attributes: true, attributeFilter: ['lang']}); + return count(); + }); + await page.getByRole('button', {name: translate('en', 'lang'), exact: true}).click(); + await page.getByRole('menuitemradio', {name: '繁體中文'}).click(); + await expect(page.locator('html')).toHaveAttribute('lang', 'zh-TW'); + expect(Number(await page.locator('html').getAttribute('data-tc-faces'))).toBeGreaterThan(latin + 50); + }); + test('zh-TW renders the same after zh-CN in one session as after a reload', async ({page}) => { const family = () => page.evaluate(() => getComputedStyle(document.body).fontFamily); await page.goto('/#/activity'); diff --git a/e2e/mobile.spec.ts b/e2e/mobile.spec.ts index 4c39c482..82979b3c 100644 --- a/e2e/mobile.spec.ts +++ b/e2e/mobile.spec.ts @@ -17,7 +17,7 @@ test('mobile page select exposes and opens every page without horizontal overflo await expect(options).toHaveCount(shown.length); await options.nth(index).click(); await expect(page).toHaveURL(new RegExp(`#/${route}$`)); - await expect(page.locator('.rp-content').getByRole('status')).toHaveCount(0); + await expect(page.locator('.rp-content [role=status]')).toHaveCount(0); } await page.goto('/#/activity'); expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true); @@ -108,7 +108,7 @@ test.describe('320px', () => { await expect(page.locator('.rp-content > *').first()).toBeVisible(); // WebKit's per-page load check: the page is the current one and has finished loading. if (route !== 'flows') await expect(page.locator(`.rp-nav[href="#/${route}"]`)).toHaveAttribute('aria-current', 'page'); - await expect(page.locator('.rp-content').getByRole('status')).toHaveCount(0); + await expect(page.locator('.rp-content [role=status]')).toHaveCount(0); expect(await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth)).toBeLessThanOrEqual(0); }); } diff --git a/e2e/nodes.spec.ts b/e2e/nodes.spec.ts index 4a96c034..a74f23a2 100644 --- a/e2e/nodes.spec.ts +++ b/e2e/nodes.spec.ts @@ -188,7 +188,7 @@ test('without a node list the page shows providers alone, with no latency tab', backend.capabilities.resources.nodes.available = false; await page.goto('/#/nodes?tab=latency'); await expect(page.getByRole('tab')).toHaveCount(0); - await expect(page.locator('.rp-content').getByRole('status')).toHaveCount(0); + await expect(page.locator('.rp-content [role=status]')).toHaveCount(0); }); test('while a cancelled removal is still pending, no other node dialog can submit', async ({page}) => { @@ -218,3 +218,41 @@ test('while a cancelled removal is still pending, no other node dialog can submi await expect(page.locator('.rp-toast.positive', {hasText: `${node.name} removed`})).toBeVisible(); await expect(add).toBeEnabled(); }); + +test('short tables fit their rows, the protocol column shows whole names, and a long address stays inside its table', async ({page}) => { + await page.setViewportSize({width: 1280, height: 900}); + const backend = await mockBackend(page); + // Slow reads, so each table is drawn while it loads. + const slow = (read: () => Promise) => async () => { + await new Promise(resolve => setTimeout(resolve, 300)); + return read(); + }; + backend.handlers['GET providers'] = slow(() => backend.api.providers()); + backend.handlers['GET geodata'] = slow(() => backend.api.geodata()); + const whole = (cell: Locator) => cell.evaluate(element => element.scrollWidth <= element.clientWidth); + await page.goto('/#/nodes'); + const sources = page.getByRole('grid', {name: 'Sources', exact: true}); + await expect(sources.getByRole('row')).toHaveCount(3); + // A heading, two rows and the frame: no placeholder height left over from loading. + expect((await page.locator('.rp-table', {has: sources}).boundingBox())!.height).toBeLessThanOrEqual(2 + 37 + 2 * 40 + 1); + const protocol = page.locator('.rp-table .rp-truncate', {hasText: /^shadowsocks$/}).first(); + expect(await whole(protocol)).toBe(true); + await page.goto('/#/settings'); + const geodata = page.getByRole('grid', {name: 'Geodata', exact: true}); + await expect(geodata.getByRole('row')).toHaveCount(3); + expect((await page.locator('.rp-table', {has: geodata}).boundingBox())!.height).toBeLessThanOrEqual(2 + 37 + 2 * 40 + 1); + // The release address is cut inside its column, not past the table's edge. + const table = (await page.locator('.rp-table', {has: geodata}).boundingBox())!; + const source = (await geodata.getByRole('row').nth(1).getByRole('gridcell').last().boundingBox())!; + expect(source.x + source.width).toBeLessThanOrEqual(table.x + table.width + 1); +}); + +test('the note about node sources belongs to the list, not the latency tab', async ({page}) => { + await mockBackend(page); + await page.goto('/#/nodes'); + const note = page.getByText(/^Sources are subscriptions, files/); + await expect(note).toBeVisible(); + await page.getByRole('tab', {name: 'Latency', exact: true}).click(); + await expect(page.getByRole('tabpanel', {name: 'Latency'}).getByRole('region', {name: 'Node latency'})).toBeVisible(); + await expect(note).toBeHidden(); +}); diff --git a/e2e/password.spec.ts b/e2e/password.spec.ts index 0df392d2..7dbc3273 100644 --- a/e2e/password.spec.ts +++ b/e2e/password.spec.ts @@ -44,8 +44,11 @@ test.use({storage: {'doona-lang': 'en'}}); test('a first visit creates the administrator and continues with its session', async ({page}) => { const state = await passwordBackend(page, true); await page.goto('/#/activity'); - const form = page.locator('.rp-login'); + const form = page.getByRole('dialog'); await expect(form.getByRole('heading')).toHaveText('Create the administrator'); + // Nothing behind the dialog works before sign-in, so it cannot be dismissed. + await page.keyboard.press('Escape'); + await expect(form).toBeVisible(); await form.getByLabel('Username', {exact: true}).fill('admin'); await form.getByLabel('Password', {exact: true}).fill('correct horse battery'); await form.getByLabel('Confirm password', {exact: true}).fill('correct horse batterx'); @@ -53,19 +56,32 @@ test('a first visit creates the administrator and continues with its session', a // A field's own problem is reported on that field and costs no attempt against the backend. const confirm = form.getByLabel('Confirm password', {exact: true}); await expect(confirm).toHaveAttribute('aria-invalid', 'true'); - await expect(form.locator('.rp-field', {hasText: 'Confirm password'})).toContainText('The passwords do not match.'); + const field = form.locator('.rp-field', {hasText: 'Confirm password'}); + await expect(field).toContainText('The passwords do not match.'); + // The error reads in the negative tone and the field it names takes a negative edge. + const tones = await field.getByText('The passwords do not match.').evaluate(error => { + const probe = document.createElement('i'); + probe.style.color = 'var(--rp-negative-text)'; + probe.style.borderColor = 'var(--rp-negative)'; + error.append(probe); + const want = {text: getComputedStyle(probe).color, edge: getComputedStyle(probe).borderTopColor}; + probe.remove(); + const input = error.closest('.rp-field')!.querySelector('.rp-input')!; + return {want, text: getComputedStyle(error).color, edge: getComputedStyle(input).borderTopColor}; + }); + expect({text: tones.text, edge: tones.edge}).toEqual(tones.want); expect(state.attempts).toHaveLength(0); await form.getByLabel('Confirm password', {exact: true}).fill('correct horse battery'); await Promise.all([page.waitForEvent('load'), form.getByRole('button', {name: 'Create and sign in'}).click()]); expect(state.attempts).toEqual([{path: 'setup', body: {username: 'admin', password: 'correct horse battery'}, authorization: undefined}]); - await expect(page.locator('.rp-login')).toHaveCount(0); + await expect(page.getByRole('dialog')).toHaveCount(0); await expect(page.locator('.rp-nav').first()).toBeVisible(); }); test('login reports wrong credentials, then signs in; a refused session asks again', async ({page}) => { const state = await passwordBackend(page, false); await page.goto('/#/activity'); - const form = page.locator('.rp-login'); + const form = page.getByRole('dialog'); await expect(form.getByRole('heading')).toHaveText('Sign in'); await expect(form.getByLabel('Confirm password', {exact: true})).toHaveCount(0); await form.getByLabel('Username', {exact: true}).fill('admin'); @@ -87,7 +103,7 @@ test('login reports wrong credentials, then signs in; a refused session asks aga test('signing out ends the session on the backend and in the tab', async ({page}) => { const state = await passwordBackend(page, false); - const form = page.locator('.rp-login'); + const form = page.getByRole('dialog'); await page.goto('/#/activity'); await form.getByLabel('Username', {exact: true}).fill('admin'); await form.getByLabel('Password', {exact: true}).fill('correct horse battery'); @@ -96,7 +112,37 @@ test('signing out ends the session on the backend and in the tab', async ({page} await Promise.all([page.waitForEvent('load'), page.getByRole('button', {name: 'Sign out', exact: true}).click()]); expect(state.attempts.at(-1)).toMatchObject({path: 'logout', authorization: 'Bearer hnk1_session'}); await page.goto('/#/activity'); - await expect(page.locator('.rp-login').getByRole('heading')).toHaveText('Sign in'); + await expect(page.getByRole('dialog').getByRole('heading')).toHaveText('Sign in'); // Signing out is not an ended session: no warning greets the next sign-in. await expect(page.locator('.rp-login .rp-alert')).toHaveCount(0); }); + +test('settings offers no token field for a password backend', async ({page}) => { + await passwordBackend(page, false); + await page.goto('/#/settings'); + await expect(page.getByText('This backend signs in with a username and password', {exact: false})).toBeVisible(); + await expect(page.locator('[name=token]')).toHaveCount(0); + // Another address is not known to use passwords until it is tested, so its token field returns. + await page.locator('[name=api]').fill('http://other.test'); + await expect(page.locator('[name=token]')).toBeVisible(); +}); + +test('a failed discovery asks to retry instead of guessing the sign-in', async ({page}) => { + const backend = await mockBackend(page); + let up = false; + backend.handlers['GET /api'] = async () => { + if (!up) throw new ApiError(502, '', 'Bad Gateway'); + return {...(await backend.api.discovery()), auth: {mode: 'password', setup_required: false, anonymous_loopback: false}}; + }; + backend.handlers['GET capabilities'] = async () => { + throw new ApiError(401, 'authentication_required', 'Authentication required'); + }; + await page.goto('/#/activity'); + const dialog = page.getByRole('dialog'); + await expect(dialog.getByRole('alert')).toContainText('Bad Gateway'); + await expect(dialog.getByLabel('Token', {exact: true})).toHaveCount(0); + up = true; + await dialog.getByRole('button', {name: 'Retry', exact: true}).click(); + await expect(dialog.getByRole('heading')).toHaveText('Sign in'); + await expect(dialog.getByLabel('Username', {exact: true})).toBeVisible(); +}); diff --git a/e2e/policies.spec.ts b/e2e/policies.spec.ts index 04daeb45..4dab8be6 100644 --- a/e2e/policies.spec.ts +++ b/e2e/policies.spec.ts @@ -21,7 +21,7 @@ test('policies select a member, pin one network, release and test the group', as await expect(automatic.getByRole('button', {name: 'Back to automatic', exact: true})).toHaveCount(0); await expect(automatic.getByRole('button', {name: /^sg-01\b/})).toHaveAttribute('aria-pressed', 'true'); await automatic.getByRole('button', {name: 'Test all', exact: true}).click(); - await expect(page.locator('.rp-toast.positive').filter({hasText: /resilient.*available.*selection (changed|unchanged)/})).toBeVisible(); + await expect(page.locator('.rp-toast.positive').filter({hasText: /resilient.*Available.*selection: (changed|unchanged)/})).toBeVisible(); await expect(automatic.getByRole('button', {name: 'Test all', exact: true})).toBeEnabled(); const controls = requests.filter(request => request.method() !== 'GET'); expect(controls.map(request => [request.method(), new URL(request.url()).pathname + new URL(request.url()).search])).toEqual([ @@ -34,3 +34,17 @@ test('policies select a member, pin one network, release and test the group', as expect(controls[1].postDataJSON()).toEqual({member_id: 'us-01', network: 'tcp'}); expect(controls[3].postDataJSON()).toMatchObject({target: {type: 'group', group_id: 'resilient'}, transport: ['tcp']}); }); + +test('a group card mounted on screen shows its members in the first frame', async ({page}) => { + // Checked in the frame callback, which sees what is about to be painted. + await page.addInitScript(() => { + const check = () => { + for (const wait of document.querySelectorAll('.rp-content section.rp-card .rp-wait-line')) + if (wait.closest('section')!.getBoundingClientRect().top < innerHeight) document.documentElement.dataset.waited = ''; + }; + new MutationObserver(() => requestAnimationFrame(check)).observe(document, {childList: true, subtree: true}); + }); + await page.goto('/#/policies'); + await expect(page.locator('.rp-content .rp-node').first()).toBeVisible(); + await expect(page.locator('html')).not.toHaveAttribute('data-waited'); +}); diff --git a/e2e/profiles.spec.ts b/e2e/profiles.spec.ts index e26d6f62..7ee4b8c3 100644 --- a/e2e/profiles.spec.ts +++ b/e2e/profiles.spec.ts @@ -68,11 +68,13 @@ browserTest('a token draft survives persistence failure and can be retried', asy await page.goto('/#/activity'); const token = page.getByLabel('Token', {exact: true}); await token.fill('retain-this-token'); + // Full even after the stored chart history is given up, which is the one retry the save makes. await page.evaluate(() => { const setItem = Storage.prototype.setItem; + let refusals = 2; Storage.prototype.setItem = function (key, value) { - if (key === 'doona-profiles') { - Storage.prototype.setItem = setItem; + if (key === 'doona-profiles' && refusals) { + if (!--refusals) Storage.prototype.setItem = setItem; throw new DOMException('Storage denied', 'QuotaExceededError'); } return setItem.call(this, key, value); diff --git a/e2e/routes.spec.ts b/e2e/routes.spec.ts index fa40098b..a9c89bd5 100644 --- a/e2e/routes.spec.ts +++ b/e2e/routes.spec.ts @@ -8,7 +8,7 @@ for (const width of [1024, 1280, 1440]) { await page.goto(`/#/${route}${route === 'connections' ? '?tab=list' : ''}`); if (!(await offered(page, route))) continue; await expect(page.locator('.rp-content > .rp-page')).toBeVisible(); - await expect(page.locator('.rp-content').getByRole('status')).toHaveCount(0); + await expect(page.locator('.rp-content [role=status]')).toHaveCount(0); // Tables that sit behind a tab or a fold are opened first; the fit rule applies to all of them. if (route === 'dns') await page.getByRole('tab', {name: 'Cache', exact: true}).click(); // A live backend may offer the rules page without the trace simulation. diff --git a/e2e/store.spec.ts b/e2e/store.spec.ts index fe0d8fba..b66ec96e 100644 --- a/e2e/store.spec.ts +++ b/e2e/store.spec.ts @@ -79,3 +79,22 @@ test('query simulation refuses DNS fan-out above the advertised address limit', await expect(page.getByText(/DNS returned more than 1 distinct addresses/)).toBeVisible(); expect(requests.filter(request => request.method() === 'POST' && request.url().endsWith('/routing/trace'))).toHaveLength(0); }); + +// Five-second polls are for what changes by the second; these lists and rings refresh far less often. +for (const [route, path, most] of [ + ['activity', 'runtime/traffic/history', 2], + ['activity', 'connections', 4], + ['settings', 'providers', 3] +] as const) + test(`${route} fetches ${path} at most ${most} times a minute`, async ({page}) => { + const {requests} = await mockBackend(page); + const count = () => requests.filter(request => new URL(request.url()).pathname === `/api/v1/${path}`).length; + await page.clock.install(); + await page.goto(`/#/${route}`); + await expect.poll(count).toBe(1); + for (let i = 0; i < 12; i++) { + await page.clock.fastForward(5000); + await page.waitForTimeout(50); + } + expect(count()).toBeLessThanOrEqual(most); + }); diff --git a/src/api/auth.ts b/src/api/auth.ts index 3f342de7..81db2140 100644 --- a/src/api/auth.ts +++ b/src/api/auth.ts @@ -1,5 +1,5 @@ import type {components} from './types'; -import {responseError} from './error'; +import {responseError, send} from './error'; export type AuthDiscovery = components['schemas']['AuthDiscovery']; export type AuthCredentials = components['schemas']['AuthCredentials']; @@ -11,7 +11,7 @@ const url = (base: string, path: string) => new URL(base.replace(/\/+$/, '') + p // Discovery is public, so it is read without a token; a backend that predates password login has no `auth`. export async function discoverAuth(base: string, signal?: AbortSignal): Promise { - const response = await fetch(url(base, '/api'), {headers: {Accept: 'application/json'}, cache: 'no-store', signal}); + const response = await send(url(base, '/api'), {headers: {Accept: 'application/json'}, cache: 'no-store', signal}); if (!response.ok) throw await responseError(response); const body: {auth?: AuthDiscovery} = await response.json(); return body.auth ?? null; diff --git a/src/api/client.test.ts b/src/api/client.test.ts index 5d6a1c99..ccdb3e1d 100644 --- a/src/api/client.test.ts +++ b/src/api/client.test.ts @@ -57,6 +57,10 @@ describe('native transport', () => { await expect(createApi('https://honk.test').startReload()).rejects.toThrow('network down'); expect(request).toHaveBeenCalledTimes(1); }); + it('reports a request that got no response as a network failure with a translated text', async () => { + vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new TypeError('Failed to fetch'))); + await expect(createApi('https://honk.test').dnsCache()).rejects.toMatchObject({status: 0, code: 'network_error', text: {key: 'ui.errNetwork'}}); + }); it.each(['events', 'logs'] as const)('skips malformed id-less %s frames without reconnecting', async kind => { vi.useFakeTimers(); const controller = new AbortController(); diff --git a/src/api/client.ts b/src/api/client.ts index 4be2987a..698decc3 100644 --- a/src/api/client.ts +++ b/src/api/client.ts @@ -2,7 +2,7 @@ import createClient from 'openapi-fetch'; import type {paths} from './types'; import type {Api} from './api'; import type {ApiEvent, EventKind, EventOptions, FlowDetail, LogOptions, LogRecord, OperationAccepted, OperationState, RoutingTraceResponse} from './model'; -import {ApiError, clientError, responseError} from './error'; +import {ApiError, clientError, responseError, send} from './error'; import {uuid} from './hash'; import {readSse} from './sse'; import {wait} from './wait'; @@ -34,10 +34,10 @@ export function createApi(base: string, token?: string): Api { cache: 'no-store', fetch: async request => { const retryable = request.method !== 'GET' || new URL(request.url).pathname.endsWith('/dns/query'); - if (!retryable) return fetch(request); + if (!retryable) return send(request); // A refusal with Retry-After is waited out a few times; the caller sees the last refusal after that. for (let refused = 0; ; refused++) { - const response = await fetch(request.clone()); + const response = await send(request.clone()); if ((response.status !== 503 && response.status !== 429) || refused >= MAX_REFUSALS) return response; const error = await responseError(response.clone()); if (!error.transient) return response; @@ -69,7 +69,7 @@ export function createApi(base: string, token?: string): Api { await wait(delay, signal); let response: Response; try { - response = await fetch(url, {headers, cache: 'no-store', signal}); + response = await send(url, {headers, cache: 'no-store', signal}); dropped = 0; } catch (error) { // A dropped connection says nothing about the accepted operation; ask again a few times before giving up. diff --git a/src/api/error.ts b/src/api/error.ts index 040f25a3..0d6ecc7b 100644 --- a/src/api/error.ts +++ b/src/api/error.ts @@ -42,6 +42,18 @@ export async function responseError(response: Response): Promise { export const clientError = (status: number, code: string, message: string, key: Key, params?: Params) => new ApiError(status, code, message, null, null, null, {key, params}); +// A request that gets no response at all fails with the browser's own words ("Failed to fetch", "Load failed"); it is +// reported as a network failure in the page language instead. A cancelled request keeps its AbortError. +export async function send(input: RequestInfo | URL, init?: RequestInit): Promise { + try { + return await fetch(input, init); + } catch (error) { + const signal = init?.signal ?? (input instanceof Request ? input.signal : null); + if (error instanceof TypeError && !signal?.aborted) throw clientError(0, 'network_error', error.message, 'ui.errNetwork'); + throw error; + } +} + // Local failures carry a message key; detail preserves backend text. export class LocalError extends Error { constructor( diff --git a/src/api/mock/activation.ts b/src/api/mock/activation.ts index f9d9ddba..bff0b954 100644 --- a/src/api/mock/activation.ts +++ b/src/api/mock/activation.ts @@ -1,24 +1,7 @@ import type {Group, Node, Provider} from '../model'; import {blockFields, quote, scanConfig, unquote} from '../../dae/text'; import {groupAdmits, readGroupEntries, writeGroupEntry} from '../../dae/groups'; - -// The demo engine's view of a native policy expression: which contract kind it behaves as. -const policyKinds: Record = { - select: 'selector', - fixed: 'selector', - urltest: 'urltest', - min_moving_avg: 'urltest', - min_avg10: 'urltest', - min_last_delay: 'urltest', - fallback: 'fallback', - roundrobin: 'loadbalance', - loadbalance: 'loadbalance', - random: 'random', - score: 'score' -}; -function policyKind(native: string): Group['policy']['kind'] { - return policyKinds[native.toLowerCase().replace(/\(.*$/, '')] ?? 'selector'; -} +import {policyKind} from '../../dae/vocab'; export function activateInventory(text: string, revision: string, nodes: Node[], groups: Group[], providers: Provider[]) { const {blocks, tokens} = scanConfig(text); @@ -64,7 +47,7 @@ export function activateInventory(text: string, revision: string, nodes: Node[], const members: Group['members'] = memberNodes.map(node => ({id: node.id, name: node.name, kind: 'node'})); for (const node of memberNodes) memberships.get(node.id)!.push(previous?.id ?? entry.name); const native = entry.policy ?? 'fixed(0)'; - const kind = policyKind(native); + const kind = policyKind(native) ?? 'selector'; const config: Group['config'] = { default_member_id: null, final_outbound: null, diff --git a/src/api/profiles.test.ts b/src/api/profiles.test.ts index 1c665416..e4fde397 100644 --- a/src/api/profiles.test.ts +++ b/src/api/profiles.test.ts @@ -54,3 +54,26 @@ it('keeps the profile this page loaded with when another tab chooses a different else Reflect.deleteProperty(globalThis, 'localStorage'); } }); + +it('gives up stored chart history to save the profiles when storage is full', async () => { + const storage: Record = {'doona-rings-traffic-["a","mock"]': 'x'.repeat(40)}; + Object.defineProperties(storage, { + getItem: {value: (key: string) => storage[key] ?? null}, + setItem: { + value: (key: string, value: string) => { + if (Object.values(storage).join('').length + value.length > 60) throw new DOMException('Full', 'QuotaExceededError'); + storage[key] = value; + } + }, + removeItem: {value: (key: string) => void delete storage[key]} + }); + vi.stubGlobal('localStorage', storage); + vi.resetModules(); + const {writeProfiles} = await import('./profiles'); + try { + writeProfiles({profiles: [{id: 'a', name: 'A', api: 'mock', token: ''}], activeId: 'a'}); + expect(Object.keys(storage)).toEqual(['doona-profiles', 'doona-profile']); + } finally { + vi.unstubAllGlobals(); + } +}); diff --git a/src/api/profiles.ts b/src/api/profiles.ts index d084ddd3..5b8af7f7 100644 --- a/src/api/profiles.ts +++ b/src/api/profiles.ts @@ -91,12 +91,29 @@ export function writeProfiles({profiles, activeId}: Profiles, storage?: StorageP const store = storage ?? localStorage; const normalized = profiles.map(profile => ({...profile, name: profile.name.trim() || profile.id, api: normalizeApi(profile.api)})); const id = normalized.find(profile => profile.id === activeId)?.id ?? normalized[0]?.id ?? ''; - store.setItem('doona-profiles', JSON.stringify(normalized)); - store.setItem('doona-profile', id); + const write = () => { + store.setItem('doona-profiles', JSON.stringify(normalized)); + store.setItem('doona-profile', id); + }; + try { + write(); + } catch { + // Stored chart history is the first thing to give up when storage is full; a second failure is the caller's. + dropRings(); + write(); + } if (!storage) pinnedId = id; touchStorage(); } +function dropRings() { + try { + for (const key of Object.keys(localStorage)) if (key.startsWith('doona-rings-')) localStorage.removeItem(key); + } catch { + /* Storage can be unavailable. */ + } +} + // Strip the hosted /ui/ suffix while preserving any reverse-proxy prefix. export function hostedRoot(loc: {origin: string; pathname: string}): string { const prefix = /^(.*?)\/ui(?:\/|$)/.exec(loc.pathname)?.[1] ?? ''; diff --git a/src/api/rings.test.ts b/src/api/rings.test.ts index 0ba1e4d7..8c986ed6 100644 --- a/src/api/rings.test.ts +++ b/src/api/rings.test.ts @@ -1,5 +1,5 @@ import {expect, it, vi} from 'vitest'; -import {append, bucket, fineLimit, mean, record, resetRings, window, type Fold} from './rings'; +import {append, bucket, fineLimit, mean, pruneRings, record, resetRings, window, type Fold} from './rings'; type Sample = {time: number; value: number | null}; const fold: Fold = (group, time) => ({time, value: mean(group.map(s => s.value))}); @@ -40,7 +40,8 @@ it('does not persist a coarse-history wipe after an out-of-order poll', () => { vi.advanceTimersByTime(60000); record('clock', {time: 3500000, value: null}, fold); vi.advanceTimersByTime(0); - expect(JSON.parse(storage.get(key)!)).toEqual({fine: [{time: 3500000, value: null}], coarse}); + expect(JSON.parse(storage.get(key)!)).toEqual({fine: [{time: 3500000, value: null}]}); + expect(JSON.parse(storage.get(`${key}-coarse`)!)).toEqual(coarse); } finally { resetRings(); vi.useRealTimers(); @@ -152,3 +153,56 @@ it('separates an edited backend while retaining history across credential change vi.unstubAllGlobals(); } }); + +// A storage whose items are its enumerable keys, as Object.keys sees them on the browser's Storage. +function enumerableStorage(entries: Record) { + const storage = {...entries}; + Object.defineProperties(storage, { + getItem: {value: (key: string) => storage[key] ?? null}, + setItem: {value: (key: string, value: string) => void (storage[key] = value)}, + removeItem: {value: (key: string) => void delete storage[key]} + }); + return storage; +} + +it('writes the coarse ring at most every ten minutes', () => { + const storage = enumerableStorage({}); + vi.stubGlobal('localStorage', storage); + vi.stubGlobal('requestIdleCallback', (run: () => void) => run()); + const key = 'doona-rings-coarse-["","mock"]-coarse'; + vi.useFakeTimers(); + const writes: string[] = []; + try { + record('coarse', undefined, fold); + for (let i = 0; i < fineLimit + 25 * 12; i++) { + vi.advanceTimersByTime(5000); + record('coarse', {time: i * 5000, value: i}, fold); + if (storage[key] !== writes.at(-1)) writes.push(storage[key]); + } + // The first save, then one per ten minutes from the hour the fine ring overflows: 1, 61, 71 and 81 minutes. + expect(writes).toHaveLength(4); + } finally { + resetRings(); + vi.useRealTimers(); + vi.unstubAllGlobals(); + } +}); + +it('prunes the rings of a deleted or moved profile at startup', () => { + const kept = 'doona-rings-traffic-["home","https://one.example"]'; + const storage = enumerableStorage({ + 'doona-profiles': JSON.stringify([{id: 'home', name: 'Home', api: 'https://one.example', token: ''}]), + 'doona-profile': 'home', + [kept]: '{}', + [`${kept}-coarse`]: '[]', + 'doona-rings-traffic-["home","https://old.example"]': '{}', + 'doona-rings-memory-["gone","https://one.example"]-coarse': '[]' + }); + vi.stubGlobal('localStorage', storage); + try { + pruneRings(); + expect(Object.keys(storage).filter(key => key.startsWith('doona-rings-'))).toEqual([kept, `${kept}-coarse`]); + } finally { + vi.unstubAllGlobals(); + } +}); diff --git a/src/api/rings.ts b/src/api/rings.ts index 7174cd60..d4ec0588 100644 --- a/src/api/rings.ts +++ b/src/api/rings.ts @@ -58,27 +58,35 @@ export function window(rings: Rings, history: T[], windowSec return {samples, since, until: now}; } -// Persist each backend's history separately; storage failures only cost persistence. -const stores = new Map; saved: number}>(); +// Persist each backend's history separately; storage failures only cost persistence. The fine ring is written every +// minute; the coarse ring, up to a week of buckets, only every ten. +type Stored = {key: string; rings: Rings; saved: number; coarseSaved: number; writtenCoarse: Timed[] | null}; +const stores = new Map(); +const coarseEvery = 10 * minute; +const owner = (id: string, api: string) => JSON.stringify([id, api || 'mock']); function storageKey(name: string) { const {activeId, profiles} = readProfiles(); - const api = profiles.find(profile => profile.id === activeId)?.api || 'mock'; - return `doona-rings-${name}-${JSON.stringify([activeId, api])}`; + return `doona-rings-${name}-${owner(activeId, profiles.find(profile => profile.id === activeId)?.api ?? '')}`; } -function load(name: string): {key: string; rings: Rings; saved: number} { - const key = storageKey(name); - const cached = stores.get(name); - if (cached && cached.key === key) return cached as {key: string; rings: Rings; saved: number}; - let rings: Rings = {fine: [], coarse: []}; +function read(key: string): unknown { try { const raw = localStorage.getItem(key); - const parsed: unknown = raw ? JSON.parse(raw) : null; - if (parsed && typeof parsed === 'object' && Array.isArray((parsed as Rings).fine) && Array.isArray((parsed as Rings).coarse)) - rings = parsed as Rings; + return raw ? JSON.parse(raw) : null; } catch { // Unreadable storage: the curve starts from this session. + return null; } - const store = {key, rings, saved: Date.now()}; +} +function load(name: string): Stored & {rings: Rings} { + const key = storageKey(name); + const cached = stores.get(name); + if (cached && cached.key === key) return cached as Stored & {rings: Rings}; + const stored = read(key) as {fine?: unknown; coarse?: unknown} | null; + const coarse = read(`${key}-coarse`); + const fine = Array.isArray(stored?.fine) ? (stored.fine as T[]) : []; + // An older build kept both rings under one key. + const rings = {fine, coarse: Array.isArray(coarse) ? (coarse as T[]) : Array.isArray(stored?.coarse) ? (stored.coarse as T[]) : []}; + const store = {key, rings, saved: Date.now(), coarseSaved: 0, writtenCoarse: Array.isArray(coarse) ? rings.coarse : null}; stores.set(name, store); return store; } @@ -95,7 +103,7 @@ function save(key: string, value: string) { } } function prune(keep: string) { - const current = new Set([...stores.values()].map(store => store.key).concat(keep)); + const current = new Set([...stores.values()].flatMap(store => [store.key, `${store.key}-coarse`]).concat(keep)); let freed = false; try { for (const key of Object.keys(localStorage)) { @@ -112,14 +120,29 @@ function prune(keep: string) { // A week of minute buckets takes a while to serialise, so the write waits for an idle moment rather than landing in // the poll that produced it; a reset in between drops it, since the rings it would write are gone. let resets = 0; -function saveWhenIdle(store: {key: string; rings: Rings}) { +function saveWhenIdle(store: Stored, coarse: boolean) { const at = resets; const run = () => { - if (at === resets) save(store.key, JSON.stringify(store.rings)); + if (at !== resets) return; + save(store.key, JSON.stringify({fine: store.rings.fine})); + if (coarse) save(`${store.key}-coarse`, JSON.stringify(store.rings.coarse)); }; if (typeof requestIdleCallback === 'function') requestIdleCallback(run, {timeout: 5000}); else setTimeout(run, 0); } +// Rings whose profile is gone or points elsewhere: every profile change reloads the page, so this runs after each. +export function pruneRings() { + const {profiles} = readProfiles(); + const owners = new Set(profiles.length ? profiles.map(profile => owner(profile.id, profile.api)) : [owner('', '')]); + try { + for (const key of Object.keys(localStorage)) { + const found = /^doona-rings-.+?-(\[.*\])(?:-coarse)?$/.exec(key); + if (key.startsWith('doona-rings-') && !(found && owners.has(found[1]))) localStorage.removeItem(key); + } + } catch { + // Unavailable storage: nothing to prune. + } +} const listeners = new Set<() => void>(); const subscribe = (listener: () => void) => { listeners.add(listener); @@ -137,7 +160,12 @@ export function record(name: string, sample: T | undefined, fol const now = Date.now(); if (now - store.saved >= minute) { store.saved = now; - saveWhenIdle(store); + const coarse = store.rings.coarse !== store.writtenCoarse && now - store.coarseSaved >= coarseEvery; + if (coarse) { + store.coarseSaved = now; + store.writtenCoarse = store.rings.coarse; + } + saveWhenIdle(store, coarse); } } return store.rings; @@ -147,6 +175,7 @@ export function resetRings() { for (const store of stores.values()) { try { localStorage.removeItem(store.key); + localStorage.removeItem(`${store.key}-coarse`); } catch { /* Storage can be unavailable. */ } diff --git a/src/api/types.ts b/src/api/types.ts index 6be4e198..0c9eea30 100644 --- a/src/api/types.ts +++ b/src/api/types.ts @@ -1178,7 +1178,7 @@ export interface components { }; AuthCredentials: { username: string; - /** @description 12 to 128 Unicode scalar values, at most 512 UTF-8 bytes; not normalised or trimmed. */ + /** @description 8 to 128 Unicode scalar values, at most 512 UTF-8 bytes; not normalised or trimmed. */ password: string; }; AuthSession: { diff --git a/src/dae/vocab.ts b/src/dae/vocab.ts index 65adbe47..5be15ef0 100644 --- a/src/dae/vocab.ts +++ b/src/dae/vocab.ts @@ -1,3 +1,5 @@ +import type {Group} from '../api/model'; + // The dae configuration vocabulary the engine accepts, as honk's parser spells it (crates/honk-config/src/parser): // the editor's completions and the demo validator both read from here so they cannot drift apart. export const globalKeys = [ @@ -37,6 +39,23 @@ export const globalKeys = [ 'max_concurrent_dials' ]; // Group policies: the canonical names first, then the dae spellings the engine maps onto them. +// Which contract kind a native policy expression behaves as; undefined for one doona does not know. +const policyKinds: Record = { + select: 'selector', + fixed: 'selector', + urltest: 'urltest', + min_moving_avg: 'urltest', + min_avg10: 'urltest', + min_last_delay: 'urltest', + fallback: 'fallback', + roundrobin: 'loadbalance', + loadbalance: 'loadbalance', + random: 'random', + score: 'score' +}; +export function policyKind(native: string): Group['policy']['kind'] | undefined { + return policyKinds[native.toLowerCase().replace(/\(.*$/, '')]; +} export const policies = ['select', 'urltest', 'roundrobin', 'fallback', 'score', 'fixed', 'min_moving_avg', 'min_avg10', 'min_last_delay', 'loadbalance']; // Built-in outbounds; `(must)` keeps DNS traffic from being hijacked for that rule. export const builtinOutbounds = ['direct', 'block', 'direct(must)', 'block(must)']; diff --git a/src/features/activity/Activity.tsx b/src/features/activity/Activity.tsx index 28e1e77c..7a88d055 100644 --- a/src/features/activity/Activity.tsx +++ b/src/features/activity/Activity.tsx @@ -18,7 +18,7 @@ export function Activity() { const vm = useActivity(); const {p, locale, range, setRange, traffic, spark, chartRate, memorySeries, memoryBytes, notices} = vm; const alert = vm.error && ; - if (!vm.ready) return alert || {t('ui.loading')}; + if (!vm.ready) return alert || (vm.discoveryFailed ? null : {t('ui.loading')}); return ( <> {alert} diff --git a/src/features/activity/messages.ts b/src/features/activity/messages.ts index c299a1f5..15822901 100644 --- a/src/features/activity/messages.ts +++ b/src/features/activity/messages.ts @@ -155,7 +155,7 @@ export const messages = defineMessages({ 'act.devices': 'Devices', 'act.domains': 'Domains', 'act.node': 'Node', - 'act.issues': 'Notifications and issues', + 'act.issues': 'Notifications', 'act.noIssues': 'No issues require attention', 'act.unavailable': 'Unavailable', 'act.d7': '7 d', diff --git a/src/features/activity/useActivity.ts b/src/features/activity/useActivity.ts index a552fc22..46ad3d86 100644 --- a/src/features/activity/useActivity.ts +++ b/src/features/activity/useActivity.ts @@ -69,11 +69,10 @@ export function useActivity() { trafficTimestamps: series.timestamps, memoryTimestamps: memoryHistory.timestamps, ready: !!capabilities.data, - error: runtime.error ?? capabilities.error, - retry: () => { - capabilities.refetch(); - if (resources?.runtime.available) runtime.refetch(); - }, + // The shell reports a failed discovery above every page; this page reports only its own reads. + discoveryFailed: !!capabilities.error, + error: runtime.error, + retry: runtime.refetch, showMemory: !!resources?.runtime_memory.available, history: { error: history.error, diff --git a/src/features/activity/useRankingCard.ts b/src/features/activity/useRankingCard.ts index fa1db860..8f0b13cf 100644 --- a/src/features/activity/useRankingCard.ts +++ b/src/features/activity/useRankingCard.ts @@ -4,7 +4,7 @@ import {LOCALE, useLang, useT} from '../../i18n'; import {usePalette} from '../../ui/charts'; import {activityRanking} from './view'; -// The poll runs only while the card is near the viewport; off screen it is paused and keeps its last list. +// The poll runs every 20 seconds while the card is near the viewport; off screen it is paused and keeps its last list. export function useRankingCard() { const t = useT(); const locale = LOCALE[useLang()]; @@ -20,7 +20,7 @@ export function useRankingCard() { }, []); // Paused only once it has a list to keep showing; before that it loads wherever it is. const [loaded, setLoaded] = useState(false); - const connections = useConnections(undefined, available === true, !near && loaded); + const connections = useConnections(undefined, available === true, !near && loaded, 20000); if (connections.data && !loaded) setLoaded(true); const rows = useMemo(() => activityRanking(connections.data, by, p, locale, t), [connections.data, by, p, locale, t]); const state = connections.data ? (rows.length ? 'ready' : 'empty') : connections.error ? 'error' : available === true ? 'loading' : 'unavailable'; diff --git a/src/features/config/messages.ts b/src/features/config/messages.ts index 94ec055d..e35f7d51 100644 --- a/src/features/config/messages.ts +++ b/src/features/config/messages.ts @@ -37,7 +37,7 @@ export const messages = defineMessages({ 'config.save': '套用並重載', 'config.incomplete': '內容不完整或已遮蔽,不能在此編輯', 'config.unquotable': '無法寫入:值含單引號、換行或結尾反斜線,無法無損轉為單引號字串。', - 'config.contentHidden': '此後端不提供組態內容(capabilities.resources.config.content 為 false)', + 'config.contentHidden': '此後端不提供組態內容', 'config.contentWithheld': '後端未回傳此來源的文字,因此不能在此編輯。請檢查後端的內容可見性原則。', 'config.valid': '驗證通過', 'config.invalid': '驗證發現 {n} 個錯誤', @@ -104,7 +104,7 @@ export const messages = defineMessages({ 'config.unsaved': '未儲存', 'config.unsavedHint': '重新載入或關閉頁面會遺失修改', 'config.editNote': - '後端可能隱藏來源文字、路徑或診斷;顯示與匯出的文字仍可能含有憑證。僅在內容完整且雜湊值符合 content_sha256 時允許編輯。儲存請求包含 If-Match;若磁碟上的檔案已變更,後端會回傳 HTTP 412,且不會覆寫檔案。', + '後端可能隱藏來源文字、路徑或診斷;顯示與匯出的文字仍可能含有憑證。僅在後端提供完整內容時可以編輯。若磁碟上的檔案在儲存前已變更,後端會拒絕儲存,不會覆寫該檔案。', 'config.readNote': '此來源由引擎寫入或後端未開放編輯,只能檢視。', 'config.level.error': '錯誤', 'config.level.warning': '警告', @@ -147,7 +147,7 @@ export const messages = defineMessages({ 'config.save': '应用并重载', 'config.incomplete': '内容不完整或已脱敏,不能在此编辑', 'config.unquotable': '无法写入:值含单引号、换行或结尾反斜线,无法无损转为单引号字符串。', - 'config.contentHidden': '此后端不提供配置内容(capabilities.resources.config.content 为 false)', + 'config.contentHidden': '此后端不提供配置内容', 'config.contentWithheld': '后端未返回此来源的文本,因此不能在此编辑。请检查后端的内容可见性策略。', 'config.valid': '校验通过', 'config.invalid': '校验发现 {n} 个错误', @@ -214,7 +214,7 @@ export const messages = defineMessages({ 'config.unsaved': '未保存', 'config.unsavedHint': '重新加载或关闭页面会丢失修改', 'config.editNote': - '后端可能隐藏来源文本、路径或诊断;显示与导出的文本仍可能包含凭据。仅在内容完整且哈希值与 content_sha256 一致时允许编辑。保存请求包含 If-Match;若磁盘上的文件已更改,后端会返回 HTTP 412,且不会覆盖文件。', + '后端可能隐藏来源文本、路径或诊断;显示与导出的文本仍可能包含凭据。仅在后端提供完整内容时可以编辑。若磁盘上的文件在保存前已更改,后端会拒绝保存,不会覆盖该文件。', 'config.readNote': '此来源由引擎写入或后端未开放编辑,只能查看。', 'config.level.error': '错误', 'config.level.warning': '警告', @@ -258,7 +258,7 @@ export const messages = defineMessages({ 'config.save': 'Apply and reload', 'config.incomplete': 'The text is incomplete or redacted; it cannot be edited here', 'config.unquotable': 'Cannot write this value losslessly as a single-quoted string: it contains an apostrophe, line break, or trailing backslash.', - 'config.contentHidden': 'This backend does not provide the configuration text (capabilities.resources.config.content is false)', + 'config.contentHidden': 'This backend does not provide the configuration text', 'config.contentWithheld': 'The backend did not return this source’s text, so it cannot be edited here. Check the backend’s content visibility policy.', 'config.valid': 'Validation passed', 'config.invalid': {one: 'Validation found {n} error', other: 'Validation found {n} errors'}, @@ -329,7 +329,7 @@ export const messages = defineMessages({ 'config.unsaved': 'Unsaved', 'config.unsavedHint': 'Reloading or closing the page loses the changes', 'config.editNote': - 'The backend may withhold source text, paths or diagnostics; displayed and exported text may still contain credentials. Editing is allowed only when the content is complete and its hash matches content_sha256. Save requests include If-Match. If the file has changed on disk, the backend returns HTTP 412 without overwriting it.', + 'The backend may withhold source text, paths or diagnostics; displayed and exported text may still contain credentials. Editing is available only when the backend provides the complete content. If the file has changed on disk before saving, the backend refuses the save and does not overwrite the file.', 'config.readNote': 'This source is written by the engine or the backend does not allow editing; view only.', 'config.level.error': 'Error', 'config.level.warning': 'Warning', diff --git a/src/features/config/view.test.ts b/src/features/config/view.test.ts index 91783ce9..dde4db95 100644 --- a/src/features/config/view.test.ts +++ b/src/features/config/view.test.ts @@ -206,3 +206,10 @@ it('describes only the selected template’s groups and omits routing changes fo expect(named).toContain('proxy, auto, telegram, media, apple'); expect(named).not.toContain('mix'); }); + +it('names group policies in words, keeping only an expression doona does not know as written', () => { + const text = 'group {\n fast { policy: min_avg10 }\n pinned { policy: fixed(0) }\n picked { policy: select }\n odd { policy: custom }\n}'; + expect(sectionSummaries([source(text)], 'en', t).find(card => card.kind === 'group')?.summary).toBe( + '4 groups: fast: Fastest on average, pinned: Manual, picked: Manual, odd: custom' + ); +}); diff --git a/src/features/config/view.ts b/src/features/config/view.ts index cc47ecf5..9d453efa 100644 --- a/src/features/config/view.ts +++ b/src/features/config/view.ts @@ -7,7 +7,8 @@ import {defaultGroup, isSubscriptionUrl, readState, type WizardState} from '../. import {defaultTemplate, templates} from '../../dae/templates'; import {blockFields, isBareName, isQuotable, scanConfig, type TextBlock, type TextToken} from '../../dae/text'; import {href as routeHref} from '../../shell/route'; -import {policyLabel} from '../policies/policies'; +import {groupPolicyText} from '../policies/policyText'; +import {policyKind} from '../../dae/vocab'; import type {EditorMark} from '../../ui/code/CodeEditor'; // Quick setup needs a writable main source with its text; a redacted text is shown but cannot be written back. @@ -97,7 +98,9 @@ function sectionSummary(kind: SectionKind, text: string, block: TextBlock, token lang, block.children.map(child => { const policy = blockFields(text, child, tokens).find(field => field.name === 'policy')?.value; - return policy ? t('ui.valuePair', {label: child.name, value: policyLabel(policy, t)}) : child.name; + if (!policy) return child.name; + const kind = policyKind(policy); + return t('ui.valuePair', {label: child.name, value: kind ? groupPolicyText({kind, native: policy}, t).label : policy}); }) ) }); diff --git a/src/features/connections/messages.ts b/src/features/connections/messages.ts index 4b600753..69592e9a 100644 --- a/src/features/connections/messages.ts +++ b/src/features/connections/messages.ts @@ -12,7 +12,7 @@ export const messages = defineMessages({ 'conn.chart.sampleUnknown': '目前共 {n} 條連線,其中 {unknown} 條沒有流量總計', 'conn.chart.moreDown': '下載較多', 'conn.chart.moreUp': '上傳較多', - 'conn.chart.hint': '橫軸為上傳量,縱軸為下載量,虛線上的連線上傳與下載相等。點選資料點可在連線分頁開啟該連線。', + 'conn.chart.hint': '橫軸為上傳量,縱軸為下載量,虛線表示上傳與下載相等。選取資料點可開啟該連線。', 'conn.chain': '鏈', 'conn.rule': '規則', 'conn.recomputed': '重算', @@ -77,7 +77,7 @@ export const messages = defineMessages({ 'conn.chart.sampleUnknown': '目前共 {n} 条连接,其中 {unknown} 条没有流量总计', 'conn.chart.moreDown': '下载较多', 'conn.chart.moreUp': '上传较多', - 'conn.chart.hint': '横轴为上传量,纵轴为下载量,虚线上的连接上传与下载相等。点击数据点可在连接分页打开该连接。', + 'conn.chart.hint': '横轴为上传量,纵轴为下载量,虚线表示上传与下载相等。点击数据点可打开该连接。', 'conn.chain': '链', 'conn.rule': '规则', 'conn.recomputed': '重算', @@ -146,7 +146,7 @@ export const messages = defineMessages({ 'conn.chart.moreDown': 'More download', 'conn.chart.moreUp': 'More upload', 'conn.chart.hint': - 'Upload runs along the horizontal axis and download up the vertical; connections on the dashed line upload as much as they download. Select a point to open that connection in the connections tab.', + 'Upload runs along the horizontal axis and download up the vertical; the dashed line marks equal traffic. Select a point to open that connection.', 'conn.chain': 'Chain', 'conn.rule': 'Rule', 'conn.recomputed': 'Recomputed', diff --git a/src/features/dns/Analysis.tsx b/src/features/dns/Analysis.tsx index 450b0c77..5cbb5b34 100644 --- a/src/features/dns/Analysis.tsx +++ b/src/features/dns/Analysis.tsx @@ -6,7 +6,7 @@ import {useDnsStatsTab} from './useDns'; import {Card, Bar, Empty, ErrorMessage, Loading, Segmented} from '../../ui/ui'; import type {DnsCacheList, DnsLogRecord} from '../../api/model'; import {usePalette, Beeswarm, FactStrip, LegendItem, ShareBar, Waffle, type ChartFact, type SwarmPoint} from '../../ui/charts'; -import {dnsAnalysis, dnsOutcomes, type DnsAnalysis as Analysis, type DnsOutcome} from './analysis'; +import {dnsAnalysis, dnsOutcomes, type DnsAnalysis as Analysis, type DnsOutcome} from './stats'; import {cacheState} from './cache'; import AlertTriangle from '../../ui/icons/AlertTriangle'; import Clock from '../../ui/icons/Clock'; @@ -165,7 +165,7 @@ function CacheCard({cache, t, shareText}: {cache: DnsCacheList | undefined | nul {t('dns.chart.coverage', { kinds: [state.coverage.positive && t('dns.chart.positive'), state.coverage.negative && t('dns.chart.negative')] .filter(Boolean) - .join(t('ui.separator')), + .join(t('ui.listSeparator')), persistent: t(state.coverage.persistent ? 'dns.chart.persistent' : 'dns.chart.memoryOnly') })}

diff --git a/src/features/dns/Dns.tsx b/src/features/dns/Dns.tsx index f298a376..1d980f40 100644 --- a/src/features/dns/Dns.tsx +++ b/src/features/dns/Dns.tsx @@ -89,7 +89,6 @@ export function Dns(props: PageProps) { }; return (
- {vm.error && } {vm.queryError && } ({...tab, content: content[tab.id]}))} value={vm.tab} onChange={vm.setTab} />
diff --git a/src/features/dns/messages.ts b/src/features/dns/messages.ts index d28d1ee2..f59ed5c1 100644 --- a/src/features/dns/messages.ts +++ b/src/features/dns/messages.ts @@ -25,7 +25,7 @@ export const messages = defineMessages({ 'dns.chart.p95': 'P95', 'dns.chart.cacheRate': '快取命中率', 'dns.chart.failureRate': '失敗率', - 'dns.chart.sample': '已載入 {n} 筆記錄,其中 {uncached} 筆未命中快取、{upstream} 筆送到上游;延遲依上游查詢計算,失敗率依未命中快取的查詢計算', + 'dns.chart.sample': '已載入:{n} 筆,未命中快取:{uncached} 筆,送往上游:{upstream} 筆', 'dns.queryFailed': '無法查詢:{error}', 'dns.deleted': '已刪除 {n} 筆快取項目', 'dns.deleteFailed': '無法刪除快取項目:{error}', @@ -103,7 +103,7 @@ export const messages = defineMessages({ 'dns.chart.p95': 'P95', 'dns.chart.cacheRate': '缓存命中率', 'dns.chart.failureRate': '失败率', - 'dns.chart.sample': '已加载 {n} 条记录,其中 {uncached} 条未命中缓存、{upstream} 条发往上游;延迟按上游查询计算,失败率按未命中缓存的查询计算', + 'dns.chart.sample': '已加载:{n} 条,未命中缓存:{uncached} 条,发往上游:{upstream} 条', 'dns.queryFailed': '无法查询:{error}', 'dns.deleted': '已删除 {n} 条缓存项', 'dns.deleteFailed': '无法删除缓存项:{error}', @@ -184,10 +184,7 @@ export const messages = defineMessages({ 'dns.chart.p95': 'P95', 'dns.chart.cacheRate': 'Cache hit rate', 'dns.chart.failureRate': 'Failure rate', - 'dns.chart.sample': { - one: '{n} loaded record: {uncached} uncached, {upstream} sent upstream; latency counts upstream lookups, the failure rate uncached ones', - other: '{n} loaded records: {uncached} uncached, {upstream} sent upstream; latency counts upstream lookups, the failure rate uncached ones' - }, + 'dns.chart.sample': 'Loaded: {n}, uncached: {uncached}, sent upstream: {upstream}', 'dns.queryFailed': 'Could not run the query: {error}', 'dns.deleted': { one: 'Deleted {n} cache entry', diff --git a/src/features/dns/analysis.test.ts b/src/features/dns/stats.test.ts similarity index 97% rename from src/features/dns/analysis.test.ts rename to src/features/dns/stats.test.ts index cfc241e0..a8f12a20 100644 --- a/src/features/dns/analysis.test.ts +++ b/src/features/dns/stats.test.ts @@ -1,6 +1,6 @@ import {expect, it} from 'vitest'; import type {DnsLogRecord} from '../../api/model'; -import {clientAddress, dnsAnalysis, ranked} from './analysis'; +import {clientAddress, dnsAnalysis, ranked} from './stats'; let n = 0; const record = (patch: Partial & {name?: string; type?: string}): DnsLogRecord => { diff --git a/src/features/dns/analysis.ts b/src/features/dns/stats.ts similarity index 100% rename from src/features/dns/analysis.ts rename to src/features/dns/stats.ts diff --git a/src/features/dns/useDns.ts b/src/features/dns/useDns.ts index 5b2f4ba4..929e002c 100644 --- a/src/features/dns/useDns.ts +++ b/src/features/dns/useDns.ts @@ -52,8 +52,6 @@ export function useDns({go, query}: PageProps) { type, setType, pending: busy === 'query', - error: capabilities.error, - retry: capabilities.refetch, queryError: error, submit: () => void submit(), setTab: (tab: string) => go('dns', tabQuery(query, tab, resources && !params.has('domain') ? fallback : null)), @@ -98,7 +96,7 @@ export function useDnsCacheTab(domain: string) { }; return { ...view, - // Delete failures arrive as toasts, flush failures in its dialog, and the page above reports the capabilities. + // Delete failures arrive as toasts, flush failures in its dialog, and the shell reports the capabilities. error: dns.cache.error, retry: dns.cache.refetch, loading: (dns.cache.loading || dns.capabilities.loading) && !dns.cache.data, diff --git a/src/features/logs/Logs.tsx b/src/features/logs/Logs.tsx index 2044b2f7..e34b84dd 100644 --- a/src/features/logs/Logs.tsx +++ b/src/features/logs/Logs.tsx @@ -16,7 +16,7 @@ export function Logs() { { id: 'ts', label: t('ui.time'), - minWidth: 180, + minWidth: 200, grow: 0, drop: 2, render: record => ( diff --git a/src/features/logs/messages.ts b/src/features/logs/messages.ts index dd205789..4ced3ba3 100644 --- a/src/features/logs/messages.ts +++ b/src/features/logs/messages.ts @@ -24,7 +24,7 @@ export const messages = defineMessages({ 'log.message': '訊息', 'log.chart.title': '日誌時間分布', 'log.chart.sample': '根據最近的 {n} 筆記錄', - 'log.chart.cell': '{time},{level} {n} 筆', + 'log.chart.cell': '{time},{level}:{n} 筆', 'log.chart.minimum': '顯示{level}及以上', 'log.chart.current': '{level}:目前的最低等級', 'log.empty': '尚無日誌' @@ -52,7 +52,7 @@ export const messages = defineMessages({ 'log.message': '消息', 'log.chart.title': '日志时间分布', 'log.chart.sample': '根据最近的 {n} 条记录', - 'log.chart.cell': '{time},{level} {n} 条', + 'log.chart.cell': '{time},{level}:{n} 条', 'log.chart.minimum': '显示{level}及以上', 'log.chart.current': '{level}:当前的最低等级', 'log.empty': '暂无日志' @@ -80,7 +80,7 @@ export const messages = defineMessages({ 'log.message': 'Message', 'log.chart.title': 'Log activity over time', 'log.chart.sample': {one: 'From the latest {n} record', other: 'From the latest {n} records'}, - 'log.chart.cell': {one: '{time}: {n} {level} record', other: '{time}: {n} {level} records'}, + 'log.chart.cell': {one: '{time}, {level}: {n} record', other: '{time}, {level}: {n} records'}, 'log.chart.minimum': 'Show {level} and above', 'log.chart.current': '{level}: the current minimum', 'log.empty': 'No log records yet' diff --git a/src/features/nodes/Latency.tsx b/src/features/nodes/Latency.tsx index c755569e..6d8241ac 100644 --- a/src/features/nodes/Latency.tsx +++ b/src/features/nodes/Latency.tsx @@ -6,7 +6,7 @@ import {usePalette, FactStrip, MarkerPlot, type ChartFact} from '../../ui/charts import AlertTriangle from '../../ui/icons/AlertTriangle'; import Clock from '../../ui/icons/Clock'; import SpeedFast from '../../ui/icons/SpeedFast'; -import {latencyMax, type LatencyBy, type LatencyMissing} from './latency'; +import {latencyMax, type LatencyBy, type LatencyMissing} from './latencyGroups'; import {useLatencyTab} from './useLatencyTab'; const named = 6; diff --git a/src/features/nodes/NodeTable.tsx b/src/features/nodes/NodeTable.tsx index 34d3b8da..60070735 100644 --- a/src/features/nodes/NodeTable.tsx +++ b/src/features/nodes/NodeTable.tsx @@ -34,7 +34,7 @@ export function NodeTable({model: m}: {model: NodeTableView}) { ) }, - {id: 'protocol', label: t('nodes.protocol'), minWidth: 120, grow: 0, drop: 2, sortable: true, render: row => row.protocol}, + {id: 'protocol', label: t('nodes.protocol'), minWidth: 144, grow: 0, drop: 2, sortable: true, render: row => row.protocol}, { id: 'latency', label: t('nodes.latency'), diff --git a/src/features/nodes/Nodes.tsx b/src/features/nodes/Nodes.tsx index 57b1777b..6db1f0d1 100644 --- a/src/features/nodes/Nodes.tsx +++ b/src/features/nodes/Nodes.tsx @@ -35,6 +35,7 @@ export function Nodes(props: PageProps) { } = useNodesPage(props); const list = ( <> +

{t('nodes.note')}

@@ -42,7 +43,6 @@ export function Nodes(props: PageProps) { ); return (
-

{t('nodes.note')}

{measured ? ( ): HealthObservation => ({ diff --git a/src/features/nodes/latency.ts b/src/features/nodes/latencyGroups.ts similarity index 100% rename from src/features/nodes/latency.ts rename to src/features/nodes/latencyGroups.ts diff --git a/src/features/nodes/useLatencyTab.ts b/src/features/nodes/useLatencyTab.ts index b6d723d7..43feebc7 100644 --- a/src/features/nodes/useLatencyTab.ts +++ b/src/features/nodes/useLatencyTab.ts @@ -1,7 +1,7 @@ import {useMemo, useState} from 'react'; import {useCapabilities, useGroups, useNodes} from '../../store'; import {offered} from '../../api/capabilities'; -import {latencyGroups, type LatencyBy} from './latency'; +import {latencyGroups, type LatencyBy} from './latencyGroups'; export function useLatencyTab() { const resources = useCapabilities().data?.resources; diff --git a/src/features/nodes/useNodeTable.ts b/src/features/nodes/useNodeTable.ts index ec0db3c1..20fe1075 100644 --- a/src/features/nodes/useNodeTable.ts +++ b/src/features/nodes/useNodeTable.ts @@ -9,7 +9,7 @@ import {toast, useLinked, type TableSort} from '../../ui/ui'; import {namedIn, readGroupEntries} from '../../dae/groups'; import type {MainSourceEdit} from '../../store/mainSource'; import {collator, nodeRows, nodeRowView} from './view'; -import {policyLabel} from '../policies/policies'; +import {policyLabel} from '../policies/policyText'; import {errorText} from '../../api/error'; type NodeTableInput = { diff --git a/src/features/nodes/useNodesPage.ts b/src/features/nodes/useNodesPage.ts index 5d683711..6bed9869 100644 --- a/src/features/nodes/useNodesPage.ts +++ b/src/features/nodes/useNodesPage.ts @@ -6,7 +6,7 @@ import {toast} from '../../ui/ui'; import {editProblem, useMainSourceEdit} from '../../store/mainSource'; import {addNamesToGroup, applyChanges, readGroupEntries} from '../../dae/groups'; import {isBareName} from '../../dae/text'; -import {groupNameError, newGroupPolicies} from '../policies/policies'; +import {groupNameError, newGroupPolicies} from '../policies/policyText'; import type {PageProps} from '../../shell/routes'; import {readSubscriptions} from './subscriptions'; import {ownedNodes, providerRows} from './view'; diff --git a/src/features/policies/PolicyPicker.tsx b/src/features/policies/PolicyPicker.tsx index 71e5dbd8..a6955918 100644 --- a/src/features/policies/PolicyPicker.tsx +++ b/src/features/policies/PolicyPicker.tsx @@ -1,6 +1,6 @@ import {useT} from '../../i18n'; import {LabeledSelect} from '../../ui/ui'; -import {policyChoices} from './policies'; +import {policyChoices} from './policyText'; // How a group chooses among its members; every group editor offers the same choices. export function PolicyPicker({value, onChange, isDisabled}: {value: string | null; onChange: (policy: string) => void; isDisabled?: boolean}) { diff --git a/src/features/policies/arrange/Arrange.tsx b/src/features/policies/arrange/Arrange.tsx index 8028f7b3..15e4fed0 100644 --- a/src/features/policies/arrange/Arrange.tsx +++ b/src/features/policies/arrange/Arrange.tsx @@ -39,7 +39,7 @@ import Close from '../../../ui/icons/Close'; import DragHandle from '../../../ui/icons/DragHandle'; import type {GroupSummary} from '../../../api/model'; import type {MainSourceEdit} from '../../../store/mainSource'; -import {groupPolicyText, newGroupPolicies} from '../policies'; +import {groupPolicyText, newGroupPolicies} from '../policyText'; import {PolicyPicker} from '../PolicyPicker'; import {holds, parsePlaceable, type ArrangeGroup, type Placeable} from './view'; import {PLACEABLE, useArrange} from './useArrange'; diff --git a/src/features/policies/arrange/useArrange.ts b/src/features/policies/arrange/useArrange.ts index 654bf166..31c18f2f 100644 --- a/src/features/policies/arrange/useArrange.ts +++ b/src/features/policies/arrange/useArrange.ts @@ -7,7 +7,7 @@ import {applyChanges, readGroupEntries, type GroupChange} from '../../../dae/gro import {toast} from '../../../ui/ui'; import {useDraftGuard} from '../../../shell/draft'; import type {MainSourceEdit} from '../../../store/mainSource'; -import {groupNameError} from '../policies'; +import {groupNameError} from '../policyText'; import {arrangeView, changeText, holds, stage, traySubscriptions, unstage, type Placeable} from './view'; import {errorText} from '../../../api/error'; import {offered} from '../../../api/capabilities'; diff --git a/src/features/policies/messages.ts b/src/features/policies/messages.ts index 7c1576ee..e4a99537 100644 --- a/src/features/policies/messages.ts +++ b/src/features/policies/messages.ts @@ -125,8 +125,8 @@ export const messages = defineMessages({ 'policy.save': '儲存', 'policy.editUnsafe': '篩選或策略必須寫在同一行,括號成對,且不含註解或大括號。', 'policy.cfg.millis': '{n} ms', - 'policy.probeChanged': '{healthy} 個可用,{unavailable} 個無法使用,{unknown} 個狀態未知;選擇已變更', - 'policy.probeUnchanged': '{healthy} 個可用,{unavailable} 個無法使用,{unknown} 個狀態未知;選擇未變更', + 'policy.probeChanged': '可用:{healthy},無法使用:{unavailable},狀態未知:{unknown},選擇:已變更', + 'policy.probeUnchanged': '可用:{healthy},無法使用:{unavailable},狀態未知:{unknown},選擇:未變更', 'policy.probePartial': '{n} 個成員中已測試 {done} 個;{error}', 'policy.purpose.data': '資料', 'policy.purpose.dns': 'DNS', @@ -262,8 +262,8 @@ export const messages = defineMessages({ 'policy.save': '保存', 'policy.editUnsafe': '筛选或策略必须写在同一行,括号成对,且不含注释或大括号。', 'policy.cfg.millis': '{n} ms', - 'policy.probeChanged': '{healthy} 个可用,{unavailable} 个不可用,{unknown} 个状态未知;选择已更改', - 'policy.probeUnchanged': '{healthy} 个可用,{unavailable} 个不可用,{unknown} 个状态未知;选择未更改', + 'policy.probeChanged': '可用:{healthy},不可用:{unavailable},状态未知:{unknown},选择:已更改', + 'policy.probeUnchanged': '可用:{healthy},不可用:{unavailable},状态未知:{unknown},选择:未更改', 'policy.probePartial': '{n} 个成员中已测试 {done} 个;{error}', 'policy.purpose.data': '数据', 'policy.purpose.dns': 'DNS', @@ -405,8 +405,8 @@ export const messages = defineMessages({ 'policy.save': 'Save', 'policy.editUnsafe': 'Filters and the policy must stay on one line with balanced parentheses and no comment or brace.', 'policy.cfg.millis': '{n} ms', - 'policy.probeChanged': '{healthy} available, {unavailable} unavailable, {unknown} unknown; selection changed', - 'policy.probeUnchanged': '{healthy} available, {unavailable} unavailable, {unknown} unknown; selection unchanged', + 'policy.probeChanged': 'Available: {healthy}, unavailable: {unavailable}, unknown: {unknown}, selection: changed', + 'policy.probeUnchanged': 'Available: {healthy}, unavailable: {unavailable}, unknown: {unknown}, selection: unchanged', 'policy.probePartial': {one: 'Tested {done} of {n} member; {error}', other: 'Tested {done} of {n} members; {error}'}, 'policy.purpose.data': 'data', 'policy.purpose.dns': 'DNS', diff --git a/src/features/policies/policies.test.ts b/src/features/policies/policyText.test.ts similarity index 99% rename from src/features/policies/policies.test.ts rename to src/features/policies/policyText.test.ts index 60abdf5e..2dc07688 100644 --- a/src/features/policies/policies.test.ts +++ b/src/features/policies/policyText.test.ts @@ -1,6 +1,6 @@ import {expect, it} from 'vitest'; import {translate, type Translator} from '../../i18n'; -import {groupPolicyText, policyChoices, policyLabel} from './policies'; +import {groupPolicyText, policyChoices, policyLabel} from './policyText'; const t: Translator = (key, params) => translate('en', key, params); it('names offered policies in words and keeps any other as written', () => { diff --git a/src/features/policies/policies.ts b/src/features/policies/policyText.ts similarity index 100% rename from src/features/policies/policies.ts rename to src/features/policies/policyText.ts diff --git a/src/features/policies/view.test.ts b/src/features/policies/view.test.ts index 560f5817..86c840c5 100644 --- a/src/features/policies/view.test.ts +++ b/src/features/policies/view.test.ts @@ -88,6 +88,9 @@ it('names the default member and describes an observation in words', () => { expect(fields).toContainEqual(['policy.cfg.defaultMember', member.name]); const [view] = memberViews([{...member, kind: 'node', health: {...g.runtime.health[0], transport: 'udp', purpose: 'dns'}}], t); expect(view.description).toBe(t('policy.observedVia', {transport: 'UDP', purpose: 'DNS'})); + // The usual observation, over TCP on the data path, goes without saying on every tile. + const [usual] = memberViews([{...member, kind: 'node', health: {...g.runtime.health[0], transport: 'tcp', purpose: 'data'}}], t); + expect(usual.description).toBe(' '); }); it('reports a partial probe with translated counts and the stopping error', () => { diff --git a/src/features/policies/view.ts b/src/features/policies/view.ts index b1bb40d5..50addb51 100644 --- a/src/features/policies/view.ts +++ b/src/features/policies/view.ts @@ -2,7 +2,7 @@ import {formatLatency} from '../../i18n/format'; import type {Group, HealthObservation, ProbeResult} from '../../api/model'; import type {Key} from '../../i18n'; import {compareLatency, healthMillis, type MessageRef} from '../../api/selectors'; -import {groupPolicyText} from './policies'; +import {groupPolicyText} from './policyText'; import {formatNumber, type Translator} from '../../i18n'; import {latencyTone, type NodeStatus} from '../../ui/ui'; import {regionOf} from './geo'; @@ -83,9 +83,11 @@ export function memberViews(members: Array asset.kind}, {id: 'size', label: t('settings.geodataSize'), minWidth: 100, grow: 0, align: 'end', render: asset => asset.size}, @@ -131,14 +132,10 @@ export function BackendActionsCard() { { id: 'source', label: t('settings.geodataSource'), - // Wide enough for a release URL: the table scrolls sideways rather than cutting the address. - minWidth: 640, + // A release URL is cut at the column's end; the tooltip gives it whole. + minWidth: 240, grow: 2, - render: asset => ( - - {asset.source} - - ) + render: asset => {asset.source} } ]} /> diff --git a/src/features/settings/RuntimeSettings.tsx b/src/features/settings/RuntimeSettings.tsx index c0e3e7d6..b7070c96 100644 --- a/src/features/settings/RuntimeSettings.tsx +++ b/src/features/settings/RuntimeSettings.tsx @@ -42,7 +42,7 @@ export function RuntimeSettingsCard() { )} {m.hasBaseline && ( <> -
+
{m.hasLevel && } {m.numeric.map(field => ( {m.recorders.length > 0 && ( -
+
{m.recorders.map(recorder => (
- {tokenToggleText}} - name="token" - type={tokenType} - value={token} - onChange={changeToken} - /> + {passwordMode ? ( +

{t('settings.passwordMode')}

+ ) : ( + {tokenToggleText}} + name="token" + type={tokenType} + value={token} + onChange={changeToken} + /> + )}
); + // A dialog over the shell, as About is: nothing behind it works until the backend accepts the credentials. return ( -
{ - event.preventDefault(); - view.submit(); - }} - > -

{view.title}

- {view.kind === null ? ( - - ) : ( - <> - {view.note} - {view.alert && ( - - {view.alert.text} - - )} - {view.kind === 'token' ? ( - - ) : ( + +
+ + + doona + +

{view.title}

+
+ { + event.preventDefault(); + view.submit(); + }} + > + {view.kind === null ? ( + view.discoveryError ? ( <> + +
+ + {t('login.settings')} + +
+ + ) : ( + + ) + ) : ( + <> + {view.note && {view.note}} + {view.alert && ( + + {view.alert.text} + + )} + {view.kind === 'token' ? ( - - {view.kind === 'setup' && ( + ) : ( + <> - )} - - )} -
- - - {t('login.settings')} - -
- - )} - + + {view.kind === 'setup' && ( + + )} + + )} +
+ + + {t('login.settings')} + +
+ + )} + +
); } diff --git a/src/shell/messages.ts b/src/shell/messages.ts index f8c78cd4..7f2e36d0 100644 --- a/src/shell/messages.ts +++ b/src/shell/messages.ts @@ -18,27 +18,27 @@ export const messages = defineMessages({ 'nav.config': '組態', 'nav.nodes': '節點', 'nav.logs': '日誌', - 'login.title': '需要 token', - 'login.note': '{backend} 要求提供 Bearer token;token 僅儲存於此瀏覽器,並隨每個請求的 Authorization 標頭送出。', + 'login.title': '需要 Token', + 'login.note': '{backend} 要求提供 Bearer Token;Token 僅儲存於此瀏覽器,並隨每個請求的 Authorization 標頭送出。', 'login.token': 'Token', 'login.submit': '連線', 'login.settings': '變更後端網址', - 'login.rejected': '後端拒絕了已儲存的 token;請輸入新的 token。', - 'login.stale': '設定檔已變更,token 未儲存。請重新載入頁面,確認後端網址後再連線。', + 'login.rejected': '後端拒絕了已儲存的 Token;請輸入新的 Token。', + 'login.stale': '設定檔已變更,Token 未儲存。請重新載入頁面,確認後端網址後再連線。', 'login.setupTitle': '建立管理員', 'login.passwordTitle': '登入', 'login.setupNote': '{backend} 尚未設定管理員。建立帳號後即登入;後端只接受來自本機、私有網路或鏈路本地位址的建立請求。', - 'login.passwordNote': '使用 {backend} 的管理員帳號登入。工作階段只保存在此分頁,關閉分頁即失效。', 'login.username': '使用者名稱', 'login.password': '密碼', 'login.confirm': '確認密碼', - 'login.passwordRule': '12 至 128 個字元。', + 'login.passwordRule': '8 至 128 個字元。', 'login.create': '建立並登入', 'login.signIn': '登入', 'login.showPassword': '顯示密碼', 'login.hidePassword': '隱藏密碼', 'login.badUsername': '使用者名稱只能包含英文字母、數字、底線、句點與連字號,長度為 1 至 64。', - 'login.badPassword': '密碼長度須為 12 至 128 個字元。', + 'login.passwordShort': '密碼少於 8 個字元。', + 'login.passwordLong': '密碼超過 128 個字元。', 'login.mismatch': '兩次輸入的密碼不一致。', 'login.invalidCredentials': '使用者名稱或密碼錯誤。', 'login.needsSetup': '後端尚未設定管理員,請先建立帳號。', @@ -139,27 +139,27 @@ export const messages = defineMessages({ 'nav.config': '配置', 'nav.nodes': '节点', 'nav.logs': '日志', - 'login.title': '需要 token', - 'login.note': '{backend} 要求提供 Bearer token;token 仅保存在此浏览器中,并随每个请求的 Authorization 请求头发送。', + 'login.title': '需要 Token', + 'login.note': '{backend} 要求提供 Bearer Token;Token 仅保存在此浏览器中,并随每个请求的 Authorization 请求头发送。', 'login.token': 'Token', 'login.submit': '连接', 'login.settings': '更改后端网址', - 'login.rejected': '后端拒绝了已保存的 token;请输入新的 token。', - 'login.stale': '连接方案已更改,token 未保存。请重新加载页面,确认后端网址后再连接。', + 'login.rejected': '后端拒绝了已保存的 Token;请输入新的 Token。', + 'login.stale': '连接方案已更改,Token 未保存。请重新加载页面,确认后端网址后再连接。', 'login.setupTitle': '创建管理员', 'login.passwordTitle': '登录', 'login.setupNote': '{backend} 尚未设置管理员。创建账号后即登录;后端只接受来自本机、私有网络或链路本地地址的创建请求。', - 'login.passwordNote': '使用 {backend} 的管理员账号登录。会话只保存在此标签页,关闭标签页即失效。', 'login.username': '用户名', 'login.password': '密码', 'login.confirm': '确认密码', - 'login.passwordRule': '12 至 128 个字符。', + 'login.passwordRule': '8 至 128 个字符。', 'login.create': '创建并登录', 'login.signIn': '登录', 'login.showPassword': '显示密码', 'login.hidePassword': '隐藏密码', 'login.badUsername': '用户名只能包含英文字母、数字、下划线、句点和连字符,长度为 1 至 64。', - 'login.badPassword': '密码长度须为 12 至 128 个字符。', + 'login.passwordShort': '密码少于 8 个字符。', + 'login.passwordLong': '密码超过 128 个字符。', 'login.mismatch': '两次输入的密码不一致。', 'login.invalidCredentials': '用户名或密码错误。', 'login.needsSetup': '后端尚未设置管理员,请先创建账号。', @@ -271,17 +271,17 @@ export const messages = defineMessages({ 'login.passwordTitle': 'Sign in', 'login.setupNote': '{backend} has no administrator yet. Creating one signs you in; the backend accepts this only from loopback, private or link-local addresses.', - 'login.passwordNote': 'Sign in with the administrator account of {backend}. The session is kept only in this tab and ends when the tab closes.', 'login.username': 'Username', 'login.password': 'Password', 'login.confirm': 'Confirm password', - 'login.passwordRule': '12 to 128 characters.', + 'login.passwordRule': '8 to 128 characters.', 'login.create': 'Create and sign in', 'login.signIn': 'Sign in', 'login.showPassword': 'Show password', 'login.hidePassword': 'Hide password', 'login.badUsername': 'The username may contain only letters, digits, underscores, periods and hyphens, 1 to 64 characters.', - 'login.badPassword': 'The password must be 12 to 128 characters long.', + 'login.passwordShort': 'The password is shorter than 8 characters.', + 'login.passwordLong': 'The password is longer than 128 characters.', 'login.mismatch': 'The passwords do not match.', 'login.invalidCredentials': 'The username or password is incorrect.', 'login.needsSetup': 'The backend has no administrator yet; create one first.', diff --git a/src/shell/useLogin.test.ts b/src/shell/useLogin.test.ts index f49c1139..8422b408 100644 --- a/src/shell/useLogin.test.ts +++ b/src/shell/useLogin.test.ts @@ -1,5 +1,5 @@ import {expect, it} from 'vitest'; -import {credentialProblems, loginProfiles, signInRefusal} from './useLogin'; +import {credentialProblems, loginProfiles, predatesAuth, signInRefusal} from './useLogin'; import {ApiError} from '../api/error'; import {signInKind} from '../api/auth'; @@ -21,9 +21,11 @@ it('updates only the challenged endpoint, preserving concurrent profile changes' it('checks credentials against the backend limits before any attempt, per field', () => { expect(credentialProblems('login', 'admin', 'correct horse battery', '')).toEqual({}); - expect(credentialProblems('login', 'ad min', 'short', '')).toEqual({username: 'login.badUsername', password: 'login.badPassword'}); - // Twelve scalar values, not twelve UTF-16 units: an emoji counts once. - expect(credentialProblems('login', 'admin', '😀'.repeat(12), '')).toEqual({}); + expect(credentialProblems('login', 'ad min', 'short', '')).toEqual({username: 'login.badUsername', password: 'login.passwordShort'}); + // Eight scalar values, not eight UTF-16 units: an emoji counts once. + expect(credentialProblems('login', 'admin', '😀'.repeat(8), '')).toEqual({}); + expect(credentialProblems('login', 'admin', '😀'.repeat(7), '')).toEqual({password: 'login.passwordShort'}); + expect(credentialProblems('login', 'admin', 'x'.repeat(129), '')).toEqual({password: 'login.passwordLong'}); expect(credentialProblems('setup', 'admin', 'correct horse battery', 'correct horse batterx')).toEqual({confirm: 'login.mismatch'}); }); @@ -37,3 +39,13 @@ it('maps refusals by code and follows a moved account state', () => { expect(signInKind({mode: 'password', setup_required: true, anonymous_loopback: false})).toBe('setup'); expect(signInKind({mode: 'password', setup_required: false, anonymous_loopback: false})).toBe('login'); }); + +it('takes only a missing or protected discovery for a backend that predates password login', () => { + expect(predatesAuth(new ApiError(404, 'not_found', 'Not found'))).toBe(true); + expect(predatesAuth(new ApiError(401, 'authentication_required', 'Token required'))).toBe(true); + expect(predatesAuth(new SyntaxError('Unexpected token <'))).toBe(true); + // A backend that cannot be reached or fails says nothing about its sign-in; the page asks to retry instead. + expect(predatesAuth(new ApiError(0, 'network_error', 'Failed to fetch'))).toBe(false); + expect(predatesAuth(new ApiError(502, '', 'Bad Gateway'))).toBe(false); + expect(predatesAuth(new TypeError('Failed to fetch'))).toBe(false); +}); diff --git a/src/shell/useLogin.ts b/src/shell/useLogin.ts index 21f04f82..586dd2d8 100644 --- a/src/shell/useLogin.ts +++ b/src/shell/useLogin.ts @@ -18,7 +18,8 @@ export function credentialProblems(kind: 'setup' | 'login', username: string, pa const problems: Partial> = {}; if (!USERNAME.test(username)) problems.username = 'login.badUsername'; const length = [...password].length; - if (length < 12 || length > 128 || new TextEncoder().encode(password).length > 512) problems.password = 'login.badPassword'; + if (length < 8) problems.password = 'login.passwordShort'; + else if (length > 128 || new TextEncoder().encode(password).length > 512) problems.password = 'login.passwordLong'; else if (kind === 'setup' && password !== confirm) problems.confirm = 'login.mismatch'; return problems; } @@ -35,23 +36,32 @@ export function signInRefusal(error: unknown): Refusal | null { return null; } +// A backend without discovery (404), one that guards it (401, 403) or a host answering with something other than JSON +// predates password login and takes a token. A network or server failure says nothing about the backend's sign-in. +export function predatesAuth(error: unknown): boolean { + if (error instanceof SyntaxError) return true; + return error instanceof ApiError && (error.status === 404 || error.status === 401 || error.status === 403); +} + export function useLogin(profileId: string, api: string, backend: string, rejected: boolean) { const t = useT(); // A session this tab held and the backend no longer accepts has ended; it is dropped before asking again. // endSession is idempotent for the page load, so running it in the initializer is safe under StrictMode. const [ended] = useState(() => endSession(profileId, api)); const [kind, setKind] = useState(null); + const [discovery, setDiscovery] = useState<{attempt: number; error: Error | null}>({attempt: 0, error: null}); useEffect(() => { const controller = new AbortController(); discoverAuth(api, controller.signal).then( auth => setKind(signInKind(auth)), - () => { - // Without discovery the backend is treated as one that predates password login. - if (!controller.signal.aborted) setKind('token'); + (error: unknown) => { + if (controller.signal.aborted) return; + if (predatesAuth(error)) setKind('token'); + else setDiscovery(state => ({...state, error: error instanceof Error ? error : new Error(String(error))})); } ); return () => controller.abort(); - }, [api]); + }, [api, discovery.attempt]); const [token, setToken] = useState(''); const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); @@ -114,8 +124,10 @@ export function useLogin(profileId: string, api: string, backend: string, reject const fieldError = (field: Field) => (problems[field] ? t(problems[field]) : undefined); return { kind, - title: t(kind === 'setup' ? 'login.setupTitle' : kind === 'login' ? 'login.passwordTitle' : 'login.title'), - note: kind === 'setup' ? t('login.setupNote', {backend}) : kind === 'login' ? t('login.passwordNote', {backend}) : t('login.note', {backend}), + discoveryError: discovery.error, + retryDiscovery: () => setDiscovery(state => ({attempt: state.attempt + 1, error: null})), + title: t(kind === 'setup' ? 'login.setupTitle' : kind === 'token' ? 'login.title' : 'login.passwordTitle'), + note: kind === 'setup' ? t('login.setupNote', {backend}) : kind === 'login' ? null : t('login.note', {backend}), alert, busy, token, diff --git a/src/shell/useShellController.ts b/src/shell/useShellController.ts index 24675f72..cdc6d5cf 100644 --- a/src/shell/useShellController.ts +++ b/src/shell/useShellController.ts @@ -83,7 +83,7 @@ export function useShellController(initial: Lang) { useEffect(warmAllPages, []); // react-aria tracks elements with a running CSS transition until transitionend or transitioncancel, which a removed // element never receives, so a page left mid-transition would keep its detached tree. runAfterTransition drops - // disconnected entries first. + // disconnected entries first. It is a private export: react-aria is pinned, so recheck this path on upgrade. useEffect(() => { runAfterTransition(() => {}); }, [route]); diff --git a/src/shell/view.test.ts b/src/shell/view.test.ts index a5e2ee3f..25757f5a 100644 --- a/src/shell/view.test.ts +++ b/src/shell/view.test.ts @@ -43,4 +43,6 @@ it('surfaces discovery failures and suppresses authentication only on the login const auth = new ApiError(401, 'authentication_required', 'Token required'); expect(shellView(settings, 'config', undefined, auth, undefined, versionError, t).error).toBe(versionError); expect(shellView(settings, 'settings', undefined, auth, undefined, null, t).error).toBe(auth); + // Before sign-in the version read is refused too; the login surface shows no error banner for it. + expect(shellView(settings, 'config', undefined, auth, undefined, auth, t).error).toBeNull(); }); diff --git a/src/shell/view.ts b/src/shell/view.ts index c3901730..73a0a040 100644 --- a/src/shell/view.ts +++ b/src/shell/view.ts @@ -78,7 +78,8 @@ export function shellView( : [] ) })); - const needsToken = capabilityError instanceof ApiError && (capabilityError.status === 401 || capabilityError.status === 403); + const refused = (error: Error | null) => error instanceof ApiError && (error.status === 401 || error.status === 403); + const needsToken = refused(capabilityError); const content: ShellView['content'] = needsToken && feature.id !== 'settings' ? {kind: 'login', profileId: profile?.id ?? '', api: profile?.api ?? '', backend: profile?.name ?? profile?.api ?? '', rejected: !!profile?.token} @@ -109,7 +110,8 @@ export function shellView( }, content, busy: !capabilities && !capabilityError, - error: (content.kind === 'login' ? null : capabilityError) ?? versionError, + // The login surface explains a refused credential itself; the version read is refused the same way before sign-in. + error: content.kind === 'login' ? (refused(versionError) ? null : versionError) : (capabilityError ?? versionError), engine: {text: engineText, href: version ? `${org}/${version.engine.name}` : org}, shortcuts, shortcutPaths: Object.fromEntries(shortcuts.map(item => [item.key, item.path])), diff --git a/src/store/connections.ts b/src/store/connections.ts index e22dbb1e..0b7b4aaf 100644 --- a/src/store/connections.ts +++ b/src/store/connections.ts @@ -4,10 +4,14 @@ import type {BulkCloseQuery, BulkCloseResult} from '../api/model'; import {ApiError} from '../api/error'; import {useResource} from './resource'; import {useAction} from './action'; -export function useConnections(src?: string, enabled = true, paused = false) { +export function useConnections(src?: string, enabled = true, paused = false, every?: number) { const api = getApi(); return useResource( - {key: ['connections', {src}], fetch: signal => api.connections({type: 'all', detail: 'full', limit: 1000, src}, signal)}, + { + key: ['connections', {src}], + every, + fetch: signal => api.connections({type: 'all', detail: 'full', limit: 1000, src}, signal) + }, {enabled, paused} ); } diff --git a/src/store/nodes.ts b/src/store/nodes.ts index 17b9b0ca..4f998c69 100644 --- a/src/store/nodes.ts +++ b/src/store/nodes.ts @@ -30,6 +30,7 @@ export function useProviders(enabled = true) { return useResource( { key: ['providers', {limit}], + every: 30000, fetch: signal => walk( cursor => api.providers({cursor, limit}, signal), diff --git a/src/store/runtime.ts b/src/store/runtime.ts index a961873f..489d3436 100644 --- a/src/store/runtime.ts +++ b/src/store/runtime.ts @@ -17,28 +17,29 @@ export function useRuntimeOutbounds(enabled: boolean) { return useResource({key: ['runtimeOutbounds'], fetch: signal => api.runtimeOutbounds(signal)}, {enabled}); } // The backend's ring, asked for the chart's window (or as much of it as the backend keeps) at its full -// resolution: the live window wants every second the backend has. +// resolution: the live window wants every second the backend has. The runtime poll extends it between the +// once-a-minute refreshes, and a range change or reconnect fetches it again. export function useTrafficHistory(windowSeconds: number, capabilities: Capabilities | undefined) { const api = getApi(); const limits = capabilities?.resources.traffic_history; const window_seconds = Math.min(windowSeconds, limits?.max_window_seconds ?? 600); const max_points = Math.min(600, limits?.max_points ?? 600); return useResource( - {key: ['trafficHistory', {window_seconds, max_points}], fetch: signal => api.trafficHistory({window_seconds, max_points}, signal)}, + {key: ['trafficHistory', {window_seconds, max_points}], every: 60000, fetch: signal => api.trafficHistory({window_seconds, max_points}, signal)}, { enabled: limits?.available === true } ); } -// The backend's memory ring over ten minutes at the recorder cadence; the chart merges it with the session's own -// samples (useMemorySamples). +// The backend's memory ring over ten minutes at the recorder cadence, refreshed once a minute; the chart merges it +// with the session's own samples (useMemorySamples). export function useMemoryHistory(capabilities: Capabilities | undefined) { const api = getApi(); const limits = capabilities?.resources.memory_history; const window_seconds = Math.min(600, limits?.max_window_seconds ?? 600); const max_points = Math.min(120, limits?.max_points ?? 120); return useResource( - {key: ['memoryHistory', {window_seconds, max_points}], fetch: signal => api.memoryHistory({window_seconds, max_points}, signal)}, + {key: ['memoryHistory', {window_seconds, max_points}], every: 60000, fetch: signal => api.memoryHistory({window_seconds, max_points}, signal)}, {enabled: limits?.available === true} ); } diff --git a/src/ui/Dialog.tsx b/src/ui/Dialog.tsx index 9e167b86..61dad8fb 100644 --- a/src/ui/Dialog.tsx +++ b/src/ui/Dialog.tsx @@ -56,7 +56,8 @@ export function ModalDialog({ alert, isOpen, onOpenChange, - hideTitle + hideTitle, + locked }: { trigger?: ReactElement; title: string; @@ -67,9 +68,11 @@ export function ModalDialog({ isOpen?: boolean; onOpenChange?: (open: boolean) => void; hideTitle?: boolean; + // Neither the underlay nor Escape closes it: the app behind cannot be used until the dialog is done. + locked?: boolean; }) { const modal = ( - + {({close}) => ( @@ -286,6 +289,9 @@ export function DetailPanel({open, title, onClose, children}: {open: boolean; ti const t = useT(); const wide = useMediaQuery(panelQuery); const showing = useContext(TabShown) && open; + // Shown before in this opening: a kept tab coming back brings its drawer back as it was, without the entrance. + const [was, setWas] = useState({showing, open, seen: false}); + if (was.showing !== showing || was.open !== open) setWas({showing, open, seen: open && (was.seen || was.showing)}); useEffect(() => { if (!showing || !wide) return; const on = (e: KeyboardEvent) => { @@ -312,7 +318,7 @@ export function DetailPanel({open, title, onClose, children}: {open: boolean; ti ); return ( - !o && onClose()}> + !o && onClose()}> {head} diff --git a/src/ui/Fields.tsx b/src/ui/Fields.tsx index 93f340c2..e6f7a511 100644 --- a/src/ui/Fields.tsx +++ b/src/ui/Fields.tsx @@ -142,7 +142,7 @@ export function TextField({ {description} )} - {error && {error}} + {error && {error}} ); } diff --git a/src/ui/Table.tsx b/src/ui/Table.tsx index 31019450..ee3c1495 100644 --- a/src/ui/Table.tsx +++ b/src/ui/Table.tsx @@ -111,9 +111,10 @@ export function fitColumns({ sort, onSort, getTextValue, - stream + stream, + fit }: { label: string; cols: TableColumn[]; @@ -154,13 +156,15 @@ export function DataTable({ getTextValue?: (row: T) => string; // Rows arrive continuously (logs, events): virtualised from the start rather than on crossing a threshold. stream?: boolean; + // A list of a few rows (sources, data files): no full-height placeholder while it loads. + fit?: boolean; }) { const t = useT(); // One set per selected key, so the table neither recomputes its selection nor re-renders every row. const keys: Selection = useMemo(() => (selected ? new Set([selected]) : new Set()), [selected]); const [ref, width] = useContentWidth(); const shown = useMemo(() => fitColumns(cols, width), [cols, width]); - const fitted = useTableHeight(height, rows.length, loading); + const fitted = useTableHeight(height, rows.length, loading, fit); const [virtual, setVirtual] = useState(stream || rows.length >= virtualiseFrom); if (!virtual && rows.length >= virtualiseFrom) setVirtual(true); const at = reveal && selected ? rows.findIndex(r => r.id === selected) : -1; diff --git a/src/ui/charts/Recharts.tsx b/src/ui/charts/Recharts.tsx index 5cd6cfa3..1e0585f9 100644 --- a/src/ui/charts/Recharts.tsx +++ b/src/ui/charts/Recharts.tsx @@ -103,6 +103,7 @@ const LazyAreaChart = lazy(() => // Rates start at zero; a level such as memory zooms to its own range so small movements stay visible. baseline?: 'zero' | 'auto'; }) { + const t = useT(); const p = usePalette(); const style = useChartStyle(p); const uid = useId(); @@ -194,6 +195,7 @@ const LazyAreaChart = lazy(() => itemStyle={style.item} labelFormatter={value => localTimeFormat(locale).format(Number(value))} formatter={v => fmt(Number(v))} + separator={t('ui.labelSeparator')} cursor={style.cursor} /> {series.map((s, k) => ( @@ -356,6 +358,7 @@ const LazyDonut = lazy(() => active={hover.inside ? undefined : false} contentStyle={style.content} itemStyle={style.item} + separator={t('ui.labelSeparator')} formatter={(v, name, item) => { const payload: unknown = item.payload; const bytes = payload && typeof payload === 'object' && 'text' in payload && typeof payload.text === 'string' ? payload.text : ''; diff --git a/src/ui/messages.ts b/src/ui/messages.ts index 26ea14c7..78705ce0 100644 --- a/src/ui/messages.ts +++ b/src/ui/messages.ts @@ -40,12 +40,14 @@ export const messages = defineMessages({ 'ui.all': '全部', 'ui.allCount': '全部 {n}', 'ui.errNoJson': '後端回應沒有 JSON 內容。', + 'ui.errNetwork': '無法連線至後端。', 'ui.errOtherOrigin': '操作位址屬於其他來源,已拒絕讀取。', 'ui.errNoStream': '後端回應沒有事件串流。', 'ui.errTraceLimits': '此後端不提供路由追蹤的位址上限', 'ui.errTooManyAddresses': 'DNS 傳回超過 {limit} 個不同位址。請縮小查詢範圍後再模擬。', 'ui.errGenerationChanged': '模擬期間路由組態已變更。請重新查詢。', 'ui.listSeparator': '、', + 'ui.labelSeparator': ':', 'ui.filter': '篩選', 'ui.clearFilters': '清除篩選', 'ui.loading': '載入中…', @@ -149,12 +151,14 @@ export const messages = defineMessages({ 'ui.all': '全部', 'ui.allCount': '全部 {n}', 'ui.errNoJson': '后端响应没有 JSON 内容。', + 'ui.errNetwork': '无法连接到后端。', 'ui.errOtherOrigin': '操作地址属于其他来源,已拒绝读取。', 'ui.errNoStream': '后端响应没有事件流。', 'ui.errTraceLimits': '此后端不提供路由追踪的地址上限', 'ui.errTooManyAddresses': 'DNS 返回超过 {limit} 个不同地址。请缩小查询范围后再模拟。', 'ui.errGenerationChanged': '模拟期间路由配置已变更。请重新查询。', 'ui.listSeparator': '、', + 'ui.labelSeparator': ':', 'ui.filter': '筛选', 'ui.clearFilters': '清除筛选', 'ui.loading': '加载中…', @@ -258,12 +262,14 @@ export const messages = defineMessages({ 'ui.all': 'All', 'ui.allCount': 'All {n}', 'ui.errNoJson': 'The backend response has no JSON body.', + 'ui.errNetwork': 'The backend could not be reached.', 'ui.errOtherOrigin': 'The operation address belongs to another origin and was not read.', 'ui.errNoStream': 'The backend response has no event stream.', 'ui.errTraceLimits': 'This backend does not provide routing trace address limits', 'ui.errTooManyAddresses': 'DNS returned more than {limit} distinct addresses. Narrow the query before simulating.', 'ui.errGenerationChanged': 'The routing changed during simulation. Run the query again.', 'ui.listSeparator': ', ', + 'ui.labelSeparator': ': ', 'ui.filter': 'Filter', 'ui.clearFilters': 'Clear filters', 'ui.loading': 'Loading…', diff --git a/src/ui/styles/cards-dashboard.css b/src/ui/styles/cards-dashboard.css index 844e65f9..e77f3a3e 100644 --- a/src/ui/styles/cards-dashboard.css +++ b/src/ui/styles/cards-dashboard.css @@ -72,7 +72,21 @@ overflow: hidden; } .rp-login { - max-width: 480px; + display: flex; + flex-direction: column; + gap: 12px; +} +.rp-login-brand { + display: flex; + flex-direction: column; + align-items: center; + gap: 8px; + font-size: 22px; + font-weight: 800; +} +.rp-login-brand img { + width: 56px; + height: 56px; } .rp-row { display: flex; @@ -115,6 +129,19 @@ grid-template-columns: 1fr; gap: 12px; } +/* A phone fits two tiles side by side; an odd last tile fills its row. */ +@media (min-width: 360px) and (max-width: 599.98px) { + .rp-strip { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + .rp-strip > :last-child:nth-child(odd) { + grid-column: 1 / -1; + } + /* A wide value keeps its room; the sparkline beside it narrows, down to nothing. */ + .rp-strip .rp-spark { + min-width: 0; + } +} /* An odd fifth tile fills its row until all five fit at 1280px. */ @media (min-width: 600px) { .rp-strip { diff --git a/src/ui/styles/fields.css b/src/ui/styles/fields.css index 61fd5159..ca36c950 100644 --- a/src/ui/styles/fields.css +++ b/src/ui/styles/fields.css @@ -50,6 +50,18 @@ .rp-toolbar.top > .rp-field-row { margin-top: 20px; } +/* S2 help text: an error reads in the negative tone at the hint's size, and the field it names takes a negative edge. */ +.rp-field-error { + font-size: 12px; + line-height: 16px; + color: var(--rp-negative-text); +} +:is(.rp-field, .rp-cluster)[data-invalid] .rp-input { + border-color: var(--rp-negative); +} +:is(.rp-field, .rp-cluster)[data-invalid] .rp-input:focus-within { + box-shadow: 0 0 0 1px var(--rp-negative); +} .rp-field > label, .rp-field .lbl { font-size: 12px; @@ -77,3 +89,21 @@ opacity: 0.4; cursor: default; } +/* On a phone a row of settings fields sits in two even columns instead of wrapping to ragged widths. */ +@media (max-width: 599.98px) { + .rp-toolbar.rp-fieldgrid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + align-items: start; + } + .rp-fieldgrid > * { + width: auto !important; + min-width: 0; + } + .rp-fieldgrid :is(.rp-input, .rp-selectbtn) { + width: 100%; + } + .rp-fieldgrid > .rp-label { + grid-column: 1 / -1; + } +} diff --git a/src/ui/styles/foundations.css b/src/ui/styles/foundations.css index b629ed05..eade04d1 100644 --- a/src/ui/styles/foundations.css +++ b/src/ui/styles/foundations.css @@ -80,8 +80,9 @@ body { sans-serif; -webkit-font-smoothing: antialiased; } -/* Simplified Chinese prefers the SC glyph forms; the TC face still fills in anything SC lacks. The other languages - leave SC out, so after zh-CN they render as they do after a reload, when the SC faces are not declared. */ +/* Simplified Chinese prefers the SC glyph forms; anything SC lacks falls to the TC faces declared so far, then the + system font. The other languages leave SC out, so after zh-CN they render as they do after a reload, when the SC + faces are not declared. */ :lang(zh-CN) body, body:lang(zh-CN) { font-family: 'Noto Sans SC', 'Noto Sans TC', system-ui, sans-serif; diff --git a/src/ui/styles/interaction-states.css b/src/ui/styles/interaction-states.css index 276b30df..8684de67 100644 --- a/src/ui/styles/interaction-states.css +++ b/src/ui/styles/interaction-states.css @@ -136,6 +136,12 @@ opacity: 0.5; cursor: default; } +/* Tiles, tags, the action bar and selected or group rows paint the overlay or the selected tint, where a palette's + subtle can fall under 4.5:1: secondary text inside them reads --rp-subtle-text. Names stay bold and secondary lines + smaller, so the order holds where that is body text. */ +:is(.rp-node, .rp-tree-tile, .rp-tag, .rp-actionbar, .rp-table [role='row']:is([data-selected], [data-disabled])) { + --rp-subtle: var(--rp-subtle-text); +} /* Group rows are headings, not disabled data: full-strength text on the overlay, the count muted. */ .rp-table [role='row'][data-disabled] { cursor: default; diff --git a/src/ui/styles/motion.css b/src/ui/styles/motion.css index d462bc6d..74b9eb96 100644 --- a/src/ui/styles/motion.css +++ b/src/ui/styles/motion.css @@ -84,6 +84,9 @@ --rp-notice-text: var(--rp-notice); --rp-positive-text: var(--rp-positive); --rp-info-text: var(--rp-info); + /* Secondary text on a tile, plain or selected. Where a palette's subtle is under 4.5:1 there, the palette sets body + text; page-level secondary text keeps reading --rp-subtle. */ + --rp-subtle-text: var(--rp-subtle); --rp-line: var(--rp-hl-low); --rp-ease: cubic-bezier(0.45, 0, 0.4, 1); --rp-ease-in: cubic-bezier(0.5, 0, 1, 1); diff --git a/src/ui/styles/nodes.css b/src/ui/styles/nodes.css index 924e84a1..127e9e09 100644 --- a/src/ui/styles/nodes.css +++ b/src/ui/styles/nodes.css @@ -59,6 +59,10 @@ button.rp-node[data-focus-visible] { overflow: auto; outline: none; border-radius: var(--rp-r-md); + /* The last visible row fades out, so a cut tile reads as more to scroll; the padding lets the final row scroll clear + of the fade. */ + padding-bottom: 24px; + mask-image: linear-gradient(to bottom, #000 calc(100% - 24px), transparent); } .rp-nodegrid .rp-node { cursor: default; diff --git a/src/ui/styles/palettes.css b/src/ui/styles/palettes.css index 62b7a231..2f8d1607 100644 --- a/src/ui/styles/palettes.css +++ b/src/ui/styles/palettes.css @@ -25,11 +25,15 @@ --rp-hl-high: #cecacd; --rp-shadow: 0 1px 2px rgba(87, 82, 121, 0.08); } -/* Dawn's love, gold and foam are under 4.5:1 as text. Glass shares the defaults above and keeps its own tones. */ +/* Dawn's love, gold and foam are under 4.5:1 as text, and pine is under it on a selected tile. Subtle is under 4.5:1 on + the tiles of every Rosé Pine flavour. Glass shares the defaults above and keeps its own tones. */ :root[data-family='rose-pine'] { + --rp-accent-text: var(--rp-text); --rp-negative-text: var(--rp-text); --rp-notice-text: var(--rp-text); --rp-positive-text: var(--rp-text); + --rp-info-text: var(--rp-text); + --rp-subtle-text: var(--rp-text); } :root[data-family='rose-pine'][data-scheme='dark'], :root[data-flavour='moon'][data-scheme='dark'] { @@ -60,7 +64,8 @@ /* Pine is under 4.5:1 as text here and under pale text on it; Main's base reads on it. */ --rp-on-accent: #191724; --rp-accent-text: var(--rp-text); - --rp-negative-text: var(--rp-negative); + /* Love is under 4.5:1 on Moon's tiles. */ + --rp-negative-text: var(--rp-text); --rp-notice-text: var(--rp-notice); --rp-positive-text: var(--rp-positive); --rp-info-text: var(--rp-text); @@ -96,6 +101,7 @@ --rp-notice-text: var(--rp-text); --rp-positive-text: var(--rp-text); --rp-info-text: var(--rp-text); + --rp-subtle-text: var(--rp-text); } :root[data-family='catppuccin'][data-scheme='dark'], :root[data-flavour='mocha'][data-scheme='dark'] { @@ -125,10 +131,12 @@ --rp-shadow: 0 1px 2px rgba(0, 0, 0, 0.35); --rp-on-accent: var(--rp-surface); --rp-accent-text: var(--rp-accent); - --rp-negative-text: var(--rp-negative); + /* Red is under 4.5:1 on a selected tile in every dark flavour. */ + --rp-negative-text: var(--rp-text); --rp-notice-text: var(--rp-notice); --rp-positive-text: var(--rp-positive); --rp-info-text: var(--rp-info); + --rp-subtle-text: var(--rp-subtle); } :root[data-family='nord'] { /* Nord ships no light theme: Snow Storm as surfaces, Polar Night as text; mixed steps are blends of official @@ -190,8 +198,8 @@ --rp-hl-high: #4c566a; --rp-shadow: 0 1px 2px rgba(0, 0, 0, 0.3); --rp-on-accent: var(--rp-base); + /* Green is under 4.5:1 on a tile, so only yellow keeps its colour. */ --rp-notice-text: var(--rp-notice); - --rp-positive-text: var(--rp-positive); } :root[data-family='kary'] { /* Kary Pro has few official roles: map editor background to cards, line highlight to pages, selection to overlays, @@ -223,6 +231,7 @@ --rp-on-accent: #ffffff; --rp-accent-text: var(--rp-text); --rp-info-text: var(--rp-text); + --rp-subtle-text: var(--rp-text); } :root[data-family='kary'][data-scheme='dark'] { --rp-base: #1a1a1a; @@ -250,8 +259,12 @@ --rp-hl-high: #474747; --rp-shadow: 0 1px 2px rgba(0, 0, 0, 0.3); --rp-on-accent: var(--rp-surface); - --rp-accent-text: var(--rp-accent); - --rp-info-text: var(--rp-info); + /* Every tone is under 4.5:1 on the grey overlay. */ + --rp-accent-text: var(--rp-text); + --rp-negative-text: var(--rp-text); + --rp-notice-text: var(--rp-text); + --rp-positive-text: var(--rp-text); + --rp-info-text: var(--rp-text); } :root[data-flavour='main'][data-scheme='dark'] { --rp-base: #191724; @@ -279,6 +292,7 @@ --rp-hl-high: #524f67; --rp-shadow: 0 1px 2px rgba(0, 0, 0, 0.35); --rp-on-accent: #ffffff; + --rp-negative-text: var(--rp-negative); } :root[data-flavour='frappe'][data-scheme='dark'] { --rp-base: #292c3c; @@ -305,6 +319,11 @@ --rp-hl-med: #51576d; --rp-hl-high: #626880; --rp-shadow: 0 1px 2px rgba(0, 0, 0, 0.3); + /* Blue, green and subtle are under 4.5:1 on Frappé's tiles. */ + --rp-accent-text: var(--rp-text); + --rp-positive-text: var(--rp-text); + --rp-info-text: var(--rp-text); + --rp-subtle-text: var(--rp-text); } :root[data-flavour='macchiato'][data-scheme='dark'] { --rp-base: #1e2030; @@ -331,6 +350,10 @@ --rp-hl-med: #494d64; --rp-hl-high: #5b6078; --rp-shadow: 0 1px 2px rgba(0, 0, 0, 0.35); + /* Blue and subtle are under 4.5:1 on Macchiato's selected tile. */ + --rp-accent-text: var(--rp-text); + --rp-info-text: var(--rp-text); + --rp-subtle-text: var(--rp-text); } /* Ant Design 5 tokens use its default/dark algorithms, palette step 6, and G2's qualitative chart colours. */ @@ -367,6 +390,7 @@ --rp-notice-text: var(--rp-text); --rp-positive-text: var(--rp-text); --rp-info-text: var(--rp-text); + --rp-subtle-text: var(--rp-text); } :root[data-family='antd'][data-scheme='dark'] { --rp-base: #000000; @@ -428,9 +452,12 @@ --rp-on-text: #ffffff; --rp-line: #e5e6eb; --rp-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); + --rp-accent-text: var(--rp-text); --rp-negative-text: var(--rp-text); --rp-notice-text: var(--rp-text); --rp-positive-text: var(--rp-text); + --rp-info-text: var(--rp-text); + --rp-subtle-text: var(--rp-text); } :root[data-family='arco'][data-scheme='dark'] { --rp-base: #17171a; @@ -461,7 +488,8 @@ --rp-line: #333335; --rp-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); --rp-accent-text: var(--rp-text); - --rp-negative-text: var(--rp-negative); + /* Red is under 4.5:1 on a tile. */ + --rp-negative-text: var(--rp-text); --rp-notice-text: var(--rp-notice); --rp-positive-text: var(--rp-positive); --rp-info-text: var(--rp-text); @@ -495,9 +523,12 @@ --rp-on-text: #ffffff; --rp-line: rgba(28, 31, 35, 0.08); --rp-shadow: 0 0 1px rgba(0, 0, 0, 0.3), 0 4px 14px rgba(0, 0, 0, 0.1); + --rp-accent-text: var(--rp-text); --rp-negative-text: var(--rp-text); --rp-notice-text: var(--rp-text); --rp-positive-text: var(--rp-text); + --rp-info-text: var(--rp-text); + --rp-subtle-text: var(--rp-text); } :root[data-family='semi'][data-scheme='dark'] { --rp-base: #16161a; @@ -527,7 +558,6 @@ --rp-on-text: #16161a; --rp-line: rgba(255, 255, 255, 0.08); --rp-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.1), 0 4px 14px rgba(0, 0, 0, 0.25); - --rp-negative-text: var(--rp-negative); + /* Red and green are under 4.5:1 on a tile, so only orange keeps its colour. */ --rp-notice-text: var(--rp-notice); - --rp-positive-text: var(--rp-positive); } diff --git a/src/ui/styles/tabs-panels.css b/src/ui/styles/tabs-panels.css index b58d9391..c9c04ab3 100644 --- a/src/ui/styles/tabs-panels.css +++ b/src/ui/styles/tabs-panels.css @@ -89,6 +89,10 @@ .rp-underlay[data-entering] .rp-modal.rp-drawer { animation: rp-drawer-in var(--rp-duration-modal-in) var(--rp-ease) both; } +.rp-underlay.still[data-entering], +.rp-underlay.still[data-entering] .rp-modal.rp-drawer { + animation: none; +} @keyframes rp-drawer-in { from { translate: 24px 0; diff --git a/tools/perf.mjs b/tools/perf.mjs index 665a26cd..927ca8d5 100644 --- a/tools/perf.mjs +++ b/tools/perf.mjs @@ -27,7 +27,7 @@ async function ready(page) { const content = { activity: '.rp-donut .recharts-sector', overview: '.rp-kv', - connections: '[role=rowheader]', + connections: '.rp-scatter circle', dns: '[role=tabpanel]', policies: '.rp-node', rules: '.rp-tree-tile',