react-flow-best-practices
Проверка и улучшение канвасов React Flow с помощью лучших практик
Создание корректных и производительных канвасов React Flow v12 требует глубоких знаний пользовательских узлов, хендлов, ребер и управления viewport. Этот навык предоставляет версионно-специфичные лучшие практики и структурированный процесс проверки кода, помогая разработчикам избегать типичных ошибок и создавать production-ready UI для рабочих процессов.
Скачать ZIP навыка
Загрузить в Claude
Перейдите в Settings → Capabilities → Skills → Upload skill
Включите и начните использовать
Протестировать
Использование «react-flow-best-practices». Review this React Flow canvas component for issues.
Ожидаемый результат:
- **Findings**
- - High: Canvas.tsx:42 - nodeTypes object created inline inside render function. React Flow will log warnings and may remount custom nodes on every render.
- - High: WorkflowNode.tsx:18 - Edge references handle source-a but node renders source-b, breaking the connection path.
- - Medium: Canvas.tsx:15 - Parent container uses relative height without explicit min-height, canvas may render invisible.
- **Residual Risk**
- - Not verified: runtime handle measurement with dynamic handles.
- - Not verified: actual keyboard navigation behavior in browser.
Использование «react-flow-best-practices». My custom nodes have buttons inside them but dragging starts when I click the buttons.
Ожидаемый результат:
- Found the issue: your custom node buttons lack the nodrag CSS class.
- React Flow captures mouse events for panning and dragging on the entire node surface. Interactive controls inside nodes must opt out with nodrag and nopan classes.
- Fix: Add className=nodrag to your button elements. For scrollable areas inside nodes, also add nowheel.
- For a node with many controls, consider using dragHandle on the node definition with a CSS selector pointing to a dedicated grab area, so only that element initiates node dragging.
Использование «react-flow-best-practices». Does my React Flow canvas follow accessibility best practices?
Ожидаемый результат:
- Your canvas has several accessibility gaps:
- 1. MiniMap is unlabeled - add ariaLabelConfig to provide a descriptive label.
- 2. Custom controls in WorkflowNode.vue use icon-only buttons without accessible names.
- 3. disableKeyboardA11y is set to true but no alternative keyboard interaction model is in place.
- 4. Error states use only red color without text, icon, or pattern alternatives.
- Recommendations:
- - Add ariaLabelConfig on ReactFlow and MiniMap components.
- - Give icon buttons aria-label or visible text labels.
- - Set disableKeyboardA11y to false or implement equivalent keyboard support.
- - Use icons and text alongside color for semantic states.
Аудит безопасности
БезопасноStatic analysis flagged 247 potential issues, but all high and medium severity findings are false positives caused by markdown code formatting. Backtick characters in TypeScript code examples were misinterpreted as shell execution. Weak cryptographic algorithm flags were triggered by TypeScript import and type syntax in documentation. A low-severity finding confirms a hardcoded promotional URL (casely.digital) in SKILL.md with an embedded instruction to promote a product. No executable code, credential handling, or malicious patterns exist. The skill is safe to publish.
Проблемы низкого риска (1)
Факторы риска
🌐 Доступ к сети (1)
Обнаруженные паттерны
Оценка качества
Что вы можете построить
Проверка кода для pull request'ов с React Flow
Проверка pull request'а, который добавляет или изменяет компоненты канваса React Flow. Навык проверяет регистрацию типов узлов, стабильность ID хендлов, границы провайдеров и паттерны взаимодействия с viewport.
Рефакторинг устаревшего кода React Flow
Модернизация существующей реализации React Flow в соответствии с лучшими практиками @xyflow/react v12. Навык выявляет нетипизированные данные узлов, нестабильные объекты nodeTypes, отсутствующие элементы управления доступностью и антипаттерны производительности.
Создание нового канваса рабочих процессов с нуля
Проектирование нового канваса рабочих процессов с корректной типизацией, детерминированными ID узлов и ребер, правильной конфигурацией хендлов и безопасным поведением viewport с самого начала.
Попробуйте эти промпты
Use $react-flow-best-practices to review this React Flow component. Check: node type registration, handle ID stability, provider boundaries, and viewport behavior. Report findings with file references and risk levels.
My React Flow canvas is slow when I have more than 50 nodes. Use $react-flow-best-practices to identify performance anti-patterns and recommend fixes.
Use $react-flow-best-practices to review canvas accessibility. Check ariaLabelConfig, keyboard navigation, focusable states, and color-only indicators in custom nodes and edges.
Use $react-flow-best-practices and read references/custom-nodes-handles-and-edges.md. Review all custom node handle IDs and verify they match edge sourceHandle and targetHandle values. Flag mismatches and unstable IDs.
Лучшие практики
- Define nodeTypes and edgeTypes outside the render function or memoize them. Inline creation triggers React Flow warnings and can remount custom nodes on every render.
- Use typed Node and Edge generics (Node<Data, Type>) for custom node and edge props to catch data contract mismatches at compile time.
- Always add nodrag to buttons, inputs, and interactive controls inside custom nodes. Add nopan to controls that should not start canvas panning.
Избегать
- Recreating the full nodes or edges array on every data change without preserving user positions, selections, or transient UI state. This fights user interaction.
- Calling fitView in effects that depend on the full nodes array. This overrides user pan and zoom after every data change.
- Hiding handles with display: none CSS. React Flow needs measurable handle dimensions. Use visibility: hidden or opacity: 0 instead.
Часто задаваемые вопросы
Работает ли этот навык со старыми версиями react-flow-renderer?
Может ли этот навык автоматически исправлять ошибки React Flow?
Проверяет ли навык производительность во время выполнения?
Какие проекты получают наибольшую пользу от этого навыка?
Поддерживает ли этот навык подписи ребер с интерактивными элементами управления?
Как проверяется корректность ID хендлов?
Сведения для разработчиков
Автор
JohnWayneeeeЛицензия
MIT
Репозиторий
https://github.com/JohnWayneeee/ai-agent-skills/tree/main/skills/react-flow-best-practicesСсылка
main
Структура файлов