track-changes.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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 {
  26. Change,
  27. ChangeOperation,
  28. CommentOperation,
  29. DeleteOperation,
  30. Operation,
  31. } from '../../../../../types/change'
  32. import { ChangeManager } from './changes/change-manager'
  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. console.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 isInsertOperation = (op: Operation): op is InsertOperation => 'i' in op
  216. const isChangeOperation = (op: Operation): op is ChangeOperation =>
  217. 'c' in op && 't' in op
  218. const isCommentOperation = (op: Operation): op is CommentOperation =>
  219. 'c' in op && !('t' in op)
  220. const isDeleteOperation = (op: Operation): op is DeleteOperation => 'd' in op
  221. const createChangeRange = (change: Change, currentDoc: CurrentDoc) => {
  222. const { id, metadata, op } = change
  223. const from = op.p
  224. // TODO: find valid positions?
  225. if (isDeleteOperation(op)) {
  226. const opType = 'd'
  227. const changeWidget = Decoration.widget({
  228. widget: new ChangeDeletedWidget(change as Change<DeleteOperation>),
  229. opType,
  230. id,
  231. metadata,
  232. })
  233. const calloutWidget = Decoration.widget({
  234. widget: new ChangeCalloutWidget(change, opType),
  235. opType,
  236. id,
  237. metadata,
  238. })
  239. return [calloutWidget.range(from, from), changeWidget.range(from, from)]
  240. }
  241. if (isChangeOperation(op) && currentDoc.ranges.resolvedThreadIds[op.t]) {
  242. return []
  243. }
  244. const isChangeOrCommentOperation =
  245. isChangeOperation(op) || isCommentOperation(op)
  246. const opType = isChangeOrCommentOperation ? 'c' : 'i'
  247. const changedText = isChangeOrCommentOperation ? op.c : op.i
  248. const to = from + changedText.length
  249. // Mark decorations must not be empty
  250. if (from === to) {
  251. return []
  252. }
  253. const changeMark = Decoration.mark({
  254. tagName: 'span',
  255. class: `ol-cm-change ol-cm-change-${opType}`,
  256. opType,
  257. id,
  258. metadata,
  259. })
  260. const calloutWidget = Decoration.widget({
  261. widget: new ChangeCalloutWidget(change, opType),
  262. opType,
  263. id,
  264. metadata,
  265. })
  266. return [calloutWidget.range(from, from), changeMark.range(from, to)]
  267. }
  268. const trackChangesTheme = EditorView.baseTheme({
  269. '.cm-line': {
  270. overflowX: 'hidden', // needed so the callout elements don't overflow (requires line wrapping to be on)
  271. },
  272. '&light .ol-cm-change-i': {
  273. backgroundColor: '#2c8e304d',
  274. },
  275. '&dark .ol-cm-change-i': {
  276. backgroundColor: 'rgba(37, 107, 41, 0.15)',
  277. },
  278. '&light .ol-cm-change-c': {
  279. backgroundColor: '#f3b1114d',
  280. },
  281. '&dark .ol-cm-change-c': {
  282. backgroundColor: 'rgba(194, 93, 11, 0.15)',
  283. },
  284. '.ol-cm-change': {
  285. padding: 'var(--half-leading, 0) 0',
  286. },
  287. '.ol-cm-change-d': {
  288. borderLeft: '2px dotted #c5060b',
  289. marginLeft: '-1px',
  290. },
  291. '.ol-cm-change-callout': {
  292. position: 'relative',
  293. pointerEvents: 'none',
  294. padding: 'var(--half-leading, 0) 0',
  295. },
  296. '.ol-cm-change-callout-inner': {
  297. display: 'inline-block',
  298. position: 'absolute',
  299. left: 0,
  300. bottom: 0,
  301. width: '10000px',
  302. borderBottom: '1px dashed black',
  303. },
  304. '.ol-cm-change-callout-i .ol-cm-change-callout-inner': {
  305. borderColor: '#2c8e30',
  306. },
  307. '.ol-cm-change-callout-c .ol-cm-change-callout-inner': {
  308. borderColor: '#f3b111',
  309. },
  310. '.ol-cm-change-callout-d .ol-cm-change-callout-inner': {
  311. borderColor: '#c5060b',
  312. },
  313. })