All files / packages/design-system-2-site/src/app/(frontend)/styling-api/styling-hook-index StylingHookIndex.tsx

100% Statements 99/99
97.87% Branches 46/47
100% Functions 25/25
100% Lines 84/84

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 2971x                                                           1x           8984x 1572x                 7510x       1178x   336x 336x     852x 852x 795x 795x 201x         594x           1x       12x                                             24x 24x 24x 24x 24x 24x 24x   24x     24x 24x 10x 11x 11x 11x 1x 1x 1x 1x   10x 10x   24x 12x 1x 12x 12x     24x 2x 2x 2x 1x 1x     1x 1x   2x 1x 1x       24x 24x   24x 19x 19x 950x 8984x 858x   19x       24x   962x 24x           24x         2x                           24x                   1x       240x                                                     962x 962x 196x 196x 196x                 962x 20x 20x                 962x   962x 962x 962x 962x                           1x                   10038x                          
'use client';
 
import Link from 'next/link';
import {
  createContext,
  Fragment,
  type ReactNode,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useRef,
  useState,
} from 'react';
import type { Crumb } from '@/components/Breadcrumbs';
import { DocShell } from '@/components/DocShell';
import { HeroSplit } from '@/components/HeroSplit';
import { ViewMarkdownButton } from '@/components/ViewMarkdownButton';
import { Combobox } from '@/components/ui/Combobox';
import { DataTable } from '@/components/ui/DataTable';
import { SearchBar } from '@/components/ui/SearchBar';
import { Switch } from '@/components/ui/Switch';
import { Tag } from '@/components/ui/Tag';
import type { Theme } from '@/lib/design-tokens';
import type { TocItem } from '@/lib/markdown';
import { type ChipId, CHIPS, HEADING_DESCRIPTIONS, headingId } from '@/lib/styling-hook-groups';
import type { HookGroup, HookRow, StylingHookIndexData } from '@/lib/styling-hooks';
import { columnsFor, hasReferences } from './HookCells';
 
// Not `THEMES` from design-tokens: that module would bundle the token JSON into the client.
const THEME_OPTIONS: { value: Theme; label: string }[] = [
  { value: 'cosmos', label: 'Cosmos' },
  { value: 'lightning-blue', label: 'Lightning Blue' },
];
 
function matches(row: HookRow, q: string): boolean {
  if (!q) return true;
  return [
    row.name,
    row.description,
    row.light.value,
    row.light.paletteName,
    row.dark?.value,
    row.dark?.paletteName,
  ]
    .filter(Boolean)
    .some((text) => text!.toLowerCase().includes(q));
}
 
function Description({ text }: { text?: string }) {
  if (!text) return null;
  // Descriptions may wrap hook names in backticks and link with [label](/route).
  const parts = text.split(/(`[^`]+`|\[[^\]]+\]\([^)]+\))/);
  return (
    <p className="styling-hook-index__description">
      {parts.map((part, i) => {
        const code = part.match(/^`([^`]+)`$/);
        if (code) return <code key={i}>{code[1]}</code>;
        const link = part.match(/^\[([^\]]+)\]\(([^)]+)\)$/);
        if (link)
          return (
            <Link key={i} href={link[2]}>
              {link[1]}
            </Link>
          );
        return <Fragment key={i}>{part}</Fragment>;
      })}
    </p>
  );
}
 
const ThemeContext = createContext<Theme>('cosmos');
 
/** Copy Markdown for the theme selected in the enclosing `StylingHookIndex`. */
export function ThemeMarkdownButton({ markdown }: { markdown: Record<Theme, string> }) {
  return <ViewMarkdownButton markdown={markdown[useContext(ThemeContext)]} />;
}
 
/**
 * The whole Index page body: the hero holds the Theme select and the search,
 * so the shell renders here, next to the filter state. `children` (page
 * actions, pager) render after the tables.
 */
