components.styles

作者: coinbase

編寫CDS元件的樣式API(styles、classNames和static classNames)指南。在為React元件新增自訂選項時,請使用此技能…

npx skills add https://github.com/coinbase/cds --skill components.styles

Goal: Add styles API (styles, classNames, and static classNames) to a CDS component and/or update the component documentation with styles documentation.

If no component name is provided, ask the user which component they want to add styles to.

Step 1: Locate the Component

Find the component source file:

packages/web/src/[source-category]/[ComponentName].tsx              # for web
packages/mobile/src/[source-category]/[ComponentName].tsx           # for mobile

Step 2: Evaluate Component Structure

⚠️ IMPORTANT: Adding styles/classNames props is a commitment to the component's internal structure.

Before adding styles API, carefully review the component's JSX structure:

  • Flag if the component could be simplified (e.g., unnecessary wrappers, redundant containers)
  • Do NOT add styles to elements that may be refactored - this creates breaking changes
  • Ask the user if you notice the component structure could be improved before committing to it

Once published, changing or removing selectors is a breaking change for consumers.

Step 3: Identify Styleable Elements

Review the component's JSX to identify elements that should be targetable via styles/classNames:

  • Root element: The outermost container element
  • Named sections: Elements with semantic meaning (e.g., start, content, end, header, footer)
  • Sub-components: Internal elements that users might want to customize
  • Conditional elements: Elements that render based on props

Approved Selector Names

IMPORTANT: Before adding a new selector name not in this list, get explicit confirmation from the user. When a new selector is approved, add it to this list.

Approved Selectors (alphabetical)

SelectorDescription
accessoryAccessory element (e.g., chevron, icon at end)
activeIndicatorActive indicator element (e.g., in tabs)
bottomContentBottom section content
carouselMain carousel track element
carouselContainerOuter carousel container
childrenContainerContainer wrapping children
contentMain content area
contentContainerContainer wrapping content
descriptionDescription text element
dayDate cell in a calendar grid
endEnd slot content (e.g., actions, icons)
fillFill/progress indicator within a track
headerHeader section
helperTextHelper/assistive text below content
iconIcon element
intermediaryMiddle/intermediary element between sections
labelLabel text element
labelsContainer for multiple labels
logoLogo element
mainContentPrimary content area
mediaMedia element (image, avatar, icon)
modalVisible modal card element
navigationNavigation controls (e.g., prev/next buttons)
overlayFull-viewport overlay/backdrop element
paginationPagination indicators
pressablePressable/interactive wrapper
progressProgress indicator element
progressBarProgressBar sub-component within a composed component
rootRoot/outermost container element
safeAreaSafe area region wrapping content
startStart slot content (e.g., back button)
stepIndividual step element (in steppers)
substepContainerContainer for nested sub-steps
subtitleSubtitle text element
tabTab element (in tabs)
tabsTabs container element
thumbDraggable thumb element (in sliders)
titleTitle text element
titleStackStack containing title/subtitle/description
titleStackContainerContainer wrapping titleStack
topContentTop section content
trackTrack/rail element (in progress bars, sliders)
triggerTrigger element that opens a dropdown/popover

JSDoc Convention for Selector Descriptions

Selector JSDoc comments describe what the element is, not what the prop does:

  • Sentence case, no trailing period
  • Concise noun phrase describing the element itself
  • Single-line format: /** Description */
  • For conditional elements, append context after a comma: /** Header element, only rendered on phone viewport */

Examples:

/** Root element */
/** Title text element */
/** Navigation controls element */
/** Header element, only rendered on phone viewport in horizontal direction */

Step 4: Add Styles API (Web Components)

For web components, add three things:

4.1 Static Class Names

Add a static classNames object with JSDoc comments. Place this before the component's type definitions:

/**
 * Static class names for [ComponentName] component parts.
 * Use these selectors to target specific elements with CSS.
 */
export const [componentName]ClassNames = {
  /** Root element */
  root: 'cds-[ComponentName]',
  /** [Concise element description] */
  [selectorName]: 'cds-[ComponentName]-[selectorName]',
  // ... more selectors as needed
} as const;

Naming conventions:

  • Use cds- prefix for all class names
  • Use PascalCase for component name: cds-NavigationBar
  • Use camelCase for sub-elements: cds-NavigationBar-contentWrapper, cds-Foo-titleStack
  • Keep names descriptive but concise

Example:

export const fooClassNames = {
  root: 'cds-Foo',
  contentWrapper: 'cds-Foo-contentWrapper',
  titleStack: 'cds-Foo-titleStack',
  helperText: 'cds-Foo-helperText',
} as const;

4.2 Update Component Props Type

Import and use the StylesAndClassNames utility type:

import type { StylesAndClassNames } from '../types';

