Token导航 LogoToken导航TokenDH.com
前端设计需要联网github未标认证来源可访问许可证需确认审计通过

textual-reactive-programming文本 React 式编程

Agent Skill

用于辅助前端页面、组件、样式和交互逻辑的开发与维护。它适合让 Agent 生成或审查 React、Next.js、Vue、Tailwind、CSS 等相关代码,整理组件结构,或定位布局和性能问题。使用时需要结合项目现有设计系统、路由和构建方式,避免只生成孤立片段;涉及页面改动时,应配合本地预览和构建检查确认视觉效果。

总安装

259

周安装

11

GitHub Stars

1

下载量

91
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:textual-reactive-programming(文本 React 式编程)
来源仓库:https://github.com/dawiddutoit/custom-claude
仓库路径:skills/textual-reactive-programming
安装命令:
npx skills add https://github.com/dawiddutoit/custom-claude --skill textual-reactive-programming
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/dawiddutoit/custom-claude --skill textual-reactive-programming

简介

textual-reactive-programming 用于辅助前端页面和组件开发。

  • 适合生成或审查 React、Vue、Tailwind CSS 等相关代码。
  • 使用时需要结合项目现有设计系统和路由方式,避免生成孤立片段。
  • 涉及页面改动时应配合本地预览和构建检查确认视觉效果。
  • 当前暂无底部简介内容,可参考来源仓库了解具体功能实现。

SKILL.md

Textual Reactive Programming

Purpose

Implement efficient, declarative data binding in Textual widgets using reactive attributes. This pattern eliminates manual refresh calls and ensures UI stays synchronized with state.

Quick Start

from textual.reactive import reactive
from textual.widgets import Static

class CounterWidget(Static):
    """Widget with reactive counter."""

    count = reactive(0)  # Reactive attribute initialized to 0

    def render(self) -> str:
        """Auto-called when count changes."""
        return f"Count: {self.count}"

    def increment(self) -> None:
        """Increment counter - triggers render()."""
        self.count += 1

# Usage:
widget = CounterWidget()
widget.increment()  # Automatically re-renders

Instructions

Step 1: Define Reactive Attributes

Declare reactive attributes using reactive():

from textual.reactive import reactive
from textual.widgets import Static
from typing import Literal

class ReactiveWidget(Static):
    """Widget with multiple reactive attributes."""

    # Basic reactive attribute
    status: reactive[str] = reactive("idle", init=False)

    # Reactive with initial value
    count: reactive[int] = reactive(0)

    # Reactive with complex type
    items: reactive[list[str]] = reactive(list, init=False)

    # Reactive with default name (attribute name used)
    message: reactive[str] = reactive("default message")

    # Reactive with type union
    state: reactive[Literal["on", "off"]] = reactive("off")

    def __init__(self, **kwargs: object) -> None:
        super().__init__(**kwargs)
        # Initialize reactive attributes in __init__
        # Only if init=False is set above
        # Otherwise they're initialized by reactive()

Reactive Declaration Options:

reactive(
    default_value,              # Required: initial value
    init=False,                 # True: initialize in __init__, False: initialize here
    layout=False,               # True: trigger layout when changed
    recompose=False,            # True: call compose() when changed
)

Important Rules:

  • Type hints are required: attribute: reactive[Type]
  • init=False means initialize in __init__
  • init=True (default) means initialize by reactive()
  • Changing a reactive attribute triggers a watcher/refresh

Step 2: Use Watch Methods

Watch methods automatically trigger when reactive attributes change:

from textual.reactive import reactive
from textual.widgets import Static
from typing import Literal

