### Basic JavaScript Editor Setup Source: https://github.com/codemirror/lang-javascript/blob/main/src/README.md Use this snippet to initialize a CodeMirror editor with basic JavaScript support. Ensure you have imported the necessary modules. ```javascript import {EditorView, basicSetup} from "codemirror" import {javascript} from "@codemirror/lang-javascript" const view = new EditorView({ parent: document.body, doc: `console.log("Hello world")`, extensions: [basicSetup, javascript()] }) ``` -------------------------------- ### ESLint Integration for JavaScript Linting Source: https://context7.com/codemirror/lang-javascript/llms.txt Integrate ESLint into CodeMirror for real-time linting of JavaScript code. This setup provides diagnostics with severity levels, source information, and auto-fix actions directly within the editor. It requires an ESLint Linter instance and can be configured with custom ESLint rules. ```javascript import { EditorView, basicSetup } from "codemirror" import { javascript, esLint } from "@codemirror/lang-javascript" import { linter, lintGutter } from "@codemirror/lint" // Note: Use eslint-linter-browserify for browser usage import { Linter } from "eslint-linter-browserify" const eslintInstance = new Linter() // Use with default recommended rules const defaultLintSource = esLint(eslintInstance) // Or provide custom ESLint configuration const customConfig = { parserOptions: { ecmaVersion: 2022, sourceType: "module", ecmaFeatures: { jsx: true } }, env: { browser: true, es2022: true }, rules: { "no-unused-vars": "warn", "no-undef": "error", "semi": ["error", "always"], "quotes": ["warn", "double"], "no-console": "warn", "eqeqeq": ["error", "always"], "curly": ["error", "all"], "no-var": "error", "prefer-const": "warn" } } const customLintSource = esLint(eslintInstance, customConfig) const editor = new EditorView({ parent: document.getElementById("editor"), doc: `// This code has several lint issues: var unusedVar = "test" // no-var, no-unused-vars let x = 1 if (x == 1) console.log("equal") // eqeqeq, curly, no-console function example(a, b) { let result = a + b return result } // Missing semicolons will be flagged const y = 2 // Undeclared variables will be errors console.log(undeclaredVariable)`, extensions: [ basicSetup, javascript({ jsx: true }), linter(customLintSource), lintGutter() ] }) // ESLint diagnostics appear with: // - Severity: "error" (red) or "warning" (yellow) // - Source: "eslint:rule-name" // - Fix actions when auto-fixable (click to apply) ``` -------------------------------- ### Global Scope Autocompletion for JavaScript Source: https://context7.com/codemirror/lang-javascript/llms.txt Configure CodeMirror's JavaScript language support to provide autocompletions from the global scope (e.g., browser globals like `console`, `document`, `Math`, `JSON`). This setup enables intelligent suggestions as the user types. ```javascript import { EditorView, basicSetup } from "codemirror" import { javascriptLanguage, scopeCompletionSource } from "@codemirror/lang-javascript" import { LanguageSupport } from "@codemirror/language" // Complete from globalThis (browser globals) const globalCompletion = scopeCompletionSource(globalThis) const jsWithGlobals = new LanguageSupport(javascriptLanguage, [ javascriptLanguage.data.of({ autocomplete: globalCompletion }) ]) const editor = new EditorView({ parent: document.getElementById("editor"), doc: `// Type \ ``` ```javascript // Type \ ``` -------------------------------- ### Basic JavaScript Support in CodeMirror Source: https://context7.com/codemirror/lang-javascript/llms.txt Integrates basic JavaScript language support into a CodeMirror editor. Requires importing `basicSetup` and `javascript`. ```javascript import { EditorView, basicSetup } from "codemirror" import { javascript } from "@codemirror/lang-javascript" // Basic JavaScript support const jsEditor = new EditorView({ parent: document.getElementById("js-editor"), doc: `function greet(name) { console.log("Hello, " + name) } greet("World")`, extensions: [basicSetup, javascript()] }) ``` -------------------------------- ### Custom API Completion with `completionPath` Helper Source: https://context7.com/codemirror/lang-javascript/llms.txt Builds a custom autocompletion source for API structures using the `completionPath` helper. It analyzes the cursor position to provide context-aware suggestions for nested properties and functions. ```javascript import { EditorView, basicSetup } from "codemirror" import { javascriptLanguage, completionPath } from "@codemirror/lang-javascript" import { LanguageSupport } from "@codemirror/language" import { autocompletion, CompletionContext, Completion } from "@codemirror/autocomplete" // Custom completion source using completionPath function customApiCompletion(context) { const path = completionPath(context) if (!path) return null // Define your API structure const apiStructure = { api: { users: { getAll: "function", getById: "function", create: "function", delete: "function" }, posts: { list: "function", get: "function", publish: "function" }, auth: { login: "function", logout: "function", refresh: "function" } }, config: { baseUrl: "property", timeout: "property", headers: "property" } } // Navigate to the right object based on path let current = apiStructure for (const step of path.path) { current = current[step] if (!current) return null } // Generate completions const options = Object.entries(current).map(([name, type]) => ({ label: name, type: typeof type === "string" ? type : "variable" })) return { from: context.pos - path.name.length, options: options.filter(opt => opt.label.startsWith(path.name)) } } // Example usage const jsWithCustomCompletion = new LanguageSupport(javascriptLanguage, [ javascriptLanguage.data.of({ autocomplete: customApiCompletion }) ]) const editor = new EditorView({ parent: document.getElementById("editor"), doc: `// Type "api." to see: users, posts, auth // Type "api.users." to see: getAll, getById, create, delete // Type "config." to see: baseUrl, timeout, headers const users = await api.users.getAll() const post = await api.posts.get(postId) await api.auth.login(credentials) console.log(config.baseUrl)`, extensions: [basicSetup, jsWithCustomCompletion] }) // Using completionPath in a completion context manually function demonstrateCompletionPath(context) { const result = completionPath(context) if (result) { console.log("Path:", result.path) // e.g., ["api", "users"] console.log("Name:", result.name) // e.g., "get" (partial input) } return null } ``` -------------------------------- ### esLint Source: https://github.com/codemirror/lang-javascript/blob/main/README.md Connects an ESLint linter to CodeMirror's lint integration. It takes an ESLint Linter instance and an optional configuration, returning a function that generates diagnostics. ```APIDOC ## esLint ### Description Connects an ESLint linter to CodeMirror's lint integration. `eslint` should be an instance of the `Linter` class, and `config` an optional ESLint configuration. The return value of this function can be passed to `linter` to create a JavaScript linting extension. Note that ESLint targets node, and is tricky to run in the browser. The `eslint-linter-browserify` package may help with that. ### Method N/A (Function Definition) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **Diagnostic[]** (array) - An array of linting diagnostics. #### Response Example N/A ``` -------------------------------- ### Enable Local Variable Completion in JavaScript Source: https://context7.com/codemirror/lang-javascript/llms.txt Integrates local variable and function completion into the JavaScript language support. Requires importing `localCompletionSource` and adding it to the editor's extensions. ```javascript import { EditorView, basicSetup } from "codemirror" import { javascriptLanguage, localCompletionSource } from "@codemirror/lang-javascript" import { LanguageSupport } from "@codemirror/language" import { autocompletion } from "@codemirror/autocomplete" // Create editor with local completion enabled const jsWithLocalCompletion = new LanguageSupport(javascriptLanguage, [ javascriptLanguage.data.of({ autocomplete: localCompletionSource }) ]) const editor = new EditorView({ parent: document.getElementById("editor"), doc: `function processData(inputData, options) { const processedItems = [] const errorCount = 0 for (const item of inputData) { const transformed = transformItem(item) // Type "pro" here to see completions for: // - processedItems (local variable) // - processData (function name) // Type "opt" to see completion for: // - options (function parameter) // Type "err" to see completion for: // - errorCount (local variable) } return { processedItems, errorCount } } class DataProcessor { constructor(config) { this.config = config this.cache = new Map() } process(data) { // Type "con" to see completion for config // Type "cac" to see completion for cache // Type "dat" to see completion for data parameter } }`, extensions: [basicSetup, jsWithLocalCompletion] }) ``` -------------------------------- ### completionPath Source: https://github.com/codemirror/lang-javascript/blob/main/README.md Helper function for defining JavaScript completion sources. Returns the completable name and object path. ```APIDOC ## completionPath(context: CompletionContext) ### Description Helper function for defining JavaScript completion sources. It returns the completable name and object path for a completion context, or null if no name/property completion should happen at that position. For example, when completing after `a.b.c` it will return `{path: ["a", "b"], name: "c"}`. When completing after `x` it will return `{path: [], name: "x"}`. When not in a property or name, it will return null if `context.explicit` is false, and `{path: [], name: ""}` otherwise. ### Method N/A (Function) ### Parameters #### Path Parameters - **context** (CompletionContext) - Required - The completion context. ### Response #### Success Response (200) - **{path: string[], name: string} | null** - An object containing the path and name, or null. ``` -------------------------------- ### scopeCompletionSource Source: https://github.com/codemirror/lang-javascript/blob/main/README.md Defines a completion source that completes from the given scope object (e.g., globalThis). It enters properties of the object when completing properties on a directly-named path. ```APIDOC ## scopeCompletionSource ### Description Defines a completion source that completes from the given scope object (for example `globalThis`). Will enter properties of the object when completing properties on a directly-named path. ### Method N/A (Function Definition) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **CompletionSource** (object) - A CodeMirror CompletionSource. #### Response Example N/A ``` -------------------------------- ### localCompletionSource Source: https://github.com/codemirror/lang-javascript/blob/main/README.md Completion source that looks up locally defined names in JavaScript code. ```APIDOC ## localCompletionSource(context: CompletionContext) ### Description Completion source that looks up locally defined names in JavaScript code. ### Method N/A (Function) ### Parameters #### Path Parameters - **context** (CompletionContext) - Required - The completion context. ### Response #### Success Response (200) - **CompletionResult | null** - The completion result or null. ``` -------------------------------- ### javascript Source: https://github.com/codemirror/lang-javascript/blob/main/README.md Provides JavaScript language support, including snippet and local variable completion. ```APIDOC ## javascript(config?: {jsx?: boolean, typescript?: boolean}) ### Description Provides JavaScript language support, including snippet and local variable completion. ### Method N/A (Function) ### Parameters #### Query Parameters - **config** (object) - Optional - Configuration object. - **jsx** (boolean) - Optional - Enable JSX support. - **typescript** (boolean) - Optional - Enable TypeScript support. ### Response #### Success Response (200) - **LanguageSupport** - The language support extension. ``` -------------------------------- ### javascript() - Main Language Support Function Source: https://context7.com/codemirror/lang-javascript/llms.txt The main entry point for adding JavaScript language support to a CodeMirror editor. It bundles parser, syntax highlighting, autocompletion, and optional JSX auto-closing tags. Configure with options to enable TypeScript and/or JSX dialects. ```APIDOC ## javascript() ### Description Provides comprehensive JavaScript language support for CodeMirror 6, including syntax highlighting, code folding, indentation, bracket closing, and autocompletion. It can be configured to support TypeScript and JSX. ### Method `javascript(options?: { typescript?: boolean, jsx?: boolean })` ### Parameters #### Options - **typescript** (boolean) - Optional - Enables TypeScript dialect support. - **jsx** (boolean) - Optional - Enables JSX dialect support. ### Request Example ```javascript import { javascript } from "@codemirror/lang-javascript" // Basic JavaScript support let extensions = [ javascript() ] // TypeScript support let tsExtensions = [ javascript({ typescript: true }) ] // JSX support let jsxExtensions = [ javascript({ jsx: true }) ] // TSX support let tsxExtensions = [ javascript({ typescript: true, jsx: true }) ] ``` ### Response Returns a `LanguageSupport` object that bundles the parser, syntax highlighting, autocompletion, and other language-aware features. ``` -------------------------------- ### snippets Source: https://github.com/codemirror/lang-javascript/blob/main/README.md A collection of JavaScript-related snippets. ```APIDOC ## snippets ### Description A collection of JavaScript-related snippets. ### Method N/A (Constant) ### Endpoint N/A ### Response #### Success Response (200) - **Completion[]** - An array of JavaScript snippet completions. ``` -------------------------------- ### typescriptLanguage Source: https://github.com/codemirror/lang-javascript/blob/main/README.md A language provider for TypeScript. ```APIDOC ## typescriptLanguage ### Description A language provider for TypeScript. ### Method N/A (Constant) ### Endpoint N/A ### Response #### Success Response (200) - **LRLanguage** - The TypeScript language provider. ``` -------------------------------- ### javascriptLanguage Source: https://github.com/codemirror/lang-javascript/blob/main/README.md A language provider based on the Lezer JavaScript parser, extended with highlighting and indentation information. ```APIDOC ## javascriptLanguage ### Description A language provider based on the Lezer JavaScript parser, extended with highlighting and indentation information. ### Method N/A (Constant) ### Endpoint N/A ### Response #### Success Response (200) - **LRLanguage** - The Lezer JavaScript language provider. ``` -------------------------------- ### jsxLanguage Source: https://github.com/codemirror/lang-javascript/blob/main/README.md Language provider for JSX. ```APIDOC ## jsxLanguage ### Description Language provider for JSX. ### Method N/A (Constant) ### Endpoint N/A ### Response #### Success Response (200) - **LRLanguage** - The JSX language provider. ``` -------------------------------- ### Custom JavaScript Autocompletion in CodeMirror Source: https://context7.com/codemirror/lang-javascript/llms.txt Extends the base JavaScript language support with custom autocompletion suggestions using `completeFromList`. This allows for tailored suggestions beyond the default ones. ```javascript import { EditorView, basicSetup } from "codemirror" import { javascriptLanguage } from "@codemirror/lang-javascript" import { LanguageSupport } from "@codemirror/language" import { completeFromList } from "@codemirror/autocomplete" // Create custom JavaScript support with additional completions const customCompletions = completeFromList([ { label: "console", type: "variable" }, { label: "document", type: "variable" }, { label: "window", type: "variable" }, { label: "fetch", type: "function" }, { label: "setTimeout", type: "function" }, { label: "setInterval", type: "function" } ]) const customJSSupport = new LanguageSupport(javascriptLanguage, [ javascriptLanguage.data.of({ autocomplete: customCompletions }) ]) const editor = new EditorView({ parent: document.getElementById("editor"), doc: `// Start typing to see custom completions const element = document.getElementById("app") fetch("/api/data").then(res => res.json())`, extensions: [basicSetup, customJSSupport] }) // Check if JavaScript language is active at a position const isJSActive = javascriptLanguage.isActiveAt(editor.state, 0, -1) console.log("JavaScript active:", isJSActive) // true ``` -------------------------------- ### JSX (React) Support in CodeMirror Source: https://context7.com/codemirror/lang-javascript/llms.txt Adds JSX syntax highlighting and features for React development by configuring `javascript` with `{ jsx: true }`. This enables support for React components and JSX syntax. ```javascript import { EditorView, basicSetup } from "codemirror" import { javascript } from "@codemirror/lang-javascript" // JSX support (React) const jsxEditor = new EditorView({ parent: document.getElementById("jsx-editor"), doc: `function App() { return (
$\ {product.price.toFixed(2)}
{/* Quantity selector */} setQuantity(parseInt(e.target.value))} min={1} />| {col.header} | ))}
|---|
| {col.render ? col.render(item[col.key], item) : String(item[col.key])} | ))}