track-changes.ts 14 KB

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