diff --git a/bun.lock b/bun.lock index f2f58a5..a640863 100644 --- a/bun.lock +++ b/bun.lock @@ -30,6 +30,8 @@ "peerDependencies": { "@better-auth/passkey": ">=1.7.22 <2", "@orpc/server": ">=2.0.0-beta.52 <3", + "@ui-sdk/core": "0.1.0-beta.23", + "@ui-sdk/react": "0.1.0-beta.23", "better-auth": ">=1.7.22 <2", "react": ">=19 <20", "react-dom": ">=19 <20", @@ -39,6 +41,8 @@ "optionalPeers": [ "@better-auth/passkey", "@orpc/server", + "@ui-sdk/core", + "@ui-sdk/react", "better-auth", "react", "react-dom", diff --git a/e2e/admin-frame-screenshots.spec.ts b/e2e/admin-frame-screenshots.spec.ts new file mode 100644 index 0000000..721c7fc --- /dev/null +++ b/e2e/admin-frame-screenshots.spec.ts @@ -0,0 +1,26 @@ +import { test } from '@playwright/test' + +/** + * Review screenshots of the new admin's frame for the owner: light and dark, desktop (1280) and + * phone (390), with the drawer open on the phone. Saved to SCREENSHOTS_DIR (default + * .screenshots/admin). `bun --bun playwright test e2e/admin-frame-screenshots.spec.ts`. + */ +const DIR = process.env.SCREENSHOTS_DIR ?? '.screenshots/admin' +const sizes = { desktop: { width: 1280, height: 800 }, phone: { width: 390, height: 844 } } + +for (const scheme of ['light', 'dark'] as const) + for (const [label, viewport] of Object.entries(sizes)) + test(`@screenshots admin frame ${label} ${scheme}`, async ({ browser }) => { + const context = await browser.newContext({ viewport, hasTouch: label === 'phone', isMobile: label === 'phone' }) + const page = await context.newPage() + await page.goto(`/admin-next?scheme=${scheme}&path=/admin/users/roles`) + await page.evaluate(() => document.fonts.ready) + await page.screenshot({ path: `${DIR}/frame-${label}-${scheme}.png` }) + if (label === 'phone') { + await page.getByRole('button', { name: 'Menu' }).click() + await page.getByRole('dialog').waitFor() + await page.waitForTimeout(400) + await page.screenshot({ path: `${DIR}/frame-${label}-${scheme}-drawer.png` }) + } + await context.close() + }) diff --git a/e2e/admin-frame.spec.ts b/e2e/admin-frame.spec.ts new file mode 100644 index 0000000..163f946 --- /dev/null +++ b/e2e/admin-frame.spec.ts @@ -0,0 +1,109 @@ +import { expect, test, type Page } from '@playwright/test' +import { expectAccessible, expectFitsScreen } from './helpers' + +/** The new admin's frame (kit 0.9.0, playground /admin-next), on a plain page unless a path is given. */ +async function openFrame(page: Page, query = '') { + await page.goto(`/admin-next?${query.includes('path=') ? query : `path=/admin/stats&${query}`}`) + await expect(page.getByRole('heading', { level: 1 })).toBeVisible() +} + +for (const scheme of ['light', 'dark'] as const) + test(`the frame is accessible and fits the screen (${scheme})`, async ({ page }) => { + await openFrame(page, `scheme=${scheme}`) + await expectAccessible(page) + await expectFitsScreen(page) + }) + +test('long names wrap or cut, never widen the page', async ({ page }) => { + await openFrame(page, 'long=1') + await expectFitsScreen(page) +}) + +test('the skip link is first and moves focus to the page', async ({ page }) => { + await openFrame(page) + await page.keyboard.press('Tab') + const skip = page.getByRole('link', { name: 'Skip to content' }) + await expect(skip).toBeFocused() + await expect(skip).toBeInViewport() + await page.keyboard.press('Enter') + await expect(page.locator('#admin-main')).toBeFocused() +}) + +test('⌘K, Ctrl+K and / open the search; / types normally inside a field', async ({ page }) => { + await openFrame(page) + await page.keyboard.press('Control+k') + await expect(page.getByText('Search opened 1 time.')).toBeVisible() + await page.keyboard.press('Meta+k') + await page.keyboard.press('/') + await expect(page.getByText('Search opened 3 times.')).toBeVisible() +}) + +test.describe('wide screens', () => { + test.skip(({ viewport }) => (viewport?.width ?? 0) < 1040, 'desktop only') + + test('the nav is a column that stays put while the page scrolls', async ({ page }) => { + await openFrame(page) + await expect(page.getByRole('button', { name: 'Menu', exact: true })).toBeHidden() + const nav = page.getByRole('navigation', { name: 'Admin' }) + await expect(nav).toBeVisible() + const before = await nav.boundingBox() + await page.evaluate(() => scrollTo(0, document.body.scrollHeight)) + await expect.poll(() => page.evaluate(() => scrollY)).toBeGreaterThan(100) + expect((await nav.boundingBox())!.y).toBe(before!.y) + }) + + test('one current item; its section opens; choosing another moves the mark', async ({ page }) => { + await openFrame(page, 'path=/admin/users/roles') + const nav = page.getByRole('navigation', { name: 'Admin' }) + await expect(nav.locator('[aria-current="page"]')).toHaveCount(1) + await expect(nav.getByRole('link', { name: 'Roles' })).toHaveAttribute('aria-current', 'page') + await nav.getByRole('link', { name: 'Analytics' }).click() + await expect(nav.getByRole('link', { name: 'Analytics' })).toHaveAttribute('aria-current', 'page') + await expect(nav.getByRole('link', { name: 'Roles' })).toHaveCount(0) + await expect(page.getByRole('heading', { level: 1 })).toHaveText('Analytics') + }) + + test('a number badge reads in full to screen readers', async ({ page }) => { + await openFrame(page) + await expect(page.getByRole('link', { name: 'Reports 12 pending' })).toBeVisible() + }) +}) + +test.describe('phones and tablets', () => { + test.skip(({ viewport }) => (viewport?.width ?? 0) >= 1040, 'narrow screens only') + + test('the nav is a drawer: focus goes in, Esc closes it, focus comes back', async ({ page }) => { + await openFrame(page) + await expect(page.getByRole('navigation', { name: 'Admin' })).toHaveCount(0) + const menu = page.getByRole('button', { name: 'Menu', exact: true }) + await expect(menu).toHaveAttribute('aria-expanded', 'false') + await menu.click() + const drawer = page.getByRole('dialog', { name: 'Admin' }) + await expect(drawer).toBeVisible() + await expect(menu).toHaveAttribute('aria-expanded', 'true') + await expect(drawer.getByRole('button', { name: 'Close menu' })).toBeFocused() + await expectAccessible(page) + await page.keyboard.press('Escape') + await expect(drawer).toBeHidden() + await expect(menu).toBeFocused() + await expect(menu).toHaveAttribute('aria-expanded', 'false') + }) + + test('choosing a page closes the drawer; so does the scrim', async ({ page }) => { + await openFrame(page) + await page.getByRole('button', { name: 'Menu', exact: true }).click() + await page.getByRole('dialog', { name: 'Admin' }).getByRole('link', { name: 'Reports 12 pending' }).click() + await expect(page.getByRole('dialog', { name: 'Admin' })).toBeHidden() + await expect(page.getByRole('heading', { level: 1 })).toHaveText('Reports') + await page.getByRole('button', { name: 'Menu', exact: true }).click() + await expect(page.getByRole('dialog', { name: 'Admin' })).toBeVisible() + await page.mouse.click(380, 400) // right of the panel: the scrim + await expect(page.getByRole('dialog', { name: 'Admin' })).toBeHidden() + }) + + test('touch targets are at least 44 px', async ({ page }) => { + await openFrame(page) + for (const name of ['Menu', 'Search']) + expect((await page.getByRole('button', { name, exact: true }).boundingBox())!.height).toBeGreaterThanOrEqual(44) + }) +}) diff --git a/e2e/admin-list-screenshots.spec.ts b/e2e/admin-list-screenshots.spec.ts new file mode 100644 index 0000000..1f56b0a --- /dev/null +++ b/e2e/admin-list-screenshots.spec.ts @@ -0,0 +1,102 @@ +import { test, type Page } from '@playwright/test' + +/** + * Review screenshots of the new admin's list page for the owner, light and dark, desktop (1280) and + * phone (390), plus a short recording of the list in use (desktop). Saved to SCREENSHOTS_DIR + * (default .screenshots/admin). `bun --bun playwright test e2e/admin-list-screenshots.spec.ts`. + */ +const DIR = process.env.SCREENSHOTS_DIR ?? '.screenshots/admin' +const sizes = { desktop: { width: 1280, height: 800 }, phone: { width: 390, height: 844 } } +const ready = async (page: Page) => { + await page.locator('[data-slot="admin-index"] [data-row-id]').filter({ visible: true }).first().waitFor() + await page.evaluate(() => document.fonts.ready) + await page.waitForTimeout(300) +} + +for (const scheme of ['light', 'dark'] as const) + for (const [label, viewport] of Object.entries(sizes)) + test(`@screenshots admin list ${label} ${scheme}`, async ({ browser }) => { + const phone = label === 'phone' + const context = await browser.newContext({ viewport, hasTouch: phone, isMobile: phone }) + const page = await context.newPage() + const shot = (name: string) => page.screenshot({ path: `${DIR}/list-${label}-${scheme}-${name}.png` }) + const base = `/admin-next?scheme=${scheme}&path=/admin/users` + + await page.goto(base) + await page.waitForTimeout(150) + await shot('1-first-load') + await ready(page) + await shot('2-list') + + await page.goto(`${base}&status=suspended,banned&sort=name`) + await ready(page) + await shot('3-filtered') + + // The previous rows stay, faded, with the loading bar, while the next ones load. + await page.getByRole('combobox', { name: 'Role' }).selectOption('user') + await page.waitForTimeout(240) + await shot('4-refreshing') + await ready(page) + + await page.goto(base) + await ready(page) + if (phone) await page.getByRole('button', { name: 'Select', exact: true }).click() + for (const index of [0, 1, 2]) + await page.locator('[data-row-id]').filter({ visible: true }).nth(index).locator('[type="checkbox"]').click() + await page.waitForTimeout(200) + await shot('5-selected') + if (!phone) { + await page.getByRole('checkbox', { name: 'Select all on this page' }).check() + await page.waitForTimeout(200) + await shot('6-page-selected') + } + await page.locator('[data-slot="admin-bulk-bar"]').getByRole('button', { name: 'Suspend' }).click() + await page.waitForTimeout(350) + await shot('7-undo-toast') + + await page.goto(`${base}&q=zzz`) + await page.getByText('No users found').filter({ visible: true }).waitFor() + await shot('8-no-results') + await context.close() + }) + +test('@screenshots admin list recording', async ({ browser }) => { + const context = await browser.newContext({ + viewport: sizes.desktop, + recordVideo: { dir: `${DIR}/video`, size: sizes.desktop }, + }) + const page = await context.newPage() + const pause = (ms = 700) => page.waitForTimeout(ms) + await page.goto('/admin-next?path=/admin/users&scheme=light') + await ready(page) + await pause() + await page.getByRole('searchbox', { name: 'Search users' }).pressSequentially('ada', { delay: 140 }) + await pause(1200) + await page.getByRole('combobox', { name: 'Status' }).selectOption('active') + await pause(1200) + await page.getByRole('button', { name: 'Remove filter Status: Active' }).click() + await page.getByRole('button', { name: 'Clear all' }).click() + await pause(1200) + await page.keyboard.press('j') + await pause(300) + await page.keyboard.press('x') + await pause(300) + await page.keyboard.press('j') + await page.keyboard.press('j') + await pause(300) + await page.keyboard.press('Shift+X') + await pause(1000) + await page.locator('[data-slot="admin-bulk-bar"]').getByRole('button', { name: 'Suspend' }).click() + await pause(1500) + await page.getByRole('button', { name: 'Undo' }).click() + await pause(1200) + await page.getByRole('link', { name: 'Next page' }).click() + await pause(1200) + await page.getByRole('button', { name: 'Posts' }).click() + await pause(1200) + await page.locator('[data-slot="admin-table"] tbody tr').nth(3).locator('td').last().click() + await pause(900) + await page.goBack() + await pause(1200) + await context.close() +}) diff --git a/e2e/admin-list.spec.ts b/e2e/admin-list.spec.ts new file mode 100644 index 0000000..762bbc7 --- /dev/null +++ b/e2e/admin-list.spec.ts @@ -0,0 +1,261 @@ +import { expect, test, type Page } from '@playwright/test' +import { expectAccessible, expectFitsScreen } from './helpers' + +/** The new admin's list page (kit 0.9.0, playground /admin-next, users behind a pretend server). */ +async function openList(page: Page, query = '') { + await page.goto(`/admin-next?path=/admin/users${query ? `&${query}` : ''}`) + await expect(page.locator('[data-slot="admin-index"] [data-row-id]').filter({ visible: true }).first()).toBeVisible() + // A mark that a full reload would wipe. + await page.evaluate(() => Object.assign(window, { stayed: true })) +} +const stayed = (page: Page) => page.evaluate(() => (window as Window & { stayed?: boolean }).stayed === true) +const wide = (page: Page) => (page.viewportSize()?.width ?? 0) >= 640 +// One table for every width (it stacks into cards on narrow screens). +const rowsOf = (page: Page) => page.locator('[data-slot="admin-table"] tbody tr[data-row-id]') + +for (const scheme of ['light', 'dark'] as const) + test(`the list is accessible and fits the screen (${scheme})`, async ({ page }) => { + await openList(page, `scheme=${scheme}`) + await expectAccessible(page) + await expectFitsScreen(page) + }) + +test('the first load shows skeleton rows, then the rows', async ({ page }) => { + await page.goto('/admin-next?path=/admin/users') + await expect(page.locator('[aria-busy="true"]').first()).toBeAttached() + await expect(rowsOf(page).first()).toBeVisible() + await expect(page.locator('[data-slot="admin-skeleton-row"]')).toHaveCount(0) +}) + +test('a filter updates the list at once, keeps the old rows while loading, and says the count', async ({ page }) => { + await openList(page) + await page.getByRole('combobox', { name: 'Status' }).selectOption('suspended') + // The old rows stay (faded) while the new ones load: never a blank table. + await expect(page.locator('[data-slot="admin-index"][data-refreshing]')).toBeAttached() + expect(await rowsOf(page).count()).toBeGreaterThan(0) + await expect(page).toHaveURL(/status=suspended/) + await expect(page.getByRole('button', { name: 'Remove filter Status: Suspended' })).toBeVisible() + await expect(page.locator('[data-slot="admin-index"][data-refreshing]')).toHaveCount(0) + await expect(page.getByRole('status').filter({ hasText: /^\d[\d,]* users$/ })).toBeAttached() + for (const status of await rowsOf(page).locator('[data-slot="badge"]').filter({ hasNotText: 'Admin' }).allTextContents()) + expect(status).toBe('Suspended') + expect(await stayed(page)).toBe(true) +}) + +test('the search follows the typing; / jumps to it; Escape clears it', async ({ page }) => { + await openList(page) + await page.keyboard.press('/') + const search = page.getByRole('searchbox', { name: 'Search users' }) + await expect(search).toBeFocused() + await page.keyboard.type('ada') + await expect(page).toHaveURL(/q=ada/) + await expect(rowsOf(page).first()).toContainText(/ada/i) + await page.keyboard.press('Escape') + await expect(page).not.toHaveURL(/q=/) + expect(await stayed(page)).toBe(true) +}) + +test('chips come off by keyboard; Clear all removes the rest; Back brings them back', async ({ page }) => { + await openList(page, 'status=suspended,banned&role=user') + const remove = page.getByRole('button', { name: 'Remove filter Status: Suspended' }) + await remove.focus() + await page.keyboard.press('Enter') + await expect(remove).toHaveCount(0) + await expect(page).toHaveURL(/status=banned/) + // Focus stays in the chips. + await expect(page.getByRole('button', { name: 'Remove filter Status: Banned' })).toBeFocused() + await page.getByRole('button', { name: 'Clear all' }).click() + await expect(page.getByRole('list', { name: 'Filters' })).toHaveCount(0) + await page.goBack() + await expect(page.getByRole('button', { name: 'Remove filter Status: Banned' })).toBeVisible() +}) + +test('views are tabs that keep the sort and drop the filters', async ({ page }) => { + await openList(page, 'sort=name&status=active') + await page.getByRole('navigation', { name: 'Views' }).getByRole('link', { name: 'Admins' }).click() + await expect(page).toHaveURL(/view=admins&sort=name$/) + await expect(page.getByRole('link', { name: 'Admins' })).toHaveAttribute('aria-current', 'page') + expect(await stayed(page)).toBe(true) +}) + +test('pages change in place, with the cursor in the URL; Back returns', async ({ page }) => { + await openList(page) + const first = await rowsOf(page).first().getAttribute('data-row-id') + await expect(page.getByRole('link', { name: 'Previous page' })).toHaveAttribute('aria-disabled', 'true') + await page.getByRole('link', { name: 'Next page' }).click() + await expect(page).toHaveURL(/after=u\d+/) + await expect(rowsOf(page).first()).not.toHaveAttribute('data-row-id', first!) + await expect(page.getByRole('link', { name: 'Previous page' })).toHaveAttribute('href', /before=u\d+/) + await page.goBack() + await expect(rowsOf(page).first()).toHaveAttribute('data-row-id', first!) + expect(await stayed(page)).toBe(true) +}) + +test('bulk actions are instant, with Undo in a toast that stays', async ({ page }) => { + await openList(page, 'status=active') + if (!wide(page)) await page.getByRole('button', { name: 'Select', exact: true }).click() + const rows = rowsOf(page) + const names = [await rows.nth(0).getAttribute('data-row-id'), await rows.nth(1).getAttribute('data-row-id')] + for (const id of names) await page.locator(`[data-row-id="${id}"] [type="checkbox"]`).filter({ visible: true }).click() + const bar = page.locator('[data-slot="admin-bulk-bar"]') + await expect(bar).toContainText('2 selected') + await expect(bar).toBeInViewport() + await expect(page.getByRole('status').filter({ hasText: '2 selected' })).toBeAttached() + await bar.getByRole('button', { name: 'Suspend' }).click() + // Optimistic: the rows change before any answer. + await expect(page.locator(`[data-row-id="${names[0]}"]`).filter({ visible: true })).toContainText('Suspended') + const toast = page.locator('[data-slot="admin-toast"]') + await expect(toast).toContainText('2 users suspended') + await expect(bar).toHaveCount(0) + await page.waitForTimeout(5500) + await expect(toast).toBeVisible() + await toast.getByRole('button', { name: 'Undo' }).click() + await expect(page.locator(`[data-row-id="${names[0]}"]`).filter({ visible: true })).toContainText('Active') + await expect(toast).toHaveCount(0) +}) + +test.describe('wide screens', () => { + test.skip(({ viewport }) => (viewport?.width ?? 0) < 640, 'table only') + + test('the header row sticks under the top bar while the page scrolls', async ({ page }) => { + await openList(page) + await page.evaluate(() => scrollTo(0, 1200)) + const header = page.getByRole('columnheader', { name: 'Email' }) + await expect.poll(async () => Math.round((await header.boundingBox())!.y)).toBe(56) + }) + + test('too wide for its room: a focusable, named region that scrolls, the name column staying put', async ({ page }) => { + await page.setViewportSize({ width: 760, height: 800 }) + await openList(page) + const region = page.getByRole('region', { name: 'Users' }) + await expect(region).toHaveAttribute('tabindex', '0') + const name = rowsOf(page).first().getByRole('rowheader') + const before = (await name.boundingBox())!.x + await region.focus() + await page.keyboard.press('ArrowRight') + await page.keyboard.press('ArrowRight') + await expect.poll(() => region.evaluate((element) => element.scrollLeft)).toBeGreaterThan(0) + expect(Math.round((await name.boundingBox())!.x)).toBe(Math.round(before)) + await expectAccessible(page) + }) + + test('only the sorted column shows an arrow', async ({ page }) => { + await openList(page) + const icons = page.locator('[data-slot="admin-sort-icon"]').filter({ visible: true }) + await expect(icons).toHaveCount(1) + await expect( + page.getByRole('columnheader', { name: 'Joined' }).locator('[data-slot="admin-sort-icon"]').filter({ visible: true }), + ).toHaveAttribute('data-direction', 'descending') + }) + + test('a real table: caption, headers, the sorted column says its order', async ({ page }) => { + await openList(page) + const table = page.getByRole('table', { name: 'Users' }) + await expect(table).toBeVisible() + await expect(table.getByRole('columnheader', { name: 'Joined' })).toHaveAttribute('aria-sort', 'descending') + await table.getByRole('button', { name: 'Name' }).click() + await expect(page).toHaveURL(/sort=name/) + await expect(table.getByRole('columnheader', { name: 'Name' })).toHaveAttribute('aria-sort', 'ascending') + }) + + test('the whole row opens the record, and Back keeps the list', async ({ page }) => { + await openList(page, 'status=banned') + const row = rowsOf(page).first() + const id = await row.getAttribute('data-row-id') + await row.locator('td').last().click() + await expect(page).toHaveURL(new RegExp(`path=%2Fadmin%2Fusers%2F${id}`)) + await page.goBack() + await expect(page.getByRole('button', { name: 'Remove filter Status: Banned' })).toBeVisible() + }) + + test('j and k move between rows, x and Shift+x select, the header goes mixed', async ({ page }) => { + await openList(page) + await page.locator('body').click({ position: { x: 5, y: 300 } }) + await page.keyboard.press('j') + await page.keyboard.press('j') + const rows = rowsOf(page) + await expect(rows.nth(1).locator('[data-slot="admin-row-link"]')).toBeFocused() + await page.keyboard.press('k') + await expect(rows.nth(0).locator('[data-slot="admin-row-link"]')).toBeFocused() + await page.keyboard.press('x') + await page.keyboard.press('j') + await page.keyboard.press('j') + await page.keyboard.press('Shift+X') + await expect(page.locator('[data-slot="admin-bulk-bar"]')).toContainText('3 selected') + const header = page.getByRole('checkbox', { name: 'Select all on this page' }) + expect(await header.evaluate((input: HTMLInputElement) => input.indeterminate)).toBe(true) + // Space on a row's link adds it too; Enter would open it. + await page.keyboard.press('j') + await page.keyboard.press('Space') + await expect(page.locator('[data-slot="admin-bulk-bar"]')).toContainText('4 selected') + }) + + test('select the page, then every matching row', async ({ page }) => { + await openList(page) + await page.getByRole('checkbox', { name: 'Select all on this page' }).check() + await expect(page.locator('[data-slot="admin-bulk-bar"]')).toContainText('50 selected') + await page.getByRole('button', { name: 'Select all 2,481 users' }).click() + await expect(page.locator('[data-slot="admin-bulk-bar"]')).toContainText('All 2,481 users are selected.') + await page.getByRole('button', { name: 'Clear selection' }).click() + await expect(page.locator('[data-slot="admin-bulk-bar"]')).toHaveCount(0) + }) +}) + +test.describe('phones', () => { + test.skip(({ viewport }) => (viewport?.width ?? 0) >= 640, 'phones only') + + test('the table stacks into cards (still a table); Select mode, then taps select', async ({ page }) => { + await openList(page) + const table = page.getByRole('table', { name: 'Users' }) + await expect(table).toBeVisible() + await expect(table.getByRole('columnheader').first()).toBeHidden() + // Each card: title, second line, badge, and "Column: value" lines; rows are still rows. + const first = rowsOf(page).first() + await expect(first.getByRole('rowheader')).toBeVisible() + await expect(first.locator('[data-label="Posts"]')).toBeVisible() + await expect(first.locator('[data-label="Role"]')).toBeHidden() + expect(await first.locator('[data-label="Posts"]').evaluate((cell) => getComputedStyle(cell, '::before').content)).toBe('"Posts: "') + // A tap on the card opens the record, outside Select mode. + // The title's link covers the card, so the tap lands on it. + await first.locator('[data-label="Joined"]').click({ force: true }) + await expect(page).toHaveURL(/path=%2Fadmin%2Fusers%2Fu\d+/) + await page.goBack() + await expect(rowsOf(page).first()).toBeVisible() + await page.getByRole('button', { name: 'Select', exact: true }).click() + await rowsOf(page).nth(0).click() + await rowsOf(page).nth(2).click() + const bar = page.locator('[data-slot="admin-bulk-bar"]') + await expect(bar).toContainText('2 selected') + // Fixed at the bottom, once it has slid in. + await expect + .poll(async () => { + const box = (await bar.boundingBox())! + return Math.round(box.y + box.height) + }) + .toBe(page.viewportSize()!.height) + await expectAccessible(page) + }) + + test('sort is a compact button naming the current order; the filter menus fit on one line', async ({ page }) => { + await openList(page) + const sort = page.getByRole('combobox', { name: 'Sort: Joined, newest first' }) + await expect(sort).toBeAttached() + await expect(page.locator('[data-slot="admin-sort-face"]')).toHaveText('Sort') + const menus = page.locator('[data-slot="admin-filter-menus"]') + const tops = await menus.locator(':scope > *').evaluateAll((items) => items.map((item) => Math.round(item.getBoundingClientRect().top))) + expect(new Set(tops).size).toBe(1) + await sort.selectOption('name:asc') + await expect(page).toHaveURL(/sort=name/) + await expect(page.getByRole('combobox', { name: 'Sort: Name, A–Z' })).toBeAttached() + await expectFitsScreen(page) + }) + + test('touch targets are at least 44 px', async ({ page }) => { + await openList(page) + for (const name of ['Select', 'Next page']) { + const target = page.getByRole(name === 'Select' ? 'button' : 'link', { name, exact: true }) + expect((await target.boundingBox())!.height).toBeGreaterThanOrEqual(44) + } + expect((await rowsOf(page).first().boundingBox())!.height).toBeGreaterThanOrEqual(44) + }) +}) diff --git a/playground/admin-next.html b/playground/admin-next.html new file mode 100644 index 0000000..1ae9a3f --- /dev/null +++ b/playground/admin-next.html @@ -0,0 +1,26 @@ + + + + + + kit admin (next) playground + + + + + + + + + + + +
+ + + diff --git a/playground/admin-next.tsx b/playground/admin-next.tsx new file mode 100644 index 0000000..dafee55 --- /dev/null +++ b/playground/admin-next.tsx @@ -0,0 +1,177 @@ +/** + * The new admin (kit 0.9.0, in progress): the frame with sample data. `?path=/admin/users` picks the + * page, `?scheme=dark|light` forces a scheme, `?long=1` tries long names. Links stay in the playground. + */ +import { useEffect, useState, type ReactNode } from 'react' +import { createRoot } from 'react-dom/client' +import { AdminFrame, AdminSearch, PageHeader, type AdminLink, type AdminNav } from '../src/admin-next/frame' +import { scaleCss, themeCss } from '../src/tokens' +import { adminTheme, ADMIN_THEME_SCOPE } from '../src/tokens/themes' +import { listQueryString, parseListQuery } from '../src/admin-next/list' +import { Badge, Button, VisuallyHidden, Card, CardContent, CardDescription, CardHeader, CardTitle } from '../src/ui' +import { UsersPage, usersSpec } from './admin-users' + +const params = new URLSearchParams(location.search) +const scheme = params.get('scheme') === 'dark' ? 'dark' : params.get('scheme') === 'light' ? 'light' : undefined +const long = params.has('long') +const empty = params.has('empty') +// The playground's own settings stay in the URL; the page's path and the list's query sit beside them. +const own = ['scheme', 'long', 'empty'].flatMap((key) => (params.has(key) ? [[key, params.get(key)!]] : [])) +const toPlayground = (href: string) => { + const [path = '', search = ''] = href.split('?') + const next = new URLSearchParams([...own, ['path', path]]) + for (const [key, value] of new URLSearchParams(search)) next.append(key, value) + return `?${next}` +} +const fromLocation = () => { + const current = new URLSearchParams(location.search) + return { path: current.get('path') ?? '/admin/users', search: current } +} + +// Lucide's icons (ISC licence): house, users, flag, file-text, chart-column, settings. +const icon = (...paths: string[]) => ( + + {paths.map((d) => ( + + ))} + +) +const icons = { + home: icon( + 'M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8', + 'M3 10a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z', + ), + users: icon( + 'M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2', + 'M22 21v-2a4 4 0 0 0-3-3.87', + 'M16 3.13a4 4 0 0 1 0 7.75', + 'M9 3a4 4 0 1 0 0 8 4 4 0 0 0 0-8', + ), + flag: icon( + 'M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528', + ), + file: icon('M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z', 'M14 2v4a2 2 0 0 0 2 2h4', 'M10 9H8', 'M16 13H8', 'M16 17H8'), + chart: icon('M3 3v16a2 2 0 0 0 2 2h16', 'M18 17V9', 'M13 17V5', 'M8 17v-3'), + settings: icon( + 'M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z', + 'M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0', + ), +} + +const nav: AdminNav = { + main: [ + { key: 'home', label: 'Home', to: '/admin', exact: true, icon: icons.home }, + { + key: 'users', + label: long ? 'People who signed up for an account' : 'Users', + to: '/admin/users', + icon: icons.users, + children: [ + { key: 'roles', label: 'Roles', to: '/admin/users/roles' }, + { key: 'suspended', label: 'Suspended', to: '/admin/users/suspended' }, + ], + }, + { key: 'reports', label: 'Reports', to: '/admin/reports', icon: icons.flag, badge: 12 }, + { key: 'stats', label: 'Analytics', to: '/admin/stats', icon: icons.chart }, + ], + groups: [ + { + key: 'content', + label: 'Content', + items: [ + { key: 'pages', label: 'Pages', to: '/admin/pages', icon: icons.file }, + { key: 'faq', label: 'FAQ', to: '/admin/faq', icon: icons.file, badge: 'New' }, + ], + }, + ], + settings: { key: 'settings', label: 'Settings', to: '/admin/settings', icon: icons.settings }, +} + +const style = document.createElement('style') +style.textContent = [scaleCss(), themeCss(adminTheme, { scope: ADMIN_THEME_SCOPE })].join('\n') +document.head.append(style) + +function App() { + const [{ path, search }, setLocation] = useState(fromLocation) + const [searched, setSearched] = useState(0) + useEffect(() => { + const onPop = () => setLocation(fromLocation()) + addEventListener('popstate', onPop) + return () => removeEventListener('popstate', onPop) + }, []) + const go = (href: string) => { + history.pushState(null, '', toPlayground(href)) + setLocation(fromLocation()) + } + // Links stay in the playground: the path and query go in the URL, the page doesn't reload. + const link: AdminLink = ({ href, onClick, ...props }) => ( + { + onClick?.(event) + if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.shiftKey || event.button !== 0) return + event.preventDefault() + go(href) + }} + /> + ) + const query = parseListQuery(search, usersSpec) + const title = + nav.main + .concat(nav.groups![0]!.items, [nav.settings!]) + .flatMap((item) => [item, ...(item.children ?? [])]) + .find((item) => item.to === path)?.label ?? 'Page' + return ( + , + }} + search={ setSearched((n) => n + 1)} />} + account={ + + } + renderLink={link} + > + 3 ? { href: '/admin/users', label: 'Users' } : undefined} + secondaryActions={} + primaryAction={} + renderLink={link} + /> + {path === '/admin/users' ? ( + go(`/admin/users${listQueryString(next, usersSpec)}`)} + renderLink={link} + empty={empty} + /> + ) : ( + + + The page goes here + + Details and settings come in the next pull requests. Search opened {searched} time{searched === 1 ? '' : 's'}. + + + + {Array.from({ length: 24 }, (_, i) => ( +

Row {i + 1}: long enough to scroll the page, so you can see the nav stay put.

+ ))} +
+
+ )} +
+ ) +} + +createRoot(document.getElementById('root')!).render() diff --git a/playground/admin-users.tsx b/playground/admin-users.tsx new file mode 100644 index 0000000..bb839ca --- /dev/null +++ b/playground/admin-users.tsx @@ -0,0 +1,301 @@ +/** + * The playground's users list: 2,481 made-up people behind a pretend server that answers after a + * short wait, so the list's live updates, loading bar, view transitions and undo can be seen. + */ +import { useEffect, useRef, useState } from 'react' +import { useAdminToast } from '../src/admin-next/feedback' +import type { AdminLink } from '../src/admin-next/frame' +import { + ResourceIndex, + type BulkTarget, + type ListColumn, + type ListFilter, + type ListQuery, + type ListSortOption, + type ListSpec, + listQueryString, +} from '../src/admin-next/list' +import { Avatar, Badge, Button, EmptyActions, Empty, EmptyDescription, EmptyTitle } from '../src/ui' + +type Status = 'active' | 'suspended' | 'banned' +type User = { id: string; name: string; email: string; role: 'user' | 'admin'; status: Status; posts: number; joined: number } + +const first = [ + 'Ada', + 'Grace', + 'Alan', + 'Katherine', + 'Linus', + 'Margaret', + 'Tim', + 'Radia', + 'Dennis', + 'Barbara', + 'Ken', + 'Frances', + 'Guido', + 'Hedy', + 'Edsger', + 'Joan', + 'Vint', + 'Mary', + 'Donald', + 'Annie', +] +const last = [ + 'Lovelace', + 'Hopper', + 'Turing', + 'Johnson', + 'Torvalds', + 'Hamilton', + 'Berners-Lee', + 'Perlman', + 'Ritchie', + 'Liskov', + 'Thompson', + 'Allen', + 'van Rossum', + 'Lamarr', + 'Dijkstra', + 'Clarke', + 'Cerf', + 'Jackson', + 'Knuth', + 'Easley', +] + +const DAY = 86_400_000 +const NOW = Date.UTC(2026, 11, 5) +// The same people on every load: a small seeded generator. +let seed = 7 +const random = () => ((seed = (seed * 16807) % 2147483647) - 1) / 2147483646 +const db: User[] = Array.from({ length: 2481 }, (_, index) => { + const name = `${first[Math.floor(random() * first.length)]} ${last[Math.floor(random() * last.length)]}` + const roll = random() + return { + id: `u${String(index + 1).padStart(4, '0')}`, + name, + email: `${name.toLowerCase().replace(/[^a-z]+/g, '.')}${index + 1}@example.com`, + role: random() < 0.03 ? 'admin' : 'user', + status: roll < 0.08 ? 'suspended' : roll < 0.1 ? 'banned' : 'active', + posts: Math.floor(random() ** 3 * 4000), + joined: NOW - Math.floor(random() * 900) * DAY, + } +}) + +export const usersSpec: ListSpec = { + views: ['all', 'admins', 'suspended'], + filters: [ + { key: 'status', options: ['active', 'suspended', 'banned'], multiple: true }, + { key: 'role', options: ['user', 'admin'] }, + ], + sorts: ['joined', 'name', 'posts'], +} + +const PAGE = 50 +const NONE: User[] = [] + +function matching(query: ListQuery): User[] { + const search = query.search.toLowerCase() + const status = query.filters.status + const role = query.filters.role + const rows = db.filter( + (user) => + (query.view !== 'admins' || user.role === 'admin') && + (query.view !== 'suspended' || user.status === 'suspended') && + (!search || user.name.toLowerCase().includes(search) || user.email.includes(search)) && + (!status || status.includes(user.status)) && + (!role || role.includes(user.role)), + ) + const { key, direction } = query.sort + const sign = direction === 'asc' ? 1 : -1 + return rows.sort((a, b) => { + const order = key === 'name' ? a.name.localeCompare(b.name) : key === 'posts' ? a.posts - b.posts : a.joined - b.joined + return sign * order || a.id.localeCompare(b.id) + }) +} + +type Page = { rows: User[]; total: number; pageInfo: { next?: string; previous?: string } } + +/** The pretend server: keyset pages of 50, answered after 250–600 ms (the first after 700 ms). */ +function fetchUsers(query: ListQuery, wait: number): Promise { + const rows = matching(query) + let start = 0 + if (query.cursor && 'after' in query.cursor) start = rows.findIndex((user) => user.id === (query.cursor as { after: string }).after) + 1 + if (query.cursor && 'before' in query.cursor) + start = Math.max(0, rows.findIndex((user) => user.id === (query.cursor as { before: string }).before) - PAGE) + const page = rows.slice(start, start + PAGE) + const result: Page = { + rows: page.map((user) => ({ ...user })), + total: rows.length, + pageInfo: { + ...(start + PAGE < rows.length && page.length ? { next: page[page.length - 1]!.id } : {}), + ...(start > 0 && page.length ? { previous: page[0]!.id } : {}), + }, + } + return new Promise((resolve) => setTimeout(() => resolve(result), wait)) +} + +/** As TanStack Query with `placeholderData: keepPreviousData`: the last page stays while the next loads. */ +function useUsers(query: ListQuery) { + const key = listQueryString(query, usersSpec) + const [data, setData] = useState<(Page & { key: string }) | undefined>(undefined) + const [version, setVersion] = useState(0) + const firstLoad = useRef(true) + useEffect(() => { + let live = true + const wait = firstLoad.current ? 700 : 250 + Math.random() * 350 + firstLoad.current = false + fetchUsers(query, wait).then((page) => live && setData({ ...page, key })) + return () => { + live = false + } + // The key is the query. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [key, version]) + return { + data, + refreshing: data !== undefined && data.key !== key, + /** An optimistic change: the rows on screen change now, the server's answer follows. */ + update: (change: (user: User) => User) => setData((current) => current && { ...current, rows: current.rows.map(change) }), + refetch: () => setVersion((n) => n + 1), + } +} + +const statusBadge: Record = { + active: { variant: 'success', label: 'Active' }, + suspended: { variant: 'warning', label: 'Suspended' }, + banned: { variant: 'destructive', label: 'Banned' }, +} +const date = new Intl.DateTimeFormat('en', { dateStyle: 'medium', timeZone: 'UTC' }) +const number = new Intl.NumberFormat('en') + +const columns: ListColumn[] = [ + { + key: 'name', + header: 'Name', + sort: 'name', + cell: (user) => ( + + + {user.name} + + ), + }, + { key: 'email', header: 'Email', phone: 'line', cell: (user) => {user.email} }, + { key: 'role', header: 'Role', phone: 'hide', cell: (user) => (user.role === 'admin' ? Admin : 'User') }, + { + key: 'status', + header: 'Status', + phone: 'badge', + cell: (user) => {statusBadge[user.status].label}, + }, + { key: 'posts', header: 'Posts', align: 'end', sort: 'posts', cell: (user) => number.format(user.posts) }, + { key: 'joined', header: 'Joined', align: 'end', sort: 'joined', cell: (user) => date.format(user.joined) }, +] + +const filters: ListFilter[] = [ + { + key: 'status', + label: 'Status', + options: [ + { value: 'active', label: 'Active' }, + { value: 'suspended', label: 'Suspended' }, + { value: 'banned', label: 'Banned' }, + ], + }, + { + key: 'role', + label: 'Role', + options: [ + { value: 'user', label: 'User' }, + { value: 'admin', label: 'Admin' }, + ], + }, +] + +const sortOptions: ListSortOption[] = [ + { key: 'joined', label: 'Joined', ascending: 'oldest first', descending: 'newest first' }, + { key: 'name', label: 'Name', ascending: 'A–Z', descending: 'Z–A' }, + { key: 'posts', label: 'Posts', ascending: 'fewest first', descending: 'most first' }, +] + +export function UsersPage({ + query, + onQueryChange, + renderLink, + empty, +}: { + query: ListQuery + onQueryChange: (query: ListQuery) => void + renderLink: AdminLink + /** `?empty=1`: the first-time empty state. */ + empty: boolean +}) { + const toast = useAdminToast() + const { data, refreshing, update, refetch } = useUsers(query) + + const setStatus = (status: Status, verb: string) => (target: BulkTarget) => { + const ids = new Set(target.all ? matching(target.query).map((user) => user.id) : target.ids) + const before = new Map(db.filter((user) => ids.has(user.id)).map((user) => [user.id, user.status])) + // Optimistic: the rows change now; the "server" (db) takes the change too. + update((user) => (ids.has(user.id) ? { ...user, status } : user)) + for (const user of db) if (ids.has(user.id)) user.status = status + const count = ids.size + toast({ + message: `${number.format(count)} ${count === 1 ? 'user' : 'users'} ${verb}`, + action: { + label: 'Undo', + run: () => { + for (const user of db) { + const was = before.get(user.id) + if (was) user.status = was + } + update((user) => ({ ...user, status: before.get(user.id) ?? user.status })) + refetch() + }, + }, + }) + } + + return ( + user.id} + rowLabel={(user) => user.name} + rowHref={(user) => `/admin/users/${user.id}`} + total={empty ? 0 : data?.total} + totalExact + pageInfo={data?.pageInfo} + bulkActions={[ + { key: 'activate', label: 'Activate', run: setStatus('active', 'activated') }, + { key: 'suspend', label: 'Suspend', destructive: true, run: setStatus('suspended', 'suspended') }, + ]} + emptyState={ + + No users yet + People who sign up show here. You can also add someone yourself. + + + + + } + renderLink={renderLink} + /> + ) +} diff --git a/playground/serve.ts b/playground/serve.ts index 4220eb1..04566d7 100644 --- a/playground/serve.ts +++ b/playground/serve.ts @@ -10,6 +10,7 @@ import { dirname, resolve } from 'node:path' import page from './index.html' import account from './account.html' import ui from './ui.html' +import adminNext from './admin-next.html' import overlays from './overlays.html' const reactNativeWeb: BunPlugin = { @@ -55,9 +56,12 @@ Bun.serve({ '/account': account, '/ui': ui, '/overlays': overlays, + '/admin-next': adminNext, '/account-native': () => new Response(nativeHtml, { headers: { 'content-type': 'text/html; charset=utf-8' } }), '/account-native.js': () => new Response(nativeJs, { headers: { 'content-type': 'text/javascript; charset=utf-8' } }), }, development: process.env.NODE_ENV !== 'production', }) -console.log(`Playground on http://127.0.0.1:${port}/ (kit/account: /account, /account-native; kit/ui: /ui, /overlays)`) +console.log( + `Playground on http://127.0.0.1:${port}/ (kit/account: /account, /account-native; kit/ui: /ui, /overlays; new admin: /admin-next)`, +) diff --git a/src/admin-next/feedback/index.ts b/src/admin-next/feedback/index.ts new file mode 100644 index 0000000..e059071 --- /dev/null +++ b/src/admin-next/feedback/index.ts @@ -0,0 +1 @@ +export * from './toast' diff --git a/src/admin-next/feedback/toast.tsx b/src/admin-next/feedback/toast.tsx new file mode 100644 index 0000000..65d5f6f --- /dev/null +++ b/src/admin-next/feedback/toast.tsx @@ -0,0 +1,100 @@ +import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from 'react' +import { CloseIcon } from '../frame/icons' + +/** + * Toasts for the admin (admin-patterns, pattern 7): a short confirmation of what the user just did, + * bottom centre, gone after 5 s (the timer waits while the pointer or focus is on it). A toast with + * an action ("Undo") stays until it is used or closed: 5 s is too short to reach it by keyboard or + * with a screen reader. Errors are alerts; the rest is read politely. + * + * Provisional: this moves onto kit/ui's Toast when it lands, with the same `useAdminToast()` call. + */ +export type AdminToast = { + message: string + tone?: 'default' | 'error' | undefined + action?: { label: string; run: () => void } | undefined +} + +type Shown = AdminToast & { id: number } + +const ToastContext = createContext<(toast: AdminToast) => void>(() => {}) + +/** Shows a toast: `toast({ message: '3 users suspended', action: { label: 'Undo', run } })`. */ +export function useAdminToast(): (toast: AdminToast) => void { + return useContext(ToastContext) +} + +const MAX = 3 +const DURATION = 5000 + +export function AdminToaster({ + children, + label, + dismiss, +}: { + children: ReactNode + /** The region's name ("Notifications"). */ + label: string + /** The close button's name. */ + dismiss: string +}) { + const [toasts, setToasts] = useState([]) + const next = useRef(0) + const show = useCallback((toast: AdminToast) => { + next.current += 1 + const id = next.current + setToasts((current) => [...current, { ...toast, id }].slice(-MAX)) + }, []) + const close = useCallback((id: number) => setToasts((current) => current.filter((toast) => toast.id !== id)), []) + return ( + + {children} +
+
    + {toasts.map((toast) => ( + close(toast.id)} /> + ))} +
