|
| 1 | +import { Decoration, DecorationSet, ViewPlugin, WidgetType, EditorView, ViewUpdate } from "@codemirror/view"; |
| 2 | +import { RangeSetBuilder } from "@codemirror/state"; |
| 3 | + |
| 4 | +class NewlineWidget extends WidgetType { |
| 5 | + toDOM(): HTMLElement { |
| 6 | + let span = document.createElement("span"); |
| 7 | + span.textContent = "¬"; |
| 8 | + span.className = "cm-newline-marker"; |
| 9 | + return span; |
| 10 | + } |
| 11 | + eq(other: WidgetType): boolean { |
| 12 | + return other instanceof NewlineWidget; |
| 13 | + } |
| 14 | +} |
| 15 | + |
| 16 | +export const lineBreakMarkerPlugin = ViewPlugin.fromClass( |
| 17 | + class { |
| 18 | + decorations: DecorationSet; |
| 19 | + |
| 20 | + constructor(view: EditorView) { |
| 21 | + this.decorations = this.getDecorations(view); |
| 22 | + } |
| 23 | + |
| 24 | + update(update: ViewUpdate) { |
| 25 | + if (update.docChanged || update.viewportChanged) { |
| 26 | + this.decorations = this.getDecorations(update.view); |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + getDecorations(view: EditorView): DecorationSet { |
| 31 | + let builder = new RangeSetBuilder<Decoration>(); |
| 32 | + let lastLineNumber = -1; |
| 33 | + |
| 34 | + for (let { from, to } of view.visibleRanges) { |
| 35 | + for (let pos = from; pos <= to; ) { |
| 36 | + let line = view.state.doc.lineAt(pos); |
| 37 | + |
| 38 | + if (line.number > lastLineNumber && line.number < view.state.doc.lines) { |
| 39 | + let deco = Decoration.widget({ |
| 40 | + widget: new NewlineWidget(), |
| 41 | + side: 1, |
| 42 | + }); |
| 43 | + builder.add(line.to, line.to, deco); |
| 44 | + lastLineNumber = line.number; |
| 45 | + } |
| 46 | + |
| 47 | + pos = line.to + 1; |
| 48 | + } |
| 49 | + } |
| 50 | + return builder.finish(); |
| 51 | + } |
| 52 | + }, |
| 53 | + { |
| 54 | + decorations: (v) => v.decorations, |
| 55 | + }, |
| 56 | +); |
| 57 | + |
| 58 | +export const lineBreakMarkerTheme = EditorView.theme({ |
| 59 | + ".cm-newline-marker": { |
| 60 | + color: "var(--cm-space-marker-color, rgba(127, 127, 127, 0.6))", |
| 61 | + pointerEvents: "none", |
| 62 | + userSelect: "none", |
| 63 | + }, |
| 64 | +}); |
| 65 | + |
| 66 | +export const lineBreakMarker = [lineBreakMarkerPlugin, lineBreakMarkerTheme]; |
| 67 | + |
| 68 | +export default lineBreakMarker; |
0 commit comments