-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree.ts
521 lines (496 loc) · 14.4 KB
/
tree.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
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
import {
Autocmd,
Disposable,
disposeAll,
Emitter,
events,
Neovim,
Range,
TreeItem,
TreeItemCollapsibleState,
TreeView,
TreeViewOptions,
window,
workspace,
} from 'coc.nvim'
import { lstatSync } from 'fs-extra'
import path from 'path'
import { URI } from 'vscode-uri'
import { CommandsParameters } from '.'
import {
configuration,
defaultConfiguration,
extensionName,
IIcon,
} from './constants'
import Grep, { GrepMatch } from './grep'
import { showWarningMessage } from './helpers'
import { listIt } from './list'
import view from './view'
export interface TodoItem {
tagName: string
shortText: string
detail?: string
highlight?: string
range: Range
path: string
extra?: string
}
export interface Folder {
level: number
sourcePath: string
key: string
tag?: string
name?: string
children: Array<TodoItem | Folder>
}
export type TodoNode = Folder | TodoItem
export type TodoEmitter = Emitter<TodoNode | undefined>
export type TodoTreeView = TreeView<TodoNode>
class TodoTree {
private disposables: Disposable[] = []
private prevBufnr: number | undefined
private previewBufnr: number | undefined
private rootItems: TodoNode[] = []
private _treeView: TodoTreeView | null = null
private opened: Partial<Folder>[] = []
private nvim: Neovim = workspace.nvim
private emitter: TodoEmitter = new Emitter()
private timeout: NodeJS.Timeout | null = null
private fetching = false
private prevNode: TodoNode | undefined
private autoPreview = configuration.autoPreview
public commandsMap = new Map<string, CommandsParameters>()
public autocmdsArr = Array<Autocmd>()
constructor() {
this.generateCommands()
this.generateAutocmds()
}
get treeView() {
if (!this._treeView) {
this.generateTreeView()
}
return this._treeView
}
set treeView(_next: TodoTreeView | null) {
// can not override treeView
}
private generateCommands() {
this.commandsMap
.set(`showTree`, {
callback: async () => {
if (this.treeView && !this.treeView.visible) {
this.autocmdsArr.map((autocmd) => {
return events.on(
autocmd.event as any,
autocmd.callback as any,
null,
this.disposables
)
})
const doc = await workspace.document
const bufnr = doc.bufnr
this.prevBufnr = await this.nvim.call('bufwinnr', [bufnr])
await this.treeView.show()
}
this.refreshTodoItems()
},
args: undefined,
})
.set(`goTo`, {
callback: (node: TodoNode) => jumpTo(node, this.nvim, this.prevBufnr),
args: undefined,
internal: true,
})
.set(`open`, {
callback: () => {
// // nothint to do
},
args: undefined,
internal: true,
})
return this.commandsMap
}
private generateAutocmds() {
this.autocmdsArr.push({
event: 'BufWritePost',
callback: () => {
if (this.treeView?.visible) {
this.refreshTodoItems(500)
}
},
})
this.autocmdsArr.push({
event: 'BufEnter',
callback: (bufnr: number) => {
if (
this._treeView?.visible &&
this.previewBufnr &&
bufnr !== this.previewBufnr
) {
this.prevNode = undefined
this.closePreview()
}
},
})
return this.autocmdsArr
}
private refreshTodoItems(timeout = 0) {
if (this.fetching) {
return
}
if (this.timeout) {
clearTimeout(this.timeout)
}
this.timeout = setTimeout(async () => {
const updateText = 'Updating items...'
await window.withProgress(
{
title: `[${extensionName}] ${updateText}`,
cancellable: true,
},
async (_, cancellationToken) => {
// let msgPrefix = updateText
let msgPrefix = ''
// see coc BasicTreeView: this.nodesMap.set(element, { item, resolved })
// it use element as map key causing every time generate some new elements, it will not reuse the old element
// it make memory leak
// so I clear it manually till fixed
// @ts-ignore
this._treeView!.nodesMap.clear()
view.clear()
this._treeView!.message = msgPrefix
let all = 0
const gs = configuration.tags.map(
(tag) => new Grep({ regex: tag.regex, tagName: tag.tagName })
)
cancellationToken.onCancellationRequested(() => {
const cancelText = 'Grep canceled'
msgPrefix = `${cancelText}: `
showWarningMessage(cancelText)
const results = gs.map((g) => {
all += g.resArr.length
return convertRawMatchesToTodoItem(g.handleGrepCancel())
})
this.rootItems = listIt(results)
})
return new Promise<void>((resolve) => {
this.fetching = true
this.rootItems = []
msgPrefix = 'All '
Promise.all(
gs.map(async (g) => convertRawMatchesToTodoItem(await g.grep()))
).then((results) => {
gs.forEach((g) => (all += g.resArr.length))
this._treeView!.message = msgPrefix + `${all} items`
this._treeView!.description = `${
view.groupByTag ? 'group by tag;' : ''
} ${view.mode} view`
this.rootItems = listIt(results)
resolve()
})
})
}
)
this.emitter.fire(undefined)
if (this.timeout) {
clearTimeout(this.timeout)
this.timeout = null
}
this.fetching = false
}, timeout)
}
private generateTreeView() {
const treeDataProvider: TreeViewOptions<TodoNode>['treeDataProvider'] = {
resolveActions: async (_, node) => {
return [
{
title: 'open it and close tree',
handler: async () => {
const doc = await workspace.document
const bufnr = doc.bufnr
const winnr = await this.nvim.call('bufwinnr', [bufnr])
await jumpTo(node, this.nvim, this.prevBufnr)
await this.nvim.command(`${winnr}wincmd c`)
},
},
]
},
onDidChangeTreeData: this.emitter.event,
getChildren: (root) => {
if (!root) {
return this.rootItems
}
if (isParent(root)) {
return root.children
}
return undefined
},
getTreeItem: (node: TodoNode) => {
let item: TreeItem
if (isParent(node)) {
let icon: IIcon['text'] | undefined
let iconHLGroup: IIcon['hlGroup'] | undefined
let description = ''
const state =
this.opened.findIndex((t) => t.key === node.key) !== -1
? TreeItemCollapsibleState.Expanded
: TreeItemCollapsibleState.Collapsed
let text = ''
if (typeof node.tag === 'string') {
const target = configuration.tags.find(
(t) => t.tagName === node.tag
)
if (target) {
icon = target?.icon?.text
text = node.tag
iconHLGroup =
configuration?.groupTagIconHighlight || target.icon?.hlGroup
}
} else {
description = node.sourcePath.replace(workspace.cwd + '/', '')
if (lstatSync(node.sourcePath).isFile()) {
icon = configuration?.fileIcon?.text
iconHLGroup = configuration?.fileIcon?.hlGroup
} else {
icon = configuration?.folderIcon?.text
iconHLGroup = configuration?.folderIcon?.hlGroup
}
const p = node.name ?? path.basename(URI.file(node.sourcePath).path)
text = p
}
item = new TreeItem(text, state)
item.command = {
command: `${extensionName}.open`,
title: 'open it',
arguments: [node],
}
item.description = description
if (configuration.parentNodeHighlightEnabled) {
item.label = {
highlights: [[0, text.length]],
label: text,
}
}
if (icon) {
item.icon = {
hlGroup: iconHLGroup || defaultConfiguration.fileIcon!.hlGroup,
text: icon,
}
}
} else {
const { shortText } = node
const icon = configuration.tags.find(
(t) => t.tagName === node.tagName
)?.icon
item = new TreeItem(`${shortText}`, TreeItemCollapsibleState.None)
const position =
node.extra ??
`[${node.range.start.line}, ${node.range.start.character}]`
if (icon) {
item.icon = {
hlGroup: icon?.hlGroup,
text: icon?.text,
}
}
item.command = {
command: `${extensionName}.goTo`,
title: 'go to it',
arguments: [node],
}
item.description = position
}
return item
},
}
this._treeView = window.createTreeView('Todo', {
treeDataProvider,
bufhidden: 'hide',
// @ts-ignore
autoWidth: true,
})
this._treeView.onDidExpandElement(({ element }) => {
if (isParent(element)) {
const { key } = element
if (this.opened.find((t) => t.key === key)) {
return
}
this.opened.push({ key })
}
})
this._treeView.onDidCollapseElement(({ element }) => {
if (isParent(element)) {
const { key } = element
const exist = this.opened.findIndex((t) => t.key === key)
if (exist !== -1) {
this.opened.splice(exist, 1)
}
}
})
// @ts-ignore
this._treeView._collapseAll = this._treeView.collapseAll
// @ts-ignore
this._treeView.collapseAll = (...args: any[]) => {
// @ts-ignore
this._treeView._collapseAll(...args)
this.opened = []
}
// override dispose if bufhidden set to wipe
// this._treeView.dispose = () => {
// // nothing to do
// }
this._treeView.onDidChangeVisibility(({ visible }) => {
if (!visible) {
this.closePreview()
disposeAll(this.disposables)
}
})
// @ts-ignore
this._treeView.registerLocalKeymap(
'n',
configuration.toggleGroupByTagKey,
async () => {
this.closePreview()
view.groupByTag = !view.groupByTag
this.refreshTodoItems()
},
true
)
// @ts-ignore
this._treeView.registerLocalKeymap(
'n',
configuration.refreshItemsKey,
async () => {
this.closePreview()
this.refreshTodoItems()
},
true
)
// @ts-ignore
this._treeView.registerLocalKeymap(
'n',
configuration.togglePreviewKey,
async (node: TodoNode) => {
this.autoPreview = !this.autoPreview
this.doPreview(node)
},
true
)
// @ts-ignore
this._treeView.registerLocalKeymap(
'n',
configuration.switchViewKey,
async () => {
this.opened = []
view.switchToNextMode()
this.closePreview()
this.refreshTodoItems()
},
true
)
// @ts-ignore
this._treeView.onDidCursorMoved(async (node) => {
if (this.prevNode !== node) {
this.prevNode = node
this.previewBufnr = await this.doPreview(node)
}
})
return this._treeView
}
private async doPreview(
node: TodoNode | undefined
): Promise<undefined | number> {
if (node && this.autoPreview) {
// const doc = workspace.getDocument(node.)
const config = {
lines: [] as string[],
border:
configuration.previewWinConfig?.border ??
defaultConfiguration.previewWinConfig?.border,
rounded:
configuration.previewWinConfig?.rounded ??
defaultConfiguration.previewWinConfig?.rounded,
maxWidth: configuration.maxPreviewWidth,
highlight:
configuration.previewWinConfig?.highlight ??
defaultConfiguration.previewWinConfig?.highlight,
borderhighlight:
configuration.previewWinConfig?.borderhighlight ??
defaultConfiguration.previewWinConfig?.borderhighlight,
winblend:
configuration.previewWinConfig?.winblend ??
defaultConfiguration.previewWinConfig?.winblend,
filetype: 'text',
}
if (isParent(node)) {
if (node.tag) {
this.closePreview()
return
} else {
config.lines.push(node.sourcePath.replace(workspace.cwd + '/', ''))
}
config.maxWidth = 1000
} else if (!isParent(node)) {
// const filetype = toVimFiletype(
// // @ts-ignore: getLanguageId: check filetype by same extension name
// workspace.documentsManager.getLanguageId(node.path)
// )
// if (filetype) {
// config.filetype = filetype
// }
const position =
node.extra ??
`[Line ${node.range.start.line}, Col ${node.range.start.character}]`
const text = `${node.detail}\n\n${position}`
config.lines = text?.split('\n') || []
}
return (await this.nvim.call('coc_todo_tree#preview', config)) as number
} else {
this.closePreview()
}
}
private closePreview(): void {
this.nvim.call('coc_todo_tree#close_preview', [], true)
}
}
export default TodoTree
export function isParent(node: TodoNode): node is Folder {
if (Object.prototype.hasOwnProperty.call(node, 'sourcePath')) {
return true
}
return false
}
async function jumpTo(
node: TodoNode,
nvim: Neovim,
prevBufnr?: number
): Promise<void> {
if (!isParent(node)) {
const filePath = URI.file(node.path).toString()
await nvim.command(`${prevBufnr ?? ''}wincmd w`)
await workspace.jumpTo(filePath, {
line: node.range.start.line - 1,
character: node.range.start.character - 1,
})
}
}
function convertRawMatchesToTodoItem(rawMatches: GrepMatch[]) {
return rawMatches.map((res) => {
return {
tagName: res.tagName,
detail: res.detail,
shortText: res.shortText,
path: res.fsPath,
range: {
start: {
character: res.column,
line: res.line,
},
end: {
character: res.column,
line: res.line,
},
},
}
})
}