Render diffs and code, now with edit
@pierre/diffs is an open source diff and code rendering library. Rich syntax highlighting, edit mode, support for custom and Shiki themes, virtualization, and more. Made by The Pierre Computer Company.
Currently v1.6.4
Edit diffs and code
Enable edit mode in any File or FileDiff component with the EditProvider. Includes support for selection management, auto-indention, undo history, find-in-file, lint markers, and more. Pairs nicely with @pierre/trees for AUI style experiences. Learn more about edit mode.
16 unmodified lines1718192021222122232425 unmodified lines505152535654555657615859606165 unmodified lines12712812913013513113213313813413514013613713813914017 unmodified lines15815916016116616716816216316416516616716816917017117217317917417517617767 unmodified lines24524624724825525625725825924925025126126226325225325425525617 unmodified lines27427527627728927827928028128225 unmodified lines30830931031132331231331431531649 unmodified lines3663673683693813703713723733 unmodified lines16 unmodified lines getSessionGitStatus, getSessionPaths,} from './mockData';
export type ThemeType = 'light' | 'dark';
// The editor's stylesheet flattens every line number to one neutral colour// (`--diffs-editor-line-number-fg`) and is injected as an unlayered <style>,// so it overrides the library's per-line colouring (which lives in @layer// base). We adopt this extra, higher-specificity unlayered sheet into the25 unmodified lines// component, so it's created in an effect and torn down on session change.function ChangesTree({ session, activePath, themeType, onSelect,}: { session: AuiSession; activePath: string | null; themeType: ThemeType; onSelect: (path: string) => void;}) { const containerRef = useRef<HTMLDivElement | null>(null); const treeRef = useRef<FileTree | null>(null);65 unmodified lines }; }, [session]);
// Inline color-scheme beats the tree's `:host { color-scheme: light dark }`, // flipping its light-dark() colours with our toggle. // pinning its light-dark() colours to the demo's dark mode. useEffect(() => { if (containerRef.current != null) { containerRef.current.style.colorScheme = themeType; containerRef.current.style.colorScheme = 'dark'; } }, [themeType, session]); }, [session]);
// Keep the highlighted row matched to the active file. useEffect(() => { const tree = treeRef.current;17 unmodified lines return <div ref={containerRef} className="aui-tree" />;}
export interface AgentUiProps { // Theme is controlled by the parent so the toggle can live outside the // component (the homepage section renders its own button group). themeType: ThemeType; // Highlight themes the surrounding worker pool was initialized with. Defaults // to the shared homepage pool's themes. theme?: { dark: string; light: string }; // Server-rendered diff HTML keyed by file path. When present the matching // FileDiff hydrates from this markup (already syntax-highlighted) instead of // waiting on the client worker, which also avoids an SSR/client mismatch. prerenderedDiffs?: Record<string, string>;}
// The demo is always dark: the snapshot is prerendered dark and matching it// avoids theme flashing, so there is no light/dark toggle.export function AgentUi({ themeType, theme = DEFAULT_THEMES, prerenderedDiffs,}: AgentUiProps) { const session = AUI_SESSIONS[0];67 unmodified lines : null, [activeFile, editKey] );
// Server-rendered, already-highlighted HTML for the active diff. The snapshot // is generated in dark mode, so only reuse it while the demo is in dark mode // (otherwise a freshly opened file would flash dark before re-highlighting). // It's also only safe when the file is unedited so the markup matches // `fileDiff`. // Server-rendered, already-highlighted HTML for the active diff. Only safe // when the file is unedited so the markup matches `fileDiff`. const activePrerenderedHTML = themeType === 'dark' && activePath != null && editsRef.current.get(editKey) == null activePath != null && editsRef.current.get(editKey) == null ? prerenderedDiffs?.[activePath] : undefined;
const breadcrumbSegments = activePath != null ? activePath.split('/') : [];17 unmodified lines } }, [activePath]);
return ( <div className="aui" data-theme-type={themeType} data-embedded="true"> <div className="aui" data-theme-type="dark" data-embedded="true"> <div className="aui-body"> <section className="aui-center"> <header className="aui-center-header"> <nav className="aui-breadcrumb" aria-label="File path">25 unmodified lines fileDiff={fileDiff} className="aui-surface" options={{ theme, themeType, themeType: 'dark', disableFileHeader: true, overflow: 'wrap', diffStyle: 'unified', }}49 unmodified lines </div> <ChangesTree session={session} activePath={activePath} themeType={themeType} onSelect={openFile} /> </aside> </div>3 unmodified linesDiff layout styles
Choose from stacked (unified) or split (side-by-side). Both use CSS Grid and Shadow DOM under the hood, meaning fewer DOM nodes and faster rendering.
11 unmodified lines121314151617181920212223242526272829303132333435363730 unmodified lines11 unmodified linesThemesType,} from '../types';export function createSpanFromToken(token: ThemedToken) {const element = document.createElement('div');const style = getTokenStyleObject(token);element.style = stringifyTokenStyle(style);return element;}export function createRow(line: number) {const row = document.createElement('div');row.dataset.line = `${line}`;const lineColumn = document.createElement('div');lineColumn.dataset.columnNumber = '';lineColumn.textContent = `${line}`;const content = document.createElement('div');content.dataset.columnContent = '';row.appendChild(lineColumn);row.appendChild(content);return { row, content };}30 unmodified lines11 unmodified lines121314151617181920212223242526272829303132333430 unmodified lines11 unmodified linesThemesType,} from '../types';export function createSpanFromToken(token: ThemedToken) {const element = document.createElement('span');const style = token.htmlStyle ?? getTokenStyleObject(token);element.style = stringifyTokenStyle(style);element.textContent = token.content;element.dataset.span = ''return element;}export function createRow(line: number) {const row = document.createElement('div');row.dataset.line = `${line}`;const content = document.createElement('div');content.dataset.columnContent = '';row.appendChild(content);return { row, content };}30 unmodified lines
Choose how changes are styled
Your diffs, your choice. Render changed lines with classic diff indicators (+/–), full-width background colors, or vertical bars. You can even highlight inline changes—character or word based—and toggle line wrapping, hide numbers, and more.
1234567891011121314const std = @import("std");const Allocator = std.heap.page_allocator;const ArrayList = std.ArrayList;pub fn main() !void {const stdout_writer_instance = std.io.getStdOut().writer();try stdout_writer_instance.print("Hi You, {s}! Welcome to our application.\n", .{"World"});var list = ArrayList(i32).init(allocator);defer list.deinit();const configuration_options = .{ .enable_logging = true, .max_buffer_size = 1024, .timeout_milliseconds = 5000 };_ = configuration_options;}12345678910111213141516171819const std = @import("std");const GeneralPurposeAllocator = std.heap.GeneralPurposeAllocator;const ArrayList = std.ArrayList;pub fn main() !void {var gpa = GeneralPurposeAllocator(.{}){};defer _ = gpa.deinit();const allocator = gpa.allocator();const stdout_writer_instance = std.io.getStdOut().writer();try stdout_writer_instance.print("Hello There, {s}! Welcome to the updated Zig application.\n", .{"Zig"});var list = ArrayList(i32).init(allocator);defer list.deinit();try list.append(42);const configuration_options = .{ .enable_logging = true, .max_buffer_size = 2048, .timeout_milliseconds = 10000, .retry_count = 3 };_ = configuration_options;}
Merge conflict resolution UI
Render conflicts through a dedicated diff primitive that treats current and incoming sections as structured additions/deletions without running text diffing. Resolve by choosing current, incoming, or both changes and preview the updated file instantly.
19 unmodified lines20212223232425262714 unmodified lines42434444454647454647484950515253545521 unmodified lines19 unmodified linesexport async function createSession(userId: string) { await cleanupExpiredSessions(userId);
|| <<<<<<< HEAD const data = {======= const sessionData = { source: 'web',>>>>>>> feature/oauth-session-source provider: 'password', userId, expiresAt: Date.now() + SESSION_TTL,14 unmodified lines if (oldest) await invalidateSession(oldest.id); }
|| <<<<<<< HEAD await db.auditLog.create({ event: 'session.created', userId, });======= await db.sessionEvent.create({ type: 'audit-log', data: { sessionId: session.id, type: 'created', source: sessionData.source ?? 'credentials', }, });>>>>>>> feature/oauth-session-source
return { session, token };}21 unmodified linesComments & Annotations
@pierre/diffs provide a flexible annotation framework for injecting additional content and context. Use it to render your own line comments, annotations from CI jobs, and other third-party content.
2 unmodified lines345677891011121314141516171819192021222 unmodified linesfrom typing import Optional
SECRET_KEY = "your-secret-key"
def create_token(user_id: str, expires_in: int = 3600) -> str:def create_token(user_id: str, role: str = "user", expires_in: int = 3600) -> str: payload = { "sub": user_id, "role": role, "exp": time.time() + expires_in } return jwt.encode(payload, SECRET_KEY, algorithm="HS256")
def verify_token(token: str) -> Optional[str]:def verify_token(token: str) -> Optional[dict]: try: payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"]) if payload["exp"] < time.time(): return None return payload["sub"] return {"user_id": payload["sub"], "role": payload["role"]} except jwt.InvalidTokenError: return NoneShould we validate the role parameter? We could restrict it to a set of allowed values.
Good idea, maybe use a Literal type or an enum.
Agreed, we should also update verify_token to return the role.
Accept/Reject Changes
Annotations can also be used to build interactive code review interfaces similar to AI-assisted coding tools like Cursor. Use it to track the state of each change, inject custom UI like accept/reject buttons, and provide immediate visual feedback.