-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
469 lines (407 loc) · 17.1 KB
/
Copy pathmain.ts
File metadata and controls
469 lines (407 loc) · 17.1 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
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
import { App, Editor, MarkdownView, Plugin, PluginSettingTab, Setting, requestUrl, Notice, Modal } from 'obsidian';
interface YandexTrackerSettings {
trackerBaseURL: string;
apiToken: string;
orgId: string;
defaultDescription: string;
defaultAssignees: string[]; // Array of assignee usernames
}
const DEFAULT_SETTINGS: YandexTrackerSettings = {
trackerBaseURL: 'https://tracker.yandex.ru/',
apiToken: '',
orgId: '',
defaultDescription: `{% cut "Создано из Obsidian" %}
Эта задача создана из заметок в Obsidian.
{% endcut %}`,
defaultAssignees: []
}
interface TaskCreationData {
confirmed: boolean;
summary: string;
description: string;
deadline: string;
tags: string[];
assignee: string;
}
class ConfirmationModal extends Modal {
private result: Promise<TaskCreationData>;
private resolvePromise: (value: TaskCreationData) => void;
private summaryInput: HTMLInputElement;
private descriptionInput: HTMLTextAreaElement;
private deadlineInput: HTMLInputElement;
private tagsInput: HTMLInputElement;
private assigneeInput: HTMLInputElement;
constructor(app: App, private summary: string, private queueKey: string, private plugin: YandexTrackerLinkerPlugin) {
super(app);
this.result = new Promise((resolve) => {
this.resolvePromise = resolve;
});
}
onOpen() {
const {contentEl} = this;
contentEl.createEl("h2", { text: "Create Yandex Tracker Task?" });
// Summary field
const summaryContainer = contentEl.createDiv();
summaryContainer.createEl("p", { text: "Summary:" });
this.summaryInput = summaryContainer.createEl("input", {
type: "text",
value: this.summary
});
this.summaryInput.style.width = "100%";
this.summaryInput.style.marginBottom = "1em";
// Description field with text from settings
const descriptionContainer = contentEl.createDiv();
descriptionContainer.createEl("p", { text: "Description (markdown):" });
this.descriptionInput = descriptionContainer.createEl("textarea");
this.descriptionInput.value = this.plugin.settings.defaultDescription;
this.descriptionInput.style.width = "100%";
this.descriptionInput.style.height = "100px";
this.descriptionInput.style.marginBottom = "1em";
// Deadline field
const deadlineContainer = contentEl.createDiv();
deadlineContainer.createEl("p", { text: "Deadline:" });
this.deadlineInput = deadlineContainer.createEl("input", {
type: "date",
});
this.deadlineInput.style.width = "100%";
this.deadlineInput.style.marginBottom = "1em";
// Set default value to tomorrow
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
this.deadlineInput.value = tomorrow.toISOString().split('T')[0];
// Tags field
const tagsContainer = contentEl.createDiv();
tagsContainer.createEl("p", { text: "Tags (comma-separated):" });
this.tagsInput = tagsContainer.createEl("input", {
type: "text",
placeholder: "tag1, tag2, tag3"
});
this.tagsInput.style.width = "100%";
this.tagsInput.style.marginBottom = "1em";
// Updated Assignee field with quick-fill buttons from settings
const assigneeContainer = contentEl.createDiv();
assigneeContainer.createEl("p", { text: "Assignee:" });
const assigneeWrapper = assigneeContainer.createDiv();
assigneeWrapper.style.display = "flex";
assigneeWrapper.style.gap = "10px";
assigneeWrapper.style.marginBottom = "1em";
this.assigneeInput = assigneeWrapper.createEl("input", {
type: "text",
placeholder: "Username"
});
this.assigneeInput.style.flex = "1";
// Create quick-fill buttons for each default assignee
for (const assignee of this.plugin.settings.defaultAssignees) {
const assigneeButton = assigneeWrapper.createEl("button", {
text: assignee,
cls: "mod-cta"
});
assigneeButton.onclick = () => {
this.assigneeInput.value = assignee;
};
}
// Queue info
contentEl.createEl("p", { text: `Queue: ${this.queueKey}` });
// Buttons
const buttonContainer = contentEl.createDiv({ cls: "modal-button-container" });
buttonContainer.createEl("button", { text: "Cancel" }).onclick = () => {
this.resolvePromise({
confirmed: false,
summary: this.summary,
description: "",
deadline: "",
tags: [],
assignee: ""
});
this.close();
};
buttonContainer.createEl("button", { text: "Create", cls: "mod-cta" }).onclick = () => {
this.resolvePromise({
confirmed: true,
summary: this.summaryInput.value.trim(),
description: this.descriptionInput.value.trim(),
deadline: this.deadlineInput.value,
tags: this.tagsInput.value.split(',').map(tag => tag.trim()).filter(tag => tag),
assignee: this.assigneeInput.value.trim()
});
this.close();
};
}
onClose() {
const {contentEl} = this;
// Ensure promise is resolved when modal is closed by ESC key
if (this.resolvePromise) {
this.resolvePromise({
confirmed: false,
summary: this.summary,
description: "",
deadline: "",
tags: [],
assignee: ""
});
}
contentEl.empty();
}
async getResult(): Promise<TaskCreationData> {
return this.result;
}
}
export default class YandexTrackerLinkerPlugin extends Plugin {
settings: YandexTrackerSettings;
private taskRegex = /@([A-Z]+-\d+)(?=\s)/g; // For existing tasks
private newTaskRegex = /(.*?)\s*@([A-Z]+)(?=\s)/; // Removed ^ to match anywhere in line
private isProcessing = false;
private linkRegex = /\[([A-Z]+-\d+)\]\(https?:\/\/[^\)]+\)/g;
async onload() {
await this.loadSettings();
console.log("YandexTrackerLinkerPlugin loaded.");
// Add command to convert tracker links
this.addCommand({
id: 'convert-tracker-links',
name: 'Convert Tracker Links',
editorCallback: (editor: Editor, view: MarkdownView) => {
this.processText(editor);
}
});
// Listen for editor changes
this.registerEvent(
this.app.workspace.on('editor-change', (editor: Editor) => {
const cursor = editor.getCursor();
const line = editor.getLine(cursor.line);
const charBeforeCursor = cursor.ch > 0 ? line.charAt(cursor.ch - 1) : '';
if (!this.isProcessing && /\s/.test(charBeforeCursor)) {
this.processText(editor);
}
})
);
// Add settings tab
this.addSettingTab(new YandexTrackerSettingTab(this.app, this));
}
onunload() {
console.log("YandexTrackerLinkerPlugin unloaded.");
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
private async createTask(data: {
summary: string,
queueKey: string,
description: string,
deadline: string,
tags: string[],
assignee: string
}): Promise<string> {
try {
const requestBody: any = {
summary: data.summary,
queue: {
key: data.queueKey
},
description: data.description,
deadline: data.deadline ? new Date(data.deadline).toISOString() : undefined,
tags: data.tags
};
// Only add assignee if it's not empty
if (data.assignee) {
requestBody.assignee = data.assignee;
}
const response = await requestUrl({
url: 'https://api.tracker.yandex.net/v2/issues/',
method: 'POST',
headers: {
'Authorization': `OAuth ${this.settings.apiToken}`,
'X-Org-ID': this.settings.orgId,
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody)
});
if (response.status !== 201) {
throw new Error(`API request failed: ${response.status}`);
}
const responseData = Array.isArray(response.json) ? response.json[0] : response.json;
if (!responseData || !responseData.key) {
throw new Error('Invalid API response: missing task key');
}
return responseData.key;
} catch (error) {
console.error('Failed to create task:', error);
if (error instanceof Error) {
new Notice(`Failed to create task: ${error.message}`);
}
throw error;
}
}
private cleanMarkdown(text: string): string {
return text
// Remove numbered lists (e.g., "1. ", "2. ")
.replace(/^\d+\.\s+/, '')
// Remove bullet points
.replace(/^[-*+]\s+/, '')
// Remove bold/italic markers
.replace(/[*_]{1,3}([^*_]+)[*_]{1,3}/g, '$1')
// Remove code blocks
.replace(/`([^`]+)`/g, '$1')
// Remove links but keep text
.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
// Remove blockquotes
.replace(/^>\s+/, '')
// Remove HTML tags
.replace(/<[^>]+>/g, '')
// Remove extra whitespace
.trim();
}
private async processText(editor: Editor) {
if (this.isProcessing) return;
this.isProcessing = true;
const cursor = editor.getCursor();
const content = editor.getValue();
let updatedContent = content;
try {
const lines = content.split('\n');
const currentLine = lines[cursor.line];
const newTaskMatch = this.newTaskRegex.exec(currentLine);
if (newTaskMatch) {
const [fullMatch, taskSummary, queueKey] = newTaskMatch;
// Check if there's already a link AFTER the @QUEUE pattern (not in the whole line)
const matchEndIndex = currentLine.indexOf(fullMatch) + fullMatch.length;
const textAfterMatch = currentLine.slice(matchEndIndex);
if (textAfterMatch.includes('](')) {
this.isProcessing = false;
return;
}
if (this.settings.apiToken && this.settings.orgId) {
try {
const cleanSummary = this.cleanMarkdown(taskSummary || "");
const summary = cleanSummary.trim() || "New task";
const modal = new ConfirmationModal(this.app, summary, queueKey, this);
modal.open();
const result = await modal.getResult();
if (!result.confirmed) {
this.isProcessing = false;
return;
}
const taskId = await this.createTask({
summary: result.summary,
queueKey: queueKey,
description: result.description,
deadline: result.deadline,
tags: result.tags,
assignee: result.assignee
});
const newLine = currentLine.replace(
fullMatch,
`${taskSummary ? taskSummary + ' ' : ''}[${taskId}](${this.settings.trackerBaseURL}${taskId})`
);
lines[cursor.line] = newLine;
updatedContent = lines.join('\n');
new Notice(`Task ${taskId} created successfully!`);
} catch (error) {
console.error('Failed to create task:', error);
this.isProcessing = false;
return;
}
} else {
new Notice('Please configure API Token and Organization ID in settings');
this.isProcessing = false;
return;
}
}
// Process existing task links
updatedContent = updatedContent.replace(this.taskRegex, (fullMatch, taskId, offset) => {
// Skip if we're already in a link
if (content.slice(Math.max(0, offset - 3), offset).endsWith('](')) return fullMatch;
// Get the current line
const lines = content.split('\n');
const currentLineIndex = content.slice(0, offset).split('\n').length - 1;
const currentLine = lines[currentLineIndex];
// Check if there's already a link to this task in the current line
const urlPattern = new RegExp(`\\[${taskId}\\]\\(${this.settings.trackerBaseURL}${taskId}\\)`);
if (urlPattern.test(currentLine)) return fullMatch;
return `[${taskId}](${this.settings.trackerBaseURL}${taskId})`;
});
if (content !== updatedContent) {
editor.setValue(updatedContent);
editor.setCursor(cursor);
}
} finally {
this.isProcessing = false;
}
}
}
class YandexTrackerSettingTab extends PluginSettingTab {
plugin: YandexTrackerLinkerPlugin;
constructor(app: App, plugin: YandexTrackerLinkerPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const {containerEl} = this;
containerEl.empty();
new Setting(containerEl)
.setName('Tracker Base URL')
.setDesc('Base URL for Yandex Tracker')
.addText(text => text
.setPlaceholder('Enter base URL')
.setValue(this.plugin.settings.trackerBaseURL)
.onChange(async (value) => {
this.plugin.settings.trackerBaseURL = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('API Token')
.setDesc('OAuth token for Yandex Tracker API')
.addText(text => text
.setPlaceholder('Enter API token')
.setValue(this.plugin.settings.apiToken)
.onChange(async (value) => {
this.plugin.settings.apiToken = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Organization ID')
.setDesc('Your Yandex Tracker organization ID')
.addText(text => text
.setPlaceholder('Enter org ID')
.setValue(this.plugin.settings.orgId)
.onChange(async (value) => {
this.plugin.settings.orgId = value;
await this.plugin.saveSettings();
}));
// Add new settings
new Setting(containerEl)
.setName('Default Description')
.setDesc('Default description template for new tasks')
.addTextArea(text => text
.setValue(this.plugin.settings.defaultDescription)
.onChange(async (value) => {
this.plugin.settings.defaultDescription = value;
await this.plugin.saveSettings();
}))
.setClass("yandex-tracker-description-setting");
new Setting(containerEl)
.setName('Default Assignees')
.setDesc('Comma-separated list of default assignee usernames for quick assignment')
.addText(text => text
.setPlaceholder('username1, username2, username3')
.setValue(this.plugin.settings.defaultAssignees.join(', '))
.onChange(async (value) => {
this.plugin.settings.defaultAssignees = value.split(',')
.map(username => username.trim())
.filter(username => username.length > 0);
await this.plugin.saveSettings();
}));
// Add some CSS for the description textarea
containerEl.createEl('style', {
text: `
.yandex-tracker-description-setting textarea {
width: 100%;
height: 100px;
font-family: monospace;
}
`
});
}
}