empty-line-filler.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import {
  2. Decoration,
  3. DecorationSet,
  4. EditorView,
  5. ViewPlugin,
  6. ViewUpdate,
  7. WidgetType,
  8. } from '@codemirror/view'
  9. import browser from './browser'
  10. class EmptyLineWidget extends WidgetType {
  11. toDOM(view: EditorView): HTMLElement {
  12. const element = document.createElement('span')
  13. element.className = 'ol-cm-filler'
  14. return element
  15. }
  16. eq(widget: EmptyLineWidget) {
  17. return true
  18. }
  19. }
  20. export const emptyLineFiller = () => {
  21. if (browser.ios) {
  22. // disable on iOS as it breaks Backspace across empty lines
  23. // https://github.com/overleaf/internal/issues/12192
  24. return []
  25. }
  26. return [
  27. ViewPlugin.fromClass(
  28. class {
  29. decorations: DecorationSet
  30. constructor(view: EditorView) {
  31. this.decorations = this.buildDecorations(view)
  32. }
  33. update(update: ViewUpdate) {
  34. if (update.docChanged || update.viewportChanged)
  35. this.decorations = this.buildDecorations(update.view)
  36. }
  37. buildDecorations(view: EditorView) {
  38. const decorations = []
  39. const { from, to } = view.viewport
  40. const { doc } = view.state
  41. let pos = from
  42. while (pos <= to) {
  43. const line = doc.lineAt(pos)
  44. if (line.length === 0) {
  45. const decoration = Decoration.widget({
  46. widget: new EmptyLineWidget(),
  47. side: 1,
  48. })
  49. decorations.push(decoration.range(pos))
  50. }
  51. pos = line.to + 1
  52. }
  53. return Decoration.set(decorations)
  54. }
  55. },
  56. {
  57. decorations(value) {
  58. return value.decorations
  59. },
  60. }
  61. ),
  62. EditorView.baseTheme({
  63. '.ol-cm-filler': {
  64. display: 'inline-block',
  65. width: '4px',
  66. },
  67. }),
  68. ]
  69. }