### Example VSCode Extension Setup Function Source: https://kermanx.com/reactive-vscode/guide/extension Illustrates a comprehensive setup function for a VSCode extension using `reactive-vscode`. It demonstrates registering a logger, handling a command (`reactive-vscode-demo.helloWorld`), reacting to theme changes with `watchEffect`, and integrating a custom TreeView. This function defines the extension's behavior upon activation. ```typescript import { defineExtension, useCommand, useIsDarkTheme, useLogger, watchEffect } from 'reactive-vscode' import { window } from 'vscode' import { useDemoTreeView } from './treeView' export = defineExtension (() => { const logger = useLogger ('Reactive VSCode') logger . info ('Extension Activated') logger . show () useCommand ('reactive-vscode-demo.helloWorld', () => { window. showInformationMessage ( message . value ) }) const isDark = useIsDarkTheme () watchEffect (() => { logger . info ('Is Dark Theme:', isDark .value) }) useDemoTreeView () }) ``` -------------------------------- ### VSCode Extension with Standard API for Decorations Source: https://kermanx.com/reactive-vscode/index This example illustrates creating a VSCode extension using the standard `vscode` API. It defines a `TextEditorDecorationType` and manages decorations based on workspace configuration changes and active text editor events. This serves as a baseline for comparison with the reactive approach. ```ts import type { ExtensionContext } from 'vscode' import { window, workspace } from 'vscode' const decorationType = window. createTextEditorDecorationType ({ backgroundColor : 'red', }) function updateDecorations ( enabled : boolean) { window. activeTextEditor ?. setDecorations ( decorationType , enabled ? [/* ... Caclulated ranges ... */] : [], ) } export function activate ( context : ExtensionContext) { const configurations = workspace. getConfiguration ('demo') let decorationsEnabled = configurations . get ('decorations')! context . subscriptions . push (workspace. onDidChangeConfiguration (( e ) => { if ( e . affectsConfiguration ('demo.decorations')) { decorationsEnabled = configurations . get ('decorations')! updateDecorations ( decorationsEnabled ) } })) context . subscriptions . push (window. onDidChangeActiveTextEditor (() => { updateDecorations ( decorationsEnabled ) })) updateDecorations ( decorationsEnabled ) } ``` -------------------------------- ### Define Extension Setup with Tree View Source: https://kermanx.com/reactive-vscode/guide/view Initializes the VSCode extension by calling the composable function to register the Tree View. This code should be executed within the extension's setup function to ensure the VSCode extension context is available. ```typescript import { defineExtension } from 'reactive-vscode' import { useDemoTreeView } from './treeView' export = defineExtension (() => { const demoTreeView = useDemoTreeView () // ... }) ``` -------------------------------- ### Develop and Debug Reactive VSCode Extension Source: https://kermanx.com/reactive-vscode/guide Commands to build and run your Reactive VSCode extension during development. 'pnpm dev' (or npm/yarn equivalents) builds the extension, and then pressing F5 in VSCode starts the debugging session in a new window. ```bash pnpm dev ``` ```bash npm run dev ``` ```bash yarn dev ``` -------------------------------- ### Reactive VSCode: Counter Extension Source: https://kermanx.com/reactive-vscode/examples/hello-counter Implements a counter extension using Reactive VSCode's defineExtension, ref, useCommands, and useStatusBarItem. It registers commands to increment/decrement a counter and displays it in the status bar. ```typescript import { defineExtension, ref, useCommands, useStatusBarItem } from 'reactive-vscode' import { StatusBarAlignment } from 'vscode' export = defineExtension(() => { const counter = ref(0) useStatusBarItem({ alignment: StatusBarAlignment.Right, priority: 100, text: () => `$(megaphone) Hello*${counter.value}`, }) useCommands({ 'extension.sayHello': () => counter.value++, 'extension.sayGoodbye': () => counter.value--, }) }) ``` -------------------------------- ### Original VSCode API: Counter Extension Source: https://kermanx.com/reactive-vscode/examples/hello-counter Implements a counter extension using the original VSCode API. It manually creates a status bar item and registers commands using commands.registerCommand, updating the status bar on each command execution. ```typescript import type { ExtensionContext } from 'vscode' import { commands, StatusBarAlignment, window } from 'vscode' export function activate(extensionContext: ExtensionContext) { let counter = 0 const item = window.createStatusBarItem(StatusBarAlignment.Right, 100) function updateStatusBar() { item.text = `$(megaphone) Hello*${counter}` item.show() } updateStatusBar() extensionContext.subscriptions.push( commands.registerCommand('extension.sayHello', () => { counter++ updateStatusBar() }), commands.registerCommand('extension.sayGoodbye', () => { counter-- updateStatusBar() }) ) } ``` -------------------------------- ### Define VSCode Extension with Reactive API Source: https://kermanx.com/reactive-vscode/index This snippet demonstrates how to define a VSCode extension using the Reactive VSCode API's `defineConfigs` and `defineExtension` functions. It utilizes `useActiveEditorDecorations` to manage editor decorations based on configuration values, showcasing a reactive approach to extension development. ```ts import { defineConfigs , defineExtension , useActiveEditorDecorations } from 'reactive-vscode' const { decorations } = defineConfigs ('demo', { decorations : Boolean }) export = defineExtension (() => { useActiveEditorDecorations ( { backgroundColor : 'red', }, () => decorations . value ? [/* ... Caclulated ranges ... */] : [], ) }) ``` -------------------------------- ### Install @reactive-vscode/vueuse with npm Source: https://kermanx.com/reactive-vscode/guide/vueuse Installs the @reactive-vscode/vueuse package as a development dependency using the npm package manager. This package provides Node.js-compatible VueUse functions for VSCode extension development. ```bash npm install -D @reactive-vscode/vueuse ``` -------------------------------- ### Install @reactive-vscode/vueuse with pnpm Source: https://kermanx.com/reactive-vscode/guide/vueuse Installs the @reactive-vscode/vueuse package as a development dependency using the pnpm package manager. This package provides Node.js-compatible VueUse functions for VSCode extension development. ```bash pnpm install -D @reactive-vscode/vueuse ``` -------------------------------- ### Install @reactive-vscode/vueuse with yarn Source: https://kermanx.com/reactive-vscode/guide/vueuse Installs the @reactive-vscode/vueuse package as a development dependency using the yarn package manager. This package provides Node.js-compatible VueUse functions for VSCode extension development. ```bash yarn add -D @reactive-vscode/vueuse ``` -------------------------------- ### Use Configuration as an Object in Extension Source: https://kermanx.com/reactive-vscode/guide/config This TypeScript snippet illustrates using the `defineConfigObject` function from `reactive-vscode` to access extension settings as a reactive object. It shows how to get and set configuration values directly on the object and use the `$update` method for more options. ```typescript import { defineConfigObject } from 'reactive-vscode' const config = defineConfigObject ('your-extension', { enable : Boolean , greeting : [ String , null], }) ``` ```typescript import { ConfigurationTarget } from 'vscode' // This will write the value back to the configuration. config . enable = false // To pass the rest of the options, you can use the `$update` method. config . $update ('enable', false, ConfigurationTarget . Global ) // Only set the ref value without writing back to the configuration. config . $set ('enable', false) ``` -------------------------------- ### Watch File System Changes in VSCode (TypeScript) Source: https://kermanx.com/reactive-vscode/guide/window This example demonstrates how to use the `useFsWatcher` composable to monitor changes in specific files within the VSCode workspace. It defines files to watch using `computed` and sets up an `onDidChange` handler to log the URI of any changed file, facilitating real-time file updates. ```typescript import { computed, defineExtension, useFsWatcher, watchEffect } from 'reactive-vscode' export = defineExtension(() => { const filesToWatch = computed(() => ['**/*.md', '**/*.txt']) const watcher = useFsWatcher(filesToWatch) watcher.onDidChange((uri) => { console.log('File changed:', uri) }) }) ``` -------------------------------- ### Access VSCode Theme and React to Changes (TypeScript) Source: https://kermanx.com/reactive-vscode/guide/window This snippet demonstrates how to use `useActiveColorTheme` and `useIsDarkTheme` to get the current VSCode theme and its dark/light status. It then uses `watchEffect` to post a message to a webview whenever the theme changes, allowing the webview to update its styles accordingly. ```typescript import { defineExtension, useActiveColorTheme, useIsDarkTheme, watchEffect } from 'reactive-vscode' import { useDemoWebviewView } from './webviewView' export = defineExtension(() => { const theme = useActiveColorTheme() const isDark = useIsDarkTheme() const webviewView = useDemoWebviewView() watchEffect(() => { webviewView.postMessage({ type: 'updateTheme', isDark: isDark.value, }) }) }) ``` -------------------------------- ### Get VSCode Window State and Log Changes (TypeScript) Source: https://kermanx.com/reactive-vscode/guide/window This code illustrates how to use the `useWindowState` composable to retrieve the window's active and focused states. It then employs `watchEffect` to log these states to the console whenever they change, enabling the extension to react to user interaction with the VSCode window. ```typescript import { defineExtension, useWindowState, watchEffect } from 'reactive-vscode' export = defineExtension(() => { const { active: isWindowActive, focused: isWindowFocused } = useWindowState() watchEffect(() => { console.log('Window is active:', isWindowActive.value) console.log('Window is focused:', isWindowFocused.value) }) }) ``` -------------------------------- ### Get Document Text using useDocumentText - TypeScript Source: https://kermanx.com/reactive-vscode/guide/editor Demonstrates how to use the `useDocumentText` composable to retrieve the text content of the active editor's document. It utilizes `useActiveTextEditor` to get the editor instance and `ref` and `watchEffect` for reactive updates. The text can be dynamically set based on other reactive variables. ```typescript import type { ExtensionContext } from 'vscode' import { computed, defineExtension, ref, useActiveTextEditor, useDocumentText, watchEffect } from 'reactive-vscode' export = defineExtension(() => { const editor = useActiveTextEditor() const text = useDocumentText(() => editor.value?.document) // Reactive, may be set from other places const name = ref('John Doe') watchEffect(() => { text.value = `Hello, ${name.value}!` }) }) ``` -------------------------------- ### Reactive API for VS Code Debugger Source: https://kermanx.com/reactive-vscode/functions Provides reactive access to the active debug session in VS Code. This allows your extension to monitor and react to changes in the debugging state, such as when a session starts or stops. It wraps `debug.activeDebugSession`. ```typescript import { useActiveDebugSession } from '@reactive-vscode/reactive-vscode'; const activeDebugSession = useActiveDebugSession(); autorun(() => { if (activeDebugSession.value) { console.log('Active debug session started:', activeDebugSession.value.name); console.log('Session type:', activeDebugSession.value.type); } else { console.log('No active debug session.'); } }); ``` -------------------------------- ### Get All Opened VSCode Terminals with reactive-vscode Source: https://kermanx.com/reactive-vscode/guide/terminal Demonstrates how to obtain a reactive list of all currently open VSCode terminals using the `useOpenedTerminals` composable. This returns a `ShallowRef` containing an array of all `Terminal` objects. ```typescript import { defineExtension, useOpenedTerminals } from 'reactive-vscode' export = defineExtension (() => { const terminals = useOpenedTerminals () }) ``` -------------------------------- ### Reactive API for VS Code Text Document Content Source: https://kermanx.com/reactive-vscode/functions Offers a reactive way to get the text content of a VS Code `TextDocument`. This is useful for components that need to monitor and react to changes in a document's text. It wraps `TextDocument.getText`. ```typescript import { useDocumentText, useActiveEditor } from '@reactive-vscode/reactive-vscode'; import { TextDocument } from 'vscode'; const activeEditor = useActiveEditor(); let documentText: ReturnType | undefined; autorun(() => { if (activeEditor.value) { const doc = activeEditor.value.document; // Use useDocumentText with the specific document documentText = useDocumentText(doc); console.log('Document text:', documentText.value); } else { documentText = undefined; console.log('No active editor, no document text.'); } }); // Example: React to changes in the document text autorun(() => { if (documentText?.value) { console.log('Document content has changed or is available:', documentText.value.length, 'characters.'); } }); ``` -------------------------------- ### Create New Reactive VSCode Project Source: https://kermanx.com/reactive-vscode/guide Initialize a new VS Code extension project using the reactive-vscode scaffolding. This command-line tool sets up the basic project structure and dependencies required for developing reactive VS Code extensions. ```bash pnpm create reactive-vscode ``` ```bash npm init reactive-vscode@latest ``` ```bash yarn create reactive-vscode ``` -------------------------------- ### Get VSCode Terminal State with reactive-vscode Source: https://kermanx.com/reactive-vscode/guide/terminal Explains how to get the state of a specific VSCode terminal using the `useTerminalState` composable. It can be used with the active terminal or any terminal obtained from `useOpenedTerminals`, returning a `ComputedRef` of the `TerminalState`. ```typescript import { defineExtension, useActiveTerminal, useOpenedTerminals, useTerminalState } from 'reactive-vscode' export = defineExtension (() => { const activeTerminal = useActiveTerminal () const activeTerminalState = useTerminalState ( activeTerminal ) const allTerminals = useOpenedTerminals () const firstTerminalState = useTerminalState (() => allTerminals .value[0]) }) ``` -------------------------------- ### Define VS Code Extension Entry Point Source: https://kermanx.com/reactive-vscode/guide Defines the main entry point for a VS Code extension using the `defineExtension` function from the `reactive-vscode` library. This function is used to initialize and configure the extension's behavior. ```typescript import { defineExtension } from 'reactive-vscode' export = defineExtension (() => { // Setup your extension here }) ``` -------------------------------- ### Implement VSCode FS Watcher with VSCode API Source: https://kermanx.com/reactive-vscode/examples/fs-watcher This snippet demonstrates how to implement a file system watcher using the native VSCode API. It manages multiple watchers and allows adding/removing patterns through commands. The function 'activate' sets up initial watchers, and 'deactivate' disposes of them. Dependencies include 'vscode'. ```typescript import type { ExtensionContext, FileSystemWatcher, Uri } from 'vscode' import { commands, window, workspace } from 'vscode' const watchers = new Map () function addPattern ( pattern : string) { if (! watchers . has ( pattern )) { const watcher = workspace. createFileSystemWatcher ( pattern ) watcher . onDidChange (( uri : Uri ) => window. showInformationMessage (`File changed: ${ uri }`)) watchers . set ( pattern , watcher ) } } function removePattern ( pattern : string) { const watcher = watchers . get ( pattern ) if ( watcher ) { watcher . dispose () watchers . delete ( pattern ) } } export function activate ( extensionContext : ExtensionContext) { addPattern ('src/**/*') addPattern ('docs/**/*') extensionContext . subscriptions . push ( commands. registerCommand ('demo.add-watch-dir', async () => { const value = await window. showInputBox ({ prompt : 'Enter a glob' }) if ( value ) addPattern ( value ) }), commands. registerCommand ('demo.remove-watch-dir', async () => { const value = await window. showInputBox ({ prompt : 'Enter a glob' }) if ( value ) removePattern ( value ) }), ) } export function deactivate () { for (const watcher of watchers . values ()) { watcher . dispose () } } ``` -------------------------------- ### Define Configuration in package.json Source: https://kermanx.com/reactive-vscode/guide/config This snippet shows how to define extension-specific settings within the `package.json` file using the `contributes.configuration` field. It includes properties like 'myExtension.enable' and 'myExtension.greeting' with their types, default values, and descriptions. ```json { "contributes": { "configuration": { "title": "My Extension", "properties": { "myExtension.enable": { "type": "boolean", "default": true, "description": "Enable My Extension" }, "myExtension.greeting": { "type": ["string", "null"], "default": "Hello!", "description": "Greeting messag. Set to null to disable" } } } } } ``` -------------------------------- ### Get the Active VSCode Terminal with reactive-vscode Source: https://kermanx.com/reactive-vscode/guide/terminal Shows how to retrieve the currently active VSCode terminal using the `useActiveTerminal` composable. This provides reactive access to the `Terminal` object representing the terminal that currently has focus. ```typescript import { defineExtension, useActiveTerminal } from 'reactive-vscode' export = defineExtension (() => { const activeTerminal = useActiveTerminal () }) ``` -------------------------------- ### Register and Execute VS Code Commands Reactively Source: https://kermanx.com/reactive-vscode/functions Provides reactive functions to register and execute VS Code commands. This includes registering single or multiple commands, text editor specific commands, and type-safe execution of commands. It leverages VS Code's `commands.registerCommand` and `commands.executeCommand` APIs. ```typescript import { useCommand, useCommands, useTextEditorCommand, useTextEditorCommands, executeCommand } from '@reactive-vscode/reactive-vscode'; // Register a single command useCommand('myExtension.myCommand', async (args: any[]) => { console.log('Command executed with args:', args); }); // Register multiple commands useCommands({ 'myExtension.command1': () => { /* ... */ }, 'myExtension.command2': () => { /* ... */ } }); // Register a text editor command useTextEditorCommand('myExtension.editorCommand', async (editor, args) => { console.log('Text editor command executed on:', editor.document.fileName); }); // Register multiple text editor commands useTextEditorCommands({ 'myExtension.editorCommand1': async (editor, args) => { /* ... */ }, 'myExtension.editorCommand2': async (editor, args) => { /* ... */ } }); // Execute a command with type checking async function runCommand() { const result = await executeCommand('some.existing.command', ['arg1', 123]); console.log('Command result:', result); } ``` -------------------------------- ### Utilities for File Paths and URIs in VS Code Source: https://kermanx.com/reactive-vscode/functions Provides reactive utilities for handling file paths and URIs within VS Code extensions. This includes converting extension-relative paths to absolute paths and creating file URIs. It leverages `ExtensionContext.asAbsolutePath` and `Uri.file`. ```typescript import { useAbsolutePath, useFileUri, asAbsolutePath } from '@reactive-vscode/reactive-vscode'; import { ExtensionContext } from 'vscode'; // Use the reactive version of asAbsolutePath const absolutePath = useAbsolutePath('path/to/your/file.txt'); console.log('Absolute Path (reactive):', absolutePath.value); // Use the shorthand version of asAbsolutePath const shorthandAbsolutePath = asAbsolutePath('another/file.json'); console.log('Absolute Path (shorthand):', shorthandAbsolutePath); // Create a reactive file URI const fileUri = useFileUri('/path/to/some/document.md'); console.log('File URI:', fileUri.value); // Example usage with ExtensionContext (assuming context is available) function getPathFromContext(context: ExtensionContext) { // If you need to use the context directly, you might pass it or access it globally // For reactive usage, use the hook directly if possible within a component context const contextAbsolutePath = useAbsolutePath('data/config.json'); console.log('Path from context:', contextAbsolutePath.value); } ``` -------------------------------- ### Reactive VS Code View Management Source: https://kermanx.com/reactive-vscode/functions Provides reactive APIs for managing various VS Code views, including Tree Views, Webview Panels, and Webview Views. You can register, update badges, set titles, and track visibility of these views reactively. This utilizes `window.createTreeView`, `window.createWebviewPanel`, `window.registerWebviewViewProvider`, and related APIs. ```typescript import { useTreeView, useWebviewPanel, useWebviewView, useViewBadge, useViewTitle, useViewVisibility } from '@reactive-vscode/reactive-vscode'; import { TreeDataProvider } from 'vscode'; // Example TreeDataProvider (replace with your actual implementation) const myTreeDataProvider: TreeDataProvider = { getChildren: (element) => [], getTreeItem: (element) => ({ id: '', label: '' }) }; // Register a Tree View const myTreeView = useTreeView('myTreeViewId', myTreeDataProvider); // Set a badge on the Tree View const treeViewBadge = useViewBadge(myTreeView); autorun(() => { treeViewBadge.value = '99+'; // Update badge reactively }); // Set a title for the Tree View const treeViewTitle = useViewTitle(myTreeView); autorun(() => { treeViewTitle.value = 'My Dynamic Title'; // Update title reactively }); // Get the visibility state of the Tree View const treeViewVisibility = useViewVisibility(myTreeView); autorun(() => { console.log('Tree View Visibility:', treeViewVisibility.value); }); // Register a Webview Panel const myWebviewPanel = useWebviewPanel('myWebviewPanelId', 'My Panel', { enableScripts: true }); autorun(() => { if (myWebviewPanel.value) { myWebviewPanel.value.webview.html = '