class WatcherWidget(Static):
    """Widget demonstrating watch methods."""

    status: reactive[Literal["idle", "running", "error"]] = reactive("idle", init=False)
    count: reactive[int] = reactive(0)
    items: reactive[list[str]] = reactive(list, init=False)

    def __init__(self, **kwargs: object) -> None:
        super().__init__(**kwargs)
        self.status = "idle"
        self.items = []

    def watch_status(self, old_value: str, new_value: str) -> None:
        """Called when status changes.

        Args:
            old_value: Previous status.
            new_value: New status.
        """
        # Update UI based on status change
        print(f"Status changed: {old_value} -> {new_value}")
        self.refresh()  # Re-render widget

    def watch_count(self, old_value: int, new_value: int) -> None:
        """Called when count changes."""
        if new_value < 0:
            # Revert invalid change
            self.count = old_value
        else:
            # Count is valid
            self.refresh()

    def watch_items(self, old_value: list[str], new_value: list[str]) -> None:
        """Called when items list changes.

        Note: Called on replacement, not on list mutations.
        """
        print(f"Items changed: {len(old_value)} -> {len(new_value)} items")
        self.refresh()

    def add_item(self, item: str) -> None:
        """Add item (triggers watch_items)."""
        # Replace list to trigger watcher
        self.items = self.items + [item]  # Creates new list
        # NOT: self.items.append(item)  # This won't trigger watcher

    def increment(self) -> None:
        """Increment count (triggers watch_count)."""
        self.count += 1  # Triggers watch_count

Watcher Pattern:

  • Method name: watch_{attribute_name}
  • Signature: watch_method(self, old_value: Type, new_value: Type) -> None
  • Called automatically when attribute changes
  • Called BEFORE re-render
  • Use for validation, side effects, cascading updates

Step 3: Implement Computed Properties

Use computed attributes that derive from other reactive attributes:

from textual.reactive import reactive, var
from textual.widgets import Static

class ComputedWidget(Static):
    """Widget with computed reactive attributes."""

    first_name: reactive[str] = reactive("John", init=False)
    last_name: reactive[str] = reactive("Doe", init=False)

    # Computed property (read-only)
    @property
    def full_name(self) -> str:
        """Derived from first_name and last_name."""
        return f"{self.first_name} {self.last_name}"

    # Alternative: Use var() for derived reactive attribute
    full_name_reactive: reactive[str] = reactive("John Doe")

    def watch_first_name(self, old_value: str, new_value: str) -> None:
        """Update computed attribute when first_name changes."""
        self.full_name_reactive = f"{new_value} {self.last_name}"
        self.refresh()

    def watch_last_name(self, old_value: str, new_value: str) -> None:
        """Update computed attribute when last_name changes."""
        self.full_name_reactive = f"{self.first_name} {new_value}"
        self.refresh()

    def render(self) -> str:
        return f"Full Name: {self.full_name}"

Pattern:

  • Use @property for computed values derived from reactive attrs
  • Watchers update derived attributes when dependencies change
  • Re-render when computed attributes change

Step 4: Handle Complex State Changes

Manage complex updates with multiple reactive attributes:

from textual.reactive import reactive
from textual.widgets import Static
from dataclasses import dataclass

@dataclass(frozen=True)
class DataPoint:
    """Immutable data point."""
    value: float
    timestamp: str

class ComplexStateWidget(Static):
    """Widget managing complex reactive state."""

    # Multiple reactive attributes
    data: reactive[list[DataPoint]] = reactive(list, init=False)
    total: reactive[float] = reactive(0.0)
    average: reactive[float] = reactive(0.0)
    loading: reactive[bool] = reactive(False)
    error: reactive[str | None] = reactive(None)

    def __init__(self, **kwargs: object) -> None:
        super().__init__(**kwargs)
        self.data = []
        self.total = 0.0
        self.average = 0.0
        self.loading = False
        self.error = None

    def watch_data(self, old_value: list[DataPoint], new_value: list[DataPoint]) -> None:
        """Recalculate totals when data changes."""
        if not new_value:
            self.total = 0.0
            self.average = 0.0
            return

        # Update computed values
        self.total = sum(p.value for p in new_value)
        self.average = self.total / len(new_value)
        self.error = None

    async def load_data(self) -> None:
        """Load data with loading state."""
        try:
            self.loading = True
            self.error = None

            # Simulate async fetch
            import asyncio
            await asyncio.sleep(1)

            # Update data (triggers watch_data)
            self.data = [
                DataPoint(10.5, "2024-01-01"),
                DataPoint(20.3, "2024-01-02"),
                DataPoint(15.8, "2024-01-03"),
            ]
        except Exception as e:
            self.error = str(e)
            self.data = []
        finally:
            self.loading = False

    def render(self) -> str:
        """Render with state."""
        if self.loading:
            return "Loading..."

        if self.error:
            return f"Error: {self.error}"

        if not self.data:
            return "No data"

        return (
            f"Items: {len(self.data)}\n"
            f"Total: {self.total:.2f}\n"
            f"Average: {self.average:.2f}"
        )

