Логотип Component Api Design

Component Api Design

Организация
staple-lab
component-api-design

Use when designing or reviewing a component's props API - variants, sizes, controlled vs uncontrolled state, compound components, polymorphism, escape hatches, TypeScript prop types, ref forwarding, and naming. Triggers on "component API", "props design", "should this be a prop or a slot", "how do I type this component".

Add to TypingMind

Обзор

Издательstaple-lab
Репозиторийdesign-system-skills
Название навыкаcomponent-api-design
Звёзды
7
Форки
0
Файлы в комплекте
Только инструкции
ЛицензияMIT
Ссылки
  • Инструкции в формате Markdown

    Модель загружает файл SKILL.md по мере необходимости, поэтому токены расходуются только при подходящем запросе.

  • Работает с любой большой языковой моделью

    Навыки ИИ — это обычный Markdown, а не код для конкретного поставщика, поэтому они работают с GPT, Claude, Gemini, Grok и локальными моделями.

  • Всё необходимое — в инструкциях

    Всё необходимое для модели содержится в инструкциях — никаких дополнительных файлов для синхронизации.

  • Открытый исходный код

    Издатель навыка на GitHub — staple-lab. Перед установкой изучите исходные материалы.

Установка

Установите навык ИИ Component Api Design в TypingMind, чтобы использовать его с любой LLM, или добавьте его в другой агент, который умеет читать SKILL.md.

1

Установка в TypingMind

TypingMind устанавливает навык прямо из его папки на GitHub: читает SKILL.md, собирает файлы ресурсов и сохраняет результат локально.

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/staple-lab/design-system-skills/tree/main/plugins/design-system/skills/component-api-design
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Добавить навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

Установка в другом агенте

Любой агент с поддержкой формата Agent Skills может использовать этот навык — скопируйте папку в каталог навыков этого агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/staple-lab/design-system-skills.git /tmp/design-system-skills
mkdir -p .claude/skills
cp -r /tmp/design-system-skills/plugins/design-system/skills/component-api-design .claude/skills/component-api-design
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

Использование в TypingMind

Включите навык Component Api Design в любом чате TypingMind, и дальше модель всё сделает сама. Его название и описание хранятся в системном промпте, а при появлении подходящего запроса модель сама загружает полные инструкции. Вам не нужно вызывать навык вручную, и до фактического использования он не расходует токены.

Модель сама загружает навык Component Api Design, как только появляется подходящий для него запрос.

Работает с любой моделью ИИ

Навыки ИИ — это обычные инструкции в Markdown, а не код для конкретного поставщика, поэтому навык Component Api Design не привязан к модели, для которой он был создан. Установите его один раз в TypingMind и используйте с GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama или локальной моделью, которую запускаете самостоятельно, — со своими ключами API.

  • Загружается только при необходимости

    Системный промпт содержит только название и описание. Инструкции загружаются при первом подходящем запросе, поэтому неиспользуемый навык не расходует токены.

  • Меняйте модели прямо в чате

    Навык состоит из инструкций, а не кода, поэтому смена модели не нарушает его работу: новая модель читает тот же файл SKILL.md.

Инструкции навыка

Это содержимое файла SKILL.md, которое загружает модель. Прочитайте его перед установкой: навык — это инструкции, которым будет следовать ваша модель.

Component API design

The props API is the public contract. Styles can be fixed in an afternoon; a bad API is in a hundred call sites and stays wrong for years. Spend the extra hour here.

Boolean props are a trap

The most common API mistake, and it compounds:

tsx
// Bad — every new state doubles the invalid combinations
<Button primary secondary danger large small loading disabled />

// Good — enumerated, mutually exclusive by construction
<Button variant="primary" size="lg" loading />

variant and size should be string unions. Booleans are for genuinely independent binary states (loading, disabled, fullWidth). The test: if two props can never be true at once, they are one prop with a union type.

Controlled, uncontrolled, or both

Both — and the convention is non-negotiable because consumers expect DOM semantics:

tsx
interface Props {
  value?: string;              // controlled
  defaultValue?: string;       // uncontrolled initial
  onValueChange?: (v: string) => void;   // fires in BOTH modes
}