export function StylingHookIndex({
  data,
  breadcrumbs,
  title,
  description,
  toc,
  children,
}: {
  data: StylingHookIndexData;
  breadcrumbs: Crumb[];
  title: string;
  description: string;
  toc: TocItem[];
  children?: ReactNode;
}) {
  const [theme, setTheme] = useState<Theme>('cosmos');
  const [search, setSearch] = useState('');
  const [chip, setChip] = useState<ChipId | null>(null);
  const [showRefs, setShowRefs] = useState<Record<string, boolean>>({});
  const [copied, setCopied] = useState('');
  const [status, setStatus] = useState('');
  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
 
  useEffect(() => () => clearTimeout(timer.current), []);
 
  // An on-this-page link to a section the filters hide clears the filters, then scrolls once it renders.
  const [pendingTarget, setPendingTarget] = useState('');
  useEffect(() => {
    const onClick = (e: MouseEvent) => {
      const link = (e.target as Element).closest?.('.doc-shell__nav a[href^="#"]');
      const id = link?.getAttribute('href')!.slice(1);
      if (!id || document.getElementById(id)) return;
      e.preventDefault();
      setChip(null);
      setSearch('');
      setPendingTarget(id);
    };
    document.addEventListener('click', onClick);
    return () => document.removeEventListener('click', onClick);
  }, []);
  useEffect(() => {
    if (!pendingTarget) return;
    document.getElementById(pendingTarget)?.scrollIntoView();
    history.pushState(null, '', `#${pendingTarget}`);
    setPendingTarget('');
  }, [pendingTarget]);
 
  const onCopy = useCallback(async (name: string) => {
    clearTimeout(timer.current);
    try {
      await navigator.clipboard.writeText(name);
      setCopied(name);
      setStatus(`Copied ${name}`);
    } catch {
      // Clipboard access denied or unavailable (e.g. an insecure context).
      setCopied('');
      setStatus(`Couldn't copy ${name}`);
    }
    timer.current = setTimeout(() => {
      setCopied('');
      setStatus('');
    }, 2000);
  }, []);
 
  const index = data.themes[theme];
  const q = search.trim().toLowerCase();
 
  const groups = useMemo(() => {
    const visible: HookGroup[] = [];
    for (const group of index.groups) {
      if (chip && group.chip !== chip) continue;
      const rows = group.rows.filter((r) => matches(r, q));
      if (rows.length) visible.push({ ...group, rows });
    }
    return visible;
  }, [index, chip, q]);
 
  // A new array whenever the filters change, so DocShell's scroll-spy observes the re-rendered headings.
  const liveToc = useMemo(() => [...toc], [toc, groups]);
 
  const shown = groups.reduce((n, g) => n + g.rows.length, 0);
  const copy = { copied, onCopy };
 
  let section: string | undefined;
  let subsection: string | undefined;
 
  const controls = (
    <>
      <Combobox
        label="Theme"
        options={THEME_OPTIONS}
        defaultValue={theme}
        onChange={(value) => setTheme(value as Theme)}
        editable={false}
        containerClassName="styling-hook-index__theme"
      />
      <SearchBar
        value={search}
        onChange={setSearch}
        label="Filter Styling Hooks"
        placeholder="Filter Styling Hooks"
        className="styling-hook-index__search"
      />
    </>
  );
 
  return (
    <ThemeContext.Provider value={theme}>
      <DocShell
        toc={liveToc}
        heading={
          <HeroSplit breadcrumbs={breadcrumbs} title={title} description={description} aside={controls} />
        }
      >
        <div className="styling-hook-index">
          <div className="styling-hook-index__chips" role="group" aria-label="Filter by category">
            <Tag active={!chip} onClick={() => setChip(null)}>
              All ({index.total})
            </Tag>
            {CHIPS.map((c) => (
              <Tag key={c.id} active={chip === c.id} onClick={() => setChip(chip === c.id ? null : c.id)}>
                {c.label} ({index.chipCounts[c.id]})
              </Tag>
            ))}
          </div>
 
          <p className="styling-hook-index__count" aria-live="polite">
            {shown === index.total
              ? `${index.total} styling hooks`
              : `Showing ${shown} of ${index.total} styling hooks`}
          </p>
          {theme === 'lightning-blue' && (
            <p className="styling-hook-index__note">
              Lightning Blue hooks have a single value; they don&apos;t define dark mode values.
            </p>
          )}
 
          {/* Always rendered so the text change is announced; a region inserted with its text often isn't. */}
          <span className="site-visually-hidden" role="status">
            {status}
          </span>
 
          {groups.length === 0 && (
            <p className="styling-hook-index__empty">No styling hooks match &ldquo;{search.trim()}&rdquo;.</p>
          )}
 
          {groups.map((group) => {
            const headings = [];
            if (group.section !== section) {
              section = group.section;
              subsection = undefined;
              headings.push(
                <Fragment key="section">
                  <h2 id={headingId(section)} className="styling-hook-index__section">
                    {section}
                  </h2>
                  <Description text={HEADING_DESCRIPTIONS[section]} />
                </Fragment>,
              );
            }
            if (group.subsection && group.subsection !== subsection) {
              subsection = group.subsection;
              headings.push(
                <Fragment key="subsection">
                  <h3 id={headingId(subsection)} className="styling-hook-index__subsection">
                    {subsection}
                  </h3>
                  <Description text={HEADING_DESCRIPTIONS[subsection]} />
                </Fragment>,
              );
            }
            const GroupHeading = group.subsection ? 'h4' : 'h3';
            // A group named like its section (Spacing, Sizing) sits under the H2 without a heading of its own.
            const ownHeading = group.subsection || group.heading !== group.section;
            const groupHeadingId = ownHeading ? `hooks-${group.id}` : headingId(group.section);
            const refsOn = Boolean(showRefs[group.id]);
            return (
              <Fragment key={group.id}>
                {headings}
                <section className="styling-hook-index__group" aria-labelledby={groupHeadingId}>
                  {(ownHeading || hasReferences(group)) && (
                    <div className="styling-hook-index__group-header">
                      {ownHeading && (
                        <GroupHeading id={groupHeadingId} className="styling-hook-index__group-title">
                          {group.heading}
                        </GroupHeading>
                      )}
                      {hasReferences(group) && (
                        <Switch
                          checked={refsOn}
                          onChange={(on) => setShowRefs((prev) => ({ ...prev, [group.id]: on }))}
                          label="Show Reference Tokens"
                        />
                      )}
                    </div>
                  )}
                  <Description text={group.description} />
                  <DataTable
                    columns={columnsFor(group, refsOn, copy)}
                    rows={group.rows}
                    getRowKey={(r) => r.name}
                    labelledBy={groupHeadingId}
                  />
                </section>
              </Fragment>
            );
          })}
        </div>
        {children}
      </DocShell>
    </ThemeContext.Provider>
  );
}