-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathannotations.js
More file actions
215 lines (174 loc) · 6.49 KB
/
Copy pathannotations.js
File metadata and controls
215 lines (174 loc) · 6.49 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
// annotations.js — Annotation decoration, hover preview, and delete support
const vscode = require('vscode');
let annotationDecorationType;
function ensureAnnotationDecorationType() {
if (!annotationDecorationType) {
annotationDecorationType = vscode.window.createTextEditorDecorationType({
isWholeLine: true
});
}
}
function disposeAnnotations() {
if (annotationDecorationType) annotationDecorationType.dispose();
annotationDecorationType = undefined;
}
function getFileKey(document) {
const relative = vscode.workspace.asRelativePath(document.uri, false);
return relative || document.uri.fsPath;
}
async function getAnnotationFileUri(document) {
let rootUri;
const wsFolder = vscode.workspace.getWorkspaceFolder(document.uri);
if (wsFolder) rootUri = wsFolder.uri;
else if (vscode.workspace.workspaceFolders?.length > 0) rootUri = vscode.workspace.workspaceFolders[0].uri;
else rootUri = vscode.Uri.joinPath(document.uri, '..');
const dir = vscode.Uri.joinPath(rootUri, '.codetime');
await vscode.workspace.fs.createDirectory(dir);
return vscode.Uri.joinPath(dir, 'annotations.json');
}
async function loadAnnotations(document) {
const studentLessonRoot = globalThis._codetimeStudentLessonRoot;
if (studentLessonRoot) {
try {
const lessonAnnotationsUri = vscode.Uri.file(
require("path").join(studentLessonRoot, "annotations.json")
);
const data = await vscode.workspace.fs.readFile(lessonAnnotationsUri);
const raw = Buffer.from(data).toString("utf8").trim();
if (raw) {
const parsed = JSON.parse(raw);
if (Array.isArray(parsed)) return parsed;
if (Array.isArray(parsed.annotations)) return parsed.annotations;
}
} catch {
// fall through to workspace annotations
}
}
try {
const fileUri = await getAnnotationFileUri(document);
const data = await vscode.workspace.fs.readFile(fileUri);
const raw = Buffer.from(data).toString("utf8").trim();
if (!raw) return [];
const parsed = JSON.parse(raw);
if (Array.isArray(parsed)) return parsed;
if (Array.isArray(parsed.annotations)) return parsed.annotations;
return [];
} catch {
return [];
}
}
async function saveAnnotations(document, annotations) {
const fileUri = await getAnnotationFileUri(document);
const payload = JSON.stringify({ annotations }, null, 2);
await vscode.workspace.fs.writeFile(fileUri, Buffer.from(payload, 'utf8'));
}
function encodeArgs(obj) {
// Safe JSON → URI for command links in Markdown hovers
return encodeURIComponent(JSON.stringify(obj));
}
async function refreshAnnotations(editor) {
if (!editor) return;
ensureAnnotationDecorationType();
const document = editor.document;
const all = await loadAnnotations(document);
const fileKey = getFileKey(document);
const current = globalThis._codetimeCurrentCommitHash ?? null;
// If no commit selected, display everything
const activeStudentFile = String(globalThis._codetimeCurrentFile || fileKey || "").replace(/\\/g, "/");
const activeCommit = globalThis._codetimeCurrentCommitHash ?? current;
const relevant = all.filter(a => {
const annFile = String(a.file || a.filePath || a.path || "").replace(/\\/g, "/");
const annCommit = a.commitHash || a.commit || a.sha || null;
const sameFile =
annFile === activeStudentFile ||
activeStudentFile.endsWith(annFile) ||
annFile.endsWith(activeStudentFile);
if (!sameFile) return false;
if (!activeCommit) return true;
return annCommit === activeCommit;
});
const decorations = relevant.map(ann => {
const preview = (ann.text || '').trim();
const md = new vscode.MarkdownString();
md.isTrusted = true;
md.supportHtml = false;
const args = { id: ann.id, file: fileKey };
const encoded = encodeArgs(args);
md.appendMarkdown(preview ? preview : '_(no text)_');
md.appendMarkdown('\n\n---\n');
md.appendMarkdown(`[Delete annotation](command:codetime.deleteAnnotation?${encoded})`);
const line = Math.min(ann.startLine ?? ann.line ?? 0, document.lineCount - 1);
return {
range: new vscode.Range(line, 0, line, 0),
hoverMessage: md,
renderOptions: { after: {
contentText: ` 💬 `,
color: '#aaa',
margin: '0 0 0 10px'
} }
};
});
editor.setDecorations(annotationDecorationType, decorations);
}
async function addAnnotationCommand() {
const editor = vscode.window.activeTextEditor;
if (!editor) return vscode.window.showErrorMessage('No active editor');
const document = editor.document;
const selection = editor.selection;
const startLine = selection.start.line;
const endLine = selection.isEmpty ? startLine : selection.end.line;
const text = await vscode.window.showInputBox({ prompt: 'Enter annotation' });
if (!text) return;
const all = await loadAnnotations(document);
const fileKey = globalThis._codetimeCurrentFile || getFileKey(document);
all.push({
id: Date.now() + '-' + Math.random().toString(36).slice(2),
file: fileKey,
startLine,
endLine,
text,
commitHash: globalThis._codetimeCurrentCommitHash ?? null
});
await saveAnnotations(document, all);
refreshAnnotations(editor);
}
async function deleteAnnotationCommand(args) {
try {
if (!args?.id || !args?.file) return;
const editor = vscode.window.activeTextEditor;
if (!editor) return;
const document = editor.document;
const all = await loadAnnotations(document);
const next = all.filter(a => !(a.id === args.id && a.file === args.file));
await saveAnnotations(document, next);
await refreshAnnotations(editor);
vscode.window.showInformationMessage('Annotation deleted.');
} catch (e) {
vscode.window.showErrorMessage('Failed to delete annotation: ' + e.message);
}
}
function registerAnnotationSupport(context) {
ensureAnnotationDecorationType();
context.subscriptions.push(
vscode.commands.registerCommand('codetime.addAnnotation', addAnnotationCommand)
);
context.subscriptions.push(
vscode.commands.registerCommand('codetime.deleteAnnotation', deleteAnnotationCommand)
);
context.subscriptions.push(
vscode.window.onDidChangeActiveTextEditor(editor => {
if (editor) refreshAnnotations(editor);
})
);
context.subscriptions.push(
vscode.commands.registerCommand('codetime.refreshAnnotations', () => {
const ed = vscode.window.activeTextEditor;
if (ed) refreshAnnotations(ed);
})
);
}
module.exports = {
registerAnnotationSupport,
refreshAnnotations,
disposeAnnotations
};