Skip to content

Scenarios ​

Copy-ready composition patterns: each recipe shows how multiple components form a real business shape.

Recipe Index ​

Spreadsheet-style Record Editing Form ​

Scenario: oas-table displays structured records with typed columns (badges / progress / dates / checkmarks); clicking a row opens an oas-form editing dialog, and validated submissions write back into the table — a complete "browse in table → edit in form" loop.

Click a row to open the editing form (validation + write-back)

CancelSave

Last saved: —

Pattern notes:

  1. Typed columns own presentation (declare type for badges / dates / checkmarks), the form owns editing — each side uses the most suitable component
  2. Build form fields from the clicked row's data; validation rules are declared on the oas-form (shape { fieldName: [{ required, pattern, message, ... }] }, matched by field name) — the save button calls form.submit(), and on success the form emits oas-submit (detail.values is the full form value collected by name)
  3. Write-back is "read all → patch one row → setAttribute the whole thing" (the table's uncontrolled data channel, complementary to the inline-editing channel)
  4. For quick single-cell edits use editable + editComponent (see the Table page); for multi-field row editing use this form recipe

Desktop Address Form ​

Scenario: desktop back-office entry of shipping / office addresses. Such a form couples deeply with the business — which fields (email or not, company name or not), how many region levels (province / city, or province / city / district), how strict the validation — every product differs, and it usually shares layout and submit pipeline with order or customer-record forms. So this ships no composite component: assemble oas-form + oas-cascader + oas-input, and keep both fields and rules in the host.

The mobile e-commerce address book — editor / list / contact shapes out of the box — is Address; that is the mature e-commerce shape, while a desktop form is free assembly. Pick per scenario.

Variant A: two-level regions (province / city, no email) ​

Two-level regions: province / city + street address

Save addressClearNot submitted

Variant B: three-level regions + email + phone format validation ​

Three-level regions: province / city / district + email + phone validation

Save addressClearNot submitted

Pattern notes:

  1. Region is one field: a single oas-cascader (name="region") instead of three interlocked selects — its value is a path of region codes, and the level count comes from the depth of options (pass two levels for a two-level dataset); cascading reset, keyboard navigation and search are cascader built-ins
  2. Rules live on the form: rules shape { fieldName: [{ required, pattern, message }] }, keyed by the control's name; failed fields render their message in the matching oas-form-item error slot and the form dispatches oas-validate-fail
  3. Phone / email are hand-written pattern rules (^1\d{10}$ / ^[^@\s]+@[^@\s]+\.[^@\s]+$) — the library ships no built-in "email / phone" rule presets today; that is a future candidate, and this page does not invent the API
  4. The two variants differ only in data and rules: the depth of options plus the field set in rules (with or without email, with or without a pattern on phone) — one shell trimmed by data and rules, which is exactly why the desktop case is a recipe rather than a component
  5. Cancel path = form.reset() (the "Clear" button): back to field initial values without dispatching oas-submit; a controlled host restores its own form state instead

Turning the submitted path back into an address object on the host side (values.region is a code path; map it back to names with the same dataset before persisting):

Host side: path → address object (click to expand the code)
ts
import type { OASForm } from '@oas-ui/ui'

interface RegionNode {
  label: string
  value: string
  children?: RegionNode[]
}

/** Region data is injected by the host: two levels for two-level data, three for three (no built-in divisions) */
const regions: RegionNode[] = [
  { label: 'Zhejiang', value: '330000', children: [{ label: 'Hangzhou', value: '330100' }] },
]

/** code → name: turn the path string submitted by the cascader back into a readable address */
const regionName = new Map<string, string>()
const indexRegion = (nodes: RegionNode[]): void => {
  for (const node of nodes) {
    regionName.set(node.value, node.label)
    if (node.children) indexRegion(node.children)
  }
}
indexRegion(regions)

type SubmitDetail = { values: Record<string, string> }

const addressForm = document.querySelector('#recipe-addr-full') as OASForm | null
addressForm?.addEventListener('oas-submit', (event) => {
  const { values } = (event as CustomEvent<SubmitDetail>).detail
  // The region field's value is a path array of codes, one per level
  const path: string[] = JSON.parse(values.region ?? '[]')
  const nameOf = (code: string): string => regionName.get(code) ?? code
  const [province, city, district] = path.map(nameOf)
  const payload = {
    name: values.name,
    phone: values.phone,
    email: values.email,
    province,
    city,
    district,
    detail: values.detail,
  }
  void fetch('/api/addresses', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  })
})

Country Select (with Flags) ​