Pattern:

  • Organize related reactive attributes together
  • Watch methods maintain invariants (total, average, etc.)
  • Atomic updates: replace entire list/dict to trigger watchers
  • Use frozen dataclasses for immutable data points

Step 5: Implement Validation with Reactive Attributes

Use watchers to validate and enforce constraints:

from textual.reactive import reactive
from textual.widgets import Input, Static

class ValidatingWidget(Static):
    """Widget with reactive validation."""

    value: reactive[str] = reactive("", init=False)
    is_valid: reactive[bool] = reactive(True)
    error_message: reactive[str] = reactive("")

    def __init__(self, **kwargs: object) -> None:
        super().__init__(**kwargs)
        self.value = ""
        self.is_valid = True
        self.error_message = ""

    def watch_value(self, old_value: str, new_value: str) -> None:
        """Validate value when it changes."""
        # Validate
        is_valid = self._validate(new_value)

        if is_valid:
            self.is_valid = True
            self.error_message = ""
        else:
            self.is_valid = False
            self.error_message = "Invalid value"

        self.refresh()

    def _validate(self, value: str) -> bool:
        """Validate value according to rules."""
        # Example: email validation
        return "@" in value and "." in value

    def render(self) -> str:
        """Render with validation status."""
        status = "✓" if self.is_valid else "✗"
        return f"{status} {self.value}\n{self.error_message}"

Validation Pattern:

  • Watch method validates on change
  • Update separate reactive attributes for validity
  • Re-render to show status
  • Use color changes via CSS for invalid state

Examples

Example 1: Agent Status Widget with Reactive Updates

from textual.reactive import reactive
from textual.widgets import Static
from rich.text import Text
from typing import Literal

class AgentStatusWidget(Static):
    """Reactive agent status widget."""

    agent_id: reactive[str] = reactive("")
    status: reactive[Literal["idle", "running", "error"]] = reactive("idle", init=False)
    task_count: reactive[int] = reactive(0)
    error_message: reactive[str | None] = reactive(None)

    DEFAULT_CSS = """
    AgentStatusWidget {
        height: auto;
        border: solid $primary;
        padding: 1;
    }

    AgentStatusWidget .status-idle {
        color: $warning;
    }

    AgentStatusWidget .status-running {
        color: $success;
    }

    AgentStatusWidget .status-error {
        color: $error;
    }
    """

    def __init__(self, agent_id: str, **kwargs: object) -> None:
        super().__init__(**kwargs)
        self.agent_id = agent_id
        self.status = "idle"
        self.task_count = 0
        self.error_message = None

    def watch_status(self, old_value: str, new_value: str) -> None:
        """Update display when status changes."""
        self.refresh()

    def watch_task_count(self, old_value: int, new_value: int) -> None:
        """Track task count changes."""
        if new_value > old_value:
            # Task started
            if self.status == "idle":
                self.status = "running"
        elif new_value == 0:
            # All tasks completed
            if self.status == "running":
                self.status = "idle"

    def watch_error_message(self, old_value: str | None, new_value: str | None) -> None:
        """Update status when error occurs."""
        if new_value:
            self.status = "error"
        else:
            self.status = "idle"

    def render(self) -> Text:
        """Render reactive agent status."""
        text = Text()

        # Status indicator
        icon = self._get_icon()
        text.append(icon, style=f"status-{self.status}")
        text.append(" ")

        # Agent info
        text.append(self.agent_id, style="bold")
        text.append(f" ({self.status.upper()})")

        # Task count
        if self.task_count > 0:
            text.append(f" [{self.task_count} tasks]", style="dim")

        # Error
        if self.error_message:
            text.append("\n")
            text.append(f"Error: {self.error_message}", style="bold red")

        return text

    def _get_icon(self) -> str:
        """Get status icon."""
        return {
            "idle": "◐",
            "running": "●",
            "error": "✗",
        }.get(self.status, "?")

    async def update_task_count(self, count: int) -> None:
        """Update task count."""
        self.task_count = count

    async def set_error(self, error: str | None) -> None:
        """Set error state."""
        self.error_message = error

