-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreaming-diff-example.js
More file actions
264 lines (210 loc) · 7.72 KB
/
streaming-diff-example.js
File metadata and controls
264 lines (210 loc) · 7.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
// Practical example: Streaming diffs into any text editor or web interface
// This demonstrates the core concepts without VSCode dependencies
const {
stringDiff,
createEditsFromRealDiff,
linesToText,
} = require('./dist/index.js');
/**
* Simulate streaming a diff with visual feedback
*/
class DiffStreamer {
constructor(onUpdate, onHighlight) {
this.onUpdate = onUpdate; // Callback when text changes
this.onHighlight = onHighlight; // Callback to highlight changes
}
async streamDiff(originalText, modifiedText, delayMs = 500) {
console.log('🚀 Starting diff stream...\n');
// Compute the differences
const changes = stringDiff(originalText, modifiedText, true);
console.log(`Found ${changes.length} changes to apply\n`);
let currentText = originalText;
let cumulativeOffset = 0;
for (let i = 0; i < changes.length; i++) {
const change = changes[i];
console.log(`📝 Applying change ${i + 1}/${changes.length}:`);
console.log(` Range: ${change.originalStart}-${change.originalStart + change.originalLength}`);
console.log(` Original: "${originalText.substring(change.originalStart, change.originalStart + change.originalLength)}"`);
// Extract new text
const newText = modifiedText.substring(
change.modifiedStart,
change.modifiedStart + change.modifiedLength
);
console.log(` New: "${newText}"`);
// Apply the change to current text
const adjustedStart = change.originalStart + cumulativeOffset;
const adjustedEnd = adjustedStart + change.originalLength;
currentText = currentText.substring(0, adjustedStart) +
newText +
currentText.substring(adjustedEnd);
// Update cumulative offset for next changes
cumulativeOffset += newText.length - change.originalLength;
// Notify callbacks
this.onUpdate(currentText, adjustedStart, adjustedStart + newText.length);
this.onHighlight(adjustedStart, adjustedStart + newText.length);
console.log(` Result: "${currentText}"\n`);
// Wait before next change
await new Promise(resolve => setTimeout(resolve, delayMs));
}
console.log('✅ Diff streaming complete!');
return currentText;
}
}
/**
* Stream a unified diff (like git diff output)
*/
async function streamUnifiedDiff(originalLines, diffLines, onUpdate, delayMs = 300) {
console.log('🔄 Processing unified diff...\n');
// Parse the diff
const edits = createEditsFromRealDiff(originalLines, diffLines);
console.log(`Parsed ${edits.length} line edits\n`);
let currentLines = [...originalLines];
// Apply edits one by one (in reverse order to maintain line numbers)
const sortedEdits = [...edits].sort((a, b) => b.start - a.start);
for (let i = 0; i < sortedEdits.length; i++) {
const edit = sortedEdits[i];
console.log(`📋 Applying edit ${i + 1}/${sortedEdits.length}:`);
console.log(` Lines ${edit.start}-${edit.end}: ${edit.replacement.length ? 'replace' : 'delete'}`);
if (edit.replacement.length > 0) {
console.log(` New content: ${edit.replacement.join(', ')}`);
}
// Apply the edit
currentLines.splice(edit.start, edit.end - edit.start, ...edit.replacement);
// Notify callback
const currentText = linesToText(currentLines);
onUpdate(currentText, edit.start, edit.start + edit.replacement.length);
console.log(` Current state: ${currentLines.length} lines\n`);
await new Promise(resolve => setTimeout(resolve, delayMs));
}
console.log('✅ Unified diff streaming complete!');
return currentLines;
}
/**
* Demo: Git-like diff streaming
*/
async function demoGitDiffStreaming() {
console.log('=== Git Diff Streaming Demo ===\n');
const originalCode = `function hello() {
console.log("Hello World");
return "world";
}`;
const modifiedCode = `function greet(name) {
console.log("Hello " + name);
return "Hello " + name;
}`;
const streamer = new DiffStreamer(
(text, start, end) => {
// In a real editor, this would update the display
console.log(`📺 Editor updated (changed chars ${start}-${end})`);
},
(start, end) => {
// In a real editor, this would highlight the changed region
console.log(`🎨 Highlighting chars ${start}-${end}`);
}
);
await streamer.streamDiff(originalCode, modifiedCode, 800);
}
/**
* Demo: Unified diff streaming (like applying a patch)
*/
async function demoUnifiedDiffStreaming() {
console.log('\n=== Unified Diff Streaming Demo ===\n');
const originalLines = [
'line 1',
'old line 2',
'line 3',
'line 4'
];
const unifiedDiff = [
'@@ -1,4 +1,4 @@',
' line 1',
'-old line 2',
'+new line 2',
' line 3',
'+inserted line',
' line 4'
];
console.log('Original:', originalLines);
console.log('Diff:', unifiedDiff);
console.log();
const result = await streamUnifiedDiff(
originalLines,
unifiedDiff,
(text, startLine, endLine) => {
console.log(`📺 Document updated (lines ${startLine}-${endLine})`);
},
500
);
console.log('Final result:', result);
}
/**
* Demo: Real-time collaboration simulation
*/
async function demoCollaborativeEditing() {
console.log('\n=== Collaborative Editing Demo ===\n');
let documentState = 'The quick brown fox jumps over the lazy dog.';
console.log(`Initial document: "${documentState}"\n`);
// Simulate multiple users making changes
const userChanges = [
{ user: 'Alice', text: 'The quick red fox jumps over the lazy dog.' },
{ user: 'Bob', text: 'The quick red fox leaps over the lazy dog.' },
{ user: 'Charlie', text: 'The quick red fox leaps over the sleepy dog.' }
];
for (const change of userChanges) {
console.log(`👤 ${change.user} is making changes...`);
const streamer = new DiffStreamer(
(text) => {
documentState = text;
console.log(`📄 Document: "${documentState}"`);
},
(start, end) => {
console.log(`✨ Change highlighted: chars ${start}-${end}`);
}
);
await streamer.streamDiff(documentState, change.text, 400);
console.log();
}
console.log(`Final collaborative document: "${documentState}"`);
}
/**
* Demo: Code generation streaming
*/
async function demoCodeGeneration() {
console.log('\n=== Code Generation Streaming Demo ===\n');
const template = `// TODO: Implement function
function processData() {
// Implementation needed
}`;
const generated = `// Auto-generated function
function processData(input) {
const result = input.map(item => item * 2);
return result.filter(value => value > 0);
}`;
console.log('🤖 AI Code Generation Streaming...\n');
const streamer = new DiffStreamer(
(text, start, end) => {
console.log(`💻 Code updated (chars ${start}-${end})`);
},
(start, end) => {
console.log(`🔍 Generated code highlighted`);
}
);
await streamer.streamDiff(template, generated, 600);
}
// Run all demos
async function runAllDemos() {
await demoGitDiffStreaming();
await demoUnifiedDiffStreaming();
await demoCollaborativeEditing();
await demoCodeGeneration();
console.log('\n🎉 All streaming demos completed!');
console.log('\n💡 Integration possibilities:');
console.log(' • VSCode extensions for diff streaming');
console.log(' • Web-based code editors with real-time updates');
console.log(' • Collaborative editing platforms');
console.log(' • AI code generation with visual feedback');
console.log(' • Git integration tools');
console.log(' • Code review and merge tools');
}
// Run the demos
runAllDemos().catch(console.error);