@wangs-ui/skills 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,244 @@
1
+ import path from "node:path";
2
+ import fs from "node:fs";
3
+ import { fileURLToPath } from "node:url";
4
+ import { cancel, intro, isCancel, multiselect, outro } from "@clack/prompts";
5
+ //#region skills/create-form/SKILL.md?raw
6
+ var SKILL_default$7 = "---\nname: create-form\ndescription: Architecture, validation workflows, and MCP discovery protocol for building forms and input controls with @wangs-ui/react-core.\n---\n\n# Skill: Form Architecture & Validation Workflows\n\nUse this skill when building forms, data entry panels, settings pages, or multipart forms in Wangs UI applications.\n\n---\n\n## 1. MCP Inspection Protocol (Mandatory Single Source of Truth)\n\nDo **NOT** hardcode or guess prop names, field configurations, or validation options. Retrieve active component definitions and live implementation stories directly from MCP:\n\n### Inspect Component & Form Contracts:\n\n```json\nget-documentation({ \"id\": \"form\" })\nget-documentation({ \"id\": \"field\" })\nget-documentation({ \"id\": \"input\" })\nget-documentation({ \"id\": \"numberinput\" })\nget-documentation({ \"id\": \"select\" })\nget-documentation({ \"id\": \"multiselect\" })\nget-documentation({ \"id\": \"datepicker\" })\nget-documentation({ \"id\": \"fileupload\" })\n```\n\n### Inspect Live Story Implementations:\n\n```json\nget-documentation-for-story({ \"id\": \"form\", \"storyName\": \"Default\" })\nget-documentation-for-story({ \"id\": \"field\", \"storyName\": \"Default\" })\nget-documentation-for-story({ \"id\": \"select\", \"storyName\": \"Basic\" })\nget-documentation-for-story({ \"id\": \"datepicker\", \"storyName\": \"Default\" })\nget-documentation-for-story({ \"id\": \"fileupload\", \"storyName\": \"Default\" })\n```\n\n### Inspect Knowledge Graph & Usages:\n\n```json\nquery_graph({ \"query\": \"useFormControl\" })\nquery_graph({ \"query\": \"Field\" })\n```\n\n---\n\n## 2. Form Architecture & State Principles\n\n1. **State & Control**:\n - Standard REST payload forms use `useFormControl` with JSON mode.\n - Multipart file upload workflows use `useFormControl` with FormData mode.\n2. **Field Composition**:\n - Form inputs are wrapped with `<Field>` layout containers for unified label, tooltip, helper text, and error rendering.\n - Exact props, slot rendering functions, and field binding options must be retrieved via MCP (`get-documentation({ \"id\": \"field\" })`).\n3. **Server Validation Error Mapping**:\n - Backend validation responses (e.g. `422 Unprocessable Entity`) are mapped back into the form instance via `formControl.setError()`.\n4. **Submission Lifecycle**:\n - In-flight network requests should manage loading state on submit actions and prevent accidental reset during mutations.\n\n---\n\n## 3. Mandatory Implementation Rules\n\n1. **Always Query MCP First**: Never guess input props or event signatures; obtain the exact types from `get-documentation`.\n2. **Strict Subpath Imports**: All components must be imported via their granular subpath (`@wangs-ui/react-core/primitive/*`, `@wangs-ui/form`).\n3. **Translate All Visible Strings**: Every field label, placeholder, helper text, and error message must be wrapped in `t('...')` from `@wangs-ui/react-i18n`.\n";
7
+ //#endregion
8
+ //#region skills/data-table/SKILL.md?raw
9
+ var SKILL_default$6 = "---\nname: data-table\ndescription: Architecture, workflows, and MCP discovery protocol for building DataTables with sorting, pagination, filtering, selection, and export.\n---\n\n# Skill: DataTable Architecture & Integration Workflows\n\nUse this skill when implementing data grids, server-paginated tables, filterable listing views, or batch management interfaces with `@wangs-ui/react-core`.\n\n---\n\n## 1. MCP Inspection Protocol (Mandatory Single Source of Truth)\n\nDo **NOT** guess table prop names or hardcode table structures. Query the MCP server dynamically to inspect exact TypeScript signatures, live story implementations, and companion controls:\n\n### Inspect Component Contracts:\n\n```json\nget-documentation({ \"id\": \"datatable\" })\nget-documentation({ \"id\": \"exportbutton\" })\nget-documentation({ \"id\": \"filtercontainer\" })\nget-documentation({ \"id\": \"bulkactionbutton\" })\n```\n\n### Inspect Live Story Implementations:\n\n```json\nget-documentation-for-story({ \"id\": \"datatable\", \"storyName\": \"Basic\" })\nget-documentation-for-story({ \"id\": \"datatable\", \"storyName\": \"ServerPagination\" })\nget-documentation-for-story({ \"id\": \"datatable\", \"storyName\": \"Sortable\" })\nget-documentation-for-story({ \"id\": \"datatable\", \"storyName\": \"MultipleSelection\" })\nget-documentation-for-story({ \"id\": \"datatable\", \"storyName\": \"CustomColumn\" })\nget-documentation-for-story({ \"id\": \"exportbutton\", \"storyName\": \"WithTable\" })\n```\n\n### Inspect Knowledge Graph & Usages:\n\n```json\nquery_graph({ \"query\": \"DataTable\" })\nquery_graph({ \"query\": \"useDataTableFetch\" })\n```\n\n---\n\n## 2. Core Architecture & Mental Model\n\nThe Wangs UI `DataTable` is built on a modular, headless-first architecture:\n\n1. **Declarative Column Definitions (`TableColumn<T>[]`)**:\n Columns are configured as typed array objects, not as JSX children. Check `get-documentation({ \"id\": \"datatable\" })` for column field types.\n2. **Table Instance Hook (`useDataTable`)**:\n Coordinates table state (sorting, pagination, selection, column ordering, pinning, visibility).\n3. **Data Fetching Hook (`useDataTableFetch`)**:\n Feeds server-side data, handles loading indicators, manages query parameters (`search`, `filter`, `sort`, `page`, `limit`), and debounces requests automatically.\n4. **Ecosystem Companions**:\n - `FilterContainer` & `FilterToggleButton`: Filter popovers and faceted search.\n - `ExportButton`: Client/server export to Excel, CSV, PDF, or Print.\n - `BulkActionButton`: Contextual batch actions triggered when rows are selected.\n - `CustomColumn`: User-controlled column ordering, visibility toggling, and pinning.\n\n---\n\n## 3. Mandatory Implementation Rules\n\n1. **Query MCP for Current Code Patterns**: Always run `get-documentation-for-story` for `datatable` before drafting code.\n2. **Strict Subpath Imports**: Import via `@wangs-ui/react-core/primitive/datatable` and companion primitive paths.\n3. **Always Translate Visible Copy**: All column header labels, empty state messages, and action button labels must be wrapped in `t('...')` from `@wangs-ui/react-i18n`.\n4. **Stable Row Identity**: Always configure a unique key identifier for stable selection and row identity.\n";
10
+ //#endregion
11
+ //#region skills/dialog-modal/SKILL.md?raw
12
+ var SKILL_default$5 = "---\nname: dialog-modal\ndescription: Patterns, overlay selection criteria, and MCP discovery protocol for Dialog, Modal, and DialogForm components in Wangs UI.\n---\n\n# Skill: Dialog, Modal & Overlay Workflows\n\nUse this skill when building interactive modals, create/edit dialog forms, destructive action confirmations, or slide-in overlay panels.\n\n---\n\n## 1. MCP Inspection Protocol (Mandatory Single Source of Truth)\n\nDo **NOT** guess overlay props, event names, or footer slots. Query the MCP server dynamically to inspect exact contracts and live story implementations:\n\n### Inspect Overlay Contracts:\n\n```json\nget-documentation({ \"id\": \"dialog\" })\nget-documentation({ \"id\": \"dialogform\" })\nget-documentation({ \"id\": \"modal\" })\nget-documentation({ \"id\": \"toast\" })\n```\n\n### Inspect Live Story Implementations:\n\n```json\nget-documentation-for-story({ \"id\": \"dialog\", \"storyName\": \"Confirmation\" })\nget-documentation-for-story({ \"id\": \"dialogform\", \"storyName\": \"Default\" })\nget-documentation-for-story({ \"id\": \"modal\", \"storyName\": \"Default\" })\n```\n\n### Inspect Knowledge Graph & Usages:\n\n```json\nquery_graph({ \"query\": \"Dialog\" })\nquery_graph({ \"query\": \"DialogForm\" })\n```\n\n---\n\n## 2. Overlay Selection Matrix\n\n| Component | Primary Use Case | Key Characteristics |\n| :--------------- | :-------------------------------------------- | :------------------------------------------------------------------------------------ |\n| **`Dialog`** | Confirmations, alerts, simple detail previews | Standard `header`, `footer`, and body layout; built-in backdrop dimming. |\n| **`DialogForm`** | Create/Edit forms embedded inside a dialog | Built-in form submit/cancel action bar, dirty state tracking, and submit lifecycle. |\n| **`Modal`** | Slide-in drawers, complex custom viewports | Headless overlay primitive with flexible animations, size variants, and drawer modes. |\n\n---\n\n## 3. Mandatory Implementation Rules\n\n1. **Query MCP for Current Code Patterns**: Always inspect `dialog`, `dialogform`, or `modal` stories via MCP before writing overlay code.\n2. **Strict Subpath Imports**: Import via `@wangs-ui/react-core/primitive/dialog`, `@wangs-ui/react-core/primitive/dialogform`, `@wangs-ui/react-core/primitive/modal`, or `@wangs-ui/react-core/primitive/toast`.\n3. **Prevent Dismissal During Async Mutations**: Guard the close handler so users cannot accidentally dismiss the dialog while a mutation request is in-flight.\n4. **Coordinate with Toast Notifications**: Trigger feedback toasts on successful creation, update, or deletion actions.\n5. **Translate All Overlay Copy**: All dialog titles, confirmation descriptions, and button labels must be localized using `t('...')` from `@wangs-ui/react-i18n`.\n";
13
+ //#endregion
14
+ //#region skills/i18n-usage/SKILL.md?raw
15
+ var SKILL_default$4 = "---\nname: i18n-usage\ndescription: Comprehensive guidelines for application internationalization, JIT translations (t), ICU formatting, and locale-aware formatting with @wangs-ui/react-i18n.\n---\n\n# Skill: Application Internationalization & Formatting Protocol\n\nUse this skill when implementing multi-language interfaces, translating user-facing text, formatting dates, times, currencies, or numbers in React applications built with Wangs UI and `@wangs-ui/react-i18n`.\n\n---\n\n## 1. The MCP Discovery Protocol (Single Source of Truth)\n\nDo **NOT** guess component localization contracts, language switcher variants, or datepicker props. Query the MCP server dynamically to inspect exact props and live story implementations:\n\n### Inspect Localized Component Contracts:\n\n```json\nget-documentation({ \"id\": \"languageswitcher\" })\nget-documentation({ \"id\": \"currencyinput\" })\nget-documentation({ \"id\": \"datepicker\" })\nget-documentation({ \"id\": \"select\" })\nget-documentation({ \"id\": \"datatable\" })\n```\n\n### Inspect Live Story Implementations:\n\n```json\nget-documentation-for-story({ \"id\": \"languageswitcher\", \"storyName\": \"Basic\" })\nget-documentation-for-story({ \"id\": \"currencyinput\", \"storyName\": \"Basic\" })\nget-documentation-for-story({ \"id\": \"datepicker\", \"storyName\": \"Default\" })\n```\n\n---\n\n## 2. Root Provider Setup (`WangsUiI18nProvider`)\n\nWrap the application root with `WangsUiI18nProvider` from `@wangs-ui/react-i18n` to enable dynamic JIT translations, versioned cache invalidation, and locale context:\n\n```tsx\nimport { WangsUiI18nProvider } from '@wangs-ui/react-i18n';\nimport React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport App from './App';\n\nReactDOM.createRoot(document.getElementById('root')!).render(\n <React.StrictMode>\n <WangsUiI18nProvider defaultLocale=\"en\" baseUrl={import.meta.env.VITE_API_URL || ''}>\n <App />\n </WangsUiI18nProvider>\n </React.StrictMode>,\n);\n```\n\n---\n\n## 3. Translation Protocol with `useI18n()`\n\nThe `@wangs-ui/react-i18n` package uses a Just-In-Time (JIT) translation architecture where natural English text strings serve as database keys.\n\n### A. Consumer-Level Translation for `ReactNode` Props (Mandatory)\n\nAll user-facing text props in Wangs UI components (`placeholder`, `label`, `emptyMessage`, `header`, `tooltip`, etc.) are typed as `ReactNode` and rendered as-is. Components do **NOT** automatically translate custom strings. Translation **MUST** be called at the application/consumer level:\n\n```tsx\nimport { useI18n } from '@wangs-ui/react-i18n';\nimport Button from '@wangs-ui/react-core/primitive/button';\nimport DataTable from '@wangs-ui/react-core/primitive/datatable';\nimport Select from '@wangs-ui/react-core/primitive/select';\n\nexport function OrderList() {\n const { t } = useI18n();\n\n return (\n <div>\n <Select placeholder={t('Search category...')} />\n <DataTable emptyMessage={t('No orders found')} />\n <Button label={t('Create new order')} />\n </div>\n );\n}\n```\n\n### B. Natural English Sentence Keys\n\nAlways write full, natural English sentences as translation keys. Never use artificial dotted namespace keys:\n\n```tsx\n// ✅ Good — Natural English\nt('Invoice Summary');\nt('Are you sure you want to delete this customer?');\n\n// ❌ Bad — Artificial dotted keys\nt('invoice.summary.title');\nt('dialog.delete.customer.confirm');\n```\n\n### C. Named Variable Interpolation (Single Braces `{var}`)\n\nPass interpolation values inside a plain object using descriptive named variables. This provides crucial semantic context for AI translation engines:\n\n```tsx\n// ✅ Good — Named variables provide context\nt('Upload {count} files to {groupName}', { count: 5, groupName: 'Marketing' });\nt('Welcome back, {userName}!', { userName: user.name });\n\n// ❌ Bad — Concatenation or positional arguments\nt('Welcome back, ' + user.name);\nt('Upload {0} files to {1}', 5, 'Marketing');\n```\n\n### D. ICU Pluralization & Zero-State (`=0`)\n\nAlways handle singular, plural, and zero states directly within ICU MessageFormat strings. Do **NOT** use JavaScript ternary operators:\n\n```tsx\n// ✅ Good — Clean ICU pluralization with zero-state handling\nt('{count, plural, =0 {No items selected} one {1 item selected} other {{count} items selected}}', {\n count: selectedCount,\n});\n\n// ❌ Bad — Manual JS branching\nselectedCount === 0\n ? t('No items selected')\n : selectedCount === 1\n ? t('1 item selected')\n : t('{count} items selected', { count: selectedCount });\n```\n\n### E. Rich Text / Annotated Strings\n\nUse standard supported HTML tags (`<a>`, `<b>`, `<i>`, `<u>`, `<s>`, `<br/>`, `<sub>`, `<sup>`, `<code>`, `<mark>`) for inline styling. Tags are automatically parsed into React elements without custom regex or string manipulation:\n\n```tsx\nimport Link from '@wangs-ui/foundation/theme/Link';\n\nt('You have selected <b>{count} items</b>. Click <a>here</a> to review.', {\n count: selectedCount,\n a: (chunks) => <Link href=\"/review\">{chunks}</Link>,\n});\n```\n\n---\n\n## 4. Locale Formatting Protocol with `useLocaleFormatter()`\n\nFor locale-aware formatting of dates, relative times, currencies, numbers, and display names, use the dedicated `useLocaleFormatter()` hook. All functions automatically adapt to the active locale without triggering backend database requests:\n\n```tsx\nimport { useLocaleFormatter } from '@wangs-ui/react-i18n';\n\nexport function SummaryCard({ updatedAt, amount, count }: Props) {\n const {\n formatDate,\n formatRelativeTime,\n formatCurrency,\n formatNumber,\n formatDisplayName,\n formatList,\n truncateText,\n } = useLocaleFormatter();\n\n return (\n <div>\n {/* Date formatting with Go tokens or date-fns tokens, and timezone */}\n <p>{formatDate(new Date(), 'dd MMMM yyyy, HH:mm', 'Asia/Jakarta')}</p>\n\n {/* Relative time */}\n <p>{formatRelativeTime(updatedAt)}</p>\n\n {/* Currency formatting */}\n <p>{formatCurrency(amount, 'IDR')}</p>\n\n {/* Number formatting with locale grouping */}\n <p>{formatNumber(count)}</p>\n\n {/* ISO code to localized name */}\n <p>{formatDisplayName('id', 'language')}</p>\n\n {/* Localized list */}\n <p>{formatList(['Finance', 'Operations', 'IT'])}</p>\n\n {/* Emoji & multi-byte safe text truncation */}\n <p>{truncateText('Long product description with emojis 🚀', 20)}</p>\n </div>\n );\n}\n```\n\n> [!NOTE]\n> Formatters MUST NOT be called as standalone `t()` keys (e.g. `t(formatRelativeTime(date))`). Instead, pass the formatted result as a named variable:\n>\n> ```tsx\n> const { t } = useI18n();\n> const { formatRelativeTime } = useLocaleFormatter();\n> const label = t('Updated {time}', { time: formatRelativeTime(updatedAt) });\n> ```\n\n---\n\n## 5. Language Switching UI Integration\n\nConnect the Wangs UI `LanguageSwitcher` primitive directly with `useI18n()` state:\n\n```tsx\nimport LanguageSwitcher from '@wangs-ui/react-core/primitive/languageswitcher';\nimport { useI18n } from '@wangs-ui/react-i18n';\n\nexport function HeaderLanguageSwitcher() {\n const { locale, setLocale, languageOptions } = useI18n();\n\n return (\n <LanguageSwitcher\n options={languageOptions}\n value={locale}\n onChange={(code) => setLocale(code)}\n />\n );\n}\n```\n\n---\n\n## 6. Strict Behavioral Constraints (MUST NOT)\n\n- **NO Formatters Destructured from `useI18n()`:** Formatters are isolated in `useLocaleFormatter()`. Never attempt to import `formatDate` or `formatCurrency` from `useI18n()`.\n- **NO String Concatenation in `t()` Keys:** Never concatenate strings or use dynamic template literals (e.g. `t('Hello ' + user.name)` or ``t(`Hello ${user.name}`)``). This creates infinite distinct keys in the translation database and prevents caching.\n- **NO Manual Zero-State JavaScript Branching:** Always use ICU `=0` syntax inside a single plural key.\n- **NO Dotted Artificial Translation Keys:** Never use dotted keys like `t('app.header.title')`. Use natural English sentences.\n- **NO Custom Markdown Formatting Symbols:** Do not use `*bold*` or `_italic_` in translation keys. Use valid HTML tags like `<b>bold</b>`.\n- **NO Hardcoded Static Translation Dictionaries:** Do not bundle static translation files (`id.json`, `zh.json`). The JIT backend broker manages translations dynamically.\n- **NO Unnecessary English Key Modifications:** Minor typos or punctuation changes in keys create orphaned entries in the translation backend and trigger new AI translation costs.\n";
16
+ //#endregion
17
+ //#region skills/layout-navigation/SKILL.md?raw
18
+ var SKILL_default$3 = "---\nname: layout-navigation\ndescription: Architecture, navigation hierarchies, and MCP discovery protocol for AppLayout, Sidebar, Breadcrumb, and Tabs in Wangs UI.\n---\n\n# Skill: Application Layout & Navigation Hierarchy\n\nUse this skill when constructing application shells, multi-level sidebars, page headers, breadcrumbs, or tabbed views with `@wangs-ui/react-core`.\n\n---\n\n## 1. MCP Inspection Protocol (Mandatory Single Source of Truth)\n\nDo **NOT** guess layout block slots, sidebar item interfaces, or breadcrumb props. Query the MCP server dynamically to inspect exact contracts and live story implementations:\n\n### Inspect Layout & Navigation Contracts:\n\n```json\nget-documentation({ \"id\": \"applayout\" })\nget-documentation({ \"id\": \"sidebar\" })\nget-documentation({ \"id\": \"breadcrumb\" })\nget-documentation({ \"id\": \"tabs\" })\n```\n\n### Inspect Live Story Implementations:\n\n```json\nget-documentation-for-story({ \"id\": \"applayout\", \"storyName\": \"Default\" })\nget-documentation-for-story({ \"id\": \"sidebar\", \"storyName\": \"Default\" })\nget-documentation-for-story({ \"id\": \"breadcrumb\", \"storyName\": \"Default\" })\nget-documentation-for-story({ \"id\": \"tabs\", \"storyName\": \"Default\" })\n```\n\n### Inspect Knowledge Graph & Usages:\n\n```json\nquery_graph({ \"query\": \"AppLayout\" })\nquery_graph({ \"query\": \"Sidebar\" })\n```\n\n---\n\n## 2. Layout Architecture & Mental Model\n\n1. **Top-Level App Shell (`AppLayout`)**:\n Provides structured slots for `sidebar`, `header`, and main content view, handling responsive viewport scaling and mobile navigation overlays.\n2. **Hierarchical Menu (`Sidebar`)**:\n Renders single and nested navigation items, active route indicators, collapsible state, and notification badges.\n3. **Breadcrumb Trail (`Breadcrumb`)**:\n Maintains clear navigational hierarchy on page headers.\n4. **Tabbed Sub-Views (`Tabs`)**:\n Organizes complex entity detail views or multi-section settings into distinct tabbed panels.\n\n---\n\n## 3. Mandatory Implementation Rules\n\n1. **Query MCP for Current Code Patterns**: Inspect `applayout` and `sidebar` stories via MCP before assembling the layout.\n2. **Strict Subpath Imports**: Import layout blocks via `@wangs-ui/react-core/blocks/*` and primitives via `@wangs-ui/react-core/primitive/*`.\n3. **Consistent Spacing Grid**: Use standard container padding (`p-6` or `p-xxl`) across page contents.\n4. **Page Hierarchy Alignment**: Every page view inside the layout must provide a clear `.heading-1` hierarchy and synchronized breadcrumbs.\n5. **Translate Navigation Labels**: Wrap all sidebar item labels and breadcrumb texts in `t('...')` from `@wangs-ui/react-i18n`.\n";
19
+ //#endregion
20
+ //#region skills/react19-compiler-typescript/SKILL.md?raw
21
+ var SKILL_default$2 = "---\nname: react19-compiler-typescript\ndescription: Enforce idiomatic React 19 + TypeScript conventions built around the React Compiler's automatic memoization. Use this any time writing, generating, reviewing, or refactoring React components, hooks, or props in TypeScript/TSX — including code that manually wraps things in useMemo/useCallback/React.memo, uses forwardRef, mutates props/state, or needs typing for Actions, useOptimistic, use(), or refs. Trigger even if the user didn't say \"React 19\" or \"compiler\" explicitly; it applies whenever React component/hook code is being written or optimized.\n---\n\n# React 19 + TypeScript with the React Compiler\n\n## Why this matters\n\nReact Compiler (stable since React Compiler 1.0, October 2025) rewrites your components\nand hooks at build time, inserting memoization equivalent to `useMemo`/`useCallback`/\n`React.memo` automatically and more granularly than a human would by hand. It ships as\n`babel-plugin-react-compiler`, and its lint rules live inside `eslint-plugin-react-hooks`\n(recommended preset) so linting and compilation share one source of truth.\n\nThe practical consequence: **manual memoization is no longer the default** — it's\neither redundant, or actively harmful if it doesn't match what the compiler would have\ninferred (the compiler bails out silently rather than risk breaking your app). Writing\n\"optimized\" React in 2026 means writing _plain, rule-following_ React and trusting the\nbuild step, not sprinkling `useMemo` everywhere out of habit.\n\nThis skill assumes and builds on the base `typescript-strict-typing` skill for general\ntyping discipline (no `any`, `interface` for entities, discriminated unions for variant\nstate, etc.) — apply both together.\n\n## Core principle\n\n> Write plain, obviously-pure React. Let the compiler memoize. The Rules of React are no\n> longer just style guidance — the compiler's correctness depends on you following them.\n\n---\n\n## 1. Stop hand-rolling memoization\n\n> ⚠️ **Everything in this section assumes the compiler is confirmed active** (wired per\n> §7, verified via the \"Memo ✨\" badge in §8). If you drop manual memoization _without_\n> that confirmation, you don't get automatic memoization to replace it — you get\n> **neither**. That's not a correctness bug (React still renders the right output), but\n> every child re-renders on every parent render regardless of whether its props\n> actually changed, and every inline computation reruns every render with nothing\n> caching it. It's the pre-memoization default behavior of React — often invisible in\n> small trees, but a real source of jank in large lists, heavy computations, or deep\n> trees under a frequently-re-rendering parent. If you're not certain the compiler is\n> active yet, keep existing manual memoization until you've verified it, then remove it.\n\nDon't reach for `useMemo`, `useCallback`, or `React.memo` by default — the compiler adds\nthis automatically wherever it determines it helps.\n\n```tsx\n// ❌ Old habit — noisy, and a mismatched dependency array is a whole class of bugs\nconst filteredUsers = useMemo(() => users.filter((u) => u.isActive), [users]);\nconst handleClick = useCallback(() => onSelect(user.id), [onSelect, user.id]);\n\n// ✅ New default — just write the logic; the compiler memoizes what's worth memoizing\nconst filteredUsers = users.filter((u) => u.isActive);\nconst handleClick = () => onSelect(user.id);\n```\n\nManual memoization is still justified, narrowly, when:\n\n- You've **confirmed a compiler bail-out** (see §6) on a genuine hot path via profiling,\n and fixing the underlying Rules-of-React violation isn't possible right now.\n- A value must have **stable referential identity across a boundary the compiler can't\n see** — e.g. passed into a non-React library, a WebSocket subscription, or a\n third-party hook incompatible with the compiler (`react-hook-form`'s `useForm`,\n `@tanstack/react-table`'s `useReactTable` are known cases).\n- Keep any manual memoization it produces isolated and commented with _why_, so it\n doesn't silently rot into a bail-out later when the code around it changes.\n\n## 2. The Rules of React are now load-bearing\n\nThe compiler assumes your components and hooks are pure. Violating these rules doesn't\njust risk a subtle bug anymore — it causes the compiler to silently skip optimizing that\ncomponent:\n\n- **Idempotent renders** — given the same props/state/context, a component must return\n the same output. No random values, no `Date.now()`, no side effects during render.\n- **Immutability** — never mutate props, state, or context directly. Always create new\n objects/arrays for changes.\n- **Side effects only in effects or event handlers** — never during render.\n- **Hooks called unconditionally, top-level, same order every render** — no hooks inside\n conditionals, loops, or nested functions.\n\n```tsx\n// ❌ Mutates a prop — breaks purity and the compiler can't safely memoize this\nfunction TodoList({ todos }: { todos: Todo[] }) {\n todos.sort((a, b) => a.priority - b.priority); // mutates caller's array\n return (\n <ul>\n {todos.map((t) => (\n <li key={t.id}>{t.title}</li>\n ))}\n </ul>\n );\n}\n\n// ✅ Creates a new array — pure, compiler-safe\nfunction TodoList({ todos }: { todos: Todo[] }) {\n const sorted = [...todos].sort((a, b) => a.priority - b.priority);\n return (\n <ul>\n {sorted.map((t) => (\n <li key={t.id}>{t.title}</li>\n ))}\n </ul>\n );\n}\n```\n\n## 3. Naming conventions the compiler relies on\n\nThe compiler identifies what to optimize by naming heuristics, same as the Rules of\nHooks linter:\n\n| Kind | Convention | Notes |\n| ------------------------------------------------------------------------ | ------------------------------- | ----------------------------------------------------------------------------- |\n| Components | `PascalCase`, returns JSX | Compiler treats it as a component to optimize |\n| Custom hooks | `camelCase`, prefixed `use` | Required for both Rules-of-Hooks lint and compiler analysis |\n| Plain helper functions that return JSX-like values but aren't components | Avoid `PascalCase`/`use` naming | Prevents the compiler (and other devs) from mistaking it for a component/hook |\n\n## 4. Typing React 19 primitives\n\n**`ref` as a normal prop** — `forwardRef` is no longer required for most cases; function\ncomponents can accept `ref` directly.\n\n```tsx\ntype InputProps = {\n ref?: React.Ref<HTMLInputElement>;\n placeholder?: string;\n};\n\nfunction TextInput({ ref, placeholder }: InputProps) {\n return <input ref={ref} placeholder={placeholder} />;\n}\n```\n\n**Actions with `useActionState`** — type the state and payload as generics; model the\nresult as a discriminated union (per the base typing skill) rather than optional fields.\n\n```tsx\ntype FormState = { status: 'idle' } | { status: 'error'; message: string } | { status: 'success' };\n\nconst [state, formAction, isPending] = useActionState<FormState, FormData>(\n async (_previous, formData) => {\n const email = formData.get('email');\n if (typeof email !== 'string' || !email.includes('@')) {\n return { status: 'error', message: 'Invalid email' };\n }\n await submit(email);\n return { status: 'success' };\n },\n { status: 'idle' },\n);\n```\n\n**Optimistic updates with `useOptimistic`** — type both the state and the update shape.\n\n```tsx\nconst [optimisticTodos, addOptimisticTodo] = useOptimistic<Todo[], Todo>(\n todos,\n (state, newTodo) => [...state, newTodo],\n);\n```\n\n**Reading a promise or context with `use()`** — type the resolved value, not the\npromise wrapper; `use()` is not a hook and may be called conditionally.\n\n```tsx\nfunction Comments({ commentsPromise }: { commentsPromise: Promise<Comment[]> }) {\n const comments = use(commentsPromise); // suspends until resolved\n return (\n <ul>\n {comments.map((c) => (\n <li key={c.id}>{c.text}</li>\n ))}\n </ul>\n );\n}\n```\n\n**Stable event callbacks with `useEffectEvent`** (React 19.2+) — separates \"event\"\nlogic from \"reactive\" effect logic so the callback always sees the latest props/state\nwithout being listed as an effect dependency. Needs `eslint-plugin-react-hooks@6+` to\nlint correctly.\n\n```tsx\nconst onVisit = useEffectEvent((url: string) => {\n logVisit(url, theme); // always fresh `theme`, never re-triggers the effect\n});\n\nuseEffect(() => {\n onVisit(url);\n}, [url]); // `theme` intentionally omitted — onVisit is stable\n```\n\n## 5. Compiler-friendly render patterns\n\n- Creating new object/array/function literals inline in render (`style={{ color }}`,\n `onClick={() => ...}`) is fine — stop manually hoisting or `useMemo`-wrapping these\n preemptively; the compiler memoizes them if it determines it's worthwhile.\n- Avoid module-level mutable variables read or written during render — that state is\n invisible to the compiler and breaks idempotence.\n- Don't use `useRef` to store a value that should trigger a re-render when it changes —\n refs are an imperative escape hatch, not state, and the compiler treats them as such.\n- Keep components small and composable. The compiler optimizes per component/hook\n boundary, so a single 300-line component gives it far less to work with than several\n focused ones.\n\n## 6. Typing props (builds on `typescript-strict-typing`)\n\n- `interface` for a component's `Props` — it's an entity shape, often extended.\n- A discriminated union when a component has mutually exclusive prop combinations,\n instead of a pile of optional props that can contradict each other.\n\n```tsx\n// ❌ Bad — nothing stops passing both `href` and `onClick` incoherently\ninterface ButtonProps {\n label: string;\n href?: string;\n onClick?: () => void;\n}\n\n// ✅ Good — the two variants can't be mixed\ntype ButtonProps =\n | { variant: 'link'; label: string; href: string }\n | { variant: 'action'; label: string; onClick: () => void };\n```\n\n## 7. Tooling setup\n\n**The compiler is opt-in — no default setup enables it automatically.** Plain\n`@vitejs/plugin-react` (`react()`), plain Next.js, plain Babel/webpack config, etc. do\n**not** run the compiler on their own. Verify it's actually wired up before assuming any\nof the memoization guidance above applies to your build.\n\n```bash\n# Compiler (build-time transform)\nnpm install --save-dev --save-exact babel-plugin-react-compiler@latest\n```\n\n**Lint rules — oxlint.** Oxlint ships a **native, Rust-based** `react/react-compiler`\nrule that runs the same compiler analysis in lint-only mode — same diagnostics as the\nBabel-based ESLint version, no Babel needed for linting. It's experimental and **off by\ndefault**, so it has to be enabled explicitly:\n\n```json\n// .oxlintrc.json\n{\n \"plugins\": [\"react\"],\n \"rules\": {\n \"react/react-compiler\": \"error\"\n }\n}\n```\n\nThis single rule reports two distinct things — both worth fixing, but for different\nreasons:\n\n- **Rules-of-React violations** (conditional hooks, reading a ref during render, mutating\n props) — these are real bugs, independent of the compiler.\n- **Compiler bail-outs** — places the compiler declined to optimize (e.g. unsupported\n syntax) without a rule violation. Not incorrect code, just a missed optimization —\n lower priority than a violation, but worth knowing about on a hot path.\n\nIf you'd rather use an existing ESLint plugin's rules through oxlint instead of the\nnative one (e.g. to match a team convention), oxlint's `jsPlugins` can load\n`eslint-plugin-react-hooks` directly — slower than the native rule since it still runs\nthrough Babel, but useful if you need a rule the native port doesn't cover yet:\n\n```json\n{\n \"jsPlugins\": [{ \"name\": \"react-hooks-js\", \"specifier\": \"eslint-plugin-react-hooks\" }],\n \"rules\": { \"react-hooks-js/set-state-in-render\": \"error\" }\n}\n```\n\n**Lint rules — ESLint** (if not on oxlint): the same rules ship inside\n`eslint-plugin-react-hooks`.\n\n```bash\nnpm install --save-dev eslint-plugin-react-hooks@latest\n```\n\n```js\n// eslint.config.js\nimport reactHooks from 'eslint-plugin-react-hooks';\nimport { defineConfig } from 'eslint/config';\n\nexport default defineConfig([reactHooks.configs.flat.recommended]);\n```\n\n**Wiring it into Vite 8.** `@vitejs/plugin-react` v6+ (the version that ships with Vite 8) switched its default transform from Babel to oxc for speed, so the compiler is\n**never** on by default and the old `react({ babel: {...} })` option **does not work**\non this setup — it's silently ignored, not an error, which is an easy way to think the\ncompiler is running when it isn't. Wire it in explicitly, as a separate Babel pass that\nruns before `react()`:\n\n```js\n// vite.config.js\nimport { defineConfig } from 'vite';\nimport react, { reactCompilerPreset } from '@vitejs/plugin-react';\nimport babel from '@rolldown/plugin-babel';\n\nexport default defineConfig({\n plugins: [\n babel({ presets: [reactCompilerPreset()] }), // must run before react()\n react(),\n ],\n});\n```\n\n```bash\nnpm install --save-dev @rolldown/plugin-babel @babel/core babel-plugin-react-compiler\nnpm install --save-dev @types/babel__core # if using TypeScript\n```\n\n`reactCompilerPreset()` is a helper exported from `@vitejs/plugin-react` itself — it\nbundles `babel-plugin-react-compiler` with sane default include/exclude filters so you\ndon't have to hand-roll a Babel preset. It optionally accepts:\n\n- `compilationMode: 'annotation'` — only compile components explicitly marked with a\n `\"use memo\"` directive, instead of the whole codebase (useful for a gradual rollout).\n- `target: '17' | '18'` — if any part of the app still runs on an older React major and\n needs the `react-compiler-runtime` package instead of `react/compiler-runtime`.\n\nAfter adding this, confirm it's actually active via the React DevTools \"Memo ✨\" badge\n(§8) before trusting the \"don't hand-roll memoization\" guidance in §1 — a silently\nmisconfigured Babel order (`react()` before `babel()`) is a common way for this to look\nwired up but do nothing.\n\n- Treat compiler-related lint errors (Rules-of-React violations, mismatched manual\n memoization) as must-fix, not optional — an unfixed violation means that component\n silently gets **zero** compiler optimization.\n- For a large existing codebase, adopt incrementally by scoping the babel plugin to a\n directory (e.g. a UI component library) before enabling it globally.\n- If a specific function is genuinely incompatible with the compiler (e.g. it calls\n `useForm` from `react-hook-form`), opt it out with the `\"use no memo\"` directive as\n the **first line of the function body** — it's a temporary escape hatch, not a\n permanent fix, so leave a comment explaining why.\n\n```tsx\nfunction LegacyForm() {\n 'use no memo';\n const form = useForm(); // incompatible with the compiler today\n // ...\n}\n```\n\n## 8. Checking whether the compiler is actually optimizing\n\n- **React DevTools** — an optimized component shows a \"Memo ✨\" badge next to its name\n in the component tree.\n- **ESLint** — the compiler's recommended rules flag Rules-of-React violations at lint\n time, before they ever become a silent runtime bail-out.\n- A bail-out is not a crash — it just means that specific component/hook is running\n unoptimized. Treat a missing \"Memo ✨\" badge on a component you expect to be optimized\n as a signal to check for a Rules-of-React violation, not a compiler bug.\n\n---\n\n## Review checklist\n\n- [ ] Compiler confirmed active (\"Memo ✨\" badge) before removing any _existing_ manual\n memoization — don't strip it on faith\n- [ ] No new `useMemo`/`useCallback`/`React.memo` added without a documented reason\n (confirmed bail-out, or a boundary the compiler can't see through)\n- [ ] No prop/state/context mutation anywhere in render\n- [ ] All hooks called unconditionally at the top level, same order every render\n- [ ] Side effects live in `useEffect`/event handlers, never during render\n- [ ] Components are `PascalCase`; hooks are `camelCase` and prefixed `use`\n- [ ] `ref` accepted as a normal prop instead of `forwardRef`, unless targeting a version\n that requires it\n- [ ] Action/optimistic-update state modeled as a discriminated union, not optional\n fields\n- [ ] Mutually exclusive prop combinations modeled as a discriminated union `Props` type\n- [ ] `eslint-plugin-react-hooks` recommended config enabled and passing\n- [ ] Any `\"use no memo\"` usage has a comment explaining why\n\n## Quick reference\n\n| Situation | Do |\n| -------------------------------------------------------------- | ------------------------------------------------------------- |\n| Tempted to write `useMemo`/`useCallback` | Don't — write the plain expression, let the compiler decide |\n| Need a ref on a function component | Accept `ref` as a prop, skip `forwardRef` |\n| Form/async state with distinct outcomes | Discriminated union via `useActionState`, not optional fields |\n| Callback needs latest props/state without re-running an effect | `useEffectEvent` |\n| A hook/library is known-incompatible with the compiler | `\"use no memo\"` at the top of that function, with a comment |\n| Checking if optimization is happening | React DevTools \"Memo ✨\" badge + compiler ESLint rules |\n";
22
+ //#endregion
23
+ //#region skills/typescript-strict-typing/SKILL.md?raw
24
+ var SKILL_default$1 = "---\nname: typescript-strict-typing\ndescription: Enforce strict TypeScript typing discipline and naming conventions whenever writing, generating, reviewing, or refactoring TypeScript/TSX code. Use this any time code contains `any`, loose/implicit types, untyped catch blocks, unchecked type assertions, boolean-flag state instead of variants, or inconsistent naming — even if the user didn't explicitly ask for a \"strict\" pass. Governs `any` vs `unknown`, narrowing, discriminated unions, `interface` vs `type` usage, naming conventions, and tsconfig strictness baseline.\n---\n\n# TypeScript Strict Typing Enforcer\n\n## Why this matters\n\nTypeScript's type system is only as strong as its weakest escape hatch. A single `any`,\nan un-narrowed `unknown`, or a lazy `as` assertion silently turns off the compiler for\neverything downstream of it — the bug doesn't disappear, it just moves to runtime where\nit's more expensive to find. The goal of this skill is not \"add types for the sake of\nit,\" it's **make illegal states unrepresentable** and **make the compiler prove\ncorrectness wherever possible**, so bugs surface at build time instead of in production.\n\nApply these rules by default whenever writing or editing TypeScript, without waiting for\nthe user to ask for \"strict mode\" explicitly. If a rule would need to be broken (e.g. a\nthird-party type is genuinely untyped), say so explicitly and isolate the escape hatch\nrather than letting it leak.\n\n## Core principle\n\n> Narrow, don't cast. Model states, don't flag them. Let the compiler do the checking.\n\n---\n\n## 1. Never use `any`\n\n`any` is not \"unknown type,\" it's \"type checking off.\" It's contagious — once a value is\n`any`, everything it touches becomes unchecked too.\n\n- Never write `any` for parameters, return types, variables, or generics.\n- Use `unknown` for genuinely unknown external data (API responses, `JSON.parse`, catch\n clauses, third-party callbacks) and narrow it before use.\n- Use generics (`<T>`) when a function needs to work across types but preserve the\n relationship between input and output.\n- If a library ships untyped, write a minimal local type/interface for the surface area\n you actually use instead of reaching for `any`.\n\n```ts\n// ❌ Bad\nfunction parseConfig(json: any) {\n return json.settings.theme; // no safety, no autocomplete, silent runtime crash\n}\n\n// ✅ Good\nfunction parseConfig(json: unknown): string {\n if (\n typeof json === 'object' &&\n json !== null &&\n 'settings' in json &&\n typeof (json as { settings: unknown }).settings === 'object'\n ) {\n // still narrow further or validate with a schema library (zod, valibot, etc.)\n }\n throw new Error('Invalid config shape');\n}\n```\n\nThe only acceptable `any` is a well-justified, isolated, and commented one (e.g.\ninterfacing with a genuinely untyped legacy module) — never a default.\n\n## 2. `unknown` + narrowing, not casting\n\nPrefer proving a type through control flow over asserting it with `as`.\n\n**Narrowing techniques, in order of preference:**\n\n1. **`typeof`** — primitives (`string`, `number`, `boolean`, `undefined`, `function`)\n2. **`instanceof`** — class instances, `Error`, `Date`, custom classes\n3. **`in`** — checking a property exists before accessing it on a union/unknown\n4. **User-defined type guards** — `function isUser(x: unknown): x is User`\n5. **Discriminated union tag checks** — `switch (value.kind) { ... }` (see §3)\n6. **Exhaustiveness checks** — a `never`-typed default branch so adding a new variant is\n a compile error until every switch/if-chain handles it\n\n```ts\n// ✅ Type guard\nfunction isUser(value: unknown): value is User {\n return typeof value === 'object' && value !== null && 'id' in value && 'email' in value;\n}\n\n// ✅ Exhaustiveness check\nfunction assertNever(x: never): never {\n throw new Error(`Unhandled case: ${JSON.stringify(x)}`);\n}\n\nfunction area(shape: Shape): number {\n switch (shape.kind) {\n case 'circle':\n return Math.PI * shape.radius ** 2;\n case 'square':\n return shape.side ** 2;\n default:\n return assertNever(shape); // compile error if a variant is missed\n }\n}\n```\n\nType assertions (`as X`) and the non-null assertion (`!`) bypass this entirely — treat\nthem as a last resort (see §7), not a shortcut.\n\n## 3. Discriminated unions for variant state\n\nWhenever a value can be one of several distinct \"shapes\" (loading/success/error states,\nevent types, API response variants), model it as a **discriminated union** with a\nliteral tag field — never as a loose object with optional fields or boolean flags.\n\n```ts\n// ❌ Bad — booleans can contradict each other; unclear which fields are valid together\ninterface FetchState {\n isLoading: boolean;\n isError: boolean;\n data?: User;\n error?: string;\n}\n\n// ✅ Good — only one shape is possible at a time, and the compiler enforces it\ntype FetchState =\n | { status: 'idle' }\n | { status: 'loading' }\n | { status: 'success'; data: User }\n | { status: 'error'; error: string };\n\nfunction render(state: FetchState) {\n switch (state.status) {\n case 'success':\n return state.data.name; // `data` is guaranteed to exist here\n case 'error':\n return state.error; // `error` is guaranteed to exist here\n default:\n return null;\n }\n}\n```\n\nUse a consistent tag field name across a codebase (`kind`, `type`, or `status` — pick\none and stick with it) so narrowing patterns stay predictable.\n\n## 4. `interface` vs `type` — pick by intent, not habit\n\nBoth can describe object shapes, but they signal different intent. Default rule:\n\n| Use `interface` for... | Use `type` for... |\n| -------------------------------------------------------------------------- | -------------------------------------------------------------------------- |\n| Object / entity shapes (a `User`, a `Product`, a component's `Props`) | Unions (`\"a\" \\| \"b\"`) and discriminated unions |\n| Public API contracts meant to be `implements`-ed by classes | Intersections (`A & B`) |\n| Shapes that consumers may want to **extend/augment** (declaration merging) | Tuples (`[string, number]`) |\n| | Function types / callback signatures |\n| | Mapped, conditional, or utility-derived types (`Partial<T>`, `Pick<T, K>`) |\n| | Aliasing a primitive or another type for readability |\n\n```ts\n// ✅ interface — an entity with identity, extendable\ninterface User {\n id: string;\n email: string;\n role: UserRole;\n}\n\ninterface AdminUser extends User {\n permissions: Permission[];\n}\n\n// ✅ type — union, alias, derived shape\ntype UserRole = 'admin' | 'editor' | 'viewer';\ntype UserId = User['id'];\ntype PartialUser = Partial<User>;\ntype Callback<T> = (value: T) => void;\n```\n\nDon't mix conventions arbitrarily within one file — if a shape is a plain data object\nthat will never need a union/intersection, `interface` is the default; the moment it\nneeds to express \"one of several shapes,\" reach for `type`.\n\n## 5. Naming conventions\n\n| Kind | Convention | Example |\n| ---------------------------------------------------------- | ------------------------------------------- | ----------------------------------- |\n| Types, interfaces, classes, enums | `PascalCase` | `UserProfile`, `OrderStatus` |\n| Interfaces | `PascalCase`, **no `I` prefix** | `User`, not `IUser` |\n| Type aliases | `PascalCase` | `type ApiResponse<T> = ...` |\n| Variables, functions, methods, properties | `camelCase` | `getUserById`, `isValid` |\n| Booleans | `camelCase` with `is/has/should/can` prefix | `isLoading`, `hasPermission` |\n| True constants (module-level, never reassigned, primitive) | `UPPER_SNAKE_CASE` | `MAX_RETRIES`, `DEFAULT_TIMEOUT_MS` |\n| Enum members | `PascalCase` | `enum Status { Active, Archived }` |\n| Generic type parameters (simple, single-purpose) | Single uppercase letter | `T`, `K`, `V`, `E` for errors |\n| Generic type parameters (multiple / non-obvious) | Descriptive, prefixed with `T` | `TInput`, `TOutput`, `TContext` |\n| Discriminated union tag field | Consistent across the codebase | `kind`, `type`, or `status` |\n| Files with a single exported entity | Match the entity name | `UserProfile.ts`, `useAuth.ts` |\n\nNaming should describe **intent**, not implementation — `fetchUser` not\n`getUserFromApiEndpoint`; `retryCount` not `numRetries2`.\n\n## 6. Baseline `tsconfig.json` strictness\n\nTreat these as the non-negotiable floor for any project this skill touches:\n\n```json\n{\n \"compilerOptions\": {\n \"strict\": true,\n \"noImplicitAny\": true,\n \"strictNullChecks\": true,\n \"strictFunctionTypes\": true,\n \"strictPropertyInitialization\": true,\n \"noUncheckedIndexedAccess\": true,\n \"exactOptionalPropertyTypes\": true,\n \"noImplicitOverride\": true,\n \"noFallthroughCasesInSwitch\": true,\n \"noUnusedLocals\": true,\n \"noUnusedParameters\": true,\n \"forceConsistentCasingInFileNames\": true\n }\n}\n```\n\n`strict: true` alone enables the core group (`noImplicitAny`, `strictNullChecks`, etc.),\nbut `noUncheckedIndexedAccess` and `exactOptionalPropertyTypes` are commonly missed and\nclose real gaps (array/object index access returning `T` instead of `T | undefined`;\noptional properties silently accepting `undefined` as an explicit value).\n\n## 7. Type assertions and non-null assertions are a last resort\n\n- `as X` and `x!` tell the compiler \"trust me\" — they produce zero runtime safety and\n actively hide bugs if wrong.\n- Acceptable only when the compiler genuinely cannot know something you do (e.g. a DOM\n query you've already null-checked, or narrowing a third-party type at a well-tested\n boundary) — and even then, prefer a type guard or a runtime check over a bare\n assertion.\n- Never use `as any` or `as unknown as X` to force an incompatible cast — that's `any`\n wearing a disguise.\n- `x!` should almost always be replaceable by an actual null check or optional chaining\n (`x?.y`) plus a real fallback.\n\n## 8. Readonly by default\n\nPrefer immutable shapes unless mutation is intentional and localized.\n\n```ts\ninterface Point {\n readonly x: number;\n readonly y: number;\n}\n\nfunction config(values: readonly string[]) {\n /* ... */\n}\n\nconst ROLES = ['admin', 'editor', 'viewer'] as const;\ntype UserRole = (typeof ROLES)[number];\n```\n\n## 9. Explicit return types on exported/public functions\n\nInference is fine for local, private helpers, but exported functions, class methods, and\nanything forming a public API should declare an explicit return type. This prevents an\ninternal implementation change from silently widening/narrowing the public contract.\n\n```ts\n// ❌ Return type is inferred and can silently drift\nexport function getActiveUsers(users: User[]) {\n return users.filter((u) => u.active);\n}\n\n// ✅ Explicit, intentional contract\nexport function getActiveUsers(users: User[]): User[] {\n return users.filter((u) => u.active);\n}\n```\n\n## 10. Prefer literal unions over numeric enums\n\nString literal unions are simpler, tree-shake better, and produce clearer error\nmessages than TypeScript `enum`. Reserve `enum` (or `as const` object maps) for cases\nthat need reverse lookup or genuinely benefit from a namespaced runtime value.\n\n```ts\n// ✅ Preferred\ntype OrderStatus = 'pending' | 'shipped' | 'delivered' | 'cancelled';\n\n// Acceptable when a namespaced runtime object is actually needed\nconst OrderStatus = {\n Pending: 'pending',\n Shipped: 'shipped',\n} as const;\ntype OrderStatus = (typeof OrderStatus)[keyof typeof OrderStatus];\n```\n\n---\n\n## Review checklist\n\nBefore considering TypeScript code \"done,\" verify:\n\n- [ ] No `any` anywhere (including implicit `any` from missing annotations)\n- [ ] External/uncertain data enters as `unknown` and is narrowed before use\n- [ ] Variant state is a discriminated union, not optional fields + booleans\n- [ ] `interface` used for object/entity shapes; `type` used for unions/aliases/intersections\n- [ ] No stray `I` prefixes on interfaces\n- [ ] Naming follows the casing table in §5 consistently\n- [ ] `as` / `!` are rare, justified, and can't be replaced by a guard or null check\n- [ ] Exported functions/methods have explicit return types\n- [ ] Switch statements over unions have an exhaustiveness (`never`) check\n- [ ] `tsconfig.json` includes the strictness baseline in §6\n\n## Quick reference\n\n| Situation | Use |\n| ---------------------------------------------- | ------------------------------------------------------------- |\n| External/uncertain data | `unknown` + narrowing |\n| \"This value is definitely one of these shapes\" | Discriminated union (`type`) |\n| Object with identity, may be extended | `interface` |\n| Union, intersection, tuple, mapped type | `type` |\n| Need to prove a type through logic | Type guard / narrowing |\n| Tempted to write `any` | Stop — use `unknown`, a generic, or a local interface instead |\n";
25
+ //#endregion
26
+ //#region skills/wangs-ui-components/SKILL.md?raw
27
+ var SKILL_default = "---\nname: wangs-ui-components\ndescription: Foundational rules, subpath imports, design tokens, and the MCP Discovery Protocol for building React apps with Wangs UI.\n---\n\n# Skill: Wangs UI Component Fundamentals & MCP Protocol\n\nUse this skill whenever you write or modify UI components using Wangs UI (`@wangs-ui/react-core`, `@wangs-ui/react-icons`, `@wangs-ui/react-presets`, `@wangs-ui/foundation`).\n\n---\n\n## 1. The MCP Discovery Protocol (Mandatory Single Source of Truth)\n\nDo **NOT** guess component props, Pass-Through (`pt`) slots, or event names. Always query the MCP server dynamically to retrieve the current API signatures and live story implementations:\n\n```mermaid\ngraph TD\n A[Identify Component Needed] --> B[Call get-documentation id]\n B --> C{Need live story / variant code?}\n C -->|Yes| D[Call get-documentation-for-story]\n C -->|No| E[Check Graphify: query_graph]\n D --> E\n E --> F[Implement Component with Subpath Imports]\n```\n\n### Discovery Steps:\n\n1. **Inspect Component Contract & Props**:\n ```json\n get-documentation({ \"id\": \"button\" })\n get-documentation({ \"id\": \"input\" })\n get-documentation({ \"id\": \"datatable\" })\n ```\n2. **Inspect Live Usage & Story Variants**:\n ```json\n get-documentation-for-story({ \"id\": \"button\", \"storyName\": \"Default\" })\n get-documentation-for-story({ \"id\": \"datatable\", \"storyName\": \"ServerPagination\" })\n ```\n3. **Inspect Relationships & Real Usages in Graph**:\n ```json\n query_graph({ \"query\": \"DataTable\" })\n query_graph({ \"query\": \"usePT\" })\n ```\n\n---\n\n## 2. Subpath Modular Imports (Mandatory)\n\nAlways import via specific subpaths to guarantee tree-shaking and avoid bundling entire packages:\n\n```tsx\n// Primitives (@wangs-ui/react-core/primitive/*)\nimport Button from '@wangs-ui/react-core/primitive/button';\nimport Input from '@wangs-ui/react-core/primitive/input';\nimport NumberInput from '@wangs-ui/react-core/primitive/numberinput';\nimport Select from '@wangs-ui/react-core/primitive/select';\nimport Badge from '@wangs-ui/react-core/primitive/badge';\nimport Card from '@wangs-ui/react-core/primitive/card';\nimport DataTable from '@wangs-ui/react-core/primitive/datatable';\n\n// Blocks (@wangs-ui/react-core/blocks/*)\nimport AppLayout from '@wangs-ui/react-core/blocks/applayout';\nimport Sidebar from '@wangs-ui/react-core/blocks/sidebar';\n\n// Providers & System Hooks\nimport { WangsUiProvider } from '@wangs-ui/react-core/api';\nimport { useI18n } from '@wangs-ui/react-i18n';\nimport { useTheme } from '@wangs-ui/foundation/theme';\n\n// Icons (@wangs-ui/react-icons)\nimport { SearchLine, AddLine, DeleteBin6Line, CheckLine } from '@wangs-ui/react-icons';\n```\n\n---\n\n## 3. Strict Primitive Substitution Rule\n\nNever write raw HTML elements when a Wangs UI primitive exists:\n\n| Forbidden Raw HTML | Mandatory Wangs UI Component | Subpath Import | MCP Documentation ID |\n| :------------------------ | :--------------------------- | :------------------------------------------- | :------------------- |\n| `<button>` | `Button` | `@wangs-ui/react-core/primitive/button` | `button` |\n| `<input type=\"text\">` | `Input` | `@wangs-ui/react-core/primitive/input` | `input` |\n| `<input type=\"number\">` | `NumberInput` | `@wangs-ui/react-core/primitive/numberinput` | `numberinput` |\n| `<input type=\"checkbox\">` | `Checkbox` | `@wangs-ui/react-core/primitive/checkbox` | `checkbox` |\n| `<select>` | `Select` | `@wangs-ui/react-core/primitive/select` | `select` |\n| `<dialog>` / modal | `Dialog` / `Modal` | `@wangs-ui/react-core/primitive/dialog` | `dialog`, `modal` |\n| `<table>` | `DataTable` | `@wangs-ui/react-core/primitive/datatable` | `datatable` |\n| Container box | `Card` | `@wangs-ui/react-core/primitive/card` | `card` |\n| Pill badge / status | `Badge` | `@wangs-ui/react-core/primitive/badge` | `badge` |\n\n---\n\n## 4. Typography Scale & 4px Spacing Tokens\n\n### Typography Helper Classes\n\n- `.heading-1` — Page title (22px, 600)\n- `.heading-2` — Section / Card title (18px, 600)\n- `.heading-3` — Sub-header (16px, 500)\n- `.heading-4` — Field label (14px, 500)\n- `.heading-5` — Small group header (12px, 600)\n- `.p` — Body copy (12px, 500)\n\n### 4px Spacing Tokens\n\n- Gap: `gap-xs` (4px), `gap-s` (6px), `gap-md` (8px), `gap-m` (12px), `gap-l` (16px), `gap-xl` (20px), `gap-xxl` (24px)\n- Padding: `p-xs`, `p-s`, `p-md`, `p-m`, `p-l`, `p-xl`, `p-xxl`\n";
28
+ //#endregion
29
+ //#region src/registry.ts
30
+ var __dirname = path.dirname(fileURLToPath(import.meta.url));
31
+ var EMBEDDED_SKILLS_RAW = {
32
+ "create-form": SKILL_default$7,
33
+ "data-table": SKILL_default$6,
34
+ "dialog-modal": SKILL_default$5,
35
+ "i18n-usage": SKILL_default$4,
36
+ "layout-navigation": SKILL_default$3,
37
+ "react19-compiler-typescript": SKILL_default$2,
38
+ "typescript-strict-typing": SKILL_default$1,
39
+ "wangs-ui-components": SKILL_default
40
+ };
41
+ function parseSkillContent(id, content) {
42
+ let name = id;
43
+ let description = "Wangs UI consumer skill";
44
+ const frontmatterMatch = content.match(/^---\s*\n([\s\S]*?)\n---\s*\n/);
45
+ if (frontmatterMatch) {
46
+ const fm = frontmatterMatch[1];
47
+ const nameMatch = fm.match(/^name:\s*(.+)$/m);
48
+ const descMatch = fm.match(/^description:\s*(.+)$/m);
49
+ if (nameMatch) name = nameMatch[1].trim();
50
+ if (descMatch) description = descMatch[1].trim();
51
+ }
52
+ return {
53
+ id,
54
+ name,
55
+ description,
56
+ content
57
+ };
58
+ }
59
+ function loadAllSkills() {
60
+ if (Object.keys(EMBEDDED_SKILLS_RAW).length > 0) return Object.entries(EMBEDDED_SKILLS_RAW).map(([id, content]) => parseSkillContent(id, content));
61
+ const candidates = [
62
+ path.resolve(__dirname, "skills"),
63
+ path.resolve(__dirname, "../skills"),
64
+ path.resolve(__dirname, "../../skills")
65
+ ];
66
+ for (const skillsDir of candidates) if (fs.existsSync(skillsDir)) {
67
+ const entries = fs.readdirSync(skillsDir, { withFileTypes: true });
68
+ const skills = [];
69
+ for (const entry of entries) if (entry.isDirectory()) {
70
+ const skillMdPath = path.join(skillsDir, entry.name, "SKILL.md");
71
+ if (fs.existsSync(skillMdPath)) {
72
+ const content = fs.readFileSync(skillMdPath, "utf-8");
73
+ skills.push(parseSkillContent(entry.name, content));
74
+ }
75
+ }
76
+ if (skills.length > 0) return skills;
77
+ }
78
+ return [];
79
+ }
80
+ function getSkill(id) {
81
+ return loadAllSkills().find((s) => s.id === id || s.name === id);
82
+ }
83
+ //#endregion
84
+ //#region src/detector.ts
85
+ function getAgentSkillDirs(baseDir = process.cwd()) {
86
+ const dirs = [];
87
+ const candidates = [
88
+ path.join(baseDir, ".agents", "skills"),
89
+ path.join(baseDir, ".claude", "skills"),
90
+ path.join(baseDir, ".opencode", "skills"),
91
+ path.join(baseDir, ".kilo", "skills")
92
+ ];
93
+ for (const c of candidates) if (fs.existsSync(c) || fs.existsSync(path.dirname(c))) dirs.push(c);
94
+ if (dirs.length === 0) dirs.push(path.join(baseDir, ".agents", "skills"));
95
+ return dirs;
96
+ }
97
+ function isSkillInstalled(skillId, baseDir = process.cwd()) {
98
+ const dirs = getAgentSkillDirs(baseDir);
99
+ for (const d of dirs) {
100
+ const skillPath = path.join(d, skillId, "SKILL.md");
101
+ if (fs.existsSync(skillPath)) return true;
102
+ }
103
+ return false;
104
+ }
105
+ function getInstalledSkills(baseDir = process.cwd()) {
106
+ const dirs = getAgentSkillDirs(baseDir);
107
+ const installed = /* @__PURE__ */ new Set();
108
+ for (const d of dirs) if (fs.existsSync(d)) {
109
+ const entries = fs.readdirSync(d, { withFileTypes: true });
110
+ for (const entry of entries) if (entry.isDirectory()) {
111
+ const skillMd = path.join(d, entry.name, "SKILL.md");
112
+ if (fs.existsSync(skillMd)) installed.add(entry.name);
113
+ }
114
+ }
115
+ return Array.from(installed);
116
+ }
117
+ function installSkill(skill, baseDir = process.cwd()) {
118
+ const targetDirs = getAgentSkillDirs(baseDir);
119
+ const writtenPaths = [];
120
+ for (const baseSkillDir of targetDirs) {
121
+ const destDir = path.join(baseSkillDir, skill.id);
122
+ fs.mkdirSync(destDir, { recursive: true });
123
+ const destFile = path.join(destDir, "SKILL.md");
124
+ fs.writeFileSync(destFile, skill.content, "utf-8");
125
+ writtenPaths.push(destFile);
126
+ }
127
+ return writtenPaths;
128
+ }
129
+ function removeSkill(skillId, baseDir = process.cwd()) {
130
+ const targetDirs = getAgentSkillDirs(baseDir);
131
+ const removedPaths = [];
132
+ for (const baseSkillDir of targetDirs) {
133
+ const destDir = path.join(baseSkillDir, skillId);
134
+ if (fs.existsSync(destDir)) {
135
+ fs.rmSync(destDir, {
136
+ recursive: true,
137
+ force: true
138
+ });
139
+ removedPaths.push(destDir);
140
+ }
141
+ }
142
+ return removedPaths;
143
+ }
144
+ //#endregion
145
+ //#region src/commands/list.ts
146
+ function listSkills(baseDir = process.cwd()) {
147
+ intro(`\x1b[1m\x1b[36m📦 Wangs UI Consumer Skills Registry\x1b[0m (v1.0.1)`);
148
+ const allSkills = loadAllSkills();
149
+ const targetDirs = getAgentSkillDirs(baseDir);
150
+ if (allSkills.length === 0) {
151
+ console.log("No skills found in registry.");
152
+ outro("Done.");
153
+ return;
154
+ }
155
+ console.log(`\nAgent directories: \x1b[2m${targetDirs.join(", ")}\x1b[0m\n`);
156
+ for (const skill of allSkills) {
157
+ const statusBadge = isSkillInstalled(skill.id, baseDir) ? "\x1B[32m[Installed]\x1B[0m" : "\x1B[90m[Available]\x1B[0m";
158
+ console.log(` ${statusBadge} \x1b[1m${skill.id}\x1b[0m`);
159
+ console.log(` \x1b[90m${skill.description}\x1b[0m\n`);
160
+ }
161
+ outro(`Total skills: ${allSkills.length} | Run \x1b[36mnpx @wangs-ui/skills add <skill-name>\x1b[0m to install.`);
162
+ }
163
+ //#endregion
164
+ //#region src/commands/add.ts
165
+ async function addSkills(skillIds, baseDir = process.cwd()) {
166
+ intro("\x1B[1m\x1B[36m➕ Install Wangs UI Consumer Skills\x1B[0m");
167
+ const allSkills = loadAllSkills();
168
+ let targetIds = skillIds.filter(Boolean);
169
+ if (targetIds.length === 0) {
170
+ const selected = await multiselect({
171
+ message: "Select Wangs UI skills to install into your agent environment:",
172
+ options: allSkills.map((s) => ({
173
+ value: s.id,
174
+ label: s.id,
175
+ hint: s.description
176
+ })),
177
+ required: true
178
+ });
179
+ if (isCancel(selected)) {
180
+ cancel("Operation cancelled.");
181
+ return;
182
+ }
183
+ targetIds = selected;
184
+ }
185
+ const installedList = [];
186
+ for (const id of targetIds) {
187
+ const skill = getSkill(id);
188
+ if (!skill) {
189
+ console.log(`\x1b[33m⚠️ Skill "${id}" not found in registry. Run "list" to view available skills.\x1b[0m`);
190
+ continue;
191
+ }
192
+ const paths = installSkill(skill, baseDir);
193
+ installedList.push(skill.id);
194
+ for (const p of paths) console.log(` \x1b[32m✔\x1b[0m Installed \x1b[1m${skill.id}\x1b[0m -> \x1b[2m${p}\x1b[0m`);
195
+ }
196
+ if (installedList.length > 0) outro(`\x1b[32mSuccessfully installed ${installedList.length} skill(s)!\x1b[0m`);
197
+ else outro("No skills were installed.");
198
+ }
199
+ //#endregion
200
+ //#region src/commands/update.ts
201
+ function updateSkills(skillIds = [], baseDir = process.cwd()) {
202
+ intro("\x1B[1m\x1B[36m🔄 Update Wangs UI Consumer Skills\x1B[0m");
203
+ let targets = skillIds.filter(Boolean);
204
+ if (targets.length === 0) targets = getInstalledSkills(baseDir);
205
+ if (targets.length === 0) {
206
+ console.log("No installed skills found in project to update.");
207
+ outro("Done.");
208
+ return;
209
+ }
210
+ const updatedList = [];
211
+ for (const id of targets) {
212
+ const skill = getSkill(id);
213
+ if (!skill) {
214
+ console.log(`\x1b[33m⚠️ Skill "${id}" not found in current registry.\x1b[0m`);
215
+ continue;
216
+ }
217
+ const paths = installSkill(skill, baseDir);
218
+ updatedList.push(skill.id);
219
+ for (const p of paths) console.log(` \x1b[32m✔\x1b[0m Updated \x1b[1m${skill.id}\x1b[0m -> \x1b[2m${p}\x1b[0m`);
220
+ }
221
+ outro(`\x1b[32mSuccessfully updated ${updatedList.length} skill(s)!\x1b[0m`);
222
+ }
223
+ //#endregion
224
+ //#region src/commands/remove.ts
225
+ function removeSkills(skillIds, baseDir = process.cwd()) {
226
+ intro("\x1B[1m\x1B[31m🗑️ Remove Wangs UI Consumer Skills\x1B[0m");
227
+ const targets = skillIds.filter(Boolean);
228
+ if (targets.length === 0) {
229
+ console.log("Please specify skill name(s) to remove.");
230
+ outro("Aborted.");
231
+ return;
232
+ }
233
+ const removedList = [];
234
+ for (const id of targets) {
235
+ const paths = removeSkill(id, baseDir);
236
+ if (paths.length > 0) {
237
+ removedList.push(id);
238
+ for (const p of paths) console.log(` \x1b[31m✔\x1b[0m Removed \x1b[1m${id}\x1b[0m from \x1b[2m${p}\x1b[0m`);
239
+ } else console.log(` \x1b[90m- Skill "${id}" was not installed.\x1b[0m`);
240
+ }
241
+ outro(`\x1b[32mCompleted. Removed ${removedList.length} skill(s).\x1b[0m`);
242
+ }
243
+ //#endregion
244
+ export { getAgentSkillDirs as a, isSkillInstalled as c, loadAllSkills as d, listSkills as i, removeSkill as l, updateSkills as n, getInstalledSkills as o, addSkills as r, installSkill as s, removeSkills as t, getSkill as u };
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@wangs-ui/skills",
3
+ "version": "1.0.1",
4
+ "description": "CLI to install, update, and manage modular AI agent skills for Wangs UI React applications",
5
+ "keywords": [
6
+ "agents",
7
+ "ai",
8
+ "antigravity",
9
+ "claude-code",
10
+ "cli",
11
+ "cursor",
12
+ "kilo",
13
+ "mcp",
14
+ "opencode",
15
+ "skills",
16
+ "wangs-ui"
17
+ ],
18
+ "homepage": "https://github.com/fewangsit/wangs-ui-react",
19
+ "license": "MIT",
20
+ "author": "Wangsit FE Developer",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/fewangsit/wangs-ui-react.git",
24
+ "directory": "packages/skills"
25
+ },
26
+ "bin": {
27
+ "skills": "dist/bin.js",
28
+ "wangs-ui-skills": "dist/bin.js"
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "skills"
33
+ ],
34
+ "type": "module",
35
+ "sideEffects": false,
36
+ "main": "./dist/index.js",
37
+ "module": "./dist/index.js",
38
+ "exports": {
39
+ ".": {
40
+ "import": "./dist/index.js",
41
+ "default": "./dist/index.js"
42
+ },
43
+ "./package.json": "./package.json"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public",
47
+ "registry": "https://registry.npmjs.org/"
48
+ },
49
+ "dependencies": {
50
+ "@clack/prompts": "^1.7.0"
51
+ },
52
+ "devDependencies": {},
53
+ "scripts": {
54
+ "build": "vite build",
55
+ "check:publint": "publint",
56
+ "check:attw": "attw --pack ."
57
+ }
58
+ }
@@ -0,0 +1,67 @@
1
+ ---
2
+ name: create-form
3
+ description: Architecture, validation workflows, and MCP discovery protocol for building forms and input controls with @wangs-ui/react-core.
4
+ ---
5
+
6
+ # Skill: Form Architecture & Validation Workflows
7
+
8
+ Use this skill when building forms, data entry panels, settings pages, or multipart forms in Wangs UI applications.
9
+
10
+ ---
11
+
12
+ ## 1. MCP Inspection Protocol (Mandatory Single Source of Truth)
13
+
14
+ Do **NOT** hardcode or guess prop names, field configurations, or validation options. Retrieve active component definitions and live implementation stories directly from MCP:
15
+
16
+ ### Inspect Component & Form Contracts:
17
+
18
+ ```json
19
+ get-documentation({ "id": "form" })
20
+ get-documentation({ "id": "field" })
21
+ get-documentation({ "id": "input" })
22
+ get-documentation({ "id": "numberinput" })
23
+ get-documentation({ "id": "select" })
24
+ get-documentation({ "id": "multiselect" })
25
+ get-documentation({ "id": "datepicker" })
26
+ get-documentation({ "id": "fileupload" })
27
+ ```
28
+
29
+ ### Inspect Live Story Implementations:
30
+
31
+ ```json
32
+ get-documentation-for-story({ "id": "form", "storyName": "Default" })
33
+ get-documentation-for-story({ "id": "field", "storyName": "Default" })
34
+ get-documentation-for-story({ "id": "select", "storyName": "Basic" })
35
+ get-documentation-for-story({ "id": "datepicker", "storyName": "Default" })
36
+ get-documentation-for-story({ "id": "fileupload", "storyName": "Default" })
37
+ ```
38
+
39
+ ### Inspect Knowledge Graph & Usages:
40
+
41
+ ```json
42
+ query_graph({ "query": "useFormControl" })
43
+ query_graph({ "query": "Field" })
44
+ ```
45
+
46
+ ---
47
+
48
+ ## 2. Form Architecture & State Principles
49
+
50
+ 1. **State & Control**:
51
+ - Standard REST payload forms use `useFormControl` with JSON mode.
52
+ - Multipart file upload workflows use `useFormControl` with FormData mode.
53
+ 2. **Field Composition**:
54
+ - Form inputs are wrapped with `<Field>` layout containers for unified label, tooltip, helper text, and error rendering.
55
+ - Exact props, slot rendering functions, and field binding options must be retrieved via MCP (`get-documentation({ "id": "field" })`).
56
+ 3. **Server Validation Error Mapping**:
57
+ - Backend validation responses (e.g. `422 Unprocessable Entity`) are mapped back into the form instance via `formControl.setError()`.
58
+ 4. **Submission Lifecycle**:
59
+ - In-flight network requests should manage loading state on submit actions and prevent accidental reset during mutations.
60
+
61
+ ---
62
+
63
+ ## 3. Mandatory Implementation Rules
64
+
65
+ 1. **Always Query MCP First**: Never guess input props or event signatures; obtain the exact types from `get-documentation`.
66
+ 2. **Strict Subpath Imports**: All components must be imported via their granular subpath (`@wangs-ui/react-core/primitive/*`, `@wangs-ui/form`).
67
+ 3. **Translate All Visible Strings**: Every field label, placeholder, helper text, and error message must be wrapped in `t('...')` from `@wangs-ui/react-i18n`.
@@ -0,0 +1,68 @@
1
+ ---
2
+ name: data-table
3
+ description: Architecture, workflows, and MCP discovery protocol for building DataTables with sorting, pagination, filtering, selection, and export.
4
+ ---
5
+
6
+ # Skill: DataTable Architecture & Integration Workflows
7
+
8
+ Use this skill when implementing data grids, server-paginated tables, filterable listing views, or batch management interfaces with `@wangs-ui/react-core`.
9
+
10
+ ---
11
+
12
+ ## 1. MCP Inspection Protocol (Mandatory Single Source of Truth)
13
+
14
+ Do **NOT** guess table prop names or hardcode table structures. Query the MCP server dynamically to inspect exact TypeScript signatures, live story implementations, and companion controls:
15
+
16
+ ### Inspect Component Contracts:
17
+
18
+ ```json
19
+ get-documentation({ "id": "datatable" })
20
+ get-documentation({ "id": "exportbutton" })
21
+ get-documentation({ "id": "filtercontainer" })
22
+ get-documentation({ "id": "bulkactionbutton" })
23
+ ```
24
+
25
+ ### Inspect Live Story Implementations:
26
+
27
+ ```json
28
+ get-documentation-for-story({ "id": "datatable", "storyName": "Basic" })
29
+ get-documentation-for-story({ "id": "datatable", "storyName": "ServerPagination" })
30
+ get-documentation-for-story({ "id": "datatable", "storyName": "Sortable" })
31
+ get-documentation-for-story({ "id": "datatable", "storyName": "MultipleSelection" })
32
+ get-documentation-for-story({ "id": "datatable", "storyName": "CustomColumn" })
33
+ get-documentation-for-story({ "id": "exportbutton", "storyName": "WithTable" })
34
+ ```
35
+
36
+ ### Inspect Knowledge Graph & Usages:
37
+
38
+ ```json
39
+ query_graph({ "query": "DataTable" })
40
+ query_graph({ "query": "useDataTableFetch" })
41
+ ```
42
+
43
+ ---
44
+
45
+ ## 2. Core Architecture & Mental Model
46
+
47
+ The Wangs UI `DataTable` is built on a modular, headless-first architecture:
48
+
49
+ 1. **Declarative Column Definitions (`TableColumn<T>[]`)**:
50
+ Columns are configured as typed array objects, not as JSX children. Check `get-documentation({ "id": "datatable" })` for column field types.
51
+ 2. **Table Instance Hook (`useDataTable`)**:
52
+ Coordinates table state (sorting, pagination, selection, column ordering, pinning, visibility).
53
+ 3. **Data Fetching Hook (`useDataTableFetch`)**:
54
+ Feeds server-side data, handles loading indicators, manages query parameters (`search`, `filter`, `sort`, `page`, `limit`), and debounces requests automatically.
55
+ 4. **Ecosystem Companions**:
56
+ - `FilterContainer` & `FilterToggleButton`: Filter popovers and faceted search.
57
+ - `ExportButton`: Client/server export to Excel, CSV, PDF, or Print.
58
+ - `BulkActionButton`: Contextual batch actions triggered when rows are selected.
59
+ - `CustomColumn`: User-controlled column ordering, visibility toggling, and pinning.
60
+
61
+ ---
62
+
63
+ ## 3. Mandatory Implementation Rules
64
+
65
+ 1. **Query MCP for Current Code Patterns**: Always run `get-documentation-for-story` for `datatable` before drafting code.
66
+ 2. **Strict Subpath Imports**: Import via `@wangs-ui/react-core/primitive/datatable` and companion primitive paths.
67
+ 3. **Always Translate Visible Copy**: All column header labels, empty state messages, and action button labels must be wrapped in `t('...')` from `@wangs-ui/react-i18n`.
68
+ 4. **Stable Row Identity**: Always configure a unique key identifier for stable selection and row identity.
@@ -0,0 +1,58 @@
1
+ ---
2
+ name: dialog-modal
3
+ description: Patterns, overlay selection criteria, and MCP discovery protocol for Dialog, Modal, and DialogForm components in Wangs UI.
4
+ ---
5
+
6
+ # Skill: Dialog, Modal & Overlay Workflows
7
+
8
+ Use this skill when building interactive modals, create/edit dialog forms, destructive action confirmations, or slide-in overlay panels.
9
+
10
+ ---
11
+
12
+ ## 1. MCP Inspection Protocol (Mandatory Single Source of Truth)
13
+
14
+ Do **NOT** guess overlay props, event names, or footer slots. Query the MCP server dynamically to inspect exact contracts and live story implementations:
15
+
16
+ ### Inspect Overlay Contracts:
17
+
18
+ ```json
19
+ get-documentation({ "id": "dialog" })
20
+ get-documentation({ "id": "dialogform" })
21
+ get-documentation({ "id": "modal" })
22
+ get-documentation({ "id": "toast" })
23
+ ```
24
+
25
+ ### Inspect Live Story Implementations:
26
+
27
+ ```json
28
+ get-documentation-for-story({ "id": "dialog", "storyName": "Confirmation" })
29
+ get-documentation-for-story({ "id": "dialogform", "storyName": "Default" })
30
+ get-documentation-for-story({ "id": "modal", "storyName": "Default" })
31
+ ```
32
+
33
+ ### Inspect Knowledge Graph & Usages:
34
+
35
+ ```json
36
+ query_graph({ "query": "Dialog" })
37
+ query_graph({ "query": "DialogForm" })
38
+ ```
39
+
40
+ ---
41
+
42
+ ## 2. Overlay Selection Matrix
43
+
44
+ | Component | Primary Use Case | Key Characteristics |
45
+ | :--------------- | :-------------------------------------------- | :------------------------------------------------------------------------------------ |
46
+ | **`Dialog`** | Confirmations, alerts, simple detail previews | Standard `header`, `footer`, and body layout; built-in backdrop dimming. |
47
+ | **`DialogForm`** | Create/Edit forms embedded inside a dialog | Built-in form submit/cancel action bar, dirty state tracking, and submit lifecycle. |
48
+ | **`Modal`** | Slide-in drawers, complex custom viewports | Headless overlay primitive with flexible animations, size variants, and drawer modes. |
49
+
50
+ ---
51
+
52
+ ## 3. Mandatory Implementation Rules
53
+
54
+ 1. **Query MCP for Current Code Patterns**: Always inspect `dialog`, `dialogform`, or `modal` stories via MCP before writing overlay code.
55
+ 2. **Strict Subpath Imports**: Import via `@wangs-ui/react-core/primitive/dialog`, `@wangs-ui/react-core/primitive/dialogform`, `@wangs-ui/react-core/primitive/modal`, or `@wangs-ui/react-core/primitive/toast`.
56
+ 3. **Prevent Dismissal During Async Mutations**: Guard the close handler so users cannot accidentally dismiss the dialog while a mutation request is in-flight.
57
+ 4. **Coordinate with Toast Notifications**: Trigger feedback toasts on successful creation, update, or deletion actions.
58
+ 5. **Translate All Overlay Copy**: All dialog titles, confirmation descriptions, and button labels must be localized using `t('...')` from `@wangs-ui/react-i18n`.