+
+
+ ) +} + +function ToastItem({ toast, dismiss, onClose }: { toast: Shown; dismiss: string; onClose: () => void }) { + const [paused, setPaused] = useState(false) + const latest = useRef(onClose) + latest.current = onClose + useEffect(() => { + if (toast.action || paused) return + const timer = setTimeout(() => latest.current(), DURATION) + return () => clearTimeout(timer) + }, [toast.action, paused]) + return ( +
  • setPaused(true)} + onPointerLeave={() => setPaused(false)} + onFocus={() => setPaused(true)} + onBlur={() => setPaused(false)} + > + {toast.message} + {toast.action && ( + + )} + +
  • + ) +} diff --git a/src/admin-next/frame/AdminFrame.tsx b/src/admin-next/frame/AdminFrame.tsx new file mode 100644 index 0000000..23d6981 --- /dev/null +++ b/src/admin-next/frame/AdminFrame.tsx @@ -0,0 +1,345 @@ +import { useEffect, useId, useRef, useState, type AnchorHTMLAttributes, type ReactNode } from 'react' +import { Badge, Kbd, VisuallyHidden } from '../../ui' +import { AdminToaster } from '../feedback/toast' +import { CloseIcon, MenuIcon, SearchIcon } from './icons' +import { drawerOpen, SIDEBAR_QUERY, type DrawerEvent } from './layout' +import { formatBadge, isLocalPath, resolveNav, type AdminNav, type ResolvedItem, type ResolvedLink } from './nav' +import { adminFrameTextEn, type AdminFrameText } from './text' + +/** + * How links are drawn, so any router works: TanStack's , or a plain
    (the default). The + * props always hold `href` (a path the app gave the kit), `data-slot`, and `aria-current` on the page shown. + */ +export type AdminLinkProps = AnchorHTMLAttributes & { href: string; 'data-slot': string; children: ReactNode } +export type AdminLink = (props: AdminLinkProps) => ReactNode +export const plainAdminLink: AdminLink = (props) => + +/** + * `renderLink` for local paths only (isLocalPath): any other href is drawn as plain text, so a value + * from data can never make the admin link or navigate to another site. + */ +export function localLinks(renderLink: AdminLink): AdminLink { + // A disabled link that keeps its name, as the record pager draws a missing record. + return (props) => + isLocalPath(props.href) ? ( + renderLink(props) + ) : ( + + {props.children} + + ) +} + +export type AdminBrand = { + name: string + /** A small mark before the name (an or an SVG, 24 px). Decorative: the name is written. */ + logo?: ReactNode + /** The admin's home. */ + href: string +} + +export type AdminFrameProps = { + nav: AdminNav + /** The page being shown: marks the current nav item and closes the drawer when it changes. */ + pathname: string + brand: AdminBrand + /** The top bar's search (usually ``). */ + search?: ReactNode + /** The right side of the top bar: the account menu, a theme switch. */ + account?: ReactNode + /** Force a scheme; by default the frame follows the device. */ + scheme?: 'light' | 'dark' | undefined + text?: AdminFrameText + renderLink?: AdminLink + children: ReactNode +} + +/** + * The admin's frame (admin-patterns, pattern 1): a top bar, the nav in a column on wide screens and in + * a drawer behind the menu button below 1040 px, and the page. The nav never scrolls with the page. + * The admin theme applies inside it only, so the app's public pages keep their own. + */ +export function AdminFrame({ + nav, + pathname, + brand, + search, + account, + scheme, + text = adminFrameTextEn, + renderLink: anyLink = plainAdminLink, + children, +}: AdminFrameProps) { + const renderLink = localLinks(anyLink) + const resolved = resolveNav(nav, pathname) + const [open, setOpen] = useState(false) + const send = (event: DrawerEvent) => setOpen((now) => drawerOpen(now, event)) + const drawerId = useId() + const mainId = 'admin-main' + + // A new page closes the drawer. + const shown = useRef(pathname) + useEffect(() => { + if (shown.current !== pathname) send('navigated') + shown.current = pathname + }, [pathname]) + + // Growing past the breakpoint turns the drawer back into the column. + useEffect(() => { + const wide = window.matchMedia(SIDEBAR_QUERY) + const onChange = () => wide.matches && send('wide') + wide.addEventListener('change', onChange) + return () => wide.removeEventListener('change', onChange) + }, []) + + return ( +
    + + {text.skip} + +
    + + {renderLink({ + href: brand.href, + 'data-slot': 'admin-brand', + children: ( + <> + {brand.logo && {brand.logo}} + {brand.name} + + ), + })} +
    {search}
    +
    {account}
    +
    +
    + + send('close')} label={text.navigation} closeLabel={text.closeMenu}> + send('navigated')} /> + +
    + + {children} + +
    +
    +
    + ) +} + +/** + * The nav drawer, on the native : modal, so focus stays inside, Esc closes it, and the + * browser puts focus back on the menu button. Its content renders only while open, so the nav isn't + * in the page twice. + */ +function AdminDrawer({ + id, + open, + onClose, + label, + closeLabel, + children, +}: { + id: string + open: boolean + onClose: () => void + label: string + closeLabel: string + children: ReactNode +}) { + const ref = useRef(null) + useEffect(() => { + const dialog = ref.current + if (!dialog) return + if (open && !dialog.open) dialog.showModal() + if (!open && dialog.open) dialog.close() + }, [open]) + return ( + event.target === event.currentTarget && onClose()} + > + {open && ( +
    + + +
    + )} +
    + ) +} + +type NavContentProps = { + nav: ReturnType> + text: AdminFrameText + renderLink: AdminLink + onNavigate?: (() => void) | undefined +} + +function NavContent({ nav, text, renderLink, onNavigate }: NavContentProps) { + const groupId = useId() + return ( + <> +
      + {nav.main.map((item) => ( + + ))} +
    + {nav.groups.map((group) => ( +
    +

    + {group.label} +

    +
      + {group.items.map((item) => ( + + ))} +
    +
    + ))} + {nav.settings && ( +
      + +
    + )} + + ) +} + +function NavItem({ + item, + text, + renderLink, + onNavigate, +}: { + item: ResolvedItem + text: AdminFrameText + renderLink: AdminLink + onNavigate?: (() => void) | undefined +}) { + return ( +
  • + + {item.open && item.children.length > 0 && ( +
      + {item.children.map((child) => ( +
    • + +
    • + ))} +
    + )} +
  • + ) +} + +function NavLink({ + link, + icon, + text, + renderLink, + onNavigate, + sub = false, +}: { + link: ResolvedLink + icon?: ReactNode + text: AdminFrameText + renderLink: AdminLink + onNavigate?: (() => void) | undefined + sub?: boolean +}) { + const badge = link.badge === undefined ? undefined : formatBadge(link.badge, { compact: true }) + return renderLink({ + href: link.to, + 'data-slot': sub ? 'admin-nav-sublink' : 'admin-nav-link', + 'aria-current': link.current ? 'page' : undefined, + onClick: onNavigate, + children: ( + <> + {icon && ( + + )} + {link.label} + {badge !== undefined && ( + + + {typeof link.badge === 'number' ? ( + <> + + {text.pending(formatBadge(link.badge))} + + ) : ( + badge + )} + + + )} + + ), + }) +} + +export type AdminSearchProps = { + /** Opens the search (the ⌘K palette, once it ships; until then the app's own search page). */ + onOpen: () => void + text?: AdminFrameText +} + +/** Typing goes to this element, so single-key shortcuts stay off. */ +export function editable(target: EventTarget | null): boolean { + if (!(target instanceof HTMLElement)) return false + return target.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName) +} + +/** + * The top bar's search: a field-shaped button that opens the search, also with ⌘K (Ctrl+K) anywhere + * and with / outside a text field. On phones it is a search icon. + */ +export function AdminSearch({ onOpen, text = adminFrameTextEn }: AdminSearchProps) { + const latest = useRef(onOpen) + latest.current = onOpen + const [mac, setMac] = useState(false) + useEffect(() => { + setMac(/Mac|iPhone|iPad/.test(navigator.platform)) + const onKey = (event: KeyboardEvent) => { + const palette = event.key.toLowerCase() === 'k' && (event.metaKey || event.ctrlKey) && !event.altKey + // A list page takes / for its own search first (it marks the event handled). + const slash = + event.key === '/' && !event.defaultPrevented && !event.metaKey && !event.ctrlKey && !event.altKey && !editable(event.target) + if (!palette && !slash) return + event.preventDefault() + latest.current() + } + document.addEventListener('keydown', onKey) + return () => document.removeEventListener('keydown', onKey) + }, []) + return ( + + ) +} diff --git a/src/admin-next/frame/PageHeader.tsx b/src/admin-next/frame/PageHeader.tsx new file mode 100644 index 0000000..d21287e --- /dev/null +++ b/src/admin-next/frame/PageHeader.tsx @@ -0,0 +1,92 @@ +import type { ReactNode } from 'react' +import { ChevronLeftIcon, ChevronRightIcon } from './icons' +import { localLinks, plainAdminLink, type AdminLink } from './AdminFrame' +import { adminFrameTextEn, type AdminFrameText } from './text' + +export type PageHeaderProps = { + /** The page's one h1. */ + title: string + /** A status next to the title (a kit/ui ). */ + badge?: ReactNode + /** The list this page belongs to. Give the list's URL with its filters, so Back keeps them. */ + backTo?: { href: string; label?: string | undefined } | undefined + /** The page's main action (a primary } + primaryAction={} + pagination={{ next: '/admin/users/2' }} + />, + ) + expect(html.match(/

    { + test('every language has every word', () => { + const keys = Object.keys(adminFrameTextEn).sort() + for (const text of [adminFrameTextFr, adminFrameTextEs, adminFrameTextHt]) { + expect(Object.keys(text).sort()).toEqual(keys) + expect(text.pending('3')).toContain('3') + } + }) +}) + +describe('links to another site', () => { + test('nav, brand, back and pager links that are not paths on this site are drawn as text', () => { + const html = renderToStaticMarkup( + + + , + ) + expect(html).not.toContain('evil.example') + expect(html).not.toContain('javascript:') + expect(html).toContain('Outside') + expect(html).toContain('Example') + }) +}) diff --git a/src/admin-next/frame/text.ts b/src/admin-next/frame/text.ts new file mode 100644 index 0000000..42c0c62 --- /dev/null +++ b/src/admin-next/frame/text.ts @@ -0,0 +1,80 @@ +/** + * Every word the admin frame shows, in one typed object, in the kit's four languages. An app passes + * its own, or one of these with a few lines changed: `{ ...adminFrameTextEn, search: 'Search orders' }`. + */ +export type AdminFrameText = { + /** The skip link, first on the page. */ + skip: string + /** The menu button that opens the nav on phones and tablets. */ + menu: string + closeMenu: string + /** The nav's name for screen readers. */ + navigation: string + /** The search field's placeholder and the search button's name. */ + search: string + /** Read after a number badge in the nav ("12" → "12 pending"). */ + pending: (count: string) => string + /** The page header's back link when the app gives no label. */ + back: string + previous: string + next: string + /** The toasts' region name, and their close button. */ + notifications: string + dismiss: string +} + +export const adminFrameTextEn: AdminFrameText = { + skip: 'Skip to content', + menu: 'Menu', + closeMenu: 'Close menu', + navigation: 'Admin', + search: 'Search', + pending: (count) => `${count} pending`, + back: 'Back', + previous: 'Previous', + next: 'Next', + notifications: 'Notifications', + dismiss: 'Dismiss', +} + +export const adminFrameTextFr: AdminFrameText = { + skip: 'Aller au contenu', + menu: 'Menu', + closeMenu: 'Fermer le menu', + navigation: 'Administration', + search: 'Rechercher', + pending: (count) => `${count} en attente`, + back: 'Retour', + previous: 'Précédent', + next: 'Suivant', + notifications: 'Notifications', + dismiss: 'Fermer', +} + +export const adminFrameTextEs: AdminFrameText = { + skip: 'Ir al contenido', + menu: 'Menú', + closeMenu: 'Cerrar el menú', + navigation: 'Administración', + search: 'Buscar', + pending: (count) => `${count} pendientes`, + back: 'Volver', + previous: 'Anterior', + next: 'Siguiente', + notifications: 'Notificaciones', + dismiss: 'Cerrar', +} + +export const adminFrameTextHt: AdminFrameText = { + skip: 'Ale nan kontni an', + menu: 'Meni', + closeMenu: 'Fèmen meni an', + navigation: 'Administrasyon', + search: 'Chèche', + pending: (count) => `${count} ap tann`, + back: 'Retounen', + previous: 'Anvan', + next: 'Pwochen', + notifications: 'Notifikasyon', + dismiss: 'Fèmen', +} diff --git a/src/admin-next/list/FilterBar.tsx b/src/admin-next/list/FilterBar.tsx new file mode 100644 index 0000000..5e73285 --- /dev/null +++ b/src/admin-next/list/FilterBar.tsx @@ -0,0 +1,228 @@ +import { useEffect, useRef, useState, type ReactNode, type Ref } from 'react' +import { Button, Input, NativeSelect } from '../../ui' +import { ArrowUpDownIcon, CloseIcon as XIcon } from '../frame/icons' +import { activeFilterCount, changeList, type ListQuery, type ListSpec, type SortDirection } from './query' +import { adminListTextEn, type AdminListText } from './text' + +export type ListFilter = { + /** The filter's key in the list's spec (and the URL). */ + key: string + label: string + options: readonly { value: string; label: string }[] +} + +export type ListSortOption = { + /** A key from the spec's `sorts`. */ + key: string + label: string + /** The words for each direction ("A–Z", "Oldest first"). */ + ascending: string + descending: string +} + +export type FilterBarProps = { + spec: ListSpec + query: ListQuery + onQueryChange: (query: ListQuery) => void + filters?: readonly ListFilter[] | undefined + sortOptions?: readonly ListSortOption[] | undefined + /** The resource's name in the plural ("users"), for the search's name. */ + plural: string + searchRef?: Ref | undefined + /** How long typing waits before the list updates (ms). */ + searchDelay?: number | undefined + /** Beside the search (the phone's Select button). */ + end?: ReactNode + text?: AdminListText | undefined +} + +/** + * The list's search, filters and sort (admin-patterns, pattern 3), each change applied at once. Each + * filter on shows as a chip that its button removes; "Clear all" removes them all. Filters use the + * system's own select until kit/ui's popover lands (then they open in a popover, a sheet on phones). + */ +export function FilterBar({ + spec, + query, + onQueryChange, + filters = [], + sortOptions = [], + plural, + searchRef, + searchDelay = 250, + end, + text = adminListTextEn, +}: FilterBarProps) { + const [search, setSearch] = useState(query.search) + const latest = useRef({ query, onQueryChange }) + latest.current = { query, onQueryChange } + // A change from elsewhere (Clear all, Back) shows in the field; typing isn't overwritten. + useEffect(() => { + setSearch((typed) => (typed.trim() === query.search ? typed : query.search)) + }, [query.search]) + // The list follows the typing, a moment after the last key. + useEffect(() => { + if (search.trim() === latest.current.query.search) return + const timer = setTimeout(() => { + const { query: current, onQueryChange: change } = latest.current + change(changeList(current, { type: 'search', search }, spec)) + }, searchDelay) + return () => clearTimeout(timer) + }, [search, searchDelay, spec]) + + const chips = filters.flatMap((filter) => + (query.filters[filter.key] ?? []).map((value) => ({ + filter, + value, + label: `${filter.label}: ${filter.options.find((option) => option.value === value)?.label ?? value}`, + })), + ) + const sortWords = (option: ListSortOption, direction: SortDirection) => + text.sortBy(option.label, direction === 'asc' ? option.ascending : option.descending) + const sorted = sortOptions.find((option) => option.key === query.sort.key) + const currentSort = sorted ? sortWords(sorted, query.sort.direction) : '' + const multiple = (key: string) => spec.filters?.find((filter) => filter.key === key)?.multiple ?? false + const apply = (next: ListQuery) => onQueryChange(next) + + return ( +
    +
    + setSearch(event.currentTarget.value)} + onKeyDown={(event) => { + if (event.key === 'Enter') apply(changeList(query, { type: 'search', search }, spec)) + if (event.key === 'Escape' && search) { + event.preventDefault() + setSearch('') + apply(changeList(query, { type: 'search', search: '' }, spec)) + } + }} + /> + {end} +
    + {filters.map((filter) => { + const on = query.filters[filter.key] ?? [] + return ( + { + const value = event.currentTarget.value + if (!value) return + const values = multiple(filter.key) ? [...on, value] : [value] + apply(changeList(query, { type: 'filter', key: filter.key, values }, spec)) + }} + > + + {filter.options.map((option) => ( + + ))} + + ) + })} + {sortOptions.length > 0 && ( + // Where the table stacks, the sort shows as a compact "Sort" button: the same native + // select lies over it (invisible), so a tap opens the same options in the system's picker. + + + + { + const [key = '', direction] = event.currentTarget.value.split(':') as [string, SortDirection] + apply(changeList(query, { type: 'sort', key, direction }, spec)) + }} + > + {sortOptions.flatMap((option) => + (['asc', 'desc'] as const).map((direction) => ( + + )), + )} + + + + )} +
    +
    + {activeFilterCount(query) > 0 && ( +
      + {chips.map((chip) => ( + + apply( + changeList( + query, + { + type: 'filter', + key: chip.filter.key, + values: (query.filters[chip.filter.key] ?? []).filter((value) => value !== chip.value), + }, + spec, + ), + ) + } + /> + ))} +
    • + +
    • +
    + )} +
    + ) +} + +/** One filter that is on: its words, and a button that takes it off (focus then moves to the next chip). */ +function FilterChip({ label, text, onRemove }: { label: string; text: AdminListText; onRemove: () => void }) { + return ( +
  • + {label} + +
  • + ) +} diff --git a/src/admin-next/list/ResourceIndex.tsx b/src/admin-next/list/ResourceIndex.tsx new file mode 100644 index 0000000..38fa657 --- /dev/null +++ b/src/admin-next/list/ResourceIndex.tsx @@ -0,0 +1,587 @@ +import { useEffect, useId, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent, type ReactNode } from 'react' +import { flushSync } from 'react-dom' +import { Button, Checkbox, Empty, EmptyActions, EmptyDescription, EmptyTitle, Skeleton, VisuallyHidden } from '../../ui' +import { editable, localLinks, plainAdminLink, type AdminLink } from '../frame/AdminFrame' +import { isLocalPath } from '../frame/nav' +import { ArrowDownIcon, ArrowUpIcon, ChevronLeftIcon, ChevronRightIcon } from '../frame/icons' +import { FilterBar, type ListFilter, type ListSortOption } from './FilterBar' +import { activeFilterCount, changeList, listQueryString, roughCount, type ListQuery, type ListSpec } from './query' +import { isSelected, noSelection, selectedCount, selectionState, togglePage, toggleRange, toggleRow, type Selection } from './selection' +import { adminListTextEn, type AdminListText } from './text' + +export type ListColumn = { + key: string + header: string + cell: (row: Row) => ReactNode + /** Numbers and amounts: `end` (right-aligned, tabular figures). */ + align?: 'start' | 'end' | undefined + /** A key from the spec's `sorts`: the header becomes a sort button. */ + sort?: string | undefined + /** + * Its part when the table stacks into cards (under 600 px of room): `line` is the second line, + * `badge` sits at the card's end, `value` shows "Column: value", `hide` leaves it out. The + * primary column is always the card's title. Default `value`. + */ + phone?: Exclude | undefined +} + +/** Where a cell goes in the stacked layout. */ +export type PhonePart = 'title' | 'line' | 'badge' | 'value' | 'hide' + +export type ListView = { key: string; label: string } + +/** What a bulk action works on: the rows picked, or every row matching the list. */ +export type BulkTarget = { ids: readonly string[]; all: boolean; count: number; query: ListQuery } + +export type BulkAction = { + key: string + label: string + /** Outline red, as kit/ui's destructive button. Confirm it in a dialog before acting. */ + destructive?: boolean | undefined + /** + * Run it. Update the list at once (an optimistic update) and show a toast with Undo; the selection + * clears when it returns. + */ + run: (target: BulkTarget) => void +} + +export type ResourceIndexProps = { + /** The resource's name, for the search, the counts and the table's caption. */ + resource: { singular: string; plural: string; title: string } + /** The list page's path: views and pages link to it with their query. */ + pathname: string + spec: ListSpec + query: ListQuery + /** + * A filter, the search or the sort changed. Put the new query in the URL (`listQueryString`) with + * the router, without a reload; the data follows from the URL. + */ + onQueryChange: (query: ListQuery) => void + views?: readonly ListView[] | undefined + filters?: readonly ListFilter[] | undefined + sortOptions?: readonly ListSortOption[] | undefined + columns: readonly ListColumn[] + /** + * The page's rows; `undefined` only on the first load (skeleton rows). While the next rows load, + * keep giving the previous ones and set `refreshing` (TanStack Query: `placeholderData: + * keepPreviousData`, then `refreshing={isPlaceholderData}`): the table never goes blank. + */ + rows: readonly Row[] | undefined + refreshing?: boolean | undefined + rowId: (row: Row) => string + /** The row's name for its checkbox ("Select Ada Lovelace"). */ + rowLabel: (row: Row) => string + /** The record's page: a path on this site ("/admin/users/42"); anything else is shown as text, not a link. */ + rowHref: (row: Row) => string + /** The column whose cell links to the record; the first by default. */ + primaryColumn?: string | undefined + /** The list's count (exact up to 1,000, then shown as "about"). */ + total?: number | undefined + /** The count is exact (a cheap count): shown as is, never "about". */ + totalExact?: boolean | undefined + /** Keyset cursors of the next and previous pages. */ + pageInfo?: { next?: string | undefined; previous?: string | undefined } | undefined + bulkActions?: readonly BulkAction[] | undefined + /** The first-time empty state: what this list is for and its main action. */ + emptyState?: ReactNode + renderLink?: AdminLink | undefined + text?: AdminListText | undefined +} + +/** + * A list page (admin-patterns, pattern 3; spec items 5–8): views as tabs, the search and filters, + * the table with its bulk bar (one table: it restyles into cards where it has under 600 px), the count and the pages. Every change updates the + * rows in place: the previous rows stay with a thin loading bar until the new ones arrive, and pages + * change with a view transition where the browser has one. Keyboard: / searches, j and k move between + * rows, x (or Space on a row) selects it, Shift adds the range, Enter opens it. + */ +export function ResourceIndex({ + resource, + pathname, + spec, + query, + onQueryChange, + views, + filters, + sortOptions, + columns, + rows, + refreshing = false, + rowId, + rowLabel, + rowHref, + primaryColumn, + total, + totalExact = false, + pageInfo, + bulkActions = [], + emptyState, + renderLink: anyLink = plainAdminLink, + text = adminListTextEn, +}: ResourceIndexProps) { + // Row, view and page links: local paths only (a row's href comes from data). + const renderLink = useMemo(() => localLinks(anyLink), [anyLink]) + const root = useRef(null) + const wrap = useRef(null) + const captionId = useId() + // A table wider than its room scrolls sideways in a named region a keyboard can focus. + const [scrolls, setScrolls] = useState(false) + useEffect(() => { + const element = wrap.current + if (!element || typeof ResizeObserver !== 'function') return + const measure = () => setScrolls(element.scrollWidth > element.clientWidth + 1) + const observer = new ResizeObserver(measure) + observer.observe(element) + const table = element.firstElementChild + if (table) observer.observe(table) + return () => observer.disconnect() + }, []) + const searchRef = useRef(null) + const counted = (n: number) => (totalExact ? n.toLocaleString('en-US') : roughCount(n)) + const href = (next: ListQuery) => `${pathname}${listQueryString(next, spec)}` + const primary = primaryColumn ?? columns[0]?.key + + // Rows on screen: new rows swap in with a view transition when only the page changed. + const [shown, setShown] = useState(rows) + const paged = useRef(false) + const listKey = listQueryString({ ...query, cursor: undefined }, spec) + const pageKey = listQueryString(query, spec) + const lastKeys = useRef({ listKey, pageKey }) + if (lastKeys.current.pageKey !== pageKey) { + paged.current = lastKeys.current.listKey === listKey + lastKeys.current = { listKey, pageKey } + } + useEffect(() => { + if (rows === shown) return + if (refreshing) return + const wasPaged = paged.current + paged.current = false + if (wasPaged && shown) { + swapWithTransition(() => setShown(rows)) + const top = root.current?.getBoundingClientRect().top ?? 0 + if (top < 0) root.current?.scrollIntoView({ block: 'start' }) + } else setShown(rows) + }, [rows, refreshing, shown]) + + const pageIds = useMemo(() => (shown ?? []).map(rowId), [shown, rowId]) + + // Selection: kept across pages, cleared when the list itself changes. + const [selection, setSelection] = useState(noSelection) + const [selecting, setSelecting] = useState(false) + const anchor = useRef(undefined) + useEffect(() => { + setSelection(noSelection) + setSelecting(false) + }, [listKey]) + const count = selectedCount(selection, total) + const state = selectionState(selection, pageIds) + + // One polite announcement at a time: the count after a change, then "3 selected". + const [announcement, setAnnouncement] = useState('') + const announcedList = useRef(listKey) + const totalWords = total === undefined ? '' : text.results(counted(total), resource.plural, resource.singular, total) + useEffect(() => { + if (refreshing || announcedList.current === listKey) return + announcedList.current = listKey + if (totalWords) setAnnouncement(totalWords) + }, [refreshing, listKey, totalWords]) + const lastCount = useRef(0) + useEffect(() => { + if (count !== lastCount.current && count > 0) + setAnnouncement(selection.all ? text.allSelected(counted(count), resource.plural) : text.selected(counted(count))) + lastCount.current = count + }, [count, selection.all, text, resource.plural]) + + const pick = (id: string, range: boolean) => { + // Read the anchor now: the updater runs later, after it has moved to this row. + const from = anchor.current + setSelection((current) => (range ? toggleRange(current, from, id, pageIds) : toggleRow(current, id, pageIds))) + anchor.current = id + } + + // Keyboard: / for the list's search (before the frame's search), j/k between rows, x to select. + useEffect(() => { + const visibleLinks = () => + [...(root.current?.querySelectorAll('[data-row-id] [data-slot="admin-row-link"]') ?? [])].filter( + (link) => link.offsetParent !== null, + ) + const onKey = (event: globalThis.KeyboardEvent) => { + if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey || editable(event.target)) return + if (document.querySelector('dialog[open]')) return + if (event.key === '/') { + event.preventDefault() + searchRef.current?.focus() + return + } + const key = event.key.toLowerCase() + if (key !== 'j' && key !== 'k' && key !== 'x') return + const links = visibleLinks() + const row = (document.activeElement as HTMLElement | null)?.closest('[data-row-id]') + const index = row ? links.findIndex((link) => row.contains(link)) : -1 + if (key === 'x') { + if (!row?.dataset.rowId || !bulkActions.length) return + event.preventDefault() + pick(row.dataset.rowId, event.shiftKey) + return + } + const next = links[key === 'j' ? Math.min(index + 1, links.length - 1) : Math.max(index - 1, 0)] + if (!next) return + event.preventDefault() + next.focus() + next.scrollIntoView({ block: 'nearest' }) + } + document.addEventListener('keydown', onKey, { capture: true }) + return () => document.removeEventListener('keydown', onKey, { capture: true }) + }) + + // A click anywhere on a row opens it, as its link would (not on its checkbox, buttons or links, + // nor when text was being selected). + const openRow = (event: MouseEvent) => { + if (event.button !== 0) return + const target = event.target as HTMLElement + if (target.closest('a, button, input, select, textarea, label')) return + if (window.getSelection()?.toString()) return + const link = event.currentTarget.querySelector('[data-slot="admin-row-link"]') + if (!link) return + // While rows are selected, a click on a row adds it (as Shopify's lists do). + if (selecting || count > 0) { + const id = event.currentTarget.dataset.rowId + if (id) pick(id, event.shiftKey) + return + } + // Only a path on this site is opened: the row's own href must be one (isLocalPath), and the link + // the app's router drew from it must stay on this origin. + const row = shown?.find((candidate) => rowId(candidate) === event.currentTarget.dataset.rowId) + if (!row || !isLocalPath(rowHref(row)) || new URL(link.href, location.href).origin !== location.origin) return + if (event.metaKey || event.ctrlKey) window.open(link.href, '_blank', 'noopener') + else link.click() + } + // Space on a row's link selects the row (Enter still opens it). + const rowKey = (event: KeyboardEvent) => { + if (event.key !== ' ' || !bulkActions.length) return + if ((event.target as HTMLElement).dataset.slot !== 'admin-row-link') return + event.preventDefault() + const id = event.currentTarget.dataset.rowId + if (id) pick(id, event.shiftKey) + } + + const selectable = bulkActions.length > 0 + const loading = shown === undefined + const filtered = activeFilterCount(query) > 0 || query.view !== (spec.views?.[0] ?? query.view) || query.cursor !== undefined + const empty = shown !== undefined && shown.length === 0 + const target = (): BulkTarget => ({ ids: [...selection.ids], all: selection.all, count, query }) + const colSpan = columns.length + (selectable ? 1 : 0) + const pageLink = (cursor: ListQuery['cursor'], label: string, icon: ReactNode) => + cursor ? ( + renderLink({ + href: href(changeList(query, { type: 'page', cursor }, spec)), + 'data-slot': 'admin-list-pager', + 'aria-label': label, + title: label, + children: icon, + }) + ) : ( + + {icon} + + ) + + return ( +
    0 ? '' : undefined} + data-has-select={selectable ? '' : undefined} + > + + {announcement} + + {views && views.length > 1 && ( + + )} +
    +
    + 0 ? ( + + + + ) : undefined + } + /> +
    + +
    + ) +} + +/** A column's part in the stacked (card) layout; the primary column is always the title. */ +function phoneRole(column: ListColumn, primary: string | undefined): PhonePart { + return column.key === primary ? 'title' : (column.phone ?? 'value') +} + +function NoResults({ text, plural, search, onClear }: { text: AdminListText; plural: string; search: string; onClear: () => void }) { + return ( + + {text.noResults(plural)} + {search ? `${text.noResultsSearch(search)} ${text.noResultsHint}` : text.noResultsHint} + + + + + ) +} + +/** Swaps the rows inside a view transition where the browser has one and motion is welcome. */ +function swapWithTransition(update: () => void) { + const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches + if (reduced || typeof document.startViewTransition !== 'function') return update() + document.startViewTransition(() => flushSync(update)) +} diff --git a/src/admin-next/list/index.ts b/src/admin-next/list/index.ts new file mode 100644 index 0000000..187558c --- /dev/null +++ b/src/admin-next/list/index.ts @@ -0,0 +1,5 @@ +export * from './FilterBar' +export * from './query' +export * from './ResourceIndex' +export * from './selection' +export * from './text' diff --git a/src/admin-next/list/list.test.tsx b/src/admin-next/list/list.test.tsx new file mode 100644 index 0000000..8214e60 --- /dev/null +++ b/src/admin-next/list/list.test.tsx @@ -0,0 +1,148 @@ +import { describe, expect, test } from 'bun:test' +import { renderToStaticMarkup } from 'react-dom/server' +import { parseListQuery, type ListSpec } from './query' +import { ResourceIndex, type ListColumn, type ResourceIndexProps } from './ResourceIndex' +import { noSelection, selectedCount, selectionState, togglePage, toggleRange, toggleRow } from './selection' +import { adminListTextEn, adminListTextEs, adminListTextFr, adminListTextHt } from './text' + +const page = ['a', 'b', 'c', 'd', 'e'] + +describe('selection', () => { + test('rows on and off; the header checkbox goes none → some → page', () => { + let selection = toggleRow(noSelection, 'b', page) + expect(selectionState(selection, page)).toBe('some') + selection = togglePage(selection, page) + expect(selectionState(selection, page)).toBe('page') + expect(selectionState(togglePage(selection, page), page)).toBe('none') + expect(selectionState(noSelection, page)).toBe('none') + }) + + test('a range takes the clicked row’s new state, in either direction', () => { + const on = toggleRange(toggleRow(noSelection, 'b', page), 'b', 'd', page) + expect([...on.ids].sort()).toEqual(['b', 'c', 'd']) + const off = toggleRange(on, 'd', 'c', page) + expect([...off.ids]).toEqual(['b']) + // No anchor yet: just the row. + expect([...toggleRange(noSelection, undefined, 'c', page).ids]).toEqual(['c']) + }) + + test('"all matching" counts the list, and leaving it keeps the page', () => { + const all = { ids: new Set(page), all: true } + expect(selectionState(all, page)).toBe('all') + expect(selectedCount(all, 2481)).toBe(2481) + const less = toggleRow(all, 'a', page) + expect(less.all).toBe(false) + expect(selectedCount(less, 2481)).toBe(4) + }) +}) + +type Row = { id: string; name: string; posts: number } +const spec: ListSpec = { views: ['all', 'admins'], filters: [{ key: 'status', options: ['active'] }], sorts: ['name', 'posts'] } +const columns: ListColumn[] = [ + { key: 'name', header: 'Name', sort: 'name', cell: (row) => row.name }, + { key: 'posts', header: 'Posts', align: 'end', sort: 'posts', cell: (row) => row.posts }, +] +const render = (props: Partial> = {}, search = '') => + renderToStaticMarkup( + + resource={{ singular: 'user', plural: 'users', title: 'Users' }} + pathname="/admin/users" + spec={spec} + query={parseListQuery(new URLSearchParams(search), spec)} + onQueryChange={() => {}} + views={[ + { key: 'all', label: 'All' }, + { key: 'admins', label: 'Admins' }, + ]} + columns={columns} + rows={[ + { id: 'u1', name: 'Ada', posts: 3 }, + { id: 'u2', name: 'Grace', posts: 1200 }, + ]} + rowId={(row) => row.id} + rowLabel={(row) => row.name} + rowHref={(row) => `/admin/users/${row.id}`} + total={31_487} + pageInfo={{ next: 'u2' }} + bulkActions={[{ key: 'suspend', label: 'Suspend', run: () => {} }]} + {...props} + />, + ) + +describe('ResourceIndex', () => { + test('a real table: caption, column headers, each row named by its linked primary cell', () => { + const html = render() + expect(html).toMatch(/Users<\/span><\/caption>/) + expect(html).toContain(']*>
    Ada<\/a><\/th>/) + expect(html).toContain('aria-label="Select Ada"') + expect(html).toContain('aria-label="Select all on this page"') + }) + + test('the sorted column says its order; the others have none', () => { + expect(render({}, '?sort=-posts')).toContain('aria-sort="descending"') + expect(render({}, '?sort=-posts').match(/aria-sort=/g)).toHaveLength(1) + }) + + test('views are links that keep the sort, the current one marked', () => { + const html = render({}, '?sort=name&status=active') + expect(html).toContain('href="/admin/users?view=admins&sort=name" data-slot="admin-view"') + expect(html).toMatch(/href="\/admin\/users\?sort=name" data-slot="admin-view" aria-current="page"/) + }) + + test('pages are links with the cursor; no previous page is a disabled link', () => { + const html = render({}, '?status=active') + expect(html).toContain('href="/admin/users?status=active&after=u2" data-slot="admin-list-pager" aria-label="Next page"') + expect(html).toContain('role="link" aria-disabled="true" aria-label="Previous page"') + expect(html).toContain('about 31,500 users') + expect(render({ totalExact: true })).toContain('31,487 users') + }) + + test('the first load shows skeleton rows, busy; no count or pages yet', () => { + const html = render({ rows: undefined, total: undefined }) + expect(html.match(/data-slot="admin-skeleton-row"/g)).toHaveLength(8) + expect(html).toContain('aria-busy="true"') + expect(html).not.toContain('admin-index-footer') + }) + + test('empty: the first-time state, or "no results" with Clear filters when filtered', () => { + const first = render({ rows: [], total: 0, emptyState:

    No users yet

    }) + expect(first).toContain('No users yet') + const filtered = render({ rows: [], total: 0, emptyState:

    No users yet

    }, '?q=zed') + expect(filtered).not.toContain('No users yet') + expect(filtered).toContain('Nothing matches “zed”.') + expect(filtered).toContain('Clear filters') + }) + + test('one table for every width: each cell says its part and its column for the stacked cards', () => { + const html = render() + expect(html).not.toContain('admin-list-rows') + expect(html).toContain('data-phone="title"') + expect(html).toContain('data-phone="value" data-label="Posts"') + expect(html.match(/role="row"/g)).toHaveLength(3) + }) + + test('no bulk actions, no checkboxes', () => { + expect(render({ bulkActions: [] })).not.toContain('type="checkbox"') + }) + + test('a row whose href is not a path on this site gets no link', () => { + for (const bad of ['https://evil.example/x', '//evil.example', '/\\evil.example', 'javascript:alert(1)']) { + const html = render({ rowHref: () => bad }) + expect(html, bad).not.toContain('evil.example') + expect(html, bad).not.toContain('javascript:') + expect(html, bad).not.toContain('data-slot="admin-row-link" href') + expect(html, bad).toContain('Ada') + } + }) +}) + +describe('admin list words', () => { + test('every language has every word', () => { + const keys = Object.keys(adminListTextEn).sort() + for (const text of [adminListTextFr, adminListTextEs, adminListTextHt]) { + expect(Object.keys(text).sort()).toEqual(keys) + expect(text.results('3', 'users', 'user', 3)).toContain('3') + } + }) +}) diff --git a/src/admin-next/list/query.test.ts b/src/admin-next/list/query.test.ts new file mode 100644 index 0000000..051969e --- /dev/null +++ b/src/admin-next/list/query.test.ts @@ -0,0 +1,94 @@ +import { describe, expect, test } from 'bun:test' +import { activeFilterCount, changeList, listQueryString, parseListQuery, roughCount, type ListSpec } from './query' + +const spec: ListSpec = { + views: ['all', 'admins', 'suspended'], + filters: [ + { key: 'status', options: ['active', 'suspended', 'banned'], multiple: true }, + { key: 'role', options: ['user', 'admin'] }, + ], + sorts: ['created', 'name'], +} +const parse = (search: string) => parseListQuery(new URLSearchParams(search), spec) + +describe('admin list query', () => { + test('a plain URL is the default list, and the default list has a plain URL', () => { + const query = parse('') + expect(query).toEqual({ + view: 'all', + search: '', + filters: {}, + sort: { key: 'created', direction: 'desc' }, + cursor: undefined, + }) + expect(listQueryString(query, spec)).toBe('') + }) + + test('round-trips every part, in a stable order', () => { + const url = '?view=admins&q=ada&status=active%2Cbanned&role=admin&sort=name&after=abc_123' + expect(listQueryString(parse(url), spec)).toBe(url) + expect(parse('?sort=-name').sort).toEqual({ key: 'name', direction: 'desc' }) + }) + + test('drops what the spec does not allow', () => { + const query = parse('?view=evil&status=active&status=nope&role=user,admin&sort=password&after=