highlights.ts 11 KB

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