From 7b3b7e9debb24a1b705e3a2c8a5a17e01e6b26cf Mon Sep 17 00:00:00 2001
From: Jean Gerard Bousiquot
Date: Sun, 6 Dec 2026 00:49:44 -0500
Subject: [PATCH 1/7] kit/ui: Rail, ShareButtons, Poster, AdSlot and
kit/testing (work in progress)
Co-Authored-By: Claude Fable 5.2
---
package.json | 6 +
scripts/build.ts | 11 ++
scripts/check-package.ts | 13 +-
scripts/check-size.ts | 10 +-
src/testing.ts | 7 +
src/testing/checks.ts | 137 +++++++++++++++++++
src/ui/ad.tsx | 83 ++++++++++++
src/ui/display.tsx | 33 +++++
src/ui/index.ts | 17 +++
src/ui/patterns/styles/10-rail.css | 185 +++++++++++++++++++++++++
src/ui/patterns/styles/20-share.css | 83 ++++++++++++
src/ui/patterns/styles/30-ad.css | 102 ++++++++++++++
src/ui/rail.tsx | 201 ++++++++++++++++++++++++++++
src/ui/share-icons.svg | 12 ++
src/ui/share.tsx | 180 +++++++++++++++++++++++++
src/ui/styles/20-display.css | 56 ++++++++
src/ui/text.ts | 27 ++++
17 files changed, 1160 insertions(+), 3 deletions(-)
create mode 100644 src/testing.ts
create mode 100644 src/testing/checks.ts
create mode 100644 src/ui/ad.tsx
create mode 100644 src/ui/patterns/styles/10-rail.css
create mode 100644 src/ui/patterns/styles/20-share.css
create mode 100644 src/ui/patterns/styles/30-ad.css
create mode 100644 src/ui/rail.tsx
create mode 100644 src/ui/share-icons.svg
create mode 100644 src/ui/share.tsx
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/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..21e3e34 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', 3 * 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/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..6ee54c9
--- /dev/null
+++ b/src/ui/ad.tsx
@@ -0,0 +1,83 @@
+import type { ComponentProps, ReactNode } from 'react'
+
+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
+}
+
+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/styles/10-rail.css b/src/ui/patterns/styles/10-rail.css
new file mode 100644
index 0000000..3d74066
--- /dev/null
+++ b/src/ui/patterns/styles/10-rail.css
@@ -0,0 +1,185 @@
+/*
+ * @jgb-solutions/kit/ui/patterns.css: the styles of kit/ui's patterns for content sites (rails,
+ * share buttons, ad slots). Load it after core.css, the same way:
+ *
+ * @import "@jgb-solutions/kit/ui/patterns.css" layer(components);
+ *
+ * Same rules as core.css: `data-slot` parts only, inside `:where()`, tokens only.
+ */
+
+/* Rail: a row that moves sideways, with its arrows at the top right.
+ Component tokens: --rail-gap, --rail-item-width (unset: each item is as wide as its content). */
+:where([data-slot='rail']) {
+ --rail-gap: var(--space-3);
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-3);
+ min-width: 0;
+}
+/* A row of chips with no heading: the row, then its arrows, on one line. */
+:where([data-slot='rail'][data-layout='inline']) {
+ flex-direction: row;
+ align-items: center;
+ gap: var(--space-2);
+}
+:where([data-slot='rail'][data-layout='inline']) :where([data-slot='rail-track']) {
+ flex: 1;
+}
+
+:where([data-slot='rail-header']) {
+ display: flex;
+ align-items: flex-end;
+ gap: var(--space-3);
+}
+:where([data-slot='rail-heading']) {
+ flex: 1;
+ min-width: 0;
+}
+:where([data-slot='rail-title']) {
+ margin: 0;
+ color: var(--foreground);
+ font-family: var(--font-display, var(--font-body));
+ font-size: var(--font-size-xl);
+ font-weight: 700;
+ line-height: var(--line-height-xl);
+ letter-spacing: -0.01em;
+}
+:where([data-slot='rail-description']) {
+ margin: 0;
+ color: var(--muted-foreground);
+ font-family: var(--font-body);
+ font-size: var(--font-size-sm);
+ line-height: var(--line-height-sm);
+}
+:where([data-slot='rail-more']) {
+ position: relative;
+ display: inline-flex;
+ flex: none;
+ align-items: center;
+ gap: var(--space-1);
+ color: var(--muted-foreground);
+ font-family: var(--font-body);
+ font-size: var(--font-size-sm);
+ font-weight: 500;
+ line-height: var(--line-height-sm);
+ text-decoration: none;
+ white-space: nowrap;
+}
+@media (hover: hover) {
+ :where([data-slot='rail-more']):hover {
+ color: var(--foreground);
+ }
+}
+
+:where([data-slot='rail-arrows']) {
+ display: flex;
+ flex: none;
+}
+/* The whole row fits: no arrows, but their space stays, so the header doesn't move when it stops fitting. */
+:where([data-slot='rail-arrows'][data-idle]) {
+ visibility: hidden;
+}
+/* A 44 px button around a 32 px circle. */
+:where([data-slot='rail-arrow']) {
+ position: relative;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: var(--hit-min);
+ height: var(--hit-min);
+ padding: 0;
+ border: 0;
+ border-radius: var(--radius-pill);
+ background: none;
+ color: var(--foreground);
+ cursor: pointer;
+ -webkit-tap-highlight-color: transparent;
+}
+:where([data-slot='rail-arrow']) :where([data-icon]) {
+ box-sizing: content-box;
+ width: 1rem;
+ height: 1rem;
+ padding: calc(0.5rem - 1px);
+ border: 1px solid var(--border);
+ border-radius: var(--radius-pill);
+ background: var(--card);
+ transition:
+ border-color var(--duration-base) var(--easing-out),
+ color var(--duration-base) var(--easing-out);
+}
+:where([data-slot='rail-arrow'][data-side='previous']) :where([data-icon]),
+:where([dir='rtl']) :where([data-slot='rail-arrow'][data-side='next'], [data-slot='rail-more']) :where([data-icon]) {
+ scale: -1 1;
+}
+:where([dir='rtl']) :where([data-slot='rail-arrow'][data-side='previous']) :where([data-icon]) {
+ scale: 1;
+}
+@media (hover: hover) {
+ :where([data-slot='rail-arrow']):hover:not(:disabled) :where([data-icon]) {
+ border-color: var(--primary);
+ color: var(--primary-text);
+ }
+}
+:where([data-slot='rail-arrow']):disabled {
+ opacity: 0.35;
+ cursor: default;
+}
+:where([data-slot='rail-arrow'], [data-slot='rail-more']):focus-visible {
+ outline: 2px solid var(--ring);
+ outline-offset: 2px;
+}
+
+:where([data-slot='rail-track']) {
+ display: flex;
+ gap: var(--rail-gap);
+ min-width: 0;
+ margin: 0;
+ padding: 0;
+ overflow-x: auto;
+ list-style: none;
+ scroll-snap-type: x proximity;
+ scrollbar-width: none;
+ overscroll-behavior-x: contain;
+}
+:where([data-slot='rail-track'])::-webkit-scrollbar {
+ display: none;
+}
+@media (prefers-reduced-motion: no-preference) {
+ :where([data-slot='rail-track']) {
+ scroll-behavior: smooth;
+ }
+}
+/* While more of the row is hidden past its far edge, that edge fades out. */
+:where([data-slot='rail-track'][data-more]) {
+ mask-image: linear-gradient(to right, black 88%, transparent);
+}
+:where([dir='rtl']) :where([data-slot='rail-track'][data-more]) {
+ mask-image: linear-gradient(to left, black 88%, transparent);
+}
+:where([data-slot='rail-item']) {
+ flex: none;
+ width: var(--rail-item-width, auto);
+ min-width: 0;
+ scroll-snap-align: start;
+}
+
+/* Touch screens: the arrows are compact, so they don't take a phone row's width, and their touch
+ area stays 44 px; "See all" gets the same height to touch. */
+@media (pointer: coarse) {
+ :where([data-slot='rail-arrow']) {
+ width: 2rem;
+ height: 2rem;
+ }
+ :where([data-slot='rail-arrow']) :where([data-icon]) {
+ padding: calc(0.375rem - 1px);
+ }
+ :where([data-slot='rail-arrow'], [data-slot='rail-more'])::after {
+ content: '';
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ width: max(100%, var(--hit-min));
+ height: max(100%, var(--hit-min));
+ translate: -50% -50%;
+ }
+}
diff --git a/src/ui/patterns/styles/20-share.css b/src/ui/patterns/styles/20-share.css
new file mode 100644
index 0000000..8575377
--- /dev/null
+++ b/src/ui/patterns/styles/20-share.css
@@ -0,0 +1,83 @@
+/* Share buttons: quiet outline circles. Component tokens: --share-size, --share-tone (per button:
+ `[data-slot='share-button'][data-network='whatsapp'] { --share-tone: … }` colours one network). */
+:where([data-slot='share']) {
+ --share-size: var(--hit-min);
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: var(--space-2) var(--space-3);
+}
+:where([data-slot='share'][data-size='sm']) {
+ --share-size: 2.25rem;
+}
+:where([data-slot='share-list']) {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-2);
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+:where([data-slot='share-button']) {
+ position: relative;
+ display: grid;
+ place-items: center;
+ width: var(--share-size);
+ height: var(--share-size);
+ padding: 0;
+ border: 1px solid var(--border);
+ border-radius: var(--radius-pill);
+ background: none;
+ color: var(--share-tone, var(--foreground));
+ cursor: pointer;
+ -webkit-tap-highlight-color: transparent;
+ transition:
+ border-color var(--duration-base) var(--easing-out),
+ color var(--duration-base) var(--easing-out),
+ translate var(--duration-base) var(--easing-out);
+}
+:where([data-slot='share-button']) :where([data-icon]) {
+ width: 1.25rem;
+ height: 1.25rem;
+}
+:where([data-slot='share'][data-size='sm']) :where([data-slot='share-button']) :where([data-icon]) {
+ width: 1.125rem;
+ height: 1.125rem;
+}
+@media (hover: hover) {
+ :where([data-slot='share-button']):hover {
+ border-color: var(--share-tone, var(--primary));
+ color: var(--share-tone, var(--primary-text));
+ translate: 0 -1px;
+ }
+}
+:where([data-slot='share-button']):focus-visible {
+ outline: 2px solid var(--ring);
+ outline-offset: 2px;
+}
+/* Copied: the button says so without colour alone (the status line reads it out, and shows it). */
+:where([data-slot='share-button'][data-copied]) {
+ border-color: var(--success);
+ color: var(--success);
+}
+:where([data-slot='share-status']) {
+ color: var(--success);
+ font-family: var(--font-body);
+ font-size: var(--font-size-sm);
+ line-height: var(--line-height-sm);
+}
+:where([data-slot='share-status']):empty {
+ display: none;
+}
+/* The small row still gives a finger 44 px. */
+@media (pointer: coarse) {
+ :where([data-slot='share-button'])::after {
+ content: '';
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ width: max(100%, var(--hit-min));
+ height: max(100%, var(--hit-min));
+ translate: -50% -50%;
+ }
+}
diff --git a/src/ui/patterns/styles/30-ad.css b/src/ui/patterns/styles/30-ad.css
new file mode 100644
index 0000000..e53a098
--- /dev/null
+++ b/src/ui/patterns/styles/30-ad.css
@@ -0,0 +1,102 @@
+/* Ad slot: a reserved height, a label, the network's element over a house ad.
+ Component tokens: --ad-height, --ad-radius. */
+:where([data-slot='ad-slot']) {
+ --ad-height: 15.625rem;
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-2);
+ min-width: 0;
+}
+:where([data-slot='ad-slot'][data-size='banner']) {
+ --ad-height: 6.25rem;
+}
+:where([data-slot='ad-slot'][data-size='leaderboard']) {
+ --ad-height: 5.625rem;
+}
+:where([data-slot='ad-slot'][data-size='fluid']) {
+ --ad-height: 17.5rem;
+}
+:where([data-slot='ad-label']) {
+ margin: 0;
+ color: var(--muted-foreground);
+ font-family: var(--font-body);
+ font-size: var(--font-size-xs);
+ font-weight: 500;
+ line-height: var(--line-height-xs);
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+}
+/* The house ad and the network's element share one cell. They are never seen together: the house
+ ad leaves the moment the element is marked as filled. */
+:where([data-slot='ad-frame']) {
+ display: grid;
+ min-height: var(--ad-height);
+ overflow: hidden;
+ border-radius: var(--ad-radius, var(--radius-card));
+}
+:where([data-slot='ad-frame']) > * {
+ grid-area: 1 / 1;
+ min-width: 0;
+}
+:where([data-slot='ad-unit']) {
+ display: flex;
+ justify-content: center;
+}
+/* Above the still-empty element, so it can be clicked until an ad arrives. */
+:where([data-slot='ad-house']) {
+ z-index: 1;
+ display: flex;
+ align-items: center;
+ gap: var(--space-4);
+ padding: var(--space-4) var(--space-5);
+ border: 1px solid var(--border);
+ border-radius: inherit;
+ background: var(--card);
+ color: var(--card-foreground);
+ font-family: var(--font-body);
+ text-decoration: none;
+ transition: border-color var(--duration-base) var(--easing-out);
+}
+:where([data-slot='ad-frame']:has([data-ad-status='filled'])) :where([data-slot='ad-house']) {
+ display: none;
+}
+@media (hover: hover) {
+ :where([data-slot='ad-house']):hover {
+ border-color: var(--primary);
+ }
+}
+:where([data-slot='ad-house']):focus-visible {
+ outline: 2px solid var(--ring);
+ outline-offset: -2px;
+}
+:where([data-slot='ad-house-icon']) {
+ flex: none;
+ width: 3rem;
+ height: 3rem;
+ border-radius: var(--radius-control);
+}
+:where([data-slot='ad-house-text']) {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-1);
+ min-width: 0;
+}
+:where([data-slot='ad-house-label']) {
+ color: var(--muted-foreground);
+ font-size: var(--font-size-xs);
+ font-weight: 600;
+ line-height: var(--line-height-xs);
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+}
+:where([data-slot='ad-house-name']) {
+ font-family: var(--font-display, var(--font-body));
+ font-size: var(--font-size-lg);
+ font-weight: 700;
+ line-height: var(--line-height-lg);
+}
+:where([data-slot='ad-house-tagline']) {
+ color: var(--muted-foreground);
+ font-size: var(--font-size-sm);
+ line-height: var(--line-height-sm);
+}
diff --git a/src/ui/rail.tsx b/src/ui/rail.tsx
new file mode 100644
index 0000000..9742972
--- /dev/null
+++ b/src/ui/rail.tsx
@@ -0,0 +1,201 @@
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type ComponentProps,
+ type ReactNode,
+ type RefObject,
+} from 'react'
+import { renderSlot, type RenderProp } from './render'
+
+type Edges = { start: boolean; end: boolean }
+type RailParts = {
+ track: RefObject
+ edges: Edges
+ measure: () => void
+ move: (direction: 1 | -1) => void
+}
+const RailContext = /* @__PURE__ */ createContext(null)
+
+function useRail(part: string): RailParts {
+ const rail = useContext(RailContext)
+ if (!rail) throw new Error(`<${part}> must be inside `)
+ return rail
+}
+
+/** How close to an end counts as "at the end", in px: sub-pixel widths never leave an arrow live. */
+const EDGE = 4
+
+export type RailProps = ComponentProps<'section'> & {
+ /**
+ * `stacked` (default): a header (title, "See all", arrows at the top right) over the row.
+ * `inline`: the row and its arrows on one line, for a row of chips with no heading.
+ */
+ layout?: 'stacked' | 'inline'
+}
+
+/**
+ * A row that moves 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 (their space is kept, so nothing shifts). Swiping and the keyboard still scroll it, and it
+ * stays a real list for screen readers.
+ *
+ *
+ *
+ * New this week
+ * }>See all
+ *
+ *
+ * {items.map((item) => … )}
+ *
+ */
+export function Rail({ layout = 'stacked', children, ...props }: RailProps) {
+ const track = useRef(null)
+ // Until measured (the server, the first paint) the row counts as fitting: no arrow flashes in.
+ const [edges, setEdges] = useState({ start: true, end: true })
+
+ const measure = useCallback(() => {
+ const el = track.current
+ if (!el) return
+ // Right-to-left rows scroll into negative numbers.
+ const at = Math.abs(el.scrollLeft)
+ const next = { start: at <= EDGE, end: at + el.clientWidth >= el.scrollWidth - EDGE }
+ setEdges((now) => (now.start === next.start && now.end === next.end ? now : next))
+ }, [])
+
+ const move = useCallback((direction: 1 | -1) => {
+ const el = track.current
+ if (!el) return
+ const forward = getComputedStyle(el).direction === 'rtl' ? -1 : 1
+ // Most of what is in view, so the last card of one press is the first of the next. The
+ // stylesheet makes it smooth, and instant for people who ask for less motion.
+ el.scrollBy({ left: forward * direction * el.clientWidth * 0.85 })
+ }, [])
+
+ const parts = useMemo(() => ({ track, edges, measure, move }), [edges, measure, move])
+ return (
+
+
+
+ )
+}
+
+/** The line above the row: the heading on the left; "See all" and the arrows at the top right. */
+export function RailHeader(props: ComponentProps<'div'>) {
+ return
+}
+/** The title and its one-line hint. */
+export function RailHeading(props: ComponentProps<'div'>) {
+ return
+}
+/** An `` by default; `render={ }` changes the level. */
+export function RailTitle({ render, ...props }: ComponentProps<'h2'> & { render?: RenderProp }) {
+ return renderSlot(render, 'h2', { ...props, 'data-slot': 'rail-title' })
+}
+export function RailDescription(props: ComponentProps<'p'>) {
+ return
+}
+/** The "See all" link: `render={ }`. Its touch area is 44 px tall. */
+export function RailMore({ render, children, ...props }: ComponentProps<'a'> & { render?: RenderProp }) {
+ return renderSlot(render, 'a', {
+ ...props,
+ 'data-slot': 'rail-more',
+ children: (
+ <>
+ {children}
+
+ >
+ ),
+ })
+}
+
+export type RailArrowsProps = Omit, 'children'> & {
+ /** The back arrow's name, with the row's name in it: "Scroll genres back". */
+ previous: string
+ /** The forward arrow's name: "Scroll genres on". */
+ next: string
+}
+/** The row's two arrows. Hidden (space kept) while the whole row fits. */
+export function RailArrows({ previous, next, ...props }: RailArrowsProps) {
+ const { edges, move } = useRail('RailArrows')
+ return (
+
+ move(-1)}
+ >
+
+
+ move(1)}>
+
+
+
+ )
+}
+
+/** The list that scrolls. Give it an `aria-label` when the row has no title. */
+export function RailTrack({ children, onScroll, ...props }: ComponentProps<'ul'>) {
+ const { track, edges, measure } = useRail('RailTrack')
+
+ // The row's own width changes (a resize, a font arriving).
+ useEffect(() => {
+ const el = track.current
+ if (!el) return
+ const observer = new ResizeObserver(measure)
+ observer.observe(el)
+ return () => observer.disconnect()
+ }, [track, measure])
+ // Its content changes (more items arrive) without its width changing.
+ useEffect(measure)
+
+ return (
+ {
+ measure()
+ onScroll?.(event)
+ }}
+ >
+ {children}
+
+ )
+}
+
+/** One item of the row. Its width comes from its content, or from `--rail-item-width` on the rail. */
+export function RailItem(props: ComponentProps<'li'>) {
+ return
+}
+
+/** Points forward; the stylesheet turns it for "previous" and for right-to-left pages. */
+function Chevron(): ReactNode {
+ return (
+
+
+
+ )
+}
diff --git a/src/ui/share-icons.svg b/src/ui/share-icons.svg
new file mode 100644
index 0000000..402a232
--- /dev/null
+++ b/src/ui/share-icons.svg
@@ -0,0 +1,12 @@
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/ui/share.tsx b/src/ui/share.tsx
new file mode 100644
index 0000000..b8dc7e1
--- /dev/null
+++ b/src/ui/share.tsx
@@ -0,0 +1,180 @@
+import { useEffect, useRef, useState, useSyncExternalStore, type ComponentProps } from 'react'
+import type { UiText } from './text'
+
+export type ShareNetwork = 'whatsapp' | 'facebook' | 'x' | 'telegram' | 'pinterest' | 'linkedin'
+
+export type ShareButtonsProps = Omit, 'children' | 'title'> & {
+ /** The page's full address (`https://…`): what gets shared. */
+ url: string
+ /** The page's title, as the share should say it. */
+ title: string
+ /** The page's share picture (a full address). Pinterest needs one: without it, its button is left out. */
+ image?: string | undefined
+ /**
+ * Where the icons' file is served: import `@jgb-solutions/kit/ui/share-icons.svg` as a URL with
+ * your bundler and pass it here. One cached file, instead of icon paths in every page's JavaScript.
+ */
+ sprite: string
+ /** The buttons' names, in the page's language (`uiTextEn` and its siblings have them). */
+ text: Pick
+ /** `sm` for a row that sits under a list's intro: it looks smaller and keeps a 44 px touch area. */
+ size?: 'md' | 'sm'
+}
+
+const NAMES: Record = {
+ whatsapp: 'WhatsApp',
+ facebook: 'Facebook',
+ x: 'X',
+ telegram: 'Telegram',
+ pinterest: 'Pinterest',
+ linkedin: 'LinkedIn',
+}
+
+/** The share link of each network, in the one order every page uses. Plain links: no script of theirs runs. */
+export function shareLinks({
+ url,
+ title,
+ image,
+}: {
+ url: string
+ title: string
+ image?: string | undefined
+}): { network: ShareNetwork; href: string }[] {
+ const enc = encodeURIComponent
+ return [
+ { network: 'whatsapp', href: `https://wa.me/?text=${enc(`${title} ${url}`)}` },
+ { network: 'facebook', href: `https://www.facebook.com/sharer/sharer.php?u=${enc(url)}` },
+ { network: 'x', href: `https://x.com/intent/post?text=${enc(title)}&url=${enc(url)}` },
+ { network: 'telegram', href: `https://t.me/share/url?url=${enc(url)}&text=${enc(title)}` },
+ ...(image
+ ? [
+ {
+ network: 'pinterest' as const,
+ href: `https://pinterest.com/pin/create/button/?url=${enc(url)}&media=${enc(image)}&description=${enc(title)}`,
+ },
+ ]
+ : []),
+ { network: 'linkedin', href: `https://www.linkedin.com/sharing/share-offsite/?url=${enc(url)}` },
+ ]
+}
+
+/** The share-by-email link: the title as the subject, the title and the address as the message. */
+export function shareEmailHref({ url, title }: { url: string; title: string }): string {
+ return `mailto:?subject=${encodeURIComponent(title)}&body=${encodeURIComponent(`${title}\n${url}`)}`
+}
+
+const noSubscribe = () => () => {}
+
+function escapeAttribute(value: string): string {
+ return value.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(//g, '>')
+}
+
+function Icon({ sprite, id }: { sprite: string; id: string }) {
+ return (
+
+
+
+ )
+}
+
+/**
+ * Share buttons for a page: WhatsApp, Facebook, X, Telegram, Pinterest (when the page has a
+ * picture), LinkedIn, email, copy link, then the phone's own share sheet where the browser has one.
+ * Plain links that open in a new tab, with no third-party script. Each is a 44 px target.
+ */
+export function ShareButtons({ url, title, image, sprite, text, size = 'md', ...props }: ShareButtonsProps) {
+ const [copied, setCopied] = useState(false)
+ const timer = useRef | undefined>(undefined)
+ useEffect(() => () => clearTimeout(timer.current), [])
+ // The share sheet exists only in the browser (mostly phones): false on the server, so its button
+ // appears after hydration.
+ const canShare = useSyncExternalStore(
+ noSubscribe,
+ () => typeof navigator.share === 'function',
+ () => false,
+ )
+
+ async function copy() {
+ try {
+ await navigator.clipboard.writeText(url)
+ setCopied(true)
+ clearTimeout(timer.current)
+ timer.current = setTimeout(() => setCopied(false), 2000)
+ } catch {
+ // No clipboard access (an old browser, a page inside a frame): the browser's own box, with the address selected.
+ window.prompt(text.copyLink, url)
+ }
+ }
+
+ function more() {
+ // The person closing the sheet is not an error.
+ navigator.share({ title, url }).catch(() => {})
+ }
+
+ // Cloudflare's email obfuscation rewrites every mailto: link into one that works only once its
+ // script has run. Its documented off switch is a pair of HTML comments around the link, and React
+ // can't write comments, so this one item is written as HTML. Every value in it is escaped.
+ const email = ` `
+
+ return (
+
+
+ {shareLinks({ url, title, image }).map(({ network, href }) => {
+ const name = text.shareOn.replace('{network}', NAMES[network])
+ return (
+
+
+
+
+
+ )
+ })}
+
+
+
+
+
+
+ {canShare && (
+
+
+
+
+
+ )}
+
+
+ {copied ? text.linkCopied : ''}
+
+
+ )
+}
diff --git a/src/ui/styles/20-display.css b/src/ui/styles/20-display.css
index 037ee34..cedd514 100644
--- a/src/ui/styles/20-display.css
+++ b/src/ui/styles/20-display.css
@@ -238,3 +238,59 @@
/* A picture that fails to load leaves the initials showing, with no broken-image text over them. */
color: transparent;
}
+
+/* Poster: a cover, an upright poster or a wide still. The box holds its shape before the picture
+ arrives. Component tokens: --poster-radius, --poster-tone. */
+:where([data-slot='poster']) {
+ --poster-tone: var(--chart-1);
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 100%;
+ aspect-ratio: 1;
+ overflow: hidden;
+ container-type: inline-size;
+ border-radius: var(--poster-radius, var(--radius-card));
+ background: linear-gradient(
+ 135deg,
+ color-mix(in oklab, var(--poster-tone) 30%, var(--card)),
+ color-mix(in oklab, var(--poster-tone) 12%, var(--card))
+ );
+ color: color-mix(in oklab, var(--poster-tone) 45%, var(--card-foreground));
+ font-family: var(--font-display, var(--font-body));
+ font-weight: 700;
+ line-height: 1;
+ user-select: none;
+}
+:where([data-slot='poster'][data-ratio='portrait']) {
+ aspect-ratio: 2 / 3;
+}
+:where([data-slot='poster'][data-ratio='wide']) {
+ aspect-ratio: 16 / 9;
+}
+:where([data-slot='poster'][data-tone='2']) {
+ --poster-tone: var(--chart-2);
+}
+:where([data-slot='poster'][data-tone='3']) {
+ --poster-tone: var(--chart-3);
+}
+:where([data-slot='poster'][data-tone='4']) {
+ --poster-tone: var(--chart-4);
+}
+:where([data-slot='poster'][data-tone='5']) {
+ --poster-tone: var(--chart-5);
+}
+/* The initials grow with the box: a quarter of its width, between 14 and 48 px. */
+:where([data-slot='poster-fallback']) {
+ font-size: clamp(0.875rem, 25cqi, 3rem);
+}
+:where([data-slot='poster-image']) {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ /* A picture that fails to load leaves the initials showing, with no broken-image text over them. */
+ color: transparent;
+}
diff --git a/src/ui/text.ts b/src/ui/text.ts
index 9ec45ed..8e49974 100644
--- a/src/ui/text.ts
+++ b/src/ui/text.ts
@@ -25,6 +25,13 @@ export type UiText = {
copy: string
copied: string
share: string
+ /** `{network}` is replaced by the network's name: "Share on WhatsApp". */
+ shareOn: string
+ shareByEmail: string
+ copyLink: string
+ linkCopied: string
+ /** The phone's own share sheet. */
+ shareMore: string
}
export const uiTextEn: UiText = {
@@ -48,6 +55,11 @@ export const uiTextEn: UiText = {
copy: 'Copy',
copied: 'Copied',
share: 'Share',
+ shareOn: 'Share on {network}',
+ shareByEmail: 'Share by email',
+ copyLink: 'Copy link',
+ linkCopied: 'Link copied',
+ shareMore: 'More ways to share',
}
export const uiTextFr: UiText = {
@@ -71,6 +83,11 @@ export const uiTextFr: UiText = {
copy: 'Copier',
copied: 'Copié',
share: 'Partager',
+ shareOn: 'Partager sur {network}',
+ shareByEmail: 'Partager par e-mail',
+ copyLink: 'Copier le lien',
+ linkCopied: 'Lien copié',
+ shareMore: 'Plus d’options de partage',
}
export const uiTextEs: UiText = {
@@ -94,6 +111,11 @@ export const uiTextEs: UiText = {
copy: 'Copiar',
copied: 'Copiado',
share: 'Compartir',
+ shareOn: 'Compartir en {network}',
+ shareByEmail: 'Compartir por correo',
+ copyLink: 'Copiar enlace',
+ linkCopied: 'Enlace copiado',
+ shareMore: 'Más formas de compartir',
}
/** Haitian Creole. To be read by a native speaker before 1.0. */
@@ -118,4 +140,9 @@ export const uiTextHt: UiText = {
copy: 'Kopye',
copied: 'Kopye',
share: 'Pataje',
+ shareOn: 'Pataje sou {network}',
+ shareByEmail: 'Pataje pa imèl',
+ copyLink: 'Kopye lyen an',
+ linkCopied: 'Lyen an kopye',
+ shareMore: 'Plis fason pou pataje',
}
From 7f059d8e7f1c6756788778f3d9abfaa3367ac868 Mon Sep 17 00:00:00 2001
From: Jean Gerard Bousiquot
Date: Sun, 6 Dec 2026 00:53:05 -0500
Subject: [PATCH 2/7] kit/ui patterns: tests, the showcase's Patterns page,
README and changelog
Co-Authored-By: Claude Fable 5.2
---
CHANGELOG.md | 10 ++
README.md | 58 +++++++++++
e2e/patterns.spec.ts | 151 +++++++++++++++++++++++++++
playground/specimens.tsx | 140 ++++++++++++++++++++++++-
playground/ui.css | 24 +++++
playwright.config.ts | 4 +-
scripts/build-showcase.ts | 10 +-
showcase/app.tsx | 35 ++++++-
showcase/site.ts | 11 +-
src/ui/patterns.test.tsx | 210 ++++++++++++++++++++++++++++++++++++++
10 files changed, 647 insertions(+), 6 deletions(-)
create mode 100644 e2e/patterns.spec.ts
create mode 100644 src/ui/patterns.test.tsx
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 26dd90c..c100fd5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,16 @@
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, then the phone's share sheet. 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 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.
+- `kit/ui` text: `shareOn`, `shareByEmail`, `copyLink`, `linkCopied` and `shareMore`, in the four languages. **Breaking for an app that builds its own `UiText`:** add the five.
+- `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 758e0fe..edefa53 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..92e8c9c
--- /dev/null
+++ b/e2e/patterns.spec.ts
@@ -0,0 +1,151 @@
+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()
+ expect(await 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()
+ expect(await 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')
+
+ if (browserName === 'chromium') await context.grantPermissions(['clipboard-read', 'clipboard-write'])
+ test.skip(browserName !== 'chromium', 'only Chromium lets a test grant the clipboard')
+ await share.getByRole('button', { name: 'Copy link' }).click()
+ await expect(share.getByRole('status')).toHaveText('Link copied')
+ expect(await page.evaluate(() => navigator.clipboard.readText())).toBe('https://example.com/shows/morning-jazz')
+})
+
+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)
+ const report = await page.evaluate(checkTouchTargets, { within: 'header, main' })
+ 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/playground/specimens.tsx b/playground/specimens.tsx
index 6140c1d..0af2b06 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' },
+ { href: '#field-notes', name: 'Field Notes', tagline: 'Top ten lists about nearly everything' },
+]
+
+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/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/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/ui/patterns.test.tsx b/src/ui/patterns.test.tsx
new file mode 100644
index 0000000..1c71ec7
--- /dev/null
+++ b/src/ui/patterns.test.tsx
@@ -0,0 +1,210 @@
+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(/]*disabled=""/g)).toHaveLength(2)
+ expect(markup).not.toContain('data-more')
+ expect(markup).not.toContain('data-overflow')
+ })
+
+ test('each arrow is a named button', () => {
+ expect(markup).toContain('data-side="previous" aria-label="Scroll new this week back"')
+ expect(markup).toContain('data-side="next" aria-label="Scroll new this week on"')
+ })
+
+ test('"See all" keeps the link it was given', () => {
+ expect(markup).toMatch(/See all {
+ expect(() => html( )).toThrow(' must be inside ')
+ })
+})
+
+describe('ShareButtons', () => {
+ test('the links come in the one order, and Pinterest only with a picture', () => {
+ expect(shareLinks(page).map((link) => link.network)).toEqual(['whatsapp', 'facebook', 'x', 'telegram', 'pinterest', 'linkedin'])
+ expect(shareLinks({ url: page.url, title: page.title }).map((link) => link.network)).toEqual([
+ 'whatsapp',
+ 'facebook',
+ 'x',
+ 'telegram',
+ 'linkedin',
+ ])
+ })
+
+ test('every value is encoded into its link', () => {
+ for (const { href } of shareLinks(page)) {
+ expect(href).toStartWith('https://')
+ expect(href).not.toMatch(/[<>" ]/)
+ expect(href).toContain(encodeURIComponent(page.url))
+ }
+ expect(shareEmailHref(page)).toBe(
+ `mailto:?subject=${encodeURIComponent(page.title)}&body=${encodeURIComponent(`${page.title}\n${page.url}`)}`,
+ )
+ })
+
+ const markup = html( )
+
+ test('plain links that open in a new tab, each named, with no script', () => {
+ expect(markup).toContain('aria-label="Share on WhatsApp"')
+ expect(markup.match(/target="_blank" rel="noopener noreferrer"/g)).toHaveLength(6)
+ expect(markup).not.toContain(''}
+ sprite={'/s.svg">'}
+ text={{ ...uiTextEn, shareByEmail: '">' }}
+ />,
+ )
+ const hostileItem = /(.*?)/.exec(hostile)![1]!
+ expect(hostileItem.match(/<[a-z]+/g)).toEqual([' {
+ expect(markup).toContain('')
+ })
+
+ test('the four languages name every button', () => {
+ for (const text of [uiTextEn, uiTextFr, uiTextEs, uiTextHt]) {
+ expect(text.shareOn).toContain('{network}')
+ for (const key of ['shareByEmail', 'copyLink', 'linkCopied', 'shareMore'] as const) expect(text[key].length).toBeGreaterThan(3)
+ }
+ })
+
+ test('the icons file has a symbol for every button', () => {
+ const sprite = readFileSync('src/ui/share-icons.svg', 'utf8')
+ for (const id of ['whatsapp', 'facebook', 'x', 'telegram', 'pinterest', 'linkedin', 'email', 'copy', 'more'])
+ expect(sprite).toContain(` {
+ test('shows the initials under the picture, on a tone made from the name', () => {
+ const markup = html( )
+ expect(markup).toContain('role="img" aria-label="Smooth Jazz Lounge"')
+ expect(markup).toContain('data-ratio="wide"')
+ expect(markup).toMatch(/data-tone="[1-5]"/)
+ expect(markup).toContain('SL ')
+ expect(markup).toContain(' {
+ const markup = html( )
+ expect(markup).not.toContain(' {
+ const house = {
+ href: 'https://example.com/tools',
+ name: 'Example Tools',
+ tagline: 'Free tools that run in your browser',
+ icon: '/tools.svg',
+ }
+
+ test('ads off: nothing is rendered and nothing is reserved', () => {
+ expect(html( )).toBe('')
+ })
+
+ test('a labelled region with the house ad under the network element', () => {
+ const markup = html(
+
+
+ ,
+ )
+ expect(markup).toStartWith('')
+ expect(markup).toContain('')
+ expect(markup).toContain('Also from us ')
+ expect(markup).toContain('
')
+ })
+
+ test('the stylesheet hides the house ad only once the network marks its element as filled', () => {
+ const css = readFileSync('src/ui/patterns/styles/30-ad.css', 'utf8')
+ expect(css).toContain(":where([data-slot='ad-frame']:has([data-ad-status='filled'])) :where([data-slot='ad-house'])")
+ expect(css).toMatch(/min-height: var\(--ad-height\)/)
+ })
+
+ test('a page always gets the same house ad', () => {
+ const ads = [house, { ...house, name: 'Two' }, { ...house, name: 'Three' }]
+ expect(pickHouseAd(ads, '/films/dune')).toBe(pickHouseAd(ads, '/films/dune')!)
+ expect(new Set(['/a', '/b', '/c', '/d', '/e', '/f', '/g'].map((seed) => pickHouseAd(ads, seed)!.name)).size).toBeGreaterThan(1)
+ expect(pickHouseAd([], '/a')).toBeUndefined()
+ })
+})
+
+describe('kit/testing', () => {
+ test('each check is self-contained, so a test runner can send its source to the page', () => {
+ for (const check of [checkTouchTargets, adsAfterContent]) {
+ const source = check.toString()
+ expect(source).not.toMatch(/\bimport\b|\brequire\(/)
+ // Runs with nothing but its own body: every name it uses is a local or a browser global.
+ expect(() => new Function(`return (${source})`)).not.toThrow()
+ }
+ })
+})
From 95fc04a054d796fdd727781f1c497badef54afe5 Mon Sep 17 00:00:00 2001
From: Jean Gerard Bousiquot
Date: Sun, 6 Dec 2026 00:57:19 -0500
Subject: [PATCH 3/7] Patterns tests: wait for the glide; the showcase's name
takes 44 px to touch
Co-Authored-By: Claude Fable 5.2
---
e2e/patterns.spec.ts | 8 +++++---
showcase/showcase.css | 15 +++++++++++++++
2 files changed, 20 insertions(+), 3 deletions(-)
diff --git a/e2e/patterns.spec.ts b/e2e/patterns.spec.ts
index 92e8c9c..5293002 100644
--- a/e2e/patterns.spec.ts
+++ b/e2e/patterns.spec.ts
@@ -33,7 +33,8 @@ test('a row that overflows has its arrows at the top right, each disabled at its
await next.click()
await expect(previous).toBeEnabled()
- expect(await track.evaluate((el) => el.scrollLeft)).toBeGreaterThan(50)
+ // 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()
@@ -69,7 +70,7 @@ test('right to left: forward still means further along the row', async ({ page }
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()
- expect(await track.evaluate((el) => el.scrollLeft)).toBeLessThan(-50)
+ 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 }) => {
@@ -143,7 +144,8 @@ for (const info of PAGES) {
test.skip(!['phone', 'iphone'].includes(testInfo.project.name), 'touch screens')
await page.goto(`${BASE}${info.path}`)
await alive(page)
- const report = await page.evaluate(checkTouchTargets, { within: 'header, main' })
+ // 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/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;
From 01660ed034ce144c7279c75ee5770a7d5bc49af7 Mon Sep 17 00:00:00 2001
From: Jean Gerard Bousiquot
Date: Sun, 6 Dec 2026 00:58:59 -0500
Subject: [PATCH 4/7] House ad: a wash of the brand colour, a bigger name in
tall slots, an optional button; row header centred
Co-Authored-By: Claude Fable 5.2
---
playground/specimens.tsx | 4 +--
src/ui/ad.tsx | 3 +++
src/ui/patterns.test.tsx | 2 ++
src/ui/patterns/styles/10-rail.css | 3 ++-
src/ui/patterns/styles/30-ad.css | 40 +++++++++++++++++++++++++++++-
5 files changed, 48 insertions(+), 4 deletions(-)
diff --git a/playground/specimens.tsx b/playground/specimens.tsx
index 0af2b06..b826c34 100644
--- a/playground/specimens.tsx
+++ b/playground/specimens.tsx
@@ -487,8 +487,8 @@ const SHOWS = [
] 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' },
- { href: '#field-notes', name: 'Field Notes', tagline: 'Top ten lists about nearly everything' },
+ { 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() {
diff --git a/src/ui/ad.tsx b/src/ui/ad.tsx
index 6ee54c9..681dd5a 100644
--- a/src/ui/ad.tsx
+++ b/src/ui/ad.tsx
@@ -11,6 +11,8 @@ export type HouseAd = {
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'> & {
@@ -63,6 +65,7 @@ export function AdSlot({ enabled = true, size = 'rectangle', label, house, house
{house.name}
{house.tagline}
+ {house.cta ? {house.cta} : null}
) : null}
{children ? {children}
: null}
diff --git a/src/ui/patterns.test.tsx b/src/ui/patterns.test.tsx
index 1c71ec7..0ed5b98 100644
--- a/src/ui/patterns.test.tsx
+++ b/src/ui/patterns.test.tsx
@@ -166,6 +166,7 @@ describe('AdSlot', () => {
name: 'Example Tools',
tagline: 'Free tools that run in your browser',
icon: '/tools.svg',
+ cta: 'Try it',
}
test('ads off: nothing is rendered and nothing is reserved', () => {
@@ -181,6 +182,7 @@ describe('AdSlot', () => {
expect(markup).toStartWith('')
expect(markup).toContain('')
expect(markup).toContain('Also from us ')
+ expect(markup).toContain('Try it ')
expect(markup).toContain('
')
})
diff --git a/src/ui/patterns/styles/10-rail.css b/src/ui/patterns/styles/10-rail.css
index 3d74066..905d5a0 100644
--- a/src/ui/patterns/styles/10-rail.css
+++ b/src/ui/patterns/styles/10-rail.css
@@ -28,7 +28,8 @@
:where([data-slot='rail-header']) {
display: flex;
- align-items: flex-end;
+ /* "See all" and the arrows share the heading block's centre line. */
+ align-items: center;
gap: var(--space-3);
}
:where([data-slot='rail-heading']) {
diff --git a/src/ui/patterns/styles/30-ad.css b/src/ui/patterns/styles/30-ad.css
index e53a098..21fd3b1 100644
--- a/src/ui/patterns/styles/30-ad.css
+++ b/src/ui/patterns/styles/30-ad.css
@@ -51,12 +51,28 @@
padding: var(--space-4) var(--space-5);
border: 1px solid var(--border);
border-radius: inherit;
- background: var(--card);
+ /* A wash of the brand colour, so it reads as a promotion and not as an empty box. */
+ background: linear-gradient(135deg, color-mix(in oklab, var(--primary) 12%, var(--card)), var(--card) 70%);
color: var(--card-foreground);
font-family: var(--font-body);
text-decoration: none;
transition: border-color var(--duration-base) var(--easing-out);
}
+/* The tall slots: stacked, with a bigger name. */
+:where([data-slot='ad-slot'][data-size='rectangle'], [data-slot='ad-slot'][data-size='fluid']) :where([data-slot='ad-house']) {
+ flex-direction: column;
+ align-items: flex-start;
+ justify-content: center;
+ padding: var(--space-6);
+}
+:where([data-slot='ad-slot'][data-size='rectangle'], [data-slot='ad-slot'][data-size='fluid']) :where([data-slot='ad-house-name']) {
+ font-size: var(--font-size-2xl);
+ line-height: var(--line-height-2xl);
+}
+:where([data-slot='ad-slot'][data-size='rectangle'], [data-slot='ad-slot'][data-size='fluid']) :where([data-slot='ad-house-icon']) {
+ width: 4rem;
+ height: 4rem;
+}
:where([data-slot='ad-frame']:has([data-ad-status='filled'])) :where([data-slot='ad-house']) {
display: none;
}
@@ -100,3 +116,25 @@
font-size: var(--font-size-sm);
line-height: var(--line-height-sm);
}
+:where([data-slot='ad-house-text']) {
+ flex: 1;
+}
+:where([data-slot='ad-slot'][data-size='rectangle'], [data-slot='ad-slot'][data-size='fluid']) :where([data-slot='ad-house-text']) {
+ flex: none;
+}
+/* Looks like a button; the whole ad is the link. */
+:where([data-slot='ad-house-cta']) {
+ display: inline-flex;
+ flex: none;
+ align-items: center;
+ min-height: var(--control-sm);
+ padding-inline: var(--space-4);
+ border: 1px solid var(--border);
+ border-radius: var(--radius-pill);
+ background: var(--card);
+ color: var(--primary-text);
+ font-size: var(--font-size-sm);
+ font-weight: 600;
+ line-height: var(--line-height-sm);
+ white-space: nowrap;
+}
From 1376238a54ed4dc7ec5f97b42f26c96b6aacd016 Mon Sep 17 00:00:00 2001
From: Jean Gerard Bousiquot
Date: Sun, 6 Dec 2026 01:11:15 -0500
Subject: [PATCH 5/7] House ad: the tall slots' rules come last, so they apply
Co-Authored-By: Claude Fable 5.2
---
src/ui/patterns/styles/30-ad.css | 43 ++++++++++++++++----------------
1 file changed, 22 insertions(+), 21 deletions(-)
diff --git a/src/ui/patterns/styles/30-ad.css b/src/ui/patterns/styles/30-ad.css
index 21fd3b1..1a98fab 100644
--- a/src/ui/patterns/styles/30-ad.css
+++ b/src/ui/patterns/styles/30-ad.css
@@ -58,24 +58,6 @@
text-decoration: none;
transition: border-color var(--duration-base) var(--easing-out);
}
-/* The tall slots: stacked, with a bigger name. */
-:where([data-slot='ad-slot'][data-size='rectangle'], [data-slot='ad-slot'][data-size='fluid']) :where([data-slot='ad-house']) {
- flex-direction: column;
- align-items: flex-start;
- justify-content: center;
- padding: var(--space-6);
-}
-:where([data-slot='ad-slot'][data-size='rectangle'], [data-slot='ad-slot'][data-size='fluid']) :where([data-slot='ad-house-name']) {
- font-size: var(--font-size-2xl);
- line-height: var(--line-height-2xl);
-}
-:where([data-slot='ad-slot'][data-size='rectangle'], [data-slot='ad-slot'][data-size='fluid']) :where([data-slot='ad-house-icon']) {
- width: 4rem;
- height: 4rem;
-}
-:where([data-slot='ad-frame']:has([data-ad-status='filled'])) :where([data-slot='ad-house']) {
- display: none;
-}
@media (hover: hover) {
:where([data-slot='ad-house']):hover {
border-color: var(--primary);
@@ -119,9 +101,6 @@
:where([data-slot='ad-house-text']) {
flex: 1;
}
-:where([data-slot='ad-slot'][data-size='rectangle'], [data-slot='ad-slot'][data-size='fluid']) :where([data-slot='ad-house-text']) {
- flex: none;
-}
/* Looks like a button; the whole ad is the link. */
:where([data-slot='ad-house-cta']) {
display: inline-flex;
@@ -138,3 +117,25 @@
line-height: var(--line-height-sm);
white-space: nowrap;
}
+
+/* The tall slots: stacked, with a bigger name. */
+:where([data-slot='ad-slot'][data-size='rectangle'], [data-slot='ad-slot'][data-size='fluid']) :where([data-slot='ad-house']) {
+ flex-direction: column;
+ align-items: flex-start;
+ justify-content: center;
+ padding: var(--space-6);
+}
+:where([data-slot='ad-slot'][data-size='rectangle'], [data-slot='ad-slot'][data-size='fluid']) :where([data-slot='ad-house-name']) {
+ font-size: var(--font-size-2xl);
+ line-height: var(--line-height-2xl);
+}
+:where([data-slot='ad-slot'][data-size='rectangle'], [data-slot='ad-slot'][data-size='fluid']) :where([data-slot='ad-house-icon']) {
+ width: 4rem;
+ height: 4rem;
+}
+:where([data-slot='ad-frame']:has([data-ad-status='filled'])) :where([data-slot='ad-house']) {
+ display: none;
+}
+:where([data-slot='ad-slot'][data-size='rectangle'], [data-slot='ad-slot'][data-size='fluid']) :where([data-slot='ad-house-text']) {
+ flex: none;
+}
From 497e4aa71c9bc9abdfca4c2b9eeb34ef40240b62 Mon Sep 17 00:00:00 2001
From: Jean Gerard Bousiquot
Date: Sun, 6 Dec 2026 01:15:31 -0500
Subject: [PATCH 6/7] Share buttons wrap into even rows on a phone, the share
sheet first; tall house ads get a corner mark
- Phones: 7 or 8 buttons wrap as rows of 4, 9 or 10 as rows of 5; none is left alone on a line.
The share sheet's button comes first there, and its place is kept while the page comes alive.
- Tall house ads show the product's icon, or its initials, large in the lower corner.
- Changelog: the five new UiText strings are marked as breaking.
Co-Authored-By: Claude Fable 5.2
---
CHANGELOG.md | 7 +++---
e2e/patterns.spec.ts | 25 +++++++++++++++++++
scripts/check-size.ts | 2 +-
src/ui/ad.tsx | 5 ++++
src/ui/patterns.test.tsx | 15 ++++++++++--
src/ui/patterns/styles/20-share.css | 26 ++++++++++++++++++++
src/ui/patterns/styles/30-ad.css | 37 +++++++++++++++++++++++++----
src/ui/share.tsx | 34 +++++++++++++++++---------
8 files changed, 130 insertions(+), 21 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c100fd5..973cfe7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,10 +6,11 @@ All notable changes to `@jgb-solutions/kit`. Versions follow semver.
- `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, then the phone's share sheet. 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 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.
+ - `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.
-- `kit/ui` text: `shareOn`, `shareByEmail`, `copyLink`, `linkCopied` and `shareMore`, in the four languages. **Breaking for an app that builds its own `UiText`:** add the five.
+- **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
diff --git a/e2e/patterns.spec.ts b/e2e/patterns.spec.ts
index 5293002..1848703 100644
--- a/e2e/patterns.spec.ts
+++ b/e2e/patterns.spec.ts
@@ -100,6 +100,31 @@ test('share buttons are plain links in the one order; copy says so', async ({ pa
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()
diff --git a/scripts/check-size.ts b/scripts/check-size.ts
index 21e3e34..b53e29d 100644
--- a/scripts/check-size.ts
+++ b/scripts/check-size.ts
@@ -21,7 +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', 3 * 1024],
+ ['dist/ui/patterns.css', 4 * 1024],
]
for (const [path, budget] of FILES) {
if (!existsSync(path)) {
diff --git a/src/ui/ad.tsx b/src/ui/ad.tsx
index 681dd5a..4f3dbfc 100644
--- a/src/ui/ad.tsx
+++ b/src/ui/ad.tsx
@@ -1,4 +1,5 @@
import type { ComponentProps, ReactNode } from 'react'
+import { initials } from './display'
export type AdSize = 'banner' | 'leaderboard' | 'rectangle' | 'fluid'
@@ -66,6 +67,10 @@ export function AdSlot({ enabled = true, size = 'rectangle', label, house, house
{house.tagline}
{house.cta ? {house.cta} : null}
+ {/* The tall slots' lower corner: the product's icon, or its initials, large. Decoration only. */}
+
+ {house.icon ? : initials(house.name)}
+
) : null}
{children ? {children}
: null}
diff --git a/src/ui/patterns.test.tsx b/src/ui/patterns.test.tsx
index 0ed5b98..e3d8db0 100644
--- a/src/ui/patterns.test.tsx
+++ b/src/ui/patterns.test.tsx
@@ -124,7 +124,13 @@ describe('ShareButtons', () => {
test('copy is a button; the share sheet button waits for the browser; the status line starts empty', () => {
expect(markup).toContain(']*disabled=""/)
+ // 6 networks, email, copy and the share sheet: the count the stylesheet wraps into even rows.
+ expect(markup).toContain('data-slot="share" data-size="md" data-count="9"')
expect(markup).toContain(' ')
})
@@ -182,7 +188,12 @@ describe('AdSlot', () => {
expect(markup).toStartWith('')
expect(markup).toContain('')
expect(markup).toContain('Also from us ')
- expect(markup).toContain('Try it ')
+ expect(markup).toContain('Try it ')
+ // The tall slots' corner mark is decoration: the icon again, or the initials.
+ expect(markup).toContain(' )).toContain(
+ 'ET ',
+ )
expect(markup).toContain('
')
})
diff --git a/src/ui/patterns/styles/20-share.css b/src/ui/patterns/styles/20-share.css
index 8575377..088b794 100644
--- a/src/ui/patterns/styles/20-share.css
+++ b/src/ui/patterns/styles/20-share.css
@@ -69,6 +69,32 @@
:where([data-slot='share-status']):empty {
display: none;
}
+/* The share sheet's button before the page knows whether the browser has one: left out. */
+:where([data-slot='share-sheet'][data-pending]) {
+ display: none;
+}
+/* Phones: even rows, never one button alone on a line (7 or 8 buttons: rows of 4; 9 or 10: rows
+ of 5). The share sheet comes first, and its place is kept free while the page comes alive, so
+ nothing moves when it appears. The small size fits 7 on one line. */
+@media (width < 34rem) {
+ :where([data-slot='share']:is([data-count='7'], [data-count='8'], [data-count='9'], [data-count='10'])) :where([data-slot='share-list']) {
+ display: grid;
+ grid-template-columns: repeat(4, var(--share-size));
+ }
+ :where([data-slot='share']:is([data-count='9'], [data-count='10'])) :where([data-slot='share-list']) {
+ grid-template-columns: repeat(5, var(--share-size));
+ }
+ :where([data-slot='share'][data-size='sm'][data-count='7']) :where([data-slot='share-list']) {
+ display: flex;
+ }
+ :where([data-slot='share-sheet']) {
+ order: -1;
+ }
+ :where([data-slot='share-sheet'][data-pending]) {
+ display: block;
+ visibility: hidden;
+ }
+}
/* The small row still gives a finger 44 px. */
@media (pointer: coarse) {
:where([data-slot='share-button'])::after {
diff --git a/src/ui/patterns/styles/30-ad.css b/src/ui/patterns/styles/30-ad.css
index 1a98fab..fc00049 100644
--- a/src/ui/patterns/styles/30-ad.css
+++ b/src/ui/patterns/styles/30-ad.css
@@ -44,8 +44,10 @@
}
/* Above the still-empty element, so it can be clicked until an ad arrives. */
:where([data-slot='ad-house']) {
+ position: relative;
z-index: 1;
display: flex;
+ overflow: hidden;
align-items: center;
gap: var(--space-4);
padding: var(--space-4) var(--space-5);
@@ -129,13 +131,40 @@
font-size: var(--font-size-2xl);
line-height: var(--line-height-2xl);
}
-:where([data-slot='ad-slot'][data-size='rectangle'], [data-slot='ad-slot'][data-size='fluid']) :where([data-slot='ad-house-icon']) {
- width: 4rem;
- height: 4rem;
-}
:where([data-slot='ad-frame']:has([data-ad-status='filled'])) :where([data-slot='ad-house']) {
display: none;
}
:where([data-slot='ad-slot'][data-size='rectangle'], [data-slot='ad-slot'][data-size='fluid']) :where([data-slot='ad-house-text']) {
flex: none;
}
+
+/* The house ad's mark: hidden in the short slots; in the tall ones it fills the lower corner, so
+ the card reads as designed, not as a box with space left over. Behind the words. */
+:where([data-slot='ad-house-mark']) {
+ display: none;
+}
+:where([data-slot='ad-slot'][data-size='rectangle'], [data-slot='ad-slot'][data-size='fluid']) :where([data-slot='ad-house-mark']) {
+ position: absolute;
+ inset-inline-end: var(--space-4);
+ bottom: -0.12em;
+ z-index: -1;
+ display: block;
+ color: color-mix(in oklab, var(--primary) 14%, transparent);
+ font-family: var(--font-display, var(--font-body));
+ font-size: 7.5rem;
+ font-weight: 800;
+ line-height: 1;
+ letter-spacing: -0.04em;
+ user-select: none;
+}
+:where([data-slot='ad-house-mark']) :where(img) {
+ display: block;
+ width: 6rem;
+ height: 6rem;
+ margin-bottom: calc(0.12em + var(--space-5));
+ border-radius: var(--radius-card);
+}
+/* The icon is the mark in a tall slot, so it isn't shown twice. */
+:where([data-slot='ad-slot'][data-size='rectangle'], [data-slot='ad-slot'][data-size='fluid']) :where([data-slot='ad-house-icon']) {
+ display: none;
+}
diff --git a/src/ui/share.tsx b/src/ui/share.tsx
index b8dc7e1..0f08d46 100644
--- a/src/ui/share.tsx
+++ b/src/ui/share.tsx
@@ -79,20 +79,26 @@ function Icon({ sprite, id }: { sprite: string; id: string }) {
/**
* Share buttons for a page: WhatsApp, Facebook, X, Telegram, Pinterest (when the page has a
- * picture), LinkedIn, email, copy link, then the phone's own share sheet where the browser has one.
- * Plain links that open in a new tab, with no third-party script. Each is a 44 px target.
+ * picture), LinkedIn, email, copy link, and the phone's own share sheet where the browser has one
+ * (first on a phone, last on a wide screen). Plain links that open in a new tab, with no third-party
+ * script. Each is a 44 px target. On a phone the buttons wrap into even rows (4 + 4, 5 + 4), never
+ * one left alone on a line.
*/
export function ShareButtons({ url, title, image, sprite, text, size = 'md', ...props }: ShareButtonsProps) {
const [copied, setCopied] = useState(false)
const timer = useRef | undefined>(undefined)
useEffect(() => () => clearTimeout(timer.current), [])
- // The share sheet exists only in the browser (mostly phones): false on the server, so its button
- // appears after hydration.
- const canShare = useSyncExternalStore(
+ // The phone's share sheet exists only in the browser, so the server can't know. Until the page
+ // comes alive its button is `pending`: a phone keeps its place free (nearly every phone has the
+ // sheet, so nothing moves when it appears), a wide screen leaves it out.
+ const sheet = useSyncExternalStore<'pending' | 'yes' | 'no'>(
noSubscribe,
- () => typeof navigator.share === 'function',
- () => false,
+ () => (typeof navigator.share === 'function' ? 'yes' : 'no'),
+ () => 'pending',
)
+ const links = shareLinks({ url, title, image })
+ // How many buttons there are: the stylesheet wraps them into even rows on a phone.
+ const count = links.length + 2 + (sheet === 'no' ? 0 : 1)
async function copy() {
try {
@@ -123,9 +129,9 @@ export function ShareButtons({ url, title, image, sprite, text, size = 'md', ...
)}"> `
return (
-
+
- {shareLinks({ url, title, image }).map(({ network, href }) => {
+ {links.map(({ network, href }) => {
const name = text.shareOn.replace('{network}', NAMES[network])
return (
@@ -157,14 +163,20 @@ export function ShareButtons({ url, title, image, sprite, text, size = 'md', ...
- {canShare && (
-
+ {sheet !== 'no' && (
+ // Last in the page's order; the stylesheet shows it first on a phone, where it is the one most people want.
+
From 84706411849e6c82b29ff594b7521e8fced9d8e8 Mon Sep 17 00:00:00 2001
From: Jean Gerard Bousiquot
Date: Sun, 6 Dec 2026 01:45:03 -0500
Subject: [PATCH 7/7] Copy link: fall back to a selected field when the
clipboard API is refused, and never throw
Found in the walkthrough: in a browser that refuses the clipboard API and has no prompt(),
the button threw and said nothing. It now tries the clipboard API, then a selected
off-screen field, then the browser's own box, and stays quiet if all three fail. The browser
test now expects "Link copied" in Firefox and WebKit too.
Co-Authored-By: Claude Fable 5.2
---
e2e/patterns.spec.ts | 6 ++++--
src/ui/share.tsx | 36 ++++++++++++++++++++++++++++++++++--
2 files changed, 38 insertions(+), 4 deletions(-)
diff --git a/e2e/patterns.spec.ts b/e2e/patterns.spec.ts
index 1848703..762d45e 100644
--- a/e2e/patterns.spec.ts
+++ b/e2e/patterns.spec.ts
@@ -93,11 +93,13 @@ test('share buttons are plain links in the one order; copy says so', async ({ pa
.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'])
- test.skip(browserName !== 'chromium', 'only Chromium lets a test grant the clipboard')
await share.getByRole('button', { name: 'Copy link' }).click()
await expect(share.getByRole('status')).toHaveText('Link copied')
- expect(await page.evaluate(() => navigator.clipboard.readText())).toBe('https://example.com/shows/morning-jazz')
+ // 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) => {
diff --git a/src/ui/share.tsx b/src/ui/share.tsx
index 0f08d46..b37e9da 100644
--- a/src/ui/share.tsx
+++ b/src/ui/share.tsx
@@ -65,6 +65,26 @@ export function shareEmailHref({ url, title }: { url: string; title: string }):
const noSubscribe = () => () => {}
+/** Copies through a selected, off-screen field: for browsers that refuse the clipboard API. True when it worked. */
+function copyWithSelection(value: string): boolean {
+ const field = document.createElement('textarea')
+ field.value = value
+ field.readOnly = true
+ field.style.position = 'fixed'
+ field.style.opacity = '0'
+ document.body.append(field)
+ field.select()
+ let done = false
+ try {
+ done = document.execCommand('copy')
+ } catch {
+ // Refused here too: the caller falls back to the browser's own box.
+ done = false
+ }
+ field.remove()
+ return done
+}
+
function escapeAttribute(value: string): string {
return value.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(//g, '>')
}
@@ -101,14 +121,26 @@ export function ShareButtons({ url, title, image, sprite, text, size = 'md', ...
const count = links.length + 2 + (sheet === 'no' ? 0 : 1)
async function copy() {
+ let done = false
try {
await navigator.clipboard.writeText(url)
+ done = true
+ } catch {
+ // No clipboard access (an old browser, a page inside a frame, a refused permission): the older way.
+ done = copyWithSelection(url)
+ }
+ if (done) {
setCopied(true)
clearTimeout(timer.current)
timer.current = setTimeout(() => setCopied(false), 2000)
- } catch {
- // No clipboard access (an old browser, a page inside a frame): the browser's own box, with the address selected.
+ return
+ }
+ try {
+ // The browser's own box, with the address selected, to copy by hand.
window.prompt(text.copyLink, url)
+ } catch {
+ // Some embedded browsers have no prompt either. Nothing is left to try, and nothing was copied,
+ // so the status line stays silent rather than claim it.
}
}