ranges.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. import { StateEffect, StateField, TransactionSpec } from '@codemirror/state'
  2. import {
  3. Decoration,
  4. type DecorationSet,
  5. EditorView,
  6. type PluginValue,
  7. ViewPlugin,
  8. WidgetType,
  9. } from '@codemirror/view'
  10. import {
  11. AnyOperation,
  12. Change,
  13. DeleteOperation,
  14. } from '../../../../../types/change'
  15. import { debugConsole } from '@/utils/debugging'
  16. import {
  17. isCommentOperation,
  18. isDeleteOperation,
  19. isInsertOperation,
  20. } from '@/utils/operations'
  21. import { Ranges } from '@/features/review-panel/context/ranges-context'
  22. import { Threads } from '@/features/review-panel/context/threads-context'
  23. import { isSelectionWithinOp } from '@/features/review-panel/utils/is-selection-within-op'
  24. type RangesData = {
  25. ranges: Ranges
  26. threads: Threads
  27. }
  28. const updateRangesEffect = StateEffect.define<RangesData>()
  29. const highlightRangesEffect = StateEffect.define<AnyOperation>()
  30. const clearHighlightRangesEffect = StateEffect.define<AnyOperation>()
  31. export const updateRanges = (data: RangesData): TransactionSpec => {
  32. return {
  33. effects: updateRangesEffect.of(data),
  34. }
  35. }
  36. export const highlightRanges = (op: AnyOperation): TransactionSpec => {
  37. return {
  38. effects: highlightRangesEffect.of(op),
  39. }
  40. }
  41. export const clearHighlightRanges = (op: AnyOperation): TransactionSpec => {
  42. return {
  43. effects: clearHighlightRangesEffect.of(op),
  44. }
  45. }
  46. export const rangesDataField = StateField.define<RangesData | null>({
  47. create() {
  48. return null
  49. },
  50. update(rangesData, tr) {
  51. for (const effect of tr.effects) {
  52. if (effect.is(updateRangesEffect)) {
  53. return effect.value
  54. }
  55. }
  56. return rangesData
  57. },
  58. })
  59. /**
  60. * A custom extension that initialises the change manager, passes any updates to it,
  61. * and produces decorations for tracked changes and comments.
  62. */
  63. export const ranges = () => [
  64. rangesDataField,
  65. // handle viewportChanged updates
  66. ViewPlugin.define(() => {
  67. let timer: number
  68. return {
  69. update(update) {
  70. if (update.viewportChanged) {
  71. if (timer) {
  72. window.clearTimeout(timer)
  73. }
  74. timer = window.setTimeout(() => {
  75. dispatchEvent(new Event('editor:viewport-changed'))
  76. }, 25)
  77. }
  78. },
  79. }
  80. }),
  81. // draw change decorations
  82. ViewPlugin.define<
  83. PluginValue & {
  84. decorations: DecorationSet
  85. }
  86. >(
  87. () => {
  88. return {
  89. decorations: Decoration.none,
  90. update(update) {
  91. for (const transaction of update.transactions) {
  92. this.decorations = this.decorations.map(transaction.changes)
  93. for (const effect of transaction.effects) {
  94. if (effect.is(updateRangesEffect)) {
  95. this.decorations = buildChangeDecorations(effect.value)
  96. } else if (
  97. effect.is(highlightRangesEffect) &&
  98. isDeleteOperation(effect.value)
  99. ) {
  100. this.decorations = updateDeleteWidgetHighlight(
  101. this.decorations,
  102. widget =>
  103. widget.change.op.p === effect.value.p &&
  104. widget.highlightType !== 'focus',
  105. 'highlight'
  106. )
  107. } else if (
  108. effect.is(clearHighlightRangesEffect) &&
  109. isDeleteOperation(effect.value)
  110. ) {
  111. this.decorations = updateDeleteWidgetHighlight(
  112. this.decorations,
  113. widget =>
  114. widget.change.op.p === effect.value.p &&
  115. widget.highlightType !== 'focus',
  116. null
  117. )
  118. }
  119. }
  120. if (transaction.selection) {
  121. this.decorations = updateDeleteWidgetHighlight(
  122. this.decorations,
  123. ({ change }) =>
  124. isSelectionWithinOp(change.op, update.state.selection.main),
  125. 'focus'
  126. )
  127. this.decorations = updateDeleteWidgetHighlight(
  128. this.decorations,
  129. ({ change }) =>
  130. !isSelectionWithinOp(change.op, update.state.selection.main),
  131. null
  132. )
  133. }
  134. }
  135. },
  136. }
  137. },
  138. {
  139. decorations: value => value.decorations,
  140. }
  141. ),
  142. // draw highlight decorations
  143. ViewPlugin.define<
  144. PluginValue & {
  145. decorations: DecorationSet
  146. }
  147. >(
  148. () => {
  149. return {
  150. decorations: Decoration.none,
  151. update(update) {
  152. for (const transaction of update.transactions) {
  153. this.decorations = this.decorations.map(transaction.changes)
  154. for (const effect of transaction.effects) {
  155. if (effect.is(highlightRangesEffect)) {
  156. this.decorations = buildHighlightDecorations(
  157. 'ol-cm-change-highlight',
  158. effect.value
  159. )
  160. } else if (effect.is(clearHighlightRangesEffect)) {
  161. this.decorations = Decoration.none
  162. }
  163. }
  164. }
  165. },
  166. }
  167. },
  168. {
  169. decorations: value => value.decorations,
  170. }
  171. ),
  172. // draw focus decorations
  173. ViewPlugin.define<
  174. PluginValue & {
  175. decorations: DecorationSet
  176. }
  177. >(
  178. view => {
  179. return {
  180. decorations: Decoration.none,
  181. update(update) {
  182. if (
  183. !update.transactions.some(
  184. tr =>
  185. tr.selection ||
  186. tr.effects.some(effect => effect.is(updateRangesEffect))
  187. )
  188. ) {
  189. this.decorations = this.decorations.map(update.changes)
  190. return
  191. }
  192. this.decorations = Decoration.none
  193. const rangesData = view.state.field(rangesDataField)
  194. if (!rangesData?.ranges) {
  195. return
  196. }
  197. const { changes, comments } = rangesData.ranges
  198. const unresolvedComments = rangesData.threads
  199. ? comments.filter(
  200. comment =>
  201. comment.op.t &&
  202. rangesData.threads[comment.op.t] &&
  203. !rangesData.threads[comment.op.t].resolved
  204. )
  205. : []
  206. for (const range of [...changes, ...unresolvedComments]) {
  207. if (isSelectionWithinOp(range.op, update.state.selection.main)) {
  208. this.decorations = buildHighlightDecorations(
  209. 'ol-cm-change-focus',
  210. range.op
  211. )
  212. break
  213. }
  214. }
  215. },
  216. }
  217. },
  218. {
  219. decorations: value => value.decorations,
  220. }
  221. ),
  222. // styles for change decorations
  223. trackChangesTheme,
  224. ]
  225. const buildChangeDecorations = (data: RangesData) => {
  226. if (!data.ranges) {
  227. return Decoration.none
  228. }
  229. const changes = [...data.ranges.changes, ...data.ranges.comments]
  230. const decorations = []
  231. for (const change of changes) {
  232. try {
  233. decorations.push(...createChangeRange(change, data))
  234. } catch (error) {
  235. // ignore invalid changes
  236. debugConsole.debug('invalid change position', error)
  237. }
  238. }
  239. return Decoration.set(decorations, true)
  240. }
  241. const updateDeleteWidgetHighlight = (
  242. decorations: DecorationSet,
  243. predicate: (widget: ChangeDeletedWidget) => boolean,
  244. highlightType?: 'focus' | 'highlight' | null
  245. ) => {
  246. const widgetsToReplace: ChangeDeletedWidget[] = []
  247. const cursor = decorations.iter()
  248. while (cursor.value) {
  249. const widget = cursor.value.spec?.widget
  250. if (widget instanceof ChangeDeletedWidget && predicate(widget)) {
  251. widgetsToReplace.push(cursor.value.spec.widget)
  252. }
  253. cursor.next()
  254. }
  255. return decorations.update({
  256. sort: true,
  257. filter: (from, to, decoration) => {
  258. return !widgetsToReplace.includes(decoration.spec?.widget)
  259. },
  260. add: widgetsToReplace.map(({ change }) =>
  261. Decoration.widget({
  262. widget: new ChangeDeletedWidget(change, highlightType),
  263. side: 1,
  264. opType: 'd',
  265. id: change.id,
  266. metadata: change.metadata,
  267. }).range(change.op.p, change.op.p)
  268. ),
  269. })
  270. }
  271. const buildHighlightDecorations = (className: string, op: AnyOperation) => {
  272. if (isDeleteOperation(op)) {
  273. // delete indicators are handled in change decorations
  274. return Decoration.none
  275. }
  276. const opFrom = op.p
  277. const opLength = isInsertOperation(op) ? op.i.length : op.c.length
  278. const opType = isInsertOperation(op) ? 'i' : 'c'
  279. if (opLength === 0) {
  280. return Decoration.none
  281. }
  282. return Decoration.set(
  283. Decoration.mark({
  284. class: `${className} ${className}-${opType}`,
  285. }).range(opFrom, opFrom + opLength),
  286. true
  287. )
  288. }
  289. class ChangeDeletedWidget extends WidgetType {
  290. constructor(
  291. public change: Change<DeleteOperation>,
  292. public highlightType: 'highlight' | 'focus' | null = null
  293. ) {
  294. super()
  295. }
  296. toDOM() {
  297. const widget = document.createElement('span')
  298. widget.classList.add('ol-cm-change')
  299. widget.classList.add('ol-cm-change-d')
  300. if (this.highlightType) {
  301. widget.classList.add(`ol-cm-change-d-${this.highlightType}`)
  302. }
  303. return widget
  304. }
  305. eq(old: ChangeDeletedWidget) {
  306. return old.highlightType === this.highlightType
  307. }
  308. }
  309. const createChangeRange = (change: Change, data: RangesData) => {
  310. const { id, metadata, op } = change
  311. const from = op.p
  312. if (isDeleteOperation(op)) {
  313. const opType = 'd'
  314. const changeWidget = Decoration.widget({
  315. widget: new ChangeDeletedWidget(change as Change<DeleteOperation>),
  316. side: 1,
  317. opType,
  318. id,
  319. metadata,
  320. })
  321. return [changeWidget.range(from, from)]
  322. }
  323. const _isCommentOperation = isCommentOperation(op)
  324. if (_isCommentOperation) {
  325. const thread = data.threads[op.t]
  326. if (!thread || thread.resolved) {
  327. return []
  328. }
  329. }
  330. const opType = _isCommentOperation ? 'c' : 'i'
  331. const changedText = _isCommentOperation ? op.c : op.i
  332. const to = from + changedText.length
  333. // Mark decorations must not be empty
  334. if (from === to) {
  335. return []
  336. }
  337. const changeMark = Decoration.mark({
  338. tagName: 'span',
  339. class: `ol-cm-change ol-cm-change-${opType}`,
  340. opType,
  341. id,
  342. metadata,
  343. })
  344. return [changeMark.range(from, to)]
  345. }
  346. const trackChangesTheme = EditorView.baseTheme({
  347. '.ol-cm-change-i, .ol-cm-change-highlight-i, .ol-cm-change-focus-i': {
  348. backgroundColor: 'rgba(44, 142, 48, 0.30)',
  349. },
  350. '&light .ol-cm-change-c, &light .ol-cm-change-highlight-c, &light .ol-cm-change-focus-c':
  351. {
  352. backgroundColor: 'rgba(243, 177, 17, 0.30)',
  353. },
  354. '&dark .ol-cm-change-c, &dark .ol-cm-change-highlight-c, &dark .ol-cm-change-focus-c':
  355. {
  356. backgroundColor: 'rgba(194, 93, 11, 0.15)',
  357. },
  358. '.ol-cm-change-focus .ol-cm-change': {
  359. backgroundColor: 'transparent',
  360. },
  361. '.ol-cm-change': {
  362. padding: 'var(--half-leading, 0) 0',
  363. },
  364. '.ol-cm-change-highlight': {
  365. padding: 'var(--half-leading, 0) 0',
  366. },
  367. '.ol-cm-change-focus': {
  368. padding: 'var(--half-leading, 0) 0',
  369. },
  370. '&light .ol-cm-change-d': {
  371. borderLeft: '2px dotted #c5060b',
  372. marginLeft: '-1px',
  373. },
  374. '&dark .ol-cm-change-d': {
  375. borderLeft: '2px dotted #c5060b',
  376. marginLeft: '-1px',
  377. },
  378. '&light .ol-cm-change-d-highlight': {
  379. borderLeft: '3px solid #c5060b',
  380. marginLeft: '-2px',
  381. },
  382. '&dark .ol-cm-change-d-highlight': {
  383. borderLeft: '3px solid #c5060b',
  384. marginLeft: '-2px',
  385. },
  386. })