Elffuss BraidHub

kikocis/continue public

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