### React Virtualizer Component Setup
Source: https://diffs.com/docs
Wrap your diff/file components in `Virtualizer` from `@pierre/diffs/react` to enable virtualization. The `Virtualizer` component acts as the scroll container. Currently, window scrolling is not supported without manual orchestration.
```jsx
import { Virtualizer } from "@pierre/diffs/react";
function MyDiffComponent() {
return (
{/* Your diff/file components here */}
);
}
```
--------------------------------
### getSharedHighlighter
Source: https://diffs.com/docs
Get direct access to the shared Shiki highlighter instance used internally by all components. Useful for custom highlighting operations.
```APIDOC
## getSharedHighlighter
### Description
Get direct access to the shared Shiki highlighter instance used internally by all components. Useful for custom highlighting operations.
### Returns
- `Highlighter`: The shared Shiki highlighter instance.
```
--------------------------------
### Custom CSS for Hunk Separators
Source: https://diffs.com/docs
Customize the appearance of hunk separators using CSS by targeting specific elements within the diff markup. This example demonstrates blending the separator with the background and aligning glyphs.
```css
.diff-gutter.diff-gutter-left {
/* Custom styles for the left gutter */
}
.diff-gutter.diff-gutter-left .glyph {
/* Align glyphs */
}
.diff-line-info {
/* Blend separator with background */
}
```
--------------------------------
### Vanilla JS Virtualizer Instance
Source: https://diffs.com/docs
In vanilla JavaScript, create a `Virtualizer` instance and pass it to `VirtualizedFileDiff` or `VirtualizedFile` components to enable virtualization.
```javascript
import { Virtualizer } from "@pierre/diffs";
import { VirtualizedFileDiff } from "@pierre/diffs/vanilla";
const virtualizer = new Virtualizer(/* ... */);
const diff = new VirtualizedFileDiff(virtualizer, {
// ...
});
```
--------------------------------
### Bundled Static File Serving
Source: https://diffs.com/docs
If your bundler lacks special worker support, build and serve the worker file statically.
```plaintext
output: {
format: 'es',
entryFileNames: '[name].js',
chunkFileNames: '[name]-[hash].js',
assetFileNames: '[name]-[hash].[ext]',
dir: 'dist/worker'
}
```
--------------------------------
### preloadHighlighter
Source: https://diffs.com/docs
Preload specific themes and languages before rendering to ensure instant highlighting with no async loading delay.
```APIDOC
## preloadHighlighter
### Description
Preload specific themes and languages before rendering to ensure instant highlighting with no async loading delay.
### Parameters
- **themes** (Array) - Required - An array of theme names to preload.
- **languages** (Array) - Required - An array of language identifiers to preload.
```
--------------------------------
### registerCustomLanguage
Source: https://diffs.com/docs
Register a custom Shiki language loader and optionally map it to file names or extensions. Use this when you're working with languages not bundled by Shiki or want custom highlighting grammars.
```APIDOC
## registerCustomLanguage
### Description
Register a custom Shiki language loader and optionally map it to file names or extensions. Use this when you're working with languages not bundled by Shiki or want custom highlighting grammars.
### Parameters
- **language** (object) - Required - The language object to register.
- **extensions** (Array) - Optional - File extensions to associate with this language.
```
--------------------------------
### Vanilla JS Dynamic Render Options
Source: https://diffs.com/docs
Call `setRenderOptions(options)` on the obtained pool instance to dynamically change render options.
```javascript
import { getOrCreateWorkerPoolSingleton } from '@pierre/diffs/vanilla';
const workerPool = getOrCreateWorkerPoolSingleton();
workerPool.setRenderOptions({ theme: 'light' });
```
--------------------------------
### Render Cache Configuration
Source: https://diffs.com/docs
Enable caching for files or diffs by setting a `cacheKey` property. The cache is invalidated if render options change.
```javascript
const diffComponent = new FileDiff(document.getElementById('diff'), {
cacheKey: 'my-unique-file-key',
// ... other options
});
```
--------------------------------
### Render a single file with File component (Vanilla JS)
Source: https://diffs.com/docs
Use the `File` component to render a single code file. This component takes `FileContents` as a prop.
```javascript
import { File } from "@pierre/diffs";
const fileContents = {
language: "javascript",
contents: "// some javascript code",
};
const fileElement = new File({
file: fileContents,
});
document.body.appendChild(fileElement.render());
```
--------------------------------
### registerCustomTheme
Source: https://diffs.com/docs
Register a custom Shiki theme for use with any component. The theme name you register must match the `name` field inside your theme JSON file.
```APIDOC
## registerCustomTheme
### Description
Register a custom Shiki theme for use with any component. The theme name you register must match the `name` field inside your theme JSON file.
### Parameters
- **theme** (object) - Required - The theme object to register.
```
--------------------------------
### Render a diff between two files with FileDiff (Vanilla JS)
Source: https://diffs.com/docs
Use the `FileDiff` component to render the differences between two files. It accepts `oldFile` and `newFile` props, which should be `FileContents` objects.
```javascript
import { FileDiff } from "@pierre/diffs";
const oldFileContents = {
language: "javascript",
contents: "// old javascript code",
};
const newFileContents = {
language: "javascript",
contents: "// new javascript code",
};
const fileDiffElement = new FileDiff({
oldFile: oldFileContents,
newFile: newFileContents,
});
document.body.appendChild(fileDiffElement.render());
```
--------------------------------
### Render a diff from a patch string with FileDiff (Vanilla JS)
Source: https://diffs.com/docs
Use the `FileDiff` component with a patch string to render differences. The `patch` prop should be a string containing the patch content.
```javascript
import { FileDiff } from "@pierre/diffs";
const patchString = `
--- a/file.js
+++ b/file.js
@@ -1,3 +1,4 @@
console.log("hello");
-console.log("world");
+console.log("world!");
+console.log("again");
`;
const fileDiffElement = new FileDiff({
patch: patchString,
});
document.body.appendChild(fileDiffElement.render());
```
--------------------------------
### parseDiffFromFile
Source: https://diffs.com/docs
Compare two versions of a file and generate a `FileDiffMetadata` structure. Use this when you have the full contents of both file versions rather than a patch string.
```APIDOC
## parseDiffFromFile
### Description
Compare two versions of a file and generate a `FileDiffMetadata` structure. Use this when you have the full contents of both file versions rather than a patch string.
If both `oldFile` and `newFile` have a `cacheKey`, the resulting `FileDiffMetadata` will automatically receive a combined cache key (format: `oldKey:newKey`). See Render Cache for more information.
An optional `throwOnError` parameter (default: `false`) controls error handling. When `true`, parsing errors throw exceptions; when `false`, errors are logged to the console and parsing continues on a best-effort basis.
### Parameters
- **oldFile** (string) - Required - The content of the old file version.
- **newFile** (string) - Required - The content of the new file version.
- **throwOnError** (boolean) - Optional - Controls error handling behavior.
### Returns
- `FileDiffMetadata`: A structure representing the differences between the two files.
```
--------------------------------
### Parse diff from a patch string using parsePatchFiles (Vanilla JS)
Source: https://diffs.com/docs
The `parsePatchFiles` utility function creates `FileDiffMetadata` from a patch string. This is useful for processing git output or patch files from APIs.
```javascript
import { parsePatchFiles } from "@pierre/diffs";
const patchString = `
--- a/file.js
+++ b/file.js
@@ -1,3 +1,4 @@
console.log("hello");
-console.log("world");
+console.log("world!");
+console.log("again");
`;
const fileDiffMetadata = await parsePatchFiles(patchString);
// Use fileDiffMetadata with FileDiff component or other utilities
```
--------------------------------
### disposeHighlighter
Source: https://diffs.com/docs
Dispose the shared Shiki highlighter instance to free memory. Useful when cleaning up resources in single-page applications.
```APIDOC
## disposeHighlighter
### Description
Dispose the shared Shiki highlighter instance to free memory. Useful when cleaning up resources in single-page applications.
### Usage
```javascript
disposeHighlighter();
```
```
--------------------------------
### trimPatchContext
Source: https://diffs.com/docs
Trim patches with large context windows down to a fixed context window while keeping valid diff headers.
```APIDOC
## trimPatchContext
### Description
Trim patches with large context windows down to a fixed context window while keeping valid diff headers.
### Parameters
- **patchContent** (string) - Required - The patch content to trim.
- **contextLines** (number) - Required - The desired number of context lines.
### Returns
- `string`: The trimmed patch content.
```
--------------------------------
### Parse diff from two files using parseDiffFromFile (Vanilla JS)
Source: https://diffs.com/docs
The `parseDiffFromFile` utility function creates `FileDiffMetadata` from two file versions. This method includes full file contents, enabling features like 'expand unchanged'.
```javascript
import { parseDiffFromFile } from "@pierre/diffs";
const oldFileContents = {
language: "javascript",
contents: "// old javascript code",
};
const newFileContents = {
language: "javascript",
contents: "// new javascript code",
};
const fileDiffMetadata = await parseDiffFromFile(oldFileContents, newFileContents);
// Use fileDiffMetadata with FileDiff component or other utilities
```
--------------------------------
### React Worker Pool Context Provider
Source: https://diffs.com/docs
Wrap your component tree with `WorkerPoolContextProvider` to automatically use the worker pool for syntax highlighting in nested `FileDiff` and `File` components.
```jsx
import { WorkerPoolContextProvider } from '@pierre/diffs/react';
function App() {
return (
{/* Your components */}
);
}
```
--------------------------------
### VS Code Webview Extension - Extension Side Configuration
Source: https://diffs.com/docs
Configure the extension side of a VS Code webview to expose the worker file. Add the worker directory to `localResourceRoots` and create the worker URI.
```typescript
getWebviewOptions() {
return {
// ... other options
localResourceRoots: [
// ... other roots
Uri.joinPath(this.context.extensionUri, 'dist', 'worker')
]
};
}
```
```html
const workerUri = this.webview.asWebviewUri(Uri.joinPath(this.context.extensionUri, 'dist', 'worker', 'worker_portable.js'));
// ... in your HTML generation
```
--------------------------------
### Vanilla JS Singleton Worker Pool
Source: https://diffs.com/docs
Use `getOrCreateWorkerPoolSingleton` to obtain a singleton worker pool instance and pass it to `File` or `FileDiff` components. Terminate the pool with `terminateWorkerPoolSingleton`.
```javascript
import { getOrCreateWorkerPoolSingleton, terminateWorkerPoolSingleton } from '@pierre/diffs/vanilla';
import { File } from '@pierre/diffs/file';
// Initialize and get the pool
const workerPool = getOrCreateWorkerPoolSingleton({
// ... initial options
});
// Use the pool with a component
const fileComponent = new File(document.getElementById('diff'), {
workerPool: workerPool,
// ... other options
});
// Later, to terminate
// terminateWorkerPoolSingleton();
```
--------------------------------
### React Dynamic Render Options with useWorkerPool Hook
Source: https://diffs.com/docs
Use the `useWorkerPool` hook to access the pool manager and dynamically change render options like themes.
```jsx
import { useWorkerPool } from '@pierre/diffs/react';
function MyComponent() {
const { setRenderOptions } = useWorkerPool();
const changeTheme = () => {
setRenderOptions({ theme: 'dark' });
};
return ;
}
```
--------------------------------
### setLanguageOverride
Source: https://diffs.com/docs
Override the syntax highlighting language for a `FileContents` or `FileDiffMetadata` object. This is useful when the filename doesn't have an extension or doesn't match the actual language.
```APIDOC
## setLanguageOverride
### Description
Override the syntax highlighting language for a `FileContents` or `FileDiffMetadata` object. This is useful when the filename doesn't have an extension or doesn't match the actual language.
### Parameters
- **diffOrContents** (object) - Required - The `FileContents` or `FileDiffMetadata` object to modify.
- **language** (string) - Required - The language identifier to set.
```
--------------------------------
### VS Code Webview Extension - Webview Side Worker Loading
Source: https://diffs.com/docs
Load the worker code in the webview side using a blob URL. Fetch the worker code and create the `workerFactory` function.
```typescript
declare global {
interface Window {
workerUri: string;
}
}
const fetchWorker = async () => {
const response = await fetch(window.workerUri);
return await response.text();
};
const workerFactory = async () => {
const workerCode = await fetchWorker();
const blob = new Blob([workerCode], { type: 'application/javascript' });
const url = URL.createObjectURL(blob);
return new Worker(url);
};
```
--------------------------------
### parsePatchFiles
Source: https://diffs.com/docs
Parse unified diff / patch file content into structured data. Handles both single patches and multi-commit patch files.
```APIDOC
## parsePatchFiles
### Description
Parse unified diff / patch file content into structured data. Handles both single patches and multi-commit patch files (like those from GitHub pull request `.patch` URLs). An optional second parameter `cacheKeyPrefix` can be provided to generate cache keys for each file in the patch (format: `prefix-patchIndex-fileIndex`), enabling caching of rendered diff results in the worker pool.
An optional `throwOnError` parameter (default: `false`) controls error handling. When `true`, parsing errors throw exceptions; when `false`, errors are logged to the console and parsing continues on a best-effort basis.
### Parameters
- **patchContent** (string) - Required - The content of the patch file.
- **cacheKeyPrefix** (string) - Optional - A prefix for generating cache keys for files within the patch.
- **throwOnError** (boolean) - Optional - Controls error handling behavior.
### Returns
- `Array`: An array of structures representing the parsed diffs.
```
--------------------------------
### VS Code Webview Extension - Content Security Policy
Source: https://diffs.com/docs
Ensure your Content Security Policy includes `worker-src` and `connect-src` directives for VS Code webviews.
```plaintext
Content-Security-Policy: script-src 'self' 'unsafe-inline'; worker-src 'self'; connect-src 'self';
```
--------------------------------
### resolveMergeConflict
Source: https://diffs.com/docs
Apply a merge conflict action payload to a file string and return the next contents. This API is experimental.
```APIDOC
## resolveMergeConflict
### Description
Apply a merge conflict action payload to a file string and return the next contents.
> **Experimental:** `UnresolvedFile`-related merge conflict APIs are currently beta/experimental and may change in future releases.
Default merge-conflict buttons work even without callbacks: `UnresolvedFile` applies the resolution internally. In vanilla, provide `onMergeConflictAction` for controlled state. Use `onMergeConflictResolve` when you want uncontrolled resolution plus a notification with the resolved file. React `UnresolvedFile` is intentionally uncontrolled.
### Usage
```javascript
// Example usage (conceptual)
const resolvedContent = resolveMergeConflict(fileContent, actionPayload);
```
```
--------------------------------
### Override language for FileContents or FileDiffMetadata (Vanilla JS)
Source: https://diffs.com/docs
The `setLanguageOverride` utility function allows you to change the language of `FileContents` or `FileDiffMetadata` after they have been created. This is useful if the detected language is incorrect or needs to be specified manually.
```javascript
import { FileContents, setLanguageOverride } from "@pierre/diffs";
const fileContents = new FileContents({
language: "plaintext", // Initially detected as plaintext
contents: "function greet() { console.log('Hello!'); }",
});
// Override the language to javascript
const overriddenFileContents = setLanguageOverride(fileContents, "javascript");
// Now use overriddenFileContents with diff components
```
--------------------------------
### Vanilla JS Hunk Separator Function (Last Resort)
Source: https://diffs.com/docs
This low-level `hunkSeparators` function is available on the Vanilla JS `FileDiff` API but is being phased out. It is not compatible with React components or SSR and should only be used as a last resort for customization.
```javascript
import { hunkSeparators } from "@pierre/diffs/vanilla";
const customSeparators = (hunkData, instance) => {
// Custom logic for hunk separators
return "...";
};
// Usage with FileDiff API (discouraged)
const fileDiff = new FileDiff(element, {
hunkSeparators: customSeparators
});
```
--------------------------------
### NextJS Client Component Directive
Source: https://diffs.com/docs
When using the App Router in NextJS, ensure your functions utilizing workers have the `'use client'` directive, as workers only function in client components.
```javascript
'use client';
```
--------------------------------
### diffAcceptRejectHunk
Source: https://diffs.com/docs
Programmatically accept or reject individual hunks or specific change blocks within a hunk in a diff. This is useful for building interactive code review interfaces or AI-assisted coding tools.
```APIDOC
## diffAcceptRejectHunk
### Description
Programmatically accept or reject individual hunks (or specific change blocks inside a hunk) in a diff. This is useful for building interactive code review interfaces, AI-assisted coding tools, or any workflow where users need to selectively apply changes.
To resolve an entire hunk, pass `'accept'`, `'reject'`, or `'both'`. To resolve only one change block in a hunk, pass an object with `type` and `changeIndex` (for example: `diffAcceptRejectHunk(diff, hunkIndex, { type: 'accept', changeIndex: 0 })`). `changeIndex` maps to the target entry in that hunk's `hunkContent` array.
When you **accept** a hunk, the new (additions) version is kept and the hunk is converted to context lines. When you **reject** a hunk, the old (deletions) version is restored. You can also use **both** as a lower-level way to mux the two sides together, which keeps the old lines first and then appends the new lines before collapsing the result back to context. The function returns a new `FileDiffMetadata` object with all line numbers properly adjusted for subsequent hunks.
### Basic Usage
```javascript
// Example usage (conceptual)
diffAcceptRejectHunk(diff, hunkIndex, 'accept');
diffAcceptRejectHunk(diff, hunkIndex, { type: 'reject', changeIndex: 1 });
```
### Returns
- `FileDiffMetadata`: A new object with updated line numbers.
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.