Hello Webview

'; } }); // Register a Webview View const myWebviewView = useWebviewView('myWebviewViewId', { resolveWebviewView: async (webviewView) => { // Setup webview content } }); ``` -------------------------------- ### Reactive FileSystemWatcher with Reactive VSCode API Source: https://kermanx.com/reactive-vscode/examples/fs-watcher/index This snippet demonstrates how to use the `useFsWatcher` hook from Reactive VSCode to watch a dynamic set of files. It shows how to add and remove glob patterns to the watcher and display messages when files change. Dependencies include 'reactive-vscode' and 'vscode'. ```typescript import { defineExtension, reactive, useCommands, useFsWatcher } from 'reactive-vscode' import { window } from 'vscode' export = defineExtension (() => { const globs = reactive (new Set (['src/**/*', 'docs/**/*'])) const watcher = useFsWatcher ( globs ) watcher . onDidChange ( uri => window. showInformationMessage (`File changed: ${ uri }`)) useCommands ({ 'demo.add-watch-dir': async () => { const value = await window. showInputBox ({ prompt : 'Enter a glob' }) if ( value ) globs . add ( value ) }, 'demo.remove-watch-dir': async () => { const value = await window. showInputBox ({ prompt : 'Enter a glob' }) if ( value ) globs . delete ( value ) }, }) }) ``` -------------------------------- ### Use Configuration as Refs in Extension Source: https://kermanx.com/reactive-vscode/guide/config This TypeScript snippet demonstrates how to use the `defineConfigs` function from `reactive-vscode` to access extension settings defined in `package.json` as reactive references. It shows how to retrieve configuration values and update them, optionally writing back to the VSCode configuration. ```typescript import { defineConfigs } from 'reactive-vscode' const { enable, greeting } = defineConfigs ('your-extension', { enable : Boolean , greeting : [ String , null], }) ``` ```typescript import { ConfigurationTarget } from 'vscode' // This will write the value back to the configuration. enable .value = false // To pass the rest of the options, you can use the `update` method. enable .update(false, ConfigurationTarget . Global ) // Only set the ref value without writing back to the configuration. enable .set(false) ``` -------------------------------- ### Reactive API for VS Code Tasks Source: https://kermanx.com/reactive-vscode/functions Provides reactive access to VS Code's task execution system. You can fetch tasks, monitor task executions, and react to their status changes. This uses `tasks.fetchTasks` and `tasks.taskExecutions`. ```typescript import { useFetchTasks, useTaskExecutions } from '@reactive-vscode/reactive-vscode'; const allTasks = useFetchTasks(); const runningTaskExecutions = useTaskExecutions(); autorun(() => { console.log('Available Tasks:', allTasks.value.length); allTasks.value.forEach(task => { console.log(' - Task:', task.name, 'Type:', task.type); }); }); autorun(() => { console.log('Running Task Executions:', runningTaskExecutions.value.length); runningTaskExecutions.value.forEach(execution => { console.log(' - Execution:', execution.task.name, 'Status:', execution.state); }); }); // Example: Fetching tasks and logging their names // const tasks = await fetchTasks(); // tasks.forEach(task => console.log(task.name)); ``` -------------------------------- ### FileSystemWatcher with Original VSCode API Source: https://kermanx.com/reactive-vscode/examples/fs-watcher/index This snippet shows the traditional VSCode API implementation for managing file system watchers. It includes functions to add and remove patterns, register commands to interact with these watchers, and ensures watchers are disposed of when the extension deactivates. Dependencies include 'vscode'. ```typescript import type { ExtensionContext, FileSystemWatcher, Uri } from 'vscode' import { commands, window, workspace } from 'vscode' const watchers = new Map () function addPattern ( pattern : string) { if (! watchers . has ( pattern )) { const watcher = workspace. createFileSystemWatcher ( pattern ) watcher . onDidChange (( uri : Uri ) => window. showInformationMessage (`File changed: ${ uri }`)) watchers . set ( pattern , watcher ) } } function removePattern ( pattern : string) { const watcher = watchers . get ( pattern ) if ( watcher ) { watcher . dispose () watchers . delete ( pattern ) } } export function activate ( extensionContext : ExtensionContext) { addPattern ('src/**/*') addPattern ('docs/**/*') extensionContext . subscriptions . push ( commands. registerCommand ('demo.add-watch-dir', async () => { const value = await window. showInputBox ({ prompt : 'Enter a glob' }) if ( value ) addPattern ( value ) }), commands. registerCommand ('demo.remove-watch-dir', async () => { const value = await window. showInputBox ({ prompt : 'Enter a glob' }) if ( value ) removePattern ( value ) }), ) } export function deactivate () { for (const watcher of watchers . values ()) { watcher . dispose () } } ``` -------------------------------- ### Reactive VS Code Lifecycle Management Source: https://kermanx.com/reactive-vscode/functions Provides reactive utilities for managing the lifecycle of your VS Code extension. This includes handling disposables, setting VS Code contexts, defining configurations, and registering activation/deactivation hooks. Functions like `useDisposable`, `useVscodeContext`, `defineConfigs`, `onActivate`, and `onDeactivate` are included. ```typescript import { useDisposable, useVscodeContext, defineConfigs, onActivate, onDeactivate } from '@reactive-vscode/reactive-vscode'; import { Disposable, workspace } from 'vscode'; // Manage a disposable resource const myDisposable = new Disposable(() => { console.log('Disposing my resource'); }); useDisposable(myDisposable); // Set a VS Code context const contextValue = useVscodeContext('myExtension.myContext'); contextValue.value = true; // Sets the context variable // Define extension configurations defineConfigs({ 'myExtension.setting1': { type: 'string', default: 'default value', description: 'A sample setting' } }); // Access configuration reactively const setting1 = workspace.getConfiguration('myExtension').get('setting1'); console.log('Setting 1:', setting1); // Extension activation hook onActivate(() => { console.log('My extension has been activated!'); }); // Extension deactivation hook onDeactivate(() => { console.log('My extension is being deactivated.'); }); // Example of using defineConfigObject defineConfigObject({ 'myExtension.anotherSetting': { defaultValue: 123, description: 'Another setting' } }); ``` -------------------------------- ### Generate Configuration with vscode-ext-gen Source: https://kermanx.com/reactive-vscode/guide/config This TypeScript snippet shows how to integrate `reactive-vscode` with `vscode-ext-gen` for generating configuration settings. It uses `defineConfigObject` with types and defaults from generated meta files to create a configuration object. ```typescript import type { NestedScopedConfigs } from './generated-meta' import { defineConfigObject, defineConfigs, reactive, ref } from 'reactive-vscode' import { scopedConfigs } from './generated-meta' const config = defineConfigObject ( scopedConfigs . scope , scopedConfigs . defaults , ) ``` -------------------------------- ### Implement Reactive FS Watcher with reactive-vscode Source: https://kermanx.com/reactive-vscode/examples/fs-watcher This snippet uses the 'reactive-vscode' library to create a reactive file system watcher. It allows dynamic addition and removal of file globs to monitor and displays a message when a file changes. Dependencies include 'reactive-vscode' and 'vscode'. ```typescript import { defineExtension, reactive, useCommands, useFsWatcher } from 'reactive-vscode' import { window } from 'vscode' export = defineExtension (() => { const globs = reactive (new Set (['src/**/*', 'docs/**/*'])) const watcher = useFsWatcher ( globs ) watcher . onDidChange ( uri => window. showInformationMessage (`File changed: ${ uri }`)) useCommands ({ 'demo.add-watch-dir': async () => { const value = await window. showInputBox ({ prompt : 'Enter a glob' }) if ( value ) globs . add ( value ) }, 'demo.remove-watch-dir': async () => { const value = await window. showInputBox ({ prompt : 'Enter a glob' }) if ( value ) globs . delete ( value ) }, }) }) ``` -------------------------------- ### Reactive API for VS Code Comments Source: https://kermanx.com/reactive-vscode/functions Offers a reactive API for managing comments within VS Code. This allows extensions to create comment controllers and interact with the commenting UI. It wraps `comments.createCommentController`. ```typescript import { useCommentController } from '@reactive-vscode/reactive-vscode'; import { CommentController, CommentThread, Uri } from 'vscode'; const commentController: CommentController = { commentingRangeProvider: undefined, createCommentThread: (uri: Uri, range, comments) => { console.log('Creating comment thread at:', range); return {} as CommentThread; }, dispose: () => {} }; const controller = useCommentController(commentController); // Example: Adding a comment thread // const thread = controller.value?.createCommentThread( // Uri.parse('file:///path/to/document.txt'), // new Range(0, 0, 0, 0), // [] // ); console.log('Comment controller ready.'); ``` -------------------------------- ### Reactive VS Code Logger and Output Channel Source: https://kermanx.com/reactive-vscode/functions Enables reactive logging to VS Code output channels and provides a way to define loggers that are available even before extension activation. This helps in debugging and monitoring extension behavior. It uses `window.createOutputChannel`, `useLogger`, and `defineLogger`. ```typescript import { useLogger, useOutputChannel, defineLogger } from '@reactive-vscode/reactive-vscode'; import { OutputChannel } from 'vscode'; // Define a logger that can be used before activation const earlyLogger = defineLogger('MyEarlyLogger'); earlyLogger.info('This message is from a pre-activation logger.'); // Create and get a reactive output channel const myOutputChannel = useOutputChannel('My Custom Output'); // Get a logger that writes to the custom output channel const myLogger = useLogger(myOutputChannel); myLogger.info('This is an informational message.'); myLogger.warn('This is a warning message.'); myLogger.error('This is an error message.'); // You can also directly access the output channel autorun(() => { if (myOutputChannel.value) { myOutputChannel.value.appendLine('Appended line to output channel.'); } }); ``` -------------------------------- ### Reactive API for VS Code Environment Shell Path Source: https://kermanx.com/reactive-vscode/functions Provides a reactive binding to the default shell path configured in VS Code. Your extension can automatically update its behavior or configuration based on the user's default shell environment. It wraps `env.shell`. ```typescript import { useDefaultShell } from '@reactive-vscode/reactive-vscode'; const defaultShellPath = useDefaultShell(); autorun(() => { const shellPath = defaultShellPath.value; if (shellPath) { console.log('The default shell path is:', shellPath); // You can use this path to configure processes or commands if (shellPath.includes('bash')) { console.log('Detected a bash-like shell.'); } } else { console.log('Default shell path not available.'); } }); ``` -------------------------------- ### Add Editor Decorations Reactively with reactive-vscode Source: https://kermanx.com/reactive-vscode/examples/editor-decoration This snippet shows how to use the `reactive-vscode` library to define configurations and reactively set decorations on the active editor. It leverages `defineConfigs` and `useActiveEditorDecorations` for a more declarative approach. The decorations are conditionally applied based on a boolean configuration value. ```typescript import { defineConfigs, defineExtension, useActiveEditorDecorations } from 'reactive-vscode' const { decorations } = defineConfigs('demo', { decorations: Boolean }) export = defineExtension(() => { useActiveEditorDecorations( { backgroundColor: 'red', }, () => decorations.value ? [/* ... Caclulated ranges ... */] : [], ) }) ``` -------------------------------- ### Reactive Event Handling in VS Code Source: https://kermanx.com/reactive-vscode/functions Offers reactive wrappers for VS Code's event system, allowing you to subscribe to and react to events in a declarative way. This includes general event listeners and event emitters. It uses VS Code's `Event` and `EventEmitter` APIs. ```typescript import { useEvent, useEventEmitter } from '@reactive-vscode/reactive-vscode'; import { EventEmitter } from 'vscode'; // Create a reactive event emitter const myEventEmitter = useEventEmitter(); // Subscribe to the event const eventListener = useEvent(myEventEmitter.event); autorun(() => { if (eventListener.value) { console.log('Received event:', eventListener.value); } }); // Emit an event after a delay setTimeout(() => { myEventEmitter.emit('Hello Reactive World!'); }, 2000); // Example: Listening to a VS Code built-in event (e.g., workspace configuration changes) import { workspace } from 'vscode'; const onConfigChange = useEvent(workspace.onDidChangeConfiguration); autorun(() => { console.log('Configuration changed:', onConfigChange.value?.affectsConfiguration('some.setting')); }); ``` -------------------------------- ### Reactive Editor Decorations with reactive-vscode Source: https://kermanx.com/reactive-vscode/examples/editor-decoration/index Implements editor decorations reactively using the 'reactive-vscode' library. It defines configurations and hooks into the active editor to apply decorations based on a boolean configuration value. Dependencies include 'reactive-vscode'. ```typescript import { defineConfigs, defineExtension, useActiveEditorDecorations } from 'reactive-vscode' const { decorations } = defineConfigs('demo', { decorations: Boolean }) export = defineExtension(() => { useActiveEditorDecorations( { backgroundColor: 'red', }, () => decorations.value ? [/* ... Caclulated ranges ... */] : [] ) }) ``` -------------------------------- ### Reactive API for VS Code Chat Participants Source: https://kermanx.com/reactive-vscode/functions Provides a reactive API for creating and managing chat participants within VS Code. This allows for integration with the VS Code chat feature, enabling extensions to contribute to chat conversations. It wraps `chat.createChatParticipant`. ```typescript import { useChatParticipant } from '@reactive-vscode/reactive-vscode'; import { ChatRequestHandler, ChatParticipant } from 'vscode'; const handleChatRequest: ChatRequestHandler = async (request, context, token) => { // Handle chat requests here return [ { kind: 'text', value: `You asked: ${request.prompt}` } ]; }; const chatParticipant: ChatParticipant = { id: 'myChatParticipant', name: 'My Chat Bot', iconPath: 'path/to/icon.png', handleCommand: handleChatRequest }; useChatParticipant(chatParticipant); console.log('Chat participant registered.'); ``` -------------------------------- ### Define VSCode Extension with Reactive Decorators Source: https://kermanx.com/reactive-vscode/guide/why This snippet demonstrates how to define a VSCode extension using the reactive-vscode library. It utilizes `defineConfigs` to manage configurations and `useActiveEditorDecorations` to apply decorations based on the 'decorations' configuration value. The code is concise and leverages Vue's reactivity for state management. ```typescript import { defineConfigs, defineExtension, useActiveEditorDecorations } from 'reactive-vscode' const { decorations } = defineConfigs('demo', { decorations: Boolean }) export = defineExtension(() => { useActiveEditorDecorations( { backgroundColor: 'red', }, () => decorations.value ? [/* ... Caclulated ranges ... */] : [] ) }) ``` -------------------------------- ### Register a Webview View using useWebviewView Source: https://kermanx.com/reactive-vscode/guide/view Registers a Webview View in VSCode using the `useWebviewView` composable. It allows rendering dynamic HTML content within the editor and includes options for script enablement and message handling. ```typescript import { computed , createSingletonComposable , ref , useWebviewView } from 'reactive-vscode' export const useDemoWebviewView = createSingletonComposable (() => { const message = ref ('') const html = computed (() => `