Scenario: a form needs a country/region picker — with flags, searchable by Chinese/English name and ISO code, grouped by continent. oas-select already carries the whole interaction via searchable + group + filterMethod; what's missing is data, not a component — the country list, flags and localized names are all host-supplied (the same "externalize the data contract" principle as the composite-component admission criteria).

Variant A: groups + flags + search. The option label inlines an emoji flag (zero assets, renders everywhere), group clusters by continent, and searchable gives you search out of the box (default label-contains matching):

Country select: groups + flags + search (variant A)

Selected: (none)

Variant B: custom matching (zh/en/ISO/aliases). The default filter only matches against the label; assign a host function to the filterMethod property and "zhongguo / china / CN / 中国" all hit the same option:

Country select: filterMethod multi-channel matching (variant B)

Selected: (none)

Recipe code (data + filterMethod + wiring)
ts
import type { OASSelect } from '@oas-ui/ui'

// Data is the host's job: maintain the country list / names / aliases for your
// business (24-country sample here). Flags use emoji regional indicators —
// zero assets, renders everywhere; for SVG flags, self-register them in the
// icons registry and reference via the option.icon field — the component
// ships no flag assets.
interface Country {
  code: string // ISO 3166-1 alpha-2
  zh: string
  en: string
  flag: string
  group: string
  aliases: string[] // pinyin / common aliases for filterMethod
}
const countries: Country[] = [
  { code: 'CN', zh: '中国', en: 'China', flag: '🇨🇳', group: 'Asia', aliases: ['zhongguo', 'china', 'cn'] },
  { code: 'JP', zh: '日本', en: 'Japan', flag: '🇯🇵', group: 'Asia', aliases: ['riben', 'japan', 'jp'] },
  { code: 'KR', zh: '韩国', en: 'South Korea', flag: '🇰🇷', group: 'Asia', aliases: ['hanguo', 'korea', 'kr'] },
  { code: 'SG', zh: '新加坡', en: 'Singapore', flag: '🇸🇬', group: 'Asia', aliases: ['xinjiapo', 'singapore', 'sg'] },
  { code: 'TH', zh: '泰国', en: 'Thailand', flag: '🇹🇭', group: 'Asia', aliases: ['taiguo', 'thailand', 'th'] },
  { code: 'VN', zh: '越南', en: 'Vietnam', flag: '🇻🇳', group: 'Asia', aliases: ['yuenan', 'vietnam', 'vn'] },
  { code: 'DE', zh: '德国', en: 'Germany', flag: '🇩🇪', group: 'Europe', aliases: ['deguo', 'germany', 'de'] },
  { code: 'FR', zh: '法国', en: 'France', flag: '🇫🇷', group: 'Europe', aliases: ['faguo', 'france', 'fr'] },
  { code: 'GB', zh: '英国', en: 'United Kingdom', flag: '🇬🇧', group: 'Europe', aliases: ['yingguo', 'uk', 'gb', 'britain'] },
  { code: 'IT', zh: '意大利', en: 'Italy', flag: '🇮🇹', group: 'Europe', aliases: ['yidali', 'italy', 'it'] },
  { code: 'ES', zh: '西班牙', en: 'Spain', flag: '🇪🇸', group: 'Europe', aliases: ['xibanya', 'spain', 'es'] },
  { code: 'NL', zh: '荷兰', en: 'Netherlands', flag: '🇳🇱', group: 'Europe', aliases: ['helan', 'netherlands', 'nl', 'holland'] },
  { code: 'CH', zh: '瑞士', en: 'Switzerland', flag: '🇨🇭', group: 'Europe', aliases: ['ruishi', 'switzerland', 'ch'] },
  { code: 'SE', zh: '瑞典', en: 'Sweden', flag: '🇸🇪', group: 'Europe', aliases: ['ruidian', 'sweden', 'se'] },
  { code: 'US', zh: '美国', en: 'United States', flag: '🇺🇸', group: 'North America', aliases: ['meiguo', 'usa', 'us', 'america'] },
  { code: 'CA', zh: '加拿大', en: 'Canada', flag: '🇨🇦', group: 'North America', aliases: ['jianada', 'canada', 'ca'] },
  { code: 'MX', zh: '墨西哥', en: 'Mexico', flag: '🇲🇽', group: 'North America', aliases: ['moxige', 'mexico', 'mx'] },
  { code: 'BR', zh: '巴西', en: 'Brazil', flag: '🇧🇷', group: 'South America', aliases: ['baxi', 'brazil', 'br'] },
  { code: 'AR', zh: '阿根廷', en: 'Argentina', flag: '🇦🇷', group: 'South America', aliases: ['agenting', 'argentina', 'ar'] },
  { code: 'AU', zh: '澳大利亚', en: 'Australia', flag: '🇦🇺', group: 'Oceania', aliases: ['aodaliya', 'australia', 'au'] },
  { code: 'NZ', zh: '新西兰', en: 'New Zealand', flag: '🇳🇿', group: 'Oceania', aliases: ['xinxilan', 'new zealand', 'nz'] },
  { code: 'EG', zh: '埃及', en: 'Egypt', flag: '🇪🇬', group: 'Africa', aliases: ['aiji', 'egypt', 'eg'] },
  { code: 'ZA', zh: '南非', en: 'South Africa', flag: '🇿🇦', group: 'Africa', aliases: ['nanfei', 'south africa', 'za'] },
  { code: 'NG', zh: '尼日利亚', en: 'Nigeria', flag: '🇳🇬', group: 'Africa', aliases: ['niriliya', 'nigeria', 'ng'] },
]

