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 `
)
+ 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 (
+
+
+ {initials(name)}
+
+ {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('
')
+ expect(markup.match(/
/g)).toHaveLength(2)
+ })
+
+ test('before it is measured, the row counts as fitting: the arrows are hidden and disabled, and nothing fades', () => {
+ expect(markup).toContain('data-slot="rail-arrows" data-idle=""')
+ expect(markup.match(/