wealth/.claude/skills/front-end-architect/references/ui-rules.md

19 KiB
Raw Blame History

UI rules

UX, SEO, and asset rules for b2c-b2b.md. Read it when you build or change what the user sees or what search engines read: a page, template, organism, form, copy, upload, image, font, icon, metadata, or viewport. Work only on repositories, caches, actions, stores, or libs doesn't need it.

Contents: Images, fonts, and CSS (Fonts and the icon sprite) · Metadata and viewport · SEO and i18n · Crawlers · Copy · Feedback · Stability · Loading, progress, and empty states · File uploads · Forms · Keyboard and context

Images, fonts, and CSS

  • Use next/image with explicit dimensions and sizes. Never lazy-load the LCP image: give it loading="eager" and fetchPriority="high", or preload when it's discovered late. priority is deprecated in Next.js 16. Everything below the fold stays lazy.
  • Content images are <img> elements with a src, as next/image renders them, never CSS backgrounds: Google indexes images only from <img>. Both templates use the same image URLs and alt texts. A gallery or a slider renders every slide's <img> in the HTML, and only the first one is eager.
  • Fonts come from island/fonts as variable woff2. Preload only the critical face, use font-display: swap, and give each face a size-adjusted fallback face so the swap doesn't shift layout (code-patterns.md). Never use next/font: it renames the files (next section).
  • Reserve space for images, banners, ads, and embeds with fixed aspect ratios.
  • Register every project whose components use Tailwind classes as a source (see code-patterns.md).

Fonts and the icon sprite

Fonts and the icon sprite change rarely, and every page needs them. A hash in their file names changes whenever a build step changes its output, such as a Next.js or svgo upgrade or a new loader option, even when the file itself didn't change. Every visitor then downloads them again. So they keep fixed names, and only a developer decides when visitors download them again.

  • Names: fonts keep their own names, such as yekan-bakh-vf.woff2, and the sprite stays symbol-defs.svg. Each app serves them from public/fonts/ and public/icons/.
  • No step adds a hash to them or renames them: not the bundler, not the CSS pipeline, not next/font (it copies fonts to _next/static/media/<hash>.woff2), not icon-sprite-plugin, not a CDN upload. fonts.css names each file by its root path, url('/fonts/yekan-bakh-vf.woff2'), which Next.js leaves alone. A relative path such as url('../fonts/...') goes through the bundler and gets a hash.
  • Fonts have no version. A font file never changes under its name: a changed font ships as a new file with a new name.
  • The sprite has a version in its link, never in its file name: /icons/symbol-defs.svg?v=1. island constants.ts holds ICON_SPRITE_VERSION and the ICON_SPRITE_URL built from it, and the Icon atom points <use href> at ${ICON_SPRITE_URL}#${name}. A new Icomoon import or a changed svgo config raises ICON_SPRITE_VERSION in the same commit. Never reuse or lower a version.
  • The critical font's path lives in island constants.ts as CRITICAL_FONT_URL, and each root layout preloads it with preload(CRITICAL_FONT_URL, { as: 'font', type: 'font/woff2', crossOrigin: 'anonymous' }). The preload URL must equal the one in fonts.css, or the browser downloads the font twice.
  • Serve them as immutable. Next.js serves public/ with Cache-Control: public, max-age=0, so the browser asks again on every visit. Add this to the headers() in next.config.ts, and keep the same header on the CDN. The CDN must keep the query string in its cache key, or a new ?v= still gets the old sprite.
const immutable = [{ key: 'Cache-Control', value: 'public, max-age=31536000, immutable' }];

// inside headers()
{ source: '/fonts/:path*', headers: immutable },
{ source: '/icons/:path*', headers: immutable },
  • The pwa lib's service worker keeps them too, by exact URL with the ?v= included (lib-pwa.md). A new sprite version reaches each visitor with their next request, and the worker deletes the old one. The worker checks fonts and the sprite in the background (stale-while-revalidate), so a font changed under its old name reaches each visitor one visit late; a changed font still always gets a new name.