// options: flag inlined in label + localized name (pick zh/en per page locale),
// grouped by continent
const toOptions = (list: Country[], locale: 'zh' | 'en') =>
  list.map((c) => ({ label: `${c.flag} ${locale === 'zh' ? c.zh : c.en}`, value: c.code, group: c.group }))

const selectA = document.getElementById('recipe-country-a') as OASSelect
selectA.setAttribute('options', JSON.stringify(toOptions(countries, 'en')))
selectA.addEventListener('oas-change', (e) => {
  const code = (e as CustomEvent<{ value: string }>).detail.value
  const hit = countries.find((c) => c.code === code)
  document.getElementById('recipe-country-a-out')!.textContent = hit ? `${hit.flag} ${hit.en} (${hit.code})` : '(none)'
})

// Variant B: assign a host function to filterMethod — zh/en/ISO/alias channels
const selectB = document.getElementById('recipe-country-b') as OASSelect
selectB.setAttribute('options', JSON.stringify(toOptions(countries, 'en')))
selectB.filterMethod = (query: string, option: { label: string; value: string }) => {
  const q = query.trim().toLowerCase()
  if (!q) return true
  const hit = countries.find((c) => c.code === option.value)
  if (!hit) return option.label.toLowerCase().includes(q)
  return (
    hit.zh.includes(query.trim()) ||
    hit.en.toLowerCase().includes(q) ||
    hit.code.toLowerCase() === q ||
    hit.aliases.some((a) => a.includes(q))
  )
}
selectB.addEventListener('oas-change', (e) => {
  const code = (e as CustomEvent<{ value: string }>).detail.value
  const hit = countries.find((c) => c.code === code)
  document.getElementById('recipe-country-b-out')!.textContent = hit ? `${hit.flag} ${hit.en} / ${hit.zh}` : '(none)'
})

Pattern notes:

  • Data stays external: the country list / names / aliases are host data (localized projects pick the zh/en field per locale); the component only provides the searchable / group / filterMethod interaction surface.
  • Two flag paths: emoji regional indicators (zero assets, the default here; rendered as color flags on macOS/iOS/Android/Linux, but Windows system fonts have no flag glyphs and show a two-letter code — use SVG flags for a consistent cross-platform look) or SVG flags self-registered in the icons registry and referenced via option.icon — the component ships no flag assets.
  • filterMethod is the matching extension point: the default label-contains match is often enough; pinyin / alias / ISO channels are decided by your function, the component never guesses business aliases.

Kanban-driven Task Flow ​

oas-kanban's oas-change event is the data-change protocol — map from/to/index to your backend state transitions:

ts
const laneField = 'state' // swimlane field (replace with your actual field name)
const kanban = document.querySelector('oas-kanban') as HTMLElement
kanban.addEventListener('oas-change', async (e) => {
  const { id, from, to, index, ids, swimlane } = (e as CustomEvent).detail
  await api.moveCards({
    cardIds: ids ?? [id], // ids is an array on multi-select batch moves
    toColumn: to,
    toIndex: index,
    ...(swimlane ? { [laneField]: swimlane.to } : {}),
  })
})

WIP limits are advisory (the data-over-limit marker); hard blocking is the host's choice, enforced after the event.

Scenario: the "gallery" form of a spreadsheet — records are shown as rich card stacks grouped by a field value instead of rows. Compose it with oas-card + grouping; no dedicated component needed.

Product gallery grouped by category

