track-changes.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. export const trackChanges = (
  51. { currentDoc, loadingThreads }: Options,
  52. changeManager: ChangeManager
  53. ) => {
  54. // A state field that stored any comments found within the ranges of a "cut" transaction,
  55. // to be restored when pasting matching text.
  56. const cutCommentsState = StateField.define<StoredComment[]>({
  57. create: () => {
  58. return []
  59. },
  60. update: (value, transaction) => {
  61. if (transaction.annotation(Transaction.remote)) {
  62. return value
  63. }
  64. if (!transaction.docChanged) {
  65. return value
  66. }
  67. if (transaction.isUserEvent('delete.cut')) {
  68. return findCommentsInCut(currentDoc, transaction)
  69. }
  70. if (transaction.isUserEvent('input.paste')) {
  71. restoreCommentsOnPaste(currentDoc, transaction, value)
  72. return []
  73. }
  74. return value
  75. },
  76. })
  77. return [
  78. // attach any comments detached by the transaction as an inverted effect, to be applied on undo
  79. invertedEffects.of(transaction => {
  80. if (
  81. transaction.docChanged &&
  82. !transaction.annotation(Transaction.remote)
  83. ) {
  84. const detachedComments = findDetachedCommentsInChanges(
  85. currentDoc,
  86. transaction
  87. )
  88. if (detachedComments.size) {
  89. return [restoreDetachedCommentsEffect.of(detachedComments)]
  90. }
  91. }
  92. return []
  93. }),
  94. // restore any detached comments on undo
  95. EditorState.transactionExtender.of(transaction => {
  96. for (const effect of transaction.effects) {
  97. if (effect.is(restoreDetachedCommentsEffect)) {
  98. // send the comments to the ShareJS doc
  99. restoreDetachedComments(currentDoc, transaction, effect.value)
  100. // return a transaction spec to rebuild the change markers
  101. return buildChangeMarkers()
  102. }
  103. }
  104. return null
  105. }),
  106. cutCommentsState,
  107. // initialize/destroy the change manager, and handle any updates
  108. ViewPlugin.define(() => {
  109. changeManager.initialize()
  110. return {
  111. update: update => {
  112. changeManager.handleUpdate(update)
  113. },
  114. destroy: () => {
  115. changeManager.destroy()
  116. },
  117. }
  118. }),
  119. // draw change decorations
  120. ViewPlugin.define<
  121. PluginValue & {
  122. decorations: DecorationSet
  123. }
  124. >(
  125. () => {
  126. return {
  127. decorations: loadingThreads
  128. ? Decoration.none
  129. : buildChangeDecorations(currentDoc),
  130. update(update) {
  131. for (const transaction of update.transactions) {
  132. this.decorations = this.decorations.map(transaction.changes)
  133. for (const effect of transaction.effects) {
  134. if (effect.is(clearChangesEffect)) {
  135. this.decorations = Decoration.none
  136. } else if (effect.is(buildChangesEffect)) {
  137. this.decorations = buildChangeDecorations(currentDoc)
  138. }
  139. }
  140. }
  141. },
  142. }
  143. },
  144. {
  145. decorations: value => value.decorations,
  146. }
  147. ),
  148. // styles for change decorations
  149. trackChangesTheme,
  150. ]
  151. }
  152. export const clearChangeMarkers = () => {
  153. return {
  154. effects: clearChangesEffect.of(null),
  155. }
  156. }
  157. export const buildChangeMarkers = () => {
  158. return {
  159. effects: buildChangesEffect.of(null),
  160. }
  161. }
  162. const buildChangeDecorations = (currentDoc: CurrentDoc) => {
  163. const changes = [...currentDoc.ranges.changes, ...currentDoc.ranges.comments]
  164. const decorations = []
  165. for (const change of changes) {
  166. try {
  167. decorations.push(...createChangeRange(change, currentDoc))
  168. } catch (error) {
  169. // ignore invalid changes
  170. console.debug('invalid change position', error)
  171. }
  172. }
  173. return Decoration.set(decorations, true)
  174. }
  175. class ChangeDeletedWidget extends WidgetType {
  176. constructor(public change: Change<DeleteOperation>) {
  177. super()
  178. }
  179. toDOM() {
  180. const widget = document.createElement('span')
  181. widget.classList.add('ol-cm-change')
  182. widget.classList.add('ol-cm-change-d')
  183. return widget
  184. }
  185. eq() {
  186. return true
  187. }
  188. }
  189. class ChangeCalloutWidget extends WidgetType {
  190. constructor(public change: Change, public opType: string) {
  191. super()
  192. }
  193. toDOM() {
  194. const widget = document.createElement('span')
  195. widget.className = 'ol-cm-change-callout'
  196. widget.classList.add(`ol-cm-change-callout-${this.opType}`)
  197. const inner = document.createElement('span')
  198. inner.classList.add('ol-cm-change-callout-inner')
  199. widget.appendChild(inner)
  200. return widget
  201. }
  202. eq(widget: ChangeCalloutWidget) {
  203. return widget.opType === this.opType
  204. }
  205. updateDOM(element: HTMLElement) {
  206. element.className = 'ol-cm-change-callout'
  207. element.classList.add(`ol-cm-change-callout-${this.opType}`)
  208. return true
  209. }
  210. }
  211. // const isInsertOperation = (op: Operation): op is InsertOperation => 'i' in op
  212. const isChangeOperation = (op: Operation): op is ChangeOperation =>
  213. 'c' in op && 't' in op
  214. const isCommentOperation = (op: Operation): op is CommentOperation =>
  215. 'c' in op && !('t' in op)
  216. const isDeleteOperation = (op: Operation): op is DeleteOperation => 'd' in op
  217. const createChangeRange = (change: Change, currentDoc: CurrentDoc) => {
  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. opType,
  226. id,
  227. metadata,
  228. })
  229. const calloutWidget = Decoration.widget({
  230. widget: new ChangeCalloutWidget(change, opType),
  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. })