track-changes.ts 8.7 KB

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