Design system / Molecules & instances
CreativeXHub design system
Molecules & instances
Component taxonomy, product adapters and state ownership, illustrated through navigation and submission editing.
Bind reusable components to product behavior
This page explains component contracts, named instances and state ownership. For focused component contracts, use Molecules; for coordinated feature sections, use Organisms. Page compositions explains how those pieces fill templates and real route boundaries.
Responsibility, ownership and product binding
Responsibility
Classify the responsibility. A molecule completes one focused concern, such as selecting a value. An organism coordinates several concerns, such as listing, adding and removing members.
Ownership
Identify the code owner. Generic Button behavior belongs to the UI library. Submission copy, data contracts and rules belong to the submission feature.
Binding
Identify the product binding. A named instance supplies product copy, navigation, data mapping or behavior to a reusable component at any taxonomy layer.
The component vocabulary
- Foundation
- Tokens, typography, motion, icons and layout inputs. Home: src/theming.
- Atom
- An indivisible product-neutral control or display element with a focused API.
- Molecule
- Atoms completing one focused interaction or presentation concern.
- Organism
- A bounded section coordinating multiple concerns, such as a navigation header or manager.
- Template
- Page layout and slots, without fetching, authorization or business policy.
- Page / route
- The server boundary for rendering intent, authorized initial data and product composition.
Data and command boundaries
Server route: authorize + load initial data
→ instance: product copy, mapping, navigation, behavior contract
→ view: values, slots, feedback and callbacks
User intent → callback → behavior hook → operation contract
Result → hook state → visible feedbackInstances must not copy the abstraction’s structure/styles, encode raw API transport or perform route authorization. A stable or cross-route binding belongs beside its abstraction in instances/. One-off route assembly stays with its owner. Two consumers alone do not justify promotion to generic UI.
Choose the state owner
ADR-0032 defines state placement by responsibility. Keep a trivial selected tab local. Use a colocated behavior hook for asynchronous saves, external effects or coordinated interactions. Escalate to a reducer, Context or store only when their stated criteria apply.
- URL for shareable navigation; server boundary for authorized initial data.
- Local state for trivial view behavior.
- A colocated behavior hook from the first external effect, subscription, asynchronous lifecycle or coordinated multi-step interaction. Return state and commands, never JSX.
- A reducer when related transitions are clearer as events.
- Bounded Context for a stable ambient contract needed by many descendants—not a feature store or a shortcut past two prop levels.
- A client store only for demonstrated cross-surface coordination needs, with a dedicated ADR.
Reusing a hook shares logic, not the same state instance. Sharing one draft requires an explicit common owner.
docs/decisions/ADR-0032-client-behavior-and-state-escalation.mdComposable navigation: links, submenus and sections
SectionNavigation coordinates a navigation-owned organism, not a sidebar template or a product route. SectionNavigationLink renders one destination with explicit prefix and label slots; SectionNavigationSubmenu groups related links. The organism composes those focused molecules with disclosure, parent/child selection and vertical/horizontal/responsive placement. Callers supply destinations and active IDs; the organism does not read the URL or load data. Selection is controlled; only disclosure is local.
Real SectionNavigation organism, constrained by its supported className to exercise wrapped labels.
| Input | Intent | Owner |
|---|---|---|
| items | Stable id, label, href, optional non-interactive prefix and one-level children | The caller/instance supplies content; the organism composes shared link/submenu molecules. |
| prefixDecorative | True by default; false when the index belongs in the accessible link name | The content owner decides meaning; meaningful prefixes and labels are separated for assistive technology. |
| activeId / activeChildId | Marks the selected page, or the selected child with its ancestor highlighted | The URL owner supplies selection; disclosure is separate local view state. |
| children | Separate submenu button and bounded link group; current section opens initially and can be closed | The organism owns disclosure, aria-expanded/controls and mobile/desktop panel placement. |
| orientation | vertical by default; horizontal; responsive (scrolling primary strip with bounded submenus on narrow screens, nested vertical layout from md) | The organism owns layout; instances choose the supported contract. |
| className / native nav props | Outer placement/width, accessible landmark name and standard attributes/ref | Consumers do not duplicate link or prefix/label internals. |
DocumentationNavigation is the named cross-documentation-route instance beside the organism. It binds the catalogue, two-digit numbering, landmark copy and responsive orientation. DocsShell supplies URL-derived section/family IDs, server-projected molecule names and outer placement; the instance does not reproduce links or styles. The live documentation menu is this instance, not an independently styled example.
Different font metrics can look offset even when their line boxes are centered. SectionNavigationLink centers explicit Text slots and uses local cap/alphabetic font-box trimming where supported, with normal flex centering as the fallback. It keeps a token-backed minimum row target based on existing supporting line height and padding. There are no pixel nudges, descendant overrides, global Text/theme changes or new typography values. Wrapped labels remain centered with their prefix.
Responsive navigation exposes one CSS-selected presentation at a time: a scrolling primary strip with bounded child groups below it on narrow screens, or child groups immediately following their owning control on desktop. Both compose the same link/submenu pieces and share disclosure state, with distinct control IDs. Native Tab and Shift+Tab follow the visible sequence; closed groups are not keyboard stops.
src/components/navigation/section-navigation.tsxsrc/components/navigation/instances/documentation-navigation.tsx| Component | Supported inputs | Responsibility |
|---|---|---|
| SectionNavigationLink | item; current; branch | One real link with aligned prefix/label, current-page semantics and separate ancestor treatment. No URL reads or disclosure state. |
| SectionNavigationSubmenu | items; activeId; native group props including id, aria-label, hidden, className and style/ref | A labelled link collection. The composing owner supplies selection, visibility and outer placement; it reuses SectionNavigationLink rather than copying its styles. |
Repository path: src/components/navigation/section-navigation-link.tsx
Repository path: src/components/navigation/section-navigation-submenu.tsx
A focused contract: the generic inline editor
Current component with fictional data. Example changes are not persisted.
A shared language
Save updates only local text. The selector supplies pending/error props; it does not simulate a network request.
InlineEditableField receives draft, editing, saving and error values plus caller-supplied commands. This specimen supplies local state only. Current submission editing uses the shared batch form under ADR-0084, not this generic single-field editor. The save walkthrough below describes that separate product integration.
Compact edition controls
The intake list is a separate route-owned organism. Its EditionSubmissionsTable contract documents Include, URL-backed table/cards, grouping, pending/errors and the authorized integration. The review-results specimen does not substitute for this parent contract.
Current component with fictional data. Example changes are not persisted.
InlineEditTrigger is a product-neutral atom for an editable value without a permanent Edit button. It forwards native button props and ref, including disabled, onClick, aria-label and aria-expanded. Its children provide the visible value. The owner supplies an accessible action name, editor, initial focus, save/cancel behavior and focus restoration. Only the pencil changes on hover: the background, foreground and outline stay unchanged. Keyboard focus retains a visible ring. One tap on the value opens its editor directly; there is no reveal-then-tap step. Native Enter and Space also activate the button. Disabled controls hide the pencil. For bounded titles, supply max-w-full and wrap the text in a min-w-0 break-words span.
src/components/ui/inlineEditTrigger.tsxOverviewEditableField is the edition-owned molecule used by the live local example above. It composes the actual InlineEditTrigger with a controlled editor at the same position. actionLabel, value, heading and saveLabel describe the field; editing, saving, disabled, onStart, onSave and onCancel remain owner-supplied. children provides the labeled input and initial focus. The display trigger unmounts while editing, rather than remaining above another details form. Enter submits a single-line input; a textarea retains Enter for line breaks. Ctrl/Cmd+Enter submits, and Escape or Cancel discards the draft unless saving. Existing useEditTriggerFocus restores the new display trigger. The molecule owns presentation, not requests, authorization or saved data. Its heading mode retains a screen-reader heading during editing without putting a form inside h1.
src/components/editions/overviewEditableField.tsxsrc/components/editions/overviewCards.tsxEditionCard is the edition-owned presentation organism shared by collection summaries and the editable EditionHero. It owns the image, compact title/details placement, optional content, and one top divider above facts and creator attribution. No lower rule or fixed card height is added. Year, period and description share a wrapping details row. title, details, children and facts accept slots; bannerImageUrl supplies the image. previewSize selects compact or summary image height. An optional native-button imageControl preserves its owner ref and handlers; imageEditor replaces the image while editing. createdByDisplayName and label are optional. The component has no request, policy or editing state.
EditionSummaryCard is the durable read-only instance in editions/instances. It binds supplied text, availability, deadline and a canonical href to EditionCard without mounting editing hooks. The example below uses fictional data and a local fragment link. EditionHero supplies controlled fields, banner editing, availability and richer route-supplied counts to the same card. OverviewEditableField supports containerClassName for its root and className for its trigger, so owners can compose compact metadata and full-width active editors without descendant overrides.
Current component with fictional data. Example changes are not persisted.
| Composition | Interaction and supported inputs | State and authorization |
|---|---|---|
| EditionAdminHeader / EditionHero | Tabs remain in the header. The shallow banner itself is the edit trigger and is replaced by its staged editor. Title, description, year and period use true edit-in-place controls at their original positions. Statistics and Created by share a ruled read-only facts section below availability. OverviewCards fills the available width with two equal medium-and-larger columns and one phone column; cards have independent content heights. Empty descriptions offer Add a description. | Server routes retain scope and authorization. Existing title, description, banner and gate hooks retain drafts, audited saves, focus and unsaved protection. useEditionCalendar owns year/period drafts and calendar-only saves under ADR-0109. Created by identifies the original creator, not an assigned manager. The actual isolated specimen composes both cards; its info editing is disabled and invitation preview is fictional. |
| SubmissionGateControls | Scope, submissionsOpen, submissionDeadline, submissionDeadlineMode and singular/plural labels. One availability trigger displays status and date and opens accepting, date and type together. Empty dates show No deadline. | useSubmissionGate owns acknowledged values, drafts, pending/errors and leave protection. All three fields save in one PATCH. Save/Cancel and Escape retain the saved display until success; failed drafts remain available. |
| RoundDetailHeader within RoundDetail | Round/state/configurationSaving and optional statistics slot. No decorative gradient or per-round image settings. OverviewEditableField replaces only the selected field in place. Availability keeps its disclosure; round identity and labeled counts remain ruled facts. Cards follow independent content heights. | Activation saves immediately; date/type have an explicit Save deadline. Program locks disable metadata/deadline editing but not activation. Existing hooks retain dirty drafts, confirmations and saves. Hard Deadlines still close active rounds. Scored does not mean all reviews completed. No unavailable aggregate report is invented. RoundSettings remains after results. |
| DestinationLink and RoundReviewLink | A full selectable monospace URL with Copy and native new-tab Open, without a nested URL frame. DestinationLink receives href/label, presentation=inline|card and children. Card uses compact spacing and a fluid native h2. The supplied invitation summary places labeled Total, Linked members and Unclaimed counts beside Manage invitees; controls stay on one line when space permits and wrap naturally. RoundReviewLink binds the route and forwards slots. | useDestinationLink owns origin hydration and clipboard feedback. OverviewCards is an edition-owned slot-only template with info/link slots and optional navigation. Navigation sits beside the summary; the link spans the full phone width below both. At medium widths both cards have equal columns beside navigation. Each card follows its own content height without a minimum height or forced aspect ratio. The invitation owner retains drafts above the drawer mount boundary. Copy/Open do not grant access. Public specimens use fictional protected destinations. |
| RoundReviewersPanel within RoundDetail | Explicit reviewerLabel/reviewerLabelPlural, counts, capabilities and commands. Juror/Jury produces Invited Jury, Add Jury and Invite Jury without inferring either term. Reviewer/Reviewers are the omitted-label defaults. | The shared MemberManager exposes Manage invitees and saved counts directly, without an outer collapse. Its drawer owns presentation; feature hooks retain drafts and requests above the mount boundary. The isolated round specimen imports the actual panel with fictional read-only capabilities; the authorized parent supplies real commands. |
Soft Deadline means guidance only. Hard Deadline closes intake or reviews after its date. The product triggers associate their displayed status and date through aria-describedby, so assistive technology receives the current value as well as the edit action. Edition and round headings retain the actual title as their accessible name. Product editors require authorized tenant operations and are not mounted here. This specimen imports the actual trigger and saves only local fictional text; it sends no tenant requests. The owning headers use semantic typography, borders and surfaces without child-style overrides, Context or a client store.
Switching rounds and occasional settings
Current component with fictional data. Example changes are not persisted.
Example internal review
Numbered destinations change only this fictional selection. Management requires an authorized workspace.
Settings below keep local changes when closed; deletion is disabled.
Round settings
Configure review options, scoring criteria and reviewer labels here. Closing this panel keeps drafts. Save or cancel changes before switching rounds.
RoundNavigation uses numbered RoundTabs to the left of the review card, including one tab for a one-round Edition. Full accessible names and the current-page state identify each destination. The compact Manage Review Rounds cog sits at the bottom of the rail's layout area, not the viewport, and opens a separate full-width management area. Many rounds can increase rail height without stretching the card. The phone Review Link fills the workspace below the rail and summary. Close/Escape retains creation drafts and restores focus.
Only the review card row shares space with the rail. Results and settings span the full workspace width below it, preserving usable controls on smaller screens.
| Component | Inputs and behavior | Ownership and limits |
|---|---|---|
| RoundTabs | rounds contains roundCode/name/href in existing order; currentRoundCode supplies aria-current. Visible labels are numbers; accessible labels include full names. Optional onManage/manageDisabled control the footer action; triggerRef supports focus return. Tab/Enter retains native links; ArrowUp/Down/Home/End also moves focus. | Review-round-owned navigation molecule, not an in-page ARIA tab widget. Native links preserve URL state, view/group queries and unsaved-change guards. RoundNavigation drops roundNav. The actual public adapter uses fictional anchors/local selection; management remains disabled without authorized workspace operations. |
| RoundSettings | round, state (editSaving/actionBusy/rubricLocked/handleDelete), configurationSaving and children. Show/Hide exposes aria-expanded/controls. useRoundSettingsReady keeps the JavaScript-only trigger disabled and its section busy until hydration. Explicit Close controls appear at both ends; Escape restores trigger focus. | Internal feature organism after RoundSubmissionsPanel. Closed children stay mounted, preserving drafts/errors/saves. A colocated readiness hook owns the mount effect, without requests or global state. Metadata mutations disable disclosure/close; configuration saves may continue while hidden. Locks, scored-round deletion restrictions and confirmation remain enforced. Escape in the delete dialog dismisses only that dialog. |
| ReviewRoundsWorkspace / RoundDetail | Server-supplied round/result data, direct workspace commands and URL-selected round. RoundDetailHeader handles only routine metadata and availability. | Server routes retain authorization. Selection/query state stays in the URL; local state owns disclosures and management mode. Existing hooks retain requests and unsaved-change protection. No new Context, store or API policy is introduced. |
Repository path: src/app/(tenants)/console/[tenantCode]/admin/programs/[programCode]/editions/[editionCode]/review-rounds/components/roundTabs.tsx
Repository path: src/app/(tenants)/console/[tenantCode]/admin/programs/[programCode]/editions/[editionCode]/review-rounds/components/roundSettings.tsx
Implementation and review standard
Before meaningful frontend changes, declare layer, owner, generic eligibility, server boundary and state level. Follow the frontend skill; verify interactive UI and hooks, run the baseline checks, and request independent quality review before shipping.
Responsibilities in an interaction
Separate the view, product binding, behavior lifecycle and server operation. A reusable editor displays a draft and calls supplied commands. Its feature owner supplies tenant context and persistence; the server validates access.
| Part | Its job | What stays elsewhere |
|---|---|---|
| Route / server | Check access and load permitted initial data. | A client view cannot substitute for authorization. |
| Product instance | Supply product labels, navigation, mapping and behavior bindings. | Do not copy shared markup or embed raw endpoint strings. |
| Behavior hook | Manage requests, subscriptions or coordinated state changes; return values and commands. | Rendered JSX belongs to the view. |
| Reusable view | Present controls, labels and feedback; report intent through callbacks. | It does not choose submission APIs or tenant policy. |
| Operation / API client | Own transport paths, payload mapping and response handling. | Every server operation still checks permission. |
When to name a product instance
Name a product instance for a stable binding of copy, mapping, navigation or behavior. A supported variant or temporary route assembly does not require an instance.
| Situation | Recommended approach |
|---|---|
| Only wording, size, variant or a supported slot differs | Configure the existing component. An outline Button is not a new instance. |
| One route has a temporary or route-specific assembly | Keep it with that route or feature. Extract a behavior hook if the work needs one; that alone does not require an instance. |
| A stable product surface binds copy, mapping, navigation or behavior | Name an instance beside its abstraction in instances/. A durable binding can qualify before it has a second route. |
| The existing instance already has the same meaning and lifecycle | Reuse it, or pass its supported configuration rather than clone it. |
| Meaning differs but the view and behavior contracts still fit | Make a thin sibling adapter. Avoid a growing set of flags such as isEdition, isAdmin and useOtherApi. |
| The new flow requires contradictory states or copied structure | Revisit the abstraction. Evolve or split it rather than hide a new responsibility inside an instance. |
Reuse structure, behavior or a shared state owner
- Appearance and structure: reuse the view's props and slots. Shared markup and styling belong in that abstraction.
- Lifecycle: reuse a behavior hook or command with its loading, errors and result semantics intact. Do not reach into another instance's private setters.
- Mapping: use a pure, feature-owned helper for repeated domain-to-view or payload conversion when needed.
- Operation: call a typed callback or established API client rather than copying endpoint strings.
- The same draft: choose one common state owner. Reusing the same hook in two places does not synchronize them.
- The whole surface: reuse the instance when its product meaning fits. Wrapping it is valid if it exposes the right customization point.
Follow a batch save from the draft to the operation
Current implementation: creation and editing use SubmissionForm. The edition instance injects its scoped update operation without copying the form. ADR-0084 defines batch saves for fields and attachments, replacing per-field submission persistence.
- SubmissionForm renders the fields, attachment controls, readiness guidance and save actions. Drafts need only a title; Submit uses UI readiness rules, while narrative fields remain optional. This submissions-owned organism is not generic UI.
- useSubmissionForm owns the local form and attachment draft, dirty tracking and the saved baseline. It sends the current fields and full attachment set together. A false result leaves the draft intact instead of marking it saved.
- EditSubmissionForm and useEditSubmission bind the shared form to persistence. The hook owns pending/error state, persisted status and attachment-description errors, guards against overlapping saves, normalizes the batch payload and returns an explicit success boolean. Its default operation remains submission-specific.
- EditEditionSubmissionForm wraps that form and injects an edition-scoped updateFields callback. The callback captures the route identifiers it needs rather than using the generic tenant/id arguments. The authorized route supplies returnHref for Cancel, matching the edit page’s return link to the submission view. That view retains the originating personal list, manager Submissions list or specific Reviews round through validated URL context. List context does not grant access; direct links without context return from the view to the edition’s public list.
- submission-api owns the URL, HTTP method, payload and response translation. Server permission checks remain required beyond this client-side trace.
During creation, an owner that supplies existingFiles must update that collection after onRemoveExistingFile. The displayed attachments, readiness and save payload follow the current collection. Edit mode instead retains its local attachment order and descriptions across parent rerenders; those drafts reset their saved baseline only after a successful save.
SubmissionFileDisplay is the submissions-owned molecule for existing attachments. In edit mode, the form supplies controlled descriptions, file-keyed errors, local removal commands and controlled reordering. Drag a file's reorder handle, or focus it and press Space, Arrow Up or Arrow Down, then Space again. Escape cancels a keyboard move. Order changes stay local until the full attachment set saves successfully; failed saves retain the chosen order. Controls are disabled while saving. Newly uploaded files follow the retained files. Referenced files can show Size unknown; a saved link does not prove source availability. SubmissionDetailView composes SubmissionMediaGallery for reading, with native preview failure guidance rather than edit controls. Routes supply permitted URLs; neither view resolves access or checks storage metadata.
Repository path: src/components/submissions/submissionFileDisplay.tsx
Repository path: src/components/submissions/submissionMediaGallery.tsx
updateFields={(_, __, data) =>
updateEditionSubmissionFields(
tenantCode, programCode, editionCode, submissionCode, data
)
}This excerpt omits surrounding props. The edition instance captures route identifiers and injects the scoped operation; the shared form retains its markup and draft contract.
src/components/submissions/instances/editEditionSubmissionForm.tsxRepository path: src/components/submissions/submission-api.ts
Instance responsibilities depend on the integration
CreateEditionSubmissionForm: form, saving and navigation
The instance configures SubmissionForm with categories, visible fields and integrity-statement copy. useSubmissionMutation supplies pending/error state; the injected operation creates the submission, navigates on success and refreshes server-owned discovery.
The form receives feedback and submit/cancel callbacks. The hook tracks the operation; the instance chooses the destination; the API module carries transport.
Repository path: src/components/submissions/instances/create-edition-submission-form.tsx
Repository path: src/components/submissions/use-submission-mutation.ts
ConsoleShell: a template binding, not a save controller
ConsoleShell binds AppShell or SidebarShell to supplied identity, navigation and content. The server supplies management discovery; the instance binds URL selection and focused-task presentation. It does not establish route authorization. Sidebar effects belong to useSidebarShell, not to a client-side permission hook.
src/components/navigation/instances/consoleShell.tsxVerify failure and lifecycle behavior
Implementation guidance: check the following conditions when changing a workflow. Verify each result contract; current hooks do not supply every guarantee listed here.
| Question | Why it matters in the current examples |
|---|---|
| Can two saves run together? | useEditSubmission uses an in-flight guard and returns false for an overlapping save. The form disables controls during persistence. Preserve both protections; a loading flag alone does not serialize requests. |
| Does awaiting the command prove success? | Check the result contract. useEditSubmission.save returns true or false; the shared form retains its dirty draft on false. useSubmissionMutation still catches creation errors into state, so an arbitrary resolved promise is not proof of success. |
| What does Cancel cancel? | The shared form's Cancel confirms leaving unsaved edits before invoking navigation. It does not abort a network request. There are no longer per-field cancelEditing commands in the submission hook. |
| What if the record or server data changes? | Drafts initialize from props, but do not automatically reconcile later updates. Decide when to preserve, reset or merge a draft without erasing input. |
| Can someone understand and recover from the error? | Keep labels, errors, pending feedback and retry/cancel paths accessible. Decide where focus returns and whether the feedback should be announced. |
Locate a change by responsibility
| Change | Where it belongs | Who is affected |
|---|---|---|
| Shared structure, style, props or slots | Reusable view | Compatible consumers and instances; overrides may mask visual changes. |
| Pending, cancellation, errors or return values | Behavior hook | All callers, including those injecting their own operations. |
| Product wording, mapping or destination | Instance / adapter | Consumers of that product binding, not every use of the base view. |
| Endpoint, payload or response handling | Operation / API client | Callers of that operation, even if the UI looks unchanged. |