generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
307 lines (240 loc) · 8.77 KB
/
main.ts
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
import { App, debounce, Debouncer, Editor, EditorPosition, EventRef, Events, ItemView, MarkdownPostProcessorContext, MarkdownView, Menu, Modal, Notice, Plugin, PluginSettingTab, Setting, TAbstractFile, TFile, Vault, WorkspaceLeaf } from 'obsidian';
interface Comment {
name: string
content: string
startPos: EditorPosition
endPos: EditorPosition
contentPos: EditorPosition
children: Comment[]
file: TFile
timestamp?: Date
}
interface AllComments {
[key: string]: Comment[]
}
const VIEW_TYPE_COMMENT = 'comment-view'
export default class CommentPlugin extends Plugin {
debounceUpdate = debounce(this.updateComments, 500, true)
modifyListener: EventRef
fileOpenListener: EventRef
async onload() {
//this.registerMarkdownPostProcessor(this.postProcessor.bind(this))
this.addRibbonIcon('dice', 'Comments', () => {
this.activateView();
});
this.registerView(
VIEW_TYPE_COMMENT,
(leaf) => new CommentView(leaf, this)
)
this.modifyListener = this.app.vault.on('modify', file => {
this.debounceUpdate(file)
})
this.fileOpenListener = this.app.workspace.on('file-open', file => {
if (file) this.updateComments(file)}
)
this.addCommand({
id: 'comment-add',
name: 'Add new comment',
editorCallback(editor, ctx) {
editor.replaceRange(`> [!comment] NAME | ${new Date().toLocaleDateString()}\n> COMMENT`, editor.getCursor())
},
})
}
async activateView() {
const { workspace } = this.app;
let leaf: WorkspaceLeaf | null = null;
const leaves = workspace.getLeavesOfType(VIEW_TYPE_COMMENT);
if (leaves.length > 0) {
leaf = leaves[0];
} else {
leaf = workspace.getRightLeaf(false);
if (!leaf) return
await leaf.setViewState({ type: VIEW_TYPE_COMMENT, active: true });
}
workspace.revealLeaf(leaf);
}
onunload() {
this.app.workspace.offref(this.modifyListener)
this.app.workspace.offref(this.fileOpenListener)
}
postProcessor(el: HTMLElement, ctx: MarkdownPostProcessorContext) {
if (this.app.workspace.getActiveViewOfType(MarkdownView)?.getMode() == 'source') return;
let callouts = el.findAll(".callout").filter(c => c.getAttribute('data-callout')?.toLowerCase() === 'comment')
callouts.forEach(c => c.hide())
}
async updateComments(file: TAbstractFile) {
if (!(file instanceof TFile)) return
const content = await file.vault.cachedRead(file)
const comments = this.findComments(file, content, {line: 0, ch: 0})
this.app.workspace.getLeavesOfType(VIEW_TYPE_COMMENT).forEach(leaf => {
if (leaf.view instanceof CommentView) leaf.view.setComments(comments, file.name)
})
}
findComments(file: TFile, fileContent: string, posOffset: EditorPosition, contentPos?: EditorPosition): Comment[] {
const comments: Comment[] = []
const regex = /> \[!comment\] (.+?)\n((?:> *.*\n?)+)/gi;
const matches = fileContent.matchAll(regex)
for (const match of matches) {
let name = match[1].trim()
let timestamp
if (name.indexOf('| ') >= 0) {
const [day,month,year] = name.slice(name.indexOf("| ") + 2).split('/').map(Number)
timestamp = new Date(year, month - 1, day)
name = name.slice(0, name.indexOf('| '))
}
// Original full content, including subcomments
let content = match[2].split('\n')
.map(line => line.replace(/^>/, '').trim())
.join('\n')
const startLine = fileContent.slice(0,match.index).match(/\n/g)?.length || 0
const endLine = fileContent.slice(0, match.index + match[0].length + 1).match(/\n/g)?.length || 0
const startPos = {line: startLine + posOffset.line, ch: 0 }
const endPos = {line: endLine + posOffset.line, ch: 0}
if (!contentPos) contentPos = {line: endPos.line, ch: 0}
// We need to add one to the line cause we are not counting the title (name) line
const children = this.findComments(file, content, {line: startPos.line + 1, ch: 0}, contentPos)
// We want this comment not to have the subcomments as content
if (content.indexOf('>') >= 0)
content = content.slice(0, content.indexOf('>'))
comments.push({name, content, startPos, endPos, children, contentPos, file, timestamp })
}
return comments
}
}
class CommentView extends ItemView {
private comments: AllComments = {};
private commentsEl: HTMLElement
private plugin: CommentPlugin
constructor(leaf: WorkspaceLeaf, plugin: CommentPlugin) {
super(leaf)
this.plugin = plugin
}
getViewType() {
return VIEW_TYPE_COMMENT
}
getDisplayText() {
return 'Comment View'
}
setComments(comments: Comment[], file: string) {
this.comments[file] = comments
this.renderComments(this.comments[file], file, this.commentsEl)
}
renderComments(comments: Comment[], fileName: string, element: HTMLElement, nested?: boolean) {
element.empty()
comments.forEach((comment, index) => {
const commentContainer = element.createEl('div', {
cls: nested ? 'comment-child-container' : 'comment-item-container',
});
if (nested) commentContainer.createEl('div', {cls: 'comment-child-separator' })
const headerDiv = commentContainer.createEl('div', {cls: 'comment-header'})
let minimizeEl
if (!nested) {
headerDiv.createEl('b', {
text: `Line ${comment.endPos.line}`,
cls: 'comment-line'
})
minimizeEl = headerDiv.createEl('button', {
text: '+',
cls: 'comment-minimize',
})
} else {
// Create empty div to retain layout
headerDiv.createEl('div')
}
headerDiv.createEl('b', {
cls: nested ? 'comment-child-date' : 'comment-item-date',
text: comment.timestamp?.toLocaleDateString()
})
const commentItem = commentContainer.createEl('div', {
cls: nested ? 'comment-child' : 'comment-item'
})
// Comment text
commentItem.createEl('p', {
text: `${comment.content}`,
cls: nested ? 'comment-child-text': 'comment-item-text'
});
commentItem.createEl('i', {
text: comment.name,
cls: 'comment-name'
})
if (!nested && comment.children.length > 0) {
const childrenCommentsEl = commentContainer.createEl('div', { cls: 'comment-children', attr: {'hidden': true }})
// Initially hide the children
childrenCommentsEl.hide()
// Recursively render the comments
this.renderComments(comment.children, fileName, childrenCommentsEl, true)
// Minize the comment listener
minimizeEl?.addEventListener('click', () => {
if (childrenCommentsEl.hidden) {
childrenCommentsEl.hidden = false
childrenCommentsEl.show()
minimizeEl!.innerText = '-'
} else {
childrenCommentsEl.hide()
childrenCommentsEl.hidden = true
minimizeEl!.innerText = '+'
}
})
}
// Add click event to navigate to source
commentItem.addEventListener('click', () => this.navigateToComment(comment, fileName));
commentItem.addEventListener('contextmenu', (evt) => this.showCommentOptions(evt, comment))
})
}
private async navigateToComment(comment: Comment, fileName: string) {
await this.app.workspace.openLinkText('', fileName)
const editor = this.app.workspace.getActiveViewOfType(MarkdownView)?.editor
const file = this.app.workspace.getActiveFile()
if (editor && file ) {
// Convert character position to line and character
editor.setCursor(comment.contentPos);
editor.scrollIntoView({ from: comment.contentPos, to: comment.contentPos }, true);
}
}
private showCommentOptions(evt: MouseEvent, comment: Comment) {
const menu = new Menu()
menu.addItem(item => {
item
.setTitle("Add")
.setIcon("plus")
.onClick(() => this.addComment(comment))
})
menu.addItem(item => {
item
.setTitle('Remove')
.setIcon('trash')
.onClick(() => this.removeComment(comment))
})
menu.showAtMouseEvent(evt)
}
private addComment(comment: Comment) {
this.app.vault.process(comment.file, content => {
const lines = content.split('\n')
lines.splice(comment.endPos.line - 1, 0, "> ", `>> [!comment] NAME | ${new Date().toLocaleDateString()}`, ">> COMMENT")
content = lines.join('\n')
return content
})
}
private removeComment(comment: Comment) {
this.app.vault.process(comment.file, content => {
const lines = content.split('\n')
lines.splice(comment.startPos.line - 1, comment.endPos.line - comment.startPos.line)
content = lines.join('\n')
return content
})
const comments = this.comments[comment.file.name]
comments.remove(comment)
this.renderComments(comments, comment.file.name, this.commentsEl)
}
async onOpen() {
const container = this.containerEl.children[1]
container.empty()
const commentContainer = container.createEl('div')
commentContainer.createEl('h2', { text: 'Comments', cls: 'comments-title'})
this.commentsEl = commentContainer.createEl('div')
const activeFile = this.app.workspace.getActiveFile()
if (activeFile) this.plugin.updateComments(activeFile)
}
async onClose() {
}
}