forked from kermanx/reactive-vscode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseEditorDecorations.ts
78 lines (70 loc) · 2.33 KB
/
useEditorDecorations.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
import type { MaybeRef, MaybeRefOrGetter } from '@reactive-vscode/reactivity'
import type { DecorationOptions, DecorationRenderOptions, Range, TextEditor, TextEditorDecorationType } from 'vscode'
import type { Awaitable, Nullable } from '../utils/types'
import { computed, toValue, watch, watchEffect } from '@reactive-vscode/reactivity'
import { window } from 'vscode'
import { useDisposable } from './useDisposable'
import { useDocumentText } from './useDocumentText'
export interface UseEditorDecorationsOptions {
/**
* The triggers to update the decorations.
*
* @default ['effect', 'documentChanged']
*/
updateOn?: ('effect' | 'documentChanged')[]
}
/**
* Reactively set decorations on the given editor. See `vscode::TextEditor.setDecorations`.
*
* @category editor
*/
export function useEditorDecorations(
editor: MaybeRefOrGetter<Nullable<TextEditor>>,
decorationTypeOrOptions: MaybeRefOrGetter<TextEditorDecorationType | DecorationRenderOptions>,
decorations:
| MaybeRef<readonly Range[] | readonly DecorationOptions[]>
| ((editor: TextEditor) => Awaitable<readonly Range[] | readonly DecorationOptions[]>),
options: UseEditorDecorationsOptions = {},
) {
const {
updateOn = ['effect', 'documentChanged'],
} = options
const decorationType = computed<TextEditorDecorationType>(
(oldDecorationTypeOrOptions) => {
oldDecorationTypeOrOptions?.dispose()
const decorationTypeOrOptionsValue = toValue(decorationTypeOrOptions)
return 'key' in decorationTypeOrOptionsValue
? decorationTypeOrOptionsValue
: useDisposable(window.createTextEditorDecorationType(decorationTypeOrOptionsValue))
},
)
const update = async () => {
const editorValue = toValue(editor)
if (!editorValue)
return
editorValue.setDecorations(
decorationType.value,
typeof decorations === 'function'
? await decorations(editorValue)
: toValue(decorations),
)
}
const documentText = updateOn.includes('documentChanged')
? useDocumentText(() => toValue(editor)?.document)
: null
if (updateOn.includes('effect')) {
watchEffect(async () => {
void documentText?.value
await update()
})
}
else if (documentText) {
watch(documentText, update)
}
return {
/**
* Manually trigger the decoration update.
*/
update,
}
}