Metadata and viewport

  • Metadata is always in <head>. Since Next.js 15.2, metadata streams into <body> after the shell, and only a built-in list of HTML-limited bots waits for it in <head>. Every app's next.config.ts sets that list to every user agent, so crawlers, link previews, and iOS's Add to Home Screen all find the tags in <head>:

    htmlLimitedBots: /.*/,
    
    • The body still streams: Suspense parts arrive after the first flush as before.
    • The cost: the first flush waits for generateMetadata, so it becomes the page's TTFB, and on a client-side navigation the page's content waits for it too (a loading.tsx still shows at once; a link to an indexable page, which has none, is a NavLink that shows a pending hint). Keep it fast: it reads only the caches the page's first paint awaits anyway, so it adds no request.
    • A request without a User-Agent header still gets streamed metadata.
  • Fixed values use the metadata export: tags that are the same for every request, such as robots: { index: false } in the (account) layout, or APPLE_WEB_APP in the root layout (lib-pwa.md). generateMetadata is only for values that depend on the request or on data: params, search params, the locale, or a cache read. The same split holds for viewport and generateViewport. A segment exports one of each pair, never both: when part of it is dynamic, generateMetadata spreads the fixed values from a constant.

  • Build metadata from configs/seo.ts: title, description, canonical URL, hreflang alternates, and Open Graph. Provide sitemap.ts, robots.ts, and the web app manifest's manifest.ts (lib-pwa.md).

  • Robots tags, the canonical URL, and the title come only from server metadata; only error boundaries render their own noindex. Client code never sets, changes, or removes them: Google may skip rendering a page whose server HTML says noindex, and it reads the canonical only in <head>. So a page that should rank never ships noindex to remove it later.

  • Every root layout's viewport is width: 'device-width', initialScale: 1, maximumScale: 1, kept as ROOT_VIEWPORT in configs/seo.ts. Next.js renders <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">, always in <head>, because the viewport never streams. Without maximum-scale=1, Safari on iPhone zooms in whenever an input, select, or textarea with text smaller than 16px gets focus, and the page stays zoomed after the keyboard closes. The root layout's generateViewport returns ROOT_VIEWPORT with the themeColor of the theme the server chose; themeColor belongs to the viewport, never to metadata.

    • Accepted trade-off: iOS still lets the user pinch-zoom, but Chrome on Android doesn't unless the user turns on "Force enable zoom", and Lighthouse's meta-viewport accessibility audit fails. Reviews don't flag it. Never add userScalable: false: it blocks pinch-zoom everywhere else too.

SEO and i18n

  • Every indexable page renders its schema.org JSON-LD with the json-ld lib (lib-json-ld.md): the business and the website on the home page, the product with its offer, rating, and breadcrumb on product pages, the breadcrumb on listing pages, and the store-wide return and shipping policies on their own pages. It says only what the page shows: the same name, price, availability, rating, and trail, in the page's language, with machine values (Latin digits, ISO 8601 dates, ISO 4217 currency).
  • Server Components translate with a per-request i18next instance from apps/<app>/src/i18n/; react-i18next hooks run only in client components. Set lang and dir on <html> from the locale.

Crawlers

