ranges.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. import { EditorState, StateEffect, 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. Change,
  12. DeleteOperation,
  13. EditOperation,
  14. } from '../../../../../types/change'
  15. import { ChangeManager } from './changes/change-manager'
  16. import { debugConsole } from '@/utils/debugging'
  17. import {
  18. isCommentOperation,
  19. isDeleteOperation,
  20. isInsertOperation,
  21. } from '@/utils/operations'
  22. import {
  23. DocumentContainer,
  24. RangesTrackerWithResolvedThreadIds,
  25. } from '@/features/ide-react/editor/document-container'
  26. import { trackChangesAnnotation } from '@/features/source-editor/extensions/realtime'
  27. import { Ranges } from '@/features/review-panel-new/context/ranges-context'
  28. import { Threads } from '@/features/review-panel-new/context/threads-context'
  29. import { isSplitTestEnabled } from '@/utils/splitTestUtils'
  30. type RangesData = {
  31. ranges: Ranges
  32. threads: Threads
  33. }
  34. const updateRangesEffect = StateEffect.define<RangesData>()
  35. export const updateRanges = (data: RangesData): TransactionSpec => {
  36. return {
  37. effects: updateRangesEffect.of(data),
  38. }
  39. }
  40. const clearChangesEffect = StateEffect.define()
  41. const buildChangesEffect = StateEffect.define()
  42. type Options = {
  43. currentDoc: DocumentContainer
  44. loadingThreads?: boolean
  45. ranges?: Ranges
  46. threads?: Threads
  47. }
  48. /**
  49. * A custom extension that initialises the change manager, passes any updates to it,
  50. * and produces decorations for tracked changes and comments.
  51. */
  52. export const ranges = (
  53. { currentDoc, loadingThreads, ranges, threads }: Options,
  54. changeManager?: ChangeManager
  55. ) => {
  56. return [
  57. // initialize/destroy the change manager, and handle any updates
  58. changeManager
  59. ? ViewPlugin.define(() => {
  60. changeManager.initialize()
  61. return {
  62. update: update => {
  63. changeManager.handleUpdate(update)
  64. },
  65. destroy: () => {
  66. changeManager.destroy()
  67. },
  68. }
  69. })
  70. : ViewPlugin.define(view => {
  71. let timer: number
  72. return {
  73. update(update) {
  74. if (update.viewportChanged) {
  75. if (timer) {
  76. window.clearTimeout(timer)
  77. }
  78. timer = window.setTimeout(() => {
  79. dispatchEvent(new Event('editor:viewport-changed'))
  80. }, 25)
  81. }
  82. },
  83. }
  84. }),
  85. // draw change decorations
  86. ViewPlugin.define<
  87. PluginValue & {
  88. decorations: DecorationSet
  89. }
  90. >(
  91. () => {
  92. let decorations = Decoration.none
  93. if (isSplitTestEnabled('review-panel-redesign')) {
  94. if (ranges && threads) {
  95. decorations = buildChangeDecorations(currentDoc, {
  96. ranges,
  97. threads,
  98. })
  99. }
  100. } else if (!loadingThreads) {
  101. decorations = buildChangeDecorations(currentDoc)
  102. }
  103. return {
  104. decorations,
  105. update(update) {
  106. for (const transaction of update.transactions) {
  107. this.decorations = this.decorations.map(transaction.changes)
  108. for (const effect of transaction.effects) {
  109. if (effect.is(clearChangesEffect)) {
  110. this.decorations = Decoration.none
  111. } else if (effect.is(buildChangesEffect)) {
  112. this.decorations = buildChangeDecorations(currentDoc)
  113. } else if (effect.is(updateRangesEffect)) {
  114. this.decorations = buildChangeDecorations(
  115. currentDoc,
  116. effect.value
  117. )
  118. }
  119. }
  120. }
  121. },
  122. }
  123. },
  124. {
  125. decorations: value => value.decorations,
  126. }
  127. ),
  128. // styles for change decorations
  129. trackChangesTheme,
  130. ]
  131. }
  132. export const clearChangeMarkers = () => {
  133. return {
  134. effects: clearChangesEffect.of(null),
  135. }
  136. }
  137. export const buildChangeMarkers = () => {
  138. return {
  139. effects: buildChangesEffect.of(null),
  140. }
  141. }
  142. const buildChangeDecorations = (
  143. currentDoc: DocumentContainer,
  144. data?: RangesData
  145. ) => {
  146. const ranges = data ? data.ranges : currentDoc.ranges
  147. if (!ranges) {
  148. return Decoration.none
  149. }
  150. const changes = [...ranges.changes, ...ranges.comments]
  151. const decorations = []
  152. for (const change of changes) {
  153. try {
  154. decorations.push(...createChangeRange(change, currentDoc, data))
  155. } catch (error) {
  156. // ignore invalid changes
  157. debugConsole.debug('invalid change position', error)
  158. }
  159. }
  160. return Decoration.set(decorations, true)
  161. }
  162. class ChangeDeletedWidget extends WidgetType {
  163. constructor(public change: Change<DeleteOperation>) {
  164. super()
  165. }
  166. toDOM() {
  167. const widget = document.createElement('span')
  168. widget.classList.add('ol-cm-change')
  169. widget.classList.add('ol-cm-change-d')
  170. return widget
  171. }
  172. eq() {
  173. return true
  174. }
  175. }
  176. class ChangeCalloutWidget extends WidgetType {
  177. constructor(
  178. public change: Change,
  179. public opType: string
  180. ) {
  181. super()
  182. }
  183. toDOM() {
  184. const widget = document.createElement('span')
  185. widget.className = 'ol-cm-change-callout'
  186. widget.classList.add(`ol-cm-change-callout-${this.opType}`)
  187. const inner = document.createElement('span')
  188. inner.classList.add('ol-cm-change-callout-inner')
  189. widget.appendChild(inner)
  190. return widget
  191. }
  192. eq(widget: ChangeCalloutWidget) {
  193. return widget.opType === this.opType
  194. }
  195. updateDOM(element: HTMLElement) {
  196. element.className = 'ol-cm-change-callout'
  197. element.classList.add(`ol-cm-change-callout-${this.opType}`)
  198. return true
  199. }
  200. }
  201. const createChangeRange = (
  202. change: Change,
  203. currentDoc: DocumentContainer,
  204. data?: RangesData
  205. ) => {
  206. const { id, metadata, op } = change
  207. const from = op.p
  208. // TODO: find valid positions?
  209. if (isDeleteOperation(op)) {
  210. const opType = 'd'
  211. const changeWidget = Decoration.widget({
  212. widget: new ChangeDeletedWidget(change as Change<DeleteOperation>),
  213. side: 1,
  214. opType,
  215. id,
  216. metadata,
  217. })
  218. const calloutWidget = Decoration.widget({
  219. widget: new ChangeCalloutWidget(change, opType),
  220. side: 1,
  221. opType,
  222. id,
  223. metadata,
  224. })
  225. return [calloutWidget.range(from, from), changeWidget.range(from, from)]
  226. }
  227. const _isCommentOperation = isCommentOperation(op)
  228. if (
  229. _isCommentOperation &&
  230. (currentDoc.ranges as RangesTrackerWithResolvedThreadIds)
  231. .resolvedThreadIds![op.t]
  232. ) {
  233. return []
  234. }
  235. if (_isCommentOperation) {
  236. if (data) {
  237. const thread = data.threads[op.t]
  238. if (!thread || thread.resolved) {
  239. return []
  240. }
  241. } else if (
  242. (currentDoc.ranges as RangesTrackerWithResolvedThreadIds)
  243. .resolvedThreadIds![op.t]
  244. ) {
  245. return []
  246. }
  247. }
  248. const opType = _isCommentOperation ? 'c' : 'i'
  249. const changedText = _isCommentOperation ? op.c : op.i
  250. const to = from + changedText.length
  251. // Mark decorations must not be empty
  252. if (from === to) {
  253. return []
  254. }
  255. const changeMark = Decoration.mark({
  256. tagName: 'span',
  257. class: `ol-cm-change ol-cm-change-${opType}`,
  258. opType,
  259. id,
  260. metadata,
  261. })
  262. const calloutWidget = Decoration.widget({
  263. widget: new ChangeCalloutWidget(change, opType),
  264. opType,
  265. id,
  266. metadata,
  267. })
  268. return [calloutWidget.range(from, from), changeMark.range(from, to)]
  269. }
  270. /**
  271. * Remove tracked changes from the range tracker when they're rejected,
  272. * and restore the original content
  273. */
  274. export const rejectChanges = (
  275. state: EditorState,
  276. ranges: DocumentContainer['ranges'],
  277. changeIds: string[]
  278. ) => {
  279. const changes = ranges!.getChanges(changeIds) as Change<EditOperation>[]
  280. if (changes.length === 0) {
  281. return {}
  282. }
  283. // When doing bulk rejections, adjacent changes might interact with each other.
  284. // Consider an insertion with an adjacent deletion (which is a common use-case, replacing words):
  285. //
  286. // "foo bar baz" -> "foo quux baz"
  287. //
  288. // The change above will be modeled with two ops, with the insertion going first:
  289. //
  290. // foo quux baz
  291. // |--| -> insertion of "quux", op 1, at position 4
  292. // | -> deletion of "bar", op 2, pushed forward by "quux" to position 8
  293. //
  294. // When rejecting these changes at once, if the insertion is rejected first, we get unexpected
  295. // results. What happens is:
  296. //
  297. // 1) Rejecting the insertion deletes the added word "quux", i.e., it removes 4 chars
  298. // starting from position 4;
  299. //
  300. // "foo quux baz" -> "foo baz"
  301. // |--| -> 4 characters to be removed
  302. //
  303. // 2) Rejecting the deletion adds the deleted word "bar" at position 8 (i.e. it will act as if
  304. // the word "quuux" was still present).
  305. //
  306. // "foo baz" -> "foo bazbar"
  307. // | -> deletion of "bar" is reverted by reinserting "bar" at position 8
  308. //
  309. // While the intended result would be "foo bar baz", what we get is:
  310. //
  311. // "foo bazbar" (note "bar" readded at position 8)
  312. //
  313. // The issue happens because of step 1. To revert the insertion of "quux", 4 characters are deleted
  314. // from position 4. This includes the position where the deletion exists; when that position is
  315. // cleared, the RangesTracker considers that the deletion is gone and stops tracking/updating it.
  316. // As we still hold a reference to it, the code tries to revert it by readding the deleted text, but
  317. // does so at the outdated position (position 8, which was valid when "quux" was present).
  318. //
  319. // To avoid this kind of problem, we need to make sure that reverting operations doesn't affect
  320. // subsequent operations that come after. Reverse sorting the operations based on position will
  321. // achieve it; in the case above, it makes sure that the the deletion is reverted first:
  322. //
  323. // 1) Rejecting the deletion adds the deleted word "bar" at position 8
  324. //
  325. // "foo quux baz" -> "foo quuxbar baz"
  326. // | -> deletion of "bar" is reverted by
  327. // reinserting "bar" at position 8
  328. //
  329. // 2) Rejecting the insertion deletes the added word "quux", i.e., it removes 4 chars
  330. // starting from position 4 and achieves the expected result:
  331. //
  332. // "foo quuxbar baz" -> "foo bar baz"
  333. // |--| -> 4 characters to be removed
  334. changes.sort((a, b) => b.op.p - a.op.p)
  335. const changesToDispatch = changes.map(change => {
  336. const { op } = change
  337. if (isInsertOperation(op)) {
  338. const from = op.p
  339. const content = op.i
  340. const to = from + content.length
  341. const text = state.doc.sliceString(from, to)
  342. if (text !== content) {
  343. throw new Error(`Op to be removed does not match editor text`)
  344. }
  345. return { from, to, insert: '' }
  346. } else if (isDeleteOperation(op)) {
  347. return {
  348. from: op.p,
  349. to: op.p,
  350. insert: op.d,
  351. }
  352. } else {
  353. throw new Error(`unknown change type: ${JSON.stringify(change)}`)
  354. }
  355. })
  356. return {
  357. changes: changesToDispatch,
  358. annotations: [trackChangesAnnotation.of('reject')],
  359. }
  360. }
  361. const trackChangesTheme = EditorView.baseTheme({
  362. '.cm-line': {
  363. overflowX: 'hidden', // needed so the callout elements don't overflow (requires line wrapping to be on)
  364. },
  365. '&light .ol-cm-change-i': {
  366. backgroundColor: '#2c8e304d',
  367. },
  368. '&dark .ol-cm-change-i': {
  369. backgroundColor: 'rgba(37, 107, 41, 0.15)',
  370. },
  371. '&light .ol-cm-change-c': {
  372. backgroundColor: '#f3b1114d',
  373. },
  374. '&dark .ol-cm-change-c': {
  375. backgroundColor: 'rgba(194, 93, 11, 0.15)',
  376. },
  377. '.ol-cm-change': {
  378. padding: 'var(--half-leading, 0) 0',
  379. },
  380. '.ol-cm-change-d': {
  381. borderLeft: '2px dotted #c5060b',
  382. marginLeft: '-1px',
  383. },
  384. '.ol-cm-change-callout': {
  385. position: 'relative',
  386. pointerEvents: 'none',
  387. padding: 'var(--half-leading, 0) 0',
  388. },
  389. '.ol-cm-change-callout-inner': {
  390. display: 'inline-block',
  391. position: 'absolute',
  392. left: 0,
  393. bottom: 0,
  394. width: '100vw',
  395. borderBottom: '1px dashed black',
  396. },
  397. // disable callout line in Firefox
  398. '@supports (-moz-appearance:none)': {
  399. '.ol-cm-change-callout-inner': {
  400. display: 'none',
  401. },
  402. },
  403. '.ol-cm-change-callout-i .ol-cm-change-callout-inner': {
  404. borderColor: '#2c8e30',
  405. },
  406. '.ol-cm-change-callout-c .ol-cm-change-callout-inner': {
  407. borderColor: '#f3b111',
  408. },
  409. '.ol-cm-change-callout-d .ol-cm-change-callout-inner': {
  410. borderColor: '#c5060b',
  411. },
  412. })