line-wrapping-indentation.ts 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. import {
  2. Decoration,
  3. DecorationSet,
  4. EditorView,
  5. ViewPlugin,
  6. ViewUpdate,
  7. } from '@codemirror/view'
  8. import { type Range, StateEffect, StateField } from '@codemirror/state'
  9. import { sourceOnly } from './visual/visual'
  10. const MAX_INDENT_FRACTION = 0.9
  11. const setMaxIndentEffect = StateEffect.define<number>()
  12. /**
  13. * Calculates the indentation needed for each line based on the spaces and tabs at the start of the line.
  14. * Decorates each line with a `style` attribute, to ensure that wrapped lines share the same indentation.
  15. *
  16. * NOTE: performance increases linearly with document size, but decorating only the viewport causes unacceptable layout shifts when scrolling.
  17. */
  18. export const lineWrappingIndentation = (visual: boolean) => {
  19. // this extension should only be active in the source editor
  20. return sourceOnly(visual, [
  21. // store the current maxIndent, based on the clientWidth
  22. StateField.define<number>({
  23. create() {
  24. return 0
  25. },
  26. update(value, tr) {
  27. for (const effect of tr.effects) {
  28. if (effect.is(setMaxIndentEffect)) {
  29. value = effect.value
  30. }
  31. }
  32. return value
  33. },
  34. provide(field) {
  35. return [
  36. // calculate the max indent when the geometry changes
  37. ViewPlugin.define(view => {
  38. const measure = {
  39. key: 'line-wrapping-indentation-max-indent',
  40. read(view: EditorView) {
  41. return (
  42. (view.contentDOM.clientWidth / view.defaultCharacterWidth) *
  43. MAX_INDENT_FRACTION
  44. )
  45. },
  46. write(value: number, view: EditorView) {
  47. if (view.state.field(field) !== value) {
  48. window.setTimeout(() => {
  49. view.dispatch({
  50. effects: setMaxIndentEffect.of(value),
  51. })
  52. })
  53. }
  54. },
  55. }
  56. return {
  57. update(update: ViewUpdate) {
  58. if (update.geometryChanged) {
  59. view.requestMeasure(measure)
  60. }
  61. },
  62. }
  63. }),
  64. // rebuild the decorations when needed
  65. ViewPlugin.define<{ decorations: DecorationSet }>(
  66. view => {
  67. let previousMaxIndent = 0
  68. const value = {
  69. decorations: buildDecorations(view, view.state.field(field)),
  70. update(update: ViewUpdate) {
  71. const maxIndent = view.state.field(field)
  72. if (
  73. maxIndent !== previousMaxIndent ||
  74. update.geometryChanged ||
  75. update.viewportChanged
  76. ) {
  77. value.decorations = buildDecorations(view, maxIndent)
  78. }
  79. previousMaxIndent = maxIndent
  80. },
  81. }
  82. return value
  83. },
  84. {
  85. decorations: value => value.decorations,
  86. }
  87. ),
  88. ]
  89. },
  90. }),
  91. ])
  92. }
  93. export const buildDecorations = (view: EditorView, maxIndent: number) => {
  94. const { state } = view
  95. const { doc, tabSize } = state
  96. const decorations: Range<Decoration>[] = []
  97. let from = 0
  98. for (const line of doc.iterLines()) {
  99. // const indent = line.match(/^(\s*)/)[1].length
  100. const indent = calculateIndent(line, tabSize, maxIndent)
  101. if (indent) {
  102. decorations.push(lineIndentDecoration(indent).range(from))
  103. }
  104. from += line.length + 1
  105. }
  106. return Decoration.set(decorations)
  107. }
  108. const lineIndentDecoration = (indent: number) =>
  109. Decoration.line({
  110. attributes: {
  111. // style: `text-indent: ${indent}ch hanging`, // "hanging" would be ideal, when browsers support it
  112. style: `text-indent: -${indent}ch; padding-left: calc(${indent}ch + 6px)`, // add 6px to account for existing padding-left
  113. },
  114. })
  115. // calculate the character width of whitespace at the start of a line
  116. const calculateIndent = (line: string, tabSize: number, maxIndent: number) => {
  117. let indent = 0
  118. for (const char of line) {
  119. if (char === ' ') {
  120. indent++
  121. } else if (char === '\t') {
  122. indent += tabSize - (indent % tabSize)
  123. } else {
  124. break
  125. }
  126. }
  127. return Math.min(indent, maxIndent)
  128. }