highlights.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. import {
  2. EditorState,
  3. Line,
  4. Range,
  5. RangeSet,
  6. StateEffect,
  7. StateField,
  8. } from '@codemirror/state'
  9. import {
  10. Decoration,
  11. DecorationSet,
  12. EditorView,
  13. showTooltip,
  14. gutter,
  15. gutterLineClass,
  16. GutterMarker,
  17. Tooltip,
  18. ViewPlugin,
  19. WidgetType,
  20. } from '@codemirror/view'
  21. import { Highlight, HighlightType } from '../services/types/doc'
  22. export const setHighlightsEffect = StateEffect.define<Highlight[]>()
  23. const ADDITION_MARKER_CLASS = 'ol-cm-addition-marker'
  24. const DELETION_MARKER_CLASS = 'ol-cm-deletion-marker'
  25. function highlightToMarker(highlight: Highlight) {
  26. const className =
  27. highlight.type === 'addition'
  28. ? ADDITION_MARKER_CLASS
  29. : DELETION_MARKER_CLASS
  30. const { from, to } = highlight.range
  31. return Decoration.mark({
  32. class: className,
  33. attributes: {
  34. style: `--hue: ${highlight.hue}`,
  35. },
  36. }).range(from, to)
  37. }
  38. type LineStatus = {
  39. line: Line
  40. highlights: Highlight[]
  41. empty: boolean
  42. changeType: HighlightType | 'mixed'
  43. }
  44. type LineStatuses = Map<number, LineStatus>
  45. function highlightedLines(highlights: Highlight[], state: EditorState) {
  46. const lineStatuses = new Map<number, LineStatus>()
  47. for (const highlight of highlights) {
  48. const fromLine = state.doc.lineAt(highlight.range.from).number
  49. const toLine = state.doc.lineAt(highlight.range.to).number
  50. for (let lineNum = fromLine; lineNum <= toLine; ++lineNum) {
  51. const status = lineStatuses.get(lineNum)
  52. if (status) {
  53. status.highlights.push(highlight)
  54. if (status.changeType !== highlight.type) {
  55. status.changeType = 'mixed'
  56. }
  57. } else {
  58. const line = state.doc.line(lineNum)
  59. lineStatuses.set(lineNum, {
  60. line,
  61. highlights: [highlight],
  62. empty: line.length === 0,
  63. changeType: highlight.type,
  64. })
  65. }
  66. }
  67. }
  68. return lineStatuses
  69. }
  70. const tooltipTheme = EditorView.theme({
  71. '.cm-tooltip': {
  72. backgroundColor: 'transparent',
  73. borderWidth: 0,
  74. // Prevent a tooltip getting in the way of hovering over a line that it
  75. // obscures
  76. pointerEvents: 'none',
  77. },
  78. })
  79. const theme = EditorView.baseTheme({
  80. ['.' + ADDITION_MARKER_CLASS]: {
  81. paddingTop: 'var(--half-leading)',
  82. paddingBottom: 'var(--half-leading)',
  83. backgroundColor: 'hsl(var(--hue), 70%, 85%)',
  84. },
  85. ['.' + DELETION_MARKER_CLASS]: {
  86. textDecoration: 'line-through',
  87. color: 'hsl(var(--hue), 70%, 40%)',
  88. },
  89. '.cm-tooltip.ol-cm-highlight-tooltip': {
  90. backgroundColor: 'hsl(var(--hue), 70%, 50%)',
  91. borderRadius: '4px',
  92. padding: '4px',
  93. color: '#fff',
  94. },
  95. '.ol-cm-empty-line-addition-marker': {
  96. padding: 'var(--half-leading) 2px',
  97. },
  98. '.ol-cm-changed-line': {
  99. backgroundColor: 'rgba(0, 0, 0, 0.03)',
  100. },
  101. '.ol-cm-change-gutter': {
  102. width: '3px',
  103. paddingLeft: '1px',
  104. },
  105. '.ol-cm-changed-line-gutter': {
  106. backgroundColor: 'hsl(var(--hue), 70%, 40%)',
  107. height: '100%',
  108. },
  109. '.ol-cm-highlighted-line-gutter': {
  110. backgroundColor: 'rgba(0, 0, 0, 0.03)',
  111. },
  112. })
  113. function createHighlightTooltip(pos: number, highlight: Highlight) {
  114. return {
  115. pos,
  116. above: true,
  117. create: () => {
  118. const dom = document.createElement('div')
  119. dom.classList.add('ol-cm-highlight-tooltip')
  120. dom.style.setProperty('--hue', String(highlight.hue))
  121. dom.textContent = highlight.label
  122. return { dom }
  123. },
  124. }
  125. }
  126. const setHighlightTooltipEffect = StateEffect.define<Tooltip | null>()
  127. const tooltipField = StateField.define<Tooltip | null>({
  128. create() {
  129. return null
  130. },
  131. update(tooltip, transaction) {
  132. for (const effect of transaction.effects) {
  133. if (effect.is(setHighlightTooltipEffect)) {
  134. return effect.value
  135. }
  136. }
  137. return tooltip
  138. },
  139. provide: field => showTooltip.from(field),
  140. })
  141. function highlightAtPos(state: EditorState, pos: number) {
  142. const highlights = state.field(highlightDecorationsField).highlights
  143. return highlights.find(highlight => {
  144. const { from, to } = highlight.range
  145. return pos >= from && pos <= to
  146. })
  147. }
  148. const highlightTooltipPlugin = ViewPlugin.fromClass(
  149. class {
  150. private lastTooltipPos: number | null = null
  151. // eslint-disable-next-line no-useless-constructor
  152. constructor(readonly view: EditorView) {}
  153. setHighlightTooltip(tooltip: Tooltip | null) {
  154. this.view.dispatch({
  155. effects: setHighlightTooltipEffect.of(tooltip),
  156. })
  157. }
  158. setTooltipFromEvent(event: MouseEvent) {
  159. const pos = this.view.posAtCoords({ x: event.clientX, y: event.clientY })
  160. if (pos !== this.lastTooltipPos) {
  161. let tooltip = null
  162. if (pos !== null) {
  163. const highlight = highlightAtPos(this.view.state, pos)
  164. if (highlight) {
  165. tooltip = createHighlightTooltip(pos, highlight)
  166. }
  167. }
  168. this.setHighlightTooltip(tooltip)
  169. this.lastTooltipPos = pos
  170. }
  171. }
  172. handleMouseMove(event: MouseEvent) {
  173. this.setTooltipFromEvent(event)
  174. }
  175. startHover(event: MouseEvent, el: HTMLElement) {
  176. const handleMouseMove = this.handleMouseMove.bind(this)
  177. this.view.contentDOM.addEventListener('mousemove', handleMouseMove)
  178. const handleMouseLeave = () => {
  179. this.setHighlightTooltip(null)
  180. this.lastTooltipPos = null
  181. this.view.contentDOM.removeEventListener('mousemove', handleMouseMove)
  182. el.removeEventListener('mouseleave', handleMouseLeave)
  183. }
  184. el.addEventListener('mouseleave', handleMouseLeave)
  185. this.setTooltipFromEvent(event)
  186. }
  187. },
  188. {
  189. eventHandlers: {
  190. mouseover(event) {
  191. const el = event.target as HTMLElement
  192. const classList = el.classList
  193. if (
  194. classList.contains(ADDITION_MARKER_CLASS) ||
  195. classList.contains(DELETION_MARKER_CLASS) ||
  196. // An empty line widget doesn't trigger a mouseover event, so detect
  197. // an event on a line element that contains one instead
  198. (classList.contains('cm-line') &&
  199. el.querySelector(
  200. `.ol-cm-empty-line-addition-marker, .ol-cm-empty-line-deletion-marker`
  201. ))
  202. ) {
  203. this.startHover(event, el)
  204. }
  205. },
  206. },
  207. provide() {
  208. return tooltipField
  209. },
  210. }
  211. )
  212. class EmptyLineAdditionMarkerWidget extends WidgetType {
  213. constructor(readonly hue: number) {
  214. super()
  215. }
  216. toDOM(view: EditorView): HTMLElement {
  217. const element = document.createElement('span')
  218. element.classList.add(
  219. 'ol-cm-empty-line-addition-marker',
  220. ADDITION_MARKER_CLASS
  221. )
  222. element.style.setProperty('--hue', this.hue.toString())
  223. return element
  224. }
  225. }
  226. class EmptyLineDeletionMarkerWidget extends WidgetType {
  227. constructor(readonly hue: number) {
  228. super()
  229. }
  230. toDOM(view: EditorView): HTMLElement {
  231. const element = document.createElement('span')
  232. element.classList.add(
  233. 'ol-cm-empty-line-deletion-marker',
  234. DELETION_MARKER_CLASS
  235. )
  236. element.style.setProperty('--hue', this.hue.toString())
  237. element.textContent = ' '
  238. return element
  239. }
  240. }
  241. function createMarkers(highlights: Highlight[]) {
  242. return RangeSet.of(highlights.map(highlight => highlightToMarker(highlight)))
  243. }
  244. function createEmptyLineHighlightMarkers(lineStatuses: LineStatuses) {
  245. const markers: Range<Decoration>[] = []
  246. for (const lineStatus of lineStatuses.values()) {
  247. if (lineStatus.line.length === 0) {
  248. const highlight = lineStatus.highlights[0]
  249. const widget =
  250. highlight.type === 'addition'
  251. ? new EmptyLineAdditionMarkerWidget(highlight.hue)
  252. : new EmptyLineDeletionMarkerWidget(highlight.hue)
  253. markers.push(
  254. Decoration.widget({
  255. widget,
  256. }).range(lineStatus.line.from)
  257. )
  258. }
  259. }
  260. return RangeSet.of(markers)
  261. }
  262. class ChangeGutterMarker extends GutterMarker {
  263. constructor(readonly hue: number) {
  264. super()
  265. }
  266. toDOM(view: EditorView) {
  267. const el = document.createElement('div')
  268. el.className = 'ol-cm-changed-line-gutter'
  269. el.style.setProperty('--hue', this.hue.toString())
  270. return el
  271. }
  272. }
  273. function createGutterMarkers(lineStatuses: LineStatuses) {
  274. const gutterMarkers: Range<GutterMarker>[] = []
  275. for (const lineStatus of lineStatuses.values()) {
  276. gutterMarkers.push(
  277. new ChangeGutterMarker(lineStatus.highlights[0].hue).range(
  278. lineStatus.line.from
  279. )
  280. )
  281. }
  282. return RangeSet.of(gutterMarkers)
  283. }
  284. const lineHighlight = Decoration.line({ class: 'ol-cm-changed-line' })
  285. function createLineHighlights(lineStatuses: LineStatuses) {
  286. const lineHighlights: Range<Decoration>[] = []
  287. for (const lineStatus of lineStatuses.values()) {
  288. lineHighlights.push(lineHighlight.range(lineStatus.line.from))
  289. }
  290. return RangeSet.of(lineHighlights)
  291. }
  292. const changeLineGutterMarker = new (class extends GutterMarker {
  293. elementClass = 'ol-cm-highlighted-line-gutter'
  294. })()
  295. function createGutterHighlights(lineStatuses: LineStatuses) {
  296. const gutterMarkers: Range<GutterMarker>[] = []
  297. for (const lineStatus of lineStatuses.values()) {
  298. gutterMarkers.push(changeLineGutterMarker.range(lineStatus.line.from))
  299. }
  300. return RangeSet.of(gutterMarkers, true)
  301. }
  302. type HighlightDecorations = {
  303. highlights: Highlight[]
  304. highlightMarkers: DecorationSet
  305. emptyLineHighlightMarkers: DecorationSet
  306. lineHighlights: DecorationSet
  307. gutterMarkers: RangeSet<GutterMarker>
  308. gutterHighlights: RangeSet<GutterMarker>
  309. }
  310. export const highlightDecorationsField =
  311. StateField.define<HighlightDecorations>({
  312. create() {
  313. return {
  314. highlights: [],
  315. highlightMarkers: Decoration.none,
  316. emptyLineHighlightMarkers: Decoration.none,
  317. lineHighlights: Decoration.none,
  318. gutterMarkers: RangeSet.empty,
  319. gutterHighlights: RangeSet.empty,
  320. }
  321. },
  322. update(highlightDecorations, tr) {
  323. for (const effect of tr.effects) {
  324. if (effect.is(setHighlightsEffect)) {
  325. const highlights = effect.value
  326. const lineStatuses = highlightedLines(highlights, tr.state)
  327. const highlightMarkers = createMarkers(highlights)
  328. const emptyLineHighlightMarkers =
  329. createEmptyLineHighlightMarkers(lineStatuses)
  330. const lineHighlights = createLineHighlights(lineStatuses)
  331. const gutterMarkers = createGutterMarkers(lineStatuses)
  332. const gutterHighlights = createGutterHighlights(lineStatuses)
  333. return {
  334. highlights,
  335. highlightMarkers,
  336. emptyLineHighlightMarkers,
  337. lineHighlights,
  338. gutterMarkers,
  339. gutterHighlights,
  340. }
  341. }
  342. }
  343. return highlightDecorations
  344. },
  345. provide: field => [
  346. EditorView.decorations.from(field, value => value.highlightMarkers),
  347. EditorView.decorations.from(
  348. field,
  349. value => value.emptyLineHighlightMarkers
  350. ),
  351. EditorView.decorations.from(field, value => value.lineHighlights),
  352. theme,
  353. tooltipTheme,
  354. highlightTooltipPlugin,
  355. ],
  356. })
  357. const changeGutter = gutter({
  358. class: 'ol-cm-change-gutter',
  359. markers: view => view.state.field(highlightDecorationsField).gutterMarkers,
  360. renderEmptyElements: false,
  361. })
  362. const gutterHighlighter = gutterLineClass.from(
  363. highlightDecorationsField,
  364. value => value.gutterHighlights
  365. )
  366. export function highlights() {
  367. return [highlightDecorationsField, changeGutter, gutterHighlighter]
  368. }