export type [ComponentName]BaseProps = BoxBaseProps & {
  // ... other props (without styles/classNames)
};

export type [ComponentName]Props = [ComponentName]BaseProps & StylesAndClassNames<typeof [componentName]ClassNames> & Omit<BoxProps<[ComponentName]DefaultElement>, 'children'>;

This automatically generates the styles and classNames props based on your static classNames object.

4.3 Apply in Component Implementation

Apply the static classNames, dynamic classNames, and styles in the component:

import { cx } from '../cx';

// In the component:
<VStack
  className={cx([componentName]ClassNames.root, className, classNames?.root)}
  style={{ ...style, ...styles?.root }}
  // ... other props
>
  <HStack
    className={cx([componentName]ClassNames.contentWrapper, classNames?.contentWrapper)}
    style={styles?.contentWrapper}
  >
    {children}
  </HStack>
</VStack>

4.4 Add Tests for Static Class Names

Add tests to verify that static class names are applied correctly to the component. This ensures the class names remain stable for consumers who depend on them for CSS targeting.

Test pattern:

import { [componentName]ClassNames } from '../[ComponentName]';

describe('[ComponentName] static classNames', () => {
  it('applies static class names to component elements', () => {
    render(
      <[ComponentName]WithTheme
        start={<div>Start</div>}  // Include props that render conditional elements
      >
        <div>Children</div>
      </[ComponentName]WithTheme>,
    );

    // Test root element
    const root = screen.getByRole('[role]'); // or use testID/other selector
    expect(root).toHaveClass([componentName]ClassNames.root);

    // Test sub-elements using querySelector with the static class name
    expect(root.querySelector(`.${[componentName]ClassNames.start}`)).toBeInTheDocument();
    expect(root.querySelector(`.${[componentName]ClassNames.content}`)).toBeInTheDocument();
  });
});

Key testing principles:

  • Import the static classNames object from the component
  • Use toHaveClass() for elements accessible via roles/queries
  • Use querySelector() with the static class name for internal elements
  • Test all selectors, including those on conditionally rendered elements (pass appropriate props)

Example from NavigationBar:

import { navigationBarClassNames } from '../NavigationBar';

describe('NavigationBar static classNames', () => {
  it('applies static class names to component elements', () => {
    render(
      <NavigationBarWithTheme start={<div>Start</div>}>
        <div>Children</div>
      </NavigationBarWithTheme>,
    );

    const nav = screen.getByRole('navigation');
    expect(nav).toHaveClass(navigationBarClassNames.root);
    expect(nav.querySelector(`.${navigationBarClassNames.start}`)).toBeInTheDocument();
    expect(nav.querySelector(`.${navigationBarClassNames.content}`)).toBeInTheDocument();
  });
});

Step 5: Add Styles API (Mobile Components)

For mobile components, the pattern is simpler (no static classNames):

5.1 Add styles prop type

export type [ComponentName]Props = {
  // ... other props
  /** Custom styles for individual elements of the [ComponentName] component */
  styles?: {
    /** Root container element */
    root?: StyleProp<ViewStyle>;
    /** [Concise element description] */
    [selectorName]?: StyleProp<ViewStyle | TextStyle>;
    // ... more selectors as needed
  };
};

5.2 Apply in Component Implementation

<View style={[defaultStyles.root, styles?.root]}>
  <View style={[defaultStyles.content, styles?.content]}>{children}</View>
</View>

Step 6: Add JSDoc Notes for Special Cases

If any selectors have special rendering conditions, append the note after the element description with a comma:

styles?: {
  /** Header element, only rendered on phone viewport in horizontal direction */
  header?: React.CSSProperties;
};

Common cases to document:

  • Viewport-specific rendering (phone/tablet/desktop)
  • Direction-specific rendering (horizontal/vertical)
  • Conditional rendering based on props
  • Elements that only render with certain data (e.g., subSteps)

Reference: StylesAndClassNames Utility

The StylesAndClassNames utility type (from packages/web/src/types.ts) automatically generates:

// Given:
const fooClassNames = {
  root: 'cds-Foo',
  contentWrapper: 'cds-Foo-contentWrapper',
} as const;

// StylesAndClassNames<typeof fooClassNames> generates:
{
  styles?: {
    root?: React.CSSProperties;
    contentWrapper?: React.CSSProperties;
  };
  classNames?: {
    root?: string;
    contentWrapper?: string;
  };
}

Reference: NavigationBar Example

See packages/web/src/navigation/NavigationBar.tsx for a complete example of the styles API pattern:

  • Lines 16-28: Static classNames with JSDoc
  • Line 80: Using StylesAndClassNames type on regular Props (not BaseProps)
  • Lines 117, 140, 149: Applying classNames with cx()
  • Lines 125, 142, 152: Applying styles

