track-changes.ts 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. import {
  2. EditorState,
  3. RangeSet,
  4. StateEffect,
  5. StateField,
  6. Transaction,
  7. } from '@codemirror/state'
  8. import {
  9. Decoration,
  10. type DecorationSet,
  11. EditorView,
  12. type PluginValue,
  13. ViewPlugin,
  14. WidgetType,
  15. } from '@codemirror/view'
  16. import {
  17. findCommentsInCut,
  18. findDetachedCommentsInChanges,
  19. restoreCommentsOnPaste,
  20. restoreDetachedComments,
  21. StoredComment,
  22. } from './changes/comments'
  23. import { invertedEffects } from '@codemirror/commands'
  24. import { Change, DeleteOperation } from '../../../../../types/change'
  25. import { ChangeManager } from './changes/change-manager'
  26. import { debugConsole } from '@/utils/debugging'
  27. import { isCommentOperation, isDeleteOperation } from '@/utils/operations'
  28. import {
  29. DocumentContainer,
  30. RangesTrackerWithResolvedThreadIds,
  31. } from '@/features/ide-react/editor/document-container'
  32. const clearChangesEffect = StateEffect.define()
  33. const buildChangesEffect = StateEffect.define()
  34. const restoreDetachedCommentsEffect = StateEffect.define<RangeSet<any>>({
  35. map: (value, mapping) => {
  36. return value
  37. .update({
  38. filter: (from, to) => {
  39. return from <= mapping.length && to <= mapping.length
  40. },
  41. })
  42. .map(mapping)
  43. },
  44. })
  45. type Options = {
  46. currentDoc: DocumentContainer
  47. loadingThreads: boolean
  48. }
  49. /**
  50. * A custom extension that initialises the change manager, passes any updates to it,
  51. * and produces decorations for tracked changes and comments.
  52. */
  53. export const trackChanges = (
  54. { currentDoc, loadingThreads }: Options,
  55. changeManager: ChangeManager
  56. ) => {
  57. // A state field that stored any comments found within the ranges of a "cut" transaction,
  58. // to be restored when pasting matching text.
  59. const cutCommentsState = StateField.define<StoredComment[]>({
  60. create: () => {
  61. return []
  62. },
  63. update: (value, transaction) => {
  64. if (transaction.annotation(Transaction.remote)) {
  65. return value
  66. }
  67. if (!transaction.docChanged) {
  68. return value
  69. }
  70. if (transaction.isUserEvent('delete.cut')) {
  71. return findCommentsInCut(currentDoc, transaction)
  72. }
  73. if (transaction.isUserEvent('input.paste')) {
  74. restoreCommentsOnPaste(currentDoc, transaction, value)
  75. return []
  76. }
  77. return value
  78. },
  79. })
  80. return [
  81. // attach any comments detached by the transaction as an inverted effect, to be applied on undo
  82. invertedEffects.of(transaction => {
  83. if (
  84. transaction.docChanged &&
  85. !transaction.annotation(Transaction.remote)
  86. ) {
  87. const detachedComments = findDetachedCommentsInChanges(
  88. currentDoc,
  89. transaction
  90. )
  91. if (detachedComments.size) {
  92. return [restoreDetachedCommentsEffect.of(detachedComments)]
  93. }
  94. }
  95. return []
  96. }),
  97. // restore any detached comments on undo
  98. EditorState.transactionExtender.of(transaction => {
  99. for (const effect of transaction.effects) {
  100. if (effect.is(restoreDetachedCommentsEffect)) {
  101. // send the comments to the ShareJS doc
  102. restoreDetachedComments(currentDoc, transaction, effect.value)
  103. // return a transaction spec to rebuild the change markers
  104. return buildChangeMarkers()
  105. }
  106. }
  107. return null
  108. }),
  109. cutCommentsState,
  110. // initialize/destroy the change manager, and handle any updates
  111. ViewPlugin.define(() => {
  112. changeManager.initialize()
  113. return {
  114. update: update => {
  115. changeManager.handleUpdate(update)
  116. },
  117. destroy: () => {
  118. changeManager.destroy()
  119. },
  120. }
  121. }),
  122. // draw change decorations
  123. ViewPlugin.define<
  124. PluginValue & {
  125. decorations: DecorationSet
  126. }
  127. >(
  128. () => {
  129. return {
  130. decorations: loadingThreads
  131. ? Decoration.none
  132. : buildChangeDecorations(currentDoc),
  133. update(update) {
  134. for (const transaction of update.transactions) {
  135. this.decorations = this.decorations.map(transaction.changes)
  136. for (const effect of transaction.effects) {
  137. if (effect.is(clearChangesEffect)) {
  138. this.decorations = Decoration.none
  139. } else if (effect.is(buildChangesEffect)) {
  140. this.decorations = buildChangeDecorations(currentDoc)
  141. }
  142. }
  143. }
  144. },
  145. }
  146. },
  147. {
  148. decorations: value => value.decorations,
  149. }
  150. ),
  151. // styles for change decorations
  152. trackChangesTheme,
  153. ]
  154. }
  155. export const clearChangeMarkers = () => {
  156. return {
  157. effects: clearChangesEffect.of(null),
  158. }
  159. }
  160. export const buildChangeMarkers = () => {
  161. return {
  162. effects: buildChangesEffect.of(null),
  163. }
  164. }
  165. const buildChangeDecorations = (currentDoc: DocumentContainer) => {
  166. if (!currentDoc.ranges) {
  167. return Decoration.none
  168. }
  169. const changes = [...currentDoc.ranges.changes, ...currentDoc.ranges.comments]
  170. const decorations = []
  171. for (const change of changes) {
  172. try {
  173. decorations.push(...createChangeRange(change, currentDoc))
  174. } catch (error) {
  175. // ignore invalid changes
  176. debugConsole.debug('invalid change position', error)
  177. }
  178. }
  179. return Decoration.set(decorations, true)
  180. }
  181. class ChangeDeletedWidget extends WidgetType {
  182. constructor(public change: Change<DeleteOperation>) {
  183. super()
  184. }
  185. toDOM() {
  186. const widget = document.createElement('span')
  187. widget.classList.add('ol-cm-change')
  188. widget.classList.add('ol-cm-change-d')
  189. return widget
  190. }
  191. eq() {
  192. return true
  193. }
  194. }
  195. class ChangeCalloutWidget extends WidgetType {
  196. constructor(public change: Change, public opType: string) {
  197. super()
  198. }
  199. toDOM() {
  200. const widget = document.createElement('span')
  201. widget.className = 'ol-cm-change-callout'
  202. widget.classList.add(`ol-cm-change-callout-${this.opType}`)
  203. const inner = document.createElement('span')
  204. inner.classList.add('ol-cm-change-callout-inner')
  205. widget.appendChild(inner)
  206. return widget
  207. }
  208. eq(widget: ChangeCalloutWidget) {
  209. return widget.opType === this.opType
  210. }
  211. updateDOM(element: HTMLElement) {
  212. element.className = 'ol-cm-change-callout'
  213. element.classList.add(`ol-cm-change-callout-${this.opType}`)
  214. return true
  215. }
  216. }
  217. const createChangeRange = (change: Change, currentDoc: DocumentContainer) => {
  218. const { id, metadata, op } = change
  219. const from = op.p
  220. // TODO: find valid positions?
  221. if (isDeleteOperation(op)) {
  222. const opType = 'd'
  223. const changeWidget = Decoration.widget({
  224. widget: new ChangeDeletedWidget(change as Change<DeleteOperation>),
  225. side: 1,
  226. opType,
  227. id,
  228. metadata,
  229. })
  230. const calloutWidget = Decoration.widget({
  231. widget: new ChangeCalloutWidget(change, opType),
  232. side: 1,
  233. opType,
  234. id,
  235. metadata,
  236. })
  237. return [calloutWidget.range(from, from), changeWidget.range(from, from)]
  238. }
  239. const _isCommentOperation = isCommentOperation(op)
  240. if (
  241. _isCommentOperation &&
  242. (currentDoc.ranges as RangesTrackerWithResolvedThreadIds)
  243. .resolvedThreadIds![op.t]
  244. ) {
  245. return []
  246. }
  247. const opType = _isCommentOperation ? 'c' : 'i'
  248. const changedText = _isCommentOperation ? op.c : op.i
  249. const to = from + changedText.length
  250. // Mark decorations must not be empty
  251. if (from === to) {
  252. return []
  253. }
  254. const changeMark = Decoration.mark({
  255. tagName: 'span',
  256. class: `ol-cm-change ol-cm-change-${opType}`,
  257. opType,
  258. id,
  259. metadata,
  260. })
  261. const calloutWidget = Decoration.widget({
  262. widget: new ChangeCalloutWidget(change, opType),
  263. opType,
  264. id,
  265. metadata,
  266. })
  267. return [calloutWidget.range(from, from), changeMark.range(from, to)]
  268. }
  269. const trackChangesTheme = EditorView.baseTheme({
  270. '.cm-line': {
  271. overflowX: 'hidden', // needed so the callout elements don't overflow (requires line wrapping to be on)
  272. },
  273. '&light .ol-cm-change-i': {
  274. backgroundColor: '#2c8e304d',
  275. },
  276. '&dark .ol-cm-change-i': {
  277. backgroundColor: 'rgba(37, 107, 41, 0.15)',
  278. },
  279. '&light .ol-cm-change-c': {
  280. backgroundColor: '#f3b1114d',
  281. },
  282. '&dark .ol-cm-change-c': {
  283. backgroundColor: 'rgba(194, 93, 11, 0.15)',
  284. },
  285. '.ol-cm-change': {
  286. padding: 'var(--half-leading, 0) 0',
  287. },
  288. '.ol-cm-change-d': {
  289. borderLeft: '2px dotted #c5060b',
  290. marginLeft: '-1px',
  291. },
  292. '.ol-cm-change-callout': {
  293. position: 'relative',
  294. pointerEvents: 'none',
  295. padding: 'var(--half-leading, 0) 0',
  296. },
  297. '.ol-cm-change-callout-inner': {
  298. display: 'inline-block',
  299. position: 'absolute',
  300. left: 0,
  301. bottom: 0,
  302. width: '10000px',
  303. borderBottom: '1px dashed black',
  304. },
  305. '.ol-cm-change-callout-i .ol-cm-change-callout-inner': {
  306. borderColor: '#2c8e30',
  307. },
  308. '.ol-cm-change-callout-c .ol-cm-change-callout-inner': {
  309. borderColor: '#f3b111',
  310. },
  311. '.ol-cm-change-callout-d .ol-cm-change-callout-inner': {
  312. borderColor: '#c5060b',
  313. },
  314. })