Move the console onto ReUI PRO
Install ReUI (MCP, skill, @reui registry, Tailwind v4, shadcn base-nova) and move the shared UI onto it: Button, Tag, Check, Input/Textarea, Segmented, Alert, Panel, Dialog, Tooltip, Menu and Select (Popover), Toast (sonner), the Table frame (DataGrid), the Dashboard KPI strip, the shnt Ops palette, Geist and the type scale. Design only: behaviour, texts and roles are unchanged. Tests that asserted the old DOM were updated; the tests now format numbers in English wherever they run. docs/reui-migration-plan.md records the plan and its decisions. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
commit
f3531c64f9
680 files changed
+139836
No files matched your search
@@ -0,0 +1,113 @@
|
||||
/*
|
||||
The alert is FILLED, not just tinted at the border. Two treatments coexisted:
|
||||
this one, which only painted the border and the text, and Zones' local copy
|
||||
(`.note` + `.noteWarning`), with a background. The result was that the "Note!" in
|
||||
"Delete Cluster" weighed less than the same alert inside a zone modal. The filled
|
||||
one wins, which is what was drawn and what is seen on the first pass.
|
||||
*/
|
||||
|
||||
.alert {
|
||||
padding: var(--s-7) var(--s-8);
|
||||
border-radius: var(--r-3);
|
||||
font-size: var(--t-4);
|
||||
line-height: 1.6;
|
||||
border: 1px solid var(--line);
|
||||
background: var(--pan2);
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.alert b { display: inline; }
|
||||
|
||||
/* It measured 22×17: below the 24 target minimum. */
|
||||
.close {
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
min-width: 26px; min-height: 26px;
|
||||
float: right;
|
||||
background: none;
|
||||
border: 0;
|
||||
color: inherit;
|
||||
opacity: 0.6;
|
||||
font-size: var(--t-6);
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
padding: 0 0 0 var(--s-5);
|
||||
}
|
||||
|
||||
.close:hover { opacity: 1; }
|
||||
|
||||
/* The tones come from `ui/tones.module.css`, shared with the pill. */
|
||||
.success { composes: ok from './tones.module.css'; }
|
||||
.info { composes: info from './tones.module.css'; }
|
||||
.warning { composes: warn from './tones.module.css'; }
|
||||
.danger { composes: dan from './tones.module.css'; }
|
||||
|
||||
/*
|
||||
The `Note!` goes OUTLINED and the rest filled, and that is the only difference in
|
||||
treatment this file adds.
|
||||
|
||||
This file's header says a notice is filled, and that is still true for the three
|
||||
that ask for attention. That decision solved something else: that the SAME notice
|
||||
weighed differently on two screens. This one separates two DIFFERENT notices on
|
||||
one screen, which is the one the dense-form design asked for and the one that did not exist
|
||||
today. Measured: `notice-info` and `notice-warning` gave the same signature,
|
||||
`filled | no-icon | 8px | 15px from the panel`.
|
||||
|
||||
Only the `info` steps back, because it is the only one that explains rather than
|
||||
warns. The `warning` stays **filled and in `--warn`**: reassigning it to `--dan`
|
||||
would have made red mean two things, and `--dan` is reserved for the error, the
|
||||
validation and the destructive.
|
||||
|
||||
The tone still comes from `tones.module.css`: only the background is removed here,
|
||||
so the border and the text are still the shared pair's and no second blue is born.
|
||||
*/
|
||||
/*
|
||||
On light a whole paragraph in blue reads as a link, so the light theme sets
|
||||
`--note-ink` and the prose takes it, leaving `Note!` and the icon in blue. Dark
|
||||
does not set it, and its note stays blue throughout, as before.
|
||||
*/
|
||||
.alert.info { background: transparent; color: var(--note-ink, var(--info)); }
|
||||
.alert.info > b:first-of-type, .alert.info > .icon { color: var(--info); }
|
||||
|
||||
/*
|
||||
Two classes and not one, and the reason matters more than the rule.
|
||||
|
||||
The first version wrote `.info { background: transparent }` and **did nothing**.
|
||||
`composes` does not copy declarations: it adds the tone's class to the element, so
|
||||
there are two rules of ONE class each (this one and `tones.module.css`'s) with the
|
||||
same specificity, and the one the bundle emits later wins. It emitted the tone's:
|
||||
|
||||
._info_7n07s_40{background:0 0}
|
||||
._info_n8r8o_11{background:var(--info-bg); …}
|
||||
|
||||
With `.alert.info` it is two classes against one and the order stops deciding.
|
||||
|
||||
And what really has to be remembered: **the sweep caught this, not the review**.
|
||||
It was seen because the `notice-<type>` family now takes the fill in; with the
|
||||
previous signature (`borderRadius | inset`) this change would have come out green
|
||||
while being a no-op.
|
||||
*/
|
||||
|
||||
/*
|
||||
The icon, aligned with the first line of the text and not with the box: a
|
||||
six-hundred-character notice takes five lines, and an icon centred on that box
|
||||
floats in the middle of the paragraph.
|
||||
*/
|
||||
.icon {
|
||||
float: left;
|
||||
margin: 3px var(--s-3) 0 0;
|
||||
}
|
||||
|
||||
/*
|
||||
The air an alert leaves beneath it. It was written across eleven modules under
|
||||
three names (`.notice`, `.noticeGap` and `.alertSlot`) and produced four
|
||||
distances: 24 px in Zones and its modals, the lists screens, Administration, the
|
||||
Dashboard, DNS Client and Apps; 14 in DHCP, in Logs and on login; and 12 in the
|
||||
four account modals, where the alert sat loose and kept the container's `gap`.
|
||||
|
||||
The subtraction is the same one the section header does: in a `flex` container
|
||||
with `gap`, the child's margin ADDS to the gap, so 24 of margin inside a `gap` of
|
||||
14 gives 38. `--gap` is declared by `.screen` in `SectionHeader.module.css`
|
||||
and inherits; outside it does not exist and the fallback is 0, which is exactly
|
||||
what is needed.
|
||||
*/
|
||||
.gap { margin-bottom: calc(var(--gap-block) - var(--gap, 0px)); }
|
||||
@@ -0,0 +1,157 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { Alert } from './Alert'
|
||||
import { Note, Warning } from './PanelForm'
|
||||
|
||||
/* common.js:213-217: only success alerts dismiss themselves, and after 5 s. */
|
||||
|
||||
afterEach(() => vi.useRealTimers())
|
||||
|
||||
describe('self-dismissal of the alert', () => {
|
||||
it('a success dismisses itself after five seconds', () => {
|
||||
vi.useFakeTimers()
|
||||
const close = vi.fn()
|
||||
render(<Alert type="success" title="Saved!" onDismiss={close} />)
|
||||
|
||||
vi.advanceTimersByTime(4999)
|
||||
expect(close).not.toHaveBeenCalled()
|
||||
vi.advanceTimersByTime(1)
|
||||
expect(close).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('an error does NOT dismiss itself: the user has to read it', () => {
|
||||
vi.useFakeTimers()
|
||||
const close = vi.fn()
|
||||
render(<Alert type="danger" title="Error!" onDismiss={close} />)
|
||||
|
||||
vi.advanceTimersByTime(30000)
|
||||
expect(close).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('a success that cannot be closed does not go away by itself either', () => {
|
||||
vi.useFakeTimers()
|
||||
render(<Alert type="success" title="Saved!" />)
|
||||
vi.advanceTimersByTime(30000)
|
||||
expect(screen.getByRole('alert')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('a new alert restarts the clock', () => {
|
||||
vi.useFakeTimers()
|
||||
const close = vi.fn()
|
||||
const { rerender } = render(<Alert type="success" title="Saved!" onDismiss={close} />)
|
||||
|
||||
vi.advanceTimersByTime(4000)
|
||||
rerender(<Alert type="success" title="Flushed!" onDismiss={close} />)
|
||||
vi.advanceTimersByTime(4000)
|
||||
expect(close).not.toHaveBeenCalled()
|
||||
|
||||
vi.advanceTimersByTime(1000)
|
||||
expect(close).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
/*
|
||||
The difference between `Note!` and `Warning!`, and why it is tested here and not
|
||||
in `PanelForm`.
|
||||
|
||||
They are drawn by TWO routes (42 notices through the form kit's `Note`/`Warning`
|
||||
and 36 with `<Alert>` directly in the modals), so the treatment has to live where
|
||||
the two share code. These tests fix exactly that: that both routes come out the
|
||||
same.
|
||||
|
||||
What jsdom CANNOT answer, said so nobody reads more into it than there is: there is
|
||||
no CSS here, so **filled against outlined is not checked in these tests**. That is
|
||||
measured by `dev/uniformity.js` against the real page, with the `notice-<type>`
|
||||
family that takes the fill in precisely because the previous signature did not see
|
||||
it. The division is the usual one: the unit test watches structure and semantics,
|
||||
the sweep watches the treatment.
|
||||
*/
|
||||
describe('Note! against Warning!', () => {
|
||||
it('each type brings its icon, and it is decorative', () => {
|
||||
const { container, rerender } = render(
|
||||
<Alert type="info" title="Note!">
|
||||
text
|
||||
</Alert>,
|
||||
)
|
||||
const noteIcon = container.querySelector('svg')
|
||||
expect(noteIcon).toBeTruthy()
|
||||
expect(noteIcon).toHaveAttribute('aria-hidden', 'true')
|
||||
expect(noteIcon).toHaveAttribute('focusable', 'false')
|
||||
/* The STRING is kept, not the node: React reuses the same `svg` on
|
||||
re-render, so a live reference would end up compared with itself and the
|
||||
test would always pass. */
|
||||
const noteDrawing = noteIcon!.innerHTML
|
||||
|
||||
rerender(
|
||||
<Alert type="warning" title="Warning!">
|
||||
text
|
||||
</Alert>,
|
||||
)
|
||||
/* It is not the same drawing: if it were, the icon would tell nothing apart. */
|
||||
expect(container.querySelector('svg')!.innerHTML).not.toBe(noteDrawing)
|
||||
})
|
||||
|
||||
/*
|
||||
The icon must NOT replace or repeat the word. `Note!` and `Warning!` are
|
||||
upstream literals and they are still in the text.
|
||||
*/
|
||||
it('the icon does not touch the accessible text', () => {
|
||||
render(
|
||||
<Alert type="warning" title="Warning!">
|
||||
Enable IPv6 support only if this DNS Server has native IPv6 Internet access
|
||||
</Alert>,
|
||||
)
|
||||
const notice = screen.getByRole('alert')
|
||||
expect(notice).toHaveTextContent(
|
||||
'Warning! Enable IPv6 support only if this DNS Server has native IPv6 Internet access',
|
||||
)
|
||||
/* The svg adds no text: the accessible content is the same with and without it. */
|
||||
expect(notice.querySelector('svg')?.textContent).toBe('')
|
||||
})
|
||||
|
||||
it('it keeps the role, the title and the close button', () => {
|
||||
const onDismiss = vi.fn()
|
||||
render(
|
||||
<Alert type="info" title="Note!" onDismiss={onDismiss}>
|
||||
text
|
||||
</Alert>,
|
||||
)
|
||||
expect(screen.getByRole('alert')).toBeTruthy()
|
||||
expect(screen.getByRole('button', { name: 'Close' })).toBeTruthy()
|
||||
})
|
||||
|
||||
/*
|
||||
THE ONE THAT MATTERS: the two routes have to give the same thing. If `PanelForm`
|
||||
went back to treating its notices on its own, the same `Note!` would weigh
|
||||
differently in a panel and in a modal, which is the defect `Alert.module.css`'s
|
||||
header records having already fixed once.
|
||||
*/
|
||||
it('the PanelForm route and the direct Alert route draw the same', () => {
|
||||
const { container: viaKit } = render(<Note>text</Note>)
|
||||
const { container: viaAlert } = render(
|
||||
<Alert type="info" title="Note!">
|
||||
text
|
||||
</Alert>,
|
||||
)
|
||||
const a = viaKit.querySelector('[role=alert]')!
|
||||
const b = viaAlert.querySelector('[role=alert]')!
|
||||
|
||||
expect(a.className).toBe(b.className)
|
||||
expect(a.querySelector('svg')?.innerHTML).toBe(b.querySelector('svg')?.innerHTML)
|
||||
expect(a.textContent).toBe(b.textContent)
|
||||
})
|
||||
|
||||
it('and the same for Warning', () => {
|
||||
const { container: viaKit } = render(<Warning>text</Warning>)
|
||||
const { container: viaAlert } = render(
|
||||
<Alert type="warning" title="Warning!">
|
||||
text
|
||||
</Alert>,
|
||||
)
|
||||
const a = viaKit.querySelector('[role=alert]')!
|
||||
const b = viaAlert.querySelector('[role=alert]')!
|
||||
|
||||
expect(a.className).toBe(b.className)
|
||||
expect(a.querySelector('svg')?.innerHTML).toBe(b.querySelector('svg')?.innerHTML)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,93 @@
|
||||
import { useEffect, useRef, type ReactNode } from 'react'
|
||||
import { Icon, type IconName } from './Icon'
|
||||
import { Alert as ReuiAlert } from '@/components/reui/alert'
|
||||
|
||||
/*
|
||||
A replica of the old console's `showAlert` (common.js:202-217): a type, a bold
|
||||
title, the text after it and a "×" to dismiss it.
|
||||
|
||||
The "×" is not decoration: in upstream the alert can be closed, so removing it
|
||||
would be removing behaviour. It was caught by comparing side by side against the
|
||||
reference instance.
|
||||
|
||||
And **success alerts dismiss themselves after five seconds**, as they do there
|
||||
(`common.js:213-217`, `success` only). It was missing: it was a real behavioural
|
||||
difference, and a noticeable one, because a "Settings Saved!" that never goes away
|
||||
ends up covering the next alert.
|
||||
*/
|
||||
export type AlertType = 'success' | 'info' | 'warning' | 'danger'
|
||||
|
||||
/*
|
||||
The icon, by TYPE and not by the title.
|
||||
|
||||
The dense-form design asked for the difference between `Note!` and `Warning!` to be visible, and
|
||||
measuring showed that today **it is not**: the two `dev/uniformity.js` signatures
|
||||
came out identical (`filled | no-icon | 8px | 15px from the panel`) because only
|
||||
the tone told them apart, and the signature does not look at that.
|
||||
|
||||
It goes here and not in `PanelForm` because the two notices are drawn by TWO
|
||||
routes: 42 through the form kit's `Note`/`Warning`, and 36 with `<Alert>` directly
|
||||
in the Zones modals and the Settings dialogs. Handling it only in the kit would
|
||||
have made the same `Note!` weigh differently in a panel and in a modal, which is
|
||||
exactly the defect `Alert.module.css`'s header records having fixed.
|
||||
|
||||
`Icon` already comes out `aria-hidden` and `focusable="false"`, so the icon is
|
||||
decorative by construction: the word `Note!`/`Warning!` is still in the text and
|
||||
the icon neither repeats nor replaces it.
|
||||
*/
|
||||
const ICON_BY_TYPE: Record<AlertType, IconName> = {
|
||||
success: 'check',
|
||||
info: 'about',
|
||||
warning: 'warning',
|
||||
danger: 'warning',
|
||||
}
|
||||
|
||||
const VARIANT = { success: 'success', info: 'info', warning: 'warning', danger: 'destructive' } as const
|
||||
|
||||
const AUTO_DISMISS_MS = 5000
|
||||
|
||||
export function Alert({
|
||||
type,
|
||||
title,
|
||||
children,
|
||||
onDismiss,
|
||||
}: {
|
||||
type: AlertType
|
||||
title: string
|
||||
children?: ReactNode
|
||||
onDismiss?: () => void
|
||||
}) {
|
||||
// The dismiss callback is kept in a ref: the places that pass it write a new
|
||||
// function on every render, and as a dependency it would restart the timer
|
||||
// forever and never fire.
|
||||
const dismiss = useRef(onDismiss)
|
||||
dismiss.current = onDismiss
|
||||
|
||||
useEffect(() => {
|
||||
if (type !== 'success' || onDismiss == null) return
|
||||
const t = setTimeout(() => dismiss.current?.(), AUTO_DISMISS_MS)
|
||||
return () => clearTimeout(t)
|
||||
// The timer restarts with each new alert, even if the previous one was also
|
||||
// a success: that is what upstream does, since it rebuilds the whole node.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [type, title, children])
|
||||
|
||||
return (
|
||||
<ReuiAlert variant={VARIANT[type]} className="relative flex items-start gap-2.5 pr-9">
|
||||
<Icon name={ICON_BY_TYPE[type]} size={15} className="mt-0.5 shrink-0" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<b className="font-medium">{title}</b> {children}
|
||||
</div>
|
||||
{onDismiss && (
|
||||
<button
|
||||
type="button"
|
||||
className="absolute top-2 right-2 inline-flex size-6 border-0 bg-transparent items-center justify-center rounded-md text-muted-foreground transition-colors outline-none hover:bg-muted hover:text-foreground focus-visible:ring-3 focus-visible:ring-ring/50"
|
||||
aria-label="Close"
|
||||
onClick={onDismiss}
|
||||
>
|
||||
<Icon name="close" size={14} />
|
||||
</button>
|
||||
)}
|
||||
</ReuiAlert>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
Two sizes and three variants, and nothing else. Row actions used to use `.ib`
|
||||
(defined three times, with three different disabled opacities) on nine screens
|
||||
and the normal `Button` in DHCP, so the same action looked two different ways
|
||||
depending on the table.
|
||||
*/
|
||||
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--s-3);
|
||||
font-size: var(--t-4);
|
||||
/* The same height as the field and the dropdown it sits next to: it was 30 px,
|
||||
so "Go" and "Resolve" stood 4 px short of the row they belong to. */
|
||||
min-height: var(--field-height);
|
||||
padding: var(--s-4) var(--s-8);
|
||||
border-radius: var(--r-2);
|
||||
border: 1px solid var(--line);
|
||||
background: var(--shine-btn), var(--pan2);
|
||||
color: var(--ink);
|
||||
cursor: pointer;
|
||||
font-weight: 500;
|
||||
font-family: inherit;
|
||||
white-space: nowrap;
|
||||
box-shadow: var(--edge);
|
||||
transition: border-color var(--t-fast), background var(--t-fast);
|
||||
}
|
||||
|
||||
.btn:hover:not(:disabled) { border-color: var(--line-hover); }
|
||||
.btn:active:not(:disabled) { box-shadow: var(--sunken); }
|
||||
|
||||
.btn:disabled { opacity: 0.5; cursor: default; }
|
||||
.btn:focus-visible { outline: var(--focus); outline-offset: var(--focus-offset); }
|
||||
|
||||
/* The one in a table row: it does not compete with the row's data. */
|
||||
.sm {
|
||||
font-size: var(--t-3);
|
||||
font-weight: 400;
|
||||
padding: var(--s-3) var(--s-6);
|
||||
color: var(--mute);
|
||||
/* A row's button is not in a form row: it keeps its own size. */
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
/*
|
||||
Only for the small one WITHOUT a variant. `.sm:hover` is a class plus a
|
||||
pseudo-class, so it beat `.primary` (a class alone) and a small primary got
|
||||
lighter on hover: `--ink` text over the amber, 1.69:1. It was not seen until the
|
||||
console had its first `size="sm" variant="primary"`, on the "Show" of the
|
||||
Dashboard's custom range.
|
||||
*/
|
||||
.sm:not(.primary):not(.danger):hover:not(:disabled) { color: var(--ink); }
|
||||
|
||||
/* A button that stays pressed (the "Glue" and "RRSIG" filters) says so with the
|
||||
accent colour, not only with `aria-pressed`. */
|
||||
.btn[aria-pressed='true'] { color: var(--acc-ink); border-color: var(--acc-ink); }
|
||||
|
||||
/* The primary carries its own edge, stronger because amber takes more light. The
|
||||
text is dark and not white for a measured reason: white over `#f5a524` gives
|
||||
2.04:1 and does not even reach the large-text minimum; dark gives 9.09:1. */
|
||||
.primary {
|
||||
background: var(--shine-primary), var(--acc);
|
||||
border-color: var(--acc);
|
||||
color: var(--on-acc);
|
||||
font-weight: 550;
|
||||
box-shadow: var(--edge-strong);
|
||||
}
|
||||
|
||||
/*
|
||||
The primary's hover LIGHTENED by 6 %, and over `--acc` that gives 1.108:1, below
|
||||
the 1.20 this console settled on when fixing `--hover`, and the same order of
|
||||
magnitude as that defect. Lightening further does not fit: the red channel of
|
||||
`#f5a524` is already at 245 and saturates before reaching the threshold. It
|
||||
darkens instead, which is the only thing that gets there. And the
|
||||
`border-color: var(--acc)` goes, since that was what the button was already worth
|
||||
at rest: it did nothing.
|
||||
*/
|
||||
.primary:hover:not(:disabled) { filter: brightness(0.90); } /* 1.240:1 */
|
||||
|
||||
/*
|
||||
The destructive one is FILLED. It only tinted the border, so the "Delete" in
|
||||
"Delete Cluster" weighed the same as the "Close" beside it, while the "Add" of a
|
||||
harmless modal was a solid amber block: the most consequential button on the
|
||||
screen was the quietest, and this console has no undo anywhere.
|
||||
*/
|
||||
.danger {
|
||||
background: var(--shine-danger), var(--dan-fill);
|
||||
border-color: var(--dan);
|
||||
color: var(--on-dan);
|
||||
font-weight: 550;
|
||||
}
|
||||
|
||||
/*
|
||||
Not in a table ROW: there "Delete" repeats once per row and a red block per row
|
||||
turns the table into an alarm. It stays as red text, and the fill appears on hover
|
||||
and on keyboard focus.
|
||||
*/
|
||||
.sm.danger {
|
||||
background: var(--pan2);
|
||||
border-color: var(--line);
|
||||
color: var(--dan);
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.sm.danger:hover:not(:disabled),
|
||||
.sm.danger:focus-visible {
|
||||
background: var(--dan-fill);
|
||||
border-color: var(--dan);
|
||||
color: var(--on-dan);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { ButtonHTMLAttributes, Ref } from 'react'
|
||||
import { Button as ReuiButton } from '@/components/ui/button'
|
||||
|
||||
export type ButtonVariant = 'primary' | 'secondary' | 'danger'
|
||||
|
||||
/*
|
||||
The console's button is ReUI's: the three variants map onto its `default`, `outline`
|
||||
and `destructive`, and the two sizes onto `default` and `sm`.
|
||||
|
||||
`size="sm"` is the button for a table row. It existed as `.ib` copied across three
|
||||
modules and did not exist in DHCP, which used the large button: the same action
|
||||
("Edit") looked different depending on which screen you were on.
|
||||
*/
|
||||
const VARIANT = { primary: 'default', secondary: 'outline', danger: 'destructive' } as const
|
||||
|
||||
export function Button({
|
||||
variant = 'secondary',
|
||||
size = 'md',
|
||||
icon = false,
|
||||
className,
|
||||
ref,
|
||||
...rest
|
||||
}: ButtonHTMLAttributes<HTMLButtonElement> & {
|
||||
variant?: ButtonVariant
|
||||
size?: 'md' | 'sm'
|
||||
/** No label: an icon only. The width comes from the icon, not from text. */
|
||||
icon?: boolean
|
||||
ref?: Ref<HTMLButtonElement>
|
||||
}) {
|
||||
return (
|
||||
<ReuiButton
|
||||
ref={ref}
|
||||
variant={VARIANT[variant]}
|
||||
size={icon ? (size === 'sm' ? 'icon-sm' : 'icon') : size === 'sm' ? 'sm' : 'default'}
|
||||
data-variant={variant}
|
||||
data-icon={icon || undefined}
|
||||
className={className}
|
||||
{...rest}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
.check {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: var(--s-6);
|
||||
/* The label IS the target: it is clicked from the text, not only from the box.
|
||||
At 22 px tall it fell short for a finger. */
|
||||
min-height: 26px;
|
||||
padding: var(--s-2) 0;
|
||||
font-size: var(--t-4);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* The box aligns with the label's first line, not with its box. */
|
||||
.text { min-width: 0; }
|
||||
|
||||
.help {
|
||||
composes: withCode from './text.module.css';
|
||||
font-size: var(--t-3);
|
||||
color: var(--mute);
|
||||
line-height: 1.55;
|
||||
margin-top: var(--s-3);
|
||||
margin-left: calc(var(--ctrl) + var(--s-6));
|
||||
/*
|
||||
720 px, and **it is a local exception with its figure**, not a missing token.
|
||||
|
||||
Decided 2026-09-03, in a design review. Measured
|
||||
first: **it really bites**. At 1920, with the control column at 1022 px, the nine
|
||||
checkbox helps of `Settings › General` come out at exactly 720, so it is not dead
|
||||
code that can be deleted.
|
||||
|
||||
And it does not go up to `tokens.css` for the same reason the Dashboard hero did
|
||||
not: **only this uses it**. A global token is declared when two places share a
|
||||
decision; declaring one for a single use is inventing vocabulary nobody speaks.
|
||||
|
||||
What the cap is and why it is not `--help-col`: this is **the only help the
|
||||
dense-form design did NOT move** to the third column. A checkbox's stays under its control
|
||||
(because the checkbox IS its label and separating them would break that unit), so
|
||||
it inherits the control column's width, which on wide screens goes well past
|
||||
what reads comfortably. 720 is the readable line cap for THIS case.
|
||||
|
||||
If some day a second help stays out of the third column, then there are two and
|
||||
a token is due; today there are nine from the same place.
|
||||
*/
|
||||
max-width: 720px;
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import styles from './Check.module.css'
|
||||
|
||||
/*
|
||||
The checkbox with its label and help. It was written three times (Settings, DHCP
|
||||
and Administration), byte for byte identical apart from the styles module.
|
||||
|
||||
And it brings the **switch**, which is the only gesture of its own this console has
|
||||
allowed itself. A yes/no setting is not the same as ticking a table row: the first
|
||||
changes how the server behaves and stays that way, the second is a selection that
|
||||
lasts one click. Upstream paints them the same because Bootstrap 3 only had a
|
||||
checkbox. Here the setting gets a switch and the selection stays a checkbox, which
|
||||
is the difference the shape had to say and was not saying.
|
||||
|
||||
Underneath it is still an `input[type=checkbox]`: same keyboard, same role, same
|
||||
tests. What changes is what you see.
|
||||
*/
|
||||
|
||||
export function Check({
|
||||
label,
|
||||
checked,
|
||||
onChange,
|
||||
help,
|
||||
disabled,
|
||||
toggle = false,
|
||||
}: {
|
||||
label: string
|
||||
checked: boolean
|
||||
onChange: (v: boolean) => void
|
||||
help?: ReactNode
|
||||
disabled?: boolean
|
||||
/** A setting that stays put. False for a row selection. */
|
||||
toggle?: boolean
|
||||
}) {
|
||||
const common = {
|
||||
checked,
|
||||
disabled,
|
||||
'aria-label': label,
|
||||
onCheckedChange: (v: boolean) => onChange(v),
|
||||
}
|
||||
return (
|
||||
<div>
|
||||
<div className={styles.check}>
|
||||
{/* The control carries the name itself and the text beside it only forwards the
|
||||
click: a wrapping <label> would name the hidden input as well, and the one
|
||||
control would be found twice. A switch is announced as a checkbox on
|
||||
purpose: same role, same keyboard as the input it replaces. */}
|
||||
{toggle ? (
|
||||
<Switch role="checkbox" nativeButton render={<button type="button" />} {...common} />
|
||||
) : (
|
||||
<Checkbox nativeButton render={<button type="button" />} {...common} />
|
||||
)}
|
||||
<span className={styles.text} onClick={() => !disabled && onChange(!checked)}>
|
||||
{label}
|
||||
</span>
|
||||
</div>
|
||||
{help && <div className={styles.help}>{help}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { ClusterNodeSelect, nodeOptions, defaultNode, AGGREGATE } from './ClusterNodeSelect'
|
||||
|
||||
const NODES = [
|
||||
{ name: 'dns1.casa', type: 'Primary' },
|
||||
{ name: 'dns2.casa', type: 'Secondary' },
|
||||
]
|
||||
|
||||
describe('nodeOptions', () => {
|
||||
it('lists each node as name and lowercased type', () => {
|
||||
expect(nodeOptions(NODES)).toEqual([
|
||||
{ value: 'dns1.casa', label: 'dns1.casa (primary)' },
|
||||
{ value: 'dns2.casa', label: 'dns2.casa (secondary)' },
|
||||
])
|
||||
})
|
||||
|
||||
/* Only two of upstream's ten selectors offer the aggregate: Dashboard and
|
||||
Settings (cluster.js, updateAllClusterNodeDropDowns). */
|
||||
it('offers the aggregate first, and only when asked', () => {
|
||||
expect(nodeOptions(NODES, { aggregate: true })[0]).toEqual({ value: AGGREGATE, label: 'Cluster' })
|
||||
expect(nodeOptions(NODES).some((o) => o.value === AGGREGATE)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('defaultNode', () => {
|
||||
it('starts on the aggregate where there is one, and on this server elsewhere', () => {
|
||||
expect(defaultNode(true, 'dns1.casa')).toBe(AGGREGATE)
|
||||
expect(defaultNode(false, 'dns1.casa')).toBe('dns1.casa')
|
||||
})
|
||||
})
|
||||
|
||||
describe('ClusterNodeSelect', () => {
|
||||
/* The rule that keeps it invisible on every single-server install, which is
|
||||
every install this project has been developed against. */
|
||||
it('draws nothing when no cluster is initialised', () => {
|
||||
const { container } = render(
|
||||
<ClusterNodeSelect nodes={NODES} initialised={false} value="x" onChange={() => {}} />,
|
||||
)
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
})
|
||||
|
||||
/* `ui/Select` is a combobox and keeps its listbox closed, so what is asserted
|
||||
here is the control and the node it shows; the option list itself is covered
|
||||
by `nodeOptions` above, which is a pure function. */
|
||||
it('draws the control and shows the node in use', () => {
|
||||
render(<ClusterNodeSelect nodes={NODES} initialised value="dns1.casa" onChange={() => {}} />)
|
||||
expect(screen.getByRole('combobox')).toBeInTheDocument()
|
||||
expect(screen.getByText('dns1.casa (primary)')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows the aggregate when the screen is one of the two that has it', () => {
|
||||
render(
|
||||
<ClusterNodeSelect nodes={NODES} initialised aggregate value={AGGREGATE} onChange={() => {}} />,
|
||||
)
|
||||
expect(screen.getByText('Cluster')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('is labelled, and the label can be named by the screen', () => {
|
||||
const onChange = vi.fn()
|
||||
render(
|
||||
<ClusterNodeSelect
|
||||
nodes={NODES}
|
||||
initialised
|
||||
value="dns1.casa"
|
||||
onChange={onChange}
|
||||
label="Cluster Node"
|
||||
/>,
|
||||
)
|
||||
expect(screen.getByText('Cluster Node')).toBeInTheDocument()
|
||||
expect(onChange).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
import { ThisServerName } from './ClusterNodeSelect'
|
||||
|
||||
/* cluster.js:1041-1047: with no node chosen, the dropdown shows this server. */
|
||||
describe('ClusterNodeSelect with no node chosen', () => {
|
||||
const NODES = [
|
||||
{ name: 'a.example', type: 'Primary' },
|
||||
{ name: 'b.example', type: 'Secondary' },
|
||||
]
|
||||
|
||||
it('shows this server, and the screen keeps the empty value', () => {
|
||||
render(
|
||||
<ThisServerName.Provider value="b.example">
|
||||
<ClusterNodeSelect nodes={NODES} initialised value="" onChange={() => {}} label="Cluster Node" />
|
||||
</ThisServerName.Provider>,
|
||||
)
|
||||
expect(screen.getByRole('combobox', { name: 'Cluster Node' })).toHaveTextContent('b.example (secondary)')
|
||||
})
|
||||
|
||||
it('shows the dash when this server is not among the nodes', () => {
|
||||
render(
|
||||
<ThisServerName.Provider value="other.example">
|
||||
<ClusterNodeSelect nodes={NODES} initialised value="" onChange={() => {}} label="Cluster Node" />
|
||||
</ThisServerName.Provider>,
|
||||
)
|
||||
expect(screen.getByRole('combobox', { name: 'Cluster Node' })).not.toHaveTextContent('example')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,101 @@
|
||||
import { createContext, useContext } from 'react'
|
||||
import { Select } from './Select'
|
||||
import { Field } from './Field'
|
||||
|
||||
/*
|
||||
This server's name (`dnsServerDomain`), which the shell provides. With no node
|
||||
chosen, upstream's dropdown selects it (`updateClusterNodeDropDown`,
|
||||
cluster.js:1041-1051). The value a screen holds stays empty, which the server
|
||||
takes as this node, so only what the dropdown shows changes: this node's name
|
||||
instead of the empty-value dash.
|
||||
*/
|
||||
export const ThisServerName = createContext('')
|
||||
|
||||
/*
|
||||
Which cluster node a screen is looking at.
|
||||
|
||||
Upstream puts one of these on ten surfaces (`cluster.js`,
|
||||
`updateAllClusterNodeDropDowns`) and this console had it on none of them. It
|
||||
is not decoration: the server proxies the whole request to the chosen
|
||||
node (`DnsWebService.cs:2378`), so without it a console can only ever show the
|
||||
node it happens to be served from.
|
||||
|
||||
Three rules, all upstream's:
|
||||
|
||||
· It exists only when the server says `clusterInitialized`. On a single-server
|
||||
install there is nothing to choose and nothing is drawn.
|
||||
· Two of the ten (Dashboard and Settings) also offer **Cluster**, the aggregate,
|
||||
and it is their default. The other eight start on this server.
|
||||
· A node is listed as `name (type)`, with the type lowercased.
|
||||
*/
|
||||
|
||||
export interface ClusterNode {
|
||||
name: string
|
||||
type: string
|
||||
}
|
||||
|
||||
/** Upstream's word for the aggregate. The API client does not send it. */
|
||||
export const AGGREGATE = 'cluster'
|
||||
|
||||
export function nodeOptions(
|
||||
nodes: ClusterNode[],
|
||||
{ aggregate = false }: { aggregate?: boolean } = {},
|
||||
): { value: string; label: string }[] {
|
||||
const out = aggregate ? [{ value: AGGREGATE, label: 'Cluster' }] : []
|
||||
for (const n of nodes) out.push({ value: n.name, label: `${n.name} (${n.type.toLowerCase()})` })
|
||||
return out
|
||||
}
|
||||
|
||||
/** What a screen shows before anyone chooses: the aggregate where there is one,
|
||||
* and this server everywhere else. */
|
||||
export function defaultNode(aggregate: boolean, thisServer: string): string {
|
||||
return aggregate ? AGGREGATE : thisServer
|
||||
}
|
||||
|
||||
export function ClusterNodeSelect({
|
||||
nodes,
|
||||
initialised,
|
||||
aggregate = false,
|
||||
value,
|
||||
onChange,
|
||||
label = 'Node',
|
||||
disabled = false,
|
||||
}: {
|
||||
nodes: ClusterNode[]
|
||||
initialised: boolean
|
||||
aggregate?: boolean
|
||||
value: string
|
||||
onChange: (node: string) => void
|
||||
label?: string
|
||||
/** Upstream disables it where the node is already fixed (a zone open on one). */
|
||||
disabled?: boolean
|
||||
}) {
|
||||
const thisServer = useContext(ThisServerName)
|
||||
if (!initialised) return null
|
||||
|
||||
/* Only this server's own name stands in for the empty value: it is the node the
|
||||
empty value means. Upstream's fallback to the first node would also SEND that
|
||||
node, so it is not drawn here without being sent. */
|
||||
const shown = value === '' && !aggregate && nodes.some((n) => n.name === thisServer) ? thisServer : value
|
||||
|
||||
return (
|
||||
<Field label={label}>
|
||||
{(id) => (
|
||||
<Select id={id} value={shown} disabled={disabled} onChange={(e) => onChange(e.target.value)}>
|
||||
{nodeOptions(nodes, { aggregate }).map((o) => (
|
||||
<option key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
)}
|
||||
</Field>
|
||||
)
|
||||
}
|
||||
|
||||
/* `getPrimaryClusterNodeName` (cluster.js:997): the node whose type is `Primary`,
|
||||
or empty when the cluster is not initialised. */
|
||||
export function primaryNodeName(nodes: readonly ClusterNode[], initialised: boolean): string {
|
||||
if (!initialised) return ''
|
||||
return nodes.find((n) => n.type === 'Primary')?.name ?? ''
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/*
|
||||
The consequence block: the `Force …` box of the four Cluster dialogs.
|
||||
|
||||
It is not a form row, and that distinction is the whole point. A `Field` row says
|
||||
"this parameter of the action"; these four boxes do not parameterise the action,
|
||||
they change what it MEANS. Without the box, `Remove Node` asks the other node to
|
||||
leave and waits for it; with it, the node is deleted whether it answers or not.
|
||||
Drawn as one more row, the two are indistinguishable at a glance, and this is the
|
||||
only screen in the console where an action can leave the system split in two.
|
||||
|
||||
So it goes at the end of the body, in a box of its own, and when the box is ticked
|
||||
the box ARMS: a `--dan` rule down its side and the fill that goes with it. The
|
||||
verb in the footer does not change, because upstream does not change it and a
|
||||
design cannot invent a second verb.
|
||||
|
||||
There is no second sentence either. Upstream writes only the half that describes
|
||||
ticking the box ("Enabling this option will cause…") and says nothing about not
|
||||
ticking it. Writing that half would be inventing product copy, so the contrast
|
||||
between forcing and not forcing lives in this comment, not on the screen.
|
||||
What DOES stay on screen is upstream's own `Note!`, which already says what is
|
||||
left to do by hand; it sits after the block, where this console puts every `Note!`.
|
||||
*/
|
||||
.force {
|
||||
border: 1px solid var(--line);
|
||||
border-left: 3px solid var(--line);
|
||||
border-radius: var(--r-3);
|
||||
padding: var(--s-6) var(--s-8);
|
||||
background: var(--pan2);
|
||||
transition: border-color var(--t-fast), background var(--t-fast);
|
||||
}
|
||||
|
||||
.force[data-armed='true'] {
|
||||
border-color: var(--dan);
|
||||
border-left-color: var(--dan);
|
||||
background: var(--dan-fill);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import { useState, type ReactNode } from 'react'
|
||||
import { Button } from './Button'
|
||||
import { Check } from './Check'
|
||||
import { Dialog } from './Dialog'
|
||||
import styles from './Confirm.module.css'
|
||||
import text from './text.module.css'
|
||||
|
||||
/*
|
||||
The "are you sure?" step.
|
||||
|
||||
Upstream solves it with a native `confirm()`; the text and the step are the same,
|
||||
because you still need to confirm before the request goes out.
|
||||
|
||||
It was written six times: once as a component inside Administration (from where
|
||||
the Dashboard, Zones and the lists screens imported it, none of which have
|
||||
anything to do with Administration), another as a component inside Settings, and
|
||||
four times bare with `Dialog` + one button + `close="Cancel"` +
|
||||
`size="compact"` in Logs, DHCP and again Zones and the lists. Outside one table
|
||||
(the rules of Blocking › Rules, which offers Undo through `ui/Toast`) this console
|
||||
has no undo, so the place where six versions are least welcome is precisely this
|
||||
one.
|
||||
|
||||
Of the six, two (Zones and the lists) kept the "busy" flag and the closing INSIDE
|
||||
the dialog, and the other four asked each call site for them. The first form is
|
||||
better and no second API is needed to have it: if `onConfirm` returns a promise,
|
||||
this component disables the button while it runs and closes when it settles.
|
||||
Whoever already tracks their own state keeps passing `busy`.
|
||||
|
||||
It does not cover the "Remove Lease?" dialog, and that is deliberate: that one is
|
||||
not a one-line confirmation but four paragraphs of warning with its list of
|
||||
alternatives and its slot for a server alert. That it would fit in `text` does
|
||||
not make it the same thing.
|
||||
*/
|
||||
export function Confirm({
|
||||
open,
|
||||
title,
|
||||
text: body,
|
||||
label,
|
||||
variant = 'danger',
|
||||
busy,
|
||||
onClose,
|
||||
onConfirm,
|
||||
}: {
|
||||
open: boolean
|
||||
title: string
|
||||
text: ReactNode
|
||||
/** The action's verb: "Delete", "Convert", "Disable". */
|
||||
label: string
|
||||
variant?: 'primary' | 'danger'
|
||||
busy?: boolean
|
||||
onClose: () => void
|
||||
/** If it returns a promise, the dialog stays busy while it runs and closes when it settles. */
|
||||
onConfirm: () => unknown
|
||||
}) {
|
||||
const [inProgress, setInProgress] = useState(false)
|
||||
|
||||
function confirm() {
|
||||
const r = onConfirm()
|
||||
if (!(r instanceof Promise)) return
|
||||
setInProgress(true)
|
||||
void r.finally(() => {
|
||||
setInProgress(false)
|
||||
onClose()
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(o) => !o && onClose()}
|
||||
title={title}
|
||||
actions={
|
||||
<Button variant={variant} disabled={busy || inProgress} onClick={confirm}>
|
||||
{label}
|
||||
</Button>
|
||||
}
|
||||
close="Cancel"
|
||||
size="compact"
|
||||
>
|
||||
{/* `pre-wrap`: there are multi-line confirmations (the Zones ones), and
|
||||
without this they read as one run-on paragraph on one screen and not on
|
||||
another. */}
|
||||
<div className={text.paragraph} style={{ whiteSpace: 'pre-wrap' }}>
|
||||
{body}
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
/*
|
||||
The `Force …` box of the four Cluster dialogs, as a block and not as a row.
|
||||
|
||||
Why it is not a prop of `Confirm`, which is where the design placed it: none of
|
||||
the four dialogs that carry one IS a `Confirm`. They keep upstream's `Close`
|
||||
rather than `Cancel`, they carry two paragraphs instead of one line, and they end
|
||||
with their own `Note!`. `Confirm`'s own header already says it does not cover that
|
||||
shape (it says so about "Remove Lease?"), and adding a slot to it that no `Confirm`
|
||||
would ever use is a prop written for a drawing rather than for a call site.
|
||||
|
||||
So the slot is this block, and the four dialogs place it where the design put it:
|
||||
last among the controls, before the `Note!`.
|
||||
|
||||
The reasoning lives in `Confirm.module.css`.
|
||||
*/
|
||||
export function ForceBlock({
|
||||
label,
|
||||
help,
|
||||
checked,
|
||||
onChange,
|
||||
}: {
|
||||
/** Upstream's literal: "Force Delete Cluster", "Force Remove Node"… */
|
||||
label: string
|
||||
/** Upstream's help for that box, whole. It is the only sentence the product
|
||||
* writes about forcing, and it is not paraphrased. */
|
||||
help: string
|
||||
checked: boolean
|
||||
onChange: (v: boolean) => void
|
||||
}) {
|
||||
return (
|
||||
<div className={styles.force} data-armed={checked}>
|
||||
<Check label={label} help={help} checked={checked} onChange={onChange} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/*
|
||||
The "More Details" and "Raw Responses" disclosure.
|
||||
|
||||
A `<details>` triangle is painted by the browser (and each one paints its own), so
|
||||
it is another surface we had not drawn. It was solved twice, in Apps and in DNS
|
||||
Client, and both times with the chevron hand-encoded as an SVG in a `data:` URI:
|
||||
the same path as `chevronRight` from `ui/Icon`, but with `stroke-width: 2.5`
|
||||
against the 1.75 of the whole set. In other words, the only icon in the console
|
||||
with a different stroke weight, and in duplicate. Now it is the real icon.
|
||||
*/
|
||||
|
||||
.details > summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--s-4);
|
||||
/* The target gets clicked: with no padding it measured 17 px tall in Apps, and
|
||||
in DNS Client it did carry it. The same old difference. */
|
||||
padding: var(--s-3) 0;
|
||||
font-size: var(--t-3);
|
||||
color: var(--acc-ink);
|
||||
cursor: pointer;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.details > summary::-webkit-details-marker { display: none; }
|
||||
|
||||
.chevron {
|
||||
flex: none;
|
||||
transition: transform var(--t-fast);
|
||||
}
|
||||
|
||||
.details[open] > summary .chevron { transform: rotate(90deg); }
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.chevron { transition: none; }
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { Icon } from './Icon'
|
||||
import styles from './Details.module.css'
|
||||
|
||||
/** A `<details>` with the icon set's chevron. See the styles module. */
|
||||
export function Details({
|
||||
summary,
|
||||
children,
|
||||
className,
|
||||
}: {
|
||||
summary: ReactNode
|
||||
children: ReactNode
|
||||
className?: string
|
||||
}) {
|
||||
return (
|
||||
<details className={[styles.details, className].filter(Boolean).join(' ')}>
|
||||
<summary>
|
||||
<Icon name="chevronRight" size={12} className={styles.chevron} />
|
||||
{summary}
|
||||
</summary>
|
||||
{children}
|
||||
</details>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { Button } from './Button'
|
||||
import { Icon } from './Icon'
|
||||
import {
|
||||
Dialog as ReuiDialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
/*
|
||||
The footer is NOT free text. When it was, 23 modals put the action first and 17
|
||||
put it last, and in five of them the action was destructive: `Delete` and `Close`
|
||||
swapped places between two dialogs on the same screen.
|
||||
|
||||
Here the order belongs to the component, not to whoever uses it:
|
||||
|
||||
[ actions … ] [ Close ]
|
||||
|
||||
`actions` are the buttons that DO something; the dismiss one is painted by
|
||||
`Dialog` and always goes last, in the corner upstream had it in all 40 of its
|
||||
modals. That way no new modal can pick its own order again.
|
||||
*/
|
||||
|
||||
/* The widths, by what the content is: see `size` below. */
|
||||
const WIDTH = {
|
||||
compact: 'sm:max-w-[440px]',
|
||||
form: 'sm:max-w-[600px]',
|
||||
medium: 'sm:max-w-[760px]',
|
||||
wide: 'sm:max-w-[940px]',
|
||||
} as const
|
||||
|
||||
export function Dialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
title,
|
||||
children,
|
||||
actions,
|
||||
close = 'Close',
|
||||
size = 'form',
|
||||
}: {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
title: string
|
||||
children: ReactNode
|
||||
/** The buttons that do something. The dismiss one is not passed: Dialog adds it. */
|
||||
actions?: ReactNode
|
||||
/** Label for the dismiss button. `Cancel` when the modal is a question. */
|
||||
close?: string
|
||||
/**
|
||||
* The size, decided by the CONTENT and not by taste:
|
||||
*
|
||||
* · `compact`: a question and two buttons. The longest confirmation literal
|
||||
* in the console measures 405 px in the real typeface, so at 440 they all fit
|
||||
* on one line. Upstream does not have this size because its confirmations are
|
||||
* the browser's `confirm()`.
|
||||
* · `form`: fields with their labels. The ones upstream leaves at 600.
|
||||
* · `medium`: long forms and narrow tables. Upstream's 750-800.
|
||||
* · `wide`: real tables. Upstream's 940.
|
||||
*
|
||||
* The steps are upstream's, which did decide modal by modal; the figures are
|
||||
* lower because our typography runs tighter.
|
||||
*/
|
||||
size?: 'compact' | 'form' | 'medium' | 'wide'
|
||||
}) {
|
||||
return (
|
||||
<ReuiDialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent
|
||||
showCloseButton={false}
|
||||
data-size={size}
|
||||
className={cn('max-h-[calc(100dvh-2rem)] overflow-y-auto', WIDTH[size])}
|
||||
>
|
||||
<DialogHeader className="flex-row items-center justify-between gap-3">
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogClose
|
||||
render={<Button icon variant="secondary" size="sm" aria-label="Close" />}
|
||||
>
|
||||
<Icon name="close" size={16} />
|
||||
</DialogClose>
|
||||
</DialogHeader>
|
||||
<div className="min-w-0">{children}</div>
|
||||
<DialogFooter>
|
||||
{actions}
|
||||
<Button onClick={() => onOpenChange(false)}>{close}</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</ReuiDialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
/* One label and its closing dot: a line never ends inside it (see `DomainName.tsx`). */
|
||||
.label { white-space: nowrap; }
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
A domain name wraps at its dots and reads as the name the server sent.
|
||||
|
||||
jsdom does not lay text out, so what is checked here is the DOM that decides the
|
||||
wrapping: one piece per label with its dot, a `<wbr>` after each dot and nowhere
|
||||
else. And what a person or a screen reader gets out of it, which must be the
|
||||
name untouched.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { DomainName } from './DomainName'
|
||||
|
||||
describe('a domain name', () => {
|
||||
it('is one piece per label, with a break opportunity only after each dot', () => {
|
||||
const { container } = render(<DomainName name="0.30.172.in-addr.arpa" />)
|
||||
const pieces = [...container.querySelectorAll('span')].map((s) => s.textContent)
|
||||
expect(pieces).toEqual(['0.', '30.', '172.', 'in-addr.', 'arpa'])
|
||||
expect(container.querySelectorAll('wbr')).toHaveLength(4)
|
||||
expect(container.textContent).toBe('0.30.172.in-addr.arpa')
|
||||
})
|
||||
|
||||
it('keeps the accessible name of the control that holds it', () => {
|
||||
render(
|
||||
<button type="button">
|
||||
<DomainName name="example.net" />
|
||||
</button>,
|
||||
)
|
||||
expect(screen.getByRole('button', { name: 'example.net' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps a name with no dot whole, hyphens included, as one piece', () => {
|
||||
for (const name of ['<root>', '@', 'localhost', 'living-room-tv']) {
|
||||
const { container, unmount } = render(<DomainName name={name} />)
|
||||
const pieces = [...container.querySelectorAll('span')].map((s) => s.textContent)
|
||||
expect(pieces).toEqual([name])
|
||||
expect(container.querySelector('wbr')).toBeNull()
|
||||
unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('leaves the root and an empty name as plain text', () => {
|
||||
for (const name of ['.', '']) {
|
||||
const { container, unmount } = render(<DomainName name={name} />)
|
||||
expect(container.querySelector('span')).toBeNull()
|
||||
expect(container.textContent).toBe(name)
|
||||
unmount()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,45 @@
|
||||
import { Fragment } from 'react'
|
||||
import styles from './DomainName.module.css'
|
||||
|
||||
/*
|
||||
A domain name that wraps at its dots and nowhere else.
|
||||
|
||||
It used to be the text alone with `word-break: break-word` on the button that
|
||||
holds it, and that rule does more than break a name that does not fit: it lets the
|
||||
browser size the column as if the name could break after ANY letter. At 390 px the
|
||||
Zones column shrank to five characters and `0.30.172.in-addr.arpa` came out in four
|
||||
lines cut through the middle of its labels. A hyphen is no better place: `in-addr`
|
||||
is one label, and the browser breaks after a hyphen of its own accord.
|
||||
|
||||
So each label (with the dot that closes it) is one unbreakable piece, and a `<wbr>`
|
||||
after the dot is the only place a line may end. The column is then as narrow as
|
||||
the longest label and no narrower; a table that cannot fit that scrolls, which is
|
||||
what the table wrapper is for.
|
||||
|
||||
Nothing changes in what is read: `<wbr>` carries no text, so the accessible name,
|
||||
the copied text and the find-in-page match are the name as the server sent it.
|
||||
The root (`.`) and an empty name are left as plain text.
|
||||
|
||||
A name with no dot is one label, and it is one piece too. It used to be left as
|
||||
plain text, so a record's relative name broke after its hyphen: at 1440 the
|
||||
records' Name column was 125 px beside a Data column of 700, and
|
||||
`living-room-tv` read `living-room-` over `tv`. As one piece it sets the column's
|
||||
minimum instead.
|
||||
*/
|
||||
export function DomainName({ name }: { name: string }) {
|
||||
if (name === '' || name === '.') return <>{name}</>
|
||||
if (!name.includes('.')) return <span className={styles.label}>{name}</span>
|
||||
|
||||
const labels = name.split('.')
|
||||
const last = labels.length - 1
|
||||
return (
|
||||
<>
|
||||
{labels.map((label, i) => (
|
||||
<Fragment key={i}>
|
||||
<span className={styles.label}>{i < last ? `${label}.` : label}</span>
|
||||
{i < last && <wbr />}
|
||||
</Fragment>
|
||||
))}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
The table of a list edited in place: the TSIG keys, the forwarders, a scope's
|
||||
static routes, the SSO group maps.
|
||||
|
||||
It is not the data table of `ui/Table.module.css` and must not look like it: that
|
||||
one is a screen's main object (with its panel, its border and its shadow), and this
|
||||
one lives INSIDE a panel, tight against its fields. That is why it goes without a
|
||||
box, without a header background and with a narrower cell.
|
||||
|
||||
What they do share is the label: the column header is the same small caps as any
|
||||
other table's (`--text-*` in tokens). It was not before (it ran at 0.07em), and on
|
||||
top of that this table was written THREE times, in Settings, in DHCP and in
|
||||
Administration, with the same values copied by hand.
|
||||
*/
|
||||
.table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
.table th {
|
||||
text-align: left;
|
||||
font-size: var(--text-size);
|
||||
font-weight: var(--text-weight);
|
||||
letter-spacing: var(--text-tracking);
|
||||
text-transform: uppercase;
|
||||
color: var(--mute);
|
||||
padding: 0 var(--s-5) var(--s-4) 0;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.table td {
|
||||
padding: var(--s-3) var(--s-5) var(--s-3) 0;
|
||||
vertical-align: middle;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import styles from './EditableTable.module.css'
|
||||
|
||||
/*
|
||||
The table of a list edited in place: the TSIG keys, the forwarders, a scope's
|
||||
static routes, the SSO group maps, a section's permissions.
|
||||
|
||||
It is a different piece from the data table (`ui/Table`) and it must be: that one
|
||||
is a screen's main object, with its panel and its border; this one lives INSIDE a
|
||||
panel, up against its fields, and that is why it goes without a box and tighter.
|
||||
What they share (the small-caps column label) comes from the same tokens.
|
||||
|
||||
It exists as a component for the same reason as the other one: the scaffolding was
|
||||
written five times. Three modules also defined their own class with the same values
|
||||
copied by hand, and that is where one ended up with 0.07em of letter-spacing and
|
||||
the rest with 0.05.
|
||||
*/
|
||||
export function EditableTable({
|
||||
header,
|
||||
children,
|
||||
className,
|
||||
}: {
|
||||
header: ReactNode
|
||||
children: ReactNode
|
||||
className?: string
|
||||
}) {
|
||||
return (
|
||||
<table className={[styles.table, className].filter(Boolean).join(' ')}>
|
||||
<thead>
|
||||
<tr>{header}</tr>
|
||||
</thead>
|
||||
<tbody>{children}</tbody>
|
||||
</table>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
The two "there is nothing here" states and the "it has not arrived yet" one. There
|
||||
used to be five treatments of empty (dotted box, loose muted text, two different
|
||||
paddings, a `<b>` that was sometimes there) and three of loading.
|
||||
*/
|
||||
|
||||
/* Region empty state: it replaces a whole table, list or grid. */
|
||||
.box {
|
||||
border: 1px dashed var(--line);
|
||||
border-radius: var(--r-4);
|
||||
padding: var(--s-12);
|
||||
text-align: center;
|
||||
color: var(--mute);
|
||||
font-size: var(--t-4);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.title {
|
||||
display: block;
|
||||
color: var(--ink);
|
||||
font-size: var(--t-5);
|
||||
font-weight: 550;
|
||||
margin-bottom: var(--s-3);
|
||||
}
|
||||
|
||||
.actions {
|
||||
margin-top: var(--s-9);
|
||||
display: flex;
|
||||
gap: var(--s-5);
|
||||
justify-content: center;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
/* Empty state inside a panel: one line, no box, not competing with it. */
|
||||
.line {
|
||||
color: var(--faint);
|
||||
font-size: var(--t-4);
|
||||
padding: var(--s-7) 0;
|
||||
}
|
||||
|
||||
/* Loading: same place and same weight as the empty state it will replace. */
|
||||
.loading {
|
||||
padding: var(--s-12);
|
||||
text-align: center;
|
||||
color: var(--faint);
|
||||
font-size: var(--t-4);
|
||||
}
|
||||
|
||||
/*
|
||||
Failure. It used to reuse `.loading` exactly, so **the data never arrived and the
|
||||
data is on its way looked identical**: same muted centred line, no border. On a
|
||||
screen you have just opened that is the difference between waiting and retrying.
|
||||
|
||||
The design rule settles it in one line: **dashed = empty, continuous = error, and they are
|
||||
never swapped**. So this is the only one of the three with a solid border, and it
|
||||
is `--dan`; the empty box keeps the dashed one and loading keeps none.
|
||||
|
||||
`--dim` deliberately does NOT appear here. It means "this is here, readable, and
|
||||
not current": the previous data while a refresh is in flight. A failure slot has
|
||||
no previous data in it: dimming it would say something that is not true.
|
||||
|
||||
The background and the text are COMPOSED from the shared tone and not written
|
||||
again: the error already has its pair of colours in `tones.module.css`, which is
|
||||
where the notice and the pill take theirs from. Writing it again is how two reds
|
||||
are born.
|
||||
|
||||
The one deviation, and it is declared: **the border is not `--dan-bd`, it is
|
||||
`--dan`**. The tone uses it dimmed because there the border only bounds a notice
|
||||
that is already saying it with its background; here it has to read **against the
|
||||
viewer's dashed box**, which is a `--line` away, and `--dan-bd` does not reach
|
||||
that far.
|
||||
*/
|
||||
.failure {
|
||||
composes: dan from './tones.module.css';
|
||||
border: 1px solid var(--dan);
|
||||
border-radius: var(--r-4);
|
||||
padding: var(--s-12);
|
||||
text-align: center;
|
||||
font-size: var(--t-4);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.loading.line {
|
||||
padding: var(--s-7) 0;
|
||||
text-align: left;
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import styles from './Empty.module.css'
|
||||
|
||||
/*
|
||||
An empty state is painted in two ways and no more:
|
||||
|
||||
· `Empty`: a REGION's empty state, the one that takes the place of the table or
|
||||
grid that has no rows. Dotted box, centred, with a title and, if the user can
|
||||
do something about it, the button that does it.
|
||||
· `Empty compact`: the empty state INSIDE a panel, a muted line that does not
|
||||
compete with the panel containing it.
|
||||
|
||||
And `Loading` and `Failure` are the same slot before the data: one while it travels
|
||||
and the other when it never arrived. Same place and same weight as the empty state
|
||||
they replace, so the screen does not jump when it resolves.
|
||||
|
||||
`Failure` was written by hand in four modules (`.fail` in Settings, DHCP, Logs and
|
||||
Administration) with the same four values `.loading` already had here.
|
||||
*/
|
||||
|
||||
export function Empty({
|
||||
title,
|
||||
children,
|
||||
actions,
|
||||
compact = false,
|
||||
}: {
|
||||
/** What it is that is not there. Region empty state only. */
|
||||
title?: string
|
||||
/** Why it is not there, or what to do so that it is. */
|
||||
children?: ReactNode
|
||||
actions?: ReactNode
|
||||
compact?: boolean
|
||||
}) {
|
||||
if (compact) return <div className={styles.line}>{children}</div>
|
||||
|
||||
return (
|
||||
<div className={styles.box}>
|
||||
{title != null && <span className={styles.title}>{title}</span>}
|
||||
{children}
|
||||
{actions != null && <div className={styles.actions}>{actions}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function Loading({
|
||||
children = 'Loading…',
|
||||
compact = false,
|
||||
announce = true,
|
||||
}: {
|
||||
/** What is loading, when saying so helps: "Loading DS records…". */
|
||||
children?: ReactNode
|
||||
compact?: boolean
|
||||
/**
|
||||
* `false` for the SECOND placeholder of the same wait. See below: one request
|
||||
* is one announcement, however many holes it leaves on screen.
|
||||
*/
|
||||
announce?: boolean
|
||||
}) {
|
||||
/*
|
||||
`role="status"` because a screen that is busy has to say so: without it the only
|
||||
signal is a grey line nobody hears, and the wait is exactly when a screen reader
|
||||
user has least to go on. It is polite by definition (it does not interrupt), and
|
||||
it announces once, when the text appears.
|
||||
|
||||
Measured on 2026-09-07 with the state matrix: not one of the twenty-nine call
|
||||
sites had an announced busy state.
|
||||
|
||||
## Why one of them can keep quiet
|
||||
|
||||
"It announces once" stopped being true the moment a screen had two holes for the
|
||||
same request: the domain tree and its records both wait on the same call, and
|
||||
two `role="status"` regions saying "Loading…" is the same wait read out twice.
|
||||
The eye needs a placeholder in each hole (that is what says the content is
|
||||
coming and not gone), but the ear needs one.
|
||||
|
||||
So the rule is per REQUEST, not per hole: the first placeholder announces, any
|
||||
further placeholder for the same wait passes `announce={false}` and is drawn
|
||||
without the role. It is not a way to skip the announcement; a screen with a
|
||||
single hole has no reason to touch this.
|
||||
*/
|
||||
return (
|
||||
<div
|
||||
role={announce ? 'status' : undefined}
|
||||
className={`${styles.loading}${compact ? ` ${styles.line}` : ''}`}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/*
|
||||
The data never arrived. It fills the same slot as the `Loading` it replaces, and
|
||||
until the design pass it also wore the same clothes, which was the defect: a muted centred
|
||||
line with no border said "on its way" and "it failed" with the same picture.
|
||||
|
||||
The design rule, verbatim: **dashed = empty, continuous = error, never swapped.**
|
||||
So this is the one with the solid `--dan` border.
|
||||
|
||||
What is NOT here yet, and belongs to whoever redesigns the screen: the rule also
|
||||
asks for the cause, the time of the last good data and a single `Retry`. The cause
|
||||
already arrives as `children`; the other two are the screen's to supply, and the
|
||||
one call site (`Settings.tsx:149`) has neither. Adding an `actions` prop that
|
||||
nothing passes would be inventing API ahead of its use.
|
||||
*/
|
||||
export function Failure({ children }: { children: ReactNode }) {
|
||||
return <div className={styles.failure}>{children}</div>
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
/* The "Help: …" line, at the foot of a panel or a dialog. */
|
||||
.help { font-size: var(--t-3); padding: var(--s-5) 0 0; }
|
||||
.help a { display: inline-block; padding: var(--s-3) 0; color: var(--acc-ink); }
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { External } from './External'
|
||||
|
||||
/* Some destinations come from the server, such as the update feed's links. Only
|
||||
the web's own schemes become a link; anything else is shown, not followed. */
|
||||
describe('External', () => {
|
||||
it('links an https destination in a new tab', () => {
|
||||
render(<External href="https://example.test/notes">Read Change Logs</External>)
|
||||
const link = screen.getByRole('link', { name: 'Read Change Logs' })
|
||||
expect(link).toHaveAttribute('href', 'https://example.test/notes')
|
||||
expect(link).toHaveAttribute('target', '_blank')
|
||||
expect(link).toHaveAttribute('rel', 'noreferrer')
|
||||
})
|
||||
|
||||
it('links an http destination', () => {
|
||||
render(<External href="http://example.test/">Download Now!</External>)
|
||||
expect(screen.getByRole('link', { name: 'Download Now!' })).toHaveAttribute('href', 'http://example.test/')
|
||||
})
|
||||
|
||||
it.each(['javascript:alert(1)', ' JavaScript:alert(1)', 'data:text/html,<b>x</b>', 'vbscript:x', 'file:///etc/passwd'])(
|
||||
'does not link %s',
|
||||
(href) => {
|
||||
render(<External href={href}>Download Now!</External>)
|
||||
expect(screen.queryByRole('link')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('Download Now!')).toBeInTheDocument()
|
||||
},
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import styles from './External.module.css'
|
||||
|
||||
/*
|
||||
The links that lead out of the console.
|
||||
|
||||
They are here and not scattered because a review found they had been going missing
|
||||
one at a time: upstream's sentence stayed and the destination disappeared ("read
|
||||
the change log" with no change log, "Use ZONEMD to Validate Zone" with no RFC).
|
||||
With a single place where they are written, `dev/check-parity-controls.mjs` can
|
||||
verify by list that none is missing.
|
||||
|
||||
Two shapes, which is what upstream has:
|
||||
|
||||
- `External`, inside a sentence: "validated using the [ZONEMD] record".
|
||||
- `HelpText`, the standalone line at the foot of a panel or a dialog: "Help: …".
|
||||
*/
|
||||
export function External({ href, children }: { href: string; children: ReactNode }) {
|
||||
if (!webDestination(href)) return <span>{children}</span>
|
||||
return (
|
||||
<a href={href} target="_blank" rel="noreferrer">
|
||||
{children}
|
||||
</a>
|
||||
)
|
||||
}
|
||||
|
||||
/*
|
||||
OURS: some destinations come from the server, such as the three links of the
|
||||
update feed, so only the web's own schemes become a link. React already blocks
|
||||
`javascript:`, and browsers block a top-level `data:`; this does not depend on
|
||||
either.
|
||||
*/
|
||||
function webDestination(href: string): boolean {
|
||||
try {
|
||||
const { protocol } = new URL(href, window.location.href)
|
||||
return protocol === 'https:' || protocol === 'http:'
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The help line. It is not a link inside a sentence, so WCAG's target-size
|
||||
* exception does not apply to it: it carries a box of its own.
|
||||
*/
|
||||
export function HelpText({ href, children }: { href: string; children: ReactNode }) {
|
||||
return (
|
||||
<div className={styles.help}>
|
||||
<External href={href}>{children}</External>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { useId, type ComponentProps, type InputHTMLAttributes, type ReactNode, type Ref, type TextareaHTMLAttributes } from 'react'
|
||||
import { Input as ReuiInput } from '@/components/ui/input'
|
||||
import { Textarea as ReuiTextarea } from '@/components/ui/textarea'
|
||||
import { cn } from '@/lib/utils'
|
||||
import textStyles from './text.module.css'
|
||||
|
||||
export function Field({ label, children }: { label: string; children: (id: string) => ReactNode }) {
|
||||
const id = useId()
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<label className="text-xs font-medium text-muted-foreground" htmlFor={id}>
|
||||
{label}
|
||||
</label>
|
||||
{children(id)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export type InputProps = InputHTMLAttributes<HTMLInputElement> & {
|
||||
mono?: boolean
|
||||
/** React 19 passes `ref` as a normal prop, but it still has to be declared. */
|
||||
ref?: Ref<HTMLInputElement>
|
||||
}
|
||||
|
||||
export function Input({ mono, className, ...rest }: InputProps) {
|
||||
return (
|
||||
<ReuiInput className={cn('text-sm', mono && textStyles.mono, className)} {...rest} />
|
||||
)
|
||||
}
|
||||
|
||||
/** A field with its label associated via `htmlFor`, which is what lets the tests
|
||||
* query it with `getByLabelText` exactly as a screen reader would. */
|
||||
export function LabeledInput({ label, mono, ...rest }: InputProps & { label: string }) {
|
||||
return <Field label={label}>{(id) => <Input id={id} mono={mono} {...rest} />}</Field>
|
||||
}
|
||||
|
||||
export type TextareaProps = TextareaHTMLAttributes<HTMLTextAreaElement> & {
|
||||
mono?: boolean
|
||||
ref?: Ref<HTMLTextAreaElement>
|
||||
}
|
||||
|
||||
export function Textarea({ mono, className, ...rest }: TextareaProps) {
|
||||
return (
|
||||
<ReuiTextarea className={cn('text-sm', mono && textStyles.mono, className)} {...rest} />
|
||||
)
|
||||
}
|
||||
|
||||
/** A textarea with an associated label, so it can be queried by its name. */
|
||||
export function LabeledTextarea({ label, mono, ...rest }: TextareaProps & { label: string }) {
|
||||
return <Field label={label}>{(id) => <Textarea id={id} mono={mono} {...rest} />}</Field>
|
||||
}
|
||||
|
||||
/*
|
||||
The dropdown lives in `ui/Select`: it is no longer a native `<select>`, so it does
|
||||
not take `SelectHTMLAttributes` but its list of options. It is re-exported from
|
||||
here because the screens ask for it alongside the rest of the fields.
|
||||
*/
|
||||
import { Select, type Option } from './Select'
|
||||
|
||||
export { Select, type Option }
|
||||
|
||||
/** A dropdown with an associated label. Phases 6 and 7 asked for it. */
|
||||
export function LabeledSelect({
|
||||
label,
|
||||
...rest
|
||||
}: Omit<ComponentProps<typeof Select>, 'id'> & { label: string }) {
|
||||
return <Field label={label}>{(id) => <Select id={id} {...rest} />}</Field>
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
Upstream's five links that hang off the `body`. See `app/footer.ts` for which ones
|
||||
they are and why.
|
||||
|
||||
The markup and the link treatment were written twice (in the sidebar and on the
|
||||
login screen), and out of that came two different targets for the same link:
|
||||
`padding: var(--s-2) var(--s-1)` in one and `var(--s-1) 0` in the other. Here they
|
||||
go once.
|
||||
|
||||
What each place does decide is the SIZE and the alignment: in the sidebar it sits
|
||||
tight against the edge and on login it is centred under the card. That comes from
|
||||
the caller's `className`.
|
||||
*/
|
||||
|
||||
.footer { color: var(--faint); }
|
||||
|
||||
/* The name does not break ("DNS Client" was falling onto two lines), but a break
|
||||
is still possible: the separator sits loose between the anchors, with its
|
||||
spaces, exactly as upstream has it. Putting `nowrap` on the wrapper instead of
|
||||
on the link left the list without a single break opportunity and the sidebar
|
||||
overflowed by 47 px horizontally. */
|
||||
.footer a {
|
||||
color: var(--faint);
|
||||
text-decoration: none;
|
||||
white-space: nowrap;
|
||||
padding: var(--s-2) var(--s-1);
|
||||
}
|
||||
|
||||
.footer a:hover { color: var(--ink); text-decoration: underline; }
|
||||
|
||||
.sep { color: var(--line); }
|
||||
|
||||
/*
|
||||
The theme credit: its own line below the links. It deliberately does not share a
|
||||
row with them (see `app/footer.ts`), and the link is treated like the ones above, so
|
||||
as not to invent a third kind of link inside the same six-line block.
|
||||
|
||||
The hierarchy comes from the SEPARATE LINE, not from colour: the first attempt
|
||||
dropped the "Theme by" to `--line`, which is a border colour, and it measured
|
||||
1.62:1 against the background (the minimum for text is 4.5). It inherits the
|
||||
footer's `--faint`, which gives 5.61:1.
|
||||
*/
|
||||
.credit { margin-top: var(--s-3); }
|
||||
@@ -0,0 +1,28 @@
|
||||
import { Fragment } from 'react'
|
||||
import { THEME_CREDIT, FOOTER } from '../app/footer'
|
||||
import styles from './FooterLinks.module.css'
|
||||
|
||||
/**
|
||||
* Upstream's footer links, and beneath them the theme credit (the only thing this
|
||||
* console adds here). See `app/footer.ts` and the styles module.
|
||||
*/
|
||||
export function FooterLinks({ className }: { className?: string }) {
|
||||
return (
|
||||
<div className={[styles.footer, className].filter(Boolean).join(' ')}>
|
||||
{FOOTER.map((e, i) => (
|
||||
<Fragment key={e.href}>
|
||||
{i > 0 && <span className={styles.sep}> | </span>}
|
||||
<a href={e.href} aria-label={e.name} target="_blank" rel="noreferrer">
|
||||
{e.text}
|
||||
</a>
|
||||
</Fragment>
|
||||
))}
|
||||
<div className={styles.credit}>
|
||||
Theme:{' '}
|
||||
<a href={THEME_CREDIT.href} aria-label={THEME_CREDIT.name} target="_blank" rel="noreferrer">
|
||||
{THEME_CREDIT.text}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
/*
|
||||
The label + control row, a single one. There were four grids (210 px on pages,
|
||||
180 px in the Zones modals, 170 px in the Administration ones, 110 px in the Logs
|
||||
filter) and two different labels: 600 and `--ink` on pages, 400 and `--mute` in
|
||||
the Zones modals. With the muted one, in "Add Zone" the label receded behind the
|
||||
value; with the strong one, in "Add User" it competed with it.
|
||||
|
||||
The strong one wins: in a long form the label is what you look for when scanning,
|
||||
not what you read afterwards.
|
||||
*/
|
||||
|
||||
/*
|
||||
THREE columns: label, control and help.
|
||||
|
||||
It is the dense-form design's decision, and the one that holds it up: in a dense form
|
||||
**the surface is the text**. `General` has 41 paragraphs of help against 39
|
||||
controls, and under each field they made a page twice as long in which the text
|
||||
weighed more than the fields.
|
||||
|
||||
The third column is `--help-col` and **only `.row` carries it**. `.mrow` (the
|
||||
dialog) stays at two: there are 560 px of width there, and the design measured a
|
||||
panel, not a modal.
|
||||
*/
|
||||
.row {
|
||||
display: grid;
|
||||
grid-template-columns: 210px minmax(0, 1fr) var(--help-col);
|
||||
gap: var(--s-8);
|
||||
padding: var(--s-7) var(--s-9);
|
||||
align-items: start;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
|
||||
/* The help as the control's sibling and not inside it: that is what moves it into
|
||||
its own column. In the modal it stays nested, and that is why it still falls
|
||||
underneath. */
|
||||
.rowHelp {
|
||||
grid-column: 3;
|
||||
}
|
||||
|
||||
.row:last-child { border-bottom: 0; }
|
||||
|
||||
/* Inside a modal there is less room and fewer rows: no separator, no 210 px. */
|
||||
.mrow {
|
||||
display: grid;
|
||||
grid-template-columns: 180px minmax(0, 1fr);
|
||||
gap: var(--s-8);
|
||||
padding: var(--s-3) 0;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.rowLabel,
|
||||
.mrowLabel {
|
||||
font-size: var(--t-4);
|
||||
color: var(--ink);
|
||||
font-weight: 600;
|
||||
padding-top: var(--s-5);
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.rowCtl,
|
||||
.mrowCtl {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--s-3);
|
||||
}
|
||||
|
||||
/*
|
||||
A one-line field gains nothing from being 640 px wide.
|
||||
|
||||
The control column is `1fr`, so it eats everything left over, and that did not
|
||||
show while every dialog was 560 wide. Once "User Details" got the 880 its sessions
|
||||
table asks for, the box for typing "admin" grew to 640 px. The cap is 420, which
|
||||
is what the page forms were already using in practice: measured across the
|
||||
console's 46 fields, the median is 174 px and the maximum 420.
|
||||
|
||||
The cap also reaches a table that is a row's control: "Member Of" in My Profile is
|
||||
ONE column and measured 831 px for an 82 px group name. Upstream does not stretch
|
||||
it either: it puts it in a `col-sm-7`. What stays outside is the `textarea` (IP
|
||||
lists, which do use the width) and tables that are NOT a row's control, like the
|
||||
sessions one, which needs everything it can get.
|
||||
*/
|
||||
.mrow input:not([type='checkbox']):not([type='radio']),
|
||||
.mrow select,
|
||||
.mrow table {
|
||||
max-width: 420px;
|
||||
}
|
||||
|
||||
/*
|
||||
The breakpoints, and why the panel and the modal no longer share one.
|
||||
|
||||
This breakpoint was a SINGLE one at 720 for both rows. What motivated it is still
|
||||
true and is written down: at 390 the 210 px grid left 20 px for the field and made
|
||||
seventeen Settings fields invisible. **But that proves 390 had to be protected,
|
||||
not that 720 was the right threshold.**
|
||||
|
||||
So they part company:
|
||||
|
||||
· `.row` follows the breakpoints the dense-form design measured: 1180 and 560.
|
||||
· `.mrow` **keeps its 720 and its geometry**: the design measured a dense form,
|
||||
not a dialog, and does not authorise touching the modal. That 720 stands as
|
||||
**modal** debt, with its figure, and not mixed in with the dense form.
|
||||
|
||||
At 1180 the help leaves the third column and drops to a second line of its own row.
|
||||
It stays visible and stays complete: **no width hides it**.
|
||||
*/
|
||||
@media (max-width: 1180px) {
|
||||
.row {
|
||||
grid-template-columns: 210px minmax(0, 1fr);
|
||||
}
|
||||
|
||||
/* Second line, aligned with the control and not with the label. */
|
||||
.rowHelp {
|
||||
grid-column: 2;
|
||||
}
|
||||
}
|
||||
|
||||
/* At 560 it stacks completely: label, control and help, in that order. */
|
||||
@media (max-width: 560px) {
|
||||
.row {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: var(--s-4);
|
||||
padding: var(--s-7) var(--s-8);
|
||||
}
|
||||
|
||||
.rowLabel { padding-top: 0; }
|
||||
.rowHelp { grid-column: 1; }
|
||||
}
|
||||
|
||||
/* 720: the MODAL's, which stays where it was. */
|
||||
@media (max-width: 720px) {
|
||||
.mrow {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: var(--s-4);
|
||||
}
|
||||
|
||||
.mrowLabel { padding-top: 0; }
|
||||
}
|
||||
|
||||
/*
|
||||
The help under a field, and the group of checkboxes in a row.
|
||||
|
||||
Both were defined three times (in Settings, in DHCP and in Administration) with
|
||||
the same values copied by hand. It is the same story as the table and the panel:
|
||||
what gets repeated ends up drifting apart.
|
||||
*/
|
||||
.help {
|
||||
composes: withCode from './text.module.css';
|
||||
font-size: var(--t-3);
|
||||
color: var(--mute);
|
||||
line-height: 1.55;
|
||||
max-width: 720px;
|
||||
}
|
||||
|
||||
.help a { color: var(--acc-ink); }
|
||||
|
||||
|
||||
/* Several checkboxes or radios inside a single row. */
|
||||
.group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--s-6);
|
||||
}
|
||||
|
||||
/*
|
||||
The row switched off by its master switch.
|
||||
|
||||
An amber edge on the side, and nothing else here: the opacity already comes with
|
||||
the control's own `disabled`, and the pill that NAMES it is drawn by `Row` next to
|
||||
the label. The three pieces together are the master-switch signal, and none is
|
||||
spare: the edge is seen without reading, the pill says which switch it is, and the
|
||||
opacity says it is not active.
|
||||
|
||||
Amber and not red, and amber and not a padlock: *amber = you can*. The user can
|
||||
switch this on themselves. If the permission were missing as well, **the padlock
|
||||
wins** and this edge is not drawn: what you cannot touch does not need two
|
||||
explanations of why it is off.
|
||||
|
||||
The edge is an INNER SHADOW and not a `border-left`, and the measurement decided
|
||||
that, not taste. With `border-left: 2px` the grid of those five rows became
|
||||
`210px 540px 360px` against the `210px 542px 360px` of the other 34: the border
|
||||
eats two pixels of the box and **shifts the control**. In a dense form that is a
|
||||
column that stops being aligned, and `dev/uniformity.js` caught it as a third
|
||||
`grid-panel` signature that existed only in `/settings/general/`.
|
||||
|
||||
A state signal cannot move the content it points at. The inner shadow paints
|
||||
exactly the same edge and takes up no grid: the family is back to two signatures
|
||||
and the 39 rows stay aligned.
|
||||
*/
|
||||
.dependent { box-shadow: inset 2px 0 0 0 var(--acc-ink); }
|
||||
.withPill { display: flex; align-items: center; gap: var(--s-4); flex-wrap: wrap; }
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
import { useId, type ReactNode } from 'react'
|
||||
import { Tag } from './Tag'
|
||||
import frm from './Form.module.css'
|
||||
|
||||
/*
|
||||
A form row: label on the left, control on the right.
|
||||
|
||||
It was written by hand 38 times, and on top of that existed TWICE as a component
|
||||
(in `screens/settings/parts.tsx` and in `screens/dhcp/parts.tsx`, byte-identical
|
||||
apart from one comment) without any of the other twelve screens using either. With
|
||||
the row loose, the pieces around it drifted apart too: the help under a field and
|
||||
the checkbox group were each defined three times.
|
||||
|
||||
`modal` changes the grid: inside a dialog there is less room and fewer rows, so the
|
||||
label column is narrower and carries no separator. That is the only real
|
||||
difference between the two variants, which is why it is a parameter and not
|
||||
another component.
|
||||
*/
|
||||
export function Row({
|
||||
label,
|
||||
help,
|
||||
modal = false,
|
||||
dependsOn,
|
||||
children,
|
||||
}: {
|
||||
label: string
|
||||
help?: ReactNode
|
||||
modal?: boolean
|
||||
/*
|
||||
The name of the switch that has this row turned off, if there is one.
|
||||
|
||||
It is the master-switch signal, and it comes in THREE pieces with none to
|
||||
spare: an **amber edge** on the side (seen without reading), **opacity**, which
|
||||
already comes with the control's own `disabled`, and **a pill that NAMES it**,
|
||||
because "this is off" without saying who turned it off makes you hunt for the
|
||||
switch across the whole screen.
|
||||
|
||||
Amber and not a padlock: *amber = you can*. A control turned off by its master
|
||||
can be switched on by the user themselves; one turned off by permission cannot.
|
||||
If both applied, **the padlock wins**: what you cannot touch does not need two
|
||||
explanations of why it is off.
|
||||
*/
|
||||
dependsOn?: string
|
||||
/** Receives the `id` to put on the control, so the label governs it. */
|
||||
children: (id: string) => ReactNode
|
||||
}) {
|
||||
const id = useId()
|
||||
return (
|
||||
<div className={`${modal ? frm.mrow : frm.row}${dependsOn != null ? ` ${frm.dependent}` : ''}`}>
|
||||
{/*
|
||||
The pill goes OUTSIDE the `<label>`, and this was measured before being left
|
||||
this way.
|
||||
|
||||
Put inside, the field's accessible name became "ECS IPv4 Prefix
|
||||
Length**Needs Enable EDNS Client Subnet**" and the control **stopped being
|
||||
findable by its own label**. It is exactly what the design rules forbid for the
|
||||
tooltip ("it never replaces the accessible name"), and here it was happening
|
||||
with the pill: a visual reinforcement had eaten the name.
|
||||
|
||||
Outside, the label still governs its control and the pill is still read: it
|
||||
is in the same cell, next to it, and it is ordinary text.
|
||||
*/}
|
||||
{dependsOn == null ? (
|
||||
<label className={modal ? frm.mrowLabel : frm.rowLabel} htmlFor={id}>
|
||||
{label}
|
||||
</label>
|
||||
) : (
|
||||
<div className={`${modal ? frm.mrowLabel : frm.rowLabel} ${frm.withPill}`}>
|
||||
<label htmlFor={id}>{label}</label>
|
||||
<Tag tone="acc">Needs {dependsOn}</Tag>
|
||||
</div>
|
||||
)}
|
||||
<div className={modal ? frm.mrowCtl : frm.rowCtl}>
|
||||
{children(id)}
|
||||
{/* In the MODAL the help stays nested in the control's cell, which is
|
||||
what makes it fall underneath. Its geometry is not touched: the dense-form
|
||||
design measured a form, not a dialog. */}
|
||||
{modal && help != null && <div className={frm.help}>{help}</div>}
|
||||
</div>
|
||||
{/* In the PANEL it is the control's sibling, and that is why it can take up
|
||||
its own column. It is the structural change the third column asks for:
|
||||
while it was inside the cell, no grid rule could get it out. */}
|
||||
{!modal && help != null && <div className={`${frm.rowHelp} ${frm.help}`}>{help}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A row whose label governs no single control (checkbox and radio groups):
|
||||
* upstream uses a `<label>` with no `for` there, because pointing it at one of the
|
||||
* group's controls would lie about what it refers to.
|
||||
*/
|
||||
export function GroupRow({
|
||||
label,
|
||||
help,
|
||||
modal = false,
|
||||
role,
|
||||
children,
|
||||
}: {
|
||||
label: string
|
||||
help?: ReactNode
|
||||
modal?: boolean
|
||||
/*
|
||||
Opt-in: makes the group a `radiogroup` NAMED by the row's label, so a screen
|
||||
reader announces that label before the options and a test can find the group
|
||||
by it. Upstream's markup does not do it; it changes no text and no layout.
|
||||
*/
|
||||
role?: 'radiogroup'
|
||||
children: ReactNode
|
||||
}) {
|
||||
const labelId = useId()
|
||||
return (
|
||||
<div className={modal ? frm.mrow : frm.row}>
|
||||
<div className={modal ? frm.mrowLabel : frm.rowLabel} id={role != null ? labelId : undefined}>
|
||||
{label}
|
||||
</div>
|
||||
<div className={modal ? frm.mrowCtl : frm.rowCtl}>
|
||||
<div className={frm.group} role={role} aria-labelledby={role != null ? labelId : undefined}>
|
||||
{children}
|
||||
</div>
|
||||
{modal && help != null && <div className={frm.help}>{help}</div>}
|
||||
</div>
|
||||
{/* Same as in `Row`, and for the same reason: `GroupRow` draws on the SAME
|
||||
`.row` grid, and twenty places pass it help. If its own stayed nested,
|
||||
two rows of the same panel would put the same thing in two places and
|
||||
the third column would be empty in every other one. */}
|
||||
{!modal && help != null && <div className={`${frm.rowHelp} ${frm.help}`}>{help}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** The standalone help, for when it does not hang off a row. */
|
||||
export function HelpText({ children }: { children: ReactNode }) {
|
||||
return <div className={frm.help}>{children}</div>
|
||||
}
|
||||
+284
@@ -0,0 +1,284 @@
|
||||
import type { ReactElement, SVGProps } from 'react'
|
||||
|
||||
/*
|
||||
The console's icon set, drawn here.
|
||||
|
||||
They used to be Unicode characters (`▣ ◆ ○ ✓ ⊘ ⊞ ⌕ ⚙ ▤ ☺ ≡ ⓘ`), and that has two
|
||||
and a half problems: every operating system paints them with its own font, so the
|
||||
console changed appearance depending on the machine; they share neither stroke
|
||||
weight nor grid, because they are not a set but twelve loose symbols from
|
||||
different tables; and `☺` for Administration is literally a smiley face.
|
||||
|
||||
A library cannot be brought in: the server's CSP is `default-src 'self'` with no
|
||||
`font-src` (DnsWebService.cs:1969-1975), so no CDN and no icon font. They go as
|
||||
inline SVG, which is also what lets them inherit the text colour.
|
||||
|
||||
24 grid, 1.75 stroke and round caps, the same for all twenty-one.
|
||||
*/
|
||||
|
||||
const STROKE = {
|
||||
fill: 'none',
|
||||
stroke: 'currentColor',
|
||||
strokeWidth: 1.75,
|
||||
strokeLinecap: 'round',
|
||||
strokeLinejoin: 'round',
|
||||
} as const
|
||||
|
||||
export type IconName =
|
||||
| 'dashboard' | 'zones' | 'cache' | 'allowed' | 'blocked' | 'apps'
|
||||
| 'dnsclient' | 'settings' | 'dhcp' | 'admin' | 'logs' | 'about'
|
||||
| 'chevronDown' | 'chevronRight' | 'chevronLeft'
|
||||
| 'first' | 'last' | 'close' | 'menu' | 'plus' | 'sort' | 'back' | 'check'
|
||||
| 'edit' | 'power' | 'card' | 'convert' | 'warning' | 'lock'
|
||||
| 'moveUp' | 'moveDown'
|
||||
|
||||
const PATHS: Record<IconName, ReactElement> = {
|
||||
// ── Sections ───────────────────────────────────────────────────────────
|
||||
/* A panel with its readings: the dashboard. */
|
||||
dashboard: (
|
||||
<>
|
||||
<rect x="3" y="3" width="7.5" height="8.5" rx="1.5" />
|
||||
<rect x="13.5" y="3" width="7.5" height="5" rx="1.5" />
|
||||
<rect x="3" y="15" width="7.5" height="6" rx="1.5" />
|
||||
<rect x="13.5" y="11" width="7.5" height="10" rx="1.5" />
|
||||
</>
|
||||
),
|
||||
/* A domain tree: the root and its branches. That is what a zone is. */
|
||||
zones: (
|
||||
<>
|
||||
<path d="M12 3v5" />
|
||||
<path d="M6 21v-3a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v3" />
|
||||
<path d="M12 12v4" />
|
||||
<circle cx="12" cy="4.5" r="1.5" />
|
||||
<circle cx="6" cy="19.5" r="1.5" />
|
||||
<circle cx="18" cy="19.5" r="1.5" />
|
||||
<circle cx="12" cy="10.5" r="1.5" />
|
||||
</>
|
||||
),
|
||||
/* Stacked layers: what is stored waiting to be served again. */
|
||||
cache: (
|
||||
<>
|
||||
<ellipse cx="12" cy="5.5" rx="8" ry="2.75" />
|
||||
<path d="M4 5.5v6c0 1.5 3.6 2.75 8 2.75s8-1.25 8-2.75v-6" />
|
||||
<path d="M4 11.5v6c0 1.5 3.6 2.75 8 2.75s8-1.25 8-2.75v-6" />
|
||||
</>
|
||||
),
|
||||
/* Shield with a tick: what gets through. */
|
||||
allowed: (
|
||||
<>
|
||||
<path d="M12 3 5 6v5.5c0 4.2 2.9 8 7 9.5 4.1-1.5 7-5.3 7-9.5V6z" />
|
||||
<path d="m9 12 2.2 2.2L15.5 10" />
|
||||
</>
|
||||
),
|
||||
/* Shield with a cross: what does not. */
|
||||
blocked: (
|
||||
<>
|
||||
<path d="M12 3 5 6v5.5c0 4.2 2.9 8 7 9.5 4.1-1.5 7-5.3 7-9.5V6z" />
|
||||
<path d="m9.5 9.5 5 5m0-5-5 5" />
|
||||
</>
|
||||
),
|
||||
/* A module that plugs into the server. */
|
||||
apps: (
|
||||
<>
|
||||
<rect x="4" y="8" width="16" height="12" rx="2" />
|
||||
<path d="M9 8V5.5a2.5 2.5 0 0 1 5 0V8" />
|
||||
<path d="M9.5 14h5" />
|
||||
</>
|
||||
),
|
||||
/* A query going out and an answer coming back. */
|
||||
dnsclient: (
|
||||
<>
|
||||
<path d="M4 9h11" />
|
||||
<path d="m11.5 5.5 3.5 3.5-3.5 3.5" />
|
||||
<path d="M20 15H9" />
|
||||
<path d="m12.5 11.5-3.5 3.5 3.5 3.5" />
|
||||
</>
|
||||
),
|
||||
/* The sliders of a settings panel. */
|
||||
settings: (
|
||||
<>
|
||||
<path d="M5 7h9" />
|
||||
<path d="M18 7h1" />
|
||||
<path d="M5 17h4" />
|
||||
<path d="M13 17h6" />
|
||||
<circle cx="16" cy="7" r="2" />
|
||||
<circle cx="11" cy="17" r="2" />
|
||||
</>
|
||||
),
|
||||
/* An assignment: the address handed out to a machine. */
|
||||
dhcp: (
|
||||
<>
|
||||
<rect x="3" y="4" width="18" height="9" rx="2" />
|
||||
<path d="M7.5 8.5h4" />
|
||||
<path d="M12 17v3" />
|
||||
<path d="M8 20h8" />
|
||||
<path d="M12 13v4" />
|
||||
</>
|
||||
),
|
||||
/* A key: who can do what. Not a smiley, not a person. */
|
||||
admin: (
|
||||
<>
|
||||
<circle cx="8" cy="12" r="4" />
|
||||
<path d="M11.8 11h8.2" />
|
||||
<path d="M17 11v3.5" />
|
||||
<path d="M20 11v2.5" />
|
||||
</>
|
||||
),
|
||||
/* Log lines, one shorter because the last one is mid-write. */
|
||||
logs: (
|
||||
<>
|
||||
<path d="M4.5 6.5h15" />
|
||||
<path d="M4.5 10.5h15" />
|
||||
<path d="M4.5 14.5h15" />
|
||||
<path d="M4.5 18.5h8" />
|
||||
</>
|
||||
),
|
||||
/*
|
||||
The notice triangle. It was the only icon the design pass added to the set, and it is drawn
|
||||
with the same grid and the same stroke as the other twenty-seven. Its inside
|
||||
repeats the language of `about` (stem and dot) because they are the same idea seen
|
||||
two ways, and `about` is the circle that belongs to the `Note!`.
|
||||
*/
|
||||
warning: (
|
||||
<>
|
||||
<path d="M12 4.5 21.5 20.5H2.5z" />
|
||||
<path d="M12 10.5v4" />
|
||||
<path d="M12 17v.5" />
|
||||
</>
|
||||
),
|
||||
/*
|
||||
The padlock. It is the second word of the console's two-word vocabulary
|
||||
("amber = you can, padlock = you cannot"), and it was not drawn: the set had the
|
||||
notice triangle but not this.
|
||||
|
||||
Same closed body and same arc as the rest: a grid of 24 and a stroke of
|
||||
*/
|
||||
lock: (
|
||||
<>
|
||||
<rect x="4.5" y="10.5" width="15" height="10" rx="2" />
|
||||
<path d="M8 10.5V7.5a4 4 0 0 1 8 0v3" />
|
||||
<path d="M12 14.5v2" />
|
||||
</>
|
||||
),
|
||||
about: (
|
||||
<>
|
||||
<circle cx="12" cy="12" r="9" />
|
||||
<path d="M12 11v5.5" />
|
||||
<path d="M12 7.75v.5" />
|
||||
</>
|
||||
),
|
||||
|
||||
// ── Controls ──────────────────────────────────────────────────────────
|
||||
chevronDown: <path d="m6 9 6 6 6-6" />,
|
||||
chevronRight: <path d="m9 6 6 6-6 6" />,
|
||||
chevronLeft: <path d="m15 6-6 6 6 6" />,
|
||||
first: (
|
||||
<>
|
||||
<path d="m17 6-6 6 6 6" />
|
||||
<path d="M7.5 6v12" />
|
||||
</>
|
||||
),
|
||||
last: (
|
||||
<>
|
||||
<path d="m7 6 6 6-6 6" />
|
||||
<path d="M16.5 6v12" />
|
||||
</>
|
||||
),
|
||||
close: <path d="m6 6 12 12M18 6 6 18" />,
|
||||
check: <path d="m20 6-11 11-5-5" />,
|
||||
|
||||
// ── Row actions ───────────────────────────────────────────────────────
|
||||
edit: (
|
||||
<>
|
||||
<path d="M11 4H6a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5" />
|
||||
<path d="M18.5 2.5a2.12 2.12 0 0 1 3 3L12 15l-4 1 1-4z" />
|
||||
</>
|
||||
),
|
||||
/* Power on and off: the same symbol for both states, because the "Status"
|
||||
column already says which one it is in. */
|
||||
power: (
|
||||
<>
|
||||
<path d="M12 3v9" />
|
||||
<path d="M18.4 6.6a9 9 0 1 1-12.8 0" />
|
||||
</>
|
||||
),
|
||||
/* Someone's record: "View Details". */
|
||||
card: (
|
||||
<>
|
||||
<rect x="3" y="4" width="18" height="16" rx="2" />
|
||||
<circle cx="9" cy="10" r="2" />
|
||||
<path d="M5.5 17c.7-1.8 2-2.5 3.5-2.5s2.8.7 3.5 2.5" />
|
||||
<path d="M15 9.5h3.5" />
|
||||
<path d="M15 13h3.5" />
|
||||
</>
|
||||
),
|
||||
convert: (
|
||||
<>
|
||||
<path d="M4 8h13" />
|
||||
<path d="m14 5 3 3-3 3" />
|
||||
<path d="M20 16H7" />
|
||||
<path d="m10 13-3 3 3 3" />
|
||||
</>
|
||||
),
|
||||
menu: (
|
||||
<>
|
||||
<path d="M4 7h16" />
|
||||
<path d="M4 12h16" />
|
||||
<path d="M4 17h16" />
|
||||
</>
|
||||
),
|
||||
/* The three dots of a row menu. Filled, not stroked. */
|
||||
plus: (
|
||||
<g fill="currentColor" stroke="none">
|
||||
<circle cx="12" cy="5.5" r="1.6" />
|
||||
<circle cx="12" cy="12" r="1.6" />
|
||||
<circle cx="12" cy="18.5" r="1.6" />
|
||||
</g>
|
||||
),
|
||||
/* The double arrowhead of a sortable column, with no direction yet. */
|
||||
sort: (
|
||||
<>
|
||||
<path d="m8 10 4-4 4 4" />
|
||||
<path d="m8 14 4 4 4-4" />
|
||||
</>
|
||||
),
|
||||
back: (
|
||||
<>
|
||||
<path d="M19 12H5" />
|
||||
<path d="m11 6-6 6 6 6" />
|
||||
</>
|
||||
),
|
||||
/* One line up or down: the row's move buttons in Blocking › Lists. */
|
||||
moveUp: (
|
||||
<>
|
||||
<path d="M12 19V5" />
|
||||
<path d="m6 11 6-6 6 6" />
|
||||
</>
|
||||
),
|
||||
moveDown: (
|
||||
<>
|
||||
<path d="M12 5v14" />
|
||||
<path d="m6 13 6 6 6-6" />
|
||||
</>
|
||||
),
|
||||
}
|
||||
|
||||
export function Icon({
|
||||
name,
|
||||
size = 16,
|
||||
...rest
|
||||
}: { name: IconName; size?: number } & Omit<SVGProps<SVGSVGElement>, 'ref'>) {
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
aria-hidden="true"
|
||||
focusable="false"
|
||||
{...STROKE}
|
||||
{...rest}
|
||||
>
|
||||
{PATHS[name]}
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
Where a dense form's section index goes, decided by measurement on 2026-10-16.
|
||||
|
||||
The dense form's row is `210px 1fr var(--help-col)`, and the `1fr` is the control
|
||||
column: everything left over goes to it. Administration › Permissions puts its
|
||||
index beside its content from `--bp-index` (960) up, and Permissions can, because
|
||||
it has no row grid. Here a column of `--index-col` plus its gap is 188 px taken
|
||||
from the controls: at 1440 the row would go from `210px 552px 360px` to
|
||||
`210px 364px 360px` (measured by forcing the layout), the third signature `Sso.tsx`
|
||||
once refused for the same reason.
|
||||
|
||||
So the COLUMN appears only where the screen is wide enough to give the controls,
|
||||
beside it, at least what they have at 1440 without it: 552 px. The screen at 1440
|
||||
is 1,176 px wide (the window less the 216 px side panel and the 48 px of padding),
|
||||
so the line is 1,176 + 188 = **1,364 px of screen**, about a 1,628 px window.
|
||||
Measured at 1680: `210px 604px 360px` with the column, against `210px 792px 360px`
|
||||
without.
|
||||
|
||||
Everywhere below that line the index is the STRIP Permissions shows under 960, the
|
||||
same primitive with `strip`, above the form: it takes height and no width, so the
|
||||
row at 1440 keeps its `552px`. It pins at the top as it scrolls (`ui/SectionIndex`),
|
||||
and the form under it is told so through `--pinned` (below), which its block titles
|
||||
and anchors read.
|
||||
|
||||
It is a container query and not a window breakpoint because the quantity it
|
||||
protects is the screen's width, whatever the chrome around it takes. The room is
|
||||
its own container so whoever uses it needs to declare nothing.
|
||||
*/
|
||||
.room {
|
||||
container-type: inline-size;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
/* Between the strip and the form: Permissions' strip keeps the same distance
|
||||
(`Admin.module.css`, `.withIndex > :last-child`). */
|
||||
gap: var(--s-10);
|
||||
}
|
||||
|
||||
/* The slot steps aside so the strip's own `position: sticky` travels down the whole
|
||||
room and not only down a slot as tall as itself. */
|
||||
.strip { display: contents; }
|
||||
|
||||
/*
|
||||
`--pinned`: what is pinned above the form at this width, for its block titles to pin
|
||||
below (`ui/PanelForm.module.css`) and for a jump from the index to land below. Here
|
||||
the strip, on top of whatever was already pinned; beside the column, only that.
|
||||
*/
|
||||
.form { --pinned: calc(var(--stuck-top, 0px) + var(--index-strip)); }
|
||||
|
||||
.column { min-width: 0; }
|
||||
|
||||
.side { display: none; }
|
||||
|
||||
@container (min-width: 1364px) {
|
||||
.strip { display: none; }
|
||||
|
||||
.form { --pinned: var(--stuck-top, 0px); }
|
||||
|
||||
.withIndex {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) var(--index-col);
|
||||
gap: var(--s-10);
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
/* The slot steps aside so that the index itself is the grid item, which is what
|
||||
its own `position: sticky` needs to travel down the whole form. */
|
||||
.side { display: contents; }
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { SectionIndex } from './SectionIndex'
|
||||
import styles from './IndexedForm.module.css'
|
||||
|
||||
/*
|
||||
A dense form with its section index (`ui/SectionIndex`): beside the form where the
|
||||
form can spare the width, a strip above it everywhere else. Settings' long panes
|
||||
and Administration › SSO use it; the decision about widths is in
|
||||
`IndexedForm.module.css`.
|
||||
|
||||
The index is drawn twice and only one is ever shown: the strip and the column are
|
||||
the same entries and the same `active`, and which one shows is the screen's width,
|
||||
which only CSS knows without a measuring pass. The hidden one is `display: none`,
|
||||
so it is out of the accessibility tree too: a reader meets one index, not two.
|
||||
|
||||
The structure around `children` never changes with `sections`, so a form that reads
|
||||
its own sections back from the page (Settings does) is not remounted when they
|
||||
arrive.
|
||||
*/
|
||||
export function IndexedForm({
|
||||
sections,
|
||||
active,
|
||||
children,
|
||||
}: {
|
||||
/** The sections, in page order; with none there is no index and the form keeps its width. */
|
||||
sections: { id: string; label: string }[]
|
||||
/** The section in view (`ui/useSectionInView`). */
|
||||
active?: string
|
||||
children: ReactNode
|
||||
}) {
|
||||
const on = sections.length > 0
|
||||
return (
|
||||
<div className={styles.room}>
|
||||
{on && (
|
||||
<div className={styles.strip}>
|
||||
<SectionIndex sections={sections} active={active} strip />
|
||||
</div>
|
||||
)}
|
||||
<div className={on ? `${styles.form} ${styles.withIndex}` : undefined}>
|
||||
<div className={styles.column}>{children}</div>
|
||||
{on && (
|
||||
<div className={styles.side}>
|
||||
<SectionIndex sections={sections} active={active} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
/*
|
||||
The permissions matrix. See `Matrix.tsx` for why it exists at all; here is what is
|
||||
decided about how it looks.
|
||||
|
||||
Two densities share this sheet because they are the same object read at two
|
||||
distances: the concession map (eleven sections across, one row per subject) and
|
||||
the eleven sections themselves, three verbs across. Splitting them into two
|
||||
modules is how this console once ended up with seven containers.
|
||||
*/
|
||||
|
||||
/* The hidden name is `ui/text`'s: the update dialog is its second user, and the
|
||||
rule the two share moved there when the second one appeared. */
|
||||
.sr { composes: sr from './text.module.css'; }
|
||||
|
||||
.wrap { min-width: 0; position: relative; }
|
||||
|
||||
/* The table's name, drawn: it is the small-caps label the two columns of a
|
||||
section already carried above them. */
|
||||
.caption {
|
||||
composes: smallCaps from './label.module.css';
|
||||
text-align: left;
|
||||
padding-bottom: var(--s-4);
|
||||
}
|
||||
|
||||
/* Only the map scrolls sideways: eleven sections do not fit at 390 and the
|
||||
subject column stays put so a row never loses whose it is. */
|
||||
.scrolls { overflow-x: auto; }
|
||||
|
||||
.table {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.table th,
|
||||
.table td {
|
||||
border-bottom: 1px solid var(--line2);
|
||||
padding: var(--s-3) var(--s-5);
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.table tr:last-child th,
|
||||
.table tr:last-child td { border-bottom: 0; }
|
||||
|
||||
/*
|
||||
The header row carries a background, and it is `--pan` and not `Table`'s `--pan2`:
|
||||
this is a nested, read-only table inside a panel, not the console's data table,
|
||||
so it does not sit on the raised step.
|
||||
|
||||
It goes on the WHOLE row and not only on the sticky corner. Measured with
|
||||
`dev/uniformity.js` on 2026-09-04: with it only on the corner, the map and the
|
||||
eleven sections came out as TWO `table` signatures (`rgb(25, 28, 31)` against
|
||||
`rgba(0, 0, 0, 0)`) for what is one object at its two densities. Inside a panel
|
||||
the colour is the one already behind it, so nothing changes to the eye; what
|
||||
changes is that the sticky corner stops being a special case.
|
||||
*/
|
||||
.table thead th { background: var(--pan); }
|
||||
|
||||
/* The header of a column: the console's one small-caps label. */
|
||||
.verb,
|
||||
.who {
|
||||
composes: smallCaps from './label.module.css';
|
||||
white-space: nowrap;
|
||||
height: var(--row-header);
|
||||
}
|
||||
|
||||
.verb { text-align: center; width: 46px; }
|
||||
.who { text-align: left; }
|
||||
|
||||
/* The subject: the row's entity, so it weighs more than the marks beside it. */
|
||||
.subject {
|
||||
text-align: left;
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--t-4);
|
||||
font-weight: 400;
|
||||
color: var(--ink);
|
||||
/* Between words: `anywhere` let the column shrink until a name broke letter by letter. */
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
/*
|
||||
In the map the subject does NOT wrap: it is a sticky column and a name broken
|
||||
across two lines ("DHCP Administrator / s") stops being a name. The table already
|
||||
scrolls sideways, so the column is as wide as the longest name and the sections
|
||||
move past it.
|
||||
*/
|
||||
.dense .subject { white-space: nowrap; overflow-wrap: normal; }
|
||||
|
||||
/*
|
||||
The population header of the map. It spans the whole width because it labels the
|
||||
rows under it, not a column.
|
||||
*/
|
||||
.group {
|
||||
composes: smallCaps from './label.module.css';
|
||||
text-align: left;
|
||||
background: var(--pan2);
|
||||
padding-top: var(--s-4);
|
||||
padding-bottom: var(--s-4);
|
||||
}
|
||||
|
||||
/*
|
||||
The column that stays while the rest scrolls. It carries its own background:
|
||||
without one, the eleven sections would slide underneath it and show through.
|
||||
*/
|
||||
.stick {
|
||||
position: sticky;
|
||||
left: 0;
|
||||
z-index: 1;
|
||||
background: var(--pan);
|
||||
}
|
||||
|
||||
.group.stick { background: var(--pan2); }
|
||||
|
||||
.cell { text-align: center; width: 46px; }
|
||||
|
||||
/*
|
||||
The mark: `--ok`, not amber.
|
||||
|
||||
Amber is this console's word for "you can press this", and nothing in this list
|
||||
can be pressed: it is edited in `Edit Permissions`. Painting 84 read-only states
|
||||
in the colour of action was the loudest thing on the screen and it was saying the
|
||||
wrong word.
|
||||
*/
|
||||
.mark { margin: 0 auto; display: block; }
|
||||
|
||||
/*
|
||||
`base.css` draws the console's checkbox by hand (it is not the browser's, so
|
||||
`accent-color` does nothing to it) and paints it `--acc` when ticked. Only the
|
||||
colour is overridden here, not the shape: the box, the sunken shadow and the drawn
|
||||
tick stay the shared ones, so this is still the same checkbox and not a second
|
||||
idea of what one looks like. The tick's stroke goes to `--ok-bg` for the same
|
||||
reason the amber one is `--on-acc`: it is the ink of its own fill.
|
||||
*/
|
||||
/* The selector carries the type and the attribute because `base.css`'s does:
|
||||
`input[type='checkbox']:checked` outweighs a bare class, so overriding it from
|
||||
a module means matching its shape and adding the class. */
|
||||
input[type='checkbox'].mark:checked {
|
||||
background-color: var(--ok);
|
||||
border-color: var(--ok);
|
||||
background-image:
|
||||
var(--glyph-tick-ok),
|
||||
var(--shine-check);
|
||||
}
|
||||
|
||||
/*
|
||||
And it is NOT dimmed, although it is disabled.
|
||||
|
||||
`base.css` takes a disabled control to 0.45 because a control you cannot use has
|
||||
to say so. These are not controls you cannot use: they are the datum this screen
|
||||
exists to show, and a permission at 45 % reads as "not applicable" when it means
|
||||
"granted".
|
||||
*/
|
||||
input[type='checkbox'].mark:disabled { cursor: default; opacity: 1; box-shadow: var(--sunken); }
|
||||
|
||||
input[type='checkbox'].mark:disabled:checked { box-shadow: var(--edge-strong); }
|
||||
|
||||
/*
|
||||
The map's cell: three marks, one per verb, in View · Modify · Delete order.
|
||||
|
||||
Its padding is NOT trimmed to squeeze eleven sections in: `dev/uniformity.js`
|
||||
signs a table by its header and its cell density, so a second density here would
|
||||
make `Matrix` two table objects instead of one, and the map is the same primitive
|
||||
at its second density, not another table. The map scrolls sideways anyway.
|
||||
*/
|
||||
.marks { text-align: center; }
|
||||
|
||||
.pips { display: inline-flex; gap: var(--s-2); }
|
||||
|
||||
/*
|
||||
A granted verb is filled; a denied one is an empty box and NOT a gap. The absence
|
||||
has to be visible: an empty cell and a cell of three empty boxes say different
|
||||
things, and only one of them is "this subject is in this section".
|
||||
*/
|
||||
.pip {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 2px;
|
||||
border: 1px solid var(--line);
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.pip[data-on='true'] { background: var(--ok); border-color: var(--ok); }
|
||||
|
||||
/* Upstream's "No user permissions" / "No group permissions". */
|
||||
.none {
|
||||
text-align: center;
|
||||
color: var(--faint);
|
||||
font-size: var(--t-4);
|
||||
padding: var(--s-7) var(--s-5);
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { Matrix, MatrixCell, MatrixEmpty, MatrixGroup, MatrixMarks, MatrixRow } from './Matrix'
|
||||
import { ForceBlock } from './Confirm'
|
||||
|
||||
/*
|
||||
What these check is the ONE thing this primitive had to resolve rather than merely
|
||||
draw: that a cell of the permissions matrix has a name written in the DOM, and
|
||||
that the grid is a table with both axes declared.
|
||||
|
||||
The negative test matters as much as the positive one: before this primitive the
|
||||
same 84 cells rendered inside a CSS grid, so `getByRole('table')` found nothing
|
||||
and every cell's name was whatever the reader synthesised by position.
|
||||
*/
|
||||
|
||||
const COLUMNS = [
|
||||
{ label: 'Username', wide: true },
|
||||
{ label: 'View' },
|
||||
{ label: 'Modify' },
|
||||
{ label: 'Delete' },
|
||||
]
|
||||
|
||||
describe('Matrix', () => {
|
||||
it('is a table, and names it with a literal that already exists', () => {
|
||||
render(
|
||||
<Matrix caption="User Permissions" columns={COLUMNS}>
|
||||
<MatrixRow subject="admin">
|
||||
<MatrixCell name="Zones · admin · View" granted />
|
||||
<MatrixCell name="Zones · admin · Modify" granted={false} />
|
||||
<MatrixCell name="Zones · admin · Delete" granted={false} />
|
||||
</MatrixRow>
|
||||
</Matrix>,
|
||||
)
|
||||
expect(screen.getByRole('table', { name: 'User Permissions' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('declares both axes: the verbs as columns and the subject as its row', () => {
|
||||
render(
|
||||
<Matrix caption="User Permissions" columns={COLUMNS}>
|
||||
<MatrixRow subject="admin">
|
||||
<MatrixCell name="Zones · admin · View" granted />
|
||||
<MatrixCell name="Zones · admin · Modify" granted={false} />
|
||||
<MatrixCell name="Zones · admin · Delete" granted={false} />
|
||||
</MatrixRow>
|
||||
</Matrix>,
|
||||
)
|
||||
for (const verb of ['View', 'Modify', 'Delete']) {
|
||||
expect(screen.getByRole('columnheader', { name: verb })).toHaveAttribute('scope', 'col')
|
||||
}
|
||||
expect(screen.getByRole('rowheader', { name: 'admin' })).toHaveAttribute('scope', 'row')
|
||||
})
|
||||
|
||||
it('every cell carries {Section} · {Subject} · {Verb}, and its state', () => {
|
||||
render(
|
||||
<Matrix caption="User Permissions" columns={COLUMNS}>
|
||||
<MatrixRow subject="admin">
|
||||
<MatrixCell name="Zones · admin · View" granted />
|
||||
<MatrixCell name="Zones · admin · Modify" granted={false} />
|
||||
<MatrixCell name="Zones · admin · Delete" granted={false} />
|
||||
</MatrixRow>
|
||||
</Matrix>,
|
||||
)
|
||||
expect(screen.getByRole('checkbox', { name: 'Zones · admin · View' })).toBeChecked()
|
||||
expect(screen.getByRole('checkbox', { name: 'Zones · admin · Modify' })).not.toBeChecked()
|
||||
})
|
||||
|
||||
it('the cell is read only: it is a state, and it is not editable from here', () => {
|
||||
render(
|
||||
<Matrix caption="Group Permissions" columns={COLUMNS}>
|
||||
<MatrixRow subject="Everyone">
|
||||
<MatrixCell name="Cache · Everyone · View" granted />
|
||||
</MatrixRow>
|
||||
</Matrix>,
|
||||
)
|
||||
expect(screen.getByRole('checkbox', { name: 'Cache · Everyone · View' })).toBeDisabled()
|
||||
})
|
||||
|
||||
it('says which population a run of rows belongs to', () => {
|
||||
render(
|
||||
<Matrix caption="Permissions" columns={COLUMNS} dense>
|
||||
<MatrixGroup label="Group Permissions" span={4} />
|
||||
<MatrixRow subject="Administrators" stick>
|
||||
<MatrixMarks
|
||||
verbs={[
|
||||
{ verb: 'View', granted: true },
|
||||
{ verb: 'Modify', granted: true },
|
||||
{ verb: 'Delete', granted: false },
|
||||
]}
|
||||
/>
|
||||
</MatrixRow>
|
||||
</Matrix>,
|
||||
)
|
||||
expect(screen.getByRole('rowheader', { name: 'Group Permissions' })).toHaveAttribute(
|
||||
'scope',
|
||||
'rowgroup',
|
||||
)
|
||||
})
|
||||
|
||||
it('a map cell says the verbs it grants, and says nothing when it grants none', () => {
|
||||
render(
|
||||
<Matrix caption="Permissions" columns={COLUMNS} dense>
|
||||
<MatrixRow subject="ops">
|
||||
<MatrixMarks
|
||||
verbs={[
|
||||
{ verb: 'View', granted: true },
|
||||
{ verb: 'Modify', granted: false },
|
||||
{ verb: 'Delete', granted: false },
|
||||
]}
|
||||
/>
|
||||
<MatrixMarks
|
||||
verbs={[
|
||||
{ verb: 'View', granted: false },
|
||||
{ verb: 'Modify', granted: false },
|
||||
{ verb: 'Delete', granted: false },
|
||||
]}
|
||||
/>
|
||||
</MatrixRow>
|
||||
</Matrix>,
|
||||
)
|
||||
const cells = screen.getAllByRole('cell')
|
||||
expect(cells[0]).toHaveTextContent('View')
|
||||
expect(cells[1]).toHaveTextContent('')
|
||||
})
|
||||
|
||||
it('keeps upstream literal when there is nothing to show', () => {
|
||||
render(
|
||||
<Matrix caption="User Permissions" columns={COLUMNS}>
|
||||
<MatrixEmpty text="No user permissions" span={4} />
|
||||
</Matrix>,
|
||||
)
|
||||
expect(screen.getByText('No user permissions')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('ForceBlock', () => {
|
||||
it('carries upstream label and help, and arms only when ticked', () => {
|
||||
const help =
|
||||
'Enabling this option will cause this Primary node to delete the Cluster for itself even when other Secondary nodes still exist, orphaning them.'
|
||||
const { rerender, container } = render(
|
||||
<ForceBlock label="Force Delete Cluster" help={help} checked={false} onChange={() => {}} />,
|
||||
)
|
||||
expect(screen.getByRole('checkbox', { name: 'Force Delete Cluster' })).not.toBeChecked()
|
||||
expect(screen.getByText(help)).toBeInTheDocument()
|
||||
expect(container.querySelector('[data-armed="true"]')).toBeNull()
|
||||
|
||||
rerender(<ForceBlock label="Force Delete Cluster" help={help} checked onChange={() => {}} />)
|
||||
expect(container.querySelector('[data-armed="true"]')).not.toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,197 @@
|
||||
import { useId, type ReactNode } from 'react'
|
||||
import styles from './Matrix.module.css'
|
||||
|
||||
/*
|
||||
The permissions matrix: two axes, read only, and every cell with a name.
|
||||
|
||||
It is a primitive of its own because none of the
|
||||
twenty-eight already there does what `Administration > Permissions` needs:
|
||||
|
||||
· `Table` orders rows of data. Its columns are labels, not an axis: nothing in
|
||||
it says that a cell belongs to a column AND to a row.
|
||||
· `EditableTable` edits, and this list does not edit; the editing happens in
|
||||
`Edit Permissions`.
|
||||
· `Check` is a control, and these cells are a state.
|
||||
|
||||
## What it fixes, and it is not decoration
|
||||
|
||||
Before this, the eleven sections were a CSS grid (`_permCols_`): no `<table>`, no
|
||||
`<th>`, no `<tbody>`. Measured in the browser on 2026-09-04: no `<table>` at all on
|
||||
`/admin/permissions/`, with 84 cells inside. A screen reader moving through it had
|
||||
no rows and no columns to move by, so "which of these is Modify" could only be
|
||||
answered by counting.
|
||||
|
||||
So the three things this contributes:
|
||||
|
||||
1. `th[scope=col]` on the three verbs and `th[scope=row]` on the subject, so the
|
||||
reader announces both headers for every cell.
|
||||
2. `th[scope=rowgroup]` for the concession map, which puts users and groups in
|
||||
one table and has to say which population a row belongs to.
|
||||
3. A NAME per cell, written in the DOM and not deduced: a visually hidden
|
||||
`<label>` with `{Section} · {Subject} · {Verb}`.
|
||||
|
||||
## Why the cell is still an `<input type="checkbox" disabled>`
|
||||
|
||||
The drawing proposed replacing it with a glyph, and the argument is good: these
|
||||
are not controls, and amber is this console's word for "you can". Half of it is
|
||||
taken: the mark is `--ok` and no longer amber, because amber is for the things you
|
||||
can press and this list is read only.
|
||||
|
||||
The control itself stays, and for a reason that is not inertia: a checkbox
|
||||
announces its own state, in the reader's own language, with no literal to write.
|
||||
A glyph does not, so it would need the words for granted and not granted, and
|
||||
upstream has no such words. The rule is that where there is no upstream literal,
|
||||
none is written. Keeping the checkbox is what lets the cell be
|
||||
named without inventing copy.
|
||||
|
||||
It costs nothing in the tab order either: a `disabled` input is not focusable, so
|
||||
the 84 cells were never tab stops to begin with.
|
||||
*/
|
||||
|
||||
export function Matrix({
|
||||
caption,
|
||||
columns,
|
||||
children,
|
||||
className,
|
||||
dense = false,
|
||||
captionHidden = false,
|
||||
}: {
|
||||
/*
|
||||
The table's name, and it is DRAWN: "User Permissions", "Group Permissions" are
|
||||
literals the screen already showed as a title above each column, so they become
|
||||
the caption rather than disappearing into a heading beside it. It is always an
|
||||
existing literal, never a new one.
|
||||
*/
|
||||
caption: string
|
||||
/** The column axis. `label` is drawn; a column whose label is only for the
|
||||
* reader passes `hidden`. */
|
||||
columns: { label: string; hidden?: boolean; wide?: boolean }[]
|
||||
children: ReactNode
|
||||
className?: string
|
||||
/** The second density: the concession map, where a cell carries three marks
|
||||
* instead of one. */
|
||||
dense?: boolean
|
||||
/** Only for the map: its name would repeat the `h1` two centimetres below it,
|
||||
* so it stays for the reader and not for the eye. */
|
||||
captionHidden?: boolean
|
||||
}) {
|
||||
return (
|
||||
<div className={[styles.wrap, dense ? styles.scrolls : null, className].filter(Boolean).join(' ')}>
|
||||
<table className={[styles.table, dense ? styles.dense : null].filter(Boolean).join(' ')}>
|
||||
<caption className={captionHidden ? styles.sr : styles.caption}>{caption}</caption>
|
||||
<thead>
|
||||
<tr>
|
||||
{columns.map((c) => (
|
||||
<th
|
||||
key={c.label}
|
||||
scope="col"
|
||||
className={[c.wide ? styles.who : styles.verb, c.wide && dense ? styles.stick : null]
|
||||
.filter(Boolean)
|
||||
.join(' ')}
|
||||
>
|
||||
{/* The corner cell of a cross-tab labels nothing: it is neither a
|
||||
section nor a verb. It stays empty rather than being given an
|
||||
invented name; the row headers under it say what they are. */}
|
||||
{c.label === '' ? null : c.hidden ? <span className={styles.sr}>{c.label}</span> : c.label}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>{children}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** The population a run of rows belongs to: `th[scope=rowgroup]`. Only the
|
||||
* concession map needs it; the eleven sections say it in their caption. */
|
||||
export function MatrixGroup({ label, span }: { label: string; span: number }) {
|
||||
return (
|
||||
<tr>
|
||||
<th scope="rowgroup" colSpan={span} className={styles.group}>
|
||||
{label}
|
||||
</th>
|
||||
</tr>
|
||||
)
|
||||
}
|
||||
|
||||
/** A row: its subject as `th[scope=row]`, and its cells. */
|
||||
export function MatrixRow({
|
||||
subject,
|
||||
children,
|
||||
stick = false,
|
||||
}: {
|
||||
subject: string
|
||||
children: ReactNode
|
||||
/** In the map the subject column stays put while the eleven sections scroll:
|
||||
* without it, a row loses whose it is as soon as it moves. */
|
||||
stick?: boolean
|
||||
}) {
|
||||
return (
|
||||
<tr>
|
||||
<th scope="row" className={[styles.subject, stick ? styles.stick : null].filter(Boolean).join(' ')}>
|
||||
{subject}
|
||||
</th>
|
||||
{children}
|
||||
</tr>
|
||||
)
|
||||
}
|
||||
|
||||
/*
|
||||
One permission: granted or not, and named.
|
||||
|
||||
`name` is `{Section} · {Subject} · {Verb}` and every one of its three parts is a
|
||||
literal that already exists on the screen. Nothing is composed that the user
|
||||
cannot also read.
|
||||
*/
|
||||
export function MatrixCell({ name, granted }: { name: string; granted: boolean }) {
|
||||
const id = useId()
|
||||
return (
|
||||
<td className={styles.cell}>
|
||||
<label className={styles.sr} htmlFor={id}>
|
||||
{name}
|
||||
</label>
|
||||
<input
|
||||
id={id}
|
||||
type="checkbox"
|
||||
className={styles.mark}
|
||||
checked={granted}
|
||||
disabled
|
||||
readOnly
|
||||
/>
|
||||
</td>
|
||||
)
|
||||
}
|
||||
|
||||
/*
|
||||
The map's cell: the three verbs at once.
|
||||
|
||||
The marks are decoration (the reader gets the row's subject, the column's section
|
||||
and the names of the verbs that ARE granted, which is the whole content), so they
|
||||
carry `aria-hidden` and the cell says its verbs in text. A cell with nothing
|
||||
granted says nothing, exactly as upstream's empty cell does.
|
||||
*/
|
||||
export function MatrixMarks({ verbs }: { verbs: { verb: string; granted: boolean }[] }) {
|
||||
const granted = verbs.filter((v) => v.granted).map((v) => v.verb)
|
||||
return (
|
||||
<td className={styles.marks}>
|
||||
{granted.length > 0 && <span className={styles.sr}>{granted.join(', ')}</span>}
|
||||
<span className={styles.pips} aria-hidden="true">
|
||||
{verbs.map((v) => (
|
||||
<span key={v.verb} className={styles.pip} data-on={v.granted} />
|
||||
))}
|
||||
</span>
|
||||
</td>
|
||||
)
|
||||
}
|
||||
|
||||
/** The "there is nothing here" row, with upstream's literal. */
|
||||
export function MatrixEmpty({ text, span }: { text: string; span: number }) {
|
||||
return (
|
||||
<tr>
|
||||
<td colSpan={span} className={styles.none}>
|
||||
{text}
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/* A row's `⋮` menu. It used to live inside Zones; every table uses it. */
|
||||
|
||||
.menu { position:relative; display:inline-block; }
|
||||
|
||||
/*
|
||||
The quiet `⋮` (the `quiet` prop): no frame, no fill and no shadow at rest; the
|
||||
button's own ones come back on hover, on keyboard focus and while its menu is open.
|
||||
Two classes against Button's one, so the order the modules load in does not decide.
|
||||
*/
|
||||
.menu .quiet:not(:hover):not(:focus-visible):not([aria-expanded='true']) {
|
||||
border-color: transparent;
|
||||
background: transparent;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
/* The trigger that is a whole row: the account one, at the foot of the sidebar. */
|
||||
.menuWidth { position: relative; }
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
width: 100%;
|
||||
gap: var(--s-3);
|
||||
padding: var(--s-4) var(--s-5);
|
||||
border: 0;
|
||||
border-radius: var(--r-2);
|
||||
background: none;
|
||||
color: var(--ink);
|
||||
font: inherit;
|
||||
font-size: var(--t-4);
|
||||
cursor: pointer;
|
||||
}
|
||||
.row:hover { background: var(--hover-strong); }
|
||||
.menuList { display:flex; flex-direction:column; }
|
||||
.sep { height:1px; margin: var(--s-2) var(--s-3); background:var(--line); }
|
||||
.menuList button { text-align:left; border:0; background:transparent; color:var(--mute); /* Longhands and not the `font:` shorthand: `inherit` is not valid as a
|
||||
component of a shorthand (only as the whole value), so the declaration was
|
||||
invalid and the browser dropped it. The menu items had always carried the
|
||||
browser's default size and weight (13 px) instead of the console's. */
|
||||
font-family: inherit;
|
||||
font-size: var(--t-4);
|
||||
font-weight: 400;
|
||||
line-height: 1.2; padding: var(--s-4) var(--s-6); border-radius: var(--r-2); cursor:pointer; }
|
||||
.menuList button:hover,
|
||||
.menuList button:focus-visible { background:var(--hover-strong); color:var(--ink); }
|
||||
.menuList button:disabled { opacity:.4; cursor:default; }
|
||||
|
||||
/*
|
||||
Destructive things get marked, and here they were not.
|
||||
|
||||
`Menu.tsx` says "destructive things go in here" and `ui/Table.module.css` says
|
||||
"delete keeps its colour". The fact fell between the two sentences: all SEVEN
|
||||
delete actions in the console (Delete Zone, Remove Lease, Delete Scope, Delete
|
||||
Session, Delete User, Delete Group, Remove Node) were painted the same grey as
|
||||
"Export Zone". And in four of the six menus the destructive one is the ONLY
|
||||
option: you opened a menu whose entire content was an action with no undo, without
|
||||
a single signal that it was one.
|
||||
|
||||
It goes red and not amber for a measured reason, not a taste one: `--warn` is
|
||||
`rgb(251,191,36)` and `--acc` is `rgb(245,165,36)` (both are the same amber), so an
|
||||
orange option would read as the accent colour, which in this console means "this
|
||||
is the recommended action". Exactly the opposite. `--dan` gives 6.19:1 over the
|
||||
menu background.
|
||||
*/
|
||||
.menuList button[data-variant='danger'] { color: var(--dan); }
|
||||
|
||||
.menuList button[data-variant='danger']:hover,
|
||||
.menuList button[data-variant='danger']:focus-visible {
|
||||
background: var(--dan-fill);
|
||||
color: var(--on-dan);
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { fireEvent, render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { Menu } from './Menu'
|
||||
|
||||
/*
|
||||
For this piece, jsdom can only answer half: there is no layout, so
|
||||
`getBoundingClientRect()` returns zeros and there is no point asserting here that
|
||||
the menu flips when it does not fit (that is measured in the browser, with the
|
||||
window at 900 and at 560 px). What it can answer is the behaviour, and in
|
||||
particular the bug the flipping introduced: the handler that closes the menu on
|
||||
scroll is shared with `resize`, and there the `target` is `window`, which is not a
|
||||
node.
|
||||
*/
|
||||
function Sample({ asRow = false }: { asRow?: boolean } = {}) {
|
||||
return (
|
||||
<Menu label="Options" text="Options" asRow={asRow}>
|
||||
{(close) => (
|
||||
<>
|
||||
<button onClick={close}>One</button>
|
||||
<button onClick={close}>Two</button>
|
||||
</>
|
||||
)}
|
||||
</Menu>
|
||||
)
|
||||
}
|
||||
|
||||
describe('Menu', () => {
|
||||
it('resizing the window with the menu open closes it, and does not blow up', async () => {
|
||||
render(<Sample />)
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Options' }))
|
||||
expect(screen.getByRole('menu')).toBeInTheDocument()
|
||||
|
||||
fireEvent(window, new Event('resize'))
|
||||
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('it reports on opening, for whoever needs to check the state just before', async () => {
|
||||
const openOnes: number[] = []
|
||||
render(
|
||||
<Menu label="Options" text="Options" onOpen={() => openOnes.push(1)}>
|
||||
{() => <button role="menuitem">One</button>}
|
||||
</Menu>,
|
||||
)
|
||||
const b = screen.getByRole('button', { name: 'Options' })
|
||||
await userEvent.click(b)
|
||||
await userEvent.click(b) // closing does not report
|
||||
await userEvent.click(b)
|
||||
expect(openOnes).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('Escape closes it and returns the focus to the trigger', async () => {
|
||||
render(<Sample />)
|
||||
const b = screen.getByRole('button', { name: 'Options' })
|
||||
await userEvent.click(b)
|
||||
fireEvent.keyDown(document, { key: 'Escape' })
|
||||
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
|
||||
expect(document.activeElement).toBe(b)
|
||||
})
|
||||
|
||||
/*
|
||||
The row trigger is the account one, at the foot of the sidebar. It was written
|
||||
separately, with its own state, and it had forgotten precisely the three things
|
||||
you cannot see by looking at it open: it did not close on an outside click, nor
|
||||
on Escape, nor on scroll. Now it is this same menu, so it inherits them; this
|
||||
test is what stops it being written on its own again.
|
||||
*/
|
||||
it('the row trigger closes on an outside click, just like the button one', async () => {
|
||||
render(
|
||||
<>
|
||||
<Sample asRow />
|
||||
<p>outside</p>
|
||||
</>,
|
||||
)
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Options' }))
|
||||
expect(screen.getByRole('menu')).toBeInTheDocument()
|
||||
await userEvent.click(screen.getByText('outside'))
|
||||
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
/*
|
||||
The keyboard pattern, which is what `role="menu"` promises. It was carried
|
||||
without any of it until 2026-09-07: the role was there and the items were loose
|
||||
buttons. These tests are the promise, and they are written against the
|
||||
primitive rather than against any call site, because the call sites render
|
||||
plain buttons and it is the menu that turns them into items.
|
||||
*/
|
||||
describe('the keyboard the role promises', () => {
|
||||
function Three() {
|
||||
return (
|
||||
<Menu label="Options" text="Options">
|
||||
{() => (
|
||||
<>
|
||||
<button>One</button>
|
||||
<button disabled>Two</button>
|
||||
<button>Three</button>
|
||||
</>
|
||||
)}
|
||||
</Menu>
|
||||
)
|
||||
}
|
||||
|
||||
it('the items are menu items, and a disabled one is not', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Three />)
|
||||
await user.click(screen.getByRole('button', { name: 'Options' }))
|
||||
expect(screen.getAllByRole('menuitem').map((e) => e.textContent)).toEqual(['One', 'Three'])
|
||||
expect(screen.getByRole('button', { name: 'Two' })).toBeDisabled()
|
||||
})
|
||||
|
||||
it('opening puts the focus on the first item', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Three />)
|
||||
await user.click(screen.getByRole('button', { name: 'Options' }))
|
||||
expect(screen.getByRole('menuitem', { name: 'One' })).toHaveFocus()
|
||||
})
|
||||
|
||||
/* One tab stop for the whole menu, not one per item: that is the difference
|
||||
between a menu and a pile of buttons. */
|
||||
it('only the focused item is a tab stop', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Three />)
|
||||
await user.click(screen.getByRole('button', { name: 'Options' }))
|
||||
expect(screen.getByRole('menuitem', { name: 'One' })).toHaveAttribute('tabindex', '0')
|
||||
expect(screen.getByRole('menuitem', { name: 'Three' })).toHaveAttribute('tabindex', '-1')
|
||||
})
|
||||
|
||||
it('the arrows move, they wrap, and they skip what is disabled', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Three />)
|
||||
await user.click(screen.getByRole('button', { name: 'Options' }))
|
||||
await user.keyboard('{ArrowDown}')
|
||||
expect(screen.getByRole('menuitem', { name: 'Three' })).toHaveFocus()
|
||||
await user.keyboard('{ArrowDown}')
|
||||
expect(screen.getByRole('menuitem', { name: 'One' })).toHaveFocus()
|
||||
await user.keyboard('{ArrowUp}')
|
||||
expect(screen.getByRole('menuitem', { name: 'Three' })).toHaveFocus()
|
||||
})
|
||||
|
||||
it('Home and End go to the ends', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Three />)
|
||||
await user.click(screen.getByRole('button', { name: 'Options' }))
|
||||
await user.keyboard('{End}')
|
||||
expect(screen.getByRole('menuitem', { name: 'Three' })).toHaveFocus()
|
||||
await user.keyboard('{Home}')
|
||||
expect(screen.getByRole('menuitem', { name: 'One' })).toHaveFocus()
|
||||
})
|
||||
|
||||
it('the down arrow opens it from the trigger, without a click', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Three />)
|
||||
screen.getByRole('button', { name: 'Options' }).focus()
|
||||
await user.keyboard('{ArrowDown}')
|
||||
expect(await screen.findByRole('menuitem', { name: 'One' })).toHaveFocus()
|
||||
})
|
||||
|
||||
it('Tab leaves the menu instead of walking through it', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Three />)
|
||||
await user.click(screen.getByRole('button', { name: 'Options' }))
|
||||
await user.keyboard('{Tab}')
|
||||
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
})
|
||||
+256
@@ -0,0 +1,256 @@
|
||||
import { Button } from './Button'
|
||||
import { useEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type ReactNode, type RefObject } from 'react'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
||||
import styles from './Menu.module.css'
|
||||
import { Icon, type IconName } from './Icon'
|
||||
|
||||
/*
|
||||
The `⋮` menu on each row. Upstream solves it with the Bootstrap 3 dropdown; here
|
||||
it is a button with a list that closes on an outside click or on Escape.
|
||||
|
||||
It used to live inside Zones and now belongs to everyone, because the rule that
|
||||
orders row actions needs it on every table: **destructive things go in here**. A
|
||||
row cannot have a loose "Delete" next to a "Disable" (there are two hundred and
|
||||
forty rows and this console has no undo anywhere), so deleting costs you opening
|
||||
the menu. On a detail screen it does go outside: there you act on an object you
|
||||
are looking at.
|
||||
|
||||
It deliberately does not use Radix: `DropdownMenu` would bring a new dependency
|
||||
into `package.json` for a twenty-line component, and the project's primitives are
|
||||
deliberately few.
|
||||
|
||||
And it is the ONLY menu. There was another one written by hand in the sidebar
|
||||
(the account one) with its own list, its own styles and its own state, and what
|
||||
it had forgotten was everything you cannot see by looking at it open: it did not
|
||||
close on an outside click, nor on Escape, nor on scroll. Three behaviours already
|
||||
solved here. The difference that was real (it hangs upwards from the foot of the
|
||||
sidebar, aligned left, and its trigger is a wide row instead of a button) is the
|
||||
two parameters below.
|
||||
*/
|
||||
|
||||
/*
|
||||
This is a real menu, and that is a contract rather than a label.
|
||||
|
||||
`role="menu"` promises a keyboard: arrows that move between items, `Home`/`End`,
|
||||
one tab stop for the whole menu rather than one per item, and `Escape` that
|
||||
closes it from anywhere inside and gives the focus back to the trigger. It was
|
||||
carrying the role without any of that until 2026-09-07: twelve call sites
|
||||
announcing a menu and handing over a pile of loose buttons.
|
||||
|
||||
The pattern is implemented **here**, once, and not at the call sites: items are
|
||||
whatever the caller renders, so the menu finds them in the DOM when it opens and
|
||||
gives them `role="menuitem"` and a roving `tabindex`. A call site that renders a
|
||||
button gets a menu item for free, which is the only way twelve of them stay
|
||||
consistent.
|
||||
|
||||
Disabled items keep their button role on purpose: they are announced, they are
|
||||
not reachable, and skipping them in the arrow order is what the pattern asks for.
|
||||
|
||||
Upstream declares no menu roles at all (its Bootstrap dropdown is a `<ul>` of
|
||||
links), so nothing here is owed to parity. It is owed to the role we chose.
|
||||
*/
|
||||
export function Menu({
|
||||
label,
|
||||
text,
|
||||
onOpen,
|
||||
anchor = 'right',
|
||||
asRow = false,
|
||||
quiet = false,
|
||||
icon = 'plus',
|
||||
alignTo,
|
||||
children,
|
||||
}: {
|
||||
/** Accessible name; it is all there is when it carries no visible label. */
|
||||
label: string
|
||||
/** Visible text. Without it, the button is the compact `⋮` of a row. */
|
||||
text?: string
|
||||
/**
|
||||
* Fired on open, for the menu that needs to know the server state right before
|
||||
* showing its options. Upstream does the same with the Dashboard's blocking
|
||||
* menu (`main.js:2429`): it asks on open, not on render, because between the
|
||||
* two the setting may have changed in another tab.
|
||||
*/
|
||||
onOpen?: () => void
|
||||
/** Which edge the list aligns to against the trigger. */
|
||||
anchor?: 'right' | 'left'
|
||||
/** The trigger fills the width of its column, with the label on the left. */
|
||||
asRow?: boolean
|
||||
/**
|
||||
* The compact `⋮` with no frame at rest, for a list where one menu repeats on
|
||||
* every short row (the Dashboard's tops, Blocking's top tables): fifteen framed
|
||||
* buttons weighed as much as the figures beside them. The frame comes back on
|
||||
* hover, on keyboard focus and while the menu is open, so the affordance is the
|
||||
* same; only the resting weight changes.
|
||||
*/
|
||||
quiet?: boolean
|
||||
/**
|
||||
* The icon of the compact trigger, the `⋮` unless told otherwise. The DNS
|
||||
* Client's server list hangs a chevron off its field instead, because there the
|
||||
* menu stands for a dropdown, not for a row's actions.
|
||||
*/
|
||||
icon?: IconName
|
||||
/**
|
||||
* Measure the list's edge from this element instead of the trigger, and open
|
||||
* at least as wide as it (and no wider than the window allows on that side,
|
||||
* since a field's entries can be long). For a trigger attached to a field: the list hangs
|
||||
* from the whole control, as a dropdown does, not from the arrow alone.
|
||||
*/
|
||||
alignTo?: RefObject<HTMLElement | null>
|
||||
children: (close: () => void) => ReactNode
|
||||
}) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const list = useRef<HTMLDivElement>(null)
|
||||
const trigger = useRef<HTMLButtonElement>(null)
|
||||
const giveBack = useRef(false)
|
||||
/* Escape hands the focus back to the trigger, after the popup has gone: the item
|
||||
that held it is removed, and the browser would leave it on the page's body. An
|
||||
outside click does not: the focus belongs to whatever was clicked. */
|
||||
useEffect(() => {
|
||||
if (!open && giveBack.current) {
|
||||
giveBack.current = false
|
||||
trigger.current?.focus()
|
||||
}
|
||||
}, [open])
|
||||
|
||||
/*
|
||||
The surface is ReUI's Popover: it takes the list out of any clipping ancestor
|
||||
(the segmented actions group and the table wrapper both clip), opens where it
|
||||
fits, closes on an outside click and on Escape, and gives the focus back to the
|
||||
trigger. What stays here is what makes it a MENU: the roles and the keyboard.
|
||||
It still closes on scroll, as the native one does.
|
||||
*/
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
/* Scrolling the page closes it, but scrolling the list itself does not. The
|
||||
`instanceof` is not redundant: this same handler serves `resize`, and there
|
||||
the `target` is `window`, which is not a node. */
|
||||
const onScroll = (e: Event) => {
|
||||
if (e.target instanceof Node && list.current?.contains(e.target)) return
|
||||
setOpen(false)
|
||||
}
|
||||
const escape = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') {
|
||||
giveBack.current = true
|
||||
setOpen(false)
|
||||
}
|
||||
}
|
||||
document.addEventListener('keydown', escape)
|
||||
window.addEventListener('scroll', onScroll, true)
|
||||
window.addEventListener('resize', onScroll)
|
||||
return () => {
|
||||
document.removeEventListener('keydown', escape)
|
||||
window.removeEventListener('scroll', onScroll, true)
|
||||
window.removeEventListener('resize', onScroll)
|
||||
}
|
||||
}, [open])
|
||||
|
||||
/*
|
||||
The items are found, not declared. `children` is a render function, so the menu
|
||||
cannot clone them: it reads the list once it is on screen.
|
||||
*/
|
||||
const allItems = () =>
|
||||
Array.from(list.current?.querySelectorAll<HTMLElement>('button, a[href]') ?? [])
|
||||
const reachable = () => allItems().filter((el) => !el.hasAttribute('disabled'))
|
||||
|
||||
const focusAt = (els: HTMLElement[], i: number) => {
|
||||
els.forEach((el, n) => { el.tabIndex = n === i ? 0 : -1 })
|
||||
els[i]?.focus()
|
||||
}
|
||||
|
||||
/* Callback ref: the list is in the DOM when it arrives, so the items get their
|
||||
role and the first one the focus, once per opening. */
|
||||
const setList = (el: HTMLDivElement | null) => {
|
||||
list.current = el
|
||||
if (el == null) return
|
||||
el.querySelectorAll<HTMLElement>('button, a[href]').forEach((item) => {
|
||||
if (!item.hasAttribute('disabled')) item.setAttribute('role', 'menuitem')
|
||||
})
|
||||
const els = reachable()
|
||||
els.forEach((item, i) => { item.tabIndex = i === 0 ? 0 : -1 })
|
||||
els[0]?.focus()
|
||||
}
|
||||
|
||||
const onListKeyDown = (e: ReactKeyboardEvent<HTMLDivElement>) => {
|
||||
const els = reachable()
|
||||
if (els.length === 0) return
|
||||
const here = els.indexOf(document.activeElement as HTMLElement)
|
||||
switch (e.key) {
|
||||
case 'ArrowDown': e.preventDefault(); focusAt(els, here < 0 ? 0 : (here + 1) % els.length); break
|
||||
case 'ArrowUp': e.preventDefault(); focusAt(els, here < 0 ? els.length - 1 : (here - 1 + els.length) % els.length); break
|
||||
case 'Home': e.preventDefault(); focusAt(els, 0); break
|
||||
case 'End': e.preventDefault(); focusAt(els, els.length - 1); break
|
||||
/* A menu is one tab stop, so leaving by Tab leaves the menu, not the item. */
|
||||
case 'Tab': setOpen(false); break
|
||||
}
|
||||
}
|
||||
|
||||
/* Opening with the keyboard lands on the first item, which is what the arrow
|
||||
asked for. */
|
||||
const onTriggerKeyDown = (e: ReactKeyboardEvent<HTMLElement>) => {
|
||||
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
|
||||
e.preventDefault()
|
||||
if (!open) { onOpen?.(); setOpen(true) }
|
||||
}
|
||||
}
|
||||
|
||||
const change = (next: boolean) => {
|
||||
if (next) onOpen?.()
|
||||
setOpen(next)
|
||||
}
|
||||
|
||||
const triggerEl = asRow ? (
|
||||
<button
|
||||
ref={trigger}
|
||||
type="button"
|
||||
className={styles.row}
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={open}
|
||||
onKeyDown={onTriggerKeyDown}
|
||||
>
|
||||
{text}
|
||||
<Icon name="chevronDown" size={12} />
|
||||
</button>
|
||||
) : (
|
||||
<Button
|
||||
ref={trigger}
|
||||
size="sm"
|
||||
className={quiet && text == null ? styles.quiet : undefined}
|
||||
icon={text == null}
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={open}
|
||||
aria-label={label}
|
||||
onKeyDown={onTriggerKeyDown}
|
||||
>
|
||||
{text == null ? (
|
||||
<Icon name={icon} size={16} />
|
||||
) : (
|
||||
<>
|
||||
{text}
|
||||
<Icon name="chevronDown" size={12} />
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className={asRow ? styles.menuWidth : styles.menu}>
|
||||
<Popover open={open} onOpenChange={change}>
|
||||
<PopoverTrigger render={triggerEl} />
|
||||
<PopoverContent
|
||||
side="bottom"
|
||||
align={anchor === 'left' ? 'start' : 'end'}
|
||||
anchor={alignTo}
|
||||
className="w-auto max-h-(--available-height) min-w-[170px] gap-0 overflow-y-auto p-1"
|
||||
>
|
||||
<div className={styles.menuList} role="menu" aria-label={label} ref={setList} onKeyDown={onListKeyDown}>
|
||||
{children(() => setOpen(false))}
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function Separator() {
|
||||
return <div className={styles.sep} role="separator" />
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { Notifier } from './Notifier'
|
||||
|
||||
/*
|
||||
The air it leaves beneath is measured in the browser, not here: jsdom does not lay
|
||||
out. What it can answer is the contract, which is what fifty places were writing by
|
||||
hand (and out of that came four distances for the same thing).
|
||||
*/
|
||||
describe('Notifier', () => {
|
||||
it('with no alert it draws nothing', () => {
|
||||
const { container } = render(<Notifier notice={null} onClose={() => {}} />)
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
})
|
||||
|
||||
it('with an alert it draws title, text and the close button', async () => {
|
||||
const close = vi.fn()
|
||||
render(
|
||||
<Notifier
|
||||
notice={{ type: 'danger', title: 'Error!', text: 'Zone not found.' }}
|
||||
onClose={close}
|
||||
/>,
|
||||
)
|
||||
expect(screen.getByText('Error!')).toBeInTheDocument()
|
||||
expect(screen.getByText('Zone not found.')).toBeInTheDocument()
|
||||
await userEvent.click(screen.getByRole('button'))
|
||||
expect(close).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,33 @@
|
||||
import { Alert } from './Alert'
|
||||
import type { Notice } from '../lib/notice'
|
||||
import styles from './Alert.module.css'
|
||||
|
||||
/*
|
||||
The alert slot of a screen or a modal: if there is an alert, it is painted; if
|
||||
not, there is nothing. And always with the same air beneath it.
|
||||
|
||||
It existed as a component inside Administration and ONE screen used it; the other
|
||||
fifty wrote the same `{notice && (<Alert …>{notice.text}</Alert>)}` by hand. Out of
|
||||
that came three different distances for the same thing, measured in the browser by
|
||||
forcing a server failure:
|
||||
|
||||
· 24 px in Zones, its twelve modals, the lists screens, Administration, the
|
||||
Dashboard, DNS Client and Apps, which wrapped the alert in a `div` with a
|
||||
margin;
|
||||
· 14 px in DHCP and in Logs, where the alert sat loose inside the screen's
|
||||
`flex` container and kept its `gap`;
|
||||
· 12 px in the four account modals, for the same reason inside the dialog.
|
||||
|
||||
It settles at 24, which is `--gap-block` (the token that names the distance
|
||||
between independent blocks) and the one three quarters of them already had.
|
||||
*/
|
||||
export function Notifier({ notice, onClose }: { notice: Notice | null; onClose: () => void }) {
|
||||
if (notice == null) return null
|
||||
return (
|
||||
<div className={styles.gap}>
|
||||
<Alert type={notice.type} title={notice.title} onDismiss={onClose}>
|
||||
{notice.text}
|
||||
</Alert>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
Pagination, a single one. There were two: in Zones the active button was
|
||||
transparent with an amber border and measured 26 px; in Logs it was solid amber and
|
||||
measured 24. The solid one wins, which is what was drawn and what is told apart at
|
||||
a glance.
|
||||
*/
|
||||
|
||||
.pg { display: flex; gap: var(--s-2); flex-wrap: wrap; }
|
||||
|
||||
.pgb {
|
||||
min-width: 24px;
|
||||
height: 24px;
|
||||
padding: 0 var(--s-3);
|
||||
border-radius: var(--r-2);
|
||||
border: 1px solid var(--line);
|
||||
background: var(--pan2);
|
||||
color: var(--mute);
|
||||
font-size: var(--t-3);
|
||||
font-family: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.pgb:hover { color: var(--ink); }
|
||||
|
||||
.pgb[aria-current='true'] {
|
||||
background: var(--acc);
|
||||
border-color: var(--acc);
|
||||
color: var(--on-acc);
|
||||
font-weight: 600;
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { Icon } from './Icon'
|
||||
import styles from './Pagination.module.css'
|
||||
import type { Pagination as Window } from '../lib/pagination'
|
||||
|
||||
/*
|
||||
The page bar: first, previous, the window of ten, next and last.
|
||||
|
||||
It was written by hand on three screens (the zone list, a zone's records and Query
|
||||
Logs) with the same markup and the same string of buttons. The arithmetic already
|
||||
lived in one place (`lib/pagination.ts`, which is tested on its own); what was
|
||||
missing was the buttons doing the same.
|
||||
|
||||
The only thing that really differed between the three is HOW the last page is
|
||||
asked for: the zone list and Query Logs send `-1` and let the server resolve it
|
||||
(which is what upstream does), and a zone's records compute it client-side because
|
||||
they have them all. That is why `last` is a parameter and not hard-coded.
|
||||
*/
|
||||
export function Pagination({
|
||||
window,
|
||||
current,
|
||||
last,
|
||||
onGoTo,
|
||||
}: {
|
||||
window: Window
|
||||
current: number
|
||||
/** Which number to ask for as "last". `-1` lets the server resolve it. */
|
||||
last: number
|
||||
onGoTo: (page: number) => void
|
||||
}) {
|
||||
return (
|
||||
<span className={styles.pg}>
|
||||
{window.first && (
|
||||
<button type="button" className={styles.pgb} aria-label="First" onClick={() => onGoTo(1)}>
|
||||
<Icon name="first" size={14} />
|
||||
</button>
|
||||
)}
|
||||
{window.previous != null && (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.pgb}
|
||||
aria-label="Previous"
|
||||
onClick={() => onGoTo(window.previous!)}
|
||||
>
|
||||
<Icon name="chevronLeft" size={14} />
|
||||
</button>
|
||||
)}
|
||||
{window.pages.map((p) => (
|
||||
<button
|
||||
key={p}
|
||||
type="button"
|
||||
className={styles.pgb}
|
||||
aria-current={p === current}
|
||||
onClick={() => onGoTo(p)}
|
||||
>
|
||||
{p}
|
||||
</button>
|
||||
))}
|
||||
{window.next != null && (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.pgb}
|
||||
aria-label="Next"
|
||||
onClick={() => onGoTo(window.next!)}
|
||||
>
|
||||
<Icon name="chevronRight" size={14} />
|
||||
</button>
|
||||
)}
|
||||
{window.last && (
|
||||
<button type="button" className={styles.pgb} aria-label="Last" onClick={() => onGoTo(last)}>
|
||||
<Icon name="last" size={14} />
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
The panel: the bordered box where a piece of screen lives.
|
||||
|
||||
It was defined SEVEN times (`.panel` in Dashboard, DNS Client, Logs and About;
|
||||
`.block` in Settings, DHCP and Administration) and no two were alike:
|
||||
|
||||
· shadow yes in Dashboard, About and Settings; no in Logs, DNS Client, DHCP and Admin
|
||||
· header background yes in Dashboard and Settings; no in the other five
|
||||
· and TWO title typographies for the same object: 12.5 px in sentence case for
|
||||
some, 10.5 px in small caps for others
|
||||
|
||||
The box's values are the table's (`ui/Table.module.css`), which is the most-seen
|
||||
surface in this console: same border, same shadow, same header on the raised step.
|
||||
The TITLE is not the table's any more (see `.title`).
|
||||
*/
|
||||
.panel {
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--r-4);
|
||||
background: var(--pan);
|
||||
box-shadow: var(--e-1), var(--edge);
|
||||
overflow: hidden;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/*
|
||||
The header sits on the raised step, just like the table's `thead`: it separates
|
||||
the label from the content without spending another rule line.
|
||||
|
||||
It is `flex` because many of them carry an action on the right ("More",
|
||||
"Blocking"), and the ones that do not never notice.
|
||||
*/
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--s-7);
|
||||
padding: var(--s-6) var(--s-9);
|
||||
border-bottom: 1px solid var(--line);
|
||||
background: var(--pan2);
|
||||
}
|
||||
|
||||
/*
|
||||
The title is one step above a table's header row, not the same row twice.
|
||||
|
||||
Until 2026-10-15 it composed the small capitals of a table's `thead` (`--t-1`,
|
||||
`--mute`, uppercase), on the reasoning that a panel and a table are the same
|
||||
object. On screen that read as two identical grey rows stacked: "TOP BLOCKED
|
||||
DOMAINS" and right under it "DOMAIN · HITS", with nothing to tell the name of the
|
||||
box from the names of its columns. Adrián reversed it on 2026-10-15: the box keeps
|
||||
the table's border, shadow and raised header, and its title takes the block-title
|
||||
step of the type scale (`--t-5`, "block title" in tokens.css) in `--ink`, as written.
|
||||
|
||||
Only the style changed. The words are the ones each screen already passes, upstream's
|
||||
where upstream has them; nothing is re-cased in the source, and nothing here is
|
||||
`text-transform`, so what is drawn is what the screen reader reads. The small
|
||||
capitals stay where they label something smaller than a box: a column, a group of
|
||||
fields, a figure.
|
||||
*/
|
||||
.title {
|
||||
margin: 0;
|
||||
font-size: var(--t-5);
|
||||
font-weight: 600;
|
||||
line-height: 1.3;
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.body { padding: var(--s-9); }
|
||||
|
||||
/* A panel with no header needs to recover the air the header used to give it. */
|
||||
.noHeader { padding-top: var(--s-9); }
|
||||
@@ -0,0 +1,97 @@
|
||||
import { useId, type ReactNode } from 'react'
|
||||
import { Frame, FrameHeader, FramePanel } from '@/components/reui/frame'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
/*
|
||||
The console's bordered box: ONE component, not a class each screen applies on its
|
||||
own.
|
||||
|
||||
This used to be a `<fieldset>` with a `<legend>` as its header, and it did not
|
||||
work: a `legend` measures its `width: 100%` against the fieldset's CONTENT box,
|
||||
and the browser reserves that fieldset a side padding of its own that nobody had
|
||||
removed. The title band ended up 21 px narrower than the card, floating inside
|
||||
instead of touching the edges. It was patched over with `float: left`, which is
|
||||
exactly the kind of patch that appears when you unify through CSS instead of
|
||||
through a component.
|
||||
|
||||
With a `div` the header is an ordinary child and the band reaches the edge with no
|
||||
tricks. The group is still announced: `role="group"` with `aria-labelledby` is
|
||||
what the ARIA specification gives as the equivalent of `fieldset`/`legend`, and it
|
||||
is also what upstream does, using `div.panel` with its title and no `fieldset`.
|
||||
*/
|
||||
export function Panel({
|
||||
title,
|
||||
actions,
|
||||
groups2 = false,
|
||||
children,
|
||||
className,
|
||||
}: {
|
||||
/*
|
||||
With no title, the panel just groups: no label is invented for it.
|
||||
|
||||
It takes a node and not only a string because some titles carry formatting (the
|
||||
log viewer puts the file name in monospace), and a component that only accepts
|
||||
plain text forces the screen to skip it and replicate the markup, which is
|
||||
exactly what this exists to avoid.
|
||||
*/
|
||||
title?: ReactNode
|
||||
/** What goes on the right of the header. */
|
||||
actions?: ReactNode
|
||||
/*
|
||||
Announce the panel as a named GROUP. Only where it really does group related
|
||||
controls (the Settings and DHCP blocks, which are what used to be a `fieldset`);
|
||||
not on a panel containing a chart or a table, where the `h2` already provides
|
||||
the structure and the role is redundant.
|
||||
|
||||
This is not cosmetic: applied to all of them, the "Query Response Types" panel
|
||||
ended up named the same as the chart it contains, and a screen reader said the
|
||||
same name twice in a row.
|
||||
*/
|
||||
groups2?: boolean
|
||||
children: ReactNode
|
||||
className?: string
|
||||
}) {
|
||||
const id = useId()
|
||||
|
||||
/* ReUI's Frame: a tinted outer frame with the panel inside. `dense` removes the
|
||||
frame's own padding, so what sits in the panel (tables, rows) keeps its edges. */
|
||||
if (title == null) {
|
||||
return (
|
||||
<Frame dense className={className}>
|
||||
<FramePanel className="p-0">{children}</FramePanel>
|
||||
</Frame>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Frame
|
||||
dense
|
||||
className={className}
|
||||
role={groups2 ? 'group' : undefined}
|
||||
aria-labelledby={groups2 ? id : undefined}
|
||||
>
|
||||
<FrameHeader className="flex-row items-center justify-between gap-3 px-4 py-2.5">
|
||||
<h2 className="m-0 text-sm leading-5 font-semibold text-foreground" id={id}>
|
||||
{title}
|
||||
</h2>
|
||||
{actions}
|
||||
</FrameHeader>
|
||||
<FramePanel className="p-0">{children}</FramePanel>
|
||||
</Frame>
|
||||
)
|
||||
}
|
||||
|
||||
/*
|
||||
The panel body: the padding that separates the content from its edges.
|
||||
|
||||
It goes as a component and not as a class each screen composes, for the same
|
||||
reason as the panel: what is shared is the PIECE, not a loose rule. It is optional
|
||||
because some panels have content that reaches the edges on purpose (the Settings
|
||||
blocks, whose rows bring their own padding, and the tables).
|
||||
|
||||
`className` is for the variants that do exist: the log viewer tightens its list
|
||||
and the Dashboard's "Top" panel trims the air above.
|
||||
*/
|
||||
export function Body({ children, className }: { children: ReactNode; className?: string }) {
|
||||
return <div className={cn('p-4', className)}>{children}</div>
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
/*
|
||||
The panel-form kit: blocks with a title, label/control rows, editable lists and
|
||||
the sticky save bar. Settings and DHCP use it, the two big forms in the console.
|
||||
|
||||
It was written twice. DHCP's file explained why: Settings was being built
|
||||
separately at the time, and "coupling two screens through their presentation
|
||||
components turns any tweak in Settings into a change in DHCP". That solved a coordination problem while
|
||||
it was being built, and its bill was paid on screen: Settings' action bar floated
|
||||
with a shadow and DHCP's did not; the "Note!" alert was indented in DHCP and flush
|
||||
in Settings; the `<code>` in the help broke long words in one and not in the
|
||||
other. None of the three was decided.
|
||||
|
||||
It lives in `ui/` and not in one of the two screens, which is what stops touching
|
||||
it again from meaning one screen rules over the other.
|
||||
*/
|
||||
|
||||
/* Only what belongs to the block: the box is painted by `ui/Panel`. */
|
||||
.block {
|
||||
margin: 0 0 var(--s-9) 0;
|
||||
padding-bottom: var(--s-9);
|
||||
/*
|
||||
`clip`, not the panel's `hidden`. `overflow: hidden` makes the block a scroll
|
||||
container, and a sticky child sticks inside its nearest scroll container: the
|
||||
title below "stuck" to the block's own top, which is where it already was, so it
|
||||
never stayed in view (found 2026-10-16, when its `top` became the strip's height
|
||||
and the title moved 93 px down inside its block at 390). `clip` clips the same
|
||||
corners without being a scroll container, so the title pins to the window.
|
||||
Written as `div.block`, below, because the panel's own `overflow: hidden`
|
||||
(`ui/Panel.module.css`) has the same weight as `.block` and may come later.
|
||||
*/
|
||||
}
|
||||
|
||||
div.block { overflow: clip; }
|
||||
|
||||
/* Control and suffix on the same line: "3600 seconds". */
|
||||
.inline {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--s-6);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
/*
|
||||
Only what belongs to the text area: the box comes from `ui/Field`.
|
||||
|
||||
`--area-min` is a FLOOR, not the height: the height is still set by `rows` at each
|
||||
call site (today they come out 66, 98 and 130 px, all well above), and the
|
||||
`max-width: 560px` stays as it was.
|
||||
|
||||
What it buys, then: this area is `resize: vertical`, so it can be dragged down to
|
||||
nothing. The floor is for that. **It changes no default render**, and that is
|
||||
worth saying rather than claiming an improvement nobody can see.
|
||||
*/
|
||||
.area {
|
||||
width: 100%;
|
||||
max-width: 560px;
|
||||
min-height: var(--area-min);
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
/*
|
||||
The panel body's indent, for whatever sits loose between rows, and the notice's
|
||||
width cap.
|
||||
|
||||
`--notice-max` comes from the design rules: **a notice belongs to no control**, so it takes
|
||||
up its section and not the help column; but the longest one in `General` is six
|
||||
hundred characters, and at 1440 with no cap that is a line nobody reads.
|
||||
|
||||
It goes here and not in `ui/Alert` on purpose. The rule says "at SECTION width",
|
||||
and the screen notice (the `Notifier`'s, above the title) is not in a section:
|
||||
capping it the same way would apply the rule where it was not decided. Dialog
|
||||
notices do not need it either, because the dialog itself is 880 at most.
|
||||
*/
|
||||
.notices {
|
||||
margin: var(--s-3) var(--s-9) 0 var(--s-9);
|
||||
max-width: var(--notice-max);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--s-4);
|
||||
}
|
||||
|
||||
.plain {
|
||||
composes: helpPanel from './text.module.css';
|
||||
padding: 0 var(--s-9);
|
||||
}
|
||||
|
||||
.link { font-size: var(--t-3); padding: var(--s-5) var(--s-9) 0 var(--s-9); }
|
||||
.link a { color: var(--acc-ink); }
|
||||
|
||||
.pre {
|
||||
margin: 0 var(--s-9);
|
||||
padding: var(--s-7) var(--s-8);
|
||||
background: var(--field);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--r-2);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--t-2);
|
||||
color: var(--ink);
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.editable { composes: table from './EditableTable.module.css'; }
|
||||
|
||||
/*
|
||||
A list's numeric cell has the SAME floor as a row's.
|
||||
|
||||
Without the floor, the table columns share out whatever is left of the control
|
||||
cell, and when the third help column opened that left the cells of the two QPM
|
||||
lists at 59 px: measured at 1181, five of them (`6000`, `1200`) no longer fitted
|
||||
in their own box. A field that does not show its value is not an aesthetic
|
||||
squeeze.
|
||||
|
||||
`--ctrl-num` is the same token that governs a row's default numeric width, and
|
||||
here it is a FLOOR and not a width: the column still grows with the room there is.
|
||||
*/
|
||||
.editable input {
|
||||
width: 100%;
|
||||
min-width: var(--ctrl-num);
|
||||
}
|
||||
|
||||
/*
|
||||
And when even that does not fit, the table scrolls INSIDE its cell instead of
|
||||
clipping. That is what lets the floor above be a real floor: without this, a table
|
||||
wider than its cell would overflow the whole page.
|
||||
*/
|
||||
.listScroll {
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.tdel { width: 74px; }
|
||||
|
||||
/* The save bar, stuck to the bottom of the content area. It floats over the
|
||||
form, so it carries elevation: without it the content slides underneath with
|
||||
nothing saying there are two planes.
|
||||
|
||||
And it is drawn ABOVE the blocks' own sticky labels (`z-index: 1`, below). Without
|
||||
a layer of its own, a label scrolling up from under it painted over it: measured on
|
||||
2026-10-16 at 1440 in Settings › General, with `Advanced Options` entering at the
|
||||
foot of the window the bar's four buttons were gone behind the label. */
|
||||
.bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--s-5);
|
||||
flex-wrap: wrap;
|
||||
padding: var(--s-8) var(--s-9);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--r-4);
|
||||
background: var(--pan);
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
z-index: var(--layer-sticky);
|
||||
box-shadow: var(--e-2), var(--edge);
|
||||
}
|
||||
|
||||
.spacer { flex: 1; }
|
||||
|
||||
/* When narrow the bar stacks and the elastic spacer stops making sense: with it,
|
||||
"Backup Settings" fell off the screen. */
|
||||
@media (max-width: 720px) {
|
||||
.spacer { display: none; }
|
||||
.bar { padding: var(--s-7) var(--s-8); }
|
||||
}
|
||||
|
||||
/*
|
||||
The section count, in its label.
|
||||
|
||||
It is the same count pill any table in the console carries
|
||||
(`ui/count.module.css`), placed here in the block's header. It is dimmed on
|
||||
purpose: it goes with the label, it does not compete with it.
|
||||
*/
|
||||
.count {
|
||||
font: 400 var(--t-2)/1 var(--font-mono);
|
||||
color: var(--faint);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/*
|
||||
The section label stays at the top while scrolling, in the dense form only.
|
||||
|
||||
It is a decision of the dense-form design, and it goes here and not in `ui/Panel` on purpose:
|
||||
only `Settings` has ten sections in a row inside one screen. On the Dashboard a
|
||||
whole panel fits in the window's height, so pinning its label buys nothing and
|
||||
does add a layer that something else can cover.
|
||||
|
||||
What it buys here: `General` has 41 paragraphs of help, and scrolling inside a
|
||||
section you lost track of which one you were in, with ten sections whose controls
|
||||
have similar names.
|
||||
|
||||
The background is compulsory: without it, the content shows through under the
|
||||
label.
|
||||
*/
|
||||
.block > [class*='_header_'] {
|
||||
position: sticky;
|
||||
/* Below whatever is pinned above the form: the section index's strip
|
||||
(`--pinned`, `ui/IndexedForm`), or the narrow screen's top bar (`--stuck-top`,
|
||||
`app/Shell.module.css`), which hid the title underneath before 2026-10-16. */
|
||||
top: var(--pinned, var(--stuck-top, 0px));
|
||||
z-index: 1;
|
||||
background: var(--pan);
|
||||
}
|
||||
|
||||
/*
|
||||
`Block`'s warning slot, with a class of its OWN besides `notices`.
|
||||
|
||||
It changes nothing visually (`composes` gives it the same geometry); it exists
|
||||
because without it the slot and the `Notices` below share a name and **the
|
||||
measurement cannot tell them apart**: on the "Warning! above, Note! below" check
|
||||
the probe read the block's first `notices` and answered about a different element.
|
||||
A decision the instrument cannot see cannot be held.
|
||||
*/
|
||||
.notices { composes: notices; }
|
||||
|
||||
/*
|
||||
A block with an anchor (`BlockAnchors`). Followed from the section index, it lands
|
||||
below whatever is pinned (the strip, the top bar) with the same 14 px the column
|
||||
keeps from the window's top (`ui/SectionIndex.module.css`), never under them.
|
||||
*/
|
||||
.anchor { scroll-margin-top: calc(var(--pinned, var(--stuck-top, 0px)) + var(--s-9)); }
|
||||
@@ -0,0 +1,465 @@
|
||||
import { createContext, type ReactNode, useContext, useEffect, useRef, useState } from 'react'
|
||||
import { Alert } from './Alert'
|
||||
import { Button } from './Button'
|
||||
import { Empty } from './Empty'
|
||||
import { Input, Textarea } from './Field'
|
||||
import { HelpText, GroupRow, Row } from './Form'
|
||||
import { Panel } from './Panel'
|
||||
import { EditableTable } from './EditableTable'
|
||||
import check from './Check.module.css'
|
||||
import text from './text.module.css'
|
||||
import styles from './PanelForm.module.css'
|
||||
|
||||
/*
|
||||
The pieces of the panel-form kit. See `PanelForm.module.css` for why they live
|
||||
here and not inside Settings or DHCP.
|
||||
|
||||
Upstream puts each group of fields in a `div.well` with NO title (index.html:2565
|
||||
onwards). The redesign gives it a small-caps header: same fields, same order,
|
||||
just visually grouped. The titles come from the `well`'s `id`
|
||||
(`divSettingsGeneralRateLimiting` -> "Rate Limiting") so as not to invent new
|
||||
taxonomies.
|
||||
*/
|
||||
|
||||
/*
|
||||
A block's anchor, for a section index beside the form (`ui/SectionIndex`).
|
||||
|
||||
The screen that draws the index wraps its blocks in `BlockAnchors` with a prefix,
|
||||
and every block WITH a title takes the id `<prefix>-<title in kebab case>`, plus
|
||||
its title in `data-section` for the screen to read the entries back in page order.
|
||||
So the index's entries are the blocks' own titles, and a block added to a pane
|
||||
appears in it without anyone writing it down twice. A block without a title gets
|
||||
nothing: an index cannot name what the screen does not name.
|
||||
|
||||
It is a context and not a prop because nine panes and thirty-odd blocks would
|
||||
otherwise each have to remember to pass it, and DHCP, which draws no index, gets
|
||||
no ids at all.
|
||||
*/
|
||||
const AnchorPrefix = createContext<string | null>(null)
|
||||
|
||||
export function BlockAnchors({ prefix, children }: { prefix: string; children: ReactNode }) {
|
||||
return <AnchorPrefix.Provider value={prefix}>{children}</AnchorPrefix.Provider>
|
||||
}
|
||||
|
||||
/** The id `BlockAnchors` gives a block with this title. */
|
||||
function blockAnchor(prefix: string, title: string): string {
|
||||
return `${prefix}-${title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')}`
|
||||
}
|
||||
|
||||
/*
|
||||
The title is optional on purpose.
|
||||
|
||||
Five panels repeated their own name as the legend of the first block (TSIG,
|
||||
Recursion, Blocking, Logging and SSO), and in three of them it was the ONLY
|
||||
legend, so it grouped nothing: it just repeated. In SSO it got said four times in
|
||||
a row before the first control. Without `title` the panel still groups: what
|
||||
disappears is the echo.
|
||||
*/
|
||||
/*
|
||||
`notices` is where the `Warning!` goes, and it goes BEFORE the controls on
|
||||
purpose.
|
||||
|
||||
It is the dense-form rule: **`Warning!` before, `Note!` after**. One can change your
|
||||
decision and the other explains it, so reading the warning after having touched
|
||||
the control arrives late by definition.
|
||||
|
||||
Before this, all forty `Settings` notices went BELOW, the seven `Warning!`
|
||||
included. Now the seven are in this slot and the thirty-three `Note!` are still
|
||||
below, and that is checked: `dev/master-switch-signal.test.mjs` does not look at
|
||||
it, but the 2026-09-03 sweep walked the four panes that have a warning (`general`,
|
||||
`blocking`, `logging` and `recursion`) and measured that every `Warning!` ends up
|
||||
above the first control of its block, at all four widths.
|
||||
|
||||
It is a prop of the block and not a convention each pane has to remember: whoever
|
||||
places it decides the position, and a rule that depends on remembering gets
|
||||
forgotten: eleven of twelve call sites proved it with `role="menuitem"`.
|
||||
*/
|
||||
export function Block({
|
||||
title,
|
||||
notices,
|
||||
children,
|
||||
}: {
|
||||
title?: string
|
||||
/** This block's warnings. They are drawn **above** the controls. */
|
||||
notices?: ReactNode
|
||||
children: ReactNode
|
||||
}) {
|
||||
/*
|
||||
The section count, COUNTED and not written by hand.
|
||||
|
||||
The dense-form design puts on every section label how many controls it has,
|
||||
and its ten figures add up to 39 (the screen's total), so the drawing checks itself. That
|
||||
property only survives if the number comes from the content: ten hand-written
|
||||
numbers part company with the content on the first control anyone adds, and they
|
||||
do it silently.
|
||||
|
||||
It is counted from the DOM and not from React's `children` because a section
|
||||
mixes rows of several kinds (`TextRow`, `AreaRow`, `GroupRow`, `EditableList`),
|
||||
and some carry more than one control inside. What has to be counted is what the
|
||||
user sees.
|
||||
*/
|
||||
const prefix = useContext(AnchorPrefix)
|
||||
const anchor = prefix != null && title != null ? blockAnchor(prefix, title) : undefined
|
||||
const box = useRef<HTMLDivElement>(null)
|
||||
const [howMany, setHowMany] = useState<number | null>(null)
|
||||
useEffect(() => {
|
||||
const root = box.current
|
||||
if (root == null) return
|
||||
/*
|
||||
The cells of an editable list do NOT count.
|
||||
|
||||
Measured: counting them, `Rate Limiting` said **18** and the ten added up to
|
||||
54. The design says 39, and the difference is exactly the **15 cells of the two
|
||||
QPM lists**. And the design is right: a row cell is **server data** (with
|
||||
another configuration they are other rows and another number), so counting them
|
||||
turns the section count into a volatile figure instead of a property of the
|
||||
screen: 39 comparable controls and 15 data cells, kept apart on purpose.
|
||||
*/
|
||||
const controls = [...root.querySelectorAll('input, select, textarea, [role="combobox"]')]
|
||||
const n = controls.filter((c) => c.closest('table') == null).length
|
||||
setHowMany(n > 0 ? n : null)
|
||||
/* No dependency array, and on purpose: what has to be counted is the DOM as
|
||||
already drawn, and it changes for reasons that are not props of this block
|
||||
(a row appearing because its master switches on, a list growing). It settles
|
||||
because `setHowMany` with the same value does not re-render. */
|
||||
})
|
||||
|
||||
return (
|
||||
<div ref={box} id={anchor} data-section={anchor != null ? title : undefined} className={anchor != null ? styles.anchor : undefined}>
|
||||
<Panel
|
||||
title={title}
|
||||
className={styles.block}
|
||||
groups2
|
||||
actions={howMany != null ? <span className={styles.count}>{howMany}</span> : undefined}
|
||||
>
|
||||
{notices != null && <div className={styles.notices}>{notices}</div>}
|
||||
{children}
|
||||
</Panel>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function TextRow({
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
placeholder,
|
||||
suffix,
|
||||
help,
|
||||
type = 'text',
|
||||
width,
|
||||
disabled,
|
||||
dependsOn,
|
||||
maxLength,
|
||||
}: {
|
||||
label: string
|
||||
value: string
|
||||
onChange: (v: string) => void
|
||||
placeholder?: string
|
||||
suffix?: string
|
||||
help?: ReactNode
|
||||
type?: 'text' | 'number' | 'password'
|
||||
/*
|
||||
Upstream pins the numeric ones at 80-100 px and leaves the text ones wide.
|
||||
|
||||
**No default value here**: when nothing is said, `--ctrl-num` rules, which is
|
||||
where the design system writes down the width of a numeric field. The default used to be a
|
||||
literal `100` on this line, so the token existed and governed nothing.
|
||||
|
||||
The explicit widths the console already has (80, 125, 200, 38, 28) still win
|
||||
over the token: they are per-field decisions and not drift. */
|
||||
width?: number | 'wide'
|
||||
disabled?: boolean
|
||||
/** Who has it switched off, when it is a master switch and not a permission. */
|
||||
dependsOn?: string
|
||||
maxLength?: number
|
||||
}) {
|
||||
return (
|
||||
<Row label={label} help={help} dependsOn={dependsOn}>
|
||||
{(id) => (
|
||||
<div className={styles.inline}>
|
||||
<Input
|
||||
id={id}
|
||||
type={type}
|
||||
value={value}
|
||||
placeholder={placeholder}
|
||||
disabled={disabled}
|
||||
maxLength={maxLength}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
style={
|
||||
width === 'wide'
|
||||
? { width: '100%', maxWidth: 420 }
|
||||
: { width: width ?? 'var(--ctrl-num)' }
|
||||
}
|
||||
/>
|
||||
{suffix && <Trailer>{suffix}</Trailer>}
|
||||
</div>
|
||||
)}
|
||||
</Row>
|
||||
)
|
||||
}
|
||||
|
||||
export function AreaRow({
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
rows = 3,
|
||||
help,
|
||||
disabled,
|
||||
dependsOn,
|
||||
}: {
|
||||
label: string
|
||||
value: string
|
||||
onChange: (v: string) => void
|
||||
rows?: number
|
||||
help?: ReactNode
|
||||
disabled?: boolean
|
||||
/** Who has it switched off, when it is a master switch and not a permission. */
|
||||
dependsOn?: string
|
||||
}) {
|
||||
return (
|
||||
<Row label={label} help={help} dependsOn={dependsOn}>
|
||||
{(id) => (
|
||||
<Textarea
|
||||
mono
|
||||
id={id}
|
||||
className={styles.area}
|
||||
rows={rows}
|
||||
spellCheck={false}
|
||||
disabled={disabled}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
/>
|
||||
)}
|
||||
</Row>
|
||||
)
|
||||
}
|
||||
|
||||
/** The suffix that follows a control: "seconds", "MB", "(0 to disable)". */
|
||||
export function Trailer({ children }: { children: ReactNode }) {
|
||||
return <span className={text.trailer}>{children}</span>
|
||||
}
|
||||
|
||||
export interface RadioOption {
|
||||
value: string
|
||||
label: string
|
||||
help?: ReactNode
|
||||
}
|
||||
|
||||
/*
|
||||
The radio group. It shares its row and its help with `ui/Check`: they are the
|
||||
same control with different cardinality, and when each screen wrote its own, a
|
||||
radio's help and a checkbox's help did not land on the same left edge.
|
||||
*/
|
||||
export function Radios({
|
||||
name,
|
||||
value,
|
||||
options,
|
||||
onChange,
|
||||
disabled,
|
||||
}: {
|
||||
name: string
|
||||
value: string
|
||||
options: RadioOption[]
|
||||
onChange: (v: string) => void
|
||||
disabled?: boolean
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
{options.map((o) => (
|
||||
<div key={o.value}>
|
||||
<label className={check.check}>
|
||||
<input
|
||||
type="radio"
|
||||
name={name}
|
||||
value={o.value}
|
||||
checked={value === o.value}
|
||||
disabled={disabled}
|
||||
onChange={() => onChange(o.value)}
|
||||
/>
|
||||
<span className={check.text}>{o.label}</span>
|
||||
</label>
|
||||
{o.help && <div className={check.help}>{o.help}</div>}
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/** Several loose blocks carrying the panel body's inset. */
|
||||
export function Notices({ children }: { children: ReactNode }) {
|
||||
return <div className={styles.notices}>{children}</div>
|
||||
}
|
||||
|
||||
/*
|
||||
Upstream's alerts are `<p><b>Note!</b> …</p>` in bold, inline. Here they become
|
||||
a coloured block: `Warning!` amber, `Note!` blue. They always go inside a
|
||||
`Notices`, which is what supplies the inset. When the alert supplied it itself on
|
||||
one screen and not the other, the same "Note!" came out indented in DHCP and flush
|
||||
in Settings.
|
||||
*/
|
||||
export function Warning({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<Alert type="warning" title="Warning!">
|
||||
{children}
|
||||
</Alert>
|
||||
)
|
||||
}
|
||||
|
||||
export function Note({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<Alert type="info" title="Note!">
|
||||
{children}
|
||||
</Alert>
|
||||
)
|
||||
}
|
||||
|
||||
/** Loose upstream text that is neither `Note!` nor `Warning!`. */
|
||||
export function Plain({ children }: { children: ReactNode }) {
|
||||
return <div className={styles.plain}>{children}</div>
|
||||
}
|
||||
|
||||
export function Help({ href, children }: { href: string; children: ReactNode }) {
|
||||
return (
|
||||
<div className={styles.link}>
|
||||
<a href={href} target="_blank" rel="noreferrer">
|
||||
{children}
|
||||
</a>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function Pre({ children }: { children: ReactNode }) {
|
||||
return <pre className={styles.pre}>{children}</pre>
|
||||
}
|
||||
|
||||
export interface Column<T> {
|
||||
key: keyof T & string
|
||||
label: string
|
||||
type?: 'text' | 'number'
|
||||
min?: number
|
||||
max?: number
|
||||
/** When the cell is not a text field: the TSIG algorithm dropdown. */
|
||||
render?: (row: T, set: (partial: Partial<T>) => void, id: string, name: string) => ReactNode
|
||||
}
|
||||
|
||||
/*
|
||||
Editable list: a header, one row per entry with its "Delete", and "Add" below.
|
||||
Upstream puts the "Add" in the header; here it goes underneath, because a table
|
||||
header with a button inside cannot be labelled.
|
||||
|
||||
There were two, and they had stopped being copies: DHCP's declared its columns and
|
||||
generated each cell's name and `id` by itself; Settings' received the cells
|
||||
already built, so every call site wrote its own `aria-label` by hand and none had
|
||||
an `id`. The declarative one wins, with an escape hatch (`render`) for the single
|
||||
cell that is not a text field.
|
||||
|
||||
The accessible name is `"<table> <row> <column>"`. It is unique by construction;
|
||||
the other scheme (`"<column> <row>"`) forced you to disambiguate the columns by
|
||||
hand, and out of that came an `aria-label` of "IPv4 UDP Limit" over a header that
|
||||
said "UDP Limit".
|
||||
|
||||
The deterministic `id` exists because upstream's validation alert says literally
|
||||
"the text field in focus": without being able to focus the failing cell, the alert
|
||||
cannot be resolved.
|
||||
*/
|
||||
export function EditableList<T extends Record<string, string>>({
|
||||
label,
|
||||
columns,
|
||||
rows,
|
||||
onChange,
|
||||
blank,
|
||||
help,
|
||||
disabled,
|
||||
cellId,
|
||||
}: {
|
||||
label: string
|
||||
columns: Column<T>[]
|
||||
rows: T[]
|
||||
onChange: (rows: T[]) => void
|
||||
blank: () => T
|
||||
help?: ReactNode
|
||||
disabled?: boolean
|
||||
cellId?: (row: number, column: string) => string
|
||||
}) {
|
||||
return (
|
||||
/*
|
||||
The help travels through `GroupRow` and is not drawn here underneath.
|
||||
|
||||
The dense-form design asks for all 41 in the third column, and the two belonging to the
|
||||
lists ARE two of those 41. Drawn inside the group they ended up under the
|
||||
table while the other thirty-nine were beside it: the same help in two places
|
||||
on one screen.
|
||||
*/
|
||||
<GroupRow label={label} help={help}>
|
||||
<div className={styles.listScroll}>
|
||||
<EditableTable
|
||||
className={styles.editable}
|
||||
header={
|
||||
<>
|
||||
{columns.map((c) => (
|
||||
<th key={c.key}>{c.label}</th>
|
||||
))}
|
||||
<th className={styles.tdel} />
|
||||
</>
|
||||
}
|
||||
>
|
||||
{rows.map((row, i) => {
|
||||
const set = (partial: Partial<T>) =>
|
||||
onChange(rows.map((r, j) => (j === i ? { ...r, ...partial } : r)))
|
||||
return (
|
||||
// Rows have no stable identity in upstream: they are numbered with
|
||||
// a random number. The index is the same criterion.
|
||||
// eslint-disable-next-line react/no-array-index-key
|
||||
<tr key={i}>
|
||||
{columns.map((c) => {
|
||||
const id = cellId?.(i, c.key)
|
||||
const name = `${label} ${i + 1} ${c.label}`
|
||||
return (
|
||||
<td key={c.key}>
|
||||
{c.render ? (
|
||||
c.render(row, set, id ?? '', name)
|
||||
) : (
|
||||
<Input
|
||||
id={id}
|
||||
aria-label={name}
|
||||
type={c.type ?? 'text'}
|
||||
min={c.min}
|
||||
max={c.max}
|
||||
disabled={disabled}
|
||||
value={row[c.key]}
|
||||
onChange={(e) => set({ [c.key]: e.target.value } as Partial<T>)}
|
||||
/>
|
||||
)}
|
||||
</td>
|
||||
)
|
||||
})}
|
||||
<td className={styles.tdel}>
|
||||
<Button
|
||||
variant="danger"
|
||||
disabled={disabled}
|
||||
onClick={() => onChange(rows.filter((_, j) => j !== i))}
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</EditableTable>
|
||||
</div>
|
||||
{/* With no rows, the table showed the headers and nothing beneath: blank
|
||||
does not say "there are none", it says "I do not know". */}
|
||||
{rows.length === 0 && <Empty compact>No entries.</Empty>}
|
||||
<div>
|
||||
<Button disabled={disabled} onClick={() => onChange([...rows, blank()])}>
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
</GroupRow>
|
||||
)
|
||||
}
|
||||
|
||||
export { Check } from './Check'
|
||||
export { HelpText, GroupRow, Row }
|
||||
export { styles as panelFormStyles }
|
||||
@@ -0,0 +1,66 @@
|
||||
import type { ComponentProps, ReactNode } from 'react'
|
||||
import { Button } from './Button'
|
||||
import { Icon } from './Icon'
|
||||
import { Tooltip } from './Tooltip'
|
||||
|
||||
/*
|
||||
A button the permission switches off, **and that does not disappear**.
|
||||
|
||||
It is the console's design rule, verbatim: *disabled, never hidden*. "A control that
|
||||
disappears depending on who is looking makes the screen change shape and leaves
|
||||
nobody aware that the action exists." And `Settings` did exactly the opposite:
|
||||
without permission, `Save Settings`, `Flush Cache` and the two backup ones **were
|
||||
not drawn**, so the bar had a different number of buttons depending on who looked
|
||||
and nobody could tell a permission was missing.
|
||||
|
||||
The three pieces:
|
||||
|
||||
· it is still **there**, switched off;
|
||||
· it carries a **padlock**, which is the word from the vocabulary: *padlock =
|
||||
you cannot*, and it is the opposite of the amber, which says you can;
|
||||
· and it **says WHICH** permission is missing, in a tooltip. A padlock that does
|
||||
not name the permission leaves the administrator guessing what to ask for.
|
||||
|
||||
`permission` is the server's string verbatim (`Settings.canModify`,
|
||||
`Cache.canDelete`), and it is drawn as the design wrote it: `Requires Cache: Delete`.
|
||||
It is neither translated nor reworded: it is what has to be asked for.
|
||||
|
||||
## Why the tooltip opens over a disabled button
|
||||
|
||||
A `<button disabled>` receives neither pointer nor focus events in any browser, so
|
||||
a tooltip hanging off it would never open. It works here because `ui/Tooltip`
|
||||
**already wraps its child in a `<span>` of its own** and hangs
|
||||
`onMouseEnter`/`onFocus` off that: the trigger is that wrapper and the button
|
||||
inside stays disabled. Checked in the browser on 2026-09-03 with a user with no
|
||||
permissions: `Requires Settings: Modify` and `Requires Cache: Delete` appear on
|
||||
hover.
|
||||
|
||||
There used to be one more `<span>` here, put in "so the tooltip had something
|
||||
alive to wrap", and it was redundant: a negative test that stayed green after
|
||||
removing it gave it away. A wrapper that can be removed without breaking anything
|
||||
was holding nothing up.
|
||||
*/
|
||||
export function PermissionButton({
|
||||
permission,
|
||||
children,
|
||||
...rest
|
||||
}: {
|
||||
/** The server's `Section.action`, or `undefined` when the permission is granted. */
|
||||
permission?: string
|
||||
children: ReactNode
|
||||
} & Omit<ComponentProps<typeof Button>, 'children'>) {
|
||||
if (permission == null) {
|
||||
return <Button {...rest}>{children}</Button>
|
||||
}
|
||||
|
||||
const [section, action] = permission.split('.')
|
||||
const verb = (action ?? '').replace(/^can/, '')
|
||||
return (
|
||||
<Tooltip text={`Requires ${section}: ${verb}`}>
|
||||
<Button {...rest} disabled>
|
||||
<Icon name="lock" size={13} />
|
||||
{children}
|
||||
</Button>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
The raw output box. See `Raw.tsx` for the why of each decision.
|
||||
|
||||
The border and the radius go on the BOX and the scrolling on the `<pre>` inside:
|
||||
if the border belonged to the element that scrolls, it would go with it when
|
||||
horizontal.
|
||||
*/
|
||||
.box {
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--r-3);
|
||||
background: var(--field);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* The frame for a server error: solid and in `--dan`. See `Raw.tsx`. */
|
||||
.error { border-color: var(--dan); }
|
||||
|
||||
.text {
|
||||
margin: 0;
|
||||
padding: var(--s-7) var(--s-8);
|
||||
font: var(--t-3)/1.55 var(--font-mono);
|
||||
color: var(--ink);
|
||||
/* It does NOT wrap: one line of the file is one line on screen. */
|
||||
white-space: pre;
|
||||
tab-size: 2;
|
||||
overflow: auto;
|
||||
overscroll-behavior: contain;
|
||||
max-height: var(--raw-height, 440px);
|
||||
}
|
||||
|
||||
/* The focus shows on the whole box and not on the text, which is what */
|
||||
.text:focus-visible {
|
||||
outline: 2px solid var(--acc-ink);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
/*
|
||||
`wrap`: a log. One line of the file starts at the edge and its continuations hang
|
||||
`--raw-hang` characters in, so the messages keep one column. `hanging each-line`
|
||||
inverts which lines take the indent: the first and every one after a newline of the
|
||||
file stay at the edge, and only the soft-wrapped ones move. `break-word` (not
|
||||
`anywhere`) only cuts a piece wider than the whole box; the breaks inside a long
|
||||
path or URL come from the caller's `<wbr>`. See `Raw.tsx`.
|
||||
*/
|
||||
.wrap {
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: break-word;
|
||||
text-indent: var(--raw-hang, 0ch) hanging each-line;
|
||||
}
|
||||
|
||||
/* `--bp-stack`: 26 characters of 43 is too much indent for a phone. */
|
||||
@media (max-width: 560px) {
|
||||
.wrap { text-indent: 2ch hanging each-line; }
|
||||
}
|
||||
|
||||
/*
|
||||
`fill`: the parent hands the height down. The box takes what its flex column gives
|
||||
it, never less than `--raw-height`, and the text is laid out of flow so the file
|
||||
adds nothing to the page's height. See `Raw.tsx`.
|
||||
*/
|
||||
.fill {
|
||||
position: relative;
|
||||
flex: 1 1 auto;
|
||||
min-height: var(--raw-height, 440px);
|
||||
}
|
||||
|
||||
.fill > .text {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
max-height: none;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
Raw output, and the things it can lose.
|
||||
|
||||
All three are checked against the CSS and not against the render, because jsdom
|
||||
does not apply CSS modules: `white-space` and `max-height` do not exist there.
|
||||
Skipping them for that reason would leave exactly what this primitive comes to
|
||||
decide without a guard, and it is the same reason `dev/master-switch-signal.test.mjs`
|
||||
exists. What IS checked against the render is what the DOM does have: the
|
||||
accessible name and the focus.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { Raw } from './Raw'
|
||||
|
||||
describe('the raw output', () => {
|
||||
it('it can be focused, so it can be read with a keyboard', () => {
|
||||
render(<Raw text="DNS response">{'{ "a": 1 }'}</Raw>)
|
||||
expect(screen.getByLabelText('DNS response')).toHaveAttribute('tabindex', '0')
|
||||
})
|
||||
|
||||
/*
|
||||
A tab stop that announces nothing is worse than none: the cursor lands inside a
|
||||
box and the screen reader does not say what of.
|
||||
*/
|
||||
it('and it announces WHAT it is, not just that there is something', () => {
|
||||
render(<Raw text="2026-09-03 log file">text</Raw>)
|
||||
expect(screen.getByLabelText('2026-09-03 log file')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('the text travels intact, with its spaces', () => {
|
||||
render(<Raw text="x">{'{\n "k": 1\n}'}</Raw>)
|
||||
expect(screen.getByLabelText('x').textContent).toBe('{\n "k": 1\n}')
|
||||
})
|
||||
|
||||
/* On the box and not on the text, because with `fill` it is the box's floor. */
|
||||
it('the height is a cap and can be set case by case', () => {
|
||||
render(<Raw text="x" height={140}>y</Raw>)
|
||||
expect(screen.getByLabelText('x').parentElement).toHaveStyle({ '--raw-height': '140px' })
|
||||
})
|
||||
|
||||
/* DNS Client's JSON keeps its indentation: nothing wraps unless asked. */
|
||||
it('by default it neither wraps nor fills', () => {
|
||||
const { container } = render(<Raw text="x">y</Raw>)
|
||||
expect(container.firstElementChild?.className).not.toMatch(/fill/)
|
||||
expect(screen.getByLabelText('x').className).not.toMatch(/wrap/)
|
||||
expect(screen.getByLabelText('x').style.getPropertyValue('--raw-hang')).toBe('')
|
||||
})
|
||||
|
||||
it('with wrap, continuation lines hang by the characters asked for', () => {
|
||||
render(<Raw text="x" wrap hang={26}>y</Raw>)
|
||||
expect(screen.getByLabelText('x').className).toMatch(/wrap/)
|
||||
expect(screen.getByLabelText('x')).toHaveStyle({ '--raw-hang': '26ch' })
|
||||
})
|
||||
|
||||
it('with fill, the box takes the height handed down', () => {
|
||||
const { container } = render(<Raw text="x" fill height={240}>y</Raw>)
|
||||
expect(container.firstElementChild?.className).toMatch(/fill/)
|
||||
expect(container.firstElementChild).toHaveStyle({ '--raw-height': '240px' })
|
||||
})
|
||||
|
||||
/* The `--dan` frame is for the error the server returns as TEXT, which has
|
||||
nowhere else to go. It is not the normal state. */
|
||||
it('with no tone the box is not marked as an error', () => {
|
||||
const { container } = render(<Raw text="x">y</Raw>)
|
||||
expect(container.firstElementChild?.className).not.toMatch(/error/)
|
||||
})
|
||||
|
||||
it('with the error tone, it is', () => {
|
||||
const { container } = render(<Raw text="x" tone="error">y</Raw>)
|
||||
expect(container.firstElementChild?.className).toMatch(/error/)
|
||||
})
|
||||
})
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import styles from './Raw.module.css'
|
||||
|
||||
/*
|
||||
Raw output: a block of text that is NOT interpreted.
|
||||
|
||||
It is the first pattern of the tool screens. The two surfaces that show what the server
|
||||
returned verbatim use it (`DNS Client`'s JSON response and `View Logs`'s file),
|
||||
and it exists as a primitive because it was written TWICE, in
|
||||
`dnsclient/DnsClient.module.css` and in `logs/Logs.module.css`, and had already
|
||||
drifted: one capped at `460px` and the other at `60vh`.
|
||||
|
||||
## Why it does not wrap, unless the caller asks
|
||||
|
||||
Both said `white-space: pre-wrap; word-break: break-word`, and that is what this
|
||||
primitive comes to remove. A wrapped JSON line **stops being indented**, which is
|
||||
the only thing that makes a two-thousand-character JSON readable. It is paid for
|
||||
with a horizontal scrollbar, and for JSON that is the right price: not one
|
||||
character is lost and nothing lies about the structure. DNS Client keeps it.
|
||||
|
||||
`wrap` is the other answer, and it is for a log (`View Logs`). There the end of a
|
||||
line is the part that says something (the list URL, the zone file, the exception),
|
||||
and on the showcase's server log of 2026-10-15 **365 of its 572 lines (64 %) ran
|
||||
past the box at 1440 (122 characters) and 570 at 390 (43)**: their ends sat behind a scrollbar
|
||||
that moves every line at once and takes the timestamps with it. So `wrap`
|
||||
soft-wraps and keeps each line ONE entry with a hanging indent: an entry's first
|
||||
line starts at the edge and only its continuations are pushed in, by `hang`
|
||||
characters, the width of the log's `[yyyy-MM-dd HH:mm:ss UTC] ` prefix. The
|
||||
messages read as a column of their own, and a line at the edge is a new entry.
|
||||
|
||||
It is `text-indent: … hanging each-line` on the `<pre>` itself, with no element per
|
||||
line, so the text in the DOM, the copied text and what a screen reader reads are
|
||||
the file as it came. Below 560 px (`--bp-stack`) the indent drops to `2ch`: 26 of
|
||||
the 43 characters a phone gets would leave 17 for each continuation. A line breaks
|
||||
at its spaces and wherever the caller put a `<wbr>` (`View Logs` puts one after the
|
||||
separators of a long path or URL, as `ui/UrlText` does); `overflow-wrap:
|
||||
break-word` only cuts a piece that alone is wider than the box.
|
||||
|
||||
No wrap toggle is offered because **that would be adding a control**, and design
|
||||
does not get to decide that: each surface gets the one that serves its text.
|
||||
|
||||
## Why the height is capped, or handed down
|
||||
|
||||
The panel does not grow with the content: the content scrolls inside it. Measured
|
||||
in the harness, the `View Logs` viewer loaded **1,073,928 characters**; a panel
|
||||
that grows with that stops being a panel and turns the screen into the file.
|
||||
|
||||
By default `height` is that cap. With `fill`, the box takes the height its parent
|
||||
gives it instead (the parent is a flex column that has been handed the rest of the
|
||||
window), and `height` becomes the floor under which it does not shrink. The text is
|
||||
then laid out of flow (`position: absolute`), so however long the file is it adds
|
||||
nothing to the height of the page: the box is as tall as the window allows, never
|
||||
as tall as the log.
|
||||
|
||||
## Why it is focusable, and why it carries a name
|
||||
|
||||
A region that scrolls and cannot be focused **cannot be read with a keyboard**:
|
||||
without `tabIndex` there is no way to get the cursor inside to use the arrows. And
|
||||
a tab stop that announces nothing is worse than none, so the name is compulsory:
|
||||
`text` ends up in `aria-label`.
|
||||
|
||||
`overscroll-behavior: contain` so that reaching the end of the block does not drag
|
||||
the whole page, which is the classic defect of a scrolling box inside another.
|
||||
*/
|
||||
export function Raw({
|
||||
children,
|
||||
text,
|
||||
height = 440,
|
||||
tone = 'normal',
|
||||
wrap = false,
|
||||
hang = 0,
|
||||
fill = false,
|
||||
}: {
|
||||
children: ReactNode
|
||||
/** What this is, for whoever hears it instead of seeing it. Compulsory on purpose. */
|
||||
text: string
|
||||
/** The cap in pixels: the block never grows past it. With `fill`, the floor. */
|
||||
height?: number
|
||||
/*
|
||||
`error` only for the case where **the server returns the error as text** and
|
||||
there is nowhere else to put it (the `View Logs` viewer, `logs.js:170-172`). The
|
||||
frame turns `--dan`: the error is framed, not disguised as data. It is the one
|
||||
exception to the design rule "solid = error", and that is why the frame IS solid.
|
||||
*/
|
||||
tone?: 'normal' | 'error'
|
||||
/** Soft-wrap with a hanging indent instead of scrolling sideways. See above. */
|
||||
wrap?: boolean
|
||||
/** With `wrap`, how many characters a continuation line is pushed in. */
|
||||
hang?: number
|
||||
/** Take the height the parent (a flex column) hands down. See above. */
|
||||
fill?: boolean
|
||||
}) {
|
||||
const box = [styles.box, tone === 'error' ? styles.error : null, fill ? styles.fill : null]
|
||||
const pre = [styles.text, wrap ? styles.wrap : null]
|
||||
return (
|
||||
<div
|
||||
className={box.filter(Boolean).join(' ')}
|
||||
style={{ '--raw-height': `${height}px` } as React.CSSProperties}
|
||||
>
|
||||
<pre
|
||||
className={pre.filter(Boolean).join(' ')}
|
||||
style={wrap ? ({ '--raw-hang': `${hang}ch` } as React.CSSProperties) : undefined}
|
||||
tabIndex={0}
|
||||
aria-label={text}
|
||||
>
|
||||
{children}
|
||||
</pre>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { fireEvent, render, screen } from '@testing-library/react'
|
||||
import { RouteLink } from './RouteLink'
|
||||
import { forgetRoot } from '../app/route'
|
||||
|
||||
afterEach(() => {
|
||||
window.history.replaceState(null, '', '/')
|
||||
forgetRoot()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
/*
|
||||
What the browser would have done with the click once React is through with it.
|
||||
jsdom does not navigate on its own, so whether the application took the click is
|
||||
read from `defaultPrevented`, at the window, after React's handler ran.
|
||||
*/
|
||||
function clickAndSee(link: HTMLElement, init: MouseEventInit = {}): boolean {
|
||||
let prevented = false
|
||||
const seen = (e: Event) => {
|
||||
prevented = e.defaultPrevented
|
||||
e.preventDefault()
|
||||
}
|
||||
window.addEventListener('click', seen)
|
||||
fireEvent.click(link, init)
|
||||
window.removeEventListener('click', seen)
|
||||
return prevented
|
||||
}
|
||||
|
||||
describe('RouteLink', () => {
|
||||
it('is a real link, with the address it goes to', () => {
|
||||
render(<RouteLink to={{ section: 'logs', sub: 'Query Logs' }}>Open Query Logs</RouteLink>)
|
||||
expect(screen.getByRole('link', { name: 'Open Query Logs' })).toHaveAttribute('href', '/logs/query-logs/')
|
||||
})
|
||||
|
||||
it('a plain click navigates inside the console and fires popstate', () => {
|
||||
const heard = vi.fn()
|
||||
window.addEventListener('popstate', heard)
|
||||
render(<RouteLink to={{ section: 'logs', sub: 'Query Logs' }}>Open Query Logs</RouteLink>)
|
||||
const prevented = clickAndSee(screen.getByRole('link', { name: 'Open Query Logs' }))
|
||||
window.removeEventListener('popstate', heard)
|
||||
expect(prevented).toBe(true)
|
||||
expect(window.location.pathname).toBe('/logs/query-logs/')
|
||||
expect(heard).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('a ctrl-click is left to the browser', () => {
|
||||
const heard = vi.fn()
|
||||
window.addEventListener('popstate', heard)
|
||||
render(<RouteLink to={{ section: 'logs', sub: 'Query Logs' }}>Open Query Logs</RouteLink>)
|
||||
const prevented = clickAndSee(screen.getByRole('link', { name: 'Open Query Logs' }), { ctrlKey: true })
|
||||
window.removeEventListener('popstate', heard)
|
||||
expect(prevented).toBe(false)
|
||||
expect(window.location.pathname).toBe('/')
|
||||
expect(heard).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { navigateTo, plainClick, toTrail, type Route } from '../app/route'
|
||||
|
||||
/*
|
||||
A link from inside a screen to another section of the console: Recently Blocked's
|
||||
"Open Query Logs", Lists' "Settings › Blocking".
|
||||
|
||||
It is a real `<a>` with the real address (it can be copied, and a modifier or
|
||||
middle click opens it in another tab, which is what the routes existing as folders
|
||||
is for), and a plain click moves the console without reloading it, the way the
|
||||
sidebar and the sub-tabs already do. A bare `<a href>` reloaded the whole console
|
||||
and threw away every screen's state on the way.
|
||||
*/
|
||||
export function RouteLink({ to, children }: { to: Route; children: ReactNode }) {
|
||||
return (
|
||||
<a
|
||||
href={toTrail(to)}
|
||||
onClick={(e) => {
|
||||
if (!plainClick(e)) return
|
||||
e.preventDefault()
|
||||
navigateTo(to)
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
/*
|
||||
Replaces the fourteen copies of `.hrow` / `.zt` / `.tags` / `.acts` that each
|
||||
section module had made for itself. Every value comes from `theme/tokens.css`:
|
||||
not a single loose px is written here.
|
||||
*/
|
||||
|
||||
.hrow {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: var(--s-11);
|
||||
margin-bottom: var(--gap-block);
|
||||
}
|
||||
|
||||
.left { min-width: 0; }
|
||||
|
||||
/*
|
||||
The path. In normal case and at body size: in tight small caps it would read as a
|
||||
magazine kicker, which is decoration, and this is navigation.
|
||||
*/
|
||||
.trail {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--s-3);
|
||||
margin-bottom: var(--s-2);
|
||||
}
|
||||
|
||||
.title {
|
||||
margin: 0;
|
||||
font-size: var(--t-7);
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.025em;
|
||||
color: var(--ink);
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
/* One sentence under the title (Blocking only): body size, muted, and no wider than
|
||||
a notice so it reads as a line and not a paragraph. */
|
||||
.subtitle {
|
||||
margin: var(--s-2) 0 0;
|
||||
max-width: var(--notice-max);
|
||||
font-size: var(--t-4);
|
||||
line-height: 1.5;
|
||||
color: var(--mute);
|
||||
}
|
||||
|
||||
/* When the screen is a detail view, the crumb is also the way back. */
|
||||
.ctx {
|
||||
font-family: inherit;
|
||||
font-size: var(--t-4);
|
||||
color: var(--mute);
|
||||
background: none;
|
||||
border: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
button.ctx { cursor: pointer; }
|
||||
button.ctx:hover { color: var(--acc-ink); }
|
||||
|
||||
.sep { color: var(--faint); flex: none; }
|
||||
|
||||
.tags {
|
||||
display: flex;
|
||||
gap: var(--s-3);
|
||||
margin-top: var(--s-5);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.acts {
|
||||
display: flex;
|
||||
gap: var(--s-4);
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
/* It aligns with the title, not with the kicker: otherwise the action bar of a
|
||||
section with sub-tabs sits higher than that of one without. */
|
||||
padding-top: var(--s-1);
|
||||
}
|
||||
|
||||
/* When narrow the title and the action bar stack: otherwise the title column
|
||||
narrows until it breaks the section name letter by letter. */
|
||||
@media (max-width: 720px) {
|
||||
.hrow {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: var(--s-8);
|
||||
}
|
||||
|
||||
.acts {
|
||||
justify-content: flex-start;
|
||||
padding-top: 0;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
The column of a screen whose header sits inside a `flex` container with `gap`. It
|
||||
lives here and not in the screens because what it corrects is this header.
|
||||
|
||||
The gap under the title is `--gap-block` across the whole console. On these
|
||||
screens it came to 38 px instead of 24 because in flex the gap ADDS to the child's
|
||||
margin: the header contributed its 24 and the container another 14. It is
|
||||
subtracted, and the subtraction is written ONCE: the container's gap lives in
|
||||
`--gap` and both rules read it from there, so changing it does not knock the
|
||||
title out of line again.
|
||||
*/
|
||||
.screen {
|
||||
--gap: var(--s-9);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--gap);
|
||||
}
|
||||
|
||||
/* The section header, which is always the first child. */
|
||||
.screen > :first-child { margin-bottom: calc(var(--gap-block) - var(--gap)); }
|
||||
@@ -0,0 +1,107 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { Icon } from './Icon'
|
||||
import styles from './SectionHeader.module.css'
|
||||
|
||||
/*
|
||||
A section's header. There used to be four different treatments:
|
||||
|
||||
· 22 px in Zones, Cache, Allowed, Blocked, Apps, DHCP, Administration and Logs
|
||||
· 19 px in About
|
||||
· **14 px** in Settings, with the panel name in a muted `span`
|
||||
· **none at all** in Dashboard and DNS Client
|
||||
|
||||
The 14 px one was the worst possible place for the smallest title: Settings is the
|
||||
longest screen in the console (5,400 px of scroll, 54 fields) and the one that can
|
||||
take the server down. And all nine sub-tabs showed the same "Settings", so the
|
||||
title was no use either for knowing where you were or for finding it with Ctrl+F.
|
||||
|
||||
## The composition
|
||||
|
||||
Above the title goes a PATH, not a kicker:
|
||||
|
||||
DHCP ›
|
||||
Leases
|
||||
|
||||
The difference is not where it sits, it is what each thing is. A kicker is
|
||||
editorial decoration (tight muted small caps) and adds nothing; a path is
|
||||
navigation, and it is needed here because some names collide: "Cache" is a
|
||||
top-level section AND a Settings sub-tab, and "General" or "Logging" say nothing
|
||||
on their own. That is why it goes in a `nav`, in normal case, and the `h1` remains
|
||||
exactly the name of the screen.
|
||||
|
||||
With no sub-tabs there is no path: the title is the section name, plain.
|
||||
|
||||
## A subtitle only where the words are ours
|
||||
|
||||
`subtitle` is one plain sentence under the title saying what the screen is for.
|
||||
Upstream writes none, and every other section keeps upstream's texts and nothing
|
||||
more, so only the Blocking tabs pass one (deviation 2 in CONVENTIONS.md, 2026-10-15),
|
||||
declared in the header comment of each file that writes it. Cache passes the
|
||||
sentence its identity band already said (`screens/lists/Lists.tsx`): it moved up
|
||||
when the band went, it is not a new one.
|
||||
|
||||
## Tags are STATE, not counts
|
||||
|
||||
`labels` is for state pills (`Primary`, `Enabled`, `DNSSEC`). Counts have their
|
||||
place in the count bar above the table; putting them here with the same look as a
|
||||
state was another of the inconsistencies: the same pill meant a figure sometimes,
|
||||
a state other times and a setting others.
|
||||
*/
|
||||
|
||||
export function SectionHeader({
|
||||
section,
|
||||
onBack,
|
||||
title,
|
||||
subtitle,
|
||||
labels,
|
||||
actions,
|
||||
tabs,
|
||||
}: {
|
||||
/** The section name. Only when there are sub-tabs. */
|
||||
section?: string
|
||||
/** On a detail screen, the way back to the section. The kicker becomes that
|
||||
* path: there used to be a "← Zones" above and a "ZONES" below, two elements
|
||||
* saying the same thing two centimetres apart. */
|
||||
onBack?: () => void
|
||||
/** The most specific name: the sub-tab if there is one, otherwise the section. */
|
||||
title: string
|
||||
/** What the screen is for, in one sentence. Blocking only: see above. */
|
||||
subtitle?: string
|
||||
/** STATE pills. Counts go in the count bar. */
|
||||
labels?: ReactNode
|
||||
/** Action bar, always top right. */
|
||||
actions?: ReactNode
|
||||
/**
|
||||
* The section's sub-navigation, drawn UNDER the header row. It goes here and
|
||||
* not in the caller so that the four sections that have one put it in the same
|
||||
* place: title, then tabs, then content, which is what the design draws for
|
||||
* Administration and for Logs.
|
||||
*/
|
||||
tabs?: ReactNode
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
<div className={styles.hrow}>
|
||||
<div className={styles.left}>
|
||||
{section != null && (
|
||||
<nav className={styles.trail} aria-label="Breadcrumb">
|
||||
{onBack != null ? (
|
||||
<button type="button" className={styles.ctx} onClick={onBack}>
|
||||
{section}
|
||||
</button>
|
||||
) : (
|
||||
<span className={styles.ctx}>{section}</span>
|
||||
)}
|
||||
<Icon name="chevronRight" size={12} className={styles.sep} />
|
||||
</nav>
|
||||
)}
|
||||
<h1 className={styles.title}>{title}</h1>
|
||||
{subtitle != null && <p className={styles.subtitle}>{subtitle}</p>}
|
||||
{labels != null && <div className={styles.tags}>{labels}</div>}
|
||||
</div>
|
||||
{actions != null && <div className={styles.acts}>{actions}</div>}
|
||||
</div>
|
||||
{tabs}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
/*
|
||||
The section index. A column beside the form, a strip underneath.
|
||||
|
||||
It looks like `Segmented` and **it is not painted like it, on purpose**.
|
||||
`Segmented` marks the active one with FILLED amber, because there you have chosen
|
||||
a value and the others have stopped being there. Here you have chosen nothing: the
|
||||
ten sections are still on the page. Filling it would say "you picked this one",
|
||||
which is false.
|
||||
|
||||
So the active one is marked with an **edge** in `--acc` and its text in `--ink`.
|
||||
It is the same pair of colours saying something else: not "this one is yours" but
|
||||
"you are here". And it leaves the fill free for what really is a choice.
|
||||
*/
|
||||
/*
|
||||
Written strip first, and the column on top of it, so that one set of rules serves
|
||||
both ways of asking for the strip: below `--bp-index`, as every screen gets it, and
|
||||
always, for a screen that decides by its own width and passes `strip`
|
||||
(`.strip`, Settings and SSO beside their dense form). Before 2026-10-16 the strip
|
||||
lived inside the `max-width: 960px` query alone; a second copy of it for `.strip`
|
||||
would have been two strips to keep equal.
|
||||
|
||||
THE STRIP. A column no longer fits beside the form, and stacking ten links on top
|
||||
of it would push the first field off the screen. The strip scrolls and **loses
|
||||
none of them**: every item is `flex: 0 0 auto` and does not wrap, so at 390 px all
|
||||
ten are still there and are reached by rolling the strip.
|
||||
|
||||
`-webkit-overflow-scrolling` is not set: momentum scrolling has been the default
|
||||
since iOS 13 and the property no longer does anything.
|
||||
|
||||
It is PINNED (2026-10-16): on a 5,400 px pane a strip that scrolls away is only an
|
||||
index at the very top, and the entry that follows the scroll is never seen. It pins
|
||||
under whatever is already pinned above the content (`--stuck-top`, the top bar on a
|
||||
narrow screen, `app/Shell.module.css`), at its exact height (`--index-strip`), so a
|
||||
dense form's block titles can pin right below it (`ui/PanelForm.module.css`). Its
|
||||
background is the page's, so what scrolls under it does not show through, and it
|
||||
sits on the sticky layer, above those titles and with the save bar.
|
||||
*/
|
||||
.index {
|
||||
flex: none;
|
||||
/* As wide as the column it pins over, even when its entries are narrower: in a
|
||||
flex column (`ui/IndexedForm`) `start` shrank it to its entries, and what
|
||||
scrolled underneath showed beside it (1440, 2026-10-16). */
|
||||
align-self: stretch;
|
||||
position: sticky;
|
||||
top: var(--stuck-top, 0px);
|
||||
z-index: var(--layer-sticky);
|
||||
height: var(--index-strip);
|
||||
box-sizing: border-box;
|
||||
background: var(--bg);
|
||||
overflow-x: auto;
|
||||
/*
|
||||
The two that make the `overflow-x` above worth anything.
|
||||
|
||||
Measured at 960: without them the strip came out 991 px inside a 960 viewport
|
||||
and **what scrolled was the page**, not the strip. A flex item does not go
|
||||
below the width of its content while its `min-width` is `auto`, so `overflow-x`
|
||||
never came into play: there was nothing to overflow because the parent was the
|
||||
one giving way.
|
||||
|
||||
They go here and not in whoever uses it: the primitive has to survive being put
|
||||
in a flex container, which is where it is going: beside the form.
|
||||
*/
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
/*
|
||||
3 px, which is exactly what the focus halo measures. An `overflow-x` that is not
|
||||
`visible` turns `overflow-y` to `auto` as well (it is what the CSS specification
|
||||
says when only one of the two stops being `visible`), so anything sticking out
|
||||
above or below is clipped. With 2 px it ate 1 px of the first item's halo when it
|
||||
took focus. A bitten halo is the only focus signal this has.
|
||||
*/
|
||||
padding: 3px 0;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
gap: var(--s-2);
|
||||
}
|
||||
|
||||
.list > li {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.item {
|
||||
display: block;
|
||||
font-size: var(--t-4);
|
||||
line-height: 1.4;
|
||||
padding: var(--s-4) var(--s-7);
|
||||
color: var(--mute);
|
||||
text-decoration: none;
|
||||
white-space: nowrap;
|
||||
/* The edge is ALWAYS there, transparent when it does not apply: if it only
|
||||
appeared on the active one, all ten would move 2 px every time it changes.
|
||||
In the strip it is at the bottom: on the left it would act as a separator
|
||||
between pills and read as a grid, not as position. */
|
||||
border-bottom: 2px solid transparent;
|
||||
border-radius: var(--r-2) var(--r-2) 0 0;
|
||||
}
|
||||
|
||||
.item:hover {
|
||||
color: var(--ink);
|
||||
background: var(--pan2);
|
||||
}
|
||||
|
||||
/*
|
||||
The focus ring, visible and with the same halo as a field.
|
||||
|
||||
There is no global rule for the link (`base.css` only sets one on `select` and on
|
||||
`input[type=file]`), so without this the index would keep the browser's default
|
||||
outline, which changes from one machine to another. It is exactly what the icon
|
||||
set already had to fix on its own.
|
||||
*/
|
||||
.item:focus-visible {
|
||||
outline: none;
|
||||
color: var(--ink);
|
||||
box-shadow: var(--halo-focus);
|
||||
}
|
||||
|
||||
/* `location`, not `selected`: you are here, you have not chosen this. */
|
||||
.item[aria-current='location'] {
|
||||
color: var(--ink);
|
||||
font-weight: 550;
|
||||
border-bottom-color: var(--acc-ink);
|
||||
background: var(--pan2);
|
||||
}
|
||||
|
||||
/*
|
||||
THE COLUMN, above `--bp-index` and unless the screen asked for the strip: beside
|
||||
the form, pinned while it scrolls, each entry on its own line with its edge on the
|
||||
left.
|
||||
*/
|
||||
@media (min-width: 961px) {
|
||||
.index:not(.strip) {
|
||||
width: var(--index-col);
|
||||
flex: 0 0 var(--index-col);
|
||||
align-self: start;
|
||||
position: sticky;
|
||||
/* Level with the form's sticky bar, so it does not slide under it while
|
||||
scrolling. */
|
||||
top: var(--s-9);
|
||||
overflow-x: visible;
|
||||
min-width: auto;
|
||||
max-width: none;
|
||||
padding: 0;
|
||||
border-bottom: 0;
|
||||
z-index: auto;
|
||||
height: auto;
|
||||
background: none;
|
||||
}
|
||||
|
||||
.index:not(.strip) .list {
|
||||
flex-direction: column;
|
||||
gap: var(--s-1);
|
||||
}
|
||||
|
||||
.index:not(.strip) .list > li {
|
||||
flex: 0 1 auto;
|
||||
}
|
||||
|
||||
.index:not(.strip) .item {
|
||||
white-space: normal;
|
||||
border-bottom: 0;
|
||||
border-left: 2px solid transparent;
|
||||
border-radius: var(--r-2);
|
||||
}
|
||||
|
||||
.index:not(.strip) .item[aria-current='location'] {
|
||||
border-left-color: var(--acc-ink);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest'
|
||||
import { render, screen, cleanup } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { SectionIndex } from './SectionIndex'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
const SECTIONS = [
|
||||
{ id: 'local-parameters', label: 'Local Parameters' },
|
||||
{ id: 'zone-defaults', label: 'Zone Defaults' },
|
||||
{ id: 'rate-limiting', label: 'Rate Limiting' },
|
||||
]
|
||||
|
||||
describe('SectionIndex', () => {
|
||||
it('it draws one link per section, in order and pointing at its anchor', () => {
|
||||
render(<SectionIndex sections={SECTIONS} />)
|
||||
|
||||
const links = screen.getAllByRole('link')
|
||||
expect(links.map((a) => a.textContent)).toEqual([
|
||||
'Local Parameters',
|
||||
'Zone Defaults',
|
||||
'Rate Limiting',
|
||||
])
|
||||
expect(links.map((a) => a.getAttribute('href'))).toEqual([
|
||||
'#local-parameters',
|
||||
'#zone-defaults',
|
||||
'#rate-limiting',
|
||||
])
|
||||
})
|
||||
|
||||
/*
|
||||
`location` and not `selected`. The distinction is the whole primitive: `selected`
|
||||
asserts you have chosen one of several exclusive options, and here the ten
|
||||
sections are all still on the page.
|
||||
*/
|
||||
it('it marks the active section with aria-current="location"', () => {
|
||||
render(<SectionIndex sections={SECTIONS} active="zone-defaults" />)
|
||||
|
||||
expect(screen.getByRole('link', { name: 'Zone Defaults' })).toHaveAttribute(
|
||||
'aria-current',
|
||||
'location',
|
||||
)
|
||||
})
|
||||
|
||||
it('it marks no other one, not even with "false"', () => {
|
||||
render(<SectionIndex sections={SECTIONS} active="zone-defaults" />)
|
||||
|
||||
const others = screen
|
||||
.getAllByRole('link')
|
||||
.filter((a) => a.textContent !== 'Zone Defaults')
|
||||
expect(others).toHaveLength(2)
|
||||
for (const a of others) expect(a.hasAttribute('aria-current')).toBe(false)
|
||||
})
|
||||
|
||||
it('with no active section it marks none', () => {
|
||||
render(<SectionIndex sections={SECTIONS} />)
|
||||
|
||||
for (const a of screen.getAllByRole('link')) {
|
||||
expect(a.hasAttribute('aria-current')).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
/*
|
||||
It does not select. If an `aria-selected`, an `aria-pressed` or a `role="tab"`
|
||||
ever appeared here, this would be `Segmented` under another name, which is
|
||||
exactly what the design warned against.
|
||||
*/
|
||||
it('it announces no selection of any kind', () => {
|
||||
const { container } = render(<SectionIndex sections={SECTIONS} active="rate-limiting" />)
|
||||
|
||||
expect(container.querySelector('[aria-selected]')).toBeNull()
|
||||
expect(container.querySelector('[aria-pressed]')).toBeNull()
|
||||
expect(container.querySelector('[role="tab"]')).toBeNull()
|
||||
expect(container.querySelector('[role="tablist"]')).toBeNull()
|
||||
expect(screen.queryAllByRole('button')).toHaveLength(0)
|
||||
})
|
||||
|
||||
/* Nor does it hide. It takes no children and owns no content: it moves the wheel. */
|
||||
it('it hides nothing', () => {
|
||||
const { container } = render(<SectionIndex sections={SECTIONS} active="rate-limiting" />)
|
||||
|
||||
expect(container.querySelector('[hidden]')).toBeNull()
|
||||
expect(container.querySelector('[aria-hidden]')).toBeNull()
|
||||
})
|
||||
|
||||
it('the index carries a name for whoever cannot see the screen', () => {
|
||||
render(<SectionIndex sections={SECTIONS} />)
|
||||
expect(screen.getByRole('navigation', { name: 'On this page' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('the name can be changed', () => {
|
||||
render(<SectionIndex sections={SECTIONS} label="Settings sections" />)
|
||||
expect(screen.getByRole('navigation', { name: 'Settings sections' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
/*
|
||||
Native navigation: they are links, so the tab key walks them in order without
|
||||
anyone setting a `tabIndex`. It is checked because the alternative (buttons with
|
||||
an `onClick` that scrolls) would have had to be reimplemented.
|
||||
*/
|
||||
it('the tab key walks them in order, with no tabIndex of their own', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<SectionIndex sections={SECTIONS} />)
|
||||
|
||||
const links = screen.getAllByRole('link')
|
||||
for (const a of links) expect(a.hasAttribute('tabindex')).toBe(false)
|
||||
|
||||
await user.tab()
|
||||
expect(links[0]).toHaveFocus()
|
||||
await user.tab()
|
||||
expect(links[1]).toHaveFocus()
|
||||
await user.tab()
|
||||
expect(links[2]).toHaveFocus()
|
||||
})
|
||||
|
||||
it('the mark follows the active section when it changes', () => {
|
||||
const { rerender } = render(<SectionIndex sections={SECTIONS} active="local-parameters" />)
|
||||
expect(screen.getByRole('link', { name: 'Local Parameters' })).toHaveAttribute(
|
||||
'aria-current',
|
||||
'location',
|
||||
)
|
||||
|
||||
rerender(<SectionIndex sections={SECTIONS} active="rate-limiting" />)
|
||||
expect(screen.getByRole('link', { name: 'Local Parameters' }).hasAttribute('aria-current')).toBe(
|
||||
false,
|
||||
)
|
||||
expect(screen.getByRole('link', { name: 'Rate Limiting' })).toHaveAttribute(
|
||||
'aria-current',
|
||||
'location',
|
||||
)
|
||||
})
|
||||
|
||||
/*
|
||||
Watching the scroll belongs to the SCREEN, not to this primitive.
|
||||
|
||||
`active` comes in as a prop and who works it out is screen wiring. This exists so
|
||||
that wiring does not creep in here over time: if it ever does,
|
||||
then the decision to bring it in is taken in the open, not by stealth.
|
||||
*/
|
||||
it('it does not watch the scroll: that is wiring the screen does', () => {
|
||||
const onWindow = vi.spyOn(window, 'addEventListener')
|
||||
const onDocument = vi.spyOn(document, 'addEventListener')
|
||||
const observer = vi.fn()
|
||||
vi.stubGlobal('IntersectionObserver', observer)
|
||||
|
||||
render(<SectionIndex sections={SECTIONS} active="zone-defaults" />)
|
||||
|
||||
const events = [...onWindow.mock.calls, ...onDocument.mock.calls].map(([e]) => e)
|
||||
expect(events).not.toContain('scroll')
|
||||
expect(events).not.toContain('hashchange')
|
||||
expect(observer).not.toHaveBeenCalled()
|
||||
|
||||
onWindow.mockRestore()
|
||||
onDocument.mockRestore()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
})
|
||||
|
||||
/*
|
||||
As a strip wider than the screen, the entry you are in can be out of sight: the
|
||||
strip rolls itself to it, and only itself, never the page.
|
||||
*/
|
||||
describe('SectionIndex: the strip keeps the active entry in view', () => {
|
||||
function overflowing(nav: HTMLElement) {
|
||||
Object.defineProperty(nav, 'scrollWidth', { configurable: true, value: 1000 })
|
||||
Object.defineProperty(nav, 'clientWidth', { configurable: true, value: 300 })
|
||||
nav.getBoundingClientRect = () => ({ left: 0 }) as DOMRect
|
||||
for (const [i, a] of [...nav.querySelectorAll('a')].entries()) {
|
||||
Object.defineProperty(a, 'offsetWidth', { configurable: true, value: 100 })
|
||||
a.getBoundingClientRect = () => ({ left: i * 120 }) as DOMRect
|
||||
}
|
||||
const roll = vi.fn()
|
||||
nav.scrollTo = roll as unknown as HTMLElement['scrollTo']
|
||||
return roll
|
||||
}
|
||||
|
||||
it('rolls the strip, centred, smoothly, and does not move the page', () => {
|
||||
const page = vi.spyOn(window, 'scrollTo').mockImplementation(() => {})
|
||||
const { rerender } = render(<SectionIndex sections={SECTIONS} active={SECTIONS[0].id} strip />)
|
||||
const roll = overflowing(screen.getByRole('navigation'))
|
||||
const last = SECTIONS[SECTIONS.length - 1]
|
||||
rerender(<SectionIndex sections={SECTIONS} active={last.id} strip />)
|
||||
const left = (SECTIONS.length - 1) * 120 - (300 - 100) / 2
|
||||
expect(roll).toHaveBeenCalledWith({ left, behavior: 'smooth' })
|
||||
expect(page).not.toHaveBeenCalled()
|
||||
page.mockRestore()
|
||||
})
|
||||
|
||||
it('does not move for an entry already in view, and moves instantly with reduced motion', () => {
|
||||
const { rerender } = render(<SectionIndex sections={SECTIONS} active={SECTIONS[2].id} strip />)
|
||||
const roll = overflowing(screen.getByRole('navigation'))
|
||||
rerender(<SectionIndex sections={SECTIONS} active={SECTIONS[1].id} strip />)
|
||||
expect(roll).not.toHaveBeenCalled()
|
||||
|
||||
vi.stubGlobal('matchMedia', (q: string) => ({ matches: q.includes('reduce'), addEventListener() {}, removeEventListener() {} }))
|
||||
rerender(<SectionIndex sections={SECTIONS} active={SECTIONS[SECTIONS.length - 1].id} strip />)
|
||||
expect(roll).toHaveBeenCalledWith(expect.objectContaining({ behavior: 'auto' }))
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,109 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import styles from './SectionIndex.module.css'
|
||||
|
||||
/*
|
||||
The section index of a long screen.
|
||||
|
||||
`Segmented` looks like it and **is not**, and confusing the two is what the design
|
||||
itself warned against: "the same shape in the same place would be two
|
||||
indistinguishable things". The difference is not one of appearance but of what
|
||||
happens to the screen:
|
||||
|
||||
· `Segmented` **chooses a value**: it changes what you see, and what was there
|
||||
stops being there. That is why it is announced with `aria-selected` or
|
||||
`aria-pressed`.
|
||||
· `SectionIndex` **changes nothing, it moves the wheel**. The ten sections of
|
||||
`Settings › General` are all still there before and after pressing; the only
|
||||
thing that moves is the point of the page you are looking at.
|
||||
|
||||
Everything else follows from that without having to be decided:
|
||||
|
||||
· They are **links**, not buttons. An `href="#section"` navigates and scrolls,
|
||||
which is exactly what this does and nothing more. And it comes with focus, the
|
||||
keyboard, "open in another tab" and a copyable link already in place: there is
|
||||
nothing to reimplement and therefore nothing to reimplement badly.
|
||||
· The active one carries **`aria-current="location"`**, not `aria-selected`. It
|
||||
is the difference said out loud: `selected` asserts you have chosen one of
|
||||
several exclusive options; `location` says where you are inside something that
|
||||
is still whole.
|
||||
|
||||
## What it does NOT do, deliberately
|
||||
|
||||
**It does not watch the scroll.** `active` comes in as a prop. Who works it out (an
|
||||
`IntersectionObserver`, the URL hash, the pane that draws it) is screen wiring and
|
||||
belongs to the screen. Bringing it in here, the primitive would start having an
|
||||
opinion about its caller's DOM, and would stop being testable without mounting the
|
||||
whole screen.
|
||||
|
||||
**It does scroll ITSELF, sideways, and only itself.** As a strip wider than the
|
||||
screen, the entry `active` names can be out of sight to the right; when `active`
|
||||
changes, the strip rolls to bring it into view (centred), with `scrollTo` on the
|
||||
strip and never `scrollIntoView`, which would move the page too. Instantly when the
|
||||
reader asks for reduced motion. A column, or a strip that fits, does not move.
|
||||
|
||||
**It hides nothing and owns no content.** It takes no children, draws no panels and
|
||||
marks nothing as `hidden`. If it ever did, it would be `Segmented` under another
|
||||
name.
|
||||
*/
|
||||
export function SectionIndex({
|
||||
sections,
|
||||
active,
|
||||
label = 'On this page',
|
||||
strip = false,
|
||||
}: {
|
||||
/** The sections, in the order they appear on the page. */
|
||||
sections: { id: string; label: string }[]
|
||||
/** The `id` of the section you are in. Without it, none is marked. */
|
||||
active?: string
|
||||
/** The index's name, for whoever cannot see the screen. */
|
||||
label?: string
|
||||
/*
|
||||
Always the strip, whatever the window. Without it the index is a column above
|
||||
`--bp-index` and a strip below, which suits a screen whose content does not care
|
||||
how wide the column is (Permissions). A dense form does care: its control column
|
||||
is what the index's column would come out of, so it decides by its own width and
|
||||
asks for the strip where the column does not fit (`ui/IndexedForm`).
|
||||
*/
|
||||
strip?: boolean
|
||||
}) {
|
||||
const box = useRef<HTMLElement>(null)
|
||||
useEffect(() => {
|
||||
const nav = box.current
|
||||
if (nav == null || active == null || nav.scrollWidth <= nav.clientWidth) return
|
||||
const link = nav.querySelector<HTMLElement>('[aria-current="location"]')
|
||||
if (link == null || typeof nav.scrollTo !== 'function') return
|
||||
const left = link.getBoundingClientRect().left - nav.getBoundingClientRect().left + nav.scrollLeft
|
||||
const right = left + link.offsetWidth
|
||||
if (left >= nav.scrollLeft && right <= nav.scrollLeft + nav.clientWidth) return
|
||||
nav.scrollTo({ left: left - (nav.clientWidth - link.offsetWidth) / 2, behavior: reducedMotion() ? 'auto' : 'smooth' })
|
||||
}, [active])
|
||||
|
||||
return (
|
||||
<nav ref={box} className={strip ? `${styles.index} ${styles.strip}` : styles.index} aria-label={label}>
|
||||
<ul className={styles.list}>
|
||||
{sections.map((s) => (
|
||||
<li key={s.id}>
|
||||
<a
|
||||
href={`#${s.id}`}
|
||||
className={styles.item}
|
||||
/* Only on the active one: an `aria-current="false"` on the other nine
|
||||
is noise that some readers go as far as announcing. */
|
||||
aria-current={s.id === active ? 'location' : undefined}
|
||||
>
|
||||
{s.label}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
|
||||
/** `prefers-reduced-motion`, read when needed; no `matchMedia` (the tests) means no. */
|
||||
function reducedMotion(): boolean {
|
||||
try {
|
||||
return typeof window.matchMedia === 'function' && window.matchMedia('(prefers-reduced-motion: reduce)').matches
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
/*
|
||||
Pick one of a handful of values, with all of them in view. See the styles module
|
||||
for why it exists.
|
||||
|
||||
`asTabs` changes the semantics, not the look: a tab group governs a panel and
|
||||
is announced with `role="tab"` and `aria-selected`; a group of options (the
|
||||
Dashboard's period) are state buttons and are announced with `aria-pressed`. They
|
||||
look alike and are not the same thing, so the caller decides.
|
||||
|
||||
`compact` is the smaller strip that sits on a title's line (the Dashboard's period,
|
||||
beside its title) instead of on a line of its own.
|
||||
*/
|
||||
export function Segmented<T extends string>({
|
||||
options,
|
||||
active,
|
||||
onChoose,
|
||||
label,
|
||||
asTabs = false,
|
||||
compact = false,
|
||||
}: {
|
||||
options: { id: T; label: string }[]
|
||||
active: T
|
||||
onChoose: (id: T) => void
|
||||
/** The group's name, for whoever does not see the screen. */
|
||||
label: string
|
||||
asTabs?: boolean
|
||||
compact?: boolean
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className="inline-flex max-w-full min-w-0 gap-0.5 overflow-x-auto rounded-lg bg-muted p-0.5 [scrollbar-width:none]"
|
||||
role={asTabs ? 'tablist' : 'group'}
|
||||
aria-label={label}
|
||||
>
|
||||
{options.map((o) => (
|
||||
<button
|
||||
key={o.id}
|
||||
type="button"
|
||||
className={cn(
|
||||
'flex-none rounded-md border-0 bg-transparent px-3 text-sm font-medium whitespace-nowrap text-muted-foreground transition-colors outline-none hover:text-foreground focus-visible:ring-3 focus-visible:ring-ring/50',
|
||||
'aria-pressed:bg-card aria-pressed:text-foreground aria-pressed:shadow-xs aria-selected:bg-card aria-selected:text-foreground aria-selected:shadow-xs',
|
||||
compact ? 'h-6 text-xs' : 'h-7',
|
||||
)}
|
||||
role={asTabs ? 'tab' : undefined}
|
||||
aria-selected={asTabs ? o.id === active : undefined}
|
||||
aria-pressed={asTabs ? undefined : o.id === active}
|
||||
onClick={() => onChoose(o.id)}
|
||||
>
|
||||
{o.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
/*
|
||||
The trigger is the same hole as a text field: in a form, choosing and typing have
|
||||
to weigh the same. What changes is that this one opens.
|
||||
*/
|
||||
|
||||
.trigger {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--s-6);
|
||||
width: 100%;
|
||||
min-height: var(--field-height);
|
||||
padding: var(--s-5) var(--s-7);
|
||||
border: 1px solid var(--line-field);
|
||||
border-radius: var(--r-3);
|
||||
background-color: var(--field);
|
||||
color: var(--ink);
|
||||
font: inherit;
|
||||
font-size: var(--t-4);
|
||||
/* `font: inherit` brought the body's 1.55 and the trigger came out 37.4 px:
|
||||
three px taller than the text field beside it (see `--field-line`). */
|
||||
line-height: var(--field-line);
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
box-shadow: var(--sunken);
|
||||
transition: border-color var(--t-fast), box-shadow var(--t-fast);
|
||||
}
|
||||
|
||||
.trigger:hover:not(:disabled) { border-color: var(--line-ctrl); }
|
||||
|
||||
.trigger:focus-visible,
|
||||
.trigger[aria-expanded='true'] {
|
||||
outline: none;
|
||||
border-color: var(--acc-ink);
|
||||
box-shadow: var(--sunken), var(--halo-focus);
|
||||
}
|
||||
|
||||
.trigger:disabled { opacity: 0.45; cursor: default; }
|
||||
|
||||
.value { composes: truncated from './text.module.css'; }
|
||||
.emptyText { color: var(--faint); }
|
||||
|
||||
.chevron { color: var(--mute); flex: none; transition: transform var(--t-fast); }
|
||||
.trigger[aria-expanded='true'] .chevron { transform: rotate(180deg); }
|
||||
|
||||
/*
|
||||
The list. It is genuinely raised (two steps above the field) because it floats
|
||||
over the form and has to read as something in front.
|
||||
*/
|
||||
.list {
|
||||
/* The surface (position, border, shadow) is the Popover's. */
|
||||
max-height: 280px;
|
||||
scrollbar-width: thin;
|
||||
overflow-y: auto;
|
||||
padding: var(--s-3);
|
||||
}
|
||||
|
||||
.option {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--s-5);
|
||||
padding: var(--s-4) var(--s-5);
|
||||
border-radius: var(--r-2);
|
||||
font-size: var(--t-4);
|
||||
color: var(--ink);
|
||||
cursor: pointer;
|
||||
/* Only an option wider than the window wraps, between words; the rest fit on one line. */
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
.option[data-active='true'] { background: var(--hover-strong); }
|
||||
.option[aria-selected='true'] { color: var(--acc-ink); font-weight: 600; }
|
||||
.option[aria-disabled='true'] { color: var(--faint); cursor: default; }
|
||||
.option[aria-disabled='true'][data-active='true'] { background: none; }
|
||||
|
||||
/* Fixed room for the tick: without it, choosing would shift the text. */
|
||||
.brand {
|
||||
display: inline-flex;
|
||||
justify-content: center;
|
||||
width: 14px;
|
||||
flex: none;
|
||||
color: var(--acc-ink);
|
||||
}
|
||||
|
||||
.isEmpty { color: var(--faint); }
|
||||
|
||||
/*
|
||||
`searchable` (the console's own, see `Select.tsx`): the box holds the search field
|
||||
on top and the listbox under it, and only the listbox scrolls, so the field stays
|
||||
in view however far down the options go.
|
||||
*/
|
||||
.searching {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--s-3);
|
||||
overflow: hidden;
|
||||
}
|
||||
.scroll {
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
|
||||
/* The field of `ui/Field`, one step smaller: it filters the list, it is not a value of the form. */
|
||||
.search {
|
||||
flex: none;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
min-height: var(--field-height);
|
||||
padding: var(--s-4) var(--s-6);
|
||||
border: 1px solid var(--line-field);
|
||||
border-radius: var(--r-2);
|
||||
background-color: var(--field);
|
||||
color: var(--ink);
|
||||
font: inherit;
|
||||
font-size: var(--t-4);
|
||||
line-height: var(--field-line);
|
||||
box-shadow: var(--sunken);
|
||||
}
|
||||
.search::placeholder { color: var(--faint); }
|
||||
.search:focus {
|
||||
outline: none;
|
||||
border-color: var(--acc-ink);
|
||||
background-color: var(--field-focus);
|
||||
}
|
||||
|
||||
/* An `<optgroup>`'s label: a heading of the options under it, not one of them. */
|
||||
.groupLabel {
|
||||
composes: smallCaps from './label.module.css';
|
||||
margin-top: var(--s-3);
|
||||
padding: var(--s-4) var(--s-5) var(--s-2);
|
||||
border-top: 1px solid var(--line);
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
/* The search matched nothing: the line where the options would be. */
|
||||
.none {
|
||||
padding: var(--s-4) var(--s-5);
|
||||
font-size: var(--t-4);
|
||||
color: var(--mute);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.trigger,
|
||||
.chevron { transition: none; }
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { fireEvent, render, screen, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { Select } from './Select'
|
||||
|
||||
/*
|
||||
jsdom has no layout, so the list's width and its pull-back from the window's edge
|
||||
are measured in the browser. What it can answer is which scrolls close the list:
|
||||
with more options than the height cap, the list scrolls itself (the wheel, and the
|
||||
arrow keys through `scrollIntoView`), and that scroll used to close it.
|
||||
*/
|
||||
function Sample() {
|
||||
return (
|
||||
<Select aria-label="Pick" value="">
|
||||
<option value="" />
|
||||
<option value="one">One</option>
|
||||
<option value="two">Two</option>
|
||||
</Select>
|
||||
)
|
||||
}
|
||||
|
||||
describe('Select', () => {
|
||||
it('scrolling the list itself keeps it open', async () => {
|
||||
render(<Sample />)
|
||||
await userEvent.click(screen.getByRole('combobox', { name: 'Pick' }))
|
||||
const list = screen.getByRole('listbox')
|
||||
|
||||
fireEvent.scroll(list)
|
||||
expect(screen.getByRole('listbox')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('scrolling the page closes it', async () => {
|
||||
render(<Sample />)
|
||||
await userEvent.click(screen.getByRole('combobox', { name: 'Pick' }))
|
||||
|
||||
fireEvent.scroll(document)
|
||||
expect(screen.queryByRole('listbox')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('resizing the window closes it, and does not blow up', async () => {
|
||||
render(<Sample />)
|
||||
await userEvent.click(screen.getByRole('combobox', { name: 'Pick' }))
|
||||
|
||||
fireEvent(window, new Event('resize'))
|
||||
expect(screen.queryByRole('listbox')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
/*
|
||||
`searchable`, the console's own. Off, the dropdown is exactly what it was: no field,
|
||||
the focus stays on the trigger, and typing jumps to an option. On, a field on top
|
||||
filters the options and takes the keys a text field keeps.
|
||||
*/
|
||||
function Searchable({ onChange = () => {} }: { onChange?: (v: string) => void }) {
|
||||
return (
|
||||
<Select
|
||||
aria-label="Pick"
|
||||
value=""
|
||||
searchable
|
||||
searchLabel="Search lists"
|
||||
noMatchText="No lists match"
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
>
|
||||
<option value="" />
|
||||
<option value="none">None</option>
|
||||
<option value="sb" data-search="raw.githubusercontent.com">Steven Black</option>
|
||||
<option value="oisd" data-search="big.oisd.nl">OISD Big</option>
|
||||
<optgroup label="More lists">
|
||||
<option value="more:0" data-search="lists.example.org">Example Ads</option>
|
||||
<option value="more:1" data-search="trackers.example.net">Example Trackers</option>
|
||||
</optgroup>
|
||||
</Select>
|
||||
)
|
||||
}
|
||||
|
||||
const shown = () => within(screen.getByRole('listbox')).queryAllByRole('option').map((o) => o.textContent)
|
||||
|
||||
describe('Select without searchable', () => {
|
||||
it('opens with no search field and keeps the focus on the trigger', async () => {
|
||||
render(<Sample />)
|
||||
const trigger = screen.getByRole('combobox', { name: 'Pick' })
|
||||
await userEvent.click(trigger)
|
||||
expect(screen.getByRole('listbox')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('textbox')).toBeNull()
|
||||
expect(screen.getAllByRole('combobox')).toHaveLength(1)
|
||||
expect(trigger).toHaveFocus()
|
||||
expect(trigger).toHaveAttribute('aria-activedescendant')
|
||||
})
|
||||
|
||||
it('typing still jumps to the option starting with it, and Enter chooses it', async () => {
|
||||
const changed: string[] = []
|
||||
render(
|
||||
<Select aria-label="Pick" value="" onChange={(e) => changed.push(e.target.value)}>
|
||||
<option value="" />
|
||||
<option value="one">One</option>
|
||||
<option value="two">Two</option>
|
||||
</Select>,
|
||||
)
|
||||
await userEvent.click(screen.getByRole('combobox', { name: 'Pick' }))
|
||||
await userEvent.keyboard('t{Enter}')
|
||||
expect(changed).toEqual(['two'])
|
||||
})
|
||||
|
||||
it('arrows, Home and End move over every option', async () => {
|
||||
const changed: string[] = []
|
||||
render(
|
||||
<Select aria-label="Pick" value="" onChange={(e) => changed.push(e.target.value)}>
|
||||
<option value="" />
|
||||
<option value="one">One</option>
|
||||
<option value="two">Two</option>
|
||||
</Select>,
|
||||
)
|
||||
const trigger = screen.getByRole('combobox', { name: 'Pick' })
|
||||
await userEvent.click(trigger)
|
||||
await userEvent.keyboard('{End}{ArrowUp}{Enter}')
|
||||
await userEvent.click(trigger)
|
||||
await userEvent.keyboard('{Home}{ArrowDown}{ArrowDown}{ArrowDown} ')
|
||||
expect(changed).toEqual(['one', 'two'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('Select with searchable', () => {
|
||||
it('opens with the focus in the search field', async () => {
|
||||
render(<Searchable />)
|
||||
await userEvent.click(screen.getByRole('combobox', { name: 'Pick' }))
|
||||
const field = screen.getByRole('combobox', { name: 'Search lists' })
|
||||
expect(field).toHaveFocus()
|
||||
expect(field).toHaveAttribute('aria-controls', screen.getByRole('listbox').id)
|
||||
expect(field).toHaveAttribute('aria-autocomplete', 'list')
|
||||
})
|
||||
|
||||
it('filters by name, whatever the case', async () => {
|
||||
render(<Searchable />)
|
||||
await userEvent.click(screen.getByRole('combobox', { name: 'Pick' }))
|
||||
await userEvent.keyboard('STEVEN')
|
||||
expect(shown()).toEqual(['Steven Black'])
|
||||
})
|
||||
|
||||
it('filters by the host in data-search too', async () => {
|
||||
render(<Searchable />)
|
||||
await userEvent.click(screen.getByRole('combobox', { name: 'Pick' }))
|
||||
await userEvent.keyboard('oisd.nl')
|
||||
expect(shown()).toEqual(['OISD Big'])
|
||||
})
|
||||
|
||||
it('arrows move over the filtered options and Enter chooses', async () => {
|
||||
const changed: string[] = []
|
||||
render(<Searchable onChange={(v) => changed.push(v)} />)
|
||||
const trigger = screen.getByRole('combobox', { name: 'Pick' })
|
||||
await userEvent.click(trigger)
|
||||
await userEvent.keyboard('example')
|
||||
expect(shown()).toEqual(['Example Ads', 'Example Trackers'])
|
||||
const field = screen.getByRole('combobox', { name: 'Search lists' })
|
||||
expect(field.getAttribute('aria-activedescendant')).toBe(screen.getByRole('option', { name: 'Example Ads' }).id)
|
||||
await userEvent.keyboard('{ArrowDown}{ArrowDown}{ArrowUp}{ArrowDown}{Enter}')
|
||||
expect(changed).toEqual(['more:1'])
|
||||
expect(screen.queryByRole('listbox')).toBeNull()
|
||||
expect(trigger).toHaveFocus()
|
||||
})
|
||||
|
||||
it('Space, Home and End stay in the field', async () => {
|
||||
const changed: string[] = []
|
||||
render(<Searchable onChange={(v) => changed.push(v)} />)
|
||||
await userEvent.click(screen.getByRole('combobox', { name: 'Pick' }))
|
||||
await userEvent.keyboard('steven{Home} {End}')
|
||||
expect(changed).toEqual([])
|
||||
expect(screen.getByRole('combobox', { name: 'Search lists' })).toHaveValue(' steven')
|
||||
})
|
||||
|
||||
it('Escape closes, returns the focus and chooses nothing', async () => {
|
||||
const changed: string[] = []
|
||||
render(<Searchable onChange={(v) => changed.push(v)} />)
|
||||
const trigger = screen.getByRole('combobox', { name: 'Pick' })
|
||||
await userEvent.click(trigger)
|
||||
await userEvent.keyboard('oisd{Escape}')
|
||||
expect(screen.queryByRole('listbox')).toBeNull()
|
||||
expect(trigger).toHaveFocus()
|
||||
expect(changed).toEqual([])
|
||||
})
|
||||
|
||||
it('a search that matches nothing says so, and Enter does nothing', async () => {
|
||||
const changed: string[] = []
|
||||
render(<Searchable onChange={(v) => changed.push(v)} />)
|
||||
await userEvent.click(screen.getByRole('combobox', { name: 'Pick' }))
|
||||
await userEvent.keyboard('zzz')
|
||||
expect(shown()).toEqual([])
|
||||
expect(screen.getByRole('status')).toHaveTextContent('No lists match')
|
||||
expect(screen.getByRole('combobox', { name: 'Search lists' })).not.toHaveAttribute('aria-activedescendant')
|
||||
await userEvent.keyboard('{Enter}')
|
||||
expect(changed).toEqual([])
|
||||
expect(screen.getByRole('listbox')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('opens again with the search cleared', async () => {
|
||||
render(<Searchable />)
|
||||
const trigger = screen.getByRole('combobox', { name: 'Pick' })
|
||||
await userEvent.click(trigger)
|
||||
await userEvent.keyboard('zzz{Escape}')
|
||||
await userEvent.click(trigger)
|
||||
expect(screen.getByRole('combobox', { name: 'Search lists' })).toHaveValue('')
|
||||
expect(shown()).toHaveLength(6)
|
||||
})
|
||||
|
||||
it('a click chooses a filtered option', async () => {
|
||||
const changed: string[] = []
|
||||
render(<Searchable onChange={(v) => changed.push(v)} />)
|
||||
await userEvent.click(screen.getByRole('combobox', { name: 'Pick' }))
|
||||
await userEvent.keyboard('ads')
|
||||
await userEvent.click(screen.getByRole('option', { name: 'Example Ads' }))
|
||||
expect(changed).toEqual(['more:0'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('Select with an optgroup', () => {
|
||||
it('draws the group named by its label, and the label is not an option', async () => {
|
||||
render(<Searchable />)
|
||||
await userEvent.click(screen.getByRole('combobox', { name: 'Pick' }))
|
||||
const group = screen.getByRole('group', { name: 'More lists' })
|
||||
expect(within(group).getAllByRole('option').map((o) => o.textContent)).toEqual(['Example Ads', 'Example Trackers'])
|
||||
expect(screen.queryByRole('option', { name: 'More lists' })).toBeNull()
|
||||
})
|
||||
|
||||
it('the arrows step from the last option before the group into it, over the label', async () => {
|
||||
const changed: string[] = []
|
||||
render(<Searchable onChange={(v) => changed.push(v)} />)
|
||||
await userEvent.click(screen.getByRole('combobox', { name: 'Pick' }))
|
||||
await userEvent.keyboard('{ArrowDown}{ArrowDown}{ArrowDown}{ArrowDown}{Enter}')
|
||||
expect(changed).toEqual(['more:0'])
|
||||
})
|
||||
|
||||
it('a group with no match left is not drawn', async () => {
|
||||
render(<Searchable />)
|
||||
await userEvent.click(screen.getByRole('combobox', { name: 'Pick' }))
|
||||
await userEvent.keyboard('steven')
|
||||
expect(screen.queryByRole('group')).toBeNull()
|
||||
expect(screen.queryByText('More lists')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
/*
|
||||
A native `select` fires `change` only when the value changes. Picking the option
|
||||
that is already chosen does nothing there, and the console's lists that act on
|
||||
change (Group Details' "None" empties Members) relied on that.
|
||||
*/
|
||||
describe('Select: choosing the current option', () => {
|
||||
it('does not fire onChange, by click or by keyboard', async () => {
|
||||
const changed: string[] = []
|
||||
render(
|
||||
<Select aria-label="Pick" value="one" onChange={(e) => changed.push(e.target.value)}>
|
||||
<option value="one">One</option>
|
||||
<option value="two">Two</option>
|
||||
</Select>,
|
||||
)
|
||||
await userEvent.click(screen.getByRole('combobox', { name: 'Pick' }))
|
||||
await userEvent.click(screen.getByRole('option', { name: 'One' }))
|
||||
expect(screen.queryByRole('listbox')).toBeNull()
|
||||
await userEvent.click(screen.getByRole('combobox', { name: 'Pick' }))
|
||||
await userEvent.keyboard('{Enter}')
|
||||
expect(changed).toEqual([])
|
||||
await userEvent.click(screen.getByRole('combobox', { name: 'Pick' }))
|
||||
await userEvent.click(screen.getByRole('option', { name: 'Two' }))
|
||||
expect(changed).toEqual(['two'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,467 @@
|
||||
import {
|
||||
Children,
|
||||
isValidElement,
|
||||
useEffect,
|
||||
useId,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
type Ref,
|
||||
} from 'react'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
||||
import { Icon } from './Icon'
|
||||
import styles from './Select.module.css'
|
||||
|
||||
/*
|
||||
The dropdown, built here.
|
||||
|
||||
It used to be the operating system's `<select>` with a chevron painted on top:
|
||||
the closed box almost passed, but on opening it the system list appeared (the
|
||||
OS's font, size, colours and corners) and the console changed appearance
|
||||
depending on the machine. And that is why it "looked very much the same": half
|
||||
the control was not ours.
|
||||
|
||||
It is rebuilt as a listbox following the ARIA specification's rules:
|
||||
|
||||
· the trigger is a `combobox`, with `aria-expanded` and `aria-activedescendant`
|
||||
· the list is a `listbox` and each line an `option` with `aria-selected`
|
||||
· full keyboard: ↑ ↓ Home End, Enter and Space open and choose, Esc closes and
|
||||
returns focus, and typing jumps to the option starting with it
|
||||
· focus does not move into the list, so the screen reader keeps announcing the
|
||||
field and its label
|
||||
|
||||
The list is `position: fixed` computed from the trigger, not absolute: otherwise,
|
||||
inside a modal (which has `overflow: auto`) it would be clipped. For the same
|
||||
reason it closes on scroll, which is what the native `select` does.
|
||||
|
||||
`searchable` is the console's own, and opt-in: only Blocking › Lists turns it on,
|
||||
for a Quick Add catalogue too long to scroll through. It puts a search field at
|
||||
the top of the open list. The field takes the focus and is the combobox while the
|
||||
list is open (`aria-autocomplete="list"`); typing filters the options by their
|
||||
label, or by the `data-search` text an `<option>` may carry, case-insensitively;
|
||||
↑ ↓ move through what is left, Enter chooses, Esc closes and returns focus to
|
||||
the trigger, and Home, End and Space stay with the text, as in any text field.
|
||||
No match leaves a `noMatchText` line, announced as a status. The list keeps the
|
||||
width it opened with (and, opened upwards, its height), so filtering does not
|
||||
move the field. Without `searchable` nothing here changes: same DOM, same keys,
|
||||
same look.
|
||||
|
||||
`<optgroup>` children become a `group` labelled by their `label`, a line that
|
||||
cannot be chosen, as in the native element. Nothing used them before the Quick
|
||||
Add of Blocking › Lists, so no other dropdown changes.
|
||||
*/
|
||||
|
||||
export interface Option {
|
||||
value: string
|
||||
label: string
|
||||
disabled?: boolean
|
||||
/** The `<optgroup>` it sits in, by its label. */
|
||||
group?: string
|
||||
/** What a search matches besides the label: the option's `data-search`. */
|
||||
search?: string
|
||||
}
|
||||
|
||||
/*
|
||||
The options are read from the `<option>` children, as in the element it replaces.
|
||||
It could have taken an array and forced a rewrite of the twenty-five places that
|
||||
use it, but then the change would stop being design-only: each of those places is
|
||||
a list with its own logic (TSIG keys, catalogs, record types, DNSSEC algorithms),
|
||||
and rewriting it is an opportunity to break it.
|
||||
*/
|
||||
function optionsFromChildren(children: ReactNode, group?: string): Option[] {
|
||||
const outside: Option[] = []
|
||||
for (const child of Children.toArray(children)) {
|
||||
if (!isValidElement(child)) continue
|
||||
if (child.type === 'optgroup') {
|
||||
const g = child.props as { label?: string; children?: ReactNode }
|
||||
outside.push(...optionsFromChildren(g.children, g.label ?? ''))
|
||||
continue
|
||||
}
|
||||
if (child.type !== 'option') continue
|
||||
const p = child.props as {
|
||||
value?: string | number; children?: ReactNode; disabled?: boolean; 'data-search'?: string
|
||||
}
|
||||
const text = typeof p.children === 'string' || typeof p.children === 'number' ? String(p.children) : ''
|
||||
const o: Option = {
|
||||
value: p.value != null ? String(p.value) : text,
|
||||
label: text,
|
||||
disabled: p.disabled,
|
||||
}
|
||||
if (group != null) o.group = group
|
||||
if (p['data-search'] != null) o.search = p['data-search']
|
||||
outside.push(o)
|
||||
}
|
||||
return outside
|
||||
}
|
||||
|
||||
/** The indices of the options a search shows, in order: all of them for an empty one. */
|
||||
function visibleFor(options: Option[], query: string): number[] {
|
||||
const needle = query.trim().toLowerCase()
|
||||
if (needle === '') return options.map((_, i) => i)
|
||||
const out: number[] = []
|
||||
options.forEach((o, i) => {
|
||||
if (o.label.toLowerCase().includes(needle) || (o.search ?? '').toLowerCase().includes(needle)) out.push(i)
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
export function Select({
|
||||
id,
|
||||
value,
|
||||
children,
|
||||
onChange,
|
||||
disabled = false,
|
||||
placeholder,
|
||||
className,
|
||||
ref,
|
||||
'aria-label': ariaLabel,
|
||||
searchable = false,
|
||||
searchLabel = 'Search',
|
||||
noMatchText = 'No matches',
|
||||
}: {
|
||||
id?: string
|
||||
value: string | number
|
||||
children?: ReactNode
|
||||
/** The same signature as the native element, so existing callers are untouched. */
|
||||
onChange?: (e: { target: { value: string } }) => void
|
||||
disabled?: boolean
|
||||
/** What to show when the value is not among the options. */
|
||||
placeholder?: string
|
||||
className?: string
|
||||
ref?: Ref<HTMLButtonElement>
|
||||
'aria-label'?: string
|
||||
/** A search field on top of the open list (see the header). Off by default. */
|
||||
searchable?: boolean
|
||||
/** The search field's accessible name and placeholder. */
|
||||
searchLabel?: string
|
||||
/** The line shown when the search matches nothing. */
|
||||
noMatchText?: string
|
||||
}) {
|
||||
const options = optionsFromChildren(children)
|
||||
const [open, setOpen] = useState(false)
|
||||
const [active, setActive] = useState(0)
|
||||
const [query, setQuery] = useState('')
|
||||
const trigger = useRef<HTMLButtonElement>(null)
|
||||
/** The floating box: the listbox itself, or the box holding search and listbox. */
|
||||
const list = useRef<HTMLDivElement>(null)
|
||||
const search = useRef<HTMLInputElement>(null)
|
||||
const keys2 = useRef({ text: '', until: 0 })
|
||||
const listId = useId()
|
||||
|
||||
const visible = searchable ? visibleFor(options, query) : options.map((_, i) => i)
|
||||
const selectedIndex = options.findIndex((o) => o.value === String(value))
|
||||
const chosen = selectedIndex >= 0 ? options[selectedIndex] : undefined
|
||||
const activeShown = open && visible.includes(active)
|
||||
|
||||
function openList() {
|
||||
if (disabled) return
|
||||
setQuery('')
|
||||
const all = options.map((_, i) => i)
|
||||
setActive(selectedIndex >= 0 ? selectedIndex : firstUsable(options, all, 0, 1))
|
||||
setOpen(true)
|
||||
}
|
||||
|
||||
/* The focus goes back to the trigger once the list has gone (see the effect): the
|
||||
element that held it is removed, and the browser would leave it on the body. */
|
||||
const giveBack = useRef(false)
|
||||
function close(returnFocus = true) {
|
||||
giveBack.current = returnFocus
|
||||
setOpen(false)
|
||||
}
|
||||
useEffect(() => {
|
||||
if (!open && giveBack.current) {
|
||||
giveBack.current = false
|
||||
trigger.current?.focus()
|
||||
}
|
||||
}, [open])
|
||||
|
||||
function choose(i: number) {
|
||||
const o = options[i]
|
||||
if (o == null || o.disabled || !visible.includes(i)) return
|
||||
/* As the native element: `change` only when the value changes. Picking the
|
||||
option already chosen just closes the list. */
|
||||
if (o.value !== String(value)) onChange?.({ target: { value: o.value } })
|
||||
close()
|
||||
}
|
||||
|
||||
/*
|
||||
Where the list goes is ReUI's Popover's job: it takes the list out of any clipping
|
||||
ancestor, opens upwards where it does not fit below, is at least as wide as its
|
||||
trigger (`--anchor-width`) and closes on an outside press. It still closes on
|
||||
scroll, as the native element does; scrolling the list itself does not.
|
||||
*/
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const onScroll = (e: Event) => {
|
||||
if (e.target instanceof Node && list.current?.contains(e.target)) return
|
||||
setOpen(false)
|
||||
}
|
||||
// `true` so it also hears a container's scroll, not only the page's:
|
||||
// inside a modal the thing that scrolls is the modal.
|
||||
window.addEventListener('scroll', onScroll, true)
|
||||
window.addEventListener('resize', onScroll)
|
||||
return () => {
|
||||
window.removeEventListener('scroll', onScroll, true)
|
||||
window.removeEventListener('resize', onScroll)
|
||||
}
|
||||
}, [open])
|
||||
|
||||
// The selected option is kept in view when moving with the keyboard.
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const checked = list.current?.querySelector('[data-active="true"]')
|
||||
// `scrollIntoView` does not exist in jsdom, and nothing breaks without it.
|
||||
checked?.scrollIntoView?.({ block: 'nearest' })
|
||||
}, [open, active])
|
||||
|
||||
function onKeyDown(e: React.KeyboardEvent) {
|
||||
if (disabled) return
|
||||
|
||||
if (!open) {
|
||||
if (e.key === 'ArrowDown' || e.key === 'ArrowUp' || e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault()
|
||||
openList()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
switch (e.key) {
|
||||
case 'Escape':
|
||||
e.preventDefault()
|
||||
close()
|
||||
return
|
||||
case 'Tab':
|
||||
setOpen(false)
|
||||
return
|
||||
case 'Enter':
|
||||
case ' ':
|
||||
e.preventDefault()
|
||||
choose(active)
|
||||
return
|
||||
case 'ArrowDown':
|
||||
e.preventDefault()
|
||||
setActive((i) => step(options, visible, i, 1))
|
||||
return
|
||||
case 'ArrowUp':
|
||||
e.preventDefault()
|
||||
setActive((i) => step(options, visible, i, -1))
|
||||
return
|
||||
case 'Home':
|
||||
e.preventDefault()
|
||||
setActive(firstUsable(options, visible, 0, 1))
|
||||
return
|
||||
case 'End':
|
||||
e.preventDefault()
|
||||
setActive(firstUsable(options, visible, visible.length - 1, -1))
|
||||
return
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
// Typing jumps to the option starting with what was typed, like the native one.
|
||||
if (e.key.length === 1 && !e.metaKey && !e.ctrlKey && !e.altKey) {
|
||||
const now = Date.now()
|
||||
keys2.current.text = now > keys2.current.until ? e.key : keys2.current.text + e.key
|
||||
keys2.current.until = now + 600
|
||||
const wanted = keys2.current.text.toLowerCase()
|
||||
const i = options.findIndex((o) => !o.disabled && o.label.toLowerCase().startsWith(wanted))
|
||||
if (i >= 0) setActive(i)
|
||||
}
|
||||
}
|
||||
|
||||
/* The search field's keys: the list's, minus the ones a text field keeps (Home,
|
||||
End, Space and the letters, which are the search). */
|
||||
function onSearchKeyDown(e: React.KeyboardEvent) {
|
||||
switch (e.key) {
|
||||
case 'Escape':
|
||||
e.preventDefault()
|
||||
close()
|
||||
return
|
||||
case 'Tab':
|
||||
setOpen(false)
|
||||
return
|
||||
case 'Enter':
|
||||
e.preventDefault()
|
||||
if (activeShown) choose(active)
|
||||
return
|
||||
case 'ArrowDown':
|
||||
e.preventDefault()
|
||||
setActive((i) => step(options, visible, i, 1))
|
||||
return
|
||||
case 'ArrowUp':
|
||||
e.preventDefault()
|
||||
setActive((i) => step(options, visible, i, -1))
|
||||
return
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
function onSearch(text: string) {
|
||||
setQuery(text)
|
||||
const shown = visibleFor(options, text)
|
||||
const first = firstUsable(options, shown, 0, 1, -1)
|
||||
setActive(first)
|
||||
}
|
||||
|
||||
/* Consecutive options of one `<optgroup>` are drawn inside one group. */
|
||||
const runs: { group?: string; items: number[] }[] = []
|
||||
for (const i of visible) {
|
||||
const g = options[i].group
|
||||
const last = runs[runs.length - 1]
|
||||
if (last != null && last.group === g) last.items.push(i)
|
||||
else runs.push({ group: g, items: [i] })
|
||||
}
|
||||
|
||||
const option = (i: number) => {
|
||||
const o = options[i]
|
||||
return (
|
||||
<div
|
||||
key={o.value}
|
||||
id={`${listId}-${i}`}
|
||||
role="option"
|
||||
aria-selected={o.value === String(value)}
|
||||
aria-disabled={o.disabled}
|
||||
data-active={i === active}
|
||||
className={styles.option}
|
||||
onMouseEnter={() => !o.disabled && setActive(i)}
|
||||
onClick={() => choose(i)}
|
||||
>
|
||||
<span className={styles.brand}>
|
||||
{o.value === String(value) && <Icon name="check" size={13} />}
|
||||
</span>
|
||||
{o.label === '' ? <span className={styles.isEmpty}>—</span> : o.label}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const lines = runs.flatMap((run, n) =>
|
||||
run.group == null
|
||||
? run.items.map(option)
|
||||
: [
|
||||
/* The label sits beside the group and names it, not inside it: a group
|
||||
holds options only. */
|
||||
<div key={`group-${n}`} role="presentation">
|
||||
<div id={`${listId}-g${n}`} role="presentation" className={styles.groupLabel}>
|
||||
{run.group}
|
||||
</div>
|
||||
<div role="group" aria-labelledby={`${listId}-g${n}`}>
|
||||
{run.items.map(option)}
|
||||
</div>
|
||||
</div>,
|
||||
],
|
||||
)
|
||||
|
||||
const trigger_ = (
|
||||
<button
|
||||
type="button"
|
||||
id={id}
|
||||
ref={merge(trigger, ref)}
|
||||
role="combobox"
|
||||
aria-haspopup="listbox"
|
||||
aria-expanded={open}
|
||||
aria-controls={open ? listId : undefined}
|
||||
aria-activedescendant={open && !searchable ? `${listId}-${active}` : undefined}
|
||||
aria-label={ariaLabel}
|
||||
disabled={disabled}
|
||||
className={[styles.trigger, className].filter(Boolean).join(' ')}
|
||||
onKeyDown={onKeyDown}
|
||||
>
|
||||
{/*
|
||||
An option with no label (a filter's "any") is drawn with a dash, just as
|
||||
it is inside the list. Completely empty, the control reads as a broken box
|
||||
rather than as "nothing is selected".
|
||||
*/}
|
||||
<span className={chosen?.label ? styles.value : styles.emptyText}>
|
||||
{chosen?.label || placeholder || '—'}
|
||||
</span>
|
||||
<Icon name="chevronDown" size={14} className={styles.chevron} />
|
||||
</button>
|
||||
)
|
||||
|
||||
return (
|
||||
<Popover
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (next) openList()
|
||||
else setOpen(false)
|
||||
}}
|
||||
>
|
||||
<PopoverTrigger render={trigger_} />
|
||||
<PopoverContent
|
||||
side="bottom"
|
||||
align="start"
|
||||
initialFocus={false}
|
||||
finalFocus={false}
|
||||
className="w-auto max-w-[calc(100vw-1rem)] min-w-(--anchor-width) gap-0 overflow-hidden p-0"
|
||||
>
|
||||
{searchable ? (
|
||||
<div ref={list} className={`${styles.list} ${styles.searching}`}>
|
||||
<input
|
||||
ref={(el) => {
|
||||
search.current = el
|
||||
el?.focus({ preventScroll: true })
|
||||
}}
|
||||
type="text"
|
||||
role="combobox"
|
||||
aria-expanded="true"
|
||||
aria-controls={listId}
|
||||
aria-autocomplete="list"
|
||||
aria-activedescendant={activeShown ? `${listId}-${active}` : undefined}
|
||||
aria-label={searchLabel}
|
||||
placeholder={searchLabel}
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
className={styles.search}
|
||||
value={query}
|
||||
onChange={(e) => onSearch(e.target.value)}
|
||||
onKeyDown={onSearchKeyDown}
|
||||
/>
|
||||
<div id={listId} role="listbox" aria-label={ariaLabel} className={styles.scroll}>
|
||||
{lines}
|
||||
</div>
|
||||
<div role="status" className={visible.length === 0 ? styles.none : undefined}>
|
||||
{visible.length === 0 ? noMatchText : ''}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div ref={list} id={listId} role="listbox" className={styles.list}>
|
||||
{lines}
|
||||
</div>
|
||||
)}
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
|
||||
/*
|
||||
Moving is over the options shown (`shown`, indices into `options`): all of them
|
||||
unless a search is filtering. `from` and the result are positions in `shown`
|
||||
turned back into indices.
|
||||
*/
|
||||
|
||||
/** The first usable option from position `from` in that direction; if there is
|
||||
* none, `fallback` (by default the option at `from`). */
|
||||
function firstUsable(options: Option[], shown: number[], from: number, dir: number, fallback?: number): number {
|
||||
for (let p = from; p >= 0 && p < shown.length; p += dir) {
|
||||
if (!options[shown[p]].disabled) return shown[p]
|
||||
}
|
||||
return fallback ?? shown[from] ?? -1
|
||||
}
|
||||
|
||||
/** The next usable option after `current` in that direction; if there is none, it
|
||||
* stays put. From an option not shown, it starts at the first or the last. */
|
||||
function step(options: Option[], shown: number[], current: number, dir: number): number {
|
||||
const p = shown.indexOf(current)
|
||||
const from = p < 0 ? (dir > 0 ? 0 : shown.length - 1) : p + dir
|
||||
return firstUsable(options, shown, from, dir, p < 0 ? -1 : current)
|
||||
}
|
||||
|
||||
/** Merges the internal ref with whatever the caller may pass. */
|
||||
function merge(own: React.RefObject<HTMLButtonElement | null>, outside?: Ref<HTMLButtonElement>) {
|
||||
return (node: HTMLButtonElement | null) => {
|
||||
own.current = node
|
||||
if (typeof outside === 'function') outside(node)
|
||||
else if (outside != null) (outside as { current: HTMLButtonElement | null }).current = node
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
The cells of a sessions table. There are three tables (all sessions, one user's
|
||||
and my own) and all three paint the same thing: which session it is, when it was
|
||||
last seen, from where and with what.
|
||||
|
||||
Two of them shared a component; the third, "My Profile", was written by hand, and
|
||||
it showed:
|
||||
|
||||
· The column was called "Type" and the address one "Address", when upstream says
|
||||
"Session" and "Remote Address" in all three (`index.html:3603-3606`).
|
||||
· The cell showed the type as raw text, without the coloured tag upstream does
|
||||
paint (`auth.js:703-719`), and with a "current" pill of its own that exists in
|
||||
neither of the other two.
|
||||
*/
|
||||
|
||||
/* The age, under the date: "(2 hours ago)". */
|
||||
.age {
|
||||
margin-top: var(--s-1);
|
||||
font-size: var(--t-2);
|
||||
color: var(--faint);
|
||||
}
|
||||
|
||||
/*
|
||||
The user agent: two lines at rest, all of it under the pointer or while the row
|
||||
holds the focus.
|
||||
|
||||
It used to break anywhere (`word-break: break-all`), which let the table squeeze
|
||||
its column to whatever was left: 110 px at 390, twelve lines of agent, and rows of
|
||||
220 px in Administration › Sessions. Now the column keeps a minimum and the text is
|
||||
cut by LINE (`-webkit-line-clamp`, as the store descriptions in Apps), so a row is
|
||||
as tall as its session cell. Nothing is hidden from anyone: the whole string stays
|
||||
in the page for a screen reader, the copy and the find, it opens out when the
|
||||
pointer is over it, and it opens out when the keyboard reaches any control in its
|
||||
row (the username, View User Details, the menu). If the clamp is not honoured,
|
||||
the fallback is a taller row, which is what there was before.
|
||||
*/
|
||||
.agent {
|
||||
composes: annotationQuiet from './text.module.css';
|
||||
display: -webkit-box;
|
||||
-webkit-box-orient: vertical;
|
||||
-webkit-line-clamp: 2;
|
||||
line-clamp: 2;
|
||||
overflow: hidden;
|
||||
min-width: 36ch;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
.agent:hover,
|
||||
:where(tr:focus-within) .agent {
|
||||
-webkit-line-clamp: unset;
|
||||
line-clamp: none;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.label { margin-top: var(--s-2); }
|
||||
@@ -0,0 +1,60 @@
|
||||
import { Tag } from './Tag'
|
||||
import styles from './SessionCells.module.css'
|
||||
import text from './text.module.css'
|
||||
|
||||
/** What the three sessions tables need from a session. */
|
||||
export interface Session {
|
||||
partialToken: string
|
||||
tokenName: string | null
|
||||
isCurrentSession: boolean
|
||||
type: string
|
||||
lastSeen: string
|
||||
lastSeenRemoteAddress: string
|
||||
lastSeenUserAgent: string
|
||||
}
|
||||
|
||||
/*
|
||||
The "Session" cell: the token name if it has one, the partial token, "(current)"
|
||||
if it is this one, and the type as a tag. It is upstream's order
|
||||
(`auth.js:694-719`) and all three tables paint it the same.
|
||||
|
||||
A type that is not recognised comes out as "Unknown" in amber, which is what
|
||||
upstream does with its `default`: staying silent would be worse than saying it is
|
||||
not known.
|
||||
*/
|
||||
export function SessionCell({ session }: { session: Pick<Session, 'partialToken' | 'tokenName' | 'isCurrentSession' | 'type'> }) {
|
||||
const label =
|
||||
session.type === 'Standard' ? (
|
||||
<Tag>Standard</Tag>
|
||||
) : session.type === 'ApiToken' ? (
|
||||
<Tag tone="info">API Token</Tag>
|
||||
) : session.type === 'ClusterApiToken' ? (
|
||||
<Tag tone="info">Cluster API Token</Tag>
|
||||
) : (
|
||||
<Tag tone="warn">Unknown</Tag>
|
||||
)
|
||||
|
||||
return (
|
||||
<>
|
||||
{session.tokenName != null && <div>{session.tokenName}</div>}
|
||||
<div className={text.mono}>{`[${session.partialToken}]`}</div>
|
||||
{session.isCurrentSession && <div>(current)</div>}
|
||||
<div className={styles.label}>{label}</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/** The "Last Seen" cell: the date, and beneath it how long ago. */
|
||||
export function LastSeenCell({ date, ago }: { date: string; ago: string }) {
|
||||
return (
|
||||
<>
|
||||
<div className={text.mono}>{date}</div>
|
||||
<div className={styles.age}>{`(${ago})`}</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/** The "User Agent" cell. */
|
||||
export function AgentCell({ children }: { children: string }) {
|
||||
return <span className={styles.agent}>{children}</span>
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
The sub-navigation bar. An underline and not a filled pill, and the difference is
|
||||
the same one `SectionIndex` makes: `Segmented` fills with amber because there you
|
||||
have chosen a value and the others have stopped applying. Here the others are
|
||||
still there (they are other screens of the same section), so the active one is
|
||||
marked with an edge and the rest read as ordinary links.
|
||||
*/
|
||||
.bar {
|
||||
display: flex;
|
||||
gap: var(--s-8);
|
||||
align-items: stretch;
|
||||
/* The rule under the tabs is an inset shadow and not a border, so the active
|
||||
tab's edge can sit on it without leaving the box. With a border, each tab had
|
||||
to reach 1 px past the content box (`margin-bottom: -1px`) to cover it, and
|
||||
inside `overflow-x: auto` (which makes `overflow-y` auto too) that pixel was
|
||||
overflow: Chromium on Linux drew a 15 px vertical scrollbar beside the tabs of
|
||||
every section. The children paint over their parent's shadow, so the active
|
||||
edge still covers the rule. */
|
||||
/* ReUI's tabs: the line sits under the active tab only, none under the whole row. */
|
||||
margin-bottom: var(--gap-block);
|
||||
/* The strip scrolls rather than wrapping: nine panes on two lines turn a bar
|
||||
into a block, and the second line reads as a different thing. */
|
||||
overflow-x: auto;
|
||||
overscroll-behavior-x: contain;
|
||||
}
|
||||
|
||||
.tab {
|
||||
flex: 0 0 auto;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
height: 40px;
|
||||
padding: 0 var(--s-5);
|
||||
color: var(--mute);
|
||||
text-decoration: none;
|
||||
font-size: var(--t-4);
|
||||
/* The edge is ALWAYS there, transparent when it does not apply: painting it
|
||||
only on the active one moves every tab 2 px each time it changes. */
|
||||
border-bottom: 2px solid transparent;
|
||||
white-space: nowrap;
|
||||
/* The containing block of a mark's hidden words (`text.sr`, absolutely placed).
|
||||
Without it they were placed against the page and not inside the strip, and a
|
||||
marked tab beyond the strip's scroll widened the whole page: measured at 390 in
|
||||
Settings with Cache marked, 461 px of document in a 390 px window. */
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.tab:hover { color: var(--ink); }
|
||||
.tab:focus-visible { outline: none; box-shadow: var(--halo-focus); border-radius: var(--r-2); }
|
||||
.tab[aria-current='page'] { color: var(--acc-ink); border-bottom-color: var(--acc-ink); font-weight: 600; }
|
||||
|
||||
/* A tab's mark (`marks`): a dot in the active ink after the name, up where a
|
||||
superscript would sit, so the tab keeps its height and its baseline. */
|
||||
.mark {
|
||||
display: inline-block;
|
||||
width: var(--s-3);
|
||||
height: var(--s-3);
|
||||
margin-left: var(--s-2);
|
||||
vertical-align: super;
|
||||
border-radius: var(--r-full);
|
||||
background: var(--acc-ink);
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { plainClick, toTrail } from '../app/route'
|
||||
import text from './text.module.css'
|
||||
import styles from './SubTabs.module.css'
|
||||
|
||||
/*
|
||||
The sub-navigation of a section: `View Logs · Query Logs`, the nine panes of
|
||||
`Settings`, the six screens of `Administration`, `Leases · Scopes`.
|
||||
|
||||
## Why it exists, and where it was
|
||||
|
||||
It lived in the sidebar, nested under its section, and the design puts it
|
||||
**under the title** instead, for a reason: the 60 px rail hides the labels below
|
||||
1180 px, so nine sub-panes nested there run out of room. Taking them out of the
|
||||
sidebar fixes that, and Administration and Logs get the same shape.
|
||||
|
||||
What the sidebar gets back is its own shape: **twelve entries, always the same
|
||||
twelve**, instead of fourteen, eighteen or twenty-one depending on where you are.
|
||||
|
||||
## Links, not buttons
|
||||
|
||||
Each tab is a real `<a>` with the route it goes to, exactly like the sidebar: it
|
||||
survives a modifier click, it can be copied, it can be opened in another tab. That
|
||||
is what the routes existing as folders is for. A plain click is intercepted so
|
||||
there is no reload.
|
||||
|
||||
`aria-current="page"` and not `aria-selected`: these are not the tabs of an ARIA
|
||||
`tablist` (there is no panel switching under one heading, there is a page you
|
||||
navigate to), and announcing a `tab` would promise arrow-key navigation that these
|
||||
do not have. It is the same distinction `SectionIndex` documents, one step over:
|
||||
there `location`, because the sections stay on the page; here `page`, because
|
||||
each one is a different screen.
|
||||
|
||||
## A mark on a tab
|
||||
|
||||
`marks` puts a small dot after a tab's name, with its words read as part of the
|
||||
link's name (`Lists, unsaved changes`). Two callers use it, both for unsaved
|
||||
changes and with the same words: Blocking for Lists, and Settings for each pane
|
||||
holding something its one save would send. The words are the caller's and the
|
||||
caller declares them.
|
||||
*/
|
||||
export function SubTabs({
|
||||
label,
|
||||
section,
|
||||
tabs,
|
||||
active,
|
||||
onChoose,
|
||||
marks,
|
||||
}: {
|
||||
/** The accessible name of the navigation: "Settings sections". */
|
||||
label: string
|
||||
/** The section id, to build each tab's route. */
|
||||
section: string
|
||||
tabs: readonly string[]
|
||||
active: string
|
||||
onChoose: (tab: string) => void
|
||||
/** A tab's mark: the words a screen reader hears after its name. */
|
||||
marks?: Partial<Record<string, string>>
|
||||
}) {
|
||||
return (
|
||||
<nav className={styles.bar} aria-label={label}>
|
||||
{tabs.map((t) => (
|
||||
<a
|
||||
key={t}
|
||||
className={styles.tab}
|
||||
href={toTrail({ section, sub: t })}
|
||||
aria-current={t === active ? 'page' : undefined}
|
||||
onClick={(e) => {
|
||||
if (!plainClick(e)) return
|
||||
e.preventDefault()
|
||||
onChoose(t)
|
||||
}}
|
||||
>
|
||||
{t}
|
||||
{marks?.[t] != null && (
|
||||
<>
|
||||
<span className={text.sr}>, {marks[t]}</span>
|
||||
<span className={styles.mark} aria-hidden="true" />
|
||||
</>
|
||||
)}
|
||||
</a>
|
||||
))}
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,471 @@
|
||||
/*
|
||||
The console's table, a single one. It was copied across five modules: the same
|
||||
rule five times, with two cell densities (12 px in four sections, 9 px in Logs
|
||||
and Dashboard) and no row hover in Query Logs of all places, which is the widest
|
||||
table of them all and the one that needs it most to not lose your place.
|
||||
*/
|
||||
|
||||
/*
|
||||
The table is ONE object, not a pile of loose rows on the background. In a DNS
|
||||
console the table is the product: it is where 90 % of the time is spent, so it
|
||||
is given a body (panel, border and corners) instead of being left floating.
|
||||
*/
|
||||
.wrap {
|
||||
overflow-x: auto;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--r-4);
|
||||
background: var(--pan);
|
||||
box-shadow: var(--e-1), var(--edge);
|
||||
}
|
||||
|
||||
.table { border-collapse: collapse; width: 100%; }
|
||||
|
||||
/* The header sits on the raised step: it separates the labels from the data
|
||||
without needing another rule line. */
|
||||
.table thead th {
|
||||
background: color-mix(in oklab, var(--pan2) 30%, transparent);
|
||||
text-align: left;
|
||||
/* ReUI's DataGrid head: a caption, not small caps. */
|
||||
font-size: var(--t-1);
|
||||
color: var(--mute);
|
||||
font-weight: 500;
|
||||
padding: 0 var(--s-8);
|
||||
border-bottom: 1px solid var(--line);
|
||||
white-space: nowrap;
|
||||
/* A single height for every header; see `--row-header`. */
|
||||
height: var(--row-header);
|
||||
}
|
||||
|
||||
.table td {
|
||||
padding: var(--s-7) var(--s-8);
|
||||
border-bottom: 1px solid var(--line2);
|
||||
vertical-align: middle;
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
/*
|
||||
The row that is THIS one: my own session in `Administration > Sessions`, this
|
||||
node in `Cluster`.
|
||||
|
||||
Two tables need it and neither invents it: it is a wash in `--acc-bg`, and it is
|
||||
never the only channel: the session says `(current)` in its own cell and the node
|
||||
says `Self` in its `State` column. The colour is what lets you find the row
|
||||
without reading; the word is what says which row it is.
|
||||
|
||||
Hover still wins over it, because `.table tbody tr:hover` is the more specific
|
||||
selector and losing the hover on precisely the row you are on would be worse than
|
||||
the tint.
|
||||
*/
|
||||
.rowSelf { background: var(--acc-bg); }
|
||||
|
||||
/* The last row carries no line: the panel border closes it. */
|
||||
.table tbody tr:last-child td { border-bottom: 0; }
|
||||
|
||||
.table tbody tr { transition: background var(--t-fast); }
|
||||
.table tbody tr:hover { background: var(--hover); }
|
||||
|
||||
/*
|
||||
Columns have rules, and until now they did not: all ten were left-aligned,
|
||||
`Serial` included, which is a number. A left-aligned number cannot be compared
|
||||
against the one on the row below, which is exactly what it is in a column for.
|
||||
*/
|
||||
|
||||
/* The row's ENTITY: the name of the zone, the scope, the user. It is what you
|
||||
look for when scanning, so it weighs more than the rest of the line. */
|
||||
.entity {
|
||||
font-size: var(--t-5);
|
||||
font-weight: 550;
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
/*
|
||||
The row's own name when it also opens its detail view.
|
||||
|
||||
It was written twice and with opposite treatments: in Zones the name is the name
|
||||
(ink and bold) and turns `--acc` on hover; in the three Administration tables it
|
||||
was `--acc` ALREADY at rest. With two hundred and forty rows that is a whole
|
||||
column of amber, and the colour stops meaning "this is clickable" exactly where
|
||||
it had to mean it. Zones wins, which is also what `.entity` above describes.
|
||||
|
||||
The monospace family does NOT come along: it belongs to Zones because the value
|
||||
is a domain, not because it is an entity. And that is why LONGHANDS go here and
|
||||
not the `font` shorthand: `font: inherit` also resets the family, and since this
|
||||
class is composed from another module, its rule is emitted later and was wiping
|
||||
out Zones' monospacing. It is the same trap already noted in `Menu.module.css`.
|
||||
*/
|
||||
.entityLink {
|
||||
composes: hitArea from './interaction.module.css';
|
||||
border: 0;
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
font-family: inherit;
|
||||
font-size: inherit;
|
||||
line-height: inherit;
|
||||
font-weight: 600;
|
||||
color: var(--ink);
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
/*
|
||||
`overflow-wrap` and not `word-break: break-word`. The two break a word that does
|
||||
not fit, but the second also tells the table the word COULD break after any
|
||||
letter, so the column shrinks to a few characters and every name in it is cut
|
||||
letter by letter: Zones at 390 px drew `0.30.172.in-addr.arpa` in four lines.
|
||||
This one only breaks what still overflows once the column has taken its room.
|
||||
A domain goes through `ui/DomainName`, which wraps it at its dots.
|
||||
*/
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
.entityLink:hover { color: var(--acc-ink); }
|
||||
|
||||
/* Numbers: right-aligned and with fixed-width digits, so the units line up one
|
||||
above the other. */
|
||||
.number {
|
||||
text-align: right;
|
||||
font-family: var(--font-mono);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* Metadata: the date, the "N ago", the counter. They accompany, they do not compete. */
|
||||
.meta { composes: trailer from './text.module.css'; }
|
||||
|
||||
/* A cell with several lines inside aligns to the top; the rest, to the middle. */
|
||||
.stacked { vertical-align: top; }
|
||||
|
||||
/*
|
||||
The "there is nothing here" row. It was written with
|
||||
`style={{textAlign:'center'}}` in four places and with two more class names for
|
||||
the same rule.
|
||||
|
||||
It goes as `td.noRows` and not as plain `.noRows` because `.table td` (one
|
||||
class and one type) beat it on specificity, so neither the colour nor the padding
|
||||
ever applied: the row came out with the data colour and the height of a normal
|
||||
cell. Only the centring showed, which is the one of the three rules that clashes
|
||||
with nothing.
|
||||
*/
|
||||
.table td.noRows {
|
||||
text-align: center;
|
||||
color: var(--faint);
|
||||
padding: var(--s-11) var(--s-7);
|
||||
}
|
||||
|
||||
/* A sortable header is a button, not a `th` with `onclick`: that way it is
|
||||
reachable with the tab key and announced for what it is. */
|
||||
.sort {
|
||||
composes: hitArea from '../ui/interaction.module.css';
|
||||
display: inline-flex;
|
||||
/*
|
||||
Aligned to the MIDDLE of the text and not to its baseline.
|
||||
|
||||
An `inline-flex` sits on the baseline, and when there is only an icon inside
|
||||
(the "Type" header in DHCP Leases, whose label is for screen readers only), the
|
||||
line box grows underneath to make room for a descender that is not there. That
|
||||
header measured 33.77 px when the other six tables measured 33: the gap came
|
||||
from a character that is never written.
|
||||
*/
|
||||
vertical-align: middle;
|
||||
align-items: center;
|
||||
gap: var(--s-2);
|
||||
background: none;
|
||||
border: 0;
|
||||
padding: 0;
|
||||
font: inherit;
|
||||
color: inherit;
|
||||
text-transform: inherit;
|
||||
letter-spacing: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.sort:hover { color: var(--ink); }
|
||||
|
||||
/*
|
||||
The sort arrow is only visible when it is needed: on the active column, on hover
|
||||
and when reached with the keyboard. With all nine headers carrying their little
|
||||
arrow at once, the label row was a line of symbols competing with the data and
|
||||
saying nothing, because "this is sortable" is the same on all of them.
|
||||
*/
|
||||
.arrow {
|
||||
display: inline-flex;
|
||||
color: var(--faint);
|
||||
opacity: 0;
|
||||
transition: opacity var(--t-fast);
|
||||
}
|
||||
|
||||
.sort:hover .arrow,
|
||||
.sort:focus-visible .arrow,
|
||||
[aria-sort='ascending'] .arrow,
|
||||
[aria-sort='descending'] .arrow { opacity: 1; }
|
||||
|
||||
/* Ascending and descending are the SAME chevron rotated, not two different
|
||||
characters: that way the arrow turns on click instead of jumping. */
|
||||
.arrow svg { transition: transform var(--t-fast), color var(--t-fast); }
|
||||
.arrow svg[data-desc='true'] { transform: rotate(180deg); }
|
||||
|
||||
.sort:hover .arrow,
|
||||
[aria-sort='ascending'] .arrow,
|
||||
[aria-sort='descending'] .arrow { color: var(--acc-ink); }
|
||||
|
||||
/*
|
||||
The actions column: hard against the end and as wide as what it carries.
|
||||
|
||||
Without this rule the cell inherited `text-align: left` and the column kept all
|
||||
the width the table had left over, so the buttons floated in the middle of the
|
||||
gap: measured before fixing it, between the last control and the table edge there
|
||||
were 51 px in Cache, 80 in Zones, 126 in Users, 196 in Scopes and 306 in Groups.
|
||||
Five tables and five different places for the same thing.
|
||||
|
||||
`width: 1%` with `table-layout: auto` is how you say "this column, the minimum":
|
||||
the browser hands what is left over to the others.
|
||||
*/
|
||||
.actionsCell {
|
||||
width: 1%;
|
||||
white-space: nowrap;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
/*
|
||||
A row's actions, as ONE group and not as four loose chips.
|
||||
|
||||
Loose they did not read: their background sat at 1.25:1 against the row and their
|
||||
border at 1.57:1, meaning the control did not separate from the row containing
|
||||
it, and the `⋮` ended up a narrow strip next to "Delete" that looked like a
|
||||
layout bug.
|
||||
|
||||
Grouped into a segmented control with a single border and dividers inside, the
|
||||
row has ONE place where you act, and that place is visible. It also takes less
|
||||
space and copes with one row having three actions and the next one five.
|
||||
*/
|
||||
.actions {
|
||||
display: inline-flex;
|
||||
align-items: stretch;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--r-2);
|
||||
overflow: hidden;
|
||||
background: var(--pan2);
|
||||
box-shadow: var(--edge);
|
||||
}
|
||||
|
||||
/*
|
||||
`> *` is a DIRECT child, and the `⋮` menu trigger is not one: `ui/Menu` wraps it
|
||||
in a `div`. So the flattening passed it by and it kept the border, the 6 px
|
||||
radius, the solid background and the inset shadow of a loose button: one little
|
||||
rounded box per row, glued to a flat group. Measured in the same cell: "Zone
|
||||
Options" and "Disable Zone" with radius 0 and transparent background, and the
|
||||
`⋮` with radius 6 and `rgb(33,37,41)`.
|
||||
*/
|
||||
.actions > *,
|
||||
.actions > * > button {
|
||||
border: 0 !important;
|
||||
border-radius: 0 !important;
|
||||
background: transparent !important;
|
||||
box-shadow: none !important;
|
||||
min-height: 30px;
|
||||
color: var(--ink);
|
||||
font-weight: 500;
|
||||
font-size: var(--t-4);
|
||||
}
|
||||
|
||||
.actions > * + * { border-left: 1px solid var(--line) !important; }
|
||||
|
||||
/* A row with no action to offer (a cache record with neither Glue nor RRSIG)
|
||||
draws no group: empty, its border was a two-pixel box at the row's end. */
|
||||
.actions:empty { display: none; }
|
||||
|
||||
.actions > *:hover:not(:disabled),
|
||||
.actions > * > button:hover:not(:disabled) { background: var(--hover-strong) !important; }
|
||||
.actions > *:disabled,
|
||||
.actions > * > button:disabled { color: var(--faint); }
|
||||
|
||||
/* Delete keeps its colour, but inside the group: it is not filled with red,
|
||||
because a row with a red block turns the table into an alarm. */
|
||||
.actions > [data-variant='danger'] { color: var(--dan); font-weight: 500; }
|
||||
.actions > [data-variant='danger']:hover:not(:disabled) {
|
||||
background: var(--dan-fill) !important;
|
||||
color: var(--on-dan);
|
||||
}
|
||||
|
||||
/*
|
||||
Row buttons carry an ICON and not a label, and the reason is a measurement: the
|
||||
actions column was 239 px (the widest in the table, ahead of the zone name, which
|
||||
is 163) and its content was the same text repeated on every row. "Options",
|
||||
"Disable", "Delete", two hundred and forty times. That is not information: it is
|
||||
something you have to filter out in order to read the data.
|
||||
|
||||
With an icon the column drops to ~100 px and the 140 left over go to the table.
|
||||
No action loses its name: it goes in `aria-label` (so the keyboard and the screen
|
||||
reader announce it just the same) and in `title`, which is the tooltip on hover.
|
||||
And the `⋮` menu carries EVERY action with its text, delete included, so no name
|
||||
lives only inside a drawing.
|
||||
*/
|
||||
.actions > [data-icon='true'],
|
||||
.actions > * > [data-icon='true'] { padding-left: var(--s-6); padding-right: var(--s-6); }
|
||||
|
||||
/* The row-selection checkbox is 18 px: it is clicked from anywhere in its cell. */
|
||||
.checkCell {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.checkCell label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 40px;
|
||||
padding: 0 var(--s-7);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/*
|
||||
In the HEADER the checkbox stands alone and must not dictate the row height.
|
||||
|
||||
The 40 px above are for a data row, where the touch target fills the cell and
|
||||
matches the row height. Applied to the header too, Zones' measured 57 px while
|
||||
the other six tables in the console measured 33: the same header, nearly twice as
|
||||
tall, and without any label taking two lines. Here the target is still the whole
|
||||
cell, only the cell is as tall as the header is.
|
||||
*/
|
||||
thead th.checkCell { padding: 0; }
|
||||
thead .checkCell label { min-height: 0; }
|
||||
|
||||
/*
|
||||
The stacking table (`stack` in `Table.tsx`, which decides WHEN and says why).
|
||||
These rules apply while the table carries `data-stacked`, which `Table.tsx` sets
|
||||
when the table cannot fit its wrapper, and below `--bp-stack` (560 px of
|
||||
wrapper) in any case. Without it the class only marks the table.
|
||||
|
||||
`.lead` is what a screen puts on the cell or cells that identify its row; it
|
||||
means nothing to a table that does not stack.
|
||||
|
||||
`position: relative` is for the header cells that leave the screen (see `.sr`
|
||||
in text.module.css: clipped, they would otherwise push the page sideways).
|
||||
*/
|
||||
.stackWrap { position: relative; }
|
||||
|
||||
.stack[data-stacked],
|
||||
.stack[data-stacked] > thead,
|
||||
.stack[data-stacked] > tbody,
|
||||
.stack[data-stacked] > tfoot { display: block; }
|
||||
|
||||
/*
|
||||
The header row: its sort buttons and the select-all box, as one wrapping
|
||||
strip. A header that is only a word stays in the page for a screen reader and
|
||||
leaves the screen, because each row already writes it over its value; a header
|
||||
row with no control at all leaves the screen entirely.
|
||||
*/
|
||||
.stack[data-stacked] > thead > tr {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--s-3) var(--s-8);
|
||||
padding: var(--s-4) var(--s-7);
|
||||
background: var(--pan2);
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.stack[data-stacked] > thead > tr > th { height: auto; padding: 0; border: 0; width: auto !important; }
|
||||
.stack[data-stacked] > thead > tr > th.checkCell label { padding: 0; }
|
||||
.stack[data-stacked] > thead:not(:has(button, input)),
|
||||
.stack[data-stacked] > thead > tr > th:not(:has(button, input)) {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip-path: inset(50%);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/*
|
||||
A row: one flex container. The checkbox, the lead cells and the actions take
|
||||
`order: 1` and share the first line; the empty `::after` with `order: 2` and a
|
||||
full basis ends that line; every other cell is a fact, `order: 3`, as wide as
|
||||
its content and never wider than the row. The gap between lines is each fact's
|
||||
own top margin rather than `row-gap`, which would also open above the empty
|
||||
line and count twice.
|
||||
*/
|
||||
.stack[data-stacked] > tbody > tr,
|
||||
.stack[data-stacked] > tfoot > tr {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-start;
|
||||
column-gap: var(--s-9);
|
||||
padding: var(--s-5) var(--s-7) var(--s-6);
|
||||
border-bottom: 1px solid var(--line2);
|
||||
}
|
||||
.stack[data-stacked] > tbody > tr:last-child { border-bottom: 0; }
|
||||
.stack[data-stacked] > tbody > tr::after,
|
||||
.stack[data-stacked] > tfoot > tr::after { content: ''; order: 2; flex-basis: 100%; }
|
||||
|
||||
.stack[data-stacked] > tbody > tr > td,
|
||||
.stack[data-stacked] > tfoot > tr > td {
|
||||
order: 3;
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
width: auto;
|
||||
margin-top: var(--s-3);
|
||||
padding: 0;
|
||||
border: 0;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
/* The first line: the lead cells side by side, the actions pushed to its end.
|
||||
A lead cell shrinks, so a long name wraps (at its dots) before it can push
|
||||
the actions off the line. */
|
||||
.stack[data-stacked] > tbody > tr > td.lead,
|
||||
.stack[data-stacked] > tbody > tr > td.checkCell,
|
||||
.stack[data-stacked] > tbody > tr > td.actionsCell { order: 1; margin-top: 0; align-self: center; }
|
||||
.stack[data-stacked] > tbody > tr > td.actionsCell { flex: none; margin-left: auto; }
|
||||
.stack[data-stacked] > tbody > tr > td.checkCell label { min-height: 0; padding: 0; }
|
||||
|
||||
/*
|
||||
A fact whose cell is blank (`data-empty`, set by `labelCells`): its label with
|
||||
nothing after it was a line of noise, EXPIRY on every zone that has none,
|
||||
ANSWER on every blocked query. It leaves the screen and stays in the row,
|
||||
clipped as `.sr` is, so the cells after it keep their columns for a screen
|
||||
reader. The row's own cells are never taken out.
|
||||
*/
|
||||
.stack[data-stacked] > tbody > tr > td[data-empty]:not(.lead, .checkCell, .actionsCell) {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip-path: inset(50%);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* The "nothing here" row keeps its centred sentence across the whole row. */
|
||||
.stack[data-stacked] > tbody > tr > td.noRows { flex-basis: 100%; margin-top: 0; padding: var(--s-9) 0; text-align: center; }
|
||||
|
||||
/*
|
||||
The column's own header in front of each fact, in the header row's type, on
|
||||
the value's line: `# 3 TTL 3600 (1h)`. A cell whose content is a block (a
|
||||
record's Data, a scope's ranges) takes it on a line of its own above. The lead
|
||||
cells, the checkbox and the actions carry none: they are the row itself. The
|
||||
empty alternative text keeps a screen reader from reading it twice.
|
||||
*/
|
||||
.stack[data-stacked] > tbody > tr > td[data-label]:not(.lead, .checkCell, .actionsCell)::before,
|
||||
.stack[data-stacked] > tfoot > tr > td[data-label]::before {
|
||||
content: attr(data-label);
|
||||
content: attr(data-label) / '';
|
||||
margin-right: var(--s-4);
|
||||
font-family: var(--font-ui);
|
||||
font-size: var(--text-size);
|
||||
font-weight: var(--text-weight);
|
||||
letter-spacing: var(--text-tracking);
|
||||
text-transform: uppercase;
|
||||
color: var(--mute);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/*
|
||||
A value that starts with a block (a record's Data, a date with its age under it,
|
||||
a scope's ranges) would take the line under its label, one line more per fact.
|
||||
Its first block goes inline, as a grid, whose baseline is its FIRST line's: the
|
||||
label sits on the value's first line and the rest of the block hangs under the
|
||||
value. A block wider than what the label leaves wraps whole to the next line,
|
||||
which is where it was before.
|
||||
*/
|
||||
.stack[data-stacked] > tbody > tr > td[data-label]:not(.lead, .checkCell, .actionsCell) > :is(div, dl):first-child {
|
||||
display: inline-grid;
|
||||
max-width: 100%;
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
import { cleanup, render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { useState } from 'react'
|
||||
import { Table as DataTable, Th, useSort, type Keys } from './Table'
|
||||
|
||||
/*
|
||||
Upstream's rule (`sortTable`, common.js:228-280) is not a toggle: a click sorts
|
||||
ascending UNLESS the column is already ascending, in which case it goes down. The
|
||||
difference shows precisely on the first click.
|
||||
*/
|
||||
|
||||
interface Row {
|
||||
name: string
|
||||
}
|
||||
|
||||
const KEYS: Keys<Row> = { name: (f) => f.name }
|
||||
|
||||
function Table({ data }: { data: Row[] }) {
|
||||
const { rows, sort, toggle } = useSort(KEYS, data)
|
||||
return (
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<Th field="name" sort={sort} onSort={toggle}>
|
||||
Name
|
||||
</Th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((f) => (
|
||||
<tr key={f.name}>
|
||||
<td>{f.name}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)
|
||||
}
|
||||
|
||||
function texts() {
|
||||
return screen.getAllByRole('cell').map((c) => c.textContent)
|
||||
}
|
||||
|
||||
describe('table sorting', () => {
|
||||
it('unsorted: the first click sorts ascending', async () => {
|
||||
render(<Table data={[{ name: 'c' }, { name: 'a' }, { name: 'b' }]} />)
|
||||
await userEvent.click(screen.getByRole('button', { name: /Name/ }))
|
||||
expect(texts()).toEqual(['a', 'b', 'c'])
|
||||
})
|
||||
|
||||
it('already ascending: the first click turns it around, like upstream', async () => {
|
||||
render(<Table data={[{ name: 'a' }, { name: 'b' }, { name: 'c' }]} />)
|
||||
await userEvent.click(screen.getByRole('button', { name: /Name/ }))
|
||||
expect(texts()).toEqual(['c', 'b', 'a'])
|
||||
})
|
||||
|
||||
it('clicking twice goes back up, and announces it with aria-sort', async () => {
|
||||
render(<Table data={[{ name: 'c' }, { name: 'a' }]} />)
|
||||
const th = screen.getByRole('columnheader')
|
||||
const button = screen.getByRole('button', { name: /Name/ })
|
||||
|
||||
expect(th).toHaveAttribute('aria-sort', 'none')
|
||||
await userEvent.click(button)
|
||||
expect(th).toHaveAttribute('aria-sort', 'ascending')
|
||||
await userEvent.click(button)
|
||||
expect(th).toHaveAttribute('aria-sort', 'descending')
|
||||
})
|
||||
|
||||
it('it sorts by the text you see, case-insensitively', async () => {
|
||||
render(<Table data={[{ name: 'Zeta' }, { name: 'alpha' }]} />)
|
||||
await userEvent.click(screen.getByRole('button', { name: /Name/ }))
|
||||
expect(texts()).toEqual(['alpha', 'Zeta'])
|
||||
})
|
||||
})
|
||||
|
||||
/*
|
||||
The stacking table. jsdom does not lay out, so what is checked is the DOM the
|
||||
stylesheet reads: each body cell carries its column's header text, a column with
|
||||
a blank header carries none, and every part of the table keeps its role.
|
||||
*/
|
||||
describe('a stacking table', () => {
|
||||
function Users({ rows }: { rows: { name: string; type: string }[] }) {
|
||||
const { rows: sorted, sort, toggle } = useSort<{ name: string; type: string }>(
|
||||
{ name: (r) => r.name, type: (r) => r.type },
|
||||
rows,
|
||||
)
|
||||
return (
|
||||
<DataTable
|
||||
stack
|
||||
header={
|
||||
<>
|
||||
<Th field="name" sort={sort} onSort={toggle}>Username</Th>
|
||||
<th>Type</th>
|
||||
<Th field="type" sort={sort} onSort={toggle} name="Kind" />
|
||||
<th />
|
||||
</>
|
||||
}
|
||||
isEmpty={rows.length === 0}
|
||||
emptyText="No User Found"
|
||||
columns={4}
|
||||
>
|
||||
{sorted.map((r) => (
|
||||
<tr key={r.name}>
|
||||
<td>{r.name}</td>
|
||||
<td>{r.type}</td>
|
||||
<td>icon</td>
|
||||
<td>actions</td>
|
||||
</tr>
|
||||
))}
|
||||
</DataTable>
|
||||
)
|
||||
}
|
||||
|
||||
it('labels each body cell with the text of its column header', () => {
|
||||
render(<Users rows={[{ name: 'admin', type: 'Local' }]} />)
|
||||
const cells = screen.getAllByRole('cell')
|
||||
expect(cells.map((c) => c.getAttribute('data-label'))).toEqual(['Username', 'Type', 'Kind', null])
|
||||
})
|
||||
|
||||
it('keeps the table, its rows, cells and headers in their roles', () => {
|
||||
render(<Users rows={[{ name: 'admin', type: 'Local' }]} />)
|
||||
expect(screen.getByRole('table')).toBeInTheDocument()
|
||||
expect(screen.getAllByRole('row')).toHaveLength(2)
|
||||
expect(screen.getAllByRole('columnheader')).toHaveLength(4)
|
||||
expect(screen.getByRole('cell', { name: 'admin' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('labels the rows a sort brings, and none on the row that spans every column', async () => {
|
||||
function Swap() {
|
||||
const [rows, setRows] = useState([{ name: 'b', type: 'Local' }])
|
||||
return (
|
||||
<>
|
||||
<button type="button" onClick={() => setRows([{ name: 'a', type: 'Remote' }, ...rows])}>add</button>
|
||||
<button type="button" onClick={() => setRows([])}>clear</button>
|
||||
<Users rows={rows} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
render(<Swap />)
|
||||
await userEvent.click(screen.getByRole('button', { name: 'add' }))
|
||||
// Already ascending, so the click turns it around (upstream's rule, above).
|
||||
await userEvent.click(screen.getByRole('button', { name: /Username/ }))
|
||||
expect(screen.getAllByRole('cell').filter((c) => c.getAttribute('data-label') === 'Username').map((c) => c.textContent))
|
||||
.toEqual(['b', 'a'])
|
||||
await userEvent.click(screen.getByRole('button', { name: 'clear' }))
|
||||
const empty = screen.getByRole('cell', { name: 'No User Found' })
|
||||
expect(empty).not.toHaveAttribute('data-label')
|
||||
})
|
||||
|
||||
it('marks a blank cell, and not a placeholder, an icon or a control', () => {
|
||||
render(
|
||||
<DataTable
|
||||
stack
|
||||
header={
|
||||
<>
|
||||
<th>Expiry</th>
|
||||
<th>Serial</th>
|
||||
<th>Answer</th>
|
||||
<th>Placeholder</th>
|
||||
<th>Icon</th>
|
||||
<th>Pick</th>
|
||||
<th>Name</th>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<tr>
|
||||
<td></td>
|
||||
<td>{' '}</td>
|
||||
<td>
|
||||
<span className="clip" />
|
||||
</td>
|
||||
<td>—</td>
|
||||
<td>
|
||||
<svg aria-label="Reserved" />
|
||||
</td>
|
||||
<td>
|
||||
<input type="checkbox" aria-label="Select" />
|
||||
</td>
|
||||
<td>example.net</td>
|
||||
</tr>
|
||||
</DataTable>,
|
||||
)
|
||||
const blank = screen.getAllByRole('cell').map((c) => c.hasAttribute('data-empty'))
|
||||
expect(blank).toEqual([true, true, true, false, false, false, false])
|
||||
// Still in the row: the cells after a blank one keep their columns.
|
||||
expect(screen.getAllByRole('cell')).toHaveLength(7)
|
||||
})
|
||||
|
||||
it('touches nothing on a table that does not stack', () => {
|
||||
render(
|
||||
<DataTable header={<th>Name</th>}>
|
||||
<tr>
|
||||
<td>admin</td>
|
||||
</tr>
|
||||
</DataTable>,
|
||||
)
|
||||
expect(screen.getByRole('cell')).not.toHaveAttribute('data-label')
|
||||
expect(screen.getByRole('cell')).not.toHaveAttribute('data-empty')
|
||||
expect(screen.getByRole('cell')).not.toHaveAttribute('role')
|
||||
})
|
||||
})
|
||||
|
||||
/*
|
||||
WHEN it stacks. jsdom lays nothing out, so the wrapper's two widths are given by
|
||||
hand: what it offers (`clientWidth`) and what the table, laid out as a table,
|
||||
asks of it (`scrollWidth`).
|
||||
*/
|
||||
describe('when a table stacks', () => {
|
||||
const proto = Element.prototype
|
||||
const saved = {
|
||||
client: Object.getOwnPropertyDescriptor(proto, 'clientWidth')!,
|
||||
scroll: Object.getOwnPropertyDescriptor(proto, 'scrollWidth')!,
|
||||
}
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
Object.defineProperty(proto, 'clientWidth', saved.client)
|
||||
Object.defineProperty(proto, 'scrollWidth', saved.scroll)
|
||||
})
|
||||
|
||||
/** The wrapper offers `offer`; laid out as a table, it needs `need`. */
|
||||
function widths(offer: number, need: number) {
|
||||
Object.defineProperty(proto, 'clientWidth', { configurable: true, get: () => offer })
|
||||
Object.defineProperty(proto, 'scrollWidth', {
|
||||
configurable: true,
|
||||
// While stacked the table fits by construction; measuring takes the mark off.
|
||||
get(this: Element) {
|
||||
return this.querySelector(':scope > table[data-stacked]') != null ? offer : need
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function Zones() {
|
||||
return (
|
||||
<DataTable stack header={<th>Zone</th>}>
|
||||
<tr>
|
||||
<td>example.net</td>
|
||||
</tr>
|
||||
</DataTable>
|
||||
)
|
||||
}
|
||||
|
||||
it('stays a table where it fits', () => {
|
||||
widths(1000, 1000)
|
||||
render(<Zones />)
|
||||
expect(screen.getByRole('table')).not.toHaveAttribute('data-stacked')
|
||||
})
|
||||
|
||||
it('stacks where the wrapper would have to scroll, at any width', () => {
|
||||
widths(1000, 1200)
|
||||
render(<Zones />)
|
||||
expect(screen.getByRole('table')).toHaveAttribute('data-stacked')
|
||||
})
|
||||
|
||||
it('stacks below 560 px of wrapper even when nothing scrolls', () => {
|
||||
widths(500, 500)
|
||||
render(<Zones />)
|
||||
expect(screen.getByRole('table')).toHaveAttribute('data-stacked')
|
||||
})
|
||||
|
||||
it('measures again on the next render, as a table and not as it was left', () => {
|
||||
widths(1000, 1200)
|
||||
const { rerender } = render(<Zones />)
|
||||
expect(screen.getByRole('table')).toHaveAttribute('data-stacked')
|
||||
widths(1000, 900)
|
||||
rerender(<Zones />)
|
||||
expect(screen.getByRole('table')).not.toHaveAttribute('data-stacked')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,435 @@
|
||||
import { useLayoutEffect, useRef, useState, type ReactNode } from 'react'
|
||||
import { Button } from './Button'
|
||||
import { Icon, type IconName } from './Icon'
|
||||
import { useTable } from '@tanstack/react-table'
|
||||
import { DataGrid, dataGridFeatures } from '@/components/reui/data-grid/data-grid'
|
||||
import {
|
||||
DataGridTableBase,
|
||||
DataGridTableBody,
|
||||
DataGridTableFoot,
|
||||
DataGridTableHead,
|
||||
DataGridTableViewport,
|
||||
} from '@/components/reui/data-grid/data-grid-table'
|
||||
import styles from './Table.module.css'
|
||||
|
||||
/*
|
||||
Sorting by column. Upstream has it on thirteen tables (`sortTable`,
|
||||
common.js:228-280) and the new console had lost it entirely: with 240 zones
|
||||
paginated ten at a time, "which ones do I still have to sign" could not be
|
||||
answered.
|
||||
|
||||
Its rule is replicated, and it is not a plain toggle:
|
||||
|
||||
· A click sorts ASCENDING…
|
||||
· …unless the column is already ascending, in which case it sorts DESCENDING.
|
||||
|
||||
That is what its bubble sort does: it starts at `asc` and, if the first pass
|
||||
swaps nothing, it turns around. For a user clicking twice in a row the effect is
|
||||
the same as a switch; the difference is in the FIRST click on a column that was
|
||||
already sorted, and there we match too.
|
||||
|
||||
And it sorts by the TEXT YOU SEE, lowercased and compared by character code, just
|
||||
like upstream: that way a column of `2026-08-26 10:48` dates comes out right
|
||||
without treating it as a date, and the order is the same the old console gave.
|
||||
*/
|
||||
|
||||
/*
|
||||
The table: the scaffolding, not just the styles.
|
||||
|
||||
This module exported `useSort`, `Th` and `RowAction` (the helpers) and let each
|
||||
screen write the wrapper, the `table`, the `thead` and the `tbody` by hand.
|
||||
Eighteen tables with the same structure typed out eighteen times, and everything
|
||||
copying allows: six of the seven data tables had been left without their "there
|
||||
is nothing here" row, and the "My Profile" one ended up with a cell density of
|
||||
its own because nobody tied it to the shared one.
|
||||
|
||||
What is shared now is the PIECE. What still belongs to each screen is the only
|
||||
thing that really changes: which columns there are and what goes in each row.
|
||||
|
||||
<Table
|
||||
header={<><Th …>Username</Th>…</>}
|
||||
isEmpty={users.length === 0}
|
||||
emptyText="No User Found"
|
||||
columns={8}
|
||||
>
|
||||
{users.map((u) => <tr key={u.username}>…</tr>)}
|
||||
</Table>
|
||||
|
||||
`isEmpty` is explicit and not guessed by counting children: a `.map()` over an empty
|
||||
list hands back an empty array, not zero children, and a detection that is right
|
||||
by accident is worse than a parameter.
|
||||
*/
|
||||
/*
|
||||
`stack`: when the table does not fit its panel, each row becomes a block, so the
|
||||
cells that say what a row IS stay on the screen instead of behind a sideways
|
||||
scroll. WHEN is decided further down, in `useStacking`.
|
||||
|
||||
Measured on 2026-10-16 against the showcase at 390x844, before it:
|
||||
|
||||
Zones 835 px of table in a 360 px panel: Status, Serial, Expiry,
|
||||
Last Modified and the row actions off screen
|
||||
Zone records 728 in 360: Data, the column that matters, off screen
|
||||
Users 848 in 360: 2FA Status and the actions off screen
|
||||
Query Logs 917 in 360: Response Type, Domain and Answer off screen
|
||||
Sessions 945 in 360, DHCP Leases 714, Scopes 752, Cluster 1,168,
|
||||
Recently Blocked 430: the same, each with its actions or
|
||||
its last columns out of sight
|
||||
Cache no scroll, which was worse: four fixed columns left Data
|
||||
80 px, and one record of `google.com` stood a letter per
|
||||
line, 1,671 px tall. At 1024 too, beside the tree.
|
||||
|
||||
Every one is the same defect. A table can only get narrower by squeezing a
|
||||
column or by scrolling, and at that width either loses the row: squeezed, a value
|
||||
breaks letter by letter; scrolled, the cells that identify the row are on one side
|
||||
and the ones that describe it on the other. So there the row stops being a table
|
||||
row, by ONE rule for all of them:
|
||||
|
||||
[checkbox] LEAD CELL(S) .......................... [actions]
|
||||
LABEL value LABEL value LABEL value
|
||||
LABEL first line of a block value
|
||||
rest of the block…
|
||||
|
||||
The first line is what identifies the row: the cells the screen marks with
|
||||
`.lead` (the zone; the record's name and type; the user; the queried domain and
|
||||
its type), with the row's checkbox before them and its actions hard against the
|
||||
end, as at 1440. Every other cell follows as a fact, its column's header in front
|
||||
of its value, as many to a line as fit; a long value takes the whole line and
|
||||
wraps at its spaces and dots, never inside a word.
|
||||
|
||||
The labels are the table's OWN header texts, read from each column's `<th>`
|
||||
after every render into `data-label`: nothing to keep in sync and not one new
|
||||
word, and a column upstream leaves blank gets no label. CSS draws the label with
|
||||
an empty alternative text (`content: … / ""`), so a screen reader does not hear it
|
||||
twice; it hears the header, because the table keeps its semantics. A `display`
|
||||
other than `table` makes some browsers drop them, so in this mode the table, its
|
||||
row groups, rows and cells carry their roles explicitly, the ones the elements
|
||||
imply.
|
||||
|
||||
Nothing is hidden from anyone: every cell is still in its row, in the page, in the
|
||||
copy and in find. The header row stays in the page too, and on screen it keeps its
|
||||
sort buttons and the select-all box, as a strip: those are controls, and a phone
|
||||
needs them as much as a desk does.
|
||||
|
||||
After it, at 390: no table scrolls sideways and none breaks a word. Rows measure
|
||||
Zones 131, an A record 142 (the SOA 284), Leases 65, Recently Blocked 92, Query
|
||||
Logs 156 to 183, Users 198, Sessions 195 to 216, Scopes 190, Cluster 208 to 220,
|
||||
the negative-cache record that was 1,671 px 220. A table that fits is exactly
|
||||
the table it was.
|
||||
*/
|
||||
export function Table({
|
||||
header,
|
||||
children,
|
||||
isEmpty = false,
|
||||
emptyText,
|
||||
columns,
|
||||
className,
|
||||
tableClass,
|
||||
footer,
|
||||
stack = false,
|
||||
}: {
|
||||
/** The `thead` cells; normally `Th` from this same module. */
|
||||
header: ReactNode
|
||||
children: ReactNode
|
||||
/** Whether there are no rows to draw. */
|
||||
isEmpty?: boolean
|
||||
/** What to say then. Without this, an empty table shows a blank body. */
|
||||
emptyText?: ReactNode
|
||||
/** How many columns that row spans. */
|
||||
columns?: number
|
||||
/** For the wrapper: the max width of a narrow table, for example. */
|
||||
className?: string
|
||||
/** For the table: the sticky header of the "More" dialog, for example. */
|
||||
tableClass?: string
|
||||
/** The footer row, when the table carries its count inside. */
|
||||
footer?: ReactNode
|
||||
/** Rows become blocks where the table does not fit; the identifying cells carry `.lead`. */
|
||||
stack?: boolean
|
||||
}) {
|
||||
const wrap = useRef<HTMLDivElement>(null)
|
||||
useStacking(wrap, stack)
|
||||
|
||||
/* The frame is ReUI's DataGrid (viewport, table, head, body, foot); the rows are
|
||||
still the screen's own `<tr>`, because what a row holds (a menu, a link, a
|
||||
colSpan'd group) is not a column definition. So the grid is given no columns
|
||||
and no data: it supplies the structure and the look, not the rows. */
|
||||
const grid = useTable({ features: dataGridFeatures, columns: NO_COLUMNS, data: NO_ROWS })
|
||||
const base = [styles.table, stack && styles.stack, tableClass].filter(Boolean).join(' ')
|
||||
|
||||
return (
|
||||
<div ref={wrap} className={[styles.wrap, stack && styles.stackWrap, className].filter(Boolean).join(' ')}>
|
||||
<DataGrid table={grid} recordCount={0} tableLayout={{ width: 'auto' }} tableClassNames={{ base }}>
|
||||
<DataGridTableViewport>
|
||||
<DataGridTableBase>
|
||||
<DataGridTableHead>
|
||||
<tr>{header}</tr>
|
||||
</DataGridTableHead>
|
||||
<DataGridTableBody>
|
||||
{isEmpty && emptyText != null ? (
|
||||
<tr>
|
||||
<td colSpan={columns} className={styles.noRows}>
|
||||
{emptyText}
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
children
|
||||
)}
|
||||
</DataGridTableBody>
|
||||
{footer != null && (
|
||||
<DataGridTableFoot>
|
||||
<tr>{footer}</tr>
|
||||
</DataGridTableFoot>
|
||||
)}
|
||||
</DataGridTableBase>
|
||||
</DataGridTableViewport>
|
||||
</DataGrid>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const NO_COLUMNS: never[] = []
|
||||
const NO_ROWS: never[] = []
|
||||
|
||||
/*
|
||||
WHEN a table stacks: when it does not fit its wrapper, and always below
|
||||
`--bp-stack` (560 px of wrapper).
|
||||
|
||||
The first version was the 560 alone, as a container query, and it was a guess
|
||||
about where the tables stop fitting. Measured on 2026-10-16 it was wrong for four
|
||||
of them: at 1024 and 768 Zones scrolled 835 px of table in a 758 px panel, Users
|
||||
848, Sessions 945 and Query Logs about 930, each with its row actions or last
|
||||
columns out of sight, which is the defect the stacking exists for. No single
|
||||
width is right, because each table's natural width is its own and changes with
|
||||
its data (a long answer, a longer zone name). So the condition is the real one:
|
||||
the table is laid out as a table and, if the wrapper has to scroll to hold it
|
||||
(`scrollWidth > clientWidth`), it stacks.
|
||||
|
||||
The 560 stays as a floor, for the one way a table fails without scrolling: a
|
||||
column whose content can shrink to nothing (`ui/kv`'s value column, which keeps a
|
||||
DNSSEC key inside its cell) is squeezed instead. That is Cache beside its tree,
|
||||
414 px at 1024, where Data went to 80 px and a record stood 1,671 px tall.
|
||||
|
||||
How it is measured, and why it cannot loop or flicker:
|
||||
|
||||
· It is measured AS A TABLE every time: a stacked table has `data-stacked`
|
||||
taken off, is read, and gets it back in the same task. The browser lays the
|
||||
page out for the read and paints only the final state, so the in-between
|
||||
table is never seen. Measuring the unstacked form each time makes the
|
||||
decision a function of the width and the rows alone, never of the state it
|
||||
is in, so a decision cannot undo itself.
|
||||
· It runs before paint: in a layout effect after every render (new rows, a
|
||||
sort, a page) and in a `ResizeObserver` on the wrapper, after a width change
|
||||
only; height changes (which stacking itself causes) are ignored. The observer
|
||||
also watches the table, so a row that grows wider in place is caught, and the
|
||||
fonts finishing loading re-measure once.
|
||||
· No hysteresis band is needed. The only feedback is the page's own scrollbar:
|
||||
stacking makes the page taller, a scrollbar may appear and the wrapper loses
|
||||
its width, which keeps the table stacked; unstacking makes it shorter, the
|
||||
scrollbar may go and the wrapper gains width, which keeps it a table. Both
|
||||
push the way the decision already went. A pixel of slack absorbs subpixel
|
||||
widths.
|
||||
|
||||
So nothing flashes on load: the first rows are laid out, measured and placed
|
||||
before the first frame that shows them.
|
||||
*/
|
||||
const STACK_BELOW = 560 // --bp-stack
|
||||
|
||||
function measure(wrap: HTMLElement, table: HTMLTableElement): boolean {
|
||||
if (wrap.clientWidth < STACK_BELOW) return true
|
||||
const was = table.hasAttribute('data-stacked')
|
||||
if (was) table.removeAttribute('data-stacked')
|
||||
const overflows = wrap.scrollWidth > wrap.clientWidth + 1
|
||||
if (was) table.setAttribute('data-stacked', '')
|
||||
return overflows
|
||||
}
|
||||
|
||||
function place(wrap: HTMLElement, table: HTMLTableElement) {
|
||||
table.toggleAttribute('data-stacked', measure(wrap, table))
|
||||
}
|
||||
|
||||
/* The table is ReUI's, so it is found inside the wrapper rather than held by a ref. */
|
||||
const tableIn = (wrap: HTMLElement | null) => wrap?.querySelector('table') ?? null
|
||||
|
||||
function useStacking(ref: React.RefObject<HTMLDivElement | null>, stack: boolean) {
|
||||
// After every render, because the rows are the screen's: a sort, a page or a
|
||||
// filter hands back new cells, and React leaves alone attributes it did not set.
|
||||
useLayoutEffect(() => {
|
||||
const wrap = ref.current
|
||||
const table = tableIn(wrap)
|
||||
if (!stack || wrap == null || table == null) return
|
||||
labelCells(table)
|
||||
place(wrap, table)
|
||||
})
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const wrap = ref.current
|
||||
const table = tableIn(wrap)
|
||||
if (!stack || table == null || wrap == null || typeof ResizeObserver === 'undefined') return
|
||||
let wrapWidth = wrap.clientWidth
|
||||
let tableWidth = table.offsetWidth
|
||||
const observer = new ResizeObserver(() => {
|
||||
if (wrap.clientWidth === wrapWidth && table.offsetWidth === tableWidth) return
|
||||
place(wrap, table)
|
||||
wrapWidth = wrap.clientWidth
|
||||
tableWidth = table.offsetWidth
|
||||
})
|
||||
observer.observe(wrap)
|
||||
observer.observe(table)
|
||||
let live = true
|
||||
void document.fonts?.ready.then(() => {
|
||||
if (live) place(wrap, table)
|
||||
})
|
||||
return () => {
|
||||
live = false
|
||||
observer.disconnect()
|
||||
}
|
||||
}, [ref, stack])
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives every row and cell of a stacking table its role, and every body cell the
|
||||
* text of its column's header in `data-label`. Columns are counted with their
|
||||
* `colSpan`; a cell spanning several (the "nothing here" row) gets no label.
|
||||
*/
|
||||
export function labelCells(table: HTMLTableElement) {
|
||||
/* In this mode the table and its row groups carry their roles explicitly. */
|
||||
table.setAttribute('role', 'table')
|
||||
for (const group of [table.tHead, ...Array.from(table.tBodies), table.tFoot]) group?.setAttribute('role', 'rowgroup')
|
||||
const head = table.tHead?.rows[0]
|
||||
const labels: string[] = []
|
||||
if (head != null) {
|
||||
head.setAttribute('role', 'row')
|
||||
for (const th of Array.from(head.cells)) {
|
||||
th.setAttribute('role', 'columnheader')
|
||||
// A header that shows no text still names its sort button (`Th`'s `name`).
|
||||
const named = th.querySelector('button[aria-label]')?.getAttribute('aria-label')
|
||||
const label = (th.textContent ?? '').trim() || (named ?? '')
|
||||
for (let i = 0; i < th.colSpan; i++) labels.push(label)
|
||||
}
|
||||
}
|
||||
const sections = [...Array.from(table.tBodies), ...(table.tFoot != null ? [table.tFoot] : [])]
|
||||
for (const section of sections) {
|
||||
for (const row of Array.from(section.rows)) {
|
||||
row.setAttribute('role', 'row')
|
||||
let column = 0
|
||||
for (const cell of Array.from(row.cells)) {
|
||||
cell.setAttribute('role', cell.tagName === 'TH' ? 'rowheader' : 'cell')
|
||||
const label = cell.colSpan === 1 ? labels[column] : undefined
|
||||
if (label) cell.setAttribute('data-label', label)
|
||||
else cell.removeAttribute('data-label')
|
||||
if (isBlank(cell)) cell.setAttribute('data-empty', '')
|
||||
else cell.removeAttribute('data-empty')
|
||||
column += cell.colSpan
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
A cell with nothing to show: no text but white space, and no element that is a
|
||||
value without text (an icon, an image, a control). An empty `<span>`, the space
|
||||
Zones writes for a missing serial and an empty date are blank; the "no value"
|
||||
placeholder (an em dash) is text and is a value. In a stacked row a blank fact is
|
||||
only a label with nothing after it, so the stylesheet takes it off the screen; it
|
||||
stays in the row, so every later cell keeps its column for a screen reader.
|
||||
*/
|
||||
const VALUE_WITHOUT_TEXT = 'svg, img, input, button, select, textarea, [role="img"]'
|
||||
|
||||
function isBlank(cell: HTMLTableCellElement): boolean {
|
||||
return (cell.textContent ?? '').trim() === '' && cell.querySelector(VALUE_WITHOUT_TEXT) == null
|
||||
}
|
||||
|
||||
export interface Sort {
|
||||
field: string
|
||||
desc: boolean
|
||||
}
|
||||
|
||||
/** How each sortable column is read: the text the user sees in the cell. */
|
||||
export type Keys<T> = Record<string, (row: T) => string | number | null | undefined>
|
||||
|
||||
function text(v: string | number | null | undefined): string {
|
||||
return String(v ?? '').toLowerCase()
|
||||
}
|
||||
|
||||
export function useSort<T>(keys: Keys<T>, rows: T[]) {
|
||||
const [sort, setSort] = useState<Sort | null>(null)
|
||||
|
||||
const sorted = (() => {
|
||||
if (sort == null || keys[sort.field] == null) return rows
|
||||
const read = keys[sort.field]
|
||||
const sign = sort.desc ? -1 : 1
|
||||
return [...rows].sort((a, b) => {
|
||||
const x = text(read(a))
|
||||
const y = text(read(b))
|
||||
return x === y ? 0 : (x > y ? 1 : -1) * sign
|
||||
})
|
||||
})()
|
||||
|
||||
function toggle(field: string) {
|
||||
const read = keys[field]
|
||||
if (read == null) return
|
||||
// The list is looked at AS IT IS DRAWN, which is what upstream looks at.
|
||||
const alreadyAsc = sorted.every((f, i) => i === 0 || text(read(sorted[i - 1])) <= text(read(f)))
|
||||
setSort({ field, desc: alreadyAsc })
|
||||
}
|
||||
|
||||
return { rows: sorted, sort, toggle }
|
||||
}
|
||||
|
||||
/** A sortable column header. Without `field` it is an ordinary header. */
|
||||
export function Th({
|
||||
field,
|
||||
sort,
|
||||
onSort,
|
||||
children,
|
||||
name,
|
||||
...rest
|
||||
}: {
|
||||
field?: string
|
||||
sort?: Sort | null
|
||||
onSort?: (field: string) => void
|
||||
children?: ReactNode
|
||||
/** For a header upstream leaves BLANK and which is still sortable: the button
|
||||
* needs a name even though the cell shows no label. */
|
||||
name?: string
|
||||
} & React.ThHTMLAttributes<HTMLTableCellElement>) {
|
||||
if (field == null || onSort == null) return <th {...rest}>{children}</th>
|
||||
|
||||
const active = sort?.field === field
|
||||
return (
|
||||
<th aria-sort={active ? (sort!.desc ? 'descending' : 'ascending') : 'none'} {...rest}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.sort}
|
||||
aria-label={children == null ? name : undefined}
|
||||
onClick={() => onSort(field)}
|
||||
>
|
||||
{children}
|
||||
<span className={styles.arrow}>
|
||||
<Icon name={active ? 'chevronDown' : 'sort'} size={12} data-desc={active && !sort!.desc} />
|
||||
</span>
|
||||
</button>
|
||||
</th>
|
||||
)
|
||||
}
|
||||
|
||||
/*
|
||||
The button for a row action. It carries an icon and not a label (see the measured
|
||||
reasoning in `Table.module.css`) but keeps its name in `aria-label` and in
|
||||
`title`, so the keyboard, the screen reader and the tooltip all say the same thing
|
||||
the text that used to fill the column said.
|
||||
*/
|
||||
export function RowAction({
|
||||
icon,
|
||||
name,
|
||||
...rest
|
||||
}: {
|
||||
icon: IconName
|
||||
/** What it does, in upstream's wording: "Options", "Disable", "Edit". */
|
||||
name: string
|
||||
} & Omit<React.ComponentProps<typeof Button>, 'children' | 'size' | 'icon'>) {
|
||||
return (
|
||||
<Button size="sm" icon aria-label={name} title={name} {...rest}>
|
||||
<Icon name={icon} size={15} />
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/*
|
||||
The code chip: a record type (`A`, `SOA`), an app's class. It is not a state pill
|
||||
(it judges nothing), so it is neither round nor coloured.
|
||||
*/
|
||||
.chip {
|
||||
display: inline-block;
|
||||
font-size: var(--t-1);
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.03em;
|
||||
padding: var(--s-1) var(--s-4);
|
||||
border-radius: var(--r-1);
|
||||
background: var(--chip-bg);
|
||||
color: var(--chip-fg);
|
||||
white-space: nowrap;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { Badge, type BadgeProps } from '@/components/reui/badge'
|
||||
import styles from './Tag.module.css'
|
||||
|
||||
/*
|
||||
A pill says ONE state. The five tones and what they mean:
|
||||
|
||||
· neutral: a classification fact that is neither good nor bad (`Primary`, `IPv4`)
|
||||
· ok: the desirable state (`Enabled`, `Online`)
|
||||
· warn: something wants attention but works (`Updating`, `Expiring`)
|
||||
· dan: it is broken or switched off (`Disabled`, `Expired`)
|
||||
· info: an active feature that is not a judgement (`DNSSEC`)
|
||||
|
||||
No pill is painted outside this: counts go in the bar above the table, not in a
|
||||
capsule with this same look.
|
||||
*/
|
||||
|
||||
/*
|
||||
`acc` is the sixth and the youngest: the pill that **names the master switch** of
|
||||
a control that is off. The console's two-word vocabulary gives it the amber
|
||||
because "amber = you can": that is off and **you** can switch it on, which is the opposite of the
|
||||
padlock. `warn` would not do because it means "careful", and using it here would
|
||||
confuse "be careful" with "this is yours to change".
|
||||
|
||||
Sixth in this list and fifth in `tones.module.css`: `neutral` has no tone class.
|
||||
And it is sixth for what it MEANS, not for how it looks: against `warn` it gives
|
||||
ΔE00 8.8 on the text and 0.0 on the fill, below the collision threshold of
|
||||
`dev/palette-distance.mjs`. It stands because today the two never meet on one
|
||||
screen, and `dev/master-switch-signal.test.mjs` is the guard that warns if that
|
||||
changes.
|
||||
*/
|
||||
export type TagTone = 'neutral' | 'ok' | 'warn' | 'dan' | 'info' | 'acc'
|
||||
|
||||
/* The pill is ReUI's Badge in its `-light` variants, drawn with the console's own
|
||||
tokens (`theme/globals.css`). Its six tones keep their meaning. */
|
||||
const VARIANT: Record<TagTone, BadgeProps['variant']> = {
|
||||
neutral: 'secondary',
|
||||
ok: 'success-light',
|
||||
warn: 'warning-light',
|
||||
dan: 'destructive-light',
|
||||
info: 'info-light',
|
||||
acc: 'primary-light',
|
||||
}
|
||||
|
||||
export function Tag({ tone = 'neutral', children }: { tone?: TagTone; children: ReactNode }) {
|
||||
return (
|
||||
<Badge variant={VARIANT[tone]} radius="full" className={tone === 'neutral' ? undefined : `tag-${tone}`}>
|
||||
{children}
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
|
||||
/** The code chip: a record type, an app's class. Neither round nor coloured: it
|
||||
* does not say whether something is good or bad, it says WHAT it is. */
|
||||
export function Chip({ children }: { children: ReactNode }) {
|
||||
return <span className={styles.chip}>{children}</span>
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { act, render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useState } from 'react'
|
||||
import { Toast } from './Toast'
|
||||
|
||||
afterEach(() => vi.useRealTimers())
|
||||
|
||||
function Host({ returnFocus, duration }: { returnFocus?: () => void; duration?: number }) {
|
||||
const [open, setOpen] = useState(true)
|
||||
const [done, setDone] = useState(false)
|
||||
return (
|
||||
<>
|
||||
<input aria-label="Elsewhere" />
|
||||
<Toast
|
||||
message={open ? (done ? 'Done.' : 'Deleted.') : null}
|
||||
action={open && !done ? { label: 'Undo', onClick: () => setDone(true) } : undefined}
|
||||
duration={duration}
|
||||
returnFocus={returnFocus}
|
||||
onDismiss={() => setOpen(false)}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
describe('Toast', () => {
|
||||
it('its live region is in the page while closed, and empty', () => {
|
||||
render(<Toast message={null} onDismiss={() => {}} />)
|
||||
expect(screen.getByRole('status')).toBeEmptyDOMElement()
|
||||
expect(screen.queryByRole('button')).toBeNull()
|
||||
})
|
||||
|
||||
it('says its message in the region, with a focusable action and a close button', async () => {
|
||||
const run = vi.fn()
|
||||
render(<Toast message="Deleted." action={{ label: 'Undo', onClick: run }} onDismiss={() => {}} />)
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Deleted.')
|
||||
/* sonner mounts the notice a moment after: the action is waited for. */
|
||||
await screen.findByRole('button', { name: 'Undo' })
|
||||
/* sonner's own wrapper is a tab stop before the action: one Tab more than the
|
||||
hand-made notice had. */
|
||||
await userEvent.tab()
|
||||
await userEvent.tab()
|
||||
expect(screen.getByRole('button', { name: 'Undo' })).toHaveFocus()
|
||||
await userEvent.keyboard('{Enter}')
|
||||
expect(run).toHaveBeenCalledOnce()
|
||||
expect(screen.getByRole('button', { name: 'Dismiss' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('an action without its permission carries the padlock and is off', async () => {
|
||||
render(<Toast message="Deleted." action={{ label: 'Undo', onClick: () => {}, permission: 'Blocked.canModify' }} onDismiss={() => {}} />)
|
||||
expect(await screen.findByRole('button', { name: 'Undo' })).toBeDisabled()
|
||||
})
|
||||
|
||||
it('goes by itself after its duration, and holds while the focus is inside', async () => {
|
||||
vi.useFakeTimers()
|
||||
render(<Host duration={1000} />)
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(100) })
|
||||
act(() => screen.getByRole('button', { name: 'Undo' }).focus())
|
||||
act(() => vi.advanceTimersByTime(5000))
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Deleted.')
|
||||
act(() => screen.getByLabelText('Elsewhere').focus())
|
||||
act(() => vi.advanceTimersByTime(1000))
|
||||
expect(screen.getByRole('status')).toBeEmptyDOMElement()
|
||||
})
|
||||
|
||||
it('Escape dismisses it, and the focus goes where the page says', async () => {
|
||||
const back = vi.fn(() => screen.getByLabelText('Elsewhere').focus())
|
||||
render(<Host returnFocus={back} />)
|
||||
await screen.findByRole('button', { name: 'Undo' })
|
||||
act(() => screen.getByRole('button', { name: 'Undo' }).focus())
|
||||
await userEvent.keyboard('{Escape}')
|
||||
expect(screen.getByRole('status')).toBeEmptyDOMElement()
|
||||
expect(back).toHaveBeenCalledOnce()
|
||||
expect(screen.getByLabelText('Elsewhere')).toHaveFocus()
|
||||
})
|
||||
|
||||
it('losing its action while focused gives the focus back too', async () => {
|
||||
const back = vi.fn(() => screen.getByLabelText('Elsewhere').focus())
|
||||
render(<Host returnFocus={back} />)
|
||||
await userEvent.click(await screen.findByRole('button', { name: 'Undo' }))
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Done.')
|
||||
expect(back).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,241 @@
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type ReactNode, type Ref } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { Toaster } from '@/components/ui/sonner'
|
||||
import { Icon } from './Icon'
|
||||
import { PermissionButton } from './PermissionButton'
|
||||
|
||||
/*
|
||||
The passing notice with one action: "done, and you can take it back". OURS: upstream
|
||||
has nothing like it, nor its close button's name, `Dismiss`. So far it has a single
|
||||
user, the deletion of rules in the table of Blocking › Rules (CONVENTIONS.md,
|
||||
deviation 2). Every other destructive action of the console still asks first
|
||||
(`ui/Confirm`).
|
||||
|
||||
What it owes, and why:
|
||||
|
||||
- **The message is a live region that is always in the page** (`role="status"`),
|
||||
empty while closed. A region born together with its text is often not announced.
|
||||
- **The action is a real button**, reached with Tab and named by its text. When it
|
||||
needs a permission the session lacks it is drawn with the padlock and says which,
|
||||
as every `PermissionButton` does.
|
||||
- **It goes by itself after `duration`, but not while it is being used**: the
|
||||
pointer over it or the focus inside it holds the clock (WCAG 2.2.1), and the
|
||||
clock starts again whole when they leave. `timerKey` restarts it too, for a
|
||||
notice that gained something. Escape and the close button dismiss it.
|
||||
- **The focus is not lost with it.** If it closes, or loses its action, while the
|
||||
focus was inside it, the focus goes to `returnFocus`: the element that held it is
|
||||
gone, and the browser would leave it on the page's body.
|
||||
- **It moves only for those who want motion**: it rises into place, and with
|
||||
`prefers-reduced-motion` it simply appears.
|
||||
|
||||
The notice itself is drawn by ReUI's `sonner` (placement, stacking, motion); the
|
||||
clock, the hold and the focus rules stay HERE, because sonner has none of them. Its
|
||||
text is `aria-hidden` there: the live region is a separate element that never leaves
|
||||
the page, so it is announced however sonner mounts its own.
|
||||
*/
|
||||
|
||||
export interface ToastAction {
|
||||
label: string
|
||||
onClick: () => void
|
||||
disabled?: boolean
|
||||
/** The missing permission, as `PermissionButton` takes it. */
|
||||
permission?: string
|
||||
}
|
||||
|
||||
const DEFAULT_MS = 8000
|
||||
|
||||
/* One id per notice, never reused: sonner remembers a dismissed id, and a new notice
|
||||
under the same one would be removed as soon as it appeared. */
|
||||
let counter = 0
|
||||
|
||||
/* What sonner draws: the text (hidden from assistive technology, the live region
|
||||
says it), the action and the dismiss button. */
|
||||
function Body({
|
||||
message,
|
||||
action,
|
||||
actionRef,
|
||||
onDismiss,
|
||||
onUse,
|
||||
onFocusIn,
|
||||
onFocusOut,
|
||||
}: {
|
||||
message: ReactNode
|
||||
action?: ToastAction
|
||||
actionRef?: Ref<HTMLButtonElement>
|
||||
onDismiss: () => void
|
||||
onUse: (using: boolean) => void
|
||||
onFocusIn: () => void
|
||||
onFocusOut: (to: Node | null) => void
|
||||
}) {
|
||||
const box = useRef<HTMLDivElement>(null)
|
||||
return (
|
||||
<div
|
||||
ref={box}
|
||||
className="flex w-(--width) max-w-[calc(100vw-2rem)] items-center gap-3 rounded-lg border border-border bg-popover py-2 pr-2 pl-4 text-sm text-popover-foreground shadow-md"
|
||||
onMouseEnter={() => onUse(true)}
|
||||
onMouseLeave={() => onUse(false)}
|
||||
onFocus={onFocusIn}
|
||||
onBlur={(e) => {
|
||||
const to = e.relatedTarget as Node | null
|
||||
if (to != null && box.current?.contains(to)) return
|
||||
onFocusOut(to)
|
||||
}}
|
||||
>
|
||||
<p className="m-0 min-w-0 flex-1 leading-snug break-words" aria-hidden="true">
|
||||
{message}
|
||||
</p>
|
||||
{action != null && (
|
||||
<PermissionButton
|
||||
ref={actionRef}
|
||||
size="sm"
|
||||
variant="primary"
|
||||
disabled={action.disabled}
|
||||
permission={action.permission}
|
||||
onClick={action.onClick}
|
||||
>
|
||||
{action.label}
|
||||
</PermissionButton>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex size-7 shrink-0 items-center justify-center rounded-md border-0 bg-transparent text-muted-foreground transition-colors outline-none hover:bg-muted hover:text-foreground focus-visible:ring-3 focus-visible:ring-ring/50"
|
||||
aria-label="Dismiss"
|
||||
title="Dismiss"
|
||||
onClick={onDismiss}
|
||||
>
|
||||
<Icon name="close" size={14} />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function Toast({
|
||||
message,
|
||||
action,
|
||||
onDismiss,
|
||||
duration = DEFAULT_MS,
|
||||
timerKey,
|
||||
hold = false,
|
||||
returnFocus,
|
||||
actionRef,
|
||||
}: {
|
||||
/** `null` while closed. */
|
||||
message: ReactNode | null
|
||||
action?: ToastAction
|
||||
onDismiss: () => void
|
||||
duration?: number
|
||||
/** A new value restarts the clock. */
|
||||
timerKey?: unknown
|
||||
/** Keeps it open regardless of the clock: while its action is running, say. */
|
||||
hold?: boolean
|
||||
returnFocus?: () => void
|
||||
actionRef?: Ref<HTMLButtonElement>
|
||||
}) {
|
||||
const open = message != null
|
||||
const [pointer, setPointer] = useState(false)
|
||||
const [focused, setFocused] = useState(false)
|
||||
/* Whether the focus was inside when the content changed. A focused button that is
|
||||
removed leaves no blur with a destination, so only a blur to somewhere real
|
||||
clears it. */
|
||||
const hadFocus = useRef(false)
|
||||
const dismiss = useRef(onDismiss)
|
||||
const back = useRef(returnFocus)
|
||||
useEffect(() => {
|
||||
dismiss.current = onDismiss
|
||||
back.current = returnFocus
|
||||
})
|
||||
|
||||
/* Closing forgets the pointer and the focus: the box under them is gone, and no
|
||||
leave or blur may come to say so. Adjusted while rendering, as React advises
|
||||
for state that follows a prop. */
|
||||
const [wasOpen, setWasOpen] = useState(open)
|
||||
if (open !== wasOpen) {
|
||||
setWasOpen(open)
|
||||
if (!open) {
|
||||
setPointer(false)
|
||||
setFocused(false)
|
||||
}
|
||||
}
|
||||
|
||||
const paused = pointer || focused || hold
|
||||
useEffect(() => {
|
||||
if (!open || paused) return
|
||||
const t = setTimeout(() => dismiss.current(), duration)
|
||||
return () => clearTimeout(t)
|
||||
}, [open, paused, duration, timerKey])
|
||||
|
||||
/* The notice is shown, updated and removed through sonner. Its own clock is off
|
||||
(`Infinity`): the one above decides. */
|
||||
const hasAction = open && action != null
|
||||
const current = useRef<string | null>(null)
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
if (current.current != null) toast.dismiss(current.current)
|
||||
current.current = null
|
||||
return
|
||||
}
|
||||
current.current ??= `console-toast-${++counter}`
|
||||
toast.custom(
|
||||
() => (
|
||||
<Body
|
||||
message={message}
|
||||
action={action}
|
||||
actionRef={actionRef}
|
||||
onDismiss={() => dismiss.current()}
|
||||
onUse={setPointer}
|
||||
onFocusIn={() => {
|
||||
hadFocus.current = true
|
||||
setFocused(true)
|
||||
}}
|
||||
onFocusOut={(to) => {
|
||||
setFocused(false)
|
||||
if (to != null) hadFocus.current = false
|
||||
}}
|
||||
/>
|
||||
),
|
||||
{ id: current.current, duration: Infinity, unstyled: true },
|
||||
)
|
||||
})
|
||||
|
||||
/* Leaving the page takes the notice with it: sonner's store outlives this component. */
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (current.current != null) toast.dismiss(current.current)
|
||||
},
|
||||
[],
|
||||
)
|
||||
|
||||
/* Once it is closed, or has lost its action, the button the focus was on is gone. */
|
||||
useLayoutEffect(() => {
|
||||
if (hasAction) return
|
||||
/* Sonner keeps a closing notice in the page while it animates out, so the
|
||||
element is still there: what says the focus is lost is that it WAS inside. */
|
||||
if (hadFocus.current) {
|
||||
hadFocus.current = false
|
||||
back.current?.()
|
||||
}
|
||||
}, [hasAction])
|
||||
|
||||
/* Escape dismisses it from wherever the focus is while it is open. */
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const escape = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault()
|
||||
dismiss.current()
|
||||
}
|
||||
}
|
||||
document.addEventListener('keydown', escape)
|
||||
return () => document.removeEventListener('keydown', escape)
|
||||
}, [open])
|
||||
|
||||
return (
|
||||
<>
|
||||
<Toaster position="bottom-center" />
|
||||
{/* The live region: always in the page, empty while closed. */}
|
||||
<p className="sr-only" role="status">
|
||||
{open ? message : null}
|
||||
</p>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { Tooltip } from './Tooltip'
|
||||
import { Button } from './Button'
|
||||
|
||||
/*
|
||||
What jsdom can and cannot answer here, said up front so nobody reads more into
|
||||
these than there is: there is no layout, so `getBoundingClientRect()` returns
|
||||
zeros and WHERE the bubble lands is not asserted; that is measured in the
|
||||
browser. What it answers is everything that matters for it not to be a trap: that
|
||||
it opens by pointer AND by keyboard, that Escape closes it, that it is associated
|
||||
by description, and (the one that would make it harmful) that it never becomes
|
||||
the trigger's name.
|
||||
*/
|
||||
function Rail() {
|
||||
return (
|
||||
<Tooltip text="Zones">
|
||||
<Button aria-label="Zones" icon>
|
||||
▣
|
||||
</Button>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
describe('Tooltip', () => {
|
||||
it('it opens with the pointer and closes on leaving', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Rail />)
|
||||
expect(screen.queryByRole('tooltip')).toBeNull()
|
||||
|
||||
await user.hover(screen.getByRole('button', { name: 'Zones' }))
|
||||
expect(screen.getByRole('tooltip')).toHaveTextContent('Zones')
|
||||
|
||||
await user.unhover(screen.getByRole('button', { name: 'Zones' }))
|
||||
expect(screen.queryByRole('tooltip')).toBeNull()
|
||||
})
|
||||
|
||||
/*
|
||||
The reason the 60 px rail exists. If it only answered the mouse, twelve icons
|
||||
with no label would be useless with a keyboard.
|
||||
*/
|
||||
it('it opens with focus, not only with the pointer', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Rail />)
|
||||
|
||||
await user.tab()
|
||||
expect(screen.getByRole('button', { name: 'Zones' })).toHaveFocus()
|
||||
expect(screen.getByRole('tooltip')).toHaveTextContent('Zones')
|
||||
})
|
||||
|
||||
it('it closes on losing focus', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(
|
||||
<>
|
||||
<Rail />
|
||||
<button>other</button>
|
||||
</>,
|
||||
)
|
||||
await user.tab()
|
||||
expect(screen.getByRole('tooltip')).toBeTruthy()
|
||||
|
||||
await user.tab()
|
||||
expect(screen.queryByRole('tooltip')).toBeNull()
|
||||
})
|
||||
|
||||
it('Escape closes it without taking focus off the trigger', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Rail />)
|
||||
await user.tab()
|
||||
expect(screen.getByRole('tooltip')).toBeTruthy()
|
||||
|
||||
await user.keyboard('{Escape}')
|
||||
expect(screen.queryByRole('tooltip')).toBeNull()
|
||||
/* The focus stays where it was: Escape closes the bubble, it does not navigate. */
|
||||
expect(screen.getByRole('button', { name: 'Zones' })).toHaveFocus()
|
||||
})
|
||||
|
||||
it('it associates the bubble with the trigger by description', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Rail />)
|
||||
await user.tab()
|
||||
|
||||
const trigger = screen.getByRole('button', { name: 'Zones' })
|
||||
const bubble = screen.getByRole('tooltip')
|
||||
expect(trigger).toHaveAttribute('aria-describedby', bubble.id)
|
||||
expect(bubble.id).toBeTruthy()
|
||||
})
|
||||
|
||||
/*
|
||||
THE ONE THAT MATTERS. A tooltip carrying the name would leave the control
|
||||
nameless as soon as the pointer left (and, for whoever uses no pointer, always).
|
||||
So the accessible name has to be the same with the bubble open and closed, and
|
||||
the association has to be `describedby` and never `labelledby`.
|
||||
*/
|
||||
it('it never replaces the trigger accessible name', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(
|
||||
<Tooltip text="This describes, it does not name">
|
||||
<Button aria-label="Delete Zones">✕</Button>
|
||||
</Tooltip>,
|
||||
)
|
||||
|
||||
const trigger = screen.getByRole('button', { name: 'Delete Zones' })
|
||||
await user.hover(trigger)
|
||||
|
||||
/* With the bubble open, the name has not moved... */
|
||||
expect(screen.getByRole('button', { name: 'Delete Zones' })).toBe(trigger)
|
||||
expect(screen.queryByRole('button', { name: 'This describes, it does not name' })).toBeNull()
|
||||
/* ...and it is not named with it. */
|
||||
expect(trigger).not.toHaveAttribute('aria-labelledby')
|
||||
expect(trigger).toHaveAttribute('aria-label', 'Delete Zones')
|
||||
})
|
||||
|
||||
it('unopened it leaves no dangling `aria-describedby`', () => {
|
||||
render(<Rail />)
|
||||
expect(screen.getByRole('button', { name: 'Zones' })).not.toHaveAttribute('aria-describedby')
|
||||
})
|
||||
|
||||
/*
|
||||
── The three defects it carried, each with its regression ──────────────────
|
||||
*/
|
||||
|
||||
/*
|
||||
1. It overwrote whatever `aria-describedby` the trigger already had. A control
|
||||
described by its own help lost that description the moment you pointed at it,
|
||||
and the attribute is a LIST of ids, not a slot for one.
|
||||
*/
|
||||
it('it concatenates an existing `aria-describedby` instead of overwriting it', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(
|
||||
<>
|
||||
<span id="existing-help">The help it already had</span>
|
||||
<Tooltip text="Zones">
|
||||
<Button aria-label="Zones" aria-describedby="help-previous" icon>
|
||||
▣
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</>,
|
||||
)
|
||||
const trigger = screen.getByRole('button', { name: 'Zones' })
|
||||
await user.hover(trigger)
|
||||
|
||||
const ids = trigger.getAttribute('aria-describedby')!.split(' ')
|
||||
expect(ids).toContain('help-previous')
|
||||
expect(ids).toContain(screen.getByRole('tooltip').id)
|
||||
expect(ids).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('and it gives it back intact on closing', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(
|
||||
<Tooltip text="Zones">
|
||||
<Button aria-label="Zones" aria-describedby="help-previous" icon>
|
||||
▣
|
||||
</Button>
|
||||
</Tooltip>,
|
||||
)
|
||||
const trigger = screen.getByRole('button', { name: 'Zones' })
|
||||
await user.hover(trigger)
|
||||
await user.unhover(trigger)
|
||||
|
||||
expect(trigger).toHaveAttribute('aria-describedby', 'help-previous')
|
||||
})
|
||||
|
||||
/*
|
||||
2. The pointer and the focus did not compose: they were a single boolean, so
|
||||
leaving with the mouse closed a bubble the keyboard was still holding open, and
|
||||
the other way round. It stays open while EITHER cause exists.
|
||||
*/
|
||||
it('it stays open when the pointer leaves if the trigger keeps focus', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Rail />)
|
||||
const trigger = screen.getByRole('button', { name: 'Zones' })
|
||||
|
||||
await user.tab() // focus
|
||||
await user.hover(trigger) // and the pointer as well
|
||||
expect(screen.getByRole('tooltip')).toBeTruthy()
|
||||
|
||||
await user.unhover(trigger) // the pointer leaves, the focus stays
|
||||
expect(screen.getByRole('tooltip')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('it stays open on losing focus if the pointer is still over it', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(
|
||||
<>
|
||||
<Rail />
|
||||
<button>other</button>
|
||||
</>,
|
||||
)
|
||||
const trigger = screen.getByRole('button', { name: 'Zones' })
|
||||
|
||||
await user.hover(trigger)
|
||||
await user.tab()
|
||||
expect(screen.getByRole('tooltip')).toBeTruthy()
|
||||
|
||||
await user.tab() // focus moves to the other button; the pointer is still over it
|
||||
expect(screen.getByRole('tooltip')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('it only closes when both are gone', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(
|
||||
<>
|
||||
<Rail />
|
||||
<button>other</button>
|
||||
</>,
|
||||
)
|
||||
const trigger = screen.getByRole('button', { name: 'Zones' })
|
||||
await user.hover(trigger)
|
||||
await user.tab()
|
||||
await user.tab()
|
||||
await user.unhover(trigger)
|
||||
|
||||
expect(screen.queryByRole('tooltip')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,113 @@
|
||||
import { cloneElement, useId, useState } from 'react'
|
||||
import type { ReactElement, ReactNode } from 'react'
|
||||
import { Tooltip as ReuiTooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
|
||||
import type { Placement } from './tooltip-place'
|
||||
|
||||
/*
|
||||
The label that appears beside something that already has a name.
|
||||
|
||||
It exists because TWO of the console's design rules depend on it and there was
|
||||
nothing in `ui/`: the 60 px rail shows only icons, and without the label on hover
|
||||
it is twelve pictures with no names; and the padlock on a disabled control has to
|
||||
say WHICH permission is missing (`Requires Cache: Delete`) and not merely that one
|
||||
is.
|
||||
|
||||
## The three conditions, which are not decoration
|
||||
|
||||
They are design rules, and they are what the tests below hold:
|
||||
|
||||
· **It never replaces the accessible name.** What it adds is
|
||||
`aria-describedby`, which DESCRIBES; the name goes on the trigger and stays
|
||||
there. A tooltip that carried the name would make the control nameless the
|
||||
moment the pointer left (and, for anyone who never uses a pointer, always).
|
||||
· **Focus and pointer, not just pointer.** A rail that only answers the mouse is
|
||||
a rail that does not work with a keyboard. `onFocus`/`onBlur` are React
|
||||
synthetic events and they BUBBLE, so putting them on the wrapper catches the
|
||||
trigger's focus without the trigger having to cooperate.
|
||||
· **The text already exists.** This component does not compose sentences: it
|
||||
repeats the icon's label, or the permission the button needs. Two wordings for
|
||||
one control is how a console ends up with two truths.
|
||||
|
||||
## Three defects it shipped with, and what each one taught
|
||||
|
||||
They were found in review, before this was wired to anything:
|
||||
|
||||
· **It clobbered an existing `aria-describedby`.** Cloning with the bubble's id
|
||||
threw away whatever the trigger already had; a control described by its own
|
||||
help text lost that description the moment you pointed at it. It now
|
||||
CONCATENATES (that attribute is a space-separated id list, and always was)
|
||||
and the original comes back untouched on close.
|
||||
· **Pointer and focus did not compose.** They were one boolean, so leaving with
|
||||
the mouse closed a bubble the keyboard still had open, and blurring closed one
|
||||
the pointer was still over. They are two independent causes now: it stays open
|
||||
while EITHER holds. Anything else is a bubble that vanishes under your cursor.
|
||||
· **It walked off the screen**, especially at 390 and near any edge. The
|
||||
arithmetic is out in `tooltip-place.ts` as a pure function that flips and then
|
||||
clamps, and it is tested with numbers instead of with a DOM that has no
|
||||
layout.
|
||||
|
||||
## Why it is `position: fixed`
|
||||
|
||||
The same reason as `ui/Menu` and `ui/Select`, and it is not a preference: an
|
||||
absolutely positioned bubble gets clipped by any ancestor with `overflow`, and in
|
||||
this console there are two on the way (the actions group, which hides its corners,
|
||||
and the table wrapper, which scrolls horizontally). Measured from the trigger's
|
||||
rect and painted fixed, nothing can clip it.
|
||||
|
||||
It closes on Escape, on blur and on pointer-out; it does not need to close on an
|
||||
outside click, because it never takes the pointer.
|
||||
*/
|
||||
const SIDE = { top: 'top', bottom: 'bottom', left: 'left', right: 'right' } as const
|
||||
|
||||
export function Tooltip({
|
||||
text,
|
||||
placement = 'right',
|
||||
children,
|
||||
}: {
|
||||
/** The text that already exists somewhere else: the icon's label, the missing permission. */
|
||||
text: ReactNode
|
||||
/** Which side of the trigger it hangs from. The rail wants `right`. */
|
||||
placement?: Placement
|
||||
/** The trigger, which keeps its own accessible name. */
|
||||
children: ReactElement<{ 'aria-describedby'?: string }>
|
||||
}) {
|
||||
const id = useId()
|
||||
/* Two causes, not one: the pointer and the focus leave independently, and it
|
||||
stays open while EITHER holds. */
|
||||
const [hovered, setHovered] = useState(false)
|
||||
const [focused, setFocused] = useState(false)
|
||||
const open = hovered || focused
|
||||
/* What the trigger already carried, plus ours, and only while the bubble exists:
|
||||
pointing at a node that is not in the DOM describes nothing. The name stays
|
||||
where it was: a tooltip DESCRIBES, it never names. */
|
||||
const previous = children.props['aria-describedby']
|
||||
const trigger = open
|
||||
? cloneElement(children, { 'aria-describedby': [previous, id].filter(Boolean).join(' ') })
|
||||
: children
|
||||
return (
|
||||
<TooltipProvider delay={0}>
|
||||
<span
|
||||
className="inline-flex"
|
||||
onMouseEnter={() => setHovered(true)}
|
||||
onMouseLeave={() => setHovered(false)}
|
||||
onFocus={() => setFocused(true)}
|
||||
onBlur={() => setFocused(false)}
|
||||
>
|
||||
<ReuiTooltip
|
||||
open={open}
|
||||
onOpenChange={(next, details) => {
|
||||
if (!next && details.reason === 'escape-key') {
|
||||
setHovered(false)
|
||||
setFocused(false)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<TooltipTrigger render={trigger} />
|
||||
<TooltipContent id={id} role="tooltip" side={SIDE[placement as keyof typeof SIDE] ?? 'right'}>
|
||||
{text}
|
||||
</TooltipContent>
|
||||
</ReuiTooltip>
|
||||
</span>
|
||||
</TooltipProvider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
A URL wraps after its separators and reads as written.
|
||||
|
||||
jsdom does not lay text out, so what is checked is the DOM that decides the
|
||||
wrapping: where the `<wbr>` go, and that the text around them is the URL untouched.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { render } from '@testing-library/react'
|
||||
import { UrlText } from './UrlText'
|
||||
|
||||
function breaks(url: string): string[] {
|
||||
const { container, unmount } = render(<UrlText url={url} />)
|
||||
const out: string[] = []
|
||||
let piece = ''
|
||||
for (const node of container.childNodes) {
|
||||
if (node.nodeName === 'WBR') {
|
||||
out.push(piece)
|
||||
piece = ''
|
||||
} else piece += node.textContent
|
||||
}
|
||||
out.push(piece)
|
||||
expect(container.textContent).toBe(url)
|
||||
unmount()
|
||||
return out
|
||||
}
|
||||
|
||||
describe('a URL', () => {
|
||||
it('may break after each run of separators, never inside one', () => {
|
||||
expect(breaks('https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts')).toEqual([
|
||||
'https://', 'raw.', 'githubusercontent.', 'com/', 'StevenBlack/', 'hosts/', 'master/', 'hosts',
|
||||
])
|
||||
expect(breaks('file:///etc/dns/list.txt')).toEqual(['file:///', 'etc/', 'dns/', 'list.', 'txt'])
|
||||
expect(breaks('https://x.test/a?b=1&c=2')).toEqual(['https://', 'x.', 'test/', 'a?', 'b=', '1&', 'c=', '2'])
|
||||
})
|
||||
|
||||
it('leaves text with no separator as it is', () => {
|
||||
expect(breaks('hosts')).toEqual(['hosts'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,36 @@
|
||||
import { Fragment } from 'react'
|
||||
|
||||
/*
|
||||
A URL that wraps after its separators, the way `DomainName` wraps a name after its
|
||||
dots.
|
||||
|
||||
A list URL has no spaces, so without help the browser has two choices and both are
|
||||
wrong: overflow its box, or, with `overflow-wrap: anywhere` or `break-all`, end a
|
||||
line wherever the edge falls (`raw.githubuser` / `content.com`). The second also
|
||||
lets a table squeeze the column to a few characters, because it tells the browser
|
||||
the URL may break after ANY letter.
|
||||
|
||||
So a `<wbr>` goes after each run of `/`, `.`, `?`, `&` and `=`: after `https://`
|
||||
and not between its two slashes, after `raw.`, after `hosts/`. The pieces are not
|
||||
made unbreakable, unlike a domain's labels: a path segment can be longer than any
|
||||
column, and the caller's `overflow-wrap: break-word` still breaks that one piece
|
||||
when it alone does not fit. It does not change the column's minimum, which is then
|
||||
the longest piece.
|
||||
|
||||
`<wbr>` carries no text: the copied text, the find-in-page match and what a screen
|
||||
reader reads are the URL as written.
|
||||
*/
|
||||
export function UrlText({ url }: { url: string }) {
|
||||
const pieces = url.split(/(?<=[/.?&=])(?![/.?&=])/)
|
||||
if (pieces.length < 2) return <>{url}</>
|
||||
return (
|
||||
<>
|
||||
{pieces.map((piece, i) => (
|
||||
<Fragment key={i}>
|
||||
{piece}
|
||||
{i < pieces.length - 1 && <wbr />}
|
||||
</Fragment>
|
||||
))}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
The count that accompanies a table: "Total Users: 3", "2 zones", "1-6 (6) of 6
|
||||
zones (page 1 of 1)".
|
||||
|
||||
The TEXT is not touched (all three are upstream literals, from `auth.js`,
|
||||
`dhcp.js`, `apps.js` and `zone.js:923`); what was loose was how it is painted.
|
||||
Eight modules defined it for themselves and four treatments came out: `Total
|
||||
Scopes` in bold, `Total Users` in normal, "My Profile"'s `Total Groups` one step
|
||||
smaller, and Apps' halfway there at weight 550.
|
||||
|
||||
WHICH of the two positions each screen uses is still its own (in Zones it goes
|
||||
with the pagination and there is one above and one below), but the DISTANCE is not:
|
||||
the count above sat at `--gap-tight` on the three screens that have it, and the
|
||||
one below at four different distances (`--s-8`, `--s-5`, `--gap-group` and a
|
||||
`padding-top` of `--s-7`) on the four that have it. `--gap-group` is the token
|
||||
that names that distance; its own definition says "between things read together:
|
||||
the foot of a table".
|
||||
*/
|
||||
.count2 {
|
||||
font-size: var(--t-4);
|
||||
font-weight: 400;
|
||||
color: var(--mute);
|
||||
}
|
||||
|
||||
/* When it shares a line with controls (the pagination, a couple of buttons). */
|
||||
.bar {
|
||||
composes: count2;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--s-7);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
/* Above the table: tight against it, which is what it refers to. */
|
||||
.above { margin-bottom: var(--gap-tight); }
|
||||
|
||||
/* Below: the table's foot, read together with the last row. */
|
||||
.below { margin-top: var(--gap-group); }
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
Enlarge the target without enlarging the drawing.
|
||||
|
||||
In a dense table, a 70×20 px link is visually right and wrong for a finger: the
|
||||
recommendation is 44 px and there are six controls here between 14 and 20 px tall
|
||||
(a zone name, the sortable header, a user's link). Actually enlarging them would
|
||||
break the table, which is what this console does best.
|
||||
|
||||
`.hitArea` extends the HIT AREA with an invisible pseudo-element, without moving a
|
||||
single pixel of what is seen. The control still measures 20 px and is clicked as
|
||||
if it measured 36.
|
||||
*/
|
||||
.hitArea {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.hitArea::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: -8px -6px;
|
||||
/* It only widens the target: it must not cover whatever sits beside it. */
|
||||
z-index: var(--layer-hit);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
The key/value list: "Range / 10.0.1.10 - 10.0.1.200", "Key Tag / 42".
|
||||
|
||||
It was written five times (About, Zones, DHCP, the lists screens and the DS modal)
|
||||
and out of the five came four different objects: two column templates (`auto 1fr`
|
||||
and `auto minmax(0,1fr)`, which are not the same thing as soon as the value is
|
||||
long), two row gaps, and three treatments of the value. Only one of the five broke
|
||||
long strings, so the same list overflowed its cell in DHCP and in the lists screens
|
||||
and not in Zones.
|
||||
|
||||
`minmax(0,1fr)` and not `1fr`: a `1fr` grid track has a minimum of `auto`, so it
|
||||
does not go below the width of its content and a value with no spaces (a DNSSEC
|
||||
key, a hex string) pushes the column out of the table.
|
||||
*/
|
||||
|
||||
.kv {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
gap: var(--s-1) var(--s-8);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.kv dt {
|
||||
font-size: var(--t-3);
|
||||
color: var(--mute);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.kv dd {
|
||||
margin: 0;
|
||||
min-width: 0;
|
||||
font: var(--t-4) / 1.45 var(--font-mono);
|
||||
color: var(--ink);
|
||||
word-break: break-word;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
The small-caps label, ONCE.
|
||||
|
||||
It is the small tag that says "this thing here is X": a column header, a panel
|
||||
title, the name of a group of fields. It was written in fourteen places with three
|
||||
sizes (`--t-1`, `--t-2`, `--t-3`) and four letter-spacings (.04, .05, .07 and
|
||||
.09 em), so two neighbouring panels did not look alike and table headers did not
|
||||
look like block titles, despite being the same thing: the label of a box.
|
||||
|
||||
The values are the ones the tokens file already stated: `--t-1` is defined as
|
||||
"small-caps label, table header, pill", and that was exactly what the table header
|
||||
was NOT using. The letter-spacing is the one that repeated most (.05em, in seven
|
||||
of the fourteen).
|
||||
|
||||
It is applied with `composes:`, not by copying it.
|
||||
*/
|
||||
.smallCaps {
|
||||
font-size: var(--text-size);
|
||||
font-weight: var(--text-weight);
|
||||
letter-spacing: var(--text-tracking);
|
||||
text-transform: uppercase;
|
||||
color: var(--mute);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
The row of a selectable side list: the zones and lists tree, and the Logs files.
|
||||
It is clickable, it highlights on hover, and one of them is the one being viewed.
|
||||
|
||||
It was written twice. The STATES matched byte for byte (the same `--hover-strong`
|
||||
on hover, the same `--pan2` and `--acc` on the current one), so they were just two
|
||||
places to touch the same thing. The density did NOT match, and that one is a real
|
||||
decision: the tree is a hierarchy of many nodes and reads better tight; the file
|
||||
list is four entries. It splits into `.row` and `.compact`, which is naming the
|
||||
difference instead of leaving it hidden in two paddings.
|
||||
*/
|
||||
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--s-5);
|
||||
width: 100%;
|
||||
padding: var(--s-5) var(--s-7);
|
||||
border: 0;
|
||||
border-radius: var(--r-2);
|
||||
background: transparent;
|
||||
color: var(--mute);
|
||||
line-height: 1.3;
|
||||
font-size: var(--t-4);
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
/* The tree: same row, less air, because there are many and they nest. */
|
||||
.compact {
|
||||
composes: row;
|
||||
gap: var(--s-4);
|
||||
padding: var(--s-3) var(--s-4);
|
||||
}
|
||||
|
||||
.row:hover { background: var(--hover-strong); color: var(--ink); }
|
||||
.row[aria-current='true'] { background: var(--pan2); color: var(--acc-ink); font-weight: 550; }
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
The cells of a DNS records table. Zones uses them (a zone's records) and the
|
||||
lists screens too (the Allowed and Blocked entries), which are the same table
|
||||
looking at two different places, and each had them written twice.
|
||||
|
||||
They are cells and not components because the markup changes (a `<td>`, a `<dd>`,
|
||||
a `<span>` inside a compound value); what does not change, and must not, is how
|
||||
they read.
|
||||
*/
|
||||
|
||||
/* The TTL: monospaced and unbroken, with its unit muted beside it. */
|
||||
.ttl {
|
||||
composes: mono from './text.module.css';
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.ttl small { color: var(--faint); }
|
||||
|
||||
/* A public key or a hex string: it breaks by characters, not by words, because
|
||||
it has none. */
|
||||
.key {
|
||||
word-break: break-all;
|
||||
color: var(--mute);
|
||||
}
|
||||
|
||||
/*
|
||||
"show full", the button that expands that key. It sat inside a truncated key and
|
||||
measured 62×17 in one place and 44×18 in another: two sizes for the same control,
|
||||
and both below the 24 minimum. `.hitArea` enlarges the target without moving the
|
||||
drawing. And `nowrap`: the key preceding it breaks, the button does NOT.
|
||||
*/
|
||||
.showIt {
|
||||
composes: hitArea from './interaction.module.css';
|
||||
border: 0;
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
font: inherit;
|
||||
font-size: var(--t-3);
|
||||
color: var(--acc-ink);
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* The detail line under a record's value. */
|
||||
.meta {
|
||||
margin-top: var(--s-4);
|
||||
font-size: var(--t-2);
|
||||
color: var(--faint);
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
/*
|
||||
The console's text primitives.
|
||||
|
||||
They are not components: they are treatments that appear inside the prose of many
|
||||
screens (a muted suffix, an intro paragraph, an inline `<code>`) and which
|
||||
therefore have no element of their own to live in. Each screen used to rewrite
|
||||
them, and the copying showed: the monospacing in "My Profile" had lost its tabular
|
||||
figures and was one step smaller than everywhere else, and the "Forgot Password"
|
||||
paragraph ran at 1.65 line-height against 1.6 in the other four. Nobody decided
|
||||
either of those; they came out of typing the same thing six times.
|
||||
*/
|
||||
|
||||
/* Figures and text read character by character: IPs, domains, counters.
|
||||
`tabular-nums` is what stops a column of numbers from dancing. */
|
||||
.mono {
|
||||
font-family: var(--font-mono);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* The paragraph that opens a screen or a block and says what it is about. */
|
||||
.paragraph {
|
||||
margin: 0 0 var(--s-7);
|
||||
font-size: var(--t-4);
|
||||
color: var(--mute);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.paragraph b { color: var(--ink); }
|
||||
|
||||
/* The suffix that follows a control: "seconds", "MB", "(0 to disable)". */
|
||||
.trailer {
|
||||
font-size: var(--t-3);
|
||||
color: var(--mute);
|
||||
}
|
||||
|
||||
/*
|
||||
The inline `<code>`. It goes as a `composes` on the block of text containing it,
|
||||
not on the `<code>`, because what writes it is the prose: `{'…'} <code>x</code>`.
|
||||
*/
|
||||
.withCode code,
|
||||
.paragraph code,
|
||||
.helpPanel code {
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--t-2);
|
||||
background: var(--field);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--r-1);
|
||||
padding: 0 var(--s-2);
|
||||
}
|
||||
|
||||
/* The help paragraph inside a panel: smaller and carrying the body inset, so it
|
||||
does not compete with the setting it accompanies. */
|
||||
.helpPanel {
|
||||
font-size: var(--t-3);
|
||||
color: var(--mute);
|
||||
line-height: 1.55;
|
||||
max-width: 860px;
|
||||
}
|
||||
|
||||
/*
|
||||
The muted monospace annotation. There are two sizes and the difference is real,
|
||||
so both get named instead of being merged: `.annotation` is content you have to be
|
||||
able to read (the server domain, an app class path, a session's user agent);
|
||||
`.annotationQuiet` accompanies something else and must not compete with it (a
|
||||
tile's unit, a file's size).
|
||||
|
||||
They were written across six modules, with the two sizes handed out at random.
|
||||
*/
|
||||
.annotation {
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--t-3);
|
||||
color: var(--faint);
|
||||
}
|
||||
|
||||
.annotationQuiet {
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--t-2);
|
||||
color: var(--faint);
|
||||
}
|
||||
|
||||
/* A line that does not fit and is cut with an ellipsis. */
|
||||
.truncated {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/*
|
||||
The name that is only for whoever cannot see the screen.
|
||||
|
||||
It was born in `Matrix.module.css` for the permission cells, with a note saying
|
||||
"it goes here because this is its only user; the day a second one appears it
|
||||
moves". That day is this one: the update dialog needs it to say which of its two
|
||||
version numbers is which.
|
||||
|
||||
`position: absolute` and `clip-path`, and the caveat that cost a measured defect:
|
||||
**`clip-path` clips the PAINTING, not the layout**. With no positioned ancestor
|
||||
the containing block is the page, so whoever uses it inside something that scrolls
|
||||
has to give that container `position: relative`, or the hidden text pushes the
|
||||
page sideways. Measured at 390 on `/admin/permissions/`: 948 px of horizontal
|
||||
scroll with every visible element inside 390.
|
||||
*/
|
||||
.sr {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip-path: inset(50%);
|
||||
white-space: nowrap;
|
||||
border: 0;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
The five semantic tones: background, border and text for each.
|
||||
|
||||
Two components apply them, the alert (`ui/Alert`) and the pill (`ui/Tag`), and they
|
||||
were written in both, with different names for the same thing
|
||||
(`success/warning/danger` against `ok/warn/dan`). Twelve declarations for four
|
||||
decisions, and adding a fifth tone meant remembering both files.
|
||||
|
||||
The fifth WITH A CLASS (`acc`) arrived on 2026-09-03 with the pill that names the
|
||||
master switch. Fifth here and sixth in `Tag`, which is no contradiction: `neutral`
|
||||
is a tone of the component and has no class in this file.
|
||||
|
||||
Only `Tag` uses it: a notice in accent amber would be a `Warning!` that warns of
|
||||
nothing. And against `warn` it is not distinguishable (ΔE00 8.8 on the text and
|
||||
0.0 on the fill, below the project's own collision threshold): the separation is
|
||||
one of MEANING, not of colour, and `tokens.css` has it measured and reasoned.
|
||||
*/
|
||||
|
||||
.ok { background: var(--ok-bg); border-color: var(--ok-bd); color: var(--ok); }
|
||||
.info { background: var(--info-bg); border-color: var(--info-bd); color: var(--info); }
|
||||
.warn { background: var(--warn-bg); border-color: var(--warn-bd); color: var(--warn); }
|
||||
.dan { background: var(--dan-bg); border-color: var(--dan-bd); color: var(--dan); }
|
||||
.acc { background: var(--acc-bg); border-color: var(--acc-bd); color: var(--acc-ink); }
|
||||
@@ -0,0 +1,80 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { place, type Rect } from './tooltip-place'
|
||||
|
||||
/*
|
||||
These tests do NOT depend on jsdom, and that is the reason the arithmetic was
|
||||
taken out of the component: with a fake layout (every rect at zero) it is
|
||||
impossible to check that the bubble does not go off screen, which is exactly the
|
||||
defect it had. Numbers go in and numbers come out.
|
||||
|
||||
The case that rules is 390: it is the narrow width the designs draw, and
|
||||
where a 240 px bubble beside a control almost never fits any more.
|
||||
*/
|
||||
const v = (width: number, height: number): Rect => ({ top: 0, left: 0, width, height })
|
||||
const r = (left: number, top: number, width = 32, height = 32): Rect => ({ left, top, width, height })
|
||||
const bubble = (width = 240, height = 40): Rect => ({ left: 0, top: 0, width, height })
|
||||
|
||||
describe('place', () => {
|
||||
it('to the right, centred on the trigger', () => {
|
||||
const p = place({ trigger: r(100, 300), bubble: bubble(), viewport: v(1440, 900) })
|
||||
expect(p.placement).toBe('right')
|
||||
expect(p.left).toBe(140) // 100 + 32 + 8
|
||||
expect(p.top).toBe(300 + 16 - 20) // the trigger centre minus half a bubble
|
||||
})
|
||||
|
||||
/* The rail case at 1440: there is room to spare and it must not move. */
|
||||
it('it does not flip when it fits', () => {
|
||||
const p = place({ trigger: r(60, 200), bubble: bubble(), viewport: v(1440, 900) })
|
||||
expect(p.placement).toBe('right')
|
||||
})
|
||||
|
||||
it('it flips left when it does not fit on the right', () => {
|
||||
/* Trigger flush against the right edge of 1440. */
|
||||
const p = place({ trigger: r(1380, 300), bubble: bubble(), viewport: v(1440, 900) })
|
||||
expect(p.placement).toBe('left')
|
||||
expect(p.left).toBe(1380 - 8 - 240)
|
||||
})
|
||||
|
||||
it('it flips from top to bottom when it does not fit above', () => {
|
||||
const p = place({ trigger: r(600, 10), bubble: bubble(), viewport: v(1440, 900), placement: 'top' })
|
||||
expect(p.placement).toBe('bottom')
|
||||
expect(p.top).toBe(10 + 32 + 8)
|
||||
})
|
||||
|
||||
/*
|
||||
390. A 240 bubble does not fit to the right of almost anything, and flipped to
|
||||
the left it does not either: so it is not flipped to a place just as bad, it is
|
||||
clamped. What must NOT happen is that it goes off screen.
|
||||
*/
|
||||
it('at 390 it never goes off screen, on the right or on the left', () => {
|
||||
for (const x of [0, 8, 40, 120, 200, 300, 358]) {
|
||||
const p = place({ trigger: r(x, 300), bubble: bubble(), viewport: v(390, 844) })
|
||||
expect(p.left, `trigger at x=${x}`).toBeGreaterThanOrEqual(8)
|
||||
expect(p.left + 240, `trigger at x=${x}`).toBeLessThanOrEqual(390 - 8)
|
||||
}
|
||||
})
|
||||
|
||||
it('it does not flip to a place just as bad', () => {
|
||||
/* At 390 with a 240 bubble it fits on neither side: it stays where it was
|
||||
asked for and is clamped, instead of jumping from one edge to the other. */
|
||||
const p = place({ trigger: r(180, 300), bubble: bubble(), viewport: v(390, 844) })
|
||||
expect(p.placement).toBe('right')
|
||||
})
|
||||
|
||||
it('it clamps the cross axis too: a tall bubble by the top edge', () => {
|
||||
const p = place({ trigger: r(100, 4), bubble: bubble(240, 120), viewport: v(1440, 900) })
|
||||
expect(p.top).toBe(8) // centring would have put it negative
|
||||
})
|
||||
|
||||
it('and by the bottom edge', () => {
|
||||
const p = place({ trigger: r(100, 880), bubble: bubble(240, 120), viewport: v(1440, 900) })
|
||||
expect(p.top).toBe(900 - 8 - 120)
|
||||
})
|
||||
|
||||
/* Taller than the screen: it is cut off at the bottom, where there is scroll,
|
||||
and not at the top, where there is none. */
|
||||
it('a bubble taller than the viewport starts at the margin', () => {
|
||||
const p = place({ trigger: r(100, 300), bubble: bubble(240, 2000), viewport: v(1440, 900) })
|
||||
expect(p.top).toBe(8)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,108 @@
|
||||
/*
|
||||
Where the bubble goes. A pure function on purpose.
|
||||
|
||||
It lived inside `Tooltip` as four lines of arithmetic plus a CSS `transform`, and
|
||||
that combination could not be tested: jsdom has no layout, so every rect is zeros,
|
||||
and the half that decided the real position was a `translate()` in a stylesheet.
|
||||
The result was a tooltip that walked off the screen at 390 px and near any edge,
|
||||
with nothing to catch it.
|
||||
|
||||
So the arithmetic comes out here, takes numbers and returns numbers, and the
|
||||
stylesheet no longer decides anything: **there is no `transform`**. The component
|
||||
just paints `top` and `left`.
|
||||
|
||||
Three jobs, in this order, and the order matters:
|
||||
|
||||
1. **Place** it on the asked-for side.
|
||||
2. **Flip** it to the opposite side if that side does not fit. Flipping beats
|
||||
clamping here: a bubble squashed against the right edge covers the very
|
||||
control it describes.
|
||||
3. **Clamp** whatever is left into the viewport, with a margin. After a flip
|
||||
there can still be overflow on the other axis (a tall bubble beside a
|
||||
control at the top of the screen), and that is what clamping is for.
|
||||
|
||||
`margin` is not decoration: at 390 px a bubble flush against the edge reads as
|
||||
cut off, and the console's own gutter is 8.
|
||||
*/
|
||||
|
||||
export interface Rect {
|
||||
top: number
|
||||
left: number
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
|
||||
export type Placement = 'right' | 'left' | 'top' | 'bottom'
|
||||
|
||||
export interface Placed {
|
||||
top: number
|
||||
left: number
|
||||
/** Where it ACTUALLY ended up. It may not be what was asked for. */
|
||||
placement: Placement
|
||||
}
|
||||
|
||||
const opposite: Record<Placement, Placement> = {
|
||||
right: 'left',
|
||||
left: 'right',
|
||||
top: 'bottom',
|
||||
bottom: 'top',
|
||||
}
|
||||
|
||||
/** Top-left corner of the bubble for a given side, with no clamping yet. */
|
||||
function corner(t: Rect, b: Rect, side: Placement, gap: number): { top: number; left: number } {
|
||||
switch (side) {
|
||||
case 'right':
|
||||
return { left: t.left + t.width + gap, top: t.top + t.height / 2 - b.height / 2 }
|
||||
case 'left':
|
||||
return { left: t.left - gap - b.width, top: t.top + t.height / 2 - b.height / 2 }
|
||||
case 'top':
|
||||
return { left: t.left + t.width / 2 - b.width / 2, top: t.top - gap - b.height }
|
||||
case 'bottom':
|
||||
return { left: t.left + t.width / 2 - b.width / 2, top: t.top + t.height + gap }
|
||||
}
|
||||
}
|
||||
|
||||
/** Does this corner keep the bubble fully inside, on the axis the side moves along? */
|
||||
function fits(c: { top: number; left: number }, b: Rect, v: Rect, side: Placement, margin: number) {
|
||||
return side === 'right' || side === 'left'
|
||||
? c.left >= margin && c.left + b.width <= v.width - margin
|
||||
: c.top >= margin && c.top + b.height <= v.height - margin
|
||||
}
|
||||
|
||||
export function place({
|
||||
trigger,
|
||||
bubble,
|
||||
viewport,
|
||||
placement = 'right',
|
||||
gap = 8,
|
||||
margin = 8,
|
||||
}: {
|
||||
trigger: Rect
|
||||
bubble: Rect
|
||||
viewport: Rect
|
||||
placement?: Placement
|
||||
gap?: number
|
||||
margin?: number
|
||||
}): Placed {
|
||||
let side = placement
|
||||
let c = corner(trigger, bubble, side, gap)
|
||||
|
||||
/* Flip only if the other side is genuinely better: flipping into an equally bad
|
||||
spot just moves the problem and makes the bubble jump around as you scroll. */
|
||||
if (!fits(c, bubble, viewport, side, margin)) {
|
||||
const other = opposite[side]
|
||||
const alt = corner(trigger, bubble, other, gap)
|
||||
if (fits(alt, bubble, viewport, other, margin)) {
|
||||
side = other
|
||||
c = alt
|
||||
}
|
||||
}
|
||||
|
||||
/* And clamp both axes regardless. `Math.max` last so that a bubble taller than
|
||||
the viewport starts at the margin instead of at a negative offset: better cut
|
||||
off at the bottom, where there is scroll, than at the top, where there is not. */
|
||||
const left = Math.max(margin, Math.min(c.left, viewport.width - margin - bubble.width))
|
||||
const top = Math.max(margin, Math.min(c.top, viewport.height - margin - bubble.height))
|
||||
|
||||
return { top, left, placement: side }
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { act, render, screen } from '@testing-library/react'
|
||||
import { useSectionInView } from './useSectionInView'
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
/** An IntersectionObserver the test drives by hand. */
|
||||
function fakeObserver() {
|
||||
const made: { fire: (ids: [string, boolean][]) => void; observed: string[] }[] = []
|
||||
class Fake {
|
||||
observed: string[] = []
|
||||
constructor(cb: IntersectionObserverCallback) {
|
||||
const fire = (ids: [string, boolean][]) =>
|
||||
cb(
|
||||
ids.map(([id, on]) => ({ target: document.getElementById(id)!, isIntersecting: on }) as unknown as IntersectionObserverEntry),
|
||||
this as unknown as IntersectionObserver,
|
||||
)
|
||||
made.push({ observed: this.observed, fire })
|
||||
}
|
||||
observe(el: Element) { this.observed.push(el.id) }
|
||||
disconnect() {}
|
||||
}
|
||||
vi.stubGlobal('IntersectionObserver', Fake)
|
||||
return made
|
||||
}
|
||||
|
||||
function Page({ ids }: { ids: string[] }) {
|
||||
const here = useSectionInView(ids)
|
||||
return (
|
||||
<>
|
||||
{ids.map((id) => <div key={id} id={id} />)}
|
||||
<output>{here ?? 'none'}</output>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
describe('useSectionInView', () => {
|
||||
it('observes the sections by id and answers the topmost one on screen', () => {
|
||||
const made = fakeObserver()
|
||||
render(<Page ids={['a', 'b', 'c']} />)
|
||||
expect(made[0].observed).toEqual(['a', 'b', 'c'])
|
||||
act(() => made[0].fire([['b', true], ['c', true]]))
|
||||
expect(screen.getByRole('status')).toHaveTextContent('b')
|
||||
act(() => made[0].fire([['b', false]]))
|
||||
expect(screen.getByRole('status')).toHaveTextContent('c')
|
||||
})
|
||||
|
||||
it('a section that left the list is nowhere, and a new array of the same ids observes nothing new', () => {
|
||||
const made = fakeObserver()
|
||||
const { rerender } = render(<Page ids={['a', 'b']} />)
|
||||
act(() => made[0].fire([['a', true]]))
|
||||
rerender(<Page ids={['a', 'b']} />)
|
||||
expect(made).toHaveLength(1)
|
||||
rerender(<Page ids={['x', 'y']} />)
|
||||
expect(screen.getByRole('status')).toHaveTextContent('none')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,49 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
/*
|
||||
Which section of a long screen you are looking at, for `ui/SectionIndex`'s `active`.
|
||||
|
||||
`SectionIndex` deliberately does not watch the scroll: working out the active
|
||||
entry is wiring of the screen that draws the sections, and the primitive stays
|
||||
testable without one. This hook is that wiring, written once. Administration ›
|
||||
Permissions wired it first, inline; Settings needed the same lines, and two copies
|
||||
of an observer drift the way two copies of a style did.
|
||||
|
||||
It takes the ids of the sections in page order and finds them in the document, so
|
||||
the screen only has to give each section box its `id`, which the index's links
|
||||
need anyway. An empty list observes nothing and answers `undefined`.
|
||||
*/
|
||||
export function useSectionInView(ids: readonly string[]): string | undefined {
|
||||
const [here, setHere] = useState<string | undefined>(undefined)
|
||||
/* The ids, as a value: a new array with the same ids is not a new list. */
|
||||
const key = ids.join('\n')
|
||||
|
||||
useEffect(() => {
|
||||
const order = key === '' ? [] : key.split('\n')
|
||||
const boxes = order.map((id) => document.getElementById(id)).filter((e): e is HTMLElement => e != null)
|
||||
if (boxes.length === 0) return
|
||||
const seen = new Set<string>()
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
for (const e of entries) {
|
||||
if (e.isIntersecting) seen.add(e.target.id)
|
||||
else seen.delete(e.target.id)
|
||||
}
|
||||
// The topmost one that is on screen: with ten sections several are, and
|
||||
// marking the last would say you are further down than you are.
|
||||
setHere(order.find((id) => seen.has(id)))
|
||||
},
|
||||
// The band a section has to cross to count: below the top 120 px and above
|
||||
// the bottom 60 % of the window, the part the eye is on. 120 and not the 72 it
|
||||
// was: on a phone the top bar and the pinned strip take 93 px, and a jump lands
|
||||
// a section 14 px below them, so with 72 the section ABOVE it still counted
|
||||
// and the strip marked the wrong entry (measured at 390, 2026-10-16).
|
||||
{ rootMargin: '-120px 0px -60% 0px' },
|
||||
)
|
||||
for (const el of boxes) observer.observe(el)
|
||||
return () => observer.disconnect()
|
||||
}, [key])
|
||||
|
||||
// A section that has left the list (another pane, another page) is nowhere.
|
||||
return here != null && ids.includes(here) ? here : undefined
|
||||
}
|
||||
Reference in new issue
Block a user