Example 2: Form Widget with Reactive Validation

from textual.reactive import reactive
from textual.app import ComposeResult
from textual.containers import Container
from textual.widgets import Static, Input, Button

class FormWidget(Container):
    """Form with reactive validation."""

    email: reactive[str] = reactive("", init=False)
    password: reactive[str] = reactive("", init=False)
    is_valid: reactive[bool] = reactive(False)

    DEFAULT_CSS = """
    FormWidget {
        height: auto;
        border: solid $primary;
        padding: 1;
    }

    FormWidget .field {
        height: auto;
        margin: 0 0 1 0;
    }

    FormWidget .field-label {
        text-style: bold;
    }

    FormWidget .field-error {
        color: $error;
        text-style: dim;
    }

    FormWidget .submit-button {
        margin-top: 1;
    }
    """

    def __init__(self, **kwargs: object) -> None:
        super().__init__(**kwargs)
        self.email = ""
        self.password = ""
        self.is_valid = False

    def compose(self) -> ComposeResult:
        yield Static("Email", classes="field-label")
        yield Input(id="email-input", classes="field")
        yield Static("", id="email-error", classes="field-error")

        yield Static("Password", classes="field-label")
        yield Input(id="password-input", password=True, classes="field")
        yield Static("", id="password-error", classes="field-error")

        yield Button("Submit", id="submit", disabled=True, classes="submit-button")

    async def on_mount(self) -> None:
        """Set up input watchers."""
        email_input = self.query_one("#email-input", Input)
        password_input = self.query_one("#password-input", Input)

        email_input.on_change_handler = self._on_email_change
        password_input.on_change_handler = self._on_password_change

    async def _on_email_change(self, value: str) -> None:
        """Handle email input change."""
        self.email = value
        await self._validate_email()

    async def _on_password_change(self, value: str) -> None:
        """Handle password input change."""
        self.password = value
        await self._validate_password()

    def watch_email(self, old_value: str, new_value: str) -> None:
        """Validate email when changed."""
        self._check_form_valid()

    def watch_password(self, old_value: str, new_value: str) -> None:
        """Validate password when changed."""
        self._check_form_valid()

    async def _validate_email(self) -> None:
        """Validate email format."""
        error_widget = self.query_one("#email-error", Static)
        if not self.email or "@" not in self.email:
            error_widget.update("Invalid email")
        else:
            error_widget.update("")

    async def _validate_password(self) -> None:
        """Validate password strength."""
        error_widget = self.query_one("#password-error", Static)
        if len(self.password) < 8:
            error_widget.update("Password must be 8+ characters")
        else:
            error_widget.update("")

    def _check_form_valid(self) -> None:
        """Check if entire form is valid."""
        is_valid = (
            "@" in self.email
            and len(self.password) >= 8
        )
        self.is_valid = is_valid

        # Update submit button
        submit = self.query_one("#submit", Button)
        submit.disabled = not is_valid

Requirements

  • Textual >= 0.45.0
  • Python 3.9+ with type hints

Best Practices

1. Prefer reactive attributes over manual refresh:

# ❌ WRONG - manual refresh
def set_status(self, status: str) -> None:
    self._status = status
    self.refresh()

# ✅ CORRECT - reactive attribute
status: reactive[str] = reactive("")

def watch_status(self, old_value: str, new_value: str) -> None:
    """Auto-refresh on change."""
    pass  # refresh() called automatically

2. Use watchers for side effects:

def watch_count(self, old_value: int, new_value: int) -> None:
    """Handle side effects."""
    if new_value > 10:
        self.error = "Too many items"
    self.refresh()

3. Replace collections to trigger watchers:

# ❌ WRONG - mutation doesn't trigger watcher
self.items.append(new_item)

# ✅ CORRECT - replacement triggers watcher
self.items = self.items + [new_item]
# OR
self.items = [*self.items, new_item]

See Also

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

33.23%
按下载量换算30

Claude

27.74%
按下载量换算25

Cursor

18.95%
按下载量换算17

Gemini CLI

10.21%
按下载量换算9

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills