@ranimontagna/agent-toolkit 0.1.6 → 0.1.9

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.
Files changed (108) hide show
  1. package/README.md +83 -10
  2. package/package.json +1 -1
  3. package/skills/backend/database/postgres-patterns/LICENSE.ANTIGRAVITY +21 -0
  4. package/skills/backend/database/postgres-patterns/LICENSE.ECC +21 -0
  5. package/skills/backend/database/postgres-patterns/NOTICE.md +11 -0
  6. package/skills/backend/database/postgres-patterns/SKILL.md +180 -0
  7. package/skills/backend/go/golang-patterns/LICENSE +21 -0
  8. package/skills/backend/go/golang-patterns/NOTICE.md +10 -0
  9. package/skills/backend/go/golang-patterns/SKILL.md +674 -0
  10. package/skills/backend/go/golang-testing/LICENSE +21 -0
  11. package/skills/backend/go/golang-testing/NOTICE.md +10 -0
  12. package/skills/backend/go/golang-testing/SKILL.md +329 -0
  13. package/skills/backend/java/java-coding-standards/LICENSE +21 -0
  14. package/skills/backend/java/java-coding-standards/NOTICE.md +10 -0
  15. package/skills/backend/java/java-coding-standards/SKILL.md +383 -0
  16. package/skills/backend/java/java-junit/LICENSE +21 -0
  17. package/skills/backend/java/java-junit/NOTICE.md +10 -0
  18. package/skills/backend/java/java-junit/SKILL.md +64 -0
  19. package/skills/backend/kotlin/kotlin-patterns/LICENSE +21 -0
  20. package/skills/backend/kotlin/kotlin-patterns/NOTICE.md +7 -0
  21. package/skills/backend/kotlin/kotlin-patterns/SKILL.md +711 -0
  22. package/skills/backend/kotlin/kotlin-testing/LICENSE +21 -0
  23. package/skills/backend/kotlin/kotlin-testing/NOTICE.md +7 -0
  24. package/skills/backend/kotlin/kotlin-testing/SKILL.md +824 -0
  25. package/skills/backend/python/python-patterns/LICENSE +21 -0
  26. package/skills/backend/python/python-patterns/NOTICE.md +7 -0
  27. package/skills/backend/python/python-patterns/SKILL.md +424 -0
  28. package/skills/backend/python/python-testing/LICENSE +21 -0
  29. package/skills/backend/python/python-testing/NOTICE.md +7 -0
  30. package/skills/backend/python/python-testing/SKILL.md +494 -0
  31. package/skills/devops/docker-patterns/LICENSE.ANTIGRAVITY +21 -0
  32. package/skills/devops/docker-patterns/LICENSE.ECC +21 -0
  33. package/skills/devops/docker-patterns/NOTICE.md +11 -0
  34. package/skills/devops/docker-patterns/SKILL.md +397 -0
  35. package/skills/frontend/accessibility/LICENSE +21 -0
  36. package/skills/frontend/accessibility/NOTICE.md +10 -0
  37. package/skills/frontend/accessibility/SKILL.md +145 -0
  38. package/skills/frontend/design/ui-ux-pro-max/LICENSE +21 -0
  39. package/skills/frontend/design/ui-ux-pro-max/NOTICE.md +12 -0
  40. package/skills/frontend/design/ui-ux-pro-max/SKILL.md +672 -0
  41. package/skills/frontend/design/ui-ux-pro-max/data/_sync_all.py +414 -0
  42. package/skills/frontend/design/ui-ux-pro-max/data/app-interface.csv +31 -0
  43. package/skills/frontend/design/ui-ux-pro-max/data/charts.csv +26 -0
  44. package/skills/frontend/design/ui-ux-pro-max/data/colors.csv +162 -0
  45. package/skills/frontend/design/ui-ux-pro-max/data/design.csv +1776 -0
  46. package/skills/frontend/design/ui-ux-pro-max/data/draft.csv +1779 -0
  47. package/skills/frontend/design/ui-ux-pro-max/data/google-fonts.csv +1924 -0
  48. package/skills/frontend/design/ui-ux-pro-max/data/icons.csv +106 -0
  49. package/skills/frontend/design/ui-ux-pro-max/data/landing.csv +35 -0
  50. package/skills/frontend/design/ui-ux-pro-max/data/products.csv +162 -0
  51. package/skills/frontend/design/ui-ux-pro-max/data/react-performance.csv +45 -0
  52. package/skills/frontend/design/ui-ux-pro-max/data/stacks/angular.csv +51 -0
  53. package/skills/frontend/design/ui-ux-pro-max/data/stacks/astro.csv +54 -0
  54. package/skills/frontend/design/ui-ux-pro-max/data/stacks/flutter.csv +53 -0
  55. package/skills/frontend/design/ui-ux-pro-max/data/stacks/html-tailwind.csv +56 -0
  56. package/skills/frontend/design/ui-ux-pro-max/data/stacks/jetpack-compose.csv +53 -0
  57. package/skills/frontend/design/ui-ux-pro-max/data/stacks/laravel.csv +51 -0
  58. package/skills/frontend/design/ui-ux-pro-max/data/stacks/nextjs.csv +53 -0
  59. package/skills/frontend/design/ui-ux-pro-max/data/stacks/nuxt-ui.csv +51 -0
  60. package/skills/frontend/design/ui-ux-pro-max/data/stacks/nuxtjs.csv +59 -0
  61. package/skills/frontend/design/ui-ux-pro-max/data/stacks/react-native.csv +52 -0
  62. package/skills/frontend/design/ui-ux-pro-max/data/stacks/react.csv +54 -0
  63. package/skills/frontend/design/ui-ux-pro-max/data/stacks/shadcn.csv +61 -0
  64. package/skills/frontend/design/ui-ux-pro-max/data/stacks/svelte.csv +54 -0
  65. package/skills/frontend/design/ui-ux-pro-max/data/stacks/swiftui.csv +51 -0
  66. package/skills/frontend/design/ui-ux-pro-max/data/stacks/threejs.csv +54 -0
  67. package/skills/frontend/design/ui-ux-pro-max/data/stacks/vue.csv +50 -0
  68. package/skills/frontend/design/ui-ux-pro-max/data/styles.csv +85 -0
  69. package/skills/frontend/design/ui-ux-pro-max/data/typography.csv +74 -0
  70. package/skills/frontend/design/ui-ux-pro-max/data/ui-reasoning.csv +162 -0
  71. package/skills/frontend/design/ui-ux-pro-max/data/ux-guidelines.csv +100 -0
  72. package/skills/frontend/design/ui-ux-pro-max/scripts/core.py +262 -0
  73. package/skills/frontend/design/ui-ux-pro-max/scripts/design_system.py +1148 -0
  74. package/skills/frontend/design/ui-ux-pro-max/scripts/search.py +114 -0
  75. package/skills/frontend/react/react-patterns/SKILL.md +4 -4
  76. package/skills/frontend/react/react-patterns/rules/react/LICENSE +21 -0
  77. package/skills/frontend/react/react-patterns/rules/react/NOTICE.md +11 -0
  78. package/skills/frontend/react/react-patterns/rules/react/coding-style.md +109 -0
  79. package/skills/frontend/react/react-patterns/rules/react/hooks.md +187 -0
  80. package/skills/frontend/react/react-patterns/rules/react/patterns.md +194 -0
  81. package/skills/frontend/react/react-patterns/rules/react/security.md +180 -0
  82. package/skills/frontend/react/react-patterns/rules/react/testing.md +208 -0
  83. package/skills/frontend/react/react-performance/SKILL.md +2 -2
  84. package/skills/frontend/react/react-performance/rules/react/LICENSE +21 -0
  85. package/skills/frontend/react/react-performance/rules/react/NOTICE.md +11 -0
  86. package/skills/frontend/react/react-performance/rules/react/coding-style.md +109 -0
  87. package/skills/frontend/react/react-performance/rules/react/hooks.md +187 -0
  88. package/skills/frontend/react/react-performance/rules/react/patterns.md +194 -0
  89. package/skills/frontend/react/react-performance/rules/react/security.md +180 -0
  90. package/skills/frontend/react/react-performance/rules/react/testing.md +208 -0
  91. package/skills/frontend/react/react-testing/SKILL.md +4 -4
  92. package/skills/frontend/react/react-testing/rules/react/LICENSE +21 -0
  93. package/skills/frontend/react/react-testing/rules/react/NOTICE.md +11 -0
  94. package/skills/frontend/react/react-testing/rules/react/coding-style.md +109 -0
  95. package/skills/frontend/react/react-testing/rules/react/hooks.md +187 -0
  96. package/skills/frontend/react/react-testing/rules/react/patterns.md +194 -0
  97. package/skills/frontend/react/react-testing/rules/react/security.md +180 -0
  98. package/skills/frontend/react/react-testing/rules/react/testing.md +208 -0
  99. package/skills/general/code-reviewer/AGENTS.md +292 -0
  100. package/skills/general/code-reviewer/LICENSE +201 -0
  101. package/skills/general/code-reviewer/NOTICE.md +10 -0
  102. package/skills/general/code-reviewer/SKILL.md +132 -0
  103. package/skills/general/code-reviewer/rules/correctness-error-handling.md +279 -0
  104. package/skills/general/code-reviewer/rules/maintainability-naming.md +149 -0
  105. package/skills/general/code-reviewer/rules/maintainability-type-hints.md +93 -0
  106. package/skills/general/code-reviewer/rules/performance-n-plus-one.md +250 -0
  107. package/skills/general/code-reviewer/rules/security-sql-injection.md +142 -0
  108. package/skills/general/code-reviewer/rules/security-xss-prevention.md +225 -0
@@ -0,0 +1,114 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ UI/UX Pro Max Search - BM25 search engine for UI/UX style guides
5
+ Usage: python search.py "<query>" [--domain <domain>] [--stack <stack>] [--max-results 3]
6
+ python search.py "<query>" --design-system [-p "Project Name"]
7
+ python search.py "<query>" --design-system --persist [-p "Project Name"] [--page "dashboard"]
8
+
9
+ Domains: style, prompt, color, chart, landing, product, ux, typography, google-fonts
10
+ Stacks: react, nextjs, vue, svelte, astro, swiftui, react-native, flutter, nuxtjs, nuxt-ui, html-tailwind, shadcn, jetpack-compose, threejs
11
+
12
+ Persistence (Master + Overrides pattern):
13
+ --persist Save design system to design-system/MASTER.md
14
+ --page Also create a page-specific override file in design-system/pages/
15
+ """
16
+
17
+ import argparse
18
+ import sys
19
+ import io
20
+ from core import CSV_CONFIG, AVAILABLE_STACKS, MAX_RESULTS, search, search_stack
21
+ from design_system import generate_design_system, persist_design_system
22
+
23
+ # Force UTF-8 for stdout/stderr to handle emojis on Windows (cp1252 default)
24
+ if sys.stdout.encoding and sys.stdout.encoding.lower() != 'utf-8':
25
+ sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
26
+ if sys.stderr.encoding and sys.stderr.encoding.lower() != 'utf-8':
27
+ sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
28
+
29
+
30
+ def format_output(result):
31
+ """Format results for Claude consumption (token-optimized)"""
32
+ if "error" in result:
33
+ return f"Error: {result['error']}"
34
+
35
+ output = []
36
+ if result.get("stack"):
37
+ output.append(f"## UI Pro Max Stack Guidelines")
38
+ output.append(f"**Stack:** {result['stack']} | **Query:** {result['query']}")
39
+ else:
40
+ output.append(f"## UI Pro Max Search Results")
41
+ output.append(f"**Domain:** {result['domain']} | **Query:** {result['query']}")
42
+ output.append(f"**Source:** {result['file']} | **Found:** {result['count']} results\n")
43
+
44
+ for i, row in enumerate(result['results'], 1):
45
+ output.append(f"### Result {i}")
46
+ for key, value in row.items():
47
+ value_str = str(value)
48
+ if len(value_str) > 300:
49
+ value_str = value_str[:300] + "..."
50
+ output.append(f"- **{key}:** {value_str}")
51
+ output.append("")
52
+
53
+ return "\n".join(output)
54
+
55
+
56
+ if __name__ == "__main__":
57
+ parser = argparse.ArgumentParser(description="UI Pro Max Search")
58
+ parser.add_argument("query", help="Search query")
59
+ parser.add_argument("--domain", "-d", choices=list(CSV_CONFIG.keys()), help="Search domain")
60
+ parser.add_argument("--stack", "-s", choices=AVAILABLE_STACKS, help=f"Stack-specific search. Available: {', '.join(AVAILABLE_STACKS)}")
61
+ parser.add_argument("--max-results", "-n", type=int, default=MAX_RESULTS, help="Max results (default: 3)")
62
+ parser.add_argument("--json", action="store_true", help="Output as JSON")
63
+ # Design system generation
64
+ parser.add_argument("--design-system", "-ds", action="store_true", help="Generate complete design system recommendation")
65
+ parser.add_argument("--project-name", "-p", type=str, default=None, help="Project name for design system output")
66
+ parser.add_argument("--format", "-f", choices=["ascii", "markdown"], default="ascii", help="Output format for design system")
67
+ # Persistence (Master + Overrides pattern)
68
+ parser.add_argument("--persist", action="store_true", help="Save design system to design-system/MASTER.md (creates hierarchical structure)")
69
+ parser.add_argument("--page", type=str, default=None, help="Create page-specific override file in design-system/pages/")
70
+ parser.add_argument("--output-dir", "-o", type=str, default=None, help="Output directory for persisted files (default: current directory)")
71
+
72
+ args = parser.parse_args()
73
+
74
+ # Design system takes priority
75
+ if args.design_system:
76
+ result = generate_design_system(
77
+ args.query,
78
+ args.project_name,
79
+ args.format,
80
+ persist=args.persist,
81
+ page=args.page,
82
+ output_dir=args.output_dir
83
+ )
84
+ print(result)
85
+
86
+ # Print persistence confirmation
87
+ if args.persist:
88
+ project_slug = args.project_name.lower().replace(' ', '-') if args.project_name else "default"
89
+ print("\n" + "=" * 60)
90
+ print(f"✅ Design system persisted to design-system/{project_slug}/")
91
+ print(f" 📄 design-system/{project_slug}/MASTER.md (Global Source of Truth)")
92
+ if args.page:
93
+ page_filename = args.page.lower().replace(' ', '-')
94
+ print(f" 📄 design-system/{project_slug}/pages/{page_filename}.md (Page Overrides)")
95
+ print("")
96
+ print(f"📖 Usage: When building a page, check design-system/{project_slug}/pages/[page].md first.")
97
+ print(f" If exists, its rules override MASTER.md. Otherwise, use MASTER.md.")
98
+ print("=" * 60)
99
+ # Stack search
100
+ elif args.stack:
101
+ result = search_stack(args.query, args.stack, args.max_results)
102
+ if args.json:
103
+ import json
104
+ print(json.dumps(result, indent=2, ensure_ascii=False))
105
+ else:
106
+ print(format_output(result))
107
+ # Domain search
108
+ else:
109
+ result = search(args.query, args.domain, args.max_results)
110
+ if args.json:
111
+ import json
112
+ print(json.dumps(result, indent=2, ensure_ascii=False))
113
+ else:
114
+ print(format_output(result))
@@ -52,7 +52,7 @@ React has no inheritance model for components. Compose with `children`, render p
52
52
 
53
53
  ## Hooks Discipline
54
54
 
55
- See [rules/react/hooks.md](../../rules/react/hooks.md) for the full ruleset. Highlights:
55
+ See [rules/react/hooks.md](rules/react/hooks.md) for the full ruleset. Highlights:
56
56
 
57
57
  - Top-level only, never conditional
58
58
  - Cleanup every subscription, interval, listener
@@ -250,7 +250,7 @@ Wrap a component in `React.memo` only when:
250
250
  - Form inputs need labels — `<label htmlFor>` or `aria-label` if visually labeled by an icon
251
251
  - Manage focus on route changes and modal open/close
252
252
  - Run `axe` in component tests (see [skills/react-testing](../react-testing/SKILL.md))
253
- - Cross-link: [skills/accessibility/SKILL.md](../accessibility/SKILL.md) covers WCAG criteria and pattern libraries
253
+ - Cross-link: skills/accessibility covers WCAG criteria and pattern libraries when that optional skill is installed
254
254
 
255
255
  ## Routing
256
256
 
@@ -264,8 +264,8 @@ This skill is router-agnostic. The patterns above work with React Router, TanSta
264
264
 
265
265
  ## Related
266
266
 
267
- - Rules: [rules/react/](../../rules/react/) — coding-style, hooks, patterns, security, testing
268
- - Skills: [react-performance](../react-performance/SKILL.md) for the Vercel-derived performance ruleset, [frontend-patterns](../frontend-patterns/SKILL.md) for cross-framework UI concerns, [accessibility](../accessibility/SKILL.md), [angular-developer](../angular-developer/SKILL.md) for framework comparison
267
+ - Rules: [rules/react/](rules/react/) — coding-style, hooks, patterns, security, testing
268
+ - Skills: [react-performance](../react-performance/SKILL.md) for the Vercel-derived performance ruleset; frontend-patterns for cross-framework UI concerns; accessibility; angular-developer for framework comparison
269
269
  - Agents: `react-reviewer` for code review, `react-build-resolver` for build/bundler errors
270
270
  - Commands: `/react-review`, `/react-build`, `/react-test`
271
271
 
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Affaan Mustafa
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,11 @@
1
+ # Third-party notice
2
+
3
+ This directory contains React rule references copied from Affaan Mustafa's ECC
4
+ repository.
5
+
6
+ - Source: https://github.com/affaan-m/ECC/tree/main/rules/react
7
+ - Source commit: 0f84c0e2796703fbda87d577b2636351418c7442
8
+ - License: MIT
9
+ - Copyright: Copyright (c) 2026 Affaan Mustafa
10
+
11
+ The upstream MIT license is included in `LICENSE`.
@@ -0,0 +1,109 @@
1
+ ---
2
+ paths:
3
+ - "**/*.tsx"
4
+ - "**/*.jsx"
5
+ - "**/components/**/*.ts"
6
+ - "**/components/**/*.js"
7
+ - "**/hooks/**/*.ts"
8
+ - "**/hooks/**/*.js"
9
+ ---
10
+ # React Coding Style
11
+
12
+ > This file extends the upstream `typescript/coding-style.md` and `common/coding-style.md` rules with React specific content.
13
+
14
+ ## File Extensions
15
+
16
+ - `.tsx` for any file containing JSX, even one-liner snippets
17
+ - `.ts` for pure logic, custom hooks without JSX, type definitions, utilities
18
+ - `.test.tsx` / `.test.ts` mirroring the source file
19
+ - Use `.jsx` only when the project intentionally avoids TypeScript — flag every new untyped React file in review
20
+
21
+ ## Naming
22
+
23
+ - Components: `PascalCase` for both the symbol and the file (`UserCard.tsx`, default export `UserCard`)
24
+ - Custom hooks: `useCamelCase` for the symbol, kebab-case for the file when the project convention is kebab-case (`use-debounce.ts` exports `useDebounce`)
25
+ - Context: `<Domain>Context` symbol, `<Domain>Provider` provider component, `use<Domain>` consumer hook
26
+ - Event handlers: `handleClick`, `handleSubmit` inside the component; the prop that receives it is `onClick`, `onSubmit`
27
+ - Boolean props: `isLoading`, `hasError`, `canSubmit` — never `loading` or `error` alone for booleans
28
+
29
+ ## Component Shape
30
+
31
+ ```tsx
32
+ type Props = {
33
+ user: User;
34
+ onSelect: (id: string) => void;
35
+ };
36
+
37
+ export function UserCard({ user, onSelect }: Props) {
38
+ return (
39
+ <button type="button" onClick={() => onSelect(user.id)}>
40
+ {user.name}
41
+ </button>
42
+ );
43
+ }
44
+ ```
45
+
46
+ - Prefer `type Props = {}` for closed component prop shapes
47
+ - Use `interface` only when the prop type is extended via declaration merging or exported as a public API extension point
48
+ - Always destructure props in the parameter list — no `props.user` access inside the body
49
+ - Type the return implicitly through JSX (`function Foo(): JSX.Element` only when the function returns conditionally and the union confuses inference)
50
+
51
+ ## JSX
52
+
53
+ - Self-close tags with no children: `<img />`, `<UserCard user={u} />`
54
+ - Use fragments `<>...</>` over wrapper `<div>` when no DOM element is needed
55
+ - Conditional rendering: `{condition && <Foo />}` for booleans, ternary for either/or, early return for guard clauses
56
+ - Never put logic inline in JSX when it reads as multi-line — extract to a const above the return or a function
57
+
58
+ ```tsx
59
+ // Prefer
60
+ const greeting = user.isAdmin ? "Welcome, admin" : `Hello ${user.name}`;
61
+ return <h1>{greeting}</h1>;
62
+
63
+ // Over
64
+ return <h1>{user.isAdmin ? "Welcome, admin" : `Hello ${user.name}`}</h1>;
65
+ ```
66
+
67
+ ## Server / Client Boundary (Next.js App Router, RSC)
68
+
69
+ - Default a new file to Server Component — only add `"use client"` when the file uses state, effects, refs, browser APIs, or event handlers
70
+ - Place the `"use client"` directive on line 1, before any imports
71
+ - Never import a Client Component file from inside a `"use server"` action file
72
+ - Never re-export server-only code through a client module — the bundler will silently include it
73
+
74
+ ## Imports
75
+
76
+ - React imports first: `import { useState } from "react"`
77
+ - Then third-party libs, then absolute project imports, then relative
78
+ - Type-only imports: `import type { ReactNode } from "react"` — never mix runtime and type imports in one statement when ESLint's `consistent-type-imports` is configured
79
+
80
+ ## Hooks Discipline
81
+
82
+ See [hooks.md](./hooks.md) for the full ruleset. Style highlights:
83
+
84
+ - Custom hooks must start with `use` — enforced by `eslint-plugin-react-hooks`
85
+ - Group all hook calls at the top of the component, before any conditional logic
86
+ - Avoid creating ad-hoc hooks for one-line wrappers — inline the call instead
87
+
88
+ ## State
89
+
90
+ - Local first (`useState`), lift only when shared
91
+ - Context for cross-cutting state read by many components (theme, auth, i18n) — not for high-frequency updates
92
+ - External store (Zustand, Jotai, Redux Toolkit) when state must persist across route changes, sync across tabs, or be debugged via devtools
93
+ - Never duplicate state that can be derived — compute during render
94
+
95
+ ## Class Components
96
+
97
+ Forbidden in new code. Convert legacy class components to function components when touching them for non-trivial changes.
98
+
99
+ ## File Layout per Component
100
+
101
+ ```
102
+ components/UserCard/
103
+ UserCard.tsx
104
+ UserCard.module.css # or styled-components, or Tailwind classes inline
105
+ UserCard.test.tsx
106
+ index.ts # re-export only
107
+ ```
108
+
109
+ Inline single-file components are fine for trivial presentational pieces.
@@ -0,0 +1,187 @@
1
+ ---
2
+ paths:
3
+ - "**/*.tsx"
4
+ - "**/*.jsx"
5
+ - "**/hooks/**/*.ts"
6
+ - "**/hooks/**/*.js"
7
+ - "**/use-*.ts"
8
+ - "**/use-*.tsx"
9
+ ---
10
+ # React Hooks
11
+
12
+ > This file covers **React hooks** (`useState`, `useEffect`, `useMemo`, `useCallback`, custom hooks) — NOT the Claude Code `hooks/` runtime system. Naming matches the per-language convention `rules/<lang>/hooks.md` used across this repo.
13
+ >
14
+ > Extends the upstream `typescript/patterns.md` and `common/patterns.md` rules.
15
+
16
+ ## Rules of Hooks
17
+
18
+ Enforce `eslint-plugin-react-hooks` with `react-hooks/rules-of-hooks` set to error.
19
+
20
+ 1. Hooks only at the top level of a function component or another hook
21
+ 2. Never in loops, conditionals, nested functions, or after early returns
22
+ 3. Always called in the same order on every render
23
+ 4. Only inside React function components or custom hooks (functions starting with `use`)
24
+
25
+ ```tsx
26
+ // WRONG: conditional hook
27
+ function Foo({ enabled }: { enabled: boolean }) {
28
+ if (enabled) {
29
+ const [x, setX] = useState(0); // rule violation
30
+ }
31
+ }
32
+
33
+ // CORRECT: hook unconditional, condition inside
34
+ function Foo({ enabled }: { enabled: boolean }) {
35
+ const [x, setX] = useState(0);
36
+ if (!enabled) return null;
37
+ return <span>{x}</span>;
38
+ }
39
+ ```
40
+
41
+ ## `useEffect` — When NOT to Use
42
+
43
+ `useEffect` is for synchronizing with external systems (subscriptions, browser APIs, third-party libraries). It is **not** the right tool for:
44
+
45
+ - Derived state — compute it during render
46
+ - Transforming data for rendering — compute it during render
47
+ - Resetting state when a prop changes — use a `key` on the parent or derive from props
48
+ - Notifying parents of state changes — call the callback in the event handler
49
+ - Initializing app-level singletons — call the function module-side or in `main.tsx`
50
+
51
+ ```tsx
52
+ // WRONG: effect for derived state
53
+ const [fullName, setFullName] = useState("");
54
+ useEffect(() => {
55
+ setFullName(`${first} ${last}`);
56
+ }, [first, last]);
57
+
58
+ // CORRECT: derive during render
59
+ const fullName = `${first} ${last}`;
60
+ ```
61
+
62
+ ## Dependency Arrays
63
+
64
+ - Always include every reactive value referenced inside the effect/callback
65
+ - Enable `react-hooks/exhaustive-deps` lint rule — never silence it without a comment explaining why
66
+ - If the dep array grows unwieldy, the effect is doing too much — split it
67
+ - Stable identity for functions passed in deps: wrap in `useCallback` only when the function is itself a dependency of another hook or passed to a memoized child
68
+
69
+ ## Cleanup
70
+
71
+ Every subscription, interval, listener, or in-flight request must clean up.
72
+
73
+ ```tsx
74
+ useEffect(() => {
75
+ const controller = new AbortController();
76
+ fetch(url, { signal: controller.signal }).then(handleResponse);
77
+ return () => controller.abort();
78
+ }, [url]);
79
+ ```
80
+
81
+ ```tsx
82
+ useEffect(() => {
83
+ const id = setInterval(tick, 1000);
84
+ return () => clearInterval(id);
85
+ }, []);
86
+ ```
87
+
88
+ Missing cleanup = race conditions when deps change, memory leaks on unmount.
89
+
90
+ ## `useMemo` and `useCallback` — When Worth It
91
+
92
+ Default position: **do not memoize**. Add `useMemo` / `useCallback` only when:
93
+
94
+ 1. The value is passed to a `React.memo`-wrapped child as a prop, and identity matters
95
+ 2. The value is a dependency of another `useEffect` / `useMemo` / `useCallback`
96
+ 3. The computation is measurably expensive (profile before assuming)
97
+
98
+ Premature memoization adds noise, hides bugs, and can be slower than the recompute it replaces.
99
+
100
+ ## Custom Hooks
101
+
102
+ Extract a custom hook when:
103
+
104
+ - The same hook sequence (state + effect + computed) appears in 2+ components
105
+ - The logic has a clear, nameable purpose (`useDebounce`, `useOnClickOutside`, `useLocalStorage`)
106
+ - You want to test the logic independently of any component
107
+
108
+ Do NOT extract when:
109
+
110
+ - It would have a single caller — inline it
111
+ - The "hook" is just `useState` with a different name — adds indirection, no value
112
+
113
+ ```tsx
114
+ export function useDebounce<T>(value: T, delay: number): T {
115
+ const [debounced, setDebounced] = useState(value);
116
+ useEffect(() => {
117
+ const id = setTimeout(() => setDebounced(value), delay);
118
+ return () => clearTimeout(id);
119
+ }, [value, delay]);
120
+ return debounced;
121
+ }
122
+ ```
123
+
124
+ ## `useState` Patterns
125
+
126
+ - Initial state from prop only at mount: pass a function `useState(() => computeInitial(prop))` when computation is expensive
127
+ - Functional updater when the new state depends on the old: `setCount(c => c + 1)` — never `setCount(count + 1)` inside async or batched contexts
128
+ - Group related state into one object only when they always change together; otherwise split into multiple `useState` calls
129
+ - Use `useReducer` once state transitions are conditional on the previous state or there are 3+ related values
130
+
131
+ ## `useRef` Patterns
132
+
133
+ - DOM refs for imperative APIs (focus, scroll, third-party libs)
134
+ - Mutable container that does not trigger re-render (timer ids, previous values, "is mounted" flags)
135
+ - Never read or write `ref.current` during render — only inside effects or event handlers
136
+ - `useImperativeHandle` only when exposing a child API to a parent ref — last-resort escape hatch
137
+
138
+ ## `useSyncExternalStore`
139
+
140
+ Use this hook to subscribe to any external store (browser API, third-party state lib, custom event emitter). It is the supported way to make external state safe with concurrent rendering.
141
+
142
+ ```tsx
143
+ const isOnline = useSyncExternalStore(
144
+ (cb) => {
145
+ window.addEventListener("online", cb);
146
+ window.addEventListener("offline", cb);
147
+ return () => {
148
+ window.removeEventListener("online", cb);
149
+ window.removeEventListener("offline", cb);
150
+ };
151
+ },
152
+ () => navigator.onLine,
153
+ () => true,
154
+ );
155
+ ```
156
+
157
+ ## React 19 Additions
158
+
159
+ - `use()` — unwrap promises and contexts inline; usable conditionally (only hook with that property)
160
+ - `useFormStatus()` / `useFormState()` (or `useActionState`) — form submission state without prop drilling
161
+ - `useOptimistic()` — optimistic UI updates while a server action is pending
162
+ - `useTransition()` — mark non-urgent state updates so urgent ones stay responsive
163
+
164
+ When the project targets React 19+, prefer these over hand-rolled equivalents.
165
+
166
+ ## Stale Closure Trap
167
+
168
+ Async handlers and intervals capture the values from the render where they were created. Fix by:
169
+
170
+ 1. Using the functional updater form of `setState`
171
+ 2. Putting the changing value in the dep array of `useEffect` and rebuilding the handler
172
+ 3. Reading from a ref that is kept in sync
173
+
174
+ ## Lint Configuration
175
+
176
+ Required rules:
177
+
178
+ ```json
179
+ {
180
+ "rules": {
181
+ "react-hooks/rules-of-hooks": "error",
182
+ "react-hooks/exhaustive-deps": "warn"
183
+ }
184
+ }
185
+ ```
186
+
187
+ Treat `exhaustive-deps` warnings as errors in CI for new code.
@@ -0,0 +1,194 @@
1
+ ---
2
+ paths:
3
+ - "**/*.tsx"
4
+ - "**/*.jsx"
5
+ - "**/components/**/*.ts"
6
+ - "**/components/**/*.js"
7
+ - "**/app/**/*.tsx"
8
+ - "**/pages/**/*.tsx"
9
+ ---
10
+ # React Patterns
11
+
12
+ > This file extends the upstream `typescript/patterns.md` and `common/patterns.md` rules with React specific content. For hook-specific rules see [hooks.md](./hooks.md).
13
+
14
+ ## Container / Presentational Split
15
+
16
+ Container components own data fetching, state, and side effects. Presentational components receive props and render — no service calls, no hooks beyond local UI state.
17
+
18
+ ```tsx
19
+ // Container — owns data
20
+ export function UserPage({ userId }: { userId: string }) {
21
+ const { data: user, isLoading } = useUser(userId);
22
+ if (isLoading) return <Spinner />;
23
+ if (!user) return <NotFound />;
24
+ return <UserCard user={user} onSelect={handleSelect} />;
25
+ }
26
+
27
+ // Presentational — pure
28
+ export function UserCard({ user, onSelect }: { user: User; onSelect: (id: string) => void }) {
29
+ return <button onClick={() => onSelect(user.id)}>{user.name}</button>;
30
+ }
31
+ ```
32
+
33
+ ## State Location Decision Tree
34
+
35
+ 1. Used by one component → `useState` inside it
36
+ 2. Used by parent + a few children → lift to nearest common ancestor, pass via props
37
+ 3. Used across distant branches → React Context **for low-frequency reads only** (theme, auth, locale)
38
+ 4. High-frequency updates shared across the tree → external store (Zustand, Jotai, Redux Toolkit)
39
+ 5. Server-derived data → server-state library (TanStack Query, SWR, RSC fetch) — not application state
40
+
41
+ Context misused for frequently changing values causes every consumer to re-render on every update.
42
+
43
+ ## Server / Client Component Boundary (RSC, Next.js App Router)
44
+
45
+ - Server Components are the default — they run on the server, do not ship to the client, and can `await` directly
46
+ - Client Components opt in with `"use client"` at the top of the file
47
+ - Data flows down: a Server Component can render a Client Component and pass serializable props
48
+ - A Client Component cannot import a Server Component, but it can receive one via `children` or named slots
49
+
50
+ ```tsx
51
+ // Server (default)
52
+ export default async function Page() {
53
+ const user = await fetchUser();
54
+ return <UserClient user={user} />;
55
+ }
56
+
57
+ // Client
58
+ "use client";
59
+ export function UserClient({ user }: { user: User }) {
60
+ const [tab, setTab] = useState("profile");
61
+ return <Tabs value={tab} onChange={setTab}>{user.name}</Tabs>;
62
+ }
63
+ ```
64
+
65
+ - Never import `"server-only"` packages (DB clients, secrets) from a Client Component file — wrap them in a Server Component or Server Action
66
+ - Mark sensitive modules with `import "server-only"` so the bundler errors if a client file imports them
67
+
68
+ ## Suspense + Error Boundaries
69
+
70
+ Every Suspense boundary needs an Error Boundary above it. The pair handles both states.
71
+
72
+ ```tsx
73
+ <ErrorBoundary fallback={<ErrorView />}>
74
+ <Suspense fallback={<Skeleton />}>
75
+ <UserDetails id={id} />
76
+ </Suspense>
77
+ </ErrorBoundary>
78
+ ```
79
+
80
+ - Place Suspense boundaries close to where data is needed, not at the route root
81
+ - Multiple narrower boundaries reveal loaded content progressively
82
+ - Error Boundary must be a Class Component (React 19 has no functional equivalent yet) OR use a library wrapper such as `react-error-boundary`
83
+
84
+ ## Forms
85
+
86
+ ### Uncontrolled (React 19 + form actions)
87
+
88
+ Prefer uncontrolled inputs with form actions when the form has a clear submit step. The browser owns the value; React reads it via `FormData` on submit.
89
+
90
+ ```tsx
91
+ async function action(formData: FormData) {
92
+ "use server";
93
+ await saveUser({ name: String(formData.get("name")) });
94
+ }
95
+
96
+ export function UserForm() {
97
+ return (
98
+ <form action={action}>
99
+ <input name="name" required />
100
+ <button type="submit">Save</button>
101
+ </form>
102
+ );
103
+ }
104
+ ```
105
+
106
+ ### Controlled
107
+
108
+ Use controlled inputs when the value drives other UI, requires real-time validation, or formatting.
109
+
110
+ ```tsx
111
+ const [email, setEmail] = useState("");
112
+ return <input value={email} onChange={(e) => setEmail(e.target.value)} />;
113
+ ```
114
+
115
+ ### Form Libraries
116
+
117
+ For complex forms (multi-step, dynamic field arrays, cross-field validation), use a library:
118
+
119
+ - React Hook Form — minimal re-renders, uncontrolled-first
120
+ - TanStack Form — typed, framework-agnostic
121
+ - Final Form — when subscription-based re-renders matter
122
+
123
+ ## Data Fetching
124
+
125
+ | Strategy | When |
126
+ |---|---|
127
+ | RSC fetch (`await` in Server Component) | Per-request data in Next.js App Router, no client-side cache needed |
128
+ | TanStack Query | Client-side cache, mutations, optimistic updates, polling |
129
+ | SWR | Lightweight cache + revalidation, simpler than TanStack Query |
130
+ | `fetch` in `useEffect` | Avoid — race conditions, no cache, no retry. Only acceptable for one-off fire-and-forget |
131
+
132
+ Never fetch in a `useEffect` when a real cache library is available — they handle deduping, cache invalidation, error retry, and Suspense integration.
133
+
134
+ ## Lists and Keys
135
+
136
+ - `key` must be stable across renders — never `index` for any list that can reorder, insert, or delete
137
+ - `key` must be unique among siblings, not globally
138
+ - A reordered list with index keys causes state in child components to attach to the wrong row
139
+
140
+ ## Composition over Inheritance
141
+
142
+ - Pass `children` for slot-style composition
143
+ - Pass render-prop functions for parameterized rendering
144
+ - Pass component types for plug-in points: `renderItem={UserRow}`
145
+ - Never extend a component class to specialize behavior
146
+
147
+ ## Compound Components
148
+
149
+ For related controls (Tabs, Accordion, Menu), use compound components sharing state via Context:
150
+
151
+ ```tsx
152
+ <Tabs defaultValue="profile">
153
+ <Tabs.List>
154
+ <Tabs.Trigger value="profile">Profile</Tabs.Trigger>
155
+ <Tabs.Trigger value="settings">Settings</Tabs.Trigger>
156
+ </Tabs.List>
157
+ <Tabs.Panel value="profile"><ProfileForm /></Tabs.Panel>
158
+ <Tabs.Panel value="settings"><SettingsForm /></Tabs.Panel>
159
+ </Tabs>
160
+ ```
161
+
162
+ ## Portals
163
+
164
+ Use `createPortal` for modals, tooltips, toast containers — anything that must escape the parent's `overflow: hidden` or `z-index` stacking context. Render to a stable DOM node mounted in `index.html`.
165
+
166
+ ## Refs and Forwarding (React 19+)
167
+
168
+ React 19 lets function components accept `ref` as a regular prop — `forwardRef` is no longer required.
169
+
170
+ ```tsx
171
+ export function Input({ ref, ...rest }: { ref?: React.Ref<HTMLInputElement> } & InputProps) {
172
+ return <input ref={ref} {...rest} />;
173
+ }
174
+ ```
175
+
176
+ Older codebases on React 18 still need `forwardRef`.
177
+
178
+ ## Out of Scope (Pointer Sections)
179
+
180
+ ### Next.js (App Router)
181
+
182
+ - Server Actions, Route Handlers, Middleware, Parallel/Intercepted Routes, streaming Metadata
183
+ - Treated as a separate framework concern — when adding deep Next-specific patterns, propose a dedicated `rules/nextjs/` track
184
+ - For now follow Next.js official docs for App Router specifics
185
+
186
+ ### React Native
187
+
188
+ - Platform-specific imports (`Platform.OS`, `.ios.tsx` / `.android.tsx`), `StyleSheet`, navigation libraries (React Navigation, Expo Router)
189
+ - Treated as a separate track — `rules/react-native/` is not yet present
190
+ - React core hooks/patterns from this file still apply
191
+
192
+ ## Skill Reference
193
+
194
+ For React-specific deep dives see `skills/react-patterns/SKILL.md`. For cross-framework frontend concerns see `skills/frontend-patterns/SKILL.md`. For accessibility see `skills/accessibility/SKILL.md`.