Pattern notes: the group key drives columns (new Set(records.map(r => r.cat))), and each card is a rich record view (oas-card + oas-tag status badge). The gallery is essentially "group + cards" — the badge/format semantics stay aligned with the table's type column (price/stock/status share one dataset).

Calendar View (Records Laid Out by Date) ​

Scenario: the "calendar" form — lay records into calendar day cells by a date field. oas-calendar's oas-cell-render event is the channel (fired for every day cell; the host appends content).

Release schedule calendar (event dots + hover details)

Pattern notes: oas-cell-render's detail.element is the day-cell container — append .cell-dot (the built-in dot style) and set element.title for hover details; index events by the date field — note that detail.date is a Date object (from parseISODate): format it to an ISO key (YYYY-MM-DD) before comparing with your event data (a direct ev.date === detail.date comparison always fails on type mismatch). With one shared dataset, table / gallery / calendar become three projections of the same records.

Multi-project Gantt tree + resource project priority ​

Do not add a second gantt instance: create one root summary task per project (type:"summary") and put project tasks under it via children/parent. Project roots, task bars, dependencies and virtualization share one tree. On the resource side, use task project plus levelResources({ projectOrder }) to carry project priority into leveling.

ts
import { levelResources } from '@oas-ui/ui'

const tasks = [
  { id: `p-a`, name: `Project A`, type: `summary`, start: `2026-03-02`, end: `2026-03-13`, children: [
    { id: `a1`, name: `A design`, start: `2026-03-02`, end: `2026-03-06`, project: `A` },
  ]},
]
const leveled = levelResources(resources, resourceTasks, { projectOrder: [`A`, `B`] })
  • Project roots only group/aggregate; dependencies live on leaf tasks and may cross projects.
  • Resource leveling sorts by projectOrder; later projects yield first and gantt project-root dates are not rewritten.

Action Sheet: Mobile Action Menu ​

Scenario: the mobile "more actions" menu — a set of actions sliding up from the bottom, destructive ones highlighted red, and a cancel button in its own group. Compose it from oas-drawer (placement="bottom" + no-mask) holding oas-list action items; no dedicated "action panel" component needed: slide-in animation, outside-click/Esc close and scroll lock are drawer built-ins (no-mask is the non-modal form and ships no focus trap), while focusability, Enter/Space activation and oas-click reporting are list built-ins.

Open the Action Sheet (clicking an item gives feedback; outside click / Esc / cancel all close it)

Open Action Sheet

Last action: None

Take photoChoose from libraryDeleteCancel

Pattern notes:

  1. no-mask renders no overlay but keeps the "click outside to close" cancel semantics; Esc close is a drawer built-in (so is scroll lock — no-mask is a non-modal drawer, no focus trap) — distinguish close sources via oas-close's detail.source (esc / mask)
  2. A destructive item is not a component prop — list items have no danger channel; drop var(--oas-color-danger) on the slot="title" span and the semantic color is yours. That flexibility is exactly what composition buys
  3. Cancel sits in its own group (visual separation + semantic separation); after a pick the host closes the drawer and updates the feedback badge (a role="status" line, perceivable to screen readers). A no-header + no-mask drawer has no visible title, so label="Action options" supplies the aria-label accessible name (otherwise screen readers only announce "dialog")
  4. The rounded top corners come from a page-level ::part(panel) override (see the styles at the bottom of this page) — the drawer panel ships without border radius; that "last mile" belongs to the recipe. A vertical drawer needs an explicit height (height accepts concrete lengths only; default 320px)

Terminal Panel: Dark Log + Command Line ​

Scenario: a deploy / build console — dark background, monospace, a numbered output stream, status + clear on top, command line at the bottom. Assembled entirely from existing components: oas-log (line numbers, semantic levels, empty state) + oas-tag (status) + oas-button (clear) + oas-input (Enter emits oas-enter). The dark theme comes from container-level token overrides: override a set of color tokens on a recipe container, CSS custom properties pierce the shadow DOM, and every component in the subtree reskins itself — a terminal palette is a scenario-fixed color (it does not flip with the light/dark theme), which is exactly the division of labor between "recipe" and "component".

Terminal simulation (help / date / echo text / clear)

Runningdeploy@oas-ui:~/appClear