See packages/web/src/navigation/__tests__/NavigationBar.test.tsx for static classNames test example:

  • NavigationBar static classNames describe block: Tests all static class names are applied

Step 7: Update Documentation

After adding the styles API to the component, update the documentation:

  1. Run the docgen to regenerate styles data:

    yarn nx run docs:docgen
    
  2. Create or update the styles documentation use the components.write-docs SKILL for general knowledge on how to write component documentation:

    • Create _webStyles.mdx with ComponentStylesTable and StylesExplorer
    • Create _mobileStyles.mdx with ComponentStylesTable (if mobile)
    • Update index.mdx to import and render the styles tables

Final Checklist

Before completing, verify:

  • Reviewed component structure for potential simplifications (flagged to user if found)
  • Selector names are from the approved list (or got user confirmation for new ones)
  • Each selector has a JSDoc comment following the convention (sentence case, no trailing period, concise noun phrase)
  • Class names follow cds-ComponentName-selectorName convention (camelCase)
  • Using StylesAndClassNames utility type on regular Props (not BaseProps) (web) or manual styles type (mobile)
  • Static classNames applied with cx() in component JSX (web only)
  • Dynamic classNames and styles props applied correctly
  • Special rendering conditions documented in JSDoc
  • Tests added for static classNames (web only) - see Step 4.4
  • Ran yarn nx run docs:docgen to regenerate styles data
  • Documentation updated to include new component styles information
  • Updated this file's "Approved Selector Names" table if new selectors were added

來自 coinbase 的更多技能

git.repo-manager
coinbase
git.repo-manager — 一個可安裝的AI代理技能,由coinbase/cds發布。
official
agentic-wallet
coinbase
透過 awal CLI 進行加密錢包操作 — 登入、查詢餘額、發送 USDC/ETH/POL/SOL、交易代幣、為錢包充值,以及使用 x402 支付協議來…
official
authenticate-wallet
coinbase
基於電子郵件OTP的錢包驗證,包含驗證與狀態檢查。兩步驟登入流程:先透過電子郵件發起請求以接收6位數OTP,再使用flowId與驗證碼完成驗證。內建電子郵件、flowId及OTP的輸入驗證規則,防止在執行指令前發生Shell注入。提供狀態檢查、餘額查詢、地址擷取及透過配套CLI指令存取錢包視窗等功能。所有指令皆支援--json輸出,以利機器讀取...
official
fund
coinbase
透過 Coinbase Onramp 或直接轉帳將 USDC 存入錢包。開啟輔助介面,用戶可選擇預設金額(10 美元、20 美元、50 美元)或自訂數值,並從 Apple Pay、簽帳卡、銀行轉帳或 Coinbase 帳戶資金中選擇付款方式。支援多種付款方式,結算時間各異:卡片與 Apple Pay 即時到帳,ACH 銀行轉帳需 1–3 天。資金以 Base 網路上的 USDC 存入;用戶亦可透過 npx awal@2.0.3... 直接將 USDC 發送至錢包地址。
official
monetize-service
coinbase
部署一個付費API端點,其他代理可透過x402協議發現並付費使用。基於HTTP 402支付協議,在Base鏈上按請求收取USDC;客戶端使用簽名交易支付,無需API金鑰或帳戶。當您聲明發現擴展時,自動將端點註冊至x402 Bazaar供代理發現。支援多種定價層級、萬用路由,以及透過Express中介軟體為每個端點設定多種支付選項。基於@x402/express和@x402/core建置...
official
pay-for-service
coinbase
在Base上透過x402協議自動以USDC支付來呼叫付費API。執行HTTP請求(GET、POST等)至支援x402的端點,自動處理原子化USDC支付。支援透過方法、JSON主體、查詢參數及自訂標頭進行請求自訂。包含支付控制:設定每次請求的最大USDC金額,並使用關聯ID分組相關操作。需要錢包驗證及足夠的USDC餘額;驗證所有使用者輸入以防止shell...
official
query-blockchain-data
coinbase
透過 CDP SQL API 與 x402 查詢 Base 上的鏈上區塊鏈數據。當您或用戶想查看關於已解碼區塊的鏈上資訊時使用…
official
query-onchain-data
coinbase
使用SQL在Base上查詢鏈上數據,每次查詢需支付x402費用。透過CoinbaseQL(基於ClickHouse的SQL方言)存取解碼事件、交易與區塊,支援JOIN、CTE、子查詢及標準函數。主要提供三個資料表:base.events(解碼的智能合約日誌)、base.transactions(完整交易數據)及base.blocks(區塊元數據)。查詢事件時需對索引欄位(event_signature、address、block_timestamp)進行過濾,以避免掃描完整資料表...
official