test(webui): visual harness and Workbench table widgets

This commit is contained in:
2026-11-25 11:52:36 +00:00
parent 5177b2209c
commit 0ef0894140
18 changed files with 598 additions and 5 deletions
+4
View File
@@ -22,3 +22,7 @@ dist-ssr
*.njsproj
*.sln
*.sw?
# Playwright visual harness output
.screenshots/
test-results/
+127
View File
@@ -0,0 +1,127 @@
import AxeBuilder from '@axe-core/playwright'
import type { Page } from '@playwright/test'
export interface CheckResult {
name: CheckName
ok: boolean
detail: string
}
export const CHECK_NAMES = [
'noConsoleErrors',
'noHorizontalOverflow',
'headerAlignsWithBody',
'numbersRightAligned',
'focusRingVisible',
'axeNoSeriousOrCritical',
'no-literal-NaN-undefined',
] as const
export type CheckName = (typeof CHECK_NAMES)[number]
const ALIGN_TOLERANCE_PX = 1
const FOCUS_TRANSITION_MS = 300
const LITERAL_RE = /\bNaN\b|undefined/
/** Console errors and uncaught page errors seen since the collector was attached. */
export function collectConsoleErrors(page: Page, ignore: RegExp[] = []): () => string[] {
const errors: string[] = []
page.on('console', (m) => {
if (m.type() === 'error' && !ignore.some((re) => re.test(m.text()))) errors.push(m.text())
})
page.on('pageerror', (e) => errors.push(`pageerror: ${e.message}`))
return () => errors
}
export function noConsoleErrors(errors: string[]): CheckResult {
return { name: 'noConsoleErrors', ok: errors.length === 0, detail: errors.slice(0, 3).join(' | ') }
}
export async function noHorizontalOverflow(page: Page): Promise<CheckResult> {
const { sw, iw } = await page.evaluate(() => ({ sw: document.documentElement.scrollWidth, iw: window.innerWidth }))
return { name: 'noHorizontalOverflow', ok: sw <= iw, detail: `scrollWidth ${sw} > innerWidth ${iw}` }
}
export async function headerAlignsWithBody(page: Page): Promise<CheckResult> {
const bad = await page.evaluate((tol) => {
const out: string[] = []
document.querySelectorAll('table').forEach((table, ti) => {
const ths = Array.from(table.querySelectorAll('thead th'))
const row = table.querySelector('tbody tr')
if (!ths.length || !row) return
const cells = Array.from(row.children)
ths.forEach((th, i) => {
const td = cells[i]
const a = th.getBoundingClientRect()
const b = td?.getBoundingClientRect()
if (!b || a.width === 0 || b.width === 0) return
if (Math.abs(a.left - b.left) > tol) out.push(`table ${ti} col ${i} header ${a.left.toFixed(1)} body ${b.left.toFixed(1)}`)
})
})
return out
}, ALIGN_TOLERANCE_PX)
return { name: 'headerAlignsWithBody', ok: bad.length === 0, detail: bad.slice(0, 3).join(' | ') }
}
export async function numbersRightAligned(page: Page): Promise<CheckResult> {
const { total, bad } = await page.evaluate(() => {
const cells = Array.from(document.querySelectorAll('[data-numeric]'))
const wrong = cells.filter((el) => !['right', 'end'].includes(getComputedStyle(el).textAlign))
return { total: cells.length, bad: wrong.length }
})
return { name: 'numbersRightAligned', ok: bad === 0, detail: `${bad} of ${total} [data-numeric] cells not right aligned` }
}
// perfect-design draws its focus ring as a box-shadow spread with `outline-style: none`; a ring is
// a layer with zero offset and blur, a spread above 0 and a non-transparent colour.
const RING_LAYER_RE = /(rgba?\([^)]*\)|oklab\([^)]*\)|oklch\([^)]*\)|color\([^)]*\)|#[0-9a-f]+)\s+0px\s+0px\s+0px\s+([\d.]+)px/g
export async function focusRingVisible(page: Page): Promise<CheckResult> {
await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur())
await page.keyboard.press('Tab')
await page.waitForTimeout(FOCUS_TRANSITION_MS)
const info = await page.evaluate(() => {
const el = document.activeElement
if (!el || el === document.body) return null
const cs = getComputedStyle(el)
return { tag: el.tagName.toLowerCase(), width: parseFloat(cs.outlineWidth) || 0, style: cs.outlineStyle, shadow: cs.boxShadow }
})
if (!info) return { name: 'focusRingVisible', ok: false, detail: 'Tab focused nothing' }
const outline = info.width > 0 && info.style !== 'none'
const ring = Array.from(info.shadow.matchAll(RING_LAYER_RE)).some(
(m) => parseFloat(m[2]) > 0 && !/rgba\(0, 0, 0, 0\)|\/ 0\)/.test(m[1]),
)
return { name: 'focusRingVisible', ok: outline || ring, detail: `${info.tag} outline ${info.width}px ${info.style}, ring ${ring}` }
}
export async function axeNoSeriousOrCritical(page: Page): Promise<CheckResult> {
const { violations } = await new AxeBuilder({ page }).analyze()
const bad = violations.filter((v) => v.impact === 'serious' || v.impact === 'critical')
return { name: 'axeNoSeriousOrCritical', ok: bad.length === 0, detail: bad.map((v) => `${v.id}(${v.nodes.length})`).join(', ') }
}
export async function noLiteralNaNUndefined(page: Page): Promise<CheckResult> {
const text = await page.evaluate(() => document.body.innerText)
const m = LITERAL_RE.exec(text)
const ctx = m ? text.slice(Math.max(0, m.index - 30), m.index + 30).replace(/\s+/g, ' ') : ''
return { name: 'no-literal-NaN-undefined', ok: !m, detail: ctx }
}
async function guarded(name: CheckName, run: () => Promise<CheckResult>): Promise<CheckResult> {
try {
return await run()
} catch (e) {
return { name, ok: false, detail: `check threw: ${(e as Error).message.split('\n')[0]}` }
}
}
export async function runChecks(page: Page, consoleErrors: string[]): Promise<CheckResult[]> {
return [
noConsoleErrors(consoleErrors),
await guarded('noHorizontalOverflow', () => noHorizontalOverflow(page)),
await guarded('headerAlignsWithBody', () => headerAlignsWithBody(page)),
await guarded('numbersRightAligned', () => numbersRightAligned(page)),
await guarded('axeNoSeriousOrCritical', () => axeNoSeriousOrCritical(page)),
await guarded('no-literal-NaN-undefined', () => noLiteralNaNUndefined(page)),
await guarded('focusRingVisible', () => focusRingVisible(page)),
]
}
+90
View File
@@ -0,0 +1,90 @@
import { mkdirSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { expect, test } from '@playwright/test'
import type { Page } from '@playwright/test'
import { PAGE_IDS } from '../src/lib/pages'
import { collectConsoleErrors, runChecks } from './checks'
const SCENARIOS = ['live', 'empty', 'limits-hot', 'breaker-open', 'redis-down', 'auth-401', 'huge'] as const
const VIEWPORTS = {
desktop: { width: 1440, height: 900 },
phone: { width: 390, height: 844 },
} as const
const THEMES = ['light', 'dark'] as const
const KEY_STORAGE = 'llmgwAdminKey'
const OUT = join(import.meta.dirname, '..', '.screenshots')
const SETTLE_MS = 600
// Chromium logs every 401 fetch as a console error; auth-401 forces one by design.
const AUTH_401_NOISE = /Failed to load resource.*status of 40[13]/
async function sampleIds(page: Page): Promise<Record<string, string>> {
const key = { 'x-api-key': 'e2e-dummy-key' }
const get = async (path: string) => (await page.request.get(`/admin/api/${path}`, { headers: key })).json()
const [usage, catalog, targets] = await Promise.all([get('usage'), get('catalog'), get('targets')])
return {
user: `user:${encodeURIComponent(usage.users[0].id)}`,
model: `model:${encodeURIComponent(catalog.providers[0].models[0].id)}`,
router: `router:${encodeURIComponent(catalog.routers[0].name)}`,
target: `target:${encodeURIComponent((targets.mcpServers[0] ?? targets.agents[0]).name)}`,
}
}
const PANEL_PAGES: Array<{ page: (typeof PAGE_IDS)[number]; kind: string }> = [
{ page: 'users', kind: 'user' },
{ page: 'models', kind: 'model' },
{ page: 'routers', kind: 'router' },
{ page: 'targets', kind: 'target' },
]
async function visit(page: Page, hash: string, scenario: string, theme: string): Promise<void> {
await page.addInitScript(
([k, t]) => {
sessionStorage.setItem(k, 'e2e-dummy-key')
localStorage.setItem('pd-theme', JSON.stringify({ mode: t }))
},
[KEY_STORAGE, theme],
)
await page.emulateMedia({ colorScheme: theme as 'light' | 'dark' })
await page.goto(`/admin/?mock=${scenario}${hash}`)
await page.waitForLoadState('networkidle').catch(() => undefined)
await page.waitForTimeout(SETTLE_MS)
}
async function exercise(page: Page, label: string, hash: string, scenario: string, viewport: keyof typeof VIEWPORTS, theme: string): Promise<void> {
const errors = collectConsoleErrors(page, scenario === 'auth-401' ? [AUTH_401_NOISE] : [])
await visit(page, hash, scenario, theme)
mkdirSync(OUT, { recursive: true })
const name = `${label}-${scenario}-${viewport}-${theme}`
await page.screenshot({ path: join(OUT, `${name}.png`), fullPage: true })
const results = await runChecks(page, errors())
mkdirSync(join(OUT, 'results'), { recursive: true })
writeFileSync(join(OUT, 'results', `${name}.json`), JSON.stringify({ label, scenario, viewport, theme, results }))
for (const r of results) expect.soft(r.ok, `${r.name}: ${r.detail}`).toBe(true)
}
for (const id of PAGE_IDS) {
for (const scenario of SCENARIOS) {
for (const [vp, size] of Object.entries(VIEWPORTS)) {
for (const theme of THEMES) {
test(`${id} ${scenario} ${vp} ${theme}`, async ({ page }) => {
await page.setViewportSize(size)
await exercise(page, id, `#${id}`, scenario, vp as keyof typeof VIEWPORTS, theme)
})
}
}
}
}
for (const { page: pageId, kind } of PANEL_PAGES) {
for (const [vp, size] of Object.entries(VIEWPORTS)) {
for (const theme of THEMES) {
test(`${pageId} panel ${kind} live ${vp} ${theme}`, async ({ page }) => {
await page.setViewportSize(size)
const sel = (await sampleIds(page))[kind]
await exercise(page, `${pageId}-panel-${kind}`, `#${pageId}?sel=${encodeURIComponent(sel)}`, 'live', vp as keyof typeof VIEWPORTS, theme)
})
}
}
}
+73
View File
@@ -27,6 +27,8 @@
"vue-chartjs": "^5.3.4"
},
"devDependencies": {
"@axe-core/playwright": "^4.14.1",
"@playwright/test": "^1.65.1",
"@tailwindcss/vite": "^4.3.3",
"@types/node": "^24.13.3",
"@vitejs/plugin-vue": "^6.0.8",
@@ -38,6 +40,22 @@
"vue-tsc": "^3.3.8"
}
},
"node_modules/@axe-core/playwright": {
"version": "4.14.1",
"resolved": "http://gohoarder.h.raczylo.com/npm/@axe-core/playwright/-/playwright-4.14.1.tgz",
"integrity": "sha512-cSN1ijrWLnlOof22sPN4RtWGSoPpt7GzOVyOKomyhnPsy1fPNoRdBiJAUziuCRs8KoK50kKufiMUFt7itAuwOg==",
"dev": true,
"license": "MPL-2.0",
"dependencies": {
"axe-core": "~4.14.1"
},
"engines": {
"node": ">=22.12.0"
},
"peerDependencies": {
"playwright-core": ">= 1.0.0"
}
},
"node_modules/@babel/code-frame": {
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",
@@ -979,6 +997,22 @@
"vue": "^3.5.0"
}
},
"node_modules/@playwright/test": {
"version": "1.65.1",
"resolved": "http://gohoarder.h.raczylo.com/npm/@playwright/test/-/test-1.65.1.tgz",
"integrity": "sha512-y+NCIRm2LvY4slUVWvGh1nujJ8RF/hEisIsq2mtUPgdQC4L701bq5hZGMhrpeXjACvwvO9tj5dJqhvM6TP9lbw==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright": "1.65.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/@rolldown/binding-android-arm-eabi": {
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.5.tgz",
@@ -2565,6 +2599,16 @@
"node": ">= 4.5.0"
}
},
"node_modules/axe-core": {
"version": "4.14.1",
"resolved": "http://gohoarder.h.raczylo.com/npm/axe-core/-/axe-core-4.14.1.tgz",
"integrity": "sha512-FHfa+lmNjQZfJz1q8wKqIDwC6DExcHt/pkjNQb09a3NPjCKg2rhu5qb2S4r76ASyFNNtuFooJpZe37OgudVGtQ==",
"dev": true,
"license": "MPL-2.0",
"engines": {
"node": ">=4"
}
},
"node_modules/balanced-match": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
@@ -5666,6 +5710,35 @@
"pathe": "^2.0.3"
}
},
"node_modules/playwright": {
"version": "1.65.1",
"resolved": "http://gohoarder.h.raczylo.com/npm/playwright/-/playwright-1.65.1.tgz",
"integrity": "sha512-vJ1FuoOrNwOKHUIVEvSt3jT1L+wjjDpwhwIstKtfvTh8XIG4FG4bIFuvNdMxi81LGfAhUgUZleVFaOLY4RIUUw==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.65.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/playwright-core": {
"version": "1.65.1",
"resolved": "http://gohoarder.h.raczylo.com/npm/playwright-core/-/playwright-core-1.65.1.tgz",
"integrity": "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/postcss": {
"version": "8.5.26",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz",
+4 -1
View File
@@ -8,7 +8,8 @@
"dev:mock": "MOCK=1 vite",
"build": "vue-tsc -b && vite build",
"preview": "vite preview",
"test": "vitest run"
"test": "vitest run",
"test:visual": "playwright test"
},
"dependencies": {
"@fortawesome/fontawesome-svg-core": "^7.3.1",
@@ -30,6 +31,8 @@
"vue-chartjs": "^5.3.4"
},
"devDependencies": {
"@axe-core/playwright": "^4.14.1",
"@playwright/test": "^1.65.1",
"@tailwindcss/vite": "^4.3.3",
"@types/node": "^24.13.3",
"@vitejs/plugin-vue": "^6.0.8",
+20
View File
@@ -0,0 +1,20 @@
import { defineConfig } from '@playwright/test'
const PORT = 5199
export default defineConfig({
testDir: './e2e',
testMatch: '*.spec.ts',
outputDir: '.screenshots/.pw-output',
fullyParallel: true,
workers: 4,
timeout: 120_000,
reporter: [['list']],
use: { baseURL: `http://localhost:${PORT}`, browserName: 'chromium' },
webServer: {
command: `npm run dev:mock -- --port ${PORT} --strictPort`,
url: `http://localhost:${PORT}/admin/`,
reuseExistingServer: !process.env.CI,
timeout: 60_000,
},
})
+10
View File
@@ -197,3 +197,13 @@
radial-gradient(farthest-side at 0 50%, oklch(0 0 0 / 0.22), transparent) 0 0 / 0.6rem 100% no-repeat scroll,
radial-gradient(farthest-side at 100% 50%, oklch(0 0 0 / 0.22), transparent) 100% 0 / 0.6rem 100% no-repeat scroll;
}
/* Workbench table: 8px grid, 12px cell inset, 32px body rows, 30px header row. */
.wb-table table { table-layout: auto; }
.wb-table :is(th, td) { padding-inline: 12px; }
.wb-table thead :is(th) { height: 30px; padding-block: 0; }
.wb-table tbody :is(td, th) { height: 32px; padding-block: 0; }
.wb-table [data-numeric] { display: block; text-align: right; font-family: var(--font-mono); font-variant-numeric: tabular-nums; line-height: 20px; }
.wb-table :is(th, td).wb-num { text-align: right; }
.wb-table th.wb-num > * { justify-content: flex-end; }
.wb-table .wb-share-bar { min-width: 96px; }
+1 -1
View File
@@ -95,7 +95,7 @@ function onRange(value: string): void {
/>
<OfflineIndicator variant="pill" />
<span v-if="dashboard.error" class="text-destructive text-xs" role="status">refresh failed</span>
<Button variant="outline" size="sm" aria-label="Open command palette" @click="emit('openPalette')">
<Button variant="outline" size="sm" aria-label="Search ⌘K" @click="emit('openPalette')">
<Icon :icon="faMagnifyingGlass" size="sm" />
<span class="hidden sm:inline">Search</span>
<Kbd>⌘K</Kbd>
+2 -2
View File
@@ -49,12 +49,12 @@ function onNavigate(item: { id?: string }, event: MouseEvent): void {
</script>
<template>
<AppShell v-model:collapsed="collapsed" v-model:open="open" drawer-breakpoint="lg" sidebar-label="Primary">
<AppShell v-model:collapsed="collapsed" v-model:open="open" drawer-breakpoint="lg" sidebar-width="lg" sidebar-label="Primary">
<template #header="{ toggle, triggerProps }">
<AppHeader :trigger-props="triggerProps" @toggle-sidebar="toggle" @open-palette="paletteOpen = true" />
</template>
<template #sidebar>
<SidebarNav v-model:collapsed="collapsed" :groups="groups" :current="nav.page" label="Primary" @navigate="onNavigate" />
<SidebarNav v-model:collapsed="collapsed" class="w-full" :groups="groups" :current="nav.page" label="Primary" @navigate="onNavigate" />
</template>
<div class="min-w-0 p-4">
<slot />
+44
View File
@@ -0,0 +1,44 @@
import { describe, expect, it } from 'vitest'
import { wbColumns } from '@/lib/wb-columns'
describe('wbColumns', () => {
it('number columns are numeric right aligned', () => {
const [col] = wbColumns([{ key: 'req', header: 'Requests', kind: 'number' }])
expect(col.numeric).toBe(true)
expect(col.align).toBe('right')
expect(col.class).toContain('wb-num')
})
it('share columns are not sortable by default', () => {
const [def, opt] = wbColumns([
{ key: 'share', header: 'Share', kind: 'share' },
{ key: 'share2', header: 'Share', kind: 'share', sortable: true },
])
expect(def.sortable).toBe(false)
expect(opt.sortable).toBe(true)
})
it('limit columns render badge slot', () => {
const [col] = wbColumns([{ key: 'limit', header: 'Limit', kind: 'limit' }])
expect(col.kind).toBe('limit')
expect(col.class).toContain('wb-limit')
expect(col.align).not.toBe('right')
})
it('text, status and time columns are left aligned; text and time sort by default', () => {
const cols = wbColumns([
{ key: 'a', header: 'A', kind: 'text' },
{ key: 'b', header: 'B', kind: 'status' },
{ key: 'c', header: 'C', kind: 'time', width: '8rem' },
])
expect(cols.map((c) => c.numeric ?? false)).toEqual([false, false, false])
expect(cols.map((c) => c.sortable)).toEqual([true, false, true])
expect(cols[2].width).toBe('8rem')
})
it('explicit sortable wins over the kind default', () => {
const [col] = wbColumns([{ key: 'a', header: 'A', kind: 'number', sortable: false }])
expect(col.sortable).toBe(false)
})
})
+45
View File
@@ -0,0 +1,45 @@
import type { DataTableColumn } from '@perfect-design/ui'
export type WbKind = 'text' | 'number' | 'share' | 'limit' | 'status' | 'time'
export interface WbColumnDef {
key: string
header: string
kind: WbKind
sortable?: boolean
width?: string
}
/** A DataTable column that remembers its Workbench kind, so WbTable can pick the cell renderer. */
export type WbColumn<T = unknown> = DataTableColumn<T> & { kind: WbKind }
const KIND_CLASS: Record<WbKind, string> = {
text: 'wb-text',
number: 'wb-num',
share: 'wb-share',
limit: 'wb-limit',
status: 'wb-status',
time: 'wb-time',
}
// Share bars and status chips carry no useful order of their own.
const UNSORTABLE_BY_DEFAULT: ReadonlySet<WbKind> = new Set(['share', 'status'])
/** Expands compact column definitions into DataTable columns with the Workbench alignment rules. */
export function wbColumns<T = unknown>(defs: WbColumnDef[]): WbColumn<T>[] {
return defs.map((d) => {
const col: WbColumn<T> = {
key: d.key,
header: d.header,
kind: d.kind,
sortable: d.sortable ?? !UNSORTABLE_BY_DEFAULT.has(d.kind),
class: KIND_CLASS[d.kind],
}
if (d.width) col.width = d.width
if (d.kind === 'number') {
col.numeric = true
col.align = 'right'
}
return col
})
}
+16
View File
@@ -91,3 +91,19 @@ describe('useNavStore panels', () => {
expect(nav.panelPushed).toBe(false)
})
})
describe('useNavStore no-op navigation', () => {
it('goTo to the identical page and params with replace:false does not leave a push pending', () => {
const nav = useNavStore()
nav.goTo('users', { q: 'a' })
nav.goTo('users', { q: 'a' }, { replace: false })
expect(nav.pushPending).toBe(false)
})
it('goTo that changes params still pushes with replace:false', () => {
const nav = useNavStore()
nav.goTo('users', { q: 'a' })
nav.goTo('users', { q: 'b' }, { replace: false })
expect(nav.pushPending).toBe(true)
})
})
+8 -1
View File
@@ -5,6 +5,11 @@ import type { PageId } from '@/lib/pages'
import { formatSel, parseSel } from '@/lib/panel-selection'
import type { PanelKind, PanelSelection } from '@/lib/panel-selection'
function sameParams(a: Record<string, string>, b: Record<string, string>): boolean {
const keys = Object.keys(a)
return keys.length === Object.keys(b).length && keys.every((k) => a[k] === b[k])
}
/**
* useNavStore is the redesign's single navigation store (redesign-plan.md
* section 3.3, replacing the old activeTab/usageQuery shape): which page
@@ -45,9 +50,11 @@ export const useNavStore = defineStore('nav', {
* one hash rewrite — composables/useHashState.ts's own watcher).
*/
goTo(page: PageId, params: Record<string, string> = {}, opts: { replace?: boolean } = {}): void {
const unchanged = this.page === page && sameParams(this.params, params)
this.page = page
this.params = params
this.pushPending = opts.replace === false
// An unchanged hash never reaches useHashState's watcher, which is what clears this flag.
this.pushPending = opts.replace === false && !unchanged
this.panelPushed = false
},
/** Opens a detail panel and pushes a history entry, so Back closes it. */
+26
View File
@@ -0,0 +1,26 @@
<script setup lang="ts">
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from '@perfect-design/ui'
import type { PanelKind } from '@/lib/panel-selection'
defineProps<{ kind: PanelKind; id: string; title: string }>()
const emit = defineEmits<{ close: [] }>()
function onOpen(open: boolean): void {
if (!open) emit('close')
}
</script>
<template>
<Sheet :open="true" @update:open="onOpen">
<SheetContent side="right" size="lg" :data-panel-kind="kind" :data-panel-id="id">
<SheetHeader>
<SheetTitle class="truncate">{{ title }}</SheetTitle>
<SheetDescription class="sr-only">{{ kind }} details for {{ title }}</SheetDescription>
</SheetHeader>
<div class="min-w-0 flex-1 overflow-y-auto">
<slot />
</div>
</SheetContent>
</Sheet>
</template>
+17
View File
@@ -0,0 +1,17 @@
<script setup lang="ts">
import { Badge } from '@perfect-design/ui'
import { computed } from 'vue'
import { formatCompactCount } from '@/lib/format'
const props = defineProps<{ limit: number | null | undefined; unit?: string; hot?: boolean }>()
const has = computed(() => typeof props.limit === 'number' && Number.isFinite(props.limit) && props.limit > 0)
const text = computed(() => (has.value ? `${formatCompactCount(props.limit as number)}${props.unit ? `/${props.unit}` : ''}` : 'none'))
</script>
<template>
<Badge class="wb-limit-badge font-mono" variant="outline" size="sm" :tone="hot ? 'danger' : 'neutral'" :data-limit="has ? 'set' : 'none'">
{{ text }}
</Badge>
</template>
+23
View File
@@ -0,0 +1,23 @@
<script setup lang="ts">
import { StatBar } from '@perfect-design/ui'
import { computed } from 'vue'
const props = withDefaults(defineProps<{ value: number | null | undefined; label?: string }>(), { label: 'Share' })
const pct = computed(() => (Number.isFinite(props.value) ? Math.min(100, Math.max(0, (props.value as number) * 100)) : null))
const text = computed(() => (pct.value === null ? '—' : `${pct.value < 10 && pct.value > 0 ? pct.value.toFixed(1) : Math.round(pct.value)}%`))
</script>
<template>
<StatBar
class="wb-share-bar"
:label="label"
:value="pct ?? 0"
:max="100"
:value-text="text"
tone="primary"
size="sm"
layout="inline"
hide-label
/>
</template>
+39
View File
@@ -0,0 +1,39 @@
<script setup lang="ts">
import { EmptyState, ErrorState, LoadingState, StaleNotice } from '@perfect-design/ui'
export type ViewState = 'loading' | 'empty' | 'error' | 'ready'
withDefaults(
defineProps<{
state: ViewState
/** Fetch time of the data on screen; a stale one shows the notice above the content. */
updatedAt?: number | string | Date | null
emptyTitle?: string
emptyDescription?: string
errorTitle?: string
errorMessage?: string
retryable?: boolean
rows?: number
}>(),
{ emptyTitle: 'Nothing here yet', errorTitle: 'Could not load data', retryable: true, rows: 5 },
)
const emit = defineEmits<{ retry: [] }>()
</script>
<template>
<LoadingState v-if="state === 'loading'" variant="table" :rows="rows" label="Loading" />
<ErrorState
v-else-if="state === 'error'"
:title="errorTitle"
:message="errorMessage"
:retryable="retryable"
@retry="emit('retry')"
/>
<EmptyState v-else-if="state === 'empty'" :title="emptyTitle" :description="emptyDescription">
<template v-if="$slots.action" #action><slot name="action" /></template>
</EmptyState>
<template v-else>
<StaleNotice v-if="updatedAt" variant="inline" :timestamp="updatedAt" hide-when-fresh />
<slot />
</template>
</template>
+49
View File
@@ -0,0 +1,49 @@
<script setup lang="ts" generic="T extends object">
import { DataTable } from '@perfect-design/ui'
import type { DataTableCellSlotProps } from '@perfect-design/ui'
import LimitBadge from '@/widgets/LimitBadge.vue'
import ShareCell from '@/widgets/ShareCell.vue'
import type { WbColumn } from '@/lib/wb-columns'
type RowId = string | number
defineProps<{
columns: WbColumn<T>[]
rows: T[]
rowKey?: keyof T | ((row: T, index: number) => RowId)
label: string
loading?: boolean
}>()
const activeKey = defineModel<RowId | null | undefined>('activeKey')
const emit = defineEmits<{ 'row-activate': [row: T, key: RowId] }>()
function num(v: unknown): string {
return typeof v === 'number' && Number.isFinite(v) ? v.toLocaleString('en-US') : v == null || v === '' ? '—' : String(v)
}
</script>
<template>
<DataTable
v-model:active-key="activeKey"
class="wb-table"
density="compact"
size="sm"
sticky-header
layout="cards"
:columns="columns"
:rows="rows"
:row-key="rowKey"
:label="label"
:loading="loading"
@row-activate="(row, key) => emit('row-activate', row, key)"
>
<template v-for="col in columns" :key="col.key" #[`cell-${col.key}`]="p: DataTableCellSlotProps<T>">
<span v-if="col.kind === 'number'" data-numeric class="wb-num"><slot :name="`cell-${col.key}`" v-bind="p">{{ num(p.value) }}</slot></span>
<slot v-else-if="col.kind === 'share'" :name="`cell-${col.key}`" v-bind="p"><ShareCell :value="p.value as number" /></slot>
<slot v-else-if="col.kind === 'limit'" :name="`cell-${col.key}`" v-bind="p"><LimitBadge :limit="p.value as number" /></slot>
<slot v-else :name="`cell-${col.key}`" v-bind="p">{{ p.value ?? '—' }}</slot>
</template>
<template #empty><slot name="empty" /></template>
</DataTable>
</template>