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 ( + + + {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 ( + +
+ {children} +
+
+ ) +} + +/** 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 ( +

+ ) +} + +/** 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 ( + + ) +} + +/** 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('