-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathcode-block.gts
419 lines (369 loc) · 11.5 KB
/
code-block.gts
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
import { TemplateOnlyComponent } from '@ember/component/template-only';
import { registerDestructor } from '@ember/destroyable';
import { fn } from '@ember/helper';
import { hash } from '@ember/helper';
import { on } from '@ember/modifier';
import { service } from '@ember/service';
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { restartableTask, timeout, task } from 'ember-concurrency';
import perform from 'ember-concurrency/helpers/perform';
import Modifier from 'ember-modifier';
import { Copy as CopyIcon } from '@cardstack/boxel-ui/icons';
import ApplySearchReplaceBlockCommand from '@cardstack/host/commands/apply-search-replace-block';
import { MonacoEditorOptions } from '@cardstack/host/modifiers/monaco';
import type CardService from '@cardstack/host/services/card-service';
import CommandService from '@cardstack/host/services/command-service';
import LoaderService from '@cardstack/host/services/loader-service';
import { MonacoSDK } from '@cardstack/host/services/monaco-service';
import ApplyButton from '../ai-assistant/apply-button';
import { CodeData } from './formatted-message';
import type { ComponentLike } from '@glint/template';
import type * as _MonacoSDK from 'monaco-editor';
interface CopyCodeButtonSignature {
Args: {
code?: string;
};
}
interface ApplyCodePatchButtonSignature {
Args: {
codePatch?: string | null;
fileUrl?: string | null;
};
}
interface CodeBlockActionsSignature {
Args: {
codeData?: Partial<CodeData>;
};
Blocks: {
default: [
{
copyCode: ComponentLike<CopyCodeButtonSignature>;
applyCodePatch: ComponentLike<ApplyCodePatchButtonSignature>;
},
];
};
actions: [];
}
interface CodeBlockEditorSignature {
Args: {};
}
interface Signature {
Args: {
monacoSDK: MonacoSDK;
codeData: Partial<CodeData>;
};
Blocks: {
default: [
{
editor: ComponentLike<CodeBlockEditorSignature>;
actions: ComponentLike<CodeBlockActionsSignature>;
},
];
};
Element: HTMLElement;
}
let CodeBlockComponent: TemplateOnlyComponent<Signature> = <template>
{{yield
(hash
editor=(component CodeBlockEditor monacoSDK=@monacoSDK codeData=@codeData)
actions=(component CodeBlockActionsComponent codeData=@codeData)
)
}}
</template>;
export default CodeBlockComponent;
interface MonacoEditorSignature {
Args: {
Named: {
codeData: Partial<CodeData>;
monacoSDK: MonacoSDK;
editorDisplayOptions: MonacoEditorOptions;
};
};
}
function applyCodeDiffDecorations(
editor: _MonacoSDK.editor.IStandaloneCodeEditor,
monacoSDK: MonacoSDK,
codeData: Partial<CodeData>,
) {
if (codeData.searchStartLine && codeData.searchEndLine) {
editor.deltaDecorations(
[],
[
{
range: new monacoSDK.Range(
codeData.searchStartLine,
0,
codeData.searchEndLine,
1000, // Arbitrary large number to ensure the decoration spans the entire line
),
options: { inlineClassName: 'line-to-be-replaced' },
},
],
);
}
if (codeData.replaceStartLine && codeData.replaceEndLine) {
editor.deltaDecorations(
[],
[
{
range: new monacoSDK.Range(
codeData.replaceStartLine,
0,
codeData.replaceEndLine,
1000, // Arbitrary large number to ensure the decoration spans the entire line
),
options: { inlineClassName: 'line-to-be-replaced-with' },
},
],
);
}
}
class MonacoEditor extends Modifier<MonacoEditorSignature> {
private monacoState: {
editor: _MonacoSDK.editor.IStandaloneCodeEditor;
} | null = null;
modify(
element: HTMLElement,
_positional: [],
{
codeData,
monacoSDK,
editorDisplayOptions,
}: MonacoEditorSignature['Args']['Named'],
) {
let { code, language } = codeData;
if (!code || !language) {
return;
}
if (this.monacoState) {
let { editor } = this.monacoState;
let model = editor.getModel()!;
// Here we are appending deltas when code is "streaming" in, which is
// useful when code changes frequently in short periods of time. In this
// case we calculate the delta of the new code and the current code, and
// then apply that delta to the model. Compared to calling setValue()
// for every new value, this removes the need for re-tokenizing the code
// which is expensive and produces visual annoyances such as flickering.
let currentCode = model.getValue();
let newCode = code ?? '';
if (!newCode.startsWith(currentCode)) {
// This is a safety net for rare cases where the new code streamed in
// does not begin with the current code. This can happen when streaming
// in code with search/replace diff markers and the diff marker in chunk
// is incomplete, for example "<<<<<<< SEAR" instead of
// "<<<<<<< SEARCH". In this case the code diff parsing logic
// in parseCodeContent will not recognize the diff marker and it will
// display "<<<<<<< SEAR" for a brief moment in the editor, before getting
// a chunk with a complete diff marker. In this case we need to reset
// the data otherwise the appending delta will be incorrect and we'll
// see mangled code in the editor (syntax errors with incomplete diff markers).
model.setValue(newCode);
} else {
let codeDelta = newCode.slice(currentCode.length);
let lineCount = model.getLineCount();
let lastLineLength = model.getLineLength(lineCount);
let range = {
startLineNumber: lineCount,
startColumn: lastLineLength + 1,
endLineNumber: lineCount,
endColumn: lastLineLength + 1,
};
let editOperation = {
range: range,
text: codeDelta,
forceMoveMarkers: true,
};
let withDisabledReadOnly = (
readOnlySetting: boolean,
fn: () => void,
) => {
editor.updateOptions({ readOnly: false });
fn();
editor.updateOptions({ readOnly: readOnlySetting });
};
withDisabledReadOnly(!!editorDisplayOptions.readOnly, () => {
editor.executeEdits('append-source', [editOperation]);
});
editor.revealLine(lineCount + 1); // Scroll to the end as the code streams
applyCodeDiffDecorations(editor, monacoSDK, codeData);
}
} else {
let monacoContainer = element;
let editor = monacoSDK.editor.create(
monacoContainer,
editorDisplayOptions,
);
let model = editor.getModel()!;
monacoSDK.editor.setModelLanguage(model, language);
model.setValue(code);
applyCodeDiffDecorations(editor, monacoSDK, codeData);
this.monacoState = {
editor,
};
}
registerDestructor(this, () => {
let editor = this.monacoState?.editor;
if (editor) {
editor.dispose();
}
});
}
}
class CodeBlockEditor extends Component<Signature> {
editorDisplayOptions: MonacoEditorOptions = {
wordWrap: 'on',
wrappingIndent: 'indent',
fontWeight: 'bold',
scrollbar: {
alwaysConsumeMouseWheel: false,
},
lineNumbers: 'off',
minimap: {
enabled: false,
},
readOnly: true,
};
<template>
<style scoped>
:global(.line-to-be-replaced) {
background-color: rgb(255 0 0 / 37%);
}
:global(.line-to-be-replaced-with) {
background-color: rgb(6 144 29 / 56%);
}
.code-block {
margin-bottom: 15px;
width: calc(100% + 2 * var(--boxel-sp));
margin-left: calc(-1 * var(--boxel-sp));
height: 120px;
}
</style>
<div
{{MonacoEditor
monacoSDK=@monacoSDK
codeData=@codeData
editorDisplayOptions=this.editorDisplayOptions
}}
class='code-block'
data-test-editor
>
{{! Don't put anything here in this div as monaco modifier will override this element }}
</div>
</template>
}
let CodeBlockActionsComponent: TemplateOnlyComponent<CodeBlockActionsSignature> =
<template>
<style scoped>
.code-block-actions {
background: black;
height: 50px;
padding: var(--boxel-sp-sm) 27px;
padding-right: var(--boxel-sp);
display: flex;
justify-content: flex-start;
width: calc(100% + 2 * var(--boxel-sp));
margin-left: calc(-1 * var(--boxel-sp));
}
</style>
<div class='code-block-actions'>
{{yield
(hash
copyCode=(component CopyCodeButton code=@codeData.code)
applyCodePatch=(component
ApplyCodePatchButton
codePatch=@codeData.contentWithoutFileUrl
fileUrl=@codeData.fileUrl
)
)
}}
</div>
</template>;
class CopyCodeButton extends Component<CopyCodeButtonSignature> {
@tracked copyCodeButtonText: 'Copy' | 'Copied!' = 'Copy';
copyCode = restartableTask(async (code: string) => {
this.copyCodeButtonText = 'Copied!';
await navigator.clipboard.writeText(code);
await timeout(1000);
this.copyCodeButtonText = 'Copy';
});
<template>
<style scoped>
.code-copy-button {
color: var(--boxel-highlight);
background: none;
border: none;
font: 600 var(--boxel-font-xs);
padding: 0;
display: flex;
margin: auto;
width: 100%;
}
.code-copy-button svg {
margin-right: var(--boxel-sp-xs);
}
.copy-icon {
--icon-color: var(--boxel-highlight);
}
.copy-text {
display: none;
}
.code-copy-button:hover .copy-text {
display: block;
}
.code-copy-button .copy-text.shown {
display: block;
}
</style>
<button
class='code-copy-button'
{{on 'click' (fn (perform this.copyCode) @code)}}
data-test-copy-code
>
<CopyIcon
width='16'
height='16'
role='presentation'
aria-hidden='true'
class='copy-icon'
/>
<span
class='copy-text {{if this.copyCode.isRunning "shown"}}'
>{{this.copyCodeButtonText}}</span>
</button>
</template>
}
class ApplyCodePatchButton extends Component<ApplyCodePatchButtonSignature> {
@service private declare loaderService: LoaderService;
@service private declare commandService: CommandService;
@service private declare cardService: CardService;
@tracked patchCodeTaskState: 'ready' | 'applying' | 'applied' | 'failed' =
'ready';
private patchCodeTask = task(async (codePatch: string, fileUrl: string) => {
this.patchCodeTaskState = 'applying';
try {
let source = await this.cardService.getSource(new URL(fileUrl));
let applySearchReplaceBlockCommand = new ApplySearchReplaceBlockCommand(
this.commandService.commandContext,
);
let { resultContent: patchedCode } =
await applySearchReplaceBlockCommand.execute({
fileContent: source,
codeBlock: codePatch,
});
await this.cardService.saveSource(new URL(fileUrl), patchedCode);
this.loaderService.reset();
this.patchCodeTaskState = 'applied';
} catch (error) {
console.error(error);
this.patchCodeTaskState = 'failed';
}
});
<template>
<ApplyButton
data-test-apply-code-button
@state={{this.patchCodeTaskState}}
{{on 'click' (fn (perform this.patchCodeTask) @codePatch @fileUrl)}}
/>
</template>
}