| 15 | } |
| 16 | |
| 17 | export function createEditorHighlightDecorations(options: EditorHighlightDecorationOptions) { |
| 18 | const { plugin, highlightService, highlightRepository } = options; |
| 19 | const highlightCommentResolver = new HighlightCommentResolver(highlightRepository); |
| 20 | |
| 21 | return ViewPlugin.fromClass(class { |
| 22 | decorations: DecorationSet; |
| 23 | |
| 24 | constructor(view: EditorView) { |
| 25 | this.decorations = this.buildDecorations(view); |
| 26 | } |
| 27 | |
| 28 | update(update: ViewUpdate): void { |
| 29 | if (update.docChanged || update.viewportChanged || update.transactions.length > 0) { |
| 30 | this.decorations = this.buildDecorations(update.view); |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | private buildDecorations(view: EditorView): DecorationSet { |
| 35 | const activeView = plugin.app.workspace.getActiveViewOfType(MarkdownView); |
| 36 | const file = activeView?.file; |
| 37 | |
| 38 | if (!file || !highlightService.shouldProcessFile(file)) { |
| 39 | return Decoration.none; |
| 40 | } |
| 41 | |
| 42 | const decorations: Range<Decoration>[] = []; |
| 43 | const highlights = highlightService.extractHighlights(view.state.doc.toString(), file); |
| 44 | |
| 45 | for (const highlight of highlights) { |
| 46 | if (highlight.position === undefined) continue; |
| 47 | |
| 48 | const commentHighlight = highlightCommentResolver.normalizeHighlight(highlight); |
| 49 | commentHighlight.comments = highlightCommentResolver.getCommentsForHighlight(file, commentHighlight, { |
| 50 | onTextChanged: (storedHighlight, currentHighlight) => { |
| 51 | emitHighlightTextChange(plugin, file, storedHighlight, currentHighlight); |
| 52 | } |
| 53 | }); |
| 54 | |
| 55 | const highlightEndPos = highlight.position + (highlight.originalLength ?? highlight.text.length + 4); |
| 56 | |
| 57 | if (shouldShowCommentWidget(plugin)) { |
| 58 | decorations.push(createCommentWidget(plugin, commentHighlight).range(highlightEndPos)); |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | return Decoration.set(decorations.sort((a, b) => a.from - b.from)); |
| 63 | } |
| 64 | }, { |
| 65 | decorations: value => value.decorations |
| 66 | }); |
| 67 | } |
| 68 | |
| 69 | function createCommentWidget(plugin: HiNotePluginContext, highlight: HiNote): Decoration { |
| 70 | return Decoration.widget({ |