Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

xstate

БесплатноБез исполняемых скриптовНе проверен

Model complex UI logic with XState state machines. Use when a user asks to manage complex multi-step flows, model stateful UI (wizards, forms, auth), prevent…

TerminalSkillsот TerminalSkills★ 221 звезда на GitHub

Об этом скилле

XState

Overview

XState models application logic as state machines. Instead of managing boolean flags (isLoading, isError, isSuccess), you define states and transitions explicitly — making impossible states impossible. Ideal for complex flows: checkout, onboarding, authentication, multi-step forms.

Instructions

Install with npm install xstate (version 5; the setup() API below is v5 only) and, for React, npm install @xstate/react. Other framework bindings: @xstate/vue, @xstate/svelte. Without a framework, run a machine with createActor(machine).start(), actor.send(event) and actor.subscribe(snapshot => ...).

Step 1: Define a machine

setup() declares types, actors, guards and actions once, so createMachine is fully typed. The credentials live in context so that RETRY can re-run the request without carrying them in the event.

// machines/authMachine.ts
import { setup, assign, fromPromise } from 'xstate'

type User = { id: string; name: string; email: string }

export const authMachine = setup({
  types: {
    context: {} as {
      credentials: { email: string; password: string } | null
      user: User | null
      error: string | null
      retries: number
    },
    events: {} as
      | { type: 'LOGIN'; email: string; password: string }
      | { type: 'LOGOUT' }
      | { type: 'RETRY' },
  },
  actors: {
    loginUser: fromPromise<User, { email: string; password: string }>(async ({ input }) => {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(input),
      })
      if (!res.ok) throw new Error('Invalid credentials')
      return (await res.json()) as User
    }),
  },
  guards: {
    canRetry: ({ context }) => context.retries < 3,
  },
}).createMachine({
  id: 'auth',
  initial: 'idle',
  context: { credentials: null, user: null, error: null, retries: 0 },
  states: {
    idle: {
      on: {
        LOGIN: {
          target: 'authenticating',
          actions: assign({
            credentials: ({ event }) => ({ email: event.email, password: event.password }),
            retries: 0,
          }),
        },
      },
    },
    authenticating: {
      invoke: {
        src: 'loginUser',
        input: ({ context }) => context.credentials!,
        onDone: {
          target: 'authenticated',
          actions: assign({ user: ({ event }) => event.output, error: null, credentials: null }),
        },
        onError: {
          target: 'error',
          actions: assign({
            error: ({ event }) => (event.error as Error).message,
            retries: ({ context }) => context.retries + 1,
          }),
        },
      },
    },
    authenticated: {
      on: { LOGOUT: { target: 'idle', actions: assign({ user: null }) } },
    },
    error: {
      on: {
        RETRY: { target: 'authenticating', guard: 'canRetry' },
        LOGIN: {
          target: 'authenticating',
          actions: assign({
            credentials: ({ event }) => ({ email: event.email, password: event.password }),
            retries: 0,
          }),
        },
      },
    },
  },
})

Step 2: Use it in React

useMachine returns [snapshot, send, actorRef]. state.can(event) tells whether an event would cause a transition, which removes duplicated guard logic from the UI.

// components/LoginPage.tsx
import { useMachine } from '@xstate/react'
import { authMachine } from '../machines/authMachine'

export function LoginPage() {
  const [state, send] = useMachine(authMachine)

  if (state.matches('authenticated')) {
    return <div>Welcome, {state.context.user?.name}!</div>
  }

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault()
        const form = new FormData(e.currentTarget)
        send({
          type: 'LOGIN',
          email: form.get('email') as string,
          password: form.get('password') as string,
        })
      }}
    >
      <input name="email" type="email" required />
      <input name="password" type="password" required />
      {state.matches('error') && <p role="alert">{state.context.error}</p>}
      <button disabled={state.matches('authenticating')}>
        {state.matches('authenticating') ? 'Signing in...' : 'Sign in'}
      </button>
      {state.can({ type: 'RETRY' }) && (
        <button type="button" onClick={() => send({ type: 'RETRY' })}>
          Retry ({3 - state.context.retries} left)
        </button>
      )}
    </form>
  )
}

Step 3: Run and test without a UI

Machines are plain logic. Replace an actor with machine.provide() to test without the network:

import { createActor, fromPromise } from 'xstate'

const fake = authMachine.provide({
  actors: { loginUser: fromPromise(async () => ({ id: 'u1', name: 'Dana', email: '[email protected]' })) },
})
const actor = createActor(fake).start()
actor.send({ type: 'LOGIN', email: '[email protected]', password: 'correct
Полный SKILL.md на GitHub

Установить xstate в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

_scores.json

FAQ

Что делает скилл xstate?

Model complex UI logic with XState state machines. Use when a user asks to manage complex multi-step flows, model stateful UI (wizards, forms, auth), prevent impossible states, or implement finite state machines in JavaScript.

Как установить скилл xstate?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл xstate запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить xstate с