Pattern notes:

  1. The token overrides live only on the .recipe-term container — nothing else on the page is affected; the override set covers exactly the variables the subtree components actually reference (bg / bg-hover / text / border, plus the semantic -text set referenced by log rows and the tag badge — semantic rows on a black background need dark-background safe shades, otherwise they inherit the site theme's light-theme dark shades and become unreadable)
  2. Output lines and their semantics live in two parallel arrays (lines / levels, index-aligned): command echo at info, success output at success, unknown commands at error — the log maps levels to semantic tokens (colors adjust automatically in dark mode)
  3. Clearing has two equivalent paths (toolbar button / the clear command), both via the data channel lines = [] — once empty, the log's built-in empty state appears
  4. Empty commands are ignored outright (no blank lines); clearing the input after submit goes through the controlled value channel (no event emitted)

Sparklines in Table Cells: Chart-per-Cell Without a New Component ​

Scenario: dashboard "trend" columns — one mini chart per row reads far better than a column of numbers. No new component needed: the table column render channel (render function field on columns, JS property path) + oas-chart (type="area", legend off) is the entire material. A chart is a declarative tag; drop it into the cell template and the composition is done.

Trend column = oas-chart sparkline (column render channel composition)

Pattern notes:

  1. columns with function fields (render) must be assigned via JS property (attributes only take JSON; function fields cannot be serialized); the signature is render(row) (the row object) — return a string for text, return a Node/element to mount rich content (the chart wrapper in this recipe relies on it); the data body itself goes through the data attribute JSON channel (no data property setter) — the two channels are separate
  2. Assignment must happen after customElements.whenDefined('oas-table') (the component registers late via the theme's dynamic import; assigning before upgrade becomes a swallowed expando) — the same discipline every demo on this page already follows
  3. Sparkline trio: a sizing wrapper div (150x32 level) + showLegend:false to hide the legend + type="area" solid translucent fill (enable gradient for more depth); the chart fills the wrapper at width/height:100%, colors default to the token family with dark-mode variants (customize via options.colors)
  4. Don't push big/high-frequency datasets through the full data attribute reflection (serialization costs) — feed the current page slice; use windowed mode for server-side slicing (see the component page "server row window")

AI Conversation: Thinking Fold, Streaming Bubble, Message Actions ​

Scenario: the standard three-part AI assistant reply — a collapsed thinking block (reader opens the reasoning chain on demand), streaming body text, and a trailing action row (copy / retry / regenerate). No new component needed: oas-collapse folds the thinking, oas-bubble holds the body, oas-message-actions hosts the actions — the same structure as mainstream AI products.

AI reply trio: folded thinking + streaming body + action row

MeSort yesterday's orders by amountAIAssistant · 10:03
  1. Resolve "yesterday" → 2026-11-07 (host timezone)
  2. Locate order data and confirm the amount field unit
(Press "Run streaming answer")
Run streaming answerIdle

Pattern notes:

  1. Thinking block = folded into the message row's default slot: oas-message-row's default slot is a free content container (not just bubbles) — oas-collapse folds the reasoning chain; write the step count / duration in the header and let the reader expand on demand (start collapsed; the host owns final expand state)
  2. Streaming = update text in place, never append nodes: update the oas-bubble text (textContent) token by token; message-scroller's auto-scroll only follows a reader who is near the bottom — it never yanks the viewport away from a reader who scrolled up (the existing IM/AI discipline); do not appendChild per token (DOM explosion + scroll jitter)
  3. Action row = oas-message-actions in the footer slot: declare actions as key/label pairs; clicks dispatch oas-action (detail carries message-id + key) — copy goes through navigator.clipboard (the host writes it in the event handler); retry/regenerate is host business, the component ships no semantics

JSON Formatting Comparison: Tree vs Text ​

Scenario: when debugging API data, the same dataset supports two readings — the tree reading shows structure (expand, search, copy subtrees), the text reading shows bytes (what the source looks like, what formatting changed). Left oas-json-viewer (tree), right oas-diff-viewer (minified source ↔ formatted text). Keep the data as one object; both forms are projections of JSON.stringify — never maintain two copies of the text.

Two readings of one dataset (switch between formatted / compact views)

Tree reading (structure)

Text reading (bytes)

Pattern notes:

  1. The segmented control switches between two views: Formatted shows the "compact → formatted" diff (what formatting added); Compact flips the direction (formatted → compact, what minification removed)
  2. The tree panel's text switches with the view too (fed the minified or the formatted string) — the tree renders identically in both views, directly demonstrating that the structural reading is whitespace-insensitive
  3. The diff panel uses mode="split" (degrades to unified on narrow containers, built-in responsive behavior) + wrap for readable long lines; old-label / new-label make the columns' semantics explicit
  4. The tree panel's companion tools are ready when needed: search box (toolbar built-in), expandAll() / collapseAll(), copyJson() for subtree copy

Released under the MIT OR Apache-2.0 License.