track-changes.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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. : ViewPlugin.define(view => {
  149. let timer: number
  150. return {
  151. update(update) {
  152. if (update.viewportChanged) {
  153. if (timer) {
  154. window.clearTimeout(timer)
  155. }
  156. timer = window.setTimeout(() => {
  157. dispatchEvent(new Event('editor:viewport-changed'))
  158. }, 25)
  159. }
  160. },
  161. }
  162. }),
  163. // draw change decorations
  164. ViewPlugin.define<
  165. PluginValue & {
  166. decorations: DecorationSet
  167. }
  168. >(
  169. () => {
  170. let decorations = Decoration.none
  171. if (isSplitTestEnabled('review-panel-redesign')) {
  172. if (ranges && threads) {
  173. decorations = buildChangeDecorations(currentDoc, {
  174. ranges,
  175. threads,
  176. })
  177. }
  178. } else if (!loadingThreads) {
  179. decorations = buildChangeDecorations(currentDoc)
  180. }
  181. return {
  182. decorations,
  183. update(update) {
  184. for (const transaction of update.transactions) {
  185. this.decorations = this.decorations.map(transaction.changes)
  186. for (const effect of transaction.effects) {
  187. if (effect.is(clearChangesEffect)) {
  188. this.decorations = Decoration.none
  189. } else if (effect.is(buildChangesEffect)) {
  190. this.decorations = buildChangeDecorations(currentDoc)
  191. } else if (effect.is(updateRangesEffect)) {
  192. this.decorations = buildChangeDecorations(
  193. currentDoc,
  194. effect.value
  195. )
  196. }
  197. }
  198. }
  199. },
  200. }
  201. },
  202. {
  203. decorations: value => value.decorations,
  204. }
  205. ),
  206. // styles for change decorations
  207. trackChangesTheme,
  208. ]
  209. }
  210. export const clearChangeMarkers = () => {
  211. return {
  212. effects: clearChangesEffect.of(null),
  213. }
  214. }
  215. export const buildChangeMarkers = () => {
  216. return {
  217. effects: buildChangesEffect.of(null),
  218. }
  219. }
  220. const buildChangeDecorations = (
  221. currentDoc: DocumentContainer,
  222. data?: RangesData
  223. ) => {
  224. const ranges = data ? data.ranges : currentDoc.ranges
  225. if (!ranges) {
  226. return Decoration.none
  227. }
  228. const changes = [...ranges.changes, ...ranges.comments]
  229. const decorations = []
  230. for (const change of changes) {
  231. try {
  232. decorations.push(...createChangeRange(change, currentDoc, data))
  233. } catch (error) {
  234. // ignore invalid changes
  235. debugConsole.debug('invalid change position', error)
  236. }
  237. }
  238. return Decoration.set(decorations, true)
  239. }
  240. class ChangeDeletedWidget extends WidgetType {
  241. constructor(public change: Change<DeleteOperation>) {
  242. super()
  243. }
  244. toDOM() {
  245. const widget = document.createElement('span')
  246. widget.classList.add('ol-cm-change')
  247. widget.classList.add('ol-cm-change-d')
  248. return widget
  249. }
  250. eq() {
  251. return true
  252. }
  253. }
  254. class ChangeCalloutWidget extends WidgetType {
  255. constructor(
  256. public change: Change,
  257. public opType: string
  258. ) {
  259. super()
  260. }
  261. toDOM() {
  262. const widget = document.createElement('span')
  263. widget.className = 'ol-cm-change-callout'
  264. widget.classList.add(`ol-cm-change-callout-${this.opType}`)
  265. const inner = document.createElement('span')
  266. inner.classList.add('ol-cm-change-callout-inner')
  267. widget.appendChild(inner)
  268. return widget
  269. }
  270. eq(widget: ChangeCalloutWidget) {
  271. return widget.opType === this.opType
  272. }
  273. updateDOM(element: HTMLElement) {
  274. element.className = 'ol-cm-change-callout'
  275. element.classList.add(`ol-cm-change-callout-${this.opType}`)
  276. return true
  277. }
  278. }
  279. const createChangeRange = (
  280. change: Change,
  281. currentDoc: DocumentContainer,
  282. data?: RangesData
  283. ) => {
  284. const { id, metadata, op } = change
  285. const from = op.p
  286. // TODO: find valid positions?
  287. if (isDeleteOperation(op)) {
  288. const opType = 'd'
  289. const changeWidget = Decoration.widget({
  290. widget: new ChangeDeletedWidget(change as Change<DeleteOperation>),
  291. side: 1,
  292. opType,
  293. id,
  294. metadata,
  295. })
  296. const calloutWidget = Decoration.widget({
  297. widget: new ChangeCalloutWidget(change, opType),
  298. side: 1,
  299. opType,
  300. id,
  301. metadata,
  302. })
  303. return [calloutWidget.range(from, from), changeWidget.range(from, from)]
  304. }
  305. const _isCommentOperation = isCommentOperation(op)
  306. if (
  307. _isCommentOperation &&
  308. (currentDoc.ranges as RangesTrackerWithResolvedThreadIds)
  309. .resolvedThreadIds![op.t]
  310. ) {
  311. return []
  312. }
  313. if (_isCommentOperation) {
  314. if (data) {
  315. const thread = data.threads[op.t]
  316. if (!thread || thread.resolved) {
  317. return []
  318. }
  319. } else if (
  320. (currentDoc.ranges as RangesTrackerWithResolvedThreadIds)
  321. .resolvedThreadIds![op.t]
  322. ) {
  323. return []
  324. }
  325. }
  326. const opType = _isCommentOperation ? 'c' : 'i'
  327. const changedText = _isCommentOperation ? op.c : op.i
  328. const to = from + changedText.length
  329. // Mark decorations must not be empty
  330. if (from === to) {
  331. return []
  332. }
  333. const changeMark = Decoration.mark({
  334. tagName: 'span',
  335. class: `ol-cm-change ol-cm-change-${opType}`,
  336. opType,
  337. id,
  338. metadata,
  339. })
  340. const calloutWidget = Decoration.widget({
  341. widget: new ChangeCalloutWidget(change, opType),
  342. opType,
  343. id,
  344. metadata,
  345. })
  346. return [calloutWidget.range(from, from), changeMark.range(from, to)]
  347. }
  348. /**
  349. * Remove tracked changes from the range tracker when they're rejected,
  350. * and restore the original content
  351. */
  352. export const rejectChanges = (
  353. state: EditorState,
  354. ranges: DocumentContainer['ranges'],
  355. changeIds: string[]
  356. ) => {
  357. const changes = ranges!.getChanges(changeIds) as Change<EditOperation>[]
  358. if (changes.length === 0) {
  359. return {}
  360. }
  361. // When doing bulk rejections, adjacent changes might interact with each other.
  362. // Consider an insertion with an adjacent deletion (which is a common use-case, replacing words):
  363. //
  364. // "foo bar baz" -> "foo quux baz"
  365. //
  366. // The change above will be modeled with two ops, with the insertion going first:
  367. //
  368. // foo quux baz
  369. // |--| -> insertion of "quux", op 1, at position 4
  370. // | -> deletion of "bar", op 2, pushed forward by "quux" to position 8
  371. //
  372. // When rejecting these changes at once, if the insertion is rejected first, we get unexpected
  373. // results. What happens is:
  374. //
  375. // 1) Rejecting the insertion deletes the added word "quux", i.e., it removes 4 chars
  376. // starting from position 4;
  377. //
  378. // "foo quux baz" -> "foo baz"
  379. // |--| -> 4 characters to be removed
  380. //
  381. // 2) Rejecting the deletion adds the deleted word "bar" at position 8 (i.e. it will act as if
  382. // the word "quuux" was still present).
  383. //
  384. // "foo baz" -> "foo bazbar"
  385. // | -> deletion of "bar" is reverted by reinserting "bar" at position 8
  386. //
  387. // While the intended result would be "foo bar baz", what we get is:
  388. //
  389. // "foo bazbar" (note "bar" readded at position 8)
  390. //
  391. // The issue happens because of step 1. To revert the insertion of "quux", 4 characters are deleted
  392. // from position 4. This includes the position where the deletion exists; when that position is
  393. // cleared, the RangesTracker considers that the deletion is gone and stops tracking/updating it.
  394. // As we still hold a reference to it, the code tries to revert it by readding the deleted text, but
  395. // does so at the outdated position (position 8, which was valid when "quux" was present).
  396. //
  397. // To avoid this kind of problem, we need to make sure that reverting operations doesn't affect
  398. // subsequent operations that come after. Reverse sorting the operations based on position will
  399. // achieve it; in the case above, it makes sure that the the deletion is reverted first:
  400. //
  401. // 1) Rejecting the deletion adds the deleted word "bar" at position 8
  402. //
  403. // "foo quux baz" -> "foo quuxbar baz"
  404. // | -> deletion of "bar" is reverted by
  405. // reinserting "bar" at position 8
  406. //
  407. // 2) Rejecting the insertion deletes the added word "quux", i.e., it removes 4 chars
  408. // starting from position 4 and achieves the expected result:
  409. //
  410. // "foo quuxbar baz" -> "foo bar baz"
  411. // |--| -> 4 characters to be removed
  412. changes.sort((a, b) => b.op.p - a.op.p)
  413. const changesToDispatch = changes.map(change => {
  414. const { op } = change
  415. if (isInsertOperation(op)) {
  416. const from = op.p
  417. const content = op.i
  418. const to = from + content.length
  419. const text = state.doc.sliceString(from, to)
  420. if (text !== content) {
  421. throw new Error(`Op to be removed does not match editor text`)
  422. }
  423. return { from, to, insert: '' }
  424. } else if (isDeleteOperation(op)) {
  425. return {
  426. from: op.p,
  427. to: op.p,
  428. insert: op.d,
  429. }
  430. } else {
  431. throw new Error(`unknown change type: ${JSON.stringify(change)}`)
  432. }
  433. })
  434. return {
  435. changes: changesToDispatch,
  436. annotations: [trackChangesAnnotation.of('reject')],
  437. }
  438. }
  439. const trackChangesTheme = EditorView.baseTheme({
  440. '.cm-line': {
  441. overflowX: 'hidden', // needed so the callout elements don't overflow (requires line wrapping to be on)
  442. },
  443. '&light .ol-cm-change-i': {
  444. backgroundColor: '#2c8e304d',
  445. },
  446. '&dark .ol-cm-change-i': {
  447. backgroundColor: 'rgba(37, 107, 41, 0.15)',
  448. },
  449. '&light .ol-cm-change-c': {
  450. backgroundColor: '#f3b1114d',
  451. },
  452. '&dark .ol-cm-change-c': {
  453. backgroundColor: 'rgba(194, 93, 11, 0.15)',
  454. },
  455. '.ol-cm-change': {
  456. padding: 'var(--half-leading, 0) 0',
  457. },
  458. '.ol-cm-change-d': {
  459. borderLeft: '2px dotted #c5060b',
  460. marginLeft: '-1px',
  461. },
  462. '.ol-cm-change-callout': {
  463. position: 'relative',
  464. pointerEvents: 'none',
  465. padding: 'var(--half-leading, 0) 0',
  466. },
  467. '.ol-cm-change-callout-inner': {
  468. display: 'inline-block',
  469. position: 'absolute',
  470. left: 0,
  471. bottom: 0,
  472. width: '100vw',
  473. borderBottom: '1px dashed black',
  474. },
  475. // disable callout line in Firefox
  476. '@supports (-moz-appearance:none)': {
  477. '.ol-cm-change-callout-inner': {
  478. display: 'none',
  479. },
  480. },
  481. '.ol-cm-change-callout-i .ol-cm-change-callout-inner': {
  482. borderColor: '#2c8e30',
  483. },
  484. '.ol-cm-change-callout-c .ol-cm-change-callout-inner': {
  485. borderColor: '#f3b111',
  486. },
  487. '.ol-cm-change-callout-d .ol-cm-change-callout-inner': {
  488. borderColor: '#c5060b',
  489. },
  490. })