mirror of
https://github.com/open-webui/open-webui.git
synced 2026-11-22 21:50:42 -05:00
refac
This commit is contained in:
1 parent
d821e78756
commit
d61a91700a
4 files changed
+194
-3
No files matched your search
@@ -1,7 +1,8 @@
|
||||
<script lang="ts">
|
||||
import type { TerminalContext } from '$lib/types';
|
||||
import type { TerminalConnection } from '$lib/apis/terminal';
|
||||
import type { GitStatus } from '$lib/apis/terminal/git';
|
||||
import { gitRequest, type GitStatus, type GitFile } from '$lib/apis/terminal/git';
|
||||
import { reverseGitDiff } from './Messages/diff';
|
||||
import FileGitDiff from './FileNav/FileGitDiff.svelte';
|
||||
import { gitTreePath, gitTreeStatus } from './FileNav/gitTreeStatus';
|
||||
import { filesystemFile, type FilesystemFile } from '$lib/apis/terminal';
|
||||
@@ -651,6 +652,73 @@
|
||||
let filePreviewRef: FilePreview;
|
||||
let commentPreviewRef: CommentFilePreview;
|
||||
let commentGeneration = 0;
|
||||
let gitBaseContent: string | null = null;
|
||||
let gitBaseGeneration = 0;
|
||||
let gitBaseKey = '';
|
||||
const loadGitBase = async (
|
||||
connection: TerminalConnection | null,
|
||||
session: string | null,
|
||||
status: GitStatus | null,
|
||||
file: GitFile | null,
|
||||
path: string | null,
|
||||
content: string | null,
|
||||
loading: boolean,
|
||||
_version: number
|
||||
) => {
|
||||
const generation = ++gitBaseGeneration;
|
||||
const key = JSON.stringify([connection, session, path]);
|
||||
if (key !== gitBaseKey) gitBaseContent = null;
|
||||
gitBaseKey = key;
|
||||
const root = status?.is_repo && status.root ? normalizePath(status.root) : null;
|
||||
if (
|
||||
!connection ||
|
||||
root === null ||
|
||||
!path ||
|
||||
content === null ||
|
||||
loading ||
|
||||
file?.binary ||
|
||||
!normalizePath(path).startsWith(`${root.replace(/\/$/, '')}/`)
|
||||
) {
|
||||
gitBaseContent = null;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
let base = content;
|
||||
if (file?.status === 'untracked' || file?.status === 'added') base = '';
|
||||
else if (file) {
|
||||
const [unstaged, staged] = await Promise.all([
|
||||
file.unstaged
|
||||
? gitRequest<{ diff: string }>(connection, session, root, 'diff', {
|
||||
file: file.path,
|
||||
staged: 'false'
|
||||
})
|
||||
: null,
|
||||
file.staged
|
||||
? gitRequest<{ diff: string }>(connection, session, root, 'diff', {
|
||||
file: file.path,
|
||||
staged: 'true'
|
||||
})
|
||||
: null
|
||||
]);
|
||||
if (unstaged) base = reverseGitDiff(base, unstaged.diff);
|
||||
if (staged) base = reverseGitDiff(base, staged.diff);
|
||||
}
|
||||
if (generation === gitBaseGeneration) gitBaseContent = base;
|
||||
} catch {
|
||||
// A stale patch or unavailable Git service must not interfere with editing.
|
||||
if (generation === gitBaseGeneration) gitBaseContent = null;
|
||||
}
|
||||
};
|
||||
$: void loadGitBase(
|
||||
gitConnection,
|
||||
chatId,
|
||||
gitStatus,
|
||||
currentGitFile,
|
||||
selectedFile,
|
||||
fileContent,
|
||||
fileLoading,
|
||||
commentGeneration
|
||||
);
|
||||
let fileSearchTarget: FileSearchTarget | null = null;
|
||||
let documentTargetPage: number | null = null;
|
||||
|
||||
@@ -2108,6 +2176,7 @@
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
++gitBaseGeneration;
|
||||
overwriteChoice?.(false);
|
||||
disposed = true;
|
||||
++loadGeneration;
|
||||
@@ -2603,6 +2672,7 @@
|
||||
{/key}
|
||||
{:else}
|
||||
<FilePreview
|
||||
{gitBaseContent}
|
||||
bind:this={filePreviewRef}
|
||||
bind:editing
|
||||
bind:showRaw
|
||||
|
||||
@@ -2,8 +2,22 @@
|
||||
import '$lib/utils/codemirror';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { basicSetup, EditorView } from 'codemirror';
|
||||
import { keymap, placeholder as editorPlaceholder } from '@codemirror/view';
|
||||
import { Compartment, EditorState } from '@codemirror/state';
|
||||
import {
|
||||
keymap,
|
||||
placeholder as editorPlaceholder,
|
||||
GutterMarker,
|
||||
gutterLineClass
|
||||
} from '@codemirror/view';
|
||||
import {
|
||||
Compartment,
|
||||
EditorState,
|
||||
RangeSet,
|
||||
StateEffect,
|
||||
StateField,
|
||||
type Range,
|
||||
type Text
|
||||
} from '@codemirror/state';
|
||||
import { Chunk } from '@codemirror/merge';
|
||||
import { indentWithTab, historyField } from '@codemirror/commands';
|
||||
import { completeAnyWord } from '@codemirror/autocomplete';
|
||||
import { indentUnit, LanguageDescription } from '@codemirror/language';
|
||||
@@ -16,6 +30,7 @@
|
||||
export let placeholder = '';
|
||||
export let ariaLabel = '';
|
||||
export let filePath: string | null = null;
|
||||
export let gitBaseContent: string | null = null;
|
||||
export let onSave: ((content: string) => Promise<void>) | null = null;
|
||||
export let searchTarget: {
|
||||
line: number;
|
||||
@@ -24,6 +39,61 @@
|
||||
requestId: number;
|
||||
} | null = null;
|
||||
|
||||
class GitLineMarker extends GutterMarker {
|
||||
readonly elementClass: string;
|
||||
constructor(elementClass: string) {
|
||||
super();
|
||||
this.elementClass = elementClass;
|
||||
}
|
||||
}
|
||||
const added = new GitLineMarker('cm-git-line-added');
|
||||
const modified = new GitLineMarker('cm-git-line-modified');
|
||||
const diffConfig = { timeout: 50 };
|
||||
const setGitBase = StateEffect.define<string | null>();
|
||||
|
||||
function markers(base: Text, doc: Text, chunks: readonly Chunk[]) {
|
||||
const ranges: Range<GutterMarker>[] = [];
|
||||
for (const chunk of chunks) {
|
||||
if (chunk.fromB === chunk.toB) continue;
|
||||
const removed =
|
||||
chunk.fromA === chunk.toA || !base.length
|
||||
? 0
|
||||
: base.lineAt(chunk.endA).number - base.lineAt(chunk.fromA).number + 1;
|
||||
const start = doc.lineAt(chunk.fromB).number;
|
||||
const end = doc.lineAt(chunk.endB).number;
|
||||
for (let number = start; number <= end; number++) {
|
||||
const line = doc.line(number);
|
||||
if (line.from === doc.length && !line.length) continue;
|
||||
ranges.push((number - start < removed ? modified : added).range(line.from));
|
||||
}
|
||||
}
|
||||
return RangeSet.of(ranges);
|
||||
}
|
||||
|
||||
const gitLineChanges = StateField.define<{
|
||||
base: Text | null;
|
||||
chunks: readonly Chunk[];
|
||||
markers: RangeSet<GutterMarker>;
|
||||
}>({
|
||||
create: () => ({ base: null, chunks: [], markers: RangeSet.empty }),
|
||||
update(value, transaction) {
|
||||
const effect = transaction.effects.find((effect) => effect.is(setGitBase));
|
||||
if (!effect && (!transaction.docChanged || value.base === null)) return value;
|
||||
const base = effect
|
||||
? effect.value === null
|
||||
? null
|
||||
: EditorState.create({ doc: effect.value }).doc
|
||||
: value.base;
|
||||
if (base === null) return { base, chunks: [], markers: RangeSet.empty };
|
||||
const doc = transaction.state.doc;
|
||||
const chunks = effect
|
||||
? Chunk.build(base, doc, diffConfig)
|
||||
: Chunk.updateB(value.chunks, base, doc, transaction.changes, diffConfig);
|
||||
return { base, chunks, markers: markers(base, doc, chunks) };
|
||||
},
|
||||
provide: (field) => gutterLineClass.from(field, (value) => value.markers)
|
||||
});
|
||||
|
||||
let container: HTMLDivElement;
|
||||
let editor: EditorView | null = null;
|
||||
let editorTheme = new Compartment();
|
||||
@@ -49,6 +119,7 @@
|
||||
EditorState.fromJSON(view.editorJSON, { extensions }, { history: historyField })
|
||||
);
|
||||
value = internalValue = editor.state.doc.toString();
|
||||
editor.dispatch({ effects: setGitBase.of(gitBaseContent) });
|
||||
editor.scrollDOM.scrollTop = view.scrollTop ?? 0;
|
||||
editor.scrollDOM.scrollLeft = view.scrollLeft ?? 0;
|
||||
}
|
||||
@@ -136,6 +207,7 @@
|
||||
$: if (editor && searchTarget) {
|
||||
revealSearchTarget();
|
||||
}
|
||||
$: if (editor) editor.dispatch({ effects: setGitBase.of(gitBaseContent) });
|
||||
|
||||
onMount(() => {
|
||||
const isDark = document.documentElement.classList.contains('dark');
|
||||
@@ -143,6 +215,7 @@
|
||||
|
||||
extensions = [
|
||||
basicSetup,
|
||||
gitLineChanges,
|
||||
EditorState.languageData.of(() => [{ autocomplete: completeAnyWord }]),
|
||||
keymap.of([
|
||||
indentWithTab,
|
||||
@@ -220,4 +293,17 @@
|
||||
.file-code-editor :global(.cm-editor) {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.file-code-editor :global(.cm-lineNumbers .cm-git-line-added) {
|
||||
box-shadow: inset 2px 0 0 rgba(5, 150, 105, 0.65);
|
||||
}
|
||||
.file-code-editor :global(.cm-lineNumbers .cm-git-line-modified) {
|
||||
box-shadow: inset 2px 0 0 rgba(217, 119, 6, 0.6);
|
||||
}
|
||||
:global(.dark) .file-code-editor :global(.cm-lineNumbers .cm-git-line-added) {
|
||||
box-shadow: inset 2px 0 0 rgba(52, 211, 153, 0.75);
|
||||
}
|
||||
:global(.dark) .file-code-editor :global(.cm-lineNumbers .cm-git-line-modified) {
|
||||
box-shadow: inset 2px 0 0 rgba(251, 191, 36, 0.7);
|
||||
}
|
||||
</style>
|
||||
@@ -34,6 +34,7 @@
|
||||
export let fileModelData: ArrayBuffer | null = null;
|
||||
export let fileDocxData: ArrayBuffer | null = null;
|
||||
export let fileContent: string | null = null;
|
||||
export let gitBaseContent: string | null = null;
|
||||
|
||||
// Terminal connection for notebook execution
|
||||
export let baseUrl: string = '';
|
||||
@@ -417,6 +418,7 @@
|
||||
{#if searchTarget}
|
||||
<div class="absolute inset-0">
|
||||
<FileCodeEditor
|
||||
{gitBaseContent}
|
||||
{readOnly}
|
||||
bind:this={fileCodeEditorRef}
|
||||
bind:value={codeValue}
|
||||
@@ -460,6 +462,7 @@
|
||||
{:else if isHtml && showRaw}
|
||||
<div class="absolute inset-0">
|
||||
<FileCodeEditor
|
||||
{gitBaseContent}
|
||||
{readOnly}
|
||||
bind:this={fileCodeEditorRef}
|
||||
bind:value={codeValue}
|
||||
@@ -496,6 +499,7 @@
|
||||
{:else if isMarkdown && showRaw}
|
||||
<div class="absolute inset-0">
|
||||
<FileCodeEditor
|
||||
{gitBaseContent}
|
||||
{readOnly}
|
||||
bind:this={fileCodeEditorRef}
|
||||
bind:value={codeValue}
|
||||
@@ -559,6 +563,7 @@
|
||||
{:else if isCode && !showRaw}
|
||||
<div class="absolute inset-0">
|
||||
<FileCodeEditor
|
||||
{gitBaseContent}
|
||||
{readOnly}
|
||||
bind:this={fileCodeEditorRef}
|
||||
bind:value={codeValue}
|
||||
|
||||
@@ -111,3 +111,33 @@ export function emphasizePair(oldRow: DiffRow, newRow: DiffRow) {
|
||||
].filter((segment) => segment.text.length > 0);
|
||||
}
|
||||
}
|
||||
|
||||
// Reverse a Git patch against the saved file, leaving the editor's unsaved buffer alone.
|
||||
export function reverseGitDiff(content: string, patch: string): string {
|
||||
const lines = content.replace(/\r\n/g, '\n').match(/[^\n]*\n|[^\n]+$/g) ?? [];
|
||||
const base: string[] = [];
|
||||
let index = 0;
|
||||
let previous = '';
|
||||
for (const row of parseDiffRows(patch.replace(/\r\n/g, '\n'))) {
|
||||
if (row.type === 'hunk') {
|
||||
const match = row.content.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/);
|
||||
if (!match) throw new Error('Invalid Git hunk');
|
||||
const start = Number(match[1]) - (match[2] === '0' ? 0 : 1);
|
||||
if (start < index || start > lines.length) throw new Error('Git diff is out of date');
|
||||
base.push(...lines.slice(index, start));
|
||||
index = start;
|
||||
} else if (row.type === 'meta' && row.content.startsWith('\\ No newline')) {
|
||||
if (previous !== 'addition' && base.length)
|
||||
base[base.length - 1] = base[base.length - 1].replace(/\n$/, '');
|
||||
} else if (row.oldNumber !== null || row.newNumber !== null) {
|
||||
if (row.type !== 'deletion') {
|
||||
if (lines[index]?.replace(/\n$/, '') !== row.content)
|
||||
throw new Error('Git diff is out of date');
|
||||
index++;
|
||||
}
|
||||
if (row.type !== 'addition') base.push(`${row.content}\n`);
|
||||
previous = row.type;
|
||||
}
|
||||
}
|
||||
return base.concat(lines.slice(index)).join('');
|
||||
}
|
||||
Reference in new issue
Block a user