Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<!--email_off-->` 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.
Expand Down
58 changes: 58 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
<Rail>
<RailHeader>
<RailHeading>
<RailTitle>New this week</RailTitle>
</RailHeading>
<RailMore render={<a href="/new" />}>{text.seeAll}</RailMore>
<RailArrows previous="Scroll new this week back" next="Scroll new this week on" />
</RailHeader>
<RailTrack>
{items.map((item) => (
<RailItem key={item.id}>…</RailItem>
))}
</RailTrack>
</Rail>
```

`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 `<!--email_off-->` 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 `<dialog>`.
Expand Down
180 changes: 180 additions & 0 deletions e2e/patterns.spec.ts
Original file line number Diff line number Diff line change
@@ -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 = '<ins data-ad-status="filled" style="display:block;width:300px;height:250px"></ins>'
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([])
})
}
6 changes: 6 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
Loading
Loading