Rules:

  • value present → controlled. The component never updates its own state; it renders what it is given.
  • value absent → uncontrolled, defaultValue seeds it.
  • onValueChange fires in both modes. A callback that only fires when uncontrolled is a bug people hit at the worst time.
  • Never switch modes mid-life. Warn in dev if value goes from undefined to defined.
  • Name it onValueChange, not onChange, when it emits a value rather than an event — onChange implies a React ChangeEvent, and the mismatch bites at the first e.target.value.

Most primitive libraries already implement this correctly. Pass the props straight through and do not add a useState inside the wrapper; that is how wrappers break the controlled case.

Compound components

When a component has parts a consumer needs to arrange, reorder or replace, expose the parts:

tsx
<Dialog.Root>
  <Dialog.Trigger>Open</Dialog.Trigger>
  <Dialog.Content>
    <Dialog.Title>Delete project</Dialog.Title>
    <Dialog.Description>This cannot be undone.</Dialog.Description>
    <Dialog.Footer>
      <Dialog.Close>Cancel</Dialog.Close>
      <Button variant="danger">Delete</Button>
    </Dialog.Footer>
  </Dialog.Content>
</Dialog.Root>

The alternative — <Dialog title="..." description="..." footer={<>...</>} /> — looks tidier and dies on the first requirement that does not fit the props you imagined. A component with three or more ReactNode props is a compound component wearing a disguise.

When NOT to go compound: a Button with an icon does not need Button.Icon. Use compound parts when the arrangement varies, props when only the content varies.

Both can coexist: ship <Dialog> as a convenience wrapper over the parts for the 80% case, and export the parts for the rest. Make sure the convenience version is implemented using the parts, or the two drift.

Slots

For content in fixed positions, ReactNode props are right:

tsx
interface TextFieldProps {
  label: ReactNode;
  description?: ReactNode;
  errorMessage?: ReactNode;
  startAdornment?: ReactNode;   // "adornment"/"slot", not "icon" — people put buttons and badges there
  endAdornment?: ReactNode;
}

Type them ReactNode, not string. The moment someone needs <label>Name <Required/></label> a string type forces a fork.

Polymorphism

One convention per system (conventions.polymorphism in the brief). Whichever it is, the typing needs to preserve the target element's props:

tsx
// `render` (Base UI style)
<Button render={<a href="/pricing" />}>See pricing</Button>

// `asChild` (Radix style)
<Button asChild><a href="/pricing">See pricing</a></Button>

Do not invent a third. And prefer polymorphism over a href prop — the moment you add href you are reimplementing an anchor, and you will get target, rel, download and router integration wrong in that order.

TypeScript

tsx
import type { ComponentPropsWithRef, ReactNode } from 'react';
import type { VariantProps } from 'class-variance-authority';

export interface ButtonProps
  extends ComponentPropsWithRef<'button'>,          // inherit every native prop, including ref (React 19)
    VariantProps<typeof buttonVariants> {           // variant/size derived from the styles — one source
  loading?: boolean;
  startIcon?: ReactNode;
}
  • Extend the native element props. Consumers will need type="submit", form, aria-*, data-testid. Re-declaring a subset guarantees you missed one.
  • Derive variant types from the style definition so adding a variant to CVA cannot desync from the type.
  • Export every prop type. Consumers wrap your components; without the type they write any.
  • Use interface for public props (better error messages, declaration merging) and type for unions.

Encode invariants in the type rather than documenting them. An icon-only button that requires a label:

tsx
type ButtonProps = BaseProps &
  ({ children: ReactNode; 'aria-label'?: string } | { children?: never; 'aria-label': string });

Now the unlabelled icon button does not compile. That is worth more than a lint rule and infinitely more than a docs note.

Defaults

Every optional prop needs a sensible default so the zero-config case is the common case. <Button>Save</Button> should render the primary button at the default size. If a component cannot render without four props, the API is wrong.

Defaults belong in one place — the CVA/recipe defaultVariants or the destructure, not both.

Naming

DoDon'tWhy
variant, size, tonetype, style, kindtype and style collide with native props
isOpen / openvisible, shown, activeMatch the DOM/ARIA vocabulary
onValueChangeonUpdate, handleChangeon + noun + Change reads at the call site
disabledisDisabled, enabledMatch the native attribute; never invert a native boolean
startIcon / endIconleftIcon / rightIconLeft and right swap in RTL; start and end do not

