Regenerate all MDC rules with fresh Exa data and December 2025 best practices

- Refreshed all 241 library rules with current best practices
- Updated Exa search results for all libraries with 2025 content
- Fixed --regenerate-all flag logic to properly process all libraries
- Removed duplicate astro entry in rules.json (merged tags)
- Added missing docker.mdc and vim.mdc files
- All rules now include modern patterns and anti-patterns
- Updated with framework-specific recommendations for 2025

Technical improvements:
- Fixed retry_failed_only logic in generate_mdc_files.py
- Improved progress tracking for regeneration scenarios
- Ensured proper handling of --refresh-exa flag
This commit is contained in:
sanjeed5
2025-12-17 22:40:28 +05:30
parent 331fb6ffac
commit 8fbf269085
244 changed files with 66701 additions and 52708 deletions
+317 -213
View File
@@ -1,240 +1,344 @@
---
description: This rule provides guidelines for using CodeMirror effectively, covering code organization, performance, security, testing, and common pitfalls. It aims to ensure robust and maintainable code editor implementations.
globs: *.js,*.ts,*.html,*.css,*.vue,*.svelte,*.jsx,*.tsx
description: This guide defines best practices for building and maintaining CodeMirror 6-based editors, focusing on modularity, immutable state, extension-driven configuration, and modern JavaScript/TypeScript patterns.
globs: **/*.{js,jsx}
---
# CodeMirror Best Practices and Coding Standards
# CodeMirror 6 Best Practices
This document outlines best practices and coding standards for developing text editors and code-related applications using CodeMirror. Adhering to these guidelines will help ensure maintainability, performance, and a positive user experience.
This document outlines the definitive best practices for developing with CodeMirror. We exclusively target **CodeMirror 6 (CM6)**. Any reference to CodeMirror 5 (CM5) is for historical context only; **CM5 must not be used in new development and should be actively migrated away from.**
## 1. Code Organization and Structure
## Code Organization and Structure
### 1.1. Directory Structure
### 1. Always Use CodeMirror 6
* **Project Root:**
* `.cursor/rules/`: (if using cursor rules) stores project-specific rules. Each rule should correspond to a specific aspect of the project or library.
* `src/`: Contains the main source code for your CodeMirror integration.
* `dist/`: Stores the built or compiled output.
* `node_modules/`: Contains project dependencies (managed by npm or yarn).
* `package.json`: Defines project metadata and dependencies.
* `webpack.config.js` or `vite.config.js`: Configuration file for the bundler (if using one).
* `.eslintrc.js`, `.prettierrc.js`: Configuration files for linting and formatting.
* `tests/`: Contains unit, integration, and end-to-end tests.
* `README.md`: Project documentation.
CM6 is a complete rewrite with a modern, modular architecture. It offers superior performance, extensibility, and maintainability. CM5 is deprecated and unsupported.
* **`src/` directory:**
* `components/`: Reusable CodeMirror components (e.g., custom toolbars, panels).
* `modes/`: Custom language modes (if any).
* `addons/`: Custom CodeMirror addons.
* `utils/` or `helpers/`: Utility functions.
* `config/`: Configuration files (e.g., CodeMirror options).
* `styles/`: Custom CSS or styling modules for CodeMirror.
* `index.js` or `index.ts`: Entry point for the CodeMirror integration.
❌ **BAD: Using CodeMirror 5**
### 1.2. File Naming Conventions
```javascript
// Old CM5 global API
var myCodeMirror = CodeMirror(document.body, {
value: "function myScript(){}",
mode: "javascript"
});
```
* **Components:** Use PascalCase (e.g., `EditorToolbar.js`, `SyntaxHighlightingAddon.ts`).
* **Modules:** Use camelCase (e.g., `editorConfig.js`, `stringUtils.ts`).
* **Styles:** Use kebab-case (e.g., `editor-styles.css`, `toolbar-theme.scss`).
* **Test Files:** Append `.test.js` or `.spec.ts` to the corresponding component/module name (e.g., `EditorToolbar.test.js`).
✅ **GOOD: Using CodeMirror 6**
### 1.3. Module Organization
```javascript
import { EditorState } from "@codemirror/state";
import { EditorView, basicSetup } from "codemirror";
import { javascript } from "@codemirror/lang-javascript";
* **Modular Design:** Break down CodeMirror-related functionality into small, reusable modules.
* **Single Responsibility Principle:** Each module should have a clear and specific purpose.
* **Dependency Management:** Explicitly declare dependencies within each module. Use ES modules (`import`/`export`) or CommonJS (`require`/`module.exports`).
* **Avoid Global State:** Minimize the use of global variables or shared mutable state. Pass data and configuration options explicitly to functions and components.
const view = new EditorView({
state: EditorState.create({
doc: "console.log('Hello CM6!');",
extensions: [basicSetup, javascript()],
}),
parent: document.body,
});
```
### 1.4. Component Architecture
### 2. Import Only What You Need (Modular Imports)
* **Presentational and Container Components:** Separate concerns by creating presentational components (responsible for rendering UI) and container components (responsible for data fetching and state management).
* **Component Composition:** Build complex UIs by composing smaller, reusable components.
* **Props and Events:** Use props to pass data down to components and events to communicate actions up to parent components.
CM6 is designed for tree-shaking. Only import the specific packages and modules required to minimize bundle size and improve load times.
### 1.5. Code Splitting
❌ **BAD: Importing monolithic packages (if they existed for CM6)**
* **Dynamic Imports:** Use dynamic imports (`import()`) to load CodeMirror modes and addons on demand.
* **Route-Based Splitting:** If the CodeMirror editor is only used on specific routes in your application, load it only when those routes are visited.
* **Webpack or Vite Configuration:** Configure your bundler to automatically split your code into smaller chunks.
```javascript
// Hypothetical bad example: importing a giant 'codemirror-all' package
import { EditorView, EditorState, basicSetup, javascript, ... } from "codemirror-all";
```
## 2. Common Patterns and Anti-patterns
✅ **GOOD: Granular, specific imports**
### 2.1. Design Patterns
```javascript
import { EditorState } from "@codemirror/state"; // Core state management
import { EditorView, keymap } from "@codemirror/view"; // Core view rendering
import { defaultKeymap } from "@codemirror/commands"; // Standard editing commands
import { javascript } from "@codemirror/lang-javascript"; // Language support
```
* **Observer Pattern:** Use the Observer pattern to notify other parts of the application when the editor's content changes.
* **Strategy Pattern:** Implement different editing strategies based on the selected language mode.
* **Factory Pattern:** Use a factory function to create CodeMirror instances with specific configurations.
### 3. Configure Exclusively via Extensions
### 2.2. Recommended Approaches
All editor features, from basic setup to complex language services, must be added as extensions to the `EditorState`. Avoid direct DOM manipulation or non-extension-based configuration.
❌ **BAD: Direct property assignment or DOM manipulation**
```javascript
const view = new EditorView({ state: EditorState.create({ doc: "" }) });
// Don't do this: Bypassing the extension system
view.dom.style.fontSize = "16px";
```
* **Configuration Objects:** Encapsulate CodeMirror options in a configuration object to improve readability and maintainability.
* **Custom Addons:** Create custom CodeMirror addons to extend the editor's functionality.
* **Event Handling:** Use CodeMirror's event system to respond to user interactions and editor changes.
✅ **GOOD: Everything is an extension**
### 2.3. Anti-patterns
```javascript
import { EditorState } from "@codemirror/state";
import { EditorView, lineNumbers } from "@codemirror/view";
import { oneDark } from "@codemirror/theme-one-dark"; // A theme extension
* **Direct DOM Manipulation:** Avoid directly manipulating the CodeMirror DOM elements. Use the CodeMirror API instead.
* **Overly Complex Modes:** Keep language modes focused and well-structured. Delegate complex parsing logic to external libraries if necessary.
* **Ignoring Performance:** Be mindful of performance implications when adding new features or customizations.
const view = new EditorView({
state: EditorState.create({
doc: "const x = 1;",
extensions: [
lineNumbers(), // Line numbers extension
oneDark, // Theme extension
EditorView.lineWrapping, // Line wrapping extension
EditorState.tabSize.of(2), // Configuration option as an extension
],
}),
parent: document.body,
});
```
### 2.4. State Management
## Common Patterns and Anti-patterns
* **Local State:** Use component state for simple, editor-specific data.
* **Redux or Context API:** For larger applications, consider using a state management library like Redux or the React Context API to manage the editor's state centrally.
* **Immutability:** Treat the editor's state as immutable to simplify debugging and improve performance.
### 4. Embrace Immutable State Management
### 2.5. Error Handling
`EditorState` objects are immutable. All changes must be applied by creating a `Transaction` and dispatching it to the `EditorView`. This enables reliable undo/redo, time-travel debugging, and predictable behavior.
* **Try-Catch Blocks:** Use try-catch blocks to handle potential errors when interacting with the CodeMirror API.
* **Error Boundaries:** In React applications, use error boundaries to catch errors that occur during rendering.
* **Logging:** Log errors and warnings to aid in debugging.
❌ **BAD: Mutating `EditorState` or `Text` directly**
## 3. Performance Considerations
### 3.1. Optimization Techniques
* **Lazy Loading:** Load CodeMirror modes and addons only when they are needed.
* **Debouncing:** Debounce event handlers to prevent excessive updates.
* **Virtualization:** If you are displaying a large number of lines, consider using a virtualization technique to render only the visible lines.
* **Minimize DOM Updates:** Reduce the number of DOM updates by batching changes and using efficient rendering techniques.
### 3.2. Memory Management
* **Remove Event Listeners:** Remove event listeners when components are unmounted to prevent memory leaks.
* **Clear Intervals and Timeouts:** Clear any intervals or timeouts that are no longer needed.
* **Object Reuse:** Reuse objects and data structures whenever possible to reduce memory allocation.
### 3.3. Rendering Optimization
* **ShouldComponentUpdate:** In React applications, use `shouldComponentUpdate` or `React.memo` to prevent unnecessary re-renders.
* **Immutable Data Structures:** Use immutable data structures to efficiently detect changes and trigger re-renders.
### 3.4. Bundle Size Optimization
* **Tree Shaking:** Configure your bundler to remove unused code (tree shaking).
* **Minification:** Minify your code to reduce its size.
* **Gzip Compression:** Use Gzip compression to reduce the size of your assets during transfer.
### 3.5. Lazy Loading Strategies
* **Mode-Specific Loading:** Only load the language mode when the user opens a file of that type.
* **Addon-Specific Loading:** Load addons only when the user needs their functionality.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities
* **Cross-Site Scripting (XSS):** Be careful when displaying user-generated content in the editor. Sanitize the input to prevent XSS attacks.
* **Code Injection:** Avoid using `eval()` or `Function()` to execute untrusted code.
### 4.2. Input Validation
* **Sanitize Input:** Sanitize user input before displaying it in the editor.
* **Validate Data:** Validate data received from external sources before using it in the editor.
### 4.3. Authentication and Authorization
* **Secure APIs:** Use secure APIs for data access and authentication.
* **Role-Based Access Control:** Implement role-based access control to restrict access to sensitive features.
### 4.4. Data Protection
* **Encryption:** Encrypt sensitive data at rest and in transit.
* **Secure Storage:** Store data in a secure location with appropriate access controls.
### 4.5. Secure API Communication
* **HTTPS:** Use HTTPS for all API communication.
* **API Keys:** Protect API keys and prevent them from being exposed in the client-side code.
## 5. Testing Approaches
### 5.1. Unit Testing
* **Test Components:** Unit test individual CodeMirror components and modules.
* **Mock Dependencies:** Mock external dependencies to isolate the components being tested.
* **Assertion Libraries:** Use assertion libraries like Jest or Chai to write expressive tests.
### 5.2. Integration Testing
* **Test Interactions:** Test the interactions between different CodeMirror components and modules.
* **Real DOM:** Use a real DOM environment for integration testing.
### 5.3. End-to-End Testing
* **Simulate User Actions:** Simulate user actions to test the entire CodeMirror workflow.
* **Automated Testing:** Use end-to-end testing frameworks like Cypress or Puppeteer to automate the testing process.
### 5.4. Test Organization
* **Test Directory:** Create a dedicated `tests/` directory for all tests.
* **Test Files:** Place test files alongside the corresponding components/modules.
* **Test Suites:** Organize tests into logical suites based on functionality.
### 5.5. Mocking and Stubbing
* **Mock CodeMirror Instances:** Mock CodeMirror instances to control their behavior during testing.
* **Stub API Calls:** Stub API calls to prevent external dependencies from interfering with the tests.
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes
* **Not Sanitizing User Input:** Failing to sanitize user input can lead to XSS vulnerabilities.
* **Ignoring Performance Issues:** Neglecting performance considerations can result in a slow and unresponsive editor.
* **Direct DOM Manipulation:** Directly manipulating CodeMirror's DOM can break its internal workings.
### 6.2. Edge Cases
* **Handling Large Files:** CodeMirror can struggle with extremely large files. Consider using virtualization or other optimization techniques.
* **Internationalization (i18n):** Ensure that the editor supports different languages and character sets.
* **Accessibility (a11y):** Make the editor accessible to users with disabilities by providing keyboard navigation, screen reader support, and appropriate ARIA attributes.
### 6.3. Version-Specific Issues
* **Check Release Notes:** Review the CodeMirror release notes for any breaking changes or known issues.
* **Test Upgrades:** Thoroughly test CodeMirror upgrades to ensure compatibility with your existing code.
### 6.4. Compatibility Concerns
* **Browser Compatibility:** Test the editor in different browsers to ensure compatibility.
* **Framework Compatibility:** Ensure that CodeMirror integrates correctly with your chosen framework (e.g., React, Vue, Angular).
### 6.5. Debugging Strategies
* **Browser Developer Tools:** Use the browser developer tools to inspect the CodeMirror DOM, network requests, and console output.
* **Logging:** Add logging statements to your code to track the flow of execution and identify potential issues.
* **Debugging Tools:** Use a debugger to step through your code and examine variables.
## 7. Tooling and Environment
### 7.1. Recommended Tools
* **Code Editor:** VS Code, Sublime Text, or Atom with CodeMirror-specific plugins.
* **Bundler:** Webpack, Vite, or Parcel.
* **Linter:** ESLint or JSHint.
* **Formatter:** Prettier.
* **Testing Framework:** Jest, Mocha, or Jasmine.
* **End-to-End Testing Framework:** Cypress or Puppeteer.
### 7.2. Build Configuration
* **Module Bundling:** Use a module bundler to combine your code and dependencies into optimized bundles.
* **Source Maps:** Generate source maps to aid in debugging.
* **Code Optimization:** Configure your build process to optimize code for production (e.g., minification, tree shaking).
### 7.3. Linting and Formatting
* **Consistent Style:** Use a linter and formatter to enforce a consistent coding style.
* **Code Quality:** Configure the linter to catch potential code quality issues (e.g., unused variables, syntax errors).
### 7.4. Deployment Best Practices
* **Optimize Assets:** Optimize your assets (e.g., images, CSS, JavaScript) for production.
* **Content Delivery Network (CDN):** Use a CDN to deliver CodeMirror assets to users from geographically distributed servers.
* **Caching:** Configure browser caching to reduce the number of requests to your server.
### 7.5. CI/CD Integration
* **Automated Builds:** Automate the build process using a CI/CD pipeline.
* **Automated Tests:** Run automated tests as part of the CI/CD pipeline.
* **Deployment Automation:** Automate the deployment process to reduce the risk of errors.
```javascript
let state = EditorState.create({ doc: "hello" });
// This will NOT work as expected and breaks CM6's core design
// state.doc = Text.of("world");
// console.log(state.doc.toString()); // Still "hello"
```
✅ **GOOD: Using `Transaction` and `dispatch`**
```javascript
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
const startState = EditorState.create({ doc: "Hello World" });
const view = new EditorView({ state: startState, parent: document.body });
// Create a transaction to change the document
const transaction = view.state.update({
changes: { from: 0, to: 5, insert: "Goodbye" }, // Change "Hello" to "Goodbye"
selection: { anchor: 7 }, // Move cursor
// Add other state changes like effects or annotations here
});
view.dispatch(transaction); // Apply the transaction
console.log(view.state.doc.toString()); // "Goodbye World"
```
### 5. Prioritize TypeScript for New Code
For new CodeMirror components, always use TypeScript. It provides static type checking, improved IDE support, and reduces runtime errors, leading to more robust and maintainable code.
❌ **BAD: Writing new complex modules in plain JavaScript**
```javascript
// my-complex-cm-plugin.js
export function myComplexPlugin() {
// No type safety, easy to introduce bugs
return ViewPlugin.define(view => ({
update(update) {
if (update.docChanged) {
// What type is update.docChanged?
}
}
}));
}
```
✅ **GOOD: Writing new complex modules in TypeScript**
```typescript
// my-complex-cm-plugin.ts
import { EditorView, ViewPlugin, ViewUpdate } from "@codemirror/view";
import { Extension } from "@codemirror/state";
export function myComplexPlugin(): Extension {
return ViewPlugin.define(view => ({
// Explicitly typed parameters for clarity and safety
update(update: ViewUpdate) {
if (update.docChanged) {
console.log("Document changed:", update.changes.toString());
}
},
}));
}
```
## Performance Considerations
### 6. Batch Editor Updates
Avoid dispatching multiple transactions in quick succession. Group related changes into a single `Transaction` to minimize DOM updates and improve performance.
❌ **BAD: Frequent, unbatched dispatches**
```javascript
// In a loop or event handler
for (let i = 0; i < 100; i++) {
view.dispatch(view.state.update({ changes: { from: i, insert: "a" } }));
}
```
✅ **GOOD: Batching changes into a single transaction**
```javascript
let changes = [];
for (let i = 0; i < 100; i++) {
changes.push({ from: i, insert: "a" });
}
view.dispatch(view.state.update({ changes })); // Single dispatch
```
### 7. Debounce/Throttle External Event Handlers
When external events (e.g., window resize, network responses, user input outside the editor) trigger editor updates or expensive computations, always debounce or throttle them to prevent excessive processing.
```javascript
import { EditorView } from "@codemirror/view";
import { EditorState } from "@codemirror/state";
import { javascript } from "@codemirror/lang-javascript";
const view = new EditorView({
state: EditorState.create({
doc: "function expensiveLint() { /* ... */ }",
extensions: [javascript()],
}),
parent: document.body,
});
// Assume `lintDocument` is an expensive operation
const debouncedLint = debounce(() => {
// Trigger linting based on current editor state
console.log("Linting document...");
}, 500);
// Listen for editor state changes
view.dom.addEventListener("input", debouncedLint);
function debounce(func, delay) {
let timeout;
return function(...args) {
const context = this;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), delay);
};
}
```
## Common Pitfalls and Gotchas
### 8. Never Mix CodeMirror 5 and 6
The architectures are fundamentally different. Attempting to use CM5 add-ons or APIs with a CM6 editor will lead to unpredictable behavior and errors.
❌ **BAD: Using CM5 add-ons with CM6**
```javascript
// This will NOT work with CM6
import "codemirror/addon/search/searchcursor";
```
✅ **GOOD: Use CM6-native extensions**
```javascript
// For search, use CM6's @codemirror/search
import { search, searchKeymap, highlightSelectionMatches } from "@codemirror/search";
import { EditorState } from "@codemirror/state";
import { EditorView, keymap } from "@codemirror/view";
const view = new EditorView({
state: EditorState.create({
doc: "search me",
extensions: [
search(),
keymap.of(searchKeymap),
highlightSelectionMatches(),
],
}),
parent: document.body,
});
```
### 9. Understand Extension Precedence
When multiple extensions affect the same aspect of the editor (e.g., keymaps, decorations), their order in the `extensions` array and explicit `Prec` modifiers determine precedence. Debug carefully if an extension isn't behaving as expected.
```javascript
import { EditorState, Prec } from "@codemirror/state";
import { EditorView, keymap } from "@codemirror/view";
import { defaultKeymap } from "@codemirror/commands";
// A custom keymap that should override default behavior
const myCustomKeymap = keymap.of([
{
key: "Mod-s",
run: (view) => {
console.log("Custom save action!");
return true; // Indicate that the event was handled
},
},
]);
const view = new EditorView({
state: EditorState.create({
doc: "Press Cmd-S",
extensions: [
defaultKeymap, // Default keymap is defined first
Prec.highest(myCustomKeymap), // Custom keymap with highest precedence will override
],
}),
parent: document.body,
});
```
## Testing Approaches
### 10. Unit Test `EditorState` Logic
Isolate and unit test functions that operate on or produce `EditorState` objects. Since `EditorState` is immutable, these functions are pure and easy to test without a browser environment.
```javascript
// my-state-transformer.js
import { EditorState } from "@codemirror/state";
export function addCommentToLine(state, lineNumber, commentText) {
const line = state.doc.line(lineNumber);
return state.update({
changes: { from: line.from, insert: `// ${commentText}\n` + line.text },
});
}
// my-state-transformer.test.js
import { EditorState } from "@codemirror/state";
import { addCommentToLine } from "./my-state-transformer";
test("addCommentToLine adds comment correctly", () => {
const initialState = EditorState.create({ doc: "line 1\nline 2" });
const newState = addCommentToLine(initialState, 2, "My comment");
expect(newState.doc.toString()).toBe("line 1\n// My comment\nline 2");
});
```
### 11. Use End-to-End Tests for `EditorView` Interactions
For testing UI interactions (typing, selection, scrolling, extension rendering), use browser-based end-to-end testing frameworks like Playwright or Cypress. These simulate real user behavior.
```javascript
// playwright.test.js (conceptual example)
import { test, expect } from "@playwright/test";
test("editor displays line numbers and allows typing", async ({ page }) => {
await page.goto("http://localhost:3000/editor"); // Your app's editor page
const editor = page.locator(".cm-editor");
await expect(editor).toBeVisible();
// Check if line numbers are visible
await expect(page.locator(".cm-lineNumbers")).toBeVisible();
// Type into the editor
await editor.type("Hello, CodeMirror!");
await expect(editor).toHaveText(/Hello, CodeMirror!/);
});
```