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 기반 지갑 인증으로 검증 및 상태 확인을 제공합니다. 2단계 로그인 절차: 이메일로 6자리 OTP를 받기 위해 시작한 후, flowId와 코드로 인증을 완료합니다. 명령어 실행 전 셸 인젝션을 방지하기 위해 이메일, flowId, OTP에 대한 입력 검증 규칙이 포함되어 있습니다. 동반 CLI 명령어를 통해 상태 확인, 잔액 조회, 주소 검색 및 지갑 창 접근을 제공합니다. 모든 명령어는 기계 판독 가능한 출력을 위해 --json을 지원합니다...
official
fund
coinbase
Coinbase Onramp 또는 직접 전송을 통해 USDC를 지갑에 입금합니다. 사용자가 사전 설정된 금액($10, $20, $50) 또는 사용자 지정 값을 선택하고 Apple Pay, 직불카드, 은행 송금 또는 Coinbase 계정 자금 조달 중에서 선택할 수 있는 보조 UI를 엽니다. 다양한 결제 수단을 지원하며 정산 시간이 다릅니다: 카드 및 Apple Pay는 즉시, ACH 은행 송금은 1~3일 소요됩니다. Base 네트워크에서 USDC로 자금을 입금하며, 또는 사용자는 npx awal@2.0.3...을 통해 지갑 주소로 직접 USDC를 보낼 수 있습니다.
official
monetize-service
coinbase
x402 프로토콜을 통해 다른 에이전트가 발견하고 결제할 수 있는 유료 API 엔드포인트를 배포합니다. HTTP 402 결제 프로토콜을 사용하여 Base에서 요청당 USDC를 청구하며, 클라이언트는 서명된 트랜잭션으로 결제하고 API 키나 계정이 필요하지 않습니다. 검색 확장을 선언하면 엔드포인트를 x402 Bazaar에 자동으로 등록하여 에이전트가 발견할 수 있도록 합니다. Express 미들웨어를 사용하여 엔드포인트당 여러 가격 계층, 와일드카드 경로 및 여러 결제 옵션을 지원합니다. @x402/express 및 @x402/core 기반으로 구축되었습니다...
official
pay-for-service
coinbase
Base에서 x402 프로토콜을 통해 자동 USDC 결제로 유료 API를 호출합니다. x402 지원 엔드포인트에 HTTP 요청(GET, POST 등)을 실행하며, USDC 결제가 자동으로 처리됩니다. 메서드, JSON 본문, 쿼리 매개변수 및 사용자 정의 헤더를 통해 요청을 사용자 지정할 수 있습니다. 결제 제어 기능이 포함되어 있어 요청당 최대 USDC 금액을 설정하고 상관 ID로 관련 작업을 그룹화할 수 있습니다. 지갑 인증과 충분한 USDC 잔액이 필요하며, 셸을 방지하기 위해 모든 사용자 입력을 검증합니다...
official
query-blockchain-data
coinbase
Base에서 CDP SQL API를 통해 x402로 온체인 블록체인 데이터를 조회합니다. 사용자나 본인이 디코딩된 블록에 대한 온체인 정보를 확인하고자 할 때 사용하세요.
official
query-onchain-data
coinbase
Base에서 SQL을 사용하여 온체인 데이터를 쿼리하고, 쿼리당 x402 결제를 적용합니다. CoinbaseQL을 통해 디코딩된 이벤트, 트랜잭션 및 블록에 접근할 수 있습니다. CoinbaseQL은 조인, CTE, 서브쿼리 및 표준 함수를 지원하는 ClickHouse 기반 SQL 방언입니다. 세 가지 주요 테이블을 사용할 수 있습니다: base.events(디코딩된 스마트 컨트랙트 로그), base.transactions(전체 트랜잭션 데이터), base.blocks(블록 메타데이터). 이벤트 쿼리에서 전체 테이블 스캔을 피하기 위해 인덱싱된 필드(event_signature, address, block_timestamp)에 대한 필터링이 필요합니다.
official