Design Glossary
Definitions connected to actual decisions, failures, source contracts and platform boundaries.
Reference and local meaning
The rendered Material A–Z inventory captured on 2026-10-14 has 67 headings. Each is represented here with an independently authored explanation for this project, alongside local implementation vocabulary. This is a terminology map, not a copy of Material’s definitions or a claim that every referenced platform API is implemented.
Color-generation, DSP and XR terms keep their implementation boundaries explicit. Follow the related guidance to inspect actual code and verification; a term name alone cannot establish a task outcome or language authority.
Find and use a term
Matches all typed words against authored names, definitions, decisions and failures. No inferred synonyms or external search.
93 of 93 entries shown.
Accessible name
Accessibility · Local implementation vocabulary
The name identifies a control or object in the accessibility tree.
Use here: Include the visible action label and inspect the resulting computed name.
Watch for: A nearby text node or decorative SVG title may not name the intended control.
Adaptive design
Foundations · Material reference heading, locally authored explanation
A layout changes its arrangement when the available space or task context calls for another structure.
Use here: Use the bar, rail and drawer pattern to inspect real destination changes and preserved drafts.
Watch for: A smaller copy of a desktop screenshot does not demonstrate an adapted interaction model.
Anatomy
Implementation · Local implementation vocabulary
Rendered parts and their relationships make up a component’s structure.
Use here: Trace trigger, positioner, popup, content and close action to real exported parts.
Watch for: A prop table alone does not show where focus or a label belongs.
App bar
Components · Material reference heading, locally authored explanation
A header groups a task title, destinations and relevant commands.
Use here: Keep Back ancestry meaningful and measure sticky-header clearance.
Watch for: A sticky header can obscure the heading or focused field it is meant to support.
ARIA role
Accessibility · Local implementation vocabulary
An accessibility role communicates an interaction or structural model to assistive technology.
Use here: Prefer native semantics and implement the full expected keyboard behavior for composite widgets.
Watch for: Changing a role attribute alone cannot create a usable grid or menu.
Attestation
Content · Local implementation vocabulary
A language form or claim is connected to retrievable source evidence under a stated scope.
Use here: Keep the source edition and evidence span separate from interface fixtures.
Watch for: A model output or matching surname is not source attestation.
Authority
Content · Local implementation vocabulary
A person or body has an explicitly relevant mandate for a particular decision.
Use here: Keep qualified language/cultural review distinct from interface usability observations.
Watch for: One participant cannot grant authority for every community or publication context.
Authorization
Content · Local implementation vocabulary
A system decides whether the current actor may perform an operation on a resource.
Use here: Enforce capability checks at the actual server/data boundary.
Watch for: A hidden button or simulated role picker is not access control.
Banner
Components · Material reference heading, locally authored explanation
Persistent inline information placed where it can explain a page-wide condition.
Use here: Use an Alert with a clear recovery action for a condition that should remain available.
Watch for: A dismissed transient notice cannot carry the only essential failure explanation.
Bottom sheet
Components · Material reference heading, locally authored explanation
A supporting surface entering from the bottom edge of the current view.
Use here: Use bottom-side Drawer for a bounded supporting task; stage changes until applied.
Watch for: Dragging must not be the only way to dismiss or complete its task.
Breakpoint
Foundations · Local implementation vocabulary
A threshold selects a layout rule under a stated measurement.
Use here: Inspect real space, long content and actual destination behavior around the threshold.
Watch for: A device label is not a reliable substitute for available width.
Button
Components · Material reference heading, locally authored explanation
An action control that invokes a command or submits a form.
Use here: Choose its native type and expose pending, outcome and retry behavior.
Watch for: A navigation link styled as a button still needs an href and link semantics.
Card
Components · Material reference heading, locally authored explanation
A surface grouping information and its related actions.
Use here: Give individual actions native names and targets.
Watch for: Making the entire card clickable can create nested controls or an unnamed command.
Checkbox
Components · Material reference heading, locally authored explanation
An independent binary choice; a mixed state can describe a group containing different values.
Use here: Use the group example to inspect real selected IDs and mixed state.
Watch for: A mixed summary is not a third arbitrary stored value for every item.
Chip
Components · Material reference heading, locally authored explanation
A compact labelled item whose interaction may select, invoke or remove something.
Use here: Pick one documented role and make removal preserve focus and meaning.
Watch for: One visual shape cannot silently alternate between button, checkbox and navigation semantics.
Color: Baseline scheme
Color · Material reference heading, locally authored explanation
The default collection of color roles before optional personalization.
Use here: MobTranslate defaults come from tokens.css in light and dark themes.
Watch for: Its Earth palette is not an implementation of Material’s baseline algorithm.
Color: Dynamic color
Color · Material reference heading, locally authored explanation
Color choices can be generated from inputs and resolved for conditions such as theme or contrast.
Use here: The Color Schemes tool uses the pinned Material Color Utilities SDK for actual local generation, role inspection and an original image-fixture source.
Watch for: The UI package’s authored Earth roles and light/dark switch remain distinct from that opt-in proposal tool or a device wallpaper service.
Color: Extended color
Color · Material reference heading, locally authored explanation
Additional role colors support meanings that the main action palette does not cover.
Use here: Keep success, warning, error and information paired with readable foregrounds.
Watch for: A color alone cannot establish review status or authorize publication.
Color: Key color
Color · Material reference heading, locally authored explanation
A palette input selected to influence a family of related role colors.
Use here: Distinguish an algorithm input from an already resolved primary CSS role.
Watch for: Picking a hex value does not automatically produce a checked scheme.
Color: Scheme
Color · Material reference heading, locally authored explanation
A coordinated set of named fills, foregrounds and state colors for a presentation context.
Use here: Inspect the actual role pairs and their hover/focus states in both themes.
Watch for: Matching a brand color is not proof that every foreground is readable.
Color: Source color
Color · Material reference heading, locally authored explanation
An input color used as the starting point for a color-generation process.
Use here: Use the existing Color Schemes tool to generate and inspect a source-color proposal.
Watch for: A source color is unrelated to source attestation for language content.
Color: Tonal palette
Color · Material reference heading, locally authored explanation
A generated family varies lightness while following a chosen color model.
Use here: Material Color Utilities documents its tonal-palette implementation; local CSS shade numbers are authored names.
Watch for: Do not treat 50–950 shade keys as HCT tone measurements.
Color: Tone
Color · Material reference heading, locally authored explanation
Lightness in the chosen color model is distinct from hue and saturation/chroma.
Use here: Our contrast checker uses sRGB relative luminance and the WCAG ratio calculation.
Watch for: A tone label cannot replace checking a rendered text/background pair.
Color: User-generated schemes
Color · Material reference heading, locally authored explanation
A presentation palette is generated from a user-selected input under a defined policy.
Use here: The local SDK tool supports chosen seeds, variants and captured proposals; keep defaults and inspect actual pairs before applying them.
Watch for: An exported proposal is not an OS palette integration or a released global personalization service.
Composition
Implementation · Local implementation vocabulary
Native and exported parts are arranged into an application-owned task.
Use here: Preserve handlers, refs, names, form types and focus through composition.
Watch for: Nested buttons or duplicated registration can break the task despite a valid screenshot.
Condition
Foundations · Material reference heading, locally authored explanation
An observed circumstance selects a layout or interaction policy.
Use here: Measure viewport and available space instead of assuming a device name determines layout.
Watch for: A breakpoint cannot establish network availability, permission or language authority.
Consent
Content · Local implementation vocabulary
Permission for a specified activity is understood and given under agreed conditions.
Use here: Separate participation, recording, sharing and publication decisions.
Watch for: Joining a usability session does not authorize training or public cultural content.
Contrast
Color · Material reference heading, locally authored explanation
A measure of difference between presented colors; text readability is checked for its actual foreground/background pair.
Use here: Use the live ratio tool and inspect actual role/state pairs. Material’s glossary uses tone differences 40/50 as shorthand; the installed SDK gives about 4.484 for nominal tones 50/100, below a strict 4.5 test.
Watch for: One passing text ratio does not certify a whole component or page.
Controlled state
Implementation · Local implementation vocabulary
The consuming component owns the current value and applies updates through its state model.
Use here: Keep reset, validation, cancellation and loaded outcomes explicit.
Watch for: A defaultValue is an initial value, not a controlled update mechanism.
Customization
Implementation · Material reference heading, locally authored explanation
A consumer deliberately changes presentation or composition while retaining the interaction contract.
Use here: Scope CSS roles and test portals, readable pairs and saved preferences.
Watch for: A wrapper override does not necessarily reach body-mounted popups.
Dark theme
Color · Material reference heading, locally authored explanation
A dark presentation context has its own surface, foreground and state roles.
Use here: Select explicit .dark or .light so a saved choice can override system preference.
Watch for: Inverting colors or changing only the page background is insufficient.
Data table
Components · Material reference heading, locally authored explanation
Rows and columns represent related records with named headers and appropriate actions.
Use here: Keep sorting, filtering, selection, paging and detail ownership explicit.
Watch for: A native table does not automatically have an interactive grid keyboard model.
Date picker
Components · Material reference heading, locally authored explanation
A control chooses a civil calendar date or range.
Use here: The web pattern uses native inputs and validates date ordering without pretending to book an instant.
Watch for: A date string is not a timezone-aware timestamp.
Design attribute
Implementation · Material reference heading, locally authored explanation
A specified property of a part, such as its padding, radius or target size.
Use here: Trace the property to its CSS binding and measure the actual rendered part.
Watch for: A painted marker and its interaction target can have different dimensions.
Design guidelines
Foundations · Material reference heading, locally authored explanation
Decision guidance explains when to use a pattern and how to evaluate tradeoffs.
Use here: Read usage, failure and verification sections alongside an API table.
Watch for: A rule without task context can be applied mechanically to the wrong problem.
Design specs
Implementation · Material reference heading, locally authored explanation
A specification records parts, constraints, states and measurable behavior.
Use here: Use the source/render register for authored values and the live inspector for contextual geometry.
Watch for: An auto or min() constraint is not one fixed pixel dimension.
Design System Package (DSP)
Platform · Material reference heading, locally authored explanation
A tooling interchange format can bundle design-system data for compatible authoring tools.
Use here: The Material reference links the Adobe DSP format. This workspace’s source package and JSON exports have their own contracts.
Watch for: Do not advertise DSP conformance merely because a file contains token JSON.
Design tokens
Implementation · Material reference heading, locally authored explanation
Named presentation decisions provide reusable values and dependencies.
Use here: Edit authoritative CSS and regenerate/check its TypeScript and catalogue outputs.
Watch for: An imported snapshot does not watch runtime theme changes.
Design tokens: Context
Implementation · Material reference heading, locally authored explanation
The circumstances under which a token value is resolved include theme and ancestor scope.
Use here: Compare authored values with live inherited CSS using the Theming inspector.
Watch for: A global default can differ from a portalled or scoped instance.
Design tokens: Role
Implementation · Material reference heading, locally authored explanation
A semantic name states the intended job of a value.
Use here: Use primary-foreground with primary rather than selecting an unrelated shade.
Watch for: A role name does not ensure sufficient contrast after customization.
Design tokens: Types
Implementation · Material reference heading, locally authored explanation
Primitive values, semantic roles and component specifications have distinct responsibilities.
Use here: Inspect palette, CSS roles and component bindings at their own layers.
Watch for: A component preset is not a complete React style object.
Design tokens: Value
Implementation · Material reference heading, locally authored explanation
The concrete value or expression attached to a named token.
Use here: Keep authored expressions, resolved CSS and rectangles distinguishable.
Watch for: Serializing rem or var() as though it were a final pixel result loses context.
Dialog
Components · Material reference heading, locally authored explanation
A bounded task surface can control background interaction and focus.
Use here: Preserve drafts, define dismissal and return focus to a meaningful destination.
Watch for: A backdrop graphic does not itself implement modality.
Direction
Content · Local implementation vocabulary
Text and layout direction determine bidi processing and logical geometry.
Use here: Keep known language metadata, unknown-text isolation and mirrored layout decisions separate.
Watch for: English prose in an RTL shell still needs an appropriate content direction.
Divider
Components · Material reference heading, locally authored explanation
A line separates adjacent content or presents a semantic boundary.
Use here: Use Separator and distinguish structural versus decorative presentation.
Watch for: A visual line cannot repair missing headings or group semantics.
Draft
Implementation · Local implementation vocabulary
Uncommitted user intent is retained separately from the applied or loaded result.
Use here: Keep a rejected replacement from erasing the previously loaded outcome.
Watch for: A visible edited value does not mean a durable save succeeded.
Element
Foundations · Material reference heading, locally authored explanation
A rendered constituent can be a semantic DOM node, a component part or a decorative mark.
Use here: Inspect the actual node and accessible relationship before naming a role.
Watch for: Not every visible shape is an independently interactive control.
Elevation
Foundations · Local implementation vocabulary
Surfaces are distinguished through layering, borders and appropriate shadows.
Use here: Use actual theme-aware shadows and explicit overlay stacking.
Watch for: A shadow does not define modality or source authority.
Extended FAB
Components · Material reference heading, locally authored explanation
A floating-action style includes a visible action label as well as its symbol.
Use here: Allow the label to wrap and keep placement clear of reading and recovery actions.
Watch for: An extended label does not authorize a fixed overlay covering content.
Floating action button (FAB)
Components · Material reference heading, locally authored explanation
A prominent primary action has a distinct compact surface.
Use here: Use the exported labelled action and let the consuming layout own placement.
Watch for: The most visually prominent action need not be the most frequent or safest action.
Focus
Accessibility · Local implementation vocabulary
The current keyboard interaction destination is maintained explicitly through task changes.
Use here: Restore a meaningful control after dismissal or removal.
Watch for: Focus movement does not automatically establish selection or completion.
HCT
Color · Material reference heading, locally authored explanation
Hue, chroma and tone combine CAM16 hue/chroma with a CIELAB L-star tone coordinate in Material Color Utilities.
Use here: The Color Schemes tool uses the installed SDK for HCT conversion and actual palette/role generation; the UI package keeps its authored CSS contract.
Watch for: Do not infer an HCT coordinate from a local shade key or treat an algorithm result as calibrated physical perception.
Image list
Content · Material reference heading, locally authored explanation
A collection arranges images with the text and actions needed to understand them.
Use here: Use a native list/grid with source, rights and meaningful alternative text in the consuming app.
Watch for: Generated illustration, identity and actual camera-made evidence must remain distinguishable.
Libraries
Platform · Material reference heading, locally authored explanation
Reusable packages provide implementations under particular framework and platform contracts.
Use here: This private workspace package targets React, DOM and CSS; inspect its actual pinned dependencies.
Watch for: A Material taxonomy match does not imply native Compose or Flutter API compatibility.
List
Components · Material reference heading, locally authored explanation
A sequence groups records or tasks and their related actions.
Use here: Use native list structure and preserve each row’s label and outcome.
Watch for: A list is not automatically a menu, table or grid.
Locale
Content · Local implementation vocabulary
A formatting/interface choice specifies conventions such as number and date display.
Use here: Validate locale input and keep it separate from content-language metadata.
Watch for: Formatting a value cannot infer the language or pronunciation of source text.
Material Components
Platform · Material reference heading, locally authored explanation
Material implementation libraries translate design guidance into platform-specific APIs.
Use here: The coverage map names local equivalents and their implementation owners.
Watch for: MobTranslate’s wrappers do not inherit upstream Material behavior or guarantees.
Material Design
Foundations · Material reference heading, locally authored explanation
Google’s design-system reference supplies a comparison taxonomy for this work.
Use here: Use the primary reference alongside actual source, task outcomes and platform boundaries.
Watch for: Counting matching topic names is not proof of equivalent documentation depth.
Material Theming
Color · Material reference heading, locally authored explanation
Material tooling connects its role model to supported platform implementations.
Use here: This project has its own CSS theme contract; keep the distinction explicit when adopting external tooling.
Watch for: Earth-role overrides do not demonstrate Material Theme Builder integration.
Menu
Components · Material reference heading, locally authored explanation
A popup exposes commands or choices with a defined keyboard model.
Use here: Keep selection, highlight, unavailable items and submenus distinct.
Watch for: Navigation destinations and editing forms may need a different composition.
Modal
Accessibility · Local implementation vocabulary
A task surface temporarily controls background interaction and focus.
Use here: Verify initial focus, containment, Escape policy and return destination.
Watch for: A fixed overlay with a dark background is not sufficient.
Mode
Foundations · Material reference heading, locally authored explanation
A presentation or interaction configuration changes how a task is performed or displayed.
Use here: State whether a mode affects appearance, editing or capabilities.
Watch for: A selected mode label cannot confer authorization.
Navigation bar
Components · Material reference heading, locally authored explanation
A compact destination model exposes a small set of primary locations.
Use here: Use actual destinations and retain the task state when layout changes.
Watch for: A row of buttons with no navigation outcomes is only decoration.
Navigation drawer
Components · Material reference heading, locally authored explanation
A destination surface can be persistent or temporarily modal in a compact layout.
Use here: Verify dismissal, arrival focus, history and retained drafts.
Watch for: A filter drawer and a destination drawer have different application state ownership.
Navigation rail
Components · Material reference heading, locally authored explanation
A persistent intermediate-width destination model groups locations along an edge.
Use here: Measure the adaptive pattern and keep labels/names available.
Watch for: Vertical tabs do not become application navigation merely by moving to an edge.
Orbiter
Platform · Material reference heading, locally authored explanation
An XR interaction surface can sit alongside a spatial content panel.
Use here: The Material glossary treats this as spatial UI. This DOM package has no XR panel anchoring or tracking API.
Watch for: A CSS-positioned toolbar is not an implemented XR orbiter.
Outcome
Implementation · Local implementation vocabulary
An operation has a returned or persisted effect under its actual acceptance condition.
Use here: State whether the example updates page memory, local storage or a real service.
Watch for: A process starting or a request being submitted does not prove the requested effect.
Pane
Foundations · Material reference heading, locally authored explanation
A task region groups content or supporting actions within a larger layout.
Use here: Use labelled regions and responsive arrangements that preserve reading and focus order.
Watch for: A visual column is not automatically a new landmark or dialog.
Portal
Implementation · Local implementation vocabulary
A rendered subtree is mounted at another DOM location while retaining its React relationships.
Use here: Inspect inherited CSS and actual page-bound overlay geometry.
Watch for: React context preservation does not guarantee CSS ancestor inheritance.
Progress indicator
Components · Material reference heading, locally authored explanation
A named status displays known progress or explicitly unknown-total activity.
Use here: Tie its value and announcements to the actual operation and outcome.
Watch for: An animated loop does not prove that work is advancing.
Provenance
Content · Local implementation vocabulary
An artifact or decision retains its origin, revision and supporting evidence.
Use here: Keep source bytes, generated lineage and scoped review records traceable.
Watch for: A generic guide URL does not establish dictionary-word provenance.
Radio button
Components · Material reference heading, locally authored explanation
A group commits one available choice from its set.
Use here: Name the group and verify arrows, required correction and submitted value.
Watch for: Moving focus alone need not commit a remote operation.
Reduced motion
Accessibility · Local implementation vocabulary
A preference calls for avoiding unnecessary motion and preserving an immediate usable outcome.
Use here: Test cancellation and the final state in the motion lab.
Watch for: Removing animation must not remove the result or recovery controls.
Reflow
Accessibility · Local implementation vocabulary
Content adapts to smaller available dimensions without losing essential information or operation.
Use here: Check real 320px width, zoom, text spacing and necessary table/viewport scrolling.
Watch for: Shrinking text or rasterizing the interface is not a reflow solution.
Revision
Content · Local implementation vocabulary
A new identified version separates changed content from earlier evidence and decisions.
Use here: Review the exact current revision and retain prior decisions as history.
Watch for: A previous approval need not apply to the changed text.
Role
Implementation · Material reference heading, locally authored explanation
In design-token vocabulary, the role identifies the value’s intended presentation job.
Use here: Distinguish it from ARIA roles and application permissions in implementation reviews.
Watch for: Primary, button and reviewer refer to different kinds of role.
Selection
Implementation · Local implementation vocabulary
A committed choice is separate from focus, hover and draft text.
Use here: Verify native values and the operation’s explicit commit policy.
Watch for: A highlighted suggestion is not automatically the submitted entity ID.
Side sheet
Components · Material reference heading, locally authored explanation
An edge surface supports a task or supplemental information.
Use here: Use side Drawer and preserve the main task and staged changes.
Watch for: The side of the screen does not determine whether the surface should be modal.
Slider
Components · Material reference heading, locally authored explanation
A scalar or range control changes a value within declared bounds.
Use here: Name units, expose the current value and provide native keyboard alternatives.
Watch for: A 20px painted marker is not the 44px target in this implementation.
Snackbar
Components · Material reference heading, locally authored explanation
A brief notification reports an event and may expose a related command.
Use here: Use the Toast provider, clear duration policy and recovery that survives dismissal.
Watch for: The transient notice cannot contain the only essential error or source citation.
Spatial
Platform · Material reference heading, locally authored explanation
Spatial UI positions content and interaction in a tracked three-dimensional context.
Use here: World anchoring, comfort, depth and XR input require their platform’s own design and runtime checks.
Watch for: CSS elevation and a simulated 3D transform do not demonstrate a tracked spatial interface.
State
Implementation · Local implementation vocabulary
Current values, availability, errors and progress determine an interaction’s behavior.
Use here: Inspect applicable rest, hover, focus, selected, disabled, pending and failure conditions.
Watch for: A decorative variant list is not a state-machine verification.
Style
Foundations · Material reference heading, locally authored explanation
Presentation properties express hierarchy and meaning while semantics and behavior remain separate contracts.
Use here: Use source-derived tokens and verify all applicable states.
Watch for: A matching screenshot does not prove usable control behavior.
Supersession
Implementation · Local implementation vocabulary
A later intent or revision replaces an earlier candidate under a declared policy.
Use here: Guard against late request results and retain the last valid loaded outcome.
Watch for: Ignoring abort does not authorize an obsolete result to overwrite the current view.
Switch
Components · Material reference heading, locally authored explanation
A binary setting communicates an on/off state.
Use here: Decide whether changes apply immediately or belong to a submitted draft.
Watch for: A successful toggle event is not proof that a remote setting persisted.
Tab
Components · Material reference heading, locally authored explanation
Local panel navigation exposes one selected panel under a named tab list.
Use here: Define automatic/manual activation and preserve editing state across panels.
Watch for: Focus, selection and route arrival are not interchangeable.
Target size
Accessibility · Local implementation vocabulary
The operable pointer area can include an associated label and differ from the visible marker.
Use here: Measure actual controls and preserve keyboard/single-pointer alternatives.
Watch for: A glyph’s dimensions alone cannot prove adequate targets.
Text field
Components · Material reference heading, locally authored explanation
A labelled native input or textarea receives a text value.
Use here: Connect persistent help/error text, constraints and native submitted entries.
Watch for: Placeholder text cannot replace a persistent accessible label.
Theme
Color · Material reference heading, locally authored explanation
A coordinated presentation context combines roles, surfaces, type and shape.
Use here: Inspect explicit light/dark preference, inheritance, storage failure and portals.
Watch for: A changed theme does not alter evidence or publication authority.
Time picker
Components · Material reference heading, locally authored explanation
A control chooses a civil clock time, with a separately stated timezone context.
Use here: The date/time pattern validates inputs and preserves the requested zone metadata.
Watch for: A local clock value does not resolve daylight-saving ambiguity by itself.
Toolbar
Components · Material reference heading, locally authored explanation
A named command group can use a composite keyboard model.
Use here: Use the exported Toolbar when arrow navigation is appropriate; distinguish it from a plain action row.
Watch for: Grouping native buttons visually does not automatically implement roving focus.
Tooltip
Components · Material reference heading, locally authored explanation
A supplemental description appears on appropriate hover/focus interaction.
Use here: Keep essential instructions available without it and verify the actual described-by relationship.
Watch for: A tooltip is not an editor, confirmation dialog or sole accessible name.
XR
Platform · Material reference heading, locally authored explanation
Extended-reality platforms have input, tracking and spatial layout contracts beyond ordinary DOM rendering.
Use here: Reference terms are documented here without claiming a headset runtime or native SDK integration.
Watch for: A responsive web preview cannot prove spatial comfort or device tracking.
Maintain the reference
Edit the authored data in content/glossary.ts. Re-capture the rendered primary inventory when the reference changes; retain new headings as work. The check compares every reference heading, requires definitions/decisions/failures, verifies unique entry fragments and checks related routes against navigation.
pnpm --filter styleguide glossary:check
pnpm --filter styleguide examples:check
pnpm --filter styleguide build
# After starting the production preview:
pnpm --filter styleguide test:inclusive-glossaryChecked filter and link implementation
All entries are available in server-rendered HTML. Filtering becomes operable after hydration. Entry links remain unfiltered shareable destinations, hash navigation reveals and focuses their headings, and clipboard failure preserves a manual link alternative.
'use client';
import { useEffect, useRef, useState } from 'react';
import { glossaryEntries, glossaryId } from '../content/glossary';
import { searchTerms } from '../lib/document-search';
import { Button } from '@mobtranslate/ui';
const categories = [...new Set(glossaryEntries.map(entry => entry.category))].sort();
export function GlossaryExplorer() {
const [ready, setReady] = useState(false);
const [query, setQuery] = useState('');
const [category, setCategory] = useState('all');
const [status, setStatus] = useState('');
const [copying, setCopying] = useState(false);
const [target, setTarget] = useState('');
const copyEpoch = useRef(0);
const copyBusy = useRef(false);
const terms = searchTerms(query);
const entries = glossaryEntries.filter(entry => (category === 'all' || entry.category === category)
&& terms.every(term => `${entry.term} ${entry.category} ${entry.definition} ${entry.decision} ${entry.failure}`.toLocaleLowerCase('en').includes(term)));
useEffect(() => {
setReady(true);
const reveal = () => {
let id;
try { id = decodeURIComponent(location.hash.slice(1)); } catch { return; }
if (!glossaryEntries.some(entry => glossaryId(entry.term) === id)) return;
setQuery(''); setCategory('all'); setTarget(id);
};
reveal(); window.addEventListener('hashchange', reveal);
return () => { window.removeEventListener('hashchange', reveal); copyEpoch.current++; };
}, []);
useEffect(() => {
if (!target) return;
const frame = requestAnimationFrame(() => {
const heading = document.getElementById(target);
heading?.focus({ preventScroll: true }); heading?.scrollIntoView({ block: 'start' }); setTarget('');
});
return () => cancelAnimationFrame(frame);
}, [target, entries.length]);
async function copy(term: string) {
if (copyBusy.current) return;
copyBusy.current = true; setCopying(true); setStatus(`Copying the entry link for ${term}…`);
const epoch = ++copyEpoch.current;
const url = new URL(`/guides/glossary#${glossaryId(term)}`, location.origin).href;
try {
await navigator.clipboard.writeText(url);
if (copyEpoch.current === epoch) setStatus(`Copied the entry link for ${term}.`);
} catch {
if (copyEpoch.current === epoch) setStatus(`Clipboard unavailable. Use the heading link for ${term}, or copy its address manually.`);
} finally {
copyBusy.current = false;
if (copyEpoch.current === epoch) setCopying(false);
}
}
return <div data-glossary-ready={ready}>
<div className="space-y-4 mb-6">
<label className="block" htmlFor="glossary-query" lang="en" dir="auto">Find a term or implementation concern</label>
<input id="glossary-query" className="mt-input w-full" type="search" disabled={!ready} value={query} onChange={event => setQuery(event.target.value)} aria-describedby="glossary-search-help" />
<p id="glossary-search-help" lang="en" dir="auto">Matches all typed words against authored names, definitions, decisions and failures. No inferred synonyms or external search.</p>
<label className="block" htmlFor="glossary-category" lang="en" dir="auto">Topic category</label>
<select id="glossary-category" className="mt-input w-full" disabled={!ready} value={category} onChange={event => setCategory(event.target.value)}><option value="all">All categories</option>{categories.map(value => <option key={value} value={value}>{value}</option>)}</select>
<Button type="button" variant="outline" disabled={!ready} onClick={() => { setQuery(''); setCategory('all'); document.getElementById('glossary-query')?.focus(); }}>Clear glossary filters</Button>
<p role="status" data-glossary-count lang="en" dir="auto">{entries.length} of {glossaryEntries.length} entries shown.</p>
<p role="status" data-glossary-copy lang="en" dir="auto">{status}</p>
</div>
{!entries.length && <p lang="en" dir="auto">No entries match these filters. Clear the filters or use fewer words; the complete register remains available.</p>}
<nav aria-label="Visible glossary terms" className="doc-links mb-6">{entries.map(entry => <a key={entry.term} href={`#${glossaryId(entry.term)}`}><bdi>{entry.term}</bdi></a>)}</nav>
<div data-glossary-entries>{entries.map(entry => <section key={entry.term} className="mb-8" aria-labelledby={glossaryId(entry.term)} lang="en" dir="auto">
<h3 id={glossaryId(entry.term)} tabIndex={-1} className="text-xl font-semibold mb-2 scroll-mt-24 lg:scroll-mt-6"><a href={`#${glossaryId(entry.term)}`} className="underline">{entry.term}</a></h3>
<p className="text-sm mb-2">{entry.category} · {entry.material ? 'Material reference heading, locally authored explanation' : 'Local implementation vocabulary'}</p>
<p className="mb-2">{entry.definition}</p>
<p className="mb-2"><strong>Use here: </strong>{entry.decision}</p>
<p className="mb-3"><strong>Watch for: </strong>{entry.failure}</p>
<div className="flex flex-wrap items-center gap-3"><a href={entry.href} className="underline">Related guidance for {entry.term}</a><Button type="button" variant="outline" disabled={!ready} aria-disabled={copying || undefined} style={{ height: 'auto', minHeight: 44, maxWidth: '100%', whiteSpace: 'normal', overflowWrap: 'anywhere', opacity: copying ? .6 : 1 }} onClick={() => copy(entry.term)}>Copy link for {entry.term}</Button></div>
</section>)}</div>
</div>;
}