This commit is contained in:
Timothy Jaeryang Baek
2026-07-09 15:40:39 -05:00
Unverified
parent 7e3f3ffe92
commit 6597ed17b2
5 changed files with 466 additions and 97 deletions
@@ -20,6 +20,8 @@
import SvgPreview from './preview/SvgPreview.svelte';
import OfficePreview from './preview/OfficePreview.svelte';
import Spinner from './common/Spinner.svelte';
import { groupDiffLines, languageForPath, withInlineDiffSegments } from '$lib/utils/diff';
import SyntaxDiffLine from './SyntaxDiffLine.svelte';
import {
EditorState,
StateEffect,
@@ -158,7 +160,6 @@
type DiffHunk = { header: string; lines: DiffLine[] };
type DiffFileEntry = { path: string; hunks: DiffHunk[] };
type NumberedLine = DiffLine & { oldNumber: number | null; newNumber: number | null };
type LineGroup = { type: DiffLine['type']; lines: NumberedLine[] };
type GitLineChange = { line: number; type: 'added' | 'modified' };
let diffMode = $state(false);
let diffFiles = $state<DiffFileEntry[]>([]);
@@ -265,16 +266,6 @@
});
}
function diffGroupLines(lines: NumberedLine[]): LineGroup[] {
const groups: LineGroup[] = [];
for (const line of lines) {
const last = groups[groups.length - 1];
if (last && last.type === line.type) last.lines.push(line);
else groups.push({ type: line.type, lines: [line] });
}
return groups;
}
function splitLines(text: string): string[] {
return text.length === 0 ? [] : text.split('\n');
}
@@ -1235,7 +1226,7 @@
<span></span>
<code class="whitespace-pre px-2 py-0.5">{hunk.header}</code>
</div>
{#each diffGroupLines(diffNumberedLines(hunk)) as group}
{#each groupDiffLines(withInlineDiffSegments(diffNumberedLines(hunk))) as group}
<div class="w-full {diffBlockClass(group.type)}">
{#each group.lines as line}
<div
@@ -1252,9 +1243,13 @@
<span class="select-none px-1 text-center {diffPrefixClass(line.type)}"
>{diffPrefix(line.type)}</span
>
<code class="whitespace-pre px-2 {diffTextClass(line.type)}"
>{line.content || ' '}</code
>
<SyntaxDiffLine
type={line.type}
content={line.content || ' '}
segments={line.segments}
language={languageForPath(df.path)}
class={diffTextClass(line.type)}
/>
</div>
{/each}
</div>
+39 -37
View File
@@ -32,6 +32,15 @@
import { tooltip } from '$lib/tooltip';
import { t } from '$lib/i18n';
import Spinner from '$lib/components/common/Spinner.svelte';
import {
groupDiffLines,
languageForPath,
numberDiffLines,
withInlineDiffSegments,
type DiffFile,
type DiffLine
} from '$lib/utils/diff';
import SyntaxDiffLine from './SyntaxDiffLine.svelte';
type GitFile = {
path: string;
@@ -41,8 +50,6 @@
staged_status?: string;
unstaged_status?: string;
};
type DiffHunk = { header: string; lines: { type: string; content: string }[] };
type DiffFile = { path: string; hunks: DiffHunk[] };
type Commit = { hash: string; short_hash: string; author: string; date: string; message: string };
type BranchItem = {
name: string;
@@ -710,22 +717,7 @@
}
}
type LineGroup = { type: string; lines: { type: string; content: string }[] };
function groupLines(lines: { type: string; content: string }[]): LineGroup[] {
const groups: LineGroup[] = [];
for (const line of lines) {
const last = groups[groups.length - 1];
if (last && last.type === line.type) {
last.lines.push(line);
} else {
groups.push({ type: line.type, lines: [line] });
}
}
return groups;
}
function blockClass(type: string): string {
function blockClass(type: DiffLine['type']): string {
switch (type) {
case 'added':
return 'bg-green-100 border-l-[0.1875rem] border-l-green-500 dark:bg-green-500/15 dark:border-l-green-400';
@@ -736,6 +728,24 @@
}
}
function textClass(type: DiffLine['type']): string {
if (type === 'added') return 'text-green-900 dark:text-green-300';
if (type === 'removed') return 'text-red-900 dark:text-red-300';
return 'text-gray-600 dark:text-gray-400';
}
function prefixClass(type: DiffLine['type']): string {
if (type === 'added') return 'text-green-600 dark:text-green-400';
if (type === 'removed') return 'text-red-500 dark:text-red-400';
return 'text-gray-400 dark:text-gray-600';
}
function linePrefix(type: DiffLine['type']): string {
if (type === 'added') return '+';
if (type === 'removed') return '-';
return ' ';
}
$effect(() => {
if (!expanded) return;
function onKeydown(e: KeyboardEvent) {
@@ -1412,28 +1422,20 @@
>
{hunk.header}
</div>
{#each groupLines(hunk.lines) as group}
{#each groupDiffLines(withInlineDiffSegments(numberDiffLines(hunk))) as group}
<div class="w-full {blockClass(group.type)}">
{#each group.lines as line}
<div class="px-2 whitespace-pre-wrap break-all">
<span
class={line.type === 'added'
? 'text-green-600 dark:text-green-400'
: line.type === 'removed'
? 'text-red-500 dark:text-red-400'
: 'text-gray-400 dark:text-gray-600'}
>{line.type === 'added'
? '+'
: line.type === 'removed'
? '-'
: ' '}</span
><span
class={line.type === 'added'
? 'text-green-900 dark:text-green-300'
: line.type === 'removed'
? 'text-red-900 dark:text-red-300'
: 'text-gray-600 dark:text-gray-400'}>{line.content}</span
<div class="flex min-w-max">
<span class="select-none px-2 text-center {prefixClass(line.type)}"
>{linePrefix(line.type)}</span
>
<SyntaxDiffLine
type={line.type}
content={line.content || ' '}
segments={line.segments}
language={languageForPath(df.path)}
class={textClass(line.type)}
/>
</div>
{/each}
</div>
+17 -45
View File
@@ -5,12 +5,18 @@
import { tooltip } from '$lib/tooltip';
import { t } from '$lib/i18n';
import {
groupDiffLines,
languageForPath,
numberDiffLines,
withInlineDiffSegments,
type DiffFile,
type DiffLine
} from '$lib/utils/diff';
import Icon from './Icon.svelte';
import Spinner from '$lib/components/common/Spinner.svelte';
import SyntaxDiffLine from './SyntaxDiffLine.svelte';
type DiffLine = { type: 'added' | 'removed' | 'context'; content: string };
type DiffHunk = { header: string; lines: DiffLine[] };
type DiffFile = { path: string; hunks: DiffHunk[] };
type ReviewFile = {
key: string;
path: string;
@@ -21,7 +27,6 @@
deletions: number;
expanded: boolean;
};
type NumberedLine = DiffLine & { oldNumber: number | null; newNumber: number | null };
let gitStatus = $derived(gitStatusStore.status);
let reviewFiles = $state<ReviewFile[]>([]);
@@ -178,28 +183,6 @@
}
}
function hunkStart(header: string): { oldStart: number; newStart: number } {
const match = header.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
return {
oldStart: match ? Number(match[1]) : 0,
newStart: match ? Number(match[2]) : 0
};
}
function numberedLines(hunk: DiffHunk): NumberedLine[] {
let { oldStart, newStart } = hunkStart(hunk.header);
return hunk.lines.map((line) => {
if (line.type === 'added') {
return { ...line, oldNumber: null, newNumber: newStart++ };
}
if (line.type === 'removed') {
return { ...line, oldNumber: oldStart++, newNumber: null };
}
return { ...line, oldNumber: oldStart++, newNumber: newStart++ };
});
}
function blockClass(type: DiffLine['type']): string {
switch (type) {
case 'added':
@@ -238,21 +221,6 @@
if (type === 'removed') return '-';
return ' ';
}
type LineGroup = { type: DiffLine['type']; lines: NumberedLine[] };
function groupLines(lines: NumberedLine[]): LineGroup[] {
const groups: LineGroup[] = [];
for (const line of lines) {
const last = groups[groups.length - 1];
if (last && last.type === line.type) {
last.lines.push(line);
} else {
groups.push({ type: line.type, lines: [line] });
}
}
return groups;
}
</script>
<div
@@ -437,7 +405,7 @@
<span></span>
<code class="whitespace-pre px-2 py-0.5">{hunk.header}</code>
</div>
{#each groupLines(numberedLines(hunk)) as group}
{#each groupDiffLines(withInlineDiffSegments(numberDiffLines(hunk))) as group}
<div class="w-full {blockClass(group.type)}">
{#each group.lines as line}
<div class="grid w-full grid-cols-[2.75rem_2.75rem_1.25rem_auto]">
@@ -453,9 +421,13 @@
class="select-none px-1 text-center {prefixClass(line.type)}"
>{linePrefix(line.type)}</span
>
<code class="whitespace-pre px-2 {textClass(line.type)}"
>{line.content || ' '}</code
>
<SyntaxDiffLine
type={line.type}
content={line.content || ' '}
segments={line.segments}
language={languageForPath(diffFile.path)}
class={textClass(line.type)}
/>
</div>
{/each}
</div>
@@ -0,0 +1,228 @@
<script module lang="ts">
import type { HighlighterCore } from 'shiki/core';
type HighlightToken = {
content: string;
offset: number;
variants?: {
light?: { color?: string };
dark?: { color?: string };
};
};
let highlighterPromise: Promise<HighlighterCore> | null = null;
const tokenCache = new Map<string, HighlightToken[]>();
async function getHighlighter(): Promise<HighlighterCore> {
if (!highlighterPromise) {
highlighterPromise = (async () => {
const { createHighlighterCore } = await import('shiki/core');
const { createOnigurumaEngine } = await import('shiki/engine/oniguruma');
return createHighlighterCore({
themes: [import('shiki/themes/github-light.mjs'), import('shiki/themes/github-dark.mjs')],
langs: [
import('shiki/langs/javascript.mjs'),
import('shiki/langs/typescript.mjs'),
import('shiki/langs/python.mjs'),
import('shiki/langs/bash.mjs'),
import('shiki/langs/shell.mjs'),
import('shiki/langs/json.mjs'),
import('shiki/langs/html.mjs'),
import('shiki/langs/css.mjs'),
import('shiki/langs/markdown.mjs'),
import('shiki/langs/yaml.mjs'),
import('shiki/langs/toml.mjs'),
import('shiki/langs/rust.mjs'),
import('shiki/langs/go.mjs'),
import('shiki/langs/c.mjs'),
import('shiki/langs/cpp.mjs'),
import('shiki/langs/java.mjs'),
import('shiki/langs/sql.mjs'),
import('shiki/langs/svelte.mjs'),
import('shiki/langs/dockerfile.mjs'),
import('shiki/langs/xml.mjs'),
import('shiki/langs/ruby.mjs'),
import('shiki/langs/php.mjs'),
import('shiki/langs/swift.mjs'),
import('shiki/langs/kotlin.mjs'),
import('shiki/langs/lua.mjs'),
import('shiki/langs/tsx.mjs'),
import('shiki/langs/jsx.mjs'),
import('shiki/langs/scss.mjs'),
import('shiki/langs/graphql.mjs'),
import('shiki/langs/makefile.mjs')
],
engine: createOnigurumaEngine(import('shiki/wasm'))
});
})();
}
return highlighterPromise;
}
</script>
<script lang="ts">
import type { DiffLineType, InlineDiffSegment } from '$lib/utils/diff';
interface Props {
type: DiffLineType;
content: string;
segments: InlineDiffSegment[];
language: string;
class?: string;
}
type RenderSegment = InlineDiffSegment & {
light?: string;
dark?: string;
};
let { type, content, segments, language, class: className = '' }: Props = $props();
let renderedSegments = $state<RenderSegment[] | null>(null);
$effect(() => {
const currentContent = content;
const currentSegments = segments;
const currentLanguage = language;
(async () => {
if (!currentLanguage || currentLanguage === 'text') {
renderedSegments = null;
return;
}
try {
const key = `${currentLanguage}\0${currentContent}`;
let tokens = tokenCache.get(key);
if (!tokens) {
const highlighter = await getHighlighter();
if (!highlighter.getLoadedLanguages().includes(currentLanguage)) {
renderedSegments = null;
return;
}
const tokenLines = highlighter.codeToTokensWithThemes(currentContent, {
lang: currentLanguage,
themes: { light: 'github-light', dark: 'github-dark' }
}) as HighlightToken[][];
tokens = tokenLines[0] ?? [];
tokenCache.set(key, tokens);
}
if (
currentContent !== content ||
currentSegments !== segments ||
currentLanguage !== language
) {
return;
}
renderedSegments = mergeTokensWithSegments(tokens, currentSegments);
} catch {
renderedSegments = null;
}
})();
});
function mergeTokensWithSegments(
tokens: HighlightToken[],
diffSegments: InlineDiffSegment[]
): RenderSegment[] {
const ranges: Array<{ start: number; end: number; changed: boolean }> = [];
let offset = 0;
for (const segment of diffSegments) {
ranges.push({ start: offset, end: offset + segment.text.length, changed: segment.changed });
offset += segment.text.length;
}
const merged: RenderSegment[] = [];
for (const token of tokens) {
const tokenStart = token.offset;
const tokenEnd = token.offset + token.content.length;
for (const range of ranges) {
const start = Math.max(tokenStart, range.start);
const end = Math.min(tokenEnd, range.end);
if (start >= end) continue;
merged.push({
text: token.content.slice(start - tokenStart, end - tokenStart),
changed: range.changed,
light: token.variants?.light?.color,
dark: token.variants?.dark?.color
});
}
}
return merged.length ? merged : diffSegments;
}
function inlineSegmentClass(type: DiffLineType, changed: boolean): string {
if (!changed) return '';
if (type === 'added') return 'inline-change inline-added';
if (type === 'removed') return 'inline-change inline-removed';
return '';
}
function escapeHtml(text: string): string {
return text
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;');
}
function htmlForSegments(type: DiffLineType, segments: RenderSegment[]): string {
return segments
.map((segment) => {
const classes = inlineSegmentClass(type, segment.changed);
const styles = [
segment.light ? `--diff-token-light: ${segment.light}` : '',
segment.dark ? `--diff-token-dark: ${segment.dark}` : ''
]
.filter(Boolean)
.join('; ');
const classAttr = classes ? ` class="${classes}"` : '';
const styleAttr = styles ? ` style="${styles}"` : '';
return `<span${classAttr}${styleAttr}>${escapeHtml(segment.text)}</span>`;
})
.join('');
}
const fallbackSegments = $derived(renderedSegments ?? segments);
const html = $derived(htmlForSegments(type, fallbackSegments));
</script>
<code class="syntax-diff-line whitespace-pre px-2 {className}">{@html html}</code>
<style>
.syntax-diff-line :global(span) {
color: var(--diff-token-light, inherit);
}
:global(.dark) .syntax-diff-line :global(span) {
color: var(--diff-token-dark, inherit);
}
.syntax-diff-line :global(.inline-change) {
border-radius: 0.125rem;
box-decoration-break: clone;
-webkit-box-decoration-break: clone;
font-weight: 700;
padding: 0.0625rem 0.125rem;
}
.syntax-diff-line :global(.inline-added) {
background: rgba(22, 163, 74, 0.38);
box-shadow: inset 0 -0.125rem 0 rgba(21, 128, 61, 0.42);
}
.syntax-diff-line :global(.inline-removed) {
background: rgba(220, 38, 38, 0.32);
box-shadow: inset 0 -0.125rem 0 rgba(185, 28, 28, 0.38);
}
:global(.dark) .syntax-diff-line :global(.inline-added) {
background: rgba(34, 197, 94, 0.42);
box-shadow: inset 0 -0.125rem 0 rgba(134, 239, 172, 0.5);
}
:global(.dark) .syntax-diff-line :global(.inline-removed) {
background: rgba(248, 113, 113, 0.4);
box-shadow: inset 0 -0.125rem 0 rgba(252, 165, 165, 0.48);
}
</style>
+172
View File
@@ -0,0 +1,172 @@
export type DiffLineType = 'added' | 'removed' | 'context';
export type DiffLine = { type: DiffLineType; content: string };
export type DiffHunk = { header: string; lines: DiffLine[] };
export type DiffFile = { path: string; hunks: DiffHunk[] };
export type NumberedDiffLine = DiffLine & { oldNumber: number | null; newNumber: number | null };
export type InlineDiffSegment = { text: string; changed: boolean };
export type InlineDiffLine = NumberedDiffLine & { segments: InlineDiffSegment[] };
export type DiffLineGroup<T extends { type: string }> = { type: T['type']; lines: T[] };
export function languageForPath(path: string): string {
const ext = path.slice(path.lastIndexOf('.')).toLowerCase();
const byExt: Record<string, string> = {
'.py': 'python',
'.js': 'javascript',
'.ts': 'typescript',
'.jsx': 'jsx',
'.tsx': 'tsx',
'.svelte': 'svelte',
'.css': 'css',
'.scss': 'scss',
'.html': 'html',
'.json': 'json',
'.xml': 'xml',
'.yaml': 'yaml',
'.yml': 'yaml',
'.toml': 'toml',
'.md': 'markdown',
'.sh': 'bash',
'.bash': 'bash',
'.zsh': 'bash',
'.rs': 'rust',
'.go': 'go',
'.java': 'java',
'.c': 'c',
'.h': 'c',
'.cpp': 'cpp',
'.hpp': 'cpp',
'.rb': 'ruby',
'.php': 'php',
'.swift': 'swift',
'.kt': 'kotlin',
'.sql': 'sql',
'.lua': 'lua',
'.dockerfile': 'dockerfile',
'.makefile': 'makefile'
};
return byExt[ext] ?? 'text';
}
export function numberDiffLines(hunk: DiffHunk): NumberedDiffLine[] {
const match = hunk.header.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
let oldNumber = match ? Number(match[1]) : 0;
let newNumber = match ? Number(match[2]) : 0;
return hunk.lines.map((line) => {
if (line.type === 'added') return { ...line, oldNumber: null, newNumber: newNumber++ };
if (line.type === 'removed') return { ...line, oldNumber: oldNumber++, newNumber: null };
return { ...line, oldNumber: oldNumber++, newNumber: newNumber++ };
});
}
export function groupDiffLines<T extends { type: string }>(lines: T[]): DiffLineGroup<T>[] {
const groups: DiffLineGroup<T>[] = [];
for (const line of lines) {
const last = groups[groups.length - 1];
if (last && last.type === line.type) last.lines.push(line);
else groups.push({ type: line.type, lines: [line] });
}
return groups;
}
export function withInlineDiffSegments(lines: NumberedDiffLine[]): InlineDiffLine[] {
const result: InlineDiffLine[] = [];
let i = 0;
while (i < lines.length) {
const line = lines[i];
if (line.type === 'context') {
result.push({ ...line, segments: [{ text: line.content || ' ', changed: false }] });
i += 1;
continue;
}
const block: NumberedDiffLine[] = [];
while (i < lines.length && lines[i].type !== 'context') {
block.push(lines[i]);
i += 1;
}
const removed = block.filter((item) => item.type === 'removed');
const added = block.filter((item) => item.type === 'added');
const removedSegments = removed.map((item, index) =>
segmentsForPair(item.content, added[index]?.content, 'removed')
);
const addedSegments = added.map((item, index) =>
segmentsForPair(removed[index]?.content, item.content, 'added')
);
for (const item of block) {
const index =
item.type === 'removed'
? removed.indexOf(item)
: item.type === 'added'
? added.indexOf(item)
: -1;
const segments =
item.type === 'removed'
? removedSegments[index]
: item.type === 'added'
? addedSegments[index]
: [{ text: item.content || ' ', changed: false }];
result.push({ ...item, segments });
}
}
return result;
}
function segmentsForPair(
oldText: string | undefined,
newText: string | undefined,
side: 'removed' | 'added'
): InlineDiffSegment[] {
const text = side === 'removed' ? oldText : newText;
if (text === undefined) return [];
if (oldText === undefined || newText === undefined)
return [{ text: text || ' ', changed: false }];
if (oldText === newText) return [{ text: text || ' ', changed: false }];
let prefix = 0;
const maxPrefix = Math.min(oldText.length, newText.length);
while (prefix < maxPrefix && oldText[prefix] === newText[prefix]) prefix += 1;
let oldSuffix = oldText.length;
let newSuffix = newText.length;
while (
oldSuffix > prefix &&
newSuffix > prefix &&
oldText[oldSuffix - 1] === newText[newSuffix - 1]
) {
oldSuffix -= 1;
newSuffix -= 1;
}
const oldChangedLength = oldSuffix - prefix;
const newChangedLength = newSuffix - prefix;
const sharedLength = Math.max(
oldText.length - oldChangedLength,
newText.length - newChangedLength
);
const similarity = sharedLength / Math.max(oldText.length, newText.length, 1);
const changedLength = side === 'removed' ? oldChangedLength : newChangedLength;
if (similarity < 0.55 || changedLength / Math.max(text.length, 1) > 0.45) {
return [{ text: text || ' ', changed: false }];
}
const end = side === 'removed' ? oldSuffix : newSuffix;
const changed = text.slice(prefix, end);
const tokenStart = changed.search(/[A-Za-z0-9_$]/);
if (tokenStart < 0) return [{ text: text || ' ', changed: false }];
const tokenEnd = changed.search(/[A-Za-z0-9_$][^A-Za-z0-9_$]*$/);
const highlightStart = tokenStart >= 0 ? prefix + tokenStart : prefix;
const highlightEnd = tokenEnd >= 0 ? prefix + tokenEnd + 1 : end;
const segments = [
{ text: text.slice(0, highlightStart), changed: false },
{ text: text.slice(highlightStart, highlightEnd), changed: true },
{ text: text.slice(highlightEnd), changed: false }
].filter((segment) => segment.text.length > 0);
return segments.length ? segments : [{ text: ' ', changed: false }];
}