${ message . value }

`) const { postMessage } = useWebviewView ( 'reactive-webview-view', html , { webviewOptions : { enableScripts : true, enableCommandUris : true, }, onDidReceiveMessage ( ev ) { if ( ev .type === 'updateMessage') message . value = ev .message }, }, ) return { message , postMessage } }) ``` -------------------------------- ### Original VSCode API for Editor Decorations Source: https://kermanx.com/reactive-vscode/guide/why This snippet shows the equivalent implementation using the original VSCode API. It involves manually creating `TextEditorDecorationType`, managing `Disposables` within `ExtensionContext.subscriptions`, and handling configuration changes and active editor events explicitly. This approach is more verbose and less reactive compared to the reactive-vscode library. ```typescript import type { ExtensionContext } from 'vscode' import { window, workspace } from 'vscode' const decorationType = window.createTextEditorDecorationType({ backgroundColor: 'red', }) function updateDecorations(enabled: boolean) { window.activeTextEditor?.setDecorations( decorationType, enabled ? [/* ... Caclulated ranges ... */] : [] ) } export function activate(context: ExtensionContext) { const configurations = workspace.getConfiguration('demo') let decorationsEnabled = configurations.get('decorations')! context.subscriptions.push(workspace.onDidChangeConfiguration((e) => { if (e.affectsConfiguration('demo.decorations')) { decorationsEnabled = configurations.get('decorations')! updateDecorations(decorationsEnabled) } })) context.subscriptions.push(window.onDidChangeActiveTextEditor(() => { updateDecorations(decorationsEnabled) })) updateDecorations(decorationsEnabled) } ``` -------------------------------- ### Detect Theme with reactive-vscode API Source: https://kermanx.com/reactive-vscode/examples/theme-detector This snippet uses the reactive-vscode library to detect the active color theme and its kind (dark or light). It leverages `useActiveColorTheme` and `useIsDarkTheme` for reactive updates and `watchEffect` to display a message when the theme changes. No external dependencies beyond reactive-vscode and vscode are needed. ```typescript import { defineExtension, useActiveColorTheme, useIsDarkTheme, watchEffect } from 'reactive-vscode' import { window } from 'vscode' export = defineExtension(() => { const theme = useActiveColorTheme() const isDark = useIsDarkTheme() watchEffect(() => { window.showInformationMessage(`Your theme is ${theme.value} (kind: ${isDark.value ? 'dark' : 'light'})`) }) }) ``` -------------------------------- ### Access VSCode Workspace Folders and Log Count (TypeScript) Source: https://kermanx.com/reactive-vscode/guide/window This snippet shows how to use the `useWorkspaceFolders` composable to access the currently open workspace folders in VSCode. A `watchEffect` is used to log the number of workspace folders whenever this list changes, providing visibility into the project structure. ```typescript import { defineExtension, useWorkspaceFolders, watchEffect } from 'reactive-vscode' export = defineExtension(() => { const workspaceFolders = useWorkspaceFolders() watchEffect(() => { console.log('There are', workspaceFolders.value?.length, 'workspace folders') }) }) ```