diff --git a/CHANGELOG.md b/CHANGELOG.md index 26dd90c..973cfe7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,17 @@ All notable changes to `@jgb-solutions/kit`. Versions follow semver. +## Unreleased (0.9.0) + +- `kit/ui`: patterns for content sites, styled by the new `@jgb-solutions/kit/ui/patterns.css` (load it after `core.css`; a page without them, such as the admin, doesn't carry their rules): + - `Rail` and its parts (`RailHeader`, `RailHeading`, `RailTitle`, `RailDescription`, `RailMore`, `RailArrows`, `RailTrack`, `RailItem`): a row that scrolls sideways with no scrollbar and its two arrows at the top right on every screen size, compact on touch screens with a 44 px touch area, each disabled at its end, both hidden while the whole row fits. `layout="inline"` puts a row of chips and its arrows on one line. Right-to-left pages work; people who ask for less motion get instant scrolling. + - `ShareButtons` (with `shareLinks` and `shareEmailHref`): WhatsApp, Facebook, X, Telegram, Pinterest (when the page has a picture), LinkedIn, email, copy link, and the phone's share sheet (first on a phone, last on a wide screen). On a phone the buttons wrap into even rows, never one alone on a line. Plain links, no third-party script, icons from one cached file (`@jgb-solutions/kit/ui/share-icons.svg`). The email link is written between Cloudflare's `` comments, so its email obfuscation leaves it a working link without JavaScript. + - `AdSlot` (with `pickHouseAd`): a reserved height, a label, and a house ad (the product's name, one line, an optional button, and its icon or initials large in a tall slot's corner) that shows until the ad network marks its element as filled (`data-ad-status="filled"`), by CSS alone, so a slot is never a blank box. `enabled={false}` renders nothing and reserves nothing. +- `kit/ui`: `Poster`, a cover, poster or logo that keeps its shape (`square`, `portrait`, `wide`) and shows the title's initials on a colour made from the title when there is no picture or it fails to load. +- **Breaking:** `UiText` gains five strings, `shareOn` (with `{network}`), `shareByEmail`, `copyLink`, `linkCopied` and `shareMore`. The four shipped languages have them; an app that builds its own `UiText` object must add the five or it no longer type-checks. +- **To know when adopting:** the patterns' rules are in `ui/patterns.css`, not in `core.css`: import both. Share buttons ship in one quiet style; a network's brand colour is the app's to set, through `--share-tone` on that button. +- `kit/testing` (new): checks an app's browser tests run inside the page, so every app holds the same line. `checkTouchTargets` (every control has a 44 px touch area, no neighbour's touch area covers a button, no text under 12 px) and `adsAfterContent` (an ad never comes before the first block of content, or before the third search result). No dependency: pass them to your test runner's `page.evaluate`. + ## 0.9.0-beta.2 A beta, published under npm's `next` tag; `latest` stays 0.8.1. diff --git a/README.md b/README.md index b6c30d9..e61a5b5 100644 --- a/README.md +++ b/README.md @@ -483,6 +483,64 @@ Plain HTML elements with `data-slot`, `data-variant` and state attributes, style - **Words** in the four languages every app ships: `uiTextEn`, `uiTextFr`, `uiTextEs`, `uiTextHt` (each its own export, so a page bundles one). - **Content policy.** The stylesheet has no images and no inline styles: a strict Content-Security-Policy needs no exception for it. +#### Patterns for content sites + +Parts a media or reference site is built from, in `kit/ui` like the rest (no behaviour library), with their own stylesheet so a page without them doesn't carry their rules: + +```css +@import '@jgb-solutions/kit/ui/core.css' layer(components); +@import '@jgb-solutions/kit/ui/patterns.css' layer(components); +``` + +- **`Rail`**: a row that scrolls sideways. No scrollbar; two arrows at the top right on every screen size (compact on touch screens, with a 44 px touch area), each disabled at its end, both hidden while the whole row fits. Swiping, the trackpad and the keyboard still scroll it, and it stays a real list. + + ```tsx + + + + New this week + + }>{text.seeAll} + + + + {items.map((item) => ( + … + ))} + + + ``` + + `layout="inline"` puts a row of chips and its arrows on one line. `--rail-item-width` and `--rail-gap` size it. + +- **`ShareButtons`**: WhatsApp, Facebook, X, Telegram, Pinterest (when the page has a picture), LinkedIn, email, copy link, then the phone's share sheet where the browser has one. Plain links that open in a new tab; no third-party script. Serve the icons once: import `@jgb-solutions/kit/ui/share-icons.svg` as a URL with your bundler and pass it as `sprite`. To colour one network, set `--share-tone` on `[data-slot='share-button'][data-network='…']` (check its contrast in both schemes). + + The email link is written between `` comments: Cloudflare's email obfuscation otherwise rewrites every `mailto:` link into one that works only after its script runs. + +- **`Poster`**: a cover (`square`), an upright poster (`portrait`) or a still (`wide`). The box keeps its shape before the picture arrives, and shows the title's initials on a colour made from the title when there is none. + +- **`AdSlot`**: the frame around one ad. It reserves the height (`banner`, `leaderboard`, `rectangle`, `fluid`, or `--ad-height`), so an ad never moves the page, and shows a `house` ad (one of your own products, a plain link) until the network marks its element as filled (`data-ad-status="filled"`, which AdSense sets). `enabled={false}` renders nothing and reserves nothing. `pickHouseAd(ads, path)` gives a page the same house ad every time. Needs `:has()` (every browser on our floor has it). + + Where slots go is the page's job: never before the first block of real content, and never before the third result of a search. + +### `@jgb-solutions/kit/testing`: checks for an app's browser tests + +Self-contained functions a test runner sends into the page, so every app holds the same line. No dependency. + +```ts +import { adsAfterContent, checkTouchTargets } from '@jgb-solutions/kit/testing' + +// At a phone size, on a touch device profile. +const report = await page.evaluate(checkTouchTargets, { within: 'header, main' }) +expect(report.small).toEqual([]) // controls a finger can't reach (under 44 px each way) +expect(report.covered).toEqual([]) // buttons under a neighbour's touch area +expect(report.tiny).toEqual([]) // text under 12 px + +expect(await page.evaluate(adsAfterContent, { before: 1 })).toEqual([]) +``` + +A control counts by its box or by the touch area a `::before` / `::after` gives it. Links inside a sentence are left out. + ### `@jgb-solutions/kit/ui/overlays`: menus, popovers, tooltips (React 19, UI SDK) What opens next to a button, on [UI SDK](https://ui-sdk.dev)'s behaviours (focus, dismissal, positioning, ARIA) and styled by `@jgb-solutions/kit/ui/overlays.css` from the same tokens: `Menu` (with `AnchoredMenu`), `Popover` and `Tooltip`, each with its parts. Needs `@ui-sdk/core` and `@ui-sdk/react` at the exact version in `peerDependencies` (optional peers: apps that don't import this module don't install them). Dialogs and drawers are not here: they are in `kit/ui`, on the browser's own ``. diff --git a/e2e/patterns.spec.ts b/e2e/patterns.spec.ts new file mode 100644 index 0000000..762d45e --- /dev/null +++ b/e2e/patterns.spec.ts @@ -0,0 +1,180 @@ +import { expect, test, type Page } from '@playwright/test' +import { adsAfterContent, checkTouchTargets } from '../src/testing' +import { PAGES } from '../showcase/site' + +/** + * kit/ui's patterns for content sites, on the showcase's Patterns page: rows with arrows at the top + * right, share buttons, posters and ad slots. What the browser does is the point here (scrolling, + * `:has()`, the clipboard), so these also run in Firefox and WebKit. + */ +const BASE = 'http://127.0.0.1:4402' +const alive = (page: Page) => expect(page.locator('html[data-alive]')).toHaveCount(1) + +async function open(page: Page) { + await page.goto(`${BASE}/patterns/`) + await alive(page) +} +const rail = (page: Page, title: string) => page.locator('[data-slot="rail"]').filter({ has: page.getByRole('heading', { name: title }) }) + +test('a row that overflows has its arrows at the top right, each disabled at its end, and no scrollbar', async ({ page }) => { + await open(page) + const row = rail(page, 'New this week') + const track = row.locator('[data-slot="rail-track"]') + const previous = row.getByRole('button', { name: 'Previous: New this week' }) + const next = row.getByRole('button', { name: 'Next: New this week' }) + + await expect(next).toBeEnabled() + await expect(previous).toBeDisabled() + expect(await track.evaluate((el) => getComputedStyle(el).scrollbarWidth)).toBe('none') + // Top right: the arrows sit above the row and end at its right edge. + const [arrowBox, trackBox] = await Promise.all([next.boundingBox(), track.boundingBox()]) + expect(arrowBox!.y + arrowBox!.height).toBeLessThanOrEqual(trackBox!.y + 1) + expect(Math.abs(arrowBox!.x + arrowBox!.width - (trackBox!.x + trackBox!.width))).toBeLessThanOrEqual(8) + + await next.click() + await expect(previous).toBeEnabled() + // The row glides there (instantly for people who ask for less motion). + await expect.poll(() => track.evaluate((el) => el.scrollLeft)).toBeGreaterThan(50) + // To the far end: the forward arrow gives up, the back one still works. + await track.evaluate((el) => el.scrollTo({ left: el.scrollWidth, behavior: 'instant' })) + await expect(next).toBeDisabled() + await previous.click() + await expect(next).toBeEnabled() +}) + +test('a row that fits shows no arrows and keeps their space', async ({ page }) => { + await open(page) + const arrows = rail(page, 'A row that fits').locator('[data-slot="rail-arrows"]') + await expect(arrows).toHaveAttribute('data-idle', '') + await expect(arrows).toBeHidden() + expect((await arrows.boundingBox())!.width).toBeGreaterThan(40) +}) + +test('a row is a list a keyboard can walk: Tab reaches each card, and the row follows the focus', async ({ page, browserName }) => { + test.skip(browserName === 'webkit', 'Safari tabs to links only with its "Press Tab to highlight each item" setting on') + await open(page) + const row = rail(page, 'New this week') + await expect(row.getByRole('listitem')).toHaveCount(10) + const links = row.locator('[data-slot="card-link"]') + await links.first().focus() + for (let step = 0; step < 9; step++) await page.keyboard.press('Tab') + await expect(links.last()).toBeFocused() + await expect(links.last()).toBeInViewport() +}) + +test('right to left: forward still means further along the row', async ({ page }) => { + await open(page) + await page.evaluate(() => document.documentElement.setAttribute('dir', 'rtl')) + const row = rail(page, 'New this week') + const track = row.locator('[data-slot="rail-track"]') + await expect(row.getByRole('button', { name: 'Next: New this week' })).toBeEnabled() + await row.getByRole('button', { name: 'Next: New this week' }).click() + await expect(row.getByRole('button', { name: 'Previous: New this week' })).toBeEnabled() + await expect.poll(() => track.evaluate((el) => el.scrollLeft)).toBeLessThan(-50) +}) + +test('share buttons are plain links in the one order; copy says so', async ({ page, context, browserName }) => { + await open(page) + const share = page.locator('[data-slot="share"]').first() + const networks = await share + .locator('[data-slot="share-button"]') + .evaluateAll((buttons) => buttons.map((button) => button.getAttribute('data-network'))) + expect(networks.slice(0, 8)).toEqual(['whatsapp', 'facebook', 'x', 'telegram', 'pinterest', 'linkedin', 'email', 'copy']) + await expect(share.getByRole('link', { name: 'Share on WhatsApp' })).toHaveAttribute( + 'href', + /^https:\/\/wa\.me\/\?text=Morning%20Jazz%20https%3A%2F%2Fexample\.com/, + ) + await expect(share.getByRole('link', { name: 'Share by email' })).toHaveAttribute('href', /^mailto:\?subject=Morning%20Jazz&body=/) + // The icons come from the one file, and they drew. + expect( + await share + .locator('svg use') + .first() + .evaluate((use) => (use as SVGUseElement).href.baseVal), + ).toBe('/share-icons.svg#whatsapp') + + // Copy says so whichever way the browser allows it: its clipboard API, or a selected field. + if (browserName === 'chromium') await context.grantPermissions(['clipboard-read', 'clipboard-write']) + await share.getByRole('button', { name: 'Copy link' }).click() + await expect(share.getByRole('status')).toHaveText('Link copied') + // Only Chromium lets a test read the clipboard back. + if (browserName === 'chromium') + expect(await page.evaluate(() => navigator.clipboard.readText())).toBe('https://example.com/shows/morning-jazz') +}) + +test('on a phone the share buttons wrap into even rows: none is left alone on a line', async ({ page }, testInfo) => { + test.skip(!['phone', 'iphone'].includes(testInfo.project.name), 'narrow screens') + await open(page) + for (const share of await page.locator('[data-slot="share"]').all()) { + const tops = await share + .locator('[data-slot="share-button"]') + .evaluateAll((buttons) => + buttons + .filter((button) => getComputedStyle(button).visibility !== 'hidden') + .map((button) => Math.round(button.getBoundingClientRect().top)), + ) + const rows = [...new Set(tops)].map((top) => tops.filter((value) => value === top).length) + expect(rows.length, `rows of ${rows.join(' + ')}`).toBeLessThanOrEqual(2) + expect(Math.max(...rows) - Math.min(...rows), `rows of ${rows.join(' + ')}`).toBeLessThanOrEqual(1) + } + // Where the browser has a share sheet, its button comes first. + const sheet = page.locator('[data-slot="share"]').first().locator('[data-slot="share-sheet"]:not([data-pending])') + if (await sheet.count()) { + const first = await page.locator('[data-slot="share"]').first().locator('[data-slot="share-button"]').first().boundingBox() + const box = await sheet.boundingBox() + expect(box!.y).toBeLessThanOrEqual(first!.y) + expect(box!.x).toBeLessThanOrEqual(first!.x) + } +}) + +test('an ad slot shows the house ad until an ad fills it, at the same height', async ({ page }) => { + await open(page) + const slot = page.locator('[data-slot="ad-slot"]').first() + const house = slot.locator('[data-slot="ad-house"]') + await expect(slot).toHaveAccessibleName('Advertisement') + await expect(house).toBeVisible() + await expect(house).toContainText('Also from us') + const before = (await slot.boundingBox())!.height + expect(before).toBeGreaterThanOrEqual(250) + + // What an ad network does when it fills its element. + await slot.locator('[data-slot="ad-frame"]').evaluate((frame) => { + const unit = document.createElement('div') + unit.setAttribute('data-slot', 'ad-unit') + unit.innerHTML = '' + frame.append(unit) + }) + await expect(house).toBeHidden() + expect((await slot.boundingBox())!.height).toBe(before) +}) + +test('no ad comes before the content, and the check says so when one does', async ({ page }) => { + await open(page) + expect(await page.evaluate(adsAfterContent, {})).toEqual([]) + await page.evaluate(() => { + const main = document.querySelector('main')! + main.prepend(document.querySelector('[data-slot="ad-slot"]')!) + }) + expect(await page.evaluate(adsAfterContent, {})).toEqual(['the first ad slot comes after 0 block(s) of content; 1 needed']) +}) + +test('a poster with no picture shows its initials in its shape', async ({ page }) => { + await open(page) + const poster = page.getByRole('img', { name: 'Paper Moon' }) + await expect(poster).toContainText('PM') + const box = (await poster.boundingBox())! + expect(box.height / box.width).toBeCloseTo(1.5, 1) +}) + +for (const info of PAGES) { + test(`${info.path}: on a phone every control has a 44 px touch area and no text is under 12 px`, async ({ page }, testInfo) => { + test.skip(!['phone', 'iphone'].includes(testInfo.project.name), 'touch screens') + await page.goto(`${BASE}${info.path}`) + await alive(page) + // A link-style button reads as a link in a line of text, and follows the line like one. + const report = await page.evaluate(checkTouchTargets, { within: 'header, main', ignore: '[data-variant="link"]' }) + expect(report.small, 'controls under 44 px').toEqual([]) + expect(report.covered, "buttons under a neighbour's touch area").toEqual([]) + expect(report.tiny, 'text under 12 px').toEqual([]) + }) +} diff --git a/package.json b/package.json index f7876fd..faeaabe 100644 --- a/package.json +++ b/package.json @@ -119,6 +119,12 @@ "import": "./dist/ui/overlays.js" }, "./ui/overlays.css": "./dist/ui/overlays.css", + "./ui/patterns.css": "./dist/ui/patterns.css", + "./ui/share-icons.svg": "./dist/ui/share-icons.svg", + "./testing": { + "types": "./dist/testing.d.ts", + "import": "./dist/testing.js" + }, "./package.json": "./package.json" }, "engines": { diff --git a/playground/specimens.tsx b/playground/specimens.tsx index 6140c1d..b826c34 100644 --- a/playground/specimens.tsx +++ b/playground/specimens.tsx @@ -1,6 +1,7 @@ import type { ReactNode } from 'react' import { checkTheme, COLOR_TOKENS, cssVar, FONT_SIZES, scaleCss, themeCss } from '../src/tokens' import { + AdSlot, Alert, AlertActions, AlertDescription, @@ -34,8 +35,20 @@ import { Input, Kbd, NativeSelect, + pickHouseAd, + Poster, Radio, + Rail, + RailArrows, + RailDescription, + RailHeader, + RailHeading, + RailItem, + RailMore, + RailTitle, + RailTrack, Separator, + ShareButtons, Skeleton, Spinner, Switch, @@ -457,6 +470,131 @@ function Cards() { ) } +/** Where the page serves the share buttons' icons (the showcase copies the kit's file there). */ +const SHARE_ICONS = '/share-icons.svg' + +const SHOWS = [ + ['Morning Jazz', 'Live · jazz'], + ['Night Drive', 'Synthwave'], + ['The Long Read', 'Podcast · weekly'], + ['Harbour News', 'Live · news'], + ['Slow Sundays', 'Acoustic'], + ['Deep Field', 'Science'], + ['Corner Kick', 'Sport · live'], + ['Paper Moon', 'Film · 1973'], + ['Small Hours', 'Ambient'], + ['Open Mic', 'Comedy'], +] as const +const GENRES = ['All', 'Jazz', 'News', 'Sport', 'Talk', 'Classical', 'Electronic', 'Kids', 'Culture', 'Comedy', 'Science', 'Film'] +const HOUSE_ADS = [ + { href: '#pocket-tools', name: 'Pocket Tools', tagline: 'Free tools that run in your browser', cta: 'Try it' }, + { href: '#field-notes', name: 'Field Notes', tagline: 'Top ten lists about nearly everything', cta: 'Read' }, +] + +function Rows() { + return ( +
+ + + + }>{t('New this week')} + {t('Swipe, use the arrows, or Tab through the cards')} + + }>{text.seeAll} + + + + {SHOWS.map(([title, hint]) => ( + + + + + }> + {t(title)} + + {t(hint)} + + + + ))} + + + + + {GENRES.map((genre, index) => ( + + }> + {t(genre)} + + + ))} + + + + + + + }>{t('A row that fits')} + {t('No arrows when nothing is hidden; their space stays')} + + + + + {GENRES.slice(1, 3).map((genre) => ( + + }>{t(genre)} + + ))} + + +
+ ) +} + +function Posters() { + return ( +
+
+ + + + + +
+
+ ) +} + +function Sharing() { + const page = { url: 'https://example.com/shows/morning-jazz', title: 'Morning Jazz', image: 'https://example.com/morning-jazz.jpg' } + return ( +
+
+ +
+
+ +
+
+ ) +} + +function Ads() { + return ( +
+
+ + +
+
+ ) +} + function EmptyState() { return (
@@ -655,4 +793,4 @@ export function specimenCss({ theme, scoped = false }: { theme?: LookName | null ].join('\n') } -export { Alerts, Badges, Buttons, Cards, EmptyState, Forms, Gallery, Report, Themes, Tokens, Words } +export { Ads, Alerts, Badges, Buttons, Cards, EmptyState, Forms, Gallery, Posters, Report, Rows, Sharing, Themes, Tokens, Words } diff --git a/playground/ui.css b/playground/ui.css index 077bd38..3385194 100644 --- a/playground/ui.css +++ b/playground/ui.css @@ -174,3 +174,27 @@ body, margin: 0; color: var(--muted-foreground); } + +/* Patterns: rows, posters, ad slots. */ +.demo-rail { + --rail-item-width: auto; +} +.demo-rail + .demo-rail { + margin-top: var(--space-6); +} +.demo-rail-card { + width: 13rem; + overflow: hidden; +} +.demo-posters { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(6.5rem, 9rem)); + align-items: end; + gap: var(--space-4); +} +.demo-ads { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(min(100%, 18.75rem), 1fr)); + align-items: start; + gap: var(--space-6); +} diff --git a/playwright.config.ts b/playwright.config.ts index accb7df..c99308e 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -7,8 +7,8 @@ import { defineConfig, devices } from '@playwright/test' */ const PORT = 4401 const SHOWCASE_PORT = 4402 -/** The tests of what the browser itself does: dialogs and drawers, and the overlays next to them. */ -const OVERLAY_TESTS = /(overlays|dialog)\.spec\.ts$/ +/** The tests of what the browser itself does: dialogs and drawers, the overlays next to them, and rows that scroll. */ +const OVERLAY_TESTS = /(overlays|dialog|patterns)\.spec\.ts$/ export default defineConfig({ testDir: './e2e', fullyParallel: true, diff --git a/scripts/build-showcase.ts b/scripts/build-showcase.ts index 3275536..f127b98 100644 --- a/scripts/build-showcase.ts +++ b/scripts/build-showcase.ts @@ -69,7 +69,13 @@ const entryUrl = asset(entry.path) // 2. One stylesheet: the scales, every theme under its own `data-kit-theme`, the kit's sheets, the page's own. const sheetsIn = (dir: string) => [...new Glob('*.css').scanSync({ cwd: dir })].sort().map((name) => `${dir}/${name}`) -const sources = [...sheetsIn('src/ui/styles'), ...sheetsIn('src/ui/overlay/styles'), 'playground/ui.css', 'showcase/showcase.css'] +const sources = [ + ...sheetsIn('src/ui/styles'), + ...sheetsIn('src/ui/patterns/styles'), + ...sheetsIn('src/ui/overlay/styles'), + 'playground/ui.css', + 'showcase/showcase.css', +] const css = [ // UI SDK's own rules go in this layer, under everything of ours (its docs ask for this first line). '@layer ui-sdk;', @@ -195,6 +201,8 @@ await Bun.write( `${OUT}/favicon.svg`, '\n', ) +// The share buttons' icons, where the specimens look for them. +await Bun.write(`${OUT}/share-icons.svg`, Bun.file('src/ui/share-icons.svg')) for (const file of new Glob('**/*').scanSync({ cwd: 'showcase/public', onlyFiles: true })) await Bun.write(`${OUT}/${file}`, Bun.file(`showcase/public/${file}`)) diff --git a/scripts/build.ts b/scripts/build.ts index 67970de..8ac970e 100644 --- a/scripts/build.ts +++ b/scripts/build.ts @@ -44,6 +44,17 @@ const uiSheets = readdirSync('src/ui/styles') .filter((name) => name.endsWith('.css')) .sort() await Bun.write('dist/ui/core.css', (await Promise.all(uiSheets.map((name) => Bun.file(`src/ui/styles/${name}`).text()))).join('\n')) +// kit/ui's patterns for content sites (rails, share buttons, ad slots): their own stylesheet, so a +// page without them (the admin) doesn't carry their rules. +const patternSheets = readdirSync('src/ui/patterns/styles') + .filter((name) => name.endsWith('.css')) + .sort() +await Bun.write( + 'dist/ui/patterns.css', + (await Promise.all(patternSheets.map((name) => Bun.file(`src/ui/patterns/styles/${name}`).text()))).join('\n'), +) +// The share buttons' icons: one file an app serves and the browser caches. +await Bun.write('dist/ui/share-icons.svg', Bun.file('src/ui/share-icons.svg')) // kit/ui/overlays: its own stylesheet, loaded with the overlays' code, after first paint. const overlaySheets = readdirSync('src/ui/overlay/styles') .filter((name) => name.endsWith('.css')) diff --git a/scripts/check-package.ts b/scripts/check-package.ts index a748514..f1c2a97 100644 --- a/scripts/check-package.ts +++ b/scripts/check-package.ts @@ -44,6 +44,8 @@ const IMPORTS: Record = { './ui': ['react'], // The one module that carries a behaviour library: an app loads it after first paint. './ui/overlays': ['react', '@ui-sdk/react'], + // Checks a test runner sends into the page: no import at all, so they stay self-contained. + './testing': [], } const OPTIONAL_PEERS = [ 'better-auth', @@ -143,6 +145,7 @@ for (const path of [ 'dist/tokens/themes/neutral.css', 'dist/tokens/themes/admin.css', 'dist/ui/core.css', + 'dist/ui/share-icons.svg', ]) if (!existsSync(path)) problems.push(`${path} is missing (bun run build)`) for (const path of ['dist/tokens.css', 'dist/tokens/themes/neutral.css', 'dist/tokens/themes/admin.css'].filter((file) => @@ -155,7 +158,7 @@ for (const path of ['dist/tokens.css', 'dist/tokens/themes/neutral.css', 'dist/t for (const [, property] of css.matchAll(/[{;]\s*([\w-]+)\s*:/g)) if (!property!.startsWith('--') && property !== 'color-scheme') problems.push(`${path}: sets ${property}, which is not a token`) } -for (const sheet of ['dist/ui/core.css', 'dist/ui/overlays.css']) { +for (const sheet of ['dist/ui/core.css', 'dist/ui/overlays.css', 'dist/ui/patterns.css']) { if (!existsSync(sheet)) { problems.push(`${sheet} is missing (bun run build)`) continue @@ -194,6 +197,12 @@ if (existsSync('dist/ui.js')) { 'ConfirmDialog', 'Drawer', 'DialogClose', + 'Rail', + 'RailTrack', + 'RailArrows', + 'Poster', + 'ShareButtons', + 'AdSlot', 'uiTextEn', 'uiTextFr', 'uiTextEs', @@ -242,7 +251,7 @@ if (pack.exitCode !== 0) problems.push(`bun pm pack failed: ${pack.stderr.toStri const files = [...pack.stdout.toString().matchAll(/^packed\s+\S+\s+(\S+)$/gm)].map((match) => match[1]!) if (files.length === 0) problems.push('bun pm pack listed no files') const publishable = - /^(dist\/([\w-]+\/)*[\w.-]+\.(js|d\.ts)|dist\/(admin|account)\/styles\.css|dist\/tokens\.css|dist\/tokens\/(tailwind|themes\/(neutral|admin))\.css|dist\/ui\/(core|overlays)\.css|README\.md|CHANGELOG\.md|LICENSE|package\.json)$/ + /^(dist\/([\w-]+\/)*[\w.-]+\.(js|d\.ts)|dist\/(admin|account)\/styles\.css|dist\/tokens\.css|dist\/tokens\/(tailwind|themes\/(neutral|admin))\.css|dist\/ui\/(core|overlays|patterns)\.css|dist\/ui\/share-icons\.svg|README\.md|CHANGELOG\.md|LICENSE|package\.json)$/ for (const file of files) if (!publishable.test(file)) problems.push(`the tarball would include ${file}`) const forbidden: [RegExp, string][] = [ diff --git a/scripts/check-size.ts b/scripts/check-size.ts index 93fef73..b53e29d 100644 --- a/scripts/check-size.ts +++ b/scripts/check-size.ts @@ -21,6 +21,7 @@ const FILES: [path: string, budget: number][] = [ ['dist/tokens/tailwind.css', 1 * 1024], ['dist/ui/core.css', 8 * 1024], ['dist/ui/overlays.css', 4 * 1024], + ['dist/ui/patterns.css', 4 * 1024], ] for (const [path, budget] of FILES) { if (!existsSync(path)) { @@ -64,7 +65,14 @@ await cost('kit/ui: Field + Input alone', keep('Field, FieldLabel, FieldError, I // Dialogs are the browser's own : no behaviour library, so a confirm is part of the first load. await cost('kit/ui: ConfirmDialog alone', keep('ConfirmDialog'), 3 * 1024) await cost('kit/ui: Dialog and its parts', keep('Dialog, DialogHeader, DialogTitle, DialogBody, DialogFooter, DialogClose'), 3 * 1024) -await cost('kit/ui: every core component', `import * as all from ${ui}; globalThis.__keep = Object.values(all)`, 6 * 1024) +await cost( + 'kit/ui: Rail and its parts', + keep('Rail, RailHeader, RailHeading, RailTitle, RailMore, RailArrows, RailTrack, RailItem'), + 2 * 1024, +) +await cost('kit/ui: ShareButtons alone', keep('ShareButtons'), 2 * 1024) +await cost('kit/ui: AdSlot alone', keep('AdSlot, pickHouseAd'), 1.5 * 1024) +await cost('kit/ui: every core component', `import * as all from ${ui}; globalThis.__keep = Object.values(all)`, 9 * 1024) await cost( 'kit/tokens: nativeTheme + a theme', `import { nativeTheme, neutralTheme } from ${tokens}; globalThis.__keep = [nativeTheme, neutralTheme]`, diff --git a/showcase/app.tsx b/showcase/app.tsx index f6af8b9..cc9df9b 100644 --- a/showcase/app.tsx +++ b/showcase/app.tsx @@ -1,6 +1,22 @@ import { useEffect, useState, type ReactNode } from 'react' import { OverlayButtons } from '../playground/overlay-openers' -import { Alerts, Badges, Buttons, Cards, configure, EmptyState, Forms, Report, Themes, Tokens, Words } from '../playground/specimens' +import { + Ads, + Alerts, + Badges, + Buttons, + Cards, + configure, + EmptyState, + Forms, + Posters, + Report, + Rows, + Sharing, + Themes, + Tokens, + Words, +} from '../playground/specimens' import { LOOK_NAMES, lookOf, LOOKS, type LookName } from '../playground/ui-themes' import { Button, @@ -256,6 +272,14 @@ function Intro({ page }: { page: PageId }) { Escape closes them. Menus, popovers and tooltips open next to their button and load after the first paint.

) + if (page === 'patterns') + return ( +

+ Parts for content sites. A row scrolls sideways with its arrows at the top right, on every screen size. Share buttons are plain + links. A poster shows initials until its picture arrives. An ad slot holds its height and shows one of your own products when no ad + fills it. +

+ ) if (page === 'themes') return

One set of components, five faces. Each column below carries its own theme; nothing else differs between them.

return

What every component reads. A theme sets the colours, one radius and the fonts; the scales are the same everywhere.

@@ -282,6 +306,15 @@ function Content({ page }: { page: PageId }) {
) + if (page === 'patterns') + return ( + <> + + + + + + ) if (page === 'themes') return return ( <> diff --git a/showcase/showcase.css b/showcase/showcase.css index 8bb5b0c..48fd7db 100644 --- a/showcase/showcase.css +++ b/showcase/showcase.css @@ -37,6 +37,21 @@ line-height: var(--line-height-lg); text-decoration: none; } +/* The header's row is short on a phone: the name keeps its look and takes 44 px to touch. */ +@media (pointer: coarse) { + .site-brand { + position: relative; + } + .site-brand::after { + content: ''; + position: absolute; + top: 50%; + left: 0; + width: 100%; + height: max(100%, var(--hit-min)); + translate: 0 -50%; + } +} .site-wide { flex: 1; display: flex; diff --git a/showcase/site.ts b/showcase/site.ts index 0e94712..03fb66f 100644 --- a/showcase/site.ts +++ b/showcase/site.ts @@ -14,7 +14,7 @@ export const SITE = { packageName: '@jgb-solutions/kit', } as const -export type PageId = 'home' | 'components' | 'overlays' | 'themes' | 'tokens' +export type PageId = 'home' | 'components' | 'overlays' | 'patterns' | 'themes' | 'tokens' export type PageInfo = { id: PageId /** Always with a trailing slash: it is a folder with an index.html. */ @@ -55,6 +55,15 @@ export const PAGES: readonly PageInfo[] = [ description: 'Open each one: dialogs, confirm dialogs and drawers on the browser’s own dialog element, and menus, popovers and tooltips that load after the first paint.', }, + { + id: 'patterns', + path: '/patterns/', + nav: 'Patterns', + heading: 'Rows, sharing and ad slots', + title: 'Patterns: rows, share buttons, posters and ad slots | JGB Solutions UI', + description: + 'Parts for content sites: rows that scroll sideways with arrows at the top right, share buttons as plain links, posters with a fallback, and ad slots that never show a blank box.', + }, { id: 'themes', path: '/themes/', diff --git a/src/testing.ts b/src/testing.ts new file mode 100644 index 0000000..7806fef --- /dev/null +++ b/src/testing.ts @@ -0,0 +1,7 @@ +export { + adsAfterContent, + checkTouchTargets, + type AdPlacementOptions, + type TouchTargetOptions, + type TouchTargetReport, +} from './testing/checks' diff --git a/src/testing/checks.ts b/src/testing/checks.ts new file mode 100644 index 0000000..ac3539b --- /dev/null +++ b/src/testing/checks.ts @@ -0,0 +1,137 @@ +/** + * kit/testing: checks an app's browser tests run inside the page, so every app holds the same line. + * Each function is self-contained (nothing from outside its own body), because a test runner sends + * its source to the browser: + * + * import { checkTouchTargets } from '@jgb-solutions/kit/testing' + * const report = await page.evaluate(checkTouchTargets, { within: 'header, main' }) + * expect(report.small).toEqual([]) + * + * Run them at a phone size on a touch device profile (so `pointer: coarse` rules apply). + */ + +export type TouchTargetOptions = { + /** Where to look, as a selector list of containers. Default: `header, main`. */ + within?: string + /** The smallest touch target, in px. Default 44. */ + minTarget?: number + /** The smallest text, in px. Default 12. */ + minText?: number + /** Controls to leave out, as a selector (matched with `closest`). Links inside a sentence (`p`) are always left out. */ + ignore?: string +} + +export type TouchTargetReport = { + /** Controls a finger can't reach: under `minTarget` each way. */ + small: string[] + /** Buttons whose own box answers to a neighbour's wider touch area. */ + covered: string[] + /** Text under `minText`. */ + tiny: string[] +} + +/** + * Every link, button and field can be reached with a finger, and no text is too small to read. + * A control counts by its box, or by the touch area a `::before` / `::after` gives it (a positioned + * control that clips its own overflow counts by its box alone, since it clips that area too). + */ +export function checkTouchTargets(options: TouchTargetOptions = {}): TouchTargetReport { + const minTarget = options.minTarget ?? 44 + const minText = options.minText ?? 12 + const containers = (options.within ?? 'header, main').split(',').map((part) => part.trim()) + const skip = ['p', '[hidden]', '[inert]', ...(options.ignore ? [options.ignore] : [])].join(', ') + + const shown = (el: Element) => { + const box = el.getBoundingClientRect() + const style = getComputedStyle(el) + // 1 px boxes are screen-reader-only text. + return box.width > 1 && box.height > 1 && style.visibility !== 'hidden' && style.display !== 'none' + } + const name = (el: Element) => (el.getAttribute('aria-label') ?? el.textContent ?? '').trim().replace(/\s+/g, ' ').slice(0, 40) + const all = (kinds: string) => document.querySelectorAll(containers.map((container) => `${container} :is(${kinds})`).join(', ')) + + const small: string[] = [] + for (const el of all('a, button, input, select, summary')) { + if (!shown(el) || el.closest(skip)) continue + const box = el.getBoundingClientRect() + let width = box.width + let height = box.height + const own = getComputedStyle(el) + const clipped = own.overflow !== 'visible' && own.position !== 'static' + for (const pseudo of clipped ? [] : ['::before', '::after']) { + const style = getComputedStyle(el, pseudo) + if (style.content === 'none' || style.position !== 'absolute') continue + width = Math.max(width, Number.parseFloat(style.width) || 0) + height = Math.max(height, Number.parseFloat(style.height) || 0) + } + if (Math.round(width) < minTarget || Math.round(height) < minTarget) + small.push(`${el.tagName.toLowerCase()} "${name(el)}" ${Math.round(width)}×${Math.round(height)}`) + } + + const covered: string[] = [] + for (const el of all('button')) { + if (!shown(el) || el.closest(skip) || (el as HTMLButtonElement).disabled) continue + el.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' }) + const box = el.getBoundingClientRect() + const midX = box.left + box.width / 2 + const midY = box.top + box.height / 2 + const probes: [number, number][] = [ + [box.left + 2, midY], + [box.right - 2, midY], + [midX, box.top + 2], + [midX, box.bottom - 2], + ] + for (const [x, y] of probes) { + const hit = document.elementFromPoint(x, y) + if (hit && !el.contains(hit)) { + covered.push(`"${name(el)}" is covered by ${hit.tagName.toLowerCase()} "${name(hit)}"`) + break + } + } + } + + const tiny = new Set() + const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT) + for (let node = walker.nextNode(); node; node = walker.nextNode()) { + const parent = node.parentElement + if (!parent || !node.textContent?.trim() || !shown(parent)) continue + const size = Number.parseFloat(getComputedStyle(parent).fontSize) + if (size < minText) tiny.add(`"${node.textContent.trim().slice(0, 30)}" ${size}px`) + } + + return { small: [...new Set(small)], covered: [...new Set(covered)], tiny: [...tiny] } +} + +export type AdPlacementOptions = { + /** The ad slots. Default: the kit's (`[data-slot="ad-slot"]`). */ + ad?: string + /** What counts as a block of real content. Default: articles, cards, rails, list items, paragraphs, pictures, video and tables inside `main`. */ + content?: string + /** How many content blocks must come before the first ad. Default 1; use 3 on a search results page. */ + before?: number +} + +/** + * An ad never comes first: at least `before` blocks of real content sit above the first ad slot. + * Returns the problems found (none when the page has no ad). + */ +export function adsAfterContent(options: AdPlacementOptions = {}): string[] { + const adSelector = options.ad ?? '[data-slot="ad-slot"]' + const contentSelector = + options.content ?? + 'main :is(article, [data-slot="card"], [data-slot="rail"], li, p, img, video, table):not(nav *, [aria-label="breadcrumb"] *)' + const before = options.before ?? 1 + + const ad = document.querySelector(adSelector) + if (!ad) return [] + let seen = 0 + for (const block of document.querySelectorAll(contentSelector)) { + if (block.closest(adSelector)) continue + // Document order: stop at the first block that comes after the ad. + if (ad.compareDocumentPosition(block) & Node.DOCUMENT_POSITION_FOLLOWING) break + const box = block.getBoundingClientRect() + if (box.width > 1 && box.height > 1) seen += 1 + if (seen >= before) return [] + } + return [`the first ad slot comes after ${seen} block(s) of content; ${before} needed`] +} diff --git a/src/ui/ad.tsx b/src/ui/ad.tsx new file mode 100644 index 0000000..4f3dbfc --- /dev/null +++ b/src/ui/ad.tsx @@ -0,0 +1,91 @@ +import type { ComponentProps, ReactNode } from 'react' +import { initials } from './display' + +export type AdSize = 'banner' | 'leaderboard' | 'rectangle' | 'fluid' + +/** A promotion of one of the publisher's own products, shown while no ad fills the slot. */ +export type HouseAd = { + href: string + /** The product's name. */ + name: string + /** One line on what it is. */ + tagline: string + /** A square icon (a full address or a path); left out, the name stands alone. */ + icon?: string | undefined + /** The words on its button: "Try it", "Open". Left out, there is no button (the whole ad is the link). */ + cta?: string | undefined +} + +export type AdSlotProps = Omit, 'children'> & { + /** + * Ads are on for this page. `false` renders nothing at all and reserves no space (a page with ads + * switched off, a paying member). + */ + enabled?: boolean + /** + * The reserved height: `banner` 100 px, `leaderboard` 90 px, `rectangle` 250 px, `fluid` 280 px. + * The space is held before anything loads, so an ad never moves the page. `--ad-height` on the slot + * sets another height. + */ + size?: AdSize + /** The small word above the slot: "Advertisement", in the page's language. */ + label: string + /** Shown while no ad fills the slot. Left out, an unfilled slot keeps its space and stays empty. */ + house?: HouseAd | undefined + /** The word that marks the house ad as the publisher's own: "From us", "Also by this team". */ + houseLabel?: string | undefined + /** The ad network's own element (for AdSense, the ``). */ + children?: ReactNode +} + +/** + * The frame around one ad: a fixed reserved height, a label, the network's element, and a house ad + * under it. The house ad shows until the network marks its element as filled + * (`data-ad-status="filled"`, which AdSense sets), so a slot is never a blank box: not while the ad + * loads, not when none comes, not when the script is blocked. The swap is CSS alone and both are the + * same height, so nothing shifts. + * + * Where slots go is the page's job: never before the first block of real content, never before the + * third result of a search (`adsAfterContent` in `@jgb-solutions/kit/testing` checks it). + */ +export function AdSlot({ enabled = true, size = 'rectangle', label, house, houseLabel, children, ...props }: AdSlotProps) { + if (!enabled) return null + return ( + + ) +} + +/** + * One of the house ads for a page, the same one every time for the same `seed` (the page's path), + * so the server and the browser agree and a page doesn't change its promotion on reload. + */ +export function pickHouseAd(ads: readonly HouseAd[], seed: string): HouseAd | undefined { + if (ads.length === 0) return undefined + let hash = 0 + for (const char of seed) hash = (hash * 31 + char.codePointAt(0)!) >>> 0 + return ads[hash % ads.length] +} diff --git a/src/ui/display.tsx b/src/ui/display.tsx index 4f42663..b88e70d 100644 --- a/src/ui/display.tsx +++ b/src/ui/display.tsx @@ -110,6 +110,39 @@ export function Avatar({ name, src, size = 'md', decorative = false, ...props }: ) } +export type PosterProps = Omit, 'children'> & { + /** The title of the film, album, station or channel: the initials and the colour come from it. */ + name: string + src?: string | null | undefined + /** The picture's shape: a square cover, an upright poster, a wide still. */ + ratio?: 'square' | 'portrait' | 'wide' + /** The title is written right next to it, so screen readers skip the picture. */ + decorative?: boolean + /** Pictures above the fold load at once (`eager`); the rest when they come near the screen. */ + loading?: 'lazy' | 'eager' +} +/** + * A cover, poster or logo with a fallback: the box keeps its shape before the picture arrives (so + * nothing shifts), and shows the title's initials on a colour made from the title when there is no + * picture or it fails to load. Its width comes from where it sits. + */ +export function Poster({ name, src, ratio = 'square', decorative = false, loading = 'lazy', ...props }: PosterProps) { + return ( + + + {src ? : null} + + ) +} + export type SeparatorProps = ComponentProps<'div'> & { orientation?: 'horizontal' | 'vertical'; decorative?: boolean } /** A divider. Decorative by default; with `decorative={false}` it is announced as a separator. */ export function Separator({ orientation = 'horizontal', decorative = true, ...props }: SeparatorProps) { diff --git a/src/ui/index.ts b/src/ui/index.ts index 1d91157..160a078 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -5,6 +5,7 @@ * server as it will look, and an app bundles only the ones it imports. Names, parts and variants * follow shadcn's. */ +export { AdSlot, pickHouseAd, type AdSize, type AdSlotProps, type HouseAd } from './ad' export { Button, type ButtonProps, type ButtonSize, type ButtonVariant } from './button' export { Avatar, @@ -22,12 +23,14 @@ export { ChipCount, initials, Kbd, + Poster, Separator, VisuallyHidden, type AvatarProps, type BadgeProps, type CardProps, type ChipProps, + type PosterProps, type SeparatorProps, type Tone, } from './display' @@ -94,5 +97,19 @@ export { type OverlayState, type UseOverlayOptions, } from './lazy' +export { + Rail, + RailArrows, + RailDescription, + RailHeader, + RailHeading, + RailItem, + RailMore, + RailTitle, + RailTrack, + type RailArrowsProps, + type RailProps, +} from './rail' export { cx, type RenderProp } from './render' +export { ShareButtons, shareEmailHref, shareLinks, type ShareButtonsProps, type ShareNetwork } from './share' export { uiTextEn, uiTextEs, uiTextFr, uiTextHt, type UiText } from './text' diff --git a/src/ui/patterns.test.tsx b/src/ui/patterns.test.tsx new file mode 100644 index 0000000..e3d8db0 --- /dev/null +++ b/src/ui/patterns.test.tsx @@ -0,0 +1,223 @@ +import { describe, expect, test } from 'bun:test' +import { readFileSync } from 'node:fs' +import { renderToStaticMarkup } from 'react-dom/server' +import { adsAfterContent, checkTouchTargets } from '../testing' +import { + AdSlot, + pickHouseAd, + Poster, + Rail, + RailArrows, + RailHeader, + RailHeading, + RailItem, + RailMore, + RailTitle, + RailTrack, + ShareButtons, + shareEmailHref, + shareLinks, + uiTextEn, + uiTextEs, + uiTextFr, + uiTextHt, +} from './index' + +const html = renderToStaticMarkup +const page = { url: 'https://example.com/films/dune?ref=a&b=1', title: 'Dune: "Part Two" <2024>', image: 'https://example.com/dune.jpg' } + +describe('Rail', () => { + const markup = html( + + + + New this week + + }>See all + + + + One + Two + + , + ) + + test('is a section with a real list inside, so a screen reader hears "list, 2 items"', () => { + expect(markup).toStartWith('
') + expect(markup).toContain('