Googlebot Smartphone crawls the mobile template, and Google indexes what it reads there. Google renders JavaScript later, hours later for some pages, or never, and its renderer never clicks, scrolls, types, or keeps cookies. So what search engines need is in each template's server HTML. Each page's rendering doc records where every section stands (page-rendering.md).

  • The first flush of both templates holds the page's primary content: the H1; the main entity's name, price, availability, description, specs, and rating summary; the breadcrumb; the LCP image; the JSON-LD; and the links that are the only path to other pages. Streamed parts hold only secondary content. They sit in a hidden <div> at the end of the document until JavaScript moves them, Googlebot reads only the first 2 MB, and a slow part keeps the connection open, which uses up the site's crawl capacity.
  • Both templates hold the same primary content and headings, with one H1 that has the same text; the same internal links, image URLs, and alt texts; the same title, description, canonical, and robots tags; and the same JSON-LD and status. A template may collapse or reorder a section that search engines need, but never drop it; only a section they don't need, such as the mobile bottom navigation, may be in one template. Google indexes only the mobile template, and Googlebot Desktop still crawls product pages for Shopping. The breadcrumb shows in both templates, although Google shows it only in desktop results.
  • Links that crawlers follow are <a href> elements with a real URL in the server HTML: next/link, or an anchor. Never navigate with onClick and router.push, a <button>, or a clickable <div>, and never fetch menu links on hover or tap: a menu, drawer, or mega menu renders its links in the server HTML and only hides them. A fragment (#…) never changes indexable content.
  • Collapsed content that search engines need stays in the DOM: tabs, accordions, <details>, and sliders render those panels and slides in the server HTML, and only hide them (island's TabsPanel takes forceMount for this). Never mount such a panel when it opens ({isOpen && <Panel />}), and never fetch its content on click: Google sees neither.
  • Content that loads on visibility (LoadOnVisible) may or may not render for Google, and content that loads on interaction never does. Neither holds primary content or the only link to a page. Never lazy-load what shows when the page opens.
  • Pagination: each page has its own URL (?page=2) and is its own canonical, and page 1 has one URL, without ?page=1. Each page links to the previous, the next, and numbered pages with <a href> in both templates. "Load more" and infinite scroll fetch the same URLs and update the address with the History API. A page past the last answers 404.
  • Filters: decide for each filter whether its URLs are indexable. Indexable filter URLs separate parameters with &, keep one parameter order, use one key per filter (?color=red,blue), and answer 404 for an empty, duplicate, or unknown combination; internal links always use that form. robots.ts disallows every other filter parameter and every sort order on listing paths, and an empty combination that includes one of those parameters answers 200 with the no-results empty state and Clear filters.
  • Internal search: robots.ts disallows /search with one rule, and the page sets no robots tag, because Google never fetches a blocked URL to read one. Search never answers 5xx for an unknown query, and category pagination reaches every product without it. /compare is disallowed the same way, because every set of products is a new URL. A URL pattern that Google has already indexed gets noindex first, and robots.ts blocks it only after it drops out of the index.
  • robots.ts never disallows product, cart, or checkout pages, or the JS and CSS files a template needs. Storebot-Google walks product, cart, and checkout pages to check prices and shipping, and it obeys User-agent: * rules; cart and checkout carry noindex instead. Add-to-cart works for an automated browser that keeps cookies.
  • sitemap.ts lists every indexable URL in its canonical form, as a second path for discovery.
  • Variants: each variant has its own URL (?color=green&size=s), linked with <a href>. The server preselects the variant's image, price, and availability from the URL, the canonical drops the variant parameters, and the ProductGroup markup stays the same for every variant. robots.ts never blocks a variant URL.
  • An out-of-stock product stays a 200, indexable page with its stock text, a disabled buy button, and OutOfStock in its offer. The status codes for missing, replaced, and empty pages are in error-handling.md.
  • The URL decides the locale and the currency of an indexable page, never a cookie, Accept-Language, or the IP. Googlebot sends no Accept-Language and crawls mostly from US addresses, so it would index only one locale.
  • Google's renderer keeps no cookies or storage, so viewer-dependent parts render their guest variant for it. Make that variant a neutral, same-size UI, never an error message or an empty box, which Google may report as a soft 404. Every request such a part sends while Google renders the page counts against the API host's crawl budget.
  • Under overload, the reverse proxy or the CDN answers crawlers with 503 and Retry-After. A 5xx or 429 lowers Google's crawl rate for the whole host.

apps/<app>/src/app/robots.ts. configs/seo.ts lists CRAWL_BLOCKED_PARAMS, the sort, view, and non-indexable filter keys, and LISTING_PATHS, the path prefixes of filterable listings, such as '/category/', '/brand/', '/seller/', '/campaign/', and '/offers'. The parameter rules name only those paths, because product variant URLs use the same keys (?color=green&size=s) and stay open.

import type { MetadataRoute } from 'next';
import { CRAWL_BLOCKED_PARAMS, LISTING_PATHS } from '../configs';
import { clientEnv } from '../env';

export const dynamic = 'force-dynamic';

export default function robots(): MetadataRoute.Robots {
  const params = LISTING_PATHS.flatMap((path) =>
    CRAWL_BLOCKED_PARAMS.flatMap((key) => [`${path}*?${key}=`, `${path}*&${key}=`]),
  );
  return {
    // Product pages and their variants, cart, and checkout stay open: Storebot-Google checks prices and shipping there.
    rules: { userAgent: '*', disallow: ['/search', '/compare', ...params] },
    sitemap: `${clientEnv.NEXT_PUBLIC_SITE_URL}/sitemap.xml`,
  };
}

Copy

  • Every label, button, tooltip, and message is a simple, complete description of its purpose. Buttons name the action and its object ("Add this item to the cart", not "Add"). Headings describe their content. Tooltips describe the outcome, not the control.
  • Error messages have three parts: what went wrong, why (if known), and what the user can do. "The file could not be uploaded because it is larger than 10 MB. Compress the image or choose a smaller file, then try again."
  • Empty states say what would normally be here, why it is empty, and the next step, with a primary action when there is one: "Your cart is empty. Browse today's offers to find something you like." plus a "See offers" button.

Feedback

  • Every completed action shows a toast that says exactly what was done, naming the object when possible: "'Wireless headphones' was added to your cart". Success toasts auto-dismiss after 4–6 s. Error toasts come from showActionError (code-patterns.md): they stay until dismissed, name what failed, carry the hint or a support sentence with the reference ID, and offer Try again or Reload when the error's cause allows it.
  • Destructive actions ask for confirmation, naming the object and the consequence: "Remove the saved address 'Home'? This cannot be undone."
  • Prefer reversible designs: "Undo" in the toast when the back end supports it.

Stability

Refetches, state updates, and re-renders must never make the UI disappear and reappear.

  • Never switch between isLoading ? <Spinner /> : <List /> on refetch. Keep showing the data with a subtle inline indicator driven by isFetching.
  • Keep layout containers mounted and swap only their contents.
  • Use skeletons with the final content's dimensions, and reserve space for images and embeds with fixed aspect ratios.
  • A part whose model uses useSuspenseQuery changes its query key inside startTransition, so a page or filter change keeps the current content instead of falling back to the skeleton.

Loading, progress, and empty states

  • Design the loading and empty states together with the populated state. Loading states are skeletons that match the final layout. Empty states use island's EmptyState (no-data, no-results, not-found, no-access) with one sentence and a primary action when there is one (error-handling.md).
  • Anything that takes more than about 2 seconds shows progress and the current step. Never show a bare spinner for more than 3 seconds.
  • The clicked button shows a spinner, becomes disabled, and changes its label to the in-progress form ("Placing order…"). The rest of the form stays visible and read-only.

File uploads

  • Every upload shows a progress bar with a numeric percentage ("Uploading… 63%"), the file name and size, a cancel button while uploading, and a clear success or failure state with a retry action. Uploads go through the feature client's upload(): its onProgress drives the bar, and the cancel button aborts the signal. Uploads never retry automatically; the retry action sends the file again (see lib-http.md).

Forms

  • Validate on the client with valibot before submitting, and show errors inline under the field in plain language that says how to fix them ("Enter a 10-digit postal code without spaces."). Validate on blur first, then on change (mode: 'onTouched').
  • Put server errors in the right place (code in code-patterns.md) and scroll to and focus the first invalid field.
  • Disable the submit button only while submitting, never because the form is invalid; users need to click it to find out what's wrong.

Keyboard and context

  • Tab order follows reading order, Enter submits, and Esc closes. Set sensible default focus and keep primary actions in consistent places.
  • Preserve context: filters, sort, page, and scroll position survive navigating to a detail page and back. Filters, sort, and page live in the URL, so views are shareable and survive a refresh.
  • Respect prefers-reduced-motion and prefers-color-scheme.
  • Every scroll the page starts is smooth: anchor jumps, scrollIntoView, and scrollTo animate instead of jumping, so the user sees where they went. island's island.css sets scroll-behavior: smooth on every element and turns it off under prefers-reduced-motion (code-patterns.md). Code that scrolls never passes behavior, so the CSS and the user's motion setting decide.
    • Every root layout's <html> has data-scroll-behavior="smooth". Without it, Next.js 16 animates the jump to the top on every route change.
    • A scroll container that code holds in place, such as a virtualized list or a chat log pinned to its end, adds scroll-auto, or every position fix animates.