Elffuss BraidHub

kikocis/continue public

247f4e9d534b · 11.7 KiBRawPermalink
1/* eslint-disable @typescript-eslint/naming-convention */
2import { EXTENSION_NAME } from "core/control-plane/env";
3// @ts-ignore
4import svgBuilder from "svg-builder";
5import * as vscode from "vscode";
6
7import { getTheme } from "../util/getTheme";
8import { getMetaKeyLabel, getMetaKeyName } from "../util/util";
9
10const SVG_CONFIG = {
11 stroke: "#999998",
12 strokeWidth: 1,
13 shortcutColor: "#999998",
14 filter: "drop-shadow(0 2px 2px rgba(0,0,0,0.2))",
15 radius: 3,
16 leftMargin: 40,
17 debounceDelay: 500,
18 chatLabel: "Chat",
19 chatShortcut: `${getMetaKeyLabel()}+L`,
20 editLabel: "Edit",
21 editShortcut: `${getMetaKeyLabel()}+I`,
22
23 get fontSize() {
24 return Math.ceil(
25 (vscode.workspace.getConfiguration("editor").get<number>("fontSize") ??
26 14) * 0.8,
27 );
28 },
29 get fontFamily() {
30 return (
31 vscode.workspace.getConfiguration("editor").get<string>("fontFamily") ||
32 "helvetica"
33 );
34 },
35 get paddingX() {
36 return Math.ceil(this.getEstimatedTextWidth(" "));
37 },
38 get gap() {
39 return this.fontSize * 0.5;
40 },
41 get tipWidth() {
42 return (
43 this.editShortcutX +
44 this.getEstimatedTextWidth(this.editShortcut) +
45 this.paddingX
46 );
47 },
48 get tipHeight() {
49 return this.fontSize;
50 },
51 get textY() {
52 return (this.tipHeight + this.fontSize) / 2;
53 },
54 get chatLabelX() {
55 return this.paddingX;
56 },
57 get chatShortcutX() {
58 return this.chatLabelX + this.getEstimatedTextWidth(this.chatLabel + " ");
59 },
60 get editLabelX() {
61 return (
62 this.chatShortcutX +
63 this.getEstimatedTextWidth(this.chatShortcut) +
64 this.gap
65 );
66 },
67 get editShortcutX() {
68 return this.editLabelX + this.getEstimatedTextWidth(this.editLabel + " ");
69 },
70 getEstimatedTextWidth(text: string): number {
71 return text.length * this.fontSize * 0.6;
72 },
73} as const;
74
75export class InlineTipManager {
76 private static instance: InlineTipManager;
77
78 private readonly excludedURIPrefixes = ["output:", "vscode://inline-chat"];
79 private readonly hideCommand = "continue.hideInlineTip";
80 private svgTooltip: vscode.Uri | undefined = undefined;
81
82 private debounceTimer: NodeJS.Timeout | undefined;
83 private lastActiveEditor?: vscode.TextEditor;
84 private theme = getTheme();
85 private svgTooltipDecoration = this.createSvgTooltipDecoration();
86 private emptyFileTooltipDecoration = this.createEmptyFileTooltipDecoration();
87
88 public static getInstance(): InlineTipManager {
89 if (!InlineTipManager.instance) {
90 InlineTipManager.instance = new InlineTipManager();
91 }
92 return InlineTipManager.instance;
93 }
94
95 private constructor() {
96 this.createSvgTooltip();
97 this.setupSvgTipListeners();
98 }
99
100 public setupInlineTips(context: vscode.ExtensionContext) {
101 context.subscriptions.push(
102 vscode.window.onDidChangeTextEditorSelection((e) => {
103 this.handleSelectionChange(e);
104 }),
105 );
106
107 this.setupEmptyFileTips(context);
108
109 context.subscriptions.push(this);
110 }
111
112 public handleSelectionChange(e: vscode.TextEditorSelectionChangeEvent) {
113 const selection = e.selections[0];
114 const editor = e.textEditor;
115
116 if (selection.isEmpty || !this.shouldRenderTip(editor.document.uri)) {
117 editor.setDecorations(this.svgTooltipDecoration, []);
118 return;
119 }
120
121 this.debouncedSelectionChange(editor, selection);
122 }
123
124 public dispose() {
125 this.svgTooltipDecoration.dispose();
126 this.emptyFileTooltipDecoration.dispose();
127
128 if (this.debounceTimer) {
129 clearTimeout(this.debounceTimer);
130 }
131 }
132
133 private debouncedSelectionChange(
134 editor: vscode.TextEditor,
135 selection: vscode.Selection,
136 ) {
137 if (this.debounceTimer) {
138 clearTimeout(this.debounceTimer);
139 }
140
141 this.debounceTimer = setTimeout(() => {
142 // Clear decoration from previous editor
143 if (this.lastActiveEditor && this.lastActiveEditor !== editor) {
144 this.lastActiveEditor.setDecorations(this.svgTooltipDecoration, []);
145 }
146
147 this.lastActiveEditor = editor;
148
149 this.updateTooltipPosition(editor, selection);
150 }, SVG_CONFIG.debounceDelay);
151 }
152
153 private setupSvgTipListeners() {
154 vscode.workspace.onDidChangeConfiguration((e) => {
155 if (e.affectsConfiguration("workbench.colorTheme")) {
156 this.theme = getTheme();
157 this.createSvgTooltip();
158 }
159 });
160
161 vscode.workspace.onDidChangeConfiguration((e) => {
162 if (e.affectsConfiguration("editor.fontSize")) {
163 this.createSvgTooltip();
164 }
165 });
166 }
167
168 private shouldRenderTip(uri: vscode.Uri): boolean {
169 const isAllowedUri =
170 !this.excludedURIPrefixes.some((prefix) =>
171 uri.toString().startsWith(prefix),
172 ) && uri.scheme !== "comment";
173
174 const isEnabled =
175 !!vscode.workspace
176 .getConfiguration(EXTENSION_NAME)
177 .get<boolean>("showInlineTip") === true;
178
179 return isAllowedUri && isEnabled;
180 }
181
182 private setupEmptyFileTips(context: vscode.ExtensionContext) {
183 context.subscriptions.push(
184 vscode.window.onDidChangeActiveTextEditor((editor) => {
185 if (
186 editor?.document.getText() === "" &&
187 this.shouldRenderTip(editor.document.uri)
188 ) {
189 editor.setDecorations(this.emptyFileTooltipDecoration, [
190 {
191 range: new vscode.Range(
192 new vscode.Position(0, Number.MAX_VALUE),
193 new vscode.Position(0, Number.MAX_VALUE),
194 ),
195 },
196 ]);
197 }
198 }),
199 );
200
201 context.subscriptions.push(
202 vscode.workspace.onDidChangeTextDocument((e) => {
203 if (
204 e.document.getText() === "" &&
205 this.shouldRenderTip(e.document.uri)
206 ) {
207 vscode.window.visibleTextEditors.forEach((editor) => {
208 editor.setDecorations(this.emptyFileTooltipDecoration, [
209 {
210 range: new vscode.Range(
211 new vscode.Position(0, Number.MAX_VALUE),
212 new vscode.Position(0, Number.MAX_VALUE),
213 ),
214 },
215 ]);
216 });
217 } else {
218 vscode.window.visibleTextEditors.forEach((editor) => {
219 editor.setDecorations(this.emptyFileTooltipDecoration, []);
220 });
221 }
222 }),
223 );
224 }
225
226 private createEmptyFileTooltipDecoration() {
227 return vscode.window.createTextEditorDecorationType({
228 after: {
229 contentText: `Use ${getMetaKeyName()} + I to generate code`,
230 color: "#888",
231 margin: "2em 0 0 0",
232 fontStyle: "italic",
233 },
234 });
235 }
236
237 private createSvgTooltipDecoration() {
238 var backgroundColour = 0;
239 if (this.theme) {
240 backgroundColour = this.theme.colors["editor.background"];
241 }
242 return vscode.window.createTextEditorDecorationType({
243 after: {
244 contentIconPath: this.svgTooltip,
245 border: `;box-shadow: inset 0 0 0 ${SVG_CONFIG.strokeWidth}px ${SVG_CONFIG.stroke}, inset 0 0 0 ${SVG_CONFIG.tipHeight}px ${backgroundColour};
246 border-radius: ${SVG_CONFIG.radius}px;
247 filter: ${SVG_CONFIG.filter}`,
248 margin: `0 0 0 ${SVG_CONFIG.leftMargin}px`,
249 width: `${SVG_CONFIG.tipWidth}px`,
250 },
251 });
252 }
253
254 private createSvgTooltip() {
255 const baseTextConfig = {
256 y: SVG_CONFIG.textY,
257 "font-family": SVG_CONFIG.fontFamily,
258 "font-size": SVG_CONFIG.fontSize,
259 };
260
261 if (!this.theme) {
262 return;
263 }
264
265 try {
266 const svgContent = svgBuilder
267 .width(SVG_CONFIG.tipWidth)
268 .height(SVG_CONFIG.tipHeight)
269 // Chat
270 .text(
271 {
272 ...baseTextConfig,
273 x: SVG_CONFIG.chatLabelX,
274 fill: this.theme.colors["editor.foreground"],
275 },
276 SVG_CONFIG.chatLabel,
277 )
278 .text(
279 {
280 ...baseTextConfig,
281 x: SVG_CONFIG.chatShortcutX,
282 fill: SVG_CONFIG.shortcutColor,
283 },
284 SVG_CONFIG.chatShortcut,
285 )
286 // Edit
287 .text(
288 {
289 ...baseTextConfig,
290 x: SVG_CONFIG.editLabelX,
291 fill: this.theme.colors["editor.foreground"],
292 },
293 SVG_CONFIG.editLabel,
294 )
295 .text(
296 {
297 ...baseTextConfig,
298 x: SVG_CONFIG.editShortcutX,
299 fill: SVG_CONFIG.shortcutColor,
300 },
301 SVG_CONFIG.editShortcut,
302 )
303 .render();
304
305 const dataUri = `data:image/svg+xml;base64,${Buffer.from(svgContent).toString("base64")}`;
306
307 this.svgTooltip = vscode.Uri.parse(dataUri);
308 this.svgTooltipDecoration.dispose();
309 this.svgTooltipDecoration = this.createSvgTooltipDecoration();
310 } catch (error) {
311 console.error("Error creating SVG for inline tip:", error);
312 }
313 }
314
315 private buildHideTooltipHoverMsg() {
316 const hoverMarkdown = new vscode.MarkdownString(
317 `[Disable](command:${this.hideCommand})`,
318 );
319
320 hoverMarkdown.isTrusted = true;
321 hoverMarkdown.supportHtml = true;
322 return hoverMarkdown;
323 }
324
325 /**
326 * Calculates tooltip position using these rules:
327 * 1. For single-line selection: Place after the line's content
328 * 2. For multi-line selection: Place after the longer line between:
329 * - The first non-empty selected line
330 * - The line above the selection
331 * Returns null if selection is empty or contains only empty lines
332 */
333 private calculateTooltipPosition(
334 editor: vscode.TextEditor,
335 selection: vscode.Selection,
336 ): vscode.Position | null {
337 const document = editor.document;
338
339 // Get selection info
340 const startLine = selection.start.line;
341 const endLine = selection.end.line;
342 const isFullLineSelection =
343 selection.start.character === 0 &&
344 (selection.end.line > selection.start.line
345 ? selection.end.character === 0
346 : selection.end.character ===
347 document.lineAt(selection.end.line).text.length);
348
349 // Helper functions
350 const isLineEmpty = (lineNumber: number): boolean => {
351 return document.lineAt(lineNumber).text.trim().length === 0;
352 };
353
354 const getLineEndChar = (lineNumber: number): number => {
355 return document.lineAt(lineNumber).text.trimEnd().length;
356 };
357
358 // If single empty line selected and not full line selection, return null
359 if (
360 startLine === endLine &&
361 isLineEmpty(startLine) &&
362 !isFullLineSelection
363 ) {
364 return null;
365 }
366
367 // Find topmost non-empty line
368 let topNonEmptyLine = startLine;
369 while (topNonEmptyLine <= endLine && isLineEmpty(topNonEmptyLine)) {
370 topNonEmptyLine++;
371 }
372
373 // If all lines empty, return null
374 if (topNonEmptyLine > endLine) {
375 return null;
376 }
377
378 const OFFSET = 4; // Characters to offset from end of line
379
380 // Single line or full line selection
381 if (isFullLineSelection || startLine === endLine) {
382 return new vscode.Position(
383 topNonEmptyLine,
384 getLineEndChar(topNonEmptyLine) + OFFSET,
385 );
386 }
387
388 // Check line above selection
389 const lineAboveSelection = Math.max(0, startLine - 1);
390
391 // Get end positions
392 const topNonEmptyEndChar = getLineEndChar(topNonEmptyLine);
393 const lineAboveEndChar = getLineEndChar(lineAboveSelection);
394
395 const baseEndChar = Math.max(topNonEmptyEndChar, lineAboveEndChar);
396
397 return new vscode.Position(topNonEmptyLine, baseEndChar + OFFSET);
398 }
399
400 private updateTooltipPosition(
401 editor: vscode.TextEditor,
402 selection: vscode.Selection,
403 ) {
404 const position = this.calculateTooltipPosition(editor, selection);
405
406 if (!position) {
407 editor.setDecorations(this.svgTooltipDecoration, []);
408 return;
409 }
410
411 editor.setDecorations(this.svgTooltipDecoration, [
412 {
413 range: new vscode.Range(position, position),
414 hoverMessage: [this.buildHideTooltipHoverMsg()],
415 },
416 ]);
417 }
418}
419
420export default function setupInlineTips(context: vscode.ExtensionContext) {
421 InlineTipManager.getInstance().setupInlineTips(context);
422}