Consistency beats individual elegance. If the system already uses isOpen, the next component uses isOpen.

Escape hatches

Every component needs exactly one deliberate way out, or people fork it:

  1. className passthrough, merged not replaced (cn(styles.base, className))
  2. ...rest spread onto the outer element
  3. ref forwarded
  4. Component-level CSS custom properties for the values most likely to need overriding

The failure mode is silent: a developer needs a 2px adjustment, finds no way in, copies the component into their feature folder, and now there are two buttons. You never hear about it.

The review checklist

Before a component is called done:

  • No boolean props that should be a union
  • Controlled and uncontrolled both work, onXChange fires in both
  • Extends native element props; ref reaches a real DOM node
  • className merged, ...rest spread, both verified by a test
  • Every variant × size × state combination renders (that is a test, not an eyeball)
  • Disabled state is not focusable-but-interactive, and communicates why when it can
  • Loading state preserves layout (no reflow when a spinner replaces a label)
  • Keyboard operable end to end; focus visible at 3:1
  • Works in both themes and at 200% browser zoom
  • Prop types exported
  • Registry entry filled in — props, a11y notes, do/don't, tokens consumed

Часто задаваемые вопросы

Что делает навык ИИ Component Api Design?

Use when designing or reviewing a component's props API - variants, sizes, controlled vs uncontrolled state, compound components, polymorphism, escape hatches, TypeScript prop types, ref forwarding, and naming. Triggers on "component API", "props design", "should this be a prop or a slot", "how do I type this component".

Зачем использовать Component Api Design в TypingMind?

Потому что вы устанавливаете навык один раз и используете его с любой моделью. Component Api Design — это обычный текст в формате Markdown, а не код для конкретного поставщика, поэтому один и тот же навык работает с GPT-5, Claude, Gemini, Grok или локальной моделью. Вы можете менять модель прямо во время чата, и навык продолжит работать. TypingMind использует ваши собственные ключи API, поэтому вы платите поставщикам напрямую, а не оформляете подписку с оплатой за каждое место. Ваши навыки и чаты остаются в вашем собственном хранилище.

Как установить Component Api Design в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/staple-lab/design-system-skills/tree/main/plugins/design-system/skills/component-api-design. TypingMind прочитает файл SKILL.md и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать Component Api Design?

Любая модель, которую вы подключите в TypingMind. Навыки ИИ — это обычные инструкции в формате Markdown, а не код для конкретного поставщика, поэтому GPT, Claude, Gemini, Grok и локальные модели могут загружать этот навык, когда запрос ему соответствует.

Со сколькими моделями ИИ можно использовать Component Api Design?

С любым количеством. В TypingMind вы можете использовать Component Api Design с любой моделью, которая поддерживает навыки, в том числе с GPT, Claude, Gemini, Grok, DeepSeek, Mistral и Llama. Для этого вы используете собственные ключи API.

Бесплатен ли навык ИИ Component Api Design?

Да. Навык опубликован на GitHub по лицензии MIT. Издатель — staple-lab. Вы платите только своему поставщику ИИ за использованные токены.

Что такое навыки ИИ?

Навык ИИ — это набор инструкций, которыми модель ИИ может пользоваться каждый раз, когда ей нужно выполнить конкретную задачу. Он соответствует открытому формату Agent Skills: файл SKILL.md с названием и описанием, а также любые скрипты, шаблоны или справочные файлы, которые могут понадобиться модели. Модель читает инструкции, только когда ваш запрос соответствует навыку, поэтому установленный навык ничего не стоит, пока не используется.

Чем навыки ИИ отличаются от плагинов и серверов MCP?

Плагин или сервер MCP даёт модели новые инструменты, которые она может вызывать: при вызове где-то выполняется код и возвращает результат. Навык ИИ, напротив, даёт модели знания и описывает порядок действий: как подойти к задаче, какие шаги выполнить и каким должен быть хороший результат. Навыки — это обычный текст в формате Markdown, поэтому им не нужны сервер, ключ API или среда выполнения, и они работают с любой моделью.

Все

Создайте своё рабочее пространство с ИИ прямо сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