track-changes.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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(
  197. public change: Change,
  198. public opType: string
  199. ) {
  200. super()
  201. }
  202. toDOM() {
  203. const widget = document.createElement('span')
  204. widget.className = 'ol-cm-change-callout'
  205. widget.classList.add(`ol-cm-change-callout-${this.opType}`)
  206. const inner = document.createElement('span')
  207. inner.classList.add('ol-cm-change-callout-inner')
  208. widget.appendChild(inner)
  209. return widget
  210. }
  211. eq(widget: ChangeCalloutWidget) {
  212. return widget.opType === this.opType
  213. }
  214. updateDOM(element: HTMLElement) {
  215. element.className = 'ol-cm-change-callout'
  216. element.classList.add(`ol-cm-change-callout-${this.opType}`)
  217. return true
  218. }
  219. }
  220. const createChangeRange = (change: Change, currentDoc: DocumentContainer) => {
  221. const { id, metadata, op } = change
  222. const from = op.p
  223. // TODO: find valid positions?
  224. if (isDeleteOperation(op)) {
  225. const opType = 'd'
  226. const changeWidget = Decoration.widget({
  227. widget: new ChangeDeletedWidget(change as Change<DeleteOperation>),
  228. side: 1,
  229. opType,
  230. id,
  231. metadata,
  232. })
  233. const calloutWidget = Decoration.widget({
  234. widget: new ChangeCalloutWidget(change, opType),
  235. side: 1,
  236. opType,
  237. id,
  238. metadata,
  239. })
  240. return [calloutWidget.range(from, from), changeWidget.range(from, from)]
  241. }
  242. const _isCommentOperation = isCommentOperation(op)
  243. if (
  244. _isCommentOperation &&
  245. (currentDoc.ranges as RangesTrackerWithResolvedThreadIds)
  246. .resolvedThreadIds![op.t]
  247. ) {
  248. return []
  249. }
  250. const opType = _isCommentOperation ? 'c' : 'i'
  251. const changedText = _isCommentOperation ? op.c : op.i
  252. const to = from + changedText.length
  253. // Mark decorations must not be empty
  254. if (from === to) {
  255. return []
  256. }
  257. const changeMark = Decoration.mark({
  258. tagName: 'span',
  259. class: `ol-cm-change ol-cm-change-${opType}`,
  260. opType,
  261. id,
  262. metadata,
  263. })
  264. const calloutWidget = Decoration.widget({
  265. widget: new ChangeCalloutWidget(change, opType),
  266. opType,
  267. id,
  268. metadata,
  269. })
  270. return [calloutWidget.range(from, from), changeMark.range(from, to)]
  271. }
  272. const trackChangesTheme = EditorView.baseTheme({
  273. '.cm-line': {
  274. overflowX: 'hidden', // needed so the callout elements don't overflow (requires line wrapping to be on)
  275. },
  276. '&light .ol-cm-change-i': {
  277. backgroundColor: '#2c8e304d',
  278. },
  279. '&dark .ol-cm-change-i': {
  280. backgroundColor: 'rgba(37, 107, 41, 0.15)',
  281. },
  282. '&light .ol-cm-change-c': {
  283. backgroundColor: '#f3b1114d',
  284. },
  285. '&dark .ol-cm-change-c': {
  286. backgroundColor: 'rgba(194, 93, 11, 0.15)',
  287. },
  288. '.ol-cm-change': {
  289. padding: 'var(--half-leading, 0) 0',
  290. },
  291. '.ol-cm-change-d': {
  292. borderLeft: '2px dotted #c5060b',
  293. marginLeft: '-1px',
  294. },
  295. '.ol-cm-change-callout': {
  296. position: 'relative',
  297. pointerEvents: 'none',
  298. padding: 'var(--half-leading, 0) 0',
  299. },
  300. '.ol-cm-change-callout-inner': {
  301. display: 'inline-block',
  302. position: 'absolute',
  303. left: 0,
  304. bottom: 0,
  305. width: '100vw',
  306. borderBottom: '1px dashed black',
  307. },
  308. // disable callout line in Firefox
  309. '@supports (-moz-appearance:none)': {
  310. '.ol-cm-change-callout-inner': {
  311. display: 'none',
  312. },
  313. },
  314. '.ol-cm-change-callout-i .ol-cm-change-callout-inner': {
  315. borderColor: '#2c8e30',
  316. },
  317. '.ol-cm-change-callout-c .ol-cm-change-callout-inner': {
  318. borderColor: '#f3b111',
  319. },
  320. '.ol-cm-change-callout-d .ol-cm-change-callout-inner': {
  321. borderColor: '#c5060b',